ECCE @ EIC Software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
G4RunManager.hh
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file G4RunManager.hh
1 //
2 // ********************************************************************
3 // * License and Disclaimer *
4 // * *
5 // * The Geant4 software is copyright of the Copyright Holders of *
6 // * the Geant4 Collaboration. It is provided under the terms and *
7 // * conditions of the Geant4 Software License, included in the file *
8 // * LICENSE and available at http://cern.ch/geant4/license . These *
9 // * include a list of copyright holders. *
10 // * *
11 // * Neither the authors of this software system, nor their employing *
12 // * institutes,nor the agencies providing financial support for this *
13 // * work make any representation or warranty, express or implied, *
14 // * regarding this software system or assume any liability for its *
15 // * use. Please see the license in the file LICENSE and URL above *
16 // * for the full disclaimer and the limitation of liability. *
17 // * *
18 // * This code implementation is the result of the scientific and *
19 // * technical work of the GEANT4 collaboration. *
20 // * By using, copying, modifying or distributing the software (or *
21 // * any work based on the software) you agree to acknowledge its *
22 // * use in resulting scientific publications, and indicate your *
23 // * acceptance of all terms of the Geant4 Software license. *
24 // ********************************************************************
25 //
26 //
27 //
28 //
29 
30 // class description:
31 //
32 // This is a class for run control in GEANT4
33 //
34 // For the sequential mode of Geant4 application,
35 // user must provide his own classes derived from the following
36 // three abstract classes and register them to the RunManager.
37 // G4VUserDetectorConstruction - Detector Geometry, Materials
38 // G4VUserPhysicsList - Particle types and Processes
39 // G4VUserPrimaryGeneratorAction - Event Generator selection
40 //
41 // In addition to the above mandatory classes, user can easily
42 // customize of the default functionality of GEANT4 simulation
43 // by making his own classes derived from the following 5 user
44 // action classes.
45 // G4UserRunAction - Actions for each Run
46 // G4UserEventAction - Actions for each Event
47 // G4UserStackingAction - Tracks Stacking selection
48 // G4UserTrackingAction - Actions for each Track
49 // G4UserSteppingAction - Actions for each Step
50 //
51 // User may use G4VUserActionInitialization class to instantiate
52 // any of the six user action classes (1 mandatory + 6 optional).
53 // In this case, user's concrete G4VUserActionInitialization should
54 // be defined to RunManager.
55 //
56 // For the multi-threaed mode of Geant4 application,
57 // user must provide his own classes derived from the following
58 // two abstract classes and register them to the MTRunManager.
59 // G4VUserDetectorConstruction - Detector Geometry, Materials
60 // G4VUserPhysicsList - Particle types and Processes
61 // In addition, user may optionally specify the following.
62 // G4UserWorkerInitialization - Defining thread-local actions
63 // G4UserRunAction - Actions for entire Run
64 //
65 // For the multi-threaded mode, use of G4VUserActionInitialization
66 // is mandatory.
67 // In G4VUserActionInitialization, the user has to specify
68 // G4VUserPrimaryGeneratorAction class. In addition user may
69 // customize of the default functionality of GEANT4 simulation
70 // by making his own classes derived from the following 5 user
71 // action classes.
72 // G4VUserPrimaryGeneratorAction - Event Generator selection
73 // G4UserRunAction - Actions for each tread-local Run
74 // G4UserEventAction - Actions for each Event
75 // G4UserStackingAction - Tracks Stacking selection
76 // G4UserTrackingAction - Actions for each Track
77 // G4UserSteppingAction - Actions for each Step
78 //
79 // G4RunManager is the only manager class in Geant4 kernel which
80 // the user MUST construct an object by him/herself in the main()
81 // for sequential mode of Geant4 application.
82 //
83 // In the multi-threaded mode, G4MTRunManager is the dedicated
84 // run manager which the user MUST construct an object by him/herself
85 // in the main().
86 //
87 // Note) G4WorkerRunManager is the run manager for individual
88 // thread, and is instantiated automatically, and the user needs
89 // not to take care of instantiating/deleting it.
90 //
91 // Also, G4RunManager is the only manager class in Geant4 kernel
92 // which the user CAN derive it to costomize the behavior of the
93 // run control. For this case, user should use protected methods
94 // provided in this class for procedures he/she does not want to
95 // change.
96 //
97 // G4RunManager or the derived class of it MUST be a singleton.
98 // The user MUST NOT construct more than one object even if there
99 // are two different concrete implementations.
100 //
101 // G4RunManager controls all of state changes. See G4ApplicationState.hh
102 // in intercoms category for the meanings of each state.
103 //
104 
105 #ifndef G4RunManager_h
106 #define G4RunManager_h 1
107 
108 // userAction classes
110 class G4VUserPhysicsList;
114 class G4UserRunAction;
116 class G4UserEventAction;
120 
121 class G4VPhysicalVolume;
122 class G4LogicalVolume;
123 class G4Region;
124 class G4Timer;
125 class G4RunMessenger;
126 class G4DCtable;
127 class G4Run;
129 
130 #include "G4RunManagerKernel.hh"
131 #include "G4Event.hh"
132 #include "G4EventManager.hh"
133 #include "globals.hh"
134 #include <list>
135 #include <algorithm>
136 
138 {
139  public: // with description
140  static G4RunManager* GetRunManager();
141  // Static method which returns the singleton pointer of G4RunManager or
142  // its derived class.
143  // Note this returns the per-thread singleton in case of multi-threaded
144  // build
145 
146  private:
148  //Per-thread static instance of the run manager singleton
149 
150 public: // with description
151  G4RunManager();
152 
153  virtual ~G4RunManager();
154  // The constructor and the destructor. The user must construct this class
155  // object at the beginning of his/her main() and must delete it at the
156  // bottom of the main().
157 
158  public: // with description
159  virtual void BeamOn(G4int n_event,const char* macroFile=0,G4int n_select=-1);
160  // This method starts an event loop of "n_event" events. The condition of Geant4
161  // is examined before starting the event loop. This method must be invoked at
162  // Idle state. The state will be changed to GeomClosed during the event loop and
163  // will go back to Idle when the loop is over or aborted.
164  // In case a string "macroFile" which represents the name of a macro file is given,
165  // this macro file will be executed AT THE END of each event processing. In case
166  // "n_select" is greater than zero, at the end of first "n_select" events the macro
167  // file is executed.
168  virtual void Initialize();
169  // This method invokes all the necessary initialization procedures for an event
170  // loop. This method must be invoked at the Geant4 state of PreInit or Idle. The
171  // state will be changed to Init during the initialization procedures and then
172  // changed to Idle.
173  // This method invokes two protected methods, InitializeGeometry() and
174  // InitializePhysics().
175  // After some event loops, the user can invoke this method once again. It is
176  // required if the user changes geometry, physics process, and/or cut off value.
177  // If the user forget the second invokation, G4RunManager will invoke BeamOn()
178  // method will invoke this method. (Note that this feature is not valid for the
179  // first initialization.)
180  virtual void DefineWorldVolume(G4VPhysicalVolume * worldVol,
181  G4bool topologyIsChanged=true);
182  // This method must be invoked if the geometry setup has been changed between
183  // runs. The flag 'topologyIsChanged' will specify if the geometry topology is
184  // different from the original one used in the previous run; if not, it must be
185  // set to false, so that the original optimisation and navigation history is
186  // preserved. This method is invoked also at initialisation.
188  // Resets the state of the navigator for tracking; needed for geometry updates.
189  // It forces the optimisation and navigation history to be reset.
190  virtual void AbortRun(G4bool softAbort=false);
191  // This method safely aborts the current event loop even if an event is in progress.
192  // This method is available for Geant4 states of GeomClosed and EventProc. The state
193  // will be changed to Idle, so that another event loop can be done.
194  // If softAbort is true, the event loop is aborted after processing the current
195  // event, while the current event is aborted if it is false.
196  virtual void AbortEvent();
197  // This method aborts the currently processing event, remaining events in the
198  // current event loop will be processed. This method is available only for
199  // EventProc state.
200  public: // with description
201 
202  virtual void InitializeGeometry();
203  virtual void InitializePhysics();
204  // These protected methods are invoked from Initialize() method for the
205  // initializations of geometry and physics processes. The user's concrete
206  // G4VUserDetectorConstruction class will be accessed from InitializeGeometry() and
207  // G4VUserPhysicsList class will be accessed from InitializePhysics().
208 
209  virtual G4bool ConfirmBeamOnCondition();
210  virtual void RunInitialization();
211  virtual void DoEventLoop(G4int n_event,const char* macroFile=0,G4int n_select=-1);
212  virtual void RunTermination();
213  // These four protected methods are invoked from BeamOn() method. These four methods
214  // are invoked in this order.
215  // ConfirmBeamOnCondition() method checks if all the necessary initializations have
216  // already done. If the condition is not satisfied, false is returned and the follwing
217  // three methods will be skipped.
218  // RunInitialization() method initializes a run. For example, a G4Run class object
219  // is constructed in this method.
220  // DoEventLoop() method control an event loop. Arguments are same as BeamOn() method.
221  // Inide the event loop, two following protected methods are invoked at the begining
222  // and the end of each event.
223  // RunTermination() method terminates a run processing. For example, a G4Run class
224  // object is deleted in this class. If the user uses ODBMS and wants to store the
225  // G4Run class object, he/she must override this method.
226 
227  virtual void InitializeEventLoop(G4int n_event,const char* macroFile=0,G4int n_select=-1);
228  virtual void ProcessOneEvent(G4int i_event);
229  virtual void TerminateOneEvent();
230  virtual void TerminateEventLoop();
231  // Granular virtual methods invoked from DoEventLoop() method.
232 
234  // This method is invoked from RunInitialization() to create physics tables.
235 
236  virtual G4Event* GenerateEvent(G4int i_event);
237  virtual void AnalyzeEvent(G4Event* anEvent);
238  // These two protected methods are invoked from DoEventLoop() method at the begining
239  // and the end of each event processing.
240  // GenerateEvent() method constructs a G4Event class object and invoke the user's
241  // G4VUserPrimaryGeneratorAction concrete class. If the user is using ODBMS and event
242  // objects have been created and stored in the data base, he/she must override this
243  // method.
244  // AnalyzeEvent() stores an event to a data base if a concrete G4VPersistentManager
245  // class is defined.
246 
247  public: // with description
249  // Update region list.
250  // This method is mandatory before invoking following two dump methods.
251  // At RunInitialization(), this method is automatically invoked, and thus
252  // the user needs not invoke.
253 
254  void DumpRegion(const G4String& rname) const;
255  // Dump information of a region.
256 
257  void DumpRegion(G4Region* region=0) const;
258  // Dump information of a region.
259  // If the pointer is NULL, all regions are shown.
260 
261  protected:
262  void CleanUpPreviousEvents();
263  void CleanUpUnnecessaryEvents(G4int keepNEvents);
264  void StackPreviousEvent(G4Event* anEvent);
265 
266  public:
268  protected:
269  //This constructor is called in case of Geant4 Multi-threaded build
270  G4RunManager( RMType rmType );
271 
272  protected:
275 
287 
288  private:
290 
291  protected:
297 
303 
306  std::list<G4Event*>* previousEvents;
309 
316  virtual void StoreRNGStatus(const G4String& filenamePrefix );
317 
319 
321 
328 
329  public:
330  virtual void rndmSaveThisRun();
331  virtual void rndmSaveThisEvent();
332  virtual void RestoreRandomNumberStatus(const G4String& fileN);
333 
334  public: // with description
335  //The following set user-actions and user-initialization to the kernel
336  //In MT mode, actions are shared among all threads, and should be set
337  //in the master thread, while user-actions are thread-private and each `
338  //thread has private instances. Master thread does not have user-actions
339  //except for the (optional) run-action.
340  //User should instantiate the user-actions in the action-initialization
341  //and use that class set method to set user-actions and not directly
342  //the methods provided here.
343  //Multiple Run,Event,Tracking, and Stepping actions are allowed, set
344  //multiple instances and these will be appended to the current configuration
345  //Multiple Stacking and PrimaryGeneration are not allowed
346  virtual void SetUserInitialization(G4VUserDetectorConstruction* userInit);
347  virtual void SetUserInitialization(G4VUserPhysicsList* userInit);
348  virtual void SetUserInitialization(G4VUserActionInitialization* userInit);
349  virtual void SetUserInitialization(G4UserWorkerInitialization* userInit);
351  virtual void SetUserAction(G4UserRunAction* userAction);
352  virtual void SetUserAction(G4VUserPrimaryGeneratorAction* userAction);
353  virtual void SetUserAction(G4UserEventAction* userAction);
354  virtual void SetUserAction(G4UserStackingAction* userAction);
355  virtual void SetUserAction(G4UserTrackingAction* userAction);
356  virtual void SetUserAction(G4UserSteppingAction* userAction);
357 
358  // These methods store respective user initialization and action classes.
360  { return userDetector; }
362  { return physicsList; }
364  { return userActionInitialization; }
366  { return userActionInitialization; }
368  { return userWorkerInitialization; }
371  inline const G4UserRunAction* GetUserRunAction() const
372  { return userRunAction; }
374  { return userPrimaryGeneratorAction; }
375  inline const G4UserEventAction* GetUserEventAction() const
376  { return userEventAction; }
378  { return userStackingAction; }
380  { return userTrackingAction; }
382  { return userSteppingAction; }
383  // These methods returns respective user initialization and action classes.
384 
387  // Set the number of additional (optional) waiting stacks.
388  // This method must be invoked at PreInit, Init or Idle states.
389  // Once the user set the number of additional waiting stacks,
390  // he/she can use the corresponding ENUM in G4ClassificationOfNewTrack.
391 
392  inline const G4String& GetVersionString() const
393  { return kernel->GetVersionString(); }
394 
396  { kernel->SetPrimaryTransformer(pt); }
397 
399  // if vl = 1 : status before primary particle generation is stored
400  // if vl = 2 : status before event processing (after primary particle generation) is stored
401  // if vl = 3 : both are stored
402  // if vl = 0 : none is stored (default)
403  {
406  }
409 
410  public:
411  inline void SetRandomNumberStore(G4bool flag)
412  { storeRandomNumberStatus = flag; }
414  { return storeRandomNumberStatus; }
416  {
417  G4String dirStr = dir;
418  if( dirStr(dirStr.length()-1) != '/' ) dirStr += "/";
419 #ifndef WIN32
420  G4String shellCmd = "mkdir -p ";
421 #else
422  std::replace(dirStr.begin(), dirStr.end(),'/','\\');
423  G4String shellCmd = "if not exist " + dirStr + " mkdir ";
424 #endif
425  shellCmd += dirStr;
426  randomNumberStatusDir = dirStr;
427  G4int sysret = system(shellCmd);
428  if(sysret!=0)
429  {
430  G4String errmsg = "\"" + shellCmd + "\" returns non-zero value. Directory creation failed.";
431  G4Exception("GrRunManager::SetRandomNumberStoreDir","Run0071",JustWarning,errmsg);
432  G4cerr << " return value = " << sysret << G4endl;
433  }
434  }
435  inline const G4String& GetRandomNumberStoreDir() const
436  { return randomNumberStatusDir; }
438  { return randomNumberStatusForThisRun; }
440  {
442  { G4Exception("GrRunManager::SetRandomNumberStoreDir",
443  "Run0072",JustWarning,
444  "Random number status is not available for this event."); }
446  }
448  { rngStatusEventsFlag = flag; }
450  { return rngStatusEventsFlag; }
451  public: // with description
452  void GeometryHasBeenModified(G4bool prop=true);
453  // This method must be invoked (or equivalent UI command can be used)
454  // in case the user changes his/her detector geometry after Initialize()
455  // method has been invoked. Then, at the begining of the next BeamOn(),
456  // all necessary re-voxelization will be made.
457  // The parameter "prop" has to be true if this C++ method is directly
458  // invoked.
459 
460  void ReinitializeGeometry(G4bool destroyFirst=false, G4bool prop=true);
461  // This method must be invoked (or equivalent UI command can be used)
462  // in case the user needs his/her detector construction has to be
463  // re-invoked. Re-voxelization will be also done.
464  // If the first parameter "destroyFirst" is true, G4SolidStore,
465  // G4LogicalVolumeStore and G4PhysicalVolumeStore are cleaned up, and
466  // thus all solids, logical volumes and physical volumes previously defined
467  // are deleted.
468  // The second parameter "prop" has to be true if this C++ method is directly
469  // invoked.
470 
473  // This method must be invoked (or equivalent UI command can be used)
474  // in case the user changes his/her physics process(es), e.g. (in)activate
475  // some processes. Once this method is invoked, regardless of cuts are
476  // changed or not, BuildPhysicsTable() of PhysicsList is invoked for
477  // refreshing all physics tables.
478 
479  inline void CutOffHasBeenModified()
480  {
481  G4cerr << "CutOffHasBeenModified becomes obsolete." << G4endl;
482  G4cerr << "It is safe to remove invoking this method." << G4endl;
483  }
484 
485  public: // with description
487  // This method may be used if the orientation and/or size of this
488  // particular physical volume has been modified while rest of the
489  // geometries in the world has not been changed. This avoids the
490  // full re-optimization of the entire geometry tree which is forced
491  // if GeometryHasBeenModified() method is invoked.
492 
494  // Same as above, but the mother logical volume is specified.
495 
496  public:
497  inline void SetVerboseLevel(G4int vl)
498  { verboseLevel = vl;
499  kernel->SetVerboseLevel(vl); }
500  inline G4int GetVerboseLevel() const
501  { return verboseLevel; }
503  { return printModulo; }
504  inline void SetPrintProgress(G4int i)
505  { printModulo = i; }
506 
508  {
509  if(geometryToBeOptimized != vl)
510  {
514  }
515  }
517  { return geometryToBeOptimized; }
518 
519  public: // with description
521  { n_perviousEventsToBeStored = val; }
522  // Sets the number of events to be kept after processing. That is, "val" previous
523  // events can be used with the most recent event for digitizing pileup. "val"+1
524  // previous event is deleted.
525  // This method must be invoked before starting the event loop.
526  inline const G4Run* GetCurrentRun() const
527  { return currentRun; }
528  inline G4Run* GetNonConstCurrentRun() const
529  { return currentRun; }
530  // Returns the pointer to the current run. This method is available for Geant4
531  // states of GeomClosed and EventProc.
532  inline const G4Event* GetCurrentEvent() const
533  { return currentEvent; }
534  // Returns the pointer to the current event. This method is available for EventProc
535  // state.
536  inline const G4Event* GetPreviousEvent(G4int i) const
537  {
538  if(i>=1 && i<=n_perviousEventsToBeStored)
539  {
540  std::list<G4Event*>::iterator itr = previousEvents->begin();
541  for(G4int j=1;j<i;j++) { itr++; }
542  return *itr;
543  }
544  return 0;
545  }
546  // Returns the pointer to the "i" previous event. This method is availavle for
547  // EventProc state. In case the event loop has not yet to reach to the requested
548  // event, null will be returned. To use this method, SetNumberOfEventsToBeStored()
549  // method mentioned above must be invoked previously to the event loop.
550  inline void SetRunIDCounter(G4int i)
551  { runIDCounter = i; }
552  // Set the run number counter. Initially, the counter is initialized to zero and
553  // incremented by one for every BeamOn().
554 
555  public:
557  { return nParallelWorlds; }
559  { numberOfEventToBeProcessed = val; }
561  { return numberOfEventToBeProcessed; }
563  { return n_select_msg; }
564  inline G4String GetSelectMacro() const
565  { return selectMacro; }
566  inline void SetDCtable(G4DCtable* DCtbl)
567  { DCtable = DCtbl; }
568 
569  public:
570  inline RMType GetRunManagerType() const
571  { return runManagerType; }
572 
573  protected:
575 
576  public:
577  virtual void ConstructScoringWorlds();
578  protected:
579  void UpdateScoring();
580  virtual void DeleteUserInitializations();
581  //Called by destructor to delete user detector. Note: the userdetector is shared by threads
582  //Thus this should be re-implemented to empty in derived classes that implement the worker model
583  private:
584  //disable assignment and copy constructors
586  G4RunManager& operator=(const G4RunManager&) { return *this; }
587 
588  protected:
589  // This boolean flag has to be shared by all G4RunManager objects
591  public:
593  //This is used only by workers thread to reset RNG engines from files
594  //that are event specific. Not implemented for sequential since run seed
595  //defines event seeds
596  virtual void RestoreRndmEachEvent(G4bool) { /*No effect in SEQ */ }
597  protected:
599  public:
601 };
602 
603 #endif
604