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