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