routing.core.cadmap#

CadMap class and associated functions.

class routing.core.cadmap.CadMap(design_rules: list[InstanceOf[DesignRule]], ruled_volumes: list[RuledVolume], bounding_box: RuledVolume | None = None, exact_distances: bool = False, weights_operator: str = 'min', room_voxels: RoomVoxelization | None = None, distances: list[Array] | None = None, weights: list[Array] | None = None, voxel_inside: bool = False, voxel_primitives: list[Primitive3D] | None = None, name: str = '')[source]#

Bases: Object3D

A class representing the central mapping object for routing that manages volumes, voxelization, and routing state.

The core data structure that combines ruled volumes with design rules, voxelized space representation, distance and weight matrices for pathfinding, pipe history and packs for optimization, and pooling rules for pipe grouping.

Parameters:
  • design_rules – The list of DesignRule objects applied globally to all volumes.

  • ruled_volumes – The list of RuledVolume objects defining the routing space.

  • bounding_box – The optional RuledVolume defining the overall problem boundaries. If None, computed automatically from ruled_volumes with in_border=True. Defaults to None.

  • exact_distances – Flag indicating whether to use exact mesh-based distance calculation (slower but more accurate). Defaults to False.

  • weights_operator – The operator for combining weights from multiple volumes (‘min’, ‘max’, or ‘sum’). Defaults to ‘min’.

  • room_voxels – The optional RoomVoxelization representing the traversable space. Defaults to None.

  • distances – The optional list of compressed distance matrices (zarr arrays), one per ruled volume. Defaults to None.

  • weights – The optional list of compressed weight matrices (zarr arrays), one per ruled volume. Defaults to None.

  • voxel_inside – Flag indicating whether enclosed voxels are filled during voxelization. Defaults to False.

  • voxel_primitives – The optional list of primitives for voxel visualization. Defaults to None.

  • name – The name to identify this CadMap. Defaults to ‘’.

apply_pooling_coefficients(coefficients: ndarray, forbidden_voxels: ndarray) ndarray[source]#

Apply pooling coefficients to the weight tensor.

Modifies weights based on pooling coefficients: positive coefficients reduce weights (favor pooling), negative coefficients increase weights (segregation), and forbidden voxels are set to 0 (non-traversable).

Parameters:
  • coefficients – 3D array of pooling coefficients (NaN where not applicable).

  • forbidden_voxels – 3D boolean array marking forbidden voxels.

Returns:

Updated weight tensor with pooling effects applied.

apply_shaped_weighting_rules() None[source]#

Apply all shaped weighting rules to the weight tensor in-place.

This method is called after the standard weight composition to apply shape-based weight modifications (attractive, repulsive, forbidden, forced zones). The weight_tensor is modified directly.

classmethod build_bounding_volume(ruled_volumes: list[RuledVolume], border_rules: list[InstanceOf[DesignRule]] | None = None, voxel_size: float = 1.0, voxel_margin: float = 0.0) RuledVolume[source]#

Build a bounding volume to voxelize CadMap only in volume of interest.

This method has to be explicitly called to be run.

classmethod build_bounding_volume_light(ruled_volumes: list[RuledVolume], weighting_rules: list[WeightingRule] | None = None, voxel_size: float = 1.0, voxel_margin: float = 0.0) RuledVolume[source]#

Build a bounding volume (lightweight version using weighting rules).

Convenience method that calls build_bounding_volume with weighting_rules as border_rules. This is a simplified interface for common use cases.

Parameters:
  • ruled_volumes – List of RuledVolume objects to compute bounding box from.

  • weighting_rules – Optional list of WeightingRule objects to apply as border rules. Defaults to None.

  • voxel_size – Voxel size for voxelizing the bounding box. Defaults to 1.0.

  • voxel_margin – Additional margin in voxel units to add to bounding box. Defaults to 0.0.

Returns:

RuledVolume representing the bounding box.

build_pooling_matrices(types: list[str]) None[source]#

Build pooling matrices for PoolingRule to work.

Initializes the distance and coefficient matrices in the pooling rule for all pipe type combinations. These matrices define: - Minimum distances required between different pipe types - Pooling coefficients that modify routing costs when pipes are grouped

This method must be called before using pooling features in routing. The matrices are built for all combinations of pipe types in the provided list.

Parameters:

types – List of pipe type identifiers (strings) to build matrices for. All pairwise combinations of these types will have entries in the matrices.

Returns:

None

collect_packs(only_optimized: bool = True) list[Pack][source]#

Collect all best_pipe.pipe_lines in all generated packs for defining a Pack with its best pipe_lines.

compose_weights() ndarray[source]#

Compose all weight tensors into a single tensor using the chosen operator.

Combines weight matrices from all ruled volumes into a single weight tensor using the weights_operator specified in the CadMap. The result is stored in weight_tensor and used for pathfinding. Different operators have different semantics:

  • “min”: Takes the minimum weight across all volumes at each voxel (most restrictive constraint wins)

  • “min_distance”: Selects weight from the volume with minimum distance (prioritizes closest volume’s constraints)

  • “max”: Takes the maximum weight across all volumes at each voxel (most permissive constraint wins)

  • “max_distance”: Selects weight from the volume with maximum distance (prioritizes farthest volume’s constraints)

  • “sum”: Sums weights from all volumes (additive penalties)

  • “mean”: Averages weights from all volumes (balanced approach)

Note: Only “min_distance” typically gives expected results for routing.

Returns:

Composed weight tensor of same shape as room_voxels.matrix.

Raises:

