Keep constructive routing available without triangulation

This commit is contained in:
Jan Petykiewicz 2026-11-27 21:14:09 -08:00
commit 760182f25c
17 changed files with 260 additions and 153 deletions

View file

@ -8,7 +8,7 @@ Follow one complete run from board input through planning, verification, and plo
![Automatic routing sets a target for the number of verified nets and tries several ways to reach it. The router selects and optionally refines its best layout before returning a result for each net.](figures/automatic-stages.png) ![Automatic routing sets a target for the number of verified nets and tries several ways to reach it. The router selects and optionally refines its best layout before returning a result for each net.](figures/automatic-stages.png)
Follow the left column down while the number of verified nets is below the target. The router selects a layout when an attempt reaches that target or the attempts run out. It uses lattice search directly for custom physical bends, polygonal proxies, or a run without constrained triangulation. Follow the left column down while the number of verified nets is below the target. The router selects a layout when an attempt reaches that target or the attempts run out. It uses lattice search directly for custom physical bends or polygonal proxies. If constructive planning falls short and constrained triangulation is unavailable, it continues with lattice search.
1. **Set the coverage target.** A pair of nets with fixed ports that are too close can supply at most one route. Count such pairs using each net at most once. For rectangular keepouts, also bound the number of paths that can cross a vertical cut by packing tracks at the narrowest requested width. To see how the openings are counted, start with [`cut_capacity()`](../inire/router/_capacity.py#L27). 1. **Set the coverage target.** A pair of nets with fixed ports that are too close can supply at most one route. Count such pairs using each net at most once. For rectangular keepouts, also bound the number of paths that can cross a vertical cut by packing tracks at the narrowest requested width. To see how the openings are counted, start with [`cut_capacity()`](../inire/router/_capacity.py#L27).
2. **Try constructive planners.** Bundles assign ordered tracks through barriers. Column schedules place turns between openings. Compact planners fit short connections between constrained ports. Each produces seeds whose physical geometry the worker checks. 2. **Try constructive planners.** Bundles assign ordered tracks through barriers. Column schedules place turns between openings. Compact planners fit short connections between constrained ports. Each produces seeds whose physical geometry the worker checks.

View file

@ -67,6 +67,32 @@ python -m scripts.compare_topological_routing \
To see how heading inference changes the route, rerun the gallery command with `--case complex-routing-example-1-point-terminals`. Automatic accepts the westbound arrival for `net_08`, verifies the original `bundle` plan, and then refines it. Both stages again verify nine nets with zero A* expansions. [Point-terminal figure](../examples/advanced.md#point-terminals) · [Waypoint export command](benchmark-fixtures.md#complex-routing-example-1) To see how heading inference changes the route, rerun the gallery command with `--case complex-routing-example-1-point-terminals`. Automatic accepts the westbound arrival for `net_08`, verifies the original `bundle` plan, and then refines it. Both stages again verify nine nets with zero A* expansions. [Point-terminal figure](../examples/advanced.md#point-terminals) · [Waypoint export command](benchmark-fixtures.md#complex-routing-example-1)
## Compare all routing modes
These runs use the same nine-net board with a 100-node limit per search, one congestion iteration, warm start disabled, and refinement disabled. The table compares a run with triangulation available against a run with that capability disabled. Each mode keeps the input headings except `bundle`, which uses `infer_terminal_headings=True` so `net_08` can arrive westbound. Explicit `bundle` with the original fixed eastbound headings raises a heading mismatch for that net.
| Mode | With triangulation available | Without triangulation |
| --- | --- | --- |
| `automatic` | 9/9 verified. The turnaround plan completes the layout without building a mesh. | 9/9 verified through the same turnaround plan. Automatic uses lattice search if constructive planning leaves work. |
| `off` | 0/9 verified at this budget. The worker runs lattice search directly. | Same search and result. |
| `guide` | 1/9 verified. The worker builds a mesh and suggests corridors to lattice search. | Raises a dependency error when planning corridors. |
| `seed` | 1/9 verified. The worker builds a mesh and searches for starting paths inside the corridors before its routing iteration. | Raises a dependency error when planning corridors. |
| `bundle` | 9/9 verified. The worker builds and verifies ordered tracks directly from the board geometry. | Same plan and result. |
![Five panels show route outcomes at the same search budget. Automatic and bundle verify all nine nets. Off, guide, and seed leave partial paths.](figures/complex-routing-example-1-modes.png)
### Triangulation support
Corridor planning uses Shapely's constrained Delaunay triangulation to keep triangle edges inside free space and respect keepout boundaries. It requires **Shapely 2.1 or later and GEOS 3.10 or later**. On supported platforms a Shapely wheel bundles GEOS. In a pip environment, use `python -m pip install --upgrade "shapely>=2.1"`. A source build needs a compatible system GEOS. [Shapely triangulation reference](https://shapely.readthedocs.io/en/2.1.2/reference/shapely.constrained_delaunay_triangles.html) · [Shapely installation guide](https://shapely.readthedocs.io/en/2.1.2/installation.html)
Check the versions in the environment that runs Inire.
```sh
python -c 'import shapely; print(shapely.__version__, shapely.geos_version_string)'
```
Inire's base dependency permits Shapely 2.0 for lattice routing and constructive plans. With a compatible backend, automatic already uses triangulation whenever it needs corridor search. Here the ordered bundle and turnaround cover all nine nets, so automatic can move directly to verification. Explicit `guide` and `seed` also verify supplied paths without a mesh when `node_limit=0`.
## Compare a guide-mode search ## Compare a guide-mode search
The successful bundle run above reaches verification before the corridor search. To see that search's working model, the figure generator runs `net_08` by itself in guide mode on the same board. The left panel shows the actual triangulation, corridor cells in green, and the guide through them as a dashed line. The right panel zooms in on the expanded positions and physical partial path returned when A* reaches its 12-node budget. [Corridor planning](topological-routing.md#corridor-planning-and-realization) The successful bundle run above reaches verification before the corridor search. To see that search's working model, the figure generator runs `net_08` by itself in guide mode on the same board. The left panel shows the actual triangulation, corridor cells in green, and the guide through them as a dashed line. The right panel zooms in on the expanded positions and physical partial path returned when A* reaches its 12-node budget. [Corridor planning](topological-routing.md#corridor-planning-and-realization)

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

View file

@ -66,7 +66,7 @@ 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. Zero skips search and corridor preparation and allows verification of supplied seeds. |
| `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. |
@ -75,7 +75,7 @@ To read a route's polygons and write them to a test file, follow the [geometry e
| `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"`. Custom polygons for fractional 90-degree bends are positioned relative to the arc center and must include both tangent extensions. | | `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"`. Express a fractional 90-degree bend's polygon relative to the arc center and include both tangent extensions. For an S-bend, specify the first counterclockwise arc relative to its center. The router reflects it for negative offsets, rotates the second half, and extends its outlet face to the grid. |
| `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. The default uses an eight-point proxy for each arc and extends it along any grid tangents. | | `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. The default uses an eight-point proxy for each arc and extends it along any grid tangents. |
| `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

@ -35,9 +35,9 @@ Set `TopologyOptions(mode=...)` and pass it as `topology` in `RoutingOptions`.
### Mode requirements ### Mode requirements
- In guide and seed modes, nets without a corridor can use ordinary lattice search. A caller-supplied seed takes precedence over a generated one. These modes require Shapely 2.1 or later with GEOS 3.10 or later for [constrained triangulation](https://shapely.readthedocs.io/en/2.1.2/reference/shapely.constrained_delaunay_triangles.html). - Guide and seed modes need Shapely 2.1 or later with GEOS 3.10 or later when planning corridors. Nets that receive no corridor can use ordinary lattice search. A caller-supplied seed takes precedence over a generated one. Set `node_limit=0` to verify supplied seeds without planning corridors. [Constrained triangulation requirements](https://shapely.readthedocs.io/en/2.1.2/reference/shapely.constrained_delaunay_triangles.html)
- Use `infer_terminal_headings` with automatic or bundle mode if your ports may change direction and the layout supports bundle planning. Compare fixed and flexible headings in [complex-routing example 1](../../examples/advanced.md#complex-routing-example-1). - Use `infer_terminal_headings` with automatic or bundle mode if your ports may change direction and the layout supports bundle planning. Compare fixed and flexible headings in [complex-routing example 1](../../examples/advanced.md#complex-routing-example-1).
- Automatic mode starts with smaller budgets and can retry with your configured ceiling if coverage remains below the bound. It runs lattice search directly for custom physical bends or polygonal search proxies, or when constrained triangulation is unavailable. - Automatic mode starts with smaller budgets and can retry with your configured ceiling if coverage remains below the bound. It runs lattice search directly for custom physical bends or polygonal search proxies. With no triangulation available, it tries the constructive planners before falling back to lattice search. [Example with all five modes](../complex-routing-example-1.md#compare-all-routing-modes)
## Choose the next setting ## Choose the next setting

View file

@ -149,9 +149,6 @@ class RoutingWorld:
def _ensure_static_tree(self) -> None: def _ensure_static_tree(self) -> None:
self._static_obstacles.ensure_tree() self._static_obstacles.ensure_tree()
def _ensure_net_static_tree(self, net_width: float) -> STRtree:
return self._static_obstacles.ensure_net_tree(net_width)
def _ensure_static_raw_tree(self) -> None: def _ensure_static_raw_tree(self) -> None:
self._static_obstacles.ensure_raw_tree() self._static_obstacles.ensure_raw_tree()
@ -200,32 +197,13 @@ class RoutingWorld:
) )
return reach < length - 0.001 return reach < length - 0.001
def _is_in_safety_zone_fast(self, idx: int, start_port: Port | None, end_port: Port | None) -> bool:
bounds_array = self._static_obstacles.bounds_array
if bounds_array is None:
return False
bounds = bounds_array[idx]
safety_zone = self.safety_zone_radius
if (
start_port
and bounds[0] - safety_zone <= start_port.x <= bounds[2] + safety_zone
and bounds[1] - safety_zone <= start_port.y <= bounds[3] + safety_zone
):
return True
return bool(
end_port
and bounds[0] - safety_zone <= end_port.x <= bounds[2] + safety_zone
and bounds[1] - safety_zone <= end_port.y <= bounds[3] + safety_zone
)
def _is_in_safety_zone( def _is_in_safety_zone(
self, self,
geometry: Polygon, geometry: Polygon,
obj_id: int, raw_obstacle: Polygon,
start_port: Port | None, start_port: Port | None,
end_port: Port | None, end_port: Port | None,
) -> bool: ) -> bool:
raw_obstacle = self._static_obstacles.geometries[obj_id]
safety_zone = self.safety_zone_radius safety_zone = self.safety_zone_radius
obstacle_bounds = raw_obstacle.bounds obstacle_bounds = raw_obstacle.bounds
@ -272,53 +250,20 @@ class RoutingWorld:
start_port: Port | None = None, start_port: Port | None = None,
end_port: Port | None = None, end_port: Port | None = None,
) -> bool: ) -> bool:
# TODO: If static buffering becomes net-width-specific, add dedicated self._ensure_static_raw_tree()
# width-aware geometry/index handling instead of reviving dead args here. tree = self._static_obstacles.raw_tree
static_obstacles = self._static_obstacles if tree is None:
if not static_obstacles.dilated:
return False return False
self._ensure_static_tree() clearance = self.clearance
tree = static_obstacles.tree left, bottom, right, top = result.total_bounds
bounds_array = static_obstacles.bounds_array # Expand the whole proxy envelope, including the tangent faces of an arc.
if tree is None or bounds_array is None: hits = tree.query(box(left - clearance, bottom - clearance, right + clearance, top + clearance))
return False obstacles = tree.geometries
hits = tree.query(box(*result.total_dilated_bounds))
if hits.size == 0:
return False
move_poly_bounds = result.dilated_bounds
for hit_idx in hits: for hit_idx in hits:
obstacle_bounds = bounds_array[hit_idx] obstacle = obstacles[hit_idx]
poly_hits_obstacle_aabb = False for polygon in result.collision_geometry:
for poly_bounds in move_poly_bounds: if _violates_clearance(polygon, obstacle, clearance) and not self._is_in_safety_zone(polygon, obstacle, start_port, end_port):
if (
poly_bounds[0] < obstacle_bounds[2]
and poly_bounds[2] > obstacle_bounds[0]
and poly_bounds[1] < obstacle_bounds[3]
and poly_bounds[3] > obstacle_bounds[1]
):
poly_hits_obstacle_aabb = True
break
if not poly_hits_obstacle_aabb:
continue
obj_id = static_obstacles.obj_ids[hit_idx]
if self._is_in_safety_zone_fast(hit_idx, start_port, end_port):
collision_found = False
for polygon in result.collision_geometry:
if not self._is_in_safety_zone(polygon, obj_id, start_port, end_port):
collision_found = True
break
if collision_found:
return True
continue
static_obstacle = static_obstacles.dilated[obj_id]
for polygon in result.dilated_collision_geometry:
if polygon.intersects(static_obstacle) and not polygon.touches(static_obstacle):
return True return True
return False return False
@ -792,10 +737,7 @@ class RoutingWorld:
min_y, max_y = sorted([origin.y, origin.y + dy]) min_y, max_y = sorted([origin.y, origin.y + dy])
if net_width is not None: if net_width is not None:
tree = self._ensure_net_static_tree(net_width) tree, is_rect_array, bounds_array = static_obstacles.ensure_net_tree(net_width)
key = (round(net_width, 4), round(self.clearance, 4))
is_rect_array = static_obstacles.net_specific_is_rect[key]
bounds_array = static_obstacles.net_specific_bounds[key]
else: else:
self._ensure_static_tree() self._ensure_static_tree()
tree = static_obstacles.tree tree = static_obstacles.tree

View file

@ -6,10 +6,11 @@ from math import ceil, pi
from typing import TYPE_CHECKING, Literal from typing import TYPE_CHECKING, Literal
import numpy import numpy
from shapely import get_parts, snap
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
from shapely.geometry import Polygon, box from shapely.geometry import LineString, Polygon, box
from inire.constants import TOLERANCE_ANGULAR, TOLERANCE_LINEAR from inire.constants import TOLERANCE_ANGULAR, TOLERANCE_LINEAR
from inire.geometry.sbend import sbend_grid_span, sbend_span from inire.geometry.sbend import sbend_grid_span, sbend_span
@ -53,6 +54,14 @@ def _has_port_face(polygon: Polygon, port: Port, *, arrival: bool) -> bool:
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)))
def _shares_face(left: Polygon, right: Polygon) -> bool:
if left.intersection(right).length > TOLERANCE_LINEAR:
return True
# Separately transformed outlines can differ by rounding at the shared edge.
snapped = snap(right, left, TOLERANCE_LINEAR)
return snapped.is_valid and left.intersection(snapped).length > TOLERANCE_LINEAR
def check_path_geometry(path: Sequence[ComponentResult]) -> tuple[bool, bool]: def check_path_geometry(path: Sequence[ComponentResult]) -> tuple[bool, bool]:
"""Return polygon validity and physical continuity for a path.""" """Return polygon validity and physical continuity for a path."""
continuous = all(a.end_port == b.start_port for a, b in pairwise(path)) continuous = all(a.end_port == b.start_port for a, b in pairwise(path))
@ -162,7 +171,7 @@ class ComponentResult:
valid valid
and _has_port_face(shapes[0], self.start_port, arrival=False) and _has_port_face(shapes[0], self.start_port, arrival=False)
and _has_port_face(shapes[-1], self.end_port, arrival=True) 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(_shares_face(a, b) for a, b in pairwise(shapes))
) )
object.__setattr__(self, "_physical_checks", (valid, connected)) object.__setattr__(self, "_physical_checks", (valid, connected))
return valid, connected return valid, connected
@ -349,6 +358,21 @@ def _buffer_geometry(polygons: list[Polygon], dilation: float) -> list[Polygon]:
return [polygon.buffer(dilation) for polygon in polygons] if dilation > 0 else polygons return [polygon.buffer(dilation) for polygon in polygons] if dilation > 0 else polygons
def _extend_custom_sbend_face(outline: Polygon, radius: float, tail: float) -> Polygon:
if tail <= TOLERANCE_LINEAR:
return outline
_, bottom, _, top = outline.bounds
# The first arc's inlet face becomes the second arc's outlet after rotation.
section = outline.intersection(LineString(((0, bottom), (0, top))))
for face in get_parts(section):
_, low, _, high = face.bounds
if low < -radius < high:
extended = outline.union(box(-tail, low, 0, high))
if isinstance(extended, Polygon):
return extended
return outline
class Straight: class Straight:
@staticmethod @staticmethod
def generate( def generate(
@ -552,6 +576,8 @@ class SBend:
c2_local = numpy.array((dx, offset - sign * radius)) c2_local = numpy.array((dx, offset - sign * radius))
c1_xy = (rot2 @ c1_local) + numpy.array((start_port.x, start_port.y)) c1_xy = (rot2 @ c1_local) + numpy.array((start_port.x, start_port.y))
c2_xy = (rot2 @ c2_local) + numpy.array((start_port.x, start_port.y)) c2_xy = (rot2 @ c2_local) + numpy.array((start_port.x, start_port.y))
center1 = (float(c1_xy[0]), float(c1_xy[1]))
center2 = (float(c2_xy[0]), float(c2_xy[1]))
ts1 = (float(start_port.r - sign * 90), float(start_port.r - sign * 90 + sign * theta_deg)) ts1 = (float(start_port.r - sign * 90), float(start_port.r - sign * 90 + sign * theta_deg))
second_base = start_port.r + (90 if sign > 0 else 270) second_base = start_port.r + (90 if sign > 0 else 270)
@ -559,57 +585,26 @@ class SBend:
actual_geometry = SBend._arcs(start_port, rot2, radius, offset, theta, dx, grid_span, width, sagitta) actual_geometry = SBend._arcs(start_port, rot2, radius, offset, theta, dx, grid_span, width, sagitta)
arc1, arc2 = actual_geometry arc1, arc2 = actual_geometry
geometry = [
_apply_collision_model(
arc1,
collision_type,
radius,
width,
(float(c1_xy[0]), float(c1_xy[1])),
ts1,
clip_margin=clip_margin,
rotation_deg=float(start_port.r),
mirror_y=(sign < 0),
)[0],
_apply_collision_model(
arc2,
collision_type,
radius,
width,
(float(c2_xy[0]), float(c2_xy[1])),
ts2,
clip_margin=clip_margin,
rotation_deg=float(start_port.r),
mirror_y=(sign > 0),
tangent_extensions=(0, tail if tail > TOLERANCE_LINEAR else 0),
)[0],
]
if isinstance(physical_geometry_type, Polygon): def outlines(model: BendCollisionModel) -> list[Polygon]:
physical_geometry = [ if model == "arc":
return actual_geometry
if isinstance(model, Polygon):
second = _extend_custom_sbend_face(model, radius, tail)
return [
_transform_custom_collision_polygon(model, center1, float(start_port.r), mirror_y=sign < 0),
_transform_custom_collision_polygon(second, center2, float(start_port.r + 180), mirror_y=sign < 0),
]
return [
_apply_collision_model(arc1, model, radius, width, center1, ts1, clip_margin=clip_margin)[0],
_apply_collision_model( _apply_collision_model(
arc1, arc2, model, radius, width, center2, ts2, clip_margin=clip_margin,
physical_geometry_type, tangent_extensions=(0, tail if tail > TOLERANCE_LINEAR else 0),
radius,
width,
(float(c1_xy[0]), float(c1_xy[1])),
ts1,
rotation_deg=float(start_port.r),
mirror_y=(sign < 0),
)[0],
_apply_collision_model(
arc2,
physical_geometry_type,
radius,
width,
(float(c2_xy[0]), float(c2_xy[1])),
ts2,
rotation_deg=float(start_port.r),
mirror_y=(sign > 0),
)[0], )[0],
] ]
else:
physical_geometry = actual_geometry geometry = outlines(collision_type)
physical_geometry = geometry if physical_geometry_type is collision_type else outlines(physical_geometry_type)
dilated_arcs = actual_geometry dilated_arcs = actual_geometry
if dilation > 0 and (physical_geometry is actual_geometry or collision_type == "arc"): if dilation > 0 and (physical_geometry is actual_geometry or collision_type == "arc"):
if bend_fits_width(radius, width + 2 * dilation): if bend_fits_width(radius, width + 2 * dilation):

View file

@ -28,8 +28,6 @@ class StaticObstacleIndex:
"is_rect_array", "is_rect_array",
"raw_tree", "raw_tree",
"net_specific_trees", "net_specific_trees",
"net_specific_is_rect",
"net_specific_bounds",
"ray_cast_cache", "ray_cast_cache",
"id_counter", "id_counter",
"version", "version",
@ -46,9 +44,7 @@ class StaticObstacleIndex:
self.bounds_array: numpy.ndarray | None = None self.bounds_array: numpy.ndarray | None = None
self.is_rect_array: numpy.ndarray | None = None self.is_rect_array: numpy.ndarray | None = None
self.raw_tree: STRtree | None = None self.raw_tree: STRtree | None = None
self.net_specific_trees: dict[tuple[float, float], STRtree] = {} self.net_specific_trees: dict[tuple[float, float], tuple[STRtree, numpy.ndarray, numpy.ndarray]] = {}
self.net_specific_is_rect: dict[tuple[float, float], numpy.ndarray] = {}
self.net_specific_bounds: dict[tuple[float, float], numpy.ndarray] = {}
self.ray_cast_cache: dict[tuple[float, float, float, float, float | None, float, type, type, type, type], float] = {} self.ray_cast_cache: dict[tuple[float, float, float, float, float | None, float, type, type, type, type], float] = {}
self.id_counter = 0 self.id_counter = 0
self.version = 0 self.version = 0
@ -87,8 +83,6 @@ class StaticObstacleIndex:
self.obj_ids = [] self.obj_ids = []
self.raw_tree = None self.raw_tree = None
self.net_specific_trees.clear() self.net_specific_trees.clear()
self.net_specific_is_rect.clear()
self.net_specific_bounds.clear()
self.ray_cast_cache.clear() self.ray_cast_cache.clear()
self.version += 1 self.version += 1
@ -100,14 +94,15 @@ class StaticObstacleIndex:
self.tree = STRtree(geometries) self.tree = STRtree(geometries)
self.is_rect_array = numpy.array([self.is_rect[i] for i in self.obj_ids]) self.is_rect_array = numpy.array([self.is_rect[i] for i in self.obj_ids])
def ensure_net_tree(self, net_width: float) -> STRtree: def ensure_net_tree(self, net_width: float) -> tuple[STRtree, numpy.ndarray, numpy.ndarray]:
key = (round(net_width, 4), round(self.engine.clearance, 4)) width, clearance = float(net_width), float(self.engine.clearance)
key = (width, clearance)
if key in self.net_specific_trees: if key in self.net_specific_trees:
return self.net_specific_trees[key] return self.net_specific_trees[key]
if self.engine.metrics is not None: if self.engine.metrics is not None:
self.engine.metrics.total_static_net_tree_rebuilds += 1 self.engine.metrics.total_static_net_tree_rebuilds += 1
total_dilation = net_width / 2.0 + self.engine.clearance total_dilation = width / 2.0 + clearance
# A ray grazing the clearance boundary can still place a legal straight. # A ray grazing the clearance boundary can still place a legal straight.
total_dilation -= TOLERANCE_LINEAR * min(1.0, total_dilation) total_dilation -= TOLERANCE_LINEAR * min(1.0, total_dilation)
geometries = [] geometries = []
@ -121,11 +116,9 @@ class StaticObstacleIndex:
bounds_list.append(dilated.bounds) bounds_list.append(dilated.bounds)
is_rect_list.append(is_axis_aligned_rect(dilated)) is_rect_list.append(is_axis_aligned_rect(dilated))
tree = STRtree(geometries) payload = (STRtree(geometries), numpy.array(is_rect_list, dtype=bool), numpy.array(bounds_list, dtype=numpy.float64))
self.net_specific_trees[key] = tree self.net_specific_trees[key] = payload
self.net_specific_is_rect[key] = numpy.array(is_rect_list, dtype=bool) return payload
self.net_specific_bounds[key] = numpy.array(bounds_list, dtype=numpy.float64)
return tree
def ensure_raw_tree(self) -> None: def ensure_raw_tree(self) -> None:
if self.raw_tree is None and self.geometries: if self.raw_tree is None and self.geometries:

View file

@ -41,7 +41,7 @@ from inire.router._routing_policy import (
) )
from inire.router._seed_materialization import materialize_path_seed from inire.router._seed_materialization import materialize_path_seed
from inire.router._stack import route_once from inire.router._stack import route_once
from inire.router._topology import plan_corridors from inire.router._topology import constrained_triangulation_available, plan_corridors
from inire.router.cost import build_native_cost_evaluator, weighted_path_length from inire.router.cost import build_native_cost_evaluator, weighted_path_length
from inire.seeds import SBendSeed from inire.seeds import SBendSeed
@ -607,8 +607,6 @@ class _AutomaticRun:
self._lattice_fallback(trials, options, "No automatic search requested") self._lattice_fallback(trials, options, "No automatic search requested")
elif isinstance(proxy, shapely.Polygon) or physical != "arc": elif isinstance(proxy, shapely.Polygon) or physical != "arc":
self._lattice_fallback(trials, options, "Custom bend geometry uses lattice routing") self._lattice_fallback(trials, options, "Custom bend geometry uses lattice routing")
elif not hasattr(shapely, "constrained_delaunay_triangles") or shapely.geos_version < (3, 10):
self._lattice_fallback(trials, options, "Constrained triangulation is unavailable")
else: else:
with self._time("plan"): with self._time("plan"):
if options.topology.infer_terminal_headings and not self.problem.initial_paths: if options.topology.infer_terminal_headings and not self.problem.initial_paths:
@ -622,7 +620,11 @@ class _AutomaticRun:
if not cut and not conflicts: if not cut and not conflicts:
trials, rejections = self._constructive_trials() trials, rejections = self._constructive_trials()
if not any(trial.selectable for trial in trials) or len(_best_trial(trials).valid_costs) < target: if not any(trial.selectable for trial in trials) or len(_best_trial(trials).valid_costs) < target:
self._search_trials(trials, target) if constrained_triangulation_available():
self._search_trials(trials, target)
else:
worker = replace(options, refinement=replace(options.refinement, enabled=False))
self._lattice_fallback(trials, worker, "Constrained triangulation is unavailable")
self._refine(trials) self._refine(trials)
best = _best_trial(trials) best = _best_trial(trials)
metrics = _sum_route_metrics(self.metrics) metrics = _sum_route_metrics(self.metrics)

View file

@ -310,7 +310,7 @@ class PathFinder:
recent_attempt_work={}, recent_attempt_work={},
pre_pair_candidate=None, pre_pair_candidate=None,
) )
if congestion.max_iterations <= 0: if congestion.max_iterations <= 0 or (self.context.options.search.node_limit <= 0 and self.context.options.topology.mode != "bundle"):
return state return state
self._prepare_topology(state, corridors) self._prepare_topology(state, corridors)
if state.initial_paths is None and congestion.warm_start_enabled: if state.initial_paths is None and congestion.warm_start_enabled:

