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