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