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