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