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