1 /**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
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 **************************************************************************/
18 // This class is extracted from the AliRun class
19 // and contains all the MC-related functionality
20 // The number of dependencies has to be reduced...
21 // Author: F.Carminati
22 // Federico.Carminati@cern.ch
28 #include <TClonesArray.h>
30 #include <TGeoGlobalMagField.h>
31 #include <TGeoManager.h>
32 #include <TParticle.h>
34 #include <TStopwatch.h>
36 #include <TVirtualMC.h>
39 #include "AliCDBEntry.h"
40 #include "AliCDBManager.h"
41 #include "AliCDBStorage.h"
42 #include "AliDetector.h"
43 #include "AliGenerator.h"
44 #include "AliGeomManager.h"
45 #include "AliHeader.h"
52 #include "AliSimulation.h"
54 #include "AliTrackReference.h"
58 //_______________________________________________________________________
61 fSaveRndmStatus(kFALSE),
62 fSaveRndmEventStatus(kFALSE),
63 fReadRndmStatus(kFALSE),
64 fRndmFileName("random.root"),
86 //_______________________________________________________________________
87 AliMC::AliMC(const char *name, const char *title) :
88 TVirtualMCApplication(name, title),
90 fSaveRndmStatus(kFALSE),
91 fSaveRndmEventStatus(kFALSE),
92 fReadRndmStatus(kFALSE),
93 fRndmFileName("random.root"),
102 fImedia(new TArrayI(1000)),
104 fHitLists(new TList()),
107 fTrackReferences("AliTrackReference", 100),
108 fTmpTrackReferences("AliTrackReference", 100)
111 // Set transport parameters
114 // Prepare the tracking medium lists
115 for(Int_t i=0;i<1000;i++) (*fImedia)[i]=-99;
118 //_______________________________________________________________________
125 // Delete track references
128 //_______________________________________________________________________
129 void AliMC::ConstructGeometry()
132 // Either load geometry from file or create it through usual
133 // loop on detectors. In the first case the method
134 // AliModule::CreateMaterials() only builds fIdtmed and is postponed
135 // at InitGeometry().
138 if(AliSimulation::Instance()->IsGeometryFromFile()){ //load geometry either from CDB or from file
139 if(IsGeometryFromCDB()){
140 AliInfo("Loading geometry from CDB default storage");
141 AliCDBPath path("GRP","Geometry","Data");
142 AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath());
143 if(!entry) AliFatal("Unable to load geometry from CDB!");
145 gGeoManager = (TGeoManager*) entry->GetObject();
146 if (!gGeoManager) AliFatal("TGeoManager object not found in the specified CDB entry!");
149 const char *geomfilename = AliSimulation::Instance()->GetGeometryFile();
150 if(gSystem->ExpandPathName(geomfilename)){
151 AliInfo(Form("Loading geometry from file:\n %40s",geomfilename));
152 TGeoManager::Import(geomfilename);
154 AliInfo(Form("Geometry file %40s not found!\n",geomfilename));
158 gMC->SetRootGeometry();
160 // Create modules, materials, geometry
161 if (!gGeoManager) new TGeoManager("ALICE", "ALICE geometry");
163 TIter next(gAlice->Modules());
165 AliDebug(1, "Geometry creation:");
166 while((detector = dynamic_cast<AliModule*>(next()))) {
168 // Initialise detector materials and geometry
169 detector->CreateMaterials();
170 detector->CreateGeometry();
171 AliInfo(Form("%10s R:%.2fs C:%.2fs",
172 detector->GetName(),stw.RealTime(),stw.CpuTime()));
178 //_______________________________________________________________________
179 Bool_t AliMC::MisalignGeometry()
181 // Call misalignment code if AliSimulation object was defined.
183 if(!AliSimulation::Instance()->IsGeometryFromFile()){
184 //Set alignable volumes for the whole geometry
185 SetAllAlignableVolumes();
187 // Misalign geometry via AliSimulation instance
188 if (!AliSimulation::Instance()) return kFALSE;
189 AliGeomManager::SetGeometry(gGeoManager);
190 if(!AliGeomManager::CheckSymNamesLUT("ALL"))
191 AliFatal("Current loaded geometry differs in the definition of symbolic names!");
193 return AliSimulation::Instance()->MisalignGeometry(AliRunLoader::Instance());
196 //_______________________________________________________________________
197 void AliMC::ConstructOpGeometry()
200 // Loop all detector modules and call DefineOpticalProperties() method
203 TIter next(gAlice->Modules());
205 AliInfo("Optical properties definition");
206 while((detector = dynamic_cast<AliModule*>(next()))) {
207 // Initialise detector geometry
208 if(AliSimulation::Instance()->IsGeometryFromFile()) detector->CreateMaterials();
209 // Initialise detector optical properties
210 detector->DefineOpticalProperties();
214 //_______________________________________________________________________
215 void AliMC::InitGeometry()
218 // Initialize detectors
221 AliInfo("Initialisation:");
223 TIter next(gAlice->Modules());
225 while((detector = dynamic_cast<AliModule*>(next()))) {
228 AliInfo(Form("%10s R:%.2fs C:%.2fs",
229 detector->GetName(),stw.RealTime(),stw.CpuTime()));
233 //_______________________________________________________________________
234 void AliMC::SetGeometryFromCDB()
236 // Set the loading of geometry from cdb instead of creating it
237 // A default CDB storage needs to be set before this method is called
238 if(AliCDBManager::Instance()->IsDefaultStorageSet() &&
239 AliCDBManager::Instance()->GetRun() >= 0)
240 AliSimulation::Instance()->SetGeometryFile("*OCDB*");
242 AliError("Loading of geometry from CDB ignored. First set a default CDB storage!");
245 //_______________________________________________________________________
246 Bool_t AliMC::IsGeometryFromCDB() const
248 return (strcmp(AliSimulation::Instance()->GetGeometryFile(),"*OCDB*")==0);
251 //_______________________________________________________________________
252 void AliMC::SetAllAlignableVolumes()
255 // Add alignable volumes (TGeoPNEntries) looping on all
259 AliInfo(Form("Setting entries for all alignable volumes of active detectors"));
261 TIter next(gAlice->Modules());
262 while((detector = dynamic_cast<AliModule*>(next()))) {
263 detector->AddAlignableVolumes();
267 //_______________________________________________________________________
268 void AliMC::GeneratePrimaries()
271 // Generate primary particles and fill them in the stack.
274 Generator()->Generate();
277 //_______________________________________________________________________
278 void AliMC::SetGenerator(AliGenerator *generator)
281 // Load the event generator
283 if(!fGenerator) fGenerator = generator;
286 //_______________________________________________________________________
287 void AliMC::ResetGenerator(AliGenerator *generator)
290 // Load the event generator
294 AliWarning(Form("Replacing generator %s with %s",
295 fGenerator->GetName(),generator->GetName()));
298 AliWarning(Form("Replacing generator %s with NULL",
299 fGenerator->GetName()));
302 fGenerator = generator;
305 //_______________________________________________________________________
306 void AliMC::FinishRun()
308 // Clean generator information
309 AliDebug(1, "fGenerator->FinishRun()");
310 fGenerator->FinishRun();
312 //Output energy summary tables
313 AliDebug(1, "EnergySummary()");
314 ToAliDebug(1, EnergySummary());
317 //_______________________________________________________________________
318 void AliMC::BeginPrimary()
321 // Called at the beginning of each primary track
326 ResetTrackReferences();
329 //_______________________________________________________________________
330 void AliMC::PreTrack()
332 // Actions before the track's transport
334 TObjArray &dets = *gAlice->Modules();
337 for(Int_t i=0; i<=gAlice->GetNdets(); i++)
338 if((module = dynamic_cast<AliModule*>(dets[i])))
342 //_______________________________________________________________________
343 void AliMC::Stepping()
346 // Called at every step during transport
348 Int_t id = DetFromMate(gMC->CurrentMedium());
352 if ( gMC->IsNewTrack() &&
353 gMC->TrackTime() == 0. &&
355 fRDecayMax > fRDecayMin &&
356 gMC->TrackPid() == fDecayPdg )
358 FixParticleDecaytime();
364 // --- If lego option, do it and leave
365 if (AliSimulation::Instance()->Lego())
366 AliSimulation::Instance()->Lego()->StepManager();
369 //Update energy deposition tables
370 AddEnergyDeposit(gMC->CurrentVolID(copy),gMC->Edep());
372 // write tracke reference for track which is dissapearing - MI
374 if (gMC->IsTrackDisappeared() && !(gMC->IsTrackAlive())) {
375 if (gMC->Etot() > 0.05) AddTrackReference(GetCurrentTrackNumber(),
376 AliTrackReference::kDisappeared);
381 //Call the appropriate stepping routine;
382 AliModule *det = dynamic_cast<AliModule*>(gAlice->Modules()->At(id));
383 if(det && det->StepManagerIsEnabled()) {
389 //_______________________________________________________________________
390 void AliMC::EnergySummary()
393 // Print summary of deposited energy
399 Int_t kn, i, left, j, id;
400 const Float_t kzero=0;
401 Int_t ievent=AliRunLoader::Instance()->GetHeader()->GetEvent()+1;
403 // Energy loss information
405 printf("***************** Energy Loss Information per event (GEV) *****************\n");
406 for(kn=1;kn<fEventEnergy.GetSize();kn++) {
409 fEventEnergy[ndep]=kn;
414 ed2=100*TMath::Sqrt(TMath::Max(ed2-ed*ed,kzero))/ed;
417 fSummEnergy[ndep]=ed;
418 fSum2Energy[ndep]=TMath::Min(static_cast<Float_t>(99.),TMath::Max(ed2,kzero));
423 for(kn=0;kn<(ndep-1)/3+1;kn++) {
425 for(i=0;i<(3<left?3:left);i++) {
427 id=Int_t (fEventEnergy[j]+0.1);
428 printf(" %s %10.3f +- %10.3f%%;",gMC->VolName(id),fSummEnergy[j],fSum2Energy[j]);
433 // Relative energy loss in different detectors
434 printf("******************** Relative Energy Loss per event ********************\n");
435 printf("Total energy loss per event %10.3f GeV\n",edtot);
436 for(kn=0;kn<(ndep-1)/5+1;kn++) {
438 for(i=0;i<(5<left?5:left);i++) {
440 id=Int_t (fEventEnergy[j]+0.1);
441 printf(" %s %10.3f%%;",gMC->VolName(id),100*fSummEnergy[j]/edtot);
445 for(kn=0;kn<75;kn++) printf("*");
449 // Reset the TArray's
450 // fEventEnergy.Set(0);
451 // fSummEnergy.Set(0);
452 // fSum2Energy.Set(0);
455 //_____________________________________________________________________________
456 void AliMC::BeginEvent()
459 // Clean-up previous event
461 AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
462 AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
463 AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
464 AliDebug(1, " BEGINNING EVENT ");
465 AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
466 AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
467 AliDebug(1, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
469 AliRunLoader *runloader=AliRunLoader::Instance();
471 /*******************************/
472 /* Clean after eventual */
474 /*******************************/
477 //Set the next event in Run Loader -> Cleans trees (TreeK and all trees in detectors),
478 gAlice->SetEventNrInRun(gAlice->GetEventNrInRun()+1);
479 runloader->SetEventNumber(gAlice->GetEventNrInRun());// sets new files, cleans the previous event stuff, if necessary, etc.,
480 AliDebug(1, Form("EventNr is %d",gAlice->GetEventNrInRun()));
482 fEventEnergy.Reset();
483 // Clean detector information
485 if (runloader->Stack())
486 runloader->Stack()->Reset();//clean stack -> tree is unloaded
488 runloader->MakeStack();//or make a new one
490 // Random engine status
493 if ( fSaveRndmStatus || fSaveRndmEventStatus) {
494 TString fileName="random";
495 if ( fSaveRndmEventStatus ) {
497 fileName += gAlice->GetEventNrInRun();
501 // write ROOT random engine status
502 cout << "Saving random engine status in " << fileName.Data() << endl;
503 TFile f(fileName.Data(),"RECREATE");
504 gRandom->Write(fileName.Data());
507 if ( fReadRndmStatus ) {
508 //read ROOT random engine status
509 cout << "Reading random engine status from " << fRndmFileName.Data() << endl;
510 TFile f(fRndmFileName.Data());
511 gRandom->Read(fRndmFileName.Data());
514 if(AliSimulation::Instance()->Lego() == 0x0)
516 AliDebug(1, "fRunLoader->MakeTree(K)");
517 runloader->MakeTree("K");
520 AliDebug(1, "gMC->SetStack(fRunLoader->Stack())");
521 gMC->SetStack(runloader->Stack());//Was in InitMC - but was moved here
522 //because we don't have guarantee that
523 //stack pointer is not going to change from event to event
524 //since it bellobgs to header and is obtained via RunLoader
526 // Reset all Detectors & kinematics & make/reset trees
529 runloader->GetHeader()->Reset(AliCDBManager::Instance()->GetRun(),gAlice->GetEvNumber(),
530 gAlice->GetEventNrInRun());
531 // fRunLoader->WriteKinematics("OVERWRITE"); is there any reason to rewrite here since MakeTree does so
533 if(AliSimulation::Instance()->Lego())
535 AliSimulation::Instance()->Lego()->BeginEvent();
540 AliDebug(1, "ResetHits()");
543 AliDebug(1, "fRunLoader->MakeTree(H)");
544 runloader->MakeTree("H");
548 MakeTmpTrackRefsTree();
549 //create new branches and SetAdresses
550 TIter next(gAlice->Modules());
552 while((detector = (AliModule*)next()))
554 AliDebug(2, Form("%s->MakeBranch(H)",detector->GetName()));
555 detector->MakeBranch("H");
559 //_______________________________________________________________________
560 void AliMC::ResetHits()
563 // Reset all Detectors hits
565 TIter next(gAlice->Modules());
567 while((detector = dynamic_cast<AliModule*>(next()))) {
568 detector->ResetHits();
572 //_______________________________________________________________________
573 void AliMC::ResetDigits()
576 // Reset all Detectors digits
578 TIter next(gAlice->Modules());
580 while((detector = dynamic_cast<AliModule*>(next()))) {
581 detector->ResetDigits();
585 //_______________________________________________________________________
586 void AliMC::ResetSDigits()
589 // Reset all Detectors digits
591 TIter next(gAlice->Modules());
593 while((detector = dynamic_cast<AliModule*>(next()))) {
594 detector->ResetSDigits();
598 //_______________________________________________________________________
599 void AliMC::PostTrack()
601 // Posts tracks for each module
603 TObjArray &dets = *gAlice->Modules();
606 for(Int_t i=0; i<=gAlice->GetNdets(); i++)
607 if((module = dynamic_cast<AliModule*>(dets[i])))
611 //_______________________________________________________________________
612 void AliMC::FinishPrimary()
615 // Called at the end of each primary track
618 AliRunLoader *runloader=AliRunLoader::Instance();
619 // static Int_t count=0;
620 // const Int_t times=10;
621 // This primary is finished, purify stack
622 #if ROOT_VERSION_CODE > 262152
623 if (!(gMC->SecondariesAreOrdered())) {
624 if (runloader->Stack()->ReorderKine()) RemapHits();
627 if (runloader->Stack()->PurifyKine()) RemapHits();
629 TIter next(gAlice->Modules());
631 while((detector = dynamic_cast<AliModule*>(next()))) {
632 detector->FinishPrimary();
633 AliLoader* loader = detector->GetLoader();
636 TTree* treeH = loader->TreeH();
637 if (treeH) treeH->Fill(); //can be Lego run and treeH can not exist
641 // Write out track references if any
642 if (fTmpTreeTR) fTmpTreeTR->Fill();
645 void AliMC::RemapHits()
648 // Remaps the track labels of the hits
649 AliRunLoader *runloader=AliRunLoader::Instance();
650 AliStack* stack = runloader->Stack();
651 TList* hitLists = GetHitLists();
652 TIter next(hitLists);
653 TCollection *hitList;
655 while((hitList = dynamic_cast<TCollection*>(next()))) {
656 TIter nexthit(hitList);
658 while((hit = dynamic_cast<AliHit*>(nexthit()))) {
659 hit->SetTrack(stack->TrackLabel(hit->GetTrack()));
664 // This for detectors which have a special mapping mechanism
665 // for hits, such as TPC and TRD
669 TObjArray* modules = gAlice->Modules();
670 TIter nextmod(modules);
672 while((module = (AliModule*) nextmod())) {
673 AliDetector* det = dynamic_cast<AliDetector*> (module);
674 if (det) det->RemapTrackHitIDs(stack->TrackLabelMap());
677 RemapTrackReferencesIDs(stack->TrackLabelMap());
680 //_______________________________________________________________________
681 void AliMC::FinishEvent()
684 // Called at the end of the event.
687 if(AliSimulation::Instance()->Lego()) AliSimulation::Instance()->Lego()->FinishEvent();
689 TIter next(gAlice->Modules());
691 while((detector = dynamic_cast<AliModule*>(next()))) {
692 detector->FinishEvent();
695 //Update the energy deposit tables
697 for(i=0;i<fEventEnergy.GetSize();i++)
699 fSummEnergy[i]+=fEventEnergy[i];
700 fSum2Energy[i]+=fEventEnergy[i]*fEventEnergy[i];
703 AliRunLoader *runloader=AliRunLoader::Instance();
705 AliHeader* header = runloader->GetHeader();
706 AliStack* stack = runloader->Stack();
707 if ( (header == 0x0) || (stack == 0x0) )
708 {//check if we got header and stack. If not cry and exit aliroot
709 AliFatal("Can not get the stack or header from LOADER");
710 return;//never reached
712 // Update Header information
713 header->SetNprimary(stack->GetNprimary());
714 header->SetNtrack(stack->GetNtrack());
715 header->SetTimeStamp(AliSimulation::Instance()->GenerateTimeStamp());
717 // Write out the kinematics
718 if (!AliSimulation::Instance()->Lego()) stack->FinishEvent();
720 // Synchronize the TreeTR with TreeK
721 if (fTmpTreeTR) ReorderAndExpandTreeTR();
723 // Write out the event Header information
724 TTree* treeE = runloader->TreeE();
727 header->SetStack(stack);
732 AliError("Can not get TreeE from RL");
735 if(AliSimulation::Instance()->Lego() == 0x0)
737 runloader->WriteKinematics("OVERWRITE");
738 runloader->WriteTrackRefs("OVERWRITE");
739 runloader->WriteHits("OVERWRITE");
742 AliDebug(1, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
743 AliDebug(1, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
744 AliDebug(1, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
745 AliDebug(1, " FINISHING EVENT ");
746 AliDebug(1, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
747 AliDebug(1, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
748 AliDebug(1, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
751 //_______________________________________________________________________
757 //=================Create Materials and geometry
759 // Set alignable volumes for the whole geometry (with old root)
760 #if ROOT_VERSION_CODE < 331527
761 SetAllAlignableVolumes();
763 //Read the cuts for all materials
765 //Build the special IMEDIA table
768 //Compute cross-sections
771 //Initialise geometry deposition table
772 fEventEnergy.Set(gMC->NofVolumes()+1);
773 fSummEnergy.Set(gMC->NofVolumes()+1);
774 fSum2Energy.Set(gMC->NofVolumes()+1);
776 // Register MC in configuration
777 AliConfig::Instance()->Add(gMC);
780 //_______________________________________________________________________
781 void AliMC::MediaTable()
784 // Built media table to get from the media number to
788 Int_t kz, nz, idt, lz, i, k, ind;
790 TObjArray &dets = *gAlice->Detectors();
792 Int_t ndets=gAlice->GetNdets();
795 for (kz=0;kz<ndets;kz++) {
796 // If detector is defined
797 if((det=dynamic_cast<AliModule*>(dets[kz]))) {
798 TArrayI &idtmed = *(det->GetIdtmed());
799 for(nz=0;nz<100;nz++) {
801 // Find max and min material number
802 if((idt=idtmed[nz])) {
803 det->LoMedium() = det->LoMedium() < idt ? det->LoMedium() : idt;
804 det->HiMedium() = det->HiMedium() > idt ? det->HiMedium() : idt;
807 if(det->LoMedium() > det->HiMedium()) {
811 if(det->HiMedium() > fImedia->GetSize()) {
812 AliError(Form("Increase fImedia from %d to %d",
813 fImedia->GetSize(),det->HiMedium()));
816 // Tag all materials in rage as belonging to detector kz
817 for(lz=det->LoMedium(); lz<= det->HiMedium(); lz++) {
824 // Print summary table
825 AliInfo("Tracking media ranges:");
827 for(i=0;i<(ndets-1)/6+1;i++) {
828 for(k=0;k< (6<ndets-i*6?6:ndets-i*6);k++) {
830 det=dynamic_cast<AliModule*>(dets[ind]);
832 printf(" %6s: %3d -> %3d;",det->GetName(),det->LoMedium(),
835 printf(" %6s: %3d -> %3d;","NULL",0,0);
842 //_______________________________________________________________________
843 void AliMC::ReadTransPar()
846 // Read filename to set the transport parameters
850 const Int_t kncuts=10;
851 const Int_t knflags=12;
852 const Int_t knpars=kncuts+knflags;
853 const char kpars[knpars][7] = {"CUTGAM" ,"CUTELE","CUTNEU","CUTHAD","CUTMUO",
854 "BCUTE","BCUTM","DCUTE","DCUTM","PPCUTM","ANNI",
855 "BREM","COMP","DCAY","DRAY","HADR","LOSS",
856 "MULS","PAIR","PHOT","RAYL","STRA"};
862 Int_t i, itmed, iret, ktmed, kz;
865 // See whether the file is there
866 filtmp=gSystem->ExpandPathName(fTransParName.Data());
867 lun=fopen(filtmp,"r");
870 AliWarning(Form("File %s does not exist!",fTransParName.Data()));
875 // Initialise cuts and flags
876 for(i=0;i<kncuts;i++) cut[i]=-99;
877 for(i=0;i<knflags;i++) flag[i]=-99;
880 // Read up to the end of line excluded
881 iret=fscanf(lun,"%255[^\n]",line);
887 // Read the end of line
890 if(line[0]=='*') continue;
892 iret=sscanf(line,"%6s %d %f %f %f %f %f %f %f %f %f %f %d %d %d %d %d %d %d %d %d %d %d %d",
893 detName,&itmed,&cut[0],&cut[1],&cut[2],&cut[3],&cut[4],&cut[5],&cut[6],&cut[7],&cut[8],
894 &cut[9],&flag[0],&flag[1],&flag[2],&flag[3],&flag[4],&flag[5],&flag[6],&flag[7],
895 &flag[8],&flag[9],&flag[10],&flag[11]);
899 AliWarning(Form("Error reading file %s",fTransParName.Data()));
902 // Check that the module exist
903 AliModule *mod = gAlice->GetModule(detName);
905 // Get the array of media numbers
906 TArrayI &idtmed = *mod->GetIdtmed();
907 // Check that the tracking medium code is valid
908 if(0<=itmed && itmed < 100) {
911 AliWarning(Form("Invalid tracking medium code %d for %s",itmed,mod->GetName()));
914 // Set energy thresholds
915 for(kz=0;kz<kncuts;kz++) {
917 AliDebug(2, Form("%-6s set to %10.3E for tracking medium code %4d for %s",
918 kpars[kz],cut[kz],itmed,mod->GetName()));
919 gMC->Gstpar(ktmed,kpars[kz],cut[kz]);
922 // Set transport mechanisms
923 for(kz=0;kz<knflags;kz++) {
925 AliDebug(2, Form("%-6s set to %10d for tracking medium code %4d for %s",
926 kpars[kncuts+kz],flag[kz],itmed,mod->GetName()));
927 gMC->Gstpar(ktmed,kpars[kncuts+kz],Float_t(flag[kz]));
931 AliWarning(Form("Invalid medium code %d",itmed));
935 AliDebug(1, Form("%s not present",detName));
941 //_______________________________________________________________________
942 void AliMC::SetTransPar(const char *filename)
945 // Sets the file name for transport parameters
947 fTransParName = filename;
950 //_______________________________________________________________________
951 void AliMC::AddHit(Int_t id, Int_t track, Int_t *vol, Float_t *hits) const
954 // Add a hit to detector id
956 TObjArray &dets = *gAlice->Modules();
957 if(dets[id]) static_cast<AliModule*>(dets[id])->AddHit(track,vol,hits);
960 //_______________________________________________________________________
961 void AliMC::AddDigit(Int_t id, Int_t *tracks, Int_t *digits) const
964 // Add digit to detector id
966 TObjArray &dets = *gAlice->Modules();
967 if(dets[id]) static_cast<AliModule*>(dets[id])->AddDigit(tracks,digits);
970 //_______________________________________________________________________
971 Int_t AliMC::GetCurrentTrackNumber() const {
973 // Returns current track
975 return AliRunLoader::Instance()->Stack()->GetCurrentTrackNumber();
978 //_______________________________________________________________________
979 void AliMC::DumpPart (Int_t i) const
982 // Dumps particle i in the stack
984 AliRunLoader * runloader = AliRunLoader::Instance();
985 if (runloader->Stack())
986 runloader->Stack()->DumpPart(i);
989 //_______________________________________________________________________
990 void AliMC::DumpPStack () const
993 // Dumps the particle stack
995 AliRunLoader * runloader = AliRunLoader::Instance();
996 if (runloader->Stack())
997 runloader->Stack()->DumpPStack();
1000 //_______________________________________________________________________
1001 Int_t AliMC::GetNtrack() const {
1003 // Returns number of tracks in stack
1006 AliRunLoader * runloader = AliRunLoader::Instance();
1007 if (runloader->Stack())
1008 ntracks = runloader->Stack()->GetNtrack();
1012 //_______________________________________________________________________
1013 Int_t AliMC::GetPrimary(Int_t track) const
1016 // return number of primary that has generated track
1018 Int_t nprimary = -999;
1019 AliRunLoader * runloader = AliRunLoader::Instance();
1020 if (runloader->Stack())
1021 nprimary = runloader->Stack()->GetPrimary(track);
1025 //_______________________________________________________________________
1026 TParticle* AliMC::Particle(Int_t i) const
1028 // Returns the i-th particle from the stack taking into account
1029 // the remaping done by PurifyKine
1030 AliRunLoader * runloader = AliRunLoader::Instance();
1032 if (runloader->Stack())
1033 return runloader->Stack()->Particle(i);
1037 //_______________________________________________________________________
1038 const TObjArray* AliMC::Particles() const {
1040 // Returns pointer to Particles array
1042 AliRunLoader * runloader = AliRunLoader::Instance();
1044 if (runloader->Stack())
1045 return runloader->Stack()->Particles();
1049 //_______________________________________________________________________
1050 void AliMC::PushTrack(Int_t done, Int_t parent, Int_t pdg, const Float_t *pmom,
1051 const Float_t *vpos, const Float_t *polar, Float_t tof,
1052 TMCProcess mech, Int_t &ntr, Float_t weight, Int_t is) const
1054 // Delegate to stack
1056 AliRunLoader * runloader = AliRunLoader::Instance();
1058 if (runloader->Stack())
1059 runloader->Stack()->PushTrack(done, parent, pdg, pmom, vpos, polar, tof,
1060 mech, ntr, weight, is);
1063 //_______________________________________________________________________
1064 void AliMC::PushTrack(Int_t done, Int_t parent, Int_t pdg,
1065 Double_t px, Double_t py, Double_t pz, Double_t e,
1066 Double_t vx, Double_t vy, Double_t vz, Double_t tof,
1067 Double_t polx, Double_t poly, Double_t polz,
1068 TMCProcess mech, Int_t &ntr, Float_t weight, Int_t is) const
1070 // Delegate to stack
1072 AliRunLoader * runloader = AliRunLoader::Instance();
1074 if (runloader->Stack())
1075 runloader->Stack()->PushTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof,
1076 polx, poly, polz, mech, ntr, weight, is);
1079 //_______________________________________________________________________
1080 void AliMC::SetHighWaterMark(Int_t nt) const
1083 // Set high water mark for last track in event
1084 AliRunLoader * runloader = AliRunLoader::Instance();
1086 if (runloader->Stack())
1087 runloader->Stack()->SetHighWaterMark(nt);
1090 //_______________________________________________________________________
1091 void AliMC::KeepTrack(Int_t track) const
1094 // Delegate to stack
1096 AliRunLoader * runloader = AliRunLoader::Instance();
1098 if (runloader->Stack())
1099 runloader->Stack()->KeepTrack(track);
1102 //_______________________________________________________________________
1103 void AliMC::FlagTrack(Int_t track) const
1105 // Delegate to stack
1107 AliRunLoader * runloader = AliRunLoader::Instance();
1109 if (runloader->Stack())
1110 runloader->Stack()->FlagTrack(track);
1113 //_______________________________________________________________________
1114 void AliMC::SetCurrentTrack(Int_t track) const
1117 // Set current track number
1119 AliRunLoader * runloader = AliRunLoader::Instance();
1121 if (runloader->Stack())
1122 runloader->Stack()->SetCurrentTrack(track);
1125 //_______________________________________________________________________
1126 AliTrackReference* AliMC::AddTrackReference(Int_t label, Int_t id)
1129 // add a trackrefernce to the list
1130 Int_t primary = GetPrimary(label);
1131 Particle(primary)->SetBit(kKeepBit);
1133 Int_t nref = fTmpTrackReferences.GetEntriesFast();
1134 return new(fTmpTrackReferences[nref]) AliTrackReference(label, id);
1139 //_______________________________________________________________________
1140 void AliMC::ResetTrackReferences()
1143 // Reset all references
1145 fTmpTrackReferences.Clear();
1148 //_______________________________________________________________________
1149 void AliMC::RemapTrackReferencesIDs(const Int_t *map)
1152 // Remapping track reference
1153 // Called at finish primary
1156 Int_t nEntries = fTmpTrackReferences.GetEntries();
1157 for (Int_t i=0; i < nEntries; i++){
1158 AliTrackReference * ref = dynamic_cast<AliTrackReference*>(fTmpTrackReferences.UncheckedAt(i));
1160 Int_t newID = map[ref->GetTrack()];
1161 if (newID>=0) ref->SetTrack(newID);
1163 ref->SetBit(kNotDeleted,kFALSE);
1164 fTmpTrackReferences.RemoveAt(i);
1168 fTmpTrackReferences.Compress();
1171 //_______________________________________________________________________
1172 void AliMC::FixParticleDecaytime()
1175 // Fix the particle decay time according to rmin and rmax for decays
1179 gMC->TrackMomentum(p);
1180 Double_t tmin, tmax;
1183 // Transverse velocity
1184 Double_t vt = p.Pt() / p.E();
1186 if ((b = ((AliMagF*)TGeoGlobalMagField::Instance()->GetField())->SolenoidField()) > 0.) { // [kG]
1190 Double_t rho = p.Pt() / 0.0003 / b; // [cm]
1192 // Revolution frequency
1194 Double_t omega = vt / rho;
1196 // Maximum and minimum decay time
1198 // Check for curlers first
1199 const Double_t kOvRhoSqr2 = 1./(rho*TMath::Sqrt(2.));
1200 if (fRDecayMax * kOvRhoSqr2 > 1.) return;
1204 tmax = TMath::ACos((1.-fRDecayMax*kOvRhoSqr2)*(1.+fRDecayMax*kOvRhoSqr2)) / omega; // [ct]
1205 tmin = TMath::ACos((1.-fRDecayMin*kOvRhoSqr2)*(1.+fRDecayMin*kOvRhoSqr2)) / omega; // [ct]
1207 tmax = fRDecayMax / vt; // [ct]
1208 tmin = fRDecayMin / vt; // [ct]
1212 // Dial t using the two limits
1213 Double_t t = tmin + (tmax - tmin) * gRandom->Rndm(); // [ct]
1216 // Force decay time in transport code
1218 gMC->ForceDecayTime(t / 2.99792458e10);
1221 void AliMC::MakeTmpTrackRefsTree()
1223 // Make the temporary track reference tree
1224 fTmpFileTR = new TFile("TrackRefsTmp.root", "recreate");
1225 fTmpTreeTR = new TTree("TreeTR", "Track References");
1226 TClonesArray* pRef = &fTmpTrackReferences;
1227 fTmpTreeTR->Branch("TrackReferences", &pRef, 4000);
1230 //_______________________________________________________________________
1231 void AliMC::ReorderAndExpandTreeTR()
1234 // Reorder and expand the temporary track reference tree in order to match the kinematics tree
1237 AliRunLoader *rl = AliRunLoader::Instance();
1240 AliDebug(1, "fRunLoader->MakeTrackRefsContainer()");
1241 rl->MakeTrackRefsContainer();
1242 TTree * treeTR = rl->TreeTR();
1243 // make branch for central track references
1244 TClonesArray* pRef = &fTrackReferences;
1245 treeTR->Branch("TrackReferences", &pRef);
1247 AliStack* stack = rl->Stack();
1248 Int_t np = stack->GetNprimary();
1249 Int_t nt = fTmpTreeTR->GetEntries();
1251 // Loop over tracks and find the secondaries with the help of the kine tree
1254 for (Int_t ip = np - 1; ip > -1; ip--) {
1255 TParticle *part = stack->Particle(ip);
1256 //printf("Particle %5d %5d %5d %5d %5d \n", ip, part->GetPdgCode(), part->GetFirstMother(), part->GetFirstDaughter(), part->GetLastDaughter());
1258 // Skip primaries that have not been transported
1259 Int_t dau1 = part->GetFirstDaughter();
1261 if (!part->TestBit(kTransportBit)) continue;
1263 fTmpTreeTR->GetEntry(it++);
1264 Int_t nh = fTmpTrackReferences.GetEntries();
1265 // Determine range of secondaries produced by this primary
1267 Int_t inext = ip - 1;
1270 part = stack->Particle(inext);
1271 dau2 = part->GetFirstDaughter();
1272 if (!(part->TestBit(kTransportBit)) || dau2 == -1 || dau2 < np) {
1273 // if (dau2 == -1 || dau2 < np) {
1279 dau2 = stack->GetNtrack() - 1;
1282 } // find upper bound
1284 // printf("Check (1) %5d %5d %5d %5d %5d \n", ip, np, it, dau1, dau2);
1286 // Loop over reference hits and find secondary label
1287 for (Int_t id = dau1; (id <= dau2) && (dau1 > -1); id++) {
1288 for (Int_t ih = 0; ih < nh; ih++) {
1289 AliTrackReference* tr = (AliTrackReference*) fTmpTrackReferences.At(ih);
1290 Int_t label = tr->Label();
1292 if (label == ip) continue;
1293 if (label > dau2 || label < dau1)
1294 AliWarning(Form("Track Reference Label out of range !: %5d %5d %5d \n", label, dau1, dau2));
1297 Int_t nref = fTrackReferences.GetEntriesFast();
1298 new(fTrackReferences[nref]) AliTrackReference(*tr);
1302 fTrackReferences.Clear();
1307 // Now loop again and write the primaries
1309 for (Int_t ip = 0; ip < np; ip++) {
1310 TParticle* part = stack->Particle(ip);
1311 // if ((part->GetFirstDaughter() == -1 && part->GetStatusCode() <= 1) || part->GetFirstDaughter() >= np)
1312 if (part->TestBit(kTransportBit))
1314 // Skip particles that have not been transported
1315 fTmpTreeTR->GetEntry(it--);
1316 Int_t nh = fTmpTrackReferences.GetEntries();
1318 // Loop over reference hits and find primary labels
1319 for (Int_t ih = 0; ih < nh; ih++) {
1320 AliTrackReference* tr = (AliTrackReference*) fTmpTrackReferences.At(ih);
1321 Int_t label = tr->Label();
1323 Int_t nref = fTrackReferences.GetEntriesFast();
1324 new(fTrackReferences[nref]) AliTrackReference(*tr);
1329 fTrackReferences.Clear();
1333 if (ifills != stack->GetNtrack())
1334 AliWarning(Form("Number of entries in TreeTR (%5d) unequal to TreeK (%5d) \n", ifills, stack->GetNtrack()));
1338 fTmpFileTR->Close();
1340 fTmpTrackReferences.Clear();
1341 gSystem->Exec("rm -rf TrackRefsTmp.root");