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