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