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