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