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