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