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