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