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