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