]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ITS/UPGRADE/AliITSUTrackerGlo.cxx
mods. in track update
[u/mrichter/AliRoot.git] / ITS / UPGRADE / AliITSUTrackerGlo.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 /*
17   TO CHECK
18   GetBz usage
19
20  */
21
22 //-------------------------------------------------------------------------
23 //  Implementation of the ITS Upgrade tracker mother class.              
24 //-------------------------------------------------------------------------
25 #include <TTree.h>
26 #include <Riostream.h> 
27 #include <TMath.h>
28
29 #include "AliITSUTrackerGlo.h"
30 #include "AliESDEvent.h"
31 #include "AliESDtrack.h"
32 #include "AliITSURecoDet.h"
33 #include "AliITSURecoSens.h"
34 #include "AliITSUReconstructor.h"
35 #include "AliITSReconstructor.h"
36 #include "AliITSUSeed.h"
37 #include "AliITSUAux.h"
38 #include "AliITSUClusterPix.h"
39 using namespace AliITSUAux;
40 using namespace TMath;
41
42
43
44 //----------------- tmp stuff -----------------
45
46 ClassImp(AliITSUTrackerGlo)
47
48 const Double_t AliITSUTrackerGlo::fgkToler =  1e-6;// tolerance for layer on-surface check
49
50
51 //_________________________________________________________________________
52 AliITSUTrackerGlo::AliITSUTrackerGlo(AliITSUReconstructor* rec)
53 :  fReconstructor(rec)
54   ,fITS(0)
55   ,fCurrESDtrack(0)
56   ,fCurrMass(kPionMass)
57   ,fHypStore(100)
58   ,fCurrHyp(0)
59   ,fSeedsPool("AliITSUSeed",0)
60   ,fFreeSeedsID(0)
61   ,fNFreeSeeds(0)
62   ,fLastSeedID(0)
63   ,fTrCond()
64   ,fTrackPhase(-1)
65   ,fClInfo(0)
66 {
67   // Default constructor
68   if (rec) Init(rec);
69 }
70
71 //_________________________________________________________________________
72 AliITSUTrackerGlo::~AliITSUTrackerGlo()
73 {
74  // Default destructor
75  //  
76   delete fITS;
77   delete[] fClInfo;
78   //
79 }
80
81 //_________________________________________________________________________
82 void AliITSUTrackerGlo::Init(AliITSUReconstructor* rec)
83 {
84   // init with external reconstructor
85   //
86   fITS = new AliITSURecoDet(rec->GetGeom(),"ITSURecoInterface");
87   int nLr = fITS->GetNLayersActive();
88   fClInfo = new Int_t[nLr<<1];
89   for (int ilr=nLr;ilr--;) {
90     fITS->GetLayerActive(ilr)->SetClusters(rec->GetClusters(ilr));
91   }
92   //
93   fSeedsPool.ExpandCreateFast(1000); // RS TOCHECK
94   fFreeSeedsID.Set(1000);
95   //
96   fTrCond.SetNLayers(fITS->GetNLayersActive());
97   fTrCond.AddNewCondition(5);
98   fTrCond.AddGroupPattern( (0x1<<0)|(0x1<<1) );
99   fTrCond.AddGroupPattern( (0x1<<3)|(0x1<<4) );
100   fTrCond.AddGroupPattern( (0x1<<5)|(0x1<<6) );
101   //
102   fTrCond.AddNewCondition(5);
103   fTrCond.AddGroupPattern( (0x1<<0)|(0x1<<2) );
104   fTrCond.AddGroupPattern( (0x1<<3)|(0x1<<4) );
105   fTrCond.AddGroupPattern( (0x1<<5)|(0x1<<6) );
106   //
107   fTrCond.AddNewCondition(5);
108   fTrCond.AddGroupPattern( (0x1<<1)|(0x1<<2) );
109   fTrCond.AddGroupPattern( (0x1<<3)|(0x1<<4) );
110   fTrCond.AddGroupPattern( (0x1<<5)|(0x1<<6) );
111   //
112   printf("Tracking Conditions: ");
113   fTrCond.Print();
114 }
115
116 //_________________________________________________________________________
117 Int_t AliITSUTrackerGlo::Clusters2Tracks(AliESDEvent *esdEv)
118 {
119   //
120   //
121   ResetSeedsPool();
122   fTrackPhase = kClus2Tracks;
123   int nTrESD = esdEv->GetNumberOfTracks();
124   AliInfo(Form("Will try to find prolongations for %d tracks",nTrESD));
125   AliITSUReconstructor::GetRecoParam()->Print();
126   fHypStore.Delete();
127   if (fHypStore.GetSize()<nTrESD) fHypStore.Expand(nTrESD+100);
128   //
129   fITS->ProcessClusters();
130   // select ESD tracks to propagate
131   for (int itr=0;itr<nTrESD;itr++) {
132     AliESDtrack *esdTr = esdEv->GetTrack(itr);
133     AliInfo(Form("Processing track %d | MCLabel: %d",itr,esdTr->GetTPCLabel()));
134     if (!NeedToProlong(esdTr)) continue;  // are we interested in this track?
135     FindTrack(esdTr, itr);
136   }
137   //
138   AliInfo(Form("SeedsPool: %d, BookedUpTo: %d, free: %d",fSeedsPool.GetSize(),fSeedsPool.GetEntriesFast(),fNFreeSeeds));
139   fHypStore.Print();
140   FinalizeHypotheses();
141   //
142   return 0;
143 }
144
145 //_________________________________________________________________________
146 Int_t AliITSUTrackerGlo::PropagateBack(AliESDEvent *esdEv)
147 {
148   //
149   // Do outward fits in ITS
150   //
151   fTrackPhase = kPropBack;
152   int nTrESD = esdEv->GetNumberOfTracks();
153   AliInfo(Form("Will fit %d tracks",nTrESD));
154   //
155   double bz0 = GetBz();
156   Double_t xyzTrk[3],xyzVtx[3]={GetX(),GetY(),GetZ()};
157   AliITSUTrackHyp dummyTr,*currTr=0;
158   const double kWatchStep=10.; // for larger steps watch arc vs segment difference
159   Double_t times[AliPID::kSPECIES];
160   //
161   //
162   for (int itr=0;itr<nTrESD;itr++) {
163     AliESDtrack *esdTr = esdEv->GetTrack(itr);
164     // Start time integral and add distance from current position to vertex 
165     if (esdTr->IsOn(AliESDtrack::kITSout)) continue; // already done
166     //
167     esdTr->GetXYZ(xyzTrk); 
168     Double_t dst = 0.;     // set initial track lenght, tof
169     {
170       double dxs = xyzTrk[0] - xyzVtx[0];
171       double dys = xyzTrk[1] - xyzVtx[1];
172       double dzs = xyzTrk[2] - xyzVtx[2];
173       // RS: for large segment steps d use approximation of cicrular arc s by
174       // s = 2R*asin(d/2R) = d/p asin(p) \approx d/p (p + 1/6 p^3) = d (1+1/6 p^2)
175       // where R is the track radius, p = d/2R = 2C*d (C is the abs curvature)
176       // Hence s^2/d^2 = (1+1/6 p^2)^2
177       dst = dxs*dxs + dys*dys;
178       if (dst > kWatchStep*kWatchStep) { // correct circular part for arc/segment factor
179         double crv = Abs(esdTr->GetC(bz0));
180         double fcarc = 1.+crv*crv*dst/6.;
181         dst *= fcarc*fcarc;
182       }
183       dst += dzs*dzs;
184       dst = Sqrt(dst); 
185     }
186     //    
187     esdTr->SetStatus(AliESDtrack::kTIME);
188     //
189     if (!esdTr->IsOn(AliESDtrack::kITSin)) { // case of tracks w/o ITS prolongation: just set the time integration
190       dummyTr.AliExternalTrackParam::operator=(*esdTr);
191       dummyTr.StartTimeIntegral();
192       dummyTr.AddTimeStep(dst);
193       dummyTr.GetIntegratedTimes(times); 
194       esdTr->SetIntegratedTimes(times);
195       esdTr->SetIntegratedLength(dummyTr.GetIntegratedLength());
196       continue;
197     }
198     //
199     currTr = GetTrackHyp(itr);
200     currTr->StartTimeIntegral();
201     currTr->AddTimeStep(dst);
202     printf("Before resetCov: "); currTr->AliExternalTrackParam::Print();
203     currTr->ResetCovariance(10000);
204     if (RefitTrack(currTr,fITS->GetRMax())) { // propagate to exit from the ITS/TPC screen
205       UpdateESDTrack(currTr,AliESDtrack::kITSout);
206     }
207     //
208   }
209   //
210   return 0;
211 }
212
213 //_________________________________________________________________________
214 Int_t AliITSUTrackerGlo::RefitInward(AliESDEvent * /*event*/)
215 {
216   //
217   // To be implemented 
218   //
219   
220   Info("RefitInward","To be implemented");
221   return 0;
222 }
223
224 //_________________________________________________________________________
225 Int_t AliITSUTrackerGlo::LoadClusters(TTree * treeRP)
226 {
227   // read from tree (if pointer provided) or directly from the ITS reco interface
228   //
229   return fReconstructor->LoadClusters(treeRP);
230
231
232 //_________________________________________________________________________
233 void AliITSUTrackerGlo::UnloadClusters()
234 {
235   //
236   // To be implemented 
237   //
238   
239   Info("UnloadClusters","To be implemented");
240
241 //_________________________________________________________________________
242 AliCluster * AliITSUTrackerGlo::GetCluster(Int_t /*index*/) const
243 {
244   //
245   // To be implemented 
246   //
247   
248   Info("GetCluster","To be implemented");
249   return 0x0;
250
251
252 //_________________________________________________________________________
253 Bool_t AliITSUTrackerGlo::NeedToProlong(AliESDtrack* esdTr)
254 {
255   // do we need to match this track to ITS?
256   //
257   static double bz = GetBz();
258   if (!esdTr->IsOn(AliESDtrack::kTPCin) ||
259       esdTr->IsOn(AliESDtrack::kTPCout) ||
260       esdTr->IsOn(AliESDtrack::kITSin)  ||
261       esdTr->GetKinkIndex(0)>0) return kFALSE;
262   //
263   if (esdTr->Pt()<AliITSUReconstructor::GetRecoParam()->GetMinPtForProlongation()) return kFALSE;
264   //
265   float dtz[2];
266   esdTr->GetDZ(GetX(),GetY(),GetZ(),bz,dtz); 
267   // if track is not V0 candidata but has large offset wrt IP, reject it. RS TOCHECK
268   if ( !(esdTr->GetV0Index(0)>0 && dtz[0]>AliITSUReconstructor::GetRecoParam()->GetMaxDforV0dghtrForProlongation()) 
269        && (Abs(dtz[0])>AliITSUReconstructor::GetRecoParam()->GetMaxDForProlongation() ||
270            Abs(dtz[1])>AliITSUReconstructor::GetRecoParam()->GetMaxDZForProlongation())) return kFALSE;
271   //
272   return kTRUE;
273 }
274
275 //_________________________________________________________________________
276 void AliITSUTrackerGlo::FindTrack(AliESDtrack* esdTr, Int_t esdID)
277 {
278   // find prolongaion candidates finding for single seed
279   //
280   AliITSUSeed seedUC;  // copy of the seed from the upper layer
281   AliITSUSeed seedT;   // transient seed between the seedUC and new prolongation hypothesis
282   //
283   if (!InitHypothesis(esdTr,esdID)) return;  // initialize prolongations hypotheses tree
284   //
285   AliITSURecoSens *hitSens[AliITSURecoSens::kNNeighbors+1];
286   //
287   TObjArray clArr; // container for transfer of clusters matching to seed
288   //
289   int nLrActive = fITS->GetNLayersActive();
290   for (int ila=nLrActive;ila--;) {
291     int ilaUp = ila+1;                         // prolong seeds from layer above
292     //
293     // for the outermost layer the seed is created from the ESD track
294     int nSeedsUp = (ilaUp==nLrActive) ? 1 : fCurrHyp->GetNSeeds(ilaUp);
295     //
296     for (int isd=0;isd<nSeedsUp;isd++) {
297       AliITSUSeed* seedU;
298       if (ilaUp==nLrActive) {
299         seedU = 0;
300         seedUC.InitFromESDTrack(esdTr);
301       }
302       else {
303         seedU = fCurrHyp->GetSeed(ilaUp,isd);  // seed on prev.active layer to prolong  
304         seedUC = *seedU;                       // its copy will be prolonged
305         seedUC.SetParent(seedU);        
306       }
307       seedUC.ResetFMatrix();                    // reset the matrix for propagation to next layer
308       // go till next active layer
309       AliInfo(Form("working on Lr:%d Seed:%d of %d",ila,isd,nSeedsUp));
310       if (!TransportToLayer(&seedUC, fITS->GetLrIDActive(ilaUp), fITS->GetLrIDActive(ila)) ) {
311         //
312         AliInfo("Transport failed");
313         // Check if the seed satisfies to track definition
314         if (NeedToKill(&seedUC,kTransportFailed) && seedU) KillSeed(seedU,kTRUE);
315         continue; // RS TODO: decide what to do with tracks stopped on higher layers w/o killing
316       }
317       AliITSURecoLayer* lrA = fITS->GetLayerActive(ila);
318       if (!GetRoadWidth(&seedUC, ila)) { // failed to find road width on the layer
319         if (NeedToKill(&seedUC,kRWCheckFailed) && seedU) KillSeed(seedU,kTRUE);
320         continue;
321       }
322       int nsens = lrA->FindSensors(&fTrImpData[kTrPhi0], hitSens);  // find detectors which may be hit by the track
323       AliInfo(Form("Will check %d sensors on lr:%d ",nsens,ila));
324       //
325       double bz = GetBz();
326       for (int isn=nsens;isn--;) {
327         seedT = seedUC;
328         AliITSURecoSens* sens = hitSens[isn];
329         //
330         // We need to propagate the seed to sensor on lrA staying the frame of the sensor from prev.layer,
331         // since the transport matrix should be defined in this frame.
332         double xs; // X in the TF of current seed, corresponding to intersection with sensor plane
333         if (!seedT.GetTrackingXAtXAlpha(sens->GetXTF(),sens->GetPhiTF(),bz, xs)) continue;
334         if (!PropagateSeed(&seedT,xs,fCurrMass)) continue;
335         //      if (!seedT.PropagateToX(xs,bz)) continue;
336         //      if (!seedT.Rotate(sens->GetPhiTF())) continue;
337         if (!seedT.RotateToAlpha(sens->GetPhiTF())) continue;
338         //
339         int clID0 = sens->GetFirstClusterId();
340         for (int icl=sens->GetNClusters();icl--;) {
341           int res = CheckCluster(&seedT,ila,clID0+icl);
342           //
343           if (res==kStopSearchOnSensor) break;     // stop looking on this sensor
344           if (res==kClusterNotMatching) continue;  // cluster does not match
345           // cluster is matching and it was added to the hypotheses tree
346         }
347       }
348       // cluster search is done. Do we need ta have a version of this seed skipping current layer
349       seedT.SetLr(ila);
350       if (!NeedToKill(&seedT,kMissingCluster)) {
351         AliITSUSeed* seedSkp = NewSeedFromPool(&seedT);
352         double penalty = -AliITSUReconstructor::GetRecoParam()->GetMissPenalty(ila);
353         // to do: make penalty to account for probability to miss the cluster for good reason
354         seedSkp->SetChi2Cl(penalty);
355         AddProlongationHypothesis(seedSkp,ila);      
356       }
357     }
358     ((TObjArray*)fCurrHyp->GetLayerSeeds(ila))->Sort();
359     printf(">>> All hypotheses on lr %d: \n",ila);
360     for (int ih=0;ih<fCurrHyp->GetNSeeds(ila);ih++) {
361       printf(" #%3d ",ih); fCurrHyp->GetSeed(ila,ih)->Print();
362       //
363       /*
364       if (ila!=0) continue;
365       double vecL[5] = {0};
366       double matL[15] = {0};
367       AliITSUSeed* sp = fCurrHyp->GetSeed(ila,ih);
368       while(sp->GetParent()) {
369         sp->Smooth(vecL,matL);
370         if (sp->GetLayerID()>=fITS->GetNLayersActive()-1) break;
371         sp = (AliITSUSeed*)sp->GetParent();
372       }
373       */
374     }
375   }
376   //
377   SaveCurrentTrackHypotheses();
378   //
379 }
380
381 //_________________________________________________________________________
382 Bool_t AliITSUTrackerGlo::InitHypothesis(AliESDtrack *esdTr, Int_t esdID)
383 {
384   // init prolongaion candidates finding for single seed
385   fCurrHyp = GetTrackHyp(esdID);
386   if (fCurrHyp) return kTRUE;
387   //
388   fCurrMass = esdTr->GetMass();
389   fCurrESDtrack = esdTr;
390   if (fCurrMass<kPionMass*0.9) fCurrMass = kPionMass; // don't trust to mu, e identification from TPCin
391   //
392   fCurrHyp = new AliITSUTrackHyp(fITS->GetNLayersActive());
393   fCurrHyp->SetESDTrack(esdTr);
394   fCurrHyp->SetUniqueID(esdID);
395   fCurrHyp->SetMass(fCurrMass);
396   SetTrackHyp(fCurrHyp,esdID);
397   //
398   return kTRUE;
399   // TO DO
400 }
401
402 //_________________________________________________________________________
403 Bool_t AliITSUTrackerGlo::TransportToLayer(AliITSUSeed* seed, Int_t lFrom, Int_t lTo)
404 {
405   // transport seed from layerFrom to the entrance of layerTo
406   //  
407   //
408   if (lTo==lFrom) AliFatal(Form("was called with lFrom=%d lTo=%d",lFrom,lTo));
409   //
410   int dir = lTo > lFrom ? 1:-1;
411   AliITSURecoLayer* lrFr = fITS->GetLayer(lFrom); // this can be 0 when extrapolation from TPC to ITS is requested
412   Bool_t checkFirst = kTRUE;
413   while(lFrom!=lTo) {
414     if (lrFr) {
415       if (!GoToExitFromLayer(seed,lrFr,dir,checkFirst)) return kFALSE; // go till the end of current layer
416       checkFirst = kFALSE;
417     }
418     AliITSURecoLayer* lrTo =  fITS->GetLayer( (lFrom+=dir) );
419     if (!lrTo) AliFatal(Form("Layer %d does not exist",lFrom));
420     //
421     // go the entrance of the layer, assuming no materials in between
422     double xToGo = lrTo->GetR(-dir);
423     if (!seed->GetXatLabR(xToGo,xToGo,GetBz(),dir)) return kFALSE;
424     if (!PropagateSeed(seed,xToGo,fCurrMass,100, kFALSE )) return kFALSE;
425     lrFr = lrTo;
426   }
427   return kTRUE;
428   //
429 }
430
431 //_________________________________________________________________________
432 Bool_t AliITSUTrackerGlo::TransportToLayer(AliExternalTrackParam* seed, Int_t lFrom, Int_t lTo)
433 {
434   // transport track from layerFrom to the entrance of layerTo
435   //  
436   if (lTo==lFrom) AliFatal(Form("was called with lFrom=%d lTo=%d",lFrom,lTo));
437   //
438   int dir = lTo > lFrom ? 1:-1;
439   AliITSURecoLayer* lrFr = fITS->GetLayer(lFrom); // this can be 0 when extrapolation from TPC to ITS is requested
440   Bool_t checkFirst = kTRUE;
441   while(lFrom!=lTo) {
442     if (lrFr) {
443       if (!GoToExitFromLayer(seed,lrFr,dir,checkFirst)) return kFALSE; // go till the end of current layer
444       checkFirst = kFALSE;
445     }
446     AliITSURecoLayer* lrTo =  fITS->GetLayer( (lFrom+=dir) );
447     if (!lrTo) AliFatal(Form("Layer %d does not exist",lFrom));
448     //
449     if (!GoToExitFromLayer(seed,lrTo,dir)) return kFALSE; // go the entrance of the layer, assuming no materials in between
450     lrFr = lrTo;
451   }
452   return kTRUE;
453   //
454 }
455
456 //_________________________________________________________________________
457 Bool_t AliITSUTrackerGlo::GoToExitFromLayer(AliITSUSeed* seed, AliITSURecoLayer* lr, Int_t dir, Bool_t check)
458 {
459   // go to the exit from lr in direction dir, applying material corrections in steps specific for this layer
460   // If check is requested, do this only provided the track has not exited the layer already
461   double xToGo = lr->GetR(dir);
462   if (check) { // do we need to track till the surface of the current layer ?
463     double curR2 = seed->GetX()*seed->GetX() + seed->GetY()*seed->GetY(); // current radius
464     if      (dir>0) { if (curR2-xToGo*xToGo>fgkToler) return kTRUE; } // on the surface or outside of the layer
465     else if (dir<0) { if (xToGo*xToGo-curR2>fgkToler) return kTRUE; } // on the surface or outside of the layer
466   }
467   if (!seed->GetXatLabR(xToGo,xToGo,GetBz(),dir)) return kFALSE;
468   // go via layer to its boundary, applying material correction.
469   if (!PropagateSeed(seed,xToGo,fCurrMass, lr->GetMaxStep())) return kFALSE;
470   return kTRUE;
471   //
472 }
473
474 //_________________________________________________________________________
475 Bool_t AliITSUTrackerGlo::GoToExitFromLayer(AliExternalTrackParam* seed, AliITSURecoLayer* lr, Int_t dir, Bool_t check)
476 {
477   // go to the exit from lr in direction dir, applying material corrections in steps specific for this layer
478   // If check is requested, do this only provided the track has not exited the layer already
479   double xToGo = lr->GetR(dir);
480   if (check) { // do we need to track till the surface of the current layer ?
481     double curR2 = seed->GetX()*seed->GetX() + seed->GetY()*seed->GetY(); // current radius
482     if      (dir>0) { if (curR2-xToGo*xToGo>fgkToler) return kTRUE; } // on the surface or outside of the layer
483     else if (dir<0) { if (xToGo*xToGo-curR2>fgkToler) return kTRUE; } // on the surface or outside of the layer
484   }
485   if (!seed->GetXatLabR(xToGo,xToGo,GetBz(),dir)) return kFALSE;
486   // go via layer to its boundary, applying material correction.
487   if (!PropagateSeed(seed,xToGo,fCurrMass, lr->GetMaxStep())) return kFALSE;
488   return kTRUE;
489   //
490 }
491
492
493 //_________________________________________________________________________
494 Bool_t AliITSUTrackerGlo::GoToEntranceToLayer(AliITSUSeed* seed, AliITSURecoLayer* lr, Int_t dir, Bool_t check)
495 {
496   // go to the entrance of lr in direction dir, w/o applying material corrections.
497   // If check is requested, do this only provided the track did not reach the layer already
498   double xToGo = lr->GetR(-dir);
499   if (check) { // do we need to track till the surface of the current layer ?
500     double curR2 = seed->GetX()*seed->GetX() + seed->GetY()*seed->GetY(); // current radius
501     if      (dir>0) { if (curR2-xToGo*xToGo>fgkToler) return kTRUE; } // already passed
502     else if (dir<0) { if (xToGo*xToGo-curR2>fgkToler) return kTRUE; } // already passed
503   }
504   if (!seed->GetXatLabR(xToGo,xToGo,GetBz(),dir)) return kFALSE;
505   // go via layer to its boundary, applying material correction.
506   if (!PropagateSeed(seed,xToGo,fCurrMass, 100, kFALSE)) return kFALSE;
507   return kTRUE;
508   //
509 }
510
511 //_________________________________________________________________________
512 Bool_t AliITSUTrackerGlo::GoToEntranceToLayer(AliExternalTrackParam* seed, AliITSURecoLayer* lr, Int_t dir, Bool_t check)
513 {
514   // go to the entrance of lr in direction dir, w/o applying material corrections.
515   // If check is requested, do this only provided the track did not reach the layer already
516   double xToGo = lr->GetR(-dir);
517   if (check) { // do we need to track till the surface of the current layer ?
518     double curR2 = seed->GetX()*seed->GetX() + seed->GetY()*seed->GetY(); // current radius
519     if      (dir>0) { if (curR2-xToGo*xToGo>fgkToler) return kTRUE; } // already passed
520     else if (dir<0) { if (xToGo*xToGo-curR2>fgkToler) return kTRUE; } // already passed
521   }
522   if (!seed->GetXatLabR(xToGo,xToGo,GetBz(),dir)) return kFALSE;
523   // go via layer to its boundary, applying material correction.
524   if (!PropagateSeed(seed,xToGo,fCurrMass, 100, kFALSE)) return kFALSE;
525   return kTRUE;
526   //
527 }
528
529 //_________________________________________________________________________
530 Bool_t AliITSUTrackerGlo::GetRoadWidth(AliITSUSeed* seed, int ilrA)
531 {
532   // calculate road width in terms of phi and z for the track which MUST be on the external radius of the layer
533   // as well as some aux info
534   double bz = GetBz();
535   AliITSURecoLayer* lrA = fITS->GetLayerActive(ilrA);
536   seed->GetXYZ(&fTrImpData[kTrXIn]);    // lab position at the entrance from above
537   static AliExternalTrackParam sc;   // seed copy for manipalitions
538   sc = *seed;
539   //
540   fTrImpData[kTrPhiIn] = ATan2(fTrImpData[kTrYIn],fTrImpData[kTrXIn]);
541   if (!sc.Rotate(fTrImpData[kTrPhiIn])) return kFALSE; // go to the frame of the entry point into the layer
542   double dr  = lrA->GetDR();                              // approximate X dist at the inner radius
543   if (!sc.GetXYZAt(sc.GetX()-dr, bz, fTrImpData + kTrXOut)) {
544     // special case: track does not reach inner radius, might be tangential
545     double r = sc.GetD(0,0,bz);
546     double x;
547     if (!sc.GetXatLabR(r,x,bz,-1)) {
548       sc.Print();
549       AliFatal(Form("This should not happen: r=%f",r));
550     }
551     dr = Abs(sc.GetX() - x);
552     if (!sc.GetXYZAt(x, bz, fTrImpData + kTrXOut)) {
553       sc.Print();
554       AliFatal(Form("This should not happen: x=%f",x));
555     }
556   }
557   //
558   fTrImpData[kTrPhiOut] = ATan2(fTrImpData[kTrYOut],fTrImpData[kTrXOut]);
559   double sgy = sc.GetSigmaY2() + dr*dr*sc.GetSigmaSnp2() + AliITSUReconstructor::GetRecoParam()->GetSigmaY2(ilrA);
560   double sgz = sc.GetSigmaZ2() + dr*dr*sc.GetSigmaTgl2() + AliITSUReconstructor::GetRecoParam()->GetSigmaZ2(ilrA);
561   sgy = Sqrt(sgy)*AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadY();
562   sgz = Sqrt(sgz)*AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadZ();
563   fTrImpData[kTrPhi0] = 0.5*(fTrImpData[kTrPhiOut]+fTrImpData[kTrPhiIn]);
564   fTrImpData[kTrZ0]   = 0.5*(fTrImpData[kTrZOut]+fTrImpData[kTrZIn]);
565   fTrImpData[kTrDPhi] = 0.5*Abs(fTrImpData[kTrPhiOut]-fTrImpData[kTrPhiIn]) + sgy/lrA->GetR();
566   fTrImpData[kTrDZ]   = 0.5*Abs(fTrImpData[kTrZOut]-fTrImpData[kTrZIn])   + sgz;
567   //  
568   return kTRUE;
569 }
570
571 //________________________________________
572 void AliITSUTrackerGlo::ResetSeedsPool()
573 {
574   // mark all seeds in the pool as unused
575   AliInfo(Form("CurrentSize: %d, BookedUpTo: %d, free: %d",fSeedsPool.GetSize(),fSeedsPool.GetEntriesFast(),fNFreeSeeds));
576   fNFreeSeeds = 0;
577   fSeedsPool.Clear(); // seeds don't allocate memory
578 }
579
580
581 //________________________________________
582 void AliITSUTrackerGlo::MarkSeedFree(AliITSUSeed *sd) 
583 {
584   // account that this seed is "deleted" 
585   int id = sd->GetPoolID();
586   if (id<0) {
587     AliError(Form("Freeing of seed %p NOT from the pool is requested",sd)); 
588     return;
589   }
590   //  AliInfo(Form("%d %p",id, seed));
591   fSeedsPool.RemoveAt(id);
592   if (fFreeSeedsID.GetSize()<=fNFreeSeeds) fFreeSeedsID.Set( 2*fNFreeSeeds + 100 );
593   fFreeSeedsID.GetArray()[fNFreeSeeds++] = id;
594 }
595
596 //_________________________________________________________________________
597 Int_t AliITSUTrackerGlo::CheckCluster(AliITSUSeed* track, Int_t lr, Int_t clID) 
598 {
599   // Check if the cluster (in tracking frame!) is matching to track. 
600   // The track must be already propagated to sensor tracking frame.
601   // Returns:  kStopSearchOnSensor if the search on given sensor should be stopped, 
602   //           kClusterMatching    if the cluster is matching
603   //           kClusterMatching    otherwise
604   //
605   const double kTolerX = 5e-4;
606   AliCluster *cl = fITS->GetLayerActive(lr)->GetCluster(clID);
607   //
608   Bool_t goodCl = kFALSE;
609   int currLabel = Abs(fCurrESDtrack->GetTPCLabel());
610   //
611   if (cl->GetLabel(0)>=0) {
612     for (int i=0;i<3;i++) if (cl->GetLabel(i)>=0 && cl->GetLabel(i)==currLabel) {goodCl = kTRUE; break;}
613   }
614   else goodCl = kTRUE;
615   //
616   if (TMath::Abs(cl->GetX())>kTolerX) { // if due to the misalingment X is large, propagate track only
617     if (!track->PropagateParamOnlyTo(track->GetX()+cl->GetX(),GetBz())) {
618       if (goodCl) {printf("Loose good cl: Failed propagation. |"); cl->Print();}
619       return kStopSearchOnSensor; // propagation failed, seedT is intact
620     }
621   }
622   double dy = cl->GetY()-track->GetY();
623   double dz = cl->GetZ()-track->GetZ();
624   //
625   double dy2 = dy*dy;
626   double tol2 = (track->GetSigmaY2() + AliITSUReconstructor::GetRecoParam()->GetSigmaY2(lr))*
627     AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadY()*AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadY(); // RS TOOPTIMIZE
628   if (dy2>tol2) {                          // the clusters are sorted in Z(col) then in Y(row). 
629     if (goodCl) {printf("Loose good cl: dy2=%e > tol2=%e |",dy2,tol2); cl->Print();}
630     if (dy>0) return kStopSearchOnSensor;  // No chance that other cluster of this sensor will match (all Y's will be even larger)
631     else      return kClusterNotMatching;   // Other clusters may match
632   }
633   double dz2 = dz*dz;
634   tol2 = (track->GetSigmaZ2() + AliITSUReconstructor::GetRecoParam()->GetSigmaZ2(lr))*
635     AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadZ()*AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadZ(); // RS TOOPTIMIZE
636   if (dz2>tol2) {
637     if (goodCl) {printf("Loose good cl: dz2=%e > tol2=%e |",dz2,tol2); cl->Print();}
638     return kClusterNotMatching; // Other clusters may match
639   }
640   //
641   // check chi2
642   Double_t p[2]={cl->GetY(), cl->GetZ()};
643   Double_t cov[3]={cl->GetSigmaY2(), cl->GetSigmaYZ(), cl->GetSigmaZ2()};
644   double chi2 = track->GetPredictedChi2(p,cov);
645   if (chi2>AliITSUReconstructor::GetRecoParam()->GetMaxTr2ClChi2(lr)) {
646     if (goodCl) {
647       printf("Loose good cl: Chi2=%e > Chi2Max=%e |dy: %+.3e dz: %+.3e\n",
648              chi2,AliITSUReconstructor::GetRecoParam()->GetMaxTr2ClChi2(lr),dy,dz); 
649       track->Print("etp");
650       cl->Print("");
651     }
652     return kClusterNotMatching;
653   }
654   //
655   track = NewSeedFromPool(track);  // input track will be reused, use its clone for updates
656   if (!track->Update()) {
657     if (goodCl) {printf("Loose good cl: Failed update |"); cl->Print();}
658     MarkSeedFree(track);
659     return kClusterNotMatching;
660   }
661   track->SetChi2Cl(chi2);
662   track->SetLrClusterID(lr,clID);
663   cl->IncreaseClusterUsage();
664   //
665   track->SetFake(!goodCl);
666   //
667   AliInfo(Form("AddCl(%d) Cl%d lr:%d: dY:%+8.4f dZ:%+8.4f (MC: %5d %5d %5d) |Chi2=%f(%c)",
668                goodCl,clID,lr,dy,dz2,cl->GetLabel(0),cl->GetLabel(1),cl->GetLabel(2), chi2, track->IsFake() ? '-':'+'));
669   //
670   AddProlongationHypothesis(track,lr);
671   //
672   return kClusterMatching;
673 }
674
675 //_________________________________________________________________________
676 Bool_t AliITSUTrackerGlo::NeedToKill(AliITSUSeed *seed, Int_t flag)
677 {
678   // check if the seed should not be discarded
679   const UShort_t kMask = 0xffff;
680   if (flag==kMissingCluster) {
681     int lastChecked = seed->GetLayerID();
682     UShort_t patt = seed->GetHitsPattern();
683     if (lastChecked) patt |= ~(kMask<<lastChecked); // not all layers were checked, complete unchecked once by potential hits
684     Bool_t seedOK = fTrCond.CheckPattern(patt);
685     return !seedOK;
686   }
687   return kTRUE;
688 }
689
690 //______________________________________________________________________________
691 Bool_t AliITSUTrackerGlo::PropagateSeed(AliITSUSeed *seed, Double_t xToGo, Double_t mass, Double_t maxStep, Bool_t matCorr) 
692 {
693   // propagate seed to given x applying material correction if requested
694   const Double_t kEpsilon = 1e-5;
695   Double_t xpos     = seed->GetX();
696   Int_t dir         = (xpos<xToGo) ? 1:-1;
697   Double_t xyz0[3],xyz1[3],param[7];
698   //
699   Bool_t updTime = dir>0 && seed->IsStartedTimeIntegral();
700   if (matCorr || updTime) seed->GetXYZ(xyz1);   //starting global position
701   while ( (xToGo-xpos)*dir > kEpsilon){
702     Double_t step = dir*TMath::Min(TMath::Abs(xToGo-xpos), maxStep);
703     Double_t x    = xpos+step;
704     Double_t bz=GetBz();   // getting the local Bz
705     if (!seed->PropagateToX(x,bz))  return kFALSE;
706     double ds = 0;
707     if (matCorr || updTime) {
708       xyz0[0]=xyz1[0]; // global pos at the beginning of step
709       xyz0[1]=xyz1[1];
710       xyz0[2]=xyz1[2];
711       seed->GetXYZ(xyz1);    //  // global pos at the end of step
712       if (matCorr) {
713         MeanMaterialBudget(xyz0,xyz1,param);    
714         Double_t xrho=param[0]*param[4], xx0=param[1];
715         if (dir>0) xrho = -xrho; // outward should be negative
716         if (!seed->ApplyMaterialCorrection(xx0,xrho,mass,kFALSE)) return kFALSE;
717         ds = param[4];
718       }
719        else { // matCorr is not requested but time integral is
720         double d0 = xyz1[0]-xyz0[0];
721         double d1 = xyz1[1]-xyz0[1];
722         double d2 = xyz1[2]-xyz0[2];    
723         ds = TMath::Sqrt(d0*d0+d1*d1+d2*d2);
724       }     
725     }
726     if (updTime) seed->AddTimeStep(ds);
727     xpos = seed->GetX();
728   }
729   return kTRUE;
730 }
731
732 //______________________________________________________________________________
733 Bool_t AliITSUTrackerGlo::PropagateSeed(AliExternalTrackParam *seed, Double_t xToGo, Double_t mass, Double_t maxStep, Bool_t matCorr) 
734 {
735   // propagate seed to given x applying material correction if requested
736   const Double_t kEpsilon = 1e-5;
737   Double_t xpos     = seed->GetX();
738   Int_t dir         = (xpos<xToGo) ? 1:-1;
739   Double_t xyz0[3],xyz1[3],param[7];
740   //
741   Bool_t updTime = dir>0 && seed->IsStartedTimeIntegral();
742   if (matCorr || updTime) seed->GetXYZ(xyz1);   //starting global position
743   while ( (xToGo-xpos)*dir > kEpsilon){
744     Double_t step = dir*TMath::Min(TMath::Abs(xToGo-xpos), maxStep);
745     Double_t x    = xpos+step;
746     Double_t bz=GetBz();   // getting the local Bz
747     if (!seed->PropagateTo(x,bz))  return kFALSE;
748     double ds = 0;
749     if (matCorr || updTime) {
750       xyz0[0]=xyz1[0]; // global pos at the beginning of step
751       xyz0[1]=xyz1[1];
752       xyz0[2]=xyz1[2];
753       seed->GetXYZ(xyz1);    //  // global pos at the end of step
754       //
755       if (matCorr) {
756         MeanMaterialBudget(xyz0,xyz1,param);    
757         Double_t xrho=param[0]*param[4], xx0=param[1];
758         if (dir>0) xrho = -xrho; // outward should be negative
759         if (!seed->CorrectForMeanMaterial(xx0,xrho,mass)) return kFALSE;
760         ds = param[4];
761       }
762       else { // matCorr is not requested but time integral is
763         double d0 = xyz1[0]-xyz0[0];
764         double d1 = xyz1[1]-xyz0[1];
765         double d2 = xyz1[2]-xyz0[2];    
766         ds = TMath::Sqrt(d0*d0+d1*d1+d2*d2);
767       }
768     }
769     if (updTime) seed->AddTimeStep(ds);
770     //
771     xpos = seed->GetX();
772   }
773   return kTRUE;
774 }
775
776 //______________________________________________________________________________
777 void AliITSUTrackerGlo::SaveCurrentTrackHypotheses()
778 {
779   // RS: shall we clean up killed seeds?
780   fCurrHyp = 0;
781   // TODO
782   
783 }
784
785 //______________________________________________________________________________
786 void AliITSUTrackerGlo::FinalizeHypotheses()
787 {
788   // select winner for each hypothesis, remove cl. sharing conflicts
789   AliInfo("TODO");
790   //
791   int nh = fHypStore.GetEntriesFast();
792   for (int ih=0;ih<nh;ih++) {
793     AliITSUTrackHyp* hyp = (AliITSUTrackHyp*) fHypStore.UncheckedAt(ih); 
794     if (!hyp) continue;
795     hyp->DefineWinner();  // TODO
796     CookMCLabel(hyp);
797     UpdateESDTrack(hyp,AliESDtrack::kITSin);
798   }
799
800 }
801
802 //______________________________________________________________________________
803 void AliITSUTrackerGlo::UpdateESDTrack(AliITSUTrackHyp* hyp,Int_t flag)
804 {
805   // update ESD track with current best hypothesis
806   AliESDtrack* esdTr = hyp->GetESDTrack();
807   if (!esdTr) return;
808   AliITSUSeed* win = hyp->GetWinner();
809   if (!win) return;
810   switch (flag) {
811   case AliESDtrack::kITSin: 
812     esdTr->UpdateTrackParams(hyp,flag); // update kinematics
813     // TODO: set cluster info
814     break;
815     //
816   case AliESDtrack::kITSout: 
817     esdTr->UpdateTrackParams(hyp,flag); // update kinematics
818     // TODO: avoid setting friend
819     break;
820     //
821   case AliESDtrack::kITSrefit: 
822     esdTr->UpdateTrackParams(hyp,flag); // update kinematics
823     // TODO: avoid setting cluster info
824     break;
825   default:
826     AliFatal(Form("Unknown flag %d",flag));
827   }
828   //
829   // transfer module indices
830   // TODO
831 }
832
833 //______________________________________________________________________________
834 Bool_t AliITSUTrackerGlo::RefitTrack(AliITSUTrackHyp* trc, Double_t rDest, Bool_t stopAtLastCl)
835 {
836   // refit track till radius rDest
837   AliITSUTrackHyp tmpTr;
838   //
839   double rCurr = Sqrt(trc->GetX()*trc->GetX() + trc->GetY()*trc->GetY());
840   int dir,lrStart,lrStop;
841   //
842   dir = rCurr<rDest ? 1 : -1;
843   lrStart = fITS->FindFirstLayerID(rCurr,dir);
844   lrStop  = fITS->FindLastLayerID(rDest,dir);
845   printf("Refit %d: Lr:%d (%f) -> Lr:%d (%f)\n",dir,lrStart,rCurr, lrStop,rDest);
846   printf("Before refit: "); trc->AliExternalTrackParam::Print();
847   if (lrStop<0 || lrStart<0) AliFatal(Form("Failed to find start(%d) or last(%d) layers. Track from %.3f to %.3f",lrStart,lrStop,rCurr,rDest));
848   //
849   int ncl = trc->FetchClusterInfo(fClInfo);
850   fCurrMass = trc->GetMass();
851   tmpTr.AliKalmanTrack::operator=(*trc);
852   tmpTr.SetChi2(0);
853   int iclLr[2],nclLr,clCount=0;
854   //
855   for (int ilr=lrStart;ilr!=lrStop;ilr+=dir) {
856     AliITSURecoLayer* lr = fITS->GetLayer(ilr);
857     if ( dir*(rCurr-lr->GetR(dir))>0) continue; // this layer is already passed
858     int ilrA2,ilrA = lr->GetActiveID();
859     // passive layer or active w/o hits will be traversed on the way to next cluster
860     if (!lr->IsActive() || fClInfo[ilrA2=(ilrA<<1)]<0) continue; 
861     //
862     if (ilr!=lrStart && !TransportToLayer(&tmpTr,lrStart,ilr)) {
863       printf("Failed to transport %d -> %d\n",lrStart,ilr);
864       return kFALSE; // go to the entrance to the layer
865     }
866     lrStart = ilr;
867     //
868     // select the order in which possible 2 clusters (in case of the overlap) will be traversed and fitted
869     nclLr=0;
870     if (dir>0) { // clusters are stored in increasing radius order
871       iclLr[nclLr++]=fClInfo[ilrA2++];
872       if (fClInfo[ilrA2]>=0) iclLr[nclLr++]=fClInfo[ilrA2];
873     }
874     else {
875       if ( fClInfo[ilrA2+1]>=0 ) iclLr[nclLr++]=fClInfo[ilrA2+1];
876       iclLr[nclLr++]=fClInfo[ilrA2];
877     }
878     //
879     for (int icl=0;icl<nclLr;icl++) {
880       AliITSUClusterPix* clus =  (AliITSUClusterPix*)lr->GetCluster(iclLr[icl]);
881       AliITSURecoSens* sens = lr->GetSensorFromID(clus->GetVolumeId());
882       if (!tmpTr.Rotate(sens->GetPhiTF())) return kFALSE;
883       printf("Refit cl:%d on lr %d Need to go %.4f -> %.4f\n",icl,ilrA,tmpTr.GetX(),sens->GetXTF()+clus->GetX());
884       if (!PropagateSeed(&tmpTr,sens->GetXTF()+clus->GetX(),fCurrMass)) return kFALSE;
885       if (!tmpTr.Update(clus)) return kFALSE;
886       printf("AfterRefit: "); tmpTr.AliExternalTrackParam::Print();
887       if (stopAtLastCl && ++clCount==ncl) return kTRUE; // it was requested to not propagate after last update
888     }
889     //
890   }
891   // All clusters were succesfully fitted. Even if the track does not reach rDest, this is enough to validate it.
892   // Still, try to go as close as possible to rDest.
893   //
894   if (lrStart!=lrStop) {
895     printf("Going to last layer %d -> %d\n",lrStart,lrStop);
896     if (!TransportToLayer(&tmpTr,lrStart,lrStop)) return kTRUE;    
897     if (!GoToExitFromLayer(&tmpTr,fITS->GetLayer(lrStop),dir)) return kFALSE; // go till the exit from layer
898     //
899     printf("On exit from last layer\n");
900     tmpTr.AliExternalTrackParam::Print();
901     // go to the destination radius
902     if (!tmpTr.GetXatLabR(rDest,rDest,GetBz(),dir)) return kTRUE;
903     if (!PropagateSeed(&tmpTr,rDest,fCurrMass, 100, kFALSE)) return kTRUE;
904   }
905   trc->AliKalmanTrack::operator=(tmpTr);
906   printf("After refit (now at lr %d): ",lrStart); trc->AliExternalTrackParam::Print();
907   return kTRUE;
908 }
909
910 //__________________________________________________________________
911 void AliITSUTrackerGlo::CookMCLabel(AliITSUTrackHyp* hyp) 
912 {
913   // build MC label
914   //
915   const int kMaxLbPerCl = 3;
916   int lbID[kMaxLayers*6],lbStat[kMaxLayers*6];
917   Int_t lr,nLab=0,nCl=0;
918   AliITSUSeed *seed = hyp->GetWinner();
919   while(seed) {
920     int clID = seed->GetLrCluster(lr);
921     if (clID>=0) {
922       AliCluster *cl = fITS->GetLayerActive(lr)->GetCluster(clID);
923       nCl++;
924       for (int imc=0;imc<kMaxLbPerCl;imc++) { // labels within single cluster
925         int trLb = cl->GetLabel(imc);
926         if (imc<0) break;
927         // search this mc track in already accounted ones
928         int iLab;
929         for (iLab=0;iLab<nLab;iLab++) if (lbID[iLab]==trLb) break;
930         if (iLab<nLab) lbStat[iLab]++;
931         else {
932           lbID[nLab] = trLb;
933           lbStat[nLab++] = 1;
934         }
935       } // loop over given cluster's labels
936     }
937     seed = (AliITSUSeed*)seed->GetParent();
938   } // loop over clusters
939   // 
940   if (nCl) {
941     int maxLab=0,nTPCok=0;
942     AliESDtrack* esdTr = hyp->GetESDTrack();
943     int tpcLab = esdTr ? Abs(esdTr->GetTPCLabel()) : -kDummyLabel;
944     for (int ilb=nLab;ilb--;) {
945       int st = lbStat[ilb];
946       if (lbStat[maxLab]<st) maxLab=ilb;
947       if (tpcLab==lbID[ilb]) nTPCok += st;
948     }
949     hyp->SetFakeRatio(1.-float(nTPCok)/nCl);
950     hyp->SetLabel( nTPCok==nCl ? tpcLab : -tpcLab);
951     hyp->SetITSLabel( lbStat[maxLab]==nCl ? lbStat[maxLab] : -lbStat[maxLab]); // winner label
952     return;
953   }
954   //
955   hyp->SetFakeRatio(-1.);
956   hyp->SetLabel( kDummyLabel );
957   hyp->SetITSLabel( kDummyLabel );
958 }