DD4hep  1.37.0
Detector Description Toolkit for High Energy Physics
Geant4Output2ROOT.cpp
Go to the documentation of this file.
1 //==========================================================================
2 // AIDA Detector description implementation
3 //--------------------------------------------------------------------------
4 // Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
5 // All rights reserved.
6 //
7 // For the licensing terms see $DD4hepINSTALL/LICENSE.
8 // For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
9 //
10 // Author : M.Frank
11 //
12 //==========================================================================
13 
14 // Framework include files
15 #include <DD4hep/Printout.h>
16 #include <DD4hep/InstanceCount.h>
18 #include <DDG4/Geant4Output2ROOT.h>
19 #include <DDG4/Geant4Particle.h>
20 #include <DDG4/Geant4Data.h>
21 
22 // Geant4 include files
23 #include <G4HCofThisEvent.hh>
24 #include <G4ParticleTable.hh>
25 #include <G4Run.hh>
26 
27 // ROOT include files
28 #include <TFile.h>
29 #include <TTree.h>
30 #include <TBranch.h>
31 #include <TSystem.h>
32 
33 using namespace dd4hep::sim;
34 
37  : Geant4OutputAction(ctxt, nam) {
38  declareProperty("Section", m_section = "EVENT");
39  declareProperty("HandleMCTruth", m_handleMCTruth);
40  declareProperty("DisabledCollections", m_disabledCollections);
41  declareProperty("DisableParticles", m_disableParticles);
42  declareProperty("FilesByRun", m_filesByRun);
44 }
45 
48  closeOutput();
50 }
51 
54  if (!m_file) return;
55  TDirectory::TContext ctxt(m_file.get());
56  info("+++ Closing ROOT output file %s", m_file->GetName());
57  m_sections.clear();
58  m_branches.clear();
59  m_tree->Write();
60  m_file->Close();
61  m_tree = nullptr;
62  m_file.reset();
63 }
64 
66 TTree* Geant4Output2ROOT::section(const std::string& nam) {
67  auto i = m_sections.find(nam);
68  if (i == m_sections.end()) {
69  TDirectory::TContext ctxt(m_file.get());
70  TTree* t = new TTree(nam.c_str(), ("Geant4 " + nam + " information").c_str());
71  m_sections.emplace(nam, t);
72  return t;
73  }
74  return i->second;
75 }
76 
78 void Geant4Output2ROOT::beginRun(const G4Run* run) {
79  std::string fname = m_output;
80  if ( m_filesByRun ) {
81  size_t idx = m_output.rfind(".");
82  if ( m_file )
83  closeOutput();
84  fname = m_output.substr(0, idx);
85  fname += _toString(run->GetRunID(), ".run%08d");
86  if ( idx != std::string::npos )
87  fname += m_output.substr(idx);
88  }
89  if ( !m_file && !fname.empty() ) {
90  TDirectory::TContext ctxt(TDirectory::CurrentDirectory());
91  if ( !gSystem->AccessPathName(fname.c_str()) ) {
92  gSystem->Unlink(fname.c_str());
93  }
94  std::unique_ptr<TFile> file(TFile::Open(fname.c_str(), "RECREATE", "dd4hep Simulation data"));
95  if ( !file ) {
96  file.reset(TFile::Open((fname+".1").c_str(), "RECREATE", "dd4hep Simulation data"));
97  }
98  if ( !file ) {
99  except("Failed to create ROOT output file:'%s'", fname.c_str());
100  }
101  if (file->IsZombie()) {
102  except("Failed to open ROOT output file:'%s'", fname.c_str());
103  }
104  m_file = std::move(file);
106  }
108 }
109 
111 int Geant4Output2ROOT::fill(const std::string& nam, const ComponentCast& type, void* ptr) {
112  if (!m_file) return 0;
113  TBranch* b = nullptr;
114  auto i = m_branches.find(nam);
115  if (i == m_branches.end()) {
116  const std::type_info& typ = type.type();
117  if (auto* cl = TBuffer::GetClass(typ)) {
118  b = m_tree->Branch(nam.c_str(), cl->GetName(), static_cast<void*>(nullptr));
119  b->SetAutoDelete(false);
120  m_branches.emplace(nam, b);
121  }
122  else {
123  throw std::runtime_error("No ROOT TClass object available for object type:" + typeName(typ));
124  }
125  }
126  else {
127  b = i->second;
128  }
129  const Long64_t evt = b->GetEntries();
130  const Long64_t nevt = b->GetTree()->GetEntries();
131  if (nevt > evt) {
132  b->SetAddress(nullptr);
133  for (Long64_t num = nevt - evt; num > 0; --num)
134  b->Fill();
135  }
136  b->SetAddress(&ptr);
137  const int nbytes = b->Fill();
138  if (nbytes < 0) {
139  throw std::runtime_error("Failed to write ROOT collection:" + nam + "!");
140  }
141  return nbytes;
142 }
143 
146  if (m_file) {
147  auto* a = m_tree->GetListOfBranches();
148  const Long64_t evt = m_tree->GetEntries() + 1;
149  const Int_t nb = a->GetEntriesFast();
151  for (Int_t i = 0; i < nb; ++i) {
152  auto* br_ptr = static_cast<TBranch*>(a->UncheckedAt(i));
153  const Long64_t br_evt = br_ptr->GetEntries();
154  if (br_evt < evt) {
155  br_ptr->SetAddress(nullptr);
156  for (Long64_t num = evt - br_evt; num > 0; --num)
157  br_ptr->Fill();
158  }
159  }
160  m_tree->SetEntries(evt);
161  }
163 }
164 
167  if (m_disableParticles) return;
168  auto* parts = context()->event().extension<Geant4ParticleMap>();
169  if (!parts) return;
170  Geant4HitWrapper::HitManipulator* manipulator = Geant4HitWrapper::manipulator<Geant4Particle>();
171  G4ParticleTable* table = G4ParticleTable::GetParticleTable();
172  const Geant4ParticleMap::ParticleMap pm = parts->particles();
173  std::vector<void*> particles;
174  particles.reserve(pm.size());
175  for ( const auto& i : pm ) {
176  auto* p = i.second;
177  G4ParticleDefinition* def = table->FindParticle(p->pdgID);
178  p->charge = static_cast<char>(3.0 * (def ? def->GetPDGCharge() : -1.0)); // Assume e-/pi-
179  particles.emplace_back(p);
180  }
181  fill("MCParticles",manipulator->vec_type,&particles);
182 }
183 
186  auto* coll = dynamic_cast<Geant4HitCollection*>(collection);
187  if (!coll) return;
188  const std::string hc_nam = collection->GetName();
189  for(const auto& n : m_disabledCollections) {
190  if ( n == hc_nam ) {
191  return;
192  }
193  }
194  const size_t nhits = coll->GetSize();
195  std::vector<void*> hits;
196  hits.reserve(nhits);
197  coll->getHitsUnchecked(hits);
198  if ( m_handleMCTruth && m_truth && nhits > 0 ) {
199  try {
200  for(size_t i=0; i<nhits; ++i) {
201  Geant4HitData* h = coll->hit(i);
202  if (auto* trk_hit = dynamic_cast<Geant4Tracker::Hit*>(h)) {
203  Geant4HitData::Contribution& t = trk_hit->truth;
205  }
206  if (auto* cal_hit = dynamic_cast<Geant4Calorimeter::Hit*>(h)) {
207  for(auto& t : cal_hit->truth)
208  t.trackID = m_truth->particleID(t.trackID);
209  }
210  }
211  }
212  catch(...) {
213  error("+++ Exception while saving collection %s.",hc_nam.c_str());
214  }
215  }
216  fill(hc_nam, coll->vector_type(), &hits);
217 }
Geant4HitCollection.h
dd4hep::sim::Geant4Output2ROOT::saveEvent
void saveEvent(OutputContext< G4Event > &ctxt) override
Callback to store the Geant4 event.
Definition: Geant4Output2ROOT.cpp:166
dd4hep::sim::Geant4HitCollection
Generic hit container class using Geant4HitWrapper objects.
Definition: Geant4HitCollection.h:201
dd4hep::_toString
std::string _toString(bool value)
String conversions: boolean value to string.
Definition: Handle.cpp:332
G4VHitsCollection
Class of the Geant4 toolkit. See http://www-geant4.kek.jp/Reference.
Definition: Geant4Classes.h:47
dd4hep::sim::Geant4OutputAction
Base class to output Geant4 event data to persistent media.
Definition: Geant4OutputAction.h:40
dd4hep::InstanceCount::increment
static void increment(T *)
Increment count according to type information.
Definition: InstanceCount.h:98
Geant4Data.h
dd4hep::sim::Geant4Context::event
Geant4Event & event() const
Access the geant4 event – valid only between BeginEvent() and EndEvent()!
Definition: Geant4Context.cpp:84
dd4hep::sim::Geant4Output2ROOT::m_handleMCTruth
bool m_handleMCTruth
Property: Flag if Monte-Carlo truth should be followed and checked.
Definition: Geant4Output2ROOT.h:58
dd4hep::sim::Geant4Output2ROOT::commit
void commit(OutputContext< G4Event > &ctxt) override
Commit data at end of filling procedure.
Definition: Geant4Output2ROOT.cpp:145
dd4hep::sim::Geant4OutputAction::OutputContext
Helper class for thread savety.
Definition: Geant4OutputAction.h:43
dd4hep::sim::Geant4ParticleMap
Data structure to map particles produced during the generation and the simulation.
Definition: Geant4Particle.h:338
dd4hep::sim::Geant4Action::info
void info(const char *fmt,...) const
Support of info messages.
Definition: Geant4Action.cpp:215
dd4hep::sim::Geant4Event::extension
T * extension(bool alert=true)
Access to type safe extension object. Exception is thrown if the object is invalid.
Definition: Geant4Context.h:151
dd4hep::sim::Geant4Output2ROOT::Geant4Output2ROOT
Geant4Output2ROOT(Geant4Context *context, const std::string &nam)
Standard constructor.
Definition: Geant4Output2ROOT.cpp:36
dd4hep::sim::Geant4Action::except
void except(const char *fmt,...) const
Support of exceptions: Print fatal message and throw runtime_error.
Definition: Geant4Action.cpp:256
dd4hep::sim::Geant4Output2ROOT::m_tree
TTree * m_tree
Reference to the event data tree (owned by m_file)
Definition: Geant4Output2ROOT.h:50
dd4hep::sim::Geant4Output2ROOT::fill
int fill(const std::string &nam, const ComponentCast &type, void *ptr)
Fill single EVENT branch entry (Geant4 collection data)
Definition: Geant4Output2ROOT.cpp:111
dd4hep::sim::Geant4OutputAction::commit
virtual void commit(OutputContext< G4Event > &ctxt)
Commit data at end of filling procedure.
Definition: Geant4OutputAction.cpp:104
dd4hep::sim::Geant4Action::error
void error(const char *fmt,...) const
Support of error messages.
Definition: Geant4Action.cpp:231
dd4hep::sim::Geant4Tracker::Hit
DDG4 tracker hit class used by the generic DDG4 tracker sensitive detector.
Definition: Geant4Data.h:263
dd4hep::sim::Geant4ParticleMap::ParticleMap
std::map< int, Particle * > ParticleMap
Definition: Geant4Particle.h:341
dd4hep::sim::Geant4HitData
Base class for geant4 hit structures used by the default DDG4 sensitive detector implementations.
Definition: Geant4Data.h:110
dd4hep::sim::Geant4OutputAction::m_truth
Geant4ParticleMap * m_truth
Reference to MC truth object.
Definition: Geant4OutputAction.h:60
dd4hep::sim::Geant4Action::declareProperty
Geant4Action & declareProperty(const std::string &nam, T &val)
Declare property.
Definition: Geant4Action.h:366
dd4hep::InstanceCount::decrement
static void decrement(T *)
Decrement count according to type information.
Definition: InstanceCount.h:102
dd4hep::sim::Geant4OutputAction::beginRun
virtual void beginRun(const G4Run *run)
Callback to initialize storing the Geant4 information.
Definition: Geant4OutputAction.cpp:108
dd4hep::sim::Geant4Output2ROOT::m_file
std::unique_ptr< TFile > m_file
Reference to the ROOT file to open.
Definition: Geant4Output2ROOT.h:48
dd4hep::sim::Geant4Output2ROOT::m_branches
Branches m_branches
Branches in the event tree.
Definition: Geant4Output2ROOT.h:46
dd4hep::sim::Geant4Calorimeter::Hit
DDG4 calorimeter hit class used by the generic DDG4 calorimeter sensitive detector.
Definition: Geant4Data.h:323
dd4hep::sim::Geant4Output2ROOT::section
TTree * section(const std::string &nam)
Create/access tree by name for non collection user data.
Definition: Geant4Output2ROOT.cpp:66
dd4hep::sim::Geant4ParticleMap::particleID
int particleID(int track, bool throw_if_not_found=true) const
Access the equivalent track id (shortcut to the usage of TrackEquivalents)
Definition: Geant4Particle.cpp:537
dd4hep::sim::Geant4HitData::MonteCarloContrib::trackID
int trackID
Geant 4 Track identifier.
Definition: Geant4Data.h:141
dd4hep::sim::Geant4HitWrapper::HitManipulator::vec_type
const ComponentCast & vec_type
Definition: Geant4HitCollection.h:73
dd4hep::sim::Geant4Output2ROOT::saveCollection
void saveCollection(OutputContext< G4Event > &ctxt, G4VHitsCollection *collection) override
Callback to store each Geant4 hit collection.
Definition: Geant4Output2ROOT.cpp:185
dd4hep::sim::Geant4Output2ROOT::m_sections
Sections m_sections
Known file sections.
Definition: Geant4Output2ROOT.h:44
dd4hep::sim::Geant4Output2ROOT::m_disabledCollections
std::vector< std::string > m_disabledCollections
Property: vector with disabled collections.
Definition: Geant4Output2ROOT.h:54
dd4hep::sim::Geant4OutputAction::m_output
std::string m_output
Property: "Output" output destination.
Definition: Geant4OutputAction.h:56
dd4hep::sim
Namespace for the Geant4 based simulation part of the AIDA detector description toolkit.
Definition: EDM4hepFileReader.cpp:46
dd4hep::sim::Geant4Output2ROOT::beginRun
void beginRun(const G4Run *run) override
Callback to store the Geant4 run information.
Definition: Geant4Output2ROOT.cpp:78
dd4hep::sim::Geant4Output2ROOT::m_section
std::string m_section
Property: name of the event tree.
Definition: Geant4Output2ROOT.h:52
dd4hep::sim::Geant4Output2ROOT::m_disableParticles
bool m_disableParticles
Property: vector with disabled collections.
Definition: Geant4Output2ROOT.h:56
dd4hep::sim::Geant4HitWrapper::HitManipulator
Generic type manipulation class for generic hit structures created in Geant4 sensitive detectors.
Definition: Geant4HitCollection.h:65
dd4hep::sim::Geant4Output2ROOT::m_filesByRun
bool m_filesByRun
Property: Flag to create a new output file for each run.
Definition: Geant4Output2ROOT.h:60
Geant4Particle.h
dd4hep::sim::Geant4HitData::MonteCarloContrib
Utility class describing the monte carlo contribution of a given particle to a hit.
Definition: Geant4Data.h:138
dd4hep::sim::Geant4Output2ROOT::closeOutput
virtual void closeOutput()
Close current output file.
Definition: Geant4Output2ROOT.cpp:53
InstanceCount.h
dd4hep::sim::Geant4Output2ROOT::~Geant4Output2ROOT
~Geant4Output2ROOT() override
Default destructor.
Definition: Geant4Output2ROOT.cpp:47
Printout.h
Geant4Output2ROOT.h
dd4hep::sim::Geant4Context
Generic context to extend user, run and event information.
Definition: Geant4Context.h:201
dd4hep::sim::Geant4Action::context
Geant4Context * context() const
Access the context.
Definition: Geant4Action.h:270