69a5c1300acedcd7e58d7a1b42f3550921f6f2b0
[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 //-------------------------------------------------------------------------
24
25 #include <TChain.h>
26 #include <TList.h>
27 #include <TMap.h>
28 #include <TObjString.h>
29 #include <TGraph.h>
30
31 #include "AliGRPPreprocessor.h"
32 #include "AliGRPObject.h"
33 #include "AliDCSSensor.h"
34 #include "AliSplineFit.h"
35 #include "AliDCSSensorArray.h"
36
37 #include "AliTriggerConfiguration.h"
38 #include "AliTriggerRunScalers.h"
39
40 #include "AliCDBMetaData.h"
41 #include "AliLog.h"
42
43 class AliDCSValue;
44 class AliShuttleInterface;
45
46 // needed for ReceivePromptRecoParameters
47
48 #include <TSQLServer.h>
49 #include <TSQLResult.h>
50 #include <TSQLRow.h>
51 #include <AliCDBManager.h>
52 #include <AliCDBMetaData.h>
53 #include <AliCDBId.h>
54 #include <AliTriggerConfiguration.h>
55
56 const Double_t kFitFraction = 0.7;                 // Fraction of DCS sensor fits required
57
58 ClassImp(AliGRPPreprocessor)
59
60 //_______________________________________________________________
61
62   const Int_t AliGRPPreprocessor::fgknDAQLbPar = 8; // num parameters in the logbook
63   const Int_t AliGRPPreprocessor::fgknDCSDP = 50;   // number of dcs dps
64   const Int_t AliGRPPreprocessor::fgknDCSDPHallProbes = 40;   // number of dcs dps
65   const char* AliGRPPreprocessor::fgkDCSDataPoints[AliGRPPreprocessor::fgknDCSDP] = {
66                    "LHCState",              // missing in DCS
67                    "L3Polarity",
68                    "DipolePolarity",
69                    "LHCLuminosity",         // missing in DCS
70                    "BeamIntensity",         // missing in DCS
71                    "L3Current",
72                    "DipoleCurrent",
73                    "L3_BSF17_H1",
74                    "L3_BSF17_H2",
75                    "L3_BSF17_H3",
76                    "L3_BSF17_Temperature",
77                    "L3_BSF4_H1",
78                    "L3_BSF4_H2",
79                    "L3_BSF4_H3",
80                    "L3_BSF4_Temperature",
81                    "L3_BKF17_H1",
82                    "L3_BKF17_H2",
83                    "L3_BKF17_H3",
84                    "L3_BKF17_Temperature",
85                    "L3_BKF4_H1",
86                    "L3_BKF4_H2",
87                    "L3_BKF4_H3",
88                    "L3_BKF4_Temperature",
89                    "L3_BSF13_H1",
90                    "L3_BSF13_H2",
91                    "L3_BSF13_H3",
92                    "L3_BSF13_Temperature",
93                    "L3_BSF8_H1",
94                    "L3_BSF8_H2",
95                    "L3_BSF8_H3",
96                    "L3_BSF8_Temperature",
97                    "L3_BKF13_H1",
98                    "L3_BKF13_H2",
99                    "L3_BKF13_H3",
100                    "L3_BKF13_Temperature",
101                    "L3_BKF8_H1",
102                    "L3_BKF8_H2",
103                    "L3_BKF8_H3",
104                    "L3_BKF8_Temperature",
105                    "Dipole_Inside_H1",
106                    "Dipole_Inside_H2",
107                    "Dipole_Inside_H3",
108                    "Dipole_Inside_Temperature",
109                    "Dipole_Outside_H1",
110                    "Dipole_Outside_H2",
111                    "Dipole_Outside_H3",
112                    "Dipole_Outside_Temperature",
113                    "CavernTemperature",
114                    "CavernAtmosPressure",
115                    "SurfaceAtmosPressure"
116                  };
117
118   const char* AliGRPPreprocessor::fgkDCSDataPointsHallProbes[AliGRPPreprocessor::fgknDCSDPHallProbes] = {
119                    "L3_BSF17_H1",
120                    "L3_BSF17_H2",
121                    "L3_BSF17_H3",
122                    "L3_BSF17_Temperature",
123                    "L3_BSF4_H1",
124                    "L3_BSF4_H2",
125                    "L3_BSF4_H3",
126                    "L3_BSF4_Temperature",
127                    "L3_BKF17_H1",
128                    "L3_BKF17_H2",
129                    "L3_BKF17_H3",
130                    "L3_BKF17_Temperature",
131                    "L3_BKF4_H1",
132                    "L3_BKF4_H2",
133                    "L3_BKF4_H3",
134                    "L3_BKF4_Temperature",
135                    "L3_BSF13_H1",
136                    "L3_BSF13_H2",
137                    "L3_BSF13_H3",
138                    "L3_BSF13_Temperature",
139                    "L3_BSF8_H1",
140                    "L3_BSF8_H2",
141                    "L3_BSF8_H3",
142                    "L3_BSF8_Temperature",
143                    "L3_BKF13_H1",
144                    "L3_BKF13_H2",
145                    "L3_BKF13_H3",
146                    "L3_BKF13_Temperature",
147                    "L3_BKF8_H1",
148                    "L3_BKF8_H2",
149                    "L3_BKF8_H3",
150                    "L3_BKF8_Temperature",
151                    "Dipole_Inside_H1",
152                    "Dipole_Inside_H2",
153                    "Dipole_Inside_H3",
154                    "Dipole_Inside_Temperature",
155                    "Dipole_Outside_H1",
156                    "Dipole_Outside_H2",
157                    "Dipole_Outside_H3",
158                    "Dipole_Outside_Temperature",
159                  };
160                  
161   const Short_t kSensors = 48; // start index position of sensor in DCS DPs
162   const Short_t kNumSensors = 2; // Number of sensors in DCS DPs
163
164   const char* AliGRPPreprocessor::fgkLHCState[20] = {
165                    "P", "PREPARE",
166                    "J", "PREINJECTION",
167                    "I", "INJECTION",
168                    "F", "FILLING",
169                    "A", "ADJUST",
170                    "U", "UNSTABLE BEAMS",
171                    "S", "STABLE BEAMS",
172                    "D", "BEAM DUMP",
173                    "R", "RECOVER",
174                    "C", "PRECYCLE"
175                  };
176
177   const char* kppError[] = {
178                    "",
179                    "(DAQ logbook ERROR)",
180                    "(DAQ FXS ERROR)",
181                    "(DCS FXS ERROR)",
182                    "(DCS data points ERROR)",
183                    "(Trigger Configuration ERROR)"
184   };
185
186 //_______________________________________________________________
187
188 AliGRPPreprocessor::AliGRPPreprocessor(AliShuttleInterface* shuttle):
189         AliPreprocessor("GRP",shuttle),  fPressure(0)
190 {
191         // constructor - shuttle must be instantiated!
192
193         AddRunType("COSMIC");
194         AddRunType("LASER");
195         AddRunType("PHYSICS");
196         AddRunType("CALIBRATION_BC");
197         AddRunType("CALIBRATION_CENTRAL");
198         AddRunType("CALIBRATION_EMD");
199         AddRunType("CALIBRATION_MB");
200         AddRunType("CALIBRATION_SEMICENTRAL");
201         AddRunType("CALIBRATION");
202         AddRunType("PEDESTAL");
203         AddRunType("STANDALONE");
204         AddRunType("GAIN");
205         AddRunType("NOISE");
206         AddRunType("PULSER");
207         AddRunType("STANDALONE_PULSER");
208 }
209
210 //_______________________________________________________________
211
212 AliGRPPreprocessor::~AliGRPPreprocessor()
213 {
214         //destructor
215         
216         delete fPressure;
217 }
218
219 //_______________________________________________________________
220
221 void AliGRPPreprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)
222 {
223   // Initialize preprocessor
224
225   AliPreprocessor::Initialize(run, startTime, endTime);
226
227   AliInfo("Initialization of the GRP preprocessor.");
228   TClonesArray * array = new TClonesArray("AliDCSSensor",kNumSensors); 
229   for(Int_t j = 0; j < kNumSensors; j++) {
230     AliDCSSensor * sens = new ((*array)[j])AliDCSSensor;
231     sens->SetStringID(fgkDCSDataPoints[j+kSensors]);
232   }
233   AliInfo(Form("Pressure Entries: %d",array->GetEntries()));
234
235   //  fPressure = new AliDCSSensorArray(fStartTime, fEndTime, array);
236   fPressure = new AliDCSSensorArray(GetStartTimeDCSQuery(), GetEndTimeDCSQuery(), array);
237 }
238
239 //_______________________________________________________________
240
241 UInt_t AliGRPPreprocessor::Process(TMap* valueMap)
242 {
243         // process data retrieved by the Shuttle
244         
245         AliGRPObject *grpobj = new AliGRPObject();  // object to store data
246
247         //=================//
248         // DAQ logbook     //
249         //=================//
250         UInt_t error = 0;
251         
252         grpobj = ProcessDaqLB();
253
254         //=================//
255         // DAQ FXS         //
256         //=================//
257         UInt_t iDaqFxs = ProcessDaqFxs();
258         if( iDaqFxs == 0 ) {
259                 Log(Form("DAQ FXS, successful!"));
260         } else {
261                 Log(Form("DAQ FXS, could not store run raw tag file!!!"));
262                 error |= 2;
263         }
264         
265         //=================//
266         // DCS FXS         //
267         //=================//
268         UInt_t iDcsFxs = ProcessDcsFxs();
269         if( iDcsFxs == 0 ) {
270                 Log(Form("DCS FXS, successful!"));
271         } else {
272                 Log(Form("DCS FXS, Could not store CTP scalers!!!"));
273                 error |= 4;
274         }
275         
276         //=================//
277         // DCS data points //
278         //=================//
279         Log(Form("Starting DCS Query at %d and finishing at %d",GetStartTimeDCSQuery(),GetEndTimeDCSQuery()));
280         Int_t entries = ProcessDcsDPs( valueMap, grpobj );
281         Log(Form("entries found = %d",entries));
282         if( entries < fgknDCSDP-4 ) { // FIXME (!= ) LHState, LHCLuminosity, BeamIntensity, LH3_BSF4_H3 are not working yet...  
283                 Log(Form("Problem with the DCS data points!!!"));
284                 error |= 8;
285         } else  Log(Form("DCS data points, successful!"));
286         
287         //=======================//
288         // Trigger Configuration //
289         //=======================//
290         // either from DAQ logbook.....
291         const char * triggerConf = GetTriggerConfiguration();
292         if (triggerConf!= NULL) {
293                 Log("Found trigger configuration in DAQ logbook");
294                 AliTriggerConfiguration *runcfg = AliTriggerConfiguration::LoadConfigurationFromString(triggerConf);      
295                 if (!runcfg) {
296                         Log("Bad CTP run configuration file from DAQ logbook! The corresponding CDB entry will not be filled!");
297                         error |= 16;
298                 }
299                 else {
300                         TString titleCTPcfg = Form("CTP cfg for run %i from DAQ",fRun);
301                         runcfg->SetTitle(titleCTPcfg);
302                         AliCDBMetaData metaData;
303                         metaData.SetBeamPeriod(0);
304                         metaData.SetResponsible("Roman Lietava");
305                         metaData.SetComment("CTP run configuration from DAQ logbook");
306                         if (!Store("CTP","Config", runcfg, &metaData, 0, 0)) {
307                                 Log("Unable to store the CTP run configuration object to OCDB!");
308                                 error |= 16;
309                         }
310                 }
311         }
312         /*  the DCS should not been used any more to access this stuff!!!
313         // ...or from DCS FXS
314         else{
315                 Log("No trigger configuration found in the DAQ logbook!! Trying reading from DCS FXS...");
316                 TString runcfgfile = GetFile(kDCS, "CTP_runconfig", "");
317                 if (runcfgfile.IsNull()) {
318                         Log("No CTP runconfig files has been found in DCS FXS!");
319                         error |= 16;
320                 }
321                 else {
322                         Log(Form("File with Id CTP_runconfig found! Copied to %s",runcfgfile.Data()));
323                         AliTriggerConfiguration *runcfg = AliTriggerConfiguration::LoadConfiguration(runcfgfile);
324                         if (!runcfg) {
325                                 Log("Bad CTP run configuration file from DCS FXS! The corresponding CDB entry will not be filled!");
326                                 error |= 16;;
327                         }
328                         else {
329                                 TString titleCTPcfg = Form("CTP cfg for run %i from DCS",fRun);
330                                 runcfg->SetTitle(titleCTPcfg);
331                                 AliCDBMetaData metaData;
332                                 metaData.SetBeamPeriod(0);
333                                 metaData.SetResponsible("Roman Lietava");
334                                 metaData.SetComment("CTP run configuration from DCS FXS");
335                                 if (!Store("CTP","Config", runcfg, &metaData, 0, 0)) {
336                                         Log("Unable to store the CTP run configuration object to OCDB!");
337                                         error |= 16;
338                                 }
339                         }
340                 }
341         }
342         */
343         AliCDBMetaData md;
344         md.SetResponsible("Ernesto Lopez Torres");
345         md.SetComment("Output parameters from the GRP preprocessor.");
346         
347         Bool_t result = kTRUE;
348         Log("Before storing");
349         result = Store("GRP", "Data", grpobj, &md); 
350         delete grpobj;
351         
352         if (result && !error ) {
353                 Log("GRP Preprocessor Success");
354                 return 0;
355         } else {
356                 Log( Form("GRP Preprocessor FAILS!!! %s%s%s%s%s",
357                           kppError[(error&1)?1:0],
358                           kppError[(error&2)?2:0],
359                           kppError[(error&4)?3:0],
360                           kppError[(error&8)?4:0],
361                           kppError[(error&16)?5:0]
362                           ));
363                 return error;
364         }
365 }
366
367 //_______________________________________________________________
368
369 AliGRPObject* AliGRPPreprocessor::ProcessDaqLB()
370 {
371         //Getting the DAQ lb information
372         
373         time_t timeStart         = (time_t)(((TString)GetRunParameter("DAQ_time_start")).Atoi());
374         time_t timeEnd         = (time_t)(((TString)GetRunParameter("DAQ_time_end")).Atoi());
375         Float_t beamEnergy         = (Float_t)(((TString)GetRunParameter("beamEnergy")).Atof());
376         TString beamType = (TString)GetRunParameter("beamType");
377         Char_t numberOfDetectors = (Char_t)(((TString)GetRunParameter("numberOfDetectors")).Atoi());
378         UInt_t  detectorMask= (UInt_t)(((TString)GetRunParameter("detectorMask")).Atoi());
379         TString lhcPeriod = (TString)GetRunParameter("LHCperiod");
380         TString runType = (TString)GetRunType();
381
382         AliGRPObject* grpObj = new AliGRPObject();
383
384         if (timeStart != 0){
385                 grpObj->SetTimeStart(timeStart);
386                 Log(Form("Start time for run %d: %d",fRun, (Int_t)timeStart));
387         } 
388         else {
389                 Log(Form("Start time not put in logbook, setting to invalid in GRP entry!"));
390         }
391
392         if (timeEnd != 0){
393                 grpObj->SetTimeEnd(timeEnd);
394                 Log(Form("End time for run %d: %i",fRun, (Int_t)timeEnd));
395         } 
396         else {
397                 Log(Form("End time not put in logbook, setting to invalid in GRP entry!"));
398         }
399
400         if (beamEnergy != 0){
401                 grpObj->SetBeamEnergy(beamEnergy);
402                 Log(Form("Beam Energy for run %d: %f",fRun, beamEnergy));
403         } 
404         else {
405                 Log(Form("Beam Energy not put in logbook, setting to invalid in GRP entry!"));
406         }
407
408                 Log(Form("Beam Type for run %d: %s",fRun, beamType.Data()));
409                 
410         if (beamType.Length() != 0){
411                 grpObj->SetBeamType(beamType);
412                 Log(Form("Beam Type for run %d: %s",fRun, beamType.Data()));
413         } 
414         else {
415                 Log(Form("Beam Type not put in logbook, setting to invalid in GRP entry!"));
416         }
417                 
418         if (numberOfDetectors != 0){
419                 grpObj->SetNumberOfDetectors(numberOfDetectors);
420                 Log(Form("Number Of Detectors for run %d: %d",fRun, (Int_t)numberOfDetectors));
421         } 
422         else {
423                 Log(Form("Number Of Detectors not put in logbook, setting to invalid in GRP entry!"));
424         }
425
426         if (detectorMask != 0){
427                 grpObj->SetDetectorMask(detectorMask);
428                 Log(Form("Detector Mask for run %d: %d",fRun, detectorMask));
429         } 
430         else {
431                 Log(Form("Detector Mask not put in logbook, setting to invalid in GRP entry!"));
432         }
433
434         if (lhcPeriod.Length() != 0) {
435                 grpObj->SetLHCPeriod(lhcPeriod);
436                 Log(Form("LHC period (DAQ) for run %d: %s",fRun, lhcPeriod.Data()));
437         } else {
438                 Log(Form("LHCperiod not put in logbook, setting to invalid in GRP entry!"));
439         }
440         if (runType.Length() != 0) {
441                 grpObj->SetRunType(runType);
442                 Log(Form("Run Type (DAQ) for run %d: %s",fRun, runType.Data()));
443         } else {
444                 Log(Form("Run Type not put in logbook, setting to invalid in GRP entry!"));
445         }
446
447         return grpObj;
448 }
449
450 //_______________________________________________________________
451
452 UInt_t AliGRPPreprocessor::ProcessDaqFxs()
453 {
454         //======DAQ FXS======//
455         
456         TList* list = GetFileSources(kDAQ);  
457         if (!list) {
458                 Log("No raw data tag list: connection problems with DAQ FXS logbook!");
459                 return 1;
460         }
461         
462         if (list->GetEntries() == 0) {
463                 Log("no raw data tags in this run: nothing to merge!");
464                 delete  list; list=0;
465                 return 0;
466         }
467         
468         TChain *fRawTagChain = new TChain("T");
469         Int_t nFiles=0;
470         TIterator* iter = list->MakeIterator();
471         TObject* obj = 0;
472         while ((obj = iter->Next())) {
473                 TObjString* objStr = dynamic_cast<TObjString*> (obj);
474                 if (objStr) {
475                         Log(Form("Found source %s", objStr->String().Data()));
476                         TList* list2 = GetFileIDs(kDAQ, objStr->String());
477                         if (!list2) {
478                                 Log("No list with ids from DAQ was found: connection problems with DAQ FXS logbook!");
479                                 delete fRawTagChain; fRawTagChain=0;
480                                 return 1;
481                         }
482                         Log(Form("Number of ids: %d",list2->GetEntries()));
483                         for(Int_t i = 0; i < list2->GetEntries(); i++) {
484                                 TObjString *idStr = (TObjString *)list2->At(i);
485                                 TString fileName = GetFile(kDAQ,idStr->String().Data(),objStr->String().Data());
486                                 if (fileName.Length() > 0) {
487                                         Log(Form("Adding file in the chain: %s",fileName.Data()));
488                                         fRawTagChain->Add(fileName.Data());
489                                         nFiles++;
490                                 } else {
491                                         Log(Form("Could not retrieve file with id %s from source %s: "
492                                                  "connection problems with DAQ FXS!",
493                                                  idStr->String().Data(), objStr->String().Data()));
494                                         delete list; list=0;
495                                         delete list2; list2=0;
496                                         delete fRawTagChain; fRawTagChain=0;
497                                         return 2;
498                                 }
499                         }
500                         delete list2;
501                 }
502         }
503         
504         TString fRawDataFileName = "GRP_Merged.tag.root";
505         Log(Form("Merging %d raw data tags into file: %s", nFiles, fRawDataFileName.Data()));
506         
507         if( fRawTagChain->Merge(fRawDataFileName) < 1 ) {
508                 Log("Error merging raw data files!!!");
509                 return 3;
510         }
511         
512         TString outputfile = Form("Run%d.Merged.RAW.tag.root", fRun);
513         Bool_t result = StoreRunMetadataFile(fRawDataFileName.Data(),outputfile.Data());
514         
515         if (!result) {
516                 Log("Problem storing raw data tags in local file!!!");
517         } else {
518                 Log("Raw data tags merged successfully!!");
519         }
520         
521         delete iter;
522         delete list;
523         delete fRawTagChain; fRawTagChain=0;
524         
525         if (result == kFALSE) {
526                 return 4;
527         }
528         
529         return 0;
530         
531 }
532
533 //_______________________________________________________________
534 UInt_t AliGRPPreprocessor::ProcessDcsFxs()
535 {
536
537         // processing the info
538         // stored in the DCS FXS
539         // coming from the trigger
540
541         {
542                 // Get the CTP counters information
543                 TList* list = GetFileSources(kDCS,"CTP_xcounters");  
544                 if (!list) {
545                         Log("No CTP counters file: connection problems with DCS FXS logbook!");
546                         return 1;
547                 }
548                 
549                 if (list->GetEntries() == 0) {
550                         Log("No CTP counters file to be processed!");
551                         return 1;
552                 }
553                 else {
554                         TIter iter(list);
555                         TObjString *source;
556                         while ((source = dynamic_cast<TObjString *> (iter.Next()))) {
557                                 TString countersfile = GetFile(kDCS, "CTP_xcounters", source->GetName());
558                                 if (countersfile.IsNull()) {
559                                         Log("No CTP counters files has been found: empty source!");
560                                 }
561                                 else {
562                                         Log(Form("File with Id CTP_xcounters found in source %s! Copied to %s",source->GetName(),countersfile.Data()));
563                                         AliTriggerRunScalers *scalers = AliTriggerRunScalers::ReadScalers(countersfile);
564                                         if (!scalers) {
565                                                 Log("Bad CTP counters file! The corresponding CDB entry will not be filled!");
566                                                 return 1;
567                                         }
568                                         else {
569                                                 AliCDBMetaData metaData;
570                                                 metaData.SetBeamPeriod(0);
571                                                 metaData.SetResponsible("Roman Lietava");
572                                                 metaData.SetComment("CTP scalers");
573                                                 if (!Store("CTP","Scalers", scalers, &metaData, 0, 0)) {
574                                                         Log("Unable to store the CTP scalers object to OCDB!");
575                                                 }
576                                         }
577                                 }
578                         }
579                 }
580                 delete list;
581         }
582         
583         return 0;
584 }
585 //_______________________________________________________________
586
587 Int_t AliGRPPreprocessor::ProcessDcsDPs(TMap* valueMap, AliGRPObject* grpObj)
588 {
589
590         //
591         // processing DCS DPs
592         //
593
594         Int_t entries = 0;  // counting the entries that are in the DCS DB, not taking care whether they have values or not
595         Int_t nLHCEntries = 0;
596         Int_t nL3Entries = 0;
597         Int_t nDipoleEntries = 0;
598         Int_t nEnvEntries = 0;
599         Int_t nHallProbesEntries = 0;
600         nLHCEntries = ProcessLHCDPs(valueMap, grpObj);
601         nL3Entries = ProcessL3DPs(valueMap, grpObj);
602         nDipoleEntries = ProcessDipoleDPs(valueMap, grpObj);
603         nEnvEntries = ProcessEnvDPs(valueMap, grpObj);
604         nHallProbesEntries = ProcessHPDPs(valueMap, grpObj);
605
606         entries = nLHCEntries + nL3Entries + nDipoleEntries + nEnvEntries + nHallProbesEntries;
607         return entries;
608
609 }
610
611 //_______________________________________________________________
612
613 Int_t AliGRPPreprocessor::ProcessL3DPs(const TMap* valueMap, AliGRPObject* grpObj)
614 {
615
616         // processing DPs
617         // related to 
618         // L3 info
619
620         Int_t nL3Entries = 0;
621         TObjArray *array = 0x0;
622         Int_t indexDP = -1;
623
624         AliInfo(Form("==========L3Polarity==========="));
625         indexDP = kL3Polarity;
626         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
627         if(!array) {
628                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
629         } 
630         else {
631                 if (array->GetEntries() == 0){
632                         AliError(Form("No entries found in array! setting %s Polarity to invalid...",fgkDCSDataPoints[indexDP]));
633                 }
634                 else {
635                         Char_t charDCS = ProcessBool(array);
636                         grpObj->SetL3Polarity(charDCS);
637                         AliInfo(Form("%s set to %d",fgkDCSDataPoints[indexDP],(Int_t)(grpObj->GetL3Polarity())));
638                 }
639                 nL3Entries++;
640         }
641
642         if (array) array = 0x0;
643
644         AliInfo(Form("==========L3Current==========="));
645         indexDP = kL3Current;
646         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
647         if(!array) {
648                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
649         } 
650         else {
651                 if (array->GetEntries() == 0){
652                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
653                 }
654                 else {
655                         Float_t *floatDCS = ProcessFloatAll(array);
656                         grpObj->SetL3Current(floatDCS);
657                         delete floatDCS;
658                 }
659                 nL3Entries++;
660         }
661
662         return nL3Entries;
663
664 }
665 //_______________________________________________________________
666
667 Int_t AliGRPPreprocessor::ProcessDipoleDPs(const TMap* valueMap, AliGRPObject* grpObj)
668 {
669         // processing DPs
670         // related to 
671         // the Dipole info
672
673         Int_t nDipoleEntries = 0;
674         TObjArray *array = 0x0;
675         Int_t indexDP = -1;
676
677         AliInfo(Form("==========DipolePolarity==========="));
678         indexDP = kDipolePolarity;
679         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
680         if(!array) {
681                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
682         } 
683         else {
684                 if (array->GetEntries() == 0){
685                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
686                 }
687                 else {
688                         Char_t charDCS = ProcessBool(array);
689                         grpObj->SetDipolePolarity(charDCS);
690                         AliInfo(Form("%s set to %d",fgkDCSDataPoints[indexDP],(Int_t)(grpObj->GetDipolePolarity())));
691                 }
692                 nDipoleEntries++;
693         }
694
695         if (array) array = 0x0;
696
697         AliInfo(Form("==========DipoleCurrent==========="));
698         indexDP = kDipoleCurrent;
699         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
700         if(!array) {
701                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
702         } 
703         else {
704                 if (array->GetEntries() == 0){
705                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
706                 }
707                 else {
708                         Float_t *floatDCS = ProcessFloatAll(array);
709                         grpObj->SetDipoleCurrent(floatDCS);
710                         delete floatDCS;
711                 }
712                 nDipoleEntries++;
713         }
714
715         return nDipoleEntries;
716
717 }
718 //_______________________________________________________________
719
720 Int_t AliGRPPreprocessor::ProcessEnvDPs(TMap* valueMap, AliGRPObject* grpObj)
721 {
722         // processing DPs
723         // related to 
724         // evironment conditions (temperature, pressure) info
725
726         Int_t nEnvEntries = 0;
727         TObjArray *array = 0x0;
728         Int_t indexDP = -1;
729
730         AliInfo(Form("==========CavernTemperature==========="));
731         indexDP = kCavernTemperature;
732         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
733         if(!array) {
734                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
735         } 
736         else {
737                 if (array->GetEntries() == 0){
738                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
739                 }
740                 else {
741                         Float_t *floatDCS = ProcessFloatAll(array);
742                         grpObj->SetCavernTemperature(floatDCS);
743                         delete floatDCS;
744                 }
745                 nEnvEntries++;
746         }
747
748         if (array) array = 0x0;
749
750         AliInfo(Form("==========AtmosPressures (Cavern + Surface)==========="));
751         AliDCSSensorArray *dcsSensorArray = GetPressureMap(valueMap);
752         dcsSensorArray->Print();
753         if( fPressure->NumFits()==0 ) {
754                 Log("Problem with the pressure sensor values!!!");
755         } 
756         else {
757                 AliInfo(Form("==========CavernAtmosPressure==========="));
758                 indexDP = kCavernAtmosPressure;
759                 AliDCSSensor* sensorCavernP2 = dcsSensorArray->GetSensor(fgkDCSDataPoints[indexDP]);
760                 AliDebug(2,Form("sensorCavernP2 = %p", sensorCavernP2));
761                 if( sensorCavernP2->GetFit() ) {
762                         Log(Form("<%s> for run %d: Sensor Fit found",fgkDCSDataPoints[indexDP], fRun));
763                         grpObj->SetCavernAtmosPressure(sensorCavernP2);
764                         nEnvEntries++;
765                 } 
766                 //if (sensorP2) delete sensorP2;
767                 else {
768                         Log(Form("ERROR Sensor Fit for %s not found: ", fgkDCSDataPoints[indexDP] ));
769                 }
770                 AliInfo(Form("==========SurfaceAtmosPressure==========="));
771                 indexDP = kSurfaceAtmosPressure;
772                 AliDCSSensor* sensorP2 = dcsSensorArray->GetSensor(fgkDCSDataPoints[indexDP]);
773                 AliDebug(2,Form("sensorP2 = %p", sensorP2));
774                 if( sensorP2->GetFit() ) {
775                         Log(Form("<%s> for run %d: Sensor Fit found",fgkDCSDataPoints[indexDP], fRun));
776                         grpObj->SetSurfaceAtmosPressure(sensorP2);
777                         nEnvEntries++;
778                 } 
779                 //if (sensorP2) delete sensorP2;
780                 else {
781                         Log(Form("ERROR Sensor Fit for %s not found: ", fgkDCSDataPoints[indexDP] ));
782                 }
783                 
784         }
785
786         /*      indexDP = kCavernAtmosPressure;
787         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
788         if(!array) {
789                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
790         } 
791         else {
792                 Float_t *floatDCS = ProcessFloatAll(array);
793                 grpObj->SetCavernAtmosPressure(floatDCS);
794                 delete floatDCS;
795                 nEnvEntries++;
796         }
797         
798
799         if (array) array = 0x0;
800
801         AliInfo(Form("==========SurfaceAtmosPressure==========="));
802         indexDP = kSurfaceAtmosPressure;
803         AliDCSSensorArray *dcsSensorArray = GetPressureMap(valueMap);
804         dcsSensorArray->Print();
805         AliInfo(Form("fPressure = %p",fPressure));
806         AliInfo(Form("dcsSensorArray = %p",dcsSensorArray));
807         if( fPressure->NumFits()==0 ) {
808                 Log("Problem with the pressure sensor values!!!");
809         } 
810         else {
811                 AliDCSSensor* sensorP2 = dcsSensorArray->GetSensor(fgkDCSDataPoints[indexDP]);
812                 AliDebug(2,Form("sensorP2 = %p", sensorP2));
813                 if( sensorP2->GetFit() ) {
814                         Log(Form("<%s> for run %d: Sensor Fit found",fgkDCSDataPoints[indexDP], fRun));
815                         grpObj->SetSurfaceAtmosPressure(sensorP2);
816                         nEnvEntries++;
817                 } 
818                 //if (sensorP2) delete sensorP2;
819                 else {
820                         Log(Form("ERROR Sensor Fit for %s not found: ", fgkDCSDataPoints[indexDP] ));
821                 }
822                 
823         }
824         */
825
826         return nEnvEntries;
827 }
828 //_______________________________________________________________
829
830 Int_t AliGRPPreprocessor::ProcessHPDPs(const TMap* valueMap, AliGRPObject* grpObj)
831 {
832         // processing DPs
833         // related to 
834         // Hall Probes info
835
836         Int_t nHPEntries = 0;
837         TObjArray *array = 0x0;
838         Int_t indexDP = -1;
839
840         if (fgknDCSDPHallProbes != AliGRPObject::GetNumberOfHP()){
841                 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()));
842         }
843         for (indexDP = 0; indexDP < AliGRPObject::GetNumberOfHP(); indexDP++){
844                 AliInfo(Form("==========%s===========",AliGRPObject::GetHPDP(indexDP)));
845                 array = (TObjArray *)valueMap->GetValue(AliGRPObject::GetHPDP(indexDP));
846                 if(!array) {
847                         Log(Form("%s not found in the map!!!",AliGRPObject::GetHPDP(indexDP)));
848                 } 
849                 else {
850                         if (array->GetEntries() == 0){
851                                 AliError(Form("No entries found in array! setting %s to invalid...",AliGRPObject::GetHPDP(indexDP)));
852                         }
853                         else {
854                                 Float_t *floatDCS = ProcessFloatAll(array);
855                                 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])); 
856                                 grpObj->SetHallProbes((AliGRPObject::DP_HallProbes)indexDP,floatDCS);
857                                 for (Int_t kk = 0 ; kk< 5; kk++){
858                                         AliDebug(2,Form("HallProbe[%d][%d]=%f",indexDP,kk,grpObj->GetHallProbes((AliGRPObject::DP_HallProbes)indexDP,(AliGRPObject::Stats)kk)));
859                                 }
860                                 delete floatDCS;
861                         }
862                         nHPEntries++;
863                 }
864         }
865                 
866         Log(Form("Hall Probes = %d ", nHPEntries));
867         return nHPEntries;
868 }
869
870 //_______________________________________________________________
871
872 Int_t AliGRPPreprocessor::ProcessLHCDPs(const TMap* valueMap, AliGRPObject* grpObj)
873 {
874
875         //
876         // processing of LHC related DCS DPs, i.e.:
877         // LHCState
878         // LHCLuminosity
879         // BeamIntensity
880         //
881
882         Int_t nLHCEntries = 0;
883         TObjArray *array = 0x0;
884         Int_t indexDP = -1;
885
886         AliInfo(Form("==========LHCState==========="));
887         indexDP = kLHCState;
888         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
889         if(!array) {
890                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
891         } 
892         else {
893                 if (array->GetEntries() == 0){
894                         AliError(Form("No entries found in array! setting %s to invalid...",fgkDCSDataPoints[indexDP]));
895                 }
896                 else {
897                         TString stringDCS = ProcessChar(array);
898                         if (stringDCS.Length()!=0) {
899                                 Bool_t found = kFALSE;
900                                 for( Int_t i=0; i<20; i+=2 ) {
901                                         if( stringDCS.CompareTo(fgkLHCState[i]) == 0 ) {
902                                                 stringDCS = fgkLHCState[i+1];
903                                                 found = kTRUE;
904                                                 break;
905                                         }
906                                 }
907                                 if (found){
908                                         Log(Form("<%s> for run %d: %s",fgkDCSDataPoints[indexDP],fRun, stringDCS.Data()));
909                                         grpObj->SetLHCState(stringDCS);
910                                 }
911                                 else{
912                                         Log(Form("%s values found not valid!",fgkDCSDataPoints[indexDP]));
913                                         grpObj->SetLHCState(AliGRPObject::GetInvalidString());
914                                 } 
915                         }
916                         else {
917                                 Log(Form("%s not valid (null length), string set as invalid!",fgkDCSDataPoints[indexDP]));
918                                 grpObj->SetLHCState(AliGRPObject::GetInvalidString());
919                         }         
920                 }
921                 nLHCEntries++;
922         }
923         
924         if (array) array = 0x0;
925
926         AliInfo(Form("==========LHCLuminosity==========="));
927         indexDP = kLHCLuminosity;
928         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
929         if(!array) {
930                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
931         } 
932         else {
933                 if (array->GetEntries() == 0){
934                         AliError(Form("No entries found in array! setting %s and its Spline Fit to invalid...",fgkDCSDataPoints[indexDP]));
935                 }
936                 else {
937                         Float_t *floatDCS = ProcessFloatAll(array);
938                         grpObj->SetLHCLuminosity(floatDCS);
939                         delete floatDCS;
940                         AliSplineFit* splfit = GetSplineFit(array,fgkDCSDataPoints[indexDP]);
941                         grpObj->SetLHCLuminositySplineFit(splfit);
942                         //              delete splfit;
943                 }
944                 nLHCEntries++;
945         }
946
947         if (array) array = 0x0;
948
949         AliInfo(Form("==========BeamIntensity==========="));
950         indexDP = kBeamIntensity;
951         array = (TObjArray *)valueMap->GetValue(fgkDCSDataPoints[indexDP]);
952         if(!array) {
953                 Log(Form("%s not found in the map!!!",fgkDCSDataPoints[indexDP]));
954         } 
955         else {
956                 if (array->GetEntries() == 0){
957                         AliError(Form("No entries found in array! setting %s and its Spline Fit to invalid...",fgkDCSDataPoints[indexDP]));
958                 }
959                 else {
960                         Float_t *floatDCS = ProcessFloatAll(array);
961                         grpObj->SetBeamIntensity(floatDCS);
962                         delete floatDCS;
963                         AliSplineFit* splfit1 = GetSplineFit(array,fgkDCSDataPoints[indexDP]);
964                         grpObj->SetBeamIntensitySplineFit(splfit1);
965                         //delete splfit;
966                 }
967                 nLHCEntries++;
968         }
969
970         return nLHCEntries;
971 }
972 //_________________________________________________________________________
973
974 AliSplineFit* AliGRPPreprocessor::GetSplineFit(const TObjArray *array, const TString& stringID){
975
976
977         // 
978         // returning Spline Fit 
979         // 
980
981         Int_t entriesarray = array->GetEntries();
982         Float_t* value = new Float_t[entriesarray];
983         Float_t* time = new Float_t[entriesarray];
984         AliDCSValue* v = 0x0;
985         for (Int_t iarray = 0; iarray < entriesarray; iarray++){
986                 v = (AliDCSValue*)array->At(iarray);
987                 value[iarray] = v->GetFloat();
988                 time[iarray] = v->GetTimeStamp();
989                 AliInfo(Form("iarray = %d, value = %f, time = %f",iarray,value[iarray],time[iarray]));
990         }
991         TGraph* gr = new TGraph(entriesarray,value,time);
992         if (!gr ) {
993                 AliWarning(Form("%s: no input graph to compute SplineFit",stringID.Data()));
994                 return NULL;
995         }
996         AliSplineFit *fit = new AliSplineFit();
997         fit->SetMinPoints(10);
998         fit->InitKnots(gr,10,10,0.0);
999         fit->SplineFit(2);
1000         fit->Cleanup();
1001         if (!fit) {
1002                 AliWarning(Form("%s: no fit performed",stringID.Data()));
1003                 return NULL;
1004         } 
1005         return fit;
1006 }
1007
1008 //_________________________________________________________________________
1009
1010 TString AliGRPPreprocessor::ProcessChar(const TObjArray *array)
1011 {
1012
1013         // 
1014         // processing char
1015         //
1016
1017         TString aDCSString="";
1018         
1019         AliDCSValue *v = 0x0;
1020         for(Int_t iCount = 0; iCount < array->GetEntries(); iCount++) {
1021                 v = (AliDCSValue *)array->At(iCount);
1022                 if (((Int_t)(v->GetTimeStamp()) < (Int_t)GetStartTimeDCSQuery()) || ((Int_t)(v->GetTimeStamp()) > (Int_t)GetEndTimeDCSQuery())) {
1023                         AliError(Form("DCS values for the parameter outside the queried interval"));
1024                         continue;
1025                 }
1026                 if (iCount > 0) {
1027                         if (aDCSString != v->GetChar())
1028                         AliError(Form("DCS values for the parameter changed from %s to %c within the queried interval", aDCSString.Data(), (Char_t)v->GetChar()));
1029                 }
1030                 aDCSString = (TString)v->GetChar();  // keeping always last value in the array
1031         }
1032         return aDCSString;
1033 }
1034
1035 //__________________________________________________________________________________________________________________
1036
1037 Float_t* AliGRPPreprocessor::ProcessFloatAll(const TObjArray* array)
1038 {
1039         // 
1040         // processing Float values using Mean, Median, Standard Deviation wrt Mean, Standar Deviation wrt Median 
1041         //
1042         // parameters[0] = mean
1043         // parameters[1] = truncated mean (calculated excluding points outside +/- 3RMS from mean
1044         // parameters[2] = median
1045         // parameters[3] = standard deviation wrt mean
1046         // parameters[4] = standard deviation wrt median
1047         //
1048
1049         Float_t* parameters = new Float_t[5];
1050         Double_t aDCSArrayMean = 0;     // Mean
1051         Double_t aDCSArrayTruncMean = 0;// Truncated Mean
1052         Double_t aDCSArrayMedian = 0;   // Median
1053         Double_t aDCSArraySDMean = 0;   // Standard Deviation wrt Mean
1054         Double_t aDCSArraySDMedian = 0; // Standard Deviation wrt Median
1055         Float_t aDCSArraySum = 0.0;
1056         Int_t iCounts = 0;
1057         Int_t iCounts1 = 0;
1058         Float_t temp = 0;
1059         Float_t temp1 = 0;
1060         Int_t nCounts = array->GetEntries();
1061         Float_t *tempArray = new Float_t[nCounts];
1062         for(Int_t i = 0; i < nCounts; i++) {
1063                 AliDCSValue *v = (AliDCSValue *)array->At(i);
1064                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
1065                         aDCSArraySum += v->GetFloat();
1066                         tempArray[i] = v->GetFloat();
1067                         AliDebug(2,Form("%d-th entry = %f",i,tempArray[i]));
1068                         iCounts += 1;
1069                 }
1070         }
1071
1072         AliDebug(2,Form("Using %i entries, starting from %i entries",iCounts,nCounts));
1073         if(iCounts != 0) {
1074                 aDCSArrayMean = TMath::Mean(iCounts,tempArray);
1075                 aDCSArrayMedian = TMath::Median(iCounts,tempArray);
1076                 aDCSArraySDMean = TMath::RMS(iCounts,tempArray);
1077                 AliDebug(2,Form("SD = %f",aDCSArraySDMean));
1078                 // computing standard deviation wrt median
1079                 AliDebug(2,Form("maximum = %f, minimum = %f", aDCSArrayMean+3*aDCSArraySDMean, aDCSArrayMean-3*aDCSArraySDMean));
1080                 for (Int_t i = 0; i < iCounts; i++){
1081                         AliDCSValue *v = (AliDCSValue *)array->At(i);
1082                         AliDebug(2,Form("maximum = %f, minimum = %f", aDCSArrayMean+3*aDCSArraySDMean, aDCSArrayMean-3*aDCSArraySDMean));
1083                         AliDebug(2,Form("%i-th entry = %f",i, v->GetFloat())); 
1084                         if ((v->GetFloat()<=aDCSArrayMean+3*aDCSArraySDMean) && (v->GetFloat()>=aDCSArrayMean-3*aDCSArraySDMean)){
1085                                 temp1+=v->GetFloat();
1086                                 iCounts1++;
1087                                 AliDebug(2,Form("temp1 = %f, iCounts1 = %i",temp1,iCounts1));
1088                         }
1089                         temp += (v->GetFloat()-aDCSArrayMedian)*(v->GetFloat()-aDCSArrayMedian);
1090                 }
1091                 AliDebug(3,Form("temp before the ratio = %f, with %d counts", temp, iCounts));
1092                 temp/=iCounts;
1093                 AliDebug(3,Form("temp after the ratio = %f", temp));
1094                 if (temp>0) {
1095                         aDCSArraySDMedian = TMath::Sqrt(temp);
1096                 }
1097                 else if (temp==0) {
1098                         AliInfo(Form("Radical = 0 in computing standard deviation wrt median! Setting it to zero...."));
1099                         aDCSArraySDMedian = 0;
1100                 }
1101                 else{
1102                         AliError(Form("Radical < 0 in computing standard deviation! Setting it to invalid...."));
1103                         aDCSArraySDMedian = AliGRPObject::GetInvalidFloat();
1104                 }
1105         }
1106         else {
1107                 aDCSArrayMean = AliGRPObject::GetInvalidFloat();
1108                 aDCSArrayMedian = AliGRPObject::GetInvalidFloat();
1109                 aDCSArraySDMean = AliGRPObject::GetInvalidFloat();
1110         }
1111         AliDebug(2,Form("iCounts1 = %d and temp1 = %f",iCounts1, temp1));
1112         if (iCounts1 > 0) {
1113                 aDCSArrayTruncMean = temp1/iCounts1;
1114         }
1115         else{
1116                 aDCSArrayTruncMean = AliGRPObject::GetInvalidFloat();
1117         }
1118         
1119         
1120         
1121         AliDebug(2,Form("mean within %d counts = %f ",iCounts,aDCSArrayMean));
1122         AliDebug(2,Form("truncated mean within %d counts = %f (%i values used)",iCounts,aDCSArrayTruncMean,iCounts1));
1123         AliDebug(2,Form("median within %d counts = %f ",iCounts,aDCSArrayMedian));
1124         AliDebug(2,Form("standard deviation with mean within %d counts = %f ",iCounts,aDCSArraySDMean));
1125         AliDebug(2,Form("standard deviation with median within %d counts = %f ",iCounts,aDCSArraySDMedian));
1126         
1127         parameters[0] = aDCSArrayMean;
1128         parameters[1] = aDCSArrayTruncMean;
1129         parameters[2] = aDCSArrayMedian;
1130         parameters[3] = aDCSArraySDMean;
1131         parameters[4] = aDCSArraySDMedian;
1132
1133         //      AliDebug(2,Form("mean = %f, truncated mean = %f, median = %f, SD wrt mean = %f, SD wrt median = %f ",parameters[0],parameters[1],parameters[2],parameters[3],parameters[4]));
1134         AliInfo(Form("mean = %f, truncated mean = %f, median = %f, SD wrt mean = %f, SD wrt median = %f ",parameters[0],parameters[1],parameters[2],parameters[3],parameters[4]));
1135
1136         return parameters;
1137 }
1138
1139
1140 //_______________________________________________________________
1141
1142 Char_t AliGRPPreprocessor::ProcessBool(const TObjArray* array)
1143 {
1144         // 
1145         // processing Boolean values
1146         //
1147
1148         Bool_t aDCSBool = kTRUE;
1149
1150         AliDCSValue *v = 0x0;
1151
1152         for(Int_t iCount = 0; iCount < array->GetEntries(); iCount++) {
1153                 v = (AliDCSValue *)array->At(iCount);
1154                 if (((Int_t)(v->GetTimeStamp()) < (Int_t)GetStartTimeDCSQuery()) || ((Int_t)(v->GetTimeStamp()) > (Int_t)GetEndTimeDCSQuery())) {
1155                         AliError(Form("DCS values for the parameter outside the queried interval"));
1156                         continue;
1157                 }
1158                 if (iCount > 0) {
1159                         if (aDCSBool != v->GetBool())
1160                         AliError(Form("DCS values for the parameter changed from %d to %d within the queried interval", (UInt_t)aDCSBool, (UInt_t)v->GetBool()));
1161                 }
1162                 aDCSBool = v->GetBool(); // always keeping last value
1163                 AliDebug(2,Form("Bool = %d",(Int_t)aDCSBool));
1164         }
1165         
1166         Char_t caDCSBool = (Char_t) aDCSBool;
1167         return caDCSBool;
1168         
1169 }
1170
1171 //_______________________________________________________________
1172
1173 Float_t AliGRPPreprocessor::ProcessInt(const TObjArray* array)
1174 {
1175         // 
1176         // processing Int values, returning mean
1177         //
1178
1179         Float_t aDCSArraySum = 0.0;
1180         Float_t aDCSArrayMean = 0.0;
1181         Int_t iCounts = 0;
1182         AliDCSValue* v = 0x0;
1183
1184         for(Int_t iCount = 0; iCount < array->GetEntries(); iCount++) {
1185                 v = (AliDCSValue *)array->At(iCount);
1186                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
1187                         aDCSArraySum += v->GetInt();
1188                         iCounts += 1;
1189                 }
1190         }
1191
1192         if(iCounts != 0) aDCSArrayMean = aDCSArraySum/iCounts;
1193         else aDCSArrayMean = AliGRPObject::GetInvalidFloat();
1194         
1195         return aDCSArrayMean;
1196
1197 }
1198 //_______________________________________________________________
1199
1200 Float_t AliGRPPreprocessor::ProcessUInt(const TObjArray* array)
1201 {
1202         // 
1203         // processing Int values, returning mean
1204         //
1205
1206         Float_t aDCSArraySum = 0.0;
1207         Float_t aDCSArrayMean = 0.0;
1208         Int_t iCounts = 0;
1209         AliDCSValue* v = 0x0;
1210
1211         for(Int_t iCount = 0; iCount < array->GetEntries(); iCount++) {
1212                 v = (AliDCSValue *)array->At(iCount);
1213                 if(((Int_t)(v->GetTimeStamp()) >= (Int_t)GetStartTimeDCSQuery()) &&((Int_t)(v->GetTimeStamp()) <= (Int_t)GetEndTimeDCSQuery())) {
1214                         aDCSArraySum += v->GetUInt();
1215                         iCounts += 1;
1216                 }
1217         }
1218
1219         if(iCounts != 0) aDCSArrayMean = aDCSArraySum/iCounts;
1220         else aDCSArrayMean = AliGRPObject::GetInvalidFloat();
1221         
1222         return aDCSArrayMean;
1223
1224 }
1225
1226
1227 //_______________________________________________________________
1228
1229 AliDCSSensorArray *AliGRPPreprocessor::GetPressureMap(TMap* dcsAliasMap)
1230 {
1231         // extract DCS pressure maps. Perform fits to save space
1232         
1233         TMap *map = fPressure->ExtractDCS(dcsAliasMap);
1234         if (map) {
1235                 fPressure->MakeSplineFit(map);
1236                 Double_t fitFraction = fPressure->NumFits()/fPressure->NumSensors(); 
1237                 if (fitFraction > kFitFraction ) {
1238                         AliInfo(Form("Pressure values extracted, %d fits performed.", fPressure->NumFits()));
1239                 } else { 
1240                         AliInfo("Too few pressure maps fitted!!!");
1241                 }
1242         } else {
1243                 AliInfo("no atmospheric pressure map extracted!!!");
1244         }
1245         delete map;
1246         
1247         return fPressure;
1248 }
1249
1250
1251   
1252 //_______________________________________________________________
1253 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)
1254 {
1255         //
1256         // Retrieves logbook and trigger information from the online logbook
1257         // This information is needed for prompt reconstruction
1258         //
1259         // Parameters are:
1260         // Run number
1261         // DAQ params: dbHost, dbPort, dbName, user, password, logbookTable, triggerTable
1262         // cdbRoot
1263         //
1264         // returns:
1265         //         positive on success: the return code is the run number of last run processed of the same run type already processed by the SHUTTLE
1266         //         0 on success and no run was found
1267         //         negative on error
1268         //
1269         // This function is NOT called during the preprocessor run in the Shuttle!
1270         //
1271         
1272         // defaults
1273         if (dbPort == 0)
1274                 dbPort = 3306;
1275         
1276         // CDB connection
1277         AliCDBManager* cdb = AliCDBManager::Instance();
1278         cdb->SetDefaultStorage(cdbRoot);
1279         
1280         // SQL connection
1281         TSQLServer* server = TSQLServer::Connect(Form("mysql://%s:%d/%s", dbHost, dbPort, dbName), user, password);
1282         
1283         if (!server)
1284                 {
1285                         Printf("ERROR: Could not connect to DAQ LB");
1286                         return -1;
1287                 }
1288         
1289         // main logbook
1290         TString sqlQuery;
1291         sqlQuery.Form("SELECT DAQ_time_start, run_type, detectorMask, L3_magnetCurrent, Dipole_magnetCurrent FROM logbook WHERE run = %d", run);
1292         TSQLResult* result = server->Query(sqlQuery);
1293         if (!result)
1294                 {
1295                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
1296                         return -2;
1297                 }
1298         
1299         if (result->GetRowCount() == 0)
1300                 {
1301                         Printf("ERROR: Run %d not found", run);
1302                         delete result;
1303                         return -3;
1304                 }
1305         
1306         TSQLRow* row = result->Next();
1307         if (!row)
1308                 {
1309                         Printf("ERROR: Could not receive data from run %d", run);
1310                         delete result;
1311                         return -4;
1312                 }
1313         
1314         TString timeStartString(row->GetField(0));
1315         TString runType(row->GetField(1));
1316         TString detectorMaskString(row->GetField(2));
1317         TString l3CurrentString(row->GetField(3));
1318         TString dipoleCurrentString(row->GetField(4));
1319         time_t timeStart = (time_t)(timeStartString.Atoi());
1320         UInt_t detectorMask = (UInt_t)(detectorMaskString.Atoi());
1321         Float_t l3Current = (Float_t)(TMath::Abs(l3CurrentString.Atof()));
1322         Float_t dipoleCurrent = (Float_t)(TMath::Abs(dipoleCurrentString.Atof()));
1323         
1324         AliGRPObject * grpObj = new AliGRPObject();
1325         grpObj->SetTimeStart(timeStart); 
1326         grpObj->SetRunType((TString)(row->GetField(1)));
1327         grpObj->SetDetectorMask(detectorMask);
1328         grpObj->SetL3Current(l3Current,(AliGRPObject::Stats)0);
1329         grpObj->SetDipoleCurrent(dipoleCurrent,(AliGRPObject::Stats)0);
1330
1331         delete row;
1332         row = 0;
1333         
1334         delete result;
1335         result = 0;
1336         
1337         Printf("Storing GRP/GRP/Data object with the following content");
1338         grpObj->Dump();
1339         
1340         AliCDBMetaData metadata;
1341         metadata.SetResponsible("Jan Fiete Grosse-Oetringhaus & Chiara Zampolli");
1342         metadata.SetComment("GRP Output parameters received during online running");
1343         
1344         AliCDBId id("GRP/GRP/Data", run, run);
1345         Bool_t success = cdb->Put(grpObj, id, &metadata);
1346         
1347         delete grpObj;
1348         
1349         if (!success)
1350                 {
1351                         Printf("ERROR: Could not store GRP/GRP/Data into OCDB");
1352                         return -5;
1353                 }
1354         
1355         // Receive trigger information
1356         sqlQuery.Form("SELECT configFile FROM logbook_trigger_config WHERE run = %d", run);
1357         result = server->Query(sqlQuery);
1358         if (!result)
1359                 {
1360                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
1361                         return -11;
1362                 }
1363         
1364         if (result->GetRowCount() == 0)
1365                 {
1366                         Printf("ERROR: Run %d not found in logbook_trigger_config", run);
1367                         delete result;
1368                         return -12;
1369                 }
1370         
1371         row = result->Next();
1372         if (!row)
1373                 {
1374                         Printf("ERROR: Could not receive logbook_trigger_config data from run %d", run);
1375                         delete result;
1376                         return -13;
1377                 }
1378         
1379         TString triggerConfig(row->GetField(0));
1380         
1381         delete row;
1382         row = 0;
1383         
1384         delete result;
1385         result = 0;
1386         
1387         Printf("Found trigger configuration: %s", triggerConfig.Data());
1388         
1389         AliTriggerConfiguration *runcfg = AliTriggerConfiguration::LoadConfigurationFromString(triggerConfig);
1390         if (!runcfg)
1391                 {
1392                         Printf("ERROR: Could not create CTP configuration object");
1393                         return -14;
1394                 }
1395         
1396         metadata.SetComment("CTP run configuration received during online running");
1397         
1398         AliCDBId id2("GRP/CTP/Config", run, run);
1399         success = cdb->Put(runcfg, id2, &metadata);
1400         
1401         delete runcfg;
1402         runcfg = 0;
1403         
1404         if (!success)
1405                 {
1406                         Printf("ERROR: Could not store GRP/CTP/Config into OCDB");
1407                         return -15;
1408                 }
1409         
1410         // get last run with same run type that was already processed by the SHUTTLE
1411         
1412         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());
1413         result = server->Query(sqlQuery);
1414         if (!result)
1415                 {
1416                         Printf("ERROR: Can't execute query <%s>!", sqlQuery.Data());
1417                         return -21;
1418                 }
1419         
1420         if (result->GetRowCount() == 0)
1421                 {
1422                         Printf("ERROR: No result with query <%s>", sqlQuery.Data());
1423                         delete result;
1424                         return -22;
1425                 }
1426         
1427         row = result->Next();
1428         if (!row)
1429                 {
1430                         Printf("ERROR: Could not receive data for query <%s>", sqlQuery.Data());
1431                         delete result;
1432                         return -23;
1433                 }
1434         
1435         TString lastRunStr(row->GetField(0));
1436         Int_t lastRun = lastRunStr.Atoi();
1437         
1438         Printf("Last run with same run type %s is %d", runType.Data(), lastRun);
1439         
1440         delete row;
1441         row = 0;
1442         
1443         delete result;
1444         result = 0;
1445         
1446         server->Close();
1447         delete server;
1448         server = 0;
1449         
1450         return lastRun;
1451 }