View file

@ -89,17 +89,20 @@ def _edge(a: int, b: int) -> Edge:
return (a, b) if a < b else (b, a) return (a, b) if a < b else (b, a)
def constrained_triangulation_available() -> bool:
return callable(getattr(shapely, "constrained_delaunay_triangles", None)) and shapely.geos_version >= (3, 10)
class _Mesh: class _Mesh:
def __init__(self, board: Polygon, obstacles: Iterable[Polygon], margin: float, clearance: float) -> None: def __init__(self, board: Polygon, obstacles: Iterable[Polygon], margin: float, clearance: float) -> None:
triangulate = getattr(shapely, "constrained_delaunay_triangles", None) if not constrained_triangulation_available():
if triangulate is None:
raise RuntimeError("Topological routing requires Shapely 2.1 and GEOS 3.10 or newer") raise RuntimeError("Topological routing requires Shapely 2.1 and GEOS 3.10 or newer")
self.pitch = max(1.0, 2 * margin + clearance) self.pitch = max(1.0, 2 * margin + clearance)
obstacles = shapely.union_all([shape.buffer(margin + clearance, join_style="mitre") for shape in obstacles]) obstacles = shapely.union_all([shape.buffer(margin + clearance, join_style="mitre") for shape in obstacles])
self.free = board.buffer(-margin).difference(obstacles) self.free = board.buffer(-margin).difference(obstacles)
self.boundary = self.free.boundary self.boundary = self.free.boundary
self.cells: tuple[Polygon, ...] = tuple(triangulate(self.free).geoms) self.cells: tuple[Polygon, ...] = tuple(shapely.constrained_delaunay_triangles(self.free).geoms)
self.index = shapely.STRtree(self.cells) self.index = shapely.STRtree(self.cells)
self.portals: dict[Edge, _Portal] = {} self.portals: dict[Edge, _Portal] = {}
self.neighbors: list[list[int]] = [[] for _ in self.cells] self.neighbors: list[list[int]] = [[] for _ in self.cells]

View file

@ -1,4 +1,5 @@
import importlib import importlib
from dataclasses import replace
import pytest import pytest
import shapely import shapely
@ -307,6 +308,34 @@ def test_no_iterations_skips_seed_preparation(mode, monkeypatch) -> None:
assert run.metrics.nodes_expanded == run.metrics.warm_start_paths_built == 0 assert run.metrics.nodes_expanded == run.metrics.warm_start_paths_built == 0
@pytest.mark.parametrize("mode", ["guide", "seed"])
def test_zero_search_budget_verifies_seeds_without_triangulation(mode, monkeypatch) -> None:
monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False)
net = NetSpec("line", Port(10, 50, 0), Port(90, 50, 0))
problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"line": PathSeed((StraightSeed(80),))})
options = RoutingOptions(
search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=1), topology=TopologyOptions(mode=mode),
)
run = route(problem, options=options)
assert run.results_by_net["line"].is_valid
assert run.metrics.nodes_expanded == 0
def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(monkeypatch) -> None:
monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False)
net = NetSpec("line", Port(10, 50, 0), Port(90, 50, 0))
problem = RoutingProblem((0, 0, 100, 100), (net,))
options = RoutingOptions(search=SearchOptions(bend_radii=(), sbend_radii=()), refinement=RefinementOptions(enabled=False))
run = route(problem, options=options)
assert run.results_by_net["line"].is_valid
assert run.automatic is not None
assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback"
def test_automatic_final_conflict_trace_includes_direct_locks() -> None: def test_automatic_final_conflict_trace_includes_direct_locks() -> None:
problem = RoutingProblem( problem = RoutingProblem(
(0, 0, 100, 100), (0, 0, 100, 100),
@ -407,6 +436,37 @@ def test_lattice_straight_can_run_along_a_keepout_at_clearance(y, gap, valid) ->
assert route(problem, options=options).results_by_net["straight"].is_valid is valid assert route(problem, options=options).results_by_net["straight"].is_valid is valid
def test_close_net_widths_use_distinct_keepout_trees() -> None:
narrow = NetSpec("narrow", Port(10, 20, 0), Port(90, 20, 0), width=2.00001)
wide = NetSpec("wide", Port(10, 60, 0), Port(90, 60, 0), width=2.00004)
problem = RoutingProblem((0, 0, 100, 100), (narrow, wide), (box(28, 21.00001, 75, 31),), clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=()),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode="off"),
)
for candidate in (problem, replace(problem, nets=(wide, narrow))):
run = route(candidate, options=options)
assert all(result.is_valid for result in run.results_by_net.values())
assert run.metrics.static_net_tree_rebuilds == 2
def test_lattice_can_find_a_bend_with_diagonal_clearance_at_its_port() -> None:
net = NetSpec("turn", Port(20, 20, 0), Port(30, 30, 90))
problem = RoutingProblem((0, 0, 100, 100), (net,), (box(16, 14, 19.25, 17.125),), clearance=2)
options = RoutingOptions(
search=SearchOptions(node_limit=100, bend_radii=(10,), sbend_radii=()),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
topology=TopologyOptions(mode="off"),
)
result = route(problem, options=options).results_by_net["turn"]
assert result.is_valid
assert result.as_seed() == PathSeed((Bend90Seed(10, "CCW"),))
@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) @pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"])
def test_fractional_quarter_turn_reaches_its_terminal_face(mode) -> None: 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)),)) problem = RoutingProblem((0, 0, 100, 100), nets=(NetSpec("bend", Port(20, 20, 0), Port(31, 31, 90)),))

