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