NotImplementedError – If weights_operator is not recognized.

compute_distances(voxelization: MatrixBasedVoxelization)[source]#

Compute distance matrices for all ruled volumes in the CadMap.

Computes distance from each voxel to each ruled volume surface using the CadMap’s exact_distances setting. The bounding box is included if it has design rules.

Parameters:

voxelization – The MatrixBasedVoxelization to compute distances for.

Returns:

List of compressed distance arrays (zarr format), one per volume.

compute_weights() list[Array][source]#

Compute weights for each ruled volume using their design rules.

Applies all design rules (global and volume-specific) to compute weight matrices from distance matrices. Weights represent routing costs/penalties at each voxel based on proximity to volumes.

Returns:

List of compressed weight arrays (zarr format), one per volume.

copy_history(cadmap: CadMap) None[source]#

Copy history from another CadMap.

Placeholder method for copying routing history (packs, distances, etc.) from another CadMap. Currently not fully implemented.

Parameters:

cadmap – The source CadMap to copy history from.

Returns:

None

crop_and_upscale(point_inside: ndarray, bounding_box: BoundingBox, voxel_size: float) CadMap[source]#

Method to crop a CadMap inside a bounding_box to increase local voxel definition.

This method comes from initial researches on optimization domains definition and because it is not the method used finally in standard mode, it should be tested before use.

crop_with_bounding_box(bounding_box: BoundingBox) CadMap[source]#

Crop a CadMap to a bounding box without recomputing voxelization.

Creates a new CadMap containing only the portions of ruled volumes that intersect with the given bounding box. The voxelization is not recomputed, so this is faster than creating a new CadMap from scratch.

Parameters:

bounding_box – BoundingBox defining the crop region.

Returns:

New CadMap containing only volumes within the bounding box.

static extract_point_carrier_voxels(voxels: MatrixBasedVoxelization, point: ndarray) MatrixBasedVoxelization[source]#

Get the connected component that contains a given point.

Extracts all connected components and returns the one that contains the specified point. Useful for isolating the traversable region containing a specific location.

Parameters:
  • voxels – MatrixBasedVoxelization that may contain disconnected regions.

  • point – 3D point as (x, y, z) array to find the containing component.

Returns:

MatrixBasedVoxelization containing only the connected component with the point.

classmethod from_project_inputs(design_rules: list[InstanceOf[DesignRule]], ruled_volumes: list[RuledVolume], bounding_box: RuledVolume | None = None, voxel_size: float = 0.1, exact_distances: bool = False, weights_operator: str = 'min', voxel_inside: bool = False, build_cad: bool = False, name: str = '') CadMap[source]#

Build a CadMap from project inputs.

This is the main factory method for creating a CadMap from raw project data. It performs the complete initialization workflow: 1. Creates a CadMap instance with design rules and ruled volumes 2. Voxelizes the empty space (room) between volumes 3. Computes distance matrices from each volume to all voxels 4. Computes weight matrices by applying design rules to distances 5. Optionally builds CAD primitives for visualization

The resulting CadMap is ready for pathfinding operations after calling to_grid().

Parameters:
  • design_rules – List of DesignRule objects that are common to all designed objects. Examples include TurnPenalizer, WeightingRule, etc. These rules are applied globally to all volumes.

  • ruled_volumes – List of RuledVolume objects representing material volumes (obstacles) in the routing space. A RuledVolume is essentially a VolumeModel with associated DesignRules.

  • bounding_box – Optional RuledVolume defining the BoundingBox of the voxelization domain. If None, computed automatically from volumes with in_border=True. Defaults to None.

  • voxel_size – Size of each voxel in length units. Smaller values give higher precision but require more memory and computation time. Defaults to 0.1.

  • exact_distances – Flag indicating distance computation method. If True, computes exact distances from triangle meshes (slower but more accurate). If False, uses faster voxel-based approximation. Defaults to False.

  • weights_operator – Method to compose weights from multiple volumes. Options: “min”, “max”, “sum”, “mean”, “min_distance”, “max_distance”. Note: Only “min_distance” typically gives expected results for routing. Defaults to “min”.

  • voxel_inside – If True, voxelization will fill enclosed voxels inside RuledVolumes (for routing through volumes). If False, only voxels outside volumes are considered traversable. Defaults to False.

  • build_cad – Flag indicating whether to build CAD primitives for voxel visualization. If True, creates Box primitives for each voxel (memory intensive for large grids). Defaults to False.

  • name – Name identifier for this CadMap. Used for debugging and serialization. Defaults to ‘’.

Returns:

Fully initialized CadMap instance ready for routing operations.

classmethod from_project_inputs_light(ruled_volumes: list[RuledVolume], weighting_rules: list[WeightingRule], pooling_rule: PoolingRule, turn_penalizer: TurnPenalizer, bounding_box: RuledVolume | None = None, voxel_size: float = 0.1, name: str = '') CadMap[source]#

Build a CadMap from project inputs (lightweight/convenience version).

This is a convenience wrapper around from_project_inputs() that uses recommended default settings for common routing scenarios: - exact_distances=True (more accurate distance computation) - weights_operator=”min_distance” (recommended for routing) - voxel_inside=False (route outside volumes) - build_cad=True (enable visualization)

It automatically combines the provided design rules (weighting_rules, pooling_rule, turn_penalizer) into a single design_rules list.

Use this method when you want a fully configured CadMap with standard routing settings without specifying all parameters explicitly.

