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