Correct search pruning and align fractional bends to the grid

This commit is contained in:
Jan Petykiewicz 2026-11-27 18:48:24 -08:00
commit 0c66a1c15a
15 changed files with 197 additions and 62 deletions

View file

@ -70,12 +70,12 @@ To read a route's polygons and write them to a test file, follow the [geometry e
| `min_straight_length` | `5.0` | Finite, nonnegative 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` | Finite, positive maximum distance for the forward scan 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)` | 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. | | `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. Fractional radii retain their curvature and extend both tangents to the next grid point. An empty list disables 90-degree bends. |
| `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_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. |
| `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"`. | | `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"`. Custom polygons for fractional 90-degree bends are positioned relative to the arc center and must include both tangent extensions. |
| `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. The default uses the eight-point proxy. | | `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. The default uses the eight-point proxy. |
| `visibility_guidance` | `"tangent_corner"` | Choose tangent candidates, exact corner visibility with `"exact_corner"`, or no visibility suggestions with `"off"`. | | `visibility_guidance` | `"tangent_corner"` | Choose tangent candidates, exact corner visibility with `"exact_corner"`, or no visibility suggestions with `"off"`. |

View file

@ -2,6 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field
from itertools import pairwise from itertools import pairwise
from math import ceil, pi
from typing import TYPE_CHECKING, Literal from typing import TYPE_CHECKING, Literal
import numpy import numpy
@ -67,6 +68,11 @@ def bend_fits_width(radius: float, width: float) -> bool:
return radius >= width / 2 return radius >= width / 2
def bend90_grid_span(radius: float) -> int:
"""Distance from either port face to the corner on the routing grid."""
return ceil(radius)
def _normalize_length(value: float) -> float: def _normalize_length(value: float) -> float:
return float(value) return float(value)
@ -77,7 +83,7 @@ def _advance_port(start: Port, rotation: NDArray[numpy.int32], forward: float, l
def _bend90_length(radius: float) -> float: def _bend90_length(radius: float) -> float:
return abs(radius) * numpy.pi / 2.0 return radius * pi / 2 + 2 * (bend90_grid_span(radius) - radius)
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
@ -133,6 +139,10 @@ class ComponentResult:
def total_dilated_bounds(self) -> tuple[float, float, float, float]: def total_dilated_bounds(self) -> tuple[float, float, float, float]:
return self._total_dilated_bounds return self._total_dilated_bounds
@property
def bend_radius(self) -> float | None:
return self.move_spec.radius if isinstance(self.move_spec, Bend90Seed) else None
@property @property
def physical_checks(self) -> tuple[bool, bool]: def physical_checks(self) -> tuple[bool, bool]:
if self._physical_checks is None: if self._physical_checks is None:
@ -204,6 +214,8 @@ def _get_arc_polygons(
ts: tuple[float, float], ts: tuple[float, float],
sagitta: float = 0.01, sagitta: float = 0.01,
dilation: float = 0.0, dilation: float = 0.0,
*,
port_faces: tuple[Port, Port] | None = None,
) -> list[Polygon]: ) -> list[Polygon]:
t_start, t_end = numpy.radians(ts[0]), numpy.radians(ts[1]) t_start, t_end = numpy.radians(ts[0]), numpy.radians(ts[1])
num_segments = _get_num_segments(radius, abs(ts[1] - ts[0]), sagitta) num_segments = _get_num_segments(radius, abs(ts[1] - ts[0]), sagitta)
@ -215,9 +227,21 @@ def _get_arc_polygons(
cos_a = numpy.cos(angles) cos_a = numpy.cos(angles)
sin_a = numpy.sin(angles) sin_a = numpy.sin(angles)
if port_faces is not None:
cos_a[[0, -1]] = numpy.rint(cos_a[[0, -1]])
sin_a[[0, -1]] = numpy.rint(sin_a[[0, -1]])
inner_points = numpy.column_stack((cx + inner_radius * cos_a, cy + inner_radius * sin_a)) inner_points = numpy.column_stack((cx + inner_radius * cos_a, cy + inner_radius * sin_a))
outer_points = numpy.column_stack((cx + outer_radius * cos_a[::-1], cy + outer_radius * sin_a[::-1])) outer_points = numpy.column_stack((cx + outer_radius * cos_a[::-1], cy + outer_radius * sin_a[::-1]))
if port_faces is not None:
# Extend fractional radii along both tangents to reach exact grid faces.
centers = numpy.array([(port.x, port.y) for port in port_faces])
edge = (width / 2 + dilation) * numpy.column_stack((cos_a[[0, -1]], sin_a[[0, -1]]))
start_inner, end_inner = centers - edge
start_outer, end_outer = centers + edge
arc = slice(None) if radius < bend90_grid_span(radius) else slice(1, -1)
inner_points = numpy.vstack((start_inner, inner_points[arc], end_inner))
outer_points = numpy.vstack((end_outer, outer_points[arc], start_outer))
return [Polygon(numpy.concatenate((inner_points, outer_points), axis=0))] return [Polygon(numpy.concatenate((inner_points, outer_points), axis=0))]
@ -260,6 +284,8 @@ def _clip_bbox_polygonal(cxy: tuple[float, float], radius: float, width: float,
angles = numpy.radians(numpy.linspace(ts[0], ts[1], sample_count)) angles = numpy.radians(numpy.linspace(ts[0], ts[1], sample_count))
cos_a = numpy.cos(angles) cos_a = numpy.cos(angles)
sin_a = numpy.sin(angles) sin_a = numpy.sin(angles)
cos_a[numpy.abs(cos_a) < 1e-15] = 0
sin_a[numpy.abs(sin_a) < 1e-15] = 0
outer_points = numpy.column_stack((cx + conservative_outer_radius * cos_a, cy + conservative_outer_radius * sin_a)) outer_points = numpy.column_stack((cx + conservative_outer_radius * cos_a, cy + conservative_outer_radius * sin_a))
inner_points = numpy.column_stack((cx + conservative_inner_radius * cos_a[::-1], cy + conservative_inner_radius * sin_a[::-1])) inner_points = numpy.column_stack((cx + conservative_inner_radius * cos_a[::-1], cy + conservative_inner_radius * sin_a[::-1]))
@ -376,21 +402,27 @@ class Bend90:
rot2 = rotation_matrix2(start_port.r) rot2 = rotation_matrix2(start_port.r)
sign = 1 if direction == "CCW" else -1 sign = 1 if direction == "CCW" else -1
center_local = numpy.array((0.0, sign * radius)) grid_span = bend90_grid_span(radius)
tangent_length = grid_span - radius
center_local = numpy.array((tangent_length, sign * radius))
center_xy = (rot2 @ center_local) + numpy.array((start_port.x, start_port.y)) center_xy = (rot2 @ center_local) + numpy.array((start_port.x, start_port.y))
end_port = _advance_port(start_port, rot2, radius, sign * radius, sign * 90) center = (float(center_xy[0]), float(center_xy[1]))
end_port = _advance_port(start_port, rot2, grid_span, sign * grid_span, sign * 90)
start_theta = start_port.r - sign * 90 start_theta = start_port.r - sign * 90
end_theta = start_port.r end_theta = start_port.r
ts = (float(start_theta), float(end_theta)) ts = (float(start_theta), float(end_theta))
arc_polys = _get_arc_polygons((float(center_xy[0]), float(center_xy[1])), radius, width, ts, sagitta) port_faces = (start_port, end_port)
arc_polys = _get_arc_polygons(center, radius, width, ts, sagitta, port_faces=port_faces)
if tangent_length and collision_type == "clipped_bbox":
collision_type = "bbox"
collision_polys = _apply_collision_model( collision_polys = _apply_collision_model(
arc_polys[0], arc_polys[0],
collision_type, collision_type,
radius, radius,
width, width,
(float(center_xy[0]), float(center_xy[1])), center,
ts, ts,
clip_margin=clip_margin, clip_margin=clip_margin,
rotation_deg=float(start_port.r), rotation_deg=float(start_port.r),
@ -403,7 +435,7 @@ class Bend90:
physical_geometry_type, physical_geometry_type,
radius, radius,
width, width,
(float(center_xy[0]), float(center_xy[1])), center,
ts, ts,
rotation_deg=float(start_port.r), rotation_deg=float(start_port.r),
mirror_y=(sign < 0), mirror_y=(sign < 0),
@ -417,12 +449,13 @@ class Bend90:
dilated_physical_geometry = [poly.buffer(dilation) for poly in physical_geometry] dilated_physical_geometry = [poly.buffer(dilation) for poly in physical_geometry]
else: else:
dilated_physical_geometry = _get_arc_polygons( dilated_physical_geometry = _get_arc_polygons(
(float(center_xy[0]), float(center_xy[1])), center,
radius, radius,
width, width,
ts, ts,
sagitta, sagitta,
dilation=dilation, dilation=dilation,
port_faces=port_faces,
) )
dilated_collision_geometry = ( dilated_collision_geometry = (
dilated_physical_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in collision_polys] dilated_physical_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in collision_polys]

View file

@ -6,7 +6,7 @@ from typing import TYPE_CHECKING
from shapely.geometry import Polygon from shapely.geometry import Polygon
from inire.constants import TOLERANCE_LINEAR from inire.constants import TOLERANCE_LINEAR
from inire.geometry.components import build_component from inire.geometry.components import build_component, path_within_board
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.router.refiner import component_hits_ancestor_chain from inire.router.refiner import component_hits_ancestor_chain
@ -121,13 +121,6 @@ def add_node(
metrics.moves_generated += 1 metrics.moves_generated += 1
metrics.total_moves_generated += 1 metrics.total_moves_generated += 1
state = result.end_port.as_tuple() state = result.end_port.as_tuple()
new_lower_bound_g = parent.g_cost + result.length
if state in closed_set and closed_set[state] <= new_lower_bound_g + TOLERANCE_LINEAR:
if frontier_trace is not None:
frontier_trace.record("closed_set", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds)
metrics.pruned_closed_set += 1
metrics.total_pruned_closed_set += 1
return
parent_p = parent.port parent_p = parent.port
end_p = result.end_port end_p = result.end_port
@ -150,9 +143,11 @@ def add_node(
is_static_safe = cache_key in context.static_safe_cache is_static_safe = cache_key in context.static_safe_cache
if is_static_safe: if is_static_safe:
context.metrics.total_static_safe_cache_hits += 1 context.metrics.total_static_safe_cache_hits += 1
if not is_static_safe: else:
ce = context.cost_evaluator.collision_engine ce = context.cost_evaluator.collision_engine
if move_type == "straight": if ce.board is not None and not path_within_board((result,), ce.board):
collision_found = True
elif move_type == "straight":
collision_found = ce.check_move_straight_static(parent_p, result.length, net_width=net_width) collision_found = ce.check_move_straight_static(parent_p, result.length, net_width=net_width)
else: else:
collision_found = ce.check_move_static(result, start_port=parent_p, end_port=end_p) collision_found = ce.check_move_static(result, start_port=parent_p, end_port=end_p)
@ -214,7 +209,7 @@ def add_node(
metrics.total_pruned_cost += 1 metrics.total_pruned_cost += 1
return return
if state in closed_set and closed_set[state] <= parent.g_cost + move_cost + TOLERANCE_LINEAR: if context.congestion_penalty >= 0 and state in closed_set and closed_set[state] <= parent.g_cost + move_cost + TOLERANCE_LINEAR:
if frontier_trace is not None: if frontier_trace is not None:
frontier_trace.record("closed_set", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds) frontier_trace.record("closed_set", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds)
metrics.pruned_closed_set += 1 metrics.pruned_closed_set += 1

View file

@ -4,7 +4,7 @@ import math
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from inire.constants import TOLERANCE_LINEAR from inire.constants import TOLERANCE_LINEAR
from inire.geometry.components import bend_fits_width from inire.geometry.components import bend_fits_width, bend90_grid_span
from inire.geometry.sbend import sbend_grid_span from inire.geometry.sbend import sbend_grid_span
from ._astar_admission import process_move from ._astar_admission import process_move
@ -117,7 +117,7 @@ def _visible_straight_candidates(
if tangent_error > 2.0: if tangent_error > 2.0:
continue continue
length = local_x - nearest_radius length = local_x - bend90_grid_span(nearest_radius)
if length <= search_options.min_straight_length or length > max_reach + 0.01: if length <= search_options.min_straight_length or length > max_reach + 0.01:
continue continue
@ -234,8 +234,9 @@ def expand_moves(
axis_target_dist = abs(dx_t) if cp.r in (0, 180) else abs(dy_t) axis_target_dist = abs(dx_t) if cp.r in (0, 180) else abs(dy_t)
candidate_lengths.append(axis_target_dist) candidate_lengths.append(axis_target_dist)
for radius in search_options.bend_radii: bend_spans = tuple(bend90_grid_span(radius) for radius in search_options.bend_radii)
candidate_lengths.extend((max_reach - radius, axis_target_dist - radius, axis_target_dist - 2.0 * radius)) for span in bend_spans:
candidate_lengths.extend((max_reach - span, axis_target_dist - span, axis_target_dist - 2 * span))
candidate_lengths.extend( candidate_lengths.extend(
_visible_straight_candidates( _visible_straight_candidates(
@ -257,10 +258,10 @@ def expand_moves(
guide_offsets: set[int] = set() guide_offsets: set[int] = set()
if config.corridor is not None: if config.corridor is not None:
max_radius = max((*search_options.bend_radii, *search_options.sbend_radii), default=0.0) max_radius = max((*bend_spans, *search_options.sbend_radii), default=0.0)
for forward, lateral in config.corridor.nearby_anchors(cp, max_reach + 2 * max_radius): for forward, lateral in config.corridor.nearby_anchors(cp, max_reach + 2 * max_radius):
candidate_lengths.append(forward) candidate_lengths.append(forward)
candidate_lengths.extend(forward - radius for radius in search_options.bend_radii) candidate_lengths.extend(forward - span for span in bend_spans)
if search_options.sbend_offsets is None and abs(lateral) >= 1 and search_options.sbend_radii: if search_options.sbend_offsets is None and abs(lateral) >= 1 and search_options.sbend_radii:
for radius in search_options.sbend_radii: for radius in search_options.sbend_radii:
span = _sbend_forward_span(lateral, radius) span = _sbend_forward_span(lateral, radius)

View file

@ -3,6 +3,7 @@ from __future__ import annotations
from itertools import pairwise from itertools import pairwise
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from inire.geometry.components import bend90_grid_span
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.geometry.sbend import sbend_grid_span from inire.geometry.sbend import sbend_grid_span
from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed
@ -35,6 +36,7 @@ def compile_waypoints(points: tuple[XY, ...], start: Port, radius: float) -> tup
raise ValueError("The waypoint path must start at the port and have at least two points") raise ValueError("The waypoint path must start at the port and have at least two points")
directions = [_direction(a, b) for a, b in pairwise(points)] directions = [_direction(a, b) for a, b in pairwise(points)]
corners = tuple(a is not None and b is not None and a != b for a, b in pairwise(directions)) corners = tuple(a is not None and b is not None and a != b for a, b in pairwise(directions))
bend_span = bend90_grid_span(radius)
segments: list[PathSegmentSeed] = [] segments: list[PathSegmentSeed] = []
heading = int(start.r) heading = int(start.r)
for index, (a, b) in enumerate(pairwise(points)): for index, (a, b) in enumerate(pairwise(points)):
@ -52,7 +54,7 @@ def compile_waypoints(points: tuple[XY, ...], start: Port, radius: float) -> tup
raise ValueError(f"Inconsistent segment heading from {a} to {b}") raise ValueError(f"Inconsistent segment heading from {a} to {b}")
entry = index > 0 and corners[index - 1] entry = index > 0 and corners[index - 1]
exit_corner = index < len(corners) and corners[index] exit_corner = index < len(corners) and corners[index]
length = abs(dx) + abs(dy) - radius * (entry + exit_corner) length = abs(dx) + abs(dy) - bend_span * (entry + exit_corner)
if length < 0: if length < 0:
raise ValueError(f"Overlapping bend tangencies from {a} to {b}") raise ValueError(f"Overlapping bend tangencies from {a} to {b}")
if length: if length:
@ -84,7 +86,8 @@ def export_waypoints(path: Sequence[ComponentResult]) -> tuple[tuple[float, floa
move = component.move_spec move = component.move_spec
if isinstance(move, Bend90Seed): if isinstance(move, Bend90Seed):
ux, uy = _HEADINGS[int(start.r) // 90] ux, uy = _HEADINGS[int(start.r) // 90]
append(start.x + ux * move.radius, start.y + uy * move.radius) span = bend90_grid_span(move.radius)
append(start.x + ux * span, start.y + uy * span)
elif isinstance(move, SBendSeed): elif isinstance(move, SBendSeed):
append(start.x, start.y) append(start.x, start.y)
append(component.end_port.x, component.end_port.y) append(component.end_port.x, component.end_port.y)

View file

@ -25,6 +25,8 @@ if TYPE_CHECKING:
def length(self) -> float: ... def length(self) -> float: ...
@property @property
def move_type(self) -> MoveKind: ... def move_type(self) -> MoveKind: ...
@property
def bend_radius(self) -> float | None: ...
def weighted_path_length(path: Iterable[ScoreableMove], weights: Mapping[MoveKind, float]) -> float: def weighted_path_length(path: Iterable[ScoreableMove], weights: Mapping[MoveKind, float]) -> float:
@ -177,12 +179,9 @@ class CostEvaluator:
metrics.total_score_component_total_ns += perf_counter_ns() - start_ns metrics.total_score_component_total_ns += perf_counter_ns() - start_ns
return 1e15 return 1e15
move_radius = None
if component.move_type == "bend90":
move_radius = component.length * 2.0 / np.pi if component.length > 0 else None
total_cost = component.length * active_weights.unit_length_cost + self.component_penalty( total_cost = component.length * active_weights.unit_length_cost + self.component_penalty(
component.move_type, component.move_type,
move_radius=move_radius, move_radius=component.bend_radius,
weights=active_weights, weights=active_weights,
) )

View file

@ -1,11 +1,13 @@
from __future__ import annotations from __future__ import annotations
from collections import OrderedDict from collections import OrderedDict
from itertools import chain
from time import perf_counter_ns from time import perf_counter_ns
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
import numpy import numpy
from scipy.spatial import cKDTree from scipy.spatial import cKDTree
from shapely.geometry import box
if TYPE_CHECKING: if TYPE_CHECKING:
from shapely.geometry import Polygon from shapely.geometry import Polygon
@ -50,20 +52,17 @@ class DangerMap:
""" """
Pre-compute the proximity tree by sampling obstacle boundaries. Pre-compute the proximity tree by sampling obstacle boundaries.
""" """
reach = self.safety_threshold
window = box(self.minx - reach, self.miny - reach, self.maxx + reach, self.maxy + reach)
all_points = [] all_points = []
for poly in obstacles: for poly in obstacles:
# Sample exterior for ring in chain((poly.exterior,), poly.interiors):
exterior = poly.exterior if not window.intersects(ring):
continue
length = ring.length
dist = 0.0 dist = 0.0
while dist < exterior.length: while dist < length:
pt = exterior.interpolate(dist) pt = ring.interpolate(dist)
all_points.append((pt.x, pt.y))
dist += self.resolution
# Sample interiors (holes)
for interior in poly.interiors:
dist = 0.0
while dist < interior.length:
pt = interior.interpolate(dist)
all_points.append((pt.x, pt.y)) all_points.append((pt.x, pt.y))
dist += self.resolution dist += self.resolution

View file

@ -5,7 +5,7 @@ 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 _advance_port, _bend90_length, bend_fits_width, build_component from inire.geometry.components import _advance_port, _bend90_length, bend_fits_width, bend90_grid_span, 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 from inire.model import resolve_bend_geometry
@ -26,6 +26,7 @@ class _DoglegMove:
length: float length: float
move_type: MoveKind move_type: MoveKind
direction: BendDirection | None = None direction: BendDirection | None = None
bend_radius: float | None = None
def component_hits_ancestor_chain(component: ComponentResult, parent_node: Any) -> bool: def component_hits_ancestor_chain(component: ComponentResult, parent_node: Any) -> bool:
@ -90,7 +91,8 @@ class PathRefiner:
radius: float, radius: float,
) -> list[float]: ) -> list[float]:
local_dx, local_dy = port_local_coordinates(start, target.x, target.y) local_dx, local_dy = port_local_coordinates(start, target.x, target.y)
if local_dx < 4.0 * radius - 0.01: span = bend90_grid_span(radius)
if local_dx < 4 * span:
return [] return []
local_points = [port_local_coordinates(start, start.x, start.y)] local_points = [port_local_coordinates(start, start.x, start.y)]
@ -113,7 +115,7 @@ class PathRefiner:
elif local_dy < 0: elif local_dy < 0:
negative_anchors.add(float(local_dy)) negative_anchors.add(float(local_dy))
pad = 2.0 * radius + self.collision_engine.clearance + net_width pad = 2 * span + self.collision_engine.clearance + net_width
query_bounds = self._window_query_bounds(start, target, window_path, pad) query_bounds = self._window_query_bounds(start, target, window_path, pad)
x_min = min(0.0, float(local_dx)) - 0.01 x_min = min(0.0, float(local_dx)) - 0.01
x_max = max(0.0, float(local_dx)) + 0.01 x_max = max(0.0, float(local_dx)) + 0.01
@ -170,11 +172,12 @@ class PathRefiner:
side_extent: float, side_extent: float,
) -> list[_DoglegMove] | None: ) -> list[_DoglegMove] | None:
local_dx, local_dy = port_local_coordinates(start, target.x, target.y) local_dx, local_dy = port_local_coordinates(start, target.x, target.y)
if local_dx < 4.0 * radius - 0.01 or abs(side_extent) < 0.01: span = bend90_grid_span(radius)
if local_dx < 4 * span or abs(side_extent) < 0.01:
return None return None
first_sign = 1 if side_extent > 0 else -1 first_sign = 1 if side_extent > 0 else -1
first_straight = abs(side_extent) - 2.0 * radius first_straight = round(abs(side_extent)) - 2 * span
second_straight = first_straight - first_sign * local_dy 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
@ -184,9 +187,7 @@ class PathRefiner:
if 0.01 < second_straight < min_straight - 0.01: if 0.01 < second_straight < min_straight - 0.01:
return None return None
forward_length = local_dx - 4.0 * radius forward_length = local_dx - 4 * span
if forward_length < -0.01:
return None
if 0.01 < forward_length < min_straight - 0.01: if 0.01 < forward_length < min_straight - 0.01:
return None return None
@ -199,8 +200,8 @@ class PathRefiner:
(-first_sign, second_straight), (-first_sign, second_straight),
(first_sign, 0.0), (first_sign, 0.0),
): ):
curr = _advance_port(curr, rotation_matrix2(curr.r), radius, sign * radius, sign * 90) curr = _advance_port(curr, rotation_matrix2(curr.r), span, sign * span, sign * 90)
moves.append(_DoglegMove(curr, bend_length, "bend90", "CCW" if sign > 0 else "CW")) moves.append(_DoglegMove(curr, bend_length, "bend90", "CCW" if sign > 0 else "CW", bend_radius=radius))
if straight_len > 0.01: if straight_len > 0.01:
length = float(straight_len) length = float(straight_len)
curr = _advance_port(curr, rotation_matrix2(curr.r), length) curr = _advance_port(curr, rotation_matrix2(curr.r), length)
@ -247,7 +248,7 @@ class PathRefiner:
def _iter_refinement_windows(self, start: Port, path: Sequence[ComponentResult]) -> Iterator[tuple[int, int]]: def _iter_refinement_windows(self, start: Port, path: Sequence[ComponentResult]) -> Iterator[tuple[int, int]]:
ports = self._path_ports(start, path) ports = self._path_ports(start, path)
min_radius = min(self.context.options.search.bend_radii, default=0.0) min_bend_span = bend90_grid_span(min(self.context.options.search.bend_radii, default=0.0))
bends = [component.move_type == "bend90" for component in path] bends = [component.move_type == "bend90" for component in path]
bend_counts = tuple(accumulate(bends, initial=0)) bend_counts = tuple(accumulate(bends, initial=0))
limit = self.context.options.refinement.max_windows_per_net limit = self.context.options.refinement.max_windows_per_net
@ -267,7 +268,7 @@ class PathRefiner:
if window_start.r != window_end.r: if window_start.r != window_end.r:
continue continue
local_dx, _ = port_local_coordinates(window_start, window_end.x, window_end.y) local_dx, _ = port_local_coordinates(window_start, window_end.x, window_end.y)
if local_dx >= 4.0 * min_radius - 0.01: if local_dx >= 4 * min_bend_span:
yield start_idx, end_idx yield start_idx, end_idx
def _try_refine_window( def _try_refine_window(

View file

@ -333,6 +333,7 @@ def test_routes_report_boundary_violations_in_results_and_diagnostics(mode) -> N
NetSpec("edge", Port(10, 0, 0), Port(90, 0, 0)), NetSpec("edge", Port(10, 0, 0), Port(90, 0, 0)),
NetSpec("flush", Port(0, 50, 0), Port(100, 50, 0)), NetSpec("flush", Port(0, 50, 0), Port(100, 50, 0)),
), ),
initial_paths={"edge": PathSeed((StraightSeed(80),))},
) )
options = RoutingOptions( options = RoutingOptions(
search=SearchOptions(node_limit=100), search=SearchOptions(node_limit=100),
@ -365,6 +366,42 @@ def test_routes_report_boundary_violations_in_results_and_diagnostics(mode) -> N
assert traced_edge.report == edge.report assert traced_edge.report == edge.report
def test_lattice_search_detours_inside_board() -> None:
problem = RoutingProblem(
(0, 0, 120, 100),
nets=(NetSpec("detour", Port(10, 20, 0), Port(110, 20, 0)),),
static_obstacles=(box(43, 3, 73, 45),),
clearance=0,
)
options = RoutingOptions(
search=SearchOptions(bend_radii=(5,), sbend_radii=(), node_limit=1000),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
result = route(problem, options=options).results_by_net["detour"]
assert result.is_valid
board = box(*problem.bounds)
assert all(board.covers(polygon) for polygon in result.locked_geometry)
@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"])
def test_fractional_quarter_turn_reaches_its_terminal_face(mode) -> None:
problem = RoutingProblem((0, 0, 100, 100), nets=(NetSpec("bend", Port(20, 20, 0), Port(31, 31, 90)),))
options = RoutingOptions(
search=SearchOptions(bend_radii=(10.25,), sbend_radii=(), node_limit=100),
congestion=CongestionOptions(max_iterations=1),
topology=TopologyOptions(mode=mode),
)
result = route(problem, options=options).results_by_net["bend"]
assert result.is_valid
assert result.as_seed() == PathSeed((Bend90Seed(10.25, "CCW"),))
@pytest.mark.parametrize("mode", ["automatic", "off"]) @pytest.mark.parametrize("mode", ["automatic", "off"])
@pytest.mark.parametrize("proxy", ["clipped_bbox", "custom"]) @pytest.mark.parametrize("proxy", ["clipped_bbox", "custom"])
def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None: def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None:

View file

@ -483,6 +483,35 @@ def test_closed_set_dominance_prunes_before_congestion_check(basic_evaluator: Co
assert context.metrics.total_congestion_cache_misses == 0 assert context.metrics.total_congestion_cache_misses == 0
@pytest.mark.parametrize(("length_weight", "guidance_bonus", "expected_cost"), [(0.1, 0, 1), (1, 8, 2)])
def test_closed_set_keeps_cheaper_weighted_or_guided_move(length_weight, guidance_bonus, expected_cost) -> None:
evaluator = CostEvaluator(RoutingWorld(clearance=0), unit_length_cost=length_weight)
context = _build_context(evaluator, bounds=BOUNDS)
root = AStarNode(Port(0, 0, 0), 0.0, 0.0, seed_index=0)
move = Straight.generate(root.port, 10, width=2.0)
open_set = []
add_node(
root,
move,
target=Port(20, 0, 0),
net_width=2.0,
net_id="netA",
open_set=open_set,
closed_set={move.end_port.as_tuple(): 5.0},
context=context,
metrics=context.metrics,
congestion=CongestionCaches(),
config=SearchRunConfig.from_options(
context.options, guidance_seed=(move.move_spec,) if guidance_bonus else None, guidance_bonus=guidance_bonus,
),
move_type="straight",
cache_key=("cheaper",),
)
assert [node.g_cost for node in open_set] == [expected_cost]
def test_no_dynamic_paths_skips_congestion_check(basic_evaluator: CostEvaluator) -> None: def test_no_dynamic_paths_skips_congestion_check(basic_evaluator: CostEvaluator) -> None:
context = _build_context(basic_evaluator, bounds=BOUNDS) context = _build_context(basic_evaluator, bounds=BOUNDS)
root = AStarNode(Port(0, 0, 0), 0.0, 0.0) root = AStarNode(Port(0, 0, 0), 0.0, 0.0)

View file

@ -1,5 +1,6 @@
import pytest import pytest
from dataclasses import FrozenInstanceError from dataclasses import FrozenInstanceError
from math import pi, sqrt
from shapely.affinity import rotate as shapely_rotate from shapely.affinity import rotate as shapely_rotate
from shapely.affinity import scale as shapely_scale from shapely.affinity import scale as shapely_scale
from shapely.affinity import translate as shapely_translate from shapely.affinity import translate as shapely_translate
@ -8,6 +9,8 @@ from shapely.geometry import Polygon
import inire.geometry.components as components_module import inire.geometry.components as components_module
from inire.geometry.components import Bend90, SBend, Straight from inire.geometry.components import Bend90, SBend, Straight
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.router.cost import CostEvaluator
from inire.geometry.collision import RoutingWorld
def test_straight_generation() -> None: def test_straight_generation() -> None:
@ -48,6 +51,23 @@ def test_bend90_generation() -> None:
assert result_ccw.end_port.r == 90.0 assert result_ccw.end_port.r == 90.0
@pytest.mark.parametrize("direction", ["CW", "CCW"])
@pytest.mark.parametrize("proxy", ["arc", "clipped_bbox"])
def test_fractional_bend_preserves_radius_and_extends_both_tangents(direction, proxy) -> None:
radius = 10.25
start = Port(20, 20, 90)
result = Bend90.generate(start, radius, 2, direction, collision_type=proxy, dilation=1)
end = Port(31, 31, 0) if direction == "CW" else Port(9, 31, 180)
assert result.end_port == end
assert result.physical_checks == (True, True)
assert result.collision_geometry[0].covers(result.physical_geometry[0])
assert result.dilated_physical_geometry[0].covers(result.physical_geometry[0])
assert result.length == pytest.approx(radius * pi / 2 + 1.5)
evaluator = CostEvaluator(RoutingWorld(clearance=0), bend_penalty=50)
assert evaluator.score_component(result) == pytest.approx(result.length + 50 * sqrt(10 / radius))
def test_sbend_generation() -> None: def test_sbend_generation() -> None:
start = Port(0, 0, 0) start = Port(0, 0, 0)
offset = 5.0 offset = 5.0

View file

@ -1,4 +1,4 @@
from shapely.geometry import Polygon from shapely.geometry import Polygon, box
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.router.cost import CostEvaluator from inire.router.cost import CostEvaluator
@ -93,3 +93,19 @@ def test_danger_map_cache_is_instance_local_and_cleared_on_precompute() -> None:
dm_a.precompute([]) dm_a.precompute([])
assert len(dm_a._cost_cache) == 0 assert len(dm_a._cost_cache) == 0
def test_danger_map_skips_distant_rings_and_keeps_nearby_exteriors_and_holes() -> None:
danger = DangerMap((0, 0, 20, 20), resolution=1, safety_threshold=5)
outside = box(30, 30, 100_030, 100_030)
surrounding = box(-100, -100, 100, 100)
danger.precompute([outside, surrounding])
assert danger.tree is None
nearby = box(23, 0, 24, 20)
hole = box(-3, -3, 1, 23)
danger.precompute([outside, nearby, Polygon(surrounding.exterior, [hole.exterior])])
assert danger.tree.n == nearby.exterior.length + hole.exterior.length
assert danger.get_cost(20, 10) > 0
assert danger.get_cost(0, 10) > 0
assert danger.get_cost(10, 10) == 0

View file

@ -18,10 +18,10 @@ 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)) _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: def _seeded_foldback(*, reflected: bool = False, radius: float = 10) -> RoutingProblem:
points = tuple((x, 220 - y) for x, y in _FOLDBACK) if reflected else _FOLDBACK points = tuple((x, 220 - y) for x, y in _FOLDBACK) if reflected else _FOLDBACK
start = Port(*points[0], 0) start = Port(*points[0], 0)
seed, target = compile_waypoints(points, start, 10) seed, target = compile_waypoints(points, start, radius)
return RoutingProblem((0, 0, 320, 220), (NetSpec("foldback", start, target),), initial_paths={"foldback": seed}) return RoutingProblem((0, 0, 320, 220), (NetSpec("foldback", start, target),), initial_paths={"foldback": seed})
@ -33,9 +33,11 @@ _REFINEMENT_OPTIONS = RoutingOptions(
) )
def test_refinement_handles_both_signs_of_the_lateral_offset() -> None: @pytest.mark.parametrize("radius", [10, 10.25])
def test_refinement_handles_both_signs_of_the_lateral_offset(radius) -> None:
options = replace(_REFINEMENT_OPTIONS, search=replace(_REFINEMENT_OPTIONS.search, bend_radii=(radius,)))
paths = [ paths = [
route(_seeded_foldback(reflected=reflected), options=_REFINEMENT_OPTIONS).results_by_net["foldback"] route(_seeded_foldback(reflected=reflected, radius=radius), options=options).results_by_net["foldback"]
for reflected in (False, True) for reflected in (False, True)
] ]

View file

@ -23,7 +23,7 @@ dynamic = ["version"]
dependencies = [ dependencies = [
"numpy", "numpy",
"scipy", "scipy",
"shapely", "shapely>=2.0",
"rtree", "rtree",
"matplotlib", "matplotlib",
] ]

2
uv.lock generated
View file

@ -196,7 +196,7 @@ requires-dist = [
{ name = "numpy" }, { name = "numpy" },
{ name = "rtree" }, { name = "rtree" },
{ name = "scipy" }, { name = "scipy" },
{ name = "shapely" }, { name = "shapely", specifier = ">=2.0" },
] ]
[package.metadata.requires-dev] [package.metadata.requires-dev]