]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliRun.cxx
3b08c26f41a7a1e2a11a8ce6f8c18af227096675
[u/mrichter/AliRoot.git] / STEER / AliRun.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /*
17 $Log$
18 Revision 1.53  2001/02/06 11:02:26  hristov
19 New SetTrack interface added, added check for unfilled particles in FinishEvent (I.Hrivnacova)
20
21 Revision 1.52  2001/02/05 16:22:25  buncic
22 Added TreeS to GetEvent().
23
24 Revision 1.51  2001/02/02 15:16:20  morsch
25 SetHighWaterMark method added to mark last particle in event.
26
27 Revision 1.50  2001/01/27 10:32:00  hristov
28 Leave the loop when primaries are filled (I.Hrivnacova)
29
30 Revision 1.49  2001/01/26 19:58:48  hristov
31 Major upgrade of AliRoot code
32
33 Revision 1.48  2001/01/17 10:50:50  hristov
34 Corrections to destructors
35
36 Revision 1.47  2000/12/18 10:44:01  morsch
37 Possibility to set field map by passing pointer to objet of type AliMagF via
38 SetField().
39 Example:
40 gAlice->SetField(new AliMagFCM("Map2", "$(ALICE_ROOT)/data/field01.dat",2,1.,10.));
41
42 Revision 1.46  2000/12/14 19:29:27  fca
43 galice.cuts was not read any more
44
45 Revision 1.45  2000/11/30 07:12:49  alibrary
46 Introducing new Rndm and QA classes
47
48 Revision 1.44  2000/10/26 13:58:59  morsch
49 Add possibility to choose the lego generator (of type AliGeneratorLego or derived) when running
50 RunLego(). Default is the base class AliGeneratorLego.
51
52 Revision 1.43  2000/10/09 09:43:17  fca
53 Special remapping of hits for TPC and TRD. End-of-primary action introduced
54
55 Revision 1.42  2000/10/02 21:28:14  fca
56 Removal of useless dependecies via forward declarations
57
58 Revision 1.41  2000/07/13 16:19:09  fca
59 Mainly coding conventions + some small bug fixes
60
61 Revision 1.40  2000/07/12 08:56:25  fca
62 Coding convention correction and warning removal
63
64 Revision 1.39  2000/07/11 18:24:59  fca
65 Coding convention corrections + few minor bug fixes
66
67 Revision 1.38  2000/06/20 13:05:45  fca
68 Writing down the TREE headers before job starts
69
70 Revision 1.37  2000/06/09 20:05:11  morsch
71 Introduce possibility to chose magnetic field version 3: AliMagFDM + field02.dat
72
73 Revision 1.36  2000/06/08 14:03:58  hristov
74 Only one initializer for a default argument
75
76 Revision 1.35  2000/06/07 10:13:14  hristov
77 Delete only existent objects.
78
79 Revision 1.34  2000/05/18 10:45:38  fca
80 Delete Particle Factory properly
81
82 Revision 1.33  2000/05/16 13:10:40  fca
83 New method IsNewTrack and fix for a problem in Father-Daughter relations
84
85 Revision 1.32  2000/04/27 10:38:21  fca
86 Correct termination of Lego Run and introduce Lego getter in AliRun
87
88 Revision 1.31  2000/04/26 10:17:32  fca
89 Changes in Lego for G4 compatibility
90
91 Revision 1.30  2000/04/18 19:11:40  fca
92 Introduce variable Config.C function signature
93
94 Revision 1.29  2000/04/07 11:12:34  fca
95 G4 compatibility changes
96
97 Revision 1.28  2000/04/05 06:51:06  fca
98 Workaround for an HP compiler problem
99
100 Revision 1.27  2000/03/22 18:08:07  fca
101 Rationalisation of the virtual MC interfaces
102
103 Revision 1.26  2000/03/22 13:42:26  fca
104 SetGenerator does not replace an existing generator, ResetGenerator does
105
106 Revision 1.25  2000/02/23 16:25:22  fca
107 AliVMC and AliGeant3 classes introduced
108 ReadEuclid moved from AliRun to AliModule
109
110 Revision 1.24  2000/01/19 17:17:20  fca
111 Introducing a list of lists of hits -- more hits allowed for detector now
112
113 Revision 1.23  1999/12/03 11:14:31  fca
114 Fixing previous wrong checking
115
116 Revision 1.21  1999/11/25 10:40:08  fca
117 Fixing daughters information also in primary tracks
118
119 Revision 1.20  1999/10/04 18:08:49  fca
120 Adding protection against inconsistent Euclid files
121
122 Revision 1.19  1999/09/29 07:50:40  fca
123 Introduction of the Copyright and cvs Log
124
125 */
126
127 ///////////////////////////////////////////////////////////////////////////////
128 //                                                                           //
129 //  Control class for Alice C++                                              //
130 //  Only one single instance of this class exists.                           //
131 //  The object is created in main program aliroot                            //
132 //  and is pointed by the global gAlice.                                     //
133 //                                                                           //
134 //   -Supports the list of all Alice Detectors (fModules).                 //
135 //   -Supports the list of particles (fParticles).                           //
136 //   -Supports the Trees.                                                    //
137 //   -Supports the geometry.                                                 //
138 //   -Supports the event display.                                            //
139 //Begin_Html
140 /*
141 <img src="picts/AliRunClass.gif">
142 */
143 //End_Html
144 //Begin_Html
145 /*
146 <img src="picts/alirun.gif">
147 */
148 //End_Html
149 //                                                                           //
150 ///////////////////////////////////////////////////////////////////////////////
151
152 #include <stdlib.h>
153 #include <stdio.h>
154 #include <string.h>
155 #include <iostream.h>
156  
157 #include <TFile.h>
158 #include <TRandom.h>
159 #include <TBRIK.h> 
160 #include <TNode.h> 
161 #include <TCint.h> 
162 #include <TSystem.h>
163 #include <TObjectTable.h>
164 #include <TTree.h>
165 #include <TGeometry.h>
166 #include <TROOT.h>
167 #include "TBrowser.h"
168
169 #include "TParticle.h"
170 #include "AliRun.h"
171 #include "AliDisplay.h"
172 #include "AliMC.h"
173 #include "AliLego.h"
174 #include "AliMagFC.h"
175 #include "AliMagFCM.h"
176 #include "AliMagFDM.h"
177 #include "AliHit.h"
178 #include "TRandom3.h"
179 #include "AliMCQA.h"
180 #include "AliGenerator.h"
181 #include "AliLegoGenerator.h"
182
183 #include "AliDetector.h"
184
185 AliRun *gAlice;
186
187 static AliHeader *gAliHeader;
188
189 ClassImp(AliRun)
190
191 //_____________________________________________________________________________
192 AliRun::AliRun()
193 {
194   //
195   // Default constructor for AliRun
196   //
197   gAliHeader=&fHeader;
198   fRun       = 0;
199   fEvent     = 0;
200   fCurrent   = -1;
201   fModules = 0;
202   fGenerator = 0;
203   fTreeD     = 0;
204   fTreeK     = 0;
205   fTreeH     = 0;
206   fTreeE     = 0;
207   fTreeR     = 0;
208   fTreeS     = 0;
209   fParticles = 0;
210   fGeometry  = 0;
211   fDisplay   = 0;
212   fField     = 0;
213   fMC       = 0;
214   fNdets     = 0;
215   fImedia    = 0;
216   fTrRmax    = 1.e10;
217   fTrZmax    = 1.e10;
218   fInitDone  = kFALSE;
219   fLego      = 0;
220   fPDGDB     = 0;        //Particle factory object!
221   fHitLists  = 0;
222   fConfigFunction    = "\0";
223   fRandom = 0;
224   fMCQA = 0;
225   fTransParName = "\0";
226   fBaseFileName = "\0";
227   fParticleBuffer = 0;
228   fParticleMap = new TObjArray(10000);
229 }
230
231 //_____________________________________________________________________________
232 AliRun::AliRun(const char *name, const char *title)
233   : TNamed(name,title)
234 {
235   //
236   //  Constructor for the main processor.
237   //  Creates the geometry
238   //  Creates the list of Detectors.
239   //  Creates the list of particles.
240   //
241   Int_t i;
242   
243   gAlice     = this;
244   fTreeD     = 0;
245   fTreeK     = 0;
246   fTreeH     = 0;
247   fTreeE     = 0;
248   fTreeR     = 0;
249   fTreeS     = 0;
250   fTrRmax    = 1.e10;
251   fTrZmax    = 1.e10;
252   fGenerator = 0;
253   fInitDone  = kFALSE;
254   fLego      = 0;
255   fField     = 0;
256   fConfigFunction    = "Config();";
257
258   // Set random number generator
259   gRandom = fRandom = new TRandom3();
260
261   if (gSystem->Getenv("CONFIG_SEED")) {
262      gRandom->SetSeed((UInt_t)atoi(gSystem->Getenv("CONFIG_SEED")));
263   }
264   
265   gROOT->GetListOfBrowsables()->Add(this,name);
266   //
267   // create the support list for the various Detectors
268   fModules = new TObjArray(77);
269   //
270   // Create the TNode geometry for the event display
271   
272   BuildSimpleGeometry();
273   
274
275   fNtrack=0;
276   fHgwmk=0;
277   fCurrent=-1;
278   gAliHeader=&fHeader;
279   fRun       = 0;
280   fEvent     = 0;
281   //
282   // Create the particle stack
283   fParticles = new TClonesArray("TParticle",1000);
284   
285   fDisplay = 0;
286   //
287   // Create default mag field
288   SetField();
289   //
290   fMC      = gMC;
291   //
292   // Prepare the tracking medium lists
293   fImedia = new TArrayI(1000);
294   for(i=0;i<1000;i++) (*fImedia)[i]=-99;
295   //
296   // Make particles
297   fPDGDB     = TDatabasePDG::Instance();        //Particle factory object!
298   //
299   // Create HitLists list
300   fHitLists  = new TList();
301   //
302   SetTransPar();
303   fBaseFileName = "\0";
304   fParticleBuffer = 0;
305   fParticleMap = new TObjArray(10000);
306 }
307
308
309 //_____________________________________________________________________________
310 AliRun::~AliRun()
311 {
312   //
313   // Default AliRun destructor
314   //
315   delete fImedia;
316   delete fField;
317   delete fMC;
318   delete fGeometry;
319   delete fDisplay;
320   delete fGenerator;
321   delete fLego;
322   delete fTreeD;
323   delete fTreeK;
324   delete fTreeH;
325   delete fTreeE;
326   delete fTreeR;
327   delete fTreeS;
328   if (fModules) {
329     fModules->Delete();
330     delete fModules;
331   }
332   if (fParticles) {
333     fParticles->Delete();
334     delete fParticles;
335   }
336   delete fHitLists;
337   delete fPDGDB;
338   delete fMCQA;
339 }
340
341 //_____________________________________________________________________________
342 void AliRun::AddHit(Int_t id, Int_t track, Int_t *vol, Float_t *hits) const
343 {
344   //
345   //  Add a hit to detector id
346   //
347   TObjArray &dets = *fModules;
348   if(dets[id]) ((AliModule*) dets[id])->AddHit(track,vol,hits);
349 }
350
351 //_____________________________________________________________________________
352 void AliRun::AddDigit(Int_t id, Int_t *tracks, Int_t *digits) const
353 {
354   //
355   // Add digit to detector id
356   //
357   TObjArray &dets = *fModules;
358   if(dets[id]) ((AliModule*) dets[id])->AddDigit(tracks,digits);
359 }
360
361 //_____________________________________________________________________________
362 void AliRun::Browse(TBrowser *b)
363 {
364   //
365   // Called when the item "Run" is clicked on the left pane
366   // of the Root browser.
367   // It displays the Root Trees and all detectors.
368   //
369   if (fTreeK) b->Add(fTreeK,fTreeK->GetName());
370   if (fTreeH) b->Add(fTreeH,fTreeH->GetName());
371   if (fTreeD) b->Add(fTreeD,fTreeD->GetName());
372   if (fTreeE) b->Add(fTreeE,fTreeE->GetName());
373   if (fTreeR) b->Add(fTreeR,fTreeR->GetName());
374   if (fTreeS) b->Add(fTreeS,fTreeS->GetName());
375   
376   TIter next(fModules);
377   AliModule *detector;
378   while((detector = (AliModule*)next())) {
379     b->Add(detector,detector->GetName());
380   }
381   b->Add(fMCQA,"AliMCQA");
382 }
383
384 //_____________________________________________________________________________
385 void AliRun::Build()
386 {
387   //
388   // Initialize Alice geometry
389   // Dummy routine
390   //
391 }
392  
393 //_____________________________________________________________________________
394 void AliRun::BuildSimpleGeometry()
395 {
396   //
397   // Create a simple TNode geometry used by Root display engine
398   //
399   // Initialise geometry
400   //
401   fGeometry = new TGeometry("AliceGeom","Galice Geometry for Hits");
402   new TMaterial("void","Vacuum",0,0,0);  //Everything is void
403   TBRIK *brik = new TBRIK("S_alice","alice volume","void",2000,2000,3000);
404   brik->SetVisibility(0);
405   new TNode("alice","alice","S_alice");
406 }
407
408 //_____________________________________________________________________________
409 void AliRun::CleanDetectors()
410 {
411   //
412   // Clean Detectors at the end of event
413   //
414   TIter next(fModules);
415   AliModule *detector;
416   while((detector = (AliModule*)next())) {
417     detector->FinishEvent();
418   }
419 }
420
421 //_____________________________________________________________________________
422 void AliRun::CleanParents()
423 {
424   //
425   // Clean Particles stack.
426   // Set parent/daughter relations
427   //
428   TObjArray &particles = *fParticleMap;
429   TParticle *part;
430   int i;
431   for(i=0; i<fHgwmk+1; i++) {
432     part = (TParticle *)particles.At(i);
433     if(part) if(!part->TestBit(kDaughtersBit)) {
434       part->SetFirstDaughter(-1);
435       part->SetLastDaughter(-1);
436     }
437   }
438 }
439
440 //_____________________________________________________________________________
441 Int_t AliRun::DistancetoPrimitive(Int_t, Int_t)
442 {
443   //
444   // Return the distance from the mouse to the AliRun object
445   // Dummy routine
446   //
447   return 9999;
448 }
449
450 //_____________________________________________________________________________
451 void AliRun::DumpPart (Int_t i) const
452 {
453   //
454   // Dumps particle i in the stack
455   //
456   ((TParticle*) (*fParticleMap)[i])->Print();
457 }
458
459 //_____________________________________________________________________________
460 void AliRun::DumpPStack () const
461 {
462   //
463   // Dumps the particle stack
464   //
465   TObjArray &particles = *fParticleMap;
466   printf(
467          "\n\n=======================================================================\n");
468   for (Int_t i=0;i<fNtrack;i++) 
469     {
470       printf("-> %d ",i); ((TParticle*) particles[i])->Print();
471       printf("--------------------------------------------------------------\n");
472     }
473   printf(
474          "\n=======================================================================\n\n");
475 }
476
477 void  AliRun::SetField(AliMagF* magField)
478 {
479     // Set Magnetic Field Map
480     fField = magField;
481     fField->ReadField();
482 }
483
484 //_____________________________________________________________________________
485 void AliRun::SetField(Int_t type, Int_t version, Float_t scale,
486                       Float_t maxField, char* filename)
487 {
488   //
489   //  Set magnetic field parameters
490   //  type      Magnetic field transport flag 0=no field, 2=helix, 3=Runge Kutta
491   //  version   Magnetic field map version (only 1 active now)
492   //  scale     Scale factor for the magnetic field
493   //  maxField  Maximum value for the magnetic field
494
495   //
496   // --- Sanity check on mag field flags
497   if(fField) delete fField;
498   if(version==1) {
499     fField = new AliMagFC("Map1"," ",type,scale,maxField);
500   } else if(version<=2) {
501     fField = new AliMagFCM("Map2-3",filename,type,scale,maxField);
502     fField->ReadField();
503   } else if(version==3) {
504     fField = new AliMagFDM("Map4",filename,type,scale,maxField);
505     fField->ReadField();
506   } else {
507     Warning("SetField","Invalid map %d\n",version);
508   }
509 }
510  
511 //_____________________________________________________________________________
512 void AliRun::PreTrack()
513 {
514      TObjArray &dets = *fModules;
515      AliModule *module;
516
517      for(Int_t i=0; i<=fNdets; i++)
518        if((module = (AliModule*)dets[i]))
519          module->PreTrack();
520
521      fMCQA->PreTrack();
522 }
523
524 //_____________________________________________________________________________
525 void AliRun::PostTrack()
526 {
527      TObjArray &dets = *fModules;
528      AliModule *module;
529
530      for(Int_t i=0; i<=fNdets; i++)
531        if((module = (AliModule*)dets[i]))
532          module->PostTrack();
533 }
534
535 //_____________________________________________________________________________
536 void AliRun::FinishPrimary()
537 {
538   //
539   // Called  at the end of each primary track
540   //
541   
542   //  static Int_t count=0;
543   //  const Int_t times=10;
544   // This primary is finished, purify stack
545   PurifyKine();
546
547   TIter next(fModules);
548   AliModule *detector;
549   while((detector = (AliModule*)next())) {
550     detector->FinishPrimary();
551   }
552
553   // Write out hits if any
554   if (gAlice->TreeH()) {
555     gAlice->TreeH()->Fill();
556   }
557   
558   // Reset Hits info
559   gAlice->ResetHits();
560
561   //
562   //  if(++count%times==1) gObjectTable->Print();
563 }
564
565 //_____________________________________________________________________________
566 void AliRun::FinishEvent()
567 {
568   //
569   // Called at the end of the event.
570   //
571   
572   //
573   if(fLego) fLego->FinishEvent();
574
575   //Update the energy deposit tables
576   Int_t i;
577   for(i=0;i<fEventEnergy.GetSize();i++) {
578     fSummEnergy[i]+=fEventEnergy[i];
579     fSum2Energy[i]+=fEventEnergy[i]*fEventEnergy[i];
580   }
581   fEventEnergy.Reset();
582   
583   // Clean detector information
584   CleanDetectors();
585   
586   // Write out the kinematics
587   if (fTreeK) {
588     CleanParents();
589     //    fTreeK->Fill();
590     Bool_t allFilled = kFALSE;
591     TObject *part;
592     for(i=0; i<fHgwmk+1; ++i) if((part=fParticleMap->At(i))) {
593       fParticleBuffer = (TParticle*) part;
594       fParticleFileMap[i]= (Int_t) fTreeK->GetEntries();
595       fTreeK->Fill();
596       (*fParticleMap)[i]=0;      
597       
598       // When all primaries were filled no particle!=0
599       // should be left => to be removed later.
600       if (allFilled) printf("Why != 0 part # %d?\n",i);
601     }
602     else {
603       // // printf("Why = 0 part # %d?\n",i); => We know.
604       // break;
605            // we don't break now in order to be sure there is no
606            // particle !=0 left.
607            // To be removed later and replaced with break.
608       if(!allFilled) allFilled = kTRUE;
609     }  
610   }
611   
612   // Write out the digits
613   if (fTreeD) {
614     fTreeD->Fill();
615     ResetDigits();
616   }
617
618    if (fTreeS) {
619     fTreeS->Fill();
620     ResetSDigits();
621   }
622  
623   // Write out reconstructed clusters  
624   if (fTreeR) {
625     fTreeR->Fill();
626   }
627
628   // Write out the event Header information
629   if (fTreeE) fTreeE->Fill();
630   
631   // Reset stack info
632   ResetStack();
633   
634   // Write Tree headers
635   if (fTreeK) fTreeK->Write(0,TObject::kOverwrite);
636   if (fTreeH) fTreeH->Write(0,TObject::kOverwrite);
637   if (fTreeD) fTreeD->Write(0,TObject::kOverwrite);
638   if (fTreeR) fTreeR->Write(0,TObject::kOverwrite);
639   if (fTreeS) fTreeS->Write(0,TObject::kOverwrite);
640   
641   ++fEvent;
642 }
643
644 //_____________________________________________________________________________
645 void AliRun::FinishRun()
646 {
647   //
648   // Called at the end of the run.
649   //
650
651   //
652   if(fLego) fLego->FinishRun();
653
654   // Clean detector information
655   TIter next(fModules);
656   AliModule *detector;
657   while((detector = (AliModule*)next())) {
658     detector->FinishRun();
659   }
660   
661   //Output energy summary tables
662   EnergySummary();
663
664   TFile *file = fTreeE->GetCurrentFile();
665
666   file->cd();
667   
668   fTreeE->Write(0,TObject::kOverwrite);
669   
670   // Write AliRun info and all detectors parameters
671   Write();
672   
673   // Clean tree information
674   if (fTreeK) {
675     delete fTreeK; fTreeK = 0;
676   }
677   if (fTreeH) {
678     delete fTreeH; fTreeH = 0;
679   }
680   if (fTreeD) {
681     delete fTreeD; fTreeD = 0;
682   }
683   if (fTreeR) {
684     delete fTreeR; fTreeR = 0;
685   }
686   if (fTreeE) {
687     delete fTreeE; fTreeE = 0;
688   }
689     
690   // Close output file
691   file->Write();
692 }
693
694 //_____________________________________________________________________________
695 void AliRun::FlagTrack(Int_t track)
696 {
697   //
698   // Flags a track and all its family tree to be kept
699   //
700   int curr;
701   TParticle *particle;
702
703   curr=track;
704   while(1) {
705     particle=(TParticle*)fParticleMap->At(curr);
706     
707     // If the particle is flagged the three from here upward is saved already
708     if(particle->TestBit(kKeepBit)) return;
709     
710     // Save this particle
711     particle->SetBit(kKeepBit);
712     
713     // Move to father if any
714     if((curr=particle->GetFirstMother())==-1) return;
715   }
716 }
717  
718 //_____________________________________________________________________________
719 void AliRun::EnergySummary()
720 {
721   //
722   // Print summary of deposited energy
723   //
724
725   Int_t ndep=0;
726   Float_t edtot=0;
727   Float_t ed, ed2;
728   Int_t kn, i, left, j, id;
729   const Float_t kzero=0;
730   Int_t ievent=fHeader.GetEvent()+1;
731   //
732   // Energy loss information
733   if(ievent) {
734     printf("***************** Energy Loss Information per event (GEV) *****************\n");
735     for(kn=1;kn<fEventEnergy.GetSize();kn++) {
736       ed=fSummEnergy[kn];
737       if(ed>0) {
738         fEventEnergy[ndep]=kn;
739         if(ievent>1) {
740           ed=ed/ievent;
741           ed2=fSum2Energy[kn];
742           ed2=ed2/ievent;
743           ed2=100*TMath::Sqrt(TMath::Max(ed2-ed*ed,kzero))/ed;
744         } else 
745           ed2=99;
746         fSummEnergy[ndep]=ed;
747         fSum2Energy[ndep]=TMath::Min((Float_t) 99.,TMath::Max(ed2,kzero));
748         edtot+=ed;
749         ndep++;
750       }
751     }
752     for(kn=0;kn<(ndep-1)/3+1;kn++) {
753       left=ndep-kn*3;
754       for(i=0;i<(3<left?3:left);i++) {
755         j=kn*3+i;
756         id=Int_t (fEventEnergy[j]+0.1);
757         printf(" %s %10.3f +- %10.3f%%;",gMC->VolName(id),fSummEnergy[j],fSum2Energy[j]);
758       }
759       printf("\n");
760     }
761     //
762     // Relative energy loss in different detectors
763     printf("******************** Relative Energy Loss per event ********************\n");
764     printf("Total energy loss per event %10.3f GeV\n",edtot);
765     for(kn=0;kn<(ndep-1)/5+1;kn++) {
766       left=ndep-kn*5;
767       for(i=0;i<(5<left?5:left);i++) {
768         j=kn*5+i;
769         id=Int_t (fEventEnergy[j]+0.1);
770         printf(" %s %10.3f%%;",gMC->VolName(id),100*fSummEnergy[j]/edtot);
771       }
772       printf("\n");
773     }
774     for(kn=0;kn<75;kn++) printf("*"); 
775     printf("\n");
776   }
777   //
778   // Reset the TArray's
779   //  fEventEnergy.Set(0);
780   //  fSummEnergy.Set(0);
781   //  fSum2Energy.Set(0);
782 }
783
784 //_____________________________________________________________________________
785 AliModule *AliRun::GetModule(const char *name) const
786 {
787   //
788   // Return pointer to detector from name
789   //
790   return (AliModule*)fModules->FindObject(name);
791 }
792  
793 //_____________________________________________________________________________
794 AliDetector *AliRun::GetDetector(const char *name) const
795 {
796   //
797   // Return pointer to detector from name
798   //
799   return (AliDetector*)fModules->FindObject(name);
800 }
801  
802 //_____________________________________________________________________________
803 Int_t AliRun::GetModuleID(const char *name) const
804 {
805   //
806   // Return galice internal detector identifier from name
807   //
808   Int_t i=-1;
809   TObject *mod=fModules->FindObject(name);
810   if(mod) i=fModules->IndexOf(mod);
811   return i;
812 }
813  
814 //_____________________________________________________________________________
815 Int_t AliRun::GetEvent(Int_t event)
816 {
817   //
818   // Connect the Trees Kinematics and Hits for event # event
819   // Set branch addresses
820   //
821
822   // Reset existing structures
823   //  ResetStack();
824   ResetHits();
825   ResetDigits();
826   ResetSDigits();
827   
828   // Delete Trees already connected
829   if (fTreeK) delete fTreeK;
830   if (fTreeH) delete fTreeH;
831   if (fTreeD) delete fTreeD;
832   if (fTreeR) delete fTreeR;
833   if (fTreeS) delete fTreeS;
834
835   // Get header from file
836   if(fTreeE) fTreeE->GetEntry(event);
837   else Error("GetEvent","Cannot file Header Tree\n");
838   TFile *file = fTreeE->GetCurrentFile();
839
840   file->cd();
841   
842   // Get Kine Tree from file
843   char treeName[20];
844   sprintf(treeName,"TreeK%d",event);
845   fTreeK = (TTree*)gDirectory->Get(treeName);
846   if (fTreeK) fTreeK->SetBranchAddress("Particles", &fParticleBuffer);
847   else    Error("GetEvent","cannot find Kine Tree for event:%d\n",event);
848   // Create the particle stack
849   if(!fParticles) fParticles = new TClonesArray("TParticle",1000);
850   // Build the pointer list
851   if(fParticleMap) {
852     fParticleMap->Clear();
853     fParticleMap->Expand(fTreeK->GetEntries());
854   } else
855     fParticleMap = new TObjArray(fTreeK->GetEntries());
856   
857   file->cd();
858
859   // Get Hits Tree header from file
860   sprintf(treeName,"TreeH%d",event);
861   fTreeH = (TTree*)gDirectory->Get(treeName);
862   if (!fTreeH) {
863     Error("GetEvent","cannot find Hits Tree for event:%d\n",event);
864   }
865   
866   file->cd();
867
868   // Get Digits Tree header from file
869   sprintf(treeName,"TreeD%d",event);
870   fTreeD = (TTree*)gDirectory->Get(treeName);
871   if (!fTreeD) {
872     // Warning("GetEvent","cannot find Digits Tree for event:%d\n",event);
873   }
874
875   file->cd();
876
877   // Get SDigits Tree header from file
878   sprintf(treeName,"TreeS%d",event);
879   fTreeS = (TTree*)gDirectory->Get(treeName);
880   if (!fTreeS) {
881     // Warning("GetEvent","cannot find SDigits Tree for event:%d\n",event);
882   }
883
884   file->cd();
885   
886   // Get Reconstruct Tree header from file
887   sprintf(treeName,"TreeR%d",event);
888   fTreeR = (TTree*)gDirectory->Get(treeName);
889   if (!fTreeR) {
890     //    printf("WARNING: cannot find Reconstructed Tree for event:%d\n",event);
891   }
892
893   file->cd();
894  
895   // Set Trees branch addresses
896   TIter next(fModules);
897   AliModule *detector;
898   while((detector = (AliModule*)next())) {
899     detector->SetTreeAddress();
900   }
901   
902   fNtrack = Int_t (fTreeK->GetEntries());
903   return fNtrack;
904 }
905
906 //_____________________________________________________________________________
907 TGeometry *AliRun::GetGeometry()
908 {
909   //
910   // Import Alice geometry from current file
911   // Return pointer to geometry object
912   //
913   if (!fGeometry) fGeometry = (TGeometry*)gDirectory->Get("AliceGeom");
914   //
915   // Unlink and relink nodes in detectors
916   // This is bad and there must be a better way...
917   //
918   
919   TIter next(fModules);
920   AliModule *detector;
921   while((detector = (AliModule*)next())) {
922     TList *dnodes=detector->Nodes();
923     Int_t j;
924     TNode *node, *node1;
925     for ( j=0; j<dnodes->GetSize(); j++) {
926       node = (TNode*) dnodes->At(j);
927       node1 = fGeometry->GetNode(node->GetName());
928       dnodes->Remove(node);
929       dnodes->AddAt(node1,j);
930     }
931   }
932   return fGeometry;
933 }
934
935 //_____________________________________________________________________________
936 void AliRun::GetNextTrack(Int_t &mtrack, Int_t &ipart, Float_t *pmom,
937                           Float_t &e, Float_t *vpos, Float_t *polar,
938                           Float_t &tof)
939 {
940   //
941   // Return next track from stack of particles
942   //
943   TVector3 pol;
944   fCurrent=-1;
945   TParticle *track;
946   for(Int_t i=fNtrack-1; i>=0; i--) {
947     track=(TParticle*) fParticleMap->At(i);
948     if(track) if(!track->TestBit(kDoneBit)) {
949       //
950       // The track exists and has not yet been processed
951       fCurrent=i;
952       ipart=track->GetPdgCode();
953       pmom[0]=track->Px();
954       pmom[1]=track->Py(); 
955       pmom[2]=track->Pz();
956       e     =track->Energy();
957       vpos[0]=track->Vx();
958       vpos[1]=track->Vy();
959       vpos[2]=track->Vz();
960       track->GetPolarisation(pol);
961       polar[0]=pol.X();
962       polar[1]=pol.Y();
963       polar[2]=pol.Z();
964       tof=track->T();
965       track->SetBit(kDoneBit);
966       break;
967     }
968   }
969   mtrack=fCurrent;
970   //
971   // stop and start timer when we start a primary track
972   Int_t nprimaries = fHeader.GetNprimary();
973   if (fCurrent >= nprimaries) return;
974   if (fCurrent < nprimaries-1) {
975     fTimer.Stop();
976     track=(TParticle*) fParticleMap->At(fCurrent+1);
977     //    track->SetProcessTime(fTimer.CpuTime());
978   }
979   fTimer.Start();
980 }
981
982 //_____________________________________________________________________________
983 Int_t AliRun::GetPrimary(Int_t track) const
984 {
985   //
986   // return number of primary that has generated track
987   //
988   int current, parent;
989   TParticle *part;
990   //
991   parent=track;
992   while (1) {
993     current=parent;
994     part = (TParticle *)fParticleMap->At(current);
995     parent=part->GetFirstMother();
996     if(parent<0) return current;
997   }
998 }
999  
1000 //_____________________________________________________________________________
1001 void AliRun::InitMC(const char *setup)
1002 {
1003   //
1004   // Initialize the Alice setup
1005   //
1006
1007   if(fInitDone) {
1008     Warning("Init","Cannot initialise AliRun twice!\n");
1009     return;
1010   }
1011     
1012   OpenBaseFile("recreate");
1013   
1014   gROOT->LoadMacro(setup);
1015   gInterpreter->ProcessLine(fConfigFunction.Data());
1016
1017
1018   gMC->DefineParticles();  //Create standard MC particles
1019
1020   TObject *objfirst, *objlast;
1021
1022   fNdets = fModules->GetLast()+1;
1023
1024   //
1025   //=================Create Materials and geometry
1026   gMC->Init();
1027
1028   // Added also after in case of interactive initialisation of modules
1029   fNdets = fModules->GetLast()+1;
1030
1031    TIter next(fModules);
1032    AliModule *detector;
1033    while((detector = (AliModule*)next())) {
1034       detector->SetTreeAddress();
1035       objlast = gDirectory->GetList()->Last();
1036       
1037       // Add Detector histograms in Detector list of histograms
1038       if (objlast) objfirst = gDirectory->GetList()->After(objlast);
1039       else         objfirst = gDirectory->GetList()->First();
1040       while (objfirst) {
1041         detector->Histograms()->Add(objfirst);
1042         objfirst = gDirectory->GetList()->After(objfirst);
1043       }
1044    }
1045    ReadTransPar(); //Read the cuts for all materials
1046    
1047    MediaTable(); //Build the special IMEDIA table
1048    
1049    //Initialise geometry deposition table
1050    fEventEnergy.Set(gMC->NofVolumes()+1);
1051    fSummEnergy.Set(gMC->NofVolumes()+1);
1052    fSum2Energy.Set(gMC->NofVolumes()+1);
1053    
1054    //Compute cross-sections
1055    gMC->BuildPhysics();
1056    
1057    //Write Geometry object to current file.
1058    fGeometry->Write();
1059    
1060    fInitDone = kTRUE;
1061
1062    fMCQA = new AliMCQA(fNdets);
1063
1064    //
1065    // Save stuff at the beginning of the file to avoid file corruption
1066    Write();
1067 }
1068
1069 //_____________________________________________________________________________
1070 void AliRun::MediaTable()
1071 {
1072   //
1073   // Built media table to get from the media number to
1074   // the detector id
1075   //
1076   Int_t kz, nz, idt, lz, i, k, ind;
1077   //  Int_t ibeg;
1078   TObjArray &dets = *gAlice->Detectors();
1079   AliModule *det;
1080   //
1081   // For all detectors
1082   for (kz=0;kz<fNdets;kz++) {
1083     // If detector is defined
1084     if((det=(AliModule*) dets[kz])) {
1085         TArrayI &idtmed = *(det->GetIdtmed()); 
1086         for(nz=0;nz<100;nz++) {
1087         // Find max and min material number
1088         if((idt=idtmed[nz])) {
1089           det->LoMedium() = det->LoMedium() < idt ? det->LoMedium() : idt;
1090           det->HiMedium() = det->HiMedium() > idt ? det->HiMedium() : idt;
1091         }
1092       }
1093       if(det->LoMedium() > det->HiMedium()) {
1094         det->LoMedium() = 0;
1095         det->HiMedium() = 0;
1096       } else {
1097         if(det->HiMedium() > fImedia->GetSize()) {
1098           Error("MediaTable","Increase fImedia from %d to %d",
1099                 fImedia->GetSize(),det->HiMedium());
1100           return;
1101         }
1102         // Tag all materials in rage as belonging to detector kz
1103         for(lz=det->LoMedium(); lz<= det->HiMedium(); lz++) {
1104           (*fImedia)[lz]=kz;
1105         }
1106       }
1107     }
1108   }
1109   //
1110   // Print summary table
1111   printf(" Traking media ranges:\n");
1112   for(i=0;i<(fNdets-1)/6+1;i++) {
1113     for(k=0;k< (6<fNdets-i*6?6:fNdets-i*6);k++) {
1114       ind=i*6+k;
1115       det=(AliModule*)dets[ind];
1116       if(det)
1117         printf(" %6s: %3d -> %3d;",det->GetName(),det->LoMedium(),
1118                det->HiMedium());
1119       else
1120         printf(" %6s: %3d -> %3d;","NULL",0,0);
1121     }
1122     printf("\n");
1123   }
1124 }
1125
1126 //____________________________________________________________________________
1127 void AliRun::SetGenerator(AliGenerator *generator)
1128 {
1129   //
1130   // Load the event generator
1131   //
1132   if(!fGenerator) fGenerator = generator;
1133 }
1134
1135 //____________________________________________________________________________
1136 void AliRun::ResetGenerator(AliGenerator *generator)
1137 {
1138   //
1139   // Load the event generator
1140   //
1141   if(fGenerator)
1142     if(generator)
1143       Warning("ResetGenerator","Replacing generator %s with %s\n",
1144               fGenerator->GetName(),generator->GetName());
1145     else
1146       Warning("ResetGenerator","Replacing generator %s with NULL\n",
1147               fGenerator->GetName());
1148   fGenerator = generator;
1149 }
1150
1151 //____________________________________________________________________________
1152 void AliRun::SetTransPar(char *filename)
1153 {
1154   fTransParName = filename;
1155 }
1156
1157 //____________________________________________________________________________
1158 void AliRun::SetBaseFile(char *filename)
1159 {
1160   fBaseFileName = *filename;
1161 }
1162
1163 //____________________________________________________________________________
1164 void AliRun::OpenBaseFile(const char *option)
1165 {
1166   if(!strlen(fBaseFileName.Data())) {
1167     const char *filename;
1168     if ((filename=gSystem->Getenv("CONFIG_FILE"))) {
1169       fBaseFileName=filename;
1170     } else {
1171       fBaseFileName="galice.root";
1172     }  
1173   }
1174   TFile *rootfile = new TFile(fBaseFileName.Data(),option); 
1175   rootfile->SetCompressionLevel(2);
1176 }
1177
1178 //____________________________________________________________________________
1179 void AliRun::ReadTransPar()
1180 {
1181   //
1182   // Read filename to set the transport parameters
1183   //
1184
1185
1186   const Int_t kncuts=10;
1187   const Int_t knflags=11;
1188   const Int_t knpars=kncuts+knflags;
1189   const char kpars[knpars][7] = {"CUTGAM" ,"CUTELE","CUTNEU","CUTHAD","CUTMUO",
1190                                "BCUTE","BCUTM","DCUTE","DCUTM","PPCUTM","ANNI",
1191                                "BREM","COMP","DCAY","DRAY","HADR","LOSS",
1192                                "MULS","PAIR","PHOT","RAYL"};
1193   char line[256];
1194   char detName[7];
1195   char* filtmp;
1196   Float_t cut[kncuts];
1197   Int_t flag[knflags];
1198   Int_t i, itmed, iret, ktmed, kz;
1199   FILE *lun;
1200   //
1201   // See whether the file is there
1202   filtmp=gSystem->ExpandPathName(fTransParName.Data());
1203   lun=fopen(filtmp,"r");
1204   delete [] filtmp;
1205   if(!lun) {
1206     Warning("ReadTransPar","File %s does not exist!\n",fTransParName.Data());
1207     return;
1208   }
1209   //
1210   printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
1211   printf(" *%59s\n","*");
1212   printf(" *       Please check carefully what you are doing!%10s\n","*");
1213   printf(" *%59s\n","*");
1214   //
1215   while(1) {
1216     // Initialise cuts and flags
1217     for(i=0;i<kncuts;i++) cut[i]=-99;
1218     for(i=0;i<knflags;i++) flag[i]=-99;
1219     itmed=0;
1220     for(i=0;i<256;i++) line[i]='\0';
1221     // Read up to the end of line excluded
1222     iret=fscanf(lun,"%[^\n]",line);
1223     if(iret<0) {
1224       //End of file
1225       fclose(lun);
1226       printf(" *%59s\n","*");
1227       printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
1228       return;
1229     }
1230     // Read the end of line
1231     fscanf(lun,"%*c");
1232     if(!iret) continue;
1233     if(line[0]=='*') continue;
1234     // Read the numbers
1235     iret=sscanf(line,"%s %d %f %f %f %f %f %f %f %f %f %f %d %d %d %d %d %d %d %d %d %d %d",
1236                 detName,&itmed,&cut[0],&cut[1],&cut[2],&cut[3],&cut[4],&cut[5],&cut[6],&cut[7],&cut[8],
1237                 &cut[9],&flag[0],&flag[1],&flag[2],&flag[3],&flag[4],&flag[5],&flag[6],&flag[7],
1238                 &flag[8],&flag[9],&flag[10]);
1239     if(!iret) continue;
1240     if(iret<0) {
1241       //reading error
1242       Warning("ReadTransPar","Error reading file %s\n",fTransParName.Data());
1243       continue;
1244     }
1245     // Check that the module exist
1246     AliModule *mod = GetModule(detName);
1247     if(mod) {
1248       // Get the array of media numbers
1249       TArrayI &idtmed = *mod->GetIdtmed();
1250       // Check that the tracking medium code is valid
1251       if(0<=itmed && itmed < 100) {
1252         ktmed=idtmed[itmed];
1253         if(!ktmed) {
1254           Warning("ReadTransPar","Invalid tracking medium code %d for %s\n",itmed,mod->GetName());
1255           continue;
1256         }
1257         // Set energy thresholds
1258         for(kz=0;kz<kncuts;kz++) {
1259           if(cut[kz]>=0) {
1260             printf(" *  %-6s set to %10.3E for tracking medium code %4d for %s\n",
1261                    kpars[kz],cut[kz],itmed,mod->GetName());
1262             gMC->Gstpar(ktmed,kpars[kz],cut[kz]);
1263           }
1264         }
1265         // Set transport mechanisms
1266         for(kz=0;kz<knflags;kz++) {
1267           if(flag[kz]>=0) {
1268             printf(" *  %-6s set to %10d for tracking medium code %4d for %s\n",
1269                    kpars[kncuts+kz],flag[kz],itmed,mod->GetName());
1270             gMC->Gstpar(ktmed,kpars[kncuts+kz],Float_t(flag[kz]));
1271           }
1272         }
1273       } else {
1274         Warning("ReadTransPar","Invalid medium code %d *\n",itmed);
1275         continue;
1276       }
1277     } else {
1278       Warning("ReadTransPar","Module %s not present\n",detName);
1279       continue;
1280     }
1281   }
1282 }
1283
1284 //_____________________________________________________________________________
1285 void AliRun::MakeBranchInTree(TTree *tree, const char* name, void* address, Int_t size, char *file)
1286
1287     if (GetDebug()>1)
1288         printf("* MakeBranch * Making Branch %s \n",name);
1289
1290     TBranch *branch = tree->Branch(name,address,size);
1291
1292     if (file) {
1293         TDirectory *cwd = gDirectory;
1294         branch->SetFile(file);
1295         TIter next( branch->GetListOfBranches());
1296         while ((branch=(TBranch*)next())) {
1297            branch->SetFile(file);
1298         }   
1299         if (GetDebug()>1)
1300             printf("* MakeBranch * Diverting Branch %s to file %s\n",name,file);
1301         cwd->cd();
1302     } 
1303 }
1304
1305 //_____________________________________________________________________________
1306 void AliRun::MakeBranchInTree(TTree *tree, const char* name, const char *classname, void* address, Int_t size, Int_t splitlevel, char *file)
1307
1308     TDirectory *cwd = gDirectory;
1309     TBranch *branch = tree->Branch(name,classname,address,size,splitlevel);
1310     if (GetDebug()>1)
1311       printf("* MakeBranch * Making Branch %s \n",name);
1312     if (file) {
1313         branch->SetFile(file);
1314         TIter next( branch->GetListOfBranches());
1315         while ((branch=(TBranch*)next())) {
1316            branch->SetFile(file);
1317         } 
1318        if (GetDebug()>1)
1319            printf("* MakeBranch * Diverting Branch %s to file %s\n",name,file);
1320         cwd->cd();
1321     }
1322 }
1323 //_____________________________________________________________________________
1324 void AliRun::MakeTree(Option_t *option, char *file)
1325 {
1326   //
1327   //  Create the ROOT trees
1328   //  Loop on all detectors to create the Root branch (if any)
1329   //
1330
1331   char hname[30];
1332   //
1333   // Analyse options
1334   char *oK = strstr(option,"K");
1335   char *oH = strstr(option,"H");
1336   char *oE = strstr(option,"E");
1337   char *oD = strstr(option,"D");
1338   char *oR = strstr(option,"R");
1339   char *oS = strstr(option,"S");
1340   //
1341   
1342   if (oK && !fTreeK) {
1343     sprintf(hname,"TreeK%d",fEvent);
1344     fTreeK = new TTree(hname,"Kinematics");
1345     //  Create a branch for particles
1346     MakeBranchInTree(fTreeK, 
1347                      "Particles", "TParticle", &fParticleBuffer, 4000, 1, file) ;
1348     fTreeK->Write();
1349   }
1350   if (oH && !fTreeH) {
1351     sprintf(hname,"TreeH%d",fEvent);
1352     fTreeH = new TTree(hname,"Hits");
1353     fTreeH->SetAutoSave(1000000000); //no autosave
1354     fTreeH->Write();
1355   }
1356   if (oD && !fTreeD) {
1357     sprintf(hname,"TreeD%d",fEvent);
1358     fTreeD = new TTree(hname,"Digits");
1359     fTreeD->Write();
1360   }
1361   if (oS && !fTreeS) {
1362     sprintf(hname,"TreeS%d",fEvent);
1363     fTreeS = new TTree(hname,"SDigits");
1364     fTreeS->Write();
1365   }
1366   if (oR && !fTreeR) {
1367     sprintf(hname,"TreeR%d",fEvent);
1368     fTreeR = new TTree(hname,"Reconstruction");
1369     fTreeR->Write();
1370   }
1371   if (oE && !fTreeE) {
1372     fTreeE = new TTree("TE","Header");
1373     //  Create a branch for Header
1374     MakeBranchInTree(fTreeE, 
1375                      "Header", "AliHeader", &gAliHeader, 4000, 1, file) ;
1376     fTreeE->Write();
1377   }
1378   
1379   //
1380   // Create a branch for hits/digits for each detector
1381   // Each branch is a TClonesArray. Each data member of the Hits classes
1382   // will be in turn a subbranch of the detector master branch
1383   TIter next(fModules);
1384   AliModule *detector;
1385   while((detector = (AliModule*)next())) {
1386      if (oH || oR) detector->MakeBranch(option,file);
1387   }
1388 }
1389
1390 //_____________________________________________________________________________
1391 Int_t AliRun::PurifyKine(Int_t lastSavedTrack, Int_t nofTracks)
1392 {
1393   //
1394   // PurifyKine with external parameters
1395   //
1396   fHgwmk = lastSavedTrack;
1397   fNtrack = nofTracks;
1398   PurifyKine();
1399   return fHgwmk;
1400 }
1401
1402 //_____________________________________________________________________________
1403 TParticle* AliRun::Particle(Int_t i)
1404 {
1405   if(!(*fParticleMap)[i]) {
1406     Int_t nentries = fParticles->GetEntries();
1407     fTreeK->GetEntry(fParticleFileMap[i]);
1408     new ((*fParticles)[nentries]) TParticle(*fParticleBuffer);
1409     fParticleMap->AddAt((*fParticles)[nentries],i);
1410   }
1411   return (TParticle *) (*fParticleMap)[i];
1412 }
1413
1414 //_____________________________________________________________________________
1415 void AliRun::PurifyKine()
1416 {
1417   //
1418   // Compress kinematic tree keeping only flagged particles
1419   // and renaming the particle id's in all the hits
1420   //
1421   //  TClonesArray &particles = *fParticles;
1422   TObjArray &particles = *fParticleMap;
1423   int nkeep=fHgwmk+1, parent, i;
1424   TParticle *part, *father;
1425   TArrayI map(particles.GetLast()+1);
1426
1427   // Save in Header total number of tracks before compression
1428   fHeader.SetNtrack(fHeader.GetNtrack()+fNtrack-fHgwmk);
1429
1430   // If no tracks generated return now
1431   if(fHgwmk+1 == fNtrack) return;
1432
1433   Int_t toshrink = fNtrack-fHgwmk-1;
1434
1435   // First pass, invalid Daughter information
1436   for(i=0; i<fNtrack; i++) {
1437     // Preset map, to be removed later
1438     if(i<=fHgwmk) map[i]=i ; 
1439     else {
1440       map[i] = -99;
1441       //      particles.UncheckedAt(i)->ResetBit(kDaughtersBit);
1442       if((part=(TParticle*) particles.At(i))) part->ResetBit(kDaughtersBit);
1443     }
1444   }
1445   // Invalid daughter information for the parent of the first particle
1446   // generated. This may or may not be the current primary according to
1447   // whether decays have been recorded among the primaries
1448   part = (TParticle *)particles.At(fHgwmk+1);
1449   particles.At(part->GetFirstMother())->ResetBit(kDaughtersBit);
1450   // Second pass, build map between old and new numbering
1451   for(i=fHgwmk+1; i<fNtrack; i++) {
1452     if(particles.At(i)->TestBit(kKeepBit)) {
1453       
1454       // This particle has to be kept
1455       map[i]=nkeep;
1456       // If old and new are different, have to move the pointer
1457       if(i!=nkeep) particles[nkeep]=particles.At(i);
1458       part = (TParticle*) particles.At(nkeep);
1459       
1460       // as the parent is always *before*, it must be already
1461       // in place. This is what we are checking anyway!
1462       if((parent=part->GetFirstMother())>fHgwmk) 
1463         if(map[parent]==-99) Fatal("PurifyKine","map[%d] = -99!\n",parent);
1464         else part->SetFirstMother(map[parent]);
1465
1466       nkeep++;
1467     }
1468   }
1469   
1470   // Fix daughters information
1471   for (i=fHgwmk+1; i<nkeep; i++) {
1472     part = (TParticle *)particles.At(i);
1473     parent = part->GetFirstMother();
1474     if(parent>=0) {
1475       father = (TParticle *)particles.At(parent);
1476       if(father->TestBit(kDaughtersBit)) {
1477       
1478         if(i<father->GetFirstDaughter()) father->SetFirstDaughter(i);
1479         if(i>father->GetLastDaughter())  father->SetLastDaughter(i);
1480       } else {
1481         // Initialise daughters info for first pass
1482         father->SetFirstDaughter(i);
1483         father->SetLastDaughter(i);
1484         father->SetBit(kDaughtersBit);
1485       }
1486     }
1487   }
1488   
1489   // Now loop on all registered hit lists
1490   TIter next(fHitLists);
1491   TCollection *hitList;
1492   while((hitList = (TCollection*)next())) {
1493     TIter nexthit(hitList);
1494     AliHit *hit;
1495     while((hit = (AliHit*)nexthit())) {
1496       hit->SetTrack(map[hit->GetTrack()]);
1497     }
1498   }
1499
1500   // 
1501   // This for detectors which have a special mapping mechanism
1502   // for hits, such as TPC and TRD
1503   //
1504
1505    TIter nextmod(fModules);
1506    AliModule *detector;
1507    while((detector = (AliModule*)nextmod())) {
1508      detector->RemapTrackHitIDs(map.GetArray());
1509    }
1510   
1511    // Now the output bit, from fHgwmk to nkeep we write everything and we erase
1512    if(nkeep>fParticleFileMap.GetSize()) fParticleFileMap.Set(Int_t (nkeep*1.5));
1513
1514
1515    for (i=fHgwmk+1; i<nkeep; ++i) {
1516      fParticleBuffer = (TParticle*) particles.At(i);
1517      fParticleFileMap[i]=(Int_t) fTreeK->GetEntries();
1518      fTreeK->Fill();
1519      particles[i]=0;
1520    }
1521
1522    for (i=nkeep; i<fNtrack; ++i) particles[i]=0;
1523
1524    fLoadPoint-=toshrink;
1525    for(i=fLoadPoint; i<fLoadPoint+toshrink; ++i) fParticles->RemoveAt(i);
1526
1527    fNtrack=nkeep;
1528    fHgwmk=nkeep-1;
1529    //   delete [] map;
1530 }
1531
1532 //_____________________________________________________________________________
1533 void AliRun::BeginEvent()
1534 {
1535   //
1536   //  Reset all Detectors & kinematics & trees
1537   //
1538   char hname[30];
1539   //
1540
1541   //
1542   if(fLego) {
1543     fLego->BeginEvent();
1544     return;
1545   }
1546
1547   //
1548   ResetStack();
1549   ResetHits();
1550   ResetDigits();
1551   ResetSDigits();
1552
1553   // Initialise event header
1554   fHeader.Reset(fRun,fEvent);
1555
1556   if(fTreeK) {
1557     fTreeK->Reset();
1558     sprintf(hname,"TreeK%d",fEvent);
1559     fTreeK->SetName(hname);
1560   }
1561   if(fTreeH) {
1562     fTreeH->Reset();
1563     sprintf(hname,"TreeH%d",fEvent);
1564     fTreeH->SetName(hname);
1565   }
1566   if(fTreeD) {
1567     fTreeD->Reset();
1568     sprintf(hname,"TreeD%d",fEvent);
1569     fTreeD->SetName(hname);
1570   }
1571   if(fTreeS) {
1572     fTreeS->Reset();
1573     sprintf(hname,"TreeS%d",fEvent);
1574     fTreeS->SetName(hname);
1575   }
1576   if(fTreeR) {
1577     fTreeR->Reset();
1578     sprintf(hname,"TreeR%d",fEvent);
1579     fTreeR->SetName(hname);
1580   }
1581 }
1582 //_____________________________________________________________________________
1583 void AliRun::ResetDigits()
1584 {
1585   //
1586   //  Reset all Detectors digits
1587   //
1588   TIter next(fModules);
1589   AliModule *detector;
1590   while((detector = (AliModule*)next())) {
1591      detector->ResetDigits();
1592   }
1593 }
1594
1595 //_____________________________________________________________________________
1596 void AliRun::ResetSDigits()
1597 {
1598   //
1599   //  Reset all Detectors digits
1600   //
1601   TIter next(fModules);
1602   AliModule *detector;
1603   while((detector = (AliModule*)next())) {
1604      detector->ResetSDigits();
1605   }
1606 }
1607
1608 //_____________________________________________________________________________
1609 void AliRun::ResetHits()
1610 {
1611   //
1612   //  Reset all Detectors hits
1613   //
1614   TIter next(fModules);
1615   AliModule *detector;
1616   while((detector = (AliModule*)next())) {
1617      detector->ResetHits();
1618   }
1619 }
1620
1621 //_____________________________________________________________________________
1622 void AliRun::ResetPoints()
1623 {
1624   //
1625   // Reset all Detectors points
1626   //
1627   TIter next(fModules);
1628   AliModule *detector;
1629   while((detector = (AliModule*)next())) {
1630      detector->ResetPoints();
1631   }
1632 }
1633
1634 //_____________________________________________________________________________
1635 void AliRun::RunMC(Int_t nevent, const char *setup)
1636 {
1637   //
1638   // Main function to be called to process a galice run
1639   // example
1640   //    Root > gAlice.Run(); 
1641   // a positive number of events will cause the finish routine
1642   // to be called
1643   //
1644
1645   // check if initialisation has been done
1646   if (!fInitDone) InitMC(setup);
1647   
1648   // Create the Root Tree with one branch per detector
1649
1650   if (gSystem->Getenv("CONFIG_SPLIT_FILE")) {
1651     MakeTree("E");
1652     MakeTree("K","Kine.root");
1653     MakeTree("H","Hits.root");
1654     MakeTree("R","Reco.root");
1655   } else {
1656     MakeTree("EKHR");
1657   }
1658
1659   gMC->ProcessRun(nevent);
1660
1661   // End of this run, close files
1662   if(nevent>0) FinishRun();
1663 }
1664
1665 //_____________________________________________________________________________
1666
1667 void AliRun::Hits2Digits(const char *selected)
1668 {
1669    Hits2SDigits(selected);
1670    SDigits2Digits(selected);
1671 }
1672
1673 //_____________________________________________________________________________
1674
1675 void AliRun::Hits2SDigits(const char *selected)
1676 {
1677   //
1678   // Main function to be called to convert hits to digits. 
1679
1680    gAlice->GetEvent(0);
1681
1682    TObjArray *detectors = gAlice->Detectors();
1683
1684    TIter next(detectors);
1685
1686    AliDetector *detector;
1687
1688    TDirectory *cwd = gDirectory;
1689
1690    MakeTree("S");
1691    
1692    while((detector = (AliDetector*)next())) {
1693      if (selected) {
1694        if (strcmp(detector->GetName(),selected)) continue;
1695      }
1696      if (detector->IsActive()){ 
1697        if (gSystem->Getenv("CONFIG_SPLIT_FILE")) {
1698          if (GetDebug()>0)
1699              cout << "Processing " << detector->GetName() << "..." << endl;
1700          char * outFile = new char[strlen (detector->GetName())+18];
1701          sprintf(outFile,"SDigits.%s.root",detector->GetName());
1702          detector->MakeBranch("S",outFile);
1703          delete outFile;
1704        } else {
1705          detector->MakeBranch("S");
1706        }   
1707        cwd->cd();  
1708        detector->Hits2SDigits(); 
1709      }  
1710    }
1711 }
1712
1713 //_____________________________________________________________________________
1714
1715 void AliRun::SDigits2Digits(const char *selected)
1716 {
1717   //
1718   // Main function to be called to convert hits to digits. 
1719
1720    gAlice->GetEvent(0);
1721
1722    TObjArray *detectors = gAlice->Detectors();
1723
1724    TIter next(detectors);
1725
1726    AliDetector *detector;
1727
1728    TDirectory *cwd = gDirectory;
1729
1730    MakeTree("D");
1731    
1732    while((detector = (AliDetector*)next())) {
1733      if (selected) {
1734        if (strcmp(detector->GetName(),selected)) continue;
1735      }
1736      if (detector->IsActive()){ 
1737        if (gSystem->Getenv("CONFIG_SPLIT_FILE")) {
1738          if (GetDebug()>0)
1739              cout << "Processing " << detector->GetName() << "..." << endl;
1740          char * outFile = new char[strlen (detector->GetName())+16];
1741          sprintf(outFile,"Digits.%s.root",detector->GetName());
1742          detector->MakeBranch("D",outFile);
1743          delete outFile;
1744        } else {
1745          detector->MakeBranch("D");
1746        }   
1747        cwd->cd();  
1748        detector->SDigits2Digits(); 
1749      }  
1750    }
1751 }
1752
1753 //_____________________________________________________________________________
1754 void AliRun::RunLego(const char *setup, Int_t nc1, Float_t c1min,
1755                      Float_t c1max,Int_t nc2,Float_t c2min,Float_t c2max,
1756                      Float_t rmin,Float_t rmax,Float_t zmax, AliLegoGenerator* gener)
1757 {
1758   //
1759   // Generates lego plots of:
1760   //    - radiation length map phi vs theta
1761   //    - radiation length map phi vs eta
1762   //    - interaction length map
1763   //    - g/cm2 length map
1764   //
1765   //  ntheta    bins in theta, eta
1766   //  themin    minimum angle in theta (degrees)
1767   //  themax    maximum angle in theta (degrees)
1768   //  nphi      bins in phi
1769   //  phimin    minimum angle in phi (degrees)
1770   //  phimax    maximum angle in phi (degrees)
1771   //  rmin      minimum radius
1772   //  rmax      maximum radius
1773   //  
1774   //
1775   //  The number of events generated = ntheta*nphi
1776   //  run input parameters in macro setup (default="Config.C")
1777   //
1778   //  Use macro "lego.C" to visualize the 3 lego plots in spherical coordinates
1779   //Begin_Html
1780   /*
1781     <img src="picts/AliRunLego1.gif">
1782   */
1783   //End_Html
1784   //Begin_Html
1785   /*
1786     <img src="picts/AliRunLego2.gif">
1787   */
1788   //End_Html
1789   //Begin_Html
1790   /*
1791     <img src="picts/AliRunLego3.gif">
1792   */
1793   //End_Html
1794   //
1795
1796   // check if initialisation has been done
1797   if (!fInitDone) InitMC(setup);
1798   //Save current generator
1799   AliGenerator *gen=Generator();
1800
1801   // Set new generator
1802   if (!gener) gener  = new AliLegoGenerator();
1803   ResetGenerator(gener);
1804   //
1805   // Configure Generator
1806   gener->SetRadiusRange(rmin, rmax);
1807   gener->SetZMax(zmax);
1808   gener->SetCoor1Range(nc1, c1min, c1max);
1809   gener->SetCoor2Range(nc2, c2min, c2max);
1810   
1811   
1812   //Create Lego object  
1813   fLego = new AliLego("lego",gener);
1814
1815   //Prepare MC for Lego Run
1816   gMC->InitLego();
1817   
1818   //Run Lego Object
1819
1820   gMC->ProcessRun(nc1*nc2+1);
1821   
1822   // Create only the Root event Tree
1823   MakeTree("E");
1824   
1825   // End of this run, close files
1826   FinishRun();
1827   // Restore current generator
1828   ResetGenerator(gen);
1829   // Delete Lego Object
1830   delete fLego; fLego=0;
1831 }
1832
1833 //_____________________________________________________________________________
1834 void AliRun::SetConfigFunction(const char * config) 
1835 {
1836   //
1837   // Set the signature of the function contained in Config.C to configure
1838   // the run
1839   //
1840   fConfigFunction=config;
1841 }
1842
1843 //_____________________________________________________________________________
1844 void AliRun::SetCurrentTrack(Int_t track)
1845
1846   //
1847   // Set current track number
1848   //
1849   fCurrent = track; 
1850 }
1851  
1852 //_____________________________________________________________________________
1853 void AliRun::SetTrack(Int_t done, Int_t parent, Int_t pdg, Float_t *pmom,
1854                       Float_t *vpos, Float_t *polar, Float_t tof,
1855                       AliMCProcess mech, Int_t &ntr, Float_t weight)
1856
1857   //
1858   // Load a track on the stack
1859   //
1860   // done     0 if the track has to be transported
1861   //          1 if not
1862   // parent   identifier of the parent track. -1 for a primary
1863   // pdg    particle code
1864   // pmom     momentum GeV/c
1865   // vpos     position 
1866   // polar    polarisation 
1867   // tof      time of flight in seconds
1868   // mecha    production mechanism
1869   // ntr      on output the number of the track stored
1870   //
1871   TClonesArray &particles = *fParticles;
1872   TParticle *particle;
1873   Float_t mass;
1874   const Int_t kfirstdaughter=-1;
1875   const Int_t klastdaughter=-1;
1876   const Int_t kS=0;
1877   //  const Float_t tlife=0;
1878   
1879   //
1880   // Here we get the static mass
1881   // For MC is ok, but a more sophisticated method could be necessary
1882   // if the calculated mass is required
1883   // also, this method is potentially dangerous if the mass
1884   // used in the MC is not the same of the PDG database
1885   //
1886   mass = TDatabasePDG::Instance()->GetParticle(pdg)->Mass();
1887   Float_t e=TMath::Sqrt(mass*mass+pmom[0]*pmom[0]+
1888                         pmom[1]*pmom[1]+pmom[2]*pmom[2]);
1889   
1890   //printf("Loading particle %s mass %f ene %f No %d ip %d pos %f %f %f mom %f %f %f kS %d m %s\n",
1891   //pname,mass,e,fNtrack,pdg,vpos[0],vpos[1],vpos[2],pmom[0],pmom[1],pmom[2],kS,mecha);
1892
1893   particle=new(particles[fLoadPoint++]) TParticle(pdg,kS,parent,-1,kfirstdaughter,
1894                                              klastdaughter,pmom[0],pmom[1],pmom[2],
1895                                              e,vpos[0],vpos[1],vpos[2],tof);
1896   particle->SetPolarisation(TVector3(polar[0],polar[1],polar[2]));
1897   particle->SetWeight(weight);
1898   particle->SetUniqueID(mech);
1899   if(!done) particle->SetBit(kDoneBit);
1900   //  Declare that the daughter information is valid
1901   particle->SetBit(kDaughtersBit);
1902   //  Add the particle to the stack
1903   fParticleMap->AddAtAndExpand(particle,fNtrack);
1904
1905   if(parent>=0) {
1906     particle=(TParticle*) fParticleMap->At(parent);
1907     particle->SetLastDaughter(fNtrack);
1908     if(particle->GetFirstDaughter()<0) particle->SetFirstDaughter(fNtrack);
1909   } else { 
1910     //
1911     // This is a primary track. Set high water mark for this event
1912     fHgwmk=fNtrack;
1913     //
1914     // Set also number if primary tracks
1915     fHeader.SetNprimary(fHgwmk+1);
1916     fHeader.SetNtrack(fHgwmk+1);
1917   }
1918   ntr = fNtrack++;
1919   
1920 /*
1921   //
1922   // Here we get the static mass
1923   // For MC is ok, but a more sophisticated method could be necessary
1924   // if the calculated mass is required
1925   // also, this method is potentially dangerous if the mass
1926   // used in the MC is not the same of the PDG database
1927   //
1928   Float_t mass = TDatabasePDG::Instance()->GetParticle(pdg)->Mass();
1929   Float_t e=TMath::Sqrt(mass*mass+pmom[0]*pmom[0]+
1930                         pmom[1]*pmom[1]+pmom[2]*pmom[2]);
1931                         
1932   SetTrack(done, parent, pdg, pmom[0], pmom[1], pmom[2], e,
1933            vpos[0], vpos[1], vpos[2], tof, polar[0],polar[1],polar[2],
1934            mech, ntr, weight);
1935 */         
1936 }
1937
1938 //_____________________________________________________________________________
1939 void AliRun::SetTrack(Int_t done, Int_t parent, Int_t pdg,
1940                       Double_t px, Double_t py, Double_t pz, Double_t e,
1941                       Double_t vx, Double_t vy, Double_t vz, Double_t tof,
1942                       Double_t polx, Double_t poly, Double_t polz,
1943                       AliMCProcess mech, Int_t &ntr, Float_t weight)
1944
1945   //
1946   // Load a track on the stack
1947   //
1948   // done        0 if the track has to be transported
1949   //             1 if not
1950   // parent      identifier of the parent track. -1 for a primary
1951   // pdg         particle code
1952   // kS          generation status code
1953   // px, py, pz  momentum GeV/c
1954   // vx, vy, vz  position 
1955   // polar       polarisation 
1956   // tof         time of flight in seconds
1957   // mech        production mechanism
1958   // ntr         on output the number of the track stored
1959   //    
1960   // New method interface: 
1961   // arguments were changed to be in correspondence with TParticle
1962   // constructor.
1963   // Note: the energy is not calculated from the static mass but
1964   // it is passed by argument e.
1965
1966   TClonesArray &particles = *fParticles;
1967
1968   const Int_t kS=0;
1969   const Int_t kFirstDaughter=-1;
1970   const Int_t kLastDaughter=-1;
1971   
1972   TParticle* particle
1973     = new(particles[fLoadPoint++]) TParticle(pdg, kS, parent, -1, 
1974                                         kFirstDaughter, kLastDaughter,
1975                                         px, py, pz, e, vx, vy, vz, tof);
1976    
1977   particle->SetPolarisation(polx, poly, polz);
1978   particle->SetWeight(weight);
1979   particle->SetUniqueID(mech);
1980
1981   if(!done) particle->SetBit(kDoneBit);
1982
1983   //  Declare that the daughter information is valid
1984   particle->SetBit(kDaughtersBit);
1985   //  Add the particle to the stack
1986   fParticleMap->AddAtAndExpand(particle,fNtrack);
1987
1988   if(parent>=0) {
1989     particle=(TParticle*) fParticleMap->At(parent);
1990     particle->SetLastDaughter(fNtrack);
1991     if(particle->GetFirstDaughter()<0) particle->SetFirstDaughter(fNtrack);
1992   } else { 
1993     //
1994     // This is a primary track. Set high water mark for this event
1995     fHgwmk=fNtrack;
1996     //
1997     // Set also number if primary tracks
1998     fHeader.SetNprimary(fHgwmk+1);
1999     fHeader.SetNtrack(fHgwmk+1);
2000   }
2001   ntr = fNtrack++;
2002 }
2003
2004 //_____________________________________________________________________________
2005 void AliRun::SetHighWaterMark(const Int_t nt)
2006 {
2007     //
2008     // Set high water mark for last track in event
2009     fHgwmk=fNtrack-1;
2010     //
2011     // Set also number if primary tracks
2012     fHeader.SetNprimary(fHgwmk+1);
2013     fHeader.SetNtrack(fHgwmk+1);
2014 }
2015
2016 //_____________________________________________________________________________
2017 void AliRun::KeepTrack(const Int_t track)
2018
2019   //
2020   // flags a track to be kept
2021   //
2022   fParticleMap->At(track)->SetBit(kKeepBit);
2023 }
2024  
2025 //_____________________________________________________________________________
2026 void AliRun::StepManager(Int_t id) 
2027 {
2028   //
2029   // Called at every step during transport
2030   //
2031
2032   //
2033   // --- If lego option, do it and leave 
2034   if (fLego)
2035     fLego->StepManager();
2036   else {
2037     Int_t copy;
2038     //Update energy deposition tables
2039     AddEnergyDeposit(gMC->CurrentVolID(copy),gMC->Edep());
2040   
2041     //Call the appropriate stepping routine;
2042     AliModule *det = (AliModule*)fModules->At(id);
2043     if(det) {
2044       fMCQA->StepManager(id);
2045       det->StepManager();
2046     }
2047   }
2048 }
2049
2050 //_____________________________________________________________________________
2051 void AliRun::Streamer(TBuffer &R__b)
2052 {
2053    // Stream an object of class AliRun.
2054
2055    if (R__b.IsReading()) {
2056       if (!gAlice) gAlice = this;
2057
2058       AliRun::Class()->ReadBuffer(R__b, this);
2059       //
2060       gROOT->GetListOfBrowsables()->Add(this,"Run");
2061
2062       fTreeE = (TTree*)gDirectory->Get("TE");
2063       if (fTreeE) fTreeE->SetBranchAddress("Header", &gAliHeader);
2064       else    Error("Streamer","cannot find Header Tree\n");
2065       fTreeE->GetEntry(0);
2066
2067       gRandom = fRandom;
2068    } else {
2069       AliRun::Class()->WriteBuffer(R__b, this);
2070    }
2071 }
2072