FairShip
Loading...
Searching...
No Matches
geometry_from_file Namespace Reference

Functions

None check_file (str geofile)
Any make_swap (str geofile)
Any _define_swap_class ()
list[str] _missed_by_veto_hit (Any helper, ROOT.TGeoManager geometry, list[str] names)
str _some (list[str] names, int n=10)
None warn_left_out (str geofile, dict[str, str] left_out)
None check_swapped (Any swap)
dict[str, Any] stored_yaml_configs (Any ship_geo)
None check_yaml_configs (dict[str, Any] stored, Any ship_geo)

Variables

str _HELPER
str SWAP_NAME = "GeometrySwap"
str VETO_MODULE = "Veto"
Any _swap_class = None
dict YAML_CONFIGS
 geofile = geofile
Any loaded = None
list fields = []
str|None error = None

Detailed Description

Simulate on the geometry of a geometry file (run_simScript.py -g).

The modules build their geometry as usual, from the configuration (ShipGeo)
stored in the geometry file. Building does more than create volumes: the
detectors register which volumes are sensitive, and magnets attach their
fields to volumes, and a geometry file keeps neither. So the run keeps all of
that and only exchanges the volumes: a GeometrySwap module (make_swap), added last,
replaces the geometry that was just built by the one stored in the file, before
Geant4 converts it. Particles are then transported through the stored geometry,
whatever the current code would build.

The stored geometry may differ from the one the current code builds, for
example a geometry file written with a modified SBT design. Every volume to
which a field is attached must exist in the stored geometry, and its name
must tell which one: the field is copied onto it. The run stops otherwise.
Fields from field maps are added after the swap, as usual.

Other differences are reported as a warning:

* Sensitive volumes that the stored geometry lacks, e.g. the SBT cells that a
  design with fewer cells does not have. FairDetector::Initialize() binds
  sensitive volumes to the geometry given to Geant4 by name; Geant4 VMC gives
  an unknown name the volume ID 0, which no volume has, so these volumes just
  record no hits.
* Passive volumes that the stored geometry lacks, and placements that it lacks
  or adds.
* Volumes of the stored geometry that the current code does not build. These
  are passive in this run, so the warning names those made of the medium of
  a sensitive volume that the stored geometry lacks, as they may be that
  volume renamed or reshaped by the design that wrote the file: they record
  no hits.
* SBT cells that the SBT digitisation cannot find: vetoHit::GetNode finds a
  cell from its detector ID through the node names and hierarchy that
  veto.cxx gives the cells, so SBT hit positions are right only for SBT
  designs that keep them. GetNode itself is asked for each cell placement
  (_missed_by_veto_hit).

Detector IDs come from the node names and copy numbers of the stored
geometry, and the run writes the stored geometry, so the digitisation and
reconstruction see the layout the hits come from, within the limit above for
the SBT.

A detector that the current code cannot build from the stored configuration,
such as the UBT of a file from before the scintillator tiles, is left out of
the run by shipDet_conf.configure, with a warning (warn_left_out): it is not
built, so it registers no sensitive volumes, and its volumes in the stored
geometry are passive.

Function Documentation

◆ _define_swap_class()

Any geometry_from_file._define_swap_class ( )
protected

Definition at line 236 of file geometry_from_file.py.

236def _define_swap_class() -> Any:
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

◆ _missed_by_veto_hit()

list[str] geometry_from_file._missed_by_veto_hit ( Any helper,
ROOT.TGeoManager geometry,
list[str] names )
protected
Paths of the placements of the volumes `names` in geometry that vetoHit::GetNode does not find.

For each placement, GetNode is given its copy number as detector ID, and
must return its node. The geometry must be closed, as GetNode navigates.

Definition at line 413 of file geometry_from_file.py.

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

◆ _some()

str geometry_from_file._some ( list[str] names,
int n = 10 )
protected
The first n names, comma separated.

Definition at line 442 of file geometry_from_file.py.

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

◆ check_file()

None geometry_from_file.check_file ( str geofile)
Raise ValueError unless geofile holds a geometry (FAIRGeom) and its configuration (ShipGeo).

Definition at line 198 of file geometry_from_file.py.

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

◆ check_swapped()

None geometry_from_file.check_swapped ( Any swap)
After run.Init(): stop unless the geometry from the file is the one in use.

Definition at line 464 of file geometry_from_file.py.

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.

◆ check_yaml_configs()

None geometry_from_file.check_yaml_configs ( dict[str, Any] stored,
Any ship_geo )
Check that the YAML files still give the configuration stored with the geometry.

The detectors take their parameters from the YAML files, so if these changed
since the geometry file was written, the parameters would not match the
stored geometry.

Definition at line 489 of file geometry_from_file.py.

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 )

◆ make_swap()

Any geometry_from_file.make_swap ( str geofile)
The module that replaces the built geometry by the one in geofile; add it last.

The class derives from pyFairModule, so it is defined on first use only:
this keeps the library of pyFairModule from being loaded whenever this
module is imported, as it is by shipDet_conf.

Definition at line 223 of file geometry_from_file.py.

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

◆ stored_yaml_configs()

dict[str, Any] geometry_from_file.stored_yaml_configs ( Any ship_geo)
The parts of the stored configuration that the YAML files will overwrite.

Definition at line 484 of file geometry_from_file.py.

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

◆ warn_left_out()

None geometry_from_file.warn_left_out ( str geofile,
dict[str, str] left_out )
Warn about the modules left out of the run because the current code cannot build them.

``left_out`` maps the name of each such module to the reason, a phrase
describing what geofile has.

Definition at line 447 of file geometry_from_file.py.

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

Variable Documentation

◆ _HELPER

str geometry_from_file._HELPER
protected

Definition at line 59 of file geometry_from_file.py.

◆ _swap_class

Any geometry_from_file._swap_class = None
protected

Definition at line 220 of file geometry_from_file.py.

◆ error

str | None geometry_from_file.error = None

Definition at line 246 of file geometry_from_file.py.

◆ fields

list geometry_from_file.fields = []

Definition at line 245 of file geometry_from_file.py.

◆ geofile

geometry_from_file.geofile = geofile

Definition at line 243 of file geometry_from_file.py.

◆ loaded

Any geometry_from_file.loaded = None

Definition at line 244 of file geometry_from_file.py.

◆ SWAP_NAME

str geometry_from_file.SWAP_NAME = "GeometrySwap"

Definition at line 218 of file geometry_from_file.py.

◆ VETO_MODULE

str geometry_from_file.VETO_MODULE = "Veto"

Definition at line 219 of file geometry_from_file.py.

◆ YAML_CONFIGS

dict geometry_from_file.YAML_CONFIGS
Initial value:
1= {
2 "mtc_geo": "MTC_config.yaml",
3 "SiliconTarget_geo": "SiliconTarget_config.yaml",
4 "strawtubes_geo": "strawtubes_config.yaml",
5 # configure uses the stored UBT map when there is one, so this only fails
6 # if it read UpstreamTagger_config.yaml instead.
7 "UpstreamTagger_geo": "UpstreamTagger_config.yaml",
8}

Definition at line 474 of file geometry_from_file.py.