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