inire/inire/tests/test_api.py
Jan Petykiewicz eac083a37d Refine routing geometry checks and streamline documentation
Report coincident terminals and unusable seeds per net, update custom bend handling and verification, and cover the revised behavior with regression tests.

Shorten the user and developer guides around reader tasks and keep the illustrated routing walkthrough and reference links easy to find.
2026-11-29 23:12:28 -08:00

2523 lines
112 KiB
Python

import importlib
from contextlib import nullcontext
from dataclasses import asdict, replace
from pickle import dumps, loads
import pytest
import shapely
from shapely.affinity import rotate, 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
from inire import (
Bend90Seed,
CongestionOptions,
DiagnosticsOptions,
NetSpec,
ObjectiveWeights,
PathSeed,
Port,
RefinementOptions,
RoutingOptions,
RoutingProblem,
SBendOutline,
SBendSeed,
SearchOptions,
StraightSeed,
TopologyOptions,
route,
)
from inire.geometry.components import Bend90, 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._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:
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})
rejected = route(problem, options=RoutingOptions(search=SearchOptions(node_limit=0, sbend_offsets=(4,)))).results_by_net[net.net_id]
assert rejected.outcome == "unroutable"
assert rejected.report.seed_error == "Initial path for 'shift' uses an S-bend offset outside sbend_offsets"
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", "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,
)
options = RoutingOptions(
search=SearchOptions(node_limit=0, **{field: ()}),
topology=TopologyOptions(mode=mode),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
)
callback_reports = []
run = route(problem, options=options, iteration_callback=lambda _, results: callback_reports.append(results["net"].report))
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.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
@pytest.mark.parametrize(("clearance", "valid"), [(0, True), (0.001, False)])
def test_search_checks_physical_clearance_after_a_local_proxy_intersection(clearance, valid) -> None:
physical = box(0, -11, 11, -9).union(box(9, -11, 11, 0))
proxy = physical.union(box(-0.0015, -10.0005, 0.0002, -9.9995))
net = NetSpec("corner", Port(20, 20, 0), Port(30, 30, 90))
keepout = box(19.999, 19.9999, 19.9995, 20.0001)
problem = RoutingProblem((0, 0, 45, 45), (net,), (keepout,), clearance=clearance)
options = RoutingOptions(
search=SearchOptions(node_limit=25, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=physical, bend_proxy_geometry=proxy),
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[net.net_id]
assert result.is_valid is valid
assert result.reached_target is valid
if valid:
assert result.as_seed() == PathSeed((Bend90Seed(10, "CCW"),))
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:
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))
problem = RoutingProblem(
(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=()),
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]
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
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_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:
with pytest.raises(ValueError, match="unit_length_cost"):
ObjectiveWeights(unit_length_cost=value)
with pytest.raises(ValueError, match="greedy_h_weight"):
SearchOptions(greedy_h_weight=value)
with pytest.raises(ValueError, match="base_penalty"):
CongestionOptions(base_penalty=value)
with pytest.raises(ValueError, match="multiplier"):
CongestionOptions(multiplier=value)
def test_public_inputs_reject_invalid_ids_and_named_options() -> None:
with pytest.raises(TypeError, match="Net ID must be a string"):
NetSpec(7, Port(0, 0, 0), Port(10, 0, 0))
with pytest.raises(ValueError, match="net_order"):
CongestionOptions(net_order="longesst")
with pytest.raises(ValueError, match="visibility_guidance"):
SearchOptions(visibility_guidance="exact")
def _sbend_strip(offset, half_width=1):
centerline = [(0, 0), (20, offset / 10), (50, 3 * offset / 4), (80, offset)]
return Polygon(
[(x, y - half_width) for x, y in centerline] + [(x, y + half_width) for x, y in reversed(centerline)],
)
def test_custom_sbend_board_admission_agrees_with_replay_and_net_order() -> None:
polygon = Polygon([(0, -1), (79.5, 39), (79.5, 41), (0, 1)])
with pytest.warns(UserWarning, match="port faces"):
outline = SBendOutline(40, 50, 2, polygon)
edge = NetSpec("edge", Port(10, 10, 0), Port(90, 50, 0))
peer = NetSpec("peer", Port(5, 70, 0), Port(85, 110, 0))
problem = RoutingProblem((0, 0, 89.75, 115), (edge,), clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=10, min_straight_length=100, bend_radii=(), sbend_radii=(50,), sbend_offsets=(40,),
sbend_outlines=(outline,)),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode="off"),
)
seed = PathSeed((SBendSeed(40, 50),))
replay_options = replace(options, search=replace(options.search, node_limit=0))
seeded = replace(problem, initial_paths={edge.net_id: seed})
replay = route(seeded, options=replay_options).results_by_net[edge.net_id]
assert replay.is_valid
for nets in ((edge,), (edge, peer), (peer, edge)):
results = route(replace(problem, nets=nets), options=options).results_by_net
assert all(result.is_valid for result in results.values())
assert results[edge.net_id].as_seed() == seed
assert results[edge.net_id].locked_geometry == replay.locked_geometry
smaller_board = (0, 0, 89.25, 115)
assert not route(replace(problem, bounds=smaller_board), options=options).results_by_net[edge.net_id].reached_target
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:
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)
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"]
replay = route(
replace(problem, initial_paths={"shift": PathSeed((SBendSeed(40, 50),))}),
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
@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:
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])
outline = SBendOutline(40, 50, 2, polygon)
net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0), width=2)
problem = RoutingProblem(
(0, 0, 100, 100), (net,), (keepout,), initial_paths={net.net_id: PathSeed((SBendSeed(40, 50),))}, clearance=clearance,
)
options = RoutingOptions(
search=SearchOptions(node_limit=0, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline,)),
topology=TopologyOptions(mode=mode),
)
callbacks = []
run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results[net.net_id]))
result = run.results_by_net[net.net_id]
assert result.locked_geometry[0].distance(keepout) > clearance
assert result.is_valid
assert result.report.terminal_error is None
assert len(callbacks) == 1
assert callbacks[0].report == result.report
active_options = replace(options, search=replace(options.search, node_limit=30))
active = route(replace(problem, initial_paths={}), options=active_options).results_by_net[net.net_id]
assert active.is_valid
assert active.as_seed() == result.as_seed()
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 test_custom_sbend_outline_rejects_duplicate_and_ambiguous_widths() -> None:
outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15))
with pytest.raises(ValueError, match="Duplicate S-bend outline"):
SearchOptions(sbend_radii=(50,), sbend_outlines=(outline, replace(outline, width=0.1 + 0.2)))
other = replace(outline, width=0.3 * (1 + 1.5e-12))
options = SearchOptions(sbend_radii=(50,), sbend_outlines=(outline, other))
with pytest.raises(ValueError, match="Ambiguous S-bend outlines"):
options.sbend_outline(40, 50, (outline.width + other.width) / 2)
@pytest.mark.parametrize("contact", ["face", "rounding", "gap", "extra_edge", "extra_point", "wide_face", "overlap"])
@pytest.mark.parametrize("heading", [0, 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":
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()
with warning:
options = RoutingOptions(search=SearchOptions(
node_limit=0, sbend_radii=(50,),
sbend_outlines=(SBendOutline(40, 50, 2, left), SBendOutline(-40, 50, 2, right)),
))
result = route(problem, options=options).results_by_net["shift"]
assert result.reached_target
first, second = result.locked_geometry
if contact in ("rounding", "gap"):
assert first.distance(second) > 0
if contact == "wide_face":
assert first.intersection(second).length == pytest.approx(4)
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:
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,)))
result = route(problem, options=options).results_by_net[net.net_id]
assert result.is_valid
assert result.as_seed() == seed
assert result.locked_geometry == (translate(polygon, 10, 10),)
@pytest.mark.parametrize(("node_limit", "circular_proxy"), [(0, False), (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)
seed = PathSeed((Bend90Seed(4, "CCW"),))
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=(4,), sbend_radii=(), bend_physical_geometry=polygon,
bend_proxy_geometry="bbox" if circular_proxy else None,
))
warning = nullcontext() if circular_proxy else pytest.warns(UserWarning, match="declared port faces of width 10")
with warning:
result = route(problem, options=options).results_by_net[net.net_id]
if circular_proxy:
assert result.report.invalid_geometry
assert "needs radius at least 5, got 4" in result.report.seed_error
else:
assert result.is_valid
assert result.as_seed() == seed
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:
outline = box(0, -11, 11, -9).union(box(9, -11, 11, 0))
net = NetSpec("bend", Port(10, 20, 0), Port(30, 40, 90), width)
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)
options = RoutingOptions(
search=SearchOptions(node_limit=node_limit, 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:
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")
seed = PathSeed((StraightSeed(20), turn, turn, StraightSeed(20)))
problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"fold": seed}, clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=0, bend_radii=(1,)),
congestion=CongestionOptions(max_iterations=1),
)
result = route(problem, options=options).results_by_net["fold"]
assert result.locked_geometry[0].intersection(result.locked_geometry[-1]).length == 20
assert result.reached_target
assert result.outcome == "colliding"
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),
)
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
@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:
nets = (
NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0)),
NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90)),
NetSpec("partial", Port(10, 80, 0), Port(90, 80, 0)),
NetSpec("unseeded", Port(10, 90, 0), Port(90, 90, 0)),
)
seeds = {net.net_id: PathSeed((StraightSeed(80),)) for net in nets[:2]}
seeds["partial"] = PathSeed((StraightSeed(40),))
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),
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)
callbacks = []
run = route(problem, options=options)
with_callback = route(problem, options=options, iteration_callback=lambda index, results: callbacks.append((index, results)))
for net in nets[:2]:
result = run.results_by_net[net.net_id]
assert result.as_seed() == seeds[net.net_id]
assert result.outcome == "colliding"
assert result.report.dynamic_collision_count == 1
assert run.results_by_net["partial"].outcome == "partial"
assert run.results_by_net["partial"].report.total_length == 40
assert run.results_by_net["partial"].report.static_collision_count == 1
assert run.results_by_net["unseeded"].outcome == "unroutable"
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
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
assert run.metrics.route_iterations == 1
assert run.metrics.verify_path_report_calls == 3
assert run.metrics.verify_static_buffer_ops == 3
assert run.metrics.verify_dynamic_exact_pair_checks == 2
assert callbacks == [(0, run.results_by_net)]
assert with_callback.results_by_net == run.results_by_net
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:
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),
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 == 12
@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:
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(
search=SearchOptions(node_limit=5, greedy_h_weight=heuristic, bend_radii=(), sbend_radii=()),
objective=ObjectiveWeights(price, 0, 0, 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["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))
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),))
problem = RoutingProblem((0, 0, 100, 100), (net, peer), initial_paths=seeds)
options = RoutingOptions(
search=SearchOptions(node_limit=node_limit),
topology=TopologyOptions(mode=mode),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
)
callbacks = []
run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results))
assert tuple(run.results_by_net) == (net.net_id, peer.net_id)
rejected = run.results_by_net[net.net_id]
assert rejected.outcome == "unroutable"
assert rejected.path == ()
assert rejected.requested_net == net
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 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:
nets = (
NetSpec("bad", Port(10, 80, 0), Port(target_x, 80, 0)),
NetSpec("peer", Port(10, 120, 0), Port(80, 120, 0)),
)
keepouts = (box(275, 75, 285, 85),) if blocked else ()
problem = RoutingProblem((0, 0, 300, 160), nets, keepouts)
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)
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"))
result = route(problem, options=options).results_by_net["return"]
assert result.report.terminal_error is None
assert result.outcome == "unroutable"
@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:
nets = (
NetSpec("first", Port(10, 20, 0), Port(40, 20, 0)),
NetSpec("second", Port(start_x, y, 0), Port(90, y, 0)),
)
seeds = {"first": PathSeed((StraightSeed(30),)), "second": PathSeed((StraightSeed(90 - start_x),))}
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)]
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 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,))})
options = RoutingOptions(
search=SearchOptions(node_limit=node_limit, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1e11,)),
topology=TopologyOptions(mode=mode),
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
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
@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")))
def test_lattice_partial_path_leaves_crossing_net_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)
options = RoutingOptions(
search=SearchOptions(node_limit=0),
congestion=CongestionOptions(max_iterations=1),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
topology=TopologyOptions(mode="off"),
)
run = route(problem, options=options)
assert run.results_by_net["blocked"].report.static_collision_count == 1
assert run.results_by_net["through"].is_valid
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))
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=50),
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[0].routed_net_ids
assert "static" in run.iteration_trace[1].routed_net_ids
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),
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)),
)
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)
options = RoutingOptions(
search=replace(search, node_limit=0),
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
@pytest.mark.parametrize("replay", [False, True])
def test_capture_frontier_trace_preserves_route_outputs(replay) -> 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"),
)
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 {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_routing_attempts_reserve_an_index_for_a_timed_out_worker(monkeypatch) -> None:
net = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0))
problem = RoutingProblem(
(0, 0, 100, 50), (net,), initial_paths={net.net_id: PathSeed((StraightSeed(80),))},
)
options = RoutingOptions(
search=SearchOptions(node_limit=0),
topology=TopologyOptions(mode="off"),
diagnostics=DiagnosticsOptions(capture_iteration_trace=True, capture_conflict_trace=True),
)
callbacks = []
def expired(finder, state):
if finder.metrics.total_route_iterations:
state.timed_out = True
finder.metrics.total_timeout_events = 1
return state.timed_out
attempts = RoutingAttempts(lambda index, _: callbacks.append(index))
with monkeypatch.context() as patch:
patch.setattr(PathFinder, "_expired", expired)
timed_out = attempts.run(problem, options=options)
selected = attempts.run(problem, options=options)
assert timed_out.metrics.timeout_events == 1
assert attempts.metrics().route_iterations == 2
assert callbacks == [1]
assert [entry.iteration for entry in selected.iteration_trace] == [1]
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:
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._add_route(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_indexed = 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()
@pytest.mark.parametrize("during", ["preparation", "search"])
def test_worker_checks_timeout_inside_single_net_attempt(during, monkeypatch) -> 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)),))
options = RoutingOptions(
search=SearchOptions(node_limit=100),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
if during == "preparation":
def expire_during_preparation(*_args):
clock[0] = 61.0
monkeypatch.setattr(PathFinder, "_prepare_topology", expire_during_preparation)
else:
original_expand = search_module._expand_moves
def expire_during_search(*args, **kwargs):
original_expand(*args, **kwargs)
clock[0] = 61.0
monkeypatch.setattr(search_module, "_expand_moves", expire_during_search)
result = route(problem, options=options)
assert result.metrics.timeout_events == 1
assert result.metrics.nodes_expanded == int(during == "search")
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),
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