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