LDMX Software
simcore::SimulatorBase Class Referenceabstract

Public Member Functions

 SimulatorBase (const std::string &name, framework::Process &process)
 
void configure (framework::config::Parameters &parameters) override
 Callback for the EventProcessor to configure itself from the given set of parameters.
 
- Public Member Functions inherited from framework::Producer
 Producer (const std::string &name, Process &process)
 Class constructor.
 
virtual void process (Event &event) final
 Processing an event for a Producer is calling produce.
 
- Public Member Functions inherited from framework::EventProcessor
 DECLARE_FACTORY (EventProcessor, EventProcessor *, const std::string &, Process &)
 declare that we have a factory for this class
 
 EventProcessor (const std::string &name, Process &process)
 Class constructor.
 
virtual ~EventProcessor ()=default
 Class destructor.
 
virtual void beforeNewRun (ldmx::RunHeader &run_header)
 Callback for Producers to add parameters to the run header before conditions are initialized.
 
virtual void onNewRun (const ldmx::RunHeader &run_header)
 Callback for the EventProcessor to take any necessary action when the run being processed changes.
 
virtual void onFileOpen (EventFile &event_file)
 Callback for the EventProcessor to take any necessary action when a new event input ROOT file is opened.
 
virtual void onFileClose (EventFile &event_file)
 Callback for the EventProcessor to take any necessary action when a event input ROOT file is closed.
 
template<class T >
const T & getCondition (const std::string &condition_name)
 Access a conditions object for the current event.
 
TDirectory * getHistoDirectory ()
 Access/create a directory in the histogram file for this event processor to create histograms and analysis tuples.
 
void setStorageHint (framework::StorageControl::Hint hint)
 Mark the current event as having the given storage control hint from this module_.
 
void setStorageHint (framework::StorageControl::Hint hint, const std::string &purposeString)
 Mark the current event as having the given storage control hint from this module and the given purpose string.
 
int getLogFrequency () const
 Get the current logging frequency from the process.
 
int getRunNumber () const
 Get the run number from the process.
 
std::string getName () const
 Get the processor name.
 
void createHistograms (const std::vector< framework::config::Parameters > &histos)
 Internal function which is used to create histograms passed from the python configuration @parma histos vector of Parameters that configure histograms to create.
 

Protected Member Functions

void onProcessEnd () override
 Callback called once processing is complete.
 
void onProcessStart () override
 Initialization of simulation.
 
virtual void prepEvent (framework::Event &event)
 prepare a new event before entering into the Geant4 simulation
 
virtual void updateEventHeader (ldmx::EventHeader &eventHeader) const
 
virtual void saveTracks (framework::Event &event)
 
virtual void saveSDHits (framework::Event &event)
 
virtual void savePhotonuclearInteractions (framework::Event &event)
 
virtual void produce (framework::Event &event) override=0
 Process the event and put new data products into it.
 
- Protected Member Functions inherited from framework::EventProcessor
void abortEvent ()
 Abort the event immediately.
 

Protected Attributes

ConditionsInterface conditions_intf_
 Conditions interface.
 
G4UImanager * ui_manager_ {nullptr}
 User interface handle.
 
std::unique_ptr< RunManager > run_manager_
 Manager controlling G4 simulation run.
 
std::unique_ptr< LoggedSession > session_handle_
 Handle to the G4Session -> how to deal with G4cout and G4cerr.
 
framework::config::Parameters parameters_
 The parameters used to configure the simulation.
 
std::vector< std::string > pre_init_commands_
 
std::vector< std::string > post_init_commands_
 
- Protected Attributes inherited from framework::EventProcessor
HistogramPool histograms_
 helper object for making and filling histograms
 
NtupleManager & ntuple_ {NtupleManager::getInstance()}
 Manager for any ntuples.
 
logging::logger the_log_
 The logger for this EventProcessor.
 

Static Protected Attributes

static const std::vector< std::string > INVALID_COMMANDS
 Commands not allowed to be passed from python config file This is because Simulator already runs them.
 

Private Member Functions

void createLogging ()
 
void buildGeometry ()
 
void verifyParameters () const
 

Detailed Description

Definition at line 15 of file SimulatorBase.h.

Constructor & Destructor Documentation

◆ SimulatorBase()

simcore::SimulatorBase::SimulatorBase ( const std::string & name,
framework::Process & process )

Definition at line 24 of file SimulatorBase.cxx.

27 ui_manager_ = G4UImanager::GetUIpointer();
28}
Base class for a module which produces a data product.
virtual void process(Event &event) final
Processing an event for a Producer is calling produce.
G4UImanager * ui_manager_
User interface handle.
ConditionsInterface conditions_intf_
Conditions interface.

