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