]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDtrackerV1.cxx
store ESD track Id in TRD track for back searching (ESD track from TRD
[u/mrichter/AliRoot.git] / TRD / AliTRDtrackerV1.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 /* $Id$ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //                                                                           //
20 //  Track finder                                                             //
21 //                                                                           //
22 //  Authors:                                                                 //
23 //    Alex Bercuci <A.Bercuci@gsi.de>                                        //
24 //    Markus Fasel <M.Fasel@gsi.de>                                          //
25 //                                                                           //
26 ///////////////////////////////////////////////////////////////////////////////
27
28 #include <TBranch.h>
29 #include <TDirectory.h>
30 #include <TLinearFitter.h>
31 #include <TTree.h>  
32 #include <TClonesArray.h>
33 #include <TTreeStream.h>
34 #include <TGeoMatrix.h>
35 #include <TGeoManager.h>
36
37 #include "AliLog.h"
38 #include "AliMathBase.h"
39 #include "AliESDEvent.h"
40 #include "AliGeomManager.h"
41 #include "AliRieman.h"
42 #include "AliTrackPointArray.h"
43
44 #include "AliTRDgeometry.h"
45 #include "AliTRDpadPlane.h"
46 #include "AliTRDcalibDB.h"
47 #include "AliTRDReconstructor.h"
48 #include "AliTRDCalibraFillHisto.h"
49 #include "AliTRDrecoParam.h"
50
51 #include "AliTRDcluster.h" 
52 #include "AliTRDdigitsParam.h"
53 #include "AliTRDseedV1.h"
54 #include "AliTRDtrackV1.h"
55 #include "AliTRDtrackerV1.h"
56 #include "AliTRDtrackerDebug.h"
57 #include "AliTRDtrackingChamber.h"
58 #include "AliTRDchamberTimeBin.h"
59
60 ClassImp(AliTRDtrackerV1)
61 ClassImp(AliTRDtrackerV1::AliTRDLeastSquare)
62 ClassImp(AliTRDtrackerV1::AliTRDtrackFitterRieman)
63
64 const  Float_t  AliTRDtrackerV1::fgkMinClustersInTrack =  0.5;  //
65 const  Float_t  AliTRDtrackerV1::fgkLabelFraction      =  0.8;  //
66 const  Double_t AliTRDtrackerV1::fgkMaxChi2            = 12.0;  //
67 const  Double_t AliTRDtrackerV1::fgkMaxSnp             =  0.95; // Maximum local sine of the azimuthal angle
68 const  Double_t AliTRDtrackerV1::fgkMaxStep            =  2.0;  // Maximal step size in propagation 
69 Double_t AliTRDtrackerV1::fgTopologicQA[kNConfigs] = {
70   0.5112, 0.5112, 0.5112, 0.0786, 0.0786,
71   0.0786, 0.0786, 0.0579, 0.0579, 0.0474,
72   0.0474, 0.0408, 0.0335, 0.0335, 0.0335
73 };  
74 const Double_t AliTRDtrackerV1::fgkX0[kNPlanes]    = {
75   300.2, 312.8, 325.4, 338.0, 350.6, 363.2};
76 Int_t AliTRDtrackerV1::fgNTimeBins = 0;
77 AliRieman* AliTRDtrackerV1::fgRieman = NULL;
78 TLinearFitter* AliTRDtrackerV1::fgTiltedRieman = NULL;
79 TLinearFitter* AliTRDtrackerV1::fgTiltedRiemanConstrained = NULL;
80
81 //____________________________________________________________________
82 AliTRDtrackerV1::AliTRDtrackerV1(AliTRDReconstructor *rec) 
83   :AliTracker()
84   ,fkReconstructor(NULL)
85   ,fGeom(NULL)
86   ,fClusters(NULL)
87   ,fTracklets(NULL)
88   ,fTracks(NULL)
89   ,fTracksESD(NULL)
90   ,fSieveSeeding(0)
91 {
92   //
93   // Default constructor.
94   // 
95   
96   SetReconstructor(rec); // initialize reconstructor
97
98   // initialize geometry
99   if(!AliGeomManager::GetGeometry()){
100     AliFatal("Could not get geometry.");
101   }
102   fGeom = new AliTRDgeometry();
103   fGeom->CreateClusterMatrixArray();
104   TGeoHMatrix *matrix = NULL;
105   Double_t loc[] = {0., 0., 0.};
106   Double_t glb[] = {0., 0., 0.};
107   for(Int_t ily=kNPlanes; ily--;){
108     Int_t ism = 0;
109     while(!(matrix = fGeom->GetClusterMatrix(AliTRDgeometry::GetDetector(ily, 2, ism)))) ism++;
110     if(!matrix){
111       AliError(Form("Could not get transformation matrix for layer %d. Use default.", ily));
112       fR[ily] = fgkX0[ily];
113       continue;
114     }
115     matrix->LocalToMaster(loc, glb);
116     fR[ily] = glb[0]+ AliTRDgeometry::AnodePos()-.5*AliTRDgeometry::AmThick() - AliTRDgeometry::DrThick();
117   }
118
119   // initialize cluster containers
120   for (Int_t isector = 0; isector < AliTRDgeometry::kNsector; isector++) new(&fTrSec[isector]) AliTRDtrackingSector(fGeom, isector);
121   
122   // initialize arrays
123   memset(fTrackQuality, 0, kMaxTracksStack*sizeof(Double_t));
124   memset(fSeedLayer, 0, kMaxTracksStack*sizeof(Int_t));
125   memset(fSeedTB, 0, kNSeedPlanes*sizeof(AliTRDchamberTimeBin*));
126   fTracksESD = new TClonesArray("AliESDtrack", 2*kMaxTracksStack);
127   fTracksESD->SetOwner();
128 }
129
130 //____________________________________________________________________
131 AliTRDtrackerV1::~AliTRDtrackerV1()
132
133   //
134   // Destructor
135   //
136   
137   if(fgRieman) delete fgRieman; fgRieman = NULL;
138   if(fgTiltedRieman) delete fgTiltedRieman; fgTiltedRieman = NULL;
139   if(fgTiltedRiemanConstrained) delete fgTiltedRiemanConstrained; fgTiltedRiemanConstrained = NULL;
140   for(Int_t isl =0; isl<kNSeedPlanes; isl++) if(fSeedTB[isl]) delete fSeedTB[isl];
141   if(fTracksESD){ fTracksESD->Delete(); delete fTracksESD; }
142   if(fTracks) {fTracks->Delete(); delete fTracks;}
143   if(fTracklets) {fTracklets->Delete(); delete fTracklets;}
144   if(fClusters) {
145     fClusters->Delete(); delete fClusters;
146   }
147   if(fGeom) delete fGeom;
148 }
149
150 //____________________________________________________________________
151 Int_t AliTRDtrackerV1::Clusters2Tracks(AliESDEvent *esd)
152 {
153   //
154   // Steering stand alone tracking for full TRD detector
155   //
156   // Parameters :
157   //   esd     : The ESD event. On output it contains 
158   //             the ESD tracks found in TRD.
159   //
160   // Output :
161   //   Number of tracks found in the TRD detector.
162   // 
163   // Detailed description
164   // 1. Launch individual SM trackers. 
165   //    See AliTRDtrackerV1::Clusters2TracksSM() for details.
166   //
167
168   if(!fkReconstructor->GetRecoParam() ){
169     AliError("Reconstruction configuration not initialized. Call first AliTRDReconstructor::SetRecoParam().");
170     return 0;
171   }
172   
173   //AliInfo("Start Track Finder ...");
174   Int_t ntracks = 0;
175   for(int ism=0; ism<AliTRDgeometry::kNsector; ism++){
176     //  for(int ism=1; ism<2; ism++){
177     //AliInfo(Form("Processing supermodule %i ...", ism));
178     ntracks += Clusters2TracksSM(ism, esd);
179   }
180   AliInfo(Form("Number of tracks: !TRDin[%d]", ntracks));
181   return ntracks;
182 }
183
184
185 //_____________________________________________________________________________
186 Bool_t AliTRDtrackerV1::GetTrackPoint(Int_t index, AliTrackPoint &p) const
187 {
188   //AliInfo(Form("Asking for tracklet %d", index));
189   
190   // reset position of the point before using it
191   p.SetXYZ(0., 0., 0.);
192   AliTRDseedV1 *tracklet = GetTracklet(index); 
193   if (!tracklet) return kFALSE;
194
195   // get detector for this tracklet
196   Int_t det = tracklet->GetDetector();
197   Int_t sec = fGeom->GetSector(det);
198   Double_t alpha = (sec+.5)*AliTRDgeometry::GetAlpha(),
199            sinA  = TMath::Sin(alpha),
200            cosA  = TMath::Cos(alpha);
201   Double_t local[3];
202   local[0] = tracklet->GetX(); 
203   local[1] = tracklet->GetY();
204   local[2] = tracklet->GetZ();
205   Double_t global[3];
206   fGeom->RotateBack(det, local, global);
207
208   Double_t cov2D[3]; Float_t cov[6];
209   tracklet->GetCovAt(local[0], cov2D);
210   cov[0] = cov2D[0]*sinA*sinA;
211   cov[1] =-cov2D[0]*sinA*cosA;
212   cov[2] =-cov2D[1]*sinA;
213   cov[3] = cov2D[0]*cosA*cosA;
214   cov[4] = cov2D[1]*cosA;
215   cov[5] = cov2D[2];
216   // store the global position of the tracklet and its covariance matrix in the track point 
217   p.SetXYZ(global[0],global[1],global[2], cov);
218   
219   // setting volume id
220   AliGeomManager::ELayerID iLayer = AliGeomManager::ELayerID(AliGeomManager::kTRD1+fGeom->GetLayer(det));
221   Int_t    modId = fGeom->GetSector(det) * AliTRDgeometry::kNstack + fGeom->GetStack(det);
222   UShort_t volid = AliGeomManager::LayerToVolUID(iLayer, modId);
223   p.SetVolumeID(volid);
224     
225   return kTRUE;
226 }
227
228 //____________________________________________________________________
229 TLinearFitter* AliTRDtrackerV1::GetTiltedRiemanFitter()
230 {
231   if(!fgTiltedRieman) fgTiltedRieman = new TLinearFitter(4, "hyp4");
232   return fgTiltedRieman;
233 }
234
235 //____________________________________________________________________
236 TLinearFitter* AliTRDtrackerV1::GetTiltedRiemanFitterConstraint()
237 {
238   if(!fgTiltedRiemanConstrained) fgTiltedRiemanConstrained = new TLinearFitter(2, "hyp2");
239   return fgTiltedRiemanConstrained;
240 }
241   
242 //____________________________________________________________________  
243 AliRieman* AliTRDtrackerV1::GetRiemanFitter()
244 {
245   if(!fgRieman) fgRieman = new AliRieman(AliTRDseedV1::kNtb * AliTRDgeometry::kNlayer);
246   return fgRieman;
247 }
248   
249 //_____________________________________________________________________________
250 Int_t AliTRDtrackerV1::PropagateBack(AliESDEvent *event) 
251 {
252 // Propagation of ESD tracks from TPC to TOF detectors and building of the TRD track. For building
253 // a TRD track an ESD track is used as seed. The informations obtained on the TRD track (measured points,
254 // covariance, PID, etc.) are than used to update the corresponding ESD track.
255 // Each track seed is first propagated to the geometrical limit of the TRD detector. 
256 // Its prolongation is searched in the TRD and if corresponding clusters are found tracklets are 
257 // constructed out of them (see AliTRDseedV1::AttachClusters()) and the track is updated. 
258 // Otherwise the ESD track is left unchanged.
259 // 
260 // The following steps are performed:
261 // 1. Selection of tracks based on the variance in the y-z plane.
262 // 2. Propagation to the geometrical limit of the TRD volume. If track propagation fails the AliESDtrack::kTRDStop is set.
263 // 3. Prolongation inside the fiducial volume (see AliTRDtrackerV1::FollowBackProlongation()) and marking
264 // the following status bits:
265 //   - AliESDtrack::kTRDin - if the tracks enters the TRD fiducial volume
266 //   - AliESDtrack::kTRDStop - if the tracks fails propagation
267 //   - AliESDtrack::kTRDbackup - if the tracks fulfills chi2 conditions and qualify for refitting
268 // 4. Writting to friends, PID, MC label, quality etc. Setting status bit AliESDtrack::kTRDout.
269 // 5. Propagation to TOF. If track propagation fails the AliESDtrack::kTRDStop is set.
270 //  
271
272   AliTRDCalibraFillHisto *calibra = AliTRDCalibraFillHisto::Instance(); // Calibration monitor
273   if (!calibra) AliInfo("Could not get Calibra instance\n");
274   if(!fgNTimeBins) CookNTimeBins();
275
276   // Define scalers
277   Int_t nFound   = 0, // number of tracks found
278         nSeeds   = 0, // total number of ESD seeds
279         nTRDseeds= 0, // number of seeds in the TRD acceptance
280         nTPCseeds= 0; // number of TPC seeds
281   Float_t foundMin = 20.0;
282   
283   Float_t *quality = NULL;
284   Int_t   *index   = NULL;
285   nSeeds   = event->GetNumberOfTracks();
286   // Sort tracks according to quality 
287   // (covariance in the yz plane)
288   if(nSeeds){  
289     quality = new Float_t[nSeeds];
290     index   = new Int_t[nSeeds];
291     for (Int_t iSeed = nSeeds; iSeed--;) {
292       AliESDtrack *seed = event->GetTrack(iSeed);
293       Double_t covariance[15];
294       seed->GetExternalCovariance(covariance);
295       quality[iSeed] = covariance[0] + covariance[2];
296     }
297     TMath::Sort(nSeeds, quality, index,kFALSE);
298   }
299   
300   // Propagate all seeds
301   Int_t   expectedClr;
302   AliTRDtrackV1 track;
303   for (Int_t iSeed = 0; iSeed < nSeeds; iSeed++) {
304   
305     // Get the seeds in sorted sequence
306     AliESDtrack *seed = event->GetTrack(index[iSeed]);
307     Float_t p4  = seed->GetC(seed->GetBz());
308   
309     // Check the seed status
310     ULong_t status = seed->GetStatus();
311     if ((status & AliESDtrack::kTPCout) == 0) continue;
312     if ((status & AliESDtrack::kTRDout) != 0) continue;
313
314     // Propagate to the entrance in the TRD mother volume
315     new(&track) AliTRDtrackV1(*seed);
316     if(AliTRDgeometry::GetXtrdBeg() > (fgkMaxStep + track.GetX()) && !PropagateToX(track, AliTRDgeometry::GetXtrdBeg(), fgkMaxStep)){ 
317       seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
318       continue;
319     }    
320     if(!AdjustSector(&track)){
321       seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
322       continue;
323     }
324     if(TMath::Abs(track.GetSnp()) > fgkMaxSnp) {
325       seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
326       continue;
327     }
328
329     nTPCseeds++;
330
331     // store track status at TRD entrance
332     seed->UpdateTrackParams(&track, AliESDtrack::kTRDbackup);
333
334     // prepare track and do propagation in the TRD
335     track.SetReconstructor(fkReconstructor);
336     track.SetKink(Bool_t(seed->GetKinkIndex(0)));
337     expectedClr = FollowBackProlongation(track);
338     // check if track entered the TRD fiducial volume
339     if(track.GetTrackLow()){ 
340       seed->UpdateTrackParams(&track, AliESDtrack::kTRDin);
341       nTRDseeds++;
342     }
343     // check if track was stopped in the TRD
344     if (expectedClr<0){      
345       seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
346       continue;
347     }
348
349     if(expectedClr){
350       nFound++;  
351       // computes PID for track
352       track.CookPID();
353       // update calibration references using this track
354       if(calibra->GetHisto2d()) calibra->UpdateHistogramsV1(&track);
355       // save calibration object
356       if (fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 0){ 
357         AliTRDtrackV1 *calibTrack = new AliTRDtrackV1(track);
358         calibTrack->SetOwner();
359         seed->AddCalibObject(calibTrack);
360       }
361       //update ESD track
362       seed->UpdateTrackParams(&track, AliESDtrack::kTRDout);
363       track.UpdateESDtrack(seed);
364     }
365
366     if ((TMath::Abs(track.GetC(track.GetBz()) - p4) / TMath::Abs(p4) < 0.2) ||(track.Pt() > 0.8)) {
367
368       // Make backup for back propagation
369       Int_t foundClr = track.GetNumberOfClusters();
370       if (foundClr >= foundMin) {
371         track.CookLabel(1. - fgkLabelFraction);
372         //if(track.GetBackupTrack()) UseClusters(track.GetBackupTrack());
373
374         // Sign only gold tracks
375         if (track.GetChi2() / track.GetNumberOfClusters() < 4) {
376           //if ((seed->GetKinkIndex(0)      ==   0) && (track.Pt() <  1.5)) UseClusters(&track);
377         }
378         Bool_t isGold = kFALSE;
379   
380         // Full gold track
381         if (track.GetChi2() / track.GetNumberOfClusters() < 5) {
382           if (track.GetBackupTrack()) seed->UpdateTrackParams(track.GetBackupTrack(),AliESDtrack::kTRDbackup);
383
384           isGold = kTRUE;
385         }
386   
387         // Almost gold track
388         if ((!isGold)  && (track.GetNCross() == 0) &&   (track.GetChi2() / track.GetNumberOfClusters()  < 7)) {
389           //seed->UpdateTrackParams(track, AliESDtrack::kTRDbackup);
390           if (track.GetBackupTrack()) seed->UpdateTrackParams(track.GetBackupTrack(),AliESDtrack::kTRDbackup);
391   
392           isGold = kTRUE;
393         }
394         
395         if ((!isGold) && (track.GetBackupTrack())) {
396           if ((track.GetBackupTrack()->GetNumberOfClusters() > foundMin) && ((track.GetBackupTrack()->GetChi2()/(track.GetBackupTrack()->GetNumberOfClusters()+1)) < 7)) {
397             seed->UpdateTrackParams(track.GetBackupTrack(),AliESDtrack::kTRDbackup);
398             isGold = kTRUE;
399           }
400         }
401       }
402     }
403     
404     // Propagation to the TOF
405     if(!(seed->GetStatus()&AliESDtrack::kTRDStop)) {
406       Int_t sm = track.GetSector();
407       // default value in case we have problems with the geometry.
408       Double_t xtof  = 371.; 
409       //Calculate radial position of the beginning of the TOF
410       //mother volume. In order to avoid mixing of the TRD 
411       //and TOF modules some hard values are needed. This are:
412       //1. The path to the TOF module.
413       //2. The width of the TOF (29.05 cm)
414       //(with the help of Annalisa de Caro Mar-17-2009)
415       if(gGeoManager){
416         gGeoManager->cd(Form("/ALIC_1/B077_1/BSEGMO%d_1/BTOF%d_1", sm, sm));
417         TGeoHMatrix *m = NULL;
418         Double_t loc[]={0., 0., -.5*29.05}, glob[3];
419         
420         if((m=gGeoManager->GetCurrentMatrix())){
421           m->LocalToMaster(loc, glob);
422           xtof = TMath::Sqrt(glob[0]*glob[0]+glob[1]*glob[1]);
423         }
424       }
425       if(xtof > (fgkMaxStep + track.GetX()) && !PropagateToX(track, xtof, fgkMaxStep)){ 
426         seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
427         continue;
428       }
429       if(!AdjustSector(&track)){ 
430         seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
431         continue;
432       }
433       if(TMath::Abs(track.GetSnp()) > fgkMaxSnp){ 
434         seed->UpdateTrackParams(&track, AliESDtrack::kTRDStop);
435         continue;
436       }
437       //seed->UpdateTrackParams(&track, AliESDtrack::kTRDout);
438       // TODO obsolete - delete
439       seed->SetTRDQuality(track.StatusForTOF()); 
440     }
441     seed->SetTRDBudget(track.GetBudget(0));
442   }
443   if(index) delete [] index;
444   if(quality) delete [] quality;
445
446   AliInfo(Form("Number of seeds: TPCout[%d] TRDin[%d]", nTPCseeds, nTRDseeds));
447   AliInfo(Form("Number of tracks: TRDout[%d]", nFound));
448
449   // run stand alone tracking
450   if (fkReconstructor->IsSeeding()) Clusters2Tracks(event);
451   
452   return 0;
453 }
454
455
456 //____________________________________________________________________
457 Int_t AliTRDtrackerV1::RefitInward(AliESDEvent *event)
458 {
459   //
460   // Refits tracks within the TRD. The ESD event is expected to contain seeds 
461   // at the outer part of the TRD. 
462   // The tracks are propagated to the innermost time bin 
463   // of the TRD and the ESD event is updated
464   // Origin: Thomas KUHR (Thomas.Kuhr@cern.ch)
465   //
466
467   Int_t   nseed    = 0; // contor for loaded seeds
468   Int_t   found    = 0; // contor for updated TRD tracks
469   
470   
471   AliTRDtrackV1 track;
472   for (Int_t itrack = 0; itrack < event->GetNumberOfTracks(); itrack++) {
473     AliESDtrack *seed = event->GetTrack(itrack);
474     ULong_t status = seed->GetStatus();
475
476     new(&track) AliTRDtrackV1(*seed);
477     if (track.GetX() < 270.0) {
478       seed->UpdateTrackParams(&track, AliESDtrack::kTRDbackup);
479       continue;
480     }
481
482     // reject tracks which failed propagation in the TRD or
483     // are produced by the TRD stand alone tracker
484     if(!(status & AliESDtrack::kTRDout)) continue;
485     if(!(status & AliESDtrack::kTRDin)) continue;
486     nseed++; 
487
488     track.ResetCovariance(50.0);
489
490     // do the propagation and processing
491     Bool_t kUPDATE = kFALSE;
492     Double_t xTPC = 250.0;
493     if(FollowProlongation(track)){      
494       // Prolongate to TPC
495       if (PropagateToX(track, xTPC, fgkMaxStep)) { //  -with update
496         seed->UpdateTrackParams(&track, AliESDtrack::kTRDrefit);
497         found++;
498         kUPDATE = kTRUE;
499       }
500
501       // Update the friend track
502       if (fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 0){ 
503         TObject *o = NULL; Int_t ic = 0;
504         AliTRDtrackV1 *calibTrack = NULL; 
505         while((o = seed->GetCalibObject(ic++))){
506           if(!(calibTrack = dynamic_cast<AliTRDtrackV1*>(o))) continue;
507           calibTrack->SetTrackHigh(track.GetTrackHigh());
508         }
509       }
510     }
511     
512     // Prolongate to TPC without update
513     if(!kUPDATE) {
514       AliTRDtrackV1 tt(*seed);
515       if (PropagateToX(tt, xTPC, fgkMaxStep)) seed->UpdateTrackParams(&tt, AliESDtrack::kTRDbackup);
516     }
517   }
518   AliInfo(Form("Number of seeds: TRDout[%d]", nseed));
519   AliInfo(Form("Number of tracks: TRDrefit[%d]", found));
520   
521   return 0;
522 }
523
524 //____________________________________________________________________
525 Int_t AliTRDtrackerV1::FollowProlongation(AliTRDtrackV1 &t)
526 {
527   // Extrapolates the TRD track in the TPC direction.
528   //
529   // Parameters
530   //   t : the TRD track which has to be extrapolated
531   // 
532   // Output
533   //   number of clusters attached to the track
534   //
535   // Detailed description
536   //
537   // Starting from current radial position of track <t> this function
538   // extrapolates the track through the 6 TRD layers. The following steps
539   // are being performed for each plane:
540   // 1. prepare track:
541   //   a. get plane limits in the local x direction
542   //   b. check crossing sectors 
543   //   c. check track inclination
544   // 2. search tracklet in the tracker list (see GetTracklet() for details)
545   // 3. evaluate material budget using the geo manager
546   // 4. propagate and update track using the tracklet information.
547   //
548   // Debug level 2
549   //
550   
551   Bool_t kStoreIn = kTRUE;
552   Int_t    nClustersExpected = 0;
553   for (Int_t iplane = kNPlanes; iplane--;) {
554     Int_t   index(-1);
555     AliTRDseedV1 *tracklet = GetTracklet(&t, iplane, index);
556     AliDebug(2, Form("Tracklet[%p] ly[%d] idx[%d]", (void*)tracklet, iplane, index));
557     if(!tracklet) continue;
558     if(!tracklet->IsOK()){ 
559       AliDebug(1, Form("Tracklet Det[%d] !OK", tracklet->GetDetector()));
560       continue;
561     }
562     Double_t x  = tracklet->GetX();//GetX0();
563     // reject tracklets which are not considered for inward refit
564     if(x > t.GetX()+fgkMaxStep) continue;
565
566     // append tracklet to track
567     t.SetTracklet(tracklet, index);
568     
569     if (x < (t.GetX()-fgkMaxStep) && !PropagateToX(t, x+fgkMaxStep, fgkMaxStep)) break;
570     if (!AdjustSector(&t)) break;
571     
572     // Start global position
573     Double_t xyz0[3];
574     t.GetXYZ(xyz0);
575
576     // End global position
577     Double_t alpha = t.GetAlpha(), y, z;
578     if (!t.GetProlongation(x,y,z)) break;    
579     Double_t xyz1[3];
580     xyz1[0] =  x * TMath::Cos(alpha) - y * TMath::Sin(alpha);
581     xyz1[1] =  x * TMath::Sin(alpha) + y * TMath::Cos(alpha);
582     xyz1[2] =  z;
583         
584     Double_t length = TMath::Sqrt(
585       (xyz0[0]-xyz1[0])*(xyz0[0]-xyz1[0]) +
586       (xyz0[1]-xyz1[1])*(xyz0[1]-xyz1[1]) +
587       (xyz0[2]-xyz1[2])*(xyz0[2]-xyz1[2])
588     );
589     if(length>0.){
590       // Get material budget
591       Double_t param[7];
592       if(AliTracker::MeanMaterialBudget(xyz0, xyz1, param)<=0.) break;
593       Double_t xrho= param[0]*param[4];
594       Double_t xx0 = param[1]; // Get mean propagation parameters
595   
596       // Propagate and update           
597       t.PropagateTo(x, xx0, xrho);
598       if (!AdjustSector(&t)) break;
599     }
600     if(kStoreIn){
601       t.SetTrackHigh(); 
602       kStoreIn = kFALSE;
603     }
604
605     Double_t cov[3]; tracklet->GetCovAt(x, cov);
606     Double_t p[2] = { tracklet->GetY(), tracklet->GetZ()};
607     Double_t chi2 = ((AliExternalTrackParam)t).GetPredictedChi2(p, cov);
608     if (chi2 < 1e+10 && t.Update(p, cov, chi2)){ 
609       nClustersExpected += tracklet->GetN();
610     }
611   }
612
613   if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 1){
614     Int_t index;
615     for(int iplane=0; iplane<AliTRDgeometry::kNlayer; iplane++){
616       AliTRDseedV1 *tracklet = GetTracklet(&t, iplane, index);
617       if(!tracklet) continue;
618       t.SetTracklet(tracklet, index);
619     }
620
621     if(fkReconstructor->IsDebugStreaming()){
622       Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
623       TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
624       AliTRDtrackV1 track(t);
625       track.SetOwner();
626       cstreamer << "FollowProlongation"
627           << "EventNumber="     << eventNumber
628           << "ncl="                                     << nClustersExpected
629           << "track.="                  << &track
630           << "\n";
631     }
632   }
633   return nClustersExpected;
634
635 }
636
637 //_____________________________________________________________________________
638 Int_t AliTRDtrackerV1::FollowBackProlongation(AliTRDtrackV1 &t)
639 {
640 // Extrapolates/Build the TRD track in the TOF direction.
641 //
642 // Parameters
643 //   t : the TRD track which has to be extrapolated
644 // 
645 // Output
646 //   number of clusters attached to the track
647 //
648 // Starting from current radial position of track <t> this function
649 // extrapolates the track through the 6 TRD layers. The following steps
650 // are being performed for each plane:
651 // 1. Propagate track to the entrance of the next chamber:
652 //   - get chamber limits in the radial direction
653 //   - check crossing sectors 
654 //   - check track inclination
655 //   - check track prolongation against boundary conditions (see exclusion boundaries on AliTRDgeometry::IsOnBoundary())
656 // 2. Build tracklet (see AliTRDseed::AttachClusters() for details) for this layer if needed. If only 
657 //    Kalman filter is needed and tracklets are already linked to the track this step is skipped.
658 // 3. Fit tracklet using the information from the Kalman filter.
659 // 4. Propagate and update track at reference radial position of the tracklet.
660 // 5. Register tracklet with the tracker and track; update pulls monitoring.
661 //
662 // Observation
663 //   1. During the propagation a bit map is filled detailing the status of the track in each TRD chamber. The following errors are being registered for each tracklet:
664 // - AliTRDtrackV1::kProlongation : track prolongation failed
665 // - AliTRDtrackV1::kPropagation : track prolongation failed
666 // - AliTRDtrackV1::kAdjustSector : failed during sector crossing
667 // - AliTRDtrackV1::kSnp : too large bending
668 // - AliTRDtrackV1::kTrackletInit : fail to initialize tracklet
669 // - AliTRDtrackV1::kUpdate : fail to attach clusters or fit the tracklet
670 // - AliTRDtrackV1::kUnknown : anything which is not covered before
671 //   2. By default the status of the track before first TRD update is saved. 
672 // 
673 // Debug level 2
674 //
675 // Author
676 //   Alexandru Bercuci <A.Bercuci@gsi.de>
677 //
678
679   Int_t n = 0;
680   Double_t driftLength = .5*AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick();
681   AliTRDtrackingChamber *chamber = NULL;
682   
683   Int_t debugLevel = fkReconstructor->IsDebugStreaming() ? fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) : 0;
684   TTreeSRedirector *cstreamer = fkReconstructor->IsDebugStreaming() ? fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker) : 0x0;
685
686   AliTRDseedV1 tracklet, *ptrTracklet = NULL;
687   // in case of stand alone tracking we store all the pointers to the tracklets in a temporary array
688   AliTRDseedV1 *tracklets[kNPlanes];
689   memset(tracklets, 0, sizeof(AliTRDseedV1 *) * kNPlanes);
690   for(Int_t ip = 0; ip < kNPlanes; ip++){
691     tracklets[ip] = t.GetTracklet(ip);
692     t.UnsetTracklet(ip);
693   } 
694   Bool_t kStoreIn = kTRUE, kPropagateIn = kTRUE;
695
696   // Loop through the TRD layers
697   TGeoHMatrix *matrix = NULL;
698   Double_t x, y, z;
699   for (Int_t ily=0, sm=-1, stk=-1, det=-1; ily < AliTRDgeometry::kNlayer; ily++) {
700     AliDebug(2, Form("Propagate to x[%d] = %7.2f", ily, fR[ily]));
701
702     // rough estimate of the entry point
703     if (!t.GetProlongation(fR[ily], y, z)){
704       n=-1; 
705       t.SetStatus(AliTRDtrackV1::kProlongation);
706       AliDebug(4, Form("Failed Rough Prolongation to ly[%d] x[%7.2f] y[%7.2f] z[%7.2f]", ily, fR[ily], y, z));
707       break;
708     }
709
710     // find sector / stack / detector
711     sm = t.GetSector();
712     // TODO cross check with y value !
713     stk = fGeom->GetStack(z, ily);
714     det = stk>=0 ? AliTRDgeometry::GetDetector(ily, stk, sm) : -1;
715     matrix = det>=0 ? fGeom->GetClusterMatrix(det) : NULL;
716     AliDebug(3, Form("Propagate to det[%3d]", det));
717
718     // check if supermodule/chamber is installed
719     if( !fGeom->GetSMstatus(sm) ||
720         stk<0. ||
721         fGeom->IsHole(ily, stk, sm) ||
722         !matrix ){ 
723       AliDebug(4, Form("Missing Geometry ly[%d]. Guess radial position", ily));
724       // propagate to the default radial position
725       if(fR[ily] > (fgkMaxStep + t.GetX()) && !PropagateToX(t, fR[ily], fgkMaxStep)){
726         n=-1; 
727         t.SetStatus(AliTRDtrackV1::kPropagation);
728         AliDebug(4, "Failed Propagation [Missing Geometry]");
729         break;
730       }
731       if(!AdjustSector(&t)){
732         n=-1; 
733         t.SetStatus(AliTRDtrackV1::kAdjustSector);
734         AliDebug(4, "Failed Adjust Sector [Missing Geometry]");
735         break;
736       }
737       if(TMath::Abs(t.GetSnp()) > fgkMaxSnp){
738         n=-1; 
739         t.SetStatus(AliTRDtrackV1::kSnp);
740         AliDebug(4, "Failed Max Snp [Missing Geometry]");
741         break;
742       }
743       t.SetStatus(AliTRDtrackV1::kGeometry, ily);
744       continue;
745     }
746
747     // retrieve rotation matrix for the current chamber
748     Double_t loc[] = {AliTRDgeometry::AnodePos()- driftLength, 0., 0.};
749     Double_t glb[] = {0., 0., 0.};
750     matrix->LocalToMaster(loc, glb);
751
752     // Propagate to the radial distance of the current layer
753     x = glb[0] - fgkMaxStep;
754     if(x > (fgkMaxStep + t.GetX()) && !PropagateToX(t, x, fgkMaxStep)){
755       n=-1; 
756       t.SetStatus(AliTRDtrackV1::kPropagation);
757       AliDebug(4, Form("Failed Initial Propagation to x[%7.2f]", x));
758       break;
759     }
760     if(!AdjustSector(&t)){
761       n=-1; 
762       t.SetStatus(AliTRDtrackV1::kAdjustSector);
763       AliDebug(4, "Failed Adjust Sector Start");
764       break;
765     }
766     if(TMath::Abs(t.GetSnp()) > fgkMaxSnp) {
767       n=-1; 
768       t.SetStatus(AliTRDtrackV1::kSnp);
769       AliDebug(4, Form("Failed Max Snp[%f] MaxSnp[%f]", t.GetSnp(), fgkMaxSnp));
770       break;
771     }
772     Bool_t doRecalculate = kFALSE;
773     if(sm != t.GetSector()){
774       sm = t.GetSector(); 
775       doRecalculate = kTRUE;
776     }
777     if(stk != fGeom->GetStack(z, ily)){
778       stk = fGeom->GetStack(z, ily);
779       doRecalculate = kTRUE;
780     }
781     if(doRecalculate){
782       det = AliTRDgeometry::GetDetector(ily, stk, sm);
783       if(!(matrix = fGeom->GetClusterMatrix(det))){ 
784         t.SetStatus(AliTRDtrackV1::kGeometry, ily);
785         AliDebug(4, Form("Failed Geometry Matrix ly[%d]", ily));
786         continue;
787       }
788       matrix->LocalToMaster(loc, glb);
789       x = glb[0] - fgkMaxStep;
790     }
791
792     // check if track is well inside fiducial volume 
793     if (!t.GetProlongation(x+fgkMaxStep, y, z)) {
794       n=-1; 
795       t.SetStatus(AliTRDtrackV1::kProlongation);
796       AliDebug(4, Form("Failed Prolongation to x[%7.2f] y[%7.2f] z[%7.2f]", x+fgkMaxStep, y, z));
797       break;
798     }
799     if(fGeom->IsOnBoundary(det, y, z, .5)){ 
800       t.SetStatus(AliTRDtrackV1::kBoundary, ily);
801       AliDebug(4, "Failed Track on Boundary");
802       continue;
803     }
804     // mark track as entering the FIDUCIAL volume of TRD
805     if(kStoreIn){
806       t.SetTrackLow(); 
807       kStoreIn = kFALSE;
808     }
809
810     ptrTracklet  = tracklets[ily];
811     if(!ptrTracklet){ // BUILD TRACKLET
812       AliDebug(3, Form("Building tracklet det[%d]", det));
813       // check data in supermodule
814       if(!fTrSec[sm].GetNChambers()){ 
815         t.SetStatus(AliTRDtrackV1::kNoClusters, ily);
816         AliDebug(4, "Failed NoClusters");
817         continue;
818       }
819       if(fTrSec[sm].GetX(ily) < 1.){ 
820         t.SetStatus(AliTRDtrackV1::kNoClusters, ily);
821         AliDebug(4, "Failed NoX");
822         continue;
823       }
824       
825       // check data in chamber
826       if(!(chamber = fTrSec[sm].GetChamber(stk, ily))){ 
827         t.SetStatus(AliTRDtrackV1::kNoClusters, ily);
828         AliDebug(4, "Failed No Detector");
829         continue;
830       }
831       if(chamber->GetNClusters() < fgNTimeBins*fkReconstructor->GetRecoParam() ->GetFindableClusters()){ 
832         t.SetStatus(AliTRDtrackV1::kNoClusters, ily);
833         AliDebug(4, "Failed Not Enough Clusters in Detector");
834         continue;
835       }      
836       // build tracklet
837       ptrTracklet = new(&tracklet) AliTRDseedV1(det);
838       ptrTracklet->SetReconstructor(fkReconstructor);
839       ptrTracklet->SetKink(t.IsKink());
840       ptrTracklet->SetPadPlane(fGeom->GetPadPlane(ily, stk));
841       ptrTracklet->SetX0(glb[0]+driftLength);
842       if(!tracklet.Init(&t)){
843         n=-1; 
844         t.SetStatus(AliTRDtrackV1::kTrackletInit);
845         AliDebug(4, "Failed Tracklet Init");
846         break;
847       }
848       if(!tracklet.AttachClusters(chamber, kTRUE)){   
849         t.SetStatus(AliTRDtrackV1::kNoAttach, ily);
850         if(debugLevel>3){
851           AliTRDseedV1 trackletCp(*ptrTracklet);
852           UChar_t status(t.GetStatusTRD(ily));
853           (*cstreamer)   << "FollowBackProlongation2"
854           <<"status="    << status
855           <<"tracklet.=" << &trackletCp
856           << "\n";
857         }
858         AliDebug(4, "Failed Attach Clusters");
859         continue;
860       }
861       AliDebug(3, Form("Number of Clusters in Tracklet: %d", tracklet.GetN()));
862       if(tracklet.GetN() < fgNTimeBins*fkReconstructor->GetRecoParam() ->GetFindableClusters()){
863         t.SetStatus(AliTRDtrackV1::kNoClustersTracklet, ily);
864         if(debugLevel>3){
865           AliTRDseedV1 trackletCp(*ptrTracklet);
866           UChar_t status(t.GetStatusTRD(ily));
867           (*cstreamer)   << "FollowBackProlongation2"
868           <<"status="    << status
869           <<"tracklet.=" << &trackletCp
870           << "\n";
871         }
872         AliDebug(4, "Failed N Clusters Attached");
873         continue;
874       }
875       ptrTracklet->UpdateUsed();
876     } else AliDebug(2, Form("Use external tracklet ly[%d]", ily));
877     // propagate track to the radial position of the tracklet
878     ptrTracklet->UseClusters(); // TODO ? do we need this here ?
879     // fit tracklet no tilt correction
880     if(!ptrTracklet->Fit(kFALSE)){
881       t.SetStatus(AliTRDtrackV1::kNoFit, ily);
882       AliDebug(4, "Failed Tracklet Fit");
883       continue;
884     } 
885     x = ptrTracklet->GetX(); //GetX0();
886     if(x > (fgkMaxStep + t.GetX()) && !PropagateToX(t, x, fgkMaxStep)) {
887       n=-1; 
888       t.SetStatus(AliTRDtrackV1::kPropagation);
889       AliDebug(4, Form("Failed Propagation to Tracklet x[%7.2f]", x));
890       break;
891     }
892     if(!AdjustSector(&t)) {
893       n=-1; 
894       t.SetStatus(AliTRDtrackV1::kAdjustSector);
895       AliDebug(4, "Failed Adjust Sector");
896       break;
897     }
898     if(TMath::Abs(t.GetSnp()) > fgkMaxSnp) {
899       n=-1; 
900       t.SetStatus(AliTRDtrackV1::kSnp);
901       AliDebug(4, Form("Failed Max Snp[%f] MaxSnp[%f]", t.GetSnp(), fgkMaxSnp));
902       break;
903     }
904     if(kPropagateIn){
905       t.SetTrackLow(); 
906       kPropagateIn = kFALSE;
907     }
908     Double_t cov[3]; ptrTracklet->GetCovAt(x, cov);
909     Double_t p[2] = { ptrTracklet->GetY(), ptrTracklet->GetZ()};
910     Double_t chi2 = ((AliExternalTrackParam)t).GetPredictedChi2(p, cov);
911     // update Kalman with the TRD measurement
912     if(chi2>1e+10){ // TODO
913       t.SetStatus(AliTRDtrackV1::kChi2, ily);
914       if(debugLevel > 2){
915         UChar_t status(t.GetStatusTRD());
916         AliTRDseedV1  trackletCp(*ptrTracklet);
917         AliTRDtrackV1 trackCp(t);
918         trackCp.SetOwner();
919         (*cstreamer) << "FollowBackProlongation1"
920             << "status="      << status
921             << "tracklet.="   << &trackletCp
922             << "track.="      << &trackCp
923             << "\n";
924       }
925       AliDebug(4, Form("Failed Chi2[%f]", chi2));
926       continue; 
927     }
928     if(!t.Update(p, cov, chi2)) {
929       n=-1; 
930       t.SetStatus(AliTRDtrackV1::kUpdate);
931       if(debugLevel > 2){
932         UChar_t status(t.GetStatusTRD());
933         AliTRDseedV1  trackletCp(*ptrTracklet);
934         AliTRDtrackV1 trackCp(t);
935         trackCp.SetOwner();
936         (*cstreamer) << "FollowBackProlongation1"
937             << "status="      << status
938             << "tracklet.="   << &trackletCp
939             << "track.="      << &trackCp
940             << "\n";
941       }
942       AliDebug(4, Form("Failed Track Update @ y[%7.2f] z[%7.2f] s2y[%f] s2z[%f] covyz[%f]", p[0], p[1], cov[0], cov[2], cov[1]));
943       break;
944     }
945     // fill residuals ?!
946     AliTracker::FillResiduals(&t, p, cov, ptrTracklet->GetVolumeId());
947   
948
949     // load tracklet to the tracker
950     ptrTracklet->Update(&t);
951     ptrTracklet = SetTracklet(ptrTracklet);
952     Int_t index(fTracklets->GetEntriesFast()-1);
953     t.SetTracklet(ptrTracklet, index);
954     n += ptrTracklet->GetN();
955     AliDebug(2, Form("Setting Tracklet[%d] @ Idx[%d]", ily, index));
956
957     // Reset material budget if 2 consecutive gold
958 //     if(ilayer>0 && t.GetTracklet(ilayer-1) && ptrTracklet->GetN() + t.GetTracklet(ilayer-1)->GetN() > 20) t.SetBudget(2, 0.);
959
960     // Make backup of the track until is gold
961     // TO DO update quality check of the track.
962     // consider comparison with fTimeBinsRange
963     Float_t ratio0 = ptrTracklet->GetN() / Float_t(fgNTimeBins);
964     //Float_t ratio1 = Float_t(t.GetNumberOfClusters()+1) / Float_t(t.GetNExpected()+1);        
965     
966     if( (chi2                    <  18.0) &&  
967         (ratio0                  >   0.8) && 
968         //(ratio1                  >   0.6) && 
969         //(ratio0+ratio1           >   1.5) && 
970         (t.GetNCross()           ==    0) && 
971         (TMath::Abs(t.GetSnp())  <  0.85) &&
972         (t.GetNumberOfClusters() >    20)){
973       t.MakeBackupTrack();
974     }
975   } // end layers loop
976   //printf("clusters[%d] chi2[%f] x[%f] status[%d ", n, t.GetChi2(), t.GetX(), t.GetStatusTRD());
977   //for(int i=0; i<6; i++) printf("%d ", t.GetStatusTRD(i)); printf("]\n");
978
979   if(debugLevel > 1){
980     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
981     AliTRDtrackV1 track(t);
982     track.SetOwner();
983     (*cstreamer) << "FollowBackProlongation0"
984         << "EventNumber=" << eventNumber
985         << "ncl="         << n
986         << "track.="      << &track
987         << "\n";
988   }
989   
990   return n;
991 }
992
993 //_________________________________________________________________________
994 Float_t AliTRDtrackerV1::FitRieman(AliTRDseedV1 *tracklets, Double_t *chi2, Int_t *const planes){
995   //
996   // Fits a Riemann-circle to the given points without tilting pad correction.
997   // The fit is performed using an instance of the class AliRieman (equations 
998   // and transformations see documentation of this class)
999   // Afterwards all the tracklets are Updated
1000   //
1001   // Parameters: - Array of tracklets (AliTRDseedV1)
1002   //             - Storage for the chi2 values (beginning with direction z)  
1003   //             - Seeding configuration
1004   // Output:     - The curvature
1005   //
1006   AliRieman *fitter = AliTRDtrackerV1::GetRiemanFitter();
1007   fitter->Reset();
1008   Int_t allplanes[] = {0, 1, 2, 3, 4, 5};
1009   Int_t *ppl = &allplanes[0];
1010   Int_t maxLayers = 6;
1011   if(planes){
1012     maxLayers = 4;
1013     ppl = planes;
1014   }
1015   for(Int_t il = 0; il < maxLayers; il++){
1016     if(!tracklets[ppl[il]].IsOK()) continue;
1017     fitter->AddPoint(tracklets[ppl[il]].GetX0(), tracklets[ppl[il]].GetYfit(0), tracklets[ppl[il]].GetZfit(0),1,10);
1018   }
1019   fitter->Update();
1020   // Set the reference position of the fit and calculate the chi2 values
1021   memset(chi2, 0, sizeof(Double_t) * 2);
1022   for(Int_t il = 0; il < maxLayers; il++){
1023     // Reference positions
1024     tracklets[ppl[il]].Init(fitter);
1025     
1026     // chi2
1027     if((!tracklets[ppl[il]].IsOK()) && (!planes)) continue;
1028     chi2[0] += tracklets[ppl[il]].GetChi2Y();
1029     chi2[1] += tracklets[ppl[il]].GetChi2Z();
1030   }
1031   return fitter->GetC();
1032 }
1033
1034 //_________________________________________________________________________
1035 void AliTRDtrackerV1::FitRieman(AliTRDcluster **seedcl, Double_t chi2[2])
1036 {
1037   //
1038   // Performs a Riemann helix fit using the seedclusters as spacepoints
1039   // Afterwards the chi2 values are calculated and the seeds are updated
1040   //
1041   // Parameters: - The four seedclusters
1042   //             - The tracklet array (AliTRDseedV1)
1043   //             - The seeding configuration
1044   //             - Chi2 array
1045   //
1046   // debug level 2
1047   //
1048   AliRieman *fitter = AliTRDtrackerV1::GetRiemanFitter();
1049   fitter->Reset();
1050   for(Int_t i = 0; i < 4; i++){
1051     fitter->AddPoint(seedcl[i]->GetX(), seedcl[i]->GetY(), seedcl[i]->GetZ(), 1., 10.);
1052   }
1053   fitter->Update();
1054   
1055   
1056   // Update the seed and calculated the chi2 value
1057   chi2[0] = 0; chi2[1] = 0;
1058   for(Int_t ipl = 0; ipl < kNSeedPlanes; ipl++){
1059     // chi2
1060     chi2[0] += (seedcl[ipl]->GetZ() - fitter->GetZat(seedcl[ipl]->GetX())) * (seedcl[ipl]->GetZ() - fitter->GetZat(seedcl[ipl]->GetX()));
1061     chi2[1] += (seedcl[ipl]->GetY() - fitter->GetYat(seedcl[ipl]->GetX())) * (seedcl[ipl]->GetY() - fitter->GetYat(seedcl[ipl]->GetX()));
1062   }     
1063 }
1064
1065
1066 //_________________________________________________________________________
1067 Float_t AliTRDtrackerV1::FitTiltedRiemanConstraint(AliTRDseedV1 *tracklets, Double_t zVertex)
1068 {
1069   //
1070   // Fits a helix to the clusters. Pad tilting is considered. As constraint it is 
1071   // assumed that the vertex position is set to 0.
1072   // This method is very usefull for high-pt particles
1073   // Basis for the fit: (x - x0)^2 + (y - y0)^2 - R^2 = 0
1074   //      x0, y0: Center of the circle
1075   // Measured y-position: ymeas = y - tan(phiT)(zc - zt)
1076   //      zc: center of the pad row
1077   // Equation which has to be fitted (after transformation):
1078   // a + b * u + e * v + 2*(ymeas + tan(phiT)(z - zVertex))*t = 0
1079   // Transformation:
1080   // t = 1/(x^2 + y^2)
1081   // u = 2 * x * t
1082   // v = 2 * x * tan(phiT) * t
1083   // Parameters in the equation: 
1084   //    a = -1/y0, b = x0/y0, e = dz/dx
1085   //
1086   // The Curvature is calculated by the following equation:
1087   //               - curv = a/Sqrt(b^2 + 1) = 1/R
1088   // Parameters:   - the 6 tracklets
1089   //               - the Vertex constraint
1090   // Output:       - the Chi2 value of the track
1091   //
1092   // debug level 5
1093   //
1094
1095   TLinearFitter *fitter = GetTiltedRiemanFitterConstraint();
1096   fitter->StoreData(kTRUE);
1097   fitter->ClearPoints();
1098   AliTRDcluster *cl = NULL;
1099   
1100   Float_t x, y, z, w, t, error, tilt;
1101   Double_t uvt[2];
1102   Int_t nPoints = 0;
1103   for(Int_t ilr = 0; ilr < AliTRDgeometry::kNlayer; ilr++){
1104     if(!tracklets[ilr].IsOK()) continue;
1105     for(Int_t itb = 0; itb < AliTRDseedV1::kNclusters; itb++){
1106       if(!tracklets[ilr].IsUsable(itb)) continue;
1107       cl = tracklets[ilr].GetClusters(itb);
1108       if(!cl->IsInChamber()) continue;
1109       x = cl->GetX();
1110       y = cl->GetY();
1111       z = cl->GetZ();
1112       tilt = tracklets[ilr].GetTilt();
1113       // Transformation
1114       t = 1./(x * x + y * y);
1115       uvt[0] = 2. * x * t;
1116       uvt[1] = 2. * x * t * tilt ;
1117       w = 2. * (y + tilt * (z - zVertex)) * t;
1118       error = 2. * TMath::Sqrt(cl->GetSigmaY2()+tilt*tilt*cl->GetSigmaZ2()) * t;
1119       fitter->AddPoint(uvt, w, error);
1120       nPoints++;
1121     }
1122   }
1123   fitter->Eval();
1124
1125   // Calculate curvature
1126   Double_t a = fitter->GetParameter(0);
1127   Double_t b = fitter->GetParameter(1);
1128   Double_t curvature = a/TMath::Sqrt(b*b + 1);
1129
1130   Float_t chi2track = fitter->GetChisquare()/Double_t(nPoints);
1131   for(Int_t ip = 0; ip < AliTRDtrackerV1::kNPlanes; ip++)
1132     tracklets[ip].SetC(curvature);
1133
1134 /*  if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker()) >= 5){
1135     //Linear Model on z-direction
1136     Double_t xref = CalculateReferenceX(tracklets);             // Relative to the middle of the stack
1137     Double_t slope = fitter->GetParameter(2);
1138     Double_t zref = slope * xref;
1139     Float_t chi2Z = CalculateChi2Z(tracklets, zref, slope, xref);
1140     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
1141     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
1142     TTreeSRedirector &treeStreamer = *fkReconstructor->GetDebugStream(AliTRDReconstructor::kTracker);
1143     treeStreamer << "FitTiltedRiemanConstraint"
1144     << "EventNumber="           << eventNumber
1145     << "CandidateNumber="       << candidateNumber
1146     << "Curvature="                             << curvature
1147     << "Chi2Track="                             << chi2track
1148     << "Chi2Z="                                         << chi2Z
1149     << "zref="                                          << zref
1150     << "\n";
1151   }*/
1152   return chi2track;
1153 }
1154
1155 //_________________________________________________________________________
1156 Float_t AliTRDtrackerV1::FitTiltedRieman(AliTRDseedV1 *tracklets, Bool_t sigError)
1157 {
1158   //
1159   // Performs a Riemann fit taking tilting pad correction into account
1160   // The equation of a Riemann circle, where the y position is substituted by the 
1161   // measured y-position taking pad tilting into account, has to be transformed
1162   // into a 4-dimensional hyperplane equation
1163   // Riemann circle: (x-x0)^2 + (y-y0)^2 -R^2 = 0
1164   // Measured y-Position: ymeas = y - tan(phiT)(zc - zt)
1165   //          zc: center of the pad row
1166   //          zt: z-position of the track
1167   // The z-position of the track is assumed to be linear dependent on the x-position
1168   // Transformed equation: a + b * u + c * t + d * v  + e * w - 2 * (ymeas + tan(phiT) * zc) * t = 0
1169   // Transformation:       u = 2 * x * t
1170   //                       v = 2 * tan(phiT) * t
1171   //                       w = 2 * tan(phiT) * (x - xref) * t
1172   //                       t = 1 / (x^2 + ymeas^2)
1173   // Parameters:           a = -1/y0
1174   //                       b = x0/y0
1175   //                       c = (R^2 -x0^2 - y0^2)/y0
1176   //                       d = offset
1177   //                       e = dz/dx
1178   // If the offset respectively the slope in z-position is impossible, the parameters are fixed using 
1179   // results from the simple riemann fit. Afterwards the fit is redone.
1180   // The curvature is calculated according to the formula:
1181   //                       curv = a/(1 + b^2 + c*a) = 1/R
1182   //
1183   // Paramters:   - Array of tracklets (connected to the track candidate)
1184   //              - Flag selecting the error definition
1185   // Output:      - Chi2 values of the track (in Parameter list)
1186   //
1187   TLinearFitter *fitter = GetTiltedRiemanFitter();
1188   fitter->StoreData(kTRUE);
1189   fitter->ClearPoints();
1190   AliTRDLeastSquare zfitter;
1191   AliTRDcluster *cl = NULL;
1192
1193   Double_t xref = CalculateReferenceX(tracklets);
1194   Double_t x, y, z, t, tilt, dx, w, we, erry, errz;
1195   Double_t uvt[4], sumPolY[5], sumPolZ[3];
1196   memset(sumPolY, 0, sizeof(Double_t) * 5);
1197   memset(sumPolZ, 0, sizeof(Double_t) * 3);
1198   Int_t nPoints = 0;
1199   // Containers for Least-square fitter
1200   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1201     if(!tracklets[ipl].IsOK()) continue;
1202     tilt = tracklets[ipl].GetTilt();
1203     for(Int_t itb = 0; itb < AliTRDseedV1::kNclusters; itb++){
1204       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
1205       if(!cl->IsInChamber()) continue;
1206       if (!tracklets[ipl].IsUsable(itb)) continue;
1207       x = cl->GetX();
1208       y = cl->GetY();
1209       z = cl->GetZ();
1210       dx = x - xref;
1211       // Transformation
1212       t = 1./(x*x + y*y);
1213       uvt[0] = 2. * x * t;
1214       uvt[1] = t;
1215       uvt[2] = 2. * tilt * t;
1216       uvt[3] = 2. * tilt * dx * t;
1217       w = 2. * (y + tilt*z) * t;
1218       // error definition changes for the different calls
1219       we = 2. * t;
1220       we *= sigError ? TMath::Sqrt(cl->GetSigmaY2()+tilt*tilt*cl->GetSigmaZ2()) : 0.2;
1221       fitter->AddPoint(uvt, w, we);
1222       zfitter.AddPoint(&x, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
1223       // adding points for covariance matrix estimation
1224       erry = 1./(TMath::Sqrt(cl->GetSigmaY2()) + 0.1);  // 0.1 is a systematic error (due to misalignment and miscalibration)
1225       erry *= erry;
1226       errz = 1./cl->GetSigmaZ2();
1227       for(Int_t ipol = 0; ipol < 5; ipol++){
1228         sumPolY[ipol] += erry;
1229         erry *= x;
1230         if(ipol < 3){
1231           sumPolZ[ipol] += errz;
1232           errz *= x;
1233         }
1234       }
1235       nPoints++;
1236     }
1237   }
1238   fitter->Eval();
1239   zfitter.Eval();
1240
1241   Double_t offset = fitter->GetParameter(3);
1242   Double_t slope  = fitter->GetParameter(4);
1243
1244   // Linear fitter  - not possible to make boundaries
1245   // Do not accept non possible z and dzdx combinations
1246   Bool_t acceptablez = kTRUE;
1247   Double_t zref = 0.0;
1248   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
1249     if(!tracklets[iLayer].IsOK()) continue;
1250     zref = offset + slope * (tracklets[iLayer].GetX0() - xref);
1251     if (TMath::Abs(tracklets[iLayer].GetZfit(0) - zref) > tracklets[iLayer].GetPadLength() * 0.5 + 1.0) 
1252       acceptablez = kFALSE;
1253   }
1254   if (!acceptablez) {
1255     Double_t dzmf       = zfitter.GetFunctionParameter(1);
1256     Double_t zmf        = zfitter.GetFunctionValue(&xref);
1257     fgTiltedRieman->FixParameter(3, zmf);
1258     fgTiltedRieman->FixParameter(4, dzmf);
1259     fitter->Eval();
1260     fitter->ReleaseParameter(3);
1261     fitter->ReleaseParameter(4);
1262     offset = fitter->GetParameter(3);
1263     slope = fitter->GetParameter(4);
1264   }
1265
1266   // Calculate Curvarture
1267   Double_t a     =  fitter->GetParameter(0);
1268   Double_t b     =  fitter->GetParameter(1);
1269   Double_t c     =  fitter->GetParameter(2);
1270   Double_t curvature =  1.0 + b*b - c*a;
1271   if (curvature > 0.0) 
1272     curvature  =  a / TMath::Sqrt(curvature);
1273
1274   Double_t chi2track = fitter->GetChisquare()/Double_t(nPoints);
1275
1276   // Prepare error calculation
1277   TMatrixD covarPolY(3,3);
1278   covarPolY(0,0) = sumPolY[0]; covarPolY(1,1) = sumPolY[2]; covarPolY(2,2) = sumPolY[4];
1279   covarPolY(0,1) = covarPolY(1,0) = sumPolY[1];
1280   covarPolY(0,2) = covarPolY(2,0) = sumPolY[2];
1281   covarPolY(2,1) = covarPolY(1,2) = sumPolY[3];
1282   covarPolY.Invert();
1283   TMatrixD covarPolZ(2,2);
1284   covarPolZ(0,0) = sumPolZ[0]; covarPolZ(1,1) = sumPolZ[2];
1285   covarPolZ(1,0) = covarPolZ(0,1) = sumPolZ[1];
1286   covarPolZ.Invert();
1287
1288   // Update the tracklets
1289   Double_t x1, dy, dz;
1290   Double_t cov[15];
1291   memset(cov, 0, sizeof(Double_t) * 15);
1292   for(Int_t iLayer = 0; iLayer < AliTRDtrackerV1::kNPlanes; iLayer++) {
1293
1294     x  = tracklets[iLayer].GetX0();
1295     x1 = x - xref;
1296     y  = 0;
1297     z  = 0;
1298     dy = 0;
1299     dz = 0;
1300     memset(cov, 0, sizeof(Double_t) * 3);
1301     TMatrixD transform(3,3);
1302     transform(0,0) = 1;
1303     transform(0,1) = x;
1304     transform(0,2) = x*x;
1305     transform(1,1) = 1;
1306     transform(1,2) = x;
1307     transform(2,2) = 1;
1308     TMatrixD covariance(transform, TMatrixD::kMult, covarPolY);
1309     covariance *= transform.T();
1310     TMatrixD transformZ(2,2);
1311     transformZ(0,0) = transformZ(1,1) = 1;
1312     transformZ(0,1) = x;
1313     TMatrixD covarZ(transformZ, TMatrixD::kMult, covarPolZ);
1314     covarZ *= transformZ.T();
1315     // y:     R^2 = (x - x0)^2 + (y - y0)^2
1316     //     =>   y = y0 +/- Sqrt(R^2 - (x - x0)^2)
1317     //          R = Sqrt() = 1/Curvature
1318     //     =>   y = y0 +/- Sqrt(1/Curvature^2 - (x - x0)^2)  
1319     Double_t res = (x * a + b);                                                         // = (x - x0)/y0
1320     res *= res;
1321     res  = 1.0 - c * a + b * b - res;                                   // = (R^2 - (x - x0)^2)/y0^2
1322     if (res >= 0) {
1323       res = TMath::Sqrt(res);
1324       y    = (1.0 - res) / a;
1325     }
1326     cov[0] = covariance(0,0);
1327     cov[2] = covarZ(0,0);
1328     cov[1] = 0.;
1329
1330     // dy:      R^2 = (x - x0)^2 + (y - y0)^2
1331     //     =>     y = +/- Sqrt(R^2 - (x - x0)^2) + y0
1332     //     => dy/dx = (x - x0)/Sqrt(R^2 - (x - x0)^2) 
1333     // Curvature: cr = 1/R = a/Sqrt(1 + b^2 - c*a)
1334     //     => dy/dx =  (x - x0)/(1/(cr^2) - (x - x0)^2) 
1335     Double_t x0 = -b / a;
1336     if (-c * a + b * b + 1 > 0) {
1337       if (1.0/(curvature * curvature) - (x - x0) * (x - x0) > 0.0) {
1338        Double_t yderiv = (x - x0) / TMath::Sqrt(1.0/(curvature * curvature) - (x - x0) * (x - x0));
1339         if (a < 0) yderiv *= -1.0;
1340         dy = yderiv;
1341       }
1342     }
1343     z  = offset + slope * (x - xref);
1344     dz = slope;
1345     tracklets[iLayer].SetYref(0, y);
1346     tracklets[iLayer].SetYref(1, dy);
1347     tracklets[iLayer].SetZref(0, z);
1348     tracklets[iLayer].SetZref(1, dz);
1349     tracklets[iLayer].SetC(curvature);
1350     tracklets[iLayer].SetCovRef(cov);
1351     tracklets[iLayer].SetChi2(chi2track);
1352   }
1353   
1354 /*  if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >=5){
1355     TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
1356     Int_t eventNumber                   = AliTRDtrackerDebug::GetEventNumber();
1357     Int_t candidateNumber       = AliTRDtrackerDebug::GetCandidateNumber();
1358     Double_t chi2z = CalculateChi2Z(tracklets, offset, slope, xref);
1359     cstreamer << "FitTiltedRieman0"
1360         << "EventNumber="                       << eventNumber
1361         << "CandidateNumber="   << candidateNumber
1362         << "xref="                                              << xref
1363         << "Chi2Z="                                             << chi2z
1364         << "\n";
1365   }*/
1366   return chi2track;
1367 }
1368
1369
1370 //____________________________________________________________________
1371 Double_t AliTRDtrackerV1::FitLine(const AliTRDtrackV1 *track, AliTRDseedV1 *tracklets, Bool_t err, Int_t np, AliTrackPoint *points)
1372 {
1373   //
1374   // Fit track with a staight line
1375   // Fills an AliTrackPoint array with np points
1376   // Function should be used to refit tracks when no magnetic field was on
1377   //
1378   AliTRDLeastSquare yfitter, zfitter;
1379   AliTRDcluster *cl = NULL;
1380
1381   AliTRDseedV1 work[kNPlanes], *tracklet = NULL;
1382   if(!tracklets){
1383     for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1384       if(!(tracklet = track->GetTracklet(ipl))) continue;
1385       if(!tracklet->IsOK()) continue;
1386       new(&work[ipl]) AliTRDseedV1(*tracklet);
1387     }
1388     tracklets = &work[0];
1389   }
1390
1391   Double_t xref = CalculateReferenceX(tracklets);
1392   Double_t x, y, z, dx, ye, yr, tilt;
1393   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1394     if(!tracklets[ipl].IsOK()) continue;
1395     for(Int_t itb = 0; itb < fgNTimeBins; itb++){
1396       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
1397       if (!tracklets[ipl].IsUsable(itb)) continue;
1398       x = cl->GetX();
1399       z = cl->GetZ();
1400       dx = x - xref;
1401       zfitter.AddPoint(&dx, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
1402     }
1403   }
1404   zfitter.Eval();
1405   Double_t z0    = zfitter.GetFunctionParameter(0);
1406   Double_t dzdx  = zfitter.GetFunctionParameter(1);
1407   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1408     if(!tracklets[ipl].IsOK()) continue;
1409     for(Int_t itb = 0; itb < fgNTimeBins; itb++){
1410       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
1411       if (!tracklets[ipl].IsUsable(itb)) continue;
1412       x = cl->GetX();
1413       y = cl->GetY();
1414       z = cl->GetZ();
1415       tilt = tracklets[ipl].GetTilt();
1416       dx = x - xref;
1417       yr = y + tilt*(z - z0 - dzdx*dx); 
1418       // error definition changes for the different calls
1419       ye = tilt*TMath::Sqrt(cl->GetSigmaZ2());
1420       ye += err ? tracklets[ipl].GetSigmaY() : 0.2;
1421       yfitter.AddPoint(&dx, yr, ye);
1422     }
1423   }
1424   yfitter.Eval();
1425   Double_t y0   = yfitter.GetFunctionParameter(0);
1426   Double_t dydx = yfitter.GetFunctionParameter(1);
1427   Double_t chi2 = 0.;//yfitter.GetChisquare()/Double_t(nPoints);
1428
1429   //update track points array
1430   if(np && points){
1431     Float_t xyz[3];
1432     for(int ip=0; ip<np; ip++){
1433       points[ip].GetXYZ(xyz);
1434       xyz[1] = y0 + dydx * (xyz[0] - xref);
1435       xyz[2] = z0 + dzdx * (xyz[0] - xref);
1436       points[ip].SetXYZ(xyz);
1437     }
1438   }
1439   return chi2;
1440 }
1441
1442
1443 //_________________________________________________________________________
1444 Double_t AliTRDtrackerV1::FitRiemanTilt(const AliTRDtrackV1 *track, AliTRDseedV1 *tracklets, Bool_t sigError, Int_t np, AliTrackPoint *points)
1445 {
1446 //
1447 // Performs a Riemann fit taking tilting pad correction into account
1448 //
1449 // Paramters:   - Array of tracklets (connected to the track candidate)
1450 //              - Flag selecting the error definition
1451 // Output:      - Chi2 values of the track (in Parameter list)
1452 //
1453 // The equations which has to be solved simultaneously are:
1454 // BEGIN_LATEX
1455 // R^{2} = (x-x_{0})^{2} + (y^{*}-y_{0})^{2}
1456 // y^{*} = y - tg(h)(z - z_{t})
1457 // z_{t} = z_{0}+dzdx*(x-x_{r})
1458 // END_LATEX
1459 // with (x, y, z) the coordinate of the cluster, (x_0, y_0, z_0) the coordinate of the center of the Riemann circle,
1460 // R its radius, x_r a constant refrence radial position in the middle of the TRD stack  and dzdx the slope of the 
1461 // track in the x-z plane. Using the following transformations
1462 // BEGIN_LATEX
1463 // t = 1 / (x^{2} + y^{2})
1464 // u = 2 * x * t
1465 // v = 2 * tan(h) * t
1466 // w = 2 * tan(h) * (x - x_{r}) * t
1467 // END_LATEX
1468 // One gets the following linear equation
1469 // BEGIN_LATEX
1470 // a + b * u + c * t + d * v  + e * w = 2 * (y + tg(h) * z) * t
1471 // END_LATEX
1472 // where the coefficients have the following meaning 
1473 // BEGIN_LATEX
1474 // a = -1/y_{0}
1475 // b = x_{0}/y_{0}
1476 // c = (R^{2} -x_{0}^{2} - y_{0}^{2})/y_{0}
1477 // d = z_{0}
1478 // e = dz/dx
1479 // END_LATEX
1480 // The error calculation for the free term is thus
1481 // BEGIN_LATEX
1482 // #sigma = 2 * #sqrt{#sigma^{2}_{y} + (tilt corr ...) + tg^{2}(h) * #sigma^{2}_{z}} * t
1483 // END_LATEX
1484 //
1485 // From this simple model one can compute chi^2 estimates and a rough approximation of pt from the curvature according 
1486 // to the formula:
1487 // BEGIN_LATEX
1488 // C = 1/R = a/(1 + b^{2} + c*a)
1489 // END_LATEX
1490 //
1491 // Authors
1492 //   M.Ivanov <M.Ivanov@gsi.de>
1493 //   A.Bercuci <A.Bercuci@gsi.de>
1494 //   M.Fasel <M.Fasel@gsi.de>
1495
1496   TLinearFitter *fitter = GetTiltedRiemanFitter();
1497   fitter->StoreData(kTRUE);
1498   fitter->ClearPoints();
1499   AliTRDLeastSquare zfitter;
1500   AliTRDcluster *cl = NULL;
1501
1502   AliTRDseedV1 work[kNPlanes], *tracklet = NULL;
1503   if(!tracklets){
1504     for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1505       if(!(tracklet = track->GetTracklet(ipl))) continue;
1506       if(!tracklet->IsOK()) continue;
1507       new(&work[ipl]) AliTRDseedV1(*tracklet);
1508     }
1509     tracklets = &work[0];
1510   }
1511
1512   Double_t xref = CalculateReferenceX(tracklets);
1513   AliDebugGeneral("AliTRDtrackerV1::FitRiemanTilt()", 4, 
1514   Form("\nx0[(0)%6.2f (1)%6.2f (2)%6.2f (3)%6.2f (4)%6.2f (5)%6.2f] xref[%6.2f]", tracklets[0].GetX0(), tracklets[1].GetX0(), tracklets[2].GetX0(), tracklets[3].GetX0(), tracklets[4].GetX0(), tracklets[5].GetX0(), xref));
1515   Double_t x, y, z, t, tilt, dx, w, we;
1516   Double_t uvt[4];
1517   Int_t nPoints = 0;
1518   // Containers for Least-square fitter
1519   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1520     if(!tracklets[ipl].IsOK()) continue;
1521     for(Int_t itb = 0; itb < AliTRDseedV1::kNclusters; itb++){
1522       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
1523       //if (!tracklets[ipl].IsUsable(itb)) continue;
1524       x = cl->GetX();
1525       y = cl->GetY();
1526       z = cl->GetZ();
1527       tilt = tracklets[ipl].GetTilt();
1528       dx = x - xref;
1529       // Transformation
1530       t = 1./(x*x + y*y);
1531       uvt[0] = 2. * x * t;
1532       uvt[1] = t;
1533       uvt[2] = 2. * tilt * t;
1534       uvt[3] = 2. * tilt * dx * t;
1535       w = 2. * (y + tilt*z) * t;
1536       // error definition changes for the different calls
1537       we = 2. * t;
1538       we *= sigError ? TMath::Sqrt(cl->GetSigmaY2()) : 0.2;
1539       fitter->AddPoint(uvt, w, we);
1540       zfitter.AddPoint(&x, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
1541       nPoints++;
1542     }
1543   }
1544   if(fitter->Eval()) return 1.E10;
1545
1546   Double_t z0    = fitter->GetParameter(3);
1547   Double_t dzdx  = fitter->GetParameter(4);
1548
1549
1550   // Linear fitter  - not possible to make boundaries
1551   // Do not accept non possible z and dzdx combinations
1552   Bool_t accept = kTRUE;
1553   Double_t zref = 0.0;
1554   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
1555     if(!tracklets[iLayer].IsOK()) continue;
1556     zref = z0 + dzdx * (tracklets[iLayer].GetX0() - xref);
1557     if (TMath::Abs(tracklets[iLayer].GetZfit(0) - zref) > tracklets[iLayer].GetPadLength() * 0.5 + 1.0) 
1558       accept = kFALSE;
1559   }
1560   if (!accept) {
1561     zfitter.Eval();
1562     Double_t dzmf       = zfitter.GetFunctionParameter(1);
1563     Double_t zmf        = zfitter.GetFunctionValue(&xref);
1564     fitter->FixParameter(3, zmf);
1565     fitter->FixParameter(4, dzmf);
1566     fitter->Eval();
1567     fitter->ReleaseParameter(3);
1568     fitter->ReleaseParameter(4);
1569     z0   = fitter->GetParameter(3); // = zmf ?
1570     dzdx = fitter->GetParameter(4); // = dzmf ?
1571   }
1572
1573   // Calculate Curvature
1574   Double_t a    =  fitter->GetParameter(0);
1575   Double_t b    =  fitter->GetParameter(1);
1576   Double_t c    =  fitter->GetParameter(2);
1577   Double_t y0   = 1. / a;
1578   Double_t x0   = -b * y0;
1579   Double_t tmp  = y0*y0 + x0*x0 - c*y0;
1580   if(tmp<=0.) return 1.E10;
1581   Double_t radius    = TMath::Sqrt(tmp);
1582   Double_t curvature    =  1.0 + b*b - c*a;
1583   if (curvature > 0.0)  curvature  =  a / TMath::Sqrt(curvature);
1584
1585   // Calculate chi2 of the fit 
1586   Double_t chi2 = fitter->GetChisquare()/Double_t(nPoints);
1587   AliDebugGeneral("AliTRDtrackerV1::FitRiemanTilt()", 4, 
1588   Form("x0[%6.2f] y0[%6.2f] R[%6.2f] chi2[%f]\n", x0, y0, radius, chi2));
1589
1590   // Update the tracklets
1591   if(!track){
1592     for(Int_t ip = 0; ip < kNPlanes; ip++) {
1593       x = tracklets[ip].GetX0();
1594       tmp = radius*radius-(x-x0)*(x-x0);  
1595       if(tmp <= 0.) continue;
1596       tmp = TMath::Sqrt(tmp);  
1597
1598       // y:     R^2 = (x - x0)^2 + (y - y0)^2
1599       //     =>   y = y0 +/- Sqrt(R^2 - (x - x0)^2)
1600       tracklets[ip].SetYref(0, y0 - (y0>0.?1.:-1)*tmp);
1601       //     => dy/dx = (x - x0)/Sqrt(R^2 - (x - x0)^2) 
1602       tracklets[ip].SetYref(1, (x - x0) / tmp);
1603       tracklets[ip].SetZref(0, z0 + dzdx * (x - xref));
1604       tracklets[ip].SetZref(1, dzdx);
1605       tracklets[ip].SetC(curvature);
1606       tracklets[ip].SetChi2(chi2);
1607     }
1608   }
1609   //update track points array
1610   if(np && points){
1611     Float_t xyz[3];
1612     for(int ip=0; ip<np; ip++){
1613       points[ip].GetXYZ(xyz);
1614       xyz[1] = TMath::Abs(xyz[0] - x0) > radius ? 100. : y0 - (y0>0.?1.:-1.)*TMath::Sqrt((radius-(xyz[0]-x0))*(radius+(xyz[0]-x0)));
1615       xyz[2] = z0 + dzdx * (xyz[0] - xref);
1616       points[ip].SetXYZ(xyz);
1617     }
1618   }
1619   
1620   return chi2;
1621 }
1622
1623
1624 //____________________________________________________________________
1625 Double_t AliTRDtrackerV1::FitKalman(AliTRDtrackV1 *track, AliTRDseedV1 * const tracklets, Bool_t up, Int_t np, AliTrackPoint *points)
1626 {
1627 //   Kalman filter implementation for the TRD.
1628 //   It returns the positions of the fit in the array "points"
1629 // 
1630 //   Author : A.Bercuci@gsi.de
1631
1632   // printf("Start track @ x[%f]\n", track->GetX());
1633         
1634   //prepare marker points along the track
1635   Int_t ip = np ? 0 : 1;
1636   while(ip<np){
1637     if((up?-1:1) * (track->GetX() - points[ip].GetX()) > 0.) break;
1638     //printf("AliTRDtrackerV1::FitKalman() : Skip track marker x[%d] = %7.3f. Before track start ( %7.3f ).\n", ip, points[ip].GetX(), track->GetX());
1639     ip++;
1640   }
1641   //if(points) printf("First marker point @ x[%d] = %f\n", ip, points[ip].GetX());
1642
1643
1644   AliTRDseedV1 tracklet, *ptrTracklet = NULL;
1645
1646   //Loop through the TRD planes
1647   for (Int_t jplane = 0; jplane < kNPlanes; jplane++) {
1648     // GET TRACKLET OR BUILT IT         
1649     Int_t iplane = up ? jplane : kNPlanes - 1 - jplane;
1650     if(tracklets){ 
1651       if(!(ptrTracklet = &tracklets[iplane])) continue;
1652     }else{
1653       if(!(ptrTracklet  = track->GetTracklet(iplane))){ 
1654       /*AliTRDtrackerV1 *tracker = NULL;
1655         if(!(tracker = dynamic_cast<AliTRDtrackerV1*>( AliTRDrecoParam:Tracker()))) continue;
1656         ptrTracklet = new(&tracklet) AliTRDseedV1(iplane);
1657         if(!tracker->MakeTracklet(ptrTracklet, track)) */
1658         continue;
1659       }
1660     }
1661     if(!ptrTracklet->IsOK()) continue;
1662
1663     Double_t x = ptrTracklet->GetX0();
1664
1665     while(ip < np){
1666       //don't do anything if next marker is after next update point.
1667       if((up?-1:1) * (points[ip].GetX() - x) - fgkMaxStep < 0) break;
1668       if(((up?-1:1) * (points[ip].GetX() - track->GetX()) < 0) && !PropagateToX(*track, points[ip].GetX(), fgkMaxStep)) return -1.;
1669       
1670       Double_t xyz[3]; // should also get the covariance
1671       track->GetXYZ(xyz);
1672       track->Global2LocalPosition(xyz, track->GetAlpha());
1673       points[ip].SetXYZ(xyz[0], xyz[1], xyz[2]);
1674       ip++;
1675     }
1676     // printf("plane[%d] tracklet[%p] x[%f]\n", iplane, ptrTracklet, x);
1677
1678     // Propagate closer to the next update point 
1679     if(((up?-1:1) * (x - track->GetX()) + fgkMaxStep < 0) && !PropagateToX(*track, x + (up?-1:1)*fgkMaxStep, fgkMaxStep)) return -1.;
1680
1681     if(!AdjustSector(track)) return -1;
1682     if(TMath::Abs(track->GetSnp()) > fgkMaxSnp) return -1;
1683     
1684     //load tracklet to the tracker and the track
1685 /*    Int_t index;
1686     if((index = FindTracklet(ptrTracklet)) < 0){
1687       ptrTracklet = SetTracklet(&tracklet);
1688       index = fTracklets->GetEntriesFast()-1;
1689     }
1690     track->SetTracklet(ptrTracklet, index);*/
1691
1692
1693     // register tracklet to track with tracklet creation !!
1694     // PropagateBack : loaded tracklet to the tracker and update index 
1695     // RefitInward : update index 
1696     // MakeTrack   : loaded tracklet to the tracker and update index 
1697     if(!tracklets) track->SetTracklet(ptrTracklet, -1);
1698     
1699   
1700     //Calculate the mean material budget along the path inside the chamber
1701     Double_t xyz0[3]; track->GetXYZ(xyz0);
1702     Double_t alpha = track->GetAlpha();
1703     Double_t xyz1[3], y, z;
1704     if(!track->GetProlongation(x, y, z)) return -1;
1705     xyz1[0] =  x * TMath::Cos(alpha) - y * TMath::Sin(alpha); 
1706     xyz1[1] = +x * TMath::Sin(alpha) + y * TMath::Cos(alpha);
1707     xyz1[2] =  z;
1708     if(TMath::Abs(xyz0[0] - xyz1[0]) < 1e-3 && TMath::Abs(xyz0[1] - xyz1[1]) < 1e-3) continue; // check wheter we are at the same global x position
1709     Double_t param[7];
1710     if(AliTracker::MeanMaterialBudget(xyz0, xyz1, param) <=0.) break;   
1711     Double_t xrho = param[0]*param[4]; // density*length
1712     Double_t xx0  = param[1]; // radiation length
1713     
1714     //Propagate the track
1715     track->PropagateTo(x, xx0, xrho);
1716     if (!AdjustSector(track)) break;
1717   
1718     //Update track
1719     Double_t cov[3]; ptrTracklet->GetCovAt(x, cov);
1720     Double_t p[2] = { ptrTracklet->GetY(), ptrTracklet->GetZ()};
1721     Double_t chi2 = ((AliExternalTrackParam*)track)->GetPredictedChi2(p, cov);
1722     if(chi2<1e+10) track->Update(p, cov, chi2);
1723     if(!up) continue;
1724
1725                 //Reset material budget if 2 consecutive gold
1726                 if(iplane>0 && track->GetTracklet(iplane-1) && ptrTracklet->GetN() + track->GetTracklet(iplane-1)->GetN() > 20) track->SetBudget(2, 0.);
1727         } // end planes loop
1728
1729   // extrapolation
1730   while(ip < np){
1731     if(((up?-1:1) * (points[ip].GetX() - track->GetX()) < 0) && !PropagateToX(*track, points[ip].GetX(), fgkMaxStep)) return -1.;
1732     
1733     Double_t xyz[3]; // should also get the covariance
1734     track->GetXYZ(xyz); 
1735     track->Global2LocalPosition(xyz, track->GetAlpha());
1736     points[ip].SetXYZ(xyz[0], xyz[1], xyz[2]);
1737     ip++;
1738   }
1739
1740         return track->GetChi2();
1741 }
1742
1743 //_________________________________________________________________________
1744 Float_t AliTRDtrackerV1::CalculateChi2Z(AliTRDseedV1 *tracklets, Double_t offset, Double_t slope, Double_t xref)
1745 {
1746   //
1747   // Calculates the chi2-value of the track in z-Direction including tilting pad correction.
1748   // A linear dependence on the x-value serves as a model.
1749   // The parameters are related to the tilted Riemann fit.
1750   // Parameters: - Array of tracklets (AliTRDseedV1) related to the track candidate
1751   //             - the offset for the reference x
1752   //             - the slope
1753   //             - the reference x position
1754   // Output:     - The Chi2 value of the track in z-Direction
1755   //
1756   Float_t chi2Z = 0, nLayers = 0;
1757   for (Int_t iLayer = 0; iLayer < AliTRDgeometry::kNlayer; iLayer++) {
1758     if(!tracklets[iLayer].IsOK()) continue;
1759     Double_t z = offset + slope * (tracklets[iLayer].GetX0() - xref);
1760     chi2Z += TMath::Abs(tracklets[iLayer].GetZfit(0) - z);
1761     nLayers++;
1762   }
1763   chi2Z /= TMath::Max((nLayers - 3.0),1.0);
1764   return chi2Z;
1765 }
1766
1767 //_____________________________________________________________________________
1768 Int_t AliTRDtrackerV1::PropagateToX(AliTRDtrackV1 &t, Double_t xToGo, Double_t maxStep)
1769 {
1770   //
1771   // Starting from current X-position of track <t> this function
1772   // extrapolates the track up to radial position <xToGo>. 
1773   // Returns 1 if track reaches the plane, and 0 otherwise 
1774   //
1775
1776   const Double_t kEpsilon = 0.00001;
1777
1778   // Current track X-position
1779   Double_t xpos = t.GetX();
1780
1781   // Direction: inward or outward
1782   Double_t dir  = (xpos < xToGo) ? 1.0 : -1.0;
1783
1784   while (((xToGo - xpos) * dir) > kEpsilon) {
1785
1786     Double_t xyz0[3];
1787     Double_t xyz1[3];
1788     Double_t param[7];
1789     Double_t x;
1790     Double_t y;
1791     Double_t z;
1792
1793     // The next step size
1794     Double_t step = dir * TMath::Min(TMath::Abs(xToGo-xpos),maxStep);
1795
1796     // Get the global position of the starting point
1797     t.GetXYZ(xyz0);
1798
1799     // X-position after next step
1800     x = xpos + step;
1801
1802     // Get local Y and Z at the X-position of the next step
1803     if(t.GetProlongation(x,y,z)<0) return 0; // No prolongation possible
1804
1805     // The global position of the end point of this prolongation step
1806     xyz1[0] =  x * TMath::Cos(t.GetAlpha()) - y * TMath::Sin(t.GetAlpha()); 
1807     xyz1[1] = +x * TMath::Sin(t.GetAlpha()) + y * TMath::Cos(t.GetAlpha());
1808     xyz1[2] =  z;
1809
1810     // Calculate the mean material budget between start and
1811     // end point of this prolongation step
1812     if(AliTracker::MeanMaterialBudget(xyz0, xyz1, param)<=0.) return 0;
1813
1814     // Propagate the track to the X-position after the next step
1815     if (!t.PropagateTo(x, param[1], param[0]*param[4])) return 0;
1816
1817     // Rotate the track if necessary
1818     AdjustSector(&t);
1819
1820     // New track X-position
1821     xpos = t.GetX();
1822
1823   }
1824
1825   return 1;
1826
1827 }
1828
1829
1830 //_____________________________________________________________________________
1831 Int_t AliTRDtrackerV1::ReadClusters(TClonesArray* &array, TTree *clusterTree) const
1832 {
1833   //
1834   // Reads AliTRDclusters from the file. 
1835   // The names of the cluster tree and branches 
1836   // should match the ones used in AliTRDclusterizer::WriteClusters()
1837   //
1838
1839   Int_t nsize = Int_t(clusterTree->GetTotBytes() / (sizeof(AliTRDcluster))); 
1840   TObjArray *clusterArray = new TObjArray(nsize+1000); 
1841   
1842   TBranch *branch = clusterTree->GetBranch("TRDcluster");
1843   if (!branch) {
1844     AliError("Can't get the branch !");
1845     return 1;
1846   }
1847   branch->SetAddress(&clusterArray); 
1848   
1849   if(!fClusters){ 
1850     Float_t nclusters =  fkReconstructor->GetRecoParam()->GetNClusters();
1851     if(fkReconstructor->IsHLT()) nclusters /= AliTRDgeometry::kNsector;
1852     array = new TClonesArray("AliTRDcluster", Int_t(nclusters));
1853     array->SetOwner(kTRUE);
1854   }
1855   
1856   // Loop through all entries in the tree
1857   Int_t nEntries   = (Int_t) clusterTree->GetEntries();
1858   Int_t nbytes     = 0;
1859   Int_t ncl        = 0;
1860   AliTRDcluster *c = NULL;
1861   for (Int_t iEntry = 0; iEntry < nEntries; iEntry++) {
1862     // Import the tree
1863     nbytes += clusterTree->GetEvent(iEntry);  
1864     
1865     // Get the number of points in the detector
1866     Int_t nCluster = clusterArray->GetEntriesFast();  
1867     for (Int_t iCluster = 0; iCluster < nCluster; iCluster++) { 
1868       if(!(c = (AliTRDcluster *) clusterArray->UncheckedAt(iCluster))) continue;
1869       new((*fClusters)[ncl++]) AliTRDcluster(*c);
1870       delete (clusterArray->RemoveAt(iCluster)); 
1871     }
1872
1873   }
1874   delete clusterArray;
1875
1876   return 0;
1877 }
1878
1879 //_____________________________________________________________________________
1880 Int_t AliTRDtrackerV1::LoadClusters(TTree *cTree)
1881 {
1882   //
1883   // Fills clusters into TRD tracking sectors
1884   //
1885   
1886   if(!fkReconstructor->IsWritingClusters()){ 
1887     fClusters = AliTRDReconstructor::GetClusters();
1888   } else {
1889     if (ReadClusters(fClusters, cTree)) {
1890       AliError("Problem with reading the clusters !");
1891       return 1;
1892     }
1893   }
1894   SetClustersOwner();
1895
1896   if(!fClusters || !fClusters->GetEntriesFast()){ 
1897     AliInfo("No TRD clusters");
1898     return 1;
1899   }
1900
1901   //Int_t nin = 
1902   BuildTrackingContainers();  
1903
1904   //Int_t ncl  = fClusters->GetEntriesFast();
1905   //AliInfo(Form("Clusters %d [%6.2f %% in the active volume]", ncl, 100.*float(nin)/ncl));
1906
1907   return 0;
1908 }
1909
1910 //_____________________________________________________________________________
1911 Int_t AliTRDtrackerV1::LoadClusters(TClonesArray * const clusters)
1912 {
1913   //
1914   // Fills clusters into TRD tracking sectors
1915   // Function for use in the HLT
1916   
1917   if(!clusters || !clusters->GetEntriesFast()){ 
1918     AliInfo("No TRD clusters");
1919     return 1;
1920   }
1921
1922   fClusters = clusters;
1923   SetClustersOwner();
1924
1925   //Int_t nin = 
1926   BuildTrackingContainers();  
1927
1928   //Int_t ncl  = fClusters->GetEntriesFast();
1929   //AliInfo(Form("Clusters %d [%6.2f %% in the active volume]", ncl, 100.*float(nin)/ncl));
1930
1931   return 0;
1932 }
1933
1934
1935 //____________________________________________________________________
1936 Int_t AliTRDtrackerV1::BuildTrackingContainers()
1937 {
1938 // Building tracking containers for clusters
1939
1940   Int_t nin =0, icl = fClusters->GetEntriesFast();
1941   while (icl--) {
1942     AliTRDcluster *c = (AliTRDcluster *) fClusters->UncheckedAt(icl);
1943     if(c->IsInChamber()) nin++;
1944     if(fkReconstructor->IsHLT()) c->SetRPhiMethod(AliTRDcluster::kCOG);
1945     Int_t detector       = c->GetDetector();
1946     Int_t sector         = fGeom->GetSector(detector);
1947     Int_t stack          = fGeom->GetStack(detector);
1948     Int_t layer          = fGeom->GetLayer(detector);
1949     
1950     fTrSec[sector].GetChamber(stack, layer, kTRUE)->InsertCluster(c, icl);
1951   }
1952
1953   const AliTRDCalDet *cal = AliTRDcalibDB::Instance()->GetT0Det();
1954   for(int isector =0; isector<AliTRDgeometry::kNsector; isector++){ 
1955     if(!fTrSec[isector].GetNChambers()) continue;
1956     fTrSec[isector].Init(fkReconstructor, cal);
1957   }
1958
1959   return nin;
1960 }
1961
1962
1963
1964 //____________________________________________________________________
1965 void AliTRDtrackerV1::UnloadClusters() 
1966
1967 //
1968 // Clears the arrays of clusters and tracks. Resets sectors and timebins 
1969 // If option "force" is also set the containers are also deleted. This is useful 
1970 // in case of HLT
1971
1972   if(fTracks){ 
1973     fTracks->Delete(); 
1974     if(HasRemoveContainers()){delete fTracks; fTracks = NULL;}
1975   }
1976   if(fTracklets){ 
1977     fTracklets->Delete();
1978     if(HasRemoveContainers()){delete fTracklets; fTracklets = NULL;}
1979   }
1980   if(fClusters){ 
1981     if(IsClustersOwner()) fClusters->Delete();
1982     
1983     // save clusters array in the reconstructor for further use.
1984     if(!fkReconstructor->IsWritingClusters()){
1985       AliTRDReconstructor::SetClusters(fClusters);
1986       SetClustersOwner(kFALSE);
1987     } else AliTRDReconstructor::SetClusters(NULL);
1988   }
1989
1990   for (int i = 0; i < AliTRDgeometry::kNsector; i++) fTrSec[i].Clear();
1991
1992   // Increment the Event Number
1993   AliTRDtrackerDebug::SetEventNumber(AliTRDtrackerDebug::GetEventNumber()  + 1);
1994 }
1995
1996 // //____________________________________________________________________
1997 // void AliTRDtrackerV1::UseClusters(const AliKalmanTrack *t, Int_t) const
1998 // {
1999 //   const AliTRDtrackV1 *track = dynamic_cast<const AliTRDtrackV1*>(t);
2000 //   if(!track) return;
2001 // 
2002 //   AliTRDseedV1 *tracklet = NULL;
2003 //   for(Int_t ily=AliTRDgeometry::kNlayer; ily--;){
2004 //     if(!(tracklet = track->GetTracklet(ily))) continue;
2005 //     AliTRDcluster *c = NULL;
2006 //     for(Int_t ic=AliTRDseed::kNclusters; ic--;){
2007 //       if(!(c=tracklet->GetClusters(ic))) continue;
2008 //       c->Use();
2009 //     }
2010 //   }
2011 // }
2012 // 
2013
2014 //_____________________________________________________________________________
2015 Bool_t AliTRDtrackerV1::AdjustSector(AliTRDtrackV1 *const track) 
2016 {
2017   //
2018   // Rotates the track when necessary
2019   //
2020
2021   Double_t alpha = AliTRDgeometry::GetAlpha(); 
2022   Double_t y     = track->GetY();
2023   Double_t ymax  = track->GetX()*TMath::Tan(0.5*alpha);
2024   
2025   if      (y >  ymax) {
2026     if (!track->Rotate( alpha)) {
2027       return kFALSE;
2028     }
2029   } 
2030   else if (y < -ymax) {
2031     if (!track->Rotate(-alpha)) {
2032       return kFALSE;   
2033     }
2034   } 
2035
2036   return kTRUE;
2037
2038 }
2039
2040
2041 //____________________________________________________________________
2042 AliTRDseedV1* AliTRDtrackerV1::GetTracklet(AliTRDtrackV1 *const track, Int_t p, Int_t &idx)
2043 {
2044   // Find tracklet for TRD track <track>
2045   // Parameters
2046   // - track
2047   // - sector
2048   // - plane
2049   // - index
2050   // Output
2051   // tracklet
2052   // index
2053   // Detailed description
2054   //
2055   idx = track->GetTrackletIndex(p);
2056   AliTRDseedV1 *tracklet = (idx<0) ? NULL : (AliTRDseedV1*)fTracklets->UncheckedAt(idx);
2057
2058   return tracklet;
2059 }
2060
2061 //____________________________________________________________________
2062 AliTRDseedV1* AliTRDtrackerV1::SetTracklet(const AliTRDseedV1 * const tracklet)
2063 {
2064   // Add this tracklet to the list of tracklets stored in the tracker
2065   //
2066   // Parameters
2067   //   - tracklet : pointer to the tracklet to be added to the list
2068   //
2069   // Output
2070   //   - the index of the new tracklet in the tracker tracklets list
2071   //
2072   // Detailed description
2073   // Build the tracklets list if it is not yet created (late initialization)
2074   // and adds the new tracklet to the list.
2075   //
2076   if(!fTracklets){
2077     fTracklets = new TClonesArray("AliTRDseedV1", AliTRDgeometry::Nsector()*kMaxTracksStack);
2078     fTracklets->SetOwner(kTRUE);
2079   }
2080   Int_t nentries = fTracklets->GetEntriesFast();
2081   return new ((*fTracklets)[nentries]) AliTRDseedV1(*tracklet);
2082 }
2083
2084 //____________________________________________________________________
2085 void AliTRDtrackerV1::CookNTimeBins()
2086
2087   // Initialize number of time bins
2088
2089   if(fgNTimeBins){
2090     // first look if set by hand
2091     AliDebug(2, Form("NTimeBins [%d] (set by user)", fgNTimeBins));
2092   } else if(fkReconstructor && fkReconstructor->HasDigitsParam()) {
2093     // second look into digits param to avoid DB query
2094     fgNTimeBins = fkReconstructor->GetDigitsParam()->GetNTimeBins();
2095     if(fgNTimeBins>0) AliDebug(2, Form("NTimeBins [%d] (set from digits param)", fgNTimeBins));
2096     else AliWarning(Form("NTimeBins [%d] failed from digits param.", fgNTimeBins));
2097   }
2098
2099   if(!fgNTimeBins){ // third query DB
2100     AliTRDcalibDB *trd(NULL);
2101     if((trd = AliTRDcalibDB::Instance())) {
2102       if((fgNTimeBins = trd->GetNumberOfTimeBinsDCS()) <= 0){
2103         AliError("Corrupted DCS Object in OCDB");
2104         fgNTimeBins = 24;
2105         AliDebug(2, Form("NTimeBins [%d] (set to default 24)", fgNTimeBins));
2106       } else AliDebug(2, Form("NTimeBins [%d] (set from DB)", fgNTimeBins));
2107     } else AliFatal("Could not get DB.");
2108   }
2109
2110   if(fgNTimeBins<=0){
2111     AliError("NTimeBins failed all settings. Use default 24 !");
2112     fgNTimeBins = 24;
2113   }
2114 }
2115
2116 //____________________________________________________________________
2117 AliTRDtrackV1* AliTRDtrackerV1::SetTrack(const AliTRDtrackV1 * const track)
2118 {
2119   // Add this track to the list of tracks stored in the tracker
2120   //
2121   // Parameters
2122   //   - track : pointer to the track to be added to the list
2123   //
2124   // Output
2125   //   - the pointer added
2126   //
2127   // Detailed description
2128   // Build the tracks list if it is not yet created (late initialization)
2129   // and adds the new track to the list.
2130   //
2131   if(!fTracks){
2132     fTracks = new TClonesArray("AliTRDtrackV1", AliTRDgeometry::Nsector()*kMaxTracksStack);
2133     fTracks->SetOwner(kTRUE);
2134   }
2135   Int_t nentries = fTracks->GetEntriesFast();
2136   return new ((*fTracks)[nentries]) AliTRDtrackV1(*track);
2137 }
2138
2139
2140
2141 //____________________________________________________________________
2142 Int_t AliTRDtrackerV1::Clusters2TracksSM(Int_t sector, AliESDEvent *esd)
2143 {
2144   //
2145   // Steer tracking for one SM.
2146   //
2147   // Parameters :
2148   //   sector  : Array of (SM) propagation layers containing clusters
2149   //   esd     : The current ESD event. On output it contains the also
2150   //             the ESD (TRD) tracks found in this SM. 
2151   //
2152   // Output :
2153   //   Number of tracks found in this TRD supermodule.
2154   // 
2155   // Detailed description
2156   //
2157   // 1. Unpack AliTRDpropagationLayers objects for each stack.
2158   // 2. Launch stack tracking. 
2159   //    See AliTRDtrackerV1::Clusters2TracksStack() for details.
2160   // 3. Pack results in the ESD event.
2161   //
2162   
2163   Int_t nTracks   = 0;
2164   Int_t nChambers = 0;
2165   AliTRDtrackingChamber **stack = NULL, *chamber = NULL;
2166   for(int istack = 0; istack<AliTRDgeometry::kNstack; istack++){
2167     if(!(stack = fTrSec[sector].GetStack(istack))) continue;
2168     nChambers = 0;
2169     for(int ilayer=0; ilayer<AliTRDgeometry::kNlayer; ilayer++){
2170       if(!(chamber = stack[ilayer])) continue;
2171       if(chamber->GetNClusters() < fgNTimeBins * fkReconstructor->GetRecoParam() ->GetFindableClusters()) continue;
2172       nChambers++;
2173       //AliInfo(Form("sector %d stack %d layer %d clusters %d", sector, istack, ilayer, chamber->GetNClusters()));
2174     }
2175     if(nChambers < 4) continue;
2176     //AliInfo(Form("Doing stack %d", istack));
2177     nTracks += Clusters2TracksStack(stack, fTracksESD);
2178   }
2179   if(nTracks) AliDebug(2, Form("Number of tracks: SM_%02d[%d]", sector, nTracks));
2180
2181   for(int itrack=0; itrack<nTracks; itrack++){
2182     AliESDtrack *esdTrack((AliESDtrack*)(fTracksESD->operator[](itrack)));
2183     Int_t id = esd->AddTrack(esdTrack);
2184
2185     // set ESD id to stand alone TRD tracks
2186     if (fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 0){ 
2187       esdTrack=esd->GetTrack(id);
2188       TObject *o(NULL); Int_t ic(0);
2189       AliTRDtrackV1 *calibTrack(NULL); 
2190       while((o = esdTrack->GetCalibObject(ic++))){
2191         if(!(calibTrack = dynamic_cast<AliTRDtrackV1*>(o))) continue;
2192         calibTrack->SetESDid(esdTrack->GetID());
2193         break;
2194       }
2195     }
2196   }
2197
2198   // Reset Track and Candidate Number
2199   AliTRDtrackerDebug::SetCandidateNumber(0);
2200   AliTRDtrackerDebug::SetTrackNumber(0);
2201
2202   // delete ESD tracks in the array
2203   fTracksESD->Delete();
2204   return nTracks;
2205 }
2206
2207 //____________________________________________________________________
2208 Int_t AliTRDtrackerV1::Clusters2TracksStack(AliTRDtrackingChamber **stack, TClonesArray * const esdTrackList)
2209 {
2210   //
2211   // Make tracks in one TRD stack.
2212   //
2213   // Parameters :
2214   //   layer  : Array of stack propagation layers containing clusters
2215   //   esdTrackList  : Array of ESD tracks found by the stand alone tracker. 
2216   //                   On exit the tracks found in this stack are appended.
2217   //
2218   // Output :
2219   //   Number of tracks found in this stack.
2220   // 
2221   // Detailed description
2222   //
2223   // 1. Find the 3 most useful seeding chambers. See BuildSeedingConfigs() for details.
2224   // 2. Steer AliTRDtrackerV1::MakeSeeds() for 3 seeding layer configurations. 
2225   //    See AliTRDtrackerV1::MakeSeeds() for more details.
2226   // 3. Arrange track candidates in decreasing order of their quality
2227   // 4. Classify tracks in 5 categories according to:
2228   //    a) number of layers crossed
2229   //    b) track quality 
2230   // 5. Sign clusters by tracks in decreasing order of track quality
2231   // 6. Build AliTRDtrack out of seeding tracklets
2232   // 7. Cook MC label
2233   // 8. Build ESD track and register it to the output list
2234   //
2235
2236   const AliTRDCalDet *cal = AliTRDcalibDB::Instance()->GetT0Det();
2237   AliTRDtrackingChamber *chamber = NULL;
2238   AliTRDtrackingChamber **ci = NULL;
2239   AliTRDseedV1 sseed[kMaxTracksStack*6]; // to be initialized
2240   Int_t pars[4]; // MakeSeeds parameters
2241
2242   //Double_t alpha = AliTRDgeometry::GetAlpha();
2243   //Double_t shift = .5 * alpha;
2244   Int_t configs[kNConfigs];
2245   
2246   // Purge used clusters from the containers
2247   ci = &stack[0];
2248   for(Int_t ic = kNPlanes; ic--; ci++){
2249     if(!(*ci)) continue;
2250     (*ci)->Update();
2251   }
2252
2253   // Build initial seeding configurations
2254   Double_t quality = BuildSeedingConfigs(stack, configs);
2255   if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 10){
2256     AliInfo(Form("Plane config %d %d %d Quality %f"
2257     , configs[0], configs[1], configs[2], quality));
2258   }
2259
2260   
2261   // Initialize contors
2262   Int_t ntracks,      // number of TRD track candidates
2263     ntracks1,     // number of registered TRD tracks/iter
2264     ntracks2 = 0; // number of all registered TRD tracks in stack
2265   fSieveSeeding = 0;
2266
2267   // Get stack index
2268   Int_t ic = 0; ci = &stack[0];
2269   while(ic<kNPlanes && !(*ci)){ic++; ci++;}
2270   if(!(*ci)) return ntracks2;
2271   Int_t istack = fGeom->GetStack((*ci)->GetDetector());
2272
2273   do{
2274     // Loop over seeding configurations
2275     ntracks = 0; ntracks1 = 0;
2276     for (Int_t iconf = 0; iconf<3; iconf++) {
2277       pars[0] = configs[iconf];
2278       pars[1] = ntracks;
2279       pars[2] = istack;
2280       ntracks = MakeSeeds(stack, &sseed[6*ntracks], pars);
2281       //AliInfo(Form("Number of Tracks after iteration step %d: %d\n", iconf, ntracks));
2282       if(ntracks == kMaxTracksStack) break;
2283     }
2284     AliDebug(2, Form("Candidate TRD tracks %d in iteration %d.", ntracks, fSieveSeeding));
2285     
2286     if(!ntracks) break;
2287     
2288     // Sort the seeds according to their quality
2289     Int_t sort[kMaxTracksStack];
2290     TMath::Sort(ntracks, fTrackQuality, sort, kTRUE);
2291   
2292     // Initialize number of tracks so far and logic switches
2293     Int_t ntracks0 = esdTrackList->GetEntriesFast();
2294     Bool_t signedTrack[kMaxTracksStack];
2295     Bool_t fakeTrack[kMaxTracksStack];
2296     for (Int_t i=0; i<ntracks; i++){
2297       signedTrack[i] = kFALSE;
2298       fakeTrack[i] = kFALSE;
2299     }
2300     //AliInfo("Selecting track candidates ...");
2301     
2302     // Sieve clusters in decreasing order of track quality
2303     Double_t trackParams[7];
2304     //          AliTRDseedV1 *lseed = NULL;
2305     Int_t jSieve = 0, candidates;
2306     do{
2307       //AliInfo(Form("\t\tITER = %i ", jSieve));
2308
2309       // Check track candidates
2310       candidates = 0;
2311       for (Int_t itrack = 0; itrack < ntracks; itrack++) {
2312         Int_t trackIndex = sort[itrack];
2313         if (signedTrack[trackIndex] || fakeTrack[trackIndex]) continue;
2314   
2315         
2316         // Calculate track parameters from tracklets seeds
2317         Int_t ncl        = 0;
2318         Int_t nused      = 0;
2319         Int_t nlayers    = 0;
2320         Int_t findable   = 0;
2321         for (Int_t jLayer = 0; jLayer < kNPlanes; jLayer++) {
2322           Int_t jseed = kNPlanes*trackIndex+jLayer;
2323           if(!sseed[jseed].IsOK()) continue;
2324           if (TMath::Abs(sseed[jseed].GetYref(0) / sseed[jseed].GetX0()) < 0.158) findable++;
2325           // TODO here we get a sig fault which should never happen !
2326           sseed[jseed].UpdateUsed();
2327           ncl   += sseed[jseed].GetN2();
2328           nused += sseed[jseed].GetNUsed();
2329           nlayers++;
2330         }
2331
2332         // Filter duplicated tracks
2333         if (nused > 30){
2334           //printf("Skip %d nused %d\n", trackIndex, nused);
2335           fakeTrack[trackIndex] = kTRUE;
2336           continue;
2337         }
2338         if (ncl>0 && Float_t(nused)/ncl >= .25){
2339           //printf("Skip %d nused/ncl >= .25\n", trackIndex);
2340           fakeTrack[trackIndex] = kTRUE;
2341           continue;
2342         }
2343
2344         // Classify tracks
2345         Bool_t skip = kFALSE;
2346         switch(jSieve){
2347           case 0:
2348             if(nlayers < 6) {skip = kTRUE; break;}
2349             if(TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -5.){skip = kTRUE; break;}
2350             break;
2351
2352           case 1:
2353             if(nlayers < findable){skip = kTRUE; break;}
2354             if(TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -4.){skip = kTRUE; break;}
2355             break;
2356
2357           case 2:
2358             if ((nlayers == findable) || (nlayers == 6)) { skip = kTRUE; break;}
2359             if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -6.0){skip = kTRUE; break;}
2360             break;
2361
2362           case 3:
2363             if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -5.){skip = kTRUE; break;}
2364             break;
2365
2366           case 4:
2367             if (nlayers == 3){skip = kTRUE; break;}
2368             //if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) - nused/(nlayers-3.0) < -15.0){skip = kTRUE; break;}
2369             break;
2370         }
2371         if(skip){
2372           candidates++;
2373           AliDebug(4, Form("REJECTED : %d idx[%d] quality[%e] tracklets[%d] usedClusters[%d]", itrack, trackIndex, fTrackQuality[trackIndex], nlayers, nused));
2374           continue;
2375         } else AliDebug(4, Form("ACCEPTED : %d idx[%d] quality[%e] tracklets[%d] usedClusters[%d]", itrack, trackIndex, fTrackQuality[trackIndex], nlayers, nused));
2376
2377         signedTrack[trackIndex] = kTRUE;
2378
2379         // Build track parameters
2380         AliTRDseedV1 *lseed =&sseed[trackIndex*6];
2381       /*  Int_t idx = 0;
2382         while(idx<3 && !lseed->IsOK()) {
2383           idx++;
2384           lseed++;
2385         }*/
2386         Double_t x = lseed->GetX0();// - 3.5;
2387         trackParams[0] = x; //NEW AB
2388         trackParams[1] = lseed->GetYref(0); // lseed->GetYat(x);  
2389         trackParams[2] = lseed->GetZref(0); // lseed->GetZat(x); 
2390         trackParams[3] = TMath::Sin(TMath::ATan(lseed->GetYref(1)));
2391         trackParams[4] = lseed->GetZref(1) / TMath::Sqrt(1. + lseed->GetYref(1) * lseed->GetYref(1));
2392         trackParams[5] = lseed->GetC();
2393         Int_t ich = 0; while(!(chamber = stack[ich])) ich++;
2394         trackParams[6] = fGeom->GetSector(chamber->GetDetector());/* *alpha+shift;      // Supermodule*/
2395
2396         if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 1 && fkReconstructor->IsDebugStreaming()){
2397           //AliInfo(Form("Track %d [%d] nlayers %d trackQuality = %e nused %d, yref = %3.3f", itrack, trackIndex, nlayers, fTrackQuality[trackIndex], nused, trackParams[1]));
2398
2399           AliTRDseedV1 *dseed[6];
2400           for(Int_t iseed = AliTRDgeometry::kNlayer; iseed--;) dseed[iseed] = new AliTRDseedV1(lseed[iseed]);
2401
2402           //Int_t eventNrInFile = esd->GetEventNumberInFile();
2403           Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2404           Int_t trackNumber = AliTRDtrackerDebug::GetTrackNumber();
2405           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2406           TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
2407           cstreamer << "Clusters2TracksStack"
2408               << "EventNumber="         << eventNumber
2409               << "TrackNumber="         << trackNumber
2410               << "CandidateNumber="     << candidateNumber
2411               << "Iter="                                << fSieveSeeding
2412               << "Like="                                << fTrackQuality[trackIndex]
2413               << "S0.="                         << dseed[0]
2414               << "S1.="                         << dseed[1]
2415               << "S2.="                         << dseed[2]
2416               << "S3.="                         << dseed[3]
2417               << "S4.="                         << dseed[4]
2418               << "S5.="                         << dseed[5]
2419               << "p0="                          << trackParams[0]
2420               << "p1="                          << trackParams[1]
2421               << "p2="                          << trackParams[2]
2422               << "p3="                          << trackParams[3]
2423               << "p4="                          << trackParams[4]
2424               << "p5="                          << trackParams[5]
2425               << "p6="                          << trackParams[6]
2426               << "Ncl="                         << ncl
2427               << "NLayers="                     << nlayers
2428               << "Findable="                    << findable
2429               << "NUsed="                               << nused
2430               << "\n";
2431         }
2432
2433         AliTRDtrackV1 *track = MakeTrack(&sseed[trackIndex*kNPlanes], trackParams);
2434         if(!track){
2435           AliDebug(1, "Track building failed.");
2436           continue;
2437         }
2438       
2439         //AliInfo("End of MakeTrack()");
2440         AliESDtrack *esdTrack = new ((*esdTrackList)[ntracks0++]) AliESDtrack();
2441         esdTrack->UpdateTrackParams(track, AliESDtrack::kTRDout);
2442         esdTrack->SetLabel(track->GetLabel());
2443         track->UpdateESDtrack(esdTrack);
2444         // write ESD-friends if neccessary
2445         if (fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 0){
2446           AliTRDtrackV1 *calibTrack = new AliTRDtrackV1(*track);
2447           calibTrack->SetOwner();
2448           esdTrack->AddCalibObject(calibTrack);
2449         }
2450         ntracks1++;
2451         AliTRDtrackerDebug::SetTrackNumber(AliTRDtrackerDebug::GetTrackNumber() + 1);
2452       }
2453
2454       jSieve++;
2455     } while(jSieve<5 && candidates); // end track candidates sieve
2456     if(!ntracks1) break;
2457
2458     // increment counters
2459     ntracks2 += ntracks1;
2460
2461     if(fkReconstructor->IsHLT()) break;
2462     fSieveSeeding++;
2463
2464     // Rebuild plane configurations and indices taking only unused clusters into account
2465     quality = BuildSeedingConfigs(stack, configs);
2466     if(quality < 1.E-7) break; //fkReconstructor->GetRecoParam() ->GetPlaneQualityThreshold()) break;
2467     
2468     for(Int_t ip = 0; ip < kNPlanes; ip++){ 
2469       if(!(chamber = stack[ip])) continue;
2470       chamber->Build(fGeom, cal);//Indices(fSieveSeeding);
2471     }
2472
2473     if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 10){ 
2474       AliInfo(Form("Sieve level %d Plane config %d %d %d Quality %f", fSieveSeeding, configs[0], configs[1], configs[2], quality));
2475     }
2476   } while(fSieveSeeding<10); // end stack clusters sieve
2477   
2478
2479
2480   //AliInfo(Form("Registered TRD tracks %d in stack %d.", ntracks2, pars[1]));
2481
2482   return ntracks2;
2483 }
2484
2485 //___________________________________________________________________
2486 Double_t AliTRDtrackerV1::BuildSeedingConfigs(AliTRDtrackingChamber **stack, Int_t *configs)
2487 {
2488   //
2489   // Assign probabilities to chambers according to their
2490   // capability of producing seeds.
2491   // 
2492   // Parameters :
2493   //
2494   //   layers : Array of stack propagation layers for all 6 chambers in one stack
2495   //   configs : On exit array of configuration indexes (see GetSeedingConfig()
2496   // for details) in the decreasing order of their seeding probabilities. 
2497   //
2498   // Output :
2499   //
2500   //  Return top configuration quality 
2501   //
2502   // Detailed description:
2503   //
2504   // To each chamber seeding configuration (see GetSeedingConfig() for
2505   // the list of all configurations) one defines 2 quality factors:
2506   //  - an apriori topological quality (see GetSeedingConfig() for details) and
2507   //  - a data quality based on the uniformity of the distribution of
2508   //    clusters over the x range (time bins population). See CookChamberQA() for details.
2509   // The overall chamber quality is given by the product of this 2 contributions.
2510   // 
2511
2512   Double_t chamberQ[kNPlanes];memset(chamberQ, 0, kNPlanes*sizeof(Double_t));
2513   AliTRDtrackingChamber *chamber = NULL;
2514   for(int iplane=0; iplane<kNPlanes; iplane++){
2515     if(!(chamber = stack[iplane])) continue;
2516     chamberQ[iplane] = (chamber = stack[iplane]) ?  chamber->GetQuality() : 0.;
2517   }
2518
2519   Double_t tconfig[kNConfigs];memset(tconfig, 0, kNConfigs*sizeof(Double_t));
2520   Int_t planes[] = {0, 0, 0, 0};
2521   for(int iconf=0; iconf<kNConfigs; iconf++){
2522     GetSeedingConfig(iconf, planes);
2523     tconfig[iconf] = fgTopologicQA[iconf];
2524     for(int iplane=0; iplane<4; iplane++) tconfig[iconf] *= chamberQ[planes[iplane]]; 
2525   }
2526   
2527   TMath::Sort((Int_t)kNConfigs, tconfig, configs, kTRUE);
2528   //    AliInfo(Form("q[%d] = %f", configs[0], tconfig[configs[0]]));
2529   //    AliInfo(Form("q[%d] = %f", configs[1], tconfig[configs[1]]));
2530   //    AliInfo(Form("q[%d] = %f", configs[2], tconfig[configs[2]]));
2531   
2532   return tconfig[configs[0]];
2533 }
2534
2535 //____________________________________________________________________
2536 Int_t AliTRDtrackerV1::MakeSeeds(AliTRDtrackingChamber **stack, AliTRDseedV1 * const sseed, const Int_t * const ipar)
2537 {
2538 //
2539 // Seed tracklets and build candidate TRD tracks. The procedure is used during barrel tracking to account for tracks which are 
2540 // either missed by TPC prolongation or conversions inside the TRD volume. 
2541 // For stand alone tracking the procedure is used to estimate all tracks measured by TRD. 
2542 //
2543 // Parameters :
2544 //   layers : Array of stack propagation layers containing clusters
2545 //   sseed  : Array of empty tracklet seeds. On exit they are filled.
2546 //   ipar   : Control parameters:
2547 //       ipar[0] -> seeding chambers configuration
2548 //       ipar[1] -> stack index
2549 //       ipar[2] -> number of track candidates found so far
2550 //
2551 // Output :
2552 //   Number of tracks candidates found.
2553 // 
2554 // The following steps are performed:
2555 // 1. Build seeding layers by collapsing all time bins from each of the four seeding chambers along the 
2556 // radial coordinate. See AliTRDtrackingChamber::GetSeedingLayer() for details. The chambers selection for seeding
2557 // is described in AliTRDtrackerV1::Clusters2TracksStack().
2558 // 2. Using the seeding clusters from the seeding layer (step 1) build combinatorics using the following algorithm:
2559 // - for each seeding cluster in the lower seeding layer find
2560 // - all seeding clusters in the upper seeding layer inside a road defined by a given phi angle. The angle 
2561 //   is calculated on the minimum pt of tracks from vertex accesible to the stand alone tracker.
2562 // - for each pair of two extreme seeding clusters select middle upper cluster using roads defined externally by the 
2563 //   reco params
2564 // - select last seeding cluster as the nearest to the linear approximation of the track described by the first three
2565 //   seeding clusters.
2566 //   The implementation of road calculation and cluster selection can be found in the functions AliTRDchamberTimeBin::BuildCond()
2567 //   and AliTRDchamberTimeBin::GetClusters().   
2568 // 3. Helix fit of the seeding clusters set. (see AliTRDtrackerFitter::FitRieman(AliTRDcluster**)). No tilt correction is 
2569 //    performed at this level 
2570 // 4. Initialize seeding tracklets in the seeding chambers.
2571 // 5. *Filter 0* Chi2 cut on the Y and Z directions. The threshold is set externally by the reco params.
2572 // 6. Attach (true) clusters to seeding tracklets (see AliTRDseedV1::AttachClusters()) and fit tracklet (see 
2573 //    AliTRDseedV1::Fit()). The number of used clusters used by current seeds should not exceed ... (25).
2574 // 7. *Filter 1* Check if all 4 seeding tracklets are correctly constructed.
2575 // 8. Helix fit of the clusters from the seeding tracklets with tilt correction. Refit tracklets using the new 
2576 //    approximation of the track.
2577 // 9. *Filter 2* Calculate likelihood of the track. (See AliTRDtrackerV1::CookLikelihood()). The following quantities are
2578 //    checked against the Riemann fit:
2579 //      - position resolution in y
2580 //      - angular resolution in the bending plane
2581 //      - likelihood of the number of clusters attached to the tracklet
2582 // 10. Extrapolation of the helix fit to the other 2 chambers *non seeding* chambers:
2583 //      - Initialization of extrapolation tracklets with the fit parameters
2584 //      - Attach clusters to extrapolated tracklets
2585 //      - Helix fit of tracklets
2586 // 11. Improve seeding tracklets quality by reassigning clusters based on the last parameters of the track
2587 //      See AliTRDtrackerV1::ImproveSeedQuality() for details.
2588 // 12. Helix fit of all 6 seeding tracklets and chi2 calculation
2589 // 13. Hyperplane fit and track quality calculation. See AliTRDtrackerFitter::FitHyperplane() for details.
2590 // 14. Cooking labels for tracklets. Should be done only for MC
2591 // 15. Register seeds.
2592 //
2593 // Authors:
2594 //   Marian Ivanov <M.Ivanov@gsi.de>
2595 //   Alexandru Bercuci <A.Bercuci@gsi.de>
2596 //   Markus Fasel <M.Fasel@gsi.de>
2597
2598   AliTRDtrackingChamber *chamber = NULL;
2599   AliTRDcluster *c[kNSeedPlanes] = {NULL, NULL, NULL, NULL}; // initilize seeding clusters
2600   AliTRDseedV1 *cseed = &sseed[0]; // initialize tracklets for first track
2601   Int_t ncl, mcl; // working variable for looping over clusters
2602   Int_t index[AliTRDchamberTimeBin::kMaxClustersLayer], jndex[AliTRDchamberTimeBin::kMaxClustersLayer];
2603   // chi2 storage
2604   // chi2[0] = tracklet chi2 on the Z direction
2605   // chi2[1] = tracklet chi2 on the R direction
2606   Double_t chi2[4];
2607
2608   // this should be data member of AliTRDtrack TODO
2609   Double_t seedQuality[kMaxTracksStack];
2610   
2611   // unpack control parameters
2612   Int_t config  = ipar[0];
2613   Int_t ntracks = ipar[1];
2614   Int_t istack  = ipar[2];
2615   Int_t planes[kNSeedPlanes]; GetSeedingConfig(config, planes); 
2616   Int_t planesExt[kNPlanes-kNSeedPlanes]; GetExtrapolationConfig(config, planesExt);
2617
2618
2619   // Init chambers geometry
2620   Double_t hL[kNPlanes];       // Tilting angle
2621   Float_t padlength[kNPlanes]; // pad lenghts
2622   Float_t padwidth[kNPlanes];  // pad widths
2623   AliTRDpadPlane *pp = NULL;
2624   for(int iplane=0; iplane<kNPlanes; iplane++){
2625     pp                = fGeom->GetPadPlane(iplane, istack);
2626     hL[iplane]        = TMath::Tan(TMath::DegToRad()*pp->GetTiltingAngle());
2627     padlength[iplane] = pp->GetLengthIPad();
2628     padwidth[iplane] = pp->GetWidthIPad();
2629   }
2630   
2631   // Init anode wire position for chambers
2632   Double_t x0[kNPlanes],       // anode wire position
2633            driftLength = .5*AliTRDgeometry::AmThick() - AliTRDgeometry::DrThick(); // drift length
2634   TGeoHMatrix *matrix = NULL;
2635   Double_t loc[] = {AliTRDgeometry::AnodePos(), 0., 0.};
2636   Double_t glb[] = {0., 0., 0.};
2637   AliTRDtrackingChamber **cIter = &stack[0];
2638   for(int iLayer=0; iLayer<kNPlanes; iLayer++,cIter++){
2639     if(!(*cIter)) continue;
2640     if(!(matrix = fGeom->GetClusterMatrix((*cIter)->GetDetector()))){ 
2641       continue;
2642       x0[iLayer] = fgkX0[iLayer];
2643     }
2644     matrix->LocalToMaster(loc, glb);
2645     x0[iLayer] = glb[0];
2646   }
2647
2648   AliDebug(2, Form("Making seeds Stack[%d] Config[%d] Tracks[%d]...", istack, config, ntracks));
2649
2650   // Build seeding layers
2651   ResetSeedTB();
2652   Int_t nlayers = 0;
2653   for(int isl=0; isl<kNSeedPlanes; isl++){ 
2654     if(!(chamber = stack[planes[isl]])) continue;
2655     if(!chamber->GetSeedingLayer(fSeedTB[isl], fGeom, fkReconstructor)) continue;
2656     nlayers++;
2657   }
2658   if(nlayers < kNSeedPlanes) return ntracks;
2659   
2660   
2661   // Start finding seeds
2662   Double_t cond0[4], cond1[4], cond2[4];
2663   Int_t icl = 0;
2664   while((c[3] = (*fSeedTB[3])[icl++])){
2665     if(!c[3]) continue;
2666     fSeedTB[0]->BuildCond(c[3], cond0, 0);
2667     fSeedTB[0]->GetClusters(cond0, index, ncl);
2668     //printf("Found c[3] candidates 0 %d\n", ncl);
2669     Int_t jcl = 0;
2670     while(jcl<ncl) {
2671       c[0] = (*fSeedTB[0])[index[jcl++]];
2672       if(!c[0]) continue;
2673       Double_t dx    = c[3]->GetX() - c[0]->GetX();
2674       Double_t dzdx = (c[3]->GetZ() - c[0]->GetZ())/dx;
2675       Double_t dydx   = (c[3]->GetY() - c[0]->GetY())/dx;
2676       fSeedTB[1]->BuildCond(c[0], cond1, 1, dzdx, dydx);
2677       fSeedTB[1]->GetClusters(cond1, jndex, mcl);
2678       //printf("Found c[0] candidates 1 %d\n", mcl);
2679
2680       Int_t kcl = 0;
2681       while(kcl<mcl) {
2682         c[1] = (*fSeedTB[1])[jndex[kcl++]];
2683         if(!c[1]) continue;
2684         fSeedTB[2]->BuildCond(c[1], cond2, 2, dzdx, dydx);
2685         c[2] = fSeedTB[2]->GetNearestCluster(cond2);
2686         //printf("Found c[1] candidate 2 %p\n", c[2]);
2687         if(!c[2]) continue;
2688
2689         AliDebug(3, Form("Seeding clusters\n 0[%6.3f %6.3f %6.3f]\n 1[%6.3f %6.3f %6.3f]\n 2[%6.3f %6.3f %6.3f]\n 3[%6.3f %6.3f %6.3f].",
2690           c[0]->GetX(), c[0]->GetY(), c[0]->GetZ(),
2691           c[1]->GetX(), c[1]->GetY(), c[1]->GetZ(),
2692           c[2]->GetX(), c[2]->GetY(), c[2]->GetZ(),
2693           c[3]->GetX(), c[3]->GetY(), c[3]->GetZ()));
2694               
2695         for (Int_t il = 0; il < kNPlanes; il++) cseed[il].Reset();
2696       
2697         FitRieman(c, chi2);
2698       
2699         AliTRDseedV1 *tseed = &cseed[0];
2700         cIter = &stack[0];
2701         for(int iLayer=0; iLayer<kNPlanes; iLayer++, tseed++, cIter++){
2702           Int_t det = (*cIter) ? (*cIter)->GetDetector() : -1;
2703           tseed->SetDetector(det);
2704           tseed->SetTilt(hL[iLayer]);
2705           tseed->SetPadLength(padlength[iLayer]);
2706           tseed->SetPadWidth(padwidth[iLayer]);
2707           tseed->SetReconstructor(fkReconstructor);
2708           tseed->SetX0(det<0 ? fR[iLayer]+driftLength : x0[iLayer]);
2709           tseed->Init(GetRiemanFitter());
2710           tseed->SetStandAlone(kTRUE);
2711         }
2712       
2713         Bool_t isFake = kFALSE;
2714         if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
2715           if (c[0]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
2716           if (c[1]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
2717           if (c[2]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
2718       
2719           Double_t xpos[4];
2720           for(Int_t l = 0; l < kNSeedPlanes; l++) xpos[l] = fSeedTB[l]->GetX();
2721           Float_t yref[4];
2722           for(int il=0; il<4; il++) yref[il] = cseed[planes[il]].GetYref(0);
2723           Int_t ll = c[3]->GetLabel(0);
2724           Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2725           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2726           AliRieman *rim = GetRiemanFitter();
2727           TTreeSRedirector &cs0 = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
2728           cs0 << "MakeSeeds0"
2729               <<"EventNumber="          << eventNumber
2730               <<"CandidateNumber="      << candidateNumber
2731               <<"isFake="                               << isFake
2732               <<"config="                               << config
2733               <<"label="                                << ll
2734               <<"chi2z="                                << chi2[0]
2735               <<"chi2y="                                << chi2[1]
2736               <<"Y2exp="                                << cond2[0]     
2737               <<"Z2exp="                                << cond2[1]
2738               <<"X0="                                   << xpos[0] //layer[sLayer]->GetX()
2739               <<"X1="                                   << xpos[1] //layer[sLayer + 1]->GetX()
2740               <<"X2="                                   << xpos[2] //layer[sLayer + 2]->GetX()
2741               <<"X3="                                   << xpos[3] //layer[sLayer + 3]->GetX()
2742               <<"yref0="                                << yref[0]
2743               <<"yref1="                                << yref[1]
2744               <<"yref2="                                << yref[2]
2745               <<"yref3="                                << yref[3]
2746               <<"c0.="                          << c[0]
2747               <<"c1.="                          << c[1]
2748               <<"c2.="                          << c[2]
2749               <<"c3.="                          << c[3]
2750               <<"Seed0.="                               << &cseed[planes[0]]
2751               <<"Seed1.="                               << &cseed[planes[1]]
2752               <<"Seed2.="                               << &cseed[planes[2]]
2753               <<"Seed3.="                               << &cseed[planes[3]]
2754               <<"RiemanFitter.="                << rim
2755               <<"\n";
2756         }
2757         if(chi2[0] > fkReconstructor->GetRecoParam() ->GetChi2Z()/*7./(3. - sLayer)*//*iter*/){
2758           AliDebug(3, Form("Filter on chi2Z [%f].", chi2[0]));
2759           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2760           continue;
2761         }
2762         if(chi2[1] > fkReconstructor->GetRecoParam() ->GetChi2Y()/*1./(3. - sLayer)*//*iter*/){
2763           AliDebug(3, Form("Filter on chi2Y [%f].", chi2[1]));
2764           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2765           continue;
2766         }
2767         //AliInfo("Passed chi2 filter.");
2768       
2769         // try attaching clusters to tracklets
2770         Int_t mlayers = 0; 
2771         AliTRDcluster *cl = NULL;
2772         for(int iLayer=0; iLayer<kNSeedPlanes; iLayer++){
2773           Int_t jLayer = planes[iLayer];
2774           Int_t nNotInChamber = 0;
2775           if(!cseed[jLayer].AttachClusters(stack[jLayer], kTRUE)) continue;
2776           if(/*fkReconstructor->IsHLT()*/kFALSE){ 
2777             cseed[jLayer].UpdateUsed();
2778             if(!cseed[jLayer].IsOK()) continue;
2779           }else{
2780             cseed[jLayer].Fit();
2781             cseed[jLayer].UpdateUsed();
2782             cseed[jLayer].ResetClusterIter();
2783             while((cl = cseed[jLayer].NextCluster())){
2784               if(!cl->IsInChamber()) nNotInChamber++;
2785             }
2786             //printf("clusters[%d], used[%d], not in chamber[%d]\n", cseed[jLayer].GetN(), cseed[jLayer].GetNUsed(), nNotInChamber);
2787             if(cseed[jLayer].GetN() - (cseed[jLayer].GetNUsed() + nNotInChamber) < 5) continue; // checking for Cluster which are not in chamber is a much stronger restriction on real data
2788           }
2789           mlayers++;
2790         }
2791
2792         if(mlayers < kNSeedPlanes){ 
2793           AliDebug(2, Form("Found only %d tracklets out of %d. Skip.", mlayers, kNSeedPlanes));
2794           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2795           continue;
2796         }
2797
2798         // temporary exit door for the HLT
2799         if(fkReconstructor->IsHLT()){ 
2800           // attach clusters to extrapolation chambers
2801           for(int iLayer=0; iLayer<kNPlanes-kNSeedPlanes; iLayer++){
2802             Int_t jLayer = planesExt[iLayer];
2803             if(!(chamber = stack[jLayer])) continue;
2804             if(!cseed[jLayer].AttachClusters(chamber, kTRUE)) continue;
2805             cseed[jLayer].Fit();
2806           }
2807           fTrackQuality[ntracks] = 1.; // dummy value
2808           ntracks++;
2809           if(ntracks == kMaxTracksStack) return ntracks;
2810           cseed += 6; 
2811           continue;
2812         }
2813
2814
2815         // Update Seeds and calculate Likelihood
2816         // fit tracklets and cook likelihood
2817         FitTiltedRieman(&cseed[0], kTRUE);
2818         for(int iLayer=0; iLayer<kNSeedPlanes; iLayer++){
2819           Int_t jLayer = planes[iLayer];
2820           cseed[jLayer].Fit(kTRUE);
2821         }
2822         Double_t like = CookLikelihood(&cseed[0], planes); // to be checked
2823       
2824         if (TMath::Log(1.E-9 + like) < fkReconstructor->GetRecoParam() ->GetTrackLikelihood()){
2825           AliDebug(3, Form("Filter on likelihood %f[%e].", TMath::Log(1.E-9 + like), like));
2826           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2827           continue;
2828         }
2829         //AliInfo(Form("Passed likelihood %f[%e].", TMath::Log(1.E-9 + like), like));
2830       
2831         // book preliminary results
2832         seedQuality[ntracks] = like;
2833         fSeedLayer[ntracks]  = config;/*sLayer;*/
2834       
2835         // attach clusters to the extrapolation seeds
2836         Int_t elayers(0);
2837         for(int iLayer=0; iLayer<kNPlanes-kNSeedPlanes; iLayer++){
2838           Int_t jLayer = planesExt[iLayer];
2839           if(!(chamber = stack[jLayer])) continue;
2840       
2841           // fit extrapolated seed
2842           if ((jLayer == 0) && !(cseed[1].IsOK())) continue;
2843           if ((jLayer == 5) && !(cseed[4].IsOK())) continue;
2844           AliTRDseedV1 pseed = cseed[jLayer];
2845           if(!pseed.AttachClusters(chamber, kTRUE)) continue;
2846           pseed.Fit(kTRUE);
2847           cseed[jLayer] = pseed;
2848           FitTiltedRieman(cseed,  kTRUE);
2849           cseed[jLayer].Fit(kTRUE);
2850           elayers++;
2851         }
2852       
2853         // AliInfo("Extrapolation done.");
2854         // Debug Stream containing all the 6 tracklets
2855         if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
2856           TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
2857           TLinearFitter *tiltedRieman = GetTiltedRiemanFitter();
2858           Int_t eventNumber             = AliTRDtrackerDebug::GetEventNumber();
2859           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2860           cstreamer << "MakeSeeds1"
2861               << "EventNumber="         << eventNumber
2862               << "CandidateNumber="     << candidateNumber
2863               << "S0.="                                 << &cseed[0]
2864               << "S1.="                                 << &cseed[1]
2865               << "S2.="                                 << &cseed[2]
2866               << "S3.="                                 << &cseed[3]
2867               << "S4.="                                 << &cseed[4]
2868               << "S5.="                                 << &cseed[5]
2869               << "FitterT.="                    << tiltedRieman
2870               << "\n";
2871         }
2872               
2873         if(fkReconstructor->GetRecoParam()->HasImproveTracklets()){ 
2874           AliTRDseedV1 bseed[AliTRDgeometry::kNlayer];
2875           for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) bseed[jLayer] = cseed[jLayer];
2876
2877           if(ImproveSeedQuality(stack, cseed) < mlayers+elayers){
2878             AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2879             AliDebug(3, "Filter on improve seeds.");
2880           } else {
2881             // store results
2882             for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) cseed[jLayer] = bseed[jLayer];
2883           }
2884         }
2885         //AliInfo("Improve seed quality done.");
2886       
2887         // fit full track and cook likelihoods
2888         //                              Double_t curv = FitRieman(&cseed[0], chi2);
2889         //                              Double_t chi2ZF = chi2[0] / TMath::Max((mlayers - 3.), 1.);
2890         //                              Double_t chi2RF = chi2[1] / TMath::Max((mlayers - 3.), 1.);
2891       
2892         // do the final track fitting (Once with vertex constraint and once without vertex constraint)
2893         Double_t chi2Vals[3];
2894         chi2Vals[0] = FitTiltedRieman(&cseed[0], kTRUE);
2895         if(fkReconstructor->GetRecoParam()->IsVertexConstrained())
2896           chi2Vals[1] = FitTiltedRiemanConstraint(&cseed[0], GetZ()); // Do Vertex Constrained fit if desired
2897         else
2898           chi2Vals[1] = 1.;
2899         chi2Vals[2] = GetChi2Z(&cseed[0]) / TMath::Max((mlayers - 3.), 1.);
2900         // Chi2 definitions in testing stage
2901         //chi2Vals[2] = GetChi2ZTest(&cseed[0]);
2902         fTrackQuality[ntracks] = CalculateTrackLikelihood(&cseed[0], &chi2Vals[0]);
2903         //AliInfo("Hyperplane fit done\n");
2904                   
2905         if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
2906           TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
2907           Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2908           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2909           TLinearFitter *fitterTC = GetTiltedRiemanFitterConstraint();
2910           TLinearFitter *fitterT = GetTiltedRiemanFitter();
2911           Int_t ncls = 0; 
2912           for(Int_t iseed = 0; iseed < kNPlanes; iseed++){
2913                 ncls += cseed[iseed].IsOK() ? cseed[iseed].GetN2() : 0;
2914           }
2915           cstreamer << "MakeSeeds2"
2916               << "EventNumber="                 << eventNumber
2917               << "CandidateNumber="     << candidateNumber
2918               << "Chi2TR="                      << chi2Vals[0]
2919               << "Chi2TC="                      << chi2Vals[1]
2920               << "Nlayers="                     << mlayers
2921               << "NClusters="   << ncls
2922               << "Like="                                << like
2923               << "S0.="                         << &cseed[0]
2924               << "S1.="                         << &cseed[1]
2925               << "S2.="                         << &cseed[2]
2926               << "S3.="                         << &cseed[3]
2927               << "S4.="                         << &cseed[4]
2928               << "S5.="                         << &cseed[5]
2929               << "FitterT.="                    << fitterT
2930               << "FitterTC.="                   << fitterTC
2931               << "\n";
2932         }
2933               
2934         ntracks++;
2935         AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2936         if(ntracks == kMaxTracksStack){
2937           AliWarning(Form("Number of seeds reached maximum allowed (%d) in stack.", kMaxTracksStack));
2938           return ntracks;
2939         }
2940         cseed += 6;
2941       }
2942     }
2943   }
2944   
2945   return ntracks;
2946 }
2947
2948 //_____________________________________________________________________________
2949 AliTRDtrackV1* AliTRDtrackerV1::MakeTrack(AliTRDseedV1 * const seeds, Double_t *params)
2950 {
2951 //
2952 // Build a TRD track out of tracklet candidates
2953 //
2954 // Parameters :
2955 //   seeds  : array of tracklets
2956 //   params : array of track parameters as they are estimated by stand alone tracker. 7 elements.
2957 //     [0] - radial position of the track at reference point
2958 //     [1] - y position of the fit at [0]
2959 //     [2] - z position of the fit at [0]
2960 //     [3] - snp of the first tracklet
2961 //     [4] - tgl of the first tracklet
2962 //     [5] - curvature of the Riemann fit - 1/pt
2963 //     [6] - sector rotation angle
2964 //
2965 // Output :
2966 //   The TRD track.
2967 //
2968 // Initialize the TRD track based on the parameters of the fit and a parametric covariance matrix 
2969 // (diagonal with constant variance terms TODO - correct parameterization) 
2970 // 
2971 // In case of HLT just register the tracklets in the tracker and return values of the Riemann fit. For the
2972 // offline case perform a full Kalman filter on the already found tracklets (see AliTRDtrackerV1::FollowBackProlongation() 
2973 // for details). Do also MC label calculation and PID if propagation successfully.
2974
2975  
2976   Double_t alpha = AliTRDgeometry::GetAlpha();
2977   Double_t shift = AliTRDgeometry::GetAlpha()/2.0;
2978   Double_t c[15];
2979
2980   c[ 0] = 0.2; // s^2_y
2981   c[ 1] = 0.0; c[ 2] = 2.0; // s^2_z
2982   c[ 3] = 0.0; c[ 4] = 0.0; c[ 5] = 0.02; // s^2_snp
2983   c[ 6] = 0.0; c[ 7] = 0.0; c[ 8] = 0.0;  c[ 9] = 0.1; // s^2_tgl
2984   c[10] = 0.0; c[11] = 0.0; c[12] = 0.0;  c[13] = 0.0; c[14] = params[5]*params[5]*0.01; // s^2_1/pt
2985
2986   AliTRDtrackV1 track(seeds, &params[1], c, params[0], params[6]*alpha+shift);
2987   track.PropagateTo(params[0]-5.0);
2988   AliTRDseedV1 *ptrTracklet = NULL;
2989
2990   // skip Kalman filter for HLT
2991   if(/*fkReconstructor->IsHLT()*/kFALSE){ 
2992     for (Int_t jLayer = 0; jLayer < AliTRDgeometry::kNlayer; jLayer++) {
2993       track.UnsetTracklet(jLayer);
2994       ptrTracklet = &seeds[jLayer];
2995       if(!ptrTracklet->IsOK()) continue;
2996       if(TMath::Abs(ptrTracklet->GetYref(1) - ptrTracklet->GetYfit(1)) >= .2) continue; // check this condition with Marian
2997       ptrTracklet = SetTracklet(ptrTracklet);
2998       ptrTracklet->UseClusters();
2999       track.SetTracklet(ptrTracklet, fTracklets->GetEntriesFast()-1);
3000     }
3001     AliTRDtrackV1 *ptrTrack = SetTrack(&track);
3002     ptrTrack->CookPID();
3003     ptrTrack->CookLabel(.9);
3004     ptrTrack->SetReconstructor(fkReconstructor);
3005     return ptrTrack;
3006   }
3007
3008   // prevent the error message in AliTracker::MeanMaterialBudget: "start point out of geometry"
3009   if(TMath::Abs(track.GetX()) + TMath::Abs(track.GetY()) + TMath::Abs(track.GetZ()) > 10000) 
3010     return NULL;
3011
3012   track.ResetCovariance(1);
3013   Int_t nc = TMath::Abs(FollowBackProlongation(track));
3014   if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 5 && fkReconstructor->IsDebugStreaming()){
3015     Int_t eventNumber           = AliTRDtrackerDebug::GetEventNumber();
3016     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
3017     Double_t p[5]; // Track Params for the Debug Stream
3018     track.GetExternalParameters(params[0], p);
3019     TTreeSRedirector &cs = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
3020     cs << "MakeTrack"
3021     << "EventNumber="     << eventNumber
3022     << "CandidateNumber=" << candidateNumber
3023     << "nc="     << nc
3024     << "X="      << params[0]
3025     << "Y="      << p[0]
3026     << "Z="      << p[1]
3027     << "snp="    << p[2]
3028     << "tnd="    << p[3]
3029     << "crv="    << p[4]
3030     << "Yin="    << params[1]
3031     << "Zin="    << params[2]
3032     << "snpin="  << params[3]
3033     << "tndin="  << params[4]
3034     << "crvin="  << params[5]
3035     << "track.=" << &track
3036     << "\n";
3037   }
3038   if (nc < 30) return NULL;
3039
3040   AliTRDtrackV1 *ptrTrack = SetTrack(&track);
3041   ptrTrack->SetReconstructor(fkReconstructor);
3042   ptrTrack->CookLabel(.9);
3043   
3044   // computes PID for track
3045   ptrTrack->CookPID();
3046   // update calibration references using this track
3047   AliTRDCalibraFillHisto *calibra = AliTRDCalibraFillHisto::Instance();
3048   if (!calibra){ 
3049     AliInfo("Could not get Calibra instance\n");
3050     if(calibra->GetHisto2d()) calibra->UpdateHistogramsV1(ptrTrack);
3051   }
3052   return ptrTrack;
3053 }
3054
3055
3056 //____________________________________________________________________
3057 Int_t AliTRDtrackerV1::ImproveSeedQuality(AliTRDtrackingChamber **stack, AliTRDseedV1 *cseed)
3058 {
3059   //
3060   // Sort tracklets according to "quality" and try to "improve" the first 4 worst
3061   //
3062   // Parameters :
3063   //  layers : Array of propagation layers for a stack/supermodule
3064   //  cseed  : Array of 6 seeding tracklets which has to be improved
3065   // 
3066   // Output : 
3067   //   cssed : Improved seeds
3068   // 
3069   // Detailed description
3070   //
3071   // Iterative procedure in which new clusters are searched for each
3072   // tracklet seed such that the seed quality (see AliTRDseed::GetQuality())
3073   // can be maximized. If some optimization is found the old seeds are replaced.
3074   //
3075   // debug level: 7
3076   //
3077   
3078   // make a local working copy
3079   AliTRDtrackingChamber *chamber = NULL;
3080   AliTRDseedV1 bseed[AliTRDgeometry::kNlayer];
3081
3082   Float_t quality(0.), 
3083           lQuality[] = {1.e3, 1.e3, 1.e3, 1.e3, 1.e3, 1.e3};
3084   Int_t rLayers(0);
3085   for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;){ 
3086     bseed[jLayer] = cseed[jLayer];
3087     if(!bseed[jLayer].IsOK()) continue;
3088     rLayers++;
3089     lQuality[jLayer] = bseed[jLayer].GetQuality(kTRUE);
3090     quality    += lQuality[jLayer];
3091   }
3092   Float_t chi2 = FitTiltedRieman(bseed, kTRUE);
3093
3094   for (Int_t iter = 0; iter < 4; iter++) {
3095     AliDebug(2, Form("Iter[%d] Q[%f] chi2[%f]", iter, quality, chi2));
3096
3097     // Try better cluster set
3098     Int_t nLayers(0); Float_t qualitynew(0.);
3099     Int_t  indexes[6];
3100     TMath::Sort(Int_t(AliTRDgeometry::kNlayer), lQuality, indexes, kFALSE);
3101     for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) {
3102       Int_t bLayer = indexes[jLayer];
3103       bseed[bLayer].Reset("c");
3104       if(!(chamber = stack[bLayer])) continue;
3105       if(!bseed[bLayer].AttachClusters(chamber, kTRUE)) continue;
3106       bseed[bLayer].Fit(kTRUE);
3107       if(!bseed[bLayer].IsOK()) continue;
3108       nLayers++;
3109       lQuality[jLayer] = bseed[jLayer].GetQuality(kTRUE);
3110       qualitynew    += lQuality[jLayer];
3111     }
3112     if(rLayers > nLayers){
3113       AliDebug(1, Form("Lost %d tracklets while improving.", rLayers-nLayers));
3114       break;
3115     } else rLayers=nLayers;
3116
3117     if(qualitynew >= quality){ 
3118       AliDebug(4, Form("Quality worsen in iter[%d].", iter));
3119       break;
3120     } else quality = qualitynew;
3121
3122     // try improve track parameters
3123     AliTRDseedV1 tseed[AliTRDgeometry::kNlayer];
3124     for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) tseed[jLayer]=bseed[jLayer];
3125     Float_t chi2new = FitTiltedRieman(tseed, kTRUE);
3126     if(chi2new > chi2){ 
3127       AliDebug(4, Form("Chi2 worsen in iter[%d].", iter));
3128       break;
3129     } else chi2 = chi2new;
3130
3131     // store better tracklets
3132     for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) bseed[jLayer]=tseed[jLayer];
3133
3134
3135     if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 7 && fkReconstructor->IsDebugStreaming()){
3136       Int_t eventNumber                 = AliTRDtrackerDebug::GetEventNumber();
3137       Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
3138       TLinearFitter *tiltedRieman = GetTiltedRiemanFitter();
3139       TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
3140       cstreamer << "ImproveSeedQuality"
3141         << "EventNumber="               << eventNumber
3142         << "CandidateNumber="   << candidateNumber
3143         << "Iteration="                         << iter
3144         << "S0.="                                                       << &bseed[0]
3145         << "S1.="                                                       << &bseed[1]
3146         << "S2.="                                                       << &bseed[2]
3147         << "S3.="                                                       << &bseed[3]
3148         << "S4.="                                                       << &bseed[4]
3149         << "S5.="                                                       << &bseed[5]
3150         << "FitterT.="                          << tiltedRieman
3151         << "\n";
3152     }
3153   } // Loop: iter
3154   // we are sure that at least 2 tracklets are OK !
3155   return rLayers;
3156 }
3157
3158 //_________________________________________________________________________
3159 Double_t AliTRDtrackerV1::CalculateTrackLikelihood(const AliTRDseedV1 *const tracklets, Double_t *chi2){
3160   //
3161   // Calculates the Track Likelihood value. This parameter serves as main quality criterion for 
3162   // the track selection
3163   // The likelihood value containes:
3164   //    - The chi2 values from the both fitters and the chi2 values in z-direction from a linear fit
3165   //    - The Sum of the Parameter  |slope_ref - slope_fit|/Sigma of the tracklets
3166   // For all Parameters an exponential dependency is used
3167   //
3168   // Parameters: - Array of tracklets (AliTRDseedV1) related to the track candidate
3169   //             - Array of chi2 values: 
3170   //                 * Non-Constrained Tilted Riemann fit
3171   //                 * Vertex-Constrained Tilted Riemann fit
3172   //                 * z-Direction from Linear fit
3173   // Output:     - The calculated track likelihood
3174   //
3175   // debug level 2
3176   //
3177
3178   Double_t chi2phi = 0, nLayers = 0;
3179   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
3180     if(!tracklets[iLayer].IsOK()) continue;
3181     chi2phi += tracklets[iLayer].GetChi2Phi();
3182     nLayers++;
3183   }
3184   chi2phi /= Float_t (nLayers - 2.0);
3185   
3186   Double_t likeChi2Z  = TMath::Exp(-chi2[2] * 0.14);                    // Chi2Z 
3187   Double_t likeChi2TC = (fkReconstructor->GetRecoParam()->IsVertexConstrained()) ? 
3188                                                                                         TMath::Exp(-chi2[1] * 0.677) : 1;                       // Constrained Tilted Riemann
3189   Double_t likeChi2TR = TMath::Exp(-chi2[0] * 0.0078);                  // Non-constrained Tilted Riemann
3190   Double_t likeChi2Phi= TMath::Exp(-chi2phi * 3.23);//3.23
3191   Double_t trackLikelihood     = likeChi2Z * likeChi2TR * likeChi2Phi;
3192
3193   if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
3194     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
3195     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
3196     TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
3197     cstreamer << "CalculateTrackLikelihood0"
3198         << "EventNumber="                       << eventNumber
3199         << "CandidateNumber="   << candidateNumber
3200         << "LikeChi2Z="                         << likeChi2Z
3201         << "LikeChi2TR="                        << likeChi2TR
3202         << "LikeChi2TC="                        << likeChi2TC
3203         << "LikeChi2Phi="               << likeChi2Phi
3204         << "TrackLikelihood=" << trackLikelihood
3205         << "\n";
3206   }
3207   
3208   return trackLikelihood;
3209 }
3210
3211 //____________________________________________________________________
3212 Double_t AliTRDtrackerV1::CookLikelihood(AliTRDseedV1 *cseed, Int_t planes[4])
3213 {
3214   //
3215   // Calculate the probability of this track candidate.
3216   //
3217   // Parameters :
3218   //   cseeds : array of candidate tracklets
3219   //   planes : array of seeding planes (see seeding configuration)
3220   //   chi2   : chi2 values (on the Z and Y direction) from the rieman fit of the track.
3221   //
3222   // Output :
3223   //   likelihood value
3224   // 
3225   // Detailed description
3226   //
3227   // The track quality is estimated based on the following 4 criteria:
3228   //  1. precision of the rieman fit on the Y direction (likea)
3229   //  2. chi2 on the Y direction (likechi2y)
3230   //  3. chi2 on the Z direction (likechi2z)
3231   //  4. number of attached clusters compared to a reference value 
3232   //     (see AliTRDrecoParam::fkFindable) (likeN)
3233   //
3234   // The distributions for each type of probabilities are given below as of
3235   // (date). They have to be checked to assure consistency of estimation.
3236   //
3237
3238   // ratio of the total number of clusters/track which are expected to be found by the tracker.
3239   const AliTRDrecoParam *fRecoPars = fkReconstructor->GetRecoParam();
3240   
3241         Double_t chi2y = GetChi2Y(&cseed[0]);
3242   Double_t chi2z = GetChi2Z(&cseed[0]);
3243
3244   Float_t nclusters = 0.;
3245   Double_t sumda = 0.;
3246   for(UChar_t ilayer = 0; ilayer < 4; ilayer++){
3247     Int_t jlayer = planes[ilayer];
3248     nclusters += cseed[jlayer].GetN2();
3249     sumda += TMath::Abs(cseed[jlayer].GetYfit(1) - cseed[jlayer].GetYref(1));
3250   }
3251   nclusters *= .25;
3252
3253   Double_t likea     = TMath::Exp(-sumda * fRecoPars->GetPhiSlope());
3254   Double_t likechi2y  = 0.0000000001;
3255   if (fkReconstructor->IsCosmic() || chi2y < fRecoPars->GetChi2YCut()) likechi2y += TMath::Exp(-TMath::Sqrt(chi2y) * fRecoPars->GetChi2YSlope());
3256   Double_t likechi2z = TMath::Exp(-chi2z * fRecoPars->GetChi2ZSlope());
3257   Double_t likeN     = TMath::Exp(-(fRecoPars->GetNMeanClusters() - nclusters) / fRecoPars->GetNSigmaClusters());
3258   Double_t like      = likea * likechi2y * likechi2z * likeN;
3259
3260   if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
3261     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
3262     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
3263     Int_t nTracklets = 0; Float_t meanNcls = 0;
3264     for(Int_t iseed=0; iseed < kNPlanes; iseed++){
3265         if(!cseed[iseed].IsOK()) continue;
3266         nTracklets++;
3267         meanNcls += cseed[iseed].GetN2();
3268     }
3269     if(nTracklets) meanNcls /= nTracklets;
3270     // The Debug Stream contains the seed 
3271     TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
3272     cstreamer << "CookLikelihood"
3273         << "EventNumber="                       << eventNumber
3274         << "CandidateNumber=" << candidateNumber
3275         << "tracklet0.="                        << &cseed[0]
3276         << "tracklet1.="                        << &cseed[1]
3277         << "tracklet2.="                        << &cseed[2]
3278         << "tracklet3.="                        << &cseed[3]
3279         << "tracklet4.="                        << &cseed[4]
3280         << "tracklet5.="                        << &cseed[5]
3281         << "sumda="                                             << sumda
3282         << "chi2y="                                             << chi2y
3283         << "chi2z="                                             << chi2z
3284         << "likea="                                             << likea
3285         << "likechi2y="                         << likechi2y
3286         << "likechi2z="                         << likechi2z
3287         << "nclusters="                         << nclusters
3288         << "likeN="                                             << likeN
3289         << "like="                                              << like
3290         << "meanncls="        << meanNcls
3291         << "\n";
3292   }
3293
3294   return like;
3295 }
3296
3297 //____________________________________________________________________
3298 void AliTRDtrackerV1::GetSeedingConfig(Int_t iconfig, Int_t planes[4])
3299 {
3300   //
3301   // Map seeding configurations to detector planes.
3302   //
3303   // Parameters :
3304   //   iconfig : configuration index
3305   //   planes  : member planes of this configuration. On input empty.
3306   //
3307   // Output :
3308   //   planes : contains the planes which are defining the configuration
3309   // 
3310   // Detailed description
3311   //
3312   // Here is the list of seeding planes configurations together with
3313   // their topological classification:
3314   //
3315   //  0 - 5432 TQ 0
3316   //  1 - 4321 TQ 0
3317   //  2 - 3210 TQ 0
3318   //  3 - 5321 TQ 1
3319   //  4 - 4210 TQ 1
3320   //  5 - 5431 TQ 1
3321   //  6 - 4320 TQ 1
3322   //  7 - 5430 TQ 2
3323   //  8 - 5210 TQ 2
3324   //  9 - 5421 TQ 3
3325   // 10 - 4310 TQ 3
3326   // 11 - 5410 TQ 4
3327   // 12 - 5420 TQ 5
3328   // 13 - 5320 TQ 5
3329   // 14 - 5310 TQ 5
3330   //
3331   // The topologic quality is modeled as follows:
3332   // 1. The general model is define by the equation:
3333   //  p(conf) = exp(-conf/2)
3334   // 2. According to the topologic classification, configurations from the same
3335   //    class are assigned the agerage value over the model values.
3336   // 3. Quality values are normalized.
3337   // 
3338   // The topologic quality distribution as function of configuration is given below:
3339   //Begin_Html
3340   // <img src="gif/topologicQA.gif">
3341   //End_Html
3342   //
3343
3344   switch(iconfig){
3345   case 0: // 5432 TQ 0
3346     planes[0] = 2;
3347     planes[1] = 3;
3348     planes[2] = 4;
3349     planes[3] = 5;
3350     break;
3351   case 1: // 4321 TQ 0
3352     planes[0] = 1;
3353     planes[1] = 2;
3354     planes[2] = 3;
3355     planes[3] = 4;
3356     break;
3357   case 2: // 3210 TQ 0
3358     planes[0] = 0;
3359     planes[1] = 1;
3360     planes[2] = 2;
3361     planes[3] = 3;
3362     break;
3363   case 3: // 5321 TQ 1
3364     planes[0] = 1;
3365     planes[1] = 2;
3366     planes[2] = 3;
3367     planes[3] = 5;
3368     break;
3369   case 4: // 4210 TQ 1
3370     planes[0] = 0;
3371     planes[1] = 1;
3372     planes[2] = 2;
3373     planes[3] = 4;
3374     break;
3375   case 5: // 5431 TQ 1
3376     planes[0] = 1;
3377     planes[1] = 3;
3378     planes[2] = 4;
3379     planes[3] = 5;
3380     break;
3381   case 6: // 4320 TQ 1
3382     planes[0] = 0;
3383     planes[1] = 2;
3384     planes[2] = 3;
3385     planes[3] = 4;
3386     break;
3387   case 7: // 5430 TQ 2
3388     planes[0] = 0;
3389     planes[1] = 3;
3390     planes[2] = 4;
3391     planes[3] = 5;
3392     break;
3393   case 8: // 5210 TQ 2
3394     planes[0] = 0;
3395     planes[1] = 1;
3396     planes[2] = 2;
3397     planes[3] = 5;
3398     break;
3399   case 9: // 5421 TQ 3
3400     planes[0] = 1;
3401     planes[1] = 2;
3402     planes[2] = 4;
3403     planes[3] = 5;
3404     break;
3405   case 10: // 4310 TQ 3
3406     planes[0] = 0;
3407     planes[1] = 1;
3408     planes[2] = 3;
3409     planes[3] = 4;
3410     break;
3411   case 11: // 5410 TQ 4
3412     planes[0] = 0;
3413     planes[1] = 1;
3414     planes[2] = 4;
3415     planes[3] = 5;
3416     break;
3417   case 12: // 5420 TQ 5
3418     planes[0] = 0;
3419     planes[1] = 2;
3420     planes[2] = 4;
3421     planes[3] = 5;
3422     break;
3423   case 13: // 5320 TQ 5
3424     planes[0] = 0;
3425     planes[1] = 2;
3426     planes[2] = 3;
3427     planes[3] = 5;
3428     break;
3429   case 14: // 5310 TQ 5
3430     planes[0] = 0;
3431     planes[1] = 1;
3432     planes[2] = 3;
3433     planes[3] = 5;
3434     break;
3435   }
3436 }
3437
3438 //____________________________________________________________________
3439 void AliTRDtrackerV1::GetExtrapolationConfig(Int_t iconfig, Int_t planes[2])
3440 {
3441   //
3442   // Returns the extrapolation planes for a seeding configuration.
3443   //
3444   // Parameters :
3445   //   iconfig : configuration index
3446   //   planes  : planes which are not in this configuration. On input empty.
3447   //
3448   // Output :
3449   //   planes : contains the planes which are not in the configuration
3450   // 
3451   // Detailed description
3452   //
3453
3454   switch(iconfig){
3455   case 0: // 5432 TQ 0
3456     planes[0] = 1;
3457     planes[1] = 0;
3458     break;
3459   case 1: // 4321 TQ 0
3460     planes[0] = 5;
3461     planes[1] = 0;
3462     break;
3463   case 2: // 3210 TQ 0
3464     planes[0] = 4;
3465     planes[1] = 5;
3466     break;
3467   case 3: // 5321 TQ 1
3468     planes[0] = 4;
3469     planes[1] = 0;
3470     break;
3471   case 4: // 4210 TQ 1
3472     planes[0] = 5;
3473     planes[1] = 3;
3474     break;
3475   case 5: // 5431 TQ 1
3476     planes[0] = 2;
3477     planes[1] = 0;
3478     break;
3479   case 6: // 4320 TQ 1
3480     planes[0] = 5;
3481     planes[1] = 1;
3482     break;
3483   case 7: // 5430 TQ 2
3484     planes[0] = 2;
3485     planes[1] = 1;
3486     break;
3487   case 8: // 5210 TQ 2
3488     planes[0] = 4;
3489     planes[1] = 3;
3490     break;
3491   case 9: // 5421 TQ 3
3492     planes[0] = 3;
3493     planes[1] = 0;
3494     break;
3495   case 10: // 4310 TQ 3
3496     planes[0] = 5;
3497     planes[1] = 2;
3498     break;
3499   case 11: // 5410 TQ 4
3500     planes[0] = 3;
3501     planes[1] = 2;
3502     break;
3503   case 12: // 5420 TQ 5
3504     planes[0] = 3;
3505     planes[1] = 1;
3506     break;
3507   case 13: // 5320 TQ 5
3508     planes[0] = 4;
3509     planes[1] = 1;
3510     break;
3511   case 14: // 5310 TQ 5
3512     planes[0] = 4;
3513     planes[1] = 2;
3514     break;
3515   }
3516 }
3517
3518 //____________________________________________________________________
3519 AliCluster* AliTRDtrackerV1::GetCluster(Int_t idx) const
3520 {
3521   if(!fClusters) return NULL;
3522   Int_t ncls = fClusters->GetEntriesFast();
3523   return idx >= 0 && idx < ncls ? (AliCluster*)fClusters->UncheckedAt(idx) : NULL;
3524 }
3525
3526 //____________________________________________________________________
3527 AliTRDseedV1* AliTRDtrackerV1::GetTracklet(Int_t idx) const
3528 {
3529   if(!fTracklets) return NULL;
3530   Int_t ntrklt = fTracklets->GetEntriesFast();
3531   return idx >= 0 && idx < ntrklt ? (AliTRDseedV1*)fTracklets->UncheckedAt(idx) : NULL;
3532 }
3533
3534 //____________________________________________________________________
3535 AliKalmanTrack* AliTRDtrackerV1::GetTrack(Int_t idx) const
3536 {
3537   if(!fTracks) return NULL;
3538   Int_t ntrk = fTracks->GetEntriesFast();
3539   return idx >= 0 && idx < ntrk ? (AliKalmanTrack*)fTracks->UncheckedAt(idx) : NULL;
3540 }
3541
3542
3543
3544 // //_____________________________________________________________________________
3545 // Int_t AliTRDtrackerV1::Freq(Int_t n, const Int_t *inlist
3546 //           , Int_t *outlist, Bool_t down)
3547 // {    
3548 //   //
3549 //   // Sort eleements according occurancy 
3550 //   // The size of output array has is 2*n 
3551 //   //
3552 // 
3553 //   if (n <= 0) {
3554 //     return 0;
3555 //   }
3556 // 
3557 //   Int_t *sindexS = new Int_t[n];   // Temporary array for sorting
3558 //   Int_t *sindexF = new Int_t[2*n];   
3559 //   for (Int_t i = 0; i < n; i++) {
3560 //     sindexF[i] = 0;
3561 //   }
3562 // 
3563 //   TMath::Sort(n,inlist,sindexS,down); 
3564 // 
3565 //   Int_t last     = inlist[sindexS[0]];
3566 //   Int_t val      = last;
3567 //   sindexF[0]     = 1;
3568 //   sindexF[0+n]   = last;
3569 //   Int_t countPos = 0;
3570 // 
3571 //   // Find frequency
3572 //   for (Int_t i = 1; i < n; i++) {
3573 //     val = inlist[sindexS[i]];
3574 //     if (last == val) {
3575 //       sindexF[countPos]++;
3576 //     }
3577 //     else {      
3578 //       countPos++;
3579 //       sindexF[countPos+n] = val;
3580 //       sindexF[countPos]++;
3581 //       last                = val;
3582 //     }
3583 //   }
3584 //   if (last == val) {
3585 //     countPos++;
3586 //   }
3587 // 
3588 //   // Sort according frequency
3589 //   TMath::Sort(countPos,sindexF,sindexS,kTRUE);
3590 // 
3591 //   for (Int_t i = 0; i < countPos; i++) {
3592 //     outlist[2*i  ] = sindexF[sindexS[i]+n];
3593 //     outlist[2*i+1] = sindexF[sindexS[i]];
3594 //   }
3595 // 
3596 //   delete [] sindexS;
3597 //   delete [] sindexF;
3598 //   
3599 //   return countPos;
3600 // 
3601 // }
3602
3603
3604 //____________________________________________________________________
3605 void AliTRDtrackerV1::ResetSeedTB()
3606 {
3607 // reset buffer for seeding time bin layers. If the time bin 
3608 // layers are not allocated this function allocates them  
3609
3610   for(Int_t isl=0; isl<kNSeedPlanes; isl++){
3611     if(!fSeedTB[isl]) fSeedTB[isl] = new AliTRDchamberTimeBin();
3612     else fSeedTB[isl]->Clear();
3613   }
3614 }
3615
3616
3617 //_____________________________________________________________________________
3618 Float_t AliTRDtrackerV1::GetChi2Y(const AliTRDseedV1 * const tracklets) const
3619 {
3620   //    Calculates normalized chi2 in y-direction
3621   // chi2 = Sum chi2 / n_tracklets
3622
3623   Double_t chi2 = 0.; Int_t n = 0;
3624   for(Int_t ipl = kNPlanes; ipl--;){
3625     if(!tracklets[ipl].IsOK()) continue;
3626     chi2 += tracklets[ipl].GetChi2Y();
3627     n++;
3628   }
3629   return n ? chi2/n : 0.;
3630 }
3631
3632 //_____________________________________________________________________________
3633 Float_t AliTRDtrackerV1::GetChi2Z(const AliTRDseedV1 *const tracklets) const 
3634 {
3635   //    Calculates normalized chi2 in z-direction
3636   // chi2 = Sum chi2 / n_tracklets
3637
3638   Double_t chi2 = 0; Int_t n = 0;
3639   for(Int_t ipl = kNPlanes; ipl--;){
3640     if(!tracklets[ipl].IsOK()) continue;
3641     chi2 += tracklets[ipl].GetChi2Z();
3642     n++;
3643   }
3644   return n ? chi2/n : 0.;
3645 }
3646
3647 //____________________________________________________________________
3648 Float_t AliTRDtrackerV1::CalculateReferenceX(const AliTRDseedV1 *const tracklets){
3649         //
3650         // Calculates the reference x-position for the tilted Rieman fit defined as middle
3651         // of the stack (middle between layers 2 and 3). For the calculation all the tracklets
3652         // are taken into account
3653         //
3654         // Parameters: - Array of tracklets(AliTRDseedV1)
3655         //
3656         // Output: - The reference x-position(Float_t)
3657   // Only kept for compatibility with the old code
3658         //
3659         Int_t nDistances = 0;
3660         Float_t meanDistance = 0.;
3661         Int_t startIndex = 5;
3662         for(Int_t il =5; il > 0; il--){
3663         if(tracklets[il].IsOK() && tracklets[il -1].IsOK()){
3664         Float_t xdiff = tracklets[il].GetX0() - tracklets[il -1].GetX0();
3665             meanDistance += xdiff;
3666             nDistances++;
3667           }
3668           if(tracklets[il].IsOK()) startIndex = il;
3669         }
3670         if(tracklets[0].IsOK()) startIndex = 0;
3671         if(!nDistances){
3672           // We should normally never get here
3673           Float_t xpos[2]; memset(xpos, 0, sizeof(Float_t) * 2);
3674           Int_t iok = 0, idiff = 0;
3675           // This attempt is worse and should be avoided:
3676           // check for two chambers which are OK and repeat this without taking the mean value
3677           // Strategy avoids a division by 0;
3678           for(Int_t il = 5; il >= 0; il--){
3679             if(tracklets[il].IsOK()){
3680               xpos[iok] = tracklets[il].GetX0();
3681               iok++;
3682               startIndex = il;
3683             }
3684             if(iok) idiff++; // to get the right difference;
3685             if(iok > 1) break;
3686           }
3687           if(iok > 1){
3688             meanDistance = (xpos[0] - xpos[1])/idiff;
3689           }
3690           else{
3691             // we have do not even have 2 layers which are OK? The we do not need to fit at all
3692             return 331.;
3693         }
3694         }
3695         else{
3696           meanDistance /= nDistances;
3697         }
3698         return tracklets[startIndex].GetX0() + (2.5 - startIndex) * meanDistance - 0.5 * (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
3699 }
3700
3701 //_____________________________________________________________________________
3702 Double_t AliTRDtrackerV1::FitTiltedRiemanV1(AliTRDseedV1 *const tracklets){
3703   //
3704   // Track Fitter Function using the new class implementation of 
3705   // the Rieman fit
3706   //
3707   AliTRDtrackFitterRieman fitter;
3708   fitter.SetRiemanFitter(GetTiltedRiemanFitter());
3709   fitter.Reset();
3710   for(Int_t il = 0; il < AliTRDgeometry::kNlayer; il++) fitter.SetTracklet(il, &tracklets[il]);
3711   Double_t chi2 = fitter.Eval();
3712   // Update the tracklets
3713   Double_t cov[15]; Double_t x0;
3714   memset(cov, 0, sizeof(Double_t) * 15);
3715   for(Int_t il = 0; il < AliTRDgeometry::kNlayer; il++){
3716     x0 = tracklets[il].GetX0();
3717     tracklets[il].SetYref(0, fitter.GetYat(x0));
3718     tracklets[il].SetZref(0, fitter.GetZat(x0));
3719     tracklets[il].SetYref(1, fitter.GetDyDxAt(x0));
3720     tracklets[il].SetZref(1, fitter.GetDzDx());
3721     tracklets[il].SetC(fitter.GetCurvature());
3722     fitter.GetCovAt(x0, cov);
3723     tracklets[il].SetCovRef(cov);
3724     tracklets[il].SetChi2(chi2);
3725   }
3726   return chi2;
3727 }
3728
3729 ///////////////////////////////////////////////////////
3730 //                                                   //
3731 // Resources of class AliTRDLeastSquare              //
3732 //                                                   //
3733 ///////////////////////////////////////////////////////
3734
3735 //_____________________________________________________________________________
3736 AliTRDtrackerV1::AliTRDLeastSquare::AliTRDLeastSquare(){
3737 //
3738 // Constructor of the nested class AliTRDtrackFitterLeastSquare
3739 //
3740 // Fast solving linear regresion in 2D
3741 //         y=a + bx
3742 // The data members have the following meaning
3743 // fParams[0] : a
3744 // fParams[1] : b
3745 // 
3746 // fSums[0] : S
3747 // fSums[1] : Sx
3748 // fSums[2] : Sy
3749 // fSums[3] : Sxy
3750 // fSums[4] : Sxx
3751 // fSums[5] : Syy
3752 // 
3753 // fCovarianceMatrix[0] : s2a
3754 // fCovarianceMatrix[1] : s2b
3755 // fCovarianceMatrix[2] : cov(ab)
3756
3757   memset(fParams, 0, sizeof(Double_t) * 2);
3758   memset(fSums, 0, sizeof(Double_t) * 6);
3759   memset(fCovarianceMatrix, 0, sizeof(Double_t) * 3);
3760
3761 }
3762
3763 //_____________________________________________________________________________
3764 void AliTRDtrackerV1::AliTRDLeastSquare::AddPoint(const Double_t *const x, Double_t y, Double_t sigmaY){
3765   //
3766   // Adding Point to the fitter
3767   //
3768   
3769   Double_t weight = 1/(sigmaY > 1e-9 ? sigmaY : 1e-9);
3770   weight *= weight;
3771   const Double_t &xpt = *x;
3772   //    printf("Adding point x = %f, y = %f, sigma = %f\n", xpt, y, sigmaY);
3773   fSums[0] += weight;
3774   fSums[1] += weight * xpt;
3775   fSums[2] += weight * y;
3776   fSums[3] += weight * xpt * y;
3777   fSums[4] += weight * xpt * xpt;
3778   fSums[5] += weight * y * y;
3779 }
3780
3781 //_____________________________________________________________________________
3782 void AliTRDtrackerV1::AliTRDLeastSquare::RemovePoint(const Double_t *const x, Double_t y, Double_t sigmaY){
3783   //
3784   // Remove Point from the sample
3785   //
3786
3787   Double_t weight = 1/(sigmaY > 1e-9 ? sigmaY : 1e-9);
3788   weight *= weight;
3789   const Double_t &xpt = *x; 
3790   fSums[0] -= weight;
3791   fSums[1] -= weight * xpt;
3792   fSums[2] -= weight * y;
3793   fSums[3] -= weight * xpt * y;
3794   fSums[4] -= weight * xpt * xpt;
3795   fSums[5] -= weight * y * y;
3796 }
3797
3798 //_____________________________________________________________________________
3799 Bool_t AliTRDtrackerV1::AliTRDLeastSquare::Eval(){
3800   //
3801   // Evaluation of the fit:
3802   // Calculation of the parameters
3803   // Calculation of the covariance matrix
3804   //
3805   
3806   Double_t det = fSums[0] * fSums[4] - fSums[1] *fSums[1];
3807   if(det==0) return kFALSE;
3808
3809   //    for(Int_t isum = 0; isum < 5; isum++)
3810   //            printf("fSums[%d] = %f\n", isum, fSums[isum]);
3811   //    printf("denominator = %f\n", denominator);
3812   fParams[0] = (fSums[2] * fSums[4] - fSums[1] * fSums[3])/det;
3813   fParams[1] = (fSums[0] * fSums[3] - fSums[1] * fSums[2])/det;
3814   //    printf("fParams[0] = %f, fParams[1] = %f\n", fParams[0], fParams[1]);
3815   
3816   // Covariance matrix
3817   Double_t den = fSums[0]*fSums[4] - fSums[1]*fSums[1];
3818   fCovarianceMatrix[0] = fSums[4] / den;
3819   fCovarianceMatrix[1] = fSums[0] / den;
3820   fCovarianceMatrix[2] = -fSums[1] / den;
3821 /*  fCovarianceMatrix[0] = fSums[4] / fSums[0] - fSums[1] * fSums[1] / (fSums[0] * fSums[0]);
3822   fCovarianceMatrix[1] = fSums[5] / fSums[0] - fSums[2] * fSums[2] / (fSums[0] * fSums[0]);
3823   fCovarianceMatrix[2] = fSums[3] / fSums[0] - fSums[1] * fSums[2] / (fSums[0] * fSums[0]);*/
3824
3825
3826
3827   return kTRUE;
3828 }
3829
3830 //_____________________________________________________________________________
3831 Double_t AliTRDtrackerV1::AliTRDLeastSquare::GetFunctionValue(const Double_t *const xpos) const {
3832   //
3833   // Returns the Function value of the fitted function at a given x-position
3834   //
3835   return fParams[0] + fParams[1] * (*xpos);
3836 }
3837
3838 //_____________________________________________________________________________
3839 void AliTRDtrackerV1::AliTRDLeastSquare::GetCovarianceMatrix(Double_t *storage) const {
3840   //
3841   // Copies the values of the covariance matrix into the storage
3842   //
3843   memcpy(storage, fCovarianceMatrix, sizeof(Double_t) * 3);
3844 }
3845
3846 //_____________________________________________________________________________
3847 void AliTRDtrackerV1::AliTRDLeastSquare::Reset(){
3848   //
3849   // Reset the fitter
3850   //
3851   memset(fParams, 0, sizeof(Double_t) * 2);
3852   memset(fCovarianceMatrix, 0, sizeof(Double_t) * 3);
3853   memset(fSums, 0, sizeof(Double_t) * 6);
3854 }
3855
3856 ///////////////////////////////////////////////////////
3857 //                                                   //
3858 // Resources of class AliTRDtrackFitterRieman        //
3859 //                                                   //
3860 ///////////////////////////////////////////////////////
3861
3862 //_____________________________________________________________________________
3863 AliTRDtrackerV1::AliTRDtrackFitterRieman::AliTRDtrackFitterRieman():
3864   fTrackFitter(NULL),
3865   fZfitter(NULL),
3866   fCovarPolY(NULL),
3867   fCovarPolZ(NULL),
3868   fXref(0.),
3869   fSysClusterError(0.)
3870 {
3871   //
3872   // Default constructor
3873   //
3874   fZfitter = new AliTRDLeastSquare;
3875   fCovarPolY = new TMatrixD(3,3);
3876   fCovarPolZ = new TMatrixD(2,2);
3877   memset(fTracklets, 0, sizeof(AliTRDseedV1 *) * 6);
3878   memset(fParameters, 0, sizeof(Double_t) * 5);
3879   memset(fSumPolY, 0, sizeof(Double_t) * 5);
3880   memset(fSumPolZ, 0, sizeof(Double_t) * 2);
3881 }
3882
3883 //_____________________________________________________________________________
3884 AliTRDtrackerV1::AliTRDtrackFitterRieman::~AliTRDtrackFitterRieman(){
3885   //
3886   // Destructor
3887   //
3888   if(fZfitter) delete fZfitter;
3889   if(fCovarPolY) delete fCovarPolY;
3890   if(fCovarPolZ) delete fCovarPolZ;
3891 }
3892
3893 //_____________________________________________________________________________
3894 void AliTRDtrackerV1::AliTRDtrackFitterRieman::Reset(){
3895   //
3896   // Reset the Fitter
3897   //
3898   if(fTrackFitter){
3899     fTrackFitter->StoreData(kTRUE);
3900     fTrackFitter->ClearPoints();
3901   }
3902   if(fZfitter){
3903     fZfitter->Reset();
3904   }
3905   fXref = 0.;
3906   memset(fTracklets, 0, sizeof(AliTRDseedV1 *) * AliTRDgeometry::kNlayer);
3907   memset(fParameters, 0, sizeof(Double_t) * 5);
3908   memset(fSumPolY, 0, sizeof(Double_t) * 5);
3909   memset(fSumPolZ, 0, sizeof(Double_t) * 2);
3910   for(Int_t irow = 0; irow < fCovarPolY->GetNrows(); irow++)
3911     for(Int_t icol = 0; icol < fCovarPolY->GetNcols(); icol++){
3912       (*fCovarPolY)(irow, icol) = 0.;
3913       if(irow < 2 && icol < 2)
3914         (*fCovarPolZ)(irow, icol) = 0.;
3915     }
3916 }
3917
3918 //_____________________________________________________________________________
3919 void AliTRDtrackerV1::AliTRDtrackFitterRieman::SetTracklet(Int_t itr, AliTRDseedV1 *tracklet){ 
3920   //
3921   // Add tracklet into the fitter
3922   //
3923   if(itr >= AliTRDgeometry::kNlayer) return;
3924   fTracklets[itr] = tracklet; 
3925 }
3926
3927 //_____________________________________________________________________________
3928 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::Eval(){
3929   //
3930   // Perform the fit
3931   // 1. Apply linear transformation and store points in the fitter
3932   // 2. Evaluate the fit
3933   // 3. Check if the result of the fit in z-direction is reasonable
3934   // if not
3935   // 3a. Fix the parameters 3 and 4 with the results of a simple least
3936   //     square fit
3937   // 3b. Redo the fit with the fixed parameters
3938   // 4. Store fit results (parameters and errors)
3939   //
3940   if(!fTrackFitter){
3941     return 1e10;
3942   }
3943   fXref = CalculateReferenceX();
3944   for(Int_t il = 0; il < AliTRDgeometry::kNlayer; il++) UpdateFitters(fTracklets[il]);
3945   if(!fTrackFitter->GetNpoints()) return 1e10;
3946   // perform the fit
3947   fTrackFitter->Eval();
3948   fZfitter->Eval();
3949   fParameters[3] = fTrackFitter->GetParameter(3);
3950   fParameters[4] = fTrackFitter->GetParameter(4);
3951   if(!CheckAcceptable(fParameters[3], fParameters[4])) {
3952     fTrackFitter->FixParameter(3, fZfitter->GetFunctionValue(&fXref));
3953     fTrackFitter->FixParameter(4, fZfitter->GetFunctionParameter(1));
3954     fTrackFitter->Eval();
3955     fTrackFitter->ReleaseParameter(3);
3956     fTrackFitter->ReleaseParameter(4);
3957     fParameters[3] = fTrackFitter->GetParameter(3);
3958     fParameters[4] = fTrackFitter->GetParameter(4);
3959   }
3960   // Update the Fit Parameters and the errors
3961   fParameters[0] = fTrackFitter->GetParameter(0);
3962   fParameters[1] = fTrackFitter->GetParameter(1);
3963   fParameters[2] = fTrackFitter->GetParameter(2);
3964
3965   // Prepare Covariance estimation
3966   (*fCovarPolY)(0,0) = fSumPolY[0]; (*fCovarPolY)(1,1) = fSumPolY[2]; (*fCovarPolY)(2,2) = fSumPolY[4];
3967   (*fCovarPolY)(1,0) = (*fCovarPolY)(0,1) = fSumPolY[1];
3968   (*fCovarPolY)(2,0) = (*fCovarPolY)(0,2) = fSumPolY[2];
3969   (*fCovarPolY)(2,1) = (*fCovarPolY)(1,2) = fSumPolY[3];
3970   fCovarPolY->Invert();
3971   (*fCovarPolZ)(0,0) = fSumPolZ[0]; (*fCovarPolZ)(1,1) = fSumPolZ[2];
3972   (*fCovarPolZ)(1,0) = (*fCovarPolZ)(0,1) = fSumPolZ[1];
3973   fCovarPolZ->Invert();
3974   return fTrackFitter->GetChisquare() / fTrackFitter->GetNpoints();
3975 }
3976
3977 //_____________________________________________________________________________
3978 void AliTRDtrackerV1::AliTRDtrackFitterRieman::UpdateFitters(AliTRDseedV1 * const tracklet){
3979   //
3980   // Does the transformations and updates the fitters
3981   // The following transformation is applied
3982   //
3983   AliTRDcluster *cl = NULL;
3984   Double_t x, y, z, dx, t, w, we, yerr, zerr;
3985   Double_t uvt[4];
3986   if(!tracklet || !tracklet->IsOK()) return; 
3987   Double_t tilt = tracklet->GetTilt();
3988   for(Int_t itb = 0; itb < AliTRDseedV1::kNclusters; itb++){
3989     if(!(cl = tracklet->GetClusters(itb))) continue;
3990     if(!cl->IsInChamber()) continue;
3991     if (!tracklet->IsUsable(itb)) continue;
3992     x = cl->GetX();
3993     y = cl->GetY();
3994     z = cl->GetZ();
3995     dx = x - fXref;
3996     // Transformation
3997     t = 1./(x*x + y*y);
3998     uvt[0] = 2. * x * t;
3999     uvt[1] = t;
4000     uvt[2] = 2. * tilt * t;
4001     uvt[3] = 2. * tilt * dx * t;
4002     w = 2. * (y + tilt*z) * t;
4003     // error definition changes for the different calls
4004     we = 2. * t;
4005     we *= TMath::Sqrt(cl->GetSigmaY2()+tilt*tilt*cl->GetSigmaZ2());
4006     // Update sums for error calculation
4007     yerr = 1./(TMath::Sqrt(cl->GetSigmaY2()) + fSysClusterError);
4008     yerr *= yerr;
4009     zerr = 1./cl->GetSigmaZ2();
4010     for(Int_t ipol = 0; ipol < 5; ipol++){
4011       fSumPolY[ipol] += yerr;
4012       yerr *= x;
4013       if(ipol < 3){
4014         fSumPolZ[ipol] += zerr;
4015         zerr *= x;
4016       }
4017     }
4018     fTrackFitter->AddPoint(uvt, w, we);
4019     fZfitter->AddPoint(&x, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
4020   }
4021 }
4022
4023 //_____________________________________________________________________________
4024 Bool_t AliTRDtrackerV1::AliTRDtrackFitterRieman::CheckAcceptable(Double_t offset, Double_t slope){
4025   // 
4026   // Check whether z-results are acceptable
4027   // Definition: Distance between tracklet fit and track fit has to be
4028   // less then half a padlength
4029   // Point of comparision is at the anode wire
4030   //
4031   Bool_t acceptablez = kTRUE;
4032   Double_t zref = 0.0;
4033   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
4034     if(!fTracklets[iLayer]->IsOK()) continue;
4035     zref = offset + slope * (fTracklets[iLayer]->GetX0() - fXref);
4036     if (TMath::Abs(fTracklets[iLayer]->GetZfit(0) - zref) > fTracklets[iLayer]->GetPadLength() * 0.5 + 1.0) 
4037       acceptablez = kFALSE;
4038   }
4039   return acceptablez;
4040 }
4041
4042 //_____________________________________________________________________________
4043 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetYat(Double_t x) const {
4044   //
4045   // Calculate y position out of the track parameters
4046   // y:     R^2 = (x - x0)^2 + (y - y0)^2
4047   //     =>   y = y0 +/- Sqrt(R^2 - (x - x0)^2)
4048   //          R = Sqrt() = 1/Curvature
4049   //     =>   y = y0 +/- Sqrt(1/Curvature^2 - (x - x0)^2)
4050   //
4051   Double_t y = 0;
4052   Double_t disc = (x * fParameters[0] + fParameters[1]);
4053   disc = 1 - fParameters[0]*fParameters[2] + fParameters[1]*fParameters[1] - disc*disc;
4054   if (disc >= 0) {
4055     disc = TMath::Sqrt(disc);
4056     y    = (1.0 - disc) / fParameters[0];
4057   }
4058   return y;
4059 }
4060
4061 //_____________________________________________________________________________
4062 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetZat(Double_t x) const {
4063   //
4064   // Return z position for a given x position
4065   // Simple linear function
4066   //
4067   return fParameters[3] + fParameters[4] * (x - fXref);
4068 }
4069
4070 //_____________________________________________________________________________
4071 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetDyDxAt(Double_t x) const {
4072   //
4073   // Calculate dydx at a given radial position out of the track parameters
4074   // dy:      R^2 = (x - x0)^2 + (y - y0)^2
4075   //     =>     y = +/- Sqrt(R^2 - (x - x0)^2) + y0
4076   //     => dy/dx = (x - x0)/Sqrt(R^2 - (x - x0)^2) 
4077   // Curvature: cr = 1/R = a/Sqrt(1 + b^2 - c*a)
4078   //     => dy/dx =  (x - x0)/(1/(cr^2) - (x - x0)^2) 
4079   //
4080   Double_t x0 = -fParameters[1] / fParameters[0];
4081   Double_t curvature = GetCurvature();
4082   Double_t dy = 0;
4083   if (-fParameters[2] * fParameters[0] + fParameters[1] * fParameters[1] + 1 > 0) {
4084     if (1.0/(curvature * curvature) - (x - x0) * (x - x0) > 0.0) {
4085      Double_t yderiv = (x - x0) / TMath::Sqrt(1.0/(curvature * curvature) - (x - x0) * (x - x0));
4086       if (fParameters[0] < 0) yderiv *= -1.0;
4087       dy = yderiv;
4088     }
4089   }
4090   return dy;
4091 }
4092
4093 //_____________________________________________________________________________
4094 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetCurvature() const {
4095   //
4096   // Calculate track curvature
4097   //
4098   //
4099   Double_t curvature =  1.0 + fParameters[1]*fParameters[1] - fParameters[2]*fParameters[0];
4100   if (curvature > 0.0) 
4101     curvature  =  fParameters[0] / TMath::Sqrt(curvature);
4102   return curvature;
4103 }
4104
4105 //_____________________________________________________________________________
4106 void AliTRDtrackerV1::AliTRDtrackFitterRieman::GetCovAt(Double_t x, Double_t *cov) const {
4107   //
4108   // Error Definition according to gauss error propagation
4109   //  
4110   TMatrixD transform(3,3);
4111   transform(0,0) = transform(1,1) = transform(2,2) = 1;
4112   transform(0,1) = transform(1,2) = x;
4113   transform(0,2) = x*x;
4114   TMatrixD covariance(transform, TMatrixD::kMult, *fCovarPolY);
4115   covariance *= transform.T();
4116   cov[0] = covariance(0,0);
4117   TMatrixD transformZ(2,2);
4118   transformZ(0,0) = transformZ(1,1) = 1;
4119   transformZ(0,1) = x;
4120   TMatrixD covarZ(transformZ, TMatrixD::kMult, *fCovarPolZ);
4121   covarZ *= transformZ.T();
4122   cov[1] = covarZ(0,0);
4123   cov[2] = 0;
4124 }
4125
4126 //____________________________________________________________________
4127 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::CalculateReferenceX(){
4128   //
4129   // Calculates the reference x-position for the tilted Rieman fit defined as middle
4130   // of the stack (middle between layers 2 and 3). For the calculation all the tracklets
4131   // are taken into account
4132   // 
4133   // Parameters:        - Array of tracklets(AliTRDseedV1)
4134   //
4135   // Output:            - The reference x-position(Float_t)
4136   //
4137   Int_t nDistances = 0;
4138   Float_t meanDistance = 0.;
4139   Int_t startIndex = 5;
4140   for(Int_t il =5; il > 0; il--){
4141     if(fTracklets[il]->IsOK() && fTracklets[il -1]->IsOK()){
4142       Float_t xdiff = fTracklets[il]->GetX0() - fTracklets[il -1]->GetX0();
4143       meanDistance += xdiff;
4144       nDistances++;
4145     }
4146     if(fTracklets[il]->IsOK()) startIndex = il;
4147   }
4148   if(fTracklets[0]->IsOK()) startIndex = 0;
4149   if(!nDistances){
4150     // We should normally never get here
4151     Float_t xpos[2]; memset(xpos, 0, sizeof(Float_t) * 2);
4152     Int_t iok = 0, idiff = 0;
4153     // This attempt is worse and should be avoided:
4154     // check for two chambers which are OK and repeat this without taking the mean value
4155     // Strategy avoids a division by 0;
4156     for(Int_t il = 5; il >= 0; il--){
4157       if(fTracklets[il]->IsOK()){
4158         xpos[iok] = fTracklets[il]->GetX0();
4159         iok++;
4160         startIndex = il;
4161       }
4162       if(iok) idiff++;  // to get the right difference;
4163       if(iok > 1) break;
4164     }
4165     if(iok > 1){
4166       meanDistance = (xpos[0] - xpos[1])/idiff;
4167     }
4168     else{
4169       // we have do not even have 2 layers which are OK? The we do not need to fit at all
4170       return 331.;
4171     }
4172   }
4173   else{
4174     meanDistance /= nDistances;
4175   }
4176   return fTracklets[startIndex]->GetX0() + (2.5 - startIndex) * meanDistance - 0.5 * (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
4177 }