Avoid unnecessary search and placement trials in automatic routing

This commit is contained in:
Jan Petykiewicz 2026-11-30 15:35:45 -08:00
commit 9e41c1abf8
4 changed files with 100 additions and 19 deletions

View file

@ -17,7 +17,9 @@ from inire.model import FixedRoute, resolve_bend_geometry
from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode
from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle
from inire.router._capacity import cut_capacity, port_conflicts
from inire.router._columns import column_jog_candidates, column_recovery_candidates, column_recovery_subproblems, column_seed_candidates
from inire.router._columns import (
column_jog_candidates, column_partition_budget_exceeded, column_recovery_candidates, column_recovery_subproblems, column_seed_candidates,
)
from inire.router._compact import compact_port_seed_set, short_shift_seed_set
from inire.router._congestion_policy import ordered_nets
from inire.router._perimeter import (
@ -271,7 +273,10 @@ class _AutomaticRun:
if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets):
planner = "local-sbend"
with self._time("plan", planner=planner):
shifts = short_shift_seed_set(problem, options.search, self._selection_cost, defer_blocker=not self.problem.initial_paths)
shifts = short_shift_seed_set(
problem, options.search, self._selection_cost,
defer_blocker=not self.problem.initial_paths, length_weights=self.length_weights,
)
if shifts is not None:
trial = verify(replace(problem, initial_paths=shifts), planner)
complete = len(trial.valid_costs) == len(problem.nets)
@ -582,10 +587,13 @@ class _AutomaticRun:
):
with self._time("plan", planner="column-recovery"):
groups = column_recovery_subproblems(problem)
# With independent channels, try construction before spending search
# budget on each net. Keep the general bypass as a later fallback.
if len(groups) > 1 and self._try_column_recovery(options, trials, groups):
try_recovery_early = len(groups) > 1 or (len(groups) == 1 and column_partition_budget_exceeded(problem))
# Independent channels and dense aperture fields can be cheaper to route
# by construction. Try their bypass before spending search budget.
if try_recovery_early:
if self._try_column_recovery(options, trials, groups):
return True
groups = ()
probe_iterations = options.congestion.max_iterations
proxy, _ = resolve_bend_geometry(options.search)
# Clipped proxies can find cheaper routes in later probe iterations than in the wider retry.

View file

@ -120,16 +120,29 @@ def _ordered_tracks(problem: RoutingProblem) -> tuple[_Track, ...]:
return tuple(tracks)
def _partition_budget_exceeded(tracks: tuple[_Track, ...], columns: tuple[_Column, ...]) -> bool:
return any(
comb(len(tracks) + len(column.openings) - 1, len(column.openings) - 1) > _MAX_COLUMN_PARTITIONS for column in columns
)
def _track_columns(problem: RoutingProblem, tracks: tuple[_Track, ...]) -> tuple[int, int, tuple[_Column, ...]]:
start = max(int(track.left.x) for track in tracks)
finish = min(int(track.right.x) for track in tracks)
return start, finish, _columns(problem, start, finish)
def column_partition_budget_exceeded(problem: RoutingProblem) -> bool:
tracks = _ordered_tracks(problem)
return bool(tracks) and _partition_budget_exceeded(tracks, _track_columns(problem, tracks)[2])
def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3) -> _ColumnLayout | None:
tracks = _ordered_tracks(problem)
if len(tracks) < min_tracks or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks):
return None
start = max(int(track.left.x) for track in tracks)
finish = min(int(track.right.x) for track in tracks)
columns = _columns(problem, start, finish)
if not columns or any(
comb(len(tracks) + len(column.openings) - 1, len(column.openings) - 1) > _MAX_COLUMN_PARTITIONS for column in columns
):
start, finish, columns = _track_columns(problem, tracks)
if not columns or _partition_budget_exceeded(tracks, columns):
return None
launch = tuple(int(track.left.y) for track in tracks)
arrival = tuple(int(track.right.y) for track in tracks)

View file

