Keep coverage for worker options, locked retries, and route costs independent of the benchmark command-line tools.
336 lines
15 KiB
Python
336 lines
15 KiB
Python
from dataclasses import replace
|
|
from functools import partial
|
|
|
|
import pytest
|
|
import shapely
|
|
from shapely.geometry import LineString, Polygon, box
|
|
|
|
from inire import (
|
|
CongestionOptions, DiagnosticsOptions, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions,
|
|
RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, _dispatch_route, _route, route,
|
|
)
|
|
from inire.geometry.collision import RoutingWorld
|
|
from inire.router import _router, _stack
|
|
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
|
|
|
|
|
|
def test_seed_mode_recovers_a_corridor_after_an_invalid_hint() -> None:
|
|
hint = (StraightSeed(680),)
|
|
problem = replace(DETOUR.problem, initial_paths={"detour": PathSeed(hint)})
|
|
options = replace(
|
|
DETOUR.options,
|
|
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(
|
|
('mode', 'sign'),
|
|
[
|
|
('off', 1),
|
|
('guide', -1),
|
|
],
|
|
)
|
|
def test_search_infers_intermediate_sbend_offsets(mode, sign) -> None:
|
|
problem = RoutingProblem((0, 0, 100, 100), (NetSpec("shift", Port(20, 50, 0), Port(56, 50 + sign * 20, 0)),), clearance=0)
|
|
options = RoutingOptions(
|
|
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
|
|
|
|
|
|
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("narrow_by", [0, 0.001])
|
|
def test_offset_gate_search_uses_exact_clearance(narrow_by) -> None:
|
|
walls = (
|
|
box(20, 0, 26, 5 + narrow_by), box(20, 9 - narrow_by, 26, 25),
|
|
box(43, 0, 49, 11 + narrow_by), box(43, 15 - narrow_by, 49, 25),
|
|
)
|
|
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="guide"),
|
|
)
|
|
|
|
result = route(problem, options=options).results_by_net["gate"]
|
|
|
|
assert result.is_valid == (narrow_by == 0)
|
|
if narrow_by == 0:
|
|
bends = [move for move in result.as_seed().segments if isinstance(move, SBendSeed)]
|
|
assert bends == [SBendSeed(6, 10)]
|
|
|
|
|
|
def test_rounded_keepout_guidance_preserves_acute_aperture() -> None:
|
|
mode = 'seed'
|
|
keepouts = (Polygon([(35, 0), (65, 0), (50, 22.95)]), Polygon([(35, 50), (65, 50), (50, 27.05)]))
|
|
problem = RoutingProblem((0, 0, 100, 50), (NetSpec("opening", Port(7, 15, 0), Port(93, 35, 0)),), keepouts, clearance=1)
|
|
options = RoutingOptions(
|
|
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
|
|
|
|
|
|
def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
mode = 'seed'
|
|
nets = (NetSpec("a", Port(16, 48, 0), Port(199, 82, 0), 4.5), NetSpec("b", Port(18, 59, 0), Port(197, 93, 0), 1.25))
|
|
walls = (box(60, 0, 67, 56.25), box(60, 74.125, 67, 118), box(125, 0, 132, 66.25), box(125, 84.125, 132, 118))
|
|
problem = RoutingProblem((0, 0, 219, 118), nets, walls, clearance=1)
|
|
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),
|
|
)
|
|
unmodified = route(problem, options=options)
|
|
assert all(result.is_valid for result in unmodified.results_by_net.values())
|
|
|
|
route_once = _stack.route_once
|
|
|
|
def limit_guided_attempt(problem, *, options, **kwargs):
|
|
if options.topology.guide_strength:
|
|
options = replace(
|
|
options,
|
|
search=replace(options.search, node_limit=1),
|
|
topology=replace(options.topology, seed_node_limit=1),
|
|
)
|
|
return route_once(problem, options=options, **kwargs)
|
|
|
|
monkeypatch.setattr(_stack, "route_once", limit_guided_attempt)
|
|
snapshots = []
|
|
attempts = []
|
|
selected_attempts = []
|
|
run = _route(
|
|
problem, options=options,
|
|
iteration_callback=lambda index, results: snapshots.append((index, sum(result.is_valid for result in results.values()))),
|
|
run_router=partial(_dispatch_route, attempt_callback=attempts.append, selected_attempt_callback=selected_attempts.append),
|
|
)
|
|
|
|
assert all(result.is_valid for result in run.results_by_net.values())
|
|
assert snapshots == [(0, 0), (1, 0), (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
|
|
|
|
assert [attempt.topology.guide_strength for attempt in attempts] == [0.75, 0.0]
|
|
assert selected_attempts == [1]
|
|
|
|
clock = [0.0]
|
|
capture = _router.PathFinder._capture_frontier_trace
|
|
|
|
def expire_after_guided_search(self, state, results, details):
|
|
if self.context.options.topology.guide_strength:
|
|
clock[0] = state.start_time + state.timeout_s + 1
|
|
return capture(self, state, results, details)
|
|
|
|
monkeypatch.setattr(_router.time, "monotonic", lambda: clock[0])
|
|
monkeypatch.setattr(_router.PathFinder, "_capture_frontier_trace", expire_after_guided_search)
|
|
traced_options = replace(options, diagnostics=replace(options.diagnostics, capture_frontier_trace=True))
|
|
traced_run = route(problem, options=traced_options)
|
|
assert traced_run.results_by_net == run.results_by_net
|
|
assert traced_run.iteration_trace == run.iteration_trace
|
|
assert traced_run.metrics.route_iterations == run.metrics.route_iterations
|
|
assert traced_run.metrics.nodes_expanded == run.metrics.nodes_expanded
|
|
assert traced_run.metrics.timeout_events == 0
|
|
assert traced_run.metrics.diagnostic_timeout_events == 1
|
|
|
|
clock[0] = 0.0
|
|
monkeypatch.setattr(_router.PathFinder, "_capture_frontier_trace", capture)
|
|
verify_details = RoutingWorld.verify_path_details
|
|
|
|
def expire_during_component_details(self, net_id, path, **kwargs):
|
|
if kwargs.get("capture_component_conflicts"):
|
|
clock[0] = 61.0
|
|
return verify_details(self, net_id, path, **kwargs)
|
|
|
|
def limit_guided_before_retry(problem, *, options, **kwargs):
|
|
if options.topology.guide_strength:
|
|
options = replace(options, search=replace(options.search, node_limit=500), topology=replace(options.topology, seed_node_limit=500))
|
|
return route_once(problem, options=options, **kwargs)
|
|
|
|
monkeypatch.setattr(RoutingWorld, "verify_path_details", expire_during_component_details)
|
|
monkeypatch.setattr(_stack, "route_once", limit_guided_before_retry)
|
|
frontier_only = replace(options, diagnostics=DiagnosticsOptions(capture_frontier_trace=True))
|
|
traced = route(problem, options=frontier_only)
|
|
assert traced.results_by_net == run.results_by_net
|
|
assert traced.metrics.timeout_events == 0
|
|
assert traced.metrics.route_iterations == 3
|
|
|
|
|
|
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)
|
|
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
|
|
|
|
|
|
def test_small_offsets_on_a_mixed_width_board_share_the_widest_mesh(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
triangulate = shapely.constrained_delaunay_triangles
|
|
meshes = []
|
|
|
|
def record_mesh(free):
|
|
meshes.append(free)
|
|
return triangulate(free)
|
|
|
|
monkeypatch.setattr(shapely, "constrained_delaunay_triangles", record_mesh)
|
|
nets = tuple(NetSpec(str(i), Port(20, 80 + 15 * i, 0), Port(200, 81 + 15 * i, 0), 2 + i / 10) for i in range(8))
|
|
keepouts = (box(40, 10, 55, 30), box(80, 10, 95, 30))
|
|
guides = plan_corridors((0, 0, 240, 220), keepouts, nets, clearance=2, bend_radius=10, limit=2)
|
|
assert guides.keys() == {net.net_id for net in nets}
|
|
assert len(meshes) == 1
|
|
|
|
|
|
def test_seed_mode_recovers_a_narrow_guide_after_a_reserved_route_blocks_the_shared_guide(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
problem = RoutingProblem(
|
|
(0, 0, 240, 200),
|
|
(NetSpec("wide", Port(120, 60, 90), Port(120, 139, 90), 24), NetSpec("narrow", Port(40, 100, 0), Port(200, 101, 0), 2)),
|
|
(box(110, 17, 130, 59), box(110, 140, 130, 200)), clearance=1, initial_paths={"wide": PathSeed((StraightSeed(79),))},
|
|
)
|
|
options = RoutingOptions(
|
|
search=SearchOptions(node_limit=2000, bend_radii=(10,), sbend_radii=(10,), sbend_offsets=(1,)),
|
|
congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False),
|
|
objective=ObjectiveWeights(danger_weight=0, bend_penalty=20, sbend_penalty=20),
|
|
refinement=RefinementOptions(enabled=False),
|
|
topology=TopologyOptions(mode="seed", max_corridors=3, seed_node_limit=2000),
|
|
)
|
|
triangulate = shapely.constrained_delaunay_triangles
|
|
route_astar = _router.route_astar
|
|
events = []
|
|
|
|
def record_mesh(free):
|
|
events.append("mesh")
|
|
return triangulate(free)
|
|
|
|
def record_search(*args, config, **kwargs):
|
|
if config.restrict_to_corridor:
|
|
events.append("seed")
|
|
return route_astar(*args, config=config, **kwargs)
|
|
|
|
monkeypatch.setattr(shapely, "constrained_delaunay_triangles", record_mesh)
|
|
monkeypatch.setattr(_router, "route_astar", record_search)
|
|
run = route(problem, options=options)
|
|
assert all(result.is_valid for result in run.results_by_net.values())
|
|
assert run.results_by_net["wide"].as_seed() == problem.initial_paths["wide"]
|
|
assert run.topology.seeded_net_ids == ("narrow",)
|
|
assert dict(run.topology.corridor_counts)["narrow"] == 2
|
|
assert events[-3:] == ["seed", "mesh", "seed"]
|
|
|
|
def test_seed_mode_respects_user_paths_on_repeated_runs(monkeypatch: pytest.MonkeyPatch) -> 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()) == []
|
|
|
|
completed = replace(problem, initial_paths={"existing": existing, "new": existing})
|
|
|
|
def fail_on_mesh(*_args, **_kwargs):
|
|
pytest.fail("Complete verified seeds should skip corridor planning")
|
|
|
|
monkeypatch.setattr("inire.router._topology.plan_corridors", fail_on_mesh)
|
|
for mode in ("guide", "seed"):
|
|
callbacks = []
|
|
run = route(
|
|
completed, options=RoutingOptions(topology=TopologyOptions(mode=mode)),
|
|
iteration_callback=lambda index, results, callbacks=callbacks: callbacks.append((index, results)),
|
|
)
|
|
assert run.metrics.nodes_expanded == 0
|
|
assert [(index, all(result.is_valid for result in results.values())) for index, results in callbacks] == [(0, True)]
|
|
assert all(result.is_valid and result.as_seed() == existing for result in run.results_by_net.values())
|
|
|
|
|
|
def test_narrow_net_recovers_corridors_with_a_wide_peer() -> None:
|
|
mode = 'seed'
|
|
wide = NetSpec("wide", Port(12, 200, 0), Port(30, 200, 0), width=180)
|
|
problem = replace(DETOUR.problem, nets=(*DETOUR.problem.nets, wide))
|
|
options = replace(
|
|
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
|