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