From bcd9ade3eae185fa7bd8ba332327bbdcedeef4de Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 15:24:10 -0800 Subject: [PATCH] Recover remaining routes with column plans and residual detours --- docs/architecture.md | 2 +- docs/benchmark-fixtures.md | 2 +- inire/router/_automatic.py | 62 ++++++++++++++--- inire/router/_columns.py | 78 ++++++++++++++++++++-- inire/tests/routing_corpus.py | 9 +-- inire/tests/routing_expanded_benchmarks.py | 6 +- inire/tests/test_routing_benchmarks.py | 51 +++++++++++++- 7 files changed, 179 insertions(+), 31 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index b1dc292..fb6925c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -10,7 +10,7 @@ Follow the left column while coverage is below the target. Reaching the target s 1. **Set a coverage target.** Conflicting aligned port faces and [track capacity](../inire/router/_capacity.py#L29) at rectangular cuts can bound how many nets fit. 2. **Try constructive plans.** Bundles assign ordered tracks, columns schedule turns, and compact planners fit short links. Each plan supplies seeds for the worker to verify. -3. **Search for missing routes.** Early attempts use small budgets and can hold verified routes fixed. If the locks cut off a port, retry with movable seeds or different lanes. Lattice search handles custom outlines or proxies and is the fallback when corridor planning is unavailable. +3. **Search for missing routes.** Early attempts use small budgets and can hold verified routes fixed. When a column plan stalls, try separated channels or a shared bypass around the keepouts. If the locks cut off a port, retry with movable seeds or different lanes. With one net left, try a verified detour around the locked paths, including incumbents found by the seed fallback. Lattice search handles custom outlines or proxies and is the fallback when corridor planning is unavailable. 4. **Select and refine.** Prefer higher verified coverage. Compare cost on matching verified net IDs. Refinement can replace the selected layout only if those IDs remain verified. ### Example of a poor lock diff --git a/docs/benchmark-fixtures.md b/docs/benchmark-fixtures.md index 932a9ee..95c27cf 100644 --- a/docs/benchmark-fixtures.md +++ b/docs/benchmark-fixtures.md @@ -14,7 +14,7 @@ The `expanded` group adds 72 deterministic, unseeded boards with independently c | `search-challenges` | 8 | Alternating comb walls that force repeated turns and exercise search-budget exhaustion. | | `scaling` | 8 | Banks and crossing arrays of up to 256 nets, obstacle fields with up to 320 keepouts, and a 240-net board with 240 keepouts and four blocked approaches. | -The 72 reference layouts run in pytest. The corner and complex groups and seven scaling boards also have unseeded coverage assertions at the regression budget. Use `--case search-challenges` or `--case scaling` with an explicit budget to measure search and coverage on the harder boards. For scaling comparisons, use the same grid, mode, and budget and collect repeated timings with `--repeat`. +Pytest verifies the 72 reference layouts and checks that unseeded routing reaches the known bound on every board. Use `--case search-challenges` or `--case scaling` with an explicit budget to compare routing policies on the harder boards. For scaling comparisons, use the same grid, mode, and budget and collect repeated timings with `--repeat`. To exercise the low-budget fallbacks on tight geometry, run `--case geometry-corners --profile corpus-regression --mode automatic --nodes 1 --seed-nodes 1 --iterations 1`. diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index b2d59c8..c2445b1 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -17,7 +17,7 @@ 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_seed_candidates +from inire.router._columns import column_jog_candidates, 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 ( @@ -427,9 +427,9 @@ class _AutomaticRun: return [replace(trial, selection="requires-layout-check"), self._verify_incumbent(trial)] trials = [trial] if len(trial.valid_costs) < target: - dogleg = self._residual_dogleg_trial(options, _best_trial([best, trial])) - if dogleg is not None: - return [trial, dogleg] + construction = self._residual_constructive_trial(options, _best_trial([best, trial])) + if construction is not None: + return [trial, construction] joint = self._joint_lane_trial(residual, options, locks, trial) if joint is not None: trials.append(replace(joint, selection="requires-layout-check")) @@ -444,7 +444,7 @@ class _AutomaticRun: results = {**trial.run.results_by_net, **verified.run.results_by_net} return replace(verified.as_replacement_for(trial), run=replace(verified.run, results_by_net=results)) - def _residual_dogleg_trial(self, options: RoutingOptions, incumbent: Trial) -> Trial | None: + def _residual_constructive_trial(self, options: RoutingOptions, incumbent: Trial, *, limit_per_pass: int = 8) -> Trial | None: problem = self.problem if len(incumbent.valid_costs) != len(problem.nets) - 1: return None @@ -452,9 +452,14 @@ class _AutomaticRun: residual = _residual_problem(problem, LockPlan(retained)) (net,) = residual.nets seeds = {net_id: result.as_seed() for net_id, result in retained.items()} - planner = "residual-dogleg" + if net.start.r == net.target.r == 0 and net.start.x > net.target.x: + planner = "residual-perimeter" + candidates = (seed for _, seed in islice(perimeter_detour_candidates(residual, options.search), 32)) + else: + planner = "residual-dogleg" + candidates = residual_dogleg_candidates(residual, options.search, limit_per_pass=limit_per_pass) with self._time("plan", planner=planner, policy=planner): - for seed in residual_dogleg_candidates(residual, options.search, limit_per_pass=8): + for seed in candidates: candidate = replace(problem, initial_paths={**seeds, net.net_id: seed}) trial = self._verify(candidate, planner, policy=planner) if len(trial.valid_costs) == len(problem.nets): @@ -501,6 +506,29 @@ class _AutomaticRun: return True return False + def _column_recovery_trial(self, options: RoutingOptions) -> Trial | None: + problem = self.problem + if problem.initial_paths or not options.search.bend_radii or not problem._blocking_polygons: + return None + planner = "column-recovery" + with self._time("plan", planner=planner): + groups = column_recovery_subproblems(problem) + if not groups: + return None + combined = {} + for group in groups: + for seeds in column_recovery_candidates(group, options.search): + trial = self._verify(replace(group, initial_paths=seeds), planner) + if len(trial.valid_costs) == len(group.nets): + if group is problem: + return trial + combined.update(seeds) + break + else: + return None + trial = self._verify(replace(problem, initial_paths=combined), planner) + return trial if len(trial.valid_costs) == len(problem.nets) else None + def _search_trials(self, trials: list[Trial], target: int) -> None: configured_search = self.options.search first_limit = min(_INITIAL_NODE_LIMIT, configured_search.node_limit) @@ -552,9 +580,9 @@ class _AutomaticRun: return True if try_construction_early and target == len(problem.nets) and target > 2 and not problem.initial_paths: - dogleg = self._residual_dogleg_trial(options, _best_trial(probe)) - if dogleg is not None: - trials.append(dogleg) + construction = self._residual_constructive_trial(options, _best_trial(probe)) + if construction is not None: + trials.append(construction) return True if len(problem.nets) <= 2: @@ -563,6 +591,12 @@ class _AutomaticRun: if len(_best_trial(trials).valid_costs) >= target: return True + if target == len(problem.nets) and not options.congestion.shuffle_nets: + recovery = self._column_recovery_trial(options) + if recovery is not None: + trials.append(recovery) + return True + # Every short shift has lateral displacement, so the direct retry cannot lock # any straight paths. It would run the same guide with the same budget. if early is None or early.run.metrics.timeout_events: @@ -578,7 +612,13 @@ class _AutomaticRun: if len(_best_trial(trials).valid_costs) < target: run = self._run(problem, options=seeded, policy="seed-fallback") stage = RoutingStage("seed", (), run.metrics.nodes_expanded, options.search.node_limit, policy="seed-fallback") - trials.append(self._trial(run, stage)) + candidate = self._trial(run, stage) + trials.append(candidate) + if not problem.initial_paths and len(candidate.valid_costs) == target - 1 and _best_trial(trials) is candidate: + # The seed fallback can leave a better set of incumbents for a final detour. + construction = self._residual_constructive_trial(options, candidate, limit_per_pass=16) + if construction is not None: + trials.append(construction) def _joint_lane_trial(self, residual: RoutingProblem, options: RoutingOptions, locks: LockPlan, previous: Trial) -> Trial | None: if len(residual.nets) < 2: diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 6cfecbc..138db99 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -3,14 +3,15 @@ from __future__ import annotations from collections import defaultdict -from dataclasses import dataclass +from dataclasses import dataclass, replace from functools import cache, lru_cache from heapq import heappop, heappush, merge from itertools import combinations_with_replacement, islice, pairwise, product from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin from typing import TYPE_CHECKING -from shapely.geometry import LineString +from shapely import total_bounds +from shapely.geometry import LineString, box from inire.geometry.components import bend90_uses_circular_geometry, bend_fits_width from inire.geometry.intervals import Gap, open_intervals @@ -22,6 +23,8 @@ from inire.seeds import PathSeed, SBendSeed, StraightSeed if TYPE_CHECKING: from collections.abc import Callable, Iterator, Mapping + from shapely.geometry import Polygon + from inire.geometry.primitives import Port from inire.model import NetSpec, RoutingProblem, SearchOptions from inire.router._waypoints import XY @@ -117,9 +120,9 @@ def _ordered_tracks(problem: RoutingProblem) -> tuple[_Track, ...]: return tuple(tracks) -def _column_layout(problem: RoutingProblem) -> _ColumnLayout | None: +def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3) -> _ColumnLayout | None: tracks = _ordered_tracks(problem) - if len(tracks) < 3 or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks): + 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) @@ -715,14 +718,16 @@ def _column_jog_schedules( -def column_jog_candidates(problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None) -> Iterator[dict[str, PathSeed]]: +def column_jog_candidates( + problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None, recovery: bool = False, +) -> Iterator[dict[str, PathSeed]]: """Allocate tracks through ordered apertures using staggered 90-degree jogs.""" if problem.initial_paths: 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 - layout = _column_layout(problem) + layout = _column_layout(problem, min_tracks=1 if recovery else 3) if layout is None: return circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search)) @@ -730,10 +735,20 @@ def column_jog_candidates(problem: RoutingProblem, search: SearchOptions, *, lim def profiles_for_slack(slack: int) -> list[list[Profile]]: widths = layout.widths # Modulus one allows any integer track level. + residues = (0,) * len(widths) interior = [ - _column_profiles(problem, column, widths, (0,) * len(widths), desired, slack, slack, 1, combinations_limit=8192) + _column_profiles(problem, column, widths, residues, desired, slack, slack, 1, combinations_limit=8192) for column, desired in zip(layout.columns, layout.preferences, strict=True) ] + if recovery: + # Terminal rows can carry through a column without a jog. They also + # give later turns room when the interpolated rows hug aperture edges. + anchors = dict.fromkeys((layout.launch, layout.arrival)) + for i, column in enumerate(layout.columns): + rows = set(interior[i]) + for anchor in anchors: + rows.update(_column_profiles(problem, column, widths, residues, anchor, slack, slack, 1)) + interior[i] = sorted(rows) return [[layout.launch], *interior, [layout.arrival]] seen: set[tuple[tuple[str, PathSeed], ...]] = set() @@ -751,3 +766,52 @@ def column_jog_candidates(problem: RoutingProblem, search: SearchOptions, *, lim for minimum in dict.fromkeys((search.min_straight_length, 0.0)): yield from islice(seed_pass(minimum), limit_per_pass) + + +def column_recovery_subproblems(problem: RoutingProblem) -> tuple[RoutingProblem, ...]: + """Use full-width keepouts to isolate independent horizontal channels.""" + xmin, ymin, xmax, ymax = problem.bounds + dividers = [] + for shape in problem.static_obstacles: + left, bottom, right, top = shape.bounds + if left <= xmin and right >= xmax and ymin < top and bottom < ymax and shape.equals(box(left, bottom, right, top)): + dividers.append((bottom, top)) + if not dividers: + return (problem,) + + clearance = problem.clearance + + def nearby(shapes: tuple[Polygon, ...], lower: float, upper: float) -> tuple[Polygon, ...]: + return tuple(shape for shape in shapes if shape.bounds[3] > lower - clearance and shape.bounds[1] < upper + clearance) + + groups = [] + for bottom, top in open_intervals(dividers, ymin, ymax): + lower = bottom + clearance if bottom != ymin else bottom + upper = top - clearance if top != ymax else top + if lower >= upper: + continue + nets = tuple(net for net in problem.nets if lower <= net.start.y <= upper and lower <= net.target.y <= upper) + if not nets: + continue + fixed_routes = [] + for fixed in problem.fixed_routes: + polygons = nearby(fixed.polygons, lower, upper) + if polygons: + fixed_routes.append(replace(fixed, polygons=polygons)) + groups.append(replace( + problem, bounds=(xmin, lower, xmax, upper), nets=nets, + static_obstacles=nearby(problem.static_obstacles, lower, upper), fixed_routes=tuple(fixed_routes), + )) + return tuple(groups) if sum(len(group.nets) for group in groups) == len(problem.nets) else () + + +def column_recovery_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[dict[str, PathSeed]]: + """Try individual apertures and a shared bypass outside the keepout field.""" + yield from column_jog_candidates(problem, search, limit_per_pass=8, recovery=True) + obstacles = problem._blocking_polygons + if len(obstacles) < 2: + return + # Covering every keepout with one box offers a cheap option when planning + # individual columns has too many aperture assignments. Verify on the real board. + envelope = replace(problem, static_obstacles=(box(*total_bounds(obstacles)),), fixed_routes=()) + yield from column_jog_candidates(envelope, search, limit_per_pass=8, recovery=True) diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index 15daa56..4eb06f9 100644 --- a/inire/tests/routing_corpus.py +++ b/inire/tests/routing_corpus.py @@ -16,7 +16,7 @@ from inire.tests.routing_benchmarks import ( FALLBACK_BENCHMARK_CASES, VALIDATION_BENCHMARK_CASES, ) -from inire.tests.routing_expanded_benchmarks import COMPLEX_CASES, CORNER_CASES, SCALING_CASES, SCALING_REGRESSION_CASES, SEARCH_CASES +from inire.tests.routing_expanded_benchmarks import COMPLEX_CASES, CORNER_CASES, SCALING_CASES, SEARCH_CASES from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from inire.tests.terminal_bench_scenario import LENGTH_COST @@ -28,9 +28,10 @@ if TYPE_CHECKING: BROAD_CASES = (*VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) -_STANDARD_CASES = (*BENCHMARK_CASES, *BROAD_CASES, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES, *CORNER_CASES, *COMPLEX_CASES) -CORPUS_REGRESSION_CASES = (*_STANDARD_CASES, *SCALING_REGRESSION_CASES) -CORPUS_CASES = (*_STANDARD_CASES, *SEARCH_CASES, *SCALING_CASES) +CORPUS_CASES = ( + *BENCHMARK_CASES, *BROAD_CASES, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES, + *CORNER_CASES, *COMPLEX_CASES, *SEARCH_CASES, *SCALING_CASES, +) SNAPSHOT_CASES = tuple( case for case in (*BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) if case.name != "terminal-bench" ) diff --git a/inire/tests/routing_expanded_benchmarks.py b/inire/tests/routing_expanded_benchmarks.py index 406ec79..cf8e270 100644 --- a/inire/tests/routing_expanded_benchmarks.py +++ b/inire/tests/routing_expanded_benchmarks.py @@ -348,7 +348,7 @@ SEARCH_CASES = ( _comb("6x7", 6, 7, 20), ) -SCALING_REGRESSION_CASES = ( +SCALING_CASES = ( _crossings("scale-crossing-10x10-aligned", 10, 10, 120, 132, staggered=False), _crossings("scale-crossing-10x11-staggered", 10, 11, 120, 132, staggered=True), _port_bank("224", 224, obstacles=False), @@ -356,9 +356,5 @@ SCALING_REGRESSION_CASES = ( _port_bank("216-with-keepouts", 216, obstacles=True), _obstacle_field(16, 16, 3, grid=1000), _port_bank("240-with-keepouts", 240, obstacles=True, detours=4, grid=500), -) - -SCALING_CASES = ( - *SCALING_REGRESSION_CASES, _obstacle_field(20, 16, 4, grid=500), ) diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index a6d5c74..3a2c3fa 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -23,7 +23,7 @@ from inire.tests.routing_benchmarks import ( EXTERNAL_BENCHMARK_CASES, FALLBACK_BENCHMARK_CASES, ) -from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, CORPUS_REGRESSION_CASES, automatic_options, profile_options +from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from scripts.compare_topological_routing import ( _direct_trials, @@ -41,7 +41,7 @@ def _measure(case, options, strategy): @pytest.mark.routing_corpus @pytest.mark.parametrize( "case", - [pytest.param(case, id=case.name) for case in CORPUS_REGRESSION_CASES], + [pytest.param(case, id=case.name) for case in CORPUS_CASES], ) def test_automatic_reaches_corpus_routing_bound(case) -> None: profile = "corpus-regression" @@ -56,6 +56,53 @@ def test_automatic_reaches_corpus_routing_bound(case) -> None: assert len(verified) == case.routing_bound +@pytest.mark.parametrize("name", ["search-comb-1x4", "search-comb-2x5-fine", "scale-field-20x16"]) +def test_column_recovery_routes_with_a_one_node_search_budget(name) -> None: + (case,) = CASE_GROUPS[name] + options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") + options = replace( + options, + search=replace(options.search, node_limit=1), + congestion=replace(options.congestion, max_iterations=1), + topology=replace(options.topology, seed_node_limit=1), + ) + + run = route(case.problem, options=options) + + assert run.automatic is not None + assert run.automatic.selected_planner == "column-recovery" + assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} + assert all(result.is_valid for result in run.results_by_net.values()) + + +@pytest.mark.parametrize("name", ["retry-holdout-stepped-roof", "retry-holdout-west-roof"]) +def test_residual_perimeter_completes_a_return_with_straight_peers(name) -> None: + (case,) = CASE_GROUPS[name] + options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") + options = replace(options, search=replace(options.search, node_limit=1)) + + run = route(case.problem, options=options) + + assert run.automatic is not None + assert run.automatic.selected_planner == "residual-perimeter" + assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} + assert all(len(run.results_by_net[net_id].path) == 1 for net_id in ("edge", "lower", "east")) + + +@pytest.mark.routing_corpus +def test_final_dogleg_can_reuse_incumbents_from_seed_fallback() -> None: + (case,) = CASE_GROUPS["retry-holdout-reversed-bank"] + options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") + + run = route(case.problem, options=options) + + assert run.automatic is not None + assert run.automatic.selected_planner == "residual-dogleg" + [fallback] = [stage for stage in run.automatic.stages if stage.policy == "seed-fallback" and stage.operation == "search"] + assert set(fallback.valid_net_ids) == {net.net_id for net in case.problem.nets if net.net_id != "outside_lower"} + assert set(run.automatic.verified_net_ids) == {net.net_id for net in 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)