inire/inire/tests/test_layout.py
Jan Petykiewicz 5f88e02775 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.
2026-11-30 19:30:10 -08:00

245 lines
12 KiB
Python

import pickle
from copy import deepcopy
from dataclasses import asdict, replace
from json import dumps, loads
import pytest
from shapely import set_precision, union_all
from shapely.geometry import box
from inire import (
Bend90Seed, CongestionOptions, FixedRoute, NetSpec, PathSeed, Port, RefinementOptions,
RoutingOptions, RoutingProblem, SBendOutline, SearchOptions, StraightSeed, TopologyOptions, route,
)
from inire.tests.layout_helpers import PlacedPort, partition_layers, preserves_length, route_profiles
_REPLAY = RoutingOptions(search=SearchOptions(node_limit=0), refinement=RefinementOptions(enabled=False))
def test_declared_port_width_check_requires_transition_for_wider_device() -> None:
source = PlacedPort(Port(10000, 10000, 0), 500)
target = PlacedPort(Port(110000, 10000, 0), 3000)
with pytest.raises(ValueError, match="joins widths 500 and 3000"):
source.connect("wide", target)
inlet = PlacedPort(Port(70000, 10000, 0), 500)
net = source.connect("before_taper", inlet)
assert net.width == 500
assert net.target == inlet.port
rotated = replace(source, port=source.port.rotated(90)).connect("rotated", replace(inlet, port=inlet.port.rotated(90)))
assert rotated.start.r == rotated.target.r == 90
@pytest.mark.parametrize(("outer_radius", "valid"), [(3069, False), (3070, True)])
def test_replay_verifies_actual_concentric_bend_clearance(outer_radius, valid) -> None:
center_x, center_y = 3000, 6070
inner = NetSpec("inside", Port(center_x, center_y - 2500, 0), Port(center_x + 2500, center_y, 90), 490)
outer = NetSpec("outside", Port(center_x, center_y - outer_radius, 0), Port(center_x + outer_radius, center_y, 90), 509.94)
seeds = {"inside": PathSeed((Bend90Seed(2500, "CCW"),)), "outside": PathSeed((Bend90Seed(outer_radius, "CCW"),))}
problem = RoutingProblem((0, 0, 7000, 7000), (inner, outer), initial_paths=seeds, clearance=70)
options = replace(_REPLAY, search=replace(_REPLAY.search, bend_radii=(2500, outer_radius)))
results = route(problem, options=options).results_by_net
for net_id, result in results.items():
assert result.as_seed() == seeds[net_id]
assert result.is_valid is valid
assert result.report.dynamic_collision_count == int(not valid)
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) == {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_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,))
options = RoutingOptions(
search=SearchOptions(node_limit=50, bend_radii=(10, 20), sbend_radii=(), bend_proxy_geometry="clipped_bbox", bend_clip_margin=9),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
result = route(problem, options=options).results_by_net[net.net_id]
assert result.is_valid
assert result.as_seed() == PathSeed((StraightSeed(10), Bend90Seed(10, "CCW"), StraightSeed(10)))
@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)
problem = RoutingProblem(
(0, 0, 100, 50), (net,), initial_paths={net.net_id: PathSeed((StraightSeed(80),))}, clearance=clearance,
)
reports = []
for polygon in (obstacle, set_precision(obstacle, 1, mode="pointwise")):
with_obstacle = replace(problem, fixed_routes=(FixedRoute("existing", (polygon,)),)) if fixed else replace(
problem, static_obstacles=(polygon,),
)
result = route(with_obstacle, options=_REPLAY).results_by_net[net.net_id]
assert result.is_valid is valid
assert result.locked_geometry[0].bounds == (10, 19.25, 90, 20.75)
reports.append(result.report)
assert reports[0] == reports[1]
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)
problem = RoutingProblem((0, 0, 220000, 95000), (flux, feed), clearance=3000)
options = RoutingOptions(
search=SearchOptions(node_limit=80, bend_radii=(15000,), sbend_radii=()),
refinement=RefinementOptions(enabled=False),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode="off"),
)
feed_profile = replace(options, search=replace(options.search, bend_radii=(50000,)))
profiles = ((("flux",), options), (("feed",), feed_profile))
restricted = route_profiles(problem, profiles)
assert restricted["flux"].is_valid
assert not restricted["feed"].is_valid
feed = replace(feed, target=Port(150000, 70000, 90))
open_board = replace(problem, nets=(flux, feed))
both = route_profiles(open_board, profiles)
assert both["feed"].as_seed() == PathSeed((Bend90Seed(50000, "CCW"),))
assert all(result.is_valid for result in both.values())
stale_hint = replace(open_board, initial_paths={"feed": PathSeed((Bend90Seed(15000, "CCW"),))})
recovered = route_profiles(stale_hint, profiles)
assert all(result.is_valid for result in recovered.values())
assert recovered["feed"].as_seed() == both["feed"].as_seed()
assert recovered["feed"].report.seed_error == "Initial path for 'feed' uses radius 15000 outside bend_radii"
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)
geometry = {}
for layer, nets in partition_layers((((1, 0), silicon), ((4, 0), nitride))).items():
problem = RoutingProblem(
(0, 0, 20000, 20000), nets,
initial_paths={net.net_id: PathSeed((StraightSeed(18000),)) for net in nets},
)
result, = route(problem, options=_REPLAY).results_by_net.values()
assert result.is_valid
assert result.effective_net == nets[0]
assert result.as_seed() == problem.initial_paths[result.net_id]
geometry[layer] = union_all(result.locked_geometry)
assert set(geometry) == {(1, 0), (4, 0)}
assert all(shape.geom_type == "Polygon" for shape in geometry.values())
assert geometry[1, 0].intersection(geometry[4, 0]).area > 0
def test_authored_template_lengths_are_used_for_candidate_acceptance() -> None:
net = NetSpec("arm", Port(20, 20, 0), Port(30, 30, 90))
problem = RoutingProblem((0, 0, 100, 100), (net,))
outline = box(0, -11, 11, -9).union(box(9, -11, 11, 0))
options = RoutingOptions(search=SearchOptions(
node_limit=100, bend_radii=(10,), bend_physical_geometry=outline, bend_physical_length=18.7,
))
result = route(problem, options=options).results_by_net["arm"]
assert preserves_length(result, 18.7, tolerance=1e-6)
assert not preserves_length(result, 37.4, tolerance=1e-6)
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)),
)
outline = SBendOutline(40, 50, 2, polygon, length=95)
net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0))
seed = PathSeed(())
search = SearchOptions(node_limit=80, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline,))
problem = RoutingProblem((0, 0, 110, 110), (net,))
options = RoutingOptions(search=search)
result = route(problem, options=options).results_by_net["shift"]
assert result.as_seed() != seed
replay = route(
replace(problem, initial_paths={"shift": result.as_seed()}),
options=replace(options, search=replace(search, node_limit=0)),
).results_by_net["shift"]
assert preserves_length(replay, 95, tolerance=0)