From 8e8c8a7ba04ca2f802dbc684c1173b4c1b1315d1 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 29 Nov 2026 00:31:51 -0800 Subject: [PATCH] Keep routing and export verification snapshots read-only --- docs/user/api-reference.md | 4 +-- inire/_snapshot.py | 36 +++++++++++++++++++ inire/layout.py | 74 +++++++++++++++++++++++++++++++------- inire/model.py | 7 ++-- inire/results.py | 8 +++-- inire/tests/test_layout.py | 50 ++++++++++++++++++++++++++ 6 files changed, 159 insertions(+), 20 deletions(-) create mode 100644 inire/_snapshot.py diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index 93c03d2..278f3f9 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -26,7 +26,7 @@ The fields below appear in constructor order. Use one layout unit for coordinate | `bounds` | Required | Finite board rectangle as `(xmin, ymin, xmax, ymax)`, with each minimum below its maximum. | | `nets` | `()` | Sequence of `NetSpec` objects with unique IDs. Duplicate IDs raise `ValueError`. | | `static_obstacles` | `()` | Valid, nonempty Shapely `Polygon` objects that define keepouts. | -| `initial_paths` | Empty mapping | Net IDs mapped to `PathSeed` objects. | +| `initial_paths` | Empty mapping | A read-only snapshot of net IDs mapped to `PathSeed` objects. Supply a new mapping to change seeds. | | `clearance` | `2.0` | Finite, nonnegative spacing required between distinct nets and between a net and a keepout. At zero clearance, distinct nets must still be disjoint, including at vertices. Boundary contact with a keepout is allowed. | | `safety_zone_radius` | `0.0021` | Tolerance for small obstacle intersections at a move's endpoints during search. | | `self_clearance` | `0.0` | Optional spacing within one net. Applies between components when the intervening centerline is at least this long. Adjacent joins and components immediately on either side of one bend are exempt. Unintended contact is always checked. | @@ -40,7 +40,7 @@ The fields below appear in constructor order. Use one layout unit for coordinate | Value | Read it for | | --- | --- | -| `RoutingRunResult.results_by_net` | A mapping from net ID to `RoutingResult`. | +| `RoutingRunResult.results_by_net` | A read-only mapping from net ID to `RoutingResult`. Use `dict(run.results_by_net)` to make an editable copy. | | `RoutingResult.is_valid` and `outcome` | `is_valid` is true when the outcome is `completed`. Read `outcome` to distinguish success, a failed geometry check (`colliding`), a path that stopped short (`partial`), or an empty path (`unroutable`). | | `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. An unroutable result has an empty path. | diff --git a/inire/_snapshot.py b/inire/_snapshot.py new file mode 100644 index 0000000..268b573 --- /dev/null +++ b/inire/_snapshot.py @@ -0,0 +1,36 @@ +"""Read-only, insertion-ordered snapshots of public mappings.""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from types import MappingProxyType +from typing import TypeVar + +_K = TypeVar("_K") +_V = TypeVar("_V") + + +class _Snapshot(Mapping[_K, _V]): + __slots__ = ("_data",) + + def __init__(self, source: Mapping[_K, _V]) -> None: + self._data = MappingProxyType(dict(source)) + + def __getitem__(self, key: _K) -> _V: + return self._data[key] + + def __iter__(self) -> Iterator[_K]: + return iter(self._data) + + def __len__(self) -> int: + return len(self._data) + + def __repr__(self) -> str: + return repr(self._data.copy()) + + def __reduce__(self) -> tuple[type[_Snapshot[_K, _V]], tuple[dict[_K, _V]]]: + return type(self), (self._data.copy(),) + + +def snapshot(source: Mapping[_K, _V]) -> Mapping[_K, _V]: + return source if isinstance(source, _Snapshot) else _Snapshot(source) diff --git a/inire/layout.py b/inire/layout.py index 92e149f..6583679 100644 --- a/inire/layout.py +++ b/inire/layout.py @@ -4,12 +4,13 @@ from __future__ import annotations from dataclasses import dataclass, replace from math import fsum, isclose, isfinite -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Literal from shapely import set_precision, union_all from shapely.geometry import LineString from inire import route +from inire._snapshot import snapshot from inire.constants import TOLERANCE_LINEAR from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import rotate_cardinal @@ -43,13 +44,43 @@ class PlacedPort: @dataclass(frozen=True, slots=True) -class ExportVerification: - geometry_by_net: dict[str, tuple[Polygon, ...]] - reports_by_net: dict[str, RoutingReport] +class ExportNetCheck: + net_id: str + polygons: tuple[Polygon, ...] + report: RoutingReport + source: Literal["route", "fixed"] = "route" + on_grid: bool = True + profile_revision: str | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "polygons", tuple(self.polygons)) @property def is_valid(self) -> bool: - return all(report.is_valid for report in self.reports_by_net.values()) + return self.on_grid and self.report.is_valid + + +@dataclass(frozen=True, slots=True) +class ExportVerification: + checks_by_net: Mapping[str, ExportNetCheck] + grid: float + layer: tuple[int, int] | None = None + meters_per_unit: float | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "checks_by_net", snapshot(self.checks_by_net)) + + @property + def geometry_by_net(self) -> Mapping[str, tuple[Polygon, ...]]: + return snapshot({key: check.polygons for key, check in self.checks_by_net.items() if check.source == "route"}) + + @property + def reports_by_net(self) -> Mapping[str, RoutingReport]: + return snapshot({key: check.report for key, check in self.checks_by_net.items() if check.source == "route"}) + + @property + def is_valid(self) -> bool: + return all(check.is_valid for check in self.checks_by_net.values()) def verify_export_grid( @@ -59,10 +90,17 @@ def verify_export_grid( grid: float, ) -> ExportVerification: """Round and check the supplied routes together against the problem's keepouts.""" + paths = _round_paths(problem, results, grid) + return ExportVerification(_check_rounded_paths(_install_export_paths(problem, paths), paths), grid) + + +def _round_paths( + problem: RoutingProblem, results: Mapping[str, RoutingResult], grid: float, +) -> dict[str, tuple[ComponentResult, ...]]: if not isfinite(grid) or grid <= 0: raise ValueError("Export grid must be finite and positive") nets = {net.net_id: net for net in problem.nets} - paths: dict[str, tuple[ComponentResult, ...]] = {} + paths = {} for net_id, result in results.items(): net = nets.get(net_id) if net is None or net_id != result.net_id: @@ -71,19 +109,29 @@ def verify_export_grid( raise ValueError(f"Export result {net_id!r} must already be verified") _check_export_net(net, result) paths[net_id] = tuple(_round_component(component, grid) for component in result.path) + return paths + +def _install_export_paths(problem: RoutingProblem, paths: Mapping[str, tuple[ComponentResult, ...]]) -> RoutingWorld: world = RoutingWorld.from_problem(problem) for net_id, path in paths.items(): # Invalid snapped outlines still get a report. Only valid polygons can enter the index. if all(component.physical_checks[0] for component in path): world.install_path(net_id, path) - return ExportVerification( - geometry_by_net={ - net_id: tuple(polygon for component in path for polygon in component.physical_geometry) - for net_id, path in paths.items() - }, - reports_by_net={net_id: world.verify_path_report(net_id, path) for net_id, path in paths.items()}, - ) + return world + + +def _check_rounded_paths( + world: RoutingWorld, paths: Mapping[str, tuple[ComponentResult, ...]], +) -> dict[str, ExportNetCheck]: + return { + net_id: ExportNetCheck( + net_id, + tuple(polygon for component in path for polygon in component.physical_geometry), + world.verify_path_report(net_id, path), + ) + for net_id, path in paths.items() + } def _check_export_net(net: NetSpec, result: RoutingResult) -> None: diff --git a/inire/model.py b/inire/model.py index 9f182fb..5f12e4c 100644 --- a/inire/model.py +++ b/inire/model.py @@ -8,13 +8,14 @@ from typing import TYPE_CHECKING, Literal from shapely.geometry import Polygon +from inire._snapshot import snapshot from inire.geometry.components import _has_port_face, bend_fits_width from inire.geometry.primitives import Port 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 collections.abc import Iterable, Iterator, Mapping from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry from inire.results import RoutingResult @@ -318,7 +319,7 @@ class RoutingProblem: bounds: tuple[float, float, float, float] nets: tuple[NetSpec, ...] = () static_obstacles: tuple[Polygon, ...] = () - initial_paths: dict[str, PathSeed] = field(default_factory=dict) + initial_paths: Mapping[str, PathSeed] = field(default_factory=dict) clearance: float = 2.0 safety_zone_radius: float = 0.0021 self_clearance: float = 0.0 @@ -358,7 +359,7 @@ class RoutingProblem: if obstacle.is_empty or not obstacle.is_valid: raise ValueError(f"static_obstacles[{index}] must be nonempty and valid") object.__setattr__(self, "static_obstacles", obstacles) - initial_paths = dict(self.initial_paths) + initial_paths = snapshot(self.initial_paths) if any(not isinstance(seed, PathSeed) for seed in initial_paths.values()): raise TypeError("RoutingProblem.initial_paths values must be PathSeed instances") object.__setattr__( diff --git a/inire/results.py b/inire/results.py index 2ca52ef..d809f05 100644 --- a/inire/results.py +++ b/inire/results.py @@ -3,10 +3,11 @@ from __future__ import annotations from dataclasses import dataclass, field, fields from typing import TYPE_CHECKING, Literal +from inire._snapshot import snapshot from inire.seeds import PathSeed if TYPE_CHECKING: - from collections.abc import Iterable + from collections.abc import Iterable, Mapping from shapely.geometry import Polygon @@ -381,7 +382,7 @@ class AutomaticRoutingReport: @dataclass(frozen=True, slots=True) class RoutingRunResult: - results_by_net: dict[str, RoutingResult] + results_by_net: Mapping[str, RoutingResult] metrics: RouteMetrics expanded_nodes: tuple[tuple[int, int, int], ...] = () conflict_trace: tuple[ConflictTraceEntry, ...] = () @@ -390,3 +391,6 @@ class RoutingRunResult: iteration_trace: tuple[IterationTraceEntry, ...] = () topology: TopologyReport | None = None automatic: AutomaticRoutingReport | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "results_by_net", snapshot(self.results_by_net)) diff --git a/inire/tests/test_layout.py b/inire/tests/test_layout.py index 2c302e5..f83b27a 100644 --- a/inire/tests/test_layout.py +++ b/inire/tests/test_layout.py @@ -1,3 +1,5 @@ +import pickle +from copy import deepcopy from dataclasses import replace import pytest @@ -268,3 +270,51 @@ 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_export_and_routing_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()) + original = dict(run.results_by_net) + export = verify_export_grid(problem, original, grid=1) + original.clear() + + with pytest.raises(TypeError): + problem.initial_paths["track"] = PathSeed(()) + with pytest.raises(TypeError): + del run.results_by_net["track"] + with pytest.raises(TypeError): + export.geometry_by_net["track"] = (box(0, 0, 1, 1),) + with pytest.raises(TypeError): + del export.reports_by_net["track"] + with pytest.raises(TypeError): + del export.checks_by_net["track"] + + copied = dict(export.geometry_by_net) + copied.clear() + assert tuple(export.geometry_by_net) == ("track",) + assert export.is_valid + 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) + export = verify_export_grid(problem, run.results_by_net, grid=1) + for copy in (deepcopy, lambda value: pickle.loads(pickle.dumps(value))): + assert copy(problem) == problem + assert copy(export) == export + 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