Choose eligible radii for constructive routing plans

This commit is contained in:
Jan Petykiewicz 2026-11-30 11:23:55 -08:00
commit 6c5ee351c8
6 changed files with 124 additions and 34 deletions

View file

@ -220,17 +220,17 @@ def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer
if not problem.nets: if not problem.nets:
return problem return problem
_, physical_geometry = resolve_bend_geometry(search) _, physical_geometry = resolve_bend_geometry(search)
bend = min(search.bend_radii, default=0.0) common_radii = {r for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r) and r in search.sbend_radii}
if ( if (
not isfinite(bend) or bend <= 0 or bend != int(bend) or bend not in search.sbend_radii not common_radii or physical_geometry != "arc"
or physical_geometry != "arc"
or search.has_applicable_sbend_outline(net.width for net in problem.nets) or search.has_applicable_sbend_outline(net.width for net in problem.nets)
): ):
raise ValueError("Bundle routing needs a common integer radius for circular bends and S-bends") raise ValueError("Bundle routing needs a common integer radius for circular bends and S-bends")
radius = int(bend)
width = problem.nets[0].width width = problem.nets[0].width
if not bend_fits_width(radius, width): bend = min((r for r in common_radii if bend_fits_width(r, width)), default=0.0)
if not bend:
raise ValueError("Bundle bend radius must be at least half the net width") raise ValueError("Bundle bend radius must be at least half the net width")
radius = int(bend)
margin = width / 2 + problem.clearance margin = width / 2 + problem.clearance
pitch = ceil(width + problem.clearance) + 1 pitch = ceil(width + problem.clearance) + 1
floor_lane = ceil(problem.bounds[1] + width / 2) floor_lane = ceil(problem.bounds[1] + width / 2)

View file

@ -12,6 +12,7 @@ from typing import TYPE_CHECKING
from shapely.geometry import LineString from shapely.geometry import LineString
from inire.geometry.components import bend_fits_width
from inire.geometry.intervals import Gap, open_intervals from inire.geometry.intervals import Gap, open_intervals
from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans
from inire.model import resolve_bend_geometry from inire.model import resolve_bend_geometry
@ -414,6 +415,7 @@ def _schedules(
spans, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, spans, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets,
) )
needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths)) needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths))
straight_tracks = tuple(i for i, width in enumerate(widths) if not bend_fits_width(radius, width))
# The track order allows a local check of each neighboring pair. The # The track order allows a local check of each neighboring pair. The
# final router still verifies the exact arcs and every pair of routes. # final router still verifies the exact arcs and every pair of routes.
@ -442,6 +444,8 @@ def _schedules(
scores = [] scores = []
for previous, histories in approaches.items(): for previous, histories in approaches.items():
offsets = tuple(b - a for a, b in zip(previous, row, strict=True)) offsets = tuple(b - a for a, b in zip(previous, row, strict=True))
if straight_tracks and any(offsets[i] for i in straight_tracks):
continue
sequences = [choose(d, window - 4) for d in offsets] sequences = [choose(d, window - 4) for d in offsets]
if any(sequence is None for sequence in sequences): if any(sequence is None for sequence in sequences):
continue continue
@ -564,22 +568,27 @@ def column_seed_candidates(
) -> Iterator[dict[str, PathSeed]]: ) -> Iterator[dict[str, PathSeed]]:
"""Yield candidate routes from configured circular bends and problem geometry.""" """Yield candidate routes from configured circular bends and problem geometry."""
_, physical_geometry = resolve_bend_geometry(search) _, physical_geometry = resolve_bend_geometry(search)
bend = min(search.sbend_radii, default=0.0) if problem.initial_paths or physical_geometry != "arc":
if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend): return
radii = sorted({int(r) for r in search.sbend_radii if isfinite(r) and r > 0 and r == int(r)})
if not radii:
return return
layout = _column_layout(problem) layout = _column_layout(problem)
if layout is None: if layout is None:
return return
radius = int(bend)
max_span = max(before - after - 4 for (_, after), (before, _) in pairwise(layout.spans)) max_span = max(before - after - 4 for (_, after), (before, _) in pairwise(layout.spans))
max_offset = floor(problem.bounds[3]) - ceil(problem.bounds[1]) max_offset = floor(problem.bounds[3]) - ceil(problem.bounds[1])
shifting_width = max((w for a, b, w in zip(layout.launch, layout.arrival, layout.widths, strict=True) if a != b), default=0.0)
allowed_offsets = None if search.sbend_offsets is None else frozenset(search.sbend_offsets)
for radius in radii:
if not bend_fits_width(radius, shifting_width):
continue
try: try:
spans = exact_sbend_spans(radius, max_span=max_span, max_offset=max_offset, offsets=search.sbend_offsets) spans = exact_sbend_spans(radius, max_span=max_span, max_offset=max_offset, offsets=search.sbend_offsets)
except ExactSBendScanLimitError: except ExactSBendScanLimitError:
return continue
if not spans: if not spans:
return continue
allowed_offsets = None if search.sbend_offsets is None else frozenset(search.sbend_offsets)
for moves in _column_sbend_schedules( for moves in _column_sbend_schedules(
problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets,
): ):

