FairShip
Loading...
Searching...
No Matches
geometry_from_file.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4"""Simulate on the geometry of a geometry file (run_simScript.py -g).
5
6The modules build their geometry as usual, from the configuration (ShipGeo)
7stored in the geometry file. Building does more than create volumes: the
8detectors register which volumes are sensitive, and magnets attach their
9fields to volumes, and a geometry file keeps neither. So the run keeps all of
10that and only exchanges the volumes: a GeometrySwap module (make_swap), added last,
11replaces the geometry that was just built by the one stored in the file, before
12Geant4 converts it. Particles are then transported through the stored geometry,
13whatever the current code would build.
14
15The stored geometry may differ from the one the current code builds, for
16example a geometry file written with a modified SBT design. Every volume to
17which a field is attached must exist in the stored geometry, and its name
18must tell which one: the field is copied onto it. The run stops otherwise.
19Fields from field maps are added after the swap, as usual.
20
21Other differences are reported as a warning:
22
23* Sensitive volumes that the stored geometry lacks, e.g. the SBT cells that a
24 design with fewer cells does not have. FairDetector::Initialize() binds
25 sensitive volumes to the geometry given to Geant4 by name; Geant4 VMC gives
26 an unknown name the volume ID 0, which no volume has, so these volumes just
27 record no hits.
28* Passive volumes that the stored geometry lacks, and placements that it lacks
29 or adds.
30* Volumes of the stored geometry that the current code does not build. These
31 are passive in this run, so the warning names those made of the medium of
32 a sensitive volume that the stored geometry lacks, as they may be that
33 volume renamed or reshaped by the design that wrote the file: they record
34 no hits.
35* SBT cells that the SBT digitisation cannot find: vetoHit::GetNode finds a
36 cell from its detector ID through the node names and hierarchy that
37 veto.cxx gives the cells, so SBT hit positions are right only for SBT
38 designs that keep them. GetNode itself is asked for each cell placement
39 (_missed_by_veto_hit).
40
41Detector IDs come from the node names and copy numbers of the stored
42geometry, and the run writes the stored geometry, so the digitisation and
43reconstruction see the layout the hits come from, within the limit above for
44the SBT.
45
46A detector that the current code cannot build from the stored configuration,
47such as the UBT of a file from before the scintillator tiles, is left out of
48the run by shipDet_conf.configure, with a warning (warn_left_out): it is not
49built, so it registers no sensitive volumes, and its volumes in the stored
50geometry are passive.
51"""
52
53from __future__ import annotations
54
55from typing import Any
56
57import ROOT
58
59_HELPER = """
60#include <functional>
61#include <string>
62#include <unordered_map>
63#include <unordered_set>
64#include <utility>
65#include <vector>
66
67#include "TGeoManager.h"
68#include "TGeoMedium.h"
69#include "TGeoNode.h"
70#include "TGeoVolume.h"
71
72namespace ship_geofile {
73// Read the stored geometry without making it the current one. Reading a
74// TGeoManager deletes gGeoManager, but the geometry that was built must stay
75// alive: FairMCApplication still uses its list of volumes, and its fields are
76// copied. FairModule::ConstructRootGeometry() does the same.
77inline TGeoManager* Import(const char* path) {
78 TGeoManager* built = gGeoManager;
79 gGeoManager = nullptr;
80 TGeoManager* loaded = TGeoManager::Import(path, "FAIRGeom");
81 gGeoManager = built;
82 return loaded;
83}
84
85inline void Use(TGeoManager* geometry) { gGeoManager = geometry; }
86
87// The geometry in use now. PyROOT binds ROOT.gGeoManager to the global
88// itself, so a Python variable assigned from it follows every later change
89// of gGeoManager; the pointer returned here does not.
90inline TGeoManager* Current() { return gGeoManager; }
91
92// Names of the volumes.
93inline std::unordered_set<std::string> Volumes(TGeoManager* geometry) {
94 std::unordered_set<std::string> names;
95 TIter next(geometry->GetListOfVolumes());
96 while (auto* volume = static_cast<TGeoVolume*>(next())) {
97 names.insert(volume->GetName());
98 }
99 return names;
100}
101
102// Names in `a` that `b` lacks.
103inline std::vector<std::string> Difference(const std::unordered_set<std::string>& a,
104 const std::unordered_set<std::string>& b) {
105 std::vector<std::string> names;
106 for (const auto& name : a) {
107 if (!b.count(name)) names.push_back(name);
108 }
109 return names;
110}
111
112inline std::string Placement(TGeoVolume* volume, TGeoNode* node) {
113 return std::string(volume->GetName()) + "/" + node->GetName();
114}
115
116// Placements ("volume/node") of `a` that `b` lacks, with the name of the
117// volume placed, in the volumes that `b` has (the placements in the volumes
118// it lacks go with them).
119inline std::vector<std::pair<std::string, std::string>> MissingPlacements(TGeoManager* a, TGeoManager* b) {
120 std::unordered_set<std::string> have;
121 TIter next(b->GetListOfVolumes());
122 while (auto* volume = static_cast<TGeoVolume*>(next())) {
123 for (Int_t i = 0; i < volume->GetNdaughters(); ++i) have.insert(Placement(volume, volume->GetNode(i)));
124 }
125 const auto volumes = Volumes(b);
126 std::unordered_set<std::string> seen;
127 std::vector<std::pair<std::string, std::string>> missing;
128 TIter nextA(a->GetListOfVolumes());
129 while (auto* volume = static_cast<TGeoVolume*>(nextA())) {
130 if (!volumes.count(volume->GetName())) continue;
131 for (Int_t i = 0; i < volume->GetNdaughters(); ++i) {
132 TGeoNode* node = volume->GetNode(i);
133 auto name = Placement(volume, node);
134 if (!have.count(name) && seen.insert(name).second) missing.emplace_back(name, node->GetVolume()->GetName());
135 }
136 }
137 return missing;
138}
139
140// Name of the medium of a volume, empty for an assembly or a missing volume.
141inline std::string Medium(TGeoManager* geometry, const char* name) {
142 TGeoVolume* volume = geometry->GetVolume(name);
143 if (!volume || volume->IsAssembly() || !volume->GetMedium()) return "";
144 return volume->GetMedium()->GetName();
145}
146
147// Physical placements of the volumes named in `names`, as paths from the top
148// volume in the form that TGeoNavigator::cd takes ("cave/DecayVolume_1/..."),
149// with their nodes. Only the branches that lead to such volumes are walked.
150inline std::vector<std::pair<std::string, TGeoNode*>> PathsOf(TGeoManager* geometry,
151 const std::vector<std::string>& names) {
152 const std::unordered_set<std::string> wanted(names.begin(), names.end());
153 std::unordered_map<TGeoVolume*, bool> leads; // whether a volume contains a wanted one
154 std::function<bool(TGeoVolume*)> leadsTo = [&](TGeoVolume* volume) {
155 if (auto it = leads.find(volume); it != leads.end()) return it->second;
156 leads[volume] = false;
157 bool result = false;
158 for (Int_t i = 0; i < volume->GetNdaughters(); ++i) {
159 TGeoVolume* daughter = volume->GetNode(i)->GetVolume();
160 if (wanted.count(daughter->GetName()) || leadsTo(daughter)) result = true;
161 }
162 return leads[volume] = result;
163 };
164 std::vector<std::pair<std::string, TGeoNode*>> paths;
165 std::function<void(TGeoVolume*, const std::string&)> walk = [&](TGeoVolume* volume, const std::string& path) {
166 for (Int_t i = 0; i < volume->GetNdaughters(); ++i) {
167 TGeoNode* node = volume->GetNode(i);
168 const std::string nodePath = path + "/" + node->GetName();
169 if (wanted.count(node->GetVolume()->GetName())) paths.emplace_back(nodePath, node);
170 if (leadsTo(node->GetVolume())) walk(node->GetVolume(), nodePath);
171 }
172 };
173 TGeoVolume* top = geometry->GetTopVolume();
174 if (top) walk(top, top->GetName());
175 return paths;
176}
177
178// Whether `geometry` has a node at `path` (in the form of PathsOf). Follows
179// node names only, so it needs neither a navigator nor a closed geometry.
180inline bool HasPath(TGeoManager* geometry, const std::string& path) {
181 TGeoVolume* volume = geometry->GetTopVolume();
182 if (!volume) return false;
183 std::size_t start = path.find('/'); // the first element is the top volume
184 while (start != std::string::npos) {
185 const std::size_t end = path.find('/', start + 1);
186 const std::string name = path.substr(start + 1, end == std::string::npos ? std::string::npos : end - start - 1);
187 TGeoNode* node = volume->FindNode(name.c_str());
188 if (!node) return false;
189 volume = node->GetVolume();
190 start = end;
191 }
192 return true;
193}
194} // namespace ship_geofile
195"""
196
197
198def check_file(geofile: str) -> None:
199 """Raise ValueError unless geofile holds a geometry (FAIRGeom) and its configuration (ShipGeo)."""
200 try:
201 f = ROOT.TFile.Open(geofile, "READ")
202 except OSError: # recent PyROOT raises instead of returning a null file
203 f = None
204 if not f or f.IsZombie():
205 raise ValueError(f"cannot open geometry file {geofile}")
206 with f:
207 key = f.GetKey("FAIRGeom")
208 has_geometry = bool(key) and key.GetClassName() == "TGeoManager"
209 has_config = bool(f.GetKey("ShipGeo"))
210 if not has_geometry:
211 raise ValueError(f"{geofile} has no geometry FAIRGeom: give a geometry file written by run_simScript.py")
212 if not has_config:
213 raise ValueError(
214 f"{geofile} has no geometry configuration ShipGeo: give a geometry file written by run_simScript.py"
215 )
216
217
218SWAP_NAME = "GeometrySwap"
219VETO_MODULE = "Veto" # name of the SBT module (veto::veto)
220_swap_class: Any = None
221
222
223def make_swap(geofile: str) -> Any:
224 """The module that replaces the built geometry by the one in geofile; add it last.
225
226 The class derives from pyFairModule, so it is defined on first use only:
227 this keeps the library of pyFairModule from being loaded whenever this
228 module is imported, as it is by shipDet_conf.
229 """
230 global _swap_class
231 if _swap_class is None:
232 _swap_class = _define_swap_class()
233 return _swap_class(geofile)
234
235
237 class GeometrySwap(ROOT.pyFairModule):
238 """Module that replaces the built geometry by the one in a geometry file; add it last."""
239
240 def __init__(self, geofile: str) -> None:
241 ROOT.pyFairModule.__init__(self, self)
242 self.SetName(SWAP_NAME)
243 self.geofile = geofile
244 self.loaded: Any = None
245 self.fields: list[str] = []
246 self.error: str | None = None
247
248 def ConstructGeometry(self) -> None:
249 # An exception raised here would pass through the C++ of Geant4 VMC,
250 # which calls this method. Record it instead: the built geometry then
251 # stays in use, and check_swapped() stops the run after run.Init().
252 try:
253 self._swap()
254 except Exception as e:
255 self.error = str(e)
256 print(f"ERROR in GeometrySwap: {e}", flush=True)
257
258 def _swap(self) -> None:
259 if not hasattr(ROOT, "ship_geofile"):
260 ROOT.gInterpreter.Declare(_HELPER)
261 helper = ROOT.ship_geofile # declared above
262 built = helper.Current() # not ROOT.gGeoManager, which follows the global
263 loaded = helper.Import(self.geofile)
264 if not loaded:
265 raise RuntimeError(f"cannot read the geometry FAIRGeom from {self.geofile}")
266
267 # Detectors find their sensitive volumes by name (FairDetector::Initialize).
268 sensitive = {str(name) for name in ROOT.pyFairModule.SensitiveVolumeNames()}
269 warning = self._differences(helper, built, loaded, sensitive)
270
271 # Fields attached to volumes are not stored in geometry files.
272 built_volumes = list(built.GetListOfVolumes())
273 loaded_volumes = list(loaded.GetListOfVolumes())
274 same_order = [v.GetName() for v in built_volumes] == [v.GetName() for v in loaded_volumes]
275 by_name: dict[str, list[Any]] = {}
276 for volume in loaded_volumes:
277 by_name.setdefault(volume.GetName(), []).append(volume)
278 fields = []
279 missing_fields = []
280 for i, volume in enumerate(built_volumes):
281 field = volume.GetField()
282 if not field:
283 continue
284 if same_order:
285 target = loaded_volumes[i]
286 else:
287 candidates = by_name.get(volume.GetName(), [])
288 if not candidates:
289 missing_fields.append(volume.GetName())
290 continue
291 if len(candidates) != 1:
292 raise RuntimeError(
293 f"cannot tell which of the {len(candidates)} volumes {volume.GetName()} in {self.geofile}"
294 " gets the magnetic field of the volume of that name"
295 )
296 target = candidates[0]
297 fields.append((target, field, volume.GetName()))
298 if missing_fields:
299 raise RuntimeError(
300 f"the geometry in {self.geofile} lacks {len(missing_fields)} volume(s) to which the current code"
301 f" attaches a magnetic field ({_some(missing_fields)}): the field would be lost"
302 )
303 for target, field, name in fields:
304 target.SetField(field)
305 self.fields.append(name)
306
307 helper.Use(loaded)
308 self.loaded = loaded
309 # The parameter file stores the geometry given to FairGeoParSet by FairRunSim::Init().
310 geo_par = ROOT.FairRuntimeDb.instance().getContainer("FairGeoParSet")
311 if geo_par:
312 geo_par.SetGeometry(loaded)
313 if warning:
314 print(f"WARNING in GeometrySwap: {warning}", flush=True)
315 print(
316 f"GeometrySwap: transporting through the geometry of {self.geofile} ({len(loaded_volumes)} volumes);"
317 f" magnetic fields of volumes copied for: {', '.join(self.fields) or 'none'}",
318 flush=True,
319 )
320
321 def _sbt_layout(self, helper: Any, built: ROOT.TGeoManager, loaded: ROOT.TGeoManager) -> str | None:
322 """Describe the SBT cells of the stored geometry that the SBT digitisation does not find, None if none.
323
324 vetoHit::GetNode finds a cell from its detector ID, the copy number
325 of its placement, through the node names and hierarchy that
326 veto.cxx gives the cells; a cell it does not find gets the position
327 of the last ancestor found, with a ROOT error per hit. GetNode
328 itself is asked for each placement of a sensitive volume of the
329 veto module in the stored geometry. A placement that the built
330 geometry has at the same path is left out: GetNode would not find
331 it there either (e.g. the cavern volumes made sensitive with
332 --FollowMuon), so it is not a difference of the stored geometry.
333 """
334 veto_sensitive = [str(name) for name in ROOT.pyFairModule.SensitiveVolumeNames(VETO_MODULE)]
335 missed = [
336 path for path in _missed_by_veto_hit(helper, loaded, veto_sensitive) if not helper.HasPath(built, path)
337 ]
338 if not missed:
339 return None
340 return (
341 f"places {len(missed)} SBT cell(s) where the SBT digitisation (vetoHit::GetNode) does not find them"
342 f" from their detector ID ({_some(sorted(missed))}): their hit positions would be wrong. GetNode"
343 " follows the node names and hierarchy that veto.cxx gives the cells"
344 )
345
346 def _differences(
347 self, helper: Any, built: ROOT.TGeoManager, loaded: ROOT.TGeoManager, sensitive: set[str]
348 ) -> str | None:
349 """Describe how the stored geometry differs from the built one, None if it does not."""
350 built_names, loaded_names = helper.Volumes(built), helper.Volumes(loaded)
351 missing = sorted(str(name) for name in helper.Difference(built_names, loaded_names))
352 parts = []
353 missing_sensitive = [name for name in missing if name in sensitive]
354 missing_passive = [name for name in missing if name not in sensitive]
355 if missing_sensitive:
356 # Geant4 VMC gives an unknown volume name the ID 0, which no
357 # volume has, so FairMCApplication::Stepping never calls the
358 # detector for it: it just records no hits there.
359 parts.append(
360 f"lacks {len(missing_sensitive)} volume(s) that the current code registers as sensitive"
361 f" ({_some(missing_sensitive)}), which record no hits"
362 )
363 if missing_passive:
364 parts.append(
365 f"lacks {len(missing_passive)} passive volume(s) that the current code builds"
366 f" ({_some(missing_passive)})"
367 )
368 sbt = self._sbt_layout(helper, built, loaded)
369 if sbt:
370 parts.append(sbt)
371 for verb, a, b in (("lacks", built, loaded), ("has", loaded, built)):
372 placements = sorted((str(p.first), str(p.second)) for p in helper.MissingPlacements(a, b))
373 if not placements:
374 continue
375 of_sensitive = [name for name, placed in placements if placed in sensitive]
376 parts.append(
377 f"{verb} {len(placements)} placement(s) that the current code"
378 f" {'builds' if verb == 'lacks' else 'does not build'} ({_some([name for name, _ in placements])})"
379 + (
380 f", {len(of_sensitive)} of them of sensitive volumes ({_some(of_sensitive)}): detector IDs"
381 " follow the stored geometry"
382 if of_sensitive
383 else ""
384 )
385 )
386 extra = sorted(str(name) for name in helper.Difference(loaded_names, built_names))
387 if extra:
388 # The media of the sensitive volumes it lacks: an extra volume of
389 # one of them may be such a volume, renamed or reshaped.
390 missing_media = {str(helper.Medium(built, name)) for name in missing_sensitive} - {""}
391 in_missing_media = [name for name in extra if str(helper.Medium(loaded, name)) in missing_media]
392 parts.append(
393 f"has {len(extra)} volume(s) that the current code does not build ({_some(extra)}), which are"
394 " passive in this run"
395 + (
396 f"; {len(in_missing_media)} of them are made of the medium of a missing sensitive volume"
397 f" and record no hits ({_some(in_missing_media)})"
398 if in_missing_media
399 else ""
400 )
401 )
402 if not parts:
403 return None
404 return (
405 f"the geometry in {self.geofile} differs from the one the current code builds: it "
406 + "; it ".join(parts)
407 + ". Particles are transported through the stored geometry."
408 )
409
410 return GeometrySwap
411
412
413def _missed_by_veto_hit(helper: Any, geometry: ROOT.TGeoManager, names: list[str]) -> list[str]:
414 """Paths of the placements of the volumes `names` in geometry that vetoHit::GetNode does not find.
415
416 For each placement, GetNode is given its copy number as detector ID, and
417 must return its node. The geometry must be closed, as GetNode navigates.
418 """
419 if not names:
420 return []
421 wanted = ROOT.std.vector("std::string")()
422 for name in names:
423 wanted.push_back(name)
424 previous = helper.Current() # not ROOT.gGeoManager, which follows the global
425 level = ROOT.gErrorIgnoreLevel
426 missed = []
427 helper.Use(geometry) # GetNode navigates gGeoManager
428 ROOT.gErrorIgnoreLevel = ROOT.kFatal # it prints an error for each path it does not find
429 try:
430 for placement in helper.PathsOf(geometry, wanted):
431 node = placement.second
432 hit_node = ROOT.vetoHit(node.GetNumber(), 0.0).GetNode()
433 if not hit_node or ROOT.addressof(hit_node) != ROOT.addressof(node):
434 missed.append(str(placement.first))
435 finally:
436 ROOT.gErrorIgnoreLevel = level
437 geometry.GetCurrentNavigator().CdTop()
438 helper.Use(previous)
439 return missed
440
441
442def _some(names: list[str], n: int = 10) -> str:
443 """The first n names, comma separated."""
444 return ", ".join(names[:n]) + (", ..." if len(names) > n else "")
445
446
447def warn_left_out(geofile: str, left_out: dict[str, str]) -> None:
448 """Warn about the modules left out of the run because the current code cannot build them.
449
450 ``left_out`` maps the name of each such module to the reason, a phrase
451 describing what geofile has.
452 """
453 by_reason: dict[str, list[str]] = {}
454 for name, reason in left_out.items():
455 by_reason.setdefault(reason, []).append(name)
456 for reason, names in by_reason.items():
457 print(
458 f"WARNING: {geofile} has {reason}: {', '.join(names)} left out of this run. They record no hits, and"
459 " their volumes in the stored geometry are passive.",
460 flush=True,
461 )
462
463
464def check_swapped(swap: Any) -> None:
465 """After run.Init(): stop unless the geometry from the file is the one in use."""
466 in_use = ROOT.gGeoManager
467 if swap.error or not swap.loaded or not in_use or ROOT.addressof(in_use) != ROOT.addressof(swap.loaded):
468 reason = swap.error or "GeometrySwap.ConstructGeometry() did not run or did not complete"
469 raise RuntimeError(f"the geometry from {swap.geofile} is not in use: {reason}")
470
471
472# Parts of the geometry configuration that shipDet_conf.configure reads again
473# from the YAML files in $FAIRSHIP/geometry, also with -g.
474YAML_CONFIGS = {
475 "mtc_geo": "MTC_config.yaml",
476 "SiliconTarget_geo": "SiliconTarget_config.yaml",
477 "strawtubes_geo": "strawtubes_config.yaml",
478 # configure uses the stored UBT map when there is one, so this only fails
479 # if it read UpstreamTagger_config.yaml instead.
480 "UpstreamTagger_geo": "UpstreamTagger_config.yaml",
481}
482
483
484def stored_yaml_configs(ship_geo: Any) -> dict[str, Any]:
485 """The parts of the stored configuration that the YAML files will overwrite."""
486 return {key: ship_geo[key] for key in YAML_CONFIGS if key in ship_geo}
487
488
489def check_yaml_configs(stored: dict[str, Any], ship_geo: Any) -> None:
490 """Check that the YAML files still give the configuration stored with the geometry.
491
492 The detectors take their parameters from the YAML files, so if these changed
493 since the geometry file was written, the parameters would not match the
494 stored geometry.
495 """
496 changed = [YAML_CONFIGS[key] for key, value in stored.items() if dict(ship_geo.get(key, {})) != dict(value)]
497 if changed:
498 raise ValueError(
499 f"geometry/{', geometry/'.join(changed)} changed since the geometry file was written, so the detector"
500 " parameters would not match the stored geometry: write a new geometry file"
501 )
None check_file(str geofile)
dict[str, Any] stored_yaml_configs(Any ship_geo)
None check_swapped(Any swap)
None warn_left_out(str geofile, dict[str, str] left_out)
Any make_swap(str geofile)
list[str] _missed_by_veto_hit(Any helper, ROOT.TGeoManager geometry, list[str] names)
None check_yaml_configs(dict[str, Any] stored, Any ship_geo)
str _some(list[str] names, int n=10)