Parameters:
  • weighting_rules – List of WeightingRule objects that define how routing costs vary with distance to CAD volumes. These rules convert distances to weights (costs) for pathfinding.

  • pooling_rule – PoolingRule object for managing pooling and segregation between conduits. Defines which pipe types can be grouped together and minimum distances between them.

  • turn_penalizer – TurnPenalizer object that adds cost to bends in the routing path. Encourages straighter paths.

  • ruled_volumes – List of RuledVolume objects representing material volumes (obstacles) in the routing space. A RuledVolume is essentially a VolumeModel with associated DesignRules.

  • bounding_box – Optional RuledVolume defining the BoundingBox of the voxelization domain. If None, computed automatically from volumes with in_border=True. Defaults to None.

  • voxel_size – Size of each voxel in length units. Smaller values give higher precision but require more memory. Defaults to 0.1.

  • name – Name identifier for this CadMap. Used for debugging and serialization. Defaults to ‘’.

Returns:

Fully initialized CadMap instance with recommended settings, ready for routing operations.

classmethod from_voxelization(design_rules: list[InstanceOf[DesignRule]], ruled_volumes: list[RuledVolume], voxelization: MatrixBasedVoxelization, weights_operator: str = 'min', build_cad: bool = False, distances: list[ndarray] | None = None) CadMap[source]#

Build a CadMap from a pre-existing voxelization.

This method creates a CadMap when you already have a MatrixBasedVoxelization (e.g., from a previous computation or external source). It skips the voxelization step and directly uses the provided voxelization.

The method: 1. Creates a bounding box from the voxelization’s bounding box 2. Creates a RoomVoxelization from the MatrixBasedVoxelization 3. Computes or uses provided distance matrices 4. Computes weight matrices from distances 5. Composes weights into a single tensor

This is useful when: - Reusing voxelizations from previous computations - Working with voxelizations from external sources - Avoiding redundant voxelization computations

Parameters:
  • design_rules – List of DesignRule objects to apply globally. These rules affect how weights are computed from distances.

  • ruled_volumes – List of RuledVolume objects representing material volumes. These are used for distance computation and weight calculation.

  • voxelization – Pre-computed MatrixBasedVoxelization representing the traversable space. Must be compatible with the ruled volumes.

  • weights_operator – Method to compose weights from multiple volumes. Options: “min”, “max”, “sum”, “mean”, “min_distance”, “max_distance”. Defaults to “min”.

  • build_cad – Flag indicating whether to build CAD primitives for voxel visualization. If True, creates Box primitives for each voxel. Defaults to False.

  • distances – Optional list of pre-computed distance matrices (numpy arrays). If provided, these are compressed and used directly. If None, distances are computed from ruled volumes using exact_distances=True. Defaults to None.

Returns:

Fully initialized CadMap instance using the provided voxelization.

get_bifurcation_points(packs: list[Pack], tolerance: float | None, with_ports: bool = False) list[ndarray][source]#

Get all bifurcation points of the pack.

get_packs_zones_coefficients(pipe_type: PipeType) tuple[ndarray, ndarray][source]#

Build matrices of applied coefficients and forbidden voxels from all packs.

Computes pooling coefficients and forbidden voxel masks by aggregating contributions from all packs in the CadMap. These are used to modify weights based on pipe placement history.

Parameters:

pipe_type – PipeType to compute coefficients for.

Returns:

Tuple of (coefficients, forbidden_voxels) where: - coefficients: 3D array with pooling coefficients (NaN where not applicable) - forbidden_voxels: 3D boolean array marking non-traversable voxels

get_primitives() list[Primitive3D][source]#

Get all 3D primitives from CadMap including packs and solutions.

Collects primitives from all solutions and the CadMap’s own primitives (ruled volumes and voxelization) for complete visualization.

Returns:

List of all Primitive3D objects from solutions and CadMap.

get_toggled_constraints() dict[str, tuple[ConstraintRule, ndarray, ndarray]][source]#

Get all toggled constraints from ConstraintRule and DistanceAttributeToggler rules.

Collects constraint rules that are activated by distance-based attribute togglers. Returns a dictionary mapping attribute names to tuples of (constraint_rule, boolean_matrix, distance_matrix).

Returns:

Dictionary mapping attribute names to (ConstraintRule, boolean_matrix, distance_matrix) tuples.

static get_volume_in_border(ruled_volumes: list[RuledVolume]) list[RuledVolume][source]#

Get all ruled volumes that define the bounding box.

Filters ruled volumes to return only those with in_border=True, which are used to compute the overall bounding box of the routing problem.

Parameters:

ruled_volumes – List of RuledVolume objects to filter.

Returns:

List of RuledVolume objects with in_border=True.

is_point_in_voxels(point: ndarray) bool[source]#

Check if a 3D point is in a voxel with a non-null weight.

Converts the point to voxel coordinates and checks if the corresponding voxel has a non-zero weight (is traversable).

Parameters:

point – 3D point as (x, y, z) array.

Returns:

True if point is in a traversable voxel, False otherwise.

load_ports_points(specifications: list[Specification]) None[source]#

Update port positions stored in CadMap.

static merge_packs(packs: list[Pack]) list[Pack][source]#

Merge all packs that share pipelines.

Iteratively merges packs that share at least one common pipe line or are compatible based on parallelism. Continues until no more merges are possible.

Parameters:

packs – List of Pack objects to merge.

Returns:

List of merged Pack objects (fewer than input if merges occurred).

property nbytes: int#

Calculate the total memory usage in bytes of the CadMap.

Computes the total memory footprint including room voxels matrix, compressed distance and weight arrays, and other large data structures.

Returns:

Total memory usage in bytes.

