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