diff --git a/docs/benchmarks.md b/docs/benchmarks.md index ecc7a25..bf0c16a 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -27,6 +27,8 @@ Expect `3/4 valid`. All four nets need to cross a vertical cut where the opening List cases with `python -m scripts.compare_topological_routing --list`. Start with the smallest case that exhibits the behavior. +`pytest -m routing_corpus` runs regression coverage checks for the corpus and the retry holdouts. Use `pytest -m retry_holdout` to run just the holdout coverage checks. + - [Fixture sources and regeneration](benchmark-fixtures.md) ## Choose a profile diff --git a/inire/tests/conftest.py b/inire/tests/conftest.py new file mode 100644 index 0000000..447b3bc --- /dev/null +++ b/inire/tests/conftest.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +if TYPE_CHECKING: + from inire.results import RoutingRunResult + + +@pytest.fixture(scope="session") +def example_07_no_warm_start_trace() -> RoutingRunResult: + from inire.tests.example_scenarios import trace_example_07_no_warm_start # noqa: PLC0415 + + return trace_example_07_no_warm_start() diff --git a/inire/tests/example_scenarios.py b/inire/tests/example_scenarios.py index 19d1166..aa94f4d 100644 --- a/inire/tests/example_scenarios.py +++ b/inire/tests/example_scenarios.py @@ -460,6 +460,19 @@ SCENARIOS: tuple[tuple[str, ScenarioRun], ...] = tuple( (name, partial(_snapshot_outcome, capture)) for name, capture in SCENARIO_SNAPSHOTS ) +# Total results, verified results, and reached targets for each example. +EXPECTED_OUTCOMES = { + "example_01_simple_route": (1, 1, 1), + "example_02_congestion_resolution": (3, 3, 3), + "example_03_locked_paths": (2, 2, 2), + "example_04_sbends_and_radii": (2, 2, 2), + "example_05_orientation_stress": (3, 3, 3), + "example_06_bend_collision_models": (3, 3, 3), + "example_07_large_scale_routing": (10, 10, 10), + "example_08_custom_bend_geometry": (2, 2, 2), + "example_09_unroutable_best_effort": (1, 0, 0), +} + PERFORMANCE_SCENARIO_SNAPSHOTS: tuple[tuple[str, ScenarioSnapshotRun], ...] = ( ("example_07_large_scale_routing_no_warm_start", snapshot_example_07_no_warm_start), ("example_07_large_scale_routing_no_warm_start_seed43", snapshot_example_07_no_warm_start_seed43), diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index eb5a569..8cedea5 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -1,14 +1,11 @@ -import importlib from contextlib import nullcontext -from dataclasses import asdict, replace -from pickle import dumps, loads +from dataclasses import replace import pytest import shapely -from shapely.affinity import rotate, translate +from shapely.affinity import translate from shapely.geometry import Polygon, box -import inire import inire.geometry.components as components_module import inire.router._router as router_module import inire.router._search as search_module @@ -16,6 +13,7 @@ from inire import ( Bend90Seed, CongestionOptions, DiagnosticsOptions, + FixedRoute, NetSpec, ObjectiveWeights, PathSeed, @@ -30,49 +28,14 @@ from inire import ( TopologyOptions, route, ) -from inire.geometry.components import Bend90, SBend, Straight +from inire.geometry.components import SBend, Straight from inire.geometry.collision import RoutingWorld -from inire.results import RoutingReport, RoutingResult +from inire.results import ComponentConflictTrace, RoutingReport, RoutingResult from inire.router._astar_types import AStarContext from inire.router._router import PathFinder, _IterationReview from inire.router._stack import RoutingAttempts from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap -def test_root_module_exports_only_stable_surface() -> None: - assert not hasattr(inire, "RoutingWorld") - assert not hasattr(inire, "AStarContext") - assert not hasattr(inire, "PathFinder") - assert not hasattr(inire, "CostEvaluator") - assert not hasattr(inire, "DangerMap") - - -def test_deep_raw_stack_imports_remain_accessible_but_unstable() -> None: - router_module = importlib.import_module("inire.router._router") - search_module = importlib.import_module("inire.router._search") - collision_module = importlib.import_module("inire.geometry.collision") - - assert hasattr(router_module, "PathFinder") - assert hasattr(search_module, "route_astar") - assert hasattr(collision_module, "RoutingWorld") - - -def test_route_problem_smoke() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net1", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), - ) - - run = route(problem) - - assert set(run.results_by_net) == {"net1"} - assert run.results_by_net["net1"].is_valid - assert run.automatic is not None - assert run.automatic.verified_net_ids == ("net1",) - assert all(stage.node_limit <= 500 for stage in run.automatic.stages) - assert run.conflict_trace == () - assert run.frontier_trace == () - assert run.pre_pair_frontier_trace is None - assert run.iteration_trace == () def test_routing_problem_rejects_duplicate_net_ids() -> None: @@ -84,118 +47,100 @@ def test_routing_problem_rejects_duplicate_net_ids() -> None: with pytest.raises(ValueError, match="Duplicate net ID: 'shared'"): RoutingProblem(bounds=(0, 0, 100, 100), nets=nets) - -@pytest.mark.parametrize("width", [0, -2, float("nan"), float("inf")]) -def test_net_width_must_be_finite_and_positive(width) -> None: - with pytest.raises(ValueError, match="width must be finite and positive"): - NetSpec("net", Port(10, 20, 0), Port(90, 20, 0), width=width) + fixed = FixedRoute("shared", (box(10, 40, 90, 42),)) + with pytest.raises(ValueError, match="Duplicate active or fixed net ID: 'shared'"): + RoutingProblem(bounds=(0, 0, 100, 100), nets=nets[:1], fixed_routes=(fixed,)) -@pytest.mark.parametrize("clearance", [-1.0, float("nan"), float("inf")]) -def test_routing_clearance_must_be_finite_and_nonnegative(clearance) -> None: - with pytest.raises(ValueError, match="clearance must be finite and nonnegative"): - RoutingProblem((0, 0, 100, 100), clearance=clearance) +def test_routing_problem_requires_typed_geometry_inputs() -> None: + bounds = (0, 0, 100, 100) + with pytest.raises(TypeError, match="must be a Shapely Polygon"): + RoutingProblem(bounds, static_obstacles=(box(20, 20, 30, 30).boundary,)) + with pytest.raises(TypeError, match="initial_paths values must be PathSeed"): + RoutingProblem(bounds, initial_paths={"line": (StraightSeed(50),)}) -@pytest.mark.parametrize( - "bounds", - [(100, 0, 0, 100), (0, 0, 100, 0), (0, 0, float("inf"), 100), (0, 0, 100, float("nan"))], -) -def test_routing_bounds_require_a_finite_positive_rectangle(bounds) -> None: - with pytest.raises(ValueError, match="bounds must be finite"): - RoutingProblem(bounds) +def test_net_width_must_be_finite_and_positive() -> None: + for width in (0, float("nan")): + with pytest.raises(ValueError, match="width must be finite and positive"): + NetSpec("net", Port(10, 20, 0), Port(90, 20, 0), width=width) -@pytest.mark.parametrize("keepout", [Polygon(), Polygon([(0, 0), (10, 10), (0, 10), (10, 0)])]) -def test_routing_keepout_must_be_nonempty_and_valid(keepout) -> None: +def test_routing_clearance_must_be_finite_and_nonnegative() -> None: + for clearance in (-1.0, float("inf")): + with pytest.raises(ValueError, match="clearance must be finite and nonnegative"): + RoutingProblem((0, 0, 100, 100), clearance=clearance) + + +def test_routing_bounds_require_a_finite_positive_rectangle() -> None: + for bounds in ((100, 0, 0, 100), (0, 0, 100, float("nan"))): + with pytest.raises(ValueError, match="bounds must be finite"): + RoutingProblem(bounds) + + +def test_routing_keepout_must_be_nonempty_and_valid() -> None: + keepout = Polygon([(0, 0), (10, 10), (0, 10), (10, 0)]) with pytest.raises(ValueError, match=r"static_obstacles\[1\].*nonempty and valid"): RoutingProblem((0, 0, 100, 100), static_obstacles=(box(20, 20, 30, 30), keepout)) -def test_routing_keepout_must_be_a_polygon() -> None: - with pytest.raises(TypeError, match=r"static_obstacles\[0\].*Polygon"): - RoutingProblem((0, 0, 100, 100), static_obstacles=(box(20, 20, 30, 30).boundary,)) +def test_search_distances_and_radii_require_finite_values() -> None: + with pytest.raises(ValueError, match="bend_radii"): + SearchOptions(bend_radii=(float("inf"),)) + with pytest.raises(ValueError, match="min_straight_length"): + SearchOptions(min_straight_length=-1) + with pytest.raises(ValueError, match="max_straight_length"): + SearchOptions(max_straight_length=0) + with pytest.raises(ValueError, match="bend_proxy_geometry"): + SearchOptions(bend_proxy_geometry="clipped-bbox") -@pytest.mark.parametrize( - ("name", "value"), - [ - ("bend_radii", (float("inf"),)), - ("sbend_radii", (float("nan"),)), - ("bend_radii", (0,)), - ("min_straight_length", float("nan")), - ("max_straight_length", float("inf")), - ], -) -def test_search_distances_and_radii_require_finite_values(name, value) -> None: - with pytest.raises(ValueError, match=name): - SearchOptions(**{name: value}) +def test_route_does_not_generate_bends_wider_than_their_diameter() -> None: + nets = ( + NetSpec("turn", Port(20, 25, 0), Port(30, 35, 90), width=25), + NetSpec("shift", Port(20, 85, 0), Port(35, 91, 0), width=25), + ) + seeds = { + "turn": PathSeed((Bend90Seed(10, "CCW"),)), + "shift": PathSeed((SBendSeed(6, 10),)), + } + problem = RoutingProblem((0, 0, 100, 120), nets, initial_paths=seeds) + options = RoutingOptions( + search=SearchOptions(bend_radii=(10,), sbend_radii=(10,), node_limit=100), + congestion=CongestionOptions(max_iterations=1), + ) + + run = route(problem, options=options) + + assert set(run.results_by_net) == set(seeds) + for result in run.results_by_net.values(): + assert not result.is_valid + assert all(isinstance(move, StraightSeed) for move in result.as_seed().segments) -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize("with_seed", [False, True]) -@pytest.mark.parametrize( - ("target", "width", "segment", "search"), - [ - (Port(25, 25, 90), 12, Bend90Seed(5, "CCW"), SearchOptions(bend_radii=(5,), sbend_radii=(), node_limit=100)), - (Port(31, 23, 0), 25, SBendSeed(3, 10), SearchOptions(bend_radii=(), sbend_radii=(10,), node_limit=100)), - ], - ids=["quarter-turn", "sbend"], -) -def test_route_does_not_generate_bends_wider_than_their_diameter(mode, with_seed, target, width, segment, search) -> None: - net = NetSpec("wide", Port(20, 20, 0), target, width=width) - seeds = {"wide": PathSeed((segment,))} if with_seed else {} - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths=seeds) - options = RoutingOptions(search=search, topology=TopologyOptions(mode=mode), congestion=CongestionOptions(max_iterations=1)) +def test_seed_parameters_must_describe_a_forward_usable_move() -> None: + with pytest.raises(ValueError, match="seed"): + StraightSeed(-10) + with pytest.raises(ValueError, match="seed"): + Bend90Seed(0, "CW") + with pytest.raises(ValueError, match="seed"): + SBendSeed(20, 10) + with pytest.raises(ValueError, match="seed"): + SBendSeed(3.5, 10) - result = route(problem, options=options).results_by_net["wide"] + +def test_search_skips_sbends_when_the_offset_list_is_empty() -> None: + problem = RoutingProblem((0, 0, 90, 70), (NetSpec("shift", Port(10, 20, 0), Port(60, 24, 0)),)) + options = RoutingOptions( + search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=(10,), sbend_offsets=()), + topology=TopologyOptions(mode="off"), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + ) + + result = route(problem, options=options).results_by_net["shift"] assert not result.is_valid - assert all(isinstance(move, StraightSeed) for move in result.as_seed().segments) - - -@pytest.mark.parametrize( - ("seed_type", "args"), - [ - (StraightSeed, (-10,)), - (StraightSeed, (float("inf"),)), - (Bend90Seed, (0, "CW")), - (Bend90Seed, (10, "left")), - (SBendSeed, (0, 10)), - (SBendSeed, (20, 10)), - (SBendSeed, (3.5, 10)), - ], -) -def test_seed_parameters_must_describe_a_forward_usable_move(seed_type, args) -> None: - with pytest.raises(ValueError, match="seed"): - seed_type(*args) - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_route_keeps_off_lattice_sbend_physically_connected(mode) -> None: - net = NetSpec("shift", Port(10, 20, 0), Port(60, 23, 0)) - problem = RoutingProblem((0, 0, 90, 70), (net,)) - options = RoutingOptions(topology=TopologyOptions(mode=mode)) - - result = route(problem, options=options).results_by_net["shift"] - - assert result.is_valid - assert SBendSeed(3, 10) in result.as_seed().segments - footprint = shapely.union_all(result.locked_geometry) - assert footprint.geom_type == "Polygon" - assert footprint.covers(shapely.Point(net.start.x, net.start.y)) - assert footprint.covers(shapely.Point(net.target.x, net.target.y)) - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize("offsets", [(), (4,)]) -def test_route_respects_explicit_sbend_offsets(mode, offsets) -> None: - problem = RoutingProblem((0, 0, 90, 70), (NetSpec("shift", Port(10, 20, 0), Port(60, 23, 0)),)) - options = RoutingOptions(search=SearchOptions(node_limit=100, sbend_offsets=offsets), topology=TopologyOptions(mode=mode)) - - result = route(problem, options=options).results_by_net["shift"] - - assert all(segment.offset in offsets for segment in result.as_seed().segments if isinstance(segment, SBendSeed)) + assert not any(isinstance(move, SBendSeed) for move in result.as_seed().segments) def test_initial_path_must_respect_explicit_sbend_offsets() -> None: @@ -212,67 +157,40 @@ def test_initial_path_must_respect_explicit_sbend_offsets() -> None: assert result.as_seed() == seed -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize( - ("move", "target", "field"), - [(Bend90Seed(5, "CCW"), Port(25, 25, 90), "bend_radii"), (SBendSeed(3, 10), Port(31, 23, 0), "sbend_radii")], -) -def test_replay_reports_an_incompatible_seed_and_verifies_other_nets(mode, move, target, field) -> None: - nets = (NetSpec("net", Port(20, 20, 0), target), NetSpec("peer", Port(10, 60, 0), Port(70, 60, 0))) - seeds = {"net": PathSeed((move,)), "peer": PathSeed((StraightSeed(60),))} - problem = RoutingProblem( - (0, 0, 100, 100), nets, initial_paths=seeds, +def test_replay_reports_incompatible_seed_segments_and_verifies_peers() -> None: + cases = ( + (NetSpec("unsupported_turn", Port(20, 20, 0), Port(25, 25, 90)), + Bend90Seed(5, "CCW"), "uses radius 5 outside bend_radii"), + (NetSpec("unsupported_sbend", Port(20, 60, 0), Port(35, 63, 0)), + SBendSeed(3, 20), "uses radius 20 outside sbend_radii"), + (NetSpec("overwide_turn", Port(20, 100, 0), Port(30, 110, 90), width=30), + Bend90Seed(10, "CCW"), "segment 1 (Bend90Seed) needs radius at least 15, got 10"), + (NetSpec("overwide_sbend", Port(20, 150, 0), Port(35, 156, 0), width=30), + SBendSeed(6, 10), "segment 1 (SBendSeed) needs radius at least 15, got 10"), ) + peer = NetSpec("peer", Port(20, 190, 0), Port(70, 190, 0)) + seeds = {net.net_id: PathSeed((segment,)) for net, segment, _ in cases} + seeds[peer.net_id] = PathSeed((StraightSeed(50),)) + problem = RoutingProblem((0, 0, 100, 220), (*(net for net, _, _ in cases), peer), initial_paths=seeds) options = RoutingOptions( - search=SearchOptions(node_limit=0, **{field: ()}), - topology=TopologyOptions(mode=mode), + search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=(10,)), + topology=TopologyOptions(mode="off"), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) - callback_reports = [] + callbacks = [] - run = route(problem, options=options, iteration_callback=lambda _, results: callback_reports.append(results["net"].report)) + run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results)) - assert run.results_by_net["peer"].is_valid - rejected = run.results_by_net["net"] - assert rejected.outcome == "unroutable" - assert rejected.report.seed_error.endswith(f"outside {field}") - assert rejected.report.invalid_geometry - assert callback_reports == [rejected.report] - assert run.conflict_trace[-1].nets[0].report == rejected.report + assert run.results_by_net[peer.net_id].is_valid assert run.metrics.nodes_expanded == 0 - - -@pytest.mark.parametrize("mode", ["automatic", "off"]) -def test_search_routes_both_nets_after_rejecting_an_incompatible_seed(mode) -> None: - nets = (NetSpec("net", Port(10, 20, 0), Port(70, 20, 0)), NetSpec("peer", Port(10, 60, 0), Port(70, 60, 0))) - problem = RoutingProblem((0, 0, 100, 100), nets, initial_paths={"net": PathSeed((Bend90Seed(10, "CCW"),))}) - options = RoutingOptions( - search=SearchOptions(node_limit=40, bend_radii=(20,), sbend_radii=()), - topology=TopologyOptions(mode=mode), - ) - - run = route(problem, options=options) - - assert all(result.is_valid for result in run.results_by_net.values()) - assert run.results_by_net["net"].report.seed_error == "Initial path for 'net' uses radius 10 outside bend_radii" - assert run.results_by_net["net"].as_seed() == PathSeed((StraightSeed(60),)) - - -def test_search_rejects_a_keepout_intersection_just_past_a_clear_launch_face() -> None: - net = NetSpec("line", Port(10, 20, 0), Port(60, 20, 0)) - problem = RoutingProblem((0, 0, 80, 70), (net,), (box(10.0005, 19.9999, 10.001, 20.0001),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=()), - topology=TopologyOptions(mode="off"), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - ) - - run = route(problem, options=options) - result = run.results_by_net[net.net_id] - - assert result.outcome == "unroutable" - assert result.report.terminal_error is None - assert run.metrics.nodes_expanded == 1 + assert callbacks == [run.results_by_net] + traced_reports = {net.net_id: net.report for net in run.conflict_trace[-1].nets} + for net, _, error in cases: + rejected = run.results_by_net[net.net_id] + assert rejected.outcome == "unroutable" + assert rejected.report.seed_error == f"Initial path for {net.net_id!r} {error}" + assert rejected.report.invalid_geometry + assert traced_reports[net.net_id] == rejected.report @pytest.mark.parametrize(("clearance", "valid"), [(0, True), (0.001, False)]) @@ -298,8 +216,7 @@ def test_search_checks_physical_clearance_after_a_local_proxy_intersection(clear assert result.locked_geometry[0].distance(keepout) == pytest.approx(0.0005) -@pytest.mark.parametrize("node_limit", [0, 50]) -def test_lattice_search_replaces_a_complete_seed_that_hits_a_keepout(node_limit) -> None: +def test_lattice_search_repairs_a_seed_that_verification_retains() -> None: net = NetSpec("line", Port(20, 20, 0), Port(120, 20, 0)) up, down = Bend90Seed(10, "CCW"), Bend90Seed(10, "CW") detour = PathSeed((up, down, StraightSeed(60), down, up)) @@ -307,139 +224,45 @@ def test_lattice_search_replaces_a_complete_seed_that_hits_a_keepout(node_limit) (0, 0, 150, 70), (net,), (box(60, 38, 80, 42),), initial_paths={net.net_id: detour}, clearance=1, ) options = RoutingOptions( - search=SearchOptions(node_limit=node_limit, bend_radii=(10,), sbend_radii=()), + search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=()), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) - run = route(problem, options=options) - result = run.results_by_net[net.net_id] + verified = route(problem, options=options) + retained = verified.results_by_net[net.net_id] + repaired = route(problem, options=replace(options, search=replace(options.search, node_limit=50))) + replacement = repaired.results_by_net[net.net_id] - assert result.reached_target - if node_limit: - assert run.metrics.nodes_expanded > 0 - assert result.is_valid - assert result.as_seed() == PathSeed((StraightSeed(100),)) - else: - assert run.metrics.nodes_expanded == 0 - assert result.report.static_collision_count == 1 - assert result.as_seed() == detour + assert verified.metrics.nodes_expanded == 0 + assert retained.reached_target + assert retained.outcome == "colliding" + assert retained.report.static_collision_count == 1 + assert retained.as_seed() == detour + assert repaired.metrics.nodes_expanded > 0 + assert replacement.reached_target + assert replacement.is_valid + assert replacement.as_seed() == PathSeed((StraightSeed(100),)) -def test_route_warns_when_a_custom_bend_misses_its_ports() -> None: - net = NetSpec("bend", Port(20, 20, 0), Port(30, 30, 90)) - seed = PathSeed((Bend90Seed(10, "CCW"),)) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed}) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10,), bend_physical_geometry=box(4, -6, 6, -4)), - congestion=CongestionOptions(max_iterations=1), - ) - - with pytest.warns(UserWarning, match="does not match the declared port faces"): - result = route(problem, options=options).results_by_net["bend"] - - assert result.reached_target - assert result.is_valid +def test_search_and_congestion_reject_invalid_budgets() -> None: + for budget in (True, -1, 1.5): + with pytest.raises(ValueError, match="node_limit must be a nonnegative integer"): + SearchOptions(node_limit=budget) + with pytest.raises(ValueError, match="max_iterations must be a nonnegative integer"): + CongestionOptions(max_iterations=budget) -def test_route_verification_accepts_point_contact_at_the_declared_port() -> None: - net = NetSpec("bend", Port(20, 20, 0), Port(50, 30, 90)) - seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW"))) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed}) - outline = Polygon([(0, -10), (4, -8), (10, 0)]) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10,), bend_physical_geometry=outline), - congestion=CongestionOptions(max_iterations=1), - ) - - with pytest.warns(UserWarning, match="does not match the declared port faces"): - result = route(problem, options=options).results_by_net["bend"] - - straight, bend = result.locked_geometry - assert straight.intersection(bend).geom_type == "Point" - assert result.reached_target - assert result.is_valid - - -@pytest.mark.parametrize("wrong_side", [False, True]) -def test_route_verification_rejects_adjacent_component_overlap(wrong_side) -> None: - if wrong_side: - outline = shapely.union_all([box(-4, -11, 0, -9), box(-4, -10, -2, -4), box(-4, -6, 11, -4), box(9, -6, 11, 0)]) - else: - outline = shapely.union_all([ - box(0, -11, 11, -9), box(9, -11, 11, 0), - box(2, -9.5, 3, -7), box(-4, -8, 3, -7), box(-4, -10, -3, -7), - ]) - net = NetSpec("bend", Port(20, 20, 0), Port(50, 30, 90)) - seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW"))) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed}) - options = RoutingOptions( - search=SearchOptions(node_limit=0, bend_radii=(10,), bend_physical_geometry=outline), - congestion=CongestionOptions(max_iterations=1), - ) - - warning = pytest.warns(UserWarning, match="declared port faces") if wrong_side else nullcontext() - with warning: - result = route(problem, options=options).results_by_net["bend"] - - straight, bend = result.locked_geometry - assert straight.intersection(bend).area > 0 - assert result.reached_target - assert not result.is_valid - assert result.report.self_collision_count == 1 - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) -def test_custom_sbend_outline_is_shared_by_search_and_seed_replay(mode) -> None: - outline = Polygon([(0, -1), (20, 3), (50, 29), (80, 39), (80, 41), (50, 31), (20, 5), (0, 1)]) - net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0)) - problem = RoutingProblem((0, 0, 160, 160), (net,)) - options = RoutingOptions( - search=SearchOptions(bend_radii=(), sbend_radii=(50,), sbend_outlines=(SBendOutline(40, 50, 2, outline),)), - congestion=CongestionOptions(max_iterations=1), - topology=TopologyOptions(mode=mode), - ) - - result = route(problem, options=options).results_by_net["shift"] - replay = route( - replace(problem, initial_paths={"shift": result.as_seed()}), - options=replace(options, search=replace(options.search, node_limit=0)), - ).results_by_net["shift"] - - assert result.is_valid - assert replay.is_valid - assert result.as_seed() == PathSeed((SBendSeed(40, 50),)) - assert len(result.locked_geometry) == 1 - assert result.locked_geometry[0].equals(translate(outline, 30, 50)) - assert result.locked_geometry == replay.locked_geometry - - -def test_sbend_outline_warns_when_a_port_face_is_missing() -> None: - half = SBend.generate(Port(0, 0, 0), 40, 50, 2).physical_geometry[0] - - with pytest.warns(UserWarning, match="port faces"): - assert SBendOutline(40, 50, 2, half).polygon == half - - -@pytest.mark.parametrize("budget", [True, -1, 1.5, float("nan"), float("inf")]) -def test_search_and_congestion_reject_invalid_budgets(budget) -> None: - with pytest.raises(ValueError, match="node_limit must be a nonnegative integer"): - SearchOptions(node_limit=budget) - with pytest.raises(ValueError, match="max_iterations must be a nonnegative integer"): - CongestionOptions(max_iterations=budget) - - -@pytest.mark.parametrize("value", [-1, float("nan"), float("inf")]) -def test_cost_options_require_finite_nonnegative_values(value) -> None: +def test_cost_options_require_finite_nonnegative_values() -> None: with pytest.raises(ValueError, match="unit_length_cost"): - ObjectiveWeights(unit_length_cost=value) + ObjectiveWeights(unit_length_cost=float("nan")) with pytest.raises(ValueError, match="greedy_h_weight"): - SearchOptions(greedy_h_weight=value) + SearchOptions(greedy_h_weight=-1) with pytest.raises(ValueError, match="base_penalty"): - CongestionOptions(base_penalty=value) + CongestionOptions(base_penalty=float("nan")) with pytest.raises(ValueError, match="multiplier"): - CongestionOptions(multiplier=value) + CongestionOptions(multiplier=-1) def test_public_inputs_reject_invalid_ids_and_named_options() -> None: @@ -451,18 +274,6 @@ def test_public_inputs_reject_invalid_ids_and_named_options() -> None: SearchOptions(visibility_guidance="exact") -@pytest.mark.parametrize(("name", "value"), [ - ("bend_collision_type", "clipped-bbox"), - ("bend_collision_type", None), - ("bend_proxy_geometry", "clipped-bbox"), - ("bend_proxy_geometry", 1), - ("bend_physical_geometry", "bbox"), -]) -def test_search_rejects_unsupported_bend_geometry(name, value) -> None: - with pytest.raises(ValueError, match=f"Invalid {name}"): - SearchOptions(**{name: value}) - - def _sbend_strip(offset, half_width=1): centerline = [(0, 0), (20, offset / 10), (50, 3 * offset / 4), (80, offset)] return Polygon( @@ -500,95 +311,34 @@ def test_custom_sbend_board_admission_agrees_with_replay_and_net_order() -> None assert route(replace(seeded, bounds=smaller_board), options=replay_options).results_by_net[edge.net_id].report.out_of_bounds -def test_custom_quarter_turn_can_end_at_a_declared_port_outside_the_board() -> None: - polygon = box(0, -11, 11, -9).union(box(9, -11, 11, -0.5)) - net = NetSpec("corner", Port(10, 10, 0), Port(20, 20, 90)) - problem = RoutingProblem((0, 0, 35, 19.75), (net,), clearance=0) - options = RoutingOptions(search=SearchOptions(node_limit=20, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=polygon)) - - with pytest.warns(UserWarning, match="declared port faces"): - result = route(problem, options=options).results_by_net[net.net_id] - - assert result.is_valid - assert result.as_seed() == PathSeed((Bend90Seed(10, "CCW"),)) - assert result.locked_geometry[0].bounds[3] == 19.5 - - -@pytest.mark.parametrize(("field", "enabled_values"), [("sbend_radii", (50,)), ("sbend_offsets", (40,))]) -def test_disabled_sbend_outline_can_be_reenabled(field, enabled_values) -> None: - outline = SBendOutline(40, 50, 2, _sbend_strip(40)) - search = SearchOptions(node_limit=25, bend_radii=(), sbend_radii=(50,), sbend_offsets=(40,), sbend_outlines=(outline,)) - disabled = replace(search, **{field: ()}) - assert disabled.sbend_outlines == (outline,) - assert not disabled.has_applicable_sbend_outline((2,)) - assert disabled.sbend_template(40, 50, 2) is None - assert "_active_sbend_outlines" not in asdict(disabled) - assert loads(dumps(disabled)).sbend_template(40, 50, 2) is None - - net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0)) - problem = RoutingProblem((0, 0, 100, 65), (net,), clearance=0) - assert not route(problem, options=RoutingOptions(search=disabled)).results_by_net[net.net_id].reached_target - seed = PathSeed((SBendSeed(40, 50),)) - replay_options = RoutingOptions(search=replace(disabled, node_limit=0)) - replay = route(replace(problem, initial_paths={net.net_id: seed}), options=replay_options).results_by_net[net.net_id] - assert replay.report.seed_error.endswith(f"outside {field}") - enabled = replace(disabled, **{field: enabled_values}) - result = route(problem, options=RoutingOptions(search=enabled)).results_by_net[net.net_id] - assert result.is_valid - assert result.as_seed() == seed - assert result.locked_geometry == (translate(outline.polygon, 10, 10),) - - -def test_search_accepts_a_gap_between_a_custom_sbend_and_a_straight() -> None: - inset_faces = {0: 0.5, 80: 79.5} - polygon = Polygon([(inset_faces.get(x, x), y) for x, y in _sbend_strip(40).exterior.coords]) - with pytest.warns(UserWarning, match="port faces"): - outline = SBendOutline(40, 50, 2, polygon) - net = NetSpec("shift", Port(10, 10, 0), Port(110, 50, 0)) - problem = RoutingProblem((0, 0, 120, 60), (net,), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=(50,), sbend_offsets=(40,), sbend_outlines=(outline,)), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net[net.net_id] - - assert result.is_valid - first, second = result.locked_geometry - assert first.distance(second) == pytest.approx(0.5) - - -@pytest.mark.parametrize(("width", "expected_polygons"), [(0.3, 1), (0.1 + 0.2, 1), (300 * 0.001, 1), (0.31, 2)]) -def test_custom_sbend_matches_float_width_in_search_and_replay(width, expected_polygons) -> None: +def test_custom_sbend_matches_float_width_in_search_and_replay() -> None: outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15)) - net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0), width) - problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) + nets = ( + NetSpec("matching", Port(10, 10, 0), Port(90, 50, 0), 0.1 + 0.2), + NetSpec("fallback", Port(10, 70, 0), Port(90, 110, 0), 0.31), + ) + problem = RoutingProblem((0, 0, 100, 125), nets, clearance=0) search = SearchOptions(node_limit=30, sbend_outlines=(outline,), bend_radii=(), sbend_radii=(50,)) options = RoutingOptions(search=search, topology=TopologyOptions(mode="off")) - active = route(problem, options=options).results_by_net["shift"] + active = route(problem, options=options).results_by_net + seeds = {net.net_id: PathSeed((SBendSeed(40, 50),)) for net in nets} replay = route( - replace(problem, initial_paths={"shift": PathSeed((SBendSeed(40, 50),))}), + replace(problem, initial_paths=seeds), options=replace(options, search=replace(search, node_limit=0)), - ).results_by_net["shift"] - assert active.is_valid - assert replay.is_valid - assert len(active.locked_geometry) == expected_polygons - assert active.locked_geometry == replay.locked_geometry + ).results_by_net + + for net_id, polygon_count in (("matching", 1), ("fallback", 2)): + assert active[net_id].is_valid + assert replay[net_id].is_valid + assert len(active[net_id].locked_geometry) == polygon_count + assert active[net_id].locked_geometry == replay[net_id].locked_geometry -@pytest.mark.parametrize("mode", ["off", "automatic"]) -@pytest.mark.parametrize("terminal", ["start", "target"]) -def test_search_and_seed_replay_check_materialized_sbend_faces(mode, terminal) -> None: +def test_search_and_seed_replay_check_materialized_sbend_faces() -> None: clearance = 0.1 # The nominal face fails clearance. The supplied outline is within the face tolerance. - if terminal == "start": - face_x, offset = 0, 0.8e-6 - keepout = box(0, 7, 10 - clearance + 0.4e-6, 13) - else: - face_x, offset = 80, -0.8e-6 - keepout = box(90 + clearance - 0.4e-6, 47, 100, 53) - polygon = Polygon([(x + offset if x == face_x else x, y) for x, y in _sbend_strip(40).exterior.coords]) + keepout = box(0, 7, 10 - clearance + 0.4e-6, 13) + polygon = Polygon([(0.8e-6 if x == 0 else x, y) for x, y in _sbend_strip(40).exterior.coords]) outline = SBendOutline(40, 50, 2, polygon) net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0), width=2) problem = RoutingProblem( @@ -596,7 +346,7 @@ def test_search_and_seed_replay_check_materialized_sbend_faces(mode, terminal) - ) options = RoutingOptions( search=SearchOptions(node_limit=0, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline,)), - topology=TopologyOptions(mode=mode), + topology=TopologyOptions(mode="off"), ) callbacks = [] @@ -615,20 +365,6 @@ def test_search_and_seed_replay_check_materialized_sbend_faces(mode, terminal) - assert active.locked_geometry == result.locked_geometry -def test_search_checks_materialized_quarter_turn_face() -> None: - bend = Bend90.generate(Port(0, 0, 0), 20, 2, "CCW") - polygon = Polygon([(0.8e-6 if x == 0 else x, y - 20) for x, y in bend.physical_geometry[0].exterior.coords]) - net = NetSpec("corner", Port(10, 10, 0), Port(30, 30, 90)) - keepout = box(0, 7, 9.9000004, 13) - problem = RoutingProblem((0, 0, 50, 50), (net,), (keepout,), clearance=0.1) - options = RoutingOptions(search=SearchOptions(node_limit=30, bend_radii=(20,), sbend_radii=(), bend_physical_geometry=polygon)) - - result = route(problem, options=options).results_by_net[net.net_id] - - assert result.is_valid - assert result.as_seed() == PathSeed((Bend90Seed(20, "CCW"),)) - - def _nearby_sbend_outlines() -> tuple[SBendOutline, SBendOutline]: outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15)) return outline, replace(outline, width=0.3 * (1 + 1.5e-12)) @@ -643,36 +379,7 @@ def test_custom_sbend_outline_rejects_duplicate_and_ambiguous_widths() -> None: options.sbend_outline(40, 50, (outline.width + other.width) / 2) -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_ambiguous_sbend_outline_reports_the_affected_net_without_blocking_straights(mode) -> None: - outline, other = _nearby_sbend_outlines() - width = (outline.width + other.width) / 2 - peer = NetSpec("peer", Port(10, 80, 0), Port(90, 80, 0), width=0.5) - line = NetSpec("line", Port(10, 10, 0), Port(50, 10, 0), width=width) - problem = RoutingProblem((0, 0, 100, 100), (peer, line), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=10, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline, other)), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode=mode), - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - ) - callbacks = [] - - run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results)) - - assert all(result.is_valid for result in run.results_by_net.values()) - error = f"Ambiguous S-bend outlines for width {width!r} at (offset 40, radius 50)" - assert run.results_by_net["line"].report.sbend_template_error == error - assert run.results_by_net["peer"].report.sbend_template_error is None - assert callbacks - assert callbacks[-1]["line"].report.sbend_template_error == error - assert {net.net_id: net.report.sbend_template_error for net in run.conflict_trace[-1].nets} == {"peer": None, "line": error} - disabled = replace(options, search=replace(options.search, sbend_offsets=())) - assert route(problem, options=disabled).results_by_net["line"].report.sbend_template_error is None - - -@pytest.mark.parametrize("mode", ["automatic", "off"]) -@pytest.mark.parametrize("node_limit", [0, 20]) +@pytest.mark.parametrize(('mode', 'node_limit'), [('automatic', 0), ('off', 20)]) def test_ambiguous_sbend_outline_is_skipped_in_search_and_seed_replay(mode, node_limit) -> None: outline, other = _nearby_sbend_outlines() width = (outline.width + other.width) / 2 @@ -697,27 +404,26 @@ def test_ambiguous_sbend_outline_is_skipped_in_search_and_seed_replay(mode, node assert "segment 1 (SBendSeed) Ambiguous S-bend outlines" in results["shift"].report.seed_error -@pytest.mark.parametrize("contact", ["face", "rounding", "gap", "extra_edge", "extra_point", "wide_face", "overlap"]) -@pytest.mark.parametrize("heading", [0, 90]) +@pytest.mark.parametrize( + ('contact', 'heading'), + [ + ('gap', 0), + ('face', 90), + ('overlap', 90), + ], +) def test_custom_sbend_join_allows_boundary_contact_and_rejects_area_overlap(contact, heading) -> None: left, right = _sbend_strip(40), _sbend_strip(-40) - if contact in ("rounding", "gap"): - shift = 0.25e-6 if contact == "rounding" else 0.75 - left, right = translate(left, -shift), translate(right, shift) - if contact == "wide_face": - left, right = _sbend_strip(40, half_width=2), _sbend_strip(-40, half_width=2) - if contact == "overlap": + if contact == "gap": + left, right = translate(left, -0.75), translate(right, 0.75) + elif contact == "overlap": right = translate(right, -0.5) - if contact in ("extra_edge", "extra_point"): - left = left.union(box(70, 36, 74, 51)).union(box(73, 49, 80, 51)) - tip = box(0, 9, 7, 11) if contact == "extra_edge" else Polygon([(0, 50 - 40), (7, 9), (7, 11)]) - right = right.union(box(6, -3, 8, 11)).union(tip) start = Port(20, 30, 0) if heading == 0 else Port(100, 20, 90) finish = Port(180, 30, 0) if heading == 0 else Port(100, 180, 90) net = NetSpec("shift", start, finish) seed = PathSeed((SBendSeed(40, 50), SBendSeed(-40, 50))) problem = RoutingProblem((0, 0, 220, 220), (net,), initial_paths={"shift": seed}, clearance=0) - warning = pytest.warns(UserWarning, match="port faces") if contact in ("gap", "wide_face", "overlap") else nullcontext() + warning = pytest.warns(UserWarning, match="port faces") if contact in ("gap", "overlap") else nullcontext() with warning: options = RoutingOptions(search=SearchOptions( node_limit=0, sbend_radii=(50,), @@ -728,33 +434,22 @@ def test_custom_sbend_join_allows_boundary_contact_and_rejects_area_overlap(cont assert result.reached_target first, second = result.locked_geometry - if contact in ("rounding", "gap"): + if contact == "gap": assert first.distance(second) > 0 - if contact == "wide_face": - assert first.intersection(second).length == pytest.approx(4) + elif contact == "face": + assert first.intersection(second).length == pytest.approx(2) assert (first.intersection(second).area > 0) == (contact == "overlap") assert result.report.self_collision_count == int(contact == "overlap") assert result.is_valid == (contact != "overlap") -def test_custom_sbend_width_is_measured_over_the_whole_port_face() -> None: - with pytest.warns(UserWarning, match="port faces of width"): - SBendOutline(40, 50, 2, _sbend_strip(40, half_width=0.01)) - - outline = Polygon([(0, -1), (20, -2), (80, 39), (80, 40), (80, 41), (20, 5), (0, 1), (0, 0)]) - assert SBendOutline(40, 50, 2, outline).polygon == outline - - -@pytest.mark.parametrize("node_limit", [0, 40]) -def test_custom_sbend_can_exceed_the_circular_width_limit(node_limit) -> None: +def test_custom_sbend_can_exceed_the_circular_width_limit() -> None: polygon = Polygon([(0, -6), (8, -2), (8, 10), (0, 6)]) outline = SBendOutline(4, 5, 12, polygon) net = NetSpec("wide", Port(10, 10, 0), Port(18, 14, 0), width=12) seed = PathSeed((SBendSeed(4, 5),)) - problem = RoutingProblem( - (0, 0, 50, 50), (net,), initial_paths={} if node_limit else {net.net_id: seed}, clearance=0, - ) - options = RoutingOptions(search=SearchOptions(node_limit=node_limit, bend_radii=(), sbend_radii=(5,), sbend_outlines=(outline,))) + problem = RoutingProblem((0, 0, 50, 50), (net,), clearance=0) + options = RoutingOptions(search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=(5,), sbend_outlines=(outline,))) result = route(problem, options=options).results_by_net[net.net_id] @@ -763,7 +458,13 @@ def test_custom_sbend_can_exceed_the_circular_width_limit(node_limit) -> None: assert result.locked_geometry == (translate(polygon, 10, 10),) -@pytest.mark.parametrize(("node_limit", "circular_proxy"), [(0, False), (40, False), (0, True)]) +@pytest.mark.parametrize( + ('node_limit', 'circular_proxy'), + [ + (40, False), + (0, True), + ], +) def test_custom_quarter_turn_width_depends_on_whether_it_uses_a_circular_proxy(node_limit, circular_proxy) -> None: polygon = box(0, -5, 5, -3).union(box(3, -5, 5, 0)) net = NetSpec("wide", Port(20, 20, 0), Port(24, 24, 90), width=10) @@ -789,39 +490,24 @@ def test_custom_quarter_turn_width_depends_on_whether_it_uses_a_circular_proxy(n assert result.locked_geometry == (translate(polygon, 20, 24),) -@pytest.mark.parametrize("width", [2, 4]) -@pytest.mark.parametrize("node_limit", [0, 100]) -def test_custom_quarter_turn_warns_when_its_faces_do_not_match_the_width(width, node_limit) -> None: +def test_custom_quarter_turn_warns_when_its_faces_do_not_match_the_width() -> None: outline = box(0, -11, 11, -9).union(box(9, -11, 11, 0)) - net = NetSpec("bend", Port(10, 20, 0), Port(30, 40, 90), width) + net = NetSpec("bend", Port(10, 20, 0), Port(30, 40, 90), width=4) seed = PathSeed((StraightSeed(10), Bend90Seed(10, "CCW"), StraightSeed(10))) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={} if node_limit else {"bend": seed}, clearance=0) + problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) options = RoutingOptions( - search=SearchOptions(node_limit=node_limit, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=outline), + search=SearchOptions(node_limit=100, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=outline), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="off"), ) - warning = pytest.warns(UserWarning, match="declared port faces of width 4") if width == 4 else nullcontext() - with warning: + with pytest.warns(UserWarning, match="declared port faces of width 4"): result = route(problem, options=options).results_by_net["bend"] assert result.is_valid assert result.as_seed() == seed -def test_custom_quarter_turn_outline_leaves_circular_sbends_available() -> None: - net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0)) - seed = PathSeed((SBendSeed(40, 50),)) - problem = RoutingProblem((0, 0, 160, 160), (net,), initial_paths={"shift": seed}) - options = RoutingOptions(search=SearchOptions(node_limit=0, sbend_radii=(50,), bend_physical_geometry=box(0, -11, 11, 0))) - - result = route(problem, options=options).results_by_net["shift"] - - assert result.is_valid - assert result.locked_geometry == SBend.generate(net.start, 40, 50, 2).physical_geometry - - def test_route_verification_rejects_self_contact_away_from_a_join() -> None: net = NetSpec("fold", Port(10, 10, 0), Port(10, 12, 180)) turn = Bend90Seed(1, "CCW") @@ -840,56 +526,31 @@ def test_route_verification_rejects_self_contact_away_from_a_join() -> None: assert result.report.self_collision_count > 0 -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize(("seed_length", "grid_length"), [(0.2, 1), (19.5, 20), (19.75, 20), (20.49, 20)]) -def test_fractional_straight_seed_uses_grid_length(mode, seed_length, grid_length) -> None: - net = NetSpec("straight", Port(11, 25, 0), Port(11 + grid_length, 25, 0)) - seed = PathSeed((StraightSeed(seed_length),)) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"straight": seed}) - options = RoutingOptions(topology=TopologyOptions(mode=mode), congestion=CongestionOptions(max_iterations=1)) - - result = route(problem, options=options).results_by_net["straight"] - - assert result.is_valid - assert result.report.total_length == grid_length - assert result.as_seed() == PathSeed((StraightSeed(grid_length),)) - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_no_iterations_skips_seed_preparation(mode, monkeypatch) -> None: - problem = RoutingProblem((0, 0, 100, 100), (NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)),)) - options = RoutingOptions(topology=TopologyOptions(mode=mode), congestion=CongestionOptions(max_iterations=0)) - - def fail_if_called(*_args): - pytest.fail("Search preparation ran with zero routing iterations") - - monkeypatch.setattr(PathFinder, "_prepare_topology", fail_if_called) - monkeypatch.setattr(PathFinder, "_build_greedy_warm_start_paths", fail_if_called) - run = route(problem, options=options) - - assert run.results_by_net["line"].outcome == "unroutable" - assert run.metrics.nodes_expanded == run.metrics.warm_start_paths_built == 0 - - -@pytest.mark.parametrize("mode", ["guide", "seed"]) -def test_zero_search_budget_verifies_seeds_without_triangulation(mode, monkeypatch) -> None: - monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) - net = NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"line": PathSeed((StraightSeed(80),))}) - options = RoutingOptions( - search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=1), topology=TopologyOptions(mode=mode), +def test_fractional_straight_seeds_use_grid_lengths() -> None: + lengths = ((0.2, 1, 1), (19.5, 19.5, 20), (20.49, 20.49, 20)) + nets = tuple( + NetSpec(str(y), Port(10, y, 0), Port(10 + target_distance, y, 0)) + for y, (_, target_distance, _) in zip((20, 40, 60), lengths, strict=True) ) + seeds = { + net.net_id: PathSeed((StraightSeed(seed_length),)) + for net, (seed_length, _, _) in zip(nets, lengths, strict=True) + } + problem = RoutingProblem((0, 0, 100, 100), nets, initial_paths=seeds) + options = RoutingOptions(congestion=CongestionOptions(max_iterations=1)) run = route(problem, options=options) - assert run.results_by_net["line"].is_valid assert run.metrics.nodes_expanded == 0 - assert run.metrics.verify_path_report_calls == 1 + for net, (_, _, grid_length) in zip(nets, lengths, strict=True): + result = run.results_by_net[net.net_id] + assert result.is_valid + assert result.report.total_length == grid_length + assert result.as_seed() == PathSeed((StraightSeed(grid_length),)) + assert result.path[-1].end_port == Port(10 + grid_length, net.start.y, 0) -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize("rounds", [1, 10]) -def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monkeypatch) -> None: +def test_verify_only_retains_colliding_seeds_and_final_trace(monkeypatch) -> None: nets = ( NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0)), NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90)), @@ -901,16 +562,16 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke problem = RoutingProblem((0, 0, 100, 100), nets, (box(20, 77, 25, 82),), initial_paths=seeds) options = RoutingOptions( search=SearchOptions(node_limit=0), - congestion=CongestionOptions(max_iterations=rounds), + congestion=CongestionOptions(max_iterations=10), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode=mode), ) def fail_on_proximity(*_args): pytest.fail("Geometry-only verification built a proximity map") monkeypatch.setattr(DangerMap, "precompute", fail_on_proximity) + monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) callbacks = [] run = route(problem, options=options) with_callback = route(problem, options=options, iteration_callback=lambda index, results: callbacks.append((index, results))) @@ -927,8 +588,8 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke iteration, restored, final = run.conflict_trace assert (iteration.stage, restored.stage, final.stage) == ("iteration", "restored_best", "final") assert iteration.conflict_edges == restored.conflict_edges == final.conflict_edges == (("horizontal", "vertical"),) - for traced_net in final.nets[:2]: - assert traced_net.component_conflicts + for traced_net, other_net in zip(final.nets[:2], ("vertical", "horizontal"), strict=True): + assert traced_net.component_conflicts == (ComponentConflictTrace(other_net, 0, 0),) assert traced_net == next(net for net in iteration.nets if net.net_id == traced_net.net_id) assert traced_net == next(net for net in restored.nets if net.net_id == traced_net.net_id) assert run.metrics.nodes_expanded == 0 @@ -941,81 +602,31 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke assert with_callback.metrics.verify_path_report_calls == run.metrics.verify_path_report_calls -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize("move", [Bend90Seed(10, "CCW"), SBendSeed(6, 10)]) -def test_verify_only_reports_width_incompatible_seed_segments(mode, move) -> None: - net = NetSpec("wide", Port(20, 30, 0), Port(30, 40, 90), width=30) - peer = NetSpec("peer", Port(20, 80, 0), Port(70, 80, 0)) - seeds = {"wide": PathSeed((move,)), "peer": PathSeed((StraightSeed(50),))} - problem = RoutingProblem((0, 0, 100, 100), (net, peer), initial_paths=seeds) - options = RoutingOptions( - search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=(10,)), - topology=TopologyOptions(mode=mode), - ) - - callbacks = [] - results = route(problem, options=options, iteration_callback=lambda _, current: callbacks.append(current["wide"].report)).results_by_net - - assert results["peer"].is_valid - report = results["wide"].report - assert report.invalid_geometry - assert report.seed_error == f"Initial path for 'wide' segment 1 ({type(move).__name__}) needs radius at least 15, got 10" - assert callbacks == [report] - - -def test_active_search_can_recover_from_width_incompatible_seed() -> None: - net = NetSpec("wide", Port(20, 30, 0), Port(70, 30, 0), width=30) - problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"wide": PathSeed((Bend90Seed(10, "CCW"),))}) - options = RoutingOptions(search=SearchOptions(node_limit=10, bend_radii=(10,)), topology=TopologyOptions(mode="off")) - - result = route(problem, options=options).results_by_net["wide"] - - assert result.is_valid - assert result.report.seed_error is not None - assert result.as_seed() == PathSeed((StraightSeed(50),)) - - -@pytest.mark.parametrize("rotation", [0, 90, 180, 270]) -def test_lattice_heading_heuristic_is_cardinally_invariant(rotation) -> None: - origin = (60, 60) - start = Port(8, 60, 0).rotated(rotation, origin) - target = Port(112, 101, 0).rotated(rotation, origin) - keepouts = tuple(rotate(polygon, rotation, origin=origin) for polygon in (box(87, 48, 99, 71), box(28, 84, 47, 107))) - problem = RoutingProblem((0, 0, 120, 120), (NetSpec("turn", start, target, 1.75),), keepouts, clearance=1.25) - options = RoutingOptions( - search=SearchOptions(node_limit=50, bend_radii=(10,), sbend_radii=()), - objective=ObjectiveWeights(danger_weight=0), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - - assert run.results_by_net["turn"].is_valid - assert run.metrics.nodes_expanded == 17 - - -@pytest.mark.parametrize("price", [0.001, 1, 1000, 1e12]) -def test_lattice_length_cost_units_preserve_search_order(price) -> None: +def test_lattice_length_cost_units_preserve_search_order() -> None: net = NetSpec("turn", Port(15, 40, 0), Port(165, 80, 0)) problem = RoutingProblem((0, 0, 190, 100), (net,), (box(63, 7, 85, 55),)) options = RoutingOptions( search=SearchOptions(node_limit=32, min_straight_length=2, bend_radii=(10,), sbend_radii=()), - objective=ObjectiveWeights(price, 0, 0, 0), + diagnostics=DiagnosticsOptions(capture_expanded=True), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) - run = route(problem, options=options) + small = route(problem, options=replace(options, objective=ObjectiveWeights(0.001, 0, 0, 0))) + large = route(problem, options=replace(options, objective=ObjectiveWeights(1e12, 0, 0, 0))) - assert run.results_by_net["turn"].is_valid - assert run.metrics.nodes_expanded == 12 + assert small.results_by_net["turn"].is_valid + assert large.results_by_net["turn"].is_valid + assert small.results_by_net["turn"].as_seed() == large.results_by_net["turn"].as_seed() + assert small.expanded_nodes + assert small.expanded_nodes == large.expanded_nodes + assert small.metrics.nodes_expanded == large.metrics.nodes_expanded -@pytest.mark.parametrize(("heuristic", "price"), [(1.5, 1), (0, 1), (1.5, 0)]) -def test_partial_path_tracks_geometric_progress_without_cost_heuristic(heuristic, price) -> None: +def test_partial_path_tracks_geometric_progress_without_cost_heuristic() -> None: + heuristic = 1.5 + price = 0 net = NetSpec("across", Port(5, 20, 0), Port(90, 20, 0)) problem = RoutingProblem((0, 0, 100, 40), (net,), (box(45, 0, 55, 40),)) options = RoutingOptions( @@ -1031,23 +642,14 @@ def test_partial_path_tracks_geometric_progress_without_cost_heuristic(heuristic assert run.results_by_net["across"].outcome == "partial" -@pytest.mark.parametrize(("mode", "node_limit", "coordinates"), [ - ("automatic", 20, (30, 20)), - ("off", 20, (30.4, 20.4)), - ("guide", 20, (101, 20)), - ("seed", 0, (30.4, 20.4)), -]) -def test_coincident_ports_are_reported_without_blocking_the_batch(mode, node_limit, coordinates) -> None: - x, y = coordinates - net = NetSpec("abutting", Port(round(x), round(y), 0), Port(x, y, 0)) +def test_coincident_ports_are_reported_without_blocking_the_batch() -> None: + net = NetSpec("abutting", Port(30, 20, 0), Port(30.4, 20.4, 0)) peer = NetSpec("peer", Port(10, 60, 0), Port(70, 60, 0)) - seeds = {net.net_id: PathSeed((Bend90Seed(41, "CCW"),))} - if not node_limit: - seeds[peer.net_id] = PathSeed((StraightSeed(60),)) + seeds = {net.net_id: PathSeed((Bend90Seed(41, "CCW"),)), peer.net_id: PathSeed((StraightSeed(60),))} problem = RoutingProblem((0, 0, 100, 100), (net, peer), initial_paths=seeds) options = RoutingOptions( - search=SearchOptions(node_limit=node_limit), - topology=TopologyOptions(mode=mode), + search=SearchOptions(node_limit=0), + topology=TopologyOptions(mode="seed"), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) callbacks = [] @@ -1062,186 +664,101 @@ def test_coincident_ports_are_reported_without_blocking_the_batch(mode, node_lim assert rejected.effective_net == net assert rejected.report.terminal_error == f"start and target ports {net.start.as_tuple()} coincide after grid snapping" assert run.results_by_net[peer.net_id].is_valid + assert callbacks assert all(results[net.net_id] == rejected for results in callbacks) assert next(trace.report for trace in run.conflict_trace[-1].nets if trace.net_id == net.net_id) == rejected.report - if run.automatic is not None: - assert run.automatic.max_routed == 1 -@pytest.mark.parametrize("mode", ["off", "automatic"]) -@pytest.mark.parametrize(("target_x", "blocked", "message"), [ - (302, False, "face extends outside the routing board"), - (280, True, "face violates keepout clearance"), - (300, False, None), -]) -def test_invalid_terminal_faces_are_reported_without_search(mode, target_x, blocked, message) -> None: +def test_invalid_terminal_faces_are_reported_without_search() -> None: nets = ( - NetSpec("bad", Port(10, 80, 0), Port(target_x, 80, 0)), - NetSpec("peer", Port(10, 120, 0), Port(80, 120, 0)), + NetSpec("outside", Port(10, 40, 0), Port(302, 40, 0)), + NetSpec("blocked", Port(10, 80, 0), Port(280, 80, 0)), + NetSpec("flush", Port(10, 120, 0), Port(300, 120, 0)), ) - keepouts = (box(275, 75, 285, 85),) if blocked else () - problem = RoutingProblem((0, 0, 300, 160), nets, keepouts) + problem = RoutingProblem((0, 0, 300, 160), nets, (box(275, 75, 285, 85),)) options = RoutingOptions( search=SearchOptions(node_limit=600, bend_radii=(20,)), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode=mode), ) run = route(problem, options=options) - bad = run.results_by_net["bad"] - assert run.results_by_net["peer"].is_valid - assert bad.is_valid == (message is None) + outside, blocked, flush = (run.results_by_net[net.net_id] for net in nets) + assert not outside.is_valid + assert outside.report.terminal_error == "target port (302, 40, 0) face extends outside the routing board" + assert not blocked.is_valid + assert blocked.report.terminal_error == "target port (280, 80, 0) face violates keepout clearance" + assert flush.is_valid + assert flush.report.terminal_error is None assert run.metrics.nodes_expanded < 10 - if message is None: - assert bad.report.terminal_error is None - else: - assert bad.report.terminal_error == f"target port {(target_x, 80, 0)} {message}" -def test_keepout_clearance_at_face_and_opposite_coincident_headings() -> None: - net = NetSpec("return", Port(50, 50, 0), Port(50, 50, 180)) - problem = RoutingProblem((0, 0, 100, 100), (net,), (box(30, 53, 70, 60),)) - options = RoutingOptions(search=SearchOptions(node_limit=0), topology=TopologyOptions(mode="off")) +def test_same_net_clearance_preserves_join_and_checks_separated_path() -> None: + folds = (("tight", 20, 2), ("clear", 60, 3)) + nets = tuple(NetSpec(name, Port(10, y, 0), Port(10, y + 2 * radius, 180)) for name, y, radius in folds) + seeds = { + name: PathSeed((StraightSeed(25), Bend90Seed(radius, "CCW"), Bend90Seed(radius, "CCW"), StraightSeed(25))) + for name, _, radius in folds + } + problem = RoutingProblem((0, 0, 100, 100), nets, initial_paths=seeds, self_clearance=4) + options = RoutingOptions(search=SearchOptions(node_limit=0, bend_radii=(2, 3))) - result = route(problem, options=options).results_by_net["return"] + spaced = route(problem, options=options).results_by_net + unspaced = route(replace(problem, self_clearance=0), options=options).results_by_net - assert result.report.terminal_error is None - assert result.outcome == "unroutable" + assert not spaced["tight"].is_valid + assert spaced["tight"].report.self_collision_count > 0 + assert spaced["clear"].is_valid + assert all(result.is_valid for result in unspaced.values()) -@pytest.mark.parametrize(("radius", "spacing", "valid"), [(2, 0, True), (2, 4, False), (3, 4, True)]) -def test_same_net_clearance_preserves_join_and_checks_separated_path(radius, spacing, valid) -> None: - net = NetSpec("fold", Port(10, 20, 0), Port(10, 20 + 2 * radius, 180)) - seed = PathSeed((StraightSeed(25), Bend90Seed(radius, "CCW"), Bend90Seed(radius, "CCW"), StraightSeed(25))) - problem = RoutingProblem((0, 0, 100, 50), (net,), initial_paths={"fold": seed}, self_clearance=spacing) - options = RoutingOptions(search=SearchOptions(node_limit=0, bend_radii=(radius,))) - - result = route(problem, options=options).results_by_net["fold"] - - assert result.is_valid is valid - if not valid: - assert result.report.self_collision_count > 0 - - -@pytest.mark.parametrize(("start_x", "y", "collides"), [(10, 22, True), (40, 22, True), (40, 23, False)]) -def test_zero_clearance_forbids_inter_net_contact_but_allows_keepout_edges(start_x, y, collides) -> None: +def test_zero_clearance_forbids_inter_net_contact_but_allows_keepout_edges() -> None: nets = ( NetSpec("first", Port(10, 20, 0), Port(40, 20, 0)), - NetSpec("second", Port(start_x, y, 0), Port(90, y, 0)), + NetSpec("touching", Port(40, 22, 0), Port(90, 22, 0)), + NetSpec("separate", Port(40, 25, 0), Port(90, 25, 0)), ) - seeds = {"first": PathSeed((StraightSeed(30),)), "second": PathSeed((StraightSeed(90 - start_x),))} + seeds = {net.net_id: PathSeed((StraightSeed(net.target.x - net.start.x),)) for net in nets} problem = RoutingProblem((0, 0, 100, 50), nets, (box(10, 15, 40, 19),), initial_paths=seeds, clearance=0) results = route(problem, options=RoutingOptions(search=SearchOptions(node_limit=0))).results_by_net - assert [result.report.static_collision_count for result in results.values()] == [0, 0] - assert [result.report.dynamic_collision_count for result in results.values()] == [int(collides), int(collides)] + assert all(result.report.static_collision_count == 0 for result in results.values()) + assert results["first"].report.dynamic_collision_count == 1 + assert results["touching"].report.dynamic_collision_count == 1 + assert results["separate"].is_valid -def test_automatic_residual_cannot_touch_a_locked_distinct_net_at_zero_clearance() -> None: - nets = ( - NetSpec("first", Port(10, 20, 0), Port(80, 20, 0)), - NetSpec("second", Port(10, 22, 0), Port(80, 22, 0)), - ) - problem = RoutingProblem((0, 0, 100, 50), nets, clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=()), - refinement=RefinementOptions(enabled=False), - ) - - results = route(problem, options=options).results_by_net - - assert sum(result.is_valid for result in results.values()) == 1 - - -def test_zero_clearance_search_counts_physical_congestion_work() -> None: - nets = ( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0)), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90)), - ) - problem = RoutingProblem((0, 0, 100, 100), nets, clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=20, bend_radii=(), sbend_radii=()), - objective=ObjectiveWeights(danger_weight=0), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - diagnostics=DiagnosticsOptions(capture_iteration_trace=True), - ) - - run = route(problem, options=options) - - assert run.metrics.congestion_check_calls >= 2 - assert run.metrics.congestion_candidate_ids >= run.metrics.congestion_exact_pair_checks > 0 - assert run.iteration_trace[0].congestion_check_calls == run.metrics.congestion_check_calls - assert run.iteration_trace[0].congestion_exact_pair_checks == run.metrics.congestion_exact_pair_checks - - -@pytest.mark.parametrize("mode", ["off", "automatic"]) -@pytest.mark.parametrize("node_limit", [0, 10]) -@pytest.mark.parametrize("move", [Bend90Seed(1e11, "CCW"), SBendSeed(1e11, 1e11)]) -def test_unsafe_seed_reports_segment_without_allocating_geometry(monkeypatch, mode, node_limit, move) -> None: +def test_unsafe_seeds_report_segments_without_allocating_geometry(monkeypatch: pytest.MonkeyPatch) -> None: def unexpected_tessellation(*_args, **_kwargs): pytest.fail("Oversized seed reached the tessellator") monkeypatch.setattr(components_module, "_get_arc_polygons", unexpected_tessellation) monkeypatch.setattr(SBend, "_arcs", unexpected_tessellation) - net = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) - problem = RoutingProblem((0, 0, 100, 50), (net,), initial_paths={net.net_id: PathSeed((move,))}) + nets = ( + NetSpec("turn", Port(10, 20, 0), Port(90, 20, 0)), + NetSpec("shift", Port(10, 40, 0), Port(90, 40, 0)), + ) + moves = {"turn": Bend90Seed(1e11, "CCW"), "shift": SBendSeed(1e11, 1e11)} + problem = RoutingProblem( + (0, 0, 100, 60), nets, initial_paths={net_id: PathSeed((move,)) for net_id, move in moves.items()}, + ) options = RoutingOptions( - search=SearchOptions(node_limit=node_limit, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1e11,)), - topology=TopologyOptions(mode=mode), + search=SearchOptions(node_limit=0, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1e11,)), refinement=RefinementOptions(enabled=False), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) run = route(problem, options=options) - result = run.results_by_net[net.net_id] - - assert result.is_valid is bool(node_limit) - assert result.report.seed_error == ( - f"Initial path for 'track' segment 1 ({type(move).__name__}) exceeds 250,000 subdivisions for one circular arc" - ) - assert run.conflict_trace[-1].nets[0].report.seed_error == result.report.seed_error - - -def test_search_rejects_out_of_board_bends_before_tessellation(monkeypatch) -> None: - def unexpected_tessellation(*_args, **_kwargs): - pytest.fail("Search tessellated a bend with an endpoint outside the board") - - monkeypatch.setattr(components_module, "_get_num_segments", unexpected_tessellation) - problem = RoutingProblem((0, 0, 100, 50), (NetSpec("straight", Port(10, 20, 0), Port(90, 20, 0)),)) - options = RoutingOptions( - search=SearchOptions(node_limit=10, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1,), visibility_guidance="off"), - objective=ObjectiveWeights(danger_weight=0), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - assert route(problem, options=options).results_by_net["straight"].is_valid - - -@pytest.mark.parametrize(("second_x", "y", "valid"), [(53, 25, True), (52, 25, False), (50, 26, True)]) -def test_guide_admits_moves_using_physical_inter_net_clearance(second_x, y, valid) -> None: - nets = ( - NetSpec("first", Port(10, 20, 0), Port(50, 20, 0)), - NetSpec("second", Port(second_x, y, 0), Port(90, y, 0)), - ) - problem = RoutingProblem((0, 0, 100, 50), nets, clearance=4) - options = RoutingOptions( - search=SearchOptions(node_limit=50, bend_radii=(), sbend_radii=(), visibility_guidance="off"), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="guide"), - ) - - results = route(problem, options=options).results_by_net - - assert results["first"].is_valid - assert results["second"].is_valid is valid + traced = {net.net_id: net.report for net in run.conflict_trace[-1].nets} + for net_id, move in moves.items(): + result = run.results_by_net[net_id] + assert not result.is_valid + assert result.report.seed_error == ( + f"Initial path for {net_id!r} segment 1 ({type(move).__name__}) exceeds 250,000 subdivisions for one circular arc" + ) + assert traced[net_id].seed_error == result.report.seed_error def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(monkeypatch) -> None: @@ -1257,28 +774,8 @@ def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(mon assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback" -def test_automatic_final_conflict_trace_includes_direct_locks() -> None: - problem = RoutingProblem( - (0, 0, 100, 100), - ( - NetSpec("direct", Port(10, 25, 0), Port(90, 25, 0)), - NetSpec("turn", Port(10, 65, 0), Port(30, 85, 90)), - ), - ) - options = RoutingOptions(diagnostics=DiagnosticsOptions(capture_conflict_trace=True)) - - run = route(problem, options=options) - - assert run.automatic is not None - assert "direct" in run.automatic.stages[run.automatic.selected_stage].direct_net_ids - final = run.conflict_trace[-1] - assert final.stage == "final" - assert final.completed_net_ids == run.automatic.verified_net_ids == ("direct",) - assert {net.net_id: net.report for net in final.nets} == {net_id: result.report for net_id, result in run.results_by_net.items()} - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_routes_report_boundary_violations_in_results_and_diagnostics(mode) -> None: +def test_routes_report_boundary_violations_in_results_and_diagnostics() -> None: + mode = 'automatic' problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( @@ -1318,105 +815,29 @@ def test_routes_report_boundary_violations_in_results_and_diagnostics(mode) -> N assert traced_edge.report == edge.report -def test_lattice_search_detours_inside_board() -> None: - problem = RoutingProblem( - (0, 0, 120, 100), - nets=(NetSpec("detour", Port(10, 20, 0), Port(110, 20, 0)),), - static_obstacles=(box(43, 3, 73, 45),), - clearance=0, +def test_lattice_straight_uses_flat_port_faces_for_clearance() -> None: + nets = ( + NetSpec("touching", Port(10, 20, 0), Port(30, 20, 0)), + NetSpec("blocked", Port(10, 45, 0), Port(30, 45, 0)), ) - options = RoutingOptions( - search=SearchOptions(bend_radii=(5,), sbend_radii=(), node_limit=1000), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net["detour"] - - assert result.is_valid - board = box(*problem.bounds) - assert all(board.covers(polygon) for polygon in result.locked_geometry) - - -@pytest.mark.parametrize("y", [1, 2, 50]) -@pytest.mark.parametrize(("gap", "valid"), [(0.1, True), (0.099, False)]) -def test_lattice_straight_can_run_along_a_keepout_at_clearance(y, gap, valid) -> None: - problem = RoutingProblem( - (0, 0, 100, 100), - nets=(NetSpec("straight", Port(10, y, 0), Port(30, y, 0), width=0.9),), - static_obstacles=(box(15, y + 0.45 + gap, 25, y + 1),), - clearance=0.1, - ) - options = RoutingOptions( - search=SearchOptions(bend_radii=(), sbend_radii=(), node_limit=100), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - assert route(problem, options=options).results_by_net["straight"].is_valid is valid - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed"]) -@pytest.mark.parametrize( - ("obstacle", "valid"), - [(box(32, 16, 36, 24), True), (box(4, 16, 8, 24), True), (box(31.9, 16, 36, 24), False)], -) -def test_lattice_straight_uses_flat_port_faces_for_clearance(mode, obstacle, valid) -> None: - net = NetSpec("line", Port(10, 20, 0), Port(30, 20, 0)) - problem = RoutingProblem((0, 0, 60, 60), (net,), (obstacle,), clearance=2) + obstacles = (box(32, 16, 36, 24), box(31.9, 41, 36, 49)) + problem = RoutingProblem((0, 0, 60, 60), nets, obstacles, clearance=2) options = RoutingOptions( search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=()), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode=mode), - ) - - assert route(problem, options=options).results_by_net["line"].is_valid is valid - - -@pytest.mark.parametrize("min_length", [0, 0.5, 5]) -def test_lattice_can_launch_a_straight_before_a_bend_from_flat_port_face(min_length) -> None: - net = NetSpec("turn", Port(10, 20, 0), Port(50, 30, 90)) - problem = RoutingProblem((0, 15, 60, 32), (net,), (box(4, 16, 8, 24),), clearance=2) - options = RoutingOptions( - search=SearchOptions(node_limit=100, min_straight_length=min_length, bend_radii=(10,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="off"), ) - result = route(problem, options=options).results_by_net["turn"] - - assert result.is_valid - assert result.as_seed() == PathSeed((StraightSeed(30), Bend90Seed(10, "CCW"))) + results = route(problem, options=options).results_by_net + assert results["touching"].is_valid + assert not results["blocked"].is_valid -def test_lattice_partial_path_leaves_crossing_net_valid() -> None: +def test_invalid_seed_leaves_crossing_peer_valid() -> None: blocked = NetSpec("blocked", Port(10, 100, 0), Port(170, 100, 0)) through = NetSpec("through", Port(80, 40, 90), Port(80, 160, 90)) - problem = RoutingProblem((0, 0, 200, 200), (blocked, through), (box(125, 94, 145, 106),)) - options = RoutingOptions( - search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=()), - congestion=CongestionOptions(max_iterations=3, warm_start_enabled=False), - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - partial, complete = run.results_by_net["blocked"], run.results_by_net["through"] - - assert partial.outcome == "partial" - assert partial.locked_geometry[0].intersects(complete.locked_geometry[0]) - assert complete.is_valid - assert all(entry.conflict_edges == () for entry in run.conflict_trace) - - -@pytest.mark.parametrize("reverse", [False, True]) -def test_invalid_seed_leaves_crossing_peer_valid(reverse) -> None: - blocked = NetSpec("blocked", Port(10, 100, 0), Port(170, 100, 0)) - through = NetSpec("through", Port(80, 40, 90), Port(80, 160, 90)) - nets = (through, blocked) if reverse else (blocked, through) seeds = {"blocked": PathSeed((StraightSeed(160),)), "through": PathSeed((StraightSeed(120),))} - problem = RoutingProblem((0, 0, 200, 200), nets, (box(125, 94, 145, 106),), initial_paths=seeds) + problem = RoutingProblem((0, 0, 200, 200), (blocked, through), (box(125, 94, 145, 106),), initial_paths=seeds) options = RoutingOptions( search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=1), @@ -1431,52 +852,6 @@ def test_invalid_seed_leaves_crossing_peer_valid(reverse) -> None: assert all(entry.conflict_edges == () for entry in run.conflict_trace) -def test_lattice_can_chain_straights_before_a_bend_under_scan_limit() -> None: - net = NetSpec("lead", Port(10, 20, 0), Port(80, 30, 90)) - problem = RoutingProblem((0, 15, 95, 32), (net,)) - options = RoutingOptions( - search=SearchOptions(node_limit=100, max_straight_length=10, bend_radii=(10,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net["lead"] - - assert result.is_valid - assert result.as_seed() == PathSeed((*(StraightSeed(10),) * 6, Bend90Seed(10, "CCW"))) - - -def test_lattice_can_turn_away_from_a_distant_target_to_leave_a_keepout() -> None: - net = NetSpec("detour", Port(300, 100, 0), Port(360, 350, 0)) - problem = RoutingProblem((0, 0, 450, 400), (net,), (box(319, 96, 390, 170),)) - options = RoutingOptions( - search=SearchOptions(node_limit=100, bend_radii=(20,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net["detour"] - - assert result.is_valid - assert result.as_seed().segments[0] == Bend90Seed(20, "CW") - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) -def test_search_can_find_consecutive_sbends(mode) -> None: - net = NetSpec("double", Port(20, 20, 0), Port(48, 30, 0)) - problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=(10,), sbend_offsets=(5,)), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode=mode), - ) - - result = route(problem, options=options).results_by_net["double"] - - assert result.is_valid - assert result.as_seed() == PathSeed((SBendSeed(5, 10), SBendSeed(5, 10))) - - def test_congestion_retry_includes_keepout_collision_alongside_peer_conflicts() -> None: static = NetSpec("static", Port(20, 40, 0), Port(230, 40, 0)) horizontal = NetSpec("horizontal", Port(20, 150, 0), Port(230, 150, 0)) @@ -1505,52 +880,6 @@ def test_congestion_retry_includes_keepout_collision_alongside_peer_conflicts() assert run.results_by_net["static"].report.static_collision_count == 1 -def test_close_net_widths_use_distinct_keepout_trees() -> None: - narrow = NetSpec("narrow", Port(10, 20, 0), Port(90, 20, 0), width=2.00001) - wide = NetSpec("wide", Port(10, 60, 0), Port(90, 60, 0), width=2.00004) - problem = RoutingProblem((0, 0, 100, 100), (narrow, wide), (box(28, 21.00001, 75, 31),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - for candidate in (problem, replace(problem, nets=(wide, narrow))): - run = route(candidate, options=options) - assert all(result.is_valid for result in run.results_by_net.values()) - assert run.metrics.static_net_tree_rebuilds == 2 - - -def test_lattice_can_find_a_bend_with_diagonal_clearance_at_its_port() -> None: - net = NetSpec("turn", Port(20, 20, 0), Port(30, 30, 90)) - problem = RoutingProblem((0, 0, 100, 100), (net,), (box(16, 14, 19.25, 17.125),), clearance=2) - options = RoutingOptions( - search=SearchOptions(node_limit=100, bend_radii=(10,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - topology=TopologyOptions(mode="off"), - ) - - result = route(problem, options=options).results_by_net["turn"] - - assert result.is_valid - assert result.as_seed() == PathSeed((Bend90Seed(10, "CCW"),)) - - -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -def test_fractional_quarter_turn_reaches_its_terminal_face(mode) -> None: - problem = RoutingProblem((0, 0, 100, 100), nets=(NetSpec("bend", Port(20, 20, 0), Port(31, 31, 90)),)) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10.25,), sbend_radii=(), node_limit=100), - congestion=CongestionOptions(max_iterations=1), - topology=TopologyOptions(mode=mode), - ) - - result = route(problem, options=options).results_by_net["bend"] - - assert result.is_valid - assert result.as_seed() == PathSeed((Bend90Seed(10.25, "CCW"),)) - - def test_first_lattice_pass_accepts_fractional_turn_with_keepout_inside_its_bounding_box() -> None: problem = RoutingProblem( (0, 0, 100, 100), @@ -1571,33 +900,21 @@ def test_first_lattice_pass_accepts_fractional_turn_with_keepout_inside_its_boun assert result.as_seed() == PathSeed((Bend90Seed(10.25, "CCW"),)) -@pytest.mark.parametrize("mode", ["automatic", "off"]) -@pytest.mark.parametrize("proxy", ["clipped_bbox", "custom"]) -def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None: - if proxy == "clipped_bbox": - nets = ( - NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)), - NetSpec("b", Port(41, 54, 0), Port(51, 44, 270)), - ) - seeds = {"a": PathSeed((Bend90Seed(10, "CCW"),)), "b": PathSeed((Bend90Seed(10, "CW"),))} - problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths=seeds) - search = SearchOptions(node_limit=100, bend_radii=(10,), bend_collision_type="clipped_bbox", bend_clip_margin=4) - else: - nets = ( - NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)), - NetSpec("b", Port(50, 65, 0), Port(60, 75, 90)), - ) - seed = PathSeed((Bend90Seed(10, "CCW"),)) - problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths={net.net_id: seed for net in nets}) - bend_proxy = box(0, -11, 11, 0) - outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - physical_bend = outline.union(box(10, -8, 13, -6)).union(box(12, -8, 14, 9)) - search = SearchOptions(node_limit=20, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend) +def test_route_verification_detects_physical_bend_overlap() -> None: + nets = ( + NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)), + NetSpec("b", Port(50, 65, 0), Port(60, 75, 90)), + ) + seed = PathSeed((Bend90Seed(10, "CCW"),)) + problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths={net.net_id: seed for net in nets}) + bend_proxy = box(0, -11, 11, 0) + outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) + physical_bend = outline.union(box(10, -8, 13, -6)).union(box(12, -8, 14, 9)) options = RoutingOptions( - search=replace(search, node_limit=0), + search=SearchOptions(node_limit=0, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend), congestion=CongestionOptions(max_iterations=1), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - topology=TopologyOptions(mode=mode), + topology=TopologyOptions(mode="off"), ) run = route(problem, options=options) @@ -1608,12 +925,18 @@ def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None: for result in (left, right): assert result.outcome == "colliding" assert result.report.dynamic_collision_count == 1 - if run.automatic is not None: - assert run.automatic.verified_net_ids == () assert run.conflict_trace[-1].conflict_edges == (("a", "b"),) -@pytest.mark.parametrize("node_limit", [40, 500, 700, None], ids=["tight", "initial", "higher", "default"]) +@pytest.mark.parametrize( + 'node_limit', + [ + 40, + 500, + 700, + ], + ids=['tight', 'initial', 'higher'], +) def test_default_router_escalates_only_within_the_configured_node_limit(monkeypatch, node_limit) -> None: problem = RoutingProblem((0, 0, 200, 200), (NetSpec("turn", Port(20, 20, 0), Port(180, 160, 90)),)) route_astar = router_module.route_astar @@ -1639,279 +962,7 @@ def test_default_router_escalates_only_within_the_configured_node_limit(monkeypa assert run.results_by_net["turn"].is_valid == (ceiling > 500) -def test_default_router_uses_lattice_when_triangulation_is_unavailable(monkeypatch) -> None: - problem = RoutingProblem((0, 0, 200, 200), (NetSpec("turn", Port(20, 20, 0), Port(180, 160, 90)),)) - monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) - - run = route(problem) - - assert run.automatic is not None - assert run.automatic.selected_planner == "lattice" - assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback" - assert run.automatic.verified_net_ids == ("turn",) - - -def test_route_problem_supports_configs_and_debug_data() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net1", Port(10, 10, 0), Port(90, 90, 0), width=2.0),), - static_obstacles=(box(40, 0, 60, 70),), - ) - options = RoutingOptions( - search=SearchOptions( - bend_radii=(10.0,), - node_limit=50000, - greedy_h_weight=1.2, - ), - objective=ObjectiveWeights( - bend_penalty=50.0, - sbend_penalty=150.0, - ), - congestion=CongestionOptions(warm_start_enabled=False), - refinement=RefinementOptions(enabled=True), - diagnostics=DiagnosticsOptions(capture_expanded=True), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - - assert run.results_by_net["net1"].reached_target - assert run.expanded_nodes - assert run.metrics.nodes_expanded > 0 - assert run.metrics.route_iterations >= 1 - assert run.metrics.iteration_reverify_calls >= 1 - assert run.metrics.iteration_reverified_nets >= 0 - assert run.metrics.iteration_conflicting_nets >= 0 - assert run.metrics.iteration_conflict_edges >= 0 - assert run.metrics.nets_carried_forward >= 0 - assert run.metrics.nets_routed >= 1 - assert run.metrics.move_cache_abs_misses >= 0 - assert run.metrics.ray_cast_calls >= 0 - assert run.metrics.dynamic_tree_rebuilds >= 0 - assert run.metrics.visibility_corner_index_builds >= 0 - assert run.metrics.visibility_builds >= 0 - assert run.metrics.guidance_match_moves >= 0 - assert run.metrics.guidance_match_moves_straight >= 0 - assert run.metrics.guidance_match_moves_bend90 >= 0 - assert run.metrics.guidance_match_moves_sbend >= 0 - assert run.metrics.guidance_bonus_applied >= 0.0 - assert run.metrics.guidance_bonus_applied_straight >= 0.0 - assert run.metrics.guidance_bonus_applied_bend90 >= 0.0 - assert run.metrics.guidance_bonus_applied_sbend >= 0.0 - assert run.metrics.congestion_grid_span_cache_hits >= 0 - assert run.metrics.congestion_grid_span_cache_misses >= 0 - assert run.metrics.congestion_presence_cache_hits >= 0 - assert run.metrics.congestion_presence_cache_misses >= 0 - assert run.metrics.congestion_presence_skips >= 0 - assert run.metrics.congestion_candidate_precheck_hits >= 0 - assert run.metrics.congestion_candidate_precheck_misses >= 0 - assert run.metrics.congestion_candidate_precheck_skips >= 0 - assert run.metrics.congestion_candidate_nets >= 0 - assert run.metrics.congestion_net_envelope_cache_hits >= 0 - assert run.metrics.congestion_net_envelope_cache_misses >= 0 - assert run.metrics.congestion_grid_net_cache_hits >= 0 - assert run.metrics.congestion_grid_net_cache_misses >= 0 - assert run.metrics.congestion_lazy_resolutions >= 0 - assert run.metrics.congestion_lazy_requeues >= 0 - assert run.metrics.congestion_candidate_ids >= 0 - assert run.metrics.verify_dynamic_candidate_nets >= 0 - assert run.metrics.verify_path_report_calls >= 0 - assert run.metrics.pair_local_search_pairs_considered >= 0 - assert run.metrics.pair_local_search_attempts >= 0 - assert run.metrics.pair_local_search_accepts >= 0 - assert run.metrics.pair_local_search_nodes_expanded >= 0 - assert run.metrics.late_phase_capped_nets >= 0 - assert run.metrics.late_phase_capped_fallbacks >= 0 - - -def test_iteration_callback_observes_reverified_conflicts() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - snapshots: list[dict[str, str]] = [] - - def callback(iteration: int, current_results: dict[str, object]) -> None: - _ = iteration - snapshots.append({net_id: result.outcome for net_id, result in current_results.items()}) - - results = pathfinder.route_all(iteration_callback=callback) - - assert snapshots == [{"horizontal": "colliding", "vertical": "colliding"}] - assert results["horizontal"].outcome == "colliding" - assert results["vertical"].outcome == "colliding" - - -@pytest.mark.parametrize("mutate_results", [False, True]) -def test_installed_best_iteration_isolated_from_callback_edits(mutate_results: bool) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net", Port(10, 50, 0), Port(90, 50, 0)),), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - world = RoutingWorld(clearance=problem.clearance) - finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options)) - - def callback(_iteration, results): - assert results["net"].is_valid - wrong_path = (Straight.generate(Port(10, 75, 0), 80, 2.0),) - results["net"] = RoutingResult("net", wrong_path, reached_target=True) - - results = finder.route_all(iteration_callback=callback if mutate_results else None) - - assert results["net"].is_valid - assert results["net"].path[0].start_port == problem.nets[0].start - assert world.has_dynamic_paths() - assert finder.metrics.snapshot().dynamic_path_objects_added == 1 - assert finder.metrics.snapshot().dynamic_path_objects_removed == 0 - assert finder.metrics.snapshot().verify_path_report_calls == 3 - - -def test_capture_conflict_trace_preserves_route_outputs() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - base_options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run_without_trace = route(problem, options=base_options) - run_with_trace = route( - problem, - options=RoutingOptions( - congestion=base_options.congestion, - refinement=base_options.refinement, - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - ), - ) - - assert {net_id: result.outcome for net_id, result in run_without_trace.results_by_net.items()} == { - net_id: result.outcome for net_id, result in run_with_trace.results_by_net.items() - } - assert [entry.stage for entry in run_with_trace.conflict_trace] == ["iteration", "restored_best", "final"] - - -def test_capture_iteration_trace_preserves_route_outputs(monkeypatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - base_options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - def unexpected_attempt_trace(*_args, **_kwargs): - pytest.fail("Routing built an attempt trace with diagnostics disabled") - - with monkeypatch.context() as patch: - patch.setattr(router_module, "net_attempt_trace", unexpected_attempt_trace) - run_without_trace = route(problem, options=base_options) - run_with_trace = route( - problem, - options=RoutingOptions( - congestion=base_options.congestion, - refinement=base_options.refinement, - diagnostics=DiagnosticsOptions(capture_iteration_trace=True), - ), - ) - - assert {net_id: result.outcome for net_id, result in run_without_trace.results_by_net.items()} == { - net_id: result.outcome for net_id, result in run_with_trace.results_by_net.items() - } - assert len(run_with_trace.iteration_trace) == 1 - - -def test_capture_iteration_trace_records_iteration_and_attempt_deltas() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - run = route( - problem, - options=RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - diagnostics=DiagnosticsOptions(capture_iteration_trace=True), - topology=TopologyOptions(mode="off"), - ), - ) - - entry = run.iteration_trace[0] - assert entry.iteration == 0 - assert entry.congestion_penalty == 100.0 - assert entry.routed_net_ids == ("horizontal", "vertical") - assert entry.completed_nets == 0 - assert entry.conflict_edges == 1 - assert entry.total_dynamic_collisions >= 2 - assert entry.nodes_expanded >= 0 - assert entry.congestion_check_calls >= 0 - assert entry.congestion_candidate_ids >= 0 - assert entry.congestion_exact_pair_checks >= 0 - assert len(entry.net_attempts) == 2 - assert [attempt.net_id for attempt in entry.net_attempts] == ["horizontal", "vertical"] - assert all(attempt.nodes_expanded >= 0 for attempt in entry.net_attempts) - assert all(attempt.congestion_check_calls >= 0 for attempt in entry.net_attempts) - assert all(not attempt.guidance_seed_present for attempt in entry.net_attempts) - assert sum(attempt.nodes_expanded for attempt in entry.net_attempts) == entry.nodes_expanded - assert sum(attempt.congestion_check_calls for attempt in entry.net_attempts) == entry.congestion_check_calls - - -def test_capture_conflict_trace_records_component_pairs() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - final_entry = run.conflict_trace[-1] - trace_by_net = {net.net_id: net for net in final_entry.nets} - - assert final_entry.stage == "final" - assert final_entry.conflict_edges == (("horizontal", "vertical"),) - assert trace_by_net["horizontal"].component_conflicts[0].other_net_id == "vertical" - assert trace_by_net["horizontal"].component_conflicts[0].self_component_index == 0 - assert trace_by_net["horizontal"].component_conflicts[0].other_component_index == 0 - assert trace_by_net["vertical"].component_conflicts[0].other_net_id == "horizontal" - assert trace_by_net["vertical"].component_conflicts[0].self_component_index == 0 - assert trace_by_net["vertical"].component_conflicts[0].other_component_index == 0 - - -@pytest.mark.parametrize("replay", [False, True]) -def test_capture_frontier_trace_preserves_route_outputs(replay) -> None: +def test_capture_frontier_trace_preserves_route_outputs() -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( @@ -1919,105 +970,24 @@ def test_capture_frontier_trace_preserves_route_outputs(replay) -> None: NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), ), ) + problem = replace(problem, initial_paths={net.net_id: PathSeed((StraightSeed(80),)) for net in problem.nets}) base_options = RoutingOptions( + search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) - if replay: - problem = replace(problem, initial_paths={net.net_id: PathSeed((StraightSeed(80),)) for net in problem.nets}) - base_options = replace(base_options, search=replace(base_options.search, node_limit=0)) - run_without_trace = route(problem, options=base_options) run_with_trace = route( problem, options=replace(base_options, diagnostics=DiagnosticsOptions(capture_frontier_trace=True)), ) - assert {net_id: result.outcome for net_id, result in run_without_trace.results_by_net.items()} == { - net_id: result.outcome for net_id, result in run_with_trace.results_by_net.items() - } + assert run_without_trace.results_by_net == run_with_trace.results_by_net assert {trace.net_id for trace in run_with_trace.frontier_trace} == {"horizontal", "vertical"} assert run_with_trace.metrics.verify_path_report_calls == run_without_trace.metrics.verify_path_report_calls -def test_capture_pre_pair_frontier_trace_preserves_route_outputs() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - base_options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run_without_trace = route(problem, options=base_options) - run_with_trace = route( - problem, - options=RoutingOptions( - congestion=base_options.congestion, - refinement=base_options.refinement, - diagnostics=DiagnosticsOptions(capture_pre_pair_frontier_trace=True), - ), - ) - - assert {net_id: result.outcome for net_id, result in run_without_trace.results_by_net.items()} == { - net_id: result.outcome for net_id, result in run_with_trace.results_by_net.items() - } - assert run_with_trace.pre_pair_frontier_trace is None - - -def test_capture_frontier_trace_records_prune_reasons() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - run = route( - problem, - options=RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - diagnostics=DiagnosticsOptions(capture_frontier_trace=True), - topology=TopologyOptions(mode="off"), - ), - ) - - trace_by_net = {entry.net_id: entry for entry in run.frontier_trace} - assert trace_by_net["horizontal"].hotspot_bounds - assert ( - trace_by_net["horizontal"].pruned_closed_set - + trace_by_net["horizontal"].pruned_hard_collision - + trace_by_net["horizontal"].pruned_self_collision - + trace_by_net["horizontal"].pruned_cost - ) > 0 - assert trace_by_net["horizontal"].samples - - -def test_reverify_iterations_stop_early_on_stalled_conflict_graph() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=10, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - - assert run.metrics.route_iterations < 10 - - def test_reverify_iterations_limit_late_reroutes_to_conflicting_nets(monkeypatch: pytest.MonkeyPatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), @@ -2111,264 +1081,7 @@ def test_routing_attempts_reserve_an_index_for_a_timed_out_worker(monkeypatch) - assert [entry.iteration for entry in selected.conflict_trace if entry.stage == "iteration"] == [1] -def test_run_iteration_orders_subset_reroutes_by_recent_work(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("netB", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - NetSpec("netC", Port(10, 20, 0), Port(90, 20, 0), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False, shuffle_nets=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - state = pathfinder._prepare_state() - state.recent_attempt_work = {"netA": 200, "netB": 20} - route_order: list[str] = [] - - def fake_route_net_once(self, state, iteration, net_id, *, node_limit_override=None, incumbent_fallback=None): - _ = state - _ = iteration - route_order.append(net_id) - self.metrics.reroute_work += 200 if net_id == "netA" else 20 - self.metrics.total_congestion_check_calls += 1000 if net_id == "netB" else 0 - assert node_limit_override is None - assert incumbent_fallback is None - return RoutingResult(net_id=net_id, path=(), reached_target=False), False - - def fake_reverify(self, state): - _ = self - _ = state - return _IterationReview( - conflicting_nets={"netA", "netB"}, - conflict_edges={("netA", "netB")}, - completed_net_ids=set(), - total_dynamic_collisions=2, - ) - - monkeypatch.setattr(PathFinder, "_route_net_once", fake_route_net_once) - monkeypatch.setattr(PathFinder, "_reverify_iteration_results", fake_reverify) - - review = pathfinder._run_iteration(state, 1, {"netA", "netB"}, None) - - assert review is not None - assert route_order == ["netB", "netA"] - assert state.recent_attempt_work == {"netA": 200, "netB": 20} - pathfinder._run_iteration(state, 2, {"netA", "netB"}, None) - assert route_order == ["netB", "netA", "netB", "netA"] - - -def test_run_iteration_caps_two_heaviest_late_phase_nets(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("netB", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - NetSpec("netC", Port(10, 20, 0), Port(90, 20, 0), width=2.0), - NetSpec("netD", Port(10, 80, 0), Port(90, 80, 0), width=2.0), - NetSpec("netE", Port(10, 65, 0), Port(90, 65, 0), width=2.0), - ), - ) - options = RoutingOptions( - objective=ObjectiveWeights(bend_penalty=100.0), - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False, shuffle_nets=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - state = pathfinder._prepare_state() - state.results = { - net_id: RoutingResult(net_id=net_id, path=(Straight.generate(spec.start, 80.0, 2.0, dilation=1.0),), reached_target=True) - for net_id, spec in state.net_specs.items() - } - state.best_review = _IterationReview({"netA", "netB", "netC", "netD"}, {("netA", "netB"), ("netC", "netD")}, {"netE"}, 4) - state.recent_attempt_work = {"netA": 20, "netB": 40, "netC": 400, "netD": 220} - incumbents = dict(state.results) - caps_by_net: dict[str, tuple[int | None, RoutingResult | None]] = {} - - def fake_route_net_once(self, state, iteration, net_id, *, node_limit_override=None, incumbent_fallback=None): - _ = self - _ = state - _ = iteration - caps_by_net[net_id] = (node_limit_override, incumbent_fallback) - return RoutingResult(net_id=net_id, path=(), reached_target=False), False - - def fake_reverify(self, state): - _ = self - _ = state - return _IterationReview( - conflicting_nets={"netA", "netB", "netC", "netD"}, - conflict_edges={("netA", "netB"), ("netC", "netD")}, - completed_net_ids=set(), - total_dynamic_collisions=2, - ) - - monkeypatch.setattr(PathFinder, "_route_net_once", fake_route_net_once) - monkeypatch.setattr(PathFinder, "_reverify_iteration_results", fake_reverify) - - review = pathfinder._run_iteration(state, 1, {"netA", "netB", "netC", "netD"}, None) - - assert review is not None - assert caps_by_net["netA"] == (None, None) - assert caps_by_net["netB"] == (None, None) - assert caps_by_net["netC"][0] == 1 - assert caps_by_net["netD"][0] == 1 - assert caps_by_net["netC"][1] is incumbents["netC"] - assert caps_by_net["netD"][1] is incumbents["netD"] - - -def test_route_net_once_skips_search_for_capped_incumbent_fallback(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), - ) - options = RoutingOptions( - objective=ObjectiveWeights(bend_penalty=100.0), - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - state = pathfinder._prepare_state() - incumbent = RoutingResult( - net_id="netA", - path=(Straight.generate(problem.nets[0].start, 80.0, 2.0, dilation=1.0),), - reached_target=True, - ) - state.results["netA"] = incumbent - installed: list[tuple[str, tuple[object, ...]]] = [] - - def fail_route_astar(*_args, **_kwargs): - raise AssertionError("route_astar should not run for capped incumbent fallback") - - def record_added_route(self, net_id, path): - _ = self - installed.append((net_id, tuple(path))) - - monkeypatch.setattr(router_module, "route_astar", fail_route_astar) - monkeypatch.setattr(PathFinder, "_add_route", record_added_route) - - result, guidance_seed_present = pathfinder._route_net_once( - state, - 1, - "netA", - node_limit_override=1, - incumbent_fallback=incumbent, - ) - - assert result is incumbent - assert guidance_seed_present is True - assert installed == [("netA", incumbent.path)] - assert pathfinder.metrics.total_late_phase_capped_nets == 1 - assert pathfinder.metrics.total_late_phase_capped_fallbacks == 1 - - -def test_route_all_restores_best_iteration_snapshot(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=( - NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0), - NetSpec("netB", Port(50, 10, 90), Port(50, 90, 90), width=2.0), - ), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - best_result = RoutingResult( - net_id="netA", - path=(Straight.generate(Port(10, 50, 0), 80.0, 2.0, dilation=1.0),), - reached_target=True, - report=RoutingReport(), - ) - missing_result = RoutingResult(net_id="netA", path=(), reached_target=False) - unroutable_b = RoutingResult(net_id="netB", path=(), reached_target=False) - - def fake_run_iteration(self, state, iteration, reroute_net_ids, iteration_callback): - _ = self - _ = reroute_net_ids - _ = iteration_callback - if iteration == 0: - state.results = {"netA": best_result, "netB": unroutable_b} - return _IterationReview( - conflicting_nets={"netA", "netB"}, - conflict_edges={("netA", "netB")}, - completed_net_ids={"netA"}, - total_dynamic_collisions=1, - ) - state.results = {"netA": missing_result, "netB": unroutable_b} - return _IterationReview( - conflicting_nets={"netA", "netB"}, - conflict_edges={("netA", "netB")}, - completed_net_ids=set(), - total_dynamic_collisions=2, - ) - - monkeypatch.setattr(PathFinder, "_run_iteration", fake_run_iteration) - monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: (dict(state.results), {})) - - results = pathfinder.route_all() - - assert results["netA"].outcome == "completed" - assert results["netB"].outcome == "unroutable" - assert evaluator.collision_engine.has_dynamic_paths() - assert pathfinder.metrics.snapshot().verify_path_report_calls == 1 - - -def test_first_iteration_and_pair_length_tie_break() -> None: - problem = RoutingProblem(bounds=(0, 0, 100, 100)) - options = RoutingOptions(congestion=CongestionOptions(warm_start_enabled=False), topology=TopologyOptions(mode="off")) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - finder = PathFinder(AStarContext(evaluator, problem, options)) - state = finder._prepare_state() - review = _IterationReview(set(), set(), set(), 0) - - assert finder._update_best_iteration(state, review) - assert not finder._update_best_iteration(state, review) - - def results(length): - return {"a": RoutingResult("a", (), reached_target=True, report=RoutingReport(total_length=length))} - - incumbent = results(10.0) - assert not finder._whole_set_is_better(results(10.0 - 0.5e-6), review, incumbent, review) - assert finder._whole_set_is_better(results(10.0 - 2e-6), review, incumbent, review) - - -def test_pair_repair_limits_disjoint_targets_in_routing_order(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=tuple(NetSpec(net_id, Port(10, i * 10, 0), Port(90, i * 10, 0)) for i, net_id in enumerate("cdbaef", 1)), - ) - options = RoutingOptions(congestion=CongestionOptions(warm_start_enabled=False), topology=TopologyOptions(mode="off")) - world = RoutingWorld(clearance=problem.clearance) - finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options)) - state = finder._prepare_state() - state.results = {net_id: RoutingResult(net_id, (), reached_target=True) for net_id in state.ordered_net_ids} - review = _IterationReview(set(state.ordered_net_ids), {("a", "b"), ("c", "d"), ("e", "f")}, set(), 6) - visited = [] - - def repair(_finder, _state, pair, current_review): - visited.append(pair) - return current_review - - monkeypatch.setattr(PathFinder, "_run_pair_local_target", repair) - finder._run_pair_local_search(state, review) - assert visited == [("c", "d"), ("a", "b")] - - visited.clear() - review.conflict_edges.add(("b", "c")) - finder._run_pair_local_search(state, review) - assert not visited - - -@pytest.mark.parametrize("candidate_reaches_live_check", [False, True]) -def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch: pytest.MonkeyPatch, candidate_reaches_live_check: bool) -> None: +def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=tuple(NetSpec(net_id, Port(10, y, 0), Port(90, y, 0)) for net_id, y in (("a", 20), ("b", 40), ("c", 60))), @@ -2389,7 +1102,7 @@ def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch: pyt def search(_context, _ordered, _results, pair_order, **_kwargs): attempted.append(pair_order) assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds - if candidate_reaches_live_check and pair_order == ("a", "b"): + if pair_order == ("a", "b"): return {"a": RoutingResult("a", incumbent["b"].path, reached_target=True), "b": incumbent["b"]}, 0 return None @@ -2401,8 +1114,8 @@ def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch: pyt assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds assert all(world.verify_path_report(net_id, result.path) == result.report for net_id, result in incumbent.items()) metrics = finder.metrics.snapshot() - assert metrics.dynamic_path_objects_added == 3 + 4 * candidate_reaches_live_check - assert metrics.dynamic_path_objects_removed == 4 * candidate_reaches_live_check + assert metrics.dynamic_path_objects_added == 7 + assert metrics.dynamic_path_objects_removed == 4 def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pytest.MonkeyPatch) -> None: @@ -2450,8 +1163,24 @@ def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pyte assert evaluator.collision_engine.has_dynamic_paths() +def test_iteration_prefers_shorter_paths_at_equal_coverage() -> None: + problem = RoutingProblem(bounds=(0, 0, 100, 100)) + options = RoutingOptions(topology=TopologyOptions(mode="off")) + world = RoutingWorld(clearance=problem.clearance) + finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options)) + review = _IterationReview(set(), set(), {"line"}, 0) + + def completed(length): + segment = Straight.generate(Port(10, 10, 0), length, 2.0) + return {"line": RoutingResult("line", (segment,), reached_target=True, report=RoutingReport(total_length=length))} + + incumbent = completed(20) + assert finder._whole_set_is_better(completed(10), review, incumbent, review) + assert not finder._whole_set_is_better(completed(20), review, incumbent, review) + + @pytest.mark.parametrize("during", ["preparation", "search"]) -def test_worker_checks_timeout_inside_single_net_attempt(during, monkeypatch) -> None: +def test_worker_checks_timeout_inside_single_net_attempt(monkeypatch, during) -> None: clock = [0.0] monkeypatch.setattr(router_module.time, "monotonic", lambda: clock[0]) problem = RoutingProblem((0, 0, 100, 100), (NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)),)) @@ -2482,74 +1211,6 @@ def test_worker_checks_timeout_inside_single_net_attempt(during, monkeypatch) -> assert not result.results_by_net["line"].is_valid -def test_capture_conflict_trace_records_restored_best_stage(monkeypatch: pytest.MonkeyPatch) -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - diagnostics=DiagnosticsOptions(capture_conflict_trace=True), - ) - evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) - pathfinder = PathFinder(AStarContext(evaluator, problem, options)) - best_result = RoutingResult( - net_id="netA", - path=(Straight.generate(Port(10, 50, 0), 80.0, 2.0, dilation=1.0),), - reached_target=True, - report=RoutingReport(), - ) - worse_result = RoutingResult(net_id="netA", path=(), reached_target=False) - - def fake_run_iteration(self, state, iteration, reroute_net_ids, iteration_callback): - _ = self - _ = reroute_net_ids - _ = iteration_callback - if iteration == 0: - state.results = {"netA": best_result} - return _IterationReview( - conflicting_nets=set(), - conflict_edges=set(), - completed_net_ids={"netA"}, - total_dynamic_collisions=0, - ) - state.results = {"netA": worse_result} - return _IterationReview( - conflicting_nets=set(), - conflict_edges=set(), - completed_net_ids=set(), - total_dynamic_collisions=0, - ) - - monkeypatch.setattr(PathFinder, "_run_iteration", fake_run_iteration) - - pathfinder.route_all() - - assert [entry.stage for entry in pathfinder.conflict_trace] == [ - "restored_best", - "final", - ] - restored_entry = pathfinder.conflict_trace[0] - assert restored_entry.nets[0].outcome == "completed" -def test_route_problem_locked_routes_become_static_obstacles() -> None: - locked = (Straight.generate(Port(10, 50, 0), 80.0, 2.0, dilation=1.0),) - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("crossing", Port(50, 10, 90), Port(50, 90, 90), width=2.0),), - static_obstacles=tuple(polygon for component in locked for polygon in component.physical_geometry), - ) - options = RoutingOptions( - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - result = run.results_by_net["crossing"] - - assert not result.is_valid - - def test_locked_routes_enable_incremental_requests_without_sessions() -> None: problem_a = RoutingProblem( bounds=(0, -50, 100, 50), @@ -2569,25 +1230,17 @@ def test_locked_routes_enable_incremental_requests_without_sessions() -> None: assert results_b.results_by_net["netB"].is_valid -def test_route_problem_rejects_untyped_initial_paths() -> None: - with pytest.raises(TypeError): - RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net1", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), - initial_paths={"net1": (object(),)}, # type: ignore[dict-item] - ) - - -def test_route_results_metrics_are_snapshots() -> None: - problem = RoutingProblem( - bounds=(0, 0, 100, 100), - nets=(NetSpec("net1", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), +def test_close_net_widths_use_distinct_keepout_trees() -> None: + narrow = NetSpec("narrow", Port(10, 20, 0), Port(90, 20, 0), width=2.00001) + wide = NetSpec("wide", Port(10, 60, 0), Port(90, 60, 0), width=2.00004) + problem = RoutingProblem((0, 0, 100, 100), (narrow, wide), (box(28, 21.00001, 75, 31),), clearance=0) + options = RoutingOptions( + search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=()), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode="off"), ) - options = RoutingOptions(topology=TopologyOptions(mode="off")) - run1 = route(problem, options=options) - first_metrics = run1.metrics - run2 = route(problem, options=options) - assert first_metrics == run1.metrics - assert run1.metrics is not run2.metrics - assert first_metrics.nodes_expanded > 0 + for candidate in (problem, replace(problem, nets=(wide, narrow))): + run = route(candidate, options=options) + assert all(result.is_valid for result in run.results_by_net.values()) + assert run.metrics.static_net_tree_rebuilds == 2 diff --git a/inire/tests/test_astar.py b/inire/tests/test_astar.py index 8a8af6b..78a2e43 100644 --- a/inire/tests/test_astar.py +++ b/inire/tests/test_astar.py @@ -2,23 +2,18 @@ import math import pytest from shapely.geometry import Polygon -from inire import CongestionOptions, NetSpec, ObjectiveWeights, RefinementOptions, RoutingProblem, RoutingOptions, RoutingResult, SearchOptions -from inire.geometry.components import Bend90, Straight +from inire import NetSpec, RoutingProblem, RoutingOptions, RoutingResult, SearchOptions +from inire.geometry.components import Straight from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port from inire.router import _astar_moves from inire.router._astar_types import AStarContext, AStarNode, CongestionCaches, SearchRunConfig from inire.router._astar_admission import add_node -from inire.router._astar_moves import ( - _distance_to_bounds_in_heading, - _should_cap_straights_to_bounds, -) from inire.router._pair_local import _build_pair_local_context from inire.router._search import route_astar from inire.router._stack import build_routing_stack from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap -from inire.seeds import StraightSeed BOUNDS = (0, -50, 150, 150) @@ -111,146 +106,6 @@ def _validate_routing_result( } -def test_astar_straight(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - start = Port(0, 0, 0) - target = Port(50, 0, 0) - path = _route(context, start, target) - - assert path is not None - result = RoutingResult(net_id="test", path=path, reached_target=True) - validation = _validate_routing_result(result, [], clearance=2.0, expected_start=start, expected_end=target) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - assert validation["connectivity_ok"] - # Path should be exactly 50um (or slightly more if it did weird things, but here it's straight) - assert abs(validation["total_length"] - 50.0) < 1e-6 - - -def test_astar_bend(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(10.0,)) - start = Port(0, 0, 0) - # 20um right, 20um up. Needs a 10um bend and a 10um bend. - target = Port(20, 20, 0) - path = _route(context, start, target) - - assert path is not None - result = RoutingResult(net_id="test", path=path, reached_target=True) - validation = _validate_routing_result(result, [], clearance=2.0, expected_start=start, expected_end=target) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - assert validation["connectivity_ok"] - - -def test_astar_obstacle(basic_evaluator: CostEvaluator) -> None: - # Add an obstacle in the middle of a straight path - # Obstacle from x=20 to 40, y=-20 to 20 - obstacle = Polygon([(20, -20), (40, -20), (40, 20), (20, 20)]) - basic_evaluator.collision_engine.add_static_obstacle(obstacle) - basic_evaluator.danger_map.precompute([obstacle]) - - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(10.0,), node_limit=1000000) - start = Port(0, 0, 0) - target = Port(60, 0, 0) - path = _route(context, start, target) - - assert path is not None - result = RoutingResult(net_id="test", path=path, reached_target=True) - validation = _validate_routing_result(result, [obstacle], clearance=2.0, expected_start=start, expected_end=target) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - # Path should have detoured, so length > 50 - assert validation["total_length"] > 50.0 - - -def test_astar_uses_integerized_ports(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - start = Port(0, 0, 0) - target = Port(10.1, 0, 0) - path = _route(context, start, target) - - assert path is not None - result = RoutingResult(net_id="test", path=path, reached_target=True) - assert target.x == 10 - validation = _validate_routing_result(result, [], clearance=2.0, expected_start=start, expected_end=target) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - - -def test_validate_routing_result_checks_expected_start() -> None: - path = [Straight.generate(Port(100, 0, 0), 10.0, width=2.0, dilation=1.0)] - result = RoutingResult(net_id="test", path=path, reached_target=True) - - validation = _validate_routing_result( - result, - [], - clearance=2.0, - expected_start=Port(0, 0, 0), - expected_end=Port(110, 0, 0), - ) - - assert not validation["is_valid"] - assert "Initial port position mismatch" in validation["reason"] - - -def test_validate_routing_result_uses_exact_component_geometry() -> None: - bend = Bend90.generate(Port(0, 0, 0), 10.0, 2.0, direction="CCW", collision_type="bbox", dilation=1.0) - result = RoutingResult(net_id="test", path=[bend], reached_target=True) - obstacle = Polygon([(2.0, 7.0), (4.0, 7.0), (4.0, 9.0), (2.0, 9.0)]) - - validation = _validate_routing_result( - result, - [obstacle], - clearance=2.0, - expected_start=Port(0, 0, 0), - expected_end=bend.end_port, - ) - - assert validation["is_valid"], f"Validation failed: {validation.get('reason')}" - - -def test_astar_context_keeps_evaluator_weights_separate(basic_evaluator: CostEvaluator) -> None: - basic_evaluator = CostEvaluator( - basic_evaluator.collision_engine, - basic_evaluator.danger_map, - bend_penalty=120.0, - sbend_penalty=240.0, - ) - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(5.0,)) - - assert context.options.search.bend_radii == (5.0,) - assert basic_evaluator.h_manhattan(Port(0, 0, 0), Port(10, 10, 0)) > 0.0 - - -def test_distance_to_bounds_in_heading_is_directional() -> None: - bounds = (0, 0, 100, 200) - - assert _distance_to_bounds_in_heading(Port(20, 30, 0), bounds) == pytest.approx(80.0) - assert _distance_to_bounds_in_heading(Port(20, 30, 90), bounds) == pytest.approx(170.0) - assert _distance_to_bounds_in_heading(Port(20, 30, 180), bounds) == pytest.approx(20.0) - assert _distance_to_bounds_in_heading(Port(20, 30, 270), bounds) == pytest.approx(30.0) - - -def test_should_cap_straights_to_bounds_only_for_large_no_warm_runs(basic_evaluator: CostEvaluator) -> None: - large_context = AStarContext( - basic_evaluator, - RoutingProblem( - bounds=(0, 0, 1000, 1000), - nets=tuple( - NetSpec(f"net{i}", Port(0, i * 10, 0), Port(10, i * 10, 0), width=2.0) - for i in range(8) - ), - ), - RoutingOptions( - congestion=CongestionOptions(warm_start_enabled=False), - ), - ) - small_context = _build_context(basic_evaluator, bounds=BOUNDS) - - assert _should_cap_straights_to_bounds(large_context) - assert not _should_cap_straights_to_bounds(small_context) - - def test_equal_cost_arrivals_can_propose_different_straights(monkeypatch) -> None: start, target = Port(5, 20, 0), Port(35, 20, 0) problem = RoutingProblem((0, 0, 100, 50), (NetSpec("track", start, target),)) @@ -299,94 +154,7 @@ def test_pair_local_context_clones_live_static_obstacles() -> None: assert next(iter(local_context.problem.static_obstacles)).equals(obstacle) -@pytest.mark.parametrize( - ("search_danger", "refinement_enabled", "expected_tree"), - [(0.0, False, False), (0.0, True, True), (1.0, False, True)], -) -def test_worker_samples_proximity_only_for_objectives_it_uses(search_danger, refinement_enabled, expected_tree) -> None: - obstacle = Polygon([(20, -8), (40, -8), (40, -5), (20, -5)]) - net = NetSpec("pair_a", Port(10, 0, 0), Port(50, 0, 0)) - problem = RoutingProblem(bounds=BOUNDS, nets=(net,), static_obstacles=(obstacle,)) - options = RoutingOptions( - objective=ObjectiveWeights(danger_weight=search_danger), - refinement=RefinementOptions(enabled=refinement_enabled, objective=ObjectiveWeights(danger_weight=1.0)), - ) - stack = build_routing_stack(problem, options) - local = _build_pair_local_context(stack.context, problem.nets, {}, ("pair_a", "pair_b")) - - assert (stack.danger_map.tree is not None) == expected_tree - assert (local.cost_evaluator.danger_map.tree is not None) == bool(search_danger) - outside = Straight.generate(net.start, 200, net.width) - assert stack.evaluator.score_component(outside, start_port=net.start) == 1e15 - assert local.cost_evaluator.score_component(outside, start_port=net.start) == 1e15 - if refinement_enabled: - move = Straight.generate(net.start, 40, net.width) - assert stack.finder.refiner.score_path(net.start, (move,)) > stack.evaluator.score_component(move, start_port=net.start) - - -def test_route_astar_bend_collision_override_does_not_persist(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(10.0,), bend_collision_type="arc") - - route_astar( - Port(0, 0, 0), - Port(30, 10, 0), - net_width=2.0, - context=context, - config=SearchRunConfig.from_options( - context.options, - bend_collision_type="clipped_bbox", - return_partial=True, - ), - ) - - assert context.options.search.bend_collision_type == "arc" - - -def test_route_astar_returns_partial_path_when_node_limited(basic_evaluator: CostEvaluator) -> None: - obstacle = Polygon([(20, -20), (40, -20), (40, 20), (20, 20)]) - basic_evaluator.collision_engine.add_static_obstacle(obstacle) - basic_evaluator.danger_map.precompute([obstacle]) - context = _build_context(basic_evaluator, bounds=BOUNDS, bend_radii=(10.0,), node_limit=2) - start = Port(0, 0, 0) - target = Port(60, 0, 0) - - partial_path = _route(context, start, target, return_partial=True) - no_partial_path = _route(context, start, target, return_partial=False) - - assert partial_path is not None - assert partial_path - assert partial_path[-1].end_port != target - assert no_partial_path is None - - -def test_route_astar_uses_single_sbend_for_same_orientation_offset(basic_evaluator: CostEvaluator) -> None: - context = _build_context( - basic_evaluator, - bounds=BOUNDS, - bend_radii=(10.0,), - sbend_radii=(10.0,), - sbend_offsets=(10.0,), - max_straight_length=150.0, - ) - start = Port(0, 0, 0) - target = Port(100, 10, 0) - - path = _route(context, start, target) - - assert path is not None - assert path[-1].end_port == target - assert sum(1 for component in path if component.move_type == "sbend") == 1 - assert not any( - first.move_type == second.move_type == "sbend" - for first, second in zip(path, path[1:], strict=False) - ) - - -@pytest.mark.parametrize("visibility_guidance", ["off", "exact_corner", "tangent_corner"]) -def test_route_astar_supports_all_visibility_guidance_modes( - basic_evaluator: CostEvaluator, - visibility_guidance: str, -) -> None: +def test_route_astar_supports_exact_corner_guidance(basic_evaluator: CostEvaluator) -> None: obstacle = Polygon([(30, 10), (50, 10), (50, 40), (30, 40)]) basic_evaluator.collision_engine.add_static_obstacle(obstacle) basic_evaluator.danger_map.precompute([obstacle]) @@ -396,7 +164,7 @@ def test_route_astar_supports_all_visibility_guidance_modes( bend_radii=(10.0,), sbend_radii=(), max_straight_length=150.0, - visibility_guidance=visibility_guidance, + visibility_guidance="exact_corner", ) start = Port(0, 0, 0) target = Port(80, 50, 0) @@ -411,27 +179,6 @@ def test_route_astar_supports_all_visibility_guidance_modes( assert validation["connectivity_ok"] -def test_tangent_corner_mode_uses_only_tangent_queries(basic_evaluator: CostEvaluator) -> None: - obstacle = Polygon([(30, 10), (50, 10), (50, 40), (30, 40)]) - basic_evaluator.collision_engine.add_static_obstacle(obstacle) - basic_evaluator.danger_map.precompute([obstacle]) - context = _build_context( - basic_evaluator, - bounds=BOUNDS, - bend_radii=(10.0,), - sbend_radii=(), - max_straight_length=150.0, - visibility_guidance="tangent_corner", - ) - - path = _route(context, Port(0, 0, 0), Port(80, 50, 0)) - - assert path is not None - assert context.metrics.total_visibility_tangent_candidate_scans > 0 - assert context.metrics.total_visibility_corner_queries_exact == 0 - assert context.metrics.total_visibility_point_queries == 0 - - def test_route_astar_repeated_searches_succeed_with_small_cache_limit(basic_evaluator: CostEvaluator) -> None: context = AStarContext( basic_evaluator, @@ -509,9 +256,8 @@ def test_closed_set_dominance_prunes_before_congestion_check(basic_evaluator: Co assert context.metrics.total_congestion_cache_misses == 0 -@pytest.mark.parametrize(("length_weight", "guidance_bonus", "expected_cost"), [(0.1, 0, 1), (1, 8, 2)]) -def test_closed_set_keeps_cheaper_weighted_or_guided_move(length_weight, guidance_bonus, expected_cost) -> None: - evaluator = CostEvaluator(RoutingWorld(clearance=0), unit_length_cost=length_weight) +def test_closed_set_keeps_cheaper_guided_move() -> None: + evaluator = CostEvaluator(RoutingWorld(clearance=0), unit_length_cost=1) context = _build_context(evaluator, bounds=BOUNDS) root = AStarNode(Port(0, 0, 0), 0.0, 0.0, seed_index=0) move = Straight.generate(root.port, 10, width=2.0) @@ -528,154 +274,12 @@ def test_closed_set_keeps_cheaper_weighted_or_guided_move(length_weight, guidanc metrics=context.metrics, congestion=CongestionCaches(), config=SearchRunConfig.from_options( - context.options, guidance_seed=(move.move_spec,) if guidance_bonus else None, guidance_bonus=guidance_bonus, + context.options, guidance_seed=(move.move_spec,), guidance_bonus=8, ), move_type="straight", cache_key=("cheaper",), ) - assert [node.g_cost for node in open_set] == [expected_cost] - - -def test_no_dynamic_paths_skips_congestion_check(basic_evaluator: CostEvaluator) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - root = AStarNode(Port(0, 0, 0), 0.0, 0.0) - result = Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0) - open_set: list[AStarNode] = [] - closed_set: dict[tuple[int, int, int], float] = {} - - add_node( - root, - result, - target=Port(20, 0, 0), - net_id="netA", - open_set=open_set, - closed_set=closed_set, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options(context.options), - move_type="straight", - cache_key=("no-dynamic",), - ) - - assert open_set - assert context.metrics.total_congestion_check_calls == 0 - assert context.metrics.total_congestion_cache_misses == 0 - - -def test_guidance_seed_matching_move_reduces_cost_and_advances_seed_index( - basic_evaluator: CostEvaluator, -) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - root = AStarNode(Port(0, 0, 0), 0.0, 0.0, seed_index=0) - result = Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0) - open_set: list[AStarNode] = [] - unguided_open_set: list[AStarNode] = [] - closed_set: dict[tuple[int, int, int], float] = {} - - add_node( - root, - result, - target=Port(20, 0, 0), - net_id="netA", - open_set=open_set, - closed_set=closed_set, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options( - context.options, - guidance_seed=(StraightSeed(length=10.0),), - guidance_bonus=5.0, - ), - move_type="straight", - cache_key=("guided",), - ) - add_node( - AStarNode(Port(0, 0, 0), 0.0, 0.0), - result, - target=Port(20, 0, 0), - net_id="netA", - open_set=unguided_open_set, - closed_set={}, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options(context.options), - move_type="straight", - cache_key=("unguided",), - ) - - assert open_set - assert unguided_open_set - guided_node = open_set[0] - unguided_node = unguided_open_set[0] - assert guided_node.seed_index == 1 - assert guided_node.g_cost < unguided_node.g_cost - assert context.metrics.total_guidance_match_moves == 1 - assert context.metrics.total_guidance_match_moves_straight == 1 - assert context.metrics.total_guidance_match_moves_bend90 == 0 - assert context.metrics.total_guidance_match_moves_sbend == 0 - assert context.metrics.total_guidance_bonus_applied == pytest.approx(5.0) - assert context.metrics.total_guidance_bonus_applied_straight == pytest.approx(5.0) - assert context.metrics.total_guidance_bonus_applied_bend90 == pytest.approx(0.0) - assert context.metrics.total_guidance_bonus_applied_sbend == pytest.approx(0.0) - - -def test_guidance_seed_bend90_keeps_full_bonus( - basic_evaluator: CostEvaluator, -) -> None: - context = _build_context(basic_evaluator, bounds=BOUNDS) - root = AStarNode(Port(0, 0, 0), 0.0, 0.0, seed_index=0) - result = Bend90.generate(Port(0, 0, 0), 10.0, width=2.0, direction="CCW", dilation=1.0) - open_set: list[AStarNode] = [] - unguided_open_set: list[AStarNode] = [] - - add_node( - root, - result, - target=Port(10, 10, 90), - net_id="netA", - open_set=open_set, - closed_set={}, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options( - context.options, - guidance_seed=(result.move_spec,), - guidance_bonus=5.0, - ), - move_type="bend90", - cache_key=("guided-bend90",), - ) - add_node( - AStarNode(Port(0, 0, 0), 0.0, 0.0), - result, - target=Port(10, 10, 90), - net_id="netA", - open_set=unguided_open_set, - closed_set={}, - context=context, - metrics=context.metrics, - congestion=CongestionCaches(), - config=SearchRunConfig.from_options(context.options), - move_type="bend90", - cache_key=("unguided-bend90",), - ) - - assert open_set - assert unguided_open_set - guided_node = open_set[0] - unguided_node = unguided_open_set[0] - assert guided_node.seed_index == 1 - assert unguided_node.g_cost - guided_node.g_cost == pytest.approx(5.0) - assert context.metrics.total_guidance_match_moves == 1 - assert context.metrics.total_guidance_match_moves_straight == 0 - assert context.metrics.total_guidance_match_moves_bend90 == 1 - assert context.metrics.total_guidance_match_moves_sbend == 0 - assert context.metrics.total_guidance_bonus_applied == pytest.approx(5.0) - assert context.metrics.total_guidance_bonus_applied_straight == pytest.approx(0.0) - assert context.metrics.total_guidance_bonus_applied_bend90 == pytest.approx(5.0) - assert context.metrics.total_guidance_bonus_applied_sbend == pytest.approx(0.0) + [accepted] = open_set + assert accepted.g_cost == 2 + assert accepted.seed_index == 1 diff --git a/inire/tests/test_capacity.py b/inire/tests/test_capacity.py index 366aea0..a37b990 100644 --- a/inire/tests/test_capacity.py +++ b/inire/tests/test_capacity.py @@ -5,7 +5,7 @@ from shapely.geometry import Polygon, box from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route from inire.results import CapacityLimit -from inire.router._capacity import cut_capacity, port_conflicts +from inire.router._capacity import cut_capacity from inire.tests.routing_corpus import CASE_GROUPS @@ -31,19 +31,12 @@ def test_cut_capacity_counts_overlapping_rectangles_and_strict_crossings() -> No assert cut_capacity(problem, RoutingOptions()) == CapacityLimit(45, 3, 1, 4) -def test_fixed_port_conflicts_are_disjoint_and_depend_on_clearance() -> None: - (case,) = CASE_GROUPS["lidar-clements-8x8"] - pairs = port_conflicts(case.problem, case.options) - assert len(case.problem.nets) - len(pairs) == case.routing_bound - assert len({net_id for pair in pairs for net_id in pair}) == 2 * len(pairs) - assert port_conflicts(replace(case.problem, clearance=0), case.options) == () - - -@pytest.mark.parametrize("heading", [0, 90]) @pytest.mark.parametrize( - ("clearance", "second_width", "conflict"), - [(0, 1.5, False), (0, 2, True), (0, 2.5, True), (1e-7, 2 - 1e-7, True), (0.25, 1.5, False)], - ids=["positive-gap", "touching", "overlapping", "tiny-clearance", "exact-clearance"], + ('heading', 'clearance', 'second_width', 'conflict'), + [ + (90, 1e-07, 2 - 1e-07, True), + (90, 0.25, 1.5, False), + ], ) def test_automatic_bound_matches_terminal_face_clearance(heading, clearance, second_width, conflict) -> None: nets = tuple( diff --git a/inire/tests/test_clearance_precision.py b/inire/tests/test_clearance_precision.py index 619daff..c4f7342 100644 --- a/inire/tests/test_clearance_precision.py +++ b/inire/tests/test_clearance_precision.py @@ -1,7 +1,6 @@ from inire import CongestionOptions, RoutingOptions, RoutingProblem, SearchOptions from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port -from inire.geometry.components import Straight from inire.model import NetSpec from inire.router._astar_types import AStarContext from inire.router._router import PathFinder @@ -33,40 +32,6 @@ def _build_pathfinder( ), ) -def test_clearance_thresholds(): - """ - Check that clearance is correctly calculated: - two paths slightly beyond, exactly at, and slightly violating. - """ - # Clearance = 2.0, Width = 2.0 - # Required Centerline-to-Centerline = (2+2)/2 + 2.0 = 4.0 - ce = RoutingWorld(clearance=2.0) - - # Net 1: Centerline at y=0 - p1 = Port(0, 0, 0) - res1 = Straight.generate(p1, 50.0, width=2.0, dilation=1.0) - ce.add_path_geometry("net1", res1.collision_geometry, dilated_geometry=res1.dilated_collision_geometry) - - # Net 2: Parallel to Net 1 - # 1. Beyond minimum spacing: y=5. Gap = 5 - 2 = 3 > 2. OK. - p2_ok = Port(0, 5, 0) - res2_ok = Straight.generate(p2_ok, 50.0, width=2.0, dilation=1.0) - report_ok = ce.verify_path_report("net2", [res2_ok]) - assert report_ok.is_valid, f"Gap 3 should be valid, but got {report_ok.collision_count} collisions" - - # 2. Exactly at: y=4.0. Gap = 4.0 - 2.0 = 2.0. OK. - p2_exact = Port(0, 4, 0) - res2_exact = Straight.generate(p2_exact, 50.0, width=2.0, dilation=1.0) - report_exact = ce.verify_path_report("net2", [res2_exact]) - assert report_exact.is_valid, f"Gap exactly 2.0 should be valid, but got {report_exact.collision_count} collisions" - - # 3. Slightly violating: y=3.999. Gap = 3.999 - 2.0 = 1.999 < 2.0. FAIL. - p2_fail = Port(0, 3, 0) - res2_fail = Straight.generate(p2_fail, 50.0, width=2.0, dilation=1.0) - report_fail = ce.verify_path_report("net2", [res2_fail]) - assert not report_fail.is_valid, "Gap 1.999 should be invalid" - assert report_fail.collision_count > 0 - def test_verify_all_nets_cases(): """ Validate that verify_all_nets catches some common cases and doesn't flag reasonable non-failing cases. diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index 6da3177..e9aa755 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -5,10 +5,9 @@ import pytest from shapely import get_precision, set_precision from shapely.geometry import Polygon, box -import inire.geometry.collision as collision_module import inire.geometry.component_overlap as overlap_module from inire.geometry.collision import RoutingWorld -from inire.geometry.components import Bend90, ComponentResult +from inire.geometry.components import ComponentResult from inire.geometry.components import Straight from inire.geometry.primitives import Port from inire.model import RoutingProblem @@ -16,19 +15,6 @@ from inire.router._astar_types import AStarMetrics from inire.seeds import StraightSeed -def _install_static_straight( - engine: RoutingWorld, - start: Port, - length: float, - *, - width: float, - dilation: float = 0.0, -) -> None: - obstacle = Straight.generate(start, length, width=width, dilation=dilation) - for polygon in obstacle.physical_geometry: - engine.add_static_obstacle(polygon) - - def test_verify_path_rejects_invalid_polygon_before_clearance_checks() -> None: world = RoutingWorld(clearance=2) world.add_static_obstacle(box(2, -2, 8, 2)) @@ -44,70 +30,6 @@ def test_verify_path_rejects_invalid_polygon_before_clearance_checks() -> None: assert not report.is_valid -def test_collision_detection() -> None: - engine = RoutingWorld(clearance=2.0) - _install_static_straight(engine, Port(10, 15, 0), 10.0, width=10.0, dilation=1.0) - - direct_hit = Straight.generate(Port(12, 12.5, 0), 1.0, width=1.0, dilation=1.0) - assert engine.check_move_static(direct_hit) - - far_away = Straight.generate(Port(0, 2.5, 0), 5.0, width=5.0, dilation=1.0) - assert not engine.check_move_static(far_away) - - near_hit = Straight.generate(Port(8, 12.5, 0), 1.0, width=5.0, dilation=1.0) - assert engine.check_move_static(near_hit) - - -def test_move_admission_rejects_keepout_overlap_near_an_endpoint() -> None: - engine = RoutingWorld(clearance=0) - engine.add_static_obstacle(box(10.0005, 19.9999, 10.001, 20.0001)) - move = Straight.generate(Port(10, 20, 0), 50, width=2) - - assert engine.terminal_issue(move.start_port, 2) is None - assert engine.check_move_static(move) - assert engine.verify_path_report("line", (move,)).static_collision_count == 1 - - -def test_ray_cast_width_clearance() -> None: - # Clearance = 2.0um, Width = 2.0um. - # Centerline to obstacle edge must be >= W/2 + C = 1.0 + 2.0 = 3.0um. - engine = RoutingWorld(clearance=2.0) - - # Obstacle at x=10 to 20 - _install_static_straight(engine, Port(10, 50, 0), 10.0, width=100.0) - - # 1. Parallel move at x=6. Gap = 10 - 6 = 4.0. Clearly OK. - start_ok = Port(6, 50, 90) - reach_ok = engine.ray_cast(start_ok, 90, max_dist=10.0, net_width=2.0) - assert reach_ok >= 10.0 - - # 2. Parallel move at x=8. Gap = 10 - 8 = 2.0. COLLISION. - start_fail = Port(8, 50, 90) - reach_fail = engine.ray_cast(start_fail, 90, max_dist=10.0, net_width=2.0) - assert reach_fail < 10.0 - - -def test_ray_cast_reuses_exact_queries_and_separates_parameters() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - engine.add_static_obstacle(box(10, -1, 20, 1)) - origin = Port(0, 0, 0) - - assert engine.ray_cast(origin, 0, 30, net_width=2.0) == pytest.approx(7.0) - assert engine.metrics.total_ray_cast_candidate_bounds == 1 - assert engine.ray_cast(origin, 0, 30, net_width=2.0, caller="expand_forward") == pytest.approx(7.0) - assert engine.metrics.total_ray_cast_calls == 2 - assert engine.metrics.total_ray_cast_calls_expand_forward == 1 - assert engine.metrics.total_ray_cast_candidate_bounds == 1 - - assert engine.ray_cast(origin, 0, 30, net_width=6.0) == pytest.approx(5.0) - assert engine.ray_cast(origin, 0, 30) == pytest.approx(9.0) - assert engine.ray_cast(origin, 0, 4, net_width=2.0) == 4.0 - assert engine.ray_cast(origin, 90, 30, net_width=2.0) == 30.0 - engine.clearance = 4.0 - assert engine.ray_cast(origin, 0, 30, net_width=2.0) == pytest.approx(5.0) - - def test_ray_cast_discards_results_after_obstacle_changes() -> None: engine = RoutingWorld(clearance=0.0) origin = Port(0, 0, 0) @@ -132,16 +54,6 @@ def test_ray_cast_preserves_scalar_precision_at_an_obstacle_boundary() -> None: assert engine.ray_cast(origin, numpy.float32(90), 30.0) == 30.0 -def test_ray_cast_cache_has_a_fixed_capacity(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(collision_module, "_RAY_CAST_CACHE_LIMIT", 2) - engine = RoutingWorld(clearance=0.0) - engine.add_static_obstacle(box(10, -1, 20, 1)) - origin = Port(0, 0, 0) - for limit in (30, 40, 50): - assert engine.ray_cast(origin, 0, limit) == pytest.approx(10.0) - assert len(engine._static_obstacles.ray_cast_cache) <= 2 - - def test_static_index_ignores_precision_metadata_on_direct_import() -> None: obstacle = set_precision(box(10, 10, 20, 20), 1, mode="pointwise") world = RoutingWorld(clearance=.25) @@ -154,38 +66,6 @@ def test_static_index_ignores_precision_metadata_on_direct_import() -> None: assert world.verify_path_report("track", (move,)).static_collision_count == 1 -def test_check_move_static_clearance() -> None: - engine = RoutingWorld(clearance=2.0) - _install_static_straight(engine, Port(10, 50, 0), 10.0, width=100.0, dilation=1.0) - - # Straight move of length 10 at x=8 (Width 2.0) - # Gap = 10 - 8 = 2.0 < 3.0. COLLISION. - start = Port(8, 0, 90) - res = Straight.generate(start, 10.0, width=2.0, dilation=1.0) # dilation = C/2 - - assert engine.check_move_static(res) - - # Move at x=7. Gap = 3.0 == minimum. OK. - start_ok = Port(7, 0, 90) - res_ok = Straight.generate(start_ok, 10.0, width=2.0, dilation=1.0) - assert not engine.check_move_static(res_ok) - - # 3. Same exact-boundary case. - start_exact = Port(7, 0, 90) - res_exact = Straight.generate(start_exact, 10.0, width=2.0, dilation=1.0) - assert not engine.check_move_static(res_exact) - - -def test_static_bend_query_checks_clearance_beyond_its_tangent_face() -> None: - engine = RoutingWorld(clearance=2) - bend = Bend90.generate(Port(20, 20, 0), 10, 2, "CCW", dilation=1) - obstacle = box(16, 18.6, 18.25, 18.9) - assert bend.physical_geometry[0].distance(obstacle) < 2 - engine.add_static_obstacle(obstacle) - - assert engine.check_move_static(bend) - - def test_verify_path_report_uses_physical_distance_at_a_mitred_corner() -> None: engine = RoutingWorld(clearance=2.0) path = (Straight.generate(Port(0, 0, 0), 20.0, width=2.0),) @@ -199,21 +79,6 @@ def test_verify_path_report_uses_physical_distance_at_a_mitred_corner() -> None: assert engine.verify_path_report("net", path).static_collision_count == 1 -def test_verify_path_report_preserves_long_net_id() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - net_id = "net_abcdefghijklmnopqrstuvwxyz_0123456789" - path = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - geoms = [poly for component in path for poly in component.collision_geometry] - dilated = [poly for component in path for poly in component.dilated_collision_geometry] - - engine.add_path_geometry(net_id, geoms, dilated_geometry=dilated) - report = engine.verify_path_report(net_id, path) - - assert report.dynamic_collision_count == 0 - assert engine.metrics.total_verify_dynamic_candidate_nets == 0 - - def test_verify_path_report_distinguishes_long_net_ids_with_shared_prefix() -> None: engine = RoutingWorld(clearance=2.0) engine.metrics = AStarMetrics() @@ -240,64 +105,17 @@ def test_verify_path_report_distinguishes_long_net_ids_with_shared_prefix() -> N assert engine.metrics.total_verify_dynamic_candidate_nets == 1 -def test_verify_path_report_uses_physical_bounds_before_exact_checks() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_b = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_far = [Straight.generate(Port(100, 100, 0), 20.0, width=2.0, dilation=1.0)] - - engine.add_path_geometry( - "netB", - [poly for component in path_b for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_b for poly in component.dilated_collision_geometry], - ) - engine.add_path_geometry( - "netFar", - [poly for component in path_far for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_far for poly in component.dilated_collision_geometry], - ) - - report = engine.verify_path_report("netA", path_a) - - assert report.dynamic_collision_count == 1 - assert engine.metrics.total_verify_dynamic_candidate_nets == 1 - assert engine.metrics.total_verify_dynamic_exact_pair_checks == 1 - - -@pytest.mark.parametrize(("clearance", "valid"), [(1.4, True), (1.5, False)]) -def test_verify_path_report_uses_physical_distance_between_routes(clearance, valid) -> None: - engine = RoutingWorld(clearance=clearance) - existing = Straight.generate(Port(0, 0, 0), 10, width=2, dilation=clearance / 2) - query = Straight.generate(Port(12, 2, 90), 10, width=2, dilation=clearance / 2) - engine.add_route("existing", (existing,)) - - # The physical corners are one unit apart on each axis. - assert engine.verify_path_report("query", (query,)).is_valid is valid - engine.remove_path("existing") - assert engine.verify_path_report("query", (query,)).is_valid - - -@pytest.mark.parametrize("y", [1, 2, 50]) -@pytest.mark.parametrize(("gap", "valid"), [(0.1, True), (0.099, False), (0, False)]) -def test_verify_path_clearance_threshold_survives_translation(y, gap, valid) -> None: - engine = RoutingWorld(clearance=0.1) - width = 1 - gap - tested = Straight.generate(Port(0, y, 0), 20, width) - peer = Straight.generate(Port(0, y + 1, 0), 20, width) - - engine.add_route("peer", (peer,)) - assert engine.verify_path_report("query", (tested,)).is_valid is valid - engine.remove_path("peer") - engine.add_static_obstacle(peer.physical_geometry[0]) - assert engine.verify_path_report("query", (tested,)).is_valid is valid - - -def test_verify_geometry_checks_the_board_using_the_polygon() -> None: - component = Straight.generate(Port(10, 25, 0), 40.49, 2) - report = RoutingWorld(0, board=box(0, 0, 50, 50)).verify_path_report("straight", (component,)) - assert component.end_port == Port(50, 25, 0) - assert report.out_of_bounds +def test_verify_path_rejects_insufficient_clearance_after_translation() -> None: + width = 1 - 0.099 + for y in (1, 50): + engine = RoutingWorld(clearance=0.1) + tested = Straight.generate(Port(0, y, 0), 20, width) + peer = Straight.generate(Port(0, y + 1, 0), 20, width) + engine.add_route("peer", (peer,)) + assert not engine.verify_path_report("query", (tested,)).is_valid + engine.remove_path("peer") + engine.add_static_obstacle(peer.physical_geometry[0]) + assert not engine.verify_path_report("query", (tested,)).is_valid def test_rectangular_board_includes_its_edges_and_custom_board_keeps_its_hole() -> None: @@ -330,47 +148,17 @@ def test_self_collision_check_only_visits_spatial_candidates(monkeypatch) -> Non assert checks == len(path) - 1 -def test_verify_path_details_returns_conflicting_net_ids() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_b = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] +def test_batch_static_clearance_matches_individual_components() -> None: + path = tuple(Straight.generate(Port(0, y, 0), 10, width=2) for y in (0, 10, 20, 30)) + world = RoutingWorld(clearance=2) + world.add_static_obstacle(box(2, 0, 4, 2)) + world.add_static_obstacle(box(2, 12, 4, 14), owner="fixed") + world.add_static_obstacle(box(2, 23, 4, 25)) - engine.add_path_geometry( - "netB", - [poly for component in path_b for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_b for poly in component.dilated_collision_geometry], - ) + counts = [world.verify_path_geometry((component,)).static_collision_count for component in path] - detail = engine.verify_path_details("netA", path_a) - - assert detail.report.dynamic_collision_count == 1 - assert detail.conflicting_net_ids == ("netB",) - - engine.remove_path("netB") - rechecked = engine.verify_path_details("netA", path_a, geometry_report=detail.report) - assert rechecked.report == engine.verify_path_geometry(path_a) - assert rechecked.conflicting_net_ids == () - - -def test_verify_path_details_reports_component_conflicts() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_b = [ - Straight.generate(Port(100, 0, 0), 10.0, width=2.0, dilation=1.0), - Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0), - Straight.generate(Port(10, 0, 0), 10.0, width=2.0, dilation=1.0), - ] - - engine.add_route("netB", path_b) - - detail = engine.verify_path_details("netA", path_a, capture_component_conflicts=True) - - assert detail.conflicting_net_ids == ("netB",) - assert detail.component_conflicts == ((0, "netB", 1), (0, "netB", 2)) - assert detail.report.dynamic_collision_count == 1 - assert engine.verify_path_report("netA", path_a) == detail.report + assert counts == [1, 1, 0, 0] + assert world.verify_path_geometry(path).static_collision_count == sum(counts) def test_verify_path_details_deduplicates_component_conflicts() -> None: @@ -412,54 +200,8 @@ def test_verify_path_details_deduplicates_component_conflicts() -> None: assert detail.component_conflicts == ((0, "netB", 0),) -def test_remove_path_clears_dynamic_path() -> None: - engine = RoutingWorld(clearance=2.0) - path = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - geoms = [poly for component in path for poly in component.collision_geometry] - dilated = [poly for component in path for poly in component.dilated_collision_geometry] - - engine.add_path_geometry("netA", geoms, dilated_geometry=dilated) - assert {net_id for net_id, _ in engine._dynamic_paths.geometries.values()} == {"netA"} - - engine.remove_path("netA") - assert list(engine._dynamic_paths.geometries.values()) == [] - assert len(engine._static_obstacles.geometries) == 0 - - -def test_dynamic_grid_updates_incrementally_on_add_and_remove() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] - path_b = [Straight.generate(Port(0, 4, 0), 20.0, width=2.0, dilation=1.0)] - - engine.add_path_geometry( - "netA", - [poly for component in path_a for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_a for poly in component.dilated_collision_geometry], - ) - engine.add_path_geometry( - "netB", - [poly for component in path_b for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_b for poly in component.dilated_collision_geometry], - ) - - dynamic_paths = engine._dynamic_paths - assert dynamic_paths.net_to_obj_ids["netA"] - assert dynamic_paths.net_to_obj_ids["netB"] - assert dynamic_paths.grid_net_obj_ids - assert engine.metrics.total_dynamic_grid_rebuilds == 0 - - engine.remove_path("netA") - - assert "netA" not in dynamic_paths.net_to_obj_ids - assert "netB" in dynamic_paths.net_to_obj_ids - assert engine.metrics.total_dynamic_grid_rebuilds == 0 - assert "netA" not in dynamic_paths.grid_net_obj_ids.get((0, -1), {}) - assert "netB" in dynamic_paths.grid_net_obj_ids.get((0, 0), {}) - - -@pytest.mark.parametrize("large_install", [True, False]) -def test_large_dynamic_spans_use_tree_for_congestion(large_install) -> None: +def test_large_dynamic_spans_use_tree_for_congestion() -> None: + large_install = True engine = RoutingWorld(clearance=2) installed = Straight.generate(Port(0, 0, 0), 100_000 if large_install else 20, width=2, dilation=1) query = Straight.generate(Port(10, -10, 90), 20 if large_install else 100_000, width=2, dilation=1) @@ -515,35 +257,6 @@ def test_dynamic_net_envelopes_update_incrementally_on_add_and_remove() -> None: -def test_congestion_query_uses_per_polygon_bounds() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - - blocker = Straight.generate(Port(40, 4, 90), 2.0, width=2.0, dilation=1.0) - engine.add_path_geometry( - "netB", - list(blocker.collision_geometry), - dilated_geometry=list(blocker.dilated_collision_geometry), - ) - - move = ComponentResult( - start_port=Port(0, 0, 0), - collision_geometry=[box(0, 0, 10, 10), box(90, 0, 100, 10)], - end_port=Port(100, 0, 0), - length=100.0, - move_type="straight", - move_spec=StraightSeed(100.0), - physical_geometry=[box(0, 0, 10, 10), box(90, 0, 100, 10)], - dilated_collision_geometry=[box(0, 0, 10, 10), box(90, 0, 100, 10)], - dilated_physical_geometry=[box(0, 0, 10, 10), box(90, 0, 100, 10)], - ) - - assert engine.check_move_congestion(move, "netA") == 0 - assert engine.metrics.total_congestion_candidate_nets == 0 - assert engine.metrics.total_congestion_candidate_ids == 0 - assert engine.metrics.total_congestion_exact_pair_checks == 0 - - def test_congestion_touching_geometries_do_not_count_as_overlap() -> None: engine = RoutingWorld(clearance=2.0) engine.metrics = AStarMetrics() @@ -560,34 +273,6 @@ def test_congestion_touching_geometries_do_not_count_as_overlap() -> None: assert engine.check_move_congestion(touching, "netA") == 0 -def test_congestion_exact_checks_only_touch_relevant_move_polygons() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - - blocker = Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0) - engine.add_path_geometry( - "netB", - list(blocker.collision_geometry), - dilated_geometry=list(blocker.dilated_collision_geometry), - ) - - move = ComponentResult( - start_port=Port(0, 0, 0), - collision_geometry=[box(0, -2, 10, 2), box(90, -2, 100, 2)], - end_port=Port(100, 0, 0), - length=100.0, - move_type="straight", - move_spec=StraightSeed(100.0), - physical_geometry=[box(0, -2, 10, 2), box(90, -2, 100, 2)], - dilated_collision_geometry=[box(0, -2, 10, 2), box(90, -2, 100, 2)], - dilated_physical_geometry=[box(0, -2, 10, 2), box(90, -2, 100, 2)], - ) - - assert engine.check_move_congestion(move, "netA") == 1 - assert engine.metrics.total_congestion_candidate_nets == 1 - assert engine.metrics.total_congestion_candidate_ids == 1 - assert engine.metrics.total_congestion_exact_pair_checks == 1 - def test_congestion_grid_span_cache_reuses_broad_phase_candidates() -> None: engine = RoutingWorld(clearance=2.0) engine.metrics = AStarMetrics() @@ -628,65 +313,11 @@ def test_congestion_grid_span_cache_reuses_broad_phase_candidates() -> None: assert engine.metrics.total_congestion_grid_span_cache_hits == 1 -def test_has_possible_move_congestion_uses_presence_cache_and_skips_empty_spans() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - presence_cache: dict[tuple[str, int, int, int, int], bool] = {} +def test_move_admission_rejects_keepout_overlap_near_an_endpoint() -> None: + engine = RoutingWorld(clearance=0) + engine.add_static_obstacle(box(10.0005, 19.9999, 10.001, 20.0001)) + move = Straight.generate(Port(10, 20, 0), 50, width=2) - blocker = Straight.generate(Port(10, 0, 0), 20.0, width=2.0, dilation=1.0) - engine.add_path_geometry( - "netB", - list(blocker.collision_geometry), - dilated_geometry=list(blocker.dilated_collision_geometry), - ) - empty_move = Straight.generate(Port(200, 0, 0), 20.0, width=2.0, dilation=1.0) - - assert not engine.has_possible_move_congestion(empty_move, "netA", presence_cache) - assert not engine.has_possible_move_congestion(empty_move, "netA", presence_cache) - assert engine.metrics.total_congestion_presence_cache_misses == 1 - assert engine.metrics.total_congestion_presence_cache_hits == 1 - - occupied_move = Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0) - - assert engine.has_possible_move_congestion(occupied_move, "netA") - - -def test_has_candidate_move_congestion_uses_candidate_precheck_cache() -> None: - engine = RoutingWorld(clearance=2.0) - engine.metrics = AStarMetrics() - candidate_precheck_cache: dict[tuple[str, int, int, int, int], bool] = {} - net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] = {} - grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] = {} - - blocker = Straight.generate(Port(10, 0, 0), 20.0, width=2.0, dilation=1.0) - engine.add_path_geometry( - "netB", - list(blocker.collision_geometry), - dilated_geometry=list(blocker.dilated_collision_geometry), - ) - empty_move = Straight.generate(Port(200, 0, 0), 20.0, width=2.0, dilation=1.0) - occupied_move = Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0) - - assert not engine.has_candidate_move_congestion( - empty_move, - "netA", - candidate_precheck_cache, - net_envelope_cache, - grid_net_cache, - ) - assert not engine.has_candidate_move_congestion( - empty_move, - "netA", - candidate_precheck_cache, - net_envelope_cache, - grid_net_cache, - ) - assert engine.has_candidate_move_congestion( - occupied_move, - "netA", - candidate_precheck_cache, - net_envelope_cache, - grid_net_cache, - ) - assert engine.metrics.total_congestion_candidate_precheck_misses >= 2 - assert engine.metrics.total_congestion_candidate_precheck_hits >= 1 + assert engine.terminal_issue(move.start_port, 2) is None + assert engine.check_move_static(move) + assert engine.verify_path_report("line", (move,)).static_collision_count == 1 diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index 1b5454b..e3cc294 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -1,5 +1,3 @@ -from unittest.mock import Mock - import pytest from shapely.geometry import box @@ -10,7 +8,7 @@ from inire import ( from inire.geometry import sbend from inire.geometry.sbend import exact_sbend_spans from inire.router import _columns -from inire.router._columns import _jog_pivots, _schedules, column_seed_candidates +from inire.router._columns import _schedules from inire.tests.terminal_bench_scenario import LENGTH_COST @@ -27,8 +25,8 @@ def test_sbend_schedule_requires_a_window_long_enough_for_exact_spans() -> None: assert [(sequence.span, sequence.offsets) for sequence in transitions[0]] == [(40, (20,))] * 3 -@pytest.mark.parametrize("sign", [1, -1]) -def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None: +def test_automatic_column_routes_use_only_enabled_signed_sbends() -> None: + sign = -1 east = tuple(NetSpec(str(y), Port(5, y, 0), Port(220, y + sign * 10, 0)) for y in (30, 60)) west = NetSpec("west", Port(220, 90 + sign * 10, 180), Port(5, 90, 180)) problem = RoutingProblem((0, 0, 230, 130), (*east, west), (box(190, 0, 210, 10),), clearance=0) @@ -48,12 +46,11 @@ def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None: assert bends == (SBendSeed(sign * 2, 25),) * 5 -@pytest.mark.parametrize("smaller_radius", [10, 15]) -def test_column_routes_use_a_later_radius_when_the_smallest_cannot_make_the_shift(smaller_radius) -> None: +def test_column_routes_try_a_larger_radius_for_wide_shifts() -> None: nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(240, y + 20, 0), width=30) for y in (35, 110, 185)) problem = RoutingProblem((0, 0, 250, 250), nets, (box(130, 0, 150, 10),), clearance=0) options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(smaller_radius, 25), sbend_offsets=(20,)), + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10, 25), sbend_offsets=(20,)), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), ) @@ -64,7 +61,7 @@ def test_column_routes_use_a_later_radius_when_the_smallest_cannot_make_the_shif assert run.metrics.nodes_expanded == 0 for result in run.results_by_net.values(): assert result.is_valid - assert {move.radius for move in result.as_seed().segments if isinstance(move, SBendSeed)} == {25} + assert [move.radius for move in result.as_seed().segments if isinstance(move, SBendSeed)] == [25] def test_column_routes_allow_wide_straight_tracks_alongside_smaller_bends() -> None: @@ -85,74 +82,6 @@ def test_column_routes_allow_wide_straight_tracks_alongside_smaller_bends() -> N assert {move.radius for move in run.results_by_net[net.net_id].as_seed().segments if isinstance(move, SBendSeed)} == {10} -def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None: - make_state = Mock(wraps=_columns._BendState) - monkeypatch.setattr(_columns, "_BendState", make_state) - choose = _columns._bend_sequences({10: 30}, 25, LENGTH_COST, max_usable=40, weighted=False, sbend_penalty=0) - make_state.reset_mock() - - assert choose(100, 40) is None - assert choose(-100, 40) is None - make_state.assert_not_called() - assert choose(-10, 30).offsets == (-10,) - - -def test_sbend_sequences_use_the_common_offset_stride() -> None: - class SparseSpans(dict): - def items(self): - self.scans += 1 - assert self.scans <= 3 - return super().items() - - spans = SparseSpans({40_000_000: 120_000_000, 80_000_000: 160_000_000}) - spans.scans = 0 - choose = _columns._bend_sequences(spans, 100_000_000, LENGTH_COST, max_usable=280_000_000, weighted=False, sbend_penalty=0) - - assert choose(40_000_001, 120_000_000) is None - assert choose(40_000_000, 119_999_999) is None - assert choose(-40_000_000, 120_000_000).offsets == (-40_000_000,) - assert choose(80_000_000, 160_000_000).offsets == (80_000_000,) - assert choose(120_000_000, 280_000_000).offsets == (80_000_000, 40_000_000) - - -def test_sbend_sequence_only_builds_reachable_shifts_within_the_maximum_window(monkeypatch) -> None: - max_usable = 399_891 - make_state = _columns._BendState - built = 0 - - def count_state(offset, previous, span, cost, length): - nonlocal built - built += 1 - assert span <= max_usable - assert built <= 81 - return make_state(offset, previous, span, cost, length) - - monkeypatch.setattr(_columns, "_BendState", count_state) - choose = _columns._bend_sequences( - {20: 5000, 125_002: 375_006}, 312_505, LENGTH_COST, max_usable=max_usable, weighted=False, sbend_penalty=0, - ) - - assert choose(125_000, max_usable) is None - sequence = choose(125_002, max_usable) - assert sequence.offsets == (125_002,) - assert sequence.span == 375_006 - - -def test_sbend_table_reconstructs_only_the_chosen_sequence(monkeypatch) -> None: - make_sequence = _columns._BendSequence - - def build_sequence(offsets, span, cost): - assert offsets == (-180_002,) - return make_sequence(offsets, span, cost) - - monkeypatch.setattr(_columns, "_BendSequence", build_sequence) - choose = _columns._bend_sequences( - {20: 6000, 180_002: 540_006}, 450_005, LENGTH_COST, max_usable=65_000_000, weighted=False, sbend_penalty=0, - ) - - assert choose(-180_002, 65_000_000).span == 540_006 - - def test_weighted_sbend_sequence_keeps_both_short_and_low_cost_choices() -> None: weights = {"straight": 1.0, "sbend": 1.0} choose = _columns._bend_sequences({2: 14, 10: 30}, 25, weights, max_usable=70, weighted=True, sbend_penalty=0) @@ -181,25 +110,6 @@ def test_exact_sbend_scan_budget_applies_only_to_implicit_offsets(monkeypatch) - assert exact_sbend_spans(25, max_span=40, offsets=(-20,)) == {20: 40} -def test_automatic_routes_wide_tall_boards_without_a_large_implicit_scan(monkeypatch) -> None: - def unexpected_scan(_value): - raise AssertionError("The implicit offset scan exceeds the work budget") - - monkeypatch.setattr(sbend, "isqrt", unexpected_scan) - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(399_999_990, y, 0)) for y in (30, 60, 90)) - problem = RoutingProblem((0, 0, 400_000_000, 50_000_000), nets, (box(190_000_000, 0, 190_000_020, 10),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(100_000_000,)), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - - assert all(run.results_by_net[net.net_id].is_valid for net in nets) - assert run.metrics.nodes_expanded == 0 - - def test_wide_column_windows_only_scan_offsets_within_the_board_height(monkeypatch) -> None: square_root = sbend.isqrt scans = 0 @@ -226,26 +136,6 @@ def test_wide_column_windows_only_scan_offsets_within_the_board_height(monkeypat assert run.metrics.nodes_expanded == 0 -def test_large_unused_sbend_radius_skips_column_enumeration(monkeypatch) -> None: - def unexpected_enumeration(*_args, **_kwargs): - raise AssertionError("A single net is ineligible for column planning") - - monkeypatch.setattr(_columns, "exact_sbend_spans", unexpected_enumeration) - net = NetSpec("line", Port(10, 50, 0), Port(200, 50, 0)) - problem = RoutingProblem((0, 0, 300, 100), (net,)) - search = SearchOptions(node_limit=2, bend_radii=(), sbend_radii=(1_000_000_000,)) - - assert route(problem, options=RoutingOptions(search=search)).results_by_net[net.net_id].is_valid - - -def test_column_windows_bound_enumeration_for_a_large_sbend_radius() -> None: - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(95, y + 5, 0)) for y in (20, 40, 60)) - problem = RoutingProblem((0, 0, 100, 100), nets, (box(40, 0, 60, 10),)) - search = SearchOptions(sbend_radii=(1_000_000_000,)) - - assert list(column_seed_candidates(problem, search, LENGTH_COST, weighted=False)) == [] - - def test_automatic_routing_skips_column_profiles_with_too_many_partitions(monkeypatch) -> None: def unexpected_profiles(*_args, **_kwargs): raise AssertionError("The column has more than five million track assignments") @@ -283,68 +173,6 @@ def test_sbend_column_profiles_match_exhaustive_ranking_without_using_a_product( assert _columns._column_profiles(*args) == exhaustive -@pytest.mark.parametrize("weighted", [False, True]) -def test_sbend_column_passes_reuse_profiles_and_skip_duplicate_span_sets(monkeypatch, weighted) -> None: - profile_calls = Mock(wraps=_columns._column_profiles) - schedule_calls = Mock(wraps=_columns._schedules) - monkeypatch.setattr(_columns, "_column_profiles", profile_calls) - monkeypatch.setattr(_columns, "_schedules", schedule_calls) - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(400, y + 800, 0)) for y in (40, 110, 180)) - column_positions = (80, 180, 280) - keepouts = tuple(box(x, y, x + 20, y + 2) for x in column_positions for y in range(100, 700, 100)) - problem = RoutingProblem((0, 0, 410, 1700), nets, keepouts, clearance=0) - search = SearchOptions(bend_radii=(), sbend_radii=(10,)) - - assert list(column_seed_candidates(problem, search, LENGTH_COST, weighted=weighted)) == [] - - # Two distinct span sets share the base and extra-spacing profiles for each slack pair. - slack_pairs = 12 - assert schedule_calls.call_count == 2 * slack_pairs - base_profile_calls = sum(len(call.args) == 8 for call in profile_calls.call_args_list) - assert base_profile_calls <= 2 * len(column_positions) * slack_pairs - - -def test_jog_transition_rejects_an_offset_that_cannot_fit_two_bends() -> None: - assert _jog_pivots((10, 40), (17, 40), (0, 100), (2, 2), 2, 5, 1) is None - assert _jog_pivots((10, 40), (25, 40), (0, 100), (2, 2), 2, 5, 1) == (8, None) - - -def test_column_jog_seeds_can_use_straights_longer_than_the_lattice_scan() -> None: - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(405, y + 50, 0)) for y in (60, 150, 240)) - problem = RoutingProblem((0, 0, 420, 310), nets, (box(170, 0, 190, 20),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(10,), sbend_radii=(), max_straight_length=40), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - - assert run.automatic.selected_planner == "column-jogs" - assert run.metrics.nodes_expanded == 0 - for result in run.results_by_net.values(): - assert result.is_valid - assert any(isinstance(move, StraightSeed) and move.length > 40 for move in result.as_seed().segments) - - -def test_column_jogs_skip_radii_too_small_for_a_shifting_track() -> None: - wide = NetSpec("wide", Port(5, 60, 0), Port(405, 160, 0), width=30) - narrow = tuple(NetSpec(str(y), Port(5, y, 0), Port(405, y + 100, 0)) for y in (200, 340)) - problem = RoutingProblem((0, 0, 420, 470), (wide, *narrow), (box(170, 0, 190, 20),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(8, 9, 10, 11, 12, 13, 14, 20), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - - assert run.automatic.selected_planner == "column-jogs" - assert all(result.is_valid for result in run.results_by_net.values()) - segments = run.results_by_net[wide.net_id].as_seed().segments - assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {20} - - def test_column_jogs_allow_wide_straight_tracks_alongside_smaller_bends() -> None: wide = NetSpec("wide", Port(5, 30, 0), Port(405, 30, 0), width=30) narrow = tuple(NetSpec(str(y), Port(5, y, 0), Port(405, y + 50, 0)) for y in (90, 170)) @@ -363,23 +191,3 @@ def test_column_jogs_allow_wide_straight_tracks_alongside_smaller_bends() -> Non for net in narrow: segments = run.results_by_net[net.net_id].as_seed().segments assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {10} - - -@pytest.mark.parametrize(("shift", "needs_short_straights"), [(23, True), (27, False)]) -def test_column_jogs_prefer_the_lattice_minimum_but_can_relax_it(shift, needs_short_straights) -> None: - nets = tuple(NetSpec(str(y), Port(5, y, 0), Port(1000, y + shift, 0)) for y in (30, 85, 140)) - problem = RoutingProblem((0, 0, 1010, 180), nets, (box(980, 0, 990, 10),), clearance=0) - options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(10,), sbend_radii=(), min_straight_length=5), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - ) - - run = route(problem, options=options) - - assert run.automatic.selected_planner == "column-jogs" - assert run.metrics.nodes_expanded == 0 - for result in run.results_by_net.values(): - assert result.is_valid - lengths = [move.length for move in result.as_seed().segments if isinstance(move, StraightSeed)] - assert any(length < options.search.min_straight_length for length in lengths) is needs_short_straights diff --git a/inire/tests/test_compact.py b/inire/tests/test_compact.py index 7373658..c423cdd 100644 --- a/inire/tests/test_compact.py +++ b/inire/tests/test_compact.py @@ -1,4 +1,3 @@ -import pytest from inire import CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, route @@ -42,20 +41,24 @@ def test_local_sbend_packing_skips_intersecting_candidates_at_zero_clearance() - -@pytest.mark.parametrize(("forward", "scan_limit"), [(18, 2000), (14, 20)], ids=["short-tangents", "long-straight"]) -def test_local_sbend_seeds_can_use_straights_outside_lattice_scan_limits(forward, scan_limit) -> None: - east = NetSpec("east", Port(10, 10, 0), Port(10 + forward, 15, 0)) - north = NetSpec("north", Port(70, 10, 90), Port(65, 10 + forward, 90)) +def test_local_sbend_seeds_can_use_straights_outside_lattice_scan_limits() -> None: + shift = NetSpec("shift", Port(10, 10, 0), Port(28, 15, 0)) + north = NetSpec("north", Port(70, 10, 90), Port(65, 28, 90)) line = NetSpec("line", Port(10, 40, 0), Port(40, 40, 0)) - problem = RoutingProblem((0, 0, 100, 100), (east, north, line), clearance=0) + problem = RoutingProblem((0, 0, 100, 100), (shift, north, line), clearance=0) options = RoutingOptions( - search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10,), min_straight_length=5, max_straight_length=scan_limit), + search=SearchOptions(node_limit=1, bend_radii=(), sbend_radii=(10,), min_straight_length=5, max_straight_length=20), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), ) run = route(problem, options=options) - assert all(run.results_by_net[net.net_id].is_valid for net in problem.nets) assert run.automatic.selected_planner == "local-sbend" assert run.metrics.nodes_expanded == 0 + assert all(result.is_valid for result in run.results_by_net.values()) + assert any( + move.move_type == "straight" and move.length < options.search.min_straight_length + for move in run.results_by_net[shift.net_id].path + ) + assert run.results_by_net[line.net_id].path[0].length > options.search.max_straight_length diff --git a/inire/tests/test_components.py b/inire/tests/test_components.py index 89e3e66..85640be 100644 --- a/inire/tests/test_components.py +++ b/inire/tests/test_components.py @@ -1,8 +1,6 @@ import pytest -from dataclasses import FrozenInstanceError from math import asin, cos, pi, sin, sqrt from shapely.affinity import rotate as shapely_rotate -from shapely.affinity import scale as shapely_scale from shapely.affinity import translate as shapely_translate from shapely.geometry import Polygon, box @@ -14,51 +12,11 @@ from inire.router.cost import CostEvaluator from inire.geometry.collision import RoutingWorld -def test_straight_generation() -> None: - start = Port(0, 0, 0) - length = 10.0 - width = 2.0 - result = Straight.generate(start, length, width) - - assert result.end_port.x == 10.0 - assert result.end_port.y == 0.0 - assert result.end_port.r == 0.0 - assert len(result.collision_geometry) == 1 - - # Bounds of the polygon - minx, miny, maxx, maxy = result.collision_geometry[0].bounds - assert minx == 0.0 - assert maxx == 10.0 - assert miny == -1.0 - assert maxy == 1.0 - assert isinstance(result.collision_geometry, tuple) - - -def test_bend90_generation() -> None: - start = Port(0, 0, 0) - radius = 10.0 - width = 2.0 - - # CW bend - result_cw = Bend90.generate(start, radius, width, direction="CW") - assert result_cw.end_port.x == 10.0 - assert result_cw.end_port.y == -10.0 - assert result_cw.end_port.r == 270.0 - - # CCW bend - result_ccw = Bend90.generate(start, radius, width, direction="CCW") - assert result_ccw.end_port.x == 10.0 - assert result_ccw.end_port.y == 10.0 - assert result_ccw.end_port.r == 90.0 - - -@pytest.mark.parametrize("direction", ["CW", "CCW"]) -@pytest.mark.parametrize("proxy", ["arc", "clipped_bbox"]) -def test_fractional_bend_preserves_radius_and_extends_both_tangents(direction, proxy) -> None: +def test_fractional_bend_preserves_radius_and_extends_both_tangents() -> None: radius = 10.25 start = Port(20, 20, 90) - result = Bend90.generate(start, radius, 2, direction, collision_type=proxy, dilation=1) - end = Port(31, 31, 0) if direction == "CW" else Port(9, 31, 180) + result = Bend90.generate(start, radius, 2, "CCW", collision_type="clipped_bbox", dilation=1) + end = Port(9, 31, 180) assert result.end_port == end bend, = result.physical_geometry lead, = Straight.generate(start.translate(dy=-5), 5, 2).physical_geometry @@ -74,49 +32,8 @@ def test_fractional_bend_preserves_radius_and_extends_both_tangents(direction, p assert evaluator.score_component(result) == pytest.approx(result.length + 50 * sqrt(10 / radius)) -def test_sbend_generation() -> None: - start = Port(0, 0, 0) - offset = 5.0 - radius = 10.0 - width = 2.0 - - result = SBend.generate(start, offset, radius, width) - assert result.end_port.y == 5.0 - assert result.end_port.r == 0.0 - assert len(result.collision_geometry) == 2 # Optimization: returns individual arcs - first, second = result.physical_geometry - lead, = Straight.generate(Port(-5, 0, 0), 5, width).physical_geometry - tail, = Straight.generate(result.end_port, 5, width).physical_geometry - assert first.is_valid - assert second.is_valid - assert lead.intersection(first).length == pytest.approx(width) - assert first.intersection(second).length == pytest.approx(width) - assert second.intersection(tail).length == pytest.approx(width) - - # Verify failure for large offset - with pytest.raises(ValueError, match="offset must be a nonzero integer with magnitude less than twice the radius"): - SBend.generate(start, 25.0, 10.0, 2.0) - - -def test_sbend_generation_negative_offset_keeps_second_arc_below_centerline() -> None: - start = Port(0, 0, 0) - offset = -5.0 - radius = 10.0 - width = 2.0 - - result = SBend.generate(start, offset, radius, width) - - assert result.end_port.y == -5.0 - second_arc_minx, second_arc_miny, second_arc_maxx, second_arc_maxy = result.collision_geometry[1].bounds - assert second_arc_maxy <= width / 2.0 + 1e-6 - assert second_arc_miny < -width / 2.0 - - -@pytest.mark.parametrize("collision_type", ["arc", "clipped_bbox"]) -def test_translate_reuses_shared_polygons_and_preserves_each_geometry_view( - monkeypatch: pytest.MonkeyPatch, collision_type: str -) -> None: - component = SBend.generate(Port(0, 0, 90), -5.0, 10.0, 2.0, collision_type=collision_type, dilation=1.0) +def test_translate_reuses_shared_polygons_and_preserves_each_geometry_view(monkeypatch: pytest.MonkeyPatch) -> None: + component = SBend.generate(Port(0, 0, 90), -5.0, 10.0, 2.0, collision_type="clipped_bbox", dilation=1.0) calls = [] transform = components_module.transform @@ -177,45 +94,6 @@ def test_bend_collision_models() -> None: assert res_clipped_margin.collision_geometry[0].area > res_clipped.collision_geometry[0].area -def test_custom_bend_collision_polygon_uses_local_transform() -> None: - custom_poly = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - - cases = [ - (Port(0, 0, 0), "CCW", (0.0, 10.0), 0.0, False), - (Port(0, 0, 0), "CW", (0.0, -10.0), 0.0, True), - (Port(0, 0, 90), "CCW", (-10.0, 0.0), 90.0, False), - ] - - for start, direction, center_xy, rotation_deg, mirror_y in cases: - result = Bend90.generate(start, 10.0, 2.0, direction=direction, collision_type=custom_poly) - expected = custom_poly - if mirror_y: - expected = shapely_scale(expected, xfact=1.0, yfact=-1.0, origin=(0.0, 0.0)) - if rotation_deg: - expected = shapely_rotate(expected, rotation_deg, origin=(0.0, 0.0), use_radians=False) - expected = shapely_translate(expected, center_xy[0], center_xy[1]) - - assert result.collision_geometry[0].symmetric_difference(expected).area < 1e-6 - - -def test_custom_bend_collision_polygon_is_true_geometry() -> None: - custom_poly = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - result = Bend90.generate( - Port(0, 0, 0), - 10.0, - 2.0, - direction="CCW", - collision_type=custom_poly, - physical_geometry_type=custom_poly, - dilation=1.0, - ) - - assert result.collision_geometry[0].symmetric_difference(result.physical_geometry[0]).area < 1e-6 - assert result.dilated_collision_geometry is not None - assert result.dilated_physical_geometry is not None - assert result.dilated_collision_geometry[0].symmetric_difference(result.dilated_physical_geometry[0]).area < 1e-6 - - def test_custom_bend_collision_polygon_can_differ_from_physical_geometry() -> None: custom_proxy = Polygon([(0, -11), (11, -11), (11, 0), (0, 0)]) result = Bend90.generate(Port(0, 0, 0), 10.0, 2.0, direction="CCW", collision_type=custom_proxy, dilation=1.0) @@ -224,22 +102,10 @@ def test_custom_bend_collision_polygon_can_differ_from_physical_geometry() -> No assert result.dilated_collision_geometry[0].symmetric_difference(result.dilated_physical_geometry[0]).area > 1e-6 -@pytest.mark.parametrize("dilation", [1, 10]) -def test_arc_proxy_dilation_uses_the_circular_geometry(dilation) -> None: - outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - start = Port(20, 20, 0) - default = Bend90.generate(start, 10, 2, "CCW", dilation=dilation) - custom = Bend90.generate(start, 10, 2, "CCW", physical_geometry_type=outline, dilation=dilation) - - assert custom.collision_geometry == default.collision_geometry - assert custom.dilated_collision_geometry == default.dilated_collision_geometry - assert custom.dilated_physical_geometry == tuple(shape.buffer(dilation) for shape in custom.physical_geometry) - assert custom.dilated_physical_geometry != custom.dilated_collision_geometry - - -@pytest.mark.parametrize("heading", [0, 90, 180, 270]) -@pytest.mark.parametrize(("radius", "offset"), [(50, 40), (50, -40), (12.25, 11), (12.25, -11)]) -def test_custom_sbend_uses_one_asymmetric_polygon_and_reaches_grid_face(heading, radius, offset) -> None: +def test_custom_sbend_uses_one_asymmetric_polygon_and_reaches_grid_face() -> None: + heading = 270 + radius = 12.25 + offset = -11 span = sbend_grid_span(offset, radius) profile = [(0, 0), (span // 3, offset * 0.15), (2 * span // 3, offset * 0.65), (span, offset)] outline = Polygon([(x, y - 1) for x, y in profile] + [(x, y + 1) for x, y in reversed(profile)]) @@ -256,22 +122,6 @@ def test_custom_sbend_uses_one_asymmetric_polygon_and_reaches_grid_face(heading, assert result.dilated_physical_geometry[0].equals(placed.buffer(1)) -def test_sbend_collision_models() -> None: - start = Port(0, 0, 0) - offset = 5.0 - radius = 10.0 - width = 2.0 - - res_bbox = SBend.generate(start, offset, radius, width, collision_type="bbox") - # Geometry should be a list of individual bbox polygons for each arc - assert len(res_bbox.collision_geometry) == 2 - - res_arc = SBend.generate(start, offset, radius, width, collision_type="arc") - area_bbox = sum(p.area for p in res_bbox.collision_geometry) - area_arc = sum(p.area for p in res_arc.collision_geometry) - assert area_bbox > area_arc - - def test_sbend_continuity() -> None: # Verify SBend endpoints and continuity math start = Port(10, 20, 90) # Starting facing up @@ -312,8 +162,13 @@ def test_arc_sagitta_precision() -> None: assert pts_fine > pts_coarse * 2 -@pytest.mark.parametrize("radius", [100, 79999, 80001, 100000]) -@pytest.mark.parametrize("offset", [None, 0.5]) +@pytest.mark.parametrize( + ('radius', 'offset'), + [ + (80001, None), + (100000, 0.5), + ], +) def test_circular_bends_detect_keepouts_inside_the_outer_edge(radius, offset) -> None: width = radius / 200 start = Port(0, 0, 0) @@ -359,10 +214,3 @@ def test_component_transform_invariance() -> None: assert abs(res_transformed.end_port.x - p_end_transformed.x) < 1e-6 assert abs(res_transformed.end_port.y - p_end_transformed.y) < 1e-6 assert abs(res_transformed.end_port.r - p_end_transformed.r) < 1e-6 - - -def test_component_result_is_immutable_value_type() -> None: - result = Straight.generate(Port(0, 0, 0), 10.0, 2.0) - - with pytest.raises(FrozenInstanceError): - result.length = 42.0 diff --git a/inire/tests/test_congestion.py b/inire/tests/test_congestion.py index 7d3f2eb..3e27511 100644 --- a/inire/tests/test_congestion.py +++ b/inire/tests/test_congestion.py @@ -5,7 +5,6 @@ from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port from inire.model import NetSpec from inire.router._astar_types import AStarContext, SearchRunConfig -from inire.router._router import PathFinder from inire.router._search import route_astar from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap @@ -40,30 +39,6 @@ def _build_context( ) -def _build_pathfinder( - evaluator: CostEvaluator, - *, - bounds: tuple[float, float, float, float], - netlist: dict[str, tuple[Port, Port]], - net_widths: dict[str, float], - search: SearchOptions | None = None, - congestion: CongestionOptions | None = None, -) -> PathFinder: - nets = tuple( - NetSpec(net_id=net_id, start=start, target=target, width=net_widths.get(net_id, 2.0)) - for net_id, (start, target) in netlist.items() - ) - return PathFinder( - _build_context( - evaluator, - bounds=bounds, - nets=nets, - search=search, - congestion=congestion, - ), - ) - - def _route(context: AStarContext, start: Port, target: Port) -> object: return route_astar( start, diff --git a/inire/tests/test_cost.py b/inire/tests/test_cost.py index ee1de46..681ede2 100644 --- a/inire/tests/test_cost.py +++ b/inire/tests/test_cost.py @@ -46,18 +46,6 @@ def test_cost_calculation() -> None: assert h_away >= h_90 -def test_greedy_h_weight_is_mutable() -> None: - engine = RoutingWorld(clearance=2.0) - danger_map = DangerMap(bounds=(0, 0, 50, 50)) - danger_map.precompute([]) - evaluator = CostEvaluator(engine, danger_map, greedy_h_weight=1.5, bend_penalty=10.0) - - assert evaluator.greedy_h_weight == 1.5 - evaluator.greedy_h_weight = 1.2 - assert evaluator.greedy_h_weight == 1.2 - assert abs(evaluator.h_manhattan(Port(0, 0, 0), Port(10, 10, 0)) - 72.0) < 1e-6 - - def test_proximity_cost_uses_physical_outline_at_outlying_declared_ports() -> None: danger_map = DangerMap((0.5001, -10, 79.4999, 70)) danger_map.precompute([box(77, 42, 78, 43)]) @@ -72,33 +60,6 @@ def test_proximity_cost_uses_physical_outline_at_outlying_declared_ports() -> No assert evaluator.score_component(bend.translate(1, 0), start_port=start.translate(1, 0)) == 1e15 -def test_danger_map_kd_tree_and_cache() -> None: - # Test that KD-Tree based danger map works and uses cache - bounds = (0, 0, 1000, 1000) - dm = DangerMap(bounds, resolution=1.0, safety_threshold=10.0) - - # Square obstacle at (100, 100) to (110, 110) - obstacle = Polygon([(100, 100), (110, 100), (110, 110), (100, 110)]) - dm.precompute([obstacle]) - - # 1. High cost near boundary - cost_near = dm.get_cost(100.5, 100.5) - assert cost_near > 1.0 - - # 2. Zero cost far away - cost_far = dm.get_cost(500, 500) - assert cost_far == 0.0 - - # 3. Check cache usage (internal detail check) - # We can check if calling it again is fast or just verify it returns same result - cost_near_2 = dm.get_cost(100.5, 100.5) - assert cost_near_2 == cost_near - assert len(dm._cost_cache) == 2 - - # 4. Out of bounds - assert dm.get_cost(-1, -1) >= 1e12 - - def test_danger_map_cache_is_instance_local_and_cleared_on_precompute() -> None: obstacle = Polygon([(10, 10), (20, 10), (20, 20), (10, 20)]) dm_a = DangerMap((0, 0, 100, 100)) @@ -146,15 +107,6 @@ def test_danger_map_clips_sampling_without_restarting_spacing_on_diagonal_edges( assert_allclose(sorted(map(tuple, danger.tree.data)), expected, atol=1e-12) -def test_danger_map_samples_only_the_nearby_edge_of_a_large_keepout() -> None: - danger = DangerMap((0, 0, 100, 100)) - danger.precompute([box(90, 20, 100_090, 100_020)]) - - assert danger.tree is not None - assert danger.tree.n < 30 - assert danger.get_cost(85, 40) == 0.04 - - def test_large_perimeter_uses_bounded_exact_index_with_interior_opening() -> None: problem = RoutingProblem((0, 0, 1_100_000, 1_100_000)) hole = box(100, 100, 900, 900) diff --git a/inire/tests/test_example_performance.py b/inire/tests/test_example_performance.py index adf7bfb..eed1355 100644 --- a/inire/tests/test_example_performance.py +++ b/inire/tests/test_example_performance.py @@ -7,15 +7,15 @@ from typing import TYPE_CHECKING import pytest from inire.tests.example_scenarios import ( + EXPECTED_OUTCOMES, SCENARIOS, - ScenarioOutcome, snapshot_example_07_no_warm_start, snapshot_example_07_no_warm_start_seed43, trace_example_07_no_warm_start_seed43, ) if TYPE_CHECKING: - from collections.abc import Callable + from inire.tests.example_scenarios import ScenarioRun RUN_PERFORMANCE = os.environ.get("INIRE_RUN_PERFORMANCE") == "1" @@ -37,38 +37,20 @@ BASELINE_SECONDS = { "example_09_unroutable_best_effort": 0.0056, } -EXPECTED_OUTCOMES = { - "example_01_simple_route": {"total_results": 1, "valid_results": 1, "reached_targets": 1}, - "example_02_congestion_resolution": {"total_results": 3, "valid_results": 3, "reached_targets": 3}, - "example_03_locked_paths": {"total_results": 2, "valid_results": 2, "reached_targets": 2}, - "example_04_sbends_and_radii": {"total_results": 2, "valid_results": 2, "reached_targets": 2}, - "example_05_orientation_stress": {"total_results": 3, "valid_results": 3, "reached_targets": 3}, - "example_06_bend_collision_models": {"total_results": 3, "valid_results": 3, "reached_targets": 3}, - "example_07_large_scale_routing": {"total_results": 10, "valid_results": 10, "reached_targets": 10}, - "example_08_custom_bend_geometry": {"total_results": 2, "valid_results": 2, "reached_targets": 2}, - "example_09_unroutable_best_effort": {"total_results": 1, "valid_results": 0, "reached_targets": 0}, -} - - -def _assert_expected_outcome(name: str, outcome: ScenarioOutcome) -> None: - _, total_results, valid_results, reached_targets = outcome - expected = EXPECTED_OUTCOMES[name] - assert total_results == expected["total_results"] - assert valid_results == expected["valid_results"] - assert reached_targets == expected["reached_targets"] - @pytest.mark.performance -@pytest.mark.skipif(not RUN_PERFORMANCE, reason="set INIRE_RUN_PERFORMANCE=1 to run runtime regression checks") @pytest.mark.parametrize("scenario", SCENARIOS, ids=[name for name, _ in SCENARIOS]) -def test_example_like_runtime_regression(scenario: tuple[str, Callable[[], ScenarioOutcome]]) -> None: +def test_example_outcomes_and_optional_runtime(scenario: tuple[str, ScenarioRun]) -> None: name, run = scenario timings = [] - for _ in range(PERFORMANCE_REPEATS): + for _ in range(PERFORMANCE_REPEATS if RUN_PERFORMANCE else 1): outcome = run() - _assert_expected_outcome(name, outcome) + assert outcome[1:] == EXPECTED_OUTCOMES[name] timings.append(outcome[0]) + if not RUN_PERFORMANCE: + return + median_runtime = statistics.median(timings) assert median_runtime <= BASELINE_SECONDS[name] * REGRESSION_FACTOR, ( f"{name} median runtime {median_runtime:.4f}s exceeded " @@ -78,8 +60,7 @@ def test_example_like_runtime_regression(scenario: tuple[str, Callable[[], Scena @pytest.mark.performance -@pytest.mark.skipif(not RUN_PERFORMANCE, reason="set INIRE_RUN_PERFORMANCE=1 to run runtime regression checks") -def test_example_07_no_warm_start_runtime_regression() -> None: +def test_example_07_no_warm_start_outcome_and_optional_runtime() -> None: snapshot = snapshot_example_07_no_warm_start() assert snapshot.total_results == 10 @@ -87,11 +68,17 @@ def test_example_07_no_warm_start_runtime_regression() -> None: assert snapshot.reached_targets == 10 assert snapshot.metrics.warm_start_paths_built == 0 assert snapshot.metrics.warm_start_paths_used == 0 - assert snapshot.duration_s <= NO_WARM_START_REGRESSION_SECONDS, ( - "example_07_large_scale_routing_no_warm_start runtime " - f"{snapshot.duration_s:.4f}s exceeded guardrail " - f"{NO_WARM_START_REGRESSION_SECONDS:.1f}s" - ) + assert snapshot.metrics.pair_local_search_pairs_considered >= 1 + assert snapshot.metrics.pair_local_search_accepts >= 1 + assert snapshot.metrics.pair_local_search_nodes_expanded <= 128 + assert snapshot.metrics.nodes_expanded <= 2500 + assert snapshot.metrics.congestion_check_calls <= 6000 + if RUN_PERFORMANCE: + assert snapshot.duration_s <= NO_WARM_START_REGRESSION_SECONDS, ( + "example_07_large_scale_routing_no_warm_start runtime " + f"{snapshot.duration_s:.4f}s exceeded guardrail " + f"{NO_WARM_START_REGRESSION_SECONDS:.1f}s" + ) @pytest.mark.performance diff --git a/inire/tests/test_example_regressions.py b/inire/tests/test_example_regressions.py index 3c5f6b7..30c768a 100644 --- a/inire/tests/test_example_regressions.py +++ b/inire/tests/test_example_regressions.py @@ -1,83 +1,20 @@ -from dataclasses import replace import pytest -from shapely.geometry import Polygon, box +from shapely.geometry import Polygon from inire import ( CongestionOptions, - DiagnosticsOptions, NetSpec, - ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route, ) -from inire.router._stack import build_routing_stack -from inire.seeds import Bend90Seed, PathSeed, StraightSeed -from inire.tests.example_scenarios import ( - SCENARIOS, - _build_example_07_variant_stack, - _build_example_08_workers, - snapshot_example_05, - snapshot_example_07_no_warm_start, - trace_example_07_no_warm_start, -) -EXPECTED_OUTCOMES = { - "example_01_simple_route": (1, 1, 1), - "example_02_congestion_resolution": (3, 3, 3), - "example_03_locked_paths": (2, 2, 2), - "example_04_sbends_and_radii": (2, 2, 2), - "example_05_orientation_stress": (3, 3, 3), - "example_06_bend_collision_models": (3, 3, 3), - "example_07_large_scale_routing": (10, 10, 10), - "example_08_custom_bend_geometry": (2, 2, 2), - "example_09_unroutable_best_effort": (1, 0, 0), -} - - -@pytest.mark.parametrize(("name", "run"), SCENARIOS, ids=[name for name, _ in SCENARIOS]) -def test_examples_match_legacy_expected_outcomes(name: str, run) -> None: - outcome = run() - assert outcome[1:] == EXPECTED_OUTCOMES[name] - - -def test_example_05_avoids_dynamic_tree_rebuilds() -> None: - snapshot = snapshot_example_05() - - assert snapshot.valid_results == 3 - assert snapshot.metrics.dynamic_tree_rebuilds == 0 - - -def test_example_07_variant_uses_one_configuration() -> None: - evaluator, _, finder = _build_example_07_variant_stack(num_nets=10, seed=42, warm_start_enabled=False) - world = evaluator.collision_engine - - assert finder.context.options.objective == evaluator.default_weights - assert finder.context.problem.clearance == world.clearance == 6.0 - assert finder.context.problem.static_obstacles == tuple(world.iter_static_geometries()) - - -def test_example_07_no_warm_start_canary_improves_validity() -> None: - snapshot = snapshot_example_07_no_warm_start() - - assert snapshot.total_results == 10 - assert snapshot.reached_targets == 10 - assert snapshot.valid_results == 10 - assert snapshot.metrics.warm_start_paths_built == 0 - assert snapshot.metrics.warm_start_paths_used == 0 - assert snapshot.metrics.pair_local_search_pairs_considered >= 1 - assert snapshot.metrics.pair_local_search_accepts >= 1 - assert snapshot.metrics.pair_local_search_nodes_expanded <= 128 - assert snapshot.metrics.nodes_expanded <= 2500 - assert snapshot.metrics.congestion_check_calls <= 6000 - - -def test_example_07_no_warm_start_trace_finishes_without_conflict_edges() -> None: - run = trace_example_07_no_warm_start() +def test_example_07_no_warm_start_trace_finishes_without_conflict_edges(example_07_no_warm_start_trace) -> None: + run = example_07_no_warm_start_trace assert len(run.results_by_net) == 10 assert sum(result.is_valid for result in run.results_by_net.values()) == 10 @@ -92,149 +29,6 @@ def test_example_07_no_warm_start_trace_finishes_without_conflict_edges() -> Non assert final_entry.conflict_edges == () -def test_example_06_clipped_bbox_margin_keeps_legacy_seed_replayable() -> None: - bounds = (-20, -20, 170, 170) - obstacles = ( - Polygon([(40, 110), (60, 110), (60, 130), (40, 130)]), - Polygon([(40, 60), (60, 60), (60, 80), (40, 80)]), - Polygon([(40, 10), (60, 10), (60, 30), (40, 30)]), - ) - problem = RoutingProblem( - bounds=bounds, - nets=(NetSpec("clipped_model", Port(10, 20, 0), Port(90, 40, 90), width=2.0),), - static_obstacles=obstacles, - ) - common_kwargs = { - "objective": ObjectiveWeights(bend_penalty=50.0, sbend_penalty=150.0), - "congestion": CongestionOptions(use_tiered_strategy=False), - } - no_margin = route( - problem, - options=RoutingOptions( - search=SearchOptions( - bend_radii=(10.0,), - bend_collision_type="clipped_bbox", - ), - **common_kwargs, - ), - ).results_by_net["clipped_model"] - legacy_seed = PathSeed( - ( - StraightSeed(5.0), - Bend90Seed(10.0, "CW"), - Bend90Seed(10.0, "CCW"), - StraightSeed(45.0), - Bend90Seed(10.0, "CCW"), - StraightSeed(30.0), - ) - ) - simulation = replace(problem, initial_paths={"clipped_model": legacy_seed}) - legacy_options = RoutingOptions( - search=SearchOptions(node_limit=0, bend_radii=(10.0,), bend_collision_type="clipped_bbox", bend_clip_margin=1.0), - **common_kwargs, - ) - legacy = route(simulation, options=legacy_options).results_by_net["clipped_model"] - - assert no_margin.is_valid - assert legacy.is_valid - assert legacy.as_seed() == legacy_seed - - -def test_example_07_reduced_bottleneck_uses_adaptive_greedy_callback() -> None: - bounds = (0, 0, 500, 300) - obstacles = ( - box(220, 0, 280, 100), - box(220, 200, 280, 300), - ) - netlist = { - "net_00": (Port(30, 130, 0), Port(470, 60, 0)), - "net_01": (Port(30, 140, 0), Port(470, 120, 0)), - "net_02": (Port(30, 150, 0), Port(470, 180, 0)), - "net_03": (Port(30, 160, 0), Port(470, 240, 0)), - } - problem = RoutingProblem( - bounds=bounds, - nets=tuple(NetSpec(net_id, start, target, width=2.0) for net_id, (start, target) in netlist.items()), - static_obstacles=obstacles, - clearance=6.0, - ) - options = RoutingOptions( - search=SearchOptions( - node_limit=200000, - bend_radii=(30.0,), - sbend_radii=(30.0,), - greedy_h_weight=1.5, - bend_clip_margin=10.0, - ), - objective=ObjectiveWeights( - unit_length_cost=0.1, - bend_penalty=100.0, - sbend_penalty=400.0, - ), - congestion=CongestionOptions( - max_iterations=6, - base_penalty=100.0, - multiplier=1.4, - net_order="shortest", - shuffle_nets=True, - seed=42, - ), - diagnostics=DiagnosticsOptions(capture_expanded=False), - ) - stack = build_routing_stack(problem, options) - evaluator = stack.evaluator - finder = stack.finder - weights: list[float] = [] - - def iteration_callback(iteration: int, current_results: dict[str, object]) -> None: - _ = current_results - new_greedy = max(1.1, 1.5 - ((iteration + 1) / 10.0) * 0.4) - evaluator.greedy_h_weight = new_greedy - weights.append(new_greedy) - finder.metrics.reset_per_route() - - results = finder.route_all(iteration_callback=iteration_callback) - - assert weights == [1.46] - assert evaluator.greedy_h_weight == 1.46 - assert all(result.is_valid for result in results.values()) - assert all(result.reached_target for result in results.values()) - - -def test_example_06_custom_geometry_can_be_true_physical_geometry() -> None: - bounds = (-20, -20, 170, 170) - obstacles = ( - Polygon([(40, 110), (60, 110), (60, 130), (40, 130)]), - Polygon([(40, 60), (60, 60), (60, 80), (40, 80)]), - Polygon([(40, 10), (60, 10), (60, 30), (40, 30)]), - ) - custom_poly = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - result = route( - RoutingProblem( - bounds=bounds, - nets=(NetSpec("custom_geometry", Port(10, 20, 0), Port(90, 40, 90), width=2.0),), - static_obstacles=obstacles, - ), - options=RoutingOptions( - search=SearchOptions( - bend_radii=(10.0,), - bend_physical_geometry=custom_poly, - bend_proxy_geometry=custom_poly, - ), - objective=ObjectiveWeights(bend_penalty=50.0, sbend_penalty=150.0), - congestion=CongestionOptions(use_tiered_strategy=False), - ), - ).results_by_net["custom_geometry"] - - assert result.is_valid - bends = [component for component in result.path if component.move_type == "bend90"] - assert bends - assert all( - component.collision_geometry[0].symmetric_difference(component.physical_geometry[0]).area < 1e-6 - for component in bends - ) - - def test_custom_proxy_without_physical_geometry_warns_and_keeps_arc_geometry() -> None: custom_proxy = Polygon([(0, -11), (11, -11), (11, 0), (0, 0)]) @@ -263,21 +57,3 @@ def test_custom_proxy_without_physical_geometry_warns_and_keeps_arc_geometry() - component.collision_geometry[0].symmetric_difference(component.physical_geometry[0]).area > 1e-6 for component in bends ) - - -def test_example_08_custom_geometry_runs_in_separate_sessions() -> None: - standard_worker, custom_worker = _build_example_08_workers() - assert standard_worker.context.cost_evaluator.collision_engine is not custom_worker.context.cost_evaluator.collision_engine - standard = standard_worker.route_all() - custom = custom_worker.route_all() - - assert standard["standard_arc"].is_valid - assert standard["standard_arc"].reached_target - assert custom["custom_geometry_and_proxy"].is_valid - assert custom["custom_geometry_and_proxy"].reached_target - custom_bends = [component for component in custom["custom_geometry_and_proxy"].path if component.move_type == "bend90"] - assert custom_bends - assert all( - component.collision_geometry[0].symmetric_difference(component.physical_geometry[0]).area > 1e-6 - for component in custom_bends - ) diff --git a/inire/tests/test_layout.py b/inire/tests/test_layout.py index 7ed6618..90a1a98 100644 --- a/inire/tests/test_layout.py +++ b/inire/tests/test_layout.py @@ -46,35 +46,26 @@ def test_replay_verifies_actual_concentric_bend_clearance(outer_radius, valid) - assert result.report.dynamic_collision_count == int(not valid) -@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) -@pytest.mark.parametrize(("start_x", "y", "valid"), [(10, 22, False), (40, 22, False), (40, 23, True)]) -def test_imported_fixed_routes_hold_clearance_at_edges_and_vertices(mode, start_x, y, valid) -> None: - net = NetSpec("new", Port(start_x, y, 0), Port(90, y, 0)) - fixed = FixedRoute("existing", (box(10, 19, 40, 21),)) - problem = RoutingProblem((0, 0, 100, 50), (net,), clearance=0, fixed_routes=(fixed,)) - options = RoutingOptions( - search=SearchOptions(node_limit=20, bend_radii=(), sbend_radii=()), - topology=TopologyOptions(mode=mode), +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) == {"new"} - assert results["new"].is_valid is valid + 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_fixed_route_from_result_preserves_polygon_and_owner() -> None: - net = NetSpec("first", Port(10, 20, 0), Port(90, 20, 0)) - problem = RoutingProblem((0, 0, 100, 50), (net,)) - fixed = FixedRoute.from_result(route(problem).results_by_net["first"]) - assert fixed.net_id == net.net_id - assert fixed.polygons[0].equals(box(10, 19, 90, 21)) - with pytest.raises(ValueError, match="Duplicate active or fixed"): - replace(problem, fixed_routes=(fixed,)) - - -@pytest.mark.parametrize("fixed_bounds", [(23.9, 15.6, 24.4, 16.1), (25.15, 14.75, 25.25, 14.85)], ids=["overlap", "insufficient-gap"]) -def test_lattice_bend_admission_checks_physical_clearance_to_fixed_route(fixed_bounds) -> None: +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,)) @@ -91,8 +82,13 @@ def test_lattice_bend_admission_checks_physical_clearance_to_fixed_route(fixed_b assert result.as_seed() == PathSeed((StraightSeed(10), Bend90Seed(10, "CCW"), StraightSeed(10))) -@pytest.mark.parametrize("fixed", [False, True], ids=["keepout", "fixed-net"]) -@pytest.mark.parametrize(("clearance", "valid"), [(0.25, True), (0.5, False)]) +@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) @@ -111,31 +107,6 @@ def test_imported_polygon_precision_preserves_fractional_clearance(fixed, cleara assert reports[0] == reports[1] -@pytest.mark.parametrize(("pitch", "valid"), [(28000, False), (32000, False), (36000, True)]) -def test_cpw_envelope_clearance_and_signal_recipe_replay(pitch, valid) -> None: - nets = tuple(NetSpec(f"cpw{i}", Port(10000, 30000 + i * pitch, 0), Port(210000, 30000 + i * pitch, 0), 29500) - for i in range(2)) - seeds = {net.net_id: PathSeed((StraightSeed(200000),)) for net in nets} - problem = RoutingProblem((0, 0, 220000, 100000), nets, initial_paths=seeds, clearance=3000) - - envelopes = route(problem, options=_REPLAY).results_by_net - - assert all(envelope.is_valid for envelope in envelopes.values()) == valid - if valid: - signals = replace( - problem, - nets=tuple(replace(net, width=15500) for net in nets), - initial_paths={key: result.as_seed() for key, result 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_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) @@ -165,21 +136,6 @@ def test_profile_options_apply_to_active_search_and_seed_replay() -> None: assert recovered["feed"].report.seed_error == "Initial path for 'feed' uses radius 15000 outside bend_radii" -@pytest.mark.parametrize(("second_y", "valid"), [(22, False), (23, True)]) -def test_profile_reserves_replayed_net_against_zero_clearance_contact(second_y, valid) -> None: - first = NetSpec("first", Port(10, 20, 0), Port(90, 20, 0)) - second = NetSpec("second", Port(10, second_y, 0), Port(90, second_y, 0)) - seeds = {net.net_id: PathSeed((StraightSeed(80),)) for net in (first, second)} - problem = RoutingProblem((0, 0, 100, 50), (first, second), initial_paths=seeds, clearance=0) - - results = route_profiles(problem, [(("first",), _REPLAY), (("second",), _REPLAY)]) - - assert results["first"].is_valid - assert results["second"].is_valid is valid - if valid: - assert results["second"].as_seed() == seeds["second"] - - 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) @@ -212,6 +168,64 @@ def test_authored_template_lengths_are_used_for_candidate_acceptance() -> None: 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)), @@ -229,50 +243,3 @@ def test_authored_sbend_length_survives_seed_replay() -> None: options=replace(options, search=replace(search, node_limit=0)), ).results_by_net["shift"] assert preserves_length(replay, 95, tolerance=0) - - -def test_routing_inputs_and_results_are_detached_snapshots() -> 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 - - -def test_read_only_snapshots_survive_python_copy_and_pickle() -> None: - track = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) - problem = RoutingProblem((0, 0, 100, 50), (track,)) - run = route(problem) - 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 - - -def test_asdict_serializes_snapshot_entries_as_structured_data() -> None: - net = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) - seed = PathSeed((StraightSeed(80),)) - problem = RoutingProblem((0, 0, 100, 50), (net,), initial_paths={net.net_id: seed}) - run = route(problem, options=_REPLAY) - - 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} diff --git a/inire/tests/test_pathfinder.py b/inire/tests/test_pathfinder.py index dc2e721..1505319 100644 --- a/inire/tests/test_pathfinder.py +++ b/inire/tests/test_pathfinder.py @@ -105,8 +105,8 @@ def _build_manual_path(start: Port, width: float, clearance: float, steps: list[ return path -@pytest.mark.parametrize("search_raises", [False, True], ids=["success", "exception"]) -def test_frontier_replay_restores_installed_path_and_metrics(monkeypatch: pytest.MonkeyPatch, search_raises: bool) -> None: +def test_frontier_replay_restores_installed_path_and_metrics(monkeypatch: pytest.MonkeyPatch) -> None: + search_raises = True world = RoutingWorld(clearance=2.0) danger_map = DangerMap(bounds=DEFAULT_BOUNDS) finder = _build_pathfinder( @@ -219,8 +219,8 @@ def test_route_all_refreshes_static_caches_after_static_topology_changes() -> No assert [(comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in auto_result.path] == [ (comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in manual_result.path ] -@pytest.mark.parametrize("max_windows", [1, None]) -def test_refine_path_handles_same_orientation_lateral_offset(max_windows: int | None) -> None: +def test_refine_path_handles_same_orientation_lateral_offset() -> None: + max_windows = 1 engine = RoutingWorld(clearance=2.0) danger_map = DangerMap(bounds=(-20, -20, 120, 120)) danger_map.precompute([]) @@ -271,53 +271,6 @@ def test_refine_path_handles_same_orientation_lateral_offset(max_windows: int | assert windows > 1 -def test_refine_path_can_simplify_subpath_with_different_global_orientation() -> None: - engine = RoutingWorld(clearance=2.0) - danger_map = DangerMap(bounds=(-20, -20, 120, 120)) - danger_map.precompute([]) - evaluator = CostEvaluator(engine, danger_map, bend_penalty=250.0, sbend_penalty=500.0) - pf = _build_pathfinder( - evaluator, - netlist={"net": (Port(0, 0, 0), Port(65, 30, 90))}, - net_widths={"net": 2.0}, - bounds=(-20, -20, 120, 120), - bend_radii=[5.0, 10.0], - enabled=True, - ) - - start = Port(0, 0, 0) - width = 2.0 - path = _build_manual_path( - start, - width, - engine.clearance, - [ - ("B", "CCW"), - ("S", 10.0), - ("B", "CW"), - ("S", 20.0), - ("B", "CW"), - ("S", 10.0), - ("B", "CCW"), - ("S", 10.0), - ("B", "CCW"), - ("S", 5.0), - ("B", "CW"), - ("B", "CCW"), - ("S", 10.0), - ], - ) - target = path[-1].end_port - - refined = pf.refiner.refine_path("net", start, width, path) - - assert target == Port(65, 30, 90) - assert sum(1 for comp in path if comp.move_type == "bend90") == 7 - assert sum(1 for comp in refined if comp.move_type == "bend90") == 5 - assert refined[-1].end_port == target - assert pf.refiner.path_cost(refined) < pf.refiner.path_cost(path) - - def test_changed_window_checks_for_collision_with_the_unchanged_prefix() -> None: world = RoutingWorld(clearance=2.0) start = Port(10, -10, 90) diff --git a/inire/tests/test_performance_reporting.py b/inire/tests/test_performance_reporting.py index e0c5c56..f5cd1c3 100644 --- a/inire/tests/test_performance_reporting.py +++ b/inire/tests/test_performance_reporting.py @@ -3,56 +3,13 @@ import subprocess import sys from pathlib import Path -from inire.tests.example_scenarios import snapshot_example_01 +import pytest + +from inire.tests import trace_recording +from scripts import record_conflict_trace, record_frontier_trace, record_iteration_trace, record_pre_pair_frontier_trace -def test_snapshot_example_01_exposes_metrics() -> None: - snapshot = snapshot_example_01() - - assert snapshot.name == "example_01_simple_route" - assert snapshot.total_results == 1 - assert snapshot.valid_results == 1 - assert snapshot.reached_targets == 1 - assert snapshot.metrics.route_iterations >= 1 - assert snapshot.metrics.nets_routed >= 1 - assert snapshot.metrics.nodes_expanded > 0 - assert snapshot.metrics.score_component_calls >= 0 - assert snapshot.metrics.danger_map_lookup_calls >= 0 - assert snapshot.metrics.move_cache_abs_misses >= 0 - assert snapshot.metrics.guidance_match_moves >= 0 - assert snapshot.metrics.guidance_match_moves_straight >= 0 - assert snapshot.metrics.guidance_match_moves_bend90 >= 0 - assert snapshot.metrics.guidance_match_moves_sbend >= 0 - assert snapshot.metrics.guidance_bonus_applied >= 0.0 - assert snapshot.metrics.guidance_bonus_applied_straight >= 0.0 - assert snapshot.metrics.guidance_bonus_applied_bend90 >= 0.0 - assert snapshot.metrics.guidance_bonus_applied_sbend >= 0.0 - assert snapshot.metrics.ray_cast_calls >= 0 - assert snapshot.metrics.ray_cast_calls_expand_forward >= 0 - assert snapshot.metrics.dynamic_tree_rebuilds >= 0 - assert snapshot.metrics.visibility_corner_index_builds >= 0 - assert snapshot.metrics.visibility_builds >= 0 - assert snapshot.metrics.congestion_grid_span_cache_hits >= 0 - assert snapshot.metrics.congestion_grid_span_cache_misses >= 0 - assert snapshot.metrics.congestion_candidate_nets >= 0 - assert snapshot.metrics.congestion_net_envelope_cache_hits >= 0 - assert snapshot.metrics.congestion_net_envelope_cache_misses >= 0 - assert snapshot.metrics.congestion_grid_net_cache_hits >= 0 - assert snapshot.metrics.congestion_grid_net_cache_misses >= 0 - assert snapshot.metrics.congestion_lazy_resolutions >= 0 - assert snapshot.metrics.congestion_lazy_requeues >= 0 - assert snapshot.metrics.congestion_candidate_ids >= 0 - assert snapshot.metrics.verify_dynamic_candidate_nets >= 0 - assert snapshot.metrics.refinement_candidates_verified >= 0 - assert snapshot.metrics.pair_local_search_pairs_considered >= 0 - assert snapshot.metrics.pair_local_search_attempts >= 0 - assert snapshot.metrics.pair_local_search_accepts >= 0 - assert snapshot.metrics.pair_local_search_nodes_expanded >= 0 - assert snapshot.metrics.late_phase_capped_nets >= 0 - assert snapshot.metrics.late_phase_capped_fallbacks >= 0 - - -def test_record_performance_baseline_script_writes_selected_scenario(tmp_path: Path) -> None: +def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario(tmp_path: Path) -> None: repo_root = Path(__file__).resolve().parents[2] script_path = repo_root / "scripts" / "record_performance_baseline.py" @@ -74,79 +31,22 @@ def test_record_performance_baseline_script_writes_selected_scenario(tmp_path: P assert [entry["name"] for entry in payload["scenarios"]] == ["example_01_simple_route"] assert (tmp_path / "performance.md").exists() - -def test_diff_performance_baseline_script_writes_selected_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - record_script = repo_root / "scripts" / "record_performance_baseline.py" - diff_script = repo_root / "scripts" / "diff_performance_baseline.py" - baseline_dir = tmp_path / "baseline" - baseline_dir.mkdir() - output_path = tmp_path / "diff.md" - + output = tmp_path / "diff.md" + log = tmp_path / "optimization.md" subprocess.run( [ sys.executable, - str(record_script), - "--output-dir", - str(baseline_dir), - "--scenario", - "example_01_simple_route", - ], - check=True, - ) - subprocess.run( - [ - sys.executable, - str(diff_script), + str(repo_root / "scripts" / "diff_performance_baseline.py"), "--baseline", - str(baseline_dir / "performance_baseline.json"), + str(tmp_path / "performance_baseline.json"), "--include-performance-only", "--scenario", "example_01_simple_route", - "--output", - str(output_path), - ], - check=True, - ) - - report = output_path.read_text() - assert "Performance Baseline Diff" in report - assert "example_01_simple_route" in report - - -def test_diff_performance_baseline_script_can_append_measurement_log(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - record_script = repo_root / "scripts" / "record_performance_baseline.py" - diff_script = repo_root / "scripts" / "diff_performance_baseline.py" - baseline_dir = tmp_path / "baseline" - baseline_dir.mkdir() - log_path = tmp_path / "optimization.md" - - subprocess.run( - [ - sys.executable, - str(record_script), - "--output-dir", - str(baseline_dir), "--scenario", - "example_01_simple_route", - ], - check=True, - ) - subprocess.run( - [ - sys.executable, - str(diff_script), - "--baseline", - str(baseline_dir / "performance_baseline.json"), - "--include-performance-only", - "--scenario", - "example_01_simple_route", + "example_07_large_scale_routing_no_warm_start", "--metric", "duration_s", "--metric", - "valid_results", - "--metric", "nodes_expanded", "--metric", "visibility_corner_index_builds", @@ -154,61 +54,23 @@ def test_diff_performance_baseline_script_can_append_measurement_log(tmp_path: P "Step 0 - Baseline", "--notes", "Tooling smoke test.", - "--log", - str(log_path), - ], - check=True, - ) - - report = log_path.read_text() - assert "Step 0 - Baseline" in report - assert "Tooling smoke test." in report - assert "| example_01_simple_route | duration_s |" in report - assert "| example_01_simple_route | valid_results |" in report - assert "| example_01_simple_route | visibility_corner_index_builds |" in report - - -def test_diff_performance_baseline_script_renders_current_metrics_for_added_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - record_script = repo_root / "scripts" / "record_performance_baseline.py" - diff_script = repo_root / "scripts" / "diff_performance_baseline.py" - baseline_dir = tmp_path / "baseline" - baseline_dir.mkdir() - output_path = tmp_path / "diff_added.md" - - subprocess.run( - [ - sys.executable, - str(record_script), - "--output-dir", - str(baseline_dir), - "--scenario", - "example_01_simple_route", - ], - check=True, - ) - subprocess.run( - [ - sys.executable, - str(diff_script), - "--baseline", - str(baseline_dir / "performance_baseline.json"), - "--include-performance-only", - "--scenario", - "example_07_large_scale_routing_no_warm_start", - "--metric", - "duration_s", - "--metric", - "nodes_expanded", "--output", - str(output_path), + str(output), + "--log", + str(log), ], check=True, ) - report = output_path.read_text() + report = output.read_text() + assert "| example_01_simple_route | duration_s |" in report + assert "| example_01_simple_route | visibility_corner_index_builds |" in report assert "| example_07_large_scale_routing_no_warm_start | duration_s | - |" in report assert "| example_07_large_scale_routing_no_warm_start | nodes_expanded | - |" in report + entry = log.read_text() + assert "Step 0 - Baseline" in entry + assert "Tooling smoke test." in entry + assert report.rstrip() in entry def test_record_conflict_trace_script_writes_selected_scenario(tmp_path: Path) -> None: @@ -234,94 +96,41 @@ def test_record_conflict_trace_script_writes_selected_scenario(tmp_path: Path) - assert (tmp_path / "conflict_trace.md").exists() -def test_record_conflict_trace_script_supports_performance_only_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - script_path = repo_root / "scripts" / "record_conflict_trace.py" +@pytest.mark.parametrize( + ("report", "generate", "heading"), + [ + ("conflict_trace", record_conflict_trace.main, "# Conflict Trace"), + ("frontier_trace", record_frontier_trace.main, "# Frontier Trace"), + ("iteration_trace", record_iteration_trace.main, "# Iteration Trace"), + ("pre_pair_frontier_trace", record_pre_pair_frontier_trace.main, "# Pre-Pair Frontier Trace"), + ], + ids=["conflict", "frontier", "iteration", "pre-pair-frontier"], +) +def test_record_trace_reports_support_a_performance_only_scenario( + report, generate, heading, tmp_path, monkeypatch, example_07_no_warm_start_trace, +) -> None: + name = trace_recording.NO_WARM_START_SCENARIOS[0] + registry = dict(trace_recording.TRACE_PERFORMANCE_SCENARIO_RUNS) + assert name in registry + registry[name] = lambda: example_07_no_warm_start_trace + monkeypatch.setattr(trace_recording, "TRACE_PERFORMANCE_SCENARIO_RUNS", tuple(registry.items())) + monkeypatch.setattr(sys, "argv", [f"record_{report}", "--output-dir", str(tmp_path), "--scenario", name]) - subprocess.run( - [ - sys.executable, - str(script_path), - "--output-dir", - str(tmp_path), - "--scenario", - "example_07_large_scale_routing_no_warm_start", - ], - check=True, - ) + generate() - payload = json.loads((tmp_path / "conflict_trace.json").read_text()) - assert [entry["name"] for entry in payload["scenarios"]] == ["example_07_large_scale_routing_no_warm_start"] - - -def test_record_frontier_trace_script_writes_selected_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - script_path = repo_root / "scripts" / "record_frontier_trace.py" - - subprocess.run( - [ - sys.executable, - str(script_path), - "--output-dir", - str(tmp_path), - "--scenario", - "example_05_orientation_stress", - ], - check=True, - ) - - payload = json.loads((tmp_path / "frontier_trace.json").read_text()) + payload = json.loads((tmp_path / f"{report}.json").read_text()) assert payload["generated_at"] - assert payload["generator"] == "scripts/record_frontier_trace.py" - assert [entry["name"] for entry in payload["scenarios"]] == ["example_05_orientation_stress"] - assert (tmp_path / "frontier_trace.md").exists() - - -def test_record_iteration_trace_script_writes_selected_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - script_path = repo_root / "scripts" / "record_iteration_trace.py" - - subprocess.run( - [ - sys.executable, - str(script_path), - "--scenario", - "example_07_large_scale_routing_no_warm_start", - "--output-dir", - str(tmp_path), - ], - check=True, - ) - - payload = json.loads((tmp_path / "iteration_trace.json").read_text()) - assert payload["generated_at"] - assert payload["generator"] == "scripts/record_iteration_trace.py" - assert [entry["name"] for entry in payload["scenarios"]] == ["example_07_large_scale_routing_no_warm_start"] - assert (tmp_path / "iteration_trace.md").exists() - - -def test_record_pre_pair_frontier_trace_script_writes_selected_scenario(tmp_path: Path) -> None: - repo_root = Path(__file__).resolve().parents[2] - script_path = repo_root / "scripts" / "record_pre_pair_frontier_trace.py" - - subprocess.run( - [ - sys.executable, - str(script_path), - "--scenario", - "example_07_large_scale_routing_no_warm_start", - "--output-dir", - str(tmp_path), - ], - check=True, - ) - - payload = json.loads((tmp_path / "pre_pair_frontier_trace.json").read_text()) - assert payload["generated_at"] - assert payload["generator"] == "scripts/record_pre_pair_frontier_trace.py" - assert [entry["name"] for entry in payload["scenarios"]] == ["example_07_large_scale_routing_no_warm_start"] - assert payload["scenarios"][0]["pre_pair_frontier_trace"] is not None - assert (tmp_path / "pre_pair_frontier_trace.md").exists() + assert payload["generator"] == f"scripts/record_{report}.py" + [scenario] = payload["scenarios"] + assert scenario["name"] == name + if report == "frontier_trace": + # The final layout has no unresolved conflicts to replay. + assert scenario[report] == [] + else: + assert scenario[report] + markdown = (tmp_path / f"{report}.md").read_text() + assert markdown.startswith(heading + "\n") + assert f"## {name}" in markdown def test_characterize_pair_local_search_script_writes_outputs(tmp_path: Path) -> None: diff --git a/inire/tests/test_perimeter.py b/inire/tests/test_perimeter.py index d8d4666..cd7acd4 100644 --- a/inire/tests/test_perimeter.py +++ b/inire/tests/test_perimeter.py @@ -1,10 +1,9 @@ -from dataclasses import replace import pytest from shapely.geometry import Polygon, box from inire import ( - Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, StraightSeed, route, + Bend90Seed, CongestionOptions, NetSpec, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route, ) from inire.router import _automatic @@ -16,17 +15,6 @@ OPTIONS = RoutingOptions( ) -def test_short_forward_perimeter_detour_does_not_abort_the_batch() -> None: - short = NetSpec("short", Port(30, 30, 0), Port(31, 70, 0)) - peer = NetSpec("peer", Port(5, 90, 0), Port(95, 90, 0)) - problem = RoutingProblem((0, 0, 100, 100), (short, peer), (box(30.3, 5, 30.6, 40),), clearance=0) - - run = route(problem, options=OPTIONS) - - assert run.results_by_net["short"].outcome == "unroutable" - assert run.results_by_net["peer"].is_valid - - def test_forward_perimeter_detour_can_fit_at_exactly_four_radii() -> None: net = NetSpec("edge", Port(20, 25, 0), Port(60, 25, 0)) obstacles = (box(42, 20, 45, 30), box(35, 20, 38, 30), box(75, 50, 85, 58)) @@ -40,92 +28,6 @@ def test_forward_perimeter_detour_can_fit_at_exactly_four_radii() -> None: assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 -@pytest.mark.parametrize("forward", [40, 41]) -def test_tight_forward_perimeter_detours_use_pivots_without_extra_end_spacing(forward) -> None: - net = NetSpec("edge", Port(20, 25, 0), Port(20 + forward, 25, 0)) - problem = RoutingProblem((0, 0, 100, 100), (net,), (box(38, 20, 42, 50),), clearance=0) - - run = route(problem, options=OPTIONS) - - result = run.results_by_net[net.net_id] - assert result.is_valid - assert run.automatic.selected_planner == "perimeter" - assert sum(isinstance(move, Bend90Seed) for move in result.as_seed().segments) == 4 - - -def test_forward_perimeter_lanes_ignore_keepouts_beyond_the_target() -> None: - net = NetSpec("through", Port(20, 60, 0), Port(120, 60, 0)) - problem = RoutingProblem((0, 0, 200, 120), (net,), (box(55, 30, 85, 90),), clearance=0) - distant = (box(150, 0, 160, 4), box(150, 116, 160, 120)) - - clean = route(problem, options=OPTIONS).results_by_net[net.net_id] - cluttered = route(replace(problem, static_obstacles=(*problem.static_obstacles, *distant)), options=OPTIONS) - - result = cluttered.results_by_net[net.net_id] - assert cluttered.automatic.selected_planner == "perimeter" - assert result.is_valid - assert result.as_seed() == clean.as_seed() - - -def test_forward_detours_try_inner_lanes_when_keepouts_reach_board_edges() -> None: - net = NetSpec("forward", Port(20, 60, 0), Port(120, 60, 0)) - obstacles = (box(55, 50, 85, 70), box(40, 0, 45, 4), box(40, 116, 45, 120)) - problem = RoutingProblem((0, 0, 200, 120), (net,), obstacles, clearance=0) - - run = route(problem, options=OPTIONS) - - assert run.automatic.selected_planner == "perimeter" - assert run.results_by_net[net.net_id].is_valid - - -@pytest.mark.parametrize(("width", "clearance"), [(4, 0), (2, 2)]) -def test_forward_perimeter_detours_include_keepouts_clear_of_the_centerline(width, clearance) -> None: - net = NetSpec("forward", Port(20, 50, 0), Port(120, 50, 0), width=width) - problem = RoutingProblem((0, 0, 150, 100), (net,), (box(55, 51.5, 65, 60),), clearance=clearance) - - run = route(problem, options=OPTIONS) - - assert run.automatic.selected_planner == "perimeter" - assert run.results_by_net[net.net_id].is_valid - - -@pytest.mark.parametrize("smaller_radius", [10, 17.5]) -def test_perimeter_detours_choose_a_radius_usable_by_the_planner(smaller_radius) -> None: - net = NetSpec("wide", Port(20, 70, 0), Port(220, 70, 0), width=30) - problem = RoutingProblem((0, 0, 250, 180), (net,), (box(100, 40, 130, 100),), clearance=0) - options = replace(OPTIONS, search=replace(OPTIONS.search, bend_radii=(smaller_radius, 20))) - - run = route(problem, options=options) - - result = run.results_by_net[net.net_id] - assert result.is_valid - assert run.automatic.selected_planner == "perimeter" - assert {move.radius for move in result.as_seed().segments if isinstance(move, Bend90Seed)} == {20} - - -def test_return_detours_snap_board_pivots_inward_before_generating_seeds() -> None: - net = NetSpec("return", Port(88, 50, 0), Port(12, 50, 0), width=3) - problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) - - run = route(problem, options=OPTIONS) - - result = run.results_by_net[net.net_id] - assert result.is_valid - assert run.automatic.selected_planner == "perimeter" - assert result.path[-1].end_port == net.target - - -def test_return_detours_try_inner_lanes_when_keepouts_reach_board_edges() -> None: - net = NetSpec("return", Port(100, 50, 0), Port(20, 50, 0)) - obstacles = (box(40, 0, 50, 4), box(40, 96, 50, 100)) - problem = RoutingProblem((0, 0, 120, 100), (net,), obstacles, clearance=0) - - run = route(problem, options=OPTIONS) - - assert run.automatic.selected_planner == "perimeter" - assert run.results_by_net[net.net_id].is_valid - - def test_return_detours_can_fit_without_straights_at_either_port() -> None: net = NetSpec("return", Port(100, 50, 0), Port(20, 50, 0)) obstacles = (box(111.2, 38, 125, 62), box(0, 38, 8.8, 62)) @@ -178,37 +80,6 @@ def test_perimeter_detours_try_both_sides_within_the_candidate_budget(monkeypatc assert 0 < generated <= 32 -@pytest.mark.parametrize(("forward", "needs_short_straight"), [(43, True), (60, False)]) -def test_residual_doglegs_prefer_the_lattice_minimum_but_can_relax_it(forward, needs_short_straight) -> None: - trunk = NetSpec("trunk", Port(20, 50, 0), Port(20 + forward, 50, 0)) - north = NetSpec("north", Port(10, 60, 90), Port(10, 100, 90)) - rail = NetSpec("rail", Port(85, 100, 0), Port(110, 100, 0)) - problem = RoutingProblem((0, 0, 120, 120), (trunk, north, rail), (box(40, 47, 43, 53),), clearance=0) - - run = route(problem, options=OPTIONS) - - assert run.automatic.selected_planner == "residual-dogleg" - assert all(run.results_by_net[net.net_id].is_valid for net in problem.nets) - lengths = [move.length for move in run.results_by_net["trunk"].as_seed().segments if isinstance(move, StraightSeed)] - assert any(length < OPTIONS.search.min_straight_length for length in lengths) is needs_short_straight - - -def test_residual_doglegs_spend_attempts_only_on_radii_that_fit_the_trace() -> None: - trunk = NetSpec("trunk", Port(30, 100, 0), Port(270, 100, 0), width=30) - north = NetSpec("north", Port(20, 150, 90), Port(20, 200, 90)) - rail = NetSpec("rail", Port(250, 200, 0), Port(300, 200, 0)) - obstacles = (box(140, 93, 153, 107), *(box(x, 180, x + 2, 182) for x in range(70, 241, 20))) - problem = RoutingProblem((0, 0, 310, 230), (trunk, north, rail), obstacles, clearance=0) - options = replace(OPTIONS, search=replace(OPTIONS.search, bend_radii=(10, 20))) - - run = route(problem, options=options) - - assert run.automatic.selected_planner == "residual-dogleg" - assert all(result.is_valid for result in run.results_by_net.values()) - segments = run.results_by_net[trunk.net_id].as_seed().segments - assert {move.radius for move in segments if isinstance(move, Bend90Seed)} == {20} - - def test_residual_dogleg_can_cross_clear_space_inside_a_keepout_bounds() -> None: trunk = NetSpec("trunk", Port(20, 60, 0), Port(120, 60, 0)) north = NetSpec("north", Port(10, 70, 90), Port(10, 105, 90)) @@ -222,8 +93,7 @@ def test_residual_dogleg_can_cross_clear_space_inside_a_keepout_bounds() -> None assert all(result.is_valid for result in run.results_by_net.values()) -@pytest.mark.parametrize("requires_reservation", [False, True]) -def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeypatch, requires_reservation) -> None: +def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeypatch) -> None: line = NetSpec("line", Port(5, 75, 0), Port(195, 75, 0)) returning = NetSpec("return", Port(130, 50, 0), Port(40, 50, 0)) obstacles = tuple(box(x, 100, x + 1, 104) for x in (*range(10, 29, 3), *range(142, 181, 4))) @@ -235,7 +105,7 @@ def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeyp def detours(candidate_problem, search): reserved = bool(candidate_problem.fixed_routes) calls.append((candidate_problem.nets[0].net_id, reserved)) - if reserved or not requires_reservation: + if reserved: for candidate in original_detours(candidate_problem, search): generated.append(reserved) yield candidate @@ -246,5 +116,5 @@ def test_paired_perimeter_plans_peer_reserved_detours_only_as_a_fallback(monkeyp assert run.automatic.selected_planner == "paired-perimeter" assert all(result.is_valid for result in run.results_by_net.values()) - assert calls == ([("return", False), ("return", True)] if requires_reservation else [("return", False)]) - assert generated == [requires_reservation] + assert calls == [("return", False), ("return", True)] + assert generated == [True] diff --git a/inire/tests/test_primitives.py b/inire/tests/test_primitives.py index 718ca18..cb86ad3 100644 --- a/inire/tests/test_primitives.py +++ b/inire/tests/test_primitives.py @@ -7,11 +7,9 @@ import pytest from inire.geometry.primitives import Port, port_local_coordinates, rotate_cardinal -@pytest.mark.parametrize( - ("heading", "expected"), - [(0, (3.5, 7.25)), (90, (7.25, -3.5)), (180, (-3.5, -7.25)), (270, (-7.25, 3.5))], -) -def test_port_local_coordinates_preserve_fractional_points(heading, expected) -> None: +def test_port_local_coordinates_preserve_fractional_points() -> None: + heading = 270 + expected = (-7.25, 3.5) origin = Port(10, -4, heading) local = port_local_coordinates(origin, 13.5, 3.25) assert local == expected @@ -26,12 +24,6 @@ def port_strategy(draw: Any) -> Port: return Port(x, y, orientation) -def test_port_snapping() -> None: - p = Port(0.123456, 0.654321, 90) - assert p.x == 0 - assert p.y == 1 - - def test_port_rotation_preserves_coordinates_beyond_int32() -> None: assert Port(-2**31, 20, 0).rotated(180) == Port(2**31, -20, 180) assert Port(3_000_000_004, 25, 270).rotated(90, origin=(3_000_000_000, 20)) == Port(2_999_999_995, 24, 0) @@ -49,17 +41,6 @@ def test_port_transform_invariants(p: Port) -> None: assert (p_rot.r % 360) == (p.r % 360) -@given( - p=port_strategy(), - dx=st.floats(min_value=-1000, max_value=1000), - dy=st.floats(min_value=-1000, max_value=1000), -) -def test_translate_snapping(p: Port, dx: float, dy: float) -> None: - p_trans = p.translate(dx, dy) - assert isinstance(p_trans.x, int) - assert isinstance(p_trans.y, int) - - def test_orientation_normalization() -> None: p = Port(0, 0, 360) assert p.r == 0 diff --git a/inire/tests/test_refinements.py b/inire/tests/test_refinements.py index 8832ee3..7fa3cbb 100644 --- a/inire/tests/test_refinements.py +++ b/inire/tests/test_refinements.py @@ -6,7 +6,6 @@ from shapely.geometry import Polygon, box from inire import CongestionOptions, ObjectiveWeights, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route from inire import DiagnosticsOptions, PathSeed, StraightSeed from inire.geometry.collision import RoutingWorld -from inire.geometry.components import Bend90 from inire.geometry.primitives import Port from inire.geometry.primitives import port_local_coordinates from inire.model import NetSpec @@ -36,29 +35,35 @@ _REFINEMENT_OPTIONS = RoutingOptions( ) -@pytest.mark.parametrize("limit", [None, 1, 4]) -def test_refinement_window_order_matches_exhaustive_search(limit) -> None: +def test_refinement_window_order_matches_exhaustive_search() -> None: problem = _seeded_foldback() - options = replace(_REFINEMENT_OPTIONS, refinement=RefinementOptions(max_windows_per_net=limit)) start = problem.nets[0].start - path = materialize_path_seed(problem.initial_paths["foldback"], start=start, net_width=2, search=options.search, clearance=2) + path = materialize_path_seed( + problem.initial_paths["foldback"], start=start, net_width=2, search=_REFINEMENT_OPTIONS.search, clearance=2, + ) assert path is not None - finder = PathFinder(AStarContext(CostEvaluator(RoutingWorld(clearance=2), DangerMap(problem.bounds)), problem, options)) ports = [start, *(move.end_port for move in path)] - eligible = [] + unbounded = [] + bounded = [] for left, source in enumerate(ports[:-1]): for right, target in enumerate(ports[left + 1 :], start=left + 1): bends = [move.move_type == "bend90" for move in path[left:right]] forward, _ = port_local_coordinates(source, target.x, target.y) if sum(bends) >= 4 and source.r == target.r and forward >= 40: - priority = -sum((bends[0], bends[-1])) if limit == 4 else 0 - eligible.append((priority, left - right, left, right)) + unbounded.append((left - right, left, right)) + bounded.append((-sum((bends[0], bends[-1])), left - right, left, right)) - assert list(finder.refiner._iter_refinement_windows(start, path)) == [(left, right) for _, _, left, right in sorted(eligible)] + for limit, expected in ( + (None, [(left, right) for _, left, right in sorted(unbounded)]), + (4, [(left, right) for _, _, left, right in sorted(bounded)]), + ): + options = replace(_REFINEMENT_OPTIONS, refinement=RefinementOptions(max_windows_per_net=limit)) + finder = PathFinder(AStarContext(CostEvaluator(RoutingWorld(clearance=2), DangerMap(problem.bounds)), problem, options)) + assert list(finder.refiner._iter_refinement_windows(start, path)) == expected -@pytest.mark.parametrize("radius", [10, 10.25]) -def test_refinement_handles_both_signs_of_the_lateral_offset(radius) -> None: +def test_refinement_handles_both_signs_of_the_lateral_offset() -> None: + radius = 10.25 options = replace(_REFINEMENT_OPTIONS, search=replace(_REFINEMENT_OPTIONS.search, bend_radii=(radius,))) paths = [ route(_seeded_foldback(reflected=reflected, radius=radius), options=options).results_by_net["foldback"] @@ -101,8 +106,8 @@ def test_automatic_refinement_rechecks_retained_partial_paths() -> None: assert traced.conflicting_net_ids == ("foldback",) -@pytest.mark.parametrize("weights", [None, (0, 0, 0)]) -def test_automatic_selects_refinement_using_its_explicit_objective(weights) -> None: +def test_automatic_selects_refinement_using_its_explicit_objective() -> None: + weights = (0, 0, 0) problem = _seeded_foldback() lattice_options = replace( _REFINEMENT_OPTIONS, @@ -121,6 +126,7 @@ def test_automatic_selects_refinement_using_its_explicit_objective(weights) -> N assert len(actual.path) == 9 assert actual.as_seed() == expected.as_seed() assert run.automatic.stages[run.automatic.selected_stage].operation == "refine" + assert any(timing.operation == "refine" for timing in run.automatic.timings) def test_seeded_refinement_builds_proximity_map_at_zero_search_budget(monkeypatch) -> None: @@ -150,8 +156,8 @@ def test_seeded_refinement_builds_proximity_map_at_zero_search_budget(monkeypatc assert callbacks == [result] -@pytest.mark.parametrize("mode", ["automatic", "off"]) -def test_refinement_preserves_custom_bend_geometry_on_seed_replay(mode) -> None: +def test_refinement_preserves_custom_bend_geometry_on_seed_replay() -> None: + mode = 'automatic' outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) options = replace( _REFINEMENT_OPTIONS, @@ -170,111 +176,3 @@ def test_refinement_preserves_custom_bend_geometry_on_seed_replay(mode) -> None: assert result.is_valid assert replay.is_valid assert all(a.equals(b) for a, b in zip(result.locked_geometry, replay.locked_geometry, strict=True)) - - -def _build_pathfinder( - evaluator: CostEvaluator, - *, - bounds: tuple[float, float, float, float], - netlist: dict[str, tuple[Port, Port]], - net_widths: dict[str, float], - search: SearchOptions | None = None, -) -> PathFinder: - nets = tuple( - NetSpec(net_id=net_id, start=start, target=target, width=net_widths.get(net_id, 2.0)) - for net_id, (start, target) in netlist.items() - ) - return PathFinder( - AStarContext( - evaluator, - RoutingProblem(bounds=bounds, nets=nets), - RoutingOptions(search=SearchOptions() if search is None else search), - ), - ) - - -def test_arc_resolution_sagitta() -> None: - start = Port(0, 0, 0) - # R=10, 90 deg bend. - # High tolerance (0.5um) -> few segments - res_coarse = Bend90.generate(start, radius=10.0, width=2.0, direction="CCW", sagitta=0.5) - # Low tolerance (1nm) -> many segments - res_fine = Bend90.generate(start, radius=10.0, width=2.0, direction="CCW", sagitta=0.001) - - - # Check number of points in the polygon exterior - # (num_segments + 1) * 2 points usually - pts_coarse = len(res_coarse.collision_geometry[0].exterior.coords) - pts_fine = len(res_fine.collision_geometry[0].exterior.coords) - - assert pts_fine > pts_coarse - - -@pytest.mark.parametrize(("offset", "move_type"), [(0, "straight"), (5, "sbend")]) -def test_refinement_leaves_simple_paths_installed(offset: int, move_type: str) -> None: - problem = RoutingProblem( - bounds=(0, 0, 120, 120), - nets=(NetSpec("out", Port(10, 50, 0), Port(110, 50 + offset, 0)),), - ) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10.0,), sbend_radii=(10.0,)), - congestion=CongestionOptions(warm_start_enabled=False), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - - assert run.results_by_net["out"].is_valid - assert run.results_by_net["out"].path[-1].move_type == move_type - assert run.metrics.refine_path_calls == 0 - assert run.metrics.dynamic_path_objects_removed == 0 - - -def test_locked_routes() -> None: - engine = RoutingWorld(clearance=2.0) - danger_map = DangerMap(bounds=(0, -50, 100, 50)) - danger_map.precompute([]) - evaluator = CostEvaluator(engine, danger_map) - - # 1. Route Net A - netlist_a = {"netA": (Port(0, 0, 0), Port(50, 0, 0))} - results_a = _build_pathfinder( - evaluator, - bounds=(0, -50, 100, 50), - netlist=netlist_a, - net_widths={"netA": 2.0}, - search=SearchOptions(bend_radii=(5.0, 10.0)), - ).route_all() - assert results_a["netA"].is_valid - - # 2. Treat Net A as locked geometry in the next run. - for polygon in results_a["netA"].locked_geometry: - engine.add_static_obstacle(polygon) - - # 3. Route Net B through the same space. It should detour or fail. - # We'll place Net B's start/target such that it MUST cross Net A's physical path. - netlist_b = {"netB": (Port(0, -5, 0), Port(50, 5, 0))} - - # Route Net B - results_b = _build_pathfinder( - evaluator, - bounds=(0, -50, 100, 50), - netlist=netlist_b, - net_widths={"netB": 2.0}, - search=SearchOptions(bend_radii=(5.0, 10.0)), - ).route_all() - - # Net B should be is_valid (it detoured) or at least not have collisions - # with Net A in the dynamic set (because netA is now static). - # Since netA is static, netB will see it as a HARD collision if it tries to cross. - - # Our A* will find a detour around the static obstacle. - assert results_b["netB"].is_valid - - # Verify geometry doesn't intersect locked netA (physical check) - poly_a = [p.physical_geometry[0] for p in results_a["netA"].path] - poly_b = [p.physical_geometry[0] for p in results_b["netB"].path] - - for pa in poly_a: - for pb in poly_b: - assert not pa.intersects(pb) diff --git a/inire/tests/test_route_behavior.py b/inire/tests/test_route_behavior.py index 8bfc5ea..7597ab6 100644 --- a/inire/tests/test_route_behavior.py +++ b/inire/tests/test_route_behavior.py @@ -1,6 +1,6 @@ from __future__ import annotations -from shapely.geometry import Polygon +from typing import TYPE_CHECKING from inire import ( Bend90Seed, @@ -20,6 +20,9 @@ from inire import ( route, ) +if TYPE_CHECKING: + from shapely.geometry import Polygon + DEFAULT_BOUNDS = (0, -5, 100, 100) _PROBLEM_FIELDS = set(RoutingProblem.__dataclass_fields__) - {"bounds", "nets", "static_obstacles"} @@ -80,50 +83,6 @@ def _bend_count(result: RoutingResult) -> int: return sum(1 for component in result.path if component.move_type == "bend90") -def _build_manual_seed(steps: list[tuple[str, float | str]]) -> PathSeed: - segments = [] - for kind, value in steps: - if kind == "B": - segments.append(Bend90Seed(radius=5.0, direction=value)) - else: - segments.append(StraightSeed(length=value)) - return PathSeed(tuple(segments)) - - -def test_route_parallel_nets_are_valid() -> None: - run = _route_problem( - netlist={ - "net1": (Port(0, 0, 0), Port(50, 0, 0)), - "net2": (Port(0, 10, 0), Port(50, 10, 0)), - }, - net_widths={"net1": 2.0, "net2": 2.0}, - ) - - assert len(run.results_by_net) == 2 - assert run.results_by_net["net1"].is_valid - assert run.results_by_net["net2"].is_valid - assert run.results_by_net["net1"].collisions == 0 - assert run.results_by_net["net2"].collisions == 0 - - -def test_route_reports_crossing_nets_without_congestion_resolution() -> None: - run = _route_problem( - netlist={ - "net1": (Port(0, 25, 0), Port(100, 25, 0)), - "net2": (Port(50, 0, 90), Port(50, 50, 90)), - }, - net_widths={"net1": 2.0, "net2": 2.0}, - max_iterations=1, - base_penalty=1.0, - warm_start_enabled=False, - ) - - assert not run.results_by_net["net1"].is_valid - assert not run.results_by_net["net2"].is_valid - assert run.results_by_net["net1"].collisions > 0 - assert run.results_by_net["net2"].collisions > 0 - - def test_route_callback_respects_requested_net_order() -> None: callback_orders: list[list[str]] = [] @@ -144,44 +103,6 @@ def test_route_callback_respects_requested_net_order() -> None: assert callback_orders == [["long", "mid", "short"]] -def test_route_callback_receives_iteration_results() -> None: - callback_results: list[dict[str, RoutingResult]] = [] - - run = _route_problem( - netlist={ - "net1": (Port(0, 0, 0), Port(10, 0, 0)), - "net2": (Port(0, 10, 0), Port(10, 10, 0)), - }, - net_widths={"net1": 2.0, "net2": 2.0}, - iteration_callback=lambda iteration, results: callback_results.append(dict(results)), - ) - - assert len(callback_results) == 1 - assert set(callback_results[0]) == {"net1", "net2"} - assert callback_results[0]["net1"].is_valid - assert callback_results[0]["net2"].is_valid - assert run.results_by_net["net1"].reached_target - assert run.results_by_net["net2"].reached_target - - -def test_route_uses_complete_initial_paths_without_rerouting() -> None: - initial_seed = _build_manual_seed([("S", 10.0), ("B", "CCW"), ("S", 10.0), ("B", "CW")]) - run = _route_problem( - netlist={"net": (Port(0, 0, 0), Port(20, 20, 0))}, - net_widths={"net": 2.0}, - bend_radii=[5.0], - max_iterations=1, - warm_start_enabled=False, - initial_paths={"net": initial_seed}, - enabled=False, - ) - - result = run.results_by_net["net"] - assert result.is_valid - assert result.reached_target - assert result.as_seed() == initial_seed - - def test_route_uses_a_partial_initial_path_on_the_first_iteration() -> None: iterations: list[int] = [] partial_seed = PathSeed((StraightSeed(length=7.0),)) @@ -202,66 +123,12 @@ def test_route_uses_a_partial_initial_path_on_the_first_iteration() -> None: assert result.reached_target assert result.outcome == "completed" assert result.as_seed().segments == (*partial_seed.segments, StraightSeed(13)) - assert run.expanded_nodes + assert run.metrics.nodes_expanded >= len(set(run.expanded_nodes)) > 0 + assert run.metrics.route_iterations == len(iterations) + assert run.metrics.iteration_reverify_calls >= 1 assert run.metrics.guidance_match_moves > 0 -def test_route_negotiated_congestion_resolution() -> None: - obs_top = Polygon([(20, 6), (30, 6), (30, 15), (20, 10)]) - obs_bottom = Polygon([(20, 4), (30, 4), (30, -15), (20, -10)]) - run = _route_problem( - bounds=(0, -40, 100, 40), - netlist={ - "net1": (Port(0, 0, 0), Port(50, 0, 0)), - "net2": (Port(0, 10, 0), Port(50, 10, 0)), - }, - net_widths={"net1": 2.0, "net2": 2.0}, - static_obstacles=(obs_top, obs_bottom), - bend_radii=(5.0, 10.0), - max_iterations=10, - base_penalty=1000.0, - ) - - assert run.results_by_net["net1"].reached_target - assert run.results_by_net["net2"].reached_target - assert run.results_by_net["net1"].is_valid - assert run.results_by_net["net2"].is_valid - - -def test_route_refinement_reduces_locked_detour_bends() -> None: - route_a = _route_problem( - bounds=(0, -50, 100, 50), - netlist={"netA": (Port(10, 0, 0), Port(90, 0, 0))}, - net_widths={"netA": 2.0}, - bend_radii=[10.0], - enabled=False, - ) - locked_geometry = route_a.results_by_net["netA"].locked_geometry - - base_run = _route_problem( - bounds=(0, -50, 100, 50), - netlist={"netB": (Port(50, -20, 90), Port(50, 20, 90))}, - net_widths={"netB": 2.0}, - static_obstacles=locked_geometry, - bend_radii=[10.0], - enabled=False, - ) - refined_run = _route_problem( - bounds=(0, -50, 100, 50), - netlist={"netB": (Port(50, -20, 90), Port(50, 20, 90))}, - net_widths={"netB": 2.0}, - static_obstacles=locked_geometry, - bend_radii=[10.0], - enabled=True, - ) - - base_result = base_run.results_by_net["netB"] - refined_result = refined_run.results_by_net["netB"] - assert base_result.is_valid - assert refined_result.is_valid - assert _bend_count(refined_result) < _bend_count(base_result) - - def test_route_refinement_simplifies_triple_crossing_detours() -> None: detour = PathSeed( ( diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 0603a8d..74528a1 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -1,35 +1,28 @@ import sys from dataclasses import asdict, replace -from itertools import combinations -from json import dumps, loads +from json import loads import pytest -from shapely import union_all -from shapely.geometry import Point, Polygon, box, shape +from shapely.geometry import box, shape from inire import ( - Bend90Seed, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, SBendOutline, - SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, + CongestionOptions, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, RoutingResult, RoutingRunResult, + SearchOptions, StraightSeed, TopologyOptions, route, ) -from inire.constants import TOLERANCE_LINEAR 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.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 inire.tests.routing_corpus import CASE_GROUPS, automatic_options, profile_options from scripts.compare_topological_routing import ( _direct_trials, - _geometry_json, _measure as _measure_selected_mode, _mode_options, main as run_benchmarks, @@ -40,70 +33,6 @@ 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("name", ["search-comb-1x4", "search-comb-2x5-fine", "scale-field-20x16"]) -def test_column_recovery_routes_with_a_one_node_search_budget(name) -> None: - (case,) = CASE_GROUPS[name] - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - options = replace( - options, - search=replace(options.search, node_limit=1), - congestion=replace(options.congestion, max_iterations=1), - topology=replace(options.topology, seed_node_limit=1), - ) - - run = route(case.problem, options=options) - - assert run.automatic is not None - assert run.automatic.selected_planner == "column-recovery" - assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} - assert all(result.is_valid for result in run.results_by_net.values()) - - -@pytest.mark.parametrize("name", ["search-comb-3x4", "scale-field-20x16"]) -def test_column_recovery_can_skip_the_search_probe(name) -> None: - (case,) = CASE_GROUPS[name] - 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 == "column-recovery" - assert len(run.automatic.verified_net_ids) == case.routing_bound - assert run.metrics.nodes_expanded == 0 - - -@pytest.mark.parametrize("name", ["retry-holdout-stepped-roof", "retry-holdout-west-roof"]) -def test_residual_perimeter_completes_a_return_with_straight_peers(name) -> None: - (case,) = CASE_GROUPS[name] - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - options = replace(options, search=replace(options.search, node_limit=1)) - - run = route(case.problem, options=options) - - assert run.automatic is not None - assert run.automatic.selected_planner == "residual-perimeter" - assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} - assert all(len(run.results_by_net[net_id].path) == 1 for net_id in ("edge", "lower", "east")) - - @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 @@ -124,19 +53,6 @@ def test_final_dogleg_can_reuse_incumbents_from_seed_fallback(monkeypatch) -> No assert set(run.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} -def test_local_shift_plan_can_leave_one_conflicting_net_for_a_detour() -> None: - (case,) = CASE_GROUPS["stress-crossings-shared-outside-detour"] - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - - run = route(case.problem, options=options) - - assert run.automatic.selected_planner == "residual-dogleg" - assert run.metrics.nodes_expanded == 0 - assert all(result.is_valid for result in run.results_by_net.values()) - [partial] = [stage for stage in run.automatic.stages if stage.planner == "local-sbend" and stage.operation == "verify"] - assert set(partial.valid_net_ids) == {net.net_id for net in case.problem.nets if net.net_id != "outside_lower"} - - 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} @@ -160,206 +76,30 @@ def test_weighted_local_shifts_can_pack_without_verifying_alternative_placements assert seed_counts == [1] * len(case.problem.nets) -def test_expanded_corpus_uses_physical_dimensions_and_has_reference_coverage() -> None: - corpus_names = {case.name for case in CORPUS_CASES} - assert len(corpus_names) == len(CORPUS_CASES) - expanded = CASE_GROUPS["expanded"] - assert 50 <= len(expanded) <= 100 - for case in expanded: - assert case.name in corpus_names - assert case.grid_nm is not None - assert 10 <= case.grid_nm <= 1000 - assert not case.problem.initial_paths - assert len(dict(case.reference_paths)) == case.routing_bound - assert all(1000 <= net.width * case.grid_nm <= 20000 for net in case.problem.nets) - radii = (*case.options.search.bend_radii, *case.options.search.sbend_radii) - assert radii - assert all(10000 <= radius * case.grid_nm <= 100000 for radius in radii) - scaling = CASE_GROUPS["scaling"] - assert any(len(case.problem.nets) >= 200 and len(case.problem.static_obstacles) >= 200 for case in scaling) - assert any(len(case.problem.nets) < 200 <= len(case.problem.static_obstacles) for case in scaling) - assert any(len(case.problem.static_obstacles) < 200 <= len(case.problem.nets) for case in scaling) - - -def test_benchmark_json_records_the_authored_grid(tmp_path, monkeypatch) -> None: - output = tmp_path / "benchmark.json" - monkeypatch.setattr(sys, "argv", [ - "bench", "--case", "precision-sbend-single-10nm", "--profile", "corpus-regression", "--mode", "automatic", "--json", str(output), - ]) - - run_benchmarks() - - [run] = loads(output.read_text())["runs"] - assert run["grid_nm"] == 10 - assert run["options"]["search"]["sbend_radii"] == [2500] - - -@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), +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)), ) - - 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)) - - -def test_residual_dogleg_seeds_can_use_straights_longer_than_the_lattice_scan() -> None: - case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-retry-straight-decoy") - options = replace( - case.options, - search=replace(case.options.search, node_limit=25, max_straight_length=180), - congestion=replace(case.options.congestion, max_iterations=1, warm_start_enabled=False), - refinement=replace(case.options.refinement, enabled=False), - topology=TopologyOptions(mode="automatic"), - ) - - run = route(case.problem, options=options) - - assert run.automatic.selected_planner == "residual-dogleg" - assert all(run.results_by_net[net.net_id].is_valid for net in case.problem.nets) - assert any( - isinstance(move, StraightSeed) and move.length > options.search.max_straight_length - for move in run.results_by_net["trunk"].as_seed().segments - ) - - -@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 = RoutingOptions(search=SearchOptions(node_limit=500)) options = replace(options, congestion=replace(options.congestion, max_iterations=iterations)) - run_worker = _AutomaticRun._run - search_budgets = {} - callback_indices = [] + attempts = [] - 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) + 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", 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 + 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: @@ -382,51 +122,20 @@ def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None: 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: +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" - 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)] + 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"] == profile + assert payload["profile"] == "public-defaults" assert run["requested_mode"] == "automatic" options = run["options"] geometry = case.options.search @@ -440,34 +149,13 @@ def test_benchmark_profile_records_effective_options(profile, refinement, max_wi 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)) + expected_refinement = replace(defaults.refinement, enabled=True, max_windows_per_net=1) 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) + 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: @@ -485,19 +173,6 @@ def test_connectivity_screen_checks_each_net_width_and_leaves_unknown_ports_for_ 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)) @@ -510,88 +185,21 @@ def test_budgeted_retry_shares_the_cap_when_both_lock_orders_leave_connected_spa 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"), [("complex-routing-example-1", "automatic"), ("complex-routing-example-1-point-terminals", "bundle")]) -def test_unused_custom_outline_keeps_constructive_planning_available(name, mode) -> None: - (case,) = CASE_GROUPS[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()) - - -@pytest.mark.parametrize("hint", [(), (StraightSeed(2400),)]) -def test_automatic_plan_recovers_full_complex_board_with_one_supplied_hint(hint) -> None: +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(hint)}) + problem = replace(case.problem, initial_paths={"net_04": PathSeed((StraightSeed(2400),))}) options = replace( case.options, search=replace(case.options.search, node_limit=100), - topology=replace(case.options.topology, mode="automatic"), - congestion=replace(case.options.congestion, max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode="automatic"), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=replace(case.options.refinement, enabled=False), ) - result = route(problem, options=options) + run = route(problem, options=options) - assert len(result.results_by_net) == 9 - assert all(path.is_valid for path in result.results_by_net.values()) + 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: @@ -615,20 +223,6 @@ def test_point_terminal_replay_preserves_the_selected_port_headings() -> None: 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_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)) @@ -645,38 +239,6 @@ def test_bundle_first_reports_capacity_failure_and_uses_the_generic_fallback() - 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) @@ -744,48 +306,6 @@ def test_automatic_can_force_weighted_scoring_when_the_selective_pass_is_skipped 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_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) @@ -797,18 +317,6 @@ def test_port_spacing_certificate_keeps_input_order_in_mixed_width_bank() -> Non assert port_conflicts(replace(problem, nets=(nets[0], nets[2], nets[1], *nets[3:])), RoutingOptions()) == (("a", "c"), ("b", "d")) -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") @@ -825,40 +333,3 @@ def test_perimeter_residual_preserves_its_lock_and_verifies_the_layout(monkeypat 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 diff --git a/inire/tests/test_routing_fixtures.py b/inire/tests/test_routing_fixtures.py new file mode 100644 index 0000000..64f5f25 --- /dev/null +++ b/inire/tests/test_routing_fixtures.py @@ -0,0 +1,186 @@ +from dataclasses import replace +from itertools import combinations + +import pytest +from shapely import union_all +from shapely.geometry import Point, box + +from inire import Bend90Seed, RoutingRunResult, SBendSeed, StraightSeed, route +from inire.constants import TOLERANCE_LINEAR +from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES +from inire.tests.routing_benchmarks import BENCHMARK_CASES, COMPLEX_BENCHMARK_CASES, EXTERNAL_BENCHMARK_CASES +from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options, select_cases +from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES + + +_RETRY_HOLDOUT_NAMES = {case.name for case in RETRY_HOLDOUT_CASES} +_EXTERNAL_CASE_NAMES = {case.name for case in EXTERNAL_BENCHMARK_CASES} +_PLANNER_WITHOUT_SEARCH = { + "competing-detours": "paired-perimeter", + "crossing-staggered-grid": "local-sbend", + "precision-return-offset": "perimeter", + "scale-field-20x16": "column-recovery", + "search-comb-3x4": "column-recovery", + "stress-crossings-shared-outside-detour": "residual-dogleg", + "terminal-bench": "bundle-turnaround", + "terminal-bench-pair": "paired-perimeter", +} + + +@pytest.mark.routing_corpus +@pytest.mark.parametrize( + "case", + [ + pytest.param(case, id=case.name, marks=pytest.mark.retry_holdout if case.name in _RETRY_HOLDOUT_NAMES else ()) + for case in select_cases(("corpus", "retry-holdout")) + ], +) +def test_automatic_reaches_corpus_routing_bound(case) -> None: + if case.name in _EXTERNAL_CASE_NAMES: + _check_external_fixture(case) + reference_run = _check_reference_paths(case) if case.reference_paths else None + + profile = "corpus-regression" + options = automatic_options(profile_options(case, profile), profile) + callback_indices = [] + + def record_iteration(index, _results): + callback_indices.append(index) + + callback = record_iteration if case.name == "crossing-with-room" else None + run = route(case.problem, options=options, iteration_callback=callback) + + 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 + for net in case.problem.nets: + if net.net_id in verified: + result = run.results_by_net[net.net_id] + effective = result.effective_net if options.topology.infer_terminal_headings else net + assert result.path[0].start_port == effective.start + assert result.path[-1].end_port == effective.target + + if case.name in _PLANNER_WITHOUT_SEARCH: + assert run.automatic.selected_planner == _PLANNER_WITHOUT_SEARCH[case.name] + assert run.metrics.nodes_expanded == 0 + if case.name in {"competing-detours", "precision-return-offset"}: + assert not any(stage.operation == "search" for stage in run.automatic.stages) + if case.name == "crossing-staggered-grid": + assert all(sum(move.move_type == "sbend" for move in result.path) == 1 for result in run.results_by_net.values()) + if case.name == "crossing-with-room": + assert sum(stage.operation == "search" for stage in run.automatic.stages) >= 2 + assert len(callback_indices) >= 2 + assert callback_indices == list(range(run.metrics.route_iterations)) + if case.name == "stress-crossings-shared-outside-detour": + [partial] = [stage for stage in run.automatic.stages if stage.planner == "local-sbend" and stage.operation == "verify"] + assert set(partial.valid_net_ids) == verified - {"outside_lower"} + if case.name == "pic-splitter-tree-1x8-ew": + assert any(stage.policy == "direct-lookahead-hinted" for stage in run.automatic.stages) + assert run.automatic.stages[run.automatic.selected_stage].kind == "incumbent-verified" + if case.name == "fallback-custom-physical": + assert run.automatic.selected_planner == "lattice" + assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback" + assert reference_run is not None + assert run.results_by_net.keys() == reference_run.results_by_net.keys() + for net_id, result in run.results_by_net.items(): + expected = reference_run.results_by_net[net_id] + assert result.as_seed() == expected.as_seed() + assert result.locked_geometry == expected.locked_geometry + + +def test_expanded_corpus_uses_physical_dimensions_and_has_reference_coverage() -> None: + corpus_names = {case.name for case in CORPUS_CASES} + assert len(corpus_names) == len(CORPUS_CASES) + assert corpus_names.isdisjoint(case.name for case in RETRY_HOLDOUT_CASES) + expanded = CASE_GROUPS["expanded"] + assert len(expanded) >= 50 + for case in expanded: + assert case.name in corpus_names + assert case.grid_nm is not None + assert 10 <= case.grid_nm <= 1000 + assert not case.problem.initial_paths + assert len(dict(case.reference_paths)) == case.routing_bound + assert all(1000 <= net.width * case.grid_nm <= 20000 for net in case.problem.nets) + radii = (*case.options.search.bend_radii, *case.options.search.sbend_radii) + assert radii + assert all(10000 <= radius * case.grid_nm <= 100000 for radius in radii) + scaling = CASE_GROUPS["scaling"] + assert any(len(case.problem.nets) >= 200 and len(case.problem.static_obstacles) >= 200 for case in scaling) + assert any(len(case.problem.nets) < 200 <= len(case.problem.static_obstacles) for case in scaling) + assert any(len(case.problem.static_obstacles) < 200 <= len(case.problem.nets) for case in scaling) + + +def _check_reference_paths(case) -> RoutingRunResult: + 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, + search=replace(case.options.search, node_limit=0), + refinement=replace(case.options.refinement, enabled=False), + ) + run = route(problem, options=options) + + assert run.metrics.nodes_expanded == 0 + 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 + return run + + +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_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 _check_external_fixture(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) diff --git a/inire/tests/test_terminal_bench.py b/inire/tests/test_terminal_bench.py index ef0f2a6..a160e7d 100644 --- a/inire/tests/test_terminal_bench.py +++ b/inire/tests/test_terminal_bench.py @@ -1,5 +1,5 @@ from dataclasses import replace -from itertools import combinations, pairwise +from itertools import combinations import pytest import shapely @@ -7,7 +7,7 @@ from shapely import union_all from shapely.affinity import translate from shapely.geometry import box -from inire import Bend90Seed, DiagnosticsOptions, NetSpec, Port, SBendSeed, TopologyOptions, route +from inire import Bend90Seed, DiagnosticsOptions, Port, SBendSeed, TopologyOptions, route from inire.constants import TOLERANCE_LINEAR from inire.router._waypoints import export_waypoints from inire.tests.terminal_bench_lane_plan import terminal_bench_lane_problem @@ -16,49 +16,11 @@ from inire.tests.terminal_bench_scenario import ( BOARD, CLEARANCE, LENGTH_COST, - MIN_SEPARATION, - NET_WIDTH, terminal_bench_options, terminal_bench_problem, ) -def test_terminal_bench_full_board_bounded_run() -> None: - problem = terminal_bench_problem() - run = route(problem, options=terminal_bench_options(node_limit=100, max_iterations=1)) - - assert NET_WIDTH + CLEARANCE == MIN_SEPARATION - assert tuple(run.results_by_net) == tuple(f"net_{index:02d}" for index in range(9)) - assert run.results_by_net["net_03"].reached_target - for net in problem.nets: - result = run.results_by_net[net.net_id] - if not result.path: - assert not result.reached_target - continue - assert result.path[0].start_port == net.start - assert result.reached_target == (result.path[-1].end_port == net.target) - assert all(a.end_port == b.start_port for a, b in pairwise(result.path)) - - -@pytest.mark.parametrize("net_id", ["net_03", "net_04"]) -def test_terminal_bench_isolated_connection(net_id: str) -> None: - problem = terminal_bench_problem() - net = next(net for net in problem.nets if net.net_id == net_id) - run = route(replace(problem, nets=(net,)), options=terminal_bench_options(node_limit=500, max_iterations=1)) - result = run.results_by_net[net_id] - - assert result.is_valid - assert result.path[0].start_port == net.start - assert result.path[-1].end_port == net.target - board = box(*BOARD) - for component in result.path: - for shape in component.physical_geometry: - assert board.covers(shape) - assert all(shape.distance(obstacle) >= CLEARANCE for obstacle in problem.static_obstacles) - if isinstance(component.move_spec, Bend90Seed | SBendSeed): - assert component.move_spec.radius == BEND_RADIUS - - @pytest.mark.parametrize("share_bottom_passage", [False, True], ids=["single-bottom-track", "shared-bottom-passage"]) def test_terminal_bench_lane_plan_verifies_all_nine_nets(share_bottom_passage: bool) -> None: problem = terminal_bench_lane_problem(share_bottom_passage=share_bottom_passage) @@ -134,30 +96,8 @@ def test_bundle_preserves_explicit_terminal_headings_by_default() -> None: route(terminal_bench_problem(), options=options) -@pytest.mark.parametrize("mode", ["bundle", "automatic"]) -def test_bundle_and_turnaround_use_the_smallest_common_radius(mode) -> None: - options = terminal_bench_options(node_limit=1, max_iterations=1) - options = replace( - options, - search=replace(options.search, bend_radii=(BEND_RADIUS / 2, BEND_RADIUS)), - refinement=replace(options.refinement, enabled=False), - topology=TopologyOptions(mode=mode, infer_terminal_headings=(mode == "bundle")), - ) - - run = route(terminal_bench_problem(), options=options) - - assert all(result.is_valid for result in run.results_by_net.values()) - assert run.metrics.nodes_expanded == 0 - if mode == "automatic": - assert run.automatic.selected_planner == "bundle-turnaround" - for result in run.results_by_net.values(): - for move in result.as_seed().segments: - if isinstance(move, Bend90Seed | SBendSeed): - assert move.radius == BEND_RADIUS - - -@pytest.mark.parametrize("mode", ["bundle", "automatic"]) -def test_bundle_retries_the_next_common_radius_when_the_shelf_cannot_use_the_first(mode) -> None: +def test_bundle_retries_the_next_common_radius_when_the_shelf_cannot_use_the_first() -> None: + mode = 'automatic' options = terminal_bench_options(node_limit=1, max_iterations=1) radii = (BEND_RADIUS / 2, BEND_RADIUS) options = replace( @@ -179,56 +119,37 @@ def test_bundle_retries_the_next_common_radius_when_the_shelf_cannot_use_the_fir } == {BEND_RADIUS} -def test_bundle_plans_tracks_without_coincident_nets() -> None: - problem = terminal_bench_problem() - port = problem.nets[0].start - coincident = NetSpec("abutting", port, port) - options = replace(terminal_bench_options(), topology=TopologyOptions(mode="bundle", infer_terminal_headings=True)) - - run = route(replace(problem, nets=(coincident, *problem.nets)), options=options) - - assert run.results_by_net[coincident.net_id].outcome == "unroutable" - assert all(run.results_by_net[net.net_id].is_valid for net in problem.nets) - assert run.topology.seeded_net_ids == tuple(net.net_id for net in problem.nets) - - -@pytest.mark.parametrize("unsupported", ["missing-function", "old-geos"]) -def test_automatic_constructs_bundle_without_triangulation(unsupported, monkeypatch) -> None: - if unsupported == "missing-function": - monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) - else: - monkeypatch.setattr(shapely, "geos_version", (3, 9, 0)) - base = terminal_bench_options(node_limit=100, max_iterations=1) - options = replace( - base, topology=TopologyOptions(infer_terminal_headings=True), diagnostics=DiagnosticsOptions(capture_iteration_trace=True), - ) - callbacks = [] - run = route(terminal_bench_problem(), options=options, iteration_callback=lambda index, _: callbacks.append(index)) - assert len(callbacks) >= 2 - assert [entry.iteration for entry in run.iteration_trace] == callbacks[-1:] - - assert run.automatic is not None - assert len(run.automatic.verified_net_ids) == 9 - assert run.metrics.nodes_expanded == 0 - result = run.results_by_net["net_08"] - requested = next(net for net in terminal_bench_problem().nets if net.net_id == result.net_id) - assert result.path[-1].end_port.r == 180 - assert result.requested_net == requested - assert result.effective_net == replace(requested, target=replace(requested.target, r=180)) - - -def test_placement_recipes_replay_with_resolved_ports() -> None: +def test_bundle_without_triangulation_replays_with_resolved_ports(monkeypatch: pytest.MonkeyPatch) -> None: problem = terminal_bench_problem() options = replace( terminal_bench_options(node_limit=100, max_iterations=1), topology=TopologyOptions(infer_terminal_headings=True), + diagnostics=DiagnosticsOptions(capture_iteration_trace=True), ) - run = route(problem, options=options) + callbacks = [] + with monkeypatch.context() as old_geos: + old_geos.setattr(shapely, "geos_version", (3, 9, 0)) + run = route(problem, options=options, iteration_callback=lambda index, _: callbacks.append(index)) + + assert len(callbacks) >= 2 + assert [entry.iteration for entry in run.iteration_trace] == callbacks[-1:] + assert run.automatic is not None + assert set(run.automatic.verified_net_ids) == {net.net_id for net in problem.nets} assert all(result.is_valid for result in run.results_by_net.values()) + assert run.metrics.nodes_expanded == 0 + result = run.results_by_net["net_08"] + requested_net = next(net for net in problem.nets if net.net_id == result.net_id) + assert result.path[-1].end_port.r == 180 + assert result.requested_net == requested_net + assert result.effective_net == replace(requested_net, target=replace(requested_net.target, r=180)) + seeds = {key: result.as_seed() for key, result in run.results_by_net.items()} replay_options = replace( - options, search=replace(options.search, node_limit=0), topology=TopologyOptions(mode="off"), + options, + search=replace(options.search, node_limit=0), + topology=TopologyOptions(mode="off"), refinement=replace(options.refinement, enabled=False), + diagnostics=DiagnosticsOptions(), ) requested = route(replace(problem, initial_paths=seeds), options=replay_options) assert not requested.results_by_net["net_08"].reached_target diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py index 8f1b41c..c56f07f 100644 --- a/inire/tests/test_topology.py +++ b/inire/tests/test_topology.py @@ -1,7 +1,6 @@ from dataclasses import replace import pytest -from shapely.affinity import rotate, scale from shapely.geometry import LineString, Polygon, box from inire import ( @@ -13,8 +12,8 @@ from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_l from inire.tests.routing_benchmarks import DETOUR -@pytest.mark.parametrize("hint", [(), (StraightSeed(5),), (StraightSeed(680),)]) -def test_seed_mode_realizes_corridor_with_incomplete_or_invalid_hint(hint) -> None: +def test_seed_mode_recovers_a_corridor_after_an_invalid_hint() -> None: + hint = (StraightSeed(680),) problem = replace(DETOUR.problem, initial_paths={"detour": PathSeed(hint)}) options = replace( DETOUR.options, @@ -30,24 +29,13 @@ def test_seed_mode_realizes_corridor_with_incomplete_or_invalid_hint(hint) -> No assert 0 < run.metrics.nodes_expanded <= 100 -@pytest.mark.parametrize("heading", [0, 90, 180, 270]) -def test_flat_ended_straight_recovery_after_a_bend_is_cardinally_invariant(heading) -> None: - keepout = rotate(box(52.85, 25, 54, 27.2), heading, origin=(0, 0)) - board = rotate(box(38, 18, 54, 62), heading, origin=(0, 0)) - start, target = Port(40, 20, 0).rotated(heading), Port(40, 60, 180).rotated(heading) - problem = RoutingProblem(board.bounds, (NetSpec("flat", start, target),), (keepout,)) - options = RoutingOptions( - search=SearchOptions(node_limit=200, bend_radii=(10,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - assert route(problem, options=options).results_by_net["flat"].is_valid - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) -@pytest.mark.parametrize("sign", [1, -1]) +@pytest.mark.parametrize( + ('mode', 'sign'), + [ + ('off', 1), + ('guide', -1), + ], +) def test_search_infers_intermediate_sbend_offsets(mode, sign) -> None: problem = RoutingProblem((0, 0, 100, 100), (NetSpec("shift", Port(20, 50, 0), Port(56, 50 + sign * 20, 0)),), clearance=0) options = RoutingOptions( @@ -66,26 +54,6 @@ def test_search_infers_intermediate_sbend_offsets(mode, sign) -> None: assert sum(offsets) == sign * 20 -@pytest.mark.parametrize("reflection", [-1, 1]) -def test_bounded_search_revisits_turns_away_from_the_target(reflection) -> None: - start, target = Port(190, reflection * -40, 270 if reflection == 1 else 90), Port(20, reflection * -50, 0) - board = scale(box(-25, -185, 230, 0), yfact=reflection, origin=(0, 0)) - keepout = scale(box(50, -185, 187, -37), yfact=reflection, origin=(0, 0)) - problem = RoutingProblem(board.bounds, (NetSpec("detour", start, target),), (keepout,), clearance=1) - options = RoutingOptions( - search=SearchOptions(node_limit=500, min_straight_length=2, max_straight_length=40, bend_radii=(10,), sbend_radii=()), - objective=ObjectiveWeights(bend_penalty=10, danger_weight=0), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - - run = route(problem, options=options) - - assert run.results_by_net["detour"].is_valid - assert run.metrics.nodes_expanded <= 500 - - def test_small_budget_admits_a_turn_away_from_the_target() -> None: net = NetSpec("detour", Port(503, -65, 270), Port(20, -12, 180)) problem = RoutingProblem((0, -185, 555, 0), (net,), (box(50, -185, 500, -38),), clearance=1) @@ -103,28 +71,8 @@ def test_small_budget_admits_a_turn_away_from_the_target() -> None: assert run.metrics.nodes_expanded <= 10 -@pytest.mark.parametrize("with_peer", [False, True]) -def test_narrow_alternative_remains_available_with_a_shared_guide(with_peer) -> None: - narrow = NetSpec("narrow", Port(60, 110, 0), Port(740, 110, 0)) - wide = NetSpec("wide", Port(100, 500, 0), Port(150, 500, 0), 100) - nets = (narrow, wide) if with_peer else (narrow,) - problem = RoutingProblem((0, 0, 800, 600), nets, (box(300, 50, 480, 350),), clearance=6) - options = RoutingOptions( - search=SearchOptions(node_limit=500, bend_radii=(20,), sbend_radii=()), - objective=ObjectiveWeights(danger_weight=0), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="seed"), - ) - - run = route(problem, options=options) - - assert all(result.is_valid for result in run.results_by_net.values()) - - -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) @pytest.mark.parametrize("narrow_by", [0, 0.001]) -def test_offset_gate_search_uses_exact_clearance(mode, narrow_by) -> None: +def test_offset_gate_search_uses_exact_clearance(narrow_by) -> None: walls = ( box(20, 0, 26, 5 + narrow_by), box(20, 9 - narrow_by, 26, 25), box(43, 0, 49, 11 + narrow_by), box(43, 15 - narrow_by, 49, 25), @@ -136,14 +84,14 @@ def test_offset_gate_search_uses_exact_clearance(mode, narrow_by) -> None: objective=ObjectiveWeights(danger_weight=0), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode=mode), + topology=TopologyOptions(mode="guide"), ) assert route(problem, options=options).results_by_net["gate"].is_valid == (narrow_by == 0) -@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) -def test_rounded_keepout_guidance_preserves_acute_aperture(mode) -> None: +def test_rounded_keepout_guidance_preserves_acute_aperture() -> None: + mode = 'seed' keepouts = (Polygon([(35, 0), (65, 0), (50, 22.95)]), Polygon([(35, 50), (65, 50), (50, 27.05)])) problem = RoutingProblem((0, 0, 100, 50), (NetSpec("opening", Port(7, 15, 0), Port(93, 35, 0)),), keepouts, clearance=1) options = RoutingOptions( @@ -157,8 +105,8 @@ def test_rounded_keepout_guidance_preserves_acute_aperture(mode) -> None: assert route(problem, options=options).results_by_net["opening"].is_valid -@pytest.mark.parametrize("mode", ["guide", "seed"]) -def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate(mode) -> None: +def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None: + mode = 'seed' nets = (NetSpec("a", Port(16, 48, 0), Port(199, 82, 0), 4.5), NetSpec("b", Port(18, 59, 0), Port(197, 93, 0), 1.25)) walls = (box(60, 0, 67, 56.25), box(60, 74.125, 67, 118), box(125, 0, 132, 66.25), box(125, 84.125, 132, 118)) problem = RoutingProblem((0, 0, 219, 118), nets, walls, clearance=1) @@ -209,25 +157,6 @@ def test_topological_planner_finds_both_sides_of_an_obstacle() -> None: assert crossing_heights[1] >= 437 -@pytest.mark.parametrize("mode", ["guide", "seed"]) -def test_public_topological_modes_route_a_detour(mode) -> None: - options = replace(DETOUR.options, topology=TopologyOptions(mode=mode)) - problem = DETOUR.problem - run = route(problem, options=options) - - assert run.results_by_net["detour"].is_valid - assert run.topology is not None - assert run.topology.corridor_counts == (("detour", 2),) - assert run.metrics.refine_path_calls == 1 - if mode == "seed": - assert run.topology.seeded_net_ids == ("detour",) - assert 0 < run.topology.seed_nodes_expanded <= options.search.node_limit - assert all(box(*problem.bounds).covers(shape) for shape in run.results_by_net["detour"].locked_geometry) - else: - assert run.topology.seeded_net_ids == () - assert run.topology.seed_nodes_expanded == 0 - - def test_seed_mode_respects_user_paths_on_repeated_runs() -> None: existing = PathSeed((StraightSeed(140),)) problem = RoutingProblem( @@ -248,8 +177,8 @@ def test_seed_mode_respects_user_paths_on_repeated_runs() -> None: assert list(stack.world.iter_static_dilated_geometries()) == [] -@pytest.mark.parametrize("mode", ["guide", "seed"]) -def test_narrow_net_recovers_corridors_with_a_wide_peer(mode) -> None: +def test_narrow_net_recovers_corridors_with_a_wide_peer() -> None: + mode = 'seed' wide = NetSpec("wide", Port(12, 200, 0), Port(30, 200, 0), width=180) problem = replace(DETOUR.problem, nets=(*DETOUR.problem.nets, wide)) options = replace( @@ -267,48 +196,3 @@ def test_narrow_net_recovers_corridors_with_a_wide_peer(mode) -> None: if mode == "seed": assert run.topology.seeded_net_ids == ("detour",) assert run.results_by_net["detour"].is_valid - - -def test_seed_mode_routes_a_detour_between_flush_board_ports() -> None: - problem = replace(DETOUR.problem, nets=(NetSpec("detour", Port(0, 300, 0), Port(800, 300, 0)),)) - options = replace( - DETOUR.options, - search=replace(DETOUR.options.search, node_limit=100), - congestion=replace(DETOUR.options.congestion, max_iterations=1, warm_start_enabled=False), - topology=TopologyOptions(mode="seed"), - ) - run = route(problem, options=options) - - assert run.results_by_net["detour"].is_valid - assert run.topology is not None - assert run.topology.corridor_counts == (("detour", 2),) - assert run.topology.seeded_net_ids == ("detour",) - - -def test_board_edge_lead_requires_a_clear_flat_footprint() -> None: - board = box(0, 0, 100, 100) - mesh = _Mesh(board, (box(0, 48, 1, 52),), 1, 2) - assert mesh.endpoint(Port(0, 50, 0), 1, 10) is None - assert mesh.endpoint(Port(0, 0, 0), 1, 10) is None - assert mesh.endpoint(Port(0, 60, 0), 1, 10) is not None - - -def test_seed_mode_keeps_a_verified_route_when_another_net_is_partial() -> None: - problem = RoutingProblem( - bounds=(0, 0, 200, 100), - nets=( - NetSpec("barrier", Port(1, 50, 0), Port(199, 50, 0)), - NetSpec("crossing", Port(100, 10, 90), Port(100, 90, 90)), - ), - ) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10,), node_limit=100), - congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), - topology=TopologyOptions(mode="seed"), - ) - run = route(problem, options=options) - - assert run.topology is not None - assert run.topology.seeded_net_ids == ("barrier",) - assert run.results_by_net["barrier"].is_valid - assert not run.results_by_net["crossing"].is_valid diff --git a/inire/tests/test_variable_grid.py b/inire/tests/test_variable_grid.py deleted file mode 100644 index e0acd71..0000000 --- a/inire/tests/test_variable_grid.py +++ /dev/null @@ -1,71 +0,0 @@ -import unittest - -from inire.geometry.primitives import Port -from inire.model import RoutingOptions, RoutingProblem -from inire.router._astar_types import AStarContext, SearchRunConfig -from inire.router._search import route_astar -from inire.router.cost import CostEvaluator -from inire.geometry.collision import RoutingWorld - - -class TestIntegerPorts(unittest.TestCase): - def setUp(self): - self.ce = RoutingWorld(clearance=2.0) - self.cost = CostEvaluator(self.ce) - self.bounds = (0, 0, 100, 100) - - def _build_context(self) -> AStarContext: - return AStarContext( - self.cost, - RoutingProblem(bounds=self.bounds), - RoutingOptions(), - ) - - def _route(self, context: AStarContext, start: Port, target: Port): - return route_astar( - start, - target, - net_width=1.0, - context=context, - config=SearchRunConfig.from_options(context.options), - ) - - def test_route_reaches_integer_target(self): - context = self._build_context() - start = Port(0, 0, 0) - target = Port(12, 0, 0) - - path = self._route(context, start, target) - - self.assertIsNotNone(path) - last_port = path[-1].end_port - self.assertEqual(last_port.x, 12) - self.assertEqual(last_port.y, 0) - self.assertEqual(last_port.r, 0) - - def test_port_constructor_rounds_to_integer_lattice(self): - context = self._build_context() - start = Port(0.0, 0.0, 0.0) - target = Port(12.3, 0.0, 0.0) - - path = self._route(context, start, target) - - self.assertIsNotNone(path) - self.assertEqual(target.x, 12) - last_port = path[-1].end_port - self.assertEqual(last_port.x, 12) - - def test_half_step_inputs_use_integerized_targets(self): - context = self._build_context() - start = Port(0.0, 0.0, 0.0) - target = Port(7.5, 0.0, 0.0) - - path = self._route(context, start, target) - - self.assertIsNotNone(path) - self.assertEqual(target.x, 8) - last_port = path[-1].end_port - self.assertEqual(last_port.x, 8) - -if __name__ == '__main__': - unittest.main() diff --git a/inire/tests/test_visibility.py b/inire/tests/test_visibility.py index 03274d9..a2cbd2f 100644 --- a/inire/tests/test_visibility.py +++ b/inire/tests/test_visibility.py @@ -22,51 +22,6 @@ def test_corner_visibility_cache_respects_max_distance() -> None: assert any(corner[0] >= 100.0 for corner in far_corners) -def test_visibility_manager_is_lazy_until_queried() -> None: - engine = RoutingWorld(clearance=0.0) - engine.metrics = AStarMetrics() - engine.add_static_obstacle(box(10, 20, 20, 30)) - - visibility = VisibilityManager(engine) - - assert visibility.corners == [] - assert engine.metrics.total_visibility_corner_index_builds == 0 - - visibility.ensure_corner_index_current() - - assert visibility.corners - assert engine.metrics.total_visibility_corner_index_builds == 1 - - -def test_exact_corner_visibility_caches_local_queries() -> None: - engine = RoutingWorld(clearance=0.0) - engine.metrics = AStarMetrics() - engine.add_static_obstacle(box(10, 20, 20, 30)) - visibility = VisibilityManager(engine) - origin = Port(10, 20, 0) - - first = visibility.get_corner_visibility(origin, max_dist=100.0) - second = visibility.get_corner_visibility(origin, max_dist=100.0) - - assert second == first - assert engine.metrics.total_visibility_corner_index_builds == 1 - assert engine.metrics.total_visibility_point_cache_misses == 1 - assert engine.metrics.total_visibility_point_cache_hits == 1 - assert engine.metrics.total_visibility_builds == 0 - assert engine.metrics.total_visibility_corner_pairs_checked == 0 - - -def test_exact_corner_visibility_respects_fractional_distance_limits() -> None: - engine = RoutingWorld(clearance=0.0) - engine.add_static_obstacle(box(0, 0, 1, 1)) - engine.add_static_obstacle(box(-11, 0, -9.9996, 1)) - visibility = VisibilityManager(engine) - origin = Port(0, 0, 0) - - assert visibility.get_corner_visibility(origin, max_dist=9.99955) == [] - assert visibility.get_corner_visibility(origin, max_dist=9.99965) == [(-10.0, 0.0, 9.9996)] - - def test_exact_corner_visibility_accepts_only_endpoint_contact_and_scales_to_large_boards() -> None: engine = RoutingWorld(clearance=0.0) engine.add_static_obstacle(box(10, 20, 20, 30)) diff --git a/pyproject.toml b/pyproject.toml index 9f682d2..624c867 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -99,5 +99,6 @@ addopts = "-rsXx" testpaths = ["inire"] markers = [ "performance: opt-in runtime regression checks against example-like routing scenarios", - "routing_corpus: matched-budget coverage checks on the routing regression suite", + "routing_corpus: routing coverage checks on the regression corpus and retry holdouts", + "retry_holdout: routing coverage checks on the retry holdouts", ]