From ff36f94e8f4037ede5b81fffc7633fffccd2873f Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 29 Nov 2026 23:52:49 -0800 Subject: [PATCH 01/57] Bound track assignments in both column planners --- inire/router/_columns.py | 9 +++++---- inire/tests/test_columns.py | 20 +++++++++++++++++++- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index b473dfc..c341f7f 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -30,6 +30,7 @@ Profile = tuple[int, ...] Window = tuple[int, int] JogPivots = tuple[int | None, ...] JogSchedule = tuple[float, tuple[Profile, ...], tuple[JogPivots, ...]] +_MAX_COLUMN_PARTITIONS = 4096 @dataclass(frozen=True, slots=True) @@ -111,7 +112,9 @@ def _column_layout(problem: RoutingProblem) -> _ColumnLayout | None: start = max(int(track.left.x) for track in tracks) finish = min(int(track.right.x) for track in tracks) columns = _columns(problem, start, finish) - if not columns: + if not columns or any( + comb(len(tracks) + len(column.openings) - 1, len(column.openings) - 1) > _MAX_COLUMN_PARTITIONS for column in columns + ): return None launch = tuple(int(track.left.y) for track in tracks) arrival = tuple(int(track.right.y) for track in tracks) @@ -610,9 +613,7 @@ def column_jog_candidates(problem: RoutingProblem, search: SearchOptions) -> Ite if not radii: return layout = _column_layout(problem) - if layout is None or any( - comb(len(layout.tracks) + len(column.openings) - 1, len(column.openings) - 1) > 4096 for column in layout.columns - ): + if layout is None: return for radius, rows, moves in _column_jog_schedules(problem, layout, radii, search.min_straight_length): seeds = _jog_seeds(layout.tracks, rows, moves, radius, search) diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 666a9d0..3d357a0 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -1,6 +1,6 @@ from shapely.geometry import box -from inire import NetSpec, Port, RoutingOptions, RoutingProblem, SearchOptions, route +from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route from inire.geometry.sbend import exact_sbend_spans from inire.router import _columns from inire.router._columns import _jog_pivots, _schedules, column_seed_candidates @@ -45,6 +45,24 @@ def test_column_windows_bound_enumeration_for_a_large_sbend_radius() -> None: assert list(column_seed_candidates(problem, search, LENGTH_COST, weighted=False)) == [] +def test_automatic_routing_skips_column_profiles_with_too_many_partitions(monkeypatch) -> None: + def unexpected_profiles(*_args, **_kwargs): + raise AssertionError("The column has more than five million track assignments") + + monkeypatch.setattr(_columns, "_column_profiles", unexpected_profiles) + nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(200, y, 0)) for y in range(400, 560, 20)) + keepouts = tuple(box(90, y, 110, y + 3) for y in range(10, 340, 15)) + problem = RoutingProblem((0, 0, 210, 600), nets, keepouts, clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=20, bend_radii=(), sbend_radii=(10,)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + results = route(problem, options=options).results_by_net + assert all(results[net.net_id].is_valid for net in nets) + + def test_jog_transition_rejects_an_offset_that_cannot_fit_two_bends() -> None: assert _jog_pivots((10, 40), (17, 40), (0, 100), (2, 2), 2, 5, 1) is None assert _jog_pivots((10, 40), (25, 40), (0, 100), (2, 2), 2, 5, 1) == (8, None) From 1723bf338fb086928c39a709a7f520fbfa3523b5 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 29 Nov 2026 23:53:06 -0800 Subject: [PATCH 02/57] Prune S-bend sequences that cannot fit the window --- inire/router/_columns.py | 3 +++ inire/tests/test_columns.py | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index c341f7f..8bf7f29 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -270,6 +270,9 @@ def _bend_sequences( @lru_cache(maxsize=4096) def choose(delta: int, usable: int) -> _BendSequence | None: magnitude = abs(delta) + # A circular S-bend advances at least as far as it shifts. + if magnitude > usable: + return None while len(sequences) <= magnitude: height = len(sequences) candidates = [ diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 3d357a0..e896a07 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -1,3 +1,5 @@ +from unittest.mock import Mock + from shapely.geometry import box from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route @@ -20,6 +22,18 @@ def test_sbend_schedule_requires_a_window_long_enough_for_exact_spans() -> None: assert [(sequence.span, sequence.offsets) for sequence in transitions[0]] == [(40, (20,))] * 3 +def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None: + make_sequence = Mock(wraps=_columns._BendSequence) + monkeypatch.setattr(_columns, "_BendSequence", make_sequence) + choose = _columns._bend_sequences({10: 30}, 25, LENGTH_COST, weighted=False, sbend_penalty=0) + make_sequence.reset_mock() + + assert choose(100, 40) is None + assert choose(-100, 40) is None + make_sequence.assert_not_called() + assert choose(-10, 30).offsets == (-10,) + + def test_exact_sbend_spans_filter_by_window_and_configured_offsets() -> None: assert exact_sbend_spans(25, max_span=40, offsets=(-20, 10, 40, 0)) == {10: 30, 20: 40} assert exact_sbend_spans(25, max_span=39, offsets=(-20,)) == {} From f762b86429ac9c935197664c08d58dfaece14b9f Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 29 Nov 2026 23:53:39 -0800 Subject: [PATCH 03/57] Validate bend geometry options at construction --- inire/model.py | 15 ++++++++++++--- inire/tests/test_api.py | 12 ++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/inire/model.py b/inire/model.py index 484e878..27e7147 100644 --- a/inire/model.py +++ b/inire/model.py @@ -128,6 +128,18 @@ class SearchOptions(_SearchOptionsCache): _require_nonnegative("distance_heuristic_weight", self.distance_heuristic_weight) if not isfinite(self.proximity_range) or self.proximity_range <= 0: raise ValueError("proximity_range must be finite and positive") + proxy_names = ("arc", "bbox", "clipped_bbox") + for field_name, names, optional in ( + ("bend_collision_type", proxy_names, False), + ("bend_proxy_geometry", proxy_names, True), + ("bend_physical_geometry", ("arc",), True), + ): + geometry = getattr(self, field_name) + if isinstance(geometry, Polygon): + if geometry.is_empty or not geometry.is_valid: + raise ValueError(f"{field_name} must be a valid, nonempty polygon") + elif not ((optional and geometry is None) or (isinstance(geometry, str) and geometry in names)): + raise ValueError(f"Invalid {field_name} {geometry!r}") if self.bend_physical_length is not None: _, physical = resolve_bend_geometry(self) if physical == "arc" or not isfinite(self.bend_physical_length) or self.bend_physical_length <= 0: @@ -159,9 +171,6 @@ class SearchOptions(_SearchOptionsCache): raise ValueError(f"Duplicate S-bend outline for offset {outline.offset}, radius {outline.radius}, width {outline.width}") widths.append(outline.width) object.__setattr__(self, "sbend_outlines", outlines) - for geometry in (self.bend_collision_type, self.bend_proxy_geometry, self.bend_physical_geometry): - if isinstance(geometry, Polygon) and (geometry.is_empty or not geometry.is_valid): - raise ValueError("Custom bend geometry must be a valid, nonempty polygon") if self.bend_physical_geometry is None and isinstance(self.bend_proxy_geometry, Polygon): warnings.warn( "Custom bend proxy provided without bend_physical_geometry; routed bends will keep standard arc geometry.", diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 8c14050..30e9d12 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -451,6 +451,18 @@ def test_public_inputs_reject_invalid_ids_and_named_options() -> None: SearchOptions(visibility_guidance="exact") +@pytest.mark.parametrize(("name", "value"), [ + ("bend_collision_type", "clipped-bbox"), + ("bend_collision_type", None), + ("bend_proxy_geometry", "clipped-bbox"), + ("bend_proxy_geometry", 1), + ("bend_physical_geometry", "bbox"), +]) +def test_search_rejects_unsupported_bend_geometry(name, value) -> None: + with pytest.raises(ValueError, match=f"Invalid {name}"): + SearchOptions(**{name: value}) + + def _sbend_strip(offset, half_width=1): centerline = [(0, 0), (20, offset / 10), (50, 3 * offset / 4), (80, offset)] return Polygon( From 867aab8fa2249dcbde179f885f2a989d41b183e3 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 29 Nov 2026 23:56:47 -0800 Subject: [PATCH 04/57] Keep ambiguous S-bend templates local to affected nets --- docs/user/api-reference.md | 6 +-- inire/__init__.py | 17 ++++++-- inire/model.py | 22 +++++++++- inire/results.py | 6 +++ inire/router/_astar_admission.py | 10 ++--- inire/router/_astar_moves.py | 4 +- inire/router/_astar_types.py | 3 +- inire/router/_search.py | 5 +++ inire/router/_seed_materialization.py | 10 ++--- inire/tests/test_api.py | 62 ++++++++++++++++++++++++++- 10 files changed, 123 insertions(+), 22 deletions(-) diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index c601051..fcb706d 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -40,7 +40,7 @@ The fields below appear in constructor order. Use one layout unit for coordinate `PathSeed(segments)` holds an ordered tuple of `StraightSeed(length)`, `Bend90Seed(radius, direction)`, and `SBendSeed(offset, radius)` moves. Lengths and radii must be finite and positive. When routing a seed, straight lengths are rounded to the nearest grid unit, with ties rounded to even and a minimum of one unit. Bend directions are `"CW"` and `"CCW"`. S-bend offsets must be nonzero integers with magnitude less than twice the radius. A seed is materialized from the net's current start port using its width and the run's geometry options. Moves that use a generated circular outline or a proxy derived from one require a radius of at least half the net width. -A disabled radius or offset discards the seed and sets the net's `seed_error`. Active search can route the net from scratch. Zero-node replay still checks the other seeds. Unknown net IDs raise `ValueError`. +A disabled radius or offset or an ambiguous S-bend outline discards the seed and sets the net's `seed_error`. Active search can route the net from scratch. Zero-node replay still checks the other seeds. Unknown net IDs raise `ValueError`. ## Results @@ -51,7 +51,7 @@ A disabled radius or offset discards the seed and sets the net's `seed_error`. A | `RoutingResult.requested_net` and `effective_net` | The net as supplied and the net used by the worker, including resolved headings. | | `RoutingResult.path` | Ordered path components from the source to the last reached state. Each component carries its move specification and placed start and end ports. An unroutable result has an empty path. | | `RoutingResult.reached_target` | Whether the path reached the target position and heading. With heading inference, the check uses the chosen heading. Read `is_valid` for the result of geometry verification. | -| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `invalid_geometry` flags invalid polygons or a rejected seed that produced no path. `seed_error` describes a seed rejected by the configured move options or by geometry preparation. `terminal_error` identifies coincident ports or an inaccessible start or target face. | +| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `invalid_geometry` flags invalid polygons or a rejected seed that produced no path. `seed_error` describes a seed rejected by the configured move options or by geometry preparation. `terminal_error` identifies coincident ports or an inaccessible start or target face. `sbend_template_error` identifies S-bend moves skipped because multiple outlines matched the net width. A route using other moves can still complete. | | `RoutingResult.as_seed()` | The ordered moves for [saving a placement recipe](route-a-layout.md#save-a-placement-recipe) or replaying a path. | | `RoutingResult.locked_geometry` | Physical polygons checked during routing. Use these to inspect the route or [reserve a completed net](route-a-layout.md#reuse-an-existing-route). | | `RoutingRunResult.automatic` | In automatic mode, the selected planner, verified IDs, stage history, and any capacity or port-conflict bound. `None` for explicit modes. | @@ -95,7 +95,7 @@ For structured logging, `dataclasses.asdict(run)` preserves the per-net fields. | `bend_physical_length` | `None` | Optional authored centerline length for the shared custom 90-degree template, including tangent extensions. Search, refinement, and reports use it when supplied. | | `distance_heuristic_weight` | `1.0` | Finite, nonnegative multiplier for the remaining-distance term only. Increase it to favor progress toward the target relative to estimated turn penalties. The routed path's objective stays the same. | -A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and seed replay. Supply a separate outline to customize the opposite offset. Width matching allows a relative difference of `1e-12` to account for floating-point conversions. An ambiguous match raises an error. Unmatched moves use the circular S-bend. Set `SBendOutline.length` to use a process-specific centerline length for scoring, refinement, and reporting. The default is the nominal circular length. Automatic mode uses lattice search when an enabled outline matches a net width. Bundle mode requires circular bends for its nets. +A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and seed replay. Supply a separate outline to customize the opposite offset. Width matching allows a relative difference of `1e-12` to account for floating-point conversions. If multiple outlines apply to the same move, `route()` skips that move for the affected net and sets `sbend_template_error` in the final result and iteration callbacks. Direct calls to `SearchOptions.sbend_template()` and `sbend_outline()` raise `ValueError` for an ambiguous match. Moves with no matching outline use the circular S-bend. Set `SBendOutline.length` to use a process-specific centerline length for scoring, refinement, and reporting. The default is the nominal circular length. Automatic mode uses lattice search when an enabled outline matches a net width. Bundle mode requires circular bends for its nets. Match custom outline faces to their declared ports and width. `SBendOutline` warns about a mismatch at construction. For a custom 90-degree outline used in a result, `route()` warns once per radius and net width. Replay an `SBendSeed` with the same outlines and bend settings. diff --git a/inire/__init__.py b/inire/__init__.py index 6f57007..e9fa22f 100644 --- a/inire/__init__.py +++ b/inire/__init__.py @@ -79,6 +79,7 @@ def route( iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, ) -> RoutingRunResult: resolved_options = RoutingOptions() if options is None else options + search = resolved_options.search requested = {net.net_id: net for net in problem.nets} coincident = { net.net_id: RoutingResult( @@ -91,11 +92,18 @@ def route( for net in problem.nets if net.start == net.target } + template_errors = {} + if search.sbend_outlines and search.active_sbend_outlines: + widths = dict.fromkeys(net.width for net in problem.nets) + errors_by_width = {width: search._sbend_template_error(width) for width in widths} + template_errors = { + net.net_id: error for net in problem.nets if (error := errors_by_width[net.width]) is not None + } seed_errors = {} for net_id, seed in problem.initial_paths.items(): if net_id not in requested: raise ValueError(f"Initial path provided for unknown net: {net_id}") - if net_id not in coincident and (error := resolved_options.search.seed_geometry_error(seed)) is not None: + if net_id not in coincident and (error := search.seed_geometry_error(seed)) is not None: seed_errors[net_id] = f"Initial path for {net_id!r} {error}" if coincident or seed_errors: problem = replace( @@ -117,6 +125,9 @@ def route( report = replace(result.report, seed_error=error, invalid_geometry=result.report.invalid_geometry or not result.path) attached[net_id] = replace(result, report=report) attached.update(coincident) + for net_id, error in template_errors.items(): + if (result := attached.get(net_id)) is not None: + attached[net_id] = replace(result, report=replace(result.report, sbend_template_error=error)) return attached def notify(iteration: int, results: dict[str, RoutingResult]) -> None: @@ -135,11 +146,11 @@ def route( results = attach_requested(run.results_by_net) if coincident: results = {net_id: results[net_id] for net_id in requested} - _, physical_bend = _resolve_bend_geometry(resolved_options.search) + _, physical_bend = _resolve_bend_geometry(search) if isinstance(physical_bend, _Polygon): _warn_bend_port_mismatches(results, requested) run = replace(run, results_by_net=results) - if (coincident or seed_errors) and run.conflict_trace: + if (coincident or seed_errors or template_errors) and run.conflict_trace: from .router._route_traces import complete_final_conflict_trace # noqa: PLC0415 run = complete_final_conflict_trace(run) diff --git a/inire/model.py b/inire/model.py index 27e7147..9c925ef 100644 --- a/inire/model.py +++ b/inire/model.py @@ -103,6 +103,10 @@ class _SearchOptionsCache: _active_sbend_outlines: tuple[SBendOutline, ...] +class _AmbiguousSBendOutlineError(ValueError): + pass + + @dataclass(frozen=True, slots=True) class SearchOptions(_SearchOptionsCache): node_limit: int = 1000000 @@ -195,13 +199,29 @@ class SearchOptions(_SearchOptionsCache): def sbend_outlines_for_width(self, width: float) -> Iterator[SBendOutline]: return (outline for outline in self.active_sbend_outlines if _outline_width_matches(outline.width, width)) + def _sbend_templates_for_width(self, width: float) -> dict[tuple[float, float], SBendOutline | None]: + # A key mapped to None is ambiguous. A missing key uses a circular S-bend. + templates: dict[tuple[float, float], SBendOutline | None] = {} + for outline in self.sbend_outlines_for_width(width): + key = outline.offset, outline.radius + templates[key] = None if key in templates else outline + return templates + + def _sbend_template_error(self, width: float) -> str | None: + ambiguous = [ + f"(offset {offset:g}, radius {radius:g})" + for (offset, radius), outline in self._sbend_templates_for_width(width).items() + if outline is None + ] + return f"Ambiguous S-bend outlines for width {width!r} at {', '.join(ambiguous)}" if ambiguous else None + def has_applicable_sbend_outline(self, widths: Iterable[float]) -> bool: return bool(self.active_sbend_outlines) and any(next(self.sbend_outlines_for_width(width), None) is not None for width in widths) def sbend_template(self, offset: float, radius: float, width: float) -> SBendOutline | None: matches = [outline for outline in self.sbend_outlines_for_width(width) if (outline.offset, outline.radius) == (offset, radius)] if len(matches) > 1: - raise ValueError(f"Ambiguous S-bend outlines for offset {offset}, radius {radius}, width {width}") + raise _AmbiguousSBendOutlineError(f"Ambiguous S-bend outlines for offset {offset}, radius {radius}, width {width}") return matches[0] if matches else None def sbend_outline(self, offset: float, radius: float, width: float) -> Polygon | None: diff --git a/inire/results.py b/inire/results.py index 47137d8..9e2cc47 100644 --- a/inire/results.py +++ b/inire/results.py @@ -31,6 +31,12 @@ class RoutingReport: invalid_geometry: bool = False seed_error: str | None = None terminal_error: str | None = None + sbend_template_error: str | None = None + + def __setstate__(self, state: list[object]) -> None: + # Reports pickled before the template diagnostic have one fewer field. + for index, item in enumerate(fields(self)): + object.__setattr__(self, item.name, state[index] if index < len(state) else item.default) @property def intrinsic_collision_count(self) -> int: diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index ca86ed6..d893af9 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -38,11 +38,11 @@ def process_move( physical_type = config.bend_physical_geometry physical_key = id(physical_type) if isinstance(physical_type, Polygon) else physical_type search = context.options.search - template = ( - search.sbend_template(params[0], params[1], net_width) - if move_class == "sbend" and search.sbend_outlines and search.active_sbend_outlines - else None - ) + template = None + if move_class == "sbend" and config.sbend_templates: + template = config.sbend_templates.get(params) + if template is None and params in config.sbend_templates: + return outline = template.polygon if template else None self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0 diff --git a/inire/router/_astar_moves.py b/inire/router/_astar_moves.py index 3d75218..593fff1 100644 --- a/inire/router/_astar_moves.py +++ b/inire/router/_astar_moves.py @@ -335,9 +335,9 @@ def expand_moves( ) max_sbend_r = max(search_options.sbend_radii) if search_options.sbend_radii else 0.0 + templates = config.sbend_templates custom_sbends = ( - {(outline.offset, outline.radius) for outline in search_options.sbend_outlines_for_width(net_width)} - if search_options.sbend_outlines and search_options.active_sbend_outlines else () + {key for key, template in templates.items() if template is not None} if templates else () ) if not bend_fits_width(max_sbend_r, net_width) and not custom_sbends: return diff --git a/inire/router/_astar_types.py b/inire/router/_astar_types.py index c649be8..1e6ee8c 100644 --- a/inire/router/_astar_types.py +++ b/inire/router/_astar_types.py @@ -14,7 +14,7 @@ if TYPE_CHECKING: from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult from inire.geometry.primitives import Port - from inire.model import RoutingOptions, RoutingProblem + from inire.model import RoutingOptions, RoutingProblem, SBendOutline from inire.router._topology import Corridor from inire.router.cost import CostEvaluator from inire.seeds import PathSegmentSeed @@ -99,6 +99,7 @@ class SearchRunConfig: hard_congestion: bool = False propose_guidance_moves: bool = False expired: Callable[[], bool] | None = field(default=None, repr=False, compare=False) + sbend_templates: dict[tuple[float, float], SBendOutline | None] | None = None def estimate_remaining_cost(self, current: Port, target: Port, context: AStarContext) -> float: evaluator = context.cost_evaluator diff --git a/inire/router/_search.py b/inire/router/_search.py index e5405d5..4edb1bd 100644 --- a/inire/router/_search.py +++ b/inire/router/_search.py @@ -1,6 +1,7 @@ from __future__ import annotations import heapq +from dataclasses import replace from math import inf from typing import TYPE_CHECKING @@ -60,6 +61,10 @@ def route_astar( metrics = AStarMetrics() metrics.reset_per_route() + search = context.options.search + if search.sbend_outlines and search.active_sbend_outlines: + config = replace(config, sbend_templates=search._sbend_templates_for_width(net_width)) + context.ensure_static_caches_current() context.cost_evaluator.set_target(target) open_set: list[_AStarNode] = [] diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index 807f90d..3cd7747 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -5,7 +5,7 @@ from typing import TYPE_CHECKING from inire.geometry.components import ( ComponentPreparationError, build_component, component_endpoint, prepare_component_sampling, ) -from inire.model import resolve_bend_geometry +from inire.model import _AmbiguousSBendOutlineError, resolve_bend_geometry from inire.seeds import Bend90Seed, SBendSeed, StraightSeed if TYPE_CHECKING: @@ -29,14 +29,14 @@ def seed_preparation_error(seed: PathSeed, *, start: Port, net_width: float, sea proxy, physical = resolve_bend_geometry(search) for index, segment in enumerate(seed.segments, start=1): kind, parameters = seed_move(segment) - template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None try: + template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None start = component_endpoint(start, kind, parameters) prepare_component_sampling( kind, parameters, net_width, collision_type=proxy, physical_geometry_type=physical, dilation=clearance / 2, sbend_outline=template.polygon if template is not None else None, ) - except (ComponentPreparationError, OverflowError) as exc: + except (ComponentPreparationError, OverflowError, _AmbiguousSBendOutlineError) as exc: return f"segment {index} ({type(segment).__name__}) {exc}" return None @@ -68,8 +68,8 @@ def materialize_path_seed( for index, segment in enumerate(seed.segments, start=1): kind, parameters = seed_move(segment) - template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None try: + template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None component = build_component( current, net_width, @@ -83,7 +83,7 @@ def materialize_path_seed( bounds=None if diagnostic else bounds, physical_length=search.bend_physical_length if kind == "bend90" else (template.length if template else None), ) - except (ComponentPreparationError, OverflowError) as exc: + except (ComponentPreparationError, OverflowError, _AmbiguousSBendOutlineError) as exc: if diagnostic: raise SeedMaterializationError(f"segment {index} ({type(segment).__name__}) {exc}") from exc return None diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 30e9d12..30a4c10 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -629,16 +629,74 @@ def test_search_checks_materialized_quarter_turn_face() -> None: assert result.as_seed() == PathSeed((Bend90Seed(20, "CCW"),)) -def test_custom_sbend_outline_rejects_duplicate_and_ambiguous_widths() -> None: +def _nearby_sbend_outlines() -> tuple[SBendOutline, SBendOutline]: outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15)) + return outline, replace(outline, width=0.3 * (1 + 1.5e-12)) + + +def test_custom_sbend_outline_rejects_duplicate_and_ambiguous_widths() -> None: + outline, other = _nearby_sbend_outlines() with pytest.raises(ValueError, match="Duplicate S-bend outline"): SearchOptions(sbend_radii=(50,), sbend_outlines=(outline, replace(outline, width=0.1 + 0.2))) - other = replace(outline, width=0.3 * (1 + 1.5e-12)) options = SearchOptions(sbend_radii=(50,), sbend_outlines=(outline, other)) with pytest.raises(ValueError, match="Ambiguous S-bend outlines"): options.sbend_outline(40, 50, (outline.width + other.width) / 2) +@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) +def test_ambiguous_sbend_outline_reports_the_affected_net_without_blocking_straights(mode) -> None: + outline, other = _nearby_sbend_outlines() + width = (outline.width + other.width) / 2 + peer = NetSpec("peer", Port(10, 80, 0), Port(90, 80, 0), width=0.5) + line = NetSpec("line", Port(10, 10, 0), Port(50, 10, 0), width=width) + problem = RoutingProblem((0, 0, 100, 100), (peer, line), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=10, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline, other)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode=mode), + diagnostics=DiagnosticsOptions(capture_conflict_trace=True), + ) + callbacks = [] + + run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results)) + + assert all(result.is_valid for result in run.results_by_net.values()) + error = f"Ambiguous S-bend outlines for width {width!r} at (offset 40, radius 50)" + assert run.results_by_net["line"].report.sbend_template_error == error + assert run.results_by_net["peer"].report.sbend_template_error is None + assert callbacks + assert callbacks[-1]["line"].report.sbend_template_error == error + assert {net.net_id: net.report.sbend_template_error for net in run.conflict_trace[-1].nets} == {"peer": None, "line": error} + disabled = replace(options, search=replace(options.search, sbend_offsets=())) + assert route(problem, options=disabled).results_by_net["line"].report.sbend_template_error is None + + +@pytest.mark.parametrize("mode", ["automatic", "off"]) +@pytest.mark.parametrize("node_limit", [0, 20]) +def test_ambiguous_sbend_outline_is_skipped_in_search_and_seed_replay(mode, node_limit) -> None: + outline, other = _nearby_sbend_outlines() + width = (outline.width + other.width) / 2 + shift = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0), width=width) + peer = NetSpec("peer", Port(10, 70, 0), Port(90, 110, 0), width=outline.width) + seed = PathSeed((SBendSeed(40, 50),)) + paths = {} if node_limit else {net.net_id: seed for net in (shift, peer)} + problem = RoutingProblem((0, 0, 100, 120), (shift, peer), initial_paths=paths, clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=node_limit, bend_radii=(), sbend_radii=(50,), sbend_offsets=(40,), sbend_outlines=(outline, other)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode=mode), + ) + + results = route(problem, options=options).results_by_net + + assert not results["shift"].is_valid + assert not any(isinstance(component.move_spec, SBendSeed) for component in results["shift"].path) + assert results["peer"].is_valid + assert results["peer"].path[0].physical_geometry[0].equals(translate(outline.polygon, 10, 70)) + if not node_limit: + assert "segment 1 (SBendSeed) Ambiguous S-bend outlines" in results["shift"].report.seed_error + + @pytest.mark.parametrize("contact", ["face", "rounding", "gap", "extra_edge", "extra_point", "wide_face", "overlap"]) @pytest.mark.parametrize("heading", [0, 90]) def test_custom_sbend_join_allows_boundary_contact_and_rejects_area_overlap(contact, heading) -> None: From b541632ddec058671b986d8a29bc258d3aa8addb Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 09:25:08 -0800 Subject: [PATCH 05/57] Use snapped S-bend spans in local planning --- inire/router/_compact.py | 15 +++++++-------- inire/tests/test_compact.py | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 8 deletions(-) create mode 100644 inire/tests/test_compact.py diff --git a/inire/router/_compact.py b/inire/router/_compact.py index e70283b..e1c01dd 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -3,7 +3,7 @@ from __future__ import annotations from itertools import islice -from math import isfinite, sqrt +from math import isfinite from typing import TYPE_CHECKING from shapely import union_all @@ -12,7 +12,7 @@ from shapely.geometry import box from inire.constants import TOLERANCE_LINEAR from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import port_local_coordinates -from inire.geometry.sbend import exact_sbend_spans +from inire.geometry.sbend import exact_sbend_spans, sbend_grid_span from inire.model import resolve_bend_geometry from inire.results import RoutingResult from inire.router._seed_materialization import materialize_path_seed @@ -178,13 +178,12 @@ def _shift_seeds(forward: int, offset: int, search: SearchOptions) -> Iterator[P 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): + try: + span = sbend_grid_span(offset, radius) + except (ValueError, OverflowError): continue - span = round(exact) spare = forward - span - if spare < 0 or abs(exact - span) > 1e-9: + if spare < 0: continue placements = {i * spare // 8 for i in range(9)} for lead in sorted(placements, key=lambda distance: (abs(2 * distance - spare), distance)): @@ -194,7 +193,7 @@ def _shift_seeds(forward: int, offset: int, search: SearchOptions) -> Iterator[P 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.""" + """Fit links between fixed ports across both axes of a layout.""" if problem.initial_paths or len(problem.nets) < 3 or len({net.start.r % 180 for net in problem.nets}) < 2: return None if any(net.start.r != net.target.r for net in problem.nets): diff --git a/inire/tests/test_compact.py b/inire/tests/test_compact.py new file mode 100644 index 0000000..cfb0284 --- /dev/null +++ b/inire/tests/test_compact.py @@ -0,0 +1,21 @@ +from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, route + + +def test_local_sbend_planner_uses_the_snapped_span() -> None: + east = NetSpec("east", Port(10, 10, 0), Port(24, 15, 0)) + north = NetSpec("north", Port(70, 10, 90), Port(65, 24, 90)) + line = NetSpec("line", Port(10, 40, 0), Port(40, 40, 0)) + problem = RoutingProblem((0, 0, 100, 100), (east, north, line), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10,)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert all(result.is_valid for result in run.results_by_net.values()) + assert run.automatic.selected_planner == "local-sbend" + assert run.metrics.nodes_expanded == 0 + for net in (east, north): + assert run.results_by_net[net.net_id].as_seed().segments == (SBendSeed(5, 10),) From 26b12e33a290ca6174f44c7fce6b2225108dd656 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 09:25:27 -0800 Subject: [PATCH 06/57] Enforce net clearance when packing route candidates --- inire/router/_automatic.py | 5 ++--- inire/router/_compact.py | 5 ++--- inire/tests/test_compact.py | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index c7123af..7eb1db1 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -12,8 +12,7 @@ from typing import TYPE_CHECKING import shapely from shapely.geometry import box -from inire.constants import TOLERANCE_LINEAR -from inire.geometry.collision import RoutingWorld +from inire.geometry.collision import RoutingWorld, _violates_net_clearance from inire.model import FixedRoute, resolve_bend_geometry from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle @@ -335,7 +334,7 @@ class _AutomaticRun: pairs = chain(pairs, reserved_pairs) for (first_seed, first_shape), (second_seed, second_shape) in pairs: - if first_shape.distance(second_shape) < problem.clearance - TOLERANCE_LINEAR: + if _violates_net_clearance(first_shape, second_shape, problem.clearance): continue plan = replace(problem, initial_paths={first.net_id: first_seed, second.net_id: second_seed}) trial = self._verify(plan, "paired-perimeter") diff --git a/inire/router/_compact.py b/inire/router/_compact.py index e1c01dd..b975672 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -9,8 +9,7 @@ from typing import TYPE_CHECKING from shapely import union_all from shapely.geometry import box -from inire.constants import TOLERANCE_LINEAR -from inire.geometry.collision import RoutingWorld +from inire.geometry.collision import RoutingWorld, _violates_net_clearance from inire.geometry.primitives import port_local_coordinates from inire.geometry.sbend import exact_sbend_spans, sbend_grid_span from inire.model import resolve_bend_geometry @@ -119,7 +118,7 @@ def _pack_routes( if remaining <= 0: return None remaining -= 1 - if any(footprint.distance(other) < clearance - TOLERANCE_LINEAR for _, other in chosen.values()): + if any(_violates_net_clearance(footprint, other, clearance) for _, other in chosen.values()): continue chosen[net_id] = (seed, footprint) index += 1 diff --git a/inire/tests/test_compact.py b/inire/tests/test_compact.py index cfb0284..4f2a93d 100644 --- a/inire/tests/test_compact.py +++ b/inire/tests/test_compact.py @@ -19,3 +19,21 @@ def test_local_sbend_planner_uses_the_snapped_span() -> None: assert run.metrics.nodes_expanded == 0 for net in (east, north): assert run.results_by_net[net.net_id].as_seed().segments == (SBendSeed(5, 10),) + + +def test_local_sbend_packing_skips_intersecting_candidates_at_zero_clearance() -> None: + east = NetSpec("east", Port(10, 10, 0), Port(50, 18, 0)) + north = NetSpec("north", Port(26, 12, 90), Port(18, 42, 90)) + line = NetSpec("line", Port(10, 65, 0), Port(55, 65, 0)) + problem = RoutingProblem((0, 0, 100, 100), (east, north, line), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, min_straight_length=0, bend_radii=(), sbend_radii=(10,), sbend_offsets=(8,)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert all(result.is_valid for result in run.results_by_net.values()) + assert run.automatic.selected_planner == "local-sbend" + assert run.metrics.nodes_expanded == 0 From f4b16d3c556f48242f8bd80c9bf93be06eb6ab5b Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 09:25:59 -0800 Subject: [PATCH 07/57] Use reachable offset strides in the S-bend sequence table --- inire/router/_columns.py | 16 +++++++++++----- inire/tests/test_columns.py | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 8bf7f29..11007f7 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -265,6 +265,9 @@ def _bend_sequences( bend_costs = { d: sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span for d, span in spans.items() } + # Only multiples of the common offset stride can occur in a sequence. + stride = gcd(*spans) or 1 + bends = [(offset // stride, offset, span) for offset, span in spans.items()] sequences: list[tuple[_BendSequence, ...]] = [(_BendSequence((), 0, 0.0),)] @lru_cache(maxsize=4096) @@ -273,13 +276,16 @@ def _bend_sequences( # A circular S-bend advances at least as far as it shifts. if magnitude > usable: return None - while len(sequences) <= magnitude: + index, remainder = divmod(magnitude, stride) + if remainder or (index and not bends): + return None + while len(sequences) <= index: height = len(sequences) candidates = [ _BendSequence((offset, *prefix.offsets), span + prefix.span, bend_costs[offset] + prefix.cost) - for offset, span in spans.items() - if offset <= height - for prefix in sequences[height - offset] + for step, offset, span in bends + if step <= height + for prefix in sequences[height - step] ] candidates.sort( key=lambda candidate: ( @@ -293,7 +299,7 @@ def _bend_sequences( if not frontier or (weighted and candidate.cost < frontier[-1].cost - 1e-9): frontier.append(candidate) sequences.append(tuple(frontier)) - viable = [candidate for candidate in sequences[magnitude] if candidate.span <= usable] + viable = [candidate for candidate in sequences[index] if candidate.span <= usable] if not viable: return None best = viable[-1] diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index e896a07..2ddff22 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -34,6 +34,24 @@ def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(mon assert choose(-10, 30).offsets == (-10,) +def test_sbend_sequences_use_the_common_offset_stride() -> None: + class SparseSpans(dict): + def items(self): + self.scans += 1 + assert self.scans <= 3 + return super().items() + + spans = SparseSpans({40_000_000: 120_000_000, 80_000_000: 160_000_000}) + spans.scans = 0 + choose = _columns._bend_sequences(spans, 100_000_000, LENGTH_COST, weighted=False, sbend_penalty=0) + + assert choose(40_000_001, 120_000_000) is None + assert choose(40_000_000, 119_999_999) is None + assert choose(-40_000_000, 120_000_000).offsets == (-40_000_000,) + assert choose(80_000_000, 160_000_000).offsets == (80_000_000,) + assert choose(120_000_000, 280_000_000).offsets == (80_000_000, 40_000_000) + + def test_exact_sbend_spans_filter_by_window_and_configured_offsets() -> None: assert exact_sbend_spans(25, max_span=40, offsets=(-20, 10, 40, 0)) == {10: 30, 20: 40} assert exact_sbend_spans(25, max_span=39, offsets=(-20,)) == {} From 06dbfd409375f0d4e224388ad43e0705931d3815 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 09:29:21 -0800 Subject: [PATCH 08/57] Rank column S-bend profiles without enumerating full products --- inire/router/_columns.py | 88 +++++++++++++++++++++++++------------ inire/tests/test_columns.py | 19 ++++++++ 2 files changed, 79 insertions(+), 28 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 11007f7..bad7566 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -4,7 +4,8 @@ from __future__ import annotations from collections import defaultdict from dataclasses import dataclass -from functools import lru_cache +from functools import cache, lru_cache +from heapq import merge from itertools import combinations_with_replacement, islice, pairwise, product from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin from typing import TYPE_CHECKING @@ -31,6 +32,7 @@ Window = tuple[int, int] JogPivots = tuple[int | None, ...] JogSchedule = tuple[float, tuple[Profile, ...], tuple[JogPivots, ...]] _MAX_COLUMN_PARTITIONS = 4096 +_MAX_COLUMN_PROFILES = 140 @dataclass(frozen=True, slots=True) @@ -221,36 +223,66 @@ def _column_profiles( *, combinations_limit: int | None = None, ) -> list[Profile]: + @cache + def band_profiles(opening: Gap, left: int, right: int) -> tuple[Profile, ...]: + return _band_profiles( + problem, opening, widths[left:right], residues[left:right], desired[left:right], spacing_slack, wall_slack, modulus, + tuple(candidate[left:right] for candidate in reachability), + ) + + if combinations_limit is None: + return _best_column_profiles(column.openings, desired, band_profiles) + profiles = set() n = len(widths) - band_cache = {} for cuts in combinations_with_replacement(range(n + 1), len(column.openings) - 1): - groups = [] - for opening, (left, right) in zip(column.openings, pairwise((0, *cuts, n)), strict=True): - key = opening, left, right - if key not in band_cache: - band_cache[key] = _band_profiles( - problem, - opening, - widths[left:right], - residues[left:right], - desired[left:right], - spacing_slack, - wall_slack, - modulus, - tuple(candidate[left:right] for candidate in reachability), - ) - groups.append(band_cache[key]) - 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] + groups = [ + band_profiles(opening, left, right) + for opening, (left, right) in zip(column.openings, pairwise((0, *cuts, n)), strict=True) + ] + for chosen in islice(product(*groups), 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))[:_MAX_COLUMN_PROFILES] + + +def _best_column_profiles( + openings: tuple[Gap, ...], + desired: tuple[float, ...], + band_profiles: Callable[[Gap, int, int], tuple[Profile, ...]], +) -> list[Profile]: + # Sum deviations exactly so adding a band preserves the order of tied prefixes. + ratios = tuple(y.as_integer_ratio() for y in desired) + scale = max((denominator for _, denominator in ratios), default=1) + scaled_targets = tuple(numerator * (scale // denominator) for numerator, denominator in ratios) + + def extend(prefixes: list[tuple[int, Profile]], band: Profile, deviation: int) -> Iterator[tuple[int, Profile]]: + return ((cost + deviation, prefix + band) for cost, prefix in prefixes) + + # Prefixes that have placed the same number of tracks can use the same + # remaining bands. Each extension preserves the order by deviation and row. + # Disjoint bands make each row correspond to a unique track assignment. + prefixes: dict[int, list[tuple[int, Profile]]] = {0: [(0, ())]} + count = len(desired) + for index, opening in enumerate(openings, start=1): + next_prefixes = {} + for right in ((count,) if index == len(openings) else range(count + 1)): + streams = [] + for left, ranked in prefixes.items(): + if left > right: + continue + targets = scaled_targets[left:right] + for band in band_profiles(opening, left, right): + deviation = sum(abs(y * scale - target) for y, target in zip(band, targets, strict=True)) + streams.append(extend(ranked, band, deviation)) + if streams: + next_prefixes[right] = list(islice(merge(*streams), _MAX_COLUMN_PROFILES)) + if not next_prefixes: + return [] + prefixes = next_prefixes + return [row for _, row in prefixes.get(count, ())] def _bend_sequences( diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 2ddff22..5fd07c9 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -95,6 +95,25 @@ def test_automatic_routing_skips_column_profiles_with_too_many_partitions(monkey assert all(results[net.net_id].is_valid for net in nets) +def test_sbend_column_profiles_match_exhaustive_ranking_without_using_a_product(monkeypatch) -> None: + problem = RoutingProblem((0, 0, 200, 300), clearance=0) + column = _columns._Column((80, 100), ((0, 40), (45, 85), (90, 140), (145, 200), (205, 300))) + widths = (2, 3, 2, 4, 2) + desired = (20.25, 65.5, 110.75, 160.5, 250.25) + residues = (0, 1, 2, 3, 0) + reachable = (((16, 20, 24), (61, 65, 69), (106, 110, 114), (155, 159, 163), (244, 248, 252)),) + args = (problem, column, widths, residues, desired, 2, 1, 4, reachable) + exhaustive = _columns._column_profiles(*args, combinations_limit=1_000_000) + + def unexpected_product(*_groups): + raise AssertionError("S-bend profile ranking should avoid the Cartesian product") + + monkeypatch.setattr(_columns, "product", unexpected_product) + + assert len(exhaustive) == 140 + assert _columns._column_profiles(*args) == exhaustive + + def test_jog_transition_rejects_an_offset_that_cannot_fit_two_bends() -> None: assert _jog_pivots((10, 40), (17, 40), (0, 100), (2, 2), 2, 5, 1) is None assert _jog_pivots((10, 40), (25, 40), (0, 100), (2, 2), 2, 5, 1) == (8, None) From 3ffe7cfc5d7144dc89b0ae6e260bfc63615d4db1 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 09:51:18 -0800 Subject: [PATCH 09/57] Honor signed offsets when planning column S-bends --- inire/router/_columns.py | 36 ++++++++++++++++++++++++++++++------ inire/tests/test_columns.py | 24 +++++++++++++++++++++++- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index bad7566..1e12767 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -292,7 +292,21 @@ def _bend_sequences( *, weighted: bool, sbend_penalty: float, + allowed_offsets: frozenset[float] | None = None, ) -> Callable[[int, int], _BendSequence | None]: + if allowed_offsets is not None: + positive = {d: span for d, span in spans.items() if d in allowed_offsets} + negative = {d: span for d, span in spans.items() if -d in allowed_offsets} + if positive != negative: + choose_up = _bend_sequences(positive, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty) + choose_down = _bend_sequences(negative, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty) + + def choose_signed(delta: int, usable: int) -> _BendSequence | None: + return (choose_down if delta < 0 else choose_up)(delta, usable) + + return choose_signed + spans = positive + # Each S-bend replaces a straight of its forward span in this window. bend_costs = { d: sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span for d, span in spans.items() @@ -372,8 +386,9 @@ def _schedules( *, weighted: bool, sbend_penalty: float, + allowed_offsets: frozenset[float] | None = None, ) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]: - choose = _bend_sequences(spans, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty) + choose = _bend_sequences(spans, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets) needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths)) # The track order allows a local check of each neighboring pair. The @@ -463,6 +478,7 @@ def _column_sbend_schedules( *, weighted: bool, sbend_penalty: float, + allowed_offsets: frozenset[float] | None, ) -> Iterator[tuple[tuple[_BendSequence, ...], ...]]: modulus = gcd(*spans) launch, arrival = layout.launch, layout.arrival @@ -484,10 +500,14 @@ def _column_sbend_schedules( ] if weighted: adjacent = [[launch], *interior, [arrival]] - reachable_offsets = (0, *(d for offset in active_spans for d in (-offset, offset))) + reachable_offsets = (0, *( + d for offset in active_spans for d in (-offset, offset) if allowed_offsets is None or d in allowed_offsets + )) + return_offsets = tuple(-d for d in reachable_offsets) for i, (column, preference) in enumerate(zip(columns, preferences, strict=True)): - anchors = (*adjacent[i][:2], *adjacent[i + 2][:2]) - reachable = tuple(tuple(tuple(y + d for d in reachable_offsets) for y in anchor) for anchor in anchors) + anchors = [(anchor, reachable_offsets) for anchor in adjacent[i][:2]] + anchors.extend((anchor, return_offsets) for anchor in adjacent[i + 2][:2]) + reachable = tuple(tuple(tuple(y + d for d in offsets) for y in anchor) for anchor, offsets in anchors) seeded = _column_profiles(problem, column, widths, residues, preference, spacing_slack, wall_slack, modulus, reachable) interior[i] = sorted(set(interior[i] + seeded)) for i, (column, preference) in enumerate(zip(columns, preferences, strict=True)): @@ -496,7 +516,8 @@ def _column_sbend_schedules( interior[i] = sorted(set(interior[i] + roomier[:45])) profiles = [[launch], *interior, [arrival]] for rows, moves in _schedules( - windows, profiles, widths, problem.clearance, radius, active_spans, weights, weighted=weighted, sbend_penalty=sbend_penalty + windows, profiles, widths, problem.clearance, radius, active_spans, weights, + weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, ): signature = rows, moves if signature not in seen: @@ -526,7 +547,10 @@ def column_seed_candidates( spans = exact_sbend_spans(radius, max_span=max_span, offsets=search.sbend_offsets) if not spans: return - for moves in _column_sbend_schedules(problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty): + allowed_offsets = None if search.sbend_offsets is None else frozenset(search.sbend_offsets) + for moves in _column_sbend_schedules( + problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, + ): seeds = _seeds(layout.tracks, layout.spans, moves, radius) if all(search.seed_geometry_error(seed) is None for seed in seeds.values()): yield seeds diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 5fd07c9..beab33c 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -1,8 +1,9 @@ from unittest.mock import Mock +import pytest from shapely.geometry import box -from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route +from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, route from inire.geometry.sbend import exact_sbend_spans from inire.router import _columns from inire.router._columns import _jog_pivots, _schedules, column_seed_candidates @@ -22,6 +23,27 @@ def test_sbend_schedule_requires_a_window_long_enough_for_exact_spans() -> None: assert [(sequence.span, sequence.offsets) for sequence in transitions[0]] == [(40, (20,))] * 3 +@pytest.mark.parametrize("sign", [1, -1]) +def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None: + east = tuple(NetSpec(str(y), Port(5, y, 0), Port(220, y + sign * 10, 0)) for y in (30, 60)) + west = NetSpec("west", Port(220, 90 + sign * 10, 180), Port(5, 90, 180)) + problem = RoutingProblem((0, 0, 230, 130), (*east, west), (box(190, 0, 210, 10),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(25,), sbend_offsets=(sign * 2, -sign * 10)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert run.automatic.selected_planner == "column" + assert run.metrics.nodes_expanded == 0 + for result in run.results_by_net.values(): + assert result.is_valid + bends = tuple(move for move in result.as_seed().segments if isinstance(move, SBendSeed)) + assert bends == (SBendSeed(sign * 2, 25),) * 5 + + def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None: make_sequence = Mock(wraps=_columns._BendSequence) monkeypatch.setattr(_columns, "_BendSequence", make_sequence) From 5c8306c63688b4677fbf6a5918779f302a08a467 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 09:52:16 -0800 Subject: [PATCH 10/57] Limit exact S-bend span searches by lateral room --- inire/geometry/sbend.py | 12 +++++++----- inire/router/_bundle.py | 7 +++++-- inire/router/_columns.py | 3 ++- inire/router/_compact.py | 5 +++-- inire/tests/test_columns.py | 28 ++++++++++++++++++++++++++++ 5 files changed, 45 insertions(+), 10 deletions(-) diff --git a/inire/geometry/sbend.py b/inire/geometry/sbend.py index 4ea6647..eba72f9 100644 --- a/inire/geometry/sbend.py +++ b/inire/geometry/sbend.py @@ -18,19 +18,21 @@ def sbend_grid_span(offset: float, radius: float) -> int: def exact_sbend_spans( - radius: int, *, max_span: int, offsets: tuple[float, ...] | None = None, + radius: int, *, max_span: int, max_offset: int | None = None, offsets: tuple[float, ...] | None = None, ) -> dict[int, int]: - """Map allowed offset magnitudes to exact spans that fit the available length.""" + """Map allowed offset magnitudes to exact spans that fit the available room.""" if max_span < 1: return {} diameter = 2 * radius # offset * (4 * radius - offset) = diameter² - (diameter - offset)². remaining = diameter * diameter - max_span * max_span - max_offset = diameter - (isqrt(remaining - 1) + 1 if remaining > 0 else 1) - candidates = range(1, max_offset + 1) if offsets is None else sorted({int(abs(offset)) for offset in offsets}) + offset_limit = diameter - (isqrt(remaining - 1) + 1 if remaining > 0 else 1) + if max_offset is not None: + offset_limit = min(offset_limit, max_offset) + candidates = range(1, offset_limit + 1) if offsets is None else sorted({int(abs(offset)) for offset in offsets}) spans = {} for offset in candidates: - if not 0 < offset <= max_offset: + if not 0 < offset <= offset_limit: continue squared = offset * (4 * radius - offset) span = isqrt(squared) diff --git a/inire/router/_bundle.py b/inire/router/_bundle.py index adc056e..226da3b 100644 --- a/inire/router/_bundle.py +++ b/inire/router/_bundle.py @@ -118,6 +118,8 @@ def _assign_shifts( pitch: int, floor_lane: int, search: SearchOptions, + *, + max_offset: int, ) -> tuple[dict[str, list[_Shift]], int]: short, lower, upper = layout.short, layout.lower, layout.upper middle, *ascending, shelf = upper @@ -158,7 +160,7 @@ def _assign_shifts( first_top = ceil(last_upper[3] + margin + 0.1) top_lanes = [first_top + i * pitch for i in range(len(ascending))] max_span = int(max(net.target.x for net in upper) - short.start.x) - offsets = tuple(exact_sbend_spans(radius, max_span=max_span, offsets=search.sbend_offsets)) + offsets = tuple(exact_sbend_spans(radius, max_span=max_span, max_offset=max_offset, offsets=search.sbend_offsets)) shelf_options = [ int(shelf.target.y) + offset for offset in offsets @@ -237,7 +239,8 @@ def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer # destination and of the first barrier, so the bundle launches east. problem = _eastbound_launches(problem) layout = _identify_layout(problem, margin) - shifts, launch = _assign_shifts(layout, radius, margin, pitch, floor_lane, search) + max_offset = floor(problem.bounds[3]) - ceil(problem.bounds[1]) + shifts, launch = _assign_shifts(layout, radius, margin, pitch, floor_lane, search, max_offset=max_offset) seeds = {} updated_nets = [] diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 1e12767..bf9f4c9 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -544,7 +544,8 @@ def column_seed_candidates( return radius = int(bend) max_span = max(before - after - 4 for (_, after), (before, _) in pairwise(layout.spans)) - spans = exact_sbend_spans(radius, max_span=max_span, offsets=search.sbend_offsets) + max_offset = floor(problem.bounds[3]) - ceil(problem.bounds[1]) + spans = exact_sbend_spans(radius, max_span=max_span, max_offset=max_offset, offsets=search.sbend_offsets) if not spans: return allowed_offsets = None if search.sbend_offsets is None else frozenset(search.sbend_offsets) diff --git a/inire/router/_compact.py b/inire/router/_compact.py index b975672..c55b2ae 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -3,7 +3,7 @@ from __future__ import annotations from itertools import islice -from math import isfinite +from math import ceil, floor, isfinite from typing import TYPE_CHECKING from shapely import union_all @@ -66,6 +66,7 @@ def _candidate_jogs( yield _path(dx) return direction = 1 if dy > 0 else -1 + max_offset = floor(problem.bounds[2]) - ceil(problem.bounds[0]) for radius in radii: reach = abs(dy) - 2 * radius if reach < 0 or dx < 2 * radius: @@ -79,7 +80,7 @@ def _candidate_jogs( continue # Move the middle of the jog between two independently positioned # turn lanes. The S-bend stays away from the terminal access cutouts. - spans = exact_sbend_spans(radius, max_span=int(reach), offsets=search.sbend_offsets) + spans = exact_sbend_spans(radius, max_span=int(reach), max_offset=max_offset, offsets=search.sbend_offsets) for offset, span in reversed(tuple(spans.items())): available = reach - span for before in _shift_positions(problem, start.y, direction, radius, span, available): diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index beab33c..e56b0c2 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -4,6 +4,7 @@ import pytest from shapely.geometry import box from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, route +from inire.geometry import sbend from inire.geometry.sbend import exact_sbend_spans from inire.router import _columns from inire.router._columns import _jog_pivots, _schedules, column_seed_candidates @@ -77,6 +78,33 @@ def test_sbend_sequences_use_the_common_offset_stride() -> None: def test_exact_sbend_spans_filter_by_window_and_configured_offsets() -> None: assert exact_sbend_spans(25, max_span=40, offsets=(-20, 10, 40, 0)) == {10: 30, 20: 40} assert exact_sbend_spans(25, max_span=39, offsets=(-20,)) == {} + assert exact_sbend_spans(25, max_span=40, max_offset=10, offsets=(-20, 10, 40, 0)) == {10: 30} + + +def test_wide_column_windows_only_scan_offsets_within_the_board_height(monkeypatch) -> None: + square_root = sbend.isqrt + scans = 0 + + def count_scan(value): + nonlocal scans + scans += 1 + assert scans <= 120 + return square_root(value) + + monkeypatch.setattr(sbend, "isqrt", count_scan) + nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(399_999_990, y, 0)) for y in (30, 60, 90)) + problem = RoutingProblem((0, 0, 400_000_000, 120), nets, (box(190_000_000, 0, 190_000_020, 10),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(100_000_000,)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert 0 < scans <= 120 + assert all(run.results_by_net[net.net_id].is_valid for net in nets) + assert run.metrics.nodes_expanded == 0 def test_large_unused_sbend_radius_skips_column_enumeration(monkeypatch) -> None: From 5016c0e76a9d1db27ba3d5b9baf44393a246917c Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 09:54:11 -0800 Subject: [PATCH 11/57] Build only reachable S-bend sequences that fit a window --- inire/router/_columns.py | 59 ++++++++++++++++++++++--------------- inire/tests/test_columns.py | 39 ++++++++++++++++++++++-- 2 files changed, 72 insertions(+), 26 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index bf9f4c9..7f60437 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -5,7 +5,7 @@ from __future__ import annotations from collections import defaultdict from dataclasses import dataclass from functools import cache, lru_cache -from heapq import merge +from heapq import heappop, heappush, merge from itertools import combinations_with_replacement, islice, pairwise, product from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin from typing import TYPE_CHECKING @@ -290,6 +290,7 @@ def _bend_sequences( radius: int, weights: Mapping[str, float], *, + max_usable: int, weighted: bool, sbend_penalty: float, allowed_offsets: frozenset[float] | None = None, @@ -298,8 +299,8 @@ def _bend_sequences( positive = {d: span for d, span in spans.items() if d in allowed_offsets} negative = {d: span for d, span in spans.items() if -d in allowed_offsets} if positive != negative: - choose_up = _bend_sequences(positive, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty) - choose_down = _bend_sequences(negative, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty) + choose_up = _bend_sequences(positive, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty) + choose_down = _bend_sequences(negative, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty) def choose_signed(delta: int, usable: int) -> _BendSequence | None: return (choose_down if delta < 0 else choose_up)(delta, usable) @@ -308,30 +309,30 @@ def _bend_sequences( spans = positive # Each S-bend replaces a straight of its forward span in this window. - bend_costs = { - d: sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span for d, span in spans.items() - } - # Only multiples of the common offset stride can occur in a sequence. - stride = gcd(*spans) or 1 - bends = [(offset // stride, offset, span) for offset, span in spans.items()] - sequences: list[tuple[_BendSequence, ...]] = [(_BendSequence((), 0, 0.0),)] + bends = [ + (d, span, sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span) + for d, span in spans.items() + if span <= max_usable + ] + sequences = {0: (_BendSequence((), 0, 0.0),)} + upcoming = sorted(offset for offset, _, _ in bends) + stride = gcd(*upcoming) or 1 + queued = set(upcoming) @lru_cache(maxsize=4096) def choose(delta: int, usable: int) -> _BendSequence | None: magnitude = abs(delta) # A circular S-bend advances at least as far as it shifts. - if magnitude > usable: + if magnitude > usable or magnitude % stride: return None - index, remainder = divmod(magnitude, stride) - if remainder or (index and not bends): - return None - while len(sequences) <= index: - height = len(sequences) + while upcoming and upcoming[0] <= magnitude: + height = heappop(upcoming) + queued.remove(height) candidates = [ - _BendSequence((offset, *prefix.offsets), span + prefix.span, bend_costs[offset] + prefix.cost) - for step, offset, span in bends - if step <= height - for prefix in sequences[height - step] + _BendSequence((offset, *prefix.offsets), span + prefix.span, cost + prefix.cost) + for offset, span, cost in bends + for prefix in sequences.get(height - offset, ()) + if span + prefix.span <= max_usable ] candidates.sort( key=lambda candidate: ( @@ -340,12 +341,19 @@ def _bend_sequences( tuple(-d for d in candidate.offsets), ) ) - frontier = [] + frontier: list[_BendSequence] = [] for candidate in candidates: if not frontier or (weighted and candidate.cost < frontier[-1].cost - 1e-9): frontier.append(candidate) - sequences.append(tuple(frontier)) - viable = [candidate for candidate in sequences[index] if candidate.span <= usable] + sequences[height] = tuple(frontier) + # The shortest prefix determines whether a successor can fit. + remaining = max_usable - frontier[0].span + for offset, span, _ in bends: + next_height = height + offset + if span <= remaining and next_height not in queued: + heappush(upcoming, next_height) + queued.add(next_height) + viable = [candidate for candidate in sequences.get(magnitude, ()) if candidate.span <= usable] if not viable: return None best = viable[-1] @@ -388,7 +396,10 @@ def _schedules( sbend_penalty: float, allowed_offsets: frozenset[float] | None = None, ) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]: - choose = _bend_sequences(spans, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets) + max_usable = max(before - after - 4 for (_, after), (before, _) in pairwise(windows)) + choose = _bend_sequences( + spans, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, + ) needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths)) # The track order allows a local check of each neighboring pair. The diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index e56b0c2..7b931ed 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -48,7 +48,7 @@ def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None: def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None: make_sequence = Mock(wraps=_columns._BendSequence) monkeypatch.setattr(_columns, "_BendSequence", make_sequence) - choose = _columns._bend_sequences({10: 30}, 25, LENGTH_COST, weighted=False, sbend_penalty=0) + choose = _columns._bend_sequences({10: 30}, 25, LENGTH_COST, max_usable=40, weighted=False, sbend_penalty=0) make_sequence.reset_mock() assert choose(100, 40) is None @@ -66,7 +66,7 @@ def test_sbend_sequences_use_the_common_offset_stride() -> None: spans = SparseSpans({40_000_000: 120_000_000, 80_000_000: 160_000_000}) spans.scans = 0 - choose = _columns._bend_sequences(spans, 100_000_000, LENGTH_COST, weighted=False, sbend_penalty=0) + choose = _columns._bend_sequences(spans, 100_000_000, LENGTH_COST, max_usable=280_000_000, weighted=False, sbend_penalty=0) assert choose(40_000_001, 120_000_000) is None assert choose(40_000_000, 119_999_999) is None @@ -75,6 +75,41 @@ def test_sbend_sequences_use_the_common_offset_stride() -> None: assert choose(120_000_000, 280_000_000).offsets == (80_000_000, 40_000_000) +def test_sbend_sequence_only_builds_reachable_shifts_within_the_maximum_window(monkeypatch) -> None: + max_usable = 399_891 + make_sequence = _columns._BendSequence + built = 0 + + def count_sequence(offsets, span, cost): + nonlocal built + built += 1 + assert span <= max_usable + assert built <= 81 + return make_sequence(offsets, span, cost) + + monkeypatch.setattr(_columns, "_BendSequence", count_sequence) + choose = _columns._bend_sequences( + {20: 5000, 125_002: 375_006}, 312_505, LENGTH_COST, max_usable=max_usable, weighted=False, sbend_penalty=0, + ) + + assert choose(125_000, max_usable) is None + sequence = choose(125_002, max_usable) + assert sequence.offsets == (125_002,) + assert sequence.span == 375_006 + + +def test_weighted_sbend_sequence_keeps_both_short_and_low_cost_choices() -> None: + weights = {"straight": 1.0, "sbend": 1.0} + choose = _columns._bend_sequences({2: 14, 10: 30}, 25, weights, max_usable=70, weighted=True, sbend_penalty=0) + + short = choose(10, 30) + low_cost = choose(10, 70) + + assert short.offsets == (10,) + assert low_cost.offsets == (2,) * 5 + assert low_cost.cost < short.cost + + def test_exact_sbend_spans_filter_by_window_and_configured_offsets() -> None: assert exact_sbend_spans(25, max_span=40, offsets=(-20, 10, 40, 0)) == {10: 30, 20: 40} assert exact_sbend_spans(25, max_span=39, offsets=(-20,)) == {} From 253ea1f9c9c4d2cbb961d8c37d95a1402e6ba7d2 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 10:12:01 -0800 Subject: [PATCH 12/57] Keep lattice scan limits out of local S-bend seeds --- inire/router/_compact.py | 8 ++------ inire/tests/test_compact.py | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/inire/router/_compact.py b/inire/router/_compact.py index c55b2ae..f7a5c64 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -168,10 +168,8 @@ def compact_port_seed_set(problem: RoutingProblem, search: SearchOptions) -> dic 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) + yield _path(forward) return if not search.allows_sbend_offset(offset): return @@ -187,9 +185,7 @@ def _shift_seeds(forward: int, offset: int, search: SearchOptions) -> Iterator[P 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) + yield _path(lead, SBendSeed(offset, radius), spare - lead) def short_shift_seed_set(problem: RoutingProblem, search: SearchOptions, score: Scorer) -> dict[str, PathSeed] | None: diff --git a/inire/tests/test_compact.py b/inire/tests/test_compact.py index 4f2a93d..7373658 100644 --- a/inire/tests/test_compact.py +++ b/inire/tests/test_compact.py @@ -1,3 +1,5 @@ +import pytest + from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, route @@ -37,3 +39,23 @@ def test_local_sbend_packing_skips_intersecting_candidates_at_zero_clearance() - assert all(result.is_valid for result in run.results_by_net.values()) assert run.automatic.selected_planner == "local-sbend" assert run.metrics.nodes_expanded == 0 + + + +@pytest.mark.parametrize(("forward", "scan_limit"), [(18, 2000), (14, 20)], ids=["short-tangents", "long-straight"]) +def test_local_sbend_seeds_can_use_straights_outside_lattice_scan_limits(forward, scan_limit) -> None: + east = NetSpec("east", Port(10, 10, 0), Port(10 + forward, 15, 0)) + north = NetSpec("north", Port(70, 10, 90), Port(65, 10 + forward, 90)) + line = NetSpec("line", Port(10, 40, 0), Port(40, 40, 0)) + problem = RoutingProblem((0, 0, 100, 100), (east, north, line), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10,), min_straight_length=5, max_straight_length=scan_limit), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert all(run.results_by_net[net.net_id].is_valid for net in problem.nets) + assert run.automatic.selected_planner == "local-sbend" + assert run.metrics.nodes_expanded == 0 From e0efd0418180e13a6a1e5867fe7e9d6165bc4378 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 10:12:54 -0800 Subject: [PATCH 13/57] Store predecessor links for column S-bend sequences --- inire/router/_columns.py | 35 ++++++++++++++++++++++++----------- inire/tests/test_columns.py | 23 +++++++++++++++++++---- 2 files changed, 43 insertions(+), 15 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 7f60437..497a3be 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -67,6 +67,15 @@ class _BendSequence: cost: float +@dataclass(frozen=True, slots=True, repr=False, eq=False) +class _BendState: + offset: int + previous: _BendState | None + span: int + cost: float + length: int + + def _columns(problem: RoutingProblem, start: int, finish: int) -> tuple[_Column, ...]: # A bounding rectangle only reserves extra space in this candidate # planner. Capacity proofs still require the actual rectangular obstacles. @@ -314,7 +323,7 @@ def _bend_sequences( for d, span in spans.items() if span <= max_usable ] - sequences = {0: (_BendSequence((), 0, 0.0),)} + sequences = {0: (_BendState(0, None, 0, 0.0, 0),)} upcoming = sorted(offset for offset, _, _ in bends) stride = gcd(*upcoming) or 1 queued = set(upcoming) @@ -329,19 +338,20 @@ def _bend_sequences( height = heappop(upcoming) queued.remove(height) candidates = [ - _BendSequence((offset, *prefix.offsets), span + prefix.span, cost + prefix.cost) + _BendState(offset, prefix, span + prefix.span, cost + prefix.cost, prefix.length + 1) for offset, span, cost in bends for prefix in sequences.get(height - offset, ()) if span + prefix.span <= max_usable ] + # For each leading offset and span, at most one predecessor survives. candidates.sort( key=lambda candidate: ( candidate.span, - candidate.cost if weighted else len(candidate.offsets), - tuple(-d for d in candidate.offsets), + candidate.cost if weighted else candidate.length, + -candidate.offset, ) ) - frontier: list[_BendSequence] = [] + frontier: list[_BendState] = [] for candidate in candidates: if not frontier or (weighted and candidate.cost < frontier[-1].cost - 1e-9): frontier.append(candidate) @@ -353,13 +363,16 @@ def _bend_sequences( if span <= remaining and next_height not in queued: heappush(upcoming, next_height) queued.add(next_height) - viable = [candidate for candidate in sequences.get(magnitude, ()) if candidate.span <= usable] - if not viable: + best = next((state for state in reversed(sequences.get(magnitude, ())) if state.span <= usable), None) + if best is None: return None - best = viable[-1] - if delta < 0: - return _BendSequence(tuple(-offset for offset in best.offsets), best.span, best.cost) - return best + sign = -1 if delta < 0 else 1 + offsets = [] + state = best + while state.previous is not None: + offsets.append(sign * state.offset) + state = state.previous + return _BendSequence(tuple(offsets), best.span, best.cost) return choose diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 7b931ed..ead1001 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -77,17 +77,17 @@ def test_sbend_sequences_use_the_common_offset_stride() -> None: def test_sbend_sequence_only_builds_reachable_shifts_within_the_maximum_window(monkeypatch) -> None: max_usable = 399_891 - make_sequence = _columns._BendSequence + make_state = _columns._BendState built = 0 - def count_sequence(offsets, span, cost): + def count_state(offset, previous, span, cost, length): nonlocal built built += 1 assert span <= max_usable assert built <= 81 - return make_sequence(offsets, span, cost) + return make_state(offset, previous, span, cost, length) - monkeypatch.setattr(_columns, "_BendSequence", count_sequence) + monkeypatch.setattr(_columns, "_BendState", count_state) choose = _columns._bend_sequences( {20: 5000, 125_002: 375_006}, 312_505, LENGTH_COST, max_usable=max_usable, weighted=False, sbend_penalty=0, ) @@ -98,6 +98,21 @@ def test_sbend_sequence_only_builds_reachable_shifts_within_the_maximum_window(m assert sequence.span == 375_006 +def test_sbend_table_reconstructs_only_the_chosen_sequence(monkeypatch) -> None: + make_sequence = _columns._BendSequence + + def build_sequence(offsets, span, cost): + assert offsets == (-180_002,) + return make_sequence(offsets, span, cost) + + monkeypatch.setattr(_columns, "_BendSequence", build_sequence) + choose = _columns._bend_sequences( + {20: 6000, 180_002: 540_006}, 450_005, LENGTH_COST, max_usable=65_000_000, weighted=False, sbend_penalty=0, + ) + + assert choose(-180_002, 65_000_000).span == 540_006 + + def test_weighted_sbend_sequence_keeps_both_short_and_low_cost_choices() -> None: weights = {"straight": 1.0, "sbend": 1.0} choose = _columns._bend_sequences({2: 14, 10: 30}, 25, weights, max_usable=70, weighted=True, sbend_penalty=0) From 1f48f60d93db7d1588f978e2d57dd1da918acc31 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 10:14:14 -0800 Subject: [PATCH 14/57] Sweep active rectangles for automatic capacity bounds --- inire/geometry/intervals.py | 4 ++- inire/router/_capacity.py | 56 +++++++++++++++++++++++++++--------- inire/tests/test_capacity.py | 14 ++++++++- 3 files changed, 58 insertions(+), 16 deletions(-) diff --git a/inire/geometry/intervals.py b/inire/geometry/intervals.py index 68fbf2a..e9c9fa0 100644 --- a/inire/geometry/intervals.py +++ b/inire/geometry/intervals.py @@ -1,9 +1,11 @@ """Intervals left open by solid spans.""" +from collections.abc import Iterable + Gap = tuple[float, float] -def open_intervals(solid: list[Gap], ymin: float, ymax: float) -> tuple[Gap, ...]: +def open_intervals(solid: Iterable[Gap], ymin: float, ymax: float) -> tuple[Gap, ...]: openings = [] cursor = ymin for bottom, top in sorted(solid): diff --git a/inire/router/_capacity.py b/inire/router/_capacity.py index 564b370..c76fb9f 100644 --- a/inire/router/_capacity.py +++ b/inire/router/_capacity.py @@ -2,6 +2,7 @@ from __future__ import annotations +from bisect import bisect_left, bisect_right from itertools import pairwise from math import floor, isfinite from typing import TYPE_CHECKING @@ -16,12 +17,14 @@ from inire.model import resolve_bend_geometry from inire.results import CapacityLimit if TYPE_CHECKING: + from inire.geometry.intervals import Gap from inire.model import RoutingOptions, RoutingProblem def _rectangular_obstacle_bounds(problem: RoutingProblem) -> tuple[tuple[float, float, float, float], ...] | None: - bounds = tuple(tuple(shape.bounds) for shape in problem._blocking_polygons) - if any(shape.is_empty or not shape.equals(box(*extent)) for shape, extent in zip(problem._blocking_polygons, bounds, strict=True)): + polygons = problem._blocking_polygons + bounds = tuple(tuple(shape.bounds) for shape in polygons) + if any(shape.is_empty or not shape.equals(box(*extent)) for shape, extent in zip(polygons, bounds, strict=True)): return None return bounds @@ -29,32 +32,57 @@ def _rectangular_obstacle_bounds(problem: RoutingProblem) -> tuple[tuple[float, def cut_capacity(problem: RoutingProblem, options: RoutingOptions) -> CapacityLimit | None: """Bound routes across vertical cuts through truly rectangular obstacles.""" _, physical_geometry = resolve_bend_geometry(options.search) + if physical_geometry != "arc" or not problem.nets: + return None obstacles = _rectangular_obstacle_bounds(problem) - if physical_geometry != "arc" or not obstacles or not problem.nets: + if not obstacles: return None # The narrowest guide gives an optimistic upper bound for mixed widths. width = min(net.width for net in problem.nets) if not isfinite(width) or width <= 0 or problem.clearance < 0: return None - pitch = width + problem.clearance + clearance = problem.clearance + half_width = width / 2 + pitch = max(TOLERANCE_LINEAR, width + clearance - TOLERANCE_LINEAR) + ymin, ymax = problem.bounds[1], problem.bounds[3] + net_intervals = [] + for net in problem.nets: + left = min(net.start.x, net.target.x) + half_width + right = max(net.start.x, net.target.x) - half_width + if left < right: + net_intervals.append((left, right)) + net_starts = sorted(left for left, _ in net_intervals) + net_ends = sorted(right for _, right in net_intervals) + + starts = sorted((left, index, (bottom, top)) for index, (left, bottom, _, top) in enumerate(obstacles)) + ends = sorted((right, index) for index, (_, _, right, _) in enumerate(obstacles)) + edges = sorted({left for left, _, _ in starts} | {right for right, _ in ends}) + active: dict[int, Gap] = {} + start = end = 0 limit = None - edges = sorted({x for left, _, right, _ in obstacles for x in (left, right)}) for left, right in pairwise(edges): x = (left + right) / 2 - crossing = sum(min(net.start.x, net.target.x) + width / 2 < x < max(net.start.x, net.target.x) - width / 2 for net in problem.nets) + # Match the strict containment test at each cut, including a midpoint rounded to an edge. + while start < len(starts) and starts[start][0] < x: + _, index, span = starts[start] + active[index] = span + start += 1 + while end < len(ends) and ends[end][0] <= x: + _, index = ends[end] + active.pop(index, None) + end += 1 + if not active: + continue + crossing = bisect_left(net_starts, x) - bisect_right(net_ends, x) if not crossing: continue - solid = [(bottom, top) for start, bottom, end, top in obstacles if start < x < end] - if not solid: - continue - ymin, ymax = problem.bounds[1], problem.bounds[3] tracks = 0 - for low, high in open_intervals(solid, ymin, ymax): - bottom = low + width / 2 + (problem.clearance if low != ymin else 0) - top = high - width / 2 - (problem.clearance if high != ymax else 0) + for low, high in open_intervals(active.values(), ymin, ymax): + bottom = low + half_width + (clearance if low != ymin else 0) + top = high - half_width - (clearance if high != ymax else 0) room = top - bottom + 2 * TOLERANCE_LINEAR if room >= 0: - tracks += 1 + floor(room / max(TOLERANCE_LINEAR, pitch - TOLERANCE_LINEAR)) + tracks += 1 + floor(room / pitch) max_routed = len(problem.nets) - crossing + tracks if tracks < crossing and (limit is None or max_routed < limit.max_routed): limit = CapacityLimit(x, crossing, tracks, max_routed) diff --git a/inire/tests/test_capacity.py b/inire/tests/test_capacity.py index 3a7a86d..366aea0 100644 --- a/inire/tests/test_capacity.py +++ b/inire/tests/test_capacity.py @@ -1,9 +1,10 @@ from dataclasses import replace import pytest -from shapely.geometry import Polygon +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, port_conflicts from inire.tests.routing_corpus import CASE_GROUPS @@ -19,6 +20,17 @@ def test_cut_capacity_requires_rectangular_obstacles() -> None: assert cut_capacity(changed, case.options) is None +def test_cut_capacity_counts_overlapping_rectangles_and_strict_crossings() -> 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)) + vertical = NetSpec("vertical", Port(45, 10, 90), Port(45, 90, 90)) + 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) + + def test_fixed_port_conflicts_are_disjoint_and_depend_on_clearance() -> None: (case,) = CASE_GROUPS["lidar-clements-8x8"] pairs = port_conflicts(case.problem, case.options) From 80f463bf8603d74d6c1e3baa37509f27bef70f44 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 10:15:08 -0800 Subject: [PATCH 15/57] Check predecessor table growth in the short-window regression --- inire/tests/test_columns.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index ead1001..a848690 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -46,14 +46,14 @@ def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None: def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None: - make_sequence = Mock(wraps=_columns._BendSequence) - monkeypatch.setattr(_columns, "_BendSequence", make_sequence) + make_state = Mock(wraps=_columns._BendState) + monkeypatch.setattr(_columns, "_BendState", make_state) choose = _columns._bend_sequences({10: 30}, 25, LENGTH_COST, max_usable=40, weighted=False, sbend_penalty=0) - make_sequence.reset_mock() + make_state.reset_mock() assert choose(100, 40) is None assert choose(-100, 40) is None - make_sequence.assert_not_called() + make_state.assert_not_called() assert choose(-10, 30).offsets == (-10,) From 653edda5128ed63fdc0e837148483579e9de971d Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 10:41:01 -0800 Subject: [PATCH 16/57] Skip forward perimeter detours that cannot fit four turns --- inire/router/_perimeter.py | 3 ++- inire/tests/test_perimeter.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 inire/tests/test_perimeter.py diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 2306a34..a308c4e 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -246,7 +246,8 @@ def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) if net.start.x > net.target.x: yield from ((net, seed) for seed in _return_detours(problem, net, obstacles, radius)) continue - if net.start.x == net.target.x or not obstacles: + # The two outer tangencies take one radius each, and the middle leg takes two. + if net.target.x - net.start.x < 4 * radius or not obstacles: continue low, high = sorted((net.start.y, net.target.y)) if all(bottom > high or top < low or right < net.start.x or left > net.target.x for left, bottom, right, top in obstacles): diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py new file mode 100644 index 0000000..fe2252b --- /dev/null +++ b/inire/tests/test_perimeter.py @@ -0,0 +1,34 @@ +from shapely.geometry import box + +from inire import Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route + + +OPTIONS = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(10,), sbend_radii=()), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), +) + + +def test_short_forward_perimeter_detour_does_not_abort_the_batch() -> None: + short = NetSpec("short", Port(30, 30, 0), Port(31, 70, 0)) + peer = NetSpec("peer", Port(5, 90, 0), Port(95, 90, 0)) + problem = RoutingProblem((0, 0, 100, 100), (short, peer), (box(30.3, 5, 30.6, 40),), clearance=0) + + run = route(problem, options=OPTIONS) + + assert run.results_by_net["short"].outcome == "unroutable" + assert run.results_by_net["peer"].is_valid + + +def test_forward_perimeter_detour_can_fit_at_exactly_four_radii() -> None: + net = NetSpec("edge", Port(20, 25, 0), Port(60, 25, 0)) + obstacles = (box(42, 20, 45, 30), box(35, 20, 38, 30), box(75, 50, 85, 58)) + problem = RoutingProblem((0, 0, 100, 100), (net,), obstacles, clearance=0) + + run = route(problem, options=OPTIONS) + + result = run.results_by_net[net.net_id] + assert result.is_valid + assert run.automatic.selected_planner == "perimeter" + assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 From 13b2d8b7de096cf18bd633725b6015636599e43a Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 10:42:01 -0800 Subject: [PATCH 17/57] Bound implicit exact S-bend offset discovery --- docs/user/api-reference.md | 2 ++ inire/geometry/sbend.py | 11 +++++++++++ inire/router/_columns.py | 7 +++++-- inire/router/_compact.py | 7 +++++-- inire/tests/test_columns.py | 29 +++++++++++++++++++++++++++++ 5 files changed, 52 insertions(+), 4 deletions(-) diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index fcb706d..2e5cd22 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -99,6 +99,8 @@ A custom S-bend outline uses local coordinates. Its input face is centered at `( Match custom outline faces to their declared ports and width. `SBendOutline` warns about a mismatch at construction. For a custom 90-degree outline used in a result, `route()` warns once per radius and net width. Replay an `SBendSeed` with the same outlines and bend settings. +Constructive planners that need exact integer S-bend spans check up to 65,536 implicit offsets. When that budget would be exceeded, automatic routing tries other candidates. In explicit bundle mode, supply `sbend_offsets` to check a specific list of offsets. + Search and replay use placed custom outlines for board containment. When a declared port lies outside the board, proximity scoring samples the nearest point on the placed outline. Final verification checks the placed polygons against the board, keepouts, and other routes. For a complete custom S-bend outline, or a custom 90-degree bend with a custom polygon proxy, the radius determines the declared snapped endpoints. Use the supplied polygons to represent the process geometry. diff --git a/inire/geometry/sbend.py b/inire/geometry/sbend.py index eba72f9..a00630d 100644 --- a/inire/geometry/sbend.py +++ b/inire/geometry/sbend.py @@ -4,6 +4,12 @@ from math import ceil, isfinite, isqrt, sqrt from inire.constants import TOLERANCE_LINEAR +_MAX_IMPLICIT_OFFSET_CHECKS = 65_536 + + +class ExactSBendScanLimitError(ValueError): + """Implicit exact-span discovery exceeds the planner's offset budget.""" + def sbend_span(offset: float, radius: float) -> float: offset = abs(offset) @@ -29,6 +35,11 @@ def exact_sbend_spans( offset_limit = diameter - (isqrt(remaining - 1) + 1 if remaining > 0 else 1) if max_offset is not None: offset_limit = min(offset_limit, max_offset) + if offsets is None and offset_limit > _MAX_IMPLICIT_OFFSET_CHECKS: + raise ExactSBendScanLimitError( + f"Implicit exact S-bend discovery would check {offset_limit:,} offsets (limit {_MAX_IMPLICIT_OFFSET_CHECKS:,}). " + "Configure sbend_offsets to supply an explicit list." + ) candidates = range(1, offset_limit + 1) if offsets is None else sorted({int(abs(offset)) for offset in offsets}) spans = {} for offset in candidates: diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 497a3be..5cf6d3d 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -13,7 +13,7 @@ from typing import TYPE_CHECKING from shapely.geometry import LineString from inire.geometry.intervals import Gap, open_intervals -from inire.geometry.sbend import exact_sbend_spans +from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans from inire.model import resolve_bend_geometry from inire.router._waypoints import compile_waypoints from inire.seeds import PathSeed, SBendSeed, StraightSeed @@ -569,7 +569,10 @@ def column_seed_candidates( radius = int(bend) max_span = max(before - after - 4 for (_, after), (before, _) in pairwise(layout.spans)) max_offset = floor(problem.bounds[3]) - ceil(problem.bounds[1]) - spans = exact_sbend_spans(radius, max_span=max_span, max_offset=max_offset, offsets=search.sbend_offsets) + try: + spans = exact_sbend_spans(radius, max_span=max_span, max_offset=max_offset, offsets=search.sbend_offsets) + except ExactSBendScanLimitError: + return if not spans: return allowed_offsets = None if search.sbend_offsets is None else frozenset(search.sbend_offsets) diff --git a/inire/router/_compact.py b/inire/router/_compact.py index f7a5c64..d579bd5 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -11,7 +11,7 @@ from shapely.geometry import box from inire.geometry.collision import RoutingWorld, _violates_net_clearance from inire.geometry.primitives import port_local_coordinates -from inire.geometry.sbend import exact_sbend_spans, sbend_grid_span +from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans, sbend_grid_span from inire.model import resolve_bend_geometry from inire.results import RoutingResult from inire.router._seed_materialization import materialize_path_seed @@ -80,7 +80,10 @@ def _candidate_jogs( continue # Move the middle of the jog between two independently positioned # turn lanes. The S-bend stays away from the terminal access cutouts. - spans = exact_sbend_spans(radius, max_span=int(reach), max_offset=max_offset, offsets=search.sbend_offsets) + try: + spans = exact_sbend_spans(radius, max_span=int(reach), max_offset=max_offset, offsets=search.sbend_offsets) + except ExactSBendScanLimitError: + continue for offset, span in reversed(tuple(spans.items())): available = reach - span for before in _shift_positions(problem, start.y, direction, radius, span, available): diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index a848690..851efa2 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -131,6 +131,35 @@ def test_exact_sbend_spans_filter_by_window_and_configured_offsets() -> None: assert exact_sbend_spans(25, max_span=40, max_offset=10, offsets=(-20, 10, 40, 0)) == {10: 30} +def test_exact_sbend_scan_budget_applies_only_to_implicit_offsets(monkeypatch) -> None: + monkeypatch.setattr(sbend, "_MAX_IMPLICIT_OFFSET_CHECKS", 10) + + with pytest.raises(sbend.ExactSBendScanLimitError, match="would check 20 offsets"): + exact_sbend_spans(25, max_span=40) + + assert exact_sbend_spans(25, max_span=40, max_offset=10) == {2: 14, 10: 30} + assert exact_sbend_spans(25, max_span=40, offsets=(-20,)) == {20: 40} + + +def test_automatic_routes_wide_tall_boards_without_a_large_implicit_scan(monkeypatch) -> None: + def unexpected_scan(_value): + raise AssertionError("The implicit offset scan exceeds the work budget") + + monkeypatch.setattr(sbend, "isqrt", unexpected_scan) + nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(399_999_990, y, 0)) for y in (30, 60, 90)) + problem = RoutingProblem((0, 0, 400_000_000, 50_000_000), nets, (box(190_000_000, 0, 190_000_020, 10),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(100_000_000,)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert all(run.results_by_net[net.net_id].is_valid for net in nets) + assert run.metrics.nodes_expanded == 0 + + def test_wide_column_windows_only_scan_offsets_within_the_board_height(monkeypatch) -> None: square_root = sbend.isqrt scans = 0 From 5804ba568fcc0cf7512e3eb7a5971d393574d189 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 10:43:23 -0800 Subject: [PATCH 18/57] Reuse column profiles across S-bend limit passes --- inire/router/_columns.py | 26 +++++++++++++++----------- inire/tests/test_columns.py | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 5cf6d3d..0897c8a 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -512,16 +512,20 @@ def _column_sbend_schedules( columns, widths, windows, preferences = layout.columns, layout.widths, layout.spans, layout.preferences # The first pass uses moderate lateral shifts. Later passes relax the # spacing or try smaller or larger bends if a transition will not fit. - limits = tuple(dict.fromkeys(min(2 * radius - 1, ceil(radius * frac)) for frac in (0.8, 0.4, 1.44))) + limits = (min(2 * radius - 1, ceil(radius * frac)) for frac in (0.8, 0.4, 1.44)) + span_sets = dict.fromkeys(tuple((d, span) for d, span in spans.items() if d <= maximum) for maximum in limits) + active_span_sets = tuple(dict(span_set) for span_set in span_sets if span_set) + + # Keep the base and extra-spacing profiles for the current slack setting. + @lru_cache(maxsize=2 * len(columns)) + def profiles_for(column_index: int, spacing_slack: int, wall_slack: int) -> list[Profile]: + return _column_profiles( + problem, columns[column_index], widths, residues, preferences[column_index], spacing_slack, wall_slack, modulus, + ) + seen = set() - for spacing_slack, wall_slack, maximum in product((5, 3, 2, 1, 0, 7), (1, 0), limits): - active_spans = {d: span for d, span in spans.items() if d <= maximum} - if not active_spans: - continue - interior = [ - _column_profiles(problem, column, widths, residues, preference, spacing_slack, wall_slack, modulus) - for column, preference in zip(columns, preferences, strict=True) - ] + for spacing_slack, wall_slack, active_spans in product((5, 3, 2, 1, 0, 7), (1, 0), active_span_sets): + interior = [profiles_for(i, spacing_slack, wall_slack) for i in range(len(columns))] if weighted: adjacent = [[launch], *interior, [arrival]] reachable_offsets = (0, *( @@ -534,9 +538,9 @@ def _column_sbend_schedules( reachable = tuple(tuple(tuple(y + d for d in offsets) for y in anchor) for anchor, offsets in anchors) seeded = _column_profiles(problem, column, widths, residues, preference, spacing_slack, wall_slack, modulus, reachable) interior[i] = sorted(set(interior[i] + seeded)) - for i, (column, preference) in enumerate(zip(columns, preferences, strict=True)): + for i, column in enumerate(columns): if column.openings[0][0] == problem.bounds[1] or column.openings[-1][1] == problem.bounds[3]: - roomier = _column_profiles(problem, column, widths, residues, preference, spacing_slack + 5, wall_slack, modulus) + roomier = profiles_for(i, spacing_slack + 5, wall_slack) interior[i] = sorted(set(interior[i] + roomier[:45])) profiles = [[launch], *interior, [arrival]] for rows, moves in _schedules( diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 851efa2..e626abc 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -243,6 +243,27 @@ def test_sbend_column_profiles_match_exhaustive_ranking_without_using_a_product( assert _columns._column_profiles(*args) == exhaustive +@pytest.mark.parametrize("weighted", [False, True]) +def test_sbend_column_passes_reuse_profiles_and_skip_duplicate_span_sets(monkeypatch, weighted) -> None: + profile_calls = Mock(wraps=_columns._column_profiles) + schedule_calls = Mock(wraps=_columns._schedules) + monkeypatch.setattr(_columns, "_column_profiles", profile_calls) + monkeypatch.setattr(_columns, "_schedules", schedule_calls) + nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(400, y + 800, 0)) for y in (40, 110, 180)) + column_positions = (80, 180, 280) + keepouts = tuple(box(x, y, x + 20, y + 2) for x in column_positions for y in range(100, 700, 100)) + problem = RoutingProblem((0, 0, 410, 1700), nets, keepouts, clearance=0) + search = SearchOptions(bend_radii=(), sbend_radii=(10,)) + + assert list(column_seed_candidates(problem, search, LENGTH_COST, weighted=weighted)) == [] + + # Two distinct span sets share the base and extra-spacing profiles for each slack pair. + slack_pairs = 12 + assert schedule_calls.call_count == 2 * slack_pairs + base_profile_calls = sum(len(call.args) == 8 for call in profile_calls.call_args_list) + assert base_profile_calls <= 2 * len(column_positions) * slack_pairs + + def test_jog_transition_rejects_an_offset_that_cannot_fit_two_bends() -> None: assert _jog_pivots((10, 40), (17, 40), (0, 100), (2, 2), 2, 5, 1) is None assert _jog_pivots((10, 40), (25, 40), (0, 100), (2, 2), 2, 5, 1) == (8, None) From 6c5ee351c85b8068a67ede2d012ba93d2828b74b Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 11:23:55 -0800 Subject: [PATCH 19/57] Choose eligible radii for constructive routing plans --- inire/router/_bundle.py | 10 ++++---- inire/router/_columns.py | 39 ++++++++++++++++++------------ inire/router/_perimeter.py | 33 ++++++++++++++----------- inire/tests/test_columns.py | 37 ++++++++++++++++++++++++++++ inire/tests/test_perimeter.py | 17 +++++++++++++ inire/tests/test_terminal_bench.py | 22 +++++++++++++++++ 6 files changed, 124 insertions(+), 34 deletions(-) diff --git a/inire/router/_bundle.py b/inire/router/_bundle.py index 226da3b..9fad88c 100644 --- a/inire/router/_bundle.py +++ b/inire/router/_bundle.py @@ -220,17 +220,17 @@ def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer if not problem.nets: return problem _, physical_geometry = resolve_bend_geometry(search) - bend = min(search.bend_radii, default=0.0) + common_radii = {r for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r) and r in search.sbend_radii} if ( - not isfinite(bend) or bend <= 0 or bend != int(bend) or bend not in search.sbend_radii - or physical_geometry != "arc" + not common_radii or physical_geometry != "arc" or search.has_applicable_sbend_outline(net.width for net in problem.nets) ): raise ValueError("Bundle routing needs a common integer radius for circular bends and S-bends") - radius = int(bend) width = problem.nets[0].width - if not bend_fits_width(radius, width): + bend = min((r for r in common_radii if bend_fits_width(r, width)), default=0.0) + if not bend: raise ValueError("Bundle bend radius must be at least half the net width") + radius = int(bend) margin = width / 2 + problem.clearance pitch = ceil(width + problem.clearance) + 1 floor_lane = ceil(problem.bounds[1] + width / 2) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 0897c8a..fff441a 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -12,6 +12,7 @@ from typing import TYPE_CHECKING from shapely.geometry import LineString +from inire.geometry.components import bend_fits_width from inire.geometry.intervals import Gap, open_intervals from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans from inire.model import resolve_bend_geometry @@ -414,6 +415,7 @@ def _schedules( spans, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, ) needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths)) + straight_tracks = tuple(i for i, width in enumerate(widths) if not bend_fits_width(radius, width)) # The track order allows a local check of each neighboring pair. The # final router still verifies the exact arcs and every pair of routes. @@ -442,6 +444,8 @@ def _schedules( scores = [] for previous, histories in approaches.items(): offsets = tuple(b - a for a, b in zip(previous, row, strict=True)) + if straight_tracks and any(offsets[i] for i in straight_tracks): + continue sequences = [choose(d, window - 4) for d in offsets] if any(sequence is None for sequence in sequences): continue @@ -564,28 +568,33 @@ def column_seed_candidates( ) -> Iterator[dict[str, PathSeed]]: """Yield candidate routes from configured circular bends and problem geometry.""" _, physical_geometry = resolve_bend_geometry(search) - bend = min(search.sbend_radii, default=0.0) - if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend): + if problem.initial_paths or physical_geometry != "arc": + return + radii = sorted({int(r) for r in search.sbend_radii if isfinite(r) and r > 0 and r == int(r)}) + if not radii: return layout = _column_layout(problem) if layout is None: return - radius = int(bend) max_span = max(before - after - 4 for (_, after), (before, _) in pairwise(layout.spans)) max_offset = floor(problem.bounds[3]) - ceil(problem.bounds[1]) - try: - spans = exact_sbend_spans(radius, max_span=max_span, max_offset=max_offset, offsets=search.sbend_offsets) - except ExactSBendScanLimitError: - return - if not spans: - return + shifting_width = max((w for a, b, w in zip(layout.launch, layout.arrival, layout.widths, strict=True) if a != b), default=0.0) allowed_offsets = None if search.sbend_offsets is None else frozenset(search.sbend_offsets) - for moves in _column_sbend_schedules( - problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, - ): - seeds = _seeds(layout.tracks, layout.spans, moves, radius) - if all(search.seed_geometry_error(seed) is None for seed in seeds.values()): - yield seeds + for radius in radii: + if not bend_fits_width(radius, shifting_width): + continue + try: + spans = exact_sbend_spans(radius, max_span=max_span, max_offset=max_offset, offsets=search.sbend_offsets) + except ExactSBendScanLimitError: + continue + if not spans: + continue + for moves in _column_sbend_schedules( + problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, + ): + seeds = _seeds(layout.tracks, layout.spans, moves, radius) + if all(search.seed_geometry_error(seed) is None for seed in seeds.values()): + yield seeds def _jog_pivots( diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index a308c4e..39e89e1 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -7,11 +7,12 @@ from itertools import combinations, pairwise, product from math import ceil, floor, isfinite from typing import TYPE_CHECKING +from inire.geometry.components import bend90_uses_circular_geometry, bend_fits_width from inire.geometry.primitives import rotate_cardinal from inire.model import resolve_bend_geometry from inire.router._seed_materialization import materialize_path_seed from inire.router._waypoints import _direction, compile_waypoints, export_waypoints -from inire.seeds import PathSeed, StraightSeed +from inire.seeds import Bend90Seed, PathSeed, StraightSeed if TYPE_CHECKING: from collections.abc import Iterator @@ -118,7 +119,9 @@ def bundle_turnaround_candidates( returning, inferred = mismatches[0] if returning.start != inferred.start or returning.target.r != 0 or inferred.target.r != 180: return - radius = int(min(search.bend_radii)) + radius = next((int(move.radius) for move in proposal.initial_paths[returning.net_id].segments if isinstance(move, Bend90Seed)), None) + if radius is None: + return farthest = max(net.target.x for net in problem.nets) shelf = max((net for net in problem.nets if net.target.x == farthest), key=lambda net: net.target.y) if shelf == returning: @@ -189,15 +192,13 @@ def terminal_link_seed(net: NetSpec, search: SearchOptions) -> PathSeed | None: if start.r % 180 == target.r % 180: return None corner = (b[0], a[1]) if start.r % 180 == 0 else (a[0], b[1]) - radius = min(search.bend_radii, default=0.0) - if ( - not isfinite(radius) - or radius <= 0 - or corner in (a, b) - or _direction(a, corner) != start.r - or _direction(corner, b) != target.r - or min(abs(b[0] - a[0]), abs(b[1] - a[1])) < radius - ): + if corner in (a, b) or _direction(a, corner) != start.r or _direction(corner, b) != target.r: + return None + proxy, physical = resolve_bend_geometry(search) + circular = bend90_uses_circular_geometry(proxy, physical) + available = min(abs(b[0] - a[0]), abs(b[1] - a[1])) + radius = min((r for r in search.bend_radii if r <= available and (not circular or bend_fits_width(r, net.width))), default=0.0) + if not radius: return None seed, end = compile_waypoints((a, corner, b), start, radius) return seed if end == target else None @@ -235,14 +236,18 @@ def _return_detours( def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[tuple[NetSpec, PathSeed]]: """Try four-turn detours around obstacles or behind east-facing ports.""" _, physical_geometry = resolve_bend_geometry(search) - bend = min(search.bend_radii, default=0.0) - if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend): + if problem.initial_paths or physical_geometry != "arc": + 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 obstacles = tuple(shape.bounds for shape in problem._blocking_polygons if not shape.is_empty) - radius = int(bend) for net in problem.nets: if net.start.r != 0 or net.target.r != 0: continue + radius = next((r for r in radii if bend_fits_width(r, net.width)), None) + if radius is None: + continue if net.start.x > net.target.x: yield from ((net, seed) for seed in _return_detours(problem, net, obstacles, radius)) continue diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index e626abc..2c63305 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -45,6 +45,43 @@ def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None: assert bends == (SBendSeed(sign * 2, 25),) * 5 +@pytest.mark.parametrize("smaller_radius", [10, 15]) +def test_column_routes_use_a_later_radius_when_the_smallest_cannot_make_the_shift(smaller_radius) -> None: + nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(240, y + 20, 0), width=30) for y in (35, 110, 185)) + problem = RoutingProblem((0, 0, 250, 250), nets, (box(130, 0, 150, 10),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(smaller_radius, 25), sbend_offsets=(20,)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert run.automatic.selected_planner == "column" + assert run.metrics.nodes_expanded == 0 + for result in run.results_by_net.values(): + assert result.is_valid + assert {move.radius for move in result.as_seed().segments if isinstance(move, SBendSeed)} == {25} + + +def test_column_routes_allow_wide_straight_tracks_alongside_smaller_bends() -> None: + straight = NetSpec("wide", Port(5, 30, 0), Port(220, 30, 0), width=30) + shifted = tuple(NetSpec(str(y), Port(5, y, 0), Port(220, y + 8, 0)) for y in (90, 150)) + problem = RoutingProblem((0, 0, 230, 180), (straight, *shifted), (box(130, 0, 150, 10),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10, 25), sbend_offsets=(8,)), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert run.automatic.selected_planner == "column" + assert all(result.is_valid for result in run.results_by_net.values()) + for net in shifted: + assert {move.radius for move in run.results_by_net[net.net_id].as_seed().segments if isinstance(move, SBendSeed)} == {10} + + def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None: make_state = Mock(wraps=_columns._BendState) monkeypatch.setattr(_columns, "_BendState", make_state) diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index fe2252b..171b93a 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -1,3 +1,6 @@ +from dataclasses import replace + +import pytest from shapely.geometry import box from inire import Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route @@ -32,3 +35,17 @@ def test_forward_perimeter_detour_can_fit_at_exactly_four_radii() -> None: assert result.is_valid assert run.automatic.selected_planner == "perimeter" assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 + + +@pytest.mark.parametrize("smaller_radius", [10, 17.5]) +def test_perimeter_detours_choose_a_radius_usable_by_the_planner(smaller_radius) -> None: + net = NetSpec("wide", Port(20, 70, 0), Port(220, 70, 0), width=30) + problem = RoutingProblem((0, 0, 250, 180), (net,), (box(100, 40, 130, 100),), clearance=0) + options = replace(OPTIONS, search=replace(OPTIONS.search, bend_radii=(smaller_radius, 20))) + + run = route(problem, options=options) + + result = run.results_by_net[net.net_id] + assert result.is_valid + assert run.automatic.selected_planner == "perimeter" + assert {move.radius for move in result.as_seed().segments if isinstance(move, Bend90Seed)} == {20} diff --git a/inire/tests/test_terminal_bench.py b/inire/tests/test_terminal_bench.py index 0bf3f4d..23d3a1e 100644 --- a/inire/tests/test_terminal_bench.py +++ b/inire/tests/test_terminal_bench.py @@ -134,6 +134,28 @@ def test_bundle_preserves_explicit_terminal_headings_by_default() -> None: route(terminal_bench_problem(), options=options) +@pytest.mark.parametrize("mode", ["bundle", "automatic"]) +def test_bundle_and_turnaround_use_the_smallest_common_radius(mode) -> None: + options = terminal_bench_options(node_limit=1, max_iterations=1) + options = replace( + options, + search=replace(options.search, bend_radii=(BEND_RADIUS / 2, BEND_RADIUS)), + refinement=replace(options.refinement, enabled=False), + topology=TopologyOptions(mode=mode, infer_terminal_headings=(mode == "bundle")), + ) + + run = route(terminal_bench_problem(), options=options) + + assert all(result.is_valid for result in run.results_by_net.values()) + assert run.metrics.nodes_expanded == 0 + if mode == "automatic": + assert run.automatic.selected_planner == "bundle-turnaround" + for result in run.results_by_net.values(): + for move in result.as_seed().segments: + if isinstance(move, Bend90Seed | SBendSeed): + assert move.radius == BEND_RADIUS + + def test_bundle_plans_tracks_without_coincident_nets() -> None: problem = terminal_bench_problem() port = problem.nets[0].start From a83b5ed155d9bb68772626d03bba1e14b7e4277b Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 11:24:18 -0800 Subject: [PATCH 20/57] Snap return-detour board pivots inward --- inire/router/_perimeter.py | 8 +++++--- inire/tests/test_perimeter.py | 12 ++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 39e89e1..5189d4a 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -218,11 +218,13 @@ def _return_detours( high = max(start.y, target.y) + 2 * radius bottom = min(low, min((floor(bottom - margin) for _, bottom, _, _ in obstacles), default=low)) top = max(high, max((ceil(top + margin) for _, _, _, top in obstacles), default=high)) - pivots = {xmin + half_width, xmax - half_width, start.x + radius + 1, target.x - radius - 1} + left_edge = ceil(xmin + half_width) + right_edge = floor(xmax - half_width) + pivots = {left_edge, right_edge, start.x + radius + 1, target.x - radius - 1} for left, _, right, _ in obstacles: pivots.update((floor(left - margin), ceil(right + margin))) - departures = sorted(x for x in pivots if start.x + radius <= x <= xmax - half_width) - arrivals = sorted((x for x in pivots if xmin + half_width <= x <= target.x - radius), reverse=True) + departures = sorted(x for x in pivots if start.x + radius <= x <= right_edge) + arrivals = sorted((x for x in pivots if left_edge <= x <= target.x - radius), reverse=True) for y in (bottom, top): if not ymin + half_width <= y <= ymax - half_width: continue diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index 171b93a..8a95105 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -49,3 +49,15 @@ def test_perimeter_detours_choose_a_radius_usable_by_the_planner(smaller_radius) assert result.is_valid assert run.automatic.selected_planner == "perimeter" assert {move.radius for move in result.as_seed().segments if isinstance(move, Bend90Seed)} == {20} + + +def test_return_detours_snap_board_pivots_inward_before_generating_seeds() -> None: + net = NetSpec("return", Port(88, 50, 0), Port(12, 50, 0), width=3) + problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) + + run = route(problem, options=OPTIONS) + + result = run.results_by_net[net.net_id] + assert result.is_valid + assert run.automatic.selected_planner == "perimeter" + assert result.path[-1].end_port == net.target From 90b30608f6f4f74c4601f2dabb6e6337b63c5cdf Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 11:24:56 -0800 Subject: [PATCH 21/57] Allow column jog seeds beyond the lattice scan length --- inire/router/_columns.py | 2 +- inire/tests/test_columns.py | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index fff441a..556586c 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -678,7 +678,7 @@ def _jog_seeds( 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 + isinstance(move, StraightSeed) and move.length < search.min_straight_length for move in seed.segments ): return None diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 2c63305..f6667f7 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -3,7 +3,9 @@ from unittest.mock import Mock import pytest from shapely.geometry import box -from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, route +from inire import ( + CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, route, +) from inire.geometry import sbend from inire.geometry.sbend import exact_sbend_spans from inire.router import _columns @@ -304,3 +306,21 @@ def test_sbend_column_passes_reuse_profiles_and_skip_duplicate_span_sets(monkeyp def test_jog_transition_rejects_an_offset_that_cannot_fit_two_bends() -> None: assert _jog_pivots((10, 40), (17, 40), (0, 100), (2, 2), 2, 5, 1) is None assert _jog_pivots((10, 40), (25, 40), (0, 100), (2, 2), 2, 5, 1) == (8, None) + + +def test_column_jog_seeds_can_use_straights_longer_than_the_lattice_scan() -> None: + nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(405, y + 50, 0)) for y in (60, 150, 240)) + problem = RoutingProblem((0, 0, 420, 310), nets, (box(170, 0, 190, 20),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(10,), sbend_radii=(), max_straight_length=40), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert run.automatic.selected_planner == "column-jogs" + assert run.metrics.nodes_expanded == 0 + for result in run.results_by_net.values(): + assert result.is_valid + assert any(isinstance(move, StraightSeed) and move.length > 40 for move in result.as_seed().segments) From 5255b96e6a3d4d9e1ba839c33e252264d8217e7e Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 11:39:17 -0800 Subject: [PATCH 22/57] Retry bundle construction with later common radii --- inire/router/_bundle.py | 30 +++++++++++++++++++++++++++--- inire/tests/test_terminal_bench.py | 23 +++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/inire/router/_bundle.py b/inire/router/_bundle.py index 9fad88c..e6a6262 100644 --- a/inire/router/_bundle.py +++ b/inire/router/_bundle.py @@ -227,10 +227,9 @@ def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer ): raise ValueError("Bundle routing needs a common integer radius for circular bends and S-bends") width = problem.nets[0].width - bend = min((r for r in common_radii if bend_fits_width(r, width)), default=0.0) - if not bend: + radii = sorted(int(r) for r in common_radii if bend_fits_width(r, width)) + if not radii: raise ValueError("Bundle bend radius must be at least half the net width") - radius = int(bend) margin = width / 2 + problem.clearance pitch = ceil(width + problem.clearance) + 1 floor_lane = ceil(problem.bounds[1] + width / 2) @@ -239,6 +238,31 @@ def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer # destination and of the first barrier, so the bundle launches east. problem = _eastbound_launches(problem) layout = _identify_layout(problem, margin) + first_error = None + for radius in radii: + try: + return _build_bundle( + problem, layout, search, radius, margin=margin, pitch=pitch, floor_lane=floor_lane, + infer_terminal_headings=infer_terminal_headings, + ) + except ValueError as error: + if first_error is None: + first_error = error + assert first_error is not None + raise first_error + + +def _build_bundle( + problem: RoutingProblem, + layout: _Layout, + search: SearchOptions, + radius: int, + *, + margin: float, + pitch: int, + floor_lane: int, + infer_terminal_headings: bool, +) -> RoutingProblem: max_offset = floor(problem.bounds[3]) - ceil(problem.bounds[1]) shifts, launch = _assign_shifts(layout, radius, margin, pitch, floor_lane, search, max_offset=max_offset) diff --git a/inire/tests/test_terminal_bench.py b/inire/tests/test_terminal_bench.py index 23d3a1e..ef0f2a6 100644 --- a/inire/tests/test_terminal_bench.py +++ b/inire/tests/test_terminal_bench.py @@ -156,6 +156,29 @@ def test_bundle_and_turnaround_use_the_smallest_common_radius(mode) -> None: assert move.radius == BEND_RADIUS +@pytest.mark.parametrize("mode", ["bundle", "automatic"]) +def test_bundle_retries_the_next_common_radius_when_the_shelf_cannot_use_the_first(mode) -> None: + options = terminal_bench_options(node_limit=1, max_iterations=1) + radii = (BEND_RADIUS / 2, BEND_RADIUS) + options = replace( + options, + search=replace(options.search, bend_radii=radii, sbend_radii=radii, sbend_offsets=(-40, 40)), + refinement=replace(options.refinement, enabled=False), + topology=TopologyOptions(mode=mode, infer_terminal_headings=(mode == "bundle")), + ) + + run = route(terminal_bench_problem(), options=options) + + assert all(result.is_valid for result in run.results_by_net.values()) + assert run.metrics.nodes_expanded == 0 + if mode == "automatic": + assert run.automatic.selected_planner == "bundle-turnaround" + assert { + move.radius for result in run.results_by_net.values() for move in result.as_seed().segments + if isinstance(move, Bend90Seed | SBendSeed) + } == {BEND_RADIUS} + + def test_bundle_plans_tracks_without_coincident_nets() -> None: problem = terminal_bench_problem() port = problem.nets[0].start From 0e923daa9c8710d094e6326d7da944baac81781c Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 11:39:36 -0800 Subject: [PATCH 23/57] Allow residual dogleg seeds beyond the lattice scan length --- inire/router/_perimeter.py | 6 +++--- inire/tests/test_routing_benchmarks.py | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 5189d4a..a470329 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -66,7 +66,7 @@ def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions) - 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 + minimum = search.min_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) @@ -89,14 +89,14 @@ def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions) - if not remaining: return remaining -= 1 - if not 2 * radius + minimum <= b - a <= 2 * radius + maximum: + if b - a < 2 * radius + minimum: 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 + not isinstance(move, StraightSeed) or minimum <= move.length for move in seed.segments ): yield seed diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 8a8f9b6..a9cea6d 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -149,6 +149,26 @@ def test_stress_residual_dogleg_completes_layout_before_wider_search() -> None: assert iterations == list(range(observed.metrics.route_iterations)) +def test_residual_dogleg_seeds_can_use_straights_longer_than_the_lattice_scan() -> None: + case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-retry-straight-decoy") + options = replace( + case.options, + search=replace(case.options.search, node_limit=25, max_straight_length=180), + congestion=replace(case.options.congestion, max_iterations=1, warm_start_enabled=False), + refinement=replace(case.options.refinement, enabled=False), + topology=TopologyOptions(mode="automatic"), + ) + + run = route(case.problem, options=options) + + assert run.automatic.selected_planner == "residual-dogleg" + assert all(run.results_by_net[net.net_id].is_valid for net in case.problem.nets) + assert any( + isinstance(move, StraightSeed) and move.length > options.search.max_straight_length + for move in run.results_by_net["trunk"].as_seed().segments + ) + + @pytest.mark.parametrize(("iterations", "probe_limit"), [(1, 1), (3, 2)]) def test_automatic_probe_caps_iterations_and_preserves_callback_order(monkeypatch, iterations, probe_limit) -> None: (case,) = CASE_GROUPS["pic-splitter-tree-1x8-ew"] From d94f121ed28bd28d79063a307312b4aa7c5588f1 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 11:41:46 -0800 Subject: [PATCH 24/57] Retry column jogs with relaxed straight spacing --- inire/router/_automatic.py | 2 +- inire/router/_columns.py | 50 ++++++++++++++++++++++--------------- inire/tests/test_columns.py | 20 +++++++++++++++ 3 files changed, 51 insertions(+), 21 deletions(-) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 7eb1db1..8d9de02 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -477,7 +477,7 @@ class _AutomaticRun: if target != len(problem.nets) or problem.initial_paths: return False with self._time("plan", planner="column-jogs"): - for seeds in islice(column_jog_candidates(problem, options.search), 8): + for seeds in column_jog_candidates(problem, options.search, limit_per_pass=8): trial = self._verify(replace(problem, initial_paths=seeds), "column-jogs") if len(trial.valid_costs) == target: trials.append(trial) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 556586c..e29ac2e 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -664,7 +664,7 @@ def _jog_schedules( def _jog_seeds( - tracks: tuple[_Track, ...], rows: tuple[Profile, ...], moves: tuple[JogPivots, ...], radius: int, search: SearchOptions + tracks: tuple[_Track, ...], rows: tuple[Profile, ...], moves: tuple[JogPivots, ...], radius: int, minimum: float, ) -> dict[str, PathSeed] | None: seeds = {} for i, track in enumerate(tracks): @@ -677,10 +677,7 @@ def _jog_seeds( 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 move.length < search.min_straight_length - for move in seed.segments - ): + if end != track.net.target or any(isinstance(move, StraightSeed) and move.length < minimum for move in seed.segments): return None seeds[track.net.net_id] = seed return seeds @@ -691,27 +688,19 @@ def _column_jog_schedules( layout: _ColumnLayout, radii: list[int], minimum: float, + profiles_for_slack: Callable[[int], list[list[Profile]]], ) -> Iterator[tuple[int, tuple[Profile, ...], tuple[JogPivots, ...]]]: - columns, widths, preferences = layout.columns, layout.widths, layout.preferences - launch, arrival = layout.launch, layout.arrival windows = tuple((after, before) for (_, after), (before, _) in pairwise(layout.spans)) 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(widths), desired, slack, slack, 1, combinations_limit=8192) - for column, desired in zip(columns, preferences, strict=True) - ] + profiles = profiles_for_slack(slack) for radius in radii: - schedules = _jog_schedules( - [[launch], *interior, [arrival]], windows, widths, problem.clearance, radius, minimum - ) + schedules = _jog_schedules(profiles, windows, layout.widths, problem.clearance, radius, minimum) for _, rows, moves in schedules: yield radius, rows, moves -def column_jog_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[dict[str, PathSeed]]: +def column_jog_candidates(problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None) -> Iterator[dict[str, PathSeed]]: """Allocate tracks through ordered apertures using staggered 90-degree jogs.""" if problem.initial_paths: return @@ -721,7 +710,28 @@ def column_jog_candidates(problem: RoutingProblem, search: SearchOptions) -> Ite layout = _column_layout(problem) if layout is None: return - for radius, rows, moves in _column_jog_schedules(problem, layout, radii, search.min_straight_length): - seeds = _jog_seeds(layout.tracks, rows, moves, radius, search) - if seeds is not None: + @cache + def profiles_for_slack(slack: int) -> list[list[Profile]]: + widths = layout.widths + # Modulus one allows any integer track level. + interior = [ + _column_profiles(problem, column, widths, (0,) * len(widths), desired, slack, slack, 1, combinations_limit=8192) + for column, desired in zip(layout.columns, layout.preferences, strict=True) + ] + return [[layout.launch], *interior, [layout.arrival]] + + seen: set[tuple[tuple[str, PathSeed], ...]] = set() + + def seed_pass(minimum: float) -> Iterator[dict[str, PathSeed]]: + for radius, rows, moves in _column_jog_schedules(problem, layout, radii, minimum, profiles_for_slack): + seeds = _jog_seeds(layout.tracks, rows, moves, radius, minimum) + if seeds is None: + continue + signature = tuple(seeds.items()) + if signature in seen: + continue + seen.add(signature) yield seeds + + for minimum in dict.fromkeys((search.min_straight_length, 0.0)): + yield from islice(seed_pass(minimum), limit_per_pass) diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index f6667f7..519b9f8 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -324,3 +324,23 @@ def test_column_jog_seeds_can_use_straights_longer_than_the_lattice_scan() -> No for result in run.results_by_net.values(): assert result.is_valid assert any(isinstance(move, StraightSeed) and move.length > 40 for move in result.as_seed().segments) + + +@pytest.mark.parametrize(("shift", "needs_short_straights"), [(23, True), (27, False)]) +def test_column_jogs_prefer_the_lattice_minimum_but_can_relax_it(shift, needs_short_straights) -> None: + nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(1000, y + shift, 0)) for y in (30, 85, 140)) + problem = RoutingProblem((0, 0, 1010, 180), nets, (box(980, 0, 990, 10),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(10,), sbend_radii=(), min_straight_length=5), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert run.automatic.selected_planner == "column-jogs" + assert run.metrics.nodes_expanded == 0 + for result in run.results_by_net.values(): + assert result.is_valid + lengths = [move.length for move in result.as_seed().segments if isinstance(move, StraightSeed)] + assert any(length < options.search.min_straight_length for length in lengths) is needs_short_straights From 466c68024f4178640914473f240ff3f5d5856de4 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 11:59:00 -0800 Subject: [PATCH 25/57] Retry residual doglegs with relaxed straight spacing --- inire/router/_automatic.py | 2 +- inire/router/_perimeter.py | 71 +++++++++++++++++++---------------- inire/tests/test_perimeter.py | 19 +++++++++- 3 files changed, 57 insertions(+), 35 deletions(-) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 8d9de02..2dd9fb9 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -437,7 +437,7 @@ class _AutomaticRun: 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): + for seed in residual_dogleg_candidates(residual, options.search, limit_per_pass=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): diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index a470329..efb690d 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -3,7 +3,7 @@ from __future__ import annotations from dataclasses import replace -from itertools import combinations, pairwise, product +from itertools import combinations, islice, pairwise, product from math import ceil, floor, isfinite from typing import TYPE_CHECKING @@ -21,7 +21,7 @@ if TYPE_CHECKING: from inire.router._waypoints import XY -def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[PathSeed]: +def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None) -> Iterator[PathSeed]: """Try four-turn routes through interior gaps with the incumbent geometry locked.""" if len(problem.nets) != 1 or problem.initial_paths: return @@ -66,39 +66,44 @@ def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions) - 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 = search.min_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): + radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)}) + seen: set[PathSeed] = set() + + def seed_pass(minimum: float) -> Iterator[PathSeed]: + remaining = 16384 + for radius in radii: + first, last = ceil(start_x + radius + minimum), floor(end_x - radius - minimum) + if last - first < 2 * radius: 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 b - a < 2 * radius + minimum: + pivots = {first, last} + for left, _, right, _ in obstacles: + pivots.update((floor(left - radius), ceil(right + radius))) + ordered_pivots = sorted(x for x in pivots if first <= x <= last) + entrances = [x for x in ordered_pivots if straight_clear(start_x, start_y, x - radius, start_y)] + exits = [x for x in reversed(ordered_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 - 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 for move in seed.segments - ): - yield seed + 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 b - a < 2 * radius + minimum or not straight_clear(a + radius, y, b - radius, y): + continue + local_points = ((start_x, start_y), (a, start_y), (a, y), (b, y), (b, end_y), (end_x, end_y)) + seed, end = compile_waypoints(tuple(physical(x, h) for x, h in local_points), net.start, radius) + if end == net.target and seed not in seen and all( + not isinstance(move, StraightSeed) or minimum <= move.length for move in seed.segments + ): + seen.add(seed) + yield seed + + for minimum in dict.fromkeys((search.min_straight_length, 0.0)): + yield from islice(seed_pass(minimum), limit_per_pass) def bundle_turnaround_candidates( diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index 8a95105..7f842c0 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -3,7 +3,9 @@ from dataclasses import replace import pytest from shapely.geometry import box -from inire import Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route +from inire import ( + Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, StraightSeed, route, +) OPTIONS = RoutingOptions( @@ -61,3 +63,18 @@ def test_return_detours_snap_board_pivots_inward_before_generating_seeds() -> No assert result.is_valid assert run.automatic.selected_planner == "perimeter" assert result.path[-1].end_port == net.target + + +@pytest.mark.parametrize(("forward", "needs_short_straight"), [(43, True), (60, False)]) +def test_residual_doglegs_prefer_the_lattice_minimum_but_can_relax_it(forward, needs_short_straight) -> None: + trunk = NetSpec("trunk", Port(20, 50, 0), Port(20 + forward, 50, 0)) + north = NetSpec("north", Port(10, 60, 90), Port(10, 100, 90)) + rail = NetSpec("rail", Port(85, 100, 0), Port(110, 100, 0)) + problem = RoutingProblem((0, 0, 120, 120), (trunk, north, rail), (box(40, 47, 43, 53),), clearance=0) + + run = route(problem, options=OPTIONS) + + assert run.automatic.selected_planner == "residual-dogleg" + assert all(run.results_by_net[net.net_id].is_valid for net in problem.nets) + lengths = [move.length for move in run.results_by_net["trunk"].as_seed().segments if isinstance(move, StraightSeed)] + assert any(length < OPTIONS.search.min_straight_length for length in lengths) is needs_short_straight From a15693ac4fd2010a91a90b08749d177b46bdbda6 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 11:59:45 -0800 Subject: [PATCH 26/57] Defer peer-reserved perimeter detours until needed --- inire/router/_automatic.py | 24 ++++++++++++------------ inire/tests/test_perimeter.py | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 2dd9fb9..d13ee20 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -320,20 +320,20 @@ class _AutomaticRun: detours = (seed for _, seed in islice(perimeter_detour_candidates(single, options.search), 32)) candidates.append(links[-1] if supplied is not None else [*links[-1], *footprints(net, detours)]) - pairs: Iterable[tuple[tuple[PathSeed, BaseGeometry], tuple[PathSeed, BaseGeometry]]] = product(*candidates) first, second = problem.nets - for index, net in enumerate(problem.nets): - if net.net_id in problem.initial_paths or not links[1 - index]: - continue - peer_link = links[1 - index][0] - peer = problem.nets[1 - index] - fixed = FixedRoute(peer.net_id, tuple(shapely.get_parts(peer_link[1]))) - reserved = replace(problem, nets=(net,), initial_paths={}, fixed_routes=(*problem.fixed_routes, fixed)) - detours = footprints(net, (seed for _, seed in islice(perimeter_detour_candidates(reserved, options.search), 16))) - reserved_pairs = product(detours, (peer_link,)) if index == 0 else product((peer_link,), detours) - pairs = chain(pairs, reserved_pairs) - for (first_seed, first_shape), (second_seed, second_shape) in pairs: + def reserved_pairs() -> Iterator[tuple[tuple[PathSeed, BaseGeometry], tuple[PathSeed, BaseGeometry]]]: + for index, net in enumerate(problem.nets): + if net.net_id in problem.initial_paths or not links[1 - index]: + continue + peer_link = links[1 - index][0] + peer = problem.nets[1 - index] + fixed = FixedRoute(peer.net_id, tuple(shapely.get_parts(peer_link[1]))) + reserved = replace(problem, nets=(net,), initial_paths={}, fixed_routes=(*problem.fixed_routes, fixed)) + detours = footprints(net, (seed for _, seed in islice(perimeter_detour_candidates(reserved, options.search), 16))) + yield from product(detours, (peer_link,)) if index == 0 else product((peer_link,), detours) + + for (first_seed, first_shape), (second_seed, second_shape) in chain(product(*candidates), reserved_pairs()): if _violates_net_clearance(first_shape, second_shape, problem.clearance): continue plan = replace(problem, initial_paths={first.net_id: first_seed, second.net_id: second_seed}) diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index 7f842c0..1622a6f 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -6,6 +6,7 @@ from shapely.geometry import box from inire import ( Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, StraightSeed, route, ) +from inire.router import _automatic OPTIONS = RoutingOptions( @@ -78,3 +79,27 @@ def test_residual_doglegs_prefer_the_lattice_minimum_but_can_relax_it(forward, n assert all(run.results_by_net[net.net_id].is_valid for net in problem.nets) lengths = [move.length for move in run.results_by_net["trunk"].as_seed().segments if isinstance(move, StraightSeed)] assert any(length < OPTIONS.search.min_straight_length for length in lengths) is needs_short_straight + + +@pytest.mark.parametrize("requires_reservation", [False, True]) +def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeypatch, requires_reservation) -> None: + line = NetSpec("line", Port(5, 75, 0), Port(195, 75, 0)) + returning = NetSpec("return", Port(130, 50, 0), Port(40, 50, 0)) + obstacles = tuple(box(x, 100, x + 1, 104) for x in (*range(10, 29, 3), *range(142, 181, 4))) + problem = RoutingProblem((0, 0, 200, 130), (line, returning), obstacles, clearance=0) + original_detours = _automatic.perimeter_detour_candidates + calls = [] + + def detours(candidate_problem, search): + reserved = bool(candidate_problem.fixed_routes) + calls.append(reserved) + if reserved or not requires_reservation: + yield from original_detours(candidate_problem, search) + + monkeypatch.setattr(_automatic, "perimeter_detour_candidates", detours) + + run = route(problem, options=OPTIONS) + + assert run.automatic.selected_planner == "paired-perimeter" + assert all(result.is_valid for result in run.results_by_net.values()) + assert calls == ([False, False, True] if requires_reservation else [False, False]) From c32148c3127af92565cb334ac7962f4d83cb011e Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 12:12:36 -0800 Subject: [PATCH 27/57] Fit forward perimeter detours in tight spans --- inire/router/_perimeter.py | 6 ++++-- inire/tests/test_perimeter.py | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index efb690d..62fbe09 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -259,14 +259,16 @@ def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) yield from ((net, seed) for seed in _return_detours(problem, net, obstacles, radius)) continue # The two outer tangencies take one radius each, and the middle leg takes two. - if net.target.x - net.start.x < 4 * radius or not obstacles: + spare = net.target.x - net.start.x - 4 * radius + if spare < 0 or not obstacles: continue low, high = sorted((net.start.y, net.target.y)) if all(bottom > high or top < low or right < net.start.x or left > net.target.x for left, bottom, right, top in obstacles): continue margin = ceil(problem.clearance + net.width / 2 + 1) lanes = (max(ceil(top + margin) for _, _, _, top in obstacles), min(floor(bottom - margin) for _, bottom, _, _ in obstacles)) - pivots = {net.start.x + radius + 1, net.target.x - radius - 1} + end_slack = 1 if spare >= 2 else 0 + pivots = {net.start.x + radius + end_slack, net.target.x - radius - end_slack} pivots.update( x for left, _, right, _ in obstacles diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index 1622a6f..38f4248 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -40,6 +40,19 @@ def test_forward_perimeter_detour_can_fit_at_exactly_four_radii() -> None: assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 +@pytest.mark.parametrize("forward", [40, 41]) +def test_tight_forward_perimeter_detours_use_pivots_without_extra_end_spacing(forward) -> None: + net = NetSpec("edge", Port(20, 25, 0), Port(20 + forward, 25, 0)) + problem = RoutingProblem((0, 0, 100, 100), (net,), (box(38, 20, 42, 50),), clearance=0) + + run = route(problem, options=OPTIONS) + + result = run.results_by_net[net.net_id] + assert result.is_valid + assert run.automatic.selected_planner == "perimeter" + assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 + + @pytest.mark.parametrize("smaller_radius", [10, 17.5]) def test_perimeter_detours_choose_a_radius_usable_by_the_planner(smaller_radius) -> None: net = NetSpec("wide", Port(20, 70, 0), Port(220, 70, 0), width=30) From 4537392641c92e75e46349e99c4c471455b5c41e Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 12:13:27 -0800 Subject: [PATCH 28/57] Choose forward detour lanes from nearby keepouts --- inire/router/_perimeter.py | 25 +++++++++++++++---------- inire/tests/test_perimeter.py | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 62fbe09..4cd1875 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -262,25 +262,30 @@ def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) spare = net.target.x - net.start.x - 4 * radius if spare < 0 or not obstacles: continue + padding = problem.clearance + net.width / 2 + nearby = tuple(bounds for bounds in obstacles if bounds[0] <= net.target.x + padding and bounds[2] >= net.start.x - padding) low, high = sorted((net.start.y, net.target.y)) - if all(bottom > high or top < low or right < net.start.x or left > net.target.x for left, bottom, right, top in obstacles): + if all(bottom > high or top < low or right < net.start.x or left > net.target.x for left, bottom, right, top in nearby): continue - margin = ceil(problem.clearance + net.width / 2 + 1) - lanes = (max(ceil(top + margin) for _, _, _, top in obstacles), min(floor(bottom - margin) for _, bottom, _, _ in obstacles)) + margin = ceil(padding + 1) + top = max(ceil(top + margin) for _, _, _, top in nearby) + bottom = min(floor(bottom - margin) for _, bottom, _, _ in nearby) + lanes, fallback_lanes = [], [] + for y, fallback in ((top, high + 2 * radius), (bottom, low - 2 * radius)): + if min(abs(y - low), abs(y - high)) >= 2 * radius: + lanes.append(y) + else: + fallback_lanes.append(fallback) end_slack = 1 if spare >= 2 else 0 pivots = {net.start.x + radius + end_slack, net.target.x - radius - end_slack} pivots.update( x - for left, _, right, _ in obstacles + for left, _, right, _ in nearby for x in (floor(left - radius - margin), ceil(right + radius + margin)) if net.start.x + radius <= x <= net.target.x - radius ) - for y in lanes: - if ( - abs(y - net.start.y) < 2 * radius - or abs(y - net.target.y) < 2 * radius - or not problem.bounds[1] + net.width / 2 <= y <= problem.bounds[3] - net.width / 2 - ): + for y in (*lanes, *fallback_lanes): + if not problem.bounds[1] + net.width / 2 <= y <= problem.bounds[3] - net.width / 2: continue for first, last in combinations(sorted(pivots), 2): if last - first < 2 * radius: diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index 38f4248..ab1f317 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -53,6 +53,20 @@ def test_tight_forward_perimeter_detours_use_pivots_without_extra_end_spacing(fo assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 +def test_forward_perimeter_lanes_ignore_keepouts_beyond_the_target() -> None: + net = NetSpec("through", Port(20, 60, 0), Port(120, 60, 0)) + problem = RoutingProblem((0, 0, 200, 120), (net,), (box(55, 30, 85, 90),), clearance=0) + distant = (box(150, 0, 160, 4), box(150, 116, 160, 120)) + + clean = route(problem, options=OPTIONS).results_by_net[net.net_id] + cluttered = route(replace(problem, static_obstacles=(*problem.static_obstacles, *distant)), options=OPTIONS) + + result = cluttered.results_by_net[net.net_id] + assert cluttered.automatic.selected_planner == "perimeter" + assert result.is_valid + assert result.as_seed() == clean.as_seed() + + @pytest.mark.parametrize("smaller_radius", [10, 17.5]) def test_perimeter_detours_choose_a_radius_usable_by_the_planner(smaller_radius) -> None: net = NetSpec("wide", Port(20, 70, 0), Port(220, 70, 0), width=30) From 2ffd12da5f656da78626484476646e48fc798630 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 12:15:30 -0800 Subject: [PATCH 29/57] Generate ordinary perimeter pairs on demand --- inire/router/_automatic.py | 41 +++++++++++++++++++++++++---------- inire/tests/test_perimeter.py | 10 ++++++--- 2 files changed, 36 insertions(+), 15 deletions(-) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index d13ee20..b2d59c8 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -5,7 +5,7 @@ from __future__ import annotations from contextlib import contextmanager, suppress from dataclasses import replace from functools import partial -from itertools import chain, islice, pairwise, product +from itertools import chain, islice, pairwise from time import perf_counter from typing import TYPE_CHECKING @@ -57,6 +57,9 @@ if TYPE_CHECKING: from inire.router.cost import CostEvaluator from inire.seeds import PathSeed + _Footprint = tuple[PathSeed, BaseGeometry] + _PerimeterPair = tuple[_Footprint, _Footprint] + _INITIAL_NODE_LIMIT = 500 _NEAR_PORT_NODE_LIMIT = 100 @@ -298,8 +301,7 @@ class _AutomaticRun: return world = RoutingWorld.from_problem(problem, board=self.board) - def footprints(net: NetSpec, seeds: Iterable[PathSeed]) -> list[tuple[PathSeed, BaseGeometry]]: - choices = [] + def footprints(net: NetSpec, seeds: Iterable[PathSeed]) -> Iterator[_Footprint]: for seed in seeds: path = materialize_path_seed( seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance, bounds=problem.bounds, @@ -307,22 +309,36 @@ class _AutomaticRun: if not path or path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid: continue footprint = shapely.union_all([shape for component in path for shape in component.physical_geometry]) - choices.append((seed, footprint)) - return choices + yield seed, footprint - candidates: list[list[tuple[PathSeed, BaseGeometry]]] = [] - links: list[list[tuple[PathSeed, BaseGeometry]]] = [] + candidates: list[Iterator[_Footprint]] = [] + links: list[list[_Footprint]] = [] for net in problem.nets: supplied = problem.initial_paths.get(net.net_id) simple = supplied if supplied is not None else terminal_link_seed(net, options.search) - links.append(footprints(net, (simple,)) if simple is not None else []) + links.append(list(footprints(net, (simple,))) if simple is not None else []) + if supplied is not None: + candidates.append(iter(links[-1])) + continue single = replace(problem, nets=(net,), initial_paths={}) detours = (seed for _, seed in islice(perimeter_detour_candidates(single, options.search), 32)) - candidates.append(links[-1] if supplied is not None else [*links[-1], *footprints(net, detours)]) + candidates.append(chain(links[-1], footprints(net, detours))) first, second = problem.nets - def reserved_pairs() -> Iterator[tuple[tuple[PathSeed, BaseGeometry], tuple[PathSeed, BaseGeometry]]]: + def ordinary_pairs() -> Iterator[_PerimeterPair]: + left, right = candidates + checked_right: list[_Footprint] = [] + for left_candidate in left: + for right_candidate in checked_right: + yield left_candidate, right_candidate + for right_candidate in right: + checked_right.append(right_candidate) + yield left_candidate, right_candidate + if not checked_right: + return + + def reserved_pairs() -> Iterator[_PerimeterPair]: for index, net in enumerate(problem.nets): if net.net_id in problem.initial_paths or not links[1 - index]: continue @@ -331,9 +347,10 @@ class _AutomaticRun: fixed = FixedRoute(peer.net_id, tuple(shapely.get_parts(peer_link[1]))) reserved = replace(problem, nets=(net,), initial_paths={}, fixed_routes=(*problem.fixed_routes, fixed)) detours = footprints(net, (seed for _, seed in islice(perimeter_detour_candidates(reserved, options.search), 16))) - yield from product(detours, (peer_link,)) if index == 0 else product((peer_link,), detours) + for detour in detours: + yield (detour, peer_link) if index == 0 else (peer_link, detour) - for (first_seed, first_shape), (second_seed, second_shape) in chain(product(*candidates), reserved_pairs()): + for (first_seed, first_shape), (second_seed, second_shape) in chain(ordinary_pairs(), reserved_pairs()): if _violates_net_clearance(first_shape, second_shape, problem.clearance): continue plan = replace(problem, initial_paths={first.net_id: first_seed, second.net_id: second_seed}) diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index ab1f317..1c8d1ac 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -116,12 +116,15 @@ def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeyp problem = RoutingProblem((0, 0, 200, 130), (line, returning), obstacles, clearance=0) original_detours = _automatic.perimeter_detour_candidates calls = [] + generated = [] def detours(candidate_problem, search): reserved = bool(candidate_problem.fixed_routes) - calls.append(reserved) + calls.append((candidate_problem.nets[0].net_id, reserved)) if reserved or not requires_reservation: - yield from original_detours(candidate_problem, search) + for candidate in original_detours(candidate_problem, search): + generated.append(reserved) + yield candidate monkeypatch.setattr(_automatic, "perimeter_detour_candidates", detours) @@ -129,4 +132,5 @@ def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeyp assert run.automatic.selected_planner == "paired-perimeter" assert all(result.is_valid for result in run.results_by_net.values()) - assert calls == ([False, False, True] if requires_reservation else [False, False]) + assert calls == ([("return", False), ("return", True)] if requires_reservation else [("return", False)]) + assert generated == [requires_reservation] From f2b646143ff5d9b248f6523579eb411415790797 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 12:40:24 -0800 Subject: [PATCH 30/57] Account for trace clearance in forward perimeter screening --- inire/router/_perimeter.py | 2 +- inire/tests/test_perimeter.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 4cd1875..6f73cec 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -265,7 +265,7 @@ def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) padding = problem.clearance + net.width / 2 nearby = tuple(bounds for bounds in obstacles if bounds[0] <= net.target.x + padding and bounds[2] >= net.start.x - padding) low, high = sorted((net.start.y, net.target.y)) - if all(bottom > high or top < low or right < net.start.x or left > net.target.x for left, bottom, right, top in nearby): + if all(bottom > high + padding or top < low - padding for _, bottom, _, top in nearby): continue margin = ceil(padding + 1) top = max(ceil(top + margin) for _, _, _, top in nearby) diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index 1c8d1ac..dbe1ef4 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -67,6 +67,17 @@ def test_forward_perimeter_lanes_ignore_keepouts_beyond_the_target() -> None: assert result.as_seed() == clean.as_seed() +@pytest.mark.parametrize(("width", "clearance"), [(4, 0), (2, 2)]) +def test_forward_perimeter_detours_include_keepouts_clear_of_the_centerline(width, clearance) -> None: + net = NetSpec("forward", Port(20, 50, 0), Port(120, 50, 0), width=width) + problem = RoutingProblem((0, 0, 150, 100), (net,), (box(55, 51.5, 65, 60),), clearance=clearance) + + run = route(problem, options=OPTIONS) + + assert run.automatic.selected_planner == "perimeter" + assert run.results_by_net[net.net_id].is_valid + + @pytest.mark.parametrize("smaller_radius", [10, 17.5]) def test_perimeter_detours_choose_a_radius_usable_by_the_planner(smaller_radius) -> None: net = NetSpec("wide", Port(20, 70, 0), Port(220, 70, 0), width=30) From 31ad878aebd0287cba9cd9c2583e97bc307f7ff6 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 12:40:44 -0800 Subject: [PATCH 31/57] Skip unusable circular radii for residual doglegs --- inire/router/_perimeter.py | 7 ++++++- inire/tests/test_perimeter.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 6f73cec..32629cf 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -45,6 +45,12 @@ def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions, * end_x, end_y = map(int, project(net.target.x, net.target.y)) if end_x <= start_x: return + circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search)) + radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)}) + if circular: + radii = [r for r in radii if bend_fits_width(r, net.width)] + if not radii: + return half_width = net.width / 2 pad = problem.clearance + half_width _, floor_y, _, ceiling_y = extent(problem.bounds) @@ -66,7 +72,6 @@ def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions, * 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)) - radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)}) seen: set[PathSeed] = set() def seed_pass(minimum: float) -> Iterator[PathSeed]: diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index dbe1ef4..a77096d 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -119,6 +119,22 @@ def test_residual_doglegs_prefer_the_lattice_minimum_but_can_relax_it(forward, n assert any(length < OPTIONS.search.min_straight_length for length in lengths) is needs_short_straight +def test_residual_doglegs_spend_attempts_only_on_radii_that_fit_the_trace() -> None: + trunk = NetSpec("trunk", Port(30, 100, 0), Port(270, 100, 0), width=30) + north = NetSpec("north", Port(20, 150, 90), Port(20, 200, 90)) + rail = NetSpec("rail", Port(250, 200, 0), Port(300, 200, 0)) + obstacles = (box(140, 93, 153, 107), *(box(x, 180, x + 2, 182) for x in range(70, 241, 20))) + problem = RoutingProblem((0, 0, 310, 230), (trunk, north, rail), obstacles, clearance=0) + options = replace(OPTIONS, search=replace(OPTIONS.search, bend_radii=(10, 20))) + + run = route(problem, options=options) + + assert run.automatic.selected_planner == "residual-dogleg" + assert all(result.is_valid for result in run.results_by_net.values()) + segments = run.results_by_net[trunk.net_id].as_seed().segments + assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {20} + + @pytest.mark.parametrize("requires_reservation", [False, True]) def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeypatch, requires_reservation) -> None: line = NetSpec("line", Port(5, 75, 0), Port(195, 75, 0)) From 2bc8cead6e8895581a7c96ccf6b70b3aac831b18 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 12:41:20 -0800 Subject: [PATCH 32/57] Check actual keepouts on residual dogleg bounds hits --- inire/router/_perimeter.py | 23 ++++++++++++++++++++--- inire/tests/test_perimeter.py | 15 ++++++++++++++- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 32629cf..d357b59 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -3,12 +3,14 @@ from __future__ import annotations from dataclasses import replace +from functools import lru_cache from itertools import combinations, islice, pairwise, product from math import ceil, floor, isfinite from typing import TYPE_CHECKING -from inire.geometry.components import bend90_uses_circular_geometry, bend_fits_width -from inire.geometry.primitives import rotate_cardinal +from inire.geometry.collision import RoutingWorld +from inire.geometry.components import Straight, bend90_uses_circular_geometry, bend_fits_width +from inire.geometry.primitives import Port, rotate_cardinal from inire.model import resolve_bend_geometry from inire.router._seed_materialization import materialize_path_seed from inire.router._waypoints import _direction, compile_waypoints, export_waypoints @@ -62,10 +64,25 @@ def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions, * if c + pad >= start_x and a - pad <= end_x: obstacles.append((a - pad, b - pad, c + pad, d + pad)) + world: RoutingWorld | None = None + + @lru_cache(maxsize=4096) def straight_clear(a: int, b: int, c: int, d: int) -> bool: + nonlocal world + length = abs(c - a) + abs(d - b) + if not length: + return True 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) + if all(right < x0 or left > x1 or top < y0 or bottom > y1 for x0, y0, x1, y1 in obstacles): + return True + if world is None: + world = RoutingWorld.from_problem(problem) + start, end = physical(a, b), physical(c, d) + direction = _direction(start, end) + assert direction is not None + straight = Straight.generate(Port(*start, direction), length, net.width) + return not world.check_move_static(straight) lanes = {ceil(floor_y + half_width), floor(ceiling_y - half_width)} for _, bottom, _, top in obstacles: diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index a77096d..a9b5771 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -1,7 +1,7 @@ from dataclasses import replace import pytest -from shapely.geometry import box +from shapely.geometry import Polygon, box from inire import ( Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, StraightSeed, route, @@ -135,6 +135,19 @@ def test_residual_doglegs_spend_attempts_only_on_radii_that_fit_the_trace() -> N assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {20} +def test_residual_dogleg_can_cross_clear_space_inside_a_keepout_bounds() -> None: + trunk = NetSpec("trunk", Port(20, 60, 0), Port(120, 60, 0)) + north = NetSpec("north", Port(10, 70, 90), Port(10, 105, 90)) + rail = NetSpec("rail", Port(115, 100, 0), Port(145, 100, 0)) + concave = Polygon(((12, 5), (90, 5), (90, 8), (15, 8), (15, 75), (12, 75))) + problem = RoutingProblem((0, 0, 150, 120), (trunk, north, rail), (concave, box(58, 56, 65, 64)), clearance=0) + + run = route(problem, options=OPTIONS) + + assert run.automatic.selected_planner == "residual-dogleg" + assert all(result.is_valid for result in run.results_by_net.values()) + + @pytest.mark.parametrize("requires_reservation", [False, True]) def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeypatch, requires_reservation) -> None: line = NetSpec("line", Port(5, 75, 0), Port(195, 75, 0)) From 2b9d7886fd478e49a5809e9bdf0a697fd186cfb0 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 12:41:44 -0800 Subject: [PATCH 33/57] Try inner lanes for westward perimeter returns --- inire/router/_perimeter.py | 2 +- inire/tests/test_perimeter.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index d357b59..010b7b6 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -252,7 +252,7 @@ def _return_detours( pivots.update((floor(left - margin), ceil(right + margin))) departures = sorted(x for x in pivots if start.x + radius <= x <= right_edge) arrivals = sorted((x for x in pivots if left_edge <= x <= target.x - radius), reverse=True) - for y in (bottom, top): + for y in dict.fromkeys((bottom, top, low, high)): if not ymin + half_width <= y <= ymax - half_width: continue for first, last in product(departures, arrivals): diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index a9b5771..5e16d3a 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -104,6 +104,17 @@ def test_return_detours_snap_board_pivots_inward_before_generating_seeds() -> No assert result.path[-1].end_port == net.target +def test_return_detours_try_inner_lanes_when_keepouts_reach_board_edges() -> None: + net = NetSpec("return", Port(100, 50, 0), Port(20, 50, 0)) + obstacles = (box(40, 0, 50, 4), box(40, 96, 50, 100)) + problem = RoutingProblem((0, 0, 120, 100), (net,), obstacles, clearance=0) + + run = route(problem, options=OPTIONS) + + assert run.automatic.selected_planner == "perimeter" + assert run.results_by_net[net.net_id].is_valid + + @pytest.mark.parametrize(("forward", "needs_short_straight"), [(43, True), (60, False)]) def test_residual_doglegs_prefer_the_lattice_minimum_but_can_relax_it(forward, needs_short_straight) -> None: trunk = NetSpec("trunk", Port(20, 50, 0), Port(20 + forward, 50, 0)) From 393c01704a221abebb0a9b11afc1929763518e82 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 12:42:15 -0800 Subject: [PATCH 34/57] Share the return candidate budget across lanes --- inire/router/_perimeter.py | 17 +++++++++-------- inire/tests/test_perimeter.py | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 010b7b6..d996cf3 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -245,6 +245,9 @@ def _return_detours( high = max(start.y, target.y) + 2 * radius bottom = min(low, min((floor(bottom - margin) for _, bottom, _, _ in obstacles), default=low)) top = max(high, max((ceil(top + margin) for _, _, _, top in obstacles), default=high)) + lanes = tuple(y for y in dict.fromkeys((bottom, top, low, high)) if ymin + half_width <= y <= ymax - half_width) + if not lanes: + return left_edge = ceil(xmin + half_width) right_edge = floor(xmax - half_width) pivots = {left_edge, right_edge, start.x + radius + 1, target.x - radius - 1} @@ -252,14 +255,12 @@ def _return_detours( pivots.update((floor(left - margin), ceil(right + margin))) departures = sorted(x for x in pivots if start.x + radius <= x <= right_edge) arrivals = sorted((x for x in pivots if left_edge <= x <= target.x - radius), reverse=True) - for y in dict.fromkeys((bottom, top, low, high)): - if not ymin + half_width <= y <= ymax - half_width: - continue - for first, last in product(departures, arrivals): - points = ((start.x, start.y), (first, start.y), (first, y), (last, y), (last, target.y), (target.x, target.y)) - seed, end = compile_waypoints(points, start, radius) - if end == target: - yield seed + # Try each lane for a pivot pair before spending the budget on more pivots. + for first, last, y in product(departures, arrivals, lanes): + points = ((start.x, start.y), (first, start.y), (first, y), (last, y), (last, target.y), (target.x, target.y)) + seed, end = compile_waypoints(points, start, radius) + if end == target: + yield seed def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[tuple[NetSpec, PathSeed]]: diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index 5e16d3a..bb09414 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -115,6 +115,29 @@ def test_return_detours_try_inner_lanes_when_keepouts_reach_board_edges() -> Non assert run.results_by_net[net.net_id].is_valid +def test_return_detours_try_both_sides_within_the_candidate_budget(monkeypatch) -> None: + net = NetSpec("return", Port(130, 60, 0), Port(40, 60, 0)) + obstacles = (box(135, 42, 199, 48), *(box(x, 100, x + 1, 104) for x in (*range(10, 29, 3), *range(142, 181, 4)))) + problem = RoutingProblem((0, 0, 200, 130), (net,), obstacles, clearance=0) + original_detours = _automatic.perimeter_detour_candidates + generated = 0 + + def detours(candidate_problem, search): + nonlocal generated + for candidate in original_detours(candidate_problem, search): + generated += 1 + yield candidate + + monkeypatch.setattr(_automatic, "perimeter_detour_candidates", detours) + run = route(problem, options=OPTIONS) + + result = run.results_by_net[net.net_id] + assert run.automatic.selected_planner == "perimeter" + assert result.is_valid + assert next(move.direction for move in result.as_seed().segments if isinstance(move, Bend90Seed)) == "CCW" + assert 0 < generated <= 32 + + @pytest.mark.parametrize(("forward", "needs_short_straight"), [(43, True), (60, False)]) def test_residual_doglegs_prefer_the_lattice_minimum_but_can_relax_it(forward, needs_short_straight) -> None: trunk = NetSpec("trunk", Port(20, 50, 0), Port(20 + forward, 50, 0)) From 0847413ff6db064517e50b950a50ca0c99442743 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 13:05:24 -0800 Subject: [PATCH 35/57] Try inner forward detour lanes when outer lanes leave the board --- inire/router/_perimeter.py | 13 ++++++++----- inire/tests/test_perimeter.py | 11 +++++++++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index d996cf3..8f5d738 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -293,12 +293,17 @@ def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) margin = ceil(padding + 1) top = max(ceil(top + margin) for _, _, _, top in nearby) bottom = min(floor(bottom - margin) for _, bottom, _, _ in nearby) + y_floor = problem.bounds[1] + net.width / 2 + y_ceiling = problem.bounds[3] - net.width / 2 lanes, fallback_lanes = [], [] for y, fallback in ((top, high + 2 * radius), (bottom, low - 2 * radius)): - if min(abs(y - low), abs(y - high)) >= 2 * radius: + if y_floor <= y <= y_ceiling and min(abs(y - low), abs(y - high)) >= 2 * radius: lanes.append(y) - else: + elif y_floor <= fallback <= y_ceiling: fallback_lanes.append(fallback) + lanes.extend(fallback_lanes) + if not lanes: + continue end_slack = 1 if spare >= 2 else 0 pivots = {net.start.x + radius + end_slack, net.target.x - radius - end_slack} pivots.update( @@ -307,9 +312,7 @@ def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) for x in (floor(left - radius - margin), ceil(right + radius + margin)) if net.start.x + radius <= x <= net.target.x - radius ) - for y in (*lanes, *fallback_lanes): - if not problem.bounds[1] + net.width / 2 <= y <= problem.bounds[3] - net.width / 2: - continue + for y in lanes: for first, last in combinations(sorted(pivots), 2): if last - first < 2 * radius: continue diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index bb09414..fe3b20c 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -67,6 +67,17 @@ def test_forward_perimeter_lanes_ignore_keepouts_beyond_the_target() -> None: assert result.as_seed() == clean.as_seed() +def test_forward_detours_try_inner_lanes_when_keepouts_reach_board_edges() -> None: + net = NetSpec("forward", Port(20, 60, 0), Port(120, 60, 0)) + obstacles = (box(55, 50, 85, 70), box(40, 0, 45, 4), box(40, 116, 45, 120)) + problem = RoutingProblem((0, 0, 200, 120), (net,), obstacles, clearance=0) + + run = route(problem, options=OPTIONS) + + assert run.automatic.selected_planner == "perimeter" + assert run.results_by_net[net.net_id].is_valid + + @pytest.mark.parametrize(("width", "clearance"), [(4, 0), (2, 2)]) def test_forward_perimeter_detours_include_keepouts_clear_of_the_centerline(width, clearance) -> None: net = NetSpec("forward", Port(20, 50, 0), Port(120, 50, 0), width=width) From ccfe958cc3e68427b134aaecb4fe3a1d7b91ef8f Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 13:05:49 -0800 Subject: [PATCH 36/57] Share the forward detour candidate budget across lanes --- inire/router/_perimeter.py | 8 ++++---- inire/tests/test_perimeter.py | 22 ++++++++++++++++++---- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 8f5d738..67a2bc1 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -312,10 +312,10 @@ def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) for x in (floor(left - radius - margin), ceil(right + radius + margin)) if net.start.x + radius <= x <= net.target.x - radius ) - for y in lanes: - for first, last in combinations(sorted(pivots), 2): - if last - first < 2 * radius: - continue + for first, last in combinations(sorted(pivots), 2): + if last - first < 2 * radius: + continue + for y in lanes: points = ( (net.start.x, net.start.y), (first, net.start.y), diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index fe3b20c..61c810a 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -126,9 +126,23 @@ def test_return_detours_try_inner_lanes_when_keepouts_reach_board_edges() -> Non assert run.results_by_net[net.net_id].is_valid -def test_return_detours_try_both_sides_within_the_candidate_budget(monkeypatch) -> None: - net = NetSpec("return", Port(130, 60, 0), Port(40, 60, 0)) - obstacles = (box(135, 42, 199, 48), *(box(x, 100, x + 1, 104) for x in (*range(10, 29, 3), *range(142, 181, 4)))) +@pytest.mark.parametrize( + ("start", "target", "obstacles", "direction"), + [ + pytest.param( + Port(130, 60, 0), Port(40, 60, 0), + (box(135, 42, 199, 48), *(box(x, 100, x + 1, 104) for x in (*range(10, 29, 3), *range(142, 181, 4)))), + "CCW", id="return", + ), + pytest.param( + Port(20, 60, 0), Port(120, 60, 0), + (box(20, 67, 80, 73), box(85, 54, 90, 65), *(box(x, 100, x + 1, 104) for x in range(35, 86, 5))), + "CW", id="forward", + ), + ], +) +def test_perimeter_detours_try_both_sides_within_the_candidate_budget(monkeypatch, start, target, obstacles, direction) -> None: + net = NetSpec("net", start, target) problem = RoutingProblem((0, 0, 200, 130), (net,), obstacles, clearance=0) original_detours = _automatic.perimeter_detour_candidates generated = 0 @@ -145,7 +159,7 @@ def test_return_detours_try_both_sides_within_the_candidate_budget(monkeypatch) result = run.results_by_net[net.net_id] assert run.automatic.selected_planner == "perimeter" assert result.is_valid - assert next(move.direction for move in result.as_seed().segments if isinstance(move, Bend90Seed)) == "CCW" + assert next(move.direction for move in result.as_seed().segments if isinstance(move, Bend90Seed)) == direction assert 0 < generated <= 32 From ab14e62dca865cc09bd762fac5743c9e9e79a2ac Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 13:06:14 -0800 Subject: [PATCH 37/57] Try westward return bends directly at the ports --- inire/router/_perimeter.py | 13 ++++++++++--- inire/tests/test_perimeter.py | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 67a2bc1..606f110 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -250,11 +250,18 @@ def _return_detours( return left_edge = ceil(xmin + half_width) right_edge = floor(xmax - half_width) - pivots = {left_edge, right_edge, start.x + radius + 1, target.x - radius - 1} + min_departure = start.x + radius + max_arrival = target.x - radius + pivots = {left_edge, right_edge, min_departure + 1, max_arrival - 1} for left, _, right, _ in obstacles: pivots.update((floor(left - margin), ceil(right + margin))) - departures = sorted(x for x in pivots if start.x + radius <= x <= right_edge) - arrivals = sorted((x for x in pivots if left_edge <= x <= target.x - radius), reverse=True) + departures = sorted(x for x in pivots if min_departure <= x <= right_edge) + arrivals = sorted((x for x in pivots if left_edge <= x <= max_arrival), reverse=True) + # Keep the first pivot pair and try bends that meet the ports directly next. + if min_departure <= right_edge and min_departure not in departures: + departures.insert(1, min_departure) + if left_edge <= max_arrival and max_arrival not in arrivals: + arrivals.insert(1, max_arrival) # Try each lane for a pivot pair before spending the budget on more pivots. for first, last, y in product(departures, arrivals, lanes): points = ((start.x, start.y), (first, start.y), (first, y), (last, y), (last, target.y), (target.x, target.y)) diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index 61c810a..d8d4666 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -126,6 +126,21 @@ def test_return_detours_try_inner_lanes_when_keepouts_reach_board_edges() -> Non assert run.results_by_net[net.net_id].is_valid +def test_return_detours_can_fit_without_straights_at_either_port() -> None: + net = NetSpec("return", Port(100, 50, 0), Port(20, 50, 0)) + obstacles = (box(111.2, 38, 125, 62), box(0, 38, 8.8, 62)) + problem = RoutingProblem((0, 0, 125, 100), (net,), obstacles, clearance=0) + + run = route(problem, options=OPTIONS) + + assert run.automatic.selected_planner == "perimeter" + result = run.results_by_net[net.net_id] + assert result.is_valid + segments = result.as_seed().segments + assert isinstance(segments[0], Bend90Seed) + assert isinstance(segments[-1], Bend90Seed) + + @pytest.mark.parametrize( ("start", "target", "obstacles", "direction"), [ From b6480ded62c1f26a2556081df231eff6525437d4 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 13:07:21 -0800 Subject: [PATCH 38/57] Keep tracks straight when a column jog radius cannot fit them --- inire/router/_columns.py | 24 ++++++++++++++++++---- inire/tests/test_columns.py | 41 ++++++++++++++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 5 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index e29ac2e..6cfecbc 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -12,7 +12,7 @@ from typing import TYPE_CHECKING from shapely.geometry import LineString -from inire.geometry.components import bend_fits_width +from inire.geometry.components import bend90_uses_circular_geometry, bend_fits_width from inire.geometry.intervals import Gap, open_intervals from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans from inire.model import resolve_bend_geometry @@ -689,12 +689,27 @@ def _column_jog_schedules( radii: list[int], minimum: float, profiles_for_slack: Callable[[int], list[list[Profile]]], + *, + circular: bool, ) -> Iterator[tuple[int, tuple[Profile, ...], tuple[JogPivots, ...]]]: + radius_choices = [] + for radius in radii: + # Tracks that cannot bend must stay on their launch rows in every column. + straight_rows = tuple((i, layout.launch[i]) for i, width in enumerate(layout.widths) if circular and not bend_fits_width(radius, width)) + if all(layout.arrival[i] == y for i, y in straight_rows): + radius_choices.append((radius, straight_rows)) + if not radius_choices: + return windows = tuple((after, before) for (_, after), (before, _) in pairwise(layout.spans)) for slack in (1, 0): profiles = profiles_for_slack(slack) - for radius in radii: - schedules = _jog_schedules(profiles, windows, layout.widths, problem.clearance, radius, minimum) + for radius, straight_rows in radius_choices: + eligible = profiles + if straight_rows: + eligible = [[row for row in rows if all(row[i] == y for i, y in straight_rows)] for rows in profiles] + if not all(eligible): + continue + schedules = _jog_schedules(eligible, windows, layout.widths, problem.clearance, radius, minimum) for _, rows, moves in schedules: yield radius, rows, moves @@ -710,6 +725,7 @@ def column_jog_candidates(problem: RoutingProblem, search: SearchOptions, *, lim layout = _column_layout(problem) if layout is None: return + circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search)) @cache def profiles_for_slack(slack: int) -> list[list[Profile]]: widths = layout.widths @@ -723,7 +739,7 @@ def column_jog_candidates(problem: RoutingProblem, search: SearchOptions, *, lim seen: set[tuple[tuple[str, PathSeed], ...]] = set() def seed_pass(minimum: float) -> Iterator[dict[str, PathSeed]]: - for radius, rows, moves in _column_jog_schedules(problem, layout, radii, minimum, profiles_for_slack): + for radius, rows, moves in _column_jog_schedules(problem, layout, radii, minimum, profiles_for_slack, circular=circular): seeds = _jog_seeds(layout.tracks, rows, moves, radius, minimum) if seeds is None: continue diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 519b9f8..1b5454b 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -4,7 +4,8 @@ import pytest from shapely.geometry import box from inire import ( - CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, route, + Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, + route, ) from inire.geometry import sbend from inire.geometry.sbend import exact_sbend_spans @@ -326,6 +327,44 @@ def test_column_jog_seeds_can_use_straights_longer_than_the_lattice_scan() -> No assert any(isinstance(move, StraightSeed) and move.length > 40 for move in result.as_seed().segments) +def test_column_jogs_skip_radii_too_small_for_a_shifting_track() -> None: + wide = NetSpec("wide", Port(5, 60, 0), Port(405, 160, 0), width=30) + narrow = tuple(NetSpec(str(y), Port(5, y, 0), Port(405, y + 100, 0)) for y in (200, 340)) + problem = RoutingProblem((0, 0, 420, 470), (wide, *narrow), (box(170, 0, 190, 20),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(8, 9, 10, 11, 12, 13, 14, 20), sbend_radii=()), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert run.automatic.selected_planner == "column-jogs" + assert all(result.is_valid for result in run.results_by_net.values()) + segments = run.results_by_net[wide.net_id].as_seed().segments + assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {20} + + +def test_column_jogs_allow_wide_straight_tracks_alongside_smaller_bends() -> None: + wide = NetSpec("wide", Port(5, 30, 0), Port(405, 30, 0), width=30) + narrow = tuple(NetSpec(str(y), Port(5, y, 0), Port(405, y + 50, 0)) for y in (90, 170)) + problem = RoutingProblem((0, 0, 420, 240), (wide, *narrow), (box(170, 0, 190, 10),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=1, bend_radii=(10,), sbend_radii=()), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + ) + + run = route(problem, options=options) + + assert run.automatic.selected_planner == "column-jogs" + assert all(result.is_valid for result in run.results_by_net.values()) + assert all(isinstance(move, StraightSeed) for move in run.results_by_net[wide.net_id].as_seed().segments) + for net in narrow: + segments = run.results_by_net[net.net_id].as_seed().segments + assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {10} + + @pytest.mark.parametrize(("shift", "needs_short_straights"), [(23, True), (27, False)]) def test_column_jogs_prefer_the_lattice_minimum_but_can_relax_it(shift, needs_short_straights) -> None: nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(1000, y + shift, 0)) for y in (30, 85, 140)) From 6c6eb37064572f258e03f7716b7d3f2e089e3ad8 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 15:24:03 -0800 Subject: [PATCH 39/57] Expand the routing benchmark corpus with 72 boards --- docs/benchmark-fixtures.md | 17 + docs/benchmarks.md | 5 +- inire/tests/routing_benchmark_case.py | 1 + inire/tests/routing_corpus.py | 10 +- inire/tests/routing_expanded_benchmarks.py | 364 +++++++++++++++++++++ inire/tests/test_routing_benchmarks.py | 38 ++- scripts/compare_topological_routing.py | 5 + 7 files changed, 435 insertions(+), 5 deletions(-) create mode 100644 inire/tests/routing_expanded_benchmarks.py diff --git a/docs/benchmark-fixtures.md b/docs/benchmark-fixtures.md index 2e4e87d..932a9ee 100644 --- a/docs/benchmark-fixtures.md +++ b/docs/benchmark-fixtures.md @@ -3,6 +3,23 @@ - [Benchmark cases](benchmarks.md#choose-a-case) - [Corpus registry and profiles](../inire/tests/routing_corpus.py) +## Micron-scale routing cases + +The `expanded` group adds 72 deterministic, unseeded boards with independently constructed reference routes. The authored grid units are 10, 100, 250, 500, and 1000 nm. Bend radii span 10–100 µm and trace widths span 1–20 µm. The comparison script records `grid_nm` for these boards. Convert benchmark-weighted lengths to microns by multiplying by `grid_nm / 1000`. + +| Group | Boards | Coverage | +| --- | ---: | --- | +| `geometry-corners` | 32 | Exact four-bend spans, tight returns and paired routes, exact-span S-bend slots, mixed widths, and saturated or overloaded apertures. | +| `complex-layouts` | 24 | Serial aperture banks with opposing tracks, concave and fixed-route keepouts, and staggered crossing arrays. | +| `search-challenges` | 8 | Alternating comb walls that force repeated turns and exercise search-budget exhaustion. | +| `scaling` | 8 | Banks and crossing arrays of up to 256 nets, obstacle fields with up to 320 keepouts, and a 240-net board with 240 keepouts and four blocked approaches. | + +The 72 reference layouts run in pytest. The corner and complex groups and seven scaling boards also have unseeded coverage assertions at the regression budget. Use `--case search-challenges` or `--case scaling` with an explicit budget to measure search and coverage on the harder boards. For scaling comparisons, use the same grid, mode, and budget and collect repeated timings with `--repeat`. + +To exercise the low-budget fallbacks on tight geometry, run `--case geometry-corners --profile corpus-regression --mode automatic --nodes 1 --seed-nodes 1 --iterations 1`. + +- [Fixture definitions](../inire/tests/routing_expanded_benchmarks.py) + ## Complex-routing example 1 Use `complex-routing-example-1` to test fixed eastbound arrival and `complex-routing-example-1-point-terminals` to test heading inference. diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 22a18eb..ecc7a25 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -17,11 +17,12 @@ Expect `3/4 valid`. All four nets need to cross a vertical cut where the opening | If you are changing | Use `--case` | | --- | --- | -| Overall coverage | `corpus` runs the regression suite. | +| Overall coverage | `corpus` runs all benchmark boards, including the search and scaling workloads. | | Ordered tracks, shared gates, and barrier layouts | `all` includes the fixed-heading complex-routing example 1. Use `corpus` for the full regression suite. | | 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. | | 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. @@ -38,7 +39,7 @@ List cases with `python -m scripts.compare_topological_routing --list`. Start wi Both budget profiles use benchmark weights when selecting an automatic candidate. A stage can use a smaller budget, and a net can be searched more than once. Match the profile, options, and worker count when measuring a change. -### Run the full regression corpus +### Run the full benchmark corpus ```sh python -m scripts.compare_topological_routing \ diff --git a/inire/tests/routing_benchmark_case.py b/inire/tests/routing_benchmark_case.py index 2ddb1b2..2390d4c 100644 --- a/inire/tests/routing_benchmark_case.py +++ b/inire/tests/routing_benchmark_case.py @@ -21,6 +21,7 @@ class BenchmarkCase: options: RoutingOptions reference_paths: tuple[tuple[str, PathSeed], ...] = () expected_routed: int | None = None + grid_nm: int | None = None @property def routing_bound(self) -> int: diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index d308cd9..15daa56 100644 --- a/inire/tests/routing_corpus.py +++ b/inire/tests/routing_corpus.py @@ -16,6 +16,7 @@ from inire.tests.routing_benchmarks import ( FALLBACK_BENCHMARK_CASES, VALIDATION_BENCHMARK_CASES, ) +from inire.tests.routing_expanded_benchmarks import COMPLEX_CASES, CORNER_CASES, SCALING_CASES, SCALING_REGRESSION_CASES, SEARCH_CASES from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from inire.tests.terminal_bench_scenario import LENGTH_COST @@ -27,7 +28,9 @@ if TYPE_CHECKING: BROAD_CASES = (*VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) -CORPUS_CASES = (*BENCHMARK_CASES, *BROAD_CASES, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES) +_STANDARD_CASES = (*BENCHMARK_CASES, *BROAD_CASES, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES, *CORNER_CASES, *COMPLEX_CASES) +CORPUS_REGRESSION_CASES = (*_STANDARD_CASES, *SCALING_REGRESSION_CASES) +CORPUS_CASES = (*_STANDARD_CASES, *SEARCH_CASES, *SCALING_CASES) SNAPSHOT_CASES = tuple( case for case in (*BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) if case.name != "terminal-bench" ) @@ -47,6 +50,11 @@ CASE_GROUPS = { "broad": BROAD_CASES, "crossings": CROSSING_BENCHMARK_CASES, "stress": STRESS_BENCHMARK_CASES, + "geometry-corners": CORNER_CASES, + "complex-layouts": COMPLEX_CASES, + "search-challenges": SEARCH_CASES, + "scaling": SCALING_CASES, + "expanded": (*CORNER_CASES, *COMPLEX_CASES, *SEARCH_CASES, *SCALING_CASES), "retry-holdout": RETRY_HOLDOUT_CASES, "corpus": CORPUS_CASES, } diff --git a/inire/tests/routing_expanded_benchmarks.py b/inire/tests/routing_expanded_benchmarks.py new file mode 100644 index 0000000..406ec79 --- /dev/null +++ b/inire/tests/routing_expanded_benchmarks.py @@ -0,0 +1,364 @@ +"""Deterministic micron-scale layouts with independently specified routes.""" + +from __future__ import annotations + +from dataclasses import replace +from itertools import pairwise, product +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.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: + """Convert authored microns to integer layout units before timing the router.""" + assert 1000 % grid_nm == 0 + factor = 1000 // grid_nm + if factor == 1: + return replace(case, grid_nm=grid_nm) + + def port(p: Port) -> Port: + return Port(p.x * factor, p.y * factor, p.r) + + def polygon(shape: Polygon) -> Polygon: + return scale(shape, xfact=factor, yfact=factor, origin=(0, 0)) + + def move(segment: PathSegmentSeed) -> PathSegmentSeed: + if isinstance(segment, StraightSeed): + return StraightSeed(segment.length * factor) + if isinstance(segment, Bend90Seed): + return Bend90Seed(segment.radius * factor, segment.direction) + return SBendSeed(segment.offset * factor, segment.radius * factor) + + problem, options = case.problem, case.options + assert not problem.initial_paths + xmin, ymin, xmax, ymax = problem.bounds + scaled_problem = replace( + problem, + bounds=(xmin * factor, ymin * factor, xmax * factor, ymax * factor), + nets=tuple(NetSpec(net.net_id, port(net.start), port(net.target), net.width * factor) for net in problem.nets), + static_obstacles=tuple(polygon(shape) for shape in problem.static_obstacles), + fixed_routes=tuple(FixedRoute(route.net_id, tuple(polygon(shape) for shape in route.polygons)) for route in problem.fixed_routes), + clearance=problem.clearance * factor, + safety_zone_radius=problem.safety_zone_radius * factor, + self_clearance=problem.self_clearance * factor, + ) + search = options.search + offsets = search.sbend_offsets + scaled_options = replace( + options, + search=replace( + search, + bend_radii=tuple(r * factor for r in search.bend_radii), + sbend_radii=tuple(r * factor for r in search.sbend_radii), + sbend_offsets=None if offsets is None else tuple(offset * factor for offset in offsets), + min_straight_length=search.min_straight_length * factor, + max_straight_length=search.max_straight_length * factor, + proximity_range=search.proximity_range * factor, + ), + # Component scoring divides the bend surcharge by the square root of the radius. + objective=replace( + options.objective, + bend_penalty=options.objective.bend_penalty * factor**1.5, + sbend_penalty=options.objective.sbend_penalty * factor**1.5, + ), + congestion=replace(options.congestion, base_penalty=options.congestion.base_penalty * factor), + ) + reference = tuple((net_id, PathSeed(tuple(move(segment) for segment in seed.segments))) for net_id, seed in case.reference_paths) + return replace(case, problem=scaled_problem, options=scaled_options, reference_paths=reference, grid_nm=grid_nm) + + +def _forward(name: str, r: int, width: int, slack: int, *, grid: int = 1000, edge_clutter: bool = False) -> BenchmarkCase: + start, y, finish = 2 * r, 4 * r, 6 * r + slack + height = 8 * r + obstacles = (box(4 * r - r // 5, y - r // 2, 4 * r + r // 5, y + r // 2),) + if edge_clutter: + obstacles += (box(3 * r, 0, 4 * r, r // 3), box(3 * r, height - r // 3, 4 * r, height)) + route = _Track("through", ((start, y), (3 * r, y), (3 * r, y + 2 * r), (finish - r, y + 2 * r), (finish - r, y), (finish, y)), width) + return _on_grid(_waypoint_case( + f"precision-forward-{name}", "Four turns at the tangency limit, with edge clutter or slack to control available lanes", + (0, 0, finish + 2 * r, height), obstacles, (route,), radius=r, clearance=1, + ), grid) + + +def _return(name: str, r: int, width: int, *, tight: bool = False, peer: bool = False, rise: int = 0, grid: int = 1000) -> BenchmarkCase: + start, finish, y, height = 10 * r, 2 * r, 4 * r, 9 * r + right, left, lane = start + r, finish - r, y - 2 * r + board_width = 13 * r + obstacles = (box(4 * r, 0, 5 * r, r // 3), box(6 * r, height - r // 3, 7 * r, height)) + if tight: + edge = width / 2 + 0.25 + obstacles += (box(right + edge, y - r, board_width, y + r), box(0, y + rise - r, left - edge, y + rise + r)) + tracks = (_Track("return", ((start, y), (right, y), (right, lane), (left, lane), (left, y + rise), (finish, y + rise)), width),) + if peer: + tracks += (_Track("through", ((2 * r, 7 * r), (board_width - r, 7 * r)), width=width),) + return _on_grid(_waypoint_case( + f"precision-return-{name}", "East-facing westward return with limited lead room or a neighboring through track", + (0, 0, board_width, height), obstacles, tracks, radius=r, clearance=0, + ), grid) + + +def _sbend_slot(name: str, radius: int, count: int, width: int, *, pitch: int, sign: int = 1, grid: int = 1000) -> BenchmarkCase: + # A 3-4-5 triangle makes these spans exact on every chosen grid. + offset, span = sign * 4 * radius // 5, 8 * radius // 5 + start, turn, end = radius, 3 * radius, 7 * radius + levels = tuple(2 * radius + pitch * i for i in range(count)) + shifted = tuple(y + offset for y in levels) + height = max(*levels, *shifted) + 2 * radius + clearance = 2 + half_slot = width // 2 + clearance + 1 + obstacles = (*_wall(turn - 9, turn - 3, height, tuple((y - half_slot, y + half_slot) for y in levels)), + *_wall(turn + span + 3, turn + span + 9, height, tuple((y - half_slot, y + half_slot) for y in shifted))) + tracks = tuple( + _Track(f"lane_{i}", ((start, a), (turn, a), (turn + span, b), (end, b)), width) + for i, (a, b) in enumerate(zip(levels, shifted, strict=True)) + ) + case = _waypoint_case( + f"precision-sbend-{name}", "Short bank of exact signed S-bends between aligned narrow port slots", + (0, 0, 8 * radius, height), obstacles, tracks, radius=radius, clearance=clearance, + ) + options = replace(case.options, search=replace(case.options.search, bend_radii=(), sbend_offsets=(offset,))) + return _on_grid(replace(case, options=options), grid) + + +def _aperture(name: str, widths: tuple[int, ...], clearance: int, *, extra: int = 0, grid: int = 1000) -> BenchmarkCase: + lower = 32 + cursor = lower + clearance + tracks = [] + for i, width in enumerate(widths): + row = cursor + width // 2 + tracks.append(_Track(f"lane_{i}", ((20, row), (260, row)), width)) + cursor += width + clearance + upper = cursor + height = upper + 64 + case = _waypoint_case( + f"precision-aperture-{name}", "Exact-capacity wall opening with sized trace pitches and optional competing ports", + (0, 0, 280, height), _wall(120, 160, height, ((lower, upper),)), tuple(tracks), radius=10, clearance=clearance, + ) + if extra: + start = upper + 10 + overflow = tuple(NetSpec(f"overflow_{i}", Port(20, start + 10 * i, 0), Port(260, start + 10 * i, 0), widths[0]) for i in range(extra)) + case = replace(case, problem=replace(case.problem, nets=(*case.problem.nets, *overflow)), expected_routed=len(widths)) + return _on_grid(case, grid) + + +def _columns(name: str, count: int, walls: int, radius: int, width: int, *, shift_units: int, grid: int = 1000) -> BenchmarkCase: + rise = shift_units * radius + pitch = width + 14 + wall_pitch = count * (2 * radius + 10) + 4 * radius + 40 + finish = (walls + 1) * wall_pitch + 10 + height = 4 * radius + (walls + 1) * rise + count * pitch + rows = tuple(tuple(2 * radius + bank * rise + track * pitch for track in range(count)) for bank in range(walls + 2)) + obstacles = tuple( + obstacle + for bank in range(1, walls + 1) + for obstacle in _wall(bank * wall_pitch, bank * wall_pitch + 18, height, ((rows[bank][0] - width, rows[bank][-1] + width),)) + ) + tracks = [] + for i, path_rows in enumerate(zip(*rows, strict=True)): + points = [(20, path_rows[0])] + for bank, (low, high) in enumerate(pairwise(path_rows)): + x = bank * wall_pitch + 26 + radius + (count - 1 - i) * (2 * radius + 10) + points.extend(((x, low), (x, high))) + points.append((finish, path_rows[-1])) + tracks.append(_Track(f"lane_{i}", tuple(reversed(points)) if i % 2 else tuple(points), width)) + return _on_grid(_waypoint_case( + f"complex-column-{name}", "Alternating net directions through multiple narrow, ascending aperture banks", + (0, 0, finish + 30, height), obstacles, tuple(tracks), radius=radius, clearance=2, + ), grid) + + +def _residual(name: str, *, width: int, rise: int, fixed: bool, grid: int = 1000) -> BenchmarkCase: + concave = Polygon(((10, 6), (94, 6), (94, 12), (16, 12), (16, 83), (10, 83))) + obstacles = (concave, box(68, 55, 78, 66)) + upper = 60 + rise + tracks = (_Track("trunk", ((26, 60), (42, 60), (42, upper), (105, upper), (105, 60), (138, 60)), width),) + if not fixed: + tracks += (_Track("west_branch", ((6, 75), (6, 114))), _Track("east_rail", ((99, 19), (138, 19)), width=4)) + case = _waypoint_case( + f"complex-residual-{name}", "A dogleg passes through open space inside a concave obstacle's bounding box", + (0, 0, 152, 128), obstacles, tracks, radius=10, clearance=1, + ) + if fixed: + lock = FixedRoute("installed_rail", (box(99, 17, 138, 21),)) + case = replace(case, problem=replace(case.problem, fixed_routes=(lock,))) + return _on_grid(case, grid) + + +def _crossings(name: str, rows: int, columns: int, pitch_x: int, pitch_y: int, *, staggered: bool, grid: int = 1000) -> BenchmarkCase: + return _on_grid(_crossing_grid( + name, f"{rows} by {columns} placed crossing cells with {'staggered' if staggered else 'aligned'} links and opposing port banks", + tuple(160 + pitch_x * col for col in range(columns)), tuple(165 + pitch_y * row for row in range(rows)), staggered=staggered, + ), grid) + + +def _comb(name: str, lanes: int, teeth: int, radius: int, *, grid: int = 1000) -> BenchmarkCase: + pitch = 8 * radius + x_pitch = 5 * radius + finish = (teeth + 1) * x_pitch + width = min(12, radius) + tracks = [] + obstacles = [] + for i in range(lanes): + base = i * pitch + if i: + obstacles.append(box(0, base - 2, finish + 20, base + 2)) + rows = tuple(base + (2 if (j + i) % 2 else 6) * radius for j in range(teeth + 1)) + points = [(radius, rows[0])] + for j, (a, b) in enumerate(pairwise(rows), 1): + x = j * x_pitch - 2 * radius + points.extend(((x, a), (x, b))) + if b > a: + obstacles.append(box(j * x_pitch - radius // 2, base, j * x_pitch + radius // 2, base + 4 * radius)) + else: + obstacles.append(box(j * x_pitch - radius // 2, base + 4 * radius, j * x_pitch + radius // 2, base + pitch)) + points.append((finish, rows[-1])) + tracks.append(_Track(f"lane_{i}", tuple(reversed(points)) if i % 2 else tuple(points), width)) + return _on_grid(_waypoint_case( + f"search-comb-{name}", "Alternating teeth force repeated changes of lane in isolated channels", + (0, 0, finish + 20, lanes * pitch), tuple(obstacles), tuple(tracks), radius=radius, clearance=2, + ), grid) + + +def _port_bank(name: str, count: int, *, obstacles: bool, detours: int = 0, grid: int = 1000) -> BenchmarkCase: + width, clearance, pitch = 4, 2, 10 + straight = count - detours + height = straight * pitch + 20 + detours * 110 + tracks = [ + _Track(f"lane_{i:03}", ((20, y), (560, y)) if i % 2 else ((560, y), (20, y)), width) + for i, y in enumerate(range(10, 10 + straight * pitch, pitch)) + ] + keepouts = [box(160 + 26 * (i % 9), 14 + i * pitch, 195 + 26 * (i % 9), 16 + i * pitch) for i in range(straight)] if obstacles else [] + for i in range(detours): + y = straight * pitch + 50 + 110 * i + points = ((20, y), (100, y), (100, y + 45), (440, y + 45), (440, y), (560, y)) + tracks.append(_Track(f"bypass_{i}", points if i % 2 else tuple(reversed(points)), width)) + keepouts.append(box(190 + 30 * i, y - 10, 260 + 30 * i, y + 10)) + description = f"{count} interleaved eastbound and westbound nets" + if obstacles: + description += " with one keepout per row" + if detours: + description += f" and {detours} obstructed approaches" + return _on_grid(_waypoint_case( + f"scale-bank-{name}", description, (0, 0, 580, height), tuple(keepouts), tuple(tracks), radius=20, clearance=clearance, + ), grid) + + +def _obstacle_field(columns: int, rows: int, count: int, *, grid: int) -> BenchmarkCase: + pitch = 24 + field_end = 140 + pitch * columns + field_base = 64 + height = field_base + pitch * rows + 120 + lanes = tuple(field_base + pitch * i + 10 for i in range(count)) + obstacles = tuple( + box(140 + pitch * col, field_base + pitch * row + col % 3, 152 + pitch * col, field_base + pitch * row + 13 + col % 3) + for col, row in product(range(columns), range(rows)) + ) + # Stagger the turns outside the field so that no vertical leg crosses a peer's occupied row. + tracks = [] + for i, y in enumerate(lanes): + lead = 32 + 22 * i + tail = field_end + 30 + 22 * (count - 1 - i) + lane = 12 + 10 * i + tracks.append(_Track(f"bus_{i}", ((18, y), (lead, y), (lead, lane), (tail, lane), (tail, y), (field_end + 150, y)), 2)) + return _on_grid(_waypoint_case( + f"scale-field-{columns}x{rows}", f"{columns * rows} staggered rectangular obstacles across the straight approaches of {count} buses", + (0, 0, field_end + 170, height), obstacles, tuple(tracks), radius=10, clearance=2, + ), grid) + + +CORNER_CASES = ( + _forward("exact-r10", 10, 1, 0), + _forward("plus-one", 10, 4, 1), + _forward("plus-two", 20, 8, 2, grid=500), + _forward("large-radius", 100, 20, 0), + _forward("board-edges", 20, 4, 0, edge_clutter=True), + _forward("board-edges-fine", 10, 2, 2, grid=100, edge_clutter=True), + _forward("wide-exact", 25, 16, 0, grid=250), + _forward("grid-10nm", 10, 2, 0, grid=10), + _return("exact-pivots", 10, 2, tight=True), + _return("wide-exact-pivots", 20, 10, tight=True), + _return("offset", 25, 4, rise=18), + _return("offset-fine", 10, 3, rise=6, grid=100), + _return("paired", 20, 4, peer=True), + _return("paired-tight", 10, 2, tight=True, peer=True), + _return("paired-wide", 30, 12, peer=True, rise=20, grid=500), + _return("large-radius", 100, 20, tight=True, grid=250), + _sbend_slot("single-r25", 25, 1, 2, pitch=32), + _sbend_slot("single-r50", 50, 1, 6, pitch=32, sign=-1, grid=500), + _sbend_slot("single-r100", 100, 1, 8, pitch=32, grid=250), + _sbend_slot("single-10nm", 25, 1, 2, pitch=32, sign=-1, grid=10), + _sbend_slot("paired", 25, 2, 4, pitch=18, grid=500), + _sbend_slot("paired-down", 25, 2, 4, pitch=16, sign=-1), + _sbend_slot("three", 25, 3, 4, pitch=16), + _sbend_slot("four-wide", 50, 4, 8, pitch=22, sign=-1), + _aperture("pair-exact", (2, 2), 2), + _aperture("four-exact", (4,) * 4, 2, grid=500), + _aperture("six-exact", (2,) * 6, 3), + _aperture("mixed-tight", (2, 8, 4, 12), 2, grid=250), + _aperture("mixed-wide", (16, 4, 20), 3), + _aperture("overloaded-three", (2,) * 3, 3, extra=1), + _aperture("overloaded-five", (4,) * 5, 2, extra=2), + _aperture("overloaded-fine", (2,) * 2, 2, extra=1, grid=100), +) + +COMPLEX_CASES = ( + _columns("3x1", 3, 1, 10, 4, shift_units=3), + _columns("3x2", 3, 2, 10, 4, shift_units=3), + _columns("4x2", 4, 2, 10, 6, shift_units=3), + _columns("4x3", 4, 3, 10, 6, shift_units=3), + _columns("5x2", 5, 2, 15, 6, shift_units=3, grid=500), + _columns("5x3", 5, 3, 15, 8, shift_units=3), + _columns("6x2-wide", 6, 2, 20, 12, shift_units=4), + _columns("6x3", 6, 3, 20, 8, shift_units=4), + _residual("narrow-dogleg", width=2, rise=30, fixed=False), + _residual("wide-dogleg", width=10, rise=44, fixed=False), + _residual("midwidth-fine", width=6, rise=38, fixed=False, grid=250), + _residual("wide-fine", width=12, rise=45, fixed=False, grid=500), + _residual("fixed-rail", width=4, rise=34, fixed=True), + _residual("fixed-rail-wide", width=12, rise=44, fixed=True), + _residual("fixed-rail-fine", width=2, rise=34, fixed=True, grid=100), + _residual("fixed-rail-midwidth", width=8, rise=40, fixed=True, grid=500), + _crossings("complex-crossing-2x2-aligned", 2, 2, 130, 154, staggered=False), + _crossings("complex-crossing-2x3-staggered", 2, 3, 110, 128, staggered=True), + _crossings("complex-crossing-3x2-fine", 3, 2, 118, 132, staggered=True, grid=250), + _crossings("complex-crossing-3x3-uneven-pitch", 3, 3, 108, 147, staggered=True), + _crossings("complex-crossing-3x4-aligned", 3, 4, 108, 97, staggered=False), + _crossings("complex-crossing-3x4-staggered", 3, 4, 102, 116, staggered=True), + _crossings("complex-crossing-4x3-tight", 4, 3, 90, 96, staggered=True), + _crossings("complex-crossing-4x4", 4, 4, 116, 108, staggered=True), +) + +SEARCH_CASES = ( + _comb("1x2", 1, 2, 10), + _comb("1x4", 1, 4, 12), + _comb("2x3", 2, 3, 10), + _comb("2x5-fine", 2, 5, 10, grid=250), + _comb("3x4", 3, 4, 15), + _comb("4x6", 4, 6, 15), + _comb("5x5", 5, 5, 20), + _comb("6x7", 6, 7, 20), +) + +SCALING_REGRESSION_CASES = ( + _crossings("scale-crossing-10x10-aligned", 10, 10, 120, 132, staggered=False), + _crossings("scale-crossing-10x11-staggered", 10, 11, 120, 132, staggered=True), + _port_bank("224", 224, obstacles=False), + _port_bank("256-fine", 256, obstacles=False, grid=100), + _port_bank("216-with-keepouts", 216, obstacles=True), + _obstacle_field(16, 16, 3, grid=1000), + _port_bank("240-with-keepouts", 240, obstacles=True, detours=4, grid=500), +) + +SCALING_CASES = ( + *SCALING_REGRESSION_CASES, + _obstacle_field(20, 16, 4, grid=500), +) diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index a9cea6d..a6d5c74 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -23,7 +23,7 @@ from inire.tests.routing_benchmarks import ( EXTERNAL_BENCHMARK_CASES, FALLBACK_BENCHMARK_CASES, ) -from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options +from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, CORPUS_REGRESSION_CASES, automatic_options, profile_options from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from scripts.compare_topological_routing import ( _direct_trials, @@ -41,7 +41,7 @@ def _measure(case, options, strategy): @pytest.mark.routing_corpus @pytest.mark.parametrize( "case", - [pytest.param(case, id=case.name) for case in CORPUS_CASES], + [pytest.param(case, id=case.name) for case in CORPUS_REGRESSION_CASES], ) def test_automatic_reaches_corpus_routing_bound(case) -> None: profile = "corpus-regression" @@ -56,6 +56,40 @@ def test_automatic_reaches_corpus_routing_bound(case) -> None: assert len(verified) == case.routing_bound +def test_expanded_corpus_uses_physical_dimensions_and_has_reference_coverage() -> None: + corpus_names = {case.name for case in CORPUS_CASES} + assert len(corpus_names) == len(CORPUS_CASES) + expanded = CASE_GROUPS["expanded"] + assert 50 <= len(expanded) <= 100 + for case in expanded: + assert case.name in corpus_names + assert case.grid_nm is not None + assert 10 <= case.grid_nm <= 1000 + assert not case.problem.initial_paths + assert len(dict(case.reference_paths)) == case.routing_bound + assert all(1000 <= net.width * case.grid_nm <= 20000 for net in case.problem.nets) + radii = (*case.options.search.bend_radii, *case.options.search.sbend_radii) + assert radii + assert all(10000 <= radius * case.grid_nm <= 100000 for radius in radii) + scaling = CASE_GROUPS["scaling"] + assert any(len(case.problem.nets) >= 200 and len(case.problem.static_obstacles) >= 200 for case in scaling) + assert any(len(case.problem.nets) < 200 <= len(case.problem.static_obstacles) for case in scaling) + assert any(len(case.problem.static_obstacles) < 200 <= len(case.problem.nets) for case in scaling) + + +def test_benchmark_json_records_the_authored_grid(tmp_path, monkeypatch) -> None: + output = tmp_path / "benchmark.json" + monkeypatch.setattr(sys, "argv", [ + "bench", "--case", "precision-sbend-single-10nm", "--profile", "corpus-regression", "--mode", "automatic", "--json", str(output), + ]) + + run_benchmarks() + + [run] = loads(output.read_text())["runs"] + assert run["grid_nm"] == 10 + assert run["options"]["search"]["sbend_radii"] == [2500] + + @pytest.mark.parametrize( "case", [pytest.param(case, id=case.name) for case in (*CORPUS_CASES, *RETRY_HOLDOUT_CASES) if case.reference_paths], diff --git a/scripts/compare_topological_routing.py b/scripts/compare_topological_routing.py index cd963b6..80eb16f 100644 --- a/scripts/compare_topological_routing.py +++ b/scripts/compare_topological_routing.py @@ -302,6 +302,10 @@ def main() -> None: ("external", "External cases"), ("crossings", "Preplaced crossings"), ("stress", "Stress cases"), + ("geometry-corners", "Tight geometry"), + ("complex-layouts", "Complex layouts"), + ("search-challenges", "Search challenges"), + ("scaling", "Large net and keepout counts"), ("retry-holdout", "Retry-policy holdouts"), ): print(f"{title} (--case {group})") @@ -378,6 +382,7 @@ def main() -> None: "case": case.name, "strategy": mode, "requested_mode": mode_options[mode].topology.mode, + "grid_nm": case.grid_nm, "reference_net_ids": [net_id for net_id, _ in case.reference_paths], "options": asdict(mode_options[mode]), "samples": [asdict(sample) for sample in samples[mode]], From bcd9ade3eae185fa7bd8ba332327bbdcedeef4de Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 15:24:10 -0800 Subject: [PATCH 40/57] Recover remaining routes with column plans and residual detours --- docs/architecture.md | 2 +- docs/benchmark-fixtures.md | 2 +- inire/router/_automatic.py | 62 ++++++++++++++--- inire/router/_columns.py | 78 ++++++++++++++++++++-- inire/tests/routing_corpus.py | 9 +-- inire/tests/routing_expanded_benchmarks.py | 6 +- inire/tests/test_routing_benchmarks.py | 51 +++++++++++++- 7 files changed, 179 insertions(+), 31 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index b1dc292..fb6925c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -10,7 +10,7 @@ Follow the left column while coverage is below the target. Reaching the target s 1. **Set a coverage target.** Conflicting aligned port faces and [track capacity](../inire/router/_capacity.py#L29) at rectangular cuts can bound how many nets fit. 2. **Try constructive plans.** Bundles assign ordered tracks, columns schedule turns, and compact planners fit short links. Each plan supplies seeds for the worker to verify. -3. **Search for missing routes.** Early attempts use small budgets and can hold verified routes fixed. If the locks cut off a port, retry with movable seeds or different lanes. Lattice search handles custom outlines or proxies and is the fallback when corridor planning is unavailable. +3. **Search for missing routes.** Early attempts use small budgets and can hold verified routes fixed. When a column plan stalls, try separated channels or a shared bypass around the keepouts. If the locks cut off a port, retry with movable seeds or different lanes. With one net left, try a verified detour around the locked paths, including incumbents found by the seed fallback. Lattice search handles custom outlines or proxies and is the fallback when corridor planning is unavailable. 4. **Select and refine.** Prefer higher verified coverage. Compare cost on matching verified net IDs. Refinement can replace the selected layout only if those IDs remain verified. ### Example of a poor lock diff --git a/docs/benchmark-fixtures.md b/docs/benchmark-fixtures.md index 932a9ee..95c27cf 100644 --- a/docs/benchmark-fixtures.md +++ b/docs/benchmark-fixtures.md @@ -14,7 +14,7 @@ The `expanded` group adds 72 deterministic, unseeded boards with independently c | `search-challenges` | 8 | Alternating comb walls that force repeated turns and exercise search-budget exhaustion. | | `scaling` | 8 | Banks and crossing arrays of up to 256 nets, obstacle fields with up to 320 keepouts, and a 240-net board with 240 keepouts and four blocked approaches. | -The 72 reference layouts run in pytest. The corner and complex groups and seven scaling boards also have unseeded coverage assertions at the regression budget. Use `--case search-challenges` or `--case scaling` with an explicit budget to measure search and coverage on the harder boards. For scaling comparisons, use the same grid, mode, and budget and collect repeated timings with `--repeat`. +Pytest verifies the 72 reference layouts and checks that unseeded routing reaches the known bound on every board. Use `--case search-challenges` or `--case scaling` with an explicit budget to compare routing policies on the harder boards. For scaling comparisons, use the same grid, mode, and budget and collect repeated timings with `--repeat`. To exercise the low-budget fallbacks on tight geometry, run `--case geometry-corners --profile corpus-regression --mode automatic --nodes 1 --seed-nodes 1 --iterations 1`. diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index b2d59c8..c2445b1 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -17,7 +17,7 @@ from inire.model import FixedRoute, resolve_bend_geometry from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle from inire.router._capacity import cut_capacity, port_conflicts -from inire.router._columns import column_jog_candidates, column_seed_candidates +from inire.router._columns import column_jog_candidates, column_recovery_candidates, column_recovery_subproblems, column_seed_candidates from inire.router._compact import compact_port_seed_set, short_shift_seed_set from inire.router._congestion_policy import ordered_nets from inire.router._perimeter import ( @@ -427,9 +427,9 @@ class _AutomaticRun: return [replace(trial, selection="requires-layout-check"), self._verify_incumbent(trial)] trials = [trial] if len(trial.valid_costs) < target: - dogleg = self._residual_dogleg_trial(options, _best_trial([best, trial])) - if dogleg is not None: - return [trial, dogleg] + construction = self._residual_constructive_trial(options, _best_trial([best, trial])) + if construction is not None: + return [trial, construction] joint = self._joint_lane_trial(residual, options, locks, trial) if joint is not None: trials.append(replace(joint, selection="requires-layout-check")) @@ -444,7 +444,7 @@ class _AutomaticRun: results = {**trial.run.results_by_net, **verified.run.results_by_net} return replace(verified.as_replacement_for(trial), run=replace(verified.run, results_by_net=results)) - def _residual_dogleg_trial(self, options: RoutingOptions, incumbent: Trial) -> Trial | None: + def _residual_constructive_trial(self, options: RoutingOptions, incumbent: Trial, *, limit_per_pass: int = 8) -> Trial | None: problem = self.problem if len(incumbent.valid_costs) != len(problem.nets) - 1: return None @@ -452,9 +452,14 @@ class _AutomaticRun: residual = _residual_problem(problem, LockPlan(retained)) (net,) = residual.nets seeds = {net_id: result.as_seed() for net_id, result in retained.items()} - planner = "residual-dogleg" + if net.start.r == net.target.r == 0 and net.start.x > net.target.x: + planner = "residual-perimeter" + candidates = (seed for _, seed in islice(perimeter_detour_candidates(residual, options.search), 32)) + else: + planner = "residual-dogleg" + candidates = residual_dogleg_candidates(residual, options.search, limit_per_pass=limit_per_pass) with self._time("plan", planner=planner, policy=planner): - for seed in residual_dogleg_candidates(residual, options.search, limit_per_pass=8): + for seed in candidates: candidate = replace(problem, initial_paths={**seeds, net.net_id: seed}) trial = self._verify(candidate, planner, policy=planner) if len(trial.valid_costs) == len(problem.nets): @@ -501,6 +506,29 @@ class _AutomaticRun: return True return False + def _column_recovery_trial(self, options: RoutingOptions) -> Trial | None: + problem = self.problem + if problem.initial_paths or not options.search.bend_radii or not problem._blocking_polygons: + return None + planner = "column-recovery" + with self._time("plan", planner=planner): + groups = column_recovery_subproblems(problem) + if not groups: + return None + combined = {} + for group in groups: + for seeds in column_recovery_candidates(group, options.search): + trial = self._verify(replace(group, initial_paths=seeds), planner) + if len(trial.valid_costs) == len(group.nets): + if group is problem: + return trial + combined.update(seeds) + break + else: + return None + trial = self._verify(replace(problem, initial_paths=combined), planner) + return trial if len(trial.valid_costs) == len(problem.nets) else None + def _search_trials(self, trials: list[Trial], target: int) -> None: configured_search = self.options.search first_limit = min(_INITIAL_NODE_LIMIT, configured_search.node_limit) @@ -552,9 +580,9 @@ class _AutomaticRun: return True if try_construction_early and target == len(problem.nets) and target > 2 and not problem.initial_paths: - dogleg = self._residual_dogleg_trial(options, _best_trial(probe)) - if dogleg is not None: - trials.append(dogleg) + construction = self._residual_constructive_trial(options, _best_trial(probe)) + if construction is not None: + trials.append(construction) return True if len(problem.nets) <= 2: @@ -563,6 +591,12 @@ class _AutomaticRun: if len(_best_trial(trials).valid_costs) >= target: return True + if target == len(problem.nets) and not options.congestion.shuffle_nets: + recovery = self._column_recovery_trial(options) + if recovery is not None: + trials.append(recovery) + return True + # Every short shift has lateral displacement, so the direct retry cannot lock # any straight paths. It would run the same guide with the same budget. if early is None or early.run.metrics.timeout_events: @@ -578,7 +612,13 @@ class _AutomaticRun: if len(_best_trial(trials).valid_costs) < target: run = self._run(problem, options=seeded, policy="seed-fallback") stage = RoutingStage("seed", (), run.metrics.nodes_expanded, options.search.node_limit, policy="seed-fallback") - trials.append(self._trial(run, stage)) + candidate = self._trial(run, stage) + trials.append(candidate) + if not problem.initial_paths and len(candidate.valid_costs) == target - 1 and _best_trial(trials) is candidate: + # The seed fallback can leave a better set of incumbents for a final detour. + construction = self._residual_constructive_trial(options, candidate, limit_per_pass=16) + if construction is not None: + trials.append(construction) def _joint_lane_trial(self, residual: RoutingProblem, options: RoutingOptions, locks: LockPlan, previous: Trial) -> Trial | None: if len(residual.nets) < 2: diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 6cfecbc..138db99 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -3,14 +3,15 @@ from __future__ import annotations from collections import defaultdict -from dataclasses import dataclass +from dataclasses import dataclass, replace from functools import cache, lru_cache from heapq import heappop, heappush, merge from itertools import combinations_with_replacement, islice, pairwise, product from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin from typing import TYPE_CHECKING -from shapely.geometry import LineString +from shapely import total_bounds +from shapely.geometry import LineString, box from inire.geometry.components import bend90_uses_circular_geometry, bend_fits_width from inire.geometry.intervals import Gap, open_intervals @@ -22,6 +23,8 @@ from inire.seeds import PathSeed, SBendSeed, StraightSeed if TYPE_CHECKING: from collections.abc import Callable, Iterator, Mapping + from shapely.geometry import Polygon + from inire.geometry.primitives import Port from inire.model import NetSpec, RoutingProblem, SearchOptions from inire.router._waypoints import XY @@ -117,9 +120,9 @@ def _ordered_tracks(problem: RoutingProblem) -> tuple[_Track, ...]: return tuple(tracks) -def _column_layout(problem: RoutingProblem) -> _ColumnLayout | None: +def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3) -> _ColumnLayout | None: tracks = _ordered_tracks(problem) - if len(tracks) < 3 or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks): + if len(tracks) < min_tracks or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks): return None start = max(int(track.left.x) for track in tracks) finish = min(int(track.right.x) for track in tracks) @@ -715,14 +718,16 @@ def _column_jog_schedules( -def column_jog_candidates(problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None) -> Iterator[dict[str, PathSeed]]: +def column_jog_candidates( + problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None, recovery: bool = False, +) -> Iterator[dict[str, PathSeed]]: """Allocate tracks through ordered apertures using staggered 90-degree jogs.""" if problem.initial_paths: return radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)}) if not radii: return - layout = _column_layout(problem) + layout = _column_layout(problem, min_tracks=1 if recovery else 3) if layout is None: return circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search)) @@ -730,10 +735,20 @@ def column_jog_candidates(problem: RoutingProblem, search: SearchOptions, *, lim def profiles_for_slack(slack: int) -> list[list[Profile]]: widths = layout.widths # Modulus one allows any integer track level. + residues = (0,) * len(widths) interior = [ - _column_profiles(problem, column, widths, (0,) * len(widths), desired, slack, slack, 1, combinations_limit=8192) + _column_profiles(problem, column, widths, residues, desired, slack, slack, 1, combinations_limit=8192) for column, desired in zip(layout.columns, layout.preferences, strict=True) ] + if recovery: + # Terminal rows can carry through a column without a jog. They also + # give later turns room when the interpolated rows hug aperture edges. + anchors = dict.fromkeys((layout.launch, layout.arrival)) + for i, column in enumerate(layout.columns): + rows = set(interior[i]) + for anchor in anchors: + rows.update(_column_profiles(problem, column, widths, residues, anchor, slack, slack, 1)) + interior[i] = sorted(rows) return [[layout.launch], *interior, [layout.arrival]] seen: set[tuple[tuple[str, PathSeed], ...]] = set() @@ -751,3 +766,52 @@ def column_jog_candidates(problem: RoutingProblem, search: SearchOptions, *, lim for minimum in dict.fromkeys((search.min_straight_length, 0.0)): yield from islice(seed_pass(minimum), limit_per_pass) + + +def column_recovery_subproblems(problem: RoutingProblem) -> tuple[RoutingProblem, ...]: + """Use full-width keepouts to isolate independent horizontal channels.""" + xmin, ymin, xmax, ymax = problem.bounds + dividers = [] + for shape in problem.static_obstacles: + left, bottom, right, top = shape.bounds + if left <= xmin and right >= xmax and ymin < top and bottom < ymax and shape.equals(box(left, bottom, right, top)): + dividers.append((bottom, top)) + if not dividers: + return (problem,) + + clearance = problem.clearance + + def nearby(shapes: tuple[Polygon, ...], lower: float, upper: float) -> tuple[Polygon, ...]: + return tuple(shape for shape in shapes if shape.bounds[3] > lower - clearance and shape.bounds[1] < upper + clearance) + + groups = [] + for bottom, top in open_intervals(dividers, ymin, ymax): + lower = bottom + clearance if bottom != ymin else bottom + upper = top - clearance if top != ymax else top + if lower >= upper: + continue + nets = tuple(net for net in problem.nets if lower <= net.start.y <= upper and lower <= net.target.y <= upper) + if not nets: + continue + fixed_routes = [] + for fixed in problem.fixed_routes: + polygons = nearby(fixed.polygons, lower, upper) + if polygons: + fixed_routes.append(replace(fixed, polygons=polygons)) + groups.append(replace( + problem, bounds=(xmin, lower, xmax, upper), nets=nets, + static_obstacles=nearby(problem.static_obstacles, lower, upper), fixed_routes=tuple(fixed_routes), + )) + return tuple(groups) if sum(len(group.nets) for group in groups) == len(problem.nets) else () + + +def column_recovery_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[dict[str, PathSeed]]: + """Try individual apertures and a shared bypass outside the keepout field.""" + yield from column_jog_candidates(problem, search, limit_per_pass=8, recovery=True) + obstacles = problem._blocking_polygons + if len(obstacles) < 2: + return + # Covering every keepout with one box offers a cheap option when planning + # individual columns has too many aperture assignments. Verify on the real board. + envelope = replace(problem, static_obstacles=(box(*total_bounds(obstacles)),), fixed_routes=()) + yield from column_jog_candidates(envelope, search, limit_per_pass=8, recovery=True) diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index 15daa56..4eb06f9 100644 --- a/inire/tests/routing_corpus.py +++ b/inire/tests/routing_corpus.py @@ -16,7 +16,7 @@ from inire.tests.routing_benchmarks import ( FALLBACK_BENCHMARK_CASES, VALIDATION_BENCHMARK_CASES, ) -from inire.tests.routing_expanded_benchmarks import COMPLEX_CASES, CORNER_CASES, SCALING_CASES, SCALING_REGRESSION_CASES, SEARCH_CASES +from inire.tests.routing_expanded_benchmarks import COMPLEX_CASES, CORNER_CASES, SCALING_CASES, SEARCH_CASES from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from inire.tests.terminal_bench_scenario import LENGTH_COST @@ -28,9 +28,10 @@ if TYPE_CHECKING: BROAD_CASES = (*VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) -_STANDARD_CASES = (*BENCHMARK_CASES, *BROAD_CASES, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES, *CORNER_CASES, *COMPLEX_CASES) -CORPUS_REGRESSION_CASES = (*_STANDARD_CASES, *SCALING_REGRESSION_CASES) -CORPUS_CASES = (*_STANDARD_CASES, *SEARCH_CASES, *SCALING_CASES) +CORPUS_CASES = ( + *BENCHMARK_CASES, *BROAD_CASES, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES, + *CORNER_CASES, *COMPLEX_CASES, *SEARCH_CASES, *SCALING_CASES, +) SNAPSHOT_CASES = tuple( case for case in (*BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) if case.name != "terminal-bench" ) diff --git a/inire/tests/routing_expanded_benchmarks.py b/inire/tests/routing_expanded_benchmarks.py index 406ec79..cf8e270 100644 --- a/inire/tests/routing_expanded_benchmarks.py +++ b/inire/tests/routing_expanded_benchmarks.py @@ -348,7 +348,7 @@ SEARCH_CASES = ( _comb("6x7", 6, 7, 20), ) -SCALING_REGRESSION_CASES = ( +SCALING_CASES = ( _crossings("scale-crossing-10x10-aligned", 10, 10, 120, 132, staggered=False), _crossings("scale-crossing-10x11-staggered", 10, 11, 120, 132, staggered=True), _port_bank("224", 224, obstacles=False), @@ -356,9 +356,5 @@ SCALING_REGRESSION_CASES = ( _port_bank("216-with-keepouts", 216, obstacles=True), _obstacle_field(16, 16, 3, grid=1000), _port_bank("240-with-keepouts", 240, obstacles=True, detours=4, grid=500), -) - -SCALING_CASES = ( - *SCALING_REGRESSION_CASES, _obstacle_field(20, 16, 4, grid=500), ) diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index a6d5c74..3a2c3fa 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -23,7 +23,7 @@ from inire.tests.routing_benchmarks import ( EXTERNAL_BENCHMARK_CASES, FALLBACK_BENCHMARK_CASES, ) -from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, CORPUS_REGRESSION_CASES, automatic_options, profile_options +from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from scripts.compare_topological_routing import ( _direct_trials, @@ -41,7 +41,7 @@ def _measure(case, options, strategy): @pytest.mark.routing_corpus @pytest.mark.parametrize( "case", - [pytest.param(case, id=case.name) for case in CORPUS_REGRESSION_CASES], + [pytest.param(case, id=case.name) for case in CORPUS_CASES], ) def test_automatic_reaches_corpus_routing_bound(case) -> None: profile = "corpus-regression" @@ -56,6 +56,53 @@ def test_automatic_reaches_corpus_routing_bound(case) -> None: assert len(verified) == case.routing_bound +@pytest.mark.parametrize("name", ["search-comb-1x4", "search-comb-2x5-fine", "scale-field-20x16"]) +def test_column_recovery_routes_with_a_one_node_search_budget(name) -> None: + (case,) = CASE_GROUPS[name] + options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") + options = replace( + options, + search=replace(options.search, node_limit=1), + congestion=replace(options.congestion, max_iterations=1), + topology=replace(options.topology, seed_node_limit=1), + ) + + run = route(case.problem, options=options) + + assert run.automatic is not None + assert run.automatic.selected_planner == "column-recovery" + assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} + assert all(result.is_valid for result in run.results_by_net.values()) + + +@pytest.mark.parametrize("name", ["retry-holdout-stepped-roof", "retry-holdout-west-roof"]) +def test_residual_perimeter_completes_a_return_with_straight_peers(name) -> None: + (case,) = CASE_GROUPS[name] + options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") + options = replace(options, search=replace(options.search, node_limit=1)) + + run = route(case.problem, options=options) + + assert run.automatic is not None + assert run.automatic.selected_planner == "residual-perimeter" + assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} + assert all(len(run.results_by_net[net_id].path) == 1 for net_id in ("edge", "lower", "east")) + + +@pytest.mark.routing_corpus +def test_final_dogleg_can_reuse_incumbents_from_seed_fallback() -> None: + (case,) = CASE_GROUPS["retry-holdout-reversed-bank"] + options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") + + run = route(case.problem, options=options) + + assert run.automatic is not None + assert run.automatic.selected_planner == "residual-dogleg" + [fallback] = [stage for stage in run.automatic.stages if stage.policy == "seed-fallback" and stage.operation == "search"] + assert set(fallback.valid_net_ids) == {net.net_id for net in case.problem.nets if net.net_id != "outside_lower"} + assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} + + def test_expanded_corpus_uses_physical_dimensions_and_has_reference_coverage() -> None: corpus_names = {case.name for case in CORPUS_CASES} assert len(corpus_names) == len(CORPUS_CASES) From d64c70c68f6687da86d3ba2ceac09f7d5ac5860c Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 15:24:14 -0800 Subject: [PATCH 41/57] Trim verification work and plan independent channels before search --- inire/geometry/collision.py | 21 ++++++++------- inire/geometry/component_overlap.py | 37 +++++++++++++++----------- inire/geometry/dynamic_path_index.py | 7 +++-- inire/router/_automatic.py | 35 ++++++++++++++---------- inire/router/_compact.py | 14 +++++++--- inire/router/_routing_policy.py | 2 +- inire/router/_stack.py | 3 ++- inire/tests/test_api.py | 2 +- inire/tests/test_routing_benchmarks.py | 12 +++++++++ 9 files changed, 85 insertions(+), 48 deletions(-) diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index ff90675..5b0c8b7 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -117,6 +117,7 @@ class RoutingWorld: *, board: Polygon | None = None, self_clearance: float = 0.0, + use_dynamic_grid: bool = True, ) -> None: self.clearance = clearance self.self_clearance = self_clearance @@ -126,15 +127,16 @@ class RoutingWorld: self.grid_cell_size = 50.0 self.metrics = None self._static_obstacles = StaticObstacleIndex(self) - self._dynamic_paths = DynamicPathIndex(self) + self._dynamic_paths = DynamicPathIndex(self, use_grid=use_dynamic_grid) @classmethod - def from_problem(cls, problem: RoutingProblem, *, board: Polygon | None = None) -> RoutingWorld: + def from_problem(cls, problem: RoutingProblem, *, board: Polygon | None = None, use_dynamic_grid: bool = True) -> RoutingWorld: world = cls( clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, board=box(*problem.bounds) if board is None else board, self_clearance=problem.self_clearance, + use_dynamic_grid=use_dynamic_grid, ) for obstacle in problem.static_obstacles: world.add_static_obstacle(obstacle) @@ -697,15 +699,16 @@ class RoutingWorld: raw_geometries = static_obstacles.raw_tree.geometries for component in components: for polygon in component.physical_geometry: - if self.metrics is not None: - self.metrics.total_verify_static_buffer_ops += 1 - buffered = polygon.buffer(self.clearance, join_style="mitre") - hits = static_obstacles.raw_tree.query(buffered, predicate="intersects") + query = polygon + if self.clearance > 0: + x0, y0, x1, y1 = polygon.bounds + margin = self.clearance + query = box(x0 - margin, y0 - margin, x1 + margin, y1 + margin) + hits = static_obstacles.raw_tree.query(query) for hit_idx in hits: obstacle = raw_geometries[hit_idx] - # A mitre may extend past the physical clearance - # radius at a component corner. Check the distance - # before counting an overlap with that broad phase. + # Padded bounds only screen candidates. Use the physical + # polygons for clearance and zero-clearance contact rules. violates = _violates_net_clearance if static_obstacles.raw_owners[hit_idx] is not None else _violates_clearance if violates(polygon, obstacle, self.clearance): static_collision_count += 1 diff --git a/inire/geometry/component_overlap.py b/inire/geometry/component_overlap.py index db03f2e..ecd580a 100644 --- a/inire/geometry/component_overlap.py +++ b/inire/geometry/component_overlap.py @@ -9,7 +9,7 @@ from shapely.strtree import STRtree from inire.constants import TOLERANCE_LINEAR if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Iterable, Sequence from shapely.geometry import Polygon from inire.geometry.components import ComponentResult @@ -91,19 +91,8 @@ def count_path_self_collisions(components: Sequence[ComponentResult], clearance: internal_collisions += 1 if len(components) < 2: return internal_collisions - envelopes = [ - component.physical_geometry[0] if len(component.physical_geometry) == 1 else box(*component.total_physical_bounds) - for component in components - ] - index = STRtree(envelopes) distances = list(accumulate((component.length for component in components), initial=0.0)) if clearance else () - def envelope_with_clearance(i: int) -> Polygon: - if not clearance: - return envelopes[i] - x0, y0, x1, y1 = components[i].total_physical_bounds - return box(x0 - clearance, y0 - clearance, x1 + clearance, y1 + clearance) - def spacing(i: int, other: int) -> float: if not distances or distances[other] - distances[i + 1] < clearance - TOLERANCE_LINEAR: return 0.0 @@ -111,9 +100,25 @@ def count_path_self_collisions(components: Sequence[ComponentResult], clearance: return 0.0 # Keep the geometry local to one continuous bend together. return clearance + pairs: Iterable[tuple[int, int]] + if len(components) <= 3: + # At most three pairs, each with its own bounds check. + pairs = combinations(range(len(components)), 2) + else: + envelopes = [ + component.physical_geometry[0] if len(component.physical_geometry) == 1 else box(*component.total_physical_bounds) + for component in components + ] + index = STRtree(envelopes) + + def envelope_with_clearance(i: int) -> Polygon: + if not clearance: + return envelopes[i] + x0, y0, x1, y1 = components[i].total_physical_bounds + return box(x0 - clearance, y0 - clearance, x1 + clearance, y1 + clearance) + + pairs = ((i, other) for i in range(len(components)) for other in index.query(envelope_with_clearance(i)) if other > i) return internal_collisions + sum( - components_overlap(component, components[other], prefer_actual=True, at_join=other == i + 1, clearance=spacing(i, other)) - for i, component in enumerate(components) - for other in index.query(envelope_with_clearance(i)) - if other > i + components_overlap(components[i], components[other], prefer_actual=True, at_join=other == i + 1, clearance=spacing(i, other)) + for i, other in pairs ) diff --git a/inire/geometry/dynamic_path_index.py b/inire/geometry/dynamic_path_index.py index 52618de..96c5c0b 100644 --- a/inire/geometry/dynamic_path_index.py +++ b/inire/geometry/dynamic_path_index.py @@ -38,10 +38,12 @@ class DynamicPathIndex: "_physical_objects", "_physical_ids_by_net", "_physical_id_counter", + "_use_grid", ) - def __init__(self, engine: RoutingWorld) -> None: + def __init__(self, engine: RoutingWorld, *, use_grid: bool = True) -> None: self.engine = engine + self._use_grid = use_grid self.index = rtree.index.Index() self.geometries: dict[int, tuple[str, Polygon]] = {} self.dilated: dict[int, Polygon] = {} @@ -157,7 +159,8 @@ class DynamicPathIndex: self.dilated_bounds[obj_id] = dilated_bounds self.index.insert(obj_id, dilated_bounds) self.net_to_obj_ids.setdefault(net_id, set()).add(obj_id) - self._register_grid_membership(obj_id, net_id, dilated_bounds, cell_size=cell_size) + if self._use_grid: + self._register_grid_membership(obj_id, net_id, dilated_bounds, cell_size=cell_size) self._refresh_net_envelope(net_id) if physical_geometry is None: physical_geometry = [ diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index c2445b1..317fed8 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -506,28 +506,27 @@ class _AutomaticRun: return True return False - def _column_recovery_trial(self, options: RoutingOptions) -> Trial | None: + def _try_column_recovery(self, options: RoutingOptions, trials: list[Trial], groups: tuple[RoutingProblem, ...]) -> bool: problem = self.problem - if problem.initial_paths or not options.search.bend_radii or not problem._blocking_polygons: - return None planner = "column-recovery" with self._time("plan", planner=planner): - groups = column_recovery_subproblems(problem) - if not groups: - return None combined = {} for group in groups: for seeds in column_recovery_candidates(group, options.search): trial = self._verify(replace(group, initial_paths=seeds), planner) if len(trial.valid_costs) == len(group.nets): if group is problem: - return trial + trials.append(trial) + return True combined.update(seeds) break else: - return None + return False trial = self._verify(replace(problem, initial_paths=combined), planner) - return trial if len(trial.valid_costs) == len(problem.nets) else None + if len(trial.valid_costs) == len(problem.nets): + trials.append(trial) + return True + return False def _search_trials(self, trials: list[Trial], target: int) -> None: configured_search = self.options.search @@ -561,6 +560,17 @@ class _AutomaticRun: try_construction_early = not options.congestion.shuffle_nets if try_construction_early and self._try_column_jogs(options, trials, target): return True + groups = () + if ( + try_construction_early and target == len(problem.nets) and not problem.initial_paths + and options.search.bend_radii and problem._blocking_polygons + ): + with self._time("plan", planner="column-recovery"): + groups = column_recovery_subproblems(problem) + # With independent channels, try construction before spending search + # budget on each net. Keep the general bypass as a later fallback. + if len(groups) > 1 and self._try_column_recovery(options, trials, groups): + return True probe_iterations = options.congestion.max_iterations proxy, _ = resolve_bend_geometry(options.search) # Clipped proxies can find cheaper routes in later probe iterations than in the wider retry. @@ -591,11 +601,8 @@ class _AutomaticRun: if len(_best_trial(trials).valid_costs) >= target: return True - if target == len(problem.nets) and not options.congestion.shuffle_nets: - recovery = self._column_recovery_trial(options) - if recovery is not None: - trials.append(recovery) - return True + if len(groups) == 1 and self._try_column_recovery(options, trials, groups): + return True # Every short shift has lateral displacement, so the direct retry cannot lock # any straight paths. It would run the same guide with the same budget. diff --git a/inire/router/_compact.py b/inire/router/_compact.py index d579bd5..79ebeb2 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -110,7 +110,7 @@ def _pack_routes( clearance: float, ) -> dict[str, PathSeed] | None: order = sorted(candidates, key=lambda net_id: len(candidates[net_id])) - chosen: dict[str, tuple[PathSeed, BaseGeometry]] = {} + chosen: dict[str, tuple[PathSeed, BaseGeometry, tuple[float, float, float, float]]] = {} remaining = 4096 choices = [iter(candidates[net_id]) for net_id in order] index = 0 @@ -122,9 +122,14 @@ def _pack_routes( if remaining <= 0: return None remaining -= 1 - if any(_violates_net_clearance(footprint, other, clearance) for _, other in chosen.values()): + left, bottom, right, top = bounds = footprint.bounds + if any( + not (right + clearance < x0 or left > x1 + clearance or top + clearance < y0 or bottom > y1 + clearance) + and _violates_net_clearance(footprint, other, clearance) + for _, other, (x0, y0, x1, y1) in chosen.values() + ): continue - chosen[net_id] = (seed, footprint) + chosen[net_id] = (seed, footprint, bounds) index += 1 break else: @@ -141,8 +146,9 @@ def _verified_candidates( search: SearchOptions, seeds: Iterable[PathSeed], ) -> Iterator[tuple[PathSeed, BaseGeometry, tuple[ComponentResult, ...]]]: + bounds = board.bounds for seed in seeds: - path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance, bounds=board.bounds) + path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance, bounds=bounds) if not path or 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]) diff --git a/inire/router/_routing_policy.py b/inire/router/_routing_policy.py index a234a7b..b390a2b 100644 --- a/inire/router/_routing_policy.py +++ b/inire/router/_routing_policy.py @@ -82,7 +82,7 @@ def _direct_paths( *, priority: frozenset[str] = frozenset(), ) -> dict[str, RoutingResult]: - world = RoutingWorld.from_problem(problem, board=board) + world = RoutingWorld.from_problem(problem, board=board, use_dynamic_grid=False) ordered = ordered_nets(problem.nets, options.congestion.net_order) if priority: ordered.sort(key=lambda net: net.net_id not in priority) diff --git a/inire/router/_stack.py b/inire/router/_stack.py index 21f1d7d..02585e5 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -35,7 +35,8 @@ def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> Rou problem = plan_ordered_bundle(problem, options.search, infer_terminal_headings=options.topology.infer_terminal_headings) - world = RoutingWorld.from_problem(problem) + # Replay and one-node attempts can rely on the indexes already used for verification. + world = RoutingWorld.from_problem(problem, use_dynamic_grid=options.search.node_limit > 1) danger_map = proximity_map(problem, options.search.proximity_range) refinement = options.refinement diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 30a4c10..eb5a569 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -934,7 +934,7 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke assert run.metrics.nodes_expanded == 0 assert run.metrics.route_iterations == 1 assert run.metrics.verify_path_report_calls == 3 - assert run.metrics.verify_static_buffer_ops == 3 + assert run.metrics.verify_static_buffer_ops == 0 assert run.metrics.verify_dynamic_exact_pair_checks == 2 assert callbacks == [(0, run.results_by_net)] assert with_callback.results_by_net == run.results_by_net diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 3a2c3fa..314a8ac 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -75,6 +75,18 @@ def test_column_recovery_routes_with_a_one_node_search_budget(name) -> None: assert all(result.is_valid for result in run.results_by_net.values()) +def test_independent_column_channels_can_skip_the_search_probe() -> None: + (case,) = CASE_GROUPS["search-comb-3x4"] + options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") + + run = route(case.problem, options=options) + + assert run.automatic is not None + assert run.automatic.selected_planner == "column-recovery" + assert len(run.automatic.verified_net_ids) == case.routing_bound + assert run.metrics.nodes_expanded == 0 + + @pytest.mark.parametrize("name", ["retry-holdout-stepped-roof", "retry-holdout-west-roof"]) def test_residual_perimeter_completes_a_return_with_straight_peers(name) -> None: (case,) = CASE_GROUPS[name] From 9e9794517409f9f3341f7f96d4f3b730e3c5f2da Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 15:24:18 -0800 Subject: [PATCH 42/57] Route the blocking link after packing short links --- inire/geometry/component_overlap.py | 8 ++++++++ inire/router/_automatic.py | 17 ++++++++++++++++- inire/router/_compact.py | 25 ++++++++++++++++++++++--- inire/tests/test_routing_benchmarks.py | 22 +++++++++++++++++++++- 4 files changed, 67 insertions(+), 5 deletions(-) diff --git a/inire/geometry/component_overlap.py b/inire/geometry/component_overlap.py index ecd580a..205da6e 100644 --- a/inire/geometry/component_overlap.py +++ b/inire/geometry/component_overlap.py @@ -56,6 +56,14 @@ def components_overlap( normal, lateral = (port.x, port.y) if axis == 0 else (port.y, port.x) half_width = min(width_a, width_b) / 2 lo, hi = lateral - half_width, lateral + half_width + # An intersection contained in the shared face cannot count as overlap. + if ( + max(bounds_a[axis], bounds_b[axis]) >= normal - TOLERANCE_LINEAR + and min(bounds_a[axis + 2], bounds_b[axis + 2]) <= normal + TOLERANCE_LINEAR + and max(bounds_a[1 - axis], bounds_b[1 - axis]) >= lo - TOLERANCE_LINEAR + and min(bounds_a[3 - axis], bounds_b[3 - axis]) <= hi + TOLERANCE_LINEAR + ): + return False else: at_join = False diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 317fed8..458e6de 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -271,11 +271,16 @@ class _AutomaticRun: if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets): planner = "local-sbend" with self._time("plan", planner=planner): - shifts = short_shift_seed_set(problem, options.search, self._selection_cost) + shifts = short_shift_seed_set(problem, options.search, self._selection_cost, defer_blocker=not self.problem.initial_paths) if shifts is not None: trial = verify(replace(problem, initial_paths=shifts), planner) complete = len(trial.valid_costs) == len(problem.nets) trials.append(trial if complete else replace(trial, selection="incomplete-layout")) + if len(shifts) == len(problem.nets) - 1: + detour = self._residual_constructive_trial(options, trial, limit_per_pass=16) + if detour is not None: + trials.append(detour) + return trials, tuple(rejections) if not complete: rejections.append("Local S-bend layout failed full verification") return trials, tuple(rejections) @@ -459,7 +464,17 @@ class _AutomaticRun: planner = "residual-dogleg" candidates = residual_dogleg_candidates(residual, options.search, limit_per_pass=limit_per_pass) with self._time("plan", planner=planner, policy=planner): + world = None for seed in candidates: + path = materialize_path_seed( + seed, start=net.start, net_width=net.width, search=options.search, clearance=residual.clearance, bounds=residual.bounds, + ) + if not path or path[-1].end_port != net.target: + continue + if world is None: + world = RoutingWorld.from_problem(residual, board=self.board) + if not world.verify_path_report(net.net_id, path).is_valid: + continue 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): diff --git a/inire/router/_compact.py b/inire/router/_compact.py index 79ebeb2..c376c19 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -2,7 +2,7 @@ from __future__ import annotations -from itertools import islice +from itertools import combinations, islice from math import ceil, floor, isfinite from typing import TYPE_CHECKING @@ -197,7 +197,9 @@ def _shift_seeds(forward: int, offset: int, search: SearchOptions) -> Iterator[P yield _path(lead, SBendSeed(offset, radius), spare - lead) -def short_shift_seed_set(problem: RoutingProblem, search: SearchOptions, score: Scorer) -> dict[str, PathSeed] | None: +def short_shift_seed_set( + problem: RoutingProblem, search: SearchOptions, score: Scorer, *, defer_blocker: bool = False, +) -> dict[str, PathSeed] | None: """Fit links between fixed ports across both axes of a layout.""" if problem.initial_paths or len(problem.nets) < 3 or len({net.start.r % 180 for net in problem.nets}) < 2: return None @@ -222,4 +224,21 @@ def short_shift_seed_set(problem: RoutingProblem, search: SearchOptions, score: 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) + packed = _pack_routes(candidates, problem.clearance) + if packed is not None or not defer_blocker or not search.bend_radii: + return packed + + # When all conflicts between forced choices share one net, try packing + # the other links so the caller can detour the blocker around them. + forced = [(net_id, choices[0][1]) for net_id, choices in candidates.items() if len(choices) == 1] + blockers: set[str] | None = None + for (net_id, a), (peer_id, b) in combinations(forced, 2): + if _violates_net_clearance(a, b, problem.clearance): + pair = {net_id, peer_id} + blockers = pair if blockers is None else blockers & pair + if not blockers: + return None + if blockers and len(blockers) == 1: + candidates.pop(blockers.pop()) + return _pack_routes(candidates, problem.clearance) + return None diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 314a8ac..f1792bd 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -12,6 +12,7 @@ from inire import ( SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, ) from inire.constants import TOLERANCE_LINEAR +from inire.router import _automatic from inire.router._automatic import _AutomaticRun from inire.router._capacity import port_conflicts from inire.router._routing_policy import _disconnected_nets @@ -102,7 +103,13 @@ def test_residual_perimeter_completes_a_return_with_straight_peers(name) -> None @pytest.mark.routing_corpus -def test_final_dogleg_can_reuse_incumbents_from_seed_fallback() -> None: +def test_final_dogleg_can_reuse_incumbents_from_seed_fallback(monkeypatch) -> None: + short_shift_seed_set = _automatic.short_shift_seed_set + + def full_shift_set(problem, search, score, **_kwargs): + return short_shift_seed_set(problem, search, score) + + monkeypatch.setattr(_automatic, "short_shift_seed_set", full_shift_set) (case,) = CASE_GROUPS["retry-holdout-reversed-bank"] options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") @@ -115,6 +122,19 @@ def test_final_dogleg_can_reuse_incumbents_from_seed_fallback() -> None: assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} +def test_local_shift_plan_can_leave_one_conflicting_net_for_a_detour() -> None: + (case,) = CASE_GROUPS["stress-crossings-shared-outside-detour"] + options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") + + run = route(case.problem, options=options) + + assert run.automatic.selected_planner == "residual-dogleg" + assert run.metrics.nodes_expanded == 0 + assert all(result.is_valid for result in run.results_by_net.values()) + [partial] = [stage for stage in run.automatic.stages if stage.planner == "local-sbend" and stage.operation == "verify"] + assert set(partial.valid_net_ids) == {net.net_id for net in case.problem.nets if net.net_id != "outside_lower"} + + def test_expanded_corpus_uses_physical_dimensions_and_has_reference_coverage() -> None: corpus_names = {case.name for case in CORPUS_CASES} assert len(corpus_names) == len(CORPUS_CASES) From 6b699e492b19c33c066f632bd713fb3c2af39d59 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 15:35:42 -0800 Subject: [PATCH 43/57] Reuse physical bounds for rectangular board checks --- inire/geometry/collision.py | 27 ++++++++++++++++--- inire/geometry/components.py | 45 ++++++++++++++++++++------------ inire/geometry/sbend.py | 10 ++++++- inire/router/_astar_admission.py | 4 +-- inire/tests/test_collision.py | 14 ++++++++++ 5 files changed, 76 insertions(+), 24 deletions(-) diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index 5b0c8b7..5639e5b 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -103,7 +103,8 @@ class RoutingWorld: "clearance", "self_clearance", "safety_zone_radius", - "board", + "_board", + "_board_bounds", "grid_cell_size", "metrics", "_dynamic_paths", @@ -122,7 +123,8 @@ class RoutingWorld: self.clearance = clearance self.self_clearance = self_clearance self.safety_zone_radius = safety_zone_radius - self.board = floating_polygon(board) if board is not None else None + self._board = floating_polygon(board) if board is not None else None + self._board_bounds: tuple[float, float, float, float] | None = None self.grid_cell_size = 50.0 self.metrics = None @@ -131,13 +133,18 @@ class RoutingWorld: @classmethod def from_problem(cls, problem: RoutingProblem, *, board: Polygon | None = None, use_dynamic_grid: bool = True) -> RoutingWorld: + outline = box(*problem.bounds) if board is None else board world = cls( clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, - board=box(*problem.bounds) if board is None else board, + board=outline, self_clearance=problem.self_clearance, use_dynamic_grid=use_dynamic_grid, ) + if board is None: + xmin, ymin, xmax, ymax = outline.bounds + if xmin < xmax and ymin < ymax: + world._board_bounds = (xmin, ymin, xmax, ymax) for obstacle in problem.static_obstacles: world.add_static_obstacle(obstacle) for fixed in problem.fixed_routes: @@ -145,6 +152,18 @@ class RoutingWorld: world.add_static_obstacle(polygon, owner=fixed.net_id) return world + @property + def board(self) -> Polygon | None: + return self._board + + def board_covers_component(self, component: ComponentResult) -> bool: + bounds = self._board_bounds + if bounds is not None and component.standard_faces: + # For a rectangular board the physical bounds give exact containment. + left, bottom, right, top = component.total_physical_bounds + return bounds[0] <= left and bounds[1] <= bottom and right <= bounds[2] and top <= bounds[3] + return self._board is None or path_within_board((component,), self._board) + def get_static_version(self) -> int: return self._static_obstacles.version @@ -717,7 +736,7 @@ class RoutingWorld: static_collision_count=static_collision_count, self_collision_count=count_path_self_collisions(components, self.self_clearance), total_length=total_length, - out_of_bounds=self.board is not None and not path_within_board(components, self.board), + out_of_bounds=self._board is not None and not all(self.board_covers_component(component) for component in components), ) def verify_path_details( diff --git a/inire/geometry/components.py b/inire/geometry/components.py index cf0c42b..662643b 100644 --- a/inire/geometry/components.py +++ b/inire/geometry/components.py @@ -12,7 +12,7 @@ from shapely.affinity import translate as shapely_translate from shapely.geometry import Polygon, box from inire.constants import TOLERANCE_ANGULAR, TOLERANCE_LINEAR -from inire.geometry.sbend import sbend_grid_span, sbend_span +from inire.geometry.sbend import sbend_angle, sbend_centerline_length, sbend_grid_span, sbend_span from inire.seeds import Bend90Seed, PathSegmentSeed, SBendSeed, StraightSeed from .primitives import Port, rotate_cardinal, rotation_matrix2 @@ -141,8 +141,10 @@ class ComponentResult: def __post_init__(self) -> None: collision_geometry = tuple(self.collision_geometry) - physical_geometry = tuple(self.physical_geometry) - dilated_collision_geometry = tuple(self.dilated_collision_geometry) + physical_geometry = collision_geometry if self.physical_geometry is self.collision_geometry else tuple(self.physical_geometry) + dilated_collision_geometry = ( + collision_geometry if self.dilated_collision_geometry is self.collision_geometry else tuple(self.dilated_collision_geometry) + ) dilated_physical_geometry = tuple(self.dilated_physical_geometry) object.__setattr__(self, "collision_geometry", collision_geometry) @@ -152,12 +154,19 @@ class ComponentResult: object.__setattr__(self, "length", float(self.length)) bounds = tuple(poly.bounds for poly in collision_geometry) + total_bounds = _combine_bounds(bounds) object.__setattr__(self, "_bounds", bounds) - object.__setattr__(self, "_total_bounds", _combine_bounds(list(bounds))) + object.__setattr__(self, "_total_bounds", total_bounds) + if physical_geometry is collision_geometry: + object.__setattr__(self, "_total_physical_bounds", total_bounds) - dilated_bounds = tuple(poly.bounds for poly in dilated_collision_geometry) + if dilated_collision_geometry is collision_geometry: + dilated_bounds, total_dilated_bounds = bounds, total_bounds + else: + dilated_bounds = tuple(poly.bounds for poly in dilated_collision_geometry) + total_dilated_bounds = _combine_bounds(dilated_bounds) object.__setattr__(self, "_dilated_bounds", dilated_bounds) - object.__setattr__(self, "_total_dilated_bounds", _combine_bounds(list(dilated_bounds))) + object.__setattr__(self, "_total_dilated_bounds", total_dilated_bounds) @property def bounds(self) -> tuple[tuple[float, float, float, float], ...]: @@ -230,15 +239,21 @@ class ComponentResult: def translate_geometry(polygons: Sequence[Polygon]) -> tuple[Polygon, ...]: return tuple(translated[id(polygon)] for polygon in polygons) + collision_geometry = translate_geometry(self.collision_geometry) result = ComponentResult( start_port=self.start_port.translate(dx, dy), - collision_geometry=translate_geometry(self.collision_geometry), + collision_geometry=collision_geometry, end_port=self.end_port.translate(dx, dy), length=self.length, move_type=self.move_type, move_spec=self.move_spec, - physical_geometry=translate_geometry(self.physical_geometry), - dilated_collision_geometry=translate_geometry(self.dilated_collision_geometry), + physical_geometry=( + collision_geometry if self.physical_geometry is self.collision_geometry else translate_geometry(self.physical_geometry) + ), + dilated_collision_geometry=( + collision_geometry if self.dilated_collision_geometry is self.collision_geometry + else translate_geometry(self.dilated_collision_geometry) + ), dilated_physical_geometry=translate_geometry(self.dilated_physical_geometry), width=self.width, standard_faces=self.standard_faces, @@ -247,7 +262,7 @@ class ComponentResult: return result -def _combine_bounds(bounds_list: list[tuple[float, float, float, float]]) -> tuple[float, float, float, float]: +def _combine_bounds(bounds_list: Sequence[tuple[float, float, float, float]]) -> tuple[float, float, float, float]: if len(bounds_list) == 1: return bounds_list[0] arr = numpy.asarray(bounds_list, dtype=numpy.float64) @@ -285,10 +300,6 @@ def _arc_samples( return physical, dilated -def _sbend_angle(offset: float, radius: float) -> float: - return 2 * asin(sqrt(abs(offset) / radius) / 2) - - def prepare_component_sampling( kind: MoveKind, parameters: tuple, width: float, *, collision_type: BendCollisionModel, physical_geometry_type: BendPhysicalGeometry, @@ -302,7 +313,7 @@ def prepare_component_sampling( return _arc_samples(radius, width, 90, sagitta, dilation, sample_dilation=sample_dilation) if kind == "sbend" and sbend_outline is None: offset, radius = parameters - angle = float(numpy.degrees(_sbend_angle(offset, radius))) + angle = float(numpy.degrees(sbend_angle(offset, radius))) return _arc_samples(radius, width, angle, sagitta, dilation, sample_dilation=True) return 0, None @@ -612,7 +623,7 @@ class SBend: seed = SBendSeed(offset, radius) offset, radius = seed.offset, seed.radius sign = 1 if offset >= 0 else -1 - theta = _sbend_angle(offset, radius) + theta = sbend_angle(offset, radius) end_port = component_endpoint(start_port, "sbend", (offset, radius)) dx = sbend_span(offset, radius) grid_span = sbend_grid_span(offset, radius) @@ -663,7 +674,7 @@ class SBend: start_port=start_port, collision_geometry=geometry, end_port=end_port, - length=2.0 * radius * theta + max(0.0, tail), + length=sbend_centerline_length(radius, theta, tail), move_type="sbend", move_spec=seed, physical_geometry=physical_geometry, diff --git a/inire/geometry/sbend.py b/inire/geometry/sbend.py index a00630d..a204fb1 100644 --- a/inire/geometry/sbend.py +++ b/inire/geometry/sbend.py @@ -1,6 +1,6 @@ """S-bend dimensions on the routing grid.""" -from math import ceil, isfinite, isqrt, sqrt +from math import asin, ceil, isfinite, isqrt, sqrt from inire.constants import TOLERANCE_LINEAR @@ -23,6 +23,14 @@ def sbend_grid_span(offset: float, radius: float) -> int: return ceil(sbend_span(offset, radius) - TOLERANCE_LINEAR) +def sbend_angle(offset: float, radius: float) -> float: + return 2 * asin(sqrt(abs(offset) / radius) / 2) + + +def sbend_centerline_length(radius: float, angle: float, tangent: float) -> float: + return 2.0 * radius * angle + max(0.0, tangent) + + def exact_sbend_spans( radius: int, *, max_span: int, max_offset: int | None = None, offsets: tuple[float, ...] | None = None, ) -> dict[int, int]: diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index d893af9..463f6bd 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -7,7 +7,7 @@ from shapely.geometry import Polygon from inire.constants import TOLERANCE_LINEAR from inire.geometry.component_overlap import components_overlap -from inire.geometry.components import build_component, check_component_endpoint, path_within_board, uses_custom_outline +from inire.geometry.components import build_component, check_component_endpoint, uses_custom_outline from inire.geometry.primitives import Port from inire.router.refiner import component_hits_ancestor_chain @@ -160,7 +160,7 @@ def add_node( ce = context.cost_evaluator.collision_engine danger = context.cost_evaluator.danger_map if ce.board is not None: - outside_board = not path_within_board((result,), ce.board) + outside_board = not ce.board_covers_component(result) elif danger is not None and not result.standard_faces: outside_board = not danger.covers_bounds(result.total_physical_bounds) else: diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index dda2c33..6da3177 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -11,6 +11,7 @@ from inire.geometry.collision import RoutingWorld from inire.geometry.components import Bend90, ComponentResult from inire.geometry.components import Straight from inire.geometry.primitives import Port +from inire.model import RoutingProblem from inire.router._astar_types import AStarMetrics from inire.seeds import StraightSeed @@ -299,6 +300,19 @@ def test_verify_geometry_checks_the_board_using_the_polygon() -> None: assert report.out_of_bounds +def test_rectangular_board_includes_its_edges_and_custom_board_keeps_its_hole() -> None: + problem = RoutingProblem(bounds=(0, 0, 50, 50)) + rectangle = RoutingWorld.from_problem(problem) + board_with_hole = Polygon(box(*problem.bounds).exterior.coords, holes=[box(20, 1, 30, 3).exterior.coords]) + custom = RoutingWorld.from_problem(problem, board=board_with_hole) + touching = Straight.generate(Port(0, 2, 0), 50, width=4, dilation=problem.clearance / 2) + crossing = Straight.generate(Port(0, 1, 0), 50, width=4) + + assert rectangle.verify_path_geometry((touching,)).is_valid + assert rectangle.verify_path_geometry((crossing,)).out_of_bounds + assert custom.verify_path_geometry((touching,)).out_of_bounds + + def test_self_collision_check_only_visits_spatial_candidates(monkeypatch) -> None: path = tuple(Straight.generate(Port(x, 0, 0), 5, 2) for x in range(0, 500, 5)) original_check = overlap_module.components_overlap From 9e41c1abf814cd7a544e46f140348f8e8f532b80 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 15:35:45 -0800 Subject: [PATCH 44/57] Avoid unnecessary search and placement trials in automatic routing --- inire/router/_automatic.py | 20 ++++++++---- inire/router/_columns.py | 25 +++++++++++---- inire/router/_compact.py | 43 +++++++++++++++++++++++--- inire/tests/test_routing_benchmarks.py | 31 +++++++++++++++++-- 4 files changed, 100 insertions(+), 19 deletions(-) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 458e6de..4b63811 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -17,7 +17,9 @@ from inire.model import FixedRoute, resolve_bend_geometry from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle from inire.router._capacity import cut_capacity, port_conflicts -from inire.router._columns import column_jog_candidates, column_recovery_candidates, column_recovery_subproblems, column_seed_candidates +from inire.router._columns import ( + column_jog_candidates, column_partition_budget_exceeded, column_recovery_candidates, column_recovery_subproblems, column_seed_candidates, +) from inire.router._compact import compact_port_seed_set, short_shift_seed_set from inire.router._congestion_policy import ordered_nets from inire.router._perimeter import ( @@ -271,7 +273,10 @@ class _AutomaticRun: if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets): planner = "local-sbend" with self._time("plan", planner=planner): - shifts = short_shift_seed_set(problem, options.search, self._selection_cost, defer_blocker=not self.problem.initial_paths) + shifts = short_shift_seed_set( + problem, options.search, self._selection_cost, + defer_blocker=not self.problem.initial_paths, length_weights=self.length_weights, + ) if shifts is not None: trial = verify(replace(problem, initial_paths=shifts), planner) complete = len(trial.valid_costs) == len(problem.nets) @@ -582,10 +587,13 @@ class _AutomaticRun: ): with self._time("plan", planner="column-recovery"): groups = column_recovery_subproblems(problem) - # With independent channels, try construction before spending search - # budget on each net. Keep the general bypass as a later fallback. - if len(groups) > 1 and self._try_column_recovery(options, trials, groups): - return True + try_recovery_early = len(groups) > 1 or (len(groups) == 1 and column_partition_budget_exceeded(problem)) + # Independent channels and dense aperture fields can be cheaper to route + # by construction. Try their bypass before spending search budget. + if try_recovery_early: + if self._try_column_recovery(options, trials, groups): + return True + groups = () probe_iterations = options.congestion.max_iterations proxy, _ = resolve_bend_geometry(options.search) # Clipped proxies can find cheaper routes in later probe iterations than in the wider retry. diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 138db99..56f1e37 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -120,16 +120,29 @@ def _ordered_tracks(problem: RoutingProblem) -> tuple[_Track, ...]: return tuple(tracks) +def _partition_budget_exceeded(tracks: tuple[_Track, ...], columns: tuple[_Column, ...]) -> bool: + return any( + comb(len(tracks) + len(column.openings) - 1, len(column.openings) - 1) > _MAX_COLUMN_PARTITIONS for column in columns + ) + + +def _track_columns(problem: RoutingProblem, tracks: tuple[_Track, ...]) -> tuple[int, int, tuple[_Column, ...]]: + start = max(int(track.left.x) for track in tracks) + finish = min(int(track.right.x) for track in tracks) + return start, finish, _columns(problem, start, finish) + + +def column_partition_budget_exceeded(problem: RoutingProblem) -> bool: + tracks = _ordered_tracks(problem) + return bool(tracks) and _partition_budget_exceeded(tracks, _track_columns(problem, tracks)[2]) + + def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3) -> _ColumnLayout | None: tracks = _ordered_tracks(problem) if len(tracks) < min_tracks or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks): return None - start = max(int(track.left.x) for track in tracks) - finish = min(int(track.right.x) for track in tracks) - columns = _columns(problem, start, finish) - if not columns or any( - comb(len(tracks) + len(column.openings) - 1, len(column.openings) - 1) > _MAX_COLUMN_PARTITIONS for column in columns - ): + start, finish, columns = _track_columns(problem, tracks) + if not columns or _partition_budget_exceeded(tracks, columns): return None launch = tuple(int(track.left.y) for track in tracks) arrival = tuple(int(track.right.y) for track in tracks) diff --git a/inire/router/_compact.py b/inire/router/_compact.py index c376c19..b2313cd 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -2,6 +2,7 @@ from __future__ import annotations +from functools import cache from itertools import combinations, islice from math import ceil, floor, isfinite from typing import TYPE_CHECKING @@ -11,19 +12,19 @@ from shapely.geometry import box from inire.geometry.collision import RoutingWorld, _violates_net_clearance from inire.geometry.primitives import port_local_coordinates -from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans, sbend_grid_span +from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans, sbend_angle, sbend_centerline_length, sbend_grid_span, sbend_span from inire.model import resolve_bend_geometry from inire.results import RoutingResult from inire.router._seed_materialization import materialize_path_seed from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed if TYPE_CHECKING: - from collections.abc import Iterable, Iterator + from collections.abc import Iterable, Iterator, Mapping from shapely.geometry import Polygon from shapely.geometry.base import BaseGeometry - from inire.geometry.components import ComponentResult + from inire.geometry.components import ComponentResult, MoveKind from inire.model import NetSpec, RoutingProblem, SearchOptions from inire.router._routing_policy import Scorer from inire.seeds import PathSegmentSeed @@ -198,7 +199,8 @@ def _shift_seeds(forward: int, offset: int, search: SearchOptions) -> Iterator[P def short_shift_seed_set( - problem: RoutingProblem, search: SearchOptions, score: Scorer, *, defer_blocker: bool = False, + problem: RoutingProblem, search: SearchOptions, score: Scorer, *, + defer_blocker: bool = False, length_weights: Mapping[MoveKind, float] | None = None, ) -> dict[str, PathSeed] | None: """Fit links between fixed ports across both axes of a layout.""" if problem.initial_paths or len(problem.nets) < 3 or len({net.start.r % 180 for net in problem.nets}) < 2: @@ -214,6 +216,10 @@ def short_shift_seed_set( board = box(*problem.bounds) world = RoutingWorld.from_problem(problem, board=board) + if length_weights is not None and not search.sbend_outlines and any(len(seeds) > 1 for seeds in seeds_by_net): + packed = _pack_shortest_shifts(problem, search, world, board, seeds_by_net, length_weights) + if packed is not None: + return packed candidates = {} for net, seeds in zip(problem.nets, seeds_by_net, strict=True): ranked = [ @@ -242,3 +248,32 @@ def short_shift_seed_set( candidates.pop(blockers.pop()) return _pack_routes(candidates, problem.clearance) return None + + +def _pack_shortest_shifts( + problem: RoutingProblem, search: SearchOptions, world: RoutingWorld, board: Polygon, + seeds_by_net: list[tuple[PathSeed, ...]], length_weights: Mapping[MoveKind, float], +) -> dict[str, PathSeed] | None: + # Weighted length is independent of keepouts. When every cheapest seed + # verifies and fits with the others, the other placements cannot improve it. + @cache + def bend_cost(bend: SBendSeed) -> float: + offset, radius = bend.offset, bend.radius + tail = sbend_grid_span(offset, radius) - sbend_span(offset, radius) + return length_weights["sbend"] * sbend_centerline_length(radius, sbend_angle(offset, radius), tail) + + def cost(seed: PathSeed) -> float: + return sum( + bend_cost(move) if isinstance(move, SBendSeed) else length_weights["straight"] * move.length + for move in seed.segments + ) + + candidates = {} + for net, seeds in zip(problem.nets, seeds_by_net, strict=True): + best = min(seeds, key=cost) + verified = next(_verified_candidates(net, world, board, search, (best,)), None) + if verified is None: + return None + seed, footprint, _ = verified + candidates[net.net_id] = [(seed, footprint)] + return _pack_routes(candidates, problem.clearance) diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index f1792bd..0603a8d 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -12,10 +12,11 @@ from inire import ( SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, ) from inire.constants import TOLERANCE_LINEAR -from inire.router import _automatic +from inire.router import _automatic, _compact from inire.router._automatic import _AutomaticRun from inire.router._capacity import port_conflicts from inire.router._routing_policy import _disconnected_nets +from inire.router.cost import weighted_path_length from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES from inire.tests.routing_benchmarks import ( BENCHMARK_CASES, @@ -76,8 +77,9 @@ def test_column_recovery_routes_with_a_one_node_search_budget(name) -> None: assert all(result.is_valid for result in run.results_by_net.values()) -def test_independent_column_channels_can_skip_the_search_probe() -> None: - (case,) = CASE_GROUPS["search-comb-3x4"] +@pytest.mark.parametrize("name", ["search-comb-3x4", "scale-field-20x16"]) +def test_column_recovery_can_skip_the_search_probe(name) -> None: + (case,) = CASE_GROUPS[name] options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") run = route(case.problem, options=options) @@ -135,6 +137,29 @@ def test_local_shift_plan_can_leave_one_conflicting_net_for_a_detour() -> None: assert set(partial.valid_net_ids) == {net.net_id for net in case.problem.nets if net.net_id != "outside_lower"} +def test_weighted_local_shifts_can_pack_without_verifying_alternative_placements(monkeypatch) -> None: + (case,) = CASE_GROUPS["crossing-staggered-grid"] + weights = {"straight": 1.0, "bend90": 4.0, "sbend": 13.0} + + def score(result): + return weighted_path_length(result.path, weights) + + exhaustive = _compact.short_shift_seed_set(case.problem, case.options.search, score) + original = _compact._verified_candidates + seed_counts = [] + + def count_candidates(net, world, board, search, seeds): + seed_counts.append(len(seeds)) + yield from original(net, world, board, search, seeds) + + monkeypatch.setattr(_compact, "_verified_candidates", count_candidates) + packed = _compact.short_shift_seed_set(case.problem, case.options.search, score, length_weights=weights) + + assert packed + assert packed == exhaustive + assert seed_counts == [1] * len(case.problem.nets) + + def test_expanded_corpus_uses_physical_dimensions_and_has_reference_coverage() -> None: corpus_names = {case.name for case in CORPUS_CASES} assert len(corpus_names) == len(CORPUS_CASES) From ed52ea6ffd82bc0c8f0bf37f81828d56798ce2b2 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 19:29:51 -0800 Subject: [PATCH 45/57] Improve automatic routing retries and reuse component geometry Try verified perimeter construction early and reuse probe routes as movable hints during lookahead. Batch collision checks and cache component generation for repeated placement and refinement candidates. --- inire/geometry/collision.py | 57 ++++++++++++--------- inire/geometry/component_overlap.py | 9 +++- inire/router/_automatic.py | 74 ++++++++++++++++++++++++--- inire/router/_columns.py | 27 +++++----- inire/router/_compact.py | 7 ++- inire/router/_seed_materialization.py | 11 ++++ inire/router/refiner.py | 25 ++++++--- scripts/benchmark_retry_order.py | 5 +- 8 files changed, 160 insertions(+), 55 deletions(-) diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index 5639e5b..33a1e8b 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -4,7 +4,9 @@ from dataclasses import dataclass, replace from typing import TYPE_CHECKING import numpy -from shapely.geometry import LineString, box +from shapely import bounds as geometry_bounds +from shapely import box, distance +from shapely.geometry import LineString from inire.constants import TOLERANCE_LINEAR from inire.geometry.component_overlap import count_path_self_collisions @@ -705,35 +707,44 @@ class RoutingWorld: frozen_net_ids=frozen_net_ids, ) + def _count_static_path_collisions(self, components: Sequence[ComponentResult]) -> int: + static_obstacles = self._static_obstacles + self._ensure_static_raw_tree() + tree = static_obstacles.raw_tree + if tree is None: + return 0 + clearance = self.clearance + polygons = [polygon for component in components for polygon in component.physical_geometry] + if clearance > 0 and 4 <= len(polygons) <= 64: + # Use padded bounds for the broad phase, then measure the physical + # polygons. Keepouts and fixed routes use the same positive clearance. + # Stream longer paths below to bound the number of retained pairs. + shapes = numpy.asarray(polygons, dtype=object) + queries = box(*(geometry_bounds(shapes) + (-clearance, -clearance, clearance, clearance)).T) + left, right = tree.query(queries) + if not len(left): + return 0 + return int(numpy.count_nonzero(distance(shapes[left], tree.geometries[right]) < _clearance_limit(clearance))) + + count = 0 + for polygon in polygons: + query = polygon + if clearance > 0: + x0, y0, x1, y1 = polygon.bounds + query = box(x0 - clearance, y0 - clearance, x1 + clearance, y1 + clearance) + for hit in tree.query(query): + violates = _violates_net_clearance if static_obstacles.raw_owners[hit] is not None else _violates_clearance + count += violates(polygon, tree.geometries[hit], clearance) + return count + def verify_path_geometry(self, components: Sequence[ComponentResult]) -> RoutingReport: """Check polygon validity, self-spacing, the board, and static obstacles.""" - static_collision_count = 0 total_length = sum(component.length for component in components) if any(not component.physical_geometry_valid for component in components): return RoutingReport(total_length=total_length, invalid_geometry=True) - static_obstacles = self._static_obstacles - self._ensure_static_raw_tree() - if static_obstacles.raw_tree is not None: - raw_geometries = static_obstacles.raw_tree.geometries - for component in components: - for polygon in component.physical_geometry: - query = polygon - if self.clearance > 0: - x0, y0, x1, y1 = polygon.bounds - margin = self.clearance - query = box(x0 - margin, y0 - margin, x1 + margin, y1 + margin) - hits = static_obstacles.raw_tree.query(query) - for hit_idx in hits: - obstacle = raw_geometries[hit_idx] - # Padded bounds only screen candidates. Use the physical - # polygons for clearance and zero-clearance contact rules. - violates = _violates_net_clearance if static_obstacles.raw_owners[hit_idx] is not None else _violates_clearance - if violates(polygon, obstacle, self.clearance): - static_collision_count += 1 - return RoutingReport( - static_collision_count=static_collision_count, + static_collision_count=self._count_static_path_collisions(components), self_collision_count=count_path_self_collisions(components, self.self_clearance), total_length=total_length, out_of_bounds=self._board is not None and not all(self.board_covers_component(component) for component in components), diff --git a/inire/geometry/component_overlap.py b/inire/geometry/component_overlap.py index 205da6e..553202a 100644 --- a/inire/geometry/component_overlap.py +++ b/inire/geometry/component_overlap.py @@ -3,7 +3,7 @@ from __future__ import annotations from itertools import accumulate, combinations from typing import TYPE_CHECKING -from shapely.geometry import box +from shapely import box from shapely.strtree import STRtree from inire.constants import TOLERANCE_LINEAR @@ -125,7 +125,12 @@ def count_path_self_collisions(components: Sequence[ComponentResult], clearance: x0, y0, x1, y1 = components[i].total_physical_bounds return box(x0 - clearance, y0 - clearance, x1 + clearance, y1 + clearance) - pairs = ((i, other) for i in range(len(components)) for other in index.query(envelope_with_clearance(i)) if other > i) + if len(components) <= 64: + queries = [envelope_with_clearance(i) for i in range(len(components))] if clearance else envelopes + left, right = index.query(queries) + pairs = ((i, other) for i, other in zip(left, right, strict=True) if other > i) + else: + pairs = ((i, other) for i in range(len(components)) for other in index.query(envelope_with_clearance(i)) if other > i) return internal_collisions + sum( components_overlap(components[i], components[other], prefer_actual=True, at_join=other == i + 1, clearance=spacing(i, other)) for i, other in pairs diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 4b63811..ad632c1 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -44,6 +44,7 @@ from inire.router._seed_materialization import materialize_path_seed, seed_prepa 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 if TYPE_CHECKING: @@ -370,10 +371,10 @@ class _AutomaticRun: return trials[-1] = replace(trial, selection="incomplete-layout") - def _perimeter_trials(self, options: RoutingOptions) -> list[Trial]: + def _perimeter_trials(self, options: RoutingOptions, *, try_pair: bool = True) -> list[Trial]: problem = self.problem trials = [] - if len(problem.nets) == 2: + if try_pair and len(problem.nets) == 2: with self._time("plan", planner="paired-perimeter"): self._paired_perimeter(trials) if trials and len(trials[-1].valid_costs) == len(problem.nets): @@ -486,17 +487,51 @@ class _AutomaticRun: return trial return None - def _direct(self, options: RoutingOptions, policy: str) -> list[Trial]: + def _direct(self, options: RoutingOptions, policy: str, *, hints: dict[str, PathSeed] | None = None) -> list[Trial]: + def run(problem: RoutingProblem, *, options: RoutingOptions) -> RoutingRunResult: + if hints: + # Add internal hints after direct locks are chosen so search can move them. + active_hints = {net.net_id: hints[net.net_id] for net in problem.nets if net.net_id in hints} + if active_hints: + problem = replace(problem, initial_paths={**active_hints, **problem.initial_paths}) + options = replace(options, congestion=replace(options.congestion, warm_start_enabled=False)) + return self._run(problem, options=options, policy=policy) + with self._time("plan", planner="direct", policy=policy): return _direct_trials( self.problem, self.board, options, policy, - run_route=partial(self._run, policy=policy), + run_route=run, check_trial=self._trial, ) + def _try_hinted_lookahead(self, options: RoutingOptions, trials: list[Trial], incumbent: Trial, target: int) -> bool: + if ( + self.problem.initial_paths or target != len(self.problem.nets) + or not 2 <= len(incumbent.valid_costs) < target - 1 + or options.search.node_limit <= _NEAR_PORT_NODE_LIMIT + or options.congestion.max_iterations <= 1 or options.congestion.shuffle_nets or not options.congestion.warm_start_enabled + ): + return False + retained = [incumbent.run.results_by_net[net_id] for net_id in incumbent.valid_costs] + if all(len(result.path) == 1 and result.path[0].move_type == "straight" for result in retained): + return False + + hints = {result.net_id: result.as_seed() for result in retained} + attempts = self._direct(options, "direct-lookahead-hinted", hints=hints) + best = _best_trial(attempts) + if len(incumbent.valid_costs) < len(best.valid_costs) < target: + seeded = replace(options, topology=replace(options.topology, mode="seed")) + attempts.extend(self._incumbent_trials(seeded, best, target)) + if len(_best_trial(attempts).valid_costs) >= target: + trials.extend(attempts) + return True + # The ordinary retry starts from its original incumbents if hints fall short. + trials.extend(replace(trial, selection="incomplete-layout") for trial in attempts) + return False + def _early_guide(self, options: RoutingOptions) -> Trial | None: problem = self.problem if ( @@ -594,6 +629,27 @@ class _AutomaticRun: if self._try_column_recovery(options, trials, groups): return True groups = () + max_shift = 2 * max(options.search.sbend_radii, default=0) + early_perimeter = ( + try_construction_early and target == len(problem.nets) <= 2 and not problem.initial_paths + and options.search.node_limit > 1 and options.search.bend_radii and problem._blocking_polygons + and all(net.start.r == net.target.r == 0 and not _is_short_shift(net, max_shift) for net in problem.nets) + and (target == 2 or problem.nets[0].start.x > problem.nets[0].target.x) + ) + if early_perimeter: + # For a small, fixed-heading layout, try verified construction + # before searching. Defer the perimeter's residual A* to its usual turn. + with self._time("plan", planner="perimeter"): + perimeter = [] + if target == 2: + with self._time("plan", planner="paired-perimeter"): + self._paired_perimeter(perimeter) + else: + perimeter = self._perimeter_trials(options) + trials.extend(perimeter) + if perimeter and len(perimeter[-1].valid_costs) == target: + return True + probe_iterations = options.congestion.max_iterations proxy, _ = resolve_bend_geometry(options.search) # Clipped proxies can find cheaper routes in later probe iterations than in the wider retry. @@ -618,9 +674,9 @@ class _AutomaticRun: trials.append(construction) return True - if len(problem.nets) <= 2: + if len(problem.nets) <= 2 and (not early_perimeter or target == 2): with self._time("plan", planner="perimeter"): - trials.extend(self._perimeter_trials(options)) + trials.extend(self._perimeter_trials(options, try_pair=not early_perimeter)) if len(_best_trial(trials).valid_costs) >= target: return True @@ -630,6 +686,8 @@ class _AutomaticRun: # Every short shift has lateral displacement, so the direct retry cannot lock # any straight paths. It would run the same guide with the same budget. if early is None or early.run.metrics.timeout_events: + if self._try_hinted_lookahead(options, trials, _best_trial(probe), target): + return True trials.extend(self._direct(options, "direct-lookahead-retry")) return len(_best_trial(trials).valid_costs) >= target @@ -695,7 +753,9 @@ class _AutomaticRun: def _refine(self, trials: list[Trial]) -> Trial | None: best = _best_trial(trials) - if not self.options.refinement.enabled or not best.valid_costs: + if not self.options.refinement.enabled or not any( + PathRefiner.has_refinement_bends(best.run.results_by_net[net_id].path) for net_id in best.valid_costs + ): return None has_unresolved_paths = any(result.path and not result.is_valid for result in best.run.results_by_net.values()) run, stage = self._seeded_attempt( diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 56f1e37..30503a3 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -10,8 +10,8 @@ from itertools import combinations_with_replacement, islice, pairwise, product from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin from typing import TYPE_CHECKING -from shapely import total_bounds -from shapely.geometry import LineString, box +from shapely import linestrings, total_bounds +from shapely.geometry import box from inire.geometry.components import bend90_uses_circular_geometry, bend_fits_width from inire.geometry.intervals import Gap, open_intervals @@ -23,7 +23,7 @@ from inire.seeds import PathSeed, SBendSeed, StraightSeed if TYPE_CHECKING: from collections.abc import Callable, Iterator, Mapping - from shapely.geometry import Polygon + from shapely.geometry import LineString, Polygon from inire.geometry.primitives import Port from inire.model import NetSpec, RoutingProblem, SearchOptions @@ -394,23 +394,26 @@ def _bend_sequences( return choose +@lru_cache(maxsize=256) +def _arc_samples(radius: int, shift: int) -> tuple[tuple[float, float], ...]: + theta = acos(1 - abs(shift) / (2 * radius)) + signed_radius = radius if shift > 0 else -radius + angles = (theta * i / 12 for i in range(13)) + return tuple((radius * sin(angle), signed_radius * (1 - cos(angle))) for angle in angles) + + def _positions(radius: int, spans: dict[int, int], sequence: _BendSequence, window: int, y: int) -> LineString: x = (window - sequence.span) // 2 points = [(0, y), (x, y)] for shift in sequence.offsets: - theta = acos(1 - abs(shift) / (2 * radius)) - direction = 1 if shift > 0 else -1 + samples = _arc_samples(radius, shift) + points.extend((x + dx, y + dy) for dx, dy in samples[1:]) advance = spans[abs(shift)] - for i in range(1, 13): - angle = theta * i / 12 - points.append((x + radius * sin(angle), y + direction * radius * (1 - cos(angle)))) - for i in range(11, -1, -1): - angle = theta * i / 12 - points.append((x + advance - radius * sin(angle), y + shift - direction * radius * (1 - cos(angle)))) x += advance y += shift + points.extend((x - dx, y - dy) for dx, dy in reversed(samples[:-1])) points.append((window, y)) - return LineString(points) + return linestrings(points) def _schedules( diff --git a/inire/router/_compact.py b/inire/router/_compact.py index b2313cd..94a3c8f 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -25,6 +25,7 @@ if TYPE_CHECKING: from shapely.geometry.base import BaseGeometry from inire.geometry.components import ComponentResult, MoveKind + from inire.geometry.primitives import Port from inire.model import NetSpec, RoutingProblem, SearchOptions from inire.router._routing_policy import Scorer from inire.seeds import PathSegmentSeed @@ -148,8 +149,12 @@ def _verified_candidates( seeds: Iterable[PathSeed], ) -> Iterator[tuple[PathSeed, BaseGeometry, tuple[ComponentResult, ...]]]: bounds = board.bounds + component_cache: dict[tuple[Port, PathSegmentSeed], ComponentResult] = {} for seed in seeds: - path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance, bounds=bounds) + path = materialize_path_seed( + seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance, bounds=bounds, + component_cache=component_cache, + ) if not path or 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]) diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index 3cd7747..8fa2ed1 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -54,7 +54,9 @@ def materialize_path_seed( clearance: float, bounds: tuple[float, float, float, float] | None = None, diagnostic: bool = False, + component_cache: dict[tuple[Port, PathSegmentSeed], ComponentResult] | None = None, ) -> tuple[ComponentResult, ...] | None: + """Materialize a seed, optionally reusing moves with the same geometry settings.""" if diagnostic: error = seed_preparation_error(seed, start=start, net_width=net_width, search=search, clearance=clearance) if error is not None: @@ -67,6 +69,13 @@ def materialize_path_seed( bend_clip_margin = search.bend_clip_margin for index, segment in enumerate(seed.segments, start=1): + if component_cache is not None: + key = (current, segment) + cached = component_cache.get(key) + if cached is not None: + path.append(cached) + current = cached.end_port + continue kind, parameters = seed_move(segment) try: template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None @@ -87,6 +96,8 @@ def materialize_path_seed( if diagnostic: raise SeedMaterializationError(f"segment {index} ({type(segment).__name__}) {exc}") from exc return None + if component_cache is not None and len(component_cache) < 256: + component_cache[key] = component path.append(component) current = component.end_port return tuple(path) diff --git a/inire/router/refiner.py b/inire/router/refiner.py index f8aa010..761ff5d 100644 --- a/inire/router/refiner.py +++ b/inire/router/refiner.py @@ -262,7 +262,10 @@ class PathRefiner: moves.append(_DoglegMove(curr, length, "straight")) return moves if curr == target else None - def _build_dogleg(self, start: Port, width: float, radius: float, moves: list[_DoglegMove]) -> list[ComponentResult]: + def _build_dogleg( + self, start: Port, width: float, radius: float, moves: list[_DoglegMove], + components: dict[tuple[Port, MoveKind, tuple], ComponentResult], + ) -> list[ComponentResult]: search = self.context.options.search proxy, physical = resolve_bend_geometry(search) dilation = self.collision_engine.clearance / 2.0 @@ -272,11 +275,16 @@ class PathRefiner: bounds = None if board is None else board.bounds for move in moves: parameters = (move.length,) if move.direction is None else (radius, move.direction) - component = build_component( - port, width, move.move_type, parameters, - collision_type=proxy, physical_geometry_type=physical, clip_margin=search.bend_clip_margin, dilation=dilation, - physical_length=search.bend_physical_length if move.move_type == "bend90" else None, bounds=bounds, - ) + key = (port, move.move_type, parameters) + component = components.get(key) + if component is None: + component = build_component( + port, width, move.move_type, parameters, + collision_type=proxy, physical_geometry_type=physical, clip_margin=search.bend_clip_margin, dilation=dilation, + physical_length=search.bend_physical_length if move.move_type == "bend90" else None, bounds=bounds, + ) + if len(components) < 256: + components[key] = component path.append(component) port = component.end_port return path @@ -367,11 +375,12 @@ class PathRefiner: proxy, physical = resolve_bend_geometry(search) circular_bend = bend90_uses_circular_geometry(proxy, physical) custom_danger_map = self.context.cost_evaluator.danger_map if isinstance(physical, Polygon) else None + components: dict[tuple[Port, MoveKind, tuple], ComponentResult] = {} for radius in search.bend_radii: if circular_bend and not bend_fits_width(radius, net_width): continue side_extents = self._candidate_side_extents(window_start, window_end, window_path, net_width, radius) - for side_extent in side_extents: + for side_extent in dict.fromkeys(map(round, side_extents)): moves = self._dogleg_moves(window_start, window_end, radius, side_extent) if moves is None: continue @@ -383,7 +392,7 @@ class PathRefiner: if not outside and not self.score_path(scoring_start, [*prefix, *moves, *suffix]) + 1e-6 < best_candidate_cost: continue try: - replacement = self._build_dogleg(window_start, net_width, radius, moves) + replacement = self._build_dogleg(window_start, net_width, radius, moves, components) except (ComponentPreparationError, OverflowError): continue self.context.metrics.total_refinement_candidates_built += 1 diff --git a/scripts/benchmark_retry_order.py b/scripts/benchmark_retry_order.py index 1042b1e..9b31ef4 100644 --- a/scripts/benchmark_retry_order.py +++ b/scripts/benchmark_retry_order.py @@ -31,6 +31,7 @@ if TYPE_CHECKING: from inire.model import RoutingOptions, RoutingProblem from inire.results import RoutingResult from inire.router._routing_policy import Trial + from inire.seeds import PathSeed from inire.tests.routing_benchmark_case import BenchmarkCase @@ -85,14 +86,14 @@ class _RetryExperiment(_AutomaticRun): options = replace(self.options, refinement=replace(self.options.refinement, enabled=False)) trials.extend(self._widen_residual(options, retained, limit, target, policy="late-bounded-residual", check_connectivity=True)) - def _direct(self, options: RoutingOptions, policy: str) -> list[Trial]: + def _direct(self, options: RoutingOptions, policy: str, *, hints: dict[str, PathSeed] | None = None) -> list[Trial]: cap = self.retry_policy.probe_iterations if policy == "direct-probe-near-port" and cap is not None: configured = self.options.congestion.max_iterations iterations = configured if cap == "configured" else min(configured, cap) if iterations != options.congestion.max_iterations: options = replace(options, congestion=replace(options.congestion, max_iterations=iterations)) - return super()._direct(options, policy) + return super()._direct(options, policy, hints=hints) def _seed_recovery_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> None: limit = self.retry_policy.lattice_limit From 5f88e0277578235e0be652f85d080b8e9e830047 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 19:30:10 -0800 Subject: [PATCH 46/57] Consolidate routing tests while preserving the benchmark corpus Reuse benchmark and reference runs, combine related geometry and replay checks, and run example outcome and timing checks from the same cases. Keep every benchmark board and retry holdout independently selectable. --- docs/benchmarks.md | 2 + inire/tests/conftest.py | 15 + inire/tests/example_scenarios.py | 13 + inire/tests/test_api.py | 2049 ++++----------------- inire/tests/test_astar.py | 416 +---- inire/tests/test_capacity.py | 19 +- inire/tests/test_clearance_precision.py | 35 - inire/tests/test_collision.py | 429 +---- inire/tests/test_columns.py | 204 +- inire/tests/test_compact.py | 19 +- inire/tests/test_components.py | 184 +- inire/tests/test_congestion.py | 25 - inire/tests/test_cost.py | 48 - inire/tests/test_example_performance.py | 53 +- inire/tests/test_example_regressions.py | 230 +-- inire/tests/test_layout.py | 191 +- inire/tests/test_pathfinder.py | 55 +- inire/tests/test_performance_reporting.py | 295 +-- inire/tests/test_perimeter.py | 140 +- inire/tests/test_primitives.py | 25 +- inire/tests/test_refinements.py | 146 +- inire/tests/test_route_behavior.py | 147 +- inire/tests/test_routing_benchmarks.py | 615 +------ inire/tests/test_routing_fixtures.py | 186 ++ inire/tests/test_terminal_bench.py | 131 +- inire/tests/test_topology.py | 150 +- inire/tests/test_variable_grid.py | 71 - inire/tests/test_visibility.py | 45 - pyproject.toml | 3 +- 29 files changed, 929 insertions(+), 5012 deletions(-) create mode 100644 inire/tests/conftest.py create mode 100644 inire/tests/test_routing_fixtures.py delete mode 100644 inire/tests/test_variable_grid.py diff --git a/docs/benchmarks.md b/docs/benchmarks.md index ecc7a25..bf0c16a 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -27,6 +27,8 @@ Expect `3/4 valid`. All four nets need to cross a vertical cut where the opening 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. + - [Fixture sources and regeneration](benchmark-fixtures.md) ## Choose a profile diff --git a/inire/tests/conftest.py b/inire/tests/conftest.py new file mode 100644 index 0000000..447b3bc --- /dev/null +++ b/inire/tests/conftest.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +if TYPE_CHECKING: + from inire.results import RoutingRunResult + + +@pytest.fixture(scope="session") +def example_07_no_warm_start_trace() -> RoutingRunResult: + from inire.tests.example_scenarios import trace_example_07_no_warm_start # noqa: PLC0415 + + return trace_example_07_no_warm_start() diff --git a/inire/tests/example_scenarios.py b/inire/tests/example_scenarios.py index 19d1166..aa94f4d 100644 --- a/inire/tests/example_scenarios.py +++ b/inire/tests/example_scenarios.py @@ -460,6 +460,19 @@ SCENARIOS: tuple[tuple[str, ScenarioRun], ...] = tuple( (name, partial(_snapshot_outcome, capture)) for name, capture in SCENARIO_SNAPSHOTS ) +# Total results, verified results, and reached targets for each example. +EXPECTED_OUTCOMES = { + "example_01_simple_route": (1, 1, 1), + "example_02_congestion_resolution": (3, 3, 3), + "example_03_locked_paths": (2, 2, 2), + "example_04_sbends_and_radii": (2, 2, 2), + "example_05_orientation_stress": (3, 3, 3), + "example_06_bend_collision_models": (3, 3, 3), + "example_07_large_scale_routing": (10, 10, 10), + "example_08_custom_bend_geometry": (2, 2, 2), + "example_09_unroutable_best_effort": (1, 0, 0), +} + PERFORMANCE_SCENARIO_SNAPSHOTS: tuple[tuple[str, ScenarioSnapshotRun], ...] = ( ("example_07_large_scale_routing_no_warm_start", snapshot_example_07_no_warm_start), ("example_07_large_scale_routing_no_warm_start_seed43", snapshot_example_07_no_warm_start_seed43), diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index eb5a569..8cedea5 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -1,14 +1,11 @@ -import importlib from contextlib import nullcontext -from dataclasses import asdict, replace -from pickle import dumps, loads +from dataclasses import replace import pytest import shapely -from shapely.affinity import rotate, translate +from shapely.affinity import translate from shapely.geometry import Polygon, box -import inire import inire.geometry.components as components_module import inire.router._router as router_module import inire.router._search as search_module @@ -16,6 +13,7 @@ from inire import ( Bend90Seed, CongestionOptions, DiagnosticsOptions, + FixedRoute, NetSpec, ObjectiveWeights, PathSeed, @@ -30,49 +28,14 @@ from inire import ( TopologyOptions, route, ) -from inire.geometry.components import Bend90, SBend, Straight +from inire.geometry.components import SBend, Straight from inire.geometry.collision import RoutingWorld -from inire.results import RoutingReport, RoutingResult +from inire.results import ComponentConflictTrace, RoutingReport, RoutingResult from inire.router._astar_types import AStarContext from inire.router._router import PathFinder, _IterationReview from inire.router._stack import RoutingAttempts from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap -def test_root_module_exports_only_stable_surface() -> None: - assert not hasattr(inire, "RoutingWorld") - assert not hasattr(inire, "AStarContext") - assert not hasattr(inire, "PathFinder") - assert not hasattr(inire, "CostEvaluator") - assert not hasattr(inire, "DangerMap") - - -def test_deep_raw_stack_imports_remain_accessible_but_unstable() -> None: - router_module = importlib.import_module("inire.router._router") - search_module = importlib.import_module("inire.router._search") - collision_module = importlib.import_module("inire.geometry.collision") - - assert hasattr(router_module, "PathFinder") - assert hasattr(search_module, "route_astar") - assert hasattr(collision_module, "RoutingWorld") - - -def test_route_problem_smoke() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net1", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), - ) - - run = route(problem) - - assert set(run.results_by_net) == {"net1"} - assert run.results_by_net["net1"].is_valid - assert run.automatic is not None - assert run.automatic.verified_net_ids == ("net1",) - assert all(stage.node_limit <= 500 for stage in run.automatic.stages) - assert run.conflict_trace == () - assert run.frontier_trace == () - assert run.pre_pair_frontier_trace is None - assert run.iteration_trace == () def test_routing_problem_rejects_duplicate_net_ids() -> None: @@ -84,118 +47,100 @@ def test_routing_problem_rejects_duplicate_net_ids() -> None: with pytest.raises(ValueError, match="Duplicate net ID: 'shared'"): RoutingProblem(bounds=(0, 0, 100, 100), nets=nets) - -@pytest.mark.parametrize("width", [0, -2, float("nan"), float("inf")]) -def test_net_width_must_be_finite_and_positive(width) -> None: - with pytest.raises(ValueError, match="width must be finite and positive"): - NetSpec("net", Port(10, 20, 0), Port(90, 20, 0), width=width) + fixed = FixedRoute("shared", (box(10, 40, 90, 42),)) + with pytest.raises(ValueError, match="Duplicate active or fixed net ID: 'shared'"): + RoutingProblem(bounds=(0, 0, 100, 100), nets=nets[:1], fixed_routes=(fixed,)) -@pytest.mark.parametrize("clearance", [-1.0, float("nan"), float("inf")]) -def test_routing_clearance_must_be_finite_and_nonnegative(clearance) -> None: - with pytest.raises(ValueError, match="clearance must be finite and nonnegative"): - RoutingProblem((0, 0, 100, 100), clearance=clearance) +def test_routing_problem_requires_typed_geometry_inputs() -> None: + bounds = (0, 0, 100, 100) + with pytest.raises(TypeError, match="must be a Shapely Polygon"): + RoutingProblem(bounds, static_obstacles=(box(20, 20, 30, 30).boundary,)) + with pytest.raises(TypeError, match="initial_paths values must be PathSeed"): + RoutingProblem(bounds, initial_paths={"line": (StraightSeed(50),)}) -@pytest.mark.parametrize( - "bounds", - [(100, 0, 0, 100), (0, 0, 100, 0), (0, 0, float("inf"), 100), (0, 0, 100, float("nan"))], -) -def test_routing_bounds_require_a_finite_positive_rectangle(bounds) -> None: - with pytest.raises(ValueError, match="bounds must be finite"): - RoutingProblem(bounds) +def test_net_width_must_be_finite_and_positive() -> None: + for width in (0, float("nan")): + with pytest.raises(ValueError, match="width must be finite and positive"): + NetSpec("net", Port(10, 20, 0), Port(90, 20, 0), width=width) -@pytest.mark.parametrize("keepout", [Polygon(), Polygon([(0, 0), (10, 10), (0, 10), (10, 0)])]) -def test_routing_keepout_must_be_nonempty_and_valid(keepout) -> None: +def test_routing_clearance_must_be_finite_and_nonnegative() -> None: + for clearance in (-1.0, float("inf")): + with pytest.raises(ValueError, match="clearance must be finite and nonnegative"): + RoutingProblem((0, 0, 100, 100), clearance=clearance) + + +def test_routing_bounds_require_a_finite_positive_rectangle() -> None: + for bounds in ((100, 0, 0, 100), (0, 0, 100, float("nan"))): + with pytest.raises(ValueError, match="bounds must be finite"): + RoutingProblem(bounds) + + +def test_routing_keepout_must_be_nonempty_and_valid() -> None: + keepout = Polygon([(0, 0), (10, 10), (0, 10), (10, 0)]) with pytest.raises(ValueError, match=r"static_obstacles\[1\].*nonempty and valid"): RoutingProblem((0, 0, 100, 100), static_obstacles=(box(20, 20, 30, 30), keepout)) -def test_routing_keepout_must_be_a_polygon() -> None: - with pytest.raises(TypeError, match=r"static_obstacles\[0\].*Polygon"): - RoutingProblem((0, 0, 100, 100), static_obstacles=(box(20, 20, 30, 30).boundary,)) +def test_search_distances_and_radii_require_finite_values() -> None: + with pytest.raises(ValueError, match="bend_radii"): + SearchOptions(bend_radii=(float("inf"),)) + with pytest.raises(ValueError, match="min_straight_length"): + SearchOptions(min_straight_length=-1) + with pytest.raises(ValueError, match="max_straight_length"): + SearchOptions(max_straight_length=0) + with pytest.raises(ValueError, match="bend_proxy_geometry"): + SearchOptions(bend_proxy_geometry="clipped-bbox") -@pytest.mark.parametrize( - ("name", "value"), - [ - ("bend_radii", (float("inf"),)), - ("sbend_radii", (float("nan"),)), - ("bend_radii", (0,)), - ("min_straight_length", float("nan")), - ("max_straight_length", float("inf")), - ], -) -def test_search_distances_and_radii_require_finite_values(name, value) -> None: - with pytest.raises(ValueError, match=name): - SearchOptions(**{name: value}) +def test_route_does_not_generate_bends_wider_than_their_diameter() -> None: + nets = ( + NetSpec("turn", Port(20, 25, 0), Port(30, 35, 90), width=25), + NetSpec("shift", Port(20, 85, 0), Port(35, 91, 0), width=25), + ) + seeds = { + "turn": PathSeed((Bend90Seed(10, "CCW"),)), + "shift": PathSeed((SBendSeed(6, 10),)), + } + problem = RoutingProblem((0, 0, 100, 120), nets, initial_paths=seeds) + options = RoutingOptions( + search=SearchOptions(bend_radii=(10,), sbend_radii=(10,), node_limit=100), + congestion=CongestionOptions(max_iterations=1), + ) + + run = route(problem, options=options) + + assert set(run.results_by_net) == set(seeds) + for result in run.results_by_net.values(): + assert not result.is_valid + assert all(isinstance(move, StraightSeed) for move in result.as_seed().segments) -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize("with_seed", [False, True]) -@pytest.mark.parametrize( - ("target", "width", "segment", "search"), - [ - (Port(25, 25, 90), 12, Bend90Seed(5, "CCW"), SearchOptions(bend_radii=(5,), sbend_radii=(), node_limit=100)), - (Port(31, 23, 0), 25, SBendSeed(3, 10), SearchOptions(bend_radii=(), sbend_radii=(10,), node_limit=100)), - ], - ids=["quarter-turn", "sbend"], -) -def test_route_does_not_generate_bends_wider_than_their_diameter(mode, with_seed, target, width, segment, search) -> None: - net = NetSpec("wide", Port(20, 20, 0), target, width=width) - seeds = {"wide": PathSeed((segment,))} if with_seed else {} - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths=seeds) - options = RoutingOptions(search=search, topology=TopologyOptions(mode=mode), congestion=CongestionOptions(max_iterations=1)) +def test_seed_parameters_must_describe_a_forward_usable_move() -> None: + with pytest.raises(ValueError, match="seed"): + StraightSeed(-10) + with pytest.raises(ValueError, match="seed"): + Bend90Seed(0, "CW") + with pytest.raises(ValueError, match="seed"): + SBendSeed(20, 10) + with pytest.raises(ValueError, match="seed"): + SBendSeed(3.5, 10) - result = route(problem, options=options).results_by_net["wide"] + +def test_search_skips_sbends_when_the_offset_list_is_empty() -> None: + problem = RoutingProblem((0, 0, 90, 70), (NetSpec("shift", Port(10, 20, 0), Port(60, 24, 0)),)) + options = RoutingOptions( + search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=(10,), sbend_offsets=()), + topology=TopologyOptions(mode="off"), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + ) + + result = route(problem, options=options).results_by_net["shift"] assert not result.is_valid - assert all(isinstance(move, StraightSeed) for move in result.as_seed().segments) - - -@pytest.mark.parametrize( - ("seed_type", "args"), - [ - (StraightSeed, (-10,)), - (StraightSeed, (float("inf"),)), - (Bend90Seed, (0, "CW")), - (Bend90Seed, (10, "left")), - (SBendSeed, (0, 10)), - (SBendSeed, (20, 10)), - (SBendSeed, (3.5, 10)), - ], -) -def test_seed_parameters_must_describe_a_forward_usable_move(seed_type, args) -> None: - with pytest.raises(ValueError, match="seed"): - seed_type(*args) - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_route_keeps_off_lattice_sbend_physically_connected(mode) -> None: - net = NetSpec("shift", Port(10, 20, 0), Port(60, 23, 0)) - problem = RoutingProblem((0, 0, 90, 70), (net,)) - options = RoutingOptions(topology=TopologyOptions(mode=mode)) - - result = route(problem, options=options).results_by_net["shift"] - - assert result.is_valid - assert SBendSeed(3, 10) in result.as_seed().segments - footprint = shapely.union_all(result.locked_geometry) - assert footprint.geom_type == "Polygon" - assert footprint.covers(shapely.Point(net.start.x, net.start.y)) - assert footprint.covers(shapely.Point(net.target.x, net.target.y)) - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize("offsets", [(), (4,)]) -def test_route_respects_explicit_sbend_offsets(mode, offsets) -> None: - problem = RoutingProblem((0, 0, 90, 70), (NetSpec("shift", Port(10, 20, 0), Port(60, 23, 0)),)) - options = RoutingOptions(search=SearchOptions(node_limit=100, sbend_offsets=offsets), topology=TopologyOptions(mode=mode)) - - result = route(problem, options=options).results_by_net["shift"] - - assert all(segment.offset in offsets for segment in result.as_seed().segments if isinstance(segment, SBendSeed)) + assert not any(isinstance(move, SBendSeed) for move in result.as_seed().segments) def test_initial_path_must_respect_explicit_sbend_offsets() -> None: @@ -212,67 +157,40 @@ def test_initial_path_must_respect_explicit_sbend_offsets() -> None: assert result.as_seed() == seed -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize( - ("move", "target", "field"), - [(Bend90Seed(5, "CCW"), Port(25, 25, 90), "bend_radii"), (SBendSeed(3, 10), Port(31, 23, 0), "sbend_radii")], -) -def test_replay_reports_an_incompatible_seed_and_verifies_other_nets(mode, move, target, field) -> None: - nets = (NetSpec("net", Port(20, 20, 0), target), NetSpec("peer", Port(10, 60, 0), Port(70, 60, 0))) - seeds = {"net": PathSeed((move,)), "peer": PathSeed((StraightSeed(60),))} - problem = RoutingProblem( - (0, 0, 100, 100), nets, initial_paths=seeds, +def test_replay_reports_incompatible_seed_segments_and_verifies_peers() -> None: + cases = ( + (NetSpec("unsupported_turn", Port(20, 20, 0), Port(25, 25, 90)), + Bend90Seed(5, "CCW"), "uses radius 5 outside bend_radii"), + (NetSpec("unsupported_sbend", Port(20, 60, 0), Port(35, 63, 0)), + SBendSeed(3, 20), "uses radius 20 outside sbend_radii"), + (NetSpec("overwide_turn", Port(20, 100, 0), Port(30, 110, 90), width=30), + Bend90Seed(10, "CCW"), "segment 1 (Bend90Seed) needs radius at least 15, got 10"), + (NetSpec("overwide_sbend", Port(20, 150, 0), Port(35, 156, 0), width=30), + SBendSeed(6, 10), "segment 1 (SBendSeed) needs radius at least 15, got 10"), ) + peer = NetSpec("peer", Port(20, 190, 0), Port(70, 190, 0)) + seeds = {net.net_id: PathSeed((segment,)) for net, segment, _ in cases} + seeds[peer.net_id] = PathSeed((StraightSeed(50),)) + problem = RoutingProblem((0, 0, 100, 220), (*(net for net, _, _ in cases), peer), initial_paths=seeds) options = RoutingOptions( - search=SearchOptions(node_limit=0, **{field: ()}), - topology=TopologyOptions(mode=mode), + search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=(10,)), + topology=TopologyOptions(mode="off"), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) - callback_reports = [] + callbacks = [] - run = route(problem, options=options, iteration_callback=lambda _, results: callback_reports.append(results["net"].report)) + run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results)) - assert run.results_by_net["peer"].is_valid - rejected = run.results_by_net["net"] - assert rejected.outcome == "unroutable" - assert rejected.report.seed_error.endswith(f"outside {field}") - assert rejected.report.invalid_geometry - assert callback_reports == [rejected.report] - assert run.conflict_trace[-1].nets[0].report == rejected.report + assert run.results_by_net[peer.net_id].is_valid assert run.metrics.nodes_expanded == 0 - - -@pytest.mark.parametrize("mode", ["automatic", "off"]) -def test_search_routes_both_nets_after_rejecting_an_incompatible_seed(mode) -> None: - nets = (NetSpec("net", Port(10, 20, 0), Port(70, 20, 0)), NetSpec("peer", Port(10, 60, 0), Port(70, 60, 0))) - problem = RoutingProblem((0, 0, 100, 100), nets, initial_paths={"net": PathSeed((Bend90Seed(10, "CCW"),))}) - options = RoutingOptions( - search=SearchOptions(node_limit=40, bend_radii=(20,), sbend_radii=()), - topology=TopologyOptions(mode=mode), - ) - - run = route(problem, options=options) - - assert all(result.is_valid for result in run.results_by_net.values()) - assert run.results_by_net["net"].report.seed_error == "Initial path for 'net' uses radius 10 outside bend_radii" - assert run.results_by_net["net"].as_seed() == PathSeed((StraightSeed(60),)) - - -def test_search_rejects_a_keepout_intersection_just_past_a_clear_launch_face() -> None: - net = NetSpec("line", Port(10, 20, 0), Port(60, 20, 0)) - problem = RoutingProblem((0, 0, 80, 70), (net,), (box(10.0005, 19.9999, 10.001, 20.0001),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=()), - topology=TopologyOptions(mode="off"), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - ) - - run = route(problem, options=options) - result = run.results_by_net[net.net_id] - - assert result.outcome == "unroutable" - assert result.report.terminal_error is None - assert run.metrics.nodes_expanded == 1 + assert callbacks == [run.results_by_net] + traced_reports = {net.net_id: net.report for net in run.conflict_trace[-1].nets} + for net, _, error in cases: + rejected = run.results_by_net[net.net_id] + assert rejected.outcome == "unroutable" + assert rejected.report.seed_error == f"Initial path for {net.net_id!r} {error}" + assert rejected.report.invalid_geometry + assert traced_reports[net.net_id] == rejected.report @pytest.mark.parametrize(("clearance", "valid"), [(0, True), (0.001, False)]) @@ -298,8 +216,7 @@ def test_search_checks_physical_clearance_after_a_local_proxy_intersection(clear assert result.locked_geometry[0].distance(keepout) == pytest.approx(0.0005) -@pytest.mark.parametrize("node_limit", [0, 50]) -def test_lattice_search_replaces_a_complete_seed_that_hits_a_keepout(node_limit) -> None: +def test_lattice_search_repairs_a_seed_that_verification_retains() -> None: net = NetSpec("line", Port(20, 20, 0), Port(120, 20, 0)) up, down = Bend90Seed(10, "CCW"), Bend90Seed(10, "CW") detour = PathSeed((up, down, StraightSeed(60), down, up)) @@ -307,139 +224,45 @@ def test_lattice_search_replaces_a_complete_seed_that_hits_a_keepout(node_limit) (0, 0, 150, 70), (net,), (box(60, 38, 80, 42),), initial_paths={net.net_id: detour}, clearance=1, ) options = RoutingOptions( - search=SearchOptions(node_limit=node_limit, bend_radii=(10,), sbend_radii=()), + search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=()), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) - run = route(problem, options=options) - result = run.results_by_net[net.net_id] + verified = route(problem, options=options) + retained = verified.results_by_net[net.net_id] + repaired = route(problem, options=replace(options, search=replace(options.search, node_limit=50))) + replacement = repaired.results_by_net[net.net_id] - assert result.reached_target - if node_limit: - assert run.metrics.nodes_expanded > 0 - assert result.is_valid - assert result.as_seed() == PathSeed((StraightSeed(100),)) - else: - assert run.metrics.nodes_expanded == 0 - assert result.report.static_collision_count == 1 - assert result.as_seed() == detour + assert verified.metrics.nodes_expanded == 0 + assert retained.reached_target + assert retained.outcome == "colliding" + assert retained.report.static_collision_count == 1 + assert retained.as_seed() == detour + assert repaired.metrics.nodes_expanded > 0 + assert replacement.reached_target + assert replacement.is_valid + assert replacement.as_seed() == PathSeed((StraightSeed(100),)) -def test_route_warns_when_a_custom_bend_misses_its_ports() -> None: - net = NetSpec("bend", Port(20, 20, 0), Port(30, 30, 90)) - seed = PathSeed((Bend90Seed(10, "CCW"),)) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed}) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10,), bend_physical_geometry=box(4, -6, 6, -4)), - congestion=CongestionOptions(max_iterations=1), - ) - - with pytest.warns(UserWarning, match="does not match the declared port faces"): - result = route(problem, options=options).results_by_net["bend"] - - assert result.reached_target - assert result.is_valid +def test_search_and_congestion_reject_invalid_budgets() -> None: + for budget in (True, -1, 1.5): + with pytest.raises(ValueError, match="node_limit must be a nonnegative integer"): + SearchOptions(node_limit=budget) + with pytest.raises(ValueError, match="max_iterations must be a nonnegative integer"): + CongestionOptions(max_iterations=budget) -def test_route_verification_accepts_point_contact_at_the_declared_port() -> None: - net = NetSpec("bend", Port(20, 20, 0), Port(50, 30, 90)) - seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW"))) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed}) - outline = Polygon([(0, -10), (4, -8), (10, 0)]) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10,), bend_physical_geometry=outline), - congestion=CongestionOptions(max_iterations=1), - ) - - with pytest.warns(UserWarning, match="does not match the declared port faces"): - result = route(problem, options=options).results_by_net["bend"] - - straight, bend = result.locked_geometry - assert straight.intersection(bend).geom_type == "Point" - assert result.reached_target - assert result.is_valid - - -@pytest.mark.parametrize("wrong_side", [False, True]) -def test_route_verification_rejects_adjacent_component_overlap(wrong_side) -> None: - if wrong_side: - outline = shapely.union_all([box(-4, -11, 0, -9), box(-4, -10, -2, -4), box(-4, -6, 11, -4), box(9, -6, 11, 0)]) - else: - outline = shapely.union_all([ - box(0, -11, 11, -9), box(9, -11, 11, 0), - box(2, -9.5, 3, -7), box(-4, -8, 3, -7), box(-4, -10, -3, -7), - ]) - net = NetSpec("bend", Port(20, 20, 0), Port(50, 30, 90)) - seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW"))) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed}) - options = RoutingOptions( - search=SearchOptions(node_limit=0, bend_radii=(10,), bend_physical_geometry=outline), - congestion=CongestionOptions(max_iterations=1), - ) - - warning = pytest.warns(UserWarning, match="declared port faces") if wrong_side else nullcontext() - with warning: - result = route(problem, options=options).results_by_net["bend"] - - straight, bend = result.locked_geometry - assert straight.intersection(bend).area > 0 - assert result.reached_target - assert not result.is_valid - assert result.report.self_collision_count == 1 - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) -def test_custom_sbend_outline_is_shared_by_search_and_seed_replay(mode) -> None: - outline = Polygon([(0, -1), (20, 3), (50, 29), (80, 39), (80, 41), (50, 31), (20, 5), (0, 1)]) - net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0)) - problem = RoutingProblem((0, 0, 160, 160), (net,)) - options = RoutingOptions( - search=SearchOptions(bend_radii=(), sbend_radii=(50,), sbend_outlines=(SBendOutline(40, 50, 2, outline),)), - congestion=CongestionOptions(max_iterations=1), - topology=TopologyOptions(mode=mode), - ) - - result = route(problem, options=options).results_by_net["shift"] - replay = route( - replace(problem, initial_paths={"shift": result.as_seed()}), - options=replace(options, search=replace(options.search, node_limit=0)), - ).results_by_net["shift"] - - assert result.is_valid - assert replay.is_valid - assert result.as_seed() == PathSeed((SBendSeed(40, 50),)) - assert len(result.locked_geometry) == 1 - assert result.locked_geometry[0].equals(translate(outline, 30, 50)) - assert result.locked_geometry == replay.locked_geometry - - -def test_sbend_outline_warns_when_a_port_face_is_missing() -> None: - half = SBend.generate(Port(0, 0, 0), 40, 50, 2).physical_geometry[0] - - with pytest.warns(UserWarning, match="port faces"): - assert SBendOutline(40, 50, 2, half).polygon == half - - -@pytest.mark.parametrize("budget", [True, -1, 1.5, float("nan"), float("inf")]) -def test_search_and_congestion_reject_invalid_budgets(budget) -> None: - with pytest.raises(ValueError, match="node_limit must be a nonnegative integer"): - SearchOptions(node_limit=budget) - with pytest.raises(ValueError, match="max_iterations must be a nonnegative integer"): - CongestionOptions(max_iterations=budget) - - -@pytest.mark.parametrize("value", [-1, float("nan"), float("inf")]) -def test_cost_options_require_finite_nonnegative_values(value) -> None: +def test_cost_options_require_finite_nonnegative_values() -> None: with pytest.raises(ValueError, match="unit_length_cost"): - ObjectiveWeights(unit_length_cost=value) + ObjectiveWeights(unit_length_cost=float("nan")) with pytest.raises(ValueError, match="greedy_h_weight"): - SearchOptions(greedy_h_weight=value) + SearchOptions(greedy_h_weight=-1) with pytest.raises(ValueError, match="base_penalty"): - CongestionOptions(base_penalty=value) + CongestionOptions(base_penalty=float("nan")) with pytest.raises(ValueError, match="multiplier"): - CongestionOptions(multiplier=value) + CongestionOptions(multiplier=-1) def test_public_inputs_reject_invalid_ids_and_named_options() -> None: @@ -451,18 +274,6 @@ def test_public_inputs_reject_invalid_ids_and_named_options() -> None: SearchOptions(visibility_guidance="exact") -@pytest.mark.parametrize(("name", "value"), [ - ("bend_collision_type", "clipped-bbox"), - ("bend_collision_type", None), - ("bend_proxy_geometry", "clipped-bbox"), - ("bend_proxy_geometry", 1), - ("bend_physical_geometry", "bbox"), -]) -def test_search_rejects_unsupported_bend_geometry(name, value) -> None: - with pytest.raises(ValueError, match=f"Invalid {name}"): - SearchOptions(**{name: value}) - - def _sbend_strip(offset, half_width=1): centerline = [(0, 0), (20, offset / 10), (50, 3 * offset / 4), (80, offset)] return Polygon( @@ -500,95 +311,34 @@ def test_custom_sbend_board_admission_agrees_with_replay_and_net_order() -> None assert route(replace(seeded, bounds=smaller_board), options=replay_options).results_by_net[edge.net_id].report.out_of_bounds -def test_custom_quarter_turn_can_end_at_a_declared_port_outside_the_board() -> None: - polygon = box(0, -11, 11, -9).union(box(9, -11, 11, -0.5)) - net = NetSpec("corner", Port(10, 10, 0), Port(20, 20, 90)) - problem = RoutingProblem((0, 0, 35, 19.75), (net,), clearance=0) - options = RoutingOptions(search=SearchOptions(node_limit=20, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=polygon)) - - with pytest.warns(UserWarning, match="declared port faces"): - result = route(problem, options=options).results_by_net[net.net_id] - - assert result.is_valid - assert result.as_seed() == PathSeed((Bend90Seed(10, "CCW"),)) - assert result.locked_geometry[0].bounds[3] == 19.5 - - -@pytest.mark.parametrize(("field", "enabled_values"), [("sbend_radii", (50,)), ("sbend_offsets", (40,))]) -def test_disabled_sbend_outline_can_be_reenabled(field, enabled_values) -> None: - outline = SBendOutline(40, 50, 2, _sbend_strip(40)) - search = SearchOptions(node_limit=25, bend_radii=(), sbend_radii=(50,), sbend_offsets=(40,), sbend_outlines=(outline,)) - disabled = replace(search, **{field: ()}) - assert disabled.sbend_outlines == (outline,) - assert not disabled.has_applicable_sbend_outline((2,)) - assert disabled.sbend_template(40, 50, 2) is None - assert "_active_sbend_outlines" not in asdict(disabled) - assert loads(dumps(disabled)).sbend_template(40, 50, 2) is None - - net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0)) - problem = RoutingProblem((0, 0, 100, 65), (net,), clearance=0) - assert not route(problem, options=RoutingOptions(search=disabled)).results_by_net[net.net_id].reached_target - seed = PathSeed((SBendSeed(40, 50),)) - replay_options = RoutingOptions(search=replace(disabled, node_limit=0)) - replay = route(replace(problem, initial_paths={net.net_id: seed}), options=replay_options).results_by_net[net.net_id] - assert replay.report.seed_error.endswith(f"outside {field}") - enabled = replace(disabled, **{field: enabled_values}) - result = route(problem, options=RoutingOptions(search=enabled)).results_by_net[net.net_id] - assert result.is_valid - assert result.as_seed() == seed - assert result.locked_geometry == (translate(outline.polygon, 10, 10),) - - -def test_search_accepts_a_gap_between_a_custom_sbend_and_a_straight() -> None: - inset_faces = {0: 0.5, 80: 79.5} - polygon = Polygon([(inset_faces.get(x, x), y) for x, y in _sbend_strip(40).exterior.coords]) - with pytest.warns(UserWarning, match="port faces"): - outline = SBendOutline(40, 50, 2, polygon) - net = NetSpec("shift", Port(10, 10, 0), Port(110, 50, 0)) - problem = RoutingProblem((0, 0, 120, 60), (net,), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=(50,), sbend_offsets=(40,), sbend_outlines=(outline,)), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net[net.net_id] - - assert result.is_valid - first, second = result.locked_geometry - assert first.distance(second) == pytest.approx(0.5) - - -@pytest.mark.parametrize(("width", "expected_polygons"), [(0.3, 1), (0.1 + 0.2, 1), (300 * 0.001, 1), (0.31, 2)]) -def test_custom_sbend_matches_float_width_in_search_and_replay(width, expected_polygons) -> None: +def test_custom_sbend_matches_float_width_in_search_and_replay() -> None: outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15)) - net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0), width) - problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) + nets = ( + NetSpec("matching", Port(10, 10, 0), Port(90, 50, 0), 0.1 + 0.2), + NetSpec("fallback", Port(10, 70, 0), Port(90, 110, 0), 0.31), + ) + problem = RoutingProblem((0, 0, 100, 125), nets, clearance=0) search = SearchOptions(node_limit=30, sbend_outlines=(outline,), bend_radii=(), sbend_radii=(50,)) options = RoutingOptions(search=search, topology=TopologyOptions(mode="off")) - active = route(problem, options=options).results_by_net["shift"] + active = route(problem, options=options).results_by_net + seeds = {net.net_id: PathSeed((SBendSeed(40, 50),)) for net in nets} replay = route( - replace(problem, initial_paths={"shift": PathSeed((SBendSeed(40, 50),))}), + replace(problem, initial_paths=seeds), options=replace(options, search=replace(search, node_limit=0)), - ).results_by_net["shift"] - assert active.is_valid - assert replay.is_valid - assert len(active.locked_geometry) == expected_polygons - assert active.locked_geometry == replay.locked_geometry + ).results_by_net + + for net_id, polygon_count in (("matching", 1), ("fallback", 2)): + assert active[net_id].is_valid + assert replay[net_id].is_valid + assert len(active[net_id].locked_geometry) == polygon_count + assert active[net_id].locked_geometry == replay[net_id].locked_geometry -@pytest.mark.parametrize("mode", ["off", "automatic"]) -@pytest.mark.parametrize("terminal", ["start", "target"]) -def test_search_and_seed_replay_check_materialized_sbend_faces(mode, terminal) -> None: +def test_search_and_seed_replay_check_materialized_sbend_faces() -> None: clearance = 0.1 # The nominal face fails clearance. The supplied outline is within the face tolerance. - if terminal == "start": - face_x, offset = 0, 0.8e-6 - keepout = box(0, 7, 10 - clearance + 0.4e-6, 13) - else: - face_x, offset = 80, -0.8e-6 - keepout = box(90 + clearance - 0.4e-6, 47, 100, 53) - polygon = Polygon([(x + offset if x == face_x else x, y) for x, y in _sbend_strip(40).exterior.coords]) + keepout = box(0, 7, 10 - clearance + 0.4e-6, 13) + polygon = Polygon([(0.8e-6 if x == 0 else x, y) for x, y in _sbend_strip(40).exterior.coords]) outline = SBendOutline(40, 50, 2, polygon) net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0), width=2) problem = RoutingProblem( @@ -596,7 +346,7 @@ def test_search_and_seed_replay_check_materialized_sbend_faces(mode, terminal) - ) options = RoutingOptions( search=SearchOptions(node_limit=0, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline,)), - topology=TopologyOptions(mode=mode), + topology=TopologyOptions(mode="off"), ) callbacks = [] @@ -615,20 +365,6 @@ def test_search_and_seed_replay_check_materialized_sbend_faces(mode, terminal) - assert active.locked_geometry == result.locked_geometry -def test_search_checks_materialized_quarter_turn_face() -> None: - bend = Bend90.generate(Port(0, 0, 0), 20, 2, "CCW") - polygon = Polygon([(0.8e-6 if x == 0 else x, y - 20) for x, y in bend.physical_geometry[0].exterior.coords]) - net = NetSpec("corner", Port(10, 10, 0), Port(30, 30, 90)) - keepout = box(0, 7, 9.9000004, 13) - problem = RoutingProblem((0, 0, 50, 50), (net,), (keepout,), clearance=0.1) - options = RoutingOptions(search=SearchOptions(node_limit=30, bend_radii=(20,), sbend_radii=(), bend_physical_geometry=polygon)) - - result = route(problem, options=options).results_by_net[net.net_id] - - assert result.is_valid - assert result.as_seed() == PathSeed((Bend90Seed(20, "CCW"),)) - - def _nearby_sbend_outlines() -> tuple[SBendOutline, SBendOutline]: outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15)) return outline, replace(outline, width=0.3 * (1 + 1.5e-12)) @@ -643,36 +379,7 @@ def test_custom_sbend_outline_rejects_duplicate_and_ambiguous_widths() -> None: options.sbend_outline(40, 50, (outline.width + other.width) / 2) -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_ambiguous_sbend_outline_reports_the_affected_net_without_blocking_straights(mode) -> None: - outline, other = _nearby_sbend_outlines() - width = (outline.width + other.width) / 2 - peer = NetSpec("peer", Port(10, 80, 0), Port(90, 80, 0), width=0.5) - line = NetSpec("line", Port(10, 10, 0), Port(50, 10, 0), width=width) - problem = RoutingProblem((0, 0, 100, 100), (peer, line), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=10, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline, other)), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode=mode), - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - ) - callbacks = [] - - run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results)) - - assert all(result.is_valid for result in run.results_by_net.values()) - error = f"Ambiguous S-bend outlines for width {width!r} at (offset 40, radius 50)" - assert run.results_by_net["line"].report.sbend_template_error == error - assert run.results_by_net["peer"].report.sbend_template_error is None - assert callbacks - assert callbacks[-1]["line"].report.sbend_template_error == error - assert {net.net_id: net.report.sbend_template_error for net in run.conflict_trace[-1].nets} == {"peer": None, "line": error} - disabled = replace(options, search=replace(options.search, sbend_offsets=())) - assert route(problem, options=disabled).results_by_net["line"].report.sbend_template_error is None - - -@pytest.mark.parametrize("mode", ["automatic", "off"]) -@pytest.mark.parametrize("node_limit", [0, 20]) +@pytest.mark.parametrize(('mode', 'node_limit'), [('automatic', 0), ('off', 20)]) def test_ambiguous_sbend_outline_is_skipped_in_search_and_seed_replay(mode, node_limit) -> None: outline, other = _nearby_sbend_outlines() width = (outline.width + other.width) / 2 @@ -697,27 +404,26 @@ def test_ambiguous_sbend_outline_is_skipped_in_search_and_seed_replay(mode, node assert "segment 1 (SBendSeed) Ambiguous S-bend outlines" in results["shift"].report.seed_error -@pytest.mark.parametrize("contact", ["face", "rounding", "gap", "extra_edge", "extra_point", "wide_face", "overlap"]) -@pytest.mark.parametrize("heading", [0, 90]) +@pytest.mark.parametrize( + ('contact', 'heading'), + [ + ('gap', 0), + ('face', 90), + ('overlap', 90), + ], +) def test_custom_sbend_join_allows_boundary_contact_and_rejects_area_overlap(contact, heading) -> None: left, right = _sbend_strip(40), _sbend_strip(-40) - if contact in ("rounding", "gap"): - shift = 0.25e-6 if contact == "rounding" else 0.75 - left, right = translate(left, -shift), translate(right, shift) - if contact == "wide_face": - left, right = _sbend_strip(40, half_width=2), _sbend_strip(-40, half_width=2) - if contact == "overlap": + if contact == "gap": + left, right = translate(left, -0.75), translate(right, 0.75) + elif contact == "overlap": right = translate(right, -0.5) - if contact in ("extra_edge", "extra_point"): - left = left.union(box(70, 36, 74, 51)).union(box(73, 49, 80, 51)) - tip = box(0, 9, 7, 11) if contact == "extra_edge" else Polygon([(0, 50 - 40), (7, 9), (7, 11)]) - right = right.union(box(6, -3, 8, 11)).union(tip) start = Port(20, 30, 0) if heading == 0 else Port(100, 20, 90) finish = Port(180, 30, 0) if heading == 0 else Port(100, 180, 90) net = NetSpec("shift", start, finish) seed = PathSeed((SBendSeed(40, 50), SBendSeed(-40, 50))) problem = RoutingProblem((0, 0, 220, 220), (net,), initial_paths={"shift": seed}, clearance=0) - warning = pytest.warns(UserWarning, match="port faces") if contact in ("gap", "wide_face", "overlap") else nullcontext() + warning = pytest.warns(UserWarning, match="port faces") if contact in ("gap", "overlap") else nullcontext() with warning: options = RoutingOptions(search=SearchOptions( node_limit=0, sbend_radii=(50,), @@ -728,33 +434,22 @@ def test_custom_sbend_join_allows_boundary_contact_and_rejects_area_overlap(cont assert result.reached_target first, second = result.locked_geometry - if contact in ("rounding", "gap"): + if contact == "gap": assert first.distance(second) > 0 - if contact == "wide_face": - assert first.intersection(second).length == pytest.approx(4) + elif contact == "face": + assert first.intersection(second).length == pytest.approx(2) assert (first.intersection(second).area > 0) == (contact == "overlap") assert result.report.self_collision_count == int(contact == "overlap") assert result.is_valid == (contact != "overlap") -def test_custom_sbend_width_is_measured_over_the_whole_port_face() -> None: - with pytest.warns(UserWarning, match="port faces of width"): - SBendOutline(40, 50, 2, _sbend_strip(40, half_width=0.01)) - - outline = Polygon([(0, -1), (20, -2), (80, 39), (80, 40), (80, 41), (20, 5), (0, 1), (0, 0)]) - assert SBendOutline(40, 50, 2, outline).polygon == outline - - -@pytest.mark.parametrize("node_limit", [0, 40]) -def test_custom_sbend_can_exceed_the_circular_width_limit(node_limit) -> None: +def test_custom_sbend_can_exceed_the_circular_width_limit() -> None: polygon = Polygon([(0, -6), (8, -2), (8, 10), (0, 6)]) outline = SBendOutline(4, 5, 12, polygon) net = NetSpec("wide", Port(10, 10, 0), Port(18, 14, 0), width=12) seed = PathSeed((SBendSeed(4, 5),)) - problem = RoutingProblem( - (0, 0, 50, 50), (net,), initial_paths={} if node_limit else {net.net_id: seed}, clearance=0, - ) - options = RoutingOptions(search=SearchOptions(node_limit=node_limit, bend_radii=(), sbend_radii=(5,), sbend_outlines=(outline,))) + problem = RoutingProblem((0, 0, 50, 50), (net,), clearance=0) + options = RoutingOptions(search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=(5,), sbend_outlines=(outline,))) result = route(problem, options=options).results_by_net[net.net_id] @@ -763,7 +458,13 @@ def test_custom_sbend_can_exceed_the_circular_width_limit(node_limit) -> None: assert result.locked_geometry == (translate(polygon, 10, 10),) -@pytest.mark.parametrize(("node_limit", "circular_proxy"), [(0, False), (40, False), (0, True)]) +@pytest.mark.parametrize( + ('node_limit', 'circular_proxy'), + [ + (40, False), + (0, True), + ], +) def test_custom_quarter_turn_width_depends_on_whether_it_uses_a_circular_proxy(node_limit, circular_proxy) -> None: polygon = box(0, -5, 5, -3).union(box(3, -5, 5, 0)) net = NetSpec("wide", Port(20, 20, 0), Port(24, 24, 90), width=10) @@ -789,39 +490,24 @@ def test_custom_quarter_turn_width_depends_on_whether_it_uses_a_circular_proxy(n assert result.locked_geometry == (translate(polygon, 20, 24),) -@pytest.mark.parametrize("width", [2, 4]) -@pytest.mark.parametrize("node_limit", [0, 100]) -def test_custom_quarter_turn_warns_when_its_faces_do_not_match_the_width(width, node_limit) -> None: +def test_custom_quarter_turn_warns_when_its_faces_do_not_match_the_width() -> None: outline = box(0, -11, 11, -9).union(box(9, -11, 11, 0)) - net = NetSpec("bend", Port(10, 20, 0), Port(30, 40, 90), width) + net = NetSpec("bend", Port(10, 20, 0), Port(30, 40, 90), width=4) seed = PathSeed((StraightSeed(10), Bend90Seed(10, "CCW"), StraightSeed(10))) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={} if node_limit else {"bend": seed}, clearance=0) + problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) options = RoutingOptions( - search=SearchOptions(node_limit=node_limit, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=outline), + search=SearchOptions(node_limit=100, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=outline), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="off"), ) - warning = pytest.warns(UserWarning, match="declared port faces of width 4") if width == 4 else nullcontext() - with warning: + with pytest.warns(UserWarning, match="declared port faces of width 4"): result = route(problem, options=options).results_by_net["bend"] assert result.is_valid assert result.as_seed() == seed -def test_custom_quarter_turn_outline_leaves_circular_sbends_available() -> None: - net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0)) - seed = PathSeed((SBendSeed(40, 50),)) - problem = RoutingProblem((0, 0, 160, 160), (net,), initial_paths={"shift": seed}) - options = RoutingOptions(search=SearchOptions(node_limit=0, sbend_radii=(50,), bend_physical_geometry=box(0, -11, 11, 0))) - - result = route(problem, options=options).results_by_net["shift"] - - assert result.is_valid - assert result.locked_geometry == SBend.generate(net.start, 40, 50, 2).physical_geometry - - def test_route_verification_rejects_self_contact_away_from_a_join() -> None: net = NetSpec("fold", Port(10, 10, 0), Port(10, 12, 180)) turn = Bend90Seed(1, "CCW") @@ -840,56 +526,31 @@ def test_route_verification_rejects_self_contact_away_from_a_join() -> None: assert result.report.self_collision_count > 0 -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize(("seed_length", "grid_length"), [(0.2, 1), (19.5, 20), (19.75, 20), (20.49, 20)]) -def test_fractional_straight_seed_uses_grid_length(mode, seed_length, grid_length) -> None: - net = NetSpec("straight", Port(11, 25, 0), Port(11 + grid_length, 25, 0)) - seed = PathSeed((StraightSeed(seed_length),)) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"straight": seed}) - options = RoutingOptions(topology=TopologyOptions(mode=mode), congestion=CongestionOptions(max_iterations=1)) - - result = route(problem, options=options).results_by_net["straight"] - - assert result.is_valid - assert result.report.total_length == grid_length - assert result.as_seed() == PathSeed((StraightSeed(grid_length),)) - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_no_iterations_skips_seed_preparation(mode, monkeypatch) -> None: - problem = RoutingProblem((0, 0, 100, 100), (NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)),)) - options = RoutingOptions(topology=TopologyOptions(mode=mode), congestion=CongestionOptions(max_iterations=0)) - - def fail_if_called(*_args): - pytest.fail("Search preparation ran with zero routing iterations") - - monkeypatch.setattr(PathFinder, "_prepare_topology", fail_if_called) - monkeypatch.setattr(PathFinder, "_build_greedy_warm_start_paths", fail_if_called) - run = route(problem, options=options) - - assert run.results_by_net["line"].outcome == "unroutable" - assert run.metrics.nodes_expanded == run.metrics.warm_start_paths_built == 0 - - -@pytest.mark.parametrize("mode", ["guide", "seed"]) -def test_zero_search_budget_verifies_seeds_without_triangulation(mode, 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,), initial_paths={"line": PathSeed((StraightSeed(80),))}) - options = RoutingOptions( - search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=1), topology=TopologyOptions(mode=mode), +def test_fractional_straight_seeds_use_grid_lengths() -> None: + lengths = ((0.2, 1, 1), (19.5, 19.5, 20), (20.49, 20.49, 20)) + nets = tuple( + NetSpec(str(y), Port(10, y, 0), Port(10 + target_distance, y, 0)) + for y, (_, target_distance, _) in zip((20, 40, 60), lengths, strict=True) ) + seeds = { + net.net_id: PathSeed((StraightSeed(seed_length),)) + for net, (seed_length, _, _) in zip(nets, lengths, strict=True) + } + problem = RoutingProblem((0, 0, 100, 100), nets, initial_paths=seeds) + options = RoutingOptions(congestion=CongestionOptions(max_iterations=1)) run = route(problem, options=options) - assert run.results_by_net["line"].is_valid assert run.metrics.nodes_expanded == 0 - assert run.metrics.verify_path_report_calls == 1 + for net, (_, _, grid_length) in zip(nets, lengths, strict=True): + result = run.results_by_net[net.net_id] + assert result.is_valid + assert result.report.total_length == grid_length + assert result.as_seed() == PathSeed((StraightSeed(grid_length),)) + assert result.path[-1].end_port == Port(10 + grid_length, net.start.y, 0) -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize("rounds", [1, 10]) -def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monkeypatch) -> None: +def test_verify_only_retains_colliding_seeds_and_final_trace(monkeypatch) -> None: nets = ( NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0)), NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90)), @@ -901,16 +562,16 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke problem = RoutingProblem((0, 0, 100, 100), nets, (box(20, 77, 25, 82),), initial_paths=seeds) options = RoutingOptions( search=SearchOptions(node_limit=0), - congestion=CongestionOptions(max_iterations=rounds), + congestion=CongestionOptions(max_iterations=10), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode=mode), ) def fail_on_proximity(*_args): pytest.fail("Geometry-only verification built a proximity map") monkeypatch.setattr(DangerMap, "precompute", fail_on_proximity) + monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) callbacks = [] run = route(problem, options=options) with_callback = route(problem, options=options, iteration_callback=lambda index, results: callbacks.append((index, results))) @@ -927,8 +588,8 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke iteration, restored, final = run.conflict_trace assert (iteration.stage, restored.stage, final.stage) == ("iteration", "restored_best", "final") assert iteration.conflict_edges == restored.conflict_edges == final.conflict_edges == (("horizontal", "vertical"),) - for traced_net in final.nets[:2]: - assert traced_net.component_conflicts + for traced_net, other_net in zip(final.nets[:2], ("vertical", "horizontal"), strict=True): + assert traced_net.component_conflicts == (ComponentConflictTrace(other_net, 0, 0),) assert traced_net == next(net for net in iteration.nets if net.net_id == traced_net.net_id) assert traced_net == next(net for net in restored.nets if net.net_id == traced_net.net_id) assert run.metrics.nodes_expanded == 0 @@ -941,81 +602,31 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke assert with_callback.metrics.verify_path_report_calls == run.metrics.verify_path_report_calls -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize("move", [Bend90Seed(10, "CCW"), SBendSeed(6, 10)]) -def test_verify_only_reports_width_incompatible_seed_segments(mode, move) -> None: - net = NetSpec("wide", Port(20, 30, 0), Port(30, 40, 90), width=30) - peer = NetSpec("peer", Port(20, 80, 0), Port(70, 80, 0)) - seeds = {"wide": PathSeed((move,)), "peer": PathSeed((StraightSeed(50),))} - problem = RoutingProblem((0, 0, 100, 100), (net, peer), initial_paths=seeds) - options = RoutingOptions( - search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=(10,)), - topology=TopologyOptions(mode=mode), - ) - - callbacks = [] - results = route(problem, options=options, iteration_callback=lambda _, current: callbacks.append(current["wide"].report)).results_by_net - - assert results["peer"].is_valid - report = results["wide"].report - assert report.invalid_geometry - assert report.seed_error == f"Initial path for 'wide' segment 1 ({type(move).__name__}) needs radius at least 15, got 10" - assert callbacks == [report] - - -def test_active_search_can_recover_from_width_incompatible_seed() -> None: - net = NetSpec("wide", Port(20, 30, 0), Port(70, 30, 0), width=30) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"wide": PathSeed((Bend90Seed(10, "CCW"),))}) - options = RoutingOptions(search=SearchOptions(node_limit=10, bend_radii=(10,)), topology=TopologyOptions(mode="off")) - - result = route(problem, options=options).results_by_net["wide"] - - assert result.is_valid - assert result.report.seed_error is not None - assert result.as_seed() == PathSeed((StraightSeed(50),)) - - -@pytest.mark.parametrize("rotation", [0, 90, 180, 270]) -def test_lattice_heading_heuristic_is_cardinally_invariant(rotation) -> None: - origin = (60, 60) - start = Port(8, 60, 0).rotated(rotation, origin) - target = Port(112, 101, 0).rotated(rotation, origin) - keepouts = tuple(rotate(polygon, rotation, origin=origin) for polygon in (box(87, 48, 99, 71), box(28, 84, 47, 107))) - problem = RoutingProblem((0, 0, 120, 120), (NetSpec("turn", start, target, 1.75),), keepouts, clearance=1.25) - options = RoutingOptions( - search=SearchOptions(node_limit=50, bend_radii=(10,), sbend_radii=()), - objective=ObjectiveWeights(danger_weight=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["turn"].is_valid - assert run.metrics.nodes_expanded == 17 - - -@pytest.mark.parametrize("price", [0.001, 1, 1000, 1e12]) -def test_lattice_length_cost_units_preserve_search_order(price) -> None: +def test_lattice_length_cost_units_preserve_search_order() -> None: net = NetSpec("turn", Port(15, 40, 0), Port(165, 80, 0)) problem = RoutingProblem((0, 0, 190, 100), (net,), (box(63, 7, 85, 55),)) options = RoutingOptions( search=SearchOptions(node_limit=32, min_straight_length=2, bend_radii=(10,), sbend_radii=()), - objective=ObjectiveWeights(price, 0, 0, 0), + diagnostics=DiagnosticsOptions(capture_expanded=True), 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) + small = route(problem, options=replace(options, objective=ObjectiveWeights(0.001, 0, 0, 0))) + large = route(problem, options=replace(options, objective=ObjectiveWeights(1e12, 0, 0, 0))) - assert run.results_by_net["turn"].is_valid - assert run.metrics.nodes_expanded == 12 + assert small.results_by_net["turn"].is_valid + assert large.results_by_net["turn"].is_valid + assert small.results_by_net["turn"].as_seed() == large.results_by_net["turn"].as_seed() + assert small.expanded_nodes + assert small.expanded_nodes == large.expanded_nodes + assert small.metrics.nodes_expanded == large.metrics.nodes_expanded -@pytest.mark.parametrize(("heuristic", "price"), [(1.5, 1), (0, 1), (1.5, 0)]) -def test_partial_path_tracks_geometric_progress_without_cost_heuristic(heuristic, price) -> None: +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( @@ -1031,23 +642,14 @@ def test_partial_path_tracks_geometric_progress_without_cost_heuristic(heuristic assert run.results_by_net["across"].outcome == "partial" -@pytest.mark.parametrize(("mode", "node_limit", "coordinates"), [ - ("automatic", 20, (30, 20)), - ("off", 20, (30.4, 20.4)), - ("guide", 20, (101, 20)), - ("seed", 0, (30.4, 20.4)), -]) -def test_coincident_ports_are_reported_without_blocking_the_batch(mode, node_limit, coordinates) -> None: - x, y = coordinates - net = NetSpec("abutting", Port(round(x), round(y), 0), Port(x, y, 0)) +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)) - seeds = {net.net_id: PathSeed((Bend90Seed(41, "CCW"),))} - if not node_limit: - seeds[peer.net_id] = PathSeed((StraightSeed(60),)) + seeds = {net.net_id: PathSeed((Bend90Seed(41, "CCW"),)), peer.net_id: PathSeed((StraightSeed(60),))} problem = RoutingProblem((0, 0, 100, 100), (net, peer), initial_paths=seeds) options = RoutingOptions( - search=SearchOptions(node_limit=node_limit), - topology=TopologyOptions(mode=mode), + search=SearchOptions(node_limit=0), + topology=TopologyOptions(mode="seed"), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) callbacks = [] @@ -1062,186 +664,101 @@ def test_coincident_ports_are_reported_without_blocking_the_batch(mode, node_lim assert rejected.effective_net == net assert rejected.report.terminal_error == f"start and target ports {net.start.as_tuple()} coincide after grid snapping" assert run.results_by_net[peer.net_id].is_valid + assert callbacks assert all(results[net.net_id] == rejected for results in callbacks) assert next(trace.report for trace in run.conflict_trace[-1].nets if trace.net_id == net.net_id) == rejected.report - if run.automatic is not None: - assert run.automatic.max_routed == 1 -@pytest.mark.parametrize("mode", ["off", "automatic"]) -@pytest.mark.parametrize(("target_x", "blocked", "message"), [ - (302, False, "face extends outside the routing board"), - (280, True, "face violates keepout clearance"), - (300, False, None), -]) -def test_invalid_terminal_faces_are_reported_without_search(mode, target_x, blocked, message) -> None: +def test_invalid_terminal_faces_are_reported_without_search() -> None: nets = ( - NetSpec("bad", Port(10, 80, 0), Port(target_x, 80, 0)), - NetSpec("peer", Port(10, 120, 0), Port(80, 120, 0)), + NetSpec("outside", Port(10, 40, 0), Port(302, 40, 0)), + NetSpec("blocked", Port(10, 80, 0), Port(280, 80, 0)), + NetSpec("flush", Port(10, 120, 0), Port(300, 120, 0)), ) - keepouts = (box(275, 75, 285, 85),) if blocked else () - problem = RoutingProblem((0, 0, 300, 160), nets, keepouts) + problem = RoutingProblem((0, 0, 300, 160), nets, (box(275, 75, 285, 85),)) options = RoutingOptions( search=SearchOptions(node_limit=600, bend_radii=(20,)), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode=mode), ) run = route(problem, options=options) - bad = run.results_by_net["bad"] - assert run.results_by_net["peer"].is_valid - assert bad.is_valid == (message is None) + outside, blocked, flush = (run.results_by_net[net.net_id] for net in nets) + assert not outside.is_valid + assert outside.report.terminal_error == "target port (302, 40, 0) face extends outside the routing board" + assert not blocked.is_valid + assert blocked.report.terminal_error == "target port (280, 80, 0) face violates keepout clearance" + assert flush.is_valid + assert flush.report.terminal_error is None assert run.metrics.nodes_expanded < 10 - if message is None: - assert bad.report.terminal_error is None - else: - assert bad.report.terminal_error == f"target port {(target_x, 80, 0)} {message}" -def test_keepout_clearance_at_face_and_opposite_coincident_headings() -> None: - net = NetSpec("return", Port(50, 50, 0), Port(50, 50, 180)) - problem = RoutingProblem((0, 0, 100, 100), (net,), (box(30, 53, 70, 60),)) - options = RoutingOptions(search=SearchOptions(node_limit=0), topology=TopologyOptions(mode="off")) +def test_same_net_clearance_preserves_join_and_checks_separated_path() -> None: + folds = (("tight", 20, 2), ("clear", 60, 3)) + nets = tuple(NetSpec(name, Port(10, y, 0), Port(10, y + 2 * radius, 180)) for name, y, radius in folds) + seeds = { + name: PathSeed((StraightSeed(25), Bend90Seed(radius, "CCW"), Bend90Seed(radius, "CCW"), StraightSeed(25))) + for name, _, radius in folds + } + problem = RoutingProblem((0, 0, 100, 100), nets, initial_paths=seeds, self_clearance=4) + options = RoutingOptions(search=SearchOptions(node_limit=0, bend_radii=(2, 3))) - result = route(problem, options=options).results_by_net["return"] + spaced = route(problem, options=options).results_by_net + unspaced = route(replace(problem, self_clearance=0), options=options).results_by_net - assert result.report.terminal_error is None - assert result.outcome == "unroutable" + assert not spaced["tight"].is_valid + assert spaced["tight"].report.self_collision_count > 0 + assert spaced["clear"].is_valid + assert all(result.is_valid for result in unspaced.values()) -@pytest.mark.parametrize(("radius", "spacing", "valid"), [(2, 0, True), (2, 4, False), (3, 4, True)]) -def test_same_net_clearance_preserves_join_and_checks_separated_path(radius, spacing, valid) -> None: - net = NetSpec("fold", Port(10, 20, 0), Port(10, 20 + 2 * radius, 180)) - seed = PathSeed((StraightSeed(25), Bend90Seed(radius, "CCW"), Bend90Seed(radius, "CCW"), StraightSeed(25))) - problem = RoutingProblem((0, 0, 100, 50), (net,), initial_paths={"fold": seed}, self_clearance=spacing) - options = RoutingOptions(search=SearchOptions(node_limit=0, bend_radii=(radius,))) - - result = route(problem, options=options).results_by_net["fold"] - - assert result.is_valid is valid - if not valid: - assert result.report.self_collision_count > 0 - - -@pytest.mark.parametrize(("start_x", "y", "collides"), [(10, 22, True), (40, 22, True), (40, 23, False)]) -def test_zero_clearance_forbids_inter_net_contact_but_allows_keepout_edges(start_x, y, collides) -> None: +def test_zero_clearance_forbids_inter_net_contact_but_allows_keepout_edges() -> None: nets = ( NetSpec("first", Port(10, 20, 0), Port(40, 20, 0)), - NetSpec("second", Port(start_x, y, 0), Port(90, y, 0)), + NetSpec("touching", Port(40, 22, 0), Port(90, 22, 0)), + NetSpec("separate", Port(40, 25, 0), Port(90, 25, 0)), ) - seeds = {"first": PathSeed((StraightSeed(30),)), "second": PathSeed((StraightSeed(90 - start_x),))} + seeds = {net.net_id: PathSeed((StraightSeed(net.target.x - net.start.x),)) for net in nets} problem = RoutingProblem((0, 0, 100, 50), nets, (box(10, 15, 40, 19),), initial_paths=seeds, clearance=0) results = route(problem, options=RoutingOptions(search=SearchOptions(node_limit=0))).results_by_net - assert [result.report.static_collision_count for result in results.values()] == [0, 0] - assert [result.report.dynamic_collision_count for result in results.values()] == [int(collides), int(collides)] + assert all(result.report.static_collision_count == 0 for result in results.values()) + assert results["first"].report.dynamic_collision_count == 1 + assert results["touching"].report.dynamic_collision_count == 1 + assert results["separate"].is_valid -def test_automatic_residual_cannot_touch_a_locked_distinct_net_at_zero_clearance() -> None: - nets = ( - NetSpec("first", Port(10, 20, 0), Port(80, 20, 0)), - NetSpec("second", Port(10, 22, 0), Port(80, 22, 0)), - ) - problem = RoutingProblem((0, 0, 100, 50), nets, clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=()), - refinement=RefinementOptions(enabled=False), - ) - - results = route(problem, options=options).results_by_net - - assert sum(result.is_valid for result in results.values()) == 1 - - -def test_zero_clearance_search_counts_physical_congestion_work() -> None: - nets = ( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0)), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90)), - ) - problem = RoutingProblem((0, 0, 100, 100), nets, clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=20, bend_radii=(), sbend_radii=()), - objective=ObjectiveWeights(danger_weight=0), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - diagnostics=DiagnosticsOptions(capture_iteration_trace=True), - ) - - run = route(problem, options=options) - - assert run.metrics.congestion_check_calls >= 2 - assert run.metrics.congestion_candidate_ids >= run.metrics.congestion_exact_pair_checks > 0 - assert run.iteration_trace[0].congestion_check_calls == run.metrics.congestion_check_calls - assert run.iteration_trace[0].congestion_exact_pair_checks == run.metrics.congestion_exact_pair_checks - - -@pytest.mark.parametrize("mode", ["off", "automatic"]) -@pytest.mark.parametrize("node_limit", [0, 10]) -@pytest.mark.parametrize("move", [Bend90Seed(1e11, "CCW"), SBendSeed(1e11, 1e11)]) -def test_unsafe_seed_reports_segment_without_allocating_geometry(monkeypatch, mode, node_limit, move) -> None: +def test_unsafe_seeds_report_segments_without_allocating_geometry(monkeypatch: pytest.MonkeyPatch) -> None: def unexpected_tessellation(*_args, **_kwargs): pytest.fail("Oversized seed reached the tessellator") monkeypatch.setattr(components_module, "_get_arc_polygons", unexpected_tessellation) monkeypatch.setattr(SBend, "_arcs", unexpected_tessellation) - net = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) - problem = RoutingProblem((0, 0, 100, 50), (net,), initial_paths={net.net_id: PathSeed((move,))}) + nets = ( + NetSpec("turn", Port(10, 20, 0), Port(90, 20, 0)), + NetSpec("shift", Port(10, 40, 0), Port(90, 40, 0)), + ) + moves = {"turn": Bend90Seed(1e11, "CCW"), "shift": SBendSeed(1e11, 1e11)} + problem = RoutingProblem( + (0, 0, 100, 60), nets, initial_paths={net_id: PathSeed((move,)) for net_id, move in moves.items()}, + ) options = RoutingOptions( - search=SearchOptions(node_limit=node_limit, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1e11,)), - topology=TopologyOptions(mode=mode), + search=SearchOptions(node_limit=0, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1e11,)), refinement=RefinementOptions(enabled=False), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) run = route(problem, options=options) - result = run.results_by_net[net.net_id] - - assert result.is_valid is bool(node_limit) - assert result.report.seed_error == ( - f"Initial path for 'track' segment 1 ({type(move).__name__}) exceeds 250,000 subdivisions for one circular arc" - ) - assert run.conflict_trace[-1].nets[0].report.seed_error == result.report.seed_error - - -def test_search_rejects_out_of_board_bends_before_tessellation(monkeypatch) -> None: - def unexpected_tessellation(*_args, **_kwargs): - pytest.fail("Search tessellated a bend with an endpoint outside the board") - - monkeypatch.setattr(components_module, "_get_num_segments", unexpected_tessellation) - problem = RoutingProblem((0, 0, 100, 50), (NetSpec("straight", Port(10, 20, 0), Port(90, 20, 0)),)) - options = RoutingOptions( - search=SearchOptions(node_limit=10, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1,), visibility_guidance="off"), - objective=ObjectiveWeights(danger_weight=0), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - assert route(problem, options=options).results_by_net["straight"].is_valid - - -@pytest.mark.parametrize(("second_x", "y", "valid"), [(53, 25, True), (52, 25, False), (50, 26, True)]) -def test_guide_admits_moves_using_physical_inter_net_clearance(second_x, y, valid) -> None: - nets = ( - NetSpec("first", Port(10, 20, 0), Port(50, 20, 0)), - NetSpec("second", Port(second_x, y, 0), Port(90, y, 0)), - ) - problem = RoutingProblem((0, 0, 100, 50), nets, clearance=4) - options = RoutingOptions( - search=SearchOptions(node_limit=50, bend_radii=(), sbend_radii=(), visibility_guidance="off"), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="guide"), - ) - - results = route(problem, options=options).results_by_net - - assert results["first"].is_valid - assert results["second"].is_valid is valid + traced = {net.net_id: net.report for net in run.conflict_trace[-1].nets} + for net_id, move in moves.items(): + result = run.results_by_net[net_id] + assert not result.is_valid + assert result.report.seed_error == ( + f"Initial path for {net_id!r} segment 1 ({type(move).__name__}) exceeds 250,000 subdivisions for one circular arc" + ) + assert traced[net_id].seed_error == result.report.seed_error def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(monkeypatch) -> None: @@ -1257,28 +774,8 @@ def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(mon assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback" -def test_automatic_final_conflict_trace_includes_direct_locks() -> None: - problem = RoutingProblem( - (0, 0, 100, 100), - ( - NetSpec("direct", Port(10, 25, 0), Port(90, 25, 0)), - NetSpec("turn", Port(10, 65, 0), Port(30, 85, 90)), - ), - ) - options = RoutingOptions(diagnostics=DiagnosticsOptions(capture_conflict_trace=True)) - - run = route(problem, options=options) - - assert run.automatic is not None - assert "direct" in run.automatic.stages[run.automatic.selected_stage].direct_net_ids - final = run.conflict_trace[-1] - assert final.stage == "final" - assert final.completed_net_ids == run.automatic.verified_net_ids == ("direct",) - assert {net.net_id: net.report for net in final.nets} == {net_id: result.report for net_id, result in run.results_by_net.items()} - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_routes_report_boundary_violations_in_results_and_diagnostics(mode) -> None: +def test_routes_report_boundary_violations_in_results_and_diagnostics() -> None: + mode = 'automatic' problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( @@ -1318,105 +815,29 @@ def test_routes_report_boundary_violations_in_results_and_diagnostics(mode) -> N assert traced_edge.report == edge.report -def test_lattice_search_detours_inside_board() -> None: - problem = RoutingProblem( - (0, 0, 120, 100), - nets=(NetSpec("detour", Port(10, 20, 0), Port(110, 20, 0)),), - static_obstacles=(box(43, 3, 73, 45),), - clearance=0, +def test_lattice_straight_uses_flat_port_faces_for_clearance() -> None: + nets = ( + NetSpec("touching", Port(10, 20, 0), Port(30, 20, 0)), + NetSpec("blocked", Port(10, 45, 0), Port(30, 45, 0)), ) - options = RoutingOptions( - search=SearchOptions(bend_radii=(5,), sbend_radii=(), node_limit=1000), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net["detour"] - - assert result.is_valid - board = box(*problem.bounds) - assert all(board.covers(polygon) for polygon in result.locked_geometry) - - -@pytest.mark.parametrize("y", [1, 2, 50]) -@pytest.mark.parametrize(("gap", "valid"), [(0.1, True), (0.099, False)]) -def test_lattice_straight_can_run_along_a_keepout_at_clearance(y, gap, valid) -> None: - problem = RoutingProblem( - (0, 0, 100, 100), - nets=(NetSpec("straight", Port(10, y, 0), Port(30, y, 0), width=0.9),), - static_obstacles=(box(15, y + 0.45 + gap, 25, y + 1),), - clearance=0.1, - ) - options = RoutingOptions( - search=SearchOptions(bend_radii=(), sbend_radii=(), node_limit=100), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - assert route(problem, options=options).results_by_net["straight"].is_valid is valid - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed"]) -@pytest.mark.parametrize( - ("obstacle", "valid"), - [(box(32, 16, 36, 24), True), (box(4, 16, 8, 24), True), (box(31.9, 16, 36, 24), False)], -) -def test_lattice_straight_uses_flat_port_faces_for_clearance(mode, obstacle, valid) -> None: - net = NetSpec("line", Port(10, 20, 0), Port(30, 20, 0)) - problem = RoutingProblem((0, 0, 60, 60), (net,), (obstacle,), clearance=2) + obstacles = (box(32, 16, 36, 24), box(31.9, 41, 36, 49)) + problem = RoutingProblem((0, 0, 60, 60), nets, obstacles, clearance=2) options = RoutingOptions( search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=()), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode=mode), - ) - - assert route(problem, options=options).results_by_net["line"].is_valid is valid - - -@pytest.mark.parametrize("min_length", [0, 0.5, 5]) -def test_lattice_can_launch_a_straight_before_a_bend_from_flat_port_face(min_length) -> None: - net = NetSpec("turn", Port(10, 20, 0), Port(50, 30, 90)) - problem = RoutingProblem((0, 15, 60, 32), (net,), (box(4, 16, 8, 24),), clearance=2) - options = RoutingOptions( - search=SearchOptions(node_limit=100, min_straight_length=min_length, bend_radii=(10,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="off"), ) - result = route(problem, options=options).results_by_net["turn"] - - assert result.is_valid - assert result.as_seed() == PathSeed((StraightSeed(30), Bend90Seed(10, "CCW"))) + results = route(problem, options=options).results_by_net + assert results["touching"].is_valid + assert not results["blocked"].is_valid -def test_lattice_partial_path_leaves_crossing_net_valid() -> None: +def test_invalid_seed_leaves_crossing_peer_valid() -> None: blocked = NetSpec("blocked", Port(10, 100, 0), Port(170, 100, 0)) through = NetSpec("through", Port(80, 40, 90), Port(80, 160, 90)) - problem = RoutingProblem((0, 0, 200, 200), (blocked, through), (box(125, 94, 145, 106),)) - options = RoutingOptions( - search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=()), - congestion=CongestionOptions(max_iterations=3, warm_start_enabled=False), - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - partial, complete = run.results_by_net["blocked"], run.results_by_net["through"] - - assert partial.outcome == "partial" - assert partial.locked_geometry[0].intersects(complete.locked_geometry[0]) - assert complete.is_valid - assert all(entry.conflict_edges == () for entry in run.conflict_trace) - - -@pytest.mark.parametrize("reverse", [False, True]) -def test_invalid_seed_leaves_crossing_peer_valid(reverse) -> None: - blocked = NetSpec("blocked", Port(10, 100, 0), Port(170, 100, 0)) - through = NetSpec("through", Port(80, 40, 90), Port(80, 160, 90)) - nets = (through, blocked) if reverse else (blocked, through) seeds = {"blocked": PathSeed((StraightSeed(160),)), "through": PathSeed((StraightSeed(120),))} - problem = RoutingProblem((0, 0, 200, 200), nets, (box(125, 94, 145, 106),), initial_paths=seeds) + problem = RoutingProblem((0, 0, 200, 200), (blocked, through), (box(125, 94, 145, 106),), initial_paths=seeds) options = RoutingOptions( search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=1), @@ -1431,52 +852,6 @@ def test_invalid_seed_leaves_crossing_peer_valid(reverse) -> None: assert all(entry.conflict_edges == () for entry in run.conflict_trace) -def test_lattice_can_chain_straights_before_a_bend_under_scan_limit() -> None: - net = NetSpec("lead", Port(10, 20, 0), Port(80, 30, 90)) - problem = RoutingProblem((0, 15, 95, 32), (net,)) - options = RoutingOptions( - search=SearchOptions(node_limit=100, max_straight_length=10, bend_radii=(10,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net["lead"] - - assert result.is_valid - assert result.as_seed() == PathSeed((*(StraightSeed(10),) * 6, Bend90Seed(10, "CCW"))) - - -def test_lattice_can_turn_away_from_a_distant_target_to_leave_a_keepout() -> None: - net = NetSpec("detour", Port(300, 100, 0), Port(360, 350, 0)) - problem = RoutingProblem((0, 0, 450, 400), (net,), (box(319, 96, 390, 170),)) - options = RoutingOptions( - search=SearchOptions(node_limit=100, bend_radii=(20,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net["detour"] - - assert result.is_valid - assert result.as_seed().segments[0] == Bend90Seed(20, "CW") - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) -def test_search_can_find_consecutive_sbends(mode) -> None: - net = NetSpec("double", Port(20, 20, 0), Port(48, 30, 0)) - problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=(10,), sbend_offsets=(5,)), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode=mode), - ) - - result = route(problem, options=options).results_by_net["double"] - - assert result.is_valid - assert result.as_seed() == PathSeed((SBendSeed(5, 10), SBendSeed(5, 10))) - - def test_congestion_retry_includes_keepout_collision_alongside_peer_conflicts() -> None: static = NetSpec("static", Port(20, 40, 0), Port(230, 40, 0)) horizontal = NetSpec("horizontal", Port(20, 150, 0), Port(230, 150, 0)) @@ -1505,52 +880,6 @@ def test_congestion_retry_includes_keepout_collision_alongside_peer_conflicts() assert run.results_by_net["static"].report.static_collision_count == 1 -def test_close_net_widths_use_distinct_keepout_trees() -> None: - narrow = NetSpec("narrow", Port(10, 20, 0), Port(90, 20, 0), width=2.00001) - wide = NetSpec("wide", Port(10, 60, 0), Port(90, 60, 0), width=2.00004) - problem = RoutingProblem((0, 0, 100, 100), (narrow, wide), (box(28, 21.00001, 75, 31),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - for candidate in (problem, replace(problem, nets=(wide, narrow))): - run = route(candidate, options=options) - assert all(result.is_valid for result in run.results_by_net.values()) - assert run.metrics.static_net_tree_rebuilds == 2 - - -def test_lattice_can_find_a_bend_with_diagonal_clearance_at_its_port() -> None: - net = NetSpec("turn", Port(20, 20, 0), Port(30, 30, 90)) - problem = RoutingProblem((0, 0, 100, 100), (net,), (box(16, 14, 19.25, 17.125),), clearance=2) - options = RoutingOptions( - search=SearchOptions(node_limit=100, bend_radii=(10,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net["turn"] - - assert result.is_valid - assert result.as_seed() == PathSeed((Bend90Seed(10, "CCW"),)) - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_fractional_quarter_turn_reaches_its_terminal_face(mode) -> None: - problem = RoutingProblem((0, 0, 100, 100), nets=(NetSpec("bend", Port(20, 20, 0), Port(31, 31, 90)),)) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10.25,), sbend_radii=(), node_limit=100), - congestion=CongestionOptions(max_iterations=1), - topology=TopologyOptions(mode=mode), - ) - - result = route(problem, options=options).results_by_net["bend"] - - assert result.is_valid - assert result.as_seed() == PathSeed((Bend90Seed(10.25, "CCW"),)) - - def test_first_lattice_pass_accepts_fractional_turn_with_keepout_inside_its_bounding_box() -> None: problem = RoutingProblem( (0, 0, 100, 100), @@ -1571,33 +900,21 @@ def test_first_lattice_pass_accepts_fractional_turn_with_keepout_inside_its_boun assert result.as_seed() == PathSeed((Bend90Seed(10.25, "CCW"),)) -@pytest.mark.parametrize("mode", ["automatic", "off"]) -@pytest.mark.parametrize("proxy", ["clipped_bbox", "custom"]) -def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None: - if proxy == "clipped_bbox": - nets = ( - NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)), - NetSpec("b", Port(41, 54, 0), Port(51, 44, 270)), - ) - seeds = {"a": PathSeed((Bend90Seed(10, "CCW"),)), "b": PathSeed((Bend90Seed(10, "CW"),))} - problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths=seeds) - search = SearchOptions(node_limit=100, bend_radii=(10,), bend_collision_type="clipped_bbox", bend_clip_margin=4) - else: - nets = ( - NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)), - NetSpec("b", Port(50, 65, 0), Port(60, 75, 90)), - ) - seed = PathSeed((Bend90Seed(10, "CCW"),)) - problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths={net.net_id: seed for net in nets}) - bend_proxy = box(0, -11, 11, 0) - outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - physical_bend = outline.union(box(10, -8, 13, -6)).union(box(12, -8, 14, 9)) - search = SearchOptions(node_limit=20, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend) +def test_route_verification_detects_physical_bend_overlap() -> None: + nets = ( + NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)), + NetSpec("b", Port(50, 65, 0), Port(60, 75, 90)), + ) + seed = PathSeed((Bend90Seed(10, "CCW"),)) + problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths={net.net_id: seed for net in nets}) + bend_proxy = box(0, -11, 11, 0) + outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) + physical_bend = outline.union(box(10, -8, 13, -6)).union(box(12, -8, 14, 9)) options = RoutingOptions( - search=replace(search, node_limit=0), + search=SearchOptions(node_limit=0, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend), congestion=CongestionOptions(max_iterations=1), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - topology=TopologyOptions(mode=mode), + topology=TopologyOptions(mode="off"), ) run = route(problem, options=options) @@ -1608,12 +925,18 @@ def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None: for result in (left, right): assert result.outcome == "colliding" assert result.report.dynamic_collision_count == 1 - if run.automatic is not None: - assert run.automatic.verified_net_ids == () assert run.conflict_trace[-1].conflict_edges == (("a", "b"),) -@pytest.mark.parametrize("node_limit", [40, 500, 700, None], ids=["tight", "initial", "higher", "default"]) +@pytest.mark.parametrize( + 'node_limit', + [ + 40, + 500, + 700, + ], + ids=['tight', 'initial', 'higher'], +) def test_default_router_escalates_only_within_the_configured_node_limit(monkeypatch, node_limit) -> None: problem = RoutingProblem((0, 0, 200, 200), (NetSpec("turn", Port(20, 20, 0), Port(180, 160, 90)),)) route_astar = router_module.route_astar @@ -1639,279 +962,7 @@ def test_default_router_escalates_only_within_the_configured_node_limit(monkeypa assert run.results_by_net["turn"].is_valid == (ceiling > 500) -def test_default_router_uses_lattice_when_triangulation_is_unavailable(monkeypatch) -> None: - problem = RoutingProblem((0, 0, 200, 200), (NetSpec("turn", Port(20, 20, 0), Port(180, 160, 90)),)) - monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) - - run = route(problem) - - assert run.automatic is not None - assert run.automatic.selected_planner == "lattice" - assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback" - assert run.automatic.verified_net_ids == ("turn",) - - -def test_route_problem_supports_configs_and_debug_data() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net1", Port(10, 10, 0), Port(90, 90, 0), width=2.0),), - static_obstacles=(box(40, 0, 60, 70),), - ) - options = RoutingOptions( - search=SearchOptions( - bend_radii=(10.0,), - node_limit=50000, - greedy_h_weight=1.2, - ), - objective=ObjectiveWeights( - bend_penalty=50.0, - sbend_penalty=150.0, - ), - congestion=CongestionOptions(warm_start_enabled=False), - refinement=RefinementOptions(enabled=True), - diagnostics=DiagnosticsOptions(capture_expanded=True), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - - assert run.results_by_net["net1"].reached_target - assert run.expanded_nodes - assert run.metrics.nodes_expanded > 0 - assert run.metrics.route_iterations >= 1 - assert run.metrics.iteration_reverify_calls >= 1 - assert run.metrics.iteration_reverified_nets >= 0 - assert run.metrics.iteration_conflicting_nets >= 0 - assert run.metrics.iteration_conflict_edges >= 0 - assert run.metrics.nets_carried_forward >= 0 - assert run.metrics.nets_routed >= 1 - assert run.metrics.move_cache_abs_misses >= 0 - assert run.metrics.ray_cast_calls >= 0 - assert run.metrics.dynamic_tree_rebuilds >= 0 - assert run.metrics.visibility_corner_index_builds >= 0 - assert run.metrics.visibility_builds >= 0 - assert run.metrics.guidance_match_moves >= 0 - assert run.metrics.guidance_match_moves_straight >= 0 - assert run.metrics.guidance_match_moves_bend90 >= 0 - assert run.metrics.guidance_match_moves_sbend >= 0 - assert run.metrics.guidance_bonus_applied >= 0.0 - assert run.metrics.guidance_bonus_applied_straight >= 0.0 - assert run.metrics.guidance_bonus_applied_bend90 >= 0.0 - assert run.metrics.guidance_bonus_applied_sbend >= 0.0 - assert run.metrics.congestion_grid_span_cache_hits >= 0 - assert run.metrics.congestion_grid_span_cache_misses >= 0 - assert run.metrics.congestion_presence_cache_hits >= 0 - assert run.metrics.congestion_presence_cache_misses >= 0 - assert run.metrics.congestion_presence_skips >= 0 - assert run.metrics.congestion_candidate_precheck_hits >= 0 - assert run.metrics.congestion_candidate_precheck_misses >= 0 - assert run.metrics.congestion_candidate_precheck_skips >= 0 - assert run.metrics.congestion_candidate_nets >= 0 - assert run.metrics.congestion_net_envelope_cache_hits >= 0 - assert run.metrics.congestion_net_envelope_cache_misses >= 0 - assert run.metrics.congestion_grid_net_cache_hits >= 0 - assert run.metrics.congestion_grid_net_cache_misses >= 0 - assert run.metrics.congestion_lazy_resolutions >= 0 - assert run.metrics.congestion_lazy_requeues >= 0 - assert run.metrics.congestion_candidate_ids >= 0 - assert run.metrics.verify_dynamic_candidate_nets >= 0 - assert run.metrics.verify_path_report_calls >= 0 - assert run.metrics.pair_local_search_pairs_considered >= 0 - assert run.metrics.pair_local_search_attempts >= 0 - assert run.metrics.pair_local_search_accepts >= 0 - assert run.metrics.pair_local_search_nodes_expanded >= 0 - assert run.metrics.late_phase_capped_nets >= 0 - assert run.metrics.late_phase_capped_fallbacks >= 0 - - -def test_iteration_callback_observes_reverified_conflicts() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - snapshots: list[dict[str, str]] = [] - - def callback(iteration: int, current_results: dict[str, object]) -> None: - _ = iteration - snapshots.append({net_id: result.outcome for net_id, result in current_results.items()}) - - results = pathfinder.route_all(iteration_callback=callback) - - assert snapshots == [{"horizontal": "colliding", "vertical": "colliding"}] - assert results["horizontal"].outcome == "colliding" - assert results["vertical"].outcome == "colliding" - - -@pytest.mark.parametrize("mutate_results", [False, True]) -def test_installed_best_iteration_isolated_from_callback_edits(mutate_results: bool) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net", Port(10, 50, 0), Port(90, 50, 0)),), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - world = RoutingWorld(clearance=problem.clearance) - finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options)) - - def callback(_iteration, results): - assert results["net"].is_valid - wrong_path = (Straight.generate(Port(10, 75, 0), 80, 2.0),) - results["net"] = RoutingResult("net", wrong_path, reached_target=True) - - results = finder.route_all(iteration_callback=callback if mutate_results else None) - - assert results["net"].is_valid - assert results["net"].path[0].start_port == problem.nets[0].start - assert world.has_dynamic_paths() - assert finder.metrics.snapshot().dynamic_path_objects_added == 1 - assert finder.metrics.snapshot().dynamic_path_objects_removed == 0 - assert finder.metrics.snapshot().verify_path_report_calls == 3 - - -def test_capture_conflict_trace_preserves_route_outputs() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - base_options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run_without_trace = route(problem, options=base_options) - run_with_trace = route( - problem, - options=RoutingOptions( - congestion=base_options.congestion, - refinement=base_options.refinement, - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - ), - ) - - assert {net_id: result.outcome for net_id, result in run_without_trace.results_by_net.items()} == { - net_id: result.outcome for net_id, result in run_with_trace.results_by_net.items() - } - assert [entry.stage for entry in run_with_trace.conflict_trace] == ["iteration", "restored_best", "final"] - - -def test_capture_iteration_trace_preserves_route_outputs(monkeypatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - base_options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - def unexpected_attempt_trace(*_args, **_kwargs): - pytest.fail("Routing built an attempt trace with diagnostics disabled") - - with monkeypatch.context() as patch: - patch.setattr(router_module, "net_attempt_trace", unexpected_attempt_trace) - run_without_trace = route(problem, options=base_options) - run_with_trace = route( - problem, - options=RoutingOptions( - congestion=base_options.congestion, - refinement=base_options.refinement, - diagnostics=DiagnosticsOptions(capture_iteration_trace=True), - ), - ) - - assert {net_id: result.outcome for net_id, result in run_without_trace.results_by_net.items()} == { - net_id: result.outcome for net_id, result in run_with_trace.results_by_net.items() - } - assert len(run_with_trace.iteration_trace) == 1 - - -def test_capture_iteration_trace_records_iteration_and_attempt_deltas() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - run = route( - problem, - options=RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - diagnostics=DiagnosticsOptions(capture_iteration_trace=True), - topology=TopologyOptions(mode="off"), - ), - ) - - entry = run.iteration_trace[0] - assert entry.iteration == 0 - assert entry.congestion_penalty == 100.0 - assert entry.routed_net_ids == ("horizontal", "vertical") - assert entry.completed_nets == 0 - assert entry.conflict_edges == 1 - assert entry.total_dynamic_collisions >= 2 - assert entry.nodes_expanded >= 0 - assert entry.congestion_check_calls >= 0 - assert entry.congestion_candidate_ids >= 0 - assert entry.congestion_exact_pair_checks >= 0 - assert len(entry.net_attempts) == 2 - assert [attempt.net_id for attempt in entry.net_attempts] == ["horizontal", "vertical"] - assert all(attempt.nodes_expanded >= 0 for attempt in entry.net_attempts) - assert all(attempt.congestion_check_calls >= 0 for attempt in entry.net_attempts) - assert all(not attempt.guidance_seed_present for attempt in entry.net_attempts) - assert sum(attempt.nodes_expanded for attempt in entry.net_attempts) == entry.nodes_expanded - assert sum(attempt.congestion_check_calls for attempt in entry.net_attempts) == entry.congestion_check_calls - - -def test_capture_conflict_trace_records_component_pairs() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - final_entry = run.conflict_trace[-1] - trace_by_net = {net.net_id: net for net in final_entry.nets} - - assert final_entry.stage == "final" - assert final_entry.conflict_edges == (("horizontal", "vertical"),) - assert trace_by_net["horizontal"].component_conflicts[0].other_net_id == "vertical" - assert trace_by_net["horizontal"].component_conflicts[0].self_component_index == 0 - assert trace_by_net["horizontal"].component_conflicts[0].other_component_index == 0 - assert trace_by_net["vertical"].component_conflicts[0].other_net_id == "horizontal" - assert trace_by_net["vertical"].component_conflicts[0].self_component_index == 0 - assert trace_by_net["vertical"].component_conflicts[0].other_component_index == 0 - - -@pytest.mark.parametrize("replay", [False, True]) -def test_capture_frontier_trace_preserves_route_outputs(replay) -> None: +def test_capture_frontier_trace_preserves_route_outputs() -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( @@ -1919,105 +970,24 @@ def test_capture_frontier_trace_preserves_route_outputs(replay) -> None: NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), ), ) + problem = replace(problem, initial_paths={net.net_id: PathSeed((StraightSeed(80),)) for net in problem.nets}) base_options = RoutingOptions( + search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) - if replay: - problem = replace(problem, initial_paths={net.net_id: PathSeed((StraightSeed(80),)) for net in problem.nets}) - base_options = replace(base_options, search=replace(base_options.search, node_limit=0)) - run_without_trace = route(problem, options=base_options) run_with_trace = route( problem, options=replace(base_options, diagnostics=DiagnosticsOptions(capture_frontier_trace=True)), ) - assert {net_id: result.outcome for net_id, result in run_without_trace.results_by_net.items()} == { - net_id: result.outcome for net_id, result in run_with_trace.results_by_net.items() - } + assert run_without_trace.results_by_net == run_with_trace.results_by_net assert {trace.net_id for trace in run_with_trace.frontier_trace} == {"horizontal", "vertical"} assert run_with_trace.metrics.verify_path_report_calls == run_without_trace.metrics.verify_path_report_calls -def test_capture_pre_pair_frontier_trace_preserves_route_outputs() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - base_options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run_without_trace = route(problem, options=base_options) - run_with_trace = route( - problem, - options=RoutingOptions( - congestion=base_options.congestion, - refinement=base_options.refinement, - diagnostics=DiagnosticsOptions(capture_pre_pair_frontier_trace=True), - ), - ) - - assert {net_id: result.outcome for net_id, result in run_without_trace.results_by_net.items()} == { - net_id: result.outcome for net_id, result in run_with_trace.results_by_net.items() - } - assert run_with_trace.pre_pair_frontier_trace is None - - -def test_capture_frontier_trace_records_prune_reasons() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - run = route( - problem, - options=RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - diagnostics=DiagnosticsOptions(capture_frontier_trace=True), - topology=TopologyOptions(mode="off"), - ), - ) - - trace_by_net = {entry.net_id: entry for entry in run.frontier_trace} - assert trace_by_net["horizontal"].hotspot_bounds - assert ( - trace_by_net["horizontal"].pruned_closed_set - + trace_by_net["horizontal"].pruned_hard_collision - + trace_by_net["horizontal"].pruned_self_collision - + trace_by_net["horizontal"].pruned_cost - ) > 0 - assert trace_by_net["horizontal"].samples - - -def test_reverify_iterations_stop_early_on_stalled_conflict_graph() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=10, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - - assert run.metrics.route_iterations < 10 - - def test_reverify_iterations_limit_late_reroutes_to_conflicting_nets(monkeypatch: pytest.MonkeyPatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), @@ -2111,264 +1081,7 @@ def test_routing_attempts_reserve_an_index_for_a_timed_out_worker(monkeypatch) - assert [entry.iteration for entry in selected.conflict_trace if entry.stage == "iteration"] == [1] -def test_run_iteration_orders_subset_reroutes_by_recent_work(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("netB", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - NetSpec("netC", Port(10, 20, 0), Port(90, 20, 0), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False, shuffle_nets=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - state = pathfinder._prepare_state() - state.recent_attempt_work = {"netA": 200, "netB": 20} - route_order: list[str] = [] - - def fake_route_net_once(self, state, iteration, net_id, *, node_limit_override=None, incumbent_fallback=None): - _ = state - _ = iteration - route_order.append(net_id) - self.metrics.reroute_work += 200 if net_id == "netA" else 20 - self.metrics.total_congestion_check_calls += 1000 if net_id == "netB" else 0 - assert node_limit_override is None - assert incumbent_fallback is None - return RoutingResult(net_id=net_id, path=(), reached_target=False), False - - def fake_reverify(self, state): - _ = self - _ = state - return _IterationReview( - conflicting_nets={"netA", "netB"}, - conflict_edges={("netA", "netB")}, - completed_net_ids=set(), - total_dynamic_collisions=2, - ) - - monkeypatch.setattr(PathFinder, "_route_net_once", fake_route_net_once) - monkeypatch.setattr(PathFinder, "_reverify_iteration_results", fake_reverify) - - review = pathfinder._run_iteration(state, 1, {"netA", "netB"}, None) - - assert review is not None - assert route_order == ["netB", "netA"] - assert state.recent_attempt_work == {"netA": 200, "netB": 20} - pathfinder._run_iteration(state, 2, {"netA", "netB"}, None) - assert route_order == ["netB", "netA", "netB", "netA"] - - -def test_run_iteration_caps_two_heaviest_late_phase_nets(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("netB", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - NetSpec("netC", Port(10, 20, 0), Port(90, 20, 0), width=2.0), - NetSpec("netD", Port(10, 80, 0), Port(90, 80, 0), width=2.0), - NetSpec("netE", Port(10, 65, 0), Port(90, 65, 0), width=2.0), - ), - ) - options = RoutingOptions( - objective=ObjectiveWeights(bend_penalty=100.0), - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False, shuffle_nets=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - state = pathfinder._prepare_state() - state.results = { - net_id: RoutingResult(net_id=net_id, path=(Straight.generate(spec.start, 80.0, 2.0, dilation=1.0),), reached_target=True) - for net_id, spec in state.net_specs.items() - } - state.best_review = _IterationReview({"netA", "netB", "netC", "netD"}, {("netA", "netB"), ("netC", "netD")}, {"netE"}, 4) - state.recent_attempt_work = {"netA": 20, "netB": 40, "netC": 400, "netD": 220} - incumbents = dict(state.results) - caps_by_net: dict[str, tuple[int | None, RoutingResult | None]] = {} - - def fake_route_net_once(self, state, iteration, net_id, *, node_limit_override=None, incumbent_fallback=None): - _ = self - _ = state - _ = iteration - caps_by_net[net_id] = (node_limit_override, incumbent_fallback) - return RoutingResult(net_id=net_id, path=(), reached_target=False), False - - def fake_reverify(self, state): - _ = self - _ = state - return _IterationReview( - conflicting_nets={"netA", "netB", "netC", "netD"}, - conflict_edges={("netA", "netB"), ("netC", "netD")}, - completed_net_ids=set(), - total_dynamic_collisions=2, - ) - - monkeypatch.setattr(PathFinder, "_route_net_once", fake_route_net_once) - monkeypatch.setattr(PathFinder, "_reverify_iteration_results", fake_reverify) - - review = pathfinder._run_iteration(state, 1, {"netA", "netB", "netC", "netD"}, None) - - assert review is not None - assert caps_by_net["netA"] == (None, None) - assert caps_by_net["netB"] == (None, None) - assert caps_by_net["netC"][0] == 1 - assert caps_by_net["netD"][0] == 1 - assert caps_by_net["netC"][1] is incumbents["netC"] - assert caps_by_net["netD"][1] is incumbents["netD"] - - -def test_route_net_once_skips_search_for_capped_incumbent_fallback(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), - ) - options = RoutingOptions( - objective=ObjectiveWeights(bend_penalty=100.0), - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - state = pathfinder._prepare_state() - incumbent = RoutingResult( - net_id="netA", - path=(Straight.generate(problem.nets[0].start, 80.0, 2.0, dilation=1.0),), - reached_target=True, - ) - state.results["netA"] = incumbent - installed: list[tuple[str, tuple[object, ...]]] = [] - - def fail_route_astar(*_args, **_kwargs): - raise AssertionError("route_astar should not run for capped incumbent fallback") - - def record_added_route(self, net_id, path): - _ = self - installed.append((net_id, tuple(path))) - - monkeypatch.setattr(router_module, "route_astar", fail_route_astar) - monkeypatch.setattr(PathFinder, "_add_route", record_added_route) - - result, guidance_seed_present = pathfinder._route_net_once( - state, - 1, - "netA", - node_limit_override=1, - incumbent_fallback=incumbent, - ) - - assert result is incumbent - assert guidance_seed_present is True - assert installed == [("netA", incumbent.path)] - assert pathfinder.metrics.total_late_phase_capped_nets == 1 - assert pathfinder.metrics.total_late_phase_capped_fallbacks == 1 - - -def test_route_all_restores_best_iteration_snapshot(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("netB", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - best_result = RoutingResult( - net_id="netA", - path=(Straight.generate(Port(10, 50, 0), 80.0, 2.0, dilation=1.0),), - reached_target=True, - report=RoutingReport(), - ) - missing_result = RoutingResult(net_id="netA", path=(), reached_target=False) - unroutable_b = RoutingResult(net_id="netB", path=(), reached_target=False) - - def fake_run_iteration(self, state, iteration, reroute_net_ids, iteration_callback): - _ = self - _ = reroute_net_ids - _ = iteration_callback - if iteration == 0: - state.results = {"netA": best_result, "netB": unroutable_b} - return _IterationReview( - conflicting_nets={"netA", "netB"}, - conflict_edges={("netA", "netB")}, - completed_net_ids={"netA"}, - total_dynamic_collisions=1, - ) - state.results = {"netA": missing_result, "netB": unroutable_b} - return _IterationReview( - conflicting_nets={"netA", "netB"}, - conflict_edges={("netA", "netB")}, - completed_net_ids=set(), - total_dynamic_collisions=2, - ) - - monkeypatch.setattr(PathFinder, "_run_iteration", fake_run_iteration) - monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: (dict(state.results), {})) - - results = pathfinder.route_all() - - assert results["netA"].outcome == "completed" - assert results["netB"].outcome == "unroutable" - assert evaluator.collision_engine.has_dynamic_paths() - assert pathfinder.metrics.snapshot().verify_path_report_calls == 1 - - -def test_first_iteration_and_pair_length_tie_break() -> None: - problem = RoutingProblem(bounds=(0, 0, 100, 100)) - options = RoutingOptions(congestion=CongestionOptions(warm_start_enabled=False), topology=TopologyOptions(mode="off")) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - finder = PathFinder(AStarContext(evaluator, problem, options)) - state = finder._prepare_state() - review = _IterationReview(set(), set(), set(), 0) - - assert finder._update_best_iteration(state, review) - assert not finder._update_best_iteration(state, review) - - def results(length): - return {"a": RoutingResult("a", (), reached_target=True, report=RoutingReport(total_length=length))} - - incumbent = results(10.0) - assert not finder._whole_set_is_better(results(10.0 - 0.5e-6), review, incumbent, review) - assert finder._whole_set_is_better(results(10.0 - 2e-6), review, incumbent, review) - - -def test_pair_repair_limits_disjoint_targets_in_routing_order(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=tuple(NetSpec(net_id, Port(10, i * 10, 0), Port(90, i * 10, 0)) for i, net_id in enumerate("cdbaef", 1)), - ) - options = RoutingOptions(congestion=CongestionOptions(warm_start_enabled=False), topology=TopologyOptions(mode="off")) - world = RoutingWorld(clearance=problem.clearance) - finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options)) - state = finder._prepare_state() - state.results = {net_id: RoutingResult(net_id, (), reached_target=True) for net_id in state.ordered_net_ids} - review = _IterationReview(set(state.ordered_net_ids), {("a", "b"), ("c", "d"), ("e", "f")}, set(), 6) - visited = [] - - def repair(_finder, _state, pair, current_review): - visited.append(pair) - return current_review - - monkeypatch.setattr(PathFinder, "_run_pair_local_target", repair) - finder._run_pair_local_search(state, review) - assert visited == [("c", "d"), ("a", "b")] - - visited.clear() - review.conflict_edges.add(("b", "c")) - finder._run_pair_local_search(state, review) - assert not visited - - -@pytest.mark.parametrize("candidate_reaches_live_check", [False, True]) -def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch: pytest.MonkeyPatch, candidate_reaches_live_check: bool) -> None: +def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=tuple(NetSpec(net_id, Port(10, y, 0), Port(90, y, 0)) for net_id, y in (("a", 20), ("b", 40), ("c", 60))), @@ -2389,7 +1102,7 @@ def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch: pyt def search(_context, _ordered, _results, pair_order, **_kwargs): attempted.append(pair_order) assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds - if candidate_reaches_live_check and pair_order == ("a", "b"): + if pair_order == ("a", "b"): return {"a": RoutingResult("a", incumbent["b"].path, reached_target=True), "b": incumbent["b"]}, 0 return None @@ -2401,8 +1114,8 @@ def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch: pyt assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds assert all(world.verify_path_report(net_id, result.path) == result.report for net_id, result in incumbent.items()) metrics = finder.metrics.snapshot() - assert metrics.dynamic_path_objects_added == 3 + 4 * candidate_reaches_live_check - assert metrics.dynamic_path_objects_removed == 4 * candidate_reaches_live_check + assert metrics.dynamic_path_objects_added == 7 + assert metrics.dynamic_path_objects_removed == 4 def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pytest.MonkeyPatch) -> None: @@ -2450,8 +1163,24 @@ def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pyte assert evaluator.collision_engine.has_dynamic_paths() +def test_iteration_prefers_shorter_paths_at_equal_coverage() -> None: + problem = RoutingProblem(bounds=(0, 0, 100, 100)) + options = RoutingOptions(topology=TopologyOptions(mode="off")) + world = RoutingWorld(clearance=problem.clearance) + finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options)) + review = _IterationReview(set(), set(), {"line"}, 0) + + def completed(length): + segment = Straight.generate(Port(10, 10, 0), length, 2.0) + return {"line": RoutingResult("line", (segment,), reached_target=True, report=RoutingReport(total_length=length))} + + incumbent = completed(20) + assert finder._whole_set_is_better(completed(10), review, incumbent, review) + assert not finder._whole_set_is_better(completed(20), review, incumbent, review) + + @pytest.mark.parametrize("during", ["preparation", "search"]) -def test_worker_checks_timeout_inside_single_net_attempt(during, monkeypatch) -> None: +def test_worker_checks_timeout_inside_single_net_attempt(monkeypatch, during) -> None: clock = [0.0] monkeypatch.setattr(router_module.time, "monotonic", lambda: clock[0]) problem = RoutingProblem((0, 0, 100, 100), (NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)),)) @@ -2482,74 +1211,6 @@ def test_worker_checks_timeout_inside_single_net_attempt(during, monkeypatch) -> assert not result.results_by_net["line"].is_valid -def test_capture_conflict_trace_records_restored_best_stage(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - best_result = RoutingResult( - net_id="netA", - path=(Straight.generate(Port(10, 50, 0), 80.0, 2.0, dilation=1.0),), - reached_target=True, - report=RoutingReport(), - ) - worse_result = RoutingResult(net_id="netA", path=(), reached_target=False) - - def fake_run_iteration(self, state, iteration, reroute_net_ids, iteration_callback): - _ = self - _ = reroute_net_ids - _ = iteration_callback - if iteration == 0: - state.results = {"netA": best_result} - return _IterationReview( - conflicting_nets=set(), - conflict_edges=set(), - completed_net_ids={"netA"}, - total_dynamic_collisions=0, - ) - state.results = {"netA": worse_result} - return _IterationReview( - conflicting_nets=set(), - conflict_edges=set(), - completed_net_ids=set(), - total_dynamic_collisions=0, - ) - - monkeypatch.setattr(PathFinder, "_run_iteration", fake_run_iteration) - - pathfinder.route_all() - - assert [entry.stage for entry in pathfinder.conflict_trace] == [ - "restored_best", - "final", - ] - restored_entry = pathfinder.conflict_trace[0] - assert restored_entry.nets[0].outcome == "completed" -def test_route_problem_locked_routes_become_static_obstacles() -> None: - locked = (Straight.generate(Port(10, 50, 0), 80.0, 2.0, dilation=1.0),) - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("crossing", Port(50, 10, 90), Port(50, 90, 90), width=2.0),), - static_obstacles=tuple(polygon for component in locked for polygon in component.physical_geometry), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - result = run.results_by_net["crossing"] - - assert not result.is_valid - - def test_locked_routes_enable_incremental_requests_without_sessions() -> None: problem_a = RoutingProblem( bounds=(0, -50, 100, 50), @@ -2569,25 +1230,17 @@ def test_locked_routes_enable_incremental_requests_without_sessions() -> None: assert results_b.results_by_net["netB"].is_valid -def test_route_problem_rejects_untyped_initial_paths() -> None: - with pytest.raises(TypeError): - RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net1", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), - initial_paths={"net1": (object(),)}, # type: ignore[dict-item] - ) - - -def test_route_results_metrics_are_snapshots() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net1", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), +def test_close_net_widths_use_distinct_keepout_trees() -> None: + narrow = NetSpec("narrow", Port(10, 20, 0), Port(90, 20, 0), width=2.00001) + wide = NetSpec("wide", Port(10, 60, 0), Port(90, 60, 0), width=2.00004) + problem = RoutingProblem((0, 0, 100, 100), (narrow, wide), (box(28, 21.00001, 75, 31),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=()), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode="off"), ) - options = RoutingOptions(topology=TopologyOptions(mode="off")) - run1 = route(problem, options=options) - first_metrics = run1.metrics - run2 = route(problem, options=options) - assert first_metrics == run1.metrics - assert run1.metrics is not run2.metrics - assert first_metrics.nodes_expanded > 0 + for candidate in (problem, replace(problem, nets=(wide, narrow))): + run = route(candidate, options=options) + assert all(result.is_valid for result in run.results_by_net.values()) + assert run.metrics.static_net_tree_rebuilds == 2 diff --git a/inire/tests/test_astar.py b/inire/tests/test_astar.py index 8a8af6b..78a2e43 100644 --- a/inire/tests/test_astar.py +++ b/inire/tests/test_astar.py @@ -2,23 +2,18 @@ import math import pytest from shapely.geometry import Polygon -from inire import CongestionOptions, NetSpec, ObjectiveWeights, RefinementOptions, RoutingProblem, RoutingOptions, RoutingResult, SearchOptions -from inire.geometry.components import Bend90, Straight +from inire import NetSpec, RoutingProblem, RoutingOptions, RoutingResult, SearchOptions +from inire.geometry.components import Straight from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port from inire.router import _astar_moves from inire.router._astar_types import AStarContext, AStarNode, CongestionCaches, SearchRunConfig from inire.router._astar_admission import add_node -from inire.router._astar_moves import ( - _distance_to_bounds_in_heading, - _should_cap_straights_to_bounds, -) from inire.router._pair_local import _build_pair_local_context from inire.router._search import route_astar from inire.router._stack import build_routing_stack from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap -from inire.seeds import StraightSeed BOUNDS = (0, -50, 150, 150) @@ -111,146 +106,6 @@ def _validate_routing_result( } -def test_astar_straight(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - start = Port(0, 0, 0) - target = Port(50, 0, 0) - path = _route(context, start, target) - - assert path is not None - result = RoutingResult(net_id="test", path=path, reached_target=True) - validation = _validate_routing_result(result, [], clearance=2.0, expected_start=start, expected_end=target) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - assert validation["connectivity_ok"] - # Path should be exactly 50um (or slightly more if it did weird things, but here it's straight) - assert abs(validation["total_length"] - 50.0) < 1e-6 - - -def test_astar_bend(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(10.0,)) - start = Port(0, 0, 0) - # 20um right, 20um up. Needs a 10um bend and a 10um bend. - target = Port(20, 20, 0) - path = _route(context, start, target) - - assert path is not None - result = RoutingResult(net_id="test", path=path, reached_target=True) - validation = _validate_routing_result(result, [], clearance=2.0, expected_start=start, expected_end=target) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - assert validation["connectivity_ok"] - - -def test_astar_obstacle(basic_evaluator: CostEvaluator) -> None: - # Add an obstacle in the middle of a straight path - # Obstacle from x=20 to 40, y=-20 to 20 - obstacle = Polygon([(20, -20), (40, -20), (40, 20), (20, 20)]) - basic_evaluator.collision_engine.add_static_obstacle(obstacle) - basic_evaluator.danger_map.precompute([obstacle]) - - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(10.0,), node_limit=1000000) - start = Port(0, 0, 0) - target = Port(60, 0, 0) - path = _route(context, start, target) - - assert path is not None - result = RoutingResult(net_id="test", path=path, reached_target=True) - validation = _validate_routing_result(result, [obstacle], clearance=2.0, expected_start=start, expected_end=target) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - # Path should have detoured, so length > 50 - assert validation["total_length"] > 50.0 - - -def test_astar_uses_integerized_ports(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - start = Port(0, 0, 0) - target = Port(10.1, 0, 0) - path = _route(context, start, target) - - assert path is not None - result = RoutingResult(net_id="test", path=path, reached_target=True) - assert target.x == 10 - validation = _validate_routing_result(result, [], clearance=2.0, expected_start=start, expected_end=target) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - - -def test_validate_routing_result_checks_expected_start() -> None: - path = [Straight.generate(Port(100, 0, 0), 10.0, width=2.0, dilation=1.0)] - result = RoutingResult(net_id="test", path=path, reached_target=True) - - validation = _validate_routing_result( - result, - [], - clearance=2.0, - expected_start=Port(0, 0, 0), - expected_end=Port(110, 0, 0), - ) - - assert not validation["is_valid"] - assert "Initial port position mismatch" in validation["reason"] - - -def test_validate_routing_result_uses_exact_component_geometry() -> None: - bend = Bend90.generate(Port(0, 0, 0), 10.0, 2.0, direction="CCW", collision_type="bbox", dilation=1.0) - result = RoutingResult(net_id="test", path=[bend], reached_target=True) - obstacle = Polygon([(2.0, 7.0), (4.0, 7.0), (4.0, 9.0), (2.0, 9.0)]) - - validation = _validate_routing_result( - result, - [obstacle], - clearance=2.0, - expected_start=Port(0, 0, 0), - expected_end=bend.end_port, - ) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - - -def test_astar_context_keeps_evaluator_weights_separate(basic_evaluator: CostEvaluator) -> None: - basic_evaluator = CostEvaluator( - basic_evaluator.collision_engine, - basic_evaluator.danger_map, - bend_penalty=120.0, - sbend_penalty=240.0, - ) - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(5.0,)) - - assert context.options.search.bend_radii == (5.0,) - assert basic_evaluator.h_manhattan(Port(0, 0, 0), Port(10, 10, 0)) > 0.0 - - -def test_distance_to_bounds_in_heading_is_directional() -> None: - bounds = (0, 0, 100, 200) - - assert _distance_to_bounds_in_heading(Port(20, 30, 0), bounds) == pytest.approx(80.0) - assert _distance_to_bounds_in_heading(Port(20, 30, 90), bounds) == pytest.approx(170.0) - assert _distance_to_bounds_in_heading(Port(20, 30, 180), bounds) == pytest.approx(20.0) - assert _distance_to_bounds_in_heading(Port(20, 30, 270), bounds) == pytest.approx(30.0) - - -def test_should_cap_straights_to_bounds_only_for_large_no_warm_runs(basic_evaluator: CostEvaluator) -> None: - large_context = AStarContext( - basic_evaluator, - RoutingProblem( - bounds=(0, 0, 1000, 1000), - nets=tuple( - NetSpec(f"net{i}", Port(0, i * 10, 0), Port(10, i * 10, 0), width=2.0) - for i in range(8) - ), - ), - RoutingOptions( - congestion=CongestionOptions(warm_start_enabled=False), - ), - ) - small_context = _build_context(basic_evaluator, bounds=BOUNDS) - - assert _should_cap_straights_to_bounds(large_context) - assert not _should_cap_straights_to_bounds(small_context) - - def test_equal_cost_arrivals_can_propose_different_straights(monkeypatch) -> None: start, target = Port(5, 20, 0), Port(35, 20, 0) problem = RoutingProblem((0, 0, 100, 50), (NetSpec("track", start, target),)) @@ -299,94 +154,7 @@ def test_pair_local_context_clones_live_static_obstacles() -> None: assert next(iter(local_context.problem.static_obstacles)).equals(obstacle) -@pytest.mark.parametrize( - ("search_danger", "refinement_enabled", "expected_tree"), - [(0.0, False, False), (0.0, True, True), (1.0, False, True)], -) -def test_worker_samples_proximity_only_for_objectives_it_uses(search_danger, refinement_enabled, expected_tree) -> None: - obstacle = Polygon([(20, -8), (40, -8), (40, -5), (20, -5)]) - net = NetSpec("pair_a", Port(10, 0, 0), Port(50, 0, 0)) - problem = RoutingProblem(bounds=BOUNDS, nets=(net,), static_obstacles=(obstacle,)) - options = RoutingOptions( - objective=ObjectiveWeights(danger_weight=search_danger), - refinement=RefinementOptions(enabled=refinement_enabled, objective=ObjectiveWeights(danger_weight=1.0)), - ) - stack = build_routing_stack(problem, options) - local = _build_pair_local_context(stack.context, problem.nets, {}, ("pair_a", "pair_b")) - - assert (stack.danger_map.tree is not None) == expected_tree - assert (local.cost_evaluator.danger_map.tree is not None) == bool(search_danger) - outside = Straight.generate(net.start, 200, net.width) - assert stack.evaluator.score_component(outside, start_port=net.start) == 1e15 - assert local.cost_evaluator.score_component(outside, start_port=net.start) == 1e15 - if refinement_enabled: - move = Straight.generate(net.start, 40, net.width) - assert stack.finder.refiner.score_path(net.start, (move,)) > stack.evaluator.score_component(move, start_port=net.start) - - -def test_route_astar_bend_collision_override_does_not_persist(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(10.0,), bend_collision_type="arc") - - route_astar( - Port(0, 0, 0), - Port(30, 10, 0), - net_width=2.0, - context=context, - config=SearchRunConfig.from_options( - context.options, - bend_collision_type="clipped_bbox", - return_partial=True, - ), - ) - - assert context.options.search.bend_collision_type == "arc" - - -def test_route_astar_returns_partial_path_when_node_limited(basic_evaluator: CostEvaluator) -> None: - obstacle = Polygon([(20, -20), (40, -20), (40, 20), (20, 20)]) - basic_evaluator.collision_engine.add_static_obstacle(obstacle) - basic_evaluator.danger_map.precompute([obstacle]) - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(10.0,), node_limit=2) - start = Port(0, 0, 0) - target = Port(60, 0, 0) - - partial_path = _route(context, start, target, return_partial=True) - no_partial_path = _route(context, start, target, return_partial=False) - - assert partial_path is not None - assert partial_path - assert partial_path[-1].end_port != target - assert no_partial_path is None - - -def test_route_astar_uses_single_sbend_for_same_orientation_offset(basic_evaluator: CostEvaluator) -> None: - context = _build_context( - basic_evaluator, - bounds=BOUNDS, - bend_radii=(10.0,), - sbend_radii=(10.0,), - sbend_offsets=(10.0,), - max_straight_length=150.0, - ) - start = Port(0, 0, 0) - target = Port(100, 10, 0) - - path = _route(context, start, target) - - assert path is not None - assert path[-1].end_port == target - assert sum(1 for component in path if component.move_type == "sbend") == 1 - assert not any( - first.move_type == second.move_type == "sbend" - for first, second in zip(path, path[1:], strict=False) - ) - - -@pytest.mark.parametrize("visibility_guidance", ["off", "exact_corner", "tangent_corner"]) -def test_route_astar_supports_all_visibility_guidance_modes( - basic_evaluator: CostEvaluator, - visibility_guidance: str, -) -> None: +def test_route_astar_supports_exact_corner_guidance(basic_evaluator: CostEvaluator) -> None: obstacle = Polygon([(30, 10), (50, 10), (50, 40), (30, 40)]) basic_evaluator.collision_engine.add_static_obstacle(obstacle) basic_evaluator.danger_map.precompute([obstacle]) @@ -396,7 +164,7 @@ def test_route_astar_supports_all_visibility_guidance_modes( bend_radii=(10.0,), sbend_radii=(), max_straight_length=150.0, - visibility_guidance=visibility_guidance, + visibility_guidance="exact_corner", ) start = Port(0, 0, 0) target = Port(80, 50, 0) @@ -411,27 +179,6 @@ def test_route_astar_supports_all_visibility_guidance_modes( assert validation["connectivity_ok"] -def test_tangent_corner_mode_uses_only_tangent_queries(basic_evaluator: CostEvaluator) -> None: - obstacle = Polygon([(30, 10), (50, 10), (50, 40), (30, 40)]) - basic_evaluator.collision_engine.add_static_obstacle(obstacle) - basic_evaluator.danger_map.precompute([obstacle]) - context = _build_context( - basic_evaluator, - bounds=BOUNDS, - bend_radii=(10.0,), - sbend_radii=(), - max_straight_length=150.0, - visibility_guidance="tangent_corner", - ) - - path = _route(context, Port(0, 0, 0), Port(80, 50, 0)) - - assert path is not None - assert context.metrics.total_visibility_tangent_candidate_scans > 0 - assert context.metrics.total_visibility_corner_queries_exact == 0 - assert context.metrics.total_visibility_point_queries == 0 - - def test_route_astar_repeated_searches_succeed_with_small_cache_limit(basic_evaluator: CostEvaluator) -> None: context = AStarContext( basic_evaluator, @@ -509,9 +256,8 @@ def test_closed_set_dominance_prunes_before_congestion_check(basic_evaluator: Co assert context.metrics.total_congestion_cache_misses == 0 -@pytest.mark.parametrize(("length_weight", "guidance_bonus", "expected_cost"), [(0.1, 0, 1), (1, 8, 2)]) -def test_closed_set_keeps_cheaper_weighted_or_guided_move(length_weight, guidance_bonus, expected_cost) -> None: - evaluator = CostEvaluator(RoutingWorld(clearance=0), unit_length_cost=length_weight) +def test_closed_set_keeps_cheaper_guided_move() -> None: + evaluator = CostEvaluator(RoutingWorld(clearance=0), unit_length_cost=1) context = _build_context(evaluator, bounds=BOUNDS) root = AStarNode(Port(0, 0, 0), 0.0, 0.0, seed_index=0) move = Straight.generate(root.port, 10, width=2.0) @@ -528,154 +274,12 @@ def test_closed_set_keeps_cheaper_weighted_or_guided_move(length_weight, guidanc metrics=context.metrics, congestion=CongestionCaches(), config=SearchRunConfig.from_options( - context.options, guidance_seed=(move.move_spec,) if guidance_bonus else None, guidance_bonus=guidance_bonus, + context.options, guidance_seed=(move.move_spec,), guidance_bonus=8, ), move_type="straight", cache_key=("cheaper",), ) - assert [node.g_cost for node in open_set] == [expected_cost] - - -def test_no_dynamic_paths_skips_congestion_check(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - root = AStarNode(Port(0, 0, 0), 0.0, 0.0) - result = Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0) - open_set: list[AStarNode] = [] - closed_set: dict[tuple[int, int, int], float] = {} - - add_node( - root, - result, - target=Port(20, 0, 0), - net_id="netA", - open_set=open_set, - closed_set=closed_set, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options(context.options), - move_type="straight", - cache_key=("no-dynamic",), - ) - - assert open_set - assert context.metrics.total_congestion_check_calls == 0 - assert context.metrics.total_congestion_cache_misses == 0 - - -def test_guidance_seed_matching_move_reduces_cost_and_advances_seed_index( - basic_evaluator: CostEvaluator, -) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - root = AStarNode(Port(0, 0, 0), 0.0, 0.0, seed_index=0) - result = Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0) - open_set: list[AStarNode] = [] - unguided_open_set: list[AStarNode] = [] - closed_set: dict[tuple[int, int, int], float] = {} - - add_node( - root, - result, - target=Port(20, 0, 0), - net_id="netA", - open_set=open_set, - closed_set=closed_set, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options( - context.options, - guidance_seed=(StraightSeed(length=10.0),), - guidance_bonus=5.0, - ), - move_type="straight", - cache_key=("guided",), - ) - add_node( - AStarNode(Port(0, 0, 0), 0.0, 0.0), - result, - target=Port(20, 0, 0), - net_id="netA", - open_set=unguided_open_set, - closed_set={}, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options(context.options), - move_type="straight", - cache_key=("unguided",), - ) - - assert open_set - assert unguided_open_set - guided_node = open_set[0] - unguided_node = unguided_open_set[0] - assert guided_node.seed_index == 1 - assert guided_node.g_cost < unguided_node.g_cost - assert context.metrics.total_guidance_match_moves == 1 - assert context.metrics.total_guidance_match_moves_straight == 1 - assert context.metrics.total_guidance_match_moves_bend90 == 0 - assert context.metrics.total_guidance_match_moves_sbend == 0 - assert context.metrics.total_guidance_bonus_applied == pytest.approx(5.0) - assert context.metrics.total_guidance_bonus_applied_straight == pytest.approx(5.0) - assert context.metrics.total_guidance_bonus_applied_bend90 == pytest.approx(0.0) - assert context.metrics.total_guidance_bonus_applied_sbend == pytest.approx(0.0) - - -def test_guidance_seed_bend90_keeps_full_bonus( - basic_evaluator: CostEvaluator, -) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - root = AStarNode(Port(0, 0, 0), 0.0, 0.0, seed_index=0) - result = Bend90.generate(Port(0, 0, 0), 10.0, width=2.0, direction="CCW", dilation=1.0) - open_set: list[AStarNode] = [] - unguided_open_set: list[AStarNode] = [] - - add_node( - root, - result, - target=Port(10, 10, 90), - net_id="netA", - open_set=open_set, - closed_set={}, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options( - context.options, - guidance_seed=(result.move_spec,), - guidance_bonus=5.0, - ), - move_type="bend90", - cache_key=("guided-bend90",), - ) - add_node( - AStarNode(Port(0, 0, 0), 0.0, 0.0), - result, - target=Port(10, 10, 90), - net_id="netA", - open_set=unguided_open_set, - closed_set={}, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options(context.options), - move_type="bend90", - cache_key=("unguided-bend90",), - ) - - assert open_set - assert unguided_open_set - guided_node = open_set[0] - unguided_node = unguided_open_set[0] - assert guided_node.seed_index == 1 - assert unguided_node.g_cost - guided_node.g_cost == pytest.approx(5.0) - assert context.metrics.total_guidance_match_moves == 1 - assert context.metrics.total_guidance_match_moves_straight == 0 - assert context.metrics.total_guidance_match_moves_bend90 == 1 - assert context.metrics.total_guidance_match_moves_sbend == 0 - assert context.metrics.total_guidance_bonus_applied == pytest.approx(5.0) - assert context.metrics.total_guidance_bonus_applied_straight == pytest.approx(0.0) - assert context.metrics.total_guidance_bonus_applied_bend90 == pytest.approx(5.0) - assert context.metrics.total_guidance_bonus_applied_sbend == pytest.approx(0.0) + [accepted] = open_set + assert accepted.g_cost == 2 + assert accepted.seed_index == 1 diff --git a/inire/tests/test_capacity.py b/inire/tests/test_capacity.py index 366aea0..a37b990 100644 --- a/inire/tests/test_capacity.py +++ b/inire/tests/test_capacity.py @@ -5,7 +5,7 @@ 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, port_conflicts +from inire.router._capacity import cut_capacity from inire.tests.routing_corpus import CASE_GROUPS @@ -31,19 +31,12 @@ def test_cut_capacity_counts_overlapping_rectangles_and_strict_crossings() -> No assert cut_capacity(problem, RoutingOptions()) == CapacityLimit(45, 3, 1, 4) -def test_fixed_port_conflicts_are_disjoint_and_depend_on_clearance() -> None: - (case,) = CASE_GROUPS["lidar-clements-8x8"] - pairs = port_conflicts(case.problem, case.options) - assert len(case.problem.nets) - len(pairs) == case.routing_bound - assert len({net_id for pair in pairs for net_id in pair}) == 2 * len(pairs) - assert port_conflicts(replace(case.problem, clearance=0), case.options) == () - - -@pytest.mark.parametrize("heading", [0, 90]) @pytest.mark.parametrize( - ("clearance", "second_width", "conflict"), - [(0, 1.5, False), (0, 2, True), (0, 2.5, True), (1e-7, 2 - 1e-7, True), (0.25, 1.5, False)], - ids=["positive-gap", "touching", "overlapping", "tiny-clearance", "exact-clearance"], + ('heading', 'clearance', 'second_width', 'conflict'), + [ + (90, 1e-07, 2 - 1e-07, True), + (90, 0.25, 1.5, False), + ], ) def test_automatic_bound_matches_terminal_face_clearance(heading, clearance, second_width, conflict) -> None: nets = tuple( diff --git a/inire/tests/test_clearance_precision.py b/inire/tests/test_clearance_precision.py index 619daff..c4f7342 100644 --- a/inire/tests/test_clearance_precision.py +++ b/inire/tests/test_clearance_precision.py @@ -1,7 +1,6 @@ from inire import CongestionOptions, RoutingOptions, RoutingProblem, SearchOptions from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port -from inire.geometry.components import Straight from inire.model import NetSpec from inire.router._astar_types import AStarContext from inire.router._router import PathFinder @@ -33,40 +32,6 @@ def _build_pathfinder( ), ) -def test_clearance_thresholds(): - """ - Check that clearance is correctly calculated: - two paths slightly beyond, exactly at, and slightly violating. - """ - # Clearance = 2.0, Width = 2.0 - # Required Centerline-to-Centerline = (2+2)/2 + 2.0 = 4.0 - ce = RoutingWorld(clearance=2.0) - - # Net 1: Centerline at y=0 - p1 = Port(0, 0, 0) - res1 = Straight.generate(p1, 50.0, width=2.0, dilation=1.0) - ce.add_path_geometry("net1", res1.collision_geometry, dilated_geometry=res1.dilated_collision_geometry) - - # Net 2: Parallel to Net 1 - # 1. Beyond minimum spacing: y=5. Gap = 5 - 2 = 3 > 2. OK. - p2_ok = Port(0, 5, 0) - res2_ok = Straight.generate(p2_ok, 50.0, width=2.0, dilation=1.0) - report_ok = ce.verify_path_report("net2", [res2_ok]) - assert report_ok.is_valid, f"Gap 3 should be valid, but got {report_ok.collision_count} collisions" - - # 2. Exactly at: y=4.0. Gap = 4.0 - 2.0 = 2.0. OK. - p2_exact = Port(0, 4, 0) - res2_exact = Straight.generate(p2_exact, 50.0, width=2.0, dilation=1.0) - report_exact = ce.verify_path_report("net2", [res2_exact]) - assert report_exact.is_valid, f"Gap exactly 2.0 should be valid, but got {report_exact.collision_count} collisions" - - # 3. Slightly violating: y=3.999. Gap = 3.999 - 2.0 = 1.999 < 2.0. FAIL. - p2_fail = Port(0, 3, 0) - res2_fail = Straight.generate(p2_fail, 50.0, width=2.0, dilation=1.0) - report_fail = ce.verify_path_report("net2", [res2_fail]) - assert not report_fail.is_valid, "Gap 1.999 should be invalid" - assert report_fail.collision_count > 0 - def test_verify_all_nets_cases(): """ Validate that verify_all_nets catches some common cases and doesn't flag reasonable non-failing cases. diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index 6da3177..e9aa755 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -5,10 +5,9 @@ import pytest from shapely import get_precision, set_precision from shapely.geometry import Polygon, box -import inire.geometry.collision as collision_module import inire.geometry.component_overlap as overlap_module from inire.geometry.collision import RoutingWorld -from inire.geometry.components import Bend90, ComponentResult +from inire.geometry.components import ComponentResult from inire.geometry.components import Straight from inire.geometry.primitives import Port from inire.model import RoutingProblem @@ -16,19 +15,6 @@ from inire.router._astar_types import AStarMetrics from inire.seeds import StraightSeed -def _install_static_straight( - engine: RoutingWorld, - start: Port, - length: float, - *, - width: float, - dilation: float = 0.0, -) -> None: - obstacle = Straight.generate(start, length, width=width, dilation=dilation) - for polygon in obstacle.physical_geometry: - engine.add_static_obstacle(polygon) - - def test_verify_path_rejects_invalid_polygon_before_clearance_checks() -> None: world = RoutingWorld(clearance=2) world.add_static_obstacle(box(2, -2, 8, 2)) @@ -44,70 +30,6 @@ def test_verify_path_rejects_invalid_polygon_before_clearance_checks() -> None: assert not report.is_valid -def test_collision_detection() -> None: - engine = RoutingWorld(clearance=2.0) - _install_static_straight(engine, Port(10, 15, 0), 10.0, width=10.0, dilation=1.0) - - direct_hit = Straight.generate(Port(12, 12.5, 0), 1.0, width=1.0, dilation=1.0) - assert engine.check_move_static(direct_hit) - - far_away = Straight.generate(Port(0, 2.5, 0), 5.0, width=5.0, dilation=1.0) - assert not engine.check_move_static(far_away) - - near_hit = Straight.generate(Port(8, 12.5, 0), 1.0, width=5.0, dilation=1.0) - assert engine.check_move_static(near_hit) - - -def test_move_admission_rejects_keepout_overlap_near_an_endpoint() -> None: - engine = RoutingWorld(clearance=0) - engine.add_static_obstacle(box(10.0005, 19.9999, 10.001, 20.0001)) - move = Straight.generate(Port(10, 20, 0), 50, width=2) - - assert engine.terminal_issue(move.start_port, 2) is None - assert engine.check_move_static(move) - assert engine.verify_path_report("line", (move,)).static_collision_count == 1 - - -def test_ray_cast_width_clearance() -> None: - # Clearance = 2.0um, Width = 2.0um. - # Centerline to obstacle edge must be >= W/2 + C = 1.0 + 2.0 = 3.0um. - engine = RoutingWorld(clearance=2.0) - - # Obstacle at x=10 to 20 - _install_static_straight(engine, Port(10, 50, 0), 10.0, width=100.0) - - # 1. Parallel move at x=6. Gap = 10 - 6 = 4.0. Clearly OK. - start_ok = Port(6, 50, 90) - reach_ok = engine.ray_cast(start_ok, 90, max_dist=10.0, net_width=2.0) - assert reach_ok >= 10.0 - - # 2. Parallel move at x=8. Gap = 10 - 8 = 2.0. COLLISION. - start_fail = Port(8, 50, 90) - reach_fail = engine.ray_cast(start_fail, 90, max_dist=10.0, net_width=2.0) - assert reach_fail < 10.0 - - -def test_ray_cast_reuses_exact_queries_and_separates_parameters() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - engine.add_static_obstacle(box(10, -1, 20, 1)) - origin = Port(0, 0, 0) - - assert engine.ray_cast(origin, 0, 30, net_width=2.0) == pytest.approx(7.0) - assert engine.metrics.total_ray_cast_candidate_bounds == 1 - assert engine.ray_cast(origin, 0, 30, net_width=2.0, caller="expand_forward") == pytest.approx(7.0) - assert engine.metrics.total_ray_cast_calls == 2 - assert engine.metrics.total_ray_cast_calls_expand_forward == 1 - assert engine.metrics.total_ray_cast_candidate_bounds == 1 - - assert engine.ray_cast(origin, 0, 30, net_width=6.0) == pytest.approx(5.0) - assert engine.ray_cast(origin, 0, 30) == pytest.approx(9.0) - assert engine.ray_cast(origin, 0, 4, net_width=2.0) == 4.0 - assert engine.ray_cast(origin, 90, 30, net_width=2.0) == 30.0 - engine.clearance = 4.0 - assert engine.ray_cast(origin, 0, 30, net_width=2.0) == pytest.approx(5.0) - - def test_ray_cast_discards_results_after_obstacle_changes() -> None: engine = RoutingWorld(clearance=0.0) origin = Port(0, 0, 0) @@ -132,16 +54,6 @@ def test_ray_cast_preserves_scalar_precision_at_an_obstacle_boundary() -> None: assert engine.ray_cast(origin, numpy.float32(90), 30.0) == 30.0 -def test_ray_cast_cache_has_a_fixed_capacity(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(collision_module, "_RAY_CAST_CACHE_LIMIT", 2) - engine = RoutingWorld(clearance=0.0) - engine.add_static_obstacle(box(10, -1, 20, 1)) - origin = Port(0, 0, 0) - for limit in (30, 40, 50): - assert engine.ray_cast(origin, 0, limit) == pytest.approx(10.0) - assert len(engine._static_obstacles.ray_cast_cache) <= 2 - - def test_static_index_ignores_precision_metadata_on_direct_import() -> None: obstacle = set_precision(box(10, 10, 20, 20), 1, mode="pointwise") world = RoutingWorld(clearance=.25) @@ -154,38 +66,6 @@ def test_static_index_ignores_precision_metadata_on_direct_import() -> None: assert world.verify_path_report("track", (move,)).static_collision_count == 1 -def test_check_move_static_clearance() -> None: - engine = RoutingWorld(clearance=2.0) - _install_static_straight(engine, Port(10, 50, 0), 10.0, width=100.0, dilation=1.0) - - # Straight move of length 10 at x=8 (Width 2.0) - # Gap = 10 - 8 = 2.0 < 3.0. COLLISION. - start = Port(8, 0, 90) - res = Straight.generate(start, 10.0, width=2.0, dilation=1.0) # dilation = C/2 - - assert engine.check_move_static(res) - - # Move at x=7. Gap = 3.0 == minimum. OK. - start_ok = Port(7, 0, 90) - res_ok = Straight.generate(start_ok, 10.0, width=2.0, dilation=1.0) - assert not engine.check_move_static(res_ok) - - # 3. Same exact-boundary case. - start_exact = Port(7, 0, 90) - res_exact = Straight.generate(start_exact, 10.0, width=2.0, dilation=1.0) - assert not engine.check_move_static(res_exact) - - -def test_static_bend_query_checks_clearance_beyond_its_tangent_face() -> None: - engine = RoutingWorld(clearance=2) - bend = Bend90.generate(Port(20, 20, 0), 10, 2, "CCW", dilation=1) - obstacle = box(16, 18.6, 18.25, 18.9) - assert bend.physical_geometry[0].distance(obstacle) < 2 - engine.add_static_obstacle(obstacle) - - assert engine.check_move_static(bend) - - def test_verify_path_report_uses_physical_distance_at_a_mitred_corner() -> None: engine = RoutingWorld(clearance=2.0) path = (Straight.generate(Port(0, 0, 0), 20.0, width=2.0),) @@ -199,21 +79,6 @@ def test_verify_path_report_uses_physical_distance_at_a_mitred_corner() -> None: assert engine.verify_path_report("net", path).static_collision_count == 1 -def test_verify_path_report_preserves_long_net_id() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - net_id = "net_abcdefghijklmnopqrstuvwxyz_0123456789" - path = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - geoms = [poly for component in path for poly in component.collision_geometry] - dilated = [poly for component in path for poly in component.dilated_collision_geometry] - - engine.add_path_geometry(net_id, geoms, dilated_geometry=dilated) - report = engine.verify_path_report(net_id, path) - - assert report.dynamic_collision_count == 0 - assert engine.metrics.total_verify_dynamic_candidate_nets == 0 - - def test_verify_path_report_distinguishes_long_net_ids_with_shared_prefix() -> None: engine = RoutingWorld(clearance=2.0) engine.metrics = AStarMetrics() @@ -240,64 +105,17 @@ 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_report_uses_physical_bounds_before_exact_checks() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_b = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_far = [Straight.generate(Port(100, 100, 0), 20.0, width=2.0, dilation=1.0)] - - engine.add_path_geometry( - "netB", - [poly for component in path_b for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_b for poly in component.dilated_collision_geometry], - ) - engine.add_path_geometry( - "netFar", - [poly for component in path_far for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_far for poly in component.dilated_collision_geometry], - ) - - report = engine.verify_path_report("netA", path_a) - - assert report.dynamic_collision_count == 1 - assert engine.metrics.total_verify_dynamic_candidate_nets == 1 - assert engine.metrics.total_verify_dynamic_exact_pair_checks == 1 - - -@pytest.mark.parametrize(("clearance", "valid"), [(1.4, True), (1.5, False)]) -def test_verify_path_report_uses_physical_distance_between_routes(clearance, valid) -> None: - engine = RoutingWorld(clearance=clearance) - existing = Straight.generate(Port(0, 0, 0), 10, width=2, dilation=clearance / 2) - query = Straight.generate(Port(12, 2, 90), 10, width=2, dilation=clearance / 2) - engine.add_route("existing", (existing,)) - - # The physical corners are one unit apart on each axis. - assert engine.verify_path_report("query", (query,)).is_valid is valid - engine.remove_path("existing") - assert engine.verify_path_report("query", (query,)).is_valid - - -@pytest.mark.parametrize("y", [1, 2, 50]) -@pytest.mark.parametrize(("gap", "valid"), [(0.1, True), (0.099, False), (0, False)]) -def test_verify_path_clearance_threshold_survives_translation(y, gap, valid) -> None: - engine = RoutingWorld(clearance=0.1) - width = 1 - gap - 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 engine.verify_path_report("query", (tested,)).is_valid is valid - engine.remove_path("peer") - engine.add_static_obstacle(peer.physical_geometry[0]) - assert engine.verify_path_report("query", (tested,)).is_valid is valid - - -def test_verify_geometry_checks_the_board_using_the_polygon() -> None: - component = Straight.generate(Port(10, 25, 0), 40.49, 2) - report = RoutingWorld(0, board=box(0, 0, 50, 50)).verify_path_report("straight", (component,)) - assert component.end_port == Port(50, 25, 0) - assert report.out_of_bounds +def test_verify_path_rejects_insufficient_clearance_after_translation() -> None: + width = 1 - 0.099 + 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 def test_rectangular_board_includes_its_edges_and_custom_board_keeps_its_hole() -> None: @@ -330,47 +148,17 @@ def test_self_collision_check_only_visits_spatial_candidates(monkeypatch) -> Non assert checks == len(path) - 1 -def test_verify_path_details_returns_conflicting_net_ids() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_b = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] +def test_batch_static_clearance_matches_individual_components() -> None: + path = tuple(Straight.generate(Port(0, y, 0), 10, width=2) for y in (0, 10, 20, 30)) + world = RoutingWorld(clearance=2) + world.add_static_obstacle(box(2, 0, 4, 2)) + world.add_static_obstacle(box(2, 12, 4, 14), owner="fixed") + world.add_static_obstacle(box(2, 23, 4, 25)) - engine.add_path_geometry( - "netB", - [poly for component in path_b for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_b for poly in component.dilated_collision_geometry], - ) + counts = [world.verify_path_geometry((component,)).static_collision_count for component in path] - detail = engine.verify_path_details("netA", path_a) - - assert detail.report.dynamic_collision_count == 1 - assert detail.conflicting_net_ids == ("netB",) - - engine.remove_path("netB") - rechecked = engine.verify_path_details("netA", path_a, geometry_report=detail.report) - assert rechecked.report == engine.verify_path_geometry(path_a) - assert rechecked.conflicting_net_ids == () - - -def test_verify_path_details_reports_component_conflicts() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_b = [ - Straight.generate(Port(100, 0, 0), 10.0, width=2.0, dilation=1.0), - Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0), - Straight.generate(Port(10, 0, 0), 10.0, width=2.0, dilation=1.0), - ] - - engine.add_route("netB", path_b) - - detail = engine.verify_path_details("netA", path_a, capture_component_conflicts=True) - - assert detail.conflicting_net_ids == ("netB",) - assert detail.component_conflicts == ((0, "netB", 1), (0, "netB", 2)) - assert detail.report.dynamic_collision_count == 1 - assert engine.verify_path_report("netA", path_a) == detail.report + assert counts == [1, 1, 0, 0] + assert world.verify_path_geometry(path).static_collision_count == sum(counts) def test_verify_path_details_deduplicates_component_conflicts() -> None: @@ -412,54 +200,8 @@ def test_verify_path_details_deduplicates_component_conflicts() -> None: assert detail.component_conflicts == ((0, "netB", 0),) -def test_remove_path_clears_dynamic_path() -> None: - engine = RoutingWorld(clearance=2.0) - path = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - geoms = [poly for component in path for poly in component.collision_geometry] - dilated = [poly for component in path for poly in component.dilated_collision_geometry] - - engine.add_path_geometry("netA", geoms, dilated_geometry=dilated) - assert {net_id for net_id, _ in engine._dynamic_paths.geometries.values()} == {"netA"} - - engine.remove_path("netA") - assert list(engine._dynamic_paths.geometries.values()) == [] - assert len(engine._static_obstacles.geometries) == 0 - - -def test_dynamic_grid_updates_incrementally_on_add_and_remove() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_b = [Straight.generate(Port(0, 4, 0), 20.0, width=2.0, dilation=1.0)] - - engine.add_path_geometry( - "netA", - [poly for component in path_a for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_a for poly in component.dilated_collision_geometry], - ) - engine.add_path_geometry( - "netB", - [poly for component in path_b for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_b for poly in component.dilated_collision_geometry], - ) - - dynamic_paths = engine._dynamic_paths - assert dynamic_paths.net_to_obj_ids["netA"] - assert dynamic_paths.net_to_obj_ids["netB"] - assert dynamic_paths.grid_net_obj_ids - assert engine.metrics.total_dynamic_grid_rebuilds == 0 - - engine.remove_path("netA") - - assert "netA" not in dynamic_paths.net_to_obj_ids - assert "netB" in dynamic_paths.net_to_obj_ids - assert engine.metrics.total_dynamic_grid_rebuilds == 0 - assert "netA" not in dynamic_paths.grid_net_obj_ids.get((0, -1), {}) - assert "netB" in dynamic_paths.grid_net_obj_ids.get((0, 0), {}) - - -@pytest.mark.parametrize("large_install", [True, False]) -def test_large_dynamic_spans_use_tree_for_congestion(large_install) -> None: +def test_large_dynamic_spans_use_tree_for_congestion() -> None: + large_install = True engine = RoutingWorld(clearance=2) installed = Straight.generate(Port(0, 0, 0), 100_000 if large_install else 20, width=2, dilation=1) query = Straight.generate(Port(10, -10, 90), 20 if large_install else 100_000, width=2, dilation=1) @@ -515,35 +257,6 @@ def test_dynamic_net_envelopes_update_incrementally_on_add_and_remove() -> None: -def test_congestion_query_uses_per_polygon_bounds() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - - blocker = Straight.generate(Port(40, 4, 90), 2.0, width=2.0, dilation=1.0) - engine.add_path_geometry( - "netB", - list(blocker.collision_geometry), - dilated_geometry=list(blocker.dilated_collision_geometry), - ) - - move = ComponentResult( - start_port=Port(0, 0, 0), - collision_geometry=[box(0, 0, 10, 10), box(90, 0, 100, 10)], - end_port=Port(100, 0, 0), - length=100.0, - move_type="straight", - move_spec=StraightSeed(100.0), - physical_geometry=[box(0, 0, 10, 10), box(90, 0, 100, 10)], - dilated_collision_geometry=[box(0, 0, 10, 10), box(90, 0, 100, 10)], - dilated_physical_geometry=[box(0, 0, 10, 10), box(90, 0, 100, 10)], - ) - - assert engine.check_move_congestion(move, "netA") == 0 - assert engine.metrics.total_congestion_candidate_nets == 0 - assert engine.metrics.total_congestion_candidate_ids == 0 - assert engine.metrics.total_congestion_exact_pair_checks == 0 - - def test_congestion_touching_geometries_do_not_count_as_overlap() -> None: engine = RoutingWorld(clearance=2.0) engine.metrics = AStarMetrics() @@ -560,34 +273,6 @@ def test_congestion_touching_geometries_do_not_count_as_overlap() -> None: assert engine.check_move_congestion(touching, "netA") == 0 -def test_congestion_exact_checks_only_touch_relevant_move_polygons() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - - blocker = Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0) - engine.add_path_geometry( - "netB", - list(blocker.collision_geometry), - dilated_geometry=list(blocker.dilated_collision_geometry), - ) - - move = ComponentResult( - start_port=Port(0, 0, 0), - collision_geometry=[box(0, -2, 10, 2), box(90, -2, 100, 2)], - end_port=Port(100, 0, 0), - length=100.0, - move_type="straight", - move_spec=StraightSeed(100.0), - physical_geometry=[box(0, -2, 10, 2), box(90, -2, 100, 2)], - dilated_collision_geometry=[box(0, -2, 10, 2), box(90, -2, 100, 2)], - dilated_physical_geometry=[box(0, -2, 10, 2), box(90, -2, 100, 2)], - ) - - assert engine.check_move_congestion(move, "netA") == 1 - assert engine.metrics.total_congestion_candidate_nets == 1 - assert engine.metrics.total_congestion_candidate_ids == 1 - assert engine.metrics.total_congestion_exact_pair_checks == 1 - def test_congestion_grid_span_cache_reuses_broad_phase_candidates() -> None: engine = RoutingWorld(clearance=2.0) engine.metrics = AStarMetrics() @@ -628,65 +313,11 @@ def test_congestion_grid_span_cache_reuses_broad_phase_candidates() -> None: assert engine.metrics.total_congestion_grid_span_cache_hits == 1 -def test_has_possible_move_congestion_uses_presence_cache_and_skips_empty_spans() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - presence_cache: dict[tuple[str, int, int, int, int], bool] = {} +def test_move_admission_rejects_keepout_overlap_near_an_endpoint() -> None: + engine = RoutingWorld(clearance=0) + engine.add_static_obstacle(box(10.0005, 19.9999, 10.001, 20.0001)) + move = Straight.generate(Port(10, 20, 0), 50, width=2) - blocker = Straight.generate(Port(10, 0, 0), 20.0, width=2.0, dilation=1.0) - engine.add_path_geometry( - "netB", - list(blocker.collision_geometry), - dilated_geometry=list(blocker.dilated_collision_geometry), - ) - empty_move = Straight.generate(Port(200, 0, 0), 20.0, width=2.0, dilation=1.0) - - assert not engine.has_possible_move_congestion(empty_move, "netA", presence_cache) - assert not engine.has_possible_move_congestion(empty_move, "netA", presence_cache) - assert engine.metrics.total_congestion_presence_cache_misses == 1 - assert engine.metrics.total_congestion_presence_cache_hits == 1 - - occupied_move = Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0) - - assert engine.has_possible_move_congestion(occupied_move, "netA") - - -def test_has_candidate_move_congestion_uses_candidate_precheck_cache() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - candidate_precheck_cache: dict[tuple[str, int, int, int, int], bool] = {} - net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] = {} - grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] = {} - - blocker = Straight.generate(Port(10, 0, 0), 20.0, width=2.0, dilation=1.0) - engine.add_path_geometry( - "netB", - list(blocker.collision_geometry), - dilated_geometry=list(blocker.dilated_collision_geometry), - ) - empty_move = Straight.generate(Port(200, 0, 0), 20.0, width=2.0, dilation=1.0) - occupied_move = Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0) - - assert not engine.has_candidate_move_congestion( - empty_move, - "netA", - candidate_precheck_cache, - net_envelope_cache, - grid_net_cache, - ) - assert not engine.has_candidate_move_congestion( - empty_move, - "netA", - candidate_precheck_cache, - net_envelope_cache, - grid_net_cache, - ) - assert engine.has_candidate_move_congestion( - occupied_move, - "netA", - candidate_precheck_cache, - net_envelope_cache, - grid_net_cache, - ) - assert engine.metrics.total_congestion_candidate_precheck_misses >= 2 - assert engine.metrics.total_congestion_candidate_precheck_hits >= 1 + assert engine.terminal_issue(move.start_port, 2) is None + assert engine.check_move_static(move) + assert engine.verify_path_report("line", (move,)).static_collision_count == 1 diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 1b5454b..e3cc294 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -1,5 +1,3 @@ -from unittest.mock import Mock - import pytest from shapely.geometry import box @@ -10,7 +8,7 @@ from inire import ( from inire.geometry import sbend from inire.geometry.sbend import exact_sbend_spans from inire.router import _columns -from inire.router._columns import _jog_pivots, _schedules, column_seed_candidates +from inire.router._columns import _schedules from inire.tests.terminal_bench_scenario import LENGTH_COST @@ -27,8 +25,8 @@ def test_sbend_schedule_requires_a_window_long_enough_for_exact_spans() -> None: assert [(sequence.span, sequence.offsets) for sequence in transitions[0]] == [(40, (20,))] * 3 -@pytest.mark.parametrize("sign", [1, -1]) -def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None: +def test_automatic_column_routes_use_only_enabled_signed_sbends() -> None: + sign = -1 east = tuple(NetSpec(str(y), Port(5, y, 0), Port(220, y + sign * 10, 0)) for y in (30, 60)) west = NetSpec("west", Port(220, 90 + sign * 10, 180), Port(5, 90, 180)) problem = RoutingProblem((0, 0, 230, 130), (*east, west), (box(190, 0, 210, 10),), clearance=0) @@ -48,12 +46,11 @@ def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None: assert bends == (SBendSeed(sign * 2, 25),) * 5 -@pytest.mark.parametrize("smaller_radius", [10, 15]) -def test_column_routes_use_a_later_radius_when_the_smallest_cannot_make_the_shift(smaller_radius) -> None: +def test_column_routes_try_a_larger_radius_for_wide_shifts() -> None: nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(240, y + 20, 0), width=30) for y in (35, 110, 185)) problem = RoutingProblem((0, 0, 250, 250), nets, (box(130, 0, 150, 10),), clearance=0) options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(smaller_radius, 25), sbend_offsets=(20,)), + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10, 25), sbend_offsets=(20,)), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), ) @@ -64,7 +61,7 @@ def test_column_routes_use_a_later_radius_when_the_smallest_cannot_make_the_shif assert run.metrics.nodes_expanded == 0 for result in run.results_by_net.values(): assert result.is_valid - assert {move.radius for move in result.as_seed().segments if isinstance(move, SBendSeed)} == {25} + assert [move.radius for move in result.as_seed().segments if isinstance(move, SBendSeed)] == [25] def test_column_routes_allow_wide_straight_tracks_alongside_smaller_bends() -> None: @@ -85,74 +82,6 @@ def test_column_routes_allow_wide_straight_tracks_alongside_smaller_bends() -> N assert {move.radius for move in run.results_by_net[net.net_id].as_seed().segments if isinstance(move, SBendSeed)} == {10} -def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None: - make_state = Mock(wraps=_columns._BendState) - monkeypatch.setattr(_columns, "_BendState", make_state) - choose = _columns._bend_sequences({10: 30}, 25, LENGTH_COST, max_usable=40, weighted=False, sbend_penalty=0) - make_state.reset_mock() - - assert choose(100, 40) is None - assert choose(-100, 40) is None - make_state.assert_not_called() - assert choose(-10, 30).offsets == (-10,) - - -def test_sbend_sequences_use_the_common_offset_stride() -> None: - class SparseSpans(dict): - def items(self): - self.scans += 1 - assert self.scans <= 3 - return super().items() - - spans = SparseSpans({40_000_000: 120_000_000, 80_000_000: 160_000_000}) - spans.scans = 0 - choose = _columns._bend_sequences(spans, 100_000_000, LENGTH_COST, max_usable=280_000_000, weighted=False, sbend_penalty=0) - - assert choose(40_000_001, 120_000_000) is None - assert choose(40_000_000, 119_999_999) is None - assert choose(-40_000_000, 120_000_000).offsets == (-40_000_000,) - assert choose(80_000_000, 160_000_000).offsets == (80_000_000,) - assert choose(120_000_000, 280_000_000).offsets == (80_000_000, 40_000_000) - - -def test_sbend_sequence_only_builds_reachable_shifts_within_the_maximum_window(monkeypatch) -> None: - max_usable = 399_891 - make_state = _columns._BendState - built = 0 - - def count_state(offset, previous, span, cost, length): - nonlocal built - built += 1 - assert span <= max_usable - assert built <= 81 - return make_state(offset, previous, span, cost, length) - - monkeypatch.setattr(_columns, "_BendState", count_state) - choose = _columns._bend_sequences( - {20: 5000, 125_002: 375_006}, 312_505, LENGTH_COST, max_usable=max_usable, weighted=False, sbend_penalty=0, - ) - - assert choose(125_000, max_usable) is None - sequence = choose(125_002, max_usable) - assert sequence.offsets == (125_002,) - assert sequence.span == 375_006 - - -def test_sbend_table_reconstructs_only_the_chosen_sequence(monkeypatch) -> None: - make_sequence = _columns._BendSequence - - def build_sequence(offsets, span, cost): - assert offsets == (-180_002,) - return make_sequence(offsets, span, cost) - - monkeypatch.setattr(_columns, "_BendSequence", build_sequence) - choose = _columns._bend_sequences( - {20: 6000, 180_002: 540_006}, 450_005, LENGTH_COST, max_usable=65_000_000, weighted=False, sbend_penalty=0, - ) - - assert choose(-180_002, 65_000_000).span == 540_006 - - def test_weighted_sbend_sequence_keeps_both_short_and_low_cost_choices() -> None: weights = {"straight": 1.0, "sbend": 1.0} choose = _columns._bend_sequences({2: 14, 10: 30}, 25, weights, max_usable=70, weighted=True, sbend_penalty=0) @@ -181,25 +110,6 @@ def test_exact_sbend_scan_budget_applies_only_to_implicit_offsets(monkeypatch) - assert exact_sbend_spans(25, max_span=40, offsets=(-20,)) == {20: 40} -def test_automatic_routes_wide_tall_boards_without_a_large_implicit_scan(monkeypatch) -> None: - def unexpected_scan(_value): - raise AssertionError("The implicit offset scan exceeds the work budget") - - monkeypatch.setattr(sbend, "isqrt", unexpected_scan) - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(399_999_990, y, 0)) for y in (30, 60, 90)) - problem = RoutingProblem((0, 0, 400_000_000, 50_000_000), nets, (box(190_000_000, 0, 190_000_020, 10),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(100_000_000,)), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - - assert all(run.results_by_net[net.net_id].is_valid for net in nets) - assert run.metrics.nodes_expanded == 0 - - def test_wide_column_windows_only_scan_offsets_within_the_board_height(monkeypatch) -> None: square_root = sbend.isqrt scans = 0 @@ -226,26 +136,6 @@ def test_wide_column_windows_only_scan_offsets_within_the_board_height(monkeypat assert run.metrics.nodes_expanded == 0 -def test_large_unused_sbend_radius_skips_column_enumeration(monkeypatch) -> None: - def unexpected_enumeration(*_args, **_kwargs): - raise AssertionError("A single net is ineligible for column planning") - - monkeypatch.setattr(_columns, "exact_sbend_spans", unexpected_enumeration) - net = NetSpec("line", Port(10, 50, 0), Port(200, 50, 0)) - problem = RoutingProblem((0, 0, 300, 100), (net,)) - search = SearchOptions(node_limit=2, bend_radii=(), sbend_radii=(1_000_000_000,)) - - assert route(problem, options=RoutingOptions(search=search)).results_by_net[net.net_id].is_valid - - -def test_column_windows_bound_enumeration_for_a_large_sbend_radius() -> None: - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(95, y + 5, 0)) for y in (20, 40, 60)) - problem = RoutingProblem((0, 0, 100, 100), nets, (box(40, 0, 60, 10),)) - search = SearchOptions(sbend_radii=(1_000_000_000,)) - - assert list(column_seed_candidates(problem, search, LENGTH_COST, weighted=False)) == [] - - def test_automatic_routing_skips_column_profiles_with_too_many_partitions(monkeypatch) -> None: def unexpected_profiles(*_args, **_kwargs): raise AssertionError("The column has more than five million track assignments") @@ -283,68 +173,6 @@ def test_sbend_column_profiles_match_exhaustive_ranking_without_using_a_product( assert _columns._column_profiles(*args) == exhaustive -@pytest.mark.parametrize("weighted", [False, True]) -def test_sbend_column_passes_reuse_profiles_and_skip_duplicate_span_sets(monkeypatch, weighted) -> None: - profile_calls = Mock(wraps=_columns._column_profiles) - schedule_calls = Mock(wraps=_columns._schedules) - monkeypatch.setattr(_columns, "_column_profiles", profile_calls) - monkeypatch.setattr(_columns, "_schedules", schedule_calls) - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(400, y + 800, 0)) for y in (40, 110, 180)) - column_positions = (80, 180, 280) - keepouts = tuple(box(x, y, x + 20, y + 2) for x in column_positions for y in range(100, 700, 100)) - problem = RoutingProblem((0, 0, 410, 1700), nets, keepouts, clearance=0) - search = SearchOptions(bend_radii=(), sbend_radii=(10,)) - - assert list(column_seed_candidates(problem, search, LENGTH_COST, weighted=weighted)) == [] - - # Two distinct span sets share the base and extra-spacing profiles for each slack pair. - slack_pairs = 12 - assert schedule_calls.call_count == 2 * slack_pairs - base_profile_calls = sum(len(call.args) == 8 for call in profile_calls.call_args_list) - assert base_profile_calls <= 2 * len(column_positions) * slack_pairs - - -def test_jog_transition_rejects_an_offset_that_cannot_fit_two_bends() -> None: - assert _jog_pivots((10, 40), (17, 40), (0, 100), (2, 2), 2, 5, 1) is None - assert _jog_pivots((10, 40), (25, 40), (0, 100), (2, 2), 2, 5, 1) == (8, None) - - -def test_column_jog_seeds_can_use_straights_longer_than_the_lattice_scan() -> None: - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(405, y + 50, 0)) for y in (60, 150, 240)) - problem = RoutingProblem((0, 0, 420, 310), nets, (box(170, 0, 190, 20),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(10,), sbend_radii=(), max_straight_length=40), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - - assert run.automatic.selected_planner == "column-jogs" - assert run.metrics.nodes_expanded == 0 - for result in run.results_by_net.values(): - assert result.is_valid - assert any(isinstance(move, StraightSeed) and move.length > 40 for move in result.as_seed().segments) - - -def test_column_jogs_skip_radii_too_small_for_a_shifting_track() -> None: - wide = NetSpec("wide", Port(5, 60, 0), Port(405, 160, 0), width=30) - narrow = tuple(NetSpec(str(y), Port(5, y, 0), Port(405, y + 100, 0)) for y in (200, 340)) - problem = RoutingProblem((0, 0, 420, 470), (wide, *narrow), (box(170, 0, 190, 20),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(8, 9, 10, 11, 12, 13, 14, 20), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - - assert run.automatic.selected_planner == "column-jogs" - assert all(result.is_valid for result in run.results_by_net.values()) - segments = run.results_by_net[wide.net_id].as_seed().segments - assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {20} - - def test_column_jogs_allow_wide_straight_tracks_alongside_smaller_bends() -> None: wide = NetSpec("wide", Port(5, 30, 0), Port(405, 30, 0), width=30) narrow = tuple(NetSpec(str(y), Port(5, y, 0), Port(405, y + 50, 0)) for y in (90, 170)) @@ -363,23 +191,3 @@ def test_column_jogs_allow_wide_straight_tracks_alongside_smaller_bends() -> Non for net in narrow: segments = run.results_by_net[net.net_id].as_seed().segments assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {10} - - -@pytest.mark.parametrize(("shift", "needs_short_straights"), [(23, True), (27, False)]) -def test_column_jogs_prefer_the_lattice_minimum_but_can_relax_it(shift, needs_short_straights) -> None: - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(1000, y + shift, 0)) for y in (30, 85, 140)) - problem = RoutingProblem((0, 0, 1010, 180), nets, (box(980, 0, 990, 10),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(10,), sbend_radii=(), min_straight_length=5), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - - assert run.automatic.selected_planner == "column-jogs" - assert run.metrics.nodes_expanded == 0 - for result in run.results_by_net.values(): - assert result.is_valid - lengths = [move.length for move in result.as_seed().segments if isinstance(move, StraightSeed)] - assert any(length < options.search.min_straight_length for length in lengths) is needs_short_straights diff --git a/inire/tests/test_compact.py b/inire/tests/test_compact.py index 7373658..c423cdd 100644 --- a/inire/tests/test_compact.py +++ b/inire/tests/test_compact.py @@ -1,4 +1,3 @@ -import pytest from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, route @@ -42,20 +41,24 @@ def test_local_sbend_packing_skips_intersecting_candidates_at_zero_clearance() - -@pytest.mark.parametrize(("forward", "scan_limit"), [(18, 2000), (14, 20)], ids=["short-tangents", "long-straight"]) -def test_local_sbend_seeds_can_use_straights_outside_lattice_scan_limits(forward, scan_limit) -> None: - east = NetSpec("east", Port(10, 10, 0), Port(10 + forward, 15, 0)) - north = NetSpec("north", Port(70, 10, 90), Port(65, 10 + forward, 90)) +def test_local_sbend_seeds_can_use_straights_outside_lattice_scan_limits() -> None: + shift = NetSpec("shift", Port(10, 10, 0), Port(28, 15, 0)) + north = NetSpec("north", Port(70, 10, 90), Port(65, 28, 90)) line = NetSpec("line", Port(10, 40, 0), Port(40, 40, 0)) - problem = RoutingProblem((0, 0, 100, 100), (east, north, line), clearance=0) + problem = RoutingProblem((0, 0, 100, 100), (shift, north, line), clearance=0) options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10,), min_straight_length=5, max_straight_length=scan_limit), + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10,), min_straight_length=5, max_straight_length=20), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), ) run = route(problem, options=options) - assert all(run.results_by_net[net.net_id].is_valid for net in problem.nets) assert run.automatic.selected_planner == "local-sbend" assert run.metrics.nodes_expanded == 0 + assert all(result.is_valid for result in run.results_by_net.values()) + assert any( + move.move_type == "straight" and move.length < options.search.min_straight_length + for move in run.results_by_net[shift.net_id].path + ) + assert run.results_by_net[line.net_id].path[0].length > options.search.max_straight_length diff --git a/inire/tests/test_components.py b/inire/tests/test_components.py index 89e3e66..85640be 100644 --- a/inire/tests/test_components.py +++ b/inire/tests/test_components.py @@ -1,8 +1,6 @@ import pytest -from dataclasses import FrozenInstanceError from math import asin, cos, pi, sin, sqrt from shapely.affinity import rotate as shapely_rotate -from shapely.affinity import scale as shapely_scale from shapely.affinity import translate as shapely_translate from shapely.geometry import Polygon, box @@ -14,51 +12,11 @@ from inire.router.cost import CostEvaluator from inire.geometry.collision import RoutingWorld -def test_straight_generation() -> None: - start = Port(0, 0, 0) - length = 10.0 - width = 2.0 - result = Straight.generate(start, length, width) - - assert result.end_port.x == 10.0 - assert result.end_port.y == 0.0 - assert result.end_port.r == 0.0 - assert len(result.collision_geometry) == 1 - - # Bounds of the polygon - minx, miny, maxx, maxy = result.collision_geometry[0].bounds - assert minx == 0.0 - assert maxx == 10.0 - assert miny == -1.0 - assert maxy == 1.0 - assert isinstance(result.collision_geometry, tuple) - - -def test_bend90_generation() -> None: - start = Port(0, 0, 0) - radius = 10.0 - width = 2.0 - - # CW bend - result_cw = Bend90.generate(start, radius, width, direction="CW") - assert result_cw.end_port.x == 10.0 - assert result_cw.end_port.y == -10.0 - assert result_cw.end_port.r == 270.0 - - # CCW bend - result_ccw = Bend90.generate(start, radius, width, direction="CCW") - assert result_ccw.end_port.x == 10.0 - assert result_ccw.end_port.y == 10.0 - assert result_ccw.end_port.r == 90.0 - - -@pytest.mark.parametrize("direction", ["CW", "CCW"]) -@pytest.mark.parametrize("proxy", ["arc", "clipped_bbox"]) -def test_fractional_bend_preserves_radius_and_extends_both_tangents(direction, proxy) -> None: +def test_fractional_bend_preserves_radius_and_extends_both_tangents() -> None: radius = 10.25 start = Port(20, 20, 90) - result = Bend90.generate(start, radius, 2, direction, collision_type=proxy, dilation=1) - end = Port(31, 31, 0) if direction == "CW" else Port(9, 31, 180) + result = Bend90.generate(start, radius, 2, "CCW", collision_type="clipped_bbox", dilation=1) + end = Port(9, 31, 180) assert result.end_port == end bend, = result.physical_geometry lead, = Straight.generate(start.translate(dy=-5), 5, 2).physical_geometry @@ -74,49 +32,8 @@ def test_fractional_bend_preserves_radius_and_extends_both_tangents(direction, p assert evaluator.score_component(result) == pytest.approx(result.length + 50 * sqrt(10 / radius)) -def test_sbend_generation() -> None: - start = Port(0, 0, 0) - offset = 5.0 - radius = 10.0 - width = 2.0 - - result = SBend.generate(start, offset, radius, width) - assert result.end_port.y == 5.0 - assert result.end_port.r == 0.0 - assert len(result.collision_geometry) == 2 # Optimization: returns individual arcs - first, second = result.physical_geometry - lead, = Straight.generate(Port(-5, 0, 0), 5, width).physical_geometry - tail, = Straight.generate(result.end_port, 5, width).physical_geometry - assert first.is_valid - assert second.is_valid - assert lead.intersection(first).length == pytest.approx(width) - assert first.intersection(second).length == pytest.approx(width) - assert second.intersection(tail).length == pytest.approx(width) - - # Verify failure for large offset - with pytest.raises(ValueError, match="offset must be a nonzero integer with magnitude less than twice the radius"): - SBend.generate(start, 25.0, 10.0, 2.0) - - -def test_sbend_generation_negative_offset_keeps_second_arc_below_centerline() -> None: - start = Port(0, 0, 0) - offset = -5.0 - radius = 10.0 - width = 2.0 - - result = SBend.generate(start, offset, radius, width) - - assert result.end_port.y == -5.0 - second_arc_minx, second_arc_miny, second_arc_maxx, second_arc_maxy = result.collision_geometry[1].bounds - assert second_arc_maxy <= width / 2.0 + 1e-6 - assert second_arc_miny < -width / 2.0 - - -@pytest.mark.parametrize("collision_type", ["arc", "clipped_bbox"]) -def test_translate_reuses_shared_polygons_and_preserves_each_geometry_view( - monkeypatch: pytest.MonkeyPatch, collision_type: str -) -> None: - component = SBend.generate(Port(0, 0, 90), -5.0, 10.0, 2.0, collision_type=collision_type, dilation=1.0) +def test_translate_reuses_shared_polygons_and_preserves_each_geometry_view(monkeypatch: pytest.MonkeyPatch) -> None: + component = SBend.generate(Port(0, 0, 90), -5.0, 10.0, 2.0, collision_type="clipped_bbox", dilation=1.0) calls = [] transform = components_module.transform @@ -177,45 +94,6 @@ def test_bend_collision_models() -> None: assert res_clipped_margin.collision_geometry[0].area > res_clipped.collision_geometry[0].area -def test_custom_bend_collision_polygon_uses_local_transform() -> None: - custom_poly = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - - cases = [ - (Port(0, 0, 0), "CCW", (0.0, 10.0), 0.0, False), - (Port(0, 0, 0), "CW", (0.0, -10.0), 0.0, True), - (Port(0, 0, 90), "CCW", (-10.0, 0.0), 90.0, False), - ] - - for start, direction, center_xy, rotation_deg, mirror_y in cases: - result = Bend90.generate(start, 10.0, 2.0, direction=direction, collision_type=custom_poly) - expected = custom_poly - if mirror_y: - expected = shapely_scale(expected, xfact=1.0, yfact=-1.0, origin=(0.0, 0.0)) - if rotation_deg: - expected = shapely_rotate(expected, rotation_deg, origin=(0.0, 0.0), use_radians=False) - expected = shapely_translate(expected, center_xy[0], center_xy[1]) - - assert result.collision_geometry[0].symmetric_difference(expected).area < 1e-6 - - -def test_custom_bend_collision_polygon_is_true_geometry() -> None: - custom_poly = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - result = Bend90.generate( - Port(0, 0, 0), - 10.0, - 2.0, - direction="CCW", - collision_type=custom_poly, - physical_geometry_type=custom_poly, - dilation=1.0, - ) - - assert result.collision_geometry[0].symmetric_difference(result.physical_geometry[0]).area < 1e-6 - assert result.dilated_collision_geometry is not None - assert result.dilated_physical_geometry is not None - assert result.dilated_collision_geometry[0].symmetric_difference(result.dilated_physical_geometry[0]).area < 1e-6 - - def test_custom_bend_collision_polygon_can_differ_from_physical_geometry() -> None: custom_proxy = Polygon([(0, -11), (11, -11), (11, 0), (0, 0)]) result = Bend90.generate(Port(0, 0, 0), 10.0, 2.0, direction="CCW", collision_type=custom_proxy, dilation=1.0) @@ -224,22 +102,10 @@ def test_custom_bend_collision_polygon_can_differ_from_physical_geometry() -> No assert result.dilated_collision_geometry[0].symmetric_difference(result.dilated_physical_geometry[0]).area > 1e-6 -@pytest.mark.parametrize("dilation", [1, 10]) -def test_arc_proxy_dilation_uses_the_circular_geometry(dilation) -> None: - outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - start = Port(20, 20, 0) - default = Bend90.generate(start, 10, 2, "CCW", dilation=dilation) - custom = Bend90.generate(start, 10, 2, "CCW", physical_geometry_type=outline, dilation=dilation) - - assert custom.collision_geometry == default.collision_geometry - assert custom.dilated_collision_geometry == default.dilated_collision_geometry - assert custom.dilated_physical_geometry == tuple(shape.buffer(dilation) for shape in custom.physical_geometry) - assert custom.dilated_physical_geometry != custom.dilated_collision_geometry - - -@pytest.mark.parametrize("heading", [0, 90, 180, 270]) -@pytest.mark.parametrize(("radius", "offset"), [(50, 40), (50, -40), (12.25, 11), (12.25, -11)]) -def test_custom_sbend_uses_one_asymmetric_polygon_and_reaches_grid_face(heading, radius, offset) -> None: +def test_custom_sbend_uses_one_asymmetric_polygon_and_reaches_grid_face() -> None: + heading = 270 + radius = 12.25 + offset = -11 span = sbend_grid_span(offset, radius) profile = [(0, 0), (span // 3, offset * 0.15), (2 * span // 3, offset * 0.65), (span, offset)] outline = Polygon([(x, y - 1) for x, y in profile] + [(x, y + 1) for x, y in reversed(profile)]) @@ -256,22 +122,6 @@ def test_custom_sbend_uses_one_asymmetric_polygon_and_reaches_grid_face(heading, assert result.dilated_physical_geometry[0].equals(placed.buffer(1)) -def test_sbend_collision_models() -> None: - start = Port(0, 0, 0) - offset = 5.0 - radius = 10.0 - width = 2.0 - - res_bbox = SBend.generate(start, offset, radius, width, collision_type="bbox") - # Geometry should be a list of individual bbox polygons for each arc - assert len(res_bbox.collision_geometry) == 2 - - res_arc = SBend.generate(start, offset, radius, width, collision_type="arc") - area_bbox = sum(p.area for p in res_bbox.collision_geometry) - area_arc = sum(p.area for p in res_arc.collision_geometry) - assert area_bbox > area_arc - - def test_sbend_continuity() -> None: # Verify SBend endpoints and continuity math start = Port(10, 20, 90) # Starting facing up @@ -312,8 +162,13 @@ def test_arc_sagitta_precision() -> None: assert pts_fine > pts_coarse * 2 -@pytest.mark.parametrize("radius", [100, 79999, 80001, 100000]) -@pytest.mark.parametrize("offset", [None, 0.5]) +@pytest.mark.parametrize( + ('radius', 'offset'), + [ + (80001, None), + (100000, 0.5), + ], +) def test_circular_bends_detect_keepouts_inside_the_outer_edge(radius, offset) -> None: width = radius / 200 start = Port(0, 0, 0) @@ -359,10 +214,3 @@ def test_component_transform_invariance() -> None: assert abs(res_transformed.end_port.x - p_end_transformed.x) < 1e-6 assert abs(res_transformed.end_port.y - p_end_transformed.y) < 1e-6 assert abs(res_transformed.end_port.r - p_end_transformed.r) < 1e-6 - - -def test_component_result_is_immutable_value_type() -> None: - result = Straight.generate(Port(0, 0, 0), 10.0, 2.0) - - with pytest.raises(FrozenInstanceError): - result.length = 42.0 diff --git a/inire/tests/test_congestion.py b/inire/tests/test_congestion.py index 7d3f2eb..3e27511 100644 --- a/inire/tests/test_congestion.py +++ b/inire/tests/test_congestion.py @@ -5,7 +5,6 @@ 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._router import PathFinder from inire.router._search import route_astar from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap @@ -40,30 +39,6 @@ def _build_context( ) -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( - _build_context( - evaluator, - bounds=bounds, - nets=nets, - search=search, - congestion=congestion, - ), - ) - - def _route(context: AStarContext, start: Port, target: Port) -> object: return route_astar( start, diff --git a/inire/tests/test_cost.py b/inire/tests/test_cost.py index ee1de46..681ede2 100644 --- a/inire/tests/test_cost.py +++ b/inire/tests/test_cost.py @@ -46,18 +46,6 @@ def test_cost_calculation() -> None: assert h_away >= h_90 -def test_greedy_h_weight_is_mutable() -> None: - engine = RoutingWorld(clearance=2.0) - danger_map = DangerMap(bounds=(0, 0, 50, 50)) - danger_map.precompute([]) - evaluator = CostEvaluator(engine, danger_map, greedy_h_weight=1.5, bend_penalty=10.0) - - assert evaluator.greedy_h_weight == 1.5 - evaluator.greedy_h_weight = 1.2 - assert evaluator.greedy_h_weight == 1.2 - assert abs(evaluator.h_manhattan(Port(0, 0, 0), Port(10, 10, 0)) - 72.0) < 1e-6 - - def test_proximity_cost_uses_physical_outline_at_outlying_declared_ports() -> None: danger_map = DangerMap((0.5001, -10, 79.4999, 70)) danger_map.precompute([box(77, 42, 78, 43)]) @@ -72,33 +60,6 @@ def test_proximity_cost_uses_physical_outline_at_outlying_declared_ports() -> No assert evaluator.score_component(bend.translate(1, 0), start_port=start.translate(1, 0)) == 1e15 -def test_danger_map_kd_tree_and_cache() -> None: - # Test that KD-Tree based danger map works and uses cache - bounds = (0, 0, 1000, 1000) - dm = DangerMap(bounds, resolution=1.0, safety_threshold=10.0) - - # Square obstacle at (100, 100) to (110, 110) - obstacle = Polygon([(100, 100), (110, 100), (110, 110), (100, 110)]) - dm.precompute([obstacle]) - - # 1. High cost near boundary - cost_near = dm.get_cost(100.5, 100.5) - assert cost_near > 1.0 - - # 2. Zero cost far away - cost_far = dm.get_cost(500, 500) - assert cost_far == 0.0 - - # 3. Check cache usage (internal detail check) - # We can check if calling it again is fast or just verify it returns same result - cost_near_2 = dm.get_cost(100.5, 100.5) - assert cost_near_2 == cost_near - assert len(dm._cost_cache) == 2 - - # 4. Out of bounds - assert dm.get_cost(-1, -1) >= 1e12 - - def test_danger_map_cache_is_instance_local_and_cleared_on_precompute() -> None: obstacle = Polygon([(10, 10), (20, 10), (20, 20), (10, 20)]) dm_a = DangerMap((0, 0, 100, 100)) @@ -146,15 +107,6 @@ def test_danger_map_clips_sampling_without_restarting_spacing_on_diagonal_edges( assert_allclose(sorted(map(tuple, danger.tree.data)), expected, atol=1e-12) -def test_danger_map_samples_only_the_nearby_edge_of_a_large_keepout() -> None: - danger = DangerMap((0, 0, 100, 100)) - danger.precompute([box(90, 20, 100_090, 100_020)]) - - assert danger.tree is not None - assert danger.tree.n < 30 - assert danger.get_cost(85, 40) == 0.04 - - def test_large_perimeter_uses_bounded_exact_index_with_interior_opening() -> None: problem = RoutingProblem((0, 0, 1_100_000, 1_100_000)) hole = box(100, 100, 900, 900) diff --git a/inire/tests/test_example_performance.py b/inire/tests/test_example_performance.py index adf7bfb..eed1355 100644 --- a/inire/tests/test_example_performance.py +++ b/inire/tests/test_example_performance.py @@ -7,15 +7,15 @@ from typing import TYPE_CHECKING import pytest from inire.tests.example_scenarios import ( + EXPECTED_OUTCOMES, SCENARIOS, - ScenarioOutcome, snapshot_example_07_no_warm_start, snapshot_example_07_no_warm_start_seed43, trace_example_07_no_warm_start_seed43, ) if TYPE_CHECKING: - from collections.abc import Callable + from inire.tests.example_scenarios import ScenarioRun RUN_PERFORMANCE = os.environ.get("INIRE_RUN_PERFORMANCE") == "1" @@ -37,38 +37,20 @@ BASELINE_SECONDS = { "example_09_unroutable_best_effort": 0.0056, } -EXPECTED_OUTCOMES = { - "example_01_simple_route": {"total_results": 1, "valid_results": 1, "reached_targets": 1}, - "example_02_congestion_resolution": {"total_results": 3, "valid_results": 3, "reached_targets": 3}, - "example_03_locked_paths": {"total_results": 2, "valid_results": 2, "reached_targets": 2}, - "example_04_sbends_and_radii": {"total_results": 2, "valid_results": 2, "reached_targets": 2}, - "example_05_orientation_stress": {"total_results": 3, "valid_results": 3, "reached_targets": 3}, - "example_06_bend_collision_models": {"total_results": 3, "valid_results": 3, "reached_targets": 3}, - "example_07_large_scale_routing": {"total_results": 10, "valid_results": 10, "reached_targets": 10}, - "example_08_custom_bend_geometry": {"total_results": 2, "valid_results": 2, "reached_targets": 2}, - "example_09_unroutable_best_effort": {"total_results": 1, "valid_results": 0, "reached_targets": 0}, -} - - -def _assert_expected_outcome(name: str, outcome: ScenarioOutcome) -> None: - _, total_results, valid_results, reached_targets = outcome - expected = EXPECTED_OUTCOMES[name] - assert total_results == expected["total_results"] - assert valid_results == expected["valid_results"] - assert reached_targets == expected["reached_targets"] - @pytest.mark.performance -@pytest.mark.skipif(not RUN_PERFORMANCE, reason="set INIRE_RUN_PERFORMANCE=1 to run runtime regression checks") @pytest.mark.parametrize("scenario", SCENARIOS, ids=[name for name, _ in SCENARIOS]) -def test_example_like_runtime_regression(scenario: tuple[str, Callable[[], ScenarioOutcome]]) -> None: +def test_example_outcomes_and_optional_runtime(scenario: tuple[str, ScenarioRun]) -> None: name, run = scenario timings = [] - for _ in range(PERFORMANCE_REPEATS): + for _ in range(PERFORMANCE_REPEATS if RUN_PERFORMANCE else 1): outcome = run() - _assert_expected_outcome(name, outcome) + assert outcome[1:] == EXPECTED_OUTCOMES[name] timings.append(outcome[0]) + if not RUN_PERFORMANCE: + return + median_runtime = statistics.median(timings) assert median_runtime <= BASELINE_SECONDS[name] * REGRESSION_FACTOR, ( f"{name} median runtime {median_runtime:.4f}s exceeded " @@ -78,8 +60,7 @@ def test_example_like_runtime_regression(scenario: tuple[str, Callable[[], Scena @pytest.mark.performance -@pytest.mark.skipif(not RUN_PERFORMANCE, reason="set INIRE_RUN_PERFORMANCE=1 to run runtime regression checks") -def test_example_07_no_warm_start_runtime_regression() -> None: +def test_example_07_no_warm_start_outcome_and_optional_runtime() -> None: snapshot = snapshot_example_07_no_warm_start() assert snapshot.total_results == 10 @@ -87,11 +68,17 @@ def test_example_07_no_warm_start_runtime_regression() -> None: assert snapshot.reached_targets == 10 assert snapshot.metrics.warm_start_paths_built == 0 assert snapshot.metrics.warm_start_paths_used == 0 - assert snapshot.duration_s <= NO_WARM_START_REGRESSION_SECONDS, ( - "example_07_large_scale_routing_no_warm_start runtime " - f"{snapshot.duration_s:.4f}s exceeded guardrail " - f"{NO_WARM_START_REGRESSION_SECONDS:.1f}s" - ) + assert snapshot.metrics.pair_local_search_pairs_considered >= 1 + assert snapshot.metrics.pair_local_search_accepts >= 1 + assert snapshot.metrics.pair_local_search_nodes_expanded <= 128 + assert snapshot.metrics.nodes_expanded <= 2500 + assert snapshot.metrics.congestion_check_calls <= 6000 + if RUN_PERFORMANCE: + assert snapshot.duration_s <= NO_WARM_START_REGRESSION_SECONDS, ( + "example_07_large_scale_routing_no_warm_start runtime " + f"{snapshot.duration_s:.4f}s exceeded guardrail " + f"{NO_WARM_START_REGRESSION_SECONDS:.1f}s" + ) @pytest.mark.performance diff --git a/inire/tests/test_example_regressions.py b/inire/tests/test_example_regressions.py index 3c5f6b7..30c768a 100644 --- a/inire/tests/test_example_regressions.py +++ b/inire/tests/test_example_regressions.py @@ -1,83 +1,20 @@ -from dataclasses import replace import pytest -from shapely.geometry import Polygon, box +from shapely.geometry import Polygon from inire import ( CongestionOptions, - DiagnosticsOptions, NetSpec, - ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route, ) -from inire.router._stack import build_routing_stack -from inire.seeds import Bend90Seed, PathSeed, StraightSeed -from inire.tests.example_scenarios import ( - SCENARIOS, - _build_example_07_variant_stack, - _build_example_08_workers, - snapshot_example_05, - snapshot_example_07_no_warm_start, - trace_example_07_no_warm_start, -) -EXPECTED_OUTCOMES = { - "example_01_simple_route": (1, 1, 1), - "example_02_congestion_resolution": (3, 3, 3), - "example_03_locked_paths": (2, 2, 2), - "example_04_sbends_and_radii": (2, 2, 2), - "example_05_orientation_stress": (3, 3, 3), - "example_06_bend_collision_models": (3, 3, 3), - "example_07_large_scale_routing": (10, 10, 10), - "example_08_custom_bend_geometry": (2, 2, 2), - "example_09_unroutable_best_effort": (1, 0, 0), -} - - -@pytest.mark.parametrize(("name", "run"), SCENARIOS, ids=[name for name, _ in SCENARIOS]) -def test_examples_match_legacy_expected_outcomes(name: str, run) -> None: - outcome = run() - assert outcome[1:] == EXPECTED_OUTCOMES[name] - - -def test_example_05_avoids_dynamic_tree_rebuilds() -> None: - snapshot = snapshot_example_05() - - assert snapshot.valid_results == 3 - assert snapshot.metrics.dynamic_tree_rebuilds == 0 - - -def test_example_07_variant_uses_one_configuration() -> None: - evaluator, _, finder = _build_example_07_variant_stack(num_nets=10, seed=42, warm_start_enabled=False) - world = evaluator.collision_engine - - assert finder.context.options.objective == evaluator.default_weights - assert finder.context.problem.clearance == world.clearance == 6.0 - assert finder.context.problem.static_obstacles == tuple(world.iter_static_geometries()) - - -def test_example_07_no_warm_start_canary_improves_validity() -> None: - snapshot = snapshot_example_07_no_warm_start() - - assert snapshot.total_results == 10 - assert snapshot.reached_targets == 10 - assert snapshot.valid_results == 10 - assert snapshot.metrics.warm_start_paths_built == 0 - assert snapshot.metrics.warm_start_paths_used == 0 - assert snapshot.metrics.pair_local_search_pairs_considered >= 1 - assert snapshot.metrics.pair_local_search_accepts >= 1 - assert snapshot.metrics.pair_local_search_nodes_expanded <= 128 - assert snapshot.metrics.nodes_expanded <= 2500 - assert snapshot.metrics.congestion_check_calls <= 6000 - - -def test_example_07_no_warm_start_trace_finishes_without_conflict_edges() -> None: - run = trace_example_07_no_warm_start() +def test_example_07_no_warm_start_trace_finishes_without_conflict_edges(example_07_no_warm_start_trace) -> None: + run = example_07_no_warm_start_trace assert len(run.results_by_net) == 10 assert sum(result.is_valid for result in run.results_by_net.values()) == 10 @@ -92,149 +29,6 @@ def test_example_07_no_warm_start_trace_finishes_without_conflict_edges() -> Non assert final_entry.conflict_edges == () -def test_example_06_clipped_bbox_margin_keeps_legacy_seed_replayable() -> None: - bounds = (-20, -20, 170, 170) - obstacles = ( - Polygon([(40, 110), (60, 110), (60, 130), (40, 130)]), - Polygon([(40, 60), (60, 60), (60, 80), (40, 80)]), - Polygon([(40, 10), (60, 10), (60, 30), (40, 30)]), - ) - problem = RoutingProblem( - bounds=bounds, - nets=(NetSpec("clipped_model", Port(10, 20, 0), Port(90, 40, 90), width=2.0),), - static_obstacles=obstacles, - ) - common_kwargs = { - "objective": ObjectiveWeights(bend_penalty=50.0, sbend_penalty=150.0), - "congestion": CongestionOptions(use_tiered_strategy=False), - } - no_margin = route( - problem, - options=RoutingOptions( - search=SearchOptions( - bend_radii=(10.0,), - bend_collision_type="clipped_bbox", - ), - **common_kwargs, - ), - ).results_by_net["clipped_model"] - legacy_seed = PathSeed( - ( - StraightSeed(5.0), - Bend90Seed(10.0, "CW"), - Bend90Seed(10.0, "CCW"), - StraightSeed(45.0), - Bend90Seed(10.0, "CCW"), - StraightSeed(30.0), - ) - ) - simulation = replace(problem, initial_paths={"clipped_model": legacy_seed}) - legacy_options = RoutingOptions( - search=SearchOptions(node_limit=0, bend_radii=(10.0,), bend_collision_type="clipped_bbox", bend_clip_margin=1.0), - **common_kwargs, - ) - legacy = route(simulation, options=legacy_options).results_by_net["clipped_model"] - - assert no_margin.is_valid - assert legacy.is_valid - assert legacy.as_seed() == legacy_seed - - -def test_example_07_reduced_bottleneck_uses_adaptive_greedy_callback() -> None: - bounds = (0, 0, 500, 300) - obstacles = ( - box(220, 0, 280, 100), - box(220, 200, 280, 300), - ) - netlist = { - "net_00": (Port(30, 130, 0), Port(470, 60, 0)), - "net_01": (Port(30, 140, 0), Port(470, 120, 0)), - "net_02": (Port(30, 150, 0), Port(470, 180, 0)), - "net_03": (Port(30, 160, 0), Port(470, 240, 0)), - } - problem = RoutingProblem( - bounds=bounds, - nets=tuple(NetSpec(net_id, start, target, width=2.0) for net_id, (start, target) in netlist.items()), - static_obstacles=obstacles, - clearance=6.0, - ) - options = RoutingOptions( - search=SearchOptions( - node_limit=200000, - bend_radii=(30.0,), - sbend_radii=(30.0,), - greedy_h_weight=1.5, - bend_clip_margin=10.0, - ), - objective=ObjectiveWeights( - unit_length_cost=0.1, - bend_penalty=100.0, - sbend_penalty=400.0, - ), - congestion=CongestionOptions( - max_iterations=6, - base_penalty=100.0, - multiplier=1.4, - net_order="shortest", - shuffle_nets=True, - seed=42, - ), - diagnostics=DiagnosticsOptions(capture_expanded=False), - ) - stack = build_routing_stack(problem, options) - evaluator = stack.evaluator - finder = stack.finder - weights: list[float] = [] - - def iteration_callback(iteration: int, current_results: dict[str, object]) -> None: - _ = current_results - new_greedy = max(1.1, 1.5 - ((iteration + 1) / 10.0) * 0.4) - evaluator.greedy_h_weight = new_greedy - weights.append(new_greedy) - finder.metrics.reset_per_route() - - results = finder.route_all(iteration_callback=iteration_callback) - - assert weights == [1.46] - assert evaluator.greedy_h_weight == 1.46 - assert all(result.is_valid for result in results.values()) - assert all(result.reached_target for result in results.values()) - - -def test_example_06_custom_geometry_can_be_true_physical_geometry() -> None: - bounds = (-20, -20, 170, 170) - obstacles = ( - Polygon([(40, 110), (60, 110), (60, 130), (40, 130)]), - Polygon([(40, 60), (60, 60), (60, 80), (40, 80)]), - Polygon([(40, 10), (60, 10), (60, 30), (40, 30)]), - ) - custom_poly = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - result = route( - RoutingProblem( - bounds=bounds, - nets=(NetSpec("custom_geometry", Port(10, 20, 0), Port(90, 40, 90), width=2.0),), - static_obstacles=obstacles, - ), - options=RoutingOptions( - search=SearchOptions( - bend_radii=(10.0,), - bend_physical_geometry=custom_poly, - bend_proxy_geometry=custom_poly, - ), - objective=ObjectiveWeights(bend_penalty=50.0, sbend_penalty=150.0), - congestion=CongestionOptions(use_tiered_strategy=False), - ), - ).results_by_net["custom_geometry"] - - assert result.is_valid - bends = [component for component in result.path if component.move_type == "bend90"] - assert bends - assert all( - component.collision_geometry[0].symmetric_difference(component.physical_geometry[0]).area < 1e-6 - for component in bends - ) - - def test_custom_proxy_without_physical_geometry_warns_and_keeps_arc_geometry() -> None: custom_proxy = Polygon([(0, -11), (11, -11), (11, 0), (0, 0)]) @@ -263,21 +57,3 @@ def test_custom_proxy_without_physical_geometry_warns_and_keeps_arc_geometry() - component.collision_geometry[0].symmetric_difference(component.physical_geometry[0]).area > 1e-6 for component in bends ) - - -def test_example_08_custom_geometry_runs_in_separate_sessions() -> None: - standard_worker, custom_worker = _build_example_08_workers() - assert standard_worker.context.cost_evaluator.collision_engine is not custom_worker.context.cost_evaluator.collision_engine - standard = standard_worker.route_all() - custom = custom_worker.route_all() - - assert standard["standard_arc"].is_valid - assert standard["standard_arc"].reached_target - assert custom["custom_geometry_and_proxy"].is_valid - assert custom["custom_geometry_and_proxy"].reached_target - custom_bends = [component for component in custom["custom_geometry_and_proxy"].path if component.move_type == "bend90"] - assert custom_bends - assert all( - component.collision_geometry[0].symmetric_difference(component.physical_geometry[0]).area > 1e-6 - for component in custom_bends - ) diff --git a/inire/tests/test_layout.py b/inire/tests/test_layout.py index 7ed6618..90a1a98 100644 --- a/inire/tests/test_layout.py +++ b/inire/tests/test_layout.py @@ -46,35 +46,26 @@ def test_replay_verifies_actual_concentric_bend_clearance(outer_radius, valid) - assert result.report.dynamic_collision_count == int(not valid) -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize(("start_x", "y", "valid"), [(10, 22, False), (40, 22, False), (40, 23, True)]) -def test_imported_fixed_routes_hold_clearance_at_edges_and_vertices(mode, start_x, y, valid) -> None: - net = NetSpec("new", Port(start_x, y, 0), Port(90, y, 0)) - fixed = FixedRoute("existing", (box(10, 19, 40, 21),)) - problem = RoutingProblem((0, 0, 100, 50), (net,), clearance=0, fixed_routes=(fixed,)) - options = RoutingOptions( - search=SearchOptions(node_limit=20, bend_radii=(), sbend_radii=()), - topology=TopologyOptions(mode=mode), +def test_imported_fixed_routes_hold_clearance_at_edges_and_vertices() -> None: + nets = ( + NetSpec("edge", Port(10, 22, 0), Port(90, 22, 0)), + NetSpec("vertex", Port(40, 62, 0), Port(90, 62, 0)), + NetSpec("clear", Port(40, 83, 0), Port(90, 83, 0)), ) + existing = FixedRoute("existing", (box(10, 19, 40, 21), box(10, 59, 40, 61), box(10, 79, 40, 81))) + problem = RoutingProblem((0, 0, 100, 100), nets, clearance=0, fixed_routes=(existing,)) + options = RoutingOptions(search=SearchOptions(node_limit=20, bend_radii=(), sbend_radii=())) results = route(problem, options=options).results_by_net - assert set(results) == {"new"} - assert results["new"].is_valid is valid + assert set(results) == {net.net_id for net in nets} + assert not results["edge"].is_valid + assert not results["vertex"].is_valid + assert results["clear"].is_valid -def test_fixed_route_from_result_preserves_polygon_and_owner() -> None: - net = NetSpec("first", Port(10, 20, 0), Port(90, 20, 0)) - problem = RoutingProblem((0, 0, 100, 50), (net,)) - fixed = FixedRoute.from_result(route(problem).results_by_net["first"]) - assert fixed.net_id == net.net_id - assert fixed.polygons[0].equals(box(10, 19, 90, 21)) - with pytest.raises(ValueError, match="Duplicate active or fixed"): - replace(problem, fixed_routes=(fixed,)) - - -@pytest.mark.parametrize("fixed_bounds", [(23.9, 15.6, 24.4, 16.1), (25.15, 14.75, 25.25, 14.85)], ids=["overlap", "insufficient-gap"]) -def test_lattice_bend_admission_checks_physical_clearance_to_fixed_route(fixed_bounds) -> None: +def test_lattice_bend_admission_checks_physical_clearance_to_fixed_route() -> None: + fixed_bounds = (25.15, 14.75, 25.25, 14.85) net = NetSpec("active", Port(10, 10, 0), Port(30, 30, 90)) fixed = FixedRoute("locked", (box(*fixed_bounds),)) problem = RoutingProblem((0, 0, 50, 50), (net,), clearance=1, fixed_routes=(fixed,)) @@ -91,8 +82,13 @@ def test_lattice_bend_admission_checks_physical_clearance_to_fixed_route(fixed_b assert result.as_seed() == PathSeed((StraightSeed(10), Bend90Seed(10, "CCW"), StraightSeed(10))) -@pytest.mark.parametrize("fixed", [False, True], ids=["keepout", "fixed-net"]) -@pytest.mark.parametrize(("clearance", "valid"), [(0.25, True), (0.5, False)]) +@pytest.mark.parametrize( + ('fixed', 'clearance', 'valid'), + [ + (False, 0.25, True), + (True, 0.5, False), + ], +) def test_imported_polygon_precision_preserves_fractional_clearance(fixed, clearance, valid) -> None: net = NetSpec("signal", Port(10, 20, 0), Port(90, 20, 0), 1.5) obstacle = box(20, 21, 30, 24) @@ -111,31 +107,6 @@ def test_imported_polygon_precision_preserves_fractional_clearance(fixed, cleara assert reports[0] == reports[1] -@pytest.mark.parametrize(("pitch", "valid"), [(28000, False), (32000, False), (36000, True)]) -def test_cpw_envelope_clearance_and_signal_recipe_replay(pitch, valid) -> None: - nets = tuple(NetSpec(f"cpw{i}", Port(10000, 30000 + i * pitch, 0), Port(210000, 30000 + i * pitch, 0), 29500) - for i in range(2)) - seeds = {net.net_id: PathSeed((StraightSeed(200000),)) for net in nets} - problem = RoutingProblem((0, 0, 220000, 100000), nets, initial_paths=seeds, clearance=3000) - - envelopes = route(problem, options=_REPLAY).results_by_net - - assert all(envelope.is_valid for envelope in envelopes.values()) == valid - if valid: - signals = replace( - problem, - nets=tuple(replace(net, width=15500) for net in nets), - initial_paths={key: result.as_seed() for key, result in envelopes.items()}, - ) - replay = route(signals, options=_REPLAY) - assert replay.metrics.nodes_expanded == 0 - for net in signals.nets: - result = replay.results_by_net[net.net_id] - assert result.is_valid - assert result.effective_net == net - assert result.as_seed() == envelopes[net.net_id].as_seed() - - def test_profile_options_apply_to_active_search_and_seed_replay() -> None: flux = NetSpec("flux", Port(35000, 20000, 0), Port(50000, 35000, 90), 29500) feed = NetSpec("feed", Port(100000, 20000, 0), Port(115000, 35000, 90), 29500) @@ -165,21 +136,6 @@ def test_profile_options_apply_to_active_search_and_seed_replay() -> None: assert recovered["feed"].report.seed_error == "Initial path for 'feed' uses radius 15000 outside bend_radii" -@pytest.mark.parametrize(("second_y", "valid"), [(22, False), (23, True)]) -def test_profile_reserves_replayed_net_against_zero_clearance_contact(second_y, valid) -> None: - first = NetSpec("first", Port(10, 20, 0), Port(90, 20, 0)) - second = NetSpec("second", Port(10, second_y, 0), Port(90, second_y, 0)) - seeds = {net.net_id: PathSeed((StraightSeed(80),)) for net in (first, second)} - problem = RoutingProblem((0, 0, 100, 50), (first, second), initial_paths=seeds, clearance=0) - - results = route_profiles(problem, [(("first",), _REPLAY), (("second",), _REPLAY)]) - - assert results["first"].is_valid - assert results["second"].is_valid is valid - if valid: - assert results["second"].as_seed() == seeds["second"] - - def test_independent_layer_outputs_retain_assignment_and_connectivity() -> None: silicon = NetSpec("si", Port(1000, 10000, 0), Port(19000, 10000, 0), 500) nitride = NetSpec("sin", Port(10000, 1000, 90), Port(10000, 19000, 90), 750) @@ -212,6 +168,64 @@ def test_authored_template_lengths_are_used_for_candidate_acceptance() -> None: assert result.report.total_length == 18.7 +def test_routing_snapshots_stay_read_only_and_serialize() -> None: + track = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) + seeds = {"track": PathSeed((StraightSeed(80),))} + problem = RoutingProblem((0, 0, 100, 50), (track,), initial_paths=seeds) + seeds.clear() + assert tuple(problem.initial_paths) == ("track",) + + run = route(problem, options=_REPLAY, iteration_callback=lambda _, results: results.clear()) + with pytest.raises(TypeError): + problem.initial_paths["track"] = PathSeed(()) + with pytest.raises(TypeError): + del run.results_by_net["track"] + with pytest.raises(TypeError): + run.results_by_net.clear() + assert run.results_by_net["track"].is_valid + + for copy in (deepcopy, lambda value: pickle.loads(pickle.dumps(value))): + assert copy(problem) == problem + restored = copy(run) + assert restored == run + with pytest.raises(TypeError): + del restored.results_by_net["track"] + source = dict(run.results_by_net) + replacement = replace(run, results_by_net=source) + source.clear() + assert replacement.results_by_net == run.results_by_net + + problem_data = loads(dumps(asdict(problem), default=str)) + result_data = loads(dumps(asdict(run), default=str)) + assert problem_data["initial_paths"]["track"]["segments"] == [{"length": 80}] + assert result_data["results_by_net"]["track"]["report"]["total_length"] == 80 + assert result_data["results_by_net"]["track"]["path"][0]["move_spec"] == {"length": 80} + + +def test_cpw_envelope_clearance_and_signal_recipe_replay() -> None: + tracks = (("tight_a", 30000), ("tight_b", 62000), ("clear_a", 120000), ("clear_b", 156000)) + nets = tuple(NetSpec(name, Port(10000, y, 0), Port(210000, y, 0), 29500) for name, y in tracks) + seeds = {net.net_id: PathSeed((StraightSeed(200000),)) for net in nets} + problem = RoutingProblem((0, 0, 220000, 180000), nets, initial_paths=seeds, clearance=3000) + + envelopes = route(problem, options=_REPLAY).results_by_net + assert {net_id for net_id, envelope in envelopes.items() if envelope.is_valid} == {"clear_a", "clear_b"} + + signals = replace( + problem, + nets=tuple(replace(net, width=15500) for net in nets), + initial_paths={net_id: envelope.as_seed() for net_id, envelope in envelopes.items()}, + ) + replay = route(signals, options=_REPLAY) + + assert replay.metrics.nodes_expanded == 0 + for net in signals.nets: + result = replay.results_by_net[net.net_id] + assert result.is_valid + assert result.effective_net == net + assert result.as_seed() == envelopes[net.net_id].as_seed() + + def test_authored_sbend_length_survives_seed_replay() -> None: polygon = box(0, -1, 80, 41).intersection( box(0, -1, 80, 1).union(box(1, 0, 79, 41)).union(box(79, 39, 80, 41)), @@ -229,50 +243,3 @@ def test_authored_sbend_length_survives_seed_replay() -> None: options=replace(options, search=replace(search, node_limit=0)), ).results_by_net["shift"] assert preserves_length(replay, 95, tolerance=0) - - -def test_routing_inputs_and_results_are_detached_snapshots() -> None: - track = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) - seeds = {"track": PathSeed((StraightSeed(80),))} - problem = RoutingProblem((0, 0, 100, 50), (track,), initial_paths=seeds) - seeds.clear() - assert tuple(problem.initial_paths) == ("track",) - - run = route(problem, options=_REPLAY, iteration_callback=lambda _, results: results.clear()) - with pytest.raises(TypeError): - problem.initial_paths["track"] = PathSeed(()) - with pytest.raises(TypeError): - del run.results_by_net["track"] - with pytest.raises(TypeError): - run.results_by_net.clear() - assert run.results_by_net["track"].is_valid - - -def test_read_only_snapshots_survive_python_copy_and_pickle() -> None: - track = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) - problem = RoutingProblem((0, 0, 100, 50), (track,)) - run = route(problem) - for copy in (deepcopy, lambda value: pickle.loads(pickle.dumps(value))): - assert copy(problem) == problem - restored = copy(run) - assert restored == run - with pytest.raises(TypeError): - del restored.results_by_net["track"] - source = dict(run.results_by_net) - replacement = replace(run, results_by_net=source) - source.clear() - assert replacement.results_by_net == run.results_by_net - - -def test_asdict_serializes_snapshot_entries_as_structured_data() -> None: - net = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) - seed = PathSeed((StraightSeed(80),)) - problem = RoutingProblem((0, 0, 100, 50), (net,), initial_paths={net.net_id: seed}) - run = route(problem, options=_REPLAY) - - problem_data = loads(dumps(asdict(problem), default=str)) - result_data = loads(dumps(asdict(run), default=str)) - - assert problem_data["initial_paths"]["track"]["segments"] == [{"length": 80}] - assert result_data["results_by_net"]["track"]["report"]["total_length"] == 80 - assert result_data["results_by_net"]["track"]["path"][0]["move_spec"] == {"length": 80} diff --git a/inire/tests/test_pathfinder.py b/inire/tests/test_pathfinder.py index dc2e721..1505319 100644 --- a/inire/tests/test_pathfinder.py +++ b/inire/tests/test_pathfinder.py @@ -105,8 +105,8 @@ def _build_manual_path(start: Port, width: float, clearance: float, steps: list[ return path -@pytest.mark.parametrize("search_raises", [False, True], ids=["success", "exception"]) -def test_frontier_replay_restores_installed_path_and_metrics(monkeypatch: pytest.MonkeyPatch, search_raises: bool) -> None: +def test_frontier_replay_restores_installed_path_and_metrics(monkeypatch: pytest.MonkeyPatch) -> None: + search_raises = True world = RoutingWorld(clearance=2.0) danger_map = DangerMap(bounds=DEFAULT_BOUNDS) finder = _build_pathfinder( @@ -219,8 +219,8 @@ def test_route_all_refreshes_static_caches_after_static_topology_changes() -> No assert [(comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in auto_result.path] == [ (comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in manual_result.path ] -@pytest.mark.parametrize("max_windows", [1, None]) -def test_refine_path_handles_same_orientation_lateral_offset(max_windows: int | None) -> None: +def test_refine_path_handles_same_orientation_lateral_offset() -> None: + max_windows = 1 engine = RoutingWorld(clearance=2.0) danger_map = DangerMap(bounds=(-20, -20, 120, 120)) danger_map.precompute([]) @@ -271,53 +271,6 @@ def test_refine_path_handles_same_orientation_lateral_offset(max_windows: int | assert windows > 1 -def test_refine_path_can_simplify_subpath_with_different_global_orientation() -> None: - engine = RoutingWorld(clearance=2.0) - danger_map = DangerMap(bounds=(-20, -20, 120, 120)) - danger_map.precompute([]) - evaluator = CostEvaluator(engine, danger_map, bend_penalty=250.0, sbend_penalty=500.0) - pf = _build_pathfinder( - evaluator, - netlist={"net": (Port(0, 0, 0), Port(65, 30, 90))}, - net_widths={"net": 2.0}, - bounds=(-20, -20, 120, 120), - bend_radii=[5.0, 10.0], - enabled=True, - ) - - start = Port(0, 0, 0) - width = 2.0 - path = _build_manual_path( - start, - width, - engine.clearance, - [ - ("B", "CCW"), - ("S", 10.0), - ("B", "CW"), - ("S", 20.0), - ("B", "CW"), - ("S", 10.0), - ("B", "CCW"), - ("S", 10.0), - ("B", "CCW"), - ("S", 5.0), - ("B", "CW"), - ("B", "CCW"), - ("S", 10.0), - ], - ) - target = path[-1].end_port - - refined = pf.refiner.refine_path("net", start, width, path) - - assert target == Port(65, 30, 90) - assert sum(1 for comp in path if comp.move_type == "bend90") == 7 - assert sum(1 for comp in refined if comp.move_type == "bend90") == 5 - assert refined[-1].end_port == target - assert pf.refiner.path_cost(refined) < pf.refiner.path_cost(path) - - def test_changed_window_checks_for_collision_with_the_unchanged_prefix() -> None: world = RoutingWorld(clearance=2.0) start = Port(10, -10, 90) diff --git a/inire/tests/test_performance_reporting.py b/inire/tests/test_performance_reporting.py index e0c5c56..f5cd1c3 100644 --- a/inire/tests/test_performance_reporting.py +++ b/inire/tests/test_performance_reporting.py @@ -3,56 +3,13 @@ import subprocess import sys from pathlib import Path -from inire.tests.example_scenarios import snapshot_example_01 +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 -def test_snapshot_example_01_exposes_metrics() -> None: - snapshot = snapshot_example_01() - - assert snapshot.name == "example_01_simple_route" - assert snapshot.total_results == 1 - assert snapshot.valid_results == 1 - assert snapshot.reached_targets == 1 - assert snapshot.metrics.route_iterations >= 1 - assert snapshot.metrics.nets_routed >= 1 - assert snapshot.metrics.nodes_expanded > 0 - assert snapshot.metrics.score_component_calls >= 0 - assert snapshot.metrics.danger_map_lookup_calls >= 0 - assert snapshot.metrics.move_cache_abs_misses >= 0 - assert snapshot.metrics.guidance_match_moves >= 0 - assert snapshot.metrics.guidance_match_moves_straight >= 0 - assert snapshot.metrics.guidance_match_moves_bend90 >= 0 - assert snapshot.metrics.guidance_match_moves_sbend >= 0 - assert snapshot.metrics.guidance_bonus_applied >= 0.0 - assert snapshot.metrics.guidance_bonus_applied_straight >= 0.0 - assert snapshot.metrics.guidance_bonus_applied_bend90 >= 0.0 - assert snapshot.metrics.guidance_bonus_applied_sbend >= 0.0 - assert snapshot.metrics.ray_cast_calls >= 0 - assert snapshot.metrics.ray_cast_calls_expand_forward >= 0 - assert snapshot.metrics.dynamic_tree_rebuilds >= 0 - assert snapshot.metrics.visibility_corner_index_builds >= 0 - assert snapshot.metrics.visibility_builds >= 0 - assert snapshot.metrics.congestion_grid_span_cache_hits >= 0 - assert snapshot.metrics.congestion_grid_span_cache_misses >= 0 - assert snapshot.metrics.congestion_candidate_nets >= 0 - assert snapshot.metrics.congestion_net_envelope_cache_hits >= 0 - assert snapshot.metrics.congestion_net_envelope_cache_misses >= 0 - assert snapshot.metrics.congestion_grid_net_cache_hits >= 0 - assert snapshot.metrics.congestion_grid_net_cache_misses >= 0 - assert snapshot.metrics.congestion_lazy_resolutions >= 0 - assert snapshot.metrics.congestion_lazy_requeues >= 0 - assert snapshot.metrics.congestion_candidate_ids >= 0 - assert snapshot.metrics.verify_dynamic_candidate_nets >= 0 - assert snapshot.metrics.refinement_candidates_verified >= 0 - assert snapshot.metrics.pair_local_search_pairs_considered >= 0 - assert snapshot.metrics.pair_local_search_attempts >= 0 - assert snapshot.metrics.pair_local_search_accepts >= 0 - assert snapshot.metrics.pair_local_search_nodes_expanded >= 0 - assert snapshot.metrics.late_phase_capped_nets >= 0 - assert snapshot.metrics.late_phase_capped_fallbacks >= 0 - - -def test_record_performance_baseline_script_writes_selected_scenario(tmp_path: Path) -> None: +def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario(tmp_path: Path) -> None: repo_root = Path(__file__).resolve().parents[2] script_path = repo_root / "scripts" / "record_performance_baseline.py" @@ -74,79 +31,22 @@ def test_record_performance_baseline_script_writes_selected_scenario(tmp_path: P assert [entry["name"] for entry in payload["scenarios"]] == ["example_01_simple_route"] assert (tmp_path / "performance.md").exists() - -def test_diff_performance_baseline_script_writes_selected_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - record_script = repo_root / "scripts" / "record_performance_baseline.py" - diff_script = repo_root / "scripts" / "diff_performance_baseline.py" - baseline_dir = tmp_path / "baseline" - baseline_dir.mkdir() - output_path = tmp_path / "diff.md" - + output = tmp_path / "diff.md" + log = tmp_path / "optimization.md" subprocess.run( [ sys.executable, - str(record_script), - "--output-dir", - str(baseline_dir), - "--scenario", - "example_01_simple_route", - ], - check=True, - ) - subprocess.run( - [ - sys.executable, - str(diff_script), + str(repo_root / "scripts" / "diff_performance_baseline.py"), "--baseline", - str(baseline_dir / "performance_baseline.json"), + str(tmp_path / "performance_baseline.json"), "--include-performance-only", "--scenario", "example_01_simple_route", - "--output", - str(output_path), - ], - check=True, - ) - - report = output_path.read_text() - assert "Performance Baseline Diff" in report - assert "example_01_simple_route" in report - - -def test_diff_performance_baseline_script_can_append_measurement_log(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - record_script = repo_root / "scripts" / "record_performance_baseline.py" - diff_script = repo_root / "scripts" / "diff_performance_baseline.py" - baseline_dir = tmp_path / "baseline" - baseline_dir.mkdir() - log_path = tmp_path / "optimization.md" - - subprocess.run( - [ - sys.executable, - str(record_script), - "--output-dir", - str(baseline_dir), "--scenario", - "example_01_simple_route", - ], - check=True, - ) - subprocess.run( - [ - sys.executable, - str(diff_script), - "--baseline", - str(baseline_dir / "performance_baseline.json"), - "--include-performance-only", - "--scenario", - "example_01_simple_route", + "example_07_large_scale_routing_no_warm_start", "--metric", "duration_s", "--metric", - "valid_results", - "--metric", "nodes_expanded", "--metric", "visibility_corner_index_builds", @@ -154,61 +54,23 @@ def test_diff_performance_baseline_script_can_append_measurement_log(tmp_path: P "Step 0 - Baseline", "--notes", "Tooling smoke test.", - "--log", - str(log_path), - ], - check=True, - ) - - report = log_path.read_text() - assert "Step 0 - Baseline" in report - assert "Tooling smoke test." in report - assert "| example_01_simple_route | duration_s |" in report - assert "| example_01_simple_route | valid_results |" in report - assert "| example_01_simple_route | visibility_corner_index_builds |" in report - - -def test_diff_performance_baseline_script_renders_current_metrics_for_added_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - record_script = repo_root / "scripts" / "record_performance_baseline.py" - diff_script = repo_root / "scripts" / "diff_performance_baseline.py" - baseline_dir = tmp_path / "baseline" - baseline_dir.mkdir() - output_path = tmp_path / "diff_added.md" - - subprocess.run( - [ - sys.executable, - str(record_script), - "--output-dir", - str(baseline_dir), - "--scenario", - "example_01_simple_route", - ], - check=True, - ) - subprocess.run( - [ - sys.executable, - str(diff_script), - "--baseline", - str(baseline_dir / "performance_baseline.json"), - "--include-performance-only", - "--scenario", - "example_07_large_scale_routing_no_warm_start", - "--metric", - "duration_s", - "--metric", - "nodes_expanded", "--output", - str(output_path), + str(output), + "--log", + str(log), ], check=True, ) - report = output_path.read_text() + report = output.read_text() + assert "| example_01_simple_route | duration_s |" in report + assert "| example_01_simple_route | visibility_corner_index_builds |" in report assert "| example_07_large_scale_routing_no_warm_start | duration_s | - |" in report assert "| example_07_large_scale_routing_no_warm_start | nodes_expanded | - |" in report + entry = log.read_text() + assert "Step 0 - Baseline" in entry + assert "Tooling smoke test." in entry + assert report.rstrip() in entry def test_record_conflict_trace_script_writes_selected_scenario(tmp_path: Path) -> None: @@ -234,94 +96,41 @@ def test_record_conflict_trace_script_writes_selected_scenario(tmp_path: Path) - assert (tmp_path / "conflict_trace.md").exists() -def test_record_conflict_trace_script_supports_performance_only_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - script_path = repo_root / "scripts" / "record_conflict_trace.py" +@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"], +) +def test_record_trace_reports_support_a_performance_only_scenario( + report, generate, heading, tmp_path, monkeypatch, example_07_no_warm_start_trace, +) -> None: + name = trace_recording.NO_WARM_START_SCENARIOS[0] + registry = dict(trace_recording.TRACE_PERFORMANCE_SCENARIO_RUNS) + assert name in registry + registry[name] = lambda: example_07_no_warm_start_trace + monkeypatch.setattr(trace_recording, "TRACE_PERFORMANCE_SCENARIO_RUNS", tuple(registry.items())) + monkeypatch.setattr(sys, "argv", [f"record_{report}", "--output-dir", str(tmp_path), "--scenario", name]) - subprocess.run( - [ - sys.executable, - str(script_path), - "--output-dir", - str(tmp_path), - "--scenario", - "example_07_large_scale_routing_no_warm_start", - ], - check=True, - ) + generate() - payload = json.loads((tmp_path / "conflict_trace.json").read_text()) - assert [entry["name"] for entry in payload["scenarios"]] == ["example_07_large_scale_routing_no_warm_start"] - - -def test_record_frontier_trace_script_writes_selected_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - script_path = repo_root / "scripts" / "record_frontier_trace.py" - - subprocess.run( - [ - sys.executable, - str(script_path), - "--output-dir", - str(tmp_path), - "--scenario", - "example_05_orientation_stress", - ], - check=True, - ) - - payload = json.loads((tmp_path / "frontier_trace.json").read_text()) + payload = json.loads((tmp_path / f"{report}.json").read_text()) assert payload["generated_at"] - assert payload["generator"] == "scripts/record_frontier_trace.py" - assert [entry["name"] for entry in payload["scenarios"]] == ["example_05_orientation_stress"] - assert (tmp_path / "frontier_trace.md").exists() - - -def test_record_iteration_trace_script_writes_selected_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - script_path = repo_root / "scripts" / "record_iteration_trace.py" - - subprocess.run( - [ - sys.executable, - str(script_path), - "--scenario", - "example_07_large_scale_routing_no_warm_start", - "--output-dir", - str(tmp_path), - ], - check=True, - ) - - payload = json.loads((tmp_path / "iteration_trace.json").read_text()) - assert payload["generated_at"] - assert payload["generator"] == "scripts/record_iteration_trace.py" - assert [entry["name"] for entry in payload["scenarios"]] == ["example_07_large_scale_routing_no_warm_start"] - assert (tmp_path / "iteration_trace.md").exists() - - -def test_record_pre_pair_frontier_trace_script_writes_selected_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - script_path = repo_root / "scripts" / "record_pre_pair_frontier_trace.py" - - subprocess.run( - [ - sys.executable, - str(script_path), - "--scenario", - "example_07_large_scale_routing_no_warm_start", - "--output-dir", - str(tmp_path), - ], - check=True, - ) - - payload = json.loads((tmp_path / "pre_pair_frontier_trace.json").read_text()) - assert payload["generated_at"] - assert payload["generator"] == "scripts/record_pre_pair_frontier_trace.py" - assert [entry["name"] for entry in payload["scenarios"]] == ["example_07_large_scale_routing_no_warm_start"] - assert payload["scenarios"][0]["pre_pair_frontier_trace"] is not None - assert (tmp_path / "pre_pair_frontier_trace.md").exists() + assert payload["generator"] == f"scripts/record_{report}.py" + [scenario] = payload["scenarios"] + assert scenario["name"] == name + if report == "frontier_trace": + # The final layout has no unresolved conflicts to replay. + assert scenario[report] == [] + else: + assert scenario[report] + markdown = (tmp_path / f"{report}.md").read_text() + assert markdown.startswith(heading + "\n") + assert f"## {name}" in markdown def test_characterize_pair_local_search_script_writes_outputs(tmp_path: Path) -> None: diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index d8d4666..cd7acd4 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -1,10 +1,9 @@ -from dataclasses import replace import pytest from shapely.geometry import Polygon, box from inire import ( - Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, StraightSeed, route, + Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route, ) from inire.router import _automatic @@ -16,17 +15,6 @@ OPTIONS = RoutingOptions( ) -def test_short_forward_perimeter_detour_does_not_abort_the_batch() -> None: - short = NetSpec("short", Port(30, 30, 0), Port(31, 70, 0)) - peer = NetSpec("peer", Port(5, 90, 0), Port(95, 90, 0)) - problem = RoutingProblem((0, 0, 100, 100), (short, peer), (box(30.3, 5, 30.6, 40),), clearance=0) - - run = route(problem, options=OPTIONS) - - assert run.results_by_net["short"].outcome == "unroutable" - assert run.results_by_net["peer"].is_valid - - def test_forward_perimeter_detour_can_fit_at_exactly_four_radii() -> None: net = NetSpec("edge", Port(20, 25, 0), Port(60, 25, 0)) obstacles = (box(42, 20, 45, 30), box(35, 20, 38, 30), box(75, 50, 85, 58)) @@ -40,92 +28,6 @@ def test_forward_perimeter_detour_can_fit_at_exactly_four_radii() -> None: assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 -@pytest.mark.parametrize("forward", [40, 41]) -def test_tight_forward_perimeter_detours_use_pivots_without_extra_end_spacing(forward) -> None: - net = NetSpec("edge", Port(20, 25, 0), Port(20 + forward, 25, 0)) - problem = RoutingProblem((0, 0, 100, 100), (net,), (box(38, 20, 42, 50),), clearance=0) - - run = route(problem, options=OPTIONS) - - result = run.results_by_net[net.net_id] - assert result.is_valid - assert run.automatic.selected_planner == "perimeter" - assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 - - -def test_forward_perimeter_lanes_ignore_keepouts_beyond_the_target() -> None: - net = NetSpec("through", Port(20, 60, 0), Port(120, 60, 0)) - problem = RoutingProblem((0, 0, 200, 120), (net,), (box(55, 30, 85, 90),), clearance=0) - distant = (box(150, 0, 160, 4), box(150, 116, 160, 120)) - - clean = route(problem, options=OPTIONS).results_by_net[net.net_id] - cluttered = route(replace(problem, static_obstacles=(*problem.static_obstacles, *distant)), options=OPTIONS) - - result = cluttered.results_by_net[net.net_id] - assert cluttered.automatic.selected_planner == "perimeter" - assert result.is_valid - assert result.as_seed() == clean.as_seed() - - -def test_forward_detours_try_inner_lanes_when_keepouts_reach_board_edges() -> None: - net = NetSpec("forward", Port(20, 60, 0), Port(120, 60, 0)) - obstacles = (box(55, 50, 85, 70), box(40, 0, 45, 4), box(40, 116, 45, 120)) - problem = RoutingProblem((0, 0, 200, 120), (net,), obstacles, clearance=0) - - run = route(problem, options=OPTIONS) - - assert run.automatic.selected_planner == "perimeter" - assert run.results_by_net[net.net_id].is_valid - - -@pytest.mark.parametrize(("width", "clearance"), [(4, 0), (2, 2)]) -def test_forward_perimeter_detours_include_keepouts_clear_of_the_centerline(width, clearance) -> None: - net = NetSpec("forward", Port(20, 50, 0), Port(120, 50, 0), width=width) - problem = RoutingProblem((0, 0, 150, 100), (net,), (box(55, 51.5, 65, 60),), clearance=clearance) - - run = route(problem, options=OPTIONS) - - assert run.automatic.selected_planner == "perimeter" - assert run.results_by_net[net.net_id].is_valid - - -@pytest.mark.parametrize("smaller_radius", [10, 17.5]) -def test_perimeter_detours_choose_a_radius_usable_by_the_planner(smaller_radius) -> None: - net = NetSpec("wide", Port(20, 70, 0), Port(220, 70, 0), width=30) - problem = RoutingProblem((0, 0, 250, 180), (net,), (box(100, 40, 130, 100),), clearance=0) - options = replace(OPTIONS, search=replace(OPTIONS.search, bend_radii=(smaller_radius, 20))) - - run = route(problem, options=options) - - result = run.results_by_net[net.net_id] - assert result.is_valid - assert run.automatic.selected_planner == "perimeter" - assert {move.radius for move in result.as_seed().segments if isinstance(move, Bend90Seed)} == {20} - - -def test_return_detours_snap_board_pivots_inward_before_generating_seeds() -> None: - net = NetSpec("return", Port(88, 50, 0), Port(12, 50, 0), width=3) - problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) - - run = route(problem, options=OPTIONS) - - result = run.results_by_net[net.net_id] - assert result.is_valid - assert run.automatic.selected_planner == "perimeter" - assert result.path[-1].end_port == net.target - - -def test_return_detours_try_inner_lanes_when_keepouts_reach_board_edges() -> None: - net = NetSpec("return", Port(100, 50, 0), Port(20, 50, 0)) - obstacles = (box(40, 0, 50, 4), box(40, 96, 50, 100)) - problem = RoutingProblem((0, 0, 120, 100), (net,), obstacles, clearance=0) - - run = route(problem, options=OPTIONS) - - assert run.automatic.selected_planner == "perimeter" - assert run.results_by_net[net.net_id].is_valid - - def test_return_detours_can_fit_without_straights_at_either_port() -> None: net = NetSpec("return", Port(100, 50, 0), Port(20, 50, 0)) obstacles = (box(111.2, 38, 125, 62), box(0, 38, 8.8, 62)) @@ -178,37 +80,6 @@ def test_perimeter_detours_try_both_sides_within_the_candidate_budget(monkeypatc assert 0 < generated <= 32 -@pytest.mark.parametrize(("forward", "needs_short_straight"), [(43, True), (60, False)]) -def test_residual_doglegs_prefer_the_lattice_minimum_but_can_relax_it(forward, needs_short_straight) -> None: - trunk = NetSpec("trunk", Port(20, 50, 0), Port(20 + forward, 50, 0)) - north = NetSpec("north", Port(10, 60, 90), Port(10, 100, 90)) - rail = NetSpec("rail", Port(85, 100, 0), Port(110, 100, 0)) - problem = RoutingProblem((0, 0, 120, 120), (trunk, north, rail), (box(40, 47, 43, 53),), clearance=0) - - run = route(problem, options=OPTIONS) - - assert run.automatic.selected_planner == "residual-dogleg" - assert all(run.results_by_net[net.net_id].is_valid for net in problem.nets) - lengths = [move.length for move in run.results_by_net["trunk"].as_seed().segments if isinstance(move, StraightSeed)] - assert any(length < OPTIONS.search.min_straight_length for length in lengths) is needs_short_straight - - -def test_residual_doglegs_spend_attempts_only_on_radii_that_fit_the_trace() -> None: - trunk = NetSpec("trunk", Port(30, 100, 0), Port(270, 100, 0), width=30) - north = NetSpec("north", Port(20, 150, 90), Port(20, 200, 90)) - rail = NetSpec("rail", Port(250, 200, 0), Port(300, 200, 0)) - obstacles = (box(140, 93, 153, 107), *(box(x, 180, x + 2, 182) for x in range(70, 241, 20))) - problem = RoutingProblem((0, 0, 310, 230), (trunk, north, rail), obstacles, clearance=0) - options = replace(OPTIONS, search=replace(OPTIONS.search, bend_radii=(10, 20))) - - run = route(problem, options=options) - - assert run.automatic.selected_planner == "residual-dogleg" - assert all(result.is_valid for result in run.results_by_net.values()) - segments = run.results_by_net[trunk.net_id].as_seed().segments - assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {20} - - def test_residual_dogleg_can_cross_clear_space_inside_a_keepout_bounds() -> None: trunk = NetSpec("trunk", Port(20, 60, 0), Port(120, 60, 0)) north = NetSpec("north", Port(10, 70, 90), Port(10, 105, 90)) @@ -222,8 +93,7 @@ def test_residual_dogleg_can_cross_clear_space_inside_a_keepout_bounds() -> None assert all(result.is_valid for result in run.results_by_net.values()) -@pytest.mark.parametrize("requires_reservation", [False, True]) -def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeypatch, requires_reservation) -> None: +def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeypatch) -> None: line = NetSpec("line", Port(5, 75, 0), Port(195, 75, 0)) returning = NetSpec("return", Port(130, 50, 0), Port(40, 50, 0)) obstacles = tuple(box(x, 100, x + 1, 104) for x in (*range(10, 29, 3), *range(142, 181, 4))) @@ -235,7 +105,7 @@ def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeyp def detours(candidate_problem, search): reserved = bool(candidate_problem.fixed_routes) calls.append((candidate_problem.nets[0].net_id, reserved)) - if reserved or not requires_reservation: + if reserved: for candidate in original_detours(candidate_problem, search): generated.append(reserved) yield candidate @@ -246,5 +116,5 @@ def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeyp assert run.automatic.selected_planner == "paired-perimeter" assert all(result.is_valid for result in run.results_by_net.values()) - assert calls == ([("return", False), ("return", True)] if requires_reservation else [("return", False)]) - assert generated == [requires_reservation] + assert calls == [("return", False), ("return", True)] + assert generated == [True] diff --git a/inire/tests/test_primitives.py b/inire/tests/test_primitives.py index 718ca18..cb86ad3 100644 --- a/inire/tests/test_primitives.py +++ b/inire/tests/test_primitives.py @@ -7,11 +7,9 @@ import pytest from inire.geometry.primitives import Port, port_local_coordinates, rotate_cardinal -@pytest.mark.parametrize( - ("heading", "expected"), - [(0, (3.5, 7.25)), (90, (7.25, -3.5)), (180, (-3.5, -7.25)), (270, (-7.25, 3.5))], -) -def test_port_local_coordinates_preserve_fractional_points(heading, expected) -> None: +def test_port_local_coordinates_preserve_fractional_points() -> None: + heading = 270 + expected = (-7.25, 3.5) origin = Port(10, -4, heading) local = port_local_coordinates(origin, 13.5, 3.25) assert local == expected @@ -26,12 +24,6 @@ def port_strategy(draw: Any) -> Port: return Port(x, y, orientation) -def test_port_snapping() -> None: - p = Port(0.123456, 0.654321, 90) - assert p.x == 0 - assert p.y == 1 - - def test_port_rotation_preserves_coordinates_beyond_int32() -> None: assert Port(-2**31, 20, 0).rotated(180) == Port(2**31, -20, 180) assert Port(3_000_000_004, 25, 270).rotated(90, origin=(3_000_000_000, 20)) == Port(2_999_999_995, 24, 0) @@ -49,17 +41,6 @@ def test_port_transform_invariants(p: Port) -> None: assert (p_rot.r % 360) == (p.r % 360) -@given( - p=port_strategy(), - dx=st.floats(min_value=-1000, max_value=1000), - dy=st.floats(min_value=-1000, max_value=1000), -) -def test_translate_snapping(p: Port, dx: float, dy: float) -> None: - p_trans = p.translate(dx, dy) - assert isinstance(p_trans.x, int) - assert isinstance(p_trans.y, int) - - def test_orientation_normalization() -> None: p = Port(0, 0, 360) assert p.r == 0 diff --git a/inire/tests/test_refinements.py b/inire/tests/test_refinements.py index 8832ee3..7fa3cbb 100644 --- a/inire/tests/test_refinements.py +++ b/inire/tests/test_refinements.py @@ -6,7 +6,6 @@ from shapely.geometry import Polygon, box from inire import CongestionOptions, ObjectiveWeights, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route from inire import DiagnosticsOptions, PathSeed, StraightSeed from inire.geometry.collision import RoutingWorld -from inire.geometry.components import Bend90 from inire.geometry.primitives import Port from inire.geometry.primitives import port_local_coordinates from inire.model import NetSpec @@ -36,29 +35,35 @@ _REFINEMENT_OPTIONS = RoutingOptions( ) -@pytest.mark.parametrize("limit", [None, 1, 4]) -def test_refinement_window_order_matches_exhaustive_search(limit) -> None: +def test_refinement_window_order_matches_exhaustive_search() -> None: problem = _seeded_foldback() - options = replace(_REFINEMENT_OPTIONS, refinement=RefinementOptions(max_windows_per_net=limit)) start = problem.nets[0].start - path = materialize_path_seed(problem.initial_paths["foldback"], start=start, net_width=2, search=options.search, clearance=2) + path = materialize_path_seed( + problem.initial_paths["foldback"], start=start, net_width=2, search=_REFINEMENT_OPTIONS.search, clearance=2, + ) assert path is not None - finder = PathFinder(AStarContext(CostEvaluator(RoutingWorld(clearance=2), DangerMap(problem.bounds)), problem, options)) ports = [start, *(move.end_port for move in path)] - eligible = [] + unbounded = [] + bounded = [] for left, source in enumerate(ports[:-1]): for right, target in enumerate(ports[left + 1 :], start=left + 1): bends = [move.move_type == "bend90" for move in path[left:right]] forward, _ = port_local_coordinates(source, target.x, target.y) if sum(bends) >= 4 and source.r == target.r and forward >= 40: - priority = -sum((bends[0], bends[-1])) if limit == 4 else 0 - eligible.append((priority, left - right, left, right)) + unbounded.append((left - right, left, right)) + bounded.append((-sum((bends[0], bends[-1])), left - right, left, right)) - assert list(finder.refiner._iter_refinement_windows(start, path)) == [(left, right) for _, _, left, right in sorted(eligible)] + for limit, expected in ( + (None, [(left, right) for _, left, right in sorted(unbounded)]), + (4, [(left, right) for _, _, left, right in sorted(bounded)]), + ): + options = replace(_REFINEMENT_OPTIONS, refinement=RefinementOptions(max_windows_per_net=limit)) + finder = PathFinder(AStarContext(CostEvaluator(RoutingWorld(clearance=2), DangerMap(problem.bounds)), problem, options)) + assert list(finder.refiner._iter_refinement_windows(start, path)) == expected -@pytest.mark.parametrize("radius", [10, 10.25]) -def test_refinement_handles_both_signs_of_the_lateral_offset(radius) -> None: +def test_refinement_handles_both_signs_of_the_lateral_offset() -> None: + radius = 10.25 options = replace(_REFINEMENT_OPTIONS, search=replace(_REFINEMENT_OPTIONS.search, bend_radii=(radius,))) paths = [ route(_seeded_foldback(reflected=reflected, radius=radius), options=options).results_by_net["foldback"] @@ -101,8 +106,8 @@ def test_automatic_refinement_rechecks_retained_partial_paths() -> None: assert traced.conflicting_net_ids == ("foldback",) -@pytest.mark.parametrize("weights", [None, (0, 0, 0)]) -def test_automatic_selects_refinement_using_its_explicit_objective(weights) -> None: +def test_automatic_selects_refinement_using_its_explicit_objective() -> None: + weights = (0, 0, 0) problem = _seeded_foldback() lattice_options = replace( _REFINEMENT_OPTIONS, @@ -121,6 +126,7 @@ def test_automatic_selects_refinement_using_its_explicit_objective(weights) -> N assert len(actual.path) == 9 assert actual.as_seed() == expected.as_seed() assert run.automatic.stages[run.automatic.selected_stage].operation == "refine" + assert any(timing.operation == "refine" for timing in run.automatic.timings) def test_seeded_refinement_builds_proximity_map_at_zero_search_budget(monkeypatch) -> None: @@ -150,8 +156,8 @@ def test_seeded_refinement_builds_proximity_map_at_zero_search_budget(monkeypatc assert callbacks == [result] -@pytest.mark.parametrize("mode", ["automatic", "off"]) -def test_refinement_preserves_custom_bend_geometry_on_seed_replay(mode) -> None: +def test_refinement_preserves_custom_bend_geometry_on_seed_replay() -> None: + mode = 'automatic' outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) options = replace( _REFINEMENT_OPTIONS, @@ -170,111 +176,3 @@ def test_refinement_preserves_custom_bend_geometry_on_seed_replay(mode) -> None: assert result.is_valid assert replay.is_valid assert all(a.equals(b) for a, b in zip(result.locked_geometry, replay.locked_geometry, strict=True)) - - -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, -) -> 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), - ), - ) - - -def test_arc_resolution_sagitta() -> None: - start = Port(0, 0, 0) - # R=10, 90 deg bend. - # High tolerance (0.5um) -> few segments - res_coarse = Bend90.generate(start, radius=10.0, width=2.0, direction="CCW", sagitta=0.5) - # Low tolerance (1nm) -> many segments - res_fine = Bend90.generate(start, radius=10.0, width=2.0, direction="CCW", sagitta=0.001) - - - # Check number of points in the polygon exterior - # (num_segments + 1) * 2 points usually - pts_coarse = len(res_coarse.collision_geometry[0].exterior.coords) - pts_fine = len(res_fine.collision_geometry[0].exterior.coords) - - assert pts_fine > pts_coarse - - -@pytest.mark.parametrize(("offset", "move_type"), [(0, "straight"), (5, "sbend")]) -def test_refinement_leaves_simple_paths_installed(offset: int, move_type: str) -> None: - problem = RoutingProblem( - bounds=(0, 0, 120, 120), - nets=(NetSpec("out", Port(10, 50, 0), Port(110, 50 + offset, 0)),), - ) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10.0,), sbend_radii=(10.0,)), - congestion=CongestionOptions(warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - - assert run.results_by_net["out"].is_valid - assert run.results_by_net["out"].path[-1].move_type == move_type - assert run.metrics.refine_path_calls == 0 - assert run.metrics.dynamic_path_objects_removed == 0 - - -def test_locked_routes() -> None: - engine = RoutingWorld(clearance=2.0) - danger_map = DangerMap(bounds=(0, -50, 100, 50)) - danger_map.precompute([]) - evaluator = CostEvaluator(engine, danger_map) - - # 1. Route Net A - netlist_a = {"netA": (Port(0, 0, 0), Port(50, 0, 0))} - results_a = _build_pathfinder( - evaluator, - bounds=(0, -50, 100, 50), - netlist=netlist_a, - net_widths={"netA": 2.0}, - search=SearchOptions(bend_radii=(5.0, 10.0)), - ).route_all() - assert results_a["netA"].is_valid - - # 2. Treat Net A as locked geometry in the next run. - for polygon in results_a["netA"].locked_geometry: - engine.add_static_obstacle(polygon) - - # 3. Route Net B through the same space. It should detour or fail. - # We'll place Net B's start/target such that it MUST cross Net A's physical path. - netlist_b = {"netB": (Port(0, -5, 0), Port(50, 5, 0))} - - # Route Net B - results_b = _build_pathfinder( - evaluator, - bounds=(0, -50, 100, 50), - netlist=netlist_b, - net_widths={"netB": 2.0}, - search=SearchOptions(bend_radii=(5.0, 10.0)), - ).route_all() - - # Net B should be is_valid (it detoured) or at least not have collisions - # with Net A in the dynamic set (because netA is now static). - # Since netA is static, netB will see it as a HARD collision if it tries to cross. - - # Our A* will find a detour around the static obstacle. - assert results_b["netB"].is_valid - - # Verify geometry doesn't intersect locked netA (physical check) - poly_a = [p.physical_geometry[0] for p in results_a["netA"].path] - poly_b = [p.physical_geometry[0] for p in results_b["netB"].path] - - for pa in poly_a: - for pb in poly_b: - assert not pa.intersects(pb) diff --git a/inire/tests/test_route_behavior.py b/inire/tests/test_route_behavior.py index 8bfc5ea..7597ab6 100644 --- a/inire/tests/test_route_behavior.py +++ b/inire/tests/test_route_behavior.py @@ -1,6 +1,6 @@ from __future__ import annotations -from shapely.geometry import Polygon +from typing import TYPE_CHECKING from inire import ( Bend90Seed, @@ -20,6 +20,9 @@ from inire import ( route, ) +if TYPE_CHECKING: + from shapely.geometry import Polygon + DEFAULT_BOUNDS = (0, -5, 100, 100) _PROBLEM_FIELDS = set(RoutingProblem.__dataclass_fields__) - {"bounds", "nets", "static_obstacles"} @@ -80,50 +83,6 @@ def _bend_count(result: RoutingResult) -> int: return sum(1 for component in result.path if component.move_type == "bend90") -def _build_manual_seed(steps: list[tuple[str, float | str]]) -> PathSeed: - segments = [] - for kind, value in steps: - if kind == "B": - segments.append(Bend90Seed(radius=5.0, direction=value)) - else: - segments.append(StraightSeed(length=value)) - return PathSeed(tuple(segments)) - - -def test_route_parallel_nets_are_valid() -> None: - run = _route_problem( - netlist={ - "net1": (Port(0, 0, 0), Port(50, 0, 0)), - "net2": (Port(0, 10, 0), Port(50, 10, 0)), - }, - net_widths={"net1": 2.0, "net2": 2.0}, - ) - - assert len(run.results_by_net) == 2 - assert run.results_by_net["net1"].is_valid - assert run.results_by_net["net2"].is_valid - assert run.results_by_net["net1"].collisions == 0 - assert run.results_by_net["net2"].collisions == 0 - - -def test_route_reports_crossing_nets_without_congestion_resolution() -> None: - run = _route_problem( - netlist={ - "net1": (Port(0, 25, 0), Port(100, 25, 0)), - "net2": (Port(50, 0, 90), Port(50, 50, 90)), - }, - net_widths={"net1": 2.0, "net2": 2.0}, - max_iterations=1, - base_penalty=1.0, - warm_start_enabled=False, - ) - - assert not run.results_by_net["net1"].is_valid - assert not run.results_by_net["net2"].is_valid - assert run.results_by_net["net1"].collisions > 0 - assert run.results_by_net["net2"].collisions > 0 - - def test_route_callback_respects_requested_net_order() -> None: callback_orders: list[list[str]] = [] @@ -144,44 +103,6 @@ def test_route_callback_respects_requested_net_order() -> None: assert callback_orders == [["long", "mid", "short"]] -def test_route_callback_receives_iteration_results() -> None: - callback_results: list[dict[str, RoutingResult]] = [] - - run = _route_problem( - netlist={ - "net1": (Port(0, 0, 0), Port(10, 0, 0)), - "net2": (Port(0, 10, 0), Port(10, 10, 0)), - }, - net_widths={"net1": 2.0, "net2": 2.0}, - iteration_callback=lambda iteration, results: callback_results.append(dict(results)), - ) - - assert len(callback_results) == 1 - assert set(callback_results[0]) == {"net1", "net2"} - assert callback_results[0]["net1"].is_valid - assert callback_results[0]["net2"].is_valid - assert run.results_by_net["net1"].reached_target - assert run.results_by_net["net2"].reached_target - - -def test_route_uses_complete_initial_paths_without_rerouting() -> None: - initial_seed = _build_manual_seed([("S", 10.0), ("B", "CCW"), ("S", 10.0), ("B", "CW")]) - run = _route_problem( - netlist={"net": (Port(0, 0, 0), Port(20, 20, 0))}, - net_widths={"net": 2.0}, - bend_radii=[5.0], - max_iterations=1, - warm_start_enabled=False, - initial_paths={"net": initial_seed}, - enabled=False, - ) - - result = run.results_by_net["net"] - assert result.is_valid - assert result.reached_target - assert result.as_seed() == initial_seed - - def test_route_uses_a_partial_initial_path_on_the_first_iteration() -> None: iterations: list[int] = [] partial_seed = PathSeed((StraightSeed(length=7.0),)) @@ -202,66 +123,12 @@ def test_route_uses_a_partial_initial_path_on_the_first_iteration() -> None: assert result.reached_target assert result.outcome == "completed" assert result.as_seed().segments == (*partial_seed.segments, StraightSeed(13)) - assert run.expanded_nodes + assert run.metrics.nodes_expanded >= len(set(run.expanded_nodes)) > 0 + assert run.metrics.route_iterations == len(iterations) + assert run.metrics.iteration_reverify_calls >= 1 assert run.metrics.guidance_match_moves > 0 -def test_route_negotiated_congestion_resolution() -> None: - obs_top = Polygon([(20, 6), (30, 6), (30, 15), (20, 10)]) - obs_bottom = Polygon([(20, 4), (30, 4), (30, -15), (20, -10)]) - run = _route_problem( - bounds=(0, -40, 100, 40), - netlist={ - "net1": (Port(0, 0, 0), Port(50, 0, 0)), - "net2": (Port(0, 10, 0), Port(50, 10, 0)), - }, - net_widths={"net1": 2.0, "net2": 2.0}, - static_obstacles=(obs_top, obs_bottom), - bend_radii=(5.0, 10.0), - max_iterations=10, - base_penalty=1000.0, - ) - - assert run.results_by_net["net1"].reached_target - assert run.results_by_net["net2"].reached_target - assert run.results_by_net["net1"].is_valid - assert run.results_by_net["net2"].is_valid - - -def test_route_refinement_reduces_locked_detour_bends() -> None: - route_a = _route_problem( - bounds=(0, -50, 100, 50), - netlist={"netA": (Port(10, 0, 0), Port(90, 0, 0))}, - net_widths={"netA": 2.0}, - bend_radii=[10.0], - enabled=False, - ) - locked_geometry = route_a.results_by_net["netA"].locked_geometry - - base_run = _route_problem( - bounds=(0, -50, 100, 50), - netlist={"netB": (Port(50, -20, 90), Port(50, 20, 90))}, - net_widths={"netB": 2.0}, - static_obstacles=locked_geometry, - bend_radii=[10.0], - enabled=False, - ) - refined_run = _route_problem( - bounds=(0, -50, 100, 50), - netlist={"netB": (Port(50, -20, 90), Port(50, 20, 90))}, - net_widths={"netB": 2.0}, - static_obstacles=locked_geometry, - bend_radii=[10.0], - enabled=True, - ) - - base_result = base_run.results_by_net["netB"] - refined_result = refined_run.results_by_net["netB"] - assert base_result.is_valid - assert refined_result.is_valid - assert _bend_count(refined_result) < _bend_count(base_result) - - def test_route_refinement_simplifies_triple_crossing_detours() -> None: detour = PathSeed( ( diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 0603a8d..74528a1 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -1,35 +1,28 @@ import sys from dataclasses import asdict, replace -from itertools import combinations -from json import dumps, loads +from json import loads import pytest -from shapely import union_all -from shapely.geometry import Point, Polygon, box, shape +from shapely.geometry import box, shape from inire import ( - Bend90Seed, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, SBendOutline, - SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, + CongestionOptions, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, RoutingResult, RoutingRunResult, + SearchOptions, StraightSeed, TopologyOptions, route, ) -from inire.constants import TOLERANCE_LINEAR from inire.router import _automatic, _compact +from inire.router._astar_types import AStarMetrics from inire.router._automatic import _AutomaticRun from inire.router._capacity import port_conflicts from inire.router._routing_policy import _disconnected_nets from inire.router.cost import weighted_path_length -from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES from inire.tests.routing_benchmarks import ( BENCHMARK_CASES, - COMPLEX_BENCHMARK_CASES, CROSSING_BENCHMARK_CASES, - EXTERNAL_BENCHMARK_CASES, FALLBACK_BENCHMARK_CASES, ) -from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options -from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES +from inire.tests.routing_corpus import CASE_GROUPS, automatic_options, profile_options from scripts.compare_topological_routing import ( _direct_trials, - _geometry_json, _measure as _measure_selected_mode, _mode_options, main as run_benchmarks, @@ -40,70 +33,6 @@ 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 CORPUS_CASES], -) -def test_automatic_reaches_corpus_routing_bound(case) -> None: - profile = "corpus-regression" - options = automatic_options(profile_options(case, profile), profile) - run = route(case.problem, options=options) - - 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} - assert run.automatic.max_routed == case.routing_bound - assert set(run.automatic.verified_net_ids) == verified - assert len(verified) == case.routing_bound - - -@pytest.mark.parametrize("name", ["search-comb-1x4", "search-comb-2x5-fine", "scale-field-20x16"]) -def test_column_recovery_routes_with_a_one_node_search_budget(name) -> None: - (case,) = CASE_GROUPS[name] - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - options = replace( - options, - search=replace(options.search, node_limit=1), - congestion=replace(options.congestion, max_iterations=1), - topology=replace(options.topology, seed_node_limit=1), - ) - - run = route(case.problem, options=options) - - assert run.automatic is not None - assert run.automatic.selected_planner == "column-recovery" - assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} - assert all(result.is_valid for result in run.results_by_net.values()) - - -@pytest.mark.parametrize("name", ["search-comb-3x4", "scale-field-20x16"]) -def test_column_recovery_can_skip_the_search_probe(name) -> None: - (case,) = CASE_GROUPS[name] - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - - run = route(case.problem, options=options) - - assert run.automatic is not None - assert run.automatic.selected_planner == "column-recovery" - assert len(run.automatic.verified_net_ids) == case.routing_bound - assert run.metrics.nodes_expanded == 0 - - -@pytest.mark.parametrize("name", ["retry-holdout-stepped-roof", "retry-holdout-west-roof"]) -def test_residual_perimeter_completes_a_return_with_straight_peers(name) -> None: - (case,) = CASE_GROUPS[name] - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - options = replace(options, search=replace(options.search, node_limit=1)) - - run = route(case.problem, options=options) - - assert run.automatic is not None - assert run.automatic.selected_planner == "residual-perimeter" - assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} - assert all(len(run.results_by_net[net_id].path) == 1 for net_id in ("edge", "lower", "east")) - - @pytest.mark.routing_corpus def test_final_dogleg_can_reuse_incumbents_from_seed_fallback(monkeypatch) -> None: short_shift_seed_set = _automatic.short_shift_seed_set @@ -124,19 +53,6 @@ def test_final_dogleg_can_reuse_incumbents_from_seed_fallback(monkeypatch) -> No assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} -def test_local_shift_plan_can_leave_one_conflicting_net_for_a_detour() -> None: - (case,) = CASE_GROUPS["stress-crossings-shared-outside-detour"] - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - - run = route(case.problem, options=options) - - assert run.automatic.selected_planner == "residual-dogleg" - assert run.metrics.nodes_expanded == 0 - assert all(result.is_valid for result in run.results_by_net.values()) - [partial] = [stage for stage in run.automatic.stages if stage.planner == "local-sbend" and stage.operation == "verify"] - assert set(partial.valid_net_ids) == {net.net_id for net in case.problem.nets if net.net_id != "outside_lower"} - - def test_weighted_local_shifts_can_pack_without_verifying_alternative_placements(monkeypatch) -> None: (case,) = CASE_GROUPS["crossing-staggered-grid"] weights = {"straight": 1.0, "bend90": 4.0, "sbend": 13.0} @@ -160,206 +76,30 @@ def test_weighted_local_shifts_can_pack_without_verifying_alternative_placements assert seed_counts == [1] * len(case.problem.nets) -def test_expanded_corpus_uses_physical_dimensions_and_has_reference_coverage() -> None: - corpus_names = {case.name for case in CORPUS_CASES} - assert len(corpus_names) == len(CORPUS_CASES) - expanded = CASE_GROUPS["expanded"] - assert 50 <= len(expanded) <= 100 - for case in expanded: - assert case.name in corpus_names - assert case.grid_nm is not None - assert 10 <= case.grid_nm <= 1000 - assert not case.problem.initial_paths - assert len(dict(case.reference_paths)) == case.routing_bound - assert all(1000 <= net.width * case.grid_nm <= 20000 for net in case.problem.nets) - radii = (*case.options.search.bend_radii, *case.options.search.sbend_radii) - assert radii - assert all(10000 <= radius * case.grid_nm <= 100000 for radius in radii) - scaling = CASE_GROUPS["scaling"] - assert any(len(case.problem.nets) >= 200 and len(case.problem.static_obstacles) >= 200 for case in scaling) - assert any(len(case.problem.nets) < 200 <= len(case.problem.static_obstacles) for case in scaling) - assert any(len(case.problem.static_obstacles) < 200 <= len(case.problem.nets) for case in scaling) - - -def test_benchmark_json_records_the_authored_grid(tmp_path, monkeypatch) -> None: - output = tmp_path / "benchmark.json" - monkeypatch.setattr(sys, "argv", [ - "bench", "--case", "precision-sbend-single-10nm", "--profile", "corpus-regression", "--mode", "automatic", "--json", str(output), - ]) - - run_benchmarks() - - [run] = loads(output.read_text())["runs"] - assert run["grid_nm"] == 10 - assert run["options"]["search"]["sbend_radii"] == [2500] - - -@pytest.mark.parametrize( - "case", - [pytest.param(case, id=case.name) for case in (*CORPUS_CASES, *RETRY_HOLDOUT_CASES) if case.reference_paths], -) -def test_benchmark_reference_paths_are_feasible(case) -> None: - reference = dict(case.reference_paths) - problem = replace(case.problem, nets=tuple(net for net in case.problem.nets if net.net_id in reference), initial_paths=reference) - options = replace(case.options, refinement=replace(case.options.refinement, enabled=False)) - run = route(problem, options=options) - - assert run.results_by_net.keys() == reference.keys() - board = box(*problem.bounds) - footprints = [] - for result in run.results_by_net.values(): - assert result.is_valid - assert result.as_seed() == reference[result.net_id] - footprint = union_all(result.locked_geometry) - assert board.covers(footprint) - assert all(footprint.distance(obstacle) >= problem.clearance - TOLERANCE_LINEAR for obstacle in problem.static_obstacles) - footprints.append(footprint) - for a, b in combinations(footprints, 2): - assert a.distance(b) >= problem.clearance - TOLERANCE_LINEAR - - -def test_stress_and_retry_holdout_cases_start_unseeded_with_complete_reference_paths() -> None: - cases = (*STRESS_BENCHMARK_CASES, *RETRY_HOLDOUT_CASES) - assert len({case.name for case in cases}) == len(cases) - for case in 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), +def test_automatic_probe_caps_iterations_before_wider_retry(monkeypatch) -> None: + iterations = 3 + probe_limit = 2 + problem = RoutingProblem( + bounds=(0, 0, 200, 200), + nets=tuple(NetSpec(str(y), Port(10, y, 0), Port(190, y + 20, 0)) for y in (30, 60, 90)), ) - - 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_stress_residual_dogleg_completes_layout_before_wider_search() -> None: - case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-retry-straight-decoy") - options = replace( - case.options, - topology=TopologyOptions(mode="automatic"), - congestion=replace(case.options.congestion, max_iterations=3), - ) - - ordinary = route(case.problem, options=options) - iterations = [] - observed = route(case.problem, options=options, iteration_callback=lambda index, _: iterations.append(index)) - report = ordinary.automatic - - assert report is not None - assert set(report.verified_net_ids) == {net.net_id for net in case.problem.nets} - assert report.selected_planner == "residual-dogleg" - [search] = [stage for stage in report.stages if stage.operation == "search"] - assert search.policy == "direct-probe-near-port" - assert set(search.valid_net_ids) == {"branch_west", "branch_east", "lower_rail"} - assert observed.results_by_net == ordinary.results_by_net - assert observed.metrics.nodes_expanded == ordinary.metrics.nodes_expanded - assert iterations == list(range(observed.metrics.route_iterations)) - - -def test_residual_dogleg_seeds_can_use_straights_longer_than_the_lattice_scan() -> None: - case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-retry-straight-decoy") - options = replace( - case.options, - search=replace(case.options.search, node_limit=25, max_straight_length=180), - congestion=replace(case.options.congestion, max_iterations=1, warm_start_enabled=False), - refinement=replace(case.options.refinement, enabled=False), - topology=TopologyOptions(mode="automatic"), - ) - - run = route(case.problem, options=options) - - assert run.automatic.selected_planner == "residual-dogleg" - assert all(run.results_by_net[net.net_id].is_valid for net in case.problem.nets) - assert any( - isinstance(move, StraightSeed) and move.length > options.search.max_straight_length - for move in run.results_by_net["trunk"].as_seed().segments - ) - - -@pytest.mark.parametrize(("iterations", "probe_limit"), [(1, 1), (3, 2)]) -def test_automatic_probe_caps_iterations_and_preserves_callback_order(monkeypatch, iterations, probe_limit) -> None: - (case,) = CASE_GROUPS["pic-splitter-tree-1x8-ew"] - profile = "corpus-regression" - options = automatic_options(profile_options(case, profile), profile) + options = RoutingOptions(search=SearchOptions(node_limit=500)) options = replace(options, congestion=replace(options.congestion, max_iterations=iterations)) - run_worker = _AutomaticRun._run - search_budgets = {} - callback_indices = [] + attempts = [] - def record_budget(self, problem, *, options, **kwargs): - if kwargs.get("policy") in {"direct-probe-near-port", "direct-lookahead-retry"}: - search_budgets[kwargs["policy"]] = options.congestion.max_iterations - return run_worker(self, problem, options=options, **kwargs) + def unresolved_worker(_planner, problem, *, options, policy): + budgets = (options.search.node_limit, options.congestion.max_iterations) + attempts.append((policy, *budgets)) + results = {net.net_id: RoutingResult(net.net_id, ()) for net in problem.nets} + return RoutingRunResult(results, AStarMetrics().snapshot()) - monkeypatch.setattr(_AutomaticRun, "_run", record_budget) - route(case.problem, options=options, iteration_callback=lambda index, _results: callback_indices.append(index)) - - assert search_budgets == {"direct-probe-near-port": probe_limit, "direct-lookahead-retry": iterations} - assert len(callback_indices) > probe_limit - assert callback_indices == list(range(len(callback_indices))) - - -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 - - 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} - 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 - - -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 + monkeypatch.setattr(_AutomaticRun, "_run", unresolved_worker) + planner = _AutomaticRun(problem, options, None) + assert not planner._initial_search_trials(options, [], len(problem.nets)) + assert attempts == [ + ("direct-probe-near-port", 100, probe_limit), + ("direct-lookahead-retry", options.search.node_limit, iterations), + ] def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None: @@ -382,51 +122,20 @@ def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None: assert len(guided[0].valid_net_ids) < len(problem.nets) -def test_automatic_times_planning_search_verification_and_refinement() -> None: - case = next(case for case in BENCHMARK_CASES if case.name == "open-bundle") - options = replace(case.options, topology=TopologyOptions(mode="automatic")) - - report = route(case.problem, options=options).automatic - - assert report is not None - assert {timing.operation for timing in report.timings} == {"plan", "verify", "search", "refine"} - assert 0 < sum(timing.duration_s for timing in report.timings) <= report.duration_s - assert report.planner_rejections - assert any(timing.planner == "bundle" and timing.operation == "plan" for timing in report.timings) - assert not any(timing.planner == "bundle" and timing.operation == "verify" for timing in report.timings) - stage = report.stages[report.selected_stage] - assert stage.planner == "direct" - assert stage.mode == "off" - assert stage.policy == "direct-probe-near-port" - - -@pytest.mark.parametrize( - ("profile", "refinement", "max_windows"), - [ - ("public-defaults", None, None), - ("public-defaults", "off", None), - ("public-defaults", "on", "1"), - ("matched-budget", None, "unlimited"), - ("matched-budget", "on", None), - ("corpus-regression", None, None), - ], -) -def test_benchmark_profile_records_effective_options(profile, refinement, max_windows, tmp_path, monkeypatch) -> None: +def test_benchmark_profile_records_effective_options(tmp_path, monkeypatch) -> None: case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == "fallback-custom-physical") defaults = RoutingOptions() output = tmp_path / "benchmark.json" - mode_args = [] if profile == "public-defaults" else ["--mode", "automatic"] - refine_args = [] if refinement is None else ["--refinement", refinement] - window_args = [] if max_windows is None else ["--refinement-windows", max_windows] monkeypatch.setattr( - sys, "argv", ["bench", "--profile", profile, "--case", case.name, *mode_args, *refine_args, *window_args, "--json", str(output)] + sys, "argv", + ["bench", "--profile", "public-defaults", "--case", case.name, "--refinement", "on", "--refinement-windows", "1", "--json", str(output)], ) run_benchmarks() payload = loads(output.read_text()) [run] = payload["runs"] - assert payload["profile"] == profile + assert payload["profile"] == "public-defaults" assert run["requested_mode"] == "automatic" options = run["options"] geometry = case.options.search @@ -440,34 +149,13 @@ def test_benchmark_profile_records_effective_options(profile, refinement, max_wi assert stage["mode"] == "off" assert stage["operation"] == "search" operations = {timing["operation"] for timing in sample["timings"]} - expected_refinement = defaults.refinement if profile == "public-defaults" else case.options.refinement - if refinement is not None: - expected_refinement = replace(expected_refinement, enabled=refinement == "on") - if max_windows is not None: - expected_refinement = replace(expected_refinement, max_windows_per_net=None if max_windows == "unlimited" else int(max_windows)) + expected_refinement = replace(defaults.refinement, enabled=True, max_windows_per_net=1) assert options["refinement"] == asdict(expected_refinement) - assert operations == ({"search", "verify", "refine"} if expected_refinement.enabled else {"search", "verify"}) - if profile == "public-defaults": - assert options["search"]["node_limit"] == defaults.search.node_limit - assert options["objective"] == asdict(defaults.objective) - assert options["congestion"] == asdict(defaults.congestion) - assert options["topology"]["automatic_length_weights"] is None - else: - assert options["search"]["node_limit"] == 500 - assert options["objective"] == asdict(case.options.objective) - assert options["congestion"]["max_iterations"] == (3 if profile == "corpus-regression" else 2) - assert options["topology"]["seed_node_limit"] == (500 if profile == "corpus-regression" else defaults.topology.seed_node_limit) - assert options["topology"]["automatic_length_weights"] == [1.0, 4.0, 13.0] - - -@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in BENCHMARK_CASES if case.name.startswith("offset-gates")]) -def test_portal_guidance_routes_offset_gates_under_small_budget(case) -> None: - options = replace(case.options, search=replace(case.options.search, node_limit=100), topology=TopologyOptions(mode="guide")) - result = route(case.problem, options=options).results_by_net["offset"] - - assert result.is_valid - assert any(component.move_type == "sbend" for component in result.path) - assert all(box(*case.problem.bounds).covers(shape) for shape in result.locked_geometry) + assert operations == {"search", "verify", "refine"} + assert options["search"]["node_limit"] == defaults.search.node_limit + assert options["objective"] == asdict(defaults.objective) + assert options["congestion"] == asdict(defaults.congestion) + assert options["topology"]["automatic_length_weights"] is None def test_connectivity_screen_checks_each_net_width_and_leaves_unknown_ports_for_search() -> None: @@ -485,19 +173,6 @@ def test_connectivity_screen_checks_each_net_width_and_leaves_unknown_ports_for_ assert _disconnected_nets(problem, box(*problem.bounds), RoutingOptions(), {}) == frozenset({"wide"}) -def test_lookahead_changes_lock_order_before_spending_search_budget() -> None: - case = next(case for case in BENCHMARK_CASES if case.name == "blocking-straight") - options = replace(case.options, search=replace(case.options.search, node_limit=100)) - - result = _measure(case, options, "direct-lookahead-retry") - - assert len(result.stages) == 1 - assert result.stages[0].node_limit == 100 - assert result.stages[0].direct_net_ids == ("vertical",) - assert result.stages[0].skipped_net_ids == () - assert "vertical" in result.valid_costs - - def test_budgeted_retry_shares_the_cap_when_both_lock_orders_leave_connected_space() -> None: case = next(case for case in BENCHMARK_CASES if case.name == "blocking-turn-room") options = replace(case.options, search=replace(case.options.search, node_limit=101)) @@ -510,88 +185,21 @@ def test_budgeted_retry_shares_the_cap_when_both_lock_orders_leave_connected_spa assert result.nodes_expanded == sum(stage.nodes_expanded for stage in result.stages) -@pytest.mark.parametrize("policy", ["direct-probe-first", "direct-probe-near-port"]) -def test_unlocked_probe_can_complete_the_turn_limited_case(policy) -> None: - case = next(case for case in BENCHMARK_CASES if case.name == "blocking-turn-room") - options = replace(case.options, search=replace(case.options.search, node_limit=100)) - - result = _measure(case, options, policy) - - assert len(result.valid_costs) == 2 - assert len(result.stages) == 1 - assert result.stages[0].kind == "lattice-probe" - assert result.stages[0].node_limit == 32 - - -def test_near_port_probe_leaves_budget_for_crossings_far_from_the_ports() -> None: - case = next(case for case in BENCHMARK_CASES if case.name == "crossing-with-room") - options = replace(case.options, search=replace(case.options.search, node_limit=100)) - - result = _measure(case, options, "direct-probe-near-port") - - assert [stage.node_limit for stage in result.stages] == [50, 50] - assert all(stage.kind == "route" for stage in result.stages) - - -@pytest.mark.parametrize( - "name", - [ - "terminal-bench-point-terminals", - "terminal-bench-clearance-5", - "terminal-bench-narrow-bottom", - *(case.name for case in COMPLEX_BENCHMARK_CASES if case.options.topology.mode == "bundle"), - ], -) -def test_bundle_first_routes_point_terminals_without_supplied_paths(name: str) -> None: - case = next(case for case in BENCHMARK_CASES if case.name == name) - assert not case.problem.initial_paths - assert not case.reference_paths - fixed = case.fixed_headings_problem() - assert [net.net_id for net in fixed.nets if net.target.r == 180] == ["net_08"] - assert not fixed.initial_paths - - sample = _measure(case, case.options, "bundle-first") - - assert sample.bundle_rejection is None - assert [stage.kind for stage in sample.stages] == ["bundle"] - assert sample.valid_costs.keys() == {net.net_id for net in case.problem.nets} - assert sample.nodes_expanded == 0 - - -@pytest.mark.parametrize(("name", "mode"), [("complex-routing-example-1", "automatic"), ("complex-routing-example-1-point-terminals", "bundle")]) -def test_unused_custom_outline_keeps_constructive_planning_available(name, mode) -> None: - (case,) = CASE_GROUPS[name] - width = 3 - outline = SBendOutline(40, 50, width, Polygon([(0, -1.5), (80, 38.5), (80, 41.5), (0, 1.5)])) - options = replace( - case.options, - search=replace(case.options.search, node_limit=100, sbend_outlines=(outline,)), - topology=replace(case.options.topology, mode=mode), - congestion=replace(case.options.congestion, max_iterations=1, warm_start_enabled=False), - refinement=replace(case.options.refinement, enabled=False), - ) - - result = route(case.problem, options=options) - - assert all(path.is_valid for path in result.results_by_net.values()) - - -@pytest.mark.parametrize("hint", [(), (StraightSeed(2400),)]) -def test_automatic_plan_recovers_full_complex_board_with_one_supplied_hint(hint) -> None: +def test_automatic_recovers_a_complex_board_after_rejecting_a_hint() -> None: (case,) = CASE_GROUPS["complex-routing-example-1"] - problem = replace(case.problem, initial_paths={"net_04": PathSeed(hint)}) + problem = replace(case.problem, initial_paths={"net_04": PathSeed((StraightSeed(2400),))}) options = replace( case.options, search=replace(case.options.search, node_limit=100), - topology=replace(case.options.topology, mode="automatic"), - congestion=replace(case.options.congestion, max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode="automatic"), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=replace(case.options.refinement, enabled=False), ) - result = route(problem, options=options) + run = route(problem, options=options) - assert len(result.results_by_net) == 9 - assert all(path.is_valid for path in result.results_by_net.values()) + assert set(run.automatic.verified_net_ids) == {net.net_id for net in problem.nets} + assert run.results_by_net["net_04"].as_seed() != problem.initial_paths["net_04"] def test_point_terminal_replay_preserves_the_selected_port_headings() -> None: @@ -615,20 +223,6 @@ def test_point_terminal_replay_preserves_the_selected_port_headings() -> None: assert all(result.is_valid and result.locked_geometry == paths[net_id].locked_geometry for net_id, result in replay.results_by_net.items()) -def test_complex_benchmarks_are_distinct_unseeded_nine_net_problems() -> None: - assert len({case.name for case in BENCHMARK_CASES}) == len(BENCHMARK_CASES) - assert len(COMPLEX_BENCHMARK_CASES) == 20 - layouts = set() - for case in COMPLEX_BENCHMARK_CASES: - problem = case.problem - assert len(problem.nets) == 9 - assert not problem.initial_paths - if case.reference_paths: - assert {net_id for net_id, _ in case.reference_paths} == {net.net_id for net in problem.nets} - layouts.add((problem.bounds, problem.nets, tuple(sorted(shape.bounds for shape in problem.static_obstacles)))) - assert len(layouts) == len(COMPLEX_BENCHMARK_CASES) - - def test_bundle_first_reports_capacity_failure_and_uses_the_generic_fallback() -> None: original = next(case for case in BENCHMARK_CASES if case.name == "terminal-bench-point-terminals") case = replace(original, problem=replace(original.problem, clearance=7)) @@ -645,38 +239,6 @@ def test_bundle_first_reports_capacity_failure_and_uses_the_generic_fallback() - assert sample.valid_costs == fallback.valid_costs -@pytest.mark.parametrize( - ("name", "planner"), - [("terminal-bench", "bundle-turnaround"), ("terminal-bench-pair", "paired-perimeter")], -) -def test_automatic_policy_preserves_fixed_terminal_headings(name: str, planner: str) -> None: - case = next(case for case in BENCHMARK_CASES if case.name == name) - assert not case.problem.initial_paths - 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 == planner - for net in case.problem.nets: - result = run.results_by_net[net.net_id] - assert result.is_valid - assert result.path[0].start_port == net.start - assert result.path[-1].end_port == net.target - - -def test_automatic_policy_stops_at_the_geometric_cut_bound() -> None: - case = next(case for case in BENCHMARK_CASES if case.name == "overloaded-gate") - options = replace(case.options, search=replace(case.options.search, node_limit=SearchOptions().node_limit)) - sample = _measure(case, options, "automatic") - - assert sample.capacity_limit is not None - assert sample.capacity_limit.cut_x == 225 - assert sample.capacity_limit.crossing_nets == 4 - assert sample.capacity_limit.tracks == 3 - assert len(sample.valid_costs) == sample.capacity_limit.max_routed == 3 - assert [stage.kind for stage in sample.stages] == ["route", "refinement"] - - def test_automatic_retry_releases_a_lock_that_disconnects_the_remaining_net() -> None: case = next(case for case in BENCHMARK_CASES if case.name == "blocking-straight") board = box(*case.problem.bounds) @@ -744,48 +306,6 @@ def test_automatic_can_force_weighted_scoring_when_the_selective_pass_is_skipped assert set(selective.automatic.verified_net_ids) == set(forced.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} -@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in EXTERNAL_BENCHMARK_CASES]) -def test_external_benchmark_has_accessible_ports_and_empty_paths(case) -> None: - problem = case.problem - assert not problem.initial_paths - assert not case.reference_paths - assert len({net.net_id for net in problem.nets}) == len(problem.nets) - board = box(*problem.bounds) - for obstacle in problem.static_obstacles: - assert obstacle.is_valid - assert board.covers(obstacle) - for net in problem.nets: - for port in (net.start, net.target): - position = Point(port.x, port.y) - assert board.covers(position) - assert all(position.distance(obstacle) >= net.width / 2 + problem.clearance for obstacle in problem.static_obstacles) - - -def test_benchmark_json_preserves_custom_bend_geometry() -> None: - case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == "fallback-custom-physical") - encoded = loads(dumps(asdict(case.options), default=_geometry_json)) - for key in ("bend_physical_geometry", "bend_proxy_geometry"): - assert shape(encoded["search"][key]).equals(getattr(case.options.search, key)) - - -def test_compact_port_jogs_close_the_mzm_layout_without_search() -> None: - case = next(case for case in EXTERNAL_BENCHMARK_CASES if case.name == "pic-splitter-mzm-combiner-4-ew") - sample = _measure(case, case.options, "automatic") - - assert len(sample.valid_costs) == 12 - assert sample.stages[sample.selected_stage].kind == "compact-port-jogs" - assert sample.nodes_expanded == 0 - - -def test_port_spacing_certificate_reaches_clements_capacity() -> None: - case = next(case for case in EXTERNAL_BENCHMARK_CASES if case.name == "lidar-clements-8x8") - sample = _measure(case, case.options, "automatic") - - assert sample.port_conflicts == (("n_30", "n_31"), ("n_32", "n_33"), ("n_34", "n_35")) - assert len(sample.valid_costs) == len(case.problem.nets) - len(sample.port_conflicts) - assert len(sample.stages) == 1 - - def test_port_spacing_certificate_keeps_input_order_in_mixed_width_bank() -> None: nets = tuple( NetSpec(name, Port(5, y, 0), Port(95, y + 40, 0), width) @@ -797,18 +317,6 @@ def test_port_spacing_certificate_keeps_input_order_in_mixed_width_bank() -> Non assert port_conflicts(replace(problem, nets=(nets[0], nets[2], nets[1], *nets[3:])), RoutingOptions()) == (("a", "c"), ("b", "d")) -def test_paired_perimeters_respect_the_supplied_detour() -> None: - case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == "fallback-seeded-detour") - options = replace(case.options, search=replace(case.options.search, node_limit=100), topology=TopologyOptions(mode="automatic")) - run = route(case.problem, options=options) - - assert run.automatic is not None - assert run.automatic.selected_planner == "paired-perimeter" - assert all(result.is_valid for result in run.results_by_net.values()) - for net_id, seed in case.problem.initial_paths.items(): - assert run.results_by_net[net_id].as_seed() == seed - - def test_perimeter_residual_preserves_its_lock_and_verifies_the_layout(monkeypatch: pytest.MonkeyPatch) -> None: (case,) = CASE_GROUPS["terminal-bench-pair"] options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") @@ -825,40 +333,3 @@ def test_perimeter_residual_preserves_its_lock_and_verifies_the_layout(monkeypat assert trials[-1].selectable assert trials[-1].stage.kind == "perimeter" assert set(trials[-1].valid_costs) == {net.net_id for net in case.problem.nets} - - -@pytest.mark.parametrize("name", ["fallback-custom-proxy", "fallback-custom-physical"]) -def test_automatic_preserves_custom_bend_geometry(name: str) -> None: - case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == name) - ordinary = route(case.problem, options=case.options) - options = replace(case.options, topology=replace(case.options.topology, mode="automatic")) - automatic = route(case.problem, options=options) - - assert automatic.automatic is not None - assert automatic.automatic.selected_planner == "lattice" - assert automatic.automatic.stages[automatic.automatic.selected_stage].kind == "lattice-fallback" - assert all(result.is_valid for result in automatic.results_by_net.values()) - for net_id, result in automatic.results_by_net.items(): - expected = ordinary.results_by_net[net_id] - assert result.as_seed() == expected.as_seed() - assert result.locked_geometry == expected.locked_geometry - - -def test_automatic_return_detour_respects_a_small_search_budget() -> None: - case = next(case for case in BENCHMARK_CASES if case.name == "reversed-heading") - options = replace( - case.options, - search=replace(case.options.search, node_limit=1), - congestion=replace(case.options.congestion, max_iterations=1), - refinement=replace(case.options.refinement, enabled=False), - topology=TopologyOptions(mode="automatic"), - ) - iterations = [] - run = route(case.problem, options=options, iteration_callback=lambda iteration, _: iterations.append(iteration)) - - assert run.automatic is not None - assert run.automatic.selected_planner == "perimeter" - assert max(stage.node_limit for stage in run.automatic.stages) == 1 - assert iterations == list(range(run.metrics.route_iterations)) - assert run.metrics.refine_path_calls == 0 - assert run.results_by_net["return"].is_valid diff --git a/inire/tests/test_routing_fixtures.py b/inire/tests/test_routing_fixtures.py new file mode 100644 index 0000000..64f5f25 --- /dev/null +++ b/inire/tests/test_routing_fixtures.py @@ -0,0 +1,186 @@ +from dataclasses import replace +from itertools import combinations + +import pytest +from shapely import union_all +from shapely.geometry import Point, box + +from inire import Bend90Seed, RoutingRunResult, SBendSeed, StraightSeed, route +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.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} +_PLANNER_WITHOUT_SEARCH = { + "competing-detours": "paired-perimeter", + "crossing-staggered-grid": "local-sbend", + "precision-return-offset": "perimeter", + "scale-field-20x16": "column-recovery", + "search-comb-3x4": "column-recovery", + "stress-crossings-shared-outside-detour": "residual-dogleg", + "terminal-bench": "bundle-turnaround", + "terminal-bench-pair": "paired-perimeter", +} + + +@pytest.mark.routing_corpus +@pytest.mark.parametrize( + "case", + [ + pytest.param(case, id=case.name, marks=pytest.mark.retry_holdout if case.name in _RETRY_HOLDOUT_NAMES else ()) + for case in select_cases(("corpus", "retry-holdout")) + ], +) +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 + + profile = "corpus-regression" + options = automatic_options(profile_options(case, profile), profile) + callback_indices = [] + + def record_iteration(index, _results): + callback_indices.append(index) + + callback = record_iteration if case.name == "crossing-with-room" else None + run = route(case.problem, options=options, iteration_callback=callback) + + 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} + assert run.automatic.max_routed == case.routing_bound + assert set(run.automatic.verified_net_ids) == verified + assert len(verified) == case.routing_bound + for net in case.problem.nets: + if net.net_id in verified: + result = run.results_by_net[net.net_id] + effective = result.effective_net if options.topology.infer_terminal_headings else net + assert result.path[0].start_port == effective.start + assert result.path[-1].end_port == effective.target + + if case.name in _PLANNER_WITHOUT_SEARCH: + assert run.automatic.selected_planner == _PLANNER_WITHOUT_SEARCH[case.name] + assert run.metrics.nodes_expanded == 0 + if case.name in {"competing-detours", "precision-return-offset"}: + assert not any(stage.operation == "search" for stage in run.automatic.stages) + if case.name == "crossing-staggered-grid": + assert all(sum(move.move_type == "sbend" for move in result.path) == 1 for result in run.results_by_net.values()) + if case.name == "crossing-with-room": + assert sum(stage.operation == "search" for stage in run.automatic.stages) >= 2 + assert len(callback_indices) >= 2 + assert callback_indices == list(range(run.metrics.route_iterations)) + if case.name == "stress-crossings-shared-outside-detour": + [partial] = [stage for stage in run.automatic.stages if stage.planner == "local-sbend" and stage.operation == "verify"] + assert set(partial.valid_net_ids) == verified - {"outside_lower"} + 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 == "fallback-custom-physical": + assert run.automatic.selected_planner == "lattice" + assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback" + assert reference_run is not None + assert run.results_by_net.keys() == reference_run.results_by_net.keys() + for net_id, result in run.results_by_net.items(): + expected = reference_run.results_by_net[net_id] + assert result.as_seed() == expected.as_seed() + assert result.locked_geometry == expected.locked_geometry + + +def test_expanded_corpus_uses_physical_dimensions_and_has_reference_coverage() -> None: + corpus_names = {case.name for case in CORPUS_CASES} + assert len(corpus_names) == len(CORPUS_CASES) + assert corpus_names.isdisjoint(case.name for case in RETRY_HOLDOUT_CASES) + expanded = CASE_GROUPS["expanded"] + assert len(expanded) >= 50 + for case in expanded: + assert case.name in corpus_names + assert case.grid_nm is not None + assert 10 <= case.grid_nm <= 1000 + assert not case.problem.initial_paths + assert len(dict(case.reference_paths)) == case.routing_bound + assert all(1000 <= net.width * case.grid_nm <= 20000 for net in case.problem.nets) + radii = (*case.options.search.bend_radii, *case.options.search.sbend_radii) + assert radii + assert all(10000 <= radius * case.grid_nm <= 100000 for radius in radii) + scaling = CASE_GROUPS["scaling"] + assert any(len(case.problem.nets) >= 200 and len(case.problem.static_obstacles) >= 200 for case in scaling) + assert any(len(case.problem.nets) < 200 <= len(case.problem.static_obstacles) for case in scaling) + assert any(len(case.problem.static_obstacles) < 200 <= len(case.problem.nets) for case in scaling) + + +def _check_reference_paths(case) -> RoutingRunResult: + reference = dict(case.reference_paths) + problem = replace(case.problem, nets=tuple(net for net in case.problem.nets if net.net_id in reference), initial_paths=reference) + options = replace( + case.options, + search=replace(case.options.search, node_limit=0), + refinement=replace(case.options.refinement, enabled=False), + ) + run = route(problem, options=options) + + assert run.metrics.nodes_expanded == 0 + assert run.results_by_net.keys() == reference.keys() + board = box(*problem.bounds) + footprints = [] + for result in run.results_by_net.values(): + assert result.is_valid + assert result.as_seed() == reference[result.net_id] + footprint = union_all(result.locked_geometry) + assert board.covers(footprint) + assert all(footprint.distance(obstacle) >= problem.clearance - TOLERANCE_LINEAR for obstacle in problem.static_obstacles) + footprints.append(footprint) + for a, b in combinations(footprints, 2): + assert a.distance(b) >= problem.clearance - TOLERANCE_LINEAR + return run + + +def test_stress_and_retry_holdout_cases_start_unseeded_with_complete_reference_paths() -> None: + cases = (*STRESS_BENCHMARK_CASES, *RETRY_HOLDOUT_CASES) + assert len({case.name for case in cases}) == len(cases) + for case in 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_complex_benchmarks_are_distinct_unseeded_nine_net_problems() -> None: + assert len({case.name for case in BENCHMARK_CASES}) == len(BENCHMARK_CASES) + assert len(COMPLEX_BENCHMARK_CASES) == 20 + layouts = set() + for case in COMPLEX_BENCHMARK_CASES: + problem = case.problem + assert len(problem.nets) == 9 + assert not problem.initial_paths + if case.reference_paths: + assert {net_id for net_id, _ in case.reference_paths} == {net.net_id for net in problem.nets} + layouts.add((problem.bounds, problem.nets, tuple(sorted(shape.bounds for shape in problem.static_obstacles)))) + assert len(layouts) == len(COMPLEX_BENCHMARK_CASES) + + +def _check_external_fixture(case) -> None: + problem = case.problem + assert not problem.initial_paths + assert not case.reference_paths + assert len({net.net_id for net in problem.nets}) == len(problem.nets) + board = box(*problem.bounds) + for obstacle in problem.static_obstacles: + assert obstacle.is_valid + assert board.covers(obstacle) + for net in problem.nets: + for port in (net.start, net.target): + position = Point(port.x, port.y) + assert board.covers(position) + assert all(position.distance(obstacle) >= net.width / 2 + problem.clearance for obstacle in problem.static_obstacles) diff --git a/inire/tests/test_terminal_bench.py b/inire/tests/test_terminal_bench.py index ef0f2a6..a160e7d 100644 --- a/inire/tests/test_terminal_bench.py +++ b/inire/tests/test_terminal_bench.py @@ -1,5 +1,5 @@ from dataclasses import replace -from itertools import combinations, pairwise +from itertools import combinations import pytest import shapely @@ -7,7 +7,7 @@ from shapely import union_all from shapely.affinity import translate from shapely.geometry import box -from inire import Bend90Seed, DiagnosticsOptions, NetSpec, Port, SBendSeed, TopologyOptions, route +from inire import Bend90Seed, DiagnosticsOptions, Port, SBendSeed, TopologyOptions, route from inire.constants import TOLERANCE_LINEAR from inire.router._waypoints import export_waypoints from inire.tests.terminal_bench_lane_plan import terminal_bench_lane_problem @@ -16,49 +16,11 @@ from inire.tests.terminal_bench_scenario import ( BOARD, CLEARANCE, LENGTH_COST, - MIN_SEPARATION, - NET_WIDTH, terminal_bench_options, terminal_bench_problem, ) -def test_terminal_bench_full_board_bounded_run() -> None: - problem = terminal_bench_problem() - run = route(problem, options=terminal_bench_options(node_limit=100, max_iterations=1)) - - assert NET_WIDTH + CLEARANCE == MIN_SEPARATION - assert tuple(run.results_by_net) == tuple(f"net_{index:02d}" for index in range(9)) - assert run.results_by_net["net_03"].reached_target - for net in problem.nets: - result = run.results_by_net[net.net_id] - if not result.path: - assert not result.reached_target - continue - assert result.path[0].start_port == net.start - assert result.reached_target == (result.path[-1].end_port == net.target) - assert all(a.end_port == b.start_port for a, b in pairwise(result.path)) - - -@pytest.mark.parametrize("net_id", ["net_03", "net_04"]) -def test_terminal_bench_isolated_connection(net_id: str) -> None: - problem = terminal_bench_problem() - net = next(net for net in problem.nets if net.net_id == net_id) - run = route(replace(problem, nets=(net,)), options=terminal_bench_options(node_limit=500, max_iterations=1)) - result = run.results_by_net[net_id] - - assert result.is_valid - assert result.path[0].start_port == net.start - assert result.path[-1].end_port == net.target - board = box(*BOARD) - for component in result.path: - for shape in component.physical_geometry: - assert board.covers(shape) - assert all(shape.distance(obstacle) >= CLEARANCE for obstacle in problem.static_obstacles) - if isinstance(component.move_spec, Bend90Seed | SBendSeed): - assert component.move_spec.radius == BEND_RADIUS - - @pytest.mark.parametrize("share_bottom_passage", [False, True], ids=["single-bottom-track", "shared-bottom-passage"]) def test_terminal_bench_lane_plan_verifies_all_nine_nets(share_bottom_passage: bool) -> None: problem = terminal_bench_lane_problem(share_bottom_passage=share_bottom_passage) @@ -134,30 +96,8 @@ def test_bundle_preserves_explicit_terminal_headings_by_default() -> None: route(terminal_bench_problem(), options=options) -@pytest.mark.parametrize("mode", ["bundle", "automatic"]) -def test_bundle_and_turnaround_use_the_smallest_common_radius(mode) -> None: - options = terminal_bench_options(node_limit=1, max_iterations=1) - options = replace( - options, - search=replace(options.search, bend_radii=(BEND_RADIUS / 2, BEND_RADIUS)), - refinement=replace(options.refinement, enabled=False), - topology=TopologyOptions(mode=mode, infer_terminal_headings=(mode == "bundle")), - ) - - run = route(terminal_bench_problem(), options=options) - - assert all(result.is_valid for result in run.results_by_net.values()) - assert run.metrics.nodes_expanded == 0 - if mode == "automatic": - assert run.automatic.selected_planner == "bundle-turnaround" - for result in run.results_by_net.values(): - for move in result.as_seed().segments: - if isinstance(move, Bend90Seed | SBendSeed): - assert move.radius == BEND_RADIUS - - -@pytest.mark.parametrize("mode", ["bundle", "automatic"]) -def test_bundle_retries_the_next_common_radius_when_the_shelf_cannot_use_the_first(mode) -> None: +def test_bundle_retries_the_next_common_radius_when_the_shelf_cannot_use_the_first() -> None: + mode = 'automatic' options = terminal_bench_options(node_limit=1, max_iterations=1) radii = (BEND_RADIUS / 2, BEND_RADIUS) options = replace( @@ -179,56 +119,37 @@ def test_bundle_retries_the_next_common_radius_when_the_shelf_cannot_use_the_fir } == {BEND_RADIUS} -def test_bundle_plans_tracks_without_coincident_nets() -> None: - problem = terminal_bench_problem() - port = problem.nets[0].start - coincident = NetSpec("abutting", port, port) - options = replace(terminal_bench_options(), topology=TopologyOptions(mode="bundle", infer_terminal_headings=True)) - - run = route(replace(problem, nets=(coincident, *problem.nets)), options=options) - - assert run.results_by_net[coincident.net_id].outcome == "unroutable" - assert all(run.results_by_net[net.net_id].is_valid for net in problem.nets) - assert run.topology.seeded_net_ids == tuple(net.net_id for net in problem.nets) - - -@pytest.mark.parametrize("unsupported", ["missing-function", "old-geos"]) -def test_automatic_constructs_bundle_without_triangulation(unsupported, monkeypatch) -> None: - if unsupported == "missing-function": - monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) - else: - monkeypatch.setattr(shapely, "geos_version", (3, 9, 0)) - base = terminal_bench_options(node_limit=100, max_iterations=1) - options = replace( - base, topology=TopologyOptions(infer_terminal_headings=True), diagnostics=DiagnosticsOptions(capture_iteration_trace=True), - ) - callbacks = [] - run = route(terminal_bench_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:] - - assert run.automatic is not None - assert len(run.automatic.verified_net_ids) == 9 - assert run.metrics.nodes_expanded == 0 - result = run.results_by_net["net_08"] - requested = next(net for net in terminal_bench_problem().nets if net.net_id == result.net_id) - assert result.path[-1].end_port.r == 180 - assert result.requested_net == requested - assert result.effective_net == replace(requested, target=replace(requested.target, r=180)) - - -def test_placement_recipes_replay_with_resolved_ports() -> None: +def test_bundle_without_triangulation_replays_with_resolved_ports(monkeypatch: pytest.MonkeyPatch) -> None: problem = terminal_bench_problem() options = replace( terminal_bench_options(node_limit=100, max_iterations=1), topology=TopologyOptions(infer_terminal_headings=True), + diagnostics=DiagnosticsOptions(capture_iteration_trace=True), ) - run = route(problem, options=options) + 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)) + + assert len(callbacks) >= 2 + assert [entry.iteration for entry in run.iteration_trace] == callbacks[-1:] + assert run.automatic is not None + assert set(run.automatic.verified_net_ids) == {net.net_id for net in problem.nets} assert all(result.is_valid for result in run.results_by_net.values()) + assert run.metrics.nodes_expanded == 0 + result = run.results_by_net["net_08"] + requested_net = next(net for net in problem.nets if net.net_id == result.net_id) + assert result.path[-1].end_port.r == 180 + assert result.requested_net == requested_net + assert result.effective_net == replace(requested_net, target=replace(requested_net.target, r=180)) + seeds = {key: result.as_seed() for key, result in run.results_by_net.items()} replay_options = replace( - options, search=replace(options.search, node_limit=0), topology=TopologyOptions(mode="off"), + options, + search=replace(options.search, node_limit=0), + topology=TopologyOptions(mode="off"), refinement=replace(options.refinement, enabled=False), + diagnostics=DiagnosticsOptions(), ) requested = route(replace(problem, initial_paths=seeds), options=replay_options) assert not requested.results_by_net["net_08"].reached_target diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py index 8f1b41c..c56f07f 100644 --- a/inire/tests/test_topology.py +++ b/inire/tests/test_topology.py @@ -1,7 +1,6 @@ from dataclasses import replace import pytest -from shapely.affinity import rotate, scale from shapely.geometry import LineString, Polygon, box from inire import ( @@ -13,8 +12,8 @@ from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_l from inire.tests.routing_benchmarks import DETOUR -@pytest.mark.parametrize("hint", [(), (StraightSeed(5),), (StraightSeed(680),)]) -def test_seed_mode_realizes_corridor_with_incomplete_or_invalid_hint(hint) -> None: +def test_seed_mode_recovers_a_corridor_after_an_invalid_hint() -> None: + hint = (StraightSeed(680),) problem = replace(DETOUR.problem, initial_paths={"detour": PathSeed(hint)}) options = replace( DETOUR.options, @@ -30,24 +29,13 @@ def test_seed_mode_realizes_corridor_with_incomplete_or_invalid_hint(hint) -> No assert 0 < run.metrics.nodes_expanded <= 100 -@pytest.mark.parametrize("heading", [0, 90, 180, 270]) -def test_flat_ended_straight_recovery_after_a_bend_is_cardinally_invariant(heading) -> None: - keepout = rotate(box(52.85, 25, 54, 27.2), heading, origin=(0, 0)) - board = rotate(box(38, 18, 54, 62), heading, origin=(0, 0)) - start, target = Port(40, 20, 0).rotated(heading), Port(40, 60, 180).rotated(heading) - problem = RoutingProblem(board.bounds, (NetSpec("flat", start, target),), (keepout,)) - options = RoutingOptions( - search=SearchOptions(node_limit=200, bend_radii=(10,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - assert route(problem, options=options).results_by_net["flat"].is_valid - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) -@pytest.mark.parametrize("sign", [1, -1]) +@pytest.mark.parametrize( + ('mode', 'sign'), + [ + ('off', 1), + ('guide', -1), + ], +) def test_search_infers_intermediate_sbend_offsets(mode, sign) -> None: problem = RoutingProblem((0, 0, 100, 100), (NetSpec("shift", Port(20, 50, 0), Port(56, 50 + sign * 20, 0)),), clearance=0) options = RoutingOptions( @@ -66,26 +54,6 @@ def test_search_infers_intermediate_sbend_offsets(mode, sign) -> None: assert sum(offsets) == sign * 20 -@pytest.mark.parametrize("reflection", [-1, 1]) -def test_bounded_search_revisits_turns_away_from_the_target(reflection) -> None: - start, target = Port(190, reflection * -40, 270 if reflection == 1 else 90), Port(20, reflection * -50, 0) - board = scale(box(-25, -185, 230, 0), yfact=reflection, origin=(0, 0)) - keepout = scale(box(50, -185, 187, -37), yfact=reflection, origin=(0, 0)) - problem = RoutingProblem(board.bounds, (NetSpec("detour", start, target),), (keepout,), clearance=1) - options = RoutingOptions( - search=SearchOptions(node_limit=500, min_straight_length=2, max_straight_length=40, bend_radii=(10,), sbend_radii=()), - objective=ObjectiveWeights(bend_penalty=10, danger_weight=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["detour"].is_valid - assert run.metrics.nodes_expanded <= 500 - - def test_small_budget_admits_a_turn_away_from_the_target() -> None: net = NetSpec("detour", Port(503, -65, 270), Port(20, -12, 180)) problem = RoutingProblem((0, -185, 555, 0), (net,), (box(50, -185, 500, -38),), clearance=1) @@ -103,28 +71,8 @@ def test_small_budget_admits_a_turn_away_from_the_target() -> None: assert run.metrics.nodes_expanded <= 10 -@pytest.mark.parametrize("with_peer", [False, True]) -def test_narrow_alternative_remains_available_with_a_shared_guide(with_peer) -> None: - narrow = NetSpec("narrow", Port(60, 110, 0), Port(740, 110, 0)) - wide = NetSpec("wide", Port(100, 500, 0), Port(150, 500, 0), 100) - nets = (narrow, wide) if with_peer else (narrow,) - problem = RoutingProblem((0, 0, 800, 600), nets, (box(300, 50, 480, 350),), clearance=6) - options = RoutingOptions( - search=SearchOptions(node_limit=500, bend_radii=(20,), sbend_radii=()), - objective=ObjectiveWeights(danger_weight=0), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="seed"), - ) - - run = route(problem, options=options) - - assert all(result.is_valid for result in run.results_by_net.values()) - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) @pytest.mark.parametrize("narrow_by", [0, 0.001]) -def test_offset_gate_search_uses_exact_clearance(mode, narrow_by) -> None: +def test_offset_gate_search_uses_exact_clearance(narrow_by) -> None: walls = ( box(20, 0, 26, 5 + narrow_by), box(20, 9 - narrow_by, 26, 25), box(43, 0, 49, 11 + narrow_by), box(43, 15 - narrow_by, 49, 25), @@ -136,14 +84,14 @@ def test_offset_gate_search_uses_exact_clearance(mode, narrow_by) -> None: objective=ObjectiveWeights(danger_weight=0), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode=mode), + topology=TopologyOptions(mode="guide"), ) assert route(problem, options=options).results_by_net["gate"].is_valid == (narrow_by == 0) -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) -def test_rounded_keepout_guidance_preserves_acute_aperture(mode) -> None: +def test_rounded_keepout_guidance_preserves_acute_aperture() -> None: + mode = 'seed' keepouts = (Polygon([(35, 0), (65, 0), (50, 22.95)]), Polygon([(35, 50), (65, 50), (50, 27.05)])) problem = RoutingProblem((0, 0, 100, 50), (NetSpec("opening", Port(7, 15, 0), Port(93, 35, 0)),), keepouts, clearance=1) options = RoutingOptions( @@ -157,8 +105,8 @@ def test_rounded_keepout_guidance_preserves_acute_aperture(mode) -> None: assert route(problem, options=options).results_by_net["opening"].is_valid -@pytest.mark.parametrize("mode", ["guide", "seed"]) -def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate(mode) -> None: +def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None: + mode = 'seed' nets = (NetSpec("a", Port(16, 48, 0), Port(199, 82, 0), 4.5), NetSpec("b", Port(18, 59, 0), Port(197, 93, 0), 1.25)) walls = (box(60, 0, 67, 56.25), box(60, 74.125, 67, 118), box(125, 0, 132, 66.25), box(125, 84.125, 132, 118)) problem = RoutingProblem((0, 0, 219, 118), nets, walls, clearance=1) @@ -209,25 +157,6 @@ def test_topological_planner_finds_both_sides_of_an_obstacle() -> None: assert crossing_heights[1] >= 437 -@pytest.mark.parametrize("mode", ["guide", "seed"]) -def test_public_topological_modes_route_a_detour(mode) -> None: - options = replace(DETOUR.options, topology=TopologyOptions(mode=mode)) - problem = DETOUR.problem - run = route(problem, options=options) - - assert run.results_by_net["detour"].is_valid - assert run.topology is not None - assert run.topology.corridor_counts == (("detour", 2),) - assert run.metrics.refine_path_calls == 1 - if mode == "seed": - assert run.topology.seeded_net_ids == ("detour",) - assert 0 < run.topology.seed_nodes_expanded <= options.search.node_limit - assert all(box(*problem.bounds).covers(shape) for shape in run.results_by_net["detour"].locked_geometry) - else: - assert run.topology.seeded_net_ids == () - assert run.topology.seed_nodes_expanded == 0 - - def test_seed_mode_respects_user_paths_on_repeated_runs() -> None: existing = PathSeed((StraightSeed(140),)) problem = RoutingProblem( @@ -248,8 +177,8 @@ def test_seed_mode_respects_user_paths_on_repeated_runs() -> None: assert list(stack.world.iter_static_dilated_geometries()) == [] -@pytest.mark.parametrize("mode", ["guide", "seed"]) -def test_narrow_net_recovers_corridors_with_a_wide_peer(mode) -> None: +def test_narrow_net_recovers_corridors_with_a_wide_peer() -> None: + mode = 'seed' wide = NetSpec("wide", Port(12, 200, 0), Port(30, 200, 0), width=180) problem = replace(DETOUR.problem, nets=(*DETOUR.problem.nets, wide)) options = replace( @@ -267,48 +196,3 @@ def test_narrow_net_recovers_corridors_with_a_wide_peer(mode) -> None: if mode == "seed": assert run.topology.seeded_net_ids == ("detour",) assert run.results_by_net["detour"].is_valid - - -def test_seed_mode_routes_a_detour_between_flush_board_ports() -> None: - problem = replace(DETOUR.problem, nets=(NetSpec("detour", Port(0, 300, 0), Port(800, 300, 0)),)) - options = replace( - DETOUR.options, - search=replace(DETOUR.options.search, node_limit=100), - congestion=replace(DETOUR.options.congestion, max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="seed"), - ) - run = route(problem, options=options) - - assert run.results_by_net["detour"].is_valid - assert run.topology is not None - assert run.topology.corridor_counts == (("detour", 2),) - assert run.topology.seeded_net_ids == ("detour",) - - -def test_board_edge_lead_requires_a_clear_flat_footprint() -> None: - board = box(0, 0, 100, 100) - mesh = _Mesh(board, (box(0, 48, 1, 52),), 1, 2) - assert mesh.endpoint(Port(0, 50, 0), 1, 10) is None - assert mesh.endpoint(Port(0, 0, 0), 1, 10) is None - assert mesh.endpoint(Port(0, 60, 0), 1, 10) is not None - - -def test_seed_mode_keeps_a_verified_route_when_another_net_is_partial() -> None: - problem = RoutingProblem( - bounds=(0, 0, 200, 100), - nets=( - NetSpec("barrier", Port(1, 50, 0), Port(199, 50, 0)), - NetSpec("crossing", Port(100, 10, 90), Port(100, 90, 90)), - ), - ) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10,), node_limit=100), - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), - topology=TopologyOptions(mode="seed"), - ) - run = route(problem, options=options) - - assert run.topology is not None - assert run.topology.seeded_net_ids == ("barrier",) - assert run.results_by_net["barrier"].is_valid - assert not run.results_by_net["crossing"].is_valid diff --git a/inire/tests/test_variable_grid.py b/inire/tests/test_variable_grid.py deleted file mode 100644 index e0acd71..0000000 --- a/inire/tests/test_variable_grid.py +++ /dev/null @@ -1,71 +0,0 @@ -import unittest - -from inire.geometry.primitives import Port -from inire.model import RoutingOptions, RoutingProblem -from inire.router._astar_types import AStarContext, SearchRunConfig -from inire.router._search import route_astar -from inire.router.cost import CostEvaluator -from inire.geometry.collision import RoutingWorld - - -class TestIntegerPorts(unittest.TestCase): - def setUp(self): - self.ce = RoutingWorld(clearance=2.0) - self.cost = CostEvaluator(self.ce) - self.bounds = (0, 0, 100, 100) - - def _build_context(self) -> AStarContext: - return AStarContext( - self.cost, - RoutingProblem(bounds=self.bounds), - RoutingOptions(), - ) - - def _route(self, context: AStarContext, start: Port, target: Port): - return route_astar( - start, - target, - net_width=1.0, - context=context, - config=SearchRunConfig.from_options(context.options), - ) - - def test_route_reaches_integer_target(self): - context = self._build_context() - start = Port(0, 0, 0) - target = Port(12, 0, 0) - - path = self._route(context, start, target) - - self.assertIsNotNone(path) - last_port = path[-1].end_port - self.assertEqual(last_port.x, 12) - self.assertEqual(last_port.y, 0) - self.assertEqual(last_port.r, 0) - - def test_port_constructor_rounds_to_integer_lattice(self): - context = self._build_context() - start = Port(0.0, 0.0, 0.0) - target = Port(12.3, 0.0, 0.0) - - path = self._route(context, start, target) - - self.assertIsNotNone(path) - self.assertEqual(target.x, 12) - last_port = path[-1].end_port - self.assertEqual(last_port.x, 12) - - def test_half_step_inputs_use_integerized_targets(self): - context = self._build_context() - start = Port(0.0, 0.0, 0.0) - target = Port(7.5, 0.0, 0.0) - - path = self._route(context, start, target) - - self.assertIsNotNone(path) - self.assertEqual(target.x, 8) - last_port = path[-1].end_port - self.assertEqual(last_port.x, 8) - -if __name__ == '__main__': - unittest.main() diff --git a/inire/tests/test_visibility.py b/inire/tests/test_visibility.py index 03274d9..a2cbd2f 100644 --- a/inire/tests/test_visibility.py +++ b/inire/tests/test_visibility.py @@ -22,51 +22,6 @@ def test_corner_visibility_cache_respects_max_distance() -> None: assert any(corner[0] >= 100.0 for corner in far_corners) -def test_visibility_manager_is_lazy_until_queried() -> None: - engine = RoutingWorld(clearance=0.0) - engine.metrics = AStarMetrics() - engine.add_static_obstacle(box(10, 20, 20, 30)) - - visibility = VisibilityManager(engine) - - assert visibility.corners == [] - assert engine.metrics.total_visibility_corner_index_builds == 0 - - visibility.ensure_corner_index_current() - - assert visibility.corners - assert engine.metrics.total_visibility_corner_index_builds == 1 - - -def test_exact_corner_visibility_caches_local_queries() -> None: - engine = RoutingWorld(clearance=0.0) - engine.metrics = AStarMetrics() - engine.add_static_obstacle(box(10, 20, 20, 30)) - visibility = VisibilityManager(engine) - origin = Port(10, 20, 0) - - first = visibility.get_corner_visibility(origin, max_dist=100.0) - second = visibility.get_corner_visibility(origin, max_dist=100.0) - - assert second == first - assert engine.metrics.total_visibility_corner_index_builds == 1 - assert engine.metrics.total_visibility_point_cache_misses == 1 - assert engine.metrics.total_visibility_point_cache_hits == 1 - assert engine.metrics.total_visibility_builds == 0 - assert engine.metrics.total_visibility_corner_pairs_checked == 0 - - -def test_exact_corner_visibility_respects_fractional_distance_limits() -> None: - engine = RoutingWorld(clearance=0.0) - engine.add_static_obstacle(box(0, 0, 1, 1)) - engine.add_static_obstacle(box(-11, 0, -9.9996, 1)) - visibility = VisibilityManager(engine) - origin = Port(0, 0, 0) - - assert visibility.get_corner_visibility(origin, max_dist=9.99955) == [] - assert visibility.get_corner_visibility(origin, max_dist=9.99965) == [(-10.0, 0.0, 9.9996)] - - def test_exact_corner_visibility_accepts_only_endpoint_contact_and_scales_to_large_boards() -> None: engine = RoutingWorld(clearance=0.0) engine.add_static_obstacle(box(10, 20, 20, 30)) diff --git a/pyproject.toml b/pyproject.toml index 9f682d2..624c867 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -99,5 +99,6 @@ 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", + "routing_corpus: routing coverage checks on the regression corpus and retry holdouts", + "retry_holdout: routing coverage checks on the retry holdouts", ] From 1f098fd4caddb10ffb56478ce5b3afcbe36f125e Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 22:30:23 -0800 Subject: [PATCH 47/57] Render polygon holes in XY for 3D inputs --- inire/tests/test_visualization.py | 3 ++- inire/utils/visualization.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/inire/tests/test_visualization.py b/inire/tests/test_visualization.py index 1bf99b1..a61795b 100644 --- a/inire/tests/test_visualization.py +++ b/inire/tests/test_visualization.py @@ -1,5 +1,6 @@ from matplotlib import pyplot as plt from numpy import asarray +from shapely import force_3d from shapely.geometry import Polygon, box from inire.utils.visualization import plot_routing_results @@ -7,7 +8,7 @@ from scripts.render_documentation_figures import _polygon def test_polygon_holes_remain_unfilled_in_routes_and_documentation() -> None: - keepout = Polygon(box(1, 1, 9, 9).exterior, [box(3, 3, 7, 7).exterior]) + keepout = force_3d(Polygon(box(1, 1, 9, 9).exterior, [box(3, 3, 7, 7).exterior]), z=1) figure, route_axes = plot_routing_results({}, [keepout], (0, 0, 10, 10)) walkthrough_axes = figure.add_axes((0.6, 0.6, 0.25, 0.25)) _polygon(walkthrough_axes, keepout, fill="gray", edge="black") diff --git a/inire/utils/visualization.py b/inire/utils/visualization.py index f7fd1d8..5c337bb 100644 --- a/inire/utils/visualization.py +++ b/inire/utils/visualization.py @@ -33,7 +33,7 @@ def draw_polygon(ax: Axes, polygon: Polygon, **style: object) -> None: return polygon = orient(polygon) - paths = [Path(list(ring.coords), closed=True) for ring in (polygon.exterior, *polygon.interiors)] + paths = [Path(numpy.column_stack(ring.xy), closed=True) for ring in (polygon.exterior, *polygon.interiors)] ax.add_patch(PathPatch(Path.make_compound_path(*paths), **style)) From 7476209ef394ae279a6053e1f94d9757d60a858b Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 22:30:29 -0800 Subject: [PATCH 48/57] 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] From b59888265d10e3328daeba2aaf65cfa6c19bc69c Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 22:39:12 -0800 Subject: [PATCH 49/57] Fix locked-order coverage and native benchmark scoring --- inire/router/cost.py | 2 +- inire/tests/routing_corpus.py | 2 +- inire/tests/test_routing_benchmarks.py | 39 ++++++++++++++++++++++++++ scripts/compare_topological_routing.py | 10 ++----- 4 files changed, 43 insertions(+), 10 deletions(-) diff --git a/inire/router/cost.py b/inire/router/cost.py index c76017b..7724882 100644 --- a/inire/router/cost.py +++ b/inire/router/cost.py @@ -277,7 +277,7 @@ def proximity_map(problem: RoutingProblem, proximity_range: float) -> DangerMap: ) -def build_native_cost_evaluator(problem: RoutingProblem, objective: ObjectiveWeights, *, proximity_range: float = 10.0) -> CostEvaluator: +def build_native_cost_evaluator(problem: RoutingProblem, objective: ObjectiveWeights, *, proximity_range: float) -> CostEvaluator: """Score candidate paths using the original layout's obstacles and objective.""" danger = None if objective.danger_weight and problem._blocking_polygons: diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index 6ad0aad..49949b9 100644 --- a/inire/tests/routing_corpus.py +++ b/inire/tests/routing_corpus.py @@ -139,7 +139,7 @@ def native_verified_costs( results: dict[str, RoutingResult], verified_net_ids: Iterable[str], ) -> dict[str, float]: - scorer = build_native_cost_evaluator(case.problem, options.objective) + scorer = build_native_cost_evaluator(case.problem, options.objective, proximity_range=options.search.proximity_range) costs = {} for net_id in verified_net_ids: path = results[net_id].path diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 1f9e09d..8ebf000 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -15,6 +15,7 @@ from inire.router._automatic import _AutomaticRun from inire.router._capacity import port_conflicts from inire.router._routing_policy import _disconnected_nets from inire.router.cost import weighted_path_length +from inire.tests.routing_benchmark_case import BenchmarkCase from inire.tests.routing_benchmarks import ( BENCHMARK_CASES, CROSSING_BENCHMARK_CASES, @@ -158,6 +159,44 @@ def test_benchmark_profile_records_effective_options(tmp_path, monkeypatch) -> N assert options["topology"]["automatic_length_weights"] is None +def test_seed_order_locked_rejects_touching_routes_at_zero_clearance() -> None: + problem = RoutingProblem( + bounds=(0, 0, 100, 40), + nets=(NetSpec("a", Port(10, 10, 0), Port(90, 10, 0)), NetSpec("b", Port(10, 12, 0), Port(90, 12, 0))), + clearance=0, + ) + options = RoutingOptions( + search=SearchOptions(node_limit=60, bend_radii=(), sbend_radii=()), + congestion=CongestionOptions(max_iterations=1), + ) + case = BenchmarkCase("touching-routes", "Two straight routes sharing an edge", problem, options) + + sample = _measure(case, options, "seed-order-locked") + + first, retry = sample.stages + assert first.valid_net_ids == ("a",) + assert retry.incumbent_net_ids == first.valid_net_ids + assert retry.valid_net_ids == first.valid_net_ids + assert sample.valid_costs.keys() == {"a"} + + +def test_benchmark_native_cost_uses_configured_proximity_range() -> None: + problem = RoutingProblem( + bounds=(0, 0, 100, 40), + nets=(NetSpec("a", Port(10, 10, 0), Port(90, 10, 0)),), + static_obstacles=(box(0, 28, 100, 30),), + ) + options = RoutingOptions(search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=())) + case = BenchmarkCase("proximity-cost", "Straight route near one keepout", problem, options) + + default = _measure(case, options, "off") + wider = _measure(case, replace(options, search=replace(options.search, proximity_range=40)), "off") + + assert default.valid_costs == wider.valid_costs == {"a": 80.0} + assert default.native_valid_costs == {"a": 80.0} + assert wider.native_valid_costs["a"] > default.native_valid_costs["a"] + + def test_connectivity_screen_checks_each_net_width_and_leaves_unknown_ports_for_search() -> None: problem = RoutingProblem( bounds=(0, 0, 400, 160), diff --git a/scripts/compare_topological_routing.py b/scripts/compare_topological_routing.py index 80eb16f..2d6e377 100644 --- a/scripts/compare_topological_routing.py +++ b/scripts/compare_topological_routing.py @@ -17,7 +17,7 @@ import shapely from shapely.geometry import box, mapping from inire import RoutingOptions, RoutingStage, route -from inire.router._routing_policy import _best_trial +from inire.router._routing_policy import LockPlan, _best_trial, _residual_problem from inire.router._routing_policy import _trial as _summarize_trial from inire.tests.direct_routing_policies import DIRECT_POLICIES from inire.tests.direct_routing_policies import direct_trials as _direct_trials @@ -98,13 +98,7 @@ def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: st seeds = {net_id: result.as_seed() for net_id, result in incumbents.items()} second_problem = replace(problem, initial_paths={**seeds, **problem.initial_paths}) elif strategy == "seed-order-locked" and incumbents: - locked = tuple(shape for result in incumbents.values() for shape in result.locked_geometry) - second_problem = replace( - problem, - nets=tuple(net for net in problem.nets if net.net_id not in incumbents), - static_obstacles=problem.static_obstacles + locked, - initial_paths={net_id: seed for net_id, seed in problem.initial_paths.items() if net_id not in incumbents}, - ) + second_problem = _residual_problem(problem, LockPlan(incumbents)) else: second_problem = problem From f609e5a69582fdc47300653cacadddc11483c891 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 22:39:16 -0800 Subject: [PATCH 50/57] Simplify residual routing and document seed precedence --- docs/user/tune-and-troubleshoot.md | 3 ++- inire/router/_routing_policy.py | 18 +++--------------- 2 files changed, 5 insertions(+), 16 deletions(-) diff --git a/docs/user/tune-and-troubleshoot.md b/docs/user/tune-and-troubleshoot.md index 662b70a..a4d04ea 100644 --- a/docs/user/tune-and-troubleshoot.md +++ b/docs/user/tune-and-troubleshoot.md @@ -35,7 +35,8 @@ Set `TopologyOptions(mode=...)` and pass it as `topology` in `RoutingOptions`. ### Mode requirements -- 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) +- 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. 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) +- Seed mode gives complete caller-supplied paths priority when they can be reserved without collisions. Partial paths are hints. Seed mode may replace them with complete paths generated from a corridor before the main search. - 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. It can try lattice search after constructive planning and corridor-guided search leave unresolved nets. diff --git a/inire/router/_routing_policy.py b/inire/router/_routing_policy.py index b390a2b..e05865b 100644 --- a/inire/router/_routing_policy.py +++ b/inire/router/_routing_policy.py @@ -217,21 +217,9 @@ def _route_residual( residual_mode: Literal["guide", "seed"] | None = None, run_route: RouteCall = route_once, ) -> tuple[RoutingRunResult, RoutingStage]: - return _route_prepared_residual( - _residual_problem(problem, locks), options, locks, residual_mode=residual_mode, run_route=run_route - ) - - -def _route_prepared_residual( - problem: RoutingProblem, - options: RoutingOptions, - locks: LockPlan, - *, - residual_mode: Literal["guide", "seed"] | None = None, - run_route: RouteCall = route_once, -) -> tuple[RoutingRunResult, RoutingStage]: + residual_problem = _residual_problem(problem, locks) direct = locks.direct - residual = problem.nets + residual = residual_problem.nets if not residual: mode = "off" elif residual_mode is not None: @@ -239,7 +227,7 @@ def _route_prepared_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" - run = run_route(problem, options=replace(options, topology=replace(options.topology, mode=mode))) + run = run_route(residual_problem, options=replace(options, topology=replace(options.topology, mode=mode))) skipped = tuple(sorted(locks.disconnected)) return ( replace(run, results_by_net={**direct, **run.results_by_net, **{net_id: RoutingResult(net_id, ()) for net_id in skipped}}), From 72f8fbda5aae4b312d89f766d60620a0b621e212 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 22:48:28 -0800 Subject: [PATCH 51/57] Fix retry accounting and preserve authored bend lengths in benchmarks --- inire/tests/routing_corpus.py | 1 + inire/tests/test_routing_benchmarks.py | 20 ++++++++++++++++++-- scripts/benchmark_retry_order.py | 14 +++++++------- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index 49949b9..14cbd21 100644 --- a/inire/tests/routing_corpus.py +++ b/inire/tests/routing_corpus.py @@ -81,6 +81,7 @@ def _public_defaults(case: BenchmarkCase, defaults: RoutingOptions) -> RoutingOp bend_collision_type=geometry.bend_collision_type, bend_proxy_geometry=geometry.bend_proxy_geometry, bend_physical_geometry=geometry.bend_physical_geometry, + bend_physical_length=geometry.bend_physical_length, sbend_outlines=geometry.sbend_outlines, bend_clip_margin=geometry.bend_clip_margin, min_straight_length=geometry.min_straight_length, diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 8ebf000..e5822f2 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -19,9 +19,9 @@ from inire.tests.routing_benchmark_case import BenchmarkCase from inire.tests.routing_benchmarks import ( BENCHMARK_CASES, CROSSING_BENCHMARK_CASES, - FALLBACK_BENCHMARK_CASES, ) from inire.tests.routing_corpus import CASE_GROUPS, automatic_options, profile_options +from scripts.benchmark_retry_order import _measure as _measure_retry from scripts.compare_topological_routing import ( _direct_trials, _measure as _measure_selected_mode, @@ -124,7 +124,10 @@ def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None: def test_benchmark_profile_records_effective_options(tmp_path, monkeypatch) -> None: - case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == "fallback-custom-physical") + (fixture,) = CASE_GROUPS["fallback-custom-physical"] + search = replace(fixture.options.search, bend_physical_length=25) + case = replace(fixture, options=replace(fixture.options, search=search)) + monkeypatch.setitem(CASE_GROUPS, case.name, (case,)) defaults = RoutingOptions() output = tmp_path / "benchmark.json" monkeypatch.setattr( @@ -142,6 +145,7 @@ def test_benchmark_profile_records_effective_options(tmp_path, monkeypatch) -> N geometry = case.options.search assert options["search"]["bend_radii"] == list(geometry.bend_radii) assert shape(options["search"]["bend_physical_geometry"]).equals(geometry.bend_physical_geometry) + assert options["search"]["bend_physical_length"] == geometry.bend_physical_length [sample] = run["samples"] assert payload["cost_metrics"] == {"valid_costs": "benchmark_weighted_length", "native_valid_costs": "native_objective"} assert sample["native_valid_costs"].keys() == sample["valid_costs"].keys() @@ -159,6 +163,18 @@ def test_benchmark_profile_records_effective_options(tmp_path, monkeypatch) -> N assert options["topology"]["automatic_length_weights"] is None +def test_retry_experiment_records_worker_expansions() -> None: + (case,) = CASE_GROUPS["retry-holdout-floor-pocket"] + + sample = _measure_retry(case, "public-defaults", "lattice-500") + + [attempt] = sample["retry_attempts"] + [stage] = [stage for stage in sample["stages"] if stage["policy"] == "early-bounded-lattice"] + assert attempt["policy"] == "bounded-lattice" + assert 0 < attempt["nodes_expanded"] == stage["nodes_expanded"] <= sample["nodes_expanded"] + assert len(sample["verified"]) == case.routing_bound + + def test_seed_order_locked_rejects_touching_routes_at_zero_clearance() -> None: problem = RoutingProblem( bounds=(0, 0, 100, 40), diff --git a/scripts/benchmark_retry_order.py b/scripts/benchmark_retry_order.py index 9b31ef4..2b7e7f8 100644 --- a/scripts/benchmark_retry_order.py +++ b/scripts/benchmark_retry_order.py @@ -59,12 +59,12 @@ class _RetryExperiment(_AutomaticRun): self.retry_policy = policy self.retry_attempts: list[dict] = [] - def _record_retry(self, policy: str, outcome: str, started: float, first_run: int) -> None: + def _record_retry(self, policy: str, outcome: str, started: float, first_attempt: int) -> None: self.retry_attempts.append({ "policy": policy, "outcome": outcome, "elapsed_s": perf_counter() - started, - "nodes_expanded": sum(metrics.nodes_expanded for metrics in self.metrics[first_run:]), + "nodes_expanded": sum(metrics.nodes_expanded for metrics in self.attempts.samples[first_attempt:]), }) def _search_trials(self, trials: list[Trial], target: int) -> None: @@ -105,10 +105,10 @@ class _RetryExperiment(_AutomaticRun): and _near_port_coverage_stalled(trials, target) ): retry = replace(options, search=replace(options.search, node_limit=limit)) - started, first_run = perf_counter(), len(self.metrics) + started, first_attempt = perf_counter(), len(self.attempts.samples) self._lattice_fallback(trials, retry, "Near-port and lookahead searches were one net short", policy="early-bounded-lattice") complete = len(trials[-1].valid_costs) == target - self._record_retry("bounded-lattice", "complete" if complete else "incomplete", started, first_run) + self._record_retry("bounded-lattice", "complete" if complete else "incomplete", started, first_attempt) if complete: return trials[-1] = replace(trials[-1], selection="incomplete-layout") @@ -142,12 +142,12 @@ class _RetryExperiment(_AutomaticRun): policy: str, check_connectivity: bool = False, ) -> list[Trial]: - started, first_run = perf_counter(), len(self.metrics) + started, first_attempt = perf_counter(), len(self.attempts.samples) if check_connectivity: with self._time("plan", policy=policy): blocked = _disconnected_nets(self.problem, self.board, options, retained) if blocked: - self._record_retry(policy, "disconnected", started, first_run) + self._record_retry(policy, "disconnected", started, first_attempt) return [] retry = replace( @@ -164,7 +164,7 @@ class _RetryExperiment(_AutomaticRun): verified = self._verify_incumbent(trial) complete = len(verified.valid_costs) == target trials.append(verified if complete else replace(verified, selection="incomplete-layout")) - self._record_retry(policy, "complete" if complete else "incomplete", started, first_run) + self._record_retry(policy, "complete" if complete else "incomplete", started, first_attempt) return trials From 266aeb6c5e2c97af9dea233c35a51be41ffea297 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 22:48:31 -0800 Subject: [PATCH 52/57] Include placed geometry in routing parity snapshots --- docs/routing-diagnostics.md | 4 +- inire/tests/test_routing_benchmark_parity.py | 39 ++++++++++++++++---- scripts/routing_benchmark_parity.py | 20 +++++++--- 3 files changed, 49 insertions(+), 14 deletions(-) diff --git a/docs/routing-diagnostics.md b/docs/routing-diagnostics.md index c11f31a..db8ff2f 100644 --- a/docs/routing-diagnostics.md +++ b/docs/routing-diagnostics.md @@ -77,7 +77,7 @@ Use the returned result to count final successes. For live progress during routi ## Reproduce and compare -1. Start with a fixture that shows the symptom. Capture the same options at both revisions. For a behavior-preserving change, exact parity checks paths, scores, stage metadata, stable counters, and coverage. Add `--callbacks` and `--diagnostics` to both captures when changing callback or trace behavior. +1. Start with a fixture that shows the symptom. Capture the same options at both revisions. For a behavior-preserving change, exact parity checks move sequences, effective ports, physical polygon hashes, scores, stage metadata, stable counters, and coverage. Add `--callbacks` and `--diagnostics` to both captures when changing callback or trace behavior. 2. For a policy change, check verified IDs, paths, and per-net costs first. Advance to the full corpus and relevant holdouts once the focused case behaves as intended. Use interleaved repeats for timing and name the boards that get slower. Time inside failed retries can explain a tail regression that the median obscures. 3. If the run gets slower without more expansions, check the operation timings and use the counters above to pick a narrower trace or profile. @@ -89,6 +89,8 @@ python -m scripts.routing_benchmark_parity capture /tmp/routing-after.json --cas python -m scripts.routing_benchmark_parity compare /tmp/routing-before.json /tmp/routing-after.json ``` +Use capture scripts with the same snapshot schema on both revisions. Version 1 snapshots still compare with each other. Version 2 adds effective port and polygon data. + Select a built-in trace case by name with `--scenario`. Use `--output-dir` to write the capture in a scratch directory. ### Check timing and counters diff --git a/inire/tests/test_routing_benchmark_parity.py b/inire/tests/test_routing_benchmark_parity.py index 010cf7f..8ce1506 100644 --- a/inire/tests/test_routing_benchmark_parity.py +++ b/inire/tests/test_routing_benchmark_parity.py @@ -1,31 +1,54 @@ import json import sys +from dataclasses import replace +from inire import NetSpec, Port, RoutingOptions, RoutingProblem +from inire.tests.routing_benchmark_case import BenchmarkCase +from inire.tests.routing_corpus import CASE_GROUPS from scripts.routing_benchmark_parity import main def test_parity_command_reports_the_first_net_difference(tmp_path, monkeypatch, capsys) -> None: + net = NetSpec("lane", Port(10, 20, 0), Port(90, 20, 0)) + problem = RoutingProblem((0, 0, 100, 60), (net,)) + case = BenchmarkCase("placement-control", "Straight lane", problem, RoutingOptions()) + monkeypatch.setitem(CASE_GROUPS, case.name, (case,)) before = tmp_path / "before.json" after = tmp_path / "after.json" - monkeypatch.setattr(sys, "argv", [ - "parity", "capture", str(before), "--case", "reversed-heading", "--profile", "corpus-regression", "--callbacks", - ]) + capture_settings = ["--case", case.name, "--profile", "corpus-regression", "--callbacks"] + compare = ["parity", "compare", str(before), str(after)] + monkeypatch.setattr(sys, "argv", ["parity", "capture", str(before), *capture_settings]) assert main() == 0 payload = json.loads(before.read_text()) ordinary, with_callback = payload["runs"] assert ordinary["stable"]["callbacks"] == [] assert with_callback["stable"]["callbacks"] - assert "native" in ordinary["stable"]["costs"]["return"] + assert "native" in ordinary["stable"]["costs"][net.net_id] + original = ordinary["stable"]["nets"][net.net_id] + assert with_callback["stable"]["callbacks"][0]["nets"][net.net_id] == original ordinary["elapsed_s"] += 5 after.write_text(json.dumps(payload)) - monkeypatch.setattr(sys, "argv", ["parity", "compare", str(before), str(after)]) + monkeypatch.setattr(sys, "argv", compare) assert main() == 0 assert "2 runs match." in capsys.readouterr().out - ordinary["stable"]["nets"]["return"]["seed"][0]["kind"] = "DifferentMove" + original["seed"][0]["kind"] = "DifferentMove" after.write_text(json.dumps(payload)) assert main() == 1 message = capsys.readouterr().out - assert "reversed-heading / corpus-regression" in message - assert "nets.return.seed[0].kind" in message + assert "placement-control / corpus-regression" in message + assert "nets.lane.seed[0].kind" in message + + moved = replace(net, start=net.start.translate(dy=20), target=net.target.translate(dy=20)) + monkeypatch.setitem(CASE_GROUPS, case.name, (replace(case, problem=replace(problem, nets=(moved,))),)) + monkeypatch.setattr(sys, "argv", ["parity", "capture", str(after), *capture_settings]) + assert main() == 0 + original = json.loads(before.read_text())["runs"][0]["stable"]["nets"][net.net_id] + shifted = json.loads(after.read_text())["runs"][0]["stable"]["nets"][net.net_id] + assert original["seed"] == shifted["seed"] + assert original["report"] == shifted["report"] + assert original["physical_polygon_hashes"] != shifted["physical_polygon_hashes"] + monkeypatch.setattr(sys, "argv", compare) + assert main() == 1 + assert "nets.lane.effective_net.start.y" in capsys.readouterr().out diff --git a/scripts/routing_benchmark_parity.py b/scripts/routing_benchmark_parity.py index 2f2a8fc..8c152c0 100644 --- a/scripts/routing_benchmark_parity.py +++ b/scripts/routing_benchmark_parity.py @@ -5,11 +5,14 @@ from __future__ import annotations from argparse import ArgumentParser from concurrent.futures import ProcessPoolExecutor from dataclasses import asdict, replace +from hashlib import sha256 from json import dumps, loads from pathlib import Path from time import perf_counter from typing import TYPE_CHECKING +from shapely import to_wkb + from inire import DiagnosticsOptions, route from inire.results import RouteMetrics from inire.tests.routing_corpus import ( @@ -27,7 +30,7 @@ if TYPE_CHECKING: from inire import RoutingResult -SCHEMA_VERSION = 1 +SCHEMA_VERSION = 2 STABLE_COUNTERS = tuple(name for name in RouteMetrics.__dataclass_fields__ if not name.endswith("_ns")) @@ -39,6 +42,8 @@ def _paths(results: dict[str, RoutingResult]) -> dict: "outcome": result.outcome, "reached_target": result.reached_target, "seed": [{"kind": type(move).__name__, **asdict(move)} for move in result.as_seed().segments], + "effective_net": asdict(result.effective_net) if result.effective_net is not None else None, + "physical_polygon_hashes": [sha256(wkb).hexdigest() for wkb in to_wkb(result.locked_geometry, byte_order=1)], "report": asdict(result.report), } for net_id, result in results.items() @@ -119,19 +124,24 @@ def _first_difference(expected: object, actual: object, field: str = "") -> str return f"{field} is {expected!r} before and {actual!r} after" -def _read(path: Path) -> dict: +def _read(path: Path) -> tuple[int, dict]: payload = loads(path.read_text(encoding="utf-8")) - if payload["schema_version"] != SCHEMA_VERSION: + version = payload["schema_version"] + if version not in (1, SCHEMA_VERSION): raise ValueError(f"Unsupported parity schema in {path}") rows = payload["runs"] by_key = {(row["case"], row["profile"], row["with_callback"], row["with_diagnostics"]): row for row in rows} if len(by_key) != len(rows): raise ValueError(f"Duplicate parity run in {path}") - return by_key + return version, by_key def _compare(before: Path, after: Path, allowed_counters: list[str]) -> int: - baseline, current = _read(before), _read(after) + before_version, baseline = _read(before) + after_version, current = _read(after) + if before_version != after_version: + print(f"Parity schema mismatch ({before_version} and {after_version}). Capture both revisions with the same script version.") + return 1 for key in sorted(baseline.keys() | current.keys()): label = f"{key[0]} / {key[1]} (callback={key[2]}, diagnostics={key[3]})" if key not in baseline or key not in current: From 8c8cbe569b58b80ec8118b363257ecbb19fac771 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 22:58:43 -0800 Subject: [PATCH 53/57] Share routing preparation and report benchmark worker options --- docs/benchmarks.md | 2 ++ inire/__init__.py | 44 ++++++++++++++++++++------ inire/router/_automatic.py | 8 +++-- inire/router/_stack.py | 16 ++++++++-- inire/tests/direct_routing_policies.py | 14 ++++---- inire/tests/test_routing_benchmarks.py | 43 ++++++++++++++++++++++++- scripts/benchmark_retry_order.py | 32 ++++++++++++++----- scripts/compare_topological_routing.py | 36 +++++++++++++-------- 8 files changed, 152 insertions(+), 43 deletions(-) diff --git a/docs/benchmarks.md b/docs/benchmarks.md index aa38282..59bc866 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -43,6 +43,8 @@ List cases with `python -m scripts.compare_topological_routing --list`. Start wi Both budget profiles use benchmark weights when selecting an automatic candidate. A stage can use a smaller budget, and a net can be searched more than once. Match the profile, options, and worker count when measuring a change. +Benchmark JSON records the configured options for each strategy. Each sample's `attempt_options` lists the effective options passed to routing workers in execution order, including rejected bundle attempts and any fallback workers. `requested_mode` is null for policies that choose their own mode for each attempt. + ### Run the full benchmark corpus ```sh diff --git a/inire/__init__.py b/inire/__init__.py index 9bf069f..df4163e 100644 --- a/inire/__init__.py +++ b/inire/__init__.py @@ -54,6 +54,9 @@ if _shapely.geos_version < (3, 10, 0): __author__ = 'Jan Petykiewicz' __version__ = '0.1' +_IterationCallback = Callable[[int, dict[str, RoutingResult]], None] +_Router = Callable[[RoutingProblem, RoutingOptions, _IterationCallback | None], RoutingRunResult] + def _warn_bend_port_mismatches(results: dict[str, RoutingResult], nets: dict[str, NetSpec]) -> None: checked = set() @@ -75,10 +78,27 @@ def _warn_bend_port_mismatches(results: dict[str, RoutingResult], nets: dict[str warnings.warn( f"Custom 90-degree bend of radius {move.radius:g} does not match the declared port faces " f"of width {width:g} on net {net_id!r}", - stacklevel=3, + stacklevel=4, ) +def _dispatch_route( + problem: RoutingProblem, + options: RoutingOptions, + iteration_callback: _IterationCallback | None, + *, + attempt_callback: Callable[[RoutingOptions], None] | None = None, +) -> RoutingRunResult: + if options.topology.mode == "automatic": + from .router._automatic import route_automatic # noqa: PLC0415 + + return route_automatic(problem, options, iteration_callback, attempt_callback=attempt_callback) + + from .router._stack import route_explicit # noqa: PLC0415 + + return route_explicit(problem, options=options, iteration_callback=iteration_callback, attempt_callback=attempt_callback) + + def route( problem: RoutingProblem, *, @@ -86,7 +106,18 @@ def route( iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, ) -> RoutingRunResult: resolved_options = RoutingOptions() if options is None else options - search = resolved_options.search + return _route(problem, options=resolved_options, iteration_callback=iteration_callback) + + +def _route( + problem: RoutingProblem, + *, + options: RoutingOptions, + iteration_callback: _IterationCallback | None = None, + run_router: _Router = _dispatch_route, +) -> RoutingRunResult: + """Prepare inputs and attach diagnostics around a routing implementation.""" + search = options.search requested = {net.net_id: net for net in problem.nets} coincident = { net.net_id: RoutingResult( @@ -142,14 +173,7 @@ def route( iteration_callback(iteration, attach_requested(results)) callback = notify if iteration_callback is not None else None - if resolved_options.topology.mode == "automatic": - from .router._automatic import route_automatic # noqa: PLC0415 - - run = route_automatic(problem, resolved_options, callback) - else: - from .router._stack import route_explicit # noqa: PLC0415 - - run = route_explicit(problem, options=resolved_options, iteration_callback=callback) + run = run_router(problem, options, callback) results = attach_requested(run.results_by_net) if coincident: results = {net_id: results[net_id] for net_id in requested} diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index f7face4..4f13a7c 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -84,6 +84,8 @@ class _AutomaticRun: problem: RoutingProblem, options: RoutingOptions, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None, + *, + attempt_callback: Callable[[RoutingOptions], None] | None = None, ) -> None: if any(not seed.segments for seed in problem.initial_paths.values()): problem = replace(problem, initial_paths={net_id: seed for net_id, seed in problem.initial_paths.items() if seed.segments}) @@ -91,7 +93,7 @@ class _AutomaticRun: self.problem = problem self.options = options self.board = box(*problem.bounds) - self.attempts = RoutingAttempts(iteration_callback) + self.attempts = RoutingAttempts(iteration_callback, attempt_callback=attempt_callback) self.timings: list[RoutingTiming] = [] self.cost_pass_performed = False self.evaluator: CostEvaluator | None = None @@ -804,5 +806,7 @@ def route_automatic( problem: RoutingProblem, options: RoutingOptions, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, + *, + attempt_callback: Callable[[RoutingOptions], None] | None = None, ) -> RoutingRunResult: - return _AutomaticRun(problem, options, iteration_callback).execute() + return _AutomaticRun(problem, options, iteration_callback, attempt_callback=attempt_callback).execute() diff --git a/inire/router/_stack.py b/inire/router/_stack.py index ff1b3b7..1972238 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -71,11 +71,14 @@ def route_once( phase_timer: PhaseTimer | None = None, corridors: dict[str, tuple[Corridor, ...]] | None = None, iteration_offset: int = 0, + attempt_callback: Callable[[RoutingOptions], None] | 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") + if attempt_callback is not None: + attempt_callback(options) started_at = time.monotonic() finder = build_routing_stack(problem, options).finder effective = {net.net_id: net for net in finder.context.problem.nets} @@ -116,8 +119,14 @@ def collect_worker_result(finder: PathFinder, results: dict[str, RoutingResult]) class RoutingAttempts: """Coordinate workers without retaining diagnostic data from discarded runs.""" - def __init__(self, callback: Callable[[int, dict[str, RoutingResult]], None] | None) -> None: + def __init__( + self, + callback: Callable[[int, dict[str, RoutingResult]], None] | None, + *, + attempt_callback: Callable[[RoutingOptions], None] | None = None, + ) -> None: self.callback = callback + self.attempt_callback = attempt_callback self.iterations = 0 self.samples: list[RouteMetrics] = [] @@ -130,7 +139,7 @@ class RoutingAttempts: ) -> RoutingRunResult: result = route_once( problem, options=options, iteration_callback=self.callback, phase_timer=phase_timer, - iteration_offset=self.iterations, + iteration_offset=self.iterations, attempt_callback=self.attempt_callback, ) self.iterations += result.metrics.route_iterations self.samples.append(result.metrics) @@ -145,8 +154,9 @@ def route_explicit( *, options: RoutingOptions, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, + attempt_callback: Callable[[RoutingOptions], None] | None = None, ) -> RoutingRunResult: - attempts = RoutingAttempts(iteration_callback) + attempts = RoutingAttempts(iteration_callback, attempt_callback=attempt_callback) with_guidance = attempts.run(problem, options=options) topology = options.topology if ( diff --git a/inire/tests/direct_routing_policies.py b/inire/tests/direct_routing_policies.py index 489e171..9d15d1d 100644 --- a/inire/tests/direct_routing_policies.py +++ b/inire/tests/direct_routing_policies.py @@ -25,7 +25,7 @@ if TYPE_CHECKING: from shapely.geometry import Polygon from inire import RoutingOptions, RoutingProblem, RoutingRunResult, RoutingStage - from inire.router._routing_policy import LockPlan, Trial + from inire.router._routing_policy import LockPlan, RouteCall, Trial @dataclass(frozen=True, slots=True) @@ -56,17 +56,19 @@ _EXPERIMENTS = { DIRECT_POLICIES = tuple(_EXPERIMENTS) -def direct_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str) -> list[Trial]: +def direct_trials( + problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str, *, run_route: RouteCall = route_once, +) -> list[Trial]: experiment = _EXPERIMENTS[strategy] summarize = partial(_trial, score=benchmark_weighted_length) if experiment is None: - return _direct_trials(problem, board, options, strategy, check_trial=summarize) + return _direct_trials(problem, board, options, strategy, check_trial=summarize, run_route=run_route) def check(run: RoutingRunResult, stage: RoutingStage) -> Trial: return summarize(run, replace(stage, policy=strategy)) def run_residual(worker: RoutingOptions, locks: LockPlan) -> Trial: - return check(*_route_residual(problem, worker, locks, residual_mode=experiment.residual_mode)) + return check(*_route_residual(problem, worker, locks, residual_mode=experiment.residual_mode, run_route=run_route)) plan = partial(_plan_locks, problem, board, options, check_connectivity=experiment.check_connectivity) locks = plan() @@ -85,7 +87,7 @@ def direct_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptio trials = [] if probe_limit and experiment.probe == "first": - trials.append(_lattice_probe(problem, options, probe_limit, run_route=route_once, check_trial=check)) + trials.append(_lattice_probe(problem, options, probe_limit, run_route=run_route, check_trial=check)) if len(trials[-1].valid_costs) == len(problem.nets): return trials @@ -95,7 +97,7 @@ def direct_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptio return trials if probe_limit and experiment.probe == "after": - trials.append(_lattice_probe(problem, options, probe_limit, run_route=route_once, check_trial=check)) + trials.append(_lattice_probe(problem, options, probe_limit, run_route=run_route, check_trial=check)) if len(trials[-1].valid_costs) == len(problem.nets): return trials diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index e5822f2..bf54c90 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -161,6 +161,8 @@ def test_benchmark_profile_records_effective_options(tmp_path, monkeypatch) -> N assert options["objective"] == asdict(defaults.objective) assert options["congestion"] == asdict(defaults.congestion) assert options["topology"]["automatic_length_weights"] is None + [attempt] = sample["attempt_options"] + assert attempt == {**options, "topology": {**options["topology"], "mode": "off"}} def test_retry_experiment_records_worker_expansions() -> None: @@ -175,6 +177,23 @@ def test_retry_experiment_records_worker_expansions() -> None: assert len(sample["verified"]) == case.routing_bound +def test_retry_experiment_preserves_public_input_handling() -> None: + port = Port(10, 5, 0) + problem = RoutingProblem( + bounds=(0, 0, 100, 40), + nets=(NetSpec("coincident", port, port), NetSpec("straight", Port(10, 15, 0), Port(90, 15, 0))), + ) + case = BenchmarkCase("coincident-control", "Coincident ports beside a straight route", problem, RoutingOptions()) + + baseline = _measure_retry(case, "matched-budget", "baseline") + experiment = _measure_retry(case, "matched-budget", "probe-iterations-2") + + assert baseline["verified"] == experiment["verified"] == ["straight"] + assert baseline["routing_bound"] == experiment["routing_bound"] == 1 + assert baseline["nodes_expanded"] == experiment["nodes_expanded"] == 0 + assert baseline["stages"] == experiment["stages"] + + def test_seed_order_locked_rejects_touching_routes_at_zero_clearance() -> None: problem = RoutingProblem( bounds=(0, 0, 100, 40), @@ -194,6 +213,9 @@ def test_seed_order_locked_rejects_touching_routes_at_zero_clearance() -> None: assert retry.incumbent_net_ids == first.valid_net_ids assert retry.valid_net_ids == first.valid_net_ids assert sample.valid_costs.keys() == {"a"} + assert [(attempt.topology.mode, attempt.search.node_limit, attempt.congestion.net_order) for attempt in sample.attempt_options] == [ + ("seed", 30, "user"), ("seed", 30, "longest"), + ] def test_benchmark_native_cost_uses_configured_proximity_range() -> None: @@ -278,8 +300,25 @@ def test_point_terminal_replay_preserves_the_selected_port_headings() -> None: assert all(result.is_valid and result.locked_geometry == paths[net_id].locked_geometry for net_id, result in replay.results_by_net.items()) -def test_bundle_first_reports_capacity_failure_and_uses_the_generic_fallback() -> None: +def test_bundle_first_reports_effective_settings_and_capacity_fallback(tmp_path, monkeypatch) -> None: original = next(case for case in BENCHMARK_CASES if case.name == "terminal-bench-point-terminals") + output = tmp_path / "benchmark.json" + monkeypatch.setattr(sys, "argv", [ + "bench", "--case", original.name, "--policy", "bundle-first", "--iterations", "4", "--refinement", "on", "--json", str(output), + ]) + run_benchmarks() + + [record] = loads(output.read_text())["runs"] + [success] = record["samples"] + [bundle] = success["attempt_options"] + assert record["requested_mode"] is None + assert record["options"]["congestion"]["max_iterations"] == 4 + assert record["options"]["refinement"]["enabled"] + assert bundle["topology"]["mode"] == "bundle" + assert bundle["congestion"]["max_iterations"] == 1 + assert not bundle["refinement"]["enabled"] + assert len(success["valid_costs"]) == len(original.problem.nets) + case = replace(original, problem=replace(original.problem, clearance=7)) options = replace(case.options, search=replace(case.options.search, node_limit=20)) @@ -292,6 +331,8 @@ def test_bundle_first_reports_capacity_failure_and_uses_the_generic_fallback() - assert sample.stages == fallback.stages assert sample.net_outcomes == fallback.net_outcomes assert sample.valid_costs == fallback.valid_costs + assert sample.attempt_options[0].topology.mode == "bundle" + assert sample.attempt_options[1:] == fallback.attempt_options def test_automatic_retry_releases_a_lock_that_disconnects_the_remaining_net() -> None: diff --git a/scripts/benchmark_retry_order.py b/scripts/benchmark_retry_order.py index 2b7e7f8..5645c3a 100644 --- a/scripts/benchmark_retry_order.py +++ b/scripts/benchmark_retry_order.py @@ -12,7 +12,7 @@ from statistics import median from time import perf_counter from typing import TYPE_CHECKING -from inire import route +from inire import _route, route from inire.router._automatic import _AutomaticRun from inire.router._routing_policy import LockPlan, _best_trial, _disconnected_nets, _route_residual from inire.tests.routing_corpus import ( @@ -28,8 +28,9 @@ from inire.tests.routing_corpus import ( if TYPE_CHECKING: from typing import Literal + from inire import _IterationCallback from inire.model import RoutingOptions, RoutingProblem - from inire.results import RoutingResult + from inire.results import RoutingResult, RoutingRunResult from inire.router._routing_policy import Trial from inire.seeds import PathSeed from inire.tests.routing_benchmark_case import BenchmarkCase @@ -54,8 +55,14 @@ _POLICIES = { class _RetryExperiment(_AutomaticRun): - def __init__(self, problem: RoutingProblem, options: RoutingOptions, policy: _RetryPolicy) -> None: - super().__init__(problem, options, None) + def __init__( + self, + problem: RoutingProblem, + options: RoutingOptions, + iteration_callback: _IterationCallback | None, + policy: _RetryPolicy, + ) -> None: + super().__init__(problem, options, iteration_callback) self.retry_policy = policy self.retry_attempts: list[dict] = [] @@ -179,12 +186,21 @@ def _near_port_coverage_stalled(trials: list[Trial], target: int) -> bool: def _measure(case: BenchmarkCase, profile: str, name: str) -> dict: options = automatic_options(profile_options(case, profile), profile) + retry_attempts: list[dict] = [] + + def run_experiment( + problem: RoutingProblem, options: RoutingOptions, iteration_callback: _IterationCallback | None, + ) -> RoutingRunResult: + experiment = _RetryExperiment(problem, options, iteration_callback, _POLICIES[name]) + run = experiment.execute() + retry_attempts.extend(experiment.retry_attempts) + return run + started = perf_counter() - experiment = None if name == "baseline" else _RetryExperiment(case.problem, options, _POLICIES[name]) - if experiment is None: + if name == "baseline": run = route(case.problem, options=options) else: - run = experiment.execute() + run = _route(case.problem, options=options, run_router=run_experiment) elapsed = perf_counter() - started report = run.automatic assert report is not None @@ -199,7 +215,7 @@ def _measure(case: BenchmarkCase, profile: str, name: str) -> dict: "seeds": {net_id: repr(run.results_by_net[net_id].as_seed()) for net_id in verified}, "stages": [asdict(stage) for stage in report.stages], "selected_stage": report.selected_stage, - "retry_attempts": [] if experiment is None else experiment.retry_attempts, + "retry_attempts": retry_attempts, "timings": [asdict(timing) for timing in report.timings], } diff --git a/scripts/compare_topological_routing.py b/scripts/compare_topological_routing.py index 2d6e377..56ed169 100644 --- a/scripts/compare_topological_routing.py +++ b/scripts/compare_topological_routing.py @@ -16,9 +16,10 @@ from typing import TYPE_CHECKING import shapely from shapely.geometry import box, mapping -from inire import RoutingOptions, RoutingStage, route +from inire import RoutingOptions, RoutingStage, _dispatch_route, _route, route from inire.router._routing_policy import LockPlan, _best_trial, _residual_problem from inire.router._routing_policy import _trial as _summarize_trial +from inire.router._stack import route_once from inire.tests.direct_routing_policies import DIRECT_POLICIES from inire.tests.direct_routing_policies import direct_trials as _direct_trials from inire.tests.routing_corpus import ( @@ -35,7 +36,7 @@ from inire.tests.routing_corpus import ( if TYPE_CHECKING: from inire import CapacityLimit, RoutingProblem, RoutingTiming, TopologyReport - from inire.router._routing_policy import Trial + from inire.router._routing_policy import RouteCall, Trial from inire.tests.routing_benchmark_case import BenchmarkCase @@ -56,6 +57,7 @@ class RunSample: route_iterations: int topology: TopologyReport | None stages: tuple[RoutingStage, ...] + attempt_options: tuple[RoutingOptions, ...] bundle_rejection: str | None = None bundle_duration_s: float | None = None selected_stage: int = 0 @@ -73,15 +75,17 @@ _trial = partial(_summarize_trial, score=benchmark_weighted_length) def _mode_options(options: RoutingOptions, strategy: str, profile: str = "matched-budget") -> RoutingOptions: if strategy in AUTOMATIC_POLICIES: return automatic_options(options, profile, strategy) - return replace(options, topology=replace(options.topology, mode="off" if strategy in POLICIES else strategy)) + if strategy in POLICIES: + return options + return replace(options, topology=replace(options.topology, mode=strategy)) -def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: str) -> list[Trial]: +def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: str, *, run_route: RouteCall = route) -> list[Trial]: limit = options.search.node_limit first_limit = max(1, limit // 2) first_order = options.congestion.net_order first_options = replace(options, search=replace(options.search, node_limit=first_limit), topology=replace(options.topology, mode="seed")) - run = route(problem, options=first_options) + run = run_route(problem, options=first_options) first = _trial(run, RoutingStage("seed", (), run.metrics.nodes_expanded, first_limit, net_order=first_order)) if len(first.valid_costs) == len(problem.nets) or limit == 1: return [first] @@ -102,7 +106,7 @@ def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: st else: second_problem = problem - run = route(second_problem, options=second_options) + run = run_route(second_problem, options=second_options) if strategy == "seed-order-locked": run = replace(run, results_by_net={**incumbents, **run.results_by_net}) stage = RoutingStage("seed", (), run.metrics.nodes_expanded, second_limit, net_order=second_order, incumbent_net_ids=tuple(incumbents)) @@ -111,11 +115,14 @@ def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: st def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> RunSample: board = box(*case.problem.bounds) + attempt_options: list[RoutingOptions] = [] + run_route = partial(_route, run_router=partial(_dispatch_route, attempt_callback=attempt_options.append)) + run_worker = partial(route_once, attempt_callback=attempt_options.append) started = perf_counter() bundle_rejection = None bundle_duration = None if strategy in AUTOMATIC_POLICIES: - run = route(case.problem, options=options) + run = run_route(case.problem, options=options) report = run.automatic assert report is not None selected = report.stages[report.selected_stage] @@ -131,6 +138,7 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run route_iterations=run.metrics.route_iterations, topology=run.topology, stages=report.stages, + attempt_options=tuple(attempt_options), selected_stage=report.selected_stage, capacity_limit=report.capacity_limit, planner_rejections=report.planner_rejections, @@ -147,23 +155,23 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run refinement=replace(options.refinement, enabled=strategy == "bundle-first-refine"), ) try: - run = route(case.problem, options=bundle_options) + run = run_route(case.problem, options=bundle_options) except ValueError as exc: bundle_rejection = str(exc) bundle_duration = perf_counter() - started - trials = _direct_trials(case.fixed_headings_problem(), board, options, "direct-probe-near-port") + trials = _direct_trials(case.fixed_headings_problem(), board, options, "direct-probe-near-port", run_route=run_worker) else: bundle_duration = perf_counter() - started stage = RoutingStage("bundle", (), run.metrics.nodes_expanded, options.search.node_limit, kind="bundle") trials = [_trial(run, stage)] elif strategy in DIRECT_POLICIES: problem = case.fixed_headings_problem() - trials = _direct_trials(problem, board, options, strategy) + trials = _direct_trials(problem, board, options, strategy, run_route=run_worker) elif strategy in ORDER_POLICIES: problem = case.fixed_headings_problem() - trials = _order_trials(problem, options, strategy) + trials = _order_trials(problem, options, strategy, run_route=run_route) else: - run = route(case.fixed_headings_problem(), options=options) + run = run_route(case.fixed_headings_problem(), options=options) trials = [_trial(run, RoutingStage(strategy, (), run.metrics.nodes_expanded, options.search.node_limit))] best = _best_trial(trials) duration = perf_counter() - started @@ -179,6 +187,7 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run route_iterations=sum(trial.run.metrics.route_iterations for trial in trials), topology=run.topology, stages=tuple(trial.stage for trial in trials), + attempt_options=tuple(attempt_options), bundle_rejection=bundle_rejection, bundle_duration_s=bundle_duration, selected_stage=next(i for i, trial in enumerate(trials) if trial is best), @@ -371,11 +380,12 @@ def main() -> None: samples[mode].append(_measure(case, mode_options[mode], mode)) for mode in modes: _print_summary(mode, samples[mode]) + requested_mode = mode_options[mode].topology.mode if mode not in POLICIES or mode in AUTOMATIC_POLICIES else None records.append( { "case": case.name, "strategy": mode, - "requested_mode": mode_options[mode].topology.mode, + "requested_mode": requested_mode, "grid_nm": case.grid_nm, "reference_net_ids": [net_id for net_id, _ in case.reference_paths], "options": asdict(mode_options[mode]), From 495bf8d307420d9699f39265ddc55363d68bcbf1 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 22:58:45 -0800 Subject: [PATCH 54/57] Check reference route clearance against peers and fixed routes --- inire/tests/test_routing_fixtures.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/inire/tests/test_routing_fixtures.py b/inire/tests/test_routing_fixtures.py index 5908a9b..7686f52 100644 --- a/inire/tests/test_routing_fixtures.py +++ b/inire/tests/test_routing_fixtures.py @@ -1,5 +1,4 @@ from dataclasses import replace -from itertools import combinations import pytest from shapely import union_all @@ -136,16 +135,21 @@ def _check_reference_paths(case) -> RoutingRunResult: assert run.metrics.nodes_expanded == 0 assert run.results_by_net.keys() == reference.keys() board = box(*problem.bounds) - footprints = [] + occupied = [polygon for fixed in problem.fixed_routes for polygon in fixed.polygons] + clearance = problem.clearance + separation = clearance - TOLERANCE_LINEAR * min(1.0, clearance) for result in run.results_by_net.values(): assert result.is_valid assert result.as_seed() == reference[result.net_id] footprint = union_all(result.locked_geometry) assert board.covers(footprint) - assert all(footprint.distance(obstacle) >= problem.clearance - TOLERANCE_LINEAR for obstacle in problem.static_obstacles) - footprints.append(footprint) - for a, b in combinations(footprints, 2): - assert a.distance(b) >= problem.clearance - TOLERANCE_LINEAR + if clearance: + assert all(footprint.distance(obstacle) >= separation for obstacle in problem.static_obstacles) + assert all(footprint.distance(other) >= separation for other in occupied) + else: + assert all(footprint.disjoint(obstacle) or footprint.touches(obstacle) for obstacle in problem.static_obstacles) + assert all(footprint.disjoint(other) for other in occupied) + occupied.append(footprint) return run From f247cff54a6aaea9bfa478aadf4a9146df38bfbb Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Tue, 1 Dec 2026 23:05:48 -0800 Subject: [PATCH 55/57] Validate direct benchmark inputs and preserve fallback headings --- inire/tests/routing_benchmark_case.py | 4 ++- inire/tests/test_routing_benchmarks.py | 47 +++++++++++++++++++------- scripts/compare_topological_routing.py | 22 +++++++++--- 3 files changed, 55 insertions(+), 18 deletions(-) diff --git a/inire/tests/routing_benchmark_case.py b/inire/tests/routing_benchmark_case.py index 2390d4c..52c5781 100644 --- a/inire/tests/routing_benchmark_case.py +++ b/inire/tests/routing_benchmark_case.py @@ -2,6 +2,7 @@ from __future__ import annotations +from contextlib import suppress from dataclasses import dataclass, replace from math import pi from typing import TYPE_CHECKING @@ -29,7 +30,8 @@ class BenchmarkCase: def fixed_headings_problem(self) -> RoutingProblem: if self.options.topology.infer_terminal_headings: - return ordered_bundle_terminal_headings(self.problem) + with suppress(ValueError): + return ordered_bundle_terminal_headings(self.problem) return self.problem diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index bf54c90..4feeee2 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -194,6 +194,25 @@ def test_retry_experiment_preserves_public_input_handling() -> None: assert baseline["stages"] == experiment["stages"] +def test_direct_benchmarks_validate_inputs_before_locking_routes() -> None: + port = Port(10, 5, 0) + problem = RoutingProblem( + bounds=(0, 0, 100, 40), + nets=(NetSpec("coincident", port, port), NetSpec("straight", Port(10, 15, 0), Port(90, 15, 0))), + ) + options = RoutingOptions(search=SearchOptions(node_limit=20)) + case = BenchmarkCase("direct-inputs", "Coincident ports beside a straight route", problem, options) + bad_seed = replace(problem, initial_paths={"unknown": PathSeed((StraightSeed(20),))}) + + for strategy in ("direct-guide", "direct-probe-near-port", "bundle-first"): + with pytest.raises(ValueError, match="Initial path provided for unknown net: unknown"): + _measure(replace(case, problem=bad_seed), options, strategy) + + sample = _measure(case, options, strategy) + assert sample.net_outcomes == {"coincident": "unroutable", "straight": "completed"} + assert sample.stages[sample.selected_stage].direct_net_ids == ("straight",) + + def test_seed_order_locked_rejects_touching_routes_at_zero_clearance() -> None: problem = RoutingProblem( bounds=(0, 0, 100, 40), @@ -319,20 +338,24 @@ def test_bundle_first_reports_effective_settings_and_capacity_fallback(tmp_path, assert not bundle["refinement"]["enabled"] assert len(success["valid_costs"]) == len(original.problem.nets) - case = replace(original, problem=replace(original.problem, clearance=7)) - options = replace(case.options, search=replace(case.options.search, node_limit=20)) + options = replace(original.options, search=replace(original.options.search, node_limit=20)) + for clearance, rejection in ((7, "insufficient track capacity"), (15, "The short route must leave through the first gap")): + case = replace(original, problem=replace(original.problem, clearance=clearance)) + if clearance == 15: + assert case.fixed_headings_problem() == case.problem - fallback = _measure(case, options, "direct-probe-near-port") - sample = _measure(case, options, "bundle-first") + fallback = _measure(case, options, "direct-probe-near-port") + sample = _measure(case, options, "bundle-first") - assert sample.bundle_rejection is not None - assert "insufficient track capacity" in sample.bundle_rejection - assert sample.bundle_duration_s is not None - assert sample.stages == fallback.stages - assert sample.net_outcomes == fallback.net_outcomes - assert sample.valid_costs == fallback.valid_costs - assert sample.attempt_options[0].topology.mode == "bundle" - assert sample.attempt_options[1:] == fallback.attempt_options + assert sample.bundle_rejection is not None + assert rejection in sample.bundle_rejection + assert sample.bundle_duration_s is not None + assert sample.stages == fallback.stages + assert sample.net_outcomes == fallback.net_outcomes + assert sample.net_outcomes.keys() == {net.net_id for net in case.problem.nets} + assert sample.valid_costs == fallback.valid_costs + assert sample.attempt_options[0].topology.mode == "bundle" + assert sample.attempt_options[1:] == fallback.attempt_options def test_automatic_retry_releases_a_lock_that_disconnects_the_remaining_net() -> None: diff --git a/scripts/compare_topological_routing.py b/scripts/compare_topological_routing.py index 56ed169..ba035ff 100644 --- a/scripts/compare_topological_routing.py +++ b/scripts/compare_topological_routing.py @@ -35,7 +35,7 @@ from inire.tests.routing_corpus import ( ) if TYPE_CHECKING: - from inire import CapacityLimit, RoutingProblem, RoutingTiming, TopologyReport + from inire import CapacityLimit, RoutingProblem, RoutingRunResult, RoutingTiming, TopologyReport, _IterationCallback from inire.router._routing_policy import RouteCall, Trial from inire.tests.routing_benchmark_case import BenchmarkCase @@ -118,6 +118,19 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run attempt_options: list[RoutingOptions] = [] run_route = partial(_route, run_router=partial(_dispatch_route, attempt_callback=attempt_options.append)) run_worker = partial(route_once, attempt_callback=attempt_options.append) + + def measure_direct(problem: RoutingProblem, policy: str) -> tuple[RoutingRunResult, list[Trial]]: + trials: list[Trial] = [] + + def run_direct( + prepared_problem: RoutingProblem, worker_options: RoutingOptions, _iteration_callback: _IterationCallback | None, + ) -> RoutingRunResult: + trials.extend(_direct_trials(prepared_problem, board, worker_options, policy, run_route=run_worker)) + return _best_trial(trials).run + + run = _route(problem, options=options, run_router=run_direct) + return run, trials + started = perf_counter() bundle_rejection = None bundle_duration = None @@ -159,23 +172,22 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run except ValueError as exc: bundle_rejection = str(exc) bundle_duration = perf_counter() - started - trials = _direct_trials(case.fixed_headings_problem(), board, options, "direct-probe-near-port", run_route=run_worker) + run, trials = measure_direct(case.fixed_headings_problem(), "direct-probe-near-port") else: bundle_duration = perf_counter() - started stage = RoutingStage("bundle", (), run.metrics.nodes_expanded, options.search.node_limit, kind="bundle") trials = [_trial(run, stage)] elif strategy in DIRECT_POLICIES: - problem = case.fixed_headings_problem() - trials = _direct_trials(problem, board, options, strategy, run_route=run_worker) + run, trials = measure_direct(case.fixed_headings_problem(), strategy) elif strategy in ORDER_POLICIES: problem = case.fixed_headings_problem() trials = _order_trials(problem, options, strategy, run_route=run_route) + run = _best_trial(trials).run else: run = run_route(case.fixed_headings_problem(), options=options) trials = [_trial(run, RoutingStage(strategy, (), run.metrics.nodes_expanded, options.search.node_limit))] best = _best_trial(trials) duration = perf_counter() - started - run = best.run return RunSample( duration_s=duration, net_outcomes={net_id: result.outcome for net_id, result in run.results_by_net.items()}, From f6e7bac4c5c5909e72c8533bd7275373628718a2 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 2 Dec 2026 00:55:43 -0800 Subject: [PATCH 56/57] Make retry exports optional and report benchmark placement and selection --- docs/benchmarks.md | 4 +++- inire/__init__.py | 6 +++++- inire/router/_stack.py | 8 +++++++- inire/tests/routing_corpus.py | 12 +++++++++++- inire/tests/test_routing_benchmarks.py | 11 +++++++++++ inire/tests/test_topology.py | 9 +++++++++ scripts/benchmark_retry_order.py | 27 ++++++++++++++++---------- scripts/compare_topological_routing.py | 14 ++++++++++++- scripts/routing_benchmark_parity.py | 7 ++----- 9 files changed, 78 insertions(+), 20 deletions(-) diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 59bc866..ab474e1 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -45,6 +45,8 @@ Both budget profiles use benchmark weights when selecting an automatic candidate Benchmark JSON records the configured options for each strategy. Each sample's `attempt_options` lists the effective options passed to routing workers in execution order, including rejected bundle attempts and any fallback workers. `requested_mode` is null for policies that choose their own mode for each attempt. +For explicit `guide` and `seed` runs, `selected_attempt` is the zero-based index into `attempt_options` of the worker whose routes were returned. + ### Run the full benchmark corpus ```sh @@ -83,7 +85,7 @@ python -m scripts.benchmark_retry_order \ --json /tmp/inire-residual.json ``` -Compare verified IDs, unchanged incumbents, and time spent on failed attempts. +Omit `--json` for a console summary. The optional JSON includes effective ports and polygon hashes for verified nets, so you can compare incumbent placement as well as coverage and time spent on failed attempts. - [Earlier retry results](benchmark-results.md#early-and-late-retries) diff --git a/inire/__init__.py b/inire/__init__.py index df4163e..2911e17 100644 --- a/inire/__init__.py +++ b/inire/__init__.py @@ -88,6 +88,7 @@ def _dispatch_route( iteration_callback: _IterationCallback | None, *, attempt_callback: Callable[[RoutingOptions], None] | None = None, + selected_attempt_callback: Callable[[int], None] | None = None, ) -> RoutingRunResult: if options.topology.mode == "automatic": from .router._automatic import route_automatic # noqa: PLC0415 @@ -96,7 +97,10 @@ def _dispatch_route( from .router._stack import route_explicit # noqa: PLC0415 - return route_explicit(problem, options=options, iteration_callback=iteration_callback, attempt_callback=attempt_callback) + return route_explicit( + problem, options=options, iteration_callback=iteration_callback, attempt_callback=attempt_callback, + selected_attempt_callback=selected_attempt_callback, + ) def route( diff --git a/inire/router/_stack.py b/inire/router/_stack.py index 1972238..e5ec67b 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -155,6 +155,7 @@ def route_explicit( options: RoutingOptions, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, attempt_callback: Callable[[RoutingOptions], None] | None = None, + selected_attempt_callback: Callable[[int], None] | None = None, ) -> RoutingRunResult: attempts = RoutingAttempts(iteration_callback, attempt_callback=attempt_callback) with_guidance = attempts.run(problem, options=options) @@ -165,6 +166,8 @@ def route_explicit( or with_guidance.metrics.timeout_events or not with_guidance.topology or not with_guidance.topology.corridor_counts or all(result.is_valid for result in with_guidance.results_by_net.values()) ): + if selected_attempt_callback is not None: + selected_attempt_callback(0) return with_guidance retry = replace( @@ -174,5 +177,8 @@ def route_explicit( without_guidance = attempts.run(problem, options=retry) old_count = sum(result.is_valid for result in with_guidance.results_by_net.values()) new_count = sum(result.is_valid for result in without_guidance.results_by_net.values()) - selected = without_guidance if new_count > old_count else with_guidance + retry_won = new_count > old_count + if selected_attempt_callback is not None: + selected_attempt_callback(int(retry_won)) + selected = without_guidance if retry_won else with_guidance return replace(selected, metrics=attempts.metrics()) diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index 14cbd21..a31f1fa 100644 --- a/inire/tests/routing_corpus.py +++ b/inire/tests/routing_corpus.py @@ -2,9 +2,12 @@ from __future__ import annotations -from dataclasses import replace +from dataclasses import asdict, replace +from hashlib import sha256 from typing import TYPE_CHECKING +from shapely import to_wkb + from inire import RoutingOptions from inire.router.cost import build_native_cost_evaluator, weighted_path_length from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES @@ -134,6 +137,13 @@ def benchmark_weighted_length(result: RoutingResult) -> float: return weighted_path_length(result.path, LENGTH_COST) +def route_placement(result: RoutingResult) -> dict: + return { + "effective_net": asdict(result.effective_net) if result.effective_net is not None else None, + "physical_polygon_hashes": [sha256(wkb).hexdigest() for wkb in to_wkb(result.locked_geometry, byte_order=1)], + } + + def native_verified_costs( case: BenchmarkCase, options: RoutingOptions, diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 4feeee2..e515565 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -192,6 +192,17 @@ def test_retry_experiment_preserves_public_input_handling() -> None: assert baseline["routing_bound"] == experiment["routing_bound"] == 1 assert baseline["nodes_expanded"] == experiment["nodes_expanded"] == 0 assert baseline["stages"] == experiment["stages"] + assert baseline["placements"] == experiment["placements"] + + coincident, straight = problem.nets + moved = replace(straight, start=straight.start.translate(dy=5), target=straight.target.translate(dy=5)) + moved_case = replace(case, problem=replace(problem, nets=(coincident, moved))) + shifted = _measure_retry(moved_case, "matched-budget", "baseline") + assert shifted["seeds"] == baseline["seeds"] + original_placement = baseline["placements"]["straight"] + moved_placement = shifted["placements"]["straight"] + assert moved_placement["effective_net"]["start"]["y"] == 20 + assert moved_placement["physical_polygon_hashes"] != original_placement["physical_polygon_hashes"] def test_direct_benchmarks_validate_inputs_before_locking_routes() -> None: diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py index bb82252..37521d0 100644 --- a/inire/tests/test_topology.py +++ b/inire/tests/test_topology.py @@ -9,7 +9,9 @@ from inire import ( ) from inire.router._stack import build_routing_stack from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_lane_assignments, plan_corridors +from inire.tests.routing_benchmark_case import BenchmarkCase from inire.tests.routing_benchmarks import DETOUR +from scripts.compare_topological_routing import _measure def test_seed_mode_recovers_a_corridor_after_an_invalid_hint() -> None: @@ -135,6 +137,13 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None: assert [entry.iteration for entry in run.conflict_trace if entry.stage == "iteration"] == [2] assert run.conflict_trace[-1].iteration is None + case = BenchmarkCase("guidance-retry", "Two offset gates", problem, options) + sample = _measure(case, options, mode) + + assert sample.valid_costs.keys() == {"a", "b"} + assert [attempt.topology.guide_strength for attempt in sample.attempt_options] == [0.75, 0.0] + assert sample.selected_attempt == 1 + def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytest.MonkeyPatch) -> None: problem = DETOUR.problem diff --git a/scripts/benchmark_retry_order.py b/scripts/benchmark_retry_order.py index 5645c3a..a761abc 100644 --- a/scripts/benchmark_retry_order.py +++ b/scripts/benchmark_retry_order.py @@ -22,6 +22,7 @@ from inire.tests.routing_corpus import ( benchmark_weighted_length, native_verified_costs, profile_options, + route_placement, select_cases, ) @@ -184,7 +185,7 @@ def _near_port_coverage_stalled(trials: list[Trial], target: int) -> bool: return len(first.valid_costs) == target - 1 and first.valid_costs.keys() == second.valid_costs.keys() -def _measure(case: BenchmarkCase, profile: str, name: str) -> dict: +def _measure(case: BenchmarkCase, profile: str, name: str, *, capture_details: bool = True) -> dict: options = automatic_options(profile_options(case, profile), profile) retry_attempts: list[dict] = [] @@ -205,14 +206,17 @@ def _measure(case: BenchmarkCase, profile: str, name: str) -> dict: report = run.automatic assert report is not None verified = sorted(report.verified_net_ids) + summary = {"elapsed_s": elapsed, "verified": verified} + if not capture_details: + return summary return { - "elapsed_s": elapsed, - "verified": verified, + **summary, "routing_bound": report.max_routed, "nodes_expanded": run.metrics.nodes_expanded, "weighted_cost": {net_id: benchmark_weighted_length(run.results_by_net[net_id]) for net_id in verified}, "native_cost": native_verified_costs(case, options, run.results_by_net, verified), "seeds": {net_id: repr(run.results_by_net[net_id].as_seed()) for net_id in verified}, + "placements": {net_id: route_placement(run.results_by_net[net_id]) for net_id in verified}, "stages": [asdict(stage) for stage in report.stages], "selected_stage": report.selected_stage, "retry_attempts": retry_attempts, @@ -220,13 +224,13 @@ def _measure(case: BenchmarkCase, profile: str, name: str) -> dict: } -def _measure_case(job: tuple[BenchmarkCase, str, tuple[str, ...], int]) -> dict: - case, profile, policies, repeats = job +def _measure_case(job: tuple[BenchmarkCase, str, tuple[str, ...], int, bool]) -> dict: + case, profile, policies, repeats, capture_details = job samples = {name: [] for name in policies} for index in range(repeats): offset = index % len(policies) for name in policies[offset:] + policies[:offset]: - samples[name].append(_measure(case, profile, name)) + samples[name].append(_measure(case, profile, name, capture_details=capture_details)) return {"case": case.name, "profile": profile, "required": len(case.problem.nets), "samples": samples} @@ -237,24 +241,27 @@ def main() -> None: parser.add_argument("--policy", choices=tuple(_POLICIES), action="append") parser.add_argument("--repeat", type=int, default=1) parser.add_argument("--jobs", type=int, default=1) - parser.add_argument("--json", type=Path, required=True) + parser.add_argument("--json", type=Path, help="Write per-run coverage, placement, costs, and retry details to this file.") args = parser.parse_args() if args.repeat < 1 or args.jobs < 1: parser.error("--repeat and --jobs must be positive") cases = select_cases(args.case or ["corpus"]) profiles = tuple(dict.fromkeys(args.profile or ("public-defaults", "corpus-regression"))) policies = tuple(dict.fromkeys(args.policy or _POLICIES)) - jobs = [(case, profile, policies, args.repeat) for case in cases for profile in profiles] + capture_details = args.json is not None + jobs = [(case, profile, policies, args.repeat, capture_details) for case in cases for profile in profiles] rows = [] with ProcessPoolExecutor(max_workers=args.jobs) as pool: for result in pool.map(_measure_case, jobs): - rows.append(result) + if capture_details: + rows.append(result) summary = " ".join( f"{name}={len(samples[0]['verified'])}/{result['required']}@{median(s['elapsed_s'] for s in samples):.3f}s" for name, samples in result["samples"].items() ) print(result["case"], result["profile"], summary, flush=True) - args.json.write_text(dumps({"runs": rows}, indent=2) + "\n", encoding="utf-8") + if args.json is not None: + args.json.write_text(dumps({"runs": rows}, indent=2) + "\n", encoding="utf-8") if __name__ == "__main__": diff --git a/scripts/compare_topological_routing.py b/scripts/compare_topological_routing.py index ba035ff..128e3ec 100644 --- a/scripts/compare_topological_routing.py +++ b/scripts/compare_topological_routing.py @@ -61,6 +61,7 @@ class RunSample: bundle_rejection: str | None = None bundle_duration_s: float | None = None selected_stage: int = 0 + selected_attempt: int | None = None capacity_limit: CapacityLimit | None = None planner_rejections: tuple[str, ...] = () port_conflicts: tuple[tuple[str, str], ...] = () @@ -116,7 +117,17 @@ def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: st def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> RunSample: board = box(*case.problem.bounds) attempt_options: list[RoutingOptions] = [] - run_route = partial(_route, run_router=partial(_dispatch_route, attempt_callback=attempt_options.append)) + selected_attempt: int | None = None + + def select_attempt(index: int) -> None: + nonlocal selected_attempt + selected_attempt = index + + dispatch = partial( + _dispatch_route, attempt_callback=attempt_options.append, + selected_attempt_callback=select_attempt if strategy in ("guide", "seed") else None, + ) + run_route = partial(_route, run_router=dispatch) run_worker = partial(route_once, attempt_callback=attempt_options.append) def measure_direct(problem: RoutingProblem, policy: str) -> tuple[RoutingRunResult, list[Trial]]: @@ -203,6 +214,7 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run bundle_rejection=bundle_rejection, bundle_duration_s=bundle_duration, selected_stage=next(i for i, trial in enumerate(trials) if trial is best), + selected_attempt=selected_attempt, ) diff --git a/scripts/routing_benchmark_parity.py b/scripts/routing_benchmark_parity.py index 8c152c0..ed060d7 100644 --- a/scripts/routing_benchmark_parity.py +++ b/scripts/routing_benchmark_parity.py @@ -5,14 +5,11 @@ from __future__ import annotations from argparse import ArgumentParser from concurrent.futures import ProcessPoolExecutor from dataclasses import asdict, replace -from hashlib import sha256 from json import dumps, loads from pathlib import Path from time import perf_counter from typing import TYPE_CHECKING -from shapely import to_wkb - from inire import DiagnosticsOptions, route from inire.results import RouteMetrics from inire.tests.routing_corpus import ( @@ -22,6 +19,7 @@ from inire.tests.routing_corpus import ( benchmark_weighted_length, native_verified_costs, profile_options, + route_placement, select_cases, ) from scripts.compare_topological_routing import _geometry_json @@ -42,8 +40,7 @@ def _paths(results: dict[str, RoutingResult]) -> dict: "outcome": result.outcome, "reached_target": result.reached_target, "seed": [{"kind": type(move).__name__, **asdict(move)} for move in result.as_seed().segments], - "effective_net": asdict(result.effective_net) if result.effective_net is not None else None, - "physical_polygon_hashes": [sha256(wkb).hexdigest() for wkb in to_wkb(result.locked_geometry, byte_order=1)], + **route_placement(result), "report": asdict(result.report), } for net_id, result in results.items() From 63acb94642457ba170afd2011b2c5d280df3e2b6 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Wed, 2 Dec 2026 17:16:34 -0800 Subject: [PATCH 57/57] Fix routing correctness and bound optional routing work Check physical keepout clearance, retain useful partial paths, and account for all pair repair searches. Verify complete seeds early and recover narrower corridors when shared guides are blocked. Keep frontier diagnostics outside routing decisions and bound their work by the worker deadline. Correct benchmark scaling and scenario validation, and update the guides and release metadata. --- README.md | 16 +- archive/routing/README.md | 2 + archive/routing/routing-refactor-plan.md | 2 +- docs/architecture.md | 2 +- docs/benchmark-fixtures.md | 6 +- docs/routing-diagnostics.md | 6 +- docs/topological-routing.md | 6 +- docs/user/tune-and-troubleshoot.md | 2 +- inire/__init__.py | 4 + inire/geometry/collision.py | 18 +- inire/geometry/components.py | 18 +- inire/geometry/static_obstacle_index.py | 9 +- inire/results.py | 5 + inire/router/_astar_admission.py | 2 +- inire/router/_congestion_policy.py | 12 - inire/router/_pair_local.py | 8 +- inire/router/_router.py | 327 ++++++++++++++------- inire/router/_routing_policy.py | 20 +- inire/router/_stack.py | 4 +- inire/router/_topology.py | 79 ++++- inire/router/refiner.py | 18 +- inire/router/visibility.py | 3 +- inire/tests/example_scenarios.py | 14 +- inire/tests/routing_expanded_benchmarks.py | 2 +- inire/tests/routing_external_benchmarks.py | 5 +- inire/tests/test_api.py | 142 ++++++++- inire/tests/test_collision.py | 15 +- inire/tests/test_congestion_policy.py | 11 - inire/tests/test_example_performance.py | 2 +- inire/tests/test_example_regressions.py | 7 + inire/tests/test_performance_reporting.py | 17 ++ inire/tests/test_refinements.py | 21 ++ inire/tests/test_routing_benchmarks.py | 26 +- inire/tests/test_terminal_bench.py | 40 ++- inire/tests/test_topology.py | 132 ++++++++- inire/tests/test_visibility.py | 18 +- plans/routing-follow-up-review.md | 228 ++++++++++++++ pyproject.toml | 7 +- scripts/diff_performance_baseline.py | 10 +- scripts/record_performance_baseline.py | 8 +- 40 files changed, 1074 insertions(+), 200 deletions(-) create mode 100644 plans/routing-follow-up-review.md diff --git a/README.md b/README.md index db8e725..c609e27 100644 --- a/README.md +++ b/README.md @@ -31,22 +31,22 @@ else: print(result.outcome) ``` -![A short solid waveguide connects the start at (50, 100) and target at (250, 100). Both port arrows point east.](docs/figures/first-route.png) +![A short solid waveguide connects the start at (50, 100) and target at (250, 100). Both port arrows point east.](https://mpxd.net/code/jan/inire/raw/branch/topo/docs/figures/first-route.png) The example prints `200.0`. Heading `0` is east at both ports. ## Route your own layout -- [Layout inputs](docs/user/route-a-layout.md#define-the-inputs) -- [Partial routes](docs/user/tune-and-troubleshoot.md#why-a-net-stopped-short) -- [Placement recipes](docs/user/route-a-layout.md#save-a-placement-recipe) -- [User guide](DOCS.md) +- [Layout inputs](https://mpxd.net/code/jan/inire/src/branch/topo/docs/user/route-a-layout.md#user-content-define-the-inputs) +- [Partial routes](https://mpxd.net/code/jan/inire/src/branch/topo/docs/user/tune-and-troubleshoot.md#user-content-why-a-net-stopped-short) +- [Placement recipes](https://mpxd.net/code/jan/inire/src/branch/topo/docs/user/route-a-layout.md#user-content-save-a-placement-recipe) +- [User guide](https://mpxd.net/code/jan/inire/src/branch/topo/DOCS.md) ## Develop Inire -- [Developer guide](docs/development.md) -- [Routing benchmarks](docs/benchmarks.md) +- [Developer guide](https://mpxd.net/code/jan/inire/src/branch/topo/docs/development.md) +- [Routing benchmarks](https://mpxd.net/code/jan/inire/src/branch/topo/docs/benchmarks.md) ## License -Inire is distributed under the [GNU Affero General Public License v3](LICENSE.md). +Inire is distributed under the [GNU Affero General Public License v3](https://mpxd.net/code/jan/inire/src/branch/topo/LICENSE.md). diff --git a/archive/routing/README.md b/archive/routing/README.md index e72197d..9d3009d 100644 --- a/archive/routing/README.md +++ b/archive/routing/README.md @@ -28,3 +28,5 @@ Use these records to recover the rationale for a routing decision or compare a f | Reroute order and work immediately before repair | [Pre-pair frontier trace](pre_pair_frontier_trace.md). | Each trace report has a companion JSON file with the same basename. The baseline comparison tool reads `performance_baseline.json` from this directory by default. For a fresh trace, set `--output-dir` to keep the capture separate from the archived record. See the [fan-out capture command](../../docs/routing-diagnostics.md#follow-a-late-conflict-into-pair-local-repair). + +In the archived traces and pair-local characterization, `nodes_expanded` excludes pair-local search. The archived `pair_local_search_nodes_expanded` counts only attempts that produced a locally valid pair. Neither convention affects the nine scenarios in the saved performance baseline, which used no pair-local search. Fresh captures count every pair-local search in both counters. diff --git a/archive/routing/routing-refactor-plan.md b/archive/routing/routing-refactor-plan.md index 5764183..26c1c5b 100644 --- a/archive/routing/routing-refactor-plan.md +++ b/archive/routing/routing-refactor-plan.md @@ -42,7 +42,7 @@ Use this record to recover the original refactor scope and the reason for each p ## Verification -Use the current 67-board corpus as the regression baseline for routing changes. The `corpus-regression` and `public-defaults` profiles reach every board's routing bound and verify 433 of 437 nets each. For behavior-preserving changes, compare exact paths, per-net costs, bounds, planner stage order and metadata, and relevant callback and trace payloads. For changes that intentionally eliminate work, such as item 13, record the expected counter differences while checking route and trace parity. [Corpus reproduction](../../docs/benchmarks.md#run-the-full-regression-corpus) +Use the current 67-board corpus as the regression baseline for routing changes. The `corpus-regression` and `public-defaults` profiles reach every board's routing bound and verify 433 of 437 nets each. For behavior-preserving changes, compare exact paths, per-net costs, bounds, planner stage order and metadata, and relevant callback and trace payloads. For changes that intentionally eliminate work, such as item 13, record the expected counter differences while checking route and trace parity. [Corpus reproduction](../../docs/benchmarks.md#run-the-full-benchmark-corpus) Capture the same cases and options at both revisions. The parity command defaults to the `corpus-regression` and `public-defaults` profiles. [Parity commands](../../docs/routing-diagnostics.md#reproduce-and-compare) diff --git a/docs/architecture.md b/docs/architecture.md index fb6925c..4f3b083 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -10,7 +10,7 @@ Follow the left column while coverage is below the target. Reaching the target s 1. **Set a coverage target.** Conflicting aligned port faces and [track capacity](../inire/router/_capacity.py#L29) at rectangular cuts can bound how many nets fit. 2. **Try constructive plans.** Bundles assign ordered tracks, columns schedule turns, and compact planners fit short links. Each plan supplies seeds for the worker to verify. -3. **Search for missing routes.** Early attempts use small budgets and can hold verified routes fixed. When a column plan stalls, try separated channels or a shared bypass around the keepouts. If the locks cut off a port, retry with movable seeds or different lanes. With one net left, try a verified detour around the locked paths, including incumbents found by the seed fallback. Lattice search handles custom outlines or proxies and is the fallback when corridor planning is unavailable. +3. **Search for missing routes.** Early attempts use small budgets and can hold verified routes fixed. When a column plan stalls, try separated channels or a shared bypass around the keepouts. If the locks cut off a port, retry with movable seeds or different lanes. With one net left, try a verified detour around the locked paths, including incumbents found by the seed fallback. Lattice search handles custom outlines and proxies and can retry unresolved nets after corridor-guided attempts. 4. **Select and refine.** Prefer higher verified coverage. Compare cost on matching verified net IDs. Refinement can replace the selected layout only if those IDs remain verified. ### Example of a poor lock diff --git a/docs/benchmark-fixtures.md b/docs/benchmark-fixtures.md index 95c27cf..ed24852 100644 --- a/docs/benchmark-fixtures.md +++ b/docs/benchmark-fixtures.md @@ -5,16 +5,16 @@ ## Micron-scale routing cases -The `expanded` group adds 72 deterministic, unseeded boards with independently constructed reference routes. The authored grid units are 10, 100, 250, 500, and 1000 nm. Bend radii span 10–100 µm and trace widths span 1–20 µm. The comparison script records `grid_nm` for these boards. Convert benchmark-weighted lengths to microns by multiplying by `grid_nm / 1000`. +The `expanded` group adds 75 deterministic, unseeded boards with independently constructed reference routes. The authored grid units are 10, 100, 250, 500, and 1000 nm. Bend radii span 10–100 µm and trace widths span 1–20 µm. The comparison script records `grid_nm` for these boards and the imported fixtures. Convert benchmark-weighted lengths to microns by multiplying by `grid_nm / 1000`. | Group | Boards | Coverage | | --- | ---: | --- | | `geometry-corners` | 32 | Exact four-bend spans, tight returns and paired routes, exact-span S-bend slots, mixed widths, and saturated or overloaded apertures. | | `complex-layouts` | 24 | Serial aperture banks with opposing tracks, concave and fixed-route keepouts, and staggered crossing arrays. | -| `search-challenges` | 8 | Alternating comb walls that force repeated turns and exercise search-budget exhaustion. | +| `search-challenges` | 11 | Alternating comb walls and other tight passages that require repeated turns or exercise search-budget exhaustion. | | `scaling` | 8 | Banks and crossing arrays of up to 256 nets, obstacle fields with up to 320 keepouts, and a 240-net board with 240 keepouts and four blocked approaches. | -Pytest verifies the 72 reference layouts and checks that unseeded routing reaches the known bound on every board. Use `--case search-challenges` or `--case scaling` with an explicit budget to compare routing policies on the harder boards. For scaling comparisons, use the same grid, mode, and budget and collect repeated timings with `--repeat`. +Pytest verifies the 75 reference layouts and checks that unseeded routing reaches the known bound on every board. Use `--case search-challenges` or `--case scaling` with an explicit budget to compare routing policies on the harder boards. For scaling comparisons, use the same grid, mode, and budget and collect repeated timings with `--repeat`. To exercise the low-budget fallbacks on tight geometry, run `--case geometry-corners --profile corpus-regression --mode automatic --nodes 1 --seed-nodes 1 --iterations 1`. diff --git a/docs/routing-diagnostics.md b/docs/routing-diagnostics.md index db8ff2f..8b87785 100644 --- a/docs/routing-diagnostics.md +++ b/docs/routing-diagnostics.md @@ -22,10 +22,12 @@ Use repeated wall times to check whether counter changes affect runtime. | Similar expansions, more search time | Check `ray_cast_calls*` and `ray_cast_exact_geometry_checks` for visibility work. Compare dynamic `congestion_candidate_ids` with `congestion_exact_pair_checks` to see how much candidate geometry reaches exact tests. | | Verification dominates | Compare `verify_path_report_calls` with `verify_static_buffer_ops` and `verify_dynamic_exact_pair_checks`. This can distinguish repeated path checks from expensive checks of the same paths. | | Refinement takes longer | Compare `refinement_windows_considered`, `refinement_candidates_verified`, and `refinement_candidates_accepted`. Check whether the added windows buy a better path before enlarging the default budget. | -| Attempts reach targets while verified coverage stays flat | Compare `iteration_conflict_edges` and `nets_carried_forward`. After congestion iterations finish, check how many pair repairs were tried and how many were installed. `pair_local_search_nodes_expanded` counts expansions from searches that produced a locally valid pair. Use `pair_local_search_attempts` to count every try. | +| Attempts reach targets while verified coverage stays flat | Compare `iteration_conflict_edges` and `nets_carried_forward`. After congestion iterations finish, check how many pair repairs were tried and how many were installed. `pair_local_search_nodes_expanded` counts expansions from every pair-local search and is included in `nodes_expanded`. Use `pair_local_search_attempts` to count every try. | `nets_routed` and `nets_reached_target` count attempts. Use `result.is_valid` or `verified_net_ids` for final successes. +`timeout_events` counts routing workers that reached their deadline. Frontier diagnostics use the time left after routing and final verification. They gather component details for colliding nets and check the deadline during that work and during frontier replay. `diagnostic_timeout_events` counts workers where the deadline stopped or skipped frontier diagnostics. A diagnostic timeout leaves the routing result, retry decisions, and replay callback intact. + - [Full metrics field list](../inire/results.py) Exact corner visibility uses cached local queries. Track them with `visibility_corner_queries_exact` and `visibility_point_cache_hits`. The legacy graph counters `visibility_builds` and `visibility_corner_pairs_checked` report zero, as do `ray_cast_calls_visibility_build` and `ray_cast_calls_visibility_query`. @@ -43,7 +45,7 @@ Returned traces describe the selected attempt. Numbered entries use the same run | Which net consumed an iteration's budget? | `capture_iteration_trace` records `iteration_trace`. Inspect per-net `net_attempts` for expansions, pruning, congestion calls, and seed usage. | | Which routes have a clearance conflict? | `capture_conflict_trace` records the conflicting net IDs and the component indices in `conflict_trace`. | | Which candidate moves were pruned near the conflict? | `capture_frontier_trace` records `frontier_trace` for routes that reached their targets and still conflict with other nets. The trace samples moves and their prune reasons during a replay. | -| What did the last unresolved iteration hand to pair-local repair? | `capture_pre_pair_frontier_trace` records `pre_pair_frontier_trace`. Check reroute order, conflict edges, and per-net attempt work immediately before repair. | +| What layout did the worker restore for pair-local repair? | `capture_pre_pair_frontier_trace` records the selected congestion iteration, its reroute order, conflict edges, and work. The worker saves that layout and replays it after repair and verification. A conflicting net carried from an earlier iteration has zero attempt work for the selected iteration. | | Where did detailed search explore? | `capture_expanded` records positions and headings from the detailed routing iterations in `expanded_nodes`. Use `plot_expanded_nodes()` as in the [fan-out script](../examples/07_large_scale_routing.py). | diff --git a/docs/topological-routing.md b/docs/topological-routing.md index 321a2ee..3e505d5 100644 --- a/docs/topological-routing.md +++ b/docs/topological-routing.md @@ -10,17 +10,17 @@ Read the panels from top to bottom. Follow the crossed triangle edges, the suggested crossing points, then the S-bend in the verified route. -1. **Find space for centerlines.** Inset the board by half the widest guide's width. Expand obstacles by that amount plus clearance. Try a straight port lead to reach the mesh, or use the port itself. A flush port can reach the inset mesh via a lead whose flat end fits on the board. If a narrow net has no passage, retry with its own width. +1. **Find space for centerlines.** Inset the board by half the widest guide's width. Expand obstacles by that amount plus clearance. Try a straight port lead to reach the mesh, or use the port itself. A flush port can reach the inset mesh via a lead whose flat end fits on the board. Nets can reuse shared corridors when the mesh has open space around both ports and the area between them. A narrower mesh can recover missing corridors and add passages near keepouts or board edges. If a shared guide fails and a reserved route occupies that shared space, the worker can build a narrower mesh on demand. A straight path that fits in the shared mesh can supply its own alternate guide. A portal is an edge shared by adjacent free-space triangles. For an earlier representation of a route by its crossings of triangle edges, see Section III-A and Figure 1 of [Hama and Etoh's curvilinear detailed-routing paper](https://www.cecs.uci.edu/~papers/compendium94-03/papers/1998/aspdac98/pdffiles/06c_3.pdf). -2. **Choose a passage and a lane.** Rank passages by distance and competing nets. Place lanes on shared triangle edges according to turn room and reservations. A joint retry can move lanes for several nets. +2. **Choose a passage and a lane.** Rank passages by distance and competing nets. Assign lanes jointly by reserving space on shared triangle edges as each net is planned. - [Lane scoring](../inire/router/_topology.py#L255) -3. **Turn the sketch into a path.** Guide mode suggests moves and adds a soft cost. Seed mode searches within a corridor and checks the resulting seed against obstacles and earlier seeds. With alternatives, it allocates at least half the seed budget to the first corridor. +3. **Turn the sketch into a path.** Guide mode suggests moves and adds a soft cost. Seed mode searches within a corridor and checks the resulting seed against obstacles and earlier seeds. With alternatives, it allocates at least half the seed budget to the first corridor. With at least two iterations and positive guidance strength, an explicit guided run that leaves unresolved nets can retry with the guidance cost disabled. Guide and seed modes can verify a complete supplied layout before building corridors. A passage can be connected in the mesh and leave too little room to bend onto the target port's heading. For the bend-radius and port-alignment rules that constrain the physical route, see Section II-B of [LiDAR 2.0](https://arxiv.org/html/2505.17239v1#S2.SS2). diff --git a/docs/user/tune-and-troubleshoot.md b/docs/user/tune-and-troubleshoot.md index a4d04ea..cdce9dd 100644 --- a/docs/user/tune-and-troubleshoot.md +++ b/docs/user/tune-and-troubleshoot.md @@ -31,7 +31,7 @@ Set `TopologyOptions(mode=...)` and pass it as `topology` in `RoutingOptions`. - **`off`.** Run lattice search directly to measure what search can do without corridor suggestions. - **`guide`.** Suggest a passage through free space. Search can leave it to make a turn. - **`seed`.** Try to build a valid starting path inside the suggested passage before the detailed search. -- **`bundle`.** Route supported ordered rectangular bundles with an empty `initial_paths` mapping. Use circular physical bends. The smallest 90-degree bend radius must be a positive integer and must also appear in `sbend_radii`. Unsupported layouts and invalid schedules raise `ValueError`. +- **`bundle`.** Route supported ordered rectangular bundles with an empty `initial_paths` mapping. Use circular physical bends and configure a usable positive integer radius in both `bend_radii` and `sbend_radii`. Unsupported layouts and invalid schedules raise `ValueError` when routing iterations are enabled. ### Mode requirements diff --git a/inire/__init__.py b/inire/__init__.py index 2911e17..ccef84e 100644 --- a/inire/__init__.py +++ b/inire/__init__.py @@ -147,6 +147,10 @@ def _route( raise ValueError(f"Initial path provided for unknown net: {net_id}") if net_id not in coincident and (error := search.seed_geometry_error(seed)) is not None: seed_errors[net_id] = f"Initial path for {net_id!r} {error}" + if options.topology.mode == "automatic" and options.topology.infer_terminal_headings and any( + seed.segments and net_id not in coincident for net_id, seed in problem.initial_paths.items() + ): + options = replace(options, topology=replace(options.topology, infer_terminal_headings=False)) if coincident or seed_errors: problem = replace( problem, diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index 33a1e8b..b7681f0 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -18,7 +18,7 @@ from inire.results import RoutingReport from inire.geometry.static_obstacle_index import StaticObstacleIndex if TYPE_CHECKING: - from collections.abc import Iterable, Sequence + from collections.abc import Callable, Iterable, Sequence from shapely.geometry import Polygon from shapely.geometry.base import BaseGeometry @@ -304,7 +304,7 @@ class RoutingWorld: clearance = self.clearance left, bottom, right, top = result.total_bounds - if self._static_obstacles.owners: + if self._static_obstacles.owners or result.check_physical_keepout: x0, y0, x1, y1 = result.total_physical_bounds left, bottom, right, top = min(left, x0), min(bottom, y0), max(right, x1), max(top, y1) # The broad phase must include both the keepout proxy and the physical outline. @@ -317,6 +317,8 @@ class RoutingWorld: if any(_violates_net_clearance(polygon, obstacle, clearance) for polygon in physical): return True continue + if result.check_physical_keepout and any(_violates_clearance(polygon, obstacle, clearance) for polygon in physical): + return True for polygon in result.collision_geometry: if not _violates_clearance(polygon, obstacle, clearance): continue @@ -758,8 +760,11 @@ class RoutingWorld: capture_component_conflicts: bool = False, include_invalid_dynamic: bool = True, geometry_report: RoutingReport | None = None, + diagnostic_expired: Callable[[], bool] | None = None, ) -> PathVerificationDetail: - """Check the full path, optionally reusing its report against unchanged static geometry.""" + """Check a path, or collect component conflicts from an already verified report for diagnostics.""" + if diagnostic_expired is not None and geometry_report is None: + raise ValueError("Diagnostic conflict collection needs a verified path report") if self.metrics is not None: self.metrics.total_verify_path_report_calls += 1 report = self.verify_path_geometry(components) if geometry_report is None else geometry_report @@ -772,7 +777,10 @@ class RoutingWorld: and (include_invalid_dynamic or not report.intrinsic_collision_count) and self._dynamic_paths.has_physical_paths() ): + comparisons = 0 for component_index, component in enumerate(components): + if diagnostic_expired is not None and diagnostic_expired(): + return PathVerificationDetail(report=report) component_hits: set[str] = set() for polygon in component.physical_geometry: candidates = self._physical_candidates(net_id, polygon) @@ -782,6 +790,10 @@ class RoutingWorld: for hit_net_id, hit_component_index, other in candidates: if hit_net_id in polygon_hits and not capture_component_conflicts: continue + if diagnostic_expired is not None: + comparisons += 1 + if comparisons % 32 == 0 and diagnostic_expired(): + return PathVerificationDetail(report=report) if self.metrics is not None: self.metrics.total_verify_dynamic_exact_pair_checks += 1 if _violates_net_clearance(polygon, other, self.clearance): diff --git a/inire/geometry/components.py b/inire/geometry/components.py index 662643b..5c6b1e4 100644 --- a/inire/geometry/components.py +++ b/inire/geometry/components.py @@ -1,6 +1,6 @@ from __future__ import annotations -from dataclasses import dataclass, field, replace +from dataclasses import dataclass, field, fields, replace from math import asin, ceil, isfinite, pi, radians, sqrt from typing import TYPE_CHECKING, Literal @@ -138,6 +138,13 @@ class ComponentResult: _total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None) _physical_geometry_valid: bool | None = field(init=False, repr=False, compare=False, default=None) _coordinate_count: int | None = field(init=False, repr=False, compare=False, default=None) + check_physical_keepout: bool = field(default=False, repr=False, compare=False) + + def __setstate__(self, state: list[object]) -> None: + for item, value in zip(fields(self), state, strict=False): + object.__setattr__(self, item.name, value) + if len(state) < len(fields(self)): + object.__setattr__(self, "check_physical_keepout", self.collision_geometry is not self.physical_geometry) def __post_init__(self) -> None: collision_geometry = tuple(self.collision_geometry) @@ -257,6 +264,7 @@ class ComponentResult: dilated_physical_geometry=translate_geometry(self.dilated_physical_geometry), width=self.width, standard_faces=self.standard_faces, + check_physical_keepout=self.check_physical_keepout, ) object.__setattr__(result, "_coordinate_count", self._coordinate_count) return result @@ -565,6 +573,11 @@ class Bend90: dilated_physical_geometry=dilated_physical_geometry, width=width, standard_faces=physical_geometry is arc_polys, + check_physical_keepout=( + custom_physical + or isinstance(collision_type, Polygon) + or (collision_type == "clipped_bbox" and clip_margin is not None and clip_margin > 0) + ), ) @@ -682,6 +695,9 @@ class SBend: dilated_physical_geometry=dilated_physical_geometry, width=width, standard_faces=outline is None, + check_physical_keepout=( + outline is None and collision_type == "clipped_bbox" and clip_margin is not None and clip_margin > 0 + ), ) diff --git a/inire/geometry/static_obstacle_index.py b/inire/geometry/static_obstacle_index.py index 99fd153..2585d17 100644 --- a/inire/geometry/static_obstacle_index.py +++ b/inire/geometry/static_obstacle_index.py @@ -1,5 +1,6 @@ from __future__ import annotations +from collections import OrderedDict from typing import TYPE_CHECKING import numpy @@ -15,6 +16,9 @@ if TYPE_CHECKING: from inire.geometry.collision import RoutingWorld +_NET_TREE_CACHE_SIZE = 8 + + class StaticObstacleIndex: __slots__ = ( "engine", @@ -48,7 +52,7 @@ class StaticObstacleIndex: self.raw_tree: STRtree | None = None self.raw_owners: tuple[str | None, ...] = () self.owners: dict[int, str] = {} - self.net_specific_trees: dict[tuple[float, float], tuple[STRtree, numpy.ndarray, numpy.ndarray]] = {} + self.net_specific_trees: OrderedDict[tuple[float, float], tuple[STRtree, numpy.ndarray, numpy.ndarray]] = OrderedDict() self.ray_cast_cache: dict[tuple[float, float, float, float, float | None, float, type, type, type, type], float] = {} self.id_counter = 0 self.version = 0 @@ -107,6 +111,7 @@ class StaticObstacleIndex: width, clearance = float(net_width), float(self.engine.clearance) key = (width, clearance) if key in self.net_specific_trees: + self.net_specific_trees.move_to_end(key) return self.net_specific_trees[key] if self.engine.metrics is not None: @@ -127,6 +132,8 @@ class StaticObstacleIndex: payload = (STRtree(geometries), numpy.array(is_rect_list, dtype=bool), numpy.array(bounds_list, dtype=numpy.float64)) self.net_specific_trees[key] = payload + if len(self.net_specific_trees) > _NET_TREE_CACHE_SIZE: + self.net_specific_trees.popitem(last=False) return payload def ensure_raw_tree(self) -> None: diff --git a/inire/results.py b/inire/results.py index 9e2cc47..3446b5e 100644 --- a/inire/results.py +++ b/inire/results.py @@ -256,6 +256,11 @@ class RouteMetrics: pair_local_search_nodes_expanded: int late_phase_capped_nets: int late_phase_capped_fallbacks: int + diagnostic_timeout_events: int = 0 + + def __setstate__(self, state: list[object]) -> None: + for index, item in enumerate(fields(self)): + object.__setattr__(self, item.name, state[index] if index < len(state) else item.default) def _sum_route_metrics(samples: Iterable[RouteMetrics]) -> RouteMetrics: diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index 463f6bd..c782cb6 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -217,7 +217,7 @@ def add_node( applied_bonus = config.guidance_bonus context.metrics.total_guidance_bonus_applied_sbend += applied_bonus context.metrics.total_guidance_bonus_applied += applied_bonus - move_cost = max(0.001, move_cost - applied_bonus) + move_cost = min(move_cost, max(0.001, move_cost - applied_bonus)) next_seed_index = parent.seed_index + 1 if corridor is not None and config.corridor_strength: diff --git a/inire/router/_congestion_policy.py b/inire/router/_congestion_policy.py index cf8c9f1..835e4f1 100644 --- a/inire/router/_congestion_policy.py +++ b/inire/router/_congestion_policy.py @@ -106,15 +106,3 @@ def next_reroute_net_ids( if has_corridors or (all_reached_target and 0 < len(review.conflict_edges) <= 3): return set(ordered_net_ids).difference(review.completed_net_ids) return set(ordered_net_ids) - - -def reached_pair_local_plateau(*, improved: bool, all_reached_target: bool, best_conflict_edges: int | None) -> bool: - # A non-improving iteration with at most two remaining conflicts is - # enough to hand the reached-target layout to bounded pair-local repair. - return not improved and all_reached_target and best_conflict_edges is not None and best_conflict_edges <= 2 - - -def repeated_conflict_count(current_edges: int, previous_edges: int, previous_repeats: int) -> int: - if current_edges and current_edges == previous_edges: - return previous_repeats + 1 - return 0 diff --git a/inire/router/_pair_local.py b/inire/router/_pair_local.py index 74650a5..a6e1e6a 100644 --- a/inire/router/_pair_local.py +++ b/inire/router/_pair_local.py @@ -72,8 +72,8 @@ def search_pair_candidate( *, needs_self_collision_check: Set[str], expired: Callable[[], bool] | None = None, -) -> tuple[dict[str, RoutingResult], int] | None: - """Return both locally verified replacements and their search work.""" +) -> tuple[dict[str, RoutingResult] | None, int]: + """Return search work and the locally verified replacements, if any.""" local = _build_pair_local_context(context, ordered_nets, incumbent_results, pair_order) world = local.cost_evaluator.collision_engine options = local.options @@ -102,11 +102,11 @@ def search_pair_candidate( config=config, ) if not path or path[-1].end_port != net.target: - return None + return None, local.metrics.total_nodes_expanded report = world.verify_path_report(net_id, path) if not report.is_valid: - return None + return None, local.metrics.total_nodes_expanded replacements[net_id] = RoutingResult(net_id, tuple(path), reached_target=True, report=report) for component in path: for polygon in component.physical_geometry: diff --git a/inire/router/_router.py b/inire/router/_router.py index 4c394f1..94bddbb 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -7,8 +7,9 @@ from dataclasses import dataclass, field, replace from functools import partial from typing import TYPE_CHECKING -from shapely import shortest_line +from shapely import STRtree, shortest_line +from inire.geometry.collision import _violates_net_clearance from inire.geometry.components import bend_fits_width, bend90_uses_circular_geometry from inire.model import resolve_bend_geometry from inire.results import ( @@ -30,14 +31,12 @@ from inire.router._congestion_policy import ( can_reserve, next_reroute_net_ids, ordered_nets, - reached_pair_local_plateau, - repeated_conflict_count, reroute_plan, review_verified_results, ) from inire.router._pair_local import search_pair_candidate from inire.router._route_traces import conflict_trace_entry, iteration_trace_entry, net_attempt_trace -from inire.router._search import incumbent_guidance, path_guidance, route_astar +from inire.router._search import _distance_to_terminal, incumbent_guidance, path_guidance, route_astar from inire.router._seed_materialization import materialize_path_seed, SeedMaterializationError from inire.router.refiner import PathRefiner @@ -49,7 +48,7 @@ if TYPE_CHECKING: from inire.geometry.components import ComponentResult from inire.model import NetSpec from inire.results import ConflictTraceStage, RoutingOperation - from inire.router._topology import Corridor + from inire.router._topology import Corridor, DeferredCorridor PhaseTimer = Callable[[RoutingOperation], AbstractContextManager[None]] @@ -67,11 +66,11 @@ class _RoutingState: best_results: dict[str, RoutingResult] best_is_indexed: bool best_review: _IterationReview | None - last_conflict_edge_count: int - repeated_conflict_count: int recent_attempt_work: dict[str, int] - pre_pair_candidate: _PrePairCandidate | None + pre_pair_candidate: _PrePairCandidate | None = None + best_pre_pair_candidate: _PrePairCandidate | None = None corridors: dict[str, tuple[Corridor, ...]] = field(default_factory=dict) + deferred_corridors: dict[str, DeferredCorridor] = field(default_factory=dict) seed_errors: dict[str, str] = field(default_factory=dict) terminal_errors: dict[str, str] = field(default_factory=dict) replay_details: dict[str, PathVerificationDetail] | None = None @@ -253,11 +252,19 @@ class PathFinder: continue net = state.net_specs[net_id] candidates = state.corridors.get(net_id, ()) + blocked_shared_space = self._shared_guide_blocked(state, net_id) remaining = min(topology.seed_node_limit, self.context.options.search.node_limit) - for index, corridor in enumerate(candidates): - if remaining <= 0: + for index in range(topology.max_corridors): + if remaining <= 0 or expired(): + break + if index == 1 and blocked_shared_space: + self._recover_corridor(state, net_id) + candidates = state.corridors[net_id] + if index >= len(candidates): break searches_left = len(candidates) - index + if index == 0 and blocked_shared_space: + searches_left = min(topology.max_corridors, searches_left + 1) budget = max(1, remaining // searches_left) if index == 0 and searches_left > 1: budget = max(budget, (remaining + 1) // 2) @@ -266,7 +273,7 @@ class PathFinder: node_limit=budget, skip_congestion=True, self_collision_check=True, - corridor=corridor, + corridor=candidates[index], restrict_to_corridor=True, expired=expired, ) @@ -279,6 +286,23 @@ class PathFinder: break return seeds + def _shared_guide_blocked(self, state: _RoutingState, net_id: str) -> bool: + deferred = state.deferred_corridors.get(net_id) + if deferred is None: + return False + world = self.context.cost_evaluator.collision_engine + return any(world.iter_static_obstacle_bounds(deferred.bounds)) or any(world.iter_dynamic_path_bounds(deferred.bounds)) + + def _recover_corridor(self, state: _RoutingState, net_id: str) -> Corridor | None: + deferred = state.deferred_corridors.pop(net_id) + if self._expired(state): + return None + alternate = deferred.recover() + if alternate is not None: + first, *rest = state.corridors[net_id] + state.corridors[net_id] = (first, alternate, *rest)[:self.context.options.topology.max_corridors] + return alternate + def _prepare_topology(self, state: _RoutingState, corridors: dict[str, tuple[Corridor, ...]] | None) -> None: topology = self.context.options.topology if topology.mode == "bundle": @@ -300,6 +324,7 @@ class PathFinder: clearance=world.clearance, bend_radius=min(self.context.options.search.bend_radii, default=0.0), limit=topology.max_corridors, + deferred=state.deferred_corridors, ) state.corridors = corridors before = self.metrics.total_nodes_expanded @@ -329,13 +354,10 @@ class PathFinder: best_results={}, best_is_indexed=False, best_review=None, - last_conflict_edge_count=0, - repeated_conflict_count=0, recent_attempt_work={}, - pre_pair_candidate=None, ) - self._materialize_problem_initial_paths(state) if congestion.max_iterations: + self._materialize_problem_initial_paths(state) world = self.context.cost_evaluator.collision_engine search = self.context.options.search proxy, physical_bend = resolve_bend_geometry(search) @@ -361,6 +383,9 @@ class PathFinder: return state if self._expired(state): return state + if self.context.options.topology.mode in ("guide", "seed") and self._verify_complete_seeds(state): + self.topology_report = TopologyReport() + return state self._prepare_topology(state, corridors) if self._expired(state): return state @@ -379,12 +404,39 @@ class PathFinder: state.results[net_id] = RoutingResult(net_id, path, reached_target=True, report=report) return state + def _verify_complete_seeds(self, state: _RoutingState) -> bool: + paths = state.initial_paths + if not paths or len(paths) != len(state.net_specs) or any( + path[-1].end_port != state.net_specs[net_id].target for net_id, path in paths.items() + ): + return False + + seeded = {net_id: RoutingResult(net_id, path, reached_target=True) for net_id, path in paths.items()} + self._replace_indexed_routes(state, seeded) + results, details, review = self._analyze_results( + state.ordered_net_ids, seeded, capture_component_conflicts=False, count_iteration_metrics=False, + ) + if len(review.completed_net_ids) != len(seeded): + self._replace_indexed_routes(state, {}) + return False + state.results = results + state.replay_details = details + return True + def _expired(self, state: _RoutingState) -> bool: if not state.timed_out and time.monotonic() - state.start_time >= state.timeout_s: state.timed_out = True self.metrics.total_timeout_events += 1 return state.timed_out + def _diagnostics_expired(self, state: _RoutingState) -> bool: + if self.metrics.total_diagnostic_timeout_events: + return True + if time.monotonic() - state.start_time >= state.timeout_s: + self.metrics.total_diagnostic_timeout_events += 1 + return True + return False + def _materialize_problem_initial_paths(self, state: _RoutingState) -> None: if not self.context.problem.initial_paths: return @@ -434,7 +486,7 @@ class PathFinder: state.results, details_by_net, review = self._analyze_results( state.ordered_net_ids, state.results, - capture_component_conflicts=diagnostics.capture_conflict_trace or diagnostics.capture_pre_pair_frontier_trace, + capture_component_conflicts=diagnostics.capture_conflict_trace, count_iteration_metrics=False, ) else: @@ -448,22 +500,54 @@ class PathFinder: details_by_net=details_by_net, review=review, ) - if diagnostics.capture_pre_pair_frontier_trace: - self.pre_pair_frontier_trace = self._materialize_pre_pair_frontier_trace( - state, - state.results, - details_by_net, - ) return review def _update_best_iteration(self, state: _RoutingState, review: _IterationReview) -> bool: if state.best_review is not None and review.rank >= state.best_review.rank: + if review.rank == state.best_review.rank and review.completed_net_ids == state.best_review.completed_net_ids and not state.timed_out: + self._keep_partial_progress(state) return False state.best_results = dict(state.results) state.best_review = review + state.best_pre_pair_candidate = state.pre_pair_candidate return True + def _keep_partial_progress(self, state: _RoutingState) -> None: + candidates = [ + result for net_id, result in state.results.items() + if result.path and not result.reached_target + and (incumbent := state.best_results.get(net_id)) != result + and (incumbent is None or not incumbent.reached_target) + ] + if not candidates: + return + + world = self.context.cost_evaluator.collision_engine + reserved = STRtree([shape for result in state.best_results.values() if can_reserve(result) for shape in result.locked_geometry]) + + def is_clear(result: RoutingResult) -> bool: + return world.verify_path_geometry(result.path).is_valid and not any( + _violates_net_clearance(shape, reserved.geometries[hit], world.clearance) + for shape in result.locked_geometry + for hit in reserved.query(shape, predicate="dwithin", distance=world.clearance) + ) + + for candidate in candidates: + if self._expired(state): + break + net_id = candidate.net_id + incumbent = state.best_results.get(net_id) + if incumbent and incumbent.path: + target = state.net_specs[net_id].target + if ( + _distance_to_terminal(candidate.path[-1].end_port, target) >= _distance_to_terminal(incumbent.path[-1].end_port, target) + and is_clear(incumbent) + ): + continue + if is_clear(candidate): + state.best_results[net_id] = candidate + def _restore_best_iteration(self, state: _RoutingState) -> None: if not state.best_results: return @@ -490,19 +574,29 @@ class PathFinder: def _build_frontier_hotspot_bounds( self, state: _RoutingState, - net_id: str, - details_by_net: dict[str, PathVerificationDetail], + result: RoutingResult, + detail: PathVerificationDetail | None = None, ) -> tuple[tuple[float, float, float, float], ...]: - result = state.results.get(net_id) - detail = details_by_net.get(net_id) - if result is None or detail is None or not result.path: + if not result.report.dynamic_collision_count or self._diagnostics_expired(state): return () + world = self.context.cost_evaluator.collision_engine + if detail is None or not detail.component_conflicts: + with self._scratch_diagnostics(): + detail = world.verify_path_details( + result.net_id, result.path, + capture_component_conflicts=True, + include_invalid_dynamic=False, + geometry_report=result.report, + diagnostic_expired=partial(self._diagnostics_expired, state), + ) hotspot_bounds: list[tuple[float, float, float, float]] = [] seen: set[tuple[float, float, float, float]] = set() - margin = max(5.0, self.context.cost_evaluator.collision_engine.clearance * 2.0) + margin = max(5.0, world.clearance * 2.0) for self_component_index, other_net_id, other_component_index in detail.component_conflicts: + if self._diagnostics_expired(state): + break other_result = state.results.get(other_net_id) if other_result is None or not other_result.path: continue @@ -540,8 +634,8 @@ class PathFinder: return tuple(hotspot_bounds) @contextmanager - def _frontier_replay(self, net_id: str, path: tuple[ComponentResult, ...]) -> Iterator[AStarMetrics]: - """Use scratch counters while replaying a net with its path temporarily removed.""" + def _scratch_diagnostics(self) -> Iterator[AStarMetrics]: + """Isolate the counters of optional geometry checks and frontier replays.""" context = self.context world = context.cost_evaluator.collision_engine danger_map = context.cost_evaluator.danger_map @@ -553,16 +647,22 @@ class PathFinder: if danger_map is not None: danger_map.metrics = scratch_metrics + yield scratch_metrics + finally: + context.metrics, world.metrics = context_metrics, world_metrics + if danger_map is not None: + danger_map.metrics = danger_metrics + + @contextmanager + def _frontier_replay(self, net_id: str, path: tuple[ComponentResult, ...]) -> Iterator[AStarMetrics]: + world = self.context.cost_evaluator.collision_engine + with self._scratch_diagnostics() as scratch_metrics: world.remove_path(net_id) try: yield scratch_metrics finally: if path: self._add_route(net_id, path) - finally: - context.metrics, world.metrics = context_metrics, world_metrics - if danger_map is not None: - danger_map.metrics = danger_metrics def _capture_single_frontier_trace( self, @@ -571,7 +671,7 @@ class PathFinder: result: RoutingResult, hotspot_bounds: tuple[tuple[float, float, float, float], ...], ) -> NetFrontierTrace: - if not hotspot_bounds: + if not hotspot_bounds or self._diagnostics_expired(state): return NetFrontierTrace( net_id=net_id, hotspot_bounds=(), @@ -592,6 +692,7 @@ class PathFinder: frontier_trace=collector, self_collision_check=(net_id in state.needs_self_collision_check), node_limit=self.context.options.search.node_limit, + expired=partial(self._diagnostics_expired, state), ) net = state.net_specs[net_id] @@ -673,7 +774,7 @@ class PathFinder: final_results: dict[str, RoutingResult], details_by_net: dict[str, PathVerificationDetail], ) -> None: - if not self.context.options.diagnostics.capture_frontier_trace: + if not self.context.options.diagnostics.capture_frontier_trace or self._diagnostics_expired(state): return self.frontier_trace = [] @@ -683,10 +784,9 @@ class PathFinder: detail = details_by_net.get(net_id) if result is None or detail is None or not result.reached_target: continue - if detail.report.dynamic_collision_count == 0 or not detail.component_conflicts: - continue - - hotspot_bounds = self._build_frontier_hotspot_bounds(state, net_id, details_by_net) + hotspot_bounds = self._build_frontier_hotspot_bounds(state, result, detail) + if self._diagnostics_expired(state): + break if not hotspot_bounds: continue @@ -752,27 +852,39 @@ class PathFinder: targets.sort(key=lambda pair: min(order_index[pair[0]], order_index[pair[1]])) return targets - def _materialize_pre_pair_frontier_trace( - self, - state: _RoutingState, - results: dict[str, RoutingResult], - details_by_net: dict[str, PathVerificationDetail], - ) -> PrePairFrontierTraceEntry | None: - candidate = state.pre_pair_candidate + def _capture_pre_pair_frontier_trace(self, state: _RoutingState, restored: dict[str, RoutingResult]) -> None: + if self._diagnostics_expired(state): + return + replay = replace(state, results=restored, replay_details=None) + changed = [net_id for net_id in state.ordered_net_ids if restored.get(net_id) != state.results.get(net_id)] + with self._scratch_diagnostics(): + try: + self._replace_indexed_routes(replay, restored, net_ids=changed) + self.pre_pair_frontier_trace = self._materialize_pre_pair_frontier_trace(replay) + finally: + self._replace_indexed_routes(replay, state.results, net_ids=changed) + + def _materialize_pre_pair_frontier_trace(self, state: _RoutingState) -> PrePairFrontierTraceEntry | None: + candidate = state.best_pre_pair_candidate if candidate is None: return None - result_by_net = dict(results) - detail_by_net = dict(details_by_net) nets: list[PrePairNetTrace] = [] attempt_by_net = {attempt.net_id: attempt for attempt in candidate.net_attempts} - for net_id in candidate.routed_net_ids: - attempt = attempt_by_net.get(net_id) - result = result_by_net.get(net_id) - detail = detail_by_net.get(net_id) - if attempt is None or result is None or detail is None or not result.reached_target: + conflict_net_ids = {net_id for edge in candidate.conflict_edges for net_id in edge} + net_ids = dict.fromkeys((*candidate.routed_net_ids, *sorted(conflict_net_ids))) + for net_id in net_ids: + if self._diagnostics_expired(state): + break + result = state.results.get(net_id) + if result is None or not result.reached_target or not result.path: continue - hotspot_bounds = self._build_frontier_hotspot_bounds(state, net_id, detail_by_net) + attempt = attempt_by_net.get(net_id) + if attempt is None: + attempt = net_attempt_trace(net_id, dict.fromkeys(_ATTEMPT_TRACE_TOTALS, 0), reached_target=True, guidance_seed_present=False) + hotspot_bounds = self._build_frontier_hotspot_bounds(state, result) + if self._diagnostics_expired(state): + break nets.append( PrePairNetTrace( net_id=net_id, @@ -800,24 +912,15 @@ class PathFinder: state: _RoutingState, *, iteration: int, - reroute_net_ids: set[str], - routed_net_ids: list[str], attempt_traces: list[IterationNetAttemptTrace], review: _IterationReview, ) -> None: - if ( - len(reroute_net_ids) < len(state.ordered_net_ids) - and review.conflict_edges - and all_results_reached_target(state.ordered_net_ids, state.results) - ): - state.pre_pair_candidate = _PrePairCandidate( - iteration=iteration, - routed_net_ids=tuple(routed_net_ids), - conflict_edges=tuple(sorted(review.conflict_edges)), - net_attempts=tuple(attempt_traces), - ) - return - state.pre_pair_candidate = None + state.pre_pair_candidate = _PrePairCandidate( + iteration=iteration, + routed_net_ids=tuple(attempt.net_id for attempt in attempt_traces), + conflict_edges=tuple(sorted(review.conflict_edges)), + net_attempts=tuple(attempt_traces), + ) if review.conflict_edges else None def _apply_pair_local_candidate( self, @@ -861,7 +964,7 @@ class PathFinder: if self._expired(state): break self.metrics.total_pair_local_search_attempts += 1 - candidate = search_pair_candidate( + replacements, nodes_expanded = search_pair_candidate( self.context, ordered_nets, incumbent_results, @@ -869,10 +972,10 @@ class PathFinder: needs_self_collision_check=state.needs_self_collision_check, expired=partial(self._expired, state), ) - if candidate is None: - continue - replacements, nodes_expanded = candidate self.metrics.total_pair_local_search_nodes_expanded += nodes_expanded + self.metrics.total_nodes_expanded += nodes_expanded + if replacements is None: + continue accepted, next_review = self._apply_pair_local_candidate( state, replacements, @@ -911,6 +1014,10 @@ class PathFinder: world = self.context.cost_evaluator.collision_engine net = state.net_specs[net_id] self.metrics.total_nets_routed += 1 + if iteration == 0 and state.replay_details is not None: + self.metrics.total_warm_start_paths_used += 1 + self.metrics.total_nets_reached_target += 1 + return state.results[net_id], False if node_limit_override is not None: self.metrics.total_late_phase_capped_nets += 1 world.remove_path(net_id) @@ -952,7 +1059,9 @@ class PathFinder: if node_limit_override is not None and can_reserve(incumbent_fallback): return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present) + alternate = self._recover_corridor(state, net_id) if iteration and self._shared_guide_blocked(state, net_id) else None corridors = state.corridors.get(net_id, ()) + corridor = alternate if alternate is not None else (corridors[iteration] if iteration < len(corridors) else None) run_config = SearchRunConfig.from_options( self.context.options, bend_collision_type=coll_model, @@ -964,7 +1073,7 @@ class PathFinder: skip_congestion=skip_congestion, self_collision_check=(net_id in state.needs_self_collision_check), node_limit=search.node_limit if node_limit_override is None else node_limit_override, - corridor=corridors[iteration] if iteration < len(corridors) else None, + corridor=corridor, corridor_strength=self.context.options.topology.guide_strength / (iteration + 1), hard_congestion=bool(state.corridors) and iteration == 0, expired=partial(self._expired, state), @@ -1090,8 +1199,6 @@ class PathFinder: self._update_pre_pair_candidate( state, iteration=trace_iteration, - reroute_net_ids=reroute_net_ids, - routed_net_ids=routed_net_ids, attempt_traces=attempt_traces, review=review, ) @@ -1109,15 +1216,18 @@ class PathFinder: def _reverify_iteration_results(self, state: _RoutingState) -> _IterationReview: diagnostics = self.context.options.diagnostics replay = self.context.options.search.node_limit == 0 and not state.timed_out - capture_conflicts = diagnostics.capture_conflict_trace or ( - replay and (diagnostics.capture_frontier_trace or diagnostics.capture_pre_pair_frontier_trace) - ) - state.results, details_by_net, review = self._analyze_results( - state.ordered_net_ids, - state.results, - capture_component_conflicts=capture_conflicts, - count_iteration_metrics=True, - ) + details_by_net = state.replay_details + if details_by_net is None: + state.results, details_by_net, review = self._analyze_results( + state.ordered_net_ids, + state.results, + capture_component_conflicts=diagnostics.capture_conflict_trace, + count_iteration_metrics=True, + ) + else: + self.metrics.total_iteration_reverify_calls += 1 + self.metrics.total_iteration_reverified_nets += len(details_by_net) + review = review_verified_results(state.results, details_by_net) if replay: # Replay has one iteration. These details describe the whole indexed layout. state.replay_details = details_by_net @@ -1162,13 +1272,12 @@ class PathFinder: reroute_net_ids = next_reroute_net_ids( state.ordered_net_ids, review, all_reached_target=all_reached, has_corridors=bool(state.corridors) ) - if reached_pair_local_plateau(improved=improved, all_reached_target=all_reached, best_conflict_edges=state.best_conflict_edges): - return False - - edge_count = len(review.conflict_edges) - state.repeated_conflict_count = repeated_conflict_count(edge_count, state.last_conflict_edge_count, state.repeated_conflict_count) - state.last_conflict_edge_count = edge_count - if state.repeated_conflict_count >= 2: + if ( + not improved and self.context.options.search.node_limit and state.best_review is not None + and 0 < len(state.best_review.conflict_edges) <= 2 + and all_results_reached_target(state.ordered_net_ids, state.best_results) + and self._collect_pair_local_targets(state, state.best_results, state.best_review) + ): return False self.context.congestion_penalty *= congestion.multiplier return False @@ -1196,12 +1305,13 @@ class PathFinder: net = state.net_specs[net_id] self.metrics.total_refine_path_calls += 1 world.remove_path(net_id) - refined_path = tuple(self.refiner.refine_path(net_id, net.start, net.width, result.path)) + refined_path = tuple(self.refiner.refine_path(net_id, net.start, net.width, result.path, expired=partial(self._expired, state))) self._add_route(net_id, refined_path) report = result.report - if replay and refined_path != result.path: + if refined_path != result.path: state.replay_details = None - report = world.verify_path_geometry(refined_path) + if replay: + report = world.verify_path_geometry(refined_path) state.results[net_id] = RoutingResult( net_id=net_id, path=refined_path, @@ -1227,11 +1337,10 @@ class PathFinder: continue detail = replay_details.get(net.net_id) if detail is None: - capture_conflicts = diagnostics.capture_conflict_trace or (diagnostics.capture_frontier_trace and result.reached_target) detail = self.context.cost_evaluator.collision_engine.verify_path_details( net.net_id, result.path, - capture_component_conflicts=capture_conflicts, + capture_component_conflicts=diagnostics.capture_conflict_trace, include_invalid_dynamic=False, geometry_report=result.report if replay and result.reached_target else None, ) @@ -1281,6 +1390,10 @@ class PathFinder: state = self._prepare_state(corridors, started_at=started_at) replay = self.context.options.search.node_limit == 0 timed_out = self._run_iterations(state, None if replay else iteration_callback) + if self.topology_report is not None and state.corridors: + self.topology_report = replace( + self.topology_report, corridor_counts=tuple((net_id, len(candidates)) for net_id, candidates in state.corridors.items()), + ) self.accumulated_expanded_nodes = list(state.accumulated_expanded_nodes) # A partial iteration can leave the index out of sync with the saved results. best_is_live = not timed_out and state.best_is_indexed @@ -1288,20 +1401,30 @@ class PathFinder: self._restore_best_iteration(state) diagnostics = self.context.options.diagnostics - capture_restored = diagnostics.capture_conflict_trace or diagnostics.capture_pre_pair_frontier_trace + capture_restored = diagnostics.capture_conflict_trace + pre_pair_layout = None if not timed_out or capture_restored: review = state.best_review if best_is_live and not capture_restored else None if review is None: review = self._review_restored_best(state) - if not timed_out: + if not timed_out and not self._expired(state): + if ( + diagnostics.capture_pre_pair_frontier_trace and state.best_pre_pair_candidate is not None + and self._collect_pair_local_targets(state, state.results, review) + ): + pre_pair_layout = dict(state.results) self._run_pair_local_search(state, review) if not timed_out and not self._expired(state): with phase_timer("refine") if phase_timer is not None and self.context.options.refinement.enabled else nullcontext(): self._refine_results(state) with phase_timer("verify") if phase_timer is not None else nullcontext(): final_results, details_by_net = self._verify_results(state) - if not self._expired(state): - self._capture_frontier_trace(state, final_results, details_by_net) + timed_out = timed_out or self._expired(state) if replay and iteration_callback is not None and not timed_out and self.metrics.total_route_iterations: iteration_callback(self.iteration_offset, {net_id: final_results[net_id] for net_id in state.ordered_net_ids}) + if not timed_out and (pre_pair_layout is not None or diagnostics.capture_frontier_trace): + with phase_timer("verify") if phase_timer is not None else nullcontext(): + if pre_pair_layout is not None: + self._capture_pre_pair_frontier_trace(state, pre_pair_layout) + self._capture_frontier_trace(state, final_results, details_by_net) return final_results diff --git a/inire/router/_routing_policy.py b/inire/router/_routing_policy.py index e05865b..2459584 100644 --- a/inire/router/_routing_policy.py +++ b/inire/router/_routing_policy.py @@ -132,19 +132,31 @@ def _disconnected_nets( for net in residual: by_width.setdefault(net.width, []).append(net) - disconnected = set() - for width, nets in by_width.items(): + def free_regions(width: float) -> tuple[Polygon, ...]: # Allow the whole board to centerlines, including flush ports. Rounded # buffers and a small under-dilation keep this test optimistic. padding = max(0.0, problem.clearance + width / 2 - max(problem.safety_zone_radius, TOLERANCE_LINEAR)) forbidden = shapely.union_all([shape.buffer(padding) for shape in obstacles]) regions = tuple(region for region in shapely.get_parts(board.difference(forbidden)) if region.area > 0) - if len(regions) < 2: - continue for region in regions: shapely.prepare(region) + return regions + + widest = max(by_width) + shared_regions = free_regions(widest) + disconnected = set() + for width, nets in by_width.items(): + if width == widest and len(shared_regions) < 2: + continue + regions = shared_regions if width == widest else None for net in nets: start, target = Point(net.start.x, net.start.y), Point(net.target.x, net.target.y) + if width != widest and any(region.covers(start) and region.covers(target) for region in shared_regions): + continue + if regions is None: + regions = free_regions(width) + if len(regions) < 2: + break start_regions = {idx for idx, region in enumerate(regions) if region.covers(start)} target_regions = {idx for idx, region in enumerate(regions) if region.covers(target)} if start_regions and target_regions and start_regions.isdisjoint(target_regions): diff --git a/inire/router/_stack.py b/inire/router/_stack.py index e5ec67b..4463f54 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -30,7 +30,7 @@ class RoutingStack: def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> RoutingStack: - if options.topology.mode == "bundle": + if options.topology.mode == "bundle" and options.congestion.max_iterations: from inire.router._bundle import plan_ordered_bundle # noqa: PLC0415 problem = plan_ordered_bundle(problem, options.search, infer_terminal_headings=options.topology.infer_terminal_headings) @@ -95,7 +95,7 @@ def route_once( iteration_callback=callback, phase_timer=phase_timer, corridors=corridors, started_at=started_at, iteration_offset=iteration_offset, ) results = attach_effective(results) - if options.topology.mode == "bundle": + if options.topology.mode == "bundle" and options.congestion.max_iterations: for result in results.values(): if not result.is_valid: raise ValueError(f"Bundle schedule failed geometric verification for {result.net_id}") diff --git a/inire/router/_topology.py b/inire/router/_topology.py index 663f5c9..48d6867 100644 --- a/inire/router/_topology.py +++ b/inire/router/_topology.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass, field +from functools import cache, partial from heapq import heappop, heappush from itertools import pairwise from math import hypot, inf @@ -14,9 +15,10 @@ from shapely.geometry import LineString, Point, box from inire.constants import TOLERANCE_LINEAR from inire.geometry.collision import _violates_clearance from inire.geometry.index_helpers import is_axis_aligned_rect +from inire.geometry.primitives import port_local_coordinates if TYPE_CHECKING: - from collections.abc import Iterable, Sequence + from collections.abc import Callable, Iterable, Sequence from shapely.geometry import Polygon from shapely.geometry.base import BaseGeometry @@ -69,6 +71,12 @@ class Corridor: return sorted(candidates, key=lambda xy: xy[0] + abs(xy[1]))[:4] +@dataclass(frozen=True, slots=True) +class DeferredCorridor: + bounds: tuple[float, float, float, float] + recover: Callable[[], Corridor | None] + + @dataclass(frozen=True, slots=True) class _Portal: lanes: tuple[XY, ...] @@ -379,6 +387,7 @@ def plan_corridors( clearance: float, bend_radius: float, limit: int, + deferred: dict[str, DeferredCorridor] | None = None, ) -> dict[str, tuple[Corridor, ...]]: """Plan clearance-aware corridor guides for the requested nets.""" if not nets: @@ -395,22 +404,70 @@ def plan_corridors( widest = max(net.width for net in nets) guides, shared_space = plan_group(nets, widest) - # Keep shared assignments and add routes through passages opened by the narrower margin. + if all(net.width == widest for net in nets) and len(guides) == len(nets): + return guides + + pitch = max(1.0, widest + clearance) + turn_room = max(bend_radius, pitch) + + def shared_straight(net: NetSpec) -> LineString | None: + forward, side = port_local_coordinates(net.start, net.target.x, net.target.y) + if net.start.r != net.target.r or side or forward <= 0: + return None + direct = LineString(((net.start.x, net.start.y), (net.target.x, net.target.y))) + return direct if shared_space.covers(direct) else None + + def shared_guide_space(net: NetSpec) -> tuple[float, float, float, float] | None: + shared = guides.get(net.net_id) + if not shared: + return None + x0, x1 = sorted((net.start.x, net.target.x)) + y0, y1 = sorted((net.start.y, net.target.y)) + direct = shared_straight(net) + if direct is None: + # Allow room for approaching both port headings in the shared mesh. + # Nets close to a wall or board edge still get width-specific alternatives. + bounds = (x0 - turn_room, y0 - turn_room, x1 + turn_room, y1 + turn_room) + return bounds if shared_space.covers(box(*bounds)) else None + first, *rest = shared + if not first.footprint.covers(direct): + footprint = direct.buffer(pitch + net.width / 2).intersection(board) + shapely.prepare(footprint) + guides[net.net_id] = (first, Corridor(direct, footprint, turn_room), *rest)[:limit] + gap = net.width / 2 + clearance + return (x0 - gap, y0 - gap, x1 + gap, y1 + gap) + by_width: dict[float, list[NetSpec]] = {} for net in nets: by_width.setdefault(net.width, []).append(net) + + @cache + def width_guides(width: float) -> dict[str, tuple[Corridor, ...]]: + return plan_group(by_width[width], width)[0] + + def narrower_alternate(net_id: str, width: float) -> Corridor | None: + return next( + (c for c in width_guides(width).get(net_id, ()) if c.centerline.difference(shared_space).length > widest + 2 * clearance), + None, + ) + + # Keep shared assignments and add routes through passages opened by the narrower margin. + shapely.prepare(shared_space) for width, group in by_width.items(): if width < widest: - narrow, _ = plan_group(group, width) - for net_id, corridors in narrow.items(): - if net_id not in guides: - guides[net_id] = corridors + for net in group: + net_id = net.net_id + if limit == 1 and net_id in guides: continue - alternate = next( - (c for c in corridors if c.centerline.difference(shared_space).length > widest + 2 * clearance), - None, - ) - if alternate is not None: + if (shared_bounds := shared_guide_space(net)) is not None: + if deferred is not None: + deferred[net_id] = DeferredCorridor(shared_bounds, partial(narrower_alternate, net_id, width)) + continue + if net_id not in guides: + if corridors := width_guides(width).get(net_id): + guides[net_id] = corridors + continue + if alternate := narrower_alternate(net_id, width): first, *rest = guides[net_id] guides[net_id] = (first, alternate, *rest)[:limit] missing = [net for net in group if net.net_id not in guides] diff --git a/inire/router/refiner.py b/inire/router/refiner.py index 761ff5d..87ea5b1 100644 --- a/inire/router/refiner.py +++ b/inire/router/refiner.py @@ -19,7 +19,7 @@ from inire.geometry.primitives import port_local_coordinates from inire.model import resolve_bend_geometry if TYPE_CHECKING: - from collections.abc import Iterator, Sequence + from collections.abc import Callable, Iterator, Sequence from inire.geometry.collision import RoutingWorld from inire.geometry.components import ComponentResult, MoveKind @@ -360,6 +360,8 @@ class PathRefiner: end_idx: int, best_cost: float, incumbent_valid: bool, + *, + expired: Callable[[], bool] | None = None, ) -> tuple[list[ComponentResult], float] | None: ports = self._path_ports(start, path) window_start = ports[start_idx] @@ -377,10 +379,14 @@ class PathRefiner: custom_danger_map = self.context.cost_evaluator.danger_map if isinstance(physical, Polygon) else None components: dict[tuple[Port, MoveKind, tuple], ComponentResult] = {} for radius in search.bend_radii: + if expired is not None and expired(): + break if circular_bend and not bend_fits_width(radius, net_width): continue side_extents = self._candidate_side_extents(window_start, window_end, window_path, net_width, radius) for side_extent in dict.fromkeys(map(round, side_extents)): + if expired is not None and expired(): + return (best_path, best_candidate_cost) if best_path is not None else None moves = self._dogleg_moves(window_start, window_end, radius, side_extent) if moves is None: continue @@ -426,8 +432,10 @@ class PathRefiner: start: Port, net_width: float, path: Sequence[ComponentResult], + *, + expired: Callable[[], bool] | None = None, ) -> list[ComponentResult]: - if not self.has_refinement_bends(path): + if not self.has_refinement_bends(path) or (expired is not None and expired()): return list(path) best_path = list(path) @@ -438,12 +446,16 @@ class PathRefiner: for _ in range(3): improved = False for start_idx, end_idx in self._iter_refinement_windows(start, best_path): + if expired is not None and expired(): + return best_path if incumbent_valid is None: incumbent_valid = self.collision_engine.verify_path_report(net_id, best_path).is_valid if remaining is not None: remaining -= 1 self.context.metrics.total_refinement_windows_considered += 1 - refined = self._try_refine_window(net_id, start, net_width, best_path, start_idx, end_idx, best_cost, incumbent_valid) + refined = self._try_refine_window( + net_id, start, net_width, best_path, start_idx, end_idx, best_cost, incumbent_valid, expired=expired, + ) if refined is not None: best_path, best_cost = refined incumbent_valid = True diff --git a/inire/router/visibility.py b/inire/router/visibility.py index 3cd1ca4..9744706 100644 --- a/inire/router/visibility.py +++ b/inire/router/visibility.py @@ -67,7 +67,8 @@ class VisibilityManager: return seen = set() - for x, y in raw_corners: + for point in raw_corners: + x, y = point[0], point[1] sx, sy = round(x, 3), round(y, 3) if (sx, sy) not in seen: seen.add((sx, sy)) diff --git a/inire/tests/example_scenarios.py b/inire/tests/example_scenarios.py index aa94f4d..692dcd9 100644 --- a/inire/tests/example_scenarios.py +++ b/inire/tests/example_scenarios.py @@ -28,7 +28,7 @@ from inire.tests.routing_corpus import SNAPSHOT_CASES, profile_options from inire.tests.terminal_bench_scenario import terminal_bench_options, terminal_bench_problem if TYPE_CHECKING: - from collections.abc import Iterable + from collections.abc import Collection, Iterable from inire.router._astar_types import AStarMetrics from inire.router._router import PathFinder @@ -498,9 +498,19 @@ def capture_scenario_snapshots( selected_scenarios: Iterable[str] | None = None, *, include_performance_only: bool = False, + baseline_scenarios: Collection[str] = (), ) -> tuple[ScenarioSnapshot, ...]: + allowed = None if selected_scenarios is None else set(selected_scenarios) + if allowed is not None: + regular = dict(SCENARIO_SNAPSHOTS) + performance_only = dict(PERFORMANCE_SCENARIO_SNAPSHOTS) + unknown = allowed.difference(regular, performance_only, baseline_scenarios) + if unknown: + raise ValueError(f"Unknown performance scenario(s): {', '.join(sorted(unknown))}") + disabled = allowed.intersection(performance_only).difference(regular) + if disabled and not include_performance_only: + raise ValueError(f"Scenario(s) require --include-performance-only: {', '.join(sorted(disabled))}") registry = SCENARIO_SNAPSHOTS if include_performance_only: registry += PERFORMANCE_SCENARIO_SNAPSHOTS - allowed = None if selected_scenarios is None else set(selected_scenarios) return tuple(capture() for name, capture in registry if allowed is None or name in allowed) diff --git a/inire/tests/routing_expanded_benchmarks.py b/inire/tests/routing_expanded_benchmarks.py index 6337859..39d4c9e 100644 --- a/inire/tests/routing_expanded_benchmarks.py +++ b/inire/tests/routing_expanded_benchmarks.py @@ -71,7 +71,7 @@ def _on_grid(case: BenchmarkCase, grid_nm: int) -> BenchmarkCase: objective=replace( options.objective, bend_penalty=options.objective.bend_penalty * factor**1.5, - sbend_penalty=options.objective.sbend_penalty * factor**1.5, + sbend_penalty=options.objective.sbend_penalty * factor, ), congestion=replace(options.congestion, base_penalty=options.congestion.base_penalty * factor), ) diff --git a/inire/tests/routing_external_benchmarks.py b/inire/tests/routing_external_benchmarks.py index 77ae861..5028b0d 100644 --- a/inire/tests/routing_external_benchmarks.py +++ b/inire/tests/routing_external_benchmarks.py @@ -13,7 +13,9 @@ from inire.tests.routing_benchmark_case import BenchmarkCase, benchmark_options def _external_benchmarks() -> tuple[BenchmarkCase, ...]: fixture = Path(__file__).with_name("data") / "external_routing_benchmarks.json" cases = [] - for row in loads(fixture.read_text(encoding="utf-8"))["cases"]: + payload = loads(fixture.read_text(encoding="utf-8")) + grid_nm = 1000 // payload["units_per_micron"] + for row in payload["cases"]: problem = RoutingProblem( tuple(row["bounds"]), tuple(NetSpec(net["id"], Port(*net["start"]), Port(*net["target"]), width=net["width"]) for net in row["nets"]), @@ -32,6 +34,7 @@ def _external_benchmarks() -> tuple[BenchmarkCase, ...]: problem, options, expected_routed=row.get("expected_routed"), + grid_nm=grid_nm, )) return tuple(cases) diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 6cbb8a1..c9affbc 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -35,7 +35,7 @@ from inire.geometry.collision import RoutingWorld from inire.results import ComponentConflictTrace, RoutingReport, RoutingResult from inire.router._astar_types import AStarContext from inire.router._router import PathFinder, _IterationReview -from inire.router._stack import RoutingAttempts +from inire.router._stack import RoutingAttempts, build_routing_stack from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap @@ -956,7 +956,7 @@ def test_default_router_escalates_only_within_the_configured_node_limit(monkeypa assert run.results_by_net["turn"].is_valid == (ceiling > 500) -def test_capture_frontier_trace_preserves_route_outputs() -> None: +def test_capture_frontier_trace_preserves_route_outputs(monkeypatch: pytest.MonkeyPatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( @@ -981,6 +981,117 @@ def test_capture_frontier_trace_preserves_route_outputs() -> None: assert {trace.net_id for trace in run_with_trace.frontier_trace} == {"horizontal", "vertical"} assert run_with_trace.metrics.verify_path_report_calls == run_without_trace.metrics.verify_path_report_calls + search = replace(base_options.search, node_limit=60, bend_radii=(), sbend_radii=()) + options = replace(base_options, search=search, diagnostics=DiagnosticsOptions(capture_frontier_trace=True)) + control = route(problem, options=options) + clock = [0.0] + monkeypatch.setattr(router_module.time, "monotonic", lambda: clock[0]) + route_astar = router_module.route_astar + diagnostic_work = [] + + def expire_in_frontier(*args, config, metrics, **kwargs): + if config.frontier_trace is None: + return route_astar(*args, config=config, metrics=metrics, **kwargs) + clock[0] = 61.0 + path = route_astar(*args, config=config, metrics=metrics, **kwargs) + diagnostic_work.append(metrics.total_nodes_expanded) + return path + + monkeypatch.setattr(router_module, "route_astar", expire_in_frontier) + expired = route(problem, options=options) + assert diagnostic_work == [0] + assert expired.metrics.timeout_events == 0 + assert expired.metrics.diagnostic_timeout_events == 1 + assert expired.metrics.nodes_expanded == control.metrics.nodes_expanded + assert expired.results_by_net == control.results_by_net + + clock[0] = 0.0 + callback_times = [] + detail_calls = [] + verify_details = RoutingWorld.verify_path_details + + def expire_during_component_details(self, net_id, path, **kwargs): + if kwargs.get("capture_component_conflicts"): + detail_calls.append(net_id) + clock[0] = 61.0 + return verify_details(self, net_id, path, **kwargs) + + monkeypatch.setattr(RoutingWorld, "verify_path_details", expire_during_component_details) + replay = route( + problem, options=replace(options, search=base_options.search), + iteration_callback=lambda index, _: callback_times.append((index, clock[0])), + ) + assert callback_times == [(0, 0.0)] + assert len(detail_calls) == 1 + assert replay.metrics.timeout_events == 0 + assert replay.metrics.diagnostic_timeout_events == 1 + assert replay.results_by_net == run_without_trace.results_by_net + + +def test_pre_pair_trace_uses_restored_layout_after_repair(monkeypatch: pytest.MonkeyPatch) -> None: + nets = ( + NetSpec("horizontal", Port(40, 100, 0), Port(160, 100, 0)), + NetSpec("vertical", Port(100, 40, 90), Port(100, 160, 90)), + ) + seeds = {net.net_id: PathSeed((StraightSeed(120),)) for net in nets} + problem = RoutingProblem((0, 0, 200, 200), nets, clearance=1, initial_paths=seeds) + options = RoutingOptions( + search=SearchOptions(node_limit=3000, bend_radii=(10,), sbend_radii=()), + objective=ObjectiveWeights(danger_weight=0), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + topology=TopologyOptions(mode="off"), + ) + control = route(problem, options=options) + assert all(result.is_valid for result in control.results_by_net.values()) + assert control.metrics.pair_local_search_accepts == 1 + clock = [0.0] + monkeypatch.setattr(router_module.time, "monotonic", lambda: clock[0]) + capture = PathFinder._capture_single_frontier_trace + replayed = [] + + def expire_in_pre_pair(self, state, net_id, result, hotspot_bounds): + if hotspot_bounds: + assert self.metrics.total_pair_local_search_accepts == 1 + assert result.as_seed() == seeds[net_id] + assert all(state.results[key].as_seed() == seed for key, seed in seeds.items()) + replayed.append(net_id) + clock[0] = 61.0 + return capture(self, state, net_id, result, hotspot_bounds) + + monkeypatch.setattr(PathFinder, "_capture_single_frontier_trace", expire_in_pre_pair) + traced = replace(options, diagnostics=DiagnosticsOptions(capture_pre_pair_frontier_trace=True)) + stack = build_routing_stack(problem, traced) + results = stack.finder.route_all() + metrics = stack.finder.metrics.snapshot() + assert len(replayed) == 1 + assert results == control.results_by_net + assert metrics.nodes_expanded == control.metrics.nodes_expanded + assert metrics.pair_local_search_attempts == control.metrics.pair_local_search_attempts + assert metrics.dynamic_path_objects_added == control.metrics.dynamic_path_objects_added + assert metrics.dynamic_path_objects_removed == control.metrics.dynamic_path_objects_removed + assert metrics.timeout_events == 0 + assert metrics.diagnostic_timeout_events == 1 + assert all(stack.world.verify_path_report(key, result.path).is_valid for key, result in results.items()) + + clock[0] = 0.0 + verified = [] + verify_details = RoutingWorld.verify_path_details + + def expire_during_pre_pair_details(self, net_id, path, **kwargs): + if kwargs.get("capture_component_conflicts"): + verified.append(net_id) + clock[0] = 61.0 + return verify_details(self, net_id, path, **kwargs) + + monkeypatch.setattr(RoutingWorld, "verify_path_details", expire_during_pre_pair_details) + expired = route(problem, options=traced) + assert len(verified) == 1 + assert len(replayed) == 1 + assert expired.results_by_net == control.results_by_net + assert expired.metrics.timeout_events == 0 + assert expired.metrics.diagnostic_timeout_events == 1 + def test_reverify_iterations_limit_late_reroutes_to_conflicting_nets(monkeypatch: pytest.MonkeyPatch) -> None: problem = RoutingProblem( @@ -1097,8 +1208,8 @@ def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch) -> attempted.append(pair_order) assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds if pair_order == ("a", "b"): - return {"a": RoutingResult("a", incumbent["b"].path, reached_target=True), "b": incumbent["b"]}, 0 - return None + return {"a": RoutingResult("a", incumbent["b"].path, reached_target=True), "b": incumbent["b"]}, 3 + return None, 5 monkeypatch.setattr(router_module, "search_pair_candidate", search) assert finder._run_pair_local_target(state, ("a", "b"), review) is review @@ -1108,6 +1219,7 @@ def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch) -> assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds assert all(world.verify_path_report(net_id, result.path) == result.report for net_id, result in incumbent.items()) metrics = finder.metrics.snapshot() + assert metrics.nodes_expanded == metrics.pair_local_search_nodes_expanded == 8 assert metrics.dynamic_path_objects_added == 7 assert metrics.dynamic_path_objects_removed == 4 @@ -1157,6 +1269,28 @@ def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pyte assert evaluator.collision_engine.has_dynamic_paths() +def test_equal_rank_keeps_clear_partial_progress_and_completed_geometry() -> None: + problem = RoutingProblem( + (0, 0, 100, 100), + (NetSpec("line", Port(10, 25, 0), Port(90, 25, 0)), NetSpec("peer", Port(50, 15, 90), Port(50, 40, 90))), + (box(70, 24, 72, 26),), + ) + finder = build_routing_stack(problem, RoutingOptions(topology=TopologyOptions(mode="off"))).finder + state = finder._prepare_state() + peer = RoutingResult("peer", (Straight.generate(problem.nets[1].start, 25, 2),), reached_target=True) + review = _IterationReview(set(), set(), {"peer"}, 0) + state.results = {"peer": peer, "line": RoutingResult("line", ())} + assert finder._update_best_iteration(state, review) + for length, saved_length in ((20, 20), (30, 30), (45, 30), (70, 30), (10, 30)): + state.results = { + "peer": replace(peer, path=(Straight.generate(Port(85, 15, 90), 25, 2),)), + "line": RoutingResult("line", (Straight.generate(problem.nets[0].start, length, 2),)), + } + assert not finder._update_best_iteration(state, review) + assert state.best_results["line"].path[-1].length == saved_length + assert state.best_results["peer"] is peer + + def test_iteration_prefers_shorter_paths_at_equal_coverage() -> None: problem = RoutingProblem(bounds=(0, 0, 100, 100)) options = RoutingOptions(topology=TopologyOptions(mode="off")) diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index 8569235..bc98869 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -7,7 +7,7 @@ from shapely.geometry import Polygon, box import inire.geometry.component_overlap as overlap_module from inire.geometry.collision import RoutingWorld -from inire.geometry.components import ComponentResult +from inire.geometry.components import Bend90, ComponentResult from inire.geometry.components import Straight from inire.geometry.primitives import Port from inire.model import RoutingProblem @@ -329,3 +329,16 @@ def test_move_admission_rejects_keepout_overlap_near_an_endpoint() -> None: assert engine.terminal_issue(move.start_port, 2) is None assert engine.check_move_static(move) assert engine.verify_path_report("line", (move,)).static_collision_count == 1 + + +def test_bend_admission_checks_the_outline_outside_the_proxy() -> None: + for proxy, margin in (("arc", None), ("clipped_bbox", 5), (box(0, -1, 1, 0), None)): + bend = Bend90.generate(Port(0, 0, 0), 10, 2, "CCW", collision_type=proxy, clip_margin=margin).translate(70, 20) + world = RoutingWorld(clearance=1) + hit = world.add_static_obstacle(box(77.3, 22.3, 77.7, 22.7)) + assert world.check_move_static(bend) + assert world.verify_path_report("bend", (bend,)).static_collision_count == 1 + world.remove_static_obstacle(hit) + world.add_static_obstacle(box(82, 27, 84, 32)) + assert not world.check_move_static(bend) + assert world.verify_path_report("bend", (bend,)).is_valid diff --git a/inire/tests/test_congestion_policy.py b/inire/tests/test_congestion_policy.py index 71b8d3a..6eb6752 100644 --- a/inire/tests/test_congestion_policy.py +++ b/inire/tests/test_congestion_policy.py @@ -6,8 +6,6 @@ from inire.router._congestion_policy import ( IterationReview, next_reroute_net_ids, ordered_nets, - reached_pair_local_plateau, - repeated_conflict_count, reroute_plan, ) @@ -56,12 +54,3 @@ def test_next_reroute_nets_respect_reached_targets_and_corridors() -> None: assert next_reroute_net_ids(ordered, review, all_reached_target=True, has_corridors=False) == {"a", "b", "c"} assert next_reroute_net_ids(ordered, review, all_reached_target=False, has_corridors=True) == {"a", "b", "c"} assert next_reroute_net_ids(ordered, review, all_reached_target=False, has_corridors=False) == set(ordered) - - -def test_stopping_rules_track_plateau_and_repeated_conflict_count() -> None: - assert reached_pair_local_plateau(improved=False, all_reached_target=True, best_conflict_edges=2) - assert not reached_pair_local_plateau(improved=True, all_reached_target=True, best_conflict_edges=2) - assert not reached_pair_local_plateau(improved=False, all_reached_target=True, best_conflict_edges=3) - assert repeated_conflict_count(2, 2, 1) == 2 - assert repeated_conflict_count(3, 2, 1) == 0 - assert repeated_conflict_count(0, 0, 1) == 0 diff --git a/inire/tests/test_example_performance.py b/inire/tests/test_example_performance.py index eed1355..0c1982b 100644 --- a/inire/tests/test_example_performance.py +++ b/inire/tests/test_example_performance.py @@ -70,7 +70,7 @@ def test_example_07_no_warm_start_outcome_and_optional_runtime() -> None: assert snapshot.metrics.warm_start_paths_used == 0 assert snapshot.metrics.pair_local_search_pairs_considered >= 1 assert snapshot.metrics.pair_local_search_accepts >= 1 - assert snapshot.metrics.pair_local_search_nodes_expanded <= 128 + assert 0 < snapshot.metrics.pair_local_search_nodes_expanded <= 750 assert snapshot.metrics.nodes_expanded <= 2500 assert snapshot.metrics.congestion_check_calls <= 6000 if RUN_PERFORMANCE: diff --git a/inire/tests/test_example_regressions.py b/inire/tests/test_example_regressions.py index 30c768a..2b60419 100644 --- a/inire/tests/test_example_regressions.py +++ b/inire/tests/test_example_regressions.py @@ -22,6 +22,13 @@ def test_example_07_no_warm_start_trace_finishes_without_conflict_edges(example_ assert run.metrics.pair_local_search_pairs_considered >= 1 assert run.metrics.pair_local_search_accepts >= 1 assert run.pre_pair_frontier_trace is not None + restored = next(entry for entry in run.conflict_trace if entry.stage == "restored_best") + pre_pair = run.pre_pair_frontier_trace + attempt = next(entry for entry in run.iteration_trace if entry.iteration == pre_pair.iteration) + assert pre_pair.conflict_edges == restored.conflict_edges + assert pre_pair.routed_net_ids == attempt.routed_net_ids + work = {net.net_id: net.nodes_expanded for net in attempt.net_attempts} + assert all(net.nodes_expanded == work.get(net.net_id, 0) for net in pre_pair.nets) final_entry = run.conflict_trace[-1] assert final_entry.stage == "final" diff --git a/inire/tests/test_performance_reporting.py b/inire/tests/test_performance_reporting.py index 0e74b93..79049c5 100644 --- a/inire/tests/test_performance_reporting.py +++ b/inire/tests/test_performance_reporting.py @@ -31,6 +31,20 @@ def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario( assert [entry["name"] for entry in payload["scenarios"]] == ["example_01_simple_route"] assert (tmp_path / "performance.md").exists() + retired = "example_retired" + baseline_path = tmp_path / "performance_baseline.json" + payload["scenarios"].append({**payload["scenarios"][0], "name": retired}) + baseline_path.write_text(json.dumps(payload)) + saved_files = {path: path.read_bytes() for path in tmp_path.iterdir()} + invalid = subprocess.run( + [sys.executable, str(script_path), "--output-dir", str(tmp_path), + "--scenario", "example_01_simple_route", "--scenario", "example_01_simple_rote"], + capture_output=True, text=True, check=False, + ) + assert invalid.returncode == 2 + assert "Unknown performance scenario(s): example_01_simple_rote" in invalid.stderr + assert {path: path.read_bytes() for path in tmp_path.iterdir()} == saved_files + output = tmp_path / "diff.md" log = tmp_path / "optimization.md" subprocess.run( @@ -44,6 +58,8 @@ def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario( "example_01_simple_route", "--scenario", "example_07_large_scale_routing_no_warm_start", + "--scenario", + retired, "--metric", "duration_s", "--metric", @@ -67,6 +83,7 @@ def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario( assert "| example_01_simple_route | visibility_corner_index_builds |" in report assert "| example_07_large_scale_routing_no_warm_start | duration_s | - |" in report assert "| example_07_large_scale_routing_no_warm_start | nodes_expanded | - |" in report + assert f"| {retired} | missing | - | - | - |" in report entry = log.read_text() assert "Step 0 - Baseline" in entry assert "Tooling smoke test." in entry diff --git a/inire/tests/test_refinements.py b/inire/tests/test_refinements.py index 7fa3cbb..b851d36 100644 --- a/inire/tests/test_refinements.py +++ b/inire/tests/test_refinements.py @@ -3,6 +3,7 @@ from dataclasses import replace import pytest from shapely.geometry import Polygon, box +from inire.router import _router from inire import CongestionOptions, ObjectiveWeights, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route from inire import DiagnosticsOptions, PathSeed, StraightSeed from inire.geometry.collision import RoutingWorld @@ -74,6 +75,26 @@ def test_refinement_handles_both_signs_of_the_lateral_offset() -> None: assert paths[0].report.total_length == pytest.approx(paths[1].report.total_length) +def test_refinement_stops_between_candidates_when_worker_expires(monkeypatch: pytest.MonkeyPatch) -> None: + clock = [0.0] + monkeypatch.setattr(_router.time, "monotonic", lambda: clock[0]) + dogleg_moves = _router.PathRefiner._dogleg_moves + candidates = [] + + def expire_at_first_candidate(*args, **kwargs): + candidates.append(clock[0]) + clock[0] = 61.0 + return dogleg_moves(*args, **kwargs) + + monkeypatch.setattr(_router.PathRefiner, "_dogleg_moves", expire_at_first_candidate) + problem = _seeded_foldback() + options = replace(_REFINEMENT_OPTIONS, refinement=RefinementOptions(max_windows_per_net=None)) + run = route(problem, options=options) + assert candidates == [0.0] + assert run.metrics.timeout_events == run.metrics.refinement_windows_considered == 1 + assert run.results_by_net["foldback"].is_valid + + def test_automatic_refinement_rechecks_retained_partial_paths() -> None: base = _seeded_foldback() blocked = NetSpec("blocked", Port(150, 120, 90), Port(150, 210, 90)) diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index e515565..1732962 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -6,7 +6,8 @@ import pytest from shapely.geometry import box, shape from inire import ( - CongestionOptions, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, RoutingResult, RoutingRunResult, + Bend90Seed, CongestionOptions, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions, RoutingOptions, RoutingProblem, + RoutingResult, RoutingRunResult, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, ) from inire.router import _automatic, _compact @@ -21,6 +22,7 @@ from inire.tests.routing_benchmarks import ( CROSSING_BENCHMARK_CASES, ) from inire.tests.routing_corpus import CASE_GROUPS, automatic_options, profile_options +from inire.tests.routing_expanded_benchmarks import _on_grid from scripts.benchmark_retry_order import _measure as _measure_retry from scripts.compare_topological_routing import ( _direct_trials, @@ -171,9 +173,9 @@ def test_retry_experiment_records_worker_expansions() -> None: sample = _measure_retry(case, "public-defaults", "lattice-500") [attempt] = sample["retry_attempts"] - [stage] = [stage for stage in sample["stages"] if stage["policy"] == "early-bounded-lattice"] + stage_work = sum(stage["nodes_expanded"] for stage in sample["stages"] if stage["policy"] == "early-bounded-lattice") assert attempt["policy"] == "bounded-lattice" - assert 0 < attempt["nodes_expanded"] == stage["nodes_expanded"] <= sample["nodes_expanded"] + assert 0 < attempt["nodes_expanded"] == stage_work <= sample["nodes_expanded"] assert len(sample["verified"]) == case.routing_bound @@ -265,6 +267,24 @@ def test_benchmark_native_cost_uses_configured_proximity_range() -> None: assert wider.native_valid_costs["a"] > default.native_valid_costs["a"] +def test_benchmark_native_cost_scales_with_grid_for_straights_and_bends() -> None: + problem = RoutingProblem((0, 0, 80, 80), (NetSpec("a", Port(10, 10, 0), Port(32, 36, 90)),)) + options = RoutingOptions( + search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=(10,)), + objective=ObjectiveWeights(danger_weight=0), + refinement=RefinementOptions(enabled=False), + ) + seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW"), SBendSeed(8, 10))) + case = BenchmarkCase("grid-cost", "Straight, quarter-turn, and S-bend", problem, options, reference_paths=(("a", seed),)) + normalized = [] + for nm in (1000, 500, 250, 100, 10): + scaled = _on_grid(case, nm) + replay = replace(scaled, problem=replace(scaled.problem, initial_paths=dict(scaled.reference_paths))) + sample = _measure(replay, replay.options, "off") + normalized.append(sample.native_valid_costs["a"] * nm / 1000) + assert normalized == pytest.approx([normalized[0]] * len(normalized)) + + def test_connectivity_screen_checks_each_net_width_and_leaves_unknown_ports_for_search() -> None: problem = RoutingProblem( bounds=(0, 0, 400, 160), diff --git a/inire/tests/test_terminal_bench.py b/inire/tests/test_terminal_bench.py index f22c834..5f52332 100644 --- a/inire/tests/test_terminal_bench.py +++ b/inire/tests/test_terminal_bench.py @@ -7,8 +7,9 @@ from shapely import union_all from shapely.affinity import translate from shapely.geometry import box -from inire import Bend90Seed, DiagnosticsOptions, Port, SBendSeed, TopologyOptions, route +from inire import Bend90Seed, DiagnosticsOptions, PathSeed, Port, SBendSeed, StraightSeed, TopologyOptions, route from inire.constants import TOLERANCE_LINEAR +from inire.router import _bundle, _router from inire.router._waypoints import export_waypoints from inire.tests.terminal_bench_lane_plan import terminal_bench_lane_problem from inire.tests.terminal_bench_scenario import ( @@ -168,3 +169,40 @@ def test_bundle_replays_with_resolved_ports_without_building_a_mesh(monkeypatch: assert result.effective_net == original.effective_net assert result.as_seed() == seeds[key] assert result.locked_geometry == original.locked_geometry + + +def test_automatic_preserves_headings_for_supplied_nonempty_seeds() -> None: + problem = terminal_bench_problem() + options = terminal_bench_options(node_limit=20, max_iterations=1) + options = replace( + options, + topology=TopologyOptions(infer_terminal_headings=True), + congestion=replace(options.congestion, warm_start_enabled=False), + refinement=replace(options.refinement, enabled=False), + ) + for move in (StraightSeed(5), Bend90Seed(1000, "CW")): + run = route(replace(problem, initial_paths={"net_00": PathSeed((move,))}), options=options) + assert all(result.is_valid and result.requested_net == result.effective_net for result in run.results_by_net.values()) + assert run.automatic.selected_planner == "bundle-turnaround" + assert bool(run.results_by_net["net_00"].report.seed_error) == isinstance(move, Bend90Seed) + + empty = route(replace(problem, initial_paths={"net_00": PathSeed(())}), options=options) + assert empty.results_by_net["net_08"].effective_net.target.r == 180 + + +def test_zero_iterations_skip_bundle_planning_and_seed_materialization(monkeypatch: pytest.MonkeyPatch) -> None: + problem = terminal_bench_problem() + seeded = replace(problem, initial_paths={"net_00": PathSeed((StraightSeed(5),))}) + options = terminal_bench_options(node_limit=20, max_iterations=0) + + def fail_if_prepared(*_args, **_kwargs): + pytest.fail("A run with zero iterations prepared routes") + + monkeypatch.setattr(_bundle, "plan_ordered_bundle", fail_if_prepared) + monkeypatch.setattr(_router, "materialize_path_seed", fail_if_prepared) + for mode in ("off", "automatic", "bundle"): + for candidate in (problem, seeded): + run = route(candidate, options=replace(options, topology=TopologyOptions(mode=mode, infer_terminal_headings=True))) + assert run.metrics.route_iterations == run.metrics.nodes_expanded == 0 + assert len(run.results_by_net) == len(problem.nets) + assert all(result.outcome == "unroutable" and result.requested_net == result.effective_net for result in run.results_by_net.values()) diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py index 37521d0..0966df6 100644 --- a/inire/tests/test_topology.py +++ b/inire/tests/test_topology.py @@ -1,12 +1,15 @@ from dataclasses import replace import pytest +import shapely from shapely.geometry import LineString, Polygon, box from inire import ( CongestionOptions, DiagnosticsOptions, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, ) +from inire.geometry.collision import RoutingWorld +from inire.router import _router, _stack from inire.router._stack import build_routing_stack from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_lane_assignments, plan_corridors from inire.tests.routing_benchmark_case import BenchmarkCase @@ -112,7 +115,7 @@ def test_rounded_keepout_guidance_preserves_acute_aperture() -> None: assert route(problem, options=options).results_by_net["opening"].is_valid -def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None: +def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate(monkeypatch: pytest.MonkeyPatch) -> None: mode = 'seed' nets = (NetSpec("a", Port(16, 48, 0), Port(199, 82, 0), 4.5), NetSpec("b", Port(18, 59, 0), Port(197, 93, 0), 1.25)) walls = (box(60, 0, 67, 56.25), box(60, 74.125, 67, 118), box(125, 0, 132, 66.25), box(125, 84.125, 132, 118)) @@ -125,6 +128,21 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None: topology=TopologyOptions(mode=mode), diagnostics=DiagnosticsOptions(capture_iteration_trace=True, capture_conflict_trace=True), ) + unmodified = route(problem, options=options) + assert all(result.is_valid for result in unmodified.results_by_net.values()) + + route_once = _stack.route_once + + def limit_guided_attempt(problem, *, options, **kwargs): + if options.topology.guide_strength: + options = replace( + options, + search=replace(options.search, node_limit=1), + topology=replace(options.topology, seed_node_limit=1), + ) + return route_once(problem, options=options, **kwargs) + + monkeypatch.setattr(_stack, "route_once", limit_guided_attempt) snapshots = [] run = route( problem, options=options, @@ -132,7 +150,7 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None: ) assert all(result.is_valid for result in run.results_by_net.values()) - assert snapshots == [(0, 1), (1, 1), (2, 2)] + assert snapshots == [(0, 0), (1, 0), (2, 2)] assert [(entry.iteration, entry.completed_nets) for entry in run.iteration_trace] == [(2, 2)] assert [entry.iteration for entry in run.conflict_trace if entry.stage == "iteration"] == [2] assert run.conflict_trace[-1].iteration is None @@ -144,6 +162,47 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None: assert [attempt.topology.guide_strength for attempt in sample.attempt_options] == [0.75, 0.0] assert sample.selected_attempt == 1 + clock = [0.0] + capture = _router.PathFinder._capture_frontier_trace + + def expire_after_guided_search(self, state, results, details): + if self.context.options.topology.guide_strength: + clock[0] = state.start_time + state.timeout_s + 1 + return capture(self, state, results, details) + + monkeypatch.setattr(_router.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr(_router.PathFinder, "_capture_frontier_trace", expire_after_guided_search) + traced_options = replace(options, diagnostics=replace(options.diagnostics, capture_frontier_trace=True)) + traced_run = route(problem, options=traced_options) + assert traced_run.results_by_net == run.results_by_net + assert traced_run.iteration_trace == run.iteration_trace + assert traced_run.metrics.route_iterations == run.metrics.route_iterations + assert traced_run.metrics.nodes_expanded == run.metrics.nodes_expanded + assert traced_run.metrics.timeout_events == 0 + assert traced_run.metrics.diagnostic_timeout_events == 1 + + clock[0] = 0.0 + monkeypatch.setattr(_router.PathFinder, "_capture_frontier_trace", capture) + verify_details = RoutingWorld.verify_path_details + + def expire_during_component_details(self, net_id, path, **kwargs): + if kwargs.get("capture_component_conflicts"): + clock[0] = 61.0 + return verify_details(self, net_id, path, **kwargs) + + def limit_guided_before_retry(problem, *, options, **kwargs): + if options.topology.guide_strength: + options = replace(options, search=replace(options.search, node_limit=500), topology=replace(options.topology, seed_node_limit=500)) + return route_once(problem, options=options, **kwargs) + + monkeypatch.setattr(RoutingWorld, "verify_path_details", expire_during_component_details) + monkeypatch.setattr(_stack, "route_once", limit_guided_before_retry) + frontier_only = replace(options, diagnostics=DiagnosticsOptions(capture_frontier_trace=True)) + traced = route(problem, options=frontier_only) + assert traced.results_by_net == run.results_by_net + assert traced.metrics.timeout_events == 0 + assert traced.metrics.route_iterations == 3 + def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytest.MonkeyPatch) -> None: problem = DETOUR.problem @@ -171,7 +230,58 @@ def test_topological_planner_finds_both_sides_of_an_obstacle() -> None: assert crossing_heights[1] >= 437 -def test_seed_mode_respects_user_paths_on_repeated_runs() -> None: +def test_small_offsets_on_a_mixed_width_board_share_the_widest_mesh(monkeypatch: pytest.MonkeyPatch) -> None: + triangulate = shapely.constrained_delaunay_triangles + meshes = [] + + def record_mesh(free): + meshes.append(free) + return triangulate(free) + + monkeypatch.setattr(shapely, "constrained_delaunay_triangles", record_mesh) + nets = tuple(NetSpec(str(i), Port(20, 80 + 15 * i, 0), Port(200, 81 + 15 * i, 0), 2 + i / 10) for i in range(8)) + keepouts = (box(40, 10, 55, 30), box(80, 10, 95, 30)) + guides = plan_corridors((0, 0, 240, 220), keepouts, nets, clearance=2, bend_radius=10, limit=2) + assert guides.keys() == {net.net_id for net in nets} + assert len(meshes) == 1 + + +def test_seed_mode_recovers_a_narrow_guide_after_a_reserved_route_blocks_the_shared_guide(monkeypatch: pytest.MonkeyPatch) -> None: + problem = RoutingProblem( + (0, 0, 240, 200), + (NetSpec("wide", Port(120, 60, 90), Port(120, 139, 90), 24), NetSpec("narrow", Port(40, 100, 0), Port(200, 101, 0), 2)), + (box(110, 17, 130, 59), box(110, 140, 130, 200)), clearance=1, initial_paths={"wide": PathSeed((StraightSeed(79),))}, + ) + options = RoutingOptions( + search=SearchOptions(node_limit=2000, bend_radii=(10,), sbend_radii=(10,), sbend_offsets=(1,)), + congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), + objective=ObjectiveWeights(danger_weight=0, bend_penalty=20, sbend_penalty=20), + refinement=RefinementOptions(enabled=False), + topology=TopologyOptions(mode="seed", max_corridors=3, seed_node_limit=2000), + ) + triangulate = shapely.constrained_delaunay_triangles + route_astar = _router.route_astar + events = [] + + def record_mesh(free): + events.append("mesh") + return triangulate(free) + + def record_search(*args, config, **kwargs): + if config.restrict_to_corridor: + events.append("seed") + return route_astar(*args, config=config, **kwargs) + + monkeypatch.setattr(shapely, "constrained_delaunay_triangles", record_mesh) + monkeypatch.setattr(_router, "route_astar", record_search) + run = route(problem, options=options) + assert all(result.is_valid for result in run.results_by_net.values()) + assert run.results_by_net["wide"].as_seed() == problem.initial_paths["wide"] + assert run.topology.seeded_net_ids == ("narrow",) + assert dict(run.topology.corridor_counts)["narrow"] == 2 + assert events[-3:] == ["seed", "mesh", "seed"] + +def test_seed_mode_respects_user_paths_on_repeated_runs(monkeypatch: pytest.MonkeyPatch) -> None: existing = PathSeed((StraightSeed(140),)) problem = RoutingProblem( bounds=(0, 0, 180, 100), @@ -190,6 +300,22 @@ def test_seed_mode_respects_user_paths_on_repeated_runs() -> None: assert stack.finder.topology_report.seeded_net_ids == ("new",) assert list(stack.world.iter_static_dilated_geometries()) == [] + completed = replace(problem, initial_paths={"existing": existing, "new": existing}) + + def fail_on_mesh(*_args, **_kwargs): + pytest.fail("Complete verified seeds should skip corridor planning") + + monkeypatch.setattr("inire.router._topology.plan_corridors", fail_on_mesh) + for mode in ("guide", "seed"): + callbacks = [] + run = route( + completed, options=RoutingOptions(topology=TopologyOptions(mode=mode)), + iteration_callback=lambda index, results, callbacks=callbacks: callbacks.append((index, results)), + ) + assert run.metrics.nodes_expanded == 0 + assert [(index, all(result.is_valid for result in results.values())) for index, results in callbacks] == [(0, True)] + assert all(result.is_valid and result.as_seed() == existing for result in run.results_by_net.values()) + def test_narrow_net_recovers_corridors_with_a_wide_peer() -> None: mode = 'seed' diff --git a/inire/tests/test_visibility.py b/inire/tests/test_visibility.py index a2cbd2f..b301c9e 100644 --- a/inire/tests/test_visibility.py +++ b/inire/tests/test_visibility.py @@ -1,4 +1,5 @@ -from shapely.geometry import box +from shapely import force_3d +from shapely.geometry import Polygon, box from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port @@ -42,6 +43,21 @@ def test_exact_corner_visibility_accepts_only_endpoint_contact_and_scales_to_lar assert (0, 15) not in {(x, y) for x, y, _ in blocked} +def test_corner_index_projects_exterior_and_hole_vertices_to_xy() -> None: + polygon = Polygon(box(30, 40, 60, 60).exterior.coords, (box(35, 45, 55, 55).exterior.coords,)) + for clearance in (0, 2): + for owner in (None, "fixed"): + corners = [] + for obstacle in (polygon, force_3d(polygon, z=5)): + world = RoutingWorld(clearance=clearance) + world.add_static_obstacle(obstacle, owner=owner) + visibility = VisibilityManager(world) + visibility._build_corner_index() + corners.append(visibility.corners) + assert corners[0] == corners[1] + assert len(corners[0]) == 8 + + def test_clear_cache_invalidates_without_rebuilding_and_static_change_rebuilds_lazily() -> None: engine = RoutingWorld(clearance=0.0) engine.metrics = AStarMetrics() diff --git a/plans/routing-follow-up-review.md b/plans/routing-follow-up-review.md new file mode 100644 index 0000000..6dc5aee --- /dev/null +++ b/plans/routing-follow-up-review.md @@ -0,0 +1,228 @@ +# Routing follow-up review + +Review baseline `f6e7bac`. This plan follows the [full project review](full-project-review.md) and the subsequent changes to routing, dependency requirements, and benchmark reporting. All 20 items were implemented. The reproductions below describe the baseline. + +## Implementation verification + +- The performance-enabled test suite passed all 395 tests. The topology, terminal, visibility, and refinement tests also passed on Python 3.11 with NumPy 1.26 and on Python 3.14 with Shapely 2.2 and GEOS 3.15. Ruff and the offline lockfile check passed. +- All 152 corpus and holdout boards reached their routing bounds under `matched-budget`, `public-defaults`, and `corpus-regression`. Each profile verified 2,245 nets. Verified IDs and per-net physical route lengths matched the baseline in all three profiles. Independent Shapely checks and zero-node seed replay confirmed board containment, clearance, and replayed geometry. +- The fixed-budget lattice runs verified four nets instead of three on `holdout-staggered-opposed` and two instead of zero on `lidar-clements-8x8`. Guided runs on `blocking-turn-room` verified both nets instead of one in both modes, using 25 guide expansions and 32 seed expansions. The equal-rank partial for `lane_1` on `search-comb-3x4` advanced from x=240 to x=237 in both modes. +- The ten-net fan-out retained all ten routes. Its counters now show 624 pair-local expansions and 1,703 total expansions. With shuffle seeds 42, 44, and 45, the pre-pair trace matched the restored iteration's conflict edges and component indices. A fake-clock test stopped diagnostic replay before its first expansion while keeping the same verified results and routing work. Historical captures retain the metric definitions used at capture time, which are recorded in the [archive guide](../archive/routing/README.md#compare-performance-or-diagnose-a-trace). +- The 200-net mixed-width board retained 400 guides with one triangulation and routed all 200 nets in 400 lattice expansions. The exact-width ray-tree cache retained eight entries. The residual connectivity probe constructed one union for 120 residual widths and again found no disconnected nets. Distinct widths still receive their own mesh when they need recovery. +- Guide and seed each verified the 240 supplied paths on `scale-bank-240-with-keepouts` with zero triangulations and zero expansions. The returned seeds matched the supplied paths. +- The imported fixture comparison reports a 100 nm grid. The grid-cost test checks the normalized objective at all five authored resolutions. The wheel and source distribution carry matching project URLs and README content. All eight README targets, including the illustration and three heading anchors, resolved from outside the checkout. + +### Fixes from the implementation review + +- The pre-pair trace saves the restored layout and replays it after repair and final verification. Under a controlled deadline, both crossing nets now verify with tracing enabled, using the same 608 expansions and one repair attempt as the untraced run. +- A frontier replay that expires increments `diagnostic_timeout_events`. The offset-gate retry still verifies both nets when the guided worker's trace expires. A verification-only worker still delivers its callback. +- The 40-net board with 144 keepouts and a one-grid-unit offset uses one triangulation and retains 80 guides. The earlier implementation built 40 triangulations. Guide and seed modes each verified all 40 nets with one triangulation. Narrower meshes still recover missing corridors and passages near obstacles or board edges. +- All 397 tests passed with performance checks enabled. An independent rerun of all three benchmark profiles verified the same 2,245 net IDs and per-net lengths in each profile. Expansion totals also matched the implementation before these review fixes. + +### Fixes from the second implementation review + +- Frontier-only conflict collection uses verified reports and runs after routing, final verification, and the replay callback. In the dense two-net replay, the callback still fired at 31.6 seconds of controlled work with tracing enabled. The diagnostic pass reached the deadline separately. The offset-gate retry still verified both nets. +- Deferred pre-pair tracing collects component conflicts only for colliding nets. On the 22-net board, expiry during the first optional check stopped further checks and kept all 22 verified routes. +- Failed shared guides can recover narrower alternatives when reservations obstruct the shared space. The width-24 seeded blocker and width-2 offset repro now verifies both nets in 1,792 expansions. The clear 40-net offset board still verifies 40/40 with one triangulation in guide and seed modes. +- The performance-enabled suite passed 398 tests. All three corpus profiles reached every routing bound and matched the prior verified IDs, per-net lengths, and expansion totals. + +## 1. Catch physical keepout collisions missed by bend proxies — High + +Use a `120 × 120` board, a width-2 net from `(10, 20, 0)` to `(80, 80, 90)`, clearance 1, and a keepout from `(77.3, 22.3)` to `(77.7, 22.7)`. Set lattice mode, a 200-node budget, a single 90-degree radius of 10, no S-bends, zero proximity cost, three iterations, and disable warm start and refinement. With `bend_collision_type="clipped_bbox"` and `bend_clip_margin=5`, search repeatedly picks a one-bend path that fails final verification. Standard arc admission finds a valid three-bend detour in 37 expansions. A probe that checks the physical clearance of each proposed bend also finds the detour in 37 expansions with the original clipped proxy settings. + +Check static clearance against the physical outline when a bend proxy may understate it. Query the physical bounds in that case. Reuse the cached move-admission decision and preserve the fast path for standard geometry. Exercise a shrunken built-in proxy, a custom polygon proxy with an arc outline, and an exact-clearance control. Require unchanged coverage across the corpus and check work and runtime for standard arc routing. [Static move admission](../inire/geometry/collision.py#L299) + +## 2. Count all pair-local search expansions — Medium + +In `example_07_large_scale_routing_no_warm_start`, the router verifies 10/10 nets and reports 1,079 total expansions and 42 pair-local expansions. Instrumenting the actual `route_astar` calls in pair repair records 624 expansions over three pair attempts. The failed order spends 582 expansions before returning no candidate. All 624 expansions are absent from the top-level `nodes_expanded` field. The current diagnostics guide documents the narrower meaning of the pair-specific counter. + +Return expansion work even when a pair attempt fails and add it to both counters. Keep metrics from diagnostic replay isolated. Update the metric documentation and reconcile the expansion guardrails and saved baselines that use the older definitions. Compare the selected routes, attempt order, and verified coverage independently of the counter changes. [Pair search](../inire/router/_pair_local.py#L67) · [Counter update](../inire/router/_router.py#L851) · [Metric guide](../docs/routing-diagnostics.md#route-metrics) + +## 3. Skip planning and seed materialization with zero iterations — Medium + +With `max_iterations=0`, the point-terminal bundle fixture returns nine unroutable results with zero iterations in `off` and `automatic` modes. In `bundle` mode the router builds a schedule, performs zero routing iterations, and raises `Bundle schedule failed geometric verification for net_00`. The lattice worker also materializes supplied seeds before discovering that it will run zero iterations. + +Make the disabled-iteration outcome consistent across modes. Skip bundle planning and unused seed materialization while preserving public input checks and per-net diagnostics. Exercise a supported bundle, a bundle-shaped layout rejected by the planner when enabled, and seeded input. Keep zero-node replay with positive iterations available. [Bundle setup](../inire/router/_stack.py#L32) · [Bundle result check](../inire/router/_stack.py#L98) · [Seed preparation](../inire/router/_router.py#L337) + +## 4. Read visibility corners in XY at zero clearance — High + +A `100 × 80` board with a straight width-2 net from `(10, 20, 0)` to `(80, 20, 0)` and a keepout above it is enough to reproduce an exception. Use a polygon with exterior `box(30, 40, 60, 60)`, a hole `box(35, 45, 55, 55)`, and set every vertex's Z coordinate to 5. At zero clearance, both `tangent_corner` and `exact_corner` raise `ValueError: too many values to unpack` in lattice mode. The same input completes when visibility is off. The exception also occurs when the polygon is supplied as a fixed route. At clearance 2 the buffer yields XY coordinates and the search completes in each case. + +Read XY coordinates from each exterior and interior ring before indexing corners. Keep the original polygons available for returned geometry. Exercise XY and XYZ keepouts and fixed routes in both visibility modes and at zero and positive clearance. Compare the paths and the corner counts. [Visibility corner extraction](../inire/router/visibility.py#L55) · [Obstacle buffering](../inire/geometry/static_obstacle_index.py#L62) + +## 5. Keep routing when the conflict count stalls but the layout can improve — High + +Under matched-budget fixture settings with `mode="off"`, a 90-node search limit, seven iterations, warm start off, and refinement off, `holdout-staggered-opposed` stops after four iterations and verifies 3/9 nets. Its conflict edge counts are `[4, 1, 1, 1]`. Disabling only the repeated-count stop yields `[4, 1, 1, 1, 0, 0, 0]` and verifies 4/9. The same change improves `lidar-clements-8x8` from 0/6 to 2/6, against a bound of three. In both cases the edge identities also repeat before a later iteration improves coverage. Of 60 boards checked under these settings, five met the repeat-stop condition and two gained coverage when it was disabled. + +Remove the count-only early exit or replace it with a stopping rule that accounts for the changing congestion penalties. Keep the iteration and time limits. Compare the verified net IDs, check the progression of conflicts and penalties, and measure runtime on the boards that keep searching. Retain the path to pair-local repair while checking that it still triggers where it improves coverage. [Iteration stop](../inire/router/_router.py#L1166) · [Repeated-count rule](../inire/router/_congestion_policy.py#L117) + +## 6. Bound the cost of width-specific corridor meshes — Medium + +On a `1000 × 1000` board with 144 rectangular keepouts below 40 straight nets, corridor planning builds one mesh at uniform width 2 and 40 meshes when widths increase from 2 by 0.01 per net. Both runs guide all 40 nets. The measured planning times were 2.42 seconds and 5.43 seconds in the same process. Every width below the maximum gets a mesh even when the widest mesh has already supplied passages. + +A `1400 × 2400` board with 200 nets and 240 rectangular keepouts scales from one to 200 meshes, with two corridors per net in both runs. Planning took about 54 and 68 seconds in the same process. To reproduce it, place keepouts at `box(20 + 48*x, 18 + 48*y, 31 + 48*x, 30 + 48*y)` for `x` from 0 through 19 and `y` from 0 through 11. Give net `i` east-facing ports at `(5, 620 + 8*i)` and `(45, 620 + 8*i)`. Compare width 2 with `2 + 0.005*i` using clearance 2, bend radius 10, and two corridors per net. Use the mesh count as the primary comparison because the wall times vary with load. + +Keep width-specific recovery for missing corridors and passages that are genuinely too narrow in the shared mesh. Reuse a conservative mesh or defer narrower alternatives until the shared candidates fail. Verify both the mixed-width narrow-aperture fixtures and the case where a wide-mesh corridor exists but the narrower net needs a different passage. Compare triangulation counts and routing coverage on a large mixed-width layout before replacing the eager passes. [Width-specific planning](../inire/router/_topology.py#L384) · [Narrow corridor coverage](../inire/tests/test_topology.py) + +## 7. Update the corridor walkthrough after the retry removals — Low + +The corridor walkthrough still says that a joint retry can move lanes for several nets. The automatic planner removed that retry and its alternate-lane permutation in `7476209`. The architecture overview also describes lattice fallback in terms of planning being unavailable. The current flow requires triangulation and uses lattice when the geometry calls for it or earlier planners leave unresolved nets. + +Describe the shared portal assignment, width-specific recovery, and remaining lattice retries in the active guides. Check the walkthrough links and benchmark command against the current output. Keep the historical review and experiment records tied to their revisions. [Corridor walkthrough](../docs/topological-routing.md#corridor-planning-and-realization) · [Automatic architecture](../docs/architecture.md#automatic-routing) + +The bundle guide also says the smallest 90-degree radius must be a positive integer shared with `sbend_radii`. The planner tries the usable common integer radii. The point-terminal fixture verifies all nine nets with 90-degree radii `(10.5, 50)` and S-bend radii `(50,)`. Describe the eligibility of the common radius and retain the existing layout and geometry requirements. [Mode requirements](../docs/user/tune-and-troubleshoot.md#choose-a-routing-mode) · [Bundle radius selection](../inire/router/_bundle.py#L222) + +Restore the link from the archived refactor plan to the current corpus command. It points to `#run-the-full-regression-corpus`, while the current heading uses `#run-the-full-benchmark-corpus`. The historical results can stay tied to the original corpus. [Archived link](../archive/routing/routing-refactor-plan.md#verification) · [Current corpus command](../docs/benchmarks.md#run-the-full-benchmark-corpus) + +## 8. Hand off to pair repair only when the saved layout has a repairable pair — High + +Run `blocking-turn-room` with matched-budget options, an 85-node limit, five congestion iterations, zero guidance cost, and warm start and refinement off. Both guide and seed modes reach one verified net in iteration 0. In iteration 1 both nets reach their targets but conflict, and the router stops to hand off to pair repair. It restores iteration 0, whose partial path has no conflict edges, so pair repair tries no pairs. Bypassing only the pair-local handoff lets iteration 2 verify both nets. The guide run rises from 10 to 25 expansions and the seed run from 17 to 32. The repeated-count rule in item 5 stays enabled for this reproduction. + +Base the handoff on the saved layout the repair will receive. Require an eligible conflict pair before skipping the remaining congestion iterations. Cover the zero-edge saved layout and retain the early handoff on the fan-out fixture where pair repair succeeds. A control requiring at least one saved conflict edge retained all 10 fan-out routes and all three pair-search attempts. Evaluate coverage and work jointly with item 5. [Pair-local handoff](../inire/router/_router.py#L1163) · [Pair eligibility](../inire/router/_router.py#L727) · [Plateau rule](../inire/router/_congestion_policy.py#L111) + +## 9. Preserve useful partial paths when congestion iterations tie — Low + +With the same settings on `search-comb-3x4`, guide and seed each finish five iterations with no completed nets or conflict edges. The final path for `lane_1` ends at `(240, 150, 180)`. Every callback after iteration 0 shows that net ending at `(237, 150, 180)`, closer to its target at `(15, 150, 180)`. The equal layout rank always keeps the first iteration, even when a later iteration advances a partial path. + +Both partial paths fit the board and meet static clearance. On ties in completed net IDs and conflict rank, prefer more useful partial results using the existing target-distance ordering. Check the geometry of any candidate partial path used for this comparison. Preserve completed geometry and keep conflict trace indices aligned with the selected paths. Include an empty-to-partial case and a control where a closer endpoint belongs to a colliding path. [Layout selection](../inire/router/_router.py#L459) · [Search progress](../inire/router/_search.py#L41) + +## 10. Bound the width-specific ray indexes in lattice search — Medium + +Route the 200-net board from item 6 in lattice mode at four nodes per net and one iteration. Turn off bends, visibility, proximity cost, warm start, and refinement. Both width distributions verify 200/200 in 400 expansions. The uniform-width run retains one ray index with 240 buffered obstacles. The mixed-width run retains 200 indexes and 48,000 buffered obstacles. In fresh processes on the same core, the probes took about 0.35 and 2.05 seconds, with peak memory about 78 and 103 MiB. + +Bound retention while preserving exact-width geometry. Compare a size-limited index cache with a shared raw index that buffers only candidates for each query. Keep the tree for commonly reused widths if it saves work. Check exact-clearance behavior, repeated-width interleaving, a large mixed-width layout, and the normal lattice coverage and runtime baselines. [Width-specific index](../inire/geometry/static_obstacle_index.py#L106) · [Ray query](../inire/geometry/collision.py#L886) + +## 11. Verify complete seed layouts before planning corridors — Medium + +Use the reference paths in `scale-bank-240-with-keepouts` as `initial_paths`, with matched-budget options, one iteration, and warm start and refinement off. Guide and seed each verify 240/240 with zero expansions, after building corridors for all 240 nets. In one local run per mode, corridor planning took about 208 seconds in guide and 210 seconds in seed. A probe bypassing just `plan_corridors` returned identical verified placements in about 0.12 seconds per mode. A 40-net, 144-keepout control reproduced placement parity, with about 2.5 seconds of planning per mode. + +With a controlled clock, a plan that consumes the worker deadline returns an empty, unroutable result for an otherwise valid straight seed in both modes. This isolates the ordering problem without relying on host load. + +When every net has a seed that reaches its target, check the complete seeded layout before building guides. Take the fast path only if the seeds verify together. Exercise partial, incompatible, overlapping, and missing seeds that still need the normal search. Reuse verification work and retain the requested refinement and callback behavior. [Setup before the first iteration](../inire/router/_router.py#L315) · [Corridor planning](../inire/router/_router.py#L282) + +## 12. Scale the flat S-bend surcharge linearly with the benchmark grid — Medium + +The expanded fixture converter multiplies both bend surcharges by the grid scale raised to the power of 1.5. That compensates for the radius adjustment on 90-degree bends. An S-bend has a flat surcharge, so the same physical route is valued differently when expressed in finer grid units. A width-2 µm S-bend with radius 10 µm, offset 8 µm, and an exact 16 µm span has length 18.546 µm at both 1,000 nm and 10 nm grids. With proximity cost off and the default 500-unit surcharge before conversion, normalized native cost changes from 518.546 to 5,018.546. + +Scale the S-bend surcharge by the grid factor. Check normalized costs for a straight, a quarter turn, and an exact-span S-bend across the authored grids. With a corrected surcharge on 24 fine-grid expanded cases that allow S-bends, automatic regression coverage, verified paths, and expansion counts stayed the same. In a lattice control limited to 200 nodes per net and one iteration, `complex-column-5x2` retained the same verified net but changed its path and used 842 expansions instead of 992. Reconcile affected benchmark baselines and update the fixture guide, which still lists 72 expanded cases and eight search challenges. The current groups have 75 and 11 respectively. [Grid conversion](../inire/tests/routing_expanded_benchmarks.py#L59) · [Component radius](../inire/geometry/components.py#L197) · [Native surcharge](../inire/router/cost.py#L234) · [Fixture guide](../docs/benchmark-fixtures.md#micron-scale-routing-cases) + +Propagate the imported grid into the same comparison records. The converted fixtures declare ten layout units per micron, but the loader discards that scale. A JSON comparison of `lidar-toy-example` emits `"grid_nm": null`. The known scale for all six imported boards is 100 nm. Test that the comparison output carries the scale from the fixture data. [Imported fixture loader](../inire/tests/routing_external_benchmarks.py#L13) · [Comparison export](../scripts/compare_topological_routing.py#L413) + +## 13. Make the guidance retry regression independent of corridor candidates — Medium + +The two-net offset-gate test expects the guided attempt to verify one net in each of its first two iterations and the retry without a guidance cost to verify both nets. This holds on the lockfile environment with Shapely 2.1.2 and GEOS 3.13.1. With the local Shapely 2.2.0 distribution and GEOS 3.15.0, the planner generates different corridor centerlines and the first guided iteration verifies both nets. The worker skips the retry and reports selected attempt 0, and the test fails on the hard-coded callback sequence. + +Decouple the retry and attempt-index assertions from the particular corridor candidates this layout receives. Keep the real layout as a coverage control and use a deterministic first-attempt outcome to exercise retry selection and diagnostic indices. Verify the control on both dependency combinations and retain the check that both nets route. [Offset-gate regression](../inire/tests/test_topology.py#L115) · [Explicit retry and selection](../inire/router/_stack.py#L161) + +## 14. Observe the worker deadline during refinement and frontier replay — Medium + +On a `100 × 100` board, replay two perpendicular width-2 straights through the center, from `(10, 50, 0)` to `(90, 50, 0)` and from `(50, 10, 90)` to `(50, 90, 90)`. Use lattice mode, a 60-node limit, one iteration, no bends, warm start off, refinement off, and `capture_frontier_trace=True`. Advance a controlled clock from zero to 61 seconds as the first frontier replay starts. Both diagnostic searches still expand three nodes each past the 60-second worker deadline. The run reports zero timeouts. The same replay routine is used for pre-pair traces. + +On the seeded foldback control with unlimited refinement windows, advance the clock at the first window. A second window starts after expiration, and the timeout is counted only after refinement returns. The worker currently checks once before refining each net. + +Pass the worker's expiry check through frontier A* replay and check it between diagnostic replays and at refinement windows and bounded candidate checkpoints. Keep final verification and the latest verified geometry available after expiration. Exercise expiry before and during a diagnostic search, expiry during a refinement window, and an uninterrupted run with the same results and stable work counters. [Frontier replay](../inire/router/_router.py#L567) · [Worker deadline](../inire/router/_router.py#L382) · [Refinement loop](../inire/router/refiner.py#L423) · [Foldback control](../inire/tests/test_refinements.py#L21) + +## 15. Keep pre-pair counters and frontier geometry on the same layout — Medium + +Run the ten-net fan-out using `_trace_example_07_variant(warm_start_enabled=False, seed=44)`. Iteration 6 verifies six nets and leaves one conflict, `net_06`–`net_07`. Iteration 7 verifies four nets and has four conflict edges, none matching that pair. The worker restores iteration 6 and sends `net_06`–`net_07` to pair repair. The pre-pair trace reports iteration 7's edges, reroute order, and work, while replaying the restored iteration 6 geometry. Four routed paths differ between those layouts. The guide presents this trace as a record of the handoff into pair repair. + +With seed 45, both iterations verify seven nets with one conflict. The trace lists `net_02`–`net_03`, and pair repair receives `net_08`–`net_09`. A comparison of counts alone misses the attribution error. [Fan-out trace fixture](../inire/tests/example_scenarios.py#L367) + +Keep the attempt metadata associated with the saved layout and use it for the trace after restoring that layout. Include carries and any missing per-net attempt data consistently. The iteration trace already records the discarded iteration. Add a control where the conflict identities change and an earlier layout is restored, and check that the pre-pair conflict edges match the pair-repair input and that hotspot geometry refers to that same layout. Preserve coverage and search selection with diagnostics enabled. [Saved-layout restoration](../inire/router/_router.py#L430) · [Pre-pair trace assembly](../inire/router/_router.py#L755) · [Trace guide](../docs/routing-diagnostics.md#traces) + +## 16. Reject unknown performance scenarios before writing reports — Medium + +Run `scripts.record_performance_baseline --scenario example_01_simple_rote --output-dir ` using the documented module invocation. It exits successfully and writes an empty `scenarios` list and a Markdown baseline with no measurements. With the default output directory, those writes replace the committed baseline files. The diff tool accepts the same misspelling and emits an empty comparison. The shared snapshot selector simply drops unknown names. + +Validate all explicitly requested scenario names before measuring or writing files. Distinguish unknown names from performance-only names that need the existing flag. Keep the diff tool's support for a scenario newly present in the current run or present only in the baseline. Exercise a misspelling alongside an existing output file, a mixed valid and invalid selection, and a valid performance-only selection. [Snapshot selection](../inire/tests/example_scenarios.py#L497) · [Baseline recorder](../scripts/record_performance_baseline.py#L100) · [Baseline comparison](../scripts/diff_performance_baseline.py#L200) + +## 17. Resolve heading inference from the caller's seeded request — High + +Use `terminal-bench-point-terminals` in automatic mode with inference enabled, 20 search nodes, one congestion iteration, warm start off, and refinement off. Give `net_00` a radius-1000 quarter-turn seed while only radius 50 is configured. The public wrapper rejects the seed and the automatic planner now sees an unseeded request. It verifies 9/9 after changing `net_08` from the requested east-facing arrival to west-facing. The API describes caller headings as fixed when initial paths are supplied. + +Replace the rejected seed with a compatible `StraightSeed(5)` prefix on `net_00`. All headings stay fixed, but the automatic planner skips the fixed-heading bundle turnaround because it checks the configured inference flag. The run verifies 1/9. Turning inference off while keeping the same prefix and budget verifies 9/9 using the bundle turnaround. + +Resolve whether inference is active at the public boundary, where the original seeds and options are both available, and use that decision for selecting the compatible constructive planner. Preserve diagnostics for rejected seeds and the unseeded inference behavior. Cover a valid prefix, an unusable nonempty seed, and a fully seeded replay. Verify requested and effective poses as well as counts. [Seed filtering](../inire/__init__.py#L141) · [Bundle selection](../inire/router/_automatic.py#L225) · [Inference gate](../inire/router/_automatic.py#L762) · [Heading contract](../docs/user/api-reference.md#topologyoptions) + +## 18. Make the project links usable in release artifacts — Low + +The project and repository URLs are present as top-level keys in `[project]`, but the built wheel has neither a `Home-page` nor a `Project-URL` header. The README is copied into the wheel and into its long description with seven checkout-relative documentation links. The wheel contains none of those targets. One example is `docs/user/route-a-layout.md#define-the-inputs`, which resolves from the repository root and fails from the installed README. + +Declare the links in `[project.urls]` and give the released long description and installed README resolvable documentation links. Verify the wheel and source distribution metadata from fresh builds and check the links from outside the checkout. Keep the repository README's documentation useful when browsing the source. [Package metadata](../pyproject.toml#L1) · [Repository README](../README.md) + +## 19. Reuse connectivity work across residual net widths — Medium + +On a `1400 × 2800` board, use the 240 keepouts from item 6. Place 240 width-2 nets from `(5, 630 + 9*i, 0)` to `(45, 630 + 9*i + int(i >= 120), 0)`, with clearance 2. Direct planning locks the first 120 straights. The connectivity check finds no disconnected nets among the 120 remaining shifts. With uniform widths, it buffers 360 polygons and builds one union. Change the width of residual net `i` to `2 + 0.005*(i - 120)`. The test still finds no disconnected nets, while preparing 120 unions from 43,200 buffered polygons. Local interleaved probes took roughly 0.06 seconds and 6.8 seconds respectively. + +A separate 24-net automatic control with twelve straight locks and twelve mixed-width quarter turns reached this check twice and verified all 24 nets. Screen narrower nets against the widest residual width's free-space regions. Terminals already in one shared region can skip the narrower calculation. Keep the exact-width check where the shared result leaves connectivity unresolved. Compare disconnected IDs, lock selection, and coverage on mixed-width apertures and the corpus. [Connectivity check](../inire/router/_routing_policy.py#L117) · [Lock planning](../inire/router/_routing_policy.py#L155) + +## 20. Keep seed guidance from increasing the cost of free moves — Medium + +On a `120 × 100` board with no obstacles and zero clearance, use a width-2 net from `(10, 45, 0)` to `(100, 5, 270)`. Set lattice mode, eight expansion nodes, radius-10 quarter turns, no S-bends, visibility off, warm start off, one iteration, and refinement off. Set all four objective weights to zero. Supply `PathSeed((StraightSeed(80), Bend90Seed(10, "CW")))`. A matching move with computed cost zero receives a cost of 0.001 at the discount floor. The returned path stops after a straight at `(100, 45, 0)`. + +An in-memory probe capped the discounted cost at the original cost. On the same budget it verified the supplied prefix followed by a length-30 straight. Keep the discount nonincreasing while preserving its floor for moves whose original cost already exceeds the floor. Exercise zero and small positive original costs, seeded and unseeded search, and the low-length-cost benchmarks. [Guidance scoring](../inire/router/_astar_admission.py#L199) + +## Implementation order + +1. Fix bend admission, visibility coordinates, zero-iteration handling, and heading inference for seeded requests. Add targeted reproductions and run the timing-enabled suite. Enforce the worker deadline inside optional refinement and diagnostics. +2. Evaluate the two congestion stopping rules independently. Check the reproduced coverage gains, preserve successful pair repairs, and measure the runtime cost of continuing through a plateau. Handle tied partial outcomes after the coverage changes. +3. Correct pre-pair trace attribution separately from route selection. Update the expansion counters in a separate change so the metric baselines and any affected guardrails can be reconciled with measured work. +4. Change seed verification order, mesh scheduling, ray-index retention, and lock connectivity independently after the correctness fixes. Use the large uniform- and mixed-width layouts, the seeded 240-net board, and narrow passages to check the tradeoffs. Update the walkthrough once the retained routing paths are clear. +5. Correct the fixture unit conversion and compare old and new scores and paths separately from runtime router changes. Decouple the retry regression from the geometry planner's choice of candidates. Check the guidance discount against zero-cost and low-cost search. +6. Validate performance scenario selection and update release metadata. Verify the report and distribution artifacts in scratch directories. + +For each routing change, compare verified net IDs across the corpus and holdout under all three profiles. Preserve coverage, validate changed routes against obstacles, fixed routes, peers, and board bounds, and report length and runtime changes over the common verified nets. Use the full timing-enabled suite before combining changes. + +## Baseline verification + +- All 389 tests passed with performance checks enabled. Ruff passed. The local environment used Python 3.13.18, Shapely 2.1.2, and GEOS 3.13.1. +- All 152 corpus and retry-holdout boards were checked with `matched-budget`, `public-defaults`, and `corpus-regression`. Each profile produced 2,245 verified routes. Independent geometry checks agreed with the reports, and zero-node seed replays reproduced endpoint poses, lengths, and polygon outlines. +- The geometry sweeps covered 96 legal primitive seed replays, 384 active searches across four routing modes, 500 generated corridor plans, 4,320 physical-index comparisons, and 1,077 ray-intersection comparisons. They produced no additional findings. +- Five benchmark cases matched on geometry, counters, and traces across two Python hash seeds, with and without callbacks. The package archives passed content checks and the extracted wheel routed a guide case in the local environment. The documented `offset-gates` comparison also ran successfully with the current command. +- A follow-up sweep across 75 boards and three modes checked iteration handoff and selected partial geometry. Four of the 225 runs stopped at the pair-repair handoff before the configured iteration limit. Bypassing only that condition improved coverage in two runs, both on `blocking-turn-room`. +- The follow-up baseline again passed all 389 timing-enabled tests and Ruff. Another 144 rotated uniform- and mixed-width layouts verified from seed and agreed with the capacity and port-spacing checks. +- In 18 benchmark CLI mode and policy runs, verified outcomes agreed with the selected stages and reported cost entries. Four retry samples on `stress-refine-return-shelf` each verified all four nets and reported placement data for those same net IDs. + +## Previous closing review + +The next full review pass after items 12 and 13 found no additional issues. + +- Independently checked all 152 corpus and holdout boards under each of the three profiles on both Python 3.13.18 with Shapely 2.1.2 and GEOS 3.13.1, and Python 3.14.10 with Shapely 2.2.0 and GEOS 3.15.0. Each environment and profile verified 2,245 routes. Checked endpoint poses, polygon validity and clearance, and geometry and lengths after replay. +- On each dependency combination, 648 generated compound paths replayed from seeds and 96 active mixed-width gate layouts met their bounds and clearances. Callbacks, traces, and final reports agreed. The active control layouts returned equal paths and work counts with diagnostics enabled. +- Built the wheel and source archive and matched all 40 runtime modules in the wheel against the checkout. Exercised automatic, off, guide, and seed routing from the extracted wheel on both environments. All 12 advanced examples verified, the fixture export and five documentation figures regenerated byte for byte, and the local file links across the 15 active documentation pages resolved. +- All 389 timing-enabled tests and Ruff passed in the lockfile environment. The Python 3.14 suite passed 387 tests, skipped the opt-in performance test, and reproduced the one retry assertion failure in item 13. + +## Additional review of deadlines and diagnostics + +- All 389 timing-enabled tests and Ruff passed again. Across 128 seeded foldback controls with varied orientation, radius, width, spacing, and routing mode, refinement preserved endpoint poses, clearance, and route validity. All 128 changed placement without increasing the configured path cost. +- The deadline probes in item 14 exercised real frontier searches and refinement with a controlled clock. A sweep of 225 bounded runs produced one pre-pair trace, whose metadata matched the saved layout. The fan-out with seed 44 and a separate three-net control both reproduced the attribution issue in item 15. + +## Full-codebase review passes + +The expanded review took its scope from the 190 tracked files at `f6e7bac`, including 110 Python files. It covered library modules, tests and fixtures, reporting and import/export commands, examples and visualizations, documentation and archived reports, and packaging and dependency configuration. The first full-codebase pass added items 16–18 and found the imported grid omission in item 12. The release and link checks then added the missing installed-documentation targets in item 18 and the archived link in item 7. + +| Area | Evidence gathered in the follow-up passes | +| --- | --- | +| Public API, geometry, and collision state | 648 compound seed replays exercised terminal poses, clearance, snapshots, and callbacks. An independent oracle agreed with 1,920 physical-index queries after insertions, removals, and replacements. All 36 concurrent routing calls matched serial placements and coverage. | +| Search, constructive planners, congestion, and refinement | Independent clearance and seed-replay checks covered all 152 corpus and holdout boards under the three profiles on Python 3.11, 3.13, and 3.14. Each profile verified 2,245 routes in each environment. Another 96 mixed-width gate controls preserved paths and search work with diagnostics enabled. The earlier 128 refinement controls covered rotated and mirrored paths with several widths and spacings. A same-core check of the slower splitter-tree fixture recorded the same 15,653 expansions and the same verified IDs on Python 3.11 and 3.13. | +| Tests and diagnostics | The lockfile suite passed all 389 tests with performance checks enabled and Ruff passed. The Python 3.11 suite passed 388 tests with the opt-in timing test skipped. A branch-instrumented Python 3.14 run passed 377 tests with performance gates and the known item 13 assertion deselected. The deadline and pre-pair counterexamples were checked against the saved layouts. | +| Benchmarks, scripts, and data | All 16 script entry points accepted `--help`. Exercised benchmark comparisons, two-worker retries, parity snapshots, performance reports, four trace exports, and both waypoint entry points. All 27 exported paths replayed and independently met clearance. The external importer reproduced the checked-in data byte for byte from the two pinned archives. | +| Examples, visualization, and documentation | Executed the user-guide Python snippets with their documented inputs, ran nine numbered examples, and regenerated 24 documentation and gallery figures. Fifteen figures matched byte for byte. The changed gallery placements retained verified coverage and matched the accompanying descriptions. Checked 388 local links across 30 distinct tracked Markdown pages, including the archive and historical plans. The broken archive fragment is recorded in item 7. | +| Build and dependency compatibility | The lockfile check passed offline. Built the wheel and source archive and rebuilt the wheel from the unpacked archive. The 40 runtime Python files matched the checkout. The installed wheel routed in four modes and serialized results on Python 3.11.11 with Shapely 2.1.0, GEOS 3.13.1, and NumPy 1.26.4 and 2.2.6. The four plotting helpers produced PNGs on the minimum Python and Shapely versions. The unpacked source distribution ran the waypoint export to 9/9. | + +The final full-codebase pass after documenting those findings found no additional issues. It reran the suite, independent corpus verification, replay and index controls, command and data round-trips, source and installed documentation checks, and release builds. The numbered findings record the fixes identified at that review baseline. + +## Additional review of lock connectivity and guidance costs + +The next requested pass added items 19 and 20. A two-width aperture control classified the wide net as disconnected and retained the narrow net. The valid eight-node control path also verified independently in seed replay. + +All 389 timing-enabled tests passed and Ruff passed. The offline lockfile check, wheel and source archive rebuild, and a smoke test of all 16 command entry points passed again. Benchmark, retry, parity, waypoint, and diagnostics commands produced their artifacts in scratch directories. + +## Review pass after items 19 and 20 + +This pass found no additional issues at `f6e7bac`. It covered the routing and geometry modules, public results, benchmark and diagnostic commands, fixture data, documentation and generated figures, and release artifacts. + +- All 389 tests passed with performance checks enabled, Ruff passed, and the offline lockfile check passed. Independent geometry and seed-replay checks verified 2,245 routes per profile across all 152 corpus and holdout boards. +- Search-time and final same-net collision checks agreed on 1,008 generated paths, including 244 with overlaps. Across 240 bounded search configurations, traced and ordinary routing agreed on paths and work counts. All 96 verified placements in that matrix met clearance and bounds. Compound replay, mixed-width gate, physical index mutation, and concurrent placement controls passed again. +- The review checked all 16 script entry points. Selected coverage agreed with reported costs and placement data in 18 comparison records and eight retry samples. Both pinned archive imports regenerated the external fixture data byte for byte. The twelve core documentation figures also regenerated byte for byte. +- The wheel and source archive rebuilt successfully and all 40 runtime modules matched. The extracted wheel passed routing in the four search modes and result serialization on Python 3.11 with Shapely 2.1.0. diff --git a/pyproject.toml b/pyproject.toml index e442040..3871a0b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,8 +7,6 @@ license = { file = "LICENSE.md" } authors = [ { name="Jan Petykiewicz", email="jan@mpxd.net" }, ] -homepage = "https://mpxd.net/code/jan/inire" -repository = "https://mpxd.net/code/jan/inire" classifiers = [ "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", @@ -28,6 +26,11 @@ dependencies = [ "matplotlib", ] +[project.urls] +Homepage = "https://mpxd.net/code/jan/inire" +Repository = "https://mpxd.net/code/jan/inire" +Documentation = "https://mpxd.net/code/jan/inire/src/branch/topo/DOCS.md" + [dependency-groups] dev = [ "hypothesis>=6.151.9", diff --git a/scripts/diff_performance_baseline.py b/scripts/diff_performance_baseline.py index 4fd9eff..e51ef89 100644 --- a/scripts/diff_performance_baseline.py +++ b/scripts/diff_performance_baseline.py @@ -40,8 +40,11 @@ def _current_snapshots( selected_scenarios: tuple[str, ...] | None, *, include_performance_only: bool, + baseline: dict[str, dict[str, object]], ) -> dict[str, dict[str, object]]: - snapshots = capture_scenario_snapshots(selected_scenarios, include_performance_only=include_performance_only) + snapshots = capture_scenario_snapshots( + selected_scenarios, include_performance_only=include_performance_only, baseline_scenarios=baseline.keys(), + ) return {snapshot.name: asdict(snapshot) for snapshot in snapshots} @@ -201,7 +204,10 @@ def main() -> None: metrics = tuple(args.metrics) if args.metrics else SUMMARY_KEYS _validate_metrics(metrics) baseline = _load_baseline(args.baseline, selected) - current = _current_snapshots(selected, include_performance_only=args.include_performance_only) + try: + current = _current_snapshots(selected, include_performance_only=args.include_performance_only, baseline=baseline) + except ValueError as exc: + parser.error(str(exc)) report = _render_report(baseline, current, metrics) if args.output is not None: diff --git a/scripts/record_performance_baseline.py b/scripts/record_performance_baseline.py index 3df56c0..3cedbe9 100644 --- a/scripts/record_performance_baseline.py +++ b/scripts/record_performance_baseline.py @@ -99,10 +99,12 @@ def main() -> None: repo_root = Path(__file__).resolve().parents[1] output_dir = repo_root / "archive" / "routing" if args.output_dir is None else args.output_dir.resolve() - output_dir.mkdir(parents=True, exist_ok=True) - selected = tuple(args.scenarios) if args.scenarios else None - payload = _build_payload(selected, include_performance_only=args.include_performance_only) + try: + payload = _build_payload(selected, include_performance_only=args.include_performance_only) + except ValueError as exc: + parser.error(str(exc)) + output_dir.mkdir(parents=True, exist_ok=True) json_path = output_dir / "performance_baseline.json" markdown_path = output_dir / "performance.md"