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