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