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