utilities
Loading...
Searching...
No Matches
gemcUtilities.cc
Go to the documentation of this file.
1#include "gemcUtilities.h"
2#include "gemcConventions.h"
3
4// Implementation notes:
5// - Doxygen documentation is kept authoritative in gemcUtilities.h.
6// - This file only provides brief, non-Doxygen comments to clarify intent and flow.
7
8// geant4 headers
9#include "G4Threading.hh"
10#include "G4UImanager.hh"
11#include "G4UnitsTable.hh"
12
13// gemc
14#include "glogger.h"
15#include "gtouchable.h"
16#include "gutilities.h"
17#include "g4SceneProperties.h"
18#include "g4display_options.h"
19
20#include <algorithm>
21#include <cctype>
22#include <cstdlib>
23#include <iostream>
24#include <sstream>
25
26namespace {
27bool scalarOptionIsTrue(const std::shared_ptr<GOptions>& gopts, const std::string& name) {
28 if (gopts == nullptr) { return false; }
29
30 std::string value = gopts->getScalarString(name);
31 std::transform(value.begin(), value.end(), value.begin(),
32 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
33
34 if (value == "true" || value == "yes" || value == "on" || value == "1") {
35 return true;
36 }
37 if (value == "false" || value == "no" || value == "off" || value == "0" || value == "null") {
38 return false;
39 }
40
41 std::cerr << FATALERRORL << "The option " << name
42 << " accepts only true/false/yes/no/on/off/1/0." << std::endl;
43 std::exit(EC__NOOPTIONFOUND);
44}
45
46std::string rootExtentForFieldCommand(const std::shared_ptr<GOptions>& gopts) {
47 if (gopts == nullptr) { return ""; }
48
49 std::string rootDefinition = gopts->getScalarString("root");
50 for (auto& c : rootDefinition) {
51 if (c == ',') { c = ' '; }
52 }
53
54 const auto tokens = gutilities::getStringVectorFromString(rootDefinition);
55 if (tokens.size() < 5 || tokens[0] != "G4Box") { return ""; }
56
57 const double dx = gutilities::getG4Number(tokens[1]);
58 const double dy = gutilities::getG4Number(tokens[2]);
59 const double dz = gutilities::getG4Number(tokens[3]);
60 if (dx <= 0 || dy <= 0 || dz <= 0) { return ""; }
61
62 std::ostringstream command;
63 command << "/vis/set/extentForField "
64 << -dx << " " << dx << " "
65 << -dy << " " << dy << " "
66 << -dz << " " << dz << " mm";
67 return command.str();
68}
69}
70
71namespace gemc {
72 // return the number of cores from options.
73 // if 0 is given, returns max number of available cores
74 int get_nthreads(const std::shared_ptr<GOptions>& gopts, const std::shared_ptr<GLogger>& log) {
75 int useThreads = gopts->getScalarInt("nthreads");
76
77 // Geant4 provides a platform-specific core count helper.
78 int ncores = G4Threading::G4GetNumberOfCores();
79
80 // Clamp user request:
81 // - 0 means "use all available cores"
82 // - values larger than available cores are clamped
83 if (useThreads == 0 || useThreads > ncores) useThreads = ncores;
84
85 log->info(0, "Using ", useThreads, " threads out of ", ncores, " available cores.");
86
87 return useThreads;
88 }
89
90 std::vector<std::string> verbosity_commands([[maybe_unused]] const std::shared_ptr<GOptions>& gopts,
91 [[maybe_unused]] const std::shared_ptr<GLogger>& log) {
92 std::vector<std::string> cmds;
93
94 // --- Always-quiet commands ---
95 // These commands reduce Geant4 output noise for typical production runs.
96 cmds.emplace_back("/control/verbose 0");
97 cmds.emplace_back("/hit/verbose 0");
98
99 cmds.emplace_back("/process/verbose 0");
100 cmds.emplace_back("/process/setVerbose 0 all");
101 cmds.emplace_back("/process/had/verbose 0");
102 cmds.emplace_back("/process/had/deex/verbose 0");
103 cmds.emplace_back("/process/had/cascade 0");
104 cmds.emplace_back("/process/em/verbose 0");
105 cmds.emplace_back("/process/eLoss/verbose 0");
106
107 cmds.emplace_back("/tracking/verbose 0");
108 cmds.emplace_back("/geometry/navigator/verbose 0");
109
110 cmds.emplace_back("/event/verbose 0");
111 cmds.emplace_back("/event/stack/verbose 0");
112
113 cmds.emplace_back("/cuts/verbose 0");
114
115 cmds.emplace_back("/run/particle/verbose 0");
116 cmds.emplace_back("/run/verbose 0");
117
118 cmds.emplace_back("/material/verbose 0");
119
120 cmds.emplace_back("/vis/verbose 0");
121 cmds.emplace_back("/particle/verbose 0");
122
123 // cmds.emplace_back("/control/cout/ignoreInitializationCout 1");
124 // cmds.emplace_back("/control/cout/useBuffer 1"); // keep MT output tidy?
125
126 return cmds;
127 }
128
129 std::vector<std::string> initial_commands(const std::shared_ptr<GOptions>& gopts,
130 [[maybe_unused]] const std::shared_ptr<GLogger>& log,
131 bool configure_visualization) {
132 // check_overlaps is typically provided by the Geant4 system options set.
133 auto check_overlaps = gopts->getScalarInt("check_overlaps"); // notice: from g4system options
134 auto gui = gopts->getSwitch("gui");
135 auto g4view = g4display::getG4View(gopts);
136
137 std::vector<std::string> cmds;
138
139 // Batch mode: optionally schedule geometry overlap checks before initialization.
140 // Geant4 overlap checks use the current "/geometry/test/..." configuration.
141 if (check_overlaps == 2) {
142 log->info(0, "Running /geometry/test/run with 50 points.");
143 cmds.emplace_back("/geometry/test/resolution 50");
144 cmds.emplace_back("/geometry/test/run");
145 }
146 else if (check_overlaps >= 100) {
147 log->info(0, "Running /geometry/test/run with ", check_overlaps, " points.");
148 cmds.emplace_back("/geometry/test/resolution " + std::to_string(check_overlaps));
149 cmds.emplace_back("/geometry/test/run");
150 }
151
152 // In GUI mode without startup geometry, defer initialization until the setup
153 // tab has selected and loaded a real system. Initializing the synthetic ROOT
154 // world here leaves stale world/vis state behind after setup-tab reloads.
155 if (gui && !configure_visualization) { return cmds; }
156
157 // A re-initialize is required when:
158 // - physics changes
159 // - geometry changes
160 cmds.emplace_back("/run/initialize");
161
162 if (!configure_visualization) return cmds;
163
164 // Create the viewer and its attached scene only after /run/initialize has built the world.
165 G4SceneProperties g4SceneProperties(gopts);
166 for (const auto& command : g4SceneProperties.scene_commands(gopts)) {
167 cmds.emplace_back(command);
168 }
169
170 // If there is no GUI, or no need for batch screenshot, initialization commands are enough.
171 if (!gui && g4view.driver != "TOOLSSG_OFFSCREEN") return cmds;
172
173 // do not draw volumes in batch screenshot
174 if (g4view.driver != "TOOLSSG_OFFSCREEN") {
175 auto g4camera = g4display::getG4Camera(gopts);
176 auto g4light = g4display::getG4Light(gopts);
177 const double toDegrees = 180.0 / M_PI;
178 double thetaValue = gutilities::getG4Number(g4camera.theta) * toDegrees;
179 double phiValue = gutilities::getG4Number(g4camera.phi) * toDegrees;
180 double lightThetaValue = gutilities::getG4Number(g4light.theta) * toDegrees;
181 double lightPhiValue = gutilities::getG4Number(g4light.phi) * toDegrees;
182 if (lightThetaValue == 0.0 && lightPhiValue == 0.0) {
183 lightThetaValue = thetaValue;
184 lightPhiValue = phiValue;
185 }
186
187 // Disable auto refresh and quieten vis messages whilst scene and trajectories are established.
188 cmds.emplace_back("/vis/viewer/set/autoRefresh false");
189 cmds.emplace_back("/vis/viewer/set/viewpointThetaPhi " + std::to_string(thetaValue) + " " + std::to_string(phiValue));
190 cmds.emplace_back("/vis/viewer/set/lightsThetaPhi " + std::to_string(lightThetaValue) + " " + std::to_string(lightPhiValue));
191 }
192
193 // GUI / batch screenshot mode: set up a minimal visualization scene with trajectories and hits.
194 cmds.emplace_back("/vis/scene/add/trajectories smooth");
195 cmds.emplace_back("/vis/modeling/trajectories/create/drawByCharge");
196 cmds.emplace_back("/vis/modeling/trajectories/drawByCharge-0/default/setDrawStepPts true");
197 cmds.emplace_back("/vis/modeling/trajectories/drawByCharge-0/default/setStepPtsSize 2");
198 // Draw optical photons in cyan so they are distinct from other neutral particles.
199 cmds.emplace_back("/vis/modeling/trajectories/create/drawByParticleID");
200 cmds.emplace_back("/vis/modeling/trajectories/drawByParticleID-0/set opticalphoton cyan");
201
202 cmds.emplace_back("/vis/scene/add/hits");
203 cmds.emplace_back("/vis/scene/endOfEventAction accumulate 10000");
204 cmds.push_back("/vis/viewer/set/background " + g4view.background);
205 cmds.push_back("/vis/viewer/set/numberOfCloudPoints " + std::to_string(g4view.cloudPoints));
206 const auto decorations = g4display::getG4Decorations(gopts);
207 for (const auto& command : g4SceneProperties.addSceneDecorations(gopts)) { cmds.emplace_back(command); }
208 for (const auto& command : g4SceneProperties.addSceneTexts(gopts)) { cmds.emplace_back(command); }
209 if (decorations.eventID) { cmds.emplace_back("/vis/scene/add/eventID"); }
210
211 if (scalarOptionIsTrue(gopts, "show_auxiliary_edges")) {
212 cmds.emplace_back("/vis/viewer/set/auxiliaryEdge 1");
213 cmds.emplace_back("/vis/viewer/set/hiddenEdge 1");
214 }
215
216 const int fieldLinePoints = gopts->getScalarInt("show_field_lines");
217 if (fieldLinePoints > 0) {
218 if (const auto extent = rootExtentForFieldCommand(gopts); !extent.empty()) {
219 cmds.emplace_back(extent);
220 }
221 cmds.emplace_back("/vis/scene/add/magneticField " + std::to_string(fieldLinePoints));
222 }
223
224 // do not draw volumes in batch screenshot
225 if (g4view.driver != "TOOLSSG_OFFSCREEN") {
226 // Re-enable refresh and flush once configuration is complete.
227 cmds.emplace_back("/vis/viewer/set/autoRefresh true");
228 cmds.emplace_back("/vis/viewer/flush");
229 }
230
231 // cmds.emplace_back("/tracking/verbose 2");
232 return cmds;
233 }
234
235 // initialize G4MTRunManager
236 void run_manager_commands([[maybe_unused]] const std::shared_ptr<GOptions>& gopts,
237 const std::shared_ptr<GLogger>& log, const std::vector<std::string>& commands) {
238 auto* g4uim = G4UImanager::GetUIpointer();
239
240 // Apply commands sequentially so the UI manager sees the same order as a macro file.
241 for (const auto& cmd : commands) {
242 log->info(2, "Executing UIManager command: ", cmd);
243 g4uim->ApplyCommand(cmd);
244 }
245 }
246
248 new G4UnitDefinition("milligray", "milliGy", "Dose", gemc_units::milligray);
249 new G4UnitDefinition("microgray", "microGy", "Dose", gemc_units::microgray);
250 new G4UnitDefinition("nanogray", "nanoGy", "Dose", gemc_units::nanogray);
251 new G4UnitDefinition("picogray", "picoGy", "Dose", gemc_units::picogray);
252 }
253
254
255#include <unistd.h> // needed for get_pid
256
257 void start_random_engine(const std::shared_ptr<GOptions>& gopts, const std::shared_ptr<GLogger>& log) {
258 auto randomEngineName = gopts->getScalarString("randomEngine");
259 auto seed = gopts->getScalarInt("seed");
260
261 // If the user did not set a seed, derive one using several fast-changing sources.
262 // This helps reduce accidental seed reuse across runs.
263 if (seed == SEEDNOTSET) {
264 auto timed = time(NULL);
265 auto clockd = clock();
266 auto getpidi = getpid();
267 seed = (G4int)( timed - clockd - getpidi );
268 log->info(1, "Using random seed ", seed);
269 } else {
270 log->info(1, "User defined seed ", seed);
271 }
272
273
274 // The names come from the CLHEP library, can be found with
275 // grep ": public HepRandomEngine" *.h $CLHEP_BASE_DIR/include/CLHEP/Random/* | awk -Fclass '{print $2}' | awk -F: '{print $1}'
276 //
277 // Select the engine implementation based on the configured string.
278 if (randomEngineName == "DRand48Engine")
279 G4Random::setTheEngine(new CLHEP::DRand48Engine(seed));
280 else if (randomEngineName == "DualRand")
281 G4Random::setTheEngine(new CLHEP::DualRand(seed));
282 else if (randomEngineName == "Hurd160Engine")
283 G4Random::setTheEngine(new CLHEP::Hurd160Engine(seed));
284 else if (randomEngineName == "HepJamesRandom")
285 G4Random::setTheEngine(new CLHEP::HepJamesRandom(seed));
286 else if (randomEngineName == "MTwistEngine")
287 G4Random::setTheEngine(new CLHEP::MTwistEngine(seed));
288 else if (randomEngineName == "MixMaxRng")
289 G4Random::setTheEngine(new CLHEP::MixMaxRng(seed));
290 else if (randomEngineName == "RandEngine")
291 G4Random::setTheEngine(new CLHEP::RandEngine(seed));
292 else if (randomEngineName == "RanecuEngine")
293 G4Random::setTheEngine(new CLHEP::RanecuEngine(seed));
294 else if (randomEngineName == "Ranlux64Engine")
295 G4Random::setTheEngine(new CLHEP::Ranlux64Engine(seed));
296 else if (randomEngineName == "RanluxEngine")
297 G4Random::setTheEngine(new CLHEP::RanluxEngine(seed));
298 else if (randomEngineName == "RanshiEngine")
299 G4Random::setTheEngine(new CLHEP::RanshiEngine(seed));
300 else if (randomEngineName == "Hurd288Engine")
301 G4Random::setTheEngine(new CLHEP::Hurd288Engine(seed));
302 else if (randomEngineName == "TripleRand")
303 G4Random::setTheEngine(new CLHEP::TripleRand(seed));
304 else { log->error(EC__RANDOMENGINENOTFOUND, "Random engine >", randomEngineName, "< not found. Exiting."); }
305
306 // Apply the seed after selecting the engine so the engine instance is active.
307 log->info(0, "Starting random engine ", randomEngineName, " with seed ", seed);
308 G4Random::setTheSeed(seed);
309 }
310}
std::vector< std::string > addSceneTexts(const std::shared_ptr< GOptions > &gopts)
std::vector< std::string > addSceneDecorations(const std::shared_ptr< GOptions > &gopts)
std::vector< std::string > scene_commands(const std::shared_ptr< GOptions > &gopts)
Conventional constants used by GEMC utility helpers.
Utility helpers for runtime setup, command preparation, and random-engine initialization.
#define EC__NOOPTIONFOUND
#define SEEDNOTSET
Sentinel value used to mark that the random seed has not been explicitly set.
#define EC__RANDOMENGINENOTFOUND
Error code used when the configured random engine name is not recognized.
void define_new_gemc_units()
std::vector< std::string > initial_commands(const std::shared_ptr< GOptions > &gopts, const std::shared_ptr< GLogger > &log, bool configure_visualization)
Build a list of Geant4 UI commands needed at startup.
void start_random_engine(const std::shared_ptr< GOptions > &gopts, const std::shared_ptr< GLogger > &log)
Select and start the random engine, then seed it.
std::vector< std::string > verbosity_commands(const std::shared_ptr< GOptions > &gopts, const std::shared_ptr< GLogger > &log)
Build a list of Geant4 UI commands that reduce verbosity across subsystems.
void run_manager_commands(const std::shared_ptr< GOptions > &gopts, const std::shared_ptr< GLogger > &log, const std::vector< std::string > &commands)
Execute a sequence of Geant4 UI commands through the UI manager.
int get_nthreads(const std::shared_ptr< GOptions > &gopts, const std::shared_ptr< GLogger > &log)
Determine the number of worker threads to use for the run.
#define FATALERRORL
G4Light getG4Light(const std::shared_ptr< GOptions > &gopts)
G4View getG4View(const std::shared_ptr< GOptions > &gopts)
G4Camera getG4Camera(const std::shared_ptr< GOptions > &gopts)
G4Decorations getG4Decorations(const std::shared_ptr< GOptions > &gopts)
constexpr G4double milligray
constexpr G4double nanogray
constexpr G4double microgray
constexpr G4double picogray
double getG4Number(const string &v, bool warnIfNotUnit=false)
vector< std::string > getStringVectorFromString(const std::string &input)