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