Geant4 11.2.2
Toolkit for the simulation of the passage of particles through matter
Loading...
Searching...
No Matches
G4RunManager.cc
Go to the documentation of this file.
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// G4RunManager implementation
27//
28// Original author: M.Asai, 1996
29// --------------------------------------------------------------------
30
31#include "G4RunManager.hh"
32
33#include "G4ApplicationState.hh"
34#include "G4AssemblyStore.hh"
35#include "G4CopyRandomState.hh"
36#include "G4GeometryManager.hh"
37#include "G4HCofThisEvent.hh"
38#include "G4LogicalVolume.hh"
41#include "G4Material.hh"
45#include "G4ParticleTable.hh"
47#include "G4ProcessManager.hh"
48#include "G4ProcessTable.hh"
50#include "G4Profiler.hh"
51#include "G4RegionStore.hh"
52#include "G4Run.hh"
53#include "G4RunManagerKernel.hh"
54#include "G4RunMessenger.hh"
55#include "G4SDManager.hh"
56#include "G4ScoringBox.hh"
57#include "G4ScoringCylinder.hh"
58#include "G4ScoringManager.hh"
59#include "G4SmartVoxelHeader.hh"
60#include "G4SmartVoxelStat.hh"
61#include "G4SolidStore.hh"
62#include "G4StateManager.hh"
63#include "G4TiMemory.hh"
64#include "G4Timer.hh"
66#include "G4UImanager.hh"
67#include "G4UnitsTable.hh"
68#include "G4UserRunAction.hh"
71#include "G4VHitsCollection.hh"
73#include "G4VPhysicalVolume.hh"
75#include "G4VScoringMesh.hh"
78#include "G4VUserPhysicsList.hh"
80#include "G4VVisManager.hh"
82#include "G4ios.hh"
83#include "Randomize.hh"
84
85#include <sstream>
86
87using namespace CLHEP;
88
89// The following lines are needed since G4VUserPhysicsList
90// uses a #define theParticleIterator
91#ifdef theParticleIterator
92# undef theParticleIterator
93#endif
94
95G4ThreadLocal G4RunManager* G4RunManager::fRunManager = nullptr;
96
98
99// --------------------------------------------------------------------
104
105// --------------------------------------------------------------------
107{
108 return fRunManager;
109}
110
111// --------------------------------------------------------------------
113{
114 if (fRunManager != nullptr) {
115 G4Exception("G4RunManager::G4RunManager()", "Run0031", FatalException,
116 "G4RunManager constructed twice.");
117 }
118 fRunManager = this;
119
122
123 timer = new G4Timer();
124 runMessenger = new G4RunMessenger(this);
125 previousEvents = new std::list<G4Event*>;
128 std::ostringstream oss;
129 G4Random::saveFullState(oss);
133}
134
135// --------------------------------------------------------------------
137{
138 // This version of the constructor should never be called in sequential mode!
139#ifndef G4MULTITHREADED
141 msg << "Geant4 code is compiled without multi-threading support "
142 "(-DG4MULTITHREADED is set to off).";
143 msg << " This type of RunManager can only be used in mult-threaded "
144 "applications.";
145 G4Exception("G4RunManager::G4RunManager(G4bool)", "Run0107", FatalException, msg);
146#endif
147
148 if (fRunManager != nullptr) {
149 G4Exception("G4RunManager::G4RunManager()", "Run0031", FatalException,
150 "G4RunManager constructed twice.");
151 return;
152 }
153 fRunManager = this;
154
155 switch (rmType) {
156 case masterRM:
158 break;
159 case workerRM:
161 break;
162 default:
164 msgx << "This type of RunManager can only be used in multi-threaded "
165 "applications.";
166 G4Exception("G4RunManager::G4RunManager(G4bool)", "Run0108", FatalException, msgx);
167 return;
168 }
169 runManagerType = rmType;
170
172
173 timer = new G4Timer();
174 runMessenger = new G4RunMessenger(this);
175 previousEvents = new std::list<G4Event*>;
179 std::ostringstream oss;
180 G4Random::saveFullState(oss);
184}
185
186// --------------------------------------------------------------------
188{
189 // finalise profiler before shutting down the threads
192 // set the application state to the quite state
193 if (pStateManager->GetCurrentState() != G4State_Quit) {
194 if (verboseLevel > 1) G4cout << "G4 kernel has come to Quit state." << G4endl;
195 pStateManager->SetNewState(G4State_Quit);
196 }
197
199 delete currentRun;
200 delete timer;
201 delete runMessenger;
202 delete previousEvents;
203
204 // The following will work for all RunManager types
205 // if derived class does the correct thing in the derived
206 // destructor that is: set to zero pointers of
207 // user initialization objects for which have no
208 // ownership
210 delete userRunAction;
211 userRunAction = nullptr;
212 if (verboseLevel > 1) G4cout << "UserRunAction deleted." << G4endl;
213
216 if (verboseLevel > 1) G4cout << "UserPrimaryGenerator deleted." << G4endl;
217
218 if (verboseLevel > 1) G4cout << "RunManager is deleting RunManagerKernel." << G4endl;
219
220 delete kernel;
221
222 fRunManager = nullptr;
223
224 if (verboseLevel > 1) G4cout << "RunManager is deleted." << G4endl;
225}
226
227// --------------------------------------------------------------------
229{
230 delete userDetector;
231 userDetector = nullptr;
232 if (verboseLevel > 1) G4cout << "UserDetectorConstruction deleted." << G4endl;
233
234 delete physicsList;
235 physicsList = nullptr;
236 if (verboseLevel > 1) G4cout << "UserPhysicsList deleted." << G4endl;
237
239 userActionInitialization = nullptr;
240 if (verboseLevel > 1) G4cout << "UserActionInitialization deleted." << G4endl;
241
243 userWorkerInitialization = nullptr;
244 if (verboseLevel > 1) G4cout << "UserWorkerInitialization deleted." << G4endl;
245
248 if (verboseLevel > 1) G4cout << "UserWorkerThreadInitialization deleted." << G4endl;
249}
250
251// --------------------------------------------------------------------
252void G4RunManager::BeamOn(G4int n_event, const char* macroFile, G4int n_select)
253{
254 fakeRun = n_event <= 0;
256 if (cond) {
261 DoEventLoop(n_event, macroFile, n_select);
263 }
264 fakeRun = false;
265}
266
267// --------------------------------------------------------------------
269{
271
272 G4ApplicationState currentState = stateManager->GetCurrentState();
273 if (currentState != G4State_PreInit && currentState != G4State_Idle) {
274 G4cerr << "Illegal application state - BeamOn() ignored." << G4endl;
275 return false;
276 }
277
279 G4cerr << " Geant4 kernel should be initialized" << G4endl;
280 G4cerr << "before the first BeamOn(). - BeamOn ignored." << G4endl;
281 return false;
282 }
283
285 if (verboseLevel > 0) {
286 G4cout << "Start re-initialization because " << G4endl;
287 if (!geometryInitialized) G4cout << " Geometry" << G4endl;
288 if (!physicsInitialized) G4cout << " Physics processes" << G4endl;
289 G4cout << "has been modified since last Run." << G4endl;
290 }
291 Initialize();
292 }
293 return true;
294}
295
296// --------------------------------------------------------------------
298{
299 if (!(kernel->RunInitialization(fakeRun))) return;
300
301 runAborted = false;
303
305 delete currentRun;
306 currentRun = nullptr;
307
308 if (fakeRun) return;
309
311
313 if (currentRun == nullptr) currentRun = new G4Run();
314
317
320 if (fSDM != nullptr) {
322 }
323
324 if (G4VScoreNtupleWriter::Instance() != nullptr) {
325 auto hce = (fSDM != nullptr) ? fSDM->PrepareNewEvent() : nullptr;
327 delete hce;
328 }
329
330 std::ostringstream oss;
331 G4Random::saveFullState(oss);
334
335 for (G4int i_prev = 0; i_prev < n_perviousEventsToBeStored; ++i_prev) {
336 previousEvents->push_back(nullptr);
337 }
338
339 if (printModulo >= 0 || verboseLevel > 0) {
340 G4cout << "### Run " << currentRun->GetRunID() << " starts." << G4endl;
341 }
343
344#if defined(GEANT4_USE_TIMEMORY)
345 masterRunProfiler.reset(new ProfilerConfig(currentRun));
346#endif
347
350 }
351
353 G4String fileN = "currentRun";
355 std::ostringstream os;
356 os << "run" << currentRun->GetRunID();
357 fileN = os.str();
358 }
359 StoreRNGStatus(fileN);
360 }
361}
362
363// --------------------------------------------------------------------
364void G4RunManager::DoEventLoop(G4int n_event, const char* macroFile, G4int n_select)
365{
366 InitializeEventLoop(n_event, macroFile, n_select);
367
368 // Event loop
369 for (G4int i_event = 0; i_event < n_event; ++i_event) {
370 ProcessOneEvent(i_event);
372 if (runAborted) break;
373 }
374
375 // For G4MTRunManager, TerminateEventLoop() is invoked after all threads are
376 // finished.
378}
379
380// --------------------------------------------------------------------
381void G4RunManager::InitializeEventLoop(G4int n_event, const char* macroFile, G4int n_select)
382{
383 if (verboseLevel > 0) {
384 timer->Start();
385 }
386
387 n_select_msg = n_select;
388 if (macroFile != nullptr) {
389 if (n_select_msg < 0) n_select_msg = n_event;
390 msgText = "/control/execute ";
391 msgText += macroFile;
392 selectMacro = macroFile;
393 }
394 else {
395 n_select_msg = -1;
396 selectMacro = "";
397 }
398}
399
400// --------------------------------------------------------------------
409
410// --------------------------------------------------------------------
417
418// --------------------------------------------------------------------
420{
421 if (verboseLevel > 0 && !fakeRun) {
422 timer->Stop();
423 G4cout << " Run terminated." << G4endl;
424 G4cout << "Run Summary" << G4endl;
425 if (runAborted) {
426 G4cout << " Run Aborted after " << numberOfEventProcessed << " events processed." << G4endl;
427 }
428 else {
429 G4cout << " Number of events processed : " << numberOfEventProcessed << G4endl;
430 }
431 G4cout << " " << *timer << G4endl;
432 }
434}
435
436// --------------------------------------------------------------------
438{
439 if (userPrimaryGeneratorAction == nullptr) {
440 G4Exception("G4RunManager::GenerateEvent()", "Run0032", FatalException,
441 "G4VUserPrimaryGeneratorAction is not defined!");
442 return nullptr;
443 }
444
445 auto anEvent = new G4Event(i_event);
446
448 std::ostringstream oss;
449 G4Random::saveFullState(oss);
451 anEvent->SetRandomNumberStatus(randomNumberStatusForThisEvent);
452 }
453
455 G4String fileN = "currentEvent";
457 std::ostringstream os;
458 os << "run" << currentRun->GetRunID() << "evt" << anEvent->GetEventID();
459 fileN = os.str();
460 }
461 StoreRNGStatus(fileN);
462 }
463
464 if (printModulo > 0 && anEvent->GetEventID() % printModulo == 0) {
465 G4cout << "--> Event " << anEvent->GetEventID() << " starts." << G4endl;
466 }
468 return anEvent;
469}
470
471// --------------------------------------------------------------------
473{
474 G4String fileN = randomNumberStatusDir + fnpref + ".rndm";
475 G4Random::saveEngineStatus(fileN);
476}
477
478// --------------------------------------------------------------------
480{
482 if (fPersM != nullptr) fPersM->Store(anEvent);
483 currentRun->RecordEvent(anEvent);
484}
485
486// --------------------------------------------------------------------
488{
489 if (!fakeRun) {
490#if defined(GEANT4_USE_TIMEMORY)
491 masterRunProfiler.reset();
492#endif
494 // tasking occasionally will call this function even
495 // if there was not a current run
496 if (currentRun != nullptr) {
499 if (fPersM != nullptr) fPersM->Store(currentRun);
500 // write & close analysis output
503 }
504 }
505 ++runIDCounter;
506 }
507
509}
510
511// --------------------------------------------------------------------
513{
514 // Delete all events carried over from previous run.
515 // This method is invoked at the beginning of the next run
516 // or from the destructor of G4RunManager at the very end of
517 // the program.
518 // N.B. If ToBeKept() is true, the pointer of this event is
519 // kept in G4Run of the previous run, and deleted along with
520 // the deletion of G4Run.
521
522 auto evItr = previousEvents->cbegin();
523 while (evItr != previousEvents->cend()) {
524 G4Event* evt = *evItr;
525 if (evt != nullptr && !(evt->ToBeKept())) delete evt;
526 evItr = previousEvents->erase(evItr);
527 }
528}
529
530// --------------------------------------------------------------------
532{
533 // Delete events that are no longer necessary for post
534 // processing such as visualization.
535 // N.B. If ToBeKept() is true, the pointer of this event is
536 // kept in G4Run of the previous run, and deleted along with
537 // the deletion of G4Run.
538
539 auto evItr = previousEvents->cbegin();
540 while (evItr != previousEvents->cend()) {
541 if (G4int(previousEvents->size()) <= keepNEvents) return;
542
543 G4Event* evt = *evItr;
544 if (evt != nullptr) {
545 if (evt->GetNumberOfGrips() == 0) {
546 if (!(evt->ToBeKept())) delete evt;
547 evItr = previousEvents->erase(evItr);
548 }
549 else {
550 ++evItr;
551 }
552 }
553 else {
554 evItr = previousEvents->erase(evItr);
555 }
556 }
557}
558
559// --------------------------------------------------------------------
561{
562 if (anEvent->ToBeKept()) currentRun->StoreEvent(anEvent);
563
565 if (anEvent->GetNumberOfGrips() == 0) {
566 if (!(anEvent->ToBeKept())) delete anEvent;
567 }
568 else {
569 previousEvents->push_back(anEvent);
570 }
571 }
573}
574
575// --------------------------------------------------------------------
577{
579 G4ApplicationState currentState = stateManager->GetCurrentState();
580 if (currentState != G4State_PreInit && currentState != G4State_Idle) {
581 G4cerr << "Illegal application state - "
582 << "G4RunManager::Initialize() ignored." << G4endl;
583 return;
584 }
585
586 stateManager->SetNewState(G4State_Init);
590 if (stateManager->GetCurrentState() != G4State_Idle) {
591 stateManager->SetNewState(G4State_Idle);
592 }
593}
594
595// --------------------------------------------------------------------
597{
598 if (userDetector == nullptr) {
599 G4Exception("G4RunManager::InitializeGeometry", "Run0033", FatalException,
600 "G4VUserDetectorConstruction is not defined!");
601 return;
602 }
603
604 if (verboseLevel > 1) G4cout << "userDetector->Construct() start." << G4endl;
605
607 G4ApplicationState currentState = stateManager->GetCurrentState();
608 if (currentState == G4State_PreInit || currentState == G4State_Idle) {
609 stateManager->SetNewState(G4State_Init);
610 }
617 }
618 // Notify the VisManager as well
621 if (pVVisManager != nullptr) pVVisManager->GeometryHasChanged();
622 }
623
625 geometryInitialized = true;
626 stateManager->SetNewState(currentState);
627}
628
629// --------------------------------------------------------------------
631{
633 G4ApplicationState currentState = stateManager->GetCurrentState();
634 if (currentState == G4State_PreInit || currentState == G4State_Idle) {
635 stateManager->SetNewState(G4State_Init);
636 }
637 if (physicsList != nullptr) {
639 }
640 else {
641 G4Exception("G4RunManager::InitializePhysics()", "Run0034", FatalException,
642 "G4VUserPhysicsList is not defined!");
643 }
644 physicsInitialized = true;
645 stateManager->SetNewState(currentState);
646}
647
648// --------------------------------------------------------------------
650{
651 // This method is valid only for GeomClosed or EventProc state
653 if (currentState == G4State_GeomClosed || currentState == G4State_EventProc) {
654 runAborted = true;
655 if (currentState == G4State_EventProc && !softAbort) {
658 }
659 }
660 else {
661 G4cerr << "Run is not in progress. AbortRun() ignored." << G4endl;
662 }
663}
664
665// --------------------------------------------------------------------
667{
668 // This method is valid only for EventProc state
670 if (currentState == G4State_EventProc) {
673 }
674 else {
675 G4cerr << "Event is not in progress. AbortEevnt() ignored." << G4endl;
676 }
677}
678
679// --------------------------------------------------------------------
681{
682 kernel->DefineWorldVolume(worldVol, topologyIsChanged);
683}
684
685// --------------------------------------------------------------------
687{
688 G4int runNumber = 0;
689 if (currentRun != nullptr) runNumber = currentRun->GetRunID();
691 G4cerr << "Warning from G4RunManager::rndmSaveThisRun():"
692 << " Random number status was not stored prior to this run." << G4endl
693 << "/random/setSavingFlag command must be issued. "
694 << "Command ignored." << G4endl;
695 return;
696 }
697
698 G4fs::path fileIn = randomNumberStatusDir + "currentRun.rndm";
699
700 std::ostringstream os;
701 os << "run" << runNumber << ".rndm" << '\0';
702 G4fs::path fileOut = randomNumberStatusDir + os.str();
703
704 if (G4CopyRandomState(fileIn, fileOut, "G4RunManager::rndmSaveThisRun()") && verboseLevel > 0)
705 {
706 G4cout << fileIn << " is copied to " << fileOut << G4endl;
707 }
708}
709
710// --------------------------------------------------------------------
712{
713 if (currentEvent == nullptr) {
714 G4cerr << "Warning from G4RunManager::rndmSaveThisEvent():"
715 << " there is no currentEvent available." << G4endl << "Command ignored." << G4endl;
716 return;
717 }
718
720 G4cerr << "Warning from G4RunManager::rndmSaveThisEvent():"
721 << " Random number engine status is not available." << G4endl
722 << "/random/setSavingFlag command must be issued "
723 << "prior to the start of the run. Command ignored." << G4endl;
724 return;
725 }
726
727 G4fs::path fileIn = randomNumberStatusDir + "currentEvent.rndm";
728
729 std::ostringstream os;
730 os << "run" << currentRun->GetRunID() << "evt" << currentEvent->GetEventID() << ".rndm" << '\0';
731 G4fs::path fileOut = randomNumberStatusDir + os.str();
732
733 if (G4CopyRandomState(fileIn, fileOut, "G4RunManager::rndmSaveThisEvent()") && verboseLevel > 0)
734 {
735 G4cout << fileIn << " is copied to " << fileOut << G4endl;
736 }
737}
738
739// --------------------------------------------------------------------
741{
742 G4String fileNameWithDirectory;
743 if (fileN.find('/') == std::string::npos) {
744 fileNameWithDirectory = randomNumberStatusDir + fileN;
745 }
746 else {
747 fileNameWithDirectory = fileN;
748 }
749
750 G4Random::restoreEngineStatus(fileNameWithDirectory);
751 if (verboseLevel > 0)
752 G4cout << "RandomNumberEngineStatus restored from file: " << fileNameWithDirectory << G4endl;
753 G4Random::showEngineStatus();
754}
755
756// --------------------------------------------------------------------
757void G4RunManager::DumpRegion(const G4String& rname) const
758{
759 kernel->DumpRegion(rname);
760}
761
762// --------------------------------------------------------------------
764{
765 kernel->DumpRegion(region);
766}
767
768// --------------------------------------------------------------------
770{
771 using MeshShape = G4VScoringMesh::MeshShape;
772
774 if (ScM == nullptr) return;
775
776 auto nPar = (G4int)ScM->GetNumberOfMesh();
777 if (nPar < 1) return;
778
780 for (G4int iw = 0; iw < nPar; ++iw) {
781 G4VScoringMesh* mesh = ScM->GetMesh(iw);
783 G4VPhysicalVolume* pWorld = nullptr;
784 if (mesh->GetShape() != MeshShape::realWorldLogVol) {
785 pWorld =
787 if (pWorld == nullptr) {
789 ScM->GetWorldName(iw));
790 pWorld->SetName(ScM->GetWorldName(iw));
791
792 G4ParallelWorldProcess* theParallelWorldProcess = mesh->GetParallelWorldProcess();
793 if (theParallelWorldProcess != nullptr) {
794 theParallelWorldProcess->SetParallelWorld(ScM->GetWorldName(iw));
795 }
796 else {
797 theParallelWorldProcess = new G4ParallelWorldProcess(ScM->GetWorldName(iw));
798 mesh->SetParallelWorldProcess(theParallelWorldProcess);
799 theParallelWorldProcess->SetParallelWorld(ScM->GetWorldName(iw));
800
801 theParticleIterator->reset();
802 while ((*theParticleIterator)()) {
803 G4ParticleDefinition* particle = theParticleIterator->value();
804 G4ProcessManager* pmanager = particle->GetProcessManager();
805 if (pmanager != nullptr) {
806 pmanager->AddProcess(theParallelWorldProcess);
807 if (theParallelWorldProcess->IsAtRestRequired(particle)) {
808 pmanager->SetProcessOrdering(theParallelWorldProcess, idxAtRest, 9900);
809 }
810 pmanager->SetProcessOrderingToSecond(theParallelWorldProcess, idxAlongStep);
811 pmanager->SetProcessOrdering(theParallelWorldProcess, idxPostStep, 9900);
812 }
813 }
814 }
815 theParallelWorldProcess->SetLayeredMaterialFlag(mesh->LayeredMassFlg());
816 }
817 }
818 mesh->Construct(pWorld);
819 }
821}
822
823// --------------------------------------------------------------------
825{
829 }
830
832 if (ScM == nullptr) return;
833 auto nPar = (G4int)ScM->GetNumberOfMesh();
834 if (nPar < 1) return;
835
837 if (HCE == nullptr) return;
838 auto nColl = (G4int)HCE->GetCapacity();
839 for (G4int i = 0; i < nColl; ++i) {
840 G4VHitsCollection* HC = HCE->GetHC(i);
841 if (HC != nullptr) ScM->Accumulate(HC);
842 }
843}
844
845// --------------------------------------------------------------------
847{
848 G4LogicalVolume* pMotherL = pPhys->GetMotherLogical();
849 if (pMotherL != nullptr) ReOptimize(pMotherL);
850}
851
852// --------------------------------------------------------------------
854{
855 G4Timer localtimer;
856 if (verboseLevel > 1) {
857 localtimer.Start();
858 }
859 G4SmartVoxelHeader* header = pLog->GetVoxelHeader();
860 delete header;
861 header = new G4SmartVoxelHeader(pLog);
862 pLog->SetVoxelHeader(header);
863 if (verboseLevel > 1) {
864 localtimer.Stop();
865 G4SmartVoxelStat stat(pLog, header, localtimer.GetSystemElapsed(), localtimer.GetUserElapsed());
866 G4cout << G4endl << "Voxelisation of logical volume <" << pLog->GetName() << ">" << G4endl;
867 G4cout << " heads : " << stat.GetNumberHeads() << " - nodes : " << stat.GetNumberNodes()
868 << " - pointers : " << stat.GetNumberPointers() << G4endl;
869 G4cout << " Memory used : " << (stat.GetMemoryUse() + 512) / 1024
870 << "k - total time : " << stat.GetTotalTime() << " - system time : " << stat.GetSysTime()
871 << G4endl;
872 }
873}
874
875// --------------------------------------------------------------------
880
881// --------------------------------------------------------------------
883{
884 physicsList = userInit;
885 kernel->SetPhysics(userInit);
886}
887
888// --------------------------------------------------------------------
890{
891 G4Exception("G4RunManager::SetUserInitialization()", "Run3001", FatalException,
892 "Base-class G4RunManager cannot take G4UserWorkerInitialization. Use "
893 "G4MTRunManager.");
894}
895
896// --------------------------------------------------------------------
898{
899 G4Exception("G4RunManager::SetUserThreadInitialization()", "Run3001", FatalException,
900 "Base-class G4RunManager cannot take G4UserWorkerThreadInitialization. "
901 "Use G4MTRunManager.");
902}
903
904// --------------------------------------------------------------------
910
911// --------------------------------------------------------------------
913{
914 userRunAction = userAction;
915}
916
917// --------------------------------------------------------------------
922
923// --------------------------------------------------------------------
925{
926 eventManager->SetUserAction(userAction);
927 userEventAction = userAction;
928}
929
930// --------------------------------------------------------------------
932{
933 eventManager->SetUserAction(userAction);
934 userStackingAction = userAction;
935}
936
937// --------------------------------------------------------------------
939{
940 eventManager->SetUserAction(userAction);
941 userTrackingAction = userAction;
942}
943
944// --------------------------------------------------------------------
946{
947 eventManager->SetUserAction(userAction);
948 userSteppingAction = userAction;
949}
950
951// --------------------------------------------------------------------
953{
954 if (prop) {
955 G4UImanager::GetUIpointer()->ApplyCommand("/run/geometryModified");
956 }
957 else {
959 }
960}
961
962// --------------------------------------------------------------------
964{
965 if (destroyFirst && G4Threading::IsMasterThread()) {
966 if (verboseLevel > 0) {
967 G4cout << "#### Assemblies, Volumes and Solids Stores are wiped out." << G4endl;
968 }
974
975 // remove all logical volume pointers from regions
976 // exception: world logical volume pointer must be kept
978 for (const auto& rItr : *regionStore) {
979 if (rItr->GetName() == "DefaultRegionForTheWorld") continue;
980 auto lvItr = rItr->GetRootLogicalVolumeIterator();
981 for (std::size_t iRLV = 0; iRLV < rItr->GetNumberOfRootVolumes(); ++iRLV) {
982 rItr->RemoveRootLogicalVolume(*lvItr, false);
983 ++lvItr;
984 }
985 if (verboseLevel > 0) {
986 G4cout << "#### Region <" << rItr->GetName() << "> is cleared." << G4endl;
987 }
988 }
989
990 // clear transportation manager
993 }
994 if (prop) {
995 G4UImanager::GetUIpointer()->ApplyCommand("/run/reinitializeGeometry");
996 }
997 else {
999 geometryInitialized = false;
1000 // Notify the VisManager as well
1003 if (pVVisManager != nullptr) pVVisManager->GeometryHasChanged();
1004 }
1005 }
1006}
1007
1008// --------------------------------------------------------------------
1010{
1011 std::vector<std::string> _args;
1012 for (G4int i = 0; i < argc; ++i)
1013 _args.emplace_back(argv[i]);
1014 ConfigureProfilers(_args);
1015}
1016
1017// --------------------------------------------------------------------
1018void G4RunManager::ConfigureProfilers(const std::vector<std::string>& args)
1019{
1020#ifdef GEANT4_USE_TIMEMORY
1021 // parse command line if arguments were passed
1023#else
1024 G4ConsumeParameters(args);
1025#endif
1026}
1027
1028// --------------------------------------------------------------------
1029
1030#if !defined(GEANT4_USE_TIMEMORY)
1031# define TIMEMORY_WEAK_PREFIX
1032# define TIMEMORY_WEAK_POSTFIX
1033#endif
1034
1035// --------------------------------------------------------------------
1036
1037extern "C"
1038{
1039 // this allows the default setup to be overridden by linking
1040 // in an custom extern C function into the application
1043
1044 extern void G4ProfilerInit(void);
1045
1046 // this gets executed when the library gets loaded
1048 {
1049#ifdef GEANT4_USE_TIMEMORY
1051
1052 // guard against re-initialization
1053 static G4bool _once = false;
1054 if (_once) return;
1055 _once = true;
1056
1057 puts(">>> G4RunProfilerInit <<<");
1058
1059 using RunProfilerConfig = G4ProfilerConfig<G4ProfileType::Run>;
1060 using EventProfilerConfig = G4ProfilerConfig<G4ProfileType::Event>;
1061 using TrackProfilerConfig = G4ProfilerConfig<G4ProfileType::Track>;
1062 using StepProfilerConfig = G4ProfilerConfig<G4ProfileType::Step>;
1063 using UserProfilerConfig = G4ProfilerConfig<G4ProfileType::User>;
1064
1065 //
1066 // these are the default functions for evaluating whether
1067 // to start profiling
1068 //
1069 RunProfilerConfig::GetFallbackQueryFunctor() = [](const G4Run* _run) {
1070 return G4Profiler::GetEnabled(G4ProfileType::Run) && _run;
1071 };
1072
1073 EventProfilerConfig::GetFallbackQueryFunctor() = [](const G4Event* _event) {
1074 return G4Profiler::GetEnabled(G4ProfileType::Event) && _event;
1075 };
1076
1077 TrackProfilerConfig::GetFallbackQueryFunctor() = [](const G4Track* _track) {
1078 return G4Profiler::GetEnabled(G4ProfileType::Track) && _track && _track->GetDynamicParticle();
1079 };
1080
1081 StepProfilerConfig::GetFallbackQueryFunctor() = [](const G4Step* _step) {
1082 return G4Profiler::GetEnabled(G4ProfileType::Step) && _step && _step->GetTrack();
1083 };
1084
1085 UserProfilerConfig::GetFallbackQueryFunctor() = [](const std::string& _user) {
1086 return G4Profiler::GetEnabled(G4ProfileType::User) && !_user.empty();
1087 };
1088
1089 //
1090 // these are the default functions which encode the profiling label.
1091 // Will not be called unless the query returned true
1092 //
1093 RunProfilerConfig::GetFallbackLabelFunctor() = [](const G4Run* _run) {
1094 return TIMEMORY_JOIN('/', "G4Run", _run->GetRunID());
1095 };
1096
1097 EventProfilerConfig::GetFallbackLabelFunctor() = [](const G4Event* _event) -> std::string {
1099 return TIMEMORY_JOIN('/', "G4Event", _event->GetEventID());
1100 else
1101 return "G4Event";
1102 };
1103
1104 TrackProfilerConfig::GetFallbackLabelFunctor() = [](const G4Track* _track) {
1105 auto pdef = _track->GetDynamicParticle()->GetParticleDefinition();
1106 return TIMEMORY_JOIN('/', "G4Track", pdef->GetParticleName());
1107 };
1108
1109 StepProfilerConfig::GetFallbackLabelFunctor() = [](const G4Step* _step) {
1110 auto pdef = _step->GetTrack()->GetParticleDefinition();
1111 return TIMEMORY_JOIN('/', "G4Step", pdef->GetParticleName());
1112 };
1113
1114 UserProfilerConfig::GetFallbackLabelFunctor() = [](const std::string& _user) {
1115 return _user;
1116 };
1117
1118 using RunTool = typename RunProfilerConfig::type;
1119 using EventTool = typename EventProfilerConfig::type;
1120 using TrackTool = typename TrackProfilerConfig::type;
1121 using StepTool = typename StepProfilerConfig::type;
1122 using UserTool = typename UserProfilerConfig::type;
1123
1124 RunProfilerConfig::GetFallbackToolFunctor() = [](const std::string& _label) {
1125 return new RunTool{_label};
1126 };
1127
1128 EventProfilerConfig::GetFallbackToolFunctor() = [](const std::string& _label) {
1129 return new EventTool{_label};
1130 };
1131
1132 TrackProfilerConfig::GetFallbackToolFunctor() = [](const std::string& _label) {
1133 return new TrackTool(_label, tim::scope::config(tim::scope::flat{}));
1134 };
1135
1136 StepProfilerConfig::GetFallbackToolFunctor() = [](const std::string& _label) {
1137 return new StepTool(_label, tim::scope::config(tim::scope::flat{}));
1138 };
1139
1140 UserProfilerConfig::GetFallbackToolFunctor() = [](const std::string& _label) {
1141 return new UserTool(_label);
1142 };
1143
1144 auto comps = "wall_clock, cpu_clock, cpu_util, peak_rss";
1145 auto run_env_comps = tim::get_env<std::string>("G4PROFILE_RUN_COMPONENTS", comps);
1146 auto event_env_comps = tim::get_env<std::string>("G4PROFILE_EVENT_COMPONENTS", comps);
1147 auto track_env_comps = tim::get_env<std::string>("G4PROFILE_TRACK_COMPONENTS", comps);
1148 auto step_env_comps = tim::get_env<std::string>("G4PROFILE_STEP_COMPONENTS", comps);
1149 auto user_env_comps = tim::get_env<std::string>("G4PROFILE_USER_COMPONENTS", comps);
1150
1151 tim::configure<G4RunProfiler>(run_env_comps);
1152 tim::configure<G4EventProfiler>(event_env_comps);
1153 tim::configure<G4TrackProfiler>(track_env_comps);
1154 tim::configure<G4StepProfiler>(step_env_comps);
1155 tim::configure<G4UserProfiler>(user_env_comps);
1156#endif
1157 }
1158} // extern "C"
1159
1160// --------------------------------------------------------------------
1161
1162#ifdef GEANT4_USE_TIMEMORY
1163namespace
1164{
1165static G4bool profiler_is_initialized = (G4RunProfilerInit(), true);
1166}
1167#endif
1168
1169// --------------------------------------------------------------------
G4ApplicationState
@ G4State_EventProc
@ G4State_Init
@ G4State_Idle
@ G4State_Quit
@ G4State_GeomClosed
@ G4State_PreInit
Helper function for copying random state files in G4run.
G4bool G4CopyRandomState(const G4fs::path &source, const G4fs::path &dest, const G4String &callsite)
@ FatalException
void G4Exception(const char *originOfException, const char *exceptionCode, G4ExceptionSeverity severity, const char *description)
std::ostringstream G4ExceptionDescription
@ idxPostStep
@ idxAtRest
@ idxAlongStep
TIMEMORY_WEAK_PREFIX void G4RunProfilerInit(void) TIMEMORY_WEAK_POSTFIX
#define TIMEMORY_WEAK_PREFIX
void G4ProfilerInit(void)
#define TIMEMORY_WEAK_POSTFIX
#define TIMEMORY_JOIN(...)
bool G4bool
Definition G4Types.hh:86
int G4int
Definition G4Types.hh:85
#define theParticleIterator
G4GLOB_DLL std::ostream G4cerr
#define G4endl
Definition G4ios.hh:67
G4GLOB_DLL std::ostream G4cout
static G4AssemblyStore * GetInstance()
static void Clean()
void SetUserAction(G4UserEventAction *userAction)
void ProcessOneEvent(G4Event *anEvent)
G4bool ToBeKept() const
Definition G4Event.hh:107
G4int GetNumberOfGrips() const
Definition G4Event.hh:120
G4HCofThisEvent * GetHCofThisEvent() const
Definition G4Event.hh:161
void SetEventAborted()
Definition G4Event.hh:93
G4int GetEventID() const
Definition G4Event.hh:123
static G4GeometryManager * GetInstance()
void OpenGeometry(G4VPhysicalVolume *vol=nullptr)
G4VHitsCollection * GetHC(G4int i)
static G4LogicalVolumeStore * GetInstance()
void SetVoxelHeader(G4SmartVoxelHeader *pVoxel)
const G4String & GetName() const
G4SmartVoxelHeader * GetVoxelHeader() const
static G4ParallelWorldProcessStore * GetInstance()
void SetLayeredMaterialFlag(G4bool flg=true)
void SetParallelWorld(G4String parallelWorldName)
G4bool IsAtRestRequired(G4ParticleDefinition *)
G4ProcessManager * GetProcessManager() const
G4PTblDicIterator * GetIterator() const
static G4ParticleTable * GetParticleTable()
G4UImessenger * CreateMessenger()
static G4PhysicalVolumeStore * GetInstance()
void SetProcessOrdering(G4VProcess *aProcess, G4ProcessVectorDoItIndex idDoIt, G4int ordDoIt=ordDefault)
void SetProcessOrderingToSecond(G4VProcess *aProcess, G4ProcessVectorDoItIndex idDoIt)
G4int AddProcess(G4VProcess *aProcess, G4int ordAtRestDoIt=ordInActive, G4int ordAlongSteptDoIt=ordInActive, G4int ordPostStepDoIt=ordInActive)
static G4ProcessTable * GetProcessTable()
static void Configure(const std::vector< std::string > &args)
Definition G4Profiler.cc:91
static bool GetPerEvent()
static void Finalize()
static G4RegionStore * GetInstance()
void SetPhysics(G4VUserPhysicsList *uPhys)
void DefineWorldVolume(G4VPhysicalVolume *worldVol, G4bool topologyIsChanged=true)
void SetNumberOfParallelWorld(G4int i)
G4EventManager * GetEventManager() const
G4bool RunInitialization(G4bool fakeRun=false)
void DumpRegion(const G4String &rname) const
G4bool isScoreNtupleWriter
G4bool geometryInitialized
void CleanUpPreviousEvents()
void CleanUpUnnecessaryEvents(G4int keepNEvents)
G4int storeRandomNumberStatusToG4Event
G4UserWorkerInitialization * userWorkerInitialization
virtual void AbortRun(G4bool softAbort=false)
virtual void Initialize()
G4int nParallelWorlds
std::list< G4Event * > * previousEvents
G4Timer * timer
G4UserWorkerThreadInitialization * userWorkerThreadInitialization
G4bool geometryDirectlyUpdated
G4int numberOfEventProcessed
virtual void RestoreRandomNumberStatus(const G4String &fileN)
virtual void InitializeEventLoop(G4int n_event, const char *macroFile=nullptr, G4int n_select=-1)
G4UserEventAction * userEventAction
void ReinitializeGeometry(G4bool destroyFirst=false, G4bool prop=true)
virtual void rndmSaveThisEvent()
virtual void DeleteUserInitializations()
G4RunManagerKernel * kernel
G4Run * currentRun
virtual G4bool ConfirmBeamOnCondition()
static G4RunManager * GetRunManager()
virtual void AbortEvent()
virtual void rndmSaveThisRun()
virtual void InitializePhysics()
G4DCtable * DCtable
G4String randomNumberStatusForThisRun
G4String msgText
virtual void BeamOn(G4int n_event, const char *macroFile=nullptr, G4int n_select=-1)
static G4bool IfGeometryHasBeenDestroyed()
G4UserRunAction * userRunAction
virtual void DefineWorldVolume(G4VPhysicalVolume *worldVol, G4bool topologyIsChanged=true)
G4bool rngStatusEventsFlag
G4String selectMacro
virtual void InitializeGeometry()
virtual void RunTermination()
G4bool physicsInitialized
G4VUserActionInitialization * userActionInitialization
void StackPreviousEvent(G4Event *anEvent)
static G4RUN_DLL G4bool fGeometryHasBeenDestroyed
void ReOptimize(G4LogicalVolume *)
G4VUserDetectorConstruction * userDetector
G4VUserPrimaryGeneratorAction * userPrimaryGeneratorAction
G4int numberOfEventToBeProcessed
virtual ~G4RunManager()
G4String randomNumberStatusDir
virtual void TerminateEventLoop()
virtual void SetUserAction(G4UserRunAction *userAction)
G4String randomNumberStatusForThisEvent
void GeometryHasBeenModified(G4bool prop=true)
G4UserTrackingAction * userTrackingAction
RMType runManagerType
G4int n_perviousEventsToBeStored
virtual void SetUserInitialization(G4VUserDetectorConstruction *userInit)
void ReOptimizeMotherOf(G4VPhysicalVolume *)
virtual void ProcessOneEvent(G4int i_event)
virtual void ConfigureProfilers(const std::vector< std::string > &args={})
G4bool storeRandomNumberStatus
virtual G4Event * GenerateEvent(G4int i_event)
G4bool initializedAtLeastOnce
G4EventManager * eventManager
virtual void StoreRNGStatus(const G4String &filenamePrefix)
virtual void DoEventLoop(G4int n_event, const char *macroFile=nullptr, G4int n_select=-1)
virtual void TerminateOneEvent()
virtual void RunInitialization()
void DumpRegion(const G4String &rname) const
G4ProfilerConfig< G4ProfileType::Run > ProfilerConfig
G4VUserPhysicsList * physicsList
virtual void AnalyzeEvent(G4Event *anEvent)
G4UserStackingAction * userStackingAction
void UpdateScoring()
G4Event * currentEvent
virtual void ConstructScoringWorlds()
G4UserSteppingAction * userSteppingAction
Definition G4Run.hh:49
void SetHCtable(G4HCtable *HCtbl)
Definition G4Run.hh:108
G4int GetRunID() const
Definition G4Run.hh:86
void StoreEvent(G4Event *evt)
Definition G4Run.cc:73
virtual void RecordEvent(const G4Event *)
Definition G4Run.cc:59
void SetNumberOfEventToBeProcessed(G4int n_ev)
Definition G4Run.hh:107
void SetRunID(G4int id)
Definition G4Run.hh:106
void SetDCtable(G4DCtable *DCtbl)
Definition G4Run.hh:109
void SetRandomNumberStatus(G4String &st)
Definition G4Run.hh:110
G4HCofThisEvent * PrepareNewEvent()
static G4SDManager * GetSDMpointerIfExist()
G4HCtable * GetHCtable() const
G4VScoringMesh * GetMesh(G4int i) const
void Accumulate(G4VHitsCollection *map)
size_t GetNumberOfMesh() const
G4String GetWorldName(G4int i) const
static G4ScoringManager * GetScoringManagerIfExist()
G4long GetMemoryUse() const
G4double GetTotalTime() const
G4long GetNumberPointers() const
G4long GetNumberHeads() const
G4double GetSysTime() const
G4long GetNumberNodes() const
static void Clean()
static G4SolidStore * GetInstance()
const G4ApplicationState & GetCurrentState() const
static G4StateManager * GetStateManager()
G4bool SetNewState(const G4ApplicationState &requestedState)
void Stop()
G4double GetSystemElapsed() const
Definition G4Timer.cc:124
G4double GetUserElapsed() const
Definition G4Timer.cc:135
void Start()
G4VPhysicalVolume * GetParallelWorld(const G4String &worldName)
static G4TransportationManager * GetTransportationManager()
G4VPhysicalVolume * IsWorldExisting(const G4String &worldName)
G4int ApplyCommand(const char *aCommand)
static G4UImanager * GetUIpointer()
virtual void EndOfRunAction(const G4Run *)
virtual G4Run * GenerateRun()
virtual void BeginOfRunAction(const G4Run *)
static G4VPersistencyManager * GetPersistencyManager()
virtual G4bool Store(const G4Event *anEvent)=0
G4LogicalVolume * GetMotherLogical() const
void SetName(const G4String &pName)
virtual void Write()=0
virtual void Fill(G4HCofThisEvent *hce, G4int eventNumber)=0
virtual G4bool Book(G4HCofThisEvent *hce)=0
static G4VScoreNtupleWriter * Instance()
virtual void OpenFile()=0
MeshShape GetShape() const
void GeometryHasBeenDestroyed()
G4ParallelWorldProcess * GetParallelWorldProcess() const
void SetParallelWorldProcess(G4ParallelWorldProcess *proc)
virtual void Construct(G4VPhysicalVolume *fWorldPhys)
G4bool LayeredMassFlg()
virtual void Build() const =0
virtual G4VPhysicalVolume * Construct()=0
virtual void GeneratePrimaries(G4Event *anEvent)=0
static G4VVisManager * GetConcreteInstance()
virtual void GeometryHasChanged()=0
G4bool IsMasterThread()
void G4ConsumeParameters(_Args &&...)
Definition templates.hh:177
#define G4ThreadLocal
Definition tls.hh:77