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

16 ui_manager_ = G4UImanager::GetUIpointer();
17}
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 170 of file SimulatorBase.cxx.

170 {
171 // Instantiate the GDML parser and corresponding messenger owned and
172 // managed by DetectorConstruction
173 auto parser{simcore::geo::Parser::Factory::get().make("gdml", parameters_,
175 if (not parser) {
176 EXCEPTION_RAISE(
177 "UnableToCreate",
178 "Unable to find a parser registered under the name 'gdml'.");
179 }
180 auto parser_ptr{parser.value()};
181
182 // Set the DetectorConstruction instance used to build the detector
183 // from the GDML description.
184 run_manager_->SetUserInitialization(
185 new DetectorConstruction(parser_ptr, parameters_, conditions_intf_));
186
187 // Parse the detector geometry and validate if specified.
188 auto detector_path{parameters_.get<std::string>("detector")};
189 ldmx_log(trace) << "Reading in geometry from '" << detector_path << "'";
190 G4GeometryManager::GetInstance()->OpenGeometry();
191 parser_ptr->read();
192 run_manager_->DefineWorldVolume(parser_ptr->getWorldVolume());
193}
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 110 of file SimulatorBase.cxx.

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

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

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

◆ createLogging()

void simcore::SimulatorBase::createLogging ( )
private

Definition at line 149 of file SimulatorBase.cxx.

149 {
150 auto logging_prefix = parameters_.get<std::string>("logging_prefix");
151 session_handle_ = std::make_unique<LoggedSession>(logging_prefix);
152
153 if (session_handle_ != nullptr)
154 ui_manager_->SetCoutDestination(session_handle_.get());
155}
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 32 of file SimulatorBase.cxx.

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

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

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

◆ 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.

◆ saveSDHits()

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

Definition at line 162 of file SimulatorBase.cxx.

162 {
163 // Copy hit objects from SD hit collections into the output event.
164 SensitiveDetector::Factory::get().apply([&event](auto sd) {
165 sd->saveHits(event);
166 sd->onFinishedEvent();
167 });
168}

◆ saveTracks()

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

Definition at line 157 of file SimulatorBase.cxx.

157 {
158 TrackMap& tracks{g4user::TrackingAction::get()->getTrackMap()};
159 tracks.traceAncestry();
160 event.add("SimParticles", tracks.getParticleMap());
161}
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 18 of file SimulatorBase.cxx.

18 {
19 auto event_info = static_cast<UserEventInformation*>(
20 run_manager_->GetCurrentEvent()->GetUserInformation());
21
22 eventHeader.setWeight(event_info->getWeight());
23 eventHeader.setFloatParameter("total_photonuclear_energy",
24 event_info->getPNEnergy());
25 eventHeader.setFloatParameter("total_electronuclear_energy",
26 event_info->getENEnergy());
27 eventHeader.setFloatParameter("db_material_z",
28 event_info->getDarkBremMaterialZ());
29 eventHeader.setFloatParameter("aprime_conversion_material_z",
30 event_info->getAPrimeConversionMaterialZ());
31}
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 78 of file SimulatorBase.cxx.

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