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