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