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