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