]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TOF/AliTOFPreprocessor.cxx
fix in energy-loss correction in TOF tracker, removed TEXP correction
[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                                   AliInfo(Form("found source %s", str->String().Data()));
510                                   // file to be stored run per run
511                                   TString fileNameRun = GetFile(kDAQ, "RUNLevel", str->GetName());
512                                   if (fileNameRun.Length()>0){
513                                           AliInfo(Form("Got the file %s, now we can store the Reference Data for the current Run.", fileNameRun.Data()));
514                                           daqFile = new TFile(fileNameRun.Data(),"READ");
515                                           h2 = (TH2S*) daqFile->Get("htof");
516                                           AliCDBMetaData metaDataHisto;
517                                           metaDataHisto.SetBeamPeriod(0);
518                                           metaDataHisto.SetResponsible("Chiara Zampolli");
519                                           metaDataHisto.SetComment("This preprocessor stores the array of histos object as Reference Data.");
520                                           AliInfo("Storing Reference Data");
521                                           resultDAQRef = StoreReferenceData("Calib","DAQData",h2, &metaDataHisto);
522                                           if (!resultDAQRef){
523                                                   Log("some problems occurred::No Reference Data stored, TOF exiting from Shuttle");
524                                                   delete h2;
525                                                   delete list;
526                                                   delete fCal;
527                                                   fCal=0x0;
528                                                   return 5;//return error code for failure in storing Ref Data 
529                                           }
530                                           daqFile->Close();
531                                           delete daqFile;
532                                   }
533                                   
534                                   else{
535                                           Log("The input data file from DAQ (run-level) was not found, TOF exiting from Shuttle "); 
536                                           delete list;
537                                           delete fCal;
538                                           fCal=0x0;
539                                           return 4;//return error code for failure in retrieving Ref Data 
540                                   }
541                           }
542                           delete list;
543                   }
544           else{
545                   Log("The input data file list from DAQ (run-level) was not found, TOF exiting from Shuttle "); 
546                   delete fCal;
547                   fCal=0x0;
548                   return 4;//return error code for failure in retrieving Ref Data 
549           }     
550   }
551
552
553   //Total files, with cumulative histos
554   
555   TList* listTot = GetFileSources(kDAQ, "DELAYS");
556   if (listTot !=0x0 && listTot->GetEntries()!=0)
557           {
558                   AliInfo("The following sources produced files with the id DELAYS");
559                   listTot->Print();
560                   for (Int_t jj=0;jj<listTot->GetEntries();jj++){
561                           TObjString * str = dynamic_cast<TObjString*> (listTot->At(jj));
562                           AliInfo(Form("found source %s", str->String().Data()));
563                           
564                           // file with summed histos, to extract calib params
565                           TString fileName = GetFile(kDAQ, "DELAYS", str->GetName());
566                           if (fileName.Length()>0){
567                                   AliInfo(Form("Got the file %s, now we can extract some values.", fileName.Data()));
568                                   
569                                   daqFile = new TFile(fileName.Data(),"READ");
570                                   if (h2) delete h2;
571                                   h2 = (TH2S*) daqFile->Get("htoftot");
572                                   if (!h2){
573                                           Log("some problems occurred:: No histo retrieved, TOF exiting from Shuttle");
574                                           delete listTot;
575                                           delete daqFile;
576                                           delete fCal;
577                                           fCal=0x0;
578                                           return 7; //return error code for histograms not existing/junky
579                                   }
580                                   else {
581                                           static const Int_t kSize=h2->GetNbinsX();
582                                           static const Int_t kNBins=h2->GetNbinsY();
583                                           static const Double_t kXBinmin=h2->GetYaxis()->GetBinLowEdge(1);
584                                           if (kSize != fNChannels){
585                                                   Log(" number of bins along x different from number of pads, found only a subset of the histograms, TOF exiting from Shuttle");
586                                                   delete listTot;
587                                                   delete h2;
588                                                   delete daqFile;
589                                                   delete fCal;
590                                                   fCal=0x0;
591                                                   return 7; //return error code for histograms not existing/junky
592                                           }
593                                           Int_t nNotStatistics = 0; // number of channel with not enough statistics
594
595                                           /* FDR flag set. do not compute delays, use nominal cable delays */
596                                           if (fFDRFlag) {
597
598                                             Log(" Not computing delays according to flag set in Config entry in OCDB!");
599                                             FillWithCosmicCalibration(fCal);
600
601                                             /* check whether the new calibration is different from the previous one */
602                                             if (curCal) { /* well, check also whether we have a previous calibration */
603                                               for (Int_t i = 0; i < fNChannels; i++) {
604                                                 if (fCal->GetDelay(i) != curCal->GetDelay(i)) {
605                                                   updateOCDB = kTRUE;
606                                                   break;
607                                                 }
608                                               }
609                                             }
610                                             else /* otherwise update OCDB */
611                                               updateOCDB = kTRUE;
612
613                                           }
614
615                                           else {  // computing delays if not in FDR runs
616
617                                             updateOCDB = kTRUE; /* always update OCDB when computing delays */
618
619                                                   for (Int_t ich=0;ich<kSize;ich++){
620                                                           /* check whether channel has been read out during current run.
621                                                            * if the status is bad it means it has not been read out.
622                                                            * in this case skip channel in order to not affect the mean */ 
623                                                           if (fStatus->GetHWStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFHWBad){
624                                                                   AliDebug(2,Form(" Channel %i found bad according to FEEmap, (HW status = %i), skipping from delay computing",ich, (Int_t)fStatus->GetHWStatus(ich)));
625                                                                   continue;
626                                                           }
627                                                           AliDebug(2,Form(" Channel %i found ok according to FEEmap, starting delay computing",ich));
628                                                           TH1S *h1 = new TH1S("h1","h1",kNBins,kXBinmin-0.5,kNBins*1.+kXBinmin-0.5);
629                                                           for (Int_t ibin=0;ibin<kNBins;ibin++){
630                                                                   h1->SetBinContent(ibin+1,h2->GetBinContent(ich+1,ibin+1));
631                                                           }
632                                                           if(h1->Integral()<integralThr) {
633                                                                   nNotStatistics++;
634                                                                   Log(Form(" Not enough statistics for bin %i, skipping this channel",ich));  // printing message only if not in FDR runs
635                                                                   delete h1;
636                                                                   h1=0x0;
637                                                                   continue;
638                                                           }
639                                                           Bool_t found=kFALSE; 
640                                                           Float_t minContent=h1->Integral()*thrPar; 
641                                                           Int_t nbinsX = h1->GetNbinsX();
642                                                           Int_t startBin=1;
643                                                           for (Int_t j=1; j<=nbinsX; j++){
644                                                                   if ((
645                                                                        h1->GetBinContent(j) +     
646                                                                        h1->GetBinContent(j+1)+
647                                                                        h1->GetBinContent(j+2)+ 
648                                                                        h1->GetBinContent(j+3))>minContent){
649                                                                           found=kTRUE;
650                                                                           startBin=j;
651                                                                           break;
652                                                                   }
653                                                           }
654                                                           if(!found) AliInfo(Form("WARNING!!! no start of fit found for histo # %i",ich));
655                                                           // Now calculate the mean over the interval. 
656                                                           Double_t mean = 0;
657                                                           Double_t sumw2 = 0;
658                                                           Double_t nent = 0;
659                                                           for(Int_t k=0;k<binRangeAve;k++){
660                                                                   mean=mean+h1->GetBinCenter(startBin+k)*h1->GetBinContent(startBin+k);                 
661                                                                   nent=nent+h1->GetBinContent(startBin+k);                 
662                                                                   sumw2=sumw2+(h1->GetBinCenter(startBin+k))*(h1->GetBinCenter(startBin+k))*(h1->GetBinContent(startBin+k));
663                                                           }
664                                                           mean= mean/nent; //<x>
665                                                           sumw2=sumw2/nent; //<x^2>
666                                                           Double_t rmsmean= 0;
667                                                           rmsmean = TMath::Sqrt((sumw2-mean*mean)/nent);
668                                                           if (ich<fNChannels) {
669                                                                   Float_t delay = mean*AliTOFGeometry::TdcBinWidth()*1.E-3; // delay in ns
670                                                                   fCal->SetDelay(ich,delay);  // delay in ns
671                                                                   AliDebug(2,Form("Setting delay %f (ns) for channel %i",delay,ich));
672                                                           }
673                                                           delete h1;
674                                                           h1=0x0;
675                                                   }
676                                           }
677                                           if (nNotStatistics!=0) Log(Form("Too little statistics for %d channels!",nNotStatistics)); 
678                                   }
679                                   delete h2;
680                                   daqFile->Close();
681                                   delete daqFile;
682                           }
683                           else{
684                                   Log("The Cumulative data file from DAQ does not exist, TOF exiting from Shuttle"); 
685                                   delete listTot;
686                                   delete fCal;
687                                   fCal=0x0;
688                                   return 6;//return error code for problems in retrieving DAQ data 
689                           }
690                   }
691                   delete listTot;
692           }
693   else{
694     Log("Problem: no list for Cumulative data file from DAQ was found, TOF exiting from Shuttle");
695     delete fCal;
696     fCal=0x0;
697     return 6; //return error code for problems in retrieving DAQ data 
698   }
699
700   /* check whether we don't need to update OCDB.
701    * in this case we can return without errors and
702    * the current FEE is stored in the fStatus object. */
703   if (!updateOCDB) {
704     AliInfo("update OCDB flag not set. Do not overwrite stored file.");
705     return 0; /* return ok */
706   }
707   
708   daqFile=0;
709   AliCDBMetaData metaData;
710   metaData.SetBeamPeriod(0);
711   metaData.SetResponsible("Chiara Zampolli");
712   metaData.SetComment("This preprocessor fills an AliTOFChannelOnlineArray object for online calibration - delays.");
713   AliInfo("Storing Calibration Data");
714   resultTOFPP = Store("Calib","ParOnlineDelay",fCal, &metaData,deltaStartingRun,kTRUE);
715   if(!resultTOFPP){
716     Log("Some problems occurred while storing online object resulting from DAQ data processing");
717     delete fCal;
718     fCal=0x0;
719     return 8;//return error code for problems in storing DAQ data 
720   }
721
722   if (fCal){
723     delete fCal;
724     fCal = 0;
725   }
726
727   return 0;
728 }
729
730 //_____________________________________________________________________________
731
732 UInt_t 
733 AliTOFPreprocessor::ProcessT0Fill()
734 {
735   // Processing data from DAQ for T0-fill measurement 
736
737   Log("Processing T0-fill");
738
739 #if 0
740   /* instance and setup CDB manager */
741   AliCDBManager *cdb = AliCDBManager::Instance();
742   /* load geometry */
743   if (!gGeoManager) AliGeomManager::LoadGeometry();
744 #endif
745
746   /* get params from OCDB */
747   AliCDBEntry *cdbe = NULL;
748
749   /* 
750    * at this stage status object is not on OCDB yet
751    * since it will be stored later. nevertheless we
752    * should have the array in memory since it has been
753    * already setup by ProcessFEF. 
754    */
755   
756   /* check status and latency window available */
757   if (!fStatus || !fLatencyWindow){
758     AliError("No valid fStatus or fLatencyWindow found, some errors must have occurred!!");
759     return 21;
760   }
761
762   /* get offline calibration from OCDB */
763   cdbe = GetFromOCDB("Calib", "ParOffline");
764   if (!cdbe) {
765     Log("cannot get \"ParOffline\" entry from OCDB");
766     return 21;
767   }
768   TObjArray *offlineArray = (TObjArray *)cdbe->GetObject();
769   AliTOFChannelOffline *channelOffline;
770   if (!offlineArray) {
771     Log("cannot get \"ParOffline\" object from CDB entry");
772     return 21;
773   }
774   Log("got \"ParOffline\" object");
775
776   /* get deltaBC offset from OCDB */
777   cdbe = GetFromOCDB("Calib", "DeltaBCOffset");
778   if (!cdbe) {
779     Log("cannot get \"DeltaBCOffset\" entry from OCDB");
780     return 21;
781   }
782   AliTOFDeltaBCOffset *deltaBCOffsetObject = (AliTOFDeltaBCOffset *)cdbe->GetObject();
783   if (!deltaBCOffsetObject) {
784     Log("cannot get \"DeltaBCOffset\" object from CDB entry");
785     return 21;
786   }
787   Int_t deltaBCOffset = deltaBCOffsetObject->GetDeltaBCOffset();
788   Log(Form("got \"DeltaBCOffset\" object: deltaBCOffset=%d (BC bins)", deltaBCOffset));
789
790   /* get CTP latency from OCDB */
791   cdbe = GetFromOCDB("Calib", "CTPLatency");
792   if (!cdbe) {
793     Log("cannot get \"CTPLatency\" entry from OCDB");
794     return 21;
795   }
796   AliTOFCTPLatency *ctpLatencyObject = (AliTOFCTPLatency *)cdbe->GetObject();
797   if (!ctpLatencyObject) {
798     Log("cannot get \"CTPLatency\" object from CDB entry");
799     return 21;
800   }
801   Float_t ctpLatency = ctpLatencyObject->GetCTPLatency();
802   Log(Form("got \"CTPLatency\" object: ctpLatency=%f (ps)", ctpLatency));
803   
804   /* get file sources from FXS */
805   TList *fileList = GetFileSources(kDAQ, "HITS");
806   if (!fileList || fileList->GetEntries() == 0) {
807     Log("cannot get DAQ source file list or empty list");
808     return 21;
809   }
810   Log(Form("got DAQ source file list: %d files", fileList->GetEntries()));
811   fileList->Print();
812   
813   /* create tree chain using file sources */
814   TChain chain("hitTree");
815   for (Int_t ifile = 0; ifile < fileList->GetEntries(); ifile++) {
816     TObjString *str = (TObjString *)fileList->At(ifile);
817     TString filename = GetFile(kDAQ, "HITS", str->GetName());
818     chain.Add(filename);
819     Log(Form("file added to input chain: source=%s, filename=%s", str->String().Data(), filename.Data()));
820   }
821   Int_t nhits = chain.GetEntries();
822   Log(Form("input chain ready: %d hits", nhits));
823
824   /* setup input chain */
825   AliTOFHitField *hit = new AliTOFHitField();
826   chain.SetBranchAddress("hit", &hit);
827
828   /* create calib histo and geometry */
829   AliTOFcalibHisto calibHisto;
830   calibHisto.LoadCalibHisto();
831   AliTOFGeometry tofGeo;
832
833   /* constants */
834   Float_t c = TMath::C() * 1.e2 / 1.e12; /* cm/ps */
835   Float_t c_1 = 1. / c;
836   /* variables */
837   Int_t index, timebin, totbin, deltaBC, l0l1latency, det[5];
838   Float_t timeps, totns, corrps, length, timeexp, timezero, pos[3], latencyWindow;
839
840   /* histos */
841   TH1F *hT0Fill = new TH1F("hT0Fill", "T0 fill;t - t_{exp}^{(c)} (ps);", 2000, -24400., 24400.);
842
843   /* loop over hits */
844   for (Int_t ihit = 0; ihit < nhits; ihit++) {
845
846     /* get entry */
847    chain.GetEntry(ihit);
848     
849     /* get hit info */
850     index = hit->GetIndex();
851     timebin = hit->GetTimeBin();
852     totbin = hit->GetTOTBin();
853     deltaBC = hit->GetDeltaBC();
854     l0l1latency = hit->GetL0L1Latency();
855     latencyWindow = fLatencyWindow[index] * 1.e3;
856     
857     /* convert time in ps and tot in ns */
858     timeps = timebin * AliTOFGeometry::TdcBinWidth();
859     totns = totbin * AliTOFGeometry::ToTBinWidth() * 1.e-3;
860     /* get calibration correction in ps */
861     
862
863     channelOffline = (AliTOFChannelOffline *)offlineArray->At(index);
864     if (totns < AliTOFGeometry::SlewTOTMin()) totns = AliTOFGeometry::SlewTOTMin();
865     if (totns > AliTOFGeometry::SlewTOTMax()) totns = AliTOFGeometry::SlewTOTMax();
866     corrps = 0.;
867     for (Int_t ipar = 0; ipar < 6; ipar++) corrps += channelOffline->GetSlewPar(ipar) * TMath::Power(totns, ipar);
868     corrps *= 1.e3;
869     /* perform time correction */
870     //    timeps = timeps + (deltaBC - deltaBCOffset) * AliTOFGeometry::BunchCrossingBinWidth() + l0l1latency * AliTOFGeometry::BunchCrossingBinWidth() + ctpLatency - latencyWindow - corrps; /* deltaBC correction removed for the time being */
871     timeps = timeps + l0l1latency * AliTOFGeometry::BunchCrossingBinWidth() + ctpLatency - latencyWindow - corrps;
872     /* compute length and expected time */
873     tofGeo.GetVolumeIndices(index, det);
874     tofGeo.GetPosPar(det, pos);
875     length = 0.;
876     for (Int_t i = 0; i < 3; i++) length += pos[i] * pos[i];
877     length = TMath::Sqrt(length);
878     timeexp = length * c_1;
879     /* compute time zero */
880     timezero = timeps - timeexp;
881     
882     /* fill histos */
883     hT0Fill->Fill(timezero);
884   }
885
886   /* rebin until maximum bin has required minimum entries */
887   Int_t maxBin = hT0Fill->GetMaximumBin();
888   Float_t maxBinContent = hT0Fill->GetBinContent(maxBin);
889   Float_t binWidth = hT0Fill->GetBinWidth(maxBin);
890   while (maxBinContent < 400 && binWidth < 90.) {
891     hT0Fill->Rebin(2);
892     maxBin = hT0Fill->GetMaximumBin();
893     maxBinContent = hT0Fill->GetBinContent(maxBin);
894     binWidth = hT0Fill->GetBinWidth(maxBin);
895   }
896   Float_t maxBinCenter = hT0Fill->GetBinCenter(maxBin);
897
898   /* rough fit of the edge */
899   TF1 *gaus = (TF1 *)gROOT->GetFunction("gaus");
900   gaus->SetParameter(1, maxBinCenter);
901   Float_t fitMin = maxBinCenter - 1000.; /* fit from 1 ns before max */
902   Float_t fitMax = maxBinCenter + 1000.; /* fit until 1 ns above max */
903   hT0Fill->Fit("gaus", "q0", "", fitMin, fitMax);
904   /* better fit of the edge */
905   Float_t mean, sigma;
906   for (Int_t istep = 0; istep < 10; istep++) {
907     mean = gaus->GetParameter(1);
908     sigma = gaus->GetParameter(2);
909     fitMin = mean - 3. * sigma;
910     fitMax = mean;
911     hT0Fill->Fit("gaus", "q0", "", fitMin, fitMax);
912   }
913   /* print params */
914   mean = gaus->GetParameter(1);
915   sigma = gaus->GetParameter(2);
916   Float_t meane = gaus->GetParError(1);
917   Float_t sigmae = gaus->GetParError(2);
918   Log(Form("edge fit: mean  = %f +- %f ps", mean, meane));
919   Log(Form("edge fit: sigma = %f +- %f ps", sigma, sigmae));
920   /* check error */
921   if (meane > 300.) {
922     Log("error on mean is large: store default T0-fill value (0 ps)");
923     mean = 0.;
924   }
925   if (sigmae > 300.) {
926     Log("error on sigma is large: store default TOFreso value (200 ps)");
927     sigma = 200.;
928   }
929
930   /* create RunParams object */
931   UInt_t timestamp[1] = {0};
932   Float_t t0[1] = {mean};
933   Float_t tofReso[1] = {sigma};
934   Float_t t0Spread[1] = {-1.};
935   AliTOFRunParams *runParamsObject = new AliTOFRunParams(1);
936   runParamsObject->SetTimestamp(timestamp);
937   runParamsObject->SetT0(t0);
938   runParamsObject->SetTOFResolution(tofReso);
939   runParamsObject->SetT0Spread(t0Spread);
940
941   /* store reference data */
942   if(fStoreRefData){
943     AliCDBMetaData metaDataHisto;
944     metaDataHisto.SetBeamPeriod(0);
945     metaDataHisto.SetResponsible("Roberto Preghenella");
946     metaDataHisto.SetComment("online T0-fill histogram");
947     if (!StoreReferenceData("Calib","T0Fill", hT0Fill, &metaDataHisto)) {
948       Log("error while storing reference data");
949       delete hT0Fill;
950       delete hit;
951       delete runParamsObject;
952       return 21;
953     }
954     Log("reference data successfully stored");
955   }
956   
957   AliCDBMetaData metaData;
958   metaData.SetBeamPeriod(0);
959   metaData.SetResponsible("Roberto Preghenella");
960   metaData.SetComment("online RunParams measurement");
961   if (!Store("Calib", "RunParams", runParamsObject, &metaData, 0, kFALSE)) {
962     Log("error while storing RunParams object");
963     delete hT0Fill;
964     delete hit;
965     delete runParamsObject;
966     return 21;
967   }
968   Log("RunParams object successfully stored");
969
970   delete hT0Fill;
971   delete hit;
972   delete runParamsObject;
973   return 0;
974
975 }
976  
977 //_____________________________________________________________________________
978
979 UInt_t 
980 AliTOFPreprocessor::ProcessNoiseCalibTrg()
981 {
982   // Processing data from DAQ using calibration triggers for noise measurement 
983
984   Log("Processing Noise (calibration trigger)");
985
986   /* check status and matching window available */
987   if (!fStatus || !fMatchingWindow){
988     AliError("No valid fStatus or fMatchingWindow found, some errors must have occurred!!");
989     return 22;
990   }
991
992   Float_t noiseThr = 1000.;   // setting default threshold for noise to 1000 Hz
993   // reading config map
994   AliCDBEntry *cdbEntry = GetFromOCDB("Calib","ConfigNoise");
995   if (!cdbEntry) Log(Form("No Configuration entry found in CDB, using default values: NoiseThr = %f",noiseThr));
996   else {
997     TMap *configMap = (TMap*)cdbEntry->GetObject();
998     if (!configMap) Log(Form("No map found in Config entry in CDB, using default values: NoiseThr = %f", noiseThr));
999     else {
1000       TObjString *strNoiseThr = (TObjString*)configMap->GetValue("NoiseThr");
1001       if (strNoiseThr) {
1002         TString tmpstr = strNoiseThr->GetString();
1003         noiseThr = tmpstr.Atoi();
1004       }
1005       else Log(Form("No NoiseThr value found in Map from ConfigNoise entry in CDB, using default value: NoiseThr = %f",noiseThr));
1006     }
1007   }
1008
1009   /* get file sources from FXS */
1010   TList *fileList = GetFileSources(kDAQ, "CALIB");
1011   if (!fileList || fileList->GetEntries() == 0) {
1012     Log("cannot get DAQ source file list or empty list");
1013     return 22;
1014   }
1015   Log(Form("got DAQ source file list: %d files", fileList->GetEntries()));
1016   fileList->Print();
1017
1018   /* open input file (only one expected) */
1019   TObjString *str = (TObjString *)fileList->At(0);
1020   TString filename = GetFile(kDAQ, "CALIB", str->GetName());
1021   Log(Form("opening input file: source=%s, filename=%s", str->String().Data(), filename.Data()));
1022   TFile *filein = TFile::Open(filename.Data());
1023   if (!filein || !filein->IsOpen()) {
1024     Log("cannot open input file");
1025     return 22;
1026   }
1027
1028   /* get histo from input file */
1029   TH1F *hCalibHit = (TH1F *)filein->Get("hCalibHit");
1030   if (!hCalibHit) {
1031     Log("cannot get \"hCalibHit\" histo");
1032     return 22;
1033   }
1034
1035   /* create and set noise rate histo and check rate */
1036   TH1F *hNoiseRate = new TH1F("hNoiseRate", ";index;rate (Hz)", fNChannels, 0., fNChannels);
1037   Float_t rate, rate_err;
1038   for (Int_t ich = 0; ich < fNChannels; ich++) {
1039     /* check channel enabled */
1040     if (fStatus->GetHWStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFHWBad) continue;
1041     /* set noise rate histo */
1042     rate = hCalibHit->GetBinContent(ich + 1);
1043     rate_err = hCalibHit->GetBinError(ich + 1);
1044     rate /= fMatchingWindow[ich] * 1.e-9;
1045     rate_err /= fMatchingWindow[ich] * 1.e-9;
1046     hNoiseRate->SetBinContent(ich + 1, rate);
1047     hNoiseRate->SetBinError(ich + 1, rate_err);
1048     /* check error */
1049     if (rate_err == 0.) continue;
1050     /* check noise rate and set noise flags */
1051     if ((rate - 3. * rate_err) > noiseThr) {
1052       Log(Form("channel %d detected as noisy: rate = (%f +- %f) Hz", ich, rate, rate_err));
1053       if (fStatus->GetNoiseStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFNoiseOk) {
1054         Log(Form("channel %d noise status changed from Ok to Bad", ich));
1055         fStatus->SetNoiseStatus(ich, AliTOFChannelOnlineStatusArray::kTOFNoiseBad);
1056         fIsStatusMapChanged = kTRUE;
1057       }
1058       else Log(Form("channel %d noise status unchanged", ich));
1059     }
1060     else if ((rate + 3. * rate_err) < noiseThr) {
1061       if (fStatus->GetNoiseStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFNoiseBad) {
1062         Log(Form("channel %d noise status changed from Bad to Ok", ich));
1063         fStatus->SetNoiseStatus(ich, AliTOFChannelOnlineStatusArray::kTOFNoiseOk);
1064         fIsStatusMapChanged = kTRUE;
1065       }
1066     }
1067   }
1068
1069   /* store reference data */
1070   if(fStoreRefData){
1071     AliCDBMetaData metaDataHisto;
1072     metaDataHisto.SetBeamPeriod(0);
1073     metaDataHisto.SetResponsible("Roberto Preghenella");
1074     metaDataHisto.SetComment("calibration trigger noise rate histogram");
1075     if (!StoreReferenceData("Calib","CalibNoise", hNoiseRate, &metaDataHisto)) {
1076       Log("error while storing reference data");
1077       delete hNoiseRate;
1078       filein->Close();
1079       return 22;
1080     }
1081     Log("reference data successfully stored");
1082   }
1083
1084   delete hNoiseRate;
1085   filein->Close();
1086   return 0;
1087 }
1088
1089 //_____________________________________________________________________________
1090
1091 UInt_t 
1092 AliTOFPreprocessor::ProcessReadout()
1093 {
1094   // Processing data from DAQ to compute reaodut efficiency
1095
1096   Log("Processing Readout");
1097
1098   /* get file sources from FXS */
1099   TList *fileList = GetFileSources(kDAQ, "READOUT");
1100   if (!fileList || fileList->GetEntries() == 0) {
1101     Log("cannot get DAQ source file list or empty list");
1102     return 22;
1103   }
1104   Log(Form("got DAQ source file list: %d files", fileList->GetEntries()));
1105   fileList->Print();
1106
1107   /* open input file (only one expected) */
1108   TObjString *str = (TObjString *)fileList->At(0);
1109   TString filename = GetFile(kDAQ, "READOUT", str->GetName());
1110   Log(Form("opening input file: source=%s, filename=%s", str->String().Data(), filename.Data()));
1111   TFile *filein = TFile::Open(filename.Data());
1112   if (!filein || !filein->IsOpen()) {
1113     Log("cannot open input file");
1114     return 23;
1115   }
1116
1117   /* get histo from input file */
1118   TH1F *hChainEfficiency = (TH1F *)filein->Get("hChainEfficiency");
1119   if (!hChainEfficiency) {
1120     Log("cannot get \"hChainEfficiency\" histo");
1121     return 23;
1122   }
1123
1124   /* fill channel efficiency histo */
1125
1126  /* temporarly disable warnings */
1127   AliLog::EType_t logLevel = (AliLog::EType_t)AliLog::GetGlobalLogLevel();
1128   AliLog::SetGlobalLogLevel(AliLog::kError);
1129
1130   TH1F *hChannelEfficiency = new TH1F("hChannelEfficiency", "Channel readout efficiency;index;efficiency", fNChannels, 0., fNChannels);
1131   Int_t chainIndex, det[5], dummy, index;
1132   Float_t effi, effi_err;
1133   /* loop over DDLs */
1134   for (Int_t iddl = 0; iddl < 72; iddl++) {
1135     /* loop over TRMs */
1136     for (Int_t itrm = 0; itrm < 10; itrm++) {
1137       /* loop over chains */
1138       for (Int_t ichain = 0; ichain < 2; ichain++) {
1139         chainIndex = ichain + 2 * itrm + 20 * iddl;
1140         effi = hChainEfficiency->GetBinContent(chainIndex + 1);
1141         effi_err = hChainEfficiency->GetBinError(chainIndex + 1);
1142         /* loop over TDCs */
1143         for (Int_t itdc = 0; itdc < 15; itdc++) {
1144           /* loop over channels */
1145           for (Int_t ichannel = 0; ichannel < 8; ichannel++) {
1146
1147             /* get channel index */
1148             AliTOFRawStream::EquipmentId2VolumeId(iddl, itrm + 3, ichain, itdc, ichannel, det);
1149             dummy = det[4];
1150             det[4] = det[3];
1151             det[3] = dummy;
1152             /* check valid index */
1153             if (det[0] < 0 || det[0] > 17 ||
1154                 det[1] < 0 || det[1] > 5 ||
1155                 det[2] < 0 || det[2] > 18 ||
1156                 det[3] < 0 || det[3] > 1 ||
1157                 det[4] < 0 || det[4] > 47) continue;
1158             index = AliTOFGeometry::GetIndex(det);
1159
1160             /* set channel efficiency */
1161             hChannelEfficiency->SetBinContent(index + 1, effi);
1162             hChannelEfficiency->SetBinError(index + 1, effi_err);
1163
1164           }
1165         }
1166       }
1167     }
1168   }
1169
1170   /* re-enable warnings */
1171   AliLog::SetGlobalLogLevel(logLevel);
1172
1173   /* store reference data */
1174   if(fStoreRefData){
1175     /* setup TOF readout info object */
1176     AliTOFReadoutInfo readoutInfo;
1177     readoutInfo.SetChainEfficiency((TH1F *)filein->Get("hChainEfficiency"));
1178     readoutInfo.SetTRMData((TH1F *)filein->Get("hTRMData"));
1179     readoutInfo.SetTRMEmptyEvent((TH1F *)filein->Get("hTRMEmptyEvent"));
1180     readoutInfo.SetTRMBadEventCounter((TH1F *)filein->Get("hTRMBadEventCounter"));
1181     readoutInfo.SetTRMBadCRC((TH1F *)filein->Get("hTRMBadCRC"));
1182     readoutInfo.SetChainData((TH1F *)filein->Get("hChainData"));
1183     readoutInfo.SetChainBadStatus((TH1F *)filein->Get("hChainBadStatus"));
1184     readoutInfo.SetChainBadEventCounter((TH1F *)filein->Get("hChainBadEventCounter"));
1185     readoutInfo.SetTDCError((TH1F *)filein->Get("hTDCError"));
1186     readoutInfo.SetTDCErrorFlags((TH2F *)filein->Get("hTDCErrorFlags"));
1187
1188     AliCDBMetaData metaDataHisto;
1189     metaDataHisto.SetBeamPeriod(0);
1190     metaDataHisto.SetResponsible("Roberto Preghenella");
1191     metaDataHisto.SetComment("readout info data");
1192     if (!StoreReferenceData("Calib","ReadoutInfo", &readoutInfo, &metaDataHisto)) {
1193       Log("error while storing reference data");
1194       filein->Close();
1195       return 23;
1196     }
1197     Log("reference data successfully stored");
1198   }
1199
1200   AliCDBMetaData metaData;
1201   metaData.SetBeamPeriod(0);
1202   metaData.SetResponsible("Roberto Preghenella");
1203   metaData.SetComment("online ReadoutEfficiency measurement");
1204   if (!Store("Calib", "ReadoutEfficiency", hChannelEfficiency, &metaData, 0, kFALSE)) {
1205     Log("error while storing ReadoutEfficiency object");
1206     delete hChannelEfficiency;
1207     filein->Close();
1208     return 23;
1209   }
1210   Log("ReadoutEfficiency object successfully stored");
1211
1212   delete hChannelEfficiency;
1213   filein->Close();
1214   return 0;
1215 }
1216
1217 //_____________________________________________________________________________
1218
1219 UInt_t AliTOFPreprocessor::ProcessPulserData()
1220 {
1221   // Processing Pulser Run data for TOF channel status
1222
1223   Log("Processing Pulser");
1224
1225   if (fStatus==0x0){
1226           AliError("No valid fStatus found, some errors must have occurred!!");
1227           return 20;
1228   }
1229
1230   TH1::AddDirectory(0);
1231   
1232   Bool_t resultPulserRef=kFALSE;
1233   Bool_t resultPulser=kFALSE;
1234   
1235   static const Int_t kSize = AliTOFGeometry::NPadXSector()*AliTOFGeometry::NSectors();
1236   TH1S * htofPulser = new TH1S("hTOFpulser","histo with signals on TOF during pulser", kSize,-0.5,kSize-0.5);
1237   for (Int_t ibin =1;ibin<=kSize;ibin++){
1238           htofPulser->SetBinContent(ibin,-1);
1239   }
1240   
1241   // processing pulser
1242   
1243   TFile * daqFile=0x0;
1244   TH1S *h1=0x0;
1245   
1246   //retrieving Pulser data 
1247   TList* listPulser = GetFileSources(kDAQ, "PULSER");
1248   if (listPulser !=0x0 && listPulser->GetEntries()!=0)
1249           {
1250                   AliInfo("The following sources produced files with the id PULSER");
1251                   listPulser->Print();
1252                   Int_t nPulser = 0;
1253                   for (Int_t jj=0;jj<listPulser->GetEntries();jj++){
1254                           Int_t nPulserSource = 0;
1255                           TObjString * str = dynamic_cast<TObjString*> (listPulser->At(jj));
1256                           AliInfo(Form("found source %s", str->String().Data()));
1257                           // file to be stored run per run
1258                           TString fileNamePulser = GetFile(kDAQ, "PULSER", str->GetName());
1259                           if (fileNamePulser.Length()>0){
1260                                   // storing refernce data
1261                                   AliInfo(Form("Got the file %s, now we can process pulser data.", fileNamePulser.Data()));
1262                                   daqFile = new TFile(fileNamePulser.Data(),"READ");
1263                                   h1 = (TH1S*) daqFile->Get("hTOFpulser");
1264                                   for (Int_t ibin=0;ibin<kSize;ibin++){
1265                                           if ((h1->GetBinContent(ibin+1))!=-1){
1266                                                   if ((htofPulser->GetBinContent(ibin+1))==-1){
1267                                                           htofPulser->SetBinContent(ibin+1,h1->GetBinContent(ibin+1));
1268                                                   }
1269                                                   else {
1270                                                           Log(Form("Something strange occurred during Pulser run, channel %i already read by another LDC, please check!",ibin));
1271                                                   }
1272                                           }
1273                                   }
1274                                   
1275                                   // elaborating infos
1276                                   Double_t mean =0;
1277                                   Int_t nread=0;
1278                                   Int_t nreadNotEmpty=0;
1279                                   for (Int_t ientry=1;ientry<=h1->GetNbinsX();ientry++){
1280                                           
1281                                           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)));
1282                                           /* check whether channel has been read out during current run.
1283                                            * if the status is bad it means it has not been read out.
1284                                            * in this case skip channel in order to not affect the mean */ 
1285                                           if (fStatus->GetHWStatus(ientry-1) == AliTOFChannelOnlineStatusArray::kTOFHWBad)
1286                                                   continue;
1287                                           nPulser++;
1288                                           nPulserSource++;
1289                                           if (h1->GetBinContent(ientry)==-1) continue;
1290                                           else {
1291                                                   if (h1->GetBinContent(ientry)>0) {
1292                                                           nreadNotEmpty++;
1293                                                           AliDebug(2,Form(" channel %i is ok with entry = %f; so far %i channels added ",ientry-1,h1->GetBinContent(ientry),nreadNotEmpty));
1294                                                   }
1295                                                   mean+=h1->GetBinContent(ientry);
1296                                                   nread++;
1297                                           }
1298                                   }
1299                                   if (nread!=0) {
1300                                           mean/=nread;
1301                                           AliDebug(2,Form(" nread =  %i , nreadNotEmpty = %i, mean = %f",nread,nreadNotEmpty,mean));
1302                                           for (Int_t ich =0;ich<fNChannels;ich++){
1303                                                   if (h1->GetBinContent(ich+1)==-1) continue;
1304                                                   AliDebug(3,Form(" channel %i pulser status before pulser = %i",ich,(Int_t)fStatus->GetPulserStatus(ich)));
1305                                                   
1306                                                   /* check whether channel has been read out during current run.
1307                                                    * if the status is bad it means it has not been read out.
1308                                                    * in this case skip channel in order to leave its status 
1309                                                    * unchanged */
1310                                                   if (fStatus->GetHWStatus(ich) == AliTOFChannelOnlineStatusArray::kTOFHWBad)
1311                                                           continue;
1312                                                   
1313                                                   if (h1->GetBinContent(ich+1)<0.05*mean){
1314                                                           fStatus->SetPulserStatus(ich,AliTOFChannelOnlineStatusArray::kTOFPulserBad);  // bad status for pulser
1315                                                           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)));
1316                                                   }
1317                                                   else {
1318                                                           fStatus->SetPulserStatus(ich,AliTOFChannelOnlineStatusArray::kTOFPulserOk);  // good status for pulser
1319                                                           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)));
1320                                                   }
1321                                           }
1322                                   }
1323                                   else {
1324                                           Log("No channels read!! No action taken, keeping old status");
1325                                   }
1326                                   
1327                                   daqFile->Close();
1328                                   delete daqFile;
1329                                   delete h1;
1330                           }
1331                           
1332                           else{
1333                                   Log("The input data file from DAQ (pulser) was not found, TOF exiting from Shuttle "); 
1334                                   delete listPulser;
1335                                   delete htofPulser;
1336                                   htofPulser = 0x0;
1337                                   if (fStatus){
1338                                           delete fStatus;
1339                                           fStatus = 0;
1340                                   }
1341                                   return 10;//return error code for failure in retrieving Ref Data 
1342                           }
1343                           AliDebug(2,Form(" Number of channels processed during pulser run from source %i = %i",jj, nPulserSource));             
1344                   }
1345                   AliDebug(2,Form(" Number of channels processed during pulser run = %i",nPulser));
1346                   delete listPulser;
1347           }
1348   
1349   else{
1350           Log("The input data file list from DAQ (pulser) was not found, TOF exiting from Shuttle "); 
1351           delete htofPulser;
1352           htofPulser = 0x0;
1353           if (fStatus){
1354                   delete fStatus;
1355                   fStatus = 0;
1356           }
1357           return 10;//return error code for failure in retrieving Ref Data 
1358   }     
1359   
1360   //storing in OCDB  
1361   
1362   AliCDBMetaData metaData;
1363   metaData.SetBeamPeriod(0);
1364   metaData.SetResponsible("Chiara Zampolli");
1365   metaData.SetComment("This preprocessor fills an AliTOFChannelOnlineStatusArray object after a Pulser run.");
1366   AliInfo("Storing Calibration Data from Pulser Run");
1367   resultPulser = Store("Calib","Status",fStatus, &metaData,0,kTRUE);
1368   if(!resultPulser){
1369     Log("Some problems occurred while storing online object resulting from Pulser data processing");
1370     delete htofPulser;
1371     htofPulser = 0x0;
1372     if (fStatus){
1373             delete fStatus;
1374             fStatus = 0;
1375     }
1376     return 11;//return error code for problems in storing Pulser data 
1377   }
1378
1379   if(fStoreRefData){
1380     
1381     AliCDBMetaData metaDataHisto;
1382     metaDataHisto.SetBeamPeriod(0);
1383     metaDataHisto.SetResponsible("Chiara Zampolli");
1384     char comment[200];
1385     sprintf(comment,"This preprocessor stores the Ref data from a pulser run.");
1386     metaDataHisto.SetComment(comment);
1387     AliInfo("Storing Reference Data");
1388     resultPulserRef = StoreReferenceData("Calib","PulserData",htofPulser, &metaDataHisto);
1389     if (!resultPulserRef){
1390       Log("some problems occurred::No Reference Data for pulser stored, TOF exiting from Shuttle");
1391       delete htofPulser;
1392       htofPulser = 0x0;
1393       if (fStatus){
1394               delete fStatus;
1395               fStatus = 0;
1396       }
1397       return 9;//return error code for failure in storing Ref Data 
1398     }
1399   }
1400   
1401   daqFile=0;
1402
1403   delete htofPulser;
1404   htofPulser = 0x0;
1405
1406   if (fStatus){
1407     delete fStatus;
1408     fStatus = 0;
1409   }
1410
1411   return 0;
1412 }
1413 //_____________________________________________________________________________
1414
1415 UInt_t AliTOFPreprocessor::ProcessNoiseData()
1416 {
1417
1418   // Processing Noise Run data for TOF channel status
1419
1420   Log("Processing Noise");
1421
1422   if (fStatus==0x0){
1423           AliError("No valid fStatus found, some errors must have occurred!!");
1424           return 20;
1425   }
1426
1427   Float_t noiseThr = 1;   // setting default threshold for noise to 1 Hz
1428   // reading config map
1429   AliCDBEntry *cdbEntry = GetFromOCDB("Calib","ConfigNoise");
1430   if (!cdbEntry) {
1431           Log(Form("No Configuration entry found in CDB, using default values: NoiseThr = %f",noiseThr));
1432   }
1433   else {
1434           TMap *configMap = (TMap*)cdbEntry->GetObject();
1435           if (!configMap){
1436                   Log(Form("No map found in Config entry in CDB, using default values: NoiseThr = %f", noiseThr));
1437           }
1438           else{
1439                   TObjString *strNoiseThr = (TObjString*)configMap->GetValue("NoiseThr");
1440                   if (strNoiseThr) {
1441                           TString tmpstr = strNoiseThr->GetString();
1442                           noiseThr = tmpstr.Atoi();
1443                   }
1444                   else {
1445                           Log(Form("No NoiseThr value found in Map from ConfigNoise entry in CDB, using default value: NoiseThr = %f",noiseThr));
1446                   }
1447           }
1448   }
1449
1450   delete cdbEntry;
1451   cdbEntry = 0x0;
1452
1453   TH1::AddDirectory(0);
1454
1455   Bool_t resultNoiseRef=kFALSE;
1456   Bool_t resultNoise=kFALSE;
1457
1458   static const Int_t kSize = AliTOFGeometry::NPadXSector()*AliTOFGeometry::NSectors();
1459   TH1F * htofNoise = new TH1F("hTOFnoise","histo with signals on TOF during noise", kSize,-0.5,kSize-0.5);
1460   for (Int_t ibin =1;ibin<=kSize;ibin++){
1461           htofNoise->SetBinContent(ibin,-1);
1462   }
1463   
1464   // processing noise
1465   
1466   TFile * daqFile=0x0;
1467   TH1F * h1=0x0;
1468   
1469   // useful counters
1470   Int_t nNoise = 0;
1471   Int_t nNoisyChannels = 0;
1472   Int_t nNotNoisyChannels = 0;
1473   Int_t nChannelsFromDA = 0;
1474   Int_t nMatchingWindowNullNonZero = 0;
1475   Int_t nMatchingWindowNullEqualZero = 0;
1476
1477   // retrieving Noise data 
1478   TList* listNoise = GetFileSources(kDAQ, "NOISE");
1479   if (listNoise !=0x0 && listNoise->GetEntries()!=0)
1480           {
1481                   AliInfo("The following sources produced files with the id NOISE");
1482                   listNoise->Print();
1483                   for (Int_t jj=0;jj<listNoise->GetEntries();jj++){
1484                           Int_t nNoiseSource = 0;
1485                           TObjString * str = dynamic_cast<TObjString*> (listNoise->At(jj));
1486                           AliInfo(Form("found source %s", str->String().Data()));
1487                           // file to be stored run per run
1488                           TString fileNameNoise = GetFile(kDAQ, "NOISE", str->GetName());
1489                           if (fileNameNoise.Length()>0){
1490                                   // storing reference data
1491                                   AliInfo(Form("Got the file %s, now we can process noise data.", fileNameNoise.Data()));
1492                                   daqFile = new TFile(fileNameNoise.Data(),"READ");
1493                                   h1 = (TH1F*) daqFile->Get("hTOFnoise");
1494                                   for (Int_t ibin=0;ibin<kSize;ibin++){
1495                                           if ((h1->GetBinContent(ibin+1))!=-1){
1496                                                   nNoiseSource++;
1497                                                   // checking the matching window for current channel
1498                                                   if (fMatchingWindow[ibin] == 0){
1499                                                           Log(Form("Matching window for channel %i null, but the channel was read by the LDC! skipping channel, BUT Please check!",ibin));
1500                                                           if ((h1->GetBinContent(ibin+1))!=0) nMatchingWindowNullNonZero++;                                             
1501                                                           if ((h1->GetBinContent(ibin+1))==0) nMatchingWindowNullEqualZero++;                                           
1502                                                           continue;
1503                                                   }
1504                                                   if ((htofNoise->GetBinContent(ibin+1))==-1){
1505                                                           htofNoise->SetBinContent(ibin+1,h1->GetBinContent(ibin+1)/(fMatchingWindow[ibin]*1.E-9));
1506                                                           if ((h1->GetBinContent(ibin+1))!= 0) AliDebug(2,Form("Channel = %i, Matching window = %i, Content = %f", ibin, fMatchingWindow[ibin], htofNoise->GetBinContent(ibin+1)));
1507                                                   }
1508                                                   else {
1509                                                           Log(Form("Something strange occurred during Noise run, channel %i already read by another LDC, please check!",ibin));
1510                                                   }
1511                                           }
1512                                   }
1513
1514                                   Log(Form(" Number of channels processed during noise run from source %i = %i",jj, nNoiseSource));
1515                                   daqFile->Close();
1516                                   delete daqFile;
1517                                   delete h1;
1518                                   daqFile = 0x0;
1519                                   h1 = 0x0;
1520
1521                           }
1522                           else{
1523                                   Log("The input data file from DAQ (noise) was not found, TOF exiting from Shuttle "); 
1524                                   delete listNoise;
1525                                   listNoise = 0x0;
1526                                   delete htofNoise;
1527                                   htofNoise = 0x0;
1528                                   if (fStatus){
1529                                           delete fStatus;
1530                                           fStatus = 0;
1531                                   }
1532                                   if (fMatchingWindow){
1533                                           delete [] fMatchingWindow;
1534                                           fMatchingWindow = 0;
1535                                   }
1536                                   return 13;//return error code for failure in retrieving Ref Data 
1537                           }
1538                   }               
1539           }
1540                           
1541   else{
1542           Log("The input data file list from DAQ (noise) was not found, TOF exiting from Shuttle "); 
1543           delete htofNoise;
1544           htofNoise = 0x0;
1545           if (fStatus){
1546                   delete fStatus;
1547                   fStatus = 0;
1548           }
1549           if (fMatchingWindow){
1550                   delete [] fMatchingWindow;
1551                   fMatchingWindow = 0;
1552           }
1553           return 13;//return error code for failure in retrieving Ref Data 
1554   }     
1555   
1556   // elaborating infos to set NOISE status
1557   for (Int_t ich =0;ich<fNChannels;ich++){
1558           if (htofNoise->GetBinContent(ich+1)== -1) continue;
1559
1560           nChannelsFromDA++;
1561
1562           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)));
1563           //AliDebug(2,Form( " channel %i status before noise = %i",ich,(Int_t)fStatus->GetNoiseStatus(ich)));
1564           
1565           /* check whether channel has been read out during current run.
1566            * if the status is bad it means it has not been read out.
1567            * in this case skip channel in order to leave its status 
1568            * unchanged */
1569
1570           if ((fStatus->GetHWStatus(ich)) == AliTOFChannelOnlineStatusArray::kTOFHWBad)
1571                   continue;
1572           
1573           nNoise++;
1574           if (htofNoise->GetBinContent(ich+1) >= noiseThr){
1575                   fStatus->SetNoiseStatus(ich,AliTOFChannelOnlineStatusArray::kTOFNoiseBad); // bad status for noise
1576                   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)));
1577                   nNoisyChannels++;
1578           }
1579           else {
1580                   fStatus->SetNoiseStatus(ich,AliTOFChannelOnlineStatusArray::kTOFNoiseOk); // good status for noise
1581                   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)));
1582                   nNotNoisyChannels++;
1583           }
1584   }
1585   
1586   Log(Form(" Number of channels processed by DA during noise run, independetly from TOFFEE = %i",nChannelsFromDA));
1587   Log(Form(" Number of channels processed during noise run (that were ON according to TOFFEE) = %i",nNoise));
1588   Log(Form(" Number of noisy channels found during noise run = %i",nNoisyChannels));
1589   Log(Form(" Number of not noisy channels found during noise run = %i",nNotNoisyChannels));
1590   Log(Form(" Number of channels with matching window NULL (so skipped), but Non Zero content = %i",nMatchingWindowNullNonZero));
1591   Log(Form(" Number of channels with matching window NULL (so skipped), and Zero content = %i",nMatchingWindowNullEqualZero));
1592
1593   delete listNoise;
1594   
1595   //daqFile=0;
1596   
1597   //storing in OCDB
1598   
1599   AliCDBMetaData metaData;
1600   metaData.SetBeamPeriod(0);
1601   metaData.SetResponsible("Chiara Zampolli");
1602   metaData.SetComment("This preprocessor fills an AliTOFChannelOnlineStatusArray object after a Noise run.");
1603   AliInfo("Storing Calibration Data from Noise Run");
1604   resultNoise = Store("Calib","Status",fStatus, &metaData,0,kTRUE);
1605   if(!resultNoise){
1606     Log("Some problems occurred while storing online object resulting from Noise data processing");
1607     delete htofNoise;
1608     htofNoise = 0x0;
1609     if (fStatus){
1610             delete fStatus;
1611             fStatus = 0;
1612     }
1613     if (fMatchingWindow){
1614             delete [] fMatchingWindow;
1615             fMatchingWindow = 0;
1616     }
1617     return 14;//return error code for problems in storing Noise data 
1618   }
1619
1620   if(fStoreRefData){
1621     
1622     AliCDBMetaData metaDataHisto;
1623     metaDataHisto.SetBeamPeriod(0);
1624     metaDataHisto.SetResponsible("Chiara Zampolli");
1625     char comment[200];
1626     sprintf(comment,"This preprocessor stores the Ref data from a noise run. ");
1627     metaDataHisto.SetComment(comment);
1628     AliInfo("Storing Reference Data");
1629     resultNoiseRef = StoreReferenceData("Calib","NoiseData",htofNoise, &metaDataHisto);
1630     if (!resultNoiseRef){
1631       Log("some problems occurred::No Reference Data for noise stored");
1632       delete htofNoise;
1633       htofNoise = 0x0;
1634       if (fStatus){
1635               delete fStatus;
1636               fStatus = 0;
1637       }
1638       if (fMatchingWindow){
1639               delete [] fMatchingWindow;
1640               fMatchingWindow = 0;
1641       }
1642       return 12;//return error code for failure in storing Ref Data 
1643     }
1644   }
1645
1646   delete htofNoise;
1647   htofNoise = 0x0;
1648
1649   if (fStatus){
1650     delete fStatus;
1651     fStatus = 0;
1652   }
1653
1654   if (fMatchingWindow){
1655           delete [] fMatchingWindow;
1656           fMatchingWindow = 0;
1657   }
1658
1659   return 0;
1660 }
1661 //_____________________________________________________________________________
1662
1663 UInt_t AliTOFPreprocessor::ProcessFEEData()
1664 {
1665   // Processing Pulser Run data for TOF channel status
1666   // dummy for the time being
1667
1668   Log("Processing FEE");
1669
1670   //Bool_t updateOCDB = kFALSE;
1671   AliTOFFEEReader feeReader;
1672
1673   TH1C hCurrentFEE("hCurrentFEE","histo with current FEE channel status", fNChannels, 0, fNChannels);
1674   
1675   /* load current TOF FEE(dump) from DCS FXS, 
1676    * setup TOFFEEdump object */
1677
1678   const char * toffeeFileName = GetFile(kDCS,"TofFeeMap",""); 
1679   AliInfo(Form("toffee file name = %s", toffeeFileName));
1680   if (toffeeFileName == NULL) {
1681     return 15;
1682   } 
1683   AliTOFFEEDump feedump;
1684   feedump.ReadFromFile(toffeeFileName);
1685   
1686   /* load current TOF FEE(light) config from DCS FXS, parse, 
1687    * fill current FEE histogram and set FEE status */
1688   
1689   const char * nameFile = GetFile(kDCS,"TofFeeLightMap",""); 
1690   AliInfo(Form("toffeeLight file name = %s",nameFile));
1691   if (nameFile == NULL) {
1692           return 15;
1693   } 
1694   feeReader.LoadFEElightConfig(nameFile);
1695   Int_t parseFee = feeReader.ParseFEElightConfig();
1696   AliDebug(2,Form("%i enabled channels found in FEElight configuration",parseFee));
1697   /* load stored TOF FEE from OCDB and compare it with current FEE.
1698    * if stored FEE is different from current FEE set update flag.
1699    * if there is no stored FEE in OCDB set update flag */
1700   
1701   fMatchingWindow = new Int_t[fNChannels];
1702   fLatencyWindow = new Int_t[fNChannels];
1703   
1704   AliCDBEntry *cdbEntry = GetFromOCDB("Calib","Status");
1705   if (!cdbEntry) {
1706           /* no CDB entry found. set update flag */
1707           Log("     ************ WARNING ************");
1708           Log("No CDB Status entry found, creating a new one!");
1709           Log("     *********************************");
1710           fStatus = new AliTOFChannelOnlineStatusArray(fNChannels);
1711           //updateOCDB = kTRUE;
1712           fIsStatusMapChanged = kTRUE;
1713   }
1714   else {
1715           if (cdbEntry) cdbEntry->SetOwner(kFALSE);
1716           /* CDB entry OK. loop over channels */
1717           fStatus = (AliTOFChannelOnlineStatusArray*) cdbEntry->GetObject();
1718           delete cdbEntry;
1719           cdbEntry = 0x0;
1720           /* cehck whether status object has latency window data */
1721           if (!fStatus->HasLatencyWindow()) {
1722             /* create new status object and update OCDB */
1723             Log("     ************ WARNING ************");
1724             Log("CDB Status entry found but has no latency window data, creating a new one!");
1725             Log("     *********************************");
1726             delete fStatus;
1727             fStatus = new AliTOFChannelOnlineStatusArray(fNChannels);
1728             //updateOCDB = kTRUE;
1729             fIsStatusMapChanged = kTRUE;
1730           }
1731   }
1732   for (Int_t iChannel = 0; iChannel < fNChannels; iChannel++){
1733           //AliDebug(2,Form("********** channel %i",iChannel));
1734           /* compare current FEE channel status with stored one 
1735            * if different set update flag and break loop */
1736           //AliDebug(2,Form( " channel %i status before FEE = %i",iChannel,(Int_t)fStatus->GetHWStatus(iChannel)));
1737           fMatchingWindow[iChannel] = feeReader.GetMatchingWindow(iChannel);
1738           fLatencyWindow[iChannel] = feeReader.GetLatencyWindow(iChannel);
1739           if (feeReader.IsChannelEnabled(iChannel)) {
1740                   hCurrentFEE.SetBinContent(iChannel + 1, 1);
1741                   if (fStatus->GetHWStatus(iChannel)!=AliTOFChannelOnlineStatusArray::kTOFHWOk){
1742                           //updateOCDB = kTRUE;
1743                           fIsStatusMapChanged = kTRUE;
1744                           fStatus->SetHWStatus(iChannel,AliTOFChannelOnlineStatusArray::kTOFHWOk);
1745                           AliDebug(3,Form( " changed into enabled: channel %i status after FEE = %i",iChannel,(Int_t)fStatus->GetHWStatus(iChannel)));
1746                   }
1747                   if (fStatus->GetLatencyWindow(iChannel)!=fLatencyWindow[iChannel]){
1748                           //updateOCDB = kTRUE;
1749                           fIsStatusMapChanged = kTRUE;
1750                           fStatus->SetLatencyWindow(iChannel,fLatencyWindow[iChannel]);
1751                           AliDebug(3,Form( " changed latency window: channel %i latency window after FEE = %i",iChannel,fStatus->GetLatencyWindow(iChannel)));
1752                   }
1753           }
1754           else {
1755                   if (fStatus->GetHWStatus(iChannel)!=AliTOFChannelOnlineStatusArray::kTOFHWBad){
1756                           //updateOCDB = kTRUE;
1757                           fIsStatusMapChanged = kTRUE;
1758                           fStatus->SetHWStatus(iChannel,AliTOFChannelOnlineStatusArray::kTOFHWBad);
1759                           AliDebug(3,Form( " changed into disabled: channel %i status after FEE = %i",iChannel,(Int_t)fStatus->GetHWStatus(iChannel)));
1760                   }
1761           }
1762   }
1763
1764
1765   /* check whether we don't have to store reference data.
1766    * in this case we return without errors. */
1767   if (fStoreRefData) {
1768     /* store reference data */
1769     AliCDBMetaData metaDataHisto;
1770     metaDataHisto.SetBeamPeriod(0);
1771     metaDataHisto.SetResponsible("Roberto Preghenella");
1772     metaDataHisto.SetComment("This preprocessor stores the FEE Ref data of the current run.");
1773     AliInfo("Storing FEE reference data");
1774     /* store FEE reference data */
1775     if (!StoreReferenceData("Calib", "FEEData", &hCurrentFEE, &metaDataHisto)) {
1776       /* failed */
1777       Log("problems while storing FEE reference data");
1778       if (fStatus){
1779         delete fStatus;
1780         fStatus = 0;
1781       }
1782       return 18; /* error return code for problems while storing FEE reference data */
1783     }
1784     
1785     /* store TOF FEE dump reference data */
1786     AliCDBMetaData metaDatadump;
1787     metaDatadump.SetBeamPeriod(0);
1788     metaDatadump.SetResponsible("Roberto Preghenella");
1789     metaDatadump.SetComment("This preprocessor stores the TOF FEE dump Ref data of the current run.");
1790     AliInfo("Storing TOF FEE dump reference data");
1791     /* store FEE reference data */
1792     if (!StoreReferenceData("Calib", "FEEDump", &feedump, &metaDatadump)) {
1793       /* failed */
1794       Log("problems while storing TOF FEE dump reference data");
1795       return 18; /* error return code for problems while storing FEE reference data */
1796     }
1797   }
1798
1799   return 0;
1800
1801 }
1802
1803 //_____________________________________________________________________________
1804
1805 UInt_t AliTOFPreprocessor::Process(TMap *dcsAliasMap)
1806 {
1807   //
1808   // Main AliTOFPreprocessor method called by SHUTTLE
1809   //
1810
1811   TString runType = GetRunType();
1812   Log(Form("RunType %s",runType.Data()));
1813   
1814   // processing 
1815
1816   /* always process FEE data */
1817   Int_t iresultFEE = ProcessFEEData();
1818   if (iresultFEE != 0)
1819     return iresultFEE;
1820
1821   if (runType == "PULSER") {
1822     Int_t iresultPulser = ProcessPulserData();
1823     return iresultPulser; 
1824   }
1825
1826   if (runType == "NOISE") { // for the time being associating noise runs with pedestal runs; proper run type to be defined 
1827     Int_t iresultNoise = ProcessNoiseData();
1828     return iresultNoise; 
1829   }
1830  
1831   if (runType == "PHYSICS") {
1832     //    Int_t iresultDAQ = ProcessOnlineDelays();
1833     Int_t iresultDAQ = ProcessT0Fill();
1834     Int_t iresultNoiseCalib = ProcessNoiseCalibTrg();
1835     Int_t iresultReadout = ProcessReadout();
1836     Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
1837     Int_t iResultHVandLVdps = ProcessHVandLVdps(dcsAliasMap);
1838     return iresultDAQ+iresultNoiseCalib+iresultDCS+iResultHVandLVdps+iresultReadout;
1839   }
1840
1841   // storing
1842   return 0;
1843 }
1844
1845
1846 //_____________________________________________________________________________
1847
1848 void
1849 AliTOFPreprocessor::FillWithCosmicCalibration(AliTOFChannelOnlineArray *cal)
1850 {
1851   /*
1852    * fill with cosmic calibration 
1853    */
1854
1855   Log(" Using cosmic-ray calibration.");
1856   
1857   AliTOFcalibHisto calibHisto;
1858   calibHisto.SetFullCorrectionFlag(AliTOFcalibHisto::kTimeSlewingCorr, kFALSE);
1859   Log(Form(" loading calibration histograms from %s", calibHisto.GetCalibHistoFileName()));
1860   Log(Form(" loading calibration parameters from %s", calibHisto.GetCalibParFileName()));
1861   calibHisto.LoadCalibPar();
1862   
1863   /* loop over channel index */
1864   for (Int_t iIndex = 0; iIndex < fNChannels; iIndex++) {
1865     cal->SetDelay(iIndex, calibHisto.GetFullCorrection(iIndex));
1866   }
1867   
1868 }
1869
1870 //_____________________________________________________________________________
1871
1872 void
1873 AliTOFPreprocessor::FillWithCableLengthMap(AliTOFChannelOnlineArray *cal)
1874 {
1875   /*
1876    * fill with cosmic calibration 
1877    */
1878   
1879   Log(" Using cable-length map.");
1880   AliTOFRawStream tofrs;
1881   Int_t det[5], dummy, index;
1882   Float_t cableTimeShift;
1883   
1884   /* temporarly disable warnings */
1885   AliLog::EType_t logLevel = (AliLog::EType_t)AliLog::GetGlobalLogLevel();
1886   AliLog::SetGlobalLogLevel(AliLog::kError);
1887   
1888   /* loop over EO indeces */
1889   for (Int_t iddl = 0; iddl < 72; iddl++)
1890     for (Int_t islot = 3; islot <= 12; islot++)
1891       for (Int_t ichain = 0; ichain < 2; ichain++)
1892         for (Int_t itdc = 0; itdc < 15; itdc++)
1893           for (Int_t ichannel = 0; ichannel < 8; ichannel++) {
1894             
1895             /* get DO index */
1896             tofrs.EquipmentId2VolumeId(iddl, islot, ichain, itdc, ichannel, det);
1897             
1898             /* swap det[3] and det[4] indeces (needed to obtain correct channel index) */
1899             dummy = det[3];
1900             det[3] = det[4];
1901             det[4] = dummy;
1902             
1903             /* check DO index */
1904             if (det[0] < 0 || det[0] > 17 ||
1905                 det[1] < 0 || det[1] > 4 ||
1906                 det[2] < 0 || det[2] > 18 ||
1907                 det[3] < 0 || det[3] > 1 ||
1908                 det[4] < 0 || det[4] > 47)
1909               continue;
1910             
1911             /* get channel index */
1912             index = AliTOFGeometry::GetIndex(det);
1913             
1914             /* get cable time shift */
1915             cableTimeShift = AliTOFCableLengthMap::GetCableTimeShift(iddl, islot, ichain, itdc);
1916             
1917             /* set delay */
1918             if (index<fNChannels) {
1919               cal->SetDelay(index,cableTimeShift);  // delay in ns
1920               AliDebug(2,Form("Setting delay %f (ns) for channel %i",cableTimeShift,index));
1921             }
1922             
1923           } /* loop over EO indeces */
1924   
1925   /* re-enable warnings */
1926   AliLog::SetGlobalLogLevel(logLevel);
1927   
1928 }
1929
1930