View file

@ -7,7 +7,7 @@ from shapely.geometry import Polygon, box
import inire.geometry.collision as collision_module import inire.geometry.collision as collision_module
import inire.geometry.component_overlap as overlap_module import inire.geometry.component_overlap as overlap_module
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
from inire.geometry.components import ComponentResult from inire.geometry.components import Bend90, ComponentResult
from inire.geometry.components import Straight from inire.geometry.components import Straight
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.router._astar_types import AStarMetrics from inire.router._astar_types import AStarMetrics
@ -161,6 +161,16 @@ def test_check_move_static_clearance() -> None:
assert not engine.check_move_static(res_exact, start_port=start_exact) assert not engine.check_move_static(res_exact, start_port=start_exact)
def test_static_bend_query_checks_clearance_beyond_its_tangent_face() -> None:
engine = RoutingWorld(clearance=2)
bend = Bend90.generate(Port(20, 20, 0), 10, 2, "CCW", dilation=1)
obstacle = box(16, 18.6, 18.25, 18.9)
assert bend.physical_geometry[0].distance(obstacle) < 2
engine.add_static_obstacle(obstacle)
assert engine.check_move_static(bend, start_port=bend.start_port, end_port=bend.end_port)
def test_verify_path_report_uses_physical_distance_at_a_mitred_corner() -> None: def test_verify_path_report_uses_physical_distance_at_a_mitred_corner() -> None:
engine = RoutingWorld(clearance=2.0) engine = RoutingWorld(clearance=2.0)
path = (Straight.generate(Port(0, 0, 0), 20.0, width=2.0),) path = (Straight.generate(Port(0, 0, 0), 20.0, width=2.0),)

