c78fbe3ea8ab51b8d85ef8c3f846321c8871dbfb
[u/mrichter/AliRoot.git] / TOF / AliTOFPreprocessor.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 //#include <Riostream.h>
20 //#include <stdio.h>
21 //#include <stdlib.h>
22
23 #include <TFile.h>
24 #include <TH2S.h>
25 #include <TH1F.h>
26 #include <TCanvas.h>
27 #include <TMath.h>
28 #include <TObjArray.h>
29 #include <TObjString.h>
30 #include <TTimeStamp.h>
31
32 #include "AliCDBMetaData.h"
33 #include "AliCDBEntry.h"
34 #include "AliLog.h"
35 #include "AliTOFChannelOnlineArray.h"
36 #include "AliTOFChannelOnlineStatusArray.h"
37 #include "AliTOFDataDCS.h"
38 #include "AliTOFDCSmaps.h"
39 #include "AliTOFLvHvDataPoints.h"
40 #include "AliTOFGeometry.h"
41 #include "AliTOFPreprocessor.h"
42 #include "AliTOFFEEReader.h"
43 #include "AliTOFRawStream.h"
44 #include "AliTOFCableLengthMap.h"
45 #include "AliTOFcalibHisto.h"
46 #include "AliTOFFEEDump.h"
47 #include "TChain.h"
48 #include "AliTOFDeltaBCOffset.h"
49 #include "AliTOFCTPLatency.h"
50 #include "AliTOFRunParams.h"
51 #include "AliTOFT0FillOnlineCalib.h"
52 #include "AliTOFHitField.h"
53 #include "AliTOFChannelOffline.h"
54 #include "TF1.h"
55 #include "TGeoManager.h"
56 #include "AliGeomManager.h"
57 #include "AliTOFReadoutInfo.h"
58
59 // TOF preprocessor class.
60 // It takes data from DCS and passes them to the class AliTOFDataDCS, which
61 // processes them. The result is then written to the CDB.
62 // Analogously, it takes data form DAQ (both at Run level and inclusive - 
63 // of all the runs - level, processes them, and stores both Reference Data
64 // and Online Calibration files in the CDB. 
65 // Processing of Pulser/Noise Run data and of TOF FEE DCS map included also.
66
67 // return codes:
68 // return=0 : all ok
69 // return=1 : no DCS input data Map
70 // return=2 : no DCS input data processing
71 // return=3 : no DCS processed data was stored in Ref Data
72 // return=4 : no DAQ input for Ref Data
73 // return=5 : failed to store DAQ Ref Data
74 // return=6 : failed to retrieve DAQ data for calibration 
75 // return=7 : problems in processing histos in the input DAQ file 
76 // return=8 : failed to store Online Delays
77 // return=9 : failed to store Reference Data for Pulser
78 // return=10: failed to retrieve Pulser data 
79 // return=11: failed to store Pulser map in OCDB
80 // return=12: failed to store Reference Data for Noise
81 // return=13: failed to retrieve Noise data 
82 // return=14: failed to store Noise map in OCDB
83 // return=15: failed to retrieve FEE data from FXS
84 // return=16: failed to retrieve FEE data from OCDB
85 // return=17: failed to store FEE data in OCDB
86 // return=18: failed to store FEE reference data in OCDB
87 // return=20: failed in retrieving status variable
88 // return=100 : no DCS input data Map (HV and LV status)
89 // return=200 : no DCS input data processing (HV and LV status)
90 // return=300 : no DCS processed data was stored in Ref Data (HV and LV status)
91
92 ClassImp(AliTOFPreprocessor)
93
94 const Int_t    AliTOFPreprocessor::fgkBinRangeAve = 13;    // number of bins where to calculate the mean 
95 const Double_t AliTOFPreprocessor::fgkIntegralThr = 100;   // min number of entries to perform computation of delay per channel 
96 const Double_t AliTOFPreprocessor::fgkThrPar      = 0.013; // parameter used to trigger the calculation of the delay
97
98 //_____________________________________________________________________________
99
100 AliTOFPreprocessor::AliTOFPreprocessor(AliShuttleInterface* shuttle) :
101   AliPreprocessor("TOF", shuttle),
102   fData(0),
103   fHVLVmaps(0),
104   fCal(0),
105   fNChannels(0),
106   fStoreRefData(kTRUE),
107   fFDRFlag(kFALSE),
108   fStatus(0),
109   fMatchingWindow(0),
110   fLatencyWindow(0),
111   fIsStatusMapChanged(0)
112 {
113   // constructor
114   AddRunType("PHYSICS");
115   AddRunType("PULSER");
116   AddRunType("NOISE");
117
118 }
119
120 //_____________________________________________________________________________
121
122 AliTOFPreprocessor::~AliTOFPreprocessor()
123 {
124   // destructor
125 }
126
127 //______________________________________________________________________________
128 void AliTOFPreprocessor::Initialize(Int_t run, UInt_t startTime,
129         UInt_t endTime)
130 {
131   // Creates AliTOFDataDCS object
132
133   AliPreprocessor::Initialize(run, startTime, endTime);
134
135         AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s \n\tStartTime DCS Query %s \n\tEndTime DCS Query %s", run,
136                 TTimeStamp(startTime).AsString(),
137                 TTimeStamp(endTime).AsString(), ((TTimeStamp)GetStartTimeDCSQuery()).AsString(), ((TTimeStamp)GetEndTimeDCSQuery()).AsString()));
138
139         fData = new AliTOFDataDCS(fRun, fStartTime, fEndTime, GetStartTimeDCSQuery(), GetEndTimeDCSQuery());
140         fHVLVmaps = new AliTOFLvHvDataPoints(fRun, fStartTime, fEndTime, GetStartTimeDCSQuery(), GetEndTimeDCSQuery());
141         fNChannels = AliTOFGeometry::NSectors()*(2*(AliTOFGeometry::NStripC()+AliTOFGeometry::NStripB())+AliTOFGeometry::NStripA())*AliTOFGeometry::NpadZ()*AliTOFGeometry::NpadX();
142 }
143 //_____________________________________________________________________________
144 Bool_t AliTOFPreprocessor::ProcessDCS(){
145
146   // check whether DCS should be processed or not...
147
148   TString runType = GetRunType();
149   Log(Form("RunType %s",runType.Data()));
150
151   if (runType != "PHYSICS"){
152     return kFALSE;
153   }
154
155   return kTRUE;
156 }
157 //_____________________________________________________________________________
158
159 UInt_t AliTOFPreprocessor::ProcessDCSDataPoints(TMap *dcsAliasMap)
160 {
161   // Fills data into a AliTOFDataDCS object
162
163
164   Log("Processing DCS DP");
165   TH1::AddDirectory(0);
166
167   Bool_t resultDCSMap=kFALSE;
168   Bool_t resultDCSStore=kFALSE;
169
170   // processing DCS
171
172   fData->SetFDRFlag(fFDRFlag);
173   
174   if (!dcsAliasMap){
175     Log("No DCS map found: TOF exiting from Shuttle");
176     if (fData){
177             delete fData;
178             fData = 0;
179     }
180     return 1;// return error Code for DCS input data not found 
181   }
182   else {
183
184   // The processing of the DCS input data is forwarded to AliTOFDataDCS
185     resultDCSMap=fData->ProcessData(*dcsAliasMap);
186     if(!resultDCSMap){
187       Log("Some problems occurred while processing DCS data, TOF exiting from Shuttle");
188       if (fData){
189               delete fData;
190               fData = 0;
191       }
192       return 2;// return error Code for processed DCS data not stored 
193     }
194     else{
195       AliCDBMetaData metaDataDCS;
196       metaDataDCS.SetBeamPeriod(0);
197       metaDataDCS.SetResponsible("Chiara Zampolli");
198       metaDataDCS.SetComment("This preprocessor fills an AliTOFDataDCS object.");
199       AliInfo("Storing DCS Data");
200       resultDCSStore = StoreReferenceData("Calib","DCSData",fData, &metaDataDCS);
201       if (!resultDCSStore){
202         Log("Some problems occurred while storing DCS data results in Reference Data, TOF exiting from Shuttle");
203         if (fData){
204                 delete fData;
205                 fData = 0;
206         }
207         return 3;// return error Code for processed DCS data not stored 
208                  // in reference data
209         
210       }
211     }
212   }
213   if (fData){
214           delete fData;
215           fData = 0;
216   }
217   
218   return 0;
219 }
220 //_____________________________________________________________________________
221
222 UInt_t AliTOFPreprocessor::ProcessHVandLVdps(TMap *dcsAliasMap)
223 {
224   //
225   //Fills data into a AliTOFLvHvDataPoints object
226   // Merges fStatus object with LV and HV status at SOR
227   // Updates fStatus object with LV and HV status
228   //    at EOR in case of correct end of run
229   //    at last but two value in case of end-of-run caused by TOF detector.
230   //
231
232   Log("Processing HV and LV DCS DPs");
233   TH1::AddDirectory(0);
234
235   Bool_t resultDCSMap=kFALSE;
236
237   // processing DCS HV and LV data points
238
239   fHVLVmaps->SetFDRFlag(fFDRFlag);
240   
241   if (!dcsAliasMap){
242     Log("No DCS map found: TOF exiting from Shuttle");
243     if (fHVLVmaps){
244       delete fHVLVmaps;
245       fHVLVmaps = 0;
246     }
247     return 100;// return error Code for DCS input data not found 
248   }
249   else {
250
251     // The processing of the DCS input data is forwarded to AliTOFDataDCS
252     //if (0) { // AdC
253     resultDCSMap = fHVLVmaps->ProcessData(*dcsAliasMap);
254     if (!resultDCSMap) {
255       Log("Some problems occurred while processing DCS data, TOF exiting from Shuttle");
256       if (fHVLVmaps) {
257         delete fHVLVmaps;
258         fHVLVmaps = 0;
259       }
260       return 200;// return error Code for processed DCS data not stored 
261     }
262     else {
263
264       // check with plots. Start...
265       /*
266       TH1F *hROsor = new TH1F("hROsor","RO status map at SOR",91*96*18,-0.5,91*96*18-0.5);
267       for (Int_t ii=1; ii<=91*96*18; ii++) hROsor->SetBinContent(ii,-1);
268       for (Int_t ii=0; ii<91*96*18; ii++) {
269         if (fStatus->GetHWStatus(ii)==AliTOFChannelOnlineStatusArray::kTOFHWBad)
270           hROsor->SetBinContent(ii+1,0);
271         else if (fStatus->GetHWStatus(ii)==AliTOFChannelOnlineStatusArray::kTOFHWOk)
272           hROsor->SetBinContent(ii+1,1);
273       }
274
275       TH1F *hROandHVandLVsor = new TH1F("hROandHVandLVsor","RO.and.HV.andLV status map at SOR",91*96*18,-0.5,91*96*18-0.5);
276       for (Int_t ii=1; ii<=91*96*18; ii++) hROandHVandLVsor->SetBinContent(ii,-1);
277       TH1F *hROandHVandLVeor = new TH1F("hROandHVandLVeor","RO.and.HV.andLV status map at EOR",91*96*18,-0.5,91*96*18-0.5);
278       for (Int_t ii=1; ii<=91*96*18; ii++) hROandHVandLVeor->SetBinContent(ii,-1);
279       */
280
281       AliTOFDCSmaps * lvANDhvMap = (AliTOFDCSmaps*)fHVLVmaps->GetHVandLVmapAtSOR(); // Get LV.and.HV status map at SOR
282       for (Int_t index=0; index<fNChannels; index++) {
283         if ( ( lvANDhvMap->GetCellValue(index)==0 &&
284                fStatus->GetHWStatus(index) != AliTOFChannelOnlineStatusArray::kTOFHWBad ) ||
285              ( lvANDhvMap->GetCellValue(index)==1 &&
286                fStatus->GetHWStatus(index) != AliTOFChannelOnlineStatusArray::kTOFHWOk ) ) {
287           fStatus->SetHWStatus(index, AliTOFChannelOnlineStatusArray::kTOFHWBad);
288           fIsStatusMapChanged=kTRUE;
289         }
290       }
291       
292       // check with plots. Start...
293       /*
294       for (Int_t ii=0; ii<91*96*18; ii++) {
295         if (fStatus->GetHWStatus(ii)==AliTOFChannelOnlineStatusArray::kTOFHWBad)
296           hROandHVandLVsor->SetBinContent(ii+1,0);
297         else if (fStatus->GetHWStatus(ii)==AliTOFChannelOnlineStatusArray::kTOFHWOk)
298           hROandHVandLVsor->SetBinContent(ii+1,1);
299       }
300       */
301
302       lvANDhvMap = (AliTOFDCSmaps*)fHVLVmaps->GetHVandLVmapAtEOR(); // Get LV.and.HV status map at EOR
303       for (Int_t index=0; index<fNChannels; index++) {
304         if ( ( lvANDhvMap->GetCellValue(index)==0 &&
305                fStatus->GetHWStatus(index)!=AliTOFChannelOnlineStatusArray::kTOFHWBad ) ||
306              ( lvANDhvMap->GetCellValue(index)==1 &&
307                fStatus->GetHWStatus(index) != AliTOFChannelOnlineStatusArray::kTOFHWOk ) ) {
308           fStatus->SetHWStatus(index, AliTOFChannelOnlineStatusArray::kTOFHWBad);
309           fIsStatusMapChanged=kTRUE;
310         }
311       }
312
313       // check with plots. Start...
314       /*
315       for (Int_t ii=0; ii<91*96*18; ii++) {
316         if (fStatus->GetHWStatus(ii)==AliTOFChannelOnlineStatusArray::kTOFHWBad)
317           hROandHVandLVeor->SetBinContent(ii+1,0);
318         else if (fStatus->GetHWStatus(ii)==AliTOFChannelOnlineStatusArray::kTOFHWOk)
319           hROandHVandLVeor->SetBinContent(ii+1,1);
320       }
321
322       TCanvas *canvas = new TCanvas("canvas","",10,10,1000,1000);
323       canvas->SetFillColor(0);
324       canvas->Divide(2,2);
325       canvas->cd(1);
326       hROsor->SetLineWidth(2);
327       hROsor->Draw();
328       canvas->cd(2);
329       hROandHVandLVsor->SetLineWidth(2);
330       hROandHVandLVsor->Draw();
331       canvas->cd(3);
332       hROandHVandLVeor->SetLineWidth(2);
333       hROandHVandLVeor->Draw();
334       canvas->cd();
335       */
336
337     }
338     //} // AdC
339   }
340
341
342   /* check whether we don't need to update OCDB.
343    * in this case we can return without errors. */
344
345   if (!fIsStatusMapChanged) {
346     AliInfo("TOF HW status config has not changed. Do not overwrite stored file.");
347     return 0; // return ok
348   }
349
350   TString runType = GetRunType();
351   if (runType != "PHYSICS") {
352     AliInfo(Form("Run Type = %s, waiting to store status map",GetRunType()));
353     return 0; // return ok
354   }
355
356   // update the OCDB with the current FEE.and.HV.and.LV
357   // since even a little difference has been detected.
358
359   AliCDBMetaData metaData;
360   metaData.SetBeamPeriod(0);
361   metaData.SetResponsible("Roberto Preghenella");
362   metaData.SetComment("This preprocessor fills an AliTOFChannelOnlineStatusArray object from FEE.and.HV.and.LV data.");
363   AliInfo("Storing Status data from current run. Collected RO.and.HV.and.LV infos @ EOR");
364   // store TOF channel status
365   if (!Store("Calib", "Status", fStatus, &metaData, 0, kTRUE)) {
366     // failed
367     Log("problems while storing RO.and.HV.and.LV Status data object");
368     if (fStatus){
369       delete fStatus;
370       fStatus = 0;
371     }
372     if (fHVLVmaps) {
373       delete fHVLVmaps;
374       fHVLVmaps = 0;
375     }
376     return 17; // return error code for problems while TOF channel status
377   }
378
379   // everything fine. return
380
381   if (fStatus){
382     delete fStatus;
383     fStatus = 0;
384   }
385
386   if (fHVLVmaps) {
387     delete fHVLVmaps;
388     fHVLVmaps = 0;
389   }
390   
391   return 0;
392 }
393
394 //_____________________________________________________________________________
395
396 UInt_t AliTOFPreprocessor::ProcessOnlineDelays()
397 {
398   // Processing data from DAQ for online calibration 
399
400   Bool_t updateOCDB = kFALSE;
401   Log("Processing DAQ delays");
402
403   // reading configuration map 
404   TString compDelays = "kFALSE";
405   Int_t deltaStartingRun = fRun;
406   Int_t startingRun = fRun-deltaStartingRun;
407   Int_t binRangeAve = fgkBinRangeAve;
408   Double_t integralThr = fgkIntegralThr;
409   Double_t thrPar = fgkThrPar;
410
411   AliCDBEntry *cdbEntry = GetFromOCDB("Calib","Config");
412   if (!cdbEntry) {
413           Log(Form("No Configuration entry found in CDB, using default values: ComputingDelays = %s, StartingRun = %i",compDelays.Data(), startingRun));
414   }
415   else {
416           TMap *configMap = (TMap*)cdbEntry->GetObject();
417           if (!configMap){
418                   Log(Form("No map found in Config entry in CDB, using default values: ComputingDelays = %s, StartingRun = %i",compDelays.Data(), startingRun));
419           }
420           else{
421                   TObjString *strDelays = (TObjString*)configMap->GetValue("ComputingDelays");
422                   if (strDelays) {
423                           compDelays = (TString) strDelays->GetString();
424                   }
425                   else {
426                           Log(Form("No ComputingDelays value found in Map from Config entry in CDB, using default value: ComputingDelays =  %s",compDelays.Data()));
427                   }
428                   TObjString *strRun = (TObjString*)configMap->GetValue("StartingRun");
429                   if (strRun) {
430                           TString tmpstr = strRun->GetString();
431                           startingRun = tmpstr.Atoi();
432                           deltaStartingRun = fRun - startingRun;
433                   }
434                   else {
435                           Log(Form("No StartingRun value found in Map from Config entry in CDB, using default value: StartingRun = %i",startingRun));
436                   }
437                   TObjString *strBinRangeAve = (TObjString*)configMap->GetValue("BinRangeAve");
438                   if (strBinRangeAve) {
439                           TString tmpstr = strBinRangeAve->GetString();
440                           binRangeAve = tmpstr.Atoi();
441                   }
442                   else {
443                           Log(Form("No BinRangeAve value found in Map from Config entry in CDB, using default value: BinRangeAve = %i",binRangeAve));
444                   }
445                   TObjString *strIntegralThr = (TObjString*)configMap->GetValue("IntegralThr");
446                   if (strIntegralThr) {
447                           TString tmpstr = strIntegralThr->GetString();
448                           integralThr = tmpstr.Atof();
449                   }
450                   else {
451                           Log(Form("No IntegralThr value found in Map from Config entry in CDB, using default value: IntegralThr = %f",integralThr));
452                   }
453                   TObjString *strThrPar = (TObjString*)configMap->GetValue("ThrPar");
454                   if (strThrPar) {
455                           TString tmpstr = strThrPar->GetString();
456                           thrPar = tmpstr.Atof();
457                   }
458                   else {
459                           Log(Form("No ThrPar value found in Map from Config entry in CDB, using default value: ThrPar = %f",thrPar));
460                   }
461           }
462   }
463   if (compDelays == "kTRUE") fFDRFlag = kFALSE;
464   else fFDRFlag = kTRUE;
465
466   delete cdbEntry;
467   cdbEntry = 0x0;
468
469   Log(Form("ComputingDelays = %s, StartingRun = %i",compDelays.Data(),startingRun));
470
471   /* init array with current calibration, if any */
472   fCal = new AliTOFChannelOnlineArray(fNChannels);  
473   AliTOFChannelOnlineArray *curCal = NULL;
474
475   AliCDBEntry *cdbEntry2 = GetFromOCDB("Calib","ParOnlineDelay");
476   if (!cdbEntry2 || !cdbEntry2->GetObject()) {
477     /* no CDB entry found. set update flag */
478     Log("     ************ WARNING ************");
479     Log("No CDB ParOnlineDelay entry found, creating a new one!");
480     Log("     *********************************");
481     updateOCDB = kTRUE;
482   }
483   else {
484     Log("Found previous ParOnlineDelay entry. Using it to init calibration");
485     curCal = (AliTOFChannelOnlineArray *)cdbEntry2->GetObject();
486     for (Int_t i = 0; i < fNChannels; i++)
487       fCal->SetDelay(i, curCal->GetDelay(i));
488   }
489  
490
491   TH1::AddDirectory(0);
492
493   Bool_t resultDAQRef=kFALSE;
494   Bool_t resultTOFPP=kFALSE;
495   TH2S *h2 = 0x0;
496   // processing DAQ
497   
498   TFile * daqFile=0x0;
499   
500   if(fStoreRefData){
501     //retrieving data at Run level
502           TList* list = GetFileSources(kDAQ, "RUNLevel");
503           if (list !=0x0 && list->GetEntries()!=0)
504                   {
505                           AliInfo("The following sources produced files with the id RUNLevel");
506                           list->Print();
507                           for (Int_t jj=0;jj<list->GetEntries();jj++){
508                                   TObjString * str = dynamic_cast<TObjString*> (list->At(jj));
509                                   if (!str) {
510                                     AliError("dynamic_cast returned NULL");
511                                     return 4;
512                                   }
513                                   AliInfo(Form("found source %s", str->String().Data()));
514                                   // file to be stored run per run
515                                   TString fileNameRun = GetFile(kDAQ, "RUNLevel", str->GetName());
516                                   if (fileNameRun.Length()>0){
517                                           AliInfo(Form("Got the file %s, now we can store the Reference Data for the current Run.", fileNameRun.Data()));
518                                           daqFile = new TFile(fileNameRun.Data(),"READ");
519                                           h2 = (TH2S*) daqFile->Get("htof");
520                                           AliCDBMetaData metaDataHisto;
521                                           metaDataHisto.SetBeamPeriod(0);
522                                           metaDataHisto.SetResponsible("Chiara Zampolli");
523                                           metaDataHisto.SetComment("This preprocessor stores the array of histos object as Reference Data.");
524                                           AliInfo("Storing Reference Data");
525                                           resultDAQRef = StoreReferenceData("Calib","DAQData",h2, &metaDataHisto);
526                                           if (!resultDAQRef){
527                                                   Log("some problems occurred::No Reference Data stored, TOF exiting from Shuttle");
528                                                   delete h2;
529                                                   delete list;
530                                                   delete fCal;
531                                                   fCal=0x0;
532                                                   return 5;//return error code for failure in storing Ref Data 
533                                           }
534                                           daqFile->Close();
535                                           delete daqFile;
536                                   }
537                                   
538                                   else{
539                                           Log("The input data file from DAQ (run-level) was not found, TOF exiting from Shuttle "); 
540                                           delete list;
541                                           delete fCal;
542                                           fCal=0x0;
543                                           return 4;//return error code for failure in retrieving Ref Data 
544                                   }
545                           }
546                           delete list;
547                   }
548           else{
549                   Log("The input data file list from DAQ (run-level) was not found, TOF exiting from Shuttle "); 
550                   delete fCal;
551                   fCal=0x0;
552                   return 4;//return error code for failure in retrieving Ref Data 
553           }     
554   }
555
556
557   //Total files, with cumulative histos
558   
559   TList* listTot = GetFileSources(kDAQ, "DELAYS");
560   if (listTot !=0x0 && listTot->GetEntries()!=0)
561           {
562                   AliInfo("The following sources produced files with the id DELAYS");
563                   listTot->Print();
564                   for (Int_t jj=0;jj<listTot->GetEntries();jj++){
565                     TObjString * str = dynamic_cast<TObjString*> (listTot->At(jj));
566                     if (!str) {
567                       AliError("dynamic_cast returned NULL");
568                                     return 4;
569                           }
570                           AliInfo(Form("found source %s", str->String().Data()));
571                           
572                           // file with summed histos, to extract calib params
573                           TString fileName = GetFile(kDAQ, "DELAYS", str->GetName());
574                           if (fileName.Length()>0){
575                                   AliInfo(Form("Got the file %s, now we can extract some values.", fileName.Data()));
576                                   
577                                   daqFile = new TFile(fileName.Data(),"READ");
578                                   if (h2) delete h2;
579                                   h2 = (TH2S*) daqFile->Get("htoftot");
580                                   if (!h2){
581                                           Log("some problems occurred:: No histo retrieved, TOF exiting from Shuttle");
582                                           delete listTot;
583                                           delete daqFile;
584                                           delete fCal;
585                                           fCal=0x0;
586                                           return 7; //return error code for histograms not existing/junky
587                                   }
588                                   else {
589                                           static const Int_t kSize=h2->GetNbinsX();
590                                           static const Int_t kNBins=h2->GetNbinsY();
591                                           static const Double_t kXBinmin=h2->GetYaxis()->GetBinLowEdge(1);
592                                           if (kSize != fNChannels){
593                                                   Log(" number of bins along x different from number of pads, found only a subset of the histograms, TOF exiting from Shuttle");
594                                                   delete listTot;
595                                                   delete h2;
596                                                   delete daqFile;
597                                                   delete fCal;
598                                                   fCal=0x0;
599                                                   return 7; //return error code for histograms not existing/junky
600                                           }
601                                           Int_t nNotStatistics = 0; // number of channel with not enough statistics
602
603                                           /* FDR flag set. do not compute delays, use nominal cable delays */
604                                           if (fFDRFlag) {
605
606                                             Log(" Not computing delays according to flag set in Config entry in OCDB!");
607                                             FillWithCosmicCalibration(fCal);
608
609                                             /* check whether the new calibration is different from the previous one */
610                                             if (curCal) { /* well, check also whether we have a previous calibration */
611                                               for (Int_t i = 0; i < fNChannels; i++) {
612                                                 if (fCal->GetDelay(i) != curCal->GetDelay(i)) {
613                                                   updateOCDB = kTRUE;
614                                                   break;
615                                                 }
616                                               }
617                                             }
618                                             else /* otherwise update OCDB */
619                                               updateOCDB = kTRUE;
620
621                                           }
622
623                                           else {  // computing delays if not in FDR runs
624
625                                             updateOCDB = kTRUE; /* always update OCDB when computing delays */
626
627                                                   for (Int_t ich=0;ich<kSize;ich++){
628                                                           /* check whether channel has been read out during current run.
629                                                            * if the status is bad it means it has not been read out.
630                                                            * in this case skip channel in order to not affect the mean */ 
631                                                           if (fStatus->GetHWStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFHWBad){
632                                                                   AliDebug(2,Form(" Channel %i found bad according to FEEmap, (HW status = %i), skipping from delay computing",ich, (Int_t)fStatus->GetHWStatus(ich)));
633                                                                   continue;
634                                                           }
635                                                           AliDebug(2,Form(" Channel %i found ok according to FEEmap, starting delay computing",ich));
636                                                           TH1S *h1 = new TH1S("h1","h1",kNBins,kXBinmin-0.5,kNBins*1.+kXBinmin-0.5);
637                                                           for (Int_t ibin=0;ibin<kNBins;ibin++){
638                                                                   h1->SetBinContent(ibin+1,h2->GetBinContent(ich+1,ibin+1));
639                                                           }
640                                                           if(h1->Integral()<integralThr) {
641                                                                   nNotStatistics++;
642                                                                   Log(Form(" Not enough statistics for bin %i, skipping this channel",ich));  // printing message only if not in FDR runs
643                                                                   delete h1;
644                                                                   h1=0x0;
645                                                                   continue;
646                                                           }
647                                                           Bool_t found=kFALSE; 
648                                                           Float_t minContent=h1->Integral()*thrPar; 
649                                                           Int_t nbinsX = h1->GetNbinsX();
650                                                           Int_t startBin=1;
651                                                           for (Int_t j=1; j<=nbinsX; j++){
652                                                                   if ((
653                                                                        h1->GetBinContent(j) +     
654                                                                        h1->GetBinContent(j+1)+
655                                                                        h1->GetBinContent(j+2)+ 
656                                                                        h1->GetBinContent(j+3))>minContent){
657                                                                           found=kTRUE;
658                                                                           startBin=j;
659                                                                           break;
660                                                                   }
661                                                           }
662                                                           if(!found) AliInfo(Form("WARNING!!! no start of fit found for histo # %i",ich));
663                                                           // Now calculate the mean over the interval. 
664                                                           Double_t mean = 0;
665                                                           Double_t sumw2 = 0;
666                                                           Double_t nent = 0;
667                                                           for(Int_t k=0;k<binRangeAve;k++){
668                                                                   mean=mean+h1->GetBinCenter(startBin+k)*h1->GetBinContent(startBin+k);                 
669                                                                   nent=nent+h1->GetBinContent(startBin+k);                 
670                                                                   sumw2=sumw2+(h1->GetBinCenter(startBin+k))*(h1->GetBinCenter(startBin+k))*(h1->GetBinContent(startBin+k));
671                                                           }
672                                                           mean= mean/nent; //<x>
673                                                           sumw2=sumw2/nent; //<x^2>
674                                                           Double_t rmsmean= 0;
675                                                           rmsmean = TMath::Sqrt((sumw2-mean*mean)/nent);
676                                                           if (ich<fNChannels) {
677                                                                   Float_t delay = mean*AliTOFGeometry::TdcBinWidth()*1.E-3; // delay in ns
678                                                                   fCal->SetDelay(ich,delay);  // delay in ns
679                                                                   AliDebug(2,Form("Setting delay %f (ns) for channel %i",delay,ich));
680                                                           }
681                                                           delete h1;
682                                                           h1=0x0;
683                                                   }
684                                           }
685                                           if (nNotStatistics!=0) Log(Form("Too little statistics for %d channels!",nNotStatistics)); 
686                                   }
687                                   delete h2;
688                                   daqFile->Close();
689                                   delete daqFile;
690                           }
691                           else{
692                                   Log("The Cumulative data file from DAQ does not exist, TOF exiting from Shuttle"); 
693                                   delete listTot;
694                                   delete fCal;
695                                   fCal=0x0;
696                                   return 6;//return error code for problems in retrieving DAQ data 
697                           }
698                   }
699                   delete listTot;
700           }
701   else{
702     Log("Problem: no list for Cumulative data file from DAQ was found, TOF exiting from Shuttle");
703     delete fCal;
704     fCal=0x0;
705     return 6; //return error code for problems in retrieving DAQ data 
706   }
707
708   /* check whether we don't need to update OCDB.
709    * in this case we can return without errors and
710    * the current FEE is stored in the fStatus object. */
711   if (!updateOCDB) {
712     AliInfo("update OCDB flag not set. Do not overwrite stored file.");
713     return 0; /* return ok */
714   }
715   
716   daqFile=0;
717   AliCDBMetaData metaData;
718   metaData.SetBeamPeriod(0);
719   metaData.SetResponsible("Chiara Zampolli");
720   metaData.SetComment("This preprocessor fills an AliTOFChannelOnlineArray object for online calibration - delays.");
721   AliInfo("Storing Calibration Data");
722   resultTOFPP = Store("Calib","ParOnlineDelay",fCal, &metaData,deltaStartingRun,kTRUE);
723   if(!resultTOFPP){
724     Log("Some problems occurred while storing online object resulting from DAQ data processing");
725     delete fCal;
726     fCal=0x0;
727     return 8;//return error code for problems in storing DAQ data 
728   }
729
730   if (fCal){
731     delete fCal;
732     fCal = 0;
733   }
734
735   return 0;
736 }
737
738 //_____________________________________________________________________________
739
740 UInt_t 
741 AliTOFPreprocessor::ProcessT0Fill()
742 {
743   // Processing data from DAQ for T0-fill measurement 
744
745   Log("Processing T0-fill");
746
747 #if 0
748   /* instance and setup CDB manager */
749   AliCDBManager *cdb = AliCDBManager::Instance();
750   /* load geometry */
751   if (!gGeoManager) AliGeomManager::LoadGeometry();
752 #endif
753
754   /* get params from OCDB */
755   AliCDBEntry *cdbe = NULL;
756
757   /* 
758    * at this stage status object is not on OCDB yet
759    * since it will be stored later. nevertheless we
760    * should have the array in memory since it has been
761    * already setup by ProcessFEF. 
762    */
763   
764   /* check status and latency window available */
765   if (!fStatus || !fLatencyWindow){
766     AliError("No valid fStatus or fLatencyWindow found, some errors must have occurred!!");
767     return 21;
768   }
769
770   /* get offline calibration from OCDB */
771   cdbe = GetFromOCDB("Calib", "ParOffline");
772   if (!cdbe) {
773     Log("cannot get \"ParOffline\" entry from OCDB");
774     return 21;
775   }
776   TObjArray *offlineArray = (TObjArray *)cdbe->GetObject();
777   AliTOFChannelOffline *channelOffline;
778   if (!offlineArray) {
779     Log("cannot get \"ParOffline\" object from CDB entry");
780     return 21;
781   }
782   Log("got \"ParOffline\" object");
783
784   /* get deltaBC offset from OCDB */
785   cdbe = GetFromOCDB("Calib", "DeltaBCOffset");
786   if (!cdbe) {
787     Log("cannot get \"DeltaBCOffset\" entry from OCDB");
788     return 21;
789   }
790   AliTOFDeltaBCOffset *deltaBCOffsetObject = (AliTOFDeltaBCOffset *)cdbe->GetObject();
791   if (!deltaBCOffsetObject) {
792     Log("cannot get \"DeltaBCOffset\" object from CDB entry");
793     return 21;
794   }
795   Int_t deltaBCOffset = deltaBCOffsetObject->GetDeltaBCOffset();
796   Log(Form("got \"DeltaBCOffset\" object: deltaBCOffset=%d (BC bins)", deltaBCOffset));
797
798   /* get CTP latency from OCDB */
799   cdbe = GetFromOCDB("Calib", "CTPLatency");
800   if (!cdbe) {
801     Log("cannot get \"CTPLatency\" entry from OCDB");
802     return 21;
803   }
804   AliTOFCTPLatency *ctpLatencyObject = (AliTOFCTPLatency *)cdbe->GetObject();
805   if (!ctpLatencyObject) {
806     Log("cannot get \"CTPLatency\" object from CDB entry");
807     return 21;
808   }
809   Float_t ctpLatency = ctpLatencyObject->GetCTPLatency();
810   Log(Form("got \"CTPLatency\" object: ctpLatency=%f (ps)", ctpLatency));
811   
812   /* get file sources from FXS */
813   TList *fileList = GetFileSources(kDAQ, "HITS");
814   if (!fileList || fileList->GetEntries() == 0) {
815     Log("cannot get DAQ source file list or empty list");
816     return 21;
817   }
818   Log(Form("got DAQ source file list: %d files", fileList->GetEntries()));
819   fileList->Print();
820   
821   /* create tree chain using file sources */
822   TChain chain("hitTree");
823   for (Int_t ifile = 0; ifile < fileList->GetEntries(); ifile++) {
824     TObjString *str = (TObjString *)fileList->At(ifile);
825     TString filename = GetFile(kDAQ, "HITS", str->GetName());
826     chain.Add(filename);
827     Log(Form("file added to input chain: source=%s, filename=%s", str->String().Data(), filename.Data()));
828   }
829   Int_t nhits = chain.GetEntries();
830   Log(Form("input chain ready: %d hits", nhits));
831
832   /* setup input chain */
833   AliTOFHitField *hit = new AliTOFHitField();
834   chain.SetBranchAddress("hit", &hit);
835
836   /* create calib histo and geometry */
837   AliTOFcalibHisto calibHisto;
838   calibHisto.LoadCalibHisto();
839   AliTOFGeometry tofGeo;
840
841   /* constants */
842   Float_t c = TMath::C() * 1.e2 / 1.e12; /* cm/ps */
843   Float_t c_1 = 1. / c;
844   /* variables */
845   Int_t index, timebin, totbin, deltaBC, l0l1latency, det[5];
846   Float_t timeps, totns, corrps, length, timeexp, timezero, pos[3], latencyWindow;
847
848   /* histos */
849   TH1F *hT0Fill = new TH1F("hT0Fill", "T0 fill;t - t_{exp}^{(c)} (ps);", 2000, -24400., 24400.);
850
851   /* loop over hits */
852   for (Int_t ihit = 0; ihit < nhits; ihit++) {
853
854     /* get entry */
855    chain.GetEntry(ihit);
856     
857     /* get hit info */
858     index = hit->GetIndex();
859     timebin = hit->GetTimeBin();
860     totbin = hit->GetTOTBin();
861     deltaBC = hit->GetDeltaBC();
862     l0l1latency = hit->GetL0L1Latency();
863     latencyWindow = fLatencyWindow[index] * 1.e3;
864     
865     /* convert time in ps and tot in ns */
866     timeps = timebin * AliTOFGeometry::TdcBinWidth();
867     totns = totbin * AliTOFGeometry::ToTBinWidth() * 1.e-3;
868     /* get calibration correction in ps */
869     
870
871     channelOffline = (AliTOFChannelOffline *)offlineArray->At(index);
872     if (totns < AliTOFGeometry::SlewTOTMin()) totns = AliTOFGeometry::SlewTOTMin();
873     if (totns > AliTOFGeometry::SlewTOTMax()) totns = AliTOFGeometry::SlewTOTMax();
874     corrps = 0.;
875     for (Int_t ipar = 0; ipar < 6; ipar++) corrps += channelOffline->GetSlewPar(ipar) * TMath::Power(totns, ipar);
876     corrps *= 1.e3;
877     /* perform time correction */
878     //    timeps = timeps + (deltaBC - deltaBCOffset) * AliTOFGeometry::BunchCrossingBinWidth() + l0l1latency * AliTOFGeometry::BunchCrossingBinWidth() + ctpLatency - latencyWindow - corrps; /* deltaBC correction removed for the time being */
879     timeps = timeps + l0l1latency * AliTOFGeometry::BunchCrossingBinWidth() + ctpLatency - latencyWindow - corrps;
880     /* compute length and expected time */
881     tofGeo.GetVolumeIndices(index, det);
882     tofGeo.GetPosPar(det, pos);
883     length = 0.;
884     for (Int_t i = 0; i < 3; i++) length += pos[i] * pos[i];
885     length = TMath::Sqrt(length);
886     timeexp = length * c_1;
887     /* compute time zero */
888     timezero = timeps - timeexp;
889     
890     /* fill histos */
891     hT0Fill->Fill(timezero);
892   }
893
894   /* rebin until maximum bin has required minimum entries */
895   Int_t maxBin = hT0Fill->GetMaximumBin();
896   Float_t maxBinContent = hT0Fill->GetBinContent(maxBin);
897   Float_t binWidth = hT0Fill->GetBinWidth(maxBin);
898   while (maxBinContent < 400 && binWidth < 90.) {
899     hT0Fill->Rebin(2);
900     maxBin = hT0Fill->GetMaximumBin();
901     maxBinContent = hT0Fill->GetBinContent(maxBin);
902     binWidth = hT0Fill->GetBinWidth(maxBin);
903   }
904   Float_t maxBinCenter = hT0Fill->GetBinCenter(maxBin);
905
906   /* rough fit of the edge */
907   TF1 *gaus = (TF1 *)gROOT->GetFunction("gaus");
908   gaus->SetParameter(1, maxBinCenter);
909   Float_t fitMin = maxBinCenter - 1000.; /* fit from 1 ns before max */
910   Float_t fitMax = maxBinCenter + 1000.; /* fit until 1 ns above max */
911   hT0Fill->Fit("gaus", "q0", "", fitMin, fitMax);
912   /* better fit of the edge */
913   Float_t mean, sigma;
914   for (Int_t istep = 0; istep < 10; istep++) {
915     mean = gaus->GetParameter(1);
916     sigma = gaus->GetParameter(2);
917     fitMin = mean - 3. * sigma;
918     fitMax = mean;
919     hT0Fill->Fit("gaus", "q0", "", fitMin, fitMax);
920   }
921   /* print params */
922   mean = gaus->GetParameter(1);
923   sigma = gaus->GetParameter(2);
924   Float_t meane = gaus->GetParError(1);
925   Float_t sigmae = gaus->GetParError(2);
926   Log(Form("edge fit: mean  = %f +- %f ps", mean, meane));
927   Log(Form("edge fit: sigma = %f +- %f ps", sigma, sigmae));
928   /* check error */
929   if (meane > 300.) {
930     Log("error on mean is large: store default T0-fill value (0 ps)");
931     mean = 0.;
932   }
933   if (sigmae > 300.) {
934     Log("error on sigma is large: store default TOFreso value (200 ps)");
935     sigma = 200.;
936   }
937
938   /* scratch values from the fit and use max bin center as t0-fill */
939   mean = maxBinCenter;
940   sigma = -1.;
941   Log(Form("do not care about fitted value, just use max bin as t0-fill: %f ps", mean));
942
943   /* create RunParams object */
944   UInt_t timestamp[1] = {0};
945   Float_t t0[1] = {mean};
946   Float_t tofReso[1] = {sigma};
947   Float_t t0Spread[1] = {-1.};
948   AliTOFRunParams *runParamsObject = new AliTOFRunParams(1);
949   runParamsObject->SetTimestamp(timestamp);
950   runParamsObject->SetT0(t0);
951   runParamsObject->SetTOFResolution(tofReso);
952   runParamsObject->SetT0Spread(t0Spread);
953
954   /* store reference data */
955   if(fStoreRefData){
956     AliCDBMetaData metaDataHisto;
957     metaDataHisto.SetBeamPeriod(0);
958     metaDataHisto.SetResponsible("Roberto Preghenella");
959     metaDataHisto.SetComment("online T0-fill histogram");
960     if (!StoreReferenceData("Calib","T0Fill", hT0Fill, &metaDataHisto)) {
961       Log("error while storing reference data");
962       delete hT0Fill;
963       delete hit;
964       delete runParamsObject;
965       return 21;
966     }
967     Log("reference data successfully stored");
968   }
969   
970   AliCDBMetaData metaData;
971   metaData.SetBeamPeriod(0);
972   metaData.SetResponsible("Roberto Preghenella");
973   metaData.SetComment("online RunParams measurement");
974   if (!Store("Calib", "RunParams", runParamsObject, &metaData, 0, kFALSE)) {
975     Log("error while storing RunParams object");
976     delete hT0Fill;
977     delete hit;
978     delete runParamsObject;
979     return 21;
980   }
981   Log("RunParams object successfully stored");
982
983   delete hT0Fill;
984   delete hit;
985   delete runParamsObject;
986   return 0;
987
988 }
989  
990 //_____________________________________________________________________________
991
992 UInt_t 
993 AliTOFPreprocessor::ProcessNoiseCalibTrg()
994 {
995   // Processing data from DAQ using calibration triggers for noise measurement 
996
997   Log("Processing Noise (calibration trigger)");
998
999   /* check status and matching window available */
1000   if (!fStatus || !fMatchingWindow){
1001     AliError("No valid fStatus or fMatchingWindow found, some errors must have occurred!!");
1002     return 22;
1003   }
1004
1005   Float_t noiseThr = 1000.;   // setting default threshold for noise to 1000 Hz
1006   // reading config map
1007   AliCDBEntry *cdbEntry = GetFromOCDB("Calib","ConfigNoise");
1008   if (!cdbEntry) Log(Form("No Configuration entry found in CDB, using default values: NoiseThr = %f",noiseThr));
1009   else {
1010     TMap *configMap = (TMap*)cdbEntry->GetObject();
1011     if (!configMap) Log(Form("No map found in Config entry in CDB, using default values: NoiseThr = %f", noiseThr));
1012     else {
1013       TObjString *strNoiseThr = (TObjString*)configMap->GetValue("NoiseThr");
1014       if (strNoiseThr) {
1015         TString tmpstr = strNoiseThr->GetString();
1016         noiseThr = tmpstr.Atoi();
1017       }
1018       else Log(Form("No NoiseThr value found in Map from ConfigNoise entry in CDB, using default value: NoiseThr = %f",noiseThr));
1019     }
1020   }
1021
1022   /* get file sources from FXS */
1023   TList *fileList = GetFileSources(kDAQ, "CALIB");
1024   if (!fileList || fileList->GetEntries() == 0) {
1025     Log("cannot get DAQ source file list or empty list");
1026     return 22;
1027   }
1028   Log(Form("got DAQ source file list: %d files", fileList->GetEntries()));
1029   fileList->Print();
1030
1031   /* open input file (only one expected) */
1032   TObjString *str = (TObjString *)fileList->At(0);
1033   TString filename = GetFile(kDAQ, "CALIB", str->GetName());
1034   Log(Form("opening input file: source=%s, filename=%s", str->String().Data(), filename.Data()));
1035   TFile *filein = TFile::Open(filename.Data());
1036   if (!filein || !filein->IsOpen()) {
1037     Log("cannot open input file");
1038     return 22;
1039   }
1040
1041   /* get histo from input file */
1042   TH1F *hCalibHit = (TH1F *)filein->Get("hCalibHit");
1043   if (!hCalibHit) {
1044     Log("cannot get \"hCalibHit\" histo");
1045     return 22;
1046   }
1047
1048   /* create and set noise rate histo and check rate */
1049   TH1F *hNoiseRate = new TH1F("hNoiseRate", ";index;rate (Hz)", fNChannels, 0., fNChannels);
1050   Float_t rate, rate_err;
1051   for (Int_t ich = 0; ich < fNChannels; ich++) {
1052     /* check channel enabled */
1053     if (fStatus->GetHWStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFHWBad) continue;
1054     /* set noise rate histo */
1055     rate = hCalibHit->GetBinContent(ich + 1);
1056     rate_err = hCalibHit->GetBinError(ich + 1);
1057     rate /= fMatchingWindow[ich] * 1.e-9;
1058     rate_err /= fMatchingWindow[ich] * 1.e-9;
1059     hNoiseRate->SetBinContent(ich + 1, rate);
1060     hNoiseRate->SetBinError(ich + 1, rate_err);
1061     /* check error */
1062     if (rate_err == 0.) continue;
1063     /* check noise rate and set noise flags */
1064     if ((rate - 3. * rate_err) > noiseThr) {
1065       Log(Form("channel %d detected as noisy: rate = (%f +- %f) Hz", ich, rate, rate_err));
1066       if (fStatus->GetNoiseStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFNoiseOk) {
1067         Log(Form("channel %d noise status changed from Ok to Bad", ich));
1068         fStatus->SetNoiseStatus(ich, AliTOFChannelOnlineStatusArray::kTOFNoiseBad);
1069         fIsStatusMapChanged = kTRUE;
1070       }
1071       else Log(Form("channel %d noise status unchanged", ich));
1072     }
1073     else if ((rate + 3. * rate_err) < noiseThr) {
1074       if (fStatus->GetNoiseStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFNoiseBad) {
1075         Log(Form("channel %d noise status changed from Bad to Ok", ich));
1076         fStatus->SetNoiseStatus(ich, AliTOFChannelOnlineStatusArray::kTOFNoiseOk);
1077         fIsStatusMapChanged = kTRUE;
1078       }
1079     }
1080   }
1081
1082   /* store reference data */
1083   if(fStoreRefData){
1084     AliCDBMetaData metaDataHisto;
1085     metaDataHisto.SetBeamPeriod(0);
1086     metaDataHisto.SetResponsible("Roberto Preghenella");
1087     metaDataHisto.SetComment("calibration trigger noise rate histogram");
1088     if (!StoreReferenceData("Calib","CalibNoise", hNoiseRate, &metaDataHisto)) {
1089       Log("error while storing reference data");
1090       delete hNoiseRate;
1091       filein->Close();
1092       return 22;
1093     }
1094     Log("reference data successfully stored");
1095   }
1096
1097   delete hNoiseRate;
1098   filein->Close();
1099   return 0;
1100 }
1101
1102 //_____________________________________________________________________________
1103
1104 UInt_t 
1105 AliTOFPreprocessor::ProcessReadout()
1106 {
1107   // Processing data from DAQ to compute reaodut efficiency
1108
1109   Log("Processing Readout");
1110
1111   /* get file sources from FXS */
1112   TList *fileList = GetFileSources(kDAQ, "READOUT");
1113   if (!fileList || fileList->GetEntries() == 0) {
1114     Log("cannot get DAQ source file list or empty list");
1115     return 22;
1116   }
1117   Log(Form("got DAQ source file list: %d files", fileList->GetEntries()));
1118   fileList->Print();
1119
1120   /* open input file (only one expected) */
1121   TObjString *str = (TObjString *)fileList->At(0);
1122   TString filename = GetFile(kDAQ, "READOUT", str->GetName());
1123   Log(Form("opening input file: source=%s, filename=%s", str->String().Data(), filename.Data()));
1124   TFile *filein = TFile::Open(filename.Data());
1125   if (!filein || !filein->IsOpen()) {
1126     Log("cannot open input file");
1127     return 23;
1128   }
1129
1130   /* get histo from input file */
1131   TH1F *hChainEfficiency = (TH1F *)filein->Get("hChainEfficiency");
1132   if (!hChainEfficiency) {
1133     Log("cannot get \"hChainEfficiency\" histo");
1134     return 23;
1135   }
1136
1137   /* fill channel efficiency histo */
1138
1139  /* temporarly disable warnings */
1140   AliLog::EType_t logLevel = (AliLog::EType_t)AliLog::GetGlobalLogLevel();
1141   AliLog::SetGlobalLogLevel(AliLog::kError);
1142
1143   TH1F *hChannelEfficiency = new TH1F("hChannelEfficiency", "Channel readout efficiency;index;efficiency", fNChannels, 0., fNChannels);
1144   Int_t chainIndex, det[5], dummy, index;
1145   Float_t effi, effi_err;
1146   /* loop over DDLs */
1147   for (Int_t iddl = 0; iddl < 72; iddl++) {
1148     /* loop over TRMs */
1149     for (Int_t itrm = 0; itrm < 10; itrm++) {
1150       /* loop over chains */
1151       for (Int_t ichain = 0; ichain < 2; ichain++) {
1152         chainIndex = ichain + 2 * itrm + 20 * iddl;
1153         effi = hChainEfficiency->GetBinContent(chainIndex + 1);
1154         effi_err = hChainEfficiency->GetBinError(chainIndex + 1);
1155         /* loop over TDCs */
1156         for (Int_t itdc = 0; itdc < 15; itdc++) {
1157           /* loop over channels */
1158           for (Int_t ichannel = 0; ichannel < 8; ichannel++) {
1159
1160             /* get channel index */
1161             AliTOFRawStream::EquipmentId2VolumeId(iddl, itrm + 3, ichain, itdc, ichannel, det);
1162             dummy = det[4];
1163             det[4] = det[3];
1164             det[3] = dummy;
1165             /* check valid index */
1166             if (det[0] < 0 || det[0] > 17 ||
1167                 det[1] < 0 || det[1] > 5 ||
1168                 det[2] < 0 || det[2] > 18 ||
1169                 det[3] < 0 || det[3] > 1 ||
1170                 det[4] < 0 || det[4] > 47) continue;
1171             index = AliTOFGeometry::GetIndex(det);
1172
1173             /* set channel efficiency */
1174             hChannelEfficiency->SetBinContent(index + 1, effi);
1175             hChannelEfficiency->SetBinError(index + 1, effi_err);
1176
1177           }
1178         }
1179       }
1180     }
1181   }
1182
1183   /* re-enable warnings */
1184   AliLog::SetGlobalLogLevel(logLevel);
1185
1186   /* store reference data */
1187   if(fStoreRefData){
1188     /* setup TOF readout info object */
1189     AliTOFReadoutInfo readoutInfo;
1190     readoutInfo.SetChainEfficiency((TH1F *)filein->Get("hChainEfficiency"));
1191     readoutInfo.SetTRMData((TH1F *)filein->Get("hTRMData"));
1192     readoutInfo.SetTRMEmptyEvent((TH1F *)filein->Get("hTRMEmptyEvent"));
1193     readoutInfo.SetTRMBadEventCounter((TH1F *)filein->Get("hTRMBadEventCounter"));
1194     readoutInfo.SetTRMBadCRC((TH1F *)filein->Get("hTRMBadCRC"));
1195     readoutInfo.SetChainData((TH1F *)filein->Get("hChainData"));
1196     readoutInfo.SetChainBadStatus((TH1F *)filein->Get("hChainBadStatus"));
1197     readoutInfo.SetChainBadEventCounter((TH1F *)filein->Get("hChainBadEventCounter"));
1198     readoutInfo.SetTDCError((TH1F *)filein->Get("hTDCError"));
1199     readoutInfo.SetTDCErrorFlags((TH2F *)filein->Get("hTDCErrorFlags"));
1200
1201     AliCDBMetaData metaDataHisto;
1202     metaDataHisto.SetBeamPeriod(0);
1203     metaDataHisto.SetResponsible("Roberto Preghenella");
1204     metaDataHisto.SetComment("readout info data");
1205     if (!StoreReferenceData("Calib","ReadoutInfo", &readoutInfo, &metaDataHisto)) {
1206       Log("error while storing reference data");
1207       filein->Close();
1208       return 23;
1209     }
1210     Log("reference data successfully stored");
1211   }
1212
1213   AliCDBMetaData metaData;
1214   metaData.SetBeamPeriod(0);
1215   metaData.SetResponsible("Roberto Preghenella");
1216   metaData.SetComment("online ReadoutEfficiency measurement");
1217   if (!Store("Calib", "ReadoutEfficiency", hChannelEfficiency, &metaData, 0, kFALSE)) {
1218     Log("error while storing ReadoutEfficiency object");
1219     delete hChannelEfficiency;
1220     filein->Close();
1221     return 23;
1222   }
1223   Log("ReadoutEfficiency object successfully stored");
1224
1225   delete hChannelEfficiency;
1226   filein->Close();
1227   return 0;
1228 }
1229
1230 //_____________________________________________________________________________
1231
1232 UInt_t AliTOFPreprocessor::ProcessPulserData()
1233 {
1234   // Processing Pulser Run data for TOF channel status
1235
1236   Log("Processing Pulser");
1237
1238   if (fStatus==0x0){
1239           AliError("No valid fStatus found, some errors must have occurred!!");
1240           return 20;
1241   }
1242
1243   TH1::AddDirectory(0);
1244   
1245   Bool_t resultPulserRef=kFALSE;
1246   Bool_t resultPulser=kFALSE;
1247   
1248   static const Int_t kSize = AliTOFGeometry::NPadXSector()*AliTOFGeometry::NSectors();
1249   TH1S * htofPulser = new TH1S("hTOFpulser","histo with signals on TOF during pulser", kSize,-0.5,kSize-0.5);
1250   for (Int_t ibin =1;ibin<=kSize;ibin++){
1251           htofPulser->SetBinContent(ibin,-1);
1252   }
1253   
1254   // processing pulser
1255   
1256   TFile * daqFile=0x0;
1257   TH1S *h1=0x0;
1258   
1259   //retrieving Pulser data 
1260   TList* listPulser = GetFileSources(kDAQ, "PULSER");
1261   if (listPulser !=0x0 && listPulser->GetEntries()!=0)
1262           {
1263                   AliInfo("The following sources produced files with the id PULSER");
1264                   listPulser->Print();
1265                   Int_t nPulser = 0;
1266                   for (Int_t jj=0;jj<listPulser->GetEntries();jj++){
1267                           Int_t nPulserSource = 0;
1268                           TObjString * str = dynamic_cast<TObjString*> (listPulser->At(jj));
1269                           if (!str) {
1270                             AliError("dynamic_cast returned NULL");
1271                             return 4;
1272                           }
1273                           AliInfo(Form("found source %s", str->String().Data()));
1274                           // file to be stored run per run
1275                           TString fileNamePulser = GetFile(kDAQ, "PULSER", str->GetName());
1276                           if (fileNamePulser.Length()>0){
1277                                   // storing refernce data
1278                                   AliInfo(Form("Got the file %s, now we can process pulser data.", fileNamePulser.Data()));
1279                                   daqFile = new TFile(fileNamePulser.Data(),"READ");
1280                                   h1 = (TH1S*) daqFile->Get("hTOFpulser");
1281                                   for (Int_t ibin=0;ibin<kSize;ibin++){
1282                                           if ((h1->GetBinContent(ibin+1))!=-1){
1283                                                   if ((htofPulser->GetBinContent(ibin+1))==-1){
1284                                                           htofPulser->SetBinContent(ibin+1,h1->GetBinContent(ibin+1));
1285                                                   }
1286                                                   else {
1287                                                           Log(Form("Something strange occurred during Pulser run, channel %i already read by another LDC, please check!",ibin));
1288                                                   }
1289                                           }
1290                                   }
1291                                   
1292                                   // elaborating infos
1293                                   Double_t mean =0;
1294                                   Int_t nread=0;
1295                                   Int_t nreadNotEmpty=0;
1296                                   for (Int_t ientry=1;ientry<=h1->GetNbinsX();ientry++){
1297                                           
1298                                           AliDebug(3,Form(" channel %i pulser status before pulser = %i, with global status = %i",ientry,(Int_t)fStatus->GetPulserStatus(ientry),(Int_t)fStatus->GetStatus(ientry)));
1299                                           /* check whether channel has been read out during current run.
1300                                            * if the status is bad it means it has not been read out.
1301                                            * in this case skip channel in order to not affect the mean */ 
1302                                           if (fStatus->GetHWStatus(ientry-1) == AliTOFChannelOnlineStatusArray::kTOFHWBad)
1303                                                   continue;
1304                                           nPulser++;
1305                                           nPulserSource++;
1306                                           if (h1->GetBinContent(ientry)==-1) continue;
1307                                           else {
1308                                                   if (h1->GetBinContent(ientry)>0) {
1309                                                           nreadNotEmpty++;
1310                                                           AliDebug(2,Form(" channel %i is ok with entry = %f; so far %i channels added ",ientry-1,h1->GetBinContent(ientry),nreadNotEmpty));
1311                                                   }
1312                                                   mean+=h1->GetBinContent(ientry);
1313                                                   nread++;
1314                                           }
1315                                   }
1316                                   if (nread!=0) {
1317                                           mean/=nread;
1318                                           AliDebug(2,Form(" nread =  %i , nreadNotEmpty = %i, mean = %f",nread,nreadNotEmpty,mean));
1319                                           for (Int_t ich =0;ich<fNChannels;ich++){
1320                                                   if (h1->GetBinContent(ich+1)==-1) continue;
1321                                                   AliDebug(3,Form(" channel %i pulser status before pulser = %i",ich,(Int_t)fStatus->GetPulserStatus(ich)));
1322                                                   
1323                                                   /* check whether channel has been read out during current run.
1324                                                    * if the status is bad it means it has not been read out.
1325                                                    * in this case skip channel in order to leave its status 
1326                                                    * unchanged */
1327                                                   if (fStatus->GetHWStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFHWBad)
1328                                                           continue;
1329                                                   
1330                                                   if (h1->GetBinContent(ich+1)<0.05*mean){
1331                                                           fStatus->SetPulserStatus(ich,AliTOFChannelOnlineStatusArray::kTOFPulserBad);  // bad status for pulser
1332                                                           AliDebug(2,Form( " channel %i pulser status after pulser = %i (bad, content = %f), with global status = %i",ich,(Int_t)fStatus->GetPulserStatus(ich),h1->GetBinContent(ich+1),(Int_t)fStatus->GetStatus(ich)));
1333                                                   }
1334                                                   else {
1335                                                           fStatus->SetPulserStatus(ich,AliTOFChannelOnlineStatusArray::kTOFPulserOk);  // good status for pulser
1336                                                           AliDebug(2,Form( " channel %i pulser status after pulser = %i (good), with global status = %i",ich,(Int_t)fStatus->GetPulserStatus(ich),(Int_t)fStatus->GetStatus(ich)));
1337                                                   }
1338                                           }
1339                                   }
1340                                   else {
1341                                           Log("No channels read!! No action taken, keeping old status");
1342                                   }
1343                                   
1344                                   daqFile->Close();
1345                                   delete daqFile;
1346                                   delete h1;
1347                           }
1348                           
1349                           else{
1350                                   Log("The input data file from DAQ (pulser) was not found, TOF exiting from Shuttle "); 
1351                                   delete listPulser;
1352                                   delete htofPulser;
1353                                   htofPulser = 0x0;
1354                                   if (fStatus){
1355                                           delete fStatus;
1356                                           fStatus = 0;
1357                                   }
1358                                   return 10;//return error code for failure in retrieving Ref Data 
1359                           }
1360                           AliDebug(2,Form(" Number of channels processed during pulser run from source %i = %i",jj, nPulserSource));             
1361                   }
1362                   AliDebug(2,Form(" Number of channels processed during pulser run = %i",nPulser));
1363                   delete listPulser;
1364           }
1365   
1366   else{
1367           Log("The input data file list from DAQ (pulser) was not found, TOF exiting from Shuttle "); 
1368           delete htofPulser;
1369           htofPulser = 0x0;
1370           if (fStatus){
1371                   delete fStatus;
1372                   fStatus = 0;
1373           }
1374           return 10;//return error code for failure in retrieving Ref Data 
1375   }     
1376   
1377   //storing in OCDB  
1378   
1379   AliCDBMetaData metaData;
1380   metaData.SetBeamPeriod(0);
1381   metaData.SetResponsible("Chiara Zampolli");
1382   metaData.SetComment("This preprocessor fills an AliTOFChannelOnlineStatusArray object after a Pulser run.");
1383   AliInfo("Storing Calibration Data from Pulser Run");
1384   resultPulser = Store("Calib","Status",fStatus, &metaData,0,kTRUE);
1385   if(!resultPulser){
1386     Log("Some problems occurred while storing online object resulting from Pulser data processing");
1387     delete htofPulser;
1388     htofPulser = 0x0;
1389     if (fStatus){
1390             delete fStatus;
1391             fStatus = 0;
1392     }
1393     return 11;//return error code for problems in storing Pulser data 
1394   }
1395
1396   if(fStoreRefData){
1397     
1398     AliCDBMetaData metaDataHisto;
1399     metaDataHisto.SetBeamPeriod(0);
1400     metaDataHisto.SetResponsible("Chiara Zampolli");
1401     metaDataHisto.SetComment("This preprocessor stores the Ref data from a pulser run.");
1402     AliInfo("Storing Reference Data");
1403     resultPulserRef = StoreReferenceData("Calib","PulserData",htofPulser, &metaDataHisto);
1404     if (!resultPulserRef){
1405       Log("some problems occurred::No Reference Data for pulser stored, TOF exiting from Shuttle");
1406       delete htofPulser;
1407       htofPulser = 0x0;
1408       if (fStatus){
1409               delete fStatus;
1410               fStatus = 0;
1411       }
1412       return 9;//return error code for failure in storing Ref Data 
1413     }
1414   }
1415   
1416   daqFile=0;
1417
1418   delete htofPulser;
1419   htofPulser = 0x0;
1420
1421   if (fStatus){
1422     delete fStatus;
1423     fStatus = 0;
1424   }
1425
1426   return 0;
1427 }
1428 //_____________________________________________________________________________
1429
1430 UInt_t AliTOFPreprocessor::ProcessNoiseData()
1431 {
1432
1433   // Processing Noise Run data for TOF channel status
1434
1435   Log("Processing Noise");
1436
1437   if (fStatus==0x0){
1438           AliError("No valid fStatus found, some errors must have occurred!!");
1439           return 20;
1440   }
1441
1442   Float_t noiseThr = 1;   // setting default threshold for noise to 1 Hz
1443   // reading config map
1444   AliCDBEntry *cdbEntry = GetFromOCDB("Calib","ConfigNoise");
1445   if (!cdbEntry) {
1446           Log(Form("No Configuration entry found in CDB, using default values: NoiseThr = %f",noiseThr));
1447   }
1448   else {
1449           TMap *configMap = (TMap*)cdbEntry->GetObject();
1450           if (!configMap){
1451                   Log(Form("No map found in Config entry in CDB, using default values: NoiseThr = %f", noiseThr));
1452           }
1453           else{
1454                   TObjString *strNoiseThr = (TObjString*)configMap->GetValue("NoiseThr");
1455                   if (strNoiseThr) {
1456                           TString tmpstr = strNoiseThr->GetString();
1457                           noiseThr = tmpstr.Atoi();
1458                   }
1459                   else {
1460                           Log(Form("No NoiseThr value found in Map from ConfigNoise entry in CDB, using default value: NoiseThr = %f",noiseThr));
1461                   }
1462           }
1463   }
1464
1465   delete cdbEntry;
1466   cdbEntry = 0x0;
1467
1468   TH1::AddDirectory(0);
1469
1470   Bool_t resultNoiseRef=kFALSE;
1471   Bool_t resultNoise=kFALSE;
1472
1473   static const Int_t kSize = AliTOFGeometry::NPadXSector()*AliTOFGeometry::NSectors();
1474   TH1F * htofNoise = new TH1F("hTOFnoise","histo with signals on TOF during noise", kSize,-0.5,kSize-0.5);
1475   for (Int_t ibin =1;ibin<=kSize;ibin++){
1476           htofNoise->SetBinContent(ibin,-1);
1477   }
1478   
1479   // processing noise
1480   
1481   TFile * daqFile=0x0;
1482   TH1F * h1=0x0;
1483   
1484   // useful counters
1485   Int_t nNoise = 0;
1486   Int_t nNoisyChannels = 0;
1487   Int_t nNotNoisyChannels = 0;
1488   Int_t nChannelsFromDA = 0;
1489   Int_t nMatchingWindowNullNonZero = 0;
1490   Int_t nMatchingWindowNullEqualZero = 0;
1491
1492   // retrieving Noise data 
1493   TList* listNoise = GetFileSources(kDAQ, "NOISE");
1494   if (listNoise !=0x0 && listNoise->GetEntries()!=0)
1495           {
1496                   AliInfo("The following sources produced files with the id NOISE");
1497                   listNoise->Print();
1498                   for (Int_t jj=0;jj<listNoise->GetEntries();jj++){
1499                           Int_t nNoiseSource = 0;
1500                           TObjString * str = dynamic_cast<TObjString*> (listNoise->At(jj));
1501                           if (!str) {
1502                             AliError("dynamic_cast returned NULL");
1503                             return 4;
1504                           }
1505                           AliInfo(Form("found source %s", str->String().Data()));
1506                           // file to be stored run per run
1507                           TString fileNameNoise = GetFile(kDAQ, "NOISE", str->GetName());
1508                           if (fileNameNoise.Length()>0){
1509                                   // storing reference data
1510                                   AliInfo(Form("Got the file %s, now we can process noise data.", fileNameNoise.Data()));
1511                                   daqFile = new TFile(fileNameNoise.Data(),"READ");
1512                                   h1 = (TH1F*) daqFile->Get("hTOFnoise");
1513                                   for (Int_t ibin=0;ibin<kSize;ibin++){
1514                                           if ((h1->GetBinContent(ibin+1))!=-1){
1515                                                   nNoiseSource++;
1516                                                   // checking the matching window for current channel
1517                                                   if (fMatchingWindow[ibin] == 0){
1518                                                           Log(Form("Matching window for channel %i null, but the channel was read by the LDC! skipping channel, BUT Please check!",ibin));
1519                                                           if ((h1->GetBinContent(ibin+1))!=0) nMatchingWindowNullNonZero++;                                             
1520                                                           if ((h1->GetBinContent(ibin+1))==0) nMatchingWindowNullEqualZero++;                                           
1521                                                           continue;
1522                                                   }
1523                                                   if ((htofNoise->GetBinContent(ibin+1))==-1){
1524                                                           htofNoise->SetBinContent(ibin+1,h1->GetBinContent(ibin+1)/(fMatchingWindow[ibin]*1.E-9));
1525                                                           if ((h1->GetBinContent(ibin+1))!= 0) AliDebug(2,Form("Channel = %i, Matching window = %i, Content = %f", ibin, fMatchingWindow[ibin], htofNoise->GetBinContent(ibin+1)));
1526                                                   }
1527                                                   else {
1528                                                           Log(Form("Something strange occurred during Noise run, channel %i already read by another LDC, please check!",ibin));
1529                                                   }
1530                                           }
1531                                   }
1532
1533                                   Log(Form(" Number of channels processed during noise run from source %i = %i",jj, nNoiseSource));
1534                                   daqFile->Close();
1535                                   delete daqFile;
1536                                   delete h1;
1537                                   daqFile = 0x0;
1538                                   h1 = 0x0;
1539
1540                           }
1541                           else{
1542                                   Log("The input data file from DAQ (noise) was not found, TOF exiting from Shuttle "); 
1543                                   delete listNoise;
1544                                   listNoise = 0x0;
1545                                   delete htofNoise;
1546                                   htofNoise = 0x0;
1547                                   if (fStatus){
1548                                           delete fStatus;
1549                                           fStatus = 0;
1550                                   }
1551                                   if (fMatchingWindow){
1552                                           delete [] fMatchingWindow;
1553                                           fMatchingWindow = 0;
1554                                   }
1555                                   return 13;//return error code for failure in retrieving Ref Data 
1556                           }
1557                   }               
1558           }
1559                           
1560   else{
1561           Log("The input data file list from DAQ (noise) was not found, TOF exiting from Shuttle "); 
1562           delete htofNoise;
1563           htofNoise = 0x0;
1564           if (fStatus){
1565                   delete fStatus;
1566                   fStatus = 0;
1567           }
1568           if (fMatchingWindow){
1569                   delete [] fMatchingWindow;
1570                   fMatchingWindow = 0;
1571           }
1572           return 13;//return error code for failure in retrieving Ref Data 
1573   }     
1574   
1575   // elaborating infos to set NOISE status
1576   for (Int_t ich =0;ich<fNChannels;ich++){
1577           if (htofNoise->GetBinContent(ich+1)== -1) continue;
1578
1579           nChannelsFromDA++;
1580
1581           AliDebug(3,Form(" channel %i noise status before noise = %i, with global status = %i",ich,(Int_t)fStatus->GetNoiseStatus(ich),(Int_t)fStatus->GetStatus(ich)));
1582           //AliDebug(2,Form( " channel %i status before noise = %i",ich,(Int_t)fStatus->GetNoiseStatus(ich)));
1583           
1584           /* check whether channel has been read out during current run.
1585            * if the status is bad it means it has not been read out.
1586            * in this case skip channel in order to leave its status 
1587            * unchanged */
1588
1589           if ((fStatus->GetHWStatus(ich)) == AliTOFChannelOnlineStatusArray::kTOFHWBad)
1590                   continue;
1591           
1592           nNoise++;
1593           if (htofNoise->GetBinContent(ich+1) >= noiseThr){
1594                   fStatus->SetNoiseStatus(ich,AliTOFChannelOnlineStatusArray::kTOFNoiseBad); // bad status for noise
1595                   AliDebug(3,Form( " channel %i noise status after noise = %i, with global status = %i",ich,(Int_t)fStatus->GetNoiseStatus(ich),(Int_t)fStatus->GetStatus(ich)));
1596                   nNoisyChannels++;
1597           }
1598           else {
1599                   fStatus->SetNoiseStatus(ich,AliTOFChannelOnlineStatusArray::kTOFNoiseOk); // good status for noise
1600                   AliDebug(3,Form(" channel %i noise status after noise = %i, with global status = %i",ich,(Int_t)fStatus->GetNoiseStatus(ich),(Int_t)fStatus->GetStatus(ich)));
1601                   nNotNoisyChannels++;
1602           }
1603   }
1604   
1605   Log(Form(" Number of channels processed by DA during noise run, independetly from TOFFEE = %i",nChannelsFromDA));
1606   Log(Form(" Number of channels processed during noise run (that were ON according to TOFFEE) = %i",nNoise));
1607   Log(Form(" Number of noisy channels found during noise run = %i",nNoisyChannels));
1608   Log(Form(" Number of not noisy channels found during noise run = %i",nNotNoisyChannels));
1609   Log(Form(" Number of channels with matching window NULL (so skipped), but Non Zero content = %i",nMatchingWindowNullNonZero));
1610   Log(Form(" Number of channels with matching window NULL (so skipped), and Zero content = %i",nMatchingWindowNullEqualZero));
1611
1612   delete listNoise;
1613   
1614   //daqFile=0;
1615   
1616   //storing in OCDB
1617   
1618   AliCDBMetaData metaData;
1619   metaData.SetBeamPeriod(0);
1620   metaData.SetResponsible("Chiara Zampolli");
1621   metaData.SetComment("This preprocessor fills an AliTOFChannelOnlineStatusArray object after a Noise run.");
1622   AliInfo("Storing Calibration Data from Noise Run");
1623   resultNoise = Store("Calib","Status",fStatus, &metaData,0,kTRUE);
1624   if(!resultNoise){
1625     Log("Some problems occurred while storing online object resulting from Noise data processing");
1626     delete htofNoise;
1627     htofNoise = 0x0;
1628     if (fStatus){
1629             delete fStatus;
1630             fStatus = 0;
1631     }
1632     if (fMatchingWindow){
1633             delete [] fMatchingWindow;
1634             fMatchingWindow = 0;
1635     }
1636     return 14;//return error code for problems in storing Noise data 
1637   }
1638
1639   if(fStoreRefData){
1640     
1641     AliCDBMetaData metaDataHisto;
1642     metaDataHisto.SetBeamPeriod(0);
1643     metaDataHisto.SetResponsible("Chiara Zampolli");
1644     metaDataHisto.SetComment("This preprocessor stores the Ref data from a noise run. ");
1645     AliInfo("Storing Reference Data");
1646     resultNoiseRef = StoreReferenceData("Calib","NoiseData",htofNoise, &metaDataHisto);
1647     if (!resultNoiseRef){
1648       Log("some problems occurred::No Reference Data for noise stored");
1649       delete htofNoise;
1650       htofNoise = 0x0;
1651       if (fStatus){
1652               delete fStatus;
1653               fStatus = 0;
1654       }
1655       if (fMatchingWindow){
1656               delete [] fMatchingWindow;
1657               fMatchingWindow = 0;
1658       }
1659       return 12;//return error code for failure in storing Ref Data 
1660     }
1661   }
1662
1663   delete htofNoise;
1664   htofNoise = 0x0;
1665
1666   if (fStatus){
1667     delete fStatus;
1668     fStatus = 0;
1669   }
1670
1671   if (fMatchingWindow){
1672           delete [] fMatchingWindow;
1673           fMatchingWindow = 0;
1674   }
1675
1676   return 0;
1677 }
1678 //_____________________________________________________________________________
1679
1680 UInt_t AliTOFPreprocessor::ProcessFEEData()
1681 {
1682   // Processing Pulser Run data for TOF channel status
1683   // dummy for the time being
1684
1685   Log("Processing FEE");
1686
1687   //Bool_t updateOCDB = kFALSE;
1688   AliTOFFEEReader feeReader;
1689
1690   TH1C hCurrentFEE("hCurrentFEE","histo with current FEE channel status", fNChannels, 0, fNChannels);
1691   
1692   /* load current TOF FEE(dump) from DCS FXS, 
1693    * setup TOFFEEdump object */
1694
1695   const char * toffeeFileName = GetFile(kDCS,"TofFeeMap",""); 
1696   AliInfo(Form("toffee file name = %s", toffeeFileName));
1697   if (toffeeFileName == NULL) {
1698     return 15;
1699   } 
1700   AliTOFFEEDump feedump;
1701   feedump.ReadFromFile(toffeeFileName);
1702   
1703   /* load current TOF FEE(light) config from DCS FXS, parse, 
1704    * fill current FEE histogram and set FEE status */
1705   
1706   const char * nameFile = GetFile(kDCS,"TofFeeLightMap",""); 
1707   AliInfo(Form("toffeeLight file name = %s",nameFile));
1708   if (nameFile == NULL) {
1709           return 15;
1710   } 
1711   feeReader.LoadFEElightConfig(nameFile);
1712   Int_t parseFee = feeReader.ParseFEElightConfig();
1713   AliDebug(2,Form("%i enabled channels found in FEElight configuration",parseFee));
1714   /* load stored TOF FEE from OCDB and compare it with current FEE.
1715    * if stored FEE is different from current FEE set update flag.
1716    * if there is no stored FEE in OCDB set update flag */
1717   
1718   fMatchingWindow = new Int_t[fNChannels];
1719   fLatencyWindow = new Int_t[fNChannels];
1720   
1721   AliCDBEntry *cdbEntry = GetFromOCDB("Calib","Status");
1722   if (!cdbEntry) {
1723           /* no CDB entry found. set update flag */
1724           Log("     ************ WARNING ************");
1725           Log("No CDB Status entry found, creating a new one!");
1726           Log("     *********************************");
1727           fStatus = new AliTOFChannelOnlineStatusArray(fNChannels);
1728           //updateOCDB = kTRUE;
1729           fIsStatusMapChanged = kTRUE;
1730   }
1731   else {
1732           if (cdbEntry) cdbEntry->SetOwner(kFALSE);
1733           /* CDB entry OK. loop over channels */
1734           fStatus = (AliTOFChannelOnlineStatusArray*) cdbEntry->GetObject();
1735           delete cdbEntry;
1736           cdbEntry = 0x0;
1737           /* cehck whether status object has latency window data */
1738           if (!fStatus->HasLatencyWindow()) {
1739             /* create new status object and update OCDB */
1740             Log("     ************ WARNING ************");
1741             Log("CDB Status entry found but has no latency window data, creating a new one!");
1742             Log("     *********************************");
1743             delete fStatus;
1744             fStatus = new AliTOFChannelOnlineStatusArray(fNChannels);
1745             //updateOCDB = kTRUE;
1746             fIsStatusMapChanged = kTRUE;
1747           }
1748   }
1749   for (Int_t iChannel = 0; iChannel < fNChannels; iChannel++){
1750           //AliDebug(2,Form("********** channel %i",iChannel));
1751           /* compare current FEE channel status with stored one 
1752            * if different set update flag and break loop */
1753           //AliDebug(2,Form( " channel %i status before FEE = %i",iChannel,(Int_t)fStatus->GetHWStatus(iChannel)));
1754           fMatchingWindow[iChannel] = feeReader.GetMatchingWindow(iChannel);
1755           fLatencyWindow[iChannel] = feeReader.GetLatencyWindow(iChannel);
1756           if (feeReader.IsChannelEnabled(iChannel)) {
1757                   hCurrentFEE.SetBinContent(iChannel + 1, 1);
1758                   if (fStatus->GetHWStatus(iChannel)!=AliTOFChannelOnlineStatusArray::kTOFHWOk){
1759                           //updateOCDB = kTRUE;
1760                           fIsStatusMapChanged = kTRUE;
1761                           fStatus->SetHWStatus(iChannel,AliTOFChannelOnlineStatusArray::kTOFHWOk);
1762                           AliDebug(3,Form( " changed into enabled: channel %i status after FEE = %i",iChannel,(Int_t)fStatus->GetHWStatus(iChannel)));
1763                   }
1764                   if (fStatus->GetLatencyWindow(iChannel)!=fLatencyWindow[iChannel]){
1765                           //updateOCDB = kTRUE;
1766                           fIsStatusMapChanged = kTRUE;
1767                           fStatus->SetLatencyWindow(iChannel,fLatencyWindow[iChannel]);
1768                           AliDebug(3,Form( " changed latency window: channel %i latency window after FEE = %i",iChannel,fStatus->GetLatencyWindow(iChannel)));
1769                   }
1770           }
1771           else {
1772                   if (fStatus->GetHWStatus(iChannel)!=AliTOFChannelOnlineStatusArray::kTOFHWBad){
1773                           //updateOCDB = kTRUE;
1774                           fIsStatusMapChanged = kTRUE;
1775                           fStatus->SetHWStatus(iChannel,AliTOFChannelOnlineStatusArray::kTOFHWBad);
1776                           AliDebug(3,Form( " changed into disabled: channel %i status after FEE = %i",iChannel,(Int_t)fStatus->GetHWStatus(iChannel)));
1777                   }
1778           }
1779   }
1780
1781
1782   /* check whether we don't have to store reference data.
1783    * in this case we return without errors. */
1784   if (fStoreRefData) {
1785     /* store reference data */
1786     AliCDBMetaData metaDataHisto;
1787     metaDataHisto.SetBeamPeriod(0);
1788     metaDataHisto.SetResponsible("Roberto Preghenella");
1789     metaDataHisto.SetComment("This preprocessor stores the FEE Ref data of the current run.");
1790     AliInfo("Storing FEE reference data");
1791     /* store FEE reference data */
1792     if (!StoreReferenceData("Calib", "FEEData", &hCurrentFEE, &metaDataHisto)) {
1793       /* failed */
1794       Log("problems while storing FEE reference data");
1795       if (fStatus){
1796         delete fStatus;
1797         fStatus = 0;
1798       }
1799       return 18; /* error return code for problems while storing FEE reference data */
1800     }
1801     
1802     /* store TOF FEE dump reference data */
1803     AliCDBMetaData metaDatadump;
1804     metaDatadump.SetBeamPeriod(0);
1805     metaDatadump.SetResponsible("Roberto Preghenella");
1806     metaDatadump.SetComment("This preprocessor stores the TOF FEE dump Ref data of the current run.");
1807     AliInfo("Storing TOF FEE dump reference data");
1808     /* store FEE reference data */
1809     if (!StoreReferenceData("Calib", "FEEDump", &feedump, &metaDatadump)) {
1810       /* failed */
1811       Log("problems while storing TOF FEE dump reference data");
1812       return 18; /* error return code for problems while storing FEE reference data */
1813     }
1814   }
1815
1816   return 0;
1817
1818 }
1819
1820 //_____________________________________________________________________________
1821
1822 UInt_t AliTOFPreprocessor::Process(TMap *dcsAliasMap)
1823 {
1824   //
1825   // Main AliTOFPreprocessor method called by SHUTTLE
1826   //
1827
1828   TString runType = GetRunType();
1829   Log(Form("RunType %s",runType.Data()));
1830   
1831   // processing 
1832
1833   /* always process FEE data */
1834   Int_t iresultFEE = ProcessFEEData();
1835   if (iresultFEE != 0)
1836     return iresultFEE;
1837
1838   if (runType == "PULSER") {
1839     Int_t iresultPulser = ProcessPulserData();
1840     return iresultPulser; 
1841   }
1842
1843   if (runType == "NOISE") { // for the time being associating noise runs with pedestal runs; proper run type to be defined 
1844     Int_t iresultNoise = ProcessNoiseData();
1845     return iresultNoise; 
1846   }
1847  
1848   if (runType == "PHYSICS") {
1849     //    Int_t iresultDAQ = ProcessOnlineDelays();
1850     Int_t iresultDAQ = ProcessT0Fill();
1851     Int_t iresultNoiseCalib = ProcessNoiseCalibTrg();
1852     Int_t iresultReadout = ProcessReadout();
1853     Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
1854     Int_t iResultHVandLVdps = ProcessHVandLVdps(dcsAliasMap);
1855     return iresultDAQ+iresultNoiseCalib+iresultDCS+iResultHVandLVdps+iresultReadout;
1856   }
1857
1858   // storing
1859   return 0;
1860 }
1861
1862
1863 //_____________________________________________________________________________
1864
1865 void
1866 AliTOFPreprocessor::FillWithCosmicCalibration(AliTOFChannelOnlineArray *cal)
1867 {
1868   /*
1869    * fill with cosmic calibration 
1870    */
1871
1872   Log(" Using cosmic-ray calibration.");
1873   
1874   AliTOFcalibHisto calibHisto;
1875   calibHisto.SetFullCorrectionFlag(AliTOFcalibHisto::kTimeSlewingCorr, kFALSE);
1876   Log(Form(" loading calibration histograms from %s", calibHisto.GetCalibHistoFileName()));
1877   Log(Form(" loading calibration parameters from %s", calibHisto.GetCalibParFileName()));
1878   calibHisto.LoadCalibPar();
1879   
1880   /* loop over channel index */
1881   for (Int_t iIndex = 0; iIndex < fNChannels; iIndex++) {
1882     cal->SetDelay(iIndex, calibHisto.GetFullCorrection(iIndex));
1883   }
1884   
1885 }
1886
1887 //_____________________________________________________________________________
1888
1889 void
1890 AliTOFPreprocessor::FillWithCableLengthMap(AliTOFChannelOnlineArray *cal)
1891 {
1892   /*
1893    * fill with cosmic calibration 
1894    */
1895   
1896   Log(" Using cable-length map.");
1897   AliTOFRawStream tofrs;
1898   Int_t det[5], dummy, index;
1899   Float_t cableTimeShift;
1900   
1901   /* temporarly disable warnings */
1902   AliLog::EType_t logLevel = (AliLog::EType_t)AliLog::GetGlobalLogLevel();
1903   AliLog::SetGlobalLogLevel(AliLog::kError);
1904   
1905   /* loop over EO indeces */
1906   for (Int_t iddl = 0; iddl < 72; iddl++)
1907     for (Int_t islot = 3; islot <= 12; islot++)
1908       for (Int_t ichain = 0; ichain < 2; ichain++)
1909         for (Int_t itdc = 0; itdc < 15; itdc++)
1910           for (Int_t ichannel = 0; ichannel < 8; ichannel++) {
1911             
1912             /* get DO index */
1913             tofrs.EquipmentId2VolumeId(iddl, islot, ichain, itdc, ichannel, det);
1914             
1915             /* swap det[3] and det[4] indeces (needed to obtain correct channel index) */
1916             dummy = det[3];
1917             det[3] = det[4];
1918             det[4] = dummy;
1919             
1920             /* check DO index */
1921             if (det[0] < 0 || det[0] > 17 ||
1922                 det[1] < 0 || det[1] > 4 ||
1923                 det[2] < 0 || det[2] > 18 ||
1924                 det[3] < 0 || det[3] > 1 ||
1925                 det[4] < 0 || det[4] > 47)
1926               continue;
1927             
1928             /* get channel index */
1929             index = AliTOFGeometry::GetIndex(det);
1930             if (index < 0) continue;
1931             
1932             /* get cable time shift */
1933             cableTimeShift = AliTOFCableLengthMap::GetCableTimeShift(iddl, islot, ichain, itdc);
1934             
1935             /* set delay */
1936             if (index<fNChannels) {
1937               cal->SetDelay(index,cableTimeShift);  // delay in ns
1938               AliDebug(2,Form("Setting delay %f (ns) for channel %i",cableTimeShift,index));
1939             }
1940             
1941           } /* loop over EO indeces */
1942   
1943   /* re-enable warnings */
1944   AliLog::SetGlobalLogLevel(logLevel);
1945   
1946 }
1947
1948