GGS(GenericGEANT4Simulation)Software  2.99.0
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Macros
Public Member Functions | Protected Member Functions
GGSRunManagerExtensions Class Reference

Class with additional functionalities for run managers. More...

#include <GGSRunManagerExtensions.h>

Inheritance diagram for GGSRunManagerExtensions:
Inheritance graph
[legend]

Public Member Functions

 GGSRunManagerExtensions ()
 Constructor.
 
virtual ~GGSRunManagerExtensions ()=default
 Destructor. More...
 
int GetNKilledEvents ()
 Getter method for number of killed events. More...
 
void KillEvent ()
 Kills the current event. More...
 
void SimulateAgainKilledEvent ()
 Simulates again a killed event. More...
 
bool IsCurrentEventKilled ()
 Getter method for killed event flag. More...
 
const std::string & GetRandomStateAtBeginOfEvent ()
 Getter method for random engine state at the beginning of the current event. More...
 
void SetGGSGeneratorAction (G4VUserPrimaryGeneratorAction *userAction)
 Replacement of the SetUserAction method. More...
 
int GetNDiscardedEvents ()
 Getter method for number of discarded events. More...
 
const std::string & RngStateRestoredFrom ()
 The random engine state file for this event. More...
 

Protected Member Functions

void BeginOfEventProcessing ()
 Method for storing the random engine state and resetting the internal flags at the beginning event generation. More...
 
void BeginOfEventSimulation ()
 Reset the internal flags at the beginning of event simulation. More...
 
void DumpStatus (G4int eventID)
 Prints the status of the random number generator. More...
 
bool IsKilledAndToBeSimulatedAgain (const G4Event *ev)
 Checks if the event has been killed and has to be re-simulated. More...
 
void PrintLogVols ()
 Print a list of logical volumes in current geometries.
 
void HandleEventRngStateFile (int runID, int eventID)
 Handles the read/write operations to/from the random generator state file for each event. More...
 

Detailed Description

Class with additional functionalities for run managers.

This class is meant to be used to extend the interfaces of standard G4 run managers with additional GGS functionalities. The class has a virtual destructor to make it possible to obtain the GGSRunManagerExtensions interface from a a G4RunManager pointer with a dynamic_cast.

Definition at line 28 of file GGSRunManagerExtensions.h.

Constructor & Destructor Documentation

virtual GGSRunManagerExtensions::~GGSRunManagerExtensions ( )
virtualdefault

Destructor.

Declared only to make it possible to recover the GGSRunManagerExtensions interface from a G4RunManager pointer.

Member Function Documentation

void GGSRunManagerExtensions::BeginOfEventProcessing ( )
protected

Method for storing the random engine state and resetting the internal flags at the beginning event generation.

To be called in derived classes before generating the event, i.e. before calling the GenerateEvent method of the run manager class. Do not call again if the primaries are re-generated.

Definition at line 47 of file GGSRunManagerExtensions.cpp.

47  {
48  std::stringstream buffer;
49  G4Random::getTheEngine()->put(buffer);
50  _stateAtBeginOfEvent = std::move(buffer.str());
51  _nKilledEvs = 0;
52 }
void GGSRunManagerExtensions::BeginOfEventSimulation ( )
protected

Reset the internal flags at the beginning of event simulation.

To be called in derived classes before starting to process an event, i.e. before calling G4EventManager::ProcessOneEvent.

Definition at line 54 of file GGSRunManagerExtensions.cpp.

54  {
55  _isCurrEvKilled = false;
56  _simAgainKilledEv = false;
57 }
void GGSRunManagerExtensions::DumpStatus ( G4int  eventID)
protected

Prints the status of the random number generator.

To be called after generating the event and before starting to simulate it

Parameters
eventIDThe ID of the event

Definition at line 59 of file GGSRunManagerExtensions.cpp.

