]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDtrackerV1.cxx
Replace plane by layer and chamber by stack
[u/mrichter/AliRoot.git] / TRD / AliTRDtrackerV1.cxx
1
2 /**************************************************************************
3 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 *                                                                        *
5 * Author: The ALICE Off-line Project.                                    *
6 * Contributors are mentioned in the code where appropriate.              *
7 *                                                                        *
8 * Permission to use, copy, modify and distribute this software and its   *
9 * documentation strictly for non-commercial purposes is hereby granted   *
10 * without fee, provided that the above copyright notice appears in all   *
11 * copies and that both the copyright notice and this permission notice   *
12 * appear in the supporting documentation. The authors make no claims     *
13 * about the suitability of this software for any purpose. It is          *
14 * provided "as is" without express or implied warranty.                  *
15 **************************************************************************/
16
17 /* $Id$ */
18
19 ///////////////////////////////////////////////////////////////////////////////
20 //                                                                           //
21 //  Track finder                                                             //
22 //                                                                           //
23 //  Authors:                                                                 //
24 //    Alex Bercuci <A.Bercuci@gsi.de>                                        //
25 //    Markus Fasel <M.Fasel@gsi.de>                                          //
26 //                                                                           //
27 ///////////////////////////////////////////////////////////////////////////////
28
29 // #include <Riostream.h>
30 // #include <stdio.h>
31 // #include <string.h>
32
33 #include <TBranch.h>
34 #include <TDirectory.h>
35 #include <TLinearFitter.h>
36 #include <TTree.h>  
37 #include <TClonesArray.h>
38 #include <TTreeStream.h>
39
40 #include "AliLog.h"
41 #include "AliESDEvent.h"
42 #include "AliGeomManager.h"
43 #include "AliRieman.h"
44 #include "AliTrackPointArray.h"
45
46 #include "AliTRDgeometry.h"
47 #include "AliTRDpadPlane.h"
48 #include "AliTRDcalibDB.h"
49 #include "AliTRDReconstructor.h"
50 #include "AliTRDCalibraFillHisto.h"
51 #include "AliTRDrecoParam.h"
52
53 #include "AliTRDcluster.h" 
54 #include "AliTRDseedV1.h"
55 #include "AliTRDtrackV1.h"
56 #include "AliTRDtrackerV1.h"
57 #include "AliTRDtrackerDebug.h"
58 #include "AliTRDtrackingChamber.h"
59 #include "AliTRDchamberTimeBin.h"
60
61
62
63 ClassImp(AliTRDtrackerV1)
64
65
66 const  Float_t  AliTRDtrackerV1::fgkMinClustersInTrack =  0.5;  //
67 const  Float_t  AliTRDtrackerV1::fgkLabelFraction      =  0.8;  //
68 const  Double_t AliTRDtrackerV1::fgkMaxChi2            = 12.0;  //
69 const  Double_t AliTRDtrackerV1::fgkMaxSnp             =  0.95; // Maximum local sine of the azimuthal angle
70 const  Double_t AliTRDtrackerV1::fgkMaxStep            =  2.0;  // Maximal step size in propagation 
71 Double_t AliTRDtrackerV1::fgTopologicQA[kNConfigs] = {
72   0.1112, 0.1112, 0.1112, 0.0786, 0.0786,
73   0.0786, 0.0786, 0.0579, 0.0579, 0.0474,
74   0.0474, 0.0408, 0.0335, 0.0335, 0.0335
75 };
76 Int_t AliTRDtrackerV1::fgNTimeBins = 0;
77 TTreeSRedirector *AliTRDtrackerV1::fgDebugStreamer = 0x0;
78 AliRieman* AliTRDtrackerV1::fgRieman = 0x0;
79 TLinearFitter* AliTRDtrackerV1::fgTiltedRieman = 0x0;
80 TLinearFitter* AliTRDtrackerV1::fgTiltedRiemanConstrained = 0x0;
81
82 //____________________________________________________________________
83 AliTRDtrackerV1::AliTRDtrackerV1() 
84   :AliTracker()
85   ,fGeom(new AliTRDgeometry())
86   ,fClusters(0x0)
87   ,fTracklets(0x0)
88   ,fTracks(0x0)
89   ,fSieveSeeding(0)
90 {
91   //
92   // Default constructor.
93   // 
94   if (!AliTRDcalibDB::Instance()) {
95     AliFatal("Could not get calibration object");
96   }
97   if(!fgNTimeBins) fgNTimeBins = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
98
99   for (Int_t isector = 0; isector < AliTRDgeometry::kNsector; isector++) new(&fTrSec[isector]) AliTRDtrackingSector(fGeom, isector);
100
101   if (!AliTRDReconstructor::RecoParam()){
102         AliWarning("RecoParams not set in AliTRDReconstructor. Setting to default LowFluxParam.");
103     AliTRDReconstructor::SetRecoParam(AliTRDrecoParam::GetLowFluxParam());
104   }
105   
106
107   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() > 1){
108     TDirectory *savedir = gDirectory; 
109     fgDebugStreamer    = new TTreeSRedirector("TRD.TrackerDebug.root");
110     savedir->cd();
111   }
112 }
113
114 //____________________________________________________________________
115 AliTRDtrackerV1::~AliTRDtrackerV1()
116
117   //
118   // Destructor
119   //
120   
121   if(fgDebugStreamer) delete fgDebugStreamer;
122   if(fgRieman) delete fgRieman;
123   if(fgTiltedRieman) delete fgTiltedRieman;
124   if(fgTiltedRiemanConstrained) delete fgTiltedRiemanConstrained;
125   if(fTracks) {fTracks->Delete(); delete fTracks;}
126   if(fTracklets) {fTracklets->Delete(); delete fTracklets;}
127   if(fClusters) {fClusters->Delete(); delete fClusters;}
128   if(fGeom) delete fGeom;
129 }
130
131 //____________________________________________________________________
132 Int_t AliTRDtrackerV1::Clusters2Tracks(AliESDEvent *esd)
133 {
134   //
135   // Steering stand alone tracking for full TRD detector
136   //
137   // Parameters :
138   //   esd     : The ESD event. On output it contains 
139   //             the ESD tracks found in TRD.
140   //
141   // Output :
142   //   Number of tracks found in the TRD detector.
143   // 
144   // Detailed description
145   // 1. Launch individual SM trackers. 
146   //    See AliTRDtrackerV1::Clusters2TracksSM() for details.
147   //
148
149   if(!AliTRDReconstructor::RecoParam()){
150     AliError("Reconstruction configuration not initialized. Call first AliTRDReconstructor::SetRecoParam().");
151     return 0;
152   }
153   
154   //AliInfo("Start Track Finder ...");
155   Int_t ntracks = 0;
156   for(int ism=0; ism<AliTRDgeometry::kNsector; ism++){
157     //  for(int ism=1; ism<2; ism++){
158     //AliInfo(Form("Processing supermodule %i ...", ism));
159     ntracks += Clusters2TracksSM(ism, esd);
160   }
161   AliInfo(Form("Number of found tracks : %d", ntracks));
162   return ntracks;
163 }
164
165
166 //_____________________________________________________________________________
167 Bool_t AliTRDtrackerV1::GetTrackPoint(Int_t index, AliTrackPoint &p) const
168 {
169   //AliInfo(Form("Asking for tracklet %d", index));
170   
171   if(index<0 || index == 0xffff) return kFALSE;
172   AliTRDseedV1 *tracklet = 0x0; 
173   if(!(tracklet = (AliTRDseedV1*)fTracklets->UncheckedAt(index))) return kFALSE;
174   
175   // get detector for this tracklet
176   AliTRDcluster *cl = 0x0;
177   Int_t ic = 0; do; while(!(cl = tracklet->GetClusters(ic++)));  
178   Int_t  idet     = cl->GetDetector();
179     
180   Double_t local[3];
181   local[0] = tracklet->GetX0(); 
182   local[1] = tracklet->GetYfit(0);
183   local[2] = tracklet->GetZfit(0);
184   Double_t global[3];
185   fGeom->RotateBack(idet, local, global);
186   p.SetXYZ(global[0],global[1],global[2]);
187   
188   
189   // setting volume id
190   AliGeomManager::ELayerID iLayer = AliGeomManager::kTRD1;
191   switch (fGeom->GetLayer(idet)) {
192   case 0:
193     iLayer = AliGeomManager::kTRD1;
194     break;
195   case 1:
196     iLayer = AliGeomManager::kTRD2;
197     break;
198   case 2:
199     iLayer = AliGeomManager::kTRD3;
200     break;
201   case 3:
202     iLayer = AliGeomManager::kTRD4;
203     break;
204   case 4:
205     iLayer = AliGeomManager::kTRD5;
206     break;
207   case 5:
208     iLayer = AliGeomManager::kTRD6;
209     break;
210   };
211   Int_t    modId = fGeom->GetSector(idet) * fGeom->Nstack() + fGeom->GetStack(idet);
212   UShort_t volid = AliGeomManager::LayerToVolUID(iLayer, modId);
213   p.SetVolumeID(volid);
214     
215   return kTRUE;
216 }
217
218 //____________________________________________________________________
219 TLinearFitter* AliTRDtrackerV1::GetTiltedRiemanFitter()
220 {
221   if(!fgTiltedRieman) fgTiltedRieman = new TLinearFitter(4, "hyp4");
222   return fgTiltedRieman;
223 }
224
225 //____________________________________________________________________
226 TLinearFitter* AliTRDtrackerV1::GetTiltedRiemanFitterConstraint()
227 {
228   if(!fgTiltedRiemanConstrained) fgTiltedRiemanConstrained = new TLinearFitter(2, "hyp2");
229   return fgTiltedRiemanConstrained;
230 }
231   
232 //____________________________________________________________________  
233 AliRieman* AliTRDtrackerV1::GetRiemanFitter()
234 {
235   if(!fgRieman) fgRieman = new AliRieman(AliTRDtrackingChamber::kNTimeBins * AliTRDgeometry::kNlayer);
236   return fgRieman;
237 }
238   
239 //_____________________________________________________________________________
240 Int_t AliTRDtrackerV1::PropagateBack(AliESDEvent *event) 
241 {
242   //
243   // Gets seeds from ESD event. The seeds are AliTPCtrack's found and
244   // backpropagated by the TPC tracker. Each seed is first propagated 
245   // to the TRD, and then its prolongation is searched in the TRD.
246   // If sufficiently long continuation of the track is found in the TRD
247   // the track is updated, otherwise it's stored as originaly defined 
248   // by the TPC tracker.   
249   //  
250
251   // Calibration monitor
252   AliTRDCalibraFillHisto *calibra = AliTRDCalibraFillHisto::Instance();
253   if (!calibra) AliInfo("Could not get Calibra instance\n");
254   
255   Int_t   found    = 0;     // number of tracks found
256   Float_t foundMin = 20.0;
257   
258   Int_t    nSeed   = event->GetNumberOfTracks();
259   if(!nSeed){
260     // run stand alone tracking
261     if (AliTRDReconstructor::RecoParam()->SeedingOn()) Clusters2Tracks(event);
262     return 0;
263   }
264   
265   Float_t *quality = new Float_t[nSeed];
266   Int_t   *index   = new Int_t[nSeed];
267   for (Int_t iSeed = 0; iSeed < nSeed; iSeed++) {
268     AliESDtrack *seed = event->GetTrack(iSeed);
269     Double_t covariance[15];
270     seed->GetExternalCovariance(covariance);
271     quality[iSeed] = covariance[0] + covariance[2];
272   }
273   // Sort tracks according to covariance of local Y and Z
274   TMath::Sort(nSeed,quality,index,kFALSE);
275   
276   // Backpropagate all seeds
277   Int_t   expectedClr;
278   AliTRDtrackV1 track;
279   for (Int_t iSeed = 0; iSeed < nSeed; iSeed++) {
280   
281     // Get the seeds in sorted sequence
282     AliESDtrack *seed = event->GetTrack(index[iSeed]);
283   
284     // Check the seed status
285     ULong_t status = seed->GetStatus();
286     if ((status & AliESDtrack::kTPCout) == 0) continue;
287     if ((status & AliESDtrack::kTRDout) != 0) continue;
288   
289     // Do the back prolongation
290     new(&track) AliTRDtrackV1(*seed);
291     //track->Print();
292     //Int_t   lbl         = seed->GetLabel();
293     //track.SetSeedLabel(lbl);
294     seed->UpdateTrackParams(&track, AliESDtrack::kTRDbackup); // Make backup
295     Float_t p4          = track.GetC();
296     if((expectedClr = FollowBackProlongation(track))){
297       // computes PID for track
298       track.CookPID();
299       // update calibration references using this track
300       if(calibra->GetHisto2d()) calibra->UpdateHistogramsV1(&track);
301       // save calibration object
302       if ((track.GetNumberOfClusters() > 15) && (track.GetNumberOfClusters() > 0.5*expectedClr)) {
303         seed->UpdateTrackParams(&track, AliESDtrack::kTRDout);
304   
305         track.UpdateESDtrack(seed);
306         
307         // Add TRD track to ESDfriendTrack
308         if (AliTRDReconstructor::RecoParam()->GetStreamLevel() > 0 /*&& quality TODO*/){ 
309           AliTRDtrackV1 *calibTrack = new AliTRDtrackV1(track);
310           calibTrack->SetOwner();
311           seed->AddCalibObject(calibTrack);
312         }
313       }
314     }
315
316     if ((TMath::Abs(track.GetC() - p4) / TMath::Abs(p4) < 0.2) ||(track.Pt() > 0.8)) {
317       //
318       // Make backup for back propagation
319       //
320       Int_t foundClr = track.GetNumberOfClusters();
321       if (foundClr >= foundMin) {
322         //AliInfo(Form("Making backup track ncls [%d]...", foundClr));
323         //track.CookdEdx();
324         //track.CookdEdxTimBin(seed->GetID());
325         track.CookLabel(1. - fgkLabelFraction);
326         if(track.GetBackupTrack()) UseClusters(track.GetBackupTrack());
327         
328
329         // Sign only gold tracks
330         if (track.GetChi2() / track.GetNumberOfClusters() < 4) {
331           if ((seed->GetKinkIndex(0)      ==   0) && (track.Pt() <  1.5)) UseClusters(&track);
332         }
333         Bool_t isGold = kFALSE;
334   
335         // Full gold track
336         if (track.GetChi2() / track.GetNumberOfClusters() < 5) {
337           if (track.GetBackupTrack()) seed->UpdateTrackParams(track.GetBackupTrack(),AliESDtrack::kTRDbackup);
338
339           isGold = kTRUE;
340         }
341   
342         // Almost gold track
343         if ((!isGold)  && (track.GetNCross() == 0) &&   (track.GetChi2() / track.GetNumberOfClusters()  < 7)) {
344           //seed->UpdateTrackParams(track, AliESDtrack::kTRDbackup);
345           if (track.GetBackupTrack()) seed->UpdateTrackParams(track.GetBackupTrack(),AliESDtrack::kTRDbackup);
346   
347           isGold = kTRUE;
348         }
349         
350         if ((!isGold) && (track.GetBackupTrack())) {
351           if ((track.GetBackupTrack()->GetNumberOfClusters() > foundMin) && ((track.GetBackupTrack()->GetChi2()/(track.GetBackupTrack()->GetNumberOfClusters()+1)) < 7)) {
352             seed->UpdateTrackParams(track.GetBackupTrack(),AliESDtrack::kTRDbackup);
353             isGold = kTRUE;
354           }
355         }
356   
357         //if ((track->StatusForTOF() > 0) && (track->GetNCross() == 0) && (Float_t(track->GetNumberOfClusters()) / Float_t(track->GetNExpected())  > 0.4)) {
358         //seed->UpdateTrackParams(track->GetBackupTrack(), AliESDtrack::kTRDbackup);
359         //}
360       }
361     }
362     
363     // Propagation to the TOF (I.Belikov)
364     if (track.IsStopped() == kFALSE) {
365       Double_t xtof  = 371.0;
366       Double_t xTOF0 = 370.0;
367     
368       Double_t c2    = track.GetSnp() + track.GetC() * (xtof - track.GetX());
369       if (TMath::Abs(c2) >= 0.99) continue;
370       
371       PropagateToX(track, xTOF0, fgkMaxStep);
372   
373       // Energy losses taken to the account - check one more time
374       c2 = track.GetSnp() + track.GetC() * (xtof - track.GetX());
375       if (TMath::Abs(c2) >= 0.99) continue;
376       
377       //if (!PropagateToX(*track,xTOF0,fgkMaxStep)) {
378       //        fHBackfit->Fill(7);
379       //delete track;
380       //        continue;
381       //}
382   
383       Double_t ymax = xtof * TMath::Tan(0.5 * AliTRDgeometry::GetAlpha());
384       Double_t y;
385       track.GetYAt(xtof,GetBz(),y);
386       if (y >  ymax) {
387         if (!track.Rotate( AliTRDgeometry::GetAlpha())) continue;       
388       }else if (y < -ymax) {
389         if (!track.Rotate(-AliTRDgeometry::GetAlpha())) continue;
390       }
391           
392       if (track.PropagateTo(xtof)) {
393         seed->UpdateTrackParams(&track, AliESDtrack::kTRDout);
394         track.UpdateESDtrack(seed);
395         
396         // Add TRD track to ESDfriendTrack
397 //                              if (AliTRDReconstructor::RecoParam()->GetStreamLevel() > 0 /*&& quality TODO*/){ 
398 //                                      AliTRDtrackV1 *calibTrack = new AliTRDtrackV1(track);
399 //                                      calibTrack->SetOwner();
400 //                                      seed->AddCalibObject(calibTrack);
401 //                              }
402         found++;
403       }
404     } else {                    
405       if ((track.GetNumberOfClusters() > 15) && (track.GetNumberOfClusters() > 0.5*expectedClr)) {
406         seed->UpdateTrackParams(&track, AliESDtrack::kTRDout);
407   
408         track.UpdateESDtrack(seed);
409         
410         // Add TRD track to ESDfriendTrack
411 //                              if (AliTRDReconstructor::RecoParam()->GetStreamLevel() > 0 /*&& quality TODO*/){ 
412 //                                      AliTRDtrackV1 *calibTrack = new AliTRDtrackV1(track);
413 //                                      calibTrack->SetOwner();
414 //                                      seed->AddCalibObject(calibTrack);
415 //                              }
416         found++;
417       }
418     }
419   
420     seed->SetTRDQuality(track.StatusForTOF());
421     seed->SetTRDBudget(track.GetBudget(0));
422   }
423   
424
425   AliInfo(Form("Number of seeds: %d", nSeed));
426   AliInfo(Form("Number of back propagated TRD tracks: %d", found));
427       
428   delete [] index;
429   delete [] quality;
430   
431   return 0;
432 }
433
434
435 //____________________________________________________________________
436 Int_t AliTRDtrackerV1::RefitInward(AliESDEvent *event)
437 {
438   //
439   // Refits tracks within the TRD. The ESD event is expected to contain seeds 
440   // at the outer part of the TRD. 
441   // The tracks are propagated to the innermost time bin 
442   // of the TRD and the ESD event is updated
443   // Origin: Thomas KUHR (Thomas.Kuhr@cern.ch)
444   //
445
446   Int_t   nseed    = 0; // contor for loaded seeds
447   Int_t   found    = 0; // contor for updated TRD tracks
448   
449   
450   AliTRDtrackV1 track;
451   for (Int_t itrack = 0; itrack < event->GetNumberOfTracks(); itrack++) {
452     AliESDtrack *seed = event->GetTrack(itrack);
453     new(&track) AliTRDtrackV1(*seed);
454
455     if (track.GetX() < 270.0) {
456       seed->UpdateTrackParams(&track, AliESDtrack::kTRDbackup);
457       continue;
458     }
459
460     ULong_t status = seed->GetStatus();
461     if((status & AliESDtrack::kTRDout) == 0) continue;
462     if((status & AliESDtrack::kTRDin)  != 0) continue;
463     nseed++; 
464
465     track.ResetCovariance(50.0);
466
467     // do the propagation and processing
468     Bool_t kUPDATE = kFALSE;
469     Double_t xTPC = 250.0;
470     if(FollowProlongation(track)){      
471       // Prolongate to TPC
472       if (PropagateToX(track, xTPC, fgkMaxStep)) { //  -with update
473   seed->UpdateTrackParams(&track, AliESDtrack::kTRDrefit);
474   found++;
475   kUPDATE = kTRUE;
476       }
477     }    
478     
479     // Prolongate to TPC without update
480     if(!kUPDATE) {
481       AliTRDtrackV1 tt(*seed);
482       if (PropagateToX(tt, xTPC, fgkMaxStep)) seed->UpdateTrackParams(&tt, AliESDtrack::kTRDrefit);
483     }
484   }
485   AliInfo(Form("Number of loaded seeds: %d",nseed));
486   AliInfo(Form("Number of found tracks from loaded seeds: %d",found));
487   
488   return 0;
489 }
490
491
492 //____________________________________________________________________
493 Int_t AliTRDtrackerV1::FollowProlongation(AliTRDtrackV1 &t)
494 {
495   // Extrapolates the TRD track in the TPC direction.
496   //
497   // Parameters
498   //   t : the TRD track which has to be extrapolated
499   // 
500   // Output
501   //   number of clusters attached to the track
502   //
503   // Detailed description
504   //
505   // Starting from current radial position of track <t> this function
506   // extrapolates the track through the 6 TRD layers. The following steps
507   // are being performed for each plane:
508   // 1. prepare track:
509   //   a. get plane limits in the local x direction
510   //   b. check crossing sectors 
511   //   c. check track inclination
512   // 2. search tracklet in the tracker list (see GetTracklet() for details)
513   // 3. evaluate material budget using the geo manager
514   // 4. propagate and update track using the tracklet information.
515   //
516   // Debug level 2
517   //
518   
519   Int_t    nClustersExpected = 0;
520   Int_t lastplane = 5; //GetLastPlane(&t);
521   for (Int_t iplane = lastplane; iplane >= 0; iplane--) {
522     Int_t   index   = 0;
523     AliTRDseedV1 *tracklet = GetTracklet(&t, iplane, index);
524     if(!tracklet) continue;
525     if(!tracklet->IsOK()) AliWarning("tracklet not OK");
526     
527     Double_t x  = tracklet->GetX0();
528     // reject tracklets which are not considered for inward refit
529     if(x > t.GetX()+fgkMaxStep) continue;
530
531     // append tracklet to track
532     t.SetTracklet(tracklet, index);
533     
534     if (x < (t.GetX()-fgkMaxStep) && !PropagateToX(t, x+fgkMaxStep, fgkMaxStep)) break;
535     if (!AdjustSector(&t)) break;
536     
537     // Start global position
538     Double_t xyz0[3];
539     t.GetXYZ(xyz0);
540
541     // End global position
542     Double_t alpha = t.GetAlpha(), y, z;
543     if (!t.GetProlongation(x,y,z)) break;    
544     Double_t xyz1[3];
545     xyz1[0] =  x * TMath::Cos(alpha) - y * TMath::Sin(alpha);
546     xyz1[1] =  x * TMath::Sin(alpha) + y * TMath::Cos(alpha);
547     xyz1[2] =  z;
548         
549     // Get material budget
550     Double_t param[7];
551     AliTracker::MeanMaterialBudget(xyz0, xyz1, param);
552     Double_t xrho= param[0]*param[4];
553     Double_t xx0 = param[1]; // Get mean propagation parameters
554
555     // Propagate and update             
556     t.PropagateTo(x, xx0, xrho);
557     if (!AdjustSector(&t)) break;
558     
559     Double_t maxChi2 = t.GetPredictedChi2(tracklet);
560     if (maxChi2 < 1e+10 && t.Update(tracklet, maxChi2)){ 
561       nClustersExpected += tracklet->GetN();
562     }
563   }
564
565   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() > 1){
566     Int_t index;
567     for(int iplane=0; iplane<6; iplane++){
568       AliTRDseedV1 *tracklet = GetTracklet(&t, iplane, index);
569       if(!tracklet) continue;
570       t.SetTracklet(tracklet, index);
571     }
572
573     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
574     TTreeSRedirector &cstreamer = *fgDebugStreamer;
575     cstreamer << "FollowProlongation"
576         << "EventNumber="       << eventNumber
577         << "ncl="                                       << nClustersExpected
578         //<< "track.="                  << &t
579         << "\n";
580   }
581
582   return nClustersExpected;
583
584 }
585
586 //_____________________________________________________________________________
587 Int_t AliTRDtrackerV1::FollowBackProlongation(AliTRDtrackV1 &t)
588 {
589   // Extrapolates the TRD track in the TOF direction.
590   //
591   // Parameters
592   //   t : the TRD track which has to be extrapolated
593   // 
594   // Output
595   //   number of clusters attached to the track
596   //
597   // Detailed description
598   //
599   // Starting from current radial position of track <t> this function
600   // extrapolates the track through the 6 TRD layers. The following steps
601   // are being performed for each plane:
602   // 1. prepare track:
603   //   a. get plane limits in the local x direction
604   //   b. check crossing sectors 
605   //   c. check track inclination
606   // 2. build tracklet (see AliTRDseed::AttachClusters() for details)
607   // 3. evaluate material budget using the geo manager
608   // 4. propagate and update track using the tracklet information.
609   //
610   // Debug level 2
611   //
612
613   Int_t nClustersExpected = 0;
614   Double_t clength = AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick();
615   AliTRDtrackingChamber *chamber = 0x0;
616   
617   AliTRDseedV1 tracklet, *ptrTracklet = 0x0;
618
619   // Loop through the TRD layers
620   for (Int_t ilayer = 0; ilayer < AliTRDgeometry::Nlayer(); ilayer++) {
621     // BUILD TRACKLET IF NOT ALREADY BUILT
622     Double_t x = 0., y, z, alpha;
623     ptrTracklet  = t.GetTracklet(ilayer);
624     if(!ptrTracklet){
625       ptrTracklet = new(&tracklet) AliTRDseedV1(ilayer);
626       alpha = t.GetAlpha();
627       Int_t sector = Int_t(alpha/AliTRDgeometry::GetAlpha() + (alpha>0. ? 0 : AliTRDgeometry::kNsector));
628
629       if(!fTrSec[sector].GetNChambers()) continue;
630       
631       if((x = fTrSec[sector].GetX(ilayer)) < 1.) continue;
632     
633       if (!t.GetProlongation(x, y, z)) break;
634       Int_t stack = fGeom->GetStack(z, ilayer);
635       Int_t nCandidates = stack >= 0 ? 1 : 2;
636       z -= stack >= 0 ? 0. : 4.; 
637       
638       for(int icham=0; icham<nCandidates; icham++, z+=8){
639         if((stack = fGeom->GetStack(z, ilayer)) < 0) continue;
640       
641         if(!(chamber = fTrSec[sector].GetChamber(stack, ilayer))) continue;
642       
643         if(chamber->GetNClusters() < fgNTimeBins*AliTRDReconstructor::RecoParam()->GetFindableClusters()) continue;
644       
645         x = chamber->GetX();
646       
647         AliTRDpadPlane *pp = fGeom->GetPadPlane(ilayer, stack);
648         tracklet.SetTilt(TMath::Tan(-TMath::DegToRad()*pp->GetTiltingAngle()));
649         tracklet.SetPadLength(pp->GetLengthIPad());
650         tracklet.SetPlane(ilayer);
651         tracklet.SetX0(x);
652         if(!tracklet.Init(&t)){
653           t.SetStopped(kTRUE);
654           return nClustersExpected;
655         }
656         if(!tracklet.AttachClustersIter(chamber, 1000.)) continue;
657         tracklet.Init(&t);
658         
659         if(tracklet.GetN() < fgNTimeBins * AliTRDReconstructor::RecoParam()->GetFindableClusters()) continue;
660       
661         break;
662       }
663     }
664     if(!ptrTracklet->IsOK()){
665       if(x < 1.) continue; //temporary
666       if(!PropagateToX(t, x-fgkMaxStep, fgkMaxStep)) break;
667       if(!AdjustSector(&t)) break;
668       if(TMath::Abs(t.GetSnp()) > fgkMaxSnp) break;
669       continue;
670     }
671     
672     // Propagate closer to the current chamber if neccessary 
673     x -= clength;
674     if (x > (fgkMaxStep + t.GetX()) && !PropagateToX(t, x-fgkMaxStep, fgkMaxStep)) break;
675     if (!AdjustSector(&t)) break;
676     if (TMath::Abs(t.GetSnp()) > fgkMaxSnp) break;
677     
678     // load tracklet to the tracker and the track
679     ptrTracklet = SetTracklet(ptrTracklet);
680     t.SetTracklet(ptrTracklet, fTracklets->GetEntriesFast()-1);
681   
682   
683     // Calculate the mean material budget along the path inside the chamber
684     //Calculate global entry and exit positions of the track in chamber (only track prolongation)
685     Double_t xyz0[3]; // entry point 
686     t.GetXYZ(xyz0);
687     alpha = t.GetAlpha();
688     x = ptrTracklet->GetX0();
689     if (!t.GetProlongation(x, y, z)) break;
690     Double_t xyz1[3]; // exit point
691     xyz1[0] =  x * TMath::Cos(alpha) - y * TMath::Sin(alpha); 
692     xyz1[1] = +x * TMath::Sin(alpha) + y * TMath::Cos(alpha);
693     xyz1[2] =  z;
694     Double_t param[7];
695     AliTracker::MeanMaterialBudget(xyz0, xyz1, param);  
696     // The mean propagation parameters
697     Double_t xrho = param[0]*param[4]; // density*length
698     Double_t xx0  = param[1]; // radiation length
699     
700     // Propagate and update track
701     t.PropagateTo(x, xx0, xrho);
702     if (!AdjustSector(&t)) break;
703     Double_t maxChi2 = t.GetPredictedChi2(ptrTracklet);
704     if (maxChi2<1e+10 && t.Update(ptrTracklet, maxChi2)){ 
705       nClustersExpected += ptrTracklet->GetN();
706       //t.SetTracklet(&tracklet, index);
707     }
708     // Reset material budget if 2 consecutive gold
709     if(ilayer>0 && t.GetTracklet(ilayer-1) && ptrTracklet->GetN() + t.GetTracklet(ilayer-1)->GetN() > 20) t.SetBudget(2, 0.);
710
711     // Make backup of the track until is gold
712     // TO DO update quality check of the track.
713     // consider comparison with fTimeBinsRange
714     Float_t ratio0 = ptrTracklet->GetN() / Float_t(fgNTimeBins);
715     //Float_t ratio1 = Float_t(t.GetNumberOfClusters()+1) / Float_t(t.GetNExpected()+1);        
716     //printf("tracklet.GetChi2() %f     [< 18.0]\n", tracklet.GetChi2()); 
717     //printf("ratio0    %f              [>   0.8]\n", ratio0);
718     //printf("ratio1     %f             [>   0.6]\n", ratio1); 
719     //printf("ratio0+ratio1 %f          [>   1.5]\n", ratio0+ratio1); 
720     //printf("t.GetNCross()  %d         [==    0]\n", t.GetNCross()); 
721     //printf("TMath::Abs(t.GetSnp()) %f [<  0.85]\n", TMath::Abs(t.GetSnp()));
722     //printf("t.GetNumberOfClusters() %d [>    20]\n", t.GetNumberOfClusters());
723     
724     if (//(tracklet.GetChi2()      <  18.0) && TO DO check with FindClusters and move it to AliTRDseed::Update 
725         (ratio0                  >   0.8) && 
726         //(ratio1                  >   0.6) && 
727         //(ratio0+ratio1           >   1.5) && 
728         (t.GetNCross()           ==    0) && 
729         (TMath::Abs(t.GetSnp())  <  0.85) &&
730         (t.GetNumberOfClusters() >    20)) t.MakeBackupTrack();
731     
732   } // end layers loop
733
734   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() > 1){
735     TTreeSRedirector &cstreamer = *fgDebugStreamer;
736     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
737     //AliTRDtrackV1 *debugTrack = new AliTRDtrackV1(t);
738     //debugTrack->SetOwner();
739     cstreamer << "FollowBackProlongation"
740         << "EventNumber="                       << eventNumber
741         << "ncl="                                                       << nClustersExpected
742         //<< "track.="                                  << debugTrack
743         << "\n";
744   }
745   
746   return nClustersExpected;
747 }
748
749 //_________________________________________________________________________
750 Float_t AliTRDtrackerV1::FitRieman(AliTRDseedV1 *tracklets, Double_t *chi2, Int_t *planes){
751   //
752   // Fits a Riemann-circle to the given points without tilting pad correction.
753   // The fit is performed using an instance of the class AliRieman (equations 
754   // and transformations see documentation of this class)
755   // Afterwards all the tracklets are Updated
756   //
757   // Parameters: - Array of tracklets (AliTRDseedV1)
758   //             - Storage for the chi2 values (beginning with direction z)  
759   //             - Seeding configuration
760   // Output:     - The curvature
761   //
762   AliRieman *fitter = AliTRDtrackerV1::GetRiemanFitter();
763   fitter->Reset();
764   Int_t allplanes[] = {0, 1, 2, 3, 4, 5};
765   Int_t *ppl = &allplanes[0];
766   Int_t maxLayers = 6;
767   if(planes){
768     maxLayers = 4;
769     ppl = planes;
770   }
771   for(Int_t il = 0; il < maxLayers; il++){
772     if(!tracklets[ppl[il]].IsOK()) continue;
773     fitter->AddPoint(tracklets[ppl[il]].GetX0(), tracklets[ppl[il]].GetYfitR(0), tracklets[ppl[il]].GetZProb(),1,10);
774   }
775   fitter->Update();
776   // Set the reference position of the fit and calculate the chi2 values
777   memset(chi2, 0, sizeof(Double_t) * 2);
778   for(Int_t il = 0; il < maxLayers; il++){
779     // Reference positions
780     tracklets[ppl[il]].Init(fitter);
781     
782     // chi2
783     if((!tracklets[ppl[il]].IsOK()) && (!planes)) continue;
784     chi2[0] += tracklets[ppl[il]].GetChi2Y();
785     chi2[1] += tracklets[ppl[il]].GetChi2Z();
786   }
787   return fitter->GetC();
788 }
789
790 //_________________________________________________________________________
791 void AliTRDtrackerV1::FitRieman(AliTRDcluster **seedcl, Double_t chi2[2])
792 {
793   //
794   // Performs a Riemann helix fit using the seedclusters as spacepoints
795   // Afterwards the chi2 values are calculated and the seeds are updated
796   //
797   // Parameters: - The four seedclusters
798   //             - The tracklet array (AliTRDseedV1)
799   //             - The seeding configuration
800   //             - Chi2 array
801   //
802   // debug level 2
803   //
804   AliRieman *fitter = AliTRDtrackerV1::GetRiemanFitter();
805   fitter->Reset();
806   for(Int_t i = 0; i < 4; i++)
807     fitter->AddPoint(seedcl[i]->GetX(), seedcl[i]->GetY(), seedcl[i]->GetZ(), 1, 10);
808   fitter->Update();
809   
810   
811   // Update the seed and calculated the chi2 value
812   chi2[0] = 0; chi2[1] = 0;
813   for(Int_t ipl = 0; ipl < kNSeedPlanes; ipl++){
814     // chi2
815     chi2[0] += (seedcl[ipl]->GetZ() - fitter->GetZat(seedcl[ipl]->GetX())) * (seedcl[ipl]->GetZ() - fitter->GetZat(seedcl[ipl]->GetX()));
816     chi2[1] += (seedcl[ipl]->GetY() - fitter->GetYat(seedcl[ipl]->GetX())) * (seedcl[ipl]->GetY() - fitter->GetYat(seedcl[ipl]->GetX()));
817   }     
818 }
819
820
821 //_________________________________________________________________________
822 Float_t AliTRDtrackerV1::FitTiltedRiemanConstraint(AliTRDseedV1 *tracklets, Double_t zVertex)
823 {
824   //
825   // Fits a helix to the clusters. Pad tilting is considered. As constraint it is 
826   // assumed that the vertex position is set to 0.
827   // This method is very usefull for high-pt particles
828   // Basis for the fit: (x - x0)^2 + (y - y0)^2 - R^2 = 0
829   //      x0, y0: Center of the circle
830   // Measured y-position: ymeas = y - tan(phiT)(zc - zt)
831   //      zc: center of the pad row
832   // Equation which has to be fitted (after transformation):
833   // a + b * u + e * v + 2*(ymeas + tan(phiT)(z - zVertex))*t = 0
834   // Transformation:
835   // t = 1/(x^2 + y^2)
836   // u = 2 * x * t
837   // v = 2 * x * tan(phiT) * t
838   // Parameters in the equation: 
839   //    a = -1/y0, b = x0/y0, e = dz/dx
840   //
841   // The Curvature is calculated by the following equation:
842   //               - curv = a/Sqrt(b^2 + 1) = 1/R
843   // Parameters:   - the 6 tracklets
844   //               - the Vertex constraint
845   // Output:       - the Chi2 value of the track
846   //
847   // debug level 5
848   //
849
850   TLinearFitter *fitter = GetTiltedRiemanFitterConstraint();
851   fitter->StoreData(kTRUE);
852   fitter->ClearPoints();
853   AliTRDcluster *cl = 0x0;
854   
855   Float_t x, y, z, w, t, error, tilt;
856   Double_t uvt[2];
857   Int_t nPoints = 0;
858   for(Int_t ilr = 0; ilr < AliTRDgeometry::kNlayer; ilr++){
859     if(!tracklets[ilr].IsOK()) continue;
860     for(Int_t itb = 0; itb < fgNTimeBins; itb++){
861       if(!tracklets[ilr].IsUsable(itb)) continue;
862       cl = tracklets[ilr].GetClusters(itb);
863       x = cl->GetX();
864       y = cl->GetY();
865       z = cl->GetZ();
866       tilt = tracklets[ilr].GetTilt();
867       // Transformation
868       t = 1./(x * x + y * y);
869       uvt[0] = 2. * x * t;
870       uvt[1] = 2. * x * t * tilt ;
871       w = 2. * (y + tilt * (z - zVertex)) * t;
872       error = 2. * 0.2 * t;
873       fitter->AddPoint(uvt, w, error);
874       nPoints++;
875     }
876   }
877   fitter->Eval();
878
879   // Calculate curvature
880   Double_t a = fitter->GetParameter(0);
881   Double_t b = fitter->GetParameter(1);
882   Double_t curvature = a/TMath::Sqrt(b*b + 1);
883
884   Float_t chi2track = fitter->GetChisquare()/Double_t(nPoints);
885   for(Int_t ip = 0; ip < AliTRDtrackerV1::kNPlanes; ip++)
886     tracklets[ip].SetCC(curvature);
887
888   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() >= 5){
889     //Linear Model on z-direction
890     Double_t xref = CalculateReferenceX(tracklets);             // Relative to the middle of the stack
891     Double_t slope = fitter->GetParameter(2);
892     Double_t zref = slope * xref;
893     Float_t chi2Z = CalculateChi2Z(tracklets, zref, slope, xref);
894     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
895     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
896     TTreeSRedirector &treeStreamer = *fgDebugStreamer;
897     treeStreamer << "FitTiltedRiemanConstraint"
898     << "EventNumber="           << eventNumber
899     << "CandidateNumber="       << candidateNumber
900     << "Curvature="                             << curvature
901     << "Chi2Track="                             << chi2track
902     << "Chi2Z="                                         << chi2Z
903     << "zref="                                          << zref
904     << "\n";
905   }
906   return chi2track;
907 }
908
909 //_________________________________________________________________________
910 Float_t AliTRDtrackerV1::FitTiltedRieman(AliTRDseedV1 *tracklets, Bool_t sigError)
911 {
912   //
913   // Performs a Riemann fit taking tilting pad correction into account
914   // The equation of a Riemann circle, where the y position is substituted by the 
915   // measured y-position taking pad tilting into account, has to be transformed
916   // into a 4-dimensional hyperplane equation
917   // Riemann circle: (x-x0)^2 + (y-y0)^2 -R^2 = 0
918   // Measured y-Position: ymeas = y - tan(phiT)(zc - zt)
919   //          zc: center of the pad row
920   //          zt: z-position of the track
921   // The z-position of the track is assumed to be linear dependent on the x-position
922   // Transformed equation: a + b * u + c * t + d * v  + e * w - 2 * (ymeas + tan(phiT) * zc) * t = 0
923   // Transformation:       u = 2 * x * t
924   //                       v = 2 * tan(phiT) * t
925   //                       w = 2 * tan(phiT) * (x - xref) * t
926   //                       t = 1 / (x^2 + ymeas^2)
927   // Parameters:           a = -1/y0
928   //                       b = x0/y0
929   //                       c = (R^2 -x0^2 - y0^2)/y0
930   //                       d = offset
931   //                       e = dz/dx
932   // If the offset respectively the slope in z-position is impossible, the parameters are fixed using 
933   // results from the simple riemann fit. Afterwards the fit is redone.
934   // The curvature is calculated according to the formula:
935   //                       curv = a/(1 + b^2 + c*a) = 1/R
936   //
937   // Paramters:   - Array of tracklets (connected to the track candidate)
938   //              - Flag selecting the error definition
939   // Output:      - Chi2 values of the track (in Parameter list)
940   //
941   TLinearFitter *fitter = GetTiltedRiemanFitter();
942   fitter->StoreData(kTRUE);
943   fitter->ClearPoints();
944   AliTRDLeastSquare zfitter;
945   AliTRDcluster *cl = 0x0;
946
947   Double_t xref = CalculateReferenceX(tracklets);
948   Double_t x, y, z, t, tilt, dx, w, we;
949   Double_t uvt[4];
950   Int_t nPoints = 0;
951   // Containers for Least-square fitter
952   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
953     if(!tracklets[ipl].IsOK()) continue;
954     for(Int_t itb = 0; itb < fgNTimeBins; itb++){
955       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
956       if (!tracklets[ipl].IsUsable(itb)) continue;
957       x = cl->GetX();
958       y = cl->GetY();
959       z = cl->GetZ();
960       tilt = tracklets[ipl].GetTilt();
961       dx = x - xref;
962       // Transformation
963       t = 1./(x*x + y*y);
964       uvt[0] = 2. * x * t;
965       uvt[1] = t;
966       uvt[2] = 2. * tilt * t;
967       uvt[3] = 2. * tilt * dx * t;
968       w = 2. * (y + tilt*z) * t;
969       // error definition changes for the different calls
970       we = 2. * t;
971       we *= sigError ? tracklets[ipl].GetSigmaY() : 0.2;
972       fitter->AddPoint(uvt, w, we);
973       zfitter.AddPoint(&x, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
974       nPoints++;
975     }
976   }
977   fitter->Eval();
978   zfitter.Eval();
979
980   Double_t offset = fitter->GetParameter(3);
981   Double_t slope  = fitter->GetParameter(4);
982
983   // Linear fitter  - not possible to make boundaries
984   // Do not accept non possible z and dzdx combinations
985   Bool_t acceptablez = kTRUE;
986   Double_t zref = 0.0;
987   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
988     if(!tracklets[iLayer].IsOK()) continue;
989     zref = offset + slope * (tracklets[iLayer].GetX0() - xref);
990     if (TMath::Abs(tracklets[iLayer].GetZProb() - zref) > tracklets[iLayer].GetPadLength() * 0.5 + 1.0) 
991       acceptablez = kFALSE;
992   }
993   if (!acceptablez) {
994     Double_t dzmf       = zfitter.GetFunctionParameter(1);
995     Double_t zmf        = zfitter.GetFunctionValue(&xref);
996     fgTiltedRieman->FixParameter(3, zmf);
997     fgTiltedRieman->FixParameter(4, dzmf);
998     fitter->Eval();
999     fitter->ReleaseParameter(3);
1000     fitter->ReleaseParameter(4);
1001     offset = fitter->GetParameter(3);
1002     slope = fitter->GetParameter(4);
1003   }
1004
1005   // Calculate Curvarture
1006   Double_t a     =  fitter->GetParameter(0);
1007   Double_t b     =  fitter->GetParameter(1);
1008   Double_t c     =  fitter->GetParameter(2);
1009   Double_t curvature =  1.0 + b*b - c*a;
1010   if (curvature > 0.0) 
1011     curvature  =  a / TMath::Sqrt(curvature);
1012
1013   Double_t chi2track = fitter->GetChisquare()/Double_t(nPoints);
1014
1015   // Update the tracklets
1016   Double_t dy, dz;
1017   for(Int_t iLayer = 0; iLayer < AliTRDtrackerV1::kNPlanes; iLayer++) {
1018
1019     x  = tracklets[iLayer].GetX0();
1020     y  = 0;
1021     z  = 0;
1022     dy = 0;
1023     dz = 0;
1024
1025     // y:     R^2 = (x - x0)^2 + (y - y0)^2
1026     //     =>   y = y0 +/- Sqrt(R^2 - (x - x0)^2)
1027     //          R = Sqrt() = 1/Curvature
1028     //     =>   y = y0 +/- Sqrt(1/Curvature^2 - (x - x0)^2)  
1029     Double_t res = (x * a + b);                                                         // = (x - x0)/y0
1030     res *= res;
1031     res  = 1.0 - c * a + b * b - res;                                   // = (R^2 - (x - x0)^2)/y0^2
1032     if (res >= 0) {
1033       res = TMath::Sqrt(res);
1034       y    = (1.0 - res) / a;
1035     }
1036
1037     // dy:      R^2 = (x - x0)^2 + (y - y0)^2
1038     //     =>     y = +/- Sqrt(R^2 - (x - x0)^2) + y0
1039     //     => dy/dx = (x - x0)/Sqrt(R^2 - (x - x0)^2) 
1040     // Curvature: cr = 1/R = a/Sqrt(1 + b^2 - c*a)
1041     //     => dy/dx =  (x - x0)/(1/(cr^2) - (x - x0)^2) 
1042     Double_t x0 = -b / a;
1043     if (-c * a + b * b + 1 > 0) {
1044       if (1.0/(curvature * curvature) - (x - x0) * (x - x0) > 0.0) {
1045   Double_t yderiv = (x - x0) / TMath::Sqrt(1.0/(curvature * curvature) - (x - x0) * (x - x0));
1046   if (a < 0) yderiv *= -1.0;
1047   dy = yderiv;
1048       }
1049     }
1050     z  = offset + slope * (x - xref);
1051     dz = slope;
1052     tracklets[iLayer].SetYref(0, y);
1053     tracklets[iLayer].SetYref(1, dy);
1054     tracklets[iLayer].SetZref(0, z);
1055     tracklets[iLayer].SetZref(1, dz);
1056     tracklets[iLayer].SetC(curvature);
1057     tracklets[iLayer].SetChi2(chi2track);
1058   }
1059   
1060   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() >=5){
1061     TTreeSRedirector &cstreamer = *fgDebugStreamer;
1062     Int_t eventNumber                   = AliTRDtrackerDebug::GetEventNumber();
1063     Int_t candidateNumber       = AliTRDtrackerDebug::GetCandidateNumber();
1064     Double_t chi2z = CalculateChi2Z(tracklets, offset, slope, xref);
1065     cstreamer << "FitTiltedRieman0"
1066         << "EventNumber="                       << eventNumber
1067         << "CandidateNumber="   << candidateNumber
1068         << "xref="                                              << xref
1069         << "Chi2Z="                                             << chi2z
1070         << "\n";
1071   }
1072   return chi2track;
1073 }
1074
1075
1076 //____________________________________________________________________
1077 Double_t AliTRDtrackerV1::FitLine(AliTRDtrackV1 *track, AliTRDseedV1 *tracklets, Bool_t err, Int_t np, AliTrackPoint *points)
1078 {
1079   AliTRDLeastSquare yfitter, zfitter;
1080   AliTRDcluster *cl = 0x0;
1081
1082   AliTRDseedV1 work[kNPlanes], *tracklet = 0x0;
1083   if(!tracklets){
1084     for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1085       if(!(tracklet = track->GetTracklet(ipl))) continue;
1086       if(!tracklet->IsOK()) continue;
1087       new(&work[ipl]) AliTRDseedV1(*tracklet);
1088     }
1089     tracklets = &work[0];
1090   }
1091
1092   Double_t xref = CalculateReferenceX(tracklets);
1093   Double_t x, y, z, dx, ye, yr, tilt;
1094   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1095     if(!tracklets[ipl].IsOK()) continue;
1096     for(Int_t itb = 0; itb < fgNTimeBins; itb++){
1097       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
1098       if (!tracklets[ipl].IsUsable(itb)) continue;
1099       x = cl->GetX();
1100       z = cl->GetZ();
1101       dx = x - xref;
1102       zfitter.AddPoint(&dx, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
1103     }
1104   }
1105   zfitter.Eval();
1106   Double_t z0    = zfitter.GetFunctionParameter(0);
1107   Double_t dzdx  = zfitter.GetFunctionParameter(1);
1108   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1109     if(!tracklets[ipl].IsOK()) continue;
1110     for(Int_t itb = 0; itb < fgNTimeBins; itb++){
1111       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
1112       if (!tracklets[ipl].IsUsable(itb)) continue;
1113       x = cl->GetX();
1114       y = cl->GetY();
1115       z = cl->GetZ();
1116       tilt = tracklets[ipl].GetTilt();
1117       dx = x - xref;
1118       yr = y + tilt*(z - z0 - dzdx*dx); 
1119       // error definition changes for the different calls
1120       ye = tilt*TMath::Sqrt(cl->GetSigmaZ2());
1121       ye += err ? tracklets[ipl].GetSigmaY() : 0.2;
1122       yfitter.AddPoint(&dx, yr, ye);
1123     }
1124   }
1125   yfitter.Eval();
1126   Double_t y0   = yfitter.GetFunctionParameter(0);
1127   Double_t dydx = yfitter.GetFunctionParameter(1);
1128   Double_t chi2 = 0.;//yfitter.GetChisquare()/Double_t(nPoints);
1129
1130   //update track points array
1131   if(np && points){
1132     Float_t xyz[3];
1133     for(int ip=0; ip<np; ip++){
1134       points[ip].GetXYZ(xyz);
1135       xyz[1] = y0 + dydx * (xyz[0] - xref);
1136       xyz[2] = z0 + dzdx * (xyz[0] - xref);
1137       points[ip].SetXYZ(xyz);
1138     }
1139   }
1140   return chi2;
1141 }
1142
1143
1144 //_________________________________________________________________________
1145 Double_t AliTRDtrackerV1::FitRiemanTilt(AliTRDtrackV1 *track, AliTRDseedV1 *tracklets, Bool_t sigError, Int_t np, AliTrackPoint *points)
1146 {
1147   //
1148   // Performs a Riemann fit taking tilting pad correction into account
1149   // The equation of a Riemann circle, where the y position is substituted by the 
1150   // measured y-position taking pad tilting into account, has to be transformed
1151   // into a 4-dimensional hyperplane equation
1152   // Riemann circle: (x-x0)^2 + (y-y0)^2 -R^2 = 0
1153   // Measured y-Position: ymeas = y - tan(phiT)(zc - zt)
1154   //          zc: center of the pad row
1155   //          zt: z-position of the track
1156   // The z-position of the track is assumed to be linear dependent on the x-position
1157   // Transformed equation: a + b * u + c * t + d * v  + e * w - 2 * (ymeas + tan(phiT) * zc) * t = 0
1158   // Transformation:       u = 2 * x * t
1159   //                       v = 2 * tan(phiT) * t
1160   //                       w = 2 * tan(phiT) * (x - xref) * t
1161   //                       t = 1 / (x^2 + ymeas^2)
1162   // Parameters:           a = -1/y0
1163   //                       b = x0/y0
1164   //                       c = (R^2 -x0^2 - y0^2)/y0
1165   //                       d = offset
1166   //                       e = dz/dx
1167   // If the offset respectively the slope in z-position is impossible, the parameters are fixed using 
1168   // results from the simple riemann fit. Afterwards the fit is redone.
1169   // The curvature is calculated according to the formula:
1170   //                       curv = a/(1 + b^2 + c*a) = 1/R
1171   //
1172   // Paramters:   - Array of tracklets (connected to the track candidate)
1173   //              - Flag selecting the error definition
1174   // Output:      - Chi2 values of the track (in Parameter list)
1175   //
1176   TLinearFitter *fitter = GetTiltedRiemanFitter();
1177   fitter->StoreData(kTRUE);
1178   fitter->ClearPoints();
1179   AliTRDLeastSquare zfitter;
1180   AliTRDcluster *cl = 0x0;
1181
1182   AliTRDseedV1 work[kNPlanes], *tracklet = 0x0;
1183   if(!tracklets){
1184     for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1185       if(!(tracklet = track->GetTracklet(ipl))) continue;
1186       if(!tracklet->IsOK()) continue;
1187       new(&work[ipl]) AliTRDseedV1(*tracklet);
1188     }
1189     tracklets = &work[0];
1190   }
1191
1192   Double_t xref = CalculateReferenceX(tracklets);
1193   Double_t x, y, z, t, tilt, dx, w, we;
1194   Double_t uvt[4];
1195   Int_t nPoints = 0;
1196   // Containers for Least-square fitter
1197   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
1198     if(!tracklets[ipl].IsOK()) continue;
1199     for(Int_t itb = 0; itb < fgNTimeBins; itb++){
1200       if(!(cl = tracklets[ipl].GetClusters(itb))) continue;
1201       if (!tracklets[ipl].IsUsable(itb)) continue;
1202       x = cl->GetX();
1203       y = cl->GetY();
1204       z = cl->GetZ();
1205       tilt = tracklets[ipl].GetTilt();
1206       dx = x - xref;
1207       // Transformation
1208       t = 1./(x*x + y*y);
1209       uvt[0] = 2. * x * t;
1210       uvt[1] = t;
1211       uvt[2] = 2. * tilt * t;
1212       uvt[3] = 2. * tilt * dx * t;
1213       w = 2. * (y + tilt*z) * t;
1214       // error definition changes for the different calls
1215       we = 2. * t;
1216       we *= sigError ? tracklets[ipl].GetSigmaY() : 0.2;
1217       fitter->AddPoint(uvt, w, we);
1218       zfitter.AddPoint(&x, z, static_cast<Double_t>(TMath::Sqrt(cl->GetSigmaZ2())));
1219       nPoints++;
1220     }
1221   }
1222   fitter->Eval();
1223   Double_t z0    = fitter->GetParameter(3);
1224   Double_t dzdx  = fitter->GetParameter(4);
1225
1226
1227   // Linear fitter  - not possible to make boundaries
1228   // Do not accept non possible z and dzdx combinations
1229   Bool_t accept = kTRUE;
1230   Double_t zref = 0.0;
1231   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
1232     if(!tracklets[iLayer].IsOK()) continue;
1233     zref = z0 + dzdx * (tracklets[iLayer].GetX0() - xref);
1234     if (TMath::Abs(tracklets[iLayer].GetZProb() - zref) > tracklets[iLayer].GetPadLength() * 0.5 + 1.0) 
1235       accept = kFALSE;
1236   }
1237   if (!accept) {
1238     zfitter.Eval();
1239     Double_t dzmf       = zfitter.GetFunctionParameter(1);
1240     Double_t zmf        = zfitter.GetFunctionValue(&xref);
1241     fitter->FixParameter(3, zmf);
1242     fitter->FixParameter(4, dzmf);
1243     fitter->Eval();
1244     fitter->ReleaseParameter(3);
1245     fitter->ReleaseParameter(4);
1246     z0   = fitter->GetParameter(3); // = zmf ?
1247     dzdx = fitter->GetParameter(4); // = dzmf ?
1248   }
1249
1250   // Calculate Curvature
1251   Double_t a    =  fitter->GetParameter(0);
1252   Double_t b    =  fitter->GetParameter(1);
1253   Double_t c    =  fitter->GetParameter(2);
1254   Double_t y0   = 1. / a;
1255   Double_t x0   = -b * y0;
1256   Double_t R    = TMath::Sqrt(y0*y0 + x0*x0 - c*y0);
1257   Double_t C    =  1.0 + b*b - c*a;
1258   if (C > 0.0) C  =  a / TMath::Sqrt(C);
1259
1260   // Calculate chi2 of the fit 
1261   Double_t chi2 = fitter->GetChisquare()/Double_t(nPoints);
1262
1263   // Update the tracklets
1264   if(!track){
1265     for(Int_t ip = 0; ip < kNPlanes; ip++) {
1266       x = tracklets[ip].GetX0();
1267       Double_t tmp = TMath::Sqrt(R*R-(x-x0)*(x-x0));  
1268
1269       // y:     R^2 = (x - x0)^2 + (y - y0)^2
1270       //     =>   y = y0 +/- Sqrt(R^2 - (x - x0)^2)
1271       tracklets[ip].SetYref(0, y0 - (y0>0.?1.:-1)*tmp);
1272       //     => dy/dx = (x - x0)/Sqrt(R^2 - (x - x0)^2) 
1273       tracklets[ip].SetYref(1, (x - x0) / tmp);
1274       tracklets[ip].SetZref(0, z0 + dzdx * (x - xref));
1275       tracklets[ip].SetZref(1, dzdx);
1276       tracklets[ip].SetC(C);
1277       tracklets[ip].SetChi2(chi2);
1278     }
1279   }
1280
1281   //update track points array
1282   if(np && points){
1283     Float_t xyz[3];
1284     for(int ip=0; ip<np; ip++){
1285       points[ip].GetXYZ(xyz);
1286       xyz[1] = y0 - (y0>0.?1.:-1)*TMath::Sqrt(R*R-(xyz[0]-x0)*(xyz[0]-x0));
1287       xyz[2] = z0 + dzdx * (xyz[0] - xref);
1288       points[ip].SetXYZ(xyz);
1289     }
1290   }
1291   
1292   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() >=5){
1293     TTreeSRedirector &cstreamer = *fgDebugStreamer;
1294     Int_t eventNumber                   = AliTRDtrackerDebug::GetEventNumber();
1295     Int_t candidateNumber       = AliTRDtrackerDebug::GetCandidateNumber();
1296     Double_t chi2z = CalculateChi2Z(tracklets, z0, dzdx, xref);
1297     cstreamer << "FitRiemanTilt"
1298         << "EventNumber="                       << eventNumber
1299         << "CandidateNumber="   << candidateNumber
1300         << "xref="                                              << xref
1301         << "Chi2Z="                                             << chi2z
1302         << "\n";
1303   }
1304   return chi2;
1305 }
1306
1307
1308
1309 //_________________________________________________________________________
1310 Float_t AliTRDtrackerV1::CalculateChi2Z(AliTRDseedV1 *tracklets, Double_t offset, Double_t slope, Double_t xref)
1311 {
1312   //
1313   // Calculates the chi2-value of the track in z-Direction including tilting pad correction.
1314   // A linear dependence on the x-value serves as a model.
1315   // The parameters are related to the tilted Riemann fit.
1316   // Parameters: - Array of tracklets (AliTRDseedV1) related to the track candidate
1317   //             - the offset for the reference x
1318   //             - the slope
1319   //             - the reference x position
1320   // Output:     - The Chi2 value of the track in z-Direction
1321   //
1322   Float_t chi2Z = 0, nLayers = 0;
1323   for (Int_t iLayer = 0; iLayer < AliTRDgeometry::kNlayer; iLayer++) {
1324     if(!tracklets[iLayer].IsOK()) continue;
1325     Double_t z = offset + slope * (tracklets[iLayer].GetX0() - xref);
1326     chi2Z += TMath::Abs(tracklets[iLayer].GetMeanz() - z);
1327     nLayers++;
1328   }
1329   chi2Z /= TMath::Max((nLayers - 3.0),1.0);
1330   return chi2Z;
1331 }
1332
1333 //_____________________________________________________________________________
1334 Int_t AliTRDtrackerV1::PropagateToX(AliTRDtrackV1 &t, Double_t xToGo, Double_t maxStep)
1335 {
1336   //
1337   // Starting from current X-position of track <t> this function
1338   // extrapolates the track up to radial position <xToGo>. 
1339   // Returns 1 if track reaches the plane, and 0 otherwise 
1340   //
1341
1342   const Double_t kEpsilon = 0.00001;
1343
1344   // Current track X-position
1345   Double_t xpos = t.GetX();
1346
1347   // Direction: inward or outward
1348   Double_t dir  = (xpos < xToGo) ? 1.0 : -1.0;
1349
1350   while (((xToGo - xpos) * dir) > kEpsilon) {
1351
1352     Double_t xyz0[3];
1353     Double_t xyz1[3];
1354     Double_t param[7];
1355     Double_t x;
1356     Double_t y;
1357     Double_t z;
1358
1359     // The next step size
1360     Double_t step = dir * TMath::Min(TMath::Abs(xToGo-xpos),maxStep);
1361
1362     // Get the global position of the starting point
1363     t.GetXYZ(xyz0);
1364
1365     // X-position after next step
1366     x = xpos + step;
1367
1368     // Get local Y and Z at the X-position of the next step
1369     if (!t.GetProlongation(x,y,z)) {
1370       return 0; // No prolongation possible
1371     }
1372
1373     // The global position of the end point of this prolongation step
1374     xyz1[0] =  x * TMath::Cos(t.GetAlpha()) - y * TMath::Sin(t.GetAlpha()); 
1375     xyz1[1] = +x * TMath::Sin(t.GetAlpha()) + y * TMath::Cos(t.GetAlpha());
1376     xyz1[2] =  z;
1377
1378     // Calculate the mean material budget between start and
1379     // end point of this prolongation step
1380     AliTracker::MeanMaterialBudget(xyz0, xyz1, param);
1381
1382     // Propagate the track to the X-position after the next step
1383     if (!t.PropagateTo(x,param[1],param[0]*param[4])) {
1384       return 0;
1385     }
1386
1387     // Rotate the track if necessary
1388     AdjustSector(&t);
1389
1390     // New track X-position
1391     xpos = t.GetX();
1392
1393   }
1394
1395   return 1;
1396
1397 }
1398
1399
1400 //_____________________________________________________________________________
1401 Int_t AliTRDtrackerV1::ReadClusters(TClonesArray* &array, TTree *clusterTree) const
1402 {
1403   //
1404   // Reads AliTRDclusters from the file. 
1405   // The names of the cluster tree and branches 
1406   // should match the ones used in AliTRDclusterizer::WriteClusters()
1407   //
1408
1409   Int_t nsize = Int_t(clusterTree->GetTotBytes() / (sizeof(AliTRDcluster))); 
1410   TObjArray *clusterArray = new TObjArray(nsize+1000); 
1411   
1412   TBranch *branch = clusterTree->GetBranch("TRDcluster");
1413   if (!branch) {
1414     AliError("Can't get the branch !");
1415     return 1;
1416   }
1417   branch->SetAddress(&clusterArray); 
1418   
1419   if(!fClusters){ 
1420     array = new TClonesArray("AliTRDcluster", nsize);
1421     array->SetOwner(kTRUE);
1422   }
1423   
1424   // Loop through all entries in the tree
1425   Int_t nEntries   = (Int_t) clusterTree->GetEntries();
1426   Int_t nbytes     = 0;
1427   Int_t ncl        = 0;
1428   AliTRDcluster *c = 0x0;
1429   for (Int_t iEntry = 0; iEntry < nEntries; iEntry++) {
1430     // Import the tree
1431     nbytes += clusterTree->GetEvent(iEntry);  
1432     
1433     // Get the number of points in the detector
1434     Int_t nCluster = clusterArray->GetEntriesFast();  
1435     for (Int_t iCluster = 0; iCluster < nCluster; iCluster++) { 
1436       if(!(c = (AliTRDcluster *) clusterArray->UncheckedAt(iCluster))) continue;
1437       c->SetInChamber();
1438       new((*fClusters)[ncl++]) AliTRDcluster(*c);
1439       delete (clusterArray->RemoveAt(iCluster)); 
1440     }
1441
1442   }
1443   delete clusterArray;
1444
1445   return 0;
1446 }
1447
1448 //_____________________________________________________________________________
1449 Int_t AliTRDtrackerV1::LoadClusters(TTree *cTree)
1450 {
1451   //
1452   // Fills clusters into TRD tracking_sectors 
1453   // Note that the numbering scheme for the TRD tracking_sectors 
1454   // differs from that of TRD sectors
1455   //
1456
1457   
1458   if (ReadClusters(fClusters, cTree)) {
1459     AliError("Problem with reading the clusters !");
1460     return 1;
1461   }
1462   Int_t ncl  = fClusters->GetEntriesFast(), nin = 0;
1463   if(!ncl){ 
1464     AliInfo("Clusters 0");
1465     return 1;
1466   }
1467
1468   Int_t icl = ncl;
1469   while (icl--) {
1470     AliTRDcluster *c = (AliTRDcluster *) fClusters->UncheckedAt(icl);
1471     if(c->IsInChamber()) nin++;
1472     Int_t detector       = c->GetDetector();
1473     Int_t sector         = fGeom->GetSector(detector);
1474     Int_t stack          = fGeom->GetStack(detector);
1475     Int_t layer          = fGeom->GetLayer(detector);
1476     
1477     fTrSec[sector].GetChamber(stack, layer, kTRUE)->InsertCluster(c, icl);
1478   }
1479   AliInfo(Form("Clusters %d in %6.2f %%", ncl, 100.*float(nin)/ncl));
1480   
1481   for(int isector =0; isector<AliTRDgeometry::kNsector; isector++){ 
1482     if(!fTrSec[isector].GetNChambers()) continue;
1483     fTrSec[isector].Init();
1484   }
1485   
1486   return 0;
1487 }
1488
1489
1490 //____________________________________________________________________
1491 void AliTRDtrackerV1::UnloadClusters() 
1492
1493   //
1494   // Clears the arrays of clusters and tracks. Resets sectors and timebins 
1495   //
1496
1497   if(fTracks) fTracks->Delete(); 
1498   if(fTracklets) fTracklets->Delete();
1499   if(fClusters) fClusters->Delete();
1500
1501   for (int i = 0; i < AliTRDgeometry::kNsector; i++) fTrSec[i].Clear();
1502
1503   // Increment the Event Number
1504   AliTRDtrackerDebug::SetEventNumber(AliTRDtrackerDebug::GetEventNumber()  + 1);
1505 }
1506
1507 //_____________________________________________________________________________
1508 Bool_t AliTRDtrackerV1::AdjustSector(AliTRDtrackV1 *track) 
1509 {
1510   //
1511   // Rotates the track when necessary
1512   //
1513
1514   Double_t alpha = AliTRDgeometry::GetAlpha(); 
1515   Double_t y     = track->GetY();
1516   Double_t ymax  = track->GetX()*TMath::Tan(0.5*alpha);
1517
1518   if      (y >  ymax) {
1519     if (!track->Rotate( alpha)) {
1520       return kFALSE;
1521     }
1522   } 
1523   else if (y < -ymax) {
1524     if (!track->Rotate(-alpha)) {
1525       return kFALSE;   
1526     }
1527   } 
1528
1529   return kTRUE;
1530
1531 }
1532
1533
1534 //____________________________________________________________________
1535 AliTRDseedV1* AliTRDtrackerV1::GetTracklet(AliTRDtrackV1 *track, Int_t p, Int_t &idx)
1536 {
1537   // Find tracklet for TRD track <track>
1538   // Parameters
1539   // - track
1540   // - sector
1541   // - plane
1542   // - index
1543   // Output
1544   // tracklet
1545   // index
1546   // Detailed description
1547   //
1548   idx = track->GetTrackletIndex(p);
1549   AliTRDseedV1 *tracklet = (idx==0xffff) ? 0x0 : (AliTRDseedV1*)fTracklets->UncheckedAt(idx);
1550
1551   return tracklet;
1552 }
1553
1554 //____________________________________________________________________
1555 AliTRDseedV1* AliTRDtrackerV1::SetTracklet(AliTRDseedV1 *tracklet)
1556 {
1557   // Add this tracklet to the list of tracklets stored in the tracker
1558   //
1559   // Parameters
1560   //   - tracklet : pointer to the tracklet to be added to the list
1561   //
1562   // Output
1563   //   - the index of the new tracklet in the tracker tracklets list
1564   //
1565   // Detailed description
1566   // Build the tracklets list if it is not yet created (late initialization)
1567   // and adds the new tracklet to the list.
1568   //
1569   if(!fTracklets){
1570     fTracklets = new TClonesArray("AliTRDseedV1", AliTRDgeometry::Nsector()*kMaxTracksStack);
1571     fTracklets->SetOwner(kTRUE);
1572   }
1573   Int_t nentries = fTracklets->GetEntriesFast();
1574   return new ((*fTracklets)[nentries]) AliTRDseedV1(*tracklet);
1575 }
1576
1577 //____________________________________________________________________
1578 AliTRDtrackV1* AliTRDtrackerV1::SetTrack(AliTRDtrackV1 *track)
1579 {
1580   // Add this track to the list of tracks stored in the tracker
1581   //
1582   // Parameters
1583   //   - track : pointer to the track to be added to the list
1584   //
1585   // Output
1586   //   - the pointer added
1587   //
1588   // Detailed description
1589   // Build the tracks list if it is not yet created (late initialization)
1590   // and adds the new track to the list.
1591   //
1592   if(!fTracks){
1593     fTracks = new TClonesArray("AliTRDtrackV1", AliTRDgeometry::Nsector()*kMaxTracksStack);
1594     fTracks->SetOwner(kTRUE);
1595   }
1596   Int_t nentries = fTracks->GetEntriesFast();
1597   return new ((*fTracks)[nentries]) AliTRDtrackV1(*track);
1598 }
1599
1600
1601
1602 //____________________________________________________________________
1603 Int_t AliTRDtrackerV1::Clusters2TracksSM(Int_t sector, AliESDEvent *esd)
1604 {
1605   //
1606   // Steer tracking for one SM.
1607   //
1608   // Parameters :
1609   //   sector  : Array of (SM) propagation layers containing clusters
1610   //   esd     : The current ESD event. On output it contains the also
1611   //             the ESD (TRD) tracks found in this SM. 
1612   //
1613   // Output :
1614   //   Number of tracks found in this TRD supermodule.
1615   // 
1616   // Detailed description
1617   //
1618   // 1. Unpack AliTRDpropagationLayers objects for each stack.
1619   // 2. Launch stack tracking. 
1620   //    See AliTRDtrackerV1::Clusters2TracksStack() for details.
1621   // 3. Pack results in the ESD event.
1622   //
1623   
1624   // allocate space for esd tracks in this SM
1625   TClonesArray esdTrackList("AliESDtrack", 2*kMaxTracksStack);
1626   esdTrackList.SetOwner();
1627   
1628   Int_t nTracks   = 0;
1629   Int_t nChambers = 0;
1630   AliTRDtrackingChamber **stack = 0x0, *chamber = 0x0;
1631   for(int istack = 0; istack<AliTRDgeometry::kNstack; istack++){
1632     if(!(stack = fTrSec[sector].GetStack(istack))) continue;
1633     nChambers = 0;
1634     for(int ilayer=0; ilayer<AliTRDgeometry::kNlayer; ilayer++){
1635       if(!(chamber = stack[ilayer])) continue;
1636       if(chamber->GetNClusters() < fgNTimeBins * AliTRDReconstructor::RecoParam()->GetFindableClusters()) continue;
1637       nChambers++;
1638       //AliInfo(Form("sector %d stack %d layer %d clusters %d", sector, istack, ilayer, chamber->GetNClusters()));
1639     }
1640     if(nChambers < 4) continue;
1641     //AliInfo(Form("Doing stack %d", istack));
1642     nTracks += Clusters2TracksStack(stack, &esdTrackList);
1643   }
1644   //AliInfo(Form("Found %d tracks in SM %d [%d]\n", nTracks, sector, esd->GetNumberOfTracks()));
1645   
1646   for(int itrack=0; itrack<nTracks; itrack++)
1647     esd->AddTrack((AliESDtrack*)esdTrackList[itrack]);
1648
1649   // Reset Track and Candidate Number
1650   AliTRDtrackerDebug::SetCandidateNumber(0);
1651   AliTRDtrackerDebug::SetTrackNumber(0);
1652   return nTracks;
1653 }
1654
1655 //____________________________________________________________________
1656 Int_t AliTRDtrackerV1::Clusters2TracksStack(AliTRDtrackingChamber **stack, TClonesArray *esdTrackList)
1657 {
1658   //
1659   // Make tracks in one TRD stack.
1660   //
1661   // Parameters :
1662   //   layer  : Array of stack propagation layers containing clusters
1663   //   esdTrackList  : Array of ESD tracks found by the stand alone tracker. 
1664   //                   On exit the tracks found in this stack are appended.
1665   //
1666   // Output :
1667   //   Number of tracks found in this stack.
1668   // 
1669   // Detailed description
1670   //
1671   // 1. Find the 3 most useful seeding chambers. See BuildSeedingConfigs() for details.
1672   // 2. Steer AliTRDtrackerV1::MakeSeeds() for 3 seeding layer configurations. 
1673   //    See AliTRDtrackerV1::MakeSeeds() for more details.
1674   // 3. Arrange track candidates in decreasing order of their quality
1675   // 4. Classify tracks in 5 categories according to:
1676   //    a) number of layers crossed
1677   //    b) track quality 
1678   // 5. Sign clusters by tracks in decreasing order of track quality
1679   // 6. Build AliTRDtrack out of seeding tracklets
1680   // 7. Cook MC label
1681   // 8. Build ESD track and register it to the output list
1682   //
1683
1684   AliTRDtrackingChamber *chamber = 0x0;
1685   AliTRDseedV1 sseed[kMaxTracksStack*6]; // to be initialized
1686   Int_t pars[4]; // MakeSeeds parameters
1687
1688   //Double_t alpha = AliTRDgeometry::GetAlpha();
1689   //Double_t shift = .5 * alpha;
1690   Int_t configs[kNConfigs];
1691   
1692   // Build initial seeding configurations
1693   Double_t quality = BuildSeedingConfigs(stack, configs);
1694   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() > 1){
1695     AliInfo(Form("Plane config %d %d %d Quality %f"
1696     , configs[0], configs[1], configs[2], quality));
1697   }
1698   
1699   // Initialize contors
1700   Int_t ntracks,      // number of TRD track candidates
1701     ntracks1,     // number of registered TRD tracks/iter
1702     ntracks2 = 0; // number of all registered TRD tracks in stack
1703   fSieveSeeding = 0;
1704   do{
1705     // Loop over seeding configurations
1706     ntracks = 0; ntracks1 = 0;
1707     for (Int_t iconf = 0; iconf<3; iconf++) {
1708       pars[0] = configs[iconf];
1709       pars[1] = ntracks;
1710       ntracks = MakeSeeds(stack, &sseed[6*ntracks], pars);
1711       if(ntracks == kMaxTracksStack) break;
1712     }
1713     if(AliTRDReconstructor::RecoParam()->GetStreamLevel() > 1) AliInfo(Form("Candidate TRD tracks %d in iteration %d.", ntracks, fSieveSeeding));
1714     
1715     if(!ntracks) break;
1716     
1717     // Sort the seeds according to their quality
1718     Int_t sort[kMaxTracksStack];
1719     TMath::Sort(ntracks, fTrackQuality, sort, kTRUE);
1720   
1721     // Initialize number of tracks so far and logic switches
1722     Int_t ntracks0 = esdTrackList->GetEntriesFast();
1723     Bool_t signedTrack[kMaxTracksStack];
1724     Bool_t fakeTrack[kMaxTracksStack];
1725     for (Int_t i=0; i<ntracks; i++){
1726       signedTrack[i] = kFALSE;
1727       fakeTrack[i] = kFALSE;
1728     }
1729     //AliInfo("Selecting track candidates ...");
1730     
1731     // Sieve clusters in decreasing order of track quality
1732     Double_t trackParams[7];
1733     //          AliTRDseedV1 *lseed = 0x0;
1734     Int_t jSieve = 0, candidates;
1735     do{
1736       //AliInfo(Form("\t\tITER = %i ", jSieve));
1737
1738       // Check track candidates
1739       candidates = 0;
1740       for (Int_t itrack = 0; itrack < ntracks; itrack++) {
1741   Int_t trackIndex = sort[itrack];
1742   if (signedTrack[trackIndex] || fakeTrack[trackIndex]) continue;
1743   
1744         
1745   // Calculate track parameters from tracklets seeds
1746   Int_t labelsall[1000];
1747   Int_t nlabelsall = 0;
1748   Int_t naccepted  = 0;
1749   Int_t ncl        = 0;
1750   Int_t nused      = 0;
1751   Int_t nlayers    = 0;
1752   Int_t findable   = 0;
1753   for (Int_t jLayer = 0; jLayer < kNPlanes; jLayer++) {
1754     Int_t jseed = kNPlanes*trackIndex+jLayer;
1755     if(!sseed[jseed].IsOK()) continue;
1756     if (TMath::Abs(sseed[jseed].GetYref(0) / sseed[jseed].GetX0()) < 0.15) findable++;
1757   
1758     sseed[jseed].UpdateUsed();
1759     ncl   += sseed[jseed].GetN2();
1760     nused += sseed[jseed].GetNUsed();
1761     nlayers++;
1762   
1763     // Cooking label
1764     for (Int_t itime = 0; itime < fgNTimeBins; itime++) {
1765       if(!sseed[jseed].IsUsable(itime)) continue;
1766       naccepted++;
1767       Int_t tindex = 0, ilab = 0;
1768       while(ilab<3 && (tindex = sseed[jseed].GetClusters(itime)->GetLabel(ilab)) >= 0){
1769         labelsall[nlabelsall++] = tindex;
1770         ilab++;
1771       }
1772     }
1773   }
1774   // Filter duplicated tracks
1775   if (nused > 30){
1776     //printf("Skip %d nused %d\n", trackIndex, nused);
1777     fakeTrack[trackIndex] = kTRUE;
1778     continue;
1779   }
1780   if (Float_t(nused)/ncl >= .25){
1781     //printf("Skip %d nused/ncl >= .25\n", trackIndex);
1782     fakeTrack[trackIndex] = kTRUE;
1783     continue;
1784   }
1785         
1786   // Classify tracks
1787   Bool_t skip = kFALSE;
1788   switch(jSieve){
1789   case 0:
1790     if(nlayers < 6) {skip = kTRUE; break;}
1791     if(TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -5.){skip = kTRUE; break;}
1792     break;
1793   
1794   case 1:
1795     if(nlayers < findable){skip = kTRUE; break;}
1796     if(TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -4.){skip = kTRUE; break;}
1797     break;
1798   
1799   case 2:
1800     if ((nlayers == findable) || (nlayers == 6)) { skip = kTRUE; break;}
1801     if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -6.0){skip = kTRUE; break;}
1802     break;
1803   
1804   case 3:
1805     if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) < -5.){skip = kTRUE; break;}
1806     break;
1807   
1808   case 4:
1809     if (nlayers == 3){skip = kTRUE; break;}
1810     //if (TMath::Log(1.E-9+fTrackQuality[trackIndex]) - nused/(nlayers-3.0) < -15.0){skip = kTRUE; break;}
1811     break;
1812   }
1813   if(skip){
1814     candidates++;
1815     //printf("REJECTED : %d [%d] nlayers %d trackQuality = %e nused %d\n", itrack, trackIndex, nlayers, fTrackQuality[trackIndex], nused);
1816     continue;
1817   }
1818   signedTrack[trackIndex] = kTRUE;
1819             
1820
1821   // Build track label - what happens if measured data ???
1822   Int_t labels[1000];
1823   Int_t outlab[1000];
1824   Int_t nlab = 0;
1825   for (Int_t iLayer = 0; iLayer < 6; iLayer++) {
1826     Int_t jseed = kNPlanes*trackIndex+iLayer;
1827     if(!sseed[jseed].IsOK()) continue;
1828     for(int ilab=0; ilab<2; ilab++){
1829       if(sseed[jseed].GetLabels(ilab) < 0) continue;
1830       labels[nlab] = sseed[jseed].GetLabels(ilab);
1831       nlab++;
1832     }
1833   }
1834   Freq(nlab,labels,outlab,kFALSE);
1835   Int_t   label     = outlab[0];
1836   Int_t   frequency = outlab[1];
1837   Freq(nlabelsall,labelsall,outlab,kFALSE);
1838   Int_t   label1    = outlab[0];
1839   Int_t   label2    = outlab[2];
1840   Float_t fakeratio = (naccepted - outlab[1]) / Float_t(naccepted);
1841   
1842         
1843   // Sign clusters
1844   AliTRDcluster *cl = 0x0; Int_t clusterIndex = -1;
1845   for (Int_t jLayer = 0; jLayer < 6; jLayer++) {
1846     Int_t jseed = kNPlanes*trackIndex+jLayer;
1847     if(!sseed[jseed].IsOK()) continue;
1848     if(TMath::Abs(sseed[jseed].GetYfit(1) - sseed[jseed].GetYfit(1)) >= .2) continue; // check this condition with Marian
1849     sseed[jseed].UseClusters();
1850     if(!cl){
1851       Int_t ic = 0;
1852       while(!(cl = sseed[jseed].GetClusters(ic))) ic++;
1853       clusterIndex =  sseed[jseed].GetIndexes(ic);
1854     }
1855   }
1856   if(!cl) continue;
1857
1858         
1859   // Build track parameters
1860   AliTRDseedV1 *lseed =&sseed[trackIndex*6];
1861   Int_t idx = 0;
1862   while(idx<3 && !lseed->IsOK()) {
1863     idx++;
1864     lseed++;
1865   }
1866   Double_t cR = lseed->GetC();
1867   Double_t x = lseed->GetX0() - 3.5;
1868   trackParams[0] = x; //NEW AB
1869   trackParams[1] = lseed->GetYat(x);//lseed->GetYref(0);
1870   trackParams[2] = lseed->GetZat(x);//lseed->GetZref(0);
1871   trackParams[3] = lseed->GetX0() * cR - TMath::Sin(TMath::ATan(lseed->GetYref(1)));
1872   trackParams[4] = lseed->GetZref(1) / TMath::Sqrt(1. + lseed->GetYref(1) * lseed->GetYref(1));
1873   trackParams[5] = cR;
1874   Int_t ich = 0; while(!(chamber = stack[ich])) ich++;
1875   trackParams[6] = fGeom->GetSector(chamber->GetDetector());/* *alpha+shift;    // Supermodule*/
1876
1877   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() > 1){
1878     AliInfo(Form("Track %d [%d] nlayers %d trackQuality = %e nused %d, yref = %3.3f", itrack, trackIndex, nlayers, fTrackQuality[trackIndex], nused, trackParams[1]));
1879           
1880     Int_t nclusters = 0;
1881     AliTRDseedV1 *dseed[6];
1882     for(int is=0; is<6; is++){
1883       dseed[is] = new AliTRDseedV1(sseed[trackIndex*6+is]);
1884       dseed[is]->SetOwner();
1885       nclusters += sseed[is].GetN2();
1886     }
1887     //Int_t eventNrInFile = esd->GetEventNumberInFile();
1888     //AliInfo(Form("Number of clusters %d.", nclusters));
1889     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
1890     Int_t trackNumber = AliTRDtrackerDebug::GetTrackNumber();
1891     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
1892     TTreeSRedirector &cstreamer = *fgDebugStreamer;
1893     cstreamer << "Clusters2TracksStack"
1894         << "EventNumber="               << eventNumber
1895         << "TrackNumber="               << trackNumber
1896         << "CandidateNumber="   << candidateNumber
1897         << "Iter="                              << fSieveSeeding
1898         << "Like="                              << fTrackQuality[trackIndex]
1899         << "S0.="                               << dseed[0]
1900         << "S1.="                               << dseed[1]
1901         << "S2.="                               << dseed[2]
1902         << "S3.="                               << dseed[3]
1903         << "S4.="                               << dseed[4]
1904         << "S5.="                               << dseed[5]
1905         << "p0="                                << trackParams[0]
1906         << "p1="                                << trackParams[1]
1907         << "p2="                                << trackParams[2]
1908         << "p3="                                << trackParams[3]
1909         << "p4="                                << trackParams[4]
1910         << "p5="                                << trackParams[5]
1911         << "p6="                                << trackParams[6]
1912         << "Label="                             << label
1913         << "Label1="                    << label1
1914         << "Label2="                    << label2
1915         << "FakeRatio="                 << fakeratio
1916         << "Freq="                              << frequency
1917         << "Ncl="                               << ncl
1918         << "NLayers="                   << nlayers
1919         << "Findable="                  << findable
1920
1921         << "NUsed="                             << nused
1922         << "\n";
1923   }
1924       
1925   AliTRDtrackV1 *track = MakeTrack(&sseed[trackIndex*kNPlanes], trackParams);
1926   if(!track){
1927     AliWarning("Fail to build a TRD Track.");
1928     continue;
1929   }
1930   //AliInfo("End of MakeTrack()");
1931   AliESDtrack esdTrack;
1932   esdTrack.UpdateTrackParams(track, AliESDtrack::kTRDout);
1933   esdTrack.SetLabel(track->GetLabel());
1934   track->UpdateESDtrack(&esdTrack);
1935   // write ESD-friends if neccessary
1936   if (AliTRDReconstructor::RecoParam()->GetStreamLevel() > 0){
1937     //printf("Creating Calibrations Object\n");
1938     AliTRDtrackV1 *calibTrack = new AliTRDtrackV1(*track);
1939     calibTrack->SetOwner();
1940     esdTrack.AddCalibObject(calibTrack);
1941   }
1942   new ((*esdTrackList)[ntracks0++]) AliESDtrack(esdTrack);
1943   ntracks1++;
1944   AliTRDtrackerDebug::SetTrackNumber(AliTRDtrackerDebug::GetTrackNumber() + 1);
1945       }
1946
1947       jSieve++;
1948     } while(jSieve<5 && candidates); // end track candidates sieve
1949     if(!ntracks1) break;
1950
1951     // increment counters
1952     ntracks2 += ntracks1;
1953     fSieveSeeding++;
1954
1955     // Rebuild plane configurations and indices taking only unused clusters into account
1956     quality = BuildSeedingConfigs(stack, configs);
1957     if(quality < 1.E-7) break; //AliTRDReconstructor::RecoParam()->GetPlaneQualityThreshold()) break;
1958     
1959     for(Int_t ip = 0; ip < kNPlanes; ip++){ 
1960       if(!(chamber = stack[ip])) continue;
1961       chamber->Build(fGeom);//Indices(fSieveSeeding);
1962     }
1963
1964     if(AliTRDReconstructor::RecoParam()->GetStreamLevel() > 1){ 
1965       AliInfo(Form("Sieve level %d Plane config %d %d %d Quality %f", fSieveSeeding, configs[0], configs[1], configs[2], quality));
1966     }
1967   } while(fSieveSeeding<10); // end stack clusters sieve
1968   
1969
1970
1971   //AliInfo(Form("Registered TRD tracks %d in stack %d.", ntracks2, pars[1]));
1972
1973   return ntracks2;
1974 }
1975
1976 //___________________________________________________________________
1977 Double_t AliTRDtrackerV1::BuildSeedingConfigs(AliTRDtrackingChamber **stack, Int_t *configs)
1978 {
1979   //
1980   // Assign probabilities to chambers according to their
1981   // capability of producing seeds.
1982   // 
1983   // Parameters :
1984   //
1985   //   layers : Array of stack propagation layers for all 6 chambers in one stack
1986   //   configs : On exit array of configuration indexes (see GetSeedingConfig()
1987   // for details) in the decreasing order of their seeding probabilities. 
1988   //
1989   // Output :
1990   //
1991   //  Return top configuration quality 
1992   //
1993   // Detailed description:
1994   //
1995   // To each chamber seeding configuration (see GetSeedingConfig() for
1996   // the list of all configurations) one defines 2 quality factors:
1997   //  - an apriori topological quality (see GetSeedingConfig() for details) and
1998   //  - a data quality based on the uniformity of the distribution of
1999   //    clusters over the x range (time bins population). See CookChamberQA() for details.
2000   // The overall chamber quality is given by the product of this 2 contributions.
2001   // 
2002
2003   Double_t chamberQ[kNPlanes];
2004   AliTRDtrackingChamber *chamber = 0x0;
2005   for(int iplane=0; iplane<kNPlanes; iplane++){
2006     if(!(chamber = stack[iplane])) continue;
2007     chamberQ[iplane] = (chamber = stack[iplane]) ?  chamber->GetQuality() : 0.;
2008   }
2009
2010   Double_t tconfig[kNConfigs];
2011   Int_t planes[4];
2012   for(int iconf=0; iconf<kNConfigs; iconf++){
2013     GetSeedingConfig(iconf, planes);
2014     tconfig[iconf] = fgTopologicQA[iconf];
2015     for(int iplane=0; iplane<4; iplane++) tconfig[iconf] *= chamberQ[planes[iplane]]; 
2016   }
2017   
2018   TMath::Sort((Int_t)kNConfigs, tconfig, configs, kTRUE);
2019   //    AliInfo(Form("q[%d] = %f", configs[0], tconfig[configs[0]]));
2020   //    AliInfo(Form("q[%d] = %f", configs[1], tconfig[configs[1]]));
2021   //    AliInfo(Form("q[%d] = %f", configs[2], tconfig[configs[2]]));
2022   
2023   return tconfig[configs[0]];
2024 }
2025
2026 //____________________________________________________________________
2027 Int_t AliTRDtrackerV1::MakeSeeds(AliTRDtrackingChamber **stack, AliTRDseedV1 *sseed, Int_t *ipar)
2028 {
2029   //
2030   // Make tracklet seeds in the TRD stack.
2031   //
2032   // Parameters :
2033   //   layers : Array of stack propagation layers containing clusters
2034   //   sseed  : Array of empty tracklet seeds. On exit they are filled.
2035   //   ipar   : Control parameters:
2036   //       ipar[0] -> seeding chambers configuration
2037   //       ipar[1] -> stack index
2038   //       ipar[2] -> number of track candidates found so far
2039   //
2040   // Output :
2041   //   Number of tracks candidates found.
2042   // 
2043   // Detailed description
2044   //
2045   // The following steps are performed:
2046   // 1. Select seeding layers from seeding chambers
2047   // 2. Select seeding clusters from the seeding AliTRDpropagationLayerStack.
2048   //   The clusters are taken from layer 3, layer 0, layer 1 and layer 2, in
2049   //   this order. The parameters controling the range of accepted clusters in
2050   //   layer 0, 1, and 2 are defined in AliTRDchamberTimeBin::BuildCond().
2051   // 3. Helix fit of the cluster set. (see AliTRDtrackerFitter::FitRieman(AliTRDcluster**))
2052   // 4. Initialize seeding tracklets in the seeding chambers.
2053   // 5. Filter 0.
2054   //   Chi2 in the Y direction less than threshold ... (1./(3. - sLayer))
2055   //   Chi2 in the Z direction less than threshold ... (1./(3. - sLayer))
2056   // 6. Attach clusters to seeding tracklets and find linear approximation of
2057   //   the tracklet (see AliTRDseedV1::AttachClustersIter()). The number of used
2058   //   clusters used by current seeds should not exceed ... (25).
2059   // 7. Filter 1.
2060   //   All 4 seeding tracklets should be correctly constructed (see
2061   //   AliTRDseedV1::AttachClustersIter())
2062   // 8. Helix fit of the seeding tracklets
2063   // 9. Filter 2.
2064   //   Likelihood calculation of the fit. (See AliTRDtrackerV1::CookLikelihood() for details)
2065   // 10. Extrapolation of the helix fit to the other 2 chambers:
2066   //    a) Initialization of extrapolation tracklet with fit parameters
2067   //    b) Helix fit of tracklets
2068   //    c) Attach clusters and linear interpolation to extrapolated tracklets
2069   //    d) Helix fit of tracklets
2070   // 11. Improve seeding tracklets quality by reassigning clusters.
2071   //      See AliTRDtrackerV1::ImproveSeedQuality() for details.
2072   // 12. Helix fit of all 6 seeding tracklets and chi2 calculation
2073   // 13. Hyperplane fit and track quality calculation. See AliTRDtrackerFitter::FitHyperplane() for details.
2074   // 14. Cooking labels for tracklets. Should be done only for MC
2075   // 15. Register seeds.
2076   //
2077
2078   AliTRDtrackingChamber *chamber = 0x0;
2079   AliTRDcluster *c[4] = {0x0, 0x0, 0x0, 0x0}; // initilize seeding clusters
2080   AliTRDseedV1 *cseed = &sseed[0]; // initialize tracklets for first track
2081   Int_t ncl, mcl; // working variable for looping over clusters
2082   Int_t index[AliTRDchamberTimeBin::kMaxClustersLayer], jndex[AliTRDchamberTimeBin::kMaxClustersLayer];
2083   // chi2 storage
2084   // chi2[0] = tracklet chi2 on the Z direction
2085   // chi2[1] = tracklet chi2 on the R direction
2086   Double_t chi2[4];
2087
2088
2089   // this should be data member of AliTRDtrack
2090   Double_t seedQuality[kMaxTracksStack];
2091   
2092   // unpack control parameters
2093   Int_t config  = ipar[0];
2094   Int_t ntracks = ipar[1];
2095   Int_t planes[kNSeedPlanes]; GetSeedingConfig(config, planes); 
2096   
2097   // Init chambers geometry
2098   Int_t ic = 0; while(!(chamber = stack[ic])) ic++;
2099   Int_t istack = fGeom->GetStack(chamber->GetDetector());
2100   Double_t hL[kNPlanes];       // Tilting angle
2101   Float_t padlength[kNPlanes]; // pad lenghts
2102   AliTRDpadPlane *pp = 0x0;
2103   for(int iplane=0; iplane<kNPlanes; iplane++){
2104     pp                = fGeom->GetPadPlane(iplane, istack);
2105     hL[iplane]        = TMath::Tan(-TMath::DegToRad()*pp->GetTiltingAngle());
2106     padlength[iplane] = pp->GetLengthIPad();
2107   }
2108   
2109   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() > 1){
2110     AliInfo(Form("Making seeds Stack[%d] Config[%d] Tracks[%d]...", istack, config, ntracks));
2111   }
2112
2113   Int_t nlayers = 0;
2114   AliTRDchamberTimeBin *layer[] = {0x0, 0x0, 0x0, 0x0};
2115   for(int isl=0; isl<kNSeedPlanes; isl++){ 
2116     if(!(chamber = stack[planes[isl]])) continue;
2117     if(!(layer[isl] = chamber->GetSeedingLayer(fGeom))) continue;
2118     nlayers++;
2119     //AliInfo(Form("seeding plane %d clusters %d", planes[isl], Int_t(*layer[isl])));
2120   }
2121   if(nlayers < 4) return 0;
2122   
2123   
2124   // Start finding seeds
2125   Double_t cond0[4], cond1[4], cond2[4];
2126   Int_t icl = 0;
2127   while((c[3] = (*layer[3])[icl++])){
2128     if(!c[3]) continue;
2129     layer[0]->BuildCond(c[3], cond0, 0);
2130     layer[0]->GetClusters(cond0, index, ncl);
2131     //printf("Found c[3] candidates 0 %d\n", ncl);
2132     Int_t jcl = 0;
2133     while(jcl<ncl) {
2134       c[0] = (*layer[0])[index[jcl++]];
2135       if(!c[0]) continue;
2136       Double_t dx    = c[3]->GetX() - c[0]->GetX();
2137       Double_t theta = (c[3]->GetZ() - c[0]->GetZ())/dx;
2138       Double_t phi   = (c[3]->GetY() - c[0]->GetY())/dx;
2139       layer[1]->BuildCond(c[0], cond1, 1, theta, phi);
2140       layer[1]->GetClusters(cond1, jndex, mcl);
2141       //printf("Found c[0] candidates 1 %d\n", mcl);
2142
2143       Int_t kcl = 0;
2144       while(kcl<mcl) {
2145   c[1] = (*layer[1])[jndex[kcl++]];
2146   if(!c[1]) continue;
2147   layer[2]->BuildCond(c[1], cond2, 2, theta, phi);
2148   c[2] = layer[2]->GetNearestCluster(cond2);
2149   //printf("Found c[1] candidate 2 %p\n", c[2]);
2150   if(!c[2]) continue;
2151         
2152   //                            AliInfo("Seeding clusters found. Building seeds ...");
2153   //                            for(Int_t i = 0; i < kNSeedPlanes; i++) printf("%i. coordinates: x = %6.3f, y = %6.3f, z = %6.3f\n", i, c[i]->GetX(), c[i]->GetY(), c[i]->GetZ());
2154         
2155   for (Int_t il = 0; il < 6; il++) cseed[il].Reset();
2156
2157   FitRieman(c, chi2);
2158
2159   AliTRDseedV1 *tseed = 0x0;
2160   for(int iLayer=0; iLayer<kNSeedPlanes; iLayer++){
2161     Int_t jLayer = planes[iLayer];
2162     tseed = &cseed[jLayer];
2163     tseed->SetPlane(jLayer);
2164     tseed->SetTilt(hL[jLayer]);
2165     tseed->SetPadLength(padlength[jLayer]);
2166     tseed->SetX0(stack[jLayer]->GetX());
2167     tseed->Init(GetRiemanFitter());
2168   }
2169
2170   Bool_t isFake = kFALSE;
2171   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() >= 2){
2172     if (c[0]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
2173     if (c[1]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
2174     if (c[2]->GetLabel(0) != c[3]->GetLabel(0)) isFake = kTRUE;
2175
2176     Double_t xpos[4];
2177     for(Int_t l = 0; l < kNSeedPlanes; l++) xpos[l] = layer[l]->GetX();
2178     Float_t yref[4];
2179     for(int il=0; il<4; il++) yref[il] = cseed[planes[il]].GetYref(0);
2180     Int_t ll = c[3]->GetLabel(0);
2181     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2182     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2183     AliRieman *rim = GetRiemanFitter();
2184     TTreeSRedirector &cs0 = *fgDebugStreamer;
2185     cs0 << "MakeSeeds0"
2186         <<"EventNumber="                << eventNumber
2187         <<"CandidateNumber="    << candidateNumber
2188         <<"isFake="                             << isFake
2189         <<"config="                             << config
2190         <<"label="                              << ll
2191         <<"chi2z="                              << chi2[0]
2192         <<"chi2y="                              << chi2[1]
2193         <<"Y2exp="                              << cond2[0]     
2194         <<"Z2exp="                              << cond2[1]
2195         <<"X0="                                 << xpos[0] //layer[sLayer]->GetX()
2196         <<"X1="                                 << xpos[1] //layer[sLayer + 1]->GetX()
2197         <<"X2="                                 << xpos[2] //layer[sLayer + 2]->GetX()
2198         <<"X3="                                 << xpos[3] //layer[sLayer + 3]->GetX()
2199         <<"yref0="                              << yref[0]
2200         <<"yref1="                              << yref[1]
2201         <<"yref2="                              << yref[2]
2202         <<"yref3="                              << yref[3]
2203         <<"c0.="                                << c[0]
2204         <<"c1.="                                << c[1]
2205         <<"c2.="                                << c[2]
2206         <<"c3.="                                << c[3]
2207         <<"Seed0.="                             << &cseed[planes[0]]
2208         <<"Seed1.="                             << &cseed[planes[1]]
2209         <<"Seed2.="                             << &cseed[planes[2]]
2210         <<"Seed3.="                             << &cseed[planes[3]]
2211         <<"RiemanFitter.="              << rim
2212         <<"\n";
2213   }
2214
2215   if(chi2[0] > AliTRDReconstructor::RecoParam()->GetChi2Z()/*7./(3. - sLayer)*//*iter*/){
2216     //AliInfo(Form("Failed chi2 filter on chi2Z [%f].", chi2[0]));
2217     AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2218     continue;
2219   }
2220   if(chi2[1] > AliTRDReconstructor::RecoParam()->GetChi2Y()/*1./(3. - sLayer)*//*iter*/){
2221     //AliInfo(Form("Failed chi2 filter on chi2Y [%f].", chi2[1]));
2222     AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2223     continue;
2224   }
2225   //AliInfo("Passed chi2 filter.");
2226
2227   // try attaching clusters to tracklets
2228   Int_t nUsedCl = 0;
2229   Int_t mlayers = 0;
2230   for(int iLayer=0; iLayer<kNSeedPlanes; iLayer++){
2231     Int_t jLayer = planes[iLayer];
2232     if(!cseed[jLayer].AttachClustersIter(stack[jLayer], 5., kFALSE, c[iLayer])) continue;
2233     nUsedCl += cseed[jLayer].GetNUsed();
2234     if(nUsedCl > 25) break;
2235     mlayers++;
2236   }
2237   if(mlayers < kNSeedPlanes){ 
2238     //AliInfo(Form("Failed updating all seeds %d [%d].", mlayers, kNSeedPlanes));
2239     AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2240     continue;
2241   }
2242   // fit tracklets and cook likelihood
2243   FitTiltedRieman(&cseed[0], kTRUE);// Update Seeds and calculate Likelihood
2244   chi2[0] = GetChi2Y(&cseed[0]);
2245   chi2[1] = GetChi2Z(&cseed[0]);
2246   //Chi2 definitions in testing stage
2247   //chi2[0] = GetChi2YTest(&cseed[0]);
2248   //chi2[1] = GetChi2ZTest(&cseed[0]);
2249   Double_t like = CookLikelihood(&cseed[0], planes, chi2); // to be checked
2250
2251   if (TMath::Log(1.E-9 + like) < AliTRDReconstructor::RecoParam()->GetTrackLikelihood()){
2252     //AliInfo(Form("Failed likelihood %f[%e].", TMath::Log(1.E-9 + like), like));
2253     AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2254     continue;
2255   }
2256   //AliInfo(Form("Passed likelihood %f[%e].", TMath::Log(1.E-9 + like), like));
2257
2258   // book preliminary results
2259   seedQuality[ntracks] = like;
2260   fSeedLayer[ntracks]  = config;/*sLayer;*/
2261
2262   // attach clusters to the extrapolation seeds
2263   Int_t lextrap[2];
2264   GetExtrapolationConfig(config, lextrap);
2265   Int_t nusedf   = 0; // debug value
2266   for(int iLayer=0; iLayer<2; iLayer++){
2267     Int_t jLayer = lextrap[iLayer];
2268     if(!(chamber = stack[jLayer])) continue;
2269             
2270     // prepare extrapolated seed
2271     cseed[jLayer].Reset();
2272     cseed[jLayer].SetPlane(jLayer);
2273     cseed[jLayer].SetTilt(hL[jLayer]);
2274     cseed[jLayer].SetX0(chamber->GetX());
2275     cseed[jLayer].SetPadLength(padlength[jLayer]);
2276
2277     // fit extrapolated seed
2278     if ((jLayer == 0) && !(cseed[1].IsOK())) continue;
2279     if ((jLayer == 5) && !(cseed[4].IsOK())) continue;
2280     AliTRDseedV1 pseed = cseed[jLayer];
2281     if(!pseed.AttachClustersIter(chamber, 1000.)) continue;
2282     cseed[jLayer] = pseed;
2283     nusedf += cseed[jLayer].GetNUsed(); // debug value
2284     FitTiltedRieman(cseed,  kTRUE);
2285   }
2286
2287   // AliInfo("Extrapolation done.");
2288   // Debug Stream containing all the 6 tracklets
2289   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() >= 2){
2290     TTreeSRedirector &cstreamer = *fgDebugStreamer;
2291     TLinearFitter *tiltedRieman = GetTiltedRiemanFitter();
2292     Int_t eventNumber           = AliTRDtrackerDebug::GetEventNumber();
2293     Int_t candidateNumber       = AliTRDtrackerDebug::GetCandidateNumber();
2294     cstreamer << "MakeSeeds1"
2295         << "EventNumber="               << eventNumber
2296         << "CandidateNumber="   << candidateNumber
2297         << "S0.="                               << &cseed[0]
2298         << "S1.="                               << &cseed[1]
2299         << "S2.="                               << &cseed[2]
2300         << "S3.="                               << &cseed[3]
2301         << "S4.="                               << &cseed[4]
2302         << "S5.="                               << &cseed[5]
2303         << "FitterT.="                  << tiltedRieman
2304         << "\n";
2305   }
2306         
2307   if(ImproveSeedQuality(stack, cseed) < 4){
2308     AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2309     continue;
2310   }
2311   //AliInfo("Improve seed quality done.");
2312
2313   // fit full track and cook likelihoods
2314   //                            Double_t curv = FitRieman(&cseed[0], chi2);
2315   //                            Double_t chi2ZF = chi2[0] / TMath::Max((mlayers - 3.), 1.);
2316   //                            Double_t chi2RF = chi2[1] / TMath::Max((mlayers - 3.), 1.);
2317
2318   // do the final track fitting (Once with vertex constraint and once without vertex constraint)
2319   Double_t chi2Vals[3];
2320   chi2Vals[0] = FitTiltedRieman(&cseed[0], kFALSE);
2321   if(AliTRDReconstructor::RecoParam()->IsVertexConstrained())
2322         chi2Vals[1] = FitTiltedRiemanConstraint(&cseed[0], GetZ()); // Do Vertex Constrained fit if desired
2323   else
2324         chi2Vals[1] = 1.;
2325   chi2Vals[2] = GetChi2Z(&cseed[0]) / TMath::Max((mlayers - 3.), 1.);
2326   // Chi2 definitions in testing stage
2327   //chi2Vals[2] = GetChi2ZTest(&cseed[0]);
2328   fTrackQuality[ntracks] = CalculateTrackLikelihood(&cseed[0], &chi2Vals[0]);
2329   //AliInfo("Hyperplane fit done\n");
2330
2331   // finalize tracklets
2332   Int_t labels[12];
2333   Int_t outlab[24];
2334   Int_t nlab = 0;
2335   for (Int_t iLayer = 0; iLayer < 6; iLayer++) {
2336     if (!cseed[iLayer].IsOK()) continue;
2337
2338     if (cseed[iLayer].GetLabels(0) >= 0) {
2339       labels[nlab] = cseed[iLayer].GetLabels(0);
2340       nlab++;
2341     }
2342
2343     if (cseed[iLayer].GetLabels(1) >= 0) {
2344       labels[nlab] = cseed[iLayer].GetLabels(1);
2345       nlab++;
2346     }
2347   }
2348   Freq(nlab,labels,outlab,kFALSE);
2349   Int_t label     = outlab[0];
2350   Int_t frequency = outlab[1];
2351   for (Int_t iLayer = 0; iLayer < 6; iLayer++) {
2352     cseed[iLayer].SetFreq(frequency);
2353     cseed[iLayer].SetChi2Z(chi2[1]);
2354   }
2355       
2356   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() >= 2){
2357     TTreeSRedirector &cstreamer = *fgDebugStreamer;
2358     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2359     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2360     TLinearFitter *fitterTC = GetTiltedRiemanFitterConstraint();
2361     TLinearFitter *fitterT = GetTiltedRiemanFitter();
2362     cstreamer << "MakeSeeds2"
2363         << "EventNumber="               << eventNumber
2364         << "CandidateNumber="   << candidateNumber
2365         << "Chi2TR="                    << chi2Vals[0]
2366         << "Chi2TC="                    << chi2Vals[1]
2367         << "Nlayers="                   << mlayers
2368         << "NUsedS="                    << nUsedCl
2369         << "NUsed="                             << nusedf
2370         << "Like="                              << like
2371         << "S0.="                               << &cseed[0]
2372         << "S1.="                               << &cseed[1]
2373         << "S2.="                               << &cseed[2]
2374         << "S3.="                               << &cseed[3]
2375         << "S4.="                               << &cseed[4]
2376         << "S5.="                               << &cseed[5]
2377         << "Label="                             << label
2378         << "Freq="                              << frequency
2379         << "FitterT.="                  << fitterT
2380         << "FitterTC.="                 << fitterTC
2381         << "\n";
2382   }
2383         
2384   ntracks++;
2385   AliTRDtrackerDebug::SetCandidateNumber(AliTRDtrackerDebug::GetCandidateNumber() + 1);
2386   if(ntracks == kMaxTracksStack){
2387     AliWarning(Form("Number of seeds reached maximum allowed (%d) in stack.", kMaxTracksStack));
2388     for(int isl=0; isl<4; isl++) delete layer[isl];
2389     return ntracks;
2390   }
2391   cseed += 6;
2392       }
2393     }
2394   }
2395   for(int isl=0; isl<4; isl++) delete layer[isl];
2396   
2397   return ntracks;
2398 }
2399
2400 //_____________________________________________________________________________
2401 AliTRDtrackV1* AliTRDtrackerV1::MakeTrack(AliTRDseedV1 *seeds, Double_t *params)
2402 {
2403   //
2404   // Build a TRD track out of tracklet candidates
2405   //
2406   // Parameters :
2407   //   seeds  : array of tracklets
2408   //   params : track parameters (see MakeSeeds() function body for a detailed description)
2409   //
2410   // Output :
2411   //   The TRD track.
2412   //
2413   // Detailed description
2414   //
2415   // To be discussed with Marian !!
2416   //
2417
2418   AliTRDCalibraFillHisto *calibra = AliTRDCalibraFillHisto::Instance();
2419   if (!calibra) AliInfo("Could not get Calibra instance\n");
2420
2421   Double_t alpha = AliTRDgeometry::GetAlpha();
2422   Double_t shift = AliTRDgeometry::GetAlpha()/2.0;
2423   Double_t c[15];
2424
2425   c[ 0] = 0.2;
2426   c[ 1] = 0.0; c[ 2] = 2.0;
2427   c[ 3] = 0.0; c[ 4] = 0.0; c[ 5] = 0.02;
2428   c[ 6] = 0.0; c[ 7] = 0.0; c[ 8] = 0.0;  c[ 9] = 0.1;
2429   c[10] = 0.0; c[11] = 0.0; c[12] = 0.0;  c[13] = 0.0; c[14] = params[5]*params[5]*0.01;
2430
2431   AliTRDtrackV1 track(seeds, &params[1], c, params[0], params[6]*alpha+shift);
2432   track.PropagateTo(params[0]-5.0);
2433   track.ResetCovariance(1);
2434   Int_t nc = FollowBackProlongation(track);
2435   if (nc < 30) return 0x0;
2436
2437   AliTRDtrackV1 *ptrTrack = SetTrack(&track);
2438   ptrTrack->CookLabel(.9);
2439   // computes PID for track
2440   ptrTrack->CookPID();
2441   // update calibration references using this track
2442   if(calibra->GetHisto2d()) calibra->UpdateHistogramsV1(ptrTrack);
2443
2444   return ptrTrack;
2445 }
2446
2447
2448 //____________________________________________________________________
2449 Int_t AliTRDtrackerV1::ImproveSeedQuality(AliTRDtrackingChamber **stack, AliTRDseedV1 *cseed)
2450 {
2451   //
2452   // Sort tracklets according to "quality" and try to "improve" the first 4 worst
2453   //
2454   // Parameters :
2455   //  layers : Array of propagation layers for a stack/supermodule
2456   //  cseed  : Array of 6 seeding tracklets which has to be improved
2457   // 
2458   // Output :
2459   //   cssed : Improved seeds
2460   // 
2461   // Detailed description
2462   //
2463   // Iterative procedure in which new clusters are searched for each
2464   // tracklet seed such that the seed quality (see AliTRDseed::GetQuality())
2465   // can be maximized. If some optimization is found the old seeds are replaced.
2466   //
2467   // debug level: 7
2468   //
2469   
2470   // make a local working copy
2471   AliTRDtrackingChamber *chamber = 0x0;
2472   AliTRDseedV1 bseed[6];
2473   Int_t nLayers = 0;
2474   for (Int_t jLayer = 0; jLayer < 6; jLayer++) bseed[jLayer] = cseed[jLayer];
2475   
2476   Float_t lastquality = 10000.0;
2477   Float_t lastchi2    = 10000.0;
2478   Float_t chi2        =  1000.0;
2479
2480   for (Int_t iter = 0; iter < 4; iter++) {
2481     Float_t sumquality = 0.0;
2482     Float_t squality[6];
2483     Int_t   sortindexes[6];
2484
2485     for (Int_t jLayer = 0; jLayer < 6; jLayer++) {
2486       squality[jLayer]  = bseed[jLayer].IsOK() ? bseed[jLayer].GetQuality(kTRUE) : -1.;
2487       sumquality += squality[jLayer];
2488     }
2489     if ((sumquality >= lastquality) || (chi2       >     lastchi2)) break;
2490
2491     nLayers = 0;
2492     lastquality = sumquality;
2493     lastchi2    = chi2;
2494     if (iter > 0) for (Int_t jLayer = 0; jLayer < 6; jLayer++) cseed[jLayer] = bseed[jLayer];
2495
2496     TMath::Sort(6, squality, sortindexes, kFALSE);
2497     for (Int_t jLayer = 5; jLayer > 1; jLayer--) {
2498       Int_t bLayer = sortindexes[jLayer];
2499       if(!(chamber = stack[bLayer])) continue;
2500       bseed[bLayer].AttachClustersIter(chamber, squality[bLayer], kTRUE);
2501       if(bseed[bLayer].IsOK()) nLayers++;
2502     }
2503
2504     chi2 = FitTiltedRieman(bseed, kTRUE);
2505     if(AliTRDReconstructor::RecoParam()->GetStreamLevel() >= 7){
2506       Int_t eventNumber                 = AliTRDtrackerDebug::GetEventNumber();
2507       Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2508       TLinearFitter *tiltedRieman = GetTiltedRiemanFitter();
2509       TTreeSRedirector &cstreamer = *fgDebugStreamer;
2510       cstreamer << "ImproveSeedQuality"
2511     << "EventNumber="           << eventNumber
2512     << "CandidateNumber="       << candidateNumber
2513     << "Iteration="                             << iter
2514     << "S0.="                                                   << &bseed[0]
2515     << "S1.="                                                   << &bseed[1]
2516     << "S2.="                                                   << &bseed[2]
2517     << "S3.="                                                   << &bseed[3]
2518     << "S4.="                                                   << &bseed[4]
2519     << "S5.="                                                   << &bseed[5]
2520     << "FitterT.="                              << tiltedRieman
2521     << "\n";
2522     }
2523   } // Loop: iter
2524   
2525   // we are sure that at least 2 tracklets are OK !
2526   return nLayers+2;
2527 }
2528
2529 //_________________________________________________________________________
2530 Double_t AliTRDtrackerV1::CalculateTrackLikelihood(AliTRDseedV1 *tracklets, Double_t *chi2){
2531   //
2532   // Calculates the Track Likelihood value. This parameter serves as main quality criterion for 
2533   // the track selection
2534   // The likelihood value containes:
2535   //    - The chi2 values from the both fitters and the chi2 values in z-direction from a linear fit
2536   //    - The Sum of the Parameter  |slope_ref - slope_fit|/Sigma of the tracklets
2537   // For all Parameters an exponential dependency is used
2538   //
2539   // Parameters: - Array of tracklets (AliTRDseedV1) related to the track candidate
2540   //             - Array of chi2 values: 
2541   //                 * Non-Constrained Tilted Riemann fit
2542   //                 * Vertex-Constrained Tilted Riemann fit
2543   //                 * z-Direction from Linear fit
2544   // Output:     - The calculated track likelihood
2545   //
2546   // debug level 2
2547   //
2548
2549   Double_t sumdaf = 0, nLayers = 0;
2550   for (Int_t iLayer = 0; iLayer < kNPlanes; iLayer++) {
2551     if(!tracklets[iLayer].IsOK()) continue;
2552     sumdaf += TMath::Abs((tracklets[iLayer].GetYfit(1) - tracklets[iLayer].GetYref(1))/ tracklets[iLayer].GetSigmaY2());
2553     nLayers++;
2554   }
2555   sumdaf /= Float_t (nLayers - 2.0);
2556   
2557   Double_t likeChi2Z  = TMath::Exp(-chi2[2] * 0.14);                    // Chi2Z 
2558   Double_t likeChi2TC = (AliTRDReconstructor::RecoParam()->IsVertexConstrained()) ? 
2559                                                                                         TMath::Exp(-chi2[1] * 0.677) : 1;                       // Constrained Tilted Riemann
2560   Double_t likeChi2TR = TMath::Exp(-chi2[0] * 0.78);                    // Non-constrained Tilted Riemann
2561   Double_t likeAF     = TMath::Exp(-sumdaf * 3.23);
2562   Double_t trackLikelihood     = likeChi2Z * likeChi2TR * likeAF;
2563
2564   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() >= 2){
2565     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2566     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2567     TTreeSRedirector &cstreamer = *fgDebugStreamer;
2568     cstreamer << "CalculateTrackLikelihood0"
2569         << "EventNumber="                       << eventNumber
2570         << "CandidateNumber="   << candidateNumber
2571         << "LikeChi2Z="                         << likeChi2Z
2572         << "LikeChi2TR="                        << likeChi2TR
2573         << "LikeChi2TC="                        << likeChi2TC
2574         << "LikeAF="                                    << likeAF
2575         << "TrackLikelihood=" << trackLikelihood
2576         << "\n";
2577   }
2578
2579   return trackLikelihood;
2580 }
2581
2582 //____________________________________________________________________
2583 Double_t AliTRDtrackerV1::CookLikelihood(AliTRDseedV1 *cseed, Int_t planes[4]
2584           , Double_t *chi2)
2585 {
2586   //
2587   // Calculate the probability of this track candidate.
2588   //
2589   // Parameters :
2590   //   cseeds : array of candidate tracklets
2591   //   planes : array of seeding planes (see seeding configuration)
2592   //   chi2   : chi2 values (on the Z and Y direction) from the rieman fit of the track.
2593   //
2594   // Output :
2595   //   likelihood value
2596   // 
2597   // Detailed description
2598   //
2599   // The track quality is estimated based on the following 4 criteria:
2600   //  1. precision of the rieman fit on the Y direction (likea)
2601   //  2. chi2 on the Y direction (likechi2y)
2602   //  3. chi2 on the Z direction (likechi2z)
2603   //  4. number of attached clusters compared to a reference value 
2604   //     (see AliTRDrecoParam::fkFindable) (likeN)
2605   //
2606   // The distributions for each type of probabilities are given below as of
2607   // (date). They have to be checked to assure consistency of estimation.
2608   //
2609
2610   // ratio of the total number of clusters/track which are expected to be found by the tracker.
2611   Float_t fgFindable = AliTRDReconstructor::RecoParam()->GetFindableClusters();
2612
2613   
2614   Int_t nclusters = 0;
2615   Double_t sumda = 0.;
2616   for(UChar_t ilayer = 0; ilayer < 4; ilayer++){
2617     Int_t jlayer = planes[ilayer];
2618     nclusters += cseed[jlayer].GetN2();
2619     sumda += TMath::Abs(cseed[jlayer].GetYfitR(1) - cseed[jlayer].GetYref(1));
2620   }
2621   Double_t likea     = TMath::Exp(-sumda*10.6);
2622   Double_t likechi2y  = 0.0000000001;
2623   if (chi2[0] < 0.5) likechi2y += TMath::Exp(-TMath::Sqrt(chi2[0]) * 7.73);
2624   Double_t likechi2z = TMath::Exp(-chi2[1] * 0.088) / TMath::Exp(-chi2[1] * 0.019);
2625   Int_t enc = Int_t(fgFindable*4.*fgNTimeBins);         // Expected Number Of Clusters, normally 72
2626   Double_t likeN     = TMath::Exp(-(enc - nclusters) * 0.19);
2627   
2628   Double_t like      = likea * likechi2y * likechi2z * likeN;
2629
2630   //    AliInfo(Form("sumda(%f) chi2[0](%f) chi2[1](%f) likea(%f) likechi2y(%f) likechi2z(%f) nclusters(%d) likeN(%f)", sumda, chi2[0], chi2[1], likea, likechi2y, likechi2z, nclusters, likeN));
2631   if(AliTRDReconstructor::RecoParam()->GetStreamLevel() >= 2){
2632     Int_t eventNumber = AliTRDtrackerDebug::GetEventNumber();
2633     Int_t candidateNumber = AliTRDtrackerDebug::GetCandidateNumber();
2634     // The Debug Stream contains the seed 
2635     TTreeSRedirector &cstreamer = *fgDebugStreamer;
2636     cstreamer << "CookLikelihood"
2637         << "EventNumber="                       << eventNumber
2638         << "CandidateNumber=" << candidateNumber
2639         << "tracklet0.="                        << &cseed[0]
2640         << "tracklet1.="                        << &cseed[1]
2641         << "tracklet2.="                        << &cseed[2]
2642         << "tracklet3.="                        << &cseed[3]
2643         << "tracklet4.="                        << &cseed[4]
2644         << "tracklet5.="                        << &cseed[5]
2645         << "sumda="                                             << sumda
2646         << "chi0="                                              << chi2[0]
2647         << "chi1="                                              << chi2[1]
2648         << "likea="                                             << likea
2649         << "likechi2y="                         << likechi2y
2650         << "likechi2z="                         << likechi2z
2651         << "nclusters="                         << nclusters
2652         << "likeN="                                             << likeN
2653         << "like="                                              << like
2654         << "\n";
2655   }
2656
2657   return like;
2658 }
2659
2660
2661
2662 //____________________________________________________________________
2663 void AliTRDtrackerV1::GetSeedingConfig(Int_t iconfig, Int_t planes[4])
2664 {
2665   //
2666   // Map seeding configurations to detector planes.
2667   //
2668   // Parameters :
2669   //   iconfig : configuration index
2670   //   planes  : member planes of this configuration. On input empty.
2671   //
2672   // Output :
2673   //   planes : contains the planes which are defining the configuration
2674   // 
2675   // Detailed description
2676   //
2677   // Here is the list of seeding planes configurations together with
2678   // their topological classification:
2679   //
2680   //  0 - 5432 TQ 0
2681   //  1 - 4321 TQ 0
2682   //  2 - 3210 TQ 0
2683   //  3 - 5321 TQ 1
2684   //  4 - 4210 TQ 1
2685   //  5 - 5431 TQ 1
2686   //  6 - 4320 TQ 1
2687   //  7 - 5430 TQ 2
2688   //  8 - 5210 TQ 2
2689   //  9 - 5421 TQ 3
2690   // 10 - 4310 TQ 3
2691   // 11 - 5410 TQ 4
2692   // 12 - 5420 TQ 5
2693   // 13 - 5320 TQ 5
2694   // 14 - 5310 TQ 5
2695   //
2696   // The topologic quality is modeled as follows:
2697   // 1. The general model is define by the equation:
2698   //  p(conf) = exp(-conf/2)
2699   // 2. According to the topologic classification, configurations from the same
2700   //    class are assigned the agerage value over the model values.
2701   // 3. Quality values are normalized.
2702   // 
2703   // The topologic quality distribution as function of configuration is given below:
2704   //Begin_Html
2705   // <img src="gif/topologicQA.gif">
2706   //End_Html
2707   //
2708
2709   switch(iconfig){
2710   case 0: // 5432 TQ 0
2711     planes[0] = 2;
2712     planes[1] = 3;
2713     planes[2] = 4;
2714     planes[3] = 5;
2715     break;
2716   case 1: // 4321 TQ 0
2717     planes[0] = 1;
2718     planes[1] = 2;
2719     planes[2] = 3;
2720     planes[3] = 4;
2721     break;
2722   case 2: // 3210 TQ 0
2723     planes[0] = 0;
2724     planes[1] = 1;
2725     planes[2] = 2;
2726     planes[3] = 3;
2727     break;
2728   case 3: // 5321 TQ 1
2729     planes[0] = 1;
2730     planes[1] = 2;
2731     planes[2] = 3;
2732     planes[3] = 5;
2733     break;
2734   case 4: // 4210 TQ 1
2735     planes[0] = 0;
2736     planes[1] = 1;
2737     planes[2] = 2;
2738     planes[3] = 4;
2739     break;
2740   case 5: // 5431 TQ 1
2741     planes[0] = 1;
2742     planes[1] = 3;
2743     planes[2] = 4;
2744     planes[3] = 5;
2745     break;
2746   case 6: // 4320 TQ 1
2747     planes[0] = 0;
2748     planes[1] = 2;
2749     planes[2] = 3;
2750     planes[3] = 4;
2751     break;
2752   case 7: // 5430 TQ 2
2753     planes[0] = 0;
2754     planes[1] = 3;
2755     planes[2] = 4;
2756     planes[3] = 5;
2757     break;
2758   case 8: // 5210 TQ 2
2759     planes[0] = 0;
2760     planes[1] = 1;
2761     planes[2] = 2;
2762     planes[3] = 5;
2763     break;
2764   case 9: // 5421 TQ 3
2765     planes[0] = 1;
2766     planes[1] = 2;
2767     planes[2] = 4;
2768     planes[3] = 5;
2769     break;
2770   case 10: // 4310 TQ 3
2771     planes[0] = 0;
2772     planes[1] = 1;
2773     planes[2] = 3;
2774     planes[3] = 4;
2775     break;
2776   case 11: // 5410 TQ 4
2777     planes[0] = 0;
2778     planes[1] = 1;
2779     planes[2] = 4;
2780     planes[3] = 5;
2781     break;
2782   case 12: // 5420 TQ 5
2783     planes[0] = 0;
2784     planes[1] = 2;
2785     planes[2] = 4;
2786     planes[3] = 5;
2787     break;
2788   case 13: // 5320 TQ 5
2789     planes[0] = 0;
2790     planes[1] = 2;
2791     planes[2] = 3;
2792     planes[3] = 5;
2793     break;
2794   case 14: // 5310 TQ 5
2795     planes[0] = 0;
2796     planes[1] = 1;
2797     planes[2] = 3;
2798     planes[3] = 5;
2799     break;
2800   }
2801 }
2802
2803 //____________________________________________________________________
2804 void AliTRDtrackerV1::GetExtrapolationConfig(Int_t iconfig, Int_t planes[2])
2805 {
2806   //
2807   // Returns the extrapolation planes for a seeding configuration.
2808   //
2809   // Parameters :
2810   //   iconfig : configuration index
2811   //   planes  : planes which are not in this configuration. On input empty.
2812   //
2813   // Output :
2814   //   planes : contains the planes which are not in the configuration
2815   // 
2816   // Detailed description
2817   //
2818
2819   switch(iconfig){
2820   case 0: // 5432 TQ 0
2821     planes[0] = 1;
2822     planes[1] = 0;
2823     break;
2824   case 1: // 4321 TQ 0
2825     planes[0] = 5;
2826     planes[1] = 0;
2827     break;
2828   case 2: // 3210 TQ 0
2829     planes[0] = 4;
2830     planes[1] = 5;
2831     break;
2832   case 3: // 5321 TQ 1
2833     planes[0] = 4;
2834     planes[1] = 0;
2835     break;
2836   case 4: // 4210 TQ 1
2837     planes[0] = 5;
2838     planes[1] = 3;
2839     break;
2840   case 5: // 5431 TQ 1
2841     planes[0] = 2;
2842     planes[1] = 0;
2843     break;
2844   case 6: // 4320 TQ 1
2845     planes[0] = 5;
2846     planes[1] = 1;
2847     break;
2848   case 7: // 5430 TQ 2
2849     planes[0] = 2;
2850     planes[1] = 1;
2851     break;
2852   case 8: // 5210 TQ 2
2853     planes[0] = 4;
2854     planes[1] = 3;
2855     break;
2856   case 9: // 5421 TQ 3
2857     planes[0] = 3;
2858     planes[1] = 0;
2859     break;
2860   case 10: // 4310 TQ 3
2861     planes[0] = 5;
2862     planes[1] = 2;
2863     break;
2864   case 11: // 5410 TQ 4
2865     planes[0] = 3;
2866     planes[1] = 2;
2867     break;
2868   case 12: // 5420 TQ 5
2869     planes[0] = 3;
2870     planes[1] = 1;
2871     break;
2872   case 13: // 5320 TQ 5
2873     planes[0] = 4;
2874     planes[1] = 1;
2875     break;
2876   case 14: // 5310 TQ 5
2877     planes[0] = 4;
2878     planes[1] = 2;
2879     break;
2880   }
2881 }
2882
2883 //____________________________________________________________________
2884 AliCluster* AliTRDtrackerV1::GetCluster(Int_t idx) const
2885 {
2886   Int_t ncls = fClusters->GetEntriesFast();
2887   return idx >= 0 || idx < ncls ? (AliCluster*)fClusters->UncheckedAt(idx) : 0x0;
2888 }
2889
2890 //____________________________________________________________________
2891 AliTRDseedV1* AliTRDtrackerV1::GetTracklet(Int_t idx) const
2892 {
2893   Int_t ntrklt = fTracklets->GetEntriesFast();
2894   return idx >= 0 || idx < ntrklt ? (AliTRDseedV1*)fTracklets->UncheckedAt(idx) : 0x0;
2895 }
2896
2897 //____________________________________________________________________
2898 AliKalmanTrack* AliTRDtrackerV1::GetTrack(Int_t idx) const
2899 {
2900   Int_t ntrk = fTracks->GetEntriesFast();
2901   return idx >= 0 || idx < ntrk ? (AliKalmanTrack*)fTracks->UncheckedAt(idx) : 0x0;
2902 }
2903
2904 //____________________________________________________________________
2905 Float_t AliTRDtrackerV1::CalculateReferenceX(AliTRDseedV1 *tracklets){
2906   //
2907   // Calculates the reference x-position for the tilted Rieman fit defined as middle
2908   // of the stack (middle between layers 2 and 3). For the calculation all the tracklets
2909   // are taken into account
2910   // 
2911   // Parameters:        - Array of tracklets(AliTRDseedV1)
2912   //
2913   // Output:            - The reference x-position(Float_t)
2914   //
2915   Int_t nDistances = 0;
2916   Float_t meanDistance = 0.;
2917   Int_t startIndex = 5;
2918   for(Int_t il =5; il > 0; il--){
2919     if(tracklets[il].IsOK() && tracklets[il -1].IsOK()){
2920       Float_t xdiff = tracklets[il].GetX0() - tracklets[il -1].GetX0();
2921       meanDistance += xdiff;
2922       nDistances++;
2923     }
2924     if(tracklets[il].IsOK()) startIndex = il;
2925   }
2926   if(tracklets[0].IsOK()) startIndex = 0;
2927   if(!nDistances){
2928     // We should normally never get here
2929     Float_t xpos[2]; memset(xpos, 0, sizeof(Float_t) * 2);
2930     Int_t iok = 0, idiff = 0;
2931     // This attempt is worse and should be avoided:
2932     // check for two chambers which are OK and repeat this without taking the mean value
2933     // Strategy avoids a division by 0;
2934     for(Int_t il = 5; il >= 0; il--){
2935       if(tracklets[il].IsOK()){
2936   xpos[iok] = tracklets[il].GetX0();
2937   iok++;
2938   startIndex = il;
2939       }
2940       if(iok) idiff++;  // to get the right difference;
2941       if(iok > 1) break;
2942     }
2943     if(iok > 1){
2944       meanDistance = (xpos[0] - xpos[1])/idiff;
2945     }
2946     else{
2947       // we have do not even have 2 layers which are OK? The we do not need to fit at all
2948       return 331.;
2949     }
2950   }
2951   else{
2952     meanDistance /= nDistances;
2953   }
2954   return tracklets[startIndex].GetX0() + (2.5 - startIndex) * meanDistance - 0.5 * (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
2955 }
2956
2957 //_____________________________________________________________________________
2958 Int_t AliTRDtrackerV1::Freq(Int_t n, const Int_t *inlist
2959           , Int_t *outlist, Bool_t down)
2960 {    
2961   //
2962   // Sort eleements according occurancy 
2963   // The size of output array has is 2*n 
2964   //
2965
2966   if (n <= 0) {
2967     return 0;
2968   }
2969
2970   Int_t *sindexS = new Int_t[n];   // Temporary array for sorting
2971   Int_t *sindexF = new Int_t[2*n];   
2972   for (Int_t i = 0; i < n; i++) {
2973     sindexF[i] = 0;
2974   }
2975
2976   TMath::Sort(n,inlist,sindexS,down); 
2977
2978   Int_t last     = inlist[sindexS[0]];
2979   Int_t val      = last;
2980   sindexF[0]     = 1;
2981   sindexF[0+n]   = last;
2982   Int_t countPos = 0;
2983
2984   // Find frequency
2985   for (Int_t i = 1; i < n; i++) {
2986     val = inlist[sindexS[i]];
2987     if (last == val) {
2988       sindexF[countPos]++;
2989     }
2990     else {      
2991       countPos++;
2992       sindexF[countPos+n] = val;
2993       sindexF[countPos]++;
2994       last                = val;
2995     }
2996   }
2997   if (last == val) {
2998     countPos++;
2999   }
3000
3001   // Sort according frequency
3002   TMath::Sort(countPos,sindexF,sindexS,kTRUE);
3003
3004   for (Int_t i = 0; i < countPos; i++) {
3005     outlist[2*i  ] = sindexF[sindexS[i]+n];
3006     outlist[2*i+1] = sindexF[sindexS[i]];
3007   }
3008
3009   delete [] sindexS;
3010   delete [] sindexF;
3011   
3012   return countPos;
3013
3014 }
3015
3016 //_____________________________________________________________________________
3017 Float_t AliTRDtrackerV1::GetChi2Y(AliTRDseedV1 *tracklets) const
3018 {
3019   //    Chi2 definition on y-direction
3020
3021   Float_t chi2 = 0;
3022   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
3023     if(!tracklets[ipl].IsOK()) continue;
3024     Double_t distLayer = tracklets[ipl].GetYfit(0) - tracklets[ipl].GetYref(0); 
3025     chi2 += distLayer * distLayer;
3026   }
3027   return chi2;
3028 }
3029
3030 //_____________________________________________________________________________
3031 Float_t AliTRDtrackerV1::GetChi2Z(AliTRDseedV1 *tracklets) const 
3032 {
3033   //    Chi2 definition on z-direction
3034
3035   Float_t chi2 = 0;
3036   for(Int_t ipl = 0; ipl < kNPlanes; ipl++){
3037     if(!tracklets[ipl].IsOK()) continue;
3038     Double_t distLayer = tracklets[ipl].GetMeanz() - tracklets[ipl].GetZref(0); 
3039     chi2 += distLayer * distLayer;
3040   }
3041   return chi2;
3042 }
3043
3044 ///////////////////////////////////////////////////////
3045 //                                                   //
3046 // Resources of class AliTRDLeastSquare              //
3047 //                                                   //
3048 ///////////////////////////////////////////////////////
3049
3050 //_____________________________________________________________________________
3051 AliTRDtrackerV1::AliTRDLeastSquare::AliTRDLeastSquare(){
3052   //
3053   // Constructor of the nested class AliTRDtrackFitterLeastSquare
3054   //
3055   memset(fParams, 0, sizeof(Double_t) * 2);
3056   memset(fSums, 0, sizeof(Double_t) * 5);
3057   memset(fCovarianceMatrix, 0, sizeof(Double_t) * 3);
3058
3059 }
3060
3061 //_____________________________________________________________________________
3062 void AliTRDtrackerV1::AliTRDLeastSquare::AddPoint(Double_t *x, Double_t y, Double_t sigmaY){
3063   //
3064   // Adding Point to the fitter
3065   //
3066   Double_t weight = 1/(sigmaY * sigmaY);
3067   Double_t &xpt = *x;
3068   //    printf("Adding point x = %f, y = %f, sigma = %f\n", xpt, y, sigmaY);
3069   fSums[0] += weight;
3070   fSums[1] += weight * xpt;
3071   fSums[2] += weight * y;
3072   fSums[3] += weight * xpt * y;
3073   fSums[4] += weight * xpt * xpt;
3074   fSums[5] += weight * y * y;
3075 }
3076
3077 //_____________________________________________________________________________
3078 void AliTRDtrackerV1::AliTRDLeastSquare::RemovePoint(Double_t *x, Double_t y, Double_t sigmaY){
3079   //
3080   // Remove Point from the sample
3081   //
3082   Double_t weight = 1/(sigmaY * sigmaY);
3083   Double_t &xpt = *x; 
3084   fSums[0] -= weight;
3085   fSums[1] -= weight * xpt;
3086   fSums[2] -= weight * y;
3087   fSums[3] -= weight * xpt * y;
3088   fSums[4] -= weight * xpt * xpt;
3089   fSums[5] -= weight * y * y;
3090 }
3091
3092 //_____________________________________________________________________________
3093 void AliTRDtrackerV1::AliTRDLeastSquare::Eval(){
3094   //
3095   // Evaluation of the fit:
3096   // Calculation of the parameters
3097   // Calculation of the covariance matrix
3098   //
3099   
3100   Double_t denominator = fSums[0] * fSums[4] - fSums[1] *fSums[1];
3101   //    for(Int_t isum = 0; isum < 5; isum++)
3102   //            printf("fSums[%d] = %f\n", isum, fSums[isum]);
3103   //    printf("denominator = %f\n", denominator);
3104   fParams[0] = (fSums[2] * fSums[4] - fSums[1] * fSums[3])/ denominator;
3105   fParams[1] = (fSums[0] * fSums[3] - fSums[1] * fSums[2]) / denominator;
3106   //    printf("fParams[0] = %f, fParams[1] = %f\n", fParams[0], fParams[1]);
3107   
3108   // Covariance matrix
3109   fCovarianceMatrix[0] = fSums[4] - fSums[1] * fSums[1] / fSums[0];
3110   fCovarianceMatrix[1] = fSums[5] - fSums[2] * fSums[2] / fSums[0];
3111   fCovarianceMatrix[2] = fSums[3] - fSums[1] * fSums[2] / fSums[0];
3112 }
3113
3114 //_____________________________________________________________________________
3115 Double_t AliTRDtrackerV1::AliTRDLeastSquare::GetFunctionValue(Double_t *xpos) const {
3116   //
3117   // Returns the Function value of the fitted function at a given x-position
3118   //
3119   return fParams[0] + fParams[1] * (*xpos);
3120 }
3121
3122 //_____________________________________________________________________________
3123 void AliTRDtrackerV1::AliTRDLeastSquare::GetCovarianceMatrix(Double_t *storage) const {
3124   //
3125   // Copies the values of the covariance matrix into the storage
3126   //
3127   memcpy(storage, fCovarianceMatrix, sizeof(Double_t) * 3);
3128 }
3129