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