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