Geant4 10.7.0
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//
27//
28//
29
30// On Sun, to prevent conflict with ObjectSpace, G4Timer.hh has to be
31// loaded *before* globals.hh...
32#include "G4Timer.hh"
33
35#include "G4RunManager.hh"
36#include "G4RunManagerKernel.hh"
38
39#include "G4ApplicationState.hh"
40#include "G4Material.hh"
42#include "G4ParticleTable.hh"
43#include "G4ProcessTable.hh"
45#include "G4Run.hh"
46#include "G4RunMessenger.hh"
47#include "G4SDManager.hh"
48#include "G4StateManager.hh"
49#include "G4TiMemory.hh"
50#include "G4UImanager.hh"
51#include "G4UnitsTable.hh"
52#include "G4UserRunAction.hh"
59#include "G4VUserPhysicsList.hh"
61#include "G4VVisManager.hh"
62#include "G4ios.hh"
63#include "Randomize.hh"
64#include "G4TiMemory.hh"
65#include "G4Profiler.hh"
66#include <sstream>
67
68using namespace CLHEP;
69
70G4ThreadLocal G4RunManager* G4RunManager::fRunManager = 0;
71
74{
76}
77
78// The following lines are needed since G4VUserPhysicsList
79// uses a #define theParticleIterator
80#ifdef theParticleIterator
81# undef theParticleIterator
82#endif
83
84G4RunManager* G4RunManager::GetRunManager() { return fRunManager; }
85
87 : userDetector(0)
88 , physicsList(0)
89 , userActionInitialization(0)
90 , userWorkerInitialization(0)
91 , userWorkerThreadInitialization(0)
92 , userRunAction(0)
93 , userPrimaryGeneratorAction(0)
94 , userEventAction(0)
95 , userStackingAction(0)
96 , userTrackingAction(0)
97 , userSteppingAction(0)
98 , geometryInitialized(false)
99 , physicsInitialized(false)
100 , runAborted(false)
101 , initializedAtLeastOnce(false)
102 , geometryToBeOptimized(true)
103 , runIDCounter(0)
104 , verboseLevel(0)
105 , printModulo(-1)
106 , DCtable(0)
107 , currentRun(0)
108 , currentEvent(0)
109 , n_perviousEventsToBeStored(0)
110 , numberOfEventToBeProcessed(0)
111 , storeRandomNumberStatus(false)
112 , storeRandomNumberStatusToG4Event(0)
113 , rngStatusEventsFlag(false)
114 , currentWorld(0)
115 , nParallelWorlds(0)
116 , msgText(" ")
117 , n_select_msg(-1)
118 , numberOfEventProcessed(0)
119 , selectMacro("")
120 , fakeRun(false)
121 , isScoreNtupleWriter(false)
122 , geometryDirectlyUpdated(false)
123{
124 if(fRunManager)
125 {
126 G4Exception("G4RunManager::G4RunManager()", "Run0031", FatalException,
127 "G4RunManager constructed twice.");
128 }
129 fRunManager = this;
130
133
134 timer = new G4Timer();
135 runMessenger = new G4RunMessenger(this);
136 previousEvents = new std::list<G4Event*>;
140 std::ostringstream oss;
141 G4Random::saveFullState(oss);
145}
146
148 : userDetector(0)
149 , physicsList(0)
150 , userActionInitialization(0)
151 , userWorkerInitialization(0)
152 , userWorkerThreadInitialization(0)
153 , userRunAction(0)
154 , userPrimaryGeneratorAction(0)
155 , userEventAction(0)
156 , userStackingAction(0)
157 , userTrackingAction(0)
158 , userSteppingAction(0)
159 , geometryInitialized(false)
160 , physicsInitialized(false)
161 , runAborted(false)
162 , initializedAtLeastOnce(false)
163 , geometryToBeOptimized(true)
164 , runIDCounter(0)
165 , verboseLevel(0)
166 , printModulo(-1)
167 , DCtable(0)
168 , currentRun(0)
169 , currentEvent(0)
170 , n_perviousEventsToBeStored(0)
171 , numberOfEventToBeProcessed(0)
172 , storeRandomNumberStatus(false)
173 , storeRandomNumberStatusToG4Event(0)
174 , rngStatusEventsFlag(false)
175 , currentWorld(0)
176 , nParallelWorlds(0)
177 , msgText(" ")
178 , n_select_msg(-1)
179 , numberOfEventProcessed(0)
180 , selectMacro("")
181 , fakeRun(false)
182 , isScoreNtupleWriter(false)
183 , geometryDirectlyUpdated(false)
184{
185 // This version of the constructor should never be called in sequential mode!
186#ifndef G4MULTITHREADED
188 msg << "Geant4 code is compiled without multi-threading support "
189 "(-DG4MULTITHREADED "
190 "is set to off).";
191 msg << " This type of RunManager can only be used in mult-threaded "
192 "applications.";
193 G4Exception("G4RunManager::G4RunManager(G4bool)", "Run0107", FatalException,
194 msg);
195#endif
196
197 if(fRunManager)
198 {
199 G4Exception("G4RunManager::G4RunManager()", "Run0031", FatalException,
200 "G4RunManager constructed twice.");
201 return;
202 }
203 fRunManager = this;
204
205 switch(rmType)
206 {
207 case masterRM:
209 break;
210 case workerRM:
212 break;
213 default:
215 msgx << " This type of RunManager can only be used in mult-threaded "
216 "applications.";
217 G4Exception("G4RunManager::G4RunManager(G4bool)", "Run0108",
218 FatalException, msgx);
219 return;
220 }
221 runManagerType = rmType;
222
224
225 timer = new G4Timer();
226 runMessenger = new G4RunMessenger(this);
227 previousEvents = new std::list<G4Event*>;
231 std::ostringstream oss;
232 G4Random::saveFullState(oss);
236}
237
239{
240 // finalize profiler before shutting down the threads
243 // set the application state to the quite state
244 if(pStateManager->GetCurrentState() != G4State_Quit)
245 {
246 if(verboseLevel > 0)
247 G4cout << "G4 kernel has come to Quit state." << G4endl;
248 pStateManager->SetNewState(G4State_Quit);
249 }
250
252 if(currentRun)
253 delete currentRun;
254 delete timer;
255 delete runMessenger;
256 delete previousEvents;
257
258 // The following will work for all RunManager types
259 // if derived class does the correct thing in derived
260 // destructor that is set to zero pointers of
261 // user initialization objects for which does not have
262 // ownership
264 if(userRunAction)
265 {
266 delete userRunAction;
267 userRunAction = 0;
268 if(verboseLevel > 1)
269 G4cout << "UserRunAction deleted." << G4endl;
270 }
272 {
275 if(verboseLevel > 1)
276 G4cout << "UserPrimaryGenerator deleted." << G4endl;
277 }
278
279 if(verboseLevel > 1)
280 G4cout << "RunManager is deleting RunManagerKernel." << G4endl;
281
282 delete kernel;
283
284 fRunManager = 0;
285}
286
288{
289 if(userDetector)
290 {
291 delete userDetector;
292 userDetector = 0;
293 if(verboseLevel > 1)
294 G4cout << "UserDetectorConstruction deleted." << G4endl;
295 }
296 if(physicsList)
297 {
298 delete physicsList;
299 physicsList = 0;
300 if(verboseLevel > 1)
301 G4cout << "UserPhysicsList deleted." << G4endl;
302 }
304 {
307 if(verboseLevel > 1)
308 G4cout << "UserActionInitialization deleted." << G4endl;
309 }
311 {
314 if(verboseLevel > 1)
315 G4cout << "UserWorkerInitialization deleted." << G4endl;
316 }
318 {
321 if(verboseLevel > 1)
322 G4cout << "UserWorkerThreadInitialization deleted." << G4endl;
323 }
324}
325
326void G4RunManager::BeamOn(G4int n_event, const char* macroFile, G4int n_select)
327{
328 if(n_event <= 0)
329 {
330 fakeRun = true;
331 }
332 else
333 {
334 fakeRun = false;
335 }
337 if(cond)
338 {
343 DoEventLoop(n_event, macroFile, n_select);
345 }
346 fakeRun = false;
347}
348
350{
352
353 G4ApplicationState currentState = stateManager->GetCurrentState();
354 if(currentState != G4State_PreInit && currentState != G4State_Idle)
355 {
356 G4cerr << "Illegal application state - BeamOn() ignored." << G4endl;
357 return false;
358 }
359
361 {
362 G4cerr << " Geant4 kernel should be initialized" << G4endl;
363 G4cerr << "before the first BeamOn(). - BeamOn ignored." << G4endl;
364 return false;
365 }
366
368 {
369 if(verboseLevel > 0)
370 {
371 G4cout << "Start re-initialization because " << G4endl;
373 G4cout << " Geometry" << G4endl;
375 G4cout << " Physics processes" << G4endl;
376 G4cout << "has been modified since last Run." << G4endl;
377 }
378 Initialize();
379 }
380 return true;
381}
382
384{
386 return;
387
388 runAborted = false;
390
392 if(currentRun)
393 delete currentRun;
394 currentRun = 0;
395
396 if(fakeRun)
397 return;
398
401
402 if(userRunAction)
404 if(!currentRun)
405 currentRun = new G4Run();
406
409
412 if(fSDM)
413 {
415 }
416
418 {
419 auto hce = fSDM->PrepareNewEvent();
421 delete hce;
422 }
423
424 std::ostringstream oss;
425 G4Random::saveFullState(oss);
428
429 for(G4int i_prev = 0; i_prev < n_perviousEventsToBeStored; i_prev++)
430 {
431 previousEvents->push_back((G4Event*) 0);
432 }
433
434 if(printModulo >= 0 || verboseLevel > 0)
435 {
436 G4cout << "### Run " << currentRun->GetRunID() << " starts." << G4endl;
437 }
438 if(userRunAction)
440
441#if defined(GEANT4_USE_TIMEMORY)
442 masterRunProfiler.reset(new ProfilerConfig(currentRun));
443#endif
444
446 {
448 }
449
451 {
452 G4String fileN = "currentRun";
454 {
455 std::ostringstream os;
456 os << "run" << currentRun->GetRunID();
457 fileN = os.str();
458 }
459 StoreRNGStatus(fileN);
460 }
461}
462
463void G4RunManager::DoEventLoop(G4int n_event, const char* macroFile,
464 G4int n_select)
465{
466 InitializeEventLoop(n_event, macroFile, n_select);
467
468 // Event loop
469 for(G4int i_event = 0; i_event < n_event; i_event++)
470 {
471 ProcessOneEvent(i_event);
473 if(runAborted)
474 break;
475 }
476
477 // For G4MTRunManager, TerminateEventLoop() is invoked after all threads are
478 // finished.
481}
482
483void G4RunManager::InitializeEventLoop(G4int n_event, const char* macroFile,
484 G4int n_select)
485{
486 if(verboseLevel > 0)
487 {
488 timer->Start();
489 }
490
491 n_select_msg = n_select;
492 if(macroFile != 0)
493 {
494 if(n_select_msg < 0)
495 n_select_msg = n_event;
496 msgText = "/control/execute ";
497 msgText += macroFile;
498 selectMacro = macroFile;
499 }
500 else
501 {
502 n_select_msg = -1;
503 selectMacro = "";
504 }
505}
506
508{
509 currentEvent = GenerateEvent(i_event);
513 if(i_event < n_select_msg)
515}
516
518{
520 currentEvent = 0;
522}
523
525{
526 if(verboseLevel > 0 && !fakeRun)
527 {
528 timer->Stop();
529 G4cout << " Run terminated." << G4endl;
530 G4cout << "Run Summary" << G4endl;
531 if(runAborted)
532 {
533 G4cout << " Run Aborted after " << numberOfEventProcessed
534 << " events processed." << G4endl;
535 }
536 else
537 {
538 G4cout << " Number of events processed : " << numberOfEventProcessed
539 << G4endl;
540 }
541 G4cout << " " << *timer << G4endl;
542 }
543 ////////////////
544 /// G4ProductionCutsTable::GetProductionCutsTable()->PhysicsTableUpdated();
546}
547
549{
551 {
552 G4Exception("G4RunManager::GenerateEvent()", "Run0032", FatalException,
553 "G4VUserPrimaryGeneratorAction is not defined!");
554 return 0;
555 }
556
557 G4Event* anEvent = new G4Event(i_event);
558
561 {
562 std::ostringstream oss;
563 G4Random::saveFullState(oss);
566 }
567
569 {
570 G4String fileN = "currentEvent";
572 {
573 std::ostringstream os;
574 os << "run" << currentRun->GetRunID() << "evt" << anEvent->GetEventID();
575 fileN = os.str();
576 }
577 StoreRNGStatus(fileN);
578 }
579
580 if(printModulo > 0 && anEvent->GetEventID() % printModulo == 0)
581 {
582 G4cout << "--> Event " << anEvent->GetEventID() << " starts." << G4endl;
583 }
585 return anEvent;
586}
587
589{
590 G4String fileN = randomNumberStatusDir + fnpref + ".rndm";
591 G4Random::saveEngineStatus(fileN);
592}
593
595{
596 G4VPersistencyManager* fPersM =
598 if(fPersM)
599 fPersM->Store(anEvent);
600 currentRun->RecordEvent(anEvent);
601}
602
604{
605 if(!fakeRun)
606 {
607#if defined(GEANT4_USE_TIMEMORY)
608 masterRunProfiler.reset();
609#endif
611 // tasking occasionally will call this function even
612 // if there was not a current run
613 if(currentRun)
614 {
615 if(userRunAction)
617 G4VPersistencyManager* fPersM =
619 if(fPersM)
620 fPersM->Store(currentRun);
621 // write & close analysis output
623 {
625 }
626 }
627 runIDCounter++;
628 }
629
631}
632
634{
635 // Delete all events carried over from previous run.
636 // This method is invoked at the beginning of the next run
637 // or from the destructor of G4RunManager at the very end of
638 // the program.
639 // N.B. If ToBeKept() is true, the pointer of this event is
640 // kept in G4Run of the previous run, and deleted along with
641 // the deletion of G4Run.
642
643 std::list<G4Event*>::iterator evItr = previousEvents->begin();
644 while(evItr != previousEvents->end())
645 {
646 G4Event* evt = *evItr;
647 if(evt && !(evt->ToBeKept()))
648 delete evt;
649 evItr = previousEvents->erase(evItr);
650 }
651}
652
654{
655 // Delete events that are no longer necessary for post
656 // processing such as visualization.
657 // N.B. If ToBeKept() is true, the pointer of this event is
658 // kept in G4Run of the previous run, and deleted along with
659 // the deletion of G4Run.
660
661 std::list<G4Event*>::iterator evItr = previousEvents->begin();
662 while(evItr != previousEvents->end())
663 {
664 if(G4int(previousEvents->size()) <= keepNEvents)
665 return;
666
667 G4Event* evt = *evItr;
668 if(evt)
669 {
670 if(evt->GetNumberOfGrips() == 0)
671 {
672 if(!(evt->ToBeKept()))
673 delete evt;
674 evItr = previousEvents->erase(evItr);
675 }
676 else
677 {
678 evItr++;
679 }
680 }
681 else
682 {
683 evItr = previousEvents->erase(evItr);
684 }
685 }
686}
687
689{
690 if(anEvent->ToBeKept())
691 currentRun->StoreEvent(anEvent);
692
694 {
695 if(anEvent->GetNumberOfGrips() == 0)
696 {
697 if(!(anEvent->ToBeKept()))
698 delete anEvent;
699 }
700 else
701 {
702 previousEvents->push_back(anEvent);
703 }
704 }
705
707}
708
710{
712 G4ApplicationState currentState = stateManager->GetCurrentState();
713 if(currentState != G4State_PreInit && currentState != G4State_Idle)
714 {
715 G4cerr << "Illegal application state - "
716 << "G4RunManager::Initialize() ignored." << G4endl;
717 return;
718 }
719
720 stateManager->SetNewState(G4State_Init);
726 if(stateManager->GetCurrentState() != G4State_Idle)
727 {
728 stateManager->SetNewState(G4State_Idle);
729 }
730}
731
733{
734 if(!userDetector)
735 {
736 G4Exception("G4RunManager::InitializeGeometry", "Run0033", FatalException,
737 "G4VUserDetectorConstruction is not defined!");
738 return;
739 }
740
741 if(verboseLevel > 1)
742 G4cout << "userDetector->Construct() start." << G4endl;
743
745 G4ApplicationState currentState = stateManager->GetCurrentState();
746 if(currentState == G4State_PreInit || currentState == G4State_Idle)
747 {
748 stateManager->SetNewState(G4State_Init);
749 }
751 {
757 }
758 // Notify the VisManager as well
760 {
762 if(pVVisManager)
763 pVVisManager->GeometryHasChanged();
764 }
765
767 geometryInitialized = true;
768 stateManager->SetNewState(currentState);
769}
770
772{
774 G4ApplicationState currentState = stateManager->GetCurrentState();
775 if(currentState == G4State_PreInit || currentState == G4State_Idle)
776 {
777 stateManager->SetNewState(G4State_Init);
778 }
779 if(physicsList)
780 {
782 }
783 else
784 {
785 G4Exception("G4RunManager::InitializePhysics()", "Run0034", FatalException,
786 "G4VUserPhysicsList is not defined!");
787 }
788 physicsInitialized = true;
789 stateManager->SetNewState(currentState);
790}
791
793{
794 // This method is valid only for GeomClosed or EventProc state
795 G4ApplicationState currentState =
797 if(currentState == G4State_GeomClosed || currentState == G4State_EventProc)
798 {
799 runAborted = true;
800 if(currentState == G4State_EventProc && !softAbort)
801 {
804 }
805 }
806 else
807 {
808 G4cerr << "Run is not in progress. AbortRun() ignored." << G4endl;
809 }
810}
811
813{
814 // This method is valid only for EventProc state
815 G4ApplicationState currentState =
817 if(currentState == G4State_EventProc)
818 {
821 }
822 else
823 {
824 G4cerr << "Event is not in progress. AbortEevnt() ignored." << G4endl;
825 }
826}
827
829 G4bool topologyIsChanged)
830{
831 kernel->DefineWorldVolume(worldVol, topologyIsChanged);
832}
833
835{
836 G4int runNumber = 0;
837 if(currentRun) runNumber = currentRun->GetRunID();
839 {
840 G4cerr << "Warning from G4RunManager::rndmSaveThisRun():"
841 << " Random number status was not stored prior to this run."
842 << G4endl << "/random/setSavingFlag command must be issued. "
843 << "Command ignored." << G4endl;
844 return;
845 }
846
847 G4String fileIn = randomNumberStatusDir + "currentRun.rndm";
848
849 std::ostringstream os;
850 os << "run" << runNumber << ".rndm" << '\0';
851 G4String fileOut = randomNumberStatusDir + os.str();
852
853#ifdef WIN32
854 G4String copCmd = "/control/shell copy " + fileIn + " " + fileOut;
855#else
856 G4String copCmd = "/control/shell cp " + fileIn + " " + fileOut;
857#endif
859 if(verboseLevel > 0)
860 { G4cout << fileIn << " is copied to " << fileOut << G4endl; }
861}
862
864{
865 if(currentEvent == 0)
866 {
867 G4cerr
868 << "Warning from G4RunManager::rndmSaveThisEvent():"
869 << " there is no currentEvent available."
870 << G4endl << "Command ignored." << G4endl;
871 return;
872 }
873
875 {
876 G4cerr
877 << "Warning from G4RunManager::rndmSaveThisEvent():"
878 << " Random number engine status is not available."
879 << G4endl << "/random/setSavingFlag command must be issued "
880 << "prior to the start of the run. Command ignored." << G4endl;
881 return;
882 }
883
884 G4String fileIn = randomNumberStatusDir + "currentEvent.rndm";
885
886 std::ostringstream os;
887 os << "run" << currentRun->GetRunID() << "evt" << currentEvent->GetEventID()
888 << ".rndm" << '\0';
889 G4String fileOut = randomNumberStatusDir + os.str();
890
891#ifdef WIN32
892 G4String copCmd = "/control/shell copy " + fileIn + " " + fileOut;
893#else
894 G4String copCmd = "/control/shell cp " + fileIn + " " + fileOut;
895#endif
897 if(verboseLevel > 0)
898 { G4cout << fileIn << " is copied to " << fileOut << G4endl; }
899}
900
902{
903 G4String fileNameWithDirectory;
904 if(fileN.index("/") == std::string::npos)
905 {
906 fileNameWithDirectory = randomNumberStatusDir + fileN;
907 }
908 else
909 {
910 fileNameWithDirectory = fileN;
911 }
912
913 G4Random::restoreEngineStatus(fileNameWithDirectory);
914 if(verboseLevel > 0)
915 G4cout << "RandomNumberEngineStatus restored from file: "
916 << fileNameWithDirectory << G4endl;
917 G4Random::showEngineStatus();
918}
919
920void G4RunManager::DumpRegion(const G4String& rname) const
921{
922 kernel->DumpRegion(rname);
923}
924
926{
927 kernel->DumpRegion(region);
928}
929
930#include "G4HCofThisEvent.hh"
933#include "G4ParticleTable.hh"
934#include "G4ProcessManager.hh"
935#include "G4ScoringManager.hh"
937#include "G4VHitsCollection.hh"
938#include "G4VScoringMesh.hh"
939
940#include "G4ScoringBox.hh"
941#include "G4ScoringCylinder.hh"
942
944{
945 using MeshShape = G4VScoringMesh::MeshShape;
946
948 if(!ScM)
949 return;
950
951 G4int nPar = ScM->GetNumberOfMesh();
952 if(nPar < 1)
953 return;
954
957 for(G4int iw = 0; iw < nPar; iw++)
958 {
959 G4VScoringMesh* mesh = ScM->GetMesh(iw);
962 G4VPhysicalVolume* pWorld = nullptr;
963 if(mesh->GetShape() != MeshShape::realWorldLogVol)
964 {
965 pWorld =
967 ScM->GetWorldName(iw));
968 if(!pWorld)
969 {
970 pWorld =
972 ScM->GetWorldName(iw));
973 pWorld->SetName(ScM->GetWorldName(iw));
974
975 G4ParallelWorldProcess* theParallelWorldProcess =
977 if(theParallelWorldProcess)
978 {
979 theParallelWorldProcess->SetParallelWorld(ScM->GetWorldName(iw));
980 }
981 else
982 {
983 theParallelWorldProcess =
985 mesh->SetParallelWorldProcess(theParallelWorldProcess);
986 theParallelWorldProcess->SetParallelWorld(ScM->GetWorldName(iw));
987
988 theParticleIterator->reset();
989 while((*theParticleIterator)())
990 {
991 G4ParticleDefinition* particle = theParticleIterator->value();
992 G4ProcessManager* pmanager = particle->GetProcessManager();
993 if(pmanager)
994 {
995 pmanager->AddProcess(theParallelWorldProcess);
996 if(theParallelWorldProcess->IsAtRestRequired(particle))
997 {
998 pmanager->SetProcessOrdering(theParallelWorldProcess, idxAtRest,
999 9900);
1000 }
1001 pmanager->SetProcessOrderingToSecond(theParallelWorldProcess,
1002 idxAlongStep);
1003 pmanager->SetProcessOrdering(theParallelWorldProcess, idxPostStep,
1004 9900);
1005 }
1006 }
1007 }
1008 theParallelWorldProcess->SetLayeredMaterialFlag(mesh->LayeredMassFlg());
1009 }
1010 }
1011 mesh->Construct(pWorld);
1012 }
1013
1015}
1016
1018{
1020 {
1023 }
1024
1026 if(!ScM)
1027 return;
1028 G4int nPar = ScM->GetNumberOfMesh();
1029 if(nPar < 1)
1030 return;
1031
1033 if(!HCE)
1034 return;
1035 G4int nColl = HCE->GetCapacity();
1036 for(G4int i = 0; i < nColl; i++)
1037 {
1038 G4VHitsCollection* HC = HCE->GetHC(i);
1039 if(HC)
1040 ScM->Accumulate(HC);
1041 }
1042}
1043
1044#include "G4LogicalVolume.hh"
1045#include "G4SmartVoxelHeader.hh"
1046#include "G4SmartVoxelStat.hh"
1047#include "G4VPhysicalVolume.hh"
1048
1050{
1051 G4LogicalVolume* pMotherL = pPhys->GetMotherLogical();
1052 if(pMotherL)
1053 ReOptimize(pMotherL);
1054}
1055
1057{
1058 G4Timer localtimer;
1059 if(verboseLevel > 1)
1060 {
1061 localtimer.Start();
1062 }
1063 G4SmartVoxelHeader* header = pLog->GetVoxelHeader();
1064 delete header;
1065 header = new G4SmartVoxelHeader(pLog);
1066 pLog->SetVoxelHeader(header);
1067 if(verboseLevel > 1)
1068 {
1069 localtimer.Stop();
1070 G4SmartVoxelStat stat(pLog, header, localtimer.GetSystemElapsed(),
1071 localtimer.GetUserElapsed());
1072 G4cout << G4endl << "Voxelisation of logical volume <" << pLog->GetName()
1073 << ">" << G4endl;
1074 G4cout << " heads : " << stat.GetNumberHeads()
1075 << " - nodes : " << stat.GetNumberNodes()
1076 << " - pointers : " << stat.GetNumberPointers() << G4endl;
1077 G4cout << " Memory used : " << (stat.GetMemoryUse() + 512) / 1024
1078 << "k - total time : " << stat.GetTotalTime()
1079 << " - system time : " << stat.GetSysTime() << G4endl;
1080 }
1081}
1082
1084{
1085 userDetector = userInit;
1086}
1087
1089{
1090 physicsList = userInit;
1091 kernel->SetPhysics(userInit);
1092}
1093
1095 G4UserWorkerInitialization* /*userInit*/)
1096{
1098 "G4RunManager::SetUserInitialization()", "Run3001", FatalException,
1099 "Base-class G4RunManager cannot take G4UserWorkerInitialization. Use "
1100 "G4MTRunManager.");
1101}
1102
1105{
1107 "G4RunManager::SetUserThreadInitialization()", "Run3001", FatalException,
1108 "Base-class G4RunManager cannot take G4UserWorkerThreadInitialization. "
1109 "Use G4MTRunManager.");
1110}
1111
1113{
1114 userActionInitialization = userInit;
1116}
1117
1119{
1120 userRunAction = userAction;
1121}
1122
1124{
1125 userPrimaryGeneratorAction = userAction;
1126}
1127
1129{
1130 eventManager->SetUserAction(userAction);
1131 userEventAction = userAction;
1132}
1133
1135{
1136 eventManager->SetUserAction(userAction);
1137 userStackingAction = userAction;
1138}
1139
1141{
1142 eventManager->SetUserAction(userAction);
1143 userTrackingAction = userAction;
1144}
1145
1147{
1148 eventManager->SetUserAction(userAction);
1149 userSteppingAction = userAction;
1150}
1151
1153{
1154 if(prop)
1155 {
1156 G4UImanager::GetUIpointer()->ApplyCommand("/run/geometryModified");
1157 }
1158 else
1159 {
1161 }
1162}
1163
1164#include "G4AssemblyStore.hh"
1165#include "G4GeometryManager.hh"
1166#include "G4LogicalVolumeStore.hh"
1167#include "G4PhysicalVolumeStore.hh"
1168#include "G4RegionStore.hh"
1169#include "G4SolidStore.hh"
1170
1172{
1173 if(destroyFirst && G4Threading::IsMasterThread())
1174 {
1175 if(verboseLevel > 0)
1176 {
1177 G4cout << "#### Assemblies, Volumes and Solids Stores are wiped out."
1178 << G4endl;
1179 }
1185
1186 // remove all logical volume pointers from regions
1187 // exception: world logical volume pointer must be kept
1189 std::vector<G4Region*>::iterator rItr;
1190 for(rItr = regionStore->begin(); rItr != regionStore->end(); rItr++)
1191 {
1192 if((*rItr)->GetName() == "DefaultRegionForTheWorld")
1193 continue;
1194 // if((*rItr)->GetName()=="DefaultRegionForParallelWorld") continue;
1195 std::vector<G4LogicalVolume*>::iterator lvItr =
1196 (*rItr)->GetRootLogicalVolumeIterator();
1197 for(size_t iRLV = 0; iRLV < (*rItr)->GetNumberOfRootVolumes(); iRLV++)
1198 {
1199 (*rItr)->RemoveRootLogicalVolume(*lvItr, false);
1200 lvItr++;
1201 }
1202 if(verboseLevel > 0)
1203 {
1204 G4cout << "#### Region <" << (*rItr)->GetName() << "> is cleared."
1205 << G4endl;
1206 }
1207 }
1208
1209 // clear transportation manager
1212 }
1213 if(prop)
1214 {
1215 G4UImanager::GetUIpointer()->ApplyCommand("/run/reinitializeGeometry");
1216 }
1217 else
1218 {
1220 geometryInitialized = false;
1221 // Notify the VisManager as well
1223 {
1225 if(pVVisManager)
1226 pVVisManager->GeometryHasChanged();
1227 }
1228 }
1229}
1230
1231//---------------------------------------------------------------------------//
1232
1233void G4RunManager::ConfigureProfilers(int argc, char** argv)
1234{
1235 std::vector<std::string> _args;
1236 for(int i = 0; i < argc; ++i)
1237 _args.push_back(argv[i]);
1238 ConfigureProfilers(_args);
1239}
1240
1241//---------------------------------------------------------------------------//
1242
1243void G4RunManager::ConfigureProfilers(const std::vector<std::string>& args)
1244{
1245#ifdef GEANT4_USE_TIMEMORY
1246 // parse command line if arguments were passed
1248#else
1249 G4ConsumeParameters(args);
1250#endif
1251}
1252
1253//---------------------------------------------------------------------------//
1254
1255#if !defined(GEANT4_USE_TIMEMORY)
1256# define TIMEMORY_WEAK_PREFIX
1257# define TIMEMORY_WEAK_POSTFIX
1258#endif
1259
1260//---------------------------------------------------------------------------//
1261
1262extern "C"
1263{
1264 // this allows the default setup to be overridden by linking
1265 // in an custom extern C function into the application
1268
1269 extern void G4ProfilerInit(void);
1270
1271 // this gets executed when the library gets loaded
1273 {
1274#ifdef GEANT4_USE_TIMEMORY
1276
1277 // guard against re-initialization
1278 static bool _once = false;
1279 if(_once)
1280 return;
1281 _once = true;
1282
1283 puts(">>> G4RunProfilerInit <<<");
1284
1285 using RunProfilerConfig = G4ProfilerConfig<G4ProfileType::Run>;
1286 using EventProfilerConfig = G4ProfilerConfig<G4ProfileType::Event>;
1287 using TrackProfilerConfig = G4ProfilerConfig<G4ProfileType::Track>;
1288 using StepProfilerConfig = G4ProfilerConfig<G4ProfileType::Step>;
1289 using UserProfilerConfig = G4ProfilerConfig<G4ProfileType::User>;
1290
1291 //
1292 // these are the default functions for evaluating whether
1293 // to start profiling
1294 //
1295 RunProfilerConfig::GetFallbackQueryFunctor() = [](const G4Run* _run) {
1296 return G4Profiler::GetEnabled(G4ProfileType::Run) && _run;
1297 };
1298
1299 EventProfilerConfig::GetFallbackQueryFunctor() = [](const G4Event* _event) {
1300 return G4Profiler::GetEnabled(G4ProfileType::Event) && _event;
1301 };
1302
1303 TrackProfilerConfig::GetFallbackQueryFunctor() = [](const G4Track* _track) {
1304 return G4Profiler::GetEnabled(G4ProfileType::Track) && _track &&
1305 _track->GetDynamicParticle();
1306 };
1307
1308 StepProfilerConfig::GetFallbackQueryFunctor() = [](const G4Step* _step) {
1309 return G4Profiler::GetEnabled(G4ProfileType::Step) && _step &&
1310 _step->GetTrack();
1311 };
1312
1313 UserProfilerConfig::GetFallbackQueryFunctor() =
1314 [](const std::string& _user) {
1315 return G4Profiler::GetEnabled(G4ProfileType::User) && !_user.empty();
1316 };
1317
1318 //
1319 // these are the default functions which encode the profiling label.
1320 // Will not be called unless the query returned true
1321 //
1322 RunProfilerConfig::GetFallbackLabelFunctor() = [](const G4Run* _run) {
1323 return TIMEMORY_JOIN('/', "G4Run", _run->GetRunID());
1324 };
1325
1326 EventProfilerConfig::GetFallbackLabelFunctor() =
1327 [](const G4Event* _event) -> std::string {
1329 return TIMEMORY_JOIN('/', "G4Event", _event->GetEventID());
1330 else
1331 return "G4Event";
1332 };
1333
1334 TrackProfilerConfig::GetFallbackLabelFunctor() = [](const G4Track* _track) {
1335 auto pdef = _track->GetDynamicParticle()->GetParticleDefinition();
1336 return TIMEMORY_JOIN('/', "G4Track", pdef->GetParticleName());
1337 };
1338
1339 StepProfilerConfig::GetFallbackLabelFunctor() = [](const G4Step* _step) {
1340 auto pdef = _step->GetTrack()->GetParticleDefinition();
1341 return TIMEMORY_JOIN('/', "G4Step", pdef->GetParticleName());
1342 };
1343
1344 UserProfilerConfig::GetFallbackLabelFunctor() =
1345 [](const std::string& _user) { return _user; };
1346
1347 using RunTool = typename RunProfilerConfig::type;
1348 using EventTool = typename EventProfilerConfig::type;
1349 using TrackTool = typename TrackProfilerConfig::type;
1350 using StepTool = typename StepProfilerConfig::type;
1351 using UserTool = typename UserProfilerConfig::type;
1352
1353 RunProfilerConfig::GetFallbackToolFunctor() =
1354 [](const std::string& _label) { return new RunTool{ _label }; };
1355
1356 EventProfilerConfig::GetFallbackToolFunctor() =
1357 [](const std::string& _label) { return new EventTool{ _label }; };
1358
1359 TrackProfilerConfig::GetFallbackToolFunctor() =
1360 [](const std::string& _label) {
1361 return new TrackTool(_label, tim::scope::config(tim::scope::flat{}));
1362 };
1363
1364 StepProfilerConfig::GetFallbackToolFunctor() =
1365 [](const std::string& _label) {
1366 return new StepTool(_label, tim::scope::config(tim::scope::flat{}));
1367 };
1368
1369 UserProfilerConfig::GetFallbackToolFunctor() =
1370 [](const std::string& _label) { return new UserTool(_label); };
1371
1372 auto comps = "wall_clock, cpu_clock, cpu_util, peak_rss";
1373 auto run_env_comps =
1374 tim::get_env<std::string>("G4PROFILE_RUN_COMPONENTS", comps);
1375 auto event_env_comps =
1376 tim::get_env<std::string>("G4PROFILE_EVENT_COMPONENTS", comps);
1377 auto track_env_comps =
1378 tim::get_env<std::string>("G4PROFILE_TRACK_COMPONENTS", comps);
1379 auto step_env_comps =
1380 tim::get_env<std::string>("G4PROFILE_STEP_COMPONENTS", comps);
1381 auto user_env_comps =
1382 tim::get_env<std::string>("G4PROFILE_USER_COMPONENTS", comps);
1383
1384 tim::configure<G4RunProfiler>(run_env_comps);
1385 tim::configure<G4EventProfiler>(event_env_comps);
1386 tim::configure<G4TrackProfiler>(track_env_comps);
1387 tim::configure<G4StepProfiler>(step_env_comps);
1388 tim::configure<G4UserProfiler>(user_env_comps);
1389#endif
1390 }
1391} // extern "C"
1392
1393//---------------------------------------------------------------------------//
1394
1395#ifdef GEANT4_USE_TIMEMORY
1396namespace
1397{
1398 static bool profiler_is_initialized = (G4RunProfilerInit(), true);
1399}
1400#endif
1401
1402//---------------------------------------------------------------------------//
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:35
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:538
#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 BeamOn(G4int n_event, const char *macroFile=0, G4int n_select=-1)
G4UserEventAction * userEventAction
void ReinitializeGeometry(G4bool destroyFirst=false, G4bool prop=true)
virtual void DoEventLoop(G4int n_event, const char *macroFile=0, G4int n_select=-1)
virtual void rndmSaveThisEvent()
virtual void DeleteUserInitializations()
G4int runIDCounter
G4RunManagerKernel * kernel
G4int verboseLevel
G4Run * currentRun
virtual G4bool ConfirmBeamOnCondition()
static G4RunManager * GetRunManager()
Definition: G4RunManager.cc:84
virtual void AbortEvent()
virtual void rndmSaveThisRun()
virtual void InitializePhysics()
G4DCtable * DCtable
G4String randomNumberStatusForThisRun
G4bool runAborted
G4String msgText
static G4bool IfGeometryHasBeenDestroyed()
Definition: G4RunManager.cc:73
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 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()
virtual void InitializeEventLoop(G4int n_event, const char *macroFile=0, G4int n_select=-1)
G4UserSteppingAction * userSteppingAction
Definition: G4Run.hh:49
void SetHCtable(G4HCtable *HCtbl)
Definition: G4Run.hh:106
G4int GetRunID() const
Definition: G4Run.hh:82
void StoreEvent(G4Event *evt)
Definition: G4Run.cc:74
virtual void RecordEvent(const G4Event *)
Definition: G4Run.cc:62
void SetNumberOfEventToBeProcessed(G4int n_ev)
Definition: G4Run.hh:102
void SetRunID(G4int id)
Definition: G4Run.hh:101
void SetDCtable(G4DCtable *DCtbl)
Definition: G4Run.hh:107
void SetRandomNumberStatus(G4String &st)
Definition: G4Run.hh:108
G4HCofThisEvent * PrepareNewEvent()
Definition: G4SDManager.cc:109
static G4SDManager * GetSDMpointerIfExist()
Definition: G4SDManager.cc:48
G4HCtable * GetHCtable() const
Definition: G4SDManager.hh:103
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:68
static G4SolidStore * GetInstance()
const G4ApplicationState & GetCurrentState() const
static G4StateManager * GetStateManager()
G4bool SetNewState(const G4ApplicationState &requestedState)
Definition: G4Step.hh:62
str_size index(const char *, G4int pos=0) const
void Stop()
G4double GetSystemElapsed() const
Definition: G4Timer.cc:132
G4double GetUserElapsed() const
Definition: G4Timer.cc:143
void Start()
G4VPhysicalVolume * GetParallelWorld(const G4String &worldName)
static G4TransportationManager * GetTransportationManager()
G4VPhysicalVolume * IsWorldExisting(const G4String &worldName)
G4int ApplyCommand(const char *aCommand)
Definition: G4UImanager.cc:485
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)
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:187
#define G4ThreadLocal
Definition: tls.hh:77