]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - TRD/AliTRDseedV1.cxx
extend debug stream to prepare studies of bremsstrahlung detection in
[u/mrichter/AliRoot.git] / TRD / AliTRDseedV1.cxx
index fac4bd3ab55a4f7dba6324b26cc3996ca92d1b64..82f2ca98c430e7f936278c8d17b60e972f7d6ae5 100644 (file)
@@ -102,7 +102,7 @@ AliTRDseedV1::AliTRDseedV1(Int_t det)
   for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec]  = -1.;
   fLabels[0]=-1; fLabels[1]=-1; // most freq MC labels
   fLabels[2]=0;  // number of different labels for tracklet
-  memset(fRefCov, 0, 3*sizeof(Double_t));
+  memset(fRefCov, 0, 7*sizeof(Double_t));
   // covariance matrix [diagonal]
   // default sy = 200um and sz = 2.3 cm 
   fCov[0] = 4.e-4; fCov[1] = 0.; fCov[2] = 5.3; 
@@ -221,7 +221,7 @@ void AliTRDseedV1::Copy(TObject &ref) const
   memcpy(target.fdEdx, fdEdx, kNslices*sizeof(Float_t)); 
   memcpy(target.fProb, fProb, AliPID::kSPECIES*sizeof(Float_t)); 
   memcpy(target.fLabels, fLabels, 3*sizeof(Int_t)); 
-  memcpy(target.fRefCov, fRefCov, 3*sizeof(Double_t)); 
+  memcpy(target.fRefCov, fRefCov, 7*sizeof(Double_t)); 
   memcpy(target.fCov, fCov, 3*sizeof(Double_t)); 
   
   TObject::Copy(ref);
@@ -247,7 +247,7 @@ Bool_t AliTRDseedV1::Init(AliTRDtrackV1 *track)
 
   Double_t y, z; 
   if(!track->GetProlongation(fX0, y, z)) return kFALSE;
-  UpDate(track);
+  Update(track);
   return kTRUE;
 }
 
@@ -279,23 +279,23 @@ void AliTRDseedV1::Reset()
   for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec]  = -1.;
   fLabels[0]=-1; fLabels[1]=-1; // most freq MC labels
   fLabels[2]=0;  // number of different labels for tracklet
-  memset(fRefCov, 0, 3*sizeof(Double_t));
+  memset(fRefCov, 0, 7*sizeof(Double_t));
   // covariance matrix [diagonal]
   // default sy = 200um and sz = 2.3 cm 
   fCov[0] = 4.e-4; fCov[1] = 0.; fCov[2] = 5.3; 
 }
 
 //____________________________________________________________________
