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