]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/STEER/AliGRPPreprocessor.cxx
New event header version.
[u/mrichter/AliRoot.git] / STEER / STEER / AliGRPPreprocessor.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 //-------------------------------------------------------------------------
19 //                          Class AliGRPPreprocessor
20 //                  Global Run Parameters (GRP) preprocessor
21 //    Origin: Panos Christakoglou, UOA-CERN, Panos.Christakoglou@cern.ch
22 //    Modified: Ernesto.Lopez.Torres@cern.ch  CEADEN-CERN
23 //    Modified: Chiara.Zampolli@cern.ch  CERN
24 //-------------------------------------------------------------------------
25
26 #include <TChain.h>
27 #include <TList.h>
28 #include <TMap.h>
29 #include <TObjString.h>
30 #include <TObjArray.h>
31 #include <TGraph.h>
32 #include <TString.h>
33 #include <TFile.h>
34
35 #include <float.h>
36
37 #include "AliGRPPreprocessor.h"
38 #include "AliGRPObject.h"
39 #include "AliDCSSensor.h"
40 #include "AliSplineFit.h"
41 #include "AliDCSSensorArray.h"
42 #include "AliRawEventHeaderVersions.h"
43
44 #include "AliTriggerConfiguration.h"
45 #include "AliTriggerRunScalers.h"
46 #include "AliTriggerInput.h"
47
48 #include "AliCDBMetaData.h"
49 #include "AliESDVertex.h"
50 #include "AliLHCReader.h"
51 #include "AliLHCData.h"
52 #include "AliDCSArray.h"
53 #include "AliDAQ.h"
54 #include "AliLTUConfig.h"
55
56 class AliLog;
57 class AliDCSValue;
58 class AliShuttleInterface;
59
60 // needed for ReceivePromptRecoParameters
61
62 #include <TSQLServer.h>
63 #include <TSQLResult.h>
64 #include <TSQLRow.h>
65 #include <AliCDBManager.h>
66 #include <AliCDBMetaData.h>
67 #include <AliCDBId.h>
68 #include <AliTriggerConfiguration.h>
69 #include "AliCTPTimeParams.h"
70 #include "AliLHCClockPhase.h"
71
72 const Double_t kFitFraction = -1.;                 // Fraction of DCS sensor fits required
73
74 ClassImp(AliGRPPreprocessor)
75
76 //_______________________________________________________________
77
78   const Int_t AliGRPPreprocessor::fgknDAQLbPar = 6; // num parameters in the logbook used to fill the GRP object
79   const Int_t AliGRPPreprocessor::fgknDCSDP = 48;   // number of dcs dps
80   const Int_t AliGRPPreprocessor::fgknDCSDPHallProbes = 40;   // number of dcs dps
81   const Int_t AliGRPPreprocessor::fgknLHCDP = 9;   // number of dcs dps from LHC data
82   const Int_t AliGRPPreprocessor::fgkDCSDPHallTopShift = 4;   // shift from the top to get tp the Hall Probes names in the list of DCS DPs
83   const Int_t AliGRPPreprocessor::fgkDCSDPNonWorking = 5; // number of non working DCS DPs
84   const char* AliGRPPreprocessor::fgkDCSDataPoints[AliGRPPreprocessor::fgknDCSDP] = {
85                    "L3Polarity",
86                    "DipolePolarity",
87                    "L3Current",
88                    "DipoleCurrent",
89                    "L3_BSF17_H1",
90                    "L3_BSF17_H2",
91                    "L3_BSF17_H3",
92                    "L3_BSF17_Temperature",
93                    "L3_BSF4_H1",
94                    "L3_BSF4_H2",
95                    "L3_BSF4_H3",
96                    "L3_BSF4_Temperature",
97                    "L3_BKF17_H1",
98                    "L3_BKF17_H2",
99                    "L3_BKF17_H3",
100                    "L3_BKF17_Temperature",
101                    "L3_BKF4_H1",
102                    "L3_BKF4_H2",
103                    "L3_BKF4_H3",
104                    "L3_BKF4_Temperature",
105                    "L3_BSF13_H1",
106                    "L3_BSF13_H2",
107                    "L3_BSF13_H3",
108                    "L3_BSF13_Temperature",
109                    "L3_BSF8_H1",
110                    "L3_BSF8_H2",
111                    "L3_BSF8_H3",
112                    "L3_BSF8_Temperature",
113                    "L3_BKF13_H1",
114                    "L3_BKF13_H2",
115                    "L3_BKF13_H3",
116                    "L3_BKF13_Temperature",
117                    "L3_BKF8_H1",
118                    "L3_BKF8_H2",
119                    "L3_BKF8_H3",
120                    "L3_BKF8_Temperature",
121                    "Dipole_Inside_H1",
122                    "Dipole_Inside_H2",
123                    "Dipole_Inside_H3",
124                    "Dipole_Inside_Temperature",
125                    "Dipole_Outside_H1",
126                    "Dipole_Outside_H2",
127                    "Dipole_Outside_H3",
128                    "Dipole_Outside_Temperature",
129                    "CavernTemperature",
130                    "CavernAtmosPressure",
131                    "SurfaceAtmosPressure",
132                    "CavernAtmosPressure2"
133                  };
134
135   const char* AliGRPPreprocessor::fgkDCSDataPointsHallProbes[AliGRPPreprocessor::fgknDCSDPHallProbes] = {
136                    "L3_BSF17_H1",
137                    "L3_BSF17_H2",
138                    "L3_BSF17_H3",
139                    "L3_BSF17_Temperature",
140                    "L3_BSF4_H1",
141                    "L3_BSF4_H2",
142                    "L3_BSF4_H3",
143                    "L3_BSF4_Temperature",
144                    "L3_BKF17_H1",
145                    "L3_BKF17_H2",
146                    "L3_BKF17_H3",
147                    "L3_BKF17_Temperature",
148                    "L3_BKF4_H1",
149                    "L3_BKF4_H2",
150                    "L3_BKF4_H3",
151                    "L3_BKF4_Temperature",
152                    "L3_BSF13_H1",
153                    "L3_BSF13_H2",
154                    "L3_BSF13_H3",
155                    "L3_BSF13_Temperature",
156                    "L3_BSF8_H1",
157                    "L3_BSF8_H2",
158                    "L3_BSF8_H3",
159                    "L3_BSF8_Temperature",
160                    "L3_BKF13_H1",
161                    "L3_BKF13_H2",
162                    "L3_BKF13_H3",
163                    "L3_BKF13_Temperature",
164                    "L3_BKF8_H1",
165                    "L3_BKF8_H2",
166                    "L3_BKF8_H3",
167                    "L3_BKF8_Temperature",
168                    "Dipole_Inside_H1",
169                    "Dipole_Inside_H2",
170                    "Dipole_Inside_H3",
171                    "Dipole_Inside_Temperature",
172                    "Dipole_Outside_H1",
173                    "Dipole_Outside_H2",
174                    "Dipole_Outside_H3",
175                    "Dipole_Outside_Temperature"
176                  };
177                  
178   const Short_t kSensors = 45; // start index position of sensor in DCS DPs
179   const Short_t kNumSensors = 3; // Number of sensors in DCS DPs (CavernAtmosPressure, SurfaceAtmosPressure, CavernAtmosPressure2)
180
181
182   const char* AliGRPPreprocessor::fgkLHCDataPoints[AliGRPPreprocessor::fgknLHCDP] = {
183           "LHC_Beam_Energy",
184           "LHC_MachineMode",
185           "LHC_BeamMode",
186           "LHC_Beams_Particle_Type",
187           "BPTX_Phase_Shift_B1",
188           "BPTX_Phase_Shift_B2",
189           "LHC_Particle_Type_B1",
190           "LHC_Particle_Type_B2",
191           "LHC_Data_Quality_Flag"
192   };
193
194   const char* kppError[] = {
195                    "",
196                    "(DAQ logbook ERROR)",
197                    "(DAQ FXS ERROR)",
198                    "(Trigger Scalers not found in DCS FXS - ERROR)",
199                    "(DCS data points ERROR)",
200                    "(Trigger Configuration ERROR)",
201                    "(DAQ logbook ERROR determining partition of the run)",
202                    "(CTP timing ERROR)",
203                    "(SPD Mean Vertex ERROR)",
204                    "(DCS FXS Error for LHC Data)",
205                    "(LHC Data Error)",
206                    "(LHC Clock Phase Error (from LHC Data))",
207                    "(LTU Configuration Error)"
208   };
209
210 //_______________________________________________________________
211
212 AliGRPPreprocessor::AliGRPPreprocessor(AliShuttleInterface* shuttle):
213         AliPreprocessor("GRP",shuttle),  fPressure(0), fmaxFloat(0), fminFloat(0),fmaxDouble(0), fminDouble(0), fmaxInt(0), fminInt(0), fmaxUInt(0), fminUInt(0),fdaqStartEndTimeOk(kTRUE),ffailedDPs(new TObjArray(fgknDCSDP))
214 {
215         // constructor - shuttle must be instantiated!
216
217         AddRunType("COSMIC");
218         AddRunType("LASER");
219         AddRunType("PHYSICS");
220         AddRunType("CALIBRATION_BC");
221         AddRunType("CALIBRATION_CENTRAL");
222         AddRunType("CALIBRATION_EMD");
223         AddRunType("CALIBRATION_MB");
224         AddRunType("CALIBRATION_SEMICENTRAL");
225         AddRunType("CALIBRATION");
226         AddRunType("PEDESTAL");
227         AddRunType("STANDALONE");
228         AddRunType("GAIN");
229         AddRunType("NOISE");
230         AddRunType("PULSER");
231         AddRunType("STANDALONE_PULSER");
232         AddRunType("STANDALONE_BC");
233
234         fmaxFloat = FLT_MAX;
235         fminFloat = -FLT_MAX;
236         fmaxDouble = DBL_MAX;
237         fminDouble = -DBL_MAX;
238         fmaxInt = kMaxInt;
239         fminInt = kMinInt;
240         fmaxUInt = kMaxUInt;
241         fminUInt = 0;
242
243         AliInfo(Form("Max allowed float = %6.5e",fmaxFloat));
244         AliInfo(Form("Min allowed float = %6.5e",fminFloat));
245         AliInfo(Form("Max allowed double = %6.5e",fmaxDouble));
246         AliInfo(Form("Min allowed double = %6.5e",fminDouble));
247         AliInfo(Form("Max allowed integer = %d",fmaxInt));
248         AliInfo(Form("Min allowed integer = %d",fminInt));
249         AliInfo(Form("Max allowed unsigned integer = %u",(Int_t)fmaxUInt));
250         AliInfo(Form("Min allowed unsigned integer = %u",(Int_t)fminUInt));
251
252         ffailedDPs->SetOwner(kTRUE);
253 }
254
255 //_______________________________________________________________
256
257 AliGRPPreprocessor::~AliGRPPreprocessor()
258 {
259         //destructor
260         
261         delete fPressure;
262         delete ffailedDPs;
263
264 }
265
266 //_______________________________________________________________
267
268 void AliGRPPreprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)
269 {
270         // Initialize preprocessor
271
272         AliPreprocessor::Initialize(run, startTime, endTime);
273         
274         AliInfo("Initialization of the GRP preprocessor.");
275         AliInfo(Form("Start Time DCS = %d",GetStartTimeDCSQuery()));
276         AliInfo(Form("End Time DCS = %d",GetEndTimeDCSQuery()));
277         TClonesArray * array = new TClonesArray("AliDCSSensor",kNumSensors); 
278         for(Int_t j = 0; j < kNumSensors; j++) {
279                 AliDCSSensor * sens = new ((*array)[j])AliDCSSensor;
280                 sens->SetStringID(fgkDCSDataPoints[j+kSensors]);
281         }
282         AliInfo(Form("Pressure Entries: %d",array->GetEntries()));
283         
284         fPressure = new AliDCSSensorArray(GetStartTimeDCSQuery(), GetEndTimeDCSQuery(), array);
285
286         ffailedDPs->Clear(); // cleaning ffailedDPs for current run
287         for (Int_t iDP=0; iDP < fgknDCSDP; iDP++){
288                 TObjString* dp = new TObjString(fgkDCSDataPoints[iDP]);
289                 ffailedDPs->AddAt(dp,iDP);
290         }
291
292 }
293
294 //_______________________________________________________________
295
296 UInt_t AliGRPPreprocessor::Process(TMap* valueMap)
297 {
298         // process data retrieved by the Shuttle
299         
300         // retrieving "partition" and "detector" fields from DAQ logbook to 
301         // determine the partition in which the run was taken
302         // the partition is used to decide how to react in case of errors for CTP
303
304         TString partition = (TString)GetRunParameter("partition");  
305         TString detector = (TString)GetRunParameter("detector");   
306
307         AliGRPObject *grpobj = new AliGRPObject();  // object to store data
308         grpobj->SetBeamEnergyIsSqrtSHalfGeV(); // new format
309
310         //=================//
311         // DAQ logbook     //
312         //=================//
313
314         Log("*************** Processing DAQ logbook");
315
316         UInt_t error = 0;
317         
318         Int_t iDaqLB = ProcessDaqLB(grpobj);
319         TString runType = (TString)GetRunType();
320         TString beamType = (TString)GetRunParameter("beamType");
321         if(iDaqLB == fgknDAQLbPar) {
322                 Log(Form("DAQ Logbook, successful! Retrieved %d/%d entries",iDaqLB,fgknDAQLbPar));
323         } else {
324                 Log(Form("DAQ Logbook, could not get all expected entries!!! Retrieved only %d/%d entries",iDaqLB,fgknDAQLbPar));
325                 error |= 1;
326         }
327
328         //=================//
329         // DAQ FXS         //
330         //=================//
331
332         Log("*************** Processing DAQ FXS");
333
334         UInt_t iDaqFxs = ProcessDaqFxs();
335         if( iDaqFxs == 0 ) {
336                 Log(Form("DAQ FXS, successful!"));
337         } else {
338                 Log(Form("DAQ FXS, could not store run raw tag file!!!"));
339                 error |= 2;
340         }
341         
342         //=================//
343         // DCS FXS         //
344         //=================//
345
346         Log("*************** Processing DCS FXS");
347
348         UInt_t iDcsFxs = ProcessDcsFxs(partition, detector);
349         if( iDcsFxs == 0 ) {
350                 Log(Form("DCS FXS, successful!"));
351         } else  if (iDcsFxs ==1) {
352                 Log(Form("DCS FXS, Could not store CTP scalers!!!"));
353                 error |= 4;
354         } else{
355                 Log(Form("Incorrect field in DAQ logbook for partition = %s and detector = %s, going into error without CTP scalers...",partition.Data(),detector.Data()));
356                 error |= 32;
357         }
358         
359         //=================//
360         // DCS data points //
361         //=================//
362
363         Log("*************** Processing DCS DPs");
364
365         Log(Form("Starting DCS Query at %d and finishing at %d",GetStartTimeDCSQuery(),GetEndTimeDCSQuery()));
366         Int_t entries = ProcessDcsDPs( valueMap, grpobj );
367         Log(Form("entries found = %d (should be %d)",entries, fgknDCSDP-fgkDCSDPNonWorking));
368         if (fdaqStartEndTimeOk){
369                 if( entries < fgknDCSDP - fgkDCSDPNonWorking ) { // L3_BSF4_H3, L3_BSF17_H1, L3_BSF17_H2, L3_BSF17_H3, L3_BSF17_Temperature are not working yet...  
370                         Log(Form("Possible problem with the DCS data points!!! Only %d/%d entries found - Please read further for more details",entries,fgknDCSDP-fgkDCSDPNonWorking));
371                         Log(Form("The DPs giving problems were:"));
372                         for (Int_t iDP = 0; iDP < fgknDCSDP; iDP++){
373                                 TObjString *dpString = (TObjString*)ffailedDPs->At(iDP);
374                                 if (dpString){
375                                         TString name = dpString->String();
376                                         if (name != "L3_BSF4_H3" && name != "L3_BSF17_H1" && name != "L3_BSF17_H2" && name != "L3_BSF17_H3" && name != "L3_BSF17_Temperature" ){
377                                                 Log(Form("******** %s ******** not present, but foreseen --> causing an ERROR",name.Data()));
378                                         }
379                                         else {
380                                                 Log(Form(" %s is not present, but was not generating any error since it is not ready in DCS - check the other DPs in this list!",name.Data()));
381                                         }
382                                 }
383                         }
384                         error |= 8;
385                 }
386                 else  Log(Form("DCS data points, successful!"));
387         }
388         else Log(Form("Statistical values for DCS DPs could not be computed due to missing DAQ_time_start and DAQ_time_end fields in DAQ logbook")); 
389         
390         //=======================//
391         // Trigger Configuration //
392         //=======================//
393
394         Log("*************** Processing Trigger Configuration");
395
396         const char * triggerConf = GetTriggerConfiguration();
397
398         if (partition.IsNull() && !detector.IsNull()){ // standalone partition
399                 Log("STANDALONE partition for current run, using Trigger Configuration dummy value");
400                 AliCDBEntry *cdbEntry = GetFromOCDB("CTP","DummyConfig");
401                 if (!cdbEntry) {
402                         Log(Form("No dummy CTP configuration entry found, going into error..."));
403                         error |= 16;
404                 }
405                 else{
406                         AliTriggerConfiguration *runcfg = (AliTriggerConfiguration*)cdbEntry->GetObject();
407                         if (!runcfg){
408                                 Log(Form("dummy CTP config not found in OCDB entry, going into error..."));
409                                 error |= 16;
410                         }
411                         else {
412                                 TString titleCTPcfg = Form("CTP cfg for run %i from Dummy entry in OCDB",fRun);
413                                 runcfg->SetTitle(titleCTPcfg);
414                                 AliCDBMetaData metaData;
415                                 metaData.SetResponsible("Roman Lietava");
416                                 metaData.SetComment("CTP run configuration from dummy entry in OCDB");
417                                 if (!Store("CTP","Config", runcfg, &metaData, 0, 0)) {
418                                         Log("Unable to store the dummy CTP run configuration object to OCDB!");
419                                         error |= 16;
420                                 }
421                         }
422                 }
423         }
424
425         else if (!partition.IsNull() && detector.IsNull()){ // global partition
426                 Log("GLOBAL partition for current run, using Trigger Configuration from DAQ Logbook");
427                 if (triggerConf!= NULL) {
428                         Log("Found trigger configuration in DAQ logbook");
429                         AliTriggerConfiguration *runcfg = AliTriggerConfiguration::LoadConfigurationFromString(triggerConf);      
430                         if (!runcfg) {
431                                 Log("Bad CTP run configuration file from DAQ logbook! The corresponding CDB entry will not be filled!");
432                                 error |= 16;
433                         }
434                         else {
435                                 TString titleCTPcfg = Form("CTP cfg for run %i from DAQ",fRun);
436                                 runcfg->SetTitle(titleCTPcfg);
437                                 AliCDBMetaData metaData;
438                                 metaData.SetBeamPeriod(0);
439                                 metaData.SetResponsible("Roman Lietava");
440                                 metaData.SetComment("CTP run configuration from DAQ logbook");
441                                 if (!Store("CTP","Config", runcfg, &metaData, 0, 0)) {
442                                         Log("Unable to store the CTP run configuration object to OCDB!");
443                                         error |= 16;
444                                 }
445                         }
446                 }
447
448                 else {
449                         Log("Trigger configuration NULL in DAQ logbook");
450                         error |= 16;
451                 }
452         }
453
454         else {
455                 Log(Form("Incorrect field in DAQ logbook for partition = %s and detector = %s, going into error without trigger configuration...",partition.Data(),detector.Data()));
456                 error |= 32;
457         }
458
459         //===========================//
460         // Trigger Timing Parameters //
461         //===========================//
462
463         Log("*************** Processing Trigger Time Params");
464         
465         const char * triggerCTPtiming = GetCTPTimeParams();
466
467         if (partition.IsNull() && !detector.IsNull()){ // standalone partition
468                 Log("STANDALONE partition for current run, using CTP timing params dummy value");
469                 AliCDBEntry *cdbEntry = GetFromOCDB("CTP","DummyCTPtime");
470                 if (!cdbEntry) {
471                         Log(Form("No dummy CTP timing parameters entry found, going into error..."));
472                         error |= 64;
473                 }
474                 else{
475                         AliCTPTimeParams *runCTPtiming = (AliCTPTimeParams*)cdbEntry->GetObject();
476                         if (!runCTPtiming){
477                                 Log(Form("dummy CTP timing parameters not found in OCDB entry, going into error..."));
478                                 error |= 64;
479                         }
480                         else {
481                                 TString titleCTPtiming = Form("CTP timing params for run %i from Dummy entry in OCDB",fRun);
482                                 runCTPtiming->SetTitle(titleCTPtiming);
483                                 AliCDBMetaData metadata;
484                                 metadata.SetResponsible("Roman Lietava");
485                                 metadata.SetComment("CTP run timing parameters from dummy entry in OCDB");
486                                 if (!Store("CTP","CTPtiming", runCTPtiming, &metadata, 0, 0)) {
487                                         Log("Unable to store the dummy CTP timing params object to OCDB!");
488                                         error |= 64;
489                                 }
490                         }
491                 }
492         }
493
494         else if (!partition.IsNull() && detector.IsNull()){ // global partition
495                 Log("GLOBAL partition for current run, using Trigger Timing Parameters from DAQ Logbook");
496                 if (triggerCTPtiming!= NULL) {
497                         Log("Found trigger timing params in DAQ logbook");
498                         AliDebug(2,Form("%s",triggerCTPtiming));
499                         AliCTPTimeParams *runCTPtiming = AliCTPTimeParams::LoadCTPTimeParamsFromString(triggerCTPtiming);         
500                         if (!runCTPtiming) {
501                                 Log("Bad CTP trigger timing params file from DAQ logbook! The corresponding CDB entry will not be filled!");
502                                 error |= 64;
503                         }
504                         else {
505                                 TString titleCTPtiming = Form("CTP timing params for run %i from DAQ",fRun);
506                                 runCTPtiming->SetTitle(titleCTPtiming);
507                                 AliCDBMetaData metadata;
508                                 metadata.SetBeamPeriod(0);
509                                 metadata.SetResponsible("Roman Lietava");
510                                 metadata.SetComment("CTP timing params from DAQ logbook");
511                                 if (!Store("CTP","CTPtiming", runCTPtiming, &metadata, 0, 0)) {
512                                         Log("Unable to store the CTP timing params object to OCDB!");
513                                         error |= 64;
514                                 }
515                         }
516                 }
517
518                 else {
519                         Log("Trigger timing params NULL in DAQ logbook");
520                         error |= 64;
521                 }
522         }
523
524         else {
525                 Log(Form("Incorrect field in DAQ logbook for partition = %s and detector = %s, going into error without trigger timing parameters...",partition.Data(),detector.Data()));
526                 error |= 32;
527         }
528
529         //===========================//
530         // LTU Configuration         //
531         //===========================//
532
533         Log("*************** Processing LTU Configuration");
534         
535         if (partition.IsNull() && !detector.IsNull()){ // standalone partition
536                 Log("STANDALONE partition for current run, using LTU configuration dummy value");
537                 AliCDBEntry *cdbEntry = GetFromOCDB("CTP","DummyLTUConfig");
538                 if (!cdbEntry) {
539                         Log(Form("No dummy LTU Config entry found, going into error..."));
540                         error |= 2048;
541                 }
542                 else{
543                         TObjArray *ltuConfig = (TObjArray*)cdbEntry->GetObject();
544                         if (!ltuConfig){
545                                 Log(Form("dummy LTU Config not found in OCDB entry, going into error..."));
546                                 error |= 2048;
547                         }
548                         else {
549                                 AliCDBMetaData metadata;
550                                 metadata.SetResponsible("Roman Lietava");
551                                 metadata.SetComment("LTU Config from dummy entry in OCDB");
552                                 if (!Store("CTP","LTUConfig", ltuConfig, &metadata, 0, 0)) {
553                                         Log("Unable to store the dummy LTU Config object to OCDB!");
554                                         error |= 2048;
555                                 }
556                         }
557                 }
558         }
559
560         else if (!partition.IsNull() && detector.IsNull()){ // global partition
561         
562                 Log("GLOBAL partition for current run, getting LTU Config from DAQ Logbook (logbook_detectors table)");
563                 UInt_t  detectorMask = (UInt_t)(((TString)GetRunParameter("detectorMask")).Atoi());
564                 Printf ("detectormask = %d",detectorMask);
565                 TObjArray * ltuarray = new TObjArray();
566                 ltuarray->SetOwner(1);
567                 Bool_t isLTUok = kTRUE;
568                 for(Int_t i = 0; i<AliDAQ::kNDetectors-2; i++){
569                         if ((detectorMask >> i) & 0x1) {
570                                 TString det = AliDAQ::OfflineModuleName(i);
571                                 TString detCTPName = AliTriggerInput::fgkCTPDetectorName[i];
572                                 if (detCTPName == "CTP") {
573                                         detCTPName="TRG"; // converting according to what is found in DAQ logbook_detectors                                     
574                                         Printf("Processing CTP (CTP Detector name %s) --> SKIPPING, CTP does not have any LTU!!!!!!",detCTPName.Data());
575                                         continue;
576                                 }                               
577                                 Printf("Processing detector %s (CTP Detector name %s)",det.Data(),detCTPName.Data());
578                                 TString* ltu = GetLTUConfig(detCTPName.Data());
579                                 if (!ltu){
580                                         Log(Form("No LTU Configuration from DAQ logbook for detector %s (BUT it was expected)! The corresponding CDB entry will not be filled!",detCTPName.Data()));
581                                         error |= 2048;
582                                         isLTUok = kFALSE;
583                                         break;
584                                 }
585                                 else{
586                                         Float_t ltuFineDelay1 = ltu[0].Atof();
587                                         Float_t ltuFineDelay2 = ltu[1].Atof();
588                                         Float_t ltuBCDelayAdd = ltu[2].Atof();
589                                         const char* name = AliDAQ::DetectorName(i);
590                                         AliLTUConfig* ltuConfig = new AliLTUConfig((UChar_t)AliDAQ::DetectorID(name),ltuFineDelay1,ltuFineDelay2,ltuBCDelayAdd);
591                                         ltuarray->AddAtAndExpand(ltuConfig,i);
592                                 }                               
593                         }
594                 }
595                 if (isLTUok){
596                         AliCDBMetaData metadata;
597                         metadata.SetBeamPeriod(0);
598                         metadata.SetResponsible("Roman Lietava");
599                         metadata.SetComment("LTU Configuration for current run");
600                         if (!Store("CTP","LTUConfig", ltuarray, &metadata, 0, 0)) {
601                                 Log("Unable to store the LTU Config object to OCDB!");
602                                 error |= 2048;
603                         }               
604                 }
605                 delete ltuarray;
606         }
607
608         else {
609                 Log(Form("Incorrect field in DAQ logbook for partition = %s and detector = %s, going into error without trigger timing parameters...",partition.Data(),detector.Data()));
610                 error |= 32;
611         }
612
613
614         //=================//
615         // LHC Data        //
616         //=================//
617
618         if (runType == "PHYSICS"){  // processing the LHC file only in PHYSICS runs
619                 Log("*************** Processing LHC Data");
620
621                 UInt_t iLHCData = ProcessLHCData(grpobj);
622                 
623                 if( iLHCData == 0 ) {
624                         Log(Form("LHC Data from DCS FXS, successful!"));
625                 } else  if (iLHCData == 1) {
626                         Log(Form("LHC Data, problems with DCS FXS!"));
627                         error |= 256;
628                 } else  if (iLHCData == 2) {
629                         Log(Form("LHC Data, problems with DAQ_time_start/DAQ_time_end!"));
630                         error |= 512;
631                 } else if (iLHCData ==3){
632                         Log(Form("Problems in storing LHC Phase - going into Error"));
633                         error |= 1024;
634                 } else if (iLHCData ==4){
635                         Log(Form("Problems with LHC Phase - going into Error"));
636                         error |= 1024;
637                 } else{
638                         Log(Form("LHC Data problems"));
639                         error |= 512;
640                 }
641         
642         }
643
644         //==================//
645         // SPD Mean Vertex  //
646         //==================//
647
648         Log("*************** Processing SPD Mean Vertex");
649
650         if (runType == "PHYSICS"){
651                 UInt_t iSPDMeanVertex = ProcessSPDMeanVertex();
652                 if( iSPDMeanVertex == 1 ) {
653                         Log(Form("SPD Mean Vertex, successful!"));
654                 } else {
655                         Log(Form("SPD Mean Vertex failed!!!"));
656                         error |= 128; 
657                 }
658         }
659         else {
660                 Log("SPD Mean Vertex not processed since runType != PHYSICS");
661         }
662
663         // storing AliGRPObject in OCDB
664
665         AliCDBMetaData md;
666         md.SetResponsible("Chiara Zampolli");
667         md.SetComment("Output parameters from the GRP preprocessor.");
668         
669         Bool_t result = kTRUE;
670         result = Store("GRP", "Data", grpobj, &md); 
671         delete grpobj;
672
673         if (result && !error ) {
674                 Log("GRP Preprocessor Success");
675                 return 0;
676         } else {
677                 Log( Form("GRP Preprocessor FAILS!!! %s%s%s%s%s%s%s%s%s%s%s%s",
678                           kppError[(error&1)?1:0],
679                           kppError[(error&2)?2:0],
680                           kppError[(error&4)?3:0],
681                           kppError[(error&8)?4:0],
682                           kppError[(error&16)?5:0],
683                           kppError[(error&32)?6:0],
684                           kppError[(error&64)?7:0],
685                           kppError[(error&128)?8:0],
686                           kppError[(error&256)?9:0],
687                           kppError[(error&512)?10:0],
688                           kppError[(error&1024)?11:0],
689                           kppError[(error&2048)?12:0]
690                           ));
691                 return error;
692         }
693
694
695 }
696
697 //_______________________________________________________________
698
699 UInt_t AliGRPPreprocessor::ProcessLHCData(AliGRPObject *grpobj)
700 {
701         //
702         //Getting the LHC Data from DCS FXS
703         //
704
705         TString timeStartString = (TString)GetRunParameter("DAQ_time_start");
706         TString timeEndString = (TString)GetRunParameter("DAQ_time_end");
707         if (timeStartString.IsNull() || timeEndString.IsNull()){
708                 if (timeStartString.IsNull()){ 
709                         AliError("DAQ_time_start not set in logbook! Setting statistical values for current DP to invalid");
710                 }
711                 else if (timeEndString.IsNull()){
712                         AliError("DAQ_time_end not set in logbook! Setting statistical values for current DP to invalid");
713                 }
714                 return 2;
715         }  
716
717         Double_t timeStart = timeStartString.Atof();
718         Double_t timeEnd = timeEndString.Atof();
719
720         TString fileName = GetFile(kDCS, "LHCData","");
721         if (fileName.Length()>0){
722                 AliInfo("Got The LHC Data file");
723                 AliLHCReader lhcReader;
724
725                 // Processing data to be put in AliGRPObject
726
727                 // Energy
728                 Log("*************Energy ");
729                 TObjArray* energyArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[0]);
730                 if (energyArray){                       
731                         Float_t energy = ProcessEnergy(energyArray,timeStart);
732                         if (energy != -1.) {
733                                 grpobj->SetBeamEnergy(energy);
734                                 grpobj->SetBeamEnergyIsSqrtSHalfGeV(kTRUE);
735                         }
736                         delete energyArray;
737                 }
738                 else {
739                         AliError("Energy not found in LHC Data file!!!");
740                 }       
741
742                 Double_t timeBeamModeEnd = timeEnd;        // max validity for Beam Mode 
743                 Double_t timeMachineModeEnd = timeEnd;     // max validity for Machine Mode
744                 Double_t timeBeamEnd = timeEnd;            // max validity for Beam Type
745                 Double_t timeBeamTypeEnd[2] = {timeEnd, timeEnd}; // max validity for Beam Type1,2
746                 Double_t timeBeamModeStart = -1;    // min validity for Beam Mode
747                 Double_t timeMachineModeStart = -1; // min validity for Machine Mode
748                 Double_t timeBeamStart = -1;        // min validity for Beam Type
749                 Double_t timeBeamTypeStart[2] = {-1,-1};        // min validity for Beam Type1,2
750                 Int_t indexBeamMode = -1;                  // index of measurement used to set Beam Mode
751                 Int_t indexMachineMode = -1;               // index of measurement used to set Machine Mode
752                 Int_t indexBeam = -1;                      // index of measurement used to set Beam Type
753                 Int_t indexBeamType[2] = {-1, -1};                      // index of measurement used to set Beam Type1,2
754                 Bool_t foundBeamModeStart = kFALSE;        // flag to be set in case an entry for the Beam Mode is found before (or at) SOR
755                 Bool_t foundMachineModeStart = kFALSE;     // flag to be set in case an entry for the Machine Mode is found before (or at) SOR
756                 Bool_t foundBeamStart = kFALSE;            // flag to be set in case an entry for the Beam Type is found before (or at) SOR
757                 Bool_t foundBeamTypeStart[2] = {kFALSE, kFALSE};            // flag to be set in case an entry for the Beam Type1,2 is found before (or at) SOR
758                 Bool_t flagBeamMode = kFALSE;  //flag set true if a changed occurred in BeamMode
759                 Bool_t flagMachineMode = kFALSE;  //flag set true if a changed occurred in MachineMode
760                 Bool_t flagBeam = kFALSE;  //flag set true if a changed occurred in BeamType
761                 Bool_t flagBeamType[2] = {kFALSE, kFALSE};  //flag set true if a changed occurred in BeamType1,2
762                 
763                 Double_t arrayTimes[5]={2.E9, 2.E9, 2.E9, 2.E9, 2.E9}; // array to keep track of the times of the possible changes of the LHC DPs; each entry set to Wed May 18 2033, 03:33:20 GMT (ALICE should not be running anymore...)
764                                                                        // arrayTimes elements order correspond to the one used in the array of the strings fgkLHCDataPoints, i.e.:
765                                                                        // arrayTimes[0] --> MachineMode
766                                                                        // arrayTimes[1] --> BeamMode
767                                                                        // arrayTimes[2] --> BeamType (when written together)
768                                                                        // arrayTimes[3] --> BeamType1 (when written separate)
769                                                                        // arrayTimes[4] --> BeamType2 (when written separate)
770
771                 // BeamMode
772                 Log("*************BeamMode (LHCState) ");
773                 TObjArray* beamModeArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[2]);
774                 Int_t nBeamMode = -1;
775                 if (beamModeArray){     
776                         nBeamMode = beamModeArray->GetEntries();        
777                         if (nBeamMode==0){
778                                 AliInfo("Found zero entries for the Beam Mode, leaving it empty");
779                         }
780                         else{
781                                 for (Int_t iBeamMode = 0; iBeamMode<nBeamMode; iBeamMode++){
782                                         AliDCSArray* beamMode = (AliDCSArray*)beamModeArray->At(iBeamMode);
783                                         if (beamMode){
784                                                 if (beamMode->GetTimeStamp()<=timeStart && beamMode->GetTimeStamp()>=timeBeamModeStart){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
785                                                         timeBeamModeStart = beamMode->GetTimeStamp();
786                                                         indexBeamMode = iBeamMode;
787                                                         foundBeamModeStart = kTRUE;
788                                                 }
789                                                 else {
790                                                         break;
791
792                                                 }
793                                         }
794                                 }
795                                 if (!foundBeamModeStart){
796                                         AliInfo("No value for the Beam Mode found before start of run, the Beam Mode will remain empty");
797                                 }
798                                 else {
799                                         AliDCSArray* beamMode = (AliDCSArray*)beamModeArray->At(indexBeamMode);
800                                         TObjString* beamModeString = beamMode->GetStringArray(0);
801                                         AliInfo(Form("LHC State (corresponding to BeamMode) = %s (set at %f)",(beamModeString->String()).Data(),beamMode->GetTimeStamp()));
802                                         grpobj->SetLHCState(beamModeString->String());
803                                         if (indexBeamMode < nBeamMode-1){
804                                                 AliDCSArray* beamMode1 = (AliDCSArray*)beamModeArray->At(indexBeamMode+1);
805                                                 if (beamMode1){
806                                                         if (beamMode1->GetTimeStamp()<=timeStart){
807                                                                 AliError("you did not choose the correct value! there is still something before (or at) SOR, but later than this!");
808                                                         }
809                                                         else if (beamMode1->GetTimeStamp()>timeStart && beamMode1->GetTimeStamp()<=timeEnd){
810                                                                 timeBeamModeEnd = beamMode1->GetTimeStamp();
811                                                                 TObjString* beamModeString1 = beamMode1->GetStringArray(0);
812                                                                 TString bmString0 = beamModeString->String();
813                                                                 TString bmString1 = beamModeString1->String();
814                                                                 if (bmString0.CompareTo(bmString1.Data(),TString::kIgnoreCase) == -1){
815                                                                         AliWarning(Form("The beam mode changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",bmString0.Data(), bmString1.Data(), timeBeamModeEnd, bmString0.Data()));
816                                                                         flagBeamMode = kTRUE;
817                                                                         arrayTimes[1]=timeBeamModeEnd;
818
819                                                                 }
820                                                         }
821                                                 }
822                                                 else {
823                                                         AliInfo("Invalid pointer for the first entry for Beam Mode after the first valid one, not considering anything after what has already been found");
824                                                 }
825                                         }
826                                 }
827                         }
828                         delete beamModeArray;
829                 }
830                 else{
831                         AliError("Beam mode array not found in LHC Data file!!!");
832                 }
833                 
834                 // MachineMode
835                 Log("*************MachineMode ");
836                 TObjArray* machineModeArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[1]);
837                 Int_t nMachineMode = -1;
838                 if (machineModeArray){
839                         nMachineMode = machineModeArray->GetEntries();
840                         if (nMachineMode==0){
841                                 AliInfo("No Machine Mode found, leaving it empty");
842                         }
843                         else{
844                                 for (Int_t iMachineMode = 0; iMachineMode<nMachineMode; iMachineMode++){
845                                         AliDCSArray* machineMode = (AliDCSArray*)machineModeArray->At(iMachineMode);
846                                         if (machineMode){
847                                                 if (machineMode->GetTimeStamp()<=timeStart && machineMode->GetTimeStamp()>=timeMachineModeStart){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
848                                                         timeMachineModeStart = machineMode->GetTimeStamp();
849                                                         indexMachineMode = iMachineMode;
850                                                         foundMachineModeStart = kTRUE;
851                                                 }
852                                                 else{
853                                                         break;
854                                                 }
855                                         }
856                                 }
857                                 if (!foundMachineModeStart){
858                                         AliInfo("No value for the Machine Mode found before start of run, the Machine Mode will remain empty");
859                                 }
860                                 else {
861                                         AliDCSArray* machineMode = (AliDCSArray*)machineModeArray->At(indexMachineMode);
862                                         TObjString* machineModeString = machineMode->GetStringArray(0);
863                                         AliInfo(Form("MachineMode = %s (set at %f)",(machineModeString->String()).Data(),machineMode->GetTimeStamp()));
864                                         grpobj->SetMachineMode(machineModeString->String());
865                                         if (indexMachineMode < nMachineMode-1){
866                                                 AliDCSArray* machineMode1 = (AliDCSArray*)machineModeArray->At(indexMachineMode+1);
867                                                 if (machineMode1){
868                                                         if (machineMode1->GetTimeStamp()>timeStart && machineMode1->GetTimeStamp()<=timeEnd){
869                                                                 timeMachineModeEnd = machineMode1->GetTimeStamp();
870                                                                 TObjString* machineModeString1 = machineMode1->GetStringArray(0);
871                                                                 TString mmString0 = machineModeString->String();
872                                                                 TString mmString1 = machineModeString1->String();
873                                                                 if (mmString0.CompareTo(mmString1.Data(),TString::kIgnoreCase) == -1){
874                                                                         AliWarning(Form("The machine mode changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",mmString0.Data(),mmString1.Data(),timeMachineModeEnd,mmString0.Data()));
875                                                                         flagMachineMode = kTRUE;
876                                                                         arrayTimes[0]=timeMachineModeEnd;
877                                                                 }
878                                                         }
879                                                 }
880                                                 else {
881                                                         AliInfo("Invalid pointer for the first entry for Machine Mode after the first valid one, not considering anything after what has already been found");
882                                                 }
883                                         }
884                                 }
885                         }
886                         delete machineModeArray;
887                 }
888                 else{
889                         AliError("Machine mode array not found in LHC Data file!!!");
890                 }
891                 
892                 // BeamType1 and BeamType2 - both put in the same string
893                 Log("*************BeamType ");
894                 TObjArray* beamArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[3]);
895                 if (beamArray){                 
896                         Int_t nBeam = beamArray->GetEntries();
897                         if (nBeam==0){
898                                 AliInfo("No Beam Type found, leaving it empty");
899                         }
900                         else{
901                                 for (Int_t iBeam = 0; iBeam<nBeam; iBeam++){
902                                         AliDCSArray* beam = (AliDCSArray*)beamArray->At(iBeam);
903                                         if (beam){
904                                                 if (beam->GetTimeStamp()<=timeStart && beam->GetTimeStamp()>=timeBeamStart){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
905                                                         timeBeamStart = beam->GetTimeStamp();
906                                                         indexBeam = iBeam;
907                                                         foundBeamStart = kTRUE;
908                                                 }
909                                                 else{
910                                                         break;
911                                                 }
912                                         }
913                                 }
914                                 if (!foundBeamStart){
915                                         AliInfo("No value for the Beam Type found before start of run, the (common) Beam Type will remain empty");
916                                 }
917                                 else {
918                                         AliDCSArray* beam = (AliDCSArray*)beamArray->At(indexBeam);
919                                         TObjString* beamString = beam->GetStringArray(0);
920                                         TString beamType = beamString->String();
921                                         AliInfo(Form("Beam Type = %s",beamType.Data()));        
922                                         if (beamType.CompareTo("PROTON",TString::kIgnoreCase) == 0){
923                                                 AliInfo("Setting beam type to p-p");
924                                                 grpobj->SetBeamType("p-p");
925                                         }
926                                         else { // if there is no PROTON beam, we suppose it is Pb, and we put A-A
927                                                 AliInfo("Setting beam type to A-A");
928                                                 grpobj->SetBeamType("A-A");
929                                         }
930                                         /*
931                                           else if (beamType.CompareTo("LEAD82",TString::kIgnoreCase) == 0){
932                                                 AliInfo("Setting beam type to Pb-Pb");
933                                                 grpobj->SetBeamType("Pb-Pb");
934                                         }
935                                         else{
936                                                 AliError("Beam Type not known, leaving it empty");
937                                         }
938                                         */
939                                         if (indexBeam < nBeam-1){
940                                                 AliDCSArray* beam1 = (AliDCSArray*)beamArray->At(indexBeam+1);
941                                                 if (beam1){
942                                                         if (beam1->GetTimeStamp()>timeStart && beam1->GetTimeStamp()<=timeEnd){
943                                                                 timeBeamEnd = beam1->GetTimeStamp();
944                                                                 TObjString* beamString1 = beam1->GetStringArray(0);
945                                                                 TString beamType1 = beamString1->String();
946                                                                 if (beamType.CompareTo(beamType1.Data(),TString::kIgnoreCase) == -1){
947                                                                         AliWarning(Form("The Beam Type changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",beamType.Data(),(beamString1->String()).Data(),timeBeamEnd,beamType.Data()));
948                                                                         flagBeam = kTRUE;
949                                                                         arrayTimes[2] = timeBeamEnd;
950                                                                 }
951                                                         }
952                                                 }
953                                                 else {
954                                                         AliInfo("Invalid pointer for the first entry for Beam Type after the first valid one, not considering anything after what has already been found");
955                                                 }
956                                         }
957                                 }
958                         }
959                         delete beamArray;
960                 }
961                 else{
962                         AliError("Beam Type array not found in LHC Data file!!!");
963                 }               
964
965                 // BeamType1 and BeamType2 - in separete string
966                 Log("*************BeamType, 1 and 2 ");
967                 Int_t indexBeamTypeString = 6;  // index of the string with the alias of BeanType1 in the array fgkLHCDataPoints
968                 TString combinedBeamType = "-";  // combined beam tyope, built from beam type 1 and beam type 2
969                 for (Int_t ibeamType = 0; ibeamType<2; ibeamType++){
970                         beamArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[indexBeamTypeString+ibeamType]);
971                         if (beamArray){                 
972                                 Int_t nBeam = beamArray->GetEntries();
973                                 if (nBeam==0){
974                                         AliInfo(Form("No Beam Type %s found, leaving it empty",fgkLHCDataPoints[indexBeamTypeString+ibeamType]));
975                                 }
976                                 else{
977                                         for (Int_t iBeam = 0; iBeam<nBeam; iBeam++){
978                                                 AliDCSArray* beam = (AliDCSArray*)beamArray->At(iBeam);
979                                                 if (beam){
980                                                         if (beam->GetTimeStamp()<=timeStart && beam->GetTimeStamp()>=timeBeamTypeStart[ibeamType]){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
981                                                                 timeBeamTypeStart[ibeamType] = beam->GetTimeStamp();
982                                                                 indexBeamType[ibeamType] = iBeam;
983                                                                 foundBeamTypeStart[ibeamType] = kTRUE;
984                                                         }
985                                                         else{
986                                                                 break;
987                                                         }
988                                                 }
989                                         }
990                                         if (!foundBeamTypeStart[ibeamType]){
991                                                 AliInfo(Form("No value for the Beam Type %s found before start of run, the Beam Type %d will remain empty", fgkLHCDataPoints[indexBeamTypeString+ibeamType], ibeamType));
992                                         }
993                                         else {
994                                                 AliDCSArray* beam = (AliDCSArray*)beamArray->At(indexBeam);
995                                                 TObjString* beamString = beam->GetStringArray(0);
996                                                 TString beamType = beamString->String();
997                                                 AliInfo(Form("Beam Type (for %s) = %s", fgkLHCDataPoints[indexBeamTypeString+ibeamType], beamType.Data()));     
998                                                 if (beamType.CompareTo("PROTON",TString::kIgnoreCase) == 0){
999                                                         AliInfo(Form("Setting beam type %s to p", fgkLHCDataPoints[indexBeamTypeString+ibeamType]));
1000                                                         grpobj->SetSingleBeamType(ibeamType,"p");
1001                                                         if (ibeamType == 0) combinedBeamType.Prepend("p");
1002                                                         else combinedBeamType.Append("p");
1003                                                 }
1004                                                 else { // if there is no PROTON beam, we suppose it is Pb, and we put A-A
1005                                                         AliInfo("Setting beam type to A");
1006                                                         grpobj->SetSingleBeamType(ibeamType,"A");
1007                                                         if (ibeamType == 0) combinedBeamType.Prepend("A");
1008                                                         else combinedBeamType.Append("A");
1009                                                 }
1010                                                 /*
1011                                                   else if (beamType.CompareTo("LEAD82",TString::kIgnoreCase) == 0){
1012                                                   AliInfo("Setting beam type to Pb-Pb");
1013                                                   grpobj->SetSingleBeamType(ibeamType, "Pb-Pb");
1014                                                   }
1015                                                   else{
1016                                                   AliError("Beam Type not known, leaving it empty");
1017                                                   }
1018                                                 */
1019                                                 if (indexBeamType[ibeamType] < nBeam-1){
1020                                                         AliDCSArray* beam1 = (AliDCSArray*)beamArray->At(indexBeam+1);
1021                                                         if (beam1){
1022                                                                 if (beam1->GetTimeStamp()>timeStart && beam1->GetTimeStamp()<=timeEnd){
1023                                                                         timeBeamTypeEnd[ibeamType] = beam1->GetTimeStamp();
1024                                                                         TObjString* beamString1 = beam1->GetStringArray(0);
1025                                                                         TString beamType1 = beamString1->String();
1026                                                                         if (beamType.CompareTo(beamType1.Data(),TString::kIgnoreCase) == -1){
1027                                                                                 AliWarning(Form("The Beam Type for %s changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",fgkLHCDataPoints[indexBeamTypeString+ibeamType],beamType.Data(),(beamString1->String()).Data(),timeBeamEnd,beamType.Data()));
1028                                                                                 flagBeamType[ibeamType] = kTRUE;
1029                                                                                 arrayTimes[3+ibeamType] = timeBeamTypeEnd[ibeamType];
1030                                                                         }
1031                                                                 }
1032                                                         }
1033                                                         else {
1034                                                                 AliInfo(Form("Invalid pointer for the first entry for Beam Type %s after the first valid one, not considering anything after what has already been found",fgkLHCDataPoints[indexBeamTypeString+ibeamType]));
1035                                                         }
1036                                                 }
1037                                         }
1038                                 }
1039                                 delete beamArray;
1040                         }
1041                         else{
1042                                 AliError(Form("Beam Type %s array not found in LHC Data file!!!",fgkLHCDataPoints[indexBeamTypeString+ibeamType]));
1043                         }               
1044                 }
1045                 AliInfo(Form("Setting combined beam type to %s",combinedBeamType.Data()));
1046                 grpobj->SetBeamType(combinedBeamType);
1047                 
1048                 // Setting minTimeLHCValidity
1049                 if (flagBeamMode == kTRUE || flagMachineMode == kTRUE || flagBeam == kTRUE || flagBeamType[0] == kTRUE || flagBeamType[1] == kTRUE){ 
1050                         Double_t minTimeLHCValidity= TMath::MinElement(5,arrayTimes);
1051                         AliWarning(Form("Setting MaxTimeLHCValidity to %f",minTimeLHCValidity));
1052                         grpobj->SetMaxTimeLHCValidity(minTimeLHCValidity);
1053                 }
1054                 /* 
1055                    // Old way to determine the Maximum Time during which the LHC info is valid
1056                 if (timeBeamModeEnd!=0 || timeMachineModeEnd!=0 || timeBeamEnd !=0){
1057                         Double_t minTimeLHCValidity;
1058                         if (flagBeamMode == kFALSE && flagMachineMode == kFALSE && flagBeam == kTRUE){ // flagBeam only true --> it is the only one that changed
1059                                 minTimeLHCValidity = timeBeamEnd;
1060                         }
1061                         else if (flagBeamMode == kFALSE && flagMachineMode == kTRUE && flagBeam == kFALSE){ // flagMachineMode only true
1062                                 minTimeLHCValidity = timeMachineModeEnd;
1063                         }
1064                         else if (flagBeamMode == kTRUE && flagMachineMode == kFALSE && flagBeam == kFALSE){ // flagBeamMode only true
1065                                 minTimeLHCValidity = timeBeamModeEnd;
1066                         }
1067                         else if (flagBeamMode == kFALSE && flagMachineMode == kTRUE && flagBeam == kTRUE){ // flagBeam and flagMachineMode only true
1068                                 minTimeLHCValidity= TMath::Min(timeBeamEnd,timeMachineModeEnd);
1069                         }
1070                         else if (flagBeamMode == kTRUE && flagMachineMode == kFALSE && flagBeam == kTRUE){ // flagBeam and flagBeamMode only true
1071                                 minTimeLHCValidity= TMath::Min(timeBeamEnd,timeBeamModeEnd);
1072                         }
1073                         else if (flagBeamMode == kTRUE && flagMachineMode == kTRUE && flagBeam == kFALSE){ // flagMachineMode and flagBeamMode only true
1074                                 minTimeLHCValidity= TMath::Min(timeMachineModeEnd,timeBeamModeEnd);
1075                         }
1076                         else {
1077                                 Double_t arrayTimes[3] = {timeBeamModeEnd,timeMachineModeEnd,timeBeamEnd};// flagMachineMode and flagBeamMode and flagBeam 
1078                                 minTimeLHCValidity= TMath::MinElement(3,arrayTimes);
1079                         }
1080                         AliWarning(Form("Setting MaxTimeLHCValidity to %f",minTimeLHCValidity));
1081                         grpobj->SetMaxTimeLHCValidity(minTimeLHCValidity);
1082                 }
1083                 */
1084                 
1085                 // Data Quality Flag --> storing start and end values of periods within the run during which the value was found to be FALSE
1086                 Log("*************Data Quality Flag ");
1087                 TObjArray* dataQualityArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[8]);
1088                 Int_t nDataQuality = -1;
1089                 Double_t timeDataQualityStart = -1; // min validity for Data Quality Flag
1090                 Int_t indexDataQuality = -1;               // index of first measurement used to set Data Quality Flag
1091                 Bool_t foundDataQualityStart = kFALSE;     // flag to be set in case an entry for the Data Quality Flag is found before (or at) SOR
1092
1093                 if (dataQualityArray){
1094                         nDataQuality = dataQualityArray->GetEntries();
1095                         if (nDataQuality==0){
1096                                 AliInfo("No Data Quality Flag found, leaving it empty");
1097                         }
1098                         else{
1099                                 for (Int_t iDataQuality = 0; iDataQuality<nDataQuality; iDataQuality++){
1100                                         AliDCSArray* dataQuality = (AliDCSArray*)dataQualityArray->At(iDataQuality);
1101                                         if (dataQuality){
1102                                                 if (dataQuality->GetTimeStamp()<=timeStart && dataQuality->GetTimeStamp()>=timeDataQualityStart){// taking always the very last entry: if two measurements have the same timestamp, the last one is taken
1103                                                         timeDataQualityStart = dataQuality->GetTimeStamp();
1104                                                         indexDataQuality = iDataQuality;
1105                                                         foundDataQualityStart = kTRUE;
1106                                                 }
1107                                                 else{
1108                                                         // we suppose here that if the first measurement is not before SOR, then none will be (they MUST be in chronological order!!!) 
1109                                                         break;
1110                                                 }
1111                                         }
1112                                 }
1113                                 if (!foundDataQualityStart){
1114                                         // The Data Quality Flag should be found and TRUE at the start of the run. For the time being, if it is not found, don't do anything, but it means there is a problem..
1115                                         AliInfo("No value for the Data Quality Flag found before start of run, the Data Quality Flag will remain empty");
1116                                 }
1117                                 else {
1118                                         // counting how many FALSE values there are
1119                                         Bool_t foundEndOfFalse = kFALSE;
1120                                         Int_t nFalse = 0;
1121                                         for (Int_t iDataQuality = indexDataQuality; iDataQuality < nDataQuality; iDataQuality ++){
1122                                                 AliDCSArray* dataQuality = (AliDCSArray*)dataQualityArray->At(iDataQuality);
1123                                                 AliDebug(4,Form("dataQuality->GetTimeStamp() = %f, timeDataQualityStart = %f, timeEnd = %f", dataQuality->GetTimeStamp(), timeDataQualityStart, timeEnd ));
1124                                                 if (dataQuality->GetTimeStamp()>=timeDataQualityStart && dataQuality->GetTimeStamp()<=timeEnd){ // considering only values between the first valid and the end of the run
1125                                                         Bool_t dataQualityFlag = dataQuality->GetBool(0);
1126                                                         AliDebug(3,Form("DataQuality = %d (set at %f)",(Int_t)dataQualityFlag,dataQuality->GetTimeStamp()));
1127                                                         if (dataQualityFlag != kTRUE){
1128                                                                 if (iDataQuality == indexDataQuality) {  // the first Data Quality value should be TRUE, but ignoring the problem now...
1129                                                                         AliError("The first value for the Data Quality MUST be TRUE! Ignoring for now...");
1130                                                                 }
1131                                                                 nFalse++;
1132                                                         }
1133                                                 }
1134                                         }
1135
1136                                         AliInfo(Form("Found %d FALSE values for the Data Quality Flag",nFalse));
1137                                         Double_t falses[nFalse*2];  // dimensioning this to the maximum possible, as if each false value was followed by a true one --> the false periods correspond to the number of falses
1138
1139                                         Int_t iDataQuality = indexDataQuality;
1140                                         if (nFalse > 0){
1141                                                 Int_t iFalse = 0;
1142                                                 // filling the info about the periods when the flag was set to FALSE
1143                                                 // starting, like for the other DPS, from the measurement closest to SOR (the index of which is iDataQuality)
1144                                                 while (iDataQuality < nDataQuality){
1145                                                         AliDebug(3,Form("iDataQuality = %d",iDataQuality));
1146                                                         AliDCSArray* dataQuality = (AliDCSArray*)dataQualityArray->At(iDataQuality);
1147                                                         if (dataQuality->GetTimeStamp()>=timeDataQualityStart && dataQuality->GetTimeStamp()<=timeEnd){ // considering only values between the first valid and the end of the run
1148                                                                 Bool_t dataQualityFlag = dataQuality->GetBool(0);
1149                                                                 AliDebug(3,Form("DataQuality = %d (set at %f)",(Int_t)dataQualityFlag,dataQuality->GetTimeStamp()));
1150                                                                 if (dataQualityFlag == kTRUE){
1151                                                                         // found TRUE value, continuing
1152                                                                         iDataQuality++;
1153                                                                         continue;
1154                                                                 }
1155                                                                 else{
1156                                                                         /*
1157                                                                         // the check was already done before
1158                                                                         if (iDataQuality == indexDataQuality) {  // the first Data Quality value should be TRUE, but ignoring the problem now...
1159                                                                         AliError("The first value for the Data Quality MUST be TRUE! Ignoring for now...");
1160                                                                         }
1161                                                                         */
1162                                                                         falses[iFalse*2] = dataQuality->GetTimeStamp();
1163                                                                         foundEndOfFalse = kFALSE;
1164                                                                         Int_t iDataQualityNext = iDataQuality+1;
1165                                                                         while (iDataQualityNext < nDataQuality){
1166                                                                                 AliDCSArray* dataQualityNext = (AliDCSArray*)dataQualityArray->At(iDataQualityNext);
1167                                                                                 if (dataQualityNext->GetTimeStamp()>timeDataQualityStart && dataQualityNext->GetTimeStamp()<=timeEnd && dataQualityNext->GetTimeStamp() > dataQuality->GetTimeStamp()){ // considering only values between the first valid and the end of the run, and subsequent to the current value
1168                                                                                         Bool_t dataQualityFlagNext = dataQualityNext->GetBool(0);
1169                                                                                         AliDebug(3,Form("DataQualityNext = %d (set at %f)",(Int_t)dataQualityFlagNext,dataQualityNext->GetTimeStamp()));
1170                                                                                         if (dataQualityFlagNext == kTRUE){
1171                                                                                                 // found TRUE value, first FALSE period completed
1172                                                                                                 foundEndOfFalse = kTRUE;
1173                                                                                                 falses[iFalse*2+1] = dataQualityNext->GetTimeStamp();
1174                                                                                                 iFalse++;
1175                                                                                                 break;
1176                                                                                         }
1177                                                                                         iDataQualityNext++;
1178                                                                                 }
1179                                                                         }
1180                                                                         if (!foundEndOfFalse) {
1181                                                                                 AliInfo("Please, note that the last FALSE value lasted until the end of the run");
1182                                                                                 falses[iFalse*2+1] = timeEnd;
1183                                                                                 iFalse++;
1184                                                                                 break;
1185                                                                         }
1186                                                                         iDataQuality = iDataQualityNext+1;
1187                                                                 }
1188                                                         }
1189                                                 }
1190                                                 grpobj->SetNFalseDataQualityFlag(iFalse);
1191                                                 grpobj->SetFalseDataQualityFlagPeriods(falses);
1192                                         }
1193                                 }
1194                         }
1195                         delete dataQualityArray;
1196                 }
1197                 else{
1198                         AliError("Data Quality Flag array not found in LHC Data file!!!");
1199                 }
1200
1201                 // Processing data to go to AliLHCData object
1202                 AliLHCData* dt = new AliLHCData(fileName.Data(),timeStart,timeEnd);
1203                 // storing AliLHCData in OCDB
1204                 if (dt){
1205                   AliInfo(Form("Filled %d records to AliLHCData object",dt->GetData().GetEntriesFast()));
1206                   AliCDBMetaData md;
1207                   md.SetResponsible("Ruben Shahoyan");
1208                   md.SetComment("LHC data from the GRP preprocessor.");
1209                   Bool_t result = kTRUE;
1210                   result = Store("GRP", "LHCData", dt, &md); 
1211                   delete dt;
1212                   if (!result){
1213                         Log(Form("Problems in storing LHC Data - but not going into Error"));
1214                   }
1215                 }
1216
1217                 // processing LHC Phase
1218
1219                 TObjArray *beam1phase = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[4]);
1220                 TObjArray *beam2phase = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[5]);
1221                 if (beam1phase == 0x0 || beam2phase == 0x0){
1222                         Log(Form("Problems in retrieving LHC Clock data from LHC file"));
1223                         return 4;
1224                 }                       
1225                 AliLHCClockPhase *phaseObj = ProcessLHCClockPhase(beam1phase,beam2phase,timeEnd);
1226                 delete beam1phase;
1227                 delete beam2phase;
1228                 if (phaseObj){
1229                         AliInfo(Form("LHC Phase found"));
1230                         AliCDBMetaData mdPhase;
1231                         mdPhase.SetResponsible("Cvetan Cheshkov");
1232                         mdPhase.SetComment("LHC Clock Phase");
1233                         Bool_t result = kTRUE;
1234                         result = Store("Calib", "LHCClockPhase", phaseObj, &mdPhase); 
1235                         delete phaseObj;
1236                         if (!result) return 3;
1237                 }
1238                 else return 4;
1239         }
1240         
1241         else {
1242                 AliError("No LHCData file found in DCS FXS");
1243                 return 1;
1244         }
1245
1246         return 0;
1247 }
1248
1249 //_______________________________________________________________
1250
1251 UInt_t AliGRPPreprocessor::ProcessSPDMeanVertex()
1252 {
1253         //
1254         //Getting the SPD Mean Vertex
1255         //
1256
1257         TList* list = GetForeignFileSources("SPD", kDAQ, "VertexDiamond");
1258         Bool_t storeResult = kTRUE;
1259         if (list !=0x0 && list->GetEntries()!=0)
1260                 {
1261                         AliInfo("The following sources produced files with the id VertexDiamond from SPD");
1262                         list->Print();
1263                         for (Int_t jj=0;jj<list->GetEntries();jj++){
1264                                 TObjString * str = dynamic_cast<TObjString*> (list->At(jj)); 
1265                                 if (!str){
1266                                         AliError(Form("Expecting a TObjString in the list for the %d-th source, but something else was found.",jj));
1267                                         continue;
1268                                 }
1269                                 AliInfo(Form("found source %s", str->String().Data()));
1270                                 TString fileNameRun = GetForeignFile("SPD", kDAQ, "VertexDiamond", str->GetName());
1271                                 if (fileNameRun.Length()>0){
1272                                         AliInfo(Form("Got the file %s", fileNameRun.Data()));
1273                                         TFile daqFile(fileNameRun.Data(),"READ");
1274                                         if (daqFile.IsOpen()) {
1275                                                 AliESDVertex* meanVtx = dynamic_cast<AliESDVertex*>(daqFile.Get("MeanVertexPos"));
1276                                                 if (meanVtx){
1277                                                         meanVtx->Print();       
1278                                                         // storing in the OCDB 
1279                                                         AliCDBMetaData md;
1280                                                         md.SetResponsible("Cvetan Cheshkov");
1281                                                         md.SetComment("SPD Mean Vertex");                                       
1282                                                         storeResult = Store("Calib", "MeanVertexSPD", meanVtx, &md, 0, kTRUE); 
1283                                                 }
1284                                                 else{
1285                                                         AliWarning("No SPD Mean Vertex object found in file");
1286                                                 } 
1287                                         }
1288                                         else {
1289                                                 AliError("Can't open file");
1290                                                 storeResult = kFALSE;
1291                                         }
1292                                 }
1293                                 else{
1294                                         AliWarning("No file found for current source for SPD Mean Vertex");
1295                                 }
1296                         }
1297                 }
1298         else {
1299                 AliWarning("No list found for SPD Mean Vertex");
1300         }
1301
1302         if (list) delete list;
1303
1304         return storeResult;
1305 }
1306
1307
1308 //_______________________________________________________________
1309
1310 Int_t AliGRPPreprocessor::ProcessDaqLB(AliGRPObject* grpObj)
1311 {
1312         //Getting the DAQ lb information
1313         
1314         time_t timeStart = (time_t)(((TString)GetRunParameter("DAQ_time_start")).Atoi());
1315         time_t timeEnd = (time_t)(((TString)GetRunParameter("DAQ_time_end")).Atoi());
1316         Float_t beamEnergy = (Float_t)(((TString)GetRunParameter("beamEnergy")).Atof());
1317         TString beamType = (TString)GetRunParameter("beamType");
1318         Char_t numberOfDetectors = (Char_t)(((TString)GetRunParameter("numberOfDetectors")).Atoi());
1319         UInt_t  detectorMask = (UInt_t)(((TString)GetRunParameter("detectorMask")).Atoi());
1320         TString lhcPeriod = (TString)GetRunParameter("LHCperiod");
1321         TString runType = (TString)GetRunType();
1322
1323         if (timeEnd >= 2.E9) AliFatal("ALICE run finshed later than Wed May 18 2033, 03:33:20 GMT, maximum time allowed for LHC data --> fix the GRP preprocessor!!!");
1324
1325         UInt_t nparameter = 0;
1326         if (timeStart != 0){
1327                 grpObj->SetTimeStart(timeStart);
1328                 Log(Form("Start time for run %d: %d",fRun, (Int_t)timeStart));
1329                 nparameter++;
1330         } 
1331         else {
1332                 Log(Form("Start time not put in logbook, setting to invalid in GRP entry, and causing an error!"));
1333         }
1334
1335         if (timeEnd != 0){
1336                 grpObj->SetTimeEnd(timeEnd);
1337                 Log(Form("End time for run %d: %i",fRun, (Int_t)timeEnd));
1338                 nparameter++;
1339         } 
1340         else {
1341                 Log(Form("End time not put in logbook, setting to invalid in GRP entry, and causing an error!"));
1342         }
1343
1344         if (beamEnergy != 0){
1345                 Log(Form("Beam Energy for run %d: %f (NOT USING IT TO FILL THE GRP OBJECT, taking it from the LHC file)",fRun, beamEnergy));
1346         } 
1347         else {
1348                 Log(Form("Beam Energy not put in logbook, but not using it anyway for the GRP object (taking it from the LHC file)"));
1349         }
1350
1351                 
1352         if (beamType.Length() != 0){
1353                 Log(Form("Beam Type for run %d: %s (NOT USING IT TO FILL THE GRP OBJECT, taking it from the LHC file)",fRun, beamType.Data()));
1354         } 
1355         else {
1356                 Log(Form("Beam Type not put in logbook, but not using it anyway for the GRP entry (taking it from the LHC file)"));
1357         }
1358                 
1359         if (numberOfDetectors != 0){
1360                 grpObj->SetNumberOfDetectors(numberOfDetectors);
1361                 Log(Form("Number Of Detectors for run %d: %d",fRun, (Int_t)numberOfDetectors));
1362                 nparameter++;
1363         } 
1364         else {
1365                 Log(Form("Number Of Detectors not put in logbook, setting to invalid in GRP entry, and causing an error!"));
1366         }
1367
1368         if (detectorMask != 0){
1369                 grpObj->SetDetectorMask(detectorMask);
1370                 Log(Form("Detector Mask for run %d: %d",fRun, detectorMask));
1371                 nparameter++;
1372         } 
1373         else {
1374                 Log(Form("Detector Mask not put in logbook, setting to invalid in GRP entry, and causing an error!"));
1375         }
1376
1377         if (lhcPeriod.Length() != 0) {
1378                 grpObj->SetLHCPeriod(lhcPeriod);
1379                 Log(Form("LHC period (DAQ) for run %d: %s",fRun, lhcPeriod.Data()));
1380                 nparameter++;
1381         } 
1382         else {
1383                 Log(Form("LHCperiod not put in logbook, setting to invalid in GRP entry, and causing an error!"));
1384         }
1385         if (runType.Length() != 0) {
1386                 grpObj->SetRunType(runType);
1387                 Log(Form("Run Type (DAQ) for run %d: %s",fRun, runType.Data()));
1388                 nparameter++;
1389         } 
1390         else {
1391                 Log(Form("Run Type not put in logbook, setting to invalid in GRP entry, and causing an error!"));
1392         }
1393
1394         return nparameter;
1395 }
1396
1397 //_______________________________________________________________
1398
1399 UInt_t AliGRPPreprocessor::ProcessDaqFxs()
1400 {
1401         //======DAQ FXS======//
1402         
1403         AliRawEventHeaderV3_9::Class()->IgnoreTObjectStreamer(); // to avoid trying reading TObject store in AliRawEventHeaderV3_9 - temporary fix 
1404         AliRawEventHeaderV3_11::Class()->IgnoreTObjectStreamer(); // to avoid trying reading TObject store in AliRawEventHeaderV3_11 - temporary fix 
1405         AliRawEventHeaderV3_12::Class()->IgnoreTObjectStreamer(); // to avoid trying reading TObject store in AliRawEventHeaderV3_12 - temporary fix 
1406         TList* list = GetFileSources(kDAQ);  
1407         if (!list) {
1408                 Log("No raw data tag list: connection problems with DAQ FXS logbook!");
1409                 return 1;
1410         }
1411         
1412         if (list->GetEntries() == 0) {
1413                 Log("no raw data tags in this run: nothing to merge!");
1414                 delete  list; list=0;
1415                 return 0;
1416         }
1417         
1418         TChain *fRawTagChain = new TChain("T");
1419         Int_t nFiles=0;
1420         TIterator* iter = list->MakeIterator();
1421         TObject* obj = 0;
1422         while ((obj = iter->Next())) {
1423                 TObjString* objStr = dynamic_cast<TObjString*> (obj);
1424                 if (objStr) {
1425                         Log(Form("Found source %s", objStr->String().Data()));
1426                         TList* list2 = GetFileIDs(kDAQ, objStr->String());
1427                         if (!list2) {
1428                                 Log("No list with ids from DAQ was found: connection problems with DAQ FXS logbook!");
1429                                 delete fRawTagChain; fRawTagChain=0;
1430                                 return 1;
1431                         }
1432                         Log(Form("Number of ids: %d",list2->GetEntries()));
1433                         for(Int_t i = 0; i < list2->GetEntries(); i++) {
1434                                 TObjString *idStr = (TObjString *)list2->At(i);
1435                                 if (idStr->String().CompareTo("QAThreshold") == 0 || idStr->String().CompareTo("TriggerClassesAndHistosToClone") == 0) {
1436                                         Log(Form("Skipping file with Id %s",idStr->String().Data()));
1437                                         continue; 
1438                                 }
1439                                 TString fileName = GetFile(kDAQ,idStr->String().Data(),objStr->String().Data());
1440                                 if (fileName.Length() > 0) {
1441                                         Log(Form("Adding file in the chain: %s",fileName.Data()));
1442                                         fRawTagChain->Add(fileName.Data());
1443                                         nFiles++;
1444                                 } else {
1445                                         Log(Form("Could not retrieve file with id %s from source %s: "
1446                                                  "connection problems with DAQ FXS!",
1447                                                  idStr->String().Data(), objStr->String().Data()));
1448                                         delete list; list=0;
1449                                         delete list2; list2=0;
1450                                         delete fRawTagChain; fRawTagChain=0;
1451                                         return 2;
1452                                 }
1453                         }
1454                         delete list2;
1455                 }
1456         }
1457         
1458         TString fRawDataFileName = "GRP_Merged.tag.root";
1459         Log(Form("Merging %d raw data tags into file: %s", nFiles, fRawDataFileName.Data()));
1460         
1461         if( fRawTagChain->Merge(fRawDataFileName) < 1 ) {
1462                 Log("Error merging raw data files!!!");
1463                 return 3;
1464         }
1465         
1466         TString outputfile = Form("Run%d.Merged.RAW.tag.root", fRun);
1467         Bool_t result = StoreRunMetadataFile(fRawDataFileName.Data(),outputfile.Data());
1468         
1469         if (!result) {
1470                 Log("Problem storing raw data tags in local file!!!");
1471         } else {
1472                 Log("Raw data tags merged successfully!!");
1473         }
1474         
1475         delete iter;
1476         delete list;
1477         delete fRawTagChain; fRawTagChain=0;
1478         
1479         if (result == kFALSE) {
1480                 return 4;
1481         }
1482         
1483         return 0;
1484         
1485 }
1486
1487 //_______________________________________________________________
1488 UInt_t AliGRPPreprocessor::ProcessDcsFxs(TString partition, TString detector)
1489 {
1490
1491         // processing the info
1492         // stored in the DCS FXS
1493         // coming from the trigger
1494
1495         // Get the CTP counters information
1496
1497         if (partition.IsNull() && !detector.IsNull()){ // standalone partition
1498                 Log("STANDALONE partition for current run, using Trigger Scalers dummy value");
1499                 AliCDBEntry *cdbEntry = GetFromOCDB("CTP","DummyScalers");
1500                 if (!cdbEntry) {
1501                         Log(Form("No dummy CTP scalers entry found, going into error..."));
1502                         return 1;
1503                 }
1504                 else{
1505                         AliTriggerRunScalers *scalers = (AliTriggerRunScalers*)cdbEntry->GetObject();
1506                         if (!scalers){
1507                                 Log(Form("CTP dummy scalers not found in OCDB entry, going into error..."));
1508                                 return 1;
1509                         }
1510                         else {
1511                                 AliCDBMetaData metaData;
1512                                 metaData.SetResponsible("Roman Lietava");
1513                                 metaData.SetComment("CTP scalers from dummy entry in OCDB");
1514                                 if (!Store("CTP","Scalers", scalers, &metaData, 0, 0)) {
1515                                         Log("Unable to store the dummy CTP scalers object to OCDB!");
1516                                         return 1;
1517                                 }
1518                         }
1519                 }
1520         }
1521
1522         else if (!partition.IsNull() && detector.IsNull()){ // global partition
1523                 Log("GLOBAL partition for current run, using CTP scalers from DCS FXS");
1524                 TString countersfile = GetFile(kDCS, "CTP_xcounters","");
1525                 if (countersfile.IsNull()) {
1526                         Log("No CTP counters files has been found: empty source!");
1527                         return 1;
1528                 }
1529                 else {
1530                         Log(Form("File with Id CTP_xcounters found in DCS FXS! Copied to %s",countersfile.Data()));
1531                         AliTriggerRunScalers *scalers = AliTriggerRunScalers::ReadScalers(countersfile);
1532                         if (!scalers) {
1533                                 Log("Bad CTP counters file! The corresponding CDB entry will not be filled!");
1534                                 return 1;
1535                         }
1536                         else {
1537                                 AliCDBMetaData metaData;
1538                                 metaData.SetBeamPeriod(0);
1539                                 metaData.SetResponsible("Roman Lietava");
1540                                 metaData.SetComment("CTP scalers");
1541                                 if (!Store("CTP","Scalers", scalers, &metaData, 0, 0)) {
1542                                         Log("Unable to store the CTP scalers object to OCDB!");
1543                                         delete scalers;                                 
1544                                         return 1;
1545                                 }
1546                         }
1547                         delete scalers;
1548                 }
1549         }
1550         
1551
1552         else{   
1553                 Log(Form("Incorrect field in DAQ logbook for partition = %s and detector = %s, going into error...",partition.Data(),detector.Data()));
1554                 return 2;
1555         }
1556
1557         return 0;
1558
1559 }
1560 //_______________________________________________________________
1561
1562 Int_t AliGRPPreprocessor::ProcessDcsDPs(TMap* valueMap, AliGRPObject* grpObj)
1563 {
1564
1565         //
1566         // processing DCS DPs
1567         //
1568
1569         Int_t entries = 0;  // counting the entries that are in the DCS DB, not taking care whether they have values or not
1570         Int_t nL3Entries = 0;
1571         Int_t nDipoleEntries = 0;
1572         Int_t nEnvEntries = 0;
1573         Int_t nHallProbesEntries = 0;
1574         nL3Entries = ProcessL3DPs(valueMap, grpObj);
1575         nDipoleEntries = ProcessDipoleDPs(valueMap, grpObj);
1576         nEnvEntries = ProcessEnvDPs(valueMap, grpObj);
1577         nHallProbesEntries = ProcessHPDPs(valueMap, grpObj);
1578         grpObj->SetPolarityConventionLHC();  // after the dipole cables swap we comply with LHC convention
1579         Log(Form("L3Entries = %d, nDipoleEntries =%d, nEnvEntries = %d, nHallProbesEntries = %d", nL3Entries, nDipoleEntries, nEnvEntries, nHallProbesEntries));
1580         entries = nL3Entries + nDipoleEntries + nEnvEntries + nHallProbesEntries;
1581         return entries;
1582
1583 }
1584
1585 //_______________________________________________________________
1586
1587 Int_t AliGRPPreprocessor::ProcessL3DPs(const TMap* valueMap, AliGRPObject* grpObj)
1588 {
1589
1590         // processing DPs
1591         // related to 
1592         // L3 info
1593
1594         Int_t nL3Entries = 0;
1595
1596         TObjArray *array = 0x0;
1597         Int_t indexDP = -1;
1598         Bool_t isZero = kTRUE; // flag to monitor L3Current. If set to true, the magnet is OFF, and the polarity can change
1599
1600         AliInfo(Form("==========L3Current==========="));
1601         Bool_t outOfRange = kFALSE;  // flag to monitor if any value collected by DCS is out of range
1602         indexDP = kL3Current;
1603         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1604         if(!array) {
1605                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1606         } 
1607         else {
1608                 if (array->GetEntries() == 0){
1609                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
1610                 }
1611                 else {
1612                         Float_t *floatDCS = ProcessFloatAllMagnet(array, indexDP, isZero);
1613                         if (floatDCS != NULL){
1614                                 grpObj->SetL3Current(floatDCS);
1615                         }
1616                         else{
1617                                 outOfRange = kTRUE;
1618                         }       
1619                         if (floatDCS){
1620                                 delete[] floatDCS;
1621                                 floatDCS = 0x0;
1622                         }
1623                 }
1624                 if (!outOfRange) {
1625                         nL3Entries++;
1626                         ffailedDPs->RemoveAt(indexDP);
1627                 }
1628         }
1629
1630         if (array) array = 0x0;
1631
1632         AliInfo(Form("==========L3Polarity==========="));
1633         indexDP = kL3Polarity;
1634         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1635         if(!array) {
1636                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1637         } 
1638         else {
1639                 if (array->GetEntries() == 0){
1640                         AliError(Form("No entries found in array! setting %s Polarity to invalid...",fgkDCSDataPoints[indexDP]));
1641                 }
1642                 else {
1643                         Bool_t change = kFALSE;
1644                         Char_t charDCS = ProcessBool(array,change);
1645                         if (change == kFALSE){
1646                                 grpObj->SetL3Polarity(charDCS);
1647                                 AliInfo(Form("%s set to %d",fgkDCSDataPoints[indexDP],(Int_t)(grpObj->GetL3Polarity())));
1648                                 ffailedDPs->RemoveAt(indexDP);
1649                                 nL3Entries++;
1650                         }
1651                         else if (isZero){
1652                                 AliInfo(Form("%s set to invalid, but magnet was OFF (according to the current), DP not considered wrong",fgkDCSDataPoints[indexDP]));
1653                                 ffailedDPs->RemoveAt(indexDP);
1654                                 nL3Entries++;
1655                         }
1656                         else {
1657                                 AliError(Form("%s value changed within the run, while the magnet was ON (according to the current), setting it to invalid and considering the DP as wrong",fgkDCSDataPoints[indexDP]));
1658                         }
1659                 }
1660         }
1661
1662         return nL3Entries;
1663
1664 }
1665 //_______________________________________________________________
1666
1667 Int_t AliGRPPreprocessor::ProcessDipoleDPs(const TMap* valueMap, AliGRPObject* grpObj)
1668 {
1669         // processing DPs
1670         // related to 
1671         // the Dipole info
1672
1673         Int_t nDipoleEntries = 0;
1674         TObjArray *array = 0x0;
1675         Int_t indexDP = -1;
1676         Bool_t isZero = kTRUE; // flag to monitor L3Current. If set to true, the magnet is OFF, and the polarity can change
1677
1678         AliInfo(Form("==========DipoleCurrent==========="));
1679         Bool_t outOfRange = kFALSE;  // flag to monitor if any value collected by DCS is out of range
1680         indexDP = kDipoleCurrent;
1681         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1682         if(!array) {
1683                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1684         } 
1685         else {
1686                 if (array->GetEntries() == 0){
1687                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
1688                 }
1689                 else {
1690                         Float_t *floatDCS = ProcessFloatAllMagnet(array, indexDP, isZero);
1691                         if (floatDCS != NULL){
1692                                 grpObj->SetDipoleCurrent(floatDCS);
1693                         } 
1694                         else{
1695                                 outOfRange=kTRUE;
1696                         }
1697                         if (floatDCS){
1698                                 delete[] floatDCS;
1699                                 floatDCS = 0x0;
1700                         }
1701                 }
1702                 if (!outOfRange) {
1703                         nDipoleEntries++;
1704                         ffailedDPs->RemoveAt(indexDP);
1705                 }
1706         }
1707
1708         if (array) array = 0x0;
1709
1710         AliInfo(Form("==========DipolePolarity==========="));
1711         indexDP = kDipolePolarity;
1712         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1713         if(!array) {
1714                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1715         } 
1716         else {
1717                 if (array->GetEntries() == 0){
1718                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
1719                 }
1720                 else {
1721                         Bool_t change = kFALSE;
1722                         Char_t charDCS = ProcessBool(array,change);
1723                         if (!change){
1724                                 grpObj->SetDipolePolarity(charDCS);
1725                                 AliInfo(Form("%s set to %d",fgkDCSDataPoints[indexDP],(Int_t)(grpObj->GetDipolePolarity())));
1726                                 ffailedDPs->RemoveAt(indexDP);
1727                                 nDipoleEntries++;
1728                         }
1729                         else if (isZero){
1730                                 AliInfo(Form("%s set to invalid, but magnet was OFF (according to the current), DP not considered wrong",fgkDCSDataPoints[indexDP]));
1731                                 ffailedDPs->RemoveAt(indexDP);
1732                                 nDipoleEntries++;
1733                         }
1734                         else{
1735                                 AliError(Form("%s value changed within the run while the magnet was ON (according to the current), setting it to invalid and considering the DP as wrong", fgkDCSDataPoints[indexDP]));
1736                         }
1737                 }
1738         }
1739
1740         return nDipoleEntries;
1741
1742 }
1743 //_______________________________________________________________
1744
1745 Int_t AliGRPPreprocessor::ProcessEnvDPs(TMap* valueMap, AliGRPObject* grpObj)
1746 {
1747         // processing DPs
1748         // related to 
1749         // evironment conditions (temperature, pressure) info
1750
1751         Int_t nEnvEntries = 0;
1752         TObjArray *array = 0x0;
1753         Int_t indexDP = -1;
1754
1755         AliInfo(Form("==========CavernTemperature==========="));
1756         Bool_t outOfRange = kFALSE;  // flag to monitor if any value collected by DCS is out of range
1757         indexDP = kCavernTemperature;
1758         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1759         if(!array) {
1760                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1761         } 
1762         else {
1763                 if (array->GetEntries() == 0){
1764                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
1765                 }
1766                 else {
1767                         Float_t *floatDCS = ProcessFloatAll(array);
1768                         if (floatDCS != NULL){
1769                                 grpObj->SetCavernTemperature(floatDCS);
1770                         }
1771                         else{
1772                                 outOfRange = kTRUE;
1773                         }
1774                         if (floatDCS){
1775                                 delete[] floatDCS;
1776                                 floatDCS = 0x0;
1777                         }
1778                 }
1779                 if (!outOfRange) {
1780                         ffailedDPs->RemoveAt(indexDP);
1781                         nEnvEntries++;
1782                 }
1783         }
1784
1785         if (array) array = 0x0;
1786
1787         AliInfo(Form("========== AtmosPressures (Cavern + Surface + Cavern2) ==========="));
1788         AliDCSSensorArray *dcsSensorArray = GetPressureMap(valueMap);
1789         //dcsSensorArray->Print();
1790         if( fPressure->NumFits()<kNumSensors ) {
1791                 Log(Form("Check the pressure sensor values! Not all the %d pressure sensors have been fit",kNumSensors));
1792         } 
1793         Log(Form("Number of fits performed = %d",fPressure->NumFits()));
1794
1795         AliInfo(Form("==========CavernAtmosPressure==========="));
1796         indexDP = kCavernAtmosPressure;
1797         AliDCSSensor* sensorCavernP2 = dcsSensorArray->GetSensor(fgkDCSDataPoints[indexDP]);
1798         TGraph* graph = sensorCavernP2->GetGraph();
1799         AliDebug(3,Form("index = %d",indexDP));
1800         AliDebug(3,Form("name = %s",fgkDCSDataPoints[indexDP]));
1801         AliDebug(2,Form("graph = %p",graph));
1802         AliDebug(3,Form("sensorCavernP2 = %p", sensorCavernP2));
1803         if(sensorCavernP2->GetFit() || graph) {
1804                 if (sensorCavernP2->GetFit()){
1805                         Log(Form("Fit for sensor %s found",fgkDCSDataPoints[indexDP]));
1806                 }
1807                 else {
1808                         Log(Form("Fit for sensor %s not found, but the graph is there - NOT going into error",fgkDCSDataPoints[indexDP]));
1809                 }
1810                 grpObj->SetCavernAtmosPressure(sensorCavernP2);
1811                 ffailedDPs->RemoveAt(indexDP);
1812                 nEnvEntries++;
1813         } 
1814         //if (sensorP2) delete sensorP2;
1815         else {
1816                 Log(Form("ERROR!!! Neither graph nor fit found for sensor %s - this will not increase the number of found DCS DPs and will cause an error", fgkDCSDataPoints[indexDP] ));
1817         }
1818         
1819         AliInfo(Form("==========SurfaceAtmosPressure==========="));
1820         indexDP = kSurfaceAtmosPressure;
1821         AliDCSSensor* sensorP2 = dcsSensorArray->GetSensor(fgkDCSDataPoints[indexDP]);
1822         graph = sensorP2->GetGraph();
1823         AliDebug(3,Form("index = %d",indexDP));
1824         AliDebug(3,Form("name = %s",fgkDCSDataPoints[indexDP]));
1825         AliDebug(2,Form("graph = %p",graph));   
1826         AliDebug(3,Form("sensorP2 = %p", sensorP2));
1827         if(sensorP2->GetFit() || graph) {
1828                 if (sensorP2->GetFit()){
1829                         Log(Form("Fit for sensor %s found",fgkDCSDataPoints[indexDP]));
1830                 }
1831                 else {
1832                         Log(Form("Fit for sensor %s not found, but the graph is there - NOT going into error",fgkDCSDataPoints[indexDP]));
1833                 }
1834                 grpObj->SetSurfaceAtmosPressure(sensorP2);
1835                 ffailedDPs->RemoveAt(indexDP);
1836                 nEnvEntries++;
1837         } 
1838         //if (sensorP2) delete sensorP2;
1839         else {
1840                 Log(Form("ERROR!!! Neither graph nor fit found for sensor %s - this will not increase the number of found DCS DPs and will cause an error", fgkDCSDataPoints[indexDP] ));
1841         }
1842
1843         AliInfo(Form("==========CavernAtmosPressure2==========="));
1844         indexDP = kCavernAtmosPressure2;
1845         AliDCSSensor* sensorCavernP22 = dcsSensorArray->GetSensor(fgkDCSDataPoints[indexDP]);
1846         graph = sensorCavernP22->GetGraph();
1847         AliDebug(3,Form("index = %d",indexDP));
1848         AliDebug(3,Form("name = %s",fgkDCSDataPoints[indexDP]));
1849         AliDebug(2,Form("graph = %p",graph));   
1850         AliDebug(3,Form("sensorCavernP2_2 = %p", sensorCavernP22));
1851         if(sensorCavernP22->GetFit() || graph) {
1852                 if (sensorCavernP22->GetFit()){
1853                         Log(Form("Fit for sensor %s found",fgkDCSDataPoints[indexDP]));
1854                 }
1855                 else {
1856                         Log(Form("Fit for sensor %s not found, but the graph is there - NOT going into error",fgkDCSDataPoints[indexDP]));
1857                 }
1858                 grpObj->SetCavernAtmosPressure2(sensorCavernP22);
1859                 ffailedDPs->RemoveAt(indexDP);
1860                 nEnvEntries++;
1861         } 
1862         //if (sensorP2) delete sensorP2;
1863         else {
1864                 Log(Form("ERROR!!! Neither graph nor fit found for sensor %s - this will not increase the number of found DCS DPs and will cause an error", fgkDCSDataPoints[indexDP] ));
1865         }
1866         
1867         
1868         return nEnvEntries;
1869 }
1870 //_______________________________________________________________
1871
1872 Int_t AliGRPPreprocessor::ProcessHPDPs(const TMap* valueMap, AliGRPObject* grpObj)
1873 {
1874         // processing DPs
1875         // related to 
1876         // Hall Probes info
1877
1878         Int_t nHPEntries = 0;
1879         TObjArray *array = 0x0;
1880         Int_t indexDP = -1;
1881         Bool_t outOfRange; // flag to monitor if any value collected by DCS is out of range
1882
1883         if (fgknDCSDPHallProbes != AliGRPObject::GetNumberOfHP()){
1884                 AliError(Form("Number of Hall probes expected in GRP Preprocessor (i.e. %d) different from number of Hall Probes foreseen in GRP object (i.e. %d). Looping on entries from GRP object anyway.", fgknDCSDPHallProbes, AliGRPObject::GetNumberOfHP()));
1885         }
1886         for (indexDP = 0; indexDP < AliGRPObject::GetNumberOfHP(); indexDP++){
1887                 outOfRange = kFALSE; // resetting outOfRange flag at each HP
1888                 AliInfo(Form("==========%s===========",AliGRPObject::GetHPDP(indexDP)));
1889                 array = (TObjArray *)valueMap->GetValue(AliGRPObject::GetHPDP(indexDP));
1890                 if(!array) {
1891                         Log(Form("%s not found in the map!!!",AliGRPObject::GetHPDP(indexDP)));
1892                 } 
1893                 else {
1894                         if (array->GetEntries() == 0){
1895                                 AliError(Form("No entries found in array! setting %s to invalid...",AliGRPObject::GetHPDP(indexDP)));
1896                         }
1897                         else {
1898                                 Float_t *floatDCS = ProcessFloatAll(array);
1899                                 if (floatDCS != NULL){
1900                                         AliDebug(2,Form("value[0] = %f, value[1] = %f, value[2] = %f, value[3] = %f, value[4] = %f",floatDCS[0],floatDCS[1],floatDCS[2],floatDCS[3],floatDCS[4])); 
1901                                         grpObj->SetHallProbes((AliGRPObject::DP_HallProbes)indexDP,floatDCS);
1902                                         for (Int_t kk = 0 ; kk< 5; kk++){
1903                                                 AliDebug(2,Form("HallProbe[%d][%d]=%f",indexDP,kk,grpObj->GetHallProbes((AliGRPObject::DP_HallProbes)indexDP,(AliGRPObject::Stats)kk)));
1904                                         }
1905                                 }
1906                                 else{
1907                                         outOfRange = kTRUE;
1908                                 }
1909                                 if (floatDCS){
1910                                         delete[] floatDCS;
1911                                         floatDCS = 0x0;
1912                                 }
1913                         }
1914                         if (!outOfRange) {
1915                                 ffailedDPs->RemoveAt(indexDP + fgkDCSDPHallTopShift);  // 7 = shift in the complete list of DPs to get to the Hall Probes
1916                                 nHPEntries++;
1917                         }
1918                 }
1919         }
1920                 
1921         Log(Form("Hall Probes = %d ", nHPEntries));
1922         return nHPEntries;
1923 }
1924
1925 //_________________________________________________________________________
1926
1927 AliSplineFit* AliGRPPreprocessor::GetSplineFit(const TObjArray *array, const TString& stringID){
1928
1929
1930         // 
1931         // returning Spline Fit 
1932         // 
1933
1934         Int_t entriesarray = array->GetEntries();
1935         Float_t* value = new Float_t[entriesarray];
1936         Float_t* time = new Float_t[entriesarray];
1937         AliDCSValue* v = 0x0;
1938         for (Int_t iarray = 0; iarray < entriesarray; iarray++){
1939                 v = (AliDCSValue*)array->At(iarray);
1940                 value[iarray] = v->GetFloat();
1941                 time[iarray] = v->GetTimeStamp();
1942                 AliDebug(2,Form("iarray = %d, value = %f, time = %f",iarray,value[iarray],time[iarray]));
1943         }
1944         TGraph* gr = new TGraph(entriesarray,value,time);
1945         if (!gr ) {
1946                 AliWarning(Form("%s: no input graph to compute SplineFit",stringID.Data()));
1947                 return NULL;
1948         }
1949         AliSplineFit *fit = new AliSplineFit();
1950         fit->SetMinPoints(10);
1951         fit->InitKnots(gr,10,10,0.0);
1952         fit->SplineFit(2);
1953         fit->Cleanup();
1954         return fit;
1955 }
1956
1957 //_________________________________________________________________________
1958
1959 TString AliGRPPreprocessor::ProcessChar(const TObjArray *array)
1960 {
1961
1962         // 
1963         // processing char
1964         //
1965
1966         TString aDCSString="";
1967         
1968         AliDCSValue *v = 0x0;
1969         for(Int_t iCount = 0; iCount < array->GetEntries(); iCount++) {
1970                 v = (AliDCSValue *)array->At(iCount);
1971                 if (((Int_t)(v->GetTimeStamp()) < (Int_t)GetStartTimeDCSQuery()) || ((Int_t)(v->GetTimeStamp()) > (Int_t)GetEndTimeDCSQuery())) {
1972                         AliError(Form("DCS values for the parameter outside the queried interval"));
1973                         continue;
1974                 }
1975                 if (iCount > 0) {
1976                         if (aDCSString != v->GetChar())
1977                         AliError(Form("DCS values for the parameter changed from %s to %c within the queried interval", aDCSString.Data(), (Char_t)v->GetChar()));
1978                 }
1979                 aDCSString = (TString)v->GetChar();  // keeping always last value in the array
1980         }
1981         return aDCSString;
1982 }
1983
1984 //__________________________________________________________________________________________________________________
1985
1986 Float_t* AliGRPPreprocessor::ProcessFloatAll(const TObjArray* array)
1987 {
1988         // 
1989         // processing Float values using Mean, Median, Standard Deviation wrt Mean, Standar Deviation wrt Median 
1990         //
1991         // parameters[0] = mean
1992         // parameters[1] = truncated mean (calculated excluding points outside +/- 3RMS from mean
1993         // parameters[2] = median
1994         // parameters[3] = standard deviation wrt mean
1995         // parameters[4] = standard deviation wrt median
1996         //
1997
1998         TString timeStartString = (TString)GetRunParameter("DAQ_time_start");
1999         TString timeEndString = (TString)GetRunParameter("DAQ_time_end");
2000         if (timeStartString.IsNull() || timeStartString.IsNull()){
2001                 if (timeStartString.IsNull()){ 
2002                         AliError("DAQ_time_start not set in logbook! Setting statistical values for current DP to invalid");
2003                 }
2004                 else if (timeStartString.IsNull()){
2005                         AliError("DAQ_time_end not set in logbook! Setting statistical values for current DP to invalid");
2006                 }
2007                 fdaqStartEndTimeOk = kFALSE;
2008                 return 0;
2009         }  
2010
2011         Int_t timeStart = (Int_t)(timeStartString.Atoi());
2012         Int_t timeEnd = (Int_t)(timeEndString.Atoi());
2013         Float_t* parameters = new Float_t[5];
2014         Int_t iCounts = 0;
2015         Int_t iCountsRun = 0;
2016         Int_t nCounts = array->GetEntries();
2017         Float_t valueBeforeSOR = 0;
2018         Float_t valueAfterEOR = 0;
2019         Int_t timestampBeforeSOR = -1;
2020         Int_t timestampAfterEOR = -1;
2021         Int_t ientrySOR = -1;
2022         Int_t ientryEOR = -1;
2023         Float_t* arrayValues = 0x0; 
2024         Double_t* arrayWeights = 0x0; 
2025         Bool_t truncMeanFlag = kTRUE;  // flag to indicate whether Truncated Mean should be calculated or not
2026         Bool_t sdFlag = kTRUE;  // flag to indicate whether SD (wrt Mean/Median) should be calculated or not
2027
2028         for(Int_t i = 0; i < nCounts; i++) {
2029                 AliDCSValue *v = (AliDCSValue *)array->At(i);
2030                 if ((v->GetFloat() <= fminFloat) || (v->GetFloat() >= fmaxFloat)) {
2031                         AliError(Form("Error! Float value found in DCS map at %d-th entry is OUT OF RANGE: value = %6.5e",i,v->GetFloat()));
2032                         if (v->GetFloat() < fminFloat) AliInfo(Form("The value is smaller than %6.5e",fminFloat));
2033                         if (v->GetFloat() > fmaxFloat) AliInfo(Form("The value is greater than %6.5e",fmaxFloat));
2034                         delete [] parameters;
2035                         return NULL;
2036                 }
2037                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
2038                         AliDebug(2,Form("%d-th entry = %f at timestamp %i",i,v->GetFloat(),v->GetTimeStamp()));
2039                         iCounts += 1;
2040                         // look for the last value before SOR and the first value before EOR
2041                         if (((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) && (Int_t)(v->GetTimeStamp()) < timeStart) {
2042                                 timestampBeforeSOR = (Int_t)(v->GetTimeStamp());
2043                                 AliDebug(2,Form("timestamp of last value before SOR = %d, with DAQ_time_start = %d",timestampBeforeSOR,timeStart));
2044                                 valueBeforeSOR = v->GetFloat();
2045                         }
2046                         else if ((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery() && (Int_t)(v->GetTimeStamp()) > timeEnd && timestampAfterEOR == -1){
2047                                 timestampAfterEOR = (Int_t)(v->GetTimeStamp());
2048                                 valueAfterEOR = v->GetFloat();
2049                                 AliDebug(2,Form("timestamp of first value after EOR = %d, with DAQ_time_end = %d",timestampAfterEOR,timeEnd));
2050                         }
2051                         // check if there are DPs between DAQ_time_start and DAQ_time_end
2052                         if(((Int_t)(v->GetTimeStamp()) >= timeStart) &&((Int_t)(v->GetTimeStamp()) <= timeEnd)) {
2053                                 if (ientrySOR == -1) ientrySOR = i;  // first entry after SOR
2054                                 if (ientryEOR < i) ientryEOR = i;  // last entry before EOR
2055                                 AliDebug(2,Form("entry between SOR and EOR"));
2056                                 iCountsRun += 1;
2057                         }
2058                 }
2059                 else {
2060                         AliError(Form("DCS values for the parameter outside the queried interval: timestamp = %d",v->GetTimeStamp()));
2061                 }
2062         }
2063
2064         if (timestampBeforeSOR == -1){
2065                 AliWarning("No value found before SOR");
2066         }
2067         if (timestampAfterEOR == -1){
2068                 AliWarning("No value found after EOR");
2069         }
2070
2071         AliDebug(2,Form("Number of valid entries (within DCS query interval) = %i, from a total amount of %i entries",iCounts,nCounts));
2072         AliDebug(2,Form("Last value before DAQ_time_start (SOR) = %f at timestamp = %d",valueBeforeSOR,timestampBeforeSOR));
2073         AliDebug(2,Form("First value after DAQ_time_end (EOR)   = %f at timestamp = %d",valueAfterEOR,timestampAfterEOR));
2074         AliInfo(Form("Found %d entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)",iCountsRun));
2075         AliDebug(2,Form("Index of first entry after DAQ_time_start (SOR) = %d ",ientrySOR));
2076         AliDebug(2,Form("Index of first entry before DAQ_time_end (EOR) = %d ",ientryEOR));
2077
2078         Int_t nentriesUsed = 0;
2079         if (iCountsRun > 1){
2080                 AliInfo("Using entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)");
2081                 AliDebug(2,"Calculating (weighted) Mean and Median");
2082                 arrayValues = new Float_t[iCountsRun]; 
2083                 arrayWeights = new Double_t[iCountsRun]; 
2084                 nentriesUsed = iCountsRun;
2085                 for (Int_t i = ientrySOR; i <= ientryEOR; i++){
2086                         AliDCSValue *v = (AliDCSValue *)array->At(i);
2087                         Int_t timestamp2 = 0;
2088                         if (i < ientryEOR){
2089                                 AliDCSValue *v1 = (AliDCSValue *)array->At(i+1);
2090                                 timestamp2 = (Int_t)v1->GetTimeStamp();
2091                         }
2092                         else {
2093                                 timestamp2 = timeEnd+1;
2094                         }
2095                         arrayWeights[i-ientrySOR] = (Double_t)(timestamp2 - (Int_t)v->GetTimeStamp());
2096                         arrayValues[i-ientrySOR] = v->GetFloat();
2097                 }
2098                 parameters[0] = TMath::Mean(iCountsRun,arrayValues,arrayWeights);
2099                 parameters[2] = TMath::Median(iCountsRun,arrayValues,arrayWeights);
2100         }
2101         else if (iCountsRun == 1){
2102                 AliDCSValue* v = (AliDCSValue *)array->At(ientrySOR);
2103                 nentriesUsed = 2;
2104                 if (timestampBeforeSOR != -1 && timestampBeforeSOR != (Int_t)v->GetTimeStamp()){
2105                         AliWarning("Using single entry between DAQ_time_start (SOR) and DAQ_time_end (EOR) and last entry before SOR. Truncated mean won't be calculated.");
2106                         arrayValues = new Float_t[2];
2107                         arrayWeights = new Double_t[2];
2108                         arrayValues[0] = valueBeforeSOR;
2109                         arrayWeights[0] = (Double_t)((Int_t)v->GetTimeStamp()-timestampBeforeSOR);
2110                         arrayValues[1] = v->GetFloat();
2111                         arrayWeights[1] = (Double_t)(timeEnd+1-(Int_t)v->GetTimeStamp());
2112                         AliDebug(2, Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
2113                         AliDebug(2, Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
2114                         parameters[0] = TMath::Mean(2,arrayValues,arrayWeights);
2115                         parameters[2] = TMath::Median(2,arrayValues,arrayWeights);
2116                         truncMeanFlag = kFALSE;
2117                 }
2118                 else{
2119                         AliError("Cannot calculate mean, truncated mean, median, SD wrt mean, SD wrt median for current DP - only one value collected during the run, but no value before with which to calculate the statistical quantities");
2120                         parameters[0] = AliGRPObject::GetInvalidFloat();
2121                         parameters[1] = AliGRPObject::GetInvalidFloat();
2122                         parameters[2] = AliGRPObject::GetInvalidFloat();
2123                         parameters[3] = AliGRPObject::GetInvalidFloat();
2124                         parameters[4] = AliGRPObject::GetInvalidFloat();
2125                         return parameters;
2126                 }
2127         }
2128         else { // iCountsRun == 0, using only the point immediately before SOR
2129                 if (timestampBeforeSOR == -1){
2130                         AliError("Cannot set mean, truncated mean, median, SD wrt mean, SD wrt median for current DP - no points during the run collected, and point before SOR missing");
2131                         parameters[0] = AliGRPObject::GetInvalidFloat();
2132                         parameters[1] = AliGRPObject::GetInvalidFloat();
2133                         parameters[2] = AliGRPObject::GetInvalidFloat();
2134                         parameters[3] = AliGRPObject::GetInvalidFloat();
2135                         parameters[4] = AliGRPObject::GetInvalidFloat();
2136                         return parameters;
2137                 }
2138                 else {
2139                         AliWarning("Using only last entry before SOR. Truncated mean and Standard deviations (wrt mean/median) won't be calculated.");
2140                         AliDebug(2,Form("value = %f",valueBeforeSOR)); 
2141                         parameters[0] = valueBeforeSOR;
2142                         parameters[2] = valueBeforeSOR;
2143                         truncMeanFlag = kFALSE;
2144                         sdFlag = kFALSE;
2145                 }
2146         }
2147
2148         Float_t temp = 0;
2149         Float_t temp1 = 0;
2150         Float_t sumweights = 0; 
2151         Int_t entriesTruncMean = 0;
2152         Float_t* arrayValuesTruncMean = new Float_t[nentriesUsed]; 
2153         Double_t* arrayWeightsTruncMean = new Double_t[nentriesUsed]; 
2154
2155         // calculating SD wrt Mean and Median
2156         AliDebug(2,"Calculating SD wrt Mean and SD wrt Median");
2157         if (sdFlag){
2158                 for (Int_t i =0; i< nentriesUsed; i++){
2159                         AliDebug(2,Form("Entry %d: value = %f, weight = %f",i,arrayValues[i],arrayWeights[i]));
2160                         temp += (arrayValues[i]-parameters[2])*(arrayValues[i]-parameters[2]);
2161                         temp1 += arrayWeights[i]*(arrayValues[i]-parameters[0])*(arrayValues[i]-parameters[0]);
2162                         sumweights += arrayWeights[i];
2163                 }
2164                 // setting SD wrt Mean 
2165                 if (sumweights != 0 ){
2166                         parameters[3] = TMath::Sqrt(temp1/sumweights);
2167                 }
2168                 else {
2169                         AliError("Sum of weights to calculate Standard Deviation (wrt mean) <= 0, setting the SD to invalid");
2170                         parameters[3] = AliGRPObject::GetInvalidFloat();
2171                 }
2172                 // setting SD wrt Median
2173                 if (nentriesUsed != 0){
2174                         parameters[4] = TMath::Sqrt(temp/nentriesUsed);
2175                 }
2176                 else{
2177                         AliError("Number of entries used to calculate Standard Deviation (wrt median) <= 0, setting the SD to invalid");
2178                         parameters[4] = AliGRPObject::GetInvalidFloat();
2179                 }
2180         }
2181         else {
2182                 parameters[3] = AliGRPObject::GetInvalidFloat();
2183                 parameters[4] = AliGRPObject::GetInvalidFloat();
2184         }               
2185
2186         // calculating truncated mean (this comes afterwards since you need the SD wrt Mean)
2187         if (truncMeanFlag){
2188                 AliDebug(2,"Calculating Truncated Mean");
2189                 for (Int_t i =0; i< nentriesUsed; i++){
2190                         AliDebug(2,Form("Entry %d: value = %f, weight = %f",i,arrayValues[i],arrayWeights[i]));
2191                         if ((arrayValues[i]<=parameters[0]+3*parameters[3]) && (arrayValues[i]>=parameters[0]-3*parameters[3])){
2192                                 arrayValuesTruncMean[entriesTruncMean]=arrayValues[i];
2193                                 arrayWeightsTruncMean[entriesTruncMean]=arrayWeights[i];
2194                                 AliDebug(2,Form("For Truncated Mean: Entry %d: value = %f, weight = %f",entriesTruncMean,arrayValuesTruncMean[entriesTruncMean],arrayWeightsTruncMean[entriesTruncMean]));
2195                                 entriesTruncMean++;                     
2196                         }
2197                         else{
2198                                 AliDebug(2,"Discarding entry");
2199                         }
2200                 }
2201                 // setting truncated mean 
2202                 if (entriesTruncMean >1){
2203                         AliDebug(2,Form("%d entries used for truncated mean",entriesTruncMean));
2204                         parameters[1] = TMath::Mean(entriesTruncMean,arrayValuesTruncMean,arrayWeightsTruncMean);
2205                 }
2206                 else{   
2207                         AliDebug(2,Form("Too few entries (%d) to calculate truncated mean",entriesTruncMean));
2208                         parameters[1] = AliGRPObject::GetInvalidFloat();
2209                 }
2210         }
2211         else{
2212                         parameters[1] = AliGRPObject::GetInvalidFloat();
2213         }
2214
2215         if (arrayValues){
2216                 delete [] arrayValues;
2217         } 
2218         if (arrayWeights){
2219                 delete [] arrayWeights;
2220         } 
2221         delete [] arrayValuesTruncMean;
2222         delete [] arrayWeightsTruncMean;
2223
2224         AliInfo(Form("(weighted) mean = %f ",parameters[0]));
2225         AliInfo(Form("(weighted) truncated mean = %f ",parameters[1]));
2226         AliInfo(Form("median = %f ",parameters[2]));
2227         AliInfo(Form("(weighted) standard deviation with (weighted) mean = %f ",parameters[3]));
2228         AliInfo(Form("standard deviation with median = %f ",parameters[4]));
2229         
2230         return parameters;
2231 }
2232
2233 //__________________________________________________________________________________________________________________
2234
2235 Float_t* AliGRPPreprocessor::ProcessFloatAllMagnet(const TObjArray* array, Int_t indexDP, Bool_t &isZero)
2236 {
2237         // 
2238         // processing Float values using Mean, Median, Standard Deviation wrt Mean, Standar Deviation wrt Median 
2239         // used for L3 and Dipole magnets, using isZero flag to decide whther the magnet was OFF/ON
2240         // the flag is set according to the L3/Dipole current value
2241         // current threshold for L3 = 350 A (value provided by DCS)
2242         // current threshold for Dipole = 450 A (value provided by DCS)
2243         //
2244         // parameters[0] = mean
2245         // parameters[1] = truncated mean (calculated excluding points outside +/- 3RMS from mean
2246         // parameters[2] = median
2247         // parameters[3] = standard deviation wrt mean
2248         // parameters[4] = standard deviation wrt median
2249         //
2250
2251         AliInfo(Form("indexDP = %d",indexDP)); 
2252
2253         Int_t nCounts = array->GetEntries();
2254         for(Int_t i = 0; i < nCounts; i++) {
2255                 AliDCSValue *v = (AliDCSValue *)array->At(i);
2256                 if ((v->GetFloat() <= fminFloat) || (v->GetFloat() >= fmaxFloat)) {
2257                         AliError(Form("Error! Float value found in DCS map at %d-th entry is OUT OF RANGE: value = %6.5e",i,v->GetFloat()));
2258                         if (v->GetFloat() < fminFloat) AliInfo(Form("The value is smaller than %6.5e",fminFloat));
2259                         if (v->GetFloat() > fmaxFloat) AliInfo(Form("The value is greater than %6.5e",fmaxFloat));
2260                         return NULL;
2261                 }
2262                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
2263                         AliDebug(2,Form("%d-th entry = %f",i,v->GetFloat()));
2264                         if (indexDP == kL3Current && v->GetFloat() > 350 && isZero == kTRUE) isZero=kFALSE; 
2265                         if (indexDP == kDipoleCurrent && v->GetFloat() > 450 && isZero == kTRUE) isZero=kFALSE; 
2266                 }
2267                 else {
2268                         AliError(Form("DCS values for the parameter outside the queried interval"));
2269                 }
2270         }
2271
2272         return ProcessFloatAll(array);
2273 }
2274
2275
2276 //_______________________________________________________________
2277
2278 Char_t AliGRPPreprocessor::ProcessBool(const TObjArray* array, Bool_t &change)
2279 {
2280         // 
2281         // processing Boolean values
2282         //
2283
2284         Bool_t aDCSBool = kTRUE;
2285
2286         AliDCSValue *v = 0x0;
2287
2288         for(Int_t iCount = 0; iCount < array->GetEntries(); iCount++) {
2289                 v = (AliDCSValue *)array->At(iCount);
2290                 if (((Int_t)(v->GetTimeStamp()) < (Int_t)GetStartTimeDCSQuery()) || ((Int_t)(v->GetTimeStamp()) > (Int_t)GetEndTimeDCSQuery())) {
2291                         AliError(Form("DCS values for the parameter outside the queried interval"));
2292                         continue;
2293                 }
2294                 if (iCount > 0) {
2295                         if (aDCSBool != v->GetBool()) {
2296                                 AliError(Form("DCS values for the parameter changed from %d to %d within the queried interval", (UInt_t)aDCSBool, (UInt_t)v->GetBool()));
2297                                 change = kTRUE;
2298                         }
2299                 }
2300                 aDCSBool = v->GetBool(); // always keeping last value
2301                 AliDebug(2,Form("Bool = %d",(Int_t)aDCSBool));
2302         }
2303         
2304         Char_t caDCSBool = (Char_t) aDCSBool;
2305         return caDCSBool;
2306         
2307 }
2308
2309 //_______________________________________________________________
2310
2311 Float_t AliGRPPreprocessor::ProcessInt(const TObjArray* array)
2312 {
2313         // 
2314         // processing Int values, returning mean
2315         // AliGRPObject::GetInvalidFloat() is returned if any of the DCS values
2316         // are outside the queried time interval or their value is out of range
2317         //
2318
2319         TString timeStartString = (TString)GetRunParameter("DAQ_time_start");
2320         TString timeEndString = (TString)GetRunParameter("DAQ_time_end");
2321         if (timeStartString.IsNull() || timeStartString.IsNull()){
2322                 if (timeStartString.IsNull()){ 
2323                         AliError("DAQ_time_start not set in logbook! Setting statistical values for current DP to invalid");
2324                 }
2325                 else if (timeStartString.IsNull()){
2326                         AliError("DAQ_time_end not set in logbook! Setting statistical values for current DP to invalid");
2327                 }
2328                 return 0;
2329         }  
2330
2331         Int_t timeStart = (Int_t)(timeStartString.Atoi());
2332         Int_t timeEnd = (Int_t)(timeEndString.Atoi());
2333         Float_t aDCSArrayMean = 0.0;
2334         Int_t iCounts = 0;
2335         Float_t valueBeforeSOR = 0;
2336         Float_t valueAfterEOR = 0;
2337         Int_t timestampBeforeSOR = -1;
2338         Int_t timestampAfterEOR = -1;
2339         Int_t ientrySOR = -1;
2340         Int_t ientryEOR = -1;
2341         Float_t* arrayValues = 0x0; 
2342         Double_t* arrayWeights = 0x0; 
2343         Int_t iCountsRun = 0;
2344         Int_t nCounts = array->GetEntries();
2345
2346         for(Int_t i = 0; i < nCounts; i++) {
2347                 AliDCSValue* v = (AliDCSValue *)array->At(i);
2348                 if ((v->GetInt() < fminInt) || (v->GetInt() > fmaxInt)) {
2349                         AliError(Form("Error! Int value found in DCS map at %d-th entry is OUT OF RANGE: value = %d",i, v->GetInt()));
2350                         return AliGRPObject::GetInvalidFloat();
2351                 }
2352                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
2353                         AliDebug(2,Form("%d-th entry = %d at timestamp %i",i,v->GetInt(),v->GetTimeStamp()));
2354                         iCounts += 1;
2355                         // look for the last value before SOR and the first value before EOR
2356                         if (((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) && (Int_t)(v->GetTimeStamp()) < timeStart) {
2357                                 timestampBeforeSOR = (Int_t)(v->GetTimeStamp());
2358                                 AliDebug(2,Form("timestamp of last entry before SOR = %d, with DAQ_time_start = %d",timestampBeforeSOR,timeStart));
2359                                 valueBeforeSOR = (Float_t) v->GetInt();
2360                         }
2361                         else if ((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery() && (Int_t)(v->GetTimeStamp()) > timeEnd && timestampAfterEOR == -1){
2362                                 timestampAfterEOR = (Int_t)(v->GetTimeStamp());
2363                                 valueAfterEOR = (Float_t) v->GetInt();
2364                                 AliDebug(2,Form("timestamp of first entry after EOR = %d, with DAQ_time_end = %d",timestampAfterEOR,timeEnd));
2365                         }
2366                         // check if there are DPs between DAQ_time_start and DAQ_time_end
2367                         if(((Int_t)(v->GetTimeStamp()) >= timeStart) &&((Int_t)(v->GetTimeStamp()) <= timeEnd)) {
2368                                 if (ientrySOR == -1) ientrySOR = i;  // first entry after SOR
2369                                 if (ientryEOR < i) ientryEOR = i;  // last entry before EOR
2370                                 AliDebug(2,Form("entry between SOR and EOR"));
2371                                 iCountsRun += 1;
2372                         }
2373                 }
2374                 else {
2375                         AliError(Form("DCS values for the parameter outside the queried interval: timestamp = %d",v->GetTimeStamp()));
2376                 }
2377         }
2378
2379         if (timestampBeforeSOR == -1){
2380                 AliWarning("No value found before SOR!");
2381         }
2382         if (timestampAfterEOR == -1){
2383                 AliWarning("No value found after EOR!");
2384         }
2385
2386         AliDebug(2,Form("Number of valid entries (within query interval) = %i, starting from %i entries",iCounts,nCounts));
2387         AliDebug(2,Form("Last value before DAQ_time_start (SOR) = %f at timestamp = %d",valueBeforeSOR,timestampBeforeSOR));
2388         AliDebug(2,Form("First value after DAQ_time_end (EOR)   = %f at timestamp = %d",valueAfterEOR,timestampAfterEOR));
2389         AliInfo(Form("Found %d entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)",iCountsRun));
2390         AliDebug(2,Form("Index of first entry after DAQ_time_start (SOR) = %d ",ientrySOR));
2391         AliDebug(2,Form("Index of first entry before DAQ_time_end (EOR) = %d ",ientryEOR));
2392
2393         Int_t nentriesUsed = 0;
2394         if (iCountsRun > 1){
2395                 AliInfo("Using entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)");
2396                 AliDebug(2,"Calculating (weighted) Mean");
2397                 arrayValues = new Float_t[iCountsRun]; 
2398                 arrayWeights = new Double_t[iCountsRun]; 
2399                 nentriesUsed = iCountsRun;
2400                 for (Int_t i = ientrySOR; i <= ientryEOR; i++){
2401                         AliDCSValue *v = (AliDCSValue *)array->At(i);
2402                         Int_t timestamp2 = 0;
2403                         if (i < ientryEOR){
2404                                 AliDCSValue *v1 = (AliDCSValue *)array->At(i+1);
2405                                 timestamp2 = (Int_t)v1->GetTimeStamp();
2406                         }
2407                         else {
2408                                 timestamp2 = timeEnd+1;
2409                         }
2410                         arrayWeights[i-ientrySOR] = (Double_t)(timestamp2 - (Int_t)v->GetTimeStamp());
2411                         arrayValues[i-ientrySOR] = (Float_t)v->GetInt();
2412                 }
2413                 aDCSArrayMean = TMath::Mean(iCountsRun,arrayValues,arrayWeights);
2414                 delete [] arrayValues;
2415                 delete [] arrayWeights;
2416         }
2417         else if (iCountsRun == 1){
2418                 AliDCSValue* v = (AliDCSValue *)array->At(ientrySOR);
2419                 nentriesUsed = 2;
2420                 if (timestampBeforeSOR != -1 && timestampBeforeSOR != (Int_t)v->GetTimeStamp()){
2421                         AliWarning("Using single entry between DAQ_time_start (SOR) and DAQ_time_end (EOR) and last entry before SOR.");
2422                         arrayValues = new Float_t[2];
2423                         arrayWeights = new Double_t[2];
2424                         arrayValues[0] = valueBeforeSOR;
2425                         arrayWeights[0] = (Double_t)((Int_t)v->GetTimeStamp()-timestampBeforeSOR);
2426                         arrayValues[1] = (Float_t)v->GetInt();
2427                         arrayWeights[1] = (Double_t)(timeEnd+1-(Int_t)v->GetTimeStamp());
2428                         AliDebug(2,Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
2429                         AliDebug(2,Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
2430                         aDCSArrayMean = TMath::Mean(2,arrayValues,arrayWeights);
2431                         delete [] arrayValues;
2432                         delete [] arrayWeights;
2433                 }
2434                 else{
2435                         AliError("Cannot calculate mean - only one value collected during the run, but no value before with which to calculate the statistical quantities");
2436                         return AliGRPObject::GetInvalidFloat();
2437                 }
2438         }
2439         else { // iCountsRun == 0, using the point immediately before SOR and the one immediately after EOR
2440                 if (timestampBeforeSOR == -1 || timestampAfterEOR == -1){
2441                         if (timestampBeforeSOR == -1){
2442                                 AliError("Cannot calculate mean - no points during the run collected, and point before SOR missing");
2443                         }
2444                         if (timestampAfterEOR == -1){
2445                                 AliError("Cannot calculate maen - no points during the run collected, and point after EOR missing");
2446                         }
2447                         return AliGRPObject::GetInvalidFloat();
2448                 }
2449                 else {
2450                         AliWarning("Using last entry before SOR and first entry after EOR.");
2451                         nentriesUsed = 2;
2452                         arrayValues = new Float_t[2];
2453                         arrayWeights = new Double_t[2];
2454                         arrayValues[0] = valueBeforeSOR;
2455                         arrayWeights[0] = (Double_t)(timestampAfterEOR - timestampBeforeSOR);
2456                         arrayValues[1] = valueAfterEOR;
2457                         arrayWeights[1] = 1.;
2458                         AliDebug(2,Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
2459                         AliDebug(2,Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
2460                         aDCSArrayMean = TMath::Mean(1,arrayValues,arrayWeights);
2461                         delete [] arrayValues;
2462                         delete [] arrayWeights;
2463                 }
2464         }
2465
2466         AliInfo(Form("mean = %f ", aDCSArrayMean));
2467         return aDCSArrayMean;
2468
2469 }
2470 //_______________________________________________________________
2471
2472 Float_t AliGRPPreprocessor::ProcessUInt(const TObjArray* array)
2473 {
2474         // 
2475         // processing Int values, returning mean 
2476         // AliGRPObject::GetInvalidFloat() is returned if any of the DCS values
2477         // are outside the queried time interval or their value is out of range
2478         //
2479
2480         TString timeStartString = (TString)GetRunParameter("DAQ_time_start");
2481         TString timeEndString = (TString)GetRunParameter("DAQ_time_end");
2482         if (timeStartString.IsNull() || timeStartString.IsNull()){
2483                 if (timeStartString.IsNull()){ 
2484                         AliError("DAQ_time_start not set in logbook! Setting statistical values for current DP to invalid");
2485                 }
2486                 else if (timeStartString.IsNull()){
2487                         AliError("DAQ_time_end not set in logbook! Setting statistical values for current DP to invalid");
2488                 }
2489                 return 0;
2490         }  
2491
2492         Int_t timeStart = (Int_t)(timeStartString.Atoi());
2493         Int_t timeEnd = (Int_t)(timeEndString.Atoi());
2494         Float_t aDCSArrayMean = 0.0;
2495         Int_t iCounts = 0;
2496         Float_t valueBeforeSOR = 0;
2497         Float_t valueAfterEOR = 0;
2498         Int_t timestampBeforeSOR = -1;
2499         Int_t timestampAfterEOR = -1;
2500         Int_t ientrySOR = -1;
2501         Int_t ientryEOR = -1;
2502         Float_t* arrayValues = 0x0; 
2503         Double_t* arrayWeights = 0x0; 
2504         Int_t iCountsRun = 0;
2505         Int_t nCounts = array->GetEntries();
2506
2507         for(Int_t i = 0; i < nCounts; i++) {
2508                 AliDCSValue* v = (AliDCSValue *)array->At(i);
2509                 if ((v->GetUInt() < fminUInt) || (v->GetUInt() > fmaxUInt)) {
2510                         AliError(Form("Error! UInt value found in DCS map at %d-th entry is OUT OF RANGE: value = %u",i,v->GetUInt()));
2511                         return AliGRPObject::GetInvalidFloat();
2512                 }
2513                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
2514                         AliDebug(2,Form("%d-th entry = %d at timestamp %i",i,v->GetUInt(),v->GetTimeStamp()));
2515                         iCounts += 1;
2516                         // look for the last value before SOR and the first value before EOR
2517                         if (((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) && (Int_t)(v->GetTimeStamp()) < timeStart) {
2518                                 timestampBeforeSOR = (Int_t)(v->GetTimeStamp());
2519                                 AliDebug(2,Form("timestamp of last entry before SOR = %d, with DAQ_time_start = %d",timestampBeforeSOR,timeStart));
2520                                 valueBeforeSOR = (Float_t)v->GetUInt();
2521                         }
2522                         else if ((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery() && (Int_t)(v->GetTimeStamp()) > timeEnd && timestampAfterEOR == -1){
2523                                 timestampAfterEOR = (Int_t)(v->GetTimeStamp());
2524                                 valueAfterEOR = (Float_t)v->GetUInt();
2525                                 AliDebug(2,Form("timestamp of first entry after EOR = %d, with DAQ_time_end = %d",timestampAfterEOR,timeEnd));
2526                         }
2527                         // check if there are DPs between DAQ_time_start and DAQ_time_end
2528                         if(((Int_t)(v->GetTimeStamp()) >= timeStart) &&((Int_t)(v->GetTimeStamp()) <= timeEnd)) {
2529                                 if (ientrySOR == -1) ientrySOR = i;  // first entry after SOR
2530                                 if (ientryEOR < i) ientryEOR = i;  // last entry before EOR
2531                                 AliDebug(2,Form("entry between SOR and EOR"));
2532                                 iCountsRun += 1;
2533                         }
2534                 }
2535                 else {
2536                         AliError(Form("DCS values for the parameter outside the queried interval: timestamp = %d",v->GetTimeStamp()));
2537                 }
2538         }
2539
2540         if (timestampBeforeSOR == -1){
2541                 AliWarning("No value found before SOR!");
2542         }
2543         if (timestampAfterEOR == -1){
2544                 AliWarning("No value found after EOR!");
2545         }
2546
2547         AliDebug(2,Form("Number of valid entries (within query interval) = %i, starting from %i entries",iCounts,nCounts));
2548         AliDebug(2,Form("Last value before DAQ_time_start (SOR) = %f at timestamp = %d",valueBeforeSOR,timestampBeforeSOR));
2549         AliDebug(2,Form("First value after DAQ_time_end (EOR)   = %f at timestamp = %d",valueAfterEOR,timestampAfterEOR));
2550         AliInfo(Form("Found %d entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)",iCountsRun));
2551         AliDebug(2,Form("Index of first entry after DAQ_time_start (SOR) = %d ",ientrySOR));
2552         AliDebug(2,Form("Index of first entry before DAQ_time_end (EOR) = %d ",ientryEOR));
2553
2554         Int_t nentriesUsed = 0;
2555         if (iCountsRun > 1){
2556                 AliInfo("Using entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)");
2557                 AliDebug(2,"Calculating (weighted) Mean");
2558                 arrayValues = new Float_t[iCountsRun]; 
2559                 arrayWeights = new Double_t[iCountsRun]; 
2560                 nentriesUsed = iCountsRun;
2561                 for (Int_t i = ientrySOR; i <= ientryEOR; i++){
2562                         AliDCSValue *v = (AliDCSValue *)array->At(i);
2563                         Int_t timestamp2 = 0;
2564                         if (i < ientryEOR){
2565                                 AliDCSValue *v1 = (AliDCSValue *)array->At(i+1);
2566                                 timestamp2 = (Int_t)v1->GetTimeStamp();
2567                         }
2568                         else {
2569                                 timestamp2 = timeEnd+1;
2570                         }
2571                         arrayWeights[i-ientrySOR] = (Double_t)(timestamp2 - (Int_t)v->GetTimeStamp());
2572                         arrayValues[i-ientrySOR] = (Float_t)v->GetUInt();
2573                 }
2574                 aDCSArrayMean = TMath::Mean(iCountsRun,arrayValues,arrayWeights);
2575                 delete [] arrayValues;
2576                 delete [] arrayWeights;
2577         }
2578         else if (iCountsRun == 1){
2579                 AliDCSValue* v = (AliDCSValue *)array->At(ientrySOR);
2580                 nentriesUsed = 2;
2581                 if (timestampBeforeSOR != -1 && timestampBeforeSOR != (Int_t)v->GetTimeStamp()){
2582                         AliWarning("Using single entry between DAQ_time_start (SOR) and DAQ_time_end (EOR) and last entry before SOR.");
2583                         arrayValues = new Float_t[2];
2584                         arrayWeights = new Double_t[2];
2585                         arrayValues[0] = valueBeforeSOR;
2586                         arrayWeights[0] = (Double_t)((Int_t)v->GetTimeStamp()-timestampBeforeSOR);
2587                         arrayValues[1] = (Float_t)v->GetUInt();
2588                         arrayWeights[1] = (Double_t)(timeEnd+1-(Int_t)v->GetTimeStamp());
2589                         AliDebug(2,Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
2590                         AliDebug(2,Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
2591                         aDCSArrayMean = TMath::Mean(2,arrayValues,arrayWeights);
2592                         delete [] arrayValues;
2593                         delete [] arrayWeights;
2594                 }
2595                 else{
2596                         AliError("Cannot calculate mean - only one value collected during the run, but no value before with which to calculate the statistical quantities");
2597                         return AliGRPObject::GetInvalidFloat();
2598                 }
2599         }
2600         else { // iCountsRun == 0, using the point immediately before SOR and the one immediately after EOR
2601                 if (timestampBeforeSOR == -1 || timestampAfterEOR == -1){
2602                         if (timestampBeforeSOR == -1){
2603                                 AliError("Cannot calculate mean - no points during the run collected, and point before SOR missing");
2604                         }
2605                         if (timestampAfterEOR == -1){
2606                                 AliError("Cannot calculate maen - no points during the run collected, and point after EOR missing");
2607                         }
2608                         return AliGRPObject::GetInvalidFloat();
2609                 }
2610                 else {
2611                         AliWarning("Using last entry before SOR and first entry after EOR.");
2612                         nentriesUsed = 2;
2613                         arrayValues = new Float_t[2];
2614                         arrayWeights = new Double_t[2];
2615                         arrayValues[0] = valueBeforeSOR;
2616                         arrayWeights[0] = (Double_t)(timestampAfterEOR - timestampBeforeSOR);
2617                         arrayValues[1] = valueAfterEOR;
2618                         arrayWeights[1] = 1.;
2619                         AliDebug(2,Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
2620                         AliDebug(2,Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
2621                         aDCSArrayMean = TMath::Mean(1,arrayValues,arrayWeights);
2622                         delete [] arrayValues;
2623                         delete [] arrayWeights;
2624                 }
2625         }
2626
2627         AliInfo(Form("mean = %f ",aDCSArrayMean));
2628         return aDCSArrayMean;
2629
2630 }
2631
2632
2633 //_______________________________________________________________
2634
2635 AliDCSSensorArray *AliGRPPreprocessor::GetPressureMap(TMap* dcsAliasMap)
2636 {
2637         // extract DCS pressure maps. Perform fits to save space
2638         
2639         TMap *map = fPressure->ExtractDCS(dcsAliasMap);
2640         if (map) {
2641                 AliDebug(2,Form("Map has %d entries",map->GetEntries()));
2642                 fPressure->MakeSplineFit(map);
2643                 Double_t fitFraction = fPressure->NumFits()/fPressure->NumSensors(); 
2644                 if (fitFraction > kFitFraction ) {
2645                         AliInfo(Form("Pressure values extracted, %d fits performed for %d sensors.", fPressure->NumFits(),fPressure->NumSensors()));
2646                 } else { 
2647                         AliInfo("Too few pressure maps fitted!!!");
2648                 }
2649         } else {
2650                 AliInfo("no atmospheric pressure map extracted!!!");
2651         }
2652         delete map;
2653         
2654         return fPressure;
2655 }
2656
2657
2658   
2659 //_______________________________________________________________
2660 Int_t AliGRPPreprocessor::ReceivePromptRecoParameters(UInt_t run, const char* dbHost, Int_t dbPort, const char* dbName, const char* user, const char* password, const char *cdbRoot, TString &gdc)
2661 {
2662         //
2663         // Retrieves logbook and trigger information from the online logbook
2664         // This information is needed for prompt reconstruction
2665         //
2666         // Parameters are:
2667         // Run number
2668         // DAQ params: dbHost, dbPort, dbName, user, password, logbookTable, triggerTable
2669         // cdbRoot
2670         //
2671         // returns:
2672         //         positive on success: the return code is the run number of last run processed of the same run type already processed by the SHUTTLE
2673         //         0 on success and no run was found
2674         //         negative on error
2675         //
2676         // This function is NOT called during the preprocessor run in the Shuttle!
2677         //
2678         
2679         // defaults
2680         if (dbPort == 0)
2681                 dbPort = 3306;
2682         
2683         // CDB connection
2684         AliCDBManager* cdb = AliCDBManager::Instance();
2685         cdb->SetDefaultStorage(cdbRoot);
2686         
2687         // SQL connection
2688         TSQLServer* server = TSQLServer::Connect(Form("mysql://%s:%d/%s", dbHost, dbPort, dbName), user, password);
2689         
2690         if (!server)
2691                 {
2692                         Printf("ERROR: Could not connect to DAQ LB");
2693                         return -1;
2694                 }
2695         
2696         // main logbook
2697         TString sqlQuery;
2698         sqlQuery.Form("SELECT DAQ_time_start, run_type, detectorMask, L3_magnetCurrent, Dipole_magnetCurrent,beamType FROM logbook WHERE run = %d", run);
2699         TSQLResult* result = server->Query(sqlQuery);
2700         if (!result)
2701                 {
2702                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
2703                         return -2;
2704                 }
2705         
2706         if (result->GetRowCount() == 0)
2707                 {
2708                         Printf("ERROR: Run %d not found", run);
2709                         delete result;
2710                         return -3;
2711                 }
2712         
2713         TSQLRow* row = result->Next();
2714         if (!row)
2715                 {
2716                         Printf("ERROR: Could not receive data from run %d", run);
2717                         delete result;
2718                         return -4;
2719                 }
2720         
2721         TString timeStartString(row->GetField(0));
2722         TString runType(row->GetField(1));
2723         TString detectorMaskString(row->GetField(2));
2724         TString l3CurrentString(row->GetField(3));
2725         TString dipoleCurrentString(row->GetField(4));
2726         TString beamTypeString(row->GetField(5));
2727         time_t timeStart = (time_t)(timeStartString.Atoi());
2728         UInt_t detectorMask = (UInt_t)(detectorMaskString.Atoi());
2729         Float_t l3Current = (Float_t)(TMath::Abs(l3CurrentString.Atof()));
2730         Float_t dipoleCurrent = (Float_t)(TMath::Abs(dipoleCurrentString.Atof()));
2731         Char_t l3Polarity = (l3CurrentString.Atof() < 0) ? 1 : 0;
2732         Char_t dipolePolarity = (dipoleCurrentString.Atof() < 0) ? 1 : 0;
2733         if (beamTypeString.CompareTo("Pb-Pb",TString::kIgnoreCase) == 0){
2734                 beamTypeString="A-A";
2735         }
2736         
2737         AliGRPObject * grpObj = new AliGRPObject();
2738         grpObj->SetTimeStart(timeStart); 
2739         grpObj->SetRunType((TString)(row->GetField(1)));
2740         grpObj->SetDetectorMask(detectorMask);
2741         grpObj->SetL3Current(l3Current,(AliGRPObject::Stats)0);
2742         grpObj->SetDipoleCurrent(dipoleCurrent,(AliGRPObject::Stats)0);
2743         grpObj->SetL3Polarity(l3Polarity);
2744         grpObj->SetDipolePolarity(dipolePolarity);
2745         grpObj->SetPolarityConventionLHC();  // after the dipole cables swap we comply with LHC convention
2746         grpObj->SetBeamType(beamTypeString);
2747
2748         delete row;
2749         row = 0;
2750         
2751         delete result;
2752         result = 0;
2753         
2754         Printf("Storing GRP/GRP/Data object with the following content");
2755         grpObj->Dump();
2756         
2757         AliCDBMetaData metadata;
2758         metadata.SetResponsible("Jan Fiete Grosse-Oetringhaus & Chiara Zampolli");
2759         metadata.SetComment("GRP Output parameters received during online running");
2760         
2761         AliCDBId id("GRP/GRP/Data", run, run);
2762         Bool_t success = cdb->Put(grpObj, id, &metadata);
2763         
2764         delete grpObj;
2765         
2766         if (!success)
2767                 {
2768                         Printf("ERROR: Could not store GRP/GRP/Data into OCDB");
2769                         return -5;
2770                 }
2771         
2772         // Receive trigger information
2773         sqlQuery.Form("SELECT configFile FROM logbook_trigger_config WHERE run = %d", run);
2774         result = server->Query(sqlQuery);
2775         if (!result)
2776                 {
2777                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
2778                         return -11;
2779                 }
2780         
2781         if (result->GetRowCount() == 0)
2782                 {
2783                         Printf("ERROR: Run %d not found in logbook_trigger_config", run);
2784                         delete result;
2785                         return -12;
2786                 }
2787         
2788         row = result->Next();
2789         if (!row)
2790                 {
2791                         Printf("ERROR: Could not receive logbook_trigger_config data from run %d", run);
2792                         delete result;
2793                         return -13;
2794                 }
2795         
2796         TString triggerConfig(row->GetField(0));
2797         
2798         delete row;
2799         row = 0;
2800         
2801         delete result;
2802         result = 0;
2803         
2804         Printf("Found trigger configuration: %s", triggerConfig.Data());
2805         
2806         AliTriggerConfiguration *runcfg = AliTriggerConfiguration::LoadConfigurationFromString(triggerConfig);
2807         if (!runcfg)
2808                 {
2809                         Printf("ERROR: Could not create CTP configuration object");
2810                         return -14;
2811                 }
2812         
2813         metadata.SetComment("CTP run configuration received during online running");
2814         
2815         AliCDBId id2("GRP/CTP/Config", run, run);
2816         success = cdb->Put(runcfg, id2, &metadata);
2817         
2818         delete runcfg;
2819         runcfg = 0;
2820         
2821         if (!success)
2822                 {
2823                         Printf("ERROR: Could not store GRP/CTP/Config into OCDB");
2824                         return -15;
2825                 }
2826         
2827
2828         // Receive list of GDCs for this run
2829         sqlQuery.Form("SELECT GDC FROM logbook_stats_GDC WHERE run = %d", run);
2830         result = server->Query(sqlQuery);
2831         if (!result)
2832                 {
2833                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
2834                         return -24;
2835                 }
2836         
2837         if (result->GetRowCount() == 0)
2838                 {
2839                         Printf("ERROR: Run %d not found in logbook_stats_GDC", run);
2840                         delete result;
2841                         return -25;
2842                 }
2843
2844         gdc = "";
2845         for (Int_t iGDC = 0; iGDC < result->GetRowCount(); iGDC++) {
2846           row = result->Next();
2847           if (!row)
2848             {
2849               Printf("ERROR: Could not receive logbook_stats_GDC data from run %d", run);
2850               delete result;
2851               return -26;
2852             }
2853           gdc += row->GetField(0);
2854           gdc += " ";
2855         }
2856
2857         delete row;
2858         row = 0;
2859         
2860         delete result;
2861         result = 0;
2862         
2863         Printf("Found GDC: %s", gdc.Data());
2864
2865         // get last run with same run type that was already processed by the SHUTTLE
2866         
2867         sqlQuery.Form("SELECT max(logbook.run) FROM logbook LEFT JOIN logbook_shuttle ON logbook_shuttle.run = logbook.run WHERE run_type = '%s' AND shuttle_done = 1", runType.Data());
2868         result = server->Query(sqlQuery);
2869         if (!result)
2870                 {
2871                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
2872                         return -21;
2873                 }
2874         
2875         if (result->GetRowCount() == 0)
2876                 {
2877                         Printf("ERROR: No result with query <%s>", sqlQuery.Data());
2878                         delete result;
2879                         return -22;
2880                 }
2881         
2882         row = result->Next();
2883         if (!row)
2884                 {
2885                         Printf("ERROR: Could not receive data for query <%s>", sqlQuery.Data());
2886                         delete result;
2887                         return -23;
2888                 }
2889         
2890         TString lastRunStr(row->GetField(0));
2891         Int_t lastRun = lastRunStr.Atoi();
2892         
2893         Printf("Last run with same run type %s is %d", runType.Data(), lastRun);
2894         
2895         delete row;
2896         row = 0;
2897         
2898         delete result;
2899         result = 0;
2900         
2901         server->Close();
2902         delete server;
2903         server = 0;
2904         
2905         return lastRun;
2906 }
2907 //------------------------------------------------------------------------------------------------------
2908 Float_t AliGRPPreprocessor::ProcessEnergy(TObjArray* const array, Double_t timeStart){
2909
2910         //
2911         // Method to processo LHC Energy information
2912         // Only the first value is returned, provided that it is withing DAQ_time_start and DAQ_time_end
2913         //
2914
2915         Int_t nCounts = array->GetEntries();
2916         Float_t energy = -1;
2917         Double_t timeEnergy = -1;
2918         Int_t indexEnergy = -1;
2919         Bool_t foundEnergy = kFALSE;
2920
2921         AliDebug(2,Form("Energy measurements = %d\n",nCounts));
2922         if (nCounts ==0){
2923                 AliWarning("No Energy values found! Beam Energy remaining invalid!");
2924         }
2925         else{
2926                 for (Int_t i = 0; i < nCounts; i++){
2927                         AliDCSArray *dcs = (AliDCSArray*)array->At(i);
2928                         if (dcs){
2929                                 if (dcs->GetTimeStamp()<=timeStart && dcs->GetTimeStamp()>=timeEnergy){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
2930                                         timeEnergy = dcs->GetTimeStamp();
2931                                         indexEnergy = i;
2932                                         foundEnergy = kTRUE;
2933                                 }
2934                                 else{
2935                                         break;
2936                                 }
2937                         }
2938                 }
2939                 if (!foundEnergy){
2940                         AliInfo("No value for the Energy found before start of run, the Energy will remain invalid");
2941                 }
2942                 else {
2943                         AliDCSArray* dcs = (AliDCSArray*)array->At(indexEnergy);
2944                         energy = (Float_t)(TMath::Nint(((Double_t)(dcs->GetInt(0)))*120/1000)); // sqrt(s)/2 energy in GeV
2945                         AliInfo(Form("Energy value found = %d (at %f), converting --> sqrt(s)/2 = %f (GeV)", dcs->GetInt(0),dcs->GetTimeStamp(),energy));
2946                 }
2947         }
2948
2949         return energy;
2950 }
2951 //------------------------------------------------------------------------------------------------------
2952 AliLHCClockPhase* AliGRPPreprocessor::ProcessLHCClockPhase(TObjArray *beam1phase,TObjArray *beam2phase, Double_t timeEnd)
2953 {
2954   //
2955   // Method to process LHC-Clock Phase data
2956   // Only the values between DAQ_time_start and DAQ_time_end are kept
2957   //
2958   AliLHCClockPhase *phaseObj = new AliLHCClockPhase;
2959
2960   Bool_t foundBeam1Phase = kFALSE, foundBeam2Phase = kFALSE;
2961   const Float_t threshold = 0.050; // we store the measurement only in case they differ with more 50ps from the previous one 
2962
2963   TString timeCreatedStr = GetRunParameter("time_created");
2964   Double_t timeCreated = timeCreatedStr.Atof();
2965
2966   Int_t nCounts = beam1phase->GetEntries();
2967   AliDebug(2,Form("Beam1 phase measurements = %d\n",nCounts));
2968   if (nCounts ==0){
2969     AliWarning("No beam1 LHC clock phase values found!");
2970     delete phaseObj;
2971     return NULL;
2972   }
2973   else{
2974     Double_t prevPhase = 0;
2975     for (Int_t i = 0; i < nCounts; i++){
2976       AliDCSArray *dcs = (AliDCSArray*)beam1phase->At(i);
2977       if (dcs){
2978               //if (dcs->GetTimeStamp()>=timeStart && dcs->GetTimeStamp()<=timeEnd) {
2979               if (dcs->GetTimeStamp()>=timeCreated && dcs->GetTimeStamp()<=timeEnd) {
2980           if ((i == 0) || (i == (nCounts-1)) ||
2981               !foundBeam1Phase ||
2982               (TMath::Abs(dcs->GetDouble(0)-prevPhase) > threshold)) {
2983             prevPhase = dcs->GetDouble(0);
2984             foundBeam1Phase = kTRUE;
2985             AliInfo(Form("B1 Clk Phase = %f at TS = %f",
2986                          (Float_t)dcs->GetDouble(0),dcs->GetTimeStamp()));  
2987             phaseObj->AddPhaseB1DP((UInt_t)dcs->GetTimeStamp(),(Float_t)dcs->GetDouble(0));
2988           }
2989         }
2990       }
2991     }
2992     if (!foundBeam1Phase){
2993       AliError("No beam1 LHC clock phase values found within the run!");
2994       delete phaseObj;
2995       return NULL;
2996     }
2997   }
2998
2999   nCounts = beam2phase->GetEntries();
3000   AliDebug(2,Form("Beam2 phase measurements = %d\n",nCounts));
3001   if (nCounts ==0){
3002     AliWarning("No beam2 LHC clock phase values found!");
3003     delete phaseObj;
3004     return NULL;
3005   }
3006   else{
3007     Double_t prevPhase = 0;
3008     for (Int_t i = 0; i < nCounts; i++){
3009       AliDCSArray *dcs = (AliDCSArray*)beam2phase->At(i);
3010       if (dcs){
3011         if (dcs->GetTimeStamp()>=timeCreated && dcs->GetTimeStamp()<=timeEnd) {
3012           if ((i == 0) || (i == (nCounts-1)) ||
3013               !foundBeam2Phase ||
3014               (TMath::Abs(dcs->GetDouble(0)-prevPhase) > threshold)) {
3015             prevPhase = dcs->GetDouble(0);
3016             foundBeam2Phase = kTRUE;
3017             AliInfo(Form("B2 Clk Phase = %f at TS = %f",
3018                          (Float_t)dcs->GetDouble(0),dcs->GetTimeStamp()));  
3019             phaseObj->AddPhaseB2DP((UInt_t)dcs->GetTimeStamp(),(Float_t)dcs->GetDouble(0));
3020           }
3021         }
3022       }
3023     }
3024     if (!foundBeam2Phase){
3025       AliError("No beam2 LHC clock phase values found within the run!");
3026       delete phaseObj;
3027       return NULL;
3028     }
3029   }
3030
3031   return phaseObj;
3032 }