Preserve bend geometry through refinement and validate joins

This commit is contained in:
Jan Petykiewicz 2026-11-27 15:51:53 -08:00
commit 489c20847a
11 changed files with 205 additions and 49 deletions

View file

@ -32,7 +32,7 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati
## Geometry and refinement ## Geometry and refinement
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. Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks adjacent components for overlap and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Refinement uses the same configured bend geometry as search and seed materialization. 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). 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).

View file

@ -25,14 +25,14 @@ The fields below appear in constructor order. Use one layout unit for coordinate
| --- | --- | --- | | --- | --- | --- |
| `bounds` | Required | Finite board rectangle as `(xmin, ymin, xmax, ymax)`, with each minimum below its maximum. | | `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`. | | `nets` | `()` | Sequence of `NetSpec` objects with unique IDs. Duplicate IDs raise `ValueError`. |
| `static_obstacles` | `()` | Shapely polygons that define keepouts. | | `static_obstacles` | `()` | Valid, nonempty Shapely `Polygon` objects that define keepouts. |
| `initial_paths` | Empty mapping | Net IDs mapped to `PathSeed` objects. | | `initial_paths` | Empty mapping | Net IDs mapped to `PathSeed` objects. |
| `clearance` | `2.0` | Finite, nonnegative spacing required 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. | | `safety_zone_radius` | `0.0021` | Tolerance for small obstacle intersections at a move's endpoints during search. |
## Path seeds ## Path seeds
`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). `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. A radius absent from the corresponding option list raises `ValueError`. Search skips seeds with a configured 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 ## Results
@ -67,11 +67,11 @@ To read a route's polygons and write them to a test file, follow the [geometry e
| Field | Default | Effect | | Field | Default | Effect |
| --- | --- | --- | | --- | --- | --- |
| `node_limit` | `1_000_000` | Per-search expansion ceiling. Automatic uses smaller budgets for its initial stages. | | `node_limit` | `1_000_000` | Per-search expansion ceiling. Automatic uses smaller budgets for its initial stages. |
| `min_straight_length` | `5.0` | Minimum length for regular forward moves in lattice search. | | `min_straight_length` | `5.0` | Finite, nonnegative 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. | | `max_straight_length` | `2000.0` | Finite, positive maximum distance for the forward scan 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. | | `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. Each move needs a radius of at least half its net width. | | `bend_radii` | `(50.0, 100.0)` | Finite, positive radii permitted for 90-degree bends in search and seeds. Each move needs a radius of at least half its net width. An empty list disables 90-degree bends. |
| `sbend_radii` | `(10.0,)` | Permitted S-bend radii, subject to the same width requirement. | | `sbend_radii` | `(10.0,)` | Finite, positive radii permitted for S-bends in search and seeds, subject to the same width requirement. An empty list disables S-bends. |
| `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. | | `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_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_proxy_geometry` | `None` | Override the proxy. A custom polygon proxy by itself keeps the standard physical arc and emits a warning. |

View file

