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