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