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