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.
335 lines
16 KiB
Python
335 lines
16 KiB
Python
import sys
|
|
from dataclasses import asdict, replace
|
|
from json import loads
|
|
|
|
import pytest
|
|
from shapely.geometry import box, shape
|
|
|
|
from inire import (
|
|
CongestionOptions, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, RoutingResult, RoutingRunResult,
|
|
SearchOptions, StraightSeed, TopologyOptions, route,
|
|
)
|
|
from inire.router import _automatic, _compact
|
|
from inire.router._astar_types import AStarMetrics
|
|
from inire.router._automatic import _AutomaticRun
|
|
from inire.router._capacity import port_conflicts
|
|
from inire.router._routing_policy import _disconnected_nets
|
|
from inire.router.cost import weighted_path_length
|
|
from inire.tests.routing_benchmarks import (
|
|
BENCHMARK_CASES,
|
|
CROSSING_BENCHMARK_CASES,
|
|
FALLBACK_BENCHMARK_CASES,
|
|
)
|
|
from inire.tests.routing_corpus import CASE_GROUPS, automatic_options, profile_options
|
|
from scripts.compare_topological_routing import (
|
|
_direct_trials,
|
|
_measure as _measure_selected_mode,
|
|
_mode_options,
|
|
main as run_benchmarks,
|
|
)
|
|
|
|
|
|
def _measure(case, options, strategy):
|
|
return _measure_selected_mode(case, _mode_options(options, strategy), strategy)
|
|
|
|
|
|
@pytest.mark.routing_corpus
|
|
def test_final_dogleg_can_reuse_incumbents_from_seed_fallback(monkeypatch) -> None:
|
|
short_shift_seed_set = _automatic.short_shift_seed_set
|
|
|
|
def full_shift_set(problem, search, score, **_kwargs):
|
|
return short_shift_seed_set(problem, search, score)
|
|
|
|
monkeypatch.setattr(_automatic, "short_shift_seed_set", full_shift_set)
|
|
(case,) = CASE_GROUPS["retry-holdout-reversed-bank"]
|
|
options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression")
|
|
|
|
run = route(case.problem, options=options)
|
|
|
|
assert run.automatic is not None
|
|
assert run.automatic.selected_planner == "residual-dogleg"
|
|
[fallback] = [stage for stage in run.automatic.stages if stage.policy == "seed-fallback" and stage.operation == "search"]
|
|
assert set(fallback.valid_net_ids) == {net.net_id for net in case.problem.nets if net.net_id != "outside_lower"}
|
|
assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets}
|
|
|
|
|
|
def test_weighted_local_shifts_can_pack_without_verifying_alternative_placements(monkeypatch) -> None:
|
|
(case,) = CASE_GROUPS["crossing-staggered-grid"]
|
|
weights = {"straight": 1.0, "bend90": 4.0, "sbend": 13.0}
|
|
|
|
def score(result):
|
|
return weighted_path_length(result.path, weights)
|
|
|
|
exhaustive = _compact.short_shift_seed_set(case.problem, case.options.search, score)
|
|
original = _compact._verified_candidates
|
|
seed_counts = []
|
|
|
|
def count_candidates(net, world, board, search, seeds):
|
|
seed_counts.append(len(seeds))
|
|
yield from original(net, world, board, search, seeds)
|
|
|
|
monkeypatch.setattr(_compact, "_verified_candidates", count_candidates)
|
|
packed = _compact.short_shift_seed_set(case.problem, case.options.search, score, length_weights=weights)
|
|
|
|
assert packed
|
|
assert packed == exhaustive
|
|
assert seed_counts == [1] * len(case.problem.nets)
|
|
|
|
|
|
def test_automatic_probe_caps_iterations_before_wider_retry(monkeypatch) -> None:
|
|
iterations = 3
|
|
probe_limit = 2
|
|
problem = RoutingProblem(
|
|
bounds=(0, 0, 200, 200),
|
|
nets=tuple(NetSpec(str(y), Port(10, y, 0), Port(190, y + 20, 0)) for y in (30, 60, 90)),
|
|
)
|
|
options = RoutingOptions(search=SearchOptions(node_limit=500))
|
|
options = replace(options, congestion=replace(options.congestion, max_iterations=iterations))
|
|
attempts = []
|
|
|
|
def unresolved_worker(_planner, problem, *, options, policy):
|
|
budgets = (options.search.node_limit, options.congestion.max_iterations)
|
|
attempts.append((policy, *budgets))
|
|
results = {net.net_id: RoutingResult(net.net_id, ()) for net in problem.nets}
|
|
return RoutingRunResult(results, AStarMetrics().snapshot())
|
|
|
|
monkeypatch.setattr(_AutomaticRun, "_run", unresolved_worker)
|
|
planner = _AutomaticRun(problem, options, None)
|
|
assert not planner._initial_search_trials(options, [], len(problem.nets))
|
|
assert attempts == [
|
|
("direct-probe-near-port", 100, probe_limit),
|
|
("direct-lookahead-retry", options.search.node_limit, iterations),
|
|
]
|
|
|
|
|
|
def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None:
|
|
case = next(case for case in CROSSING_BENCHMARK_CASES if case.name == "crossing-staggered-grid")
|
|
first, *others = case.problem.nets
|
|
# A 22-unit shift leaves a net unresolved after the early guide and exercises the retry.
|
|
problem = replace(case.problem, nets=(replace(first, target=first.target.translate(dy=2)), *others))
|
|
options = replace(
|
|
case.options,
|
|
search=replace(case.options.search, node_limit=101),
|
|
congestion=replace(case.options.congestion, max_iterations=1),
|
|
topology=TopologyOptions(mode="automatic"),
|
|
)
|
|
|
|
report = route(problem, options=options).automatic
|
|
|
|
assert report is not None
|
|
guided = [stage for stage in report.stages if stage.operation == "search" and stage.mode == "guide"]
|
|
assert [(stage.policy, stage.node_limit) for stage in guided] == [("early-guide", 101), ("direct-probe-near-port", 100)]
|
|
assert len(guided[0].valid_net_ids) < len(problem.nets)
|
|
|
|
|
|
def test_benchmark_profile_records_effective_options(tmp_path, monkeypatch) -> None:
|
|
case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == "fallback-custom-physical")
|
|
defaults = RoutingOptions()
|
|
output = tmp_path / "benchmark.json"
|
|
monkeypatch.setattr(
|
|
sys, "argv",
|
|
["bench", "--profile", "public-defaults", "--case", case.name, "--refinement", "on", "--refinement-windows", "1", "--json", str(output)],
|
|
)
|
|
|
|
run_benchmarks()
|
|
|
|
payload = loads(output.read_text())
|
|
[run] = payload["runs"]
|
|
assert payload["profile"] == "public-defaults"
|
|
assert run["requested_mode"] == "automatic"
|
|
options = run["options"]
|
|
geometry = case.options.search
|
|
assert options["search"]["bend_radii"] == list(geometry.bend_radii)
|
|
assert shape(options["search"]["bend_physical_geometry"]).equals(geometry.bend_physical_geometry)
|
|
[sample] = run["samples"]
|
|
assert payload["cost_metrics"] == {"valid_costs": "benchmark_weighted_length", "native_valid_costs": "native_objective"}
|
|
assert sample["native_valid_costs"].keys() == sample["valid_costs"].keys()
|
|
stage = sample["stages"][sample["selected_stage"]]
|
|
assert stage["planner"] == "lattice"
|
|
assert stage["mode"] == "off"
|
|
assert stage["operation"] == "search"
|
|
operations = {timing["operation"] for timing in sample["timings"]}
|
|
expected_refinement = replace(defaults.refinement, enabled=True, max_windows_per_net=1)
|
|
assert options["refinement"] == asdict(expected_refinement)
|
|
assert operations == {"search", "verify", "refine"}
|
|
assert options["search"]["node_limit"] == defaults.search.node_limit
|
|
assert options["objective"] == asdict(defaults.objective)
|
|
assert options["congestion"] == asdict(defaults.congestion)
|
|
assert options["topology"]["automatic_length_weights"] is None
|
|
|
|
|
|
def test_connectivity_screen_checks_each_net_width_and_leaves_unknown_ports_for_search() -> None:
|
|
problem = RoutingProblem(
|
|
bounds=(0, 0, 400, 160),
|
|
nets=(
|
|
NetSpec("narrow", Port(25, 74, 0), Port(375, 76, 0), width=2),
|
|
NetSpec("wide", Port(25, 90, 0), Port(375, 92, 0), width=8),
|
|
NetSpec("unknown", Port(160, 80, 0), Port(375, 110, 0), width=8),
|
|
),
|
|
static_obstacles=(box(150, 0, 170, 72), box(150, 88, 170, 160)),
|
|
clearance=6,
|
|
)
|
|
|
|
assert _disconnected_nets(problem, box(*problem.bounds), RoutingOptions(), {}) == frozenset({"wide"})
|
|
|
|
|
|
def test_budgeted_retry_shares_the_cap_when_both_lock_orders_leave_connected_space() -> None:
|
|
case = next(case for case in BENCHMARK_CASES if case.name == "blocking-turn-room")
|
|
options = replace(case.options, search=replace(case.options.search, node_limit=101))
|
|
|
|
result = _measure(case, options, "direct-lookahead-retry")
|
|
|
|
assert [stage.node_limit for stage in result.stages] == [50, 51]
|
|
assert [stage.direct_net_ids for stage in result.stages] == [("horizontal",), ("vertical",)]
|
|
assert all(not stage.skipped_net_ids for stage in result.stages)
|
|
assert result.nodes_expanded == sum(stage.nodes_expanded for stage in result.stages)
|
|
|
|
|
|
def test_automatic_recovers_a_complex_board_after_rejecting_a_hint() -> None:
|
|
(case,) = CASE_GROUPS["complex-routing-example-1"]
|
|
problem = replace(case.problem, initial_paths={"net_04": PathSeed((StraightSeed(2400),))})
|
|
options = replace(
|
|
case.options,
|
|
search=replace(case.options.search, node_limit=100),
|
|
topology=TopologyOptions(mode="automatic"),
|
|
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
|
|
refinement=replace(case.options.refinement, enabled=False),
|
|
)
|
|
|
|
run = route(problem, options=options)
|
|
|
|
assert set(run.automatic.verified_net_ids) == {net.net_id for net in problem.nets}
|
|
assert run.results_by_net["net_04"].as_seed() != problem.initial_paths["net_04"]
|
|
|
|
|
|
def test_point_terminal_replay_preserves_the_selected_port_headings() -> None:
|
|
(case,) = CASE_GROUPS["complex-routing-example-1-point-terminals"]
|
|
a, *others = case.problem.nets
|
|
problem = replace(case.problem, nets=(replace(a, start=a.start.translate(rotation=180)), *others))
|
|
options = replace(case.options, topology=replace(case.options.topology, mode="automatic"))
|
|
chosen = route(problem, options=options)
|
|
paths = chosen.results_by_net
|
|
assert all(path.is_valid for path in paths.values())
|
|
rebuilt = tuple(
|
|
replace(net, start=paths[net.net_id].path[0].start_port, target=paths[net.net_id].path[-1].end_port) for net in problem.nets
|
|
)
|
|
assert rebuilt[0].start.r != problem.nets[0].start.r
|
|
assert [net.net_id for net in rebuilt if net.target.r == 180] == ["net_08"]
|
|
seeds = {net_id: result.as_seed() for net_id, result in paths.items()}
|
|
replay_options = replace(
|
|
options, search=replace(options.search, node_limit=0), refinement=replace(options.refinement, enabled=False),
|
|
)
|
|
replay = route(replace(problem, nets=rebuilt, initial_paths=seeds), options=replay_options)
|
|
assert all(result.is_valid and result.locked_geometry == paths[net_id].locked_geometry for net_id, result in replay.results_by_net.items())
|
|
|
|
|
|
def test_bundle_first_reports_capacity_failure_and_uses_the_generic_fallback() -> None:
|
|
original = next(case for case in BENCHMARK_CASES if case.name == "terminal-bench-point-terminals")
|
|
case = replace(original, problem=replace(original.problem, clearance=7))
|
|
options = replace(case.options, search=replace(case.options.search, node_limit=20))
|
|
|
|
fallback = _measure(case, options, "direct-probe-near-port")
|
|
sample = _measure(case, options, "bundle-first")
|
|
|
|
assert sample.bundle_rejection is not None
|
|
assert "insufficient track capacity" in sample.bundle_rejection
|
|
assert sample.bundle_duration_s is not None
|
|
assert sample.stages == fallback.stages
|
|
assert sample.net_outcomes == fallback.net_outcomes
|
|
assert sample.valid_costs == fallback.valid_costs
|
|
|
|
|
|
def test_automatic_retry_releases_a_lock_that_disconnects_the_remaining_net() -> None:
|
|
case = next(case for case in BENCHMARK_CASES if case.name == "blocking-straight")
|
|
board = box(*case.problem.bounds)
|
|
options = replace(case.options, search=replace(case.options.search, node_limit=100), topology=TopologyOptions(mode="seed"))
|
|
first = _direct_trials(case.problem, board, options, "direct-guide")[0]
|
|
assert tuple(first.valid_costs) == ("horizontal",)
|
|
|
|
[retry] = _AutomaticRun(case.problem, options, None)._incumbent_trials(options, first, len(case.problem.nets))
|
|
|
|
assert retry.stage.kind == "incumbent-retry"
|
|
assert retry.stage.incumbent_net_ids == ("horizontal",)
|
|
assert retry.stage.retry_reason == "Incumbents disconnect vertical when locked"
|
|
|
|
|
|
def test_joint_portal_lane_retry_keeps_incumbents_and_verifies_another_net() -> None:
|
|
problem = RoutingProblem(
|
|
(0, 0, 580, 360),
|
|
tuple(
|
|
NetSpec(f"track{i}", Port(35, left, 0), Port(545, right, 0))
|
|
for i, (left, right) in enumerate(zip((45, 78, 114, 142, 173, 214), (130, 159, 187, 210, 249, 286), strict=True))
|
|
),
|
|
(box(265, 0, 315, 103.5), box(265, 136.5, 315, 206), box(265, 242, 315, 360)),
|
|
clearance=5,
|
|
)
|
|
options = RoutingOptions(search=SearchOptions(node_limit=500, bend_radii=(20,), sbend_radii=(20,)))
|
|
planner = _AutomaticRun(problem, options, None)
|
|
attempts = replace(options, refinement=replace(options.refinement, enabled=False))
|
|
small = replace(attempts, search=replace(attempts.search, node_limit=100))
|
|
first = planner._direct(small, "direct-probe-near-port")[0]
|
|
|
|
trials = planner._incumbent_trials(attempts, first, len(problem.nets))
|
|
|
|
ordinary, joint, *_ = trials
|
|
assert set(first.valid_costs) == {"track2", "track5"}
|
|
assert joint.stage.policy == "joint-portal-lanes"
|
|
assert set(joint.stage.incumbent_net_ids) == set(first.valid_costs)
|
|
assert not joint.selectable
|
|
assert set(ordinary.valid_costs) <= {"track2", "track3", "track5"}
|
|
assert any(trial.selectable and set(trial.valid_costs) == {"track2", "track3", "track5"} for trial in trials)
|
|
|
|
|
|
def test_automatic_weighted_scoring_preserves_coverage_and_reduces_cost() -> None:
|
|
case = next(case for case in BENCHMARK_CASES if case.name == "bypass-interleaved-directions")
|
|
baseline = _measure(case, case.options, "automatic-span")
|
|
weighted = _measure(case, case.options, "automatic")
|
|
|
|
assert len(weighted.valid_costs) == len(case.problem.nets)
|
|
assert weighted.valid_costs.keys() == baseline.valid_costs.keys()
|
|
assert sum(weighted.valid_costs.values()) < sum(baseline.valid_costs.values())
|
|
assert weighted.nodes_expanded == baseline.nodes_expanded == 0
|
|
assert weighted.cost_pass_performed
|
|
assert not baseline.cost_pass_performed
|
|
|
|
|
|
def test_automatic_can_force_weighted_scoring_when_the_selective_pass_is_skipped() -> None:
|
|
case = next(case for case in BENCHMARK_CASES if case.name == "serial-staircase")
|
|
options = replace(case.options, topology=TopologyOptions(mode="automatic"))
|
|
selective = route(case.problem, options=options)
|
|
forced = route(case.problem, options=replace(options, topology=replace(options.topology, automatic_cost="always")))
|
|
|
|
assert selective.automatic is not None
|
|
assert forced.automatic is not None
|
|
assert not selective.automatic.cost_pass_performed
|
|
assert forced.automatic.cost_pass_performed
|
|
assert set(selective.automatic.verified_net_ids) == set(forced.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets}
|
|
|
|
|
|
def test_port_spacing_certificate_keeps_input_order_in_mixed_width_bank() -> None:
|
|
nets = tuple(
|
|
NetSpec(name, Port(5, y, 0), Port(95, y + 40, 0), width)
|
|
for name, y, width in (("a", 15, 6), ("b", 19, 2), ("c", 11, 3), ("d", 18, 2), ("clear", 30, 2))
|
|
)
|
|
problem = RoutingProblem((0, 0, 100, 100), nets)
|
|
|
|
assert port_conflicts(problem, RoutingOptions()) == (("a", "b"),)
|
|
assert port_conflicts(replace(problem, nets=(nets[0], nets[2], nets[1], *nets[3:])), RoutingOptions()) == (("a", "c"), ("b", "d"))
|
|
|
|
|
|
def test_perimeter_residual_preserves_its_lock_and_verifies_the_layout(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
(case,) = CASE_GROUPS["terminal-bench-pair"]
|
|
options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression")
|
|
planner = _AutomaticRun(case.problem, options, None)
|
|
monkeypatch.setattr(_AutomaticRun, "_paired_perimeter", lambda *_args: None)
|
|
|
|
trials = planner._perimeter_trials(options)
|
|
|
|
residual = [trial for trial in trials if trial.stage.kind == "perimeter-residual"]
|
|
assert residual
|
|
assert all(trial.stage.mode == "guide" and len(trial.stage.direct_net_ids) == 1 for trial in residual)
|
|
assert all(not trial.stage.skipped_net_ids for trial in residual)
|
|
assert residual[-1].selection == "requires-layout-check"
|
|
assert trials[-1].selectable
|
|
assert trials[-1].stage.kind == "perimeter"
|
|
assert set(trials[-1].valid_costs) == {net.net_id for net in case.problem.nets}
|