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