Member Function Documentation

◆ buildGeometry()

void simcore::SimulatorBase::buildGeometry ( )
private

Definition at line 201 of file SimulatorBase.cxx.

201 {
202 // Instantiate the GDML parser and corresponding messenger owned and
203 // managed by DetectorConstruction
204 auto parser{simcore::geo::Parser::Factory::get().make("gdml", parameters_,
206 if (not parser) {
207 EXCEPTION_RAISE(
208 "UnableToCreate",
209 "Unable to find a parser registered under the name 'gdml'.");
210 }
211 auto parser_ptr{parser.value()};
212
213 // Set the DetectorConstruction instance used to build the detector
214 // from the GDML description.
215 run_manager_->SetUserInitialization(
216 new DetectorConstruction(parser_ptr, parameters_, conditions_intf_));
217
218 // Parse the detector geometry and validate if specified.
219 auto detector_path{parameters_.get<std::string>("detector")};
220 ldmx_log(trace) << "Reading in geometry from '" << detector_path << "'";
221 G4GeometryManager::GetInstance()->OpenGeometry();
222 parser_ptr->read();
223 run_manager_->DefineWorldVolume(parser_ptr->getWorldVolume());
224}
const T & get(const std::string &name) const
Retrieve the parameter of the given name.
Definition Parameters.h:75
std::unique_ptr< RunManager > run_manager_
Manager controlling G4 simulation run.
framework::config::Parameters parameters_
The parameters used to configure the simulation.

◆ configure()

void simcore::SimulatorBase::configure ( framework::config::Parameters & parameters)
overridevirtual

Callback for the EventProcessor to configure itself from the given set of parameters.

The parameters a processor has access to are the member variables of the python class in the sequence that has class_name equal to the EventProcessor class name.

For an example, look at MyProcessor.

Parameters
parametersParameters for configuration.

Reimplemented from framework::EventProcessor.

Definition at line 130 of file SimulatorBase.cxx.

130 {
131 // parameters used to configure the simulation
132 parameters_ = parameters;
133
134 pre_init_commands_ =
135 parameters_.get<std::vector<std::string>>("pre_init_commands", {});
136
137 // Get the extra simulation configuring commands
138 post_init_commands_ =
139 parameters_.get<std::vector<std::string>>("post_init_commands", {});
140
141 verifyParameters();
142 if (run_manager_) {
143 // TODO: This won't work, need to think of a better solution
144 EXCEPTION_RAISE(
145 "MultipleSimulators",
146 "A simulator or resimulator producer has already been created. Only "
147 "one of them can be present in a given run. To run the resimulator, "
148 "use a an existing eventFile as input.");
149 }
150 // Set up logging before creating the run manager so that output from the
151 // creation of the runManager goes to the appropriate place.
152 createLogging();
153 run_manager_ = std::make_unique<RunManager>(parameters_, conditions_intf_);
154 // Instantiate the class so cascade parameters can be set.
155 // TODO: Are we actually using this?
156 G4CascadeParameters::Instance();
157
158 buildGeometry();
159 for (const std::string& cmd : pre_init_commands_) {
160 int g4_ret = ui_manager_->ApplyCommand(cmd);
161 if (g4_ret > 0) {
162 EXCEPTION_RAISE("PreInitCmd",
163 "Pre Initialization command '" + cmd +
164 "' returned a failure status from Geant4: " +
165 std::to_string(g4_ret));
166 }
167 }
168}

References framework::config::Parameters::get().

Referenced by simcore::ReSimulator::configure(), and simcore::Simulator::configure().

◆ createLogging()

void simcore::SimulatorBase::createLogging ( )
private

Definition at line 169 of file SimulatorBase.cxx.

169 {
170 auto logging_prefix = parameters_.get<std::string>("logging_prefix");
171 session_handle_ = std::make_unique<LoggedSession>(logging_prefix);
172
173 if (session_handle_ != nullptr)
174 ui_manager_->SetCoutDestination(session_handle_.get());
175}
std::unique_ptr< LoggedSession > session_handle_
Handle to the G4Session -> how to deal with G4cout and G4cerr.

◆ onProcessEnd()

void simcore::SimulatorBase::onProcessEnd ( )
overrideprotectedvirtual

Callback called once processing is complete.

Reimplemented from framework::EventProcessor.

Definition at line 52 of file SimulatorBase.cxx.

52 {
53 run_manager_->TerminateEventLoop();
54 run_manager_->RunTermination();
55 // Delete Run Manager
56 // From Geant4 Basic Example B01:
57 // Job termination
58 // Free the store: user actions, physics list and detector descriptions
59 // are owned and deleted by the run manager, so they should not be
60 // deleted in the main() program
61 // This needs to happen here because otherwise, Geant4 objects are deleted
62 // twice:
63 // 1. When the histogram file is closed (all ROOT objects created during
64 // processing are put there because ROOT)
65 // 2. When Simulator is deleted because run_manager_ is a unique_ptr
66 run_manager_.reset(nullptr);
67
68 // Delete the G4UIsession
69 // I don't think this needs to happen here, but since we are cleaning up
70 // loose ends...
71 session_handle_.reset(nullptr);
72};

Referenced by simcore::Simulator::onProcessEnd().

◆ onProcessStart()

void simcore::SimulatorBase::onProcessStart ( )
overrideprotectedvirtual

Initialization of simulation.

This uses the parameters set in the configure method to construct and initialize the simulation objects.

This function runs the post init setup commands.

Reimplemented from framework::EventProcessor.

Definition at line 73 of file SimulatorBase.cxx.

73 {
74 // initialize run
75 run_manager_->Initialize();
76
77 for (const std::string& cmd : post_init_commands_) {
78 int g4_ret = ui_manager_->ApplyCommand(cmd);
79 if (g4_ret > 0) {
80 EXCEPTION_RAISE("PostInitCmd",
81 "Post Initialization command '" + cmd +
82 "' returned a failue status from Geant4: " +
83 std::to_string(g4_ret));
84 }
85 }
86
87 // Instantiate the scoring worlds including any parallel worlds.
88 run_manager_->ConstructScoringWorlds();
89
90 // Initialize the current run
91 run_manager_->RunInitialization();
92
93 // Initialize the event processing
94 run_manager_->InitializeEventLoop(1);
95
96 return;
97}

◆ prepEvent()

void simcore::SimulatorBase::prepEvent ( framework::Event & event)
protectedvirtual

prepare a new event before entering into the Geant4 simulation

right now, we just make sure the PrimaryVertices are all prepared

Definition at line 29 of file SimulatorBase.cxx.

29 {
31 PrimaryGenerator::Factory::get().apply(
32 [&event](auto gen) { gen->prepEvent(event); });
33}

Referenced by simcore::ReSimulator::produce(), and simcore::Simulator::produce().

◆ produce()

virtual void simcore::SimulatorBase::produce ( framework::Event & event)
overrideprotectedpure virtual

Process the event and put new data products into it.

Parameters
eventThe Event to process.

Implements framework::Producer.

Implemented in simcore::ReSimulator, and simcore::Simulator.

◆ savePhotonuclearInteractions()

void simcore::SimulatorBase::savePhotonuclearInteractions ( framework::Event & event)
protectedvirtual

Definition at line 190 of file SimulatorBase.cxx.

190 {
191 // Save photonuclear interactions if the PhotonuclearTracker is active
192 auto pn_tracker = PhotonuclearTracker::get();
193 if (pn_tracker) {
194 auto pn_interactions = pn_tracker->getInteractions();
195 if (!pn_interactions.empty()) {
196 event.add("PhotonuclearInteractions", pn_interactions);
197 }
198 }
199}
static PhotonuclearTracker * get()
Get the current PhotonuclearTracker instance.

◆ saveSDHits()

void simcore::SimulatorBase::saveSDHits ( framework::Event & event)
protectedvirtual

Definition at line 182 of file SimulatorBase.cxx.

182 {
183 // Copy hit objects from SD hit collections into the output event.
184 SensitiveDetector::Factory::get().apply([&event](auto sd) {
185 sd->saveHits(event);
186 sd->onFinishedEvent();
187 });
188}

◆ saveTracks()

void simcore::SimulatorBase::saveTracks ( framework::Event & event)
protectedvirtual

Definition at line 177 of file SimulatorBase.cxx.

177 {
178 TrackMap& tracks{g4user::TrackingAction::get()->getTrackMap()};
179 tracks.traceAncestry();
180 event.add("SimParticles", tracks.getParticleMap());
181}
TrackMap & getTrackMap()
Get a handle to the current TrackMap for the event.
static TrackingAction * get()
Get a pointer to the current UserTrackingAction from the G4RunManager.

◆ updateEventHeader()

void simcore::SimulatorBase::updateEventHeader ( ldmx::EventHeader & eventHeader) const
protectedvirtual

Definition at line 34 of file SimulatorBase.cxx.

34 {
35 auto event_info = static_cast<UserEventInformation*>(
36 run_manager_->GetCurrentEvent()->GetUserInformation());
37
38 eventHeader.setWeight(event_info->getWeight());
39 eventHeader.setFloatParameter("total_photonuclear_energy",
40 event_info->getPNEnergy());
41 eventHeader.setFloatParameter("total_electronuclear_energy",
42 event_info->getENEnergy());
43 eventHeader.setFloatParameter("db_material_z",
44 event_info->getDarkBremMaterialZ());
45 eventHeader.setFloatParameter("aprime_conversion_material_z",
46 event_info->getAPrimeConversionMaterialZ());
47 eventHeader.setIntParameter("pn_target_z", event_info->getPNTargetZ());
48 eventHeader.setIntParameter("pn_target_a", event_info->getPNTargetA());
49 eventHeader.setIntParameter("pn_resample_count",
50 event_info->getPNResampleCount());
51}
void setIntParameter(const std::string &name, int value)
Set an int parameter value.
void setWeight(double weight)
Set the event weight.
void setFloatParameter(const std::string &name, float value)
Set a float parameter value.

◆ verifyParameters()

void simcore::SimulatorBase::verifyParameters ( ) const
private

Definition at line 98 of file SimulatorBase.cxx.

98 {
99 // in past versions of SimCore, the run number for the simulation was
100 // passed directly to the simulator class rather than pulled from central
101 // framework. This is here to prevent the user from accidentally using the
102 // old style.
103 if (parameters_.exists("runNumber")) {
104 EXCEPTION_RAISE("InvalidParam",
105 "Remove old-style of setting the simulation run number "
106 "(sim.runNumber)."
107 " Replace with using the Process object (p.run).");
108 }
109 // Looks for sub-strings matching the ones listed as an invalid command.
110 // These invalid commands are mostly commands where control has been handed
111 // over to Simulator.
112 for (const auto& invalid_command : INVALID_COMMANDS) {
113 for (const auto& cmd : pre_init_commands_) {
114 if (cmd.find(invalid_command) != std::string::npos) {
115 EXCEPTION_RAISE("PreInitCmd", "Pre Initialization command '" + cmd +
116 "' is not allowed because another "
117 "part of Simulator handles it.");
118 }
119 }
120 for (const auto& cmd : post_init_commands_) {
121 if (cmd.find(invalid_command) != std::string::npos) {
122 EXCEPTION_RAISE("PostInitCmd", "Post Initialization command '" + cmd +
123 "' is not allowed because another "
124 "part of Simulator handles it.");
125 }
126 }
127 }
128}
bool exists(const std::string &name) const
Check to see if a parameter exists.
Definition Parameters.h:60
static const std::vector< std::string > INVALID_COMMANDS
Commands not allowed to be passed from python config file This is because Simulator already runs them...

Member Data Documentation

◆ conditions_intf_

ConditionsInterface simcore::SimulatorBase::conditions_intf_
protected

Conditions interface.

Definition at line 34 of file SimulatorBase.h.

◆ INVALID_COMMANDS

const std::vector< std::string > simcore::SimulatorBase::INVALID_COMMANDS
staticprotected
Initial value:
= {
"/run/initialize",
"/run/beamOn",
"/random/setSeeds",
"ldmx",
"/persistency/gdml/read"
}

Commands not allowed to be passed from python config file This is because Simulator already runs them.

Definition at line 47 of file SimulatorBase.h.

◆ parameters_

framework::config::Parameters simcore::SimulatorBase::parameters_
protected

The parameters used to configure the simulation.

Definition at line 53 of file SimulatorBase.h.

Referenced by simcore::Simulator::beforeNewRun().

◆ post_init_commands_

std::vector<std::string> simcore::SimulatorBase::post_init_commands_
protected

Definition at line 57 of file SimulatorBase.h.

◆ pre_init_commands_

std::vector<std::string> simcore::SimulatorBase::pre_init_commands_
protected

Definition at line 55 of file SimulatorBase.h.

◆ run_manager_

std::unique_ptr<RunManager> simcore::SimulatorBase::run_manager_
protected

Manager controlling G4 simulation run.

Definition at line 40 of file SimulatorBase.h.

Referenced by simcore::ReSimulator::produce(), and simcore::Simulator::produce().

◆ session_handle_

std::unique_ptr<LoggedSession> simcore::SimulatorBase::session_handle_
protected

Handle to the G4Session -> how to deal with G4cout and G4cerr.

Definition at line 43 of file SimulatorBase.h.

◆ ui_manager_

G4UImanager* simcore::SimulatorBase::ui_manager_ {nullptr}
protected

User interface handle.

Definition at line 37 of file SimulatorBase.h.

37{nullptr};

The documentation for this class was generated from the following files: