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