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