g4system
Loading...
Searching...
No Matches
g4world.cc
Go to the documentation of this file.
1// g4world.cc : implementation of the Geant4 world builder and material initialization.
11
12// gemc
13#include "g4world.h"
14#include "gfactory.h"
15
16// g4system
17#include "g4system_options.h"
18#include "g4systemConventions.h"
19#include "gsystemConventions.h"
22
23
24// c++
25#include <vector>
26
27G4World::G4World(const GWorld *gworld, const std::shared_ptr<GOptions> &gopts)
28 : GBase(gopts, G4SYSTEM_LOGGER) {
29 auto gsystemMap = gworld->getSystemsMap();
30
31 // Phase 1: create and initialize a Geant4 object factory for each system.
32 // The factory provides solid/logical/physical creation for volumes in that system.
33 createG4SystemFactory(gopts,
34 gsystemMap,
35 gopts->getOptionalScalarString("useBackupMaterial"),
36 gopts->getRequiredScalarInt("check_overlaps")
37 );
38
39 // Phase 2: build all materials across systems, resolving dependencies iteratively.
40 buildMaterials(gsystemMap);
41
42 // Phase 3: ensure common isotopes/elements/materials exist (used by typical configurations).
43 buildDefaultMaterialsElementsAndIsotopes();
44
45 // Phase 4: build volumes. Some volumes depend on mothers that may not exist yet,
46 // so we iterate until the remaining list becomes empty or the dependency resolution stalls.
47 std::vector<GVolume *> thisIterationRemainingVolumes;
48 unsigned long previousRemainingVolumes = 0;
49
50 do {
51 thisIterationRemainingVolumes.clear();
52
53 // Loop over all systems and attempt to build all volumes in each system.
54 for (auto &[systemName, gsystem]: *gsystemMap) {
55 const std::string defaultG4Factory = g4FactoryNameFromSystemFactory(gsystem->getFactoryName());
56
57 for (auto &[volumeName, gvolumePtr]: gsystem->getGVolumesMap()) {
58 auto *gvolume = gvolumePtr.get();
59 const std::string g4Factory = gvolume->getType() == gsystem::GSYSTEMCADTFACTORYLABEL
61 : defaultG4Factory;
62 auto objectsFactory = get_factory(g4Factory);
63
64 // Try to build; if dependencies are missing, remember it for the next iteration.
65 if (!build_g4volume(gvolume, objectsFactory)) {
66 // Only track volumes that are meant to exist; nonexistent volumes are skipped quietly.
67 if (gvolume->getExistence()) {
68 log->info(2, " >> adding volumeName <", volumeName, "> to the list of remaining volumes");
69 thisIterationRemainingVolumes.push_back(gvolume);
70 }
71 }
72 }
73
74 // Diagnostic listing of the volumes that could not be built due to missing mothers.
75 if (!thisIterationRemainingVolumes.empty()) {
76 log->info(2, "G4World: ", systemName, " : ",
77 thisIterationRemainingVolumes.size(),
78 " remaining motherless g4volumes to be built:");
79 for (auto *gvolumeLeft: thisIterationRemainingVolumes) {
80 log->info(2, "G4World: ", gvolumeLeft->getName(),
81 " with mother <", gvolumeLeft->getG4MotherName(), "> ");
82 }
83 }
84 }
85
86 // Dependency-stall detection: error only when the remaining count fails to strictly
87 // decrease across iterations (a strictly smaller count means progress was made).
88 if (previousRemainingVolumes != 0 && !thisIterationRemainingVolumes.empty() &&
89 thisIterationRemainingVolumes.size() >= previousRemainingVolumes) {
90 for (auto *gvolumeLeft: thisIterationRemainingVolumes) {
91 log->warning(" >> ", gvolumeLeft->getName(),
92 " with mother <", gvolumeLeft->getG4MotherName(), "> not built");
93 }
95 "dependencies are not being resolved: their number should diminish. "
96 "Above are the outstanding gvolumes");
97 }
98 previousRemainingVolumes = thisIterationRemainingVolumes.size();
99 } while (!thisIterationRemainingVolumes.empty());
100
101 // Phase 5: build optical surfaces (mirrors), now that all logical/physical volumes exist.
102 buildOpticalSurfaces(gsystemMap);
103
104 // Optional diagnostic output: list known materials from the Geant4 NIST manager.
105 if (gopts->getSwitch("showPredefinedMaterials")) { G4NistManager::Instance()->ListMaterials("all"); }
106
107 // Optional diagnostic output: print materials used in the simulation.
108 if (gopts->getSwitch("printSystemsMaterials")) {
109 auto matTable = (G4MaterialTable *) G4Material::GetMaterialTable();
110 for (auto thisMat: *matTable) {
111 log->info(0, 2, "G4World: GEMC Material: <", thisMat->GetName(), ">, density: ",
112 thisMat->GetDensity() / (CLHEP::g / CLHEP::cm3), "g/cm3");
113
114 // Print each component; negative/zero values mean "fractional mass", positive means "number of atoms".
115 for (auto &[material, component]: thisMat->GetMatComponents()) {
116 if (component > 0.0) {
117 log->info(0, "element", material->GetName(), "number of atoms: ", component);
118 } else { log->info(0, "element", material->GetName(), "fractional mass: ", component); }
119 }
120 }
121 }
122}
123
124/*──────────────────────── look-ups ──────────────────────────*/
125
126const G4Volume *G4World::getG4Volume(const std::string &volumeName) const {
127 auto it = g4volumesMap.find(volumeName);
128 return (it != g4volumesMap.end()) ? it->second : nullptr;
129}
130
131void G4World::setFieldManagerForVolume(const std::string &volumeName,
132 G4FieldManager *fm,
133 bool forceToAllDaughters) {
134 auto it = g4volumesMap.find(volumeName);
135 if (it != g4volumesMap.end()) it->second->setFieldManager(fm, forceToAllDaughters);
136}
137
138// ---- g4FactoryNameFromSystemFactory -----------------------------------------------------------
139std::string G4World::g4FactoryNameFromSystemFactory(const std::string &factory) const {
140 // Map GEMC system factory labels to g4system object factory labels.
141 if (factory == gsystem::GSYSTEMASCIIFACTORYLABEL ||
146 "gsystemFactory factory <", factory, "> is not mapped to any G4SystemFactory");
147 }
148}
149
150void G4World::createG4SystemFactory(const std::shared_ptr<GOptions> &gopts,
151 SystemMap *gsystemsMap,
152 const std::optional<std::string> &backup_material,
153 int check_overlaps) {
154 // Instantiate a manager used to register and create factories.
155 GManager manager(gopts);
156
157 // Creating the native factory no matter what (it is the default for ASCII/SQLite/MySQL systems).
158 log->info(2, "G4World: registering default factory <", g4system::G4SYSTEMNATFACTORY, ">");
159 manager.RegisterObjectFactory<G4NativeSystemFactory>(g4system::G4SYSTEMNATFACTORY, gopts);
160
161 // Register factories based on the system factory label, then create/initialize them lazily.
162 for (auto &[gsystemName, gsystem]: *gsystemsMap) {
163 std::string factory = gsystem->getFactoryName();
164 std::string g4Factory = g4FactoryNameFromSystemFactory(factory);
165
166 log->info(2, "G4World: creating factory <", g4Factory, "> to for system <", gsystemName, ">");
167
168 // Register needed factory types:
169 // this will always be false for the default native label because it was registered above.
172 if (g4systemFactory.find(g4Factory) == g4systemFactory.end()) {
173 manager.RegisterObjectFactory<G4NativeSystemFactory>(g4Factory, gopts);
174 }
175 } else if (factory == gsystem::GSYSTEMCADTFACTORYLABEL) {
176 if (g4systemFactory.find(g4system::G4SYSTEMCADFACTORY) == g4systemFactory.end()) {
177 manager.RegisterObjectFactory<G4CadSystemFactory>(g4Factory, gopts);
178 }
179 }
180
181 // Create and initialize the concrete factory instance once per label.
182 if (g4systemFactory.find(g4Factory) == g4systemFactory.end()) {
183 g4systemFactory[g4Factory] = manager.CreateObject<G4ObjectsFactory>(g4Factory);
184 g4systemFactory[g4Factory]->initialize_context(check_overlaps, backup_material);
185 }
186
187 // SQLite and text systems may mix native and CAD rows. Register the CAD object factory when
188 // any volume in this system declares solid=CAD, independently of the system loading factory.
189 for (const auto &[volumeName, gvolume]: gsystem->getGVolumesMap()) {
190 if (gvolume->getType() != gsystem::GSYSTEMCADTFACTORYLABEL ||
191 g4systemFactory.find(g4system::G4SYSTEMCADFACTORY) != g4systemFactory.end()) {
192 continue;
193 }
194
195 manager.RegisterObjectFactory<G4CadSystemFactory>(g4system::G4SYSTEMCADFACTORY, gopts);
196 g4systemFactory[g4system::G4SYSTEMCADFACTORY] =
197 manager.CreateObject<G4ObjectsFactory>(g4system::G4SYSTEMCADFACTORY);
198 g4systemFactory[g4system::G4SYSTEMCADFACTORY]->initialize_context(check_overlaps, backup_material);
199 }
200 }
201}
202
203void G4World::buildMaterials(SystemMap *system_map) {
204 // Build materials across all systems. Some materials may depend on other materials/elements,
205 // so we iterate until all dependencies are resolved or the resolution stalls.
206 std::vector<GMaterial *> thisIterationRemainingMaterials;
207 unsigned long previousRemainingMaterials = 0;
208 do {
209 thisIterationRemainingMaterials.clear();
210
211 for (const auto &[systemName, system]: *system_map) {
212 // Loop over the material map in each system and attempt to build each material.
213 for (const auto &[gmaterialName, gmaterialPtr]: system->getGMaterialMap()) {
214 if (createG4Material(gmaterialPtr) == false) {
215 thisIterationRemainingMaterials.push_back(gmaterialPtr.get());
216 }
217 }
218 }
219
220 // Dependency-stall detection for material building: error only when the remaining
221 // count fails to strictly decrease across iterations.
222 if (previousRemainingMaterials != 0 && !thisIterationRemainingMaterials.empty() &&
223 thisIterationRemainingMaterials.size() >= previousRemainingMaterials) {
224 for (auto &gmaterialLeft: thisIterationRemainingMaterials) { log->warning(gmaterialLeft->getName()); }
226 "Dependencies are not being resolved: their number should diminish. Above are the Outstanding gmaterials");
227 }
228 previousRemainingMaterials = thisIterationRemainingMaterials.size();
229 } while (!thisIterationRemainingMaterials.empty());
230}
231
232bool G4World::build_g4volume(const GVolume *s, G4ObjectsFactory *objectsFactory) {
233 log->info(2, "G4World: using factory <", objectsFactory->className(),
234 "> to build g4volume <", s->getG4Name(), ">");
235
236 return objectsFactory->build_g4volume(s, &g4volumesMap);
237}
Factory that converts CAD files (PLY / STL) into Geant4 tessellated solids via CADMesh.
Base class orchestrating the conversion of a GVolume into a Geant4 representation.
bool build_g4volume(const GVolume *s, std::unordered_map< std::string, G4Volume * > *g4s)
Build (or retrieve) solid, logical, and physical volumes for a given GVolume.
virtual std::string_view className() const =0
Short, human-readable factory name for logging.
Convenience container holding a Geant4 solid, logical, and physical volume.
Definition g4volume.h:52
void setFieldManager(G4FieldManager *fm, bool forceToAllDaughters)
Attach a G4FieldManager to the stored logical volume, if present.
Definition g4volume.cc:28
G4World(const GWorld *gworld, const std::shared_ptr< GOptions > &gopts)
Construct and build the Geant4 world from a GEMC world.
Definition g4world.cc:27
void setFieldManagerForVolume(const std::string &volumeName, G4FieldManager *fm, bool forceToAllDaughters)
Attach a G4FieldManager to the logical volume of a named volume.
Definition g4world.cc:131
G4ObjectsFactory * get_factory(const std::string &factoryName)
Retrieve a registered factory by name.
Definition g4world.h:128
const G4Volume * getG4Volume(const std::string &volumeName) const
Return the G4Volume wrapper for a volume name.
Definition g4world.cc:126
GBase(const std::shared_ptr< GOptions > &gopt, std::string logger_name="")
std::shared_ptr< GLogger > log
const std::string & getG4Name() const
SystemMap * getSystemsMap() const
Factory that builds Geant4 native primitive solids (G4Box, G4Cons, G4Trap, ...) from GEMC GVolume rec...
Conventions, labels, and error codes used by the g4system geometry/material layer.
Option definitions for the g4system module (geometry/material construction layer).
constexpr const char * G4SYSTEM_LOGGER
Logger name used by the module-level builder (e.g. G4World).
High-level builder that turns a GEMC world description into Geant4 geometry.
std::map< std::string, SystemPtr > SystemMap
constexpr char G4SYSTEMNATFACTORY[]
constexpr char G4SYSTEMCADFACTORY[]
constexpr int ERR_G4SYSTEMFACTORYNOTFOUND
A required Geant4 system factory was not found/mapped.
constexpr int ERR_G4DEPENDENCIESNOTSOLVED
Geometry/material dependencies could not be resolved.
constexpr char GSYSTEMCADTFACTORYLABEL[]
constexpr char GSYSTEMMYSQLTFACTORYLABEL[]
constexpr char GSYSTEMSQLITETFACTORYLABEL[]
constexpr char GSYSTEMASCIIFACTORYLABEL[]