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