Use physical clearance for fixed routes and terminal bounds

Use the same physical clearance rule for fixed-route admission and verification. Preserve imported vertices while clearing GEOS precision metadata. Count touching terminal faces as conflicts at zero clearance.
This commit is contained in:
Jan Petykiewicz 2026-11-29 16:36:54 -08:00
commit 23d0a140c1
10 changed files with 127 additions and 28 deletions

View file

@ -10,7 +10,7 @@ Follow one complete run from board input through planning, verification, and plo
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 aligned terminal faces that violate clearance can supply at most one route. At zero clearance, faces that touch also conflict. 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#L28).
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.
3. **Start with a small search budget.** Lock verified straight links and search for the remaining nets. A different lock order or a small unlocked probe can free room for a turn. Promising guide and column attempts can run first.
4. **Decide what to keep fixed.** If the remaining ports are connected, route around the locked geometry. If the locks disconnect them, pass the previously verified paths as seeds that can move. A joint retry can assign different lanes through a shared opening. If recovery stalls, seed and lattice attempts can search the whole layout. The final lattice retry can use the caller's full node limit.
@ -36,7 +36,7 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati
## Geometry and refinement
A result carries the requested and effective net specs. The effective net records the resolved ports for replaying the move sequence after heading inference. Fixed routes carry their owner and physical polygons into the same collision world used by search and verification. The world applies distinct-net clearance to fixed geometry, and planners see fixed routes alongside keepouts. [Placement recipes](user/route-a-layout.md#save-a-placement-recipe)
A result carries the requested and effective net specs. The effective net records the resolved ports for replaying the move sequence after heading inference. Fixed routes carry their owner and physical polygons into the same collision world used by search and verification. The world applies distinct-net clearance to fixed geometry, and planners see fixed routes alongside keepouts. Routing preserves the vertices of imported polygons and clears their GEOS precision metadata so geometric operations use full coordinate precision. [Placement recipes](user/route-a-layout.md#save-a-placement-recipe)
Search, seed replay, and refinement share analytic endpoint and circular sampling calculations. Preparation rejects oversized sampling requests before allocating the outline. Verification uses the materialized polygons for exact containment and clearance.

View file

@ -25,12 +25,12 @@ 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. |
| `nets` | `()` | Sequence of `NetSpec` objects with unique IDs. Duplicate IDs raise `ValueError`. |
| `static_obstacles` | `()` | Valid, nonempty Shapely `Polygon` objects that define keepouts. |
| `static_obstacles` | `()` | Valid, nonempty Shapely `Polygon` objects in board coordinates that define routing keepouts. Coordinates may be fractional. |
| `initial_paths` | Empty mapping | A read-only snapshot of net IDs mapped to `PathSeed` objects. Supply a new mapping to change seeds. |
| `clearance` | `2.0` | Finite, nonnegative spacing required between distinct nets and between a net and a keepout. At zero clearance, distinct nets must still be disjoint, including at vertices. Boundary contact with a keepout is allowed. |
| `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 keepout intersections at a move's endpoints during search. |
| `self_clearance` | `0.0` | Optional spacing within one net. Applies between components when the intervening centerline is at least this long. Adjacent joins and components immediately on either side of one bend are exempt. Unintended contact is always checked. |
| `fixed_routes` | `()` | Completed or imported net geometry supplied as `FixedRoute(net_id, polygons)`. IDs must be unique across fixed and active nets. |
| `fixed_routes` | `()` | Completed or imported net geometry supplied as `FixedRoute(net_id, polygons)`. Search and verification check clearance to fixed routes using the physical outlines. IDs must be unique across fixed and active nets. |
## Path seeds

View file

@ -10,7 +10,7 @@ from inire.constants import TOLERANCE_LINEAR
from inire.geometry.component_overlap import count_path_self_collisions
from inire.geometry.components import check_path_geometry, path_within_board
from inire.geometry.dynamic_path_index import DynamicPathIndex
from inire.geometry.index_helpers import grid_cell_span
from inire.geometry.index_helpers import floating_polygon, grid_cell_span
from inire.geometry.primitives import rotate_cardinal
from inire.results import RoutingReport
from inire.geometry.static_obstacle_index import StaticObstacleIndex
@ -52,11 +52,14 @@ def _has_non_touching_overlap(left: BaseGeometry, right: BaseGeometry) -> bool:
return left.intersects(right) and not left.touches(right)
def _clearance_limit(clearance: float) -> float:
return clearance - TOLERANCE_LINEAR * min(1.0, clearance)
def _violates_clearance(left: BaseGeometry, right: BaseGeometry, clearance: float) -> bool:
if clearance <= 0:
return _has_non_touching_overlap(left, right)
tolerance = TOLERANCE_LINEAR * min(1.0, clearance)
return left.distance(right) < clearance - tolerance
return left.distance(right) < _clearance_limit(clearance)
def _violates_net_clearance(left: BaseGeometry, right: BaseGeometry, clearance: float) -> bool:
@ -118,7 +121,7 @@ class RoutingWorld:
self.clearance = clearance
self.self_clearance = self_clearance
self.safety_zone_radius = safety_zone_radius
self.board = board
self.board = floating_polygon(board) if board is not None else None
self.grid_cell_size = 50.0
self.metrics = None
@ -308,17 +311,16 @@ class RoutingWorld:
clearance = self.clearance
left, bottom, right, top = result.total_bounds
reserved = not self.clearance and self._static_obstacles.owners
if reserved:
if self._static_obstacles.owners:
x0, y0, x1, y1 = result.total_physical_bounds
left, bottom, right, top = min(left, x0), min(bottom, y0), max(right, x1), max(top, y1)
# Expand the whole proxy envelope, including the tangent faces of an arc.
# The broad phase must include both the keepout proxy and the physical outline.
hits = tree.query(box(left - clearance, bottom - clearance, right + clearance, top + clearance))
obstacles = tree.geometries
for hit_idx in hits:
obstacle = obstacles[hit_idx]
if reserved and self._static_obstacles.raw_owners[hit_idx] is not None:
if any(polygon.intersects(obstacle) for polygon in result.physical_geometry):
if self._static_obstacles.raw_owners[hit_idx] is not None:
if any(_violates_net_clearance(polygon, obstacle, clearance) for polygon in result.physical_geometry):
return True
continue
for polygon in result.collision_geometry:

View file

@ -4,12 +4,21 @@ import math
from typing import TYPE_CHECKING
import numpy
from shapely import get_precision, set_precision
if TYPE_CHECKING:
from collections.abc import Iterator, Mapping
from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
def floating_polygon(polygon: Polygon) -> Polygon:
"""Clear the GEOS precision model without moving any vertices."""
if get_precision(polygon):
return set_precision(polygon, 0, mode="pointwise")
return polygon
def build_index_payload(
geometries: Mapping[int, BaseGeometry],
) -> tuple[list[int], list[BaseGeometry], numpy.ndarray]:

View file

@ -7,7 +7,7 @@ import rtree
from shapely.strtree import STRtree
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.index_helpers import build_index_payload, is_axis_aligned_rect
from inire.geometry.index_helpers import build_index_payload, floating_polygon, is_axis_aligned_rect
if TYPE_CHECKING:
from shapely.geometry import Polygon
@ -57,8 +57,9 @@ class StaticObstacleIndex:
obj_id = self.id_counter
self.id_counter += 1
polygon = floating_polygon(polygon)
if dilated_geometry is not None:
dilated = dilated_geometry
dilated = floating_polygon(dilated_geometry)
else:
dilated = polygon.buffer(self.engine.clearance / 2.0, join_style="mitre")

View file

@ -10,6 +10,7 @@ from shapely.geometry import Polygon
from inire._snapshot import snapshot
from inire.geometry.components import _has_port_face, bend_fits_width
from inire.geometry.index_helpers import floating_polygon
from inire.geometry.primitives import Port
from inire.geometry.sbend import sbend_grid_span
from inire.seeds import Bend90Seed, PathSeed, SBendSeed
@ -305,7 +306,7 @@ class FixedRoute:
polygons = tuple(self.polygons)
if not polygons or any(not isinstance(shape, Polygon) or shape.is_empty or not shape.is_valid for shape in polygons):
raise ValueError("Fixed routes require nonempty, valid Polygon geometry")
object.__setattr__(self, "polygons", polygons)
object.__setattr__(self, "polygons", tuple(floating_polygon(polygon) for polygon in polygons))
@classmethod
def from_result(cls, result: RoutingResult) -> FixedRoute:
@ -358,7 +359,7 @@ class RoutingProblem:
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)
object.__setattr__(self, "static_obstacles", tuple(floating_polygon(obstacle) for obstacle in obstacles))
initial_paths = snapshot(self.initial_paths)
if any(not isinstance(seed, PathSeed) for seed in initial_paths.values()):
raise TypeError("RoutingProblem.initial_paths values must be PathSeed instances")

View file

@ -10,6 +10,7 @@ from shapely.geometry import box
from shapely.strtree import STRtree
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.collision import _clearance_limit
from inire.geometry.intervals import open_intervals
from inire.model import resolve_bend_geometry
from inire.results import CapacityLimit
@ -63,35 +64,41 @@ def cut_capacity(problem: RoutingProblem, options: RoutingOptions) -> CapacityLi
def port_conflicts(problem: RoutingProblem, options: RoutingOptions) -> tuple[tuple[str, str], ...]:
"""Find disjoint fixed-heading terminal pairs with insufficient optical clearance."""
_, physical_geometry = resolve_bend_geometry(options.search)
if physical_geometry != "arc" or problem.clearance <= TOLERANCE_LINEAR:
if physical_geometry != "arc":
return ()
aligned: dict[tuple[int, int], list[tuple[str, float, float]]] = {}
for net in problem.nets:
half_width = net.width / 2
for port in (net.start, net.target):
axis = port.r % 180
longitudinal, lateral = (port.x, port.y) if axis == 0 else (port.y, port.x)
aligned.setdefault((axis, longitudinal), []).append((net.net_id, lateral, net.width))
aligned.setdefault((axis, longitudinal), []).append((net.net_id, lateral - half_width, lateral + half_width))
# Each disjoint conflict pair forces at least one route to be omitted.
# A terminal's physical cross-section is fixed by its heading and width.
pairs = []
matched = set()
separation = problem.clearance - TOLERANCE_LINEAR
for bank in aligned.values():
ports = [port for port in bank if port[0] not in matched]
if len(ports) < 2:
continue
pairs.extend(_match_bank(ports, separation, matched))
pairs.extend(_match_bank(ports, problem.clearance, matched))
return tuple(pairs)
def _match_bank(ports: list[tuple[str, float, float]], separation: float, matched: set[str]) -> list[tuple[str, str]]:
spans = [box(y - (width + separation) / 2, 0, y + (width + separation) / 2, 1) for _, y, width in ports]
def _match_bank(ports: list[tuple[str, float, float]], clearance: float, matched: set[str]) -> list[tuple[str, str]]:
separation = _clearance_limit(clearance)
padding = separation / 2
spans = [box(low - padding, 0, high + padding, 1) for _, low, high in ports]
index = STRtree(spans)
def conflicts(i: int, j: int) -> bool:
a, y1, w1 = ports[i]
b, y2, w2 = ports[j]
return a != b and b not in matched and abs(y1 - y2) - (w1 + w2) / 2 < separation
a, low_a, high_a = ports[i]
b, low_b, high_b = ports[j]
if a == b or b in matched:
return False
gap = max(low_a, low_b) - min(high_a, high_b)
# Distinct conductors cannot share a point even at zero clearance.
return gap < separation if clearance else gap <= 0
pairs = []
for i, (a, _, _) in enumerate(ports):

View file

@ -1,7 +1,9 @@
from dataclasses import replace
import pytest
from shapely.geometry import Polygon
from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.router._capacity import cut_capacity, port_conflicts
from inire.tests.routing_corpus import CASE_GROUPS
@ -23,3 +25,29 @@ def test_fixed_port_conflicts_are_disjoint_and_depend_on_clearance() -> None:
assert len(case.problem.nets) - len(pairs) == case.routing_bound
assert len({net_id for pair in pairs for net_id in pair}) == 2 * len(pairs)
assert port_conflicts(replace(case.problem, clearance=0), case.options) == ()
@pytest.mark.parametrize("heading", [0, 90])
@pytest.mark.parametrize(
("clearance", "second_width", "conflict"),
[(0, 1.5, False), (0, 2, True), (0, 2.5, True), (1e-7, 2 - 1e-7, True), (0.25, 1.5, False)],
ids=["positive-gap", "touching", "overlapping", "tiny-clearance", "exact-clearance"],
)
def test_automatic_bound_matches_terminal_face_clearance(heading, clearance, second_width, conflict) -> None:
nets = tuple(
NetSpec(net_id, Port(10, y, 0).rotated(heading, (50, 50)), Port(90, y, 0).rotated(heading, (50, 50)), width)
for net_id, y, width in (("a", 20, 2), ("clear", 40, 2), ("b", 22, second_width))
)
problem = RoutingProblem((0, 0, 100, 100), nets, clearance=clearance)
options = RoutingOptions(
search=SearchOptions(node_limit=20, bend_radii=(), sbend_radii=()),
congestion=CongestionOptions(max_iterations=1),
refinement=RefinementOptions(enabled=False),
)
run = route(problem, options=options)
assert run.automatic is not None
assert run.automatic.port_conflicts == ((("a", "b"),) if conflict else ())
assert run.automatic.max_routed == len(nets) - int(conflict)
assert len(run.automatic.verified_net_ids) <= run.automatic.max_routed

View file

@ -2,6 +2,7 @@ from dataclasses import replace
import numpy
import pytest
from shapely import get_precision, set_precision
from shapely.geometry import Polygon, box
import inire.geometry.collision as collision_module
@ -139,6 +140,18 @@ def test_ray_cast_cache_has_a_fixed_capacity(monkeypatch: pytest.MonkeyPatch) ->
assert len(engine._static_obstacles.ray_cast_cache) <= 2
def test_static_index_ignores_precision_metadata_on_direct_import() -> None:
obstacle = set_precision(box(10, 10, 20, 20), 1, mode="pointwise")
world = RoutingWorld(clearance=.25)
world.add_static_obstacle(obstacle)
indexed, = world.iter_static_geometries()
assert indexed.equals_exact(obstacle, 0)
assert get_precision(indexed) == 0
move = Straight.generate(Port(5, 9, 0), 20, 2)
assert world.verify_path_report("track", (move,)).static_collision_count == 1
def test_check_move_static_clearance() -> None:
engine = RoutingWorld(clearance=2.0)
_install_static_straight(engine, Port(10, 50, 0), 10.0, width=100.0, dilation=1.0)

View file

@ -3,7 +3,7 @@ from copy import deepcopy
from dataclasses import replace
import pytest
from shapely import union_all
from shapely import set_precision, union_all
from shapely.geometry import box
from inire import (
@ -73,6 +73,44 @@ def test_fixed_route_from_result_preserves_polygon_and_owner() -> None:
replace(problem, fixed_routes=(fixed,))
@pytest.mark.parametrize("fixed_bounds", [(23.9, 15.6, 24.4, 16.1), (25.15, 14.75, 25.25, 14.85)], ids=["overlap", "insufficient-gap"])
def test_lattice_bend_admission_checks_physical_clearance_to_fixed_route(fixed_bounds) -> None:
net = NetSpec("active", Port(10, 10, 0), Port(30, 30, 90))
fixed = FixedRoute("locked", (box(*fixed_bounds),))
problem = RoutingProblem((0, 0, 50, 50), (net,), clearance=1, fixed_routes=(fixed,))
options = RoutingOptions(
search=SearchOptions(node_limit=50, bend_radii=(10, 20), sbend_radii=(), bend_proxy_geometry="clipped_bbox", bend_clip_margin=9),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
result = route(problem, options=options).results_by_net[net.net_id]
assert result.is_valid
assert result.as_seed() == PathSeed((StraightSeed(10), Bend90Seed(10, "CCW"), StraightSeed(10)))
@pytest.mark.parametrize("fixed", [False, True], ids=["keepout", "fixed-net"])
@pytest.mark.parametrize(("clearance", "valid"), [(0.25, True), (0.5, False)])
def test_imported_polygon_precision_preserves_fractional_clearance(fixed, clearance, valid) -> None:
net = NetSpec("signal", Port(10, 20, 0), Port(90, 20, 0), 1.5)
obstacle = box(20, 21, 30, 24)
problem = RoutingProblem(
(0, 0, 100, 50), (net,), initial_paths={net.net_id: PathSeed((StraightSeed(80),))}, clearance=clearance,
)
reports = []
for polygon in (obstacle, set_precision(obstacle, 1, mode="pointwise")):
with_obstacle = replace(problem, fixed_routes=(FixedRoute("existing", (polygon,)),)) if fixed else replace(
problem, static_obstacles=(polygon,),
)
result = route(with_obstacle, options=_REPLAY).results_by_net[net.net_id]
assert result.is_valid is valid
assert result.locked_geometry[0].bounds == (10, 19.25, 90, 20.75)
reports.append(result.report)
assert reports[0] == reports[1]
@pytest.mark.parametrize(("pitch", "valid"), [(28000, False), (32000, False), (36000, True)])
def test_cpw_envelope_clearance_and_signal_recipe_replay(pitch, valid) -> None:
nets = tuple(NetSpec(f"cpw{i}", Port(10000, 30000 + i * pitch, 0), Port(210000, 30000 + i * pitch, 0), 29500)