From 7476209ef394ae279a6053e1f94d9757d60a858b Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 22:30:29 -0800 Subject: [PATCH] Require triangulation and simplify automatic routing Remove the dependency fallback and joint portal lane retry, make tiered search opt-in, and consolidate tests while adding low-length-cost routing boards. --- README.md | 2 +- docs/benchmarks.md | 4 +- docs/complex-routing-example-1.md | 18 ++-- docs/development.md | 2 +- docs/user/api-reference.md | 2 +- docs/user/tune-and-troubleshoot.md | 4 +- inire/__init__.py | 7 ++ inire/model.py | 2 +- inire/router/_automatic.py | 62 ++------------ inire/router/_stack.py | 3 +- inire/router/_topology.py | 84 ++----------------- inire/tests/routing_corpus.py | 3 +- inire/tests/routing_expanded_benchmarks.py | 75 ++++++++++++++++- inire/tests/test_api.py | 58 ++++++------- inire/tests/test_capacity.py | 20 ++--- inire/tests/test_clearance_precision.py | 97 ---------------------- inire/tests/test_collision.py | 28 ++++--- inire/tests/test_congestion.py | 73 ---------------- inire/tests/test_failed_net_congestion.py | 23 ++--- inire/tests/test_performance_reporting.py | 21 +++-- inire/tests/test_routing_benchmarks.py | 27 ------ inire/tests/test_routing_fixtures.py | 10 +++ inire/tests/test_terminal_bench.py | 11 ++- inire/tests/test_topology.py | 9 +- pyproject.toml | 2 +- scripts/render_complex_routing_example.py | 17 ++-- scripts/render_documentation_figures.py | 2 +- uv.lock | 2 +- 28 files changed, 222 insertions(+), 446 deletions(-) delete mode 100644 inire/tests/test_clearance_precision.py delete mode 100644 inire/tests/test_congestion.py diff --git a/README.md b/README.md index 9c0192c..db8e725 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Inire routes photonic and RF layouts with straights, 90-degree bends, and S-bend ## Install -From a checkout with Python 3.11 or newer, run `pip install .`. +From a checkout with Python 3.11 or newer, run `pip install .`. Inire requires Shapely 2.1 or newer and checks at import that Shapely is linked against GEOS 3.10 or newer. ## Route a net diff --git a/docs/benchmarks.md b/docs/benchmarks.md index bf0c16a..aa38282 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -22,13 +22,15 @@ Expect `3/4 valid`. All four nets need to cross a vertical cut where the opening | Seeds, custom bend geometry, and fallback behavior | `broad` includes caller seeds, custom bends, imported layouts, and held-out boards. | | Ports on placed devices | `crossings` exercises external legs to preplaced crossing cells. | | Lock ordering, tight turns, and competing passages | `stress` runs known-feasible folded returns, competing locks, and shared passages. | -| Tight geometry, complex layouts, search limits, or scaling | `expanded` runs 72 additional boards. Use `geometry-corners`, `complex-layouts`, `search-challenges`, or `scaling` to focus on one group. | +| Tight geometry, complex layouts, search limits, or scaling | `expanded` runs 75 additional boards. Use `geometry-corners`, `complex-layouts`, `search-challenges`, or `scaling` to focus on one group. | | A retry tuned on the regression corpus | `retry-holdout` tests related but separate return shelves, bypasses, and competing trunks. | List cases with `python -m scripts.compare_topological_routing --list`. Start with the smallest case that exhibits the behavior. `pytest -m routing_corpus` runs regression coverage checks for the corpus and the retry holdouts. Use `pytest -m retry_holdout` to run just the holdout coverage checks. +`pytest -m routing_corpus -k search-low-length-cost` also checks the three low-length-cost boards with their original 80- or 130-node lattice budgets. The `low-length-cost` case group selects these boards for comparisons under the standard benchmark profiles. + - [Fixture sources and regeneration](benchmark-fixtures.md) ## Choose a profile diff --git a/docs/complex-routing-example-1.md b/docs/complex-routing-example-1.md index ba17777..7fb32d3 100644 --- a/docs/complex-routing-example-1.md +++ b/docs/complex-routing-example-1.md @@ -72,25 +72,25 @@ The point-terminal variant accepts a westbound arrival for `net_08`, so the orig Each run uses 100 nodes per search and one congestion iteration, with warm start and refinement disabled. Set `infer_terminal_headings=True` for `bundle` so `net_08` can arrive westbound. Fixed eastbound headings raise a mismatch in that mode. -| Mode | With triangulation available | Without triangulation | -| --- | --- | --- | -| `automatic` | 9/9 verified. The turnaround plan completes the layout without building a mesh. | 9/9 verified through the same turnaround plan. Automatic uses lattice search if constructive planning leaves work. | -| `off` | 0/9 verified at this budget. The worker runs lattice search directly. | Same search and result. | -| `guide` | 1/9 verified. The worker builds a mesh and suggests corridors to lattice search. | Raises a dependency error when planning corridors. | -| `seed` | 1/9 verified. The worker builds a mesh and searches for starting paths inside the corridors before its routing iteration. | Raises a dependency error when planning corridors. | -| `bundle` | 9/9 verified. The worker builds and verifies ordered tracks directly from the board geometry. | Same plan and result. | +| Mode | Result | +| --- | --- | +| `automatic` | 9/9 verified. The turnaround plan completes the layout without building a mesh. | +| `off` | 0/9 verified at this budget. The worker runs lattice search directly. | +| `guide` | 1/9 verified. The worker builds a mesh and suggests corridors to lattice search. | +| `seed` | 1/9 verified. The worker builds a mesh and searches for starting paths inside the corridors before its routing iteration. | +| `bundle` | 9/9 verified. The worker builds and verifies ordered tracks directly from the board geometry. | ![Five panels show route outcomes at the same search budget. Automatic and bundle verify all nine nets. Off, guide, and seed leave partial paths.](figures/complex-routing-example-1-modes.png) ### Triangulation support -An active corridor search needs Shapely 2.1+ with GEOS 3.10+. Check the versions in the environment that runs Inire. +Inire requires Shapely 2.1 or newer with GEOS 3.10 or newer. Check the versions in the environment that runs Inire. ```sh python -c 'import shapely; print(shapely.__version__, shapely.geos_version_string)' ``` -Automatic builds a mesh when it reaches corridor search on a compatible backend. Here the turnaround plan finishes first. Shapely 2.0.7 supports lattice and constructive routing. Guide and seed can also replay supplied paths without a mesh at `node_limit=0`. +Automatic builds a mesh when it reaches corridor search. Here the turnaround plan finishes first. Guide and seed also replay supplied paths without a mesh at `node_limit=0`. - [Shapely installation](https://shapely.readthedocs.io/en/2.1.2/installation.html) - [Constrained triangulation API](https://shapely.readthedocs.io/en/2.1.2/reference/shapely.constrained_delaunay_triangles.html) diff --git a/docs/development.md b/docs/development.md index 0394363..78923df 100644 --- a/docs/development.md +++ b/docs/development.md @@ -20,7 +20,7 @@ 3. For a cleanup that should preserve paths, capture both revisions and run an [exact parity comparison](routing-diagnostics.md#reproduce-and-compare). Include callbacks or traces if the change affects them. 4. For a policy or budget change, start with a case that exhibits the behavior. Compare verified IDs, cost, and work under the same [benchmark profile](benchmarks.md#choose-a-profile). Check the corpus and related holdouts before adopting the change. -Build release archives with `uv build`. The wheel contains the runtime. The source archive also includes tests and fixtures. Smoke-test the wheel outside the checkout on Python 3.11 with Shapely 2.0.7, once with NumPy 1.26 and once with NumPy 2.x. +Build release archives with `uv build`. The wheel contains the runtime. The source archive also includes tests and fixtures. Smoke-test the wheel outside the checkout on Python 3.11 with Shapely 2.1.0 and GEOS 3.10 or newer, once with NumPy 1.26 and once with NumPy 2.x. ### Check a documentation figure diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index 2e5cd22..5cf2bf9 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -127,7 +127,7 @@ Increase the iteration limit when later reroutes might resolve conflicts. Adjust | `max_iterations` | `10` | Nonnegative integer maximum for congestion iterations per attempt. Automatic's initial probe may use fewer. Zero skips warm-start and corridor searches. | | `base_penalty` | `100.0` | Finite, nonnegative initial penalty for overlapping other routes. | | `multiplier` | `1.5` | Finite, nonnegative penalty multiplier between unresolved iterations. | -| `use_tiered_strategy` | `True` | Allow a cheaper bend proxy in the first iteration when applicable. | +| `use_tiered_strategy` | `False` | Opt into a first iteration without congestion scoring when corridor guidance is absent. That iteration substitutes the clipped bounding-box proxy when the configured proxy is `arc`. | | `net_order` | `"user"` | Start from input order or sort by the sum of the horizontal and vertical distances between ports with `"shortest"` or `"longest"`. | | `warm_start_enabled` | `True` | Build greedy seeds before congestion iterations. | | `shuffle_nets` | `False` | Shuffle routing order between iterations. | diff --git a/docs/user/tune-and-troubleshoot.md b/docs/user/tune-and-troubleshoot.md index dd45200..662b70a 100644 --- a/docs/user/tune-and-troubleshoot.md +++ b/docs/user/tune-and-troubleshoot.md @@ -35,9 +35,9 @@ Set `TopologyOptions(mode=...)` and pass it as `topology` in `RoutingOptions`. ### Mode requirements -- Guide and seed modes need Shapely 2.1 or later with GEOS 3.10 or later when planning corridors. Nets that receive no corridor can use ordinary lattice search. A caller-supplied seed takes precedence over a generated one. Set `node_limit=0` to verify supplied seeds without planning corridors. [Constrained triangulation requirements](https://shapely.readthedocs.io/en/2.1.2/reference/shapely.constrained_delaunay_triangles.html) +- Inire requires Shapely 2.1 or newer with GEOS 3.10 or newer. In guide and seed modes, nets that receive no corridor can use ordinary lattice search. A caller-supplied seed takes precedence over a generated one. Set `node_limit=0` to verify supplied seeds without planning corridors. [Constrained triangulation requirements](https://shapely.readthedocs.io/en/2.1.2/reference/shapely.constrained_delaunay_triangles.html) - Use `infer_terminal_headings` with automatic or bundle mode if your ports may change direction and the layout supports bundle planning. Compare fixed and flexible headings in [complex-routing example 1](../../examples/advanced.md#complex-routing-example-1). -- Automatic starts with smaller budgets and can retry up to your ceiling. When corridor planning is unavailable, it can fall back to lattice search. +- Automatic starts with smaller budgets and can retry up to your ceiling. It can try lattice search after constructive planning and corridor-guided search leave unresolved nets. [Compare all five modes on one board](../complex-routing-example-1.md#compare-all-routing-modes) diff --git a/inire/__init__.py b/inire/__init__.py index e9fa22f..9bf069f 100644 --- a/inire/__init__.py +++ b/inire/__init__.py @@ -5,6 +5,7 @@ import warnings from collections.abc import Callable from dataclasses import replace +import shapely as _shapely from shapely.geometry import Polygon as _Polygon from .geometry.components import _has_port_face @@ -44,6 +45,12 @@ from .results import ( # noqa: PLC0414 ) from .seeds import Bend90Seed as Bend90Seed, PathSeed as PathSeed, SBendSeed as SBendSeed, StraightSeed as StraightSeed # noqa: PLC0414 +if _shapely.geos_version < (3, 10, 0): + raise ImportError( + "Inire requires GEOS 3.10 or newer. " + f"Shapely is linked against GEOS {_shapely.geos_version_string}." + ) + __author__ = 'Jan Petykiewicz' __version__ = '0.1' diff --git a/inire/model.py b/inire/model.py index 9c925ef..3661639 100644 --- a/inire/model.py +++ b/inire/model.py @@ -270,7 +270,7 @@ class CongestionOptions: max_iterations: int = 10 base_penalty: float = 100.0 multiplier: float = 1.5 - use_tiered_strategy: bool = True + use_tiered_strategy: bool = False net_order: NetOrder = "user" warm_start_enabled: bool = True shuffle_nets: bool = False diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index ad632c1..f7face4 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -21,7 +21,6 @@ from inire.router._columns import ( column_jog_candidates, column_partition_budget_exceeded, column_recovery_candidates, column_recovery_subproblems, column_seed_candidates, ) from inire.router._compact import compact_port_seed_set, short_shift_seed_set -from inire.router._congestion_policy import ordered_nets from inire.router._perimeter import ( bundle_turnaround_candidates, perimeter_detour_candidates, @@ -36,13 +35,11 @@ from inire.router._routing_policy import ( _disconnected_nets, _is_short_shift, _residual_problem, - _route_prepared_residual, _route_residual, _trial, ) from inire.router._seed_materialization import materialize_path_seed, seed_preparation_error from inire.router._stack import RoutingAttempts -from inire.router._topology import constrained_triangulation_available, plan_corridors from inire.router.cost import build_native_cost_evaluator, weighted_path_length from inire.router.refiner import PathRefiner from inire.seeds import SBendSeed @@ -56,7 +53,6 @@ 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.router.cost import CostEvaluator from inire.seeds import PathSeed @@ -131,17 +127,11 @@ class _AutomaticRun: operation: RoutingOperation = "search", planner: str | None = None, policy: str | None = None, - corridors: dict[str, tuple[Corridor, ...]] | None = None, ) -> RoutingRunResult: mode = options.topology.mode time_operation = partial(self._time, planner=planner or _planner_for_mode(mode), mode=mode, policy=policy) with time_operation(operation): - return self.attempts.run( - problem, - options=options, - phase_timer=time_operation, - corridors=corridors, - ) + return self.attempts.run(problem, options=options, phase_timer=time_operation) def _selection_cost(self, result: RoutingResult) -> float: if not self.options.search.node_limit: @@ -429,24 +419,18 @@ class _AutomaticRun: return [self._trial(run, stage)] policy = "incumbent-residual" - locks = LockPlan(retained) - residual = _residual_problem(problem, locks) - run, stage = _route_prepared_residual(residual, options, locks, residual_mode="seed", run_route=partial(self._run, policy=policy)) + run, stage = _route_residual( + problem, options, LockPlan(retained), residual_mode="seed", 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 [replace(trial, selection="requires-layout-check"), self._verify_incumbent(trial)] - trials = [trial] if len(trial.valid_costs) < target: 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")) - if joint.improves_on(_best_trial([best, trial])): - trials.append(self._verify_incumbent(joint)) - return trials + return [trial] def _verify_incumbent(self, trial: Trial) -> Trial: problem = self._seeded_problem(trial) @@ -708,36 +692,6 @@ class _AutomaticRun: 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: - 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) - nets = ordered_nets(residual.nets, options.congestion.net_order) - with self._time("plan", planner="corridor-seed", mode="seed", policy=policy): - corridors = plan_corridors( - residual.bounds, - residual._blocking_polygons, - 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_prepared_residual( - residual, retry, locks, residual_mode="seed", 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( @@ -814,11 +768,7 @@ class _AutomaticRun: if not cut and not conflicts: trials, rejections = self._constructive_trials() if not any(trial.selectable for trial in trials) or len(_best_trial(trials).valid_costs) < target: - if constrained_triangulation_available(): - self._search_trials(trials, target) - else: - worker = replace(options, refinement=replace(options.refinement, enabled=False)) - self._lattice_fallback(trials, worker, "Constrained triangulation is unavailable") + self._search_trials(trials, target) refinement_choice = self._refine(trials) best = refinement_choice or _best_trial(trials) metrics = self.attempts.metrics() diff --git a/inire/router/_stack.py b/inire/router/_stack.py index 02585e5..ff1b3b7 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -127,11 +127,10 @@ class RoutingAttempts: *, options: RoutingOptions, phase_timer: PhaseTimer | None = None, - corridors: dict[str, tuple[Corridor, ...]] | None = None, ) -> RoutingRunResult: result = route_once( problem, options=options, iteration_callback=self.callback, phase_timer=phase_timer, - corridors=corridors, iteration_offset=self.iterations, + iteration_offset=self.iterations, ) self.iterations += result.metrics.route_iterations self.samples.append(result.metrics) diff --git a/inire/router/_topology.py b/inire/router/_topology.py index 50b1d3b..663f5c9 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, permutations +from itertools import pairwise from math import hypot, inf from typing import TYPE_CHECKING @@ -93,17 +93,10 @@ def _edge(a: int, b: int) -> Edge: return (a, b) if a < b else (b, a) -def constrained_triangulation_available() -> bool: - return callable(getattr(shapely, "constrained_delaunay_triangles", None)) and shapely.geos_version >= (3, 10) - - class _Mesh: def __init__( self, board: Polygon, obstacles: Iterable[Polygon], margin: float, clearance: float, *, relief: float = 0.0, round_joins: bool = False, ) -> None: - if not constrained_triangulation_available(): - raise RuntimeError("Topological routing requires Shapely 2.1 and GEOS 3.10 or newer") - self.pitch = max(1.0, 2 * margin + clearance) self.board = board self.margin = margin @@ -259,14 +252,8 @@ 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): @@ -297,52 +284,6 @@ def _prepared_reservations(shapes_by_cell: dict[int, list[BaseGeometry]]) -> dic 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 _endpoint_access( mesh: _Mesh, nets: Sequence[NetSpec], @@ -374,11 +315,9 @@ def _plan_lane_assignments( *, bend_radius: float, limit: int, - joint_net_ids: frozenset[str], ) -> dict[str, list[_Assignment]]: - occupied: dict[int, list[tuple[str, BaseGeometry]]] = {} + occupied: dict[int, list[BaseGeometry]] = {} demand: dict[Edge, int] = {} - users: dict[Edge, list[str]] = {} assignments_by_net: dict[str, list[_Assignment]] = {} for net in nets: if net.net_id not in endpoints: @@ -388,8 +327,7 @@ def _plan_lane_assignments( candidate_cells = {cell for candidate in candidates for cell in candidate} reservations = _prepared_reservations( { - cell: [shape for _, shape in occupied.get(cell, ())] - + [shape for owner, shape in leads.get(cell, ()) if owner != net.net_id] + cell: occupied.get(cell, []) + [shape for owner, shape in leads.get(cell, ()) if owner != net.net_id] for cell in candidate_cells } ) @@ -404,14 +342,10 @@ def _plan_lane_assignments( 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((net.net_id, reservation)) + occupied.setdefault(cell, []).append(reservation) - if joint_net_ids and not _assign_shared_lanes(mesh, assignments_by_net, endpoints, users, occupied, leads, joint_net_ids, bend_radius): - return {} return assignments_by_net @@ -445,9 +379,8 @@ 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.""" + """Plan clearance-aware corridor guides for the requested nets.""" if not nets: return {} @@ -457,16 +390,11 @@ def plan_corridors( def plan_group(group: Sequence[NetSpec], width: float, *, recover: bool = False) -> tuple[dict[str, tuple[Corridor, ...]], BaseGeometry]: mesh = _Mesh(board, keepouts, width / 2, clearance, relief=8 * TOLERANCE_LINEAR if recover else 0.0, round_joins=recover) endpoints, leads = _endpoint_access(mesh, group, bend_radius) - assignments = _plan_lane_assignments( - mesh, group, endpoints, leads, bend_radius=bend_radius, limit=limit, joint_net_ids=joint_net_ids - ) + assignments = _plan_lane_assignments(mesh, group, endpoints, leads, bend_radius=bend_radius, limit=limit) return _build_corridors(mesh, board, group, assignments, bend_radius), mesh.free widest = max(net.width for net in nets) guides, shared_space = plan_group(nets, widest) - if joint_net_ids: - return guides - # Keep shared assignments and add routes through passages opened by the narrower margin. by_width: dict[float, list[NetSpec]] = {} for net in nets: diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index 4eb06f9..6ad0aad 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, SEARCH_CASES +from inire.tests.routing_expanded_benchmarks import COMPLEX_CASES, CORNER_CASES, LOW_LENGTH_COST_CASES, SCALING_CASES, SEARCH_CASES from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from inire.tests.terminal_bench_scenario import LENGTH_COST @@ -54,6 +54,7 @@ CASE_GROUPS = { "geometry-corners": CORNER_CASES, "complex-layouts": COMPLEX_CASES, "search-challenges": SEARCH_CASES, + "low-length-cost": LOW_LENGTH_COST_CASES, "scaling": SCALING_CASES, "expanded": (*CORNER_CASES, *COMPLEX_CASES, *SEARCH_CASES, *SCALING_CASES), "retry-holdout": RETRY_HOLDOUT_CASES, diff --git a/inire/tests/routing_expanded_benchmarks.py b/inire/tests/routing_expanded_benchmarks.py index cf8e270..6337859 100644 --- a/inire/tests/routing_expanded_benchmarks.py +++ b/inire/tests/routing_expanded_benchmarks.py @@ -9,13 +9,16 @@ from typing import TYPE_CHECKING from shapely.affinity import scale from shapely.geometry import Polygon, box -from inire import Bend90Seed, FixedRoute, NetSpec, PathSeed, Port, SBendSeed, StraightSeed +from inire import ( + Bend90Seed, CongestionOptions, FixedRoute, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions, + RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, +) +from inire.tests.routing_benchmark_case import BenchmarkCase from inire.tests.routing_crossing_benchmarks import _crossing_grid from inire.tests.stress_routing_benchmarks import _Track, _wall, _waypoint_case if TYPE_CHECKING: from inire.seeds import PathSegmentSeed - from inire.tests.routing_benchmark_case import BenchmarkCase def _on_grid(case: BenchmarkCase, grid_nm: int) -> BenchmarkCase: @@ -337,6 +340,73 @@ COMPLEX_CASES = ( _crossings("complex-crossing-4x4", 4, 4, 116, 108, staggered=True), ) +def _low_length_cost_case( + name: str, + description: str, + start: Port, + target: Port, + keepouts: tuple[Polygon, ...], + radii: tuple[int, int, int], + reference: PathSeed, + *, + node_limit: int, + bend_penalty: float, +) -> BenchmarkCase: + problem = RoutingProblem((0, 0, 200, 140), (NetSpec("track", start, target, width=4),), keepouts, clearance=2) + options = RoutingOptions( + search=SearchOptions( + node_limit=node_limit, bend_radii=radii, sbend_radii=radii[1:], distance_heuristic_weight=10, + ), + objective=ObjectiveWeights( + unit_length_cost=0.05, bend_penalty=bend_penalty, sbend_penalty=2 * bend_penalty, danger_weight=0, + ), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), + refinement=RefinementOptions(enabled=False), + topology=TopologyOptions(mode="off"), + ) + return BenchmarkCase(f"search-low-length-cost-{name}", description, problem, options, (("track", reference),), grid_nm=1000) + + +LOW_LENGTH_COST_CASES = ( + _low_length_cost_case( + "north-launch", + "A north-facing launch bends around staggered keepouts to an east-facing target", + Port(16, 89, 90), Port(157, 61, 0), + (box(101, 79, 143, 133), box(62, 58, 106, 122), box(85, 64, 112, 100)), + (15, 20, 25), + PathSeed(( + Bend90Seed(25, "CW"), Bend90Seed(15, "CW"), StraightSeed(38), Bend90Seed(25, "CCW"), StraightSeed(38), SBendSeed(25, 20), + )), + node_limit=80, + bend_penalty=30, + ), + _low_length_cost_case( + "blocked-straight", + "A low-cost straight approach must turn around a keepout before shifting onto the arrival row", + Port(13, 25, 0), Port(152, 36, 0), + (box(91, 14, 121, 41), box(101, 74, 110, 96), box(87, 60, 127, 90)), + (10, 20, 25), + PathSeed(( + StraightSeed(49), StraightSeed(13), Bend90Seed(10, "CCW"), Bend90Seed(20, "CW"), SBendSeed(-19, 25), StraightSeed(7), + )), + node_limit=80, + bend_penalty=250, + ), + _low_length_cost_case( + "south-launch", + "A south-facing launch must reach a high east-facing target past several offset keepouts", + Port(15, 79, 270), Port(184, 119, 0), + (box(97, 44, 123, 65), box(96, 94, 129, 134), box(44, 9, 58, 52)), + (11, 20, 25), + PathSeed(( + Bend90Seed(20, "CCW"), Bend90Seed(25, "CCW"), StraightSeed(35), Bend90Seed(11, "CW"), Bend90Seed(20, "CW"), + StraightSeed(9), StraightSeed(5), Bend90Seed(20, "CCW"), SBendSeed(43, 25), StraightSeed(23), + )), + node_limit=130, + bend_penalty=5, + ), +) + SEARCH_CASES = ( _comb("1x2", 1, 2, 10), _comb("1x4", 1, 4, 12), @@ -346,6 +416,7 @@ SEARCH_CASES = ( _comb("4x6", 4, 6, 15), _comb("5x5", 5, 5, 20), _comb("6x7", 6, 7, 20), + *LOW_LENGTH_COST_CASES, ) SCALING_CASES = ( diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 8cedea5..6cbb8a1 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -1,3 +1,5 @@ +import subprocess +import sys from contextlib import nullcontext from dataclasses import replace @@ -570,8 +572,11 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(monkeypatch) -> Non def fail_on_proximity(*_args): pytest.fail("Geometry-only verification built a proximity map") + def fail_on_triangulation(*_args): + pytest.fail("Geometry-only verification tried to triangulate the board") + monkeypatch.setattr(DangerMap, "precompute", fail_on_proximity) - monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) + monkeypatch.setattr(shapely, "constrained_delaunay_triangles", fail_on_triangulation) callbacks = [] run = route(problem, options=options) with_callback = route(problem, options=options, iteration_callback=lambda index, results: callbacks.append((index, results))) @@ -624,24 +629,6 @@ def test_lattice_length_cost_units_preserve_search_order() -> None: assert small.metrics.nodes_expanded == large.metrics.nodes_expanded -def test_partial_path_tracks_geometric_progress_without_cost_heuristic() -> None: - heuristic = 1.5 - price = 0 - net = NetSpec("across", Port(5, 20, 0), Port(90, 20, 0)) - problem = RoutingProblem((0, 0, 100, 40), (net,), (box(45, 0, 55, 40),)) - options = RoutingOptions( - search=SearchOptions(node_limit=5, greedy_h_weight=heuristic, bend_radii=(), sbend_radii=()), - objective=ObjectiveWeights(price, 0, 0, 0), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - - assert run.results_by_net["across"].outcome == "partial" - - def test_coincident_ports_are_reported_without_blocking_the_batch() -> None: net = NetSpec("abutting", Port(30, 20, 0), Port(30.4, 20.4, 0)) peer = NetSpec("peer", Port(10, 60, 0), Port(70, 60, 0)) @@ -761,17 +748,22 @@ def test_unsafe_seeds_report_segments_without_allocating_geometry(monkeypatch: p assert traced[net_id].seed_error == result.report.seed_error -def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(monkeypatch) -> None: - monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) - net = NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)) - problem = RoutingProblem((0, 0, 100, 100), (net,)) - options = RoutingOptions(search=SearchOptions(bend_radii=(), sbend_radii=()), refinement=RefinementOptions(enabled=False)) - - run = route(problem, options=options) - - assert run.results_by_net["line"].is_valid - assert run.automatic is not None - assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback" +def test_import_rejects_unsupported_geos() -> None: + proc = subprocess.run( + [ + sys.executable, + "-c", + "import shapely\n" + "shapely.geos_version = (3, 9, 0)\n" + "shapely.geos_version_string = '3.9.0'\n" + "import inire", + ], + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode != 0 + assert "ImportError: Inire requires GEOS 3.10 or newer. Shapely is linked against GEOS 3.9.0." in proc.stderr def test_routes_report_boundary_violations_in_results_and_diagnostics() -> None: @@ -880,7 +872,7 @@ def test_congestion_retry_includes_keepout_collision_alongside_peer_conflicts() assert run.results_by_net["static"].report.static_collision_count == 1 -def test_first_lattice_pass_accepts_fractional_turn_with_keepout_inside_its_bounding_box() -> None: +def test_tiered_search_accepts_a_fractional_turn_with_keepout_inside_its_bounding_box() -> None: problem = RoutingProblem( (0, 0, 100, 100), nets=(NetSpec("bend", Port(20, 20, 0), Port(31, 31, 90)),), @@ -889,7 +881,7 @@ def test_first_lattice_pass_accepts_fractional_turn_with_keepout_inside_its_boun ) options = RoutingOptions( search=SearchOptions(bend_radii=(10.25,), sbend_radii=(), node_limit=100), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=True), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) @@ -898,6 +890,8 @@ def test_first_lattice_pass_accepts_fractional_turn_with_keepout_inside_its_boun assert result.is_valid assert result.as_seed() == PathSeed((Bend90Seed(10.25, "CCW"),)) + [bend] = result.path + assert bend.collision_geometry != bend.physical_geometry def test_route_verification_detects_physical_bend_overlap() -> None: diff --git a/inire/tests/test_capacity.py b/inire/tests/test_capacity.py index a37b990..1e88bdd 100644 --- a/inire/tests/test_capacity.py +++ b/inire/tests/test_capacity.py @@ -6,21 +6,9 @@ from shapely.geometry import Polygon, box from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route from inire.results import CapacityLimit from inire.router._capacity import cut_capacity -from inire.tests.routing_corpus import CASE_GROUPS -def test_cut_capacity_requires_rectangular_obstacles() -> None: - (case,) = CASE_GROUPS["overloaded-gate"] - bound = cut_capacity(case.problem, case.options) - assert bound is not None - assert (bound.crossing_nets, bound.tracks, bound.max_routed) == (4, 3, case.routing_bound) - - triangle = Polygon([(10, 10), (20, 10), (10, 20)]) - changed = replace(case.problem, static_obstacles=(*case.problem.static_obstacles, triangle)) - assert cut_capacity(changed, case.options) is None - - -def test_cut_capacity_counts_overlapping_rectangles_and_strict_crossings() -> None: +def test_cut_capacity_counts_strict_crossings_and_requires_rectangular_obstacles() -> None: through = tuple(NetSpec(str(y), Port(5, y, 0), Port(95, y, 0)) for y in (15, 40, 75)) arriving = NetSpec("arriving", Port(5, 45, 0), Port(46, 45, 0)) departing = NetSpec("departing", Port(44, 50, 0), Port(95, 50, 0)) @@ -28,7 +16,11 @@ def test_cut_capacity_counts_overlapping_rectangles_and_strict_crossings() -> No obstacles = (box(20, 0, 50, 30), box(20, 5, 50, 15), box(40, 34, 60, 100)) problem = RoutingProblem((0, 0, 100, 100), (*through, arriving, departing, vertical), obstacles, clearance=1) - assert cut_capacity(problem, RoutingOptions()) == CapacityLimit(45, 3, 1, 4) + options = RoutingOptions() + assert cut_capacity(problem, options) == CapacityLimit(45, 3, 1, 4) + + triangle = Polygon([(10, 10), (20, 10), (10, 20)]) + assert cut_capacity(replace(problem, static_obstacles=(*obstacles, triangle)), options) is None @pytest.mark.parametrize( diff --git a/inire/tests/test_clearance_precision.py b/inire/tests/test_clearance_precision.py deleted file mode 100644 index c4f7342..0000000 --- a/inire/tests/test_clearance_precision.py +++ /dev/null @@ -1,97 +0,0 @@ -from inire import CongestionOptions, RoutingOptions, RoutingProblem, SearchOptions -from inire.geometry.collision import RoutingWorld -from inire.geometry.primitives import Port -from inire.model import NetSpec -from inire.router._astar_types import AStarContext -from inire.router._router import PathFinder -from inire.router.cost import CostEvaluator -from inire.router.danger_map import DangerMap - - -def _build_pathfinder( - evaluator: CostEvaluator, - *, - bounds: tuple[float, float, float, float], - netlist: dict[str, tuple[Port, Port]], - net_widths: dict[str, float], - search: SearchOptions | None = None, - congestion: CongestionOptions | None = None, -) -> PathFinder: - nets = tuple( - NetSpec(net_id=net_id, start=start, target=target, width=net_widths.get(net_id, 2.0)) - for net_id, (start, target) in netlist.items() - ) - return PathFinder( - AStarContext( - evaluator, - RoutingProblem(bounds=bounds, nets=nets), - RoutingOptions( - search=SearchOptions() if search is None else search, - congestion=CongestionOptions() if congestion is None else congestion, - ), - ), - ) - -def test_verify_all_nets_cases(): - """ - Validate that verify_all_nets catches some common cases and doesn't flag reasonable non-failing cases. - """ - engine = RoutingWorld(clearance=2.0) - danger_map = DangerMap(bounds=(0, 0, 100, 100)) - danger_map.precompute([]) - evaluator = CostEvaluator(collision_engine=engine, danger_map=danger_map) - - # Case 1: Parallel paths exactly at clearance (Should be VALID) - netlist_parallel_ok = { - "net1": (Port(0, 50, 0), Port(100, 50, 0)), - "net2": (Port(0, 54, 0), Port(100, 54, 0)), - } - net_widths = {"net1": 2.0, "net2": 2.0} - - results = _build_pathfinder( - evaluator, - bounds=(0, 0, 100, 100), - netlist=netlist_parallel_ok, - net_widths=net_widths, - congestion=CongestionOptions(warm_start_enabled=False, max_iterations=1), - ).route_all() - assert results["net1"].is_valid, f"Exactly at clearance should be valid, collisions={results['net1'].collisions}" - assert results["net2"].is_valid - - # Case 2: Parallel paths slightly within clearance (Should be INVALID) - netlist_parallel_fail = { - "net3": (Port(0, 20, 0), Port(100, 20, 0)), - "net4": (Port(0, 23, 0), Port(100, 23, 0)), - } - # Reset engine - engine.remove_path("net1") - engine.remove_path("net2") - - results_p = _build_pathfinder( - evaluator, - bounds=(0, 0, 100, 100), - netlist=netlist_parallel_fail, - net_widths=net_widths, - congestion=CongestionOptions(warm_start_enabled=False, max_iterations=1), - ).route_all() - # verify_all_nets should flag both as invalid because they cross-collide - assert not results_p["net3"].is_valid - assert not results_p["net4"].is_valid - - # Case 3: Crossing paths (Should be INVALID) - netlist_cross = { - "net5": (Port(0, 75, 0), Port(100, 75, 0)), - "net6": (Port(50, 0, 90), Port(50, 100, 90)), - } - engine.remove_path("net3") - engine.remove_path("net4") - - results_c = _build_pathfinder( - evaluator, - bounds=(0, 0, 100, 100), - netlist=netlist_cross, - net_widths=net_widths, - congestion=CongestionOptions(warm_start_enabled=False, max_iterations=1), - ).route_all() - assert not results_c["net5"].is_valid - assert not results_c["net6"].is_valid diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index e9aa755..8569235 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -105,17 +105,25 @@ def test_verify_path_report_distinguishes_long_net_ids_with_shared_prefix() -> N assert engine.metrics.total_verify_dynamic_candidate_nets == 1 -def test_verify_path_rejects_insufficient_clearance_after_translation() -> None: - width = 1 - 0.099 +def test_verify_path_preserves_the_clearance_boundary_after_translation() -> None: + clearance = 0.1 + width_at_clearance = 1 - clearance for y in (1, 50): - engine = RoutingWorld(clearance=0.1) - tested = Straight.generate(Port(0, y, 0), 20, width) - peer = Straight.generate(Port(0, y + 1, 0), 20, width) - engine.add_route("peer", (peer,)) - assert not engine.verify_path_report("query", (tested,)).is_valid - engine.remove_path("peer") - engine.add_static_obstacle(peer.physical_geometry[0]) - assert not engine.verify_path_report("query", (tested,)).is_valid + path = (Straight.generate(Port(0, y, 0), 20, width_at_clearance),) + for peer_width, collision_count in ((width_at_clearance, 0), (width_at_clearance + 0.002, 1)): + world = RoutingWorld(clearance=clearance) + peer = Straight.generate(Port(0, y + 1, 0), 20, peer_width) + + world.add_route("peer", (peer,)) + dynamic = world.verify_path_report("query", path) + assert dynamic.dynamic_collision_count == collision_count + assert dynamic.is_valid == (collision_count == 0) + + world.remove_path("peer") + world.add_static_obstacle(peer.physical_geometry[0]) + static = world.verify_path_report("query", path) + assert static.static_collision_count == collision_count + assert static.is_valid == (collision_count == 0) def test_rectangular_board_includes_its_edges_and_custom_board_keeps_its_hole() -> None: diff --git a/inire/tests/test_congestion.py b/inire/tests/test_congestion.py deleted file mode 100644 index 3e27511..0000000 --- a/inire/tests/test_congestion.py +++ /dev/null @@ -1,73 +0,0 @@ -import pytest - -from inire import CongestionOptions, RoutingOptions, RoutingProblem, SearchOptions -from inire.geometry.collision import RoutingWorld -from inire.geometry.primitives import Port -from inire.model import NetSpec -from inire.router._astar_types import AStarContext, SearchRunConfig -from inire.router._search import route_astar -from inire.router.cost import CostEvaluator -from inire.router.danger_map import DangerMap - -BOUNDS = (0, -40, 100, 40) - - -@pytest.fixture -def basic_evaluator() -> CostEvaluator: - engine = RoutingWorld(clearance=2.0) - # Wider bounds to allow going around (y from -40 to 40) - danger_map = DangerMap(bounds=BOUNDS) - danger_map.precompute([]) - return CostEvaluator(engine, danger_map, bend_penalty=50.0, sbend_penalty=150.0) - - -def _build_context( - evaluator: CostEvaluator, - *, - bounds: tuple[float, float, float, float], - nets: tuple[NetSpec, ...] = (), - search: SearchOptions | None = None, - congestion: CongestionOptions | None = None, -) -> AStarContext: - return AStarContext( - evaluator, - RoutingProblem(bounds=bounds, nets=nets), - RoutingOptions( - search=SearchOptions() if search is None else search, - congestion=CongestionOptions() if congestion is None else congestion, - ), - ) - - -def _route(context: AStarContext, start: Port, target: Port) -> object: - return route_astar( - start, - target, - net_width=2.0, - context=context, - config=SearchRunConfig.from_options(context.options), - ) - - -def test_astar_sbend(basic_evaluator: CostEvaluator) -> None: - context = _build_context( - basic_evaluator, - bounds=BOUNDS, - search=SearchOptions(sbend_offsets=(2.0, 5.0)), - ) - # Start at (0,0), target at (50, 2) -> 2um lateral offset - # This matches one of our discretized SBend offsets. - start = Port(0, 0, 0) - target = Port(50, 2, 0) - path = _route(context, start, target) - - assert path is not None - # Check if any component in the path is an SBend - found_sbend = False - for res in path: - # Check if the end port orientation is same as start - # and it's not a single straight (which would have y=0) - if abs(res.end_port.y - start.y) > 0.1 and abs(res.end_port.r - start.r) < 0.1: - found_sbend = True - break - assert found_sbend diff --git a/inire/tests/test_failed_net_congestion.py b/inire/tests/test_failed_net_congestion.py index 38d7815..9dc8e9b 100644 --- a/inire/tests/test_failed_net_congestion.py +++ b/inire/tests/test_failed_net_congestion.py @@ -1,24 +1,27 @@ from shapely.geometry import box -from inire import CongestionOptions, NetSpec, Port, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions +from inire import ( + CongestionOptions, NetSpec, ObjectiveWeights, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, +) from inire.router._stack import build_routing_stack -def test_partial_path_is_returned_without_installing_it() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("blocked", Port(0, 50, 0), Port(100, 50, 0)),), - static_obstacles=(box(40, 40, 60, 60),), - ) +def test_zero_cost_search_returns_progress_without_installing_the_partial_path() -> None: + net = NetSpec("blocked", Port(5, 20, 0), Port(90, 20, 0)) + keepout = box(45, 0, 55, 40) + problem = RoutingProblem((0, 0, 100, 40), (net,), (keepout,)) options = RoutingOptions( - search=SearchOptions(node_limit=10, bend_radii=(), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + search=SearchOptions(node_limit=5, greedy_h_weight=1.5, bend_radii=(), sbend_radii=()), + objective=ObjectiveWeights(0, 0, 0, 0), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), + refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) stack = build_routing_stack(problem, options) - result = stack.finder.route_all()["blocked"] + result = stack.finder.route_all()[net.net_id] assert result.outcome == "partial" assert result.path + assert net.start.x < result.path[-1].end_port.x < keepout.bounds[0] assert not stack.world.has_dynamic_paths() diff --git a/inire/tests/test_performance_reporting.py b/inire/tests/test_performance_reporting.py index f5cd1c3..0e74b93 100644 --- a/inire/tests/test_performance_reporting.py +++ b/inire/tests/test_performance_reporting.py @@ -6,7 +6,7 @@ from pathlib import Path import pytest from inire.tests import trace_recording -from scripts import record_conflict_trace, record_frontier_trace, record_iteration_trace, record_pre_pair_frontier_trace +from scripts import record_frontier_trace, record_iteration_trace, record_pre_pair_frontier_trace def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario(tmp_path: Path) -> None: @@ -73,9 +73,11 @@ def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario( assert report.rstrip() in entry -def test_record_conflict_trace_script_writes_selected_scenario(tmp_path: Path) -> None: +def test_record_conflict_trace_script_writes_both_selected_scenarios(tmp_path: Path) -> None: repo_root = Path(__file__).resolve().parents[2] script_path = repo_root / "scripts" / "record_conflict_trace.py" + regular = "example_05_orientation_stress" + performance = trace_recording.NO_WARM_START_SCENARIOS[0] subprocess.run( [ @@ -84,7 +86,9 @@ def test_record_conflict_trace_script_writes_selected_scenario(tmp_path: Path) - "--output-dir", str(tmp_path), "--scenario", - "example_05_orientation_stress", + regular, + "--scenario", + performance, ], check=True, ) @@ -92,19 +96,22 @@ def test_record_conflict_trace_script_writes_selected_scenario(tmp_path: Path) - payload = json.loads((tmp_path / "conflict_trace.json").read_text()) assert payload["generated_at"] assert payload["generator"] == "scripts/record_conflict_trace.py" - assert [entry["name"] for entry in payload["scenarios"]] == ["example_05_orientation_stress"] - assert (tmp_path / "conflict_trace.md").exists() + assert [entry["name"] for entry in payload["scenarios"]] == [regular, performance] + markdown = (tmp_path / "conflict_trace.md").read_text() + assert markdown.startswith("# Conflict Trace\n") + for entry in payload["scenarios"]: + assert entry["conflict_trace"] + assert f"## {entry['name']}" in markdown @pytest.mark.parametrize( ("report", "generate", "heading"), [ - ("conflict_trace", record_conflict_trace.main, "# Conflict Trace"), ("frontier_trace", record_frontier_trace.main, "# Frontier Trace"), ("iteration_trace", record_iteration_trace.main, "# Iteration Trace"), ("pre_pair_frontier_trace", record_pre_pair_frontier_trace.main, "# Pre-Pair Frontier Trace"), ], - ids=["conflict", "frontier", "iteration", "pre-pair-frontier"], + ids=["frontier", "iteration", "pre-pair-frontier"], ) def test_record_trace_reports_support_a_performance_only_scenario( report, generate, heading, tmp_path, monkeypatch, example_07_no_warm_start_trace, diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 74528a1..1f9e09d 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -253,33 +253,6 @@ def test_automatic_retry_releases_a_lock_that_disconnects_the_remaining_net() -> 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, *_ = trials - assert set(first.valid_costs) == {"track2", "track5"} - assert joint.stage.policy == "joint-portal-lanes" - assert set(joint.stage.incumbent_net_ids) == set(first.valid_costs) - assert not joint.selectable - assert set(ordinary.valid_costs) <= {"track2", "track3", "track5"} - assert any(trial.selectable and set(trial.valid_costs) == {"track2", "track3", "track5"} for trial in trials) - - 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/inire/tests/test_routing_fixtures.py b/inire/tests/test_routing_fixtures.py index 64f5f25..5908a9b 100644 --- a/inire/tests/test_routing_fixtures.py +++ b/inire/tests/test_routing_fixtures.py @@ -10,11 +10,13 @@ from inire.constants import TOLERANCE_LINEAR from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES from inire.tests.routing_benchmarks import BENCHMARK_CASES, COMPLEX_BENCHMARK_CASES, EXTERNAL_BENCHMARK_CASES from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options, select_cases +from inire.tests.routing_expanded_benchmarks import LOW_LENGTH_COST_CASES from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES _RETRY_HOLDOUT_NAMES = {case.name for case in RETRY_HOLDOUT_CASES} _EXTERNAL_CASE_NAMES = {case.name for case in EXTERNAL_BENCHMARK_CASES} +_LOW_LENGTH_COST_NAMES = {case.name for case in LOW_LENGTH_COST_CASES} _PLANNER_WITHOUT_SEARCH = { "competing-detours": "paired-perimeter", "crossing-staggered-grid": "local-sbend", @@ -39,6 +41,10 @@ def test_automatic_reaches_corpus_routing_bound(case) -> None: if case.name in _EXTERNAL_CASE_NAMES: _check_external_fixture(case) reference_run = _check_reference_paths(case) if case.reference_paths else None + if case.name in _LOW_LENGTH_COST_NAMES: + bounded = route(case.problem, options=case.options) + assert sum(result.is_valid for result in bounded.results_by_net.values()) == case.routing_bound + assert 0 < bounded.metrics.nodes_expanded <= case.options.search.node_limit profile = "corpus-regression" options = automatic_options(profile_options(case, profile), profile) @@ -80,6 +86,10 @@ def test_automatic_reaches_corpus_routing_bound(case) -> None: if case.name == "pic-splitter-tree-1x8-ew": assert any(stage.policy == "direct-lookahead-hinted" for stage in run.automatic.stages) assert run.automatic.stages[run.automatic.selected_stage].kind == "incumbent-verified" + if case.name == "overloaded-gate": + capacity = run.automatic.capacity_limit + assert capacity is not None + assert (capacity.crossing_nets, capacity.tracks, capacity.max_routed) == (4, 3, case.routing_bound) if case.name == "fallback-custom-physical": assert run.automatic.selected_planner == "lattice" assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback" diff --git a/inire/tests/test_terminal_bench.py b/inire/tests/test_terminal_bench.py index a160e7d..f22c834 100644 --- a/inire/tests/test_terminal_bench.py +++ b/inire/tests/test_terminal_bench.py @@ -119,7 +119,7 @@ def test_bundle_retries_the_next_common_radius_when_the_shelf_cannot_use_the_fir } == {BEND_RADIUS} -def test_bundle_without_triangulation_replays_with_resolved_ports(monkeypatch: pytest.MonkeyPatch) -> None: +def test_bundle_replays_with_resolved_ports_without_building_a_mesh(monkeypatch: pytest.MonkeyPatch) -> None: problem = terminal_bench_problem() options = replace( terminal_bench_options(node_limit=100, max_iterations=1), @@ -127,9 +127,12 @@ def test_bundle_without_triangulation_replays_with_resolved_ports(monkeypatch: p diagnostics=DiagnosticsOptions(capture_iteration_trace=True), ) callbacks = [] - with monkeypatch.context() as old_geos: - old_geos.setattr(shapely, "geos_version", (3, 9, 0)) - run = route(problem, options=options, iteration_callback=lambda index, _: callbacks.append(index)) + + def fail_on_triangulation(*_args: object) -> None: + pytest.fail("Bundle construction or replay tried to triangulate the board") + + monkeypatch.setattr(shapely, "constrained_delaunay_triangles", fail_on_triangulation) + run = route(problem, options=options, iteration_callback=lambda index, _: callbacks.append(index)) assert len(callbacks) >= 2 assert [entry.iteration for entry in run.iteration_trace] == callbacks[-1:] diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py index c56f07f..bb82252 100644 --- a/inire/tests/test_topology.py +++ b/inire/tests/test_topology.py @@ -87,7 +87,12 @@ def test_offset_gate_search_uses_exact_clearance(narrow_by) -> None: topology=TopologyOptions(mode="guide"), ) - assert route(problem, options=options).results_by_net["gate"].is_valid == (narrow_by == 0) + result = route(problem, options=options).results_by_net["gate"] + + assert result.is_valid == (narrow_by == 0) + if narrow_by == 0: + bends = [move for move in result.as_seed().segments if isinstance(move, SBendSeed)] + assert bends == [SBendSeed(6, 10)] def test_rounded_keepout_guidance_preserves_acute_aperture() -> None: @@ -142,7 +147,7 @@ def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytes return _Assignment(cells, (start.port, target.port), 1.0) monkeypatch.setattr(_Mesh, "assign_lanes", equal_cost) - assignments = _plan_lane_assignments(mesh, problem.nets, endpoints, leads, bend_radius=50, limit=2, joint_net_ids=frozenset()) + assignments = _plan_lane_assignments(mesh, problem.nets, endpoints, leads, bend_radius=50, limit=2) assert [assignment.cells for assignment in assignments["detour"]] == paths diff --git a/pyproject.toml b/pyproject.toml index 624c867..e442040 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ dynamic = ["version"] dependencies = [ "numpy>=1.26,<3", "scipy", - "shapely>=2.0.7,<3", + "shapely>=2.1,<3", "rtree", "matplotlib", ] diff --git a/scripts/render_complex_routing_example.py b/scripts/render_complex_routing_example.py index 9163d97..07cd341 100644 --- a/scripts/render_complex_routing_example.py +++ b/scripts/render_complex_routing_example.py @@ -20,7 +20,7 @@ from inire.geometry.intervals import open_intervals from inire.router._bundle import _identify_layout, plan_ordered_bundle from inire.router._seed_materialization import materialize_path_seed from inire.router._stack import route_once -from inire.router._topology import _build_corridors, _endpoint_access, _Mesh, _plan_lane_assignments, constrained_triangulation_available +from inire.router._topology import _build_corridors, _endpoint_access, _Mesh, _plan_lane_assignments from inire.router._waypoints import export_waypoints from scripts.render_documentation_figures import EDGE, INK, MUTED, _board, _polygon, _save, plt @@ -181,7 +181,7 @@ def _guide_figure(directory: Path, problem: RoutingProblem, options: RoutingOpti mesh = _Mesh(board, single.static_obstacles, net.width / 2, single.clearance) endpoints, leads = _endpoint_access(mesh, single.nets, radius) assignments = _plan_lane_assignments( - mesh, single.nets, endpoints, leads, bend_radius=radius, limit=options.topology.max_corridors, joint_net_ids=frozenset(), + mesh, single.nets, endpoints, leads, bend_radius=radius, limit=options.topology.max_corridors, ) corridors = _build_corridors(mesh, board, single.nets, assignments, radius) config = replace( @@ -221,7 +221,7 @@ def _guide_figure(directory: Path, problem: RoutingProblem, options: RoutingOpti _save(fig, directory, f"{COMPLEX_EXAMPLE}-guide.png") -def _modes_figure(directory: Path, problem: RoutingProblem, options: RoutingOptions, *, triangulation: bool) -> None: +def _modes_figure(directory: Path, problem: RoutingProblem, options: RoutingOptions) -> None: config = replace( options, search=replace(options.search, node_limit=100), @@ -232,11 +232,6 @@ def _modes_figure(directory: Path, problem: RoutingProblem, options: RoutingOpti fig, panels = plt.subplots(3, 2, figsize=(10, 7), layout="constrained") fig.suptitle("One congestion iteration ยท 100 nodes per search", color=INK, fontsize=13) for ax, mode in zip(panels.ravel()[:-1], modes, strict=True): - if mode in ("guide", "seed") and not triangulation: - ax.set_title(mode, loc="left", color=INK, fontsize=11) - ax.text(0.5, 0.5, "Requires constrained triangulation", color=MUTED, ha="center", transform=ax.transAxes) - ax.set_axis_off() - continue settings = replace(config, topology=replace(config.topology, mode=mode, infer_terminal_headings=mode == "bundle")) run = route(problem, options=settings) verified = sum(result.is_valid for result in run.results_by_net.values()) @@ -287,10 +282,8 @@ def main() -> None: _turnaround_figure(directory, problem, proposed_paths, paths) _verify_figure(directory, problem, paths, colors) _refine_figure(directory, problem, paths, _result_paths(refined)) - triangulation = constrained_triangulation_available() - if triangulation: - _guide_figure(directory, problem, options) - _modes_figure(directory, problem, options, triangulation=triangulation) + _guide_figure(directory, problem, options) + _modes_figure(directory, problem, options) print(f"{COMPLEX_EXAMPLE}: {len(problem.nets)}/{len(problem.nets)} verified, {refined.metrics.nodes_expanded} A* expansions") diff --git a/scripts/render_documentation_figures.py b/scripts/render_documentation_figures.py index d0ea84a..c07cbd9 100644 --- a/scripts/render_documentation_figures.py +++ b/scripts/render_documentation_figures.py @@ -179,7 +179,7 @@ def _corridor(directory: Path) -> None: mesh = _Mesh(box(*problem.bounds), problem.static_obstacles, net.width / 2, problem.clearance) endpoints, leads = _endpoint_access(mesh, problem.nets, radius) selected = _plan_lane_assignments( - mesh, problem.nets, endpoints, leads, bend_radius=radius, limit=options.topology.max_corridors, joint_net_ids=frozenset() + mesh, problem.nets, endpoints, leads, bend_radius=radius, limit=options.topology.max_corridors, )[net.net_id][0] result = route(problem, options=options).results_by_net[net.net_id] assert result.is_valid diff --git a/uv.lock b/uv.lock index e7869b9..23e2c17 100644 --- a/uv.lock +++ b/uv.lock @@ -196,7 +196,7 @@ requires-dist = [ { name = "numpy", specifier = ">=1.26,<3" }, { name = "rtree" }, { name = "scipy" }, - { name = "shapely", specifier = ">=2.0.7,<3" }, + { name = "shapely", specifier = ">=2.1,<3" }, ] [package.metadata.requires-dev]