property occupancy_ratio: float#

Calculate the ratio of occupied voxels to total voxels.

Returns the fraction of voxels that are active (True) in the room voxelization, indicating how much of the space is traversable.

Returns:

Ratio between 0.0 and 1.0, where 1.0 means all voxels are active.

property pipe_types: dict[str, PipeType]#

Get dictionary of pipe types from solutions.

Extracts all unique pipe types from the solutions list, indexed by their names.

Returns:

Dictionary mapping pipe type names to PipeType objects.

points_are_in_voxels(voxels: list[tuple[int, int, int]]) bool[source]#

Check if all given voxel indices correspond to active voxels.

Delegates to room_voxels to validate that all provided voxel indices are within bounds and point to active (True) voxels.

Parameters:

voxels – List of voxel indices as (i, j, k) tuples.

Returns:

True if all voxel indices are valid and active, False otherwise.

property pooling_rule: PoolingRule#

Get the PoolingRule from design rules.

Searches for a PoolingRule in the design rules. If found and history is enabled, returns it. Otherwise returns an empty PoolingRule.

Returns:

PoolingRule instance from design rules or empty PoolingRule.

property shaped_weighting_rules: list[ShapedWeightingRule]#

Get all shaped weighting rules of Cadmap.

show_with_points(points: list[ndarray]) None[source]#

Visualize CadMap with bifurcation points in a 3D viewer.

show_with_solutions() None[source]#

Visualize CadMap with all packs and solutions in a 3D viewer.

Creates a complete 3D visualization including all ruled volumes, voxelization, packs, and routing solutions.

Returns:

None

solutions_with_crossed_voxels() None[source]#

Visualize all solutions with their crossed voxels highlighted.

Creates a 3D visualization showing all routing solutions along with the voxels they cross, each colored according to its pipe type.

Returns:

None

to_graph() None[source]#

Convert CadMap to a graph representation.

Placeholder method for future graph export functionality. Currently not implemented.

Returns:

None

to_grid(grid_id: int = 0) SmartGrid[source]#

Convert CadMap to SmartGrid for pathfinding.

Creates a SmartGrid from the CadMap’s voxelization, composed weights, design rules, and toggled attributes. This grid is used by pathfinding algorithms (A*, Dijkstra, etc.) to find routes between ports.

The conversion process: 1. Composes all weight tensors into a single weight tensor 2. Collects toggled attributes from DistanceAttributeToggler rules 3. Combines global design rules with pipe-specific rules 4. Creates a SmartGrid with all this information

The resulting grid can be used with SmartFinder or SmartWorld to compute optimal paths between ports.

Parameters:

grid_id – Unique identifier for this grid (for multi-grid routing). Defaults to 0. Useful when routing across multiple grids with different voxel sizes or spatial regions.

Returns:

SmartGrid instance ready for pathfinding operations.

to_matrix_based_voxelization(voxel_size: float) MatrixBasedVoxelization[source]#

Build a new MatrixBasedVoxelization from CadMap with a new voxel size.

Creates a new voxelization of the routing space using a different voxel size, useful for multi-scale routing or refining the voxel grid. The method: 1. Creates a temporary CadMap with duplicated volumes 2. Voxelizes the space with the new voxel size 3. Returns the resulting MatrixBasedVoxelization

This is useful when you need to: - Refine a coarse grid for more precise routing - Create a coarser grid for faster initial pathfinding - Generate multiple resolution levels for hierarchical routing

Note: This creates a new CadMap internally but only returns the voxelization. Distances and weights are not computed for the new voxelization.

Parameters:

voxel_size – New voxel size in length units. Must be positive.

Returns:

MatrixBasedVoxelization with the new voxel size representing the traversable space (room) between ruled volumes.

to_trimesh()[source]#

Convert CadMap to a trimesh representation.

Creates a trimesh object from all ruled volumes’ meshes, useful for 3D visualization and geometric operations with the trimesh library.

Returns:

Trimesh object representing all ruled volumes.

unlock_line_crossed_voxels(line: PipeLine) None[source]#

Unlock (make traversable) voxels crossed by a pipe line.

Sets weights to 1 (minimum cost) for all voxels crossed by the line, and marks them as active in the room voxelization matrix.

Parameters:

line – PipeLine whose crossed voxels should be unlocked.

Returns:

None

unlock_voxels_between_points(point_1: Point3D, point_2: Point3D, radius: float) None[source]#

Unlock (make traversable) voxels between two points.

Creates a temporary pipe line between the points and unlocks all voxels it crosses, setting their weights to 1 (minimum cost). Useful for forcing a path through specific regions.

Parameters:
  • point_1 – Start point as Point3D.

  • point_2 – End point as Point3D.

  • radius – Pipe radius for computing crossed voxels.

Returns:

None

update_grid(grid: SmartGrid, overweighted_voxels: ndarray | None = None) None[source]#

Update an existing SmartGrid with new weights and attributes.

Updates the grid’s weights, design rules, and toggled attributes. Optionally applies penalty multipliers to overweighted voxels (voxels that were problematic during optimization).

Parameters:
  • grid – The SmartGrid to update.

  • overweighted_voxels – Optional array of voxel indices that should receive penalty multipliers. Defaults to None.

Returns:

None

update_packs(solution: Solution) None[source]#

Update the current packs with sections of pipelines from the given solution.

Groups pipelines by similar direction and either assigns them to existing compatible packs or creates new ones. Also updates the shape of each pack based on crossed voxels.

Parameters:

solution – A solution object containing the best pipe and its segments.