View file

@ -227,6 +227,22 @@ def test_arc_proxy_dilation_uses_the_circular_geometry(kind, dilation) -> None:
assert custom.dilated_physical_geometry != custom.dilated_collision_geometry assert custom.dilated_physical_geometry != custom.dilated_collision_geometry
@pytest.mark.parametrize("heading", [0, 90, 180, 270])
@pytest.mark.parametrize(("radius", "offset"), [(50, 40), (50, -40), (12.25, 11), (12.25, -11)])
def test_custom_sbend_uses_reflected_arc_and_reaches_grid_face(heading, radius, offset) -> None:
template = SBend.generate(Port(0, 0, 0), abs(offset), radius, 2).physical_geometry[0]
outline = shapely_translate(template, 0, -radius)
start = Port(30, 50, heading)
expected = SBend.generate(start, offset, radius, 2)
result = SBend.generate(start, offset, radius, 2, collision_type=outline, physical_geometry_type=outline, dilation=1)
assert result.physical_checks == (True, True)
assert result.end_port == expected.end_port
assert result.collision_geometry == result.physical_geometry
for actual, arc in zip(result.physical_geometry, expected.physical_geometry, strict=True):
assert actual.symmetric_difference(arc).area < 1e-10
def test_sbend_collision_models() -> None: def test_sbend_collision_models() -> None:
start = Port(0, 0, 0) start = Port(0, 0, 0)
offset = 5.0 offset = 5.0

