Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-26 09:23:12

0001 # This file is part of the ACTS project.
0002 #
0003 # Copyright (C) 2016 CERN for the benefit of the ACTS project
0004 #
0005 # This Source Code Form is subject to the terms of the Mozilla Public
0006 # License, v. 2.0. If a copy of the MPL was not distributed with this
0007 # file, You can obtain one at https://mozilla.org/MPL/2.0/.
0008 
0009 # Project includes
0010 from .type_helpers import link
0011 from .definitions import (
0012     Type,
0013     Algebra,
0014     Shape,
0015     Material,
0016     Accelerator,
0017     GridBin,
0018     GridSerializer,
0019 )
0020 
0021 # Python includes
0022 from collections import Counter
0023 from datetime import datetime
0024 import itertools
0025 import logging
0026 import numbers
0027 import os
0028 import re
0029 from pathlib import Path
0030 from typing import Optional
0031 import subprocess
0032 
0033 """ Class that represents the c++ metadata struct with all of its types """
0034 
0035 
0036 class metadata:
0037     def __init__(
0038         self,
0039         detector_name,
0040     ):
0041         self.logger = logging.getLogger(__name__)
0042         self.det_name = detector_name
0043         # Custom linear algebra implementation
0044         self.algebra = Algebra.ANY
0045         # Only relevant, if algebra type is not 'ANY'
0046         self.precision = None
0047         # Base type for type ID enums
0048         self.id_base = Type.UINT_LEAST_8
0049         # Volume link in the masks (resolve geometry connectivity in navigation)
0050         self.nav_link = link(link_type="single", data_type=Type.UINT_LEAST_16)
0051         # Surface link to its mask(s) (type ID, index range)
0052         self.mask_link = link(link_type="range", data_type=Type.UINT_32)
0053         # Surface link to its material (type ID, index)
0054         self.material_link = link(link_type="single", data_type=Type.UINT_32)
0055         # Surface types: passive, portal, sensitive etc.
0056         self.surface_types = []
0057         # Surface shapes: rectangle, ring etc.
0058         self.shapes = {}
0059         # Material types: slabs, material maps etc.
0060         self.materials = {}
0061         # Set brute force finder as default for portals/passives and volumes
0062         self.default_surface_accel = Accelerator.BRUTE_FORCE
0063         self.default_volume_accel = Accelerator.BRUTE_FORCE
0064         # Surface and volume acceleration structures
0065         self.acceleration_structs = {}
0066 
0067         self.logger.info(f'Detector: "{self.det_name}"')
0068 
0069     # Find the next valid type id for a new type in a given mulit_store
0070     def __resolve_id_priority(self, type_dict, type_id: int = -1):
0071         is_valid_id = type_id >= 0
0072         next_auto_id = (
0073             0 if not type_dict else max(len(type_dict), max(type_dict.keys()) + 1)
0074         )
0075         priority = type_id if is_valid_id else next_auto_id
0076         is_clash = priority in type_dict
0077         # Resolve clashes
0078         priority = priority + 1 if is_clash else priority
0079 
0080         # Shift lower priority items
0081         if is_clash:
0082             new_type_dict = {}
0083             for k, v in sorted(type_dict.items()):
0084                 new_type_dict[k + 1 if k >= priority else k] = type_dict[k]
0085 
0086             # Now swap
0087             type_dict, new_type_dict = new_type_dict, type_dict
0088 
0089         return priority, type_dict
0090 
0091     # Choose an algebra-plugin
0092     def set_algebra_plugin(self, plugin: Algebra, precision: Optional[Type] = None):
0093         self.algebra = plugin
0094 
0095         if self.algebra is not Algebra.ANY:
0096             if precision is not Type.SINGLE or precision is not Type.DOUBLE:
0097                 self.logger.warning(
0098                     f'Incorrect precision "{precision}" for algebra type. Using "float" instead'
0099                 )
0100                 self.precision = Type.SINGLE
0101             else:
0102                 self.precision = precision
0103             self.logger.info(f"Algebra plugin: {self.algebra}<{self.precision}>")
0104         elif precision is not None:
0105             self.logger.warning(
0106                 f'Precision "{precision}" will be ignored for generic algebra type'
0107             )
0108 
0109     # Register a new geometric shape for a portal surface at a given position
0110     # in the mask store (type_id)
0111     def add_portal(self, shape: Shape, type_id: int = -1):
0112         self.add_shape(shape, type_id)
0113         if "portal" not in self.surface_types:
0114             self.surface_types.append("portal")
0115 
0116     # Register a new geometric shape for a sensitive surface at a given position
0117     # in the mask store (type_id)
0118     def add_sensitive(self, shape: Shape, type_id: int = -1):
0119         self.add_shape(shape, type_id)
0120         if "sensitive" not in self.surface_types:
0121             self.surface_types.append("sensitive")
0122 
0123     # Register a new geometric shape for a passive surface at a given position
0124     # in the mask store (type_id)
0125     def add_passive(self, shape: Shape, type_id: int = -1):
0126         self.add_shape(shape, type_id)
0127         if "passive" not in self.surface_types:
0128             self.surface_types.append("passive")
0129 
0130     # Register a new geometric shape for the detector at a given position
0131     # in the mask store (type_id)
0132     def add_shape(self, shape: Shape, type_id: int):
0133         if shape not in itertools.chain(*self.shapes.values()):
0134             self.logger.debug(f'--> surface shape "{shape.specifier}"')
0135 
0136             # Automatically enumerate the shape if no type ID is given
0137             i, self.shapes = self.__resolve_id_priority(self.shapes, type_id)
0138             self.shapes.setdefault(i, []).append(shape)
0139 
0140     # Register a new material type
0141     def add_material(self, mat: Material, type_id: int = -1):
0142         if mat not in itertools.chain(*self.materials.values()):
0143             is_hom_mat = (
0144                 mat is Material.SLAB or mat is Material.ROD or mat is Material.RAW
0145             )
0146 
0147             if is_hom_mat:
0148                 self.logger.debug(f'--> material type "{mat.specifier}"')
0149             else:
0150                 shape_secifier = mat.param["shape"].specifier
0151                 self.logger.debug(
0152                     f'--> material type "{mat.specifier}<{shape_secifier}>"'
0153                 )
0154 
0155             # Automatically enumerate the material if no type ID is given
0156             i, self.materials = self.__resolve_id_priority(self.materials, type_id)
0157 
0158             # Check if a compatible material is already registered
0159             # under a different type id?
0160             if not is_hom_mat:
0161                 compatible_types = [
0162                     k
0163                     for k, v in self.materials.items()
0164                     if "frame" in v[0].param
0165                     and v[0].param["frame"].specifier == mat.param["frame"].specifier
0166                 ]
0167                 compatible_types.sort()
0168                 i = compatible_types[0] if len(compatible_types) > 0 else i
0169 
0170             self.materials.setdefault(i, []).append(mat)
0171 
0172     # Register a new acceleration structure for a geometric object type
0173     def add_accel_struct(
0174         self,
0175         accel: Accelerator,
0176         obj_type: str = "sensitive",
0177         type_id: int = -1,
0178         value_type: str = "surface",
0179         is_default: bool = False,
0180         grid_bin: GridBin = GridBin.DYNAMIC,
0181         grid_serializer: GridSerializer = GridSerializer.SIMPLE,
0182     ):
0183         # Update accelerator type with specific configuration
0184         if "grid" in accel.specifier:
0185             accel.param["bin"] = grid_bin
0186             accel.param["serialiser"] = grid_serializer
0187 
0188         # Make sure volume acceleration structures have indices as values
0189         value_type = "index" if "volume" in obj_type else value_type
0190         chosen = False
0191         if obj_type not in self.acceleration_structs.keys():
0192             self.acceleration_structs[obj_type] = [(accel, type_id, value_type)]
0193             chosen = True
0194         elif (accel, type_id, value_type) not in self.acceleration_structs[obj_type]:
0195             chosen = True
0196             self.acceleration_structs[obj_type].append((accel, type_id, value_type))
0197 
0198         if chosen:
0199             shape_secifier = (
0200                 "" if "grid" not in accel.specifier else accel.param["shape"].specifier
0201             )
0202             accel_type = (
0203                 f"{accel.specifier}"
0204                 if "grid" not in accel.specifier
0205                 else f"{accel.specifier}<{shape_secifier}>"
0206             )
0207 
0208             self.logger.debug(f"--> accel. struct ({obj_type}): {accel_type}")
0209 
0210         if is_default:
0211             self.set_default_accel_struct(accel, obj_type, value_type)
0212 
0213     # Mark an acceleration struct as default for the given object type
0214     # (To be used e.g. for the portal surfaces and to fetch the volume acc.
0215     # struct in the detector without resolving a specific type ID)
0216     def set_default_accel_struct(
0217         self,
0218         accel: Accelerator,
0219         obj_type: str,
0220         type_id: int = -1,
0221         value_type: str = "surface",
0222     ):
0223         # Make sure volume acceleration structures have indices as values
0224         value_type = "index" if "volume" in obj_type else value_type
0225 
0226         shape_secifier = (
0227             "" if "grid" not in accel.specifier else accel.param["shape"].specifier
0228         )
0229         accel_type = (
0230             f"{accel.specifier}"
0231             if "grid" not in accel.specifier
0232             else f"{accel.specifier}<{shape_secifier}>"
0233         )
0234 
0235         if obj_type == "portal":
0236             self.logger.debug(
0237                 f"--> setting default surface accel. struct: {accel_type}"
0238             )
0239             self.default_surface_accel = accel
0240         elif obj_type == "volume":
0241             self.logger.debug(f"--> setting default volume accel. struct: {accel_type}")
0242             self.default_volume_accel = accel
0243         else:
0244             self.logger.warning(
0245                 f'Cannot set default acceleration structure for geometry object type "{obj_type}"'
0246             )
0247 
0248         # Make sure the requested default exists
0249         if obj_type not in self.acceleration_structs.keys() or (
0250             accel,
0251             value_type,
0252         ) not in [(a, v) for a, i, v in self.acceleration_structs[obj_type]]:
0253             self.logger.warning(
0254                 f"Requested default acceleration structure ({obj_type}, {accel_type}) not defined in metadata: Adding it now..."
0255             )
0256             self.add_accel_struct(accel, obj_type, type_id, value_type)
0257 
0258 
0259 """ Class that accumulates detector type data and writes a metadata header """
0260 
0261 
0262 class metadata_generator:
0263     def __init__(
0264         self,
0265         md: metadata,
0266         output=None,
0267         format_header=True,
0268         output_file=None,
0269     ):
0270         # Internal state during header generation
0271         self.out_dir = os.getcwd() if output is None else output
0272         self.output_file = output_file
0273         self.file = None
0274         self.logger = logging.getLogger(__name__)
0275         self.format_header = format_header
0276         self.indent = 0
0277 
0278         # Save the type specifiers
0279         self.shape_specifiers = {}
0280         self.material_specifiers = {}
0281         self.accel_specifiers = {}
0282         self.grid_specifiers = []
0283 
0284         # Common header section
0285         root_dir = '#include "detray'
0286         self.__common_includes = f'#pragma once\n\n// Project include(s)\n\
0287 {root_dir}/core/detail/multi_store.hpp"\n\
0288 {root_dir}/core/detail/single_store.hpp"\n\
0289 {root_dir}/definitions/algebra.hpp"\n\
0290 {root_dir}/definitions/containers.hpp"\n\
0291 {root_dir}/definitions/indexing.hpp"\n\
0292 {root_dir}/geometry/mask.hpp"\n\
0293 {root_dir}/geometry/surface_descriptor.hpp"\n'
0294 
0295         # Dump the metadata header
0296         self.__generate(md, self.out_dir)
0297 
0298     # Write the given metadata to file
0299     def __generate(self, md: metadata, src_dir):
0300         filename = (
0301             self.output_file or f"{os.path.abspath(src_dir)}/{md.det_name}_metadata.hpp"
0302         )
0303         Path(filename).parent.mkdir(parents=True, exist_ok=True)
0304         self.logger.debug(f'Open "{filename}"')
0305         self.det_name = md.det_name
0306         self.file = open(filename, "w+")
0307 
0308         self.logger.info("Generating metadata...")
0309 
0310         # Beginning of the header (copyright, includes etc.)
0311         self.__preamble(md)
0312 
0313         # Basic typedefs
0314         self.__local_typedefs(md)
0315 
0316         # Transform store
0317         self.logger.info(" -> Transforms")
0318         self.__declare_transform_store()
0319 
0320         # Mask store
0321         self.logger.info(" -> Masks")
0322         self.__declare_mask_store(md)
0323 
0324         # Material store
0325         self.logger.info(" -> Material")
0326         self.__declare_material_store(md)
0327 
0328         # Surface type to be used in surface accelerator types
0329         # (The volume type is automatically assembled in the detector class)
0330         self.__lines(2)
0331         self.__declare_surface_descriptor(md)
0332 
0333         # Acceleration structure store
0334         self.logger.info(" -> Acceleration Structures")
0335         self.__declare_accel_store(md)
0336 
0337         # Definition of geometric object types in a detector volume
0338         self.__declare_geometry_objects(md)
0339 
0340         # Finish (write header file to disk)
0341         self.__finish()
0342 
0343         self.logger.info(f'Finished metadata for "{md.det_name} detector"')
0344 
0345     # Add a string to the header file
0346     def __put(self, string):
0347         self.file.write(f"{self.__tabs()}{string}")
0348 
0349     # Add empty lines
0350     def __lines(self, n):
0351         self.file.write("\n" * n)
0352 
0353     # Add the current indent
0354     def __tabs(self):
0355         return "\t" * self.indent
0356 
0357     # Write a C++ typedef
0358     def __typedef(self, name, type):
0359         self.__put(f"using {name} = {type};\n")
0360 
0361     # Write a C++ template parameter list
0362     def __template_list(self, params):
0363         if params and "" in params:
0364             params.remove("")
0365         return "" if not params else f"template <{','.join(params)}>"
0366 
0367     # Get the the class name from the full type (which has namespace, template params etc.)
0368     def __name_from_specifier(self, specifier):
0369         # Strip template parameter list
0370         tokens = specifier.split("<")
0371         tp_str = tokens[0]
0372 
0373         tokens = []
0374 
0375         # Strip namespace
0376         tokens = tp_str.split(":")
0377 
0378         return tokens[-1]
0379 
0380     # Beginning of the header
0381     def __preamble(self, md: metadata):
0382         copy_right = """
0383 // This file is part of the ACTS project.
0384 //
0385 // Copyright (C) 2016 CERN for the benefit of the ACTS project
0386 //
0387 // This Source Code Form is subject to the terms of the Mozilla Public
0388 // License, v. 2.0. If a copy of the MPL was not distributed with this
0389 // file, You can obtain one at https://mozilla.org/MPL/2.0/."""
0390         self.__put(copy_right.lstrip())
0391         self.__lines(2)
0392         self.__add_header_includes(md.shapes, md.materials, md.acceleration_structs)
0393         self.__lines(2)
0394         self.__put("namespace detray {")
0395         self.__lines(2)
0396         # Write the C++ metadata struct definition
0397         template_params = (
0398             f"{self.__template_list([str(md.algebra)])}\n"
0399             if md.algebra == Algebra.ANY
0400             else ""
0401         )
0402         struct_def = f"{template_params}struct {md.det_name}_metadata {{"
0403         self.__put(struct_def)
0404         self.indent = self.indent + 1
0405         self.__lines(2)
0406 
0407     # Identify the required dependencies and add the includes to the header
0408     def __add_header_includes(self, shapes, materials, accel_structs):
0409         # Add the common includes
0410         self.__put(self.__common_includes)
0411 
0412         # Set of shape class names
0413         shape_names = {
0414             self.__name_from_specifier(s.specifier)
0415             for s in itertools.chain(*shapes.values())
0416         }
0417 
0418         # Correct the header name for the line surfaces
0419         add_line = False
0420         if "line_circular" in shape_names:
0421             shape_names.remove("line_circular")
0422             add_line = True
0423         if "line_square" in shape_names:
0424             shape_names.remove("line_square")
0425             add_line = True
0426 
0427         if add_line and "line" not in shape_names:
0428             shape_names.add("line")
0429 
0430         # Set of material class names
0431         mat_names = {
0432             self.__name_from_specifier(m.specifier)
0433             for m in itertools.chain(*materials.values())
0434         }
0435         # Add shapes for material maps that have not been added, yet
0436         if "material_map" in mat_names:
0437             shape_names.update(
0438                 (
0439                     self.__name_from_specifier(m.param["shape"].specifier)
0440                     if m.param
0441                     else None
0442                 )
0443                 for m in itertools.chain(*materials.values())
0444             )
0445 
0446         # Set of acceleration structure class names
0447         accel_names = {
0448             self.__name_from_specifier(a.specifier)
0449             for accels in accel_structs.values()
0450             for a, i, v in accels
0451         }
0452         if "spatial_grid" in accel_names:
0453             # Add shapes for spatial grids that have not been added, yet
0454             shape_names.update(
0455                 (
0456                     self.__name_from_specifier(a.param["shape"].specifier)
0457                     if a.param
0458                     else None
0459                 )
0460                 for accels in accel_structs.values()
0461                 for a, i, v in accels
0462             )
0463 
0464         # Add the corresponding includes
0465         root_dir = '#include "detray'
0466         shape_names.discard(None)
0467         [
0468             self.__put(f'{root_dir}/geometry/shapes/{n}.hpp"\n')
0469             for n in sorted(shape_names)
0470         ]
0471 
0472         [self.__put(f'{root_dir}/material/{n}.hpp"\n') for n in sorted(mat_names)]
0473 
0474         [
0475             self.__put(f'{root_dir}/navigation/accelerators/{n}.hpp"\n')
0476             for n in sorted(accel_names)
0477         ]
0478 
0479     # Add some mandatory local typedefs of the metadata class
0480     def __local_typedefs(self, md: metadata):
0481         self.__typedef(
0482             "algebra_type",
0483             (
0484                 "algebra_t"
0485                 if md.algebra == Algebra.ANY
0486                 else f"{md.algebra}<{md.precision}>"
0487             ),
0488         )
0489         self.__typedef("scalar_t", "dscalar<algebra_type>")
0490         self.__lines(1)
0491         self.__typedef("nav_link", md.nav_link.data_type)
0492 
0493     # Declare the transform store type
0494     def __declare_transform_store(self):
0495         self.__lines(1)
0496         self.__put(
0497             f"\
0498 template <template <typename...> class vector_t = dvector>\n\
0499 {self.__tabs()}using transform_store =\n\
0500 {self.__tabs()}    single_store<dtransform3D<algebra_type>, vector_t, geometry_context>;"
0501         )
0502 
0503     # Generate the IDs enums for the multi store
0504     def __declare_type_enum(self, specifier, items, base_type, extra_items={}):
0505         self.__put(f"enum class {specifier} : {base_type} {{\n")
0506 
0507         self.indent = self.indent + 1
0508         for i, values in itertools.chain(items.items(), extra_items.items()):
0509             for v in values:
0510                 # Special value was passed
0511                 item = v[0] if isinstance(v, list) else v
0512                 tmp_value = v[1] if isinstance(v, list) else i
0513                 value = f"{i}u" if isinstance(tmp_value, numbers.Number) else tmp_value
0514 
0515                 # Remove the trailing '_t' suffix
0516                 sub_specifier = f"e_{item[:-2]}" if item.endswith("_t") else f"e_{item}"
0517                 self.__put(f"{sub_specifier} = {value},\n")
0518 
0519         self.indent = self.indent - 1
0520 
0521         self.__put("};")
0522 
0523     # Add the streaming operator for an enum
0524     def __define_enum_stream_op(self, specifier, items, extra_items={}):
0525         self.__put(
0526             f"DETRAY_HOST inline friend std::ostream& operator<<(std::ostream& os, {specifier} id) {{\n"
0527         )
0528 
0529         self.indent = self.indent + 1
0530 
0531         self.__put("switch (id) {\n")
0532 
0533         self.indent = self.indent + 1
0534         for i, values in itertools.chain(items.items(), extra_items.items()):
0535             value = ""
0536             item = ""
0537             sub_specifier = ""
0538             # Get the representative of the group
0539             for v in values:
0540                 # Special value was passed
0541                 item = v[0] if isinstance(v, list) else v
0542                 value = v[1] if isinstance(v, list) else f"{i}u"
0543                 # Remove the trailing '_t' suffix
0544                 item = f"e_{item[:-2]}" if item.endswith("_t") else f"e_{item}"
0545                 sub_specifier = (
0546                     item if sub_specifier == "" else f"{sub_specifier}/{item}"
0547                 )
0548 
0549             self.__put(f"case {specifier}::{item}:\n")
0550             self.indent = self.indent + 1
0551             self.__put(f'os << "{value if isinstance(v, list) else sub_specifier}";\n')
0552             self.__put("break;\n")
0553             self.indent = self.indent - 1
0554 
0555         # Add the default case
0556         self.__put("default:\n")
0557         self.indent = self.indent + 1
0558         self.__put('os << "invalid";\n')
0559         self.indent = self.indent - 1
0560 
0561         self.indent = self.indent - 1
0562 
0563         self.__put("}\n")
0564         self.__put("return os;\n")
0565 
0566         self.indent = self.indent - 1
0567 
0568         self.__put("};")
0569 
0570     # Generate the type declaration for the multi_stores
0571     def __declare_multi_store(
0572         self, specifier, id_name, types, context="empty_context", is_regular=True
0573     ):
0574         template_params = (
0575             "template<typename...> class vector_t = dvector"
0576             if is_regular
0577             else "typename container_t = host_container_types"
0578         )
0579         self.__put(f"{self.__template_list([template_params])}\n")
0580         self.__put(f"using {specifier} =\n")
0581 
0582         if is_regular:
0583             self.__put(
0584                 f"\tregular_multi_store<{id_name}, {context}, dtuple, vector_t, {','.join(itertools.chain(*types.values()))}>;"
0585             )
0586         else:
0587             type_list = []
0588             # Take one representative type from the list
0589             flattened_types = [v[0] for k, v in types.items()]
0590 
0591             # The brute force searcher needs to be at the beginning of the store
0592             if "surface_brute_force_t" in flattened_types:
0593                 flattened_types = [
0594                     t for t in flattened_types if t != "surface_brute_force_t"
0595                 ]
0596                 type_list.append("brute_force_collection<surface_type, container_t>")
0597 
0598             # Have the volume acceleration structure at the end of the store
0599             volume_brute_force = ""
0600             if "volume_brute_force_t" in flattened_types:
0601                 flattened_types = [
0602                     t for t in flattened_types if t != "volume_brute_force_t"
0603                 ]
0604                 volume_brute_force = "brute_force_collection<dindex, container_t>"
0605 
0606             type_list = type_list + [
0607                 (
0608                     f"grid_collection<{t}<container_t>>"
0609                     if (t.endswith("map_t") or t.endswith("grid_t"))
0610                     else f"typename container_t::template vector_type<{t}>"
0611                 )
0612                 for t in flattened_types
0613             ]
0614 
0615             if volume_brute_force:
0616                 type_list.append(volume_brute_force)
0617 
0618             self.__put(
0619                 f"\tmulti_store<{id_name}, {context}, dtuple, {','.join(type_list)}>;"
0620             )
0621 
0622     # Declare the surface descriptor type with all links
0623     def __declare_surface_descriptor(self, md: metadata):
0624         self.__put("using transform_link = typename transform_store<>::single_link;\n")
0625 
0626         link_type = (
0627             "single_link" if md.mask_link.link_type == "single" else "range_link"
0628         )
0629         mask_link = f"typename mask_store<>::{link_type}"
0630         self.__put(f"using mask_link = {mask_link};\n")
0631 
0632         link_type = (
0633             "single_link" if md.material_link.link_type == "single" else "range_link"
0634         )
0635         material_link = f"typename material_store<>::{link_type}"
0636         self.__put(f"using material_link = {material_link};\n")
0637 
0638         self.__put(
0639             "using surface_type = surface_descriptor<mask_link, material_link, transform_link, nav_link>;"
0640         )
0641 
0642     # Write a full mask type
0643     def __declare_mask(self, shape, type_id, algebra, link, shape_params={}):
0644         type_specifier = f"{self.__name_from_specifier(shape.specifier)}_t"
0645 
0646         # Distinguish line types
0647         if type_specifier == "line_square_t" or type_specifier == "line_circular_t":
0648             type_specifier = (
0649                 "drift_cell_t" if type_specifier == "line_square_t" else "straw_tube_t"
0650             )
0651 
0652         self.shape_specifiers.setdefault(type_id, []).append(type_specifier)
0653 
0654         # Prepare extra template parameters
0655         params = [str(v).lower() for v in shape_params.values()]
0656         template_params = "" if not shape_params else f"<{','.join(params)}>"
0657 
0658         self.__put(
0659             f"using {type_specifier} = mask<{shape.specifier}{template_params}, {algebra}, {link}>;\n"
0660         )
0661 
0662     # Declare the mask types and mask store for the detector
0663     def __declare_mask_store(self, md: metadata):
0664         # Mask types
0665         assert md.shapes, "Define at least one geometric shape"
0666 
0667         self.__lines(2)
0668         # Make sure type IDs are consecutive
0669         for type_id, (_, shapes) in enumerate(sorted(md.shapes.items())):
0670             for shape in shapes:
0671                 self.__declare_mask(
0672                     shape, type_id, "algebra_type", "nav_link", shape.param
0673                 )
0674 
0675         self.__lines(1)
0676         self.__declare_type_enum("mask_id", self.shape_specifiers, md.id_base)
0677         self.__lines(2)
0678         self.__define_enum_stream_op("mask_id", self.shape_specifiers)
0679         self.__lines(2)
0680 
0681         # Mask Store
0682         self.__declare_multi_store("mask_store", "mask_id", self.shape_specifiers)
0683 
0684     # Write a full material type
0685     def __declare_material(self, mat, type_id, algebra):
0686         type_specifier = f"{self.__name_from_specifier(mat.specifier)}_t"
0687 
0688         if mat is Material.SLAB:
0689             self.__put(f"using {type_specifier} = material_slab<scalar_t>;\n")
0690         elif mat is Material.ROD:
0691             self.__put(f"using {type_specifier} = material_rod<scalar_t>;\n")
0692         elif mat is Material.RAW:
0693             type_specifier = "raw_material_t"
0694             self.__put(f"using {type_specifier} = material<scalar_t>;\n")
0695         else:
0696             shape_specifier = mat.param["shape"].specifier
0697             shape_type = self.__name_from_specifier(shape_specifier)
0698             type_specifier = f"{shape_type}_map_t"
0699             template_list = "template <typename container_t>\n"
0700 
0701             # Only write the type if it's type ID is not yet registered
0702             if type_id not in self.material_specifiers:
0703                 self.__put(
0704                     f"{template_list}{self.__tabs()}using {type_specifier} = material_map<{algebra}, {shape_specifier}, container_t>;\n"
0705                 )
0706 
0707         self.material_specifiers.setdefault(type_id, []).append(type_specifier)
0708 
0709     # Declare the material types and material store for the detector
0710     def __declare_material_store(self, md: metadata):
0711         # Material types
0712         if md.materials:
0713             self.__lines(2)
0714             # Make sure type IDs are consecutive
0715             for type_id, (_, materials) in enumerate(sorted(md.materials.items())):
0716                 for mat in materials:
0717                     self.__declare_material(mat, type_id, "algebra_type")
0718 
0719             self.__lines(1)
0720             # Add an option for 'no material'
0721             self.__declare_type_enum(
0722                 "material_id",
0723                 self.material_specifiers,
0724                 md.id_base,
0725                 {len(md.materials): ["none"]},
0726             )
0727             self.__lines(2)
0728             self.__define_enum_stream_op(
0729                 "material_id", self.material_specifiers, {len(md.materials): ["none"]}
0730             )
0731         self.__lines(2)
0732 
0733         # Material Store
0734         self.__declare_multi_store(
0735             "material_store", "material_id", self.material_specifiers, is_regular=False
0736         )
0737 
0738     # Write a full acceleration structure type to the metadata header
0739     # and add it to the internal acceleration structure specifier dictionary
0740     def __declare_accel(self, obj_type, acc, type_id: int, value_type: str):
0741         type_specifier = f"{self.__name_from_specifier(acc.specifier)}_t"
0742 
0743         if type_specifier.endswith("grid_t"):
0744             # Assemble the spatial grid type
0745 
0746             # Grid shape
0747             shape_specifier = acc.param["shape"].specifier
0748             shape_name = self.__name_from_specifier(shape_specifier)
0749 
0750             # Grid bin entries
0751             entry_type = "surface_type" if value_type == "surface" else "dindex"
0752 
0753             # Grid bin type
0754             grid_bin = acc.param["bin"].specifier
0755             bin_name = self.__name_from_specifier(grid_bin).removesuffix("_array")
0756             bin_capacity = ""
0757             if "static" in grid_bin:
0758                 bin_capacity = acc.param["bin"].param["capacity"]
0759             bin_type_param = self.__template_list(
0760                 ["bin_entry_t", f"{bin_capacity}"]
0761             ).removeprefix("template ")
0762 
0763             # Grid serializer type
0764             grid_serializer = acc.param["serializer"].specifier
0765             serializer_name = self.__name_from_specifier(grid_serializer).removesuffix(
0766                 "_serializer"
0767             )
0768 
0769             grid_specifier = f"{bin_name}_{serializer_name}_grid_t"
0770 
0771             # First use of this spatial grid? Write common declaration to header
0772             if grid_specifier not in self.grid_specifiers:
0773                 self.__lines(2)
0774                 template_list = "template <typename axes_t, typename bin_entry_t, typename container_t>\n"
0775                 self.__put(
0776                     f"{template_list}{self.__tabs()}using {grid_specifier} = spatial_grid<algebra_type, axes_t, {grid_bin}{bin_type_param}, {grid_serializer}, container_t, false>;"
0777                 )
0778                 self.grid_specifiers.append(grid_specifier)
0779                 self.__lines(2)
0780 
0781             # Declare the final, per-shape grid types
0782             type_specifier = f"{shape_name}_grid_t"
0783             template_list = "template <typename container_t>\n"
0784 
0785             self.__put(
0786                 f"{template_list}{self.__tabs()}using {obj_type}_{type_specifier} = {grid_specifier}<axes<{shape_specifier}>, {entry_type}, container_t>;\n"
0787             )
0788 
0789         self.accel_specifiers.setdefault(type_id, []).append(
0790             f"{obj_type}_{type_specifier}"
0791         )
0792 
0793     # Declare the acceleration structure types and accel store for the detector
0794     def __declare_accel_store(self, md: metadata):
0795         # Acceleration Structures
0796         assert (
0797             len(md.acceleration_structs) > 2
0798         ), "Define at least one default surface(portal) and one default volume acceleration structure"
0799 
0800         assert (
0801             "portal" in md.acceleration_structs.keys()
0802         ), "Define at least one portal acceleration structure"
0803 
0804         assert (
0805             "volume" in md.acceleration_structs.keys()
0806         ), "Define at least one volume acceleration structure"
0807 
0808         if not md.acceleration_structs:
0809             return
0810 
0811         self.__lines(2)
0812         # Make sure an acceleration struct is declared only once,
0813         # even if it is used for multiple surface types
0814         unique_accel = []
0815         for geo_obj, accels in md.acceleration_structs.items():
0816             obj_type = "volume" if "volume" in geo_obj else "surface"
0817             for acc, type_id, value_type in accels:
0818                 if (obj_type, acc, type_id, value_type) not in unique_accel:
0819                     unique_accel.append((obj_type, acc, type_id, value_type))
0820 
0821         # Resolve same accelerator with different type_ids
0822         tmp_specifiers = {}
0823         for obj_type, acc, type_id, value_type in unique_accel:
0824             is_valid_id = type_id >= 0
0825             next_auto_id = (
0826                 0
0827                 if not tmp_specifiers
0828                 else max(len(tmp_specifiers), max(tmp_specifiers) + 1)
0829             )
0830             priority = type_id if is_valid_id else next_auto_id
0831             is_clash = priority in tmp_specifiers
0832             # Resolve clashes
0833             priority = priority + 1 if is_clash else priority
0834 
0835             # Shift lower priority items
0836             if is_clash:
0837                 new_type_dict = {}
0838                 for k, v in sorted(tmp_specifiers.items()):
0839                     new_type_dict[k + 1 if k >= priority else k] = tmp_specifiers[k]
0840 
0841                 # Now swap
0842                 tmp_specifiers, new_type_dict = new_type_dict, tmp_specifiers
0843 
0844             # If the same accelerator is registered multiple times with different priorities, find the smallest priority
0845             if (obj_type, acc, value_type) in tmp_specifiers.values():
0846                 for p, v in tmp_specifiers.items():
0847                     if v == (obj_type, acc, value_type) and priority < p:
0848                         tmp_specifiers[priority] = (obj_type, acc, value_type)
0849                         del tmp_specifiers[p]
0850             else:
0851                 tmp_specifiers[priority] = (obj_type, acc, value_type)
0852 
0853         del unique_accel
0854 
0855         # Declare the accelerator according to their priority, but make sure they are contiguous
0856         for i, (_, values) in enumerate(sorted(tmp_specifiers.items())):
0857             obj_type, acc, value_type = values
0858             self.__declare_accel(obj_type, acc, i, value_type)
0859 
0860         del tmp_specifiers
0861 
0862         # Add options for the default acceleration structs
0863         self.__lines(1)
0864 
0865         # Set enum item for default surface acceleration structure
0866         surface_default = ""
0867         if "grid" in md.default_surface_accel.specifier:
0868             shape_specifier = md.default_surface_accel.param["shape"].specifier
0869             surface_default = (
0870                 f"e_surface_{self.__name_from_specifier(shape_specifier)}_grid"
0871             )
0872         else:
0873             surface_default = f"e_surface_{self.__name_from_specifier(md.default_surface_accel.specifier)}"
0874 
0875         # Set enum item for default volume acceleration structure
0876         volume_default = ""
0877         if "grid" in md.default_volume_accel.specifier:
0878             shape_specifier = md.default_volume_accel.param["shape"].specifier
0879             volume_default = (
0880                 f"e_volume_{self.__name_from_specifier(shape_specifier)}_grid"
0881             )
0882         else:
0883             volume_default = f"e_volume_{self.__name_from_specifier(md.default_volume_accel.specifier)}"
0884 
0885         extra_items = {
0886             surface_default: ["surface_default"],
0887             volume_default: ["volume_default"],
0888         }
0889 
0890         # Type enumeration
0891         self.__declare_type_enum(
0892             "accel_id",
0893             self.accel_specifiers,
0894             md.id_base,
0895             extra_items=extra_items,
0896         )
0897 
0898         # Output stream operator for type enumeration
0899         self.__lines(2)
0900         self.__define_enum_stream_op(
0901             "accel_id",
0902             self.accel_specifiers,
0903         )
0904 
0905         # Accelerator Store
0906         self.__lines(2)
0907         self.__declare_multi_store(
0908             "accelerator_store", "accel_id", self.accel_specifiers, is_regular=False
0909         )
0910 
0911     # Declare the geometry object types (e.g. passive, portal, sensitive)
0912     # that are distinguishable to the volume: use enum values to link a
0913     # geometry object type category to the corresponding accel. struct
0914     def __declare_geometry_objects(self, md: metadata):
0915         # Helper to determine if an accel. struct is one of the defaults
0916         def is_default_accel(value_type, accel):
0917             is_surface_default = (
0918                 value_type == "surface" and accel is md.default_surface_accel.specifier
0919             )
0920             is_volume_default = (
0921                 value_type == "index" and accel is md.default_volume_accel.specifier
0922             )
0923 
0924             return is_surface_default or is_volume_default
0925 
0926         # Enumerate the different geometric objects and assign them to the accel
0927         # link of the corresponding acceleration structure, e.g.
0928         # geo_id:  value_type:        accel_link [accel_id, accel_idx]
0929         # ---------------------------------------------------------------------
0930         # 0:       portal/passive:  [brute_force, 0] <- two in one accel. struct
0931         # 1:       sensitive:       [disk_grid, 14]  <- distinct accel. struct
0932         # 2:       volume:          [brute_force, 2] <- distinct accel. struct
0933 
0934         # Find which geometric objects go together into which accel. struct
0935         accel_to_types = {}
0936         for t, accels in md.acceleration_structs.items():
0937             for a, i, v in accels:
0938                 specifier = f"{a.specifier}"
0939 
0940                 if (specifier, i, v) not in accel_to_types:
0941                     accel_to_types[specifier, i, v] = set()
0942 
0943                 accel_to_types[specifier, i, v].add(t)
0944 
0945         # Get every accelerator for which a specific type ID is requested
0946         type_id_dict = {}
0947         for acc, type_id, value_type in accel_to_types.keys():
0948             if type_id > -1:
0949                 type_id_dict.setdefault((type_id, value_type), []).append(acc)
0950 
0951         # Find a representative for each category and merge the obj type sets
0952         accel_to_types_merged = {}
0953         for acc, type_id, value_type in accel_to_types.keys():
0954             representative = acc
0955             if (
0956                 not is_default_accel(value_type, acc)
0957                 and (type_id, value_type) in type_id_dict
0958                 # and len(type_id_dict[type_id, value_type]) > 1
0959             ):
0960                 tmp_repr = type_id_dict[type_id, value_type][0]
0961                 representative = (
0962                     type_id_dict[type_id, value_type][1]
0963                     if is_default_accel(value_type, tmp_repr)
0964                     else tmp_repr
0965                 )
0966 
0967             if (representative, value_type) not in accel_to_types_merged:
0968                 accel_to_types_merged[representative, value_type] = (
0969                     set(accel_to_types[acc, type_id, value_type]),
0970                     type_id,
0971                 )
0972             else:
0973                 obj_set, priority = accel_to_types_merged[representative, value_type]
0974                 obj_set.update(accel_to_types[acc, type_id, value_type])
0975 
0976                 # Update the priority for the representative
0977                 if type_id >= 0 and (priority == -1 or priority < type_id):
0978                     accel_to_types_merged[representative, value_type] = (
0979                         obj_set,
0980                         type_id,
0981                     )
0982 
0983         # Check duplicate sets (make the set hashable by converting to tuple)
0984         counted_dict = Counter(
0985             [tuple(sorted(s)) for (s, type_id) in accel_to_types_merged.values()]
0986         )
0987         duplicates = {
0988             key: (value, type_id)
0989             for key, (value, type_id) in accel_to_types_merged.items()
0990             if counted_dict[tuple(sorted(value))] > 1
0991         }
0992 
0993         # Get the list of keys for every duplicate
0994         flipped_duplicates = {}
0995         for key, value in duplicates.items():
0996             obj_set, type_id = value
0997             flipped_duplicates.setdefault((tuple(sorted(obj_set)), type_id), []).append(
0998                 key
0999             )
1000 
1001         # Find best representative key for the duplicates and remove the others
1002         removal_keys = []
1003         for key, value in flipped_duplicates.items():
1004             # Keep the key with the smallest required type ID
1005             type_id_counter = 10000
1006             _, type_id = key
1007             for acc, value_type in value:
1008                 # Do not remove it if it the default acceleration structure
1009                 if is_default_accel(value_type, acc):
1010                     continue
1011                 # Remove the non-specific type ID of "-1" in any case
1012                 if type_id == -1 or type_id >= type_id_counter:
1013                     removal_keys.append((acc, value_type, type_id))
1014                 else:
1015                     type_id_counter = type_id
1016 
1017         for rk in removal_keys:
1018             accel_to_types_merged.pop(rk, None)
1019 
1020         # Sort, in order to find the largest geo object sets
1021         accel_to_types_sorted = dict(
1022             sorted(
1023                 accel_to_types_merged.items(),
1024                 key=lambda item: len(item[1]),
1025                 reverse=True,
1026             )
1027         )
1028 
1029         # Link slot to geometry object types
1030         accel_link_types = {}
1031 
1032         # Add a new link slot, if there are previously unknown object types
1033         def add_link(key, new_objects):
1034             new_link_types = [
1035                 l
1036                 for l in sorted(new_objects)
1037                 if l not in itertools.chain(*accel_link_types.values())
1038             ]
1039 
1040             if new_link_types:
1041                 accel_link_types[key] = new_link_types
1042 
1043         for (accel, value_type), (obj_set, type_id) in accel_to_types_sorted.items():
1044             # Only add the default methods where no other accelerator is
1045             # available (see below)
1046             if is_default_accel(value_type, accel):
1047                 continue
1048 
1049             add_link(key=type_id, new_objects=obj_set)
1050 
1051         # Add the default link for the leftover surface and volume types
1052         surface_default_list = [
1053             v
1054             for k, (v, t) in accel_to_types_sorted.items()
1055             if "surface" in k and md.default_surface_accel.specifier in k
1056         ]
1057         add_link(
1058             key="surface_default",
1059             new_objects=itertools.chain.from_iterable(surface_default_list),
1060         )
1061 
1062         volume_default_list = [
1063             v
1064             for k, (v, t) in accel_to_types_sorted.items()
1065             if "index" in k and md.default_volume_accel.specifier in k
1066         ]
1067         add_link(
1068             key="volume_default",
1069             new_objects=itertools.chain.from_iterable(volume_default_list),
1070         )
1071 
1072         # Write the id enum for the types of distinct geometric objects
1073         self.__lines(2)
1074         self.__put(f"enum geo_objects : {md.id_base} {{\n")
1075 
1076         self.indent = self.indent + 1
1077 
1078         # The surface accelerator that contains the portals has to be in slot 0:
1079         portal_key, portal_group = [
1080             (k, v) for (k, v) in accel_link_types.items() if "portal" in v
1081         ][0]
1082 
1083         if not portal_group:
1084             self.logger.error(
1085                 "No acceleration structure link define for portal surfaces!"
1086             )
1087             return
1088 
1089         for gid in portal_group:
1090             self.__put(f"e_{gid} = 0u,\n")
1091 
1092         # Loop over the other link groups and enumerate them
1093         i = 1
1094         for key, link_group in accel_link_types.items():
1095             if key == portal_key:
1096                 continue
1097             for gid in link_group:
1098                 self.__put(f"e_{gid} = {i}u,\n")
1099                 i = i + 1
1100 
1101         self.__put(f"e_size = {len(accel_link_types)}u,\n")
1102         self.__put("e_all = e_size,\n")
1103 
1104         self.indent = self.indent - 1
1105 
1106         self.__put("};")
1107 
1108         # Add streaming operator for geo_objects enum
1109         self.__lines(2)
1110         self.__define_enum_stream_op(
1111             "geo_objects",
1112             accel_link_types,
1113             extra_items={"e_size": ["size"]},
1114         )
1115 
1116         # Add the surface acceleration struct link to the volume descriptor
1117         self.__lines(2)
1118         self.__put(
1119             "using object_link_type = dmulti_index<dtyped_index<accel_id, dindex>, geo_objects::e_size>;"
1120         )
1121 
1122     # Close the header file
1123     def __finish(self):
1124         self.__lines(1)
1125         self.indent = self.indent - 1
1126         self.__put("};\n\n} // namespace detray\n")
1127         self.file.close()
1128 
1129         # Document the generated declarations
1130         with open(self.file.name) as header:
1131             text = header.read()
1132         with open(self.file.name, "w") as header:
1133             header.write(_add_doc_comments(text, self.det_name))
1134 
1135         self.logger.debug("Wrote file to disk")
1136 
1137         # Run code formatting
1138         if self.format_header and os.path.isfile(self.file.name):
1139             logging.debug("Formatting the header...")
1140             try:
1141                 subprocess.run(
1142                     ["clang-format", "-i", "-style=file", self.file.name], check=True
1143                 )
1144             except FileNotFoundError:
1145                 logging.error("clang-format not found!")
1146             except PermissionError:
1147                 logging.error("Permission denied: clang-format!")
1148             except OSError:
1149                 logging.error("Cannot open clang-format!")
1150             except subprocess.CalledProcessError:
1151                 logging.error("Running 'clang-format' failed!")
1152             except Exception as e:
1153                 logging.error(f"Unexpected error for clang-format: {e}")
1154                 raise
1155 
1156 
1157 # Doxygen comments for the generated declarations, keyed by declaration name
1158 _ENUM_DOCS = {
1159     "mask_id": "Identifiers for the supported surface masks.",
1160     "material_id": "Identifiers for material payload and map alternatives.",
1161     "accel_id": "Identifiers for navigation accelerator alternatives.",
1162     "geo_objects": "Categories used to distinguish detector geometry objects.",
1163 }
1164 
1165 _LINK_TYPES = (
1166     "nav_link",
1167     "transform_link",
1168     "mask_link",
1169     "material_link",
1170     "object_link_type",
1171 )
1172 
1173 _MATERIAL_TYPES = ("material_slab_t", "material_rod_t", "raw_material_t")
1174 
1175 
1176 def _using_doc(name):
1177     if name == "algebra_type":
1178         return "Algebra backend used by this detector metadata."
1179     if name == "scalar_t":
1180         return "Scalar type associated with the selected algebra backend."
1181     if name in _LINK_TYPES:
1182         return "Link type used to refer to the corresponding detector component store."
1183     if name == "surface_type":
1184         return "Surface descriptor type combining links to its geometry components."
1185     if name.endswith("_store"):
1186         return "Store type holding the corresponding detector component collection."
1187     if name.endswith("_map_t"):
1188         return "Material map type associated with this surface shape."
1189     if name.endswith("_grid_t"):
1190         return "Grid type used to index the corresponding detector components."
1191     if name in _MATERIAL_TYPES:
1192         return "Material representation used by this detector metadata."
1193     return "Type alias used by this detector metadata configuration."
1194 
1195 
1196 def _struct_doc(det_name):
1197     if det_name == "default":
1198         return [
1199             "Type and storage policy used to assemble a detector from geometry and",
1200             "material components.",
1201         ]
1202     name = det_name.replace("_", " ")
1203     return [f"Detector-specific aliases and storage policy for {name} geometry."]
1204 
1205 
1206 def _add_doc_comments(text, det_name):
1207     """Put a Doxygen comment in front of every generated declaration."""
1208     using_re = re.compile(r"^(\s*)using (\w+)\b")
1209     enum_re = re.compile(r"^(\s*)enum (?:class )?(\w+)\b")
1210     struct_re = re.compile(rf"^(\s*)struct {re.escape(det_name)}_metadata\b")
1211 
1212     lines = text.split("\n")
1213     result = []
1214     for line in lines:
1215         docs = []
1216         indent = ""
1217         is_struct = False
1218         if match := using_re.match(line):
1219             indent, name = match.groups()
1220             docs = [_using_doc(name)]
1221         elif (match := enum_re.match(line)) and match.group(2) in _ENUM_DOCS:
1222             indent, name = match.groups()
1223             docs = [_ENUM_DOCS[name]]
1224         elif match := struct_re.match(line):
1225             indent = match.group(1)
1226             docs = _struct_doc(det_name)
1227             is_struct = True
1228         if docs:
1229             # Struct comments go in front of the template parameter list
1230             position = len(result)
1231             if is_struct and result and result[-1].lstrip().startswith("template"):
1232                 position -= 1
1233             result[position:position] = [f"{indent}/// {doc}" for doc in docs]
1234         result.append(line)
1235     return "\n".join(result)