]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TOF/AliTOFtracker.cxx
9f23bbb9b532930847480e5dfab2a309c35b59c7
[u/mrichter/AliRoot.git] / TOF / AliTOFtracker.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 //                                                                    //
18 // AliTOFtracker Class                                                //
19 // Task: Perform association of the ESD tracks to TOF Clusters        //
20 // and Update ESD track with associated TOF Cluster parameters        //
21 //                                                                    //
22 // -- Authors : S. Arcelli, C. Zampolli (Bologna University and INFN) //
23 // -- Contacts: Annalisa.De.Caro@cern.ch                              //
24 // --         : Chiara.Zampolli@bo.infn.it                            //
25 // --         : Silvia.Arcelli@bo.infn.it                             //
26 //                                                                    //
27 //--------------------------------------------------------------------//
28
29 #include <Rtypes.h>
30 #include <TROOT.h>
31
32 #include <TSeqCollection.h>
33 #include <TClonesArray.h>
34 #include <TGeoManager.h>
35 #include <TTree.h>
36 #include <TFile.h>
37 #include <TH2F.h>
38
39 #include "AliGeomManager.h"
40 #include "AliESDtrack.h"
41 #include "AliESDEvent.h"
42 #include "AliLog.h"
43 #include "AliTrackPointArray.h"
44 #include "AliCDBManager.h"
45
46 #include "AliTOFpidESD.h"
47 #include "AliTOFRecoParam.h"
48 #include "AliTOFReconstructor.h"
49 #include "AliTOFcluster.h"
50 #include "AliTOFGeometry.h"
51 #include "AliTOFtracker.h"
52 #include "AliTOFtrack.h"
53
54 extern TGeoManager *gGeoManager;
55 extern TROOT *gROOT;
56
57 ClassImp(AliTOFtracker)
58
59 //_____________________________________________________________________________
60 AliTOFtracker::AliTOFtracker():
61   fRecoParam(0x0),
62   fGeom(0x0),
63   fPid(0x0),
64   fN(0),
65   fNseeds(0),
66   fNseedsTOF(0),
67   fngoodmatch(0),
68   fnbadmatch(0),
69   fnunmatch(0),
70   fnmatch(0),
71   fTracks(new TClonesArray("AliTOFtrack")),
72   fSeeds(new TClonesArray("AliESDtrack")),
73   fHDigClusMap(0x0),
74   fHDigNClus(0x0),
75   fHDigClusTime(0x0),
76   fHDigClusToT(0x0),
77   fHRecNClus(0x0),
78   fHRecDist(0x0),
79   fHRecSigYVsP(0x0),
80   fHRecSigZVsP(0x0),
81   fHRecSigYVsPWin(0x0),
82   fHRecSigZVsPWin(0x0),
83   fCalTree(0x0),
84   fIch(-1),
85   fToT(-1.),
86   fTime(-1.),
87   fExpTimePi(-1.),
88   fExpTimeKa(-1.),
89   fExpTimePr(-1.)
90  { 
91   //AliTOFtracker main Ctor
92    
93    // Gettimg the geometry 
94    fGeom= new AliTOFGeometry();
95
96    InitCheckHists();
97
98 }
99 //_____________________________________________________________________________
100 AliTOFtracker::~AliTOFtracker() {
101   //
102   // Dtor
103   //
104
105   SaveCheckHists();
106
107   if(!(AliCDBManager::Instance()->GetCacheFlag())){
108     delete fRecoParam;
109   }
110   delete fGeom; 
111   delete fPid; 
112   delete fHDigClusMap;
113   delete fHDigNClus;
114   delete fHDigClusTime;
115   delete fHDigClusToT;
116   delete fHRecNClus;
117   delete fHRecDist;
118   delete fHRecSigYVsP;
119   delete fHRecSigZVsP;
120   delete fHRecSigYVsPWin;
121   delete fHRecSigZVsPWin;
122   delete fCalTree;
123   if (fTracks){
124     fTracks->Delete();
125     delete fTracks;
126     fTracks=0x0;
127   }
128   if (fSeeds){
129     fSeeds->Delete();
130     delete fSeeds;
131     fSeeds=0x0;
132   }
133
134 }
135 //_____________________________________________________________________________
136 Int_t AliTOFtracker::PropagateBack(AliESDEvent* event) {
137   //
138   // Gets seeds from ESD event and Match with TOF Clusters
139   //
140
141   // initialize RecoParam for current event
142   AliDebug(1,"Initializing params for TOF");
143
144   fRecoParam = AliTOFReconstructor::GetRecoParam();  // instantiate reco param from STEER...
145
146   if (fRecoParam == 0x0) { 
147     AliFatal("No Reco Param found for TOF!!!");
148   }
149   //fRecoParam->Dump();
150   //if(fRecoParam->GetApplyPbPbCuts())fRecoParam=fRecoParam->GetPbPbparam();
151   //fRecoParam->PrintParameters();
152
153   Double_t parPID[2];   
154   parPID[0]=fRecoParam->GetTimeResolution();
155   parPID[1]=fRecoParam->GetTimeNSigma();
156   fPid=new AliTOFpidESD(parPID);
157
158   //Initialise some counters
159
160   fNseeds=0;
161   fNseedsTOF=0;
162   fngoodmatch=0;
163   fnbadmatch=0;
164   fnunmatch=0;
165   fnmatch=0;
166
167   Int_t ntrk=event->GetNumberOfTracks();
168   fNseeds = ntrk;
169   TClonesArray &aESDTrack = *fSeeds;
170
171
172   //Load ESD tracks into a local Array of ESD Seeds
173
174   for (Int_t i=0; i<fNseeds; i++) {
175     AliESDtrack *t=event->GetTrack(i);
176     new(aESDTrack[i]) AliESDtrack(*t);
177   }
178
179   //Prepare ESD tracks candidates for TOF Matching
180   CollectESD();
181
182   //First Step with Strict Matching Criterion
183   MatchTracks(kFALSE);
184
185   //Second Step with Looser Matching Criterion
186   MatchTracks(kTRUE);
187
188   AliInfo(Form("Number of matched tracks = %d (good = %d, bad = %d)",fnmatch,fngoodmatch,fnbadmatch));
189
190   //Update the matched ESD tracks
191
192   for (Int_t i=0; i<ntrk; i++) {
193     AliESDtrack *t=event->GetTrack(i);
194     AliESDtrack *seed =(AliESDtrack*)fSeeds->UncheckedAt(i);
195
196     if ( (seed->GetStatus()&AliESDtrack::kTOFin)!=0 ) {
197       t->SetStatus(AliESDtrack::kTOFin);
198       //if(seed->GetTOFsignal()>0){
199       if ( (seed->GetStatus()&AliESDtrack::kTOFout)!=0 ) {
200         t->SetStatus(AliESDtrack::kTOFout);
201         t->SetTOFsignal(seed->GetTOFsignal());
202         t->SetTOFcluster(seed->GetTOFcluster());
203         t->SetTOFsignalToT(seed->GetTOFsignalToT());
204         t->SetTOFsignalRaw(seed->GetTOFsignalRaw());
205         t->SetTOFsignalDz(seed->GetTOFsignalDz());
206         t->SetTOFsignalDx(seed->GetTOFsignalDx());
207         t->SetTOFCalChannel(seed->GetTOFCalChannel());
208         Int_t tlab[3]; seed->GetTOFLabel(tlab);    
209         t->SetTOFLabel(tlab);
210
211         Double_t alphaA = dynamic_cast<AliExternalTrackParam*>(t)->GetAlpha();
212         Double_t xA = dynamic_cast<AliExternalTrackParam*>(t)->GetX();
213         Double_t yA = dynamic_cast<AliExternalTrackParam*>(t)->GetY();
214         Double_t zA = dynamic_cast<AliExternalTrackParam*>(t)->GetZ();
215         Double_t p1A = dynamic_cast<AliExternalTrackParam*>(t)->GetSnp();
216         Double_t p2A = dynamic_cast<AliExternalTrackParam*>(t)->GetTgl();
217         Double_t p3A = dynamic_cast<AliExternalTrackParam*>(t)->GetSigned1Pt();
218         const Double_t *covA = dynamic_cast<AliExternalTrackParam*>(t)->GetCovariance();
219
220         // Make attention, please:
221         //      AliESDtrack::fTOFInfo array does not be stored in the AliESDs.root file
222         //      it is there only for a check during the reconstruction step.
223         Float_t info[10]; seed->GetTOFInfo(info);
224         t->SetTOFInfo(info);
225         AliDebug(3,Form(" distance=%f; residual in the pad reference frame: dX=%f, dZ=%f", info[0],info[1],info[2]));
226
227         // Check done:
228         //       by calling the AliESDtrack::UpdateTrackParams,
229         //       the current track parameters are changed
230         //       and it could cause refit problems.
231         //       We need to update only the following track parameters:
232         //            the track length and expected times.
233         //       Removed AliESDtrack::UpdateTrackParams call
234         //       Called AliESDtrack::SetIntegratedTimes(...) and
235         //       AliESDtrack::SetIntegratedLength() routines.
236         /*
237           AliTOFtrack *track = new AliTOFtrack(*seed);
238           t->UpdateTrackParams(track,AliESDtrack::kTOFout); // to be checked - AdC
239           delete track;
240           Double_t time[10]; t->GetIntegratedTimes(time);
241         */
242
243         Double_t time[10]; seed->GetIntegratedTimes(time);
244         t->SetIntegratedTimes(time);
245
246         Double_t length =  seed->GetIntegratedLength();
247         t->SetIntegratedLength(length);
248
249         Double_t alphaB = dynamic_cast<AliExternalTrackParam*>(t)->GetAlpha();
250         Double_t xB = dynamic_cast<AliExternalTrackParam*>(t)->GetX();
251         Double_t yB = dynamic_cast<AliExternalTrackParam*>(t)->GetY();
252         Double_t zB = dynamic_cast<AliExternalTrackParam*>(t)->GetZ();
253         Double_t p1B = dynamic_cast<AliExternalTrackParam*>(t)->GetSnp();
254         Double_t p2B = dynamic_cast<AliExternalTrackParam*>(t)->GetTgl();
255         Double_t p3B = dynamic_cast<AliExternalTrackParam*>(t)->GetSigned1Pt();
256         const Double_t *covB = dynamic_cast<AliExternalTrackParam*>(t)->GetCovariance();
257         AliDebug(2,"Track params -now(before)-:");
258         AliDebug(2,Form("    X: %f(%f), Y: %f(%f), Z: %f(%f) --- alpha: %f(%f)",
259                         xB,xA,
260                         yB,yA,
261                         zB,zA,
262                         alphaB,alphaA));
263         AliDebug(2,Form("    p1: %f(%f), p2: %f(%f), p3: %f(%f)",
264                         p1B,p1A,
265                         p2B,p2A,
266                         p3B,p3A));
267         AliDebug(2,Form("    cov1: %f(%f), cov2: %f(%f), cov3: %f(%f)"
268                         " cov4: %f(%f), cov5: %f(%f), cov6: %f(%f)"
269                         " cov7: %f(%f), cov8: %f(%f), cov9: %f(%f)"
270                         " cov10: %f(%f), cov11: %f(%f), cov12: %f(%f)"
271                         " cov13: %f(%f), cov14: %f(%f), cov15: %f(%f)",
272                         covB[0],covA[0],
273                         covB[1],covA[1],
274                         covB[2],covA[2],
275                         covB[3],covA[3],
276                         covB[4],covA[4],
277                         covB[5],covA[5],
278                         covB[6],covA[6],
279                         covB[7],covA[7],
280                         covB[8],covA[8],
281                         covB[9],covA[9],
282                         covB[10],covA[10],
283                         covB[11],covA[11],
284                         covB[12],covA[12],
285                         covB[13],covA[13],
286                         covB[14],covA[14]
287                         ));
288         AliDebug(3,Form(" TOF params: %6d  %f %f %f %f %f %6d %3d %f  %f %f %f %f %f",
289                         i,
290                         t->GetTOFsignalRaw(),
291                         t->GetTOFsignal(),
292                         t->GetTOFsignalToT(),
293                         t->GetTOFsignalDz(),
294                         t->GetTOFsignalDx(),
295                         t->GetTOFCalChannel(),
296                         t->GetTOFcluster(),
297                         t->GetIntegratedLength(),
298                         time[0], time[1], time[2], time[3], time[4]
299                         )
300                  );
301       }
302     }
303   }
304
305   //Handle Time Zero information
306
307   Double_t timeZero=0.;
308   Double_t timeZeroMax=99999.;
309   Bool_t usetimeZero     = fRecoParam->UseTimeZero();
310   Bool_t timeZeroFromT0  = fRecoParam->GetTimeZerofromT0();
311   Bool_t timeZeroFromTOF = fRecoParam->GetTimeZerofromTOF();
312
313   AliDebug(2,Form("Use Time Zero?: %d",usetimeZero));
314   AliDebug(2,Form("Time Zero from T0? : %d",timeZeroFromT0));
315   AliDebug(2,Form("Time Zero From TOF? : %d",timeZeroFromTOF));
316
317   if(usetimeZero){
318     if(timeZeroFromT0){
319       timeZero=GetTimeZerofromT0(event); 
320     }
321     if(timeZeroFromTOF && (timeZero>timeZeroMax || !timeZeroFromT0)){
322       timeZero=GetTimeZerofromTOF(event); 
323     }
324   }
325   AliDebug(2,Form("time Zero used in PID: %f",timeZero));
326   //Make TOF PID
327   fPid->MakePID(event,timeZero);
328
329   fSeeds->Clear();
330   fTracks->Clear();
331   return 0;
332   
333 }
334 //_________________________________________________________________________
335 void AliTOFtracker::CollectESD() {
336    //prepare the set of ESD tracks to be matched to clusters in TOF
337
338   Int_t seedsTOF1=0;
339   Int_t seedsTOF2=0;
340  
341   TClonesArray &aTOFTrack = *fTracks;
342   for (Int_t i=0; i<fNseeds; i++) {
343
344     AliESDtrack *t =(AliESDtrack*)fSeeds->UncheckedAt(i);
345     if ((t->GetStatus()&AliESDtrack::kTPCout)==0)continue;
346
347     AliTOFtrack *track = new AliTOFtrack(*t); // New
348     Float_t x = (Float_t)track->GetX(); //New
349
350     // TRD 'good' tracks, already propagated at 371 cm
351     if ( ( (t->GetStatus()&AliESDtrack::kTRDout)!=0 ) &&
352          ( x >= AliTOFGeometry::Rmin() ) ) {
353       if  ( track->PropagateToInnerTOF() ) {
354
355         AliDebug(1,Form(" TRD propagated track till rho = %fcm."
356                         " And then the track has been propagated till rho = %fcm.",
357                         x, (Float_t)track->GetX()));
358
359         track->SetSeedIndex(i);
360         t->UpdateTrackParams(track,AliESDtrack::kTOFin);
361         new(aTOFTrack[fNseedsTOF]) AliTOFtrack(*track);
362         fNseedsTOF++;
363         seedsTOF1++;
364       }
365       delete track;
366     }
367
368     // Propagate the rest of TPCbp  
369     else {
370       if ( track->PropagateToInnerTOF() ) { 
371
372         AliDebug(1,Form(" TPC propagated track till rho = %fcm."
373                         " And then the track has been propagated till rho = %fcm.",
374                         x, (Float_t)track->GetX()));
375
376         track->SetSeedIndex(i);
377         t->UpdateTrackParams(track,AliESDtrack::kTOFin);
378         new(aTOFTrack[fNseedsTOF]) AliTOFtrack(*track);
379         fNseedsTOF++;
380         seedsTOF2++;
381       }
382       delete track;
383     }
384   }
385
386   AliInfo(Form("Number of TOF seeds = %d (Type 1 = %d, Type 2 = %d)",fNseedsTOF,seedsTOF1,seedsTOF2));
387
388   // Sort according uncertainties on track position 
389   fTracks->Sort();
390
391 }
392 //_________________________________________________________________________
393 void AliTOFtracker::MatchTracks( Bool_t mLastStep){
394
395
396   // Parameters used/regulating the reconstruction
397
398   static Float_t corrLen=0.75;
399   static Float_t detDepth=15.3;
400   static Float_t padDepth=0.5;
401
402   const Float_t kSpeedOfLight= 2.99792458e-2; // speed of light [cm/ps]
403   const Float_t kTimeOffset = 32.; // time offset for tracking algorithm [ps]
404
405   Float_t dY=AliTOFGeometry::XPad(); 
406   Float_t dZ=AliTOFGeometry::ZPad(); 
407
408   Float_t sensRadius = fRecoParam->GetSensRadius();
409   Float_t stepSize   = fRecoParam->GetStepSize();
410   Float_t scaleFact   = fRecoParam->GetWindowScaleFact();
411   Float_t dyMax=fRecoParam->GetWindowSizeMaxY(); 
412   Float_t dzMax=fRecoParam->GetWindowSizeMaxZ();
413   Float_t dCut=fRecoParam->GetDistanceCut();
414   Double_t maxChi2=fRecoParam->GetMaxChi2TRD();
415   Bool_t timeWalkCorr    = fRecoParam->GetTimeWalkCorr();
416   if(!mLastStep){
417     AliDebug(1,"++++++++++++++TOF Reconstruction Parameters:++++++++++++ \n");
418     AliDebug(1,Form("TOF sens radius: %f",sensRadius));
419     AliDebug(1,Form("TOF step size: %f",stepSize));
420     AliDebug(1,Form("TOF Window scale factor: %f",scaleFact));
421     AliDebug(1,Form("TOF Window max dy: %f",dyMax));
422     AliDebug(1,Form("TOF Window max dz: %f",dzMax));
423     AliDebug(1,Form("TOF distance Cut: %f",dCut));
424     AliDebug(1,Form("TOF Max Chi2: %f",maxChi2));
425     AliDebug(1,Form("Time Walk Correction? : %d",timeWalkCorr));   
426   }
427
428   //Match ESD tracks to clusters in TOF
429
430   // Get the number of propagation steps
431   Int_t nSteps=(Int_t)(detDepth/stepSize);
432
433   //PH Arrays (moved outside of the loop)
434   Float_t * trackPos[4];
435   for (Int_t ii=0; ii<4; ii++) trackPos[ii] = new Float_t[nSteps];
436   Int_t * clind = new Int_t[fN];
437   
438   // Some init
439   const Int_t kNfoundMax = 10000; // related to nSteps value
440   Int_t         index[kNfoundMax];
441   Float_t        dist[kNfoundMax];
442   Float_t       distZ[kNfoundMax];
443   Float_t       distY[kNfoundMax]; // delta(rhoXphi) // AdC
444   Float_t       cxpos[kNfoundMax];
445   Float_t       crecL[kNfoundMax];
446   const Int_t kNclusterMax = 1000; // related to fN value
447   TGeoHMatrix   global[kNclusterMax];
448      
449   //The matching loop
450   for (Int_t iseed=0; iseed<fNseedsTOF; iseed++) {
451
452     for (Int_t ii=0; ii<kNfoundMax; ii++) {
453       index[ii] = -1;
454       dist[ii] = 9999.;
455       distZ[ii] = 9999.;
456       distY[ii] = 9999.;
457       cxpos[ii] = 9999.;
458       crecL[ii] = 0.;
459     }
460     for (Int_t ii=0; ii<kNclusterMax; ii++)
461       global[ii] = 0x0;
462
463     AliTOFtrack *track =(AliTOFtrack*)fTracks->UncheckedAt(iseed);
464     AliESDtrack *t =(AliESDtrack*)fSeeds->UncheckedAt(track->GetSeedIndex());
465     //if ( t->GetTOFsignal()>0. ) continue;
466     if ( (t->GetStatus()&AliESDtrack::kTOFout)!=0 ) continue;
467     AliTOFtrack *trackTOFin =new AliTOFtrack(*track);
468
469     // Determine a window around the track
470     Double_t x,par[5]; 
471     trackTOFin->GetExternalParameters(x,par);
472     Double_t cov[15]; 
473     trackTOFin->GetExternalCovariance(cov);
474
475     if (cov[0]<0. || cov[2]<0.) {
476       AliWarning(Form("Very strange track (%d)! At least one of its covariance matrix diagonal elements is negative!",iseed));
477       //delete trackTOFin;
478       //continue;
479     }
480
481     Double_t dphi=
482       scaleFact*
483       ((5*TMath::Sqrt(TMath::Abs(cov[0])) + 0.5*dY + 2.5*TMath::Abs(par[2]))/sensRadius); 
484     Double_t dz=
485        scaleFact*
486        (5*TMath::Sqrt(TMath::Abs(cov[2])) + 0.5*dZ + 2.5*TMath::Abs(par[3]));
487
488     Double_t phi=TMath::ATan2(par[0],x) + trackTOFin->GetAlpha();
489     if (phi<-TMath::Pi())phi+=2*TMath::Pi();
490     if (phi>=TMath::Pi())phi-=2*TMath::Pi();
491     Double_t z=par[1];   
492
493     //upper limit on window's size.
494
495     if(dz> dzMax) dz=dzMax;
496     if(dphi*sensRadius> dyMax) dphi=dyMax/sensRadius;
497
498
499     Int_t nc=0;
500
501     // find the clusters in the window of the track
502
503     for (Int_t k=FindClusterIndex(z-dz); k<fN; k++) {
504
505       if (nc>=kNclusterMax) {
506         AliWarning("No more matchable clusters can be stored! Please, increase the corresponding vectors size.");
507         break;
508       }
509
510       AliTOFcluster *c=fClusters[k];
511       if (c->GetZ() > z+dz) break;
512       if (c->IsUsed()) continue;
513
514       if (!c->GetStatus()) {
515         AliDebug(1,"Cluster in channel declared bad!");
516         continue; // skip bad channels as declared in OCDB
517       }
518
519       Double_t dph=TMath::Abs(c->GetPhi()-phi);
520       if (dph>TMath::Pi()) dph-=2.*TMath::Pi();
521       if (TMath::Abs(dph)>dphi) continue;
522
523       Double_t yc=(c->GetPhi() - trackTOFin->GetAlpha())*c->GetR();
524       Double_t p[2]={yc, c->GetZ()};
525       Double_t cov2[3]= {dY*dY/12., 0., dZ*dZ/12.};
526       if (trackTOFin->AliExternalTrackParam::GetPredictedChi2(p,cov2) > maxChi2)continue;
527
528       clind[nc] = k;      
529       Char_t path[100];
530       Int_t ind[5];
531       ind[0]=c->GetDetInd(0);
532       ind[1]=c->GetDetInd(1);
533       ind[2]=c->GetDetInd(2);
534       ind[3]=c->GetDetInd(3);
535       ind[4]=c->GetDetInd(4);
536       fGeom->GetVolumePath(ind,path);
537       gGeoManager->cd(path);
538       global[nc] = *gGeoManager->GetCurrentMatrix();
539       nc++;
540     }
541
542     AliDebug(1,Form(" Number of matchable TOF clusters for the track number %d: %d",iseed,nc));
543
544     //start fine propagation 
545
546     Int_t nStepsDone = 0;
547     for( Int_t istep=0; istep<nSteps; istep++){ 
548
549       Float_t xs=AliTOFGeometry::RinTOF()+istep*0.1;
550       Double_t ymax=xs*TMath::Tan(0.5*AliTOFGeometry::GetAlpha());
551
552       Bool_t skip=kFALSE;
553       Double_t ysect=trackTOFin->GetYat(xs,skip);
554       if (skip) break;
555       if (ysect > ymax) {
556         if (!trackTOFin->Rotate(AliTOFGeometry::GetAlpha())) {
557           break;
558         }
559       } else if (ysect <-ymax) {
560         if (!trackTOFin->Rotate(-AliTOFGeometry::GetAlpha())) {
561           break;
562         }
563       }
564
565       if(!trackTOFin->PropagateTo(xs)) {
566         break;
567       }
568
569       nStepsDone++;
570
571       // store the running point (Globalrf) - fine propagation     
572
573       Double_t r[3];
574       trackTOFin->GetXYZ(r);
575       trackPos[0][istep]= (Float_t) r[0];
576       trackPos[1][istep]= (Float_t) r[1];
577       trackPos[2][istep]= (Float_t) r[2];   
578       trackPos[3][istep]= trackTOFin->GetIntegratedLength();
579     }
580
581
582     Int_t nfound = 0;
583     Bool_t accept = kFALSE;
584     Bool_t isInside = kFALSE;
585     for (Int_t istep=0; istep<nStepsDone; istep++) {
586
587       if (nfound>=kNfoundMax) {
588         AliWarning("No more track positions can be stored! Please, increase the corresponding vectors size.");
589         break;
590       }
591
592       Float_t ctrackPos[3];     
593       ctrackPos[0] = trackPos[0][istep];
594       ctrackPos[1] = trackPos[1][istep];
595       ctrackPos[2] = trackPos[2][istep];
596
597       //now see whether the track matches any of the TOF clusters            
598
599       Float_t dist3d[3];
600       accept = kFALSE;
601       for (Int_t i=0; i<nc; i++) {
602         isInside = fGeom->IsInsideThePad(global[i],ctrackPos,dist3d);
603
604         if ( mLastStep ) {
605           Float_t yLoc = dist3d[1];
606           Float_t rLoc = TMath::Sqrt(dist3d[0]*dist3d[0]+dist3d[2]*dist3d[2]);
607           accept = (TMath::Abs(yLoc)<padDepth*0.5 && rLoc<dCut);
608           AliDebug(2," I am in the case mLastStep==kTRUE ");
609         }
610         else {
611           accept = isInside;
612         }
613         if (accept) {
614
615           dist[nfound] = TMath::Sqrt(dist3d[0]*dist3d[0] +
616                                      dist3d[1]*dist3d[1] +
617                                      dist3d[2]*dist3d[2]);
618           AliDebug(2,Form(" dist3dLoc[0] = %f, dist3dLoc[1] = %f, dist3dLoc[2] = %f ",
619                           dist3d[0],dist3d[1],dist3d[2]));
620           distZ[nfound] = dist3d[2]; // Z distance in the RF of the
621                                      // hit pad closest to the
622                                      // reconstructed track
623           distY[nfound] = dist3d[0]; // X distance in the RF of the
624                                      // hit pad closest to the
625                                      // reconstructed track
626                                      // It corresponds to Y coordinate
627                                      // in tracking RF
628
629
630           AliDebug(2,Form("   dist3dLoc[0] = %f --- distY[%d] = %f",
631                           dist3d[0],nfound,distY[nfound]));
632           AliDebug(2,Form("   dist3dLoc[2] = %f --- distZ[%d] = %f",
633                           dist3d[2],nfound,distZ[nfound]));
634
635
636           crecL[nfound] = trackPos[3][istep];
637           index[nfound] = clind[i]; // store cluster id             
638           cxpos[nfound] = AliTOFGeometry::RinTOF()+istep*0.1; //store prop.radius
639           nfound++;
640           if(accept &&!mLastStep)break;
641         }//end if accept
642
643       } //end for on the clusters
644       if(accept &&!mLastStep)break;
645     } //end for on the steps     
646
647     AliDebug(1,Form(" Number of track points for the track number %d: %d",iseed,nfound));
648
649
650     if (nfound == 0 ) {
651       fnunmatch++;
652       delete trackTOFin;
653       continue;
654     }
655     
656     fnmatch++;
657
658     // now choose the cluster to be matched with the track.
659
660     Int_t idclus=-1;
661     Float_t  recL = 0.;
662     Float_t  xpos=0.;
663     Float_t  mindist=1000.;
664     Float_t  mindistZ=0.;
665     Float_t  mindistY=0.;
666     for (Int_t iclus= 0; iclus<nfound;iclus++){
667       if (dist[iclus]< mindist){
668         mindist = dist[iclus];
669         mindistZ = distZ[iclus]; // Z distance in the RF of the hit
670                                  // pad closest to the reconstructed
671                                  // track
672         mindistY = distY[iclus]; // Y distance in the RF of the hit
673                                  // pad closest to the reconstructed
674                                  // track
675         xpos = cxpos[iclus];
676         idclus =index[iclus]; 
677         recL=crecL[iclus]+corrLen*0.5;
678       }
679     }
680
681
682     AliTOFcluster *c=fClusters[idclus];
683     /*
684     Float_t tiltangle = AliTOFGeometry::GetAngles(c->GetDetInd(1),c->GetDetInd(2))*TMath::DegToRad();
685     Float_t localCheck=-mindistZ;
686     localCheck/=TMath::Cos(tiltangle); // Z (tracking/ALICE RF) component of
687                                        // the distance between the
688                                        // reconstructed track and the
689                                        // TOF closest cluster
690     */
691     AliDebug(2, Form("%7d     %7d     %10d     %10d  %10d  %10d      %7d",
692                      iseed,
693                      fnmatch-1,
694                      TMath::Abs(trackTOFin->GetLabel()),
695                      c->GetLabel(0), c->GetLabel(1), c->GetLabel(2),
696                      idclus)); // AdC
697
698     c->Use(); 
699
700     // Track length correction for matching Step 2 
701
702     if(mLastStep){
703       Float_t rc=TMath::Sqrt(c->GetR()*c->GetR() + c->GetZ()*c->GetZ());
704       Float_t rt=TMath::Sqrt(trackPos[0][70]*trackPos[0][70]
705                              +trackPos[1][70]*trackPos[1][70]
706                              +trackPos[2][70]*trackPos[2][70]);
707       Float_t dlt=rc-rt;      
708       recL=trackPos[3][70]+dlt;
709     }    
710
711     if (
712         (c->GetLabel(0)==TMath::Abs(trackTOFin->GetLabel()))
713         ||
714         (c->GetLabel(1)==TMath::Abs(trackTOFin->GetLabel()))
715         ||
716         (c->GetLabel(2)==TMath::Abs(trackTOFin->GetLabel()))
717         ) {
718       fngoodmatch++;
719
720        AliDebug(2,Form(" track label good %5d",trackTOFin->GetLabel()));
721
722     }
723     else {
724       fnbadmatch++;
725
726       AliDebug(2,Form(" track label  bad %5d",trackTOFin->GetLabel()));
727
728     }
729
730     delete trackTOFin;
731
732     //  Store quantities to be used in the TOF Calibration
733     Float_t tToT=AliTOFGeometry::ToTBinWidth()*c->GetToT()*1E-3; // in ns
734     t->SetTOFsignalToT(tToT);
735     Float_t rawTime=AliTOFGeometry::TdcBinWidth()*c->GetTDCRAW()+kTimeOffset; // RAW time,in ps
736     t->SetTOFsignalRaw(rawTime);
737     t->SetTOFsignalDz(mindistZ);
738     t->SetTOFsignalDx(mindistY);
739
740     Float_t info[10] = {mindist,mindistY,mindistZ,
741                         0.,0.,0.,0.,0.,0.,0.};
742     t->SetTOFInfo(info);
743     AliDebug(2,Form(" distance=%f; residual in the pad reference frame: dX=%f, dZ=%f", info[0],info[1],info[2]));
744
745
746     Int_t ind[5];
747     ind[0]=c->GetDetInd(0);
748     ind[1]=c->GetDetInd(1);
749     ind[2]=c->GetDetInd(2);
750     ind[3]=c->GetDetInd(3);
751     ind[4]=c->GetDetInd(4);
752     Int_t calindex = AliTOFGeometry::GetIndex(ind);
753     t->SetTOFCalChannel(calindex);
754
755     // keep track of the track labels in the matched cluster
756     Int_t tlab[3];
757     tlab[0]=c->GetLabel(0);
758     tlab[1]=c->GetLabel(1);
759     tlab[2]=c->GetLabel(2);
760     AliDebug(2,Form(" tdc time of the matched track %6d = ",c->GetTDC()));    
761     Double_t tof=AliTOFGeometry::TdcBinWidth()*c->GetTDC()+kTimeOffset; // in ps
762     AliDebug(2,Form(" tof time of the matched track: %f = ",tof));    
763     Double_t tofcorr=tof;
764     if(timeWalkCorr)tofcorr=CorrectTimeWalk(mindistZ,tof);
765     AliDebug(2,Form(" tof time of the matched track, after TW corr: %f = ",tofcorr));    
766     //Set TOF time signal and pointer to the matched cluster
767     t->SetTOFsignal(tofcorr);
768     t->SetTOFcluster(idclus); // pointing to the recPoints tree
769
770     AliDebug(2,Form(" Setting TOF raw time: %f, z distance: %f  corrected time: %f ",rawTime,mindistZ,tofcorr));
771
772     //Tracking info
773     Double_t time[AliPID::kSPECIES]; t->GetIntegratedTimes(time); // in ps
774     Double_t mom=t->GetP();
775     AliDebug(2,Form(" Momentum for track %d -> %f", iseed,mom));
776     for (Int_t j=0;j<AliPID::kSPECIES;j++) {
777       Double_t mass=AliPID::ParticleMass(j);
778       time[j]+=(recL-trackPos[3][0])/kSpeedOfLight*TMath::Sqrt(mom*mom+mass*mass)/mom;
779     }
780
781     AliTOFtrack *trackTOFout = new AliTOFtrack(*t); 
782     trackTOFout->PropagateTo(xpos);
783
784     // Fill the track residual histograms.
785     FillResiduals(trackTOFout,c,kFALSE);
786
787     t->UpdateTrackParams(trackTOFout,AliESDtrack::kTOFout);
788     t->SetIntegratedLength(recL);
789     t->SetIntegratedTimes(time);
790     t->SetTOFLabel(tlab);
791
792  
793     // Fill Reco-QA histos for Reconstruction
794     fHRecNClus->Fill(nc);
795     fHRecDist->Fill(mindist);
796     fHRecSigYVsP->Fill(mom,TMath::Sqrt(cov[0]));
797     fHRecSigZVsP->Fill(mom,TMath::Sqrt(cov[2]));
798     fHRecSigYVsPWin->Fill(mom,dphi*sensRadius);
799     fHRecSigZVsPWin->Fill(mom,dz);
800
801     // Fill Tree for on-the-fly offline Calibration
802
803     if ( !((t->GetStatus() & AliESDtrack::kTIME)==0 ) ) {
804       fIch=calindex;
805       fToT=tToT;
806       fTime=rawTime;
807       fExpTimePi=time[2];
808       fExpTimeKa=time[3];
809       fExpTimePr=time[4];
810       fCalTree->Fill();
811     }
812     delete trackTOFout;
813   }
814   for (Int_t ii=0; ii<4; ii++) delete [] trackPos[ii];
815   delete [] clind;
816  
817 }
818 //_________________________________________________________________________
819 Int_t AliTOFtracker::LoadClusters(TTree *cTree) {
820   //--------------------------------------------------------------------
821   //This function loads the TOF clusters
822   //--------------------------------------------------------------------
823
824   Int_t npadX = AliTOFGeometry::NpadX();
825   Int_t npadZ = AliTOFGeometry::NpadZ();
826   Int_t nStripA = AliTOFGeometry::NStripA();
827   Int_t nStripB = AliTOFGeometry::NStripB();
828   Int_t nStripC = AliTOFGeometry::NStripC();
829
830   TBranch *branch=cTree->GetBranch("TOF");
831   if (!branch) { 
832     AliError("can't get the branch with the TOF clusters !");
833     return 1;
834   }
835
836   static TClonesArray dummy("AliTOFcluster",10000);
837   dummy.Clear();
838   TClonesArray *clusters=&dummy;
839   branch->SetAddress(&clusters);
840
841   cTree->GetEvent(0);
842   Int_t nc=clusters->GetEntriesFast();
843   fHDigNClus->Fill(nc);
844
845   AliInfo(Form("Number of clusters: %d",nc));
846
847   for (Int_t i=0; i<nc; i++) {
848     AliTOFcluster *c=(AliTOFcluster*)clusters->UncheckedAt(i);
849 //PH    fClusters[i]=new AliTOFcluster(*c); fN++;
850     fClusters[i]=c; fN++;
851
852   // Fill Digits QA histos
853  
854     Int_t isector = c->GetDetInd(0);
855     Int_t iplate = c->GetDetInd(1);
856     Int_t istrip = c->GetDetInd(2);
857     Int_t ipadX = c->GetDetInd(4);
858     Int_t ipadZ = c->GetDetInd(3);
859
860     Float_t time =(AliTOFGeometry::TdcBinWidth()*c->GetTDC())*1E-3; // in ns
861     Float_t tot = (AliTOFGeometry::TdcBinWidth()*c->GetToT())*1E-3;//in ns
862  
863     Int_t stripOffset = 0;
864     switch (iplate) {
865     case 0:
866       stripOffset = 0;
867       break;
868     case 1:
869       stripOffset = nStripC;
870       break;
871     case 2:
872       stripOffset = nStripC+nStripB;
873       break;
874     case 3:
875       stripOffset = nStripC+nStripB+nStripA;
876       break;
877     case 4:
878       stripOffset = nStripC+nStripB+nStripA+nStripB;
879       break;
880     default:
881       AliError(Form("Wrong plate number in TOF (%d) !",iplate));
882       break;
883     };
884     Int_t zindex=npadZ*(istrip+stripOffset)+(ipadZ+1);
885     Int_t phiindex=npadX*isector+ipadX+1;
886     fHDigClusMap->Fill(zindex,phiindex);
887     fHDigClusTime->Fill(time);
888     fHDigClusToT->Fill(tot);
889
890   }
891
892
893   return 0;
894 }
895 //_________________________________________________________________________
896 void AliTOFtracker::UnloadClusters() {
897   //--------------------------------------------------------------------
898   //This function unloads TOF clusters
899   //--------------------------------------------------------------------
900   for (Int_t i=0; i<fN; i++) {
901 //PH    delete fClusters[i];
902     fClusters[i] = 0x0;
903   }
904   fN=0;
905 }
906
907 //_________________________________________________________________________
908 Int_t AliTOFtracker::FindClusterIndex(Double_t z) const {
909   //--------------------------------------------------------------------
910   // This function returns the index of the nearest cluster 
911   //--------------------------------------------------------------------
912   if (fN==0) return 0;
913   if (z <= fClusters[0]->GetZ()) return 0;
914   if (z > fClusters[fN-1]->GetZ()) return fN;
915   Int_t b=0, e=fN-1, m=(b+e)/2;
916   for (; b<e; m=(b+e)/2) {
917     if (z > fClusters[m]->GetZ()) b=m+1;
918     else e=m; 
919   }
920   return m;
921 }
922
923 //_________________________________________________________________________
924 Bool_t AliTOFtracker::GetTrackPoint(Int_t index, AliTrackPoint& p) const
925 {
926   // Get track space point with index i
927   // Coordinates are in the global system
928   AliTOFcluster *cl = fClusters[index];
929   Float_t xyz[3];
930   xyz[0] = cl->GetR()*TMath::Cos(cl->GetPhi());
931   xyz[1] = cl->GetR()*TMath::Sin(cl->GetPhi());
932   xyz[2] = cl->GetZ();
933   Float_t phiangle = (Int_t(cl->GetPhi()*TMath::RadToDeg()/20.)+0.5)*20.*TMath::DegToRad();
934   Float_t sinphi = TMath::Sin(phiangle), cosphi = TMath::Cos(phiangle);
935   Float_t tiltangle = AliTOFGeometry::GetAngles(cl->GetDetInd(1),cl->GetDetInd(2))*TMath::DegToRad();
936   Float_t sinth = TMath::Sin(tiltangle), costh = TMath::Cos(tiltangle);
937   Float_t sigmay2 = AliTOFGeometry::XPad()*AliTOFGeometry::XPad()/12.;
938   Float_t sigmaz2 = AliTOFGeometry::ZPad()*AliTOFGeometry::ZPad()/12.;
939   Float_t cov[6];
940   cov[0] = sinphi*sinphi*sigmay2 + cosphi*cosphi*sinth*sinth*sigmaz2;
941   cov[1] = -sinphi*cosphi*sigmay2 + sinphi*cosphi*sinth*sinth*sigmaz2;
942   cov[2] = -cosphi*sinth*costh*sigmaz2;
943   cov[3] = cosphi*cosphi*sigmay2 + sinphi*sinphi*sinth*sinth*sigmaz2;
944   cov[4] = -sinphi*sinth*costh*sigmaz2;
945   cov[5] = costh*costh*sigmaz2;
946   p.SetXYZ(xyz[0],xyz[1],xyz[2],cov);
947
948   // Detector numbering scheme
949   Int_t nSector = AliTOFGeometry::NSectors();
950   Int_t nPlate  = AliTOFGeometry::NPlates();
951   Int_t nStripA = AliTOFGeometry::NStripA();
952   Int_t nStripB = AliTOFGeometry::NStripB();
953   Int_t nStripC = AliTOFGeometry::NStripC();
954
955   Int_t isector = cl->GetDetInd(0);
956   if (isector >= nSector)
957     AliError(Form("Wrong sector number in TOF (%d) !",isector));
958   Int_t iplate = cl->GetDetInd(1);
959   if (iplate >= nPlate)
960     AliError(Form("Wrong plate number in TOF (%d) !",iplate));
961   Int_t istrip = cl->GetDetInd(2);
962
963   Int_t stripOffset = 0;
964   switch (iplate) {
965   case 0:
966     stripOffset = 0;
967     break;
968   case 1:
969     stripOffset = nStripC;
970     break;
971   case 2:
972     stripOffset = nStripC+nStripB;
973     break;
974   case 3:
975     stripOffset = nStripC+nStripB+nStripA;
976     break;
977   case 4:
978     stripOffset = nStripC+nStripB+nStripA+nStripB;
979     break;
980   default:
981     AliError(Form("Wrong plate number in TOF (%d) !",iplate));
982     break;
983   };
984
985   Int_t idet = (2*(nStripC+nStripB)+nStripA)*isector +
986                stripOffset +
987                istrip;
988   UShort_t volid = AliGeomManager::LayerToVolUID(AliGeomManager::kTOF,idet);
989   p.SetVolumeID((UShort_t)volid);
990   return kTRUE;
991 }
992 //_________________________________________________________________________
993 void AliTOFtracker::InitCheckHists() {
994
995   //Init histos for Digits/Reco QA and Calibration
996
997
998   TDirectory *dir = gDirectory;
999   TFile *logFileTOF = 0;
1000
1001   TSeqCollection *list = gROOT->GetListOfFiles();
1002   int n = list->GetEntries();
1003   Bool_t isThere=kFALSE;
1004   for(int i=0; i<n; i++) {
1005     logFileTOF = (TFile*)list->At(i);
1006     if (strstr(logFileTOF->GetName(), "TOFQA.root")){
1007       isThere=kTRUE;
1008       break;
1009     } 
1010   }
1011
1012   if(!isThere)logFileTOF = new TFile( "TOFQA.root","RECREATE");
1013   logFileTOF->cd(); 
1014
1015   fCalTree = new TTree("CalTree", "Tree for TOF calibration");
1016   fCalTree->Branch("TOFchannelindex",&fIch,"iTOFch/I");
1017   fCalTree->Branch("ToT",&fToT,"TOFToT/F");
1018   fCalTree->Branch("TOFtime",&fTime,"TOFtime/F");
1019   fCalTree->Branch("PionExpTime",&fExpTimePi,"PiExpTime/F");
1020   fCalTree->Branch("KaonExpTime",&fExpTimeKa,"KaExpTime/F");
1021   fCalTree->Branch("ProtonExpTime",&fExpTimePr,"PrExpTime/F");
1022
1023   //Digits "QA" 
1024   fHDigClusMap = new TH2F("TOFDig_ClusMap", "",182,0.5,182.5,864, 0.5,864.5);  
1025   fHDigNClus = new TH1F("TOFDig_NClus", "",200,0.5,200.5);  
1026   fHDigClusTime = new TH1F("TOFDig_ClusTime", "",2000,0.,200.);  
1027   fHDigClusToT = new TH1F("TOFDig_ClusToT", "",500,0.,100);  
1028
1029   //Reco "QA"
1030   fHRecNClus =new TH1F("TOFRec_NClusW", "",50,0.5,50.5);
1031   fHRecDist=new TH1F("TOFRec_Dist", "",50,0.5,10.5);
1032   fHRecSigYVsP=new TH2F("TOFDig_SigYVsP", "",40,0.,4.,100, 0.,5.);
1033   fHRecSigZVsP=new TH2F("TOFDig_SigZVsP", "",40,0.,4.,100, 0.,5.);
1034   fHRecSigYVsPWin=new TH2F("TOFDig_SigYVsPWin", "",40,0.,4.,100, 0.,50.);
1035   fHRecSigZVsPWin=new TH2F("TOFDig_SigZVsPWin", "",40,0.,4.,100, 0.,50.);
1036
1037   dir->cd();
1038
1039 }
1040
1041 //_________________________________________________________________________
1042 void AliTOFtracker::SaveCheckHists() {
1043
1044   //write histos for Digits/Reco QA and Calibration
1045
1046   TDirectory *dir = gDirectory;
1047   TFile *logFileTOF = 0;
1048
1049   TSeqCollection *list = gROOT->GetListOfFiles();
1050   int n = list->GetEntries();
1051   Bool_t isThere=kFALSE;
1052   for(int i=0; i<n; i++) {
1053     logFileTOF = (TFile*)list->At(i);
1054     if (strstr(logFileTOF->GetName(), "TOFQA.root")){
1055       isThere=kTRUE;
1056       break;
1057     } 
1058   }
1059    
1060   if(!isThere) {
1061           AliError(Form("File TOFQA.root not found!! not wring histograms...."));
1062           return;
1063   }
1064   logFileTOF->cd(); 
1065   fHDigClusMap->Write(fHDigClusMap->GetName(), TObject::kOverwrite);
1066   fHDigNClus->Write(fHDigNClus->GetName(), TObject::kOverwrite);
1067   fHDigClusTime->Write(fHDigClusTime->GetName(), TObject::kOverwrite);
1068   fHDigClusToT->Write(fHDigClusToT->GetName(), TObject::kOverwrite);
1069   fHRecNClus->Write(fHRecNClus->GetName(), TObject::kOverwrite);
1070   fHRecDist->Write(fHRecDist->GetName(), TObject::kOverwrite);
1071   fHRecSigYVsP->Write(fHRecSigYVsP->GetName(), TObject::kOverwrite);
1072   fHRecSigZVsP->Write(fHRecSigZVsP->GetName(), TObject::kOverwrite);
1073   fHRecSigYVsPWin->Write(fHRecSigYVsPWin->GetName(), TObject::kOverwrite);
1074   fHRecSigZVsPWin->Write(fHRecSigZVsPWin->GetName(), TObject::kOverwrite);
1075   fCalTree->Write(fCalTree->GetName(),TObject::kOverwrite);
1076   logFileTOF->Flush();  
1077
1078   dir->cd();
1079   }
1080 //_________________________________________________________________________
1081 Float_t AliTOFtracker::CorrectTimeWalk( Float_t dist, Float_t tof) {
1082
1083   //dummy, for the moment
1084   Float_t tofcorr=0.;
1085   if(dist<AliTOFGeometry::ZPad()*0.5){
1086     tofcorr=tof;
1087     //place here the actual correction
1088   }else{
1089     tofcorr=tof; 
1090   } 
1091   return tofcorr;
1092 }
1093 //_________________________________________________________________________
1094 Float_t AliTOFtracker::GetTimeZerofromT0(AliESDEvent *event) const {
1095
1096   //Returns TimeZero as measured by T0 detector
1097
1098   return event->GetT0();
1099 }
1100 //_________________________________________________________________________
1101 Float_t AliTOFtracker::GetTimeZerofromTOF(AliESDEvent * /*event*/) const {
1102
1103   //dummy, for the moment. T0 algorithm using tracks on TOF
1104   {
1105     //place T0 algo here...
1106   }
1107   return 0.;
1108 }
1109 //_________________________________________________________________________
1110
1111 void AliTOFtracker::FillClusterArray(TObjArray* arr) const
1112 {
1113   //
1114   // Returns the TOF cluster array
1115   //
1116
1117   if (fN==0)
1118     arr = 0x0;
1119   else
1120     for (Int_t i=0; i<fN; ++i) arr->Add(fClusters[i]);
1121
1122 }
1123 //_________________________________________________________________________
1124