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