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