59  {
60  auto Indent = [](const std::string &str) {
61  std::string indentedStr;
62  size_t pos = 0;
63  while (true) {
64  auto newlinePos = str.find_first_of('\n', pos);
65  if (newlinePos != std::string::npos) {
66  indentedStr.append(" ").append(str, pos, newlinePos - pos + 1);
67  pos = newlinePos + 1;
68  } else {
69  break;
70  }
71  }
72  return indentedStr;
73  };
74 
75  if (_printModulo != 0) {
76  if (eventID % _printModulo == 0 && eventID > _lastPrinted) {
77  std::stringstream outSS, bufferSS;
78  outSS << "---> Begin of event: " << eventID << "\n";
79  outSS << "--------- " << G4Random::getTheEngine()->name() << " random engine state ---------\n";
80  if (RngStateRestoredFrom() != "") {
81  outSS << "--- Restored from: " << RngStateRestoredFrom() << "\n";
82  }
83  outSS << " State at begin of event generation:\n" << Indent(GetRandomStateAtBeginOfEvent()) << "\n";
84  outSS << " State at begin of event tracking: \n";
85  G4Random::getTheEngine()->put(bufferSS);
86  outSS << Indent(bufferSS.str());
87  outSS << "----------------------------------------\n";
88  G4cout << outSS.str() << G4endl;
89  _lastPrinted = eventID;
90  }
91  }
92 }
const std::string & GetRandomStateAtBeginOfEvent()
Getter method for random engine state at the beginning of the current event.
const std::string & RngStateRestoredFrom()
The random engine state file for this event.
int GGSRunManagerExtensions::GetNDiscardedEvents ( )

Getter method for number of discarded events.

This method returns the number of discarded events. Discarded events are events which are generated but not simulated because they do not fulfill the acceptance criterion defined by the geometry. The counter is reset every time an event is successfully generated inside acceptance and simulated (i.e. not killed). This method will always return 0 if the particle generator does not inherit from GGSGeneratorAction.

Returns
The number of discarded events since the last simulated one.

Definition at line 136 of file GGSRunManagerExtensions.cpp.

136  {
137  if (_ggsGeneratorAction) {
138  return _nDiscardedEvsInKilledEvs + _ggsGeneratorAction->GetNDiscarded();
139  }
140  return 0;
141 }
unsigned int GetNDiscarded() const
Returns the number of discarded events for the current event generation.
int GGSRunManagerExtensions::GetNKilledEvents ( )
inline

Getter method for number of killed events.

This method returns the number of killed events since the last non-killed one.

Returns
The number of killed events since the last non-killed one.

Definition at line 46 of file GGSRunManagerExtensions.h.

46 { return _nKilledEvs; }
const std::string& GGSRunManagerExtensions::GetRandomStateAtBeginOfEvent ( )
inline

Getter method for random engine state at the beginning of the current event.

Returns
an array with the numbers defining the engine state.

Definition at line 83 of file GGSRunManagerExtensions.h.

83 { return _stateAtBeginOfEvent; }
void GGSRunManagerExtensions::HandleEventRngStateFile ( int  runID,
int  eventID 
)
protected

Handles the read/write operations to/from the random generator state file for each event.

This routine reads and writes the random generator state files for each event, effectively restoring the state from file or dumping the current state to file. Read and write behavior can be toggled by the /GGS/random/saveEventRngStateToFile and /GGS/random/readEventRngStateFromFile datacard commands (notice that when reading from file is enabled then dumping to file will be automatically disabled). The path and base file name can be set by means of /GGS/random/eventRngStateFilePath and /GGS/random/eventRngStateFileBase, respectively. The effective file name for each event is built by appending the run::evt#.rndm suffix to the base name, and then using the path to obtain the absolute file name.

If the file format is bad then a fatal G4Exception is thrown.

Parameters
runIDThe ID of the current run.
eventIDThe ID of the current event.

Definition at line 153 of file GGSRunManagerExtensions.cpp.

