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