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