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