@ -2,6 +2,7 @@
from __future__ import annotations
from functools import cache
from itertools import combinations, islice
from math import ceil, floor, isfinite
from typing import TYPE_CHECKING
@ -11,19 +12,19 @@ from shapely.geometry import box
from inire.geometry.collision import RoutingWorld, _violates_net_clearance
from inire.geometry.primitives import port_local_coordinates
from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans, sbend_grid_span
from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans, sbend_angle, sbend_centerline_length, sbend_grid_span, sbend_span
from inire.model import resolve_bend_geometry
from inire.results import RoutingResult
from inire.router._seed_materialization import materialize_path_seed
from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator
from collections.abc import Iterable, Iterator, Mapping
from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
from inire.geometry.components import ComponentResult
from inire.geometry.components import ComponentResult, MoveKind
from inire.model import NetSpec, RoutingProblem, SearchOptions
from inire.router._routing_policy import Scorer
from inire.seeds import PathSegmentSeed
@ -198,7 +199,8 @@ def _shift_seeds(forward: int, offset: int, search: SearchOptions) -> Iterator[P
def short_shift_seed_set(
problem: RoutingProblem, search: SearchOptions, score: Scorer, *, defer_blocker: bool = False,
problem: RoutingProblem, search: SearchOptions, score: Scorer, *,
defer_blocker: bool = False, length_weights: Mapping[MoveKind, float] | None = None,
) -> dict[str, PathSeed] | None:
"""Fit links between fixed ports across both axes of a layout."""
if problem.initial_paths or len(problem.nets) < 3 or len({net.start.r % 180 for net in problem.nets}) < 2:
@ -214,6 +216,10 @@ def short_shift_seed_set(
board = box(*problem.bounds)
world = RoutingWorld.from_problem(problem, board=board)
if length_weights is not None and not search.sbend_outlines and any(len(seeds) > 1 for seeds in seeds_by_net):
packed = _pack_shortest_shifts(problem, search, world, board, seeds_by_net, length_weights)
if packed is not None:
return packed
candidates = {}
for net, seeds in zip(problem.nets, seeds_by_net, strict=True):
ranked = [
@ -242,3 +248,32 @@ def short_shift_seed_set(
candidates.pop(blockers.pop())
return _pack_routes(candidates, problem.clearance)
return None
def _pack_shortest_shifts(
problem: RoutingProblem, search: SearchOptions, world: RoutingWorld, board: Polygon,
seeds_by_net: list[tuple[PathSeed, ...]], length_weights: Mapping[MoveKind, float],
) -> dict[str, PathSeed] | None:
# Weighted length is independent of keepouts. When every cheapest seed
# verifies and fits with the others, the other placements cannot improve it.
@cache
def bend_cost(bend: SBendSeed) -> float:
offset, radius = bend.offset, bend.radius
tail = sbend_grid_span(offset, radius) - sbend_span(offset, radius)
return length_weights["sbend"] * sbend_centerline_length(radius, sbend_angle(offset, radius), tail)
def cost(seed: PathSeed) -> float:
return sum(
bend_cost(move) if isinstance(move, SBendSeed) else length_weights["straight"] * move.length
for move in seed.segments
)
candidates = {}
for net, seeds in zip(problem.nets, seeds_by_net, strict=True):
best = min(seeds, key=cost)
verified = next(_verified_candidates(net, world, board, search, (best,)), None)
if verified is None:
return None
seed, footprint, _ = verified
candidates[net.net_id] = [(seed, footprint)]
return _pack_routes(candidates, problem.clearance)

View file

@ -12,10 +12,11 @@ from inire import (
SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route,
)
from inire.constants import TOLERANCE_LINEAR
from inire.router import _automatic
from inire.router import _automatic, _compact
from inire.router._automatic import _AutomaticRun
from inire.router._capacity import port_conflicts
from inire.router._routing_policy import _disconnected_nets
from inire.router.cost import weighted_path_length
from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES
from inire.tests.routing_benchmarks import (
BENCHMARK_CASES,
@ -76,8 +77,9 @@ def test_column_recovery_routes_with_a_one_node_search_budget(name) -> None:
assert all(result.is_valid for result in run.results_by_net.values())
def test_independent_column_channels_can_skip_the_search_probe() -> None:
(case,) = CASE_GROUPS["search-comb-3x4"]
@pytest.mark.parametrize("name", ["search-comb-3x4", "scale-field-20x16"])
def test_column_recovery_can_skip_the_search_probe(name) -> None:
(case,) = CASE_GROUPS[name]
options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression")
run = route(case.problem, options=options)
@ -135,6 +137,29 @@ def test_local_shift_plan_can_leave_one_conflicting_net_for_a_detour() -> None:
assert set(partial.valid_net_ids) == {net.net_id for net in case.problem.nets if net.net_id != "outside_lower"}
def test_weighted_local_shifts_can_pack_without_verifying_alternative_placements(monkeypatch) -> None:
(case,) = CASE_GROUPS["crossing-staggered-grid"]
weights = {"straight": 1.0, "bend90": 4.0, "sbend": 13.0}
def score(result):
return weighted_path_length(result.path, weights)
exhaustive = _compact.short_shift_seed_set(case.problem, case.options.search, score)
original = _compact._verified_candidates
seed_counts = []
def count_candidates(net, world, board, search, seeds):
seed_counts.append(len(seeds))
yield from original(net, world, board, search, seeds)
monkeypatch.setattr(_compact, "_verified_candidates", count_candidates)
packed = _compact.short_shift_seed_set(case.problem, case.options.search, score, length_weights=weights)
assert packed
assert packed == exhaustive
assert seed_counts == [1] * len(case.problem.nets)
def test_expanded_corpus_uses_physical_dimensions_and_has_reference_coverage() -> None:
corpus_names = {case.name for case in CORPUS_CASES}
assert len(corpus_names) == len(CORPUS_CASES)