]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDseedV1.cxx
fd53b09399eba2e5a26ae952875a6ee589e188a2
[u/mrichter/AliRoot.git] / TRD / AliTRDseedV1.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 TRD offline tracklet
21 //
22 // The running horse of the TRD reconstruction. The following tasks are preformed:
23 //   1. Clusters attachment to tracks based on prior information stored at tracklet level (see AttachClusters)
24 //   2. Clusters position recalculation based on track information (see GetClusterXY and Fit)
25 //   3. Cluster error parametrization recalculation (see Fit)
26 //   4. Linear track approximation (Fit)
27 //   5. Optimal position (including z estimate for pad row cross tracklets) and covariance matrix of the track fit inside one TRD chamber (Fit)
28 //   6. Tilt pad correction and systematic effects (GetCovAt)
29 //   7. dEdx calculation (CookdEdx)
30 //   8. PID probabilities estimation (CookPID)
31 //
32 //  Authors:                                                              //
33 //    Alex Bercuci <A.Bercuci@gsi.de>                                     //
34 //    Markus Fasel <M.Fasel@gsi.de>                                       //
35 //                                                                        //
36 ////////////////////////////////////////////////////////////////////////////
37
38 #include "TMath.h"
39 #include <TTreeStream.h>
40
41 #include "AliLog.h"
42 #include "AliMathBase.h"
43 #include "AliRieman.h"
44 #include "AliCDBManager.h"
45
46 #include "AliTRDReconstructor.h"
47 #include "AliTRDpadPlane.h"
48 #include "AliTRDcluster.h"
49 #include "AliTRDseedV1.h"
50 #include "AliTRDtrackV1.h"
51 #include "AliTRDcalibDB.h"
52 #include "AliTRDchamberTimeBin.h"
53 #include "AliTRDtrackingChamber.h"
54 #include "AliTRDtrackerV1.h"
55 #include "AliTRDrecoParam.h"
56 #include "AliTRDCommonParam.h"
57
58 #include "Cal/AliTRDCalPID.h"
59 #include "Cal/AliTRDCalROC.h"
60 #include "Cal/AliTRDCalDet.h"
61
62 class AliTracker;
63
64 ClassImp(AliTRDseedV1)
65
66 //____________________________________________________________________
67 AliTRDseedV1::AliTRDseedV1(Int_t det) 
68   :AliTRDtrackletBase()
69   ,fkReconstructor(NULL)
70   ,fClusterIter(NULL)
71   ,fExB(0.)
72   ,fVD(0.)
73   ,fT0(0.)
74   ,fS2PRF(0.)
75   ,fDiffL(0.)
76   ,fDiffT(0.)
77   ,fClusterIdx(0)
78   ,fErrorMsg(0)
79   ,fN(0)
80   ,fDet(det)
81   ,fPt(0.)
82   ,fdX(0.)
83   ,fX0(0.)
84   ,fX(0.)
85   ,fY(0.)
86   ,fZ(0.)
87   ,fS2Y(0.)
88   ,fS2Z(0.)
89   ,fChi2(0.)
90 {
91   //
92   // Constructor
93   //
94   memset(fIndexes,0xFF,kNclusters*sizeof(fIndexes[0]));
95   memset(fClusters, 0, kNclusters*sizeof(AliTRDcluster*));
96   memset(fPad, 0, 4*sizeof(Float_t));
97   fYref[0] = 0.; fYref[1] = 0.; 
98   fZref[0] = 0.; fZref[1] = 0.; 
99   fYfit[0] = 0.; fYfit[1] = 0.; 
100   fZfit[0] = 0.; fZfit[1] = 0.; 
101   memset(fdEdx, 0, kNslices*sizeof(Float_t)); 
102   for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec]  = -1.;
103   fLabels[0]=-1; fLabels[1]=-1; // most freq MC labels
104   fLabels[2]=0;  // number of different labels for tracklet
105   memset(fRefCov, 0, 7*sizeof(Double_t));
106   // stand alone curvature
107   fC[0] = 0.; fC[1] = 0.; 
108   // covariance matrix [diagonal]
109   // default sy = 200um and sz = 2.3 cm 
110   fCov[0] = 4.e-4; fCov[1] = 0.; fCov[2] = 5.3; 
111   SetStandAlone(kFALSE);
112 }
113
114 //____________________________________________________________________
115 AliTRDseedV1::AliTRDseedV1(const AliTRDseedV1 &ref)
116   :AliTRDtrackletBase((AliTRDtrackletBase&)ref)
117   ,fkReconstructor(NULL)
118   ,fClusterIter(NULL)
119   ,fExB(0.)
120   ,fVD(0.)
121   ,fT0(0.)
122   ,fS2PRF(0.)
123   ,fDiffL(0.)
124   ,fDiffT(0.)
125   ,fClusterIdx(0)
126   ,fErrorMsg(0)
127   ,fN(0)
128   ,fDet(-1)
129   ,fPt(0.)
130   ,fdX(0.)
131   ,fX0(0.)
132   ,fX(0.)
133   ,fY(0.)
134   ,fZ(0.)
135   ,fS2Y(0.)
136   ,fS2Z(0.)
137   ,fChi2(0.)
138 {
139   //
140   // Copy Constructor performing a deep copy
141   //
142   if(this != &ref){
143     ref.Copy(*this);
144   }
145   SetBit(kOwner, kFALSE);
146   SetStandAlone(ref.IsStandAlone());
147 }
148
149
150 //____________________________________________________________________
151 AliTRDseedV1& AliTRDseedV1::operator=(const AliTRDseedV1 &ref)
152 {
153   //
154   // Assignment Operator using the copy function
155   //
156
157   if(this != &ref){
158     ref.Copy(*this);
159   }
160   SetBit(kOwner, kFALSE);
161
162   return *this;
163 }
164
165 //____________________________________________________________________
166 AliTRDseedV1::~AliTRDseedV1()
167 {
168   //
169   // Destructor. The RecoParam object belongs to the underlying tracker.
170   //
171
172   //printf("I-AliTRDseedV1::~AliTRDseedV1() : Owner[%s]\n", IsOwner()?"YES":"NO");
173
174   if(IsOwner()) {
175     for(int itb=0; itb<kNclusters; itb++){
176       if(!fClusters[itb]) continue; 
177       //AliInfo(Form("deleting c %p @ %d", fClusters[itb], itb));
178       delete fClusters[itb];
179       fClusters[itb] = NULL;
180     }
181   }
182 }
183
184 //____________________________________________________________________
185 void AliTRDseedV1::Copy(TObject &ref) const
186 {
187   //
188   // Copy function
189   //
190
191   //AliInfo("");
192   AliTRDseedV1 &target = (AliTRDseedV1 &)ref; 
193
194   target.fkReconstructor = fkReconstructor;
195   target.fClusterIter   = NULL;
196   target.fExB           = fExB;
197   target.fVD            = fVD;
198   target.fT0            = fT0;
199   target.fS2PRF         = fS2PRF;
200   target.fDiffL         = fDiffL;
201   target.fDiffT         = fDiffT;
202   target.fClusterIdx    = 0;
203   target.fErrorMsg      = fErrorMsg;
204   target.fN             = fN;
205   target.fDet           = fDet;
206   target.fPt            = fPt;
207   target.fdX            = fdX;
208   target.fX0            = fX0;
209   target.fX             = fX;
210   target.fY             = fY;
211   target.fZ             = fZ;
212   target.fS2Y           = fS2Y;
213   target.fS2Z           = fS2Z;
214   target.fChi2          = fChi2;
215   
216   memcpy(target.fIndexes, fIndexes, kNclusters*sizeof(Int_t));
217   memcpy(target.fClusters, fClusters, kNclusters*sizeof(AliTRDcluster*));
218   memcpy(target.fPad, fPad, 4*sizeof(Float_t));
219   target.fYref[0] = fYref[0]; target.fYref[1] = fYref[1]; 
220   target.fZref[0] = fZref[0]; target.fZref[1] = fZref[1]; 
221   target.fYfit[0] = fYfit[0]; target.fYfit[1] = fYfit[1]; 
222   target.fZfit[0] = fZfit[0]; target.fZfit[1] = fZfit[1]; 
223   memcpy(target.fdEdx, fdEdx, kNslices*sizeof(Float_t)); 
224   memcpy(target.fProb, fProb, AliPID::kSPECIES*sizeof(Float_t)); 
225   memcpy(target.fLabels, fLabels, 3*sizeof(Int_t)); 
226   memcpy(target.fRefCov, fRefCov, 7*sizeof(Double_t)); 
227   target.fC[0] = fC[0]; target.fC[1] = fC[1];
228   memcpy(target.fCov, fCov, 3*sizeof(Double_t)); 
229   
230   TObject::Copy(ref);
231 }
232
233
234 //____________________________________________________________
235 void AliTRDseedV1::Init(const AliRieman *rieman)
236 {
237 // Initialize this tracklet using the riemann fit information
238
239
240   fZref[0] = rieman->GetZat(fX0);
241   fZref[1] = rieman->GetDZat(fX0);
242   fYref[0] = rieman->GetYat(fX0);
243   fYref[1] = rieman->GetDYat(fX0);
244   if(fkReconstructor && fkReconstructor->IsHLT()){
245     fRefCov[0] = 1;
246     fRefCov[2] = 10;
247   }else{
248     fRefCov[0] = rieman->GetErrY(fX0);
249     fRefCov[2] = rieman->GetErrZ(fX0);
250   }
251   fC[0]    = rieman->GetC(); 
252   fChi2    = rieman->GetChi2();
253 }
254
255
256 //____________________________________________________________
257 Bool_t AliTRDseedV1::Init(AliTRDtrackV1 *track)
258 {
259 // Initialize this tracklet using the track information
260 //
261 // Parameters:
262 //   track - the TRD track used to initialize the tracklet
263 // 
264 // Detailed description
265 // The function sets the starting point and direction of the
266 // tracklet according to the information from the TRD track.
267 // 
268 // Caution
269 // The TRD track has to be propagated to the beginning of the
270 // chamber where the tracklet will be constructed
271 //
272
273   Double_t y, z; 
274   if(!track->GetProlongation(fX0, y, z)) return kFALSE;
275   Update(track);
276   return kTRUE;
277 }
278
279
280 //_____________________________________________________________________________
281 void AliTRDseedV1::Reset(Option_t *opt)
282 {
283 //
284 // Reset seed. If option opt="c" is given only cluster arrays are cleared.
285 //
286   for(Int_t ic=kNclusters; ic--;) fIndexes[ic] = -1;
287   memset(fClusters, 0, kNclusters*sizeof(AliTRDcluster*));
288   fN=0; SetBit(kRowCross, kFALSE);
289   if(strcmp(opt, "c")==0) return;
290
291   fExB=0.;fVD=0.;fT0=0.;fS2PRF=0.;
292   fDiffL=0.;fDiffT=0.;
293   fClusterIdx=0;
294   fErrorMsg = 0;
295   fDet=-1;
296   fPt=0.;
297   fdX=0.;fX0=0.; fX=0.; fY=0.; fZ=0.;
298   fS2Y=0.; fS2Z=0.;
299   fC[0]=0.; fC[1]=0.; 
300   fChi2 = 0.;
301
302   memset(fPad, 0, 4*sizeof(Float_t));
303   fYref[0] = 0.; fYref[1] = 0.; 
304   fZref[0] = 0.; fZref[1] = 0.; 
305   fYfit[0] = 0.; fYfit[1] = 0.; 
306   fZfit[0] = 0.; fZfit[1] = 0.; 
307   memset(fdEdx, 0, kNslices*sizeof(Float_t)); 
308   for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec]  = -1.;
309   fLabels[0]=-1; fLabels[1]=-1; // most freq MC labels
310   fLabels[2]=0;  // number of different labels for tracklet
311   memset(fRefCov, 0, 7*sizeof(Double_t));
312   // covariance matrix [diagonal]
313   // default sy = 200um and sz = 2.3 cm 
314   fCov[0] = 4.e-4; fCov[1] = 0.; fCov[2] = 5.3; 
315 }
316
317 //____________________________________________________________________
318 void AliTRDseedV1::Update(const AliTRDtrackV1 *trk)
319
320   // update tracklet reference position from the TRD track
321
322   Double_t fSnp = trk->GetSnp();
323   Double_t fTgl = trk->GetTgl();
324   fPt = trk->Pt();
325   Double_t norm =1./TMath::Sqrt((1.-fSnp)*(1.+fSnp)); 
326   fYref[1] = fSnp*norm;
327   fZref[1] = fTgl*norm;
328   SetCovRef(trk->GetCovariance());
329
330   Double_t dx = trk->GetX() - fX0;
331   fYref[0] = trk->GetY() - dx*fYref[1];
332   fZref[0] = trk->GetZ() - dx*fZref[1];
333 }
334
335 //_____________________________________________________________________________
336 void AliTRDseedV1::UpdateUsed()
337 {
338   //
339   // Calculate number of used clusers in the tracklet
340   //
341
342   Int_t nused = 0, nshared = 0;
343   for (Int_t i = kNclusters; i--; ) {
344     if (!fClusters[i]) continue;
345     if(fClusters[i]->IsUsed()){ 
346       nused++;
347     } else if(fClusters[i]->IsShared()){
348       if(IsStandAlone()) nused++;
349       else nshared++;
350     }
351   }
352   SetNUsed(nused);
353   SetNShared(nshared);
354 }
355
356 //_____________________________________________________________________________
357 void AliTRDseedV1::UseClusters()
358 {
359   //
360   // Use clusters
361   //
362   // In stand alone mode:
363   // Clusters which are marked as used or shared from another track are
364   // removed from the tracklet
365   //
366   // In barrel mode:
367   // - Clusters which are used by another track become shared
368   // - Clusters which are attached to a kink track become shared
369   //
370   AliTRDcluster **c = &fClusters[0];
371   for (Int_t ic=kNclusters; ic--; c++) {
372     if(!(*c)) continue;
373     if(IsStandAlone()){
374       if((*c)->IsShared() || (*c)->IsUsed()){ 
375         if((*c)->IsShared()) SetNShared(GetNShared()-1);
376         else SetNUsed(GetNUsed()-1);
377         (*c) = NULL;
378         fIndexes[ic] = -1;
379         SetN(GetN()-1);
380         continue;
381       }
382     } else {
383       if((*c)->IsUsed() || IsKink()){
384         (*c)->SetShared();
385         continue;
386       }
387     }
388     (*c)->Use();
389   }
390 }
391
392
393
394 //____________________________________________________________________
395 void AliTRDseedV1::CookdEdx(Int_t nslices)
396 {
397 // Calculates average dE/dx for all slices and store them in the internal array fdEdx. 
398 //
399 // Parameters:
400 //  nslices : number of slices for which dE/dx should be calculated
401 // Output:
402 //  store results in the internal array fdEdx. This can be accessed with the method
403 //  AliTRDseedV1::GetdEdx()
404 //
405 // Detailed description
406 // Calculates average dE/dx for all slices. Depending on the PID methode 
407 // the number of slices can be 3 (LQ) or 8(NN). 
408 // The calculation of dQ/dl are done using the tracklet fit results (see AliTRDseedV1::GetdQdl(Int_t))
409 //
410 // The following effects are included in the calculation:
411 // 1. calibration values for t0 and vdrift (using x coordinate to calculate slice)
412 // 2. cluster sharing (optional see AliTRDrecoParam::SetClusterSharing())
413 // 3. cluster size
414 //
415
416   memset(fdEdx, 0, kNslices*sizeof(Float_t));
417   const Double_t kDriftLength = (.5 * AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
418
419   AliTRDcluster *c(NULL);
420   for(int ic=0; ic<AliTRDtrackerV1::GetNTimeBins(); ic++){
421     if(!(c = fClusters[ic]) && !(c = fClusters[ic+kNtb])) continue;
422     Float_t dx = TMath::Abs(fX0 - c->GetX());
423
424     // Filter clusters for dE/dx calculation
425
426     // 1.consider calibration effects for slice determination
427     Int_t slice;
428     if(dx<kDriftLength){ // TODO should be replaced by c->IsInChamber()
429       slice = Int_t(dx * nslices / kDriftLength);
430     } else slice = c->GetX() < fX0 ? nslices-1 : 0;
431
432
433     // 2. take sharing into account
434     Float_t w = /*c->IsShared() ? .5 :*/ 1.;
435
436     // 3. take into account large clusters TODO
437     //w *= c->GetNPads() > 3 ? .8 : 1.;
438
439     //CHECK !!!
440     fdEdx[slice]   += w * GetdQdl(ic); //fdQdl[ic];
441   } // End of loop over clusters
442 }
443
444 //_____________________________________________________________________________
445 void AliTRDseedV1::CookLabels()
446 {
447   //
448   // Cook 2 labels for seed
449   //
450
451   Int_t labels[200];
452   Int_t out[200];
453   Int_t nlab = 0;
454   for (Int_t i = 0; i < kNclusters; i++) {
455     if (!fClusters[i]) continue;
456     for (Int_t ilab = 0; ilab < 3; ilab++) {
457       if (fClusters[i]->GetLabel(ilab) >= 0) {
458         labels[nlab] = fClusters[i]->GetLabel(ilab);
459         nlab++;
460       }
461     }
462   }
463
464   fLabels[2] = AliMathBase::Freq(nlab,labels,out,kTRUE);
465   fLabels[0] = out[0];
466   if ((fLabels[2]  > 1) && (out[3] > 1)) fLabels[1] = out[2];
467 }
468
469 //____________________________________________________________
470 Float_t AliTRDseedV1::GetAnodeWireOffset(Float_t zt)
471 {
472 // Find position inside the amplification cell for reading drift velocity map
473
474   Float_t d = fPad[3] - zt;
475   if(d<0.){
476     AliError(Form("Fail AnodeWireOffset calculation z0[%+7.2f] zt[%+7.2f] d[%+7.2f].", fPad[3], zt, d));
477     return 0.125;
478   } 
479   d -= ((Int_t)(2 * d)) / 2.0;
480   if(d > 0.25) d = 0.5 - d;
481   return d;
482 }
483
484
485 //____________________________________________________________________
486 Float_t AliTRDseedV1::GetCharge(Bool_t useOutliers)
487 {
488 // Computes total charge attached to tracklet. If "useOutliers" is set clusters 
489 // which are not in chamber are also used (default false)
490
491   AliTRDcluster *c(NULL); Float_t qt(0.);
492   for(int ic=0; ic<kNclusters; ic++){
493     if(!(c=fClusters[ic])) continue;
494     if(c->IsInChamber() && !useOutliers) continue;
495     qt += TMath::Abs(c->GetQ());
496   }
497   return qt;
498 }
499
500 //____________________________________________________________________
501 Float_t AliTRDseedV1::GetdQdl(Int_t ic, Float_t *dl) const
502 {
503 // Using the linear approximation of the track inside one TRD chamber (TRD tracklet) 
504 // the charge per unit length can be written as:
505 // BEGIN_LATEX
506 // #frac{dq}{dl} = #frac{q_{c}}{dx * #sqrt{1 + #(){#frac{dy}{dx}}^{2}_{fit} + #(){#frac{dz}{dx}}^{2}_{ref}}}
507 // END_LATEX
508 // where qc is the total charge collected in the current time bin and dx is the length 
509 // of the time bin. 
510 // The following correction are applied :
511 //   - charge : pad row cross corrections
512 //              [diffusion and TRF assymetry] TODO
513 //   - dx     : anisochronity, track inclination - see Fit and AliTRDcluster::GetXloc() 
514 //              and AliTRDcluster::GetYloc() for the effects taken into account
515 // 
516 //Begin_Html
517 //<img src="TRD/trackletDQDT.gif">
518 //End_Html
519 // In the picture the energy loss measured on the tracklet as a function of drift time [left] and respectively 
520 // drift length [right] for different particle species is displayed.
521 // Author : Alex Bercuci <A.Bercuci@gsi.de>
522 //
523   Float_t dq = 0.;
524   // check whether both clusters are inside the chamber
525   Bool_t hasClusterInChamber = kFALSE;
526   if(fClusters[ic] && fClusters[ic]->IsInChamber()){
527     hasClusterInChamber = kTRUE;
528     dq += TMath::Abs(fClusters[ic]->GetQ());
529   }
530   if(fClusters[ic+kNtb] && fClusters[ic+kNtb]->IsInChamber()){
531     hasClusterInChamber = kTRUE;
532     dq += TMath::Abs(fClusters[ic+kNtb]->GetQ());
533   }
534   if(!hasClusterInChamber) return 0.;
535   if(dq<1.e-3) return 0.;
536
537   Double_t dx = fdX;
538   if(ic-1>=0 && ic+1<kNtb){
539     Float_t x2(0.), x1(0.);
540     // try to estimate upper radial position (find the cluster which is inside the chamber)
541     if(fClusters[ic-1] && fClusters[ic-1]->IsInChamber()) x2 = fClusters[ic-1]->GetX(); 
542     else if(fClusters[ic-1+kNtb] && fClusters[ic-1+kNtb]->IsInChamber()) x2 = fClusters[ic-1+kNtb]->GetX(); 
543     else if(fClusters[ic] && fClusters[ic]->IsInChamber()) x2 = fClusters[ic]->GetX()+fdX;
544     else x2 = fClusters[ic+kNtb]->GetX()+fdX;
545     // try to estimate lower radial position (find the cluster which is inside the chamber)
546     if(fClusters[ic+1] && fClusters[ic+1]->IsInChamber()) x1 = fClusters[ic+1]->GetX();
547     else if(fClusters[ic+1+kNtb] && fClusters[ic+1+kNtb]->IsInChamber()) x1 = fClusters[ic+1+kNtb]->GetX();
548     else if(fClusters[ic] && fClusters[ic]->IsInChamber()) x1 = fClusters[ic]->GetX()-fdX;
549     else x1 = fClusters[ic+kNtb]->GetX()-fdX;
550
551     dx = .5*(x2 - x1);
552   }
553   dx *= TMath::Sqrt(1. + fYfit[1]*fYfit[1] + fZref[1]*fZref[1]);
554   if(dl) (*dl) = dx;
555   if(dx>1.e-9) return dq/dx;
556   else return 0.;
557 }
558
559 //____________________________________________________________
560 Float_t AliTRDseedV1::GetMomentum(Float_t *err) const
561
562 // Returns momentum of the track after update with the current tracklet as:
563 // BEGIN_LATEX
564 // p=#frac{1}{1/p_{t}} #sqrt{1+tgl^{2}}
565 // END_LATEX
566 // and optionally the momentum error (if err is not null). 
567 // The estimated variance of the momentum is given by:
568 // BEGIN_LATEX
569 // #sigma_{p}^{2} = (#frac{dp}{dp_{t}})^{2} #sigma_{p_{t}}^{2}+(#frac{dp}{dtgl})^{2} #sigma_{tgl}^{2}+2#frac{dp}{dp_{t}}#frac{dp}{dtgl} cov(tgl,1/p_{t})
570 // END_LATEX
571 // which can be simplified to
572 // BEGIN_LATEX
573 // #sigma_{p}^{2} = p^{2}p_{t}^{4}tgl^{2}#sigma_{tgl}^{2}-2p^{2}p_{t}^{3}tgl cov(tgl,1/p_{t})+p^{2}p_{t}^{2}#sigma_{1/p_{t}}^{2}
574 // END_LATEX
575 //
576
577   Double_t p = fPt*TMath::Sqrt(1.+fZref[1]*fZref[1]);
578   Double_t p2 = p*p;
579   Double_t tgl2 = fZref[1]*fZref[1];
580   Double_t pt2 = fPt*fPt;
581   if(err){
582     Double_t s2 = 
583       p2*tgl2*pt2*pt2*fRefCov[4]
584      -2.*p2*fZref[1]*fPt*pt2*fRefCov[5]
585      +p2*pt2*fRefCov[6];
586     (*err) = TMath::Sqrt(s2);
587   }
588   return p;
589 }
590
591 //____________________________________________________________________
592 Float_t AliTRDseedV1::GetOccupancyTB() const
593 {
594 // Returns procentage of TB occupied by clusters
595
596   Int_t n(0);
597   AliTRDcluster *c(NULL);
598   for(int ic=0; ic<AliTRDtrackerV1::GetNTimeBins(); ic++){
599     if(!(c = fClusters[ic]) && !(c = fClusters[ic+kNtb])) continue;
600     n++;
601   }
602
603   return Float_t(n)/AliTRDtrackerV1::GetNTimeBins();
604 }
605
606 //____________________________________________________________________
607 Float_t* AliTRDseedV1::GetProbability(Bool_t force)
608 {       
609   if(!force) return &fProb[0];
610   if(!CookPID()) return NULL;
611   return &fProb[0];
612 }
613
614 //____________________________________________________________
615 Bool_t AliTRDseedV1::CookPID()
616 {
617 // Fill probability array for tracklet from the DB.
618 //
619 // Parameters
620 //
621 // Output
622 //   returns pointer to the probability array and NULL if missing DB access 
623 //
624 // Retrieve PID probabilities for e+-, mu+-, K+-, pi+- and p+- from the DB according to tracklet information:
625 // - estimated momentum at tracklet reference point 
626 // - dE/dx measurements
627 // - tracklet length
628 // - TRD layer
629 // According to the steering settings specified in the reconstruction one of the following methods are used
630 // - Neural Network [default] - option "nn"  
631 // - 2D Likelihood - option "!nn"  
632
633   AliTRDcalibDB *calibration = AliTRDcalibDB::Instance();
634   if (!calibration) {
635     AliError("No access to calibration data");
636     return kFALSE;
637   }
638
639   if (!fkReconstructor) {
640     AliError("Reconstructor not set.");
641     return kFALSE;
642   }
643
644   // Retrieve the CDB container class with the parametric detector response
645   const AliTRDCalPID *pd = calibration->GetPIDObject(fkReconstructor->GetPIDMethod());
646   if (!pd) {
647     AliError("No access to AliTRDCalPID object");
648     return kFALSE;
649   }
650
651   // calculate tracklet length TO DO
652   Float_t length = (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick())/ TMath::Sqrt((1.0 - GetSnp()*GetSnp()) / (1.0 + GetTgl()*GetTgl()));
653   
654   //calculate dE/dx
655   CookdEdx(AliTRDCalPID::kNSlicesNN);
656   AliDebug(4, Form("p=%6.4f[GeV/c] dEdx{%7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f} l=%4.2f[cm]", GetMomentum(), fdEdx[0], fdEdx[1], fdEdx[2], fdEdx[3], fdEdx[4], fdEdx[5], fdEdx[6], fdEdx[7], length));
657
658   // Sets the a priori probabilities
659   Bool_t kPIDNN(fkReconstructor->GetPIDMethod()==AliTRDpidUtil::kNN);
660   for(int ispec=0; ispec<AliPID::kSPECIES; ispec++)
661     fProb[ispec] = pd->GetProbability(ispec, GetMomentum(), &fdEdx[0], length, kPIDNN?GetPlane():fkReconstructor->GetRecoParam()->GetPIDLQslices());
662   
663   return kTRUE;
664 }
665
666 //____________________________________________________________________
667 Float_t AliTRDseedV1::GetQuality(Bool_t kZcorr) const
668 {
669   //
670   // Returns a quality measurement of the current seed
671   //
672
673   Float_t zcorr = kZcorr ? GetTilt() * (fZfit[0] - fZref[0]) : 0.;
674   return 
675       .5 * TMath::Abs(18.0 - GetN())
676     + 10.* TMath::Abs(fYfit[1] - fYref[1])
677     + 5. * TMath::Abs(fYfit[0] - fYref[0] + zcorr)
678     + 2. * TMath::Abs(fZfit[0] - fZref[0]) / GetPadLength();
679 }
680
681 //____________________________________________________________________
682 void AliTRDseedV1::GetCovAt(Double_t x, Double_t *cov) const
683 {
684 // Computes covariance in the y-z plane at radial point x (in tracking coordinates) 
685 // and returns the results in the preallocated array cov[3] as :
686 //   cov[0] = Var(y)
687 //   cov[1] = Cov(yz)
688 //   cov[2] = Var(z)
689 //
690 // Details
691 //
692 // For the linear transformation
693 // BEGIN_LATEX
694 // Y = T_{x} X^{T}
695 // END_LATEX
696 //   The error propagation has the general form
697 // BEGIN_LATEX
698 // C_{Y} = T_{x} C_{X} T_{x}^{T} 
699 // END_LATEX
700 //  We apply this formula 2 times. First to calculate the covariance of the tracklet 
701 // at point x we consider: 
702 // BEGIN_LATEX
703 // T_{x} = (1 x); X=(y0 dy/dx); C_{X}=#(){#splitline{Var(y0) Cov(y0, dy/dx)}{Cov(y0, dy/dx) Var(dy/dx)}} 
704 // END_LATEX
705 // and secondly to take into account the tilt angle
706 // BEGIN_LATEX
707 // T_{#alpha} = #(){#splitline{cos(#alpha) __ sin(#alpha)}{-sin(#alpha) __ cos(#alpha)}}; X=(y z); C_{X}=#(){#splitline{Var(y)    0}{0   Var(z)}} 
708 // END_LATEX
709 //
710 // using simple trigonometrics one can write for this last case
711 // BEGIN_LATEX
712 // C_{Y}=#frac{1}{1+tg^{2}#alpha} #(){#splitline{(#sigma_{y}^{2}+tg^{2}#alpha#sigma_{z}^{2}) __ tg#alpha(#sigma_{z}^{2}-#sigma_{y}^{2})}{tg#alpha(#sigma_{z}^{2}-#sigma_{y}^{2}) __ (#sigma_{z}^{2}+tg^{2}#alpha#sigma_{y}^{2})}} 
713 // END_LATEX
714 // which can be aproximated for small alphas (2 deg) with
715 // BEGIN_LATEX
716 // C_{Y}=#(){#splitline{#sigma_{y}^{2} __ (#sigma_{z}^{2}-#sigma_{y}^{2})tg#alpha}{((#sigma_{z}^{2}-#sigma_{y}^{2})tg#alpha __ #sigma_{z}^{2}}} 
717 // END_LATEX
718 //
719 // before applying the tilt rotation we also apply systematic uncertainties to the tracklet 
720 // position which can be tunned from outside via the AliTRDrecoParam::SetSysCovMatrix(). They might 
721 // account for extra misalignment/miscalibration uncertainties. 
722 //
723 // Author :
724 // Alex Bercuci <A.Bercuci@gsi.de> 
725 // Date : Jan 8th 2009
726 //
727
728
729   Double_t xr     = fX0-x; 
730   Double_t sy2    = fCov[0] +2.*xr*fCov[1] + xr*xr*fCov[2];
731   Double_t sz2    = fS2Z;
732   //GetPadLength()*GetPadLength()/12.;
733
734   // insert systematic uncertainties
735   if(fkReconstructor){
736     Double_t sys[15]; memset(sys, 0, 15*sizeof(Double_t));
737     fkReconstructor->GetRecoParam()->GetSysCovMatrix(sys);
738     sy2 += sys[0];
739     sz2 += sys[1];
740   }
741
742   // rotate covariance matrix if no RC
743   if(!IsRowCross()){
744     Double_t t2 = GetTilt()*GetTilt();
745     Double_t correction = 1./(1. + t2);
746     cov[0] = (sy2+t2*sz2)*correction;
747     cov[1] = GetTilt()*(sz2 - sy2)*correction;
748     cov[2] = (t2*sy2+sz2)*correction;
749   } else {
750     cov[0] = sy2; cov[1] = 0.; cov[2] = sy2;
751   }
752
753   AliDebug(4, Form("C(%6.1f %+6.3f %6.1f)  RC[%c]", 1.e4*TMath::Sqrt(cov[0]), cov[1], 1.e4*TMath::Sqrt(cov[2]), IsRowCross()?'y':'n'));
754 }
755
756 //____________________________________________________________
757 Int_t AliTRDseedV1::GetCovSqrt(const Double_t * const c, Double_t *d)
758 {
759 // Helper function to calculate the square root of the covariance matrix. 
760 // The input matrix is stored in the vector c and the result in the vector d. 
761 // Both arrays have to be initialized by the user with at least 3 elements. Return negative in case of failure.
762 // 
763 // For calculating the square root of the symmetric matrix c
764 // the following relation is used:
765 // BEGIN_LATEX
766 // C^{1/2} = VD^{1/2}V^{-1}
767 // END_LATEX
768 // with V being the matrix with the n eigenvectors as columns. 
769 // In case C is symmetric the followings are true:
770 //   - matrix D is diagonal with the diagonal given by the eigenvalues of C
771 //   - V = V^{-1}
772 //
773 // Author A.Bercuci <A.Bercuci@gsi.de>
774 // Date   Mar 19 2009
775
776   const Double_t kZero(1.e-20);
777   Double_t l[2], // eigenvalues
778            v[3]; // eigenvectors
779   // the secular equation and its solution :
780   // (c[0]-L)(c[2]-L)-c[1]^2 = 0
781   // L^2 - L*Tr(c)+DET(c) = 0
782   // L12 = [Tr(c) +- sqrt(Tr(c)^2-4*DET(c))]/2
783   Double_t tr = c[0]+c[2],           // trace
784           det = c[0]*c[2]-c[1]*c[1]; // determinant
785   if(TMath::Abs(det)<kZero) return 1;
786   Double_t dd = TMath::Sqrt(tr*tr - 4*det);
787   l[0] = .5*(tr + dd*(c[0]>c[2]?-1.:1.));
788   l[1] = .5*(tr + dd*(c[0]>c[2]?1.:-1.));
789   if(l[0]<kZero || l[1]<kZero) return 2;
790   // the sym V matrix
791   // | v00   v10|
792   // | v10   v11|
793   Double_t den = (l[0]-c[0])*(l[0]-c[0])+c[1]*c[1];
794   if(den<kZero){ // almost diagonal
795     v[0] = TMath::Sign(0., c[1]);
796     v[1] = TMath::Sign(1., (l[0]-c[0]));
797     v[2] = TMath::Sign(0., c[1]*(l[0]-c[0])*(l[1]-c[2]));
798   } else {
799     Double_t tmp = 1./TMath::Sqrt(den);
800     v[0] = c[1]* tmp;
801     v[1] = (l[0]-c[0])*tmp;
802     if(TMath::Abs(l[1]-c[2])<kZero) v[2] = TMath::Sign(v[0]*(l[0]-c[0])/kZero, (l[1]-c[2]));
803     else v[2] = v[0]*(l[0]-c[0])/(l[1]-c[2]);
804   }
805   // the VD^{1/2}V is: 
806   l[0] = TMath::Sqrt(l[0]); l[1] = TMath::Sqrt(l[1]);
807   d[0] = v[0]*v[0]*l[0]+v[1]*v[1]*l[1];
808   d[1] = v[0]*v[1]*l[0]+v[1]*v[2]*l[1];
809   d[2] = v[1]*v[1]*l[0]+v[2]*v[2]*l[1];
810
811   return 0;
812 }
813
814 //____________________________________________________________
815 Double_t AliTRDseedV1::GetCovInv(const Double_t * const c, Double_t *d)
816 {
817 // Helper function to calculate the inverse of the covariance matrix.
818 // The input matrix is stored in the vector c and the result in the vector d. 
819 // Both arrays have to be initialized by the user with at least 3 elements
820 // The return value is the determinant or 0 in case of singularity.
821 //
822 // Author A.Bercuci <A.Bercuci@gsi.de>
823 // Date   Mar 19 2009
824
825   Double_t det = c[0]*c[2] - c[1]*c[1];
826   if(TMath::Abs(det)<1.e-20) return 0.;
827   Double_t invDet = 1./det;
828   d[0] = c[2]*invDet;
829   d[1] =-c[1]*invDet;
830   d[2] = c[0]*invDet;
831   return det;
832 }
833
834 //____________________________________________________________________
835 UShort_t AliTRDseedV1::GetVolumeId() const
836 {
837 // Returns geometry volume id by delegation 
838
839   for(Int_t ic(0);ic<kNclusters; ic++){
840     if(fClusters[ic]) return fClusters[ic]->GetVolumeId();
841   }
842   return 0;
843 }
844
845
846 //____________________________________________________________________
847 void AliTRDseedV1::Calibrate()
848 {
849 // Retrieve calibration and position parameters from OCDB. 
850 // The following information are used
851 //  - detector index
852 //  - column and row position of first attached cluster. If no clusters are attached 
853 // to the tracklet a random central chamber position (c=70, r=7) will be used.
854 //
855 // The following information is cached in the tracklet
856 //   t0 (trigger delay)
857 //   drift velocity
858 //   PRF width
859 //   omega*tau = tg(a_L)
860 //   diffusion coefficients (longitudinal and transversal)
861 //
862 // Author :
863 // Alex Bercuci <A.Bercuci@gsi.de> 
864 // Date : Jan 8th 2009
865 //
866
867   AliCDBManager *cdb = AliCDBManager::Instance();
868   if(cdb->GetRun() < 0){
869     AliError("OCDB manager not properly initialized");
870     return;
871   }
872
873   AliTRDcalibDB *calib = AliTRDcalibDB::Instance();
874   AliTRDCalROC  *vdROC = calib->GetVdriftROC(fDet),
875                 *t0ROC = calib->GetT0ROC(fDet);;
876   const AliTRDCalDet *vdDet = calib->GetVdriftDet();
877   const AliTRDCalDet *t0Det = calib->GetT0Det();
878
879   Int_t col = 70, row = 7;
880   AliTRDcluster **c = &fClusters[0];
881   if(GetN()){ 
882     Int_t ic = 0;
883     while (ic<kNclusters && !(*c)){ic++; c++;} 
884     if(*c){
885       col = (*c)->GetPadCol();
886       row = (*c)->GetPadRow();
887     }
888   }
889
890   fT0    = (t0Det->GetValue(fDet) + t0ROC->GetValue(col,row)) / AliTRDCommonParam::Instance()->GetSamplingFrequency();
891   fVD    = vdDet->GetValue(fDet) * vdROC->GetValue(col, row);
892   fS2PRF = calib->GetPRFWidth(fDet, col, row); fS2PRF *= fS2PRF;
893   fExB   = AliTRDCommonParam::Instance()->GetOmegaTau(fVD);
894   AliTRDCommonParam::Instance()->GetDiffCoeff(fDiffL,
895   fDiffT, fVD);
896   AliDebug(4, Form("Calibration params for Det[%3d] Col[%3d] Row[%2d]\n  t0[%f]  vd[%f]  s2PRF[%f]  ExB[%f]  Dl[%f]  Dt[%f]", fDet, col, row, fT0, fVD, fS2PRF, fExB, fDiffL, fDiffT));
897
898
899   SetBit(kCalib, kTRUE);
900 }
901
902 //____________________________________________________________________
903 void AliTRDseedV1::SetOwner()
904 {
905   //AliInfo(Form("own [%s] fOwner[%s]", own?"YES":"NO", fOwner?"YES":"NO"));
906   
907   if(TestBit(kOwner)) return;
908   for(int ic=0; ic<kNclusters; ic++){
909     if(!fClusters[ic]) continue;
910     fClusters[ic] = new AliTRDcluster(*fClusters[ic]);
911   }
912   SetBit(kOwner);
913 }
914
915 //____________________________________________________________
916 void AliTRDseedV1::SetPadPlane(AliTRDpadPlane * const p)
917 {
918 // Shortcut method to initialize pad geometry.
919   fPad[0] = p->GetLengthIPad();
920   fPad[1] = p->GetWidthIPad();
921   fPad[2] = TMath::Tan(TMath::DegToRad()*p->GetTiltingAngle());
922   fPad[3] = p->GetRow0() + p->GetAnodeWireOffset();
923 }
924
925
926 //____________________________________________________________________
927 Bool_t  AliTRDseedV1::AttachClusters(AliTRDtrackingChamber *const chamber, Bool_t tilt)
928 {
929 //
930 // Projective algorithm to attach clusters to seeding tracklets. The following steps are performed :
931 // 1. Collapse x coordinate for the full detector plane
932 // 2. truncated mean on y (r-phi) direction
933 // 3. purge clusters
934 // 4. truncated mean on z direction
935 // 5. purge clusters
936 //
937 // Parameters
938 //  - chamber : pointer to tracking chamber container used to search the tracklet
939 //  - tilt    : switch for tilt correction during road building [default true]
940 // Output
941 //  - true    : if tracklet found successfully. Failure can happend because of the following:
942 //      -
943 // Detailed description
944 //      
945 // We start up by defining the track direction in the xy plane and roads. The roads are calculated based
946 // on tracking information (variance in the r-phi direction) and estimated variance of the standard 
947 // clusters (see AliTRDcluster::SetSigmaY2()) corrected for tilt (see GetCovAt()). From this the road is
948 // BEGIN_LATEX
949 // r_{y} = 3*#sqrt{12*(#sigma^{2}_{Trk}(y) + #frac{#sigma^{2}_{cl}(y) + tg^{2}(#alpha_{L})#sigma^{2}_{cl}(z)}{1+tg^{2}(#alpha_{L})})}
950 // r_{z} = 1.5*L_{pad}
951 // END_LATEX
952 // 
953 // Author : Alexandru Bercuci <A.Bercuci@gsi.de>
954 // Debug  : level >3
955
956   const AliTRDrecoParam* const recoParam = fkReconstructor->GetRecoParam(); //the dynamic cast in GetRecoParam is slow, so caching the pointer to it
957
958   if(!recoParam){
959     AliError("Tracklets can not be used without a valid RecoParam.");
960     return kFALSE;
961   }
962   // Initialize reco params for this tracklet
963   // 1. first time bin in the drift region
964   Int_t t0 = 14;
965   Int_t kClmin = Int_t(recoParam->GetFindableClusters()*AliTRDtrackerV1::GetNTimeBins());
966
967   Double_t sysCov[5]; recoParam->GetSysCovMatrix(sysCov);       
968   Double_t s2yTrk= fRefCov[0], 
969            s2yCl = 0., 
970            s2zCl = GetPadLength()*GetPadLength()/12., 
971            syRef = TMath::Sqrt(s2yTrk),
972            t2    = GetTilt()*GetTilt();
973   //define roads
974   Double_t kroady = 1., //recoParam->GetRoad1y();
975            kroadz = GetPadLength() * recoParam->GetRoadzMultiplicator() + 1.;
976   // define probing cluster (the perfect cluster) and default calibration
977   Short_t sig[] = {0, 0, 10, 30, 10, 0,0};
978   AliTRDcluster cp(fDet, 6, 75, 0, sig, 0);
979   if(fkReconstructor->IsHLT()) cp.SetRPhiMethod(AliTRDcluster::kCOG);
980   if(!IsCalibrated()) Calibrate();
981
982   AliDebug(4, "");
983   AliDebug(4, Form("syKalman[%f] rY[%f] rZ[%f]", syRef, kroady, kroadz));
984
985   // working variables
986   const Int_t kNrows = 16;
987   const Int_t kNcls  = 3*kNclusters; // buffer size
988   AliTRDcluster *clst[kNrows][kNcls];
989   Bool_t blst[kNrows][kNcls];
990   Double_t cond[4], dx, dy, yt, zt, yres[kNrows][kNcls];
991   Int_t idxs[kNrows][kNcls], ncl[kNrows], ncls = 0;
992   memset(ncl, 0, kNrows*sizeof(Int_t));
993   memset(yres, 0, kNrows*kNcls*sizeof(Double_t));
994   memset(blst, 0, kNrows*kNcls*sizeof(Bool_t));   //this is 8 times faster to memset than "memset(clst, 0, kNrows*kNcls*sizeof(AliTRDcluster*))"
995
996   // Do cluster projection
997   AliTRDcluster *c = NULL;
998   AliTRDchamberTimeBin *layer = NULL;
999   Bool_t kBUFFER = kFALSE;
1000   for (Int_t it = 0; it < kNtb; it++) {
1001     if(!(layer = chamber->GetTB(it))) continue;
1002     if(!Int_t(*layer)) continue;
1003     // get track projection at layers position
1004     dx   = fX0 - layer->GetX();
1005     yt = fYref[0] - fYref[1] * dx;
1006     zt = fZref[0] - fZref[1] * dx;
1007     // get standard cluster error corrected for tilt
1008     cp.SetLocalTimeBin(it);
1009     cp.SetSigmaY2(0.02, fDiffT, fExB, dx, -1./*zt*/, fYref[1]);
1010     s2yCl = (cp.GetSigmaY2() + sysCov[0] + t2*s2zCl)/(1.+t2);
1011     // get estimated road
1012     kroady = 3.*TMath::Sqrt(12.*(s2yTrk + s2yCl));
1013
1014     AliDebug(5, Form("  %2d x[%f] yt[%f] zt[%f]", it, dx, yt, zt));
1015
1016     AliDebug(5, Form("  syTrk[um]=%6.2f syCl[um]=%6.2f syClTlt[um]=%6.2f Ry[mm]=%f", 1.e4*TMath::Sqrt(s2yTrk), 1.e4*TMath::Sqrt(cp.GetSigmaY2()), 1.e4*TMath::Sqrt(s2yCl), 1.e1*kroady));
1017
1018     // select clusters
1019     cond[0] = yt; cond[2] = kroady;
1020     cond[1] = zt; cond[3] = kroadz;
1021     Int_t n=0, idx[6];
1022     layer->GetClusters(cond, idx, n, 6);
1023     for(Int_t ic = n; ic--;){
1024       c  = (*layer)[idx[ic]];
1025       dy = yt - c->GetY();
1026       dy += tilt ? GetTilt() * (c->GetZ() - zt) : 0.;
1027       // select clusters on a 3 sigmaKalman level
1028 /*      if(tilt && TMath::Abs(dy) > 3.*syRef){ 
1029         printf("too large !!!\n");
1030         continue;
1031       }*/
1032       Int_t r = c->GetPadRow();
1033       AliDebug(5, Form("   -> dy[%f] yc[%f] r[%d]", TMath::Abs(dy), c->GetY(), r));
1034       clst[r][ncl[r]] = c;
1035       blst[r][ncl[r]] = kTRUE;
1036       idxs[r][ncl[r]] = idx[ic];
1037       yres[r][ncl[r]] = dy;
1038       ncl[r]++; ncls++;
1039
1040       if(ncl[r] >= kNcls) {
1041         AliWarning(Form("Cluster candidates row[%d] reached buffer limit[%d]. Some may be lost.", r, kNcls));
1042         kBUFFER = kTRUE;
1043         break;
1044       }
1045     }
1046     if(kBUFFER) break;
1047   }
1048   AliDebug(4, Form("Found %d clusters. Processing ...", ncls));
1049   if(ncls<kClmin){ 
1050     AliDebug(1, Form("CLUSTERS FOUND %d LESS THAN THRESHOLD %d.", ncls, kClmin));
1051     SetErrorMsg(kAttachClFound);
1052     return kFALSE;
1053   }
1054
1055   // analyze each row individualy
1056   Bool_t kRowSelection(kFALSE);
1057   Double_t mean[]={1.e3, 1.e3, 1.3}, syDis[]={1.e3, 1.e3, 1.3};
1058   Int_t nrow[] = {0, 0, 0}, rowId[] = {-1, -1, -1}, nr = 0, lr=-1;
1059   TVectorD vdy[3];
1060   for(Int_t ir=0; ir<kNrows; ir++){
1061     if(!(ncl[ir])) continue;
1062     if(lr>0 && ir-lr != 1){ 
1063       AliDebug(2, "Rows attached not continuous. Turn on selection."); 
1064       kRowSelection=kTRUE;
1065     }
1066
1067     AliDebug(5, Form("  r[%d] n[%d]", ir, ncl[ir]));
1068     // Evaluate truncated mean on the y direction
1069     if(ncl[ir] < 4) continue;
1070     AliMathBase::EvaluateUni(ncl[ir], yres[ir], mean[nr], syDis[nr], Int_t(ncl[ir]*.8));
1071
1072     // TODO check mean and sigma agains cluster resolution !!
1073     AliDebug(4, Form("  m_%d[%+5.3f (%5.3fs)] s[%f]", nr, mean[nr], TMath::Abs(mean[nr]/syDis[nr]), syDis[nr]));
1074     // remove outliers based on a 3 sigmaDistr level
1075     Bool_t kFOUND = kFALSE;
1076     for(Int_t ic = ncl[ir]; ic--;){
1077       if(yres[ir][ic] - mean[nr] > 3. * syDis[nr]){ 
1078         blst[ir][ic] = kFALSE; continue;
1079       }
1080       nrow[nr]++; rowId[nr]=ir; kFOUND = kTRUE;
1081     }
1082     if(kFOUND){ 
1083       vdy[nr].Use(nrow[nr], yres[ir]);
1084       nr++; 
1085     }
1086     lr = ir; if(nr>=3) break;
1087   }
1088   if(recoParam->GetStreamLevel(AliTRDrecoParam::kTracker) > 3 && fkReconstructor->IsDebugStreaming()){
1089     TTreeSRedirector &cstreamer = *fkReconstructor->GetDebugStream(AliTRDrecoParam::kTracker);
1090     UChar_t stat(0);
1091     if(IsKink()) SETBIT(stat, 1);
1092     if(IsStandAlone()) SETBIT(stat, 2);
1093     cstreamer << "AttachClusters"
1094         << "stat="   << stat
1095         << "det="    << fDet
1096         << "pt="     << fPt
1097         << "s2y="    << s2yTrk
1098         << "r0="     << rowId[0]
1099         << "dy0="    << &vdy[0]
1100         << "m0="     << mean[0]
1101         << "s0="     << syDis[0]
1102         << "r1="     << rowId[1]
1103         << "dy1="    << &vdy[1]
1104         << "m1="     << mean[1]
1105         << "s1="     << syDis[1]
1106         << "r2="     << rowId[2]
1107         << "dy2="    << &vdy[2]
1108         << "m2="     << mean[2]
1109         << "s2="     << syDis[2]
1110         << "\n";
1111   }
1112
1113
1114   // analyze gap in rows attached 
1115   if(kRowSelection){
1116     SetErrorMsg(kAttachRowGap);
1117     Int_t rowRemove(-1); 
1118     if(nr==2){ // select based on minimum distance to track projection
1119       if(TMath::Abs(mean[0])<TMath::Abs(mean[1])){ 
1120         if(nrow[1]>nrow[0]) AliDebug(2, Form("Conflicting mean[%f < %f] but ncl[%d < %d].", TMath::Abs(mean[0]), TMath::Abs(mean[1]), nrow[0], nrow[1]));
1121       }else{
1122         if(nrow[1]<nrow[0]) AliDebug(2, Form("Conflicting mean[%f > %f] but ncl[%d > %d].", TMath::Abs(mean[0]), TMath::Abs(mean[1]), nrow[0], nrow[1]));
1123         Swap(nrow[0],nrow[1]); Swap(rowId[0],rowId[1]);
1124         Swap(mean[0],mean[1]); Swap(syDis[0],syDis[1]);
1125       }
1126       rowRemove=1; nr=1; 
1127     } else if(nr==3){ // select based on 2 consecutive rows
1128       if(rowId[1]==rowId[0]+1 && rowId[1]!=rowId[2]-1){ 
1129         nr=2;rowRemove=2;
1130       } else if(rowId[1]!=rowId[0]+1 && rowId[1]==rowId[2]-1){ 
1131         Swap(nrow[0],nrow[2]); Swap(rowId[0],rowId[2]);
1132         Swap(mean[0],mean[2]); Swap(syDis[0],syDis[2]);
1133         nr=2; rowRemove=2;
1134       }
1135     }
1136     if(rowRemove>0){nrow[rowRemove]=0; rowId[rowRemove]=-1;}
1137   }
1138   AliDebug(4, Form("  Ncl[%d[%d] + %d[%d] + %d[%d]]", nrow[0], rowId[0],  nrow[1], rowId[1], nrow[2], rowId[2]));
1139
1140   if(nr==3){
1141     SetBit(kRowCross, kTRUE); // mark pad row crossing
1142     SetErrorMsg(kAttachRow);
1143     const Float_t am[]={TMath::Abs(mean[0]), TMath::Abs(mean[1]), TMath::Abs(mean[2])};
1144     AliDebug(4, Form("complex row configuration\n"
1145       "  r[%d] n[%d] m[%6.3f] s[%6.3f]\n"
1146       "  r[%d] n[%d] m[%6.3f] s[%6.3f]\n"
1147       "  r[%d] n[%d] m[%6.3f] s[%6.3f]\n"
1148       , rowId[0], nrow[0], am[0], syDis[0]
1149       , rowId[1], nrow[1], am[1], syDis[1]
1150       , rowId[2], nrow[2], am[2], syDis[2]));
1151     Int_t id[]={0,1,2}; TMath::Sort(3, am, id, kFALSE);
1152     // backup
1153     Int_t rnn[3]; memcpy(rnn, nrow, 3*sizeof(Int_t));
1154     Int_t rid[3]; memcpy(rid, rowId, 3*sizeof(Int_t));
1155     Double_t rm[3]; memcpy(rm, mean, 3*sizeof(Double_t));
1156     Double_t rs[3]; memcpy(rs, syDis, 3*sizeof(Double_t));
1157     nrow[0]=rnn[id[0]]; rowId[0]=rid[id[0]]; mean[0]=rm[id[0]]; syDis[0]=rs[id[0]];
1158     nrow[1]=rnn[id[1]]; rowId[1]=rid[id[1]]; mean[1]=rm[id[1]]; syDis[1]=rs[id[1]];
1159     nrow[2]=0;          rowId[2]=-1; mean[2] = 1.e3; syDis[2] = 1.e3;
1160     AliDebug(4, Form("solved configuration\n"
1161       "  r[%d] n[%d] m[%+6.3f] s[%6.3f]\n"
1162       "  r[%d] n[%d] m[%+6.3f] s[%6.3f]\n"
1163       "  r[%d] n[%d] m[%+6.3f] s[%6.3f]\n"
1164       , rowId[0], nrow[0], mean[0], syDis[0]
1165       , rowId[1], nrow[1], mean[1], syDis[1]
1166       , rowId[2], nrow[2], mean[2], syDis[2]));
1167     nr=2;
1168   } else if(nr==2) {
1169     SetBit(kRowCross, kTRUE); // mark pad row crossing
1170     if(nrow[1] > nrow[0]){ // swap row order
1171       Swap(nrow[0],nrow[1]); Swap(rowId[0],rowId[1]);
1172       Swap(mean[0],mean[1]); Swap(syDis[0],syDis[1]);
1173     }
1174   }
1175
1176   // Select and store clusters 
1177   // We should consider here :
1178   //  1. How far is the chamber boundary
1179   //  2. How big is the mean
1180   Int_t n(0); Float_t dyc[kNclusters]; memset(dyc,0,kNclusters*sizeof(Float_t));
1181   for (Int_t ir = 0; ir < nr; ir++) {
1182     Int_t jr(rowId[ir]);
1183     AliDebug(4, Form("  Attaching Ncl[%d]=%d ...", jr, ncl[jr]));
1184     for (Int_t ic = 0; ic < ncl[jr]; ic++) {
1185       if(!blst[jr][ic])continue;
1186       c = clst[jr][ic];
1187       Int_t it(c->GetPadTime());
1188       Int_t idx(it+kNtb*ir);
1189       if(fClusters[idx]){
1190         AliDebug(4, Form("Many cluster candidates on row[%2d] tb[%2d].", jr, it));
1191         // TODO should save also the information on where the multiplicity happened and its size
1192         SetErrorMsg(kAttachMultipleCl);
1193         // TODO should also compare with mean and sigma for this row
1194         if(yres[jr][ic] > dyc[idx]) continue;
1195       }
1196
1197       // TODO proper indexing of clusters !!
1198       fIndexes[idx]  = chamber->GetTB(it)->GetGlobalIndex(idxs[jr][ic]);
1199       fClusters[idx] = c;
1200       dyc[idx]        = yres[jr][ic];
1201       n++;
1202     }
1203   }
1204   SetN(n);
1205
1206   // number of minimum numbers of clusters expected for the tracklet
1207   if (GetN() < kClmin){
1208     AliDebug(1, Form("NOT ENOUGH CLUSTERS %d ATTACHED TO THE TRACKLET [min %d] FROM FOUND %d.", GetN(), kClmin, n));
1209     SetErrorMsg(kAttachClAttach);
1210     return kFALSE;
1211   }
1212
1213   // Load calibration parameters for this tracklet  
1214   Calibrate();
1215
1216   // calculate dx for time bins in the drift region (calibration aware)
1217   Float_t x[2] = {0.,0.}; Int_t tb[2]={0,0};
1218   for (Int_t it = t0, irp=0; irp<2 && it < AliTRDtrackerV1::GetNTimeBins(); it++) {
1219     if(!fClusters[it]) continue;
1220     x[irp]  = fClusters[it]->GetX();
1221     tb[irp] = fClusters[it]->GetLocalTimeBin();
1222     irp++;
1223   }  
1224   Int_t dtb = tb[1] - tb[0];
1225   fdX = dtb ? (x[0] - x[1]) / dtb : 0.15;
1226   return kTRUE;
1227 }
1228
1229 //____________________________________________________________
1230 void AliTRDseedV1::Bootstrap(const AliTRDReconstructor *rec)
1231 {
1232 //   Fill in all derived information. It has to be called after recovery from file or HLT.
1233 //   The primitive data are
1234 //   - list of clusters
1235 //   - detector (as the detector will be removed from clusters)
1236 //   - position of anode wire (fX0) - temporary
1237 //   - track reference position and direction
1238 //   - momentum of the track
1239 //   - time bin length [cm]
1240 // 
1241 //   A.Bercuci <A.Bercuci@gsi.de> Oct 30th 2008
1242 //
1243   fkReconstructor = rec;
1244   AliTRDgeometry g;
1245   SetPadPlane(g.GetPadPlane(fDet));
1246
1247   //fSnp = fYref[1]/TMath::Sqrt(1+fYref[1]*fYref[1]);
1248   //fTgl = fZref[1];
1249   Int_t n = 0, nshare = 0, nused = 0;
1250   AliTRDcluster **cit = &fClusters[0];
1251   for(Int_t ic = kNclusters; ic--; cit++){
1252     if(!(*cit)) return;
1253     n++;
1254     if((*cit)->IsShared()) nshare++;
1255     if((*cit)->IsUsed()) nused++;
1256   }
1257   SetN(n); SetNUsed(nused); SetNShared(nshare);
1258   Fit();
1259   CookLabels();
1260   GetProbability();
1261 }
1262
1263
1264 //____________________________________________________________________
1265 Bool_t AliTRDseedV1::Fit(UChar_t opt)
1266 {
1267 //
1268 // Linear fit of the clusters attached to the tracklet
1269 //
1270 // Parameters :
1271 //   - opt : switch for tilt pad correction of cluster y position. Options are
1272 //           0 no correction [default]
1273 //           1 full tilt correction [dz/dx and z0]
1274 //           2 pseudo tilt correction [dz/dx from pad-chamber geometry]
1275 //
1276 // Output :
1277 //  True if successful
1278 //
1279 // Detailed description
1280 //
1281 //            Fit in the xy plane
1282 // 
1283 // The fit is performed to estimate the y position of the tracklet and the track 
1284 // angle in the bending plane. The clusters are represented in the chamber coordinate 
1285 // system (with respect to the anode wire - see AliTRDtrackerV1::FollowBackProlongation() 
1286 // on how this is set). The x and y position of the cluster and also their variances 
1287 // are known from clusterizer level (see AliTRDcluster::GetXloc(), AliTRDcluster::GetYloc(), 
1288 // AliTRDcluster::GetSX() and AliTRDcluster::GetSY()). 
1289 // If gaussian approximation is used to calculate y coordinate of the cluster the position 
1290 // is recalculated taking into account the track angle. The general formula to calculate the 
1291 // error of cluster position in the gaussian approximation taking into account diffusion and track
1292 // inclination is given for TRD by:
1293 // BEGIN_LATEX
1294 // #sigma^{2}_{y} = #sigma^{2}_{PRF} + #frac{x#delta_{t}^{2}}{(1+tg(#alpha_{L}))^{2}} + #frac{x^{2}tg^{2}(#phi-#alpha_{L})tg^{2}(#alpha_{L})}{12}
1295 // END_LATEX
1296 //
1297 // Since errors are calculated only in the y directions, radial errors (x direction) are mapped to y
1298 // by projection i.e.
1299 // BEGIN_LATEX
1300 // #sigma_{x|y} = tg(#phi) #sigma_{x}
1301 // END_LATEX
1302 // and also by the lorentz angle correction
1303 //
1304 //            Fit in the xz plane
1305 //
1306 // The "fit" is performed to estimate the radial position (x direction) where pad row cross happens. 
1307 // If no pad row crossing the z position is taken from geometry and radial position is taken from the xy 
1308 // fit (see below).
1309 // 
1310 // There are two methods to estimate the radial position of the pad row cross:
1311 //   1. leading cluster radial position : Here the lower part of the tracklet is considered and the last 
1312 // cluster registered (at radial x0) on this segment is chosen to mark the pad row crossing. The error 
1313 // of the z estimate is given by :
1314 // BEGIN_LATEX
1315 // #sigma_{z} = tg(#theta) #Delta x_{x_{0}}/12
1316 // END_LATEX
1317 // The systematic errors for this estimation are generated by the following sources:
1318 //   - no charge sharing between pad rows is considered (sharp cross)
1319 //   - missing cluster at row cross (noise peak-up, under-threshold signal etc.).
1320 // 
1321 //   2. charge fit over the crossing point : Here the full energy deposit along the tracklet is considered 
1322 // to estimate the position of the crossing by a fit in the qx plane. The errors in the q directions are 
1323 // parameterized as s_q = q^2. The systematic errors for this estimation are generated by the following sources:
1324 //   - no general model for the qx dependence
1325 //   - physical fluctuations of the charge deposit 
1326 //   - gain calibration dependence
1327 //
1328 //            Estimation of the radial position of the tracklet
1329 //
1330 // For pad row cross the radial position is taken from the xz fit (see above). Otherwise it is taken as the 
1331 // interpolation point of the tracklet i.e. the point where the error in y of the fit is minimum. The error
1332 // in the y direction of the tracklet is (see AliTRDseedV1::GetCovAt()):
1333 // BEGIN_LATEX
1334 // #sigma_{y} = #sigma^{2}_{y_{0}} + 2xcov(y_{0}, dy/dx) + #sigma^{2}_{dy/dx}
1335 // END_LATEX
1336 // and thus the radial position is:
1337 // BEGIN_LATEX
1338 // x = - cov(y_{0}, dy/dx)/#sigma^{2}_{dy/dx}
1339 // END_LATEX
1340 //
1341 //            Estimation of tracklet position error 
1342 //
1343 // The error in y direction is the error of the linear fit at the radial position of the tracklet while in the z 
1344 // direction is given by the cluster error or pad row cross error. In case of no pad row cross this is given by:
1345 // BEGIN_LATEX
1346 // #sigma_{y} = #sigma^{2}_{y_{0}} - 2cov^{2}(y_{0}, dy/dx)/#sigma^{2}_{dy/dx} + #sigma^{2}_{dy/dx}
1347 // #sigma_{z} = Pad_{length}/12
1348 // END_LATEX
1349 // For pad row cross the full error is calculated at the radial position of the crossing (see above) and the error 
1350 // in z by the width of the crossing region - being a matter of parameterization. 
1351 // BEGIN_LATEX
1352 // #sigma_{z} = tg(#theta) #Delta x_{x_{0}}/12
1353 // END_LATEX
1354 // In case of no tilt correction (default in the barrel tracking) the tilt is taken into account by the rotation of
1355 // the covariance matrix. See AliTRDseedV1::GetCovAt() for details.
1356 //
1357 // Author 
1358 // A.Bercuci <A.Bercuci@gsi.de>
1359
1360   if(!fkReconstructor){
1361     AliError("The tracklet needs the reconstruction setup. Please initialize by SetReconstructor().");
1362     return kFALSE;
1363   }
1364   if(!IsCalibrated()) Calibrate();
1365   if(opt>2){
1366     AliWarning(Form("Option [%d] outside range [0, 2]. Using default",opt));
1367     opt=0;
1368   }
1369
1370   const Int_t kClmin = 8;
1371   const Float_t kScalePulls = 10.; // factor to scale y pulls - NOT UNDERSTOOD
1372   // get track direction
1373   Double_t y0   = fYref[0];
1374   Double_t dydx = fYref[1]; 
1375   Double_t z0   = fZref[0];
1376   Double_t dzdx = fZref[1];
1377
1378   AliTRDtrackerV1::AliTRDLeastSquare fitterY;
1379   AliTRDtrackerV1::AliTRDLeastSquare fitterZ;
1380
1381   // book cluster information
1382   Double_t qc[kNclusters], xc[kNclusters], yc[kNclusters], zc[kNclusters], sy[kNclusters];
1383
1384   Bool_t tilt(opt==1)       // full tilt correction
1385         ,pseudo(opt==2)     // pseudo tilt correction
1386         ,rc(IsRowCross())   // row cross candidate 
1387         ,kDZDX(IsPrimary());// switch dzdx calculation for barrel primary tracks
1388   Int_t n(0);   // clusters used in fit 
1389   AliTRDcluster *c(NULL), *cc(NULL), **jc = &fClusters[0];
1390   const AliTRDrecoParam* const recoParam = fkReconstructor->GetRecoParam(); //the dynamic cast in GetRecoParam is slow, so caching the pointer to it
1391
1392   const Char_t *tcName[]={"NONE", "FULL", "HALF"};
1393   AliDebug(2, Form("Options : TC[%s] dzdx[%c]", tcName[opt], kDZDX?'Y':'N'));
1394
1395   for (Int_t ic=0; ic<kNclusters; ic++, ++jc) {
1396     xc[ic]  = -1.; yc[ic]  = 999.; zc[ic]  = 999.; sy[ic]  = 0.;
1397     if(!(c = (*jc))) continue;
1398     if(!c->IsInChamber()) continue;
1399     // compute pseudo tilt correction
1400     if(kDZDX){ 
1401       fZfit[0] = c->GetZ();
1402       if(rc){
1403         for(Int_t kc=AliTRDseedV1::kNtb; kc<AliTRDseedV1::kNclusters; kc++){
1404           if(!(cc=fClusters[kc])) continue;
1405           if(!cc->IsInChamber()) continue;
1406           fZfit[0] += cc->GetZ(); fZfit[0] *= 0.5;
1407           break;
1408         }
1409       }
1410       fZfit[1] = fZfit[0]/fX0;
1411       if(rc){
1412         fZfit[0] += fZfit[1]*0.5*AliTRDgeometry::CdrHght();
1413         fZfit[1] = fZfit[0]/fX0;
1414       }
1415       kDZDX=kFALSE;
1416     }
1417
1418     Float_t w = 1.;
1419     if(c->GetNPads()>4) w = .5;
1420     if(c->GetNPads()>5) w = .2;
1421
1422     // cluster charge
1423     qc[n]   = TMath::Abs(c->GetQ());
1424     // pad row of leading 
1425
1426     xc[n]   = fX0 - c->GetX();
1427
1428     // Recalculate cluster error based on tracking information
1429     c->SetSigmaY2(fS2PRF, fDiffT, fExB, xc[n], -1./*zcorr?zt:-1.*/, dydx);
1430     c->SetSigmaZ2(fPad[0]*fPad[0]/12.); // for HLT
1431     sy[n]  = TMath::Sqrt(c->GetSigmaY2());
1432
1433     yc[n]  = recoParam->UseGAUS() ? 
1434       c->GetYloc(y0, sy[n], GetPadWidth()): c->GetY();
1435     zc[n]   = c->GetZ();
1436
1437     //optional r-phi correction
1438     //printf("   n[%2d] yc[%7.5f] ", n, yc[n]);
1439     Float_t correction(0.);
1440     if(tilt) correction = fPad[2]*(xc[n]*dzdx + zc[n] - z0);
1441     else if(pseudo) correction = fPad[2]*(xc[n]*fZfit[1] + zc[n]-fZfit[0]);
1442     yc[n]-=correction;
1443     //printf("corr(%s%s)[%7.5f] yc1[%7.5f]\n", (tilt?"TC":""), (zcorr?"PC":""), correction, yc[n]);
1444
1445     AliDebug(5, Form("  tb[%2d] dx[%6.3f] y[%6.2f+-%6.3f]", c->GetLocalTimeBin(), xc[n], yc[n], sy[n]));
1446     fitterY.AddPoint(&xc[n], yc[n], sy[n]);
1447     if(rc) fitterZ.AddPoint(&xc[n], qc[n]*(ic<kNtb?1.:-1.), 1.);
1448     n++;
1449   }
1450
1451   // to few clusters
1452   if (n < kClmin){ 
1453     AliDebug(1, Form("Not enough clusters to fit. Clusters: Attached[%d] Fit[%d].", GetN(), n));
1454     SetErrorMsg(kFitCl);
1455     return kFALSE; 
1456   }
1457   // fit XY
1458   if(!fitterY.Eval()){
1459     AliDebug(1, "Fit Y failed.");
1460     SetErrorMsg(kFitFailedY);
1461     return kFALSE;
1462   }
1463   fYfit[0] = fitterY.GetFunctionParameter(0);
1464   fYfit[1] = -fitterY.GetFunctionParameter(1);
1465   // store covariance
1466   Double_t p[3];
1467   fitterY.GetCovarianceMatrix(p);
1468   fCov[0] = kScalePulls*p[1]; // variance of y0
1469   fCov[1] = kScalePulls*p[2]; // covariance of y0, dydx
1470   fCov[2] = kScalePulls*p[0]; // variance of dydx
1471   // the ref radial position is set at the minimum of 
1472   // the y variance of the tracklet
1473   fX   = -fCov[1]/fCov[2];
1474   fS2Y = fCov[0] +2.*fX*fCov[1] + fX*fX*fCov[2];
1475
1476   Float_t xs=fX+.5*AliTRDgeometry::CamHght();
1477   if(xs < 0. || xs > AliTRDgeometry::CamHght()+AliTRDgeometry::CdrHght()){
1478     AliDebug(1, Form("Ref radial position ouside chamber x[%5.2f].", fX));
1479     SetErrorMsg(kFitFailedY);
1480     return kFALSE;
1481   }
1482
1483 /*    // THE LEADING CLUSTER METHOD for z fit
1484     Float_t xMin = fX0;
1485     Int_t ic=n=kNclusters-1; jc = &fClusters[ic];
1486     AliTRDcluster *c0 =0x0, **kc = &fClusters[kNtb-1];
1487     for(; ic>kNtb; ic--, --jc, --kc){
1488       if((c0 = (*kc)) && c0->IsInChamber() && (xMin>c0->GetX())) xMin = c0->GetX();
1489       if(!(c = (*jc))) continue;
1490       if(!c->IsInChamber()) continue;
1491       zc[kNclusters-1] = c->GetZ(); 
1492       fX = fX0 - c->GetX();
1493     }
1494     fZfit[0] = .5*(zc[0]+zc[kNclusters-1]); fZfit[1] = 0.;
1495     // Error parameterization
1496     fS2Z     = fdX*fZref[1];
1497     fS2Z    *= fS2Z; fS2Z    *= 0.2887; //  1/sqrt(12)*/
1498
1499   // fit QZ
1500   if(opt!=1 && IsRowCross()){
1501     if(!fitterZ.Eval()) SetErrorMsg(kFitFailedZ);
1502     if(!HasError(kFitFailedZ) && TMath::Abs(fitterZ.GetFunctionParameter(1))>1.e-10){ 
1503       // TODO - one has to recalculate xy fit based on
1504       // better knowledge of z position
1505 //       Double_t x = -fitterZ.GetFunctionParameter(0)/fitterZ.GetFunctionParameter(1);
1506 //       Double_t z0 = .5*(zc[0]+zc[n-1]);
1507 //       fZfit[0] = z0 + fZfit[1]*x; 
1508 //       fZfit[1] = fZfit[0]/fX0; 
1509 //       redo fit on xy plane
1510     }
1511     // temporary external error parameterization
1512     fS2Z     = 0.05+0.4*TMath::Abs(fZref[1]); fS2Z *= fS2Z;
1513     // TODO correct formula
1514     //fS2Z     = sigma_x*TMath::Abs(fZref[1]);
1515   } else {
1516     //fZfit[0] = zc[0] + dzdx*0.5*AliTRDgeometry::CdrHght();
1517     fS2Z     = GetPadLength()*GetPadLength()/12.;
1518   }
1519   return kTRUE;
1520 }
1521
1522
1523 /*
1524 //_____________________________________________________________________________
1525 void AliTRDseedV1::FitMI()
1526 {
1527 //
1528 // Fit the seed.
1529 // Marian Ivanov's version 
1530 //
1531 // linear fit on the y direction with respect to the reference direction. 
1532 // The residuals for each x (x = xc - x0) are deduced from:
1533 // dy = y - yt             (1)
1534 // the tilting correction is written :
1535 // y = yc + h*(zc-zt)      (2)
1536 // yt = y0+dy/dx*x         (3)
1537 // zt = z0+dz/dx*x         (4)
1538 // from (1),(2),(3) and (4)
1539 // dy = yc - y0 - (dy/dx + h*dz/dx)*x + h*(zc-z0)
1540 // the last term introduces the correction on y direction due to tilting pads. There are 2 ways to account for this:
1541 // 1. use tilting correction for calculating the y
1542 // 2. neglect tilting correction here and account for it in the error parametrization of the tracklet.
1543   const Float_t kRatio  = 0.8;
1544   const Int_t   kClmin  = 5;
1545   const Float_t kmaxtan = 2;
1546
1547   if (TMath::Abs(fYref[1]) > kmaxtan){
1548                 //printf("Exit: Abs(fYref[1]) = %3.3f, kmaxtan = %3.3f\n", TMath::Abs(fYref[1]), kmaxtan);
1549                 return;              // Track inclined too much
1550         }
1551
1552   Float_t  sigmaexp  = 0.05 + TMath::Abs(fYref[1] * 0.25); // Expected r.m.s in y direction
1553   Float_t  ycrosscor = GetPadLength() * GetTilt() * 0.5;           // Y correction for crossing 
1554   Int_t fNChange = 0;
1555
1556   Double_t sumw;
1557   Double_t sumwx;
1558   Double_t sumwx2;
1559   Double_t sumwy;
1560   Double_t sumwxy;
1561   Double_t sumwz;
1562   Double_t sumwxz;
1563
1564         // Buffering: Leave it constant fot Performance issues
1565   Int_t    zints[kNtb];            // Histograming of the z coordinate 
1566                                          // Get 1 and second max probable coodinates in z
1567   Int_t    zouts[2*kNtb];       
1568   Float_t  allowedz[kNtb];         // Allowed z for given time bin
1569   Float_t  yres[kNtb];             // Residuals from reference
1570   //Float_t  anglecor = GetTilt() * fZref[1];  // Correction to the angle
1571   
1572   Float_t pos[3*kNtb]; memset(pos, 0, 3*kNtb*sizeof(Float_t));
1573   Float_t *fX = &pos[0], *fY = &pos[kNtb], *fZ = &pos[2*kNtb];
1574   
1575   Int_t fN  = 0; AliTRDcluster *c = 0x0; 
1576   fN2 = 0;
1577   for (Int_t i = 0; i < AliTRDtrackerV1::GetNTimeBins(); i++) {
1578     yres[i] = 10000.0;
1579     if (!(c = fClusters[i])) continue;
1580     if(!c->IsInChamber()) continue;
1581     // Residual y
1582     //yres[i] = fY[i] - fYref[0] - (fYref[1] + anglecor) * fX[i] + GetTilt()*(fZ[i] - fZref[0]);
1583     fX[i] = fX0 - c->GetX();
1584     fY[i] = c->GetY();
1585     fZ[i] = c->GetZ();
1586     yres[i] = fY[i] - GetTilt()*(fZ[i] - (fZref[0] - fX[i]*fZref[1]));
1587     zints[fN] = Int_t(fZ[i]);
1588     fN++;
1589   }
1590
1591   if (fN < kClmin){
1592     //printf("Exit fN < kClmin: fN = %d\n", fN);
1593     return; 
1594   }
1595   Int_t nz = AliTRDtrackerV1::Freq(fN, zints, zouts, kFALSE);
1596   Float_t fZProb   = zouts[0];
1597   if (nz <= 1) zouts[3] = 0;
1598   if (zouts[1] + zouts[3] < kClmin) {
1599     //printf("Exit zouts[1] = %d, zouts[3] = %d\n",zouts[1],zouts[3]);
1600     return;
1601   }
1602   
1603   // Z distance bigger than pad - length
1604   if (TMath::Abs(zouts[0]-zouts[2]) > 12.0) zouts[3] = 0;
1605   
1606   Int_t  breaktime = -1;
1607   Bool_t mbefore   = kFALSE;
1608   Int_t  cumul[kNtb][2];
1609   Int_t  counts[2] = { 0, 0 };
1610   
1611   if (zouts[3] >= 3) {
1612
1613     //
1614     // Find the break time allowing one chage on pad-rows
1615     // with maximal number of accepted clusters
1616     //
1617     fNChange = 1;
1618     for (Int_t i = 0; i < AliTRDtrackerV1::GetNTimeBins(); i++) {
1619       cumul[i][0] = counts[0];
1620       cumul[i][1] = counts[1];
1621       if (TMath::Abs(fZ[i]-zouts[0]) < 2) counts[0]++;
1622       if (TMath::Abs(fZ[i]-zouts[2]) < 2) counts[1]++;
1623     }
1624     Int_t  maxcount = 0;
1625     for (Int_t i = 0; i < AliTRDtrackerV1::GetNTimeBins(); i++) {
1626       Int_t after  = cumul[AliTRDtrackerV1::GetNTimeBins()][0] - cumul[i][0];
1627       Int_t before = cumul[i][1];
1628       if (after + before > maxcount) { 
1629         maxcount  = after + before; 
1630         breaktime = i;
1631         mbefore   = kFALSE;
1632       }
1633       after  = cumul[AliTRDtrackerV1::GetNTimeBins()-1][1] - cumul[i][1];
1634       before = cumul[i][0];
1635       if (after + before > maxcount) { 
1636         maxcount  = after + before; 
1637         breaktime = i;
1638         mbefore   = kTRUE;
1639       }
1640     }
1641     breaktime -= 1;
1642   }
1643
1644   for (Int_t i = 0; i < AliTRDtrackerV1::GetNTimeBins()+1; i++) {
1645     if (i >  breaktime) allowedz[i] =   mbefore  ? zouts[2] : zouts[0];
1646     if (i <= breaktime) allowedz[i] = (!mbefore) ? zouts[2] : zouts[0];
1647   }  
1648
1649   if (((allowedz[0] > allowedz[AliTRDtrackerV1::GetNTimeBins()]) && (fZref[1] < 0)) ||
1650       ((allowedz[0] < allowedz[AliTRDtrackerV1::GetNTimeBins()]) && (fZref[1] > 0))) {
1651     //
1652     // Tracklet z-direction not in correspondance with track z direction 
1653     //
1654     fNChange = 0;
1655     for (Int_t i = 0; i < AliTRDtrackerV1::GetNTimeBins()+1; i++) {
1656       allowedz[i] = zouts[0];  // Only longest taken
1657     } 
1658   }
1659   
1660   if (fNChange > 0) {
1661     //
1662     // Cross pad -row tracklet  - take the step change into account
1663     //
1664     for (Int_t i = 0; i < AliTRDtrackerV1::GetNTimeBins()+1; i++) {
1665       if (!fClusters[i]) continue; 
1666       if(!fClusters[i]->IsInChamber()) continue;
1667       if (TMath::Abs(fZ[i] - allowedz[i]) > 2) continue;
1668       // Residual y
1669       //yres[i] = fY[i] - fYref[0] - (fYref[1] + anglecor) * fX[i] + GetTilt()*(fZ[i] - fZref[0]);   
1670       yres[i] = fY[i] - GetTilt()*(fZ[i] - (fZref[0] - fX[i]*fZref[1]));
1671 //       if (TMath::Abs(fZ[i] - fZProb) > 2) {
1672 //         if (fZ[i] > fZProb) yres[i] += GetTilt() * GetPadLength();
1673 //         if (fZ[i] < fZProb) yres[i] -= GetTilt() * GetPadLength();
1674       }
1675     }
1676   }
1677   
1678   Double_t yres2[kNtb];
1679   Double_t mean;
1680   Double_t sigma;
1681   for (Int_t i = 0; i < AliTRDtrackerV1::GetNTimeBins()+1; i++) {
1682     if (!fClusters[i]) continue;
1683     if(!fClusters[i]->IsInChamber()) continue;
1684     if (TMath::Abs(fZ[i] - allowedz[i]) > 2) continue;
1685     yres2[fN2] = yres[i];
1686     fN2++;
1687   }
1688   if (fN2 < kClmin) {
1689                 //printf("Exit fN2 < kClmin: fN2 = %d\n", fN2);
1690     fN2 = 0;
1691     return;
1692   }
1693   AliMathBase::EvaluateUni(fN2,yres2,mean,sigma, Int_t(fN2*kRatio-2.));
1694   if (sigma < sigmaexp * 0.8) {
1695     sigma = sigmaexp;
1696   }
1697   //Float_t fSigmaY = sigma;
1698
1699   // Reset sums
1700   sumw   = 0; 
1701   sumwx  = 0; 
1702   sumwx2 = 0;
1703   sumwy  = 0; 
1704   sumwxy = 0; 
1705   sumwz  = 0;
1706   sumwxz = 0;
1707
1708   fN2    = 0;
1709   Float_t fMeanz = 0;
1710   Float_t fMPads = 0;
1711   fUsable = 0;
1712   for (Int_t i = 0; i < AliTRDtrackerV1::GetNTimeBins()+1; i++) {
1713     if (!fClusters[i]) continue;
1714     if (!fClusters[i]->IsInChamber()) continue;
1715     if (TMath::Abs(fZ[i] - allowedz[i]) > 2){fClusters[i] = 0x0; continue;}
1716     if (TMath::Abs(yres[i] - mean) > 4.0 * sigma){fClusters[i] = 0x0;  continue;}
1717     SETBIT(fUsable,i);
1718     fN2++;
1719     fMPads += fClusters[i]->GetNPads();
1720     Float_t weight = 1.0;
1721     if (fClusters[i]->GetNPads() > 4) weight = 0.5;
1722     if (fClusters[i]->GetNPads() > 5) weight = 0.2;
1723    
1724         
1725     Double_t x = fX[i];
1726     //printf("x = %7.3f dy = %7.3f fit %7.3f\n", x, yres[i], fY[i]-yres[i]);
1727     
1728     sumw   += weight; 
1729     sumwx  += x * weight; 
1730     sumwx2 += x*x * weight;
1731     sumwy  += weight * yres[i];  
1732     sumwxy += weight * (yres[i]) * x;
1733     sumwz  += weight * fZ[i];    
1734     sumwxz += weight * fZ[i] * x;
1735
1736   }
1737
1738   if (fN2 < kClmin){
1739                 //printf("Exit fN2 < kClmin(2): fN2 = %d\n",fN2);
1740     fN2 = 0;
1741     return;
1742   }
1743   fMeanz = sumwz / sumw;
1744   Float_t correction = 0;
1745   if (fNChange > 0) {
1746     // Tracklet on boundary
1747     if (fMeanz < fZProb) correction =  ycrosscor;
1748     if (fMeanz > fZProb) correction = -ycrosscor;
1749   }
1750
1751   Double_t det = sumw * sumwx2 - sumwx * sumwx;
1752   fYfit[0]    = (sumwx2 * sumwy  - sumwx * sumwxy) / det;
1753   fYfit[1]    = (sumw   * sumwxy - sumwx * sumwy)  / det;
1754   
1755   fS2Y = 0;
1756   for (Int_t i = 0; i < AliTRDtrackerV1::GetNTimeBins()+1; i++) {
1757     if (!TESTBIT(fUsable,i)) continue;
1758     Float_t delta = yres[i] - fYfit[0] - fYfit[1] * fX[i];
1759     fS2Y += delta*delta;
1760   }
1761   fS2Y = TMath::Sqrt(fS2Y / Float_t(fN2-2));
1762         // TEMPORARY UNTIL covariance properly calculated
1763         fS2Y = TMath::Max(fS2Y, Float_t(.1));
1764   
1765   fZfit[0]   = (sumwx2 * sumwz  - sumwx * sumwxz) / det;
1766   fZfit[1]   = (sumw   * sumwxz - sumwx * sumwz)  / det;
1767 //   fYfitR[0] += fYref[0] + correction;
1768 //   fYfitR[1] += fYref[1];
1769 //  fYfit[0]   = fYfitR[0];
1770   fYfit[1]   = -fYfit[1];
1771
1772   UpdateUsed();
1773 }*/
1774
1775 //___________________________________________________________________
1776 void AliTRDseedV1::Print(Option_t *o) const
1777 {
1778   //
1779   // Printing the seedstatus
1780   //
1781
1782   AliInfo(Form("Det[%3d] X0[%7.2f] Pad{L[%5.2f] W[%5.2f] Tilt[%+6.2f]}", fDet, fX0, GetPadLength(), GetPadWidth(), GetTilt()));
1783   AliInfo(Form("N[%2d] Nused[%2d] Nshared[%2d] [%d]", GetN(), GetNUsed(), GetNShared(), fN));
1784   AliInfo(Form("FLAGS : RC[%c] Kink[%c] SA[%c]", IsRowCross()?'y':'n', IsKink()?'y':'n', IsStandAlone()?'y':'n'));
1785   AliInfo(Form("CALIB PARAMS :  T0[%5.2f]  Vd[%5.2f]  s2PRF[%5.2f]  ExB[%5.2f]  Dl[%5.2f]  Dt[%5.2f]", fT0, fVD, fS2PRF, fExB, fDiffL, fDiffT));
1786
1787   Double_t cov[3], x=GetX();
1788   GetCovAt(x, cov);
1789   AliInfo("    |  x[cm]  |      y[cm]       |      z[cm]      |  dydx |  dzdx |");
1790   AliInfo(Form("Fit | %7.2f | %7.2f+-%7.2f | %7.2f+-%7.2f| %5.2f | ----- |", x, GetY(), TMath::Sqrt(cov[0]), GetZ(), TMath::Sqrt(cov[2]), fYfit[1]));
1791   AliInfo(Form("Ref | %7.2f | %7.2f+-%7.2f | %7.2f+-%7.2f| %5.2f | %5.2f |", x, fYref[0]-fX*fYref[1], TMath::Sqrt(fRefCov[0]), fZref[0]-fX*fYref[1], TMath::Sqrt(fRefCov[2]), fYref[1], fZref[1]))
1792   AliInfo(Form("P / Pt [GeV/c] = %f / %f", GetMomentum(), fPt));
1793   if(IsStandAlone()) AliInfo(Form("C Rieman / Vertex [1/cm] = %f / %f", fC[0], fC[1]));
1794   AliInfo(Form("dEdx [a.u.]    = %f / %f / %f / %f / %f/ %f / %f / %f", fdEdx[0], fdEdx[1], fdEdx[2], fdEdx[3], fdEdx[4], fdEdx[5], fdEdx[6], fdEdx[7]));
1795   AliInfo(Form("PID            = %5.3f / %5.3f / %5.3f / %5.3f / %5.3f", fProb[0], fProb[1], fProb[2], fProb[3], fProb[4]));
1796
1797   if(strcmp(o, "a")!=0) return;
1798
1799   AliTRDcluster* const* jc = &fClusters[0];
1800   for(int ic=0; ic<kNclusters; ic++, jc++) {
1801     if(!(*jc)) continue;
1802     (*jc)->Print(o);
1803   }
1804 }
1805
1806
1807 //___________________________________________________________________
1808 Bool_t AliTRDseedV1::IsEqual(const TObject *o) const
1809 {
1810   // Checks if current instance of the class has the same essential members
1811   // as the given one
1812
1813   if(!o) return kFALSE;
1814   const AliTRDseedV1 *inTracklet = dynamic_cast<const AliTRDseedV1*>(o);
1815   if(!inTracklet) return kFALSE;
1816
1817   for (Int_t i = 0; i < 2; i++){
1818     if ( fYref[i] != inTracklet->fYref[i] ) return kFALSE;
1819     if ( fZref[i] != inTracklet->fZref[i] ) return kFALSE;
1820   }
1821   
1822   if ( TMath::Abs(fS2Y - inTracklet->fS2Y)>1.e-10 ) return kFALSE;
1823   if ( TMath::Abs(GetTilt() - inTracklet->GetTilt())>1.e-10 ) return kFALSE;
1824   if ( TMath::Abs(GetPadLength() - inTracklet->GetPadLength())>1.e-10 ) return kFALSE;
1825   
1826   for (Int_t i = 0; i < kNclusters; i++){
1827 //     if ( fX[i] != inTracklet->GetX(i) ) return kFALSE;
1828 //     if ( fY[i] != inTracklet->GetY(i) ) return kFALSE;
1829 //     if ( fZ[i] != inTracklet->GetZ(i) ) return kFALSE;
1830     if ( fIndexes[i] != inTracklet->fIndexes[i] ) return kFALSE;
1831   }
1832 //   if ( fUsable != inTracklet->fUsable ) return kFALSE;
1833
1834   for (Int_t i=0; i < 2; i++){
1835     if ( fYfit[i] != inTracklet->fYfit[i] ) return kFALSE;
1836     if ( fZfit[i] != inTracklet->fZfit[i] ) return kFALSE;
1837     if ( fLabels[i] != inTracklet->fLabels[i] ) return kFALSE;
1838   }
1839   
1840 /*  if ( fMeanz != inTracklet->GetMeanz() ) return kFALSE;
1841   if ( fZProb != inTracklet->GetZProb() ) return kFALSE;*/
1842   if ( fN != inTracklet->fN ) return kFALSE;
1843   //if ( fNUsed != inTracklet->fNUsed ) return kFALSE;
1844   //if ( fFreq != inTracklet->GetFreq() ) return kFALSE;
1845   //if ( fNChange != inTracklet->GetNChange() ) return kFALSE;
1846    
1847   if ( TMath::Abs(fC[0] - inTracklet->fC[0])>1.e-10 ) return kFALSE;
1848   //if ( fCC != inTracklet->GetCC() ) return kFALSE;
1849   if ( TMath::Abs(fChi2 - inTracklet->fChi2)>1.e-10 ) return kFALSE;
1850   //  if ( fChi2Z != inTracklet->GetChi2Z() ) return kFALSE;
1851
1852   if ( fDet != inTracklet->fDet ) return kFALSE;
1853   if ( TMath::Abs(fPt - inTracklet->fPt)>1.e-10 ) return kFALSE;
1854   if ( TMath::Abs(fdX - inTracklet->fdX)>1.e-10 ) return kFALSE;
1855   
1856   for (Int_t iCluster = 0; iCluster < kNclusters; iCluster++){
1857     AliTRDcluster *curCluster = fClusters[iCluster];
1858     AliTRDcluster *inCluster = inTracklet->fClusters[iCluster];
1859     if (curCluster && inCluster){
1860       if (! curCluster->IsEqual(inCluster) ) {
1861         curCluster->Print();
1862         inCluster->Print();
1863         return kFALSE;
1864       }
1865     } else {
1866       // if one cluster exists, and corresponding 
1867       // in other tracklet doesn't - return kFALSE
1868       if(curCluster || inCluster) return kFALSE;
1869     }
1870   }
1871   return kTRUE;
1872 }
1873