LDMX Software
Public Member Functions | Protected Member Functions | Protected Attributes | Static Protected Attributes | Private Member Functions | List of all members
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 beforeNewRun (ldmx::RunHeader &header)
 Handle allowing producers to modify run headers before the run begins.
 
- Public Member Functions inherited from framework::EventProcessor
 EventProcessor (const std::string &name, Process &process)
 Class constructor.
 
virtual ~EventProcessor ()
 Class destructor.
 
virtual void onNewRun (const ldmx::RunHeader &runHeader)
 Callback for the EventProcessor to take any necessary action when the run being processed changes.
 
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.
 

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

static const std::vector< std::string > invalidCommands_
 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
 

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.
 

Detailed Description

Definition at line 22 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.

15 : framework::Producer(name, process), conditionsIntf_(this) {
16 uiManager_ = G4UImanager::GetUIpointer();
17}
Base class for a module which produces a data product.
G4UImanager * uiManager_
User interface handle.
ConditionsInterface conditionsIntf_
Conditions interface.

Member Function Documentation

◆ buildGeometry()

void simcore::SimulatorBase::buildGeometry ( )
private

Definition at line 178 of file SimulatorBase.cxx.

178 {
179 // Instantiate the GDML parser and corresponding messenger owned and
180 // managed by DetectorConstruction
182 "gdml", parameters_, conditionsIntf_)};
183
184 // Set the DetectorConstruction instance used to build the detector
185 // from the GDML description.
186 runManager_->SetUserInitialization(
187 new DetectorConstruction(parser, parameters_, conditionsIntf_));
188
189 // Parse the detector geometry and validate if specified.
190 auto detectorPath{parameters_.getParameter<std::string>("detector")};
191 if (verbosity_ > 0) {
192 std::cout << "[ Simulator ] : Reading in geometry from '" << detectorPath
193 << "'... " << std::flush;
194 }
195 G4GeometryManager::GetInstance()->OpenGeometry();
196 parser->read();
197 runManager_->DefineWorldVolume(parser->GetWorldVolume());
198}
T getParameter(const std::string &name) const
Retrieve the parameter of the given name.
Definition Parameters.h:89
std::unique_ptr< RunManager > runManager_
Manager controlling G4 simulation run.
int verbosity_
Vebosity for the simulation.
framework::config::Parameters parameters_
The parameters used to configure the simulation.
Parser * createParser(const std::string &name, framework::config::Parameters &parameters, simcore::ConditionsInterface &ci)
Create an instance of the parser of the given type.
static ParserFactory & getInstance()
Get the instance to this factory.

◆ 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 className equal to the EventProcessor class name.

For an example, look at MyProcessor.

Parameters
parametersParameters for configuration.

Reimplemented from framework::EventProcessor.

Definition at line 108 of file SimulatorBase.cxx.

108 {
109 // parameters used to configure the simulation
110 parameters_ = parameters;
111 // Set the verbosity level. The default level is 0.
112 verbosity_ = parameters_.getParameter<int>("verbosity");
113
114 preInitCommands_ =
115 parameters_.getParameter<std::vector<std::string>>("preInitCommands", {});
116
117 // Get the extra simulation configuring commands
118 postInitCommands_ = parameters_.getParameter<std::vector<std::string>>(
119 "postInitCommands", {});
120
121 verifyParameters();
122 if (runManager_) {
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 runManager_ = std::make_unique<RunManager>(parameters_, conditionsIntf_);
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 : preInitCommands_) {
140 int g4Ret = uiManager_->ApplyCommand(cmd);
141 if (g4Ret > 0) {
142 EXCEPTION_RAISE("PreInitCmd",
143 "Pre Initialization command '" + cmd +
144 "' returned a failure status from Geant4: " +
145 std::to_string(g4Ret));
146 }
147 }
148}

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

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

◆ createLogging()

void simcore::SimulatorBase::createLogging ( )
private

Definition at line 150 of file SimulatorBase.cxx.

