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