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