update_packs_with_last_pipe(pipe: OptimizedPipe, solution: Solution, parallel: bool) None[source]#

Update all packs with the newly generated pipe.

Adds pipe lines from the optimized pipe to existing compatible packs, or creates new packs for lines that don’t fit in existing packs. Merges packs that become compatible after adding new lines.

Parameters:
  • pipe – OptimizedPipe containing pipe lines to add.

  • solution – Solution associated with the pipe.

  • parallel – Flag indicating if pipe lines are parallel.

Returns:

None

update_weights_from_connectivity() None[source]#

Update weight tensors to zero out voxels not in the main connected component.

Placeholder method for single CadMap. Connectivity analysis is only relevant for MultiCadMap where multiple grids need connectivity checking.

Returns:

None

update_weights_with_history(pipe_type: PipeType) None[source]#

Update weights based on pipe type and history distances.

Parameters:

pipe_type – Type of pipe to update weights for

update_with_pipe_type(solution: Solution) None[source]#

Update CadMap with pipe type-specific constraints and weights.

Applies pipe type properties to volumes, extracts global weighting rules, and updates weights to reflect the current pipe type’s constraints. This prepares the CadMap for routing a specific pipe type.

Parameters:

solution – Solution containing the pipe type to apply.

Returns:

None

volmdlr_primitives() list[Primitive3D][source]#

Get volmdlr primitives of CadMap (volumes + voxelization).

Returns all 3D geometric primitives representing the ruled volumes and optionally the voxelization for visualization.

Returns:

List of Primitive3D objects from ruled volumes and voxelization.

property with_history: bool#

Check if CadMap has history tracking enabled.

History is enabled when a PoolingRule is present in the design rules, allowing tracking of pipe placement for optimization.

Returns:

True if history tracking is enabled, False otherwise.

class routing.core.cadmap.MultiCadMap(cad_maps: list[CadMap], name: str = '')[source]#

Bases: Object3D

A class representing a unified container for multiple CadMaps.

Provides a container for multiple CadMap objects, supporting both mono-scale (multiple sub-grids with same voxel size) and multi-scale (cad_maps[0] = main, others = fine grids) scenarios.

Parameters:
  • cad_maps – The list of CadMap instances.

  • name – The name for the MultiCadMap. Defaults to ‘’.

apply_shaped_weighting_rules() None[source]#

Apply new weights within shapes stored in shaped weighting rules.

build_connectivity_graph(apply_weights: bool = False) tuple[Graph, dict[int, ndarray]][source]#

Build adjacency graph of connected voxelization components across all CadMaps.

Each node represents a connected component from a CadMap, and edges represent spatial adjacency between components of different scales.

Parameters:

apply_weights – If True, filter voxels with zero weight from weight_tensor

Returns:

Tuple of (graph, component_indices_dict) where: - graph: NetworkX graph where nodes are (cadmap_idx, component_idx) tuples - component_indices_dict: Dict mapping cadmap_idx to component_indices matrix

build_pooling_matrices(types: list[str]) None[source]#

Build pooling matrices for PoolingRule to work.

collect_packs(only_optimized: bool = True) list[Pack][source]#

Collect all best_pipe.pipe_lines in all generated packs for defining a Pack with its best pipe_lines.

property design_rules: list[InstanceOf[DesignRule]]#

Get design rules from the main CadMap.

Returns:

List of DesignRule objects from the main CadMap.

classmethod from_cad_map(cad_map: CadMap, multi_scale: bool = False, size_factor: int = 3, bounding_box: BoundingBox | None = None) MultiCadMap[source]#

Create MultiCadMap from existing CadMap.

Parameters:
  • cad_map – Source CadMap to build from

  • multi_scale – Enable hierarchical multi-scale grids

  • size_factor – Scale factor for fine grids

  • bounding_box – Optional bounding box to limit voxel creation. Only voxels within this box will be created. Useful for multi-scale scenarios to focus computation on a specific region.

classmethod from_cad_maps(cad_maps: list[CadMap], name: str = '') MultiCadMap[source]#

Create MultiCadMap from a list of CadMaps with the same voxel size.

Parameters:
  • cad_maps – List of CadMap instances with the same voxel size

  • name – Name for the MultiCadMap

classmethod from_project_inputs(design_rules: list[InstanceOf[DesignRule]], ruled_volumes: list[RuledVolume], bounding_box: RuledVolume | None = None, voxel_size: float = 0.1, exact_distances: bool = False, weights_operator: str = 'min', voxel_inside: bool = False, build_cad: bool = True, multi_scale: bool = False, size_factor: int = 3, name: str = '') MultiCadMap[source]#

Create MultiCadMap from project inputs.

get_bifurcation_points(packs: list[Pack], tolerance: float | None = None, with_ports: bool = False) list[ndarray][source]#

Get all bifurcation points in all cadmaps.

get_primitives() list[Primitive3D][source]#

Get all 3D primitives from CadMap including packs and solutions.

Collects primitives from all solutions and the CadMap’s own primitives (ruled volumes and voxelization) for complete visualization.

Returns:

List of all Primitive3D objects from solutions and CadMap.

property global_origin: tuple[float, float, float]#

Get the global origin covering all voxelizations.

Computed as a voxel center aligned with the global_voxel_size that contains all min_grid_centers from all CadMaps.

property global_shape: tuple[int, int, int]#

Get the global shape covering all voxelizations.

Computed as the shape that would cover ALL voxelizations of all CadMaps (regardless of their voxel size) using the global_voxel_size.

property global_voxel_size: float#

Get the global voxel size.