-void AliTRDseedV1::UpDate(const AliTRDtrackV1 *trk)
+void AliTRDseedV1::Update(const AliTRDtrackV1 *trk)
 { 
   // update tracklet reference position from the TRD track
-  // Funny name to avoid the clash with the function AliTRDseed::Update() (has to be made obselete)
 
   Double_t fSnp = trk->GetSnp();
   Double_t fTgl = trk->GetTgl();
   fPt = trk->Pt();
-  fYref[1] = fSnp/TMath::Sqrt(1. - fSnp*fSnp);
-  fZref[1] = fTgl;
+  Double_t norm =1./TMath::Sqrt(1. - fSnp*fSnp); 
+  fYref[1] = fSnp*norm;
+  fZref[1] = fTgl*norm;
   SetCovRef(trk->GetCovariance());
 
   Double_t dx = trk->GetX() - fX0;
@@ -451,28 +451,95 @@ void AliTRDseedV1::CookLabels()
 
 
 //____________________________________________________________________
-Float_t AliTRDseedV1::GetdQdl(Int_t ic) const
+Float_t AliTRDseedV1::GetdQdl(Int_t ic, Float_t *dl) const
 {
 // Using the linear approximation of the track inside one TRD chamber (TRD tracklet) 
 // the charge per unit length can be written as:
 // BEGIN_LATEX
-// #frac{dq}{dl} = #frac{q_{c}}{dx * #sqrt{1 + #(){#frac{dy}{dx}}^{2}_{fit} + #(){#frac{dy}{dx}}^{2}_{ref}}}
+// #frac{dq}{dl} = #frac{q_{c}}{dx * #sqrt{1 + #(){#frac{dy}{dx}}^{2}_{fit} + #(){#frac{dz}{dx}}^{2}_{ref}}}
 // END_LATEX
 // where qc is the total charge collected in the current time bin and dx is the length 
-// of the time bin. For the moment (Jan 20 2009) only pad row cross corrections are 
-// considered for the charge but none are applied for drift velocity variations along 
-// the drift region or assymetry of the TRF
+// of the time bin. 
+// The following correction are applied :
+//   - charge : pad row cross corrections
+//              [diffusion and TRF assymetry] TODO
+//   - dx     : anisochronity, track inclination - see Fit and AliTRDcluster::GetXloc() 
+//              and AliTRDcluster::GetYloc() for the effects taken into account
 // 
+//Begin_Html
+//<img src="TRD/trackletDQDT.gif">
+//End_Html
+// In the picture the energy loss measured on the tracklet as a function of drift time [left] and respectively 
+// drift length [right] for different particle species is displayed.
 // Author : Alex Bercuci <A.Bercuci@gsi.de>
 //
   Float_t dq = 0.;
-  if(fClusters[ic]) dq += TMath::Abs(fClusters[ic]->GetQ());
-  if(fClusters[ic+kNtb]) dq += TMath::Abs(fClusters[ic+kNtb]->GetQ());
-  if(dq<1.e-3 || fdX < 1.e-3) return 0.;
+  // check whether both clusters are inside the chamber
+  Bool_t hasClusterInChamber = kFALSE;
+  if(fClusters[ic] && fClusters[ic]->IsInChamber()){
+    hasClusterInChamber = kTRUE;
+    dq += TMath::Abs(fClusters[ic]->GetQ());
+  }else if(fClusters[ic+kNtb] && fClusters[ic+kNtb]->IsInChamber()){
+    hasClusterInChamber = kTRUE;
+    dq += TMath::Abs(fClusters[ic+kNtb]->GetQ());
+  }
+  if(!hasClusterInChamber) return 0.;
+  if(dq<1.e-3) return 0.;
+
+  Double_t dx = fdX;
+  if(ic-1>=0 && ic+1<kNtb){
+    Float_t x2(0.), x1(0.);
+    // try to estimate upper radial position (find the cluster which is inside the chamber)
+    if(fClusters[ic-1] && fClusters[ic-1]->IsInChamber()) x2 = fClusters[ic-1]->GetX(); 
+    else if(fClusters[ic-1+kNtb] && fClusters[ic-1+kNtb]->IsInChamber()) x2 = fClusters[ic-1+kNtb]->GetX(); 
+    else if(fClusters[ic] && fClusters[ic]->IsInChamber()) x2 = fClusters[ic]->GetX()+fdX;
+    else x2 = fClusters[ic+kNtb]->GetX()+fdX;
+    // try to estimate lower radial position (find the cluster which is inside the chamber)
+    if(fClusters[ic+1] && fClusters[ic+1]->IsInChamber()) x1 = fClusters[ic+1]->GetX();
+    else if(fClusters[ic+1+kNtb] && fClusters[ic+1+kNtb]->IsInChamber()) x1 = fClusters[ic+1+kNtb]->GetX();
+    else if(fClusters[ic] && fClusters[ic]->IsInChamber()) x1 = fClusters[ic]->GetX()-fdX;
+    else x1 = fClusters[ic+kNtb]->GetX()-fdX;
+
+    dx = .5*(x2 - x1);
+  }
+  dx *= TMath::Sqrt(1. + fYfit[1]*fYfit[1] + fZref[1]*fZref[1]);
+  if(dl) (*dl) = dx;
+  return dq/dx;
+}
+
+//____________________________________________________________
+Float_t AliTRDseedV1::GetMomentum(Float_t *err) const
+{ 
+// Returns momentum of the track after update with the current tracklet as:
+// BEGIN_LATEX
+// p=#frac{1}{1/p_{t}} #sqrt{1+tgl^{2}}
+// END_LATEX
+// and optionally the momentum error (if err is not null). 
+// The estimated variance of the momentum is given by:
+// BEGIN_LATEX
+// #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})
+// END_LATEX
+// which can be simplified to
+// BEGIN_LATEX
+// #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}
+// END_LATEX
+//
 
-  return dq/fdX/TMath::Sqrt(1. + fYfit[1]*fYfit[1] + fZref[1]*fZref[1]);
+  Double_t p = fPt*TMath::Sqrt(1.+fZref[1]*fZref[1]);
+  Double_t p2 = p*p;
+  Double_t tgl2 = fZref[1]*fZref[1];
+  Double_t pt2 = fPt*fPt;
+  if(err){
+    Double_t s2 = 
+      p2*tgl2*pt2*pt2*fRefCov[4]
+     -2.*p2*fZref[1]*fPt*pt2*fRefCov[5]
+     +p2*pt2*fRefCov[6];
+    (*err) = TMath::Sqrt(s2);
+  }
+  return p;
 }
 
+
 //____________________________________________________________________
 Float_t* AliTRDseedV1::GetProbability(Bool_t force)
 {      
@@ -491,10 +558,15 @@ Bool_t AliTRDseedV1::CookPID()
 // Output
 //   returns pointer to the probability array and 0x0 if missing DB access 
 //
-// Detailed description
+// Retrieve PID probabilities for e+-, mu+-, K+-, pi+- and p+- from the DB according to tracklet information:
+// - estimated momentum at tracklet reference point 
+// - dE/dx measurements
+// - tracklet length
+// - TRD layer
+// According to the steering settings specified in the reconstruction one of the following methods are used
+// - Neural Network [default] - option "nn"  
+// - 2D Likelihood - option "!nn"  
 
-  
-  // retrive calibration db
   AliTRDcalibDB *calibration = AliTRDcalibDB::Instance();
   if (!calibration) {
     AliError("No access to calibration data");
@@ -594,7 +666,8 @@ void AliTRDseedV1::GetCovAt(Double_t x, Double_t *cov) const
 
   Double_t xr     = fX0-x; 
   Double_t sy2    = fCov[0] +2.*xr*fCov[1] + xr*xr*fCov[2];
-  Double_t sz2    = GetPadLength()*GetPadLength()/12.;
+  Double_t sz2    = fS2Z;
+  //GetPadLength()*GetPadLength()/12.;
 
   // insert systematic uncertainties
   if(fReconstructor){
@@ -609,6 +682,8 @@ void AliTRDseedV1::GetCovAt(Double_t x, Double_t *cov) const
   cov[0] = (sy2+t2*sz2)*correction;
   cov[1] = GetTilt()*(sz2 - sy2)*correction;
   cov[2] = (t2*sy2+sz2)*correction;
+
+  //printf("C(%6.1f %+6.3f %6.1f)  [%s]\n", 1.e4*TMath::Sqrt(cov[0]), cov[1], 1.e4*TMath::Sqrt(cov[2]), IsRowCross()?" RC ":"-");
 }
 
 //____________________________________________________________
@@ -681,6 +756,15 @@ Double_t AliTRDseedV1::GetCovInv(Double_t *c, Double_t *d)
   return Det;
 }
 
+//____________________________________________________________________
+UShort_t AliTRDseedV1::GetVolumeId() const
+{
+  Int_t ic=0;
+  while(ic<kNclusters && !fClusters[ic]) ic++;
+  return fClusters[ic] ? fClusters[ic]->GetVolumeId() : 0;
+}
+
+
 //____________________________________________________________________
 void AliTRDseedV1::Calibrate()
 {
@@ -758,153 +842,36 @@ void AliTRDseedV1::SetPadPlane(AliTRDpadPlane *p)
 }
 
 
-// //____________________________________________________________________
-// Bool_t      AliTRDseedV1::AttachClustersIter(AliTRDtrackingChamber *chamber, Float_t quality, Bool_t kZcorr, AliTRDcluster *c)
-// {
-//   //
-//   // Iterative process to register clusters to the seed.
-//   // In iteration 0 we try only one pad-row and if quality not
-//   // sufficient we try 2 pad-rows (about 5% of tracks cross 2 pad-rows)
-//   //
-//   // debug level 7
-//   //
-//   
-//   if(!fReconstructor->GetRecoParam() ){
-//     AliError("Seed can not be used without a valid RecoParam.");
-//     return kFALSE;
-//   }
-// 
-//   AliTRDchamberTimeBin *layer = 0x0;
-//   if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7){
-//     AliTRDtrackingChamber ch(*chamber);
-//     ch.SetOwner(); 
-//     TTreeSRedirector &cstreamer = *fReconstructor->GetDebugStream(AliTRDReconstructor::kTracker);
-//     cstreamer << "AttachClustersIter"
-//       << "chamber.="   << &ch
-//       << "tracklet.="  << this
-//       << "\n";      
-//   }
-// 
-//   Float_t  tquality;
-//   Double_t kroady = fReconstructor->GetRecoParam() ->GetRoad1y();
-//   Double_t kroadz = GetPadLength() * .5 + 1.;
-//   
-//   // initialize configuration parameters
-//   Float_t zcorr = kZcorr ? GetTilt() * (fZfit[0] - fZref[0]) : 0.;
-//   Int_t   niter = kZcorr ? 1 : 2;
-//   
-//   Double_t yexp, zexp;
-//   Int_t ncl = 0;
-//   // start seed update
-//   for (Int_t iter = 0; iter < niter; iter++) {
-//     ncl = 0;
-//     for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
-//       if(!(layer = chamber->GetTB(iTime))) continue;
-//       if(!Int_t(*layer)) continue;
-//       
-//       // define searching configuration
-//       Double_t dxlayer = layer->GetX() - fX0;
-//       if(c){
-//         zexp = c->GetZ();
-//         //Try 2 pad-rows in second iteration
-//         if (iter > 0) {
-//           zexp = fZref[0] + fZref[1] * dxlayer - zcorr;
-//           if (zexp > c->GetZ()) zexp = c->GetZ() + GetPadLength()*0.5;
-//           if (zexp < c->GetZ()) zexp = c->GetZ() - GetPadLength()*0.5;
-//         }
-//       } else zexp = fZref[0] + (kZcorr ? fZref[1] * dxlayer : 0.);
-//       yexp  = fYref[0] + fYref[1] * dxlayer - zcorr;
-//       
-//       // Get and register cluster
-//       Int_t    index = layer->SearchNearestCluster(yexp, zexp, kroady, kroadz);
-//       if (index < 0) continue;
-//       AliTRDcluster *cl = (*layer)[index];
-//       
-//       fIndexes[iTime]  = layer->GetGlobalIndex(index);
-//       fClusters[iTime] = cl;
-// //       fY[iTime]        = cl->GetY();
-// //       fZ[iTime]        = cl->GetZ();
-//       ncl++;
-//     }
-//     if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7) AliInfo(Form("iter = %d ncl [%d] = %d", iter, fDet, ncl));
-//     
-//     if(ncl>1){      
-//       // calculate length of the time bin (calibration aware)
-//       Int_t irp = 0; Float_t x[2]={0., 0.}; Int_t tb[2] = {0,0};
-//       for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
-//         if(!fClusters[iTime]) continue;
-//         x[irp]  = fClusters[iTime]->GetX();
-//         tb[irp] = iTime;
-//         irp++;
-//         if(irp==2) break;
-//       } 
-//       Int_t dtb = tb[1] - tb[0];
-//       fdX = dtb ? (x[0] - x[1]) / dtb : 0.15;
-// 
-//       // update X0 from the clusters (calibration/alignment aware)
-//       for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
-//         if(!(layer = chamber->GetTB(iTime))) continue;
-//         if(!layer->IsT0()) continue;
-//         if(fClusters[iTime]){ 
-//           fX0 = fClusters[iTime]->GetX();
-//           break;
-//         } else { // we have to infere the position of the anode wire from the other clusters
-//           for (Int_t jTime = iTime+1; jTime < AliTRDtrackerV1::GetNTimeBins(); jTime++) {
-//             if(!fClusters[jTime]) continue;
-//             fX0 = fClusters[jTime]->GetX() + fdX * (jTime - iTime);
-//             break;
-//           }
-//         }
-//       }     
-//       
-//       // update YZ reference point
-//       // TODO
-//       
-//       // update x reference positions (calibration/alignment aware)
-// //       for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
-// //         if(!fClusters[iTime]) continue;
-// //         fX[iTime] = fX0 - fClusters[iTime]->GetX();
-// //       } 
-//       
-//       FitMI();
-//     }
-//     if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7) AliInfo(Form("iter = %d nclFit [%d] = %d", iter, fDet, fN2));
-//     
-//     if(IsOK()){
-//       tquality = GetQuality(kZcorr);
-//       if(tquality < quality) break;
-//       else quality = tquality;
-//     }
-//     kroadz *= 2.;
-//   } // Loop: iter
-//   if (!IsOK()) return kFALSE;
-// 
-//   if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=1) CookLabels();
-// 
-//   // load calibration params
-//   Calibrate();
-//   UpdateUsed();
-//   return kTRUE;     
-// }
-
 //____________________________________________________________________
 Bool_t AliTRDseedV1::AttachClusters(AliTRDtrackingChamber *chamber, Bool_t tilt)
 {
-  //
-  // Projective algorithm to attach clusters to seeding tracklets
-  //
-  // Parameters
-  //
-  // Output
-  //
-  // Detailed description
-  // 1. Collapse x coordinate for the full detector plane
-  // 2. truncated mean on y (r-phi) direction
-  // 3. purge clusters
-  // 4. truncated mean on z direction
-  // 5. purge clusters
-  // 6. fit tracklet
-  //   
+//
+// Projective algorithm to attach clusters to seeding tracklets. The following steps are performed :
+// 1. Collapse x coordinate for the full detector plane
+// 2. truncated mean on y (r-phi) direction
+// 3. purge clusters
+// 4. truncated mean on z direction
+// 5. purge clusters
+//
+// Parameters
+//  - chamber : pointer to tracking chamber container used to search the tracklet
+//  - tilt    : switch for tilt correction during road building [default true]
+// Output
+//  - true    : if tracklet found successfully. Failure can happend because of the following:
+//      -
+// Detailed description
+//     
+// We start up by defining the track direction in the xy plane and roads. The roads are calculated based
+// on tracking information (variance in the r-phi direction) and estimated variance of the standard 
+// clusters (see AliTRDcluster::SetSigmaY2()) corrected for tilt (see GetCovAt()). From this the road is
+// BEGIN_LATEX
+// 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})})}
+// r_{z} = 1.5*L_{pad}
+// END_LATEX
+// 
+// Author : Alexandru Bercuci <A.Bercuci@gsi.de>
+// Debug  : level >3
+
   Bool_t kPRINT = kFALSE;
   if(!fReconstructor->GetRecoParam() ){
     AliError("Seed can not be used without a valid RecoParam.");
@@ -912,39 +879,55 @@ Bool_t    AliTRDseedV1::AttachClusters(AliTRDtrackingChamber *chamber, Bool_t tilt)
   }
   // Initialize reco params for this tracklet
   // 1. first time bin in the drift region
-  Int_t t0 = 4;
+  Int_t t0 = 14;
   Int_t kClmin = Int_t(fReconstructor->GetRecoParam() ->GetFindableClusters()*AliTRDtrackerV1::GetNTimeBins());
 
-  Double_t syRef  = TMath::Sqrt(fRefCov[0]);
+  Double_t s2yTrk= fRefCov[0], 
+           s2yCl = 0., 
+           s2zCl = GetPadLength()*GetPadLength()/12., 
+           syRef = TMath::Sqrt(s2yTrk),
+           t2    = GetTilt()*GetTilt();
   //define roads
-  Double_t kroady = 1.; 
-  //fReconstructor->GetRecoParam() ->GetRoad1y();
-  Double_t kroadz = GetPadLength() * 1.5 + 1.;
+  Double_t kroady = 1., //fReconstructor->GetRecoParam() ->GetRoad1y();
+           kroadz = GetPadLength() * 1.5 + 1.;
+  // define probing cluster (the perfect cluster) and default calibration
+  Short_t sig[] = {0, 0, 10, 30, 10, 0,0};
+  AliTRDcluster cp(fDet, 6, 75, 0, sig, 0);
+  Calibrate();
+
   if(kPRINT) printf("AttachClusters() sy[%f] road[%f]\n", syRef, kroady);
 
   // working variables
   const Int_t kNrows = 16;
-  AliTRDcluster *clst[kNrows][kNclusters];
-  Double_t cond[4], dx, dy, yt, zt,
-    yres[kNrows][kNclusters];
-  Int_t idxs[kNrows][kNclusters], ncl[kNrows], ncls = 0;
+  const Int_t kNcls  = 3*kNclusters; // buffer size
+  AliTRDcluster *clst[kNrows][kNcls];
+  Double_t cond[4], dx, dy, yt, zt, yres[kNrows][kNcls];
+  Int_t idxs[kNrows][kNcls], ncl[kNrows], ncls = 0;
   memset(ncl, 0, kNrows*sizeof(Int_t));
-  memset(clst, 0, kNrows*kNclusters*sizeof(AliTRDcluster*));
+  memset(yres, 0, kNrows*kNcls*sizeof(Double_t));
+  memset(clst, 0, kNrows*kNcls*sizeof(AliTRDcluster*));
 
   // Do cluster projection
   AliTRDcluster *c = 0x0;
   AliTRDchamberTimeBin *layer = 0x0;
   Bool_t kBUFFER = kFALSE;
-  for (Int_t it = 0; it < AliTRDtrackerV1::GetNTimeBins(); it++) {
+  for (Int_t it = 0; it < kNtb; it++) {
     if(!(layer = chamber->GetTB(it))) continue;
     if(!Int_t(*layer)) continue;
-    
+    // get track projection at layers position
     dx   = fX0 - layer->GetX();
     yt = fYref[0] - fYref[1] * dx;
     zt = fZref[0] - fZref[1] * dx;
-    if(kPRINT) printf("\t%2d dx[%f] yt[%f] zt[%f]\n", it, dx, yt, zt);
+    // get standard cluster error corrected for tilt
+    cp.SetLocalTimeBin(it);
+    cp.SetSigmaY2(0.02, fDiffT, fExB, dx, -1./*zt*/, fYref[1]);
+    s2yCl = (cp.GetSigmaY2() + t2*s2zCl)/(1.+t2);
+    // get estimated road
+    kroady = 3.*TMath::Sqrt(12.*(s2yTrk + s2yCl));
+
+    if(kPRINT) printf("  %2d dx[%f] yt[%f] zt[%f] sT[um]=%6.2f sy[um]=%6.2f syTilt[um]=%6.2f yRoad[mm]=%f\n", it, dx, yt, zt, 1.e4*TMath::Sqrt(s2yTrk), 1.e4*TMath::Sqrt(cp.GetSigmaY2()), 1.e4*TMath::Sqrt(s2yCl), 1.e1*kroady);
 
-    // select clusters on a 5 sigmaKalman level
+    // select clusters
     cond[0] = yt; cond[2] = kroady;
     cond[1] = zt; cond[3] = kroadz;
     Int_t n=0, idx[6];
@@ -965,8 +948,8 @@ Bool_t      AliTRDseedV1::AttachClusters(AliTRDtrackingChamber *chamber, Bool_t tilt)
       yres[r][ncl[r]] = dy;
       ncl[r]++; ncls++;
 
-      if(ncl[r] >= kNclusters) {
-        AliWarning(Form("Cluster candidates reached limit %d. Some may be lost.", kNclusters));
+      if(ncl[r] >= kNcls) {
+        AliWarning(Form("Cluster candidates reached buffer limit %d. Some may be lost.", kNcls));
         kBUFFER = kTRUE;
         break;
       }
@@ -989,10 +972,28 @@ Bool_t    AliTRDseedV1::AttachClusters(AliTRDtrackingChamber *chamber, Bool_t tilt)
     if(ncl[ir] > 3) AliMathBase::EvaluateUni(ncl[ir], yres[ir], mean, syDis, Int_t(ncl[ir]*.8));
     else {
       mean = 0.; syDis = 0.;
+      continue;
     } 
 
+    if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker) > 3){
+      TTreeSRedirector &cstreamer = *fReconstructor->GetDebugStream(AliTRDReconstructor::kTracker);
+      TVectorD dy(ncl[ir], yres[ir]);
+      UChar_t stat(0);
+      if(IsKink()) SETBIT(stat, 0);
+      if(IsStandAlone()) SETBIT(stat, 1);
+      cstreamer << "AttachClusters"
+          << "stat="   << stat
+          << "det="    << fDet
+          << "pt="     << fPt
+          << "s2y="    << s2yTrk
+          << "dy="     << &dy
+          << "m="      << mean
+          << "s="      << syDis
+          << "\n";
+    }
+
     // TODO check mean and sigma agains cluster resolution !!
-    if(kPRINT) printf("\tr[%2d] m[%f %5.3fsigma] s[%f]\n", ir, mean, TMath::Abs(mean/syRef), syDis);
+    if(kPRINT) printf("\tr[%2d] m[%f %5.3fsigma] s[%f]\n", ir, mean, TMath::Abs(mean/syDis), syDis);
     // select clusters on a 3 sigmaDistr level
     Bool_t kFOUND = kFALSE;
     for(Int_t ic = ncl[ir]; ic--;){
@@ -1062,17 +1063,15 @@ Bool_t  AliTRDseedV1::AttachClusters(AliTRDtrackingChamber *chamber, Bool_t tilt)
   Calibrate();
 
   // calculate dx for time bins in the drift region (calibration aware)
-  Int_t irp = 0; Float_t x[2] = {0.,0.}; Int_t tb[2]={0,0};
-  for (Int_t it = t0; it < AliTRDtrackerV1::GetNTimeBins(); it++) {
+  Float_t x[2] = {0.,0.}; Int_t tb[2]={0,0};
+  for (Int_t it = t0, irp=0; irp<2 && it < AliTRDtrackerV1::GetNTimeBins(); it++) {
     if(!fClusters[it]) continue;
     x[irp]  = fClusters[it]->GetX();
-    tb[irp] = it;
+    tb[irp] = fClusters[it]->GetLocalTimeBin();
     irp++;
-    if(irp==2) break;
   }  
   Int_t dtb = tb[1] - tb[0];
   fdX = dtb ? (x[0] - x[1]) / dtb : 0.15;
-
   return kTRUE;
 }
 
@@ -1114,60 +1113,104 @@ void AliTRDseedV1::Bootstrap(const AliTRDReconstructor *rec)
 
 
 //____________________________________________________________________
-Bool_t AliTRDseedV1::Fit(Bool_t tilt, Int_t errors)
+Bool_t AliTRDseedV1::Fit(Bool_t tilt, Bool_t zcorr)
 {
-  //
-  // Linear fit of the tracklet
-  //
-  // Parameters :
-  //
-  // Output :
-  //  True if successful
-  //
-  // Detailed description
-  // 2. Check if tracklet crosses pad row boundary
-  // 1. Calculate residuals in the y (r-phi) direction
-  // 3. Do a Least Square Fit to the data
-  //
+//
+// Linear fit of the clusters attached to the tracklet
+//
+// Parameters :
+//   - tilt : switch for tilt pad correction of cluster y position based on 
+//            the z, dzdx info from outside [default false].
+//   - zcorr : switch for using z information to correct for anisochronity 
+//            and a finner error parameterization estimation [default false]  
+// Output :
+//  True if successful
+//
+// Detailed description
+//
+//            Fit in the xy plane
+// 
+// The fit is performed to estimate the y position of the tracklet and the track 
+// angle in the bending plane. The clusters are represented in the chamber coordinate 
+// system (with respect to the anode wire - see AliTRDtrackerV1::FollowBackProlongation() 
+// on how this is set). The x and y position of the cluster and also their variances 
+// are known from clusterizer level (see AliTRDcluster::GetXloc(), AliTRDcluster::GetYloc(), 
+// AliTRDcluster::GetSX() and AliTRDcluster::GetSY()). 
+// If gaussian approximation is used to calculate y coordinate of the cluster the position 
+// is recalculated taking into account the track angle. The general formula to calculate the 
+// error of cluster position in the gaussian approximation taking into account diffusion and track
+// inclination is given for TRD by:
+// BEGIN_LATEX
+// #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}
+// END_LATEX
+//
+// Since errors are calculated only in the y directions, radial errors (x direction) are mapped to y
+// by projection i.e.
+// BEGIN_LATEX
+// #sigma_{x|y} = tg(#phi) #sigma_{x}
+// END_LATEX
+// and also by the lorentz angle correction
+//
+//            Fit in the xz plane
+//
+// The "fit" is performed to estimate the radial position (x direction) where pad row cross happens. 
+// If no pad row crossing the z position is taken from geometry and radial position is taken from the xy 
+// fit (see below).
+// 
+// There are two methods to estimate the radial position of the pad row cross:
+//   1. leading cluster radial position : Here the lower part of the tracklet is considered and the last 
+// cluster registered (at radial x0) on this segment is chosen to mark the pad row crossing. The error 
+// of the z estimate is given by :
+// BEGIN_LATEX
+// #sigma_{z} = tg(#theta) #Delta x_{x_{0}}/12
+// END_LATEX
+// The systematic errors for this estimation are generated by the following sources:
+//   - no charge sharing between pad rows is considered (sharp cross)
+//   - missing cluster at row cross (noise peak-up, under-threshold signal etc.).
+// 
+//   2. charge fit over the crossing point : Here the full energy deposit along the tracklet is considered 
+// to estimate the position of the crossing by a fit in the qx plane. The errors in the q directions are 
+// parameterized as s_q = q^2. The systematic errors for this estimation are generated by the following sources:
+//   - no general model for the qx dependence
+//   - physical fluctuations of the charge deposit 
+//   - gain calibration dependence
+//
+//            Estimation of the radial position of the tracklet
+//
+// For pad row cross the radial position is taken from the xz fit (see above). Otherwise it is taken as the 
+// interpolation point of the tracklet i.e. the point where the error in y of the fit is minimum. The error
+// in the y direction of the tracklet is (see AliTRDseedV1::GetCovAt()):
+// BEGIN_LATEX
+// #sigma_{y} = #sigma^{2}_{y_{0}} + 2xcov(y_{0}, dy/dx) + #sigma^{2}_{dy/dx}
+// END_LATEX
+// and thus the radial position is:
+// BEGIN_LATEX
+// x = - cov(y_{0}, dy/dx)/#sigma^{2}_{dy/dx}
+// END_LATEX
+//
+//            Estimation of tracklet position error 
+//
+// The error in y direction is the error of the linear fit at the radial position of the tracklet while in the z 
+// direction is given by the cluster error or pad row cross error. In case of no pad row cross this is given by:
+// BEGIN_LATEX
+// #sigma_{y} = #sigma^{2}_{y_{0}} - 2cov^{2}(y_{0}, dy/dx)/#sigma^{2}_{dy/dx} + #sigma^{2}_{dy/dx}
+// #sigma_{z} = Pad_{length}/12
+// END_LATEX
+// For pad row cross the full error is calculated at the radial position of the crossing (see above) and the error 
+// in z by the width of the crossing region - being a matter of parameterization. 
+// BEGIN_LATEX
+// #sigma_{z} = tg(#theta) #Delta x_{x_{0}}/12
+// END_LATEX
+// In case of no tilt correction (default in the barrel tracking) the tilt is taken into account by the rotation of
+// the covariance matrix. See AliTRDseedV1::GetCovAt() for details.
+//
+// Author 
+// A.Bercuci <A.Bercuci@gsi.de>
 
-  if(!IsCalibrated()){
-    AliWarning("Tracklet fit failed. Call Calibrate().");
-    return kFALSE;
-  }
+  if(!IsCalibrated()) Calibrate();
 
   const Int_t kClmin = 8;
 
-
-  // cluster error parametrization parameters 
-  // 1. sy total charge
-  const Float_t sq0inv = 0.019962; // [1/q0]
-  const Float_t sqb    = 1.0281564;    //[cm]
-  // 2. sy for the PRF
-  const Float_t scy[AliTRDgeometry::kNlayer][4] = {
-    {2.827e-02, 9.600e-04, 4.296e-01, 2.271e-02},
-    {2.952e-02,-2.198e-04, 4.146e-01, 2.339e-02},
-    {3.090e-02, 1.514e-03, 4.020e-01, 2.402e-02},
-    {3.260e-02,-2.037e-03, 3.946e-01, 2.509e-02},
-    {3.439e-02,-3.601e-04, 3.883e-01, 2.623e-02},
-    {3.510e-02, 2.066e-03, 3.651e-01, 2.588e-02},
-  };
-  // 3. sy parallel to the track
-  const Float_t sy0 =  2.649e-02; // [cm]
-  const Float_t sya = -8.864e-04; // [cm]
-  const Float_t syb = -2.435e-01; // [cm]
-
-  // 4. sx parallel to the track
-  const Float_t sxgc = 5.427e-02;
-  const Float_t sxgm = 7.783e-01;
-  const Float_t sxgs = 2.743e-01;
-  const Float_t sxe0 =-2.065e+00;
-  const Float_t sxe1 =-2.978e-02;
-
-  // 5. sx perpendicular to the track
-//   const Float_t sxd0 = 1.881e-02;
-//   const Float_t sxd1 =-4.101e-01;
-//   const Float_t sxd2 = 1.572e+00;
-
   // get track direction
   Double_t y0   = fYref[0];
   Double_t dydx = fYref[1]; 
@@ -1175,28 +1218,20 @@ Bool_t AliTRDseedV1::Fit(Bool_t tilt, Int_t errors)
   Double_t dzdx = fZref[1];
   Double_t yt, zt;
 
-  // calculation of tg^2(phi - a_L) and tg^2(a_L)
-  Double_t tgg = (dydx-fExB)/(1.+dydx*fExB); tgg *= tgg;
-  //Double_t exb2= fExB*fExB;
-
   //AliTRDtrackerV1::AliTRDLeastSquare fitterZ;
   TLinearFitter  fitterY(1, "pol1");
-  // convertion factor from square to gauss distribution for sigma
-  //Double_t convert = 1./TMath::Sqrt(12.);
+  TLinearFitter  fitterZ(1, "pol1");
   
   // book cluster information
   Double_t qc[kNclusters], xc[kNclusters], yc[kNclusters], zc[kNclusters], sy[kNclusters];
 
-  Int_t ily = AliTRDgeometry::GetLayer(fDet);
   Int_t n = 0;
   AliTRDcluster *c=0x0, **jc = &fClusters[0];
   for (Int_t ic=0; ic<kNtb; ic++, ++jc) {
-    //zRow[ic] = -1;
     xc[ic]  = -1.;
     yc[ic]  = 999.;
     zc[ic]  = 999.;
     sy[ic]  = 0.;
-    //sz[ic]  = 0.;
     if(!(c = (*jc))) continue;
     if(!c->IsInChamber()) continue;
 
@@ -1204,66 +1239,31 @@ Bool_t AliTRDseedV1::Fit(Bool_t tilt, Int_t errors)
     if(c->GetNPads()>4) w = .5;
     if(c->GetNPads()>5) w = .2;
 
-    //zRow[fN] = c->GetPadRow();
+    // cluster charge
     qc[n]   = TMath::Abs(c->GetQ());
-    // correct cluster position for PRF and v drift
+    // pad row of leading 
+
+    // Radial cluster position
     //Int_t jc = TMath::Max(fN-3, 0);
     //xc[fN]   = c->GetXloc(fT0, fVD, &qc[jc], &xc[jc]/*, z0 - c->GetX()*dzdx*/);
-    //Double_t s2 = fS2PRF + fDiffL*fDiffL*xc[fN]/(1.+2.*exb2)+tgg*xc[fN]*xc[fN]*exb2/12.;
-    //yc[fN]   = c->GetYloc(s2, GetPadWidth(), xc[fN], fExB);
-    
-    // uncalibrated cluster correction 
-    // TODO remove
-    Double_t x, y; 
-    //GetClusterXY(c, x, y);
-    x = c->GetX(); y = c->GetY();
-    xc[n]   = fX0 - x;
-    yc[n]   = y;
-    zc[n]   = c->GetZ();
+    xc[n]   = fX0 - c->GetX();
 
-    // extrapolated y value for the track
+    // extrapolated track to cluster position
     yt = y0 - xc[n]*dydx; 
-    // extrapolated z value for the track
     zt = z0 - xc[n]*dzdx; 
-    // tilt correction
-    if(tilt) yc[n] -= GetTilt()*(zc[n] - zt); 
-
-    // ELABORATE CLUSTER ERROR
-    // TODO to be moved to AliTRDcluster
-    // basic y error (|| to track).
-    sy[n]  = xc[n] < AliTRDgeometry::CamHght() ? 2. : sy0 + sya*TMath::Exp(1./(xc[n]+syb));
-    //printf("cluster[%d]\n\tsy[0] = %5.3e [um]\n", fN,  sy[fN]*1.e4);
-    // y error due to total charge
-    sy[n] += sqb*(1./qc[n] - sq0inv);
-    //printf("\tsy[1] = %5.3e [um]\n", sy[fN]*1.e4);
-    // y error due to PRF
-    sy[n] += scy[ily][0]*TMath::Gaus(c->GetCenter(), scy[ily][1], scy[ily][2]) - scy[ily][3];
-    //printf("\tsy[2] = %5.3e [um]\n", sy[fN]*1.e4);
-
-    sy[n] *= sy[n];
-
-    // ADD ERROR ON x
-    // error of drift length parallel to the track
-    Double_t sx = sxgc*TMath::Gaus(xc[n], sxgm, sxgs) + TMath::Exp(sxe0+sxe1*xc[n]); // [cm]
-    //printf("\tsx[0] = %5.3e [um]\n", sx*1.e4);
-    // error of drift length perpendicular to the track
-    //sx += sxd0 + sxd1*d + sxd2*d*d;
-    sx *= sx; // square sx
-
-    // add error from ExB 
-    if(errors>0) sy[n] += fExB*fExB*sx;
-    //printf("\tsy[3] = %5.3e [um^2]\n", sy[fN]*1.e8);
-
-    // global radial error due to misalignment/miscalibration
-    Double_t sx0  = 0.; sx0 *= sx0;
-    // add sx contribution to sy due to track angle
-    if(errors>1) sy[n] += tgg*(sx+sx0);
-    // TODO we should add tilt pad correction here
-    //printf("\tsy[4] = %5.3e [um^2]\n", sy[fN]*1.e8);
-    c->SetSigmaY2(sy[n]);
-
-    sy[n]  = TMath::Sqrt(sy[n]);
-    fitterY.AddPoint(&xc[n], yc[n], sy[n]);
+
+    // Recalculate cluster error based on tracking information
+    c->SetSigmaY2(fS2PRF, fDiffT, fExB, xc[n], zcorr?zt:-1., dydx);
+    sy[n]  = TMath::Sqrt(c->GetSigmaY2());
+
+    yc[n]   = fReconstructor->UseGAUS() ? 
+      c->GetYloc(y0, sy[n], GetPadWidth()): c->GetY();
+    zc[n]   = c->GetZ();
+    //optional tilt correction
+    if(tilt) yc[n] -= (GetTilt()*(zc[n] - zt)); 
+
+    fitterY.AddPoint(&xc[n], yc[n], TMath::Sqrt(sy[n]));
+    fitterZ.AddPoint(&xc[n], qc[n], 1.);
     n++;
   }
   // to few clusters
@@ -1280,61 +1280,57 @@ Bool_t AliTRDseedV1::Fit(Bool_t tilt, Int_t errors)
   fCov[2] = p[3]; // variance of dydx
   // the ref radial position is set at the minimum of 
   // the y variance of the tracklet
-  fX   = -fCov[1]/fCov[2]; //fXref = fX0 - fXref;
-  fS2Y = fCov[0] +2.*fX*fCov[1] + fX*fX*fCov[2];
+  fX   = -fCov[1]/fCov[2];
 
   // fit XZ
-  if(IsRowCross()){ 
-    // TODO pad row cross position estimation !!!
-    //AliInfo(Form("Padrow cross in detector %d", fDet));
-    fZfit[0] = .5*(zc[0]+zc[n-1]); fZfit[1] = 0.;
-    fS2Z     = 0.02+1.55*fZref[1]; fS2Z *= fS2Z;
+  if(IsRowCross()){
+/*    // THE LEADING CLUSTER METHOD
+    Float_t xMin = fX0;
+    Int_t ic=n=kNclusters-1; jc = &fClusters[ic];
+    AliTRDcluster *c0 =0x0, **kc = &fClusters[kNtb-1];
+    for(; ic>kNtb; ic--, --jc, --kc){
+      if((c0 = (*kc)) && c0->IsInChamber() && (xMin>c0->GetX())) xMin = c0->GetX();
+      if(!(c = (*jc))) continue;
+      if(!c->IsInChamber()) continue;
+      zc[kNclusters-1] = c->GetZ(); 
+      fX = fX0 - c->GetX();
+    }
+    fZfit[0] = .5*(zc[0]+zc[kNclusters-1]); fZfit[1] = 0.;
+    // Error parameterization
+    fS2Z     = fdX*fZref[1];
+    fS2Z    *= fS2Z; fS2Z    *= 0.2887; //  1/sqrt(12)*/
+
+    // THE FIT X-Q PLANE METHOD 
+    Int_t ic=n=kNclusters-1; jc = &fClusters[ic];
+    for(; ic>kNtb; ic--, --jc){
+      if(!(c = (*jc))) continue;
+      if(!c->IsInChamber()) continue;
+      qc[n]   = TMath::Abs(c->GetQ());
+      xc[n]   = fX0 - c->GetX();
+      zc[n]   = c->GetZ();
+      fitterZ.AddPoint(&xc[n], -qc[n], 1.);
+      n--;
+    }
+    // fit XZ
+    fitterZ.Eval();
+    if(fitterZ.GetParameter(1)!=0.){ 
+      fX = -fitterZ.GetParameter(0)/fitterZ.GetParameter(1);
+      fX=(fX<0.)?0.:fX;
+      Float_t dl = .5*AliTRDgeometry::CamHght()+AliTRDgeometry::CdrHght();
+      fX=(fX> dl)?dl:fX;
+      fX-=.055; // TODO to be understood
+    }
+
+    fZfit[0] = .5*(zc[0]+zc[kNclusters-1]); fZfit[1] = 0.;
+    // temporary external error parameterization
+    fS2Z     = 0.05+0.4*TMath::Abs(fZref[1]); fS2Z *= fS2Z;
+    // TODO correct formula
+    //fS2Z     = sigma_x*TMath::Abs(fZref[1]);
   } else {
     fZfit[0] = zc[0]; fZfit[1] = 0.;
     fS2Z     = GetPadLength()*GetPadLength()/12.;
   }
-
-
-//   // determine z offset of the fit
-//   Float_t zslope = 0.;
-//   Int_t nchanges = 0, nCross = 0;
-//   if(nz==2){ // tracklet is crossing pad row
-//     // Find the break time allowing one chage on pad-rows
-//     // with maximal number of accepted clusters
-//     Int_t padRef = zRow[0];
-//     for (Int_t ic=1; ic<fN; ic++) {
-//       if(zRow[ic] == padRef) continue;
-//       
-//       // debug
-//       if(zRow[ic-1] == zRow[ic]){
-//         printf("ERROR in pad row change!!!\n");
-//       }
-//     
-//       // evaluate parameters of the crossing point
-//       Float_t sx = (xc[ic-1] - xc[ic])*convert;
-//       fCross[0] = .5 * (xc[ic-1] + xc[ic]);
-//       fCross[2] = .5 * (zc[ic-1] + zc[ic]);
-//       fCross[3] = TMath::Max(dzdx * sx, .01);
-//       zslope    = zc[ic-1] > zc[ic] ? 1. : -1.;
-//       padRef    = zRow[ic];
-//       nCross    = ic;
-//       nchanges++;
-//     }
-//   }
-// 
-//   // condition on nCross and reset nchanges TODO
-// 
-//   if(nchanges==1){
-//     if(dzdx * zslope < 0.){
-//       AliInfo("Tracklet-Track mismatch in dzdx. TODO.");
-//     }
-// 
-// 
-//     //zc[nc] = fitterZ.GetFunctionParameter(0); 
-//     fCross[1] = fYfit[0] - fCross[0] * fYfit[1];
-//     fCross[0] = fX0 - fCross[0];
-//   }
-
+  fS2Y = fCov[0] +2.*fX*fCov[1] + fX*fX*fCov[2];
   return kTRUE;
 }
 
@@ -1598,14 +1594,15 @@ void AliTRDseedV1::Print(Option_t *o) const
   // Printing the seedstatus
   //
 
-  AliInfo(Form("Det[%3d] X0[%7.2f] Pad[L[%5.2f] W[%5.2f] Tilt[%+6.2f]]", fDet, fX0, GetPadLength(), GetPadWidth(), GetTilt()));
+  AliInfo(Form("Det[%3d] X0[%7.2f] Pad{L[%5.2f] W[%5.2f] Tilt[%+6.2f]}", fDet, fX0, GetPadLength(), GetPadWidth(), GetTilt()));
   AliInfo(Form("N[%2d] Nused[%2d] Nshared[%2d] [%d]", GetN(), GetNUsed(), GetNShared(), fN));
+  AliInfo(Form("FLAGS : RC[%c] Kink[%c] SA[%c]", IsRowCross()?'y':'n', IsKink()?'y':'n', IsStandAlone()?'y':'n'));
 
   Double_t cov[3], x=GetX();
   GetCovAt(x, cov);
   AliInfo("    |  x[cm]  |      y[cm]       |      z[cm]      |  dydx |  dzdx |");
   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]));
-  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[2]),  fZref[0]-fX*fYref[1], TMath::Sqrt(fRefCov[2]), fYref[1], fZref[1]))
+  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]))
 
 
   if(strcmp(o, "a")!=0) return;
@@ -1684,3 +1681,4 @@ Bool_t AliTRDseedV1::IsEqual(const TObject *o) const
   }
   return kTRUE;
 }
+