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