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