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