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