Fix routing clearance, retries, and S-bend verification

This commit is contained in:
Jan Petykiewicz 2026-11-27 21:40:53 -08:00
commit 196cd00445
12 changed files with 257 additions and 90 deletions

View file

@ -26,15 +26,15 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati
## Detailed search and congestion
- **Build and admit moves.** Weighted A* searches snapped positions and headings. Rays, visible corners, and corridor waypoints propose straight endpoints. Admission checks clearance, cost, and state dominance. To understand which endpoints a net can reach within the same node budget, start with [move generation](../inire/router/_astar_moves.py).
- **Build and admit moves.** Weighted A* searches snapped positions and headings. Rays, visible corners, and corridor waypoints propose straight endpoints. If a ray blocks a launch, a flat-ended trace scan checks for room to move. An aligned target goes directly to admission, which checks the straight's rectangular footprint for clearance. S-bends can follow each other when the configured moves permit it. Admission also checks cost and state dominance. [Move generation](../inire/router/_astar_moves.py)
- **Recheck the installed set.** The driver raises the overlap penalty when successive routes collide. After an iteration it verifies the installed paths, since a later route can collide with one completed earlier. It ranks snapshots by completed nets, then by conflicts and dynamic collisions. To see when it reroutes just the conflicting nets, read [`next_reroute_net_ids()`](../inire/router/_congestion_policy.py#L93).
- **Recheck the installed set.** The driver raises the overlap penalty when successive routes collide. After an iteration it verifies the installed paths, since a later route can collide with one completed earlier. It ranks snapshots by completed nets, then by conflicts and dynamic collisions. A narrowed retry includes every net that still fails verification. [`next_reroute_net_ids()`](../inire/router/_congestion_policy.py#L93)
- **Repair a small conflict set.** The driver returns to the best iteration and can reuse its verification when those paths are still installed and restored-stage traces are disabled. If the conflicts form separate pairs, the router can try repairing up to two of them. It holds the other paths fixed, tries both routing orders as needed, and checks proposed replacements against the installed layout. For a worked trace, [follow a late conflict](routing-diagnostics.md#follow-a-late-conflict-into-pair-local-repair).
## Geometry and refinement
Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks adjacent components for overlap and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Refinement uses the same configured bend geometry as search and seed materialization. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed.
Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks for overlap within and between components, and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Refinement uses the same configured bend geometry as search and seed materialization. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed.
At a keepout corner, a mitred clearance buffer can reach farther than the specified clearance. Verification checks the actual distance before counting these hits as collisions. For an example with a corner close to the required clearance, see the [mitred-corner test](../inire/tests/test_collision.py#L146).

View file

@ -40,7 +40,7 @@ The arrow above each red target square shows the arrival heading.
## 4. Verify the seeds and refine the layout
The first `bundle-turnaround` candidate verifies all nine nets. Automatic routing runs a worker in mode `off` for one iteration with a one-node search limit and refinement disabled. The worker materializes each seed into physical polygons, installs the paths, and rechecks the installed layout for port joins, board containment, and collisions. Every net has a complete seed, so the worker records zero A* expansions. The full coverage lets automatic routing skip its search trials. [Seeded worker setup](../inire/router/_automatic.py#L165) · [Seed installation](../inire/router/_router.py#L819) · [Physical verification](../inire/geometry/collision.py#L656)
The first `bundle-turnaround` candidate verifies all nine nets. Automatic routing runs a worker in mode `off` for one iteration with a one-node search limit and refinement disabled. The worker materializes each seed into physical polygons, installs the paths, and rechecks the installed layout for port joins, board containment, and collisions. Every net has a complete seed, so the worker records zero A* expansions. The full coverage lets automatic routing skip its search trials. [Seeded worker setup](../inire/router/_automatic.py#L165) · [Seed installation](../inire/router/_router.py#L819) · [Physical verification](../inire/geometry/collision.py#L592)
![The upper panel shows the physical paths of the first four nets in installation order. The lower panel shows all nine paths after verification.](figures/complex-routing-example-1-verification.png)

View file

@ -11,6 +11,7 @@ from inire.geometry.component_overlap import count_path_self_collisions
from inire.geometry.components import check_path_geometry, path_within_board
from inire.geometry.dynamic_path_index import DynamicPathIndex
from inire.geometry.index_helpers import grid_cell_span
from inire.geometry.primitives import rotate_cardinal
from inire.results import RoutingReport
from inire.geometry.static_obstacle_index import StaticObstacleIndex
@ -187,16 +188,6 @@ class RoutingWorld:
def has_dynamic_paths(self) -> bool:
return bool(self._dynamic_paths.geometries)
def check_move_straight_static(self, start_port: Port, length: float, net_width: float) -> bool:
reach = self.ray_cast(
start_port,
start_port.r,
max_dist=length + 0.01,
net_width=net_width,
caller="straight_static",
)
return reach < length - 0.001
def _is_in_safety_zone(
self,
geometry: Polygon,
@ -718,6 +709,37 @@ class RoutingWorld:
cache[key] = reach
return reach
def straight_reach(self, origin: Port, max_dist: float, net_width: float) -> float:
"""Find where a fixed-width, flat-ended trace first enters a keepout."""
self._ensure_static_raw_tree()
tree = self._static_obstacles.raw_tree
if tree is None:
return max_dist
dx, dy = rotate_cardinal(max_dist, 0, int(origin.r))
half_x, half_y = (0.0, net_width / 2) if dx else (net_width / 2, 0.0)
left, right = sorted((origin.x, origin.x + dx))
bottom, top = sorted((origin.y, origin.y + dy))
left, bottom, right, top = left - half_x, bottom - half_y, right + half_x, top + half_y
strip = box(left, bottom, right, top)
clearance = self.clearance
padding = clearance - TOLERANCE_LINEAR * min(1.0, clearance)
candidates = tree.query(box(left - padding, bottom - padding, right + padding, top + padding))
axis = 0 if dx else 1
start = origin.x if dx else origin.y
direction = 1 if (dx or dy) > 0 else -1
face = axis if direction > 0 else axis + 2
reach = max_dist
obstacles = tree.geometries
for index in candidates:
obstacle = obstacles[index]
keepout = obstacle.buffer(padding) if padding > 0 else obstacle
overlap = keepout.intersection(strip)
if overlap.area:
reach = min(reach, direction * (overlap.bounds[face] - start))
return reach
def _cast_static_ray(
self,
origin: Port,

View file

@ -1,5 +1,6 @@
from __future__ import annotations
from itertools import combinations
from typing import TYPE_CHECKING
from shapely.geometry import box
@ -59,14 +60,21 @@ def components_overlap(
def count_path_self_collisions(components: Sequence[ComponentResult]) -> int:
internal_collisions = 0
for component in components:
for left, right in combinations(component.physical_geometry, 2):
overlap = left.intersection(right)
# A reflected S-bend seam can contain a rounding sliver.
if overlap.area and not overlap.buffer(-TOLERANCE_LINEAR / 2).is_empty:
internal_collisions += 1
if len(components) < 2:
return 0
return internal_collisions
envelopes = [
component.physical_geometry[0] if len(component.physical_geometry) == 1 else box(*component.total_physical_bounds)
for component in components
]
index = STRtree(envelopes)
return sum(
return internal_collisions + sum(
components_overlap(component, components[other], prefer_actual=True, at_join=other == i + 1)
for i, (component, envelope) in enumerate(zip(components, envelopes, strict=True))
for other in index.query(envelope)

View file

@ -89,7 +89,6 @@ def process_move(
parent,
res,
target,
net_width,
net_id,
open_set,
closed_set,
@ -106,7 +105,6 @@ def add_node(
parent: AStarNode,
result: ComponentResult,
target: Port,
net_width: float,
net_id: str,
open_set: list[AStarNode],
closed_set: dict[tuple[int, int, int], float],
@ -145,12 +143,10 @@ def add_node(
context.metrics.total_static_safe_cache_hits += 1
else:
ce = context.cost_evaluator.collision_engine
if ce.board is not None and not path_within_board((result,), ce.board):
collision_found = True
elif move_type == "straight":
collision_found = ce.check_move_straight_static(parent_p, result.length, net_width=net_width)
else:
collision_found = ce.check_move_static(result, start_port=parent_p, end_port=end_p)
collision_found = (
(ce.board is not None and not path_within_board((result,), ce.board))
or ce.check_move_static(result, start_port=parent_p, end_port=end_p)
)
if collision_found:
context.hard_collision_set.add(cache_key)
if frontier_trace is not None:

View file

@ -10,7 +10,6 @@ from inire.geometry.sbend import sbend_grid_span
from ._astar_admission import process_move
if TYPE_CHECKING:
from inire.geometry.components import MoveKind
from inire.geometry.primitives import Port
from ._astar_types import AStarContext, AStarMetrics, AStarNode, CongestionCaches, SearchRunConfig
@ -147,16 +146,6 @@ def _visible_straight_candidates(
return sorted(tangent_candidates, reverse=True)
def _previous_move_metadata(node: AStarNode) -> tuple[MoveKind | None, float | None]:
result = node.component_result
if result is None:
return None, None
move_type = result.move_type
if move_type == "straight":
return move_type, result.length
return move_type, None
def expand_moves(
current: AStarNode,
target: Port,
@ -171,7 +160,8 @@ def expand_moves(
) -> None:
search_options = context.options.search
cp = current.port
prev_move_type, prev_straight_length = _previous_move_metadata(current)
previous = current.component_result
prev_straight_length = previous.length if previous is not None and previous.move_type == "straight" else None
dx_t = target.x - cp.x
dy_t = target.y - cp.y
dist_sq = dx_t * dx_t + dy_t * dy_t
@ -190,16 +180,10 @@ def expand_moves(
dx_local = proj_t
dy_local = perp_t
if proj_t > 0 and abs(perp_t) < 1e-6 and cp.r == target.r:
max_reach = context.cost_evaluator.collision_engine.ray_cast(
cp,
cp.r,
proj_t + 1.0,
net_width=net_width,
caller="expand_snap",
)
if max_reach >= proj_t - 0.01 and (
prev_straight_length is None or proj_t < prev_straight_length - TOLERANCE_LINEAR
collision = context.cost_evaluator.collision_engine
if (
proj_t > 0 and abs(perp_t) < TOLERANCE_LINEAR and cp.r == target.r
and (prev_straight_length is None or proj_t < prev_straight_length - TOLERANCE_LINEAR)
):
process_move(
current,
@ -216,13 +200,17 @@ def expand_moves(
(int(round(proj_t)),),
)
max_reach = context.cost_evaluator.collision_engine.ray_cast(
max_reach = collision.ray_cast(
cp,
cp.r,
search_options.max_straight_length,
net_width=net_width,
caller="expand_forward",
)
if current.parent is None and max_reach < search_options.min_straight_length:
# Radius around the ray can block a launch at an otherwise clear port face.
reach = collision.straight_reach(cp, search_options.max_straight_length, net_width)
max_reach = max(max_reach, math.floor(reach + TOLERANCE_LINEAR))
if _should_cap_straights_to_bounds(context):
max_reach = min(max_reach, _distance_to_bounds_in_heading(cp, context.problem.bounds))
candidate_lengths = [
@ -321,7 +309,7 @@ def expand_moves(
)
max_sbend_r = max(search_options.sbend_radii) if search_options.sbend_radii else 0.0
if not bend_fits_width(max_sbend_r, net_width) or prev_move_type == "sbend":
if not bend_fits_width(max_sbend_r, net_width):
return
explicit_offsets = search_options.sbend_offsets

View file

@ -97,9 +97,7 @@ def next_reroute_net_ids(
all_reached_target: bool,
has_corridors: bool,
) -> set[str]:
if all_reached_target and 0 < len(review.conflict_edges) <= 3:
return set(review.conflicting_nets)
if has_corridors:
if has_corridors or (all_reached_target and 0 < len(review.conflict_edges) <= 3):
return set(ordered_net_ids).difference(review.completed_net_ids)
return set(ordered_net_ids)

View file

@ -1,7 +1,8 @@
from __future__ import annotations
from collections import OrderedDict
from itertools import chain
from itertools import chain, pairwise
from math import ceil, floor, hypot
from time import perf_counter_ns
from typing import TYPE_CHECKING
@ -10,17 +11,62 @@ from scipy.spatial import cKDTree
from shapely.geometry import box
if TYPE_CHECKING:
from shapely.geometry import Polygon
from collections.abc import Iterator
from shapely.geometry import LinearRing, Polygon
from inire.router._astar_types import AStarMetrics
_COST_CACHE_SIZE = 100000
def _clip_segment(
start: tuple[float, float],
end: tuple[float, float],
bounds: tuple[float, float, float, float],
) -> tuple[float, float] | None:
low, high = 0.0, 1.0
for axis in (0, 1):
origin = start[axis]
step = end[axis] - origin
minimum, maximum = bounds[axis], bounds[axis + 2]
if not step:
if not minimum <= origin <= maximum:
return None
continue
enter, leave = sorted(((minimum - origin) / step, (maximum - origin) / step))
low, high = max(low, enter), min(high, leave)
return (low, high) if low <= high else None
def _sample_ring(
ring: LinearRing,
bounds: tuple[float, float, float, float],
resolution: float,
) -> Iterator[tuple[float, float]]:
distance = 0.0
next_sample = 0
last_sample = ceil(ring.length / resolution) - 1
for start, end in pairwise(ring.coords):
dx, dy = end[0] - start[0], end[1] - start[1]
length = hypot(dx, dy)
clipped = _clip_segment(start, end, bounds)
if length and clipped is not None:
low, high = clipped
first = max(next_sample, ceil((distance + low * length) / resolution))
last = min(last_sample, floor((distance + high * length) / resolution))
for index in range(first, last + 1):
fraction = (index * resolution - distance) / length
yield (start[0] + fraction * dx, start[1] + fraction * dy)
if first <= last:
next_sample = last + 1
distance += length
class DangerMap:
"""
A proximity cost evaluator using a KD-Tree of obstacle boundary points.
Scales with obstacle perimeter rather than design area.
Samples the part of the obstacle perimeter within range of the design.
"""
__slots__ = ('minx', 'miny', 'maxx', 'maxy', 'resolution', 'safety_threshold', 'k', 'tree', '_cost_cache', 'metrics')
@ -53,18 +99,13 @@ class DangerMap:
Pre-compute the proximity tree by sampling obstacle boundaries.
"""
reach = self.safety_threshold
window = box(self.minx - reach, self.miny - reach, self.maxx + reach, self.maxy + reach)
bounds = (self.minx - reach, self.miny - reach, self.maxx + reach, self.maxy + reach)
window = box(*bounds)
all_points = []
for poly in obstacles:
for ring in chain((poly.exterior,), poly.interiors):
if not window.intersects(ring):
continue
length = ring.length
dist = 0.0
while dist < length:
pt = ring.interpolate(dist)
all_points.append((pt.x, pt.y))
dist += self.resolution
if window.intersects(ring):
all_points.extend(_sample_ring(ring, bounds, self.resolution))
if all_points:
self.tree = cKDTree(numpy.array(all_points))

View file

@ -3,6 +3,7 @@ from dataclasses import replace
import pytest
import shapely
from shapely.affinity import translate
from shapely.geometry import Polygon, box
import inire
@ -24,7 +25,7 @@ from inire import (
TopologyOptions,
route,
)
from inire.geometry.components import Straight
from inire.geometry.components import SBend, Straight
from inire.geometry.collision import RoutingWorld
from inire.results import RoutingReport, RoutingResult
from inire.router._astar_types import AStarContext
@ -277,6 +278,24 @@ def test_route_verification_rejects_adjacent_component_overlap(wrong_side) -> No
assert result.report.discontinuous is wrong_side
def test_custom_sbend_reports_overlap_inside_the_component() -> None:
arc = SBend.generate(Port(0, 0, 0), 40, 50, 2).physical_geometry[0]
outline = shapely.union_all((translate(arc, yoff=-50), box(38, -32, 43, -28)))
net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0))
problem = RoutingProblem((0, 0, 160, 160), (net,), initial_paths={"shift": PathSeed((SBendSeed(40, 50),))})
options = RoutingOptions(
search=SearchOptions(bend_radii=(), sbend_radii=(50,), bend_physical_geometry=outline),
congestion=CongestionOptions(max_iterations=1),
topology=TopologyOptions(mode="off"),
)
result = route(problem, options=options).results_by_net["shift"]
assert result.outcome == "colliding"
assert result.report.self_collision_count == 1
assert not result.report.discontinuous
@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"])
@pytest.mark.parametrize(("seed_length", "grid_length"), [(0.2, 1), (19.5, 20), (19.75, 20), (20.49, 20)])
def test_fractional_straight_seed_uses_grid_length(mode, seed_length, grid_length) -> None:
@ -436,6 +455,81 @@ def test_lattice_straight_can_run_along_a_keepout_at_clearance(y, gap, valid) ->
assert route(problem, options=options).results_by_net["straight"].is_valid is valid
@pytest.mark.parametrize("mode", ["off", "guide", "seed"])
@pytest.mark.parametrize(
("obstacle", "valid"),
[(box(32, 16, 36, 24), True), (box(4, 16, 8, 24), True), (box(31.9, 16, 36, 24), False)],
)
def test_lattice_straight_uses_flat_port_faces_for_clearance(mode, obstacle, valid) -> None:
net = NetSpec("line", Port(10, 20, 0), Port(30, 20, 0))
problem = RoutingProblem((0, 0, 60, 60), (net,), (obstacle,), clearance=2)
options = RoutingOptions(
search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=()),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode=mode),
)
assert route(problem, options=options).results_by_net["line"].is_valid is valid
def test_lattice_can_launch_a_straight_before_a_bend_from_flat_port_face() -> None:
net = NetSpec("turn", Port(10, 20, 0), Port(50, 30, 90))
problem = RoutingProblem((0, 0, 90, 90), (net,), (box(4, 16, 8, 24),), clearance=2)
options = RoutingOptions(
search=SearchOptions(node_limit=100, bend_radii=(10,), sbend_radii=()),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode="off"),
)
result = route(problem, options=options).results_by_net["turn"]
assert result.is_valid
assert result.as_seed() == PathSeed((StraightSeed(30), Bend90Seed(10, "CCW")))
@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"])
def test_search_can_find_consecutive_sbends(mode) -> None:
net = NetSpec("double", Port(20, 20, 0), Port(48, 30, 0))
problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=(10,), sbend_offsets=(5,)),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode=mode),
)
result = route(problem, options=options).results_by_net["double"]
assert result.is_valid
assert result.as_seed() == PathSeed((SBendSeed(5, 10), SBendSeed(5, 10)))
def test_congestion_retry_includes_keepout_collision_alongside_peer_conflicts() -> None:
static = NetSpec("static", Port(20, 40, 0), Port(230, 40, 0))
horizontal = NetSpec("horizontal", Port(20, 150, 0), Port(230, 150, 0))
vertical = NetSpec("vertical", Port(140, 105, 90), Port(140, 235, 90))
problem = RoutingProblem(
(0, 0, 260, 260), (static, horizontal, vertical), (box(80, 20, 100, 60),), clearance=0,
initial_paths={
"static": PathSeed((StraightSeed(210),)),
"horizontal": PathSeed((StraightSeed(210),)),
"vertical": PathSeed((StraightSeed(130),)),
},
)
options = RoutingOptions(
search=SearchOptions(bend_radii=(5, 10), sbend_radii=(), node_limit=500),
congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
diagnostics=DiagnosticsOptions(capture_iteration_trace=True),
topology=TopologyOptions(mode="off"),
)
run = route(problem, options=options)
assert run.iteration_trace[0].conflict_edges == 1
assert "static" in run.iteration_trace[1].routed_net_ids
assert run.results_by_net["static"].is_valid
def test_close_net_widths_use_distinct_keepout_trees() -> None:
narrow = NetSpec("narrow", Port(10, 20, 0), Port(90, 20, 0), width=2.00001)
wide = NetSpec("wide", Port(10, 60, 0), Port(90, 60, 0), width=2.00004)

View file

@ -438,7 +438,6 @@ def test_self_collision_prunes_before_congestion_check(basic_evaluator: CostEval
parent,
parent_result,
target=Port(20, 0, 0),
net_width=2.0,
net_id="netA",
open_set=open_set,
closed_set=closed_set,
@ -466,7 +465,6 @@ def test_closed_set_dominance_prunes_before_congestion_check(basic_evaluator: Co
root,
result,
target=Port(20, 0, 0),
net_width=2.0,
net_id="netA",
open_set=open_set,
closed_set=closed_set,
@ -495,7 +493,6 @@ def test_closed_set_keeps_cheaper_weighted_or_guided_move(length_weight, guidanc
root,
move,
target=Port(20, 0, 0),
net_width=2.0,
net_id="netA",
open_set=open_set,
closed_set={move.end_port.as_tuple(): 5.0},
@ -523,7 +520,6 @@ def test_no_dynamic_paths_skips_congestion_check(basic_evaluator: CostEvaluator)
root,
result,
target=Port(20, 0, 0),
net_width=2.0,
net_id="netA",
open_set=open_set,
closed_set=closed_set,
@ -554,7 +550,6 @@ def test_guidance_seed_matching_move_reduces_cost_and_advances_seed_index(
root,
result,
target=Port(20, 0, 0),
net_width=2.0,
net_id="netA",
open_set=open_set,
closed_set=closed_set,
@ -573,7 +568,6 @@ def test_guidance_seed_matching_move_reduces_cost_and_advances_seed_index(
AStarNode(Port(0, 0, 0), 0.0, 0.0),
result,
target=Port(20, 0, 0),
net_width=2.0,
net_id="netA",
open_set=unguided_open_set,
closed_set={},
@ -614,7 +608,6 @@ def test_guidance_seed_bend90_keeps_full_bonus(
root,
result,
target=Port(10, 10, 90),
net_width=2.0,
net_id="netA",
open_set=open_set,
closed_set={},
@ -633,7 +626,6 @@ def test_guidance_seed_bend90_keeps_full_bonus(
AStarNode(Port(0, 0, 0), 0.0, 0.0),
result,
target=Port(10, 10, 90),
net_width=2.0,
net_id="netA",
open_set=unguided_open_set,
closed_set={},

View file

@ -52,7 +52,8 @@ def test_reroute_plan_caps_only_heavy_nets_in_the_final_conflict_regime() -> Non
def test_next_reroute_nets_respect_reached_targets_and_corridors() -> None:
ordered = ("a", "b", "c", "d")
review = IterationReview({"a", "b"}, {("a", "b")}, {"d"}, 2)
assert next_reroute_net_ids(ordered, review, all_reached_target=True, has_corridors=True) == {"a", "b"}
assert next_reroute_net_ids(ordered, review, all_reached_target=True, has_corridors=True) == {"a", "b", "c"}
assert next_reroute_net_ids(ordered, review, all_reached_target=True, has_corridors=False) == {"a", "b", "c"}
assert next_reroute_net_ids(ordered, review, all_reached_target=False, has_corridors=True) == {"a", "b", "c"}
assert next_reroute_net_ids(ordered, review, all_reached_target=False, has_corridors=False) == set(ordered)

View file

@ -1,3 +1,6 @@
from math import ceil
from numpy.testing import assert_allclose
from shapely.geometry import Polygon, box
from inire.geometry.collision import RoutingWorld
from inire.geometry.primitives import Port
@ -109,3 +112,27 @@ def test_danger_map_skips_distant_rings_and_keeps_nearby_exteriors_and_holes() -
assert danger.get_cost(20, 10) > 0
assert danger.get_cost(0, 10) > 0
assert danger.get_cost(10, 10) == 0
def test_danger_map_clips_sampling_without_restarting_spacing_on_diagonal_edges() -> None:
obstacle = Polygon([(-13, 6), (13, -9), (30, 19), (8, 26)])
spacing = 2.75
danger = DangerMap((0, 0, 20, 20), resolution=spacing, safety_threshold=2)
window = box(-2, -2, 22, 22)
ring = obstacle.exterior
original = [ring.interpolate(i * spacing) for i in range(ceil(ring.length / spacing))]
expected = sorted((point.x, point.y) for point in original if window.covers(point))
danger.precompute([obstacle])
assert danger.tree is not None
assert_allclose(sorted(map(tuple, danger.tree.data)), expected, atol=1e-12)
def test_danger_map_samples_only_the_nearby_edge_of_a_large_keepout() -> None:
danger = DangerMap((0, 0, 100, 100))
danger.precompute([box(90, 20, 100_090, 100_020)])
assert danger.tree is not None
assert danger.tree.n < 30
assert danger.get_cost(85, 40) == 0.04