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