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