]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDtracker.cxx
2b8307059ac26fe55af3dcd012b2cb26458a08bf
[u/mrichter/AliRoot.git] / TRD / AliTRDtracker.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15                                                       
16 /* $Id$ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //                                                                           //
20 //  The standard TRD tracker                                                 //  
21 //  Based on Kalman filltering approach                                      //
22 //                                                                           //
23 ///////////////////////////////////////////////////////////////////////////////
24
25 #include <Riostream.h>
26 #include <TFile.h>
27 #include <TBranch.h>
28 #include <TTree.h>  
29 #include <TObjArray.h> 
30
31 #include "AliTRDgeometry.h"
32 #include "AliTRDpadPlane.h"
33 #include "AliTRDgeometryFull.h"
34 #include "AliTRDcluster.h" 
35 #include "AliTRDtrack.h"
36 #include "AliTRDseed.h"
37 #include "AliESD.h"
38
39 #include "AliTRDcalibDB.h"
40 #include "AliTRDCommonParam.h"
41
42 #include "TTreeStream.h"
43 #include "TGraph.h"
44 #include "AliTRDtracker.h"
45 #include "TLinearFitter.h"
46 #include "AliRieman.h"
47 #include "AliTrackPointArray.h"
48 #include "AliAlignObj.h"
49 #include "AliTRDReconstructor.h"
50
51 ClassImp(AliTRDtracker) 
52
53   const  Float_t     AliTRDtracker::fgkMinClustersInTrack = 0.5;  
54   const  Float_t     AliTRDtracker::fgkLabelFraction      = 0.8;  
55   const  Double_t    AliTRDtracker::fgkMaxChi2            = 12.; 
56   const  Double_t    AliTRDtracker::fgkMaxSnp             = 0.95; // correspond to tan = 3
57   const  Double_t    AliTRDtracker::fgkMaxStep            = 2.;   // maximal step size in propagation 
58
59 //_____________________________________________________________________________
60 AliTRDtracker::AliTRDtracker():AliTracker(),
61                                fGeom(0),
62                                fNclusters(0),
63                                fClusters(0),
64                                fNseeds(0),
65                                fSeeds(0),
66                                fNtracks(0),
67                                fTracks(0),
68                                fTimeBinsPerPlane(0),
69                                fAddTRDseeds(kFALSE),
70                                fNoTilt(kFALSE)
71 {
72   //
73   // Default constructor
74   //
75
76   for(Int_t i=0;i<kTrackingSectors;i++) fTrSec[i]=0;
77   for(Int_t j=0;j<5;j++)
78   for(Int_t k=0;k<18;k++) fHoles[j][k]=kFALSE;
79   fDebugStreamer = 0;
80
81
82
83 //_____________________________________________________________________________
84 AliTRDtracker::AliTRDtracker(const TFile *geomfile):AliTracker()
85 {
86   // 
87   //  Main constructor
88   //  
89    
90   fAddTRDseeds = kFALSE;
91   fGeom = NULL;
92   fNoTilt = kFALSE;
93   
94   TDirectory *savedir=gDirectory; 
95   TFile *in=(TFile*)geomfile;  
96   if (!in->IsOpen()) {
97     printf("AliTRDtracker::AliTRDtracker(): geometry file is not open!\n");
98     printf("    FULL TRD geometry and DEFAULT TRD parameter will be used\n");
99   }
100   else {
101     in->cd();  
102     fGeom = (AliTRDgeometry*) in->Get("TRDgeometry");
103   }
104
105   if(fGeom) {
106     //    printf("Found geometry version %d on file \n", fGeom->IsVersion());
107   }
108   else { 
109     printf("AliTRDtracker::AliTRDtracker(): can't find TRD geometry!\n");
110     fGeom = new AliTRDgeometryFull();
111   } 
112   fGeom->ReadGeoMatrices();
113
114   savedir->cd();  
115
116   fNclusters = 0;
117   fClusters  = new TObjArray(2000); 
118   fNseeds    = 0;
119   fSeeds     = new TObjArray(2000);
120   fNtracks   = 0;
121   fTracks    = new TObjArray(1000);
122
123   for(Int_t geomS = 0; geomS < kTrackingSectors; geomS++) {
124     Int_t trS = CookSectorIndex(geomS);
125     fTrSec[trS] = new AliTRDtrackingSector(fGeom, geomS);
126     for (Int_t icham=0;icham<AliTRDgeometry::kNcham; icham++){
127       fHoles[icham][trS]=fGeom->IsHole(0,icham,geomS);
128     }
129   }
130   AliTRDpadPlane *padPlane = AliTRDCommonParam::Instance()->GetPadPlane(0,0);
131   Float_t tiltAngle = TMath::Abs(padPlane->GetTiltingAngle());
132   if(tiltAngle < 0.1) {
133     fNoTilt = kTRUE;
134   }
135
136   fTimeBinsPerPlane =  AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
137
138   fDebugStreamer = new TTreeSRedirector("TRDdebug.root");
139
140   savedir->cd();
141
142 }   
143
144 //_____________________________________________________________________________
145 AliTRDtracker::~AliTRDtracker()
146 {
147   //
148   // Destructor of AliTRDtracker 
149   //
150
151   if (fClusters) {
152     fClusters->Delete();
153     delete fClusters;
154   }
155   if (fTracks) {
156     fTracks->Delete();
157     delete fTracks;
158   }
159   if (fSeeds) {
160     fSeeds->Delete();
161     delete fSeeds;
162   }
163   delete fGeom;  
164
165   for(Int_t geomS = 0; geomS < kTrackingSectors; geomS++) {
166     delete fTrSec[geomS];
167   }
168   if (fDebugStreamer) {    
169     //fDebugStreamer->Close();
170     delete fDebugStreamer;
171   }
172
173 }   
174
175 //_____________________________________________________________________________
176 Int_t  AliTRDtracker::LocalToGlobalID(Int_t lid)
177 {
178   //
179   // Transform internal TRD ID to global detector ID
180   //
181
182   Int_t  isector = fGeom->GetSector(lid);
183   Int_t  ichamber= fGeom->GetChamber(lid);
184   Int_t  iplan   = fGeom->GetPlane(lid);
185   //
186   AliAlignObj::ELayerID iLayer = AliAlignObj::kTRD1;
187   switch (iplan) {
188   case 0:
189     iLayer = AliAlignObj::kTRD1;
190     break;
191   case 1:
192     iLayer = AliAlignObj::kTRD2;
193     break;
194   case 2:
195     iLayer = AliAlignObj::kTRD3;
196     break;
197   case 3:
198     iLayer = AliAlignObj::kTRD4;
199     break;
200   case 4:
201     iLayer = AliAlignObj::kTRD5;
202     break;
203   case 5:
204     iLayer = AliAlignObj::kTRD6;
205     break;
206   };
207   Int_t modId = isector*fGeom->Ncham()+ichamber;
208   UShort_t volid = AliAlignObj::LayerToVolUID(iLayer,modId);
209
210   return volid;
211
212 }
213
214 //_____________________________________________________________________________
215 Int_t  AliTRDtracker::GlobalToLocalID(Int_t gid)
216 {
217   //
218   // Transform global detector ID to local detector ID
219   // 
220
221   Int_t modId=0;
222   AliAlignObj::ELayerID  layerId  = AliAlignObj::VolUIDToLayer(gid, modId);
223   Int_t     isector  = modId/fGeom->Ncham();
224   Int_t     ichamber = modId%fGeom->Ncham();
225   Int_t     iLayer    = -1;
226   switch (layerId) {
227   case AliAlignObj::kTRD1:
228     iLayer = 0;
229     break;
230   case AliAlignObj::kTRD2:
231     iLayer = 1;
232     break;
233   case AliAlignObj::kTRD3:
234     iLayer = 2;
235     break;
236   case AliAlignObj::kTRD4:
237     iLayer = 3;
238     break;
239   case AliAlignObj::kTRD5:
240     iLayer = 4;
241     break;
242   case AliAlignObj::kTRD6:
243     iLayer = 5;
244     break;
245   default:
246     iLayer =-1;
247   }
248   if (iLayer<0) return -1;
249   Int_t lid = fGeom->GetDetector(iLayer,ichamber,isector);
250
251   return lid;
252
253 }
254
255 //_____________________________________________________________________________
256 Bool_t  AliTRDtracker::Transform(AliTRDcluster * cluster)
257 {
258   //
259   // Transform something ... whatever ...
260   //
261
262   const Double_t kX0shift           = 2.52;    // magic constants for geo manager transformation
263   const Double_t kX0shift5          = 3.05;    // 
264   //
265   //
266   // apply alignment and calibration to transform cluster
267   //
268   //
269   Int_t detector = cluster->GetDetector();
270   Int_t plane   = fGeom->GetPlane(cluster->GetDetector());
271   Int_t chamber = fGeom->GetChamber(cluster->GetDetector());
272   Int_t sector  = fGeom->GetSector(cluster->GetDetector());
273
274   Double_t dxAmp  = (Double_t) fGeom->CamHght();          // Amplification region
275   Double_t driftX = TMath::Max(cluster->GetX()-dxAmp*0.5,0.);  // drift distance
276   //
277   // ExB correction
278   //
279   Double_t vdrift = AliTRDcalibDB::Instance()->GetVdrift(cluster->GetDetector(),0,0);
280   Double_t exB =   AliTRDcalibDB::Instance()->GetOmegaTau(vdrift);
281   //
282   AliTRDCommonParam* commonParam = AliTRDCommonParam::Instance();  
283   AliTRDpadPlane * padPlane = commonParam->GetPadPlane(plane,chamber);
284   Double_t zshiftIdeal  = 0.5*(padPlane->GetRow0()+padPlane->GetRowEnd());
285   Double_t localPos[3], localPosTracker[3];
286   localPos[0] = -cluster->GetX();
287   localPos[1] =  cluster->GetY() - driftX*exB;
288   localPos[2] =  cluster->GetZ() -zshiftIdeal;
289   //
290   cluster->SetY(cluster->GetY() - driftX*exB);
291   Double_t xplane = (Double_t) AliTRDgeometry::GetTime0(plane); 
292   cluster->SetX(xplane- cluster->GetX());
293   //
294   TGeoHMatrix * matrix =  fGeom->GetCorrectionMatrix(cluster->GetDetector());
295   if (!matrix){
296     // no matrix found - if somebody used geometry with holes
297     AliError("Invalid Geometry - Default Geometry used\n");
298     return kTRUE;   
299   }
300   matrix->LocalToMaster(localPos, localPosTracker);  
301   //
302   //
303   //
304   if (AliTRDReconstructor::StreamLevel()>1){
305     (*fDebugStreamer)<<"Transform"<<
306       "Cl.="<<cluster<<
307       "matrix.="<<matrix<<
308       "Detector="<<detector<<
309       "Sector="<<sector<<
310       "Plane="<<plane<<
311       "Chamber="<<chamber<<
312       "lx0="<<localPosTracker[0]<<
313       "ly0="<<localPosTracker[1]<<
314       "lz0="<<localPosTracker[2]<<
315       "\n";
316   }
317   //
318   if (plane==5)
319      cluster->SetX(localPosTracker[0]+kX0shift5);
320   else
321     cluster->SetX(localPosTracker[0]+kX0shift);
322     
323   cluster->SetY(localPosTracker[1]);
324   cluster->SetZ(localPosTracker[2]);
325
326   return kTRUE;
327
328 }
329
330 //_____________________________________________________________________________
331 // Bool_t  AliTRDtracker::Transform(AliTRDcluster * cluster)
332 //{
333 //   //
334 //   //
335 //   const Double_t kDriftCorrection  = 1.01;                 // drift coeficient correction
336 //   const Double_t kTime0Cor         = 0.32;                 // time0 correction
337 //   //
338 //   const Double_t kX0shift           = 2.52; 
339 //   const Double_t kX0shift5          = 3.05; 
340
341 //   //
342 //   // apply alignment and calibration to transform cluster
343 //   //
344 //   //
345 //   Int_t detector = cluster->GetDetector();
346 //   Int_t plane   = fGeom->GetPlane(cluster->GetDetector());
347 //   Int_t chamber = fGeom->GetChamber(cluster->GetDetector());
348 //   Int_t sector  = fGeom->GetSector(cluster->GetDetector());
349
350 //   Double_t dxAmp  = (Double_t) fGeom->CamHght();          // Amplification region
351 //   Double_t driftX = TMath::Max(cluster->GetX()-dxAmp*0.5,0.);  // drift distance
352 //   //
353 //   // ExB correction
354 //   //
355 //   Double_t vdrift = AliTRDcalibDB::Instance()->GetVdrift(cluster->GetDetector(),0,0);
356 //   Double_t exB =   AliTRDcalibDB::Instance()->GetOmegaTau(vdrift);
357 //   //
358
359 //   AliTRDCommonParam* commonParam = AliTRDCommonParam::Instance();  
360 //   AliTRDpadPlane * padPlane = commonParam->GetPadPlane(plane,chamber);
361 //   Double_t zshiftIdeal  = 0.5*(padPlane->GetRow0()+padPlane->GetRowEnd());
362 //   Double_t localPos[3], globalPos[3], localPosTracker[3], localPosTracker2[3];
363 //   localPos[2] = -cluster->GetX();
364 //   localPos[0] =  cluster->GetY() - driftX*exB;
365 //   localPos[1] =  cluster->GetZ() -zshiftIdeal;
366 //   TGeoHMatrix * matrix =  fGeom->GetGeoMatrix(cluster->GetDetector());
367 //   matrix->LocalToMaster(localPos, globalPos);
368   
369 //   Double_t sectorAngle = 20.*(sector%18)+10;
370 //   TGeoHMatrix  rotSector;
371 //   rotSector.RotateZ(sectorAngle);
372 //   rotSector.LocalToMaster(globalPos, localPosTracker);
373 //   //
374 //   //
375 //   TGeoHMatrix  matrix2(*matrix);
376 //   matrix2.MultiplyLeft(&rotSector);
377 //   matrix2.LocalToMaster(localPos,localPosTracker2);
378 //   //
379 //   //
380 //   //
381 //   cluster->SetY(cluster->GetY() - driftX*exB);
382 //   Double_t xplane = (Double_t) AliTRDgeometry::GetTime0(plane); 
383 //   cluster->SetX(xplane- kDriftCorrection*(cluster->GetX()-kTime0Cor));
384 //   (*fDebugStreamer)<<"Transform"<<
385 //     "Cl.="<<cluster<<
386 //     "matrix.="<<matrix<<
387 //     "matrix2.="<<&matrix2<<
388 //     "Detector="<<detector<<
389 //     "Sector="<<sector<<
390 //     "Plane="<<plane<<
391 //     "Chamber="<<chamber<<
392 //     "lx0="<<localPosTracker[0]<<
393 //     "ly0="<<localPosTracker[1]<<
394 //     "lz0="<<localPosTracker[2]<<
395 //     "lx2="<<localPosTracker2[0]<<
396 //     "ly2="<<localPosTracker2[1]<<
397 //     "lz2="<<localPosTracker2[2]<<
398 //     "\n";
399 //   //
400 //   if (plane==5)
401 //      cluster->SetX(localPosTracker[0]+kX0shift5);
402 //   else
403 //     cluster->SetX(localPosTracker[0]+kX0shift);
404     
405 //   cluster->SetY(localPosTracker[1]);
406 //   cluster->SetZ(localPosTracker[2]);
407 //   return kTRUE;
408 // }
409
410 //_____________________________________________________________________________
411 Bool_t AliTRDtracker::AdjustSector(AliTRDtrack *track) 
412 {
413   //
414   // Rotates the track when necessary
415   //
416
417   Double_t alpha = AliTRDgeometry::GetAlpha(); 
418   Double_t y = track->GetY();
419   Double_t ymax = track->GetX()*TMath::Tan(0.5*alpha);
420
421   //Int_t ns = AliTRDgeometry::kNsect;
422   //Int_t s=Int_t(track->GetAlpha()/alpha)%ns; 
423
424   if (y > ymax) {
425     //s = (s+1) % ns;
426     if (!track->Rotate(alpha)) return kFALSE;
427   } else if (y <-ymax) {
428     //s = (s-1+ns) % ns;                           
429     if (!track->Rotate(-alpha)) return kFALSE;   
430   } 
431
432   return kTRUE;
433
434 }
435
436 //_____________________________________________________________________________
437 AliTRDcluster *AliTRDtracker::GetCluster(AliTRDtrack *track, Int_t plane
438                                        , Int_t timebin, UInt_t &index)
439 {
440   //
441   // Try to find cluster in the backup list
442   //
443
444   AliTRDcluster * cl =0;
445   Int_t *indexes = track->GetBackupIndexes();
446   for (UInt_t i=0;i<kMaxTimeBinIndex;i++){
447     if (indexes[i]==0) break;  
448     AliTRDcluster * cli = (AliTRDcluster*)fClusters->UncheckedAt(indexes[i]);
449     if (!cli) break;
450     if (cli->GetLocalTimeBin()!=timebin) continue;
451     Int_t iplane = fGeom->GetPlane(cli->GetDetector());
452     if (iplane==plane) {
453       cl = cli;
454       index = indexes[i];
455       break;
456     }
457   }
458
459   return cl;
460
461 }
462
463 //_____________________________________________________________________________
464 Int_t  AliTRDtracker::GetLastPlane(AliTRDtrack * track)
465 {
466   //
467   // Return last updated plane
468   //
469
470   Int_t lastplane=0;
471   Int_t *indexes = track->GetBackupIndexes();
472   for (UInt_t i=0;i<kMaxTimeBinIndex;i++){
473     AliTRDcluster * cli = (AliTRDcluster*)fClusters->UncheckedAt(indexes[i]);
474     if (!cli) break;
475     Int_t iplane = fGeom->GetPlane(cli->GetDetector());
476     if (iplane>lastplane) {
477       lastplane = iplane;
478     }
479   }
480
481   return lastplane;
482
483 }
484
485 //_____________________________________________________________________________
486 Int_t AliTRDtracker::Clusters2Tracks(AliESD* event)
487 {
488   //
489   // Finds tracks within the TRD. The ESD event is expected to contain seeds 
490   // at the outer part of the TRD. The seeds
491   // are found within the TRD if fAddTRDseeds is TRUE. 
492   // The tracks are propagated to the innermost time bin 
493   // of the TRD and the ESD event is updated
494   //
495
496   Int_t timeBins = fTrSec[0]->GetNumberOfTimeBins();
497   Float_t foundMin = fgkMinClustersInTrack * timeBins; 
498   Int_t nseed = 0;
499   Int_t found = 0;
500   //  Int_t innerTB = fTrSec[0]->GetInnerTimeBin();
501
502   Int_t n = event->GetNumberOfTracks();
503   for (Int_t i=0; i<n; i++) {
504     AliESDtrack* seed=event->GetTrack(i);
505     ULong_t status=seed->GetStatus();
506     if ( (status & AliESDtrack::kTRDout ) == 0 ) continue;
507     if ( (status & AliESDtrack::kTRDin) != 0 ) continue;
508     nseed++;
509     
510     AliTRDtrack* seed2 = new AliTRDtrack(*seed);
511     //seed2->ResetCovariance(); 
512     AliTRDtrack *pt = new AliTRDtrack(*seed2,seed2->GetAlpha());
513     AliTRDtrack &t=*pt; 
514     FollowProlongation(t); 
515     if (t.GetNumberOfClusters() >= foundMin) {
516       UseClusters(&t);
517       CookLabel(pt, 1-fgkLabelFraction);
518       //      t.CookdEdx();
519     }
520     found++;
521 //    cout<<found<<'\r';     
522
523     Double_t xTPC = 250;
524     if (PropagateToX(t,xTPC,fgkMaxStep)) {
525       seed->UpdateTrackParams(pt, AliESDtrack::kTRDin);
526     }  
527     delete seed2;
528     delete pt;
529   }     
530
531   cout<<"Number of loaded seeds: "<<nseed<<endl;  
532   cout<<"Number of found tracks from loaded seeds: "<<found<<endl;
533
534   // after tracks from loaded seeds are found and the corresponding 
535   // clusters are used, look for additional seeds from TRD
536   
537   
538   cout<<"Total number of found tracks: "<<found<<endl;
539     
540   return 0;    
541
542 }     
543      
544 //_____________________________________________________________________________
545 Int_t AliTRDtracker::PropagateBack(AliESD* event) 
546 {
547   //
548   // Gets seeds from ESD event. The seeds are AliTPCtrack's found and
549   // backpropagated by the TPC tracker. Each seed is first propagated 
550   // to the TRD, and then its prolongation is searched in the TRD.
551   // If sufficiently long continuation of the track is found in the TRD
552   // the track is updated, otherwise it's stored as originaly defined 
553   // by the TPC tracker.   
554   //  
555
556   Int_t found=0;  
557   Float_t foundMin = 20;
558   Int_t n = event->GetNumberOfTracks();
559   //
560   //Sort tracks
561   Float_t *quality =new Float_t[n];
562   Int_t *index   =new Int_t[n];
563   for (Int_t i=0; i<n; i++) {
564     AliESDtrack* seed=event->GetTrack(i);
565     Double_t covariance[15];
566     seed->GetExternalCovariance(covariance);
567     quality[i] = covariance[0]+covariance[2];      
568   }
569   TMath::Sort(n,quality,index,kFALSE);
570   //
571   for (Int_t i=0; i<n; i++) {
572     //    AliESDtrack* seed=event->GetTrack(i);
573     AliESDtrack* seed=event->GetTrack(index[i]);
574
575     ULong_t status=seed->GetStatus();
576     if ( (status & AliESDtrack::kTPCout ) == 0 ) continue;
577     if ( (status & AliESDtrack::kTRDout) != 0 ) continue;
578
579     Int_t lbl = seed->GetLabel();
580     AliTRDtrack *track = new AliTRDtrack(*seed);
581     track->SetSeedLabel(lbl);
582     seed->UpdateTrackParams(track, AliESDtrack::kTRDbackup); //make backup
583     fNseeds++;
584     Float_t p4     = track->GetC();
585     //
586     Int_t expectedClr = FollowBackProlongation(*track);
587     if (TMath::Abs(track->GetC()-p4)/TMath::Abs(p4)<0.2 || TMath::Abs(track->GetPt())>0.8 ) {
588       // 
589       //make backup for back propagation 
590       //
591       Int_t foundClr = track->GetNumberOfClusters();
592       if (foundClr >= foundMin) {
593         track->CookdEdx(); 
594         CookdEdxTimBin(*track);
595         CookLabel(track, 1-fgkLabelFraction);
596         if (track->GetBackupTrack()) UseClusters(track->GetBackupTrack());
597         if(track->GetChi2()/track->GetNumberOfClusters()<4) {   // sign only gold tracks
598           if (seed->GetKinkIndex(0)==0&&TMath::Abs(track->GetPt())<1.5 ) UseClusters(track);
599         }
600         Bool_t isGold = kFALSE;
601         
602         if (track->GetChi2()/track->GetNumberOfClusters()<5) {  //full gold track
603           // seed->UpdateTrackParams(track, AliESDtrack::kTRDbackup);
604            if (track->GetBackupTrack()) seed->UpdateTrackParams(track->GetBackupTrack(), AliESDtrack::kTRDbackup);
605           isGold = kTRUE;
606         }
607         if (!isGold && track->GetNCross()==0&&track->GetChi2()/track->GetNumberOfClusters()<7){ //almost gold track
608           //      seed->UpdateTrackParams(track, AliESDtrack::kTRDbackup);
609           if (track->GetBackupTrack()) seed->UpdateTrackParams(track->GetBackupTrack(), AliESDtrack::kTRDbackup);
610           isGold = kTRUE;
611         }
612         if (!isGold && track->GetBackupTrack()){
613           if (track->GetBackupTrack()->GetNumberOfClusters()>foundMin&&
614               (track->GetBackupTrack()->GetChi2()/(track->GetBackupTrack()->GetNumberOfClusters()+1))<7){         
615             seed->UpdateTrackParams(track->GetBackupTrack(), AliESDtrack::kTRDbackup);
616             isGold = kTRUE;
617           }
618         }
619         if (track->StatusForTOF()>0 &&track->fNCross==0 && Float_t(track->fN)/Float_t(track->fNExpected)>0.4){
620           //seed->UpdateTrackParams(track->GetBackupTrack(), AliESDtrack::kTRDbackup);
621         }
622       }
623     }
624     // Debug part of tracking
625     TTreeSRedirector& cstream = *fDebugStreamer;
626     Int_t eventNr = event->GetEventNumber();
627     if (AliTRDReconstructor::StreamLevel()>0){
628       if (track->GetBackupTrack()){
629         cstream<<"Tracks"<<
630           "EventNr="<<eventNr<<
631           "ESD.="<<seed<<
632           "trd.="<<track<<
633           "trdback.="<<track->GetBackupTrack()<<        
634           "\n";
635       }else{
636         cstream<<"Tracks"<<
637           "EventNr="<<eventNr<<
638           "ESD.="<<seed<<
639           "trd.="<<track<<
640           "trdback.="<<track<<
641           "\n";
642       }
643     }
644     //
645     //Propagation to the TOF (I.Belikov)    
646     if (track->GetStop()==kFALSE){
647       
648       Double_t xtof=371.;
649       Double_t c2=track->GetC()*xtof - track->GetEta();
650       if (TMath::Abs(c2)>=0.99) {
651         delete track;
652         continue;
653       }
654       Double_t xTOF0 = 370. ;          
655       PropagateToX(*track,xTOF0,fgkMaxStep);
656       //
657       //energy losses taken to the account - check one more time
658       c2=track->GetC()*xtof - track->GetEta();
659       if (TMath::Abs(c2)>=0.99) {
660         delete track;
661         continue;
662       }
663
664       //      
665       Double_t ymax=xtof*TMath::Tan(0.5*AliTRDgeometry::GetAlpha());
666       Double_t y=track->GetYat(xtof);
667       if (y > ymax) {
668         if (!track->Rotate(AliTRDgeometry::GetAlpha())) {
669           delete track;
670           continue;
671         }
672       } else if (y <-ymax) {
673         if (!track->Rotate(-AliTRDgeometry::GetAlpha())) {
674           delete track;
675           continue;
676         }
677       }
678       
679       if (track->PropagateTo(xtof)) {
680         seed->UpdateTrackParams(track, AliESDtrack::kTRDout);
681         for (Int_t i=0;i<AliESDtrack::kNPlane;i++) {
682            seed->SetTRDsignals(track->GetPIDsignals(i),i);
683            seed->SetTRDTimBin(track->GetPIDTimBin(i),i);
684         }
685         //      seed->SetTRDtrack(new AliTRDtrack(*track));
686         if (track->GetNumberOfClusters()>foundMin) found++;
687       }
688     }else{
689       if (track->GetNumberOfClusters()>15&&track->GetNumberOfClusters()>0.5*expectedClr){
690         seed->UpdateTrackParams(track, AliESDtrack::kTRDout);
691         //seed->SetStatus(AliESDtrack::kTRDStop);    
692         for (Int_t i=0;i<AliESDtrack::kNPlane;i++) {
693            seed->SetTRDsignals(track->GetPIDsignals(i),i);
694            seed->SetTRDTimBin(track->GetPIDTimBin(i),i);
695         }
696         //seed->SetTRDtrack(new AliTRDtrack(*track));
697         found++;
698       }
699     }
700     seed->SetTRDQuality(track->StatusForTOF());    
701     seed->SetTRDBudget(track->fBudget[0]);    
702   
703     delete track;
704     //
705     //End of propagation to the TOF
706     //if (foundClr>foundMin)
707     //  seed->UpdateTrackParams(track, AliESDtrack::kTRDout);
708     
709
710   }
711   
712   cerr<<"Number of seeds: "<<fNseeds<<endl;  
713   cerr<<"Number of back propagated TRD tracks: "<<found<<endl;
714   
715   if (AliTRDReconstructor::SeedingOn()) MakeSeedsMI(3,5,event); //new seeding
716
717   fSeeds->Clear(); fNseeds=0;
718   delete [] index;
719   delete [] quality;
720   
721   return 0;
722
723 }
724
725 //_____________________________________________________________________________
726 Int_t AliTRDtracker::RefitInward(AliESD* event)
727 {
728   //
729   // Refits tracks within the TRD. The ESD event is expected to contain seeds 
730   // at the outer part of the TRD. 
731   // The tracks are propagated to the innermost time bin 
732   // of the TRD and the ESD event is updated
733   // Origin: Thomas KUHR (Thomas.Kuhr@cern.ch)
734   //
735
736   Int_t timeBins = fTrSec[0]->GetNumberOfTimeBins();
737   Float_t foundMin = fgkMinClustersInTrack * timeBins; 
738   Int_t nseed = 0;
739   Int_t found = 0;
740   //  Int_t innerTB = fTrSec[0]->GetInnerTimeBin();
741   AliTRDtrack seed2;
742
743   Int_t n = event->GetNumberOfTracks();
744   for (Int_t i=0; i<n; i++) {
745     AliESDtrack* seed=event->GetTrack(i);
746     new(&seed2) AliTRDtrack(*seed);
747     if (seed2.GetX()<270){
748       seed->UpdateTrackParams(&seed2, AliESDtrack::kTRDbackup); // backup TPC track - only update
749       continue;
750     }
751
752     ULong_t status=seed->GetStatus();
753     if ( (status & AliESDtrack::kTRDout ) == 0 ) {
754       continue;
755     }
756     if ( (status & AliESDtrack::kTRDin) != 0 ) {
757       continue;
758     }
759     nseed++;    
760 //     if (1/seed2.Get1Pt()>1.5&& seed2.GetX()>260.) {
761 //       Double_t oldx = seed2.GetX();
762 //       seed2.PropagateTo(500.);
763 //       seed2.ResetCovariance(1.);
764 //       seed2.PropagateTo(oldx);
765 //     }
766 //     else{
767 //       seed2.ResetCovariance(5.); 
768 //     }
769
770     AliTRDtrack *pt = new AliTRDtrack(seed2,seed2.GetAlpha());
771     Int_t * indexes2 = seed2.GetIndexes();
772     for (Int_t i=0;i<AliESDtrack::kNPlane;i++) {
773       pt->SetPIDsignals(seed2.GetPIDsignals(i),i);
774       pt->SetPIDTimBin(seed2.GetPIDTimBin(i),i);
775     }
776
777     Int_t * indexes3 = pt->GetBackupIndexes();
778     for (Int_t i=0;i<200;i++) {
779       if (indexes2[i]==0) break;
780       indexes3[i] = indexes2[i];
781     }          
782     //AliTRDtrack *pt = seed2;
783     AliTRDtrack &t=*pt; 
784     FollowProlongation(t); 
785     if (t.GetNumberOfClusters() >= foundMin) {
786       //      UseClusters(&t);
787       //CookLabel(pt, 1-fgkLabelFraction);
788       t.CookdEdx();
789       CookdEdxTimBin(t);
790     }
791     found++;
792 //    cout<<found<<'\r';     
793     Double_t xTPC = 250;
794     if(PropagateToX(t,xTPC,fgkMaxStep)) {
795       seed->UpdateTrackParams(pt, AliESDtrack::kTRDrefit);
796       for (Int_t i=0;i<AliESDtrack::kNPlane;i++) {
797         seed->SetTRDsignals(pt->GetPIDsignals(i),i);
798         seed->SetTRDTimBin(pt->GetPIDTimBin(i),i);
799       }
800     }else{
801       //if not prolongation to TPC - propagate without update
802       AliTRDtrack* seed2 = new AliTRDtrack(*seed);
803       seed2->ResetCovariance(5.); 
804       AliTRDtrack *pt2 = new AliTRDtrack(*seed2,seed2->GetAlpha());
805       delete seed2;
806       if (PropagateToX(*pt2,xTPC,fgkMaxStep)) { 
807         //pt2->CookdEdx(0.,1.);
808         pt2->CookdEdx( ); // Modification by PS
809         CookdEdxTimBin(*pt2);
810         seed->UpdateTrackParams(pt2, AliESDtrack::kTRDrefit);
811         for (Int_t i=0;i<AliESDtrack::kNPlane;i++) {
812           seed->SetTRDsignals(pt2->GetPIDsignals(i),i);
813           seed->SetTRDTimBin(pt2->GetPIDTimBin(i),i);
814         }
815       }
816       delete pt2;
817     }  
818     delete pt;
819   }   
820
821   cout<<"Number of loaded seeds: "<<nseed<<endl;  
822   cout<<"Number of found tracks from loaded seeds: "<<found<<endl;
823
824   return 0;
825
826 }
827
828 //_____________________________________________________________________________
829 Int_t AliTRDtracker::FollowProlongation(AliTRDtrack& t)
830 {
831   //
832   // Starting from current position on track=t this function tries
833   // to extrapolate the track up to timeBin=0 and to confirm prolongation
834   // if a close cluster is found. Returns the number of clusters
835   // expected to be found in sensitive layers
836   // GeoManager used to estimate mean density
837   //
838
839   Int_t sector;
840   Int_t lastplane = GetLastPlane(&t);
841   Double_t radLength = 0.0;
842   Double_t rho = 0.0;
843   Int_t expectedNumberOfClusters = 0;
844   //
845   //
846   //
847   for (Int_t iplane = lastplane; iplane>=0; iplane--){
848     //
849     Int_t    row0 = GetGlobalTimeBin(0, iplane,GetTimeBinsPerPlane()-1);
850     Int_t    rowlast = GetGlobalTimeBin(0, iplane,0);
851     //
852     // propagate track close to the plane if neccessary
853     //
854     Double_t currentx  = fTrSec[0]->GetLayer(rowlast)->GetX();
855     if (currentx < -fgkMaxStep +t.GetX()){
856       //propagate closer to chamber - safety space fgkMaxStep      
857       if (!PropagateToX(t, currentx+fgkMaxStep, fgkMaxStep)) break;
858     }
859     if (!AdjustSector(&t)) break;
860     //
861     // get material budget
862     //
863     Double_t xyz0[3],xyz1[3],param[7],x,y,z;
864     t.GetGlobalXYZ(xyz0[0],xyz0[1],xyz0[2]);   //starting global position
865     // end global position
866     x = fTrSec[0]->GetLayer(row0)->GetX();
867     if (!t.GetProlongation(x,y,z)) break;
868     xyz1[0] = x*TMath::Cos(t.GetAlpha())-y*TMath::Sin(t.GetAlpha()); 
869     xyz1[1] = +x*TMath::Sin(t.GetAlpha())+y*TMath::Cos(t.GetAlpha());
870     xyz1[2] = z;
871     AliKalmanTrack::MeanMaterialBudget(xyz0,xyz1,param);        
872     rho = param[0];
873     radLength = param[1];   // get mean propagation parameters
874     //
875     // propagate nad update
876     //
877     sector = t.GetSector();
878     //    for (Int_t itime=GetTimeBinsPerPlane()-1;itime>=0;itime--) {
879     for (Int_t itime=0 ;itime<GetTimeBinsPerPlane();itime++) {
880       Int_t    ilayer = GetGlobalTimeBin(0, iplane,itime);
881       expectedNumberOfClusters++;       
882       t.fNExpected++;
883       if (t.fX>345) t.fNExpectedLast++;
884       AliTRDpropagationLayer& timeBin=*(fTrSec[sector]->GetLayer(ilayer));
885       AliTRDcluster *cl=0;
886       UInt_t index=0;
887       Double_t maxChi2=fgkMaxChi2;
888       x = timeBin.GetX();
889       if (timeBin) {
890         AliTRDcluster * cl0 = timeBin[0];
891         if (!cl0) continue;         // no clusters in given time bin
892         Int_t plane = fGeom->GetPlane(cl0->GetDetector());
893         if (plane>lastplane) continue;
894         Int_t timebin = cl0->GetLocalTimeBin();
895         AliTRDcluster * cl2= GetCluster(&t,plane, timebin,index);
896         //
897         if (cl2) {
898           cl =cl2;      
899           Double_t h01 = GetTiltFactor(cl);
900           maxChi2=t.GetPredictedChi2(cl,h01);
901         }       
902         if (cl) {
903           //      if (cl->GetNPads()<5) 
904           Double_t dxsample = timeBin.GetdX();
905           t.SetSampledEdx(TMath::Abs(cl->GetQ()/dxsample)); 
906           Double_t h01 = GetTiltFactor(cl);
907           Int_t det = cl->GetDetector();    
908           Int_t plane = fGeom->GetPlane(det);
909           if (t.fX>345){
910             t.fNLast++;
911             t.fChi2Last+=maxChi2;
912           }
913           Double_t xcluster = cl->GetX();
914           t.PropagateTo(xcluster,radLength,rho);
915           if(!t.UpdateMI(cl,maxChi2,index,h01,plane)) {
916           }
917         }                       
918       }
919     } 
920   }
921
922   return expectedNumberOfClusters;  
923
924 }                
925
926 //_____________________________________________________________________________
927 Int_t AliTRDtracker::FollowBackProlongation(AliTRDtrack& t)
928 {
929   //  
930   // Starting from current radial position of track <t> this function
931   // extrapolates the track up to outer timebin and in the sensitive
932   // layers confirms prolongation if a close cluster is found. 
933   // Returns the number of clusters expected to be found in sensitive layers
934   // Use GEO manager for material Description
935   //
936
937   Int_t sector;
938   Int_t clusters[1000];
939   for (Int_t i=0;i<1000;i++) clusters[i]=-1;
940   Double_t radLength = 0.0;
941   Double_t rho = 0.0;
942   Int_t expectedNumberOfClusters = 0;
943   Float_t ratio0=0;
944   AliTRDtracklet tracklet;
945   //
946   //
947   for (Int_t iplane = 0; iplane<AliESDtrack::kNPlane; iplane++){
948     Int_t    row0    = GetGlobalTimeBin(0, iplane,GetTimeBinsPerPlane()-1);
949     Int_t    rowlast = GetGlobalTimeBin(0, iplane,0);
950     //
951     Double_t currentx  = fTrSec[0]->GetLayer(row0)->GetX();
952     if (currentx<t.GetX()) continue;
953     //
954     //       propagate closer to chamber if neccessary 
955     //
956     if (currentx > fgkMaxStep +t.GetX()){
957       if (!PropagateToX(t, currentx-fgkMaxStep, fgkMaxStep)) break;
958     }
959     if (!AdjustSector(&t)) break;
960     if (TMath::Abs(t.GetSnp())>fgkMaxSnp) break;
961     //
962     // get material budget inside of chamber
963     //
964     Double_t xyz0[3],xyz1[3],param[7],x,y,z;
965     t.GetGlobalXYZ(xyz0[0],xyz0[1],xyz0[2]);   //starting global position
966     // end global position
967     x = fTrSec[0]->GetLayer(rowlast)->GetX();
968     if (!t.GetProlongation(x,y,z)) break;
969     xyz1[0] = x*TMath::Cos(t.GetAlpha())-y*TMath::Sin(t.GetAlpha()); 
970     xyz1[1] = +x*TMath::Sin(t.GetAlpha())+y*TMath::Cos(t.GetAlpha());
971     xyz1[2] = z;
972     AliKalmanTrack::MeanMaterialBudget(xyz0,xyz1,param);        
973     rho = param[0];
974     radLength = param[1];   // get mean propagation parameters
975     //
976     // Find clusters
977     //
978     sector = t.GetSector();
979     Float_t  ncl   = FindClusters(sector,row0,rowlast,&t,clusters,tracklet);
980     if (tracklet.GetN()<GetTimeBinsPerPlane()/3) continue;
981     //
982     // Propagate and update track
983     //
984     for (Int_t itime= GetTimeBinsPerPlane()-1;itime>=0;itime--) {
985       Int_t    ilayer = GetGlobalTimeBin(0, iplane,itime);
986       expectedNumberOfClusters++;       
987       t.fNExpected++;
988       if (t.fX>345) t.fNExpectedLast++;
989       AliTRDpropagationLayer& timeBin=*(fTrSec[sector]->GetLayer(ilayer));
990       AliTRDcluster *cl=0;
991       UInt_t index=0;
992       Double_t maxChi2=fgkMaxChi2;
993       x = timeBin.GetX();
994       //
995       if (timeBin) {    
996         if (clusters[ilayer]>0) {
997           index = clusters[ilayer];
998           cl    = (AliTRDcluster*)GetCluster(index);
999           Double_t h01 = GetTiltFactor(cl);
1000           maxChi2=t.GetPredictedChi2(cl,h01);          
1001         }
1002         
1003         if (cl) {
1004           //      if (cl->GetNPads()<5) 
1005           Double_t dxsample = timeBin.GetdX();
1006           t.SetSampledEdx(TMath::Abs(cl->GetQ()/dxsample)); 
1007           Double_t h01 = GetTiltFactor(cl);
1008           Int_t det = cl->GetDetector();    
1009           Int_t plane = fGeom->GetPlane(det);
1010           if (t.fX>345){
1011             t.fNLast++;
1012             t.fChi2Last+=maxChi2;
1013           }
1014           Double_t xcluster = cl->GetX();
1015           t.PropagateTo(xcluster,radLength,rho);
1016           if(!t.UpdateMI(cl,maxChi2,index,h01,plane)) {
1017             if(!t.Update(cl,maxChi2,index,h01)) {
1018             }
1019           }  
1020           //      
1021           // reset material budget if 2 consecutive gold
1022           if (plane>0) 
1023             if (t.fTracklets[plane].GetN()+t.fTracklets[plane-1].GetN()>20){
1024               t.fBudget[2] = 0;
1025             }     
1026         }                       
1027       }
1028     }
1029     ratio0 = ncl/Float_t(fTimeBinsPerPlane);
1030     Float_t  ratio1 = Float_t(t.fN+1)/Float_t(t.fNExpected+1.); 
1031     if (tracklet.GetChi2()<18.&&ratio0>0.8 && ratio1>0.6 && ratio0+ratio1>1.5 && t.GetNCross()==0 && TMath::Abs(t.GetSnp())<0.85&&t.fN>20){
1032       t.MakeBackupTrack();                            // make backup of the track until is gold
1033     }
1034     
1035   }
1036
1037   return expectedNumberOfClusters;  
1038
1039 }         
1040
1041 //_____________________________________________________________________________
1042 Int_t  AliTRDtracker::PropagateToX(AliTRDtrack& t, Double_t xToGo, Double_t maxStep)
1043 {
1044   //
1045   // Starting from current radial position of track <t> this function
1046   // extrapolates the track up to radial position <xToGo>. 
1047   // Returns 1 if track reaches the plane, and 0 otherwise 
1048   //
1049
1050   const Double_t kEpsilon = 0.00001;
1051   //  Double_t tanmax = TMath::Tan(0.5*AliTRDgeometry::GetAlpha()); 
1052   Double_t xpos     = t.GetX();
1053   Double_t dir      = (xpos<xToGo) ? 1.:-1.;
1054   //
1055   while ( (xToGo-xpos)*dir > kEpsilon){
1056     Double_t step = dir*TMath::Min(TMath::Abs(xToGo-xpos), maxStep);
1057     //
1058     Double_t xyz0[3],xyz1[3],param[7],x,y,z;
1059     t.GetGlobalXYZ(xyz0[0],xyz0[1],xyz0[2]);   //starting global position
1060     x    = xpos+step;
1061     //
1062     if (!t.GetProlongation(x,y,z)) return 0;   // no prolongation
1063     //
1064     xyz1[0] = x*TMath::Cos(t.GetAlpha())-y*TMath::Sin(t.GetAlpha()); 
1065     xyz1[1] = +x*TMath::Sin(t.GetAlpha())+y*TMath::Cos(t.GetAlpha());
1066     xyz1[2] = z;
1067     //
1068     AliKalmanTrack::MeanMaterialBudget(xyz0,xyz1,param);        
1069     if (!t.PropagateTo(x,param[1],param[0])) return 0;
1070     AdjustSector(&t);
1071     xpos = t.GetX();
1072   }
1073
1074   return 1;
1075
1076 }
1077
1078 //_____________________________________________________________________________
1079 Int_t AliTRDtracker::LoadClusters(TTree *cTree)
1080 {
1081   //
1082   // Fills clusters into TRD tracking_sectors 
1083   // Note that the numbering scheme for the TRD tracking_sectors 
1084   // differs from that of TRD sectors
1085   //
1086
1087   cout<<"\n Read Sectors  clusters"<<endl;
1088   if (ReadClusters(fClusters,cTree)) {
1089      Error("LoadClusters","Problem with reading the clusters !");
1090      return 1;
1091   }
1092   Int_t ncl=fClusters->GetEntriesFast();
1093   fNclusters=ncl;
1094   cout<<"\n LoadSectors: sorting "<<ncl<<" clusters"<<endl;
1095               
1096   UInt_t index;
1097   for (Int_t ichamber=0;ichamber<5;ichamber++)
1098     for (Int_t isector=0;isector<18;isector++){
1099       fHoles[ichamber][isector]=kTRUE;
1100     }
1101
1102
1103   while (ncl--) {
1104 //    printf("\r %d left  ",ncl); 
1105     AliTRDcluster *c=(AliTRDcluster*)fClusters->UncheckedAt(ncl);
1106     Int_t detector=c->GetDetector();
1107     Int_t localTimeBin=c->GetLocalTimeBin();
1108     Int_t sector=fGeom->GetSector(detector);
1109     Int_t plane=fGeom->GetPlane(detector);
1110       
1111     Int_t trackingSector = CookSectorIndex(sector);
1112     if (c->GetLabel(0)>0){
1113       Int_t chamber = fGeom->GetChamber(detector);
1114       fHoles[chamber][trackingSector]=kFALSE;
1115     }
1116
1117     Int_t gtb = fTrSec[trackingSector]->CookTimeBinIndex(plane,localTimeBin);
1118     if(gtb < 0) continue; 
1119     Int_t layer = fTrSec[trackingSector]->GetLayerNumber(gtb);
1120
1121     index=ncl;
1122     //
1123     // apply pos correction
1124     Transform(c);    
1125     fTrSec[trackingSector]->GetLayer(layer)->InsertCluster(c,index);
1126   }    
1127
1128   return 0;
1129
1130 }
1131
1132 //_____________________________________________________________________________
1133 void AliTRDtracker::UnloadClusters() 
1134
1135   //
1136   // Clears the arrays of clusters and tracks. Resets sectors and timebins 
1137   //
1138
1139   Int_t i, nentr;
1140
1141   nentr = fClusters->GetEntriesFast();
1142   for (i = 0; i < nentr; i++) delete fClusters->RemoveAt(i);
1143   fNclusters = 0;
1144
1145   nentr = fSeeds->GetEntriesFast();
1146   for (i = 0; i < nentr; i++) delete fSeeds->RemoveAt(i);
1147
1148   nentr = fTracks->GetEntriesFast();
1149   for (i = 0; i < nentr; i++) delete fTracks->RemoveAt(i);
1150
1151   Int_t nsec = AliTRDgeometry::kNsect;
1152
1153   for (i = 0; i < nsec; i++) {    
1154     for(Int_t pl = 0; pl < fTrSec[i]->GetNumberOfLayers(); pl++) {
1155       fTrSec[i]->GetLayer(pl)->Clear();
1156     }
1157   }
1158
1159 }
1160
1161 //_____________________________________________________________________________
1162 void AliTRDtracker::MakeSeedsMI(Int_t /*inner*/, Int_t /*outer*/, AliESD * esd)
1163 {
1164   //
1165   // Creates  seeds using clusters between  position inner plane  and outer plane 
1166   //
1167
1168   const Double_t kMaxTheta = 1;
1169   const Double_t kMaxPhi   = 2.0;
1170   //
1171   const Double_t kRoad0y  =  6;     // road for middle cluster 
1172   const Double_t kRoad0z  =  8.5;   // road for middle cluster 
1173   //
1174   const Double_t kRoad1y  =  2;    // road in y for seeded cluster
1175   const Double_t kRoad1z  =  20;    // road in z for seeded cluster
1176   //
1177   const Double_t kRoad2y  =  3;    // road in y for extrapolated cluster
1178   const Double_t kRoad2z  =  20;   // road in z for extrapolated cluster
1179   const Int_t    kMaxSeed  = 3000;
1180   Int_t maxSec=AliTRDgeometry::kNsect;  
1181
1182   //
1183   // linear fitters in planes
1184   TLinearFitter fitterTC(2,"hyp2");  // fitting with tilting pads - kz fixed - kz= Z/x, + vertex const
1185   TLinearFitter fitterT2(4,"hyp4");  // fitting with tilting pads - kz not fixed
1186   fitterTC.StoreData(kTRUE);
1187   fitterT2.StoreData(kTRUE);
1188   AliRieman rieman(1000);   // rieman fitter
1189   AliRieman rieman2(1000);   // rieman fitter
1190   //  
1191   // find the maximal and minimal layer for the planes
1192   //
1193   Int_t layers[6][2];
1194   AliTRDpropagationLayer* reflayers[6];
1195   for (Int_t i=0;i<6;i++){layers[i][0]=10000; layers[i][1]=0;}
1196   for (Int_t ns=0;ns<maxSec;ns++){
1197     for (Int_t ilayer=0;ilayer<fTrSec[ns]->GetNumberOfLayers();ilayer++){
1198       AliTRDpropagationLayer& layer=*(fTrSec[ns]->GetLayer(ilayer));
1199       if (layer==0) continue;
1200       Int_t det   = layer[0]->GetDetector();    
1201       Int_t plane = fGeom->GetPlane(det);
1202       if (ilayer<layers[plane][0]) layers[plane][0] = ilayer;
1203       if (ilayer>layers[plane][1]) layers[plane][1] = ilayer;
1204     }
1205   }
1206   //
1207   AliTRDpadPlane *padPlane = AliTRDCommonParam::Instance()->GetPadPlane(0,0);
1208   Double_t h01 = TMath::Tan(-TMath::Pi() / 180.0 * padPlane->GetTiltingAngle());
1209   Double_t hL[6];         // tilting angle
1210   Double_t xcl[6];        // x - position of reference cluster
1211   Double_t ycl[6];        // y - position of reference cluster
1212   Double_t zcl[6];        // z - position of reference cluster
1213   AliTRDcluster *cl[6]={0,0,0,0,0,0};    // seeding clusters
1214   Float_t padlength[6]={10,10,10,10,10,10};   //current pad-length 
1215   Double_t chi2R =0, chi2Z=0;
1216   Double_t chi2RF =0, chi2ZF=0;
1217   //
1218   Int_t nclusters;     // total number of clusters
1219   for (Int_t i=0;i<6;i++) {hL[i]=h01; if (i%2==1) hL[i]*=-1.;}
1220   //
1221   //
1222   //         registered seed
1223   AliTRDseed *pseed = new AliTRDseed[kMaxSeed*6];
1224   AliTRDseed *seed[kMaxSeed];
1225   for (Int_t iseed=0;iseed<kMaxSeed;iseed++) seed[iseed]= &pseed[iseed*6];
1226   AliTRDseed *cseed = seed[0];
1227   // 
1228   Double_t   seedquality[kMaxSeed];  
1229   Double_t   seedquality2[kMaxSeed];  
1230   Double_t   seedparams[kMaxSeed][7];
1231   Int_t      seedlayer[kMaxSeed];
1232   Int_t      registered =0;
1233   Int_t      sort[kMaxSeed];
1234   //
1235   // seeding part
1236   //
1237   for (Int_t ns = 0; ns<maxSec; ns++){         //loop over sectors
1238   //for (Int_t ns = 0; ns<5; ns++){         //loop over sectors
1239     registered = 0;   // reset registerd seed counter
1240     cseed      = seed[registered];
1241     Float_t iter=0;
1242     for (Int_t sLayer=2; sLayer>=0;sLayer--){
1243       //for (Int_t dseed=5;dseed<15; dseed+=3){  //loop over central seeding time bins 
1244       iter+=1.;
1245       Int_t dseed = 5+Int_t(iter)*3;
1246       // Initialize seeding layers
1247       for (Int_t ilayer=0;ilayer<6;ilayer++){
1248         reflayers[ilayer] = fTrSec[ns]->GetLayer(layers[ilayer][1]-dseed);
1249         xcl[ilayer]       = reflayers[ilayer]->GetX();
1250       }      
1251       //
1252       Double_t xref                 = (xcl[sLayer+1] + xcl[sLayer+2])*0.5;      
1253       AliTRDpropagationLayer& layer0=*reflayers[sLayer+0];
1254       AliTRDpropagationLayer& layer1=*reflayers[sLayer+1];
1255       AliTRDpropagationLayer& layer2=*reflayers[sLayer+2];
1256       AliTRDpropagationLayer& layer3=*reflayers[sLayer+3];
1257       //
1258       Int_t maxn3  = layer3;
1259       for (Int_t icl3=0;icl3<maxn3;icl3++){
1260         AliTRDcluster *cl3 = layer3[icl3];
1261         if (!cl3) continue;     
1262         padlength[sLayer+3] = TMath::Sqrt(cl3->GetSigmaZ2()*12.);
1263         ycl[sLayer+3] = cl3->GetY();
1264         zcl[sLayer+3] = cl3->GetZ();
1265         Float_t yymin0 = ycl[sLayer+3] - 1- kMaxPhi *(xcl[sLayer+3]-xcl[sLayer+0]);
1266         Float_t yymax0 = ycl[sLayer+3] + 1+ kMaxPhi *(xcl[sLayer+3]-xcl[sLayer+0]);
1267         Int_t   maxn0 = layer0;  // 
1268         for (Int_t icl0=layer0.Find(yymin0);icl0<maxn0;icl0++){
1269           AliTRDcluster *cl0 = layer0[icl0];
1270           if (!cl0) continue;
1271           if (cl3->IsUsed()&&cl0->IsUsed()) continue;
1272           ycl[sLayer+0] = cl0->GetY();
1273           zcl[sLayer+0] = cl0->GetZ();
1274           if ( ycl[sLayer+0]>yymax0) break;
1275           Double_t tanphi   = (ycl[sLayer+3]-ycl[sLayer+0])/(xcl[sLayer+3]-xcl[sLayer+0]); 
1276           if (TMath::Abs(tanphi)>kMaxPhi) continue;
1277           Double_t tantheta = (zcl[sLayer+3]-zcl[sLayer+0])/(xcl[sLayer+3]-xcl[sLayer+0]); 
1278           if (TMath::Abs(tantheta)>kMaxTheta) continue; 
1279           padlength[sLayer+0] = TMath::Sqrt(cl0->GetSigmaZ2()*12.);
1280           //
1281           // expected position in 1 layer
1282           Double_t y1exp = ycl[sLayer+0]+(tanphi)  *(xcl[sLayer+1]-xcl[sLayer+0]);        
1283           Double_t z1exp = zcl[sLayer+0]+(tantheta)*(xcl[sLayer+1]-xcl[sLayer+0]);        
1284           Float_t yymin1 = y1exp - kRoad0y-tanphi;
1285           Float_t yymax1 = y1exp + kRoad0y+tanphi;
1286           Int_t   maxn1  = layer1;  // 
1287           //
1288           for (Int_t icl1=layer1.Find(yymin1);icl1<maxn1;icl1++){
1289             AliTRDcluster *cl1 = layer1[icl1];
1290             if (!cl1) continue;
1291             Int_t nusedCl = 0;
1292             if (cl3->IsUsed()) nusedCl++;
1293             if (cl0->IsUsed()) nusedCl++;
1294             if (cl1->IsUsed()) nusedCl++;
1295             if (nusedCl>1) continue;
1296             ycl[sLayer+1] = cl1->GetY();
1297             zcl[sLayer+1] = cl1->GetZ();
1298             if ( ycl[sLayer+1]>yymax1) break;
1299             if (TMath::Abs(ycl[sLayer+1]-y1exp)>kRoad0y+tanphi) continue;
1300             if (TMath::Abs(zcl[sLayer+1]-z1exp)>kRoad0z)        continue;
1301             padlength[sLayer+1] = TMath::Sqrt(cl1->GetSigmaZ2()*12.);
1302             //
1303             Double_t y2exp  = ycl[sLayer+0]+(tanphi)  *(xcl[sLayer+2]-xcl[sLayer+0])+(ycl[sLayer+1]-y1exp);       
1304             Double_t z2exp  = zcl[sLayer+0]+(tantheta)*(xcl[sLayer+2]-xcl[sLayer+0]);
1305             Int_t    index2 = layer2.FindNearestCluster(y2exp,z2exp,kRoad1y,  kRoad1z);
1306             if (index2<=0) continue; 
1307             AliTRDcluster *cl2 = (AliTRDcluster*)GetCluster(index2);
1308             padlength[sLayer+2] = TMath::Sqrt(cl2->GetSigmaZ2()*12.);
1309             ycl[sLayer+2] = cl2->GetY();
1310             zcl[sLayer+2] = cl2->GetZ();
1311             if (TMath::Abs(cl2->GetZ()-z2exp)>kRoad0z)        continue;
1312             //
1313             rieman.Reset();
1314             rieman.AddPoint(xcl[sLayer+0],ycl[sLayer+0],zcl[sLayer+0],1,10);
1315             rieman.AddPoint(xcl[sLayer+1],ycl[sLayer+1],zcl[sLayer+1],1,10);
1316             rieman.AddPoint(xcl[sLayer+3],ycl[sLayer+3],zcl[sLayer+3],1,10);        
1317             rieman.AddPoint(xcl[sLayer+2],ycl[sLayer+2],zcl[sLayer+2],1,10);
1318             rieman.Update();
1319             //
1320             // reset fitter
1321             for (Int_t iLayer=0;iLayer<6;iLayer++){
1322               cseed[iLayer].Reset();
1323             }     
1324             chi2Z =0.; chi2R=0.;
1325             for (Int_t iLayer=0;iLayer<4;iLayer++){
1326               cseed[sLayer+iLayer].fZref[0] = rieman.GetZat(xcl[sLayer+iLayer]);
1327               chi2Z += (cseed[sLayer+iLayer].fZref[0]- zcl[sLayer+iLayer])*
1328                 (cseed[sLayer+iLayer].fZref[0]- zcl[sLayer+iLayer]);
1329               cseed[sLayer+iLayer].fZref[1] = rieman.GetDZat(xcl[sLayer+iLayer]);             
1330               cseed[sLayer+iLayer].fYref[0] = rieman.GetYat(xcl[sLayer+iLayer]);
1331               chi2R += (cseed[sLayer+iLayer].fYref[0]- ycl[sLayer+iLayer])*
1332                 (cseed[sLayer+iLayer].fYref[0]- ycl[sLayer+iLayer]);
1333               cseed[sLayer+iLayer].fYref[1] = rieman.GetDYat(xcl[sLayer+iLayer]);
1334             }
1335             if (TMath::Sqrt(chi2R)>1./iter) continue;
1336             if (TMath::Sqrt(chi2Z)>7./iter) continue;
1337             //
1338             //
1339             //
1340             Float_t minmax[2]={-100,100};
1341             for (Int_t iLayer=0;iLayer<4;iLayer++){
1342               Float_t max = zcl[sLayer+iLayer]+padlength[sLayer+iLayer]*0.5+1 -cseed[sLayer+iLayer].fZref[0];
1343               if (max<minmax[1]) minmax[1]=max; 
1344               Float_t min = zcl[sLayer+iLayer]-padlength[sLayer+iLayer]*0.5-1 -cseed[sLayer+iLayer].fZref[0];
1345               if (min>minmax[0]) minmax[0]=min; 
1346             }
1347             Bool_t isFake = kFALSE; 
1348             if (cl0->GetLabel(0)!=cl3->GetLabel(0)) isFake = kTRUE;
1349             if (cl1->GetLabel(0)!=cl3->GetLabel(0)) isFake = kTRUE;
1350             if (cl2->GetLabel(0)!=cl3->GetLabel(0)) isFake = kTRUE;
1351             if (AliTRDReconstructor::StreamLevel()>0){
1352               if ((!isFake) || (icl3%10)==0 ){  //debugging print
1353                 TTreeSRedirector& cstream = *fDebugStreamer;
1354                 cstream<<"Seeds0"<<
1355                   "isFake="<<isFake<<
1356                   "Cl0.="<<cl0<<
1357                   "Cl1.="<<cl1<<
1358                   "Cl2.="<<cl2<<
1359                   "Cl3.="<<cl3<<
1360                   "Xref="<<xref<<
1361                   "X0="<<xcl[sLayer+0]<<
1362                   "X1="<<xcl[sLayer+1]<<
1363                   "X2="<<xcl[sLayer+2]<<
1364                   "X3="<<xcl[sLayer+3]<<
1365                   "Y2exp="<<y2exp<<
1366                   "Z2exp="<<z2exp<<
1367                   "Chi2R="<<chi2R<<
1368                   "Chi2Z="<<chi2Z<<             
1369                   "Seed0.="<<&cseed[sLayer+0]<<
1370                   "Seed1.="<<&cseed[sLayer+1]<<
1371                   "Seed2.="<<&cseed[sLayer+2]<<
1372                   "Seed3.="<<&cseed[sLayer+3]<<
1373                   "Zmin="<<minmax[0]<<
1374                   "Zmax="<<minmax[1]<<
1375                   "\n";
1376               }
1377             }
1378             
1379             //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1380             //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1381             //<<<<<<<<<<<<<<<<<<    FIT SEEDING PART                  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1382             //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1383             cl[sLayer+0] = cl0;
1384             cl[sLayer+1] = cl1;
1385             cl[sLayer+2] = cl2;
1386             cl[sLayer+3] = cl3;
1387             Bool_t isOK=kTRUE;
1388             for (Int_t jLayer=0;jLayer<4;jLayer++){
1389               cseed[sLayer+jLayer].fTilt = hL[sLayer+jLayer];
1390               cseed[sLayer+jLayer].fPadLength = padlength[sLayer+jLayer];
1391               cseed[sLayer+jLayer].fX0   = xcl[sLayer+jLayer];
1392               for (Int_t iter=0; iter<2; iter++){
1393                 //
1394                 // in iteration 0 we try only one pad-row
1395                 // if quality not sufficient we try 2 pad-rows - about 5% of tracks cross 2 pad-rows
1396                 //
1397                 AliTRDseed tseed = cseed[sLayer+jLayer];
1398                 Float_t    roadz  = padlength[sLayer+jLayer]*0.5;
1399                 if (iter>0) roadz = padlength[sLayer+jLayer];
1400                 //
1401                 Float_t quality =10000;
1402                 for (Int_t iTime=2;iTime<20;iTime++){ 
1403                   AliTRDpropagationLayer& layer = *(fTrSec[ns]->GetLayer(layers[sLayer+jLayer][1]-iTime));
1404                   Double_t dxlayer= layer.GetX()-xcl[sLayer+jLayer];             
1405                   Double_t zexp   = cl[sLayer+jLayer]->GetZ() ;
1406                   if (iter>0){
1407                     // try 2 pad-rows in second iteration
1408                     zexp  = tseed.fZref[0]+ tseed.fZref[1]*dxlayer;
1409                     if (zexp>cl[sLayer+jLayer]->GetZ()) zexp = cl[sLayer+jLayer]->GetZ()+padlength[sLayer+jLayer]*0.5;
1410                     if (zexp<cl[sLayer+jLayer]->GetZ()) zexp = cl[sLayer+jLayer]->GetZ()-padlength[sLayer+jLayer]*0.5;
1411                   }
1412                   //
1413                   Double_t yexp  =  tseed.fYref[0]+ 
1414                     tseed.fYref[1]*dxlayer;
1415                   Int_t    index = layer.FindNearestCluster(yexp,zexp,kRoad1y, roadz);
1416                   if (index<=0) continue; 
1417                   AliTRDcluster *cl = (AliTRDcluster*)GetCluster(index);              
1418                   //
1419                   tseed.fIndexes[iTime]  = index;
1420                   tseed.fClusters[iTime] = cl;   // register cluster
1421                   tseed.fX[iTime] = dxlayer;     // register cluster
1422                   tseed.fY[iTime] = cl->GetY();  // register cluster
1423                   tseed.fZ[iTime] = cl->GetZ();  // register cluster
1424                 } 
1425                 tseed.Update();
1426                 //count the number of clusters and distortions into quality
1427                 Float_t dangle = tseed.fYfit[1]-tseed.fYref[1];
1428                 Float_t tquality   = (18-tseed.fN2)/2. + TMath::Abs(dangle)/0.1+
1429                   TMath::Abs(tseed.fYfit[0]-tseed.fYref[0])/0.2+
1430                   2.*TMath::Abs(tseed.fMeanz-tseed.fZref[0])/padlength[jLayer];
1431                 if (iter==0 && tseed.IsOK()) {
1432                   cseed[sLayer+jLayer] = tseed;
1433                   quality = tquality;
1434                   if (tquality<5) break;  
1435                 }
1436                 if (tseed.IsOK() && tquality<quality)
1437                   cseed[sLayer+jLayer] = tseed;                         
1438               }
1439               if (!cseed[sLayer+jLayer].IsOK()){
1440                 isOK = kFALSE;
1441                 break;
1442               }                   
1443               cseed[sLayer+jLayer].CookLabels();
1444               cseed[sLayer+jLayer].UpdateUsed();
1445               nusedCl+= cseed[sLayer+jLayer].fNUsed;
1446               if (nusedCl>25){
1447                 isOK = kFALSE;
1448                 break;
1449               }     
1450             }
1451             //
1452             if (!isOK) continue;
1453             nclusters=0;
1454             for (Int_t iLayer=0;iLayer<4;iLayer++){
1455               if (cseed[sLayer+iLayer].IsOK()){
1456                 nclusters+=cseed[sLayer+iLayer].fN2;        
1457               }
1458             }
1459             // 
1460             // iteration 0
1461             rieman.Reset();
1462             for (Int_t iLayer=0;iLayer<4;iLayer++){
1463               rieman.AddPoint(xcl[sLayer+iLayer],cseed[sLayer+iLayer].fYfitR[0],
1464                               cseed[sLayer+iLayer].fZProb,1,10);
1465             }
1466             rieman.Update();
1467             //
1468             //
1469             chi2R =0; chi2Z=0;
1470             for (Int_t iLayer=0;iLayer<4;iLayer++){
1471               cseed[sLayer+iLayer].fYref[0] = rieman.GetYat(xcl[sLayer+iLayer]);
1472               chi2R += (cseed[sLayer+iLayer].fYref[0]-cseed[sLayer+iLayer].fYfitR[0])*
1473                 (cseed[sLayer+iLayer].fYref[0]-cseed[sLayer+iLayer].fYfitR[0]);
1474               cseed[sLayer+iLayer].fYref[1] = rieman.GetDYat(xcl[sLayer+iLayer]);
1475               cseed[sLayer+iLayer].fZref[0] = rieman.GetZat(xcl[sLayer+iLayer]);
1476               chi2Z += (cseed[sLayer+iLayer].fZref[0]- cseed[sLayer+iLayer].fMeanz)*
1477                 (cseed[sLayer+iLayer].fZref[0]- cseed[sLayer+iLayer].fMeanz);
1478               cseed[sLayer+iLayer].fZref[1] = rieman.GetDZat(xcl[sLayer+iLayer]);
1479             }
1480             Double_t curv = rieman.GetC();
1481             //
1482             // likelihoods
1483             //
1484             Double_t sumda = 
1485               TMath::Abs(cseed[sLayer+0].fYfitR[1]- cseed[sLayer+0].fYref[1])+
1486               TMath::Abs(cseed[sLayer+1].fYfitR[1]- cseed[sLayer+1].fYref[1])+
1487               TMath::Abs(cseed[sLayer+2].fYfitR[1]- cseed[sLayer+2].fYref[1])+
1488               TMath::Abs(cseed[sLayer+3].fYfitR[1]- cseed[sLayer+3].fYref[1]);
1489             Double_t likea = TMath::Exp(-sumda*10.6);
1490             Double_t likechi2 = 0.0000000001;
1491             if (chi2R<0.5) likechi2+=TMath::Exp(-TMath::Sqrt(chi2R)*7.73);
1492             Double_t likechi2z = TMath::Exp(-chi2Z*0.088)/TMath::Exp(-chi2Z*0.019);
1493             Double_t likeN    = TMath::Exp(-(72-nclusters)*0.19);
1494             Double_t like     = likea*likechi2*likechi2z*likeN;
1495             //
1496             Double_t likePrimY = TMath::Exp(-TMath::Abs(cseed[sLayer+0].fYref[1]-130*curv)*1.9);
1497             Double_t likePrimZ = TMath::Exp(-TMath::Abs(cseed[sLayer+0].fZref[1]-
1498                                                         cseed[sLayer+0].fZref[0]/xcl[sLayer+0])*5.9);
1499             Double_t likePrim  = TMath::Max(likePrimY*likePrimZ,0.0005);
1500                                             
1501             seedquality[registered]  = like; 
1502             seedlayer[registered]    = sLayer;
1503             if (TMath::Log(0.000000000000001+like)<-15) continue;
1504             AliTRDseed seedb[6];
1505             for (Int_t iLayer=0;iLayer<6;iLayer++){
1506               seedb[iLayer] = cseed[iLayer]; 
1507             }
1508             //
1509             //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1510             //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1511             //<<<<<<<<<<<<<<<   FULL TRACK FIT PART         <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1512             //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1513             //
1514             Int_t nlayers            = 0;
1515             Int_t nusedf             = 0;
1516             Int_t findable           = 0;
1517             //
1518             // add new layers  - avoid long extrapolation
1519             //
1520             Int_t tLayer[2]={0,0};
1521             if (sLayer==2) {tLayer[0]=1; tLayer[1]=0;}
1522             if (sLayer==1) {tLayer[0]=5; tLayer[1]=0;}
1523             if (sLayer==0) {tLayer[0]=4; tLayer[1]=5;}
1524             //
1525             for (Int_t iLayer=0;iLayer<2;iLayer++){
1526               Int_t jLayer = tLayer[iLayer];      // set tracking layer       
1527               cseed[jLayer].Reset();
1528               cseed[jLayer].fTilt    = hL[jLayer];
1529               cseed[jLayer].fPadLength = padlength[jLayer];
1530               cseed[jLayer].fX0      = xcl[jLayer];
1531               // get pad length and rough cluster
1532               Int_t    indexdummy = reflayers[jLayer]->FindNearestCluster(cseed[jLayer].fYref[0], 
1533                                                                           cseed[jLayer].fZref[0],kRoad2y,kRoad2z);
1534               if (indexdummy<=0) continue; 
1535               AliTRDcluster *cldummy = (AliTRDcluster*)GetCluster(indexdummy);
1536               padlength[jLayer]      = TMath::Sqrt(cldummy->GetSigmaZ2()*12.);
1537             }
1538             AliTRDseed::FitRiemanTilt(cseed, kTRUE);
1539             //
1540             for (Int_t iLayer=0;iLayer<2;iLayer++){
1541               Int_t jLayer = tLayer[iLayer];      // set tracking layer 
1542               if ( (jLayer==0) && !(cseed[1].IsOK())) continue;  // break not allowed
1543               if ( (jLayer==5) && !(cseed[4].IsOK())) continue;  // break not allowed
1544               Float_t  zexp  = cseed[jLayer].fZref[0];
1545               Double_t zroad =  padlength[jLayer]*0.5+1.;
1546               //
1547               // 
1548               for (Int_t iter=0;iter<2;iter++){
1549                 AliTRDseed tseed = cseed[jLayer];
1550                 Float_t quality = 10000;
1551                 for (Int_t iTime=2;iTime<20;iTime++){ 
1552                   AliTRDpropagationLayer& layer = *(fTrSec[ns]->GetLayer(layers[jLayer][1]-iTime));
1553                   Double_t dxlayer     = layer.GetX()-xcl[jLayer];
1554                   Double_t yexp        = tseed.fYref[0]+tseed.fYref[1]*dxlayer;
1555                   Float_t  yroad       = kRoad1y;
1556                   Int_t    index = layer.FindNearestCluster(yexp,zexp, yroad, zroad);
1557                   if (index<=0) continue; 
1558                   AliTRDcluster *cl = (AliTRDcluster*)GetCluster(index);              
1559                   //
1560                   tseed.fIndexes[iTime]  = index;
1561                   tseed.fClusters[iTime] = cl;   // register cluster
1562                   tseed.fX[iTime] = dxlayer;     // register cluster
1563                   tseed.fY[iTime] = cl->GetY();  // register cluster
1564                   tseed.fZ[iTime] = cl->GetZ();  // register cluster
1565                 }             
1566                 tseed.Update();
1567                 if (tseed.IsOK()){
1568                   Float_t dangle = tseed.fYfit[1]-tseed.fYref[1];
1569                   Float_t tquality   = (18-tseed.fN2)/2. + TMath::Abs(dangle)/0.1+                
1570                     TMath::Abs(tseed.fYfit[0]-tseed.fYref[0])/0.2+ 
1571                     2.*TMath::Abs(tseed.fMeanz-tseed.fZref[0])/padlength[jLayer];
1572                   //
1573                   if (tquality<quality){
1574                     cseed[jLayer]=tseed;
1575                     quality = tquality;
1576                   }
1577                 }
1578                 zroad*=2.;
1579               }
1580               if ( cseed[jLayer].IsOK()){
1581                 cseed[jLayer].CookLabels();
1582                 cseed[jLayer].UpdateUsed();
1583                 nusedf+= cseed[jLayer].fNUsed;
1584                 AliTRDseed::FitRiemanTilt(cseed, kTRUE);
1585               }
1586             }
1587             //
1588             //
1589             // make copy
1590             AliTRDseed bseed[6];
1591             for (Int_t jLayer=0;jLayer<6;jLayer++){
1592               bseed[jLayer] = cseed[jLayer];
1593             }       
1594             Float_t lastquality = 10000;
1595             Float_t lastchi2    = 10000;
1596             Float_t chi2        = 1000;
1597
1598             //
1599             for (Int_t iter =0; iter<4;iter++){
1600               //
1601               // sort tracklets according "quality", try to "improve" 4 worst 
1602               //
1603               Float_t sumquality = 0;
1604               Float_t squality[6];
1605               Int_t   sortindexes[6];
1606               for (Int_t jLayer=0;jLayer<6;jLayer++){
1607                 if (bseed[jLayer].IsOK()){ 
1608                   AliTRDseed &tseed = bseed[jLayer];
1609                   Double_t zcor  =  tseed.fTilt*(tseed.fZProb-tseed.fZref[0]);
1610                   Float_t dangle = tseed.fYfit[1]-tseed.fYref[1];
1611                   Float_t tquality  = (18-tseed.fN2)/2. + TMath::Abs(dangle)/0.1+                 
1612                     TMath::Abs(tseed.fYfit[0]-(tseed.fYref[0]-zcor))/0.2+ 
1613                     2.*TMath::Abs(tseed.fMeanz-tseed.fZref[0])/padlength[jLayer];
1614                   squality[jLayer] = tquality;
1615                 }
1616                 else  squality[jLayer]=-1;
1617                 sumquality +=squality[jLayer];
1618               }
1619
1620               if (sumquality>=lastquality ||  chi2>lastchi2) break;
1621               lastquality = sumquality;  
1622               lastchi2    = chi2;
1623               if (iter>0){
1624                 for (Int_t jLayer=0;jLayer<6;jLayer++){
1625                   cseed[jLayer] = bseed[jLayer];
1626                 }
1627               }
1628               TMath::Sort(6,squality,sortindexes,kFALSE);
1629               //
1630               //
1631               for (Int_t jLayer=5;jLayer>1;jLayer--){
1632                 Int_t bLayer = sortindexes[jLayer];
1633                 AliTRDseed tseed = bseed[bLayer];
1634                 for (Int_t iTime=2;iTime<20;iTime++){ 
1635                   AliTRDpropagationLayer& layer = *(fTrSec[ns]->GetLayer(layers[bLayer][1]-iTime));
1636                   Double_t dxlayer= layer.GetX()-xcl[bLayer];
1637                   //
1638                   Double_t zexp  =  tseed.fZref[0];
1639                   Double_t zcor  =  tseed.fTilt*(tseed.fZProb-tseed.fZref[0]);
1640                   //
1641                   Float_t  roadz = padlength[bLayer]+1;
1642                   if (TMath::Abs(tseed.fZProb-zexp)> padlength[bLayer]*0.5) {roadz = padlength[bLayer]*0.5;}
1643                   if (tseed.fZfit[1]*tseed.fZref[1]<0) {roadz = padlength[bLayer]*0.5;}
1644                   if (TMath::Abs(tseed.fZProb-zexp)<0.1*padlength[bLayer]) {
1645                     zexp = tseed.fZProb; 
1646                     roadz = padlength[bLayer]*0.5;
1647                   }
1648                   //
1649                   Double_t yexp  =  tseed.fYref[0]+ 
1650                     tseed.fYref[1]*dxlayer-zcor;
1651                   Int_t    index = layer.FindNearestCluster(yexp,zexp,kRoad1y, roadz);
1652                   if (index<=0) continue; 
1653                   AliTRDcluster *cl = (AliTRDcluster*)GetCluster(index);              
1654                   //
1655                   tseed.fIndexes[iTime]  = index;
1656                   tseed.fClusters[iTime] = cl;   // register cluster
1657                   tseed.fX[iTime] = dxlayer;     // register cluster
1658                   tseed.fY[iTime] = cl->GetY();  // register cluster
1659                   tseed.fZ[iTime] = cl->GetZ();  // register cluster
1660                 } 
1661                 tseed.Update();
1662                 if (tseed.IsOK()) {
1663                   Float_t dangle = tseed.fYfit[1]-tseed.fYref[1];
1664                   Double_t zcor  =  tseed.fTilt*(tseed.fZProb-tseed.fZref[0]);
1665                   //
1666                   Float_t tquality   = (18-tseed.fN2)/2. + TMath::Abs(dangle)/0.1+                
1667                     TMath::Abs(tseed.fYfit[0]-(tseed.fYref[0]-zcor))/0.2+ 
1668                     2.*TMath::Abs(tseed.fMeanz-tseed.fZref[0])/padlength[jLayer];
1669                   //
1670                   if (tquality<squality[bLayer])
1671                     bseed[bLayer] = tseed;
1672                 }
1673               }
1674               chi2 = AliTRDseed::FitRiemanTilt(bseed, kTRUE);
1675             }
1676             //
1677             //
1678             //
1679             nclusters  = 0;
1680             nlayers    = 0;
1681             findable   = 0;
1682             for (Int_t iLayer=0;iLayer<6;iLayer++) {
1683               if (TMath::Abs(cseed[iLayer].fYref[0]/cseed[iLayer].fX0)<0.15)
1684                 findable++;
1685               if (cseed[iLayer].IsOK()){
1686                 nclusters+=cseed[iLayer].fN2;       
1687                 nlayers++;
1688               }
1689             }
1690             if (nlayers<3) continue;
1691             rieman.Reset();
1692             for (Int_t iLayer=0;iLayer<6;iLayer++){
1693               if (cseed[iLayer].IsOK()) rieman.AddPoint(xcl[iLayer],cseed[iLayer].fYfitR[0],
1694                                                                    cseed[iLayer].fZProb,1,10);
1695             }
1696             rieman.Update();
1697             //
1698             chi2RF =0;
1699             chi2ZF =0;
1700             for (Int_t iLayer=0;iLayer<6;iLayer++){
1701               if (cseed[iLayer].IsOK()){
1702                 cseed[iLayer].fYref[0] = rieman.GetYat(xcl[iLayer]);
1703                 chi2RF += (cseed[iLayer].fYref[0]-cseed[iLayer].fYfitR[0])*
1704                   (cseed[iLayer].fYref[0]-cseed[iLayer].fYfitR[0]);
1705                 cseed[iLayer].fYref[1] = rieman.GetDYat(xcl[iLayer]);
1706                 cseed[iLayer].fZref[0] = rieman.GetZat(xcl[iLayer]);
1707                 chi2ZF += (cseed[iLayer].fZref[0]- cseed[iLayer].fMeanz)*
1708                   (cseed[iLayer].fZref[0]- cseed[iLayer].fMeanz);
1709                 cseed[iLayer].fZref[1] = rieman.GetDZat(xcl[iLayer]);
1710               }
1711             }
1712             chi2RF/=TMath::Max((nlayers-3.),1.);
1713             chi2ZF/=TMath::Max((nlayers-3.),1.);
1714             curv = rieman.GetC();
1715             
1716             //
1717
1718             Double_t xref2    = (xcl[2]+xcl[3])*0.5;  // middle of the chamber
1719             Double_t dzmf     = rieman.GetDZat(xref2);
1720             Double_t zmf      = rieman.GetZat(xref2);
1721             //
1722             // fit hyperplane
1723             //
1724             Int_t npointsT =0;
1725             fitterTC.ClearPoints();
1726             fitterT2.ClearPoints();
1727             rieman2.Reset();
1728             for (Int_t iLayer=0; iLayer<6;iLayer++){
1729               if (!cseed[iLayer].IsOK()) continue;
1730               for (Int_t itime=0;itime<25;itime++){
1731                 if (!cseed[iLayer].fUsable[itime]) continue;
1732                 Double_t x   = cseed[iLayer].fX[itime]+cseed[iLayer].fX0-xref2;  // x relative to the midle chamber
1733                 Double_t y   = cseed[iLayer].fY[itime];
1734                 Double_t z   = cseed[iLayer].fZ[itime];
1735                 // ExB correction to the correction
1736                 // tilted rieman
1737                 //
1738                 Double_t uvt[6];
1739                 Double_t x2 = cseed[iLayer].fX[itime]+cseed[iLayer].fX0;      // global x
1740                 //              
1741                 Double_t t = 1./(x2*x2+y*y);
1742                 uvt[1]  = t;    // t
1743                 uvt[0]  = 2.*x2*uvt[1];      // u 
1744                 //
1745                 uvt[2]  = 2.0*hL[iLayer]*uvt[1];
1746                 uvt[3]  = 2.0*hL[iLayer]*x*uvt[1];            
1747                 uvt[4]  = 2.0*(y+hL[iLayer]*z)*uvt[1];
1748                 //
1749                 Double_t error = 2*0.2*uvt[1];
1750                 fitterT2.AddPoint(uvt,uvt[4],error);
1751                 //
1752                 // constrained rieman
1753                 // 
1754                 z =cseed[iLayer].fZ[itime];
1755                 uvt[0]  = 2.*x2*t;           // u 
1756                 uvt[1]  = 2*hL[iLayer]*x2*uvt[1];             
1757                 uvt[2]  = 2*(y+hL[iLayer]*(z-GetZ()))*t;
1758                 fitterTC.AddPoint(uvt,uvt[2],error);
1759                 //              
1760                 rieman2.AddPoint(x2,y,z,1,10);
1761                 npointsT++;
1762               }
1763             }
1764             rieman2.Update();
1765             fitterTC.Eval();
1766             fitterT2.Eval();
1767             Double_t rpolz0 = fitterT2.GetParameter(3);
1768             Double_t rpolz1 = fitterT2.GetParameter(4);     
1769             //
1770             // linear fitter  - not possible to make boundaries
1771             // non accept non possible z and dzdx combination
1772             //      
1773             Bool_t   acceptablez =kTRUE;
1774             for (Int_t iLayer=0; iLayer<6;iLayer++){
1775               if (cseed[iLayer].IsOK()){
1776                 Double_t zT2 =  rpolz0+rpolz1*(xcl[iLayer] - xref2);
1777                 if (TMath::Abs(cseed[iLayer].fZProb-zT2)>padlength[iLayer]*0.5+1)
1778                   acceptablez = kFALSE;
1779               }
1780             }
1781             if (!acceptablez){
1782               fitterT2.FixParameter(3,zmf);
1783               fitterT2.FixParameter(4,dzmf);
1784               fitterT2.Eval();
1785               fitterT2.ReleaseParameter(3);
1786               fitterT2.ReleaseParameter(4);
1787               rpolz0 = fitterT2.GetParameter(3);
1788               rpolz1 = fitterT2.GetParameter(4);
1789             }
1790             //
1791             Double_t chi2TR = fitterT2.GetChisquare()/Float_t(npointsT);
1792             Double_t chi2TC = fitterTC.GetChisquare()/Float_t(npointsT);
1793             //
1794             Double_t polz1c = fitterTC.GetParameter(2);
1795             Double_t polz0c = polz1c*xref2;
1796             //
1797             Double_t aC     =  fitterTC.GetParameter(0);
1798             Double_t bC     =  fitterTC.GetParameter(1);
1799             Double_t cC     =  aC/TMath::Sqrt(bC*bC+1.);     // curvature
1800             //
1801             Double_t aR     =  fitterT2.GetParameter(0);
1802             Double_t bR     =  fitterT2.GetParameter(1);
1803             Double_t dR     =  fitterT2.GetParameter(2);            
1804             Double_t cR     =  1+bR*bR-dR*aR;
1805             Double_t dca    =  0.;          
1806             if (cR>0){
1807               dca = -dR/(TMath::Sqrt(1+bR*bR-dR*aR)+TMath::Sqrt(1+bR*bR)); 
1808               cR  = aR/TMath::Sqrt(cR);
1809             }
1810             //
1811             Double_t chi2ZT2=0, chi2ZTC=0;
1812             for (Int_t iLayer=0; iLayer<6;iLayer++){
1813               if (cseed[iLayer].IsOK()){
1814                 Double_t zT2 =  rpolz0+rpolz1*(xcl[iLayer] - xref2);
1815                 Double_t zTC =  polz0c+polz1c*(xcl[iLayer] - xref2);
1816                 chi2ZT2 += TMath::Abs(cseed[iLayer].fMeanz-zT2);
1817                 chi2ZTC += TMath::Abs(cseed[iLayer].fMeanz-zTC);
1818               }
1819             }
1820             chi2ZT2/=TMath::Max((nlayers-3.),1.);
1821             chi2ZTC/=TMath::Max((nlayers-3.),1.);           
1822             //
1823             //
1824             //
1825             AliTRDseed::FitRiemanTilt(cseed, kTRUE);
1826             Float_t sumdaf = 0;
1827             for (Int_t iLayer=0;iLayer<6;iLayer++){
1828               if (cseed[iLayer].IsOK())
1829                 sumdaf += TMath::Abs((cseed[iLayer].fYfit[1]-cseed[iLayer].fYref[1])/cseed[iLayer].fSigmaY2);
1830             }  
1831             sumdaf /= Float_t (nlayers-2.);
1832             //
1833             // likelihoods for full track
1834             //
1835             Double_t likezf      = TMath::Exp(-chi2ZF*0.14);
1836             Double_t likechi2C   = TMath::Exp(-chi2TC*0.677);
1837             Double_t likechi2TR  = TMath::Exp(-chi2TR*0.78);
1838             Double_t likeaf      = TMath::Exp(-sumdaf*3.23);
1839             seedquality2[registered] = likezf*likechi2TR*likeaf; 
1840 //          Bool_t isGold = kFALSE;
1841 //          
1842 //          if (nlayers == 6        && TMath::Log(0.000000001+seedquality2[index])<-5.) isGold =kTRUE;   // gold
1843 //          if (nlayers == findable && TMath::Log(0.000000001+seedquality2[index])<-4.) isGold =kTRUE;   // gold
1844 //          if (isGold &&nusedf<10){
1845 //            for (Int_t jLayer=0;jLayer<6;jLayer++){
1846 //              if ( seed[index][jLayer].IsOK()&&TMath::Abs(seed[index][jLayer].fYfit[1]-seed[index][jLayer].fYfit[1])<0.1)
1847 //                seed[index][jLayer].UseClusters();  //sign gold
1848 //            }
1849 //          }
1850             //
1851             //
1852             //
1853             Int_t index0=0;
1854             if (!cseed[0].IsOK()){
1855               index0 = 1;
1856               if (!cseed[1].IsOK()) index0 = 2;
1857             }
1858             seedparams[registered][0] = cseed[index0].fX0;
1859             seedparams[registered][1] = cseed[index0].fYref[0];
1860             seedparams[registered][2] = cseed[index0].fZref[0];
1861             seedparams[registered][5] = cR;
1862             seedparams[registered][3] = cseed[index0].fX0*cR - TMath::Sin(TMath::ATan(cseed[0].fYref[1]));
1863             seedparams[registered][4] = cseed[index0].fZref[1]/       
1864               TMath::Sqrt(1+cseed[index0].fYref[1]*cseed[index0].fYref[1]);
1865             seedparams[registered][6] = ns;
1866             //
1867             //
1868             Int_t labels[12], outlab[24];
1869             Int_t nlab=0;
1870             for (Int_t iLayer=0;iLayer<6;iLayer++){
1871               if (!cseed[iLayer].IsOK()) continue;
1872               if (cseed[iLayer].fLabels[0]>=0) {
1873                 labels[nlab] = cseed[iLayer].fLabels[0];
1874                 nlab++;
1875               }
1876               if (cseed[iLayer].fLabels[1]>=0) {
1877                 labels[nlab] = cseed[iLayer].fLabels[1];
1878                 nlab++;
1879               }       
1880             }
1881             Freq(nlab,labels,outlab,kFALSE);
1882             Int_t label = outlab[0];
1883             Int_t frequency  = outlab[1];
1884             for (Int_t iLayer=0;iLayer<6;iLayer++){
1885               cseed[iLayer].fFreq  = frequency;
1886               cseed[iLayer].fC     = cR;
1887               cseed[iLayer].fCC     = cC;
1888               cseed[iLayer].fChi2  = chi2TR;
1889               cseed[iLayer].fChi2Z = chi2ZF;
1890             }
1891             //
1892             if (1||(!isFake)){  //debugging print
1893               Float_t zvertex = GetZ();
1894               TTreeSRedirector& cstream = *fDebugStreamer;
1895               if (AliTRDReconstructor::StreamLevel()>0)
1896               cstream<<"Seeds1"<<
1897                 "isFake="<<isFake<<
1898                 "Vertex="<<zvertex<<
1899                 "Rieman2.="<<&rieman2<<
1900                 "Rieman.="<<&rieman<<
1901                 "Xref="<<xref<<
1902                 "X0="<<xcl[0]<<
1903                 "X1="<<xcl[1]<<
1904                 "X2="<<xcl[2]<<
1905                 "X3="<<xcl[3]<<
1906                 "X4="<<xcl[4]<<
1907                 "X5="<<xcl[5]<<
1908                 "Chi2R="<<chi2R<<
1909                 "Chi2Z="<<chi2Z<<
1910                 "Chi2RF="<<chi2RF<<                          //chi2 of trackletes on full track
1911                 "Chi2ZF="<<chi2ZF<<                          //chi2 z on tracklets on full track
1912                 "Chi2ZT2="<<chi2ZT2<<                        //chi2 z on tracklets on full track  - rieman tilt
1913                 "Chi2ZTC="<<chi2ZTC<<                        //chi2 z on tracklets on full track  - rieman tilt const
1914                 //
1915                 "Chi2TR="<<chi2TR<<                           //chi2 without vertex constrain
1916                 "Chi2TC="<<chi2TC<<                           //chi2 with    vertex constrain
1917                 "C="<<curv<<                                  // non constrained - no tilt correction
1918                 "DR="<<dR<<                                   // DR parameter          - tilt correction
1919                 "DCA="<<dca<<                                 // DCA                   - tilt correction
1920                 "CR="<<cR<<                                   // non constrained curvature - tilt correction
1921                 "CC="<<cC<<                                   // constrained curvature
1922                 "Polz0="<<polz0c<<
1923                 "Polz1="<<polz1c<<
1924                 "RPolz0="<<rpolz0<<
1925                 "RPolz1="<<rpolz1<<
1926                 "Ncl="<<nclusters<<
1927                 "Nlayers="<<nlayers<<
1928                 "NUsedS="<<nusedCl<<
1929                 "NUsed="<<nusedf<<
1930                 "Findable="<<findable<<
1931                 "Like="<<like<<
1932                 "LikePrim="<<likePrim<<
1933                 "Likechi2C="<<likechi2C<<
1934                 "Likechi2TR="<<likechi2TR<<
1935                 "Likezf="<<likezf<<
1936                 "LikeF="<<seedquality2[registered]<<
1937                 "S0.="<<&cseed[0]<<
1938                 "S1.="<<&cseed[1]<<
1939                 "S2.="<<&cseed[2]<<
1940                 "S3.="<<&cseed[3]<<
1941                 "S4.="<<&cseed[4]<<
1942                 "S5.="<<&cseed[5]<<
1943                 "SB0.="<<&seedb[0]<<
1944                 "SB1.="<<&seedb[1]<<
1945                 "SB2.="<<&seedb[2]<<
1946                 "SB3.="<<&seedb[3]<<
1947                 "SB4.="<<&seedb[4]<<
1948                 "SB5.="<<&seedb[5]<<
1949                 "Label="<<label<<
1950                 "Freq="<<frequency<<
1951                 "sLayer="<<sLayer<<
1952                 "\n";
1953             }
1954             if (registered<kMaxSeed-1) {
1955               registered++;
1956               cseed = seed[registered];
1957             }
1958           }// end of loop over layer 1
1959         }  // end of loop over layer 0 
1960       }    // end of loop over layer 3     
1961     }      // end of loop over seeding time bins 
1962     //
1963     // choos best
1964     //
1965     TMath::Sort(registered,seedquality2,sort,kTRUE);
1966     Bool_t signedseed[kMaxSeed];
1967     for (Int_t i=0;i<registered;i++){
1968       signedseed[i]= kFALSE;
1969     }
1970     for (Int_t iter=0; iter<5; iter++){
1971       for (Int_t iseed=0;iseed<registered;iseed++){      
1972         Int_t index = sort[iseed];
1973         if (signedseed[index]) continue;
1974         Int_t labelsall[1000];
1975         Int_t nlabelsall=0;
1976         Int_t naccepted=0;;
1977         Int_t sLayer = seedlayer[index];
1978         Int_t ncl   = 0;
1979         Int_t nused = 0;
1980         Int_t nlayers =0;
1981         Int_t findable   = 0;
1982         for (Int_t jLayer=0;jLayer<6;jLayer++){
1983           if (TMath::Abs(seed[index][jLayer].fYref[0]/xcl[jLayer])<0.15)
1984             findable++;
1985           if (seed[index][jLayer].IsOK()){
1986             seed[index][jLayer].UpdateUsed();
1987             ncl   +=seed[index][jLayer].fN2;
1988             nused +=seed[index][jLayer].fNUsed;
1989             nlayers++;
1990             //cooking label
1991             for (Int_t itime=0;itime<25;itime++){
1992               if (seed[index][jLayer].fUsable[itime]){
1993                 naccepted++;
1994                 for (Int_t ilab=0;ilab<3;ilab++){
1995                   Int_t tindex = seed[index][jLayer].fClusters[itime]->GetLabel(ilab);
1996                   if (tindex>=0){
1997                     labelsall[nlabelsall] = tindex;
1998                     nlabelsall++;
1999                   }
2000                 }
2001               }
2002             }
2003           }
2004         }
2005         //
2006         if (nused>30) continue;
2007         //
2008         if (iter==0){
2009           if (nlayers<6) continue;
2010           if (TMath::Log(0.000000001+seedquality2[index])<-5.) continue;   // gold
2011         }
2012         //
2013         if (iter==1){
2014           if (nlayers<findable) continue;
2015           if (TMath::Log(0.000000001+seedquality2[index])<-4.) continue;  //
2016         }
2017         //
2018         //
2019         if (iter==2){
2020           if (nlayers==findable || nlayers==6) continue;
2021           if (TMath::Log(0.000000001+seedquality2[index])<-6.) continue;
2022         }
2023         //
2024         if (iter==3){
2025           if (TMath::Log(0.000000001+seedquality2[index])<-5.) continue;
2026         }
2027         //
2028         if (iter==4){
2029           if (TMath::Log(0.000000001+seedquality2[index])-nused/(nlayers-3.)<-15.) continue;
2030         }
2031         //
2032         signedseed[index] = kTRUE;
2033         //
2034         Int_t labels[1000], outlab[1000];
2035         Int_t nlab=0;
2036         for (Int_t iLayer=0;iLayer<6;iLayer++){
2037           if (seed[index][iLayer].IsOK()){
2038             if (seed[index][iLayer].fLabels[0]>=0) {
2039               labels[nlab] = seed[index][iLayer].fLabels[0];
2040               nlab++;
2041             }
2042             if (seed[index][iLayer].fLabels[1]>=0) {
2043               labels[nlab] = seed[index][iLayer].fLabels[1];
2044               nlab++;
2045             }    
2046           }     
2047         }
2048         Freq(nlab,labels,outlab,kFALSE);
2049         Int_t label  = outlab[0];
2050         Int_t frequency  = outlab[1];
2051         Freq(nlabelsall,labelsall,outlab,kFALSE);
2052         Int_t label1 = outlab[0];
2053         Int_t label2 = outlab[2];
2054         Float_t fakeratio = (naccepted-outlab[1])/Float_t(naccepted);
2055         Float_t ratio = Float_t(nused)/Float_t(ncl);
2056         if (ratio<0.25){
2057           for (Int_t jLayer=0;jLayer<6;jLayer++){
2058             if ( seed[index][jLayer].IsOK()&&TMath::Abs(seed[index][jLayer].fYfit[1]-seed[index][jLayer].fYfit[1])<0.2 )
2059               seed[index][jLayer].UseClusters();  //sign gold
2060           }
2061         }
2062         //
2063         Int_t eventNr = esd->GetEventNumber();
2064         TTreeSRedirector& cstream = *fDebugStreamer;
2065         //
2066         // register seed
2067         //
2068         AliTRDtrack * track = RegisterSeed(seed[index],seedparams[index]);
2069         AliTRDtrack dummy;
2070         if (!track) track=&dummy;
2071         else{
2072           AliESDtrack esdtrack;
2073           esdtrack.UpdateTrackParams(track, AliESDtrack::kTRDout);
2074           esdtrack.SetLabel(label);
2075           esd->AddTrack(&esdtrack);     
2076           TTreeSRedirector& cstream = *fDebugStreamer;
2077           if (AliTRDReconstructor::StreamLevel()>0)
2078             cstream<<"Tracks"<<
2079               "EventNr="<<eventNr<<
2080               "ESD.="<<&esdtrack<<
2081               "trd.="<<track<<
2082               "trdback.="<<track<<
2083               "\n";
2084         }
2085         if (AliTRDReconstructor::StreamLevel()>0)
2086           cstream<<"Seeds2"<<
2087           "Iter="<<iter<<
2088           "Track.="<<track<<
2089           "Like="<<seedquality[index]<<
2090           "LikeF="<<seedquality2[index]<<
2091           "S0.="<<&seed[index][0]<<
2092           "S1.="<<&seed[index][1]<<
2093           "S2.="<<&seed[index][2]<<
2094           "S3.="<<&seed[index][3]<<
2095           "S4.="<<&seed[index][4]<<
2096           "S5.="<<&seed[index][5]<<
2097           "Label="<<label<<
2098           "Label1="<<label1<<
2099           "Label2="<<label2<<
2100           "FakeRatio="<<fakeratio<<
2101           "Freq="<<frequency<<
2102           "Ncl="<<ncl<< 
2103           "Nlayers="<<nlayers<<
2104           "Findable="<<findable<<
2105           "NUsed="<<nused<<
2106           "sLayer="<<sLayer<<
2107           "EventNr="<<eventNr<<
2108           "\n";
2109       }
2110     }
2111   }        // end of loop over sectors
2112
2113   delete [] pseed;
2114
2115 }
2116           
2117 //_____________________________________________________________________________
2118 Int_t AliTRDtracker::ReadClusters(TObjArray *array, TTree *ClusterTree) const
2119 {
2120   //
2121   // Reads AliTRDclusters (option >= 0) or AliTRDrecPoints (option < 0) 
2122   // from the file. The names of the cluster tree and branches 
2123   // should match the ones used in AliTRDclusterizer::WriteClusters()
2124   //
2125
2126   Int_t nsize = Int_t(ClusterTree->GetTotBytes()/(sizeof(AliTRDcluster))); 
2127   TObjArray *clusterArray = new TObjArray(nsize+1000); 
2128   
2129   TBranch *branch=ClusterTree->GetBranch("TRDcluster");
2130   if (!branch) {
2131     Error("ReadClusters","Can't get the branch !");
2132     return 1;
2133   }
2134   branch->SetAddress(&clusterArray); 
2135   
2136   Int_t nEntries = (Int_t) ClusterTree->GetEntries();
2137   //  printf("found %d entries in %s.\n",nEntries,ClusterTree->GetName());
2138   
2139   // Loop through all entries in the tree
2140   Int_t nbytes = 0;
2141   AliTRDcluster *c = 0;
2142   //  printf("\n");
2143   for (Int_t iEntry = 0; iEntry < nEntries; iEntry++) {    
2144     
2145     // Import the tree
2146     nbytes += ClusterTree->GetEvent(iEntry);  
2147     
2148     // Get the number of points in the detector
2149     Int_t nCluster = clusterArray->GetEntriesFast();  
2150 //    printf("\r Read %d clusters from entry %d", nCluster, iEntry);
2151     
2152     // Loop through all TRD digits
2153     for (Int_t iCluster = 0; iCluster < nCluster; iCluster++) { 
2154       c = (AliTRDcluster*)clusterArray->UncheckedAt(iCluster);
2155       AliTRDcluster *co = c;
2156       array->AddLast(co);
2157       //      delete clusterArray->RemoveAt(iCluster); 
2158       clusterArray->RemoveAt(iCluster); 
2159     }
2160   }
2161 //   cout<<"Allocated"<<nsize<<"\tLoaded"<<array->GetEntriesFast()<<"\n";
2162
2163   delete clusterArray;
2164
2165   return 0;
2166
2167 }
2168
2169 //_____________________________________________________________________________
2170 Bool_t AliTRDtracker::GetTrackPoint(Int_t index, AliTrackPoint& p) const
2171 {
2172   //
2173   // Get track space point with index i
2174   // Origin: C.Cheshkov
2175   //
2176
2177   AliTRDcluster *cl = (AliTRDcluster*)fClusters->UncheckedAt(index);
2178   Int_t  idet = cl->GetDetector();
2179   Int_t  isector = fGeom->GetSector(idet);
2180   Int_t  ichamber= fGeom->GetChamber(idet);
2181   Int_t  iplan   = fGeom->GetPlane(idet);
2182   Double_t local[3];
2183   local[0]=GetX(isector,iplan,cl->GetLocalTimeBin());
2184   local[1]=cl->GetY();
2185   local[2]=cl->GetZ();
2186   Double_t global[3];
2187   fGeom->RotateBack(idet,local,global);
2188   p.SetXYZ(global[0],global[1],global[2]);
2189   AliAlignObj::ELayerID iLayer = AliAlignObj::kTRD1;
2190   switch (iplan) {
2191   case 0:
2192     iLayer = AliAlignObj::kTRD1;
2193     break;
2194   case 1:
2195     iLayer = AliAlignObj::kTRD2;
2196     break;
2197   case 2:
2198     iLayer = AliAlignObj::kTRD3;
2199     break;
2200   case 3:
2201     iLayer = AliAlignObj::kTRD4;
2202     break;
2203   case 4:
2204     iLayer = AliAlignObj::kTRD5;
2205     break;
2206   case 5:
2207     iLayer = AliAlignObj::kTRD6;
2208     break;
2209   };
2210   Int_t modId = isector*fGeom->Ncham()+ichamber;
2211   UShort_t volid = AliAlignObj::LayerToVolUID(iLayer,modId);
2212   p.SetVolumeID(volid);
2213
2214   return kTRUE;
2215
2216 }
2217
2218 //_____________________________________________________________________________
2219 void AliTRDtracker::CookLabel(AliKalmanTrack* pt, Float_t wrong) const 
2220 {
2221   //
2222   // This cooks a label. Mmmmh, smells good...
2223   //
2224
2225   Int_t label=123456789, index, i, j;
2226   Int_t ncl=pt->GetNumberOfClusters();
2227   const Int_t kRange = fTrSec[0]->GetOuterTimeBin()+1;
2228
2229   Bool_t labelAdded;
2230
2231   //  Int_t s[kRange][2];
2232   Int_t **s = new Int_t* [kRange];
2233   for (i=0; i<kRange; i++) {
2234     s[i] = new Int_t[2];
2235   }
2236   for (i=0; i<kRange; i++) {
2237     s[i][0]=-1;
2238     s[i][1]=0;
2239   }
2240
2241   Int_t t0,t1,t2;
2242   for (i=0; i<ncl; i++) {
2243     index=pt->GetClusterIndex(i);
2244     AliTRDcluster *c=(AliTRDcluster*)fClusters->UncheckedAt(index);
2245     t0=c->GetLabel(0);
2246     t1=c->GetLabel(1);
2247     t2=c->GetLabel(2);
2248   }
2249
2250   for (i=0; i<ncl; i++) {
2251     index=pt->GetClusterIndex(i);
2252     AliTRDcluster *c=(AliTRDcluster*)fClusters->UncheckedAt(index);
2253     for (Int_t k=0; k<3; k++) { 
2254       label=c->GetLabel(k);
2255       labelAdded=kFALSE; j=0;
2256       if (label >= 0) {
2257         while ( (!labelAdded) && ( j < kRange ) ) {
2258           if (s[j][0]==label || s[j][1]==0) {
2259             s[j][0]=label; 
2260             s[j][1]=s[j][1]+1; 
2261             labelAdded=kTRUE;
2262           }
2263           j++;
2264         }
2265       }
2266     }
2267   }
2268
2269   Int_t max=0;
2270   label = -123456789;
2271
2272   for (i=0; i<kRange; i++) {
2273     if (s[i][1]>max) {
2274       max=s[i][1]; label=s[i][0];
2275     }
2276   }
2277
2278   for (i=0; i<kRange; i++) {
2279     delete []s[i];
2280   }        
2281
2282   delete []s;
2283
2284   if ((1.- Float_t(max)/ncl) > wrong) label=-label;   
2285
2286   pt->SetLabel(label); 
2287
2288 }
2289
2290 //_____________________________________________________________________________
2291 void AliTRDtracker::UseClusters(const AliKalmanTrack* t, Int_t from) const 
2292 {
2293   //
2294   // Use clusters, but don't abuse them!
2295   //
2296
2297   const Float_t kmaxchi2 =18;
2298   const Float_t kmincl   =10;
2299   AliTRDtrack * track  = (AliTRDtrack*)t;
2300   //
2301   Int_t ncl=t->GetNumberOfClusters();
2302   for (Int_t i=from; i<ncl; i++) {
2303     Int_t index = t->GetClusterIndex(i);
2304     AliTRDcluster *c=(AliTRDcluster*)fClusters->UncheckedAt(index);
2305     //
2306     Int_t iplane = fGeom->GetPlane(c->GetDetector());
2307     if (track->fTracklets[iplane].GetChi2()>kmaxchi2) continue; 
2308     if (track->fTracklets[iplane].GetN()<kmincl) continue; 
2309     if (!(c->IsUsed())) c->Use();
2310   }
2311
2312 }
2313
2314 //_____________________________________________________________________________
2315 Double_t AliTRDtracker::ExpectedSigmaY2(Double_t , Double_t , Double_t ) const
2316 {
2317   //
2318   // Parametrised "expected" error of the cluster reconstruction in Y 
2319   //
2320
2321   Double_t s = 0.08 * 0.08;    
2322   return s;
2323
2324 }
2325
2326 //_____________________________________________________________________________
2327 Double_t AliTRDtracker::ExpectedSigmaZ2(Double_t , Double_t ) const
2328 {
2329   //
2330   // Parametrised "expected" error of the cluster reconstruction in Z 
2331   //
2332
2333   Double_t s = 9 * 9 /12.;  
2334   return s;
2335
2336 }                  
2337
2338 //_____________________________________________________________________________
2339 Double_t AliTRDtracker::GetX(Int_t sector, Int_t plane, Int_t localTB) const 
2340 {
2341   //
2342   // Returns radial position which corresponds to time bin <localTB>
2343   // in tracking sector <sector> and plane <plane>
2344   //
2345
2346   Int_t index = fTrSec[sector]->CookTimeBinIndex(plane, localTB); 
2347   Int_t pl = fTrSec[sector]->GetLayerNumber(index);
2348   return fTrSec[sector]->GetLayer(pl)->GetX();
2349
2350 }
2351
2352 //_____________________________________________________________________________
2353 AliTRDtracker::AliTRDpropagationLayer
2354              ::AliTRDpropagationLayer(Double_t x, Double_t dx, Double_t rho
2355                                     , Double_t radLength, Int_t tbIndex, Int_t plane)
2356
2357   //
2358   // AliTRDpropagationLayer constructor
2359   //
2360
2361   fN = 0; fX = x; fdX = dx; fRho = rho; fX0 = radLength;
2362   fClusters = NULL; fIndex = NULL; fTimeBinIndex = tbIndex;
2363   fPlane = plane;
2364
2365   for(Int_t i=0; i < (Int_t) kZones; i++) {
2366     fZc[i]=0; fZmax[i] = 0;
2367   }
2368
2369   fYmax = 0;
2370
2371   if(fTimeBinIndex >= 0) { 
2372     fClusters = new AliTRDcluster*[kMaxClusterPerTimeBin];
2373     fIndex = new UInt_t[kMaxClusterPerTimeBin];
2374   }
2375
2376   for (Int_t i=0;i<5;i++) fIsHole[i] = kFALSE;
2377   fHole = kFALSE;
2378   fHoleZc = 0;
2379   fHoleZmax = 0;
2380   fHoleYc = 0;
2381   fHoleYmax = 0;
2382   fHoleRho = 0;
2383   fHoleX0 = 0;
2384
2385 }
2386
2387 //_____________________________________________________________________________
2388 void AliTRDtracker::AliTRDpropagationLayer
2389                   ::SetHole(Double_t Zmax, Double_t Ymax, Double_t rho
2390                           , Double_t radLength, Double_t Yc, Double_t Zc) 
2391 {
2392   //
2393   // Sets hole in the layer 
2394   //
2395
2396   fHole = kTRUE;
2397   fHoleZc = Zc;
2398   fHoleZmax = Zmax;
2399   fHoleYc = Yc;
2400   fHoleYmax = Ymax;
2401   fHoleRho = rho;
2402   fHoleX0 = radLength;
2403
2404 }
2405
2406 //_____________________________________________________________________________
2407 AliTRDtracker::AliTRDtrackingSector
2408              ::AliTRDtrackingSector(AliTRDgeometry* geo, Int_t gs)
2409 {
2410   //
2411   // AliTRDtrackingSector Constructor
2412   //
2413
2414   AliTRDpadPlane *padPlane = 0;
2415
2416   fGeom = geo;
2417   fGeomSector = gs;
2418   fN = 0;
2419   //
2420   // get holes description from geometry
2421   Bool_t holes[AliTRDgeometry::kNcham];
2422   //printf("sector\t%d\t",gs);
2423   for (Int_t icham=0; icham<AliTRDgeometry::kNcham;icham++){
2424     holes[icham] = fGeom->IsHole(0,icham,gs);
2425     //printf("%d",holes[icham]);
2426   } 
2427   //printf("\n");
2428   
2429   for(UInt_t i=0; i < kMaxTimeBinIndex; i++) fTimeBinIndex[i] = -1;
2430
2431
2432   AliTRDpropagationLayer* ppl;
2433
2434   Double_t x, dx, rho, radLength;
2435   //  Int_t    steps;
2436
2437   // add layers for each of the planes
2438   Double_t dxAmp = (Double_t) fGeom->CamHght();   // Amplification region
2439   //Double_t dxDrift = (Double_t) fGeom->CdrHght(); // Drift region  
2440
2441   Int_t    tbIndex;
2442   const Int_t  kNchambers = AliTRDgeometry::Ncham();
2443   Double_t  ymax = 0;
2444   Double_t ymaxsensitive=0;
2445   Double_t *zc = new Double_t[kNchambers];
2446   Double_t *zmax = new Double_t[kNchambers];
2447   Double_t *zmaxsensitive = new Double_t[kNchambers];  
2448
2449   AliTRDCommonParam* commonParam = AliTRDCommonParam::Instance();
2450   if (!commonParam)
2451   {
2452     printf("<AliTRDtracker::AliTRDtrackingSector::AliTRDtrackingSector> ");
2453     printf("Could not get common params\n");
2454     return;
2455   }
2456     
2457   for(Int_t plane = 0; plane < AliTRDgeometry::Nplan(); plane++) {
2458
2459     ymax          = fGeom->GetChamberWidth(plane)/2.;
2460     // Modidified for new pad plane class, 22.04.05 (C.B.)
2461     padPlane = commonParam->GetPadPlane(plane,0);
2462     ymaxsensitive = (padPlane->GetColSize(1)*padPlane->GetNcols()-4)/2.;    
2463     for(Int_t ch = 0; ch < kNchambers; ch++) {
2464       zmax[ch] = fGeom->GetChamberLength(plane,ch)/2;
2465       //
2466       // Modidified for new pad plane class, 22.04.05 (C.B.)
2467       Float_t pad = padPlane->GetRowSize(1);
2468       Float_t row0 = commonParam->GetRow0(plane,ch,0);
2469       Int_t nPads = commonParam->GetRowMax(plane,ch,0);
2470       zmaxsensitive[ch] = Float_t(nPads)*pad/2.;      
2471       zc[ch] = -(pad * nPads)/2 + row0;
2472     }
2473
2474     dx  = AliTRDcalibDB::Instance()->GetVdrift(0,0,0)
2475         / AliTRDcalibDB::Instance()->GetSamplingFrequency();
2476     rho = 0.00295 * 0.85; radLength = 11.0;  
2477
2478     Double_t x0 = (Double_t) AliTRDgeometry::GetTime0(plane);
2479     //Double_t xbottom = x0 - dxDrift;
2480     //Double_t xtop = x0 + dxAmp;
2481     //
2482     Int_t nTimeBins =  AliTRDcalibDB::Instance()->GetNumberOfTimeBins();    
2483     for (Int_t iTime = 0; iTime<nTimeBins; iTime++){
2484       Double_t xlayer  = iTime*dx - dxAmp;
2485       //if (xlayer<0) xlayer=dxAmp/2.;
2486       x = x0 - xlayer;
2487       //      
2488       tbIndex = CookTimeBinIndex(plane, iTime);
2489       ppl = new AliTRDpropagationLayer(x,dx,rho,radLength,tbIndex, plane);
2490       ppl->SetYmax(ymax,ymaxsensitive);
2491       ppl->SetZ(zc, zmax, zmaxsensitive);
2492       ppl->SetHoles(holes);
2493       InsertLayer(ppl);      
2494     }
2495   }    
2496
2497   MapTimeBinLayers();
2498   delete [] zc;
2499   delete [] zmax;
2500   delete [] zmaxsensitive;
2501
2502 }
2503
2504 //_____________________________________________________________________________
2505 Int_t  AliTRDtracker::AliTRDtrackingSector
2506                     ::CookTimeBinIndex(Int_t plane, Int_t localTB) const
2507 {
2508   //
2509   // depending on the digitization parameters calculates "global"
2510   // time bin index for timebin <localTB> in plane <plane>
2511   //
2512   //
2513
2514   Int_t tbPerPlane = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
2515   Int_t gtb = (plane+1) * tbPerPlane - localTB -1;
2516   if (localTB<0) return -1;
2517   if (gtb<0)     return -1;
2518
2519   return gtb;
2520
2521 }
2522
2523 //_____________________________________________________________________________
2524 void AliTRDtracker::AliTRDtrackingSector
2525                   ::MapTimeBinLayers() 
2526 {
2527   //
2528   // For all sensitive time bins sets corresponding layer index
2529   // in the array fTimeBins 
2530   //
2531
2532   Int_t index;
2533
2534   for(Int_t i = 0; i < fN; i++) {
2535     index = fLayers[i]->GetTimeBinIndex();
2536     
2537     //    printf("gtb %d -> pl %d -> x %f \n", index, i, fLayers[i]->GetX());
2538
2539     if(index < 0) continue;
2540     if(index >= (Int_t) kMaxTimeBinIndex) {
2541       printf("*** AliTRDtracker::MapTimeBinLayers: \n");
2542       printf("    index %d exceeds allowed maximum of %d!\n",
2543              index, kMaxTimeBinIndex-1);
2544       continue;
2545     }
2546     fTimeBinIndex[index] = i;
2547   }
2548
2549 }
2550
2551 //_____________________________________________________________________________
2552 Int_t AliTRDtracker::AliTRDtrackingSector
2553                    ::GetLayerNumber(Double_t x) const
2554 {
2555   // 
2556   // Returns the number of time bin which in radial position is closest to <x>
2557   //
2558
2559   if(x >= fLayers[fN-1]->GetX()) return fN-1; 
2560   if(x <= fLayers[0]->GetX()) return 0; 
2561
2562   Int_t b=0, e=fN-1, m=(b+e)/2;
2563   for (; b<e; m=(b+e)/2) {
2564     if (x > fLayers[m]->GetX()) b=m+1;
2565     else e=m;
2566   }
2567   if(TMath::Abs(x - fLayers[m]->GetX()) > 
2568      TMath::Abs(x - fLayers[m+1]->GetX())) return m+1;
2569
2570   else return m;
2571
2572 }
2573
2574 //_____________________________________________________________________________
2575 Int_t AliTRDtracker::AliTRDtrackingSector
2576                    ::GetInnerTimeBin() const 
2577 {
2578   // 
2579   // Returns number of the innermost SENSITIVE propagation layer
2580   //
2581
2582   return GetLayerNumber(0);
2583
2584 }
2585
2586 //_____________________________________________________________________________
2587 Int_t AliTRDtracker::AliTRDtrackingSector
2588                    ::GetOuterTimeBin() const 
2589 {
2590   // 
2591   // Returns number of the outermost SENSITIVE time bin
2592   //
2593
2594   return GetLayerNumber(GetNumberOfTimeBins() - 1);
2595
2596 }
2597
2598 //_____________________________________________________________________________
2599 Int_t AliTRDtracker::AliTRDtrackingSector
2600                    ::GetNumberOfTimeBins() const 
2601 {
2602   // 
2603   // Returns number of SENSITIVE time bins
2604   //
2605
2606   Int_t tb, layer;
2607   for(tb = kMaxTimeBinIndex-1; tb >=0; tb--) {
2608     layer = GetLayerNumber(tb);
2609     if(layer>=0) break;
2610   }
2611
2612   return tb+1;
2613
2614 }
2615
2616 //_____________________________________________________________________________
2617 void AliTRDtracker::AliTRDtrackingSector
2618                   ::InsertLayer(AliTRDpropagationLayer* pl)
2619
2620   //
2621   // Insert layer <pl> in fLayers array.
2622   // Layers are sorted according to X coordinate.
2623   //
2624
2625   if ( fN == ((Int_t) kMaxLayersPerSector)) {
2626     printf("AliTRDtrackingSector::InsertLayer(): Too many layers !\n");
2627     return;
2628   }
2629   if (fN==0) {fLayers[fN++] = pl; return;}
2630   Int_t i=Find(pl->GetX());
2631
2632   memmove(fLayers+i+1 ,fLayers+i,(fN-i)*sizeof(AliTRDpropagationLayer*));
2633   fLayers[i]=pl; fN++;
2634
2635 }              
2636
2637 //_____________________________________________________________________________
2638 Int_t AliTRDtracker::AliTRDtrackingSector
2639                    ::Find(Double_t x) const 
2640 {
2641   //
2642   // Returns index of the propagation layer nearest to X 
2643   //
2644
2645   if (x <= fLayers[0]->GetX()) return 0;
2646   if (x > fLayers[fN-1]->GetX()) return fN;
2647   Int_t b=0, e=fN-1, m=(b+e)/2;
2648   for (; b<e; m=(b+e)/2) {
2649     if (x > fLayers[m]->GetX()) b=m+1;
2650     else e=m;
2651   }
2652
2653   return m;
2654
2655 }             
2656
2657 //_____________________________________________________________________________
2658 void AliTRDtracker::AliTRDpropagationLayer
2659                   ::SetZ(Double_t* center, Double_t *w, Double_t *wsensitive )
2660 {
2661   //
2662   // set centers and the width of sectors
2663   //
2664
2665   for (Int_t icham=0;icham< AliTRDgeometry::kNcham;icham++){
2666     fZc[icham] = center[icham];  
2667     fZmax[icham] = w[icham];
2668     fZmaxSensitive[icham] = wsensitive[icham];
2669     // printf("chamber\t%d\tzc\t%f\tzmax\t%f\tzsens\t%f\n",icham,fZc[icham],fZmax[icham],fZmaxSensitive[icham]);
2670   }  
2671
2672 }
2673
2674 //_____________________________________________________________________________
2675 void AliTRDtracker::AliTRDpropagationLayer::SetHoles(Bool_t *holes)
2676 {
2677   //
2678   // set centers and the width of sectors
2679   //
2680
2681   fHole = kFALSE;
2682   for (Int_t icham=0;icham< AliTRDgeometry::kNcham;icham++){
2683     fIsHole[icham] = holes[icham]; 
2684     if (holes[icham]) fHole = kTRUE;
2685   }  
2686
2687 }
2688
2689 //_____________________________________________________________________________
2690 void AliTRDtracker::AliTRDpropagationLayer
2691                   ::InsertCluster(AliTRDcluster* c, UInt_t index) 
2692 {
2693   //
2694   // Insert cluster in cluster array.
2695   // Clusters are sorted according to Y coordinate.  
2696   //
2697
2698   if(fTimeBinIndex < 0) { 
2699     printf("*** attempt to insert cluster into non-sensitive time bin!\n");
2700     return;
2701   }
2702
2703   if (fN== (Int_t) kMaxClusterPerTimeBin) {
2704     printf("AliTRDpropagationLayer::InsertCluster(): Too many clusters !\n"); 
2705     return;
2706   }
2707   if (fN==0) {fIndex[0]=index; fClusters[fN++]=c; return;}
2708   Int_t i=Find(c->GetY());
2709   memmove(fClusters+i+1 ,fClusters+i,(fN-i)*sizeof(AliTRDcluster*));
2710   memmove(fIndex   +i+1 ,fIndex   +i,(fN-i)*sizeof(UInt_t)); 
2711   fIndex[i]=index; fClusters[i]=c; fN++;
2712
2713 }  
2714
2715 //_____________________________________________________________________________
2716 Int_t AliTRDtracker::AliTRDpropagationLayer::Find(Float_t y) const 
2717 {
2718   //
2719   // Returns index of the cluster nearest in Y    
2720   //
2721
2722   if (fN<=0) return 0;
2723   if (y <= fClusters[0]->GetY()) return 0;
2724   if (y > fClusters[fN-1]->GetY()) return fN;
2725   Int_t b=0, e=fN-1, m=(b+e)/2;
2726   for (; b<e; m=(b+e)/2) {
2727     if (y > fClusters[m]->GetY()) b=m+1;
2728     else e=m;
2729   }
2730
2731   return m;
2732
2733 }    
2734
2735 //_____________________________________________________________________________
2736 Int_t AliTRDtracker::AliTRDpropagationLayer
2737                    ::FindNearestCluster(Float_t y, Float_t z, Float_t maxroad
2738                                       , Float_t maxroadz) const 
2739 {
2740   //
2741   // Returns index of the cluster nearest to the given y,z
2742   //
2743
2744   Int_t index = -1;
2745   Int_t maxn = fN;
2746   Float_t mindist = maxroad;                    
2747   //
2748   for (Int_t i=Find(y-maxroad); i<maxn; i++) {
2749     AliTRDcluster* c=(AliTRDcluster*)(fClusters[i]);
2750     Float_t ycl = c->GetY();
2751     //
2752     if (ycl > y+maxroad) break;
2753     if (TMath::Abs(c->GetZ()-z) > maxroadz) continue;      
2754     if (TMath::Abs(ycl-y)<mindist){
2755       mindist = TMath::Abs(ycl-y);
2756       index = fIndex[i];
2757     }        
2758   }                                             
2759
2760   return index;
2761
2762 }             
2763
2764 //_____________________________________________________________________________
2765 Double_t AliTRDtracker::GetTiltFactor(const AliTRDcluster* c) 
2766 {
2767   //
2768   // Returns correction factor for tilted pads geometry 
2769   //
2770
2771   Int_t det = c->GetDetector();    
2772   Int_t plane = fGeom->GetPlane(det);
2773   AliTRDpadPlane *padPlane = AliTRDCommonParam::Instance()->GetPadPlane(plane,0);
2774   Double_t h01 = TMath::Tan(-TMath::Pi() / 180.0 * padPlane->GetTiltingAngle());
2775
2776   if(fNoTilt) h01 = 0;
2777
2778   return h01;
2779
2780 }
2781
2782 //_____________________________________________________________________________
2783 void AliTRDtracker::CookdEdxTimBin(AliTRDtrack& TRDtrack)
2784 {
2785   //
2786   // *** ADDED TO GET MORE INFORMATION FOR TRD PID  ---- PS
2787   // This is setting fdEdxPlane and fTimBinPlane
2788   // Sums up the charge in each plane for track TRDtrack and also get the 
2789   // Time bin for Max. Cluster
2790   // Prashant Shukla (shukla@physi.uni-heidelberg.de)
2791   //
2792
2793   Double_t  clscharge[AliESDtrack::kNPlane], maxclscharge[AliESDtrack::kNPlane];
2794   Int_t  nCluster[AliESDtrack::kNPlane], timebin[AliESDtrack::kNPlane];
2795
2796   //Initialization of cluster charge per plane.  
2797   for (Int_t iPlane = 0; iPlane < AliESDtrack::kNPlane; iPlane++) {
2798     clscharge[iPlane] = 0.0;
2799     nCluster[iPlane] = 0;
2800     timebin[iPlane] = -1;
2801     maxclscharge[iPlane] = 0.0;
2802   }
2803
2804   // Loop through all clusters associated to track TRDtrack
2805   Int_t nClus = TRDtrack.GetNumberOfClusters();  // from Kalmantrack
2806   for (Int_t iClus = 0; iClus < nClus; iClus++) {
2807     Double_t charge = TRDtrack.GetClusterdQdl(iClus);
2808     Int_t index = TRDtrack.GetClusterIndex(iClus);
2809     AliTRDcluster *pTRDcluster = (AliTRDcluster *) GetCluster(index); 
2810     if (!pTRDcluster) continue;
2811     Int_t tb = pTRDcluster->GetLocalTimeBin();
2812     if (!tb) continue;
2813     Int_t detector = pTRDcluster->GetDetector();
2814     Int_t iPlane   = fGeom->GetPlane(detector);
2815     clscharge[iPlane] = clscharge[iPlane]+charge;
2816     if(charge > maxclscharge[iPlane]) {
2817       maxclscharge[iPlane] = charge;
2818       timebin[iPlane] = tb;
2819     }
2820     nCluster[iPlane]++;
2821   } // end of loop over cluster
2822
2823   // Setting the fdEdxPlane and fTimBinPlane variabales 
2824   Double_t totalCharge = 0;
2825   for (Int_t iPlane = 0; iPlane < AliESDtrack::kNPlane; iPlane++) {
2826     // Quality control of TRD track.
2827     if (nCluster[iPlane]<= 5) {
2828       clscharge[iPlane]=0.0;
2829       timebin[iPlane]=-1;
2830     }
2831     if (nCluster[iPlane]) clscharge[iPlane] /= nCluster[iPlane];
2832     TRDtrack.SetPIDsignals(clscharge[iPlane], iPlane);
2833     TRDtrack.SetPIDTimBin(timebin[iPlane], iPlane);
2834     totalCharge= totalCharge+clscharge[iPlane];
2835   }
2836   //  Int_t i;
2837   //  Int_t nc=TRDtrack.GetNumberOfClusters(); 
2838   //  Float_t dedx=0;
2839   //  for (i=0; i<nc; i++) dedx += TRDtrack.GetClusterdQdl(i);
2840   //  dedx /= nc;
2841   //  for (Int_t iPlane = 0; iPlane < kNPlane; iPlane++) {
2842   //    TRDtrack.SetPIDsignals(dedx, iPlane);
2843   //    TRDtrack.SetPIDTimBin(timbin[iPlane], iPlane);
2844   //  }
2845
2846 }
2847
2848 //_____________________________________________________________________________
2849 Int_t AliTRDtracker::FindClusters(Int_t sector, Int_t t0, Int_t t1
2850                                 , AliTRDtrack * track
2851                                 , Int_t *clusters,AliTRDtracklet&tracklet)
2852 {
2853   //
2854   //
2855   // Try to find nearest clusters to the track in timebins from t0 to t1 
2856   //  
2857   //
2858   //  
2859   // correction coeficients   - depends on TRD parameters  - to be changed according it
2860   //
2861
2862   Double_t x[100],yt[100],zt[100];
2863   Double_t xmean=0;   //reference x
2864   Double_t dz[10][100],dy[10][100];
2865   Float_t zmean[100], nmean[100];
2866   Int_t    clfound=0;
2867   Int_t    indexes[10][100];    // indexes of the clusters in the road
2868   AliTRDcluster *cl[10][100];   // pointers to the clusters in the road
2869   Int_t    best[10][100];       // index of best matching cluster 
2870   //
2871   //
2872
2873   for (Int_t it=0;it<100; it++){
2874     x[it]=0;
2875     yt[it]=0;
2876     zt[it]=0;
2877     clusters[it]=-2;
2878     zmean[it]=0;
2879     nmean[it]=0;
2880     //
2881     for (Int_t ih=0;ih<10;ih++){
2882       indexes[ih][it]=-2;              //reset indexes1
2883       cl[ih][it]=0;
2884       dz[ih][it]=-100;
2885       dy[ih][it]=-100;
2886       best[ih][it]=0;
2887     }
2888   }  
2889   //
2890   Double_t x0 = track->GetX();
2891   Double_t sigmaz = TMath::Sqrt(TMath::Abs(track->GetSigmaZ2()));
2892   Int_t nall=0;
2893   Int_t nfound=0;
2894   Double_t h01 =0;
2895   Int_t plane =-1;
2896   Int_t detector =-1;
2897   Float_t padlength=0;
2898   AliTRDtrack track2(*track);
2899   Float_t snpy = track->GetSnp();
2900   Float_t tany = TMath::Sqrt(snpy*snpy/(1.-snpy*snpy)); 
2901   if (snpy<0) tany*=-1;
2902   //
2903   Double_t sy2=ExpectedSigmaY2(x0,track->GetTgl(),track->GetPt());
2904   Double_t sz2=ExpectedSigmaZ2(x0,track->GetTgl());
2905   Double_t road = 15.*sqrt(track->GetSigmaY2() + sy2);
2906   if (road>6.) road=6.;
2907
2908   //
2909   for (Int_t it=0;it<t1-t0;it++){
2910     Double_t maxChi2[2]={fgkMaxChi2,fgkMaxChi2};      
2911     AliTRDpropagationLayer& timeBin=*(fTrSec[sector]->GetLayer(it+t0));
2912     if (timeBin==0) continue;  // no indexes1
2913     Int_t maxn = timeBin;
2914     x[it] = timeBin.GetX();
2915     track2.PropagateTo(x[it]);
2916     yt[it] = track2.GetY();
2917     zt[it] = track2.GetZ();
2918     
2919     Double_t  y=yt[it],z=zt[it];
2920     Double_t chi2 =1000000;
2921     nall++;
2922     //
2923     // find 2 nearest cluster at given time bin
2924     // 
2925     // 
2926     for (Int_t i=timeBin.Find(y-road); i<maxn; i++) {
2927       AliTRDcluster* c=(AliTRDcluster*)(timeBin[i]);
2928       h01 = GetTiltFactor(c);
2929       if (plane<0){
2930         Int_t det = c->GetDetector();
2931         plane = fGeom->GetPlane(det);
2932         padlength = TMath::Sqrt(c->GetSigmaZ2()*12.);
2933       }
2934       //      if (c->GetLocalTimeBin()==0) continue;
2935       if (c->GetY() > y+road) break;
2936       if((c->GetZ()-z)*(c->GetZ()-z) > 12. * sz2) continue;      
2937
2938       Double_t dist = TMath::Abs(c->GetZ()-z);
2939       if (dist> (0.5*padlength+6.*sigmaz)) continue;   // 6 sigma boundary cut
2940       Double_t cost = 0;
2941       //
2942       if (dist> (0.5*padlength-sigmaz)){   //  sigma boundary cost function
2943         cost =  (dist-0.5*padlength)/(2.*sigmaz);
2944         if (cost>-1) cost= (cost+1.)*(cost+1.);
2945         else cost=0;
2946       }      
2947       //      Int_t label = TMath::Abs(track->GetLabel());
2948       //      if (c->GetLabel(0)!=label && c->GetLabel(1)!=label&&c->GetLabel(2)!=label) continue;
2949       chi2=track2.GetPredictedChi2(c,h01)+cost;
2950       //
2951       clfound++;      
2952       if (chi2 > maxChi2[1]) continue;
2953       detector = c->GetDetector();
2954       
2955       for (Int_t ih=2;ih<9; ih++){  //store the clusters in the road
2956         if (cl[ih][it]==0){
2957           cl[ih][it] = c;
2958           indexes[ih][it] =timeBin.GetIndex(i);   // index - 9 - reserved for outliers
2959           break;
2960         }
2961       }
2962       //
2963       if (chi2 <maxChi2[0]){
2964         maxChi2[1]     = maxChi2[0];
2965         maxChi2[0]     = chi2;
2966         indexes[1][it] = indexes[0][it];
2967         cl[1][it]      = cl[0][it];
2968         indexes[0][it] = timeBin.GetIndex(i);
2969         cl[0][it]      = c;
2970         continue;
2971       }
2972       maxChi2[1]=chi2;
2973       cl[1][it] = c;
2974       indexes[1][it] =timeBin.GetIndex(i); 
2975     }         
2976     if (cl[0][it]){
2977       nfound++;
2978       xmean += x[it];
2979     }
2980   }
2981   //
2982   if (nfound<4) return 0;  
2983   xmean /=Float_t(nfound);     // middle x
2984   track2.PropagateTo(xmean);   // propagate track to the center
2985   //
2986   // choose one of the variants
2987   //
2988   Int_t changes[10];
2989   Float_t sumz      = 0;
2990   Float_t sum       = 0;
2991   Double_t sumdy    = 0;
2992   Double_t sumdy2   = 0;
2993   Double_t sumx     = 0;
2994   Double_t sumxy    = 0;
2995   Double_t sumx2    = 0;
2996   Double_t mpads    = 0;
2997   //
2998   Int_t   ngood[10];
2999   Int_t   nbad[10];
3000   //
3001   Double_t meanz[10];
3002   Double_t moffset[10];    // mean offset
3003   Double_t mean[10];       // mean value
3004   Double_t angle[10];      // angle
3005   //
3006   Double_t smoffset[10];   // sigma of mean offset
3007   Double_t smean[10];      // sigma of mean value
3008   Double_t sangle[10];     // sigma of angle
3009   Double_t smeanangle[10]; // correlation
3010   //
3011   Double_t sigmas[10];     
3012   Double_t tchi2s[10];      // chi2s for tracklet
3013
3014   for (Int_t it=0;it<10;it++) {
3015
3016     ngood[it] = 0;
3017     nbad[it] = 0;
3018   //
3019     meanz[it] = 0;
3020     moffset[it] = 0;    // mean offset
3021     mean[it] = 0;       // mean value
3022     angle[it] = 0;      // angle
3023   //
3024     smoffset[it] = 1e10;   // sigma of mean offset
3025     smean[it] = 1e10;      // sigma of mean value
3026     sangle[it] = 1e10;     // sigma of angle
3027     smeanangle[it] = 0; // correlation
3028   //
3029     sigmas[it] = 1e10;     
3030     tchi2s[it] = 1e10;      // chi2s for tracklet
3031
3032   }
3033
3034   //
3035   // calculate zmean
3036   //
3037   for (Int_t it=0;it<t1-t0;it++){
3038     if (!cl[0][it]) continue;
3039     for (Int_t dt=-3;dt<=3;dt++){
3040       if (it+dt<0) continue;
3041       if (it+dt>t1-t0) continue;
3042       if (!cl[0][it+dt]) continue;
3043       zmean[it]+=cl[0][it+dt]->GetZ();
3044       nmean[it]+=1.;
3045     }
3046     zmean[it]/=nmean[it]; 
3047   }
3048   //
3049   for (Int_t it=0; it<t1-t0;it++){
3050     best[0][it]=0;
3051     for (Int_t ih=0;ih<10;ih++){
3052       dz[ih][it]=-100;
3053       dy[ih][it]=-100;
3054       if (!cl[ih][it]) continue;
3055       Double_t  xcluster = cl[ih][it]->GetX();
3056       Double_t ytrack,ztrack;
3057       track2.GetProlongation(xcluster, ytrack, ztrack );
3058       dz[ih][it]  = cl[ih][it]->GetZ()- ztrack;                               // calculate distance from track  in z
3059       dy[ih][it]  = cl[ih][it]->GetY()+ dz[ih][it]*h01  -ytrack;     //                                in y
3060     }
3061     // minimize changes
3062     if (!cl[0][it]) continue;
3063     if (TMath::Abs(cl[0][it]->GetZ()-zmean[it])> padlength*0.8 &&cl[1][it])
3064       if (TMath::Abs(cl[1][it]->GetZ()-zmean[it])< padlength*0.5){
3065         best[0][it]=1;
3066       }
3067   }
3068   //
3069   // iterative choosing of "best path"
3070   //
3071   //
3072   Int_t label = TMath::Abs(track->GetLabel());
3073   Int_t bestiter=0;
3074   //
3075   for (Int_t iter=0;iter<9;iter++){
3076     //
3077     changes[iter]= 0;
3078     sumz      = 0; sum=0; sumdy=0;sumdy2=0;sumx=0;sumx2=0;sumxy=0;mpads=0; ngood[iter]=0; nbad[iter]=0; 
3079     // linear fit
3080     for (Int_t it=0;it<t1-t0;it++){
3081       if (!cl[best[iter][it]][it]) continue;
3082       //calculates pad-row changes
3083       Double_t zbefore= cl[best[iter][it]][it]->GetZ();
3084       Double_t zafter = cl[best[iter][it]][it]->GetZ();
3085       for (Int_t itd = it-1; itd>=0;itd--) {
3086         if (cl[best[iter][itd]][itd]) {
3087           zbefore= cl[best[iter][itd]][itd]->GetZ();
3088           break;
3089         }
3090       }
3091       for (Int_t itd = it+1; itd<t1-t0;itd++) {
3092         if (cl[best[iter][itd]][itd]) {
3093           zafter= cl[best[iter][itd]][itd]->GetZ();
3094           break;
3095         }
3096       }
3097       if (TMath::Abs(cl[best[iter][it]][it]->GetZ()-zbefore)>0.1&&TMath::Abs(cl[best[iter][it]][it]->GetZ()-zafter)>0.1) changes[iter]++;
3098       //
3099       Double_t dx = x[it]-xmean;  // distance to reference x
3100       sumz += cl[best[iter][it]][it]->GetZ();      
3101       sum++;
3102       sumdy += dy[best[iter][it]][it];
3103       sumdy2+= dy[best[iter][it]][it]*dy[best[iter][it]][it];
3104       sumx  += dx;
3105       sumx2 += dx*dx;
3106       sumxy  += dx*dy[best[iter][it]][it];
3107       mpads += cl[best[iter][it]][it]->GetNPads();
3108       if (cl[best[iter][it]][it]->GetLabel(0)==label || cl[best[iter][it]][it]->GetLabel(1)==label||cl[best[iter][it]][it]->GetLabel(2)==label){
3109         ngood[iter]++;
3110       }
3111       else{
3112         nbad[iter]++;
3113       }
3114     }
3115     //
3116     // calculates line parameters
3117     //
3118     Double_t det  = sum*sumx2-sumx*sumx;
3119     angle[iter]   = (sum*sumxy-sumx*sumdy)/det;
3120     mean[iter]    = (sumx2*sumdy-sumx*sumxy)/det;
3121     meanz[iter]   = sumz/sum;    
3122     moffset[iter] = sumdy/sum;
3123     mpads        /= sum;                         // mean number of pads
3124     //
3125     //
3126     Double_t  sigma2 = 0;   // normalized residuals - for line fit
3127     Double_t  sigma1 = 0;   // normalized residuals - constant fit
3128     //
3129     for (Int_t it=0;it<t1-t0;it++){
3130       if (!cl[best[iter][it]][it]) continue;
3131       Double_t dx = x[it]-xmean;
3132       Double_t ytr = mean[iter]+angle[iter]*dx;
3133       sigma2 += (dy[best[iter][it]][it]-ytr)*(dy[best[iter][it]][it]-ytr);
3134       sigma1 +=  (dy[best[iter][it]][it]-moffset[iter])*(dy[best[iter][it]][it]-moffset[iter]);
3135       sum++;
3136     }
3137     sigma2      /=(sum-2);                    // normalized residuals
3138     sigma1      /=(sum-1);                    // normalized residuals
3139     //
3140     smean[iter]       = sigma2*(sumx2/det);   // estimated error2 of mean
3141     sangle[iter]      = sigma2*(sum/det);     // estimated error2 of angle
3142     smeanangle[iter]  = sigma2*(-sumx/det);   // correlation
3143     //
3144     //
3145     sigmas[iter]  = TMath::Sqrt(sigma1);      //
3146     smoffset[iter]= (sigma1/sum)+0.01*0.01;             // sigma of mean offset + unisochronity sigma 
3147     //
3148     // iterative choosing of "better path"
3149     //
3150     for (Int_t it=0;it<t1-t0;it++){
3151       if (!cl[best[iter][it]][it]) continue;
3152       //
3153       Double_t sigmatr2 = smoffset[iter]+0.5*tany*tany;             //add unisochronity + angular effect contribution
3154       Double_t sweight  = 1./sigmatr2+1./track->GetSigmaY2();
3155       Double_t weighty  = (moffset[iter]/sigmatr2)/sweight;         // weighted mean
3156       Double_t sigmacl  = TMath::Sqrt(sigma1*sigma1+track->GetSigmaY2());   //
3157       Double_t mindist=100000; 
3158       Int_t ihbest=0;
3159       for (Int_t ih=0;ih<10;ih++){
3160         if (!cl[ih][it]) break;
3161         Double_t dist2 = (dy[ih][it]-weighty)/sigmacl;
3162         dist2*=dist2;    //chi2 distance
3163         if (dist2<mindist){
3164           mindist = dist2;
3165           ihbest =ih;
3166         }
3167       }
3168       best[iter+1][it]=ihbest;
3169     }
3170     //
3171     //  update best hypothesy if better chi2 according tracklet position and angle
3172     //
3173     Double_t sy2 = smean[iter]  + track->GetSigmaY2();
3174     Double_t sa2 = sangle[iter] + track->fCee;
3175     Double_t say = track->fCey;
3176     //    Double_t chi20 = mean[bestiter]*mean[bestiter]/sy2+angle[bestiter]*angle[bestiter]/sa2;
3177     // Double_t chi21 = mean[iter]*mean[iter]/sy2+angle[iter]*angle[iter]/sa2;
3178
3179     Double_t detchi    = sy2*sa2-say*say;
3180     Double_t invers[3] = {sa2/detchi, sy2/detchi, -say/detchi};   //inverse value of covariance matrix  
3181     
3182     Double_t chi20 = mean[bestiter]*mean[bestiter]*invers[0]+angle[bestiter]*angle[bestiter]*invers[1]+
3183       2.*mean[bestiter]*angle[bestiter]*invers[2];
3184     Double_t chi21 = mean[iter]*mean[iter]*invers[0]+angle[iter]*angle[iter]*invers[1]+
3185       2*mean[iter]*angle[iter]*invers[2];
3186     tchi2s[iter] =chi21;
3187     //
3188     if (changes[iter]<=changes[bestiter] && chi21<chi20) {
3189       bestiter =iter;      
3190     }
3191   }
3192   //
3193   //set clusters 
3194   //
3195   Double_t sigma2 = sigmas[0];   // choose as sigma  from 0 iteration
3196   Short_t maxpos    = -1;
3197   Float_t maxcharge =  0;
3198   Short_t maxpos4    = -1;
3199   Float_t maxcharge4 =  0;
3200   Short_t maxpos5    = -1;
3201   Float_t maxcharge5 =  0;
3202
3203   //if (tchi2s[bestiter]>25.) sigma2*=tchi2s[bestiter]/25.;
3204   //if (tchi2s[bestiter]>25.) sigma2=1000.;  // dont'accept
3205
3206   Double_t exB = AliTRDcalibDB::Instance()->GetOmegaTau(AliTRDcalibDB::Instance()->GetVdrift(0,0,0));
3207   Double_t expectederr = sigma2*sigma2+0.01*0.01;
3208   if (mpads>3.5) expectederr  +=   (mpads-3.5)*0.04;
3209   if (changes[bestiter]>1) expectederr+=   changes[bestiter]*0.01; 
3210   expectederr+=(0.03*(tany-exB)*(tany-exB))*15;
3211   //  if (tchi2s[bestiter]>18.) expectederr*= tchi2s[bestiter]/18.;
3212   //expectederr+=10000;
3213   for (Int_t it=0;it<t1-t0;it++){
3214     if (!cl[best[bestiter][it]][it]) continue;
3215     cl[best[bestiter][it]][it]->SetSigmaY2(expectederr);  // set cluster error
3216     if (!cl[best[bestiter][it]][it]->IsUsed()){
3217       cl[best[bestiter][it]][it]->SetY( cl[best[bestiter][it]][it]->GetY()); 
3218       //      cl[best[bestiter][it]][it]->Use();
3219     }
3220     //
3221     //  time bins with maximal charge
3222     if (TMath::Abs(cl[best[bestiter][it]][it]->GetQ())> maxcharge){
3223       maxcharge = TMath::Abs(cl[best[bestiter][it]][it]->GetQ());
3224       maxpos = cl[best[bestiter][it]][it]->GetLocalTimeBin();
3225     }
3226     
3227     if (TMath::Abs(cl[best[bestiter][it]][it]->GetQ())> maxcharge4){
3228       if (cl[best[bestiter][it]][it]->GetLocalTimeBin()>=4){
3229         maxcharge4 = TMath::Abs(cl[best[bestiter][it]][it]->GetQ());
3230         maxpos4 = cl[best[bestiter][it]][it]->GetLocalTimeBin();
3231       }
3232     }
3233     if (TMath::Abs(cl[best[bestiter][it]][it]->GetQ())> maxcharge5){
3234       if (cl[best[bestiter][it]][it]->GetLocalTimeBin()>=5){
3235         maxcharge5 = TMath::Abs(cl[best[bestiter][it]][it]->GetQ());
3236         maxpos5 = cl[best[bestiter][it]][it]->GetLocalTimeBin();
3237       }
3238     }
3239     //
3240     //  time bins with maximal charge
3241     if (TMath::Abs(cl[best[bestiter][it]][it]->GetQ())> maxcharge){
3242       maxcharge = TMath::Abs(cl[best[bestiter][it]][it]->GetQ());
3243       maxpos = cl[best[bestiter][it]][it]->GetLocalTimeBin();
3244     }
3245     
3246     if (TMath::Abs(cl[best[bestiter][it]][it]->GetQ())> maxcharge4){
3247       if (cl[best[bestiter][it]][it]->GetLocalTimeBin()>=4){
3248         maxcharge4 = TMath::Abs(cl[best[bestiter][it]][it]->GetQ());
3249         maxpos4 = cl[best[bestiter][it]][it]->GetLocalTimeBin();
3250       }
3251     }
3252     if (TMath::Abs(cl[best[bestiter][it]][it]->GetQ())> maxcharge5){
3253       if (cl[best[bestiter][it]][it]->GetLocalTimeBin()>=5){
3254         maxcharge5 = TMath::Abs(cl[best[bestiter][it]][it]->GetQ());
3255         maxpos5 = cl[best[bestiter][it]][it]->GetLocalTimeBin();
3256       }
3257     }
3258     clusters[it+t0] = indexes[best[bestiter][it]][it];    
3259     //if (cl[best[bestiter][it]][it]->GetLocalTimeBin()>4 && cl[best[bestiter][it]][it]->GetLocalTimeBin()<18) clusters[it+t0] = indexes[best[bestiter][it]][it];    //Test
3260   } 
3261   //
3262   // set tracklet parameters
3263   //
3264   Double_t trackleterr2 = smoffset[bestiter]+0.01*0.01;
3265   if (mpads>3.5) trackleterr2  +=   (mpads-3.5)*0.04;
3266   trackleterr2+=   changes[bestiter]*0.01;
3267   trackleterr2*=   TMath::Max(14.-nfound,1.);
3268   trackleterr2+=   0.2*(tany-exB)*(tany-exB); 
3269   //
3270   tracklet.Set(xmean, track2.GetY()+moffset[bestiter], meanz[bestiter], track2.GetAlpha(), trackleterr2);  //set tracklet parameters
3271   tracklet.SetTilt(h01);
3272   tracklet.SetP0(mean[bestiter]);
3273   tracklet.SetP1(angle[bestiter]);
3274   tracklet.SetN(nfound);
3275   tracklet.SetNCross(changes[bestiter]);
3276   tracklet.SetPlane(plane);
3277   tracklet.SetSigma2(expectederr);
3278   tracklet.SetChi2(tchi2s[bestiter]);
3279   tracklet.SetMaxPos(maxpos,maxpos4,maxpos5);
3280   track->fTracklets[plane] = tracklet;
3281   track->fNWrong+=nbad[0];
3282   //
3283   // Debuging part
3284   //
3285   TClonesArray array0("AliTRDcluster");
3286   TClonesArray array1("AliTRDcluster");
3287   array0.ExpandCreateFast(t1-t0+1);
3288   array1.ExpandCreateFast(t1-t0+1);
3289   TTreeSRedirector& cstream = *fDebugStreamer;
3290   AliTRDcluster dummy;
3291   Double_t dy0[100];
3292   Double_t dyb[100]; 
3293
3294   for (Int_t it=0;it<t1-t0;it++){
3295     dy0[it] = dy[0][it];
3296     dyb[it] = dy[best[bestiter][it]][it];
3297     if(cl[0][it]) {
3298       new(array0[it]) AliTRDcluster(*cl[0][it]);
3299     }
3300     else{
3301       new(array0[it]) AliTRDcluster(dummy);
3302     }
3303     if(cl[best[bestiter][it]][it]) {
3304       new(array1[it]) AliTRDcluster(*cl[best[bestiter][it]][it]);
3305     }
3306     else{
3307       new(array1[it]) AliTRDcluster(dummy);
3308     }
3309   }
3310   TGraph graph0(t1-t0,x,dy0);
3311   TGraph graph1(t1-t0,x,dyb);
3312   TGraph graphy(t1-t0,x,yt);
3313   TGraph graphz(t1-t0,x,zt);
3314   //
3315   //
3316   if (AliTRDReconstructor::StreamLevel()>0)
3317   cstream<<"tracklet"<<
3318     "track.="<<track<<                                       // track parameters
3319     "tany="<<tany<<                                          // tangent of the local track angle 
3320     "xmean="<<xmean<<                                        // xmean - reference x of tracklet  
3321     "tilt="<<h01<<                                           // tilt angle
3322     "nall="<<nall<<                                          // number of foundable clusters 
3323     "nfound="<<nfound<<                                      // number of found clusters
3324     "clfound="<<clfound<<                                    // total number of found clusters in road 
3325     "mpads="<<mpads<<                                        // mean number of pads per cluster
3326     "plane="<<plane<<                                        // plane number 
3327     "detector="<<detector<<                                  // detector number
3328     "road="<<road<<                                          // the width of the used road
3329     "graph0.="<<&graph0<<                                    // x - y = dy for closest cluster
3330     "graph1.="<<&graph1<<                                    // x - y = dy for second closest cluster    
3331     "graphy.="<<&graphy<<                                    // y position of the track
3332     "graphz.="<<&graphz<<                                    // z position of the track
3333     //    "fCl.="<<&array0<<                                       // closest cluster
3334     //"fCl2.="<<&array1<<                                      // second closest cluster
3335     "maxpos="<<maxpos<<                                      // maximal charge postion
3336     "maxcharge="<<maxcharge<<                                // maximal charge 
3337     "maxpos4="<<maxpos4<<                                    // maximal charge postion - after bin 4
3338     "maxcharge4="<<maxcharge4<<                              // maximal charge         - after bin 4
3339     "maxpos5="<<maxpos5<<                                    // maximal charge postion - after bin 5
3340     "maxcharge5="<<maxcharge5<<                              // maximal charge         - after bin 5
3341     //
3342     "bestiter="<<bestiter<<                                  // best iteration number 
3343     "tracklet.="<<&tracklet<<                                // corrspond to the best iteration
3344     "tchi20="<<tchi2s[0]<<                                   // chi2 of cluster in the 0 iteration
3345     "tchi2b="<<tchi2s[bestiter]<<                            // chi2 of cluster in the best  iteration
3346     "sigmas0="<<sigmas[0]<<                                  // residuals sigma 
3347     "sigmasb="<<sigmas[bestiter]<<                           // residulas sigma
3348     //
3349     "ngood0="<<ngood[0]<<                                    // number of good clusters in 0 iteration
3350     "nbad0="<<nbad[0]<<                                      // number of bad clusters in 0 iteration
3351     "ngoodb="<<ngood[bestiter]<<                             //                        in  best iteration    
3352     "nbadb="<<nbad[bestiter]<<                               //                        in  best iteration
3353     //
3354     "changes0="<<changes[0]<<                                // changes of pardrows in iteration number 0 
3355     "changesb="<<changes[bestiter]<<                         // changes of pardrows in best iteration
3356     //
3357     "moffset0="<<moffset[0]<<                                // offset fixing angle in iter=0
3358     "smoffset0="<<smoffset[0]<<                              // sigma of offset fixing angle in iter=0
3359     "moffsetb="<<moffset[bestiter]<<                         // offset fixing angle in iter=best
3360     "smoffsetb="<<smoffset[bestiter]<<                       // sigma of offset fixing angle in iter=best
3361     //
3362     "mean0="<<mean[0]<<                                      // mean dy in iter=0;
3363     "smean0="<<smean[0]<<                                    // sigma of mean dy in iter=0
3364     "meanb="<<mean[bestiter]<<                               // mean dy in iter=best
3365     "smeanb="<<smean[bestiter]<<                             // sigma of mean dy in iter=best
3366     //
3367     "angle0="<<angle[0]<<                                    // angle deviation in the iteration number 0 
3368     "sangle0="<<sangle[0]<<                                  // sigma of angular deviation in iteration number 0
3369     "angleb="<<angle[bestiter]<<                             // angle deviation in the best iteration   
3370     "sangleb="<<sangle[bestiter]<<                           // sigma of angle deviation in the best iteration   
3371     //
3372     "expectederr="<<expectederr<<                            // expected error of cluster position
3373     "\n";
3374   //
3375   //
3376   return nfound;
3377
3378 }
3379
3380 //_____________________________________________________________________________
3381 Int_t AliTRDtracker::Freq(Int_t n, const Int_t *inlist
3382                         , Int_t *outlist, Bool_t down)
3383 {    
3384   //
3385   //  Sort eleements according occurancy 
3386   //  The size of output array has is 2*n 
3387   //
3388
3389   Int_t * sindexS = new Int_t[n];     // temp array for sorting
3390   Int_t * sindexF = new Int_t[2*n];   
3391   for (Int_t i=0;i<n;i++) sindexF[i]=0;
3392   //
3393   TMath::Sort(n,inlist, sindexS, down);  
3394   Int_t last      = inlist[sindexS[0]];
3395   Int_t val       = last;
3396   sindexF[0]      = 1;
3397   sindexF[0+n]    = last;
3398   Int_t countPos  = 0;
3399   //
3400   //  find frequency
3401   for(Int_t i=1;i<n; i++){
3402     val = inlist[sindexS[i]];
3403     if (last == val)   sindexF[countPos]++;
3404     else{      
3405       countPos++;
3406       sindexF[countPos+n] = val;
3407       sindexF[countPos]++;
3408       last =val;
3409     }
3410   }
3411   if (last==val) countPos++;
3412   // sort according frequency
3413   TMath::Sort(countPos, sindexF, sindexS, kTRUE);
3414   for (Int_t i=0;i<countPos;i++){
3415     outlist[2*i  ] = sindexF[sindexS[i]+n];
3416     outlist[2*i+1] = sindexF[sindexS[i]];
3417   }
3418   delete [] sindexS;
3419   delete [] sindexF;
3420   
3421   return countPos;
3422
3423 }
3424
3425 //_____________________________________________________________________________
3426 AliTRDtrack *AliTRDtracker::RegisterSeed(AliTRDseed * seeds, Double_t * params)
3427 {
3428   //
3429   // Register a seed
3430   //
3431   Double_t alpha=AliTRDgeometry::GetAlpha();
3432   Double_t shift=AliTRDgeometry::GetAlpha()/2.;
3433   Double_t c[15];
3434   c[0] = 0.2;
3435   c[1] = 0  ; c[2] = 2;
3436   c[3] = 0  ; c[4] = 0; c[5] = 0.02;
3437   c[6] = 0  ; c[7] = 0; c[8] = 0;      c[9] = 0.1;
3438   c[10] = 0  ; c[11] = 0; c[12] = 0;   c[13] = 0.0; c[14] = params[5]*params[5]*0.01;
3439   //
3440   Int_t index =0;
3441   AliTRDcluster *cl =0;
3442   for (Int_t ilayer=0;ilayer<6;ilayer++){
3443     if (seeds[ilayer].IsOK()){
3444       for (Int_t itime=22;itime>0;itime--){
3445         if (seeds[ilayer].fIndexes[itime]>0){
3446           index = seeds[ilayer].fIndexes[itime];
3447           cl = seeds[ilayer].fClusters[itime];
3448           break;
3449         }
3450       }
3451     }
3452     if (index>0) break;
3453   }
3454   if (cl==0) return 0;
3455   AliTRDtrack * track  = new AliTRDtrack(cl,index,&params[1],c, params[0],params[6]*alpha+shift);
3456   track->PropagateTo(params[0]-5.);
3457   track->ResetCovariance(1);
3458   //
3459   Int_t rc=FollowBackProlongation(*track);
3460   if (rc<30) {
3461     delete track;
3462     track =0;
3463   }else{
3464     track->CookdEdx();
3465     CookdEdxTimBin(*track);
3466     CookLabel(track, 0.9);
3467   }
3468
3469   return track;
3470
3471 }