View file

@ -7,11 +7,12 @@ from itertools import combinations, pairwise, product
from math import ceil, floor, isfinite from math import ceil, floor, isfinite
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from inire.geometry.components import bend90_uses_circular_geometry, bend_fits_width
from inire.geometry.primitives import rotate_cardinal from inire.geometry.primitives import rotate_cardinal
from inire.model import resolve_bend_geometry from inire.model import resolve_bend_geometry
from inire.router._seed_materialization import materialize_path_seed from inire.router._seed_materialization import materialize_path_seed
from inire.router._waypoints import _direction, compile_waypoints, export_waypoints from inire.router._waypoints import _direction, compile_waypoints, export_waypoints
from inire.seeds import PathSeed, StraightSeed from inire.seeds import Bend90Seed, PathSeed, StraightSeed
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterator from collections.abc import Iterator
@ -118,7 +119,9 @@ def bundle_turnaround_candidates(
returning, inferred = mismatches[0] returning, inferred = mismatches[0]
if returning.start != inferred.start or returning.target.r != 0 or inferred.target.r != 180: if returning.start != inferred.start or returning.target.r != 0 or inferred.target.r != 180:
return return
radius = int(min(search.bend_radii)) radius = next((int(move.radius) for move in proposal.initial_paths[returning.net_id].segments if isinstance(move, Bend90Seed)), None)
if radius is None:
return
farthest = max(net.target.x for net in problem.nets) farthest = max(net.target.x for net in problem.nets)
shelf = max((net for net in problem.nets if net.target.x == farthest), key=lambda net: net.target.y) shelf = max((net for net in problem.nets if net.target.x == farthest), key=lambda net: net.target.y)
if shelf == returning: if shelf == returning:
@ -189,15 +192,13 @@ def terminal_link_seed(net: NetSpec, search: SearchOptions) -> PathSeed | None:
if start.r % 180 == target.r % 180: if start.r % 180 == target.r % 180:
return None return None
corner = (b[0], a[1]) if start.r % 180 == 0 else (a[0], b[1]) corner = (b[0], a[1]) if start.r % 180 == 0 else (a[0], b[1])
radius = min(search.bend_radii, default=0.0) if corner in (a, b) or _direction(a, corner) != start.r or _direction(corner, b) != target.r:
if ( return None
not isfinite(radius) proxy, physical = resolve_bend_geometry(search)
or radius <= 0 circular = bend90_uses_circular_geometry(proxy, physical)
or corner in (a, b) available = min(abs(b[0] - a[0]), abs(b[1] - a[1]))
or _direction(a, corner) != start.r radius = min((r for r in search.bend_radii if r <= available and (not circular or bend_fits_width(r, net.width))), default=0.0)
or _direction(corner, b) != target.r if not radius:
or min(abs(b[0] - a[0]), abs(b[1] - a[1])) < radius
):
return None return None
seed, end = compile_waypoints((a, corner, b), start, radius) seed, end = compile_waypoints((a, corner, b), start, radius)
return seed if end == target else None return seed if end == target else None
@ -235,14 +236,18 @@ def _return_detours(
def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[tuple[NetSpec, PathSeed]]: def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[tuple[NetSpec, PathSeed]]:
"""Try four-turn detours around obstacles or behind east-facing ports.""" """Try four-turn detours around obstacles or behind east-facing ports."""
_, physical_geometry = resolve_bend_geometry(search) _, physical_geometry = resolve_bend_geometry(search)
bend = min(search.bend_radii, default=0.0) if problem.initial_paths or physical_geometry != "arc":
if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend): return
radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)})
if not radii:
return return
obstacles = tuple(shape.bounds for shape in problem._blocking_polygons if not shape.is_empty) obstacles = tuple(shape.bounds for shape in problem._blocking_polygons if not shape.is_empty)
radius = int(bend)
for net in problem.nets: for net in problem.nets:
if net.start.r != 0 or net.target.r != 0: if net.start.r != 0 or net.target.r != 0:
continue continue
radius = next((r for r in radii if bend_fits_width(r, net.width)), None)
if radius is None:
continue
if net.start.x > net.target.x: if net.start.x > net.target.x:
yield from ((net, seed) for seed in _return_detours(problem, net, obstacles, radius)) yield from ((net, seed) for seed in _return_detours(problem, net, obstacles, radius))
continue continue

