]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TOF/AliTOFcalib.cxx
Fixed bug into TOF time resolution control (F.Noferini)
[u/mrichter/AliRoot.git] / TOF / AliTOFcalib.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 /*
17 $Log: AliTOFcalib.cxx,v $
18 Revision 1.21  2007/11/02 15:41:49  hristov
19 Provide return value if the function is not void
20
21 Revision 1.20  2007/10/26 15:13:50  zampolli
22 Using a TChain instead of a TTree
23
24 Revision 1.19  2007/10/23 15:27:38  zampolli
25 Rearrangement of Calibration objects for simulation
26
27 Revision 1.16  2007/10/08 10:13:26  zampolli
28 First Run and Last Run members added, infinite validity of calib obj implemented.
29
30 Revision 1.15  2007/10/04 13:23:28  zampolli
31 Updates to handle functionalities in TOF online/offline calibration according to the latest schema
32
33 Revision 1.14  2007/06/06 16:26:30  arcelli
34 remove fall-back call to local CDB storage
35
36 Revision 1.13  2007/04/20 13:59:40  arcelli
37 make protections agains failed retrieval of the CDB object in a proper way
38
39 Revision 1.12  2007/03/23 11:31:16  arcelli
40 CDB Entry for TOF Reconstruction Parameters
41
42 Revision 1.11  2007/02/28 18:08:26  arcelli
43 Add protection against failed retrieval of the CDB cal object
44
45 Revision 1.10  2006/08/22 13:30:49  arcelli
46 removal of effective c++ warnings (C.Zampolli)
47
48 Revision 1.9  2006/04/20 22:30:50  hristov
49 Coding conventions (Annalisa)
50
51 Revision 1.8  2006/04/16 22:29:05  hristov
52 Coding conventions (Annalisa)
53
54 Revision 1.7  2006/04/16 20:12:46  hristov
55 Removing memory leak in case of cached CDB entries
56
57 Revision 1.6  2006/04/11 15:28:32  hristov
58 Checks on cache status before deleting calibration objects (A.Colla)
59
60 Revision 1.5  2006/04/05 08:35:38  hristov
61 Coding conventions (S.Arcelli, C.Zampolli)
62
63 Revision 1.4  2006/03/31 11:26:46  arcelli
64  changing CDB Ids according to standard convention
65
66 Revision 1.3  2006/03/28 14:57:02  arcelli
67 updates to handle new V5 geometry & some re-arrangements
68
69 Revision 1.2  2006/02/13 17:22:26  arcelli
70 just Fixing Log info
71
72 Revision 1.1  2006/02/13 16:10:48  arcelli
73 Add classes for TOF Calibration (C.Zampolli)
74
75 author: Chiara Zampolli, zampolli@bo.infn.it
76 */  
77
78 ///////////////////////////////////////////////////////////////////////////////
79 //                                                                           //
80 // class for TOF calibration                                                 //
81 //                                                                           //
82 ///////////////////////////////////////////////////////////////////////////////
83
84 #include "TF1.h"
85 #include "TFile.h"
86 #include "TH1F.h"
87 #include "TH2F.h"
88 //#include "TList.h"
89 //#include "TROOT.h"
90 //#include "TStyle.h"
91 #include "TTree.h"
92 #include "TChain.h"
93 #include "TProfile.h"
94 #include "TGrid.h"
95 #include "TMath.h"
96 #include "TMap.h"
97
98 #include "AliCDBEntry.h"
99 #include "AliCDBRunRange.h"
100 #include "AliCDBId.h"
101 #include "AliCDBManager.h"
102 #include "AliCDBStorage.h"
103 #include "AliCDBMetaData.h"
104 //#include "AliESDtrack.h"
105 //#include "AliESD.h"
106 #include "AliLog.h"
107
108 #include "AliTOFcalib.h"
109 #include "AliTOFChannelOnlineArray.h"
110 #include "AliTOFChannelOnline.h"
111 #include "AliTOFChannelOnlineStatus.h"
112 #include "AliTOFChannelOnlineStatusArray.h"
113 #include "AliTOFChannelOffline.h"
114 #include "AliTOFGeometry.h"
115 #include "AliTOFRecoParam.h"
116 #include "AliTOFDeltaBCOffset.h"
117 #include "AliTOFCTPLatency.h"
118 #include "AliTOFT0Fill.h"
119 #include "AliTOFRunParams.h"
120 #include "AliTOFResponseParams.h"
121 #include "AliESDEvent.h"
122 #include "AliESDtrack.h"
123
124 class TROOT;
125 class TStyle;
126
127 extern TROOT *gROOT;
128 extern TStyle *gStyle;
129
130 ClassImp(AliTOFcalib)
131
132 //_______________________________________________________________________
133 AliTOFcalib::AliTOFcalib():
134   TTask("AliTOFcalib",""),
135   fNChannels(-1),
136   fTOFCalOnline(0x0),
137   fTOFCalOnlinePulser(0x0),
138   fTOFCalOnlineNoise(0x0),
139   fTOFCalOnlineHW(0x0),
140   fTOFCalOffline(0x0),
141   fCal(0x0),
142   fStatus(0x0),
143   fTOFSimToT(0x0),
144   fkValidity(0x0),
145   fTree(0x0),
146   fChain(0x0),
147   fNruns(0),
148   fFirstRun(0),
149   fLastRun(AliCDBRunRange::Infinity()),
150   fConfigMap(new TMap),
151   fDeltaBCOffset(NULL),
152   fCTPLatency(NULL),
153   fT0Fill(NULL),
154   fRunParams(NULL),
155   fResponseParams(NULL),
156   fReadoutEfficiency(NULL),
157   fInitFlag(kFALSE),
158   fRemoveMeanT0(kTRUE),
159   fCalibrateTOFsignal(kTRUE),
160   fCorrectTExp(kFALSE)
161
162   //TOF Calibration Class ctor
163   fNChannels = AliTOFGeometry::NSectors()*(2*(AliTOFGeometry::NStripC()+AliTOFGeometry::NStripB())+AliTOFGeometry::NStripA())*AliTOFGeometry::NpadZ()*AliTOFGeometry::NpadX();
164 }
165 //____________________________________________________________________________ 
166
167 AliTOFcalib::AliTOFcalib(const AliTOFcalib & calib):
168   TTask(calib),
169   fNChannels(calib.fNChannels),
170   fTOFCalOnline(0x0),
171   fTOFCalOnlinePulser(0x0),
172   fTOFCalOnlineNoise(0x0),
173   fTOFCalOnlineHW(0x0),
174   fTOFCalOffline(0x0),
175   fCal(calib.fCal),
176   fStatus(calib.fStatus),
177   fTOFSimToT(calib.fTOFSimToT),
178   fkValidity(calib.fkValidity),
179   fTree(calib.fTree),
180   fChain(calib.fChain),
181   fNruns(calib.fNruns),
182   fFirstRun(calib.fFirstRun),
183   fLastRun(calib.fLastRun),
184   fConfigMap(calib.fConfigMap),
185   fDeltaBCOffset(NULL),
186   fCTPLatency(NULL),
187   fT0Fill(NULL),
188   fRunParams(NULL),
189   fResponseParams(NULL),
190   fReadoutEfficiency(NULL),
191   fInitFlag(calib.fInitFlag),
192   fRemoveMeanT0(calib.fRemoveMeanT0),
193   fCalibrateTOFsignal(calib.fCalibrateTOFsignal),
194   fCorrectTExp(calib.fCorrectTExp)
195 {
196
197   fTOFCalOnline = new TObjArray(fNChannels);
198   fTOFCalOnlinePulser = new TObjArray(fNChannels);
199   fTOFCalOnlineNoise = new TObjArray(fNChannels);
200   fTOFCalOnlineHW = new TObjArray(fNChannels);
201   fTOFCalOffline = new TObjArray(fNChannels);
202   fTOFCalOnline->SetOwner();
203   fTOFCalOnlinePulser->SetOwner();
204   fTOFCalOnlineNoise->SetOwner();
205   fTOFCalOnlineHW->SetOwner();
206   fTOFCalOffline->SetOwner();
207
208   //TOF Calibration Class copy ctor
209   for (Int_t iarray = 0; iarray<fNChannels; iarray++){
210     AliTOFChannelOnline * calChOnline = (AliTOFChannelOnline*)calib.fTOFCalOnline->At(iarray);
211     AliTOFChannelOnlineStatus * calChOnlineStPulser = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlinePulser->At(iarray);
212     AliTOFChannelOnlineStatus * calChOnlineStNoise = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlineNoise->At(iarray);
213     AliTOFChannelOnlineStatus * calChOnlineStHW = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlineHW->At(iarray);
214     AliTOFChannelOffline * calChOffline = (AliTOFChannelOffline*)calib.fTOFCalOffline->At(iarray);
215     fTOFCalOnline->AddAt(calChOnline,iarray);
216     fTOFCalOnlinePulser->AddAt(calChOnlineStPulser,iarray);
217     fTOFCalOnlineNoise->AddAt(calChOnlineStNoise,iarray);
218     fTOFCalOnlineHW->AddAt(calChOnlineStHW,iarray);
219     fTOFCalOffline->AddAt(calChOffline,iarray);
220   }
221
222   if (calib.fDeltaBCOffset) fDeltaBCOffset = new AliTOFDeltaBCOffset(*calib.fDeltaBCOffset);
223   if (calib.fCTPLatency) fCTPLatency = new AliTOFCTPLatency(*calib.fCTPLatency);
224   if (calib.fT0Fill) fT0Fill = new AliTOFT0Fill(*calib.fT0Fill);
225   if (calib.fRunParams) fRunParams = new AliTOFRunParams(*calib.fRunParams);
226   if (calib.fResponseParams) fResponseParams = new AliTOFResponseParams(*calib.fResponseParams);
227   if (calib.fReadoutEfficiency) fReadoutEfficiency = new TH1F(*calib.fReadoutEfficiency);
228 }
229
230 //____________________________________________________________________________ 
231
232 AliTOFcalib& AliTOFcalib::operator=(const AliTOFcalib &calib)
233 {
234   //TOF Calibration Class assignment operator
235
236   if (this == &calib)
237     return *this;
238   
239   TTask::operator=(calib);
240   fNChannels = calib.fNChannels;
241   fCal = calib.fCal;
242   fStatus = calib.fStatus;
243   fTOFSimToT = calib.fTOFSimToT;
244   fkValidity = calib.fkValidity;
245   fTree = calib.fTree;
246   fChain = calib.fChain;
247   fNruns = calib.fNruns;
248   fFirstRun = calib.fFirstRun;
249   fLastRun = calib.fLastRun;
250   for (Int_t iarray = 0; iarray<fNChannels; iarray++){
251     AliTOFChannelOnline * calChOnline = (AliTOFChannelOnline*)calib.fTOFCalOnline->At(iarray);
252     AliTOFChannelOffline * calChOffline = (AliTOFChannelOffline*)calib.fTOFCalOffline->At(iarray);
253     AliTOFChannelOnlineStatus * calChOnlineStPulser = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlinePulser->At(iarray);
254     AliTOFChannelOnlineStatus * calChOnlineStNoise = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlineNoise->At(iarray);
255     AliTOFChannelOnlineStatus * calChOnlineStHW = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlineHW->At(iarray);
256     fTOFCalOnline->AddAt(calChOnline,iarray);
257     fTOFCalOnlinePulser->AddAt(calChOnlineStPulser,iarray);
258     fTOFCalOnlineNoise->AddAt(calChOnlineStNoise,iarray);
259     fTOFCalOnlineHW->AddAt(calChOnlineStHW,iarray);
260     fTOFCalOffline->AddAt(calChOffline,iarray);
261   }
262
263   if (calib.fDeltaBCOffset) {
264     if (fDeltaBCOffset) *fDeltaBCOffset = *calib.fDeltaBCOffset;
265     else fDeltaBCOffset = new AliTOFDeltaBCOffset(*calib.fDeltaBCOffset);
266   }
267
268   if (calib.fCTPLatency) {
269     if (fCTPLatency) *fCTPLatency = *calib.fCTPLatency;
270     else fCTPLatency = new AliTOFCTPLatency(*calib.fCTPLatency);
271   }
272
273   if (calib.fT0Fill) {
274     if (fT0Fill) *fT0Fill = *calib.fT0Fill;
275     else fT0Fill = new AliTOFT0Fill(*calib.fT0Fill);
276   }
277   if (calib.fRunParams) {
278     if (fRunParams) *fRunParams = *calib.fRunParams;
279     else fRunParams = new AliTOFRunParams(*calib.fRunParams);
280   }
281   if (calib.fResponseParams) {
282     if (fResponseParams) *fResponseParams = *calib.fResponseParams;
283     else fResponseParams = new AliTOFResponseParams(*calib.fResponseParams);
284   }
285   if (calib.fReadoutEfficiency) {
286     if (fReadoutEfficiency) *fReadoutEfficiency = *calib.fReadoutEfficiency;
287     else fReadoutEfficiency = new TH1F(*calib.fReadoutEfficiency);
288   }
289   fInitFlag = calib.fInitFlag;
290   fRemoveMeanT0 = calib.fRemoveMeanT0;
291   fCalibrateTOFsignal = calib.fCalibrateTOFsignal;
292   fCorrectTExp = calib.fCorrectTExp;
293
294   return *this;
295 }
296
297 //____________________________________________________________________________ 
298
299 AliTOFcalib::~AliTOFcalib()
300 {
301   //TOF Calibration Class dtor
302   if(!(AliCDBManager::Instance()->GetCacheFlag())){ // CDB objects must NOT be deleted if cache is active!
303     if (fTOFCalOnline){
304       delete fTOFCalOnline;
305     }
306     if (fTOFCalOnlinePulser){
307       delete fTOFCalOnlinePulser;
308     }
309     if (fTOFCalOnlineNoise){
310       delete fTOFCalOnlineNoise;
311     }
312     if (fTOFCalOnlineHW){
313       delete fTOFCalOnlineHW;
314     }
315     if (fTOFCalOffline){
316       delete fTOFCalOffline;
317     }
318     if (fCal){
319       delete fCal;
320     }
321     if (fStatus){
322       delete fStatus;
323     }
324     if (fConfigMap){
325       delete fConfigMap;
326     }
327     if (fDeltaBCOffset) delete fDeltaBCOffset;
328     if (fCTPLatency) delete fCTPLatency;
329     if (fT0Fill) delete fT0Fill;
330     if (fRunParams) delete fRunParams;
331     if (fResponseParams) delete fResponseParams;
332     if (fReadoutEfficiency) delete fReadoutEfficiency;
333   }
334   if (fTree!=0x0) delete fTree;
335   if (fChain!=0x0) delete fChain;
336
337 }
338 //_____________________________________________________________________________
339 void AliTOFcalib::CreateCalArrays(){
340
341   // creating arrays for online/offline calibration objs
342
343   fTOFCalOnline = new TObjArray(fNChannels);
344   fTOFCalOnlinePulser = new TObjArray(fNChannels);
345   fTOFCalOnlineNoise = new TObjArray(fNChannels);
346   fTOFCalOnlineHW = new TObjArray(fNChannels);
347   fTOFCalOffline = new TObjArray(fNChannels);
348   fTOFCalOnline->SetOwner();
349   fTOFCalOnlinePulser->SetOwner();
350   fTOFCalOnlineNoise->SetOwner();
351   fTOFCalOnlineHW->SetOwner();
352   fTOFCalOffline->SetOwner();
353   for (Int_t iarray = 0; iarray<fNChannels; iarray++){
354     AliTOFChannelOnline * calChOnline = new AliTOFChannelOnline();
355     AliTOFChannelOnlineStatus * calChOnlineStPulser = new AliTOFChannelOnlineStatus();
356     AliTOFChannelOnlineStatus * calChOnlineStNoise = new AliTOFChannelOnlineStatus();
357     AliTOFChannelOnlineStatus * calChOnlineStHW = new AliTOFChannelOnlineStatus();
358     AliTOFChannelOffline * calChOffline = new AliTOFChannelOffline();
359     fTOFCalOnline->AddAt(calChOnline,iarray);
360     fTOFCalOnlinePulser->AddAt(calChOnlineStPulser,iarray);
361     fTOFCalOnlineNoise->AddAt(calChOnlineStNoise,iarray);
362     fTOFCalOnlineHW->AddAt(calChOnlineStHW,iarray);
363     fTOFCalOffline->AddAt(calChOffline,iarray);
364   }
365   fCal = new AliTOFChannelOnlineArray(fNChannels);
366   fStatus = new AliTOFChannelOnlineStatusArray(fNChannels);
367 }
368 //_____________________________________________________________________________
369 void AliTOFcalib::CreateCalObjects(){
370
371   // creating arrays for online/offline calibration objs
372
373   fTOFCalOffline = new TObjArray(fNChannels);
374   fTOFCalOffline->SetOwner();
375   for (Int_t iarray = 0; iarray<fNChannels; iarray++){
376     AliTOFChannelOffline * calChOffline = new AliTOFChannelOffline();
377     fTOFCalOffline->AddAt(calChOffline,iarray);
378   }
379   fCal = new AliTOFChannelOnlineArray(fNChannels);
380   fStatus = new AliTOFChannelOnlineStatusArray(fNChannels);
381 }
382 //_____________________________________________________________________________
383 void AliTOFcalib::WriteConfigMapOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
384 {
385   //Write calibration parameters to the CDB
386   SetFirstRun(minrun);
387   SetLastRun(maxrun);
388   AliCDBManager *man = AliCDBManager::Instance();
389   const Char_t *sel1 = "Config" ;  // to be consistent with TOFPreprocessor
390   TString out(Form("%s/%s",sel,sel1));
391   AliDebug(2,Form("Writing TOF configuration map for online calib on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
392   AliCDBId id(out,fFirstRun,fLastRun);
393   AliCDBMetaData *md = new AliCDBMetaData();
394   md->SetResponsible("Chiara Zampolli");
395   if (!fConfigMap) {
396     // deve uscire!!
397   }
398   man->Put(fConfigMap,id,md);
399   delete md;
400 }
401 //_____________________________________________________________________________
402
403 void AliTOFcalib::WriteConfigMapOnCDB(const Char_t *sel)
404 {
405   //Write calibration parameters to the CDB with infinite validity
406   AliCDBManager *man = AliCDBManager::Instance();
407   const Char_t *sel1 = "Config" ;  // to be consistent with TOFPreprocessor
408   TString out(Form("%s/%s",sel,sel1));
409   AliCDBRunRange runrange(fFirstRun,fLastRun);
410   AliDebug(2,Form("Writing TOF config map for online calib on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
411   AliCDBId id(out,runrange);
412   AliCDBMetaData *md = new AliCDBMetaData();
413   md->SetResponsible("Chiara Zampolli");
414   if (!fConfigMap) {
415     // deve uscire!!
416   }
417   man->Put(fConfigMap,id,md);
418   delete md;
419 }
420 //_____________________________________________________________________________
421 void AliTOFcalib::WriteParOnlineDelayOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
422 {
423   //Write calibration parameters to the CDB -------> new calib objs!!!!!
424   SetFirstRun(minrun);
425   SetLastRun(maxrun);
426   AliCDBManager *man = AliCDBManager::Instance();
427   const Char_t *sel1 = "ParOnlineDelay" ;  // to be consistent with TOFPreprocessor
428   TString out(Form("%s/%s",sel,sel1));
429   AliDebug(2,Form("Writing TOF online calib obj on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
430   AliCDBId id(out,fFirstRun,fLastRun);
431   AliCDBMetaData *md = new AliCDBMetaData();
432   md->SetResponsible("Chiara Zampolli");
433   if (!fCal) {
434     // deve uscire!!
435   }
436   man->Put(fCal,id,md);
437   delete md;
438 }
439 //_____________________________________________________________________________
440 void AliTOFcalib::WriteParOnlineStatusOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
441 {
442   //Write calibration parameters to the CDB -------> new calib objs!!!!!
443   SetFirstRun(minrun);
444   SetLastRun(maxrun);
445   AliCDBManager *man = AliCDBManager::Instance();
446   const Char_t *sel1 = "Status" ;  // to be consistent with TOFPreprocessor
447   TString out(Form("%s/%s",sel,sel1));
448   AliDebug(2,Form("Writing TOF online status calib obj on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
449   AliCDBId id(out,fFirstRun,fLastRun);
450   AliCDBMetaData *md = new AliCDBMetaData();
451   md->SetResponsible("Chiara Zampolli");
452   if (!fStatus) {
453     // deve uscire!!
454   }
455   man->Put(fStatus,id,md);
456   delete md;
457 }
458 //_____________________________________________________________________________
459
460 void AliTOFcalib::WriteParOnlineDelayOnCDB(const Char_t *sel)
461 {
462   //Write calibration parameters to the CDB with infinite validity -------> new calib objs!!!!!
463   AliCDBManager *man = AliCDBManager::Instance();
464   const Char_t *sel1 = "ParOnlineDelay" ;  // to be consistent with TOFPreprocessor
465   TString out(Form("%s/%s",sel,sel1));
466   AliCDBRunRange runrange(fFirstRun,fLastRun);
467   AliDebug(2,Form("Writing TOF online calib obj on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
468   AliCDBId id(out,runrange);
469   AliCDBMetaData *md = new AliCDBMetaData();
470   md->SetResponsible("Chiara Zampolli");
471   if (!fCal) {
472     // deve uscire!!
473   }
474   man->Put(fCal,id,md);
475   delete md;
476 }
477 //_____________________________________________________________________________
478
479 void AliTOFcalib::WriteParOnlineStatusOnCDB(const Char_t *sel)
480 {
481   //Write calibration parameters to the CDB with infinite validity -------> new calib objs!!!!!
482   AliCDBManager *man = AliCDBManager::Instance();
483   const Char_t *sel1 = "Status" ;  // to be consistent with TOFPreprocessor
484   TString out(Form("%s/%s",sel,sel1));
485   AliCDBRunRange runrange(fFirstRun,fLastRun);
486   AliDebug(2,Form("Writing TOF online status calib obj on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
487   AliCDBId id(out,runrange);
488   AliCDBMetaData *md = new AliCDBMetaData();
489   md->SetResponsible("Chiara Zampolli");
490   if (!fStatus) {
491     // deve uscire!!
492   }
493   man->Put(fStatus,id,md);
494   delete md;
495 }
496 //_____________________________________________________________________________
497 void AliTOFcalib::WriteParOnlineOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
498 {
499   //Write calibration parameters to the CDB
500   SetFirstRun(minrun);
501   SetLastRun(maxrun);
502   AliCDBManager *man = AliCDBManager::Instance();
503   const Char_t *sel1 = "ParOnline" ;  // to be consistent with TOFPreprocessor
504   TString out(Form("%s/%s",sel,sel1));
505   AliDebug(2,Form("Writing TOF online calib obj on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
506   AliCDBId id(out,fFirstRun,fLastRun);
507   AliCDBMetaData *md = new AliCDBMetaData();
508   md->SetResponsible("Chiara Zampolli");
509   if (!fTOFCalOnline) {
510     // deve uscire!!
511   }
512   man->Put(fTOFCalOnline,id,md);
513   delete md;
514 }
515 //_____________________________________________________________________________
516 void AliTOFcalib::WriteParOnlinePulserOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
517 {
518   //Write calibration parameters from pulser to the CDB
519   SetFirstRun(minrun);
520   SetLastRun(maxrun);
521   AliCDBManager *man = AliCDBManager::Instance();
522   const Char_t *sel1 = "Pulser" ;  // to be consistent with TOFPreprocessor
523   TString out(Form("%s/%s",sel,sel1));
524   AliDebug(2,Form("Writing TOF online calib obj from pulser on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
525   AliCDBId id(out,fFirstRun,fLastRun);
526   AliCDBMetaData *md = new AliCDBMetaData();
527   md->SetResponsible("Chiara Zampolli");
528   if (!fTOFCalOnlinePulser) {
529     // deve uscire!!
530   }
531   man->Put(fTOFCalOnlinePulser,id,md);
532   delete md;
533 }
534 //_____________________________________________________________________________
535 void AliTOFcalib::WriteParOnlineNoiseOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
536 {
537   //Write calibration parameters from noise to the CDB
538   SetFirstRun(minrun);
539   SetLastRun(maxrun);
540   AliCDBManager *man = AliCDBManager::Instance();
541   const Char_t *sel1 = "Noise" ;  // to be consistent with TOFPreprocessor
542   TString out(Form("%s/%s",sel,sel1));
543   AliDebug(2,Form("Writing TOF online calib obj from noise on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
544   AliCDBId id(out,fFirstRun,fLastRun);
545   AliCDBMetaData *md = new AliCDBMetaData();
546   md->SetResponsible("Chiara Zampolli");
547   if (!fTOFCalOnlineNoise) {
548     // deve uscire!!
549   }
550   man->Put(fTOFCalOnlineNoise,id,md);
551   delete md;
552 }
553 //_____________________________________________________________________________
554 void AliTOFcalib::WriteParOnlineHWOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
555 {
556   //Write calibration parameters from hardware to the CDB
557   SetFirstRun(minrun);
558   SetLastRun(maxrun);
559   AliCDBManager *man = AliCDBManager::Instance();
560   const Char_t *sel1 = "HW" ;  // to be consistent with TOFPreprocessor
561   TString out(Form("%s/%s",sel,sel1));
562   AliDebug(2,Form("Writing TOF online calib obj from hardware on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
563   AliCDBId id(out,fFirstRun,fLastRun);
564   AliCDBMetaData *md = new AliCDBMetaData();
565   md->SetResponsible("Chiara Zampolli");
566   if (!fTOFCalOnlineHW) {
567     // deve uscire!!
568   }
569   man->Put(fTOFCalOnlineHW,id,md);
570   delete md;
571 }
572 //_____________________________________________________________________________
573
574 void AliTOFcalib::WriteParOnlineOnCDB(const Char_t *sel)
575 {
576   //Write calibration parameters to the CDB with infinite validity
577   AliCDBManager *man = AliCDBManager::Instance();
578   const Char_t *sel1 = "ParOnline" ;  // to be consistent with TOFPreprocessor
579   TString out(Form("%s/%s",sel,sel1));
580   AliCDBRunRange runrange(fFirstRun,fLastRun);
581   AliDebug(2,Form("Writing TOF online calib obj on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
582   AliCDBId id(out,runrange);
583   AliCDBMetaData *md = new AliCDBMetaData();
584   md->SetResponsible("Chiara Zampolli");
585   if (!fTOFCalOnline) {
586     // deve uscire!!
587   }
588   man->Put(fTOFCalOnline,id,md);
589   delete md;
590 }
591 //_____________________________________________________________________________
592
593 void AliTOFcalib::WriteParOnlinePulserOnCDB(const Char_t *sel)
594 {
595   //Write calibration parameters from pulser to the CDB with infinite validity
596   AliCDBManager *man = AliCDBManager::Instance();
597   const Char_t *sel1 = "Pulser" ;  // to be consistent with TOFPreprocessor
598   TString out(Form("%s/%s",sel,sel1));
599   AliCDBRunRange runrange(fFirstRun,fLastRun);
600   AliDebug(2,Form("Writing TOF online calib obj from pulser on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
601   AliCDBId id(out,runrange);
602   AliCDBMetaData *md = new AliCDBMetaData();
603   md->SetResponsible("Chiara Zampolli");
604   if (!fTOFCalOnlinePulser) {
605     // deve uscire!!
606   }
607   man->Put(fTOFCalOnlinePulser,id,md);
608   delete md;
609 }
610 //_____________________________________________________________________________
611
612 void AliTOFcalib::WriteParOnlineNoiseOnCDB(const Char_t *sel)
613 {
614   //Write calibration parameters from noise to the CDB with infinite validity
615   AliCDBManager *man = AliCDBManager::Instance();
616   const Char_t *sel1 = "Noise" ;  // to be consistent with TOFPreprocessor
617   TString out(Form("%s/%s",sel,sel1));
618   AliCDBRunRange runrange(fFirstRun,fLastRun);
619   AliDebug(2,Form("Writing TOF online calib obj from noise on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
620   AliCDBId id(out,runrange);
621   AliCDBMetaData *md = new AliCDBMetaData();
622   md->SetResponsible("Chiara Zampolli");
623   if (!fTOFCalOnlineNoise) {
624     // deve uscire!!
625   }
626   man->Put(fTOFCalOnlineNoise,id,md);
627   delete md;
628 }
629 //_____________________________________________________________________________
630
631 void AliTOFcalib::WriteParOnlineHWOnCDB(const Char_t *sel)
632 {
633   //Write calibration parameters from hardware to the CDB with infinite validity
634   AliCDBManager *man = AliCDBManager::Instance();
635   const Char_t *sel1 = "HW" ;  // to be consistent with TOFPreprocessor
636   TString out(Form("%s/%s",sel,sel1));
637   AliCDBRunRange runrange(fFirstRun,fLastRun);
638   AliDebug(2,Form("Writing TOF online calib obj from harware on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
639   AliCDBId id(out,runrange);
640   AliCDBMetaData *md = new AliCDBMetaData();
641   md->SetResponsible("Chiara Zampolli");
642   if (!fTOFCalOnlineHW) {
643     // deve uscire!!
644   }
645   man->Put(fTOFCalOnlineHW,id,md);
646   delete md;
647 }
648 //_____________________________________________________________________________
649
650 void AliTOFcalib::WriteParOfflineOnCDB(const Char_t *sel, const Char_t *validity, Int_t minrun, Int_t maxrun)
651 {
652   //Write calibration parameters to the CDB
653   SetFirstRun(minrun);
654   SetLastRun(maxrun);
655   AliCDBManager *man = AliCDBManager::Instance();
656   const Char_t *sel1 = "ParOffline" ;
657   TString out(Form("%s/%s",sel,sel1));
658   AliDebug(2,Form("Writing TOF offline calib obj on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
659   AliCDBId id(out,fFirstRun,fLastRun);
660   AliCDBMetaData *md = new AliCDBMetaData();
661   md->SetResponsible("Chiara Zampolli");
662   md->SetComment(validity);
663   man->Put(fTOFCalOffline,id,md);
664   delete md;
665 }
666 //_____________________________________________________________________________
667
668 void AliTOFcalib::WriteParOfflineOnCDB(const Char_t *sel, const Char_t *validity)
669 {
670   //Write calibration parameters to the CDB with infinite validity
671   AliCDBManager *man = AliCDBManager::Instance();
672   const Char_t *sel1 = "ParOffline" ;
673   TString out(Form("%s/%s",sel,sel1));
674   AliCDBRunRange runrange(fFirstRun,fLastRun);
675   AliDebug(2,Form("Writing TOF offline calib obj on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
676   AliCDBId id(out,runrange);
677   AliCDBMetaData *md = new AliCDBMetaData();
678   md->SetResponsible("Chiara Zampolli");
679   md->SetComment(validity);
680   man->Put(fTOFCalOffline,id,md);
681   delete md;
682 }
683 //_____________________________________________________________________________
684
685 Bool_t AliTOFcalib::ReadConfigMapFromCDB(const Char_t *sel, Int_t nrun)
686 {
687   //Read calibration parameters from the CDB
688   AliCDBManager *man = AliCDBManager::Instance();
689   const Char_t *sel1 = "Config" ;
690   TString out(Form("%s/%s",sel,sel1));
691   AliCDBEntry *entry = man->Get(out,nrun);
692   if (!entry) { 
693     AliFatal("Exiting, no CDB object (ConfigMap) found!!!");
694     exit(0);  
695   }
696   if(!entry->GetObject()){
697     AliFatal("Exiting, no CDB object (ConfigMap) found!!!");
698     exit(0);  
699   }  
700   
701   fConfigMap =(TMap*)entry->GetObject();
702
703   return kTRUE; 
704    
705 }
706 //_____________________________________________________________________________
707
708 Bool_t AliTOFcalib::ReadParOnlineDelayFromCDB(const Char_t *sel, Int_t nrun)
709 {
710   //Read calibration parameters from the CDB -------> new calib objs!!!!!
711   AliCDBManager *man = AliCDBManager::Instance();
712   const Char_t *sel1 = "ParOnlineDelay" ;
713   TString out(Form("%s/%s",sel,sel1));
714   AliCDBEntry *entry = man->Get(out,nrun);
715   if (!entry) { 
716     AliFatal("Exiting, no CDB object (ParOnlineDelay) found!!!");
717     exit(0);  
718   }
719   if(!entry->GetObject()){
720     AliFatal("Exiting, no CDB object (ParOnlineDelay) found!!!");
721     exit(0);  
722   }  
723   
724   fCal =(AliTOFChannelOnlineArray*)entry->GetObject();
725
726   return kTRUE; 
727    
728 }
729 //_____________________________________________________________________________
730
731 Bool_t AliTOFcalib::ReadParOnlineStatusFromCDB(const Char_t *sel, Int_t nrun)
732 {
733   //Read calibration parameters from the CDB -------> new calib objs!!!!!
734   AliCDBManager *man = AliCDBManager::Instance();
735   const Char_t *sel1 = "Status" ;
736   TString out(Form("%s/%s",sel,sel1));
737   AliCDBEntry *entry = man->Get(out,nrun);
738   if (!entry) { 
739     AliFatal("Exiting, no CDB object (Status) found!!!");
740     exit(0);  
741   }
742   if(!entry->GetObject()){
743     AliFatal("Exiting, no CDB object (Status) found!!!");
744     exit(0);  
745   }  
746   
747   fStatus =(AliTOFChannelOnlineStatusArray*)entry->GetObject();
748
749   return kTRUE; 
750    
751 }
752 //_____________________________________________________________________________
753
754 Bool_t AliTOFcalib::ReadParOnlineFromCDB(const Char_t *sel, Int_t nrun)
755 {
756   //Read calibration parameters from the CDB
757   AliCDBManager *man = AliCDBManager::Instance();
758   const Char_t *sel1 = "ParOnline" ;
759   TString out(Form("%s/%s",sel,sel1));
760   AliCDBEntry *entry = man->Get(out,nrun);
761   if (!entry) { 
762     AliFatal("Exiting, no CDB object (ParOnline) found!!!");
763     exit(0);  
764   }
765   if(!entry->GetObject()){
766     AliFatal("Exiting, no CDB object (ParOnline) found!!!");
767     exit(0);  
768   }  
769   
770   fTOFCalOnline =(TObjArray*)entry->GetObject();
771
772   return kTRUE; 
773    
774 }
775 //_____________________________________________________________________________
776
777 Bool_t AliTOFcalib::ReadParOnlinePulserFromCDB(const Char_t *sel, Int_t nrun)
778 {
779   //Read calibration parameters from pulser from the CDB
780   AliCDBManager *man = AliCDBManager::Instance();
781   const Char_t *sel1 = "Pulser" ;
782   TString out(Form("%s/%s",sel,sel1));
783   AliCDBEntry *entry = man->Get(out,nrun);
784   if (!entry) { 
785     AliFatal("Exiting, no CDB object (Pulser) found!!!");
786     exit(0);  
787   }
788   if(!entry->GetObject()){
789     AliFatal("Exiting, no CDB object (Pulser) found!!!");
790     exit(0);  
791   }  
792   
793   fTOFCalOnlinePulser =(TObjArray*)entry->GetObject();
794
795   return kTRUE; 
796    
797 }
798 //_____________________________________________________________________________
799
800 Bool_t AliTOFcalib::ReadParOnlineNoiseFromCDB(const Char_t *sel, Int_t nrun)
801 {
802   //Read calibration parameters from noise from the CDB
803   AliCDBManager *man = AliCDBManager::Instance();
804   const Char_t *sel1 = "Noise" ;
805   TString out(Form("%s/%s",sel,sel1));
806   AliCDBEntry *entry = man->Get(out,nrun);
807   if (!entry) { 
808     AliFatal("Exiting, no CDB object (Noise) found!!!");
809     exit(0);  
810   }
811   if(!entry->GetObject()){
812     AliFatal("Exiting, no CDB object (Noise) found!!!");
813     exit(0);  
814   }  
815   
816   fTOFCalOnlineNoise =(TObjArray*)entry->GetObject();
817
818   return kTRUE; 
819    
820 }
821 //_____________________________________________________________________________
822
823 Bool_t AliTOFcalib::ReadParOnlineHWFromCDB(const Char_t *sel, Int_t nrun)
824 {
825   //Read calibration parameters from hardware from the CDB
826   AliCDBManager *man = AliCDBManager::Instance();
827   const Char_t *sel1 = "HW" ;
828   TString out(Form("%s/%s",sel,sel1));
829   AliCDBEntry *entry = man->Get(out,nrun);
830   if (!entry) { 
831     AliFatal("Exiting, no CDB object (HW map) found!!!");
832     exit(0);  
833   }
834   if(!entry->GetObject()){
835     AliFatal("Exiting, no CDB object (HW map) found!!!");
836     exit(0);  
837   }  
838   
839   fTOFCalOnlineHW =(TObjArray*)entry->GetObject();
840
841   return kTRUE; 
842    
843 }
844 //_____________________________________________________________________________
845
846 Bool_t AliTOFcalib::ReadParOfflineFromCDB(const Char_t *sel, Int_t nrun)
847 {
848   //Read calibration parameters from the CDB
849   AliCDBManager *man = AliCDBManager::Instance();
850   const Char_t *sel1 = "ParOffline" ;
851   TString out(Form("%s/%s",sel,sel1));
852   AliCDBEntry *entry = man->Get(out,nrun);
853   if (!entry) { 
854     AliFatal("Exiting, no CDB object (ParOffline) found!!!");
855     exit(0);  
856   }
857   if(!entry->GetObject()){
858     AliFatal("Exiting, no CDB object (ParOffline) found!!!");
859     exit(0);  
860   }  
861   AliCDBMetaData * md = entry->GetMetaData();
862   fkValidity = md->GetComment();  
863   fTOFCalOffline =(TObjArray*)entry->GetObject();
864
865   return kTRUE; 
866    
867 }
868 //_____________________________________________________________________________
869 void AliTOFcalib::WriteSimHistoOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun, TH1F *histo){
870   //Write Sim miscalibration parameters to the CDB
871
872   fTOFSimToT=histo;
873   AliCDBManager *man = AliCDBManager::Instance();
874   const Char_t *sel1 = "SimHisto" ;
875   TString out(Form("%s/%s",sel,sel1));
876   AliCDBMetaData *mdhisto = new AliCDBMetaData();
877   mdhisto->SetResponsible("Chiara Zampolli");
878   AliCDBId id(out,minrun,maxrun);
879   man->Put(fTOFSimToT,id,mdhisto);
880   delete mdhisto;
881 }
882 //_____________________________________________________________________________
883 Bool_t AliTOFcalib::ReadSimHistoFromCDB(const Char_t *sel, Int_t nrun)
884 {
885   //Read miscalibration parameters from the CDB
886   AliCDBManager *man = AliCDBManager::Instance();
887
888   // The Tot Histo
889
890   const Char_t *sel1 = "SimHisto" ;
891   TString out(Form("%s/%s",sel,sel1));
892   AliCDBEntry *entry = man->Get(out,nrun);
893   if (!entry) { 
894     AliFatal("Exiting, no CDB object (SimHisto) found!!!");
895     exit(0);  
896   }
897   if(!entry->GetObject()){
898     AliFatal("Exiting, no CDB object (SimHisto) found!!!");
899     exit(0);  
900   }  
901   TH1F *histo =(TH1F*)entry->GetObject();
902   fTOFSimToT=histo;
903   return kTRUE;
904 }
905 //_____________________________________________________________________________
906 void AliTOFcalib::WriteRecParOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun, AliTOFRecoParam *param){
907   //Write reconstruction parameters to the CDB
908
909   AliCDBManager *man = AliCDBManager::Instance();
910   AliCDBMetaData *md = new AliCDBMetaData();
911   md->SetResponsible("Silvia Arcelli");
912   const Char_t *sel1 = "RecoParam" ;
913   TString out(Form("%s/%s",sel,sel1));
914   AliCDBId id(out,minrun,maxrun);
915
916   TObjArray *arr=new TObjArray(1);
917   arr->AddLast(param);
918   man->Put(arr,id,md);
919   //man->Put(param,id,md);
920   delete md;
921 }
922 //_____________________________________________________________________________
923 void AliTOFcalib::WriteRecParOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun, TObjArray *arr){
924   //Write reconstruction parameters to the CDB
925
926   AliCDBManager *man = AliCDBManager::Instance();
927   AliCDBMetaData *md = new AliCDBMetaData();
928   md->SetResponsible("Silvia Arcelli");
929   const Char_t *sel1 = "RecoParam" ;
930   TString out(Form("%s/%s",sel,sel1));
931   AliCDBId id(out,minrun,maxrun);
932   man->Put(arr,id,md);
933   delete md;
934 }
935 //_____________________________________________________________________________
936 AliTOFRecoParam * AliTOFcalib::ReadRecParFromCDB(const Char_t *sel, Int_t nrun, Int_t eventType)
937 {
938   //Read reconstruction parameters from the CDB
939   AliCDBManager *man = AliCDBManager::Instance();
940   const Char_t *sel1 = "RecoParam" ;
941   TString out(Form("%s/%s",sel,sel1));
942   AliCDBEntry *entry = man->Get(out,nrun);
943   if (!entry) { 
944     AliFatal("Exiting, no CDB object (RecoParam) found!!!");
945     exit(0);  
946   }  
947   if(!entry->GetObject()){
948     AliFatal("Exiting, no CDB object (RecoParam) found!!!");
949     exit(0);  
950   }  
951
952   TObjArray *array = (TObjArray*)entry->GetObject();
953   AliTOFRecoParam *param=0x0;
954   if (eventType>=0 || eventType<array->GetEntries())
955     param=(AliTOFRecoParam*)array->At(eventType);
956   return param;
957
958 }
959 //-----------------------------------------------------------------------------
960 // Calibration methods
961 //-----------------------------------------------------------------------------
962 void AliTOFcalib::CreateTreeFromCDB(Int_t minrun, Int_t maxrun){
963
964   // creating the chain with the trees for calibration
965   // collecting them from reference data 
966   // from minrun to maxrun
967
968   Float_t p[CHENTRIESSMALL];
969   Int_t nentries;
970   fTree = new TTree("TOFCalib","Tree for TOF Calibration");
971   fTree->Branch("nentries",&nentries,"nentries/I");
972   fTree->Branch("TOFentries",p,"TOFentries[nentries]/F");
973   AliCDBManager *man = AliCDBManager::Instance();
974   AliCDBStorage *aStorage = man->GetStorage("local://$ALICE_ROOT/OCDB");
975   for (Int_t irun = minrun;irun<=maxrun;irun++){
976     AliCDBEntry *entry = aStorage->Get("TOF/RefData/TreeForCalib",irun);
977     if (!entry){
978       AliInfo(Form("No entry found for run %i",irun));
979     }
980     else{
981       TTree *tree = (TTree*)entry->GetObject();
982       tree->SetBranchAddress("nentries",&nentries);
983       tree->SetBranchAddress("TOFentries",p);      
984       fTree->CopyEntries(tree);
985       fNruns++;
986     }
987   }
988   AliInfo(Form("Number of runs being analyzed %i",fNruns));
989 }
990 //-----------------------------------------------------------------------------
991 void AliTOFcalib::CreateTreeFromGrid(Int_t minrun, Int_t maxrun){
992
993   // creating the chain with the trees for calibration
994   // collecting them from the Grid 
995   // from minrun to maxrun
996
997   Float_t p[CHENTRIESSMALL];
998   Int_t nentries;
999   fTree = new TTree("TOFCalib","Tree for TOF Calibration");
1000   fTree->SetDirectory(0);
1001   fTree->Branch("nentries",&nentries,"nentries/I");
1002   fTree->Branch("TOFentries",p,"TOFentries[nentries]/F");
1003   AliInfo("connected to alien");
1004   TGrid::Connect("alien://");
1005   
1006   TString filename;
1007   for (Int_t irun = minrun;irun<=maxrun;irun++){
1008     filename = Form("alien:///alice/cern.ch/user/c/czampolli/TOFCalibReference_%i.root",irun);
1009     TFile *filegrid = TFile::Open(filename.Data(),"READ");
1010     TTree *tree = (TTree*)filegrid->Get("T");
1011     tree->SetBranchAddress("nentries",&nentries);
1012     tree->SetBranchAddress("TOFentries",p);      
1013     fTree->CopyEntries(tree);
1014     delete tree;
1015     fNruns++;    
1016   }
1017   
1018   AliInfo(Form("Number of runs being analyzed %i",fNruns));
1019 }
1020 //-----------------------------------------------------------------------------
1021 void AliTOFcalib::CreateTreeFromFile(Int_t minrun, Int_t maxrun){
1022
1023   // creating the tree with the trees for calibration
1024   // collecting them from reference data (from file)
1025   // from minrun to maxrun
1026
1027   Float_t p[CHENTRIESSMALL];
1028   Int_t nentries;
1029   fTree = new TTree("TOFCalib","Tree for TOF Calibration");
1030   fTree->SetDirectory(0);
1031   fTree->Branch("nentries",&nentries,"nentries/I");
1032   fTree->Branch("TOFentries",p,"TOFentries[nentries]/F");
1033   TString filename;
1034   for (Int_t irun = minrun;irun<=maxrun;irun++){
1035     filename = Form("$ALICE_ROOT/TOF/RefData/TreeForCalib/fileout_%i.root",irun);
1036     TFile *file = new TFile(filename.Data(),"READ");
1037     TTree *tree = (TTree*)file->Get("T");
1038     tree->SetBranchAddress("nentries",&nentries);
1039     tree->SetBranchAddress("TOFentries",p);      
1040     fTree->CopyEntries(tree);
1041     delete tree;
1042     delete file;
1043     file = 0x0;
1044     fNruns++;
1045   }
1046
1047   AliInfo(Form("Number of runs being analyzed %i",fNruns));
1048 }
1049 //-----------------------------------------------------------------------------
1050 void AliTOFcalib::CreateChainFromGrid(Int_t minrun, Int_t maxrun){
1051
1052   // creating the chain with the trees for calibration
1053   // collecting them from the Grid 
1054   // from minrun to maxrun
1055
1056   fChain = new TChain("T");
1057   AliInfo("connected to alien");
1058   TGrid::Connect("alien://");
1059   
1060   TString filename;
1061   for (Int_t irun = minrun;irun<=maxrun;irun++){
1062     filename = Form("alien:///alice/cern.ch/user/c/czampolli/TOFCalibReference_%i.root",irun);
1063     fChain->Add(filename.Data());
1064     fNruns++;    
1065   }
1066   
1067   AliInfo(Form("Number of runs being analyzed %i",fNruns));
1068 }
1069 //-----------------------------------------------------------------------------
1070 Int_t AliTOFcalib::Calibrate(Int_t ichmin, Int_t ichmax, Option_t *optionSave, Option_t *optionFit){
1071
1072   // calibrating summing more than one channels
1073   // computing calibration parameters
1074   // Returning codes:
1075   // 0 -> everything was ok
1076   // 1 -> no tree for calibration found
1077   // 2 -> not enough statistics to perform calibration
1078   // 3 -> problems with arrays
1079   
1080   TH1::AddDirectory(0);
1081
1082   AliInfo(Form("*** Calibrating Histograms %s, summing more channels, from channel %i, to channel %i, storing Calib Pars in channel %i", GetName(),ichmin,ichmax,ichmin)) ; 
1083   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1084   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1085
1086   Float_t p[CHENTRIESSMALL];
1087   Int_t nentries;
1088   //fTree->SetBranchAddress("nentries",&nentries);
1089   //fTree->SetBranchAddress("TOFentries",p);
1090   fChain->SetBranchAddress("nentries",&nentries);
1091   fChain->SetBranchAddress("TOFentries",p);
1092
1093   Float_t ntracksTotalmean =0;
1094   for (Int_t i=ichmin; i<ichmax; i++){
1095     Int_t ientry = -1;
1096     for (Int_t irun=0;irun<fNruns;irun++){
1097       ientry = i+irun*fNChannels;
1098       //fTree->GetEntry(ientry);
1099       fChain->GetEntry(ientry);
1100       Int_t ntracksRun=nentries/3;
1101       ntracksTotalmean+=ntracksRun;
1102     }
1103   }
1104   
1105   if (ntracksTotalmean < MEANENTRIES) {
1106     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotalmean));
1107     return 2;
1108   }
1109
1110   //filling ToT and Time arrays
1111
1112   Int_t nbinToT = 100;  // ToT bin width in Profile = 48.8 ps 
1113   Float_t minToT = 0;   // ns
1114   Float_t maxToT = 4.88;  // ns
1115
1116   TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1117   TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1118   Int_t ntracksTotal = 0;
1119   Int_t ntracksRun = 0;
1120   Double_t binsProfile[101]; // sized larger than necessary, the correct 
1121                              // dim being set in the booking of the profile
1122   Int_t nusefulbins=0;
1123   Float_t meantime=0;
1124   for (Int_t i = ichmin;i<ichmax;i++){
1125     Int_t ientry = -1;
1126     for (Int_t irun=0;irun<fNruns;irun++){
1127       ientry = i+irun*fNChannels;
1128       //fTree->GetEntry(ientry);
1129       fChain->GetEntry(ientry);
1130       ntracksTotal+=nentries/3;
1131       ntracksRun=nentries/3;
1132       AliDebug(2,Form("run %i, channel %i, nentries = %i, ntracks = %i",irun,i,nentries, ntracksRun));
1133       for (Int_t j=0;j<ntracksRun;j++){
1134         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1135         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1136         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1137         Float_t tot = p[idxexToT];
1138         hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1139         meantime+=p[idxexTime]-p[idxexExTime];
1140         hToT->Fill(tot);
1141       }
1142     }
1143   }
1144   nusefulbins = FindBins(hToT,&binsProfile[0]);
1145   meantime/=ntracksTotal;
1146   AliDebug(2, Form("meantime = %f",meantime));
1147   
1148   for (Int_t j=1;j<=nusefulbins;j++) {
1149     AliDebug(2,Form(" summing channels from %i to %i, nusefulbins = %i, bin %i = %f",ichmin,ichmax,nusefulbins,j,binsProfile[j])); 
1150   }
1151
1152   TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1153   TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1154
1155   for (Int_t irun=0;irun<fNruns;irun++){
1156     Int_t ientry = -1;
1157     for (Int_t i=ichmin; i<ichmax; i++){
1158       ientry = i+irun*fNChannels;
1159       //fTree->GetEntry(ientry);
1160       fChain->GetEntry(ientry);
1161       ntracksRun=nentries/3;
1162       for (Int_t j=0;j<ntracksRun;j++){
1163         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1164         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1165         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1166         Float_t tot = p[idxexToT];
1167         Float_t time = p[idxexTime]-p[idxexExTime];
1168         AliDebug (2, Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1169         hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1170         htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1171       }
1172     }
1173   }
1174
1175   hSlewingProf->Fit("pol5",optionFit,"",0,4);
1176   TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1177   Float_t par[6];    
1178   for(Int_t kk=0;kk<6;kk++){
1179     par[kk]=calibfunc->GetParameter(kk);
1180     AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1181   }
1182
1183   if(strstr(optionSave,"save")){
1184     TFile * fileProf = new TFile("TOFCalibSave.root","recreate");
1185     fileProf->cd(); 
1186     TString profName=Form("Profile%06i_%06i",ichmin,ichmax);
1187     TString timeTotName=Form("TimeTot%06i_%06i",ichmin,ichmax);
1188     TString totName=Form("Tot%06i_%06i",ichmin,ichmax);
1189     TString deltaName=Form("Delta%06i_%06i",ichmin,ichmax);
1190     hSlewingProf->Write(profName);
1191     htimetot->Write(timeTotName);
1192     hToT->Write(totName);
1193     hdeltaTime->Write(deltaName);
1194     fileProf->Close();
1195     delete fileProf;
1196     fileProf=0x0;
1197   }
1198
1199   delete hToT;
1200   hToT=0x0;
1201   delete hSlewingProf;
1202   hSlewingProf=0x0;
1203   delete htimetot;
1204   htimetot=0x0;
1205   delete hdeltaTime;
1206   hdeltaTime=0x0;
1207
1208   AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(ichmin);
1209   calChannel->SetSlewPar(par);
1210   WriteParOfflineOnCDB("TOF/Calib","valid");
1211   return 0;
1212 }
1213 //----------------------------------------------------------------------------
1214 Int_t AliTOFcalib::Calibrate(Int_t i, Option_t *optionSave, Option_t *optionFit){
1215
1216   // computing calibration parameters for channel i
1217   // Returning codes:
1218   // 0 -> everything was ok
1219   // 1 -> no tree for calibration found
1220   // 2 -> not enough statistics to perform calibration
1221   // 3 -> problems with arrays
1222
1223   TH1::AddDirectory(0);
1224   
1225   AliInfo(Form("*** Calibrating Histograms (one channel) %s", GetName())) ; 
1226   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1227   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1228
1229   Float_t p[MAXCHENTRIESSMALL];
1230   Int_t nentries;
1231   //fTree->SetBranchAddress("nentries",&nentries);
1232   //fTree->SetBranchAddress("TOFentries",p);
1233   fChain->SetBranchAddress("nentries",&nentries);
1234   fChain->SetBranchAddress("TOFentries",p);
1235
1236   Float_t ntracksTotal =0;
1237   for (Int_t irun=0;irun<fNruns;irun++){
1238     Int_t ientry = -1;
1239     ientry = i+irun*fNChannels;
1240     //fTree->GetEntry(ientry);
1241     fChain->GetEntry(ientry);
1242     ntracksTotal+=nentries/3;    
1243   }
1244   
1245   if (ntracksTotal < MEANENTRIES) {  
1246     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotal));
1247     return 2;
1248   }
1249
1250   //filling ToT and Time arrays
1251
1252   Int_t nbinToT = 100;  // ToT bin width in Profile = 48.8 ps 
1253   Float_t minToT = 0;   // ns
1254   Float_t maxToT = 4.88;  // ns
1255
1256   TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1257   TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1258   Int_t ntracksRun = 0;
1259   Double_t binsProfile[101]; // sized larger than necessary, the correct 
1260                              // dim being set in the booking of the profile
1261   Int_t nusefulbins=0;
1262   Float_t meantime=0;
1263   for (Int_t irun=0;irun<fNruns;irun++){
1264     Int_t ientry = -1;
1265     ientry = i+irun*fNChannels;
1266     //fTree->GetEntry(ientry);
1267     fChain->GetEntry(ientry);
1268     ntracksRun=nentries/3;
1269     AliDebug(2,Form("run %i, channel %i, nentries = %i, ntracksRun = %i",irun, i ,nentries, ntracksRun));
1270     for (Int_t j=0;j<ntracksRun;j++){
1271       Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1272       Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1273       Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1274       Float_t tot = p[idxexToT];
1275       meantime+=p[idxexTime]-p[idxexExTime];
1276       hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1277       hToT->Fill(tot);
1278     }
1279   }
1280
1281   nusefulbins = FindBins(hToT,&binsProfile[0]);
1282   meantime/=ntracksTotal;
1283   AliDebug(2,Form("meantime = %f",meantime));
1284   
1285   for (Int_t j=1;j<=nusefulbins;j++) {
1286     AliDebug(2,Form(" channel %i, nusefulbins = %i, bin %i = %f",i,nusefulbins,j,binsProfile[j])); 
1287   }
1288
1289   TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1290   TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1291   for (Int_t irun=0;irun<fNruns;irun++){
1292     Int_t ientry = -1;
1293     ientry = i+irun*fNChannels;
1294     //fTree->GetEntry(ientry);
1295     fChain->GetEntry(ientry);
1296     ntracksRun=nentries/3;
1297     for (Int_t j=0;j<ntracksRun;j++){
1298       Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1299       Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1300       Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1301       Float_t tot = p[idxexToT];
1302       Float_t time = p[idxexTime]-p[idxexExTime];
1303       AliDebug (2,Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1304       hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1305       htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1306     }
1307   }
1308
1309   hSlewingProf->Fit("pol5",optionFit,"",0,4);
1310   TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1311   Float_t par[6];    
1312   for(Int_t kk=0;kk<6;kk++){
1313     par[kk]=calibfunc->GetParameter(kk);
1314     AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1315   }
1316
1317
1318   if(strstr(optionSave,"save")){
1319     TFile * fileProf = new TFile("TOFCalibSave.root","recreate");
1320     fileProf->cd();   
1321     TString profName=Form("Profile%06i",i);
1322     TString timeTotName=Form("TimeTot%06i",i);
1323     TString totName=Form("Tot%06i",i);
1324     TString deltaName=Form("Delta%06i",i);
1325     hSlewingProf->Write(profName);
1326     htimetot->Write(timeTotName);
1327     hToT->Write(totName);
1328     hdeltaTime->Write(deltaName);
1329     fileProf->Close();
1330     delete fileProf;
1331     fileProf=0x0;
1332   }
1333
1334   delete hToT;
1335   hToT=0x0; 
1336   delete hSlewingProf;
1337   hSlewingProf=0x0;
1338   delete htimetot;
1339   htimetot=0x0;
1340   delete hdeltaTime;
1341   hdeltaTime=0x0;
1342
1343   AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(i);
1344   calChannel->SetSlewPar(par);
1345   WriteParOfflineOnCDB("TOF/Calib","valid");
1346   return 0;
1347 }
1348 //----------------------------------------------------------------------------
1349 Int_t AliTOFcalib::Calibrate(Int_t nch, Int_t *ch, Option_t *optionSave, Option_t *optionFit){
1350
1351   // calibrating an array of channels
1352   // computing calibration parameters
1353   // Returning codes:
1354   // 0 -> everything was ok
1355   // 1 -> no tree for calibration found
1356   // 2 -> not enough statistics to perform calibration
1357   // 3 -> problems with arrays
1358   
1359   TH1::AddDirectory(0);
1360
1361   AliInfo(Form("*** Calibrating Histograms %s, number of channels = %i", GetName(),nch)) ; 
1362   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1363   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1364   for (Int_t ich=0; ich<nch; ich++){
1365     Int_t i = ch[ich];
1366     AliInfo(Form("Calibrating channel = %i",i )) ; 
1367   }
1368   Float_t p[MAXCHENTRIESSMALL];
1369   Int_t nentries;
1370   //fTree->SetBranchAddress("nentries",&nentries);
1371   //fTree->SetBranchAddress("TOFentries",p);
1372   fChain->SetBranchAddress("nentries",&nentries);
1373   fChain->SetBranchAddress("TOFentries",p);
1374
1375   Float_t ntracksTotalmean =0;
1376   for (Int_t ich=0; ich<nch; ich++){
1377     Int_t ientry = -1;
1378       Int_t i = ch[ich];
1379       for (Int_t irun=0;irun<fNruns;irun++){
1380       ientry = i+irun*fNChannels;
1381       //fTree->GetEntry(ientry);
1382       fChain->GetEntry(ientry);
1383       ntracksTotalmean+=nentries/3;
1384     }
1385   }
1386
1387   ntracksTotalmean/=nch;
1388   if (ntracksTotalmean < MEANENTRIES) { 
1389     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotalmean));
1390     return 2;
1391   }
1392
1393   //filling ToT and Time arrays
1394
1395   Int_t nbinToT = 100;  // ToT bin width in Profile = 48.8 ps 
1396   Float_t minToT = 0;   // ns
1397   Float_t maxToT = 4.88;  // ns
1398   TFile * fileProf=0x0;
1399   if(strstr(optionSave,"save")){
1400     fileProf = new TFile("TOFCalibSave.root","recreate");
1401   }
1402   for (Int_t ich=0; ich<nch; ich++) {
1403     TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1404     TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1405     Double_t binsProfile[101]; // sized larger than necessary, the correct 
1406     // dim being set in the booking of the profile
1407     TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1408     Int_t ntracksTotal = 0;
1409     Int_t ntracksRun = 0;
1410     Int_t nusefulbins=0;
1411     Float_t meantime=0;
1412     Int_t i=-1;
1413     for (Int_t irun=0;irun<fNruns;irun++){
1414       i = ch[ich]+irun*fNChannels;
1415       AliDebug(2,Form("Calibrating channel %i",i));
1416       //fTree->GetEntry(i);
1417       fChain->GetEntry(i);
1418       ntracksTotal+=nentries/3;
1419     }
1420     if (ntracksTotal < MEANENTRIES) {
1421       AliInfo(Form(" Too small mean number of entires in channel %i (number of tracks = %d), not calibrating channel and continuing.....",i,ntracksTotal));
1422       continue;
1423     }
1424   
1425     for (Int_t irun=0;irun<fNruns;irun++){
1426       i = ch[ich]+irun*fNChannels;
1427       //fTree->GetEntry(i);
1428       fChain->GetEntry(i);
1429       ntracksRun=nentries/3;
1430       for (Int_t j=0;j<ntracksRun;j++){
1431         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1432         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1433         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1434         Float_t tot = p[idxexToT];
1435         hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1436         meantime+=p[idxexTime]-p[idxexExTime];
1437         hToT->Fill(tot);
1438       }
1439     }
1440
1441     nusefulbins = FindBins(hToT,&binsProfile[0]);
1442     meantime/=ntracksTotal;
1443     for (Int_t j=1;j<=nusefulbins;j++) {
1444       AliDebug(2,Form(" channel %i, nusefulbins = %i, bin %i = %f",i,nusefulbins,j,binsProfile[j])); 
1445     }
1446
1447     TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1448     for (Int_t irun=0;irun<fNruns;irun++){
1449       i = ch[ich]+irun*fNChannels;
1450       //fTree->GetEntry(i);
1451       fChain->GetEntry(i);
1452       ntracksRun=nentries/3;
1453       for (Int_t j=0;j<ntracksRun;j++){
1454         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1455         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1456         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1457         Float_t tot = p[idxexToT];
1458         Float_t time = p[idxexTime]-p[idxexExTime];
1459         AliDebug(2,Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1460         hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1461         htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1462       }
1463     }
1464     
1465     hSlewingProf->Fit("pol5",optionFit,"",1,4);
1466     TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1467     Float_t par[6];    
1468     for(Int_t kk=0;kk<6;kk++){
1469       par[kk]=calibfunc->GetParameter(kk);
1470       AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1471     }
1472     
1473     if(strstr(optionSave,"save") && fileProf){
1474       TString profName=Form("Profile%06i",i);
1475       TString timeTotName=Form("TimeTot%06i",i);
1476       TString totName=Form("Tot%06i",i);
1477       TString deltaName=Form("Delta%06i",i);
1478       fileProf->cd();
1479       hSlewingProf->Write(profName);
1480       htimetot->Write(timeTotName);
1481       hToT->Write(totName);
1482       hdeltaTime->Write(deltaName);
1483     }
1484
1485     AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(i);
1486     calChannel->SetSlewPar(par);
1487     delete hToT;
1488     hToT=0x0;
1489     delete hSlewingProf;
1490     hSlewingProf=0x0;
1491     delete htimetot;
1492     htimetot=0x0;
1493     delete hdeltaTime;
1494     hdeltaTime=0x0;
1495   }
1496
1497   if(strstr(optionSave,"save") && fileProf){
1498     fileProf->Close();
1499     delete fileProf;
1500     fileProf=0x0;
1501   }
1502   WriteParOfflineOnCDB("TOF/Calib","valid");
1503
1504   return 0;
1505 }
1506 //----------------------------------------------------------------------------
1507 Int_t AliTOFcalib::CalibrateFromProfile(Int_t ich, Option_t *optionSave, Option_t *optionFit){
1508
1509   // computing calibration parameters using the old profiling algo
1510   // Returning codes:
1511   // 0 -> everything was ok
1512   // 1 -> no tree for calibration found
1513   // 2 -> not enough statistics to perform calibration
1514   // 3 -> problems with arrays
1515
1516   TH1::AddDirectory(0);
1517
1518   AliInfo(Form("*** Calibrating Histograms From Profile %s", GetName())) ; 
1519   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1520   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1521   Float_t p[MAXCHENTRIESSMALL];
1522   Int_t nentries;
1523   Int_t ntracksTotal=0;
1524   //fTree->SetBranchAddress("nentries",&nentries);
1525   //fTree->SetBranchAddress("TOFentries",p);
1526   fChain->SetBranchAddress("nentries",&nentries);
1527   fChain->SetBranchAddress("TOFentries",p);
1528
1529   for (Int_t irun=0;irun<fNruns;irun++){
1530     Int_t i = ich+irun*fNChannels;
1531     //fTree->GetEntry(i);
1532     fChain->GetEntry(i);
1533     ntracksTotal+=nentries/3;
1534   }
1535
1536   if (ntracksTotal < MEANENTRIES) {  
1537     AliInfo(Form(" Too small mean number of entires per channel (mean number = %d) not calibrating and exiting.....",ntracksTotal));
1538     return 2;
1539   }
1540
1541   TH1F * hProf = Profile(ich);
1542   hProf->Fit("pol5",optionFit,"",0,4);
1543   TF1 * calibfunc = (TF1*)hProf->GetFunction("pol5");
1544   Float_t par[6];    
1545   for(Int_t kk=0;kk<6;kk++){
1546     par[kk]=calibfunc->GetParameter(kk);
1547     AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1548   }
1549
1550   if(strstr(optionSave,"save")){
1551     TFile * fileProf = new TFile("TOFCalibSave.root","recreate");
1552     fileProf->cd(); 
1553     TString profName=Form("Profile%06i",ich);
1554     hProf->Write(profName);
1555     fileProf->Close();
1556     delete fileProf;
1557     fileProf=0x0;
1558   }
1559
1560   delete hProf;
1561   hProf=0x0;
1562   AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(ich);
1563   calChannel->SetSlewPar(par);
1564   WriteParOfflineOnCDB("TOF/Calib","valid");
1565   return 0;
1566 }
1567 //----------------------------------------------------------------------------
1568 Int_t AliTOFcalib::Calibrate(Option_t *optionSave, Option_t *optionFit){
1569
1570   // calibrating the whole TOF
1571   // computing calibration parameters
1572   // Returning codes:
1573   // 0 -> everything was ok
1574   // 1 -> no tree for calibration found
1575   // 2 -> not enough statistics to perform calibration
1576   // 3 -> problems with arrays
1577
1578   TH1::AddDirectory(0);
1579
1580   AliInfo(Form("*** Calibrating Histograms %s, all channels", GetName())) ; 
1581   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1582   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1583
1584   TFile * fileProf=0x0;
1585   if(strstr(optionSave,"save")){
1586     fileProf = new TFile("TOFCalibSave.root","recreate");
1587   }
1588
1589   Float_t p[MAXCHENTRIESSMALL];
1590   Int_t nentries;
1591   //fTree->SetBranchAddress("nentries",&nentries);
1592   //fTree->SetBranchAddress("TOFentries",p);
1593   fChain->SetBranchAddress("nentries",&nentries);
1594   fChain->SetBranchAddress("TOFentries",p);
1595
1596   Float_t ntracksTotalmean =0;
1597   for (Int_t ii=0; ii<fNChannels; ii++){
1598     for (Int_t irun=0;irun<fNruns;irun++){
1599       Int_t i = ii+irun*fNChannels;
1600       //fTree->GetEntry(i);
1601       fChain->GetEntry(i);
1602       ntracksTotalmean+=nentries/3;
1603     }
1604   }
1605
1606   ntracksTotalmean/=fNChannels;
1607   if (ntracksTotalmean < MEANENTRIES) {
1608     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotalmean));
1609     return 2;
1610   }
1611
1612   //filling ToT and Time arrays
1613
1614   Int_t nbinToT = 100;  // ToT bin width in Profile = 50.0 ps 
1615   Float_t minToT = 0;   // ns
1616   Float_t maxToT = 4.88;// ns
1617   for (Int_t ii=0; ii<fNChannels; ii++) {
1618     TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1619     TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1620     TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1621     if (ii%1000 == 0) AliDebug(1,Form("Calibrating channel %i ",ii));
1622     //Int_t i = 3;
1623     Int_t nusefulbins=0;
1624     Double_t binsProfile[101]; // sized larger than necessary, the correct 
1625                               // dim being set in the booking of the profile
1626     Int_t ntracksRun = 0;
1627     Int_t ntracksTotal = 0;
1628     for (Int_t irun=0;irun<fNruns;irun++){
1629       Int_t i = ii+irun*fNChannels;
1630       //fTree->GetEntry(i);
1631       fChain->GetEntry(i);
1632       ntracksTotal+=nentries/3;
1633     }
1634     if (ntracksTotal < MEANENTRIES) {
1635       AliInfo(Form(" Too small mean number of entires in channel %i (number of tracks = %d), not calibrating channel and continuing.....",ii,ntracksTotal));
1636       continue;
1637     }
1638     Float_t meantime=0;
1639     for (Int_t irun=0;irun<fNruns;irun++){
1640       Int_t i = ii+irun*fNChannels;
1641       //fTree->GetEntry(i);
1642       fChain->GetEntry(i);
1643       ntracksRun=nentries/3;
1644       for (Int_t j=0;j<ntracksRun;j++){
1645         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1646         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1647         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1648         Float_t tot = p[idxexToT];
1649         hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1650         meantime+=p[idxexTime]-p[idxexExTime];
1651         hToT->Fill(tot);
1652       }
1653     }
1654     nusefulbins = FindBins(hToT,&binsProfile[0]);
1655     meantime/=ntracksTotal;
1656     for (Int_t j=0;j<nusefulbins;j++) {
1657       AliDebug(2,Form(" channel %i, usefulbin = %i, low edge = %f",ii,j,binsProfile[j])); 
1658     }
1659     TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1660     for (Int_t irun=0;irun<fNruns;irun++){
1661       Int_t i = ii+irun*fNChannels;
1662       //fTree->GetEntry(i);
1663       fChain->GetEntry(i);
1664       ntracksRun=nentries/3;
1665       for (Int_t j=0;j<ntracksRun;j++){
1666         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1667         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1668         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1669         Float_t tot = p[idxexToT];
1670         Float_t time = p[idxexTime]-p[idxexExTime];
1671         AliDebug (2,Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1672         hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1673         htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1674       }
1675     }
1676     hSlewingProf->Fit("pol5",optionFit,"",1,4);
1677     TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1678     Float_t par[6];    
1679     for(Int_t kk=0;kk<6;kk++){
1680       par[kk]=calibfunc->GetParameter(kk);
1681       AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1682     }
1683
1684     if(strstr(optionSave,"save") && fileProf){
1685       TString profName=Form("Profile%06i",ii);
1686       TString timeTotName=Form("TimeTot%06i",ii);
1687       TString totName=Form("Tot%06i",ii);
1688       TString deltaName=Form("Delta%06i",ii);
1689       fileProf->cd();
1690       hSlewingProf->Write(profName);
1691       htimetot->Write(timeTotName);
1692       hToT->Write(totName);
1693       hdeltaTime->Write(deltaName);
1694     }
1695     AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(ii);
1696     calChannel->SetSlewPar(par);
1697
1698     delete hToT;
1699     hToT=0x0;
1700     delete hSlewingProf;
1701     hSlewingProf=0x0;
1702     delete htimetot;
1703     htimetot=0x0;
1704     delete hdeltaTime;
1705     hdeltaTime=0x0;
1706   }
1707
1708   if(strstr(optionSave,"save")){
1709     fileProf->Close();
1710     delete fileProf;
1711     fileProf=0x0;
1712   }
1713   WriteParOfflineOnCDB("TOF/Calib","valid");
1714   return 0;
1715 }
1716
1717 //-----------------------------------------------------------------------
1718 TH1F* AliTOFcalib::Profile(Int_t ich)
1719 {
1720   // profiling algo
1721
1722   Float_t p[MAXCHENTRIESSMALL];
1723   Int_t nentries;
1724   //fTree->SetBranchAddress("nentries",&nentries);
1725   //fTree->SetBranchAddress("TOFentries",p);
1726   fChain->SetBranchAddress("nentries",&nentries);
1727   fChain->SetBranchAddress("TOFentries",p);
1728
1729   //Prepare histograms for Slewing Correction
1730   const Int_t knbinToT = 100;
1731   Int_t nbinTime = 200;
1732   Float_t minTime = -5.5; //ns
1733   Float_t maxTime = 5.5; //ns
1734   Float_t minToT = 0; //ns
1735   Float_t maxToT = 5.; //ns
1736   Float_t deltaToT = (maxToT-minToT)/knbinToT;
1737   Double_t mTime[knbinToT+1],mToT[knbinToT+1],meanTime[knbinToT+1], meanTime2[knbinToT+1],vToT[knbinToT+1], vToT2[knbinToT+1],meanToT[knbinToT+1],meanToT2[knbinToT+1],vTime[knbinToT+1],vTime2[knbinToT+1],xlow[knbinToT+1],sigmaTime[knbinToT+1];
1738   Int_t n[knbinToT+1], nentrx[knbinToT+1];
1739   Double_t sigmaToT[knbinToT+1];
1740   for (Int_t i = 0; i < knbinToT+1 ; i++){
1741     mTime[i]=0;
1742     mToT[i]=0;
1743     n[i]=0;
1744     meanTime[i]=0;
1745     meanTime2[i]=0;
1746     vToT[i]=0;
1747     vToT2[i]=0;
1748     meanToT[i]=0;
1749     meanToT2[i]=0;
1750     vTime[i]=0;
1751     vTime2[i]=0;
1752     xlow[i]=0;
1753     sigmaTime[i]=0;
1754     sigmaToT[i]=0;
1755     n[i]=0;
1756     nentrx[i]=0;
1757   }
1758   TH2F* hSlewing = new TH2F("hSlewing", "hSlewing", knbinToT, minToT, maxToT, nbinTime, minTime, maxTime);
1759   Int_t ntracksRun = 0;
1760   TH1F *histo = new TH1F("histo", "1D Time vs ToT", knbinToT, minToT, maxToT);
1761   for (Int_t irun=0;irun<fNruns;irun++){
1762     Int_t i = ich+irun*fNChannels;
1763     //fTree->GetEntry(i);
1764     fChain->GetEntry(i);
1765     ntracksRun=nentries/3;
1766     for (Int_t j=0;j<ntracksRun;j++){
1767       Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1768       Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1769       Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1770       Float_t tot = p[idxexToT];
1771       Float_t time = p[idxexTime]-p[idxexExTime];
1772       Int_t nx = (Int_t)((tot-minToT)/deltaToT)+1;
1773       if ((tot != 0) && ( time!= 0)){
1774         vTime[nx]+=time;
1775         vTime2[nx]+=time*time;
1776         vToT[nx]+=tot;
1777         vToT2[nx]+=tot*tot;
1778         nentrx[nx]++;
1779         hSlewing->Fill(tot,time);
1780       }
1781     }
1782   }
1783   Int_t nbinsToT=hSlewing->GetNbinsX();
1784   if (nbinsToT != knbinToT) {
1785     AliError("Profile :: incompatible numbers of bins");
1786     return 0x0;
1787   }
1788   
1789   Int_t usefulBins=0;
1790   for (Int_t i=1;i<=nbinsToT;i++){
1791     if (nentrx[i]!=0){
1792       n[usefulBins]+=nentrx[i];
1793       if (n[usefulBins]==0 && i == nbinsToT) {
1794         break;
1795       }
1796       meanTime[usefulBins]+=vTime[i];
1797       meanTime2[usefulBins]+=vTime2[i];
1798       meanToT[usefulBins]+=vToT[i];
1799       meanToT2[usefulBins]+=vToT2[i];
1800       if (n[usefulBins]<10 && i!=nbinsToT) continue; 
1801       mTime[usefulBins]=meanTime[usefulBins]/n[usefulBins];
1802       mToT[usefulBins]=meanToT[usefulBins]/n[usefulBins];
1803       sigmaTime[usefulBins]=TMath::Sqrt(1./n[usefulBins]/n[usefulBins]
1804                             *(meanTime2[usefulBins]-meanTime[usefulBins]
1805                             *meanTime[usefulBins]/n[usefulBins]));
1806       if ((1./n[usefulBins]/n[usefulBins]
1807            *(meanToT2[usefulBins]-meanToT[usefulBins]
1808              *meanToT[usefulBins]/n[usefulBins]))< 0) {
1809         AliError(" too small radical" );
1810         sigmaToT[usefulBins]=0;
1811       }
1812       else{       
1813         sigmaToT[usefulBins]=TMath::Sqrt(1./n[usefulBins]/n[usefulBins]
1814                              *(meanToT2[usefulBins]-meanToT[usefulBins]
1815                              *meanToT[usefulBins]/n[usefulBins]));
1816       }
1817       usefulBins++;
1818     }
1819   }
1820   for (Int_t i=0;i<usefulBins;i++){
1821     Int_t binN = (Int_t)((mToT[i]-minToT)/deltaToT)+1;
1822     histo->Fill(mToT[i],mTime[i]);
1823     histo->SetBinError(binN,sigmaTime[i]);
1824   } 
1825   delete hSlewing;
1826   hSlewing=0x0;
1827
1828   return histo;
1829 }
1830 //----------------------------------------------------------------------------
1831 Int_t AliTOFcalib::FindBins(TH1F* h, Double_t *binsProfile) const{
1832
1833   // to determine the bins for ToT histo
1834
1835   Int_t cont = 0;
1836   Int_t startBin = 1;
1837   Int_t nbin = h->GetNbinsX();
1838   Int_t nentries = (Int_t)h->GetEntries();
1839   Float_t max = h->GetBinLowEdge(nbin);
1840   Int_t nusefulbins=0;
1841   Int_t maxcont=0;
1842   // setting maxvalue of entries per bin
1843   if (nentries <= 60) maxcont = 2;
1844   else  if (nentries <= 100) maxcont = 5;
1845   else  if (nentries <= 500) maxcont = 10;
1846   else  maxcont = 20;
1847   for (Int_t j=1;j<=nbin;j++) {
1848     cont += (Int_t)h->GetBinContent(j);
1849     if (j<nbin){
1850       if (cont>=maxcont){
1851         nusefulbins++;
1852         binsProfile[nusefulbins-1]=h->GetBinLowEdge(startBin);
1853         cont=0;
1854         startBin=j+1;
1855         continue;
1856       }
1857     }
1858     else{
1859       if (cont>=maxcont){
1860         nusefulbins++;
1861         binsProfile[nusefulbins-1]=h->GetBinLowEdge(startBin);
1862         binsProfile[nusefulbins]=max;
1863       }
1864       else {
1865         binsProfile[nusefulbins]=h->GetBinLowEdge(startBin);
1866       }
1867     }
1868   }
1869   return nusefulbins;
1870 }
1871
1872
1873 //----------------------------------------------------------------------------
1874
1875 void
1876 AliTOFcalib::CreateDeltaBCOffset()
1877 {
1878   /*
1879    * create deltaBC offset
1880    */
1881
1882   if (fDeltaBCOffset) {
1883     AliWarning("DeltaBCOffset object already defined, cannot create a new one");
1884     return;
1885   }
1886   fDeltaBCOffset = new AliTOFDeltaBCOffset();
1887 }
1888   
1889 //----------------------------------------------------------------------------
1890
1891 void
1892 AliTOFcalib::CreateCTPLatency()
1893 {
1894   /*
1895    * create CTP latency
1896    */
1897
1898   if (fCTPLatency) {
1899     AliWarning("CTPLatency object already defined, cannot create a new one");
1900     return;
1901   }
1902   fCTPLatency = new AliTOFCTPLatency();
1903 }
1904   
1905 //----------------------------------------------------------------------------
1906
1907 void
1908 AliTOFcalib::CreateT0Fill()
1909 {
1910   /*
1911    * create event-time
1912    */
1913
1914   if (fT0Fill) {
1915     AliWarning("T0Fill object already defined, cannot create a new one");
1916     return;
1917   }
1918   fT0Fill = new AliTOFT0Fill();
1919 }
1920   
1921 //----------------------------------------------------------------------------
1922
1923 void
1924 AliTOFcalib::CreateRunParams()
1925 {
1926   /*
1927    * create run params
1928    */
1929
1930   if (fRunParams) {
1931     AliWarning("RunParams object already defined, cannot create a new one");
1932     return;
1933   }
1934   fRunParams = new AliTOFRunParams();
1935 }
1936   
1937 //----------------------------------------------------------------------------
1938
1939 void
1940 AliTOFcalib::WriteDeltaBCOffsetOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
1941 {
1942   /*
1943    * deltaBC offset on CDB 
1944    */
1945   
1946   if (!fDeltaBCOffset) return;
1947   AliCDBId id(Form("%s/DeltaBCOffset", sel), minrun, maxrun);
1948   AliCDBMetaData *md = new AliCDBMetaData();
1949   md->SetResponsible("Roberto Preghenella");
1950   AliCDBManager *man = AliCDBManager::Instance();
1951   man->Put(fDeltaBCOffset, id, md);
1952   AliDebug(2,Form("DeltaBCOffset written on CDB with run range [%i, %i] ",minrun ,maxrun));
1953   delete md;
1954 }
1955
1956 //----------------------------------------------------------------------------
1957
1958 void
1959 AliTOFcalib::WriteCTPLatencyOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
1960 {
1961   /*
1962    * write CTP latency on CDB 
1963    */
1964   
1965   if (!fCTPLatency) return;
1966   AliCDBId id(Form("%s/CTPLatency", sel), minrun, maxrun);
1967   AliCDBMetaData *md = new AliCDBMetaData();
1968   md->SetResponsible("Roberto Preghenella");
1969   AliCDBManager *man = AliCDBManager::Instance();
1970   man->Put(fCTPLatency, id, md);
1971   AliDebug(2,Form("CTPLatency written on CDB with run range [%i, %i] ",minrun ,maxrun));
1972   delete md;
1973 }
1974
1975 //----------------------------------------------------------------------------
1976
1977 void
1978 AliTOFcalib::WriteT0FillOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
1979 {
1980   /*
1981    * write event-time on CDB 
1982    */
1983   
1984   if (!fT0Fill) return;
1985   AliCDBId id(Form("%s/T0Fill", sel), minrun, maxrun);
1986   AliCDBMetaData *md = new AliCDBMetaData();
1987   md->SetResponsible("Roberto Preghenella");
1988   AliCDBManager *man = AliCDBManager::Instance();
1989   man->Put(fT0Fill, id, md);
1990   AliDebug(2,Form("T0Fill written on CDB with run range [%i, %i] ",minrun ,maxrun));
1991   delete md;
1992 }
1993
1994 //----------------------------------------------------------------------------
1995
1996 void
1997 AliTOFcalib::WriteRunParamsOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
1998 {
1999   /*
2000    * write run params on CDB 
2001    */
2002   
2003   if (!fRunParams) return;
2004   AliCDBId id(Form("%s/RunParams", sel), minrun, maxrun);
2005   AliCDBMetaData *md = new AliCDBMetaData();
2006   md->SetResponsible("Roberto Preghenella");
2007   AliCDBManager *man = AliCDBManager::Instance();
2008   man->Put(fRunParams, id, md);
2009   AliDebug(2,Form("RunParams written on CDB with run range [%i, %i] ",minrun ,maxrun));
2010   delete md;
2011 }
2012
2013 //----------------------------------------------------------------------------
2014
2015 void
2016 AliTOFcalib::WriteReadoutEfficiencyOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
2017 {
2018   /*
2019    * write readout efficiency on CDB 
2020    */
2021   
2022   if (!fReadoutEfficiency) return;
2023   AliCDBId id(Form("%s/ReadoutEfficiency", sel), minrun, maxrun);
2024   AliCDBMetaData *md = new AliCDBMetaData();
2025   md->SetResponsible("Roberto Preghenella");
2026   AliCDBManager *man = AliCDBManager::Instance();
2027   man->Put(fReadoutEfficiency, id, md);
2028   AliDebug(2,Form("ReadoutEfficiency written on CDB with run range [%i, %i] ",minrun ,maxrun));
2029   delete md;
2030 }
2031
2032 //----------------------------------------------------------------------------
2033
2034 Bool_t
2035 AliTOFcalib::ReadDeltaBCOffsetFromCDB(const Char_t *sel , Int_t nrun)
2036 {
2037   /*
2038    * read deltaBC offset from CDB
2039    */
2040   
2041   AliCDBManager *man = AliCDBManager::Instance();
2042   AliCDBEntry *entry = man->Get(Form("%s/DeltaBCOffset", sel),nrun);
2043   if (!entry) { 
2044     AliFatal("No DeltaBCOffset entry found in CDB");
2045     exit(0);  
2046   }
2047   fDeltaBCOffset =(AliTOFDeltaBCOffset *)entry->GetObject();
2048   if(!fDeltaBCOffset){
2049     AliFatal("No DeltaBCOffset object found in CDB entry");
2050     exit(0);  
2051   }  
2052   return kTRUE; 
2053 }
2054
2055 //----------------------------------------------------------------------------
2056
2057 Bool_t
2058 AliTOFcalib::ReadCTPLatencyFromCDB(const Char_t *sel , Int_t nrun)
2059 {
2060   /*
2061    * read CTP latency from CDB
2062    */
2063   
2064   AliCDBManager *man = AliCDBManager::Instance();
2065   AliCDBEntry *entry = man->Get(Form("%s/CTPLatency", sel),nrun);
2066   if (!entry) { 
2067     AliFatal("No CTPLatency entry found in CDB");
2068     exit(0);  
2069   }
2070   fCTPLatency =(AliTOFCTPLatency *)entry->GetObject();
2071   if(!fCTPLatency){
2072     AliFatal("No CTPLatency object found in CDB entry");
2073     exit(0);  
2074   }  
2075   return kTRUE; 
2076 }
2077
2078 //----------------------------------------------------------------------------
2079
2080 Bool_t
2081 AliTOFcalib::ReadT0FillFromCDB(const Char_t *sel , Int_t nrun)
2082 {
2083   /*
2084    * read event-time from CDB
2085    */
2086   
2087   AliCDBManager *man = AliCDBManager::Instance();
2088   AliCDBEntry *entry = man->Get(Form("%s/T0Fill", sel),nrun);
2089   if (!entry) { 
2090     AliFatal("No T0Fill entry found in CDB");
2091     exit(0);  
2092   }
2093   fT0Fill =(AliTOFT0Fill *)entry->GetObject();
2094   if(!fT0Fill){
2095     AliFatal("No T0Fill object found in CDB entry");
2096     exit(0);  
2097   }  
2098   return kTRUE; 
2099 }
2100
2101 //----------------------------------------------------------------------------
2102
2103 Bool_t
2104 AliTOFcalib::ReadRunParamsFromCDB(const Char_t *sel , Int_t nrun)
2105 {
2106   /*
2107    * read run params from CDB
2108    */
2109   
2110   AliCDBManager *man = AliCDBManager::Instance();
2111   AliCDBEntry *entry = man->Get(Form("%s/RunParams", sel),nrun);
2112   if (!entry) { 
2113     AliFatal("No RunParams entry found in CDB");
2114     exit(0);  
2115   }
2116   fRunParams =(AliTOFRunParams *)entry->GetObject();
2117   if(!fRunParams){
2118     AliFatal("No RunParams object found in CDB entry");
2119     exit(0);  
2120   }  
2121   return kTRUE; 
2122 }
2123
2124 //----------------------------------------------------------------------------
2125
2126 Bool_t
2127 AliTOFcalib::ReadReadoutEfficiencyFromCDB(const Char_t *sel , Int_t nrun)
2128 {
2129   /*
2130    * read readout efficiency from CDB
2131    */
2132   
2133   AliCDBManager *man = AliCDBManager::Instance();
2134   AliCDBEntry *entry = man->Get(Form("%s/ReadoutEfficiency", sel),nrun);
2135   if (!entry) { 
2136     AliFatal("No ReadoutEfficiency entry found in CDB");
2137     exit(0);  
2138   }
2139   fReadoutEfficiency = (TH1F *)entry->GetObject();
2140   if(!fReadoutEfficiency){
2141     AliFatal("No ReadoutEfficiency object found in CDB entry");
2142     exit(0);  
2143   }  
2144   return kTRUE; 
2145 }
2146
2147 //----------------------------------------------------------------------------
2148
2149 Bool_t 
2150 AliTOFcalib::Init(Int_t run)
2151 {
2152   /*
2153    * init
2154    */
2155
2156   if (fInitFlag) {
2157     AliWarning("the class was already initialized, re-initialize it");
2158     fInitFlag = kFALSE;
2159   }
2160   
2161   /* read channel status array */
2162   if (!ReadParOnlineStatusFromCDB("TOF/Calib", run)) {
2163     AliError("cannot get \"Status\" object from OCDB");
2164     return kFALSE;
2165   }
2166   /* get par offline array */
2167   if (!ReadParOfflineFromCDB("TOF/Calib", run)) {
2168     AliError("cannot get \"ParOffline\" object from OCDB");
2169     return kFALSE;
2170   }
2171   /* get deltaBC offset obj */
2172   if (!ReadDeltaBCOffsetFromCDB("TOF/Calib", run)) {
2173     AliError("cannot get \"DeltaBCOffset\" object from OCDB");
2174     return kFALSE;
2175   }
2176   /* get CTP latency obj */
2177   if (!ReadCTPLatencyFromCDB("TOF/Calib", run)) {
2178     AliError("cannot get \"CTPLatency\" object from OCDB");
2179     return kFALSE;
2180   }
2181   /* get run params obj */
2182   if (!ReadRunParamsFromCDB("TOF/Calib", run)) {
2183     AliError("cannot get \"RunParams\" object from OCDB");
2184     return kFALSE;
2185   }
2186   /* get readout efficiency obj */
2187   if (!ReadReadoutEfficiencyFromCDB("TOF/Calib", run)) {
2188     AliError("cannot get \"ReadoutEfficiency\" object from OCDB");
2189     return kFALSE;
2190   }
2191   /* get response params */
2192   TFile *responseFile = TFile::Open("$ALICE_ROOT/TOF/data/AliTOFresponsePar.root");
2193   if (!responseFile || !responseFile->IsOpen()) {
2194     AliError("cannot open \"ResponseParams\" local file");
2195     return kFALSE;
2196   }
2197   fResponseParams = (AliTOFResponseParams *)responseFile->Get("ResponseParams");
2198   if (!fResponseParams) {
2199     AliError("cannot get \"ResponseParams\" object from local file");
2200     return kFALSE;
2201   }
2202   responseFile->Close();
2203
2204   /* all done */
2205   fInitFlag = kTRUE;
2206   return kTRUE;
2207
2208 }
2209
2210 //----------------------------------------------------------------------------
2211
2212 Double_t
2213 AliTOFcalib::GetTimeCorrection(Int_t index, Double_t tot, Int_t deltaBC, Int_t l0l1, UInt_t timestamp)
2214 {
2215   /*
2216    * get time correction
2217    */
2218
2219   if (!fInitFlag) {
2220     AliError("class not yet initialized. Initialize it before.");
2221     return 0.;
2222   }
2223
2224   /* get calibration params */
2225   AliTOFChannelOffline *parOffline = (AliTOFChannelOffline *)fTOFCalOffline->At(index);
2226   Int_t deltaBCOffset = fDeltaBCOffset->GetDeltaBCOffset();
2227   Float_t ctpLatency = fCTPLatency->GetCTPLatency();
2228   Float_t tdcLatencyWindow = fStatus->GetLatencyWindow(index) * 1.e3;
2229   Float_t timezero = fRunParams->EvalT0(timestamp);
2230   /* check whether to remove mean T0.
2231    * useful when one wants to compute mean T0 */
2232   if (!fRemoveMeanT0) timezero = 0.;
2233
2234   /* compute correction */
2235   Double_t corr = 0.;
2236   /* deltaBC correction */
2237   deltaBC = deltaBCOffset; /* inhibit deltaBC correction for the time being */
2238   corr += (deltaBC - deltaBCOffset) * AliTOFGeometry::BunchCrossingBinWidth();
2239   /* L0-L1 latency correction */
2240   corr -= l0l1 * AliTOFGeometry::BunchCrossingBinWidth();
2241   /* CTP latency correction */
2242   corr -= ctpLatency;
2243   /* TDC latency window correction */
2244   corr += tdcLatencyWindow;
2245   /* time-zero correction */
2246   corr += timezero;
2247   /* time calibration correction */
2248   if (tot < AliTOFGeometry::SlewTOTMin()) 
2249     tot = AliTOFGeometry::SlewTOTMin();
2250   if (tot > AliTOFGeometry::SlewTOTMax()) 
2251     tot = AliTOFGeometry::SlewTOTMax();
2252   for (Int_t islew = 0; islew < 6; islew++)
2253     corr += parOffline->GetSlewPar(islew) * TMath::Power(tot, islew) * 1.e3;
2254
2255   /* return correction */
2256   return corr;
2257 }
2258
2259 //----------------------------------------------------------------------------
2260
2261 void
2262 AliTOFcalib::CalibrateESD(AliESDEvent *event)
2263 {
2264   /*
2265    * calibrate ESD
2266    */
2267
2268   if (!fInitFlag) {
2269     AliError("class not yet initialized. Initialize it before.");
2270     return;
2271   }
2272
2273   /* loop over tracks */
2274   AliESDtrack *track = NULL;
2275   Int_t index, l0l1, deltaBC;
2276   Double_t time, tot, corr, texp[AliPID::kSPECIES];
2277   UInt_t timestamp = event->GetTimeStamp();
2278   for (Int_t itrk = 0; itrk < event->GetNumberOfTracks(); itrk++) {
2279
2280     /* get track */
2281     track = event->GetTrack(itrk);
2282     if (!track || !(track->GetStatus() & AliESDtrack::kTOFout)) continue;
2283
2284     /* calibrate TOF signal */
2285     if (fCalibrateTOFsignal) {
2286       /* get info */
2287       index = track->GetTOFCalChannel();
2288       time = track->GetTOFsignalRaw();
2289       tot = track->GetTOFsignalToT();
2290       l0l1 = track->GetTOFL0L1();
2291       deltaBC = track->GetTOFDeltaBC();
2292       /* get correction */
2293       corr = GetTimeCorrection(index, tot, deltaBC, l0l1, timestamp);
2294       /* apply correction */
2295       time -= corr;
2296       /* set new TOF signal */
2297       track->SetTOFsignal(time);
2298     }
2299
2300     /* correct expected time */
2301     if (fCorrectTExp) {
2302       /* get integrated times */
2303       track->GetIntegratedTimes(texp);
2304       /* loop over particle types and correct expected time */
2305       for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++)
2306         texp[ipart] += fResponseParams->EvalTExpCorr(ipart, track->P());
2307       /* set integrated times */
2308       track->SetIntegratedTimes(texp);
2309     }
2310
2311   }
2312
2313 }
2314
2315 //----------------------------------------------------------------------------
2316
2317 Bool_t
2318 AliTOFcalib::IsChannelEnabled(Int_t index, Bool_t checkEfficiency)
2319 {
2320   /*
2321    * is channel enabled
2322    */
2323
2324   if (!fInitFlag) {
2325     AliError("class not yet initialized. Initialize it before.");
2326     return kTRUE;
2327   }
2328
2329   /* check bad status */
2330   if (fStatus->GetPulserStatus(index) == AliTOFChannelOnlineStatusArray::kTOFPulserBad) return kFALSE;
2331   if (fStatus->GetNoiseStatus(index) == AliTOFChannelOnlineStatusArray::kTOFNoiseBad) return kFALSE;
2332   if (fStatus->GetHWStatus(index) == AliTOFChannelOnlineStatusArray::kTOFHWBad) return kFALSE;
2333   if (checkEfficiency && !IsChannelEfficient(index)) return kFALSE;
2334   
2335   /* good status */
2336   return kTRUE;
2337
2338 }
2339
2340 //----------------------------------------------------------------------------
2341
2342 Bool_t
2343 AliTOFcalib::IsChannelEfficient(Int_t index)
2344 {
2345   /*
2346    * is channel efficient
2347    */
2348
2349   if (!fInitFlag) {
2350     AliError("class not yet initialized. Initialize it before.");
2351     return kTRUE;
2352   }
2353
2354   /* check efficiency */
2355   if (fReadoutEfficiency->GetBinContent(index + 1) < 0.95) return kFALSE;
2356   return kTRUE;
2357
2358 }
2359
2360 //----------------------------------------------------------------------------
2361
2362 void
2363 AliTOFcalib::CalibrateTExp(AliESDEvent *event) const
2364 {
2365   /*
2366    * calibrate TExp
2367    */
2368
2369   if (!fInitFlag) {
2370     AliError("class not yet initialized. Initialize it before.");
2371     return;
2372   }
2373
2374   /* loop over tracks */
2375   AliESDtrack *track = NULL;
2376   Double_t texp[AliPID::kSPECIES];
2377   for (Int_t itrk = 0; itrk < event->GetNumberOfTracks(); itrk++) {
2378
2379     /* get track */
2380     track = event->GetTrack(itrk);
2381     if (!track || !(track->GetStatus() & AliESDtrack::kTOFout)) continue;
2382
2383     /* get integrated times */
2384     track->GetIntegratedTimes(texp);
2385     /* loop over particle types and correct expected time */
2386     for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++)
2387       texp[ipart] += fResponseParams->EvalTExpCorr(ipart, track->P());
2388     /* set integrated times */
2389     track->SetIntegratedTimes(texp);
2390
2391   }
2392
2393 }
2394