153  {
154  _restoredFrom = "";
155  if (_saveEventRngStateToFile || _readEventRngStateFromFile) {
156 
157  const std::string fileName = _eventRandomFilePath + _eventRandomFileBase + "run" + std::to_string(runID) + "evt" +
158  std::to_string(eventID) + ".rndm";
159 
160  if (_readEventRngStateFromFile) {
161  // The different concrete random engines implement error handling in get() differently: some simply print a
162  // message on cerr, some others throw exceptions. Handle this redirecting cerr to a dummy buffer before calling
163  // get() and then check if it's empty or not (other than the usual try-catch block for eventual exceptions).
164  std::stringstream cerrDummyBuf;
165  std::streambuf *cerrBuf = std::cerr.rdbuf();
166  std::cerr.rdbuf(cerrDummyBuf.rdbuf());
167  std::ifstream stateFile(fileName);
168  if (stateFile) { // File valid and readable
169  bool error = false;
170  std::string errorMessage;
171  try {
172  G4Random::getTheEngine()->get(stateFile);
173  std::cerr.rdbuf(cerrBuf);
174  if (cerrDummyBuf.str() != "") {
175  error = true;
176  errorMessage = cerrDummyBuf.str();
177  }
178  } catch (std::exception &exc) {
179  error = true;
180  errorMessage = exc.what();
181  } catch (...) {
182  error = true;
183  errorMessage = "unknown";
184  }
185  if (error) {
186  G4Exception("GGSRunManagerExtensions::HandleEventRngStateFile", "Can't read state file",
187  G4ExceptionSeverity::FatalException,
188  (("Error when restoring the state of the random engine from file ") + fileName +
189  "\nReason: " + errorMessage)
190  .c_str());
191  } else {
192  _restoredFrom = fileName;
193  }
194  } else {
195  G4Exception("GGSRunManagerExtensions::HandleEventRngStateFile", "Missing state file",
196  G4ExceptionSeverity::FatalException,
197  (("Can't find the random engine state file ") + fileName).c_str());
198  }
199  }
200 
201  if (_saveEventRngStateToFile && !_readEventRngStateFromFile) { // If reading from file, avoid to rewrite the same
202  std::ofstream stateFile(fileName);
203  G4Random::getTheEngine()->put(stateFile);
204  }
205  }
206 }
bool GGSRunManagerExtensions::IsCurrentEventKilled ( )
inline

Getter method for killed event flag.

This method returns true if SetEventAsKilled has been called during current event.

Returns
true if the current event has been killed.

Definition at line 77 of file GGSRunManagerExtensions.h.

77 { return _isCurrEvKilled; };
bool GGSRunManagerExtensions::IsKilledAndToBeSimulatedAgain ( const G4Event *  ev)
protected

Checks if the event has been killed and has to be re-simulated.

Parameters
evthe current event.
Returns
true if the event has been killed and has to be simulated again.

Definition at line 94 of file GGSRunManagerExtensions.cpp.

94  {
95  static const char *routineName = "GGSRunManagerExtensions::IsKilledAndToBeSimulatedAgain";
96  if (_isCurrEvKilled) {
97  GGSCOUT(DEEPDEB) << "Event " << ev->GetEventID() << " has been killed. " << GGSENDL;
98  if (_ggsGeneratorAction) {
99  GGSCCOUT(DEEPDEB) << "Discarded at generation: " << _ggsGeneratorAction->GetNDiscarded()
100  << " (total: " << _nDiscardedEvsInKilledEvs << ")" << GGSENDL;
101  }
102  if (_simAgainKilledEv) {
103  GGSCCOUT(DEEPDEB) << "Will be simulated again." << GGSENDL;
104  return true;
105  }
106  } else {
107  GGSCOUT(DEEPDEB) << "Finished simulating event " << ev->GetEventID() << GGSENDL;
108  if (_ggsGeneratorAction) {
109  GGSCCOUT(DEEPDEB) << "Discarded at generation: " << _ggsGeneratorAction->GetNDiscarded()
110  << " (total: " << GetNDiscardedEvents() << ")" << GGSENDL;
111  }
112  GGSCCOUT(DEEPDEB) << "Killed: " << _nKilledEvs << GGSENDL;
113  // Reset discarded and killed event counters
114  _nDiscardedEvsInKilledEvs = 0;
115  _nKilledEvs = 0;
116  if (_simAgainKilledEv) {
117  static bool printDone = false;
118  if (!printDone) {
119  GGSCOUT(WARNING) << "Request to re-simulate an event which has not been flagged as killed. Ignoring."
120  << GGSENDL;
121  GGSCCOUT(WARNING) << "This message will be printed only once." << GGSENDL;
122  printDone = true;
123  }
124  }
125  }
126  return false;
127 }
#define GGSCCOUT(level)
Smart log utility which prints no header at the beginning of the line.
Definition: GGSSmartLog.h:126
#define GGSENDL
Definition: GGSSmartLog.h:131
int GetNDiscardedEvents()
Getter method for number of discarded events.
unsigned int GetNDiscarded() const
Returns the number of discarded events for the current event generation.
void GGSRunManagerExtensions::KillEvent ( )

