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
250
251
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
262 built = helper.Current()
263 loaded = helper.Import(self.geofile)
264 if not loaded:
265 raise RuntimeError(f"cannot read the geometry FAIRGeom from {self.geofile}")
266
267
268 sensitive = {str(name) for name in ROOT.pyFairModule.SensitiveVolumeNames()}
269 warning = self._differences(helper, built, loaded, sensitive)
270
271
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
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
357
358
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
389
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