]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TPC/AliTPC.cxx
Implementing ESD functionality in the NewIO (Yu.Belikov)
[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     cout<<"Sector "<<isec<<"is active\n";
1459     Hits2DigitsSector(isec);
1460    }
1461   else
1462    {
1463     cout<<"Sector "<<isec<<"is NOT active\n";
1464    }
1465
1466   fLoader->WriteDigits("OVERWRITE"); 
1467 }
1468
1469
1470
1471 //__________________________________________________________________
1472 void AliTPC::Hits2SDigits2(Int_t eventnumber)  
1473
1474
1475   //-----------------------------------------------------------
1476   //   summable digits - 16 bit "ADC", no noise, no saturation
1477   //-----------------------------------------------------------
1478
1479  //----------------------------------------------------
1480  // Loop over all sectors for a single event
1481  //----------------------------------------------------
1482 //  AliRunLoader* rl = (AliRunLoader*)fLoader->GetEventFolder()->FindObject(AliRunLoader::fgkRunLoaderName);
1483
1484   AliRunLoader* rl = fLoader->GetRunLoader();
1485
1486   rl->GetEvent(eventnumber);
1487   if (fLoader->TreeH() == 0x0)
1488    {
1489      if(fLoader->LoadHits())
1490       {
1491         Error("Hits2Digits","Can not load hits.");
1492         return;
1493       }
1494    }
1495   SetTreeAddress();
1496
1497
1498   if (fLoader->TreeS() == 0x0 ) 
1499    {
1500      fLoader->MakeTree("S");
1501    }
1502   
1503   if(fDefaults == 0) SetDefaults();
1504   
1505   GenerNoise(500000); //create table with noise
1506   //setup TPCDigitsArray 
1507
1508   if(GetDigitsArray()) delete GetDigitsArray();
1509
1510   
1511   AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
1512   arr->SetClass("AliSimDigits");
1513   arr->Setup(fTPCParam);
1514   arr->MakeTree(fLoader->TreeS());
1515
1516   SetDigitsArray(arr);
1517
1518   cerr<<"Digitizing TPC -- summable digits...\n"; 
1519
1520   fDigitsSwitch=1; // summable digits
1521   
1522     // set zero suppression to "0"
1523
1524   fTPCParam->SetZeroSup(0);
1525
1526  for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++) 
1527   if (IsSectorActive(isec)) 
1528    {
1529 //    cout<<"Sector "<<isec<<" is active\n";
1530     Hits2DigitsSector(isec);
1531    }
1532
1533  fLoader->WriteSDigits("OVERWRITE");
1534
1535 //this line prevents the crash in the similar one
1536 //on the beginning of this method
1537 //destructor attempts to reset the tree, which is deleted by the loader
1538 //need to be redesign
1539  if(GetDigitsArray()) delete GetDigitsArray();
1540  SetDigitsArray(0x0);
1541 }
1542 //__________________________________________________________________
1543
1544 void AliTPC::Hits2SDigits()  
1545
1546
1547   //-----------------------------------------------------------
1548   //   summable digits - 16 bit "ADC", no noise, no saturation
1549   //-----------------------------------------------------------
1550
1551  //----------------------------------------------------
1552  // Loop over all sectors for a single event
1553  //----------------------------------------------------
1554   //MI change - for pp run
1555 //  Int_t eventnumber = gAlice->GetEvNumber();
1556 //  AliRunLoader* rl = (AliRunLoader*)fLoader->GetEventFolder()->FindObject(AliRunLoader::fgkRunLoaderName);
1557 //  rl->GetEvent(eventnumber);
1558 // 12/05/2003 This method is obsolete and not used. It should be redesingned
1559 // M.Kowalski
1560
1561   if (fLoader->TreeH() == 0x0)
1562    {
1563      if(fLoader->LoadHits())
1564       {
1565         Error("Hits2Digits","Can not load hits.");
1566       }
1567    }
1568   SetTreeAddress();
1569
1570   if(fDefaults == 0) SetDefaults();
1571   GenerNoise(500000); //create table with noise
1572
1573   //setup TPCDigitsArray 
1574
1575   if(GetDigitsArray()) delete GetDigitsArray();
1576
1577   if (fLoader->TreeS() == 0x0 ) 
1578    {
1579      fLoader->MakeTree("S");
1580    }
1581   
1582   AliTPCDigitsArray *arr = new AliTPCDigitsArray; 
1583   arr->SetClass("AliSimDigits");
1584   arr->Setup(fTPCParam);
1585   arr->MakeTree(fLoader->TreeS());
1586   SetDigitsArray(arr);
1587
1588   cerr<<"Digitizing TPC -- summable digits...\n"; 
1589
1590   //  fDigitsSwitch=1; // summable digits  -for the moment direct
1591
1592   for(Int_t isec=0;isec<fTPCParam->GetNSector();isec++) if (IsSectorActive(isec)) Hits2DigitsSector(isec);
1593
1594   // write results
1595   //
1596   cout<<"Why method TPC::Hits2SDigits writes digits and not sdigits? skowron\n";
1597   fLoader->WriteDigits("OVERWRITE");
1598 }
1599 //_____________________________________________________________________________
1600
1601 void AliTPC::Hits2DigitsSector(Int_t isec)
1602 {
1603   //-------------------------------------------------------------------
1604   // TPC conversion from hits to digits.
1605   //------------------------------------------------------------------- 
1606
1607   //-----------------------------------------------------------------
1608   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1609   //-----------------------------------------------------------------
1610
1611   //-------------------------------------------------------
1612   //  Get the access to the track hits
1613   //-------------------------------------------------------
1614
1615   // check if the parameters are set - important if one calls this method
1616   // directly, not from the Hits2Digits
1617
1618   if(fDefaults == 0) SetDefaults();
1619
1620   TTree *tH = TreeH(); // pointer to the hits tree
1621   if (tH == 0x0)
1622    {
1623      Fatal("Hits2DigitsSector","Can not find TreeH in folder");
1624      return;
1625    }
1626
1627   Stat_t ntracks = tH->GetEntries();
1628
1629   if( ntracks > 0){
1630
1631   //------------------------------------------- 
1632   //  Only if there are any tracks...
1633   //-------------------------------------------
1634
1635     TObjArray **row;
1636     
1637     //printf("*** Processing sector number %d ***\n",isec);
1638
1639       Int_t nrows =fTPCParam->GetNRow(isec);
1640
1641       row= new TObjArray* [nrows+2]; // 2 extra rows for cross talk
1642     
1643       MakeSector(isec,nrows,tH,ntracks,row);
1644
1645       //--------------------------------------------------------
1646       //   Digitize this sector, row by row
1647       //   row[i] is the pointer to the TObjArray of AliTPCFastVectors,
1648       //   each one containing electrons accepted on this
1649       //   row, assigned into tracks
1650       //--------------------------------------------------------
1651
1652       Int_t i;
1653
1654       if (fDigitsArray->GetTree()==0) 
1655        {
1656          Fatal("Hits2DigitsSector","Tree not set in fDigitsArray");
1657        }
1658
1659       for (i=0;i<nrows;i++){
1660
1661         AliDigits * dig = fDigitsArray->CreateRow(isec,i); 
1662
1663         DigitizeRow(i,isec,row);
1664
1665         fDigitsArray->StoreRow(isec,i);
1666
1667         Int_t ndig = dig->GetDigitSize(); 
1668         
1669         if (gDebug > 10) 
1670         printf("*** Sector, row, compressed digits %d %d %d ***\n",isec,i,ndig);        
1671         
1672         fDigitsArray->ClearRow(isec,i);  
1673
1674    
1675        } // end of the sector digitization
1676
1677       for(i=0;i<nrows+2;i++){
1678         row[i]->Delete();  
1679         delete row[i];   
1680       }
1681       
1682        delete [] row; // delete the array of pointers to TObjArray-s
1683         
1684   } // ntracks >0
1685
1686 } // end of Hits2DigitsSector
1687
1688
1689 //_____________________________________________________________________________
1690 void AliTPC::DigitizeRow(Int_t irow,Int_t isec,TObjArray **rows)
1691 {
1692   //-----------------------------------------------------------
1693   // Single row digitization, coupling from the neighbouring
1694   // rows taken into account
1695   //-----------------------------------------------------------
1696
1697   //-----------------------------------------------------------------
1698   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1699   // Modified: Marian Ivanov GSI Darmstadt, m.ivanov@gsi.de
1700   //-----------------------------------------------------------------
1701  
1702
1703   Float_t zerosup = fTPCParam->GetZeroSup();
1704   //  Int_t nrows =fTPCParam->GetNRow(isec);
1705   fCurrentIndex[1]= isec;
1706   
1707
1708   Int_t nofPads = fTPCParam->GetNPads(isec,irow);
1709   Int_t nofTbins = fTPCParam->GetMaxTBin();
1710   Int_t indexRange[4];
1711   //
1712   //  Integrated signal for this row
1713   //  and a single track signal
1714   //    
1715
1716   AliTPCFastMatrix *m1 = new AliTPCFastMatrix(0,nofPads,0,nofTbins); // integrated
1717   AliTPCFastMatrix *m2 = new AliTPCFastMatrix(0,nofPads,0,nofTbins); // single
1718   //
1719   AliTPCFastMatrix &total  = *m1;
1720
1721   //  Array of pointers to the label-signal list
1722
1723   Int_t nofDigits = nofPads*nofTbins; // number of digits for this row
1724   Float_t  **pList = new Float_t* [nofDigits]; 
1725
1726   Int_t lp;
1727   Int_t i1;   
1728   for(lp=0;lp<nofDigits;lp++)pList[lp]=0; // set all pointers to NULL
1729   //
1730   //calculate signal 
1731   //
1732   //Int_t row1 = TMath::Max(irow-fTPCParam->GetNCrossRows(),0);
1733   //Int_t row2 = TMath::Min(irow+fTPCParam->GetNCrossRows(),nrows-1);
1734   Int_t row1=irow;
1735   Int_t row2=irow+2; 
1736   for (Int_t row= row1;row<=row2;row++){
1737     Int_t nTracks= rows[row]->GetEntries();
1738     for (i1=0;i1<nTracks;i1++){
1739       fCurrentIndex[2]= row;
1740       fCurrentIndex[3]=irow+1;
1741       if (row==irow+1){
1742         m2->Zero();  // clear single track signal matrix
1743         Float_t trackLabel = GetSignal(rows[row],i1,m2,m1,indexRange); 
1744         GetList(trackLabel,nofPads,m2,indexRange,pList);
1745       }
1746       else   GetSignal(rows[row],i1,0,m1,indexRange);
1747     }
1748   }
1749          
1750   Int_t tracks[3];
1751
1752   AliDigits *dig = fDigitsArray->GetRow(isec,irow);
1753   Int_t gi=-1;
1754   Float_t fzerosup = zerosup+0.5;
1755   for(Int_t it=0;it<nofTbins;it++){
1756     Float_t *pq = &(total.UncheckedAt(0,it));
1757     for(Int_t ip=0;ip<nofPads;ip++){
1758       gi++;
1759       Float_t q=*pq;      
1760       pq++;
1761       if(fDigitsSwitch == 0){
1762         q+=GetNoise();
1763         if(q <=fzerosup) continue; // do not fill zeros
1764         q = TMath::Nint(q);
1765         if(q > fTPCParam->GetADCSat()) q = fTPCParam->GetADCSat();  // saturation
1766
1767       }
1768
1769       else {
1770        if(q <= 0.) continue; // do not fill zeros
1771        if(q>2000.) q=2000.;
1772        q *= 16.;
1773        q = TMath::Nint(q);
1774       }
1775
1776       //
1777       //  "real" signal or electronic noise (list = -1)?
1778       //    
1779
1780       for(Int_t j1=0;j1<3;j1++){
1781         tracks[j1] = (pList[gi]) ?(Int_t)(*(pList[gi]+j1)) : -2;
1782       }
1783
1784 //Begin_Html
1785 /*
1786   <A NAME="AliDigits"></A>
1787   using of AliDigits object
1788 */
1789 //End_Html
1790       dig->SetDigitFast((Short_t)q,it,ip);
1791       if (fDigitsArray->IsSimulated())
1792         {
1793          ((AliSimDigits*)dig)->SetTrackIDFast(tracks[0],it,ip,0);
1794          ((AliSimDigits*)dig)->SetTrackIDFast(tracks[1],it,ip,1);
1795          ((AliSimDigits*)dig)->SetTrackIDFast(tracks[2],it,ip,2);
1796         }
1797      
1798     
1799     } // end of loop over time buckets
1800   }  // end of lop over pads 
1801
1802   //
1803   //  This row has been digitized, delete nonused stuff
1804   //
1805
1806   for(lp=0;lp<nofDigits;lp++){
1807     if(pList[lp]) delete [] pList[lp];
1808   }
1809   
1810   delete [] pList;
1811
1812   delete m1;
1813   delete m2;
1814   //  delete m3;
1815
1816 } // end of DigitizeRow
1817
1818 //_____________________________________________________________________________
1819
1820 Float_t AliTPC::GetSignal(TObjArray *p1, Int_t ntr, 
1821              AliTPCFastMatrix *m1, AliTPCFastMatrix *m2,Int_t *indexRange)
1822 {
1823
1824   //---------------------------------------------------------------
1825   //  Calculates 2-D signal (pad,time) for a single track,
1826   //  returns a pointer to the signal matrix and the track label 
1827   //  No digitization is performed at this level!!!
1828   //---------------------------------------------------------------
1829
1830   //-----------------------------------------------------------------
1831   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1832   // Modified: Marian Ivanov 
1833   //-----------------------------------------------------------------
1834
1835   AliTPCFastVector *tv;
1836
1837   tv = (AliTPCFastVector*)p1->At(ntr); // pointer to a track
1838   AliTPCFastVector &v = *tv;
1839   
1840   Float_t label = v(0);
1841   Int_t centralPad = (fTPCParam->GetNPads(fCurrentIndex[1],fCurrentIndex[3]-1)-1)/2;
1842
1843   Int_t nElectrons = (tv->GetNrows()-1)/4;
1844   indexRange[0]=9999; // min pad
1845   indexRange[1]=-1; // max pad
1846   indexRange[2]=9999; //min time
1847   indexRange[3]=-1; // max time
1848
1849   AliTPCFastMatrix &signal = *m1;
1850   AliTPCFastMatrix &total = *m2;
1851   //
1852   //  Loop over all electrons
1853   //
1854   for(Int_t nel=0; nel<nElectrons; nel++){
1855     Int_t idx=nel*4;
1856     Float_t aval =  v(idx+4);
1857     Float_t eltoadcfac=aval*fTPCParam->GetTotalNormFac(); 
1858     Float_t xyz[3]={v(idx+1),v(idx+2),v(idx+3)};
1859     Int_t n = ((AliTPCParamSR*)fTPCParam)->CalcResponseFast(xyz,fCurrentIndex,fCurrentIndex[3]);
1860
1861     Int_t *index = fTPCParam->GetResBin(0);  
1862     Float_t *weight = & (fTPCParam->GetResWeight(0));
1863
1864     if (n>0) for (Int_t i =0; i<n; i++){       
1865        Int_t pad=index[1]+centralPad;  //in digit coordinates central pad has coordinate 0
1866
1867          if (pad>=0){
1868          Int_t time=index[2];    
1869          Float_t qweight = *(weight)*eltoadcfac;
1870          
1871          if (m1!=0) signal.UncheckedAt(pad,time)+=qweight;
1872          total.UncheckedAt(pad,time)+=qweight;
1873          if (indexRange[0]>pad) indexRange[0]=pad;
1874          if (indexRange[1]<pad) indexRange[1]=pad;
1875          if (indexRange[2]>time) indexRange[2]=time;
1876          if (indexRange[3]<time) indexRange[3]=time;
1877
1878          index+=3;
1879          weight++;      
1880
1881        }         
1882     }
1883   } // end of loop over electrons
1884   
1885   return label; // returns track label when finished
1886 }
1887
1888 //_____________________________________________________________________________
1889 void AliTPC::GetList(Float_t label,Int_t np,AliTPCFastMatrix *m,
1890                      Int_t *indexRange, Float_t **pList)
1891 {
1892   //----------------------------------------------------------------------
1893   //  Updates the list of tracks contributing to digits for a given row
1894   //----------------------------------------------------------------------
1895
1896   //-----------------------------------------------------------------
1897   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1898   //-----------------------------------------------------------------
1899
1900   AliTPCFastMatrix &signal = *m;
1901
1902   // lop over nonzero digits
1903
1904   for(Int_t it=indexRange[2];it<indexRange[3]+1;it++){
1905     for(Int_t ip=indexRange[0];ip<indexRange[1]+1;ip++){
1906
1907
1908         // accept only the contribution larger than 500 electrons (1/2 s_noise)
1909
1910         if(signal(ip,it)<0.5) continue; 
1911
1912
1913         Int_t globalIndex = it*np+ip; // globalIndex starts from 0!
1914         
1915         if(!pList[globalIndex]){
1916         
1917           // 
1918           // Create new list (6 elements - 3 signals and 3 labels),
1919           //
1920
1921           pList[globalIndex] = new Float_t [6];
1922
1923           // set list to -1 
1924
1925           *pList[globalIndex] = -1.;
1926           *(pList[globalIndex]+1) = -1.;
1927           *(pList[globalIndex]+2) = -1.;
1928           *(pList[globalIndex]+3) = -1.;
1929           *(pList[globalIndex]+4) = -1.;
1930           *(pList[globalIndex]+5) = -1.;
1931
1932
1933           *pList[globalIndex] = label;
1934           *(pList[globalIndex]+3) = signal(ip,it);
1935         }
1936         else{
1937
1938           // check the signal magnitude
1939
1940           Float_t highest = *(pList[globalIndex]+3);
1941           Float_t middle = *(pList[globalIndex]+4);
1942           Float_t lowest = *(pList[globalIndex]+5);
1943
1944           //
1945           //  compare the new signal with already existing list
1946           //
1947
1948           if(signal(ip,it)<lowest) continue; // neglect this track
1949
1950           //
1951
1952           if (signal(ip,it)>highest){
1953             *(pList[globalIndex]+5) = middle;
1954             *(pList[globalIndex]+4) = highest;
1955             *(pList[globalIndex]+3) = signal(ip,it);
1956
1957             *(pList[globalIndex]+2) = *(pList[globalIndex]+1);
1958             *(pList[globalIndex]+1) = *pList[globalIndex];
1959             *pList[globalIndex] = label;
1960           }
1961           else if (signal(ip,it)>middle){
1962             *(pList[globalIndex]+5) = middle;
1963             *(pList[globalIndex]+4) = signal(ip,it);
1964
1965             *(pList[globalIndex]+2) = *(pList[globalIndex]+1);
1966             *(pList[globalIndex]+1) = label;
1967           }
1968           else{
1969             *(pList[globalIndex]+5) = signal(ip,it);
1970             *(pList[globalIndex]+2) = label;
1971           }
1972         }
1973
1974     } // end of loop over pads
1975   } // end of loop over time bins
1976
1977
1978
1979 }//end of GetList
1980 //___________________________________________________________________
1981 void AliTPC::MakeSector(Int_t isec,Int_t nrows,TTree *TH,
1982                         Stat_t ntracks,TObjArray **row)
1983 {
1984
1985   //-----------------------------------------------------------------
1986   // Prepares the sector digitization, creates the vectors of
1987   // tracks for each row of this sector. The track vector
1988   // contains the track label and the position of electrons.
1989   //-----------------------------------------------------------------
1990
1991   //-----------------------------------------------------------------
1992   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
1993   //-----------------------------------------------------------------
1994
1995   Float_t gasgain = fTPCParam->GetGasGain();
1996   Int_t i;
1997   Float_t xyz[4]; 
1998
1999   AliTPChit *tpcHit; // pointer to a sigle TPC hit    
2000   //MI change
2001   TBranch * branch=0;
2002   if (fHitType>1) branch = TH->GetBranch("TPC2");
2003   else branch = TH->GetBranch("TPC");
2004
2005  
2006   //----------------------------------------------
2007   // Create TObjArray-s, one for each row,
2008   // each TObjArray will store the AliTPCFastVectors
2009   // of electrons, one AliTPCFastVectors per each track.
2010   //---------------------------------------------- 
2011     
2012   Int_t *nofElectrons = new Int_t [nrows+2]; // electron counter for each row
2013   AliTPCFastVector **tracks = new AliTPCFastVector* [nrows+2]; //pointers to the track vectors
2014
2015   for(i=0; i<nrows+2; i++){
2016     row[i] = new TObjArray;
2017     nofElectrons[i]=0;
2018     tracks[i]=0;
2019   }
2020
2021  
2022
2023   //--------------------------------------------------------------------
2024   //  Loop over tracks, the "track" contains the full history
2025   //--------------------------------------------------------------------
2026
2027   Int_t previousTrack,currentTrack;
2028   previousTrack = -1; // nothing to store so far!
2029
2030   for(Int_t track=0;track<ntracks;track++){
2031     Bool_t isInSector=kTRUE;
2032     ResetHits();
2033     isInSector = TrackInVolume(isec,track);
2034     if (!isInSector) continue;
2035     //MI change
2036     branch->GetEntry(track); // get next track
2037
2038     //M.I. changes
2039
2040     tpcHit = (AliTPChit*)FirstHit(-1);
2041
2042     //--------------------------------------------------------------
2043     //  Loop over hits
2044     //--------------------------------------------------------------
2045
2046
2047     while(tpcHit){
2048       
2049       Int_t sector=tpcHit->fSector; // sector number
2050       if(sector != isec){
2051         tpcHit = (AliTPChit*) NextHit();
2052         continue; 
2053       }
2054
2055         currentTrack = tpcHit->Track(); // track number
2056
2057
2058         if(currentTrack != previousTrack){
2059                           
2060            // store already filled fTrack
2061               
2062            for(i=0;i<nrows+2;i++){
2063              if(previousTrack != -1){
2064                if(nofElectrons[i]>0){
2065                  AliTPCFastVector &v = *tracks[i];
2066                  v(0) = previousTrack;
2067                  tracks[i]->ResizeTo(4*nofElectrons[i]+1); // shrink if necessary
2068                  row[i]->Add(tracks[i]);                     
2069                }
2070                else{
2071                  delete tracks[i]; // delete empty AliTPCFastVector
2072                  tracks[i]=0;
2073                }
2074              }
2075
2076              nofElectrons[i]=0;
2077              tracks[i] = new AliTPCFastVector(481); // AliTPCFastVectors for the next fTrack
2078
2079            } // end of loop over rows
2080                
2081            previousTrack=currentTrack; // update track label 
2082         }
2083            
2084         Int_t qI = (Int_t) (tpcHit->fQ); // energy loss (number of electrons)
2085
2086        //---------------------------------------------------
2087        //  Calculate the electron attachment probability
2088        //---------------------------------------------------
2089
2090
2091         Float_t time = 1.e6*(fTPCParam->GetZLength()-TMath::Abs(tpcHit->Z()))
2092                                                         /fTPCParam->GetDriftV(); 
2093         // in microseconds!     
2094         Float_t attProb = fTPCParam->GetAttCoef()*
2095           fTPCParam->GetOxyCont()*time; //  fraction! 
2096    
2097         //-----------------------------------------------
2098         //  Loop over electrons
2099         //-----------------------------------------------
2100         Int_t index[3];
2101         index[1]=isec;
2102         for(Int_t nel=0;nel<qI;nel++){
2103           // skip if electron lost due to the attachment
2104           if((gRandom->Rndm(0)) < attProb) continue; // electron lost!
2105           xyz[0]=tpcHit->X();
2106           xyz[1]=tpcHit->Y();
2107           xyz[2]=tpcHit->Z();   
2108           //
2109           // protection for the nonphysical avalanche size (10**6 maximum)
2110           //  
2111           Double_t rn=TMath::Max(gRandom->Rndm(0),1.93e-22);
2112           xyz[3]= (Float_t) (-gasgain*TMath::Log(rn)); 
2113           index[0]=1;
2114           
2115           TransportElectron(xyz,index);    
2116           Int_t rowNumber;
2117           fTPCParam->GetPadRow(xyz,index); 
2118           // row 0 - cross talk from the innermost row
2119           // row fNRow+1 cross talk from the outermost row
2120           rowNumber = index[2]+1; 
2121           //transform position to local digit coordinates
2122           //relative to nearest pad row 
2123           if ((rowNumber<0)||rowNumber>fTPCParam->GetNRow(isec)+1) continue;
2124           Float_t x1,y1;
2125           if (isec <fTPCParam->GetNInnerSector()) {
2126             x1 = xyz[1]*fTPCParam->GetInnerPadPitchWidth();
2127             y1 = fTPCParam->GetYInner(rowNumber);
2128           }
2129           else{
2130             x1=xyz[1]*fTPCParam->GetOuterPadPitchWidth();
2131             y1 = fTPCParam->GetYOuter(rowNumber);
2132           }
2133           // gain inefficiency at the wires edges - linear
2134           x1=TMath::Abs(x1);
2135           y1-=1.;
2136           if(x1>y1) xyz[3]*=TMath::Max(1.e-6,(y1-x1+1.));       
2137        
2138           nofElectrons[rowNumber]++;      
2139           //----------------------------------
2140           // Expand vector if necessary
2141           //----------------------------------
2142           if(nofElectrons[rowNumber]>120){
2143             Int_t range = tracks[rowNumber]->GetNrows();
2144             if((nofElectrons[rowNumber])>(range-1)/4){
2145         
2146               tracks[rowNumber]->ResizeTo(range+400); // Add 100 electrons
2147             }
2148           }
2149           
2150           AliTPCFastVector &v = *tracks[rowNumber];
2151           Int_t idx = 4*nofElectrons[rowNumber]-3;
2152           Real_t * position = &(((AliTPCFastVector&)v).UncheckedAt(idx)); //make code faster
2153           memcpy(position,xyz,4*sizeof(Float_t));
2154  
2155         } // end of loop over electrons
2156
2157         tpcHit = (AliTPChit*)NextHit();
2158         
2159       } // end of loop over hits
2160     } // end of loop over tracks
2161
2162     //
2163     //   store remaining track (the last one) if not empty
2164     //
2165
2166      for(i=0;i<nrows+2;i++){
2167        if(nofElectrons[i]>0){
2168           AliTPCFastVector &v = *tracks[i];
2169           v(0) = previousTrack;
2170           tracks[i]->ResizeTo(4*nofElectrons[i]+1); // shrink if necessary
2171           row[i]->Add(tracks[i]);  
2172         }
2173         else{
2174           delete tracks[i];
2175           tracks[i]=0;
2176         }  
2177       }  
2178
2179           delete [] tracks;
2180           delete [] nofElectrons;
2181  
2182
2183 } // end of MakeSector
2184
2185
2186 //_____________________________________________________________________________
2187 void AliTPC::Init()
2188 {
2189   //
2190   // Initialise TPC detector after definition of geometry
2191   //
2192   Int_t i;
2193   //
2194   if(fDebug) {
2195     printf("\n%s: ",ClassName());
2196     for(i=0;i<35;i++) printf("*");
2197     printf(" TPC_INIT ");
2198     for(i=0;i<35;i++) printf("*");
2199     printf("\n%s: ",ClassName());
2200     //
2201     for(i=0;i<80;i++) printf("*");
2202     printf("\n");
2203   }
2204 }
2205
2206 //_____________________________________________________________________________
2207 void AliTPC::MakeBranch(Option_t* option)
2208 {
2209   //
2210   // Create Tree branches for the TPC.
2211   //
2212   if(GetDebug()) Info("MakeBranch","");
2213   Int_t buffersize = 4000;
2214   char branchname[10];
2215   sprintf(branchname,"%s",GetName());
2216   
2217   const char *h = strstr(option,"H");
2218
2219   if ( h && (fHitType<=1) && (fHits == 0x0)) fHits = new TClonesArray("AliTPChit", 176);//skowron 20.06.03
2220   
2221   AliDetector::MakeBranch(option);
2222
2223   const char *d = strstr(option,"D");
2224  
2225   if (fDigits   && fLoader->TreeD() && d) 
2226    {
2227       MakeBranchInTree(gAlice->TreeD(), branchname, &fDigits, buffersize, 0);
2228    }    
2229
2230   if (fHitType>1) MakeBranch2(option,0); // MI change 14.09.2000
2231 }
2232  
2233 //_____________________________________________________________________________
2234 void AliTPC::ResetDigits()
2235 {
2236   //
2237   // Reset number of digits and the digits array for this detector
2238   //
2239   fNdigits   = 0;
2240   if (fDigits)   fDigits->Clear();
2241 }
2242
2243 //_____________________________________________________________________________
2244 void AliTPC::SetSecAL(Int_t sec)
2245 {
2246   //---------------------------------------------------
2247   // Activate/deactivate selection for lower sectors
2248   //---------------------------------------------------
2249
2250   //-----------------------------------------------------------------
2251   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2252   //-----------------------------------------------------------------
2253   fSecAL = sec;
2254 }
2255
2256 //_____________________________________________________________________________
2257 void AliTPC::SetSecAU(Int_t sec)
2258 {
2259   //----------------------------------------------------
2260   // Activate/deactivate selection for upper sectors
2261   //---------------------------------------------------
2262
2263   //-----------------------------------------------------------------
2264   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2265   //-----------------------------------------------------------------
2266   fSecAU = sec;
2267 }
2268
2269 //_____________________________________________________________________________
2270 void AliTPC::SetSecLows(Int_t s1,Int_t s2,Int_t s3,Int_t s4,Int_t s5, Int_t s6)
2271 {
2272   //----------------------------------------
2273   // Select active lower sectors
2274   //----------------------------------------
2275
2276   //-----------------------------------------------------------------
2277   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2278   //-----------------------------------------------------------------
2279
2280   fSecLows[0] = s1;
2281   fSecLows[1] = s2;
2282   fSecLows[2] = s3;
2283   fSecLows[3] = s4;
2284   fSecLows[4] = s5;
2285   fSecLows[5] = s6;
2286 }
2287
2288 //_____________________________________________________________________________
2289 void AliTPC::SetSecUps(Int_t s1,Int_t s2,Int_t s3,Int_t s4,Int_t s5, Int_t s6,
2290                        Int_t s7, Int_t s8 ,Int_t s9 ,Int_t s10, 
2291                        Int_t s11 , Int_t s12)
2292 {
2293   //--------------------------------
2294   // Select active upper sectors
2295   //--------------------------------
2296
2297   //-----------------------------------------------------------------
2298   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2299   //-----------------------------------------------------------------
2300
2301   fSecUps[0] = s1;
2302   fSecUps[1] = s2;
2303   fSecUps[2] = s3;
2304   fSecUps[3] = s4;
2305   fSecUps[4] = s5;
2306   fSecUps[5] = s6;
2307   fSecUps[6] = s7;
2308   fSecUps[7] = s8;
2309   fSecUps[8] = s9;
2310   fSecUps[9] = s10;
2311   fSecUps[10] = s11;
2312   fSecUps[11] = s12;
2313 }
2314
2315 //_____________________________________________________________________________
2316 void AliTPC::SetSens(Int_t sens)
2317 {
2318
2319   //-------------------------------------------------------------
2320   // Activates/deactivates the sensitive strips at the center of
2321   // the pad row -- this is for the space-point resolution calculations
2322   //-------------------------------------------------------------
2323
2324   //-----------------------------------------------------------------
2325   // Origin: Marek Kowalski  IFJ, Krakow, Marek.Kowalski@ifj.edu.pl
2326   //-----------------------------------------------------------------
2327
2328   fSens = sens;
2329 }
2330
2331  
2332 void AliTPC::SetSide(Float_t side=0.)
2333 {
2334   // choice of the TPC side
2335
2336   fSide = side;
2337  
2338 }
2339 //____________________________________________________________________________
2340 void AliTPC::SetGasMixt(Int_t nc,Int_t c1,Int_t c2,Int_t c3,Float_t p1,
2341                            Float_t p2,Float_t p3)
2342 {
2343
2344   // gax mixture definition
2345
2346  fNoComp = nc;
2347  
2348  fMixtComp[0]=c1;
2349  fMixtComp[1]=c2;
2350  fMixtComp[2]=c3;
2351
2352  fMixtProp[0]=p1;
2353  fMixtProp[1]=p2;
2354  fMixtProp[2]=p3; 
2355  
2356  
2357 }
2358 //_____________________________________________________________________________
2359
2360 void AliTPC::TransportElectron(Float_t *xyz, Int_t *index)
2361 {
2362   //
2363   // electron transport taking into account:
2364   // 1. diffusion, 
2365   // 2.ExB at the wires
2366   // 3. nonisochronity
2367   //
2368   // xyz and index must be already transformed to system 1
2369   //
2370
2371   fTPCParam->Transform1to2(xyz,index);
2372   
2373   //add diffusion
2374   Float_t driftl=xyz[2];
2375   if(driftl<0.01) driftl=0.01;
2376   driftl=TMath::Sqrt(driftl);
2377   Float_t sigT = driftl*(fTPCParam->GetDiffT());
2378   Float_t sigL = driftl*(fTPCParam->GetDiffL());
2379   xyz[0]=gRandom->Gaus(xyz[0],sigT);
2380   xyz[1]=gRandom->Gaus(xyz[1],sigT);
2381   xyz[2]=gRandom->Gaus(xyz[2],sigL);
2382
2383   // ExB
2384   
2385   if (fTPCParam->GetMWPCReadout()==kTRUE){
2386     Float_t dx = fTPCParam->Transform2to2NearestWire(xyz,index);
2387     xyz[1]+=dx*(fTPCParam->GetOmegaTau());
2388   }
2389   //add nonisochronity (not implemented yet)  
2390 }
2391   
2392 ClassImp(AliTPCdigit)
2393  
2394 //_____________________________________________________________________________
2395 AliTPCdigit::AliTPCdigit(Int_t *tracks, Int_t *digits):
2396   AliDigit(tracks)
2397 {
2398   //
2399   // Creates a TPC digit object
2400   //
2401   fSector     = digits[0];
2402   fPadRow     = digits[1];
2403   fPad        = digits[2];
2404   fTime       = digits[3];
2405   fSignal     = digits[4];
2406 }
2407
2408  
2409 ClassImp(AliTPChit)
2410  
2411 //_____________________________________________________________________________
2412 AliTPChit::AliTPChit(Int_t shunt, Int_t track, Int_t *vol, Float_t *hits):
2413 AliHit(shunt,track)
2414 {
2415   //
2416   // Creates a TPC hit object
2417   //
2418   fSector     = vol[0];
2419   fPadRow     = vol[1];
2420   fX          = hits[0];
2421   fY          = hits[1];
2422   fZ          = hits[2];
2423   fQ          = hits[3];
2424 }
2425  
2426 //________________________________________________________________________
2427 // Additional code because of the AliTPCTrackHitsV2
2428
2429 void AliTPC::MakeBranch2(Option_t *option,const char *file)
2430 {
2431   //
2432   // Create a new branch in the current Root Tree
2433   // The branch of fHits is automatically split
2434   // MI change 14.09.2000
2435   if(GetDebug()) Info("MakeBranch2","");
2436   if (fHitType<2) return;
2437   char branchname[10];
2438   sprintf(branchname,"%s2",GetName());  
2439   //
2440   // Get the pointer to the header
2441   const char *cH = strstr(option,"H");
2442   //
2443   if (fTrackHits   && TreeH() && cH && fHitType&4) 
2444    {
2445     if(GetDebug()) Info("MakeBranch2","Making branch for Type 4 Hits");
2446     TreeH()->Branch(branchname,"AliTPCTrackHitsV2",&fTrackHits,fBufferSize,99);
2447    }    
2448
2449   if (fTrackHitsOld   && TreeH() && cH && fHitType&2) 
2450    {    
2451     if(GetDebug()) Info("MakeBranch2","Making branch for Type 2 Hits");
2452     AliObjectBranch * branch = new AliObjectBranch(branchname,"AliTPCTrackHits",&fTrackHitsOld, 
2453                                                    TreeH(),fBufferSize,99);
2454     TreeH()->GetListOfBranches()->Add(branch);
2455    }    
2456 }
2457
2458 void AliTPC::SetTreeAddress()
2459 {
2460 //Sets tree address for hits  
2461   if (fHitType<=1)
2462    {
2463      if (fHits == 0x0 ) fHits = new TClonesArray("AliTPChit", 176);//skowron 20.06.03
2464      AliDetector::SetTreeAddress();
2465    }
2466   if (fHitType>1) SetTreeAddress2();
2467 }
2468
2469 void AliTPC::SetTreeAddress2()
2470 {
2471   //
2472   // Set branch address for the TrackHits Tree
2473   // 
2474   if(GetDebug()) Info("SetTreeAddress2","");
2475   
2476   TBranch *branch;
2477   char branchname[20];
2478   sprintf(branchname,"%s2",GetName());
2479   //
2480   // Branch address for hit tree
2481   TTree *treeH = TreeH();
2482   if ((treeH)&&(fHitType&4)) {
2483     branch = treeH->GetBranch(branchname);
2484     if (branch) 
2485      {
2486        branch->SetAddress(&fTrackHits);
2487        cout<<"AliTPC::SetTreeAddress2 fHitType&4 Setting"<<endl;       
2488      }
2489     else cout<<"AliTPC::SetTreeAddress2 fHitType&4  Failed"<<endl;
2490   }
2491   if ((treeH)&&(fHitType&2)) {
2492     branch = treeH->GetBranch(branchname);
2493     if (branch) 
2494      {
2495        branch->SetAddress(&fTrackHitsOld);
2496        cout<<"AliTPC::SetTreeAddress2 fHitType&2 Setting"<<endl;       
2497      }
2498     else cout<<"AliTPC::SetTreeAddress2 fHitType&2  Failed"<<endl;
2499   }
2500   //set address to TREETR
2501
2502   TTree *treeTR = TreeTR();
2503   if (treeTR && fTrackReferences) {
2504     branch = treeTR->GetBranch(GetName());
2505     if (branch) branch->SetAddress(&fTrackReferences);
2506   }
2507
2508 }
2509
2510 void AliTPC::FinishPrimary()
2511 {
2512   if (fTrackHits &&fHitType&4)      fTrackHits->FlushHitStack();  
2513   if (fTrackHitsOld && fHitType&2)  fTrackHitsOld->FlushHitStack();  
2514 }
2515
2516
2517 void AliTPC::AddHit2(Int_t track, Int_t *vol, Float_t *hits)
2518
2519   //
2520   // add hit to the list  
2521   Int_t rtrack;
2522   if (fIshunt) {
2523     int primary = gAlice->GetPrimary(track);
2524     gAlice->Particle(primary)->SetBit(kKeepBit);
2525     rtrack=primary;
2526   } else {
2527     rtrack=track;
2528     gAlice->FlagTrack(track);
2529   }  
2530   //AliTPChit *hit = (AliTPChit*)fHits->UncheckedAt(fNhits-1);
2531   //if (hit->fTrack!=rtrack)
2532   //  cout<<"bad track number\n";
2533   if (fTrackHits && fHitType&4) 
2534     fTrackHits->AddHitKartez(vol[0],rtrack, hits[0],
2535                              hits[1],hits[2],(Int_t)hits[3]);
2536   if (fTrackHitsOld &&fHitType&2 ) 
2537     fTrackHitsOld->AddHitKartez(vol[0],rtrack, hits[0],
2538                                 hits[1],hits[2],(Int_t)hits[3]);
2539   
2540 }
2541
2542 void AliTPC::ResetHits()
2543
2544   if (fHitType&1) AliDetector::ResetHits();
2545   if (fHitType>1) ResetHits2();
2546 }
2547
2548 void AliTPC::ResetHits2()
2549 {
2550   //
2551   //reset hits
2552   if (fTrackHits && fHitType&4) fTrackHits->Clear();
2553   if (fTrackHitsOld && fHitType&2) fTrackHitsOld->Clear();
2554
2555 }   
2556
2557 AliHit* AliTPC::FirstHit(Int_t track)
2558 {
2559   if (fHitType>1) return FirstHit2(track);
2560   return AliDetector::FirstHit(track);
2561 }
2562 AliHit* AliTPC::NextHit()
2563 {
2564   if (fHitType>1) return NextHit2();
2565   
2566   return AliDetector::NextHit();
2567 }
2568
2569 AliHit* AliTPC::FirstHit2(Int_t track)
2570 {
2571   //
2572   // Initialise the hit iterator
2573   // Return the address of the first hit for track
2574   // If track>=0 the track is read from disk
2575   // while if track<0 the first hit of the current
2576   // track is returned
2577   // 
2578   if(track>=0) {
2579     gAlice->ResetHits();
2580     TreeH()->GetEvent(track);
2581   }
2582   //
2583   if (fTrackHits && fHitType&4) {
2584     fTrackHits->First();
2585     return fTrackHits->GetHit();
2586   }
2587   if (fTrackHitsOld && fHitType&2) {
2588     fTrackHitsOld->First();
2589     return fTrackHitsOld->GetHit();
2590   }
2591
2592   else return 0;
2593 }
2594
2595 AliHit* AliTPC::NextHit2()
2596 {
2597   //
2598   //Return the next hit for the current track
2599
2600
2601   if (fTrackHitsOld && fHitType&2) {
2602     fTrackHitsOld->Next();
2603     return fTrackHitsOld->GetHit();
2604   }
2605   if (fTrackHits) {
2606     fTrackHits->Next();
2607     return fTrackHits->GetHit();
2608   }
2609   else 
2610     return 0;
2611 }
2612
2613 void AliTPC::LoadPoints(Int_t)
2614 {
2615   //
2616   Int_t a = 0;
2617   /*  if(fHitType==1) return AliDetector::LoadPoints(a);
2618   LoadPoints2(a);
2619   */
2620   if(fHitType==1) AliDetector::LoadPoints(a);
2621   else LoadPoints2(a);
2622    
2623   // LoadPoints3(a);
2624
2625 }
2626
2627
2628 void AliTPC::RemapTrackHitIDs(Int_t *map)
2629 {
2630   if (!fTrackHits) return;
2631   
2632   if (fTrackHitsOld && fHitType&2){
2633     AliObjectArray * arr = fTrackHitsOld->fTrackHitsInfo;
2634     for (UInt_t i=0;i<arr->GetSize();i++){
2635       AliTrackHitsInfo * info = (AliTrackHitsInfo *)(arr->At(i));
2636       info->fTrackID = map[info->fTrackID];
2637     }
2638   }
2639   if (fTrackHitsOld && fHitType&4){
2640     TClonesArray * arr = fTrackHits->GetArray();;
2641     for (Int_t i=0;i<arr->GetEntriesFast();i++){
2642       AliTrackHitsParamV2 * info = (AliTrackHitsParamV2 *)(arr->At(i));
2643       info->fTrackID = map[info->fTrackID];
2644     }
2645   }
2646 }
2647
2648 Bool_t   AliTPC::TrackInVolume(Int_t id,Int_t track)
2649 {
2650   //return bool information - is track in given volume
2651   //load only part of the track information 
2652   //return true if current track is in volume
2653   //
2654   //  return kTRUE;
2655   if (fTrackHitsOld && fHitType&2) {
2656     TBranch * br = TreeH()->GetBranch("fTrackHitsInfo");
2657     br->GetEvent(track);
2658     AliObjectArray * ar = fTrackHitsOld->fTrackHitsInfo;
2659     for (UInt_t j=0;j<ar->GetSize();j++){
2660       if (  ((AliTrackHitsInfo*)ar->At(j))->fVolumeID==id) return kTRUE;
2661     } 
2662   }
2663
2664   if (fTrackHits && fHitType&4) {
2665     TBranch * br1 = TreeH()->GetBranch("fVolumes");
2666     TBranch * br2 = TreeH()->GetBranch("fNVolumes");    
2667     br2->GetEvent(track);
2668     br1->GetEvent(track);    
2669     Int_t *volumes = fTrackHits->GetVolumes();
2670     Int_t nvolumes = fTrackHits->GetNVolumes();
2671     if (!volumes && nvolumes>0) {
2672       printf("Problematic track\t%d\t%d",track,nvolumes);
2673       return kFALSE;
2674     }
2675     for (Int_t j=0;j<nvolumes; j++)
2676       if (volumes[j]==id) return kTRUE;    
2677   }
2678
2679   if (fHitType&1) {
2680     TBranch * br = TreeH()->GetBranch("fSector");
2681     br->GetEvent(track);
2682     for (Int_t j=0;j<fHits->GetEntriesFast();j++){
2683       if (  ((AliTPChit*)fHits->At(j))->fSector==id) return kTRUE;
2684     } 
2685   }
2686   return kFALSE;  
2687
2688 }
2689
2690 //_____________________________________________________________________________
2691 void AliTPC::LoadPoints2(Int_t)
2692 {
2693   //
2694   // Store x, y, z of all hits in memory
2695   //
2696   if (fTrackHits == 0 && fTrackHitsOld==0) return;
2697   //
2698   Int_t nhits =0;
2699   if (fHitType&4) nhits = fTrackHits->GetEntriesFast();
2700   if (fHitType&2) nhits = fTrackHitsOld->GetEntriesFast();
2701   
2702   if (nhits == 0) return;
2703   Int_t tracks = gAlice->GetNtrack();
2704   if (fPoints == 0) fPoints = new TObjArray(tracks);
2705   AliHit *ahit;
2706   //
2707   Int_t *ntrk=new Int_t[tracks];
2708   Int_t *limi=new Int_t[tracks];
2709   Float_t **coor=new Float_t*[tracks];
2710   for(Int_t i=0;i<tracks;i++) {
2711     ntrk[i]=0;
2712     coor[i]=0;
2713     limi[i]=0;
2714   }
2715   //
2716   AliPoints *points = 0;
2717   Float_t *fp=0;
2718   Int_t trk;
2719   Int_t chunk=nhits/4+1;
2720   //
2721   // Loop over all the hits and store their position
2722   //
2723   ahit = FirstHit2(-1);
2724   while (ahit){
2725     trk=ahit->GetTrack();
2726     if(ntrk[trk]==limi[trk]) {
2727       //
2728       // Initialise a new track
2729       fp=new Float_t[3*(limi[trk]+chunk)];
2730       if(coor[trk]) {
2731         memcpy(fp,coor[trk],sizeof(Float_t)*3*limi[trk]);
2732         delete [] coor[trk];
2733       }
2734       limi[trk]+=chunk;
2735       coor[trk] = fp;
2736     } else {
2737       fp = coor[trk];
2738     }
2739     fp[3*ntrk[trk]  ] = ahit->X();
2740     fp[3*ntrk[trk]+1] = ahit->Y();
2741     fp[3*ntrk[trk]+2] = ahit->Z();
2742     ntrk[trk]++;
2743     ahit = NextHit2();
2744   }
2745
2746
2747
2748   //
2749   for(trk=0; trk<tracks; ++trk) {
2750     if(ntrk[trk]) {
2751       points = new AliPoints();
2752       points->SetMarkerColor(GetMarkerColor());
2753       points->SetMarkerSize(GetMarkerSize());
2754       points->SetDetector(this);
2755       points->SetParticle(trk);
2756       points->SetPolyMarker(ntrk[trk],coor[trk],GetMarkerStyle());
2757       fPoints->AddAt(points,trk);
2758       delete [] coor[trk];
2759       coor[trk]=0;
2760     }
2761   }
2762   delete [] coor;
2763   delete [] ntrk;
2764   delete [] limi;
2765 }
2766
2767
2768 //_____________________________________________________________________________
2769 void AliTPC::LoadPoints3(Int_t)
2770 {
2771   //
2772   // Store x, y, z of all hits in memory
2773   // - only intersection point with pad row
2774   if (fTrackHits == 0) return;
2775   //
2776   Int_t nhits = fTrackHits->GetEntriesFast();
2777   if (nhits == 0) return;
2778   Int_t tracks = gAlice->GetNtrack();
2779   if (fPoints == 0) fPoints = new TObjArray(2*tracks);
2780   fPoints->Expand(2*tracks);
2781   AliHit *ahit;
2782   //
2783   Int_t *ntrk=new Int_t[tracks];
2784   Int_t *limi=new Int_t[tracks];
2785   Float_t **coor=new Float_t*[tracks];
2786   for(Int_t i=0;i<tracks;i++) {
2787     ntrk[i]=0;
2788     coor[i]=0;
2789     limi[i]=0;
2790   }
2791   //
2792   AliPoints *points = 0;
2793   Float_t *fp=0;
2794   Int_t trk;
2795   Int_t chunk=nhits/4+1;
2796   //
2797   // Loop over all the hits and store their position
2798   //
2799   ahit = FirstHit2(-1);
2800   //for (Int_t hit=0;hit<nhits;hit++) {
2801
2802   Int_t lastrow = -1;
2803   while (ahit){
2804     //    ahit = (AliHit*)fHits->UncheckedAt(hit);
2805     trk=ahit->GetTrack(); 
2806     Float_t  x[3]={ahit->X(),ahit->Y(),ahit->Z()};
2807     Int_t    index[3]={1,((AliTPChit*)ahit)->fSector,0};
2808     Int_t    currentrow = fTPCParam->GetPadRow(x,index) ;
2809     if (currentrow!=lastrow){
2810       lastrow = currentrow;
2811       //later calculate intersection point           
2812       if(ntrk[trk]==limi[trk]) {
2813         //
2814         // Initialise a new track
2815         fp=new Float_t[3*(limi[trk]+chunk)];
2816         if(coor[trk]) {
2817           memcpy(fp,coor[trk],sizeof(Float_t)*3*limi[trk]);
2818           delete [] coor[trk];
2819         }
2820         limi[trk]+=chunk;
2821         coor[trk] = fp;
2822       } else {
2823         fp = coor[trk];
2824       }
2825       fp[3*ntrk[trk]  ] = ahit->X();
2826       fp[3*ntrk[trk]+1] = ahit->Y();
2827       fp[3*ntrk[trk]+2] = ahit->Z();
2828       ntrk[trk]++;
2829     }
2830     ahit = NextHit2();
2831   }
2832   
2833   //
2834   for(trk=0; trk<tracks; ++trk) {
2835     if(ntrk[trk]) {
2836       points = new AliPoints();
2837       points->SetMarkerColor(GetMarkerColor()+1);
2838       points->SetMarkerStyle(5);
2839       points->SetMarkerSize(0.2);
2840       points->SetDetector(this);
2841       points->SetParticle(trk);
2842       //      points->SetPolyMarker(ntrk[trk],coor[trk],GetMarkerStyle()20);
2843       points->SetPolyMarker(ntrk[trk],coor[trk],30);
2844       fPoints->AddAt(points,tracks+trk);
2845       delete [] coor[trk];
2846       coor[trk]=0;
2847     }
2848   }
2849   delete [] coor;
2850   delete [] ntrk;
2851   delete [] limi;
2852 }
2853
2854
2855
2856 void AliTPC::FindTrackHitsIntersection(TClonesArray * arr)
2857 {
2858
2859   //
2860   //fill clones array with intersection of current point with the
2861   //middle of the row
2862   Int_t sector;
2863   Int_t ipart;
2864   
2865   const Int_t kcmaxhits=30000;
2866   AliTPCFastVector * xxxx = new AliTPCFastVector(kcmaxhits*4);
2867   AliTPCFastVector & xxx = *xxxx;
2868   Int_t maxhits = kcmaxhits;
2869       
2870   //
2871   AliTPChit * tpcHit=0;
2872   tpcHit = (AliTPChit*)FirstHit2(-1);
2873   Int_t currentIndex=0;
2874   Int_t lastrow=-1;  //last writen row
2875
2876   while (tpcHit){
2877     if (tpcHit==0) continue;
2878     sector=tpcHit->fSector; // sector number
2879     ipart=tpcHit->Track();
2880     
2881     //find row number
2882     
2883     Float_t  x[3]={tpcHit->X(),tpcHit->Y(),tpcHit->Z()};
2884     Int_t    index[3]={1,sector,0};
2885     Int_t    currentrow = fTPCParam->GetPadRow(x,index) ;       
2886     if (currentrow<0) continue;
2887     if (lastrow<0) lastrow=currentrow;
2888     if (currentrow==lastrow){
2889       if ( currentIndex>=maxhits){
2890         maxhits+=kcmaxhits;
2891         xxx.ResizeTo(4*maxhits);
2892       }     
2893       xxx(currentIndex*4)=x[0];
2894       xxx(currentIndex*4+1)=x[1];
2895       xxx(currentIndex*4+2)=x[2];       
2896       xxx(currentIndex*4+3)=tpcHit->fQ;
2897       currentIndex++;   
2898     }
2899     else 
2900       if (currentIndex>2){
2901         Float_t sumx=0;
2902         Float_t sumx2=0;
2903         Float_t sumx3=0;
2904         Float_t sumx4=0;
2905         Float_t sumy=0;
2906         Float_t sumxy=0;
2907         Float_t sumx2y=0;
2908         Float_t sumz=0;
2909         Float_t sumxz=0;
2910         Float_t sumx2z=0;
2911         Float_t sumq=0;
2912         for (Int_t index=0;index<currentIndex;index++){
2913           Float_t x,x2,x3,x4;
2914           x=x2=x3=x4=xxx(index*4);
2915           x2*=x;
2916           x3*=x2;
2917           x4*=x3;
2918           sumx+=x;
2919           sumx2+=x2;
2920           sumx3+=x3;
2921           sumx4+=x4;
2922           sumy+=xxx(index*4+1);
2923           sumxy+=xxx(index*4+1)*x;
2924           sumx2y+=xxx(index*4+1)*x2;
2925           sumz+=xxx(index*4+2);
2926           sumxz+=xxx(index*4+2)*x;
2927           sumx2z+=xxx(index*4+2)*x2;     
2928           sumq+=xxx(index*4+3);
2929         }
2930         Float_t centralPad = (fTPCParam->GetNPads(sector,lastrow)-1)/2;
2931         Float_t det=currentIndex*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumx*sumx4-sumx2*sumx3)+
2932           sumx2*(sumx*sumx3-sumx2*sumx2);
2933         
2934         Float_t detay=sumy*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumxy*sumx4-sumx2y*sumx3)+
2935           sumx2*(sumxy*sumx3-sumx2y*sumx2);
2936         Float_t detaz=sumz*(sumx2*sumx4-sumx3*sumx3)-sumx*(sumxz*sumx4-sumx2z*sumx3)+
2937           sumx2*(sumxz*sumx3-sumx2z*sumx2);
2938         
2939         Float_t detby=currentIndex*(sumxy*sumx4-sumx2y*sumx3)-sumy*(sumx*sumx4-sumx2*sumx3)+
2940           sumx2*(sumx*sumx2y-sumx2*sumxy);
2941         Float_t detbz=currentIndex*(sumxz*sumx4-sumx2z*sumx3)-sumz*(sumx*sumx4-sumx2*sumx3)+
2942           sumx2*(sumx*sumx2z-sumx2*sumxz);
2943         
2944         Float_t y=detay/det+centralPad;
2945         Float_t z=detaz/det;    
2946         Float_t by=detby/det; //y angle
2947         Float_t bz=detbz/det; //z angle
2948         sumy/=Float_t(currentIndex);
2949         sumz/=Float_t(currentIndex);
2950         
2951         AliComplexCluster cl;
2952         cl.fX=z;
2953         cl.fY=y;
2954         cl.fQ=sumq;
2955         cl.fSigmaX2=bz;
2956         cl.fSigmaY2=by;
2957         cl.fTracks[0]=ipart;
2958         
2959         AliTPCClustersRow * row = (fClustersArray->GetRow(sector,lastrow));
2960         if (row!=0) row->InsertCluster(&cl);
2961         currentIndex=0;
2962         lastrow=currentrow;
2963       } //end of calculating cluster for given row
2964                 
2965   } // end of loop over hits
2966   xxxx->Delete();
2967
2968 }
2969 //_______________________________________________________________________________
2970 void AliTPC::Digits2Reco(Int_t firstevent,Int_t lastevent)
2971 {
2972   // produces rec points from digits and writes them on the root file
2973   // AliTPCclusters.root
2974
2975   TDirectory *cwd = gDirectory;
2976
2977
2978   AliTPCParamSR *dig=(AliTPCParamSR *)gDirectory->Get("75x40_100x60");
2979   if(dig){
2980     printf("You are running 2 pad-length geom hits with 3 pad-length geom digits\n");
2981     delete dig;
2982     dig = new AliTPCParamSR();
2983   }
2984   else
2985   {
2986    dig=(AliTPCParamSR *)gDirectory->Get("75x40_100x60_150x60"); 
2987   }
2988   if(!dig){
2989    printf("No TPC parameters found\n");
2990    exit(3);
2991   }
2992    
2993   SetParam(dig);
2994   cout<<"AliTPC::Digits2Reco: TPC parameteres have been set"<<endl; 
2995   TFile *out;
2996   if(!gSystem->Getenv("CONFIG_FILE")){
2997     out=TFile::Open("AliTPCclusters.root","recreate");
2998   }
2999   else {
3000     const char *tmp1;
3001     const char *tmp2;
3002     char tmp3[80];
3003     tmp1=gSystem->Getenv("CONFIG_FILE_PREFIX");
3004     tmp2=gSystem->Getenv("CONFIG_OUTDIR");
3005     sprintf(tmp3,"%s%s/AliTPCclusters.root",tmp1,tmp2);
3006     out=TFile::Open(tmp3,"recreate");
3007   }
3008
3009   TStopwatch timer;
3010   cout<<"AliTPC::Digits2Reco - determination of rec points begins"<<endl;
3011   timer.Start();
3012   cwd->cd();
3013   for(Int_t iev=firstevent;iev<lastevent+1;iev++){
3014
3015     printf("Processing event %d\n",iev);
3016     Digits2Clusters(iev);
3017   }
3018   cout<<"AliTPC::Digits2Reco - determination of rec points ended"<<endl;
3019   timer.Stop();
3020   timer.Print();
3021   out->Close();
3022   cwd->cd(); 
3023
3024
3025 }
3026
3027 AliLoader* AliTPC::MakeLoader(const char* topfoldername)
3028 {
3029  cout<<"AliTPC::MakeLoader ";
3030  
3031  fLoader = new AliTPCLoader(GetName(),topfoldername);
3032  
3033  if (fLoader)
3034   {
3035    cout<<"Success"<<endl;
3036   }
3037  else
3038   {
3039    cout<<"Failure"<<endl;
3040   }
3041
3042  return fLoader;
3043 }
3044
3045 ////////////////////////////////////////////////////////////////////////
3046 AliTPCParam* AliTPC::LoadTPCParam(TFile *file) {
3047 //
3048 // load TPC paarmeters from a given file or create new if the object
3049 // is not found there
3050 // 12/05/2003 This method should be moved to the AliTPCLoader
3051 // and one has to decide where to store the TPC parameters
3052 // M.Kowalski
3053   char paramName[50];
3054   sprintf(paramName,"75x40_100x60_150x60");
3055   AliTPCParam *paramTPC=(AliTPCParam*)file->Get(paramName);
3056   if (paramTPC) {
3057     cout<<"TPC parameters "<<paramName<<" found."<<endl;
3058   } else {
3059     cerr<<"TPC parameters not found. Create new (they may be incorrect)."
3060         <<endl;    
3061     paramTPC = new AliTPCParamSR;
3062   }
3063   return paramTPC;
3064
3065 // the older version of parameters can be accessed with this code.
3066 // In some cases, we have old parameters saved in the file but 
3067 // digits were created with new parameters, it can be distinguish 
3068 // by the name of TPC TreeD. The code here is just for the case 
3069 // we would need to compare with old data, uncomment it if needed.
3070 //
3071 //  char paramName[50];
3072 //  sprintf(paramName,"75x40_100x60");
3073 //  AliTPCParam *paramTPC=(AliTPCParam*)in->Get(paramName);
3074 //  if (paramTPC) {
3075 //    cout<<"TPC parameters "<<paramName<<" found."<<endl;
3076 //  } else {
3077 //    sprintf(paramName,"75x40_100x60_150x60");
3078 //    paramTPC=(AliTPCParam*)in->Get(paramName);
3079 //    if (paramTPC) {
3080 //      cout<<"TPC parameters "<<paramName<<" found."<<endl;
3081 //    } else {
3082 //      cerr<<"TPC parameters not found. Create new (they may be incorrect)."
3083 //          <<endl;    
3084 //      paramTPC = new AliTPCParamSR;
3085 //    }
3086 //  }
3087 //  return paramTPC;
3088
3089 }
3090