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 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< RunManagerrun_manager_
 Manager controlling G4 simulation run.
 
std::unique_ptr< LoggedSessionsession_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
 
NtupleManagerntuple_ {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 24 of file SimulatorBase.h.

Constructor & Destructor Documentation

◆ SimulatorBase()

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

Definition at line 15 of file SimulatorBase.cxx.

18 ui_manager_ = G4UImanager::GetUIpointer();
19}
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 187 of file SimulatorBase.cxx.

187 {
188 // Instantiate the GDML parser and corresponding messenger owned and
189 // managed by DetectorConstruction
190 auto parser{simcore::geo::Parser::Factory::get().make("gdml", parameters_,
192 if (not parser) {
193 EXCEPTION_RAISE(
194 "UnableToCreate",
195 "Unable to find a parser registered under the name 'gdml'.");
196 }
197 auto parser_ptr{parser.value()};
198
199 // Set the DetectorConstruction instance used to build the detector
200 // from the GDML description.
201 run_manager_->SetUserInitialization(
202 new DetectorConstruction(parser_ptr, parameters_, conditions_intf_));
203
204 // Parse the detector geometry and validate if specified.
205 auto detector_path{parameters_.get<std::string>("detector")};
206 ldmx_log(trace) << "Reading in geometry from '" << detector_path << "'";
207 G4GeometryManager::GetInstance()->OpenGeometry();
208 parser_ptr->read();
209 run_manager_->DefineWorldVolume(parser_ptr->getWorldVolume());
210}
const T & get(const std::string &name) const
Retrieve the parameter of the given name.
Definition Parameters.h:78
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 116 of file SimulatorBase.cxx.

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

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

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

◆ createLogging()

void simcore::SimulatorBase::createLogging ( )
private

Definition at line 155 of file SimulatorBase.cxx.

155 {
156 auto logging_prefix = parameters_.get<std::string>("logging_prefix");
157 session_handle_ = std::make_unique<LoggedSession>(logging_prefix);
158
159 if (session_handle_ != nullptr)
160 ui_manager_->SetCoutDestination(session_handle_.get());
161}
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 38 of file SimulatorBase.cxx.

38 {
39 run_manager_->TerminateEventLoop();
40 run_manager_->RunTermination();
41 // Delete Run Manager
42 // From Geant4 Basic Example B01:
43 // Job termination
44 // Free the store: user actions, physics list and detector descriptions
45 // are owned and deleted by the run manager, so they should not be
46 // deleted in the main() program
47 // This needs to happen here because otherwise, Geant4 objects are deleted
48 // twice:
49 // 1. When the histogram file is closed (all ROOT objects created during
50 // processing are put there because ROOT)
51 // 2. When Simulator is deleted because run_manager_ is a unique_ptr
52 run_manager_.reset(nullptr);
53
54 // Delete the G4UIsession
55 // I don't think this needs to happen here, but since we are cleaning up
56 // loose ends...
57 session_handle_.reset(nullptr);
58};

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 59 of file SimulatorBase.cxx.

59 {
60 // initialize run
61 run_manager_->Initialize();
62
63 for (const std::string& cmd : post_init_commands_) {
64 int g4_ret = ui_manager_->ApplyCommand(cmd);
65 if (g4_ret > 0) {
66 EXCEPTION_RAISE("PostInitCmd",
67 "Post Initialization command '" + cmd +
68 "' returned a failue status from Geant4: " +
69 std::to_string(g4_ret));
70 }
71 }
72
73 // Instantiate the scoring worlds including any parallel worlds.
74 run_manager_->ConstructScoringWorlds();
75
76 // Initialize the current run
77 run_manager_->RunInitialization();
78
79 // Initialize the event processing
80 run_manager_->InitializeEventLoop(1);
81
82 return;
83}

◆ 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 176 of file SimulatorBase.cxx.

176 {
177 // Save photonuclear interactions if the PhotonuclearTracker is active
178 auto pn_tracker = PhotonuclearTracker::get();
179 if (pn_tracker) {
180 auto pn_interactions = pn_tracker->getInteractions();
181 if (!pn_interactions.empty()) {
182 event.add("PhotonuclearInteractions", pn_interactions);
183 }
184 }
185}
static PhotonuclearTracker * get()
Get the current PhotonuclearTracker instance.

◆ saveSDHits()

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

Definition at line 168 of file SimulatorBase.cxx.

168 {
169 // Copy hit objects from SD hit collections into the output event.
170 SensitiveDetector::Factory::get().apply([&event](auto sd) {
171 sd->saveHits(event);
172 sd->onFinishedEvent();
173 });
174}

◆ saveTracks()

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

Definition at line 163 of file SimulatorBase.cxx.

163 {
164 TrackMap& tracks{g4user::TrackingAction::get()->getTrackMap()};
165 tracks.traceAncestry();
166 event.add("SimParticles", tracks.getParticleMap());
167}
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 20 of file SimulatorBase.cxx.

20 {
21 auto event_info = static_cast<UserEventInformation*>(
22 run_manager_->GetCurrentEvent()->GetUserInformation());
23
24 eventHeader.setWeight(event_info->getWeight());
25 eventHeader.setFloatParameter("total_photonuclear_energy",
26 event_info->getPNEnergy());
27 eventHeader.setFloatParameter("total_electronuclear_energy",
28 event_info->getENEnergy());
29 eventHeader.setFloatParameter("db_material_z",
30 event_info->getDarkBremMaterialZ());
31 eventHeader.setFloatParameter("aprime_conversion_material_z",
32 event_info->getAPrimeConversionMaterialZ());
33 eventHeader.setIntParameter("pn_target_z", event_info->getPNTargetZ());
34 eventHeader.setIntParameter("pn_target_a", event_info->getPNTargetA());
35 eventHeader.setIntParameter("pn_resample_count",
36 event_info->getPNResampleCount());
37}
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 84 of file SimulatorBase.cxx.

84 {
85 // in past versions of SimCore, the run number for the simulation was
86 // passed directly to the simulator class rather than pulled from central
87 // framework. This is here to prevent the user from accidentally using the
88 // old style.
89 if (parameters_.exists("runNumber")) {
90 EXCEPTION_RAISE("InvalidParam",
91 "Remove old-style of setting the simulation run number "
92 "(sim.runNumber)."
93 " Replace with using the Process object (p.run).");
94 }
95 // Looks for sub-strings matching the ones listed as an invalid command.
96 // These invalid commands are mostly commands where control has been handed
97 // over to Simulator.
98 for (const auto& invalid_command : INVALID_COMMANDS) {
99 for (const auto& cmd : pre_init_commands_) {
100 if (cmd.find(invalid_command) != std::string::npos) {
101 EXCEPTION_RAISE("PreInitCmd", "Pre Initialization command '" + cmd +
102 "' is not allowed because another "
103 "part of Simulator handles it.");
104 }
105 }
106 for (const auto& cmd : post_init_commands_) {
107 if (cmd.find(invalid_command) != std::string::npos) {
108 EXCEPTION_RAISE("PostInitCmd", "Post Initialization command '" + cmd +
109 "' is not allowed because another "
110 "part of Simulator handles it.");
111 }
112 }
113 }
114}
bool exists(const std::string &name) const
Check to see if a parameter exists.
Definition Parameters.h:63
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 43 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 56 of file SimulatorBase.h.

◆ parameters_

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

The parameters used to configure the simulation.

Definition at line 62 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 66 of file SimulatorBase.h.

◆ pre_init_commands_

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

Definition at line 64 of file SimulatorBase.h.

◆ run_manager_

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

Manager controlling G4 simulation run.

Definition at line 49 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 52 of file SimulatorBase.h.

◆ ui_manager_

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

User interface handle.

Definition at line 46 of file SimulatorBase.h.

46{nullptr};

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