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