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