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