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