inire/inire/model.py
Jan Petykiewicz eac083a37d Refine routing geometry checks and streamline documentation
Report coincident terminals and unusable seeds per net, update custom bend handling and verification, and cover the revised behavior with regression tests.

Shorten the user and developer guides around reader tasks and keep the illustrated routing walkthrough and reference links easy to find.
2026-11-29 23:12:28 -08:00

389 lines
18 KiB
Python

from __future__ import annotations
import warnings
from dataclasses import dataclass, field
from math import isclose, isfinite
from numbers import Integral
from typing import TYPE_CHECKING, Literal
from shapely.geometry import Polygon
from inire._snapshot import snapshot
from inire.geometry.components import _has_port_face
from inire.geometry.index_helpers import floating_polygon
from inire.geometry.primitives import Port
from inire.geometry.sbend import sbend_grid_span
from inire.seeds import Bend90Seed, PathSeed, SBendSeed
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator, Mapping
from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry
from inire.results import RoutingResult
NetOrder = Literal["user", "shortest", "longest"]
VisibilityGuidance = Literal["off", "exact_corner", "tangent_corner"]
def _require_budget(name: str, value: int, *, minimum: int = 0) -> None:
if isinstance(value, bool) or not isinstance(value, Integral) or value < minimum:
description = "positive" if minimum else "nonnegative"
raise ValueError(f"{name} must be a {description} integer")
def _require_nonnegative(name: str, value: float) -> None:
if not isfinite(value) or value < 0:
raise ValueError(f"{name} must be finite and nonnegative")
def _outline_width_matches(left: float, right: float) -> bool:
return isclose(left, right, rel_tol=1e-12)
@dataclass(frozen=True, slots=True)
class NetSpec:
net_id: str
start: Port
target: Port
width: float = 2.0
def __post_init__(self) -> None:
if not isinstance(self.net_id, str):
raise TypeError(f"Net ID must be a string, got {self.net_id!r}")
if not isfinite(self.width) or self.width <= 0:
raise ValueError(f"Net {self.net_id!r} width must be finite and positive")
@dataclass(frozen=True, slots=True)
class ObjectiveWeights:
unit_length_cost: float = 1.0
bend_penalty: float = 250.0
sbend_penalty: float = 500.0
danger_weight: float = 1.0
def __post_init__(self) -> None:
for name in ("unit_length_cost", "bend_penalty", "sbend_penalty", "danger_weight"):
_require_nonnegative(name, getattr(self, name))
@dataclass(frozen=True, slots=True)
class SBendOutline:
"""Complete S-bend polygon in the frame of an east-facing input port at the origin."""
offset: float
radius: float
width: float
polygon: Polygon
length: float | None = None
def __post_init__(self) -> None:
seed = SBendSeed(self.offset, self.radius)
if not isfinite(self.width) or self.width <= 0:
raise ValueError("S-bend outline width must be finite and positive")
if self.length is not None and (not isfinite(self.length) or self.length <= 0):
raise ValueError("S-bend outline length must be finite and positive")
if not isinstance(self.polygon, Polygon) or self.polygon.is_empty or not self.polygon.is_valid:
raise ValueError("S-bend outline must be a valid, nonempty Polygon")
end = Port(sbend_grid_span(seed.offset, seed.radius), seed.offset, 0)
if not _has_port_face(self.polygon, Port(0, 0, 0), arrival=False, width=self.width) or not _has_port_face(
self.polygon, end, arrival=True, width=self.width,
):
warnings.warn(
f"S-bend outline does not match the declared east-facing port faces of width {self.width} at (0, 0) and ({end.x}, {end.y})",
stacklevel=3,
)
object.__setattr__(self, "offset", seed.offset)
object.__setattr__(self, "radius", seed.radius)
class _SearchOptionsCache:
# Keep derived state outside the dataclass fields used for serialization.
__slots__ = ("_active_sbend_outlines",)
_active_sbend_outlines: tuple[SBendOutline, ...]
@dataclass(frozen=True, slots=True)
class SearchOptions(_SearchOptionsCache):
node_limit: int = 1000000
max_straight_length: float = 2000.0
min_straight_length: float = 5.0
greedy_h_weight: float = 1.5
sbend_offsets: tuple[float, ...] | None = None
bend_radii: tuple[float, ...] = (50.0, 100.0)
sbend_radii: tuple[float, ...] = (10.0,)
bend_collision_type: BendCollisionModel = "arc"
bend_proxy_geometry: BendCollisionModel | None = None
bend_physical_geometry: BendPhysicalGeometry | None = None
bend_clip_margin: float | None = None
visibility_guidance: VisibilityGuidance = "tangent_corner"
sbend_outlines: tuple[SBendOutline, ...] = ()
proximity_range: float = 10.0
bend_physical_length: float | None = None
distance_heuristic_weight: float = 1.0
def __post_init__(self) -> None:
_require_budget("node_limit", self.node_limit)
_require_nonnegative("greedy_h_weight", self.greedy_h_weight)
_require_nonnegative("distance_heuristic_weight", self.distance_heuristic_weight)
if not isfinite(self.proximity_range) or self.proximity_range <= 0:
raise ValueError("proximity_range must be finite and positive")
if self.bend_physical_length is not None:
_, physical = resolve_bend_geometry(self)
if physical == "arc" or not isfinite(self.bend_physical_length) or self.bend_physical_length <= 0:
raise ValueError("bend_physical_length needs custom physical geometry and a finite positive length")
if self.visibility_guidance not in ("off", "exact_corner", "tangent_corner"):
raise ValueError(f"Unknown visibility_guidance: {self.visibility_guidance!r}")
for field_name in ("bend_radii", "sbend_radii"):
radii = tuple(getattr(self, field_name))
if any(not isfinite(radius) or radius <= 0 for radius in radii):
raise ValueError(f"{field_name} must contain only finite positive radii")
object.__setattr__(self, field_name, radii)
if not isfinite(self.min_straight_length) or self.min_straight_length < 0:
raise ValueError("min_straight_length must be finite and nonnegative")
if not isfinite(self.max_straight_length) or self.max_straight_length <= 0:
raise ValueError("max_straight_length must be finite and positive")
if self.sbend_offsets is not None:
offsets = tuple(self.sbend_offsets)
if any(not isfinite(offset) for offset in offsets):
raise ValueError("S-bend offsets must be finite")
object.__setattr__(self, "sbend_offsets", tuple(round(offset) for offset in offsets))
outlines = tuple(self.sbend_outlines)
outline_widths: dict[tuple[float, float], list[float]] = {}
for outline in outlines:
if not isinstance(outline, SBendOutline):
raise TypeError("sbend_outlines must contain SBendOutline entries")
key = outline.offset, outline.radius
widths = outline_widths.setdefault(key, [])
if any(_outline_width_matches(width, outline.width) for width in widths):
raise ValueError(f"Duplicate S-bend outline for offset {outline.offset}, radius {outline.radius}, width {outline.width}")
widths.append(outline.width)
object.__setattr__(self, "sbend_outlines", outlines)
for geometry in (self.bend_collision_type, self.bend_proxy_geometry, self.bend_physical_geometry):
if isinstance(geometry, Polygon) and (geometry.is_empty or not geometry.is_valid):
raise ValueError("Custom bend geometry must be a valid, nonempty polygon")
if self.bend_physical_geometry is None and isinstance(self.bend_proxy_geometry, Polygon):
warnings.warn(
"Custom bend proxy provided without bend_physical_geometry; routed bends will keep standard arc geometry.",
stacklevel=2,
)
def allows_sbend_offset(self, offset: float) -> bool:
return self.sbend_offsets is None or offset in self.sbend_offsets
@property
def active_sbend_outlines(self) -> tuple[SBendOutline, ...]:
try:
return self._active_sbend_outlines
except AttributeError:
active = tuple(
outline for outline in self.sbend_outlines
if outline.radius in self.sbend_radii and self.allows_sbend_offset(outline.offset)
)
object.__setattr__(self, "_active_sbend_outlines", active)
return active
def sbend_outlines_for_width(self, width: float) -> Iterator[SBendOutline]:
return (outline for outline in self.active_sbend_outlines if _outline_width_matches(outline.width, width))
def has_applicable_sbend_outline(self, widths: Iterable[float]) -> bool:
return bool(self.active_sbend_outlines) and any(next(self.sbend_outlines_for_width(width), None) is not None for width in widths)
def sbend_template(self, offset: float, radius: float, width: float) -> SBendOutline | None:
matches = [outline for outline in self.sbend_outlines_for_width(width) if (outline.offset, outline.radius) == (offset, radius)]
if len(matches) > 1:
raise ValueError(f"Ambiguous S-bend outlines for offset {offset}, radius {radius}, width {width}")
return matches[0] if matches else None
def sbend_outline(self, offset: float, radius: float, width: float) -> Polygon | None:
template = self.sbend_template(offset, radius, width)
return template.polygon if template is not None else None
def seed_geometry_error(self, seed: PathSeed) -> str | None:
for segment in seed.segments:
if isinstance(segment, Bend90Seed) and segment.radius not in self.bend_radii:
return f"uses radius {segment.radius:g} outside bend_radii"
if isinstance(segment, SBendSeed):
if segment.radius not in self.sbend_radii:
return f"uses radius {segment.radius:g} outside sbend_radii"
if not self.allows_sbend_offset(segment.offset):
return "uses an S-bend offset outside sbend_offsets"
return None
def resolve_bend_geometry(
search: SearchOptions,
*,
bend_collision_override: BendCollisionModel | None = None,
) -> tuple[BendCollisionModel, BendPhysicalGeometry]:
bend_physical_geometry = search.bend_physical_geometry
if bend_physical_geometry is None and isinstance(search.bend_collision_type, Polygon) and search.bend_proxy_geometry is None:
bend_physical_geometry = search.bend_collision_type
if bend_physical_geometry is None:
bend_physical_geometry = "arc"
if bend_collision_override is not None:
bend_proxy_geometry = bend_collision_override
elif search.bend_proxy_geometry is not None:
bend_proxy_geometry = search.bend_proxy_geometry
elif isinstance(search.bend_collision_type, Polygon):
bend_proxy_geometry = search.bend_collision_type
elif bend_physical_geometry != "arc" and search.bend_collision_type == "arc":
bend_proxy_geometry = bend_physical_geometry
else:
bend_proxy_geometry = search.bend_collision_type
return bend_proxy_geometry, bend_physical_geometry
@dataclass(frozen=True, slots=True)
class CongestionOptions:
max_iterations: int = 10
base_penalty: float = 100.0
multiplier: float = 1.5
use_tiered_strategy: bool = True
net_order: NetOrder = "user"
warm_start_enabled: bool = True
shuffle_nets: bool = False
seed: int | None = None
def __post_init__(self) -> None:
_require_budget("max_iterations", self.max_iterations)
_require_nonnegative("base_penalty", self.base_penalty)
_require_nonnegative("multiplier", self.multiplier)
if self.net_order not in ("user", "shortest", "longest"):
raise ValueError(f"Unknown net_order: {self.net_order!r}")
@dataclass(frozen=True, slots=True)
class RefinementOptions:
enabled: bool = True
objective: ObjectiveWeights | None = None
max_windows_per_net: int | None = 4
def __post_init__(self) -> None:
limit = self.max_windows_per_net
if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or limit < 1):
raise ValueError("max_windows_per_net must be a positive integer or None")
@dataclass(frozen=True, slots=True)
class DiagnosticsOptions:
capture_expanded: bool = False
capture_conflict_trace: bool = False
capture_frontier_trace: bool = False
capture_iteration_trace: bool = False
capture_pre_pair_frontier_trace: bool = False
@dataclass(frozen=True, slots=True)
class TopologyOptions:
mode: Literal["off", "guide", "seed", "bundle", "automatic"] = "automatic"
max_corridors: int = 3
guide_strength: float = 0.75
seed_node_limit: int = 600
infer_terminal_headings: bool = False
automatic_cost: Literal["selective", "always", "never"] = "selective"
automatic_length_weights: tuple[float, float, float] | None = None
def __post_init__(self) -> None:
if self.mode not in ("off", "guide", "seed", "bundle", "automatic"):
raise ValueError(f"Unknown topology mode: {self.mode!r}")
_require_budget("max_corridors", self.max_corridors, minimum=1)
if not isfinite(self.guide_strength) or self.guide_strength < 0:
raise ValueError("guide_strength must be finite and nonnegative")
_require_budget("seed_node_limit", self.seed_node_limit, minimum=1)
if self.automatic_cost not in ("selective", "always", "never"):
raise ValueError(f"Unknown automatic cost policy: {self.automatic_cost!r}")
if self.automatic_length_weights is not None:
weights = tuple(self.automatic_length_weights)
if len(weights) != 3 or any(not isfinite(weight) or weight < 0 for weight in weights):
raise ValueError("automatic_length_weights must contain three finite, nonnegative weights")
object.__setattr__(self, "automatic_length_weights", weights)
@dataclass(frozen=True, slots=True)
class RoutingOptions:
search: SearchOptions = field(default_factory=SearchOptions)
objective: ObjectiveWeights = field(default_factory=ObjectiveWeights)
congestion: CongestionOptions = field(default_factory=CongestionOptions)
refinement: RefinementOptions = field(default_factory=RefinementOptions)
diagnostics: DiagnosticsOptions = field(default_factory=DiagnosticsOptions)
topology: TopologyOptions = field(default_factory=TopologyOptions)
@dataclass(frozen=True, slots=True)
class FixedRoute:
"""Physical polygons belonging to a completed or imported net."""
net_id: str
polygons: tuple[Polygon, ...]
def __post_init__(self) -> None:
if not isinstance(self.net_id, str):
raise TypeError("Fixed route ID must be a string")
polygons = tuple(self.polygons)
if not polygons or any(not isinstance(shape, Polygon) or shape.is_empty or not shape.is_valid for shape in polygons):
raise ValueError("Fixed routes require nonempty, valid Polygon geometry")
object.__setattr__(self, "polygons", tuple(floating_polygon(polygon) for polygon in polygons))
@classmethod
def from_result(cls, result: RoutingResult) -> FixedRoute:
if not result.is_valid:
raise ValueError(f"Fixed route {result.net_id!r} must be completed and verified")
return cls(result.net_id, result.locked_geometry)
@dataclass(frozen=True, slots=True)
class RoutingProblem:
bounds: tuple[float, float, float, float]
nets: tuple[NetSpec, ...] = ()
static_obstacles: tuple[Polygon, ...] = ()
initial_paths: Mapping[str, PathSeed] = field(default_factory=dict)
clearance: float = 2.0
safety_zone_radius: float = 0.0021
self_clearance: float = 0.0
fixed_routes: tuple[FixedRoute, ...] = ()
@property
def _blocking_polygons(self) -> tuple[Polygon, ...]:
return self.static_obstacles + tuple(shape for route in self.fixed_routes for shape in route.polygons)
def __post_init__(self) -> None:
bounds = tuple(self.bounds)
if len(bounds) != 4 or not all(isfinite(value) for value in bounds) or not (bounds[0] < bounds[2] and bounds[1] < bounds[3]):
raise ValueError("Routing bounds must be finite with minimums below maximums")
if not isfinite(self.clearance) or self.clearance < 0:
raise ValueError("Routing clearance must be finite and nonnegative")
_require_nonnegative("self_clearance", self.self_clearance)
object.__setattr__(self, "bounds", bounds)
nets = tuple(self.nets)
seen: set[str] = set()
for net in nets:
if net.net_id in seen:
raise ValueError(f"Duplicate net ID: {net.net_id!r}")
seen.add(net.net_id)
object.__setattr__(self, "nets", nets)
fixed_routes = tuple(self.fixed_routes)
for fixed in fixed_routes:
if not isinstance(fixed, FixedRoute):
raise TypeError("fixed_routes must contain FixedRoute entries")
if fixed.net_id in seen:
raise ValueError(f"Duplicate active or fixed net ID: {fixed.net_id!r}")
seen.add(fixed.net_id)
object.__setattr__(self, "fixed_routes", fixed_routes)
obstacles = tuple(self.static_obstacles)
for index, obstacle in enumerate(obstacles):
if not isinstance(obstacle, Polygon):
raise TypeError(f"static_obstacles[{index}] must be a Shapely Polygon")
if obstacle.is_empty or not obstacle.is_valid:
raise ValueError(f"static_obstacles[{index}] must be nonempty and valid")
object.__setattr__(self, "static_obstacles", tuple(floating_polygon(obstacle) for obstacle in obstacles))
initial_paths = snapshot(self.initial_paths)
if any(not isinstance(seed, PathSeed) for seed in initial_paths.values()):
raise TypeError("RoutingProblem.initial_paths values must be PathSeed instances")
object.__setattr__(
self,
"initial_paths",
initial_paths,
)