From def1e4ea1df3fdb4a80c327dd14401dff9950a50 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Fri, 27 Nov 2026 15:21:37 -0800 Subject: [PATCH] Verify route continuity and simplify automatic search setup --- docs/architecture.md | 2 +- docs/routing-diagnostics.md | 2 +- docs/user/api-reference.md | 20 +-- docs/user/tune-and-troubleshoot.md | 2 +- inire/geometry/collision.py | 8 +- inire/geometry/components.py | 125 ++++++++++++--- inire/geometry/sbend.py | 15 +- inire/model.py | 28 +++- inire/results.py | 7 +- inire/router/_astar_moves.py | 24 ++- inire/router/_automatic.py | 6 +- inire/router/_bundle.py | 20 +-- inire/router/_columns.py | 15 +- inire/router/_compact.py | 6 +- inire/router/_perimeter.py | 2 +- inire/router/_route_traces.py | 17 ++- inire/router/_router.py | 20 ++- inire/router/_seed_materialization.py | 7 +- inire/router/_stack.py | 4 +- inire/router/_waypoints.py | 4 +- inire/router/refiner.py | 4 +- inire/seeds.py | 22 ++- inire/tests/test_api.py | 203 ++++++++++++++++++++++++- inire/tests/test_collision.py | 19 ++- inire/tests/test_components.py | 2 +- inire/tests/test_routing_benchmarks.py | 8 +- 26 files changed, 489 insertions(+), 103 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 6ca17f4..c9cb9e2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -32,7 +32,7 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati ## Geometry and refinement -Search uses proxies to check moves and estimate congestion. Verification checks the physical polygons against keepouts, other nets, and the board rectangle in every routing mode. It uses the distance between physical polygons to check spacing between nets. Boundary contact with the board is allowed. +Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks that the physical geometry joins across a finite-width face at each port. It checks the polygons against keepouts, other nets, and the board rectangle in every routing mode. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed. At a keepout corner, a mitred clearance buffer can reach farther than the specified clearance. Verification checks the actual distance before counting these hits as collisions. For an example with a corner close to the required clearance, see the [mitred-corner test](../inire/tests/test_collision.py#L146). diff --git a/docs/routing-diagnostics.md b/docs/routing-diagnostics.md index 4777b59..6f716b8 100644 --- a/docs/routing-diagnostics.md +++ b/docs/routing-diagnostics.md @@ -40,7 +40,7 @@ Enable the `DiagnosticsOptions` flag for the question you want to answer. ### Find components in conflict -1. Enable `capture_conflict_trace` in `DiagnosticsOptions`. In `run.conflict_trace`, choose the entry with `stage="final"` to inspect the returned paths. +1. Enable `capture_conflict_trace` in `DiagnosticsOptions`. In `run.conflict_trace`, choose the entry with `stage="final"` to inspect the returned paths, including nets verified and locked before the selected search. 2. Find the two net IDs in `conflict_edges`. In the matching `nets` entry, read `component_conflicts` for `self_component_index`, `other_net_id`, and `other_component_index`. 3. Use those zero-based indices to look up components in each net's `path` in `run.results_by_net`. Plot their physical shapes and compare the distance between them with the [required clearance](architecture.md#geometry-and-refinement). diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index 188f759..f05f602 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -8,14 +8,14 @@ Import these types from `inire`. To see how the inputs fit together in a runnabl route(problem, *, options=None, iteration_callback=None) -> RoutingRunResult ``` -Omitting `options` uses `RoutingOptions()`. To observe progress, pass a callable accepting `(index, results_by_net)`. Each call reports one completed congestion iteration on the nets in that attempt. Automatic mode keeps increasing the index across attempts. Check the returned result for final coverage, including on runs that finish without a callback. +Omitting `options` uses `RoutingOptions()`. To observe progress, pass a callable accepting `(index, results_by_net)`. Each call receives a snapshot of the nets in one completed congestion iteration. Automatic mode keeps increasing the index across attempts and uses the same planner order with or without a callback. Check the returned result for final coverage, including on runs that finish without a callback. ## Layout inputs ### Ports and nets - `Port(x, y, r)` rounds coordinates to integers. The heading `r` is in degrees, with 0 east, 90 north, 180 west, and 270 south. The rounded angle must be a multiple of 90 and is wrapped to the range 0–359. -- `NetSpec(net_id, start, target, width=2.0)` uses a unique ID and two ports. Set the start heading to the direction of departure and the target heading to the direction of arrival. +- `NetSpec(net_id, start, target, width=2.0)` uses a unique ID, two ports, and a finite positive width. Set the start heading to the direction of departure and the target heading to the direction of arrival. ### RoutingProblem @@ -23,16 +23,16 @@ The fields below appear in constructor order. Use one layout unit for coordinate | Field | Default | Meaning | | --- | --- | --- | -| `bounds` | Required | Board rectangle as `(xmin, ymin, xmax, ymax)`. | +| `bounds` | Required | Finite board rectangle as `(xmin, ymin, xmax, ymax)`, with each minimum below its maximum. | | `nets` | `()` | Sequence of `NetSpec` objects with unique IDs. Duplicate IDs raise `ValueError`. | | `static_obstacles` | `()` | Shapely polygons that define keepouts. | | `initial_paths` | Empty mapping | Net IDs mapped to `PathSeed` objects. | -| `clearance` | `2.0` | Required spacing between physical shapes. | +| `clearance` | `2.0` | Finite, nonnegative spacing required between physical shapes. | | `safety_zone_radius` | `0.0021` | Tolerance for small obstacle intersections at a move's endpoints during search. | ## Path seeds -`PathSeed(segments)` holds an ordered tuple of `StraightSeed(length)`, `Bend90Seed(radius, direction)`, and `SBendSeed(offset, radius)` moves. Bend directions are `"CW"` and `"CCW"`. A seed is materialized from the net's current start port using its width and the run's geometry options. For a workflow that starts from an existing route, see [Reuse an existing route](route-a-layout.md#reuse-an-existing-route). +`PathSeed(segments)` holds an ordered tuple of `StraightSeed(length)`, `Bend90Seed(radius, direction)`, and `SBendSeed(offset, radius)` moves. Lengths and radii must be finite and positive. Bend directions are `"CW"` and `"CCW"`. S-bend offsets must be nonzero integers with magnitude less than twice the radius. A seed is materialized from the net's current start port using its width and the run's geometry options. Search skips seeds with a bend radius below half the net width. For a workflow that starts from an existing route, see [Reuse an existing route](route-a-layout.md#reuse-an-existing-route). ## Results @@ -42,7 +42,7 @@ The fields below appear in constructor order. Use one layout unit for coordinate | `RoutingResult.is_valid` and `outcome` | `is_valid` is true when the outcome is `completed`. Read `outcome` to distinguish success, a failed geometry check (`colliding`), a path that stopped short (`partial`), or an empty path (`unroutable`). | | `RoutingResult.path` | Ordered path components from the source to the last reached state. An unroutable result has an empty path. | | `RoutingResult.reached_target` | Whether the path reached the target position and heading. With heading inference, the check uses the chosen heading. Read `is_valid` for the result of geometry verification. | -| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` indicates that physical geometry extends outside the board rectangle. | +| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `discontinuous` flags missing or point-only joins, including at terminal faces. `invalid_geometry` flags invalid or empty physical polygons. | | `RoutingResult.locked_geometry` and `as_seed()` | Physical polygons and the sequence of moves, respectively. Check validity before exporting polygons or using them as keepouts. | | `RoutingRunResult.automatic` | In automatic mode, the selected planner, verified IDs, stage history, and any capacity or port-conflict bound. `None` for explicit modes. | | `RoutingRunResult.topology` and `metrics` | Corridor counts and seed work when reported by the selected worker, plus work counters across the run. | @@ -70,9 +70,9 @@ To read a route's polygons and write them to a test file, follow the [geometry e | `min_straight_length` | `5.0` | Minimum length for regular forward moves in lattice search. | | `max_straight_length` | `2000.0` | Maximum distance the forward scan uses to propose straight moves in lattice search. | | `greedy_h_weight` | `1.5` | Weight on the estimated cost still needed to reach the target. Lower values give more influence to the cost of the path so far. | -| `bend_radii` | `(50.0, 100.0)` | Permitted radii for 90-degree bends. | -| `sbend_radii` | `(10.0,)` | Permitted S-bend radii. | -| `sbend_offsets` | `None` | Set permitted lateral offsets explicitly, or let search suggest offsets. A compact S-bend needs a nonzero offset with magnitude less than twice its radius. | +| `bend_radii` | `(50.0, 100.0)` | Permitted radii for 90-degree bends. Each move needs a radius of at least half its net width. | +| `sbend_radii` | `(10.0,)` | Permitted S-bend radii, subject to the same width requirement. | +| `sbend_offsets` | `None` | `None` lets the router choose signed lateral offsets. An explicit list restricts routing and seeds to those offsets after rounding to the grid. An empty list disables S-bends. | | `bend_collision_type` | `"arc"` | Search proxy, one of `"arc"`, `"bbox"`, or `"clipped_bbox"`. The legacy polygon form defines both shapes unless split geometry is supplied. | | `bend_proxy_geometry` | `None` | Override the proxy. A custom polygon proxy by itself keeps the standard physical arc and emits a warning. | | `bend_physical_geometry` | `None` | Override the physical geometry with `"arc"` or a polygon. A custom physical polygon also supplies the default proxy when the collision type is `"arc"`. | @@ -96,7 +96,7 @@ Increase the iteration limit when later reroutes might resolve conflicts. Adjust | Field | Default | Effect | | --- | --- | --- | -| `max_iterations` | `10` | Maximum congestion iterations per attempt. Automatic's initial probe may use fewer. | +| `max_iterations` | `10` | Maximum congestion iterations per attempt. Automatic's initial probe may use fewer. Zero skips warm-start and corridor searches. | | `base_penalty` | `100.0` | Initial penalty for overlapping other routes. | | `multiplier` | `1.5` | Scale the penalty between unresolved iterations. | | `use_tiered_strategy` | `True` | Allow a cheaper bend proxy in the first iteration when applicable. | diff --git a/docs/user/tune-and-troubleshoot.md b/docs/user/tune-and-troubleshoot.md index a810dea..7918a5a 100644 --- a/docs/user/tune-and-troubleshoot.md +++ b/docs/user/tune-and-troubleshoot.md @@ -7,7 +7,7 @@ Start with `run.results_by_net[net_id].outcome`. It distinguishes a path that st | `result.outcome` | What to inspect | | --- | --- | | `completed` | The path reached its target and passed verification. Read its length in `report.total_length` and follow the [geometry export steps](route-a-layout.md#export-verified-geometry). | -| `colliding` | The path reached its target and failed verification. Check `result.report` for keepout clearance, conflicts with another route, self-overlap, or geometry outside the board. | +| `colliding` | The path reached its target and failed verification. Check `result.report` for keepout clearance, conflicts with another route, self-overlap, invalid geometry, a bad join, or geometry outside the board. | | `partial` | Read the position and heading of `result.path[-1].end_port`. Check room for the path to continue from that heading. If the next turn fits, compare search limits. | | `unroutable` | The path is empty. Check the launch heading and room for the first straight or bend. | diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index f65f0fe..e8ece67 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -7,7 +7,7 @@ import numpy from shapely.geometry import LineString, box from inire.geometry.component_overlap import components_overlap -from inire.geometry.components import path_within_board +from inire.geometry.components import check_path_geometry, path_within_board from inire.geometry.dynamic_path_index import DynamicPathIndex from inire.geometry.index_helpers import grid_cell_span from inire.results import RoutingReport @@ -165,6 +165,8 @@ class RoutingWorld: ) def install_path(self, net_id: str, path: Sequence[ComponentResult]) -> None: + if any(not component.physical_checks[0] for component in path): + return proxies: list[Polygon] = [] dilated_proxies: list[Polygon] = [] physical_geometry: list[tuple[int, Polygon]] = [] @@ -656,6 +658,9 @@ class RoutingWorld: dynamic_collision_count = 0 self_collision_count = 0 total_length = sum(component.length for component in components) + valid_geometry, continuous = check_path_geometry(components) + if not valid_geometry: + return PathVerificationDetail(RoutingReport(total_length=total_length, invalid_geometry=True)) conflicting_net_ids: set[str] = set() component_conflicts: set[tuple[int, str, int]] = set() @@ -722,6 +727,7 @@ class RoutingWorld: self_collision_count=self_collision_count, total_length=total_length, out_of_bounds=self.board is not None and not path_within_board(components, self.board), + discontinuous=not continuous, ), conflicting_net_ids=tuple(sorted(conflicting_net_ids)), component_conflicts=tuple(sorted(component_conflicts)), diff --git a/inire/geometry/components.py b/inire/geometry/components.py index 958af15..f49b6a5 100644 --- a/inire/geometry/components.py +++ b/inire/geometry/components.py @@ -1,6 +1,7 @@ from __future__ import annotations from dataclasses import dataclass, field +from itertools import pairwise from typing import TYPE_CHECKING, Literal import numpy @@ -9,7 +10,8 @@ from shapely.affinity import scale as shapely_scale from shapely.affinity import translate as shapely_translate from shapely.geometry import Polygon, box -from inire.constants import TOLERANCE_ANGULAR +from inire.constants import TOLERANCE_ANGULAR, TOLERANCE_LINEAR +from inire.geometry.sbend import sbend_grid_span, sbend_span from inire.seeds import Bend90Seed, PathSegmentSeed, SBendSeed, StraightSeed from .primitives import Port, rotation_matrix2 @@ -30,6 +32,34 @@ def path_within_board(path: Iterable[ComponentResult], board: Polygon) -> bool: return all(board.covers(shape) for component in path for shape in component.physical_geometry) +def _has_port_face(polygon: Polygon, port: Port) -> bool: + """Find boundary along the port plane on both sides of its center.""" + axis = 0 if port.r % 180 == 0 else 1 + position = (port.x, port.y) + coordinates = numpy.asarray(polygon.exterior.coords) + on_plane = numpy.abs(coordinates[:, axis] - position[axis]) <= TOLERANCE_LINEAR + lateral = coordinates[:, 1 - axis] - position[1 - axis] + lower = numpy.minimum(lateral[:-1], lateral[1:]) + upper = numpy.maximum(lateral[:-1], lateral[1:]) + at_port = on_plane[:-1] & on_plane[1:] & (lower <= TOLERANCE_LINEAR) & (upper >= -TOLERANCE_LINEAR) + return bool(numpy.any(at_port & (lower < 0)) and numpy.any(at_port & (upper > 0))) + + +def check_path_geometry(path: Sequence[ComponentResult]) -> tuple[bool, bool]: + """Return polygon validity and physical continuity for a path.""" + continuous = all(a.end_port == b.start_port for a, b in pairwise(path)) + for component in path: + valid, connected = component.physical_checks + if not valid: + return False, False + continuous = continuous and connected + return True, continuous + + +def bend_fits_width(radius: float, width: float) -> bool: + return radius >= width / 2 + + def _normalize_length(value: float) -> float: return float(value) @@ -58,6 +88,7 @@ class ComponentResult: _total_bounds: tuple[float, float, float, float] = field(init=False, repr=False) _dilated_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False) _total_dilated_bounds: tuple[float, float, float, float] = field(init=False, repr=False) + _physical_checks: tuple[bool, bool] | None = field(init=False, repr=False, compare=False, default=None) def __post_init__(self) -> None: collision_geometry = tuple(self.collision_geometry) @@ -95,6 +126,21 @@ class ComponentResult: def total_dilated_bounds(self) -> tuple[float, float, float, float]: return self._total_dilated_bounds + @property + def physical_checks(self) -> tuple[bool, bool]: + if self._physical_checks is None: + shapes = self.physical_geometry + valid = bool(shapes) and all(not shape.is_empty and shape.is_valid for shape in shapes) + connected = ( + valid + and _has_port_face(shapes[0], self.start_port) + and _has_port_face(shapes[-1], self.end_port) + and all(a.intersection(b).length > TOLERANCE_LINEAR for a, b in pairwise(shapes)) + ) + object.__setattr__(self, "_physical_checks", (valid, connected)) + return valid, connected + return self._physical_checks + def translate(self, dx: int | float, dy: int | float) -> ComponentResult: # The collision and physical views often reference the same polygons. translated: dict[int, Polygon] = {} @@ -318,6 +364,8 @@ class Bend90: clip_margin: float | None = None, dilation: float = 0.0, ) -> ComponentResult: + if not bend_fits_width(radius, width): + raise ValueError("Bend radius must be at least half the net width") rot2 = rotation_matrix2(start_port.r) sign = 1 if direction == "CCW" else -1 @@ -358,7 +406,7 @@ class Bend90: physical_geometry = arc_polys uses_physical_custom_geometry = False if dilation > 0: - if uses_physical_custom_geometry: + if uses_physical_custom_geometry or not bend_fits_width(radius, width + 2 * dilation): dilated_physical_geometry = [poly.buffer(dilation) for poly in physical_geometry] else: dilated_physical_geometry = _get_arc_polygons( @@ -390,6 +438,45 @@ class Bend90: class SBend: + @staticmethod + def _arcs( + start_port: Port, + rotation: NDArray[numpy.int32], + radius: float, + offset: float, + theta: float, + span: float, + grid_span: int, + width: float, + sagitta: float, + ) -> list[Polygon]: + # Reflect the first arc about the midpoint and reverse it to get the + # second arc. Reuse the midpoint and its normal for both polygons. + sign = 1 if offset > 0 else -1 + angles = numpy.linspace(0, theta, _get_num_segments(radius, float(numpy.degrees(theta)), sagitta) + 1) + sin, cos = numpy.sin(angles), numpy.cos(angles) + first = numpy.column_stack((radius * sin, sign * radius * (1 - cos))) + first[-1] = (span / 2, offset / 2) + normal = numpy.column_stack((-sign * sin, cos)) + second = numpy.asarray((span, offset)) - first[::-1] + second[0] = first[-1] + second_normal = normal[::-1] + # Keep the radius fixed and extend the final tangent to the grid. + # An integer-span bend needs no extension. + if grid_span - span > TOLERANCE_LINEAR: + second = numpy.vstack((second, (grid_span, offset))) + second_normal = numpy.vstack((second_normal, (0, 1))) + else: + second[-1] = (grid_span, offset) + + origin = numpy.asarray((start_port.x, start_port.y)) + polygons = [] + for centerline, normals in ((first, normal), (second, second_normal)): + edge = width / 2 * normals + points = numpy.concatenate((centerline + edge, (centerline - edge)[::-1])) + polygons.append(Polygon(points @ rotation.T + origin)) + return polygons + @staticmethod def generate( start_port: Port, @@ -402,18 +489,19 @@ class SBend: clip_margin: float | None = None, dilation: float = 0.0, ) -> ComponentResult: - if abs(offset) >= 2 * radius: - raise ValueError(f"SBend offset {offset} must be less than 2*radius {2 * radius}") + seed = SBendSeed(offset, radius) + offset, radius = seed.offset, seed.radius + if not bend_fits_width(radius, width): + raise ValueError("Bend radius must be at least half the net width") sign = 1 if offset >= 0 else -1 theta = numpy.arccos(1.0 - abs(offset) / (2.0 * radius)) - dx = 2.0 * radius * numpy.sin(theta) + dx = sbend_span(offset, radius) + grid_span = sbend_grid_span(offset, radius) theta_deg = float(numpy.degrees(theta)) rot2 = rotation_matrix2(start_port.r) - end_local = numpy.array((dx, offset)) - end_xy = (rot2 @ end_local) + numpy.array((start_port.x, start_port.y)) - end_port = Port(end_xy[0], end_xy[1], start_port.r) + end_port = _advance_port(start_port, rot2, grid_span, offset) c1_local = numpy.array((0.0, sign * radius)) c2_local = numpy.array((dx, offset - sign * radius)) @@ -424,9 +512,9 @@ class SBend: second_base = start_port.r + (90 if sign > 0 else 270) ts2 = (float(second_base + sign * theta_deg), float(second_base)) - arc1 = _get_arc_polygons((float(c1_xy[0]), float(c1_xy[1])), radius, width, ts1, sagitta)[0] - arc2 = _get_arc_polygons((float(c2_xy[0]), float(c2_xy[1])), radius, width, ts2, sagitta)[0] - actual_geometry = [arc1, arc2] + actual_geometry = SBend._arcs(start_port, rot2, radius, offset, theta, dx, grid_span, width, sagitta) + arc1, arc2 = actual_geometry + end_collision_type = "bbox" if collision_type == "clipped_bbox" and grid_span - dx > TOLERANCE_LINEAR else collision_type geometry = [ _apply_collision_model( arc1, @@ -441,7 +529,7 @@ class SBend: )[0], _apply_collision_model( arc2, - collision_type, + end_collision_type, radius, width, (float(c2_xy[0]), float(c2_xy[1])), @@ -480,13 +568,12 @@ class SBend: physical_geometry = actual_geometry uses_physical_custom_geometry = False if dilation > 0: - if uses_physical_custom_geometry: + if uses_physical_custom_geometry or not bend_fits_width(radius, width + 2 * dilation): dilated_physical_geometry = [poly.buffer(dilation) for poly in physical_geometry] else: - dilated_physical_geometry = [ - _get_arc_polygons((float(c1_xy[0]), float(c1_xy[1])), radius, width, ts1, sagitta, dilation=dilation)[0], - _get_arc_polygons((float(c2_xy[0]), float(c2_xy[1])), radius, width, ts2, sagitta, dilation=dilation)[0], - ] + dilated_physical_geometry = SBend._arcs( + start_port, rot2, radius, offset, theta, dx, grid_span, width + 2 * dilation, sagitta, + ) dilated_collision_geometry = ( dilated_physical_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in geometry] ) @@ -498,9 +585,9 @@ class SBend: start_port=start_port, collision_geometry=geometry, end_port=end_port, - length=2.0 * radius * theta, + length=2.0 * radius * theta + max(0.0, grid_span - dx), move_type="sbend", - move_spec=SBendSeed(offset=offset, radius=radius), + move_spec=seed, physical_geometry=physical_geometry, dilated_collision_geometry=dilated_collision_geometry, dilated_physical_geometry=dilated_physical_geometry, diff --git a/inire/geometry/sbend.py b/inire/geometry/sbend.py index 2239dbf..11448e3 100644 --- a/inire/geometry/sbend.py +++ b/inire/geometry/sbend.py @@ -1,6 +1,17 @@ -"""Exact S-bend dimensions for constructive planners.""" +"""S-bend dimensions on the routing grid.""" -from math import isqrt +from math import ceil, isqrt, sqrt + +from inire.constants import TOLERANCE_LINEAR + + +def sbend_span(offset: float, radius: float) -> float: + offset = abs(offset) + return sqrt(offset * (4 * radius - offset)) + + +def sbend_grid_span(offset: float, radius: float) -> int: + return ceil(sbend_span(offset, radius) - TOLERANCE_LINEAR) def exact_sbend_spans(radius: int) -> dict[int, int]: diff --git a/inire/model.py b/inire/model.py index ba703cf..c8cfe5d 100644 --- a/inire/model.py +++ b/inire/model.py @@ -6,7 +6,7 @@ from math import isfinite from typing import TYPE_CHECKING, Literal from shapely.geometry import Polygon -from inire.seeds import PathSeed +from inire.seeds import PathSeed, SBendSeed if TYPE_CHECKING: from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry @@ -24,6 +24,10 @@ class NetSpec: target: Port width: float = 2.0 + def __post_init__(self) -> None: + 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: @@ -52,13 +56,27 @@ class SearchOptions: object.__setattr__(self, "bend_radii", tuple(self.bend_radii)) object.__setattr__(self, "sbend_radii", tuple(self.sbend_radii)) if self.sbend_offsets is not None: - object.__setattr__(self, "sbend_offsets", tuple(self.sbend_offsets)) + 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)) + 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 + + def allows_seed(self, seed: PathSeed) -> bool: + return self.sbend_offsets is None or all( + not isinstance(segment, SBendSeed) or self.allows_sbend_offset(segment.offset) for segment in seed.segments + ) + def resolve_bend_geometry( search: SearchOptions, @@ -166,6 +184,12 @@ class RoutingProblem: safety_zone_radius: float = 0.0021 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") + object.__setattr__(self, "bounds", bounds) nets = tuple(self.nets) seen: set[str] = set() for net in nets: diff --git a/inire/results.py b/inire/results.py index 83e94f3..56233f3 100644 --- a/inire/results.py +++ b/inire/results.py @@ -25,10 +25,15 @@ class RoutingReport: self_collision_count: int = 0 total_length: float = 0.0 out_of_bounds: bool = False + discontinuous: bool = False + invalid_geometry: bool = False @property def collision_count(self) -> int: - return self.static_collision_count + self.dynamic_collision_count + self.self_collision_count + int(self.out_of_bounds) + return ( + self.static_collision_count + self.dynamic_collision_count + self.self_collision_count + + int(self.out_of_bounds) + int(self.discontinuous) + int(self.invalid_geometry) + ) @property def is_valid(self) -> bool: diff --git a/inire/router/_astar_moves.py b/inire/router/_astar_moves.py index e54bba6..3fdc631 100644 --- a/inire/router/_astar_moves.py +++ b/inire/router/_astar_moves.py @@ -4,6 +4,8 @@ import math from typing import TYPE_CHECKING from inire.constants import TOLERANCE_LINEAR +from inire.geometry.components import bend_fits_width +from inire.geometry.sbend import sbend_grid_span from ._astar_admission import process_move @@ -43,8 +45,7 @@ def _sbend_forward_span(offset: float, radius: float) -> float | None: abs_offset = abs(offset) if abs_offset <= TOLERANCE_LINEAR or radius <= 0 or abs_offset >= 2.0 * radius: return None - theta = math.acos(1.0 - abs_offset / (2.0 * radius)) - return 2.0 * radius * math.sin(theta) + return sbend_grid_span(offset, radius) def _visible_straight_candidates( @@ -247,7 +248,7 @@ def expand_moves( ) ) - if cp.r == target.r and dx_local > 0 and abs(dy_local) > TOLERANCE_LINEAR: + if cp.r == target.r and dx_local > 0 and abs(dy_local) > TOLERANCE_LINEAR and search_options.allows_sbend_offset(dy_local): for radius in search_options.sbend_radii: sbend_span = _sbend_forward_span(dy_local, radius) if sbend_span is None: @@ -294,6 +295,8 @@ def expand_moves( allow_backwards = config.restrict_to_corridor or dist_sq < 150 * 150 for radius in search_options.bend_radii: + if not bend_fits_width(radius, net_width): + continue for direction in ("CW", "CCW"): if not allow_backwards: turn = 90 if direction == "CCW" else -90 @@ -317,24 +320,19 @@ def expand_moves( ) max_sbend_r = max(search_options.sbend_radii) if search_options.sbend_radii else 0.0 - if max_sbend_r <= 0 or prev_move_type == "sbend": + if not bend_fits_width(max_sbend_r, net_width) or prev_move_type == "sbend": return explicit_offsets = search_options.sbend_offsets - offsets: set[int] = {int(round(v)) for v in explicit_offsets or []} - offsets.update(guide_offsets) - - if target.r == cp.r and 0 < dx_local <= 4 * max_sbend_r and 0 < abs(dy_local) < 2 * max_sbend_r: - offsets.add(int(round(dy_local))) - - if not offsets: - return + offsets = set(explicit_offsets) if explicit_offsets is not None else guide_offsets + if explicit_offsets is None and target.r == cp.r and 0 < dx_local <= 4 * max_sbend_r and 0 < abs(dy_local) < 2 * max_sbend_r: + offsets.add(round(dy_local)) for offset in sorted(offsets): if offset == 0: continue for radius in search_options.sbend_radii: - if abs(offset) >= 2 * radius: + if abs(offset) >= 2 * radius or not bend_fits_width(radius, net_width): continue process_move( current, diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 54afc23..d6f0627 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -27,6 +27,7 @@ from inire.router._perimeter import ( residual_dogleg_candidates, terminal_link_seed, ) +from inire.router._route_traces import complete_final_conflict_trace from inire.router._routing_policy import ( LockPlan, _best_trial, @@ -431,7 +432,6 @@ class _AutomaticRun: len(problem.nets) <= 2 or problem.initial_paths or options.search.node_limit <= _NEAR_PORT_NODE_LIMIT - or self.iteration_callback is not None or options.congestion.shuffle_nets ): return None @@ -484,7 +484,7 @@ class _AutomaticRun: if len(_best_trial(trials).valid_costs) >= target: return True - try_construction_early = self.iteration_callback is None and not options.congestion.shuffle_nets + try_construction_early = not options.congestion.shuffle_nets if try_construction_early and self._try_column_jogs(options, trials, target): return True probe_iterations = options.congestion.max_iterations @@ -637,7 +637,7 @@ class _AutomaticRun: timings=tuple(self.timings), duration_s=perf_counter() - started, ) - return replace(best.run, metrics=metrics, automatic=report) + return replace(complete_final_conflict_trace(best.run), metrics=metrics, automatic=report) def route_automatic( diff --git a/inire/router/_bundle.py b/inire/router/_bundle.py index 59a0b19..5a5781b 100644 --- a/inire/router/_bundle.py +++ b/inire/router/_bundle.py @@ -11,6 +11,7 @@ from typing import TYPE_CHECKING from shapely.geometry import box from inire.geometry.primitives import Port +from inire.geometry.components import bend_fits_width from inire.geometry.sbend import exact_sbend_spans from inire.model import resolve_bend_geometry from inire.router._waypoints import XY, compile_waypoints @@ -110,16 +111,13 @@ def ordered_bundle_terminal_headings(problem: RoutingProblem) -> RoutingProblem: return replace(problem, nets=nets) -def _exact_offsets(radius: int) -> tuple[int, ...]: - return tuple(exact_sbend_spans(radius)) - - def _assign_shifts( layout: _Layout, radius: int, margin: float, pitch: int, floor_lane: int, + search: SearchOptions, ) -> tuple[dict[str, list[_Shift]], int]: short, lower, upper = layout.short, layout.lower, layout.upper middle, *ascending, shelf = upper @@ -159,9 +157,11 @@ def _assign_shifts( # final shelf that can reach its destination with an exact lattice S-bend. first_top = ceil(last_upper[3] + margin + 0.1) top_lanes = [first_top + i * pitch for i in range(len(ascending))] - offsets = _exact_offsets(radius) + offsets = tuple(exact_sbend_spans(radius)) shelf_options = [ - int(shelf.target.y) + offset for offset in offsets if top_lanes[-1] + pitch <= shelf.target.y + offset <= shelf_launch - 2 * radius + int(shelf.target.y) + offset + for offset in offsets + if search.allows_sbend_offset(-offset) and top_lanes[-1] + pitch <= shelf.target.y + offset <= shelf_launch - 2 * radius ] if not shelf_options: raise ValueError("The north shelf has no exact S-bend to the outer eastbound target") @@ -176,7 +176,7 @@ def _assign_shifts( middle_rise = side_rise + (len(ascending) - 1) * stagger middle_floor = tower_lanes[-1] + pitch if tower_lanes else tower_floor if middle_y < middle_floor: - shift = next((d for d in offsets if middle_y + d >= middle_floor), None) + shift = next((d for d in offsets if search.allows_sbend_offset(d) and middle_y + d >= middle_floor), None) if shift is None: raise ValueError("The middle track cannot rise above the tower with a lattice S-bend") shifts[middle.net_id].append(_Shift(middle_rise, middle_y + shift, sbend=True)) @@ -222,8 +222,8 @@ def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer raise ValueError("Bundle routing needs a common integer radius for circular bends and S-bends") radius = int(bend) width = problem.nets[0].width - if not isfinite(width) or width <= 0: - raise ValueError("Bundle routing requires a positive waveguide width") + if not bend_fits_width(radius, width): + raise ValueError("Bundle bend radius must be at least half the net width") margin = width / 2 + problem.clearance pitch = ceil(width + problem.clearance) + 1 floor_lane = ceil(problem.bounds[1] + width / 2) @@ -232,7 +232,7 @@ def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer # destination and of the first barrier, so the bundle launches east. problem = _eastbound_launches(problem) layout = _identify_layout(problem, margin) - shifts, launch = _assign_shifts(layout, radius, margin, pitch, floor_lane) + shifts, launch = _assign_shifts(layout, radius, margin, pitch, floor_lane, search) seeds = {} updated_nets = [] diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 3999504..8f42a3c 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -414,14 +414,12 @@ def _column_sbend_schedules( problem: RoutingProblem, layout: _ColumnLayout, radius: int, + spans: dict[int, int], weights: Mapping[str, float], *, weighted: bool, sbend_penalty: float, ) -> Iterator[tuple[tuple[_BendSequence, ...], ...]]: - spans = exact_sbend_spans(radius) - if not spans: - return modulus = gcd(*spans) launch, arrival = layout.launch, layout.arrival residues = tuple(y % modulus for y in launch) @@ -476,12 +474,17 @@ def column_seed_candidates( bend = min(search.sbend_radii, default=0.0) if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend): return + radius = int(bend) + spans = {d: span for d, span in exact_sbend_spans(radius).items() if search.allows_sbend_offset(d) or search.allows_sbend_offset(-d)} + if not spans: + return layout = _column_layout(problem) if layout is None: return - radius = int(bend) - for moves in _column_sbend_schedules(problem, layout, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty): - yield _seeds(layout.tracks, layout.spans, moves, radius) + for moves in _column_sbend_schedules(problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty): + seeds = _seeds(layout.tracks, layout.spans, moves, radius) + if all(search.allows_seed(seed) for seed in seeds.values()): + yield seeds def _jog_pivots( diff --git a/inire/router/_compact.py b/inire/router/_compact.py index ba479bd..a36d09c 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -87,6 +87,8 @@ def _candidate_jogs( for before in _shift_positions(problem, start.y, direction, radius, span, available): for exit_x in turns: for lateral in (offset, -offset): + if not search.allows_sbend_offset(direction * lateral): + continue lead = exit_x + lateral - start.x - radius if lead < 0: continue @@ -139,7 +141,7 @@ def _verified_candidates( ) -> Iterator[tuple[PathSeed, BaseGeometry, tuple[ComponentResult, ...]]]: for seed in seeds: path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance) - if path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid: + if not path or path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid: continue footprint = union_all([polygon for component in path for polygon in component.physical_geometry]) if board.covers(footprint): @@ -174,7 +176,7 @@ def _shift_seeds(forward: int, offset: int, search: SearchOptions) -> Iterator[P if minimum <= forward <= maximum: yield _path(forward) return - if search.sbend_offsets is not None and offset not in {round(value) for value in search.sbend_offsets}: + if not search.allows_sbend_offset(offset): return for radius in search.sbend_radii: if not isfinite(radius) or not 0 < abs(offset) < 2 * radius: diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 40e6be1..d800e7d 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -128,7 +128,7 @@ def bundle_turnaround_candidates( path = materialize_path_seed( proposal.initial_paths[net.net_id], start=net.start, net_width=net.width, search=search, clearance=problem.clearance ) - return tuple((round(x), round(y)) for x, y in export_waypoints(path)) + return tuple((round(x), round(y)) for x, y in export_waypoints(path or ())) shelf_points, return_points = points_for(shelf), points_for(returning) horizontals = [i for i, (a, b) in enumerate(pairwise(shelf_points)) if a[1] == b[1]] diff --git a/inire/router/_route_traces.py b/inire/router/_route_traces.py index e8192ce..0abef8b 100644 --- a/inire/router/_route_traces.py +++ b/inire/router/_route_traces.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import replace from typing import TYPE_CHECKING from inire.results import ( @@ -17,7 +18,7 @@ if TYPE_CHECKING: from collections.abc import Mapping, Sequence from inire.geometry.collision import PathVerificationDetail - from inire.results import ConflictTraceStage + from inire.results import ConflictTraceStage, RoutingRunResult from inire.router._congestion_policy import IterationReview @@ -65,6 +66,20 @@ def conflict_trace_entry( ) +def complete_final_conflict_trace(run: RoutingRunResult) -> RoutingRunResult: + """Include routes supplied by other workers in the selected final trace.""" + if not run.conflict_trace or run.conflict_trace[-1].stage != "final": + return run + final = run.conflict_trace[-1] + traced = {trace.net_id: trace for trace in final.nets} + for net_id, result in run.results_by_net.items(): + if net_id not in traced: + traced[net_id] = NetConflictTrace(net_id, result.outcome, result.reached_target, result.report) + completed = tuple(sorted(net_id for net_id, result in run.results_by_net.items() if result.is_valid)) + final = replace(final, completed_net_ids=completed, nets=tuple(traced.values())) + return replace(run, conflict_trace=(*run.conflict_trace[:-1], final)) + + def net_attempt_trace( net_id: str, deltas: Mapping[str, int], diff --git a/inire/router/_router.py b/inire/router/_router.py index 54f72f4..0cdd6c7 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -310,10 +310,12 @@ class PathFinder: recent_attempt_work={}, pre_pair_candidate=None, ) + if congestion.max_iterations <= 0: + return state self._prepare_topology(state, corridors) if state.initial_paths is None and congestion.warm_start_enabled: state.initial_paths = self._build_greedy_warm_start_paths(state) - if state.corridors and state.initial_paths and congestion.max_iterations > 0: + if state.corridors and state.initial_paths: world = self.context.cost_evaluator.collision_engine for net_id, path in state.initial_paths.items(): if not path or path[-1].end_port != net_specs[net_id].target: @@ -334,15 +336,19 @@ class PathFinder: for net_id, seed in self.context.problem.initial_paths.items(): if net_id not in net_specs: raise ValueError(f"Initial path provided for unknown net: {net_id}") + if not search.allows_seed(seed): + raise ValueError(f"Initial path for {net_id!r} uses an S-bend offset outside sbend_offsets") net = net_specs[net_id] - initial_paths[net_id] = materialize_path_seed( + path = materialize_path_seed( seed, start=net.start, net_width=net.width, search=search, clearance=self.context.cost_evaluator.collision_engine.clearance, - ) - return initial_paths + ) + if path is not None: + initial_paths[net_id] = path + return initial_paths or None def _replace_installed_paths( self, state: _RoutingState, results: dict[str, RoutingResult], *, net_ids: Sequence[str] | None = None @@ -984,7 +990,7 @@ class PathFinder: ) if iteration_callback: - iteration_callback(iteration, state.results) + iteration_callback(iteration, dict(state.results)) return review def _reverify_iteration_results(self, state: _RoutingState) -> _IterationReview: @@ -1119,8 +1125,8 @@ class PathFinder: state = self._prepare_state(corridors) timed_out = self._run_iterations(state, iteration_callback) self.accumulated_expanded_nodes = list(state.accumulated_expanded_nodes) - # A partial iteration or a callback can leave the index out of sync with the saved results. - best_is_live = not timed_out and iteration_callback is None and state.best_is_installed + # A partial iteration can leave the index out of sync with the saved results. + best_is_live = not timed_out and state.best_is_installed if not best_is_live: self._restore_best_iteration(state) diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index 5d9ba3d..6299e97 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -2,7 +2,7 @@ from __future__ import annotations from typing import TYPE_CHECKING -from inire.geometry.components import build_component +from inire.geometry.components import bend_fits_width, build_component from inire.model import resolve_bend_geometry from inire.seeds import Bend90Seed, SBendSeed, StraightSeed @@ -20,7 +20,10 @@ def materialize_path_seed( net_width: float, search: SearchOptions, clearance: float, -) -> tuple[ComponentResult, ...]: +) -> tuple[ComponentResult, ...] | None: + if any(isinstance(segment, (Bend90Seed, SBendSeed)) and not bend_fits_width(segment.radius, net_width) for segment in seed.segments): + return None + path: list[ComponentResult] = [] current = start dilation = clearance / 2.0 diff --git a/inire/router/_stack.py b/inire/router/_stack.py index 359bb64..b4cfc62 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -46,8 +46,8 @@ def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> Rou danger_map = DangerMap(bounds=problem.bounds) refinement = options.refinement - if options.objective.danger_weight or ( - refinement.enabled and refinement.objective is not None and refinement.objective.danger_weight + if options.congestion.max_iterations > 0 and ( + options.objective.danger_weight or (refinement.enabled and refinement.objective is not None and refinement.objective.danger_weight) ): danger_map.precompute(list(problem.static_obstacles)) diff --git a/inire/router/_waypoints.py b/inire/router/_waypoints.py index 0ba31fc..55367e9 100644 --- a/inire/router/_waypoints.py +++ b/inire/router/_waypoints.py @@ -1,10 +1,10 @@ from __future__ import annotations from itertools import pairwise -from math import isclose from typing import TYPE_CHECKING from inire.geometry.primitives import Port +from inire.geometry.sbend import sbend_grid_span from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed if TYPE_CHECKING: @@ -44,7 +44,7 @@ def compile_waypoints(points: tuple[XY, ...], start: Port, radius: float) -> tup ux, uy = _HEADINGS[heading // 90] offset = dy * ux - dx * uy span = dx * ux + dy * uy - if not 0 < abs(offset) < 2 * radius or not isclose(span**2, abs(offset) * (4 * radius - abs(offset))) or span <= 0: + if not 0 < abs(offset) < 2 * radius or span <= 0 or span != sbend_grid_span(offset, radius): raise ValueError(f"Invalid S-bend from {a} to {b}") segments.append(SBendSeed(offset, radius)) continue diff --git a/inire/router/refiner.py b/inire/router/refiner.py index a674060..c34fd37 100644 --- a/inire/router/refiner.py +++ b/inire/router/refiner.py @@ -6,7 +6,7 @@ from itertools import accumulate, chain from typing import TYPE_CHECKING, Any from inire.geometry.component_overlap import components_overlap -from inire.geometry.components import Bend90, Straight, _advance_port, _bend90_length +from inire.geometry.components import Bend90, Straight, _advance_port, _bend90_length, bend_fits_width from inire.geometry.primitives import port_local_coordinates, rotation_matrix2 if TYPE_CHECKING: @@ -286,6 +286,8 @@ class PathRefiner: best_candidate_cost = best_cost for radius in self.context.options.search.bend_radii: + if not bend_fits_width(radius, net_width): + continue side_extents = self._candidate_side_extents(window_start, window_end, window_path, net_width, radius) for side_extent in side_extents: moves = self._dogleg_moves(window_start, window_end, radius, side_extent) diff --git a/inire/seeds.py b/inire/seeds.py index 635e489..984ab10 100644 --- a/inire/seeds.py +++ b/inire/seeds.py @@ -1,6 +1,7 @@ from __future__ import annotations from dataclasses import dataclass +from math import isfinite from typing import Literal @@ -12,7 +13,10 @@ class StraightSeed: length: float def __post_init__(self) -> None: - object.__setattr__(self, "length", float(self.length)) + length = float(self.length) + if not isfinite(length) or length <= 0: + raise ValueError("Straight seed length must be finite and positive") + object.__setattr__(self, "length", length) @dataclass(frozen=True, slots=True) @@ -21,7 +25,12 @@ class Bend90Seed: direction: BendDirection def __post_init__(self) -> None: - object.__setattr__(self, "radius", float(self.radius)) + radius = float(self.radius) + if not isfinite(radius) or radius <= 0: + raise ValueError("Bend seed radius must be finite and positive") + if self.direction not in ("CW", "CCW"): + raise ValueError("Bend seed direction must be 'CW' or 'CCW'") + object.__setattr__(self, "radius", radius) @dataclass(frozen=True, slots=True) @@ -30,8 +39,13 @@ class SBendSeed: radius: float def __post_init__(self) -> None: - object.__setattr__(self, "offset", float(self.offset)) - object.__setattr__(self, "radius", float(self.radius)) + offset, radius = float(self.offset), float(self.radius) + if not isfinite(radius) or radius <= 0: + raise ValueError("S-bend seed radius must be finite and positive") + if not isfinite(offset) or not offset.is_integer() or not 0 < abs(offset) < 2 * radius: + raise ValueError("S-bend seed offset must be a nonzero integer with magnitude less than twice the radius") + object.__setattr__(self, "offset", offset) + object.__setattr__(self, "radius", radius) PathSegmentSeed = StraightSeed | Bend90Seed | SBendSeed diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 05319e3..5ee3684 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -2,7 +2,7 @@ import importlib import pytest import shapely -from shapely.geometry import box +from shapely.geometry import Polygon, box import inire import inire.router._router as router_module @@ -17,7 +17,9 @@ from inire import ( RefinementOptions, RoutingOptions, RoutingProblem, + SBendSeed, SearchOptions, + StraightSeed, TopologyOptions, route, ) @@ -75,6 +77,190 @@ def test_routing_problem_rejects_duplicate_net_ids() -> None: RoutingProblem(bounds=(0, 0, 100, 100), nets=nets) +@pytest.mark.parametrize("width", [0, -2, float("nan"), float("inf")]) +def test_net_width_must_be_finite_and_positive(width) -> None: + with pytest.raises(ValueError, match="width must be finite and positive"): + NetSpec("net", Port(10, 20, 0), Port(90, 20, 0), width=width) + + +@pytest.mark.parametrize("clearance", [-1.0, float("nan"), float("inf")]) +def test_routing_clearance_must_be_finite_and_nonnegative(clearance) -> None: + with pytest.raises(ValueError, match="clearance must be finite and nonnegative"): + RoutingProblem((0, 0, 100, 100), clearance=clearance) + + +@pytest.mark.parametrize( + "bounds", + [(100, 0, 0, 100), (0, 0, 100, 0), (0, 0, float("inf"), 100), (0, 0, 100, float("nan"))], +) +def test_routing_bounds_require_a_finite_positive_rectangle(bounds) -> None: + with pytest.raises(ValueError, match="bounds must be finite"): + RoutingProblem(bounds) + + +@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) +@pytest.mark.parametrize("with_seed", [False, True]) +@pytest.mark.parametrize( + ("target", "width", "segment", "search"), + [ + (Port(25, 25, 90), 12, Bend90Seed(5, "CCW"), SearchOptions(bend_radii=(5,), sbend_radii=(), node_limit=100)), + (Port(31, 23, 0), 25, SBendSeed(3, 10), SearchOptions(bend_radii=(), sbend_radii=(10,), node_limit=100)), + ], + ids=["quarter-turn", "sbend"], +) +def test_route_does_not_generate_bends_wider_than_their_diameter(mode, with_seed, target, width, segment, search) -> None: + net = NetSpec("wide", Port(20, 20, 0), target, width=width) + seeds = {"wide": PathSeed((segment,))} if with_seed else {} + problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths=seeds) + options = RoutingOptions(search=search, topology=TopologyOptions(mode=mode), congestion=CongestionOptions(max_iterations=1)) + + result = route(problem, options=options).results_by_net["wide"] + + assert not result.is_valid + assert all(isinstance(move, StraightSeed) for move in result.as_seed().segments) + + +@pytest.mark.parametrize( + ("seed_type", "args"), + [ + (StraightSeed, (-10,)), + (StraightSeed, (float("inf"),)), + (Bend90Seed, (0, "CW")), + (Bend90Seed, (10, "left")), + (SBendSeed, (0, 10)), + (SBendSeed, (20, 10)), + (SBendSeed, (3.5, 10)), + ], +) +def test_seed_parameters_must_describe_a_forward_usable_move(seed_type, args) -> None: + with pytest.raises(ValueError, match="seed"): + seed_type(*args) + + +@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) +def test_route_keeps_off_lattice_sbend_physically_connected(mode) -> None: + net = NetSpec("shift", Port(10, 20, 0), Port(60, 23, 0)) + problem = RoutingProblem((0, 0, 90, 70), (net,)) + options = RoutingOptions(topology=TopologyOptions(mode=mode)) + + result = route(problem, options=options).results_by_net["shift"] + + assert result.is_valid + assert SBendSeed(3, 10) in result.as_seed().segments + footprint = shapely.union_all(result.locked_geometry) + assert footprint.geom_type == "Polygon" + assert footprint.covers(shapely.Point(net.start.x, net.start.y)) + assert footprint.covers(shapely.Point(net.target.x, net.target.y)) + + +@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) +@pytest.mark.parametrize("offsets", [(), (4,)]) +def test_route_respects_explicit_sbend_offsets(mode, offsets) -> None: + problem = RoutingProblem((0, 0, 90, 70), (NetSpec("shift", Port(10, 20, 0), Port(60, 23, 0)),)) + options = RoutingOptions(search=SearchOptions(node_limit=100, sbend_offsets=offsets), topology=TopologyOptions(mode=mode)) + + result = route(problem, options=options).results_by_net["shift"] + + assert all(segment.offset in offsets for segment in result.as_seed().segments if isinstance(segment, SBendSeed)) + + +def test_initial_path_must_respect_explicit_sbend_offsets() -> None: + net = NetSpec("shift", Port(10, 20, 0), Port(41, 23, 0)) + seed = PathSeed((SBendSeed(3, 10), StraightSeed(20))) + problem = RoutingProblem((0, 0, 90, 70), (net,), initial_paths={"shift": seed}) + + with pytest.raises(ValueError, match="offset outside sbend_offsets"): + route(problem, options=RoutingOptions(search=SearchOptions(sbend_offsets=(4,)))) + + result = route(problem, options=RoutingOptions(search=SearchOptions(sbend_offsets=(3,)))).results_by_net["shift"] + assert result.is_valid + assert result.as_seed() == seed + + +def test_route_verification_rejects_geometry_that_misses_its_ports() -> None: + net = NetSpec("bend", Port(20, 20, 0), Port(30, 30, 90)) + seed = PathSeed((Bend90Seed(10, "CCW"),)) + problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed}) + options = RoutingOptions( + search=SearchOptions(bend_radii=(10,), bend_physical_geometry=box(4, -6, 6, -4)), + congestion=CongestionOptions(max_iterations=1), + ) + + result = route(problem, options=options).results_by_net["bend"] + + assert result.reached_target + assert not result.is_valid + assert result.report.discontinuous + + +def test_route_verification_rejects_point_only_join() -> None: + net = NetSpec("bend", Port(20, 20, 0), Port(50, 30, 90)) + seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW"))) + problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed}) + outline = Polygon([(0, -10), (4, -8), (10, 0)]) + options = RoutingOptions( + search=SearchOptions(bend_radii=(10,), bend_physical_geometry=outline), + congestion=CongestionOptions(max_iterations=1), + ) + + result = route(problem, options=options).results_by_net["bend"] + + straight, bend = result.locked_geometry + assert straight.intersection(bend).geom_type == "Point" + assert result.reached_target + assert not result.is_valid + assert result.report.discontinuous + + +def test_route_verification_rejects_geometry_past_its_arrival_port() -> None: + net = NetSpec("straight", Port(10, 25, 0), Port(50, 25, 0)) + seed = PathSeed((StraightSeed(40.49),)) + problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"straight": seed}) + options = RoutingOptions(topology=TopologyOptions(mode="off"), congestion=CongestionOptions(max_iterations=1)) + + result = route(problem, options=options).results_by_net["straight"] + + assert result.reached_target + assert not result.is_valid + assert result.report.discontinuous + + +@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) +def test_no_iterations_skips_seed_preparation(mode, monkeypatch) -> None: + problem = RoutingProblem((0, 0, 100, 100), (NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)),)) + options = RoutingOptions(topology=TopologyOptions(mode=mode), congestion=CongestionOptions(max_iterations=0)) + + def fail_if_called(*_args): + pytest.fail("Search preparation ran with zero routing iterations") + + monkeypatch.setattr(PathFinder, "_prepare_topology", fail_if_called) + monkeypatch.setattr(PathFinder, "_build_greedy_warm_start_paths", fail_if_called) + run = route(problem, options=options) + + assert run.results_by_net["line"].outcome == "unroutable" + assert run.metrics.nodes_expanded == run.metrics.warm_start_paths_built == 0 + + +def test_automatic_final_conflict_trace_includes_direct_locks() -> None: + problem = RoutingProblem( + (0, 0, 100, 100), + ( + NetSpec("direct", Port(10, 25, 0), Port(90, 25, 0)), + NetSpec("turn", Port(10, 65, 0), Port(30, 85, 90)), + ), + ) + options = RoutingOptions(diagnostics=DiagnosticsOptions(capture_conflict_trace=True)) + + run = route(problem, options=options) + + assert run.automatic is not None + assert "direct" in run.automatic.stages[run.automatic.selected_stage].direct_net_ids + final = run.conflict_trace[-1] + assert final.stage == "final" + assert final.completed_net_ids == run.automatic.verified_net_ids == ("direct",) + assert {net.net_id: net.report for net in final.nets} == {net_id: result.report for net_id, result in run.results_by_net.items()} + + @pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) def test_routes_report_boundary_violations_in_results_and_diagnostics(mode) -> None: problem = RoutingProblem( @@ -294,7 +480,7 @@ def test_iteration_callback_observes_reverified_conflicts() -> None: @pytest.mark.parametrize("mutate_results", [False, True]) -def test_installed_best_iteration_respects_callback_edits(mutate_results: bool) -> None: +def test_installed_best_iteration_isolated_from_callback_edits(mutate_results: bool) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=(NetSpec("net", Port(10, 50, 0), Port(90, 50, 0)),), @@ -309,16 +495,17 @@ def test_installed_best_iteration_respects_callback_edits(mutate_results: bool) def callback(_iteration, results): assert results["net"].is_valid - results["net"] = RoutingResult("net", ()) + wrong_path = (Straight.generate(Port(10, 75, 0), 80, 2.0),) + results["net"] = RoutingResult("net", wrong_path, reached_target=True) results = finder.route_all(iteration_callback=callback if mutate_results else None) - assert results["net"].is_valid is not mutate_results - assert world.has_dynamic_paths() is not mutate_results + assert results["net"].is_valid + assert results["net"].path[0].start_port == problem.nets[0].start + assert world.has_dynamic_paths() assert finder.metrics.snapshot().dynamic_path_objects_added == 1 - assert finder.metrics.snapshot().dynamic_path_objects_removed == int(mutate_results) - if not mutate_results: - assert finder.metrics.snapshot().verify_path_report_calls == 3 + assert finder.metrics.snapshot().dynamic_path_objects_removed == 0 + assert finder.metrics.snapshot().verify_path_report_calls == 3 def test_capture_conflict_trace_preserves_route_outputs() -> None: diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index 0fc5cb1..a613753 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -1,6 +1,8 @@ +from dataclasses import replace + import numpy import pytest -from shapely.geometry import box +from shapely.geometry import Polygon, box import inire.geometry.collision as collision_module from inire.geometry.collision import RoutingWorld @@ -24,6 +26,21 @@ def _install_static_straight( engine.add_static_obstacle(polygon) +def test_verify_path_rejects_invalid_polygon_before_clearance_checks() -> None: + world = RoutingWorld(clearance=2) + world.add_static_obstacle(box(2, -2, 8, 2)) + straight = Straight.generate(Port(0, 0, 0), 10, width=2) + self_intersecting = Polygon([(0, -1), (10, 1), (0, 1), (10, -1)]) + component = replace(straight, physical_geometry=(self_intersecting,)) + + world.install_path("invalid", (component,)) + report = world.verify_path_report("invalid", (component,)) + + assert not world.has_dynamic_paths() + assert report.invalid_geometry + assert not report.is_valid + + def test_collision_detection() -> None: engine = RoutingWorld(clearance=2.0) _install_static_straight(engine, Port(10, 15, 0), 10.0, width=10.0, dilation=1.0) diff --git a/inire/tests/test_components.py b/inire/tests/test_components.py index 0a79666..1d928c3 100644 --- a/inire/tests/test_components.py +++ b/inire/tests/test_components.py @@ -60,7 +60,7 @@ def test_sbend_generation() -> None: assert len(result.collision_geometry) == 2 # Optimization: returns individual arcs # Verify failure for large offset - with pytest.raises(ValueError, match=r"SBend offset .* must be less than 2\*radius"): + with pytest.raises(ValueError, match="offset must be a nonzero integer with magnitude less than twice the radius"): SBend.generate(start, 25.0, 10.0, 2.0) diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 0ca6770..fedc03c 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -129,7 +129,10 @@ def test_stress_residual_dogleg_completes_layout_before_wider_search() -> None: congestion=replace(case.options.congestion, max_iterations=3), ) - report = route(case.problem, options=options).automatic + ordinary = route(case.problem, options=options) + iterations = [] + observed = route(case.problem, options=options, iteration_callback=lambda index, _: iterations.append(index)) + report = ordinary.automatic assert report is not None assert set(report.verified_net_ids) == {net.net_id for net in case.problem.nets} @@ -137,6 +140,9 @@ def test_stress_residual_dogleg_completes_layout_before_wider_search() -> None: [search] = [stage for stage in report.stages if stage.operation == "search"] assert search.policy == "direct-probe-near-port" assert set(search.valid_net_ids) == {"branch_west", "branch_east", "lower_rail"} + assert observed.results_by_net == ordinary.results_by_net + assert observed.metrics.nodes_expanded == ordinary.metrics.nodes_expanded + assert iterations == list(range(observed.metrics.route_iterations)) @pytest.mark.parametrize(("iterations", "probe_limit"), [(1, 1), (3, 2)])