For mono-scale MultiCadMap, returns the common voxel size. For multi-scale MultiCadMap, returns the largest voxel size (typically from the main/coarsest grid).

Returns:

Global voxel size value.

property is_multi_scale: bool#

Check if this MultiCadMap uses multiple voxel sizes.

Returns True if CadMaps have different voxel sizes (multi-scale routing), False if all have the same voxel size (mono-scale routing).

Returns:

True if multiple voxel sizes are used, False otherwise.

load_ports_points(specifications: list[Specification]) None[source]#

Update port positions stored in main CadMap.

property main_cadmap: CadMap#

Get the primary CadMap (first in the list).

In multi-scale scenarios, the main CadMap typically has the coarsest voxelization and serves as the primary routing grid.

Returns:

The first CadMap in the list.

property nbytes: int#

Calculate the total memory usage in bytes of all CadMaps.

Sums the memory footprint of all CadMap instances in the MultiCadMap.

Returns:

Total memory usage in bytes.

property occupancy_ratio: float#

Calculate the global ratio of occupied voxels across all CadMaps.

Computes the overall fraction of active voxels across all CadMaps, weighted by the total number of voxels.

Returns:

Global occupancy ratio between 0.0 and 1.0.

property packs: list[Pack]#

Get all packs from all CadMaps.

Aggregates packs from all CadMap instances into a single list.

Returns:

List of all Pack objects from all CadMaps.

property port_points: list[ndarray]#

Get positions stored in main CadMap.

property room_voxels: RoomVoxelization#

Get room voxelization from the main CadMap.

Returns:

RoomVoxelization from the first CadMap.

property ruled_volumes: list[RuledVolume]#

Get ruled volumes from the main CadMap.

Returns:

List of RuledVolume objects from the main CadMap.

property shaped_weighting_rules: list[ShapedWeightingRule]#

Get all shaped weighting rules of Cadmap.

show_with_points(points: list[ndarray]) None[source]#

Visualize CadMap with bifurcation points in a 3D viewer.

to_grid() SmartWorld[source]#

Convert to grid representation (alias for to_world).

to_matrix_based_voxelization(voxel_size: float) MatrixBasedVoxelization[source]#

Build a new MatrixBasedVoxelization from CadMap with a new voxel_size.

to_world(auto_connect: bool = True) SmartWorld[source]#

Convert to SmartWorld with optionally interconnected grids.

Parameters:

auto_connect – If True, automatically connects adjacent grids by linking border nodes. If False, grids remain isolated and must be connected manually.

When auto_connect=False, you can manually connect grids using:

node_1 = world.grids[grid_id_1].node(x1, y1, z1) node_2 = world.grids[grid_id_2].node(x2, y2, z2) node_1.connect(node_2) node_2.connect(node_1)

update_grid(world: SmartWorld, overweighted_voxels: ndarray | None = None) None[source]#

Update CadMaps with information from SmartWorld grids.

Parameters:
  • world – SmartWorld instance containing grids

  • overweighted_voxels – Optional array with shape (n, 4) where last column is grid_id

update_packs(solution: Solution) None[source]#

Update packs by delegating to each CadMap.

update_weights_from_connectivity() None[source]#

Update weight tensors to zero out voxels not in the main connected component.

Extracts connected components from the connectivity graph and sets weights to 0 for voxels that are not part of the largest connected component.

update_weights_with_history(pipe_type: PipeType) None[source]#

Update routing weights based on historical pipe placements.

update_with_pipe_type(solution: Solution) None[source]#

Update all CadMaps with pipe type information.

volmdlr_primitives(**kwargs) list[Primitive3D][source]#

Get volmdlr primitives of MultiCadMap (volumes + voxelization).

voxel_meshes(show_connections: bool = False, apply_weights: bool = False) list[Mesh3D][source]#

Generate meshes from voxelizations with different colors by voxel size.

Parameters:
  • show_connections – If True, show connections between different scales

  • apply_weights – If True, filter voxels with zero weight from weight_tensor

Returns:

List of meshes

property voxel_sizes: set[float]#

Get all unique voxel sizes used across CadMaps.

Returns:

Set of unique voxel size values from all CadMaps.

property weights_operator: str#

Get weights operator from the main CadMap.

Returns:

Weights composition operator string from the main CadMap.

class routing.core.cadmap.Pack(pipe_lines: list[PipeLine], vector: ndarray, crossed_voxels: dict[tuple, set], parallel: bool, name: str = '')[source]#

Bases: Object3D

A class representing a collection of pipelines grouped by proximity rules and pooling specifications.

Groups multiple PipeLine objects that are aligned along a common direction and located within close proximity. Packs are used for efficient collision detection, pooling optimization, and managing pipe clusters in voxelized space.

Parameters:
  • pipe_lines – The list of PipeLine objects to include in this pack.

  • vector – The unit direction vector (shape: (3,)) representing the common alignment direction of pipes in the pack.

  • crossed_voxels – The dictionary mapping tuple(radii) to sets of voxel indices. Keys are tuples of pipe radii, values are sets of (i, j, k) voxel indices crossed by pipes with those radii.

  • parallel – Flag indicating whether the pack contains parallel pipes. Parallel packs have additional properties like normals and plane_vectors.

  • name – The name to identify this pack. Defaults to ‘’.

MIN_DISTANCE_IN_VOXEL = 1.5#
MIN_LENGTH_IN_VOXEL = 2#
add_pipe_line(pipe_line: PipeLine, solution: Solution) None[source]#

Add a single PipeLine to the current pack.

