]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TPC/AliTPC.cxx
Bug fixes, warnings only in case of debug option, more comments (P.Skowronski)
[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 /* $Id$ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //                                                                           //
20 //  Time Projection Chamber                                                  //
21 //  This class contains the basic functions for the Time Projection Chamber  //
22 //  detector. Functions specific to one particular geometry are              //
23 //  contained in the derived classes                                         //
24 //                                                                           //
25 //Begin_Html
26 /*
27 <img src="picts/AliTPCClass.gif">
28 */
29 //End_Html
30 //                                                                           //
31 //                                                                          //
32 ///////////////////////////////////////////////////////////////////////////////
33
34 //
35
36 #include <Riostream.h>
37 #include <stdlib.h>
38
39 #include <TFile.h>  
40 #include <TGeometry.h>
41 #include <TInterpreter.h>
42 #include <TMath.h>
43 #include <TMatrix.h>
44 #include <TNode.h>
45 #include <TObjectTable.h>
46 #include <TParticle.h>
47 #include <TROOT.h>
48 #include <TRandom.h>
49 #include <TSystem.h>     
50 #include <TTUBS.h>
51 #include <TTree.h>
52 #include <TVector.h>
53 #include <TVirtualMC.h>
54
55 #include "AliArrayBranch.h"
56 #include "AliClusters.h"
57 #include "AliComplexCluster.h"
58 #include "AliDigits.h"
59 #include "AliMagF.h"
60 #include "AliPoints.h"
61 #include "AliRun.h"
62 #include "AliRunLoader.h"
63 #include "AliSimDigits.h"
64 #include "AliTPC.h"
65 #include "AliTPC.h"
66 #include "AliTPCClustersArray.h"
67 #include "AliTPCClustersRow.h"
68 #include "AliTPCDigitsArray.h"
69 #include "AliTPCLoader.h"
70 #include "AliTPCPRF2D.h"
71 #include "AliTPCParamSR.h"
72 #include "AliTPCRF1D.h"
73 #include "AliTPCTrackHits.h"
74 #include "AliTPCTrackHitsV2.h"
75 #include "AliTPCcluster.h"
76 #include "AliTrackReference.h"
77
78
79 ClassImp(AliTPC) 
80
81 //_____________________________________________________________________________
82 // helper class for fast matrix and vector manipulation - no range checking
83 // origin - Marian Ivanov
84
85 class AliTPCFastMatrix : public TMatrix {
86 public :
87   AliTPCFastMatrix(Int_t row_lwb, Int_t row_upb, Int_t col_lwb, Int_t col_upb);
88   inline Float_t & UncheckedAt(Int_t rown, Int_t coln) const  {return  (fIndex[coln])[rown];} //fast acces   
89   inline Float_t   UncheckedAtFast(Int_t rown, Int_t coln) const  {return  (fIndex[coln])[rown];} //fast acces   
90 };
91
92 AliTPCFastMatrix::AliTPCFastMatrix(Int_t row_lwb, Int_t row_upb, Int_t col_lwb, Int_t col_upb):
93   TMatrix(row_lwb, row_upb,col_lwb,col_upb)
94    {
95    };
96 //_____________________________________________________________________________
97 class AliTPCFastVector : public TVector {
98 public :
99   AliTPCFastVector(Int_t size);
100   virtual ~AliTPCFastVector(){;}
101   inline Float_t & UncheckedAt(Int_t index) const  {return  fElements[index];} //fast acces  
102   
103 };
104
105 AliTPCFastVector::AliTPCFastVector(Int_t size):TVector(size){
106 };
107
108 //_____________________________________________________________________________
109 AliTPC::AliTPC()
110 {
111   //
112   // Default constructor
113   //
114   fIshunt   = 0;
115   fHits     = 0;
116   fDigits   = 0;
117   fNsectors = 0;
118   fDigitsArray = 0;
119   fClustersArray = 0;
120   fDefaults = 0;
121   fTrackHits = 0; 
122   fTrackHitsOld = 0;   
123   fHitType = 2; //default CONTAINERS - based on ROOT structure 
124   fTPCParam = 0;    
125   fNoiseTable = 0;
126   fActiveSectors =0;
127
128 }
129  
130 //_____________________________________________________________________________
131 AliTPC::AliTPC(const char *name, const char *title)
132       : AliDetector(name,title)
133 {
134   //
135   // Standard constructor
136   //
137
138   //
139   // Initialise arrays of hits and digits 
140   fHits     = new TClonesArray("AliTPChit",  176);
141   gAlice->AddHitList(fHits); 
142   fDigitsArray = 0;
143   fClustersArray= 0;
144   fDefaults = 0;
145   //
146   fTrackHits = new AliTPCTrackHitsV2;  
147   fTrackHits->SetHitPrecision(0.002);
148   fTrackHits->SetStepPrecision(0.003);  
149   fTrackHits->SetMaxDistance(100);
150
151   fTrackHitsOld = new AliTPCTrackHits;  //MI - 13.09.2000
152   fTrackHitsOld->SetHitPrecision(0.002);
153   fTrackHitsOld->SetStepPrecision(0.003);  
154   fTrackHitsOld->SetMaxDistance(100); 
155
156   fNoiseTable =0;
157
158   fHitType = 2;
159   fActiveSectors = 0;
160   //
161   // Initialise counters
162   fNsectors = 0;
163
164   //
165   fIshunt     =  0;
166   //
167   // Initialise color attributes
168   SetMarkerColor(kYellow);
169
170   //
171   //  Set TPC parameters
172   //
173
174
175   if (!strcmp(title,"Default")) {       
176     fTPCParam = new AliTPCParamSR;
177   } else {
178     cerr<<"AliTPC warning: in Config.C you must set non-default parameters\n";
179     fTPCParam=0;
180   }
181
182 }
183
184 //_____________________________________________________________________________
185 AliTPC::~AliTPC()
186 {
187   //
188   // TPC destructor
189   //
190
191   fIshunt   = 0;
192   delete fHits;
193   delete fDigits;
194   delete fTPCParam;
195   delete fTrackHits; //MI 15.09.2000
196   delete fTrackHitsOld; //MI 10.12.2001
197   if (fNoiseTable) delete [] fNoiseTable;
198
199 }
200
201 //_____________________________________________________________________________
202 void AliTPC::AddHit(Int_t track, Int_t *vol, Float_t *hits)
203 {
204   //
205   // Add a hit to the list
206   //
207   //  TClonesArray &lhits = *fHits;
208   //  new(lhits[fNhits++]) AliTPChit(fIshunt,track,vol,hits);
209   if (fHitType&1){
210     TClonesArray &lhits = *fHits;
211     new(lhits[fNhits++]) AliTPChit(fIshunt,track,vol,hits);
212   }
213   if (fHitType>1)
214    AddHit2(track,vol,hits);
215 }
216
217 //_____________________________________________________________________________
218 void AliTPC::BuildGeometry()
219 {
220
221   //
222   // Build TPC ROOT TNode geometry for the event display
223   //
224   TNode *nNode, *nTop;
225   TTUBS *tubs;
226   Int_t i;
227   const int kColorTPC=19;
228   char name[5], title[25];
229   const Double_t kDegrad=TMath::Pi()/180;
230   const Double_t kRaddeg=180./TMath::Pi();
231
232
233   Float_t innerOpenAngle = fTPCParam->GetInnerAngle();
234   Float_t outerOpenAngle = fTPCParam->GetOuterAngle();
235
236   Float_t innerAngleShift = fTPCParam->GetInnerAngleShift();
237   Float_t outerAngleShift = fTPCParam->GetOuterAngleShift();
238
239   Int_t nLo = fTPCParam->GetNInnerSector()/2;
240   Int_t nHi = fTPCParam->GetNOuterSector()/2;  
241
242   const Double_t kloAng = (Double_t)TMath::Nint(innerOpenAngle*kRaddeg);
243   const Double_t khiAng = (Double_t)TMath::Nint(outerOpenAngle*kRaddeg);
244   const Double_t kloAngSh = (Double_t)TMath::Nint(innerAngleShift*kRaddeg);
245   const Double_t khiAngSh = (Double_t)TMath::Nint(outerAngleShift*kRaddeg);  
246
247
248   const Double_t kloCorr = 1/TMath::Cos(0.5*kloAng*kDegrad);
249   const Double_t khiCorr = 1/TMath::Cos(0.5*khiAng*kDegrad);
250
251   Double_t rl,ru;
252   
253
254   //
255   // Get ALICE top node
256   //
257
258   nTop=gAlice->GetGeometry()->GetNode("alice");
259
260   //  inner sectors
261
262   rl = fTPCParam->GetInnerRadiusLow();
263   ru = fTPCParam->GetInnerRadiusUp();
264  
265
266   for(i=0;i<nLo;i++) {
267     sprintf(name,"LS%2.2d",i);
268     name[4]='\0';
269     sprintf(title,"TPC low sector %3d",i);
270     title[24]='\0';
271     
272     tubs = new TTUBS(name,title,"void",rl*kloCorr,ru*kloCorr,250.,
273                      kloAng*(i-0.5)+kloAngSh,kloAng*(i+0.5)+kloAngSh);
274     tubs->SetNumberOfDivisions(1);
275     nTop->cd();
276     nNode = new TNode(name,title,name,0,0,0,"");
277     nNode->SetLineColor(kColorTPC);
278     fNodes->Add(nNode);
279   }
280
281   // Outer sectors
282
283   rl = fTPCParam->GetOuterRadiusLow();
284   ru = fTPCParam->GetOuterRadiusUp();
285
286   for(i=0;i<nHi;i++) {
287     sprintf(name,"US%2.2d",i);
288     name[4]='\0';
289     sprintf(title,"TPC upper sector %d",i);
290     title[24]='\0';
291     tubs = new TTUBS(name,title,"void",rl*khiCorr,ru*khiCorr,250,
292                      khiAng*(i-0.5)+khiAngSh,khiAng*(i+0.5)+khiAngSh);
293     tubs->SetNumberOfDivisions(1);
294     nTop->cd();
295     nNode = new TNode(name,title,name,0,0,0,"");
296     nNode->SetLineColor(kColorTPC);
297     fNodes->Add(nNode);
298   }
299
300 }    
301
302 //_____________________________________________________________________________
303 Int_t AliTPC::DistancetoPrimitive(Int_t , Int_t )
304 {
305   //
306   // Calculate distance from TPC to mouse on the display
307   // Dummy procedure
308   //
309   return 9999;
310 }
311
312 void AliTPC::Clusters2Tracks() 
313  {
314   //-----------------------------------------------------------------
315   // This is a track finder.
316   //-----------------------------------------------------------------
317   Error("Clusters2Tracks",
318   "Dummy function !  Call AliTPCtracker::Clusters2Tracks(...) instead !");
319  }
320
321 //_____________________________________________________________________________
322 void AliTPC::CreateMaterials()
323 {
324   //-----------------------------------------------
325   // Create Materials for for TPC simulations
326   //-----------------------------------------------
327
328   //-----------------------------------------------------------------
329   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
330   //-----------------------------------------------------------------
331
332   Int_t iSXFLD=gAlice->Field()->Integ();
333   Float_t sXMGMX=gAlice->Field()->Max();
334
335   Float_t amat[5]; // atomic numbers
336   Float_t zmat[5]; // z
337   Float_t wmat[5]; // proportions
338
339   Float_t density;
340   Float_t apure[2];
341
342
343   //***************** Gases *************************
344   
345   //-------------------------------------------------
346   // pure gases
347   //-------------------------------------------------
348
349   // Neon
350
351
352   amat[0]= 20.18;
353   zmat[0]= 10.;  
354   density = 0.0009;
355  
356   apure[0]=amat[0];
357
358   AliMaterial(20,"Ne",amat[0],zmat[0],density,999.,999.);
359
360   // Argon
361
362   amat[0]= 39.948;
363   zmat[0]= 18.;  
364   density = 0.001782;  
365
366   apure[1]=amat[0];
367
368   AliMaterial(21,"Ar",amat[0],zmat[0],density,999.,999.);
369  
370
371   //--------------------------------------------------------------
372   // gases - compounds
373   //--------------------------------------------------------------
374
375   Float_t amol[3];
376
377   // CO2
378
379   amat[0]=12.011;
380   amat[1]=15.9994;
381
382   zmat[0]=6.;
383   zmat[1]=8.;
384
385   wmat[0]=1.;
386   wmat[1]=2.;
387
388   density=0.001977;
389
390   amol[0] = amat[0]*wmat[0]+amat[1]*wmat[1];
391
392   AliMixture(10,"CO2",amat,zmat,density,-2,wmat);
393   
394   // CF4
395
396   amat[0]=12.011;
397   amat[1]=18.998;
398
399   zmat[0]=6.;
400   zmat[1]=9.;
401  
402   wmat[0]=1.;
403   wmat[1]=4.;
404  
405   density=0.003034;
406
407   amol[1] = amat[0]*wmat[0]+amat[1]*wmat[1];
408
409   AliMixture(11,"CF4",amat,zmat,density,-2,wmat); 
410
411
412   // CH4
413
414   amat[0]=12.011;
415   amat[1]=1.;
416
417   zmat[0]=6.;
418   zmat[1]=1.;
419
420   wmat[0]=1.;
421   wmat[1]=4.;
422
423   density=0.000717;
424
425   amol[2] = amat[0]*wmat[0]+amat[1]*wmat[1];
426
427   AliMixture(12,"CH4",amat,zmat,density,-2,wmat);
428
429   //----------------------------------------------------------------
430   // gases - mixtures, ID >= 20 pure gases, <= 10 ID < 20 -compounds
431   //----------------------------------------------------------------
432
433   char namate[21]; 
434   density = 0.;
435   Float_t am=0;
436   Int_t nc;
437   Float_t rho,absl,X0,buf[1];
438   Int_t nbuf;
439   Float_t a,z;
440
441   for(nc = 0;nc<fNoComp;nc++)
442     {
443     
444       // retrive material constants
445       
446       gMC->Gfmate((*fIdmate)[fMixtComp[nc]],namate,a,z,rho,X0,absl,buf,nbuf);
447
448       amat[nc] = a;
449       zmat[nc] = z;
450
451       Int_t nnc = (fMixtComp[nc]>=20) ? fMixtComp[nc]%20 : fMixtComp[nc]%10;
452  
453       am += fMixtProp[nc]*((fMixtComp[nc]>=20) ? apure[nnc] : amol[nnc]); 
454       density += fMixtProp[nc]*rho;  // density of the mixture
455       
456     }
457
458   // mixture proportions by weight!
459
460   for(nc = 0;nc<fNoComp;nc++)
461     {
462
463       Int_t nnc = (fMixtComp[nc]>=20) ? fMixtComp[nc]%20 : fMixtComp[nc]%10;
464
465       wmat[nc] = fMixtProp[nc]*((fMixtComp[nc]>=20) ? 
466                  apure[nnc] : amol[nnc])/am;
467
468     } 
469
470   // Drift gases 1 - nonsensitive, 2 - sensitive
471
472   AliMixture(31,"Drift gas 1",amat,zmat,density,fNoComp,wmat);
473   AliMixture(32,"Drift gas 2",amat,zmat,density,fNoComp,wmat);
474
475
476   // Air
477
478   amat[0] = 14.61;
479   zmat[0] = 7.3;
480   density = 0.001205;
481
482   AliMaterial(24,"Air",amat[0],zmat[0],density,999.,999.); 
483
484
485   //----------------------------------------------------------------------
486   //               solid materials
487   //----------------------------------------------------------------------
488
489
490   // Kevlar C14H22O2N2
491
492   amat[0] = 12.011;
493   amat[1] = 1.;
494   amat[2] = 15.999;
495   amat[3] = 14.006;
496
497   zmat[0] = 6.;
498   zmat[1] = 1.;
499   zmat[2] = 8.;
500   zmat[3] = 7.;
501
502   wmat[0] = 14.;
503   wmat[1] = 22.;
504   wmat[2] = 2.;
505   wmat[3] = 2.;
506
507   density = 1.45;
508
509   AliMixture(34,"Kevlar",amat,zmat,density,-4,wmat);  
510
511   // NOMEX
512
513   amat[0] = 12.011;
514   amat[1] = 1.;
515   amat[2] = 15.999;
516   amat[3] = 14.006;
517
518   zmat[0] = 6.;
519   zmat[1] = 1.;
520   zmat[2] = 8.;
521   zmat[3] = 7.;
522
523   wmat[0] = 14.;
524   wmat[1] = 22.;
525   wmat[2] = 2.;
526   wmat[3] = 2.;
527
528   density = 0.03;
529
530   
531   AliMixture(35,"NOMEX",amat,zmat,density,-4,wmat);
532
533   // Makrolon C16H18O3
534
535   amat[0] = 12.011;
536   amat[1] = 1.;
537   amat[2] = 15.999;
538
539   zmat[0] = 6.;
540   zmat[1] = 1.;
541   zmat[2] = 8.;
542
543   wmat[0] = 16.;
544   wmat[1] = 18.;
545   wmat[2] = 3.;
546   
547   density = 1.2;
548
549   AliMixture(36,"Makrolon",amat,zmat,density,-3,wmat);
550   
551   // Mylar C5H4O2
552
553   amat[0]=12.011;
554   amat[1]=1.;
555   amat[2]=15.9994;
556
557   zmat[0]=6.;
558   zmat[1]=1.;
559   zmat[2]=8.;
560
561   wmat[0]=5.;
562   wmat[1]=4.;
563   wmat[2]=2.; 
564
565   density = 1.39;
566   
567   AliMixture(37, "Mylar",amat,zmat,density,-3,wmat); 
568
569   // SiO2 - used later for the glass fiber
570
571   amat[0]=28.086;
572   amat[1]=15.9994;
573
574   zmat[0]=14.;
575   zmat[1]=8.;
576
577   wmat[0]=1.;
578   wmat[1]=2.;
579
580
581   AliMixture(38,"SiO2",amat,zmat,2.2,-2,wmat); //SiO2 - quartz (rho=2.2)
582
583   // Al
584
585   amat[0] = 26.98;
586   zmat[0] = 13.;
587
588   density = 2.7;
589
590   AliMaterial(40,"Al",amat[0],zmat[0],density,999.,999.);
591
592   // Si
593
594   amat[0] = 28.086;
595   zmat[0] = 14.;
596
597   density = 2.33;
598
599   AliMaterial(41,"Si",amat[0],zmat[0],density,999.,999.);
600
601   // Cu
602
603   amat[0] = 63.546;
604   zmat[0] = 29.;
605
606   density = 8.96;
607
608   AliMaterial(42,"Cu",amat[0],zmat[0],density,999.,999.);
609
610   // Tedlar C2H3F
611
612   amat[0] = 12.011;
613   amat[1] = 1.;
614   amat[2] = 18.998;
615
616   zmat[0] = 6.;
617   zmat[1] = 1.;
618   zmat[2] = 9.;
619
620   wmat[0] = 2.;
621   wmat[1] = 3.; 
622   wmat[2] = 1.;
623
624   density = 1.71;
625
626   AliMixture(43, "Tedlar",amat,zmat,density,-3,wmat);  
627
628
629   // Plexiglas  C5H8O2
630
631   amat[0]=12.011;
632   amat[1]=1.;
633   amat[2]=15.9994;
634
635   zmat[0]=6.;
636   zmat[1]=1.;
637   zmat[2]=8.;
638
639   wmat[0]=5.;
640   wmat[1]=8.;
641   wmat[2]=2.;
642
643   density=1.18;
644
645   AliMixture(44,"Plexiglas",amat,zmat,density,-3,wmat);
646
647   // Epoxy - C14 H20 O3
648
649   
650   amat[0]=12.011;
651   amat[1]=1.;
652   amat[2]=15.9994;
653
654   zmat[0]=6.;
655   zmat[1]=1.;
656   zmat[2]=8.;
657
658   wmat[0]=14.;
659   wmat[1]=20.;
660   wmat[2]=3.;
661
662   density=1.25;
663
664   AliMixture(45,"Epoxy",amat,zmat,density,-3,wmat);
665
666   // Carbon
667
668   amat[0]=12.011;
669   zmat[0]=6.;
670   density= 2.265;
671
672   AliMaterial(46,"C",amat[0],zmat[0],density,999.,999.);
673
674   // get epoxy
675
676   gMC->Gfmate((*fIdmate)[45],namate,amat[1],zmat[1],rho,X0,absl,buf,nbuf);
677
678   // Carbon fiber
679
680   wmat[0]=0.644; // by weight!
681   wmat[1]=0.356;
682
683   density=0.5*(1.25+2.265);
684
685   AliMixture(47,"Cfiber",amat,zmat,density,2,wmat);
686
687   // get SiO2
688
689   gMC->Gfmate((*fIdmate)[38],namate,amat[0],zmat[0],rho,X0,absl,buf,nbuf); 
690
691   wmat[0]=0.725; // by weight!
692   wmat[1]=0.275;
693
694   density=1.7;
695
696   AliMixture(39,"G10",amat,zmat,density,2,wmat);
697
698  
699
700
701   //----------------------------------------------------------
702   // tracking media for gases
703   //----------------------------------------------------------
704
705   AliMedium(0, "Air", 24, 0, iSXFLD, sXMGMX, 10., 999., .1, .01, .1);
706   AliMedium(1, "Drift gas 1", 31, 0, iSXFLD, sXMGMX, 10., 999.,.1,.001, .001);
707   AliMedium(2, "Drift gas 2", 32, 1, iSXFLD, sXMGMX, 10., 999.,.1,.001, .001);
708   AliMedium(3,"CO2",10,0, iSXFLD, sXMGMX, 10., 999.,.1, .001, .001); 
709
710   //-----------------------------------------------------------  
711   // tracking media for solids
712   //-----------------------------------------------------------
713   
714   AliMedium(4,"Al",40,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
715   AliMedium(5,"Kevlar",34,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
716   AliMedium(6,"Nomex",35,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
717   AliMedium(7,"Makrolon",36,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
718   AliMedium(8,"Mylar",37,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
719   AliMedium(9,"Tedlar",43,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
720   AliMedium(10,"Cu",42,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
721   AliMedium(11,"Si",41,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
722   AliMedium(12,"G10",39,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
723   AliMedium(13,"Plexiglas",44,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
724   AliMedium(14,"Epoxy",45,0, iSXFLD, sXMGMX, 10., 999., .1, .0005, .001);
725   AliMedium(15,"Cfiber",47,0, iSXFLD, sXMGMX, 10., 999., .1, .001, .001);
726     
727 }
728
729 void AliTPC::GenerNoise(Int_t tablesize)
730 {
731   //
732   //Generate table with noise
733   //
734   if (fTPCParam==0) {
735     // error message
736     fNoiseDepth=0;
737     return;
738   }
739   if (fNoiseTable)  delete[] fNoiseTable;
740   fNoiseTable = new Float_t[tablesize];
741   fNoiseDepth = tablesize; 
742   fCurrentNoise =0; //!index of the noise in  the noise table 
743   
744   Float_t norm = fTPCParam->GetNoise()*fTPCParam->GetNoiseNormFac();
745   for (Int_t i=0;i<tablesize;i++) fNoiseTable[i]= gRandom->Gaus(0,norm);      
746 }
747
748 Float_t AliTPC::GetNoise()
749 {
750   // get noise from table
751   //  if ((fCurrentNoise%10)==0) 
752   //  fCurrentNoise= gRandom->Rndm()*fNoiseDepth;
753   if (fCurrentNoise>=fNoiseDepth) fCurrentNoise=0;
754   return fNoiseTable[fCurrentNoise++];
755   //gRandom->Gaus(0, fTPCParam->GetNoise()*fTPCParam->GetNoiseNormFac()); 
756 }
757
758
759 Bool_t  AliTPC::IsSectorActive(Int_t sec)
760 {
761   //
762   // check if the sector is active
763   if (!fActiveSectors) return kTRUE;
764   else return fActiveSectors[sec]; 
765 }
766
767 void    AliTPC::SetActiveSectors(Int_t * sectors, Int_t n)
768 {
769   // activate interesting sectors
770   SetTreeAddress();//just for security
771   if (fActiveSectors) delete [] fActiveSectors;
772   fActiveSectors = new Bool_t[fTPCParam->GetNSector()];
773   for (Int_t i=0;i<fTPCParam->GetNSector();i++) fActiveSectors[i]=kFALSE;
774   for (Int_t i=0;i<n;i++) 
775     if ((sectors[i]>=0) && sectors[i]<fTPCParam->GetNSector())  fActiveSectors[sectors[i]]=kTRUE;
776     
777 }
778
779 void    AliTPC::SetActiveSectors(Int_t flag)
780 {
781   //
782   // activate sectors which were hitted by tracks 
783   //loop over tracks
784   SetTreeAddress();//just for security
785   if (fHitType==0) return;  // if Clones hit - not short volume ID information
786   if (fActiveSectors) delete [] fActiveSectors;
787   fActiveSectors = new Bool_t[fTPCParam->GetNSector()];
788   if (flag) {
789     for (Int_t i=0;i<fTPCParam->GetNSector();i++) fActiveSectors[i]=kTRUE;
790     return;
791   }
792   for (Int_t i=0;i<fTPCParam->GetNSector();i++) fActiveSectors[i]=kFALSE;
793   TBranch * branch=0;
794   if (TreeH() == 0x0)
795    {
796      Fatal("SetActiveSectors","Can not find TreeH in folder");
797      return;
798    }
799   if (fHitType>1) branch = TreeH()->GetBranch("TPC2");
800   else branch = TreeH()->GetBranch("TPC");
801   Stat_t ntracks = TreeH()->GetEntries();
802   // loop over all hits
803   cout<<"\nAliTPC::SetActiveSectors():  Got "<<ntracks<<" tracks\n";
804   
805   for(Int_t track=0;track<ntracks;track++)
806    {
807     ResetHits();
808     //
809     if (fTrackHits && fHitType&4) {
810       TBranch * br1 = TreeH()->GetBranch("fVolumes");
811       TBranch * br2 = TreeH()->GetBranch("fNVolumes");
812       br1->GetEvent(track);
813       br2->GetEvent(track);
814       Int_t *volumes = fTrackHits->GetVolumes();
815       for (Int_t j=0;j<fTrackHits->GetNVolumes(); j++)
816         fActiveSectors[volumes[j]]=kTRUE;
817     }
818     
819     //
820     if (fTrackHitsOld && fHitType&2) {
821       TBranch * br = TreeH()->GetBranch("fTrackHitsInfo");
822       br->GetEvent(track);
823       AliObjectArray * ar = fTrackHitsOld->fTrackHitsInfo;
824       for (UInt_t j=0;j<ar->GetSize();j++){
825         fActiveSectors[((AliTrackHitsInfo*)ar->At(j))->fVolumeID] =kTRUE;
826       } 
827     }    
828   }
829   
830 }  
831
832
833
834
835 void AliTPC::Digits2Clusters(Int_t eventnumber)
836 {
837   //-----------------------------------------------------------------
838   // This is a simple cluster finder.
839   //-----------------------------------------------------------------
840   Error("Digits2Clusters",
841   "Dummy function !  Call AliTPCclusterer::Digits2Clusters(...) instead !");
842 }
843
844 extern Double_t SigmaY2(Double_t, Double_t, Double_t);
845 extern Double_t SigmaZ2(Double_t, Double_t);
846 //_____________________________________________________________________________
847 void AliTPC::Hits2Clusters(Int_t eventn)
848 {
849   //--------------------------------------------------------
850   // TPC simple cluster generator from hits
851   // obtained from the TPC Fast Simulator
852   // The point errors are taken from the parametrization
853   //--------------------------------------------------------
854
855   //-----------------------------------------------------------------
856   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
857   //-----------------------------------------------------------------
858   // Adopted to Marian's cluster data structure by I.Belikov, CERN,
859   // Jouri.Belikov@cern.ch
860   //----------------------------------------------------------------
861   
862   /////////////////////////////////////////////////////////////////////////////
863   //
864   //---------------------------------------------------------------------
865   //   ALICE TPC Cluster Parameters
866   //--------------------------------------------------------------------
867        
868   
869
870   // Cluster width in rphi
871   const Float_t kACrphi=0.18322;
872   const Float_t kBCrphi=0.59551e-3;
873   const Float_t kCCrphi=0.60952e-1;
874   // Cluster width in z
875   const Float_t kACz=0.19081;
876   const Float_t kBCz=0.55938e-3;
877   const Float_t kCCz=0.30428;
878
879
880   if (!fLoader) {
881      cerr<<"AliTPC::Hits2Clusters(): output file not open !\n";
882      return;
883   }
884
885   //if(fDefaults == 0) SetDefaults();
886
887   Float_t sigmaRphi,sigmaZ,clRphi,clZ;
888   //
889   TParticle *particle; // pointer to a given particle
890   AliTPChit *tpcHit; // pointer to a sigle TPC hit
891   Int_t sector;
892   Int_t ipart;
893   Float_t xyz[5];
894   Float_t pl,pt,tanth,rpad,ratio;
895   Float_t cph,sph;
896   
897   //---------------------------------------------------------------
898   //  Get the access to the tracks 
899   //---------------------------------------------------------------
900   
901   TTree *tH = TreeH();
902   if (tH == 0x0)
903    {
904      Fatal("Hits2Clusters","Can not find TreeH in folder");
905      return;
906    }
907   SetTreeAddress();
908   
909   Stat_t ntracks = tH->GetEntries();
910
911   //Switch to the output file
912   
913   if (fLoader->TreeR() == 0x0) fLoader->MakeTree("R");
914   
915   cout<<"fTPCParam->GetTitle() = "<<fTPCParam->GetTitle()<<endl;
916   
917   AliRunLoader* rl = (AliRunLoader*)fLoader->GetEventFolder()->FindObject(AliRunLoader::fgkRunLoaderName);
918   rl->CdGAFile();
919   //fTPCParam->Write(fTPCParam->GetTitle());
920
921   AliTPCClustersArray carray;
922   carray.Setup(fTPCParam);
923   carray.SetClusterType("AliTPCcluster");
924   carray.MakeTree(fLoader->TreeR());
925
926   Int_t nclusters=0; //cluster counter
927   
928   //------------------------------------------------------------
929   // Loop over all sectors (72 sectors for 20 deg
930   // segmentation for both lower and upper sectors)
931   // Sectors 0-35 are lower sectors, 0-17 z>0, 17-35 z<0
932   // Sectors 36-71 are upper sectors, 36-53 z>0, 54-71 z<0
933   //
934   // First cluster for sector 0 starts at "0"
935   //------------------------------------------------------------
936    
937   for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++){
938     //MI change
939     fTPCParam->AdjustCosSin(isec,cph,sph);
940     
941     //------------------------------------------------------------
942     // Loop over tracks
943     //------------------------------------------------------------
944     
945     for(Int_t track=0;track<ntracks;track++){
946       ResetHits();
947       tH->GetEvent(track);
948       //
949       //  Get number of the TPC hits
950       //     
951        tpcHit = (AliTPChit*)FirstHit(-1);
952
953       // Loop over hits
954       //
955        while(tpcHit){
956  
957          if (tpcHit->fQ == 0.) {
958            tpcHit = (AliTPChit*) NextHit();
959            continue; //information about track (I.Belikov)
960          }
961         sector=tpcHit->fSector; // sector number
962
963        if(sector != isec){
964          tpcHit = (AliTPChit*) NextHit();
965          continue; 
966        }
967         ipart=tpcHit->Track();
968         particle=gAlice->Particle(ipart);
969         pl=particle->Pz();
970         pt=particle->Pt();
971         if(pt < 1.e-9) pt=1.e-9;
972         tanth=pl/pt;
973         tanth = TMath::Abs(tanth);
974         rpad=TMath::Sqrt(tpcHit->X()*tpcHit->X() + tpcHit->Y()*tpcHit->Y());
975         ratio=0.001*rpad/pt; // pt must be in MeV/c - historical reason
976
977         //   space-point resolutions
978         
979         sigmaRphi=SigmaY2(rpad,tanth,pt);
980         sigmaZ   =SigmaZ2(rpad,tanth   );
981         
982         //   cluster widths
983         
984         clRphi=kACrphi-kBCrphi*rpad*tanth+kCCrphi*ratio*ratio;
985         clZ=kACz-kBCz*rpad*tanth+kCCz*tanth*tanth;
986         
987         // temporary protection
988         
989         if(sigmaRphi < 0.) sigmaRphi=0.4e-3;
990         if(sigmaZ < 0.) sigmaZ=0.4e-3;
991         if(clRphi < 0.) clRphi=2.5e-3;
992         if(clZ < 0.) clZ=2.5e-5;
993         
994         //
995         
996         //
997         // smearing --> rotate to the 1 (13) or to the 25 (49) sector,
998         // then the inaccuracy in a X-Y plane is only along Y (pad row)!
999         //
1000         Float_t xprim= tpcHit->X()*cph + tpcHit->Y()*sph;
1001         Float_t yprim=-tpcHit->X()*sph + tpcHit->Y()*cph;
1002         xyz[0]=gRandom->Gaus(yprim,TMath::Sqrt(sigmaRphi));   // y
1003           Float_t alpha=(isec < fTPCParam->GetNInnerSector()) ?
1004           fTPCParam->GetInnerAngle() : fTPCParam->GetOuterAngle();
1005           Float_t ymax=xprim*TMath::Tan(0.5*alpha);
1006           if (TMath::Abs(xyz[0])>ymax) xyz[0]=yprim; 
1007         xyz[1]=gRandom->Gaus(tpcHit->Z(),TMath::Sqrt(sigmaZ)); // z
1008           if (TMath::Abs(xyz[1])>fTPCParam->GetZLength()) xyz[1]=tpcHit->Z(); 
1009         xyz[2]=sigmaRphi;                                     // fSigmaY2
1010         xyz[3]=sigmaZ;                                        // fSigmaZ2
1011         xyz[4]=tpcHit->fQ;                                    // q
1012
1013         AliTPCClustersRow *clrow=carray.GetRow(sector,tpcHit->fPadRow);
1014         if (!clrow) clrow=carray.CreateRow(sector,tpcHit->fPadRow);     
1015
1016         Int_t tracks[3]={tpcHit->Track(), -1, -1};
1017         AliTPCcluster cluster(tracks,xyz);
1018
1019         clrow->InsertCluster(&cluster); nclusters++;
1020
1021         tpcHit = (AliTPChit*)NextHit();
1022         
1023
1024       } // end of loop over hits
1025
1026     }   // end of loop over tracks
1027
1028     Int_t nrows=fTPCParam->GetNRow(isec);
1029     for (Int_t irow=0; irow<nrows; irow++) {
1030         AliTPCClustersRow *clrow=carray.GetRow(isec,irow);
1031         if (!clrow) continue;
1032         carray.StoreRow(isec,irow);
1033         carray.ClearRow(isec,irow);
1034     }
1035
1036   } // end of loop over sectors  
1037
1038   cerr<<"Number of made clusters : "<<nclusters<<"                        \n";
1039   fLoader->WriteRecPoints("OVERWRITE");
1040   
1041   
1042 } // end of function
1043
1044 //_________________________________________________________________
1045 void AliTPC::Hits2ExactClustersSector(Int_t isec)
1046 {
1047   //--------------------------------------------------------
1048   //calculate exact cross point of track and given pad row
1049   //resulting values are expressed in "digit" coordinata
1050   //--------------------------------------------------------
1051
1052   //-----------------------------------------------------------------
1053   // Origin: Marian Ivanov  GSI Darmstadt, m.ivanov@gsi.de
1054   //-----------------------------------------------------------------
1055   //
1056   if (fClustersArray==0){    
1057     return;
1058   }
1059   //
1060   TParticle *particle; // pointer to a given particle
1061   AliTPChit *tpcHit; // pointer to a sigle TPC hit
1062   //  Int_t sector,nhits;
1063   Int_t ipart;
1064   const Int_t kcmaxhits=30000;
1065   AliTPCFastVector * xxxx = new AliTPCFastVector(kcmaxhits*4);
1066   AliTPCFastVector & xxx = *xxxx;
1067   Int_t maxhits = kcmaxhits;
1068   //construct array for each padrow
1069   for (Int_t i=0; i<fTPCParam->GetNRow(isec);i++) 
1070     fClustersArray->CreateRow(isec,i);
1071   
1072   //---------------------------------------------------------------
1073   //  Get the access to the tracks 
1074   //---------------------------------------------------------------
1075   
1076   TTree *tH = TreeH();
1077   if (tH == 0x0)
1078    {
1079      Fatal("Hits2Clusters","Can not find TreeH in folder");
1080      return;
1081    }
1082   SetTreeAddress();
1083
1084   Stat_t ntracks = tH->GetEntries();
1085   Int_t npart = gAlice->GetNtrack();
1086   //MI change
1087   TBranch * branch=0;
1088   if (fHitType>1) branch = tH->GetBranch("TPC2");
1089   else branch = tH->GetBranch("TPC");
1090
1091   //------------------------------------------------------------
1092   // Loop over tracks
1093   //------------------------------------------------------------
1094
1095   for(Int_t track=0;track<ntracks;track++){ 
1096     Bool_t isInSector=kTRUE;
1097     ResetHits();
1098      isInSector = TrackInVolume(isec,track);
1099     if (!isInSector) continue;
1100     //MI change
1101     branch->GetEntry(track); // get next track
1102     //
1103     //  Get number of the TPC hits and a pointer
1104     //  to the particles
1105     // Loop over hits
1106     //
1107     Int_t currentIndex=0;
1108     Int_t lastrow=-1;  //last writen row
1109
1110     //M.I. changes
1111
1112     tpcHit = (AliTPChit*)FirstHit(-1);
1113     while(tpcHit){
1114       
1115       Int_t sector=tpcHit->fSector; // sector number
1116       if(sector != isec){
1117         tpcHit = (AliTPChit*) NextHit();
1118         continue; 
1119       }
1120
1121       ipart=tpcHit->Track();
1122       if (ipart<npart) particle=gAlice->Particle(ipart);
1123       
1124       //find row number
1125
1126       Float_t  x[3]={tpcHit->X(),tpcHit->Y(),tpcHit->Z()};
1127       Int_t    index[3]={1,isec,0};
1128       Int_t    currentrow = fTPCParam->GetPadRow(x,index) ;     
1129       if (currentrow<0) {tpcHit = (AliTPChit*)NextHit(); continue;}
1130       if (lastrow<0) lastrow=currentrow;
1131       if (currentrow==lastrow){
1132         if ( currentIndex>=maxhits){
1133           maxhits+=kcmaxhits;
1134           xxx.ResizeTo(4*maxhits);
1135         }     
1136         xxx(currentIndex*4)=x[0];
1137         xxx(currentIndex*4+1)=x[1];
1138         xxx(currentIndex*4+2)=x[2];     
1139         xxx(currentIndex*4+3)=tpcHit->fQ;
1140         currentIndex++; 
1141       }
1142       else 
1143         if (currentIndex>2){
1144           Float_t sumx=0;
1145           Float_t sumx2=0;
1146           Float_t sumx3=0;
1147           Float_t sumx4=0;
1148           Float_t sumy=0;
1149           Float_t sumxy=0;
1150           Float_t sumx2y=0;
1151           Float_t sumz=0;
1152           Float_t sumxz=0;
1153           Float_t sumx2z=0;
1154           Float_t sumq=0;
1155           for (Int_t index=0;index<currentIndex;index++){
1156             Float_t x,x2,x3,x4;
1157             x=x2=x3=x4=xxx(index*4);
1158             x2*=x;
1159             x3*=x2;
1160             x4*=x3;
1161             sumx+=x;
1162             sumx2+=x2;
1163             sumx3+=x3;
1164             sumx4+=x4;
1165             sumy+=xxx(index*4+1);
1166             sumxy+=xxx(index*4+1)*x;
1167             sumx2y+=xxx(index*4+1)*x2;
1168             sumz+=xxx(index*4+2);
1169             sumxz+=xxx(index*4+2)*x;
1170             sumx2z+=xxx(index*4+2)*x2;   
1171             sumq+=xxx(index*4+3);
1172           }
1173           Float_t centralPad = (fTPCParam->GetNPads(isec,lastrow)-1)/2;
1174           Float_t det=currentIndex*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumx*sumx4-sumx2*sumx3)+
1175             sumx2*(sumx*sumx3-sumx2*sumx2);
1176           
1177           Float_t detay=sumy*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumxy*sumx4-sumx2y*sumx3)+
1178             sumx2*(sumxy*sumx3-sumx2y*sumx2);
1179           Float_t detaz=sumz*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumxz*sumx4-sumx2z*sumx3)+
1180             sumx2*(sumxz*sumx3-sumx2z*sumx2);
1181           
1182           Float_t detby=currentIndex*(sumxy*sumx4-sumx2y*sumx3)-sumy*(sumx*sumx4-sumx2*sumx3)+
1183             sumx2*(sumx*sumx2y-sumx2*sumxy);
1184           Float_t detbz=currentIndex*(sumxz*sumx4-sumx2z*sumx3)-sumz*(sumx*sumx4-sumx2*sumx3)+
1185             sumx2*(sumx*sumx2z-sumx2*sumxz);
1186           
1187           if (TMath::Abs(det)<0.00001){
1188              tpcHit = (AliTPChit*)NextHit();
1189             continue;
1190           }
1191         
1192           Float_t y=detay/det+centralPad;
1193           Float_t z=detaz/det;  
1194           Float_t by=detby/det; //y angle
1195           Float_t bz=detbz/det; //z angle
1196           sumy/=Float_t(currentIndex);
1197           sumz/=Float_t(currentIndex);
1198
1199           AliTPCClustersRow * row = (fClustersArray->GetRow(isec,lastrow));
1200           if (row!=0) {
1201             AliComplexCluster* cl = new((AliComplexCluster*)row->Append()) AliComplexCluster ;
1202             //    AliComplexCluster cl;
1203             cl->fX=z;
1204             cl->fY=y;
1205             cl->fQ=sumq;
1206             cl->fSigmaX2=bz;
1207             cl->fSigmaY2=by;
1208             cl->fTracks[0]=ipart;
1209           }
1210           currentIndex=0;
1211           lastrow=currentrow;
1212         } //end of calculating cluster for given row
1213         
1214         
1215       tpcHit = (AliTPChit*)NextHit();
1216     } // end of loop over hits
1217   }   // end of loop over tracks 
1218   //write padrows to tree 
1219   for (Int_t ii=0; ii<fTPCParam->GetNRow(isec);ii++) {
1220     fClustersArray->StoreRow(isec,ii);    
1221     fClustersArray->ClearRow(isec,ii);        
1222   }
1223   xxxx->Delete();
1224  
1225 }
1226
1227
1228
1229 //__
1230 void AliTPC::SDigits2Digits2(Int_t eventnumber)  
1231 {
1232   //create digits from summable digits
1233   GenerNoise(500000); //create teble with noise
1234
1235   //conect tree with sSDigits
1236   TTree *t = fLoader->TreeS();
1237
1238   if (t == 0x0) 
1239    {
1240      fLoader->LoadSDigits("READ");
1241      t = fLoader->TreeS();
1242      if (t == 0x0)
1243       {
1244         Error("SDigits2Digits2","Can not get input TreeS");
1245         return;
1246       }
1247    }
1248   
1249   if (fLoader->TreeD() == 0x0) fLoader->MakeTree("D");
1250   
1251   AliSimDigits digarr, *dummy=&digarr;
1252   TBranch* sdb = t->GetBranch("Segment");
1253   if (sdb == 0x0)
1254    {
1255      Error("SDigits2Digits2","Can not find branch with segments in TreeS.");
1256      return;
1257    }  
1258
1259   sdb->SetAddress(&dummy);
1260       
1261   Stat_t nentries = t->GetEntries();
1262
1263   // set zero suppression
1264
1265   fTPCParam->SetZeroSup(2);
1266
1267   // get zero suppression
1268
1269   Int_t zerosup = fTPCParam->GetZeroSup();
1270
1271   //make tree with digits 
1272   
1273   AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
1274   arr->SetClass("AliSimDigits");
1275   arr->Setup(fTPCParam);
1276   arr->MakeTree(fLoader->TreeD());
1277   
1278   AliTPCParam * par = fTPCParam;
1279
1280   //Loop over segments of the TPC
1281
1282   for (Int_t n=0; n<nentries; n++) {
1283     t->GetEvent(n);
1284     Int_t sec, row;
1285     if (!par->AdjustSectorRow(digarr.GetID(),sec,row)) {
1286       cerr<<"AliTPC warning: invalid segment ID ! "<<digarr.GetID()<<endl;
1287       continue;
1288     }
1289     if (!IsSectorActive(sec)) 
1290      {
1291 //       cout<<n<<" NOT Active \n";
1292        continue;
1293      }
1294     else
1295      {
1296 //       cout<<n<<" Active \n";
1297      }
1298     AliSimDigits * digrow =(AliSimDigits*) arr->CreateRow(sec,row);
1299     Int_t nrows = digrow->GetNRows();
1300     Int_t ncols = digrow->GetNCols();
1301
1302     digrow->ExpandBuffer();
1303     digarr.ExpandBuffer();
1304     digrow->ExpandTrackBuffer();
1305     digarr.ExpandTrackBuffer();
1306
1307     
1308     Short_t * pamp0 = digarr.GetDigits();
1309     Int_t   * ptracks0 = digarr.GetTracks();
1310     Short_t * pamp1 = digrow->GetDigits();
1311     Int_t   * ptracks1 = digrow->GetTracks();
1312     Int_t  nelems =nrows*ncols;
1313     Int_t saturation = fTPCParam->GetADCSat();
1314     //use internal structure of the AliDigits - for speed reason
1315     //if you cahnge implementation
1316     //of the Alidigits - it must be rewriten -
1317     for (Int_t i= 0; i<nelems; i++){
1318       //      Float_t q = *pamp0;
1319       //q/=16.;  //conversion faktor
1320       //Float_t noise= GetNoise(); 
1321       //q+=noise;      
1322       //q= TMath::Nint(q);
1323       Float_t q = TMath::Nint(Float_t(*pamp0)/16.+GetNoise());
1324       if (q>zerosup){
1325         if (q>saturation) q=saturation;      
1326         *pamp1=(Short_t)q;
1327         //if (ptracks0[0]==0)
1328         //  ptracks1[0]=1;
1329         //else
1330         ptracks1[0]=ptracks0[0];        
1331         ptracks1[nelems]=ptracks0[nelems];
1332         ptracks1[2*nelems]=ptracks0[2*nelems];
1333       }
1334       pamp0++;
1335       pamp1++;
1336       ptracks0++;
1337       ptracks1++;        
1338     }
1339
1340     arr->StoreRow(sec,row);
1341     arr->ClearRow(sec,row);   
1342     // cerr<<sec<<"\t"<<row<<"\n";   
1343   }  
1344
1345     
1346   //write results
1347   fLoader->WriteDigits("OVERWRITE");
1348    
1349   delete arr;
1350 }
1351 //__________________________________________________________________
1352 void AliTPC::SetDefaults(){
1353
1354    
1355    cerr<<"Setting default parameters...\n";
1356
1357   // Set response functions
1358
1359   //
1360   AliRunLoader* rl = (AliRunLoader*)fLoader->GetEventFolder()->FindObject(AliRunLoader::fgkRunLoaderName);
1361   rl->CdGAFile();
1362   AliTPCParamSR *param=(AliTPCParamSR*)gDirectory->Get("75x40_100x60");
1363   if(param){
1364     printf("You are using 2 pad-length geom hits with 3 pad-lenght geom digits...\n");
1365     delete param;
1366     param = new AliTPCParamSR();
1367   }
1368   else {
1369     param=(AliTPCParamSR*)gDirectory->Get("75x40_100x60_150x60");
1370   }
1371   if(!param){
1372     printf("No TPC parameters found\n");
1373     exit(4);
1374   }
1375
1376
1377   AliTPCPRF2D    * prfinner   = new AliTPCPRF2D;
1378   AliTPCPRF2D    * prfouter1   = new AliTPCPRF2D;
1379   AliTPCPRF2D    * prfouter2   = new AliTPCPRF2D;  
1380   AliTPCRF1D     * rf    = new AliTPCRF1D(kTRUE);
1381   rf->SetGauss(param->GetZSigma(),param->GetZWidth(),1.);
1382   rf->SetOffset(3*param->GetZSigma());
1383   rf->Update();
1384   
1385   TDirectory *savedir=gDirectory;
1386   TFile *f=TFile::Open("$ALICE_ROOT/TPC/AliTPCprf2d.root");
1387   if (!f->IsOpen()) { 
1388     cerr<<"Can't open $ALICE_ROOT/TPC/AliTPCprf2d.root !\n" ;
1389      exit(3);
1390   }
1391   prfinner->Read("prf_07504_Gati_056068_d02");
1392   prfouter1->Read("prf_10006_Gati_047051_d03");
1393   prfouter2->Read("prf_15006_Gati_047051_d03");  
1394   f->Close();
1395   savedir->cd();
1396
1397   param->SetInnerPRF(prfinner);
1398   param->SetOuter1PRF(prfouter1); 
1399   param->SetOuter2PRF(prfouter2);
1400   param->SetTimeRF(rf);
1401
1402   // set fTPCParam
1403
1404   SetParam(param);
1405
1406
1407   fDefaults = 1;
1408
1409 }
1410 //__________________________________________________________________  
1411 void AliTPC::Hits2Digits(Int_t eventnumber)  
1412
1413  //----------------------------------------------------
1414  // Loop over all sectors for a single event
1415  //----------------------------------------------------
1416   AliRunLoader* rl = (AliRunLoader*)fLoader->GetEventFolder()->FindObject(AliRunLoader::fgkRunLoaderName);
1417   rl->GetEvent(eventnumber);
1418   if (fLoader->TreeH() == 0x0)
1419    {
1420      if(fLoader->LoadHits())
1421       {
1422         Error("Hits2Digits","Can not load hits.");
1423       }
1424    }
1425   SetTreeAddress();
1426   
1427   if (fLoader->TreeD() == 0x0 ) 
1428    {
1429      fLoader->MakeTree("D");
1430      if (fLoader->TreeD() == 0x0 ) 
1431       {
1432        Error("Hits2Digits","Can not get TreeD");
1433        return;
1434       }
1435    }
1436
1437   if(fDefaults == 0) SetDefaults();  // check if the parameters are set
1438   GenerNoise(500000); //create teble with noise
1439
1440   //setup TPCDigitsArray 
1441
1442   if(GetDigitsArray()) delete GetDigitsArray();
1443
1444   AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
1445   arr->SetClass("AliSimDigits");
1446   arr->Setup(fTPCParam);
1447
1448   arr->MakeTree(fLoader->TreeD());
1449   SetDigitsArray(arr);
1450
1451   fDigitsSwitch=0; // standard digits
1452
1453   cerr<<"Digitizing TPC -- normal digits...\n";
1454
1455  for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++) 
1456   if (IsSectorActive(isec)) 
1457    {
1458     if (fDebug) Info("Hits2Digits","Sector %d is active.",isec);
1459     Hits2DigitsSector(isec);
1460    }
1461   else
1462    {
1463     if (fDebug) Info("Hits2Digits","Sector %d is NOT active.",isec);
1464    }
1465
1466   fLoader->WriteDigits("OVERWRITE"); 
1467   
1468 //this line prevents the crash in the similar one
1469 //on the beginning of this method
1470 //destructor attempts to reset the tree, which is deleted by the loader
1471 //need to be redesign
1472  if(GetDigitsArray()) delete GetDigitsArray();
1473  SetDigitsArray(0x0);
1474   
1475 }
1476
1477 //__________________________________________________________________
1478 void AliTPC::Hits2SDigits2(Int_t eventnumber)  
1479
1480
1481   //-----------------------------------------------------------
1482   //   summable digits - 16 bit "ADC", no noise, no saturation
1483   //-----------------------------------------------------------
1484
1485  //----------------------------------------------------
1486  // Loop over all sectors for a single event
1487  //----------------------------------------------------
1488 //  AliRunLoader* rl = (AliRunLoader*)fLoader->GetEventFolder()->FindObject(AliRunLoader::fgkRunLoaderName);
1489
1490   AliRunLoader* rl = fLoader->GetRunLoader();
1491
1492   rl->GetEvent(eventnumber);
1493   if (fLoader->TreeH() == 0x0)
1494    {
1495      if(fLoader->LoadHits())
1496       {
1497         Error("Hits2Digits","Can not load hits.");
1498         return;
1499       }
1500    }
1501   SetTreeAddress();
1502
1503
1504   if (fLoader->TreeS() == 0x0 ) 
1505    {
1506      fLoader->MakeTree("S");
1507    }
1508   
1509   if(fDefaults == 0) SetDefaults();
1510   
1511   GenerNoise(500000); //create table with noise
1512   //setup TPCDigitsArray 
1513
1514   if(GetDigitsArray()) delete GetDigitsArray();
1515
1516   
1517   AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
1518   arr->SetClass("AliSimDigits");
1519   arr->Setup(fTPCParam);
1520   arr->MakeTree(fLoader->TreeS());
1521
1522   SetDigitsArray(arr);
1523
1524   cerr<<"Digitizing TPC -- summable digits...\n"; 
1525
1526   fDigitsSwitch=1; // summable digits
1527   
1528     // set zero suppression to "0"
1529
1530   fTPCParam->SetZeroSup(0);
1531
1532  for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++) 
1533   if (IsSectorActive(isec)) 
1534    {
1535 //    cout<<"Sector "<<isec<<" is active\n";
1536     Hits2DigitsSector(isec);
1537    }
1538
1539  fLoader->WriteSDigits("OVERWRITE");
1540
1541 //this line prevents the crash in the similar one
1542 //on the beginning of this method
1543 //destructor attempts to reset the tree, which is deleted by the loader
1544 //need to be redesign
1545  if(GetDigitsArray()) delete GetDigitsArray();
1546  SetDigitsArray(0x0);
1547 }
1548 //__________________________________________________________________
1549
1550 void AliTPC::Hits2SDigits()  
1551
1552
1553   //-----------------------------------------------------------
1554   //   summable digits - 16 bit "ADC", no noise, no saturation
1555   //-----------------------------------------------------------
1556
1557  //----------------------------------------------------
1558  // Loop over all sectors for a single event
1559  //----------------------------------------------------
1560   //MI change - for pp run
1561 //  Int_t eventnumber = gAlice->GetEvNumber();
1562 //  AliRunLoader* rl = (AliRunLoader*)fLoader->GetEventFolder()->FindObject(AliRunLoader::fgkRunLoaderName);
1563 //  rl->GetEvent(eventnumber);
1564 // 12/05/2003 This method is obsolete and not used. It should be redesingned
1565 // M.Kowalski
1566
1567   if (fLoader->TreeH() == 0x0)
1568    {
1569      if(fLoader->LoadHits())
1570       {
1571         Error("Hits2Digits","Can not load hits.");
1572       }
1573    }
1574   SetTreeAddress();
1575
1576   if(fDefaults == 0) SetDefaults();
1577   GenerNoise(500000); //create table with noise
1578
1579   //setup TPCDigitsArray 
1580
1581   if(GetDigitsArray()) delete GetDigitsArray();
1582
1583   if (fLoader->TreeS() == 0x0 ) 
1584    {
1585      fLoader->MakeTree("S");
1586    }
1587   
1588   AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
1589   arr->SetClass("AliSimDigits");
1590   arr->Setup(fTPCParam);
1591   arr->MakeTree(fLoader->TreeS());
1592   SetDigitsArray(arr);
1593
1594   cerr<<"Digitizing TPC -- summable digits...\n"; 
1595
1596   //  fDigitsSwitch=1; // summable digits  -for the moment direct
1597
1598   for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++) if (IsSectorActive(isec)) Hits2DigitsSector(isec);
1599
1600   // write results
1601   //
1602   cout<<"Why method TPC::Hits2SDigits writes digits and not sdigits? skowron\n";
1603   fLoader->WriteDigits("OVERWRITE");
1604 }
1605 //_____________________________________________________________________________
1606
1607 void AliTPC::Hits2DigitsSector(Int_t isec)
1608 {
1609   //-------------------------------------------------------------------
1610   // TPC conversion from hits to digits.
1611   //------------------------------------------------------------------- 
1612
1613   //-----------------------------------------------------------------
1614   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1615   //-----------------------------------------------------------------
1616
1617   //-------------------------------------------------------
1618   //  Get the access to the track hits
1619   //-------------------------------------------------------
1620
1621   // check if the parameters are set - important if one calls this method
1622   // directly, not from the Hits2Digits
1623
1624   if(fDefaults == 0) SetDefaults();
1625
1626   TTree *tH = TreeH(); // pointer to the hits tree
1627   if (tH == 0x0)
1628    {
1629      Fatal("Hits2DigitsSector","Can not find TreeH in folder");
1630      return;
1631    }
1632
1633   Stat_t ntracks = tH->GetEntries();
1634
1635   if( ntracks > 0){
1636
1637   //------------------------------------------- 
1638   //  Only if there are any tracks...
1639   //-------------------------------------------
1640
1641     TObjArray **row;
1642     
1643     //printf("*** Processing sector number %d ***\n",isec);
1644
1645       Int_t nrows =fTPCParam->GetNRow(isec);
1646
1647       row= new TObjArray* [nrows+2]; // 2 extra rows for cross talk
1648     
1649       MakeSector(isec,nrows,tH,ntracks,row);
1650
1651       //--------------------------------------------------------
1652       //   Digitize this sector, row by row
1653       //   row[i] is the pointer to the TObjArray of AliTPCFastVectors,
1654       //   each one containing electrons accepted on this
1655       //   row, assigned into tracks
1656       //--------------------------------------------------------
1657
1658       Int_t i;
1659
1660       if (fDigitsArray->GetTree()==0) 
1661        {
1662          Fatal("Hits2DigitsSector","Tree not set in fDigitsArray");
1663        }
1664
1665       for (i=0;i<nrows;i++){
1666
1667         AliDigits * dig = fDigitsArray->CreateRow(isec,i); 
1668
1669         DigitizeRow(i,isec,row);
1670
1671         fDigitsArray->StoreRow(isec,i);
1672
1673         Int_t ndig = dig->GetDigitSize(); 
1674         
1675         if (gDebug > 10) 
1676         printf("*** Sector, row, compressed digits %d %d %d ***\n",isec,i,ndig);        
1677         
1678         fDigitsArray->ClearRow(isec,i);  
1679
1680    
1681        } // end of the sector digitization
1682
1683       for(i=0;i<nrows+2;i++){
1684         row[i]->Delete();  
1685         delete row[i];   
1686       }
1687       
1688        delete [] row; // delete the array of pointers to TObjArray-s
1689         
1690   } // ntracks >0
1691
1692 } // end of Hits2DigitsSector
1693
1694
1695 //_____________________________________________________________________________
1696 void AliTPC::DigitizeRow(Int_t irow,Int_t isec,TObjArray **rows)
1697 {
1698   //-----------------------------------------------------------
1699   // Single row digitization, coupling from the neighbouring
1700   // rows taken into account
1701   //-----------------------------------------------------------
1702
1703   //-----------------------------------------------------------------
1704   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1705   // Modified: Marian Ivanov GSI Darmstadt, m.ivanov@gsi.de
1706   //-----------------------------------------------------------------
1707  
1708
1709   Float_t zerosup = fTPCParam->GetZeroSup();
1710   //  Int_t nrows =fTPCParam->GetNRow(isec);
1711   fCurrentIndex[1]= isec;
1712   
1713
1714   Int_t nofPads = fTPCParam->GetNPads(isec,irow);
1715   Int_t nofTbins = fTPCParam->GetMaxTBin();
1716   Int_t indexRange[4];
1717   //
1718   //  Integrated signal for this row
1719   //  and a single track signal
1720   //    
1721
1722   AliTPCFastMatrix *m1 = new AliTPCFastMatrix(0,nofPads,0,nofTbins); // integrated
1723   AliTPCFastMatrix *m2 = new AliTPCFastMatrix(0,nofPads,0,nofTbins); // single
1724   //
1725   AliTPCFastMatrix &total  = *m1;
1726
1727   //  Array of pointers to the label-signal list
1728
1729   Int_t nofDigits = nofPads*nofTbins; // number of digits for this row
1730   Float_t  **pList = new Float_t* [nofDigits]; 
1731
1732   Int_t lp;
1733   Int_t i1;   
1734   for(lp=0;lp<nofDigits;lp++)pList[lp]=0; // set all pointers to NULL
1735   //
1736   //calculate signal 
1737   //
1738   //Int_t row1 = TMath::Max(irow-fTPCParam->GetNCrossRows(),0);
1739   //Int_t row2 = TMath::Min(irow+fTPCParam->GetNCrossRows(),nrows-1);
1740   Int_t row1=irow;
1741   Int_t row2=irow+2; 
1742   for (Int_t row= row1;row<=row2;row++){
1743     Int_t nTracks= rows[row]->GetEntries();
1744     for (i1=0;i1<nTracks;i1++){
1745       fCurrentIndex[2]= row;
1746       fCurrentIndex[3]=irow+1;
1747       if (row==irow+1){
1748         m2->Zero();  // clear single track signal matrix
1749         Float_t trackLabel = GetSignal(rows[row],i1,m2,m1,indexRange); 
1750         GetList(trackLabel,nofPads,m2,indexRange,pList);
1751       }
1752       else   GetSignal(rows[row],i1,0,m1,indexRange);
1753     }
1754   }
1755          
1756   Int_t tracks[3];
1757
1758   AliDigits *dig = fDigitsArray->GetRow(isec,irow);
1759   Int_t gi=-1;
1760   Float_t fzerosup = zerosup+0.5;
1761   for(Int_t it=0;it<nofTbins;it++){
1762     Float_t *pq = &(total.UncheckedAt(0,it));
1763     for(Int_t ip=0;ip<nofPads;ip++){
1764       gi++;
1765       Float_t q=*pq;      
1766       pq++;
1767       if(fDigitsSwitch == 0){
1768         q+=GetNoise();
1769         if(q <=fzerosup) continue; // do not fill zeros
1770         q = TMath::Nint(q);
1771         if(q > fTPCParam->GetADCSat()) q = fTPCParam->GetADCSat();  // saturation
1772
1773       }
1774
1775       else {
1776        if(q <= 0.) continue; // do not fill zeros
1777        if(q>2000.) q=2000.;
1778        q *= 16.;
1779        q = TMath::Nint(q);
1780       }
1781
1782       //
1783       //  "real" signal or electronic noise (list = -1)?
1784       //    
1785
1786       for(Int_t j1=0;j1<3;j1++){
1787         tracks[j1] = (pList[gi]) ?(Int_t)(*(pList[gi]+j1)) : -2;
1788       }
1789
1790 //Begin_Html
1791 /*
1792   <A NAME="AliDigits"></A>
1793   using of AliDigits object
1794 */
1795 //End_Html
1796       dig->SetDigitFast((Short_t)q,it,ip);
1797       if (fDigitsArray->IsSimulated())
1798         {
1799          ((AliSimDigits*)dig)->SetTrackIDFast(tracks[0],it,ip,0);
1800          ((AliSimDigits*)dig)->SetTrackIDFast(tracks[1],it,ip,1);
1801          ((AliSimDigits*)dig)->SetTrackIDFast(tracks[2],it,ip,2);
1802         }
1803      
1804     
1805     } // end of loop over time buckets
1806   }  // end of lop over pads 
1807
1808   //
1809   //  This row has been digitized, delete nonused stuff
1810   //
1811
1812   for(lp=0;lp<nofDigits;lp++){
1813     if(pList[lp]) delete [] pList[lp];
1814   }
1815   
1816   delete [] pList;
1817
1818   delete m1;
1819   delete m2;
1820   //  delete m3;
1821
1822 } // end of DigitizeRow
1823
1824 //_____________________________________________________________________________
1825
1826 Float_t AliTPC::GetSignal(TObjArray *p1, Int_t ntr, 
1827              AliTPCFastMatrix *m1, AliTPCFastMatrix *m2,Int_t *indexRange)
1828 {
1829
1830   //---------------------------------------------------------------
1831   //  Calculates 2-D signal (pad,time) for a single track,
1832   //  returns a pointer to the signal matrix and the track label 
1833   //  No digitization is performed at this level!!!
1834   //---------------------------------------------------------------
1835
1836   //-----------------------------------------------------------------
1837   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1838   // Modified: Marian Ivanov 
1839   //-----------------------------------------------------------------
1840
1841   AliTPCFastVector *tv;
1842
1843   tv = (AliTPCFastVector*)p1->At(ntr); // pointer to a track
1844   AliTPCFastVector &v = *tv;
1845   
1846   Float_t label = v(0);
1847   Int_t centralPad = (fTPCParam->GetNPads(fCurrentIndex[1],fCurrentIndex[3]-1)-1)/2;
1848
1849   Int_t nElectrons = (tv->GetNrows()-1)/4;
1850   indexRange[0]=9999; // min pad
1851   indexRange[1]=-1; // max pad
1852   indexRange[2]=9999; //min time
1853   indexRange[3]=-1; // max time
1854
1855   AliTPCFastMatrix &signal = *m1;
1856   AliTPCFastMatrix &total = *m2;
1857   //
1858   //  Loop over all electrons
1859   //
1860   for(Int_t nel=0; nel<nElectrons; nel++){
1861     Int_t idx=nel*4;
1862     Float_t aval =  v(idx+4);
1863     Float_t eltoadcfac=aval*fTPCParam->GetTotalNormFac(); 
1864     Float_t xyz[3]={v(idx+1),v(idx+2),v(idx+3)};
1865     Int_t n = ((AliTPCParamSR*)fTPCParam)->CalcResponseFast(xyz,fCurrentIndex,fCurrentIndex[3]);
1866
1867     Int_t *index = fTPCParam->GetResBin(0);  
1868     Float_t *weight = & (fTPCParam->GetResWeight(0));
1869
1870     if (n>0) for (Int_t i =0; i<n; i++){       
1871        Int_t pad=index[1]+centralPad;  //in digit coordinates central pad has coordinate 0
1872
1873          if (pad>=0){
1874          Int_t time=index[2];    
1875          Float_t qweight = *(weight)*eltoadcfac;
1876          
1877          if (m1!=0) signal.UncheckedAt(pad,time)+=qweight;
1878          total.UncheckedAt(pad,time)+=qweight;
1879          if (indexRange[0]>pad) indexRange[0]=pad;
1880          if (indexRange[1]<pad) indexRange[1]=pad;
1881          if (indexRange[2]>time) indexRange[2]=time;
1882          if (indexRange[3]<time) indexRange[3]=time;
1883
1884          index+=3;
1885          weight++;      
1886
1887        }         
1888     }
1889   } // end of loop over electrons
1890   
1891   return label; // returns track label when finished
1892 }
1893
1894 //_____________________________________________________________________________
1895 void AliTPC::GetList(Float_t label,Int_t np,AliTPCFastMatrix *m,
1896                      Int_t *indexRange, Float_t **pList)
1897 {
1898   //----------------------------------------------------------------------
1899   //  Updates the list of tracks contributing to digits for a given row
1900   //----------------------------------------------------------------------
1901
1902   //-----------------------------------------------------------------
1903   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1904   //-----------------------------------------------------------------
1905
1906   AliTPCFastMatrix &signal = *m;
1907
1908   // lop over nonzero digits
1909
1910   for(Int_t it=indexRange[2];it<indexRange[3]+1;it++){
1911     for(Int_t ip=indexRange[0];ip<indexRange[1]+1;ip++){
1912
1913
1914         // accept only the contribution larger than 500 electrons (1/2 s_noise)
1915
1916         if(signal(ip,it)<0.5) continue; 
1917
1918
1919         Int_t globalIndex = it*np+ip; // globalIndex starts from 0!
1920         
1921         if(!pList[globalIndex]){
1922         
1923           // 
1924           // Create new list (6 elements - 3 signals and 3 labels),
1925           //
1926
1927           pList[globalIndex] = new Float_t [6];
1928
1929           // set list to -1 
1930
1931           *pList[globalIndex] = -1.;
1932           *(pList[globalIndex]+1) = -1.;
1933           *(pList[globalIndex]+2) = -1.;
1934           *(pList[globalIndex]+3) = -1.;
1935           *(pList[globalIndex]+4) = -1.;
1936           *(pList[globalIndex]+5) = -1.;
1937
1938
1939           *pList[globalIndex] = label;
1940           *(pList[globalIndex]+3) = signal(ip,it);
1941         }
1942         else{
1943
1944           // check the signal magnitude
1945
1946           Float_t highest = *(pList[globalIndex]+3);
1947           Float_t middle = *(pList[globalIndex]+4);
1948           Float_t lowest = *(pList[globalIndex]+5);
1949
1950           //
1951           //  compare the new signal with already existing list
1952           //
1953
1954           if(signal(ip,it)<lowest) continue; // neglect this track
1955
1956           //
1957
1958           if (signal(ip,it)>highest){
1959             *(pList[globalIndex]+5) = middle;
1960             *(pList[globalIndex]+4) = highest;
1961             *(pList[globalIndex]+3) = signal(ip,it);
1962
1963             *(pList[globalIndex]+2) = *(pList[globalIndex]+1);
1964             *(pList[globalIndex]+1) = *pList[globalIndex];
1965             *pList[globalIndex] = label;
1966           }
1967           else if (signal(ip,it)>middle){
1968             *(pList[globalIndex]+5) = middle;
1969             *(pList[globalIndex]+4) = signal(ip,it);
1970
1971             *(pList[globalIndex]+2) = *(pList[globalIndex]+1);
1972             *(pList[globalIndex]+1) = label;
1973           }
1974           else{
1975             *(pList[globalIndex]+5) = signal(ip,it);
1976             *(pList[globalIndex]+2) = label;
1977           }
1978         }
1979
1980     } // end of loop over pads
1981   } // end of loop over time bins
1982
1983
1984
1985 }//end of GetList
1986 //___________________________________________________________________
1987 void AliTPC::MakeSector(Int_t isec,Int_t nrows,TTree *TH,
1988                         Stat_t ntracks,TObjArray **row)
1989 {
1990
1991   //-----------------------------------------------------------------
1992   // Prepares the sector digitization, creates the vectors of
1993   // tracks for each row of this sector. The track vector
1994   // contains the track label and the position of electrons.
1995   //-----------------------------------------------------------------
1996
1997   //-----------------------------------------------------------------
1998   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1999   //-----------------------------------------------------------------
2000
2001   Float_t gasgain = fTPCParam->GetGasGain();
2002   Int_t i;
2003   Float_t xyz[4]; 
2004
2005   AliTPChit *tpcHit; // pointer to a sigle TPC hit    
2006   //MI change
2007   TBranch * branch=0;
2008   if (fHitType>1) branch = TH->GetBranch("TPC2");
2009   else branch = TH->GetBranch("TPC");
2010
2011  
2012   //----------------------------------------------
2013   // Create TObjArray-s, one for each row,
2014   // each TObjArray will store the AliTPCFastVectors
2015   // of electrons, one AliTPCFastVectors per each track.
2016   //---------------------------------------------- 
2017     
2018   Int_t *nofElectrons = new Int_t [nrows+2]; // electron counter for each row
2019   AliTPCFastVector **tracks = new AliTPCFastVector* [nrows+2]; //pointers to the track vectors
2020
2021   for(i=0; i<nrows+2; i++){
2022     row[i] = new TObjArray;
2023     nofElectrons[i]=0;
2024     tracks[i]=0;
2025   }
2026
2027  
2028
2029   //--------------------------------------------------------------------
2030   //  Loop over tracks, the "track" contains the full history
2031   //--------------------------------------------------------------------
2032
2033   Int_t previousTrack,currentTrack;
2034   previousTrack = -1; // nothing to store so far!
2035
2036   for(Int_t track=0;track<ntracks;track++){
2037     Bool_t isInSector=kTRUE;
2038     ResetHits();
2039     isInSector = TrackInVolume(isec,track);
2040     if (!isInSector) continue;
2041     //MI change
2042     branch->GetEntry(track); // get next track
2043
2044     //M.I. changes
2045
2046     tpcHit = (AliTPChit*)FirstHit(-1);
2047
2048     //--------------------------------------------------------------
2049     //  Loop over hits
2050     //--------------------------------------------------------------
2051
2052
2053     while(tpcHit){
2054       
2055       Int_t sector=tpcHit->fSector; // sector number
2056       if(sector != isec){
2057         tpcHit = (AliTPChit*) NextHit();
2058         continue; 
2059       }
2060
2061         currentTrack = tpcHit->Track(); // track number
2062
2063
2064         if(currentTrack != previousTrack){
2065                           
2066            // store already filled fTrack
2067               
2068            for(i=0;i<nrows+2;i++){
2069              if(previousTrack != -1){
2070                if(nofElectrons[i]>0){
2071                  AliTPCFastVector &v = *tracks[i];
2072                  v(0) = previousTrack;
2073                  tracks[i]->ResizeTo(4*nofElectrons[i]+1); // shrink if necessary
2074                  row[i]->Add(tracks[i]);                     
2075                }
2076                else{
2077                  delete tracks[i]; // delete empty AliTPCFastVector
2078                  tracks[i]=0;
2079                }
2080              }
2081
2082              nofElectrons[i]=0;
2083              tracks[i] = new AliTPCFastVector(481); // AliTPCFastVectors for the next fTrack
2084
2085            } // end of loop over rows
2086                
2087            previousTrack=currentTrack; // update track label 
2088         }
2089            
2090         Int_t qI = (Int_t) (tpcHit->fQ); // energy loss (number of electrons)
2091
2092        //---------------------------------------------------
2093        //  Calculate the electron attachment probability
2094        //---------------------------------------------------
2095
2096
2097         Float_t time = 1.e6*(fTPCParam->GetZLength()-TMath::Abs(tpcHit->Z()))
2098                                                         /fTPCParam->GetDriftV(); 
2099         // in microseconds!     
2100         Float_t attProb = fTPCParam->GetAttCoef()*
2101           fTPCParam->GetOxyCont()*time; //  fraction! 
2102    
2103         //-----------------------------------------------
2104         //  Loop over electrons
2105         //-----------------------------------------------
2106         Int_t index[3];
2107         index[1]=isec;
2108         for(Int_t nel=0;nel<qI;nel++){
2109           // skip if electron lost due to the attachment
2110           if((gRandom->Rndm(0)) < attProb) continue; // electron lost!
2111           xyz[0]=tpcHit->X();
2112           xyz[1]=tpcHit->Y();
2113           xyz[2]=tpcHit->Z();   
2114           //
2115           // protection for the nonphysical avalanche size (10**6 maximum)
2116           //  
2117           Double_t rn=TMath::Max(gRandom->Rndm(0),1.93e-22);
2118           xyz[3]= (Float_t) (-gasgain*TMath::Log(rn)); 
2119           index[0]=1;
2120           
2121           TransportElectron(xyz,index);    
2122           Int_t rowNumber;
2123           fTPCParam->GetPadRow(xyz,index); 
2124           // row 0 - cross talk from the innermost row
2125           // row fNRow+1 cross talk from the outermost row
2126           rowNumber = index[2]+1; 
2127           //transform position to local digit coordinates
2128           //relative to nearest pad row 
2129           if ((rowNumber<0)||rowNumber>fTPCParam->GetNRow(isec)+1) continue;
2130           Float_t x1,y1;
2131           if (isec <fTPCParam->GetNInnerSector()) {
2132             x1 = xyz[1]*fTPCParam->GetInnerPadPitchWidth();
2133             y1 = fTPCParam->GetYInner(rowNumber);
2134           }
2135           else{
2136             x1=xyz[1]*fTPCParam->GetOuterPadPitchWidth();
2137             y1 = fTPCParam->GetYOuter(rowNumber);
2138           }
2139           // gain inefficiency at the wires edges - linear
2140           x1=TMath::Abs(x1);
2141           y1-=1.;
2142           if(x1>y1) xyz[3]*=TMath::Max(1.e-6,(y1-x1+1.));       
2143        
2144           nofElectrons[rowNumber]++;      
2145           //----------------------------------
2146           // Expand vector if necessary
2147           //----------------------------------
2148           if(nofElectrons[rowNumber]>120){
2149             Int_t range = tracks[rowNumber]->GetNrows();
2150             if((nofElectrons[rowNumber])>(range-1)/4){
2151         
2152               tracks[rowNumber]->ResizeTo(range+400); // Add 100 electrons
2153             }
2154           }
2155           
2156           AliTPCFastVector &v = *tracks[rowNumber];
2157           Int_t idx = 4*nofElectrons[rowNumber]-3;
2158           Real_t * position = &(((AliTPCFastVector&)v).UncheckedAt(idx)); //make code faster
2159           memcpy(position,xyz,4*sizeof(Float_t));
2160  
2161         } // end of loop over electrons
2162
2163         tpcHit = (AliTPChit*)NextHit();
2164         
2165       } // end of loop over hits
2166     } // end of loop over tracks
2167
2168     //
2169     //   store remaining track (the last one) if not empty
2170     //
2171
2172      for(i=0;i<nrows+2;i++){
2173        if(nofElectrons[i]>0){
2174           AliTPCFastVector &v = *tracks[i];
2175           v(0) = previousTrack;
2176           tracks[i]->ResizeTo(4*nofElectrons[i]+1); // shrink if necessary
2177           row[i]->Add(tracks[i]);  
2178         }
2179         else{
2180           delete tracks[i];
2181           tracks[i]=0;
2182         }  
2183       }  
2184
2185           delete [] tracks;
2186           delete [] nofElectrons;
2187  
2188
2189 } // end of MakeSector
2190
2191
2192 //_____________________________________________________________________________
2193 void AliTPC::Init()
2194 {
2195   //
2196   // Initialise TPC detector after definition of geometry
2197   //
2198   Int_t i;
2199   //
2200   if(fDebug) {
2201     printf("\n%s: ",ClassName());
2202     for(i=0;i<35;i++) printf("*");
2203     printf(" TPC_INIT ");
2204     for(i=0;i<35;i++) printf("*");
2205     printf("\n%s: ",ClassName());
2206     //
2207     for(i=0;i<80;i++) printf("*");
2208     printf("\n");
2209   }
2210 }
2211
2212 //_____________________________________________________________________________
2213 void AliTPC::MakeBranch(Option_t* option)
2214 {
2215   //
2216   // Create Tree branches for the TPC.
2217   //
2218   if(GetDebug()) Info("MakeBranch","");
2219   Int_t buffersize = 4000;
2220   char branchname[10];
2221   sprintf(branchname,"%s",GetName());
2222   
2223   const char *h = strstr(option,"H");
2224
2225   if ( h && (fHitType<=1) && (fHits == 0x0)) fHits = new TClonesArray("AliTPChit", 176);//skowron 20.06.03
2226   
2227   AliDetector::MakeBranch(option);
2228
2229   const char *d = strstr(option,"D");
2230  
2231   if (fDigits   && fLoader->TreeD() && d) 
2232    {
2233       MakeBranchInTree(gAlice->TreeD(), branchname, &fDigits, buffersize, 0);
2234    }    
2235
2236   if (fHitType>1) MakeBranch2(option,0); // MI change 14.09.2000
2237 }
2238  
2239 //_____________________________________________________________________________
2240 void AliTPC::ResetDigits()
2241 {
2242   //
2243   // Reset number of digits and the digits array for this detector
2244   //
2245   fNdigits   = 0;
2246   if (fDigits)   fDigits->Clear();
2247 }
2248
2249 //_____________________________________________________________________________
2250 void AliTPC::SetSecAL(Int_t sec)
2251 {
2252   //---------------------------------------------------
2253   // Activate/deactivate selection for lower sectors
2254   //---------------------------------------------------
2255
2256   //-----------------------------------------------------------------
2257   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2258   //-----------------------------------------------------------------
2259   fSecAL = sec;
2260 }
2261
2262 //_____________________________________________________________________________
2263 void AliTPC::SetSecAU(Int_t sec)
2264 {
2265   //----------------------------------------------------
2266   // Activate/deactivate selection for upper sectors
2267   //---------------------------------------------------
2268
2269   //-----------------------------------------------------------------
2270   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2271   //-----------------------------------------------------------------
2272   fSecAU = sec;
2273 }
2274
2275 //_____________________________________________________________________________
2276 void AliTPC::SetSecLows(Int_t s1,Int_t s2,Int_t s3,Int_t s4,Int_t s5, Int_t s6)
2277 {
2278   //----------------------------------------
2279   // Select active lower sectors
2280   //----------------------------------------
2281
2282   //-----------------------------------------------------------------
2283   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2284   //-----------------------------------------------------------------
2285
2286   fSecLows[0] = s1;
2287   fSecLows[1] = s2;
2288   fSecLows[2] = s3;
2289   fSecLows[3] = s4;
2290   fSecLows[4] = s5;
2291   fSecLows[5] = s6;
2292 }
2293
2294 //_____________________________________________________________________________
2295 void AliTPC::SetSecUps(Int_t s1,Int_t s2,Int_t s3,Int_t s4,Int_t s5, Int_t s6,
2296                        Int_t s7, Int_t s8 ,Int_t s9 ,Int_t s10, 
2297                        Int_t s11 , Int_t s12)
2298 {
2299   //--------------------------------
2300   // Select active upper sectors
2301   //--------------------------------
2302
2303   //-----------------------------------------------------------------
2304   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2305   //-----------------------------------------------------------------
2306
2307   fSecUps[0] = s1;
2308   fSecUps[1] = s2;
2309   fSecUps[2] = s3;
2310   fSecUps[3] = s4;
2311   fSecUps[4] = s5;
2312   fSecUps[5] = s6;
2313   fSecUps[6] = s7;
2314   fSecUps[7] = s8;
2315   fSecUps[8] = s9;
2316   fSecUps[9] = s10;
2317   fSecUps[10] = s11;
2318   fSecUps[11] = s12;
2319 }
2320
2321 //_____________________________________________________________________________
2322 void AliTPC::SetSens(Int_t sens)
2323 {
2324
2325   //-------------------------------------------------------------
2326   // Activates/deactivates the sensitive strips at the center of
2327   // the pad row -- this is for the space-point resolution calculations
2328   //-------------------------------------------------------------
2329
2330   //-----------------------------------------------------------------
2331   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2332   //-----------------------------------------------------------------
2333
2334   fSens = sens;
2335 }
2336
2337  
2338 void AliTPC::SetSide(Float_t side=0.)
2339 {
2340   // choice of the TPC side
2341
2342   fSide = side;
2343  
2344 }
2345 //____________________________________________________________________________
2346 void AliTPC::SetGasMixt(Int_t nc,Int_t c1,Int_t c2,Int_t c3,Float_t p1,
2347                            Float_t p2,Float_t p3)
2348 {
2349
2350   // gax mixture definition
2351
2352  fNoComp = nc;
2353  
2354  fMixtComp[0]=c1;
2355  fMixtComp[1]=c2;
2356  fMixtComp[2]=c3;
2357
2358  fMixtProp[0]=p1;
2359  fMixtProp[1]=p2;
2360  fMixtProp[2]=p3; 
2361  
2362  
2363 }
2364 //_____________________________________________________________________________
2365
2366 void AliTPC::TransportElectron(Float_t *xyz, Int_t *index)
2367 {
2368   //
2369   // electron transport taking into account:
2370   // 1. diffusion, 
2371   // 2.ExB at the wires
2372   // 3. nonisochronity
2373   //
2374   // xyz and index must be already transformed to system 1
2375   //
2376
2377   fTPCParam->Transform1to2(xyz,index);
2378   
2379   //add diffusion
2380   Float_t driftl=xyz[2];
2381   if(driftl<0.01) driftl=0.01;
2382   driftl=TMath::Sqrt(driftl);
2383   Float_t sigT = driftl*(fTPCParam->GetDiffT());
2384   Float_t sigL = driftl*(fTPCParam->GetDiffL());
2385   xyz[0]=gRandom->Gaus(xyz[0],sigT);
2386   xyz[1]=gRandom->Gaus(xyz[1],sigT);
2387   xyz[2]=gRandom->Gaus(xyz[2],sigL);
2388
2389   // ExB
2390   
2391   if (fTPCParam->GetMWPCReadout()==kTRUE){
2392     Float_t dx = fTPCParam->Transform2to2NearestWire(xyz,index);
2393     xyz[1]+=dx*(fTPCParam->GetOmegaTau());
2394   }
2395   //add nonisochronity (not implemented yet)  
2396 }
2397   
2398 ClassImp(AliTPCdigit)
2399  
2400 //_____________________________________________________________________________
2401 AliTPCdigit::AliTPCdigit(Int_t *tracks, Int_t *digits):
2402   AliDigit(tracks)
2403 {
2404   //
2405   // Creates a TPC digit object
2406   //
2407   fSector     = digits[0];
2408   fPadRow     = digits[1];
2409   fPad        = digits[2];
2410   fTime       = digits[3];
2411   fSignal     = digits[4];
2412 }
2413
2414  
2415 ClassImp(AliTPChit)
2416  
2417 //_____________________________________________________________________________
2418 AliTPChit::AliTPChit(Int_t shunt, Int_t track, Int_t *vol, Float_t *hits):
2419 AliHit(shunt,track)
2420 {
2421   //
2422   // Creates a TPC hit object
2423   //
2424   fSector     = vol[0];
2425   fPadRow     = vol[1];
2426   fX          = hits[0];
2427   fY          = hits[1];
2428   fZ          = hits[2];
2429   fQ          = hits[3];
2430 }
2431  
2432 //________________________________________________________________________
2433 // Additional code because of the AliTPCTrackHitsV2
2434
2435 void AliTPC::MakeBranch2(Option_t *option,const char *file)
2436 {
2437   //
2438   // Create a new branch in the current Root Tree
2439   // The branch of fHits is automatically split
2440   // MI change 14.09.2000
2441   if(GetDebug()) Info("MakeBranch2","");
2442   if (fHitType<2) return;
2443   char branchname[10];
2444   sprintf(branchname,"%s2",GetName());  
2445   //
2446   // Get the pointer to the header
2447   const char *cH = strstr(option,"H");
2448   //
2449   if (fTrackHits   && TreeH() && cH && fHitType&4) 
2450    {
2451     if(GetDebug()) Info("MakeBranch2","Making branch for Type 4 Hits");
2452     TreeH()->Branch(branchname,"AliTPCTrackHitsV2",&fTrackHits,fBufferSize,99);
2453    }    
2454
2455   if (fTrackHitsOld   && TreeH() && cH && fHitType&2) 
2456    {    
2457     if(GetDebug()) Info("MakeBranch2","Making branch for Type 2 Hits");
2458     AliObjectBranch * branch = new AliObjectBranch(branchname,"AliTPCTrackHits",&fTrackHitsOld, 
2459                                                    TreeH(),fBufferSize,99);
2460     TreeH()->GetListOfBranches()->Add(branch);
2461    }    
2462 }
2463
2464 void AliTPC::SetTreeAddress()
2465 {
2466 //Sets tree address for hits  
2467   if (fHitType<=1)
2468    {
2469      if (fHits == 0x0 ) fHits = new TClonesArray("AliTPChit", 176);//skowron 20.06.03
2470      AliDetector::SetTreeAddress();
2471    }
2472   if (fHitType>1) SetTreeAddress2();
2473 }
2474
2475 void AliTPC::SetTreeAddress2()
2476 {
2477   //
2478   // Set branch address for the TrackHits Tree
2479   // 
2480   if(GetDebug()) Info("SetTreeAddress2","");
2481   
2482   TBranch *branch;
2483   char branchname[20];
2484   sprintf(branchname,"%s2",GetName());
2485   //
2486   // Branch address for hit tree
2487   TTree *treeH = TreeH();
2488   if ((treeH)&&(fHitType&4)) {
2489     branch = treeH->GetBranch(branchname);
2490     if (branch) 
2491      {
2492        branch->SetAddress(&fTrackHits);
2493        if (GetDebug()) Info("SetTreeAddress2","fHitType&4 Setting");
2494      }
2495     else 
2496     if (GetDebug()) Info("SetTreeAddress2","fHitType&4 Failed (can not find branch)");
2497     
2498   }
2499   if ((treeH)&&(fHitType&2)) {
2500     branch = treeH->GetBranch(branchname);
2501     if (branch) 
2502      {
2503        branch->SetAddress(&fTrackHitsOld);
2504        if (GetDebug()) Info("SetTreeAddress2","fHitType&2 Setting");
2505      }
2506     else if (GetDebug()) 
2507       Info("SetTreeAddress2","fHitType&2 Failed (can not find branch)");
2508   }
2509   //set address to TREETR
2510
2511   TTree *treeTR = TreeTR();
2512   if (treeTR && fTrackReferences) {
2513     branch = treeTR->GetBranch(GetName());
2514     if (branch) branch->SetAddress(&fTrackReferences);
2515   }
2516
2517 }
2518
2519 void AliTPC::FinishPrimary()
2520 {
2521   if (fTrackHits &&fHitType&4)      fTrackHits->FlushHitStack();  
2522   if (fTrackHitsOld && fHitType&2)  fTrackHitsOld->FlushHitStack();  
2523 }
2524
2525
2526 void AliTPC::AddHit2(Int_t track, Int_t *vol, Float_t *hits)
2527
2528   //
2529   // add hit to the list  
2530   Int_t rtrack;
2531   if (fIshunt) {
2532     int primary = gAlice->GetPrimary(track);
2533     gAlice->Particle(primary)->SetBit(kKeepBit);
2534     rtrack=primary;
2535   } else {
2536     rtrack=track;
2537     gAlice->FlagTrack(track);
2538   }  
2539   //AliTPChit *hit = (AliTPChit*)fHits->UncheckedAt(fNhits-1);
2540   //if (hit->fTrack!=rtrack)
2541   //  cout<<"bad track number\n";
2542   if (fTrackHits && fHitType&4) 
2543     fTrackHits->AddHitKartez(vol[0],rtrack, hits[0],
2544                              hits[1],hits[2],(Int_t)hits[3]);
2545   if (fTrackHitsOld &&fHitType&2 ) 
2546     fTrackHitsOld->AddHitKartez(vol[0],rtrack, hits[0],
2547                                 hits[1],hits[2],(Int_t)hits[3]);
2548   
2549 }
2550
2551 void AliTPC::ResetHits()
2552
2553   if (fHitType&1) AliDetector::ResetHits();
2554   if (fHitType>1) ResetHits2();
2555 }
2556
2557 void AliTPC::ResetHits2()
2558 {
2559   //
2560   //reset hits
2561   if (fTrackHits && fHitType&4) fTrackHits->Clear();
2562   if (fTrackHitsOld && fHitType&2) fTrackHitsOld->Clear();
2563
2564 }   
2565
2566 AliHit* AliTPC::FirstHit(Int_t track)
2567 {
2568   if (fHitType>1) return FirstHit2(track);
2569   return AliDetector::FirstHit(track);
2570 }
2571 AliHit* AliTPC::NextHit()
2572 {
2573   if (fHitType>1) return NextHit2();
2574   
2575   return AliDetector::NextHit();
2576 }
2577
2578 AliHit* AliTPC::FirstHit2(Int_t track)
2579 {
2580   //
2581   // Initialise the hit iterator
2582   // Return the address of the first hit for track
2583   // If track>=0 the track is read from disk
2584   // while if track<0 the first hit of the current
2585   // track is returned
2586   // 
2587   if(track>=0) {
2588     gAlice->ResetHits();
2589     TreeH()->GetEvent(track);
2590   }
2591   //
2592   if (fTrackHits && fHitType&4) {
2593     fTrackHits->First();
2594     return fTrackHits->GetHit();
2595   }
2596   if (fTrackHitsOld && fHitType&2) {
2597     fTrackHitsOld->First();
2598     return fTrackHitsOld->GetHit();
2599   }
2600
2601   else return 0;
2602 }
2603
2604 AliHit* AliTPC::NextHit2()
2605 {
2606   //
2607   //Return the next hit for the current track
2608
2609
2610   if (fTrackHitsOld && fHitType&2) {
2611     fTrackHitsOld->Next();
2612     return fTrackHitsOld->GetHit();
2613   }
2614   if (fTrackHits) {
2615     fTrackHits->Next();
2616     return fTrackHits->GetHit();
2617   }
2618   else 
2619     return 0;
2620 }
2621
2622 void AliTPC::LoadPoints(Int_t)
2623 {
2624   //
2625   Int_t a = 0;
2626   /*  if(fHitType==1) return AliDetector::LoadPoints(a);
2627   LoadPoints2(a);
2628   */
2629   if(fHitType==1) AliDetector::LoadPoints(a);
2630   else LoadPoints2(a);
2631    
2632   // LoadPoints3(a);
2633
2634 }
2635
2636
2637 void AliTPC::RemapTrackHitIDs(Int_t *map)
2638 {
2639   if (!fTrackHits) return;
2640   
2641   if (fTrackHitsOld && fHitType&2){
2642     AliObjectArray * arr = fTrackHitsOld->fTrackHitsInfo;
2643     for (UInt_t i=0;i<arr->GetSize();i++){
2644       AliTrackHitsInfo * info = (AliTrackHitsInfo *)(arr->At(i));
2645       info->fTrackID = map[info->fTrackID];
2646     }
2647   }
2648   if (fTrackHitsOld && fHitType&4){
2649     TClonesArray * arr = fTrackHits->GetArray();;
2650     for (Int_t i=0;i<arr->GetEntriesFast();i++){
2651       AliTrackHitsParamV2 * info = (AliTrackHitsParamV2 *)(arr->At(i));
2652       info->fTrackID = map[info->fTrackID];
2653     }
2654   }
2655 }
2656
2657 Bool_t   AliTPC::TrackInVolume(Int_t id,Int_t track)
2658 {
2659   //return bool information - is track in given volume
2660   //load only part of the track information 
2661   //return true if current track is in volume
2662   //
2663   //  return kTRUE;
2664   if (fTrackHitsOld && fHitType&2) {
2665     TBranch * br = TreeH()->GetBranch("fTrackHitsInfo");
2666     br->GetEvent(track);
2667     AliObjectArray * ar = fTrackHitsOld->fTrackHitsInfo;
2668     for (UInt_t j=0;j<ar->GetSize();j++){
2669       if (  ((AliTrackHitsInfo*)ar->At(j))->fVolumeID==id) return kTRUE;
2670     } 
2671   }
2672
2673   if (fTrackHits && fHitType&4) {
2674     TBranch * br1 = TreeH()->GetBranch("fVolumes");
2675     TBranch * br2 = TreeH()->GetBranch("fNVolumes");    
2676     br2->GetEvent(track);
2677     br1->GetEvent(track);    
2678     Int_t *volumes = fTrackHits->GetVolumes();
2679     Int_t nvolumes = fTrackHits->GetNVolumes();
2680     if (!volumes && nvolumes>0) {
2681       printf("Problematic track\t%d\t%d",track,nvolumes);
2682       return kFALSE;
2683     }
2684     for (Int_t j=0;j<nvolumes; j++)
2685       if (volumes[j]==id) return kTRUE;    
2686   }
2687
2688   if (fHitType&1) {
2689     TBranch * br = TreeH()->GetBranch("fSector");
2690     br->GetEvent(track);
2691     for (Int_t j=0;j<fHits->GetEntriesFast();j++){
2692       if (  ((AliTPChit*)fHits->At(j))->fSector==id) return kTRUE;
2693     } 
2694   }
2695   return kFALSE;  
2696
2697 }
2698
2699 //_____________________________________________________________________________
2700 void AliTPC::LoadPoints2(Int_t)
2701 {
2702   //
2703   // Store x, y, z of all hits in memory
2704   //
2705   if (fTrackHits == 0 && fTrackHitsOld==0) return;
2706   //
2707   Int_t nhits =0;
2708   if (fHitType&4) nhits = fTrackHits->GetEntriesFast();
2709   if (fHitType&2) nhits = fTrackHitsOld->GetEntriesFast();
2710   
2711   if (nhits == 0) return;
2712   Int_t tracks = gAlice->GetNtrack();
2713   if (fPoints == 0) fPoints = new TObjArray(tracks);
2714   AliHit *ahit;
2715   //
2716   Int_t *ntrk=new Int_t[tracks];
2717   Int_t *limi=new Int_t[tracks];
2718   Float_t **coor=new Float_t*[tracks];
2719   for(Int_t i=0;i<tracks;i++) {
2720     ntrk[i]=0;
2721     coor[i]=0;
2722     limi[i]=0;
2723   }
2724   //
2725   AliPoints *points = 0;
2726   Float_t *fp=0;
2727   Int_t trk;
2728   Int_t chunk=nhits/4+1;
2729   //
2730   // Loop over all the hits and store their position
2731   //
2732   ahit = FirstHit2(-1);
2733   while (ahit){
2734     trk=ahit->GetTrack();
2735     if(ntrk[trk]==limi[trk]) {
2736       //
2737       // Initialise a new track
2738       fp=new Float_t[3*(limi[trk]+chunk)];
2739       if(coor[trk]) {
2740         memcpy(fp,coor[trk],sizeof(Float_t)*3*limi[trk]);
2741         delete [] coor[trk];
2742       }
2743       limi[trk]+=chunk;
2744       coor[trk] = fp;
2745     } else {
2746       fp = coor[trk];
2747     }
2748     fp[3*ntrk[trk]  ] = ahit->X();
2749     fp[3*ntrk[trk]+1] = ahit->Y();
2750     fp[3*ntrk[trk]+2] = ahit->Z();
2751     ntrk[trk]++;
2752     ahit = NextHit2();
2753   }
2754
2755
2756
2757   //
2758   for(trk=0; trk<tracks; ++trk) {
2759     if(ntrk[trk]) {
2760       points = new AliPoints();
2761       points->SetMarkerColor(GetMarkerColor());
2762       points->SetMarkerSize(GetMarkerSize());
2763       points->SetDetector(this);
2764       points->SetParticle(trk);
2765       points->SetPolyMarker(ntrk[trk],coor[trk],GetMarkerStyle());
2766       fPoints->AddAt(points,trk);
2767       delete [] coor[trk];
2768       coor[trk]=0;
2769     }
2770   }
2771   delete [] coor;
2772   delete [] ntrk;
2773   delete [] limi;
2774 }
2775
2776
2777 //_____________________________________________________________________________
2778 void AliTPC::LoadPoints3(Int_t)
2779 {
2780   //
2781   // Store x, y, z of all hits in memory
2782   // - only intersection point with pad row
2783   if (fTrackHits == 0) return;
2784   //
2785   Int_t nhits = fTrackHits->GetEntriesFast();
2786   if (nhits == 0) return;
2787   Int_t tracks = gAlice->GetNtrack();
2788   if (fPoints == 0) fPoints = new TObjArray(2*tracks);
2789   fPoints->Expand(2*tracks);
2790   AliHit *ahit;
2791   //
2792   Int_t *ntrk=new Int_t[tracks];
2793   Int_t *limi=new Int_t[tracks];
2794   Float_t **coor=new Float_t*[tracks];
2795   for(Int_t i=0;i<tracks;i++) {
2796     ntrk[i]=0;
2797     coor[i]=0;
2798     limi[i]=0;
2799   }
2800   //
2801   AliPoints *points = 0;
2802   Float_t *fp=0;
2803   Int_t trk;
2804   Int_t chunk=nhits/4+1;
2805   //
2806   // Loop over all the hits and store their position
2807   //
2808   ahit = FirstHit2(-1);
2809   //for (Int_t hit=0;hit<nhits;hit++) {
2810
2811   Int_t lastrow = -1;
2812   while (ahit){
2813     //    ahit = (AliHit*)fHits->UncheckedAt(hit);
2814     trk=ahit->GetTrack(); 
2815     Float_t  x[3]={ahit->X(),ahit->Y(),ahit->Z()};
2816     Int_t    index[3]={1,((AliTPChit*)ahit)->fSector,0};
2817     Int_t    currentrow = fTPCParam->GetPadRow(x,index) ;
2818     if (currentrow!=lastrow){
2819       lastrow = currentrow;
2820       //later calculate intersection point           
2821       if(ntrk[trk]==limi[trk]) {
2822         //
2823         // Initialise a new track
2824         fp=new Float_t[3*(limi[trk]+chunk)];
2825         if(coor[trk]) {
2826           memcpy(fp,coor[trk],sizeof(Float_t)*3*limi[trk]);
2827           delete [] coor[trk];
2828         }
2829         limi[trk]+=chunk;
2830         coor[trk] = fp;
2831       } else {
2832         fp = coor[trk];
2833       }
2834       fp[3*ntrk[trk]  ] = ahit->X();
2835       fp[3*ntrk[trk]+1] = ahit->Y();
2836       fp[3*ntrk[trk]+2] = ahit->Z();
2837       ntrk[trk]++;
2838     }
2839     ahit = NextHit2();
2840   }
2841   
2842   //
2843   for(trk=0; trk<tracks; ++trk) {
2844     if(ntrk[trk]) {
2845       points = new AliPoints();
2846       points->SetMarkerColor(GetMarkerColor()+1);
2847       points->SetMarkerStyle(5);
2848       points->SetMarkerSize(0.2);
2849       points->SetDetector(this);
2850       points->SetParticle(trk);
2851       //      points->SetPolyMarker(ntrk[trk],coor[trk],GetMarkerStyle()20);
2852       points->SetPolyMarker(ntrk[trk],coor[trk],30);
2853       fPoints->AddAt(points,tracks+trk);
2854       delete [] coor[trk];
2855       coor[trk]=0;
2856     }
2857   }
2858   delete [] coor;
2859   delete [] ntrk;
2860   delete [] limi;
2861 }
2862
2863
2864
2865 void AliTPC::FindTrackHitsIntersection(TClonesArray * arr)
2866 {
2867
2868   //
2869   //fill clones array with intersection of current point with the
2870   //middle of the row
2871   Int_t sector;
2872   Int_t ipart;
2873   
2874   const Int_t kcmaxhits=30000;
2875   AliTPCFastVector * xxxx = new AliTPCFastVector(kcmaxhits*4);
2876   AliTPCFastVector & xxx = *xxxx;
2877   Int_t maxhits = kcmaxhits;
2878       
2879   //
2880   AliTPChit * tpcHit=0;
2881   tpcHit = (AliTPChit*)FirstHit2(-1);
2882   Int_t currentIndex=0;
2883   Int_t lastrow=-1;  //last writen row
2884
2885   while (tpcHit){
2886     if (tpcHit==0) continue;
2887     sector=tpcHit->fSector; // sector number
2888     ipart=tpcHit->Track();
2889     
2890     //find row number
2891     
2892     Float_t  x[3]={tpcHit->X(),tpcHit->Y(),tpcHit->Z()};
2893     Int_t    index[3]={1,sector,0};
2894     Int_t    currentrow = fTPCParam->GetPadRow(x,index) ;       
2895     if (currentrow<0) continue;
2896     if (lastrow<0) lastrow=currentrow;
2897     if (currentrow==lastrow){
2898       if ( currentIndex>=maxhits){
2899         maxhits+=kcmaxhits;
2900         xxx.ResizeTo(4*maxhits);
2901       }     
2902       xxx(currentIndex*4)=x[0];
2903       xxx(currentIndex*4+1)=x[1];
2904       xxx(currentIndex*4+2)=x[2];       
2905       xxx(currentIndex*4+3)=tpcHit->fQ;
2906       currentIndex++;   
2907     }
2908     else 
2909       if (currentIndex>2){
2910         Float_t sumx=0;
2911         Float_t sumx2=0;
2912         Float_t sumx3=0;
2913         Float_t sumx4=0;
2914         Float_t sumy=0;
2915         Float_t sumxy=0;
2916         Float_t sumx2y=0;
2917         Float_t sumz=0;
2918         Float_t sumxz=0;
2919         Float_t sumx2z=0;
2920         Float_t sumq=0;
2921         for (Int_t index=0;index<currentIndex;index++){
2922           Float_t x,x2,x3,x4;
2923           x=x2=x3=x4=xxx(index*4);
2924           x2*=x;
2925           x3*=x2;
2926           x4*=x3;
2927           sumx+=x;
2928           sumx2+=x2;
2929           sumx3+=x3;
2930           sumx4+=x4;
2931           sumy+=xxx(index*4+1);
2932           sumxy+=xxx(index*4+1)*x;
2933           sumx2y+=xxx(index*4+1)*x2;
2934           sumz+=xxx(index*4+2);
2935           sumxz+=xxx(index*4+2)*x;
2936           sumx2z+=xxx(index*4+2)*x2;     
2937           sumq+=xxx(index*4+3);
2938         }
2939         Float_t centralPad = (fTPCParam->GetNPads(sector,lastrow)-1)/2;
2940         Float_t det=currentIndex*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumx*sumx4-sumx2*sumx3)+
2941           sumx2*(sumx*sumx3-sumx2*sumx2);
2942         
2943         Float_t detay=sumy*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumxy*sumx4-sumx2y*sumx3)+
2944           sumx2*(sumxy*sumx3-sumx2y*sumx2);
2945         Float_t detaz=sumz*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumxz*sumx4-sumx2z*sumx3)+
2946           sumx2*(sumxz*sumx3-sumx2z*sumx2);
2947         
2948         Float_t detby=currentIndex*(sumxy*sumx4-sumx2y*sumx3)-sumy*(sumx*sumx4-sumx2*sumx3)+
2949           sumx2*(sumx*sumx2y-sumx2*sumxy);
2950         Float_t detbz=currentIndex*(sumxz*sumx4-sumx2z*sumx3)-sumz*(sumx*sumx4-sumx2*sumx3)+
2951           sumx2*(sumx*sumx2z-sumx2*sumxz);
2952         
2953         Float_t y=detay/det+centralPad;
2954         Float_t z=detaz/det;    
2955         Float_t by=detby/det; //y angle
2956         Float_t bz=detbz/det; //z angle
2957         sumy/=Float_t(currentIndex);
2958         sumz/=Float_t(currentIndex);
2959         
2960         AliComplexCluster cl;
2961         cl.fX=z;
2962         cl.fY=y;
2963         cl.fQ=sumq;
2964         cl.fSigmaX2=bz;
2965         cl.fSigmaY2=by;
2966         cl.fTracks[0]=ipart;
2967         
2968         AliTPCClustersRow * row = (fClustersArray->GetRow(sector,lastrow));
2969         if (row!=0) row->InsertCluster(&cl);
2970         currentIndex=0;
2971         lastrow=currentrow;
2972       } //end of calculating cluster for given row
2973                 
2974   } // end of loop over hits
2975   xxxx->Delete();
2976
2977 }
2978 //_______________________________________________________________________________
2979 void AliTPC::Digits2Reco(Int_t firstevent,Int_t lastevent)
2980 {
2981   // produces rec points from digits and writes them on the root file
2982   // AliTPCclusters.root
2983
2984   TDirectory *cwd = gDirectory;
2985
2986
2987   AliTPCParamSR *dig=(AliTPCParamSR *)gDirectory->Get("75x40_100x60");
2988   if(dig){
2989     printf("You are running 2 pad-length geom hits with 3 pad-length geom digits\n");
2990     delete dig;
2991     dig = new AliTPCParamSR();
2992   }
2993   else
2994   {
2995    dig=(AliTPCParamSR *)gDirectory->Get("75x40_100x60_150x60"); 
2996   }
2997   if(!dig){
2998    printf("No TPC parameters found\n");
2999    exit(3);
3000   }
3001    
3002   SetParam(dig);
3003   cout<<"AliTPC::Digits2Reco: TPC parameteres have been set"<<endl; 
3004   TFile *out;
3005   if(!gSystem->Getenv("CONFIG_FILE")){
3006     out=TFile::Open("AliTPCclusters.root","recreate");
3007   }
3008   else {
3009     const char *tmp1;
3010     const char *tmp2;
3011     char tmp3[80];
3012     tmp1=gSystem->Getenv("CONFIG_FILE_PREFIX");
3013     tmp2=gSystem->Getenv("CONFIG_OUTDIR");
3014     sprintf(tmp3,"%s%s/AliTPCclusters.root",tmp1,tmp2);
3015     out=TFile::Open(tmp3,"recreate");
3016   }
3017
3018   TStopwatch timer;
3019   cout<<"AliTPC::Digits2Reco - determination of rec points begins"<<endl;
3020   timer.Start();
3021   cwd->cd();
3022   for(Int_t iev=firstevent;iev<lastevent+1;iev++){
3023
3024     printf("Processing event %d\n",iev);
3025     Digits2Clusters(iev);
3026   }
3027   cout<<"AliTPC::Digits2Reco - determination of rec points ended"<<endl;
3028   timer.Stop();
3029   timer.Print();
3030   out->Close();
3031   cwd->cd(); 
3032
3033
3034 }
3035
3036 AliLoader* AliTPC::MakeLoader(const char* topfoldername)
3037 {
3038 //Makes TPC loader
3039  fLoader = new AliTPCLoader(GetName(),topfoldername);
3040  return fLoader;
3041 }
3042
3043 ////////////////////////////////////////////////////////////////////////
3044 AliTPCParam* AliTPC::LoadTPCParam(TFile *file) {
3045 //
3046 // load TPC paarmeters from a given file or create new if the object
3047 // is not found there
3048 // 12/05/2003 This method should be moved to the AliTPCLoader
3049 // and one has to decide where to store the TPC parameters
3050 // M.Kowalski
3051   char paramName[50];
3052   sprintf(paramName,"75x40_100x60_150x60");
3053   AliTPCParam *paramTPC=(AliTPCParam*)file->Get(paramName);
3054   if (paramTPC) {
3055     cout<<"TPC parameters "<<paramName<<" found."<<endl;
3056   } else {
3057     cerr<<"TPC parameters not found. Create new (they may be incorrect)."
3058         <<endl;    
3059     paramTPC = new AliTPCParamSR;
3060   }
3061   return paramTPC;
3062
3063 // the older version of parameters can be accessed with this code.
3064 // In some cases, we have old parameters saved in the file but 
3065 // digits were created with new parameters, it can be distinguish 
3066 // by the name of TPC TreeD. The code here is just for the case 
3067 // we would need to compare with old data, uncomment it if needed.
3068 //
3069 //  char paramName[50];
3070 //  sprintf(paramName,"75x40_100x60");
3071 //  AliTPCParam *paramTPC=(AliTPCParam*)in->Get(paramName);
3072 //  if (paramTPC) {
3073 //    cout<<"TPC parameters "<<paramName<<" found."<<endl;
3074 //  } else {
3075 //    sprintf(paramName,"75x40_100x60_150x60");
3076 //    paramTPC=(AliTPCParam*)in->Get(paramName);
3077 //    if (paramTPC) {
3078 //      cout<<"TPC parameters "<<paramName<<" found."<<endl;
3079 //    } else {
3080 //      cerr<<"TPC parameters not found. Create new (they may be incorrect)."
3081 //          <<endl;    
3082 //      paramTPC = new AliTPCParamSR;
3083 //    }
3084 //  }
3085 //  return paramTPC;
3086
3087 }
3088