]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliGRPPreprocessor.cxx
Transient pointer of ESDtrack back to the event introduced.
[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 if (iLHCData ==4){
516                 Log(Form("Problems with LHC Data to be put in /GRP/GRP/LHCData - but not going into Error"));
517         } else{
518                 Log(Form("LHC Data problems"));
519                 error |= 512;
520         }
521         
522         //==================//
523         // SPD Mean Vertex  //
524         //==================//
525         if (runType == "PHYSICS"){
526                 UInt_t iSPDMeanVertex = ProcessSPDMeanVertex();
527                 if( iSPDMeanVertex == 1 ) {
528                         Log(Form("SPD Mean Vertex, successful!"));
529                 } else {
530                         Log(Form("SPD Mean Vertex failed!!!"));
531                         error |= 128; 
532                 }
533         }
534         else {
535                 Log("SPD Mean Vertex not processed since runType != PHYSICS");
536         }
537
538         // storing AliGRPObject in OCDB
539
540         AliCDBMetaData md;
541         md.SetResponsible("Chiara Zampolli");
542         md.SetComment("Output parameters from the GRP preprocessor.");
543         
544         Bool_t result = kTRUE;
545         result = Store("GRP", "Data", grpobj, &md); 
546         delete grpobj;
547
548         if (result && !error ) {
549                 Log("GRP Preprocessor Success");
550                 return 0;
551         } else {
552                 Log( Form("GRP Preprocessor FAILS!!! %s%s%s%s%s%s%s%s%s%s",
553                           kppError[(error&1)?1:0],
554                           kppError[(error&2)?2:0],
555                           kppError[(error&4)?3:0],
556                           kppError[(error&8)?4:0],
557                           kppError[(error&16)?5:0],
558                           kppError[(error&32)?6:0],
559                           kppError[(error&64)?7:0],
560                           kppError[(error&128)?8:0],
561                           kppError[(error&256)?9:0],
562                           kppError[(error&512)?10:0]
563                           ));
564                 return error;
565         }
566
567
568 }
569
570 //_______________________________________________________________
571
572 UInt_t AliGRPPreprocessor::ProcessLHCData(AliGRPObject *grpobj)
573 {
574         //
575         //Getting the LHC Data from DCS FXS
576         //
577
578         TString timeStartString = (TString)GetRunParameter("DAQ_time_start");
579         TString timeEndString = (TString)GetRunParameter("DAQ_time_end");
580         if (timeStartString.IsNull() || timeStartString.IsNull()){
581                 if (timeStartString.IsNull()){ 
582                         AliError("DAQ_time_start not set in logbook! Setting statistical values for current DP to invalid");
583                 }
584                 else if (timeStartString.IsNull()){
585                         AliError("DAQ_time_end not set in logbook! Setting statistical values for current DP to invalid");
586                 }
587                 return 2;
588         }  
589
590         Double_t timeStart = timeStartString.Atof();
591         Double_t timeEnd = timeEndString.Atof();
592
593         //      timeStart = 1260646960;
594         //timeEnd = 1260652740;
595
596         TString fileName = GetFile(kDCS, "LHCData","");
597         if (fileName.Length()>0){
598                 AliInfo("Got The LHC Data file");
599                 AliLHCReader* lhcReader = new AliLHCReader();
600                 TMap* lhcMap = (TMap*)lhcReader->ReadLHCDP(fileName.Data());
601                 if (lhcMap) {
602                         Log(Form("LHCData map entries = %d",lhcMap->GetEntries()));
603                         
604                         // Processing data to be put in AliGRPObject
605                         // Energy
606                         TObjArray* energyArray = (TObjArray*)lhcMap->GetValue(fgkLHCDataPoints[0]);
607                         Float_t energy = ProcessEnergy(energyArray,timeStart,timeEnd);
608                         if (energy != -1) {
609                                 grpobj->SetBeamEnergy(energy);
610                                 grpobj->SetBeamEnergyIsSqrtSHalfGeV(kTRUE);
611                         }
612                         
613                         // BeamMode
614                         TObjArray* beamModeArray = (TObjArray*)lhcMap->GetValue(fgkLHCDataPoints[2]);
615                         AliDCSArray* beamMode = (AliDCSArray*)beamModeArray->At(0);
616                         TObjString* beamModeString = beamMode->GetStringArray(0);
617                         Double_t timeBeamMode = 0;
618                         if (beamModeArray->GetEntries()!=1){
619                                 timeBeamMode = beamMode->GetTimeStamp();
620                                 AliWarning(Form("The beam mode changed at timestamp %f! Setting it to the first value found and setting MaxTimeLHCValidity",timeBeamMode));
621                         }
622                         AliInfo(Form("LHC State (corresponding to BeamMode) = %s",(beamModeString->String()).Data()));
623                         grpobj->SetLHCState(beamModeString->String());
624                         
625                         // MachineMode
626                         TObjArray* machineModeArray = (TObjArray*)lhcMap->GetValue(fgkLHCDataPoints[1]);
627                         AliDCSArray* machineMode = (AliDCSArray*)machineModeArray->At(0);
628                         TObjString* machineModeString = machineMode->GetStringArray(0);
629                         Double_t timeMachineMode = 0;
630                         if (machineModeArray->GetEntries()!=1){
631                                 timeMachineMode = machineMode->GetTimeStamp();
632                                 AliWarning(Form("The machine mode changed at timestamp %f! Setting it to the first value found and setting MaxTimeLHCValidity",timeMachineMode));
633                         }
634                         AliInfo(Form("Machine Mode = %s",(machineModeString->String()).Data()));
635                         grpobj->SetMachineMode(machineModeString->String());
636                         
637                         if (timeBeamMode!=0 || timeMachineMode!=0){
638                                 Double_t minTimeLHCValidity;
639                                 if (timeBeamMode == 0){
640                                         minTimeLHCValidity = timeMachineMode;
641                                 }
642                                 else if (timeMachineMode == 0){
643                                         minTimeLHCValidity = timeBeamMode;
644                                 }
645                                 else {
646                                         minTimeLHCValidity= TMath::Min(timeBeamMode,timeMachineMode);
647                                 }
648                                 AliWarning(Form("Setting MaxTimeLHCValidity to %f",minTimeLHCValidity));
649                                 grpobj->SetMaxTimeLHCValidity(minTimeLHCValidity);
650                         }
651                         
652                         // BeamType1 and BeamType2 
653                         TObjArray* beam1Array = (TObjArray*)lhcMap->GetValue(fgkLHCDataPoints[3]);
654                         AliInfo(Form("%d entries for Beam1",beam1Array->GetEntries()));
655                         TObjArray* beam2Array = (TObjArray*)lhcMap->GetValue(fgkLHCDataPoints[4]);
656                         AliInfo(Form("%d entries for Beam2",beam2Array->GetEntries()));
657                         
658                         // Processing data to go to AliLHCData object
659                         AliLHCData* dt = new AliLHCData(lhcMap,timeStart,timeEnd);
660                                                         
661                         // storing AliLHCData in OCDB
662                         if (dt){                        
663                                 AliCDBMetaData md;
664                                 md.SetResponsible("Ruben Shahoyan");
665                                 md.SetComment("LHC data from the GRP preprocessor.");
666                                 
667                                 Bool_t result = kTRUE;
668                                 result = Store("GRP", "LHCData", dt, &md); 
669                                 delete dt;
670                                 if (result) return 0;
671                                 else return 3;
672                         }
673                         else return 4;
674                 }
675                 else {
676                         AliError("Cannot read correctly LHCData file");
677                         return 2;
678                 }
679         }
680   
681         else {
682                 AliError("No LHCData file found in DCS FXS");
683                 return 1;
684         }
685
686 }
687
688 //_______________________________________________________________
689
690 UInt_t AliGRPPreprocessor::ProcessSPDMeanVertex()
691 {
692         //
693         //Getting the SPD Mean Vertex
694         //
695
696         TList* list = GetForeignFileSources("SPD", kDAQ, "VertexDiamond");
697         Bool_t storeResult = kTRUE;
698         if (list !=0x0 && list->GetEntries()!=0)
699                 {
700                         AliInfo("The following sources produced files with the id VertexDiamond from SPD");
701                         list->Print();
702                         for (Int_t jj=0;jj<list->GetEntries();jj++){
703                                 TObjString * str = dynamic_cast<TObjString*> (list->At(jj));
704                                 AliInfo(Form("found source %s", str->String().Data()));
705                                 TString fileNameRun = GetForeignFile("SPD", kDAQ, "VertexDiamond", str->GetName());
706                                 if (fileNameRun.Length()>0){
707                                         AliInfo(Form("Got the file %s", fileNameRun.Data()));
708                                         TFile daqFile(fileNameRun.Data(),"READ");
709                                         if (daqFile.IsOpen()) {
710                                                 AliESDVertex* meanVtx = dynamic_cast<AliESDVertex*>(daqFile.Get("MeanVertexPos"));
711                                                 if (meanVtx){
712                                                         meanVtx->Print();       
713                                                         // storing in the OCDB 
714                                                         AliCDBMetaData md;
715                                                         md.SetResponsible("Cvetan Cheshkov");
716                                                         md.SetComment("SPD Mean Vertex");                                       
717                                                         storeResult = Store("GRP", "MeanVertexSPD", meanVtx, &md, 0, kTRUE); 
718                                                 }
719                                                 else{
720                                                         AliWarning("No SPD Mean Vertex object found in file");
721                                                 } 
722                                         }
723                                         else {
724                                                 AliError("Can't open file");
725                                                 storeResult = kFALSE;
726                                         }
727                                 }
728                                 else{
729                                         AliWarning("No file found for current source for SPD Mean Vertex");
730                                 }
731                         }
732                 }
733         else {
734                 AliWarning("No list found for SPD Mean Vertex");
735         }
736
737         if (list) delete list;
738
739         return storeResult;
740 }
741
742
743 //_______________________________________________________________
744
745 Int_t AliGRPPreprocessor::ProcessDaqLB(AliGRPObject* grpObj)
746 {
747         //Getting the DAQ lb information
748         
749         time_t timeStart = (time_t)(((TString)GetRunParameter("DAQ_time_start")).Atoi());
750         time_t timeEnd = (time_t)(((TString)GetRunParameter("DAQ_time_end")).Atoi());
751         Float_t beamEnergy = (Float_t)(((TString)GetRunParameter("beamEnergy")).Atof());
752         TString beamType = (TString)GetRunParameter("beamType");
753         Char_t numberOfDetectors = (Char_t)(((TString)GetRunParameter("numberOfDetectors")).Atoi());
754         UInt_t  detectorMask = (UInt_t)(((TString)GetRunParameter("detectorMask")).Atoi());
755         TString lhcPeriod = (TString)GetRunParameter("LHCperiod");
756         TString runType = (TString)GetRunType();
757
758         UInt_t nparameter = 0;
759         if (timeStart != 0){
760                 grpObj->SetTimeStart(timeStart);
761                 Log(Form("Start time for run %d: %d",fRun, (Int_t)timeStart));
762                 nparameter++;
763         } 
764         else {
765                 Log(Form("Start time not put in logbook, setting to invalid in GRP entry!"));
766         }
767
768         if (timeEnd != 0){
769                 grpObj->SetTimeEnd(timeEnd);
770                 Log(Form("End time for run %d: %i",fRun, (Int_t)timeEnd));
771                 nparameter++;
772         } 
773         else {
774                 Log(Form("End time not put in logbook, setting to invalid in GRP entry!"));
775         }
776
777         if (beamEnergy != 0){
778                 grpObj->SetBeamEnergy(beamEnergy);
779                 Log(Form("Beam Energy for run %d: %f",fRun, beamEnergy));
780                 //if ((runType == "PHYSICS" && beamType!="Cosmics")){
781                 if ((runType == "PHYSICS" && !beamType.IsNull())){   // if beamType is NOT Null, then we're not in a Cosmics run
782                         nparameter++; // increasing nparameters only in case we're in PHYSICS runs with beamType != NULL
783                 }
784         } 
785         else {
786                 //if ((runType == "PHYSICS" && beamType!="Cosmics")){
787                 if ((runType == "PHYSICS" && !beamType.IsNull())){ // if beamType is NOT Null, then we're not in a Cosmics run
788                         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()));
789                 }
790                 else{
791                         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()));
792                 }
793         }
794
795                 
796         if (beamType.Length() != 0){
797                 grpObj->SetBeamType(beamType);
798                 Log(Form("Beam Type for run %d: %s",fRun, beamType.Data()));
799                 nparameter++; 
800         } 
801         else {
802                 Log(Form("Beam Type not put in logbook, setting to invalid in GRP entry! Not producing any error, considering this as a Cosmics run"));
803                 nparameter++;
804         }
805                 
806         if (numberOfDetectors != 0){
807                 grpObj->SetNumberOfDetectors(numberOfDetectors);
808                 Log(Form("Number Of Detectors for run %d: %d",fRun, (Int_t)numberOfDetectors));
809                 nparameter++;
810         } 
811         else {
812                 Log(Form("Number Of Detectors not put in logbook, setting to invalid in GRP entry!"));
813         }
814
815         if (detectorMask != 0){
816                 grpObj->SetDetectorMask(detectorMask);
817                 Log(Form("Detector Mask for run %d: %d",fRun, detectorMask));
818                 nparameter++;
819         } 
820         else {
821                 Log(Form("Detector Mask not put in logbook, setting to invalid in GRP entry!"));
822         }
823
824         if (lhcPeriod.Length() != 0) {
825                 grpObj->SetLHCPeriod(lhcPeriod);
826                 Log(Form("LHC period (DAQ) for run %d: %s",fRun, lhcPeriod.Data()));
827                 nparameter++;
828         } 
829         else {
830                 Log(Form("LHCperiod not put in logbook, setting to invalid in GRP entry!"));
831         }
832         if (runType.Length() != 0) {
833                 grpObj->SetRunType(runType);
834                 Log(Form("Run Type (DAQ) for run %d: %s",fRun, runType.Data()));
835                 nparameter++;
836         } 
837         else {
838                 Log(Form("Run Type not put in logbook, setting to invalid in GRP entry!"));
839         }
840
841         return nparameter;
842 }
843
844 //_______________________________________________________________
845
846 UInt_t AliGRPPreprocessor::ProcessDaqFxs()
847 {
848         //======DAQ FXS======//
849         
850         AliRawEventHeaderV3_9::Class()->IgnoreTObjectStreamer(); // to avoid trying reading TObject store in AliRawEventHeaderV3_9 - temporary fix 
851         TList* list = GetFileSources(kDAQ);  
852         if (!list) {
853                 Log("No raw data tag list: connection problems with DAQ FXS logbook!");
854                 return 1;
855         }
856         
857         if (list->GetEntries() == 0) {
858                 Log("no raw data tags in this run: nothing to merge!");
859                 delete  list; list=0;
860                 return 0;
861         }
862         
863         TChain *fRawTagChain = new TChain("T");
864         Int_t nFiles=0;
865         TIterator* iter = list->MakeIterator();
866         TObject* obj = 0;
867         while ((obj = iter->Next())) {
868                 TObjString* objStr = dynamic_cast<TObjString*> (obj);
869                 if (objStr) {
870                         Log(Form("Found source %s", objStr->String().Data()));
871                         TList* list2 = GetFileIDs(kDAQ, objStr->String());
872                         if (!list2) {
873                                 Log("No list with ids from DAQ was found: connection problems with DAQ FXS logbook!");
874                                 delete fRawTagChain; fRawTagChain=0;
875                                 return 1;
876                         }
877                         Log(Form("Number of ids: %d",list2->GetEntries()));
878                         for(Int_t i = 0; i < list2->GetEntries(); i++) {
879                                 TObjString *idStr = (TObjString *)list2->At(i);
880                                 TString fileName = GetFile(kDAQ,idStr->String().Data(),objStr->String().Data());
881                                 if (fileName.Length() > 0) {
882                                         Log(Form("Adding file in the chain: %s",fileName.Data()));
883                                         fRawTagChain->Add(fileName.Data());
884                                         nFiles++;
885                                 } else {
886                                         Log(Form("Could not retrieve file with id %s from source %s: "
887                                                  "connection problems with DAQ FXS!",
888                                                  idStr->String().Data(), objStr->String().Data()));
889                                         delete list; list=0;
890                                         delete list2; list2=0;
891                                         delete fRawTagChain; fRawTagChain=0;
892                                         return 2;
893                                 }
894                         }
895                         delete list2;
896                 }
897         }
898         
899         TString fRawDataFileName = "GRP_Merged.tag.root";
900         Log(Form("Merging %d raw data tags into file: %s", nFiles, fRawDataFileName.Data()));
901         
902         if( fRawTagChain->Merge(fRawDataFileName) < 1 ) {
903                 Log("Error merging raw data files!!!");
904                 return 3;
905         }
906         
907         TString outputfile = Form("Run%d.Merged.RAW.tag.root", fRun);
908         Bool_t result = StoreRunMetadataFile(fRawDataFileName.Data(),outputfile.Data());
909         
910         if (!result) {
911                 Log("Problem storing raw data tags in local file!!!");
912         } else {
913                 Log("Raw data tags merged successfully!!");
914         }
915         
916         delete iter;
917         delete list;
918         delete fRawTagChain; fRawTagChain=0;
919         
920         if (result == kFALSE) {
921                 return 4;
922         }
923         
924         return 0;
925         
926 }
927
928 //_______________________________________________________________
929 UInt_t AliGRPPreprocessor::ProcessDcsFxs(TString partition, TString detector)
930 {
931
932         // processing the info
933         // stored in the DCS FXS
934         // coming from the trigger
935
936         // Get the CTP counters information
937
938         if (partition.IsNull() && !detector.IsNull()){ // standalone partition
939                 Log("STANDALONE partition for current run, using Trigger Scalers dummy value");
940                 AliCDBEntry *cdbEntry = GetFromOCDB("CTP","DummyScalers");
941                 if (!cdbEntry) {
942                         Log(Form("No dummy CTP scalers entry found, going into error..."));
943                         return 1;
944                 }
945                 else{
946                         AliTriggerRunScalers *scalers = (AliTriggerRunScalers*)cdbEntry->GetObject();
947                         if (!scalers){
948                                 Log(Form("CTP dummy scalers not found in OCDB entry, going into error..."));
949                                 return 1;
950                         }
951                         else {
952                                 AliCDBMetaData metaData;
953                                 metaData.SetResponsible("Roman Lietava");
954                                 metaData.SetComment("CTP scalers from dummy entry in OCDB");
955                                 if (!Store("CTP","Scalers", scalers, &metaData, 0, 0)) {
956                                         Log("Unable to store the dummy CTP scalers object to OCDB!");
957                                         return 1;
958                                 }
959                         }
960                 }
961         }
962
963         else if (!partition.IsNull() && detector.IsNull()){ // global partition
964                 Log("GLOBAL partition for current run, using CTP scalers from DCS FXS");
965                 TString countersfile = GetFile(kDCS, "CTP_xcounters","");
966                 if (countersfile.IsNull()) {
967                         Log("No CTP counters files has been found: empty source!");
968                         return 1;
969                 }
970                 else {
971                         Log(Form("File with Id CTP_xcounters found in DCS FXS! Copied to %s",countersfile.Data()));
972                         AliTriggerRunScalers *scalers = AliTriggerRunScalers::ReadScalers(countersfile);
973                         if (!scalers) {
974                                 Log("Bad CTP counters file! The corresponding CDB entry will not be filled!");
975                                 return 1;
976                         }
977                         else {
978                                 AliCDBMetaData metaData;
979                                 metaData.SetBeamPeriod(0);
980                                 metaData.SetResponsible("Roman Lietava");
981                                 metaData.SetComment("CTP scalers");
982                                 if (!Store("CTP","Scalers", scalers, &metaData, 0, 0)) {
983                                         Log("Unable to store the CTP scalers object to OCDB!");
984                                         return 1;
985                                 }
986                         }
987                 }
988         }
989         
990
991         else{   
992                 Log(Form("Incorrect field in DAQ logbook for partition = %s and detector = %s, going into error...",partition.Data(),detector.Data()));
993                 return 2;
994         }
995
996         return 0;
997
998 }
999 //_______________________________________________________________
1000
1001 Int_t AliGRPPreprocessor::ProcessDcsDPs(TMap* valueMap, AliGRPObject* grpObj)
1002 {
1003
1004         //
1005         // processing DCS DPs
1006         //
1007
1008         Int_t entries = 0;  // counting the entries that are in the DCS DB, not taking care whether they have values or not
1009         Int_t nL3Entries = 0;
1010         Int_t nDipoleEntries = 0;
1011         Int_t nEnvEntries = 0;
1012         Int_t nHallProbesEntries = 0;
1013         nL3Entries = ProcessL3DPs(valueMap, grpObj);
1014         nDipoleEntries = ProcessDipoleDPs(valueMap, grpObj);
1015         nEnvEntries = ProcessEnvDPs(valueMap, grpObj);
1016         nHallProbesEntries = ProcessHPDPs(valueMap, grpObj);
1017         grpObj->SetPolarityConventionLHC();  // after the dipole cables swap we comply with LHC convention
1018         Log(Form("L3Entries = %d, nDipoleEntries =%d, nEnvEntries = %d, nHallProbesEntries = %d", nL3Entries, nDipoleEntries, nEnvEntries, nHallProbesEntries));
1019         entries = nL3Entries + nDipoleEntries + nEnvEntries + nHallProbesEntries;
1020         return entries;
1021
1022 }
1023
1024 //_______________________________________________________________
1025
1026 Int_t AliGRPPreprocessor::ProcessL3DPs(const TMap* valueMap, AliGRPObject* grpObj)
1027 {
1028
1029         // processing DPs
1030         // related to 
1031         // L3 info
1032
1033         Int_t nL3Entries = 0;
1034
1035         TObjArray *array = 0x0;
1036         Int_t indexDP = -1;
1037         Bool_t isZero = kTRUE; // flag to monitor L3Current. If set to true, the magnet is OFF, and the polarity can change
1038
1039         AliInfo(Form("==========L3Current==========="));
1040         Bool_t outOfRange = kFALSE;  // flag to monitor if any value collected by DCS is out of range
1041         indexDP = kL3Current;
1042         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1043         if(!array) {
1044                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1045         } 
1046         else {
1047                 if (array->GetEntries() == 0){
1048                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
1049                 }
1050                 else {
1051                         Float_t *floatDCS = ProcessFloatAllMagnet(array, indexDP, isZero);
1052                         if (floatDCS != NULL){
1053                                 grpObj->SetL3Current(floatDCS);
1054                         }
1055                         else{
1056                                 outOfRange = kTRUE;
1057                         }       
1058                         if (floatDCS){
1059                                 delete[] floatDCS;
1060                                 floatDCS = 0x0;
1061                         }
1062                 }
1063                 if (!outOfRange) {
1064                         nL3Entries++;
1065                         ffailedDPs->RemoveAt(indexDP);
1066                 }
1067         }
1068
1069         if (array) array = 0x0;
1070
1071         AliInfo(Form("==========L3Polarity==========="));
1072         indexDP = kL3Polarity;
1073         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1074         if(!array) {
1075                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1076         } 
1077         else {
1078                 if (array->GetEntries() == 0){
1079                         AliError(Form("No entries found in array! setting %s Polarity to invalid...",fgkDCSDataPoints[indexDP]));
1080                 }
1081                 else {
1082                         Bool_t change = kFALSE;
1083                         Char_t charDCS = ProcessBool(array,change);
1084                         if (change == kFALSE){
1085                                 grpObj->SetL3Polarity(charDCS);
1086                                 AliInfo(Form("%s set to %d",fgkDCSDataPoints[indexDP],(Int_t)(grpObj->GetL3Polarity())));
1087                                 ffailedDPs->RemoveAt(indexDP);
1088                                 nL3Entries++;
1089                         }
1090                         else if (isZero){
1091                                 AliInfo(Form("%s set to invalid, but magnet was OFF (according to the current), DP not considered wrong",fgkDCSDataPoints[indexDP]));
1092                                 ffailedDPs->RemoveAt(indexDP);
1093                                 nL3Entries++;
1094                         }
1095                         else {
1096                                 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]));
1097                         }
1098                 }
1099         }
1100
1101         return nL3Entries;
1102
1103 }
1104 //_______________________________________________________________
1105
1106 Int_t AliGRPPreprocessor::ProcessDipoleDPs(const TMap* valueMap, AliGRPObject* grpObj)
1107 {
1108         // processing DPs
1109         // related to 
1110         // the Dipole info
1111
1112         Int_t nDipoleEntries = 0;
1113         TObjArray *array = 0x0;
1114         Int_t indexDP = -1;
1115         Bool_t isZero = kTRUE; // flag to monitor L3Current. If set to true, the magnet is OFF, and the polarity can change
1116
1117         AliInfo(Form("==========DipoleCurrent==========="));
1118         Bool_t outOfRange = kFALSE;  // flag to monitor if any value collected by DCS is out of range
1119         indexDP = kDipoleCurrent;
1120         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1121         if(!array) {
1122                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1123         } 
1124         else {
1125                 if (array->GetEntries() == 0){
1126                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
1127                 }
1128                 else {
1129                         Float_t *floatDCS = ProcessFloatAllMagnet(array, indexDP, isZero);
1130                         if (floatDCS != NULL){
1131                                 grpObj->SetDipoleCurrent(floatDCS);
1132                         } 
1133                         else{
1134                                 outOfRange=kTRUE;
1135                         }
1136                         if (floatDCS){
1137                                 delete[] floatDCS;
1138                                 floatDCS = 0x0;
1139                         }
1140                 }
1141                 if (!outOfRange) {
1142                         nDipoleEntries++;
1143                         ffailedDPs->RemoveAt(indexDP);
1144                 }
1145         }
1146
1147         if (array) array = 0x0;
1148
1149         AliInfo(Form("==========DipolePolarity==========="));
1150         indexDP = kDipolePolarity;
1151         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1152         if(!array) {
1153                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1154         } 
1155         else {
1156                 if (array->GetEntries() == 0){
1157                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
1158                 }
1159                 else {
1160                         Bool_t change = kFALSE;
1161                         Char_t charDCS = ProcessBool(array,change);
1162                         if (!change){
1163                                 grpObj->SetDipolePolarity(charDCS);
1164                                 AliInfo(Form("%s set to %d",fgkDCSDataPoints[indexDP],(Int_t)(grpObj->GetDipolePolarity())));
1165                                 ffailedDPs->RemoveAt(indexDP);
1166                                 nDipoleEntries++;
1167                         }
1168                         else if (isZero){
1169                                 AliInfo(Form("%s set to invalid, but magnet was OFF (according to the current), DP not considered wrong",fgkDCSDataPoints[indexDP]));
1170                                 ffailedDPs->RemoveAt(indexDP);
1171                                 nDipoleEntries++;
1172                         }
1173                         else{
1174                                 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]));
1175                         }
1176                 }
1177         }
1178
1179         return nDipoleEntries;
1180
1181 }
1182 //_______________________________________________________________
1183
1184 Int_t AliGRPPreprocessor::ProcessEnvDPs(TMap* valueMap, AliGRPObject* grpObj)
1185 {
1186         // processing DPs
1187         // related to 
1188         // evironment conditions (temperature, pressure) info
1189
1190         Int_t nEnvEntries = 0;
1191         TObjArray *array = 0x0;
1192         Int_t indexDP = -1;
1193
1194         AliInfo(Form("==========CavernTemperature==========="));
1195         Bool_t outOfRange = kFALSE;  // flag to monitor if any value collected by DCS is out of range
1196         indexDP = kCavernTemperature;
1197         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
1198         if(!array) {
1199                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
1200         } 
1201         else {
1202                 if (array->GetEntries() == 0){
1203                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
1204                 }
1205                 else {
1206                         Float_t *floatDCS = ProcessFloatAll(array);
1207                         if (floatDCS != NULL){
1208                                 grpObj->SetCavernTemperature(floatDCS);
1209                         }
1210                         else{
1211                                 outOfRange = kTRUE;
1212                         }
1213                         if (floatDCS){
1214                                 delete[] floatDCS;
1215                                 floatDCS = 0x0;
1216                         }
1217                 }
1218                 if (!outOfRange) {
1219                         ffailedDPs->RemoveAt(indexDP);
1220                         nEnvEntries++;
1221                 }
1222         }
1223
1224         if (array) array = 0x0;
1225
1226         AliInfo(Form("========== AtmosPressures (Cavern + Surface + Cavern2) ==========="));
1227         AliDCSSensorArray *dcsSensorArray = GetPressureMap(valueMap);
1228         //dcsSensorArray->Print();
1229         if( fPressure->NumFits()<kNumSensors ) {
1230                 Log(Form("Check the pressure sensor values! Not all the %d pressure sensors have been fit",kNumSensors));
1231         } 
1232         Log(Form("Number of fits performed = %d",fPressure->NumFits()));
1233
1234         AliInfo(Form("==========CavernAtmosPressure==========="));
1235         indexDP = kCavernAtmosPressure;
1236         AliDCSSensor* sensorCavernP2 = dcsSensorArray->GetSensor(fgkDCSDataPoints[indexDP]);
1237         TGraph* graph = sensorCavernP2->GetGraph();
1238         AliDebug(3,Form("index = %d",indexDP));
1239         AliDebug(3,Form("name = %s",fgkDCSDataPoints[indexDP]));
1240         AliDebug(2,Form("graph = %p",graph));
1241         AliDebug(3,Form("sensorCavernP2 = %p", sensorCavernP2));
1242         if(sensorCavernP2->GetFit() || graph) {
1243                 if (sensorCavernP2->GetFit()){
1244                         Log(Form("Fit for sensor %s found",fgkDCSDataPoints[indexDP]));
1245                 }
1246                 else {
1247                         Log(Form("Fit for sensor %s not found, but the graph is there - NOT going into error",fgkDCSDataPoints[indexDP]));
1248                 }
1249                 grpObj->SetCavernAtmosPressure(sensorCavernP2);
1250                 ffailedDPs->RemoveAt(indexDP);
1251                 nEnvEntries++;
1252         } 
1253         //if (sensorP2) delete sensorP2;
1254         else {
1255                 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] ));
1256         }
1257         
1258         AliInfo(Form("==========SurfaceAtmosPressure==========="));
1259         indexDP = kSurfaceAtmosPressure;
1260         AliDCSSensor* sensorP2 = dcsSensorArray->GetSensor(fgkDCSDataPoints[indexDP]);
1261         graph = sensorP2->GetGraph();
1262         AliDebug(3,Form("index = %d",indexDP));
1263         AliDebug(3,Form("name = %s",fgkDCSDataPoints[indexDP]));
1264         AliDebug(2,Form("graph = %p",graph));   
1265         AliDebug(3,Form("sensorP2 = %p", sensorP2));
1266         if(sensorP2->GetFit() || graph) {
1267                 if (sensorP2->GetFit()){
1268                         Log(Form("Fit for sensor %s found",fgkDCSDataPoints[indexDP]));
1269                 }
1270                 else {
1271                         Log(Form("Fit for sensor %s not found, but the graph is there - NOT going into error",fgkDCSDataPoints[indexDP]));
1272                 }
1273                 grpObj->SetSurfaceAtmosPressure(sensorP2);
1274                 ffailedDPs->RemoveAt(indexDP);
1275                 nEnvEntries++;
1276         } 
1277         //if (sensorP2) delete sensorP2;
1278         else {
1279                 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] ));
1280         }
1281
1282         AliInfo(Form("==========CavernAtmosPressure2==========="));
1283         indexDP = kCavernAtmosPressure2;
1284         AliDCSSensor* sensorCavernP22 = dcsSensorArray->GetSensor(fgkDCSDataPoints[indexDP]);
1285         graph = sensorCavernP22->GetGraph();
1286         AliDebug(3,Form("index = %d",indexDP));
1287         AliDebug(3,Form("name = %s",fgkDCSDataPoints[indexDP]));
1288         AliDebug(2,Form("graph = %p",graph));   
1289         AliDebug(3,Form("sensorCavernP2_2 = %p", sensorCavernP22));
1290         if(sensorCavernP22->GetFit() || graph) {
1291                 if (sensorCavernP22->GetFit()){
1292                         Log(Form("Fit for sensor %s found",fgkDCSDataPoints[indexDP]));
1293                 }
1294                 else {
1295                         Log(Form("Fit for sensor %s not found, but the graph is there - NOT going into error",fgkDCSDataPoints[indexDP]));
1296                 }
1297                 grpObj->SetCavernAtmosPressure2(sensorCavernP22);
1298                 ffailedDPs->RemoveAt(indexDP);
1299                 nEnvEntries++;
1300         } 
1301         //if (sensorP2) delete sensorP2;
1302         else {
1303                 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] ));
1304         }
1305         
1306         
1307         return nEnvEntries;
1308 }
1309 //_______________________________________________________________
1310
1311 Int_t AliGRPPreprocessor::ProcessHPDPs(const TMap* valueMap, AliGRPObject* grpObj)
1312 {
1313         // processing DPs
1314         // related to 
1315         // Hall Probes info
1316
1317         Int_t nHPEntries = 0;
1318         TObjArray *array = 0x0;
1319         Int_t indexDP = -1;
1320         Bool_t outOfRange; // flag to monitor if any value collected by DCS is out of range
1321
1322         if (fgknDCSDPHallProbes != AliGRPObject::GetNumberOfHP()){
1323                 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()));
1324         }
1325         for (indexDP = 0; indexDP < AliGRPObject::GetNumberOfHP(); indexDP++){
1326                 outOfRange = kFALSE; // resetting outOfRange flag at each HP
1327                 AliInfo(Form("==========%s===========",AliGRPObject::GetHPDP(indexDP)));
1328                 array = (TObjArray *)valueMap->GetValue(AliGRPObject::GetHPDP(indexDP));
1329                 if(!array) {
1330                         Log(Form("%s not found in the map!!!",AliGRPObject::GetHPDP(indexDP)));
1331                 } 
1332                 else {
1333                         if (array->GetEntries() == 0){
1334                                 AliError(Form("No entries found in array! setting %s to invalid...",AliGRPObject::GetHPDP(indexDP)));
1335                         }
1336                         else {
1337                                 Float_t *floatDCS = ProcessFloatAll(array);
1338                                 if (floatDCS != NULL){
1339                                         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])); 
1340                                         grpObj->SetHallProbes((AliGRPObject::DP_HallProbes)indexDP,floatDCS);
1341                                         for (Int_t kk = 0 ; kk< 5; kk++){
1342                                                 AliDebug(2,Form("HallProbe[%d][%d]=%f",indexDP,kk,grpObj->GetHallProbes((AliGRPObject::DP_HallProbes)indexDP,(AliGRPObject::Stats)kk)));
1343                                         }
1344                                 }
1345                                 else{
1346                                         outOfRange = kTRUE;
1347                                 }
1348                                 if (floatDCS){
1349                                         delete[] floatDCS;
1350                                         floatDCS = 0x0;
1351                                 }
1352                         }
1353                         if (!outOfRange) {
1354                                 ffailedDPs->RemoveAt(indexDP + 7);  // 7 = shift in the complete list of DPs to get to the Hall Probes
1355                                 nHPEntries++;
1356                         }
1357                 }
1358         }
1359                 
1360         Log(Form("Hall Probes = %d ", nHPEntries));
1361         return nHPEntries;
1362 }
1363
1364 //_________________________________________________________________________
1365
1366 AliSplineFit* AliGRPPreprocessor::GetSplineFit(const TObjArray *array, const TString& stringID){
1367
1368
1369         // 
1370         // returning Spline Fit 
1371         // 
1372
1373         Int_t entriesarray = array->GetEntries();
1374         Float_t* value = new Float_t[entriesarray];
1375         Float_t* time = new Float_t[entriesarray];
1376         AliDCSValue* v = 0x0;
1377         for (Int_t iarray = 0; iarray < entriesarray; iarray++){
1378                 v = (AliDCSValue*)array->At(iarray);
1379                 value[iarray] = v->GetFloat();
1380                 time[iarray] = v->GetTimeStamp();
1381                 AliDebug(2,Form("iarray = %d, value = %f, time = %f",iarray,value[iarray],time[iarray]));
1382         }
1383         TGraph* gr = new TGraph(entriesarray,value,time);
1384         if (!gr ) {
1385                 AliWarning(Form("%s: no input graph to compute SplineFit",stringID.Data()));
1386                 return NULL;
1387         }
1388         AliSplineFit *fit = new AliSplineFit();
1389         fit->SetMinPoints(10);
1390         fit->InitKnots(gr,10,10,0.0);
1391         fit->SplineFit(2);
1392         fit->Cleanup();
1393         if (!fit) {
1394                 AliWarning(Form("%s: no fit performed",stringID.Data()));
1395                 return NULL;
1396         } 
1397         return fit;
1398 }
1399
1400 //_________________________________________________________________________
1401
1402 TString AliGRPPreprocessor::ProcessChar(const TObjArray *array)
1403 {
1404
1405         // 
1406         // processing char
1407         //
1408
1409         TString aDCSString="";
1410         
1411         AliDCSValue *v = 0x0;
1412         for(Int_t iCount = 0; iCount < array->GetEntries(); iCount++) {
1413                 v = (AliDCSValue *)array->At(iCount);
1414                 if (((Int_t)(v->GetTimeStamp()) < (Int_t)GetStartTimeDCSQuery()) || ((Int_t)(v->GetTimeStamp()) > (Int_t)GetEndTimeDCSQuery())) {
1415                         AliError(Form("DCS values for the parameter outside the queried interval"));
1416                         continue;
1417                 }
1418                 if (iCount > 0) {
1419                         if (aDCSString != v->GetChar())
1420                         AliError(Form("DCS values for the parameter changed from %s to %c within the queried interval", aDCSString.Data(), (Char_t)v->GetChar()));
1421                 }
1422                 aDCSString = (TString)v->GetChar();  // keeping always last value in the array
1423         }
1424         return aDCSString;
1425 }
1426
1427 //__________________________________________________________________________________________________________________
1428
1429 Float_t* AliGRPPreprocessor::ProcessFloatAll(const TObjArray* array)
1430 {
1431         // 
1432         // processing Float values using Mean, Median, Standard Deviation wrt Mean, Standar Deviation wrt Median 
1433         //
1434         // parameters[0] = mean
1435         // parameters[1] = truncated mean (calculated excluding points outside +/- 3RMS from mean
1436         // parameters[2] = median
1437         // parameters[3] = standard deviation wrt mean
1438         // parameters[4] = standard deviation wrt median
1439         //
1440
1441         TString timeStartString = (TString)GetRunParameter("DAQ_time_start");
1442         TString timeEndString = (TString)GetRunParameter("DAQ_time_end");
1443         if (timeStartString.IsNull() || timeStartString.IsNull()){
1444                 if (timeStartString.IsNull()){ 
1445                         AliError("DAQ_time_start not set in logbook! Setting statistical values for current DP to invalid");
1446                 }
1447                 else if (timeStartString.IsNull()){
1448                         AliError("DAQ_time_end not set in logbook! Setting statistical values for current DP to invalid");
1449                 }
1450                 fdaqStartEndTimeOk = kFALSE;
1451                 return 0;
1452         }  
1453
1454         Int_t timeStart = (Int_t)(timeStartString.Atoi());
1455         Int_t timeEnd = (Int_t)(timeEndString.Atoi());
1456         Float_t* parameters = new Float_t[5];
1457         Int_t iCounts = 0;
1458         Int_t iCountsRun = 0;
1459         Int_t nCounts = array->GetEntries();
1460         Float_t valueBeforeSOR = 0;
1461         Float_t valueAfterEOR = 0;
1462         Int_t timestampBeforeSOR = -1;
1463         Int_t timestampAfterEOR = -1;
1464         Int_t ientrySOR = -1;
1465         Int_t ientryEOR = -1;
1466         Float_t* arrayValues = 0x0; 
1467         Double_t* arrayWeights = 0x0; 
1468         Bool_t truncMeanFlag = kTRUE;  // flag to indicate whether Truncated Mean should be calculated or not
1469         Bool_t sdFlag = kTRUE;  // flag to indicate whether SD (wrt Mean/Median) should be calculated or not
1470
1471         for(Int_t i = 0; i < nCounts; i++) {
1472                 AliDCSValue *v = (AliDCSValue *)array->At(i);
1473                 if ((v->GetFloat() <= fminFloat) || (v->GetFloat() >= fmaxFloat)) {
1474                         AliError(Form("Error! Float value found in DCS map at %d-th entry is OUT OF RANGE: value = %6.5e",i,v->GetFloat()));
1475                         if (v->GetFloat() < fminFloat) AliInfo(Form("The value is smaller than %6.5e",fminFloat));
1476                         if (v->GetFloat() > fmaxFloat) AliInfo(Form("The value is greater than %6.5e",fmaxFloat));
1477                         return NULL;
1478                 }
1479                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
1480                         AliDebug(2,Form("%d-th entry = %f at timestamp %i",i,v->GetFloat(),v->GetTimeStamp()));
1481                         iCounts += 1;
1482                         // look for the last value before SOR and the first value before EOR
1483                         if (((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) && (Int_t)(v->GetTimeStamp()) < timeStart) {
1484                                 timestampBeforeSOR = (Int_t)(v->GetTimeStamp());
1485                                 AliDebug(2,Form("timestamp of last value before SOR = %d, with DAQ_time_start = %d",timestampBeforeSOR,timeStart));
1486                                 valueBeforeSOR = v->GetFloat();
1487                         }
1488                         else if ((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery() && (Int_t)(v->GetTimeStamp()) > timeEnd && timestampAfterEOR == -1){
1489                                 timestampAfterEOR = (Int_t)(v->GetTimeStamp());
1490                                 valueAfterEOR = v->GetFloat();
1491                                 AliDebug(2,Form("timestamp of first value after EOR = %d, with DAQ_time_end = %d",timestampAfterEOR,timeEnd));
1492                         }
1493                         // check if there are DPs between DAQ_time_start and DAQ_time_end
1494                         if(((Int_t)(v->GetTimeStamp()) >= timeStart) &&((Int_t)(v->GetTimeStamp()) <= timeEnd)) {
1495                                 if (ientrySOR == -1) ientrySOR = i;  // first entry after SOR
1496                                 if (ientryEOR < i) ientryEOR = i;  // last entry before EOR
1497                                 AliDebug(2,Form("entry between SOR and EOR"));
1498                                 iCountsRun += 1;
1499                         }
1500                 }
1501                 else {
1502                         AliError(Form("DCS values for the parameter outside the queried interval: timestamp = %d",v->GetTimeStamp()));
1503                 }
1504         }
1505
1506         if (timestampBeforeSOR == -1){
1507                 AliWarning("No value found before SOR");
1508         }
1509         if (timestampAfterEOR == -1){
1510                 AliWarning("No value found after EOR");
1511         }
1512
1513         AliDebug(2,Form("Number of valid entries (within DCS query interval) = %i, from a total amount of %i entries",iCounts,nCounts));
1514         AliDebug(2,Form("Last value before DAQ_time_start (SOR) = %f at timestamp = %d",valueBeforeSOR,timestampBeforeSOR));
1515         AliDebug(2,Form("First value after DAQ_time_end (EOR)   = %f at timestamp = %d",valueAfterEOR,timestampAfterEOR));
1516         AliInfo(Form("Found %d entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)",iCountsRun));
1517         AliDebug(2,Form("Index of first entry after DAQ_time_start (SOR) = %d ",ientrySOR));
1518         AliDebug(2,Form("Index of first entry before DAQ_time_end (EOR) = %d ",ientryEOR));
1519
1520         Int_t nentriesUsed = 0;
1521         if (iCountsRun > 1){
1522                 AliInfo("Using entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)");
1523                 AliDebug(2,"Calculating (weighted) Mean and Median");
1524                 arrayValues = new Float_t[iCountsRun]; 
1525                 arrayWeights = new Double_t[iCountsRun]; 
1526                 nentriesUsed = iCountsRun;
1527                 for (Int_t i = ientrySOR; i <= ientryEOR; i++){
1528                         AliDCSValue *v = (AliDCSValue *)array->At(i);
1529                         Int_t timestamp2 = 0;
1530                         if (i < ientryEOR){
1531                                 AliDCSValue *v1 = (AliDCSValue *)array->At(i+1);
1532                                 timestamp2 = (Int_t)v1->GetTimeStamp();
1533                         }
1534                         else {
1535                                 timestamp2 = timeEnd+1;
1536                         }
1537                         arrayWeights[i-ientrySOR] = (Double_t)(timestamp2 - (Int_t)v->GetTimeStamp());
1538                         arrayValues[i-ientrySOR] = v->GetFloat();
1539                 }
1540                 parameters[0] = TMath::Mean(iCountsRun,arrayValues,arrayWeights);
1541                 parameters[2] = TMath::Median(iCountsRun,arrayValues,arrayWeights);
1542         }
1543         else if (iCountsRun == 1){
1544                 AliDCSValue* v = (AliDCSValue *)array->At(ientrySOR);
1545                 nentriesUsed = 2;
1546                 if (timestampBeforeSOR != -1 && timestampBeforeSOR != (Int_t)v->GetTimeStamp()){
1547                         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.");
1548                         arrayValues = new Float_t[2];
1549                         arrayWeights = new Double_t[2];
1550                         arrayValues[0] = valueBeforeSOR;
1551                         arrayWeights[0] = (Double_t)((Int_t)v->GetTimeStamp()-timestampBeforeSOR);
1552                         arrayValues[1] = v->GetFloat();
1553                         arrayWeights[1] = (Double_t)(timeEnd+1-(Int_t)v->GetTimeStamp());
1554                         AliDebug(2, Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
1555                         AliDebug(2, Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
1556                         parameters[0] = TMath::Mean(2,arrayValues,arrayWeights);
1557                         parameters[2] = TMath::Median(2,arrayValues,arrayWeights);
1558                         truncMeanFlag = kFALSE;
1559                 }
1560                 else{
1561                         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");
1562                         parameters[0] = AliGRPObject::GetInvalidFloat();
1563                         parameters[1] = AliGRPObject::GetInvalidFloat();
1564                         parameters[2] = AliGRPObject::GetInvalidFloat();
1565                         parameters[3] = AliGRPObject::GetInvalidFloat();
1566                         parameters[4] = AliGRPObject::GetInvalidFloat();
1567                         return parameters;
1568                 }
1569         }
1570         else { // iCountsRun == 0, using only the point immediately before SOR
1571                 if (timestampBeforeSOR == -1){
1572                         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");
1573                         parameters[0] = AliGRPObject::GetInvalidFloat();
1574                         parameters[1] = AliGRPObject::GetInvalidFloat();
1575                         parameters[2] = AliGRPObject::GetInvalidFloat();
1576                         parameters[3] = AliGRPObject::GetInvalidFloat();
1577                         parameters[4] = AliGRPObject::GetInvalidFloat();
1578                         return parameters;
1579                 }
1580                 else {
1581                         AliWarning("Using only last entry before SOR. Truncated mean and Standard deviations (wrt mean/median) won't be calculated.");
1582                         AliDebug(2,Form("value = %f",valueBeforeSOR)); 
1583                         parameters[0] = valueBeforeSOR;
1584                         parameters[2] = valueBeforeSOR;
1585                         truncMeanFlag = kFALSE;
1586                         sdFlag = kFALSE;
1587                 }
1588         }
1589
1590         Float_t temp = 0;
1591         Float_t temp1 = 0;
1592         Float_t sumweights = 0; 
1593         Int_t entriesTruncMean = 0;
1594         Float_t* arrayValuesTruncMean = new Float_t[nentriesUsed]; 
1595         Double_t* arrayWeightsTruncMean = new Double_t[nentriesUsed]; 
1596
1597         // calculating SD wrt Mean and Median
1598         AliDebug(2,"Calculating SD wrt Mean and SD wrt Median");
1599         if (sdFlag){
1600                 for (Int_t i =0; i< nentriesUsed; i++){
1601                         AliDebug(2,Form("Entry %d: value = %f, weight = %f",i,arrayValues[i],arrayWeights[i]));
1602                         temp += (arrayValues[i]-parameters[2])*(arrayValues[i]-parameters[2]);
1603                         temp1 += arrayWeights[i]*(arrayValues[i]-parameters[0])*(arrayValues[i]-parameters[0]);
1604                         sumweights += arrayWeights[i];
1605                 }
1606                 // setting SD wrt Mean 
1607                 if (sumweights != 0 ){
1608                         parameters[3] = TMath::Sqrt(temp1/sumweights);
1609                 }
1610                 else {
1611                         AliError("Sum of weights to calculate Standard Deviation (wrt mean) <= 0, setting the SD to invalid");
1612                         parameters[3] = AliGRPObject::GetInvalidFloat();
1613                 }
1614                 // setting SD wrt Median
1615                 if (nentriesUsed != 0){
1616                         parameters[4] = TMath::Sqrt(temp/nentriesUsed);
1617                 }
1618                 else{
1619                         AliError("Number of entries used to calculate Standard Deviation (wrt median) <= 0, setting the SD to invalid");
1620                         parameters[4] = AliGRPObject::GetInvalidFloat();
1621                 }
1622         }
1623         else {
1624                 parameters[3] = AliGRPObject::GetInvalidFloat();
1625                 parameters[4] = AliGRPObject::GetInvalidFloat();
1626         }               
1627
1628         // calculating truncated mean (this comes afterwards since you need the SD wrt Mean)
1629         if (truncMeanFlag){
1630                 AliDebug(2,"Calculating Truncated Mean");
1631                 for (Int_t i =0; i< nentriesUsed; i++){
1632                         AliDebug(2,Form("Entry %d: value = %f, weight = %f",i,arrayValues[i],arrayWeights[i]));
1633                         if ((arrayValues[i]<=parameters[0]+3*parameters[3]) && (arrayValues[i]>=parameters[0]-3*parameters[3])){
1634                                 arrayValuesTruncMean[entriesTruncMean]=arrayValues[i];
1635                                 arrayWeightsTruncMean[entriesTruncMean]=arrayWeights[i];
1636                                 AliDebug(2,Form("For Truncated Mean: Entry %d: value = %f, weight = %f",entriesTruncMean,arrayValuesTruncMean[entriesTruncMean],arrayWeightsTruncMean[entriesTruncMean]));
1637                                 entriesTruncMean++;                     
1638                         }
1639                         else{
1640                                 AliDebug(2,"Discarding entry");
1641                         }
1642                 }
1643                 // setting truncated mean 
1644                 if (entriesTruncMean >1){
1645                         AliDebug(2,Form("%d entries used for truncated mean",entriesTruncMean));
1646                         parameters[1] = TMath::Mean(entriesTruncMean,arrayValuesTruncMean,arrayWeightsTruncMean);
1647                 }
1648                 else{   
1649                         AliDebug(2,Form("Too few entries (%d) to calculate truncated mean",entriesTruncMean));
1650                         parameters[1] = AliGRPObject::GetInvalidFloat();
1651                 }
1652         }
1653         else{
1654                         parameters[1] = AliGRPObject::GetInvalidFloat();
1655         }
1656
1657         AliInfo(Form("(weighted) mean = %f ",parameters[0]));
1658         AliInfo(Form("(weighted) truncated mean = %f ",parameters[1]));
1659         AliInfo(Form("median = %f ",parameters[2]));
1660         AliInfo(Form("(weighted) standard deviation with (weighted) mean = %f ",parameters[3]));
1661         AliInfo(Form("standard deviation with median = %f ",parameters[4]));
1662         
1663         return parameters;
1664 }
1665
1666 //__________________________________________________________________________________________________________________
1667
1668 Float_t* AliGRPPreprocessor::ProcessFloatAllMagnet(const TObjArray* array, Int_t indexDP, Bool_t &isZero)
1669 {
1670         // 
1671         // processing Float values using Mean, Median, Standard Deviation wrt Mean, Standar Deviation wrt Median 
1672         // used for L3 and Dipole magnets, using isZero flag to decide whther the magnet was OFF/ON
1673         // the flag is set according to the L3/Dipole current value
1674         // current threshold for L3 = 350 A (value provided by DCS)
1675         // current threshold for Dipole = 450 A (value provided by DCS)
1676         //
1677         // parameters[0] = mean
1678         // parameters[1] = truncated mean (calculated excluding points outside +/- 3RMS from mean
1679         // parameters[2] = median
1680         // parameters[3] = standard deviation wrt mean
1681         // parameters[4] = standard deviation wrt median
1682         //
1683
1684         AliInfo(Form("indexDP = %d",indexDP)); 
1685
1686         Int_t nCounts = array->GetEntries();
1687         for(Int_t i = 0; i < nCounts; i++) {
1688                 AliDCSValue *v = (AliDCSValue *)array->At(i);
1689                 if ((v->GetFloat() <= fminFloat) || (v->GetFloat() >= fmaxFloat)) {
1690                         AliError(Form("Error! Float value found in DCS map at %d-th entry is OUT OF RANGE: value = %6.5e",i,v->GetFloat()));
1691                         if (v->GetFloat() < fminFloat) AliInfo(Form("The value is smaller than %6.5e",fminFloat));
1692                         if (v->GetFloat() > fmaxFloat) AliInfo(Form("The value is greater than %6.5e",fmaxFloat));
1693                         return NULL;
1694                 }
1695                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
1696                         AliDebug(2,Form("%d-th entry = %f",i,v->GetFloat()));
1697                         if (indexDP == kL3Current && v->GetFloat() > 350 && isZero == kTRUE) isZero=kFALSE; 
1698                         if (indexDP == kDipoleCurrent && v->GetFloat() > 450 && isZero == kTRUE) isZero=kFALSE; 
1699                 }
1700                 else {
1701                         AliError(Form("DCS values for the parameter outside the queried interval"));
1702                 }
1703         }
1704
1705         return ProcessFloatAll(array);
1706 }
1707
1708
1709 //_______________________________________________________________
1710
1711 Char_t AliGRPPreprocessor::ProcessBool(const TObjArray* array, Bool_t &change)
1712 {
1713         // 
1714         // processing Boolean values
1715         //
1716
1717         Bool_t aDCSBool = kTRUE;
1718
1719         AliDCSValue *v = 0x0;
1720
1721         for(Int_t iCount = 0; iCount < array->GetEntries(); iCount++) {
1722                 v = (AliDCSValue *)array->At(iCount);
1723                 if (((Int_t)(v->GetTimeStamp()) < (Int_t)GetStartTimeDCSQuery()) || ((Int_t)(v->GetTimeStamp()) > (Int_t)GetEndTimeDCSQuery())) {
1724                         AliError(Form("DCS values for the parameter outside the queried interval"));
1725                         continue;
1726                 }
1727                 if (iCount > 0) {
1728                         if (aDCSBool != v->GetBool()) {
1729                                 AliError(Form("DCS values for the parameter changed from %d to %d within the queried interval", (UInt_t)aDCSBool, (UInt_t)v->GetBool()));
1730                                 change = kTRUE;
1731                         }
1732                 }
1733                 aDCSBool = v->GetBool(); // always keeping last value
1734                 AliDebug(2,Form("Bool = %d",(Int_t)aDCSBool));
1735         }
1736         
1737         Char_t caDCSBool = (Char_t) aDCSBool;
1738         return caDCSBool;
1739         
1740 }
1741
1742 //_______________________________________________________________
1743
1744 Float_t AliGRPPreprocessor::ProcessInt(const TObjArray* array)
1745 {
1746         // 
1747         // processing Int values, returning mean
1748         // AliGRPObject::GetInvalidFloat() is returned if any of the DCS values
1749         // are outside the queried time interval or their value is out of range
1750         //
1751
1752         TString timeStartString = (TString)GetRunParameter("DAQ_time_start");
1753         TString timeEndString = (TString)GetRunParameter("DAQ_time_end");
1754         if (timeStartString.IsNull() || timeStartString.IsNull()){
1755                 if (timeStartString.IsNull()){ 
1756                         AliError("DAQ_time_start not set in logbook! Setting statistical values for current DP to invalid");
1757                 }
1758                 else if (timeStartString.IsNull()){
1759                         AliError("DAQ_time_end not set in logbook! Setting statistical values for current DP to invalid");
1760                 }
1761                 return 0;
1762         }  
1763
1764         Int_t timeStart = (Int_t)(timeStartString.Atoi());
1765         Int_t timeEnd = (Int_t)(timeEndString.Atoi());
1766         Float_t aDCSArrayMean = 0.0;
1767         Int_t iCounts = 0;
1768         Float_t valueBeforeSOR = 0;
1769         Float_t valueAfterEOR = 0;
1770         Int_t timestampBeforeSOR = -1;
1771         Int_t timestampAfterEOR = -1;
1772         Int_t ientrySOR = -1;
1773         Int_t ientryEOR = -1;
1774         Float_t* arrayValues = 0x0; 
1775         Double_t* arrayWeights = 0x0; 
1776         Int_t iCountsRun = 0;
1777         Int_t nCounts = array->GetEntries();
1778
1779         for(Int_t i = 0; i < nCounts; i++) {
1780                 AliDCSValue* v = (AliDCSValue *)array->At(i);
1781                 if ((v->GetInt() < fminInt) || (v->GetInt() > fmaxInt)) {
1782                         AliError(Form("Error! Int value found in DCS map at %d-th entry is OUT OF RANGE: value = %d",i, v->GetInt()));
1783                         return AliGRPObject::GetInvalidFloat();
1784                 }
1785                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
1786                         AliDebug(2,Form("%d-th entry = %d at timestamp %i",i,v->GetInt(),v->GetTimeStamp()));
1787                         iCounts += 1;
1788                         // look for the last value before SOR and the first value before EOR
1789                         if (((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) && (Int_t)(v->GetTimeStamp()) < timeStart) {
1790                                 timestampBeforeSOR = (Int_t)(v->GetTimeStamp());
1791                                 AliDebug(2,Form("timestamp of last entry before SOR = %d, with DAQ_time_start = %d",timestampBeforeSOR,timeStart));
1792                                 valueBeforeSOR = (Float_t) v->GetInt();
1793                         }
1794                         else if ((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery() && (Int_t)(v->GetTimeStamp()) > timeEnd && timestampAfterEOR == -1){
1795                                 timestampAfterEOR = (Int_t)(v->GetTimeStamp());
1796                                 valueAfterEOR = (Float_t) v->GetInt();
1797                                 AliDebug(2,Form("timestamp of first entry after EOR = %d, with DAQ_time_end = %d",timestampAfterEOR,timeEnd));
1798                         }
1799                         // check if there are DPs between DAQ_time_start and DAQ_time_end
1800                         if(((Int_t)(v->GetTimeStamp()) >= timeStart) &&((Int_t)(v->GetTimeStamp()) <= timeEnd)) {
1801                                 if (ientrySOR == -1) ientrySOR = i;  // first entry after SOR
1802                                 if (ientryEOR < i) ientryEOR = i;  // last entry before EOR
1803                                 AliDebug(2,Form("entry between SOR and EOR"));
1804                                 iCountsRun += 1;
1805                         }
1806                 }
1807                 else {
1808                         AliError(Form("DCS values for the parameter outside the queried interval: timestamp = %d",v->GetTimeStamp()));
1809                 }
1810         }
1811
1812         if (timestampBeforeSOR == -1){
1813                 AliWarning("No value found before SOR!");
1814         }
1815         if (timestampAfterEOR == -1){
1816                 AliWarning("No value found after EOR!");
1817         }
1818
1819         AliDebug(2,Form("Number of valid entries (within query interval) = %i, starting from %i entries",iCounts,nCounts));
1820         AliDebug(2,Form("Last value before DAQ_time_start (SOR) = %f at timestamp = %d",valueBeforeSOR,timestampBeforeSOR));
1821         AliDebug(2,Form("First value after DAQ_time_end (EOR)   = %f at timestamp = %d",valueAfterEOR,timestampAfterEOR));
1822         AliInfo(Form("Found %d entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)",iCountsRun));
1823         AliDebug(2,Form("Index of first entry after DAQ_time_start (SOR) = %d ",ientrySOR));
1824         AliDebug(2,Form("Index of first entry before DAQ_time_end (EOR) = %d ",ientryEOR));
1825
1826         Int_t nentriesUsed = 0;
1827         if (iCountsRun > 1){
1828                 AliInfo("Using entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)");
1829                 AliDebug(2,"Calculating (weighted) Mean");
1830                 arrayValues = new Float_t[iCountsRun]; 
1831                 arrayWeights = new Double_t[iCountsRun]; 
1832                 nentriesUsed = iCountsRun;
1833                 for (Int_t i = ientrySOR; i <= ientryEOR; i++){
1834                         AliDCSValue *v = (AliDCSValue *)array->At(i);
1835                         Int_t timestamp2 = 0;
1836                         if (i < ientryEOR){
1837                                 AliDCSValue *v1 = (AliDCSValue *)array->At(i+1);
1838                                 timestamp2 = (Int_t)v1->GetTimeStamp();
1839                         }
1840                         else {
1841                                 timestamp2 = timeEnd+1;
1842                         }
1843                         arrayWeights[i-ientrySOR] = (Double_t)(timestamp2 - (Int_t)v->GetTimeStamp());
1844                         arrayValues[i-ientrySOR] = (Float_t)v->GetInt();
1845                 }
1846                 aDCSArrayMean = TMath::Mean(iCountsRun,arrayValues,arrayWeights);
1847         }
1848         else if (iCountsRun == 1){
1849                 AliDCSValue* v = (AliDCSValue *)array->At(ientrySOR);
1850                 nentriesUsed = 2;
1851                 if (timestampBeforeSOR != -1 && timestampBeforeSOR != (Int_t)v->GetTimeStamp()){
1852                         AliWarning("Using single entry between DAQ_time_start (SOR) and DAQ_time_end (EOR) and last entry before SOR.");
1853                         arrayValues = new Float_t[2];
1854                         arrayWeights = new Double_t[2];
1855                         arrayValues[0] = valueBeforeSOR;
1856                         arrayWeights[0] = (Double_t)((Int_t)v->GetTimeStamp()-timestampBeforeSOR);
1857                         arrayValues[1] = (Float_t)v->GetInt();
1858                         arrayWeights[1] = (Double_t)(timeEnd+1-(Int_t)v->GetTimeStamp());
1859                         AliDebug(2,Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
1860                         AliDebug(2,Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
1861                         aDCSArrayMean = TMath::Mean(2,arrayValues,arrayWeights);
1862                 }
1863                 else{
1864                         AliError("Cannot calculate mean - only one value collected during the run, but no value before with which to calculate the statistical quantities");
1865                         return AliGRPObject::GetInvalidFloat();
1866                 }
1867         }
1868         else { // iCountsRun == 0, using the point immediately before SOR and the one immediately after EOR
1869                 if (timestampBeforeSOR == -1 || timestampAfterEOR == -1){
1870                         if (timestampBeforeSOR == -1){
1871                                 AliError("Cannot calculate mean - no points during the run collected, and point before SOR missing");
1872                         }
1873                         if (timestampAfterEOR == -1){
1874                                 AliError("Cannot calculate maen - no points during the run collected, and point after EOR missing");
1875                         }
1876                         return AliGRPObject::GetInvalidFloat();
1877                 }
1878                 else {
1879                         AliWarning("Using last entry before SOR and first entry after EOR.");
1880                         nentriesUsed = 2;
1881                         arrayValues = new Float_t[2];
1882                         arrayWeights = new Double_t[2];
1883                         arrayValues[0] = valueBeforeSOR;
1884                         arrayWeights[0] = (Double_t)(timestampAfterEOR - timestampBeforeSOR);
1885                         arrayValues[1] = valueAfterEOR;
1886                         arrayWeights[1] = 1.;
1887                         AliDebug(2,Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
1888                         AliDebug(2,Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
1889                         aDCSArrayMean = TMath::Mean(1,arrayValues,arrayWeights);
1890                 }
1891         }
1892
1893         AliInfo(Form("mean = %f ", aDCSArrayMean));
1894         return aDCSArrayMean;
1895
1896 }
1897 //_______________________________________________________________
1898
1899 Float_t AliGRPPreprocessor::ProcessUInt(const TObjArray* array)
1900 {
1901         // 
1902         // processing Int values, returning mean 
1903         // AliGRPObject::GetInvalidFloat() is returned if any of the DCS values
1904         // are outside the queried time interval or their value is out of range
1905         //
1906
1907         TString timeStartString = (TString)GetRunParameter("DAQ_time_start");
1908         TString timeEndString = (TString)GetRunParameter("DAQ_time_end");
1909         if (timeStartString.IsNull() || timeStartString.IsNull()){
1910                 if (timeStartString.IsNull()){ 
1911                         AliError("DAQ_time_start not set in logbook! Setting statistical values for current DP to invalid");
1912                 }
1913                 else if (timeStartString.IsNull()){
1914                         AliError("DAQ_time_end not set in logbook! Setting statistical values for current DP to invalid");
1915                 }
1916                 return 0;
1917         }  
1918
1919         Int_t timeStart = (Int_t)(timeStartString.Atoi());
1920         Int_t timeEnd = (Int_t)(timeEndString.Atoi());
1921         Float_t aDCSArrayMean = 0.0;
1922         Int_t iCounts = 0;
1923         Float_t valueBeforeSOR = 0;
1924         Float_t valueAfterEOR = 0;
1925         Int_t timestampBeforeSOR = -1;
1926         Int_t timestampAfterEOR = -1;
1927         Int_t ientrySOR = -1;
1928         Int_t ientryEOR = -1;
1929         Float_t* arrayValues = 0x0; 
1930         Double_t* arrayWeights = 0x0; 
1931         Int_t iCountsRun = 0;
1932         Int_t nCounts = array->GetEntries();
1933
1934         for(Int_t i = 0; i < nCounts; i++) {
1935                 AliDCSValue* v = (AliDCSValue *)array->At(i);
1936                 if ((v->GetUInt() < fminUInt) || (v->GetUInt() > fmaxUInt)) {
1937                         AliError(Form("Error! UInt value found in DCS map at %d-th entry is OUT OF RANGE: value = %u",i,v->GetUInt()));
1938                         return AliGRPObject::GetInvalidFloat();
1939                 }
1940                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
1941                         AliDebug(2,Form("%d-th entry = %d at timestamp %i",i,v->GetUInt(),v->GetTimeStamp()));
1942                         iCounts += 1;
1943                         // look for the last value before SOR and the first value before EOR
1944                         if (((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) && (Int_t)(v->GetTimeStamp()) < timeStart) {
1945                                 timestampBeforeSOR = (Int_t)(v->GetTimeStamp());
1946                                 AliDebug(2,Form("timestamp of last entry before SOR = %d, with DAQ_time_start = %d",timestampBeforeSOR,timeStart));
1947                                 valueBeforeSOR = (Float_t)v->GetUInt();
1948                         }
1949                         else if ((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery() && (Int_t)(v->GetTimeStamp()) > timeEnd && timestampAfterEOR == -1){
1950                                 timestampAfterEOR = (Int_t)(v->GetTimeStamp());
1951                                 valueAfterEOR = (Float_t)v->GetUInt();
1952                                 AliDebug(2,Form("timestamp of first entry after EOR = %d, with DAQ_time_end = %d",timestampAfterEOR,timeEnd));
1953                         }
1954                         // check if there are DPs between DAQ_time_start and DAQ_time_end
1955                         if(((Int_t)(v->GetTimeStamp()) >= timeStart) &&((Int_t)(v->GetTimeStamp()) <= timeEnd)) {
1956                                 if (ientrySOR == -1) ientrySOR = i;  // first entry after SOR
1957                                 if (ientryEOR < i) ientryEOR = i;  // last entry before EOR
1958                                 AliDebug(2,Form("entry between SOR and EOR"));
1959                                 iCountsRun += 1;
1960                         }
1961                 }
1962                 else {
1963                         AliError(Form("DCS values for the parameter outside the queried interval: timestamp = %d",v->GetTimeStamp()));
1964                 }
1965         }
1966
1967         if (timestampBeforeSOR == -1){
1968                 AliWarning("No value found before SOR!");
1969         }
1970         if (timestampAfterEOR == -1){
1971                 AliWarning("No value found after EOR!");
1972         }
1973
1974         AliDebug(2,Form("Number of valid entries (within query interval) = %i, starting from %i entries",iCounts,nCounts));
1975         AliDebug(2,Form("Last value before DAQ_time_start (SOR) = %f at timestamp = %d",valueBeforeSOR,timestampBeforeSOR));
1976         AliDebug(2,Form("First value after DAQ_time_end (EOR)   = %f at timestamp = %d",valueAfterEOR,timestampAfterEOR));
1977         AliInfo(Form("Found %d entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)",iCountsRun));
1978         AliDebug(2,Form("Index of first entry after DAQ_time_start (SOR) = %d ",ientrySOR));
1979         AliDebug(2,Form("Index of first entry before DAQ_time_end (EOR) = %d ",ientryEOR));
1980
1981         Int_t nentriesUsed = 0;
1982         if (iCountsRun > 1){
1983                 AliInfo("Using entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)");
1984                 AliDebug(2,"Calculating (weighted) Mean");
1985                 arrayValues = new Float_t[iCountsRun]; 
1986                 arrayWeights = new Double_t[iCountsRun]; 
1987                 nentriesUsed = iCountsRun;
1988                 for (Int_t i = ientrySOR; i <= ientryEOR; i++){
1989                         AliDCSValue *v = (AliDCSValue *)array->At(i);
1990                         Int_t timestamp2 = 0;
1991                         if (i < ientryEOR){
1992                                 AliDCSValue *v1 = (AliDCSValue *)array->At(i+1);
1993                                 timestamp2 = (Int_t)v1->GetTimeStamp();
1994                         }
1995                         else {
1996                                 timestamp2 = timeEnd+1;
1997                         }
1998                         arrayWeights[i-ientrySOR] = (Double_t)(timestamp2 - (Int_t)v->GetTimeStamp());
1999                         arrayValues[i-ientrySOR] = (Float_t)v->GetUInt();
2000                 }
2001                 aDCSArrayMean = TMath::Mean(iCountsRun,arrayValues,arrayWeights);
2002         }
2003         else if (iCountsRun == 1){
2004                 AliDCSValue* v = (AliDCSValue *)array->At(ientrySOR);
2005                 nentriesUsed = 2;
2006                 if (timestampBeforeSOR != -1 && timestampBeforeSOR != (Int_t)v->GetTimeStamp()){
2007                         AliWarning("Using single entry between DAQ_time_start (SOR) and DAQ_time_end (EOR) and last entry before SOR.");
2008                         arrayValues = new Float_t[2];
2009                         arrayWeights = new Double_t[2];
2010                         arrayValues[0] = valueBeforeSOR;
2011                         arrayWeights[0] = (Double_t)((Int_t)v->GetTimeStamp()-timestampBeforeSOR);
2012                         arrayValues[1] = (Float_t)v->GetUInt();
2013                         arrayWeights[1] = (Double_t)(timeEnd+1-(Int_t)v->GetTimeStamp());
2014                         AliDebug(2,Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
2015                         AliDebug(2,Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
2016                         aDCSArrayMean = TMath::Mean(2,arrayValues,arrayWeights);
2017                 }
2018                 else{
2019                         AliError("Cannot calculate mean - only one value collected during the run, but no value before with which to calculate the statistical quantities");
2020                         return AliGRPObject::GetInvalidFloat();
2021                 }
2022         }
2023         else { // iCountsRun == 0, using the point immediately before SOR and the one immediately after EOR
2024                 if (timestampBeforeSOR == -1 || timestampAfterEOR == -1){
2025                         if (timestampBeforeSOR == -1){
2026                                 AliError("Cannot calculate mean - no points during the run collected, and point before SOR missing");
2027                         }
2028                         if (timestampAfterEOR == -1){
2029                                 AliError("Cannot calculate maen - no points during the run collected, and point after EOR missing");
2030                         }
2031                         return AliGRPObject::GetInvalidFloat();
2032                 }
2033                 else {
2034                         AliWarning("Using last entry before SOR and first entry after EOR.");
2035                         nentriesUsed = 2;
2036                         arrayValues = new Float_t[2];
2037                         arrayWeights = new Double_t[2];
2038                         arrayValues[0] = valueBeforeSOR;
2039                         arrayWeights[0] = (Double_t)(timestampAfterEOR - timestampBeforeSOR);
2040                         arrayValues[1] = valueAfterEOR;
2041                         arrayWeights[1] = 1.;
2042                         AliDebug(2,Form("value0 = %f, with weight = %f",arrayValues[0],arrayWeights[0])); 
2043                         AliDebug(2,Form("value1 = %f, with weight = %f",arrayValues[1],arrayWeights[1])); 
2044                         aDCSArrayMean = TMath::Mean(1,arrayValues,arrayWeights);
2045                 }
2046         }
2047
2048         AliInfo(Form("mean = %f ",aDCSArrayMean));
2049         return aDCSArrayMean;
2050
2051 }
2052
2053
2054 //_______________________________________________________________
2055
2056 AliDCSSensorArray *AliGRPPreprocessor::GetPressureMap(TMap* dcsAliasMap)
2057 {
2058         // extract DCS pressure maps. Perform fits to save space
2059         
2060         TMap *map = fPressure->ExtractDCS(dcsAliasMap);
2061         if (map) {
2062                 AliDebug(2,Form("Map has %d entries",map->GetEntries()));
2063                 fPressure->MakeSplineFit(map);
2064                 Double_t fitFraction = fPressure->NumFits()/fPressure->NumSensors(); 
2065                 if (fitFraction > kFitFraction ) {
2066                         AliInfo(Form("Pressure values extracted, %d fits performed for %d sensors.", fPressure->NumFits(),fPressure->NumSensors()));
2067                 } else { 
2068                         AliInfo("Too few pressure maps fitted!!!");
2069                 }
2070         } else {
2071                 AliInfo("no atmospheric pressure map extracted!!!");
2072         }
2073         delete map;
2074         
2075         return fPressure;
2076 }
2077
2078
2079   
2080 //_______________________________________________________________
2081 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)
2082 {
2083         //
2084         // Retrieves logbook and trigger information from the online logbook
2085         // This information is needed for prompt reconstruction
2086         //
2087         // Parameters are:
2088         // Run number
2089         // DAQ params: dbHost, dbPort, dbName, user, password, logbookTable, triggerTable
2090         // cdbRoot
2091         //
2092         // returns:
2093         //         positive on success: the return code is the run number of last run processed of the same run type already processed by the SHUTTLE
2094         //         0 on success and no run was found
2095         //         negative on error
2096         //
2097         // This function is NOT called during the preprocessor run in the Shuttle!
2098         //
2099         
2100         // defaults
2101         if (dbPort == 0)
2102                 dbPort = 3306;
2103         
2104         // CDB connection
2105         AliCDBManager* cdb = AliCDBManager::Instance();
2106         cdb->SetDefaultStorage(cdbRoot);
2107         
2108         // SQL connection
2109         TSQLServer* server = TSQLServer::Connect(Form("mysql://%s:%d/%s", dbHost, dbPort, dbName), user, password);
2110         
2111         if (!server)
2112                 {
2113                         Printf("ERROR: Could not connect to DAQ LB");
2114                         return -1;
2115                 }
2116         
2117         // main logbook
2118         TString sqlQuery;
2119         sqlQuery.Form("SELECT DAQ_time_start, run_type, detectorMask, L3_magnetCurrent, Dipole_magnetCurrent FROM logbook WHERE run = %d", run);
2120         TSQLResult* result = server->Query(sqlQuery);
2121         if (!result)
2122                 {
2123                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
2124                         return -2;
2125                 }
2126         
2127         if (result->GetRowCount() == 0)
2128                 {
2129                         Printf("ERROR: Run %d not found", run);
2130                         delete result;
2131                         return -3;
2132                 }
2133         
2134         TSQLRow* row = result->Next();
2135         if (!row)
2136                 {
2137                         Printf("ERROR: Could not receive data from run %d", run);
2138                         delete result;
2139                         return -4;
2140                 }
2141         
2142         TString timeStartString(row->GetField(0));
2143         TString runType(row->GetField(1));
2144         TString detectorMaskString(row->GetField(2));
2145         TString l3CurrentString(row->GetField(3));
2146         TString dipoleCurrentString(row->GetField(4));
2147         time_t timeStart = (time_t)(timeStartString.Atoi());
2148         UInt_t detectorMask = (UInt_t)(detectorMaskString.Atoi());
2149         Float_t l3Current = (Float_t)(TMath::Abs(l3CurrentString.Atof()));
2150         Float_t dipoleCurrent = (Float_t)(TMath::Abs(dipoleCurrentString.Atof()));
2151         Char_t l3Polarity = (l3CurrentString.Atof() < 0) ? 1 : 0;
2152         Char_t dipolePolarity = (dipoleCurrentString.Atof() < 0) ? 1 : 0;
2153         
2154         AliGRPObject * grpObj = new AliGRPObject();
2155         grpObj->SetTimeStart(timeStart); 
2156         grpObj->SetRunType((TString)(row->GetField(1)));
2157         grpObj->SetDetectorMask(detectorMask);
2158         grpObj->SetL3Current(l3Current,(AliGRPObject::Stats)0);
2159         grpObj->SetDipoleCurrent(dipoleCurrent,(AliGRPObject::Stats)0);
2160         grpObj->SetL3Polarity(l3Polarity);
2161         grpObj->SetDipolePolarity(dipolePolarity);
2162         grpObj->SetPolarityConventionLHC();  // after the dipole cables swap we comply with LHC convention
2163
2164         delete row;
2165         row = 0;
2166         
2167         delete result;
2168         result = 0;
2169         
2170         Printf("Storing GRP/GRP/Data object with the following content");
2171         grpObj->Dump();
2172         
2173         AliCDBMetaData metadata;
2174         metadata.SetResponsible("Jan Fiete Grosse-Oetringhaus & Chiara Zampolli");
2175         metadata.SetComment("GRP Output parameters received during online running");
2176         
2177         AliCDBId id("GRP/GRP/Data", run, run);
2178         Bool_t success = cdb->Put(grpObj, id, &metadata);
2179         
2180         delete grpObj;
2181         
2182         if (!success)
2183                 {
2184                         Printf("ERROR: Could not store GRP/GRP/Data into OCDB");
2185                         return -5;
2186                 }
2187         
2188         // Receive trigger information
2189         sqlQuery.Form("SELECT configFile FROM logbook_trigger_config WHERE run = %d", run);
2190         result = server->Query(sqlQuery);
2191         if (!result)
2192                 {
2193                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
2194                         return -11;
2195                 }
2196         
2197         if (result->GetRowCount() == 0)
2198                 {
2199                         Printf("ERROR: Run %d not found in logbook_trigger_config", run);
2200                         delete result;
2201                         return -12;
2202                 }
2203         
2204         row = result->Next();
2205         if (!row)
2206                 {
2207                         Printf("ERROR: Could not receive logbook_trigger_config data from run %d", run);
2208                         delete result;
2209                         return -13;
2210                 }
2211         
2212         TString triggerConfig(row->GetField(0));
2213         
2214         delete row;
2215         row = 0;
2216         
2217         delete result;
2218         result = 0;
2219         
2220         Printf("Found trigger configuration: %s", triggerConfig.Data());
2221         
2222         AliTriggerConfiguration *runcfg = AliTriggerConfiguration::LoadConfigurationFromString(triggerConfig);
2223         if (!runcfg)
2224                 {
2225                         Printf("ERROR: Could not create CTP configuration object");
2226                         return -14;
2227                 }
2228         
2229         metadata.SetComment("CTP run configuration received during online running");
2230         
2231         AliCDBId id2("GRP/CTP/Config", run, run);
2232         success = cdb->Put(runcfg, id2, &metadata);
2233         
2234         delete runcfg;
2235         runcfg = 0;
2236         
2237         if (!success)
2238                 {
2239                         Printf("ERROR: Could not store GRP/CTP/Config into OCDB");
2240                         return -15;
2241                 }
2242         
2243
2244         // Receive list of GDCs for this run
2245         sqlQuery.Form("SELECT GDC FROM logbook_stats_GDC WHERE run = %d", run);
2246         result = server->Query(sqlQuery);
2247         if (!result)
2248                 {
2249                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
2250                         return -24;
2251                 }
2252         
2253         if (result->GetRowCount() == 0)
2254                 {
2255                         Printf("ERROR: Run %d not found in logbook_stats_GDC", run);
2256                         delete result;
2257                         return -25;
2258                 }
2259
2260         gdc = "";
2261         for (Int_t iGDC = 0; iGDC < result->GetRowCount(); iGDC++) {
2262           row = result->Next();
2263           if (!row)
2264             {
2265               Printf("ERROR: Could not receive logbook_stats_GDC data from run %d", run);
2266               delete result;
2267               return -26;
2268             }
2269           gdc += row->GetField(0);
2270           gdc += " ";
2271         }
2272
2273         delete row;
2274         row = 0;
2275         
2276         delete result;
2277         result = 0;
2278         
2279         Printf("Found GDC: %s", gdc.Data());
2280
2281         // get last run with same run type that was already processed by the SHUTTLE
2282         
2283         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());
2284         result = server->Query(sqlQuery);
2285         if (!result)
2286                 {
2287                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
2288                         return -21;
2289                 }
2290         
2291         if (result->GetRowCount() == 0)
2292                 {
2293                         Printf("ERROR: No result with query <%s>", sqlQuery.Data());
2294                         delete result;
2295                         return -22;
2296                 }
2297         
2298         row = result->Next();
2299         if (!row)
2300                 {
2301                         Printf("ERROR: Could not receive data for query <%s>", sqlQuery.Data());
2302                         delete result;
2303                         return -23;
2304                 }
2305         
2306         TString lastRunStr(row->GetField(0));
2307         Int_t lastRun = lastRunStr.Atoi();
2308         
2309         Printf("Last run with same run type %s is %d", runType.Data(), lastRun);
2310         
2311         delete row;
2312         row = 0;
2313         
2314         delete result;
2315         result = 0;
2316         
2317         server->Close();
2318         delete server;
2319         server = 0;
2320         
2321         return lastRun;
2322 }
2323 //-----------------------------------------------------------------
2324 Double_t AliGRPPreprocessor::CalculateMean(TObjArray* array){
2325
2326         //
2327         // Calculating mean over TObjArray from LHC Data
2328         //
2329
2330         TString timeStartString = (TString)GetRunParameter("DAQ_time_start");
2331         TString timeEndString = (TString)GetRunParameter("DAQ_time_end");
2332         if (timeStartString.IsNull() || timeStartString.IsNull()){
2333                 if (timeStartString.IsNull()){ 
2334                         AliError("DAQ_time_start not set in logbook! Setting statistical values for current DP to invalid");
2335                 }
2336                 else if (timeStartString.IsNull()){
2337                         AliError("DAQ_time_end not set in logbook! Setting statistical values for current DP to invalid");
2338                 }
2339                 return 0;
2340         }  
2341
2342         Int_t timeStart = (Int_t)(timeStartString.Atoi());
2343         Int_t timeEnd = (Int_t)(timeEndString.Atoi());
2344         timeStart = 1260646960;
2345         timeEnd = 1260652740;
2346         Double_t* parameters = new Double_t[5];
2347         parameters[0] = -1.;
2348         parameters[1] = -1.;
2349         parameters[2] = -1.;
2350         parameters[3] = -1.;
2351         parameters[4] = -1.;
2352         Int_t iCounts = 0;
2353         Int_t iCountsRun = 0;
2354         Int_t nCounts = array->GetEntries();
2355         printf("ncounts = %d\n",nCounts);
2356         Double_t valueBeforeSOR = 0;
2357         Double_t valueAfterEOR = 0;
2358         Double_t timestampBeforeSOR = -1.;
2359         Double_t timestampAfterEOR = -1.;
2360         Int_t ientrySOR = -1;
2361         Int_t ientryEOR = -1;
2362         Double_t* arrayValues = 0x0; 
2363         Double_t* arrayWeights = 0x0; 
2364         Bool_t truncMeanFlag = kTRUE;  // flag to indicate whether Truncated Mean should be calculated or not
2365         Bool_t sdFlag = kTRUE;  // flag to indicate whether SD (wrt Mean/Median) should be calculated or not
2366
2367         for(Int_t i = 0; i < nCounts; i++) {
2368                 AliDCSArray *dcs = (AliDCSArray*)array->At(i);
2369                 if((dcs->GetTimeStamp() >= timeStart) &&(dcs->GetTimeStamp() <= timeEnd)) {
2370                         AliDebug(2,Form("%d-th entry = %f at timestamp %f\n",i,(Double_t)(dcs->GetInt(0)),dcs->GetTimeStamp()));
2371                         iCounts += 1;
2372                         // look for the last value before SOR and the first value before EOR
2373                         if ((dcs->GetTimeStamp() >= timeStart) && (dcs->GetTimeStamp() < timeStart)) {
2374                                 timestampBeforeSOR = dcs->GetTimeStamp();
2375                                 AliDebug(2,Form("timestamp of last value before SOR = %f, with DAQ_time_start = %d\n",timestampBeforeSOR,timeStart));
2376                                 valueBeforeSOR = (Double_t)(dcs->GetInt(0));
2377                         }
2378                         else if ((dcs->GetTimeStamp() <= timeEnd) && (dcs->GetTimeStamp() > timeEnd) && timestampAfterEOR == -1){
2379                                 timestampAfterEOR = dcs->GetTimeStamp();
2380                                 valueAfterEOR = (Double_t)(dcs->GetInt(0));
2381                                 AliDebug(2,Form("timestamp of first value after EOR = %f, with DAQ_time_end = %d\n",timestampAfterEOR,timeEnd));
2382                         }
2383                         // check if there are DPs between DAQ_time_start and DAQ_time_end
2384                         if((dcs->GetTimeStamp() >= timeStart) &&(dcs->GetTimeStamp() <= timeEnd)) {
2385                                 if (ientrySOR == -1) ientrySOR = i;  // first entry after SOR
2386                                 if (ientryEOR < i) ientryEOR = i;  // last entry before EOR
2387                                 AliDebug(2,Form("entry between SOR and EOR\n"));
2388                                 iCountsRun += 1;
2389                         }
2390                 }
2391                 else {
2392                         printf("DCS values for the parameter outside the queried interval: timestamp = %f\n",dcs->GetTimeStamp());
2393                 }
2394         }
2395
2396         if (timestampBeforeSOR == -1.){
2397                 printf("No value found before SOR\n");
2398         }
2399         if (timestampAfterEOR == -1.){
2400                 printf("No value found after EOR\n");
2401         }
2402
2403         printf("Number of valid entries (within DCS query interval) = %i, from a total amount of %i entries\n",iCounts,nCounts);
2404         printf("Last value before DAQ_time_start (SOR) = %f at timestamp = %f\n",valueBeforeSOR,timestampBeforeSOR);
2405         printf("First value after DAQ_time_end (EOR)   = %f at timestamp = %f\n",valueAfterEOR,timestampAfterEOR);
2406         printf("Found %d entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)\n",iCountsRun);
2407         printf("Index of first entry after DAQ_time_start (SOR) = %d\n ",ientrySOR);
2408         printf("Index of first entry before DAQ_time_end (EOR) = %d\n ",ientryEOR);
2409
2410         Int_t nentriesUsed = 0;
2411         if (iCountsRun > 1){
2412                 printf("Using entries between DAQ_time_start (SOR) and DAQ_time_end (EOR)\n");
2413                 printf("Calculating (weighted) Mean and Median\n" );
2414                 arrayValues = new Double_t[iCountsRun]; 
2415                 arrayWeights = new Double_t[iCountsRun]; 
2416                 nentriesUsed = iCountsRun;
2417                 for (Int_t i = ientrySOR; i <= ientryEOR; i++){
2418                         AliDCSArray *dcs = (AliDCSArray *)array->At(i);
2419                         Double_t timestamp2 = 0;
2420                         if (i < ientryEOR){
2421                                 AliDCSArray *dcs1 = (AliDCSArray *)array->At(i+1);
2422                                 timestamp2 = dcs1->GetTimeStamp();
2423                         }
2424                         else {
2425                                 timestamp2 = (Double_t)timeEnd+1;
2426                         }
2427                         arrayWeights[i-ientrySOR] = (Double_t)((Double_t)timestamp2 - dcs->GetTimeStamp());
2428                         arrayValues[i-ientrySOR] = (Double_t)(dcs->GetInt(0));
2429                         printf("Entry %d: value = %f, weight = %f\n",i-ientrySOR,arrayValues[i-ientrySOR],arrayWeights[i-ientrySOR]);
2430                 }
2431                 parameters[0] = TMath::Mean(iCountsRun,arrayValues,arrayWeights);
2432                 parameters[2] = TMath::Median(iCountsRun,arrayValues,arrayWeights);
2433         }
2434         else if (iCountsRun == 1){
2435                 AliDCSArray* dcs = (AliDCSArray *)array->At(ientrySOR);
2436                 nentriesUsed = 2;
2437                 if (timestampBeforeSOR != -1 && timestampBeforeSOR != (Int_t)dcs->GetTimeStamp()){
2438                         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");
2439                         arrayValues = new Double_t[2];
2440                         arrayWeights = new Double_t[2];
2441                         arrayValues[0] = valueBeforeSOR;
2442                         arrayWeights[0] = (Double_t)(dcs->GetTimeStamp()-(Double_t)timestampBeforeSOR);
2443                         arrayValues[1] = (Double_t)(dcs->GetInt(0));
2444                         arrayWeights[1] = (Double_t)((Double_t)timeEnd+1-dcs->GetTimeStamp());
2445                         printf("value0 = %f, with weight = %f\n",arrayValues[0],arrayWeights[0]); 
2446                         printf("value1 = %f, with weight = %f\n",arrayValues[1],arrayWeights[1]); 
2447                         parameters[0] = TMath::Mean(2,arrayValues,arrayWeights);
2448                         parameters[2] = TMath::Median(2,arrayValues,arrayWeights);
2449                         truncMeanFlag = kFALSE;
2450                 }
2451                 else{
2452                         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");
2453                         parameters[0] = -1;
2454                         parameters[1] = -1;
2455                         parameters[2] = -1;
2456                         parameters[3] = -1;
2457                         parameters[4] = -1;
2458                         return parameters[0];
2459                 }
2460         }
2461         else { // iCountsRun == 0, using only the point immediately before SOR
2462                 if (timestampBeforeSOR == -1.){
2463                         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");
2464                         parameters[0] = -1;
2465                         parameters[1] = -1;
2466                         parameters[2] = -1;
2467                         parameters[3] = -1;
2468                         parameters[4] = -1;
2469                         return parameters[0];
2470                 }
2471                 else {
2472                         printf("Using only last entry before SOR. Truncated mean and Standard deviations (wrt mean/median) won't be calculated.\n");
2473                         printf("value = %f\n",valueBeforeSOR); 
2474                         parameters[0] = valueBeforeSOR;
2475                         parameters[2] = valueBeforeSOR;
2476                         truncMeanFlag = kFALSE;
2477                         sdFlag = kFALSE;
2478                 }
2479         }
2480
2481         Double_t temp = 0;
2482         Double_t temp1 = 0;
2483         Double_t sumweights = 0; 
2484         Int_t entriesTruncMean = 0;
2485         Double_t* arrayValuesTruncMean = new Double_t[nentriesUsed]; 
2486         Double_t* arrayWeightsTruncMean = new Double_t[nentriesUsed]; 
2487
2488         // calculating SD wrt Mean and Median
2489         printf("Calculating SD wrt Mean and SD wrt Median\n");
2490         if (sdFlag){
2491                 for (Int_t i =0; i< nentriesUsed; i++){
2492                         //printf("Entry %d: value = %f, weight = %f\n",i,arrayValues[i],arrayWeights[i]);
2493                         temp += (arrayValues[i]-parameters[2])*(arrayValues[i]-parameters[2]);
2494                         temp1 += arrayWeights[i]*(arrayValues[i]-parameters[0])*(arrayValues[i]-parameters[0]);
2495                         sumweights += arrayWeights[i];
2496                 }
2497                 // setting SD wrt Mean 
2498                 if (sumweights != 0 ){
2499                         parameters[3] = TMath::Sqrt(temp1/sumweights);
2500                 }
2501                 else {
2502                         printf("Sum of weights to calculate Standard Deviation (wrt mean) <= 0, setting the SD to invalid\n");
2503                         parameters[3] = -1;
2504                 }
2505                 // setting SD wrt Median
2506                 if (nentriesUsed != 0){
2507                         parameters[4] = TMath::Sqrt(temp/nentriesUsed);
2508                 }
2509                 else{
2510                         printf("Number of entries used to calculate Standard Deviation (wrt median) <= 0, setting the SD to invalid\n");
2511                         parameters[4] = -1;
2512                 }
2513         }
2514         else {
2515                 parameters[3] = -1;
2516                 parameters[4] = -1;
2517         }               
2518
2519         // calculating truncated mean (this comes afterwards since you need the SD wrt Mean)
2520         if (truncMeanFlag){
2521                 printf("Calculating Truncated Mean\n");
2522                 for (Int_t i =0; i< nentriesUsed; i++){
2523                         //printf("Entry %d: value = %f, weight = %f\n",i,arrayValues[i],arrayWeights[i]);
2524                         if ((arrayValues[i]<=parameters[0]+3*parameters[3]) && (arrayValues[i]>=parameters[0]-3*parameters[3])){
2525                                 arrayValuesTruncMean[entriesTruncMean]=arrayValues[i];
2526                                 arrayWeightsTruncMean[entriesTruncMean]=arrayWeights[i];
2527                                 printf("For Truncated Mean: Entry %d: value = %f, weight = %f\n",entriesTruncMean,arrayValuesTruncMean[entriesTruncMean],arrayWeightsTruncMean[entriesTruncMean]);
2528                                 entriesTruncMean++;                     
2529                         }
2530                         else{
2531                                 printf("Discarding entry\n");
2532                         }
2533                 }
2534                 // setting truncated mean 
2535                 if (entriesTruncMean >1){
2536                         printf("%d entries used for truncated mean\n",entriesTruncMean);
2537                         parameters[1] = TMath::Mean(entriesTruncMean,arrayValuesTruncMean,arrayWeightsTruncMean);
2538                 }
2539                 else{   
2540                         printf("Too few entries (%d) to calculate truncated mean\n",entriesTruncMean);
2541                         parameters[1] = -1;
2542                 }
2543         }
2544         else{
2545                         parameters[1] = -1;
2546         }
2547         
2548         printf("(weighted) mean = %f \n",parameters[0]);
2549         printf("(weighted) truncated mean = %f \n",parameters[1]);
2550         printf("median = %f \n",parameters[2]);
2551         printf("(weighted) standard deviation with (weighted) mean = %f \n",parameters[3]);
2552         printf("standard deviation with median = %f \n",parameters[4]);
2553         
2554         return (parameters[0]);
2555 }
2556 //------------------------------------------------------------------------------------------------------
2557 Float_t AliGRPPreprocessor::ProcessEnergy(TObjArray* array, Double_t timeStart, Double_t timeEnd){
2558
2559         //
2560         // Method to processo LHC Energy information
2561         // Only the first value is returned, provided that it is withing DAQ_time_start and DAQ_time_end
2562         //
2563
2564         Int_t nCounts = array->GetEntries();
2565         Float_t energy = -1;
2566         AliDebug(2,Form("Energy measurements = %d\n",nCounts));
2567         for(Int_t i = 0; i < nCounts; i++) {
2568                 AliDCSArray *dcs = (AliDCSArray*)array->At(i);
2569                 if((dcs->GetTimeStamp() >= timeStart) &&(dcs->GetTimeStamp() <= timeEnd)) {
2570                         energy = (Float_t)(TMath::Nint(((Double_t)(dcs->GetInt(0)))*120/1000)); // sqrt(s)/2 energy in GeV
2571                         AliInfo(Form("Energy value found = %d, converting --> sqrt(s)/2 = %f (GeV)", dcs->GetInt(0),energy));
2572                         break;
2573                 }
2574                 else {
2575                         AliError("No energy values found between DAQ_time_start and DAQ_time_end - energy will remain invalid!");
2576                 }
2577         }
2578
2579         return energy;
2580 }