inire/inire/tests/test_topology.py

314 lines
14 KiB
Python

from dataclasses import replace
import pytest
from shapely.affinity import rotate, scale
from shapely.geometry import LineString, Polygon, box
from inire import (
CongestionOptions, DiagnosticsOptions, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions,
RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route,
)
from inire.router._stack import build_routing_stack
from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_lane_assignments, plan_corridors
from inire.tests.routing_benchmarks import DETOUR
@pytest.mark.parametrize("hint", [(), (StraightSeed(5),), (StraightSeed(680),)])
def test_seed_mode_realizes_corridor_with_incomplete_or_invalid_hint(hint) -> None:
problem = replace(DETOUR.problem, initial_paths={"detour": PathSeed(hint)})
options = replace(
DETOUR.options,
search=replace(DETOUR.options.search, node_limit=100),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="seed"),
)
run = route(problem, options=options)
assert run.results_by_net["detour"].is_valid
assert 0 < run.metrics.nodes_expanded <= 100
@pytest.mark.parametrize("heading", [0, 90, 180, 270])
def test_flat_ended_straight_recovery_after_a_bend_is_cardinally_invariant(heading) -> None:
keepout = rotate(box(52.85, 25, 54, 27.2), heading, origin=(0, 0))
board = rotate(box(38, 18, 54, 62), heading, origin=(0, 0))
start, target = Port(40, 20, 0).rotated(heading), Port(40, 60, 180).rotated(heading)
problem = RoutingProblem(board.bounds, (NetSpec("flat", start, target),), (keepout,))
options = RoutingOptions(
search=SearchOptions(node_limit=200, bend_radii=(10,), sbend_radii=()),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
assert route(problem, options=options).results_by_net["flat"].is_valid
@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"])
@pytest.mark.parametrize("sign", [1, -1])
def test_search_infers_intermediate_sbend_offsets(mode, sign) -> None:
problem = RoutingProblem((0, 0, 100, 100), (NetSpec("shift", Port(20, 50, 0), Port(56, 50 + sign * 20, 0)),), clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=(10,)),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode=mode),
)
result = route(problem, options=options).results_by_net["shift"]
assert result.is_valid
offsets = [segment.offset for segment in result.as_seed().segments if isinstance(segment, SBendSeed)]
assert len(offsets) == 2
assert sum(offsets) == sign * 20
@pytest.mark.parametrize("reflection", [-1, 1])
def test_bounded_search_revisits_turns_away_from_the_target(reflection) -> None:
start, target = Port(190, reflection * -40, 270 if reflection == 1 else 90), Port(20, reflection * -50, 0)
board = scale(box(-25, -185, 230, 0), yfact=reflection, origin=(0, 0))
keepout = scale(box(50, -185, 187, -37), yfact=reflection, origin=(0, 0))
problem = RoutingProblem(board.bounds, (NetSpec("detour", start, target),), (keepout,), clearance=1)
options = RoutingOptions(
search=SearchOptions(node_limit=500, min_straight_length=2, max_straight_length=40, bend_radii=(10,), sbend_radii=()),
objective=ObjectiveWeights(bend_penalty=10, danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
run = route(problem, options=options)
assert run.results_by_net["detour"].is_valid
assert run.metrics.nodes_expanded <= 500
def test_small_budget_admits_a_turn_away_from_the_target() -> None:
net = NetSpec("detour", Port(503, -65, 270), Port(20, -12, 180))
problem = RoutingProblem((0, -185, 555, 0), (net,), (box(50, -185, 500, -38),), clearance=1)
options = RoutingOptions(
search=SearchOptions(node_limit=10, min_straight_length=2, bend_radii=(10,), sbend_radii=()),
objective=ObjectiveWeights(bend_penalty=10, danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
run = route(problem, options=options)
assert run.results_by_net["detour"].is_valid
assert run.metrics.nodes_expanded <= 10
@pytest.mark.parametrize("with_peer", [False, True])
def test_narrow_alternative_remains_available_with_a_shared_guide(with_peer) -> None:
narrow = NetSpec("narrow", Port(60, 110, 0), Port(740, 110, 0))
wide = NetSpec("wide", Port(100, 500, 0), Port(150, 500, 0), 100)
nets = (narrow, wide) if with_peer else (narrow,)
problem = RoutingProblem((0, 0, 800, 600), nets, (box(300, 50, 480, 350),), clearance=6)
options = RoutingOptions(
search=SearchOptions(node_limit=500, bend_radii=(20,), sbend_radii=()),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="seed"),
)
run = route(problem, options=options)
assert all(result.is_valid for result in run.results_by_net.values())
@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"])
@pytest.mark.parametrize("narrow_by", [0, 0.001])
def test_offset_gate_search_uses_exact_clearance(mode, narrow_by) -> None:
walls = (
box(20, 0, 26, 5 + narrow_by), box(20, 9 - narrow_by, 26, 25),
box(43, 0, 49, 11 + narrow_by), box(43, 15 - narrow_by, 49, 25),
)
net = NetSpec("gate", Port(1, 7, 0), Port(60, 13, 0))
problem = RoutingProblem((0, 0, 62, 25), (net,), walls, clearance=1)
options = RoutingOptions(
search=SearchOptions(node_limit=250, min_straight_length=1, bend_radii=(), sbend_radii=(10,), sbend_offsets=(6,)),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode=mode),
)
assert route(problem, options=options).results_by_net["gate"].is_valid == (narrow_by == 0)
@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"])
def test_rounded_keepout_guidance_preserves_acute_aperture(mode) -> None:
keepouts = (Polygon([(35, 0), (65, 0), (50, 22.95)]), Polygon([(35, 50), (65, 50), (50, 27.05)]))
problem = RoutingProblem((0, 0, 100, 50), (NetSpec("opening", Port(7, 15, 0), Port(93, 35, 0)),), keepouts, clearance=1)
options = RoutingOptions(
search=SearchOptions(node_limit=200, bend_radii=(), sbend_radii=(10,), sbend_offsets=(10,)),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode=mode),
)
assert route(problem, options=options).results_by_net["opening"].is_valid
@pytest.mark.parametrize("mode", ["guide", "seed"])
def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate(mode) -> None:
nets = (NetSpec("a", Port(16, 48, 0), Port(199, 82, 0), 4.5), NetSpec("b", Port(18, 59, 0), Port(197, 93, 0), 1.25))
walls = (box(60, 0, 67, 56.25), box(60, 74.125, 67, 118), box(125, 0, 132, 66.25), box(125, 84.125, 132, 118))
problem = RoutingProblem((0, 0, 219, 118), nets, walls, clearance=1)
options = RoutingOptions(
search=SearchOptions(node_limit=1000, bend_radii=(10,), sbend_radii=(10,), sbend_offsets=(10, 12)),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=2),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode=mode),
diagnostics=DiagnosticsOptions(capture_iteration_trace=True, capture_conflict_trace=True),
)
snapshots = []
run = route(
problem, options=options,
iteration_callback=lambda index, results: snapshots.append((index, sum(result.is_valid for result in results.values()))),
)
assert all(result.is_valid for result in run.results_by_net.values())
assert snapshots == [(0, 1), (1, 1), (2, 2)]
assert [(entry.iteration, entry.completed_nets) for entry in run.iteration_trace] == [(2, 2)]
assert [entry.iteration for entry in run.conflict_trace if entry.stage == "iteration"] == [2]
assert run.conflict_trace[-1].iteration is None
def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytest.MonkeyPatch) -> None:
problem = DETOUR.problem
mesh = _Mesh(box(*problem.bounds), problem.static_obstacles, problem.nets[0].width / 2, problem.clearance)
endpoints, leads = _endpoint_access(mesh, problem.nets, 50)
paths = mesh.alternatives(*endpoints["detour"], {}, 2)
assert len(paths) == 2
def equal_cost(_self, cells, start, target, _reservations, _bend_radius):
return _Assignment(cells, (start.port, target.port), 1.0)
monkeypatch.setattr(_Mesh, "assign_lanes", equal_cost)
assignments = _plan_lane_assignments(mesh, problem.nets, endpoints, leads, bend_radius=50, limit=2, joint_net_ids=frozenset())
assert [assignment.cells for assignment in assignments["detour"]] == paths
def test_topological_planner_finds_both_sides_of_an_obstacle() -> None:
problem = DETOUR.problem
corridors = plan_corridors(problem.bounds, problem.static_obstacles, problem.nets, clearance=6, bend_radius=50, limit=2)
cross_section = LineString(((400, 0), (400, 600)))
crossing_heights = sorted(corridor.centerline.intersection(cross_section).y for corridor in corridors["detour"])
assert len(crossing_heights) == 2
assert crossing_heights[0] <= 163
assert crossing_heights[1] >= 437
@pytest.mark.parametrize("mode", ["guide", "seed"])
def test_public_topological_modes_route_a_detour(mode) -> None:
options = replace(DETOUR.options, topology=TopologyOptions(mode=mode))
problem = DETOUR.problem
run = route(problem, options=options)
assert run.results_by_net["detour"].is_valid
assert run.topology is not None
assert run.topology.corridor_counts == (("detour", 2),)
assert run.metrics.refine_path_calls == 1
if mode == "seed":
assert run.topology.seeded_net_ids == ("detour",)
assert 0 < run.topology.seed_nodes_expanded <= options.search.node_limit
assert all(box(*problem.bounds).covers(shape) for shape in run.results_by_net["detour"].locked_geometry)
else:
assert run.topology.seeded_net_ids == ()
assert run.topology.seed_nodes_expanded == 0
def test_seed_mode_respects_user_paths_on_repeated_runs() -> None:
existing = PathSeed((StraightSeed(140),))
problem = RoutingProblem(
bounds=(0, 0, 180, 100),
nets=(
NetSpec("existing", Port(20, 30, 0), Port(160, 30, 0)),
NetSpec("new", Port(20, 50, 0), Port(160, 50, 0)),
),
initial_paths={"existing": existing},
)
stack = build_routing_stack(problem, RoutingOptions(topology=TopologyOptions(mode="seed")))
for _ in range(2):
results = stack.finder.route_all()
assert all(result.is_valid for result in results.values())
assert results["existing"].as_seed() == existing
assert stack.finder.topology_report.seeded_net_ids == ("new",)
assert list(stack.world.iter_static_dilated_geometries()) == []
@pytest.mark.parametrize("mode", ["guide", "seed"])
def test_narrow_net_recovers_corridors_with_a_wide_peer(mode) -> None:
wide = NetSpec("wide", Port(12, 200, 0), Port(30, 200, 0), width=180)
problem = replace(DETOUR.problem, nets=(*DETOUR.problem.nets, wide))
options = replace(
DETOUR.options,
search=replace(DETOUR.options.search, node_limit=100),
congestion=replace(DETOUR.options.congestion, max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode=mode),
)
run = route(problem, options=options)
assert run.topology is not None
assert run.topology.corridor_counts == (("detour", 2),)
assert run.results_by_net["wide"].is_valid
if mode == "seed":
assert run.topology.seeded_net_ids == ("detour",)
assert run.results_by_net["detour"].is_valid
def test_seed_mode_routes_a_detour_between_flush_board_ports() -> None:
problem = replace(DETOUR.problem, nets=(NetSpec("detour", Port(0, 300, 0), Port(800, 300, 0)),))
options = replace(
DETOUR.options,
search=replace(DETOUR.options.search, node_limit=100),
congestion=replace(DETOUR.options.congestion, max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode="seed"),
)
run = route(problem, options=options)
assert run.results_by_net["detour"].is_valid
assert run.topology is not None
assert run.topology.corridor_counts == (("detour", 2),)
assert run.topology.seeded_net_ids == ("detour",)
def test_board_edge_lead_requires_a_clear_flat_footprint() -> None:
board = box(0, 0, 100, 100)
mesh = _Mesh(board, (box(0, 48, 1, 52),), 1, 2)
assert mesh.endpoint(Port(0, 50, 0), 1, 10) is None
assert mesh.endpoint(Port(0, 0, 0), 1, 10) is None
assert mesh.endpoint(Port(0, 60, 0), 1, 10) is not None
def test_seed_mode_keeps_a_verified_route_when_another_net_is_partial() -> None:
problem = RoutingProblem(
bounds=(0, 0, 200, 100),
nets=(
NetSpec("barrier", Port(1, 50, 0), Port(199, 50, 0)),
NetSpec("crossing", Port(100, 10, 90), Port(100, 90, 90)),
),
)
options = RoutingOptions(
search=SearchOptions(bend_radii=(10,), node_limit=100),
congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False),
topology=TopologyOptions(mode="seed"),
)
run = route(problem, options=options)
assert run.topology is not None
assert run.topology.seeded_net_ids == ("barrier",)
assert run.results_by_net["barrier"].is_valid
assert not run.results_by_net["crossing"].is_valid