Preserve structured serialization of routing snapshots
Allow dataclass and JSON conversion to traverse seed and result mappings while keeping the public snapshot mutation methods read-only.
This commit is contained in:
parent
8a97c1e64b
commit
725f385ba3
3 changed files with 38 additions and 17 deletions
|
|
@ -53,6 +53,8 @@ The fields below appear in constructor order. Use one layout unit for coordinate
|
||||||
|
|
||||||
Check `is_valid` and keep the effective net and geometry settings with each placement recipe. [Placement workflow](route-a-layout.md#save-a-placement-recipe)
|
Check `is_valid` and keep the effective net and geometry settings with each placement recipe. [Placement workflow](route-a-layout.md#save-a-placement-recipe)
|
||||||
|
|
||||||
|
For structured logging, `dataclasses.asdict(run)` preserves the per-net fields. Choose how to encode the Shapely polygons when writing JSON.
|
||||||
|
|
||||||
## Options and defaults
|
## Options and defaults
|
||||||
|
|
||||||
`RoutingOptions` accepts six option groups. Each group uses the defaults in its table when omitted.
|
`RoutingOptions` accepts six option groups. Each group uses the defaults in its table when omitted.
|
||||||
|
|
|
||||||
|
|
@ -2,34 +2,36 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections.abc import Iterator, Mapping
|
from typing import Never, Self, TYPE_CHECKING, TypeVar
|
||||||
from types import MappingProxyType
|
|
||||||
from typing import TypeVar
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterable, Mapping
|
||||||
|
|
||||||
_K = TypeVar("_K")
|
_K = TypeVar("_K")
|
||||||
_V = TypeVar("_V")
|
_V = TypeVar("_V")
|
||||||
|
|
||||||
|
|
||||||
class _Snapshot(Mapping[_K, _V]):
|
class _Snapshot(dict[_K, _V]):
|
||||||
__slots__ = ("_data",)
|
"""A read-only dict that dataclasses.asdict can traverse."""
|
||||||
|
|
||||||
def __init__(self, source: Mapping[_K, _V]) -> None:
|
__slots__ = ()
|
||||||
self._data = MappingProxyType(dict(source))
|
|
||||||
|
|
||||||
def __getitem__(self, key: _K) -> _V:
|
def __new__(cls, source: Mapping[_K, _V] | Iterable[tuple[_K, _V]]) -> Self:
|
||||||
return self._data[key]
|
result = super().__new__(cls)
|
||||||
|
dict.update(result, source)
|
||||||
|
return result
|
||||||
|
|
||||||
def __iter__(self) -> Iterator[_K]:
|
def __init__(self, _source: Mapping[_K, _V] | Iterable[tuple[_K, _V]]) -> None:
|
||||||
return iter(self._data)
|
# Populate only at allocation so reinitialization cannot change a snapshot.
|
||||||
|
pass
|
||||||
|
|
||||||
def __len__(self) -> int:
|
def _read_only(self, *_args: object, **_kwargs: object) -> Never:
|
||||||
return len(self._data)
|
raise TypeError("Snapshot mappings are read-only")
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
__setitem__ = __delitem__ = __ior__ = clear = pop = popitem = setdefault = update = _read_only
|
||||||
return repr(self._data.copy())
|
|
||||||
|
|
||||||
def __reduce__(self) -> tuple[type[_Snapshot[_K, _V]], tuple[dict[_K, _V]]]:
|
def __reduce__(self) -> tuple[type[_Snapshot[_K, _V]], tuple[dict[_K, _V]]]:
|
||||||
return type(self), (self._data.copy(),)
|
return type(self), (dict(self),)
|
||||||
|
|
||||||
|
|
||||||
def snapshot(source: Mapping[_K, _V]) -> Mapping[_K, _V]:
|
def snapshot(source: Mapping[_K, _V]) -> Mapping[_K, _V]:
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import pickle
|
import pickle
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from dataclasses import replace
|
from dataclasses import asdict, replace
|
||||||
|
from json import dumps, loads
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from shapely import set_precision, union_all
|
from shapely import set_precision, union_all
|
||||||
|
|
@ -241,6 +242,8 @@ def test_routing_inputs_and_results_are_detached_snapshots() -> None:
|
||||||
problem.initial_paths["track"] = PathSeed(())
|
problem.initial_paths["track"] = PathSeed(())
|
||||||
with pytest.raises(TypeError):
|
with pytest.raises(TypeError):
|
||||||
del run.results_by_net["track"]
|
del run.results_by_net["track"]
|
||||||
|
with pytest.raises(TypeError):
|
||||||
|
run.results_by_net.clear()
|
||||||
assert run.results_by_net["track"].is_valid
|
assert run.results_by_net["track"].is_valid
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -258,3 +261,17 @@ def test_read_only_snapshots_survive_python_copy_and_pickle() -> None:
|
||||||
replacement = replace(run, results_by_net=source)
|
replacement = replace(run, results_by_net=source)
|
||||||
source.clear()
|
source.clear()
|
||||||
assert replacement.results_by_net == run.results_by_net
|
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}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue