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