Updates crossed voxels, recalculates the pack’s direction vector, and updates parallel properties if applicable.

Parameters:
  • pipe_line – The PipeLine to add.

  • solution – The Solution corresponding to the pipe line.

Returns:

None

add_pipe_lines(pipe_lines: list[PipeLine], solutions: list[Solution]) None[source]#

Add a list of PipeLine objects to the current pack.

Parameters:
  • pipe_lines – List of PipeLine objects to add.

  • solutions – List of Solution objects corresponding to the pipe lines.

Returns:

None

static all_points_from_lines(pipe_lines: list[PipeLine]) ndarray[source]#

Get all points of pack from its lines.

property all_types: set[str]#

Get all pipe types in the current pack.

Returns:

Set of pipe type identifiers (strings) present in this pack.

property average_ends: ndarray#

Get average ends of Pack.

bounding_box(offset: float = 0.0) ndarray[source]#

Get the axis-aligned bounding box of the pack.

Computes the bounding box that encompasses all pipe lines in the pack, including pipe radius and an optional offset.

Parameters:

offset – Additional offset to add to the bounding box. Defaults to 0.0.

Returns:

Array of shape (2, 3) containing [[min_x, min_y, min_z], [max_x, max_y, max_z]].

catch_pipe_lines(pipe_lines: list[PipeLine], solution: Solution, pooling_rule: PoolingRule, room_voxels: RoomVoxelization) list[int][source]#

Catch pipe lines that can be added to the current pack.

Checks each pipe line in the list to see if it can be clustered with the pack based on parallelism and proximity criteria. Adds compatible pipe lines to the pack and returns their indices.

Parameters:
  • pipe_lines – List of PipeLine objects to check.

  • solution – Solution object associated with the pipe lines.

  • pooling_rule – PoolingRule defining clustering criteria.

  • room_voxels – RoomVoxelization for voxel operations.

Returns:

List of indices of pipe lines that were successfully added to the pack.

property center: ndarray#

Get center of Pack, computed with fixed lines when there are some.

property center_fixed: ndarray#

Get center of Pack, computed with fixed lines when there are some.

clean() None[source]#

Remove duplicated lines and update vector, preserving solution indexing.

clean_average_ends() None[source]#

Reset average_ends since they are a cached_property.

contains_pipe_line(pipe_line: PipeLine, pooling_rule: PoolingRule, offset: float, min_size: float) bool[source]#

Check if the current pack can cluster with a pipe line.

Determines if a pipe line can be added to this pack based on: - Parallelism: pipe line direction must be aligned with pack direction - Proximity: pipe line must be close enough to at least one pack line - Size: both lines must meet minimum size requirements

Parameters:
  • pipe_line – The PipeLine to check for clustering compatibility.

  • pooling_rule – PoolingRule defining clustering distances and coefficients.

  • offset – Offset distance for proximity checking.

  • min_size – Minimum size requirement for both pipe lines.

Returns:

True if pipe line can be clustered with this pack, False otherwise.

contains_point(point: ndarray) bool[source]#

Check if a point is inside the bounding box of the Pack.

Parameters:

point – A 3D point as np.ndarray of shape (3,)

Returns:

True if the point is inside the bounding box, False otherwise

coord_from_parametric_value(parametric_value: float) ndarray[source]#

Convert parametric value on Pack into 3D coordinate.

property frame: ndarray#

Get a Pack’s frame from vector and center.

classmethod from_pipe_line(pipe_line: PipeLine, solution: Solution, parallel: bool, room_voxels: RoomVoxelization, support_distances: list[ndarray]) Pack[source]#

Build a pack from a single PipeLine.

Creates a new Pack containing only one pipe line. This is the basic building block for pack creation. The pack’s direction vector is set to the pipe line’s direction, and crossed voxels are initialized from the pipe line’s crossed voxels.

If the pack is marked as parallel, parallel properties (normals, plane_vectors, stairs) are initialized using support distances. This enables the pack to manage parallel pipe clustering and stacking.

Parameters:
  • pipe_line – The PipeLine to build a new Pack from. Must have crossed_voxels already computed via update_crossed_voxels().

  • solution – The Solution containing the pipe_line. Stored in the pack’s solutions list for later reference.

  • parallel – Flag indicating whether the Pack contains parallel pipes. If True, parallel properties are initialized.

  • room_voxels – The CadMap’s room_voxels for voxelization operations. Used to compute voxel sizes and validate voxel indices.

  • support_distances – List of distance arrays from support volumes for parallel Packs. Required when parallel=True to compute normal vectors and plane vectors.

Returns:

A new Pack instance containing the single pipe line with all properties initialized.

classmethod from_pipe_lines(pipe_lines: list[PipeLine], solution: Solution, parallel: bool, pooling_rule: PoolingRule, room_voxels: RoomVoxelization, support_distances: list[ndarray]) list[Pack][source]#

Build multiple packs from a list of PipeLine objects.

Groups pipe lines into packs based on proximity and pooling rules. The algorithm: 1. Updates crossed voxels for each pipe line 2. Creates a new pack for the first line with crossed voxels 3. For subsequent lines, tries to add them to the current pack using catch_pipe_lines 4. If a line cannot be added to the current pack, finalizes the current pack

and starts a new one

  1. Returns all created packs

This method efficiently groups compatible pipe lines together, reducing the number of packs and enabling better pooling optimization.

