]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDtrackerV1.cxx
5d68103f88bf4532ffc00963783623167b8362e8
[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     AliDebug(2, Form("NTimeBins [%d] (set from digits param)", fgNTimeBins));
2094   } else { // third query DB
2095     AliTRDcalibDB *trd(NULL);
2096     if((trd = AliTRDcalibDB::Instance())) {
2097       if((fgNTimeBins = trd->GetNumberOfTimeBinsDCS()) <= 0){
2098         AliError("Corrupted DCS Object in OCDB");
2099         fgNTimeBins = 24;
2100         AliDebug(2, Form("NTimeBins [%d] (set to default)", fgNTimeBins));
2101       } else AliDebug(2, Form("NTimeBins [%d] (set from DB)", fgNTimeBins));
2102     } else AliFatal("Could not get DB.");
2103   }
2104   if(fgNTimeBins<=0){
2105     AliFatal("Could not get number of time bins.");
2106   }
2107 }
2108
2109 //____________________________________________________________________
2110 AliTRDtrackV1* AliTRDtrackerV1::SetTrack(const AliTRDtrackV1 * const track)
2111 {
2112   // Add this track to the list of tracks stored in the tracker
2113   //
2114   // Parameters
2115   //   - track : pointer to the track to be added to the list
2116   //
2117   // Output
2118   //   - the pointer added
2119   //
2120   // Detailed description
2121   // Build the tracks list if it is not yet created (late initialization)
2122   // and adds the new track to the list.
2123   //
2124   if(!fTracks){
2125     fTracks = new TClonesArray("AliTRDtrackV1", AliTRDgeometry::Nsector()*kMaxTracksStack);
2126     fTracks->SetOwner(kTRUE);
2127   }
2128   Int_t nentries = fTracks->GetEntriesFast();
2129   return new ((*fTracks)[nentries]) AliTRDtrackV1(*track);
2130 }
2131
2132
2133
2134 //____________________________________________________________________
2135 Int_t AliTRDtrackerV1::Clusters2TracksSM(Int_t sector, AliESDEvent *esd)
2136 {
2137   //
2138   // Steer tracking for one SM.
2139   //
2140   // Parameters :
2141   //   sector  : Array of (SM) propagation layers containing clusters
2142   //   esd     : The current ESD event. On output it contains the also
2143   //             the ESD (TRD) tracks found in this SM. 
2144   //
2145   // Output :
2146   //   Number of tracks found in this TRD supermodule.
2147   // 
2148   // Detailed description
2149   //
2150   // 1. Unpack AliTRDpropagationLayers objects for each stack.
2151   // 2. Launch stack tracking. 
2152   //    See AliTRDtrackerV1::Clusters2TracksStack() for details.
2153   // 3. Pack results in the ESD event.
2154   //
2155   
2156   Int_t nTracks   = 0;
2157   Int_t nChambers = 0;
2158   AliTRDtrackingChamber **stack = NULL, *chamber = NULL;
2159   for(int istack = 0; istack<AliTRDgeometry::kNstack; istack++){
2160     if(!(stack = fTrSec[sector].GetStack(istack))) continue;
2161     nChambers = 0;
2162     for(int ilayer=0; ilayer<AliTRDgeometry::kNlayer; ilayer++){
2163       if(!(chamber = stack[ilayer])) continue;
2164       if(chamber->GetNClusters() < fgNTimeBins * fkReconstructor->GetRecoParam() ->GetFindableClusters()) continue;
2165       nChambers++;
2166       //AliInfo(Form("sector %d stack %d layer %d clusters %d", sector, istack, ilayer, chamber->GetNClusters()));
2167     }
2168     if(nChambers < 4) continue;
2169     //AliInfo(Form("Doing stack %d", istack));
2170     nTracks += Clusters2TracksStack(stack, fTracksESD);
2171   }
2172   //AliInfo(Form("Found %d tracks in SM %d [%d]\n", nTracks, sector, esd->GetNumberOfTracks()));
2173   
2174   for(int itrack=0; itrack<nTracks; itrack++)
2175     esd->AddTrack((AliESDtrack*)(fTracksESD->operator[](itrack)));
2176
2177   // Reset Track and Candidate Number
2178   AliTRDtrackerDebug::SetCandidateNumber(0);
2179   AliTRDtrackerDebug::SetTrackNumber(0);
2180
2181   // delete ESD tracks in the array
2182   fTracksESD->Delete();
2183   return nTracks;
2184 }
2185
2186 //____________________________________________________________________
2187 Int_t AliTRDtrackerV1::Clusters2TracksStack(AliTRDtrackingChamber **stack, TClonesArray * const esdTrackList)
2188 {
2189   //
2190   // Make tracks in one TRD stack.
2191   //
2192   // Parameters :
2193   //   layer  : Array of stack propagation layers containing clusters
2194   //   esdTrackList  : Array of ESD tracks found by the stand alone tracker. 
2195   //                   On exit the tracks found in this stack are appended.
2196   //
2197   // Output :
2198   //   Number of tracks found in this stack.
2199   // 
2200   // Detailed description
2201   //
2202   // 1. Find the 3 most useful seeding chambers. See BuildSeedingConfigs() for details.
2203   // 2. Steer AliTRDtrackerV1::MakeSeeds() for 3 seeding layer configurations. 
2204   //    See AliTRDtrackerV1::MakeSeeds() for more details.
2205   // 3. Arrange track candidates in decreasing order of their quality
2206   // 4. Classify tracks in 5 categories according to:
2207   //    a) number of layers crossed
2208   //    b) track quality 
2209   // 5. Sign clusters by tracks in decreasing order of track quality
2210   // 6. Build AliTRDtrack out of seeding tracklets
2211   // 7. Cook MC label
2212   // 8. Build ESD track and register it to the output list
2213   //
2214
2215   const AliTRDCalDet *cal = AliTRDcalibDB::Instance()->GetT0Det();
2216   AliTRDtrackingChamber *chamber = NULL;
2217   AliTRDtrackingChamber **ci = NULL;
2218   AliTRDseedV1 sseed[kMaxTracksStack*6]; // to be initialized
2219   Int_t pars[4]; // MakeSeeds parameters
2220
2221   //Double_t alpha = AliTRDgeometry::GetAlpha();
2222   //Double_t shift = .5 * alpha;
2223   Int_t configs[kNConfigs];
2224   
2225   // Purge used clusters from the containers
2226   ci = &stack[0];
2227   for(Int_t ic = kNPlanes; ic--; ci++){
2228     if(!(*ci)) continue;
2229     (*ci)->Update();
2230   }
2231
2232   // Build initial seeding configurations
2233   Double_t quality = BuildSeedingConfigs(stack, configs);
2234   if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 10){
2235     AliInfo(Form("Plane config %d %d %d Quality %f"
2236     , configs[0], configs[1], configs[2], quality));
2237   }
2238
2239   
2240   // Initialize contors
2241   Int_t ntracks,      // number of TRD track candidates
2242     ntracks1,     // number of registered TRD tracks/iter
2243     ntracks2 = 0; // number of all registered TRD tracks in stack
2244   fSieveSeeding = 0;
2245
2246   // Get stack index
2247   Int_t ic = 0; ci = &stack[0];
2248   while(ic<kNPlanes && !(*ci)){ic++; ci++;}
2249   if(!(*ci)) return ntracks2;
2250   Int_t istack = fGeom->GetStack((*ci)->GetDetector());
2251
2252   do{
2253     // Loop over seeding configurations
2254     ntracks = 0; ntracks1 = 0;
2255     for (Int_t iconf = 0; iconf<3; iconf++) {
2256       pars[0] = configs[iconf];
2257       pars[1] = ntracks;
2258       pars[2] = istack;
2259       ntracks = MakeSeeds(stack, &sseed[6*ntracks], pars);
2260       //AliInfo(Form("Number of Tracks after iteration step %d: %d\n", iconf, ntracks));
2261       if(ntracks == kMaxTracksStack) break;
2262     }
2263     AliDebug(2, Form("Candidate TRD tracks %d in iteration %d.", ntracks, fSieveSeeding));
2264     
2265     if(!ntracks) break;
2266     
2267     // Sort the seeds according to their quality
2268     Int_t sort[kMaxTracksStack];
2269     TMath::Sort(ntracks, fTrackQuality, sort, kTRUE);
2270   
2271     // Initialize number of tracks so far and logic switches
2272     Int_t ntracks0 = esdTrackList->GetEntriesFast();
2273     Bool_t signedTrack[kMaxTracksStack];
2274     Bool_t fakeTrack[kMaxTracksStack];
2275     for (Int_t i=0; i<ntracks; i++){
2276       signedTrack[i] = kFALSE;
2277       fakeTrack[i] = kFALSE;
2278     }
2279     //AliInfo("Selecting track candidates ...");
2280     
2281     // Sieve clusters in decreasing order of track quality
2282     Double_t trackParams[7];
2283     //          AliTRDseedV1 *lseed = NULL;
2284     Int_t jSieve = 0, candidates;
2285     do{
2286       //AliInfo(Form("\t\tITER = %i ", jSieve));
2287
2288       // Check track candidates
2289       candidates = 0;
2290       for (Int_t itrack = 0; itrack < ntracks; itrack++) {
2291         Int_t trackIndex = sort[itrack];
2292         if (signedTrack[trackIndex] || fakeTrack[trackIndex]) continue;
2293   
2294         
2295         // Calculate track parameters from tracklets seeds
2296         Int_t ncl        = 0;
2297         Int_t nused      = 0;
2298         Int_t nlayers    = 0;
2299         Int_t findable   = 0;
2300         for (Int_t jLayer = 0; jLayer < kNPlanes; jLayer++) {
2301           Int_t jseed = kNPlanes*trackIndex+jLayer;
2302           if(!sseed[jseed].IsOK()) continue;
2303           if (TMath::Abs(sseed[jseed].GetYref(0) / sseed[jseed].GetX0()) < 0.158) findable++;
2304           // TODO here we get a sig fault which should never happen !
2305           sseed[jseed].UpdateUsed();
2306           ncl   += sseed[jseed].GetN2();
2307           nused += sseed[jseed].GetNUsed();
2308           nlayers++;
2309         }
2310
2311         // Filter duplicated tracks
2312         if (nused > 30){
2313           //printf("Skip %d nused %d\n", trackIndex, nused);
2314           fakeTrack[trackIndex] = kTRUE;
2315           continue;
2316         }
2317         if (ncl>0 && Float_t(nused)/ncl >= .25){
2318           //printf("Skip %d nused/ncl >= .25\n", trackIndex);
2319           fakeTrack[trackIndex] = kTRUE;
2320           continue;
2321         }
2322
2323         // Classify tracks
2324         Bool_t skip = kFALSE;
2325         switch(jSieve){
2326           case 0:
2327             if(nlayers < 6) {skip = kTRUE; break;}
2328             if(TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -5.){skip = kTRUE; break;}
2329             break;
2330
2331           case 1:
2332             if(nlayers < findable){skip = kTRUE; break;}
2333             if(TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -4.){skip = kTRUE; break;}
2334             break;
2335
2336           case 2:
2337             if ((nlayers == findable) || (nlayers == 6)) { skip = kTRUE; break;}
2338             if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -6.0){skip = kTRUE; break;}
2339             break;
2340
2341           case 3:
2342             if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -5.){skip = kTRUE; break;}
2343             break;
2344
2345           case 4:
2346             if (nlayers == 3){skip = kTRUE; break;}
2347             //if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) - nused/(nlayers-3.0) < -15.0){skip = kTRUE; break;}
2348             break;
2349         }
2350         if(skip){
2351           candidates++;
2352           AliDebug(4, Form("REJECTED : %d idx[%d] quality[%e] tracklets[%d] usedClusters[%d]", itrack, trackIndex, fTrackQuality[trackIndex], nlayers, nused));
2353           continue;
2354         } else AliDebug(4, Form("ACCEPTED : %d idx[%d] quality[%e] tracklets[%d] usedClusters[%d]", itrack, trackIndex, fTrackQuality[trackIndex], nlayers, nused));
2355
2356         signedTrack[trackIndex] = kTRUE;
2357
2358         // Build track parameters
2359         AliTRDseedV1 *lseed =&sseed[trackIndex*6];
2360       /*  Int_t idx = 0;
2361         while(idx<3 && !lseed->IsOK()) {
2362           idx++;
2363           lseed++;
2364         }*/
2365         Double_t x = lseed->GetX0();// - 3.5;
2366         trackParams[0] = x; //NEW AB
2367         trackParams[1] = lseed->GetYref(0); // lseed->GetYat(x);  
2368         trackParams[2] = lseed->GetZref(0); // lseed->GetZat(x); 
2369         trackParams[3] = TMath::Sin(TMath::ATan(lseed->GetYref(1)));
2370         trackParams[4] = lseed->GetZref(1) / TMath::Sqrt(1. + lseed->GetYref(1) * lseed->GetYref(1));
2371         trackParams[5] = lseed->GetC();
2372         Int_t ich = 0; while(!(chamber = stack[ich])) ich++;
2373         trackParams[6] = fGeom->GetSector(chamber->GetDetector());/* *alpha+shift;      // Supermodule*/
2374
2375         if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 1 && fkReconstructor->IsDebugStreaming()){
2376           //AliInfo(Form("Track %d [%d] nlayers %d trackQuality = %e nused %d, yref = %3.3f", itrack, trackIndex, nlayers, fTrackQuality[trackIndex], nused, trackParams[1]));
2377
2378           AliTRDseedV1 *dseed[6];
2379           for(Int_t iseed = AliTRDgeometry::kNlayer; iseed--;) dseed[iseed] = new AliTRDseedV1(lseed[iseed]);
2380
2381           //Int_t eventNrInFile = esd->GetEventNumberInFile();
2382           Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2383           Int_t trackNumber = AliTRDtrackerDebug::GetTrackNumber();
2384           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2385           TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
2386           cstreamer << "Clusters2TracksStack"
2387               << "EventNumber="         << eventNumber
2388               << "TrackNumber="         << trackNumber
2389               << "CandidateNumber="     << candidateNumber
2390               << "Iter="                                << fSieveSeeding
2391               << "Like="                                << fTrackQuality[trackIndex]
2392               << "S0.="                         << dseed[0]
2393               << "S1.="                         << dseed[1]
2394               << "S2.="                         << dseed[2]
2395               << "S3.="                         << dseed[3]
2396               << "S4.="                         << dseed[4]
2397               << "S5.="                         << dseed[5]
2398               << "p0="                          << trackParams[0]
2399               << "p1="                          << trackParams[1]
2400               << "p2="                          << trackParams[2]
2401               << "p3="                          << trackParams[3]
2402               << "p4="                          << trackParams[4]
2403               << "p5="                          << trackParams[5]
2404               << "p6="                          << trackParams[6]
2405               << "Ncl="                         << ncl
2406               << "NLayers="                     << nlayers
2407               << "Findable="                    << findable
2408               << "NUsed="                               << nused
2409               << "\n";
2410         }
2411
2412         AliTRDtrackV1 *track = MakeTrack(&sseed[trackIndex*kNPlanes], trackParams);
2413         if(!track){
2414           AliDebug(1, "Track building failed.");
2415           continue;
2416         }
2417       
2418         //AliInfo("End of MakeTrack()");
2419         AliESDtrack *esdTrack = new ((*esdTrackList)[ntracks0++]) AliESDtrack();
2420         esdTrack->UpdateTrackParams(track, AliESDtrack::kTRDout);
2421         esdTrack->SetLabel(track->GetLabel());
2422         track->UpdateESDtrack(esdTrack);
2423         // write ESD-friends if neccessary
2424         if (fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 0){
2425           AliTRDtrackV1 *calibTrack = new AliTRDtrackV1(*track);
2426           calibTrack->SetOwner();
2427           esdTrack->AddCalibObject(calibTrack);
2428         }
2429         ntracks1++;
2430         AliTRDtrackerDebug::SetTrackNumber(AliTRDtrackerDebug::GetTrackNumber() + 1);
2431       }
2432
2433       jSieve++;
2434     } while(jSieve<5 && candidates); // end track candidates sieve
2435     if(!ntracks1) break;
2436
2437     // increment counters
2438     ntracks2 += ntracks1;
2439
2440     if(fkReconstructor->IsHLT()) break;
2441     fSieveSeeding++;
2442
2443     // Rebuild plane configurations and indices taking only unused clusters into account
2444     quality = BuildSeedingConfigs(stack, configs);
2445     if(quality < 1.E-7) break; //fkReconstructor->GetRecoParam() ->GetPlaneQualityThreshold()) break;
2446     
2447     for(Int_t ip = 0; ip < kNPlanes; ip++){ 
2448       if(!(chamber = stack[ip])) continue;
2449       chamber->Build(fGeom, cal);//Indices(fSieveSeeding);
2450     }
2451
2452     if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 10){ 
2453       AliInfo(Form("Sieve level %d Plane config %d %d %d Quality %f", fSieveSeeding, configs[0], configs[1], configs[2], quality));
2454     }
2455   } while(fSieveSeeding<10); // end stack clusters sieve
2456   
2457
2458
2459   //AliInfo(Form("Registered TRD tracks %d in stack %d.", ntracks2, pars[1]));
2460
2461   return ntracks2;
2462 }
2463
2464 //___________________________________________________________________
2465 Double_t AliTRDtrackerV1::BuildSeedingConfigs(AliTRDtrackingChamber **stack, Int_t *configs)
2466 {
2467   //
2468   // Assign probabilities to chambers according to their
2469   // capability of producing seeds.
2470   // 
2471   // Parameters :
2472   //
2473   //   layers : Array of stack propagation layers for all 6 chambers in one stack
2474   //   configs : On exit array of configuration indexes (see GetSeedingConfig()
2475   // for details) in the decreasing order of their seeding probabilities. 
2476   //
2477   // Output :
2478   //
2479   //  Return top configuration quality 
2480   //
2481   // Detailed description:
2482   //
2483   // To each chamber seeding configuration (see GetSeedingConfig() for
2484   // the list of all configurations) one defines 2 quality factors:
2485   //  - an apriori topological quality (see GetSeedingConfig() for details) and
2486   //  - a data quality based on the uniformity of the distribution of
2487   //    clusters over the x range (time bins population). See CookChamberQA() for details.
2488   // The overall chamber quality is given by the product of this 2 contributions.
2489   // 
2490
2491   Double_t chamberQ[kNPlanes];memset(chamberQ, 0, kNPlanes*sizeof(Double_t));
2492   AliTRDtrackingChamber *chamber = NULL;
2493   for(int iplane=0; iplane<kNPlanes; iplane++){
2494     if(!(chamber = stack[iplane])) continue;
2495     chamberQ[iplane] = (chamber = stack[iplane]) ?  chamber->GetQuality() : 0.;
2496   }
2497
2498   Double_t tconfig[kNConfigs];memset(tconfig, 0, kNConfigs*sizeof(Double_t));
2499   Int_t planes[] = {0, 0, 0, 0};
2500   for(int iconf=0; iconf<kNConfigs; iconf++){
2501     GetSeedingConfig(iconf, planes);
2502     tconfig[iconf] = fgTopologicQA[iconf];
2503     for(int iplane=0; iplane<4; iplane++) tconfig[iconf] *= chamberQ[planes[iplane]]; 
2504   }
2505   
2506   TMath::Sort((Int_t)kNConfigs, tconfig, configs, kTRUE);
2507   //    AliInfo(Form("q[%d] = %f", configs[0], tconfig[configs[0]]));
2508   //    AliInfo(Form("q[%d] = %f", configs[1], tconfig[configs[1]]));
2509   //    AliInfo(Form("q[%d] = %f", configs[2], tconfig[configs[2]]));
2510   
2511   return tconfig[configs[0]];
2512 }
2513
2514 //____________________________________________________________________
2515 Int_t AliTRDtrackerV1::MakeSeeds(AliTRDtrackingChamber **stack, AliTRDseedV1 * const sseed, const Int_t * const ipar)
2516 {
2517 //
2518 // Seed tracklets and build candidate TRD tracks. The procedure is used during barrel tracking to account for tracks which are 
2519 // either missed by TPC prolongation or conversions inside the TRD volume. 
2520 // For stand alone tracking the procedure is used to estimate all tracks measured by TRD. 
2521 //
2522 // Parameters :
2523 //   layers : Array of stack propagation layers containing clusters
2524 //   sseed  : Array of empty tracklet seeds. On exit they are filled.
2525 //   ipar   : Control parameters:
2526 //       ipar[0] -> seeding chambers configuration
2527 //       ipar[1] -> stack index
2528 //       ipar[2] -> number of track candidates found so far
2529 //
2530 // Output :
2531 //   Number of tracks candidates found.
2532 // 
2533 // The following steps are performed:
2534 // 1. Build seeding layers by collapsing all time bins from each of the four seeding chambers along the 
2535 // radial coordinate. See AliTRDtrackingChamber::GetSeedingLayer() for details. The chambers selection for seeding
2536 // is described in AliTRDtrackerV1::Clusters2TracksStack().
2537 // 2. Using the seeding clusters from the seeding layer (step 1) build combinatorics using the following algorithm:
2538 // - for each seeding cluster in the lower seeding layer find
2539 // - all seeding clusters in the upper seeding layer inside a road defined by a given phi angle. The angle 
2540 //   is calculated on the minimum pt of tracks from vertex accesible to the stand alone tracker.
2541 // - for each pair of two extreme seeding clusters select middle upper cluster using roads defined externally by the 
2542 //   reco params
2543 // - select last seeding cluster as the nearest to the linear approximation of the track described by the first three
2544 //   seeding clusters.
2545 //   The implementation of road calculation and cluster selection can be found in the functions AliTRDchamberTimeBin::BuildCond()
2546 //   and AliTRDchamberTimeBin::GetClusters().   
2547 // 3. Helix fit of the seeding clusters set. (see AliTRDtrackerFitter::FitRieman(AliTRDcluster**)). No tilt correction is 
2548 //    performed at this level 
2549 // 4. Initialize seeding tracklets in the seeding chambers.
2550 // 5. *Filter 0* Chi2 cut on the Y and Z directions. The threshold is set externally by the reco params.
2551 // 6. Attach (true) clusters to seeding tracklets (see AliTRDseedV1::AttachClusters()) and fit tracklet (see 
2552 //    AliTRDseedV1::Fit()). The number of used clusters used by current seeds should not exceed ... (25).
2553 // 7. *Filter 1* Check if all 4 seeding tracklets are correctly constructed.
2554 // 8. Helix fit of the clusters from the seeding tracklets with tilt correction. Refit tracklets using the new 
2555 //    approximation of the track.
2556 // 9. *Filter 2* Calculate likelihood of the track. (See AliTRDtrackerV1::CookLikelihood()). The following quantities are
2557 //    checked against the Riemann fit:
2558 //      - position resolution in y
2559 //      - angular resolution in the bending plane
2560 //      - likelihood of the number of clusters attached to the tracklet
2561 // 10. Extrapolation of the helix fit to the other 2 chambers *non seeding* chambers:
2562 //      - Initialization of extrapolation tracklets with the fit parameters
2563 //      - Attach clusters to extrapolated tracklets
2564 //      - Helix fit of tracklets
2565 // 11. Improve seeding tracklets quality by reassigning clusters based on the last parameters of the track
2566 //      See AliTRDtrackerV1::ImproveSeedQuality() for details.
2567 // 12. Helix fit of all 6 seeding tracklets and chi2 calculation
2568 // 13. Hyperplane fit and track quality calculation. See AliTRDtrackerFitter::FitHyperplane() for details.
2569 // 14. Cooking labels for tracklets. Should be done only for MC
2570 // 15. Register seeds.
2571 //
2572 // Authors:
2573 //   Marian Ivanov <M.Ivanov@gsi.de>
2574 //   Alexandru Bercuci <A.Bercuci@gsi.de>
2575 //   Markus Fasel <M.Fasel@gsi.de>
2576
2577   AliTRDtrackingChamber *chamber = NULL;
2578   AliTRDcluster *c[kNSeedPlanes] = {NULL, NULL, NULL, NULL}; // initilize seeding clusters
2579   AliTRDseedV1 *cseed = &sseed[0]; // initialize tracklets for first track
2580   Int_t ncl, mcl; // working variable for looping over clusters
2581   Int_t index[AliTRDchamberTimeBin::kMaxClustersLayer], jndex[AliTRDchamberTimeBin::kMaxClustersLayer];
2582   // chi2 storage
2583   // chi2[0] = tracklet chi2 on the Z direction
2584   // chi2[1] = tracklet chi2 on the R direction
2585   Double_t chi2[4];
2586
2587   // this should be data member of AliTRDtrack TODO
2588   Double_t seedQuality[kMaxTracksStack];
2589   
2590   // unpack control parameters
2591   Int_t config  = ipar[0];
2592   Int_t ntracks = ipar[1];
2593   Int_t istack  = ipar[2];
2594   Int_t planes[kNSeedPlanes]; GetSeedingConfig(config, planes); 
2595   Int_t planesExt[kNPlanes-kNSeedPlanes]; GetExtrapolationConfig(config, planesExt);
2596
2597
2598   // Init chambers geometry
2599   Double_t hL[kNPlanes];       // Tilting angle
2600   Float_t padlength[kNPlanes]; // pad lenghts
2601   Float_t padwidth[kNPlanes];  // pad widths
2602   AliTRDpadPlane *pp = NULL;
2603   for(int iplane=0; iplane<kNPlanes; iplane++){
2604     pp                = fGeom->GetPadPlane(iplane, istack);
2605     hL[iplane]        = TMath::Tan(TMath::DegToRad()*pp->GetTiltingAngle());
2606     padlength[iplane] = pp->GetLengthIPad();
2607     padwidth[iplane] = pp->GetWidthIPad();
2608   }
2609   
2610   // Init anode wire position for chambers
2611   Double_t x0[kNPlanes],       // anode wire position
2612            driftLength = .5*AliTRDgeometry::AmThick() - AliTRDgeometry::DrThick(); // drift length
2613   TGeoHMatrix *matrix = NULL;
2614   Double_t loc[] = {AliTRDgeometry::AnodePos(), 0., 0.};
2615   Double_t glb[] = {0., 0., 0.};
2616   AliTRDtrackingChamber **cIter = &stack[0];
2617   for(int iLayer=0; iLayer<kNPlanes; iLayer++,cIter++){
2618     if(!(*cIter)) continue;
2619     if(!(matrix = fGeom->GetClusterMatrix((*cIter)->GetDetector()))){ 
2620       continue;
2621       x0[iLayer] = fgkX0[iLayer];
2622     }
2623     matrix->LocalToMaster(loc, glb);
2624     x0[iLayer] = glb[0];
2625   }
2626
2627   AliDebug(2, Form("Making seeds Stack[%d] Config[%d] Tracks[%d]...", istack, config, ntracks));
2628
2629   // Build seeding layers
2630   ResetSeedTB();
2631   Int_t nlayers = 0;
2632   for(int isl=0; isl<kNSeedPlanes; isl++){ 
2633     if(!(chamber = stack[planes[isl]])) continue;
2634     if(!chamber->GetSeedingLayer(fSeedTB[isl], fGeom, fkReconstructor)) continue;
2635     nlayers++;
2636   }
2637   if(nlayers < kNSeedPlanes) return ntracks;
2638   
2639   
2640   // Start finding seeds
2641   Double_t cond0[4], cond1[4], cond2[4];
2642   Int_t icl = 0;
2643   while((c[3] = (*fSeedTB[3])[icl++])){
2644     if(!c[3]) continue;
2645     fSeedTB[0]->BuildCond(c[3], cond0, 0);
2646     fSeedTB[0]->GetClusters(cond0, index, ncl);
2647     //printf("Found c[3] candidates 0 %d\n", ncl);
2648     Int_t jcl = 0;
2649     while(jcl<ncl) {
2650       c[0] = (*fSeedTB[0])[index[jcl++]];
2651       if(!c[0]) continue;
2652       Double_t dx    = c[3]->GetX() - c[0]->GetX();
2653       Double_t dzdx = (c[3]->GetZ() - c[0]->GetZ())/dx;
2654       Double_t dydx   = (c[3]->GetY() - c[0]->GetY())/dx;
2655       fSeedTB[1]->BuildCond(c[0], cond1, 1, dzdx, dydx);
2656       fSeedTB[1]->GetClusters(cond1, jndex, mcl);
2657       //printf("Found c[0] candidates 1 %d\n", mcl);
2658
2659       Int_t kcl = 0;
2660       while(kcl<mcl) {
2661         c[1] = (*fSeedTB[1])[jndex[kcl++]];
2662         if(!c[1]) continue;
2663         fSeedTB[2]->BuildCond(c[1], cond2, 2, dzdx, dydx);
2664         c[2] = fSeedTB[2]->GetNearestCluster(cond2);
2665         //printf("Found c[1] candidate 2 %p\n", c[2]);
2666         if(!c[2]) continue;
2667
2668         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].",
2669           c[0]->GetX(), c[0]->GetY(), c[0]->GetZ(),
2670           c[1]->GetX(), c[1]->GetY(), c[1]->GetZ(),
2671           c[2]->GetX(), c[2]->GetY(), c[2]->GetZ(),
2672           c[3]->GetX(), c[3]->GetY(), c[3]->GetZ()));
2673               
2674         for (Int_t il = 0; il < kNPlanes; il++) cseed[il].Reset();
2675       
2676         FitRieman(c, chi2);
2677       
2678         AliTRDseedV1 *tseed = &cseed[0];
2679         cIter = &stack[0];
2680         for(int iLayer=0; iLayer<kNPlanes; iLayer++, tseed++, cIter++){
2681           Int_t det = (*cIter) ? (*cIter)->GetDetector() : -1;
2682           tseed->SetDetector(det);
2683           tseed->SetTilt(hL[iLayer]);
2684           tseed->SetPadLength(padlength[iLayer]);
2685           tseed->SetPadWidth(padwidth[iLayer]);
2686           tseed->SetReconstructor(fkReconstructor);
2687           tseed->SetX0(det<0 ? fR[iLayer]+driftLength : x0[iLayer]);
2688           tseed->Init(GetRiemanFitter());
2689           tseed->SetStandAlone(kTRUE);
2690         }
2691       
2692         Bool_t isFake = kFALSE;
2693         if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
2694           if (c[0]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
2695           if (c[1]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
2696           if (c[2]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
2697       
2698           Double_t xpos[4];
2699           for(Int_t l = 0; l < kNSeedPlanes; l++) xpos[l] = fSeedTB[l]->GetX();
2700           Float_t yref[4];
2701           for(int il=0; il<4; il++) yref[il] = cseed[planes[il]].GetYref(0);
2702           Int_t ll = c[3]->GetLabel(0);
2703           Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2704           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2705           AliRieman *rim = GetRiemanFitter();
2706           TTreeSRedirector &cs0 = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
2707           cs0 << "MakeSeeds0"
2708               <<"EventNumber="          << eventNumber
2709               <<"CandidateNumber="      << candidateNumber
2710               <<"isFake="                               << isFake
2711               <<"config="                               << config
2712               <<"label="                                << ll
2713               <<"chi2z="                                << chi2[0]
2714               <<"chi2y="                                << chi2[1]
2715               <<"Y2exp="                                << cond2[0]     
2716               <<"Z2exp="                                << cond2[1]
2717               <<"X0="                                   << xpos[0] //layer[sLayer]->GetX()
2718               <<"X1="                                   << xpos[1] //layer[sLayer + 1]->GetX()
2719               <<"X2="                                   << xpos[2] //layer[sLayer + 2]->GetX()
2720               <<"X3="                                   << xpos[3] //layer[sLayer + 3]->GetX()
2721               <<"yref0="                                << yref[0]
2722               <<"yref1="                                << yref[1]
2723               <<"yref2="                                << yref[2]
2724               <<"yref3="                                << yref[3]
2725               <<"c0.="                          << c[0]
2726               <<"c1.="                          << c[1]
2727               <<"c2.="                          << c[2]
2728               <<"c3.="                          << c[3]
2729               <<"Seed0.="                               << &cseed[planes[0]]
2730               <<"Seed1.="                               << &cseed[planes[1]]
2731               <<"Seed2.="                               << &cseed[planes[2]]
2732               <<"Seed3.="                               << &cseed[planes[3]]
2733               <<"RiemanFitter.="                << rim
2734               <<"\n";
2735         }
2736         if(chi2[0] > fkReconstructor->GetRecoParam() ->GetChi2Z()/*7./(3. - sLayer)*//*iter*/){
2737           AliDebug(3, Form("Filter on chi2Z [%f].", chi2[0]));
2738           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2739           continue;
2740         }
2741         if(chi2[1] > fkReconstructor->GetRecoParam() ->GetChi2Y()/*1./(3. - sLayer)*//*iter*/){
2742           AliDebug(3, Form("Filter on chi2Y [%f].", chi2[1]));
2743           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2744           continue;
2745         }
2746         //AliInfo("Passed chi2 filter.");
2747       
2748         // try attaching clusters to tracklets
2749         Int_t mlayers = 0; 
2750         AliTRDcluster *cl = NULL;
2751         for(int iLayer=0; iLayer<kNSeedPlanes; iLayer++){
2752           Int_t jLayer = planes[iLayer];
2753           Int_t nNotInChamber = 0;
2754           if(!cseed[jLayer].AttachClusters(stack[jLayer], kTRUE)) continue;
2755           if(/*fkReconstructor->IsHLT()*/kFALSE){ 
2756             cseed[jLayer].UpdateUsed();
2757             if(!cseed[jLayer].IsOK()) continue;
2758           }else{
2759             cseed[jLayer].Fit();
2760             cseed[jLayer].UpdateUsed();
2761             cseed[jLayer].ResetClusterIter();
2762             while((cl = cseed[jLayer].NextCluster())){
2763               if(!cl->IsInChamber()) nNotInChamber++;
2764             }
2765             //printf("clusters[%d], used[%d], not in chamber[%d]\n", cseed[jLayer].GetN(), cseed[jLayer].GetNUsed(), nNotInChamber);
2766             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
2767           }
2768           mlayers++;
2769         }
2770
2771         if(mlayers < kNSeedPlanes){ 
2772           AliDebug(2, Form("Found only %d tracklets out of %d. Skip.", mlayers, kNSeedPlanes));
2773           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2774           continue;
2775         }
2776
2777         // temporary exit door for the HLT
2778         if(fkReconstructor->IsHLT()){ 
2779           // attach clusters to extrapolation chambers
2780           for(int iLayer=0; iLayer<kNPlanes-kNSeedPlanes; iLayer++){
2781             Int_t jLayer = planesExt[iLayer];
2782             if(!(chamber = stack[jLayer])) continue;
2783             if(!cseed[jLayer].AttachClusters(chamber, kTRUE)) continue;
2784             cseed[jLayer].Fit();
2785           }
2786           fTrackQuality[ntracks] = 1.; // dummy value
2787           ntracks++;
2788           if(ntracks == kMaxTracksStack) return ntracks;
2789           cseed += 6; 
2790           continue;
2791         }
2792
2793
2794         // Update Seeds and calculate Likelihood
2795         // fit tracklets and cook likelihood
2796         FitTiltedRieman(&cseed[0], kTRUE);
2797         for(int iLayer=0; iLayer<kNSeedPlanes; iLayer++){
2798           Int_t jLayer = planes[iLayer];
2799           cseed[jLayer].Fit(kTRUE);
2800         }
2801         Double_t like = CookLikelihood(&cseed[0], planes); // to be checked
2802       
2803         if (TMath::Log(1.E-9 + like) < fkReconstructor->GetRecoParam() ->GetTrackLikelihood()){
2804           AliDebug(3, Form("Filter on likelihood %f[%e].", TMath::Log(1.E-9 + like), like));
2805           AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2806           continue;
2807         }
2808         //AliInfo(Form("Passed likelihood %f[%e].", TMath::Log(1.E-9 + like), like));
2809       
2810         // book preliminary results
2811         seedQuality[ntracks] = like;
2812         fSeedLayer[ntracks]  = config;/*sLayer;*/
2813       
2814         // attach clusters to the extrapolation seeds
2815         Int_t elayers(0);
2816         for(int iLayer=0; iLayer<kNPlanes-kNSeedPlanes; iLayer++){
2817           Int_t jLayer = planesExt[iLayer];
2818           if(!(chamber = stack[jLayer])) continue;
2819       
2820           // fit extrapolated seed
2821           if ((jLayer == 0) && !(cseed[1].IsOK())) continue;
2822           if ((jLayer == 5) && !(cseed[4].IsOK())) continue;
2823           AliTRDseedV1 pseed = cseed[jLayer];
2824           if(!pseed.AttachClusters(chamber, kTRUE)) continue;
2825           pseed.Fit(kTRUE);
2826           cseed[jLayer] = pseed;
2827           FitTiltedRieman(cseed,  kTRUE);
2828           cseed[jLayer].Fit(kTRUE);
2829           elayers++;
2830         }
2831       
2832         // AliInfo("Extrapolation done.");
2833         // Debug Stream containing all the 6 tracklets
2834         if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
2835           TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
2836           TLinearFitter *tiltedRieman = GetTiltedRiemanFitter();
2837           Int_t eventNumber             = AliTRDtrackerDebug::GetEventNumber();
2838           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2839           cstreamer << "MakeSeeds1"
2840               << "EventNumber="         << eventNumber
2841               << "CandidateNumber="     << candidateNumber
2842               << "S0.="                                 << &cseed[0]
2843               << "S1.="                                 << &cseed[1]
2844               << "S2.="                                 << &cseed[2]
2845               << "S3.="                                 << &cseed[3]
2846               << "S4.="                                 << &cseed[4]
2847               << "S5.="                                 << &cseed[5]
2848               << "FitterT.="                    << tiltedRieman
2849               << "\n";
2850         }
2851               
2852         if(fkReconstructor->GetRecoParam()->HasImproveTracklets()){ 
2853           AliTRDseedV1 bseed[AliTRDgeometry::kNlayer];
2854           for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) bseed[jLayer] = cseed[jLayer];
2855
2856           if(ImproveSeedQuality(stack, cseed) < mlayers+elayers){
2857             AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2858             AliDebug(3, "Filter on improve seeds.");
2859           } else {
2860             // store results
2861             for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) cseed[jLayer] = bseed[jLayer];
2862           }
2863         }
2864         //AliInfo("Improve seed quality done.");
2865       
2866         // fit full track and cook likelihoods
2867         //                              Double_t curv = FitRieman(&cseed[0], chi2);
2868         //                              Double_t chi2ZF = chi2[0] / TMath::Max((mlayers - 3.), 1.);
2869         //                              Double_t chi2RF = chi2[1] / TMath::Max((mlayers - 3.), 1.);
2870       
2871         // do the final track fitting (Once with vertex constraint and once without vertex constraint)
2872         Double_t chi2Vals[3];
2873         chi2Vals[0] = FitTiltedRieman(&cseed[0], kTRUE);
2874         if(fkReconstructor->GetRecoParam()->IsVertexConstrained())
2875           chi2Vals[1] = FitTiltedRiemanConstraint(&cseed[0], GetZ()); // Do Vertex Constrained fit if desired
2876         else
2877           chi2Vals[1] = 1.;
2878         chi2Vals[2] = GetChi2Z(&cseed[0]) / TMath::Max((mlayers - 3.), 1.);
2879         // Chi2 definitions in testing stage
2880         //chi2Vals[2] = GetChi2ZTest(&cseed[0]);
2881         fTrackQuality[ntracks] = CalculateTrackLikelihood(&cseed[0], &chi2Vals[0]);
2882         //AliInfo("Hyperplane fit done\n");
2883                   
2884         if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
2885           TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
2886           Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2887           Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2888           TLinearFitter *fitterTC = GetTiltedRiemanFitterConstraint();
2889           TLinearFitter *fitterT = GetTiltedRiemanFitter();
2890           Int_t ncls = 0; 
2891           for(Int_t iseed = 0; iseed < kNPlanes; iseed++){
2892                 ncls += cseed[iseed].IsOK() ? cseed[iseed].GetN2() : 0;
2893           }
2894           cstreamer << "MakeSeeds2"
2895               << "EventNumber="                 << eventNumber
2896               << "CandidateNumber="     << candidateNumber
2897               << "Chi2TR="                      << chi2Vals[0]
2898               << "Chi2TC="                      << chi2Vals[1]
2899               << "Nlayers="                     << mlayers
2900               << "NClusters="   << ncls
2901               << "Like="                                << like
2902               << "S0.="                         << &cseed[0]
2903               << "S1.="                         << &cseed[1]
2904               << "S2.="                         << &cseed[2]
2905               << "S3.="                         << &cseed[3]
2906               << "S4.="                         << &cseed[4]
2907               << "S5.="                         << &cseed[5]
2908               << "FitterT.="                    << fitterT
2909               << "FitterTC.="                   << fitterTC
2910               << "\n";
2911         }
2912               
2913         ntracks++;
2914         AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2915         if(ntracks == kMaxTracksStack){
2916           AliWarning(Form("Number of seeds reached maximum allowed (%d) in stack.", kMaxTracksStack));
2917           return ntracks;
2918         }
2919         cseed += 6;
2920       }
2921     }
2922   }
2923   
2924   return ntracks;
2925 }
2926
2927 //_____________________________________________________________________________
2928 AliTRDtrackV1* AliTRDtrackerV1::MakeTrack(AliTRDseedV1 * const seeds, Double_t *params)
2929 {
2930 //
2931 // Build a TRD track out of tracklet candidates
2932 //
2933 // Parameters :
2934 //   seeds  : array of tracklets
2935 //   params : array of track parameters as they are estimated by stand alone tracker. 7 elements.
2936 //     [0] - radial position of the track at reference point
2937 //     [1] - y position of the fit at [0]
2938 //     [2] - z position of the fit at [0]
2939 //     [3] - snp of the first tracklet
2940 //     [4] - tgl of the first tracklet
2941 //     [5] - curvature of the Riemann fit - 1/pt
2942 //     [6] - sector rotation angle
2943 //
2944 // Output :
2945 //   The TRD track.
2946 //
2947 // Initialize the TRD track based on the parameters of the fit and a parametric covariance matrix 
2948 // (diagonal with constant variance terms TODO - correct parameterization) 
2949 // 
2950 // In case of HLT just register the tracklets in the tracker and return values of the Riemann fit. For the
2951 // offline case perform a full Kalman filter on the already found tracklets (see AliTRDtrackerV1::FollowBackProlongation() 
2952 // for details). Do also MC label calculation and PID if propagation successfully.
2953
2954  
2955   Double_t alpha = AliTRDgeometry::GetAlpha();
2956   Double_t shift = AliTRDgeometry::GetAlpha()/2.0;
2957   Double_t c[15];
2958
2959   c[ 0] = 0.2; // s^2_y
2960   c[ 1] = 0.0; c[ 2] = 2.0; // s^2_z
2961   c[ 3] = 0.0; c[ 4] = 0.0; c[ 5] = 0.02; // s^2_snp
2962   c[ 6] = 0.0; c[ 7] = 0.0; c[ 8] = 0.0;  c[ 9] = 0.1; // s^2_tgl
2963   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
2964
2965   AliTRDtrackV1 track(seeds, &params[1], c, params[0], params[6]*alpha+shift);
2966   track.PropagateTo(params[0]-5.0);
2967   AliTRDseedV1 *ptrTracklet = NULL;
2968
2969   // skip Kalman filter for HLT
2970   if(/*fkReconstructor->IsHLT()*/kFALSE){ 
2971     for (Int_t jLayer = 0; jLayer < AliTRDgeometry::kNlayer; jLayer++) {
2972       track.UnsetTracklet(jLayer);
2973       ptrTracklet = &seeds[jLayer];
2974       if(!ptrTracklet->IsOK()) continue;
2975       if(TMath::Abs(ptrTracklet->GetYref(1) - ptrTracklet->GetYfit(1)) >= .2) continue; // check this condition with Marian
2976       ptrTracklet = SetTracklet(ptrTracklet);
2977       ptrTracklet->UseClusters();
2978       track.SetTracklet(ptrTracklet, fTracklets->GetEntriesFast()-1);
2979     }
2980     AliTRDtrackV1 *ptrTrack = SetTrack(&track);
2981     ptrTrack->CookPID();
2982     ptrTrack->CookLabel(.9);
2983     ptrTrack->SetReconstructor(fkReconstructor);
2984     return ptrTrack;
2985   }
2986
2987   // prevent the error message in AliTracker::MeanMaterialBudget: "start point out of geometry"
2988   if(TMath::Abs(track.GetX()) + TMath::Abs(track.GetY()) + TMath::Abs(track.GetZ()) > 10000) 
2989     return NULL;
2990
2991   track.ResetCovariance(1);
2992   Int_t nc = TMath::Abs(FollowBackProlongation(track));
2993   if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) > 5 && fkReconstructor->IsDebugStreaming()){
2994     Int_t eventNumber           = AliTRDtrackerDebug::GetEventNumber();
2995     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2996     Double_t p[5]; // Track Params for the Debug Stream
2997     track.GetExternalParameters(params[0], p);
2998     TTreeSRedirector &cs = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
2999     cs << "MakeTrack"
3000     << "EventNumber="     << eventNumber
3001     << "CandidateNumber=" << candidateNumber
3002     << "nc="     << nc
3003     << "X="      << params[0]
3004     << "Y="      << p[0]
3005     << "Z="      << p[1]
3006     << "snp="    << p[2]
3007     << "tnd="    << p[3]
3008     << "crv="    << p[4]
3009     << "Yin="    << params[1]
3010     << "Zin="    << params[2]
3011     << "snpin="  << params[3]
3012     << "tndin="  << params[4]
3013     << "crvin="  << params[5]
3014     << "track.=" << &track
3015     << "\n";
3016   }
3017   if (nc < 30) return NULL;
3018
3019   AliTRDtrackV1 *ptrTrack = SetTrack(&track);
3020   ptrTrack->SetReconstructor(fkReconstructor);
3021   ptrTrack->CookLabel(.9);
3022   
3023   // computes PID for track
3024   ptrTrack->CookPID();
3025   // update calibration references using this track
3026   AliTRDCalibraFillHisto *calibra = AliTRDCalibraFillHisto::Instance();
3027   if (!calibra){ 
3028     AliInfo("Could not get Calibra instance\n");
3029     if(calibra->GetHisto2d()) calibra->UpdateHistogramsV1(ptrTrack);
3030   }
3031   return ptrTrack;
3032 }
3033
3034
3035 //____________________________________________________________________
3036 Int_t AliTRDtrackerV1::ImproveSeedQuality(AliTRDtrackingChamber **stack, AliTRDseedV1 *cseed)
3037 {
3038   //
3039   // Sort tracklets according to "quality" and try to "improve" the first 4 worst
3040   //
3041   // Parameters :
3042   //  layers : Array of propagation layers for a stack/supermodule
3043   //  cseed  : Array of 6 seeding tracklets which has to be improved
3044   // 
3045   // Output : 
3046   //   cssed : Improved seeds
3047   // 
3048   // Detailed description
3049   //
3050   // Iterative procedure in which new clusters are searched for each
3051   // tracklet seed such that the seed quality (see AliTRDseed::GetQuality())
3052   // can be maximized. If some optimization is found the old seeds are replaced.
3053   //
3054   // debug level: 7
3055   //
3056   
3057   // make a local working copy
3058   AliTRDtrackingChamber *chamber = NULL;
3059   AliTRDseedV1 bseed[AliTRDgeometry::kNlayer];
3060
3061   Float_t quality(0.), 
3062           lQuality[] = {1.e3, 1.e3, 1.e3, 1.e3, 1.e3, 1.e3};
3063   Int_t rLayers(0);
3064   for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;){ 
3065     bseed[jLayer] = cseed[jLayer];
3066     if(!bseed[jLayer].IsOK()) continue;
3067     rLayers++;
3068     lQuality[jLayer] = bseed[jLayer].GetQuality(kTRUE);
3069     quality    += lQuality[jLayer];
3070   }
3071   Float_t chi2 = FitTiltedRieman(bseed, kTRUE);
3072
3073   for (Int_t iter = 0; iter < 4; iter++) {
3074     AliDebug(2, Form("Iter[%d] Q[%f] chi2[%f]", iter, quality, chi2));
3075
3076     // Try better cluster set
3077     Int_t nLayers(0); Float_t qualitynew(0.);
3078     Int_t  indexes[6];
3079     TMath::Sort(Int_t(AliTRDgeometry::kNlayer), lQuality, indexes, kFALSE);
3080     for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) {
3081       Int_t bLayer = indexes[jLayer];
3082       bseed[bLayer].Reset("c");
3083       if(!(chamber = stack[bLayer])) continue;
3084       if(!bseed[bLayer].AttachClusters(chamber, kTRUE)) continue;
3085       bseed[bLayer].Fit(kTRUE);
3086       if(!bseed[bLayer].IsOK()) continue;
3087       nLayers++;
3088       lQuality[jLayer] = bseed[jLayer].GetQuality(kTRUE);
3089       qualitynew    += lQuality[jLayer];
3090     }
3091     if(rLayers > nLayers){
3092       AliDebug(1, Form("Lost %d tracklets while improving.", rLayers-nLayers));
3093       break;
3094     } else rLayers=nLayers;
3095
3096     if(qualitynew >= quality){ 
3097       AliDebug(4, Form("Quality worsen in iter[%d].", iter));
3098       break;
3099     } else quality = qualitynew;
3100
3101     // try improve track parameters
3102     AliTRDseedV1 tseed[AliTRDgeometry::kNlayer];
3103     for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) tseed[jLayer]=bseed[jLayer];
3104     Float_t chi2new = FitTiltedRieman(tseed, kTRUE);
3105     if(chi2new > chi2){ 
3106       AliDebug(4, Form("Chi2 worsen in iter[%d].", iter));
3107       break;
3108     } else chi2 = chi2new;
3109
3110     // store better tracklets
3111     for(Int_t jLayer=AliTRDgeometry::kNlayer; jLayer--;) bseed[jLayer]=tseed[jLayer];
3112
3113
3114     if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 7 && fkReconstructor->IsDebugStreaming()){
3115       Int_t eventNumber                 = AliTRDtrackerDebug::GetEventNumber();
3116       Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
3117       TLinearFitter *tiltedRieman = GetTiltedRiemanFitter();
3118       TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
3119       cstreamer << "ImproveSeedQuality"
3120         << "EventNumber="               << eventNumber
3121         << "CandidateNumber="   << candidateNumber
3122         << "Iteration="                         << iter
3123         << "S0.="                                                       << &bseed[0]
3124         << "S1.="                                                       << &bseed[1]
3125         << "S2.="                                                       << &bseed[2]
3126         << "S3.="                                                       << &bseed[3]
3127         << "S4.="                                                       << &bseed[4]
3128         << "S5.="                                                       << &bseed[5]
3129         << "FitterT.="                          << tiltedRieman
3130         << "\n";
3131     }
3132   } // Loop: iter
3133   // we are sure that at least 2 tracklets are OK !
3134   return rLayers;
3135 }
3136
3137 //_________________________________________________________________________
3138 Double_t AliTRDtrackerV1::CalculateTrackLikelihood(const AliTRDseedV1 *const tracklets, Double_t *chi2){
3139   //
3140   // Calculates the Track Likelihood value. This parameter serves as main quality criterion for 
3141   // the track selection
3142   // The likelihood value containes:
3143   //    - The chi2 values from the both fitters and the chi2 values in z-direction from a linear fit
3144   //    - The Sum of the Parameter  |slope_ref - slope_fit|/Sigma of the tracklets
3145   // For all Parameters an exponential dependency is used
3146   //
3147   // Parameters: - Array of tracklets (AliTRDseedV1) related to the track candidate
3148   //             - Array of chi2 values: 
3149   //                 * Non-Constrained Tilted Riemann fit
3150   //                 * Vertex-Constrained Tilted Riemann fit
3151   //                 * z-Direction from Linear fit
3152   // Output:     - The calculated track likelihood
3153   //
3154   // debug level 2
3155   //
3156
3157   Double_t chi2phi = 0, nLayers = 0;
3158   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
3159     if(!tracklets[iLayer].IsOK()) continue;
3160     chi2phi += tracklets[iLayer].GetChi2Phi();
3161     nLayers++;
3162   }
3163   chi2phi /= Float_t (nLayers - 2.0);
3164   
3165   Double_t likeChi2Z  = TMath::Exp(-chi2[2] * 0.14);                    // Chi2Z 
3166   Double_t likeChi2TC = (fkReconstructor->GetRecoParam()->IsVertexConstrained()) ? 
3167                                                                                         TMath::Exp(-chi2[1] * 0.677) : 1;                       // Constrained Tilted Riemann
3168   Double_t likeChi2TR = TMath::Exp(-chi2[0] * 0.0078);                  // Non-constrained Tilted Riemann
3169   Double_t likeChi2Phi= TMath::Exp(-chi2phi * 3.23);//3.23
3170   Double_t trackLikelihood     = likeChi2Z * likeChi2TR * likeChi2Phi;
3171
3172   if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
3173     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
3174     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
3175     TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
3176     cstreamer << "CalculateTrackLikelihood0"
3177         << "EventNumber="                       << eventNumber
3178         << "CandidateNumber="   << candidateNumber
3179         << "LikeChi2Z="                         << likeChi2Z
3180         << "LikeChi2TR="                        << likeChi2TR
3181         << "LikeChi2TC="                        << likeChi2TC
3182         << "LikeChi2Phi="               << likeChi2Phi
3183         << "TrackLikelihood=" << trackLikelihood
3184         << "\n";
3185   }
3186   
3187   return trackLikelihood;
3188 }
3189
3190 //____________________________________________________________________
3191 Double_t AliTRDtrackerV1::CookLikelihood(AliTRDseedV1 *cseed, Int_t planes[4])
3192 {
3193   //
3194   // Calculate the probability of this track candidate.
3195   //
3196   // Parameters :
3197   //   cseeds : array of candidate tracklets
3198   //   planes : array of seeding planes (see seeding configuration)
3199   //   chi2   : chi2 values (on the Z and Y direction) from the rieman fit of the track.
3200   //
3201   // Output :
3202   //   likelihood value
3203   // 
3204   // Detailed description
3205   //
3206   // The track quality is estimated based on the following 4 criteria:
3207   //  1. precision of the rieman fit on the Y direction (likea)
3208   //  2. chi2 on the Y direction (likechi2y)
3209   //  3. chi2 on the Z direction (likechi2z)
3210   //  4. number of attached clusters compared to a reference value 
3211   //     (see AliTRDrecoParam::fkFindable) (likeN)
3212   //
3213   // The distributions for each type of probabilities are given below as of
3214   // (date). They have to be checked to assure consistency of estimation.
3215   //
3216
3217   // ratio of the total number of clusters/track which are expected to be found by the tracker.
3218   const AliTRDrecoParam *fRecoPars = fkReconstructor->GetRecoParam();
3219   
3220         Double_t chi2y = GetChi2Y(&cseed[0]);
3221   Double_t chi2z = GetChi2Z(&cseed[0]);
3222
3223   Float_t nclusters = 0.;
3224   Double_t sumda = 0.;
3225   for(UChar_t ilayer = 0; ilayer < 4; ilayer++){
3226     Int_t jlayer = planes[ilayer];
3227     nclusters += cseed[jlayer].GetN2();
3228     sumda += TMath::Abs(cseed[jlayer].GetYfit(1) - cseed[jlayer].GetYref(1));
3229   }
3230   nclusters *= .25;
3231
3232   Double_t likea     = TMath::Exp(-sumda * fRecoPars->GetPhiSlope());
3233   Double_t likechi2y  = 0.0000000001;
3234   if (fkReconstructor->IsCosmic() || chi2y < fRecoPars->GetChi2YCut()) likechi2y += TMath::Exp(-TMath::Sqrt(chi2y) * fRecoPars->GetChi2YSlope());
3235   Double_t likechi2z = TMath::Exp(-chi2z * fRecoPars->GetChi2ZSlope());
3236   Double_t likeN     = TMath::Exp(-(fRecoPars->GetNMeanClusters() - nclusters) / fRecoPars->GetNSigmaClusters());
3237   Double_t like      = likea * likechi2y * likechi2z * likeN;
3238
3239   if(fkReconstructor->GetRecoParam()->GetStreamLevel(AliTRDrecoParam::kTracker) >= 2 && fkReconstructor->IsDebugStreaming()){
3240     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
3241     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
3242     Int_t nTracklets = 0; Float_t meanNcls = 0;
3243     for(Int_t iseed=0; iseed < kNPlanes; iseed++){
3244         if(!cseed[iseed].IsOK()) continue;
3245         nTracklets++;
3246         meanNcls += cseed[iseed].GetN2();
3247     }
3248     if(nTracklets) meanNcls /= nTracklets;
3249     // The Debug Stream contains the seed 
3250     TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
3251     cstreamer << "CookLikelihood"
3252         << "EventNumber="                       << eventNumber
3253         << "CandidateNumber=" << candidateNumber
3254         << "tracklet0.="                        << &cseed[0]
3255         << "tracklet1.="                        << &cseed[1]
3256         << "tracklet2.="                        << &cseed[2]
3257         << "tracklet3.="                        << &cseed[3]
3258         << "tracklet4.="                        << &cseed[4]
3259         << "tracklet5.="                        << &cseed[5]
3260         << "sumda="                                             << sumda
3261         << "chi2y="                                             << chi2y
3262         << "chi2z="                                             << chi2z
3263         << "likea="                                             << likea
3264         << "likechi2y="                         << likechi2y
3265         << "likechi2z="                         << likechi2z
3266         << "nclusters="                         << nclusters
3267         << "likeN="                                             << likeN
3268         << "like="                                              << like
3269         << "meanncls="        << meanNcls
3270         << "\n";
3271   }
3272
3273   return like;
3274 }
3275
3276 //____________________________________________________________________
3277 void AliTRDtrackerV1::GetSeedingConfig(Int_t iconfig, Int_t planes[4])
3278 {
3279   //
3280   // Map seeding configurations to detector planes.
3281   //
3282   // Parameters :
3283   //   iconfig : configuration index
3284   //   planes  : member planes of this configuration. On input empty.
3285   //
3286   // Output :
3287   //   planes : contains the planes which are defining the configuration
3288   // 
3289   // Detailed description
3290   //
3291   // Here is the list of seeding planes configurations together with
3292   // their topological classification:
3293   //
3294   //  0 - 5432 TQ 0
3295   //  1 - 4321 TQ 0
3296   //  2 - 3210 TQ 0
3297   //  3 - 5321 TQ 1
3298   //  4 - 4210 TQ 1
3299   //  5 - 5431 TQ 1
3300   //  6 - 4320 TQ 1
3301   //  7 - 5430 TQ 2
3302   //  8 - 5210 TQ 2
3303   //  9 - 5421 TQ 3
3304   // 10 - 4310 TQ 3
3305   // 11 - 5410 TQ 4
3306   // 12 - 5420 TQ 5
3307   // 13 - 5320 TQ 5
3308   // 14 - 5310 TQ 5
3309   //
3310   // The topologic quality is modeled as follows:
3311   // 1. The general model is define by the equation:
3312   //  p(conf) = exp(-conf/2)
3313   // 2. According to the topologic classification, configurations from the same
3314   //    class are assigned the agerage value over the model values.
3315   // 3. Quality values are normalized.
3316   // 
3317   // The topologic quality distribution as function of configuration is given below:
3318   //Begin_Html
3319   // <img src="gif/topologicQA.gif">
3320   //End_Html
3321   //
3322
3323   switch(iconfig){
3324   case 0: // 5432 TQ 0
3325     planes[0] = 2;
3326     planes[1] = 3;
3327     planes[2] = 4;
3328     planes[3] = 5;
3329     break;
3330   case 1: // 4321 TQ 0
3331     planes[0] = 1;
3332     planes[1] = 2;
3333     planes[2] = 3;
3334     planes[3] = 4;
3335     break;
3336   case 2: // 3210 TQ 0
3337     planes[0] = 0;
3338     planes[1] = 1;
3339     planes[2] = 2;
3340     planes[3] = 3;
3341     break;
3342   case 3: // 5321 TQ 1
3343     planes[0] = 1;
3344     planes[1] = 2;
3345     planes[2] = 3;
3346     planes[3] = 5;
3347     break;
3348   case 4: // 4210 TQ 1
3349     planes[0] = 0;
3350     planes[1] = 1;
3351     planes[2] = 2;
3352     planes[3] = 4;
3353     break;
3354   case 5: // 5431 TQ 1
3355     planes[0] = 1;
3356     planes[1] = 3;
3357     planes[2] = 4;
3358     planes[3] = 5;
3359     break;
3360   case 6: // 4320 TQ 1
3361     planes[0] = 0;
3362     planes[1] = 2;
3363     planes[2] = 3;
3364     planes[3] = 4;
3365     break;
3366   case 7: // 5430 TQ 2
3367     planes[0] = 0;
3368     planes[1] = 3;
3369     planes[2] = 4;
3370     planes[3] = 5;
3371     break;
3372   case 8: // 5210 TQ 2
3373     planes[0] = 0;
3374     planes[1] = 1;
3375     planes[2] = 2;
3376     planes[3] = 5;
3377     break;
3378   case 9: // 5421 TQ 3
3379     planes[0] = 1;
3380     planes[1] = 2;
3381     planes[2] = 4;
3382     planes[3] = 5;
3383     break;
3384   case 10: // 4310 TQ 3
3385     planes[0] = 0;
3386     planes[1] = 1;
3387     planes[2] = 3;
3388     planes[3] = 4;
3389     break;
3390   case 11: // 5410 TQ 4
3391     planes[0] = 0;
3392     planes[1] = 1;
3393     planes[2] = 4;
3394     planes[3] = 5;
3395     break;
3396   case 12: // 5420 TQ 5
3397     planes[0] = 0;
3398     planes[1] = 2;
3399     planes[2] = 4;
3400     planes[3] = 5;
3401     break;
3402   case 13: // 5320 TQ 5
3403     planes[0] = 0;
3404     planes[1] = 2;
3405     planes[2] = 3;
3406     planes[3] = 5;
3407     break;
3408   case 14: // 5310 TQ 5
3409     planes[0] = 0;
3410     planes[1] = 1;
3411     planes[2] = 3;
3412     planes[3] = 5;
3413     break;
3414   }
3415 }
3416
3417 //____________________________________________________________________
3418 void AliTRDtrackerV1::GetExtrapolationConfig(Int_t iconfig, Int_t planes[2])
3419 {
3420   //
3421   // Returns the extrapolation planes for a seeding configuration.
3422   //
3423   // Parameters :
3424   //   iconfig : configuration index
3425   //   planes  : planes which are not in this configuration. On input empty.
3426   //
3427   // Output :
3428   //   planes : contains the planes which are not in the configuration
3429   // 
3430   // Detailed description
3431   //
3432
3433   switch(iconfig){
3434   case 0: // 5432 TQ 0
3435     planes[0] = 1;
3436     planes[1] = 0;
3437     break;
3438   case 1: // 4321 TQ 0
3439     planes[0] = 5;
3440     planes[1] = 0;
3441     break;
3442   case 2: // 3210 TQ 0
3443     planes[0] = 4;
3444     planes[1] = 5;
3445     break;
3446   case 3: // 5321 TQ 1
3447     planes[0] = 4;
3448     planes[1] = 0;
3449     break;
3450   case 4: // 4210 TQ 1
3451     planes[0] = 5;
3452     planes[1] = 3;
3453     break;
3454   case 5: // 5431 TQ 1
3455     planes[0] = 2;
3456     planes[1] = 0;
3457     break;
3458   case 6: // 4320 TQ 1
3459     planes[0] = 5;
3460     planes[1] = 1;
3461     break;
3462   case 7: // 5430 TQ 2
3463     planes[0] = 2;
3464     planes[1] = 1;
3465     break;
3466   case 8: // 5210 TQ 2
3467     planes[0] = 4;
3468     planes[1] = 3;
3469     break;
3470   case 9: // 5421 TQ 3
3471     planes[0] = 3;
3472     planes[1] = 0;
3473     break;
3474   case 10: // 4310 TQ 3
3475     planes[0] = 5;
3476     planes[1] = 2;
3477     break;
3478   case 11: // 5410 TQ 4
3479     planes[0] = 3;
3480     planes[1] = 2;
3481     break;
3482   case 12: // 5420 TQ 5
3483     planes[0] = 3;
3484     planes[1] = 1;
3485     break;
3486   case 13: // 5320 TQ 5
3487     planes[0] = 4;
3488     planes[1] = 1;
3489     break;
3490   case 14: // 5310 TQ 5
3491     planes[0] = 4;
3492     planes[1] = 2;
3493     break;
3494   }
3495 }
3496
3497 //____________________________________________________________________
3498 AliCluster* AliTRDtrackerV1::GetCluster(Int_t idx) const
3499 {
3500   if(!fClusters) return NULL;
3501   Int_t ncls = fClusters->GetEntriesFast();
3502   return idx >= 0 && idx < ncls ? (AliCluster*)fClusters->UncheckedAt(idx) : NULL;
3503 }
3504
3505 //____________________________________________________________________
3506 AliTRDseedV1* AliTRDtrackerV1::GetTracklet(Int_t idx) const
3507 {
3508   if(!fTracklets) return NULL;
3509   Int_t ntrklt = fTracklets->GetEntriesFast();
3510   return idx >= 0 && idx < ntrklt ? (AliTRDseedV1*)fTracklets->UncheckedAt(idx) : NULL;
3511 }
3512
3513 //____________________________________________________________________
3514 AliKalmanTrack* AliTRDtrackerV1::GetTrack(Int_t idx) const
3515 {
3516   if(!fTracks) return NULL;
3517   Int_t ntrk = fTracks->GetEntriesFast();
3518   return idx >= 0 && idx < ntrk ? (AliKalmanTrack*)fTracks->UncheckedAt(idx) : NULL;
3519 }
3520
3521
3522
3523 // //_____________________________________________________________________________
3524 // Int_t AliTRDtrackerV1::Freq(Int_t n, const Int_t *inlist
3525 //           , Int_t *outlist, Bool_t down)
3526 // {    
3527 //   //
3528 //   // Sort eleements according occurancy 
3529 //   // The size of output array has is 2*n 
3530 //   //
3531 // 
3532 //   if (n <= 0) {
3533 //     return 0;
3534 //   }
3535 // 
3536 //   Int_t *sindexS = new Int_t[n];   // Temporary array for sorting
3537 //   Int_t *sindexF = new Int_t[2*n];   
3538 //   for (Int_t i = 0; i < n; i++) {
3539 //     sindexF[i] = 0;
3540 //   }
3541 // 
3542 //   TMath::Sort(n,inlist,sindexS,down); 
3543 // 
3544 //   Int_t last     = inlist[sindexS[0]];
3545 //   Int_t val      = last;
3546 //   sindexF[0]     = 1;
3547 //   sindexF[0+n]   = last;
3548 //   Int_t countPos = 0;
3549 // 
3550 //   // Find frequency
3551 //   for (Int_t i = 1; i < n; i++) {
3552 //     val = inlist[sindexS[i]];
3553 //     if (last == val) {
3554 //       sindexF[countPos]++;
3555 //     }
3556 //     else {      
3557 //       countPos++;
3558 //       sindexF[countPos+n] = val;
3559 //       sindexF[countPos]++;
3560 //       last                = val;
3561 //     }
3562 //   }
3563 //   if (last == val) {
3564 //     countPos++;
3565 //   }
3566 // 
3567 //   // Sort according frequency
3568 //   TMath::Sort(countPos,sindexF,sindexS,kTRUE);
3569 // 
3570 //   for (Int_t i = 0; i < countPos; i++) {
3571 //     outlist[2*i  ] = sindexF[sindexS[i]+n];
3572 //     outlist[2*i+1] = sindexF[sindexS[i]];
3573 //   }
3574 // 
3575 //   delete [] sindexS;
3576 //   delete [] sindexF;
3577 //   
3578 //   return countPos;
3579 // 
3580 // }
3581
3582
3583 //____________________________________________________________________
3584 void AliTRDtrackerV1::ResetSeedTB()
3585 {
3586 // reset buffer for seeding time bin layers. If the time bin 
3587 // layers are not allocated this function allocates them  
3588
3589   for(Int_t isl=0; isl<kNSeedPlanes; isl++){
3590     if(!fSeedTB[isl]) fSeedTB[isl] = new AliTRDchamberTimeBin();
3591     else fSeedTB[isl]->Clear();
3592   }
3593 }
3594
3595
3596 //_____________________________________________________________________________
3597 Float_t AliTRDtrackerV1::GetChi2Y(const AliTRDseedV1 * const tracklets) const
3598 {
3599   //    Calculates normalized chi2 in y-direction
3600   // chi2 = Sum chi2 / n_tracklets
3601
3602   Double_t chi2 = 0.; Int_t n = 0;
3603   for(Int_t ipl = kNPlanes; ipl--;){
3604     if(!tracklets[ipl].IsOK()) continue;
3605     chi2 += tracklets[ipl].GetChi2Y();
3606     n++;
3607   }
3608   return n ? chi2/n : 0.;
3609 }
3610
3611 //_____________________________________________________________________________
3612 Float_t AliTRDtrackerV1::GetChi2Z(const AliTRDseedV1 *const tracklets) const 
3613 {
3614   //    Calculates normalized chi2 in z-direction
3615   // chi2 = Sum chi2 / n_tracklets
3616
3617   Double_t chi2 = 0; Int_t n = 0;
3618   for(Int_t ipl = kNPlanes; ipl--;){
3619     if(!tracklets[ipl].IsOK()) continue;
3620     chi2 += tracklets[ipl].GetChi2Z();
3621     n++;
3622   }
3623   return n ? chi2/n : 0.;
3624 }
3625
3626 //____________________________________________________________________
3627 Float_t AliTRDtrackerV1::CalculateReferenceX(const AliTRDseedV1 *const tracklets){
3628         //
3629         // Calculates the reference x-position for the tilted Rieman fit defined as middle
3630         // of the stack (middle between layers 2 and 3). For the calculation all the tracklets
3631         // are taken into account
3632         //
3633         // Parameters: - Array of tracklets(AliTRDseedV1)
3634         //
3635         // Output: - The reference x-position(Float_t)
3636   // Only kept for compatibility with the old code
3637         //
3638         Int_t nDistances = 0;
3639         Float_t meanDistance = 0.;
3640         Int_t startIndex = 5;
3641         for(Int_t il =5; il > 0; il--){
3642         if(tracklets[il].IsOK() && tracklets[il -1].IsOK()){
3643         Float_t xdiff = tracklets[il].GetX0() - tracklets[il -1].GetX0();
3644             meanDistance += xdiff;
3645             nDistances++;
3646           }
3647           if(tracklets[il].IsOK()) startIndex = il;
3648         }
3649         if(tracklets[0].IsOK()) startIndex = 0;
3650         if(!nDistances){
3651           // We should normally never get here
3652           Float_t xpos[2]; memset(xpos, 0, sizeof(Float_t) * 2);
3653           Int_t iok = 0, idiff = 0;
3654           // This attempt is worse and should be avoided:
3655           // check for two chambers which are OK and repeat this without taking the mean value
3656           // Strategy avoids a division by 0;
3657           for(Int_t il = 5; il >= 0; il--){
3658             if(tracklets[il].IsOK()){
3659               xpos[iok] = tracklets[il].GetX0();
3660               iok++;
3661               startIndex = il;
3662             }
3663             if(iok) idiff++; // to get the right difference;
3664             if(iok > 1) break;
3665           }
3666           if(iok > 1){
3667             meanDistance = (xpos[0] - xpos[1])/idiff;
3668           }
3669           else{
3670             // we have do not even have 2 layers which are OK? The we do not need to fit at all
3671             return 331.;
3672         }
3673         }
3674         else{
3675           meanDistance /= nDistances;
3676         }
3677         return tracklets[startIndex].GetX0() + (2.5 - startIndex) * meanDistance - 0.5 * (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
3678 }
3679
3680 //_____________________________________________________________________________
3681 Double_t AliTRDtrackerV1::FitTiltedRiemanV1(AliTRDseedV1 *const tracklets){
3682   //
3683   // Track Fitter Function using the new class implementation of 
3684   // the Rieman fit
3685   //
3686   AliTRDtrackFitterRieman fitter;
3687   fitter.SetRiemanFitter(GetTiltedRiemanFitter());
3688   fitter.Reset();
3689   for(Int_t il = 0; il < AliTRDgeometry::kNlayer; il++) fitter.SetTracklet(il, &tracklets[il]);
3690   Double_t chi2 = fitter.Eval();
3691   // Update the tracklets
3692   Double_t cov[15]; Double_t x0;
3693   memset(cov, 0, sizeof(Double_t) * 15);
3694   for(Int_t il = 0; il < AliTRDgeometry::kNlayer; il++){
3695     x0 = tracklets[il].GetX0();
3696     tracklets[il].SetYref(0, fitter.GetYat(x0));
3697     tracklets[il].SetZref(0, fitter.GetZat(x0));
3698     tracklets[il].SetYref(1, fitter.GetDyDxAt(x0));
3699     tracklets[il].SetZref(1, fitter.GetDzDx());
3700     tracklets[il].SetC(fitter.GetCurvature());
3701     fitter.GetCovAt(x0, cov);
3702     tracklets[il].SetCovRef(cov);
3703     tracklets[il].SetChi2(chi2);
3704   }
3705   return chi2;
3706 }
3707
3708 ///////////////////////////////////////////////////////
3709 //                                                   //
3710 // Resources of class AliTRDLeastSquare              //
3711 //                                                   //
3712 ///////////////////////////////////////////////////////
3713
3714 //_____________________________________________________________________________
3715 AliTRDtrackerV1::AliTRDLeastSquare::AliTRDLeastSquare(){
3716 //
3717 // Constructor of the nested class AliTRDtrackFitterLeastSquare
3718 //
3719 // Fast solving linear regresion in 2D
3720 //         y=a + bx
3721 // The data members have the following meaning
3722 // fParams[0] : a
3723 // fParams[1] : b
3724 // 
3725 // fSums[0] : S
3726 // fSums[1] : Sx
3727 // fSums[2] : Sy
3728 // fSums[3] : Sxy
3729 // fSums[4] : Sxx
3730 // fSums[5] : Syy
3731 // 
3732 // fCovarianceMatrix[0] : s2a
3733 // fCovarianceMatrix[1] : s2b
3734 // fCovarianceMatrix[2] : cov(ab)
3735
3736   memset(fParams, 0, sizeof(Double_t) * 2);
3737   memset(fSums, 0, sizeof(Double_t) * 6);
3738   memset(fCovarianceMatrix, 0, sizeof(Double_t) * 3);
3739
3740 }
3741
3742 //_____________________________________________________________________________
3743 void AliTRDtrackerV1::AliTRDLeastSquare::AddPoint(const Double_t *const x, Double_t y, Double_t sigmaY){
3744   //
3745   // Adding Point to the fitter
3746   //
3747   
3748   Double_t weight = 1/(sigmaY > 1e-9 ? sigmaY : 1e-9);
3749   weight *= weight;
3750   const Double_t &xpt = *x;
3751   //    printf("Adding point x = %f, y = %f, sigma = %f\n", xpt, y, sigmaY);
3752   fSums[0] += weight;
3753   fSums[1] += weight * xpt;
3754   fSums[2] += weight * y;
3755   fSums[3] += weight * xpt * y;
3756   fSums[4] += weight * xpt * xpt;
3757   fSums[5] += weight * y * y;
3758 }
3759
3760 //_____________________________________________________________________________
3761 void AliTRDtrackerV1::AliTRDLeastSquare::RemovePoint(const Double_t *const x, Double_t y, Double_t sigmaY){
3762   //
3763   // Remove Point from the sample
3764   //
3765
3766   Double_t weight = 1/(sigmaY > 1e-9 ? sigmaY : 1e-9);
3767   weight *= weight;
3768   const Double_t &xpt = *x; 
3769   fSums[0] -= weight;
3770   fSums[1] -= weight * xpt;
3771   fSums[2] -= weight * y;
3772   fSums[3] -= weight * xpt * y;
3773   fSums[4] -= weight * xpt * xpt;
3774   fSums[5] -= weight * y * y;
3775 }
3776
3777 //_____________________________________________________________________________
3778 Bool_t AliTRDtrackerV1::AliTRDLeastSquare::Eval(){
3779   //
3780   // Evaluation of the fit:
3781   // Calculation of the parameters
3782   // Calculation of the covariance matrix
3783   //
3784   
3785   Double_t det = fSums[0] * fSums[4] - fSums[1] *fSums[1];
3786   if(det==0) return kFALSE;
3787
3788   //    for(Int_t isum = 0; isum < 5; isum++)
3789   //            printf("fSums[%d] = %f\n", isum, fSums[isum]);
3790   //    printf("denominator = %f\n", denominator);
3791   fParams[0] = (fSums[2] * fSums[4] - fSums[1] * fSums[3])/det;
3792   fParams[1] = (fSums[0] * fSums[3] - fSums[1] * fSums[2])/det;
3793   //    printf("fParams[0] = %f, fParams[1] = %f\n", fParams[0], fParams[1]);
3794   
3795   // Covariance matrix
3796   Double_t den = fSums[0]*fSums[4] - fSums[1]*fSums[1];
3797   fCovarianceMatrix[0] = fSums[4] / den;
3798   fCovarianceMatrix[1] = fSums[0] / den;
3799   fCovarianceMatrix[2] = -fSums[1] / den;
3800 /*  fCovarianceMatrix[0] = fSums[4] / fSums[0] - fSums[1] * fSums[1] / (fSums[0] * fSums[0]);
3801   fCovarianceMatrix[1] = fSums[5] / fSums[0] - fSums[2] * fSums[2] / (fSums[0] * fSums[0]);
3802   fCovarianceMatrix[2] = fSums[3] / fSums[0] - fSums[1] * fSums[2] / (fSums[0] * fSums[0]);*/
3803
3804
3805
3806   return kTRUE;
3807 }
3808
3809 //_____________________________________________________________________________
3810 Double_t AliTRDtrackerV1::AliTRDLeastSquare::GetFunctionValue(const Double_t *const xpos) const {
3811   //
3812   // Returns the Function value of the fitted function at a given x-position
3813   //
3814   return fParams[0] + fParams[1] * (*xpos);
3815 }
3816
3817 //_____________________________________________________________________________
3818 void AliTRDtrackerV1::AliTRDLeastSquare::GetCovarianceMatrix(Double_t *storage) const {
3819   //
3820   // Copies the values of the covariance matrix into the storage
3821   //
3822   memcpy(storage, fCovarianceMatrix, sizeof(Double_t) * 3);
3823 }
3824
3825 //_____________________________________________________________________________
3826 void AliTRDtrackerV1::AliTRDLeastSquare::Reset(){
3827   //
3828   // Reset the fitter
3829   //
3830   memset(fParams, 0, sizeof(Double_t) * 2);
3831   memset(fCovarianceMatrix, 0, sizeof(Double_t) * 3);
3832   memset(fSums, 0, sizeof(Double_t) * 6);
3833 }
3834
3835 ///////////////////////////////////////////////////////
3836 //                                                   //
3837 // Resources of class AliTRDtrackFitterRieman        //
3838 //                                                   //
3839 ///////////////////////////////////////////////////////
3840
3841 //_____________________________________________________________________________
3842 AliTRDtrackerV1::AliTRDtrackFitterRieman::AliTRDtrackFitterRieman():
3843   fTrackFitter(NULL),
3844   fZfitter(NULL),
3845   fCovarPolY(NULL),
3846   fCovarPolZ(NULL),
3847   fXref(0.),
3848   fSysClusterError(0.)
3849 {
3850   //
3851   // Default constructor
3852   //
3853   fZfitter = new AliTRDLeastSquare;
3854   fCovarPolY = new TMatrixD(3,3);
3855   fCovarPolZ = new TMatrixD(2,2);
3856   memset(fTracklets, 0, sizeof(AliTRDseedV1 *) * 6);
3857   memset(fParameters, 0, sizeof(Double_t) * 5);
3858   memset(fSumPolY, 0, sizeof(Double_t) * 5);
3859   memset(fSumPolZ, 0, sizeof(Double_t) * 2);
3860 }
3861
3862 //_____________________________________________________________________________
3863 AliTRDtrackerV1::AliTRDtrackFitterRieman::~AliTRDtrackFitterRieman(){
3864   //
3865   // Destructor
3866   //
3867   if(fZfitter) delete fZfitter;
3868   if(fCovarPolY) delete fCovarPolY;
3869   if(fCovarPolZ) delete fCovarPolZ;
3870 }
3871
3872 //_____________________________________________________________________________
3873 void AliTRDtrackerV1::AliTRDtrackFitterRieman::Reset(){
3874   //
3875   // Reset the Fitter
3876   //
3877   if(fTrackFitter){
3878     fTrackFitter->StoreData(kTRUE);
3879     fTrackFitter->ClearPoints();
3880   }
3881   if(fZfitter){
3882     fZfitter->Reset();
3883   }
3884   fXref = 0.;
3885   memset(fTracklets, 0, sizeof(AliTRDseedV1 *) * AliTRDgeometry::kNlayer);
3886   memset(fParameters, 0, sizeof(Double_t) * 5);
3887   memset(fSumPolY, 0, sizeof(Double_t) * 5);
3888   memset(fSumPolZ, 0, sizeof(Double_t) * 2);
3889   for(Int_t irow = 0; irow < fCovarPolY->GetNrows(); irow++)
3890     for(Int_t icol = 0; icol < fCovarPolY->GetNcols(); icol++){
3891       (*fCovarPolY)(irow, icol) = 0.;
3892       if(irow < 2 && icol < 2)
3893         (*fCovarPolZ)(irow, icol) = 0.;
3894     }
3895 }
3896
3897 //_____________________________________________________________________________
3898 void AliTRDtrackerV1::AliTRDtrackFitterRieman::SetTracklet(Int_t itr, AliTRDseedV1 *tracklet){ 
3899   //
3900   // Add tracklet into the fitter
3901   //
3902   if(itr >= AliTRDgeometry::kNlayer) return;
3903   fTracklets[itr] = tracklet; 
3904 }
3905
3906 //_____________________________________________________________________________
3907 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::Eval(){
3908   //
3909   // Perform the fit
3910   // 1. Apply linear transformation and store points in the fitter
3911   // 2. Evaluate the fit
3912   // 3. Check if the result of the fit in z-direction is reasonable
3913   // if not
3914   // 3a. Fix the parameters 3 and 4 with the results of a simple least
3915   //     square fit
3916   // 3b. Redo the fit with the fixed parameters
3917   // 4. Store fit results (parameters and errors)
3918   //
3919   if(!fTrackFitter){
3920     return 1e10;
3921   }
3922   fXref = CalculateReferenceX();
3923   for(Int_t il = 0; il < AliTRDgeometry::kNlayer; il++) UpdateFitters(fTracklets[il]);
3924   if(!fTrackFitter->GetNpoints()) return 1e10;
3925   // perform the fit
3926   fTrackFitter->Eval();
3927   fZfitter->Eval();
3928   fParameters[3] = fTrackFitter->GetParameter(3);
3929   fParameters[4] = fTrackFitter->GetParameter(4);
3930   if(!CheckAcceptable(fParameters[3], fParameters[4])) {
3931     fTrackFitter->FixParameter(3, fZfitter->GetFunctionValue(&fXref));
3932     fTrackFitter->FixParameter(4, fZfitter->GetFunctionParameter(1));
3933     fTrackFitter->Eval();
3934     fTrackFitter->ReleaseParameter(3);
3935     fTrackFitter->ReleaseParameter(4);
3936     fParameters[3] = fTrackFitter->GetParameter(3);
3937     fParameters[4] = fTrackFitter->GetParameter(4);
3938   }
3939   // Update the Fit Parameters and the errors
3940   fParameters[0] = fTrackFitter->GetParameter(0);
3941   fParameters[1] = fTrackFitter->GetParameter(1);
3942   fParameters[2] = fTrackFitter->GetParameter(2);
3943
3944   // Prepare Covariance estimation
3945   (*fCovarPolY)(0,0) = fSumPolY[0]; (*fCovarPolY)(1,1) = fSumPolY[2]; (*fCovarPolY)(2,2) = fSumPolY[4];
3946   (*fCovarPolY)(1,0) = (*fCovarPolY)(0,1) = fSumPolY[1];
3947   (*fCovarPolY)(2,0) = (*fCovarPolY)(0,2) = fSumPolY[2];
3948   (*fCovarPolY)(2,1) = (*fCovarPolY)(1,2) = fSumPolY[3];
3949   fCovarPolY->Invert();
3950   (*fCovarPolZ)(0,0) = fSumPolZ[0]; (*fCovarPolZ)(1,1) = fSumPolZ[2];
3951   (*fCovarPolZ)(1,0) = (*fCovarPolZ)(0,1) = fSumPolZ[1];
3952   fCovarPolZ->Invert();
3953   return fTrackFitter->GetChisquare() / fTrackFitter->GetNpoints();
3954 }
3955
3956 //_____________________________________________________________________________
3957 void AliTRDtrackerV1::AliTRDtrackFitterRieman::UpdateFitters(AliTRDseedV1 * const tracklet){
3958   //
3959   // Does the transformations and updates the fitters
3960   // The following transformation is applied
3961   //
3962   AliTRDcluster *cl = NULL;
3963   Double_t x, y, z, dx, t, w, we, yerr, zerr;
3964   Double_t uvt[4];
3965   if(!tracklet || !tracklet->IsOK()) return; 
3966   Double_t tilt = tracklet->GetTilt();
3967   for(Int_t itb = 0; itb < AliTRDseedV1::kNclusters; itb++){
3968     if(!(cl = tracklet->GetClusters(itb))) continue;
3969     if(!cl->IsInChamber()) continue;
3970     if (!tracklet->IsUsable(itb)) continue;
3971     x = cl->GetX();
3972     y = cl->GetY();
3973     z = cl->GetZ();
3974     dx = x - fXref;
3975     // Transformation
3976     t = 1./(x*x + y*y);
3977     uvt[0] = 2. * x * t;
3978     uvt[1] = t;
3979     uvt[2] = 2. * tilt * t;
3980     uvt[3] = 2. * tilt * dx * t;
3981     w = 2. * (y + tilt*z) * t;
3982     // error definition changes for the different calls
3983     we = 2. * t;
3984     we *= TMath::Sqrt(cl->GetSigmaY2()+tilt*tilt*cl->GetSigmaZ2());
3985     // Update sums for error calculation
3986     yerr = 1./(TMath::Sqrt(cl->GetSigmaY2()) + fSysClusterError);
3987     yerr *= yerr;
3988     zerr = 1./cl->GetSigmaZ2();
3989     for(Int_t ipol = 0; ipol < 5; ipol++){
3990       fSumPolY[ipol] += yerr;
3991       yerr *= x;
3992       if(ipol < 3){
3993         fSumPolZ[ipol] += zerr;
3994         zerr *= x;
3995       }
3996     }
3997     fTrackFitter->AddPoint(uvt, w, we);
3998     fZfitter->AddPoint(&x, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
3999   }
4000 }
4001
4002 //_____________________________________________________________________________
4003 Bool_t AliTRDtrackerV1::AliTRDtrackFitterRieman::CheckAcceptable(Double_t offset, Double_t slope){
4004   // 
4005   // Check whether z-results are acceptable
4006   // Definition: Distance between tracklet fit and track fit has to be
4007   // less then half a padlength
4008   // Point of comparision is at the anode wire
4009   //
4010   Bool_t acceptablez = kTRUE;
4011   Double_t zref = 0.0;
4012   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
4013     if(!fTracklets[iLayer]->IsOK()) continue;
4014     zref = offset + slope * (fTracklets[iLayer]->GetX0() - fXref);
4015     if (TMath::Abs(fTracklets[iLayer]->GetZfit(0) - zref) > fTracklets[iLayer]->GetPadLength() * 0.5 + 1.0) 
4016       acceptablez = kFALSE;
4017   }
4018   return acceptablez;
4019 }
4020
4021 //_____________________________________________________________________________
4022 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetYat(Double_t x) const {
4023   //
4024   // Calculate y position out of the track parameters
4025   // y:     R^2 = (x - x0)^2 + (y - y0)^2
4026   //     =>   y = y0 +/- Sqrt(R^2 - (x - x0)^2)
4027   //          R = Sqrt() = 1/Curvature
4028   //     =>   y = y0 +/- Sqrt(1/Curvature^2 - (x - x0)^2)
4029   //
4030   Double_t y = 0;
4031   Double_t disc = (x * fParameters[0] + fParameters[1]);
4032   disc = 1 - fParameters[0]*fParameters[2] + fParameters[1]*fParameters[1] - disc*disc;
4033   if (disc >= 0) {
4034     disc = TMath::Sqrt(disc);
4035     y    = (1.0 - disc) / fParameters[0];
4036   }
4037   return y;
4038 }
4039
4040 //_____________________________________________________________________________
4041 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetZat(Double_t x) const {
4042   //
4043   // Return z position for a given x position
4044   // Simple linear function
4045   //
4046   return fParameters[3] + fParameters[4] * (x - fXref);
4047 }
4048
4049 //_____________________________________________________________________________
4050 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetDyDxAt(Double_t x) const {
4051   //
4052   // Calculate dydx at a given radial position out of the track parameters
4053   // dy:      R^2 = (x - x0)^2 + (y - y0)^2
4054   //     =>     y = +/- Sqrt(R^2 - (x - x0)^2) + y0
4055   //     => dy/dx = (x - x0)/Sqrt(R^2 - (x - x0)^2) 
4056   // Curvature: cr = 1/R = a/Sqrt(1 + b^2 - c*a)
4057   //     => dy/dx =  (x - x0)/(1/(cr^2) - (x - x0)^2) 
4058   //
4059   Double_t x0 = -fParameters[1] / fParameters[0];
4060   Double_t curvature = GetCurvature();
4061   Double_t dy = 0;
4062   if (-fParameters[2] * fParameters[0] + fParameters[1] * fParameters[1] + 1 > 0) {
4063     if (1.0/(curvature * curvature) - (x - x0) * (x - x0) > 0.0) {
4064      Double_t yderiv = (x - x0) / TMath::Sqrt(1.0/(curvature * curvature) - (x - x0) * (x - x0));
4065       if (fParameters[0] < 0) yderiv *= -1.0;
4066       dy = yderiv;
4067     }
4068   }
4069   return dy;
4070 }
4071
4072 //_____________________________________________________________________________
4073 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::GetCurvature() const {
4074   //
4075   // Calculate track curvature
4076   //
4077   //
4078   Double_t curvature =  1.0 + fParameters[1]*fParameters[1] - fParameters[2]*fParameters[0];
4079   if (curvature > 0.0) 
4080     curvature  =  fParameters[0] / TMath::Sqrt(curvature);
4081   return curvature;
4082 }
4083
4084 //_____________________________________________________________________________
4085 void AliTRDtrackerV1::AliTRDtrackFitterRieman::GetCovAt(Double_t x, Double_t *cov) const {
4086   //
4087   // Error Definition according to gauss error propagation
4088   //  
4089   TMatrixD transform(3,3);
4090   transform(0,0) = transform(1,1) = transform(2,2) = 1;
4091   transform(0,1) = transform(1,2) = x;
4092   transform(0,2) = x*x;
4093   TMatrixD covariance(transform, TMatrixD::kMult, *fCovarPolY);
4094   covariance *= transform.T();
4095   cov[0] = covariance(0,0);
4096   TMatrixD transformZ(2,2);
4097   transformZ(0,0) = transformZ(1,1) = 1;
4098   transformZ(0,1) = x;
4099   TMatrixD covarZ(transformZ, TMatrixD::kMult, *fCovarPolZ);
4100   covarZ *= transformZ.T();
4101   cov[1] = covarZ(0,0);
4102   cov[2] = 0;
4103 }
4104
4105 //____________________________________________________________________
4106 Double_t AliTRDtrackerV1::AliTRDtrackFitterRieman::CalculateReferenceX(){
4107   //
4108   // Calculates the reference x-position for the tilted Rieman fit defined as middle
4109   // of the stack (middle between layers 2 and 3). For the calculation all the tracklets
4110   // are taken into account
4111   // 
4112   // Parameters:        - Array of tracklets(AliTRDseedV1)
4113   //
4114   // Output:            - The reference x-position(Float_t)
4115   //
4116   Int_t nDistances = 0;
4117   Float_t meanDistance = 0.;
4118   Int_t startIndex = 5;
4119   for(Int_t il =5; il > 0; il--){
4120     if(fTracklets[il]->IsOK() && fTracklets[il -1]->IsOK()){
4121       Float_t xdiff = fTracklets[il]->GetX0() - fTracklets[il -1]->GetX0();
4122       meanDistance += xdiff;
4123       nDistances++;
4124     }
4125     if(fTracklets[il]->IsOK()) startIndex = il;
4126   }
4127   if(fTracklets[0]->IsOK()) startIndex = 0;
4128   if(!nDistances){
4129     // We should normally never get here
4130     Float_t xpos[2]; memset(xpos, 0, sizeof(Float_t) * 2);
4131     Int_t iok = 0, idiff = 0;
4132     // This attempt is worse and should be avoided:
4133     // check for two chambers which are OK and repeat this without taking the mean value
4134     // Strategy avoids a division by 0;
4135     for(Int_t il = 5; il >= 0; il--){
4136       if(fTracklets[il]->IsOK()){
4137         xpos[iok] = fTracklets[il]->GetX0();
4138         iok++;
4139         startIndex = il;
4140       }
4141       if(iok) idiff++;  // to get the right difference;
4142       if(iok > 1) break;
4143     }
4144     if(iok > 1){
4145       meanDistance = (xpos[0] - xpos[1])/idiff;
4146     }
4147     else{
4148       // we have do not even have 2 layers which are OK? The we do not need to fit at all
4149       return 331.;
4150     }
4151   }
4152   else{
4153     meanDistance /= nDistances;
4154   }
4155   return fTracklets[startIndex]->GetX0() + (2.5 - startIndex) * meanDistance - 0.5 * (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
4156 }