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