From f9ba5669dd296bfc137f551e17bb0d00210a3220 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sat, 28 Nov 2026 20:03:41 -0800 Subject: [PATCH] Validate routing options and match custom S-bend widths consistently --- docs/user/api-reference.md | 14 +++--- inire/model.py | 68 ++++++++++++++++++++------ inire/router/_astar_moves.py | 2 +- inire/router/_automatic.py | 5 +- inire/router/_bundle.py | 3 +- inire/tests/test_api.py | 57 +++++++++++++++++++++ inire/tests/test_routing_benchmarks.py | 24 ++++++++- plans/full-project-review.md | 2 + 8 files changed, 149 insertions(+), 26 deletions(-) diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index 7054fce..c6502f2 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -66,10 +66,10 @@ To read a route's polygons and write them to a test file, follow the [geometry e | Field | Default | Effect | | --- | --- | --- | -| `node_limit` | `1_000_000` | Per-search expansion ceiling. Automatic uses smaller budgets for its initial stages. Zero skips search and corridor preparation and allows verification of supplied seeds. | +| `node_limit` | `1_000_000` | Nonnegative integer per-search expansion ceiling. Automatic uses smaller budgets for its initial stages. Zero skips search and corridor preparation and allows verification of supplied seeds. | | `min_straight_length` | `5.0` | Finite, nonnegative minimum length for regular forward moves in lattice search. | | `max_straight_length` | `2000.0` | Finite, positive maximum distance for the forward scan in lattice search. | -| `greedy_h_weight` | `1.5` | Weight on the estimated cost still needed to reach the target. Lower values give more influence to the cost of the path so far. | +| `greedy_h_weight` | `1.5` | Finite, nonnegative weight on the estimated cost still needed to reach the target. Lower values give more influence to the cost of the path so far. | | `bend_radii` | `(50.0, 100.0)` | Finite, positive radii permitted for 90-degree bends in search and seeds. Each move needs a radius of at least half its net width. Fractional radii retain their curvature and extend both tangents to the next grid point. An empty list disables 90-degree bends. | | `sbend_radii` | `(10.0,)` | Finite, positive radii permitted for S-bends in search and seeds, subject to the same width requirement. An empty list disables S-bends. | | `sbend_offsets` | `None` | `None` lets the router choose signed lateral offsets. An explicit list restricts routing and seeds to those offsets after rounding to the grid. An empty list disables S-bends. | @@ -80,7 +80,7 @@ To read a route's polygons and write them to a test file, follow the [geometry e | `visibility_guidance` | `"tangent_corner"` | Choose tangent candidates, exact corner visibility with `"exact_corner"`, or no visibility suggestions with `"off"`. | | `sbend_outlines` | `()` | Complete custom S-bend polygons, supplied as `SBendOutline(offset, radius, width, polygon)` entries. Each entry applies to its signed offset, radius, and net width. | -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 export. Supply a separate outline to customize the opposite offset. Unmatched moves use the circular S-bend, and matching moves use the same nominal length as that circular bend for scoring. Automatic mode uses lattice search when custom outlines are supplied. Bundle mode requires circular bends. +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 export. 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, and matching moves use the same nominal length as that circular bend for scoring. Automatic mode uses lattice search when a registered outline matches a net width. Bundle mode requires circular bends for its nets. When migrating a half-arc template, supply the complete outline through `sbend_outlines` and keep `bend_physical_geometry` for custom 90-degree bends. Both terminal faces of each custom polygon must be centered on their ports and match the routed width. A custom 90-degree template is shared across nets, so it can only be used by nets whose width matches its faces. Replay an `SBendSeed` with the same outlines and bend settings to recover its physical geometry. @@ -88,7 +88,7 @@ Circular bends approximate the outer edge within a sagitta of 0.01 layout units. ### ObjectiveWeights -The search objective scores path length, components, and proximity. Increasing a component penalty makes routes with more of that component less attractive. Refinement can use its own objective. +The search objective scores path length, components, and proximity. All weights must be finite and nonnegative. Increasing a component penalty makes routes with more of that component less attractive. Refinement can use its own objective. | Field | Default | Effect | | --- | --- | --- | @@ -103,9 +103,9 @@ Increase the iteration limit when later reroutes might resolve conflicts. Adjust | Field | Default | Effect | | --- | --- | --- | -| `max_iterations` | `10` | Maximum congestion iterations per attempt. Automatic's initial probe may use fewer. Zero skips warm-start and corridor searches. | -| `base_penalty` | `100.0` | Initial penalty for overlapping other routes. | -| `multiplier` | `1.5` | Scale the penalty between unresolved iterations. | +| `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. | | `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. | diff --git a/inire/model.py b/inire/model.py index 1d06b79..cfd0ee4 100644 --- a/inire/model.py +++ b/inire/model.py @@ -2,7 +2,8 @@ from __future__ import annotations import warnings from dataclasses import dataclass, field -from math import isfinite +from math import isclose, isfinite +from numbers import Integral from typing import TYPE_CHECKING, Literal from shapely.geometry import Polygon @@ -13,6 +14,8 @@ from inire.geometry.sbend import sbend_grid_span from inire.seeds import Bend90Seed, PathSeed, SBendSeed if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry @@ -20,6 +23,21 @@ NetOrder = Literal["user", "shortest", "longest"] VisibilityGuidance = Literal["off", "exact_corner", "tangent_corner"] +def _require_budget(name: str, value: int, *, minimum: int = 0) -> None: + if isinstance(value, bool) or not isinstance(value, Integral) or value < minimum: + description = "positive" if minimum else "nonnegative" + raise ValueError(f"{name} must be a {description} integer") + + +def _require_nonnegative(name: str, value: float) -> None: + if not isfinite(value) or value < 0: + raise ValueError(f"{name} must be finite and nonnegative") + + +def _outline_width_matches(left: float, right: float) -> bool: + return isclose(left, right, rel_tol=1e-12) + + @dataclass(frozen=True, slots=True) class NetSpec: net_id: str @@ -28,6 +46,8 @@ class NetSpec: width: float = 2.0 def __post_init__(self) -> None: + if not isinstance(self.net_id, str): + raise TypeError(f"Net ID must be a string, got {self.net_id!r}") if not isfinite(self.width) or self.width <= 0: raise ValueError(f"Net {self.net_id!r} width must be finite and positive") @@ -39,6 +59,10 @@ class ObjectiveWeights: sbend_penalty: float = 500.0 danger_weight: float = 1.0 + def __post_init__(self) -> None: + for name in ("unit_length_cost", "bend_penalty", "sbend_penalty", "danger_weight"): + _require_nonnegative(name, getattr(self, name)) + @dataclass(frozen=True, slots=True) class SBendOutline: @@ -81,6 +105,10 @@ class SearchOptions: sbend_outlines: tuple[SBendOutline, ...] = () def __post_init__(self) -> None: + _require_budget("node_limit", self.node_limit) + _require_nonnegative("greedy_h_weight", self.greedy_h_weight) + if self.visibility_guidance not in ("off", "exact_corner", "tangent_corner"): + raise ValueError(f"Unknown visibility_guidance: {self.visibility_guidance!r}") for field_name in ("bend_radii", "sbend_radii"): radii = tuple(getattr(self, field_name)) if any(not isfinite(radius) or radius <= 0 for radius in radii): @@ -96,16 +124,17 @@ class SearchOptions: raise ValueError("S-bend offsets must be finite") object.__setattr__(self, "sbend_offsets", tuple(round(offset) for offset in offsets)) outlines = tuple(self.sbend_outlines) - outline_keys = set() + outline_widths: dict[tuple[float, float], list[float]] = {} for outline in outlines: if not isinstance(outline, SBendOutline): raise TypeError("sbend_outlines must contain SBendOutline entries") if outline.radius not in self.sbend_radii or not self.allows_sbend_offset(outline.offset): raise ValueError("S-bend outline must use a configured radius and offset") - key = outline.offset, outline.radius, outline.width - if key in outline_keys: - raise ValueError(f"Duplicate S-bend outline for offset, radius, and width {key}") - outline_keys.add(key) + key = outline.offset, outline.radius + widths = outline_widths.setdefault(key, []) + if any(_outline_width_matches(width, outline.width) for width in widths): + 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): @@ -119,11 +148,17 @@ class SearchOptions: def allows_sbend_offset(self, offset: float) -> bool: return self.sbend_offsets is None or offset in self.sbend_offsets + def sbend_outlines_for_width(self, width: float) -> Iterator[SBendOutline]: + return (outline for outline in self.sbend_outlines if _outline_width_matches(outline.width, width)) + + def has_applicable_sbend_outline(self, widths: Iterable[float]) -> bool: + return bool(self.sbend_outlines) and any(next(self.sbend_outlines_for_width(width), None) is not None for width in widths) + def sbend_outline(self, offset: float, radius: float, width: float) -> Polygon | None: - for outline in self.sbend_outlines: - if (outline.offset, outline.radius, outline.width) == (offset, radius, width): - return outline.polygon - return None + matches = [outline.polygon 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}") + return matches[0] if matches else None def seed_geometry_error(self, seed: PathSeed) -> str | None: for segment in seed.segments: @@ -173,6 +208,13 @@ class CongestionOptions: shuffle_nets: bool = False seed: int | None = None + def __post_init__(self) -> None: + _require_budget("max_iterations", self.max_iterations) + _require_nonnegative("base_penalty", self.base_penalty) + _require_nonnegative("multiplier", self.multiplier) + if self.net_order not in ("user", "shortest", "longest"): + raise ValueError(f"Unknown net_order: {self.net_order!r}") + @dataclass(frozen=True, slots=True) class RefinementOptions: @@ -208,12 +250,10 @@ class TopologyOptions: def __post_init__(self) -> None: if self.mode not in ("off", "guide", "seed", "bundle", "automatic"): raise ValueError(f"Unknown topology mode: {self.mode!r}") - if not isinstance(self.max_corridors, int) or self.max_corridors < 1: - raise ValueError("max_corridors must be a positive integer") + _require_budget("max_corridors", self.max_corridors, minimum=1) if not isfinite(self.guide_strength) or self.guide_strength < 0: raise ValueError("guide_strength must be finite and nonnegative") - if not isinstance(self.seed_node_limit, int) or self.seed_node_limit < 1: - raise ValueError("seed_node_limit must be a positive integer") + _require_budget("seed_node_limit", self.seed_node_limit, minimum=1) if self.automatic_cost not in ("selective", "always", "never"): raise ValueError(f"Unknown automatic cost policy: {self.automatic_cost!r}") if self.automatic_length_weights is not None: diff --git a/inire/router/_astar_moves.py b/inire/router/_astar_moves.py index b95b4b5..c5b026b 100644 --- a/inire/router/_astar_moves.py +++ b/inire/router/_astar_moves.py @@ -333,7 +333,7 @@ def expand_moves( explicit_offsets = search_options.sbend_offsets offsets = set(explicit_offsets) if explicit_offsets is not None else guide_offsets if search_options.sbend_outlines: - offsets.update(outline.offset for outline in search_options.sbend_outlines if outline.width == net_width) + offsets.update(outline.offset for outline in search_options.sbend_outlines_for_width(net_width)) if explicit_offsets is None and target.r == cp.r and 0 < dx_local <= 4 * max_sbend_r and 0 < abs(dy_local) < 2 * max_sbend_r: offsets.add(round(dy_local)) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 3d2b1dc..042cfdc 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -611,7 +611,10 @@ class _AutomaticRun: trials: list[Trial] = [] if not self.problem.nets or options.search.node_limit <= 0 or options.congestion.max_iterations <= 0: self._lattice_fallback(trials, options, "No automatic search requested") - elif options.search.sbend_outlines or isinstance(proxy, shapely.Polygon) or physical != "arc": + elif ( + isinstance(proxy, shapely.Polygon) or physical != "arc" + or options.search.has_applicable_sbend_outline(net.width for net in self.problem.nets) + ): self._lattice_fallback(trials, options, "Custom bend geometry uses lattice routing") else: with self._time("plan"): diff --git a/inire/router/_bundle.py b/inire/router/_bundle.py index 72fb8fb..e64f1b1 100644 --- a/inire/router/_bundle.py +++ b/inire/router/_bundle.py @@ -220,7 +220,8 @@ def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer bend = min(search.bend_radii, default=0.0) if ( not isfinite(bend) or bend <= 0 or bend != int(bend) or bend not in search.sbend_radii - or physical_geometry != "arc" or search.sbend_outlines + 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) diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 02d3fae..8729705 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -314,6 +314,35 @@ def test_sbend_outline_requires_both_port_faces() -> None: SBendOutline(40, 50, 2, 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: + with pytest.raises(ValueError, match="unit_length_cost"): + ObjectiveWeights(unit_length_cost=value) + with pytest.raises(ValueError, match="greedy_h_weight"): + SearchOptions(greedy_h_weight=value) + with pytest.raises(ValueError, match="base_penalty"): + CongestionOptions(base_penalty=value) + with pytest.raises(ValueError, match="multiplier"): + CongestionOptions(multiplier=value) + + +def test_public_inputs_reject_invalid_ids_and_named_options() -> None: + with pytest.raises(TypeError, match="Net ID must be a string"): + NetSpec(7, Port(0, 0, 0), Port(10, 0, 0)) + with pytest.raises(ValueError, match="net_order"): + CongestionOptions(net_order="longesst") + with pytest.raises(ValueError, match="visibility_guidance"): + SearchOptions(visibility_guidance="exact") + + def _sbend_strip(offset, half_width=1): centerline = [(0, 0), (20, offset / 10), (50, 3 * offset / 4), (80, offset)] return Polygon( @@ -321,6 +350,34 @@ def _sbend_strip(offset, half_width=1): ) +@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: + 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) + 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"] + replay = route( + replace(problem, initial_paths={"shift": PathSeed((SBendSeed(40, 50),))}), + 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 + + +def test_custom_sbend_outline_rejects_duplicate_and_ambiguous_widths() -> None: + outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15)) + 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("contact", ["face", "rounding", "gap", "extra_edge", "extra_point"]) @pytest.mark.parametrize("heading", [0, 90]) def test_custom_sbend_join_checks_actual_centered_face(contact, heading) -> None: diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index b92f5e0..331e44a 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -5,9 +5,11 @@ from json import dumps, loads import pytest from shapely import union_all -from shapely.geometry import Point, box, shape +from shapely.geometry import Point, Polygon, box, shape -from inire import Bend90Seed, NetSpec, Port, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route +from inire import ( + Bend90Seed, NetSpec, Port, RoutingOptions, RoutingProblem, SBendOutline, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, +) from inire.constants import TOLERANCE_LINEAR from inire.router._automatic import _AutomaticRun from inire.router._routing_policy import _disconnected_nets @@ -396,6 +398,24 @@ def test_bundle_first_routes_point_terminals_without_supplied_paths(name: str) - assert sample.nodes_expanded == 0 +@pytest.mark.parametrize(("name", "mode"), [("terminal-bench", "automatic"), ("terminal-bench-point-terminals", "bundle")]) +def test_unused_custom_outline_keeps_constructive_planning_available(name, mode) -> None: + case = next(case for case in BENCHMARK_CASES if case.name == 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()) + + 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 diff --git a/plans/full-project-review.md b/plans/full-project-review.md index d0770bf..57ebeaf 100644 --- a/plans/full-project-review.md +++ b/plans/full-project-review.md @@ -22,6 +22,8 @@ On the independent 5-by-3 mm CPW chip, KLayout confirmed that the published etch Implemented items 1, 2, and 17 cover missing joins, extra line or point contact on the join plane, custom port-face widths, and outer-edge arc accuracy. The focused geometry, API, collision, and refinement run passed 287 tests. The remaining items retain the acceptance checks below. +Implemented items 3, 6, and 21 retain constructive planning for unused custom outlines, reject unsupported search and congestion settings, and match custom S-bend widths consistently in search and replay. + | Batch | Work | Acceptance gate | | --- | --- | --- | | Physical verification | 1, 2, 17, 23, and 38 | Reject the faulty geometry and keep legal joins valid in search and seed replay. Check circular bend accuracy, folded-route spacing, and isolation between different nets. |