Update of reco param by Alex
[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 track seed                                                    //
21 //                                                                        //
22 //  Authors:                                                              //
23 //    Alex Bercuci <A.Bercuci@gsi.de>                                     //
24 //    Markus Fasel <M.Fasel@gsi.de>                                       //
25 //                                                                        //
26 ////////////////////////////////////////////////////////////////////////////
27
28 #include "TMath.h"
29 #include "TLinearFitter.h"
30 #include "TClonesArray.h" // tmp
31 #include <TTreeStream.h>
32
33 #include "AliLog.h"
34 #include "AliMathBase.h"
35
36 #include "AliTRDcluster.h"
37 #include "AliTRDseedV1.h"
38 #include "AliTRDtrackV1.h"
39 #include "AliTRDcalibDB.h"
40 #include "AliTRDchamberTimeBin.h"
41 #include "AliTRDtrackingChamber.h"
42 #include "AliTRDtrackerV1.h"
43 #include "AliTRDReconstructor.h"
44 #include "AliTRDrecoParam.h"
45 #include "AliTRDgeometry.h"
46 #include "Cal/AliTRDCalPID.h"
47
48 ClassImp(AliTRDseedV1)
49
50 //____________________________________________________________________
51 AliTRDseedV1::AliTRDseedV1(Int_t plane) 
52   :AliTRDseed()
53   ,fReconstructor(0x0)
54   ,fPlane(plane)
55   ,fMom(0.)
56   ,fSnp(0.)
57   ,fTgl(0.)
58   ,fdX(0.)
59 {
60   //
61   // Constructor
62   //
63         for(int islice=0; islice < knSlices; islice++) fdEdx[islice] = 0.;
64         for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec]  = -1.;
65 }
66
67 //____________________________________________________________________
68 AliTRDseedV1::AliTRDseedV1(const AliTRDseedV1 &ref)
69   :AliTRDseed((AliTRDseed&)ref)
70   ,fReconstructor(0x0)
71   ,fPlane(ref.fPlane)
72   ,fMom(ref.fMom)
73   ,fSnp(ref.fSnp)
74   ,fTgl(ref.fTgl)
75   ,fdX(ref.fdX)
76 {
77   //
78   // Copy Constructor performing a deep copy
79   //
80
81         //AliInfo("");
82         for(int islice=0; islice < knSlices; islice++) fdEdx[islice] = ref.fdEdx[islice];
83         for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) fProb[ispec] = ref.fProb[ispec];
84 }
85
86
87 //____________________________________________________________________
88 AliTRDseedV1& AliTRDseedV1::operator=(const AliTRDseedV1 &ref)
89 {
90   //
91   // Assignment Operator using the copy function
92   //
93
94         //AliInfo("");
95         if(this != &ref){
96                 ref.Copy(*this);
97         }
98         return *this;
99
100 }
101
102 //____________________________________________________________________
103 AliTRDseedV1::~AliTRDseedV1()
104 {
105   //
106   // Destructor. The RecoParam object belongs to the underlying tracker.
107   //
108
109         //AliInfo(Form("fOwner[%s]", fOwner?"YES":"NO"));
110
111         if(IsOwner()) 
112                 for(int itb=0; itb<knTimebins; itb++){
113                         if(!fClusters[itb]) continue; 
114                         //AliInfo(Form("deleting c %p @ %d", fClusters[itb], itb));
115                         delete fClusters[itb];
116                         fClusters[itb] = 0x0;
117                 }
118 }
119
120 //____________________________________________________________________
121 void AliTRDseedV1::Copy(TObject &ref) const
122 {
123   //
124   // Copy function
125   //
126
127         //AliInfo("");
128         AliTRDseedV1 &target = (AliTRDseedV1 &)ref; 
129         
130         target.fPlane         = fPlane;
131         target.fMom           = fMom;
132         target.fSnp           = fSnp;
133         target.fTgl           = fTgl;
134         target.fdX            = fdX;
135         
136         for(int islice=0; islice < knSlices; islice++) target.fdEdx[islice] = fdEdx[islice];
137         for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) target.fProb[ispec] = fProb[ispec];
138         
139         AliTRDseed::Copy(target);
140 }
141
142
143 //____________________________________________________________
144 Bool_t AliTRDseedV1::Init(AliTRDtrackV1 *track)
145 {
146 // Initialize this tracklet using the track information
147 //
148 // Parameters:
149 //   track - the TRD track used to initialize the tracklet
150 // 
151 // Detailed description
152 // The function sets the starting point and direction of the
153 // tracklet according to the information from the TRD track.
154 // 
155 // Caution
156 // The TRD track has to be propagated to the beginning of the
157 // chamber where the tracklet will be constructed
158 //
159
160         Double_t y, z; 
161         if(!track->GetProlongation(fX0, y, z)) return kFALSE;
162         fYref[0] = y;
163         fYref[1] = track->GetSnp()/(1. - track->GetSnp()*track->GetSnp());
164         fZref[0] = z;
165         fZref[1] = track->GetTgl();
166
167         //printf("Tracklet ref x[%7.3f] y[%7.3f] z[%7.3f], snp[%f] tgl[%f]\n", fX0, fYref[0], fZref[0], track->GetSnp(), track->GetTgl());
168         return kTRUE;
169 }
170
171
172 //____________________________________________________________________
173 void AliTRDseedV1::CookdEdx(Int_t nslices)
174 {
175 // Calculates average dE/dx for all slices and store them in the internal array fdEdx. 
176 //
177 // Parameters:
178 //  nslices : number of slices for which dE/dx should be calculated
179 // Output:
180 //  store results in the internal array fdEdx. This can be accessed with the method
181 //  AliTRDseedV1::GetdEdx()
182 //
183 // Detailed description
184 // Calculates average dE/dx for all slices. Depending on the PID methode 
185 // the number of slices can be 3 (LQ) or 8(NN). 
186 // The calculation of dQ/dl are done using the tracklet fit results (see AliTRDseedV1::GetdQdl(Int_t)) i.e.
187 //
188 // dQ/dl = qc/(dx * sqrt(1 + dy/dx^2 + dz/dx^2))
189 //
190 // The following effects are included in the calculation:
191 // 1. calibration values for t0 and vdrift (using x coordinate to calculate slice)
192 // 2. cluster sharing (optional see AliTRDrecoParam::SetClusterSharing())
193 // 3. cluster size
194 //
195
196         Int_t nclusters[knSlices];
197         for(int i=0; i<knSlices; i++){ 
198                 fdEdx[i]     = 0.;
199                 nclusters[i] = 0;
200         }
201         Float_t clength = (/*.5 * */AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
202
203         AliTRDcluster *cluster = 0x0;
204         for(int ic=0; ic<AliTRDtrackerV1::GetNTimeBins(); ic++){
205                 if(!(cluster = fClusters[ic])) continue;
206                 Float_t x = cluster->GetX();
207                 
208                 // Filter clusters for dE/dx calculation
209                 
210                 // 1.consider calibration effects for slice determination
211                 Int_t slice; 
212                 if(cluster->IsInChamber()) slice = Int_t(TMath::Abs(fX0 - x) * nslices / clength);
213                 else slice = x < fX0 ? 0 : nslices-1;
214                 
215                 // 2. take sharing into account
216                 Float_t w = cluster->IsShared() ? .5 : 1.;
217                 
218                 // 3. take into account large clusters TODO
219                 //w *= c->GetNPads() > 3 ? .8 : 1.;
220                 
221                 //CHECK !!!
222                 fdEdx[slice]   += w * GetdQdl(ic); //fdQdl[ic];
223                 nclusters[slice]++;
224         } // End of loop over clusters
225
226         if(fReconstructor->GetPIDMethod() == AliTRDReconstructor::kLQPID){
227         // calculate mean charge per slice (only LQ PID)
228                 for(int is=0; is<nslices; is++){ 
229             if(nclusters[is]) fdEdx[is] /= nclusters[is];
230           }
231         }
232 }
233
234
235 //____________________________________________________________________
236 Float_t AliTRDseedV1::GetdQdl(Int_t ic) const
237 {
238         return fClusters[ic] ? TMath::Abs(fClusters[ic]->GetQ()) /fdX / TMath::Sqrt(1. + fYfit[1]*fYfit[1] + fZref[1]*fZref[1]) : 0.;
239 }
240
241 //____________________________________________________________________
242 Double_t* AliTRDseedV1::GetProbability()
243 {       
244 // Fill probability array for tracklet from the DB.
245 //
246 // Parameters
247 //
248 // Output
249 //   returns pointer to the probability array and 0x0 if missing DB access 
250 //
251 // Detailed description
252
253         
254         // retrive calibration db
255   AliTRDcalibDB *calibration = AliTRDcalibDB::Instance();
256   if (!calibration) {
257     AliError("No access to calibration data");
258     return 0x0;
259   }
260
261   if (!fReconstructor) {
262     AliError("Reconstructor not set.");
263     return 0x0;
264   }
265
266   // Retrieve the CDB container class with the parametric detector response
267   const AliTRDCalPID *pd = calibration->GetPIDObject(fReconstructor->GetPIDMethod());
268   if (!pd) {
269     AliError("No access to AliTRDCalPID object");
270     return 0x0;
271   }
272         //AliInfo(Form("Method[%d] : %s", fReconstructor->GetRecoParam() ->GetPIDMethod(), pd->IsA()->GetName()));
273
274         // calculate tracklet length TO DO
275   Float_t length = (AliTRDgeometry::AmThick() + AliTRDgeometry::DrThick());
276   /// TMath::Sqrt((1.0 - fSnp[iPlane]*fSnp[iPlane]) / (1.0 + fTgl[iPlane]*fTgl[iPlane]));
277   
278   //calculate dE/dx
279   CookdEdx(fReconstructor->GetNdEdxSlices());
280   
281   // Sets the a priori probabilities
282   for(int ispec=0; ispec<AliPID::kSPECIES; ispec++) {
283     fProb[ispec] = pd->GetProbability(ispec, fMom, &fdEdx[0], length, fPlane);  
284   }
285
286         return &fProb[0];
287 }
288
289 //____________________________________________________________________
290 Float_t AliTRDseedV1::GetQuality(Bool_t kZcorr) const
291 {
292   //
293   // Returns a quality measurement of the current seed
294   //
295
296         Float_t zcorr = kZcorr ? fTilt * (fZProb - fZref[0]) : 0.;
297         return 
298                   .5 * TMath::Abs(18.0 - fN2)
299                 + 10.* TMath::Abs(fYfit[1] - fYref[1])
300                 + 5. * TMath::Abs(fYfit[0] - fYref[0] + zcorr)
301                 + 2. * TMath::Abs(fMeanz - fZref[0]) / fPadLength;
302 }
303
304 //____________________________________________________________________
305 void AliTRDseedV1::GetCovAt(Double_t /*x*/, Double_t *cov) const
306 {
307 // Computes covariance in the y-z plane at radial point x
308
309         Int_t ic = 0; while (!fClusters[ic]) ic++; 
310   AliTRDcalibDB *fCalib = AliTRDcalibDB::Instance();
311         Double_t exB         = fCalib->GetOmegaTau(fCalib->GetVdriftAverage(fClusters[ic]->GetDetector()), -AliTracker::GetBz()*0.1);
312
313         Double_t sy2    = fSigmaY2*fSigmaY2 + .2*(fYfit[1]-exB)*(fYfit[1]-exB);
314         Double_t sz2    = fPadLength/12.;
315
316
317         //printf("Yfit[1] %f sy20 %f SigmaY2 %f\n", fYfit[1], sy20, fSigmaY2);
318
319         cov[0] = sy2;
320         cov[1] = fTilt*(sy2-sz2);
321         cov[2] = sz2;
322
323   // insert systematic uncertainties calibration and misalignment
324   Double_t sys[15];
325   fReconstructor->GetRecoParam()->GetSysCovMatrix(sys);
326   cov[0] += (sys[0]*sys[0]);
327   cov[2] += (sys[1]*sys[1]);
328 }
329
330
331 //____________________________________________________________________
332 void AliTRDseedV1::SetOwner(Bool_t own)
333 {
334         //AliInfo(Form("own [%s] fOwner[%s]", own?"YES":"NO", fOwner?"YES":"NO"));
335         
336         if(own){
337                 for(int ic=0; ic<knTimebins; ic++){
338                         if(!fClusters[ic]) continue;
339                         fClusters[ic] = new AliTRDcluster(*fClusters[ic]);
340                 }
341                 SetBit(1);
342         } else {
343                 if(IsOwner()){
344                         for(int ic=0; ic<knTimebins; ic++){
345                                 if(!fClusters[ic]) continue;
346                                 delete fClusters[ic];
347                                 //fClusters[ic] = tracker->GetClusters(index) TODO
348                         }
349                 }
350                 SetBit(1, kFALSE);
351         }
352 }
353
354 //____________________________________________________________________
355 Bool_t  AliTRDseedV1::AttachClustersIter(AliTRDtrackingChamber *chamber, Float_t quality, Bool_t kZcorr, AliTRDcluster *c)
356 {
357   //
358   // Iterative process to register clusters to the seed.
359   // In iteration 0 we try only one pad-row and if quality not
360   // sufficient we try 2 pad-rows (about 5% of tracks cross 2 pad-rows)
361   //
362         // debug level 7
363         //
364         
365         if(!fReconstructor->GetRecoParam() ){
366                 AliError("Seed can not be used without a valid RecoParam.");
367                 return kFALSE;
368         }
369
370         AliTRDchamberTimeBin *layer = 0x0;
371         if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7 && c){
372                 TClonesArray clusters("AliTRDcluster", 24);
373                 clusters.SetOwner(kTRUE);
374                 AliTRDcluster *cc = 0x0;
375                 Int_t det=-1, ncl, ncls = 0;
376                 for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
377                         if(!(layer = chamber->GetTB(iTime))) continue;
378                         if(!(ncl = Int_t(*layer))) continue;
379                         for(int ic=0; ic<ncl; ic++){ 
380                                 cc = (*layer)[ic];
381                                 det = cc->GetDetector();
382                                 new(clusters[ncls++]) AliTRDcluster(*cc);
383                         }
384                 }
385                 AliInfo(Form("N clusters[%d] = %d", fPlane, ncls));
386                 
387                 Int_t ref = c ? 1 : 0;
388                 TTreeSRedirector &cstreamer = *AliTRDtrackerV1::DebugStreamer();
389                 cstreamer << "AttachClustersIter"
390                         << "det="        << det 
391                         << "ref="        << ref 
392                         << "clusters.="  << &clusters
393                         << "tracklet.="  << this
394                         << "cl.="        << c
395                         << "\n";        
396         }
397
398         Float_t  tquality;
399         Double_t kroady = fReconstructor->GetRecoParam() ->GetRoad1y();
400         Double_t kroadz = fPadLength * .5 + 1.;
401         
402         // initialize configuration parameters
403         Float_t zcorr = kZcorr ? fTilt * (fZProb - fZref[0]) : 0.;
404         Int_t   niter = kZcorr ? 1 : 2;
405         
406         Double_t yexp, zexp;
407         Int_t ncl = 0;
408         // start seed update
409         for (Int_t iter = 0; iter < niter; iter++) {
410                 ncl = 0;
411                 for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
412                         if(!(layer = chamber->GetTB(iTime))) continue;
413                         if(!Int_t(*layer)) continue;
414                         
415                         // define searching configuration
416                         Double_t dxlayer = layer->GetX() - fX0;
417                         if(c){
418                                 zexp = c->GetZ();
419                                 //Try 2 pad-rows in second iteration
420                                 if (iter > 0) {
421                                         zexp = fZref[0] + fZref[1] * dxlayer - zcorr;
422                                         if (zexp > c->GetZ()) zexp = c->GetZ() + fPadLength*0.5;
423                                         if (zexp < c->GetZ()) zexp = c->GetZ() - fPadLength*0.5;
424                                 }
425                         } else zexp = fZref[0] + (kZcorr ? fZref[1] * dxlayer : 0.);
426                         yexp  = fYref[0] + fYref[1] * dxlayer - zcorr;
427                         
428                         // Get and register cluster
429                         Int_t    index = layer->SearchNearestCluster(yexp, zexp, kroady, kroadz);
430                         if (index < 0) continue;
431                         AliTRDcluster *cl = (*layer)[index];
432                         
433                         fIndexes[iTime]  = layer->GetGlobalIndex(index);
434                         fClusters[iTime] = cl;
435                         fY[iTime]        = cl->GetY();
436                         fZ[iTime]        = cl->GetZ();
437                         ncl++;
438                 }
439         if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7) AliInfo(Form("iter = %d ncl [%d] = %d", iter, fPlane, ncl));
440                 
441                 if(ncl>1){      
442                         // calculate length of the time bin (calibration aware)
443                         Int_t irp = 0; Float_t x[2]; Int_t tb[2];
444                         for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
445                                 if(!fClusters[iTime]) continue;
446                                 x[irp]  = fClusters[iTime]->GetX();
447                                 tb[irp] = iTime;
448                                 irp++;
449                                 if(irp==2) break;
450                         } 
451                         fdX = (x[1] - x[0]) / (tb[0] - tb[1]);
452         
453                         // update X0 from the clusters (calibration/alignment aware)
454                         for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
455                                 if(!(layer = chamber->GetTB(iTime))) continue;
456                                 if(!layer->IsT0()) continue;
457                                 if(fClusters[iTime]){ 
458                                         fX0 = fClusters[iTime]->GetX();
459                                         break;
460                                 } else { // we have to infere the position of the anode wire from the other clusters
461                                         for (Int_t jTime = iTime+1; jTime < AliTRDtrackerV1::GetNTimeBins(); jTime++) {
462                                                 if(!fClusters[jTime]) continue;
463                                                 fX0 = fClusters[jTime]->GetX() + fdX * (jTime - iTime);
464                                         }
465                                         break;
466                                 }
467                         }       
468                         
469                         // update YZ reference point
470                         // TODO
471                         
472                         // update x reference positions (calibration/alignment aware)
473                         for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
474                                 if(!fClusters[iTime]) continue;
475                                 fX[iTime] = fClusters[iTime]->GetX() - fX0;
476                         } 
477                         
478                         AliTRDseed::Update();
479                 }
480         if(fReconstructor->GetStreamLevel(AliTRDReconstructor::kTracker)>=7) AliInfo(Form("iter = %d nclFit [%d] = %d", iter, fPlane, fN2));
481                 
482                 if(IsOK()){
483                         tquality = GetQuality(kZcorr);
484                         if(tquality < quality) break;
485                         else quality = tquality;
486                 }
487                 kroadz *= 2.;
488         } // Loop: iter
489         if (!IsOK()) return kFALSE;
490
491         CookLabels();
492         UpdateUsed();
493         return kTRUE;   
494 }
495
496 //____________________________________________________________________
497 Bool_t  AliTRDseedV1::AttachClusters(AliTRDtrackingChamber *chamber
498                                        ,Bool_t kZcorr)
499 {
500   //
501   // Projective algorithm to attach clusters to seeding tracklets
502   //
503   // Parameters
504   //
505   // Output
506   //
507   // Detailed description
508   // 1. Collapse x coordinate for the full detector plane
509   // 2. truncated mean on y (r-phi) direction
510   // 3. purge clusters
511   // 4. truncated mean on z direction
512   // 5. purge clusters
513   // 6. fit tracklet
514   //    
515
516         if(!fReconstructor->GetRecoParam() ){
517                 AliError("Seed can not be used without a valid RecoParam.");
518                 return kFALSE;
519         }
520
521         const Int_t kClusterCandidates = 2 * knTimebins;
522         
523         //define roads
524         Double_t kroady = fReconstructor->GetRecoParam() ->GetRoad1y();
525         Double_t kroadz = fPadLength * 1.5 + 1.;
526         // correction to y for the tilting angle
527         Float_t zcorr = kZcorr ? fTilt * (fZProb - fZref[0]) : 0.;
528
529         // working variables
530         AliTRDcluster *clusters[kClusterCandidates];
531         Double_t cond[4], yexp[knTimebins], zexp[knTimebins],
532                 yres[kClusterCandidates], zres[kClusterCandidates];
533         Int_t ncl, *index = 0x0, tboundary[knTimebins];
534         
535         // Do cluster projection
536         AliTRDchamberTimeBin *layer = 0x0;
537         Int_t nYclusters = 0; Bool_t kEXIT = kFALSE;
538         for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
539                 if(!(layer = chamber->GetTB(iTime))) continue;
540                 if(!Int_t(*layer)) continue;
541                 
542                 fX[iTime] = layer->GetX() - fX0;
543                 zexp[iTime] = fZref[0] + fZref[1] * fX[iTime];
544                 yexp[iTime] = fYref[0] + fYref[1] * fX[iTime] - zcorr;
545                 
546                 // build condition and process clusters
547                 cond[0] = yexp[iTime] - kroady; cond[1] = yexp[iTime] + kroady;
548                 cond[2] = zexp[iTime] - kroadz; cond[3] = zexp[iTime] + kroadz;
549                 layer->GetClusters(cond, index, ncl);
550                 for(Int_t ic = 0; ic<ncl; ic++){
551                         AliTRDcluster *c = layer->GetCluster(index[ic]);
552                         clusters[nYclusters] = c;
553                         yres[nYclusters++] = c->GetY() - yexp[iTime];
554                         if(nYclusters >= kClusterCandidates) {
555                                 AliWarning(Form("Cluster candidates reached limit %d. Some may be lost.", kClusterCandidates));
556                                 kEXIT = kTRUE;
557                                 break;
558                         }
559                 }
560                 tboundary[iTime] = nYclusters;
561                 if(kEXIT) break;
562         }
563         
564         // Evaluate truncated mean on the y direction
565         Double_t mean, sigma;
566         AliMathBase::EvaluateUni(nYclusters, yres, mean, sigma, Int_t(nYclusters*.8)-2);
567         // purge cluster candidates
568         Int_t nZclusters = 0;
569         for(Int_t ic = 0; ic<nYclusters; ic++){
570                 if(yres[ic] - mean > 4. * sigma){
571                         clusters[ic] = 0x0;
572                         continue;
573                 }
574                 zres[nZclusters++] = clusters[ic]->GetZ() - zexp[clusters[ic]->GetLocalTimeBin()];
575         }
576         
577         // Evaluate truncated mean on the z direction
578         AliMathBase::EvaluateUni(nZclusters, zres, mean, sigma, Int_t(nZclusters*.8)-2);
579         // purge cluster candidates
580         for(Int_t ic = 0; ic<nZclusters; ic++){
581                 if(zres[ic] - mean > 4. * sigma){
582                         clusters[ic] = 0x0;
583                         continue;
584                 }
585         }
586
587         
588         // Select only one cluster/TimeBin
589         Int_t lastCluster = 0;
590         fN2 = 0;
591         for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
592                 ncl = tboundary[iTime] - lastCluster;
593                 if(!ncl) continue;
594                 Int_t iptr = lastCluster;
595                 if(ncl > 1){
596                         Float_t dold = 9999.;
597                         for(int ic=lastCluster; ic<tboundary[iTime]; ic++){
598                                 if(!clusters[ic]) continue;
599                                 Float_t y = yexp[iTime] - clusters[ic]->GetY();
600                                 Float_t z = zexp[iTime] - clusters[ic]->GetZ();
601                                 Float_t d = y * y + z * z;
602                                 if(d > dold) continue;
603                                 dold = d;
604                                 iptr = ic;
605                         }
606                 }
607                 fIndexes[iTime]  = chamber->GetTB(iTime)->GetGlobalIndex(iptr);
608                 fClusters[iTime] = clusters[iptr];
609                 fY[iTime]        = clusters[iptr]->GetY();
610                 fZ[iTime]        = clusters[iptr]->GetZ();
611                 lastCluster      = tboundary[iTime];
612                 fN2++;
613         }
614         
615         // number of minimum numbers of clusters expected for the tracklet
616         Int_t kClmin = Int_t(fReconstructor->GetRecoParam() ->GetFindableClusters()*AliTRDtrackerV1::GetNTimeBins());
617   if (fN2 < kClmin){
618                 AliWarning(Form("Not enough clusters to fit the tracklet %d [%d].", fN2, kClmin));
619     fN2 = 0;
620     return kFALSE;
621   }
622
623         // update used clusters
624         fNUsed = 0;
625         for (Int_t iTime = 0; iTime < AliTRDtrackerV1::GetNTimeBins(); iTime++) {
626                 if(!fClusters[iTime]) continue;
627                 if((fClusters[iTime]->IsUsed())) fNUsed++;
628         }
629
630   if (fN2-fNUsed < kClmin){
631                 AliWarning(Form("Too many clusters already in use %d (from %d).", fNUsed, fN2));
632     fN2 = 0;
633     return kFALSE;
634   }
635         
636         return kTRUE;
637 }
638
639 //____________________________________________________________________
640 Bool_t AliTRDseedV1::Fit()
641 {
642   //
643   // Linear fit of the tracklet
644   //
645   // Parameters :
646   //
647   // Output :
648   //  True if successful
649   //
650   // Detailed description
651   // 2. Check if tracklet crosses pad row boundary
652   // 1. Calculate residuals in the y (r-phi) direction
653   // 3. Do a Least Square Fit to the data
654   //
655
656         const Int_t kClmin = 8;
657         const Int_t kNtb = AliTRDtrackerV1::GetNTimeBins();
658         AliTRDtrackerV1::AliTRDLeastSquare fitterY, fitterZ;
659
660         // convertion factor from square to gauss distribution for sigma
661         Double_t convert = 1./TMath::Sqrt(12.);
662
663         // book cluster information
664         Double_t xc[knTimebins+1], yc[knTimebins], zc[knTimebins+1], sy[knTimebins], sz[knTimebins+1];
665         Int_t zRow[knTimebins];
666         AliTRDcluster *c = 0x0;
667         Int_t nc = 0;
668         for (Int_t ic=0; ic<kNtb; ic++) {
669                 zRow[ic] = -1;
670                 xc[ic]  = -1.;
671                 yc[ic]  = 999.;
672                 zc[ic]  = 999.;
673                 sy[ic]  = 0.;
674                 sz[ic]  = 0.;
675                 if(!(c = fClusters[ic])) continue;
676                 if(!c->IsInChamber()) continue;
677                 Float_t w = 1.;
678                 if(c->GetNPads()>4) w = .5;
679                 if(c->GetNPads()>5) w = .2;
680                 zRow[nc] = c->GetPadRow();
681                 xc[nc]   = fX0 - c->GetX();
682                 yc[nc]   = c->GetY();
683                 zc[nc]   = c->GetZ();
684                 sy[ic]   = w; // all clusters have the same sigma
685                 sz[ic]   = fPadLength*convert;
686                 fitterZ.AddPoint(&xc[ic], zc[ic], sz[ic]);
687                 nc++;
688         }
689   // to few clusters
690         if (nc < kClmin) return kFALSE; 
691         
692
693         Int_t zN[2*35];
694   Int_t nz = AliTRDtrackerV1::Freq(nc, zRow, zN, kFALSE);
695         // more than one pad row crossing
696         if(nz>2) return kFALSE; 
697         
698         // estimate reference parameter at average x
699         Double_t y0 = fYref[0];
700         Double_t dydx = fYref[1]; 
701         Double_t dzdx = fZref[1];
702         zc[nc]  = fZref[0];
703
704         // determine z offset of the fit
705         Int_t nchanges = 0, nCross = 0;
706         if(nz==2){ // tracklet is crossing pad row
707                 // Find the break time allowing one chage on pad-rows
708                 // with maximal number of accepted clusters
709                 Int_t padRef = zRow[0];
710                 for (Int_t ic=1; ic<nc; ic++) {
711                         if(zRow[ic] == padRef) continue;
712                         
713                         // debug
714                         if(zRow[ic-1] == zRow[ic]){
715                                 printf("ERROR in pad row change!!!\n");
716                         }
717                 
718                         // evaluate parameters of the crossing point
719                         Float_t sx = (xc[ic-1] - xc[ic])*convert;
720                         xc[nc] = .5 * (xc[ic-1] + xc[ic]);
721                         zc[nc] = .5 * (zc[ic-1] + zc[ic]);
722                         sz[nc] = TMath::Max(dzdx * sx, .01);
723                         dzdx   = zc[ic-1] > zc[ic] ? 1. : -1.;
724                         padRef = zRow[ic];
725                         nCross = ic;
726                         nchanges++;
727                 }
728         }
729
730         // condition on nCross and reset nchanges TODO
731
732         if(nchanges==1){
733                 if(dzdx * fZref[1] < 0.){
734                         AliInfo("tracklet direction does not correspond to the track direction. TODO.");
735                 }
736                 SetBit(2, kTRUE); // mark pad row crossing
737                 fCross[0] = xc[nc]; fCross[2] = zc[nc]; fCross[3] = sz[nc]; 
738                 fitterZ.AddPoint(&xc[nc], zc[nc], sz[nc]);
739                 fitterZ.Eval();
740                 dzdx = fZref[1]; // we don't trust Parameter[1] ??;
741                 zc[nc] = fitterZ.GetFunctionParameter(0); 
742         } else if(nchanges > 1){ // debug
743                 AliInfo("ERROR in n changes!!!");
744                 return kFALSE;
745         }
746
747         
748         // estimate deviation from reference direction
749         dzdx *= fTilt;
750         for (Int_t ic=0; ic<nc; ic++) {
751                 yc[ic] -= y0 + xc[ic]*(dydx + dzdx) + fTilt * (zc[ic] - zc[nc]);
752                 fitterY.AddPoint(&xc[ic], yc[ic], sy[ic]);
753         }
754         fitterY.Eval();
755         fYfit[0] = y0+fitterY.GetFunctionParameter(0);
756         fYfit[1] = dydx+fitterY.GetFunctionParameter(1);
757         if(nchanges) fCross[1] = fYfit[0] + fCross[0] * fYfit[1];
758
759 //      printf("\nnz = %d\n", nz);
760 //      for(int ic=0; ic<35; ic++) printf("%d row[%d]\n", ic, zRow[ic]);        
761 // 
762 //      for(int ic=0; ic<nz; ic++) printf("%d n[%d]\n", ic, zN[ic]);    
763
764         return kTRUE;
765 }
766
767 //___________________________________________________________________
768 void AliTRDseedV1::Draw(Option_t*)
769 {
770 }
771
772 //___________________________________________________________________
773 void AliTRDseedV1::Print(Option_t*) const
774 {
775   //
776   // Printing the seedstatus
777   //
778
779         printf("Seed status :\n");
780         printf("  fTilt      = %f\n", fTilt);
781         printf("  fPadLength = %f\n", fPadLength);
782         printf("  fX0        = %f\n", fX0);
783         for(int ic=0; ic<AliTRDtrackerV1::GetNTimeBins(); ic++) {
784           const Char_t *isUsable = fUsable[ic]?"Yes":"No";
785           printf("  %d X[%f] Y[%f] Z[%f] Indexes[%d] clusters[%p] usable[%s]\n"
786                 , ic
787                 , fX[ic]
788                 , fY[ic]
789                 , fZ[ic]
790                 , fIndexes[ic]
791                 , ((void*) fClusters[ic])
792                 , isUsable);
793         }
794
795         printf("  fYref[0] =%f fYref[1] =%f\n", fYref[0], fYref[1]);
796         printf("  fZref[0] =%f fZref[1] =%f\n", fZref[0], fZref[1]);
797         printf("  fYfit[0] =%f fYfit[1] =%f\n", fYfit[0], fYfit[1]);
798         printf("  fYfitR[0]=%f fYfitR[1]=%f\n", fYfitR[0], fYfitR[1]);
799         printf("  fZfit[0] =%f fZfit[1] =%f\n", fZfit[0], fZfit[1]);
800         printf("  fZfitR[0]=%f fZfitR[1]=%f\n", fZfitR[0], fZfitR[1]);
801         printf("  fSigmaY =%f\n", fSigmaY);
802         printf("  fSigmaY2=%f\n", fSigmaY2);            
803         printf("  fMeanz  =%f\n", fMeanz);
804         printf("  fZProb  =%f\n", fZProb);
805         printf("  fLabels[0]=%d fLabels[1]=%d\n", fLabels[0], fLabels[1]);
806         printf("  fN      =%d\n", fN);
807         printf("  fN2     =%d (>8 isOK)\n",fN2);
808         printf("  fNUsed  =%d\n", fNUsed);
809         printf("  fFreq   =%d\n", fFreq);
810         printf("  fNChange=%d\n",  fNChange);
811         printf("  fMPads  =%f\n", fMPads);
812         
813         printf("  fC      =%f\n", fC);        
814         printf("  fCC     =%f\n",fCC);      
815         printf("  fChi2   =%f\n", fChi2);  
816         printf("  fChi2Z  =%f\n", fChi2Z);
817 }
818