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