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