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