150 {
151 auto loggingPrefix = parameters_.getParameter<std::string>("logging_prefix");
152 if (verbosity_ == 0)
153 sessionHandle_ = std::make_unique<BatchSession>();
154 else if (verbosity_ > 1) {
155 if (loggingPrefix.empty())
156 sessionHandle_ = std::make_unique<LoggedSession>();
157 else
158 sessionHandle_ = std::make_unique<LoggedSession>(
159 loggingPrefix + "_G4cout.log", loggingPrefix + "_G4cerr.log");
160 }
161 if (sessionHandle_ != nullptr)
162 uiManager_->SetCoutDestination(sessionHandle_.get());
163}
std::unique_ptr< G4UIsession > sessionHandle_
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 30 of file SimulatorBase.cxx.

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

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

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

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

170 {
171 // Copy hit objects from SD hit collections into the output event.
172 SensitiveDetector::Factory::get().apply([&event](auto sd) {
173 sd->saveHits(event);
174 sd->OnFinishedEvent();
175 });
176}
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

◆ saveTracks()

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

Definition at line 165 of file SimulatorBase.cxx.

165 {
166 TrackMap& tracks{g4user::TrackingAction::get()->getTrackMap()};
167 tracks.traceAncestry();
168 event.add("SimParticles", tracks.getParticleMap());
169}
void traceAncestry()
Trace the ancestry for the particles that will be stored.
Definition TrackMap.cxx:110
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 runManager_->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}
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 76 of file SimulatorBase.cxx.

76 {
77 // in past versions of SimCore, the run number for the simulation was
78 // passed directly to the simulator class rather than pulled from central
79 // framework. This is here to prevent the user from accidentally using the
80 // old style.
81 if (parameters_.exists("runNumber")) {
82 EXCEPTION_RAISE("InvalidParam",
83 "Remove old-style of setting the simulation run number "
84 "(sim.runNumber)."
85 " Replace with using the Process object (p.run).");
86 }
87 // Looks for sub-strings matching the ones listed as an invalid command.
88 // These invalid commands are mostly commands where control has been handed
89 // over to Simulator.
90 for (const auto& invalidCommand : invalidCommands_) {
91 for (const auto& cmd : preInitCommands_) {
92 if (cmd.find(invalidCommand) != std::string::npos) {
93 EXCEPTION_RAISE("PreInitCmd", "Pre Initialization command '" + cmd +
94 "' is not allowed because another "
95 "part of Simulator handles it.");
96 }
97 }
98 for (const auto& cmd : postInitCommands_) {
99 if (cmd.find(invalidCommand) != std::string::npos) {
100 EXCEPTION_RAISE("PostInitCmd", "Post Initialization command '" + cmd +
101 "' is not allowed because another "
102 "part of Simulator handles it.");
103 }
104 }
105 }
106}
bool exists(const std::string &name) const
Check to see if a parameter exists.
Definition Parameters.h:71
static const std::vector< std::string > invalidCommands_
Commands not allowed to be passed from python config file This is because Simulator already runs them...

Member Data Documentation

◆ conditionsIntf_

ConditionsInterface simcore::SimulatorBase::conditionsIntf_
protected

Conditions interface.

Definition at line 41 of file SimulatorBase.h.

◆ invalidCommands_

const std::vector< std::string > simcore::SimulatorBase::invalidCommands_
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 54 of file SimulatorBase.h.

◆ parameters_

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

The parameters used to configure the simulation.

Definition at line 63 of file SimulatorBase.h.

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

◆ postInitCommands_

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

Definition at line 67 of file SimulatorBase.h.

◆ preInitCommands_

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

Definition at line 65 of file SimulatorBase.h.

◆ runManager_

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

Manager controlling G4 simulation run.

Definition at line 47 of file SimulatorBase.h.

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

◆ sessionHandle_

std::unique_ptr<G4UIsession> simcore::SimulatorBase::sessionHandle_
protected

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

Definition at line 50 of file SimulatorBase.h.

◆ uiManager_

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

User interface handle.

Definition at line 44 of file SimulatorBase.h.

44{nullptr};

◆ verbosity_

int simcore::SimulatorBase::verbosity_ {1}
protected

Vebosity for the simulation.

Definition at line 61 of file SimulatorBase.h.

61{1};

Referenced by simcore::ReSimulator::produce().


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