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