inire/inire/tests/test_pathfinder.py
Jan Petykiewicz fd6f96f341 Name collision-index additions by their inputs
Use add_route for route components and add_path_geometry for prepared polygons. Update the router, tests, and index helpers to use those names.
2026-11-29 19:12:15 -08:00

338 lines
13 KiB
Python

import pytest
from shapely.geometry import box
import inire.router._router as router_module
from inire import (
CongestionOptions,
DiagnosticsOptions,
NetSpec,
ObjectiveWeights,
RefinementOptions,
RoutingOptions,
RoutingProblem,
SearchOptions,
)
from inire.geometry.collision import RoutingWorld
from inire.geometry.components import Bend90, Straight
from inire.geometry.primitives import Port
from inire.results import RoutingResult
from inire.router._astar_types import AStarContext
from inire.router._router import PathFinder
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
DEFAULT_BOUNDS = (0, 0, 100, 100)
_PROBLEM_FIELDS = set(RoutingProblem.__dataclass_fields__) - {"bounds", "nets"}
_SEARCH_FIELDS = set(SearchOptions.__dataclass_fields__)
_CONGESTION_FIELDS = set(CongestionOptions.__dataclass_fields__)
_REFINEMENT_FIELDS = set(RefinementOptions.__dataclass_fields__)
_DIAGNOSTICS_FIELDS = set(DiagnosticsOptions.__dataclass_fields__)
_OBJECTIVE_FIELDS = set(ObjectiveWeights.__dataclass_fields__)
def _request_nets(
netlist: dict[str, tuple[Port, Port]],
net_widths: dict[str, float],
) -> tuple[NetSpec, ...]:
return tuple(
NetSpec(net_id=net_id, start=start, target=target, width=net_widths.get(net_id, 2.0))
for net_id, (start, target) in netlist.items()
)
def _build_options(**overrides: object) -> RoutingOptions:
search_overrides = {key: value for key, value in overrides.items() if key in _SEARCH_FIELDS}
congestion_overrides = {key: value for key, value in overrides.items() if key in _CONGESTION_FIELDS}
refinement_overrides = {key: value for key, value in overrides.items() if key in _REFINEMENT_FIELDS}
diagnostics_overrides = {key: value for key, value in overrides.items() if key in _DIAGNOSTICS_FIELDS}
objective_overrides = {key: value for key, value in overrides.items() if key in _OBJECTIVE_FIELDS}
return RoutingOptions(
search=SearchOptions(**search_overrides),
congestion=CongestionOptions(**congestion_overrides),
refinement=RefinementOptions(**refinement_overrides),
diagnostics=DiagnosticsOptions(**diagnostics_overrides),
objective=ObjectiveWeights(**objective_overrides),
)
def _build_context(
evaluator: CostEvaluator,
*,
bounds: tuple[float, float, float, float],
nets: tuple[NetSpec, ...] = (),
**request_overrides: object,
) -> AStarContext:
problem_overrides = {key: value for key, value in request_overrides.items() if key in _PROBLEM_FIELDS}
option_overrides = {key: value for key, value in request_overrides.items() if key not in _PROBLEM_FIELDS}
return AStarContext(
evaluator,
RoutingProblem(bounds=bounds, nets=nets, **problem_overrides),
_build_options(**option_overrides),
)
def _build_pathfinder(
evaluator: CostEvaluator,
*,
netlist: dict[str, tuple[Port, Port]],
net_widths: dict[str, float],
bounds: tuple[float, float, float, float] = DEFAULT_BOUNDS,
metrics=None,
**request_overrides: object,
) -> PathFinder:
return PathFinder(
_build_context(
evaluator,
bounds=bounds,
nets=_request_nets(netlist, net_widths),
**request_overrides,
),
metrics=metrics,
)
def _build_manual_path(start: Port, width: float, clearance: float, steps: list[tuple[str, float | str]]) -> list:
path = []
curr = start
dilation = clearance / 2.0
for kind, value in steps:
if kind == "B":
comp = Bend90.generate(curr, 5.0, width, value, dilation=dilation)
else:
comp = Straight.generate(curr, value, width, dilation=dilation)
path.append(comp)
curr = comp.end_port
return path
@pytest.mark.parametrize("search_raises", [False, True], ids=["success", "exception"])
def test_frontier_replay_restores_installed_path_and_metrics(monkeypatch: pytest.MonkeyPatch, search_raises: bool) -> None:
world = RoutingWorld(clearance=2.0)
danger_map = DangerMap(bounds=DEFAULT_BOUNDS)
finder = _build_pathfinder(
CostEvaluator(world, danger_map),
netlist={"replayed": (Port(10, 20, 0), Port(90, 20, 0)), "other": (Port(10, 40, 0), Port(90, 40, 0))},
net_widths={},
warm_start_enabled=False,
)
state = finder._prepare_state()
for net_id, net in state.net_specs.items():
path = (Straight.generate(net.start, 80, net.width, dilation=world.clearance / 2),)
state.results[net_id] = RoutingResult(net_id, path, reached_target=True)
finder._add_route(net_id, path)
original_metrics = finder.metrics
original_snapshot = original_metrics.snapshot()
original_bounds = sorted(world.iter_dynamic_path_bounds(DEFAULT_BOUNDS))
other_bounds = [component.bounds for component in state.results["other"].path[0].collision_geometry]
hotspot_bounds = ((30.0, 15.0, 50.0, 25.0),)
def replay_search(_start, _target, _width, *, context, metrics, net_id, config):
assert net_id == "replayed"
assert config.frontier_trace.hotspot_bounds == hotspot_bounds
assert list(world.iter_dynamic_path_bounds(DEFAULT_BOUNDS)) == other_bounds
assert metrics is context.metrics is world.metrics is danger_map.metrics
assert metrics is not original_metrics
metrics.total_nodes_expanded += 1
if search_raises:
raise RuntimeError("frontier search failed")
monkeypatch.setattr(router_module, "route_astar", replay_search)
result = state.results["replayed"]
if search_raises:
with pytest.raises(RuntimeError, match="frontier search failed"):
finder._capture_single_frontier_trace(state, result.net_id, result, hotspot_bounds)
else:
trace = finder._capture_single_frontier_trace(state, result.net_id, result, hotspot_bounds)
assert trace.net_id == result.net_id
assert trace.hotspot_bounds == hotspot_bounds
assert finder.metrics is finder.context.metrics is world.metrics is danger_map.metrics is original_metrics
assert original_metrics.snapshot() == original_snapshot
assert sorted(world.iter_dynamic_path_bounds(DEFAULT_BOUNDS)) == original_bounds
def test_failed_greedy_warm_start_releases_obstacles(monkeypatch: pytest.MonkeyPatch) -> None:
world = RoutingWorld(clearance=2.0)
obstacle = box(20, 60, 40, 80)
world.add_static_obstacle(obstacle)
finder = _build_pathfinder(
CostEvaluator(world),
netlist={"first": (Port(10, 20, 0), Port(90, 20, 0)), "second": (Port(10, 40, 0), Port(90, 40, 0))},
net_widths={},
max_iterations=1,
)
def interrupted_search(start, _target, width, *, net_id, **_options):
if net_id == "first":
return [Straight.generate(start, 80, width, dilation=world.clearance / 2)]
assert len(tuple(world.iter_static_geometries())) == 2
raise RuntimeError("warm start interrupted")
with monkeypatch.context() as patch:
patch.setattr(router_module, "route_astar", interrupted_search)
with pytest.raises(RuntimeError, match="warm start interrupted"):
finder.route_all()
assert tuple(world.iter_static_geometries()) == (obstacle,)
assert finder.context.static_cache_version == world.get_static_version()
assert all(result.is_valid for result in finder.route_all().values())
assert tuple(world.iter_static_geometries()) == (obstacle,)
def test_route_all_refreshes_static_caches_after_static_topology_changes() -> None:
netlist = {"net": (Port(0, 0, 0), Port(10, 10, 90))}
widths = {"net": 2.0}
def build_router() -> tuple[RoutingWorld, AStarContext, PathFinder]:
engine = RoutingWorld(clearance=2.0)
danger_map = DangerMap(bounds=(-20, -20, 60, 60))
danger_map.precompute([])
evaluator = CostEvaluator(engine, danger_map)
context = _build_context(
evaluator,
bounds=(-20, -20, 60, 60),
nets=_request_nets(netlist, widths),
bend_radii=[10.0],
max_straight_length=50.0,
node_limit=50,
warm_start_enabled=False,
max_iterations=1,
enabled=False,
)
return engine, context, PathFinder(context)
engine_auto, _context_auto, pf_auto = build_router()
assert pf_auto.route_all()["net"].is_valid
engine_auto.add_static_obstacle(box(4, 4, 8, 12))
auto_result = pf_auto.route_all()["net"]
engine_manual, context_manual, pf_manual = build_router()
assert pf_manual.route_all()["net"].is_valid
engine_manual.add_static_obstacle(box(4, 4, 8, 12))
context_manual.clear_static_caches()
manual_result = pf_manual.route_all()["net"]
assert auto_result.reached_target == manual_result.reached_target
assert auto_result.collisions == manual_result.collisions
assert auto_result.outcome == manual_result.outcome
assert [(comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in auto_result.path] == [
(comp.move_type, comp.start_port.as_tuple(), comp.end_port.as_tuple()) for comp in manual_result.path
]
@pytest.mark.parametrize("max_windows", [1, None])
def test_refine_path_handles_same_orientation_lateral_offset(max_windows: int | None) -> None:
engine = RoutingWorld(clearance=2.0)
danger_map = DangerMap(bounds=(-20, -20, 120, 120))
danger_map.precompute([])
evaluator = CostEvaluator(engine, danger_map, bend_penalty=250.0, sbend_penalty=500.0)
pf = _build_pathfinder(
evaluator,
netlist={"net": (Port(0, 0, 0), Port(60, 15, 0))},
net_widths={"net": 2.0},
bounds=(-20, -20, 120, 120),
bend_radii=[5.0, 10.0],
enabled=True,
max_windows_per_net=max_windows,
)
start = Port(0, 0, 0)
width = 2.0
path = _build_manual_path(
start,
width,
engine.clearance,
[
("B", "CCW"),
("S", 10.0),
("B", "CW"),
("S", 20.0),
("B", "CW"),
("S", 10.0),
("B", "CCW"),
("S", 10.0),
("B", "CCW"),
("S", 5.0),
("B", "CW"),
],
)
target = path[-1].end_port
refined = pf.refiner.refine_path("net", start, width, path)
assert target == Port(60, 15, 0)
assert sum(1 for comp in path if comp.move_type == "bend90") == 6
assert sum(1 for comp in refined if comp.move_type == "bend90") == 4
assert refined[-1].end_port == target
assert pf.refiner.path_cost(refined) < pf.refiner.path_cost(path)
windows = pf.context.metrics.total_refinement_windows_considered
if max_windows == 1:
assert windows == 1
else:
assert windows > 1
def test_refine_path_can_simplify_subpath_with_different_global_orientation() -> None:
engine = RoutingWorld(clearance=2.0)
danger_map = DangerMap(bounds=(-20, -20, 120, 120))
danger_map.precompute([])
evaluator = CostEvaluator(engine, danger_map, bend_penalty=250.0, sbend_penalty=500.0)
pf = _build_pathfinder(
evaluator,
netlist={"net": (Port(0, 0, 0), Port(65, 30, 90))},
net_widths={"net": 2.0},
bounds=(-20, -20, 120, 120),
bend_radii=[5.0, 10.0],
enabled=True,
)
start = Port(0, 0, 0)
width = 2.0
path = _build_manual_path(
start,
width,
engine.clearance,
[
("B", "CCW"),
("S", 10.0),
("B", "CW"),
("S", 20.0),
("B", "CW"),
("S", 10.0),
("B", "CCW"),
("S", 10.0),
("B", "CCW"),
("S", 5.0),
("B", "CW"),
("B", "CCW"),
("S", 10.0),
],
)
target = path[-1].end_port
refined = pf.refiner.refine_path("net", start, width, path)
assert target == Port(65, 30, 90)
assert sum(1 for comp in path if comp.move_type == "bend90") == 7
assert sum(1 for comp in refined if comp.move_type == "bend90") == 5
assert refined[-1].end_port == target
assert pf.refiner.path_cost(refined) < pf.refiner.path_cost(path)
def test_changed_window_checks_for_collision_with_the_unchanged_prefix() -> None:
world = RoutingWorld(clearance=2.0)
start = Port(10, -10, 90)
prefix = _build_manual_path(
start,
2.0,
world.clearance,
[("S", 30), ("B", "CCW"), ("S", 20), ("B", "CCW"), ("S", 15), ("B", "CCW"), ("S", 15)],
)
window_start = prefix[-1].end_port
target = Port(20, 0, 0)
pf = _build_pathfinder(CostEvaluator(world), netlist={"net": (start, target)}, net_widths={"net": 2.0})
nearby = Straight.generate(window_start, 5, 2.0)
crossing = Straight.generate(window_start, 20, 2.0)
assert pf.refiner._verify_changed_window("net", [nearby], prefix, [])
assert world.verify_path_report("net", [*prefix, crossing]).self_collision_count == 1
assert not pf.refiner._verify_changed_window("net", [crossing], prefix, [])