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