import sys from dataclasses import asdict, replace from itertools import combinations from json import dumps, loads import pytest from shapely import union_all from shapely.geometry import Point, Polygon, box, shape from inire import ( Bend90Seed, NetSpec, Port, RoutingOptions, RoutingProblem, SBendOutline, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, ) from inire.constants import TOLERANCE_LINEAR from inire.router._automatic import _AutomaticRun from inire.router._routing_policy import _disconnected_nets from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES from inire.tests.routing_benchmarks import ( BENCHMARK_CASES, COMPLEX_BENCHMARK_CASES, CROSSING_BENCHMARK_CASES, EXTERNAL_BENCHMARK_CASES, FALLBACK_BENCHMARK_CASES, ) from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES from scripts.compare_topological_routing import ( _direct_trials, _geometry_json, _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 @pytest.mark.parametrize( "case", [pytest.param(case, id=case.name) for case in CORPUS_CASES], ) def test_automatic_reaches_corpus_routing_bound(case) -> None: profile = "corpus-regression" options = automatic_options(profile_options(case, profile), profile) run = route(case.problem, options=options) assert run.automatic is not None assert run.results_by_net.keys() == {net.net_id for net in case.problem.nets} verified = {net_id for net_id, result in run.results_by_net.items() if result.is_valid} assert run.automatic.max_routed == case.routing_bound assert set(run.automatic.verified_net_ids) == verified assert len(verified) == case.routing_bound @pytest.mark.parametrize( "case", [pytest.param(case, id=case.name) for case in (*CORPUS_CASES, *RETRY_HOLDOUT_CASES) if case.reference_paths], ) def test_benchmark_reference_paths_are_feasible(case) -> None: reference = dict(case.reference_paths) problem = replace(case.problem, nets=tuple(net for net in case.problem.nets if net.net_id in reference), initial_paths=reference) options = replace(case.options, refinement=replace(case.options.refinement, enabled=False)) run = route(problem, options=options) assert run.results_by_net.keys() == reference.keys() board = box(*problem.bounds) footprints = [] for result in run.results_by_net.values(): assert result.is_valid assert result.as_seed() == reference[result.net_id] footprint = union_all(result.locked_geometry) assert board.covers(footprint) assert all(footprint.distance(obstacle) >= problem.clearance - TOLERANCE_LINEAR for obstacle in problem.static_obstacles) footprints.append(footprint) for a, b in combinations(footprints, 2): assert a.distance(b) >= problem.clearance - TOLERANCE_LINEAR def test_stress_and_retry_holdout_cases_start_unseeded_with_complete_reference_paths() -> None: cases = (*STRESS_BENCHMARK_CASES, *RETRY_HOLDOUT_CASES) assert len({case.name for case in cases}) == len(cases) for case in cases: assert not case.problem.initial_paths assert dict(case.reference_paths).keys() == {net.net_id for net in case.problem.nets} search = case.options.search for _, seed in case.reference_paths: for move in seed.segments: if isinstance(move, StraightSeed): assert search.min_straight_length <= move.length <= search.max_straight_length elif isinstance(move, Bend90Seed): assert move.radius in search.bend_radii elif isinstance(move, SBendSeed): assert move.radius in search.sbend_radii def test_stress_folded_return_can_be_refined_with_the_other_tracks_present() -> None: case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-refine-return-shelf") reference = dict(case.reference_paths) options = replace( case.options, search=replace(case.options.search, node_limit=1), congestion=replace(case.options.congestion, max_iterations=1), ) run = route(replace(case.problem, initial_paths=reference), options=options) assert all(result.is_valid for result in run.results_by_net.values()) assert run.metrics.nodes_expanded == 0 assert run.results_by_net["folded_return"].as_seed() != reference["folded_return"] def test_stress_opposed_sbends_fit_together_without_search() -> None: case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-sbend-competing-slots") options = replace(case.options, topology=TopologyOptions(mode="automatic")) run = route(case.problem, options=options) assert run.automatic is not None assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} assert run.automatic.selected_planner == "local-sbend" assert run.metrics.nodes_expanded == 0 def test_stress_residual_dogleg_completes_layout_before_wider_search() -> None: case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-retry-straight-decoy") options = replace( case.options, topology=TopologyOptions(mode="automatic"), congestion=replace(case.options.congestion, max_iterations=3), ) ordinary = route(case.problem, options=options) iterations = [] observed = route(case.problem, options=options, iteration_callback=lambda index, _: iterations.append(index)) report = ordinary.automatic assert report is not None assert set(report.verified_net_ids) == {net.net_id for net in case.problem.nets} assert report.selected_planner == "residual-dogleg" [search] = [stage for stage in report.stages if stage.operation == "search"] assert search.policy == "direct-probe-near-port" assert set(search.valid_net_ids) == {"branch_west", "branch_east", "lower_rail"} assert observed.results_by_net == ordinary.results_by_net assert observed.metrics.nodes_expanded == ordinary.metrics.nodes_expanded assert iterations == list(range(observed.metrics.route_iterations)) @pytest.mark.parametrize(("iterations", "probe_limit"), [(1, 1), (3, 2)]) def test_automatic_probe_caps_iterations_and_preserves_callback_order(monkeypatch, iterations, probe_limit) -> None: (case,) = CASE_GROUPS["pic-splitter-tree-1x8-ew"] profile = "corpus-regression" options = automatic_options(profile_options(case, profile), profile) options = replace(options, congestion=replace(options.congestion, max_iterations=iterations)) run_worker = _AutomaticRun._run search_budgets = {} callback_indices = [] def record_budget(self, problem, *, options, **kwargs): if kwargs.get("policy") in {"direct-probe-near-port", "direct-lookahead-retry"}: search_budgets[kwargs["policy"]] = options.congestion.max_iterations return run_worker(self, problem, options=options, **kwargs) monkeypatch.setattr(_AutomaticRun, "_run", record_budget) route(case.problem, options=options, iteration_callback=lambda index, _results: callback_indices.append(index)) assert search_budgets == {"direct-probe-near-port": probe_limit, "direct-lookahead-retry": iterations} assert len(callback_indices) > probe_limit assert callback_indices == list(range(len(callback_indices))) def test_automatic_routes_an_unseeded_grid_between_preplaced_crossing_ports() -> None: case = next(case for case in CROSSING_BENCHMARK_CASES if case.name == "crossing-aligned-grid") assert not case.problem.initial_paths options = replace(case.options, topology=TopologyOptions(mode="automatic")) run = route(case.problem, options=options) assert run.automatic is not None assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} for net in case.problem.nets: path = run.results_by_net[net.net_id].path assert path[0].start_port == net.start assert path[-1].end_port == net.target def test_automatic_constructs_an_exact_sbend_grid() -> None: case = next(case for case in CROSSING_BENCHMARK_CASES if case.name == "crossing-staggered-grid") options = replace(case.options, topology=TopologyOptions(mode="automatic")) run = route(case.problem, options=options) assert run.automatic is not None assert run.automatic.selected_planner == "local-sbend" assert len(run.automatic.verified_net_ids) == len(case.problem.nets) assert run.metrics.nodes_expanded == 0 for net in case.problem.nets: path = run.results_by_net[net.net_id].path assert path[0].start_port == net.start assert path[-1].end_port == net.target assert sum(move.move_type == "sbend" for move in path) == 1 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_automatic_times_planning_search_verification_and_refinement() -> None: case = next(case for case in BENCHMARK_CASES if case.name == "open-bundle") options = replace(case.options, topology=TopologyOptions(mode="automatic")) report = route(case.problem, options=options).automatic assert report is not None assert {timing.operation for timing in report.timings} == {"plan", "verify", "search", "refine"} assert 0 < sum(timing.duration_s for timing in report.timings) <= report.duration_s assert report.planner_rejections assert any(timing.planner == "bundle" and timing.operation == "plan" for timing in report.timings) assert not any(timing.planner == "bundle" and timing.operation == "verify" for timing in report.timings) stage = report.stages[report.selected_stage] assert stage.planner == "direct" assert stage.mode == "off" assert stage.policy == "direct-probe-near-port" @pytest.mark.parametrize( ("profile", "refinement", "max_windows"), [ ("public-defaults", None, None), ("public-defaults", "off", None), ("public-defaults", "on", "1"), ("matched-budget", None, "unlimited"), ("matched-budget", "on", None), ("corpus-regression", None, None), ], ) def test_benchmark_profile_records_effective_options(profile, refinement, max_windows, 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" mode_args = [] if profile == "public-defaults" else ["--mode", "automatic"] refine_args = [] if refinement is None else ["--refinement", refinement] window_args = [] if max_windows is None else ["--refinement-windows", max_windows] monkeypatch.setattr( sys, "argv", ["bench", "--profile", profile, "--case", case.name, *mode_args, *refine_args, *window_args, "--json", str(output)] ) run_benchmarks() payload = loads(output.read_text()) [run] = payload["runs"] assert payload["profile"] == profile 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 = defaults.refinement if profile == "public-defaults" else case.options.refinement if refinement is not None: expected_refinement = replace(expected_refinement, enabled=refinement == "on") if max_windows is not None: expected_refinement = replace(expected_refinement, max_windows_per_net=None if max_windows == "unlimited" else int(max_windows)) assert options["refinement"] == asdict(expected_refinement) assert operations == ({"search", "verify", "refine"} if expected_refinement.enabled else {"search", "verify"}) if profile == "public-defaults": 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 else: assert options["search"]["node_limit"] == 500 assert options["objective"] == asdict(case.options.objective) assert options["congestion"]["max_iterations"] == (3 if profile == "corpus-regression" else 2) assert options["topology"]["seed_node_limit"] == (500 if profile == "corpus-regression" else defaults.topology.seed_node_limit) assert options["topology"]["automatic_length_weights"] == [1.0, 4.0, 13.0] @pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in BENCHMARK_CASES if case.name.startswith("offset-gates")]) def test_portal_guidance_routes_offset_gates_under_small_budget(case) -> None: options = replace(case.options, search=replace(case.options.search, node_limit=100), topology=TopologyOptions(mode="guide")) result = route(case.problem, options=options).results_by_net["offset"] assert result.is_valid assert any(component.move_type == "sbend" for component in result.path) assert all(box(*case.problem.bounds).covers(shape) for shape in result.locked_geometry) 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_lookahead_changes_lock_order_before_spending_search_budget() -> None: case = next(case for case in BENCHMARK_CASES if case.name == "blocking-straight") options = replace(case.options, search=replace(case.options.search, node_limit=100)) result = _measure(case, options, "direct-lookahead-retry") assert len(result.stages) == 1 assert result.stages[0].node_limit == 100 assert result.stages[0].direct_net_ids == ("vertical",) assert result.stages[0].skipped_net_ids == () assert "vertical" in result.valid_costs 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) @pytest.mark.parametrize("policy", ["direct-probe-first", "direct-probe-near-port"]) def test_unlocked_probe_can_complete_the_turn_limited_case(policy) -> 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=100)) result = _measure(case, options, policy) assert len(result.valid_costs) == 2 assert len(result.stages) == 1 assert result.stages[0].kind == "lattice-probe" assert result.stages[0].node_limit == 32 def test_near_port_probe_leaves_budget_for_crossings_far_from_the_ports() -> None: case = next(case for case in BENCHMARK_CASES if case.name == "crossing-with-room") options = replace(case.options, search=replace(case.options.search, node_limit=100)) result = _measure(case, options, "direct-probe-near-port") assert [stage.node_limit for stage in result.stages] == [50, 50] assert all(stage.kind == "route" for stage in result.stages) @pytest.mark.parametrize( "name", [ "terminal-bench-point-terminals", "terminal-bench-clearance-5", "terminal-bench-narrow-bottom", *(case.name for case in COMPLEX_BENCHMARK_CASES if case.options.topology.mode == "bundle"), ], ) def test_bundle_first_routes_point_terminals_without_supplied_paths(name: str) -> None: case = next(case for case in BENCHMARK_CASES if case.name == name) assert not case.problem.initial_paths assert not case.reference_paths fixed = case.fixed_headings_problem() assert [net.net_id for net in fixed.nets if net.target.r == 180] == ["net_08"] assert not fixed.initial_paths sample = _measure(case, case.options, "bundle-first") assert sample.bundle_rejection is None assert [stage.kind for stage in sample.stages] == ["bundle"] assert sample.valid_costs.keys() == {net.net_id for net in case.problem.nets} assert sample.nodes_expanded == 0 @pytest.mark.parametrize(("name", "mode"), [("terminal-bench", "automatic"), ("terminal-bench-point-terminals", "bundle")]) def test_unused_custom_outline_keeps_constructive_planning_available(name, mode) -> None: case = next(case for case in BENCHMARK_CASES if case.name == name) width = 3 outline = SBendOutline(40, 50, width, Polygon([(0, -1.5), (80, 38.5), (80, 41.5), (0, 1.5)])) options = replace( case.options, search=replace(case.options.search, node_limit=100, sbend_outlines=(outline,)), topology=replace(case.options.topology, mode=mode), congestion=replace(case.options.congestion, max_iterations=1, warm_start_enabled=False), refinement=replace(case.options.refinement, enabled=False), ) result = route(case.problem, options=options) assert all(path.is_valid for path in result.results_by_net.values()) def test_complex_benchmarks_are_distinct_unseeded_nine_net_problems() -> None: assert len({case.name for case in BENCHMARK_CASES}) == len(BENCHMARK_CASES) assert len(COMPLEX_BENCHMARK_CASES) == 20 layouts = set() for case in COMPLEX_BENCHMARK_CASES: problem = case.problem assert len(problem.nets) == 9 assert not problem.initial_paths if case.reference_paths: assert {net_id for net_id, _ in case.reference_paths} == {net.net_id for net in problem.nets} layouts.add((problem.bounds, problem.nets, tuple(sorted(shape.bounds for shape in problem.static_obstacles)))) assert len(layouts) == len(COMPLEX_BENCHMARK_CASES) 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 @pytest.mark.parametrize( ("name", "planner"), [("terminal-bench", "bundle-turnaround"), ("terminal-bench-pair", "paired-perimeter")], ) def test_automatic_policy_preserves_fixed_terminal_headings(name: str, planner: str) -> None: case = next(case for case in BENCHMARK_CASES if case.name == name) assert not case.problem.initial_paths options = replace(case.options, topology=TopologyOptions(mode="automatic")) run = route(case.problem, options=options) assert run.automatic is not None assert run.automatic.selected_planner == planner for net in case.problem.nets: result = run.results_by_net[net.net_id] assert result.is_valid assert result.path[0].start_port == net.start assert result.path[-1].end_port == net.target def test_automatic_policy_stops_at_the_geometric_cut_bound() -> None: case = next(case for case in BENCHMARK_CASES if case.name == "overloaded-gate") options = replace(case.options, search=replace(case.options.search, node_limit=SearchOptions().node_limit)) sample = _measure(case, options, "automatic") assert sample.capacity_limit is not None assert sample.capacity_limit.cut_x == 225 assert sample.capacity_limit.crossing_nets == 4 assert sample.capacity_limit.tracks == 3 assert len(sample.valid_costs) == sample.capacity_limit.max_routed == 3 assert [stage.kind for stage in sample.stages] == ["route", "refinement"] 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, verified = trials assert set(ordinary.valid_costs) == set(first.valid_costs) == {"track2", "track5"} assert joint.stage.policy == verified.stage.policy == "joint-portal-lanes" assert set(joint.stage.incumbent_net_ids) == set(first.valid_costs) assert not joint.selectable assert verified.selectable assert set(verified.valid_costs) == {"track2", "track3", "track5"} 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} @pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in EXTERNAL_BENCHMARK_CASES]) def test_external_benchmark_has_accessible_ports_and_empty_paths(case) -> None: problem = case.problem assert not problem.initial_paths assert not case.reference_paths assert len({net.net_id for net in problem.nets}) == len(problem.nets) board = box(*problem.bounds) for obstacle in problem.static_obstacles: assert obstacle.is_valid assert board.covers(obstacle) for net in problem.nets: for port in (net.start, net.target): position = Point(port.x, port.y) assert board.covers(position) assert all(position.distance(obstacle) >= net.width / 2 + problem.clearance for obstacle in problem.static_obstacles) def test_benchmark_json_preserves_custom_bend_geometry() -> None: case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == "fallback-custom-physical") encoded = loads(dumps(asdict(case.options), default=_geometry_json)) for key in ("bend_physical_geometry", "bend_proxy_geometry"): assert shape(encoded["search"][key]).equals(getattr(case.options.search, key)) def test_compact_port_jogs_close_the_mzm_layout_without_search() -> None: case = next(case for case in EXTERNAL_BENCHMARK_CASES if case.name == "pic-splitter-mzm-combiner-4-ew") sample = _measure(case, case.options, "automatic") assert len(sample.valid_costs) == 12 assert sample.stages[sample.selected_stage].kind == "compact-port-jogs" assert sample.nodes_expanded == 0 def test_port_spacing_certificate_reaches_clements_capacity() -> None: case = next(case for case in EXTERNAL_BENCHMARK_CASES if case.name == "lidar-clements-8x8") sample = _measure(case, case.options, "automatic") assert sample.port_conflicts == (("n_30", "n_31"), ("n_32", "n_33"), ("n_34", "n_35")) assert len(sample.valid_costs) == len(case.problem.nets) - len(sample.port_conflicts) assert len(sample.stages) == 1 def test_paired_perimeters_respect_the_supplied_detour() -> None: case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == "fallback-seeded-detour") options = replace(case.options, search=replace(case.options.search, node_limit=100), topology=TopologyOptions(mode="automatic")) run = route(case.problem, options=options) assert run.automatic is not None assert run.automatic.selected_planner == "paired-perimeter" assert all(result.is_valid for result in run.results_by_net.values()) for net_id, seed in case.problem.initial_paths.items(): assert run.results_by_net[net_id].as_seed() == seed 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} @pytest.mark.parametrize("name", ["fallback-custom-proxy", "fallback-custom-physical"]) def test_automatic_preserves_custom_bend_geometry(name: str) -> None: case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == name) ordinary = route(case.problem, options=case.options) options = replace(case.options, topology=replace(case.options.topology, mode="automatic")) automatic = route(case.problem, options=options) assert automatic.automatic is not None assert automatic.automatic.selected_planner == "lattice" assert automatic.automatic.stages[automatic.automatic.selected_stage].kind == "lattice-fallback" assert all(result.is_valid for result in automatic.results_by_net.values()) for net_id, result in automatic.results_by_net.items(): expected = ordinary.results_by_net[net_id] assert result.as_seed() == expected.as_seed() assert result.locked_geometry == expected.locked_geometry def test_automatic_return_detour_respects_a_small_search_budget() -> None: case = next(case for case in BENCHMARK_CASES if case.name == "reversed-heading") options = replace( case.options, search=replace(case.options.search, node_limit=1), congestion=replace(case.options.congestion, max_iterations=1), refinement=replace(case.options.refinement, enabled=False), topology=TopologyOptions(mode="automatic"), ) iterations = [] run = route(case.problem, options=options, iteration_callback=lambda iteration, _: iterations.append(iteration)) assert run.automatic is not None assert run.automatic.selected_planner == "perimeter" assert max(stage.node_limit for stage in run.automatic.stages) == 1 assert iterations == list(range(run.metrics.route_iterations)) assert run.metrics.refine_path_calls == 0 assert run.results_by_net["return"].is_valid