Kills the current event.

This method can be called by user actions to kill an event. The difference between this method and G4EventManager::AbortCurrentEvent is that calling KillEvent and then SimulateAgainKilledEvent it is possible to simulate a new event without increasing the number of simulated events. In other words, when using KillEvent and SimulateAgainKilledEvent killed events won't contribute to the count of total simulated events.

See Also
SimulateAgainKilledEvent
GetNKilledEvents

Definition at line 35 of file GGSRunManagerExtensions.cpp.

35  {
36  static const std::string routineName("GGSRunManager::KillEvent");
37  if (!_isCurrEvKilled) {
38  GGSCOUT(DEEPDEB) << "Kill event" << std::endl;
39  G4EventManager::GetEventManager()->AbortCurrentEvent();
40  _isCurrEvKilled = true;
41  _nKilledEvs++;
42  if (_ggsGeneratorAction)
43  _nDiscardedEvsInKilledEvs += _ggsGeneratorAction->GetNDiscarded();
44  }
45 }
unsigned int GetNDiscarded() const
Returns the number of discarded events for the current event generation.
const std::string& GGSRunManagerExtensions::RngStateRestoredFrom ( )
inline

The random engine state file for this event.

Returns the name of the file from which the random engine state for the current event has been restored.

Returns
The name of the file used to restore the random engine state, or an empty string if the state was not restored from file.

Definition at line 124 of file GGSRunManagerExtensions.h.

124 { return _restoredFrom; }
void GGSRunManagerExtensions::SetGGSGeneratorAction ( G4VUserPrimaryGeneratorAction *  userAction)

Replacement of the SetUserAction method.

This version checks whether the generator action inherits from GGSGeneratorAction and then registers it in the parent G4RunManager. The GGSGeneratorAction can then be retrieved by means of the GetGGSGeneratorAction method.

Note: use this method to register a generator action inheriting from GGSGeneratorAction (instead of the standard SetUserAction method) to take advantage of the mechanism to avoid dynamic_cast described in GetGGSGeneratorAction; that mechanism will not work if SetUserAction is used to register the generator action in the run manager, but all other functionalities will not be affected.

Parameters
userActionThe user defined primary generator action.

Definition at line 129 of file GGSRunManagerExtensions.cpp.

129  {
130  // dynamic_cast to references to throw exceptions in case of errors
131  _ggsGeneratorAction = &(dynamic_cast<GGSGeneratorAction &>(*userAction));
132  auto &rmExt = dynamic_cast<G4RunManager &>(*this);
133  rmExt.SetUserAction(userAction);
134 }
Base class for GGS generator actions.
void GGSRunManagerExtensions::SimulateAgainKilledEvent ( )
inline

Simulates again a killed event.

This method must be called by user actions after killing an event if the killed event has to be re-generated and re-simulated. The method #SetEventAsKilled must be called before, in order to enable re-generation and simulation, otherwise a warning message is displayed and the event is not re-generated and simulated.

Definition at line 68 of file GGSRunManagerExtensions.h.

68 { _simAgainKilledEv = true; };

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