Geant4 11.1.1
Toolkit for the simulation of the passage of particles through matter
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
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 <sstream>
32
33#include "G4Timer.hh"
34
36#include "G4RunManager.hh"
37#include "G4RunManagerKernel.hh"
39
40#include "G4ApplicationState.hh"
41#include "G4Material.hh"
43#include "G4ParticleTable.hh"
44#include "G4ProcessTable.hh"
46#include "G4Run.hh"
47#include "G4RunMessenger.hh"
48#include "G4SDManager.hh"
49#include "G4StateManager.hh"
50#include "G4TiMemory.hh"
51#include "G4UImanager.hh"
52#include "G4UnitsTable.hh"
53#include "G4UserRunAction.hh"
60#include "G4VUserPhysicsList.hh"
62#include "G4VVisManager.hh"
63#include "G4ios.hh"
64#include "Randomize.hh"
65#include "G4TiMemory.hh"
66#include "G4Profiler.hh"
67
68#include "G4HCofThisEvent.hh"
71#include "G4ParticleTable.hh"
72#include "G4ProcessManager.hh"
73#include "G4ScoringManager.hh"
75#include "G4VHitsCollection.hh"
76#include "G4VScoringMesh.hh"
77
78#include "G4ScoringBox.hh"
79#include "G4ScoringCylinder.hh"
80#include "G4LogicalVolume.hh"
81#include "G4SmartVoxelHeader.hh"
82#include "G4SmartVoxelStat.hh"
83#include "G4VPhysicalVolume.hh"
84
85#include "G4AssemblyStore.hh"
86#include "G4GeometryManager.hh"
89#include "G4RegionStore.hh"
90#include "G4SolidStore.hh"
91
92using namespace CLHEP;
93
94// The following lines are needed since G4VUserPhysicsList
95// uses a #define theParticleIterator
96#ifdef theParticleIterator
97# undef theParticleIterator
98#endif
99
100G4ThreadLocal G4RunManager* G4RunManager::fRunManager = nullptr;
101
103
104// --------------------------------------------------------------------
106{
108}
109
110// --------------------------------------------------------------------
112{
113 return fRunManager;
114}
115
116// --------------------------------------------------------------------
118{
119 if(fRunManager)
120 {
121 G4Exception("G4RunManager::G4RunManager()", "Run0031", FatalException,
122 "G4RunManager constructed twice.");
123 }
124 fRunManager = this;
125
128
129 timer = new G4Timer();
130 runMessenger = new G4RunMessenger(this);
131 previousEvents = new std::list<G4Event*>;
134 std::ostringstream oss;
135 G4Random::saveFullState(oss);
139}
140
141// --------------------------------------------------------------------
143{
144 // This version of the constructor should never be called in sequential mode!
145#ifndef G4MULTITHREADED
147 msg << "Geant4 code is compiled without multi-threading support "
148 "(-DG4MULTITHREADED is set to off).";
149 msg << " This type of RunManager can only be used in mult-threaded "
150 "applications.";
151 G4Exception("G4RunManager::G4RunManager(G4bool)", "Run0107",
152 FatalException, msg);
153#endif
154
155 if(fRunManager != nullptr)
156 {
157 G4Exception("G4RunManager::G4RunManager()", "Run0031", FatalException,
158 "G4RunManager constructed twice.");
159 return;
160 }
161 fRunManager = this;
162
163 switch(rmType)
164 {
165 case masterRM:
167 break;
168 case workerRM:
170 break;
171 default:
173 msgx << "This type of RunManager can only be used in multi-threaded "
174 "applications.";
175 G4Exception("G4RunManager::G4RunManager(G4bool)", "Run0108",
176 FatalException, msgx);
177 return;
178 }
179 runManagerType = rmType;
180
182
183 timer = new G4Timer();
184 runMessenger = new G4RunMessenger(this);
185 previousEvents = new std::list<G4Event*>;
189 std::ostringstream oss;
190 G4Random::saveFullState(oss);
194}
195
196// --------------------------------------------------------------------
198{
199 // finalise profiler before shutting down the threads
202 // set the application state to the quite state
203 if(pStateManager->GetCurrentState() != G4State_Quit)
204 {
205 if(verboseLevel > 1)
206 G4cout << "G4 kernel has come to Quit state." << G4endl;
207 pStateManager->SetNewState(G4State_Quit);
208 }
209
211 delete currentRun;
212 delete timer;
213 delete runMessenger;
214 delete previousEvents;
215
216 // The following will work for all RunManager types
217 // if derived class does the correct thing in the derived
218 // destructor that is: set to zero pointers of
219 // user initialization objects for which have no
220 // ownership
222 delete userRunAction;
223 userRunAction = nullptr;
224 if(verboseLevel > 1)
225 G4cout << "UserRunAction deleted." << G4endl;
226
229 if(verboseLevel > 1)
230 G4cout << "UserPrimaryGenerator deleted." << G4endl;
231
232 if(verboseLevel > 1)
233 G4cout << "RunManager is deleting RunManagerKernel." << G4endl;
234
235 delete kernel;
236
237 fRunManager = nullptr;
238
239 if(verboseLevel > 1)
240 G4cout << "RunManager is deleted." << G4endl;
241}
242
243// --------------------------------------------------------------------
245{
246 delete userDetector;
247 userDetector = nullptr;
248 if(verboseLevel > 1)
249 G4cout << "UserDetectorConstruction deleted." << G4endl;
250
251 delete physicsList;
252 physicsList = nullptr;
253 if(verboseLevel > 1)
254 G4cout << "UserPhysicsList deleted." << G4endl;
255
257 userActionInitialization = nullptr;
258 if(verboseLevel > 1)
259 G4cout << "UserActionInitialization deleted." << G4endl;
260
262 userWorkerInitialization = nullptr;
263 if(verboseLevel > 1)
264 G4cout << "UserWorkerInitialization deleted." << G4endl;
265
268 if(verboseLevel > 1)
269 G4cout << "UserWorkerThreadInitialization deleted." << G4endl;
270}
271
272// --------------------------------------------------------------------
273void G4RunManager::BeamOn(G4int n_event, const char* macroFile, G4int n_select)
274{
275 if(n_event <= 0)
276 {
277 fakeRun = true;
278 }
279 else
280 {
281 fakeRun = false;
282 }
284 if(cond)
285 {
290 DoEventLoop(n_event, macroFile, n_select);
292 }
293 fakeRun = false;
294}
295
296// --------------------------------------------------------------------
298{
300
301 G4ApplicationState currentState = stateManager->GetCurrentState();
302 if(currentState != G4State_PreInit && currentState != G4State_Idle)
303 {
304 G4cerr << "Illegal application state - BeamOn() ignored." << G4endl;
305 return false;
306 }
307
309 {
310 G4cerr << " Geant4 kernel should be initialized" << G4endl;
311 G4cerr << "before the first BeamOn(). - BeamOn ignored." << G4endl;
312 return false;
313 }
314
316 {
317 if(verboseLevel > 0)
318 {
319 G4cout << "Start re-initialization because " << G4endl;
321 G4cout << " Geometry" << G4endl;
323 G4cout << " Physics processes" << G4endl;
324 G4cout << "has been modified since last Run." << G4endl;
325 }
326 Initialize();
327 }
328 return true;
329}
330
331// --------------------------------------------------------------------
333{
335 return;
336
337 runAborted = false;
339
341 delete currentRun;
342 currentRun = nullptr;
343
344 if(fakeRun)
345 return;
346
349
350 if(userRunAction != nullptr)
352 if(currentRun == nullptr)
353 currentRun = new G4Run();
354
357
360 if(fSDM != nullptr)
361 {
363 }
364
365 if(G4VScoreNtupleWriter::Instance() != nullptr)
366 {
367 auto hce = (fSDM != nullptr) ? fSDM->PrepareNewEvent() : nullptr;
369 delete hce;
370 }
371
372 std::ostringstream oss;
373 G4Random::saveFullState(oss);
376
377 for(G4int i_prev = 0; i_prev < n_perviousEventsToBeStored; ++i_prev)
378 {
379 previousEvents->push_back(nullptr);
380 }
381
382 if(printModulo >= 0 || verboseLevel > 0)
383 {
384 G4cout << "### Run " << currentRun->GetRunID() << " starts." << G4endl;
385 }
386 if(userRunAction != nullptr)
388
389#if defined(GEANT4_USE_TIMEMORY)
390 masterRunProfiler.reset(new ProfilerConfig(currentRun));
391#endif
392
394 {
396 }
397
399 {
400 G4String fileN = "currentRun";
402 {
403 std::ostringstream os;
404 os << "run" << currentRun->GetRunID();
405 fileN = os.str();
406 }
407 StoreRNGStatus(fileN);
408 }
409}
410
411// --------------------------------------------------------------------
412void G4RunManager::DoEventLoop(G4int n_event, const char* macroFile,
413 G4int n_select)
414{
415 InitializeEventLoop(n_event, macroFile, n_select);
416
417 // Event loop
418 for(G4int i_event = 0; i_event < n_event; ++i_event)
419 {
420 ProcessOneEvent(i_event);
422 if(runAborted)
423 break;
424 }
425
426 // For G4MTRunManager, TerminateEventLoop() is invoked after all threads are
427 // finished.
430}
431
432// --------------------------------------------------------------------
433void G4RunManager::InitializeEventLoop(G4int n_event, const char* macroFile,
434 G4int n_select)
435{
436 if(verboseLevel > 0)
437 {
438 timer->Start();
439 }
440
441 n_select_msg = n_select;
442 if(macroFile != 0)
443 {
444 if(n_select_msg < 0)
445 n_select_msg = n_event;
446 msgText = "/control/execute ";
447 msgText += macroFile;
448 selectMacro = macroFile;
449 }
450 else
451 {
452 n_select_msg = -1;
453 selectMacro = "";
454 }
455}
456
457// --------------------------------------------------------------------
459{
460 currentEvent = GenerateEvent(i_event);
464 if(i_event < n_select_msg)
466}
467
468// --------------------------------------------------------------------
470{
472 currentEvent = 0;
474}
475
476// --------------------------------------------------------------------
478{
479 if(verboseLevel > 0 && !fakeRun)
480 {
481 timer->Stop();
482 G4cout << " Run terminated." << G4endl;
483 G4cout << "Run Summary" << G4endl;
484 if(runAborted)
485 {
486 G4cout << " Run Aborted after " << numberOfEventProcessed
487 << " events processed." << G4endl;
488 }
489 else
490 {
491 G4cout << " Number of events processed : " << numberOfEventProcessed
492 << G4endl;
493 }
494 G4cout << " " << *timer << G4endl;
495 }
497}
498
499// --------------------------------------------------------------------
501{
502 if(userPrimaryGeneratorAction == nullptr)
503 {
504 G4Exception("G4RunManager::GenerateEvent()", "Run0032", FatalException,
505 "G4VUserPrimaryGeneratorAction is not defined!");
506 return nullptr;
507 }
508
509 G4Event* anEvent = new G4Event(i_event);
510
513 {
514 std::ostringstream oss;
515 G4Random::saveFullState(oss);
518 }
519
521 {
522 G4String fileN = "currentEvent";
524 {
525 std::ostringstream os;
526 os << "run" << currentRun->GetRunID() << "evt" << anEvent->GetEventID();
527 fileN = os.str();
528 }
529 StoreRNGStatus(fileN);
530 }
531
532 if(printModulo > 0 && anEvent->GetEventID() % printModulo == 0)
533 {
534 G4cout << "--> Event " << anEvent->GetEventID() << " starts." << G4endl;
535 }
537 return anEvent;
538}
539
540// --------------------------------------------------------------------
542{
543 G4String fileN = randomNumberStatusDir + fnpref + ".rndm";
544 G4Random::saveEngineStatus(fileN);
545}
546
547// --------------------------------------------------------------------
549{
550 G4VPersistencyManager* fPersM =
552 if(fPersM != nullptr)
553 fPersM->Store(anEvent);
554 currentRun->RecordEvent(anEvent);
555}
556
557// --------------------------------------------------------------------
559{
560 if(!fakeRun)
561 {
562#if defined(GEANT4_USE_TIMEMORY)
563 masterRunProfiler.reset();
564#endif
566 // tasking occasionally will call this function even
567 // if there was not a current run
568 if(currentRun != nullptr)
569 {
570 if(userRunAction != nullptr)
572 G4VPersistencyManager* fPersM =
574 if(fPersM != nullptr)
575 fPersM->Store(currentRun);
576 // write & close analysis output
578 {
580 }
581 }
582 ++runIDCounter;
583 }
584
586}
587
588// --------------------------------------------------------------------
590{
591 // Delete all events carried over from previous run.
592 // This method is invoked at the beginning of the next run
593 // or from the destructor of G4RunManager at the very end of
594 // the program.
595 // N.B. If ToBeKept() is true, the pointer of this event is
596 // kept in G4Run of the previous run, and deleted along with
597 // the deletion of G4Run.
598
599 auto evItr = previousEvents->cbegin();
600 while(evItr != previousEvents->cend())
601 {
602 G4Event* evt = *evItr;
603 if(evt != nullptr && !(evt->ToBeKept()))
604 delete evt;
605 evItr = previousEvents->erase(evItr);
606 }
607}
608
609// --------------------------------------------------------------------
611{
612 // Delete events that are no longer necessary for post
613 // processing such as visualization.
614 // N.B. If ToBeKept() is true, the pointer of this event is
615 // kept in G4Run of the previous run, and deleted along with
616 // the deletion of G4Run.
617
618 auto evItr = previousEvents->cbegin();
619 while(evItr != previousEvents->cend())
620 {
621 if(G4int(previousEvents->size()) <= keepNEvents)
622 return;
623
624 G4Event* evt = *evItr;
625 if(evt != nullptr)
626 {
627 if(evt->GetNumberOfGrips() == 0)
628 {
629 if(!(evt->ToBeKept()))
630 delete evt;
631 evItr = previousEvents->erase(evItr);
632 }
633 else
634 {
635 ++evItr;
636 }
637 }
638 else
639 {
640 evItr = previousEvents->erase(evItr);
641 }
642 }
643}
644
645// --------------------------------------------------------------------
647{
648 if(anEvent->ToBeKept())
649 currentRun->StoreEvent(anEvent);
650
652 {
653 if(anEvent->GetNumberOfGrips() == 0)
654 {
655 if(!(anEvent->ToBeKept()))
656 delete anEvent;
657 }
658 else
659 {
660 previousEvents->push_back(anEvent);
661 }
662 }
664}
665
666// --------------------------------------------------------------------
668{
670 G4ApplicationState currentState = stateManager->GetCurrentState();
671 if(currentState != G4State_PreInit && currentState != G4State_Idle)
672 {
673 G4cerr << "Illegal application state - "
674 << "G4RunManager::Initialize() ignored." << G4endl;
675 return;
676 }
677
678 stateManager->SetNewState(G4State_Init);
684 if(stateManager->GetCurrentState() != G4State_Idle)
685 {
686 stateManager->SetNewState(G4State_Idle);
687 }
688}
689
690// --------------------------------------------------------------------
692{
693 if(userDetector == nullptr)
694 {
695 G4Exception("G4RunManager::InitializeGeometry", "Run0033", FatalException,
696 "G4VUserDetectorConstruction is not defined!");
697 return;
698 }
699
700 if(verboseLevel > 1)
701 G4cout << "userDetector->Construct() start." << G4endl;
702
704 G4ApplicationState currentState = stateManager->GetCurrentState();
705 if(currentState == G4State_PreInit || currentState == G4State_Idle)
706 {
707 stateManager->SetNewState(G4State_Init);
708 }
710 {
716 }
717 // Notify the VisManager as well
719 {
721 if(pVVisManager != nullptr)
722 pVVisManager->GeometryHasChanged();
723 }
724
726 geometryInitialized = true;
727 stateManager->SetNewState(currentState);
728}
729
730// --------------------------------------------------------------------
732{
734 G4ApplicationState currentState = stateManager->GetCurrentState();
735 if(currentState == G4State_PreInit || currentState == G4State_Idle)
736 {
737 stateManager->SetNewState(G4State_Init);
738 }
739 if(physicsList != nullptr)
740 {
742 }
743 else
744 {
745 G4Exception("G4RunManager::InitializePhysics()", "Run0034", FatalException,
746 "G4VUserPhysicsList is not defined!");
747 }
748 physicsInitialized = true;
749 stateManager->SetNewState(currentState);
750}
751
752// --------------------------------------------------------------------
754{
755 // This method is valid only for GeomClosed or EventProc state
756 G4ApplicationState currentState =
758 if(currentState == G4State_GeomClosed || currentState == G4State_EventProc)
759 {
760 runAborted = true;
761 if(currentState == G4State_EventProc && !softAbort)
762 {
765 }
766 }
767 else
768 {
769 G4cerr << "Run is not in progress. AbortRun() ignored." << G4endl;
770 }
771}
772
773// --------------------------------------------------------------------
775{
776 // This method is valid only for EventProc state
777 G4ApplicationState currentState =
779 if(currentState == G4State_EventProc)
780 {
783 }
784 else
785 {
786 G4cerr << "Event is not in progress. AbortEevnt() ignored." << G4endl;
787 }
788}
789
790// --------------------------------------------------------------------
792 G4bool topologyIsChanged)
793{
794 kernel->DefineWorldVolume(worldVol, topologyIsChanged);
795}
796
797// --------------------------------------------------------------------
799{
800 G4int runNumber = 0;
801 if(currentRun != nullptr)
802 runNumber = currentRun->GetRunID();
804 {
805 G4cerr << "Warning from G4RunManager::rndmSaveThisRun():"
806 << " Random number status was not stored prior to this run."
807 << G4endl << "/random/setSavingFlag command must be issued. "
808 << "Command ignored." << G4endl;
809 return;
810 }
811
812 G4String fileIn = randomNumberStatusDir + "currentRun.rndm";
813
814 std::ostringstream os;
815 os << "run" << runNumber << ".rndm" << '\0';
816 G4String fileOut = randomNumberStatusDir + os.str();
817
818#ifdef WIN32
819 G4String copCmd = "/control/shell copy " + fileIn + " " + fileOut;
820#else
821 G4String copCmd = "/control/shell cp " + fileIn + " " + fileOut;
822#endif
824 if(verboseLevel > 0)
825 {
826 G4cout << fileIn << " is copied to " << fileOut << G4endl;
827 }
828}
829
830// --------------------------------------------------------------------
832{
833 if(currentEvent == 0)
834 {
835 G4cerr << "Warning from G4RunManager::rndmSaveThisEvent():"
836 << " there is no currentEvent available." << G4endl
837 << "Command ignored." << G4endl;
838 return;
839 }
840
842 {
843 G4cerr << "Warning from G4RunManager::rndmSaveThisEvent():"
844 << " Random number engine status is not available." << G4endl
845 << "/random/setSavingFlag command must be issued "
846 << "prior to the start of the run. Command ignored." << G4endl;
847 return;
848 }
849
850 G4String fileIn = randomNumberStatusDir + "currentEvent.rndm";
851
852 std::ostringstream os;
853 os << "run" << currentRun->GetRunID() << "evt" << currentEvent->GetEventID()
854 << ".rndm" << '\0';
855 G4String fileOut = randomNumberStatusDir + os.str();
856
857#ifdef WIN32
858 G4String copCmd = "/control/shell copy " + fileIn + " " + fileOut;
859#else
860 G4String copCmd = "/control/shell cp " + fileIn + " " + fileOut;
861#endif
863 if(verboseLevel > 0)
864 {
865 G4cout << fileIn << " is copied to " << fileOut << G4endl;
866 }
867}
868
869// --------------------------------------------------------------------
871{
872 G4String fileNameWithDirectory;
873 if(fileN.find("/") == std::string::npos)
874 {
875 fileNameWithDirectory = randomNumberStatusDir + fileN;
876 }
877 else
878 {
879 fileNameWithDirectory = fileN;
880 }
881
882 G4Random::restoreEngineStatus(fileNameWithDirectory);
883 if(verboseLevel > 0)
884 G4cout << "RandomNumberEngineStatus restored from file: "
885 << fileNameWithDirectory << G4endl;
886 G4Random::showEngineStatus();
887}
888
889// --------------------------------------------------------------------
890void G4RunManager::DumpRegion(const G4String& rname) const
891{
892 kernel->DumpRegion(rname);
893}
894
895// --------------------------------------------------------------------
897{
898 kernel->DumpRegion(region);
899}
900
901// --------------------------------------------------------------------
903{
904 using MeshShape = G4VScoringMesh::MeshShape;
905
907 if(ScM == nullptr)
908 return;
909
910 G4int nPar = (G4int)ScM->GetNumberOfMesh();
911 if(nPar < 1)
912 return;
913
915 for(G4int iw = 0; iw < nPar; ++iw)
916 {
917 G4VScoringMesh* mesh = ScM->GetMesh(iw);
920 G4VPhysicalVolume* pWorld = nullptr;
921 if(mesh->GetShape() != MeshShape::realWorldLogVol)
922 {
924 ->IsWorldExisting(ScM->GetWorldName(iw));
925 if(pWorld == nullptr)
926 {
928 ->GetParallelWorld(ScM->GetWorldName(iw));
929 pWorld->SetName(ScM->GetWorldName(iw));
930
931 G4ParallelWorldProcess* theParallelWorldProcess =
933 if(theParallelWorldProcess != nullptr)
934 {
935 theParallelWorldProcess->SetParallelWorld(ScM->GetWorldName(iw));
936 }
937 else
938 {
939 theParallelWorldProcess =
941 mesh->SetParallelWorldProcess(theParallelWorldProcess);
942 theParallelWorldProcess->SetParallelWorld(ScM->GetWorldName(iw));
943
944 theParticleIterator->reset();
945 while((*theParticleIterator)())
946 {
947 G4ParticleDefinition* particle = theParticleIterator->value();
948 G4ProcessManager* pmanager = particle->GetProcessManager();
949 if(pmanager != nullptr)
950 {
951 pmanager->AddProcess(theParallelWorldProcess);
952 if(theParallelWorldProcess->IsAtRestRequired(particle))
953 {
954 pmanager->SetProcessOrdering(theParallelWorldProcess, idxAtRest,
955 9900);
956 }
957 pmanager->SetProcessOrderingToSecond(theParallelWorldProcess,
959 pmanager->SetProcessOrdering(theParallelWorldProcess, idxPostStep,
960 9900);
961 }
962 }
963 }
964 theParallelWorldProcess->SetLayeredMaterialFlag(mesh->LayeredMassFlg());
965 }
966 }
967 mesh->Construct(pWorld);
968 }
970}
971
972// --------------------------------------------------------------------
974{
976 {
979 }
980
982 if(ScM == nullptr)
983 return;
984 G4int nPar = (G4int)ScM->GetNumberOfMesh();
985 if(nPar < 1)
986 return;
987
989 if(HCE == nullptr)
990 return;
991 G4int nColl = (G4int)HCE->GetCapacity();
992 for(G4int i = 0; i < nColl; ++i)
993 {
994 G4VHitsCollection* HC = HCE->GetHC(i);
995 if(HC != nullptr)
996 ScM->Accumulate(HC);
997 }
998}
999
1000// --------------------------------------------------------------------
1002{
1003 G4LogicalVolume* pMotherL = pPhys->GetMotherLogical();
1004 if(pMotherL != nullptr)
1005 ReOptimize(pMotherL);
1006}
1007
1008// --------------------------------------------------------------------
1010{
1011 G4Timer localtimer;
1012 if(verboseLevel > 1)
1013 {
1014 localtimer.Start();
1015 }
1016 G4SmartVoxelHeader* header = pLog->GetVoxelHeader();
1017 delete header;
1018 header = new G4SmartVoxelHeader(pLog);
1019 pLog->SetVoxelHeader(header);
1020 if(verboseLevel > 1)
1021 {
1022 localtimer.Stop();
1023 G4SmartVoxelStat stat(pLog, header, localtimer.GetSystemElapsed(),
1024 localtimer.GetUserElapsed());
1025 G4cout << G4endl << "Voxelisation of logical volume <" << pLog->GetName()
1026 << ">" << G4endl;
1027 G4cout << " heads : " << stat.GetNumberHeads()
1028 << " - nodes : " << stat.GetNumberNodes()
1029 << " - pointers : " << stat.GetNumberPointers() << G4endl;
1030 G4cout << " Memory used : " << (stat.GetMemoryUse() + 512) / 1024
1031 << "k - total time : " << stat.GetTotalTime()
1032 << " - system time : " << stat.GetSysTime() << G4endl;
1033 }
1034}
1035
1036// --------------------------------------------------------------------
1038{
1039 userDetector = userInit;
1040}
1041
1042// --------------------------------------------------------------------
1044{
1045 physicsList = userInit;
1046 kernel->SetPhysics(userInit);
1047}
1048
1049// --------------------------------------------------------------------
1051 G4UserWorkerInitialization* /*userInit*/)
1052{
1054 "G4RunManager::SetUserInitialization()", "Run3001", FatalException,
1055 "Base-class G4RunManager cannot take G4UserWorkerInitialization. Use "
1056 "G4MTRunManager.");
1057}
1058
1059// --------------------------------------------------------------------
1062{
1064 "G4RunManager::SetUserThreadInitialization()", "Run3001", FatalException,
1065 "Base-class G4RunManager cannot take G4UserWorkerThreadInitialization. "
1066 "Use G4MTRunManager.");
1067}
1068
1069// --------------------------------------------------------------------
1071{
1072 userActionInitialization = userInit;
1074}
1075
1076// --------------------------------------------------------------------
1078{
1079 userRunAction = userAction;
1080}
1081
1082// --------------------------------------------------------------------
1084{
1085 userPrimaryGeneratorAction = userAction;
1086}
1087
1088// --------------------------------------------------------------------
1090{
1091 eventManager->SetUserAction(userAction);
1092 userEventAction = userAction;
1093}
1094
1095// --------------------------------------------------------------------
1097{
1098 eventManager->SetUserAction(userAction);
1099 userStackingAction = userAction;
1100}
1101
1102// --------------------------------------------------------------------
1104{
1105 eventManager->SetUserAction(userAction);
1106 userTrackingAction = userAction;
1107}
1108
1109// --------------------------------------------------------------------
1111{
1112 eventManager->SetUserAction(userAction);
1113 userSteppingAction = userAction;
1114}
1115
1116// --------------------------------------------------------------------
1118{
1119 if(prop)
1120 {
1121 G4UImanager::GetUIpointer()->ApplyCommand("/run/geometryModified");
1122 }
1123 else
1124 {
1126 }
1127}
1128
1129// --------------------------------------------------------------------
1131{
1132 if(destroyFirst && G4Threading::IsMasterThread())
1133 {
1134 if(verboseLevel > 0)
1135 {
1136 G4cout << "#### Assemblies, Volumes and Solids Stores are wiped out."
1137 << G4endl;
1138 }
1144
1145 // remove all logical volume pointers from regions
1146 // exception: world logical volume pointer must be kept
1148 for(auto rItr = regionStore->cbegin(); rItr != regionStore->cend(); ++rItr)
1149 {
1150 if((*rItr)->GetName() == "DefaultRegionForTheWorld")
1151 continue;
1152 // if((*rItr)->GetName()=="DefaultRegionForParallelWorld") continue;
1153 auto lvItr = (*rItr)->GetRootLogicalVolumeIterator();
1154 for(std::size_t iRLV=0; iRLV<(*rItr)->GetNumberOfRootVolumes(); ++iRLV)
1155 {
1156 (*rItr)->RemoveRootLogicalVolume(*lvItr, false);
1157 ++lvItr;
1158 }
1159 if(verboseLevel > 0)
1160 {
1161 G4cout << "#### Region <" << (*rItr)->GetName() << "> is cleared."
1162 << G4endl;
1163 }
1164 }
1165
1166 // clear transportation manager
1169 }
1170 if(prop)
1171 {
1172 G4UImanager::GetUIpointer()->ApplyCommand("/run/reinitializeGeometry");
1173 }
1174 else
1175 {
1177 geometryInitialized = false;
1178 // Notify the VisManager as well
1180 {
1182 if(pVVisManager != nullptr)
1183 pVVisManager->GeometryHasChanged();
1184 }
1185 }
1186}
1187
1188// --------------------------------------------------------------------
1190{
1191 std::vector<std::string> _args;
1192 for(G4int i = 0; i < argc; ++i)
1193 _args.push_back(argv[i]);
1194 ConfigureProfilers(_args);
1195}
1196
1197// --------------------------------------------------------------------
1198void G4RunManager::ConfigureProfilers(const std::vector<std::string>& args)
1199{
1200#ifdef GEANT4_USE_TIMEMORY
1201 // parse command line if arguments were passed
1203#else
1204 G4ConsumeParameters(args);
1205#endif
1206}
1207
1208// --------------------------------------------------------------------
1209
1210#if !defined(GEANT4_USE_TIMEMORY)
1211# define TIMEMORY_WEAK_PREFIX
1212# define TIMEMORY_WEAK_POSTFIX
1213#endif
1214
1215// --------------------------------------------------------------------
1216
1217extern "C"
1218{
1219 // this allows the default setup to be overridden by linking
1220 // in an custom extern C function into the application
1223
1224 extern void G4ProfilerInit(void);
1225
1226 // this gets executed when the library gets loaded
1228 {
1229#ifdef GEANT4_USE_TIMEMORY
1231
1232 // guard against re-initialization
1233 static G4bool _once = false;
1234 if(_once)
1235 return;
1236 _once = true;
1237
1238 puts(">>> G4RunProfilerInit <<<");
1239
1240 using RunProfilerConfig = G4ProfilerConfig<G4ProfileType::Run>;
1241 using EventProfilerConfig = G4ProfilerConfig<G4ProfileType::Event>;
1242 using TrackProfilerConfig = G4ProfilerConfig<G4ProfileType::Track>;
1243 using StepProfilerConfig = G4ProfilerConfig<G4ProfileType::Step>;
1244 using UserProfilerConfig = G4ProfilerConfig<G4ProfileType::User>;
1245
1246 //
1247 // these are the default functions for evaluating whether
1248 // to start profiling
1249 //
1250 RunProfilerConfig::GetFallbackQueryFunctor() = [](const G4Run* _run) {
1251 return G4Profiler::GetEnabled(G4ProfileType::Run) && _run;
1252 };
1253
1254 EventProfilerConfig::GetFallbackQueryFunctor() = [](const G4Event* _event) {
1255 return G4Profiler::GetEnabled(G4ProfileType::Event) && _event;
1256 };
1257
1258 TrackProfilerConfig::GetFallbackQueryFunctor() = [](const G4Track* _track) {
1259 return G4Profiler::GetEnabled(G4ProfileType::Track) && _track &&
1260 _track->GetDynamicParticle();
1261 };
1262
1263 StepProfilerConfig::GetFallbackQueryFunctor() = [](const G4Step* _step) {
1264 return G4Profiler::GetEnabled(G4ProfileType::Step) && _step &&
1265 _step->GetTrack();
1266 };
1267
1268 UserProfilerConfig::GetFallbackQueryFunctor() =
1269 [](const std::string& _user) {
1270 return G4Profiler::GetEnabled(G4ProfileType::User) && !_user.empty();
1271 };
1272
1273 //
1274 // these are the default functions which encode the profiling label.
1275 // Will not be called unless the query returned true
1276 //
1277 RunProfilerConfig::GetFallbackLabelFunctor() = [](const G4Run* _run) {
1278 return TIMEMORY_JOIN('/', "G4Run", _run->GetRunID());
1279 };
1280
1281 EventProfilerConfig::GetFallbackLabelFunctor() =
1282 [](const G4Event* _event) -> std::string {
1284 return TIMEMORY_JOIN('/', "G4Event", _event->GetEventID());
1285 else
1286 return "G4Event";
1287 };
1288
1289 TrackProfilerConfig::GetFallbackLabelFunctor() = [](const G4Track* _track) {
1290 auto pdef = _track->GetDynamicParticle()->GetParticleDefinition();
1291 return TIMEMORY_JOIN('/', "G4Track", pdef->GetParticleName());
1292 };
1293
1294 StepProfilerConfig::GetFallbackLabelFunctor() = [](const G4Step* _step) {
1295 auto pdef = _step->GetTrack()->GetParticleDefinition();
1296 return TIMEMORY_JOIN('/', "G4Step", pdef->GetParticleName());
1297 };
1298
1299 UserProfilerConfig::GetFallbackLabelFunctor() =
1300 [](const std::string& _user) { return _user; };
1301
1302 using RunTool = typename RunProfilerConfig::type;
1303 using EventTool = typename EventProfilerConfig::type;
1304 using TrackTool = typename TrackProfilerConfig::type;
1305 using StepTool = typename StepProfilerConfig::type;
1306 using UserTool = typename UserProfilerConfig::type;
1307
1308 RunProfilerConfig::GetFallbackToolFunctor() =
1309 [](const std::string& _label) { return new RunTool{ _label }; };
1310
1311 EventProfilerConfig::GetFallbackToolFunctor() =
1312 [](const std::string& _label) { return new EventTool{ _label }; };
1313
1314 TrackProfilerConfig::GetFallbackToolFunctor() =
1315 [](const std::string& _label) {
1316 return new TrackTool(_label, tim::scope::config(tim::scope::flat{}));
1317 };
1318
1319 StepProfilerConfig::GetFallbackToolFunctor() =
1320 [](const std::string& _label) {
1321 return new StepTool(_label, tim::scope::config(tim::scope::flat{}));
1322 };
1323
1324 UserProfilerConfig::GetFallbackToolFunctor() =
1325 [](const std::string& _label) { return new UserTool(_label); };
1326
1327 auto comps = "wall_clock, cpu_clock, cpu_util, peak_rss";
1328 auto run_env_comps =
1329 tim::get_env<std::string>("G4PROFILE_RUN_COMPONENTS", comps);
1330 auto event_env_comps =
1331 tim::get_env<std::string>("G4PROFILE_EVENT_COMPONENTS", comps);
1332 auto track_env_comps =
1333 tim::get_env<std::string>("G4PROFILE_TRACK_COMPONENTS", comps);
1334 auto step_env_comps =
1335 tim::get_env<std::string>("G4PROFILE_STEP_COMPONENTS", comps);
1336 auto user_env_comps =
1337 tim::get_env<std::string>("G4PROFILE_USER_COMPONENTS", comps);
1338
1339 tim::configure<G4RunProfiler>(run_env_comps);
1340 tim::configure<G4EventProfiler>(event_env_comps);
1341 tim::configure<G4TrackProfiler>(track_env_comps);
1342 tim::configure<G4StepProfiler>(step_env_comps);
1343 tim::configure<G4UserProfiler>(user_env_comps);
1344#endif
1345 }
1346} // extern "C"
1347
1348// --------------------------------------------------------------------
1349
1350#ifdef GEANT4_USE_TIMEMORY
1351namespace
1352{
1353 static G4bool profiler_is_initialized = (G4RunProfilerInit(), true);
1354}
1355#endif
1356
1357// --------------------------------------------------------------------
G4ApplicationState
@ G4State_EventProc
@ G4State_Init
@ G4State_Idle
@ G4State_Quit
@ G4State_GeomClosed
@ G4State_PreInit
@ FatalException
void G4Exception(const char *originOfException, const char *exceptionCode, G4ExceptionSeverity severity, const char *description)
Definition: G4Exception.cc:59
std::ostringstream G4ExceptionDescription
Definition: G4Exception.hh:40
@ idxPostStep
@ idxAtRest
@ idxAlongStep
TIMEMORY_WEAK_PREFIX void G4RunProfilerInit(void) TIMEMORY_WEAK_POSTFIX
#define TIMEMORY_WEAK_PREFIX
void G4ProfilerInit(void)
Definition: G4Profiler.cc:540
#define TIMEMORY_WEAK_POSTFIX
#define TIMEMORY_JOIN(...)
Definition: G4TiMemory.hh:115
bool G4bool
Definition: G4Types.hh:86
int G4int
Definition: G4Types.hh:85
#define theParticleIterator
G4GLOB_DLL std::ostream G4cerr
#define G4endl
Definition: G4ios.hh:57
G4GLOB_DLL std::ostream G4cout
static G4AssemblyStore * GetInstance()
static void Clean()
void SetUserAction(G4UserEventAction *userAction)
void AbortCurrentEvent()
void ProcessOneEvent(G4Event *anEvent)
G4bool ToBeKept() const
Definition: G4Event.hh:102
G4int GetNumberOfGrips() const
Definition: G4Event.hh:115
void SetRandomNumberStatus(G4String &st)
Definition: G4Event.hh:90
G4HCofThisEvent * GetHCofThisEvent() const
Definition: G4Event.hh:156
void SetEventAborted()
Definition: G4Event.hh:88
G4int GetEventID() const
Definition: G4Event.hh:118
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()
Definition: G4Profiler.hh:115
static void Finalize()
Definition: G4Profiler.cc:331
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 n_select_msg
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()
G4int runIDCounter
G4RunManagerKernel * kernel
G4int verboseLevel
G4Run * currentRun
virtual G4bool ConfirmBeamOnCondition()
static G4RunManager * GetRunManager()
virtual void AbortEvent()
virtual void rndmSaveThisRun()
virtual void InitializePhysics()
G4DCtable * DCtable
G4String randomNumberStatusForThisRun
G4bool runAborted
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:107
G4int GetRunID() const
Definition: G4Run.hh:78
void StoreEvent(G4Event *evt)
Definition: G4Run.cc:78
virtual void RecordEvent(const G4Event *)
Definition: G4Run.cc:61
void SetNumberOfEventToBeProcessed(G4int n_ev)
Definition: G4Run.hh:103
void SetRunID(G4int id)
Definition: G4Run.hh:102
void SetDCtable(G4DCtable *DCtbl)
Definition: G4Run.hh:108
void SetRandomNumberStatus(G4String &st)
Definition: G4Run.hh:109
G4HCofThisEvent * PrepareNewEvent()
Definition: G4SDManager.cc:113
static G4SDManager * GetSDMpointerIfExist()
Definition: G4SDManager.cc:47
G4HCtable * GetHCtable() const
Definition: G4SDManager.hh:101
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()
Definition: G4SolidStore.cc:74
static G4SolidStore * GetInstance()
const G4ApplicationState & GetCurrentState() const
static G4StateManager * GetStateManager()
G4bool SetNewState(const G4ApplicationState &requestedState)
Definition: G4Step.hh:62
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)
Definition: G4UImanager.cc:495
static G4UImanager * GetUIpointer()
Definition: G4UImanager.cc:77
virtual void EndOfRunAction(const G4Run *aRun)
virtual void BeginOfRunAction(const G4Run *aRun)
virtual G4Run * GenerateRun()
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
Definition: DoubConv.h:17
G4bool IsMasterThread()
Definition: G4Threading.cc:124
void G4ConsumeParameters(_Args &&...)
Definition: templates.hh:177
#define G4ThreadLocal
Definition: tls.hh:77