View file

@ -203,8 +203,8 @@ def test_automatic_constructs_an_exact_sbend_grid() -> None:
def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None: def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None:
case = next(case for case in CROSSING_BENCHMARK_CASES if case.name == "crossing-staggered-grid") case = next(case for case in CROSSING_BENCHMARK_CASES if case.name == "crossing-staggered-grid")
first, *others = case.problem.nets first, *others = case.problem.nets
# An odd shift has no exact forward span at this radius, so use guide search. # A 22-unit shift leaves a net unresolved after the early guide and exercises the retry.
problem = replace(case.problem, nets=(replace(first, target=first.target.translate(dy=1)), *others)) problem = replace(case.problem, nets=(replace(first, target=first.target.translate(dy=2)), *others))
options = replace( options = replace(
case.options, case.options,
search=replace(case.options.search, node_limit=101), search=replace(case.options.search, node_limit=101),
@ -217,6 +217,7 @@ def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None:
assert report is not None assert report is not None
guided = [stage for stage in report.stages if stage.operation == "search" and stage.mode == "guide"] guided = [stage for stage in report.stages if stage.operation == "search" and stage.mode == "guide"]
assert [(stage.policy, stage.node_limit) for stage in guided] == [("early-guide", 101), ("direct-probe-near-port", 100)] assert [(stage.policy, stage.node_limit) for stage in guided] == [("early-guide", 101), ("direct-probe-near-port", 100)]
assert len(guided[0].valid_net_ids) < len(problem.nets)
def test_automatic_times_planning_search_verification_and_refinement() -> None: def test_automatic_times_planning_search_verification_and_refinement() -> None:

View file

@ -2,6 +2,7 @@ from dataclasses import replace
from itertools import combinations, pairwise from itertools import combinations, pairwise
import pytest import pytest
import shapely
from shapely import union_all from shapely import union_all
from shapely.affinity import translate from shapely.affinity import translate
from shapely.geometry import box from shapely.geometry import box
@ -131,3 +132,20 @@ def test_bundle_preserves_explicit_terminal_headings_by_default() -> None:
options = replace(terminal_bench_options(), topology=TopologyOptions(mode="bundle")) options = replace(terminal_bench_options(), topology=TopologyOptions(mode="bundle"))
with pytest.raises(ValueError, match="arrival heading 180 for net_08"): with pytest.raises(ValueError, match="arrival heading 180 for net_08"):
route(terminal_bench_problem(), options=options) route(terminal_bench_problem(), options=options)
@pytest.mark.parametrize("unsupported", ["missing-function", "old-geos"])
def test_automatic_constructs_bundle_without_triangulation(unsupported, monkeypatch) -> None:
if unsupported == "missing-function":
monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False)
else:
monkeypatch.setattr(shapely, "geos_version", (3, 9, 0))
base = terminal_bench_options(node_limit=100, max_iterations=1)
options = replace(base, topology=TopologyOptions(infer_terminal_headings=True))
run = route(terminal_bench_problem(), options=options)
assert run.automatic is not None
assert len(run.automatic.verified_net_ids) == 9
assert run.metrics.nodes_expanded == 0
assert run.results_by_net["net_08"].path[-1].end_port.r == 180

View file

@ -20,7 +20,7 @@ from inire.geometry.intervals import open_intervals
from inire.router._bundle import _identify_layout, plan_ordered_bundle from inire.router._bundle import _identify_layout, plan_ordered_bundle
from inire.router._seed_materialization import materialize_path_seed from inire.router._seed_materialization import materialize_path_seed
from inire.router._stack import route_once from inire.router._stack import route_once
from inire.router._topology import _build_corridors, _endpoint_access, _Mesh, _plan_lane_assignments from inire.router._topology import _build_corridors, _endpoint_access, _Mesh, _plan_lane_assignments, constrained_triangulation_available
from inire.router._waypoints import export_waypoints from inire.router._waypoints import export_waypoints
from scripts.render_documentation_figures import EDGE, INK, MUTED, _board, _polygon, _save, plt from scripts.render_documentation_figures import EDGE, INK, MUTED, _board, _polygon, _save, plt
@ -221,6 +221,44 @@ def _guide_figure(directory: Path, problem: RoutingProblem, options: RoutingOpti
_save(fig, directory, f"{COMPLEX_EXAMPLE}-guide.png") _save(fig, directory, f"{COMPLEX_EXAMPLE}-guide.png")
def _modes_figure(directory: Path, problem: RoutingProblem, options: RoutingOptions, *, triangulation: bool) -> None:
config = replace(
options,
search=replace(options.search, node_limit=100),
congestion=replace(options.congestion, max_iterations=1, warm_start_enabled=False),
refinement=replace(options.refinement, enabled=False),
)
modes = ("automatic", "off", "guide", "seed", "bundle")
fig, panels = plt.subplots(3, 2, figsize=(10, 7), layout="constrained")
fig.suptitle("One congestion iteration · 100 nodes per search", color=INK, fontsize=13)
for ax, mode in zip(panels.ravel()[:-1], modes, strict=True):
if mode in ("guide", "seed") and not triangulation:
ax.set_title(mode, loc="left", color=INK, fontsize=11)
ax.text(0.5, 0.5, "Requires constrained triangulation", color=MUTED, ha="center", transform=ax.transAxes)
ax.set_axis_off()
continue
settings = replace(config, topology=replace(config.topology, mode=mode, infer_terminal_headings=mode == "bundle"))
run = route(problem, options=settings)
verified = sum(result.is_valid for result in run.results_by_net.values())
label = "bundle with heading inference" if mode == "bundle" else mode
_board(ax, problem)
ax.set_title(f"{label} · {verified}/{len(problem.nets)} verified", loc="left", color=INK, fontsize=11)
for net in problem.nets:
_draw_ports(ax, net.start, net.target, EDGE, arrow_length=0)
result = run.results_by_net[net.net_id]
if result.path:
_footprint(ax, result.path, UPPER if result.is_valid else RETURN, dashed=not result.is_valid)
legend = panels.flat[-1]
legend.set_axis_off()
handles = [
Line2D([], [], color=UPPER, label="Verified path"),
Line2D([], [], color=RETURN, linestyle="--", label="Unverified or partial path"),
]
legend.legend(handles=handles, loc="center left", frameon=False, fontsize=10)
_save(fig, directory, f"{COMPLEX_EXAMPLE}-modes.png")
def main() -> None: def main() -> None:
parser = ArgumentParser(description=__doc__) parser = ArgumentParser(description=__doc__)
parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parents[1] / "docs" / "figures") parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parents[1] / "docs" / "figures")
@ -249,7 +287,10 @@ def main() -> None:
_turnaround_figure(directory, problem, proposed_paths, paths) _turnaround_figure(directory, problem, proposed_paths, paths)
_verify_figure(directory, problem, paths, colors) _verify_figure(directory, problem, paths, colors)
_refine_figure(directory, problem, paths, _result_paths(refined)) _refine_figure(directory, problem, paths, _result_paths(refined))
_guide_figure(directory, problem, options) triangulation = constrained_triangulation_available()
if triangulation:
_guide_figure(directory, problem, options)
_modes_figure(directory, problem, options, triangulation=triangulation)
print(f"{COMPLEX_EXAMPLE}: {len(problem.nets)}/{len(problem.nets)} verified, {refined.metrics.nodes_expanded} A* expansions") print(f"{COMPLEX_EXAMPLE}: {len(problem.nets)}/{len(problem.nets)} verified, {refined.metrics.nodes_expanded} A* expansions")