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