View file

@ -45,6 +45,43 @@ def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None:
assert bends == (SBendSeed(sign * 2, 25),) * 5 assert bends == (SBendSeed(sign * 2, 25),) * 5
@pytest.mark.parametrize("smaller_radius", [10, 15])
def test_column_routes_use_a_later_radius_when_the_smallest_cannot_make_the_shift(smaller_radius) -> None:
nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(240, y + 20, 0), width=30) for y in (35, 110, 185))
problem = RoutingProblem((0, 0, 250, 250), nets, (box(130, 0, 150, 10),), clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(smaller_radius, 25), sbend_offsets=(20,)),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
)
run = route(problem, options=options)
assert run.automatic.selected_planner == "column"
assert run.metrics.nodes_expanded == 0
for result in run.results_by_net.values():
assert result.is_valid
assert {move.radius for move in result.as_seed().segments if isinstance(move, SBendSeed)} == {25}
def test_column_routes_allow_wide_straight_tracks_alongside_smaller_bends() -> None:
straight = NetSpec("wide", Port(5, 30, 0), Port(220, 30, 0), width=30)
shifted = tuple(NetSpec(str(y), Port(5, y, 0), Port(220, y + 8, 0)) for y in (90, 150))
problem = RoutingProblem((0, 0, 230, 180), (straight, *shifted), (box(130, 0, 150, 10),), clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10, 25), sbend_offsets=(8,)),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
)
run = route(problem, options=options)
assert run.automatic.selected_planner == "column"
assert all(result.is_valid for result in run.results_by_net.values())
for net in shifted:
assert {move.radius for move in run.results_by_net[net.net_id].as_seed().segments if isinstance(move, SBendSeed)} == {10}
def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None: def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None:
make_state = Mock(wraps=_columns._BendState) make_state = Mock(wraps=_columns._BendState)
monkeypatch.setattr(_columns, "_BendState", make_state) monkeypatch.setattr(_columns, "_BendState", make_state)

View file

@ -1,3 +1,6 @@
from dataclasses import replace
import pytest
from shapely.geometry import box from shapely.geometry import box
from inire import Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route from inire import Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route
@ -32,3 +35,17 @@ def test_forward_perimeter_detour_can_fit_at_exactly_four_radii() -> None:
assert result.is_valid assert result.is_valid
assert run.automatic.selected_planner == "perimeter" assert run.automatic.selected_planner == "perimeter"
assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4
@pytest.mark.parametrize("smaller_radius", [10, 17.5])
def test_perimeter_detours_choose_a_radius_usable_by_the_planner(smaller_radius) -> None:
net = NetSpec("wide", Port(20, 70, 0), Port(220, 70, 0), width=30)
problem = RoutingProblem((0, 0, 250, 180), (net,), (box(100, 40, 130, 100),), clearance=0)
options = replace(OPTIONS, search=replace(OPTIONS.search, bend_radii=(smaller_radius, 20)))
run = route(problem, options=options)
result = run.results_by_net[net.net_id]
assert result.is_valid
assert run.automatic.selected_planner == "perimeter"
assert {move.radius for move in result.as_seed().segments if isinstance(move, Bend90Seed)} == {20}

View file

@ -134,6 +134,28 @@ def test_bundle_preserves_explicit_terminal_headings_by_default() -> None:
route(terminal_bench_problem(), options=options) route(terminal_bench_problem(), options=options)
@pytest.mark.parametrize("mode", ["bundle", "automatic"])
def test_bundle_and_turnaround_use_the_smallest_common_radius(mode) -> None:
options = terminal_bench_options(node_limit=1, max_iterations=1)
options = replace(
options,
search=replace(options.search, bend_radii=(BEND_RADIUS / 2, BEND_RADIUS)),
refinement=replace(options.refinement, enabled=False),
topology=TopologyOptions(mode=mode, infer_terminal_headings=(mode == "bundle")),
)
run = route(terminal_bench_problem(), options=options)
assert all(result.is_valid for result in run.results_by_net.values())
assert run.metrics.nodes_expanded == 0
if mode == "automatic":
assert run.automatic.selected_planner == "bundle-turnaround"
for result in run.results_by_net.values():
for move in result.as_seed().segments:
if isinstance(move, Bend90Seed | SBendSeed):
assert move.radius == BEND_RADIUS
def test_bundle_plans_tracks_without_coincident_nets() -> None: def test_bundle_plans_tracks_without_coincident_nets() -> None:
problem = terminal_bench_problem() problem = terminal_bench_problem()
port = problem.nets[0].start port = problem.nets[0].start