From a2dfb73c33e54c1d202980fe5e3f7c12f7cde4d8 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Thu, 26 Nov 2026 15:23:24 -0800 Subject: [PATCH] Complete feasible stress layouts with verified routing fallbacks --- DOCS.md | 10 +- README.md | 2 + docs/topological-routing.md | 46 +++- inire/router/_automatic.py | 130 +++++++++-- inire/router/_columns.py | 149 +++++++++++- inire/router/_compact.py | 118 ++++++++-- inire/router/_perimeter.py | 80 +++++++ inire/router/_router.py | 27 ++- inire/router/_routing_policy.py | 14 +- inire/router/_stack.py | 4 +- inire/router/_topology.py | 95 +++++++- inire/tests/stress_routing_benchmarks.py | 281 +++++++++++++++++++++++ inire/tests/test_routing_benchmarks.py | 131 ++++++++++- pyproject.toml | 1 + scripts/compare_topological_routing.py | 10 +- 15 files changed, 1022 insertions(+), 76 deletions(-) create mode 100644 inire/tests/stress_routing_benchmarks.py diff --git a/DOCS.md b/DOCS.md index cbf695f..ab4c133 100644 --- a/DOCS.md +++ b/DOCS.md @@ -123,6 +123,8 @@ Use `RoutingProblem.initial_paths` to provide semantic per-net seeds. Seeds are | `objective` | `None` | Optional override objective for refinement. `None` reuses the search objective. | | `max_windows_per_net` | `24` | Maximum candidate windows attempted per net, shared across improvement rounds. Use `1` for a faster pass or `None` to remove the window limit. | +The refiner scores candidate moves from their ports and lengths before building polygons. When the incumbent is valid in the current collision world, it verifies the replacement window against obstacles, other nets, and the unchanged parts of its own path. The router verifies the final layout in full. + ## Topological Routing `RoutingOptions.topology` accepts a `TopologyOptions` value. The `mode` is the caller's routing choice. In automatic mode, inire selects a planner for the layout and can retry with another one. Seed mode generates verified initial paths before the current router completes and refines the layout. @@ -175,7 +177,13 @@ Automatic routing verifies generated layouts with inire and uses guide, seed, an Automatic carries caller-supplied paths into the usual seed handling. For custom bend geometry or an installation without constrained triangulation, it uses the lattice router directly at the configured limit. The optional refinement pass runs on the selected layout when enabled. Set `TopologyOptions(mode="off")` to select lattice-only routing explicitly. -For unseeded layouts made up of more than two short, forward, same-heading shifts across both axes, automatic can run the full initial guide budget first. If that pass falls short, the near-port probe and other fallbacks remain available. The identical guide retry is skipped when the first pass ran without a timeout. Calls with an iteration callback, shuffled net ordering, or at most 100 nodes per search use the regular search order. +For eligible unseeded layouts with fixed headings along both axes, `local-sbend` fits one S-bend between each pair of shifted ports using a configured radius and an exact forward span on the port lattice. It samples positions along the link, packs paths to meet clearance, and accepts the layout only after all nets pass verification. Crossings use the supplied port positions and keepouts. + +If short, forward, same-heading shifts across both axes still need search, automatic can run the full initial guide budget first. The near-port probe and other fallbacks follow if needed. The identical guide retry is skipped when the first pass ran without a timeout. Calls with an iteration callback, shuffled net ordering, or at most 100 nodes per search use the regular search order. + +If the initial probe leaves unresolved nets on an ordered horizontal bank, `column-jogs` can assign lanes across separated obstacle columns. It schedules the rises and drops as staggered pairs of 90-degree turns, using each net's width and the configured clearance. When only one net remains after an incumbent-residual attempt, `residual-dogleg` tries a four-turn detour through gaps between the locked paths and obstacles. Both planners verify the complete layout before selecting it. + +When an incumbent-residual attempt falls short of the routing bound, automatic can retry a shared portal with a joint lane assignment. It keeps the incumbent paths locked and assigns distinct lanes to two to four residual nets at one portal. The retry needs an unresolved net at that portal and a changed guide. It uses the initial node budget and at most three congestion iterations. An improving candidate is checked together with the incumbent paths before it can be selected. The report records the `selected_planner`, `verified_net_ids`, and the overall `max_routed` upper bound. Each stage includes the verified net IDs and any paths that went outside the board. A path whose physical geometry crosses the board boundary has `result.report.out_of_bounds=True`, which contributes one collision to the result. `result.reached_target` still records whether that path reached its target port. diff --git a/README.md b/README.md index e3fa0a0..a2f9278 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,8 @@ Run the default correctness suite with: python3 -m pytest ``` +The default test run checks automatic routing against the expected coverage on all 67 boards at 500 nodes per search attempt and three congestion iterations. It also verifies the reference paths for the ten stress layouts. Use `pytest -m "not routing_corpus"` for a shorter local run. The comparison CLI selects the stress layouts with `--case stress` and all 67 boards with `--case corpus`. + Runtime regression checks for the example scenarios are opt-in and require: ```bash diff --git a/docs/topological-routing.md b/docs/topological-routing.md index 8e491da..99ff81c 100644 --- a/docs/topological-routing.md +++ b/docs/topological-routing.md @@ -273,12 +273,56 @@ The experiments below use `2f2add9` as the baseline. The matched-budget profile Both changes together reproduced the exact path seeds, verified net IDs, per-net costs, and geometric bounds on all 57 boards in both profiles. Each profile verified 384 of 388 nets and completed 55 boards. On the full public-default sweep, refinement polygon builds dropped from 22,400 to 10,529. This is the strongest general-purpose result. -**Constructive S-bend placement.** A nine-position scan routed all 273 nets on the 16 grids whose links admitted a single exact-span S-bend. The tests included three radii, offsets from 2 to 36, mixed widths, and a blocked midpoint. The sum of public-default board medians from three repeats fell from 41.79 to 2.50 seconds. Weighted cost matched on 14 boards and improved on two. The native objective improved on all 16. At the matched budget, one mixed-radius board incurred 2.84 additional native cost units at the same weighted cost. Trying 17 positions added time and produced no additional fully routed boards. The off-lattice offsets and the crossing with a turning exit used the regular router. +**Constructive S-bend placement.** A nine-position scan routed all 273 nets on the 16 grids whose links admitted a single exact-span S-bend. The tests included three radii, offsets from 2 to 36, mixed widths, and a blocked midpoint. The sum of public-default board medians from three repeats fell from 41.79 to 2.50 seconds. Weighted cost matched on 14 boards and improved on two. The native objective improved on all 16. At the matched budget, one mixed-radius board incurred 2.84 additional native cost units while saving 155.10 weighted units. Trying 17 positions added time and produced no additional fully routed boards. The off-lattice offsets and the crossing with a turning exit used the regular router. **Hybrid S-bend seeding.** In a separate sweep capped at 500 search nodes, seeding 12 local links on a board with an independent long detour cut the public-objective median from 5.57 to 2.63 seconds. Both runs verified 13/13 nets and the hybrid improved both costs. On the board where the long route interacts with nearby links, the attempted hybrid added 7.21 seconds before returning the same 12/13-net fallback. Independent routing regions are a better target for partial seeding. **Joint portal-lane allocation.** A bounded search assigned distinct lanes to up to four nets using the same portal. A length and turn-cost objective reduced A* expansions from 3,488 to 2,942 on a four-track passage with a verified feasibility witness. All four nets routed at the same costs. The three-run median fell from 2.66 to 2.19 seconds. The timed runs started without the witness paths. An objective that also penalized guide overlap gave 2.68 seconds. In the twelve-board sweep under public defaults, both joint objectives increased coverage from 2/6 to 3/6 on the sole dual-passage fixture. On a single-passage fixture with the same three verified nets, weighted cost improved by 12.66 units and native cost rose by 2.33 units. The sum of public-default board medians moved by less than 1% for either objective. Joint selection among the existing alternate corridors yielded the same final paths in seven matched-budget cases and reduced total expansions by about 0.5%. +Automatic routing now uses the refinement changes and the verified `local-sbend` fast path for whole layouts. The joint-lane policy runs as a single residual retry with incumbents locked. In the integrated run it verified a third net on the dual-passage fixture while retaining the two incumbent routes. Both full-corpus profiles still reach the bounds on all 57 boards. Path seeds and costs matched the baseline on the 56 boards outside the staggered grid. On the grid, `local-sbend` routed all 24 nets with zero A* expansions and the same weighted cost. + +In three paired public-default runs against `9ddef65`, the fixed-heading Terminal-Bench median fell from 5.55 to 2.96 seconds and the staggered-grid median fell from 2.92 to 0.26 seconds. + +### Corpus regression check and follow-up sweeps + +The default test suite runs all 67 boards in the matched-budget profile at 500 search and seed nodes and three congestion iterations. The check asserts the expected number of verified nets and the routing bound for each board. The original 57 cases took 27 seconds in isolation and verified 384/388 nets. The timing comparisons use separate benchmark runs. + +Prioritizing refinement windows that begin and end at bends moved the two-unit improvement on `net_05` from window 24 to window 4. The four-window prototype matched verified net IDs, bounds, and both per-net costs on all 57 boards in both profiles. Fixed-heading Terminal-Bench used different geometry at the same scores. In three paired public-default runs, the sum of the four bundle-board medians fell from 15.11 to 4.75 seconds. + +On the external splitter tree, starting at 500 nodes reduced the public-default median from 6.99 to 4.82 seconds with the same six verified paths. Trying the residual first lost two nets at the matched budget. A 500-node first pass applied broadly also increased costs on the obstructed crossing approach. A targeted prototype tried it after constructive planning fell short on forward, same-heading layouts whose lateral shifts exceed the reach of one S-bend and which include a short forward span. That guard activated on the splitter tree within the 57-board corpus. A reversed net order, a rotated layout, and a larger board margin also retained all six exact paths and ran faster in both profiles. + +Together the four-window order and the guarded first pass matched verified coverage, bounds, and both per-net costs on the full corpus in both profiles. + +The joint-lane retry added no verified nets on six witness-backed shared-passage layouts. At the matched budget it ran on four of them, adding 4.2 to 12.8 seconds to their median runtimes. On the earlier dual-passage fixture under public defaults, it increased coverage from 2/6 to 3/6 and median runtime from 29.62 to 33.77 seconds. Capping the retry at 250 nodes yielded 2/6. + +### Stress layouts + +Ten layouts add 49 nets to the benchmark corpus. Every layout has a complete reference path set. The default suite checks those paths against the fixed headings, board boundaries, obstacles, and inter-net clearance. Automatic routing starts with empty initial paths for the benchmark. Select `--case stress` for these ten boards or `--case corpus` for all 67. + +| Layout | Behavior under test | Verified before | Verified with new fallbacks | +| --- | --- | ---: | ---: | +| `stress-refine-alternating-doglegs` | Overlapping refinement windows on six-bend routes with alternating edge walls, mixed widths, and two radii. | 0/3 | 3/3 | +| `stress-refine-return-shelf` | A folded return can shorten its shelf detour while clearing its own arms and a neighboring route. | 4/4 | 4/4 | +| `stress-retry-straight-decoy` | A legal straight trunk disconnects two perpendicular branches when locked. The trunk has a tight lower bypass. | 3/4 | 4/4 | +| `stress-retry-compact-shift-bank` | A 66-unit forward span leaves little turn room for a large lateral shift, while longer links face blocked approaches. | 4/4 | 4/4 | +| `stress-retry-mixed-port-bank` | Opposing short shifts, a perpendicular exit, and a return share one board. This exercises the boundary of the proposed 500-node first-pass guard. | 5/5 | 5/5 | +| `stress-passage-width-key` | A 14-unit slit fits a narrow guide. Five peers share a wider aperture and its approach banks. | 2/6 | 6/6 | +| `stress-passage-split-merge` | Two offset apertures feed a common passage with mixed widths and opposing travel. | 0/6 | 6/6 | +| `stress-sbend-competing-slots` | The centered choices for two opposed S-bends leave less than the required clearance. Two perpendicular links serve a fixed crossing. | 4/4 | 4/4 | +| `stress-crossing-off-lattice-slot` | An odd offset rules out an exact-span S-bend while a different leg must turn in a short launch pocket. | 4/4 | 4/4 | +| `stress-crossings-shared-outside-detour` | Two placed crossings have simple local links while a long route must go around their south approach bank. | 9/9 | 9/9 | + +```sh +python -m scripts.compare_topological_routing --case stress --mode automatic \ + --nodes 500 --seed-nodes 500 --iterations 3 --json /tmp/inire-stress.json +``` + +At the matched budget, the original stress run verified 35/49 nets and took about 91 seconds in aggregate over the ten boards. The new `column-jogs` planner completes the alternating doglegs and the two shared-passage layouts by assigning aperture lanes and staggering the turns between columns. The `residual-dogleg` planner routes the straight decoy's trunk while retaining the three other verified paths. With both fallbacks, the ten boards route 49/49 nets and take about 25 seconds in aggregate at the matched budget. + +With public defaults, the earlier runs on the alternating doglegs, width-key passage, and split-merge passage exceeded the 150-second per-run limit. The three boards now complete in 2.08, 2.45, and 3.33 seconds, respectively, in a single sweep. Each profile verifies 433/437 nets across all 67 boards and reaches the geometric bound on both partial boards. The other 63 boards reproduce their previous paths and per-net costs in both profiles. + +Before the new fallbacks, the proposed four-window refinement order and guarded 500-node first pass matched the original stress baseline at the matched budget. On the seeded return-shelf diagnostic, bend-first ordering found the same cost improvement on its first window that the prior order found on its second, with different geometry. + ### External and fallback benchmarks `--case external` runs six fixed-placement problems from two public sources. The fixtures preserve net IDs and device locations, with optical ports snapped to a 0.1 µm lattice and expressed relative to the imported board. Device boxes become obstacles with outward access cutouts at the selected ports. The timed runs start from empty initial paths. The converted inputs are checked into the repo so benchmark runs work offline. [Fixture data](../inire/tests/data/external_routing_benchmarks.json) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index a89b392..e8d096f 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -18,12 +18,28 @@ from inire.geometry.collision import RoutingWorld from inire.model import resolve_bend_geometry from inire.results import AutomaticRoutingReport, CapacityLimit, RouteMetrics, RoutingStage, RoutingTiming, _planner_for_mode from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle -from inire.router._columns import column_seed_candidates, open_intervals, rectangular_obstacle_bounds -from inire.router._compact import compact_port_seed_set -from inire.router._perimeter import bundle_turnaround_candidates, perimeter_detour_candidates, terminal_link_seed -from inire.router._routing_policy import LockPlan, _best_trial, _direct_trials, _disconnected_nets, _is_short_shift, _route_residual, _trial +from inire.router._columns import column_jog_candidates, column_seed_candidates, open_intervals, rectangular_obstacle_bounds +from inire.router._compact import compact_port_seed_set, short_shift_seed_set +from inire.router._perimeter import ( + bundle_turnaround_candidates, + perimeter_detour_candidates, + residual_dogleg_candidates, + terminal_link_seed, +) +from inire.router._routing_policy import ( + LockPlan, + _best_trial, + _direct_trials, + _disconnected_nets, + _is_short_shift, + _local_delta, + _residual_problem, + _route_residual, + _trial, +) from inire.router._seed_materialization import materialize_path_seed from inire.router._stack import route_once +from inire.router._topology import plan_corridors from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap from inire.seeds import SBendSeed @@ -36,6 +52,7 @@ if TYPE_CHECKING: from inire.model import NetSpec, RoutingOptions, RoutingProblem from inire.results import RoutingOperation, RoutingResult, RoutingRunResult from inire.router._routing_policy import Trial + from inire.router._topology import Corridor from inire.seeds import PathSeed @@ -164,6 +181,7 @@ class _AutomaticRun: operation: RoutingOperation = "search", planner: str | None = None, policy: str | None = None, + corridors: dict[str, tuple[Corridor, ...]] | None = None, ) -> RoutingRunResult: def notify(_iteration: int, results: dict[str, RoutingResult]) -> None: assert self.iteration_callback is not None @@ -178,6 +196,7 @@ class _AutomaticRun: options=options, iteration_callback=notify if self.iteration_callback else None, phase_timer=time_operation, + corridors=corridors, ) self.metrics.append(run.metrics) return run @@ -256,6 +275,16 @@ class _AutomaticRun: self.cost_pass_performed = True if self._column_trial(True, trials) is None: rejections.append("Cost scoring found no verified column layout") + 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._score) + if shifts is not None: + trial = self._verify(replace(problem, initial_paths=shifts), planner) + complete = len(trial.valid_costs) == len(problem.nets) + trials.append(replace(trial, selectable=complete)) + if not complete: + rejections.append("Local S-bend layout failed full verification") return trials, tuple(rejections) def _column_trial(self, weighted: bool, trials: list[Trial]) -> Trial | None: @@ -368,7 +397,7 @@ class _AutomaticRun: break return trials - def _incumbent_trials(self, options: RoutingOptions, best: Trial) -> list[Trial]: + def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int) -> list[Trial]: problem = self.problem retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs} with self._time("plan", policy="incumbent-retry"): @@ -389,14 +418,47 @@ class _AutomaticRun: return [self._trial(run, stage)] policy = "incumbent-residual" - run, stage = _route_residual(problem, options, "direct-seed", LockPlan(retained), run_route=partial(self._run, policy=policy)) + locks = LockPlan(retained) + run, stage = _route_residual(problem, options, "direct-seed", locks, run_route=partial(self._run, policy=policy)) stage = replace(stage, kind=policy, policy=policy, retry_reason="Residual terminals remain connected with the incumbents locked") trial = self._trial(run, stage) - if len(trial.valid_costs) < len(problem.nets): - return [trial] - seeds = {net_id: result.as_seed() for net_id, result in run.results_by_net.items()} - verified = self._verify(replace(problem, initial_paths=seeds), stage.planner, kind="incumbent-verified", policy=policy) - return [replace(trial, selectable=False), verified] + if len(trial.valid_costs) == len(problem.nets): + return [replace(trial, selectable=False), 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] + joint = self._joint_lane_trial(options, locks, trial) + if joint is not None: + trials.append(replace(joint, selectable=False)) + if joint.improves_on(_best_trial([best, trial])): + trials.append(self._verify_incumbent(joint)) + return trials + + def _verify_incumbent(self, trial: Trial) -> Trial: + seeds = {net_id: trial.run.results_by_net[net_id].as_seed() for net_id in trial.valid_costs} + problem = replace(self.problem, nets=tuple(net for net in self.problem.nets if net.net_id in seeds), initial_paths=seeds) + verified = self._verify(problem, trial.stage.planner, kind="incumbent-verified", policy=trial.stage.policy) + results = {**trial.run.results_by_net, **verified.run.results_by_net} + return replace(verified, run=replace(verified.run, results_by_net=results), selectable=verified.valid_costs.keys() == seeds.keys()) + + def _residual_dogleg_trial(self, options: RoutingOptions, incumbent: Trial) -> Trial | None: + problem = self.problem + if len(incumbent.valid_costs) != len(problem.nets) - 1: + return None + retained = {net_id: incumbent.run.results_by_net[net_id] for net_id in incumbent.valid_costs} + 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" + with self._time("plan", planner=planner, policy=planner): + for seed in islice(residual_dogleg_candidates(residual, options.search), 8): + 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): + return trial + return None def _direct(self, options: RoutingOptions, policy: str) -> list[Trial]: with self._time("plan", planner="direct", policy=policy): @@ -447,6 +509,14 @@ class _AutomaticRun: if len(_best_trial(trials).valid_costs) >= target: return + if target == len(problem.nets) and not problem.initial_paths: + with self._time("plan", planner="column-jogs"): + for seeds in islice(column_jog_candidates(problem, options.search), 8): + trial = self._verify(replace(problem, initial_paths=seeds), "column-jogs") + if len(trial.valid_costs) == target: + trials.append(trial) + return + if len(problem.nets) <= 2: with self._time("plan", planner="perimeter"): trials.extend(self._perimeter_trials(options)) @@ -462,7 +532,7 @@ class _AutomaticRun: return seeded = replace(options, topology=replace(options.topology, mode="seed")) if best.valid_costs and len(problem.nets) > 2 and not problem.initial_paths: - trials.extend(self._incumbent_trials(seeded, best)) + trials.extend(self._incumbent_trials(seeded, best, target)) 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") @@ -477,6 +547,40 @@ class _AutomaticRun: policy="budget-escalation", ) + def _joint_lane_trial(self, options: RoutingOptions, locks: LockPlan, previous: Trial) -> Trial | None: + residual = _residual_problem(self.problem, locks) + if len(residual.nets) < 2: + return None + policy = "joint-portal-lanes" + unresolved = frozenset(net.net_id for net in residual.nets if net.net_id not in previous.valid_costs) + order = options.congestion.net_order + nets = residual.nets + if order != "user": + nets = tuple(sorted(nets, key=lambda net: sum(map(abs, _local_delta(net))), reverse=order == "longest")) + with self._time("plan", planner="corridor-seed", mode="seed", policy=policy): + corridors = plan_corridors( + residual.bounds, + residual.static_obstacles, + nets, + clearance=residual.clearance, + bend_radius=min(options.search.bend_radii, default=0.0), + limit=options.topology.max_corridors, + joint_net_ids=unresolved, + ) + if not corridors: + return None + retry = replace(options, congestion=replace(options.congestion, max_iterations=min(3, options.congestion.max_iterations))) + run, stage = _route_residual( + self.problem, retry, "direct-seed", locks, run_route=partial(self._run, policy=policy, corridors=corridors) + ) + stage = replace( + stage, + policy=policy, + incumbent_net_ids=tuple(locks.direct), + retry_reason="Unresolved nets share a portal with alternative lane assignments", + ) + return self._trial(run, stage) + def _lattice_fallback(self, trials: list[Trial], options: RoutingOptions, reason: str, *, policy: str | None = None) -> None: run = self._run(self.problem, options=replace(options, topology=replace(options.topology, mode="off")), policy=policy) stage = RoutingStage( @@ -540,7 +644,7 @@ class _AutomaticRun: target = min(target, cut.max_routed) if not cut and not conflicts: trials, rejections = self._constructive_trials() - if not 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) self._refine(trials) best = _best_trial(trials) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 6f5219f..d89c697 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -5,13 +5,14 @@ from __future__ import annotations from collections import defaultdict from dataclasses import dataclass from functools import lru_cache -from itertools import combinations_with_replacement, pairwise, product -from math import acos, ceil, cos, floor, gcd, isfinite, isqrt, sin +from itertools import combinations_with_replacement, islice, pairwise, product +from math import acos, ceil, comb, cos, floor, gcd, isfinite, isqrt, pi, sin from typing import TYPE_CHECKING from shapely.geometry import LineString, box from inire.model import resolve_bend_geometry +from inire.router._waypoints import compile_waypoints from inire.seeds import PathSeed, SBendSeed, StraightSeed if TYPE_CHECKING: @@ -19,12 +20,15 @@ if TYPE_CHECKING: from inire.geometry.primitives import Port from inire.model import NetSpec, RoutingProblem, SearchOptions + from inire.router._waypoints import XY from inire.seeds import PathSegmentSeed Profile = tuple[int, ...] Gap = tuple[float, float] Window = tuple[int, int] +JogPivots = tuple[int | None, ...] +JogSchedule = tuple[float, tuple[Profile, ...], tuple[JogPivots, ...]] @dataclass(frozen=True, slots=True) @@ -201,6 +205,8 @@ def _column_profiles( wall_slack: int, modulus: int, reachability: tuple[tuple[Profile, ...], ...] = (), + *, + combinations_limit: int | None = None, ) -> list[Profile]: profiles = set() n = len(widths) @@ -222,7 +228,15 @@ def _column_profiles( tuple(candidate[left:right] for candidate in reachability), ) groups.append(band_cache[key]) - profiles.update(tuple(y for group in chosen for y in group) for chosen in product(*groups)) + combinations = product(*groups) + if combinations_limit is None: + profiles.update(tuple(y for group in chosen for y in group) for chosen in combinations) + else: + for chosen in islice(combinations, combinations_limit): + profiles.add(tuple(y for group in chosen for y in group)) + combinations_limit -= 1 + if combinations_limit == 0: + break return sorted(profiles, key=lambda row: (sum(abs(a - b) for a, b in zip(row, desired, strict=True)), row))[:140] @@ -463,3 +477,132 @@ def column_seed_candidates( if signature not in seen: seen.add(signature) yield _seeds(tracks, windows, moves, radius) + + +def _jog_pivots( + left: Profile, + right: Profile, + window: Window, + widths: tuple[float, ...], + clearance: float, + radius: int, + minimum: float, +) -> JogPivots | None: + # For an upward shift, move the upper tracks first. For a downward + # shift, move the lower tracks first. Opposite shifts have disjoint + # lateral sweeps when both endpoint rows preserve track order. + upward = [i for i in reversed(range(len(left))) if left[i] < right[i]] + downward = [i for i in range(len(left)) if right[i] < left[i]] + pivots: list[int | None] = [None] * len(left) + scheduled: list[int] = [] + for i in (*upward, *downward): + low, high = sorted((left[i], right[i])) + straight = high - low - 2 * radius + if straight < 0 or 0 < straight < minimum: + return None + margin = ceil(radius + max(minimum, clearance + widths[i] / 2)) + pivot = window[0] + margin + for j in scheduled: + pitch = clearance + (widths[i] + widths[j]) / 2 + other_low, other_high = sorted((left[j], right[j])) + if min(high, other_high) + pitch > max(low, other_low): + previous = pivots[j] + assert previous is not None + pivot = max(pivot, previous + ceil(2 * radius + max(minimum, pitch))) + if pivot > window[1] - margin: + return None + pivots[i] = pivot + scheduled.append(i) + return tuple(pivots) + + +def _jog_schedules( + profiles: list[list[Profile]], + windows: tuple[Window, ...], + widths: tuple[float, ...], + clearance: float, + radius: int, + minimum: float, +) -> list[JogSchedule]: + start = profiles[0][0] + approaches: dict[Profile, list[JogSchedule]] = {start: [(0.0, (start,), ())]} + for window, rows in zip(windows, profiles[1:], strict=True): + after = {} + for row in rows: + proposals = [] + for previous, histories in approaches.items(): + pivots = _jog_pivots(previous, row, window, widths, clearance, radius, minimum) + if pivots is None: + continue + length = sum(abs(a - b) for a, b in zip(previous, row, strict=True)) + length += sum(pivot is not None for pivot in pivots) * (pi - 2) * radius + proposals.extend((score + length, (*history, row), (*moves, pivots)) for score, history, moves in histories) + if proposals: + after[row] = sorted(proposals, key=lambda proposal: (proposal[0], proposal[1]))[:3] + approaches = after + if not approaches: + break + return approaches.get(profiles[-1][0], []) + + +def _jog_seeds( + tracks: tuple[_Track, ...], rows: tuple[Profile, ...], moves: tuple[JogPivots, ...], radius: int, search: SearchOptions +) -> dict[str, PathSeed] | None: + seeds = {} + for i, track in enumerate(tracks): + points: list[XY] = [(int(track.left.x), int(track.left.y))] + for (left, right), pivots in zip(pairwise(rows), moves, strict=True): + pivot = pivots[i] + if pivot is not None: + points.extend(((pivot, left[i]), (pivot, right[i]))) + points.append((int(track.right.x), int(track.right.y))) + if track.westbound: + points.reverse() + seed, end = compile_waypoints(tuple(points), track.net.start, radius) + if end != track.net.target or any( + isinstance(move, StraightSeed) and not search.min_straight_length <= move.length <= search.max_straight_length + for move in seed.segments + ): + return None + seeds[track.net.net_id] = seed + return seeds + + +def column_jog_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[dict[str, PathSeed]]: + """Allocate tracks through ordered apertures using staggered 90-degree jogs.""" + if problem.initial_paths: + return + tracks = _ordered_tracks(problem) + if len(tracks) < 3 or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks): + 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 + start, finish = max(int(track.left.x) for track in tracks), 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) > 4096 for column in columns): + return + launch = tuple(int(track.left.y) for track in tracks) + arrival = tuple(int(track.right.y) for track in tracks) + widths = tuple(track.net.width for track in tracks) + spans = ((start, start), *(column.span for column in columns), (finish, finish)) + windows = tuple((after, before) for (_, after), (before, _) in pairwise(spans)) + preferences = [] + for column in columns: + fraction = (sum(column.span) / 2 - start) / (finish - start) + preferences.append(tuple(a + fraction * (b - a) for a, b in zip(launch, arrival, strict=True))) + for slack in (1, 0): + # Modulus one allows any integer track level, independent of the + # set of exact S-bend spans. + interior = [ + _column_profiles(problem, column, widths, (0,) * len(tracks), desired, slack, slack, 1, combinations_limit=8192) + for column, desired in zip(columns, preferences, strict=True) + ] + for radius in radii: + schedules = _jog_schedules( + [[launch], *interior, [arrival]], windows, widths, problem.clearance, radius, search.min_straight_length + ) + for _, rows, moves in schedules: + seeds = _jog_seeds(tracks, rows, moves, radius, search) + if seeds is not None: + yield seeds diff --git a/inire/router/_compact.py b/inire/router/_compact.py index 3dd2022..61e5bc9 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -1,9 +1,9 @@ -"""Fit perpendicular jogs between nearby, parallel terminal columns.""" +"""Construct short links from straight sections and tangent bends.""" from __future__ import annotations from itertools import islice -from math import isfinite +from math import isfinite, sqrt from typing import TYPE_CHECKING from shapely import union_all @@ -12,16 +12,21 @@ from shapely.geometry import box from inire.constants import TOLERANCE_LINEAR from inire.geometry.collision import RoutingWorld from inire.model import resolve_bend_geometry +from inire.results import RoutingResult from inire.router._columns import _exact_spans +from inire.router._routing_policy import _local_delta from inire.router._seed_materialization import materialize_path_seed from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Iterable, Iterator + from shapely.geometry import Polygon from shapely.geometry.base import BaseGeometry + from inire.geometry.components import ComponentResult from inire.model import NetSpec, RoutingProblem, SearchOptions + from inire.router._routing_policy import Scorer from inire.seeds import PathSegmentSeed @@ -103,25 +108,42 @@ def _pack_routes( order = sorted(candidates, key=lambda net_id: len(candidates[net_id])) chosen: dict[str, tuple[PathSeed, BaseGeometry]] = {} remaining = 4096 + choices = [iter(candidates[net_id]) for net_id in order] + index = 0 - def add(index: int) -> bool: - nonlocal remaining - if index == len(order): - return True + while 0 <= index < len(order): net_id = order[index] - for seed, footprint in candidates[net_id]: + chosen.pop(net_id, None) + for seed, footprint in choices[index]: if remaining <= 0: - break + return None remaining -= 1 if any(footprint.distance(other) < clearance - TOLERANCE_LINEAR for _, other in chosen.values()): continue chosen[net_id] = (seed, footprint) - if add(index + 1): - return True - del chosen[net_id] - return False + index += 1 + break + else: + choices[index] = iter(candidates[net_id]) + index -= 1 - return {net_id: value[0] for net_id, value in chosen.items()} if add(0) else None + return {net_id: value[0] for net_id, value in chosen.items()} if index == len(order) else None + + +def _verified_candidates( + net: NetSpec, + world: RoutingWorld, + board: Polygon, + search: SearchOptions, + seeds: Iterable[PathSeed], +) -> Iterator[tuple[PathSeed, BaseGeometry, tuple[ComponentResult, ...]]]: + for seed in seeds: + path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance) + if path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid: + continue + footprint = union_all([polygon for component in path for polygon in component.physical_geometry]) + if board.covers(footprint): + yield seed, footprint, path def compact_port_seed_set(problem: RoutingProblem, search: SearchOptions) -> dict[str, PathSeed] | None: @@ -138,17 +160,65 @@ def compact_port_seed_set(problem: RoutingProblem, search: SearchOptions) -> dic board = box(*problem.bounds) candidates = {} for net in problem.nets: - choices = [] - for seed in islice(_candidate_jogs(net, problem, search, radii), 512): - path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=problem.clearance) - if path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid: - continue - footprint = union_all([polygon for component in path for polygon in component.physical_geometry]) - if board.covers(footprint): - choices.append((seed, footprint)) - if len(choices) == 20: - break + jogs = islice(_candidate_jogs(net, problem, search, radii), 512) + choices = [(seed, footprint) for seed, footprint, _ in islice(_verified_candidates(net, world, board, search, jogs), 20)] if not choices: return None candidates[net.net_id] = choices return _pack_routes(candidates, problem.clearance) + + +def _shift_seeds(forward: int, offset: int, search: SearchOptions) -> Iterator[PathSeed]: + minimum, maximum = search.min_straight_length, search.max_straight_length + if offset == 0: + if minimum <= forward <= maximum: + yield _path(forward) + return + if search.sbend_offsets is not None and offset not in {round(value) for value in search.sbend_offsets}: + return + for radius in search.sbend_radii: + if not isfinite(radius) or not 0 < abs(offset) < 2 * radius: + continue + # The physical arc must meet the snapped straight at the join. + exact = sqrt(abs(offset) * (4 * radius - abs(offset))) + if not isfinite(exact): + continue + span = round(exact) + spare = forward - span + if spare < 0 or abs(exact - span) > 1e-9: + continue + placements = {i * spare // 8 for i in range(9)} + for lead in sorted(placements, key=lambda distance: (abs(2 * distance - spare), distance)): + tail = spare - lead + if all(not length or minimum <= length <= maximum for length in (lead, tail)): + yield _path(lead, SBendSeed(offset, radius), tail) + + +def short_shift_seed_set(problem: RoutingProblem, search: SearchOptions, score: Scorer) -> dict[str, PathSeed] | None: + """Fit exact-span 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: + return None + if any(net.start.r != net.target.r for net in problem.nets): + return None + deltas = [_local_delta(net) for net in problem.nets] + if any(forward <= 0 for forward, _ in deltas) or not any(offset for _, offset in deltas): + return None + seeds_by_net = [tuple(_shift_seeds(int(forward), int(offset), search)) for forward, offset in deltas] + if not all(seeds_by_net): + return None + + world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius) + for obstacle in problem.static_obstacles: + world.add_static_obstacle(obstacle) + board = box(*problem.bounds) + candidates = {} + for net, seeds in zip(problem.nets, seeds_by_net, strict=True): + ranked = [ + (score(RoutingResult(net.net_id, path)), seed, footprint) + for seed, footprint, path in _verified_candidates(net, world, board, search, seeds) + ] + if not ranked: + return None + ranked.sort(key=lambda choice: choice[0]) + candidates[net.net_id] = [(seed, footprint) for _, seed, footprint in ranked] + return _pack_routes(candidates, problem.clearance) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index a81b3fc..a4f3426 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -19,6 +19,86 @@ if TYPE_CHECKING: from inire.router._waypoints import XY +def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[PathSeed]: + """Try four-turn routes through interior gaps with the incumbent geometry locked.""" + if len(problem.nets) != 1 or problem.initial_paths: + return + (net,) = problem.nets + if net.start.r != net.target.r: + return + forward, lateral = ((1, 0), (0, 1), (-1, 0), (0, -1))[int(net.start.r) // 90] + + def project(x: float, y: float) -> tuple[float, float]: + return forward * x + lateral * y, forward * y - lateral * x + + def physical(x: int, y: int) -> XY: + return forward * x - lateral * y, lateral * x + forward * y + + def extent(bounds: tuple[float, float, float, float]) -> tuple[float, float, float, float]: + x0, y0, x1, y1 = bounds + a, b = project(x0, y0), project(x1, y1) + return min(a[0], b[0]), min(a[1], b[1]), max(a[0], b[0]), max(a[1], b[1]) + + start_x, start_y = map(int, project(net.start.x, net.start.y)) + end_x, end_y = map(int, project(net.target.x, net.target.y)) + if end_x <= start_x: + return + half_width = net.width / 2 + pad = problem.clearance + half_width + _, floor_y, _, ceiling_y = extent(problem.bounds) + obstacles = [] + for shape in problem.static_obstacles: + if shape.is_empty: + continue + a, b, c, d = extent(shape.bounds) + if c + pad >= start_x and a - pad <= end_x: + obstacles.append((a - pad, b - pad, c + pad, d + pad)) + + def straight_clear(a: int, b: int, c: int, d: int) -> bool: + left, right = sorted((a, c)) + bottom, top = sorted((b, d)) + return all(right <= x0 or left >= x1 or top <= y0 or bottom >= y1 for x0, y0, x1, y1 in obstacles) + + lanes = {ceil(floor_y + half_width), floor(ceiling_y - half_width)} + for _, bottom, _, top in obstacles: + lanes.update((floor(bottom), ceil(top))) + lanes = {y for y in lanes if floor_y + half_width <= y <= ceiling_y - half_width} + ordered_lanes = sorted(lanes, key=lambda y: (abs(y - start_y) + abs(y - end_y), y)) + minimum, maximum = max(0.0, search.min_straight_length), search.max_straight_length + remaining = 16384 + for radius in sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)}): + first, last = ceil(start_x + radius + minimum), floor(end_x - radius - minimum) + if last - first < 2 * radius: + continue + pivots = {first, last} + for left, _, right, _ in obstacles: + pivots.update((floor(left - radius), ceil(right + radius))) + pivots = sorted(x for x in pivots if first <= x <= last) + entrances = [x for x in pivots if straight_clear(start_x, start_y, x - radius, start_y)] + exits = [x for x in reversed(pivots) if straight_clear(x + radius, end_y, end_x, end_y)] + for y in ordered_lanes: + rises = [sorted((port_y, y)) for port_y in (start_y, end_y)] + if any(high - low < 2 * radius + minimum for low, high in rises): + continue + lower, upper = rises + departures = [x for x in entrances if straight_clear(x, lower[0] + radius, x, lower[1] - radius)] + arrivals = [x for x in exits if straight_clear(x, upper[0] + radius, x, upper[1] - radius)] + for a, b in product(departures, arrivals): + if not remaining: + return + remaining -= 1 + if not 2 * radius + minimum <= b - a <= 2 * radius + maximum: + continue + if not straight_clear(a + radius, y, b - radius, y): + continue + points = tuple(physical(x, h) for x, h in ((start_x, start_y), (a, start_y), (a, y), (b, y), (b, end_y), (end_x, end_y))) + seed, end = compile_waypoints(points, net.start, radius) + if end == net.target and all( + not isinstance(move, StraightSeed) or minimum <= move.length <= maximum for move in seed.segments + ): + yield seed + + def bundle_turnaround_candidates( problem: RoutingProblem, proposal: RoutingProblem, diff --git a/inire/router/_router.py b/inire/router/_router.py index 2c411e6..4c2cbd8 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -305,7 +305,7 @@ class PathFinder: self.context.clear_static_caches() return seeds - def _prepare_topology(self, state: _RoutingState) -> None: + def _prepare_topology(self, state: _RoutingState, corridors: dict[str, tuple[Corridor, ...]] | None) -> None: topology = self.context.options.topology if topology.mode == "bundle": self.topology_report = TopologyReport(seeded_net_ids=tuple(self.context.problem.initial_paths)) @@ -318,14 +318,16 @@ class PathFinder: world = self.context.cost_evaluator.collision_engine for net_id in state.ordered_net_ids: world.remove_path(net_id) - state.corridors = plan_corridors( - self.context.problem.bounds, - world._static_obstacles.geometries.values(), - [state.net_specs[net_id] for net_id in state.ordered_net_ids], - clearance=world.clearance, - bend_radius=min(self.context.options.search.bend_radii, default=0.0), - limit=topology.max_corridors, - ) + if corridors is None: + corridors = plan_corridors( + self.context.problem.bounds, + world._static_obstacles.geometries.values(), + [state.net_specs[net_id] for net_id in state.ordered_net_ids], + clearance=world.clearance, + bend_radius=min(self.context.options.search.bend_radii, default=0.0), + limit=topology.max_corridors, + ) + state.corridors = corridors before = self.metrics.total_nodes_expanded seeds = self._build_corridor_seeds(state) if topology.mode == "seed" and state.corridors else {} if seeds: @@ -336,7 +338,7 @@ class PathFinder: seed_nodes_expanded=self.metrics.total_nodes_expanded - before, ) - def _prepare_state(self) -> _RoutingState: + def _prepare_state(self, corridors: dict[str, tuple[Corridor, ...]] | None = None) -> _RoutingState: problem = self.context.problem congestion = self.context.options.congestion initial_paths = self._materialize_problem_initial_paths() @@ -362,7 +364,7 @@ class PathFinder: recent_attempt_work={}, pre_pair_candidate=None, ) - self._prepare_topology(state) + self._prepare_topology(state, corridors) if state.initial_paths is None and congestion.warm_start_enabled: state.initial_paths = self._build_greedy_warm_start_paths(net_specs, congestion.net_order, state.corridors) self.context.clear_static_caches() @@ -1436,6 +1438,7 @@ class PathFinder: *, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, phase_timer: PhaseTimer | None = None, + corridors: dict[str, tuple[Corridor, ...]] | None = None, ) -> dict[str, RoutingResult]: self.context.congestion_penalty = self.context.options.congestion.base_penalty self.accumulated_expanded_nodes = [] @@ -1447,7 +1450,7 @@ class PathFinder: self.metrics.reset_totals() self.metrics.reset_per_route() - state = self._prepare_state() + state = self._prepare_state(corridors) timed_out = self._run_iterations(state, iteration_callback) self.accumulated_expanded_nodes = list(state.accumulated_expanded_nodes) self._restore_best_iteration(state) diff --git a/inire/router/_routing_policy.py b/inire/router/_routing_policy.py index 3ac58cd..981ad9f 100644 --- a/inire/router/_routing_policy.py +++ b/inire/router/_routing_policy.py @@ -164,6 +164,14 @@ def _plan_locks( return LockPlan(direct, disconnected) +def _residual_problem(problem: RoutingProblem, locks: LockPlan) -> RoutingProblem: + if not locks.direct and not locks.disconnected: + return problem + residual = tuple(net for net in problem.nets if net.net_id not in locks.direct and net.net_id not in locks.disconnected) + locked = tuple(shape for result in locks.direct.values() for shape in result.locked_geometry) + return replace(problem, nets=residual, static_obstacles=problem.static_obstacles + locked) + + def _route_residual( problem: RoutingProblem, options: RoutingOptions, @@ -173,7 +181,8 @@ def _route_residual( run_route: RouteCall = route_once, ) -> tuple[RoutingRunResult, RoutingStage]: direct = locks.direct - residual = tuple(net for net in problem.nets if net.net_id not in direct and net.net_id not in locks.disconnected) + problem = _residual_problem(problem, locks) + residual = problem.nets if not residual: mode = "off" elif policy in ("direct-guide", "direct-seed"): @@ -181,9 +190,6 @@ def _route_residual( else: max_offset = 2 * max(options.search.sbend_radii, default=0) mode = "guide" if any(_is_short_shift(net, max_offset) for net in residual) else "seed" - if direct: - locked = tuple(shape for result in direct.values() for shape in result.locked_geometry) - problem = replace(problem, nets=residual, static_obstacles=problem.static_obstacles + locked) run = run_route(problem, options=replace(options, topology=replace(options.topology, mode=mode))) skipped = tuple(sorted(locks.disconnected)) return ( diff --git a/inire/router/_stack.py b/inire/router/_stack.py index 78be687..69d75d4 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -18,6 +18,7 @@ if TYPE_CHECKING: from inire.model import RoutingOptions, RoutingProblem from inire.results import RoutingResult from inire.router._router import PhaseTimer + from inire.router._topology import Corridor @dataclass(frozen=True, slots=True) @@ -72,13 +73,14 @@ def route_once( options: RoutingOptions, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, phase_timer: PhaseTimer | None = None, + corridors: dict[str, tuple[Corridor, ...]] | None = None, ) -> RoutingRunResult: """Run one explicitly selected routing mode and capture its diagnostics.""" if options.topology.mode == "automatic": raise ValueError("A single routing attempt requires an explicit planner mode") finder = build_routing_stack(problem, options).finder - results = finder.route_all(iteration_callback=iteration_callback, phase_timer=phase_timer) + results = finder.route_all(iteration_callback=iteration_callback, phase_timer=phase_timer, corridors=corridors) if options.topology.mode == "bundle": board = box(*problem.bounds) for result in results.values(): diff --git a/inire/router/_topology.py b/inire/router/_topology.py index a9a221a..50bb0cd 100644 --- a/inire/router/_topology.py +++ b/inire/router/_topology.py @@ -4,7 +4,7 @@ from __future__ import annotations from dataclasses import dataclass, field from heapq import heappop, heappush -from itertools import pairwise +from itertools import pairwise, permutations from math import hypot, inf from typing import TYPE_CHECKING @@ -218,8 +218,14 @@ class _Mesh: target: _Endpoint, reservations: dict[int, BaseGeometry], radius: float, + *, + forced_lane: tuple[Edge, XY] | None = None, ) -> _Assignment: gates = [self.portals[_edge(a, b)].lanes for a, b in pairwise(cells)] + if forced_lane is not None: + edge, lane = forced_lane + gate = next(i for i, (a, b) in enumerate(pairwise(cells)) if _edge(a, b) == edge) + gates[gate] = (lane,) gates.append((target.lead,)) choices = [(0.0, (start.port, start.lead))] for cell, gate in zip(cells, gates, strict=True): @@ -243,6 +249,59 @@ class _Mesh: return _Assignment(cells, (*points, target.port), cost) +def _prepared_reservations(shapes_by_cell: dict[int, list[BaseGeometry]]) -> dict[int, BaseGeometry]: + reservations = {cell: shapely.union_all(shapes) for cell, shapes in shapes_by_cell.items() if shapes} + for reservation in reservations.values(): + shapely.prepare(reservation) + return reservations + + +def _assign_shared_lanes( + mesh: _Mesh, + assignments: dict[str, list[_Assignment]], + endpoints: dict[str, tuple[_Endpoint, _Endpoint]], + users: dict[Edge, list[str]], + occupied: dict[int, list[tuple[str, BaseGeometry]]], + leads: dict[int, list[tuple[str, BaseGeometry]]], + unresolved: frozenset[str], + radius: float, +) -> bool: + shared = [ + (edge, group) + for edge, group in users.items() + if 2 <= len(group) <= min(4, len(mesh.portals[edge].lanes)) and not unresolved.isdisjoint(group) + ] + if not shared: + return False + edge, group = max(shared, key=lambda item: (len(item[1]) / len(mesh.portals[item[0]].lanes), len(item[1]))) + lanes = mesh.portals[edge].lanes + choices = [] + for net_id in group: + cells = assignments[net_id][0].cells + reservations = _prepared_reservations( + { + cell: [shape for owner, shape in occupied.get(cell, ()) if owner not in group] + + [shape for owner, shape in leads.get(cell, ()) if owner != net_id] + for cell in cells + } + ) + start, target = endpoints[net_id] + choices.append([mesh.assign_lanes(cells, start, target, reservations, radius, forced_lane=(edge, lane)) for lane in lanes]) + + # The selected portal has at most nine lanes and at most four users. + def cost(order: tuple[int, ...]) -> float: + return sum(candidates[lane].cost for candidates, lane in zip(choices, order, strict=True)) + + selected = min(permutations(range(len(lanes)), len(group)), key=cost) + changed = False + for net_id, candidates, lane in zip(group, choices, selected, strict=True): + proposal = candidates[lane] + if proposal.points != assignments[net_id][0].points: + assignments[net_id][0] = proposal + changed = True + return changed + + def plan_corridors( bounds: tuple[float, float, float, float], obstacles: Iterable[Polygon], @@ -251,7 +310,9 @@ def plan_corridors( clearance: float, bend_radius: float, limit: int, + joint_net_ids: frozenset[str] = frozenset(), ) -> dict[str, tuple[Corridor, ...]]: + """Plan normal guides, or return a changed assignment for a targeted joint retry.""" if not nets: return {} @@ -273,37 +334,49 @@ def plan_corridors( for cell in mesh.index.query(shape, predicate="intersects"): leads.setdefault(cell, []).append((net.net_id, shape)) - occupied: dict[int, list[BaseGeometry]] = {} + occupied: dict[int, list[tuple[str, BaseGeometry]]] = {} demand: dict[Edge, int] = {} - guides: dict[str, tuple[Corridor, ...]] = {} + users: dict[Edge, list[str]] = {} + assignments_by_net: dict[str, list[_Assignment]] = {} for net in nets: if net.net_id not in endpoints: continue start, target = endpoints[net.net_id] candidates = mesh.alternatives(start, target, demand, limit) candidate_cells = {cell for candidate in candidates for cell in candidate} - overlapping = { - cell: occupied.get(cell, []) + [shape for net_id, shape in leads.get(cell, ()) if net_id != net.net_id] for cell in candidate_cells - } - reservations = {cell: shapely.union_all(shapes) for cell, shapes in overlapping.items() if shapes} - for reservation in reservations.values(): - shapely.prepare(reservation) + reservations = _prepared_reservations( + { + cell: [shape for _, shape in occupied.get(cell, ())] + + [shape for owner, shape in leads.get(cell, ()) if owner != net.net_id] + for cell in candidate_cells + } + ) assignments = sorted( (mesh.assign_lanes(cells, start, target, reservations, bend_radius) for cells in candidates), key=lambda assignment: assignment.cost, ) if not assignments: continue + assignments_by_net[net.net_id] = assignments best = assignments[0] for a, b in pairwise(best.cells): edge = _edge(a, b) demand[edge] = demand.get(edge, 0) + 1 + if joint_net_ids: + users.setdefault(edge, []).append(net.net_id) reservation = LineString(best.points).buffer(mesh.pitch - 0.01) for cell in mesh.index.query(reservation, predicate="intersects"): - occupied.setdefault(cell, []).append(reservation) + occupied.setdefault(cell, []).append((net.net_id, reservation)) + if joint_net_ids and not _assign_shared_lanes(mesh, assignments_by_net, endpoints, users, occupied, leads, joint_net_ids, bend_radius): + return {} + + guides: dict[str, tuple[Corridor, ...]] = {} + for net in nets: + if net.net_id not in assignments_by_net: + continue corridors = [] - for assignment in assignments: + for assignment in assignments_by_net[net.net_id]: line = LineString(assignment.points) region = shapely.union_all([mesh.cells[i] for i in assignment.cells] + [line]) footprint = region.buffer(mesh.pitch + net.width / 2, join_style="mitre").intersection(board) diff --git a/inire/tests/stress_routing_benchmarks.py b/inire/tests/stress_routing_benchmarks.py new file mode 100644 index 0000000..66d6728 --- /dev/null +++ b/inire/tests/stress_routing_benchmarks.py @@ -0,0 +1,281 @@ +"""Feasible fixed placements that stress automatic routing and refinement.""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from itertools import pairwise +from typing import TYPE_CHECKING + +from shapely.geometry import Polygon, box + +from inire import NetSpec, Port, RoutingProblem +from inire.router._waypoints import _direction, compile_waypoints +from inire.tests.routing_benchmarks import BenchmarkCase, _crossing_keepout, _options + +if TYPE_CHECKING: + from inire.router._waypoints import XY + + +@dataclass(frozen=True, slots=True) +class _Track: + name: str + points: tuple[XY, ...] + width: float = 2 + radius: float | None = None + + +def _waypoint_case( + name: str, + description: str, + bounds: tuple[int, int, int, int], + obstacles: tuple[Polygon, ...], + tracks: tuple[_Track, ...], + *, + radius: float = 20, + sbend_radius: float | None = None, + clearance: float = 5, + extra_bend_radius: float | None = None, +) -> BenchmarkCase: + nets = [] + reference = [] + for track in tracks: + heading = _direction(*track.points[:2]) + assert heading is not None + start = Port(*track.points[0], heading) + seed, end = compile_waypoints(track.points, start, track.radius if track.radius is not None else radius) + nets.append(NetSpec(track.name, start, end, track.width)) + reference.append((track.name, seed)) + options = _options(radius, sbend_radius) + if extra_bend_radius is not None: + options = replace(options, search=replace(options.search, bend_radii=(radius, extra_bend_radius))) + problem = RoutingProblem(bounds, tuple(nets), obstacles, clearance=clearance) + return BenchmarkCase(name, description, problem, options, tuple(reference)) + + +def _alternating_doglegs() -> BenchmarkCase: + tracks = [] + for i in range(3): + launch, upper, lower, arrival = 147 + 17 * i, 248 + 18 * i, 88 + 18 * i, 173 + 17 * i + rise, drop, recover = 208 - 45 * i, 446 + 45 * i, 800 - 45 * i + tracks.append(_Track( + f"track_{i}", + ( + (34, launch), (rise, launch), (rise, upper), (drop, upper), (drop, lower), + (recover, lower), (recover, arrival), (1030, arrival), + ), + width=(2, 4, 3)[i], + )) + return _waypoint_case( + "stress-refine-alternating-doglegs", + "Two alternating walls force six-bend routes with overlapping refinement windows and mixed widths", + (0, 0, 1080, 410), + (box(284, 0, 379, 238), box(594, 139, 682, 410)), + tuple(tracks), + extra_bend_radius=24, + ) + + +def _return_shelf() -> BenchmarkCase: + return _waypoint_case( + "stress-refine-return-shelf", + "A folded return skirts a shelf above a neighboring route, with tempting shortcuts across its own arms", + (0, 0, 790, 480), + (box(428, 320, 502, 480), box(250, 145, 340, 168)), + ( + _Track( + "folded_return", + ( + (640, 155), (720, 155), (720, 392), (540, 392), (540, 300), + (390, 300), (390, 392), (150, 392), (150, 230), (555, 230), + ), + ), + _Track("shelf_edge", ((201, 272), (595, 272)), width=4), + _Track("lower_return", ((585, 178), (64, 178))), + _Track("east_shelf", ((675, 438), (610, 438))), + ), + extra_bend_radius=27, + ) + + +def _straight_decoy() -> BenchmarkCase: + return _waypoint_case( + "stress-retry-straight-decoy", + "A tempting straight trunk seals two perpendicular branches unless released; the lower bypass has limited room", + (0, 0, 760, 440), + (box(0, 222, 15, 238), box(745, 222, 760, 238), box(216, 114, 282, 186), box(463, 114, 539, 199)), + ( + _Track("trunk", ((25, 230), (169, 230), (169, 99), (610, 99), (610, 230), (735, 230)), width=4), + _Track("branch_west", ((326, 144), (326, 339))), + _Track("branch_east", ((398, 358), (398, 170)), width=3), + _Track("lower_rail", ((58, 79), (708, 79))), + ), + ) + + +def _compact_shift_bank() -> BenchmarkCase: + return _waypoint_case( + "stress-retry-compact-shift-bank", + "One port pair has only 66 forward units and a large sideways shift; longer peers have obstructed approaches", + (0, 0, 720, 720), + ( + box(0, 230, 720, 242), box(0, 389, 720, 401), box(0, 549, 720, 561), + box(113, 96, 202, 158), box(258, 264, 345, 298), box(337, 426, 447, 460), box(285, 581, 402, 616), + ), + ( + _Track("short", ((45, 117), (78, 117), (78, 202), (111, 202)), width=3), + _Track("middle", ((33, 274), (190, 274), (190, 347), (650, 347)), width=4), + _Track("upper", ((56, 445), (251, 445), (251, 513), (670, 513))), + _Track("top", ((63, 598), (196, 598), (196, 669), (630, 669))), + ), + ) + + +def _mixed_port_bank() -> BenchmarkCase: + return _waypoint_case( + "stress-retry-mixed-port-bank", + "Compact shifts, a perpendicular exit, and a return share a board with narrow turn access", + (0, 0, 680, 540), + ( + box(133, 53, 194, 131), box(452, 221, 498, 291), box(564, 171, 624, 230), + Polygon(((190, 185), (339, 175), (353, 218), (315, 283), (199, 290))), + box(256, 302, 348, 337), box(108, 408, 310, 443), + ), + ( + _Track("east_compact", ((40, 75), (80, 75), (80, 158), (115, 158)), width=3), + _Track("west_compact", ((590, 261), (550, 261), (550, 182), (516, 182)), width=4), + _Track("turning_exit", ((290, 50), (290, 113), (437, 113))), + _Track("upper_shift", ((40, 315), (196, 315), (196, 395), (450, 395))), + _Track("return", ((535, 475), (60, 475))), + ), + ) + + +def _wall(left: int, right: int, height: int, openings: tuple[tuple[int, int], ...]) -> tuple[Polygon, ...]: + return tuple(box(left, lower, right, upper) for (_, lower), (upper, _) in pairwise(((0, 0), *openings, (height, height)))) + + +def _passage_tracks( + banks: tuple[tuple[int, ...], ...], + turn_columns: tuple[int, ...], + finish: int, + widths: tuple[int, ...], + *, + westbound: frozenset[int] = frozenset(), +) -> tuple[_Track, ...]: + tracks = [] + for i, levels in enumerate(zip(*banks, strict=True)): + points = [(30, levels[0])] + for column, (start, end) in zip(turn_columns, pairwise(levels), strict=True): + # The lower tracks turn later while shifting upward. + x = column + 46 * (len(widths) - 1 - i) + points.extend(((x, start), (x, end))) + points.append((finish, levels[-1])) + tracks.append(_Track(f"lane_{i}", tuple(reversed(points)) if i in westbound else tuple(points), width=widths[i])) + return tuple(tracks) + + +def _width_key() -> BenchmarkCase: + return _waypoint_case( + "stress-passage-width-key", + "A one-track slit excludes the widest guides while five guides share the upper aperture and its turn banks", + (0, 0, 1210, 720), + _wall(440, 492, 720, ((246, 260), (340, 443))), + _passage_tracks( + ((64, 81, 99, 118, 135, 153), (253, 354, 372, 390, 408, 426), (498, 515, 533, 551, 569, 587)), + (100, 635), + 1190, + (2, 7, 4, 8, 5, 6), + westbound=frozenset({0, 2, 5}), + ), + ) + + +def _split_merge() -> BenchmarkCase: + return _waypoint_case( + "stress-passage-split-merge", + "Two staggered three-track apertures feed a common passage with opposing launches and mixed guide widths", + (0, 0, 1710, 880), + (*_wall(422, 470, 880, ((243, 293), (374, 439))), *_wall(930, 982, 880, ((523, 618),))), + _passage_tracks( + ( + (53, 70, 87, 105, 123, 141), (252, 269, 285, 384, 403, 426), + (534, 548, 562, 577, 592, 606), (679, 697, 716, 734, 752, 772), + ), + (104, 596, 1110), + 1670, + (3, 5, 2, 4, 6, 3), + westbound=frozenset({0, 3, 5}), + ), + ) + + +def _competing_sbends() -> BenchmarkCase: + return _waypoint_case( + "stress-sbend-competing-slots", + "Opposed exact-span S-bends compete for placement room while two perpendicular links use a fixed crossing", + (0, 0, 450, 320), + (box(104, 130, 120, 135), _crossing_keepout(350, 160)), + ( + _Track("lower_east", ((35, 112), (155, 112), (195, 132), (235, 132)), width=3), + _Track("upper_west", ((235, 141), (95, 141), (55, 121), (35, 121)), width=3), + _Track("south_access", ((330, 52), (330, 74), (350, 114), (350, 146))), + _Track("north_access", ((350, 174), (350, 212), (330, 252), (330, 284))), + ), + radius=25, + clearance=4, + ) + + +def _off_lattice_crossing() -> BenchmarkCase: + return _waypoint_case( + "stress-crossing-off-lattice-slot", + "An odd offset defeats exact S-bend placement while a second approach must bend inside a short launch pocket", + (0, 0, 500, 460), + (_crossing_keepout(260, 230), box(245, 272, 273, 317), box(145, 193, 176, 214)), + ( + _Track("west_odd_shift", ((34, 213), (106, 213), (106, 230), (246, 230))), + _Track("east_exact_shift", ((274, 230), (330, 230), (370, 250), (465, 250)), radius=25), + _Track("north_pocket", ((260, 244), (260, 263), (309, 263), (309, 344), (260, 344), (260, 429)), width=3), + _Track("south_exact_shift", ((240, 30), (240, 115), (260, 155), (260, 216)), radius=25), + ), + radius=6, + sbend_radius=25, + clearance=4, + extra_bend_radius=15, + ) + + +def _crossings_with_detour() -> BenchmarkCase: + return _waypoint_case( + "stress-crossings-shared-outside-detour", + "Two preplaced crossings have easy local links, but a long net must detour around the entire south approach bank", + (0, 0, 625, 397), + (_crossing_keepout(220, 180), _crossing_keepout(355, 180), box(160, 69, 415, 81), box(102, 216, 144, 261)), + ( + _Track("west_link", ((32, 160), (113, 160), (153, 180), (206, 180)), radius=25), + _Track("device_link", ((234, 180), (341, 180))), + _Track("east_link", ((369, 180), (459, 180), (499, 200), (581, 200)), radius=25), + _Track("west_south", ((220, 87), (220, 166))), + _Track("east_south", ((355, 166), (355, 90))), + _Track("west_north", ((220, 194), (220, 224), (200, 264), (200, 317)), radius=25), + _Track("east_north", ((375, 315), (375, 265), (355, 225), (355, 194)), radius=25), + _Track("outside_lower", ((35, 130), (100, 130), (100, 51), (505, 51), (505, 130), (590, 130)), width=4), + _Track("outside_upper", ((589, 353), (33, 353))), + ), + sbend_radius=25, + clearance=4, + ) + + +STRESS_BENCHMARK_CASES = ( + _alternating_doglegs(), + _return_shelf(), + _straight_decoy(), + _compact_shift_bank(), + _mixed_port_bank(), + _width_key(), + _split_merge(), + _competing_sbends(), + _off_lattice_crossing(), + _crossings_with_detour(), +) diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 8886554..41c6b38 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -7,7 +7,7 @@ import pytest from shapely import union_all from shapely.geometry import Point, box, shape -from inire import NetSpec, Port, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route +from inire import Bend90Seed, NetSpec, Port, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route from inire.constants import TOLERANCE_LINEAR from inire.router._automatic import _AutomaticRun from inire.router._routing_policy import _disconnected_nets @@ -19,6 +19,7 @@ from inire.tests.routing_benchmarks import ( FALLBACK_BENCHMARK_CASES, VALIDATION_BENCHMARK_CASES, ) +from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from scripts.compare_topological_routing import ( _direct_trials, _geometry_json, @@ -32,11 +33,42 @@ def _measure(case, options, strategy): return _measure_selected_mode(case, _mode_options(options, strategy), strategy) +@pytest.mark.routing_corpus @pytest.mark.parametrize( "case", [ pytest.param(case, id=case.name) - for case in (*BENCHMARK_CASES, *VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *CROSSING_BENCHMARK_CASES) + for case in ( + *BENCHMARK_CASES, *VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES, *CROSSING_BENCHMARK_CASES, + *STRESS_BENCHMARK_CASES, + ) + ], +) +def test_automatic_reaches_corpus_routing_bound(case) -> None: + options = replace( + case.options, + search=replace(case.options.search, node_limit=500), + topology=replace(case.options.topology, seed_node_limit=500), + congestion=replace(case.options.congestion, max_iterations=3), + ) + run = route(case.problem, options=_mode_options(options, "automatic", "matched-budget")) + + assert run.automatic is not None + assert run.results_by_net.keys() == {net.net_id for net in case.problem.nets} + verified = {net_id for net_id, result in run.results_by_net.items() if result.is_valid} + expected = {"overloaded-gate": 3, "lidar-clements-8x8": 3}.get(case.name, len(case.problem.nets)) + assert run.automatic.max_routed == expected + assert set(run.automatic.verified_net_ids) == verified + assert len(verified) == expected + + +@pytest.mark.parametrize( + "case", + [ + pytest.param(case, id=case.name) + for case in ( + *BENCHMARK_CASES, *VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES + ) if case.reference_paths ], ) @@ -60,6 +92,50 @@ def test_benchmark_reference_paths_are_feasible(case) -> None: assert a.distance(b) >= problem.clearance - TOLERANCE_LINEAR +def test_stress_cases_start_unseeded_with_complete_reference_paths() -> None: + assert len({case.name for case in STRESS_BENCHMARK_CASES}) == len(STRESS_BENCHMARK_CASES) + for case in STRESS_BENCHMARK_CASES: + assert not case.problem.initial_paths + assert dict(case.reference_paths).keys() == {net.net_id for net in case.problem.nets} + search = case.options.search + for _, seed in case.reference_paths: + for move in seed.segments: + if isinstance(move, StraightSeed): + assert search.min_straight_length <= move.length <= search.max_straight_length + elif isinstance(move, Bend90Seed): + assert move.radius in search.bend_radii + elif isinstance(move, SBendSeed): + assert move.radius in search.sbend_radii + + +def test_stress_folded_return_can_be_refined_with_the_other_tracks_present() -> None: + case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-refine-return-shelf") + reference = dict(case.reference_paths) + options = replace( + case.options, + search=replace(case.options.search, node_limit=1), + congestion=replace(case.options.congestion, max_iterations=1), + ) + + run = route(replace(case.problem, initial_paths=reference), options=options) + + assert all(result.is_valid for result in run.results_by_net.values()) + assert run.metrics.nodes_expanded == 0 + assert run.results_by_net["folded_return"].as_seed() != reference["folded_return"] + + +def test_stress_opposed_sbends_fit_together_without_search() -> None: + case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-sbend-competing-slots") + options = replace(case.options, topology=TopologyOptions(mode="automatic")) + + run = route(case.problem, options=options) + + assert run.automatic is not None + assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} + assert run.automatic.selected_planner == "local-sbend" + assert run.metrics.nodes_expanded == 0 + + def test_automatic_routes_an_unseeded_grid_between_preplaced_crossing_ports() -> None: case = next(case for case in CROSSING_BENCHMARK_CASES if case.name == "crossing-aligned-grid") assert not case.problem.initial_paths @@ -75,8 +151,28 @@ def test_automatic_routes_an_unseeded_grid_between_preplaced_crossing_ports() -> assert path[-1].end_port == net.target +def test_automatic_constructs_an_exact_sbend_grid() -> None: + case = next(case for case in CROSSING_BENCHMARK_CASES if case.name == "crossing-staggered-grid") + options = replace(case.options, topology=TopologyOptions(mode="automatic")) + + run = route(case.problem, options=options) + + assert run.automatic is not None + assert run.automatic.selected_planner == "local-sbend" + assert len(run.automatic.verified_net_ids) == len(case.problem.nets) + assert run.metrics.nodes_expanded == 0 + for net in case.problem.nets: + path = run.results_by_net[net.net_id].path + assert path[0].start_port == net.start + assert path[-1].end_port == net.target + assert sum(move.move_type == "sbend" for move in path) == 1 + + 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") + first, *others = case.problem.nets + # An odd shift has no exact forward span at this radius, so use guide search. + problem = replace(case.problem, nets=(replace(first, target=first.target.translate(dy=1)), *others)) options = replace( case.options, search=replace(case.options.search, node_limit=101), @@ -84,7 +180,7 @@ def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None: topology=TopologyOptions(mode="automatic"), ) - report = route(case.problem, options=options).automatic + report = route(problem, options=options).automatic assert report is not None guided = [stage for stage in report.stages if stage.operation == "search" and stage.mode == "guide"] @@ -332,13 +428,40 @@ def test_automatic_retry_releases_a_lock_that_disconnects_the_remaining_net() -> first = _direct_trials(case.problem, board, options, "direct-guide")[0] assert tuple(first.valid_costs) == ("horizontal",) - [retry] = _AutomaticRun(case.problem, options, None)._incumbent_trials(options, first) + [retry] = _AutomaticRun(case.problem, options, None)._incumbent_trials(options, first, len(case.problem.nets)) assert retry.stage.kind == "incumbent-retry" assert retry.stage.incumbent_net_ids == ("horizontal",) assert retry.stage.retry_reason == "Incumbents disconnect vertical when locked" +def test_joint_portal_lane_retry_keeps_incumbents_and_verifies_another_net() -> None: + problem = RoutingProblem( + (0, 0, 580, 360), + tuple( + NetSpec(f"track{i}", Port(35, left, 0), Port(545, right, 0)) + for i, (left, right) in enumerate(zip((45, 78, 114, 142, 173, 214), (130, 159, 187, 210, 249, 286), strict=True)) + ), + (box(265, 0, 315, 103.5), box(265, 136.5, 315, 206), box(265, 242, 315, 360)), + clearance=5, + ) + options = RoutingOptions(search=SearchOptions(node_limit=500, bend_radii=(20,), sbend_radii=(20,))) + planner = _AutomaticRun(problem, options, None) + attempts = replace(options, refinement=replace(options.refinement, enabled=False)) + small = replace(attempts, search=replace(attempts.search, node_limit=100)) + first = planner._direct(small, "direct-probe-near-port")[0] + + trials = planner._incumbent_trials(attempts, first, len(problem.nets)) + + ordinary, joint, verified = trials + assert set(ordinary.valid_costs) == set(first.valid_costs) == {"track2", "track5"} + assert joint.stage.policy == verified.stage.policy == "joint-portal-lanes" + assert set(joint.stage.incumbent_net_ids) == set(first.valid_costs) + assert not joint.selectable + assert verified.selectable + assert set(verified.valid_costs) == {"track2", "track3", "track5"} + + def test_automatic_weighted_scoring_preserves_coverage_and_reduces_cost() -> None: case = next(case for case in BENCHMARK_CASES if case.name == "bypass-interleaved-directions") baseline = _measure(case, case.options, "automatic-span") diff --git a/pyproject.toml b/pyproject.toml index e4031c4..82db859 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,4 +91,5 @@ addopts = "-rsXx" testpaths = ["inire"] markers = [ "performance: opt-in runtime regression checks against example-like routing scenarios", + "routing_corpus: matched-budget coverage checks on the routing regression suite", ] diff --git a/scripts/compare_topological_routing.py b/scripts/compare_topological_routing.py index bf68960..2493227 100644 --- a/scripts/compare_topological_routing.py +++ b/scripts/compare_topological_routing.py @@ -28,6 +28,7 @@ from inire.tests.routing_benchmarks import ( FALLBACK_BENCHMARK_CASES, VALIDATION_BENCHMARK_CASES, ) +from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from inire.tests.terminal_bench_scenario import LENGTH_COST if TYPE_CHECKING: @@ -294,7 +295,8 @@ def _geometry_json(value: object) -> dict: def main() -> None: broader = (*VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) - case_groups = {case.name: (case,) for case in (*BENCHMARK_CASES, *broader, *CROSSING_BENCHMARK_CASES)} + corpus = (*BENCHMARK_CASES, *broader, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES) + case_groups = {case.name: (case,) for case in corpus} case_groups.update( { "all": BENCHMARK_CASES, @@ -304,6 +306,8 @@ def main() -> None: "external": EXTERNAL_BENCHMARK_CASES, "broad": broader, "crossings": CROSSING_BENCHMARK_CASES, + "stress": STRESS_BENCHMARK_CASES, + "corpus": corpus, } ) defaults = RoutingOptions() @@ -313,7 +317,7 @@ def main() -> None: "--case", choices=tuple(case_groups), action="append", - help="Select a case or suite. The broad suite includes the holdout, fallback, and external suites.", + help="Select a case or suite. Use 'corpus' to select all boards.", ) parser.add_argument("--list", action="store_true", help="List the available cases.") parser.add_argument( @@ -337,12 +341,14 @@ def main() -> None: parser.add_argument("--json", type=Path, help="Write options and individual runs to this file.") args = parser.parse_args() if args.list: + print("All boards (--case corpus)") for group, title in ( ("all", "Core corpus"), ("holdout", "Held-out boards"), ("fallback", "Fallback cases"), ("external", "External cases"), ("crossings", "Preplaced crossings"), + ("stress", "Stress cases"), ): print(f"{title} (--case {group})") for case in case_groups[group]: