]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TPC/AliTPC.cxx
removed obsolete AliTPCDigitsDisplay.C
[u/mrichter/AliRoot.git] / TPC / AliTPC.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /*
17 $Log$
18 Revision 1.17.2.2  2000/04/10 08:15:12  kowal2
19
20 New, experimental data structure from M. Ivanov
21 New tracking algorithm
22 Different pad geometry for different sectors
23 Digitization rewritten
24
25 Revision 1.17.2.1  2000/04/10 07:56:53  kowal2
26 Not used anymore - removed
27
28 Revision 1.17  2000/01/19 17:17:30  fca
29 Introducing a list of lists of hits -- more hits allowed for detector now
30
31 Revision 1.16  1999/11/05 09:29:23  fca
32 Accept only signals > 0
33
34 Revision 1.15  1999/10/08 06:26:53  fca
35 Removed ClustersIndex - not used anymore
36
37 Revision 1.14  1999/09/29 09:24:33  fca
38 Introduction of the Copyright and cvs Log
39
40 */
41
42 ///////////////////////////////////////////////////////////////////////////////
43 //                                                                           //
44 //  Time Projection Chamber                                                  //
45 //  This class contains the basic functions for the Time Projection Chamber  //
46 //  detector. Functions specific to one particular geometry are              //
47 //  contained in the derived classes                                         //
48 //                                                                           //
49 //Begin_Html
50 /*
51 <img src="picts/AliTPCClass.gif">
52 */
53 //End_Html
54 //                                                                           //
55 //                                                                          //
56 ///////////////////////////////////////////////////////////////////////////////
57
58 #include <TMath.h>
59 #include <TRandom.h>
60 #include <TVector.h>
61 #include <TMatrix.h>
62 #include <TGeometry.h>
63 #include <TNode.h>
64 #include <TTUBS.h>
65 #include <TObjectTable.h>
66 #include "TParticle.h"
67 #include "AliTPC.h"
68 #include "AliRun.h"
69 #include <iostream.h>
70 #include <fstream.h>
71 #include "AliMC.h"
72
73
74 #include "AliTPCParam.h"
75 #include "AliTPCPRF2D.h"
76 #include "AliTPCRF1D.h"
77 #include "AliDigits.h"
78 #include "AliSimDigits.h"
79
80 #include "AliTPCDigitsArray.h"
81 #include "AliCluster.h"
82 #include "AliClusters.h"
83 #include "AliTPCClustersRow.h"
84 #include "AliTPCClustersArray.h"
85
86
87
88 ClassImp(AliTPC) 
89
90 //_____________________________________________________________________________
91 AliTPC::AliTPC()
92 {
93   //
94   // Default constructor
95   //
96   fIshunt   = 0;
97   fClusters = 0;
98   fHits     = 0;
99   fDigits   = 0;
100   fTracks   = 0;
101   fNsectors = 0;
102   fNtracks  = 0;
103   fNclusters= 0;
104   //MI changes
105   fDigitsArray = 0;
106   fClustersArray = 0;
107   fTPCParam = 0;
108 }
109  
110 //_____________________________________________________________________________
111 AliTPC::AliTPC(const char *name, const char *title)
112       : AliDetector(name,title)
113 {
114   //
115   // Standard constructor
116   //
117
118   //
119   // Initialise arrays of hits and digits 
120   fHits     = new TClonesArray("AliTPChit",  176);
121   //MI change  
122   fDigitsArray = 0;
123   fClustersArray= 0;
124   fTPCParam = 0;
125   //
126   // Initialise counters
127   fClusters = 0;
128   fTracks   = 0;
129   fNsectors = 0;
130   fNtracks  = 0;
131   fNclusters= 0;
132
133   //
134   fIshunt     =  0;
135   //
136   // Initialise color attributes
137   SetMarkerColor(kYellow);
138 }
139
140 //_____________________________________________________________________________
141 AliTPC::~AliTPC()
142 {
143   //
144   // TPC destructor
145   //
146   fIshunt   = 0;
147   delete fHits;
148   delete fDigits;
149   delete fClusters;
150   delete fTracks;
151   if (fDigitsArray!=0) delete fDigitsArray;
152   if (fClustersArray!=0) delete fClustersArray;
153
154   if (fTPCParam) delete fTPCParam;
155 }
156
157 //_____________________________________________________________________________
158 void AliTPC::AddCluster(Float_t *hits, Int_t *tracks)
159 {
160   //
161   // Add a simulated cluster to the list
162   //
163   if(!fClusters) fClusters=new TClonesArray("AliTPCcluster",10000);
164   TClonesArray &lclusters = *fClusters;
165   new(lclusters[fNclusters++]) AliTPCcluster(hits,tracks);
166 }
167  
168 //_____________________________________________________________________________
169 void AliTPC::AddCluster(const AliTPCcluster &c)
170 {
171   //
172   // Add a simulated cluster copy to the list
173   //
174   if(!fClusters) fClusters=new TClonesArray("AliTPCcluster",900000);
175   TClonesArray &lclusters = *fClusters;
176   new(lclusters[fNclusters++]) AliTPCcluster(c);
177 }
178  
179 //_____________________________________________________________________________
180 void AliTPC::AddHit(Int_t track, Int_t *vol, Float_t *hits)
181 {
182   //
183   // Add a hit to the list
184   //
185   TClonesArray &lhits = *fHits;
186   new(lhits[fNhits++]) AliTPChit(fIshunt,track,vol,hits);
187 }
188  
189 //_____________________________________________________________________________
190 void AliTPC::AddTrack(Float_t *hits)
191 {
192   //
193   // Add a track to the list of tracks
194   //
195   TClonesArray &ltracks = *fTracks;
196   new(ltracks[fNtracks++]) AliTPCtrack(hits);
197 }
198
199 //_____________________________________________________________________________
200 void AliTPC::AddTrack(const AliTPCtrack& t)
201 {
202   //
203   // Add a track copy to the list of tracks
204   //
205   if(!fTracks) fTracks=new TClonesArray("AliTPCtrack",10000);
206   TClonesArray &ltracks = *fTracks;
207   new(ltracks[fNtracks++]) AliTPCtrack(t);
208 }
209
210 //_____________________________________________________________________________
211 void AliTPC::BuildGeometry()
212 {
213
214   //
215   // Build TPC ROOT TNode geometry for the event display
216   //
217   TNode *Node, *Top;
218   TTUBS *tubs;
219   Int_t i;
220   const int kColorTPC=19;
221   char name[5], title[25];
222   const Double_t kDegrad=TMath::Pi()/180;
223   const Double_t kRaddeg=180./TMath::Pi();
224
225
226   Float_t InnerOpenAngle = fTPCParam->GetInnerAngle();
227   Float_t OuterOpenAngle = fTPCParam->GetOuterAngle();
228
229   Float_t InnerAngleShift = fTPCParam->GetInnerAngleShift();
230   Float_t OuterAngleShift = fTPCParam->GetOuterAngleShift();
231
232   Int_t nLo = fTPCParam->GetNInnerSector()/2;
233   Int_t nHi = fTPCParam->GetNOuterSector()/2;  
234
235   const Double_t loAng = (Double_t)TMath::Nint(InnerOpenAngle*kRaddeg);
236   const Double_t hiAng = (Double_t)TMath::Nint(OuterOpenAngle*kRaddeg);
237   const Double_t loAngSh = (Double_t)TMath::Nint(InnerAngleShift*kRaddeg);
238   const Double_t hiAngSh = (Double_t)TMath::Nint(OuterAngleShift*kRaddeg);  
239
240
241   const Double_t loCorr = 1/TMath::Cos(0.5*loAng*kDegrad);
242   const Double_t hiCorr = 1/TMath::Cos(0.5*hiAng*kDegrad);
243
244   Double_t rl,ru;
245   
246
247   //
248   // Get ALICE top node
249   //
250
251   Top=gAlice->GetGeometry()->GetNode("alice");
252
253   //  inner sectors
254
255   rl = fTPCParam->GetInnerRadiusLow();
256   ru = fTPCParam->GetInnerRadiusUp();
257  
258
259   for(i=0;i<nLo;i++) {
260     sprintf(name,"LS%2.2d",i);
261     name[4]='\0';
262     sprintf(title,"TPC low sector %3d",i);
263     title[24]='\0';
264     
265     tubs = new TTUBS(name,title,"void",rl*loCorr,ru*loCorr,250.,
266                      loAng*(i-0.5)+loAngSh,loAng*(i+0.5)+loAngSh);
267     tubs->SetNumberOfDivisions(1);
268     Top->cd();
269     Node = new TNode(name,title,name,0,0,0,"");
270     Node->SetLineColor(kColorTPC);
271     fNodes->Add(Node);
272   }
273
274   // Outer sectors
275
276   rl = fTPCParam->GetOuterRadiusLow();
277   ru = fTPCParam->GetOuterRadiusUp();
278
279   for(i=0;i<nHi;i++) {
280     sprintf(name,"US%2.2d",i);
281     name[4]='\0';
282     sprintf(title,"TPC upper sector %d",i);
283     title[24]='\0';
284     tubs = new TTUBS(name,title,"void",rl*hiCorr,ru*hiCorr,250,
285                      hiAng*(i-0.5)+hiAngSh,hiAng*(i+0.5)+hiAngSh);
286     tubs->SetNumberOfDivisions(1);
287     Top->cd();
288     Node = new TNode(name,title,name,0,0,0,"");
289     Node->SetLineColor(kColorTPC);
290     fNodes->Add(Node);
291   }
292
293
294 }  
295   
296   
297
298 //_____________________________________________________________________________
299 Int_t AliTPC::DistancetoPrimitive(Int_t , Int_t )
300 {
301   //
302   // Calculate distance from TPC to mouse on the display
303   // Dummy procedure
304   //
305   return 9999;
306 }
307
308 //_____________________________________________________________________________
309 static Double_t SigmaY2(Double_t r, Double_t tgl, Double_t pt)
310 {
311   //
312   // Parametrised error of the cluster reconstruction (pad direction)   
313   //
314   pt=TMath::Abs(pt)*1000.;
315   Double_t x=r/pt;
316   tgl=TMath::Abs(tgl);
317   Double_t s=a_rphi - b_rphi*r*tgl + c_rphi*x*x + d_rphi*x;
318   if (s<0.4e-3) s=0.4e-3;
319   s*=1.3; //Iouri Belikov
320   return s;
321 }
322
323 //_____________________________________________________________________________
324 static Double_t SigmaZ2(Double_t r, Double_t tgl) 
325 {
326   //
327   // Parametrised error of the cluster reconstruction (drift direction)
328   //
329   tgl=TMath::Abs(tgl);
330   Double_t s=a_z - b_z*r*tgl + c_z*tgl*tgl;
331   if (s<0.4e-3) s=0.4e-3;
332   s*=1.3; //Iouri Belikov
333   return s;
334 }
335
336 //_____________________________________________________________________________
337 inline Double_t f1(Double_t x1,Double_t y1,
338                    Double_t x2,Double_t y2,
339                    Double_t x3,Double_t y3) 
340 {
341   //-----------------------------------------------------------------
342   // Initial approximation of the track curvature
343   //
344   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
345   //-----------------------------------------------------------------
346   Double_t d=(x2-x1)*(y3-y2)-(x3-x2)*(y2-y1);
347   Double_t a=0.5*((y3-y2)*(y2*y2-y1*y1+x2*x2-x1*x1)-
348                   (y2-y1)*(y3*y3-y2*y2+x3*x3-x2*x2));
349   Double_t b=0.5*((x2-x1)*(y3*y3-y2*y2+x3*x3-x2*x2)-
350                   (x3-x2)*(y2*y2-y1*y1+x2*x2-x1*x1));
351
352   Double_t xr=TMath::Abs(d/(d*x1-a)), yr=d/(d*y1-b);
353
354   return -xr*yr/sqrt(xr*xr+yr*yr); 
355 }
356
357
358 //_____________________________________________________________________________
359 inline Double_t f2(Double_t x1,Double_t y1,
360                    Double_t x2,Double_t y2,
361                    Double_t x3,Double_t y3) 
362 {
363   //-----------------------------------------------------------------
364   // Initial approximation of the track curvature times center of curvature
365   //
366   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
367   //-----------------------------------------------------------------
368   Double_t d=(x2-x1)*(y3-y2)-(x3-x2)*(y2-y1);
369   Double_t a=0.5*((y3-y2)*(y2*y2-y1*y1+x2*x2-x1*x1)-
370                   (y2-y1)*(y3*y3-y2*y2+x3*x3-x2*x2));
371   Double_t b=0.5*((x2-x1)*(y3*y3-y2*y2+x3*x3-x2*x2)-
372                   (x3-x2)*(y2*y2-y1*y1+x2*x2-x1*x1));
373
374   Double_t xr=TMath::Abs(d/(d*x1-a)), yr=d/(d*y1-b);
375   
376   return -a/(d*y1-b)*xr/sqrt(xr*xr+yr*yr);
377 }
378
379 //_____________________________________________________________________________
380 inline Double_t f3(Double_t x1,Double_t y1, 
381                    Double_t x2,Double_t y2,
382                    Double_t z1,Double_t z2) 
383 {
384   //-----------------------------------------------------------------
385   // Initial approximation of the tangent of the track dip angle
386   //
387   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
388   //-----------------------------------------------------------------
389   return (z1 - z2)/sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
390 }
391
392 //_____________________________________________________________________________
393 static Int_t FindProlongation(AliTPCtrack& t, const AliTPCSector *sec,
394                             Int_t s, Int_t rf=0) 
395 {
396   //-----------------------------------------------------------------
397   // This function tries to find a track prolongation.
398   //
399   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
400   //-----------------------------------------------------------------
401   const Int_t ROWS_TO_SKIP=(t<10) ? 10 : Int_t(0.5*sec->GetNRows());
402   const Float_t MAX_CHI2=12.;
403   Int_t try_again=ROWS_TO_SKIP;
404   Double_t alpha=sec->GetAlpha();
405   Int_t ns=Int_t(2*TMath::Pi()/alpha+0.5);
406
407   for (Int_t nr=sec->GetRowNumber(t.GetX())-1; nr>=rf; nr--) {
408     Double_t x=sec->GetX(nr), ymax=sec->GetMaxY(nr);
409     if (!t.PropagateTo(x)) return 0;
410
411     AliTPCcluster *cl=0;
412     Double_t max_chi2=MAX_CHI2;
413     const AliTPCRow& row=sec[s][nr];
414     Double_t sy2=SigmaY2(t.GetX(),t.GetTgl(),t.GetPt());
415     Double_t sz2=SigmaZ2(t.GetX(),t.GetTgl());
416     Double_t road=5.*sqrt(t.GetSigmaY2() + sy2), y=t.GetY(), z=t.GetZ();
417
418     if (road>30) {
419       if (t>4) cerr<<t<<" FindProlongation warning: Too broad road !\n"; 
420       return 0;
421     }
422
423     if (row) {
424       for (Int_t i=row.Find(y-road); i<row; i++) {
425         AliTPCcluster* c=(AliTPCcluster*)(row[i]);
426         if (c->fY > y+road) break;
427         if (c->IsUsed()) continue;
428         if ((c->fZ - z)*(c->fZ - z) > 25.*(t.GetSigmaZ2() + sz2)) continue;
429         Double_t chi2=t.GetPredictedChi2(c);
430         if (chi2 > max_chi2) continue;
431         max_chi2=chi2;
432         cl=c;       
433       }
434     }
435     if (cl) {
436       t.Update(cl,max_chi2);
437       cl->fdEdX=sec->GetPadPitchWidth()*TMath::Sqrt((1+t.GetTgl()*t.GetTgl())/
438                (1-(t.GetC()*x-t.GetEta())*(t.GetC()*x-t.GetEta())));
439       try_again=ROWS_TO_SKIP;
440     } else {
441       if (try_again==0) break;
442       if (y > ymax) {
443          s = (s+1) % ns;
444          if (!t.Rotate(alpha)) return 0;
445       } else if (y <-ymax) {
446          s = (s-1+ns) % ns;
447          if (!t.Rotate(-alpha)) return 0;
448       }
449       try_again--;
450     }
451   }
452
453   return 1;
454
455 }
456
457
458 //_____________________________________________________________________________
459 static void MakeSeeds(TObjArray& seeds,const AliTPCSector *sec, Int_t max_sec,
460 Int_t i1, Int_t i2)
461 {
462   //-----------------------------------------------------------------
463   // This function creates track seeds.
464   //
465   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
466   //-----------------------------------------------------------------
467   TMatrix C(5,5); TVector x(5);
468   Double_t alpha=sec->GetAlpha(), shift=sec->GetAlphaShift();
469   Double_t cs=cos(alpha), sn=sin(alpha);
470   for (Int_t ns=0; ns<max_sec; ns++) {
471     Int_t nl=sec[(ns-1+max_sec)%max_sec][i2];
472     Int_t nm=sec[ns][i2];
473     Int_t nu=sec[(ns+1)%max_sec][i2];
474     const AliTPCRow& r1=sec[ns][i1];
475     for (Int_t is=0; is < r1; is++) {
476       Double_t x1=sec->GetX(i1), y1=r1[is]->fY, z1=r1[is]->fZ;
477       for (Int_t js=0; js < nl+nm+nu; js++) {
478         const AliTPCcluster *cl;
479         Int_t ks;
480         Double_t x2=sec->GetX(i2), y2, z2, tmp;
481
482         if (js<nl) {
483           ks=(ns-1+max_sec)%max_sec;
484           const AliTPCRow& r2=sec[(ns-1+max_sec)%max_sec][i2];
485           cl=r2[js];
486           y2=cl->fY; z2=cl->fZ;
487           tmp= x2*cs+y2*sn;
488           y2 =-x2*sn+y2*cs; x2=tmp;
489         } else 
490           if (js<nl+nm) {
491             ks=ns;
492             const AliTPCRow& r2=sec[ns][i2];
493             cl=r2[js-nl];
494             y2=cl->fY; z2=cl->fZ;
495           } else {
496             ks=(ns+1)%max_sec;
497             const AliTPCRow& r2=sec[(ns+1)%max_sec][i2];
498             cl=r2[js-nl-nm];
499             y2=cl->fY; z2=cl->fZ;
500             tmp=x2*cs-y2*sn;
501             y2 =x2*sn+y2*cs; x2=tmp;
502           }
503
504         Double_t zz=z1 - z1/x1*(x1-x2); 
505         if (TMath::Abs(zz-z2)>5) continue;
506
507         Double_t d=(x2-x1)*(0.-y2)-(0.-x2)*(y2-y1);
508         if (d==0.) {cerr<<"MakeSeeds warning: Straight seed !\n"; continue;}
509
510         Double_t x3=0., y3=0.;//gRandom->Gaus(0.,TMath::Sqrt(cl->fSigmaY2));
511
512         x(0)=y1;
513         x(1)=z1;
514         x(2)=f1(x1,y1,x2,y2,x3,y3);
515         x(3)=f2(x1,y1,x2,y2,x3,y3);
516         x(4)=f3(x1,y1,x2,y2,z1,z2);
517         
518         if (TMath::Abs(x(2)*x1-x(3)) >= 0.999) continue;
519         
520         if (TMath::Abs(x(4)) > 1.2) continue;
521
522         Double_t a=asin(x(3));
523         Double_t zv=z1 - x(4)/x(2)*(a+asin(x(2)*x1-x(3)));
524         if (TMath::Abs(zv)>10.) continue; 
525
526         TMatrix X(6,6); X=0.; 
527         X(0,0)=r1[is]->fSigmaY2; X(1,1)=r1[is]->fSigmaZ2;
528         X(2,2)=cl->fSigmaY2;     X(3,3)=cl->fSigmaZ2;
529         X(4,4)=cl->fSigmaY2;     X(5,5)=cl->fSigmaZ2;
530         //X(4,4)=3./12.; X(5,5)=3./12.;
531         TMatrix F(5,6); F.UnitMatrix();
532         Double_t sy=sqrt(X(0,0)), sz=sqrt(X(1,1));
533         F(2,0)=(f1(x1,y1+sy,x2,y2,x3,y3)-x(2))/sy;
534         F(2,2)=(f1(x1,y1,x2,y2+sy,x3,y3)-x(2))/sy;
535         F(2,4)=(f1(x1,y1,x2,y2,x3,y3+sy)-x(2))/sy;
536         F(3,0)=(f2(x1,y1+sy,x2,y2,x3,y3)-x(3))/sy;
537         F(3,2)=(f2(x1,y1,x2,y2+sy,x3,y3)-x(3))/sy;
538         F(3,4)=(f2(x1,y1,x2,y2,x3,y3+sy)-x(3))/sy;
539         F(4,0)=(f3(x1,y1+sy,x2,y2,z1,z2)-x(4))/sy;
540         F(4,1)=(f3(x1,y1,x2,y2,z1+sz,z2)-x(4))/sz;
541         F(4,2)=(f3(x1,y1,x2,y2+sy,z1,z2)-x(4))/sy;
542         F(4,3)=(f3(x1,y1,x2,y2,z1,z2+sz)-x(4))/sz;
543         F(4,4)=0;
544         F(3,3)=0;
545         
546         TMatrix t(F,TMatrix::kMult,X);
547         C.Mult(t,TMatrix(TMatrix::kTransposed,F));
548
549         AliTPCtrack *track=new AliTPCtrack(r1[is], x, C, x1, ns*alpha+shift);
550         Int_t rc=FindProlongation(*track,sec,ns,i2);
551         if (rc<0 || *track<(i1-i2)/2) delete track;
552         else seeds.AddLast(track); 
553       }
554     }
555   }
556 }
557
558 //_____________________________________________________________________________
559 AliTPCParam *AliTPCSector::param;
560 void AliTPC::Clusters2Tracks()
561 {
562   //-----------------------------------------------------------------
563   // This is a track finder.
564   //
565   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
566   //-----------------------------------------------------------------
567   if (!fClusters) return;
568
569   AliTPCParam *p=fTPCParam;
570   AliTPCSector::SetParam(p);
571
572   const Int_t nis=p->GetNInnerSector()/2;
573   AliTPCSSector *ssec=new AliTPCSSector[nis];         
574   Int_t nrow_low=ssec->GetNRows();     
575
576   const Int_t nos=p->GetNOuterSector()/2;
577   AliTPCLSector *lsec=new AliTPCLSector[nos];
578   Int_t nrow_up=lsec->GetNRows();
579
580   Int_t ncl=fClusters->GetEntriesFast();
581   while (ncl--) {
582     AliTPCcluster *c=(AliTPCcluster*)fClusters->UncheckedAt(ncl);
583     Int_t sec=c->fSector, row=c->fPadRow;
584
585     if (sec<nis*2) {
586       ssec[sec%nis][row].InsertCluster(c);
587     } else {
588       sec -= nis*2;
589       lsec[sec%nos][row].InsertCluster(c);
590     }
591   }
592   
593   TObjArray seeds(20000);
594
595   Int_t nrows=nrow_low+nrow_up;
596   Int_t gap=Int_t(0.125*nrows), shift=Int_t(0.5*gap);
597   MakeSeeds(seeds, lsec, nos, nrow_up-1, nrow_up-1-gap);
598   MakeSeeds(seeds, lsec, nos, nrow_up-1-shift, nrow_up-1-shift-gap);
599     
600   seeds.Sort();
601
602   Int_t found=0;
603   Int_t nseed=seeds.GetEntriesFast();
604
605   for (Int_t s=0; s<nseed; s++) {
606     AliTPCtrack *pt=(AliTPCtrack*)seeds.UncheckedAt(s), &t=*pt;
607     Double_t alpha=t.GetAlpha();
608     if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();  
609     if (alpha < 0.            ) alpha += 2.*TMath::Pi();  
610     Int_t ns=Int_t(alpha/lsec->GetAlpha())%nos;
611
612     if (!FindProlongation(t,lsec,ns)) continue;
613
614     alpha=t.GetAlpha() + 0.5*ssec->GetAlpha() - ssec->GetAlphaShift();
615     if (alpha > 2.*TMath::Pi()) alpha -= 2.*TMath::Pi();
616     if (alpha < 0.            ) alpha += 2.*TMath::Pi();
617     ns=Int_t(alpha/ssec->GetAlpha())%nis; //index of the inner sector needed
618
619     alpha=ns*ssec->GetAlpha() - t.GetAlpha();
620     if (!t.Rotate(alpha)) continue;
621     
622     if (!FindProlongation(t,ssec,ns)) continue;
623     
624     if (t >= Int_t(0.4*nrows)) {
625        AddTrack(t);
626        t.UseClusters();
627        cerr<<found++<<'\r';
628     }
629     delete pt; 
630   }  
631
632   delete[] ssec;
633   delete[] lsec;
634
635 }
636
637 //_____________________________________________________________________________
638 void AliTPC::CreateMaterials()
639 {
640   //-----------------------------------------------
641   // Create Materials for for TPC
642   //-----------------------------------------------
643
644   //-----------------------------------------------------------------
645   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
646   //-----------------------------------------------------------------
647
648   Int_t ISXFLD=gAlice->Field()->Integ();
649   Float_t SXMGMX=gAlice->Field()->Max();
650
651   Float_t amat[5]; // atomic numbers
652   Float_t zmat[5]; // z
653   Float_t wmat[5]; // proportions
654
655   Float_t density;
656
657   //  ********************* Gases *******************
658
659   //--------------------------------------------------------------
660   // pure gases
661   //--------------------------------------------------------------
662
663   // Ne
664
665
666   Float_t a_ne = 20.18;
667   Float_t z_ne = 10.;
668   
669   density = 0.0009;
670
671   AliMaterial(20,"Ne",a_ne,z_ne,density,999.,999.);
672
673   // Ar
674
675   Float_t a_ar = 39.948;
676   Float_t z_ar = 18.;
677
678   density = 0.001782;
679  
680   AliMaterial(21,"Ar",a_ar,z_ar,density,999.,999.);
681
682   Float_t a_pure[2];
683   
684   a_pure[0] = a_ne;
685   a_pure[1] = a_ar;
686   
687
688   //--------------------------------------------------------------
689   // gases - compounds
690   //--------------------------------------------------------------
691
692   Float_t amol[3];
693
694   //  CO2
695
696   amat[0]=12.011;
697   amat[1]=15.9994;
698
699   zmat[0]=6.;
700   zmat[1]=8.;
701
702   wmat[0]=1.;
703   wmat[1]=2.;
704
705   density=0.001977;
706
707   amol[0] = amat[0]*wmat[0]+amat[1]*wmat[1];
708
709   AliMixture(10,"CO2",amat,zmat,density,-2,wmat);
710
711   // CF4
712
713   amat[0]=12.011;
714   amat[1]=18.998;
715
716   zmat[0]=6.;
717   zmat[1]=9.;
718  
719   wmat[0]=1.;
720   wmat[1]=4.;
721  
722   density=0.003034;
723
724   amol[1] = amat[0]*wmat[0]+amat[1]*wmat[1];
725
726   AliMixture(11,"CF4",amat,zmat,density,-2,wmat); 
727
728   // CH4
729
730   amat[0]=12.011;
731   amat[1]=1.;
732
733   zmat[0]=6.;
734   zmat[1]=1.;
735
736   wmat[0]=1.;
737   wmat[1]=4.;
738
739   density=0.000717;
740
741   amol[2] = amat[0]*wmat[0]+amat[1]*wmat[1];
742
743   AliMixture(12,"CH4",amat,zmat,density,-2,wmat);
744
745   //----------------------------------------------------------------
746   // gases - mixtures, ID >= 20 pure gases, <= 10 ID < 20 -compounds
747   //----------------------------------------------------------------
748  
749   char namate[21];
750  
751   density = 0.;
752   Float_t am=0;
753   Int_t nc;
754
755   Float_t a,z,rho,absl,X0,buf[1];
756   Int_t nbuf;
757
758   for(nc = 0;nc<fNoComp;nc++)
759     {
760     
761       // retrive material constants
762       
763       gMC->Gfmate((*fIdmate)[fMixtComp[nc]],namate,a,z,rho,X0,absl,buf,nbuf);
764
765       amat[nc] = a;
766       zmat[nc] = z;
767
768       Int_t nnc = (fMixtComp[nc]>=20) ? fMixtComp[nc]%20 : fMixtComp[nc]%10;
769  
770       am += fMixtProp[nc]*((fMixtComp[nc]>=20) ? a_pure[nnc] : amol[nnc]); 
771       density += fMixtProp[nc]*rho;  // density of the mixture
772       
773     }
774
775   // mixture proportions by weight!
776
777   for(nc = 0;nc<fNoComp;nc++)
778     {
779
780       Int_t nnc = (fMixtComp[nc]>=20) ? fMixtComp[nc]%20 : fMixtComp[nc]%10;
781
782       wmat[nc] = fMixtProp[nc]*((fMixtComp[nc]>=20) ? a_pure[nnc] : amol[nnc])/am;
783
784     }  
785   
786   AliMixture(31,"Drift gas 1",amat,zmat,density,fNoComp,wmat);
787   AliMixture(32,"Drift gas 2",amat,zmat,density,fNoComp,wmat);
788   AliMixture(33,"Drift gas 3",amat,zmat,density,fNoComp,wmat); 
789
790   AliMedium(2, "Drift gas 1", 31, 0, ISXFLD, SXMGMX, 10., 999.,.1, .001, .001);
791   AliMedium(3, "Drift gas 2", 32, 0, ISXFLD, SXMGMX, 10., 999.,.1, .001, .001);
792   AliMedium(4, "Drift gas 3", 33, 1, ISXFLD, SXMGMX, 10., 999.,.1, .001, .001);
793
794   // Air 
795
796   AliMaterial(24, "Air", 14.61, 7.3, .001205, 30420., 67500.);
797
798   AliMedium(24, "Air", 24, 0, ISXFLD, SXMGMX, 10., .1, .1, .1, .1);
799
800   //----------------------------------------------------------------------
801   //               solid materials
802   //----------------------------------------------------------------------
803
804   // Al
805
806   AliMaterial(30, "Al", 26.98, 13., 2.7, 8.9, 37.2);
807
808   AliMedium(0, "Al",30, 0, ISXFLD, SXMGMX, 10., .1, .1, .1,   .1);
809
810   // Si
811
812   AliMaterial(31, "Si", 28.086, 14.,2.33, 9.36, 999.);
813
814   AliMedium(7, "Al",31, 0, ISXFLD, SXMGMX, 10., .1, .1, .1,   .1);
815   
816
817   // Mylar C5H4O2
818
819   amat[0]=12.011;
820   amat[1]=1.;
821   amat[2]=15.9994;
822
823   zmat[0]=6.;
824   zmat[1]=1.;
825   zmat[2]=8.;
826
827   wmat[0]=5.;
828   wmat[1]=4.;
829   wmat[2]=2.; 
830
831   density = 1.39;
832   
833   AliMixture(32, "Mylar",amat,zmat,density,-3,wmat);
834
835   AliMedium(5, "Mylar",32, 0, ISXFLD, SXMGMX, 10., .1, .1, .001, .01);
836
837
838
839
840   // Carbon (normal)
841
842   AliMaterial(33,"C normal",12.011,6.,2.265,18.8,999.);
843
844   AliMedium(6,"C normal",33,0, ISXFLD, SXMGMX, 10., .1, .1, .001, .01);
845
846   // G10 for inner and outr field cage
847   // G10 is 60% SiO2 + 40% epoxy, right now I use A and Z for SiO2
848
849   Float_t rhoFactor;
850
851   amat[0]=28.086;
852   amat[1]=15.9994;
853
854   zmat[0]=14.;
855   zmat[1]=8.;
856
857   wmat[0]=1.;
858   wmat[1]=2.;
859
860   density = 1.7;
861   
862
863   AliMixture(34,"G10 aux.",amat,zmat,density,-2,wmat);
864
865
866   gMC->Gfmate((*fIdmate)[34],namate,a,z,rho,X0,absl,buf,nbuf);
867
868   Float_t thickX0 = 0.0052; // field cage in X0 units
869   
870   Float_t thick = 2.; // in cm
871
872   X0=19.4; // G10 
873
874   rhoFactor = X0*thickX0/thick;
875   density = rho*rhoFactor;
876
877   AliMaterial(35,"G10-fc",a,z,density,999.,999.);
878
879   AliMedium(8,"G10-fc",35,0, ISXFLD, SXMGMX, 10., .1, .1, .001, .01);
880
881   thickX0 = 0.0027; // inner vessel (eta <0.9)
882   thick=0.5;
883   rhoFactor = X0*thickX0/thick;
884   density = rho*rhoFactor;
885
886   AliMaterial(36,"G10-iv",a,z,density,999.,999.);  
887
888   AliMedium(9,"G10-iv",36,0, ISXFLD, SXMGMX, 10., .1, .1, .001, .01);
889
890   //  Carbon fibre  
891   
892   gMC->Gfmate((*fIdmate)[33],namate,a,z,rho,X0,absl,buf,nbuf);
893
894   thickX0 = 0.0133; // outer vessel
895   thick=3.0;
896   rhoFactor = X0*thickX0/thick;
897   density = rho*rhoFactor;
898
899
900   AliMaterial(37,"C-ov",a,z,density,999.,999.);
901
902   AliMedium(10,"C-ov",37,0, ISXFLD, SXMGMX, 10., .1, .1, .001, .01);  
903
904   thickX0=0.015; // inner vessel (cone, eta > 0.9)
905   thick=1.5;
906   rhoFactor = X0*thickX0/thick;
907   density = rho*rhoFactor;
908
909   AliMaterial(38,"C-ivc",a,z,density,999.,999.);
910
911   AliMedium(11,"C-ivc",38,0, ISXFLD, SXMGMX, 10., .1, .1, .001, .01);
912
913   //
914
915   AliMedium(12,"CO2",10,0, ISXFLD, SXMGMX, 10., 999.,.1, .001, .001);
916     
917 }
918
919 //_____________________________________________________________________________
920 struct Bin {
921    UShort_t q;
922    UInt_t mask;
923    Bin();
924 };
925 Bin::Bin() {q=0; mask=0xFFFFFFFE;}
926
927 struct Peak {
928    Int_t k;
929    UInt_t mask;
930 };
931 inline Bool_t IsMaximum(Int_t k, Int_t max, const Bin *bins) {
932   UShort_t q=bins[k].q;
933   if (q==1023) return kFALSE;
934   if (bins[k-max].q > q) return kFALSE;
935   if (bins[k-1  ].q > q) return kFALSE; 
936   if (bins[k+max].q > q) return kFALSE; 
937   if (bins[k+1  ].q > q) return kFALSE; 
938   if (bins[k-max-1].q > q) return kFALSE;
939   if (bins[k+max-1].q > q) return kFALSE; 
940   if (bins[k+max+1].q > q) return kFALSE; 
941   if (bins[k-max+1].q > q) return kFALSE;
942   return kTRUE; 
943 }
944 static void FindPeaks(Int_t k, Int_t max, Bin *bins, Peak *peaks, Int_t& n) {
945 //if (n>=31) return;
946   if (n<31)
947   if (IsMaximum(k,max,bins)) {
948     peaks[n].k=k; peaks[n].mask=(2<<n);
949     n++;
950   }
951   bins[k].mask=0;
952   if (bins[k-max].mask&1) FindPeaks(k-max,max,bins,peaks,n);
953   if (bins[k-1  ].mask&1) FindPeaks(k-1  ,max,bins,peaks,n);
954   if (bins[k+max].mask&1) FindPeaks(k+max,max,bins,peaks,n);
955   if (bins[k+1  ].mask&1) FindPeaks(k+1  ,max,bins,peaks,n);
956 }
957
958 static void MarkPeak(Int_t k, Int_t max, Bin *bins, UInt_t m) {
959   UShort_t q=bins[k].q;
960
961   bins[k].mask |= m; 
962
963   if (bins[k-max].q <= q)
964      if ((bins[k-max].mask&m) == 0) MarkPeak(k-max,max,bins,m);
965   if (bins[k-1  ].q <= q)
966      if ((bins[k-1  ].mask&m) == 0) MarkPeak(k-1  ,max,bins,m);
967   if (bins[k+max].q <= q)
968      if ((bins[k+max].mask&m) == 0) MarkPeak(k+max,max,bins,m);
969   if (bins[k+1  ].q <= q)
970      if ((bins[k+1  ].mask&m) == 0) MarkPeak(k+1  ,max,bins,m);
971 }
972
973 static void MakeCluster(Int_t k,Int_t max,Bin *bins,UInt_t m,AliTPCcluster &c){
974   Float_t q=(Float_t)bins[k].q;
975   Int_t i=k/max, j=k-i*max;
976   c.fY += i*q;
977   c.fZ += j*q;
978   c.fSigmaY2 += i*i*q;
979   c.fSigmaZ2 += j*j*q;
980   c.fQ += q;
981
982   bins[k].mask = 0xFFFFFFFE;
983   
984   if (bins[k-max].mask == m) MakeCluster(k-max,max,bins,m,c);
985   if (bins[k-1  ].mask == m) MakeCluster(k-1  ,max,bins,m,c);
986   if (bins[k+max].mask == m) MakeCluster(k+max,max,bins,m,c);
987   if (bins[k+1  ].mask == m) MakeCluster(k+1  ,max,bins,m,c);
988 }
989
990 //_____________________________________________________________________________
991 void AliTPC::Digits2Clusters()
992 {
993   //-----------------------------------------------------------------
994   // This is a simple cluster finder.
995   //
996   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
997   //-----------------------------------------------------------------
998   AliTPCParam *par = fTPCParam;
999   const Int_t MAXZ=par->GetMaxTBin()+2;
1000
1001   TTree *t = (TTree *)gDirectory->Get("TreeD_75x40_100x60");
1002   AliSimDigits digarr, *dummy=&digarr;
1003   t->GetBranch("Segment")->SetAddress(&dummy);
1004   Stat_t sectors_by_rows = t->GetEntries();
1005   for (Int_t n=0; n<sectors_by_rows; n++) {
1006     t->GetEvent(n);
1007     Int_t sec, row;
1008     if (!par->AdjustSectorRow(digarr.GetID(),sec,row)) {
1009        cerr<<"AliTPC warning: invalid segment ID ! "<<digarr.GetID()<<endl;
1010        continue;
1011     }
1012
1013     Float_t rx=par->GetPadRowRadii(sec,row);
1014
1015     Int_t npads, sign;
1016     {
1017        Int_t nis=par->GetNInnerSector(), nos=par->GetNOuterSector();
1018        if (sec < nis) {
1019           npads = par->GetNPadsLow(row);
1020           sign = (sec < nis/2) ? 1 : -1;
1021        } else {
1022           npads = par->GetNPadsUp(row);
1023           sign = ((sec-nis) < nos/2) ? 1 : -1;
1024        }
1025     }
1026
1027     const Int_t MAXBIN=MAXZ*(npads+2);
1028     Bin *bins=new Bin[MAXBIN];
1029
1030     digarr.First();
1031     do {
1032        Short_t dig=digarr.CurrentDigit();
1033        if (dig<=par->GetZeroSup()) continue;
1034        Int_t j=digarr.CurrentRow()+1, i=digarr.CurrentColumn()+1;
1035        bins[i*MAXZ+j].q=dig;
1036        bins[i*MAXZ+j].mask=1;
1037     } while (digarr.Next());
1038
1039     Int_t ncl=0;
1040     for (Int_t i=0; i<MAXBIN; i++) {
1041       if ((bins[i].mask&1) == 0) continue;
1042       Peak peaks[32]; Int_t npeaks=0;
1043       FindPeaks(i, MAXZ, bins, peaks, npeaks);
1044
1045       if (npeaks>30) continue;
1046
1047       Int_t k,l;
1048       for (k=0; k<npeaks-1; k++){//mark adjacent peaks
1049         if (peaks[k].k < 0) continue; //this peak is already removed
1050         for (l=k+1; l<npeaks; l++) {
1051            if (peaks[l].k < 0) continue; //this peak is already removed
1052            Int_t ki=peaks[k].k/MAXZ, kj=peaks[k].k - ki*MAXZ;
1053            Int_t li=peaks[l].k/MAXZ, lj=peaks[l].k - li*MAXZ;
1054            Int_t di=TMath::Abs(ki - li);
1055            Int_t dj=TMath::Abs(kj - lj);
1056            if (di>1 || dj>1) continue;
1057            if (bins[peaks[k].k].q > bins[peaks[l].k].q) {
1058               peaks[l].mask=peaks[k].mask;
1059               peaks[l].k*=-1;
1060            } else {
1061               peaks[k].mask=peaks[l].mask;
1062               peaks[k].k*=-1;
1063               break;
1064            } 
1065         }
1066       }
1067
1068       for (k=0; k<npeaks; k++) {
1069         MarkPeak(TMath::Abs(peaks[k].k), MAXZ, bins, peaks[k].mask);
1070       }
1071         
1072       for (k=0; k<npeaks; k++) {
1073          if (peaks[k].k < 0) continue; //removed peak
1074          AliTPCcluster c;
1075          MakeCluster(peaks[k].k, MAXZ, bins, peaks[k].mask, c);
1076          if (c.fQ < 5) continue; //noise cluster
1077          c.fY /= c.fQ;
1078          c.fZ /= c.fQ;
1079
1080          Double_t s2 = c.fSigmaY2/c.fQ - c.fY*c.fY;
1081          c.fSigmaY2 = s2 + 1./12.;
1082          c.fSigmaY2 *= par->GetPadPitchWidth(sec)*par->GetPadPitchWidth(sec);
1083          if (s2 != 0.) {
1084             c.fSigmaY2 *= 0.064*1.3*1.3;
1085             if (sec<par->GetNInnerSector()) c.fSigmaY2 *= 1.44*1.44;
1086          }
1087
1088          s2 = c.fSigmaZ2/c.fQ - c.fZ*c.fZ;
1089          c.fSigmaZ2 = s2 + 1./12.;
1090          c.fSigmaZ2 *= par->GetZWidth()*par->GetZWidth();
1091          if (s2 != 0.) {
1092             c.fSigmaZ2 *= 0.10*1.3*1.3;
1093             if (sec<par->GetNInnerSector()) c.fSigmaZ2 *= 1.33*1.33;
1094          }
1095
1096          c.fY = (c.fY - 0.5 - 0.5*npads)*par->GetPadPitchWidth(sec);
1097          c.fZ = par->GetZWidth()*(c.fZ-1); 
1098          c.fZ -= 3.*par->GetZSigma(); // PASA delay 
1099          c.fZ = sign*(z_end - c.fZ);
1100
1101          if (rx<230./250.*TMath::Abs(c.fZ)) continue;
1102
1103          c.fSector=sec;
1104          c.fPadRow=row;
1105          Int_t ki=peaks[k].k/MAXZ, kj=peaks[k].k - ki*MAXZ;
1106          c.fTracks[0]=digarr.GetTrackID(kj-1,ki-1,0);
1107          c.fTracks[1]=digarr.GetTrackID(kj-1,ki-1,1);
1108          c.fTracks[2]=digarr.GetTrackID(kj-1,ki-1,2);
1109
1110          c.fQ=bins[peaks[k].k].q;
1111
1112          if (ki==1 || ki==npads || kj==1 || kj==MAXZ-2) {
1113            c.fSigmaY2 *= 25.;
1114            c.fSigmaZ2 *= 4.;
1115          }
1116
1117          AddCluster(c); ncl++;
1118       }
1119     }
1120
1121     cerr<<"sector, row, compressed digits, clusters: "
1122     <<sec<<' '<<row<<' '<<digarr.GetSize()<<' '<<ncl<<"                  \r";
1123         
1124     delete[] bins;  
1125   }
1126 }
1127
1128 //_____________________________________________________________________________
1129 void AliTPC::Hits2Clusters()
1130 {
1131   //--------------------------------------------------------
1132   // TPC simple cluster generator from hits
1133   // obtained from the TPC Fast Simulator
1134   // The point errors are taken from the parametrization
1135   //--------------------------------------------------------
1136
1137   //-----------------------------------------------------------------
1138   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1139   //-----------------------------------------------------------------
1140
1141    if(fTPCParam == 0){
1142      printf("AliTPCParam MUST be created firstly\n");
1143      return;
1144    }
1145
1146   Float_t sigma_rphi,sigma_z,cl_rphi,cl_z;
1147   //
1148   TParticle *particle; // pointer to a given particle
1149   AliTPChit *tpcHit; // pointer to a sigle TPC hit
1150   TClonesArray *Particles; //pointer to the particle list
1151   Int_t sector,nhits;
1152   Int_t ipart;
1153   Float_t xyz[5];
1154   Float_t pl,pt,tanth,rpad,ratio;
1155   Float_t cph,sph;
1156   
1157   //---------------------------------------------------------------
1158   //  Get the access to the tracks 
1159   //---------------------------------------------------------------
1160   
1161   TTree *TH = gAlice->TreeH();
1162   Stat_t ntracks = TH->GetEntries();
1163   
1164   //------------------------------------------------------------
1165   // Loop over all sectors (72 sectors for 20 deg
1166   // segmentation for both lower and upper sectors)
1167   // Sectors 0-35 are lower sectors, 0-17 z>0, 17-35 z<0
1168   // Sectors 36-71 are upper sectors, 36-53 z>0, 54-71 z<0
1169   //
1170   // First cluster for sector 0 starts at "0"
1171   //------------------------------------------------------------
1172    
1173   for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++){
1174     //MI change
1175     fTPCParam->AdjustCosSin(isec,cph,sph);
1176     
1177     //------------------------------------------------------------
1178     // Loop over tracks
1179     //------------------------------------------------------------
1180     
1181     for(Int_t track=0;track<ntracks;track++){
1182       ResetHits();
1183       TH->GetEvent(track);
1184       //
1185       //  Get number of the TPC hits and a pointer
1186       //  to the particles
1187       //
1188       nhits=fHits->GetEntriesFast();
1189       Particles=gAlice->Particles();
1190       //
1191       // Loop over hits
1192       //
1193       for(Int_t hit=0;hit<nhits;hit++){
1194         tpcHit=(AliTPChit*)fHits->UncheckedAt(hit);
1195         if (tpcHit->fQ == 0.) continue; //information about track (I.Belikov)
1196         sector=tpcHit->fSector; // sector number
1197         if(sector != isec) continue; //terminate iteration
1198         ipart=tpcHit->fTrack;
1199         particle=(TParticle*)Particles->UncheckedAt(ipart);
1200         pl=particle->Pz();
1201         pt=particle->Pt();
1202         if(pt < 1.e-9) pt=1.e-9;
1203         tanth=pl/pt;
1204         tanth = TMath::Abs(tanth);
1205         rpad=TMath::Sqrt(tpcHit->fX*tpcHit->fX + tpcHit->fY*tpcHit->fY);
1206         ratio=0.001*rpad/pt; // pt must be in MeV/c - historical reason
1207         
1208         //   space-point resolutions
1209         
1210         sigma_rphi=SigmaY2(rpad,tanth,pt);
1211         sigma_z   =SigmaZ2(rpad,tanth   );
1212         
1213         //   cluster widths
1214         
1215         cl_rphi=ac_rphi-bc_rphi*rpad*tanth+cc_rphi*ratio*ratio;
1216         cl_z=ac_z-bc_z*rpad*tanth+cc_z*tanth*tanth;
1217         
1218         // temporary protection
1219         
1220         if(sigma_rphi < 0.) sigma_rphi=0.4e-3;
1221         if(sigma_z < 0.) sigma_z=0.4e-3;
1222         if(cl_rphi < 0.) cl_rphi=2.5e-3;
1223         if(cl_z < 0.) cl_z=2.5e-5;
1224         
1225         //
1226         
1227         //
1228         // smearing --> rotate to the 1 (13) or to the 25 (49) sector,
1229         // then the inaccuracy in a X-Y plane is only along Y (pad row)!
1230         //
1231         //Float_t xprim= tpcHit->fX*cph + tpcHit->fY*sph;
1232         Float_t yprim=-tpcHit->fX*sph + tpcHit->fY*cph;
1233         xyz[0]=gRandom->Gaus(yprim,TMath::Sqrt(sigma_rphi));   // y
1234         xyz[1]=gRandom->Gaus(tpcHit->fZ,TMath::Sqrt(sigma_z)); // z 
1235         xyz[2]=tpcHit->fQ;                                     // q
1236         xyz[3]=sigma_rphi;                                     // fSigmaY2
1237         xyz[4]=sigma_z;                                        // fSigmaZ2
1238         
1239         Int_t tracks[5]={tpcHit->fTrack, -1, -1, sector, tpcHit->fPadRow};
1240         AddCluster(xyz,tracks);
1241         
1242       } // end of loop over hits
1243     }   // end of loop over tracks     
1244     
1245   } // end of loop over sectors  
1246   
1247 } // end of function
1248
1249 //_________________________________________________________________
1250 void AliTPC::Hits2ExactClustersSector(Int_t isec)
1251 {
1252   //--------------------------------------------------------
1253   //calculate exact cross point of track and given pad row
1254   //resulting values are expressed in "digit" coordinata
1255   //--------------------------------------------------------
1256
1257   //-----------------------------------------------------------------
1258   // Origin: Marian Ivanov  GSI Darmstadt, m.ivanov@gsi.de
1259   //-----------------------------------------------------------------
1260   //
1261   if (fClustersArray==0){    
1262     return;
1263   }
1264   //
1265   TParticle *particle; // pointer to a given particle
1266   AliTPChit *tpcHit; // pointer to a sigle TPC hit
1267   TClonesArray *Particles; //pointer to the particle list
1268   Int_t sector,nhits;
1269   Int_t ipart;
1270   const Int_t cmaxhits=30000;
1271   TVector * xxxx = new TVector(cmaxhits*4);
1272   TVector & xxx = *xxxx;
1273   Int_t maxhits = cmaxhits;
1274   //construct array for each padrow
1275   for (Int_t i=0; i<fTPCParam->GetNRow(isec);i++) 
1276     fClustersArray->CreateRow(isec,i);
1277   
1278   //---------------------------------------------------------------
1279   //  Get the access to the tracks 
1280   //---------------------------------------------------------------
1281   
1282   TTree *TH = gAlice->TreeH();
1283   Stat_t ntracks = TH->GetEntries();
1284   Particles=gAlice->Particles();
1285   Int_t npart = Particles->GetEntriesFast();
1286     
1287   //------------------------------------------------------------
1288   // Loop over tracks
1289   //------------------------------------------------------------
1290   
1291   for(Int_t track=0;track<ntracks;track++){
1292     ResetHits();
1293     TH->GetEvent(track);
1294     //
1295     //  Get number of the TPC hits and a pointer
1296     //  to the particles
1297     //
1298     nhits=fHits->GetEntriesFast();
1299     //
1300     // Loop over hits
1301     //
1302     Int_t currentIndex=0;
1303     Int_t lastrow=-1;  //last writen row
1304     for(Int_t hit=0;hit<nhits;hit++){
1305       tpcHit=(AliTPChit*)fHits->UncheckedAt(hit);
1306       if (tpcHit==0) continue;
1307       sector=tpcHit->fSector; // sector number
1308       if(sector != isec) continue; 
1309       ipart=tpcHit->fTrack;
1310       if (ipart<npart) particle=(TParticle*)Particles->UncheckedAt(ipart);
1311       
1312       //find row number
1313
1314       Float_t  x[3]={tpcHit->fX,tpcHit->fY,tpcHit->fZ};
1315       Int_t    index[3]={1,isec,0};
1316       Int_t    currentrow = fTPCParam->GetPadRow(x,index) ;     
1317       if (currentrow<0) continue;
1318       if (lastrow<0) lastrow=currentrow;
1319       if (currentrow==lastrow){
1320         if ( currentIndex>=maxhits){
1321           maxhits+=cmaxhits;
1322           xxx.ResizeTo(4*maxhits);
1323         }     
1324         xxx(currentIndex*4)=x[0];
1325         xxx(currentIndex*4+1)=x[1];
1326         xxx(currentIndex*4+2)=x[2];     
1327         xxx(currentIndex*4+3)=tpcHit->fQ;
1328         currentIndex++; 
1329       }
1330       else 
1331         if (currentIndex>2){
1332           Float_t sumx=0;
1333           Float_t sumx2=0;
1334           Float_t sumx3=0;
1335           Float_t sumx4=0;
1336           Float_t sumy=0;
1337           Float_t sumxy=0;
1338           Float_t sumx2y=0;
1339           Float_t sumz=0;
1340           Float_t sumxz=0;
1341           Float_t sumx2z=0;
1342           Float_t sumq=0;
1343           for (Int_t index=0;index<currentIndex;index++){
1344             Float_t x,x2,x3,x4;
1345             x=x2=x3=x4=xxx(index*4);
1346             x2*=x;
1347             x3*=x2;
1348             x4*=x3;
1349             sumx+=x;
1350             sumx2+=x2;
1351             sumx3+=x3;
1352             sumx4+=x4;
1353             sumy+=xxx(index*4+1);
1354             sumxy+=xxx(index*4+1)*x;
1355             sumx2y+=xxx(index*4+1)*x2;
1356             sumz+=xxx(index*4+2);
1357             sumxz+=xxx(index*4+2)*x;
1358             sumx2z+=xxx(index*4+2)*x2;   
1359             sumq+=xxx(index*4+3);
1360           }
1361           Float_t CentralPad = (fTPCParam->GetNPads(isec,lastrow)-1)/2;
1362           Float_t det=currentIndex*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumx*sumx4-sumx2*sumx3)+
1363             sumx2*(sumx*sumx3-sumx2*sumx2);
1364           
1365           Float_t detay=sumy*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumxy*sumx4-sumx2y*sumx3)+
1366             sumx2*(sumxy*sumx3-sumx2y*sumx2);
1367           Float_t detaz=sumz*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumxz*sumx4-sumx2z*sumx3)+
1368             sumx2*(sumxz*sumx3-sumx2z*sumx2);
1369           
1370           Float_t detby=currentIndex*(sumxy*sumx4-sumx2y*sumx3)-sumy*(sumx*sumx4-sumx2*sumx3)+
1371             sumx2*(sumx*sumx2y-sumx2*sumxy);
1372           Float_t detbz=currentIndex*(sumxz*sumx4-sumx2z*sumx3)-sumz*(sumx*sumx4-sumx2*sumx3)+
1373             sumx2*(sumx*sumx2z-sumx2*sumxz);
1374           
1375           Float_t y=detay/det+CentralPad;
1376           Float_t z=detaz/det;  
1377           Float_t by=detby/det; //y angle
1378           Float_t bz=detbz/det; //z angle
1379           sumy/=Float_t(currentIndex);
1380           sumz/=Float_t(currentIndex);
1381           AliCluster cl;
1382           cl.fX=z;
1383           cl.fY=y;
1384           cl.fQ=sumq;
1385           cl.fSigmaX2=bz;
1386           cl.fSigmaY2=by;
1387           cl.fTracks[0]=ipart;
1388           
1389           AliTPCClustersRow * row = (fClustersArray->GetRow(isec,lastrow));
1390           if (row!=0) row->InsertCluster(&cl);
1391           currentIndex=0;
1392           lastrow=currentrow;
1393         } //end of calculating cluster for given row
1394         
1395         
1396         
1397     } // end of loop over hits
1398   }   // end of loop over tracks 
1399   //write padrows to tree 
1400   for (Int_t ii=0; ii<fTPCParam->GetNRow(isec);ii++) {
1401     fClustersArray->StoreRow(isec,ii);    
1402     fClustersArray->ClearRow(isec,ii);        
1403   }
1404   xxxx->Delete();
1405  
1406 }
1407
1408 //__________________________________________________________________  
1409 void AliTPC::Hits2Digits()  
1410
1411  //----------------------------------------------------
1412  // Loop over all sectors
1413  //----------------------------------------------------
1414
1415   if(fTPCParam == 0){
1416     printf("AliTPCParam MUST be created firstly\n");
1417     return;
1418   } 
1419
1420  for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++) Hits2DigitsSector(isec);
1421
1422 }
1423
1424
1425 //_____________________________________________________________________________
1426 void AliTPC::Hits2DigitsSector(Int_t isec)
1427 {
1428   //-------------------------------------------------------------------
1429   // TPC conversion from hits to digits.
1430   //------------------------------------------------------------------- 
1431
1432   //-----------------------------------------------------------------
1433   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1434   //-----------------------------------------------------------------
1435
1436   //-------------------------------------------------------
1437   //  Get the access to the track hits
1438   //-------------------------------------------------------
1439
1440
1441   TTree *TH = gAlice->TreeH(); // pointer to the hits tree
1442   Stat_t ntracks = TH->GetEntries();
1443
1444   if( ntracks > 0){
1445
1446   //------------------------------------------- 
1447   //  Only if there are any tracks...
1448   //-------------------------------------------
1449
1450     TObjArray **row;
1451     
1452       printf("*** Processing sector number %d ***\n",isec);
1453
1454       Int_t nrows =fTPCParam->GetNRow(isec);
1455
1456       row= new TObjArray* [nrows];
1457     
1458       MakeSector(isec,nrows,TH,ntracks,row);
1459
1460       //--------------------------------------------------------
1461       //   Digitize this sector, row by row
1462       //   row[i] is the pointer to the TObjArray of TVectors,
1463       //   each one containing electrons accepted on this
1464       //   row, assigned into tracks
1465       //--------------------------------------------------------
1466
1467       Int_t i;
1468
1469       if (fDigitsArray->GetTree()==0) fDigitsArray->MakeTree();
1470
1471       for (i=0;i<nrows;i++){
1472
1473         AliDigits * dig = fDigitsArray->CreateRow(isec,i); 
1474
1475         DigitizeRow(i,isec,row);
1476
1477         fDigitsArray->StoreRow(isec,i);
1478
1479         Int_t ndig = dig->GetSize(); 
1480  
1481         printf("*** Sector, row, compressed digits %d %d %d ***\n",isec,i,ndig);
1482         
1483         fDigitsArray->ClearRow(isec,i);  
1484
1485    
1486        } // end of the sector digitization
1487
1488       for(i=0;i<nrows;i++){
1489         row[i]->Delete();     
1490       }
1491       
1492        delete [] row; // delete the array of pointers to TObjArray-s
1493         
1494   } // ntracks >0
1495
1496 } // end of Hits2DigitsSector
1497
1498
1499 //_____________________________________________________________________________
1500 void AliTPC::DigitizeRow(Int_t irow,Int_t isec,TObjArray **rows)
1501 {
1502   //-----------------------------------------------------------
1503   // Single row digitization, coupling from the neighbouring
1504   // rows taken into account
1505   //-----------------------------------------------------------
1506
1507   //-----------------------------------------------------------------
1508   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1509   // Modified: Marian Ivanov GSI Darmstadt, m.ivanov@gsi.de
1510   //-----------------------------------------------------------------
1511  
1512
1513   Float_t zerosup = fTPCParam->GetZeroSup();
1514   Int_t nrows =fTPCParam->GetNRow(isec);
1515   fCurrentIndex[1]= isec;
1516   
1517
1518   Int_t n_of_pads = fTPCParam->GetNPads(isec,irow);
1519   Int_t n_of_tbins = fTPCParam->GetMaxTBin();
1520   Int_t IndexRange[4];
1521   //
1522   //  Integrated signal for this row
1523   //  and a single track signal
1524   //    
1525   TMatrix *m1   = new TMatrix(0,n_of_pads,0,n_of_tbins); // integrated
1526   TMatrix *m2   = new TMatrix(0,n_of_pads,0,n_of_tbins); // single
1527   //
1528   TMatrix &Total  = *m1;
1529
1530   //  Array of pointers to the label-signal list
1531
1532   Int_t NofDigits = n_of_pads*n_of_tbins; // number of digits for this row
1533   Float_t  **pList = new Float_t* [NofDigits]; 
1534
1535   Int_t lp;
1536   Int_t i1;   
1537   for(lp=0;lp<NofDigits;lp++)pList[lp]=0; // set all pointers to NULL
1538   //
1539   //calculate signal 
1540   //
1541   Int_t row1 = TMath::Max(irow-fTPCParam->GetNCrossRows(),0);
1542   Int_t row2 = TMath::Min(irow+fTPCParam->GetNCrossRows(),nrows-1);
1543   for (Int_t row= row1;row<=row2;row++){
1544     Int_t nTracks= rows[row]->GetEntries();
1545     for (i1=0;i1<nTracks;i1++){
1546       fCurrentIndex[2]= row;
1547       fCurrentIndex[3]=irow;
1548       if (row==irow){
1549         m2->Zero();  // clear single track signal matrix
1550         Float_t TrackLabel = GetSignal(rows[row],i1,m2,m1,IndexRange); 
1551         GetList(TrackLabel,n_of_pads,m2,IndexRange,pList);
1552       }
1553       else   GetSignal(rows[row],i1,0,m1,IndexRange);
1554     }
1555   }
1556          
1557   Int_t tracks[3];
1558
1559   AliDigits *dig = fDigitsArray->GetRow(isec,irow);
1560   for(Int_t ip=0;ip<n_of_pads;ip++){
1561     for(Int_t it=0;it<n_of_tbins;it++){
1562
1563       Float_t q = Total(ip,it);
1564
1565       Int_t gi =it*n_of_pads+ip; // global index
1566
1567       q = gRandom->Gaus(q,fTPCParam->GetNoise()*fTPCParam->GetNoiseNormFac()); 
1568
1569       q = (Int_t)q;
1570
1571       if(q <=zerosup) continue; // do not fill zeros
1572       if(q > adc_sat) q = adc_sat;  // saturation
1573
1574       //
1575       //  "real" signal or electronic noise (list = -1)?
1576       //    
1577
1578       for(Int_t j1=0;j1<3;j1++){
1579         tracks[j1] = (pList[gi]) ?(Int_t)(*(pList[gi]+j1)) : -1;
1580       }
1581
1582 //Begin_Html
1583 /*
1584   <A NAME="AliDigits"></A>
1585   using of AliDigits object
1586 */
1587 //End_Html
1588       dig->SetDigitFast((Short_t)q,it,ip);
1589       if (fDigitsArray->IsSimulated())
1590         {
1591          ((AliSimDigits*)dig)->SetTrackIDFast(tracks[0],it,ip,0);
1592          ((AliSimDigits*)dig)->SetTrackIDFast(tracks[1],it,ip,1);
1593          ((AliSimDigits*)dig)->SetTrackIDFast(tracks[2],it,ip,2);
1594         }
1595      
1596     
1597     } // end of loop over time buckets
1598   }  // end of lop over pads 
1599
1600   //
1601   //  This row has been digitized, delete nonused stuff
1602   //
1603
1604   for(lp=0;lp<NofDigits;lp++){
1605     if(pList[lp]) delete [] pList[lp];
1606   }
1607   
1608   delete [] pList;
1609
1610   delete m1;
1611   delete m2;
1612   //  delete m3;
1613
1614 } // end of DigitizeRow
1615
1616 //_____________________________________________________________________________
1617
1618 Float_t AliTPC::GetSignal(TObjArray *p1, Int_t ntr, TMatrix *m1, TMatrix *m2,
1619                           Int_t *IndexRange)
1620 {
1621
1622   //---------------------------------------------------------------
1623   //  Calculates 2-D signal (pad,time) for a single track,
1624   //  returns a pointer to the signal matrix and the track label 
1625   //  No digitization is performed at this level!!!
1626   //---------------------------------------------------------------
1627
1628   //-----------------------------------------------------------------
1629   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1630   // Modified: Marian Ivanov 
1631   //-----------------------------------------------------------------
1632
1633   TVector *tv;
1634  
1635   tv = (TVector*)p1->At(ntr); // pointer to a track
1636   TVector &v = *tv;
1637   
1638   Float_t label = v(0);
1639   Int_t CentralPad = (fTPCParam->GetNPads(fCurrentIndex[1],fCurrentIndex[3])-1)/2;
1640
1641   Int_t nElectrons = (tv->GetNrows()-1)/4;
1642   IndexRange[0]=9999; // min pad
1643   IndexRange[1]=-1; // max pad
1644   IndexRange[2]=9999; //min time
1645   IndexRange[3]=-1; // max time
1646
1647   //  Float_t IneffFactor = 0.5; // inefficiency in the gain close to the edge, as above
1648
1649   TMatrix &signal = *m1;
1650   TMatrix &total = *m2;
1651   //
1652   //  Loop over all electrons
1653   //
1654   for(Int_t nel=0; nel<nElectrons; nel++){
1655     Int_t idx=nel*4;
1656     Float_t aval =  v(idx+4);
1657     Float_t eltoadcfac=aval*fTPCParam->GetTotalNormFac(); 
1658     Float_t xyz[3]={v(idx+1),v(idx+2),v(idx+3)};
1659     Int_t n = fTPCParam->CalcResponse(xyz,fCurrentIndex,fCurrentIndex[3]);
1660     
1661     if (n>0) for (Int_t i =0; i<n; i++){
1662        Int_t *index = fTPCParam->GetResBin(i);        
1663        Int_t pad=index[1]+CentralPad;  //in digit coordinates central pad has coordinate 0
1664        if ( ( pad<(fTPCParam->GetNPads(fCurrentIndex[1],fCurrentIndex[3]))) && (pad>0)) {
1665          Int_t time=index[2];    
1666          Float_t weight = fTPCParam->GetResWeight(i); //we normalise response to ADC channel
1667          weight *= eltoadcfac;
1668          
1669          if (m1!=0) signal(pad,time)+=weight; 
1670          total(pad,time)+=weight;
1671          IndexRange[0]=TMath::Min(IndexRange[0],pad);
1672          IndexRange[1]=TMath::Max(IndexRange[1],pad);
1673          IndexRange[2]=TMath::Min(IndexRange[2],time);
1674          IndexRange[3]=TMath::Max(IndexRange[3],time); 
1675        }         
1676     }
1677   } // end of loop over electrons
1678   
1679   return label; // returns track label when finished
1680 }
1681
1682 //_____________________________________________________________________________
1683 void AliTPC::GetList(Float_t label,Int_t np,TMatrix *m,Int_t *IndexRange,
1684                      Float_t **pList)
1685 {
1686   //----------------------------------------------------------------------
1687   //  Updates the list of tracks contributing to digits for a given row
1688   //----------------------------------------------------------------------
1689
1690   //-----------------------------------------------------------------
1691   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1692   //-----------------------------------------------------------------
1693
1694   TMatrix &signal = *m;
1695
1696   // lop over nonzero digits
1697
1698   for(Int_t it=IndexRange[2];it<IndexRange[3]+1;it++){
1699     for(Int_t ip=IndexRange[0];ip<IndexRange[1]+1;ip++){
1700
1701
1702         // accept only the contribution larger than 500 electrons (1/2 s_noise)
1703
1704         if(signal(ip,it)<0.5) continue; 
1705
1706
1707         Int_t GlobalIndex = it*np+ip; // GlobalIndex starts from 0!
1708         
1709         if(!pList[GlobalIndex]){
1710         
1711           // 
1712           // Create new list (6 elements - 3 signals and 3 labels),
1713           //
1714
1715           pList[GlobalIndex] = new Float_t [6];
1716
1717           // set list to -1 
1718
1719           *pList[GlobalIndex] = -1.;
1720           *(pList[GlobalIndex]+1) = -1.;
1721           *(pList[GlobalIndex]+2) = -1.;
1722           *(pList[GlobalIndex]+3) = -1.;
1723           *(pList[GlobalIndex]+4) = -1.;
1724           *(pList[GlobalIndex]+5) = -1.;
1725
1726
1727           *pList[GlobalIndex] = label;
1728           *(pList[GlobalIndex]+3) = signal(ip,it);
1729         }
1730         else{
1731
1732           // check the signal magnitude
1733
1734           Float_t highest = *(pList[GlobalIndex]+3);
1735           Float_t middle = *(pList[GlobalIndex]+4);
1736           Float_t lowest = *(pList[GlobalIndex]+5);
1737
1738           //
1739           //  compare the new signal with already existing list
1740           //
1741
1742           if(signal(ip,it)<lowest) continue; // neglect this track
1743
1744           //
1745
1746           if (signal(ip,it)>highest){
1747             *(pList[GlobalIndex]+5) = middle;
1748             *(pList[GlobalIndex]+4) = highest;
1749             *(pList[GlobalIndex]+3) = signal(ip,it);
1750
1751             *(pList[GlobalIndex]+2) = *(pList[GlobalIndex]+1);
1752             *(pList[GlobalIndex]+1) = *pList[GlobalIndex];
1753             *pList[GlobalIndex] = label;
1754           }
1755           else if (signal(ip,it)>middle){
1756             *(pList[GlobalIndex]+5) = middle;
1757             *(pList[GlobalIndex]+4) = signal(ip,it);
1758
1759             *(pList[GlobalIndex]+2) = *(pList[GlobalIndex]+1);
1760             *(pList[GlobalIndex]+1) = label;
1761           }
1762           else{
1763             *(pList[GlobalIndex]+5) = signal(ip,it);
1764             *(pList[GlobalIndex]+2) = label;
1765           }
1766         }
1767
1768     } // end of loop over pads
1769   } // end of loop over time bins
1770
1771
1772
1773 }//end of GetList
1774 //___________________________________________________________________
1775 void AliTPC::MakeSector(Int_t isec,Int_t nrows,TTree *TH,
1776                         Stat_t ntracks,TObjArray **row)
1777 {
1778
1779   //-----------------------------------------------------------------
1780   // Prepares the sector digitization, creates the vectors of
1781   // tracks for each row of this sector. The track vector
1782   // contains the track label and the position of electrons.
1783   //-----------------------------------------------------------------
1784
1785   //-----------------------------------------------------------------
1786   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1787   //-----------------------------------------------------------------
1788
1789   Float_t gasgain = fTPCParam->GetGasGain();
1790   Int_t i;
1791   Float_t xyz[4]; 
1792
1793   AliTPChit *tpcHit; // pointer to a sigle TPC hit    
1794  
1795   //----------------------------------------------
1796   // Create TObjArray-s, one for each row,
1797   // each TObjArray will store the TVectors
1798   // of electrons, one TVector per each track.
1799   //---------------------------------------------- 
1800     
1801   for(i=0; i<nrows; i++){
1802     row[i] = new TObjArray;
1803   }
1804   Int_t *n_of_electrons = new Int_t [nrows]; // electron counter for each row
1805   TVector **tracks = new TVector* [nrows]; //pointers to the track vectors
1806
1807   //--------------------------------------------------------------------
1808   //  Loop over tracks, the "track" contains the full history
1809   //--------------------------------------------------------------------
1810
1811   Int_t previousTrack,currentTrack;
1812   previousTrack = -1; // nothing to store so far!
1813
1814   for(Int_t track=0;track<ntracks;track++){
1815
1816     ResetHits();
1817
1818     TH->GetEvent(track); // get next track
1819     Int_t nhits = fHits->GetEntriesFast(); // get number of hits for this track
1820
1821     if(nhits == 0) continue; // no hits in the TPC for this track
1822
1823     //--------------------------------------------------------------
1824     //  Loop over hits
1825     //--------------------------------------------------------------
1826
1827     for(Int_t hit=0;hit<nhits;hit++){
1828
1829       tpcHit = (AliTPChit*)fHits->UncheckedAt(hit); // get a pointer to a hit
1830       
1831       Int_t sector=tpcHit->fSector; // sector number
1832       if(sector != isec) continue; 
1833
1834         currentTrack = tpcHit->fTrack; // track number
1835         if(currentTrack != previousTrack){
1836                           
1837            // store already filled fTrack
1838               
1839            for(i=0;i<nrows;i++){
1840              if(previousTrack != -1){
1841                if(n_of_electrons[i]>0){
1842                  TVector &v = *tracks[i];
1843                  v(0) = previousTrack;
1844                  tracks[i]->ResizeTo(4*n_of_electrons[i]+1); // shrink if necessary
1845                  row[i]->Add(tracks[i]);                     
1846                }
1847                else{
1848                  delete tracks[i]; // delete empty TVector
1849                  tracks[i]=0;
1850                }
1851              }
1852
1853              n_of_electrons[i]=0;
1854              tracks[i] = new TVector(481); // TVectors for the next fTrack
1855
1856            } // end of loop over rows
1857                
1858            previousTrack=currentTrack; // update track label 
1859         }
1860            
1861         Int_t QI = (Int_t) (tpcHit->fQ); // energy loss (number of electrons)
1862
1863        //---------------------------------------------------
1864        //  Calculate the electron attachment probability
1865        //---------------------------------------------------
1866
1867
1868         Float_t time = 1.e6*(fTPCParam->GetZLength()-TMath::Abs(tpcHit->fZ))
1869                                                         /fTPCParam->GetDriftV(); 
1870         // in microseconds!     
1871         Float_t AttProb = fTPCParam->GetAttCoef()*
1872           fTPCParam->GetOxyCont()*time; //  fraction! 
1873    
1874         //-----------------------------------------------
1875         //  Loop over electrons
1876         //-----------------------------------------------
1877         Int_t index[3];
1878         index[1]=isec;
1879         for(Int_t nel=0;nel<QI;nel++){
1880           // skip if electron lost due to the attachment
1881           if((gRandom->Rndm(0)) < AttProb) continue; // electron lost!
1882           xyz[0]=tpcHit->fX;
1883           xyz[1]=tpcHit->fY;
1884           xyz[2]=tpcHit->fZ;      
1885           xyz[3]= (Float_t) (-gasgain*TMath::Log(gRandom->Rndm()));
1886           index[0]=1;
1887           
1888           TransportElectron(xyz,index); //MI change -august       
1889           Int_t row_number;
1890           fTPCParam->GetPadRow(xyz,index); //MI change august
1891           row_number = index[2];
1892           //transform position to local digit coordinates
1893           //relative to nearest pad row 
1894           if ((row_number<0)||row_number>=fTPCParam->GetNRow(isec)) continue;     
1895           n_of_electrons[row_number]++;   
1896           //----------------------------------
1897           // Expand vector if necessary
1898           //----------------------------------
1899           if(n_of_electrons[row_number]>120){
1900             Int_t range = tracks[row_number]->GetNrows();
1901             if((n_of_electrons[row_number])>(range-1)/4){
1902         
1903               tracks[row_number]->ResizeTo(range+400); // Add 100 electrons
1904             }
1905           }
1906           
1907           TVector &v = *tracks[row_number];
1908           Int_t idx = 4*n_of_electrons[row_number]-3;
1909
1910           v(idx)=  xyz[0];   // X - pad row coordinate
1911           v(idx+1)=xyz[1];   // Y - pad coordinate (along the pad-row)
1912           v(idx+2)=xyz[2];   // Z - time bin coordinate
1913           v(idx+3)=xyz[3];   // avalanche size  
1914         } // end of loop over electrons
1915         
1916       } // end of loop over hits
1917     } // end of loop over tracks
1918
1919     //
1920     //   store remaining track (the last one) if not empty
1921     //
1922
1923      for(i=0;i<nrows;i++){
1924        if(n_of_electrons[i]>0){
1925           TVector &v = *tracks[i];
1926           v(0) = previousTrack;
1927           tracks[i]->ResizeTo(4*n_of_electrons[i]+1); // shrink if necessary
1928           row[i]->Add(tracks[i]);  
1929         }
1930         else{
1931           delete tracks[i];
1932           tracks[i]=0;
1933         }  
1934       }  
1935
1936           delete [] tracks;
1937           delete [] n_of_electrons;
1938  
1939
1940 } // end of MakeSector
1941
1942
1943 //_____________________________________________________________________________
1944 void AliTPC::Init()
1945 {
1946   //
1947   // Initialise TPC detector after definition of geometry
1948   //
1949   Int_t i;
1950   //
1951   printf("\n");
1952   for(i=0;i<35;i++) printf("*");
1953   printf(" TPC_INIT ");
1954   for(i=0;i<35;i++) printf("*");
1955   printf("\n");
1956   //
1957   for(i=0;i<80;i++) printf("*");
1958   printf("\n");
1959 }
1960
1961 //_____________________________________________________________________________
1962 void AliTPC::MakeBranch(Option_t* option)
1963 {
1964   //
1965   // Create Tree branches for the TPC.
1966   //
1967   Int_t buffersize = 4000;
1968   char branchname[10];
1969   sprintf(branchname,"%s",GetName());
1970
1971   AliDetector::MakeBranch(option);
1972
1973   char *D = strstr(option,"D");
1974
1975   if (fDigits   && gAlice->TreeD() && D) {
1976     gAlice->TreeD()->Branch(branchname,&fDigits, buffersize);
1977     printf("Making Branch %s for digits\n",branchname);
1978   }     
1979
1980   char *R = strstr(option,"R");
1981
1982   if (fClusters && gAlice->TreeR() && R) {
1983     gAlice->TreeR()->Branch(branchname,&fClusters, buffersize);
1984     printf("Making Branch %s for Clusters\n",branchname);
1985   }     
1986 }
1987  
1988 //_____________________________________________________________________________
1989 void AliTPC::ResetDigits()
1990 {
1991   //
1992   // Reset number of digits and the digits array for this detector
1993   // reset clusters
1994   //
1995   fNdigits   = 0;
1996   if (fDigits)   fDigits->Clear();
1997   fNclusters = 0;
1998   if (fClusters) fClusters->Clear();
1999 }
2000
2001 //_____________________________________________________________________________
2002 void AliTPC::SetSecAL(Int_t sec)
2003 {
2004   //---------------------------------------------------
2005   // Activate/deactivate selection for lower sectors
2006   //---------------------------------------------------
2007
2008   //-----------------------------------------------------------------
2009   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2010   //-----------------------------------------------------------------
2011
2012   fSecAL = sec;
2013 }
2014
2015 //_____________________________________________________________________________
2016 void AliTPC::SetSecAU(Int_t sec)
2017 {
2018   //----------------------------------------------------
2019   // Activate/deactivate selection for upper sectors
2020   //---------------------------------------------------
2021
2022   //-----------------------------------------------------------------
2023   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2024   //-----------------------------------------------------------------
2025
2026   fSecAU = sec;
2027 }
2028
2029 //_____________________________________________________________________________
2030 void AliTPC::SetSecLows(Int_t s1,Int_t s2,Int_t s3,Int_t s4,Int_t s5, Int_t s6)
2031 {
2032   //----------------------------------------
2033   // Select active lower sectors
2034   //----------------------------------------
2035
2036   //-----------------------------------------------------------------
2037   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2038   //-----------------------------------------------------------------
2039
2040   fSecLows[0] = s1;
2041   fSecLows[1] = s2;
2042   fSecLows[2] = s3;
2043   fSecLows[3] = s4;
2044   fSecLows[4] = s5;
2045   fSecLows[5] = s6;
2046 }
2047
2048 //_____________________________________________________________________________
2049 void AliTPC::SetSecUps(Int_t s1,Int_t s2,Int_t s3,Int_t s4,Int_t s5, Int_t s6,
2050                        Int_t s7, Int_t s8 ,Int_t s9 ,Int_t s10, 
2051                        Int_t s11 , Int_t s12)
2052 {
2053   //--------------------------------
2054   // Select active upper sectors
2055   //--------------------------------
2056
2057   //-----------------------------------------------------------------
2058   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2059   //-----------------------------------------------------------------
2060
2061   fSecUps[0] = s1;
2062   fSecUps[1] = s2;
2063   fSecUps[2] = s3;
2064   fSecUps[3] = s4;
2065   fSecUps[4] = s5;
2066   fSecUps[5] = s6;
2067   fSecUps[6] = s7;
2068   fSecUps[7] = s8;
2069   fSecUps[8] = s9;
2070   fSecUps[9] = s10;
2071   fSecUps[10] = s11;
2072   fSecUps[11] = s12;
2073 }
2074
2075 //_____________________________________________________________________________
2076 void AliTPC::SetSens(Int_t sens)
2077 {
2078
2079   //-------------------------------------------------------------
2080   // Activates/deactivates the sensitive strips at the center of
2081   // the pad row -- this is for the space-point resolution calculations
2082   //-------------------------------------------------------------
2083
2084   //-----------------------------------------------------------------
2085   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2086   //-----------------------------------------------------------------
2087
2088   fSens = sens;
2089 }
2090  
2091 void AliTPC::SetSide(Float_t side)
2092 {
2093   fSide = side;
2094  
2095 }
2096 //____________________________________________________________________________
2097 void AliTPC::SetGasMixt(Int_t nc,Int_t c1,Int_t c2,Int_t c3,Float_t p1,
2098                            Float_t p2,Float_t p3)
2099 {
2100
2101  fNoComp = nc;
2102  
2103  fMixtComp[0]=c1;
2104  fMixtComp[1]=c2;
2105  fMixtComp[2]=c3;
2106
2107  fMixtProp[0]=p1;
2108  fMixtProp[1]=p2;
2109  fMixtProp[2]=p3; 
2110  
2111  
2112 }
2113 //_____________________________________________________________________________
2114
2115 void AliTPC::TransportElectron(Float_t *xyz, Int_t *index)
2116 {
2117   //
2118   // electron transport taking into account:
2119   // 1. diffusion, 
2120   // 2.ExB at the wires
2121   // 3. nonisochronity
2122   //
2123   // xyz and index must be already transformed to system 1
2124   //
2125
2126   fTPCParam->Transform1to2(xyz,index);
2127   
2128   //add diffusion
2129   Float_t driftl=xyz[2];
2130   if(driftl<0.01) driftl=0.01;
2131   driftl=TMath::Sqrt(driftl);
2132   Float_t sig_t = driftl*(fTPCParam->GetDiffT());
2133   Float_t sig_l = driftl*(fTPCParam->GetDiffL());
2134   xyz[0]=gRandom->Gaus(xyz[0],sig_t);
2135   xyz[1]=gRandom->Gaus(xyz[1],sig_t);
2136   xyz[2]=gRandom->Gaus(xyz[2],sig_l);
2137
2138   // ExB
2139   
2140   if (fTPCParam->GetMWPCReadout()==kTRUE){
2141     Float_t x1=xyz[0];
2142     fTPCParam->Transform2to2NearestWire(xyz,index);
2143     Float_t dx=xyz[0]-x1;
2144     xyz[1]+=dx*(fTPCParam->GetOmegaTau());
2145   }
2146   //add nonisochronity (not implemented yet)
2147   
2148 }
2149 //_____________________________________________________________________________
2150 void AliTPC::Streamer(TBuffer &R__b)
2151 {
2152   //
2153   // Stream an object of class AliTPC.
2154   //
2155    if (R__b.IsReading()) {
2156       Version_t R__v = R__b.ReadVersion(); if (R__v) { }
2157       AliDetector::Streamer(R__b);
2158       if (R__v < 2) return;
2159       R__b >> fNsectors;
2160       R__b >> fNclusters;
2161       R__b >> fNtracks;
2162
2163    } else {
2164       R__b.WriteVersion(AliTPC::IsA());
2165       AliDetector::Streamer(R__b);
2166       R__b << fNsectors;
2167       R__b << fNclusters;
2168       R__b << fNtracks;
2169    }
2170 }
2171   
2172 ClassImp(AliTPCcluster)
2173  
2174 //_____________________________________________________________________________
2175 AliTPCcluster::AliTPCcluster(Float_t *hits, Int_t *lab)
2176 {
2177   //
2178   // Creates a simulated cluster for the TPC
2179   //
2180   fTracks[0]  = lab[0];
2181   fTracks[1]  = lab[1];
2182   fTracks[2]  = lab[2];
2183   fSector     = lab[3];
2184   fPadRow     = lab[4];
2185   fY          = hits[0];
2186   fZ          = hits[1];
2187   fQ          = hits[2];
2188   fSigmaY2    = hits[3];
2189   fSigmaZ2    = hits[4];
2190 }
2191  
2192 //_____________________________________________________________________________
2193 void AliTPCcluster::GetXYZ(Float_t *x, const AliTPCParam *par) const 
2194 {
2195   //
2196   // Transformation from local to global coordinate system
2197   //
2198   x[0]=par->GetPadRowRadii(fSector,fPadRow);
2199   x[1]=fY;
2200   x[2]=fZ;
2201   Float_t cs, sn, tmp;
2202   par->AdjustCosSin(fSector,cs,sn);
2203   tmp = x[0]*cs-x[1]*sn;
2204   x[1]= x[0]*sn+x[1]*cs; x[0]=tmp;
2205 }
2206  
2207 //_____________________________________________________________________________
2208 Int_t AliTPCcluster::Compare(TObject * o)
2209 {
2210   //
2211   // compare two clusters according y coordinata
2212   //
2213   AliTPCcluster *cl= (AliTPCcluster *)o;
2214   if (fY<cl->fY) return -1;
2215   if (fY==cl->fY) return 0;
2216   return 1;  
2217 }
2218
2219 Bool_t AliTPCcluster::IsSortable() const
2220 {
2221   //
2222   //make AliTPCcluster sortabale
2223   //
2224   return kTRUE; 
2225 }
2226
2227
2228
2229 ClassImp(AliTPCdigit)
2230  
2231 //_____________________________________________________________________________
2232 AliTPCdigit::AliTPCdigit(Int_t *tracks, Int_t *digits):
2233   AliDigit(tracks)
2234 {
2235   //
2236   // Creates a TPC digit object
2237   //
2238   fSector     = digits[0];
2239   fPadRow     = digits[1];
2240   fPad        = digits[2];
2241   fTime       = digits[3];
2242   fSignal     = digits[4];
2243 }
2244
2245  
2246 ClassImp(AliTPChit)
2247  
2248 //_____________________________________________________________________________
2249 AliTPChit::AliTPChit(Int_t shunt, Int_t track, Int_t *vol, Float_t *hits):
2250 AliHit(shunt,track)
2251 {
2252   //
2253   // Creates a TPC hit object
2254   //
2255   fSector     = vol[0];
2256   fPadRow     = vol[1];
2257   fX          = hits[0];
2258   fY          = hits[1];
2259   fZ          = hits[2];
2260   fQ          = hits[3];
2261 }
2262  
2263  
2264 ClassImp(AliTPCtrack)
2265  
2266 //_____________________________________________________________________________
2267 AliTPCtrack::AliTPCtrack(Float_t *hits)
2268 {
2269   //
2270   // Default creator for a TPC reconstructed track object
2271   //
2272   fX=hits[0]; // This is dummy code !
2273 }
2274 //_________________________________________________________________________
2275
2276 AliTPCtrack::AliTPCtrack(const AliTPCcluster *c,const TVector& xx,
2277                          const TMatrix& CC, Double_t xref, Double_t alpha):
2278   x(xx),C(CC),fClusters(200)
2279 {
2280   //-----------------------------------------------------------------
2281   // This is the main track constructor.
2282   //
2283   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2284   //-----------------------------------------------------------------
2285   fX=xref;
2286   fAlpha=alpha;
2287   fChi2=0.;
2288   fClusters.AddLast((AliTPCcluster*)(c));
2289 }
2290
2291 //_____________________________________________________________________________
2292 AliTPCtrack::AliTPCtrack(const AliTPCtrack& t) : x(t.x), C(t.C),
2293   fClusters(t.fClusters.GetEntriesFast()) 
2294 {
2295   //-----------------------------------------------------------------
2296   // This is a track copy constructor.
2297   //
2298   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2299   //-----------------------------------------------------------------
2300   fX=t.fX;
2301   fChi2=t.fChi2;
2302   fAlpha=t.fAlpha;
2303   Int_t n=t.fClusters.GetEntriesFast();
2304   for (Int_t i=0; i<n; i++) fClusters.AddLast(t.fClusters.UncheckedAt(i));
2305 }
2306
2307 //_____________________________________________________________________________
2308 Int_t AliTPCtrack::Compare(TObject *o) {
2309   //-----------------------------------------------------------------
2310   // This function compares tracks according to the uncertainty of their
2311   // position in Y.
2312   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2313   //-----------------------------------------------------------------
2314   AliTPCtrack *t=(AliTPCtrack*)o;
2315   Double_t co=t->GetSigmaY2();
2316   Double_t c =GetSigmaY2();
2317   if (c>co) return 1;
2318   else if (c<co) return -1;
2319   return 0;
2320 }
2321
2322 //_____________________________________________________________________________
2323 Int_t AliTPCtrack::PropagateTo(Double_t xk,Double_t x0,Double_t rho,Double_t pm)
2324 {
2325   //-----------------------------------------------------------------
2326   // This function propagates a track to a reference plane x=xk.
2327   //
2328   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2329   //-----------------------------------------------------------------
2330   if (TMath::Abs(x(2)*xk - x(3)) >= 0.999) {
2331     if (*this>4) cerr<<*this<<" AliTPCtrack warning: Propagation failed !\n";
2332     return 0;
2333   }
2334
2335   Double_t x1=fX, x2=x1+(xk-x1), dx=x2-x1, y1=x(0), z1=x(1);
2336   Double_t c1=x(2)*x1 - x(3), r1=sqrt(1.- c1*c1);
2337   Double_t c2=x(2)*x2 - x(3), r2=sqrt(1.- c2*c2);
2338   
2339   x(0) += dx*(c1+c2)/(r1+r2);
2340   x(1) += dx*(c1+c2)/(c1*r2 + c2*r1)*x(4);
2341
2342   TMatrix F(5,5); F.UnitMatrix();
2343   Double_t rr=r1+r2, cc=c1+c2, xx=x1+x2;
2344   F(0,2)= dx*(rr*xx + cc*(c1*x1/r1+c2*x2/r2))/(rr*rr);
2345   F(0,3)=-dx*(2*rr + cc*(c1/r1 + c2/r2))/(rr*rr);
2346   Double_t cr=c1*r2+c2*r1;
2347   F(1,2)= dx*x(4)*(cr*xx-cc*(r1*x2-c2*c1*x1/r1+r2*x1-c1*c2*x2/r2))/(cr*cr);
2348   F(1,3)=-dx*x(4)*(2*cr + cc*(c2*c1/r1-r1 + c1*c2/r2-r2))/(cr*cr);
2349   F(1,4)= dx*cc/cr; 
2350   TMatrix tmp(F,TMatrix::kMult,C);
2351   C.Mult(tmp,TMatrix(TMatrix::kTransposed,F));
2352
2353   fX=x2;
2354
2355   //Multiple scattering******************
2356   Double_t ey=x(2)*fX - x(3);
2357   Double_t ex=sqrt(1-ey*ey);
2358   Double_t ez=x(4);
2359   TMatrix Q(5,5); Q=0.;
2360   Q(2,2)=ez*ez+ey*ey;   Q(2,3)=-ex*ey;       Q(2,4)=-ex*ez;
2361   Q(3,2)=Q(2,3);        Q(3,3)= ez*ez+ex*ex; Q(3,4)=-ey*ez;
2362   Q(4,2)=Q(2,4);        Q(4,3)= Q(3,4);      Q(4,4)=1.;
2363   
2364   F=0;
2365   F(2,2)=-x(2)*ex;          F(2,3)=-x(2)*ey;
2366   F(3,2)=-ex*(x(2)*fX-ey);  F(3,3)=-(1.+ x(2)*fX*ey - ey*ey);
2367   F(4,2)=-ez*ex;            F(4,3)=-ez*ey;           F(4,4)=1.;
2368   
2369   tmp.Mult(F,Q);
2370   Q.Mult(tmp,TMatrix(TMatrix::kTransposed,F));
2371   
2372   Double_t p2=GetPt()*GetPt()*(1.+x(4)*x(4));
2373   Double_t beta2=p2/(p2 + pm*pm);
2374   Double_t d=sqrt((x1-fX)*(x1-fX)+(y1-x(0))*(y1-x(0))+(z1-x(1))*(z1-x(1)));
2375   Double_t theta2=14.1*14.1/(beta2*p2*1e6)*d/x0*rho;
2376   Q*=theta2;
2377   C+=Q;
2378
2379   //Energy losses************************
2380   Double_t dE=0.153e-3/beta2*(log(5940*beta2/(1-beta2)) - beta2)*d*rho;
2381   if (x1 < x2) dE=-dE;
2382   x(2)*=(1.- sqrt(p2+pm*pm)/p2*dE);
2383   //x(3)*=(1.- sqrt(p2+pm*pm)/p2*dE);
2384
2385   return 1;
2386 }
2387
2388 //_____________________________________________________________________________
2389 void AliTPCtrack::PropagateToVertex(Double_t x0,Double_t rho,Double_t pm) 
2390 {
2391   //-----------------------------------------------------------------
2392   // This function propagates tracks to the "vertex".
2393   //
2394   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2395   //-----------------------------------------------------------------
2396   Double_t c=x(2)*fX - x(3);
2397   Double_t tgf=-x(3)/(x(2)*x(0) + sqrt(1-c*c));
2398   Double_t snf=tgf/sqrt(1.+ tgf*tgf);
2399   Double_t xv=(x(3)+snf)/x(2);
2400   PropagateTo(xv,x0,rho,pm);
2401 }
2402
2403 //_____________________________________________________________________________
2404 void AliTPCtrack::Update(const AliTPCcluster *c, Double_t chisq)
2405 {
2406   //-----------------------------------------------------------------
2407   // This function associates a clusters with this track.
2408   //
2409   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2410   //-----------------------------------------------------------------
2411   TMatrix H(2,5); H.UnitMatrix();
2412   TMatrix Ht(TMatrix::kTransposed,H);
2413   TVector m(2);   m(0)=c->fY; m(1)=c->fZ; 
2414   TMatrix V(2,2); V(0,0)=c->fSigmaY2; V(0,1)=0.; V(1,0)=0.; V(1,1)=c->fSigmaZ2;
2415
2416   TMatrix tmp(H,TMatrix::kMult,C);
2417   TMatrix R(tmp,TMatrix::kMult,Ht); R+=V;
2418   
2419   Double_t det=(Double_t)R(0,0)*R(1,1) - (Double_t)R(0,1)*R(1,0);
2420   R(0,1)=R(0,0); R(0,0)=R(1,1); R(1,1)=R(0,1); 
2421   R(1,0)*=-1; R(0,1)=R(1,0);
2422   R*=1./det;
2423   
2424   //R.Invert();
2425   
2426   TMatrix K(C,TMatrix::kMult,Ht); K*=R;
2427   
2428   TVector savex=x;
2429   x*=H; x-=m;
2430
2431   x*=-1; x*=K; x+=savex;
2432   if (TMath::Abs(x(2)*fX-x(3)) >= 0.999) {
2433     if (*this>4) cerr<<*this<<" AliTPCtrack warning: Filtering failed !\n";
2434     x=savex;
2435     return;
2436   }
2437   
2438   TMatrix saveC=C;
2439   C.Mult(K,tmp); C-=saveC; C*=-1;
2440
2441   fClusters.AddLast((AliTPCcluster*)c);
2442   fChi2 += chisq;
2443 }
2444
2445 //_____________________________________________________________________________
2446 Int_t AliTPCtrack::Rotate(Double_t alpha)
2447 {
2448   //-----------------------------------------------------------------
2449   // This function rotates this track.
2450   //
2451   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2452   //-----------------------------------------------------------------
2453   fAlpha += alpha;
2454   
2455   Double_t x1=fX, y1=x(0);
2456   Double_t ca=cos(alpha), sa=sin(alpha);
2457   Double_t r1=x(2)*fX - x(3);
2458   
2459   fX = x1*ca + y1*sa;
2460   x(0)=-x1*sa + y1*ca;
2461   x(3)=x(3)*ca + (x(2)*y1 + sqrt(1.- r1*r1))*sa;
2462   
2463   Double_t r2=x(2)*fX - x(3);
2464   if (TMath::Abs(r2) >= 0.999) {
2465     if (*this>4) cerr<<*this<<" AliTPCtrack warning: Rotation failed !\n";
2466     return 0;
2467   }
2468   
2469   Double_t y0=x(0) + sqrt(1.- r2*r2)/x(2);
2470   if ((x(0)-y0)*x(2) >= 0.) {
2471     if (*this>4) cerr<<*this<<" AliTPCtrack warning: Rotation failed !!!\n";
2472     return 0;
2473   }
2474   
2475   TMatrix F(5,5); F.UnitMatrix();
2476   F(0,0)=ca;
2477   F(3,0)=x(2)*sa; 
2478   F(3,2)=(y1 - r1*x1/sqrt(1.- r1*r1))*sa; 
2479   F(3,3)= ca + sa*r1/sqrt(1.- r1*r1);
2480   TMatrix tmp(F,TMatrix::kMult,C); 
2481   // Double_t dy2=C(0,0);
2482   C.Mult(tmp,TMatrix(TMatrix::kTransposed,F));
2483   // C(0,0)+=dy2*sa*sa*r1*r1/(1.- r1*r1);
2484   // C(1,1)+=dy2*sa*sa*x(4)*x(4)/(1.- r1*r1);
2485   
2486   return 1;
2487 }
2488
2489 //_____________________________________________________________________________
2490 void AliTPCtrack::UseClusters() const 
2491 {
2492   //-----------------------------------------------------------------
2493   // This function marks clusters associated with this track.
2494   //
2495   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2496   //-----------------------------------------------------------------
2497   Int_t num_of_clusters=fClusters.GetEntriesFast();
2498   for (Int_t i=0; i<num_of_clusters; i++) {
2499     //if (i<=14) continue;
2500     AliTPCcluster *c=(AliTPCcluster*)fClusters.UncheckedAt(i);
2501     c->Use();   
2502   }
2503 }
2504
2505 //_____________________________________________________________________________
2506 Double_t AliTPCtrack::GetPredictedChi2(const AliTPCcluster *c) const 
2507 {
2508   //-----------------------------------------------------------------
2509   // This function calculates a predicted chi2 increment.
2510   //
2511   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2512   //-----------------------------------------------------------------
2513   TMatrix H(2,5); H.UnitMatrix();
2514   TVector m(2);   m(0)=c->fY; m(1)=c->fZ; 
2515   TMatrix V(2,2); V(0,0)=c->fSigmaY2; V(0,1)=0.; V(1,0)=0.; V(1,1)=c->fSigmaZ2;
2516   TVector res=x;  res*=H; res-=m; //res*=-1; 
2517   TMatrix tmp(H,TMatrix::kMult,C);
2518   TMatrix R(tmp,TMatrix::kMult,TMatrix(TMatrix::kTransposed,H)); R+=V;
2519   
2520   Double_t det=(Double_t)R(0,0)*R(1,1) - (Double_t)R(0,1)*R(1,0);
2521   if (TMath::Abs(det) < 1.e-10) {
2522     if (*this>4) cerr<<*this<<" AliTPCtrack warning: Singular matrix !\n";
2523     return 1e10;
2524   }
2525   R(0,1)=R(0,0); R(0,0)=R(1,1); R(1,1)=R(0,1); 
2526   R(1,0)*=-1; R(0,1)=R(1,0);
2527   R*=1./det;
2528   
2529   //R.Invert();
2530   
2531   TVector r=res;
2532   res*=R;
2533   return r*res;
2534 }
2535
2536 //_____________________________________________________________________________
2537 struct S { Int_t lab; Int_t max; };
2538 Int_t AliTPCtrack::GetLabel(Int_t nrows) const 
2539 {
2540   //-----------------------------------------------------------------
2541   // This function returns the track label. If label<0, this track is fake.
2542   //
2543   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2544   //-----------------------------------------------------------------
2545   Int_t num_of_clusters=fClusters.GetEntriesFast();
2546   S *s=new S[num_of_clusters];
2547   Int_t i;
2548   for (i=0; i<num_of_clusters; i++) s[i].lab=s[i].max=0;
2549   
2550   Int_t lab=123456789;
2551   for (i=0; i<num_of_clusters; i++) {
2552     AliTPCcluster *c=(AliTPCcluster*)fClusters.UncheckedAt(i);
2553     lab=TMath::Abs(c->fTracks[0]);
2554     Int_t j;
2555     for (j=0; j<num_of_clusters; j++)
2556       if (s[j].lab==lab || s[j].max==0) break;
2557     s[j].lab=lab;
2558     s[j].max++;
2559   }
2560   
2561   Int_t max=0;
2562   for (i=0; i<num_of_clusters; i++) 
2563     if (s[i].max>max) {max=s[i].max; lab=s[i].lab;}
2564     
2565   delete[] s;
2566   
2567   for (i=0; i<num_of_clusters; i++) {
2568     AliTPCcluster *c=(AliTPCcluster*)fClusters.UncheckedAt(i);
2569     if (TMath::Abs(c->fTracks[1]) == lab ||
2570         TMath::Abs(c->fTracks[2]) == lab ) max++;
2571   }
2572   
2573   if (1.-Float_t(max)/num_of_clusters > 0.10) return -lab;
2574   
2575   Int_t tail=Int_t(0.08*nrows);
2576   if (num_of_clusters < tail) return lab;
2577   
2578   max=0;
2579   for (i=1; i<=tail; i++) {
2580     AliTPCcluster *c=(AliTPCcluster*)fClusters.UncheckedAt(num_of_clusters-i);
2581     if (lab == TMath::Abs(c->fTracks[0]) ||
2582         lab == TMath::Abs(c->fTracks[1]) ||
2583         lab == TMath::Abs(c->fTracks[2])) max++;
2584   }
2585   if (max < Int_t(0.5*tail)) return -lab;
2586   
2587   return lab;
2588 }
2589
2590 //_____________________________________________________________________________
2591 void AliTPCtrack::GetPxPyPz(Double_t& px, Double_t& py, Double_t& pz) const 
2592 {
2593   //-----------------------------------------------------------------
2594   // This function returns reconstructed track momentum in the global system.
2595   //
2596   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2597   //-----------------------------------------------------------------
2598   Double_t pt=TMath::Abs(GetPt()); // GeV/c
2599   Double_t r=x(2)*fX-x(3);
2600   Double_t y0=x(0) + sqrt(1.- r*r)/x(2);
2601   px=-pt*(x(0)-y0)*x(2);    //cos(phi);
2602   py=-pt*(x(3)-fX*x(2));   //sin(phi);
2603   pz=pt*x(4);
2604   Double_t tmp=px*TMath::Cos(fAlpha) - py*TMath::Sin(fAlpha);
2605   py=px*TMath::Sin(fAlpha) + py*TMath::Cos(fAlpha);
2606   px=tmp;  
2607 }
2608
2609 //_____________________________________________________________________________
2610 Double_t AliTPCtrack::GetdEdX(Double_t low, Double_t up) const {
2611   //-----------------------------------------------------------------
2612   // This funtion calculates dE/dX within the "low" and "up" cuts.
2613   //
2614   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2615   //-----------------------------------------------------------------
2616   Int_t ncl=fClusters.GetEntriesFast();
2617   Int_t n=0;
2618   Double_t *q=new Double_t[ncl];
2619   Int_t i;
2620   for (i=1; i<ncl; i++) { //Shall I think of this "i=1" ? (I.Belikov)
2621      AliTPCcluster *cl=(AliTPCcluster*)(fClusters.UncheckedAt(i));
2622      q[n++]=TMath::Abs(cl->fQ)/cl->fdEdX;
2623      if (cl->fSector<36) q[n-1]*=1.1;
2624   }
2625
2626   //stupid sorting
2627   Int_t swap;
2628   do {
2629     swap=0;
2630     for (i=0; i<n-1; i++) {
2631       if (q[i]<=q[i+1]) continue;
2632       Double_t tmp=q[i]; q[i]=q[i+1]; q[i+1]=tmp;
2633       swap++;
2634     }
2635   } while (swap);
2636
2637   Int_t nl=Int_t(low*n), nu=Int_t(up *n);
2638   Double_t dedx=0.;
2639   for (i=nl; i<=nu; i++) dedx += q[i];
2640   dedx /= (nu-nl+1);
2641   return dedx;
2642 }
2643
2644 //_________________________________________________________________________
2645 //
2646 // Classes for internal tracking use
2647 //_________________________________________________________________________
2648 void AliTPCRow::InsertCluster(const AliTPCcluster* c) {
2649   //-----------------------------------------------------------------------
2650   // Insert a cluster into this pad row in accordence with its y-coordinate
2651   //
2652   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2653   //-----------------------------------------------------------------------
2654   if (num_of_clusters==MAX_CLUSTER_PER_ROW) {
2655     cerr<<"AliTPCRow::InsertCluster(): Too many clusters !\n"; return;
2656   }
2657   if (num_of_clusters==0) {clusters[num_of_clusters++]=c; return;}
2658   Int_t i=Find(c->fY);
2659   memmove(clusters+i+1 ,clusters+i,(num_of_clusters-i)*sizeof(AliTPCcluster*));
2660   clusters[i]=c; num_of_clusters++;
2661 }
2662 //___________________________________________________________________
2663
2664 Int_t AliTPCRow::Find(Double_t y) const {
2665   //-----------------------------------------------------------------------
2666   // Return the index of the nearest cluster 
2667   //
2668   // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
2669   //-----------------------------------------------------------------------
2670   if (y <= clusters[0]->fY) return 0;
2671   if (y > clusters[num_of_clusters-1]->fY) return num_of_clusters;
2672   Int_t b=0, e=num_of_clusters-1, m=(b+e)/2;
2673   for (; b<e; m=(b+e)/2) {
2674     if (y > clusters[m]->fY) b=m+1;
2675     else e=m; 
2676   }
2677   return m;
2678 }
2679 //________________________________________________________________________
2680