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