Parameters:
  • pipe_lines – List of PipeLine objects to group into packs. Lines should have their crossed_voxels updated before calling this method.

  • solution – The current Solution containing these pipe lines. Stored in each pack’s solutions list.

  • parallel – Flag indicating whether the packs contain parallel pipes. Affects how parallel properties are initialized.

  • pooling_rule – The CadMap’s pooling_rule for grouping pipes. Used to determine if lines can be clustered together based on distances and coefficients between pipe types.

  • room_voxels – The CadMap’s room_voxels for voxelization operations. Used to update crossed voxels and validate voxel indices.

  • support_distances – List of distance arrays from support volumes for parallel Packs. Required when parallel=True.

Returns:

List of Pack instances created from the pipe lines. Each pack contains one or more compatible pipe lines.

get_bifurcation_points() list[ndarray][source]#

Get all bifurcation points of the pack.

get_fixed_lines() list[PipeLine][source]#

Get all fixed lines in pack, i.e. all lines that are on a Port.

get_parametric_value(point: ndarray) float[source]#

Get parametric coordinate on Pack for point.

initialize_parallel_properties(distances: list[ndarray], voxel_size: float) None[source]#

Initialize parallel properties of Pack when it is just created and parallel.

Computes normal vectors to support surfaces, plane vectors perpendicular to the pack direction, and initializes the first stair (layer) of parallel pipes.

Parameters:
  • distances – List of distance arrays from support volumes.

  • voxel_size – Size of each voxel in length units.

Returns:

None

property is_pack: bool#

Check if a Pack fits with Pack’s concept (WIP).

property length: float#

Get total length of Pack from start to end.

static lines_center(lines: list[PipeLine]) ndarray[source]#

Get average point from PipeLines’ ends.

merge_with_other(other: Pack) bool[source]#

Merge this pack with another pack if they meet compatibility criteria.

Two packs can be merged if: 1. Their direction vectors are sufficiently parallel (dot product > threshold) 2. They have the same parallel flag (both parallel or both non-parallel) 3. They share at least one common pipe line (same object reference)

When merged, all pipe lines and solutions from the other pack are added to this pack, and the pack’s direction vector is recalculated.

Parameters:

other – The Pack to attempt merging with.

Returns:

True if packs were successfully merged, False otherwise.

points_matrix(offset: float = 0.0) ndarray[source]#

Get bounding box matrix of all points with radius and offset.

Computes the minimum and maximum points across all pipe lines in the pack, expanded by pipe radius and an optional offset.

Parameters:

offset – Additional offset to add to the bounding box. Defaults to 0.0.

Returns:

Array of shape (2, 3) containing [min_point, max_point] for all pipe lines.

property radius: float#

Compute radius of current pack with pack_circles method.

show(**kwargs) None[source]#

Visualize the pack in a 3D viewer.

Displays all pipe lines and the pack’s bounding box using BabylonJS viewer.

Parameters:

kwargs – Optional keyword arguments passed to to_volume_model.

Returns:

None

to_volume_model(**kwargs) VolumeModel[source]#

Create a VolumeModel containing all pipe lines and the pack’s bounding box.

Wraps all 3D primitives (cylinders for pipe lines and box for bounding box) into a VolumeModel object for visualization or geometric operations.

Parameters:

kwargs – Optional keyword arguments passed to volmdlr_primitives, such as ‘color’ for custom visualization colors.

Returns:

VolumeModel instance containing all pack primitives.

update_coefficients(coefficients: ndarray, pipe_type: PipeType, pooling_rule: PoolingRule, room_voxels: RoomVoxelization) ndarray[source]#

Update coefficients that will be applied to voxels in Pack’s halo (action field).

update_forbidden_voxels(forbidden_voxels: ndarray, pipe_type: PipeType, voxel_size: float, pooling_rule: PoolingRule, radii_in_voxel: dict[tuple[float, ...], float]) ndarray[source]#

Update forbidden voxels in Pack’s halo (action field).

Marks voxels as forbidden (non-traversable) in the pack’s influence zone when pipes cannot physically fit together in a single voxel. Uses circle packing algorithms to determine if multiple pipes can coexist.

Parameters:
  • forbidden_voxels – 3D boolean array marking forbidden voxels (True = forbidden).

  • pipe_type – PipeType of the pipe being routed.

  • voxel_size – Size of each voxel in length units.

  • pooling_rule – PoolingRule defining minimum distances between pipe types.

  • radii_in_voxel – Dictionary caching whether radius combinations fit in a voxel.

Returns:

Updated forbidden_voxels array with pack’s influence zone marked.

update_parallel_properties(pipe_line: PipeLine) None[source]#

Update parallel properties of Pack with a new PipeLine when it is parallel.

Adds the new pipe line to an existing stair (layer) if it aligns with the same normal vector, or creates a new stair if no matching layer exists.

Parameters:

pipe_line – The PipeLine being added to update parallel properties.

Returns:

None

volmdlr_primitives(**kwargs) list[Cylinder][source]#

Get 3D shapes of all lines and the pack’s bounding box.

Creates Cylinder primitives for each pipe line and a Box primitive representing the pack’s bounding box.

Parameters:

kwargs – Optional keyword arguments, including ‘color’ for visualization.

Returns:

List of Cylinder primitives for pipe lines plus a Box primitive for the bounding box.

routing.core.cadmap.bounding_volume_from_box(bounding_box: BoundingBox) RuledVolume[source]#

Get a RuledVolume from a BoundingBox.

routing.core.cadmap.get_faces_in_bounding_box(bounding_volume: RuledVolume, volumes: list[RuledVolume]) list[dict[Any, list]][source]#

Get all faces in a bounding volume (Block).

Not the best methodology, kept for possible utility.