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