266 lines
14 KiB
Python
266 lines
14 KiB
Python
"""Timing models, ranked alternatives, and bounded matching."""
|
|
|
|
from dataclasses import replace
|
|
from math import sqrt
|
|
|
|
import pytest
|
|
from shapely.geometry import LineString, Polygon, box
|
|
|
|
from inire._catalog import BendVariant, Catalog, Evaluation, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant
|
|
from inire._catalog_timing import Delay, DelayModel
|
|
from inire.router import _catalog_layout, _catalog_tuning
|
|
from inire.router._catalog_layout import CatalogNet, LayoutResult, LayoutSettings, _layout_rank, route_layout
|
|
from inire.router._catalog_matching import MatchGroup, MatchResult
|
|
from inire.router._catalog_search import SearchResult
|
|
from inire.router._catalog_tuning import tune_group, window_replacements
|
|
from inire.router._catalog_verify import replay_moves, verify_path
|
|
|
|
|
|
@pytest.mark.parametrize("units", ["optical_length", "seconds"])
|
|
def test_matching_retries_a_more_expensive_baseline_across_a_fixed_crossing(units) -> None:
|
|
meter_per_unit = 1e-6
|
|
scale = meter_per_unit / 299_792_458 if units == "seconds" else 1
|
|
evaluator = MoveEvaluator(Grid((0, 0), 1, meter_per_unit), Catalog(
|
|
"crossing", {"g": Profile("ridge", 2)}, {"regular": StraightVariant("g", 1), "slow": StraightVariant("g", 2)},
|
|
))
|
|
nets = {
|
|
"after-crossing": CatalogNet(Pose(5, 5, 0, "g"), Pose(40, 5, 0, "g")),
|
|
"reference": CatalogNet(Pose(5, 15, 0, "g"), Pose(40, 15, 0, "g")),
|
|
}
|
|
observations = []
|
|
|
|
def fixed_side(wavelength):
|
|
observations.append(("fixed-route", wavelength))
|
|
return 100 if wavelength == 1.55e-6 else 50
|
|
|
|
def crossing(wavelength):
|
|
observations.append(("crossing", wavelength))
|
|
return 5
|
|
|
|
def group_index(wavelength, _angle):
|
|
observations.append(("straight", wavelength))
|
|
return 4 if wavelength == 1.55e-6 else 3
|
|
|
|
timing = DelayModel(
|
|
1.3e-6, group_indices={"g": group_index}, variant_delays={"slow": lambda _move, wavelength: 145 if wavelength == 1.55e-6 else 50},
|
|
fixed_contributions={"after-crossing": (fixed_side, crossing), "reference": (110,)},
|
|
)
|
|
settings = LayoutSettings(box(0, 0, 50, 20), node_limit=30, refinement=False)
|
|
report = route_layout(evaluator, nets, settings, timing=timing)
|
|
normal = report.routes["after-crossing"].path
|
|
assert normal is not None
|
|
assert normal[0].move.variant == "regular"
|
|
assert report.completed == tuple(nets)
|
|
assert report.delays["after-crossing"].optical_length == 160
|
|
assert all(wavelength == 1.3e-6 for _, wavelength in observations)
|
|
observations.clear()
|
|
|
|
group = MatchGroup("timing", {"after-crossing": 0, "reference": 0}, 1.55e-6, 0.05 * scale, units=units)
|
|
matched = route_layout(evaluator, nets, settings, timing=timing, groups=(group,))
|
|
chosen = matched.routes["after-crossing"].path
|
|
assert matched.completed == tuple(nets)
|
|
assert chosen is not None
|
|
assert chosen[0].move.variant == "slow"
|
|
assert matched.matching["timing"].delays["after-crossing"].optical_length == 250
|
|
assert matched.matching["timing"].skew == 0
|
|
assert {"fixed-route", "crossing", "straight"} <= {name for name, _ in observations}
|
|
assert all(wavelength == group.wavelength for _, wavelength in observations)
|
|
|
|
restricted = MoveEvaluator(evaluator.grid, replace(evaluator.catalog, variants={"regular": StraightVariant("g", 1)}))
|
|
unmatched = route_layout(restricted, nets, settings, timing=timing, groups=(group,))
|
|
assert unmatched.completed == ()
|
|
assert all(candidate.path is not None for candidate in unmatched.routes.values())
|
|
assert unmatched.matching["timing"].skew == pytest.approx(5 * scale, abs=1e-12 * scale)
|
|
assert unmatched.matching["timing"].status == "unmatched"
|
|
|
|
|
|
@pytest.mark.parametrize(("limit", "expected_status", "expected_skew"), [
|
|
(0, "unmatched", 1), (1, "unmatched", 0.2), (2, "unmatched", 0.2), (3, "matched", 0), (4, "matched", 0),
|
|
])
|
|
def test_tuning_budget_keeps_the_best_verified_delay_choices(monkeypatch, limit, expected_status, expected_skew) -> None:
|
|
# The second proposal is for b. Its baseline remains eligible and pairs
|
|
# more closely with a's first improvement.
|
|
catalog = Catalog(
|
|
"timing-budget", {"g": Profile("ridge", 1)},
|
|
{name: StraightVariant("g", 1) for name in ("base-a", "base-b", "middle", "last")},
|
|
)
|
|
evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), catalog)
|
|
board = box(0, 0, 20, 20)
|
|
terminals = {
|
|
"a": (Pose(2, 4, 0, "g"), Pose(17, 4, 0, "g")),
|
|
"b": (Pose(2, 8, 0, "g"), Pose(17, 8, 0, "g")),
|
|
}
|
|
|
|
def recipe(name, variant):
|
|
return replay_moves(evaluator, terminals[name][0], (Move(variant, steps=15),))
|
|
|
|
base = {name: recipe(name, f"base-{name}") for name in terminals}
|
|
proposals = {"a": (recipe("a", "middle"), recipe("a", "last")), "b": (recipe("b", "last"),)}
|
|
|
|
def replacements(_evaluator, path, _window):
|
|
return iter(proposals["a" if path[0].start.y == 4 else "b"])
|
|
|
|
monkeypatch.setattr(_catalog_tuning, "window_replacements", replacements)
|
|
timing = DelayModel(1.55e-6, variant_delays={"base-a": 400, "base-b": 401, "middle": 400.8, "last": 401.6})
|
|
group = MatchGroup("budget", {"a": 0, "b": 0}, 1.55e-6, 0.05)
|
|
windows = {"a": box(2, 2, 17, 6), "b": box(2, 6, 17, 10)}
|
|
|
|
report, changes = tune_group(
|
|
evaluator, group, timing, base, windows,
|
|
lambda name, path: verify_path(evaluator, path, *terminals[name], board=board) is None,
|
|
proposal_limit=limit,
|
|
)
|
|
assert report.status == expected_status
|
|
assert report.skew == pytest.approx(expected_skew)
|
|
assert report.budget_exhausted == (limit < 4)
|
|
if limit == 0:
|
|
assert not changes
|
|
if limit == 1:
|
|
assert changes == {"a": proposals["a"][0]}
|
|
|
|
|
|
def test_missing_fixed_contribution_leaves_the_verified_geometry_available() -> None:
|
|
evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("unknown", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)}))
|
|
nets = {"member": CatalogNet(Pose(5, 5, 0, "g"), Pose(40, 5, 0, "g"))}
|
|
settings = LayoutSettings(box(0, 0, 50, 20))
|
|
model = DelayModel(1.55e-6, group_indices={"g": 4}, fixed_contributions={"member": (None,)})
|
|
report_only = route_layout(evaluator, nets, settings, timing=model)
|
|
assert report_only.completed == ("member",)
|
|
assert report_only.delays["member"] is None
|
|
grouped = route_layout(evaluator, nets, settings, timing=model, groups=(MatchGroup("requires-fixed", {"member": 0}, 1.55e-6, 0.05),))
|
|
assert grouped.completed == ()
|
|
assert grouped.routes["member"].path == report_only.routes["member"].path
|
|
assert grouped.matching["requires-fixed"].status == "missing_delay"
|
|
assert not grouped.matching["requires-fixed"].budget_exhausted
|
|
|
|
|
|
@pytest.mark.parametrize("reverse_order", [False, True])
|
|
def test_adjacent_windows_keep_clearance_for_the_other_owner(reverse_order) -> None:
|
|
square = box(0, -1, 16, 1)
|
|
protruding = Polygon(((0, -1), (16, -1), (16, 1), (12, 1), (10, 1.1), (6, 1.1), (4, 1), (0, 1)))
|
|
profiles = {"g": Profile("ridge", 2)}
|
|
altered = FixedVariant(
|
|
"protruding", {"in": Pose(0, 0, 0, "g"), "out": Pose(16, 0, 180, "g")},
|
|
(protruding,), (("in", "out"),), (Orientation(),), 1, 16,
|
|
)
|
|
safe = replace(altered, cell="safe", footprints=(square,))
|
|
variants = {"s": StraightVariant("g", 1), "protruding": altered, "safe": safe}
|
|
evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("adjacent", profiles, variants))
|
|
settings = LayoutSettings(box(0, 0, 24, 22), clearance=1, node_limit=0, refinement=False)
|
|
windows = {"a": box(2, 8, 18, 12), "b": box(2, 12, 18, 16)}
|
|
timing = DelayModel(1.55e-6, group_indices={"g": 4}, variant_delays={"protruding": 64, "safe": 64})
|
|
group = MatchGroup("adjacent", {"a": 0, "b": 0}, 1.55e-6, 0)
|
|
for candidate in ("safe", "protruding"):
|
|
nets = {
|
|
"a": CatalogNet(Pose(2, 10, 0, "g"), Pose(18, 10, 0, "g"), seed=(Move(candidate, traversal=("in", "out")),)),
|
|
"b": CatalogNet(Pose(2, 14, 0, "g"), Pose(18, 14, 0, "g"), seed=(Move("s", steps=16),)),
|
|
}
|
|
if reverse_order:
|
|
nets = dict(reversed(tuple(nets.items())))
|
|
result = route_layout(evaluator, nets, settings, timing=timing, groups=(group,), windows=windows)
|
|
if candidate == "safe":
|
|
assert result.completed == tuple(nets)
|
|
assert result.matching["adjacent"].complete
|
|
else:
|
|
assert result.completed == ()
|
|
assert result.routes["a"].path is None
|
|
assert result.matching["adjacent"].status == "unrouted"
|
|
|
|
|
|
def test_four_completed_independent_nets_outrank_a_three_net_match() -> None:
|
|
evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("ranking", {"g": Profile("ridge", 2)}, {
|
|
"low": StraightVariant("g", 1), "high": StraightVariant("g", 2),
|
|
}))
|
|
low = {}
|
|
high = {}
|
|
for i in range(4):
|
|
start = Pose(2, i * 5 + 2, 0, "g")
|
|
name = f"net{i}"
|
|
low[name] = SearchResult(replay_moves(evaluator, start, (Move("low", steps=6),)), "verified", 0, 0)
|
|
high[name] = SearchResult(replay_moves(evaluator, start, (Move("high", steps=8),)), "verified", 0, 0)
|
|
report = MatchResult("matched", "matched", {}, 0.0)
|
|
three = LayoutResult(low, tuple(low)[:3], matching={"matched": report})
|
|
four = LayoutResult(high, tuple(high))
|
|
assert _layout_rank(four) < _layout_rank(three)
|
|
assert _layout_rank(LayoutResult(low, tuple(low))) < _layout_rank(four)
|
|
|
|
|
|
def test_final_layout_verification_preserves_the_incumbent_on_a_conflicting_match(monkeypatch) -> None:
|
|
evaluator = MoveEvaluator(
|
|
Grid((0, 0), 1, 1e-6), Catalog("joint-verification", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)}),
|
|
)
|
|
board = box(0, 0, 30, 30)
|
|
nets = {
|
|
name: CatalogNet(Pose(4, y, 0, "g"), Pose(26, y, 0, "g"), seed=(Move("s", steps=22),))
|
|
for name, y in (("a", 9), ("b", 21))
|
|
}
|
|
groups = (MatchGroup("joint", {"a": 0, "b": 4}, 1.55e-6, 0.05),)
|
|
originals = {name: evaluator.evaluate(net.seed[0], net.start) for name, net in nets.items()}
|
|
proposed = {}
|
|
for name, net in nets.items():
|
|
line = LineString(((4, net.start.y), (8, net.start.y), (12, 15), (18, 15), (22, net.target.y), (26, net.target.y)))
|
|
proposed[name] = (Evaluation(Move("s", steps=22), net.start, net.target, (line.buffer(1, cap_style="flat"),), line.length, 1),)
|
|
other = originals["b" if name == "a" else "a"]
|
|
assert other is not None
|
|
assert verify_path(evaluator, proposed[name], net.start, net.target, board=board, occupied=other.footprints) is None
|
|
|
|
original_tune = _catalog_layout.tune_group
|
|
|
|
def conflicting_tune(evaluator, group, timing, baselines, windows, verifies, *, proposal_limit):
|
|
if proposal_limit == 0:
|
|
return original_tune(evaluator, group, timing, baselines, windows, verifies, proposal_limit=0)
|
|
return MatchResult("joint", "matched", {"a": Delay(100, 0), "b": Delay(104, 0)}, 0.0), proposed
|
|
|
|
monkeypatch.setattr(_catalog_layout, "tune_group", conflicting_tune)
|
|
timing = DelayModel(1.55e-6, group_indices={"g": 4})
|
|
result = route_layout(evaluator, nets, LayoutSettings(board, node_limit=0, refinement=False), timing=timing, groups=groups)
|
|
assert result.completed == ()
|
|
assert result.matching["joint"].status == "unmatched"
|
|
assert result.matching["joint"].skew == 4
|
|
assert {name: report.path for name, report in result.routes.items()} == {name: (move,) for name, move in originals.items()}
|
|
|
|
|
|
@pytest.mark.parametrize(("poses", "expected"), [
|
|
((((20, 40, 0), (120, 40, 0)), ((120, 70, 180), (20, 70, 180)), ((160, 20, 90), (160, 120, 90))), 400),
|
|
((((20, 160, 45), (50, 190, 45)), ((90, 190, 225), (60, 160, 225)), ((130, 190, 315), (160, 160, 315))), 120 * sqrt(2)),
|
|
])
|
|
def test_cardinal_and_diagonal_directions_match_on_total_delay(poses, expected) -> None:
|
|
evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("axes", {"g": Profile("ridge", 4)}, {"s": StraightVariant("g", 1)}))
|
|
nets = {
|
|
str(i): CatalogNet(Pose(*a, "g"), Pose(*b, "g")) for i, (a, b) in enumerate(poses)
|
|
}
|
|
settings = LayoutSettings(box(0, 0, 400, 300), clearance=1)
|
|
timing = DelayModel(1.55e-6, group_indices={"g": 4})
|
|
group = MatchGroup("matched", dict.fromkeys(nets, 0.0), 1.55e-6, 0.05)
|
|
result = route_layout(evaluator, nets, settings, timing=timing, groups=(group,))
|
|
assert result.completed == tuple(nets)
|
|
report = result.matching["matched"]
|
|
assert report.skew == 0
|
|
assert [delay.optical_length for delay in report.delays.values()] == pytest.approx([expected] * 3)
|
|
repeated = MatchGroup("duplicate", {"0": 0}, 1.55e-6, 0)
|
|
with pytest.raises(ValueError, match="multiple groups"):
|
|
route_layout(evaluator, nets, settings, timing=timing, groups=(group, repeated))
|
|
|
|
|
|
def test_four_turn_tuning_includes_the_window_edge_and_rejects_protrusion() -> None:
|
|
evaluator = MoveEvaluator(
|
|
Grid((0, 0), 1, 1e-6), Catalog("boundary", {"g": Profile("ridge", 4)}, {
|
|
"s": StraightVariant("g", 1),
|
|
"left": BendVariant("g", 90, 10, 0.01, sagitta=0.01),
|
|
"right": BendVariant("g", -90, 10, 0.01, sagitta=0.01),
|
|
}),
|
|
)
|
|
original = replay_moves(evaluator, Pose(20, 120, 0, "g"), (Move("s", steps=120),))
|
|
assert original is not None
|
|
exact = box(40, 115, 100, 152)
|
|
outside = box(40, 115, 100, 151.99)
|
|
boundary_candidates = [
|
|
path for path in window_replacements(evaluator, original, exact) if path is not None
|
|
and any(shape.bounds[3] == 152 for move in path for shape in move.footprints)
|
|
]
|
|
assert boundary_candidates
|
|
for path in boundary_candidates:
|
|
assert verify_path(evaluator, path, original[0].start, original[0].end, board=box(0, 0, 400, 300)) is None
|
|
accepted = tuple(path for path in window_replacements(evaluator, original, outside) if path is not None)
|
|
assert accepted
|
|
assert all(path not in accepted for path in boundary_candidates)
|