363 lines
17 KiB
Python
363 lines
17 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_benchmark_case import BenchmarkCase
|
|
from inire.tests.routing_benchmarks import (
|
|
BENCHMARK_CASES,
|
|
CROSSING_BENCHMARK_CASES,
|
|
)
|
|
from inire.tests.routing_corpus import CASE_GROUPS, automatic_options, profile_options
|
|
from scripts.benchmark_retry_order import _measure as _measure_retry
|
|
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:
|
|
(fixture,) = CASE_GROUPS["fallback-custom-physical"]
|
|
search = replace(fixture.options.search, bend_physical_length=25)
|
|
case = replace(fixture, options=replace(fixture.options, search=search))
|
|
monkeypatch.setitem(CASE_GROUPS, case.name, (case,))
|
|
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)
|
|
assert options["search"]["bend_physical_length"] == geometry.bend_physical_length
|
|
[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_retry_experiment_records_worker_expansions() -> None:
|
|
(case,) = CASE_GROUPS["retry-holdout-floor-pocket"]
|
|
|
|
sample = _measure_retry(case, "public-defaults", "lattice-500")
|
|
|
|
[attempt] = sample["retry_attempts"]
|
|
[stage] = [stage for stage in sample["stages"] if stage["policy"] == "early-bounded-lattice"]
|
|
assert attempt["policy"] == "bounded-lattice"
|
|
assert 0 < attempt["nodes_expanded"] == stage["nodes_expanded"] <= sample["nodes_expanded"]
|
|
assert len(sample["verified"]) == case.routing_bound
|
|
|
|
|
|
def test_seed_order_locked_rejects_touching_routes_at_zero_clearance() -> None:
|
|
problem = RoutingProblem(
|
|
bounds=(0, 0, 100, 40),
|
|
nets=(NetSpec("a", Port(10, 10, 0), Port(90, 10, 0)), NetSpec("b", Port(10, 12, 0), Port(90, 12, 0))),
|
|
clearance=0,
|
|
)
|
|
options = RoutingOptions(
|
|
search=SearchOptions(node_limit=60, bend_radii=(), sbend_radii=()),
|
|
congestion=CongestionOptions(max_iterations=1),
|
|
)
|
|
case = BenchmarkCase("touching-routes", "Two straight routes sharing an edge", problem, options)
|
|
|
|
sample = _measure(case, options, "seed-order-locked")
|
|
|
|
first, retry = sample.stages
|
|
assert first.valid_net_ids == ("a",)
|
|
assert retry.incumbent_net_ids == first.valid_net_ids
|
|
assert retry.valid_net_ids == first.valid_net_ids
|
|
assert sample.valid_costs.keys() == {"a"}
|
|
|
|
|
|
def test_benchmark_native_cost_uses_configured_proximity_range() -> None:
|
|
problem = RoutingProblem(
|
|
bounds=(0, 0, 100, 40),
|
|
nets=(NetSpec("a", Port(10, 10, 0), Port(90, 10, 0)),),
|
|
static_obstacles=(box(0, 28, 100, 30),),
|
|
)
|
|
options = RoutingOptions(search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=()))
|
|
case = BenchmarkCase("proximity-cost", "Straight route near one keepout", problem, options)
|
|
|
|
default = _measure(case, options, "off")
|
|
wider = _measure(case, replace(options, search=replace(options.search, proximity_range=40)), "off")
|
|
|
|
assert default.valid_costs == wider.valid_costs == {"a": 80.0}
|
|
assert default.native_valid_costs == {"a": 80.0}
|
|
assert wider.native_valid_costs["a"] > default.native_valid_costs["a"]
|
|
|
|
|
|
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_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}
|