inire/inire/tests/test_api.py

1550 lines
65 KiB
Python

import importlib
from dataclasses import replace
import pytest
import shapely
from shapely.affinity import translate
from shapely.geometry import Polygon, box
import inire
import inire.router._router as router_module
from inire import (
Bend90Seed,
CongestionOptions,
DiagnosticsOptions,
NetSpec,
ObjectiveWeights,
PathSeed,
Port,
RefinementOptions,
RoutingOptions,
RoutingProblem,
SBendSeed,
SearchOptions,
StraightSeed,
TopologyOptions,
route,
)
from inire.geometry.components import SBend, Straight
from inire.geometry.collision import RoutingWorld
from inire.results import RoutingReport, RoutingResult
from inire.router._astar_types import AStarContext
from inire.router._router import PathFinder, _IterationReview
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:
nets = (
NetSpec("shared", Port(10, 20, 0), Port(90, 20, 0)),
NetSpec("shared", Port(10, 70, 0), Port(90, 70, 0)),
)
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)
@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)
@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)
@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:
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,))
@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})
@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))
result = route(problem, options=options).results_by_net["wide"]
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))
def test_initial_path_must_respect_explicit_sbend_offsets() -> None:
net = NetSpec("shift", Port(10, 20, 0), Port(41, 23, 0))
seed = PathSeed((SBendSeed(3, 10), StraightSeed(20)))
problem = RoutingProblem((0, 0, 90, 70), (net,), initial_paths={"shift": seed})
with pytest.raises(ValueError, match="offset outside sbend_offsets"):
route(problem, options=RoutingOptions(search=SearchOptions(sbend_offsets=(4,))))
result = route(problem, options=RoutingOptions(search=SearchOptions(sbend_offsets=(3,)))).results_by_net["shift"]
assert result.is_valid
assert result.as_seed() == seed
@pytest.mark.parametrize("mode", ["automatic", "off"])
@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_initial_path_must_respect_configured_radii(mode, move, target, field) -> None:
problem = RoutingProblem(
(0, 0, 100, 100), (NetSpec("net", Port(20, 20, 0), target),), initial_paths={"net": PathSeed((move,))},
)
options = RoutingOptions(search=SearchOptions(**{field: ()}), topology=TopologyOptions(mode=mode))
with pytest.raises(ValueError, match=f"Initial path for 'net'.*outside {field}"):
route(problem, options=options)
def test_route_verification_rejects_geometry_that_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),
)
result = route(problem, options=options).results_by_net["bend"]
assert result.reached_target
assert not result.is_valid
assert result.report.discontinuous
def test_route_verification_rejects_point_only_join() -> 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),
)
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 not result.is_valid
assert result.report.discontinuous
@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(-4, -11, 2, -10.5)])
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(bend_radii=(10,), bend_physical_geometry=outline),
congestion=CongestionOptions(max_iterations=1),
)
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
assert result.report.discontinuous is wrong_side
def test_custom_sbend_reports_overlap_inside_the_component() -> None:
arc = SBend.generate(Port(0, 0, 0), 40, 50, 2).physical_geometry[0]
outline = shapely.union_all((translate(arc, yoff=-50), box(38, -32, 43, -28)))
net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0))
problem = RoutingProblem((0, 0, 160, 160), (net,), initial_paths={"shift": PathSeed((SBendSeed(40, 50),))})
options = RoutingOptions(
search=SearchOptions(bend_radii=(), sbend_radii=(50,), bend_physical_geometry=outline),
congestion=CongestionOptions(max_iterations=1),
topology=TopologyOptions(mode="off"),
)
result = route(problem, options=options).results_by_net["shift"]
assert result.outcome == "colliding"
assert result.report.self_collision_count == 1
assert not result.report.discontinuous
@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),
)
run = route(problem, options=options)
assert run.results_by_net["line"].is_valid
assert run.metrics.nodes_expanded == 0
def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(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,))
options = RoutingOptions(search=SearchOptions(bend_radii=(), sbend_radii=()), refinement=RefinementOptions(enabled=False))
run = route(problem, options=options)
assert run.results_by_net["line"].is_valid
assert run.automatic is not None
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:
problem = RoutingProblem(
bounds=(0, 0, 100, 100),
nets=(
NetSpec("edge", Port(10, 0, 0), Port(90, 0, 0)),
NetSpec("flush", Port(0, 50, 0), Port(100, 50, 0)),
),
initial_paths={"edge": PathSeed((StraightSeed(80),))},
)
options = RoutingOptions(
search=SearchOptions(node_limit=100),
topology=TopologyOptions(mode=mode),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
)
run = route(problem, options=options)
valid_ids = tuple(net_id for net_id, result in run.results_by_net.items() if result.is_valid)
assert valid_ids == ("flush",)
if mode == "automatic":
assert run.automatic is not None
assert run.automatic.verified_net_ids == valid_ids
selected = run.automatic.stages[run.automatic.selected_stage]
assert selected.out_of_bounds_net_ids == ("edge",)
edge = run.results_by_net["edge"]
assert edge.reached_target
assert edge.outcome == "colliding"
assert edge.report.out_of_bounds
assert edge.collisions == 1
assert not edge.report.is_valid
final = run.conflict_trace[-1]
assert final.stage == "final"
assert "edge" not in final.completed_net_ids
traced_edge = next(net for net in final.nets if net.net_id == "edge")
assert traced_edge.outcome == edge.outcome
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,
)
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)
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
def test_lattice_can_launch_a_straight_before_a_bend_from_flat_port_face() -> None:
net = NetSpec("turn", Port(10, 20, 0), Port(50, 30, 90))
problem = RoutingProblem((0, 0, 90, 90), (net,), (box(4, 16, 8, 24),), clearance=2)
options = RoutingOptions(
search=SearchOptions(node_limit=100, 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")))
@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))
vertical = NetSpec("vertical", Port(140, 105, 90), Port(140, 235, 90))
problem = RoutingProblem(
(0, 0, 260, 260), (static, horizontal, vertical), (box(80, 20, 100, 60),), clearance=0,
initial_paths={
"static": PathSeed((StraightSeed(210),)),
"horizontal": PathSeed((StraightSeed(210),)),
"vertical": PathSeed((StraightSeed(130),)),
},
)
options = RoutingOptions(
search=SearchOptions(bend_radii=(5, 10), sbend_radii=(), node_limit=500),
congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
diagnostics=DiagnosticsOptions(capture_iteration_trace=True),
topology=TopologyOptions(mode="off"),
)
run = route(problem, options=options)
assert run.iteration_trace[0].conflict_edges == 1
assert "static" in run.iteration_trace[1].routed_net_ids
assert run.results_by_net["static"].is_valid
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),
nets=(NetSpec("bend", Port(20, 20, 0), Port(31, 31, 90)),),
static_obstacles=(box(20, 28, 24, 30),),
clearance=0,
)
options = RoutingOptions(
search=SearchOptions(bend_radii=(10.25,), sbend_radii=(), node_limit=100),
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["bend"]
assert result.is_valid
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)),
)
problem = RoutingProblem((0, 0, 120, 120), nets)
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)
physical_bend = bend_proxy.union(box(-13, -11, 1, -9)).union(box(-13, -11, -11, 15))
search = SearchOptions(node_limit=20, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend)
options = RoutingOptions(
search=search,
congestion=CongestionOptions(max_iterations=1),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
topology=TopologyOptions(mode=mode),
)
run = route(problem, options=options)
left = run.results_by_net["a"]
right = run.results_by_net["b"]
assert left.locked_geometry[0].intersection(right.locked_geometry[0]).area > 0
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"])
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
attempted_limits = []
def route_with_budget(*args, config, **kwargs):
attempted_limits.append(config.node_limit)
if config.node_limit <= 500:
return None
return route_astar(*args, config=config, **kwargs)
monkeypatch.setattr(router_module, "route_astar", route_with_budget)
options = None if node_limit is None else RoutingOptions(search=SearchOptions(node_limit=node_limit))
run = route(problem, options=options)
assert run.automatic is not None
ceiling = SearchOptions().node_limit if node_limit is None else node_limit
assert attempted_limits
assert max(attempted_limits) <= ceiling
limits = [stage.node_limit for stage in run.automatic.stages]
assert min(500, ceiling) in limits
assert [limit for limit in limits if limit > 500] == ([ceiling] if ceiling > 500 else [])
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
def test_capture_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),
topology=TopologyOptions(mode="off"),
)
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_frontier_trace=True),
topology=base_options.topology,
),
)
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 {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),
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=10, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
)
evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds))
pathfinder = PathFinder(AStarContext(evaluator, problem, options))
colliding_a = RoutingResult(
net_id="netA",
path=(Straight.generate(Port(10, 50, 0), 80.0, 2.0, dilation=1.0),),
reached_target=True,
report=RoutingReport(dynamic_collision_count=1, total_length=80.0),
)
colliding_b = RoutingResult(
net_id="netB",
path=(Straight.generate(Port(50, 10, 90), 80.0, 2.0, dilation=1.0),),
reached_target=True,
report=RoutingReport(dynamic_collision_count=1, total_length=80.0),
)
completed_c = RoutingResult(
net_id="netC",
path=(Straight.generate(Port(10, 20, 0), 80.0, 2.0, dilation=1.0),),
reached_target=True,
report=RoutingReport(total_length=80.0),
)
iterations_seen: list[int] = []
reroute_sets: list[set[str]] = []
def fake_run_iteration(self, state, iteration, reroute_net_ids, iteration_callback):
_ = self
_ = iteration_callback
iterations_seen.append(iteration)
reroute_sets.append(set(reroute_net_ids))
state.results = {"netA": colliding_a, "netB": colliding_b, "netC": completed_c}
return _IterationReview(
conflicting_nets={"netA", "netB"},
conflict_edges={("netA", "netB")},
completed_net_ids={"netC"},
total_dynamic_collisions=2,
)
monkeypatch.setattr(PathFinder, "_run_iteration", fake_run_iteration)
monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: (dict(state.results), {}))
monkeypatch.setattr(PathFinder, "_run_pair_local_search", lambda self, state, review: None)
results = pathfinder.route_all()
assert iterations_seen == [0, 1]
assert reroute_sets == [{"netA", "netB", "netC"}, {"netA", "netB"}]
assert results["netA"].outcome == "colliding"
assert results["netB"].outcome == "colliding"
assert results["netC"].reached_target
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):
_ = self
_ = state
_ = iteration
route_order.append(net_id)
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"]
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_install(self, net_id, path):
_ = self
installed.append((net_id, tuple(path)))
monkeypatch.setattr(router_module, "route_astar", fail_route_astar)
monkeypatch.setattr(PathFinder, "_install_path", record_install)
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:
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))),
)
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()
for net in problem.nets:
path = (Straight.generate(net.start, 80, net.width, dilation=1.0),)
finder._install_path(net.net_id, path)
state.results[net.net_id] = RoutingResult(net.net_id, path, reached_target=True, report=world.verify_path_report(net.net_id, path))
initial_bounds = sorted(world.iter_dynamic_path_bounds(problem.bounds))
incumbent = dict(state.results)
review = _IterationReview(set(), set(), set(incumbent), 0)
attempted = []
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"):
return {"a": RoutingResult("a", incumbent["b"].path, reached_target=True), "b": incumbent["b"]}, 0
return None
monkeypatch.setattr(router_module, "search_pair_candidate", search)
assert finder._run_pair_local_target(state, ("a", "b"), review) is review
assert attempted == [("a", "b"), ("b", "a")]
assert state.results == incumbent
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
def test_route_all_restores_best_iteration_snapshot_on_timeout(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),
)
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_iterations(self, state, iteration_callback):
_ = iteration_callback
_ = self
state.results = {"netA": best_result}
pathfinder._update_best_iteration(
state,
_IterationReview(
conflicting_nets=set(),
conflict_edges=set(),
completed_net_ids={"netA"},
total_dynamic_collisions=0,
),
)
state.best_is_installed = True
state.results = {"netA": worse_result}
return True
monkeypatch.setattr(PathFinder, "_run_iterations", fake_run_iterations)
monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: (dict(state.results), {}))
results = pathfinder.route_all()
assert results["netA"].outcome == "completed"
assert evaluator.collision_engine.has_dynamic_paths()
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),
nets=(NetSpec("netA", Port(10, 0, 0), Port(90, 0, 0), width=2.0),),
)
options = RoutingOptions(search=SearchOptions(bend_radii=(10.0,)))
results_a = route(problem_a, options=options)
assert results_a.results_by_net["netA"].is_valid
problem_b = RoutingProblem(
bounds=(0, -50, 100, 50),
nets=(NetSpec("netB", Port(50, -20, 90), Port(50, 20, 90), width=2.0),),
static_obstacles=results_a.results_by_net["netA"].locked_geometry,
)
results_b = route(problem_b, options=options)
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),),
)
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