LDMX Software
Public Member Functions | Private Member Functions | Private Attributes | List of all members
simcore::Simulator Class Reference

Producer that runs Geant4 simulation inside of ldmx-app. More...

#include <Simulator.h>

Public Member Functions

 Simulator (const std::string &name, framework::Process &process)
 Constructor.
 
virtual ~Simulator ()=default
 Destructor.
 
void configure (framework::config::Parameters &parameters) override
 Callback for the processor to configure itself from the given set of parameters.
 
void beforeNewRun (ldmx::RunHeader &header) override
 Given a non-const reference to the new RunHeader, we can add parameters from the simulation here before the run starts.
 
void onNewRun (const ldmx::RunHeader &header) override
 Before the run starts (but after the conditions are configured) set up the random seeds for this run.
 
virtual void produce (framework::Event &event) override
 Run simulation and export results to output event.
 
void onProcessEnd () override
 Callback called once processing is complete.
 
- Public Member Functions inherited from simcore::SimulatorBase
 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.
 
- Public Member Functions inherited from framework::EventProcessor
 EventProcessor (const std::string &name, Process &process)
 Class constructor.
 
virtual ~EventProcessor ()
 Class destructor.
 
virtual void onFileOpen (EventFile &eventFile)
 Callback for the EventProcessor to take any necessary action when a new event input ROOT file is opened.
 
virtual void onFileClose (EventFile &eventFile)
 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.
 

Private Member Functions

void setSeeds (std::vector< int > seeds)
 Set the seeds to be used by the Geant4 random engine.
 

Private Attributes

int numEventsBegan_ {0}
 Number of events started.
 
int numEventsCompleted_ {0}
 Number of events completed.
 
int run_ {-1}
 the run number (for accessing the run header in onFileClose
 

Additional Inherited Members

- Static Public Member Functions inherited from framework::EventProcessor
static void declare (const std::string &classname, int classtype, EventProcessorMaker *)
 Internal function which is part of the PluginFactory machinery.
 
- Static Public Attributes inherited from framework::Producer
static const int CLASSTYPE {1}
 Constant used to track EventProcessor types by the PluginFactory.
 
- Protected Member Functions inherited from simcore::SimulatorBase
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)
 
- Protected Member Functions inherited from framework::EventProcessor
void abortEvent ()
 Abort the event immediately.
 
- Protected Attributes inherited from simcore::SimulatorBase
ConditionsInterface conditionsIntf_
 Conditions interface.
 
G4UImanager * uiManager_ {nullptr}
 User interface handle.
 
std::unique_ptr< RunManagerrunManager_
 Manager controlling G4 simulation run.
 
std::unique_ptr< G4UIsession > sessionHandle_
 Handle to the G4Session -> how to deal with G4cout and G4cerr.
 
int verbosity_ {1}
 Vebosity for the simulation.
 
framework::config::Parameters parameters_
 The parameters used to configure the simulation.
 
std::vector< std::string > preInitCommands_
 
std::vector< std::string > postInitCommands_
 
- Protected Attributes inherited from framework::EventProcessor
HistogramHelper histograms_
 Interface class for making and filling histograms.
 
NtupleManagerntuple_ {NtupleManager::getInstance()}
 Manager for any ntuples.
 
logging::logger theLog_
 The logger for this EventProcessor.
 
- Static Protected Attributes inherited from simcore::SimulatorBase
static const std::vector< std::string > invalidCommands_
 Commands not allowed to be passed from python config file This is because Simulator already runs them.
 

Detailed Description

Producer that runs Geant4 simulation inside of ldmx-app.

Most (if not all) of the heavy lifting is done in the classes in the Sim* modules. This producer is mainly focused on calling appropriate functions at the right time in the processing chain.

Definition at line 46 of file Simulator.h.

Constructor & Destructor Documentation

◆ Simulator()

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

Constructor.

Blank Producer constructor Constructs object that are non-configurable.

Parameters
nameName for this instance of the class.
processThe Process class assocaited with EventProcessor, provided by the Framework.

Definition at line 45 of file Simulator.cxx.

Member Function Documentation

◆ beforeNewRun()

void simcore::Simulator::beforeNewRun ( ldmx::RunHeader header)
overridevirtual

Given a non-const reference to the new RunHeader, we can add parameters from the simulation here before the run starts.

Parameters
headerof new run

Reimplemented from framework::Producer.

Definition at line 52 of file Simulator.cxx.

52 {
53 // Get the detector header from the user detector construction
54 DetectorConstruction* detector =
55 dynamic_cast<RunManager*>(RunManager::GetRunManager())
56 ->getDetectorConstruction();
57
58 header.setDetectorName(detector->getDetectorName());
59 header.setDescription(parameters_.getParameter<std::string>("description"));
60 header.setIntParameter(
61 "Included Scoring Planes",
62 !parameters_.getParameter<std::string>("scoringPlanes").empty());
63 header.setIntParameter(
64 "Use Random Seed from Event Header",
65 parameters_.getParameter<bool>("rootPrimaryGenUseSeed"));
66
67 // lambda function for dumping 3-vectors into the run header
68 auto threeVectorDump = [&header](const std::string& name,
69 const std::vector<double>& vec) {
70 header.setFloatParameter(name + " X", vec.at(0));
71 header.setFloatParameter(name + " Y", vec.at(1));
72 header.setFloatParameter(name + " Z", vec.at(2));
73 };
74
75 auto beamSpotSmear{
76 parameters_.getParameter<std::vector<double>>("beamSpotSmear", {})};
77 if (!beamSpotSmear.empty()) {
78 threeVectorDump("Smear Beam Spot [mm]", beamSpotSmear);
79 }
80
81 // lambda function for dumping vectors of strings to the run header
82 auto stringVectorDump = [&header](const std::string& name,
83 const std::vector<std::string>& vec) {
84 int index = 0;
85 for (auto const& val : vec) {
86 header.setStringParameter(name + " " + std::to_string(++index), val);
87 }
88 };
89
90 stringVectorDump("Pre Init Command",
91 parameters_.getParameter<std::vector<std::string>>(
92 "preInitCommands", {}));
93 stringVectorDump("Post Init Command",
94 parameters_.getParameter<std::vector<std::string>>(
95 "postInitCommands", {}));
96
98 [&header](auto bop) { bop->RecordConfig(header); });
99
100 int counter = 0;
101 PrimaryGenerator::Factory::get().apply([&header, &counter](auto gen) {
102 std::string gen_id = "Gen" + std::to_string(counter++);
103 gen->RecordConfig(gen_id, header);
104 });
105
106 // Set a string parameter with the Geant4 SHA-1.
107 if (G4RunManagerKernel::GetRunManagerKernel()) {
108 G4String g4Version{
109 G4RunManagerKernel::GetRunManagerKernel()->GetVersionString()};
110 header.setStringParameter("Geant4 revision", g4Version);
111 } else {
112 ldmx_log(warn) << "Unable to access G4 RunManager Kernel. Will not store "
113 "G4 Version string.";
114 }
115
116 header.setStringParameter("ldmx-sw revision", GIT_SHA1);
117}
T getParameter(const std::string &name) const
Retrieve the parameter of the given name.
Definition Parameters.h:89
void setFloatParameter(const std::string &name, float value)
Set a float parameter value.
Definition RunHeader.h:189
void setDetectorName(const std::string &det)
Set the name of the detector that was used in this run.
Definition RunHeader.h:80
void setStringParameter(const std::string &name, std::string value)
Set a string parameter value.
Definition RunHeader.h:214
void setDescription(const std::string &des)
Set the description of this run.
Definition RunHeader.h:92
void setIntParameter(const std::string &name, int value)
Set an int parameter value.
Definition RunHeader.h:164
void apply(UnaryFunction f) const
Apply the input UnaryFunction to each entry in the inventory.
Definition Factory.h:283
static Factory & get()
get the factory instance
Definition Factory.h:217
framework::config::Parameters parameters_
The parameters used to configure the simulation.

References simcore::Factory< Prototype, PrototypePtr, PrototypeConstructorArgs >::apply(), simcore::Factory< Prototype, PrototypePtr, PrototypeConstructorArgs >::get(), simcore::DetectorConstruction::getDetectorName(), framework::config::Parameters::getParameter(), simcore::SimulatorBase::parameters_, ldmx::RunHeader::setDescription(), ldmx::RunHeader::setDetectorName(), ldmx::RunHeader::setFloatParameter(), ldmx::RunHeader::setIntParameter(), and ldmx::RunHeader::setStringParameter().

◆ configure()

void simcore::Simulator::configure ( framework::config::Parameters parameters)
overridevirtual

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

Parameters
parametersParameterSet for configuration.

Reimplemented from framework::EventProcessor.

Definition at line 48 of file Simulator.cxx.

48 {
49 SimulatorBase::configure(parameters);
50}
void configure(framework::config::Parameters &parameters) override
Callback for the EventProcessor to configure itself from the given set of parameters.

References simcore::SimulatorBase::configure().

◆ onNewRun()

void simcore::Simulator::onNewRun ( const ldmx::RunHeader header)
overridevirtual

Before the run starts (but after the conditions are configured) set up the random seeds for this run.

Parameters
[in]headerRunHeader for this run, unused

Reimplemented from framework::EventProcessor.

Definition at line 119 of file Simulator.cxx.

119 {
121 getCondition<framework::RandomNumberSeedService>(
123 std::vector<int> seeds;
124 seeds.push_back(rseed.getSeed("Simulator[0]"));
125 seeds.push_back(rseed.getSeed("Simulator[1]"));
126 setSeeds(seeds);
127
128 run_ = runHeader.getRunNumber();
129}
System for consistent seeding of random number generators.
static const std::string CONDITIONS_OBJECT_NAME
Conditions object name.
uint64_t getSeed(const std::string &name) const
Access a given seed by name.
void setSeeds(std::vector< int > seeds)
Set the seeds to be used by the Geant4 random engine.
int run_
the run number (for accessing the run header in onFileClose
Definition Simulator.h:119

References framework::RandomNumberSeedService::CONDITIONS_OBJECT_NAME, ldmx::RunHeader::getRunNumber(), framework::RandomNumberSeedService::getSeed(), run_, and setSeeds().

◆ onProcessEnd()

void simcore::Simulator::onProcessEnd ( )
overridevirtual

Callback called once processing is complete.

Reimplemented from framework::EventProcessor.

Definition at line 169 of file Simulator.cxx.

169 {
171 std::cout << "[ Simulator ] : "
172 << "Started " << numEventsBegan_ << " events to produce "
173 << numEventsCompleted_ << " events." << std::endl;
174}
void onProcessEnd() override
Callback called once processing is complete.
int numEventsBegan_
Number of events started.
Definition Simulator.h:113
int numEventsCompleted_
Number of events completed.
Definition Simulator.h:116

References numEventsBegan_, numEventsCompleted_, and simcore::SimulatorBase::onProcessEnd().

◆ produce()

void simcore::Simulator::produce ( framework::Event event)
overridevirtual

Run simulation and export results to output event.

Parameters
eventThe event to process.

Implements simcore::SimulatorBase.

Definition at line 131 of file Simulator.cxx.

131 {
132 // Generate and process a Geant4 event.
134 // Save the state of the random engine to an output stream. A string
135 // is then extracted and saved to the event header.
136 std::ostringstream stream;
137 G4Random::saveFullState(stream);
138 runManager_->ProcessOneEvent(event.getEventHeader().getEventNumber());
139
140 // If a Geant4 event has been aborted, skip the rest of the processing
141 // sequence. This will immediately force the simulation to move on to
142 // the next event.
143 if (runManager_->GetCurrentEvent()->IsAborted()) {
144 runManager_->TerminateOneEvent(); // clean up event objects
146 [](auto sd) { sd->OnFinishedEvent(); });
147 this->abortEvent(); // get out of processors loop
148 }
149
150 // Terminate the event. This checks if an event is to be stored or
151 // stacked for later.
153
154 // store event-wide information in EventHeader
155 auto& event_header = event.getEventHeader();
156 updateEventHeader(event_header);
157
158 event_header.setStringParameter("eventSeed", stream.str());
159
160 saveTracks(event);
161
162 saveSDHits(event);
163
164 runManager_->TerminateOneEvent();
165
166 return;
167}
void abortEvent()
Abort the event immediately.
ldmx::EventHeader & getEventHeader()
Get the event header.
Definition Event.h:58
int getEventNumber() const
Return the event number.
Definition EventHeader.h:78
std::unique_ptr< RunManager > runManager_
Manager controlling G4 simulation run.

References framework::EventProcessor::abortEvent(), simcore::Factory< Prototype, PrototypePtr, PrototypeConstructorArgs >::apply(), simcore::Factory< Prototype, PrototypePtr, PrototypeConstructorArgs >::get(), framework::Event::getEventHeader(), ldmx::EventHeader::getEventNumber(), numEventsBegan_, numEventsCompleted_, and simcore::SimulatorBase::runManager_.

◆ setSeeds()

void simcore::Simulator::setSeeds ( std::vector< int >  seeds)
private

Set the seeds to be used by the Geant4 random engine.

Parameters
[in]seedsA vector of seeds to pass to the G4 random engine. The vector must contain at least 2 seeds otherwise an exception is thrown.

Definition at line 176 of file Simulator.cxx.

176 {
177 // If no seeds have been specified then return immediately.
178 if (seeds.empty()) {
179 return;
180 }
181
182 // If seeds are specified, make sure that the container has at least
183 // two seeds. If not, throw an exception.
184 if (seeds.size() == 1) {
185 EXCEPTION_RAISE("ConfigurationException",
186 "At least two seeds need to be specified.");
187 }
188
189 // Create the array of seeds and pass them to G4Random. Currently,
190 // only 100 seeds can be specified at a time. If less than 100
191 // seeds are specified, the remaining slots are set to 0.
192
193 constexpr int max_number_of_seeds{100};
194 std::vector<long> seedVec(max_number_of_seeds, 0);
195 for (std::size_t index{0}; index < seeds.size(); ++index) {
196 seedVec[index] = static_cast<long>(seeds[index]);
197 }
198
199 // Pass the array of seeds to the random engine.
200 G4Random::setTheSeeds(seedVec.data());
201}

Referenced by onNewRun().

Member Data Documentation

◆ numEventsBegan_

int simcore::Simulator::numEventsBegan_ {0}
private

Number of events started.

Definition at line 113 of file Simulator.h.

113{0};

Referenced by onProcessEnd(), and produce().

◆ numEventsCompleted_

int simcore::Simulator::numEventsCompleted_ {0}
private

Number of events completed.

Definition at line 116 of file Simulator.h.

116{0};

Referenced by onProcessEnd(), and produce().

◆ run_

int simcore::Simulator::run_ {-1}
private

the run number (for accessing the run header in onFileClose

Definition at line 119 of file Simulator.h.

119{-1};

Referenced by onNewRun().


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