@ -716,8 +716,8 @@ class RoutingWorld:
conflicting_net_ids.update(component_hits) conflicting_net_ids.update(component_hits)
for index, component in enumerate(components): for index, component in enumerate(components):
for other_index in range(index + 2, len(components)): for other_index in range(index + 1, len(components)):
if components_overlap(component, components[other_index], prefer_actual=True): if components_overlap(component, components[other_index], prefer_actual=True, at_join=other_index == index + 1):
self_collision_count += 1 self_collision_count += 1
return PathVerificationDetail( return PathVerificationDetail(

View file

@ -2,6 +2,8 @@ from __future__ import annotations
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from inire.constants import TOLERANCE_LINEAR
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Sequence from collections.abc import Sequence
from shapely.geometry import Polygon from shapely.geometry import Polygon
@ -13,24 +15,18 @@ def components_overlap(
component_a: ComponentResult, component_a: ComponentResult,
component_b: ComponentResult, component_b: ComponentResult,
prefer_actual: bool = False, prefer_actual: bool = False,
*,
at_join: bool = False,
) -> bool: ) -> bool:
polygons_a: Sequence[Polygon] polygons_a: Sequence[Polygon]
polygons_b: Sequence[Polygon] polygons_b: Sequence[Polygon]
if prefer_actual: if prefer_actual:
polygons_a = component_a.physical_geometry polygons_a = component_a.physical_geometry
polygons_b = component_b.physical_geometry polygons_b = component_b.physical_geometry
bounds_a = ( extents_a = tuple(polygon.bounds for polygon in polygons_a)
min(polygon.bounds[0] for polygon in polygons_a), extents_b = tuple(polygon.bounds for polygon in polygons_b)
min(polygon.bounds[1] for polygon in polygons_a), bounds_a = (min(b[0] for b in extents_a), min(b[1] for b in extents_a), max(b[2] for b in extents_a), max(b[3] for b in extents_a))
max(polygon.bounds[2] for polygon in polygons_a), bounds_b = (min(b[0] for b in extents_b), min(b[1] for b in extents_b), max(b[2] for b in extents_b), max(b[3] for b in extents_b))
max(polygon.bounds[3] for polygon in polygons_a),
)
bounds_b = (
min(polygon.bounds[0] for polygon in polygons_b),
min(polygon.bounds[1] for polygon in polygons_b),
max(polygon.bounds[2] for polygon in polygons_b),
max(polygon.bounds[3] for polygon in polygons_b),
)
else: else:
polygons_a = component_a.collision_geometry polygons_a = component_a.collision_geometry
polygons_b = component_b.collision_geometry polygons_b = component_b.collision_geometry
@ -47,6 +43,15 @@ def components_overlap(
for polygon_a in polygons_a: for polygon_a in polygons_a:
for polygon_b in polygons_b: for polygon_b in polygons_b:
if polygon_a.intersects(polygon_b) and not polygon_a.touches(polygon_b): if at_join:
# Sampling a bend can leave sub-tolerance slivers at its shared face.
overlap = polygon_a.intersection(polygon_b)
if overlap.area > 0:
port = component_a.end_port
axis, position = (0, port.x) if port.r % 180 == 0 else (1, port.y)
bounds = overlap.bounds
if bounds[axis] < position - TOLERANCE_LINEAR or bounds[axis + 2] > position + TOLERANCE_LINEAR:
return True
elif polygon_a.intersects(polygon_b) and not polygon_a.touches(polygon_b):
return True return True
return False return False

View file

@ -32,16 +32,23 @@ 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) return all(board.covers(shape) for component in path for shape in component.physical_geometry)
def _has_port_face(polygon: Polygon, port: Port) -> bool: def _has_port_face(polygon: Polygon, port: Port, *, arrival: bool) -> bool:
"""Find boundary along the port plane on both sides of its center.""" """Find a centered port face with material on the required side."""
axis = 0 if port.r % 180 == 0 else 1 axis = 0 if port.r % 180 == 0 else 1
position = (port.x, port.y) position = (port.x, port.y)
coordinates = numpy.asarray(polygon.exterior.coords) exterior = polygon.exterior
coordinates = numpy.asarray(exterior.coords)
on_plane = numpy.abs(coordinates[:, axis] - position[axis]) <= TOLERANCE_LINEAR on_plane = numpy.abs(coordinates[:, axis] - position[axis]) <= TOLERANCE_LINEAR
lateral = coordinates[:, 1 - axis] - position[1 - axis] lateral = coordinates[:, 1 - axis] - position[1 - axis]
lower = numpy.minimum(lateral[:-1], lateral[1:]) lower = numpy.minimum(lateral[:-1], lateral[1:])
upper = numpy.maximum(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) at_port = on_plane[:-1] & on_plane[1:] & (lower <= TOLERANCE_LINEAR) & (upper >= -TOLERANCE_LINEAR)
# The interior is left of a counterclockwise exterior edge.
forward = 1 if port.r < 180 else -1
inward = forward if not arrival else -forward
left = (lateral[1:] - lateral[:-1]) * (1 if axis == 1 else -1)
interior = left if exterior.is_ccw else -left
at_port &= interior * inward > 0
return bool(numpy.any(at_port & (lower < 0)) and numpy.any(at_port & (upper > 0))) return bool(numpy.any(at_port & (lower < 0)) and numpy.any(at_port & (upper > 0)))
@ -133,8 +140,8 @@ class ComponentResult:
valid = bool(shapes) and all(not shape.is_empty and shape.is_valid for shape in shapes) valid = bool(shapes) and all(not shape.is_empty and shape.is_valid for shape in shapes)
connected = ( connected = (
valid valid
and _has_port_face(shapes[0], self.start_port) and _has_port_face(shapes[0], self.start_port, arrival=False)
and _has_port_face(shapes[-1], self.end_port) and _has_port_face(shapes[-1], self.end_port, arrival=True)
and all(a.intersection(b).length > TOLERANCE_LINEAR for a, b in pairwise(shapes)) and all(a.intersection(b).length > TOLERANCE_LINEAR for a, b in pairwise(shapes))
) )
object.__setattr__(self, "_physical_checks", (valid, connected)) object.__setattr__(self, "_physical_checks", (valid, connected))

View file

@ -6,7 +6,7 @@ from math import isfinite
from typing import TYPE_CHECKING, Literal from typing import TYPE_CHECKING, Literal
from shapely.geometry import Polygon from shapely.geometry import Polygon
from inire.seeds import PathSeed, SBendSeed from inire.seeds import Bend90Seed, PathSeed, SBendSeed
if TYPE_CHECKING: if TYPE_CHECKING:
from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry
@ -53,8 +53,15 @@ class SearchOptions:
visibility_guidance: VisibilityGuidance = "tangent_corner" visibility_guidance: VisibilityGuidance = "tangent_corner"
def __post_init__(self) -> None: def __post_init__(self) -> None:
object.__setattr__(self, "bend_radii", tuple(self.bend_radii)) for field_name in ("bend_radii", "sbend_radii"):
object.__setattr__(self, "sbend_radii", tuple(self.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: if self.sbend_offsets is not None:
offsets = tuple(self.sbend_offsets) offsets = tuple(self.sbend_offsets)
if any(not isfinite(offset) for offset in offsets): if any(not isfinite(offset) for offset in offsets):
@ -72,10 +79,16 @@ class SearchOptions:
def allows_sbend_offset(self, offset: float) -> bool: def allows_sbend_offset(self, offset: float) -> bool:
return self.sbend_offsets is None or offset in self.sbend_offsets return self.sbend_offsets is None or offset in self.sbend_offsets
def allows_seed(self, seed: PathSeed) -> bool: def seed_geometry_error(self, seed: PathSeed) -> str | None:
return self.sbend_offsets is None or all( for segment in seed.segments:
not isinstance(segment, SBendSeed) or self.allows_sbend_offset(segment.offset) 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( def resolve_bend_geometry(
@ -197,7 +210,13 @@ class RoutingProblem:
raise ValueError(f"Duplicate net ID: {net.net_id!r}") raise ValueError(f"Duplicate net ID: {net.net_id!r}")
seen.add(net.net_id) seen.add(net.net_id)
object.__setattr__(self, "nets", nets) object.__setattr__(self, "nets", nets)
object.__setattr__(self, "static_obstacles", tuple(self.static_obstacles)) 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", obstacles)
initial_paths = dict(self.initial_paths) initial_paths = dict(self.initial_paths)
if any(not isinstance(seed, PathSeed) for seed in initial_paths.values()): if any(not isinstance(seed, PathSeed) for seed in initial_paths.values()):
raise TypeError("RoutingProblem.initial_paths values must be PathSeed instances") raise TypeError("RoutingProblem.initial_paths values must be PathSeed instances")

View file

@ -483,7 +483,7 @@ def column_seed_candidates(
return return
for moves in _column_sbend_schedules(problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty): 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) seeds = _seeds(layout.tracks, layout.spans, moves, radius)
if all(search.allows_seed(seed) for seed in seeds.values()): if all(search.seed_geometry_error(seed) is None for seed in seeds.values()):
yield seeds yield seeds

View file

@ -336,8 +336,9 @@ class PathFinder:
for net_id, seed in self.context.problem.initial_paths.items(): for net_id, seed in self.context.problem.initial_paths.items():
if net_id not in net_specs: if net_id not in net_specs:
raise ValueError(f"Initial path provided for unknown net: {net_id}") raise ValueError(f"Initial path provided for unknown net: {net_id}")
if not search.allows_seed(seed): error = search.seed_geometry_error(seed)
raise ValueError(f"Initial path for {net_id!r} uses an S-bend offset outside sbend_offsets") if error is not None:
raise ValueError(f"Initial path for {net_id!r} {error}")
net = net_specs[net_id] net = net_specs[net_id]
path = materialize_path_seed( path = materialize_path_seed(
seed, seed,

View file

@ -1,13 +1,13 @@
from __future__ import annotations from __future__ import annotations
import math
from dataclasses import dataclass from dataclasses import dataclass
from itertools import accumulate, chain from itertools import accumulate, chain
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from inire.geometry.component_overlap import components_overlap from inire.geometry.component_overlap import components_overlap
from inire.geometry.components import Bend90, Straight, _advance_port, _bend90_length, bend_fits_width from inire.geometry.components import _advance_port, _bend90_length, bend_fits_width, build_component
from inire.geometry.primitives import port_local_coordinates, rotation_matrix2 from inire.geometry.primitives import port_local_coordinates, rotation_matrix2
from inire.model import resolve_bend_geometry
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator, Sequence from collections.abc import Iterator, Sequence
@ -173,9 +173,9 @@ class PathRefiner:
if local_dx < 4.0 * radius - 0.01 or abs(side_extent) < 0.01: if local_dx < 4.0 * radius - 0.01 or abs(side_extent) < 0.01:
return None return None
side_abs = abs(side_extent) first_sign = 1 if side_extent > 0 else -1
first_straight = side_abs - 2.0 * radius first_straight = abs(side_extent) - 2.0 * radius
second_straight = side_abs - 2.0 * radius - math.copysign(float(local_dy), side_extent) second_straight = first_straight - first_sign * local_dy
if first_straight < -0.01 or second_straight < -0.01: if first_straight < -0.01 or second_straight < -0.01:
return None return None
min_straight = self.context.options.search.min_straight_length min_straight = self.context.options.search.min_straight_length
@ -190,7 +190,6 @@ class PathRefiner:
if 0.01 < forward_length < min_straight - 0.01: if 0.01 < forward_length < min_straight - 0.01:
return None return None
first_sign = 1 if side_extent > 0 else -1
bend_length = _bend90_length(radius) bend_length = _bend90_length(radius)
moves: list[_DoglegMove] = [] moves: list[_DoglegMove] = []
curr = start curr = start
@ -209,14 +208,17 @@ class PathRefiner:
return moves if curr == target else None return moves if curr == target else None
def _build_dogleg(self, start: Port, width: float, radius: float, moves: list[_DoglegMove]) -> list[ComponentResult]: def _build_dogleg(self, start: Port, width: float, radius: float, moves: list[_DoglegMove]) -> list[ComponentResult]:
search = self.context.options.search
proxy, physical = resolve_bend_geometry(search)
dilation = self.collision_engine.clearance / 2.0 dilation = self.collision_engine.clearance / 2.0
path = [] path = []
port = start port = start
for move in moves: for move in moves:
if move.direction is None: parameters = (move.length,) if move.direction is None else (radius, move.direction)
component = Straight.generate(port, move.length, width, dilation=dilation) component = build_component(
else: port, width, move.move_type, parameters,
component = Bend90.generate(port, radius, width, move.direction, dilation=dilation) collision_type=proxy, physical_geometry_type=physical, clip_margin=search.bend_clip_margin, dilation=dilation,
)
path.append(component) path.append(component)
port = component.end_port port = component.end_port
return path return path
@ -230,6 +232,10 @@ class PathRefiner:
) -> bool: ) -> bool:
if not self.collision_engine.verify_path_report(net_id, replacement).is_valid: if not self.collision_engine.verify_path_report(net_id, replacement).is_valid:
return False return False
if prefix and components_overlap(prefix[-1], replacement[0], prefer_actual=True, at_join=True):
return False
if suffix and components_overlap(replacement[-1], suffix[0], prefer_actual=True, at_join=True):
return False
# The verified incumbent's prefix and suffix remain separated by # The verified incumbent's prefix and suffix remain separated by
# several components. Only pairs involving a replacement can change. # several components. Only pairs involving a replacement can change.
for i, component in enumerate(replacement): for i, component in enumerate(replacement):

View file

@ -98,6 +98,32 @@ def test_routing_bounds_require_a_finite_positive_rectangle(bounds) -> None:
RoutingProblem(bounds) RoutingProblem(bounds)
@pytest.mark.parametrize("keepout", [Polygon(), Polygon([(0, 0), (10, 10), (0, 10), (10, 0)])])
def test_routing_keepout_must_be_nonempty_and_valid(keepout) -> None:
with pytest.raises(ValueError, match=r"static_obstacles\[1\].*nonempty and valid"):
RoutingProblem((0, 0, 100, 100), static_obstacles=(box(20, 20, 30, 30), keepout))
def test_routing_keepout_must_be_a_polygon() -> None:
with pytest.raises(TypeError, match=r"static_obstacles\[0\].*Polygon"):
RoutingProblem((0, 0, 100, 100), static_obstacles=(box(20, 20, 30, 30).boundary,))
@pytest.mark.parametrize(
("name", "value"),
[
("bend_radii", (float("inf"),)),
("sbend_radii", (float("nan"),)),
("bend_radii", (0,)),
("min_straight_length", float("nan")),
("max_straight_length", float("inf")),
],
)
def test_search_distances_and_radii_require_finite_values(name, value) -> None:
with pytest.raises(ValueError, match=name):
SearchOptions(**{name: value})
@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) @pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"])
@pytest.mark.parametrize("with_seed", [False, True]) @pytest.mark.parametrize("with_seed", [False, True])
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -177,6 +203,20 @@ def test_initial_path_must_respect_explicit_sbend_offsets() -> None:
assert result.as_seed() == seed assert result.as_seed() == seed
@pytest.mark.parametrize("mode", ["automatic", "off"])
@pytest.mark.parametrize(
("move", "target", "field"),
[(Bend90Seed(5, "CCW"), Port(25, 25, 90), "bend_radii"), (SBendSeed(3, 10), Port(31, 23, 0), "sbend_radii")],
)
def test_initial_path_must_respect_configured_radii(mode, move, target, field) -> None:
problem = RoutingProblem(
(0, 0, 100, 100), (NetSpec("net", Port(20, 20, 0), target),), initial_paths={"net": PathSeed((move,))},
)
options = RoutingOptions(search=SearchOptions(**{field: ()}), topology=TopologyOptions(mode=mode))
with pytest.raises(ValueError, match=f"Initial path for 'net'.*outside {field}"):
route(problem, options=options)
def test_route_verification_rejects_geometry_that_misses_its_ports() -> None: def test_route_verification_rejects_geometry_that_misses_its_ports() -> None:
net = NetSpec("bend", Port(20, 20, 0), Port(30, 30, 90)) net = NetSpec("bend", Port(20, 20, 0), Port(30, 30, 90))
seed = PathSeed((Bend90Seed(10, "CCW"),)) seed = PathSeed((Bend90Seed(10, "CCW"),))
@ -212,6 +252,30 @@ def test_route_verification_rejects_point_only_join() -> None:
assert result.report.discontinuous assert result.report.discontinuous
@pytest.mark.parametrize("wrong_side", [False, True])
def test_route_verification_rejects_adjacent_component_overlap(wrong_side) -> None:
if wrong_side:
outline = shapely.union_all([box(-4, -11, 0, -9), box(-4, -10, -2, -4), box(-4, -6, 11, -4), box(9, -6, 11, 0)])
else:
outline = shapely.union_all([box(0, -11, 11, -9), box(9, -11, 11, 0), box(-4, -11, 2, -10.5)])
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})
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).area > 0
assert result.reached_target
assert not result.is_valid
assert result.report.self_collision_count == 1
assert result.report.discontinuous is wrong_side
def test_route_verification_rejects_geometry_past_its_arrival_port() -> None: def test_route_verification_rejects_geometry_past_its_arrival_port() -> None:
net = NetSpec("straight", Port(10, 25, 0), Port(50, 25, 0)) net = NetSpec("straight", Port(10, 25, 0), Port(50, 25, 0))
seed = PathSeed((StraightSeed(40.49),)) seed = PathSeed((StraightSeed(40.49),))

View file

@ -1,16 +1,70 @@
import pytest from dataclasses import replace
from inire import CongestionOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route import pytest
from shapely.geometry import Polygon
from inire import CongestionOptions, ObjectiveWeights, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
from inire.geometry.components import Bend90 from inire.geometry.components import Bend90
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.model import NetSpec from inire.model import NetSpec
from inire.router._astar_types import AStarContext from inire.router._astar_types import AStarContext
from inire.router._router import PathFinder from inire.router._router import PathFinder
from inire.router._waypoints import compile_waypoints
from inire.router.cost import CostEvaluator from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap from inire.router.danger_map import DangerMap
_FOLDBACK = ((20, 80), (60, 80), (60, 150), (120, 150), (120, 100), (180, 100), (180, 150), (240, 150), (240, 70), (280, 70))
def _seeded_foldback(*, reflected: bool = False) -> RoutingProblem:
points = tuple((x, 220 - y) for x, y in _FOLDBACK) if reflected else _FOLDBACK
start = Port(*points[0], 0)
seed, target = compile_waypoints(points, start, 10)
return RoutingProblem((0, 0, 320, 220), (NetSpec("foldback", start, target),), initial_paths={"foldback": seed})
_REFINEMENT_OPTIONS = RoutingOptions(
search=SearchOptions(node_limit=1, bend_radii=(10,)),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=1),
topology=TopologyOptions(mode="off"),
)
def test_refinement_handles_both_signs_of_the_lateral_offset() -> None:
paths = [
route(_seeded_foldback(reflected=reflected), options=_REFINEMENT_OPTIONS).results_by_net["foldback"]
for reflected in (False, True)
]
assert all(path.is_valid and sum(move.move_type == "bend90" for move in path.path) == 4 for path in paths)
assert paths[0].report.total_length == pytest.approx(paths[1].report.total_length)
@pytest.mark.parametrize("mode", ["automatic", "off"])
def test_refinement_preserves_custom_bend_geometry_on_seed_replay(mode) -> None:
outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)])
options = replace(
_REFINEMENT_OPTIONS,
search=replace(_REFINEMENT_OPTIONS.search, bend_physical_geometry=outline),
topology=TopologyOptions(mode=mode),
)
problem = _seeded_foldback()
run = route(problem, options=options)
result = run.results_by_net["foldback"]
replay = route(
replace(problem, initial_paths={"foldback": result.as_seed()}),
options=replace(options, refinement=RefinementOptions(enabled=False)),
).results_by_net["foldback"]
assert run.metrics.refinement_candidates_accepted > 0
assert result.is_valid
assert replay.is_valid
assert all(a.equals(b) for a, b in zip(result.locked_geometry, replay.locked_geometry, strict=True))
def _build_pathfinder( def _build_pathfinder(
evaluator: CostEvaluator, evaluator: CostEvaluator,
*, *,