Defer geometry checks in catalog routing search

This commit is contained in:
Jan Petykiewicz 2026-12-04 09:41:08 -08:00
commit ee41dc600a
4 changed files with 228 additions and 119 deletions

View file

@ -70,19 +70,22 @@ The following constrained-case runs used an AMD Ryzen 9 5900X and a 1000-node de
| Configuration | Verified | Time | Catalog cost | | Configuration | Verified | Time | Catalog cost |
| --- | ---: | ---: | ---: | | --- | ---: | ---: | ---: |
| Native Manhattan, refinement disabled | 39 | 1.96 s | 17.9400 | | Native Manhattan, refinement disabled | 39 | 2.00 s | 17.9400 |
| Catalog Manhattan, refinement disabled | 40 | 0.54 s | 18.4426 | | Catalog Manhattan, refinement disabled | 40 | 0.25 s | 18.4426 |
| Typed, refinement disabled | 40 | 2.06 s | 10.2136 | | Typed Manhattan, refinement disabled | 40 | 1.29 s | 10.2136 |
| Typed, refinement enabled | 40 | 2.24 s | 10.0140 | | Typed Manhattan, refinement enabled | 40 | 0.99 s | 10.0140 |
| Octagonal, refinement disabled | 40 | 6.15 s | 10.2136 | | Octagonal, refinement disabled | 40 | 1.20 s | 10.2136 |
| Typed, 1 µm guidance, refinement disabled | 40 | 2.47 s | 10.2136 | | Octagonal, refinement enabled | 40 | 1.52 s | 10.2136 |
| Typed, 10 µm guidance, refinement disabled | 40 | 2.02 s | 10.2136 |
On the 39 routes verified by native Manhattan, the typed run without refinement cost 9.711. At both guidance pitches, 39 fine routes verified inside their first corridor and one completed after the explicit retry. The diagonal-savings case lowered the planted route from 591.416 µm and cost 0.076 to 481.982 µm and cost 0.06663. Profiling the octagonal run identified geometry admission and straight-span proposals as the largest search costs. Checking the output pose and cost lower bound before geometry evaluation brought the median over all 40 nets to 1.79 s. On the 39 routes verified by native Manhattan, the unrefined typed and octagonal runs each cost 9.711. Deferring geometry until a proposal reaches the front of the queue, caching straight-span projections, and indexing the obstacles in final verification reduced the unrefined octagonal median from 6.40 s at `7616b39` to 1.20 s and the number of exact geometry checks in search from 19,123 to 2,483. All 40 routes kept their verified net IDs, physical lengths, and costs.
The 40-net diagonal-savings case took 0.77 s in octagonal mode with refinement disabled. The planted route used 481.982 µm at a cost of 0.06663, compared with the cardinal reference's 591.416 µm and 0.076. The 40-net case with a native diagonal terminal pair took 0.24 s under the same settings.
At `7616b39`, typed Manhattan without refinement took 2.47 s with 1 µm guidance and 2.02 s with 10 µm guidance. At each pitch, 39 fine routes verified inside their first corridor and one completed after the explicit retry.
The `corpus-open-lanes` and `corpus-lanes` cases reuse twelve lanes from the existing scale banks. The open lanes all switched profiles and reduced the total catalog cost from 0.648 to 0.552. With the corpus keepouts present, all twelve routed and the total stayed at 0.648 because the wider guide would violate clearance. The `corpus-open-lanes` and `corpus-lanes` cases reuse twelve lanes from the existing scale banks. The open lanes all switched profiles and reduced the total catalog cost from 0.648 to 0.552. With the corpus keepouts present, all twelve routed and the total stayed at 0.648 because the wider guide would violate clearance.
The constrained run with a zero-node budget verified and completed zero routes and reported `node_limit` for all 40. Native Manhattan used 115 MiB peak resident memory on the constrained board. The refined typed run used 90 MiB. The constrained run with a zero-node budget verified and completed zero routes and reported `node_limit` for all 40. On the constrained board, native Manhattan used 116 MiB peak resident memory, unrefined octagonal used 102 MiB, and refined typed Manhattan used 91 MiB.
## Delay and independent-net retry ## Delay and independent-net retry

View file

@ -7,7 +7,6 @@ from itertools import count, islice
from math import ceil, floor, fsum, hypot, inf, isfinite from math import ceil, floor, fsum, hypot, inf, isfinite
from typing import TYPE_CHECKING, Literal from typing import TYPE_CHECKING, Literal
from shapely import box
from shapely.geometry import LineString, Point from shapely.geometry import LineString, Point
from shapely.strtree import STRtree from shapely.strtree import STRtree
@ -15,7 +14,7 @@ from inire._catalog import HEADING_STEPS, Move, Pose, StraightVariant, _require_
from inire.geometry.collision import _violates_net_clearance from inire.geometry.collision import _violates_net_clearance
from ._catalog_verify import ( from ._catalog_verify import (
compatible_join, face_reservation, meets_attachment_clearance, replay_moves, validate_attachment, _colliders, compatible_join, face_reservation, meets_attachment_clearance, replay_moves, validate_attachment,
verify_move, verify_path, wholly_in_attachment, verify_move, verify_path, wholly_in_attachment,
) )
@ -93,6 +92,13 @@ class _Arrival:
priority_penalty: float = 0.0 priority_penalty: float = 0.0
@dataclass(frozen=True, slots=True)
class _PendingMove:
spec: Move
start: Pose
previous: _Arrival | None
def _placed_path(arrival: _Arrival | None) -> tuple[Evaluation, ...]: def _placed_path(arrival: _Arrival | None) -> tuple[Evaluation, ...]:
path = [] path = []
while arrival is not None: while arrival is not None:
@ -117,6 +123,8 @@ def path_recipe(path: Sequence[Evaluation]) -> tuple[Move, ...]:
COST_TOLERANCE = 1e-12 COST_TOLERANCE = 1e-12
_TravelState = tuple[str, int] _TravelState = tuple[str, int]
_Position = tuple[int, int, int, str]
_BlockerProjection = tuple[float, float, tuple[float, ...]]
def _reverse_distances( def _reverse_distances(
@ -136,17 +144,6 @@ def _reverse_distances(
return distances return distances
def _colliders(tree: STRtree, shapes: Sequence[BaseGeometry], clearance: float) -> tuple[BaseGeometry, ...]:
if not len(tree) or not shapes:
return ()
bounds = [shape.bounds for shape in shapes]
area = box(
min(b[0] for b in bounds) - clearance, min(b[1] for b in bounds) - clearance,
max(b[2] for b in bounds) + clearance, max(b[3] for b in bounds) + clearance,
)
return tuple(tree.geometries[index] for index in tree.query(area))
def _geometry_bias(move: Evaluation, blockers: STRtree, radius: float, weight: float, length_factor: float) -> float: def _geometry_bias(move: Evaluation, blockers: STRtree, radius: float, weight: float, length_factor: float) -> float:
if not weight: if not weight:
return 0.0 return 0.0
@ -165,10 +162,13 @@ class _Proposals:
) -> None: ) -> None:
self.evaluator = evaluator self.evaluator = evaluator
self.target = target self.target = target
self.origin = start.x, start.y
self.clearance = clearance self.clearance = clearance
self.guide_points = corridor.points if corridor is not None else () self.guide_points = corridor.points if corridor is not None else ()
self.scan_steps = scan_steps self.scan_steps = scan_steps
self.blocker_bounds = tuple(shape.bounds for shape in blockers) self.blocker_bounds = tuple(shape.bounds for shape in blockers if not shape.is_empty)
self._blocker_projections: dict[_TravelState, tuple[float, tuple[int, ...], tuple[_BlockerProjection, ...]]] = {}
self._exit_alignments: dict[_TravelState, dict[int, set[int]]] = {}
self._forward_only: dict[tuple[str, int], bool] = {} self._forward_only: dict[tuple[str, int], bool] = {}
profiles = evaluator.catalog.profiles profiles = evaluator.catalog.profiles
self._straights: dict[str, list[str]] = {profile: [] for profile in profiles} self._straights: dict[str, list[str]] = {profile: [] for profile in profiles}
@ -242,29 +242,31 @@ class _Proposals:
dx, dy = self._direction dx, dy = self._direction
return dx * x + dy * y return dx * x + dy * y
def lower_bound(self, pose: Pose) -> float: def lower_bound(self, position: _Position) -> float:
residual = self.residual_cost.get((pose.profile, pose.heading), inf) x, y, heading, profile = position
dx, dy = HEADING_STEPS[pose.heading] key = profile, heading
tx, ty = self.target.x - pose.x, self.target.y - pose.y residual = self.residual_cost.get(key, inf)
if any(sign * (tx, ty)[axis] < distances.get((pose.profile, pose.heading), inf) dx, dy = HEADING_STEPS[heading]
tx, ty = self.target.x - x, self.target.y - y
if any(sign * (tx, ty)[axis] < distances.get(key, inf)
for axis, sign, distances in self.minimum_progress): for axis, sign, distances in self.minimum_progress):
return inf return inf
if self._is_forward_only(pose) and (dx * ty != dy * tx or dx * tx + dy * ty < 0): if self._is_forward_only(profile, heading) and (dx * ty != dy * tx or dx * tx + dy * ty < 0):
return inf return inf
return max(0.0, residual + self._projection(tx, ty) * self.cost_per_unit) return max(0.0, residual + self._projection(tx, ty) * self.cost_per_unit)
def _is_forward_only(self, pose: Pose) -> bool: def _is_forward_only(self, profile: str, heading: int) -> bool:
key = (pose.profile, pose.heading) key = profile, heading
if key not in self._forward_only: if key not in self._forward_only:
dx, dy = HEADING_STEPS[pose.heading] dx, dy = HEADING_STEPS[heading]
profiles = {pose.profile} profiles = {profile}
pending = [pose.profile] pending = [profile]
while pending: while pending:
profile = pending.pop() current = pending.pop()
for _, end in self.evaluator.local_moves(profile, pose.heading): for _, end in self.evaluator.local_moves(current, heading):
if (end.profile, end.heading) not in self.residual_cost: if (end.profile, end.heading) not in self.residual_cost:
continue continue
if end.heading != pose.heading or dx * end.y != dy * end.x or dx * end.x + dy * end.y < 0: if end.heading != heading or dx * end.y != dy * end.x or dx * end.x + dy * end.y < 0:
self._forward_only[key] = False self._forward_only[key] = False
return False return False
if end.profile not in profiles: if end.profile not in profiles:
@ -273,15 +275,20 @@ class _Proposals:
self._forward_only[key] = True self._forward_only[key] = True
return self._forward_only[key] return self._forward_only[key]
def destination_bound(self, start: Pose, move: Move) -> tuple[Pose, float] | None: def destination_bound(self, start: Pose, move: Move) -> tuple[_Position, float] | None:
"""Return the exact output pose and an inexpensive lower bound on move cost.""" """Return the exact output pose and an inexpensive lower bound on move cost."""
if move.steps is not None: if move.steps is not None:
dx, dy = HEADING_STEPS[start.heading] dx, dy = HEADING_STEPS[start.heading]
span = int(self.evaluator.grid.pitch) * move.steps pitch = int(self.evaluator.grid.pitch)
price = self._straight_prices[move.variant] * span * hypot(dx, dy) * self.evaluator.grid.meters_per_unit * 100 span = pitch * move.steps
return start.shifted(dx * span, dy * span), price length = move.steps * (pitch * hypot(dx, dy))
price = length * self.evaluator.grid.meters_per_unit * 100 * self._straight_prices[move.variant]
return (start.x + dx * span, start.y + dy * span, start.heading, start.profile), price
local = self._fixed_offsets[(start.profile, start.heading)].get(move) local = self._fixed_offsets[(start.profile, start.heading)].get(move)
return (local[0].shifted(start.x, start.y), local[1]) if local is not None else None if local is None:
return None
end, price = local
return (start.x + end.x, start.y + end.y, end.heading, end.profile), price
def two_turn_recipes(self, start: Pose) -> Iterator[tuple[Move, ...]]: def two_turn_recipes(self, start: Pose) -> Iterator[tuple[Move, ...]]:
"""Solve the straight spans of a two-turn route between parallel terminals.""" """Solve the straight spans of a two-turn route between parallel terminals."""
@ -356,6 +363,44 @@ class _Proposals:
for move, _ in fixed: for move, _ in fixed:
yield move yield move
def _project_blockers(
self, profile: str, heading: int, fixed: Sequence[tuple[Move, Pose]],
) -> tuple[float, tuple[int, ...], tuple[_BlockerProjection, ...]]:
key = profile, heading
if key not in self._blocker_projections:
dx, dy = HEADING_STEPS[heading]
margin = self.clearance + self.evaluator.catalog.profiles[profile].width / 2
side_reach = margin * (dx * dx + dy * dy) + max(abs(dx * end.y - dy * end.x) for _, end in fixed)
offsets = {0, *(dx * end.x + dy * end.y for _, end in fixed)}
ox, oy = self.origin
projections = []
for bx0, by0, bx1, by1 in self.blocker_bounds:
side = [dx * (y - oy) - dy * (x - ox) for x in (bx0, bx1) for y in (by0, by1)]
xs = (bx0 - margin, bx0, bx1, bx1 + margin) if dx else (ox,)
ys = (by0 - margin, by0, by1, by1 + margin) if dy else (oy,)
along = {dx * (x - ox) + dy * (y - oy) for x in xs for y in ys}
projections.append((min(side), max(side), tuple(along)))
self._blocker_projections[key] = side_reach, tuple(offsets), tuple(projections)
return self._blocker_projections[key]
def _aligned_exits(self, profile: str, heading: int, fixed: Sequence[tuple[Move, Pose]]) -> dict[int, set[int]]:
key = profile, heading
if key not in self._exit_alignments:
dx, dy = HEADING_STEPS[heading]
offsets: dict[int, set[int]] = {}
def add_exit(x: int, y: int, exit_heading: int) -> None:
ex, ey = HEADING_STEPS[exit_heading]
offset = x * ey - y * ex if dx * ey != dy * ex else dx * x + dy * y
offsets.setdefault(exit_heading, set()).add(offset)
for end in {end for _, end in fixed}:
add_exit(end.x, end.y, end.heading)
for _, following in self.evaluator.local_moves(end.profile, end.heading):
add_exit(end.x + following.x, end.y + following.y, following.heading)
self._exit_alignments[key] = offsets
return self._exit_alignments[key]
def _straight_steps( def _straight_steps(
self, start: Pose, fixed: Sequence[tuple[Move, Pose]], board_bounds: tuple[float, float, float, float], self, start: Pose, fixed: Sequence[tuple[Move, Pose]], board_bounds: tuple[float, float, float, float],
) -> list[int]: ) -> list[int]:
@ -379,41 +424,38 @@ class _Proposals:
for _, end in fixed: for _, end in fixed:
add_projection(x - start.x - end.x, y - start.y - end.y) add_projection(x - start.x - end.x, y - start.y - end.y)
def align_exit(end: Pose) -> None: for heading, offsets in self._aligned_exits(start.profile, start.heading, fixed).items():
rx, ry = tx - end.x, ty - end.y ex, ey = HEADING_STEPS[heading]
ex, ey = HEADING_STEPS[end.heading]
divisor = pitch * (dx * ey - dy * ex) divisor = pitch * (dx * ey - dy * ex)
if divisor: if divisor:
n, remainder = divmod(rx * ey - ry * ex, divisor) target = tx * ey - ty * ex
for offset in offsets:
n, remainder = divmod(target - offset, divisor)
if not remainder: if not remainder:
steps.add(n) steps.add(n)
else: else:
add_projection(rx, ry) target = dx * tx + dy * ty
for offset in offsets:
for _, end in fixed: span = (target - offset) / (pitch * magnitude)
align_exit(end) steps.update((floor(span), ceil(span)))
for _, following in self.evaluator.local_moves(end.profile, end.heading):
align_exit(following.shifted(end.x, end.y))
# Obstacle edges and the inverse displacement of fixed cells create # Obstacle edges and the inverse displacement of fixed cells create
# interior launch points even when a long straight has clear reach. # interior launch points even when a long straight has clear reach.
margin = self.clearance + self.evaluator.catalog.profiles[start.profile].width / 2 side_reach, offsets, blockers = self._project_blockers(start.profile, start.heading, fixed)
# This only influences proposals. Admission still checks the full x, y = start.x - self.origin[0], start.y - self.origin[1]
# footprints against the spatial index. side = dx * y - dy * x
side_reach = margin * magnitude + max((abs(dx * end.y - dy * end.x) for _, end in fixed), default=0) along = dx * x + dy * y
relevant = False divisor = pitch * magnitude
for bx0, by0, bx1, by1 in self.blocker_bounds: boundaries = set()
side = tuple(dx * (y - start.y) - dy * (x - start.x) for x in (bx0, bx1) for y in (by0, by1)) for lo, hi, projections in blockers:
if min(side) > side_reach or max(side) < -side_reach: if lo <= side + side_reach and hi >= side - side_reach:
continue boundaries.update(projections)
relevant = True for boundary in boundaries:
for x in (bx0 - margin, bx0, bx1, bx1 + margin): distance = boundary - along
for y in (by0 - margin, by0, by1, by1 + margin): for offset in offsets:
px, py = x - start.x, y - start.y span = (distance - offset) / divisor
add_projection(px, py) steps.update((floor(span), ceil(span)))
for _, end in fixed: if self.scan_steps and (boundaries or not self._is_forward_only(start.profile, start.heading)):
add_projection(px - end.x, py - end.y)
if self.scan_steps and (relevant or not self._is_forward_only(start)):
steps.add(1) steps.add(1)
return sorted((n for n in steps if 0 < n <= limit), reverse=True) return sorted((n for n in steps if 0 < n <= limit), reverse=True)
@ -491,7 +533,8 @@ def search_path(
proposals = _Proposals(evaluator, start, target, (*keepouts, *occupied), clearance, corridor, scan_steps) proposals = _Proposals(evaluator, start, target, (*keepouts, *occupied), clearance, corridor, scan_steps)
initial_bound = proposals.lower_bound(start) origin = start.x, start.y, start.heading, start.profile
initial_bound = proposals.lower_bound(origin)
if initial_bound == inf or initial_bound > max_cost + COST_TOLERANCE: if initial_bound == inf or initial_bound > max_cost + COST_TOLERANCE:
return SearchResult(None, "exhausted", 0, 0) return SearchResult(None, "exhausted", 0, 0)
incumbent = None incumbent = None
@ -514,61 +557,36 @@ def search_path(
) is None: ) is None:
incumbent = path incumbent = path
max_cost = cost max_cost = cost
# Queue moves using only their output pose and a cost lower bound.
# A move that can still win is materialized and may be requeued with its
# full cost and geometry-dependent penalty before consuming an arrival.
order = count() order = count()
queue: list[tuple[float, float, int, Pose, _Arrival | None]] = [(initial_bound, initial_bound, next(order), start, None)] queue: list[tuple[float, float, int, _Position, _Arrival | _PendingMove | None]] = [
(initial_bound, initial_bound, next(order), origin, None),
]
expanded = cache_hits = 0 expanded = cache_hits = 0
proposed, geometry_checks = macro_trials, macro_checks proposed, geometry_checks = macro_trials, macro_checks
visits: dict[Pose, int] = {} visits: dict[_Position, int] = {}
evaluated: dict[tuple[Pose, Move], Evaluation | None] = {} evaluated: dict[tuple[Pose, Move], Evaluation | None] = {}
board_bounds = board.bounds
while queue and expanded < node_limit: while queue and expanded < node_limit:
_, _, _, pose, parent = heappop(queue) priority, distance_cost, ordinal, position, pending = heappop(queue)
prior = visits.get(pose, 0) prior = visits.get(position, 0)
if prior >= arrivals_per_pose: if prior >= arrivals_per_pose:
continue continue
visits[pose] = prior + 1 if isinstance(pending, _PendingMove):
expanded += 1 move_start, spec, parent = pending.start, pending.spec, pending.previous
if parent is not None and pose == target:
path = _placed_path(parent)
if (incumbent is None or fsum(move.cost for move in path) < max_cost - COST_TOLERANCE) and (
path_recipe(path) not in excluded_paths
) and verify_path(
evaluator, path, start, target, board=board, keepouts=keepouts, occupied=occupied,
clearance=clearance, self_clearance=self_clearance, face_tolerance=face_tolerance,
source_attachment=source_attachment, destination_attachment=destination_attachment,
) is None:
return SearchResult(
path, "verified", expanded, proposed, geometry_checks=geometry_checks,
geometry_cache_hits=cache_hits, geometry_cache_entries=len(evaluated),
)
source_can_attach = parent is None or parent.source_can_attach
allowed = {
key: tuple(
(attachment, seam) for attachment, seam, source in end_permissions
if id(attachment.obstacle) == key and (not source or source_can_attach)
)
for key in attached
}
for spec in proposals.from_pose(pose, board.bounds):
if parent is not None and spec.steps is not None: if parent is not None and spec.steps is not None:
previous = parent.move.move previous = parent.move.move
if previous.variant == spec.variant and previous.steps is not None: if previous.variant == spec.variant and previous.steps is not None:
combined = Move(spec.variant, steps=previous.steps + spec.steps) combined = Move(spec.variant, steps=previous.steps + spec.steps)
if evaluated.get((parent.move.start, combined)) is not None: if evaluated.get((parent.move.start, combined)) is not None:
continue continue
proposed += 1 source_can_attach = parent is None or parent.source_can_attach
preview = proposals.destination_bound(pose, spec)
if preview is None:
continue
expected, base_cost = preview
if visits.get(expected, 0) >= arrivals_per_pose:
continue
distance_cost = proposals.lower_bound(expected)
prefix_cost = parent.cost if parent is not None else 0.0 prefix_cost = parent.cost if parent is not None else 0.0
if distance_cost == inf or prefix_cost + base_cost + distance_cost > max_cost + COST_TOLERANCE: key = (move_start, spec)
continue
key = (pose, spec)
if key not in evaluated: if key not in evaluated:
move = evaluator.evaluate(spec, pose) move = evaluator.evaluate(spec, move_start)
if move is not None and corridor is not None and not corridor.admits(move.end): if move is not None and corridor is not None and not corridor.admits(move.end):
move = None move = None
if move is not None: if move is not None:
@ -583,8 +601,15 @@ def search_path(
else: else:
cache_hits += 1 cache_hits += 1
move = evaluated[key] move = evaluated[key]
if move is None or visits.get(move.end, 0) >= arrivals_per_pose: if move is None:
continue continue
allowed = {
key: tuple(
(attachment, seam) for attachment, seam, source in end_permissions
if id(attachment.obstacle) == key and (not source or source_can_attach)
)
for key in attached
}
# Source permission depends on the arrival history. Destination # Source permission depends on the arrival history. Destination
# permission is provisional until final verification checks the suffix. # permission is provisional until final verification checks the suffix.
if any(not meets_attachment_clearance(move, obstacle, allowed[key], clearance) for key, obstacle in attached.items()): if any(not meets_attachment_clearance(move, obstacle, allowed[key], clearance) for key, obstacle in attached.items()):
@ -608,7 +633,44 @@ def search_path(
) )
if arrival.cost + distance_cost > max_cost + COST_TOLERANCE: if arrival.cost + distance_cost > max_cost + COST_TOLERANCE:
continue continue
heappush(queue, (round(arrival.cost + distance_cost + penalty, 12), distance_cost, next(order), move.end, arrival)) exact_priority = round(arrival.cost + distance_cost + penalty, 12)
if exact_priority != priority:
heappush(queue, (exact_priority, distance_cost, ordinal, position, arrival))
continue
parent = arrival
else:
parent = pending
pose = parent.move.end if parent is not None else start
visits[position] = prior + 1
expanded += 1
if parent is not None and pose == target:
path = _placed_path(parent)
if (incumbent is None or fsum(move.cost for move in path) < max_cost - COST_TOLERANCE) and (
path_recipe(path) not in excluded_paths
) and verify_path(
evaluator, path, start, target, board=board, keepouts=keepouts, occupied=occupied,
clearance=clearance, self_clearance=self_clearance, face_tolerance=face_tolerance,
source_attachment=source_attachment, destination_attachment=destination_attachment,
) is None:
return SearchResult(
path, "verified", expanded, proposed, geometry_checks=geometry_checks,
geometry_cache_hits=cache_hits, geometry_cache_entries=len(evaluated),
)
prefix_cost = parent.cost if parent is not None else 0.0
penalty = parent.priority_penalty if parent is not None else 0.0
for spec in proposals.from_pose(pose, board_bounds):
proposed += 1
preview = proposals.destination_bound(pose, spec)
if preview is None:
continue
expected, base_cost = preview
if visits.get(expected, 0) >= arrivals_per_pose:
continue
distance_cost = proposals.lower_bound(expected)
if distance_cost == inf or prefix_cost + base_cost + distance_cost > max_cost + COST_TOLERANCE:
continue
estimated_priority = round(prefix_cost + base_cost + distance_cost + penalty, 12)
heappush(queue, (estimated_priority, distance_cost, next(order), expected, _PendingMove(spec, pose, parent)))
return SearchResult( return SearchResult(
incumbent, "verified" if incumbent is not None else ("node_limit" if queue else "exhausted"), incumbent, "verified" if incumbent is not None else ("node_limit" if queue else "exhausted"),

View file

@ -3,11 +3,12 @@ from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from itertools import accumulate, combinations from itertools import accumulate, combinations
from math import hypot, isfinite, ulp from math import hypot, isfinite, isnan, ulp
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from shapely.affinity import affine_transform from shapely.affinity import affine_transform
from shapely.geometry import LineString, Polygon, box from shapely.geometry import LineString, Polygon, box
from shapely.strtree import STRtree
from inire._catalog import HEADING_STEPS, face_endpoints from inire._catalog import HEADING_STEPS, face_endpoints
from inire.geometry.collision import _violates_clearance, _violates_net_clearance from inire.geometry.collision import _violates_clearance, _violates_net_clearance
@ -164,6 +165,19 @@ def _internal_edges(path: Sequence[Evaluation], clearance: float) -> Iterable[tu
yield i, j, clearance if uncertain or separation >= clearance else 0.0 yield i, j, clearance if uncertain or separation >= clearance else 0.0
def _colliders(tree: STRtree, shapes: Sequence[BaseGeometry], clearance: float) -> tuple[BaseGeometry, ...]:
if not len(tree) or not shapes:
return ()
bounds = [extent for shape in shapes if not isnan((extent := shape.bounds)[0])]
if not bounds:
return ()
area = box(
min(b[0] for b in bounds) - clearance, min(b[1] for b in bounds) - clearance,
max(b[2] for b in bounds) + clearance, max(b[3] for b in bounds) + clearance,
)
return tuple(tree.geometries[index] for index in tree.query(area))
def verify_move( def verify_move(
evaluator: MoveEvaluator, evaluator: MoveEvaluator,
move: Evaluation, move: Evaluation,
@ -208,14 +222,15 @@ def verify_path(
return "terminal_pose" return "terminal_pose"
attachments = ((source_attachment, start, True), (destination_attachment, target, False)) attachments = ((source_attachment, start, True), (destination_attachment, target, False))
attached = {id(item.obstacle): item.obstacle for item, _, _ in attachments if item is not None} attached = {id(item.obstacle): item.obstacle for item, _, _ in attachments if item is not None}
ordinary_keepouts = tuple(obstacle for obstacle in keepouts if id(obstacle) not in attached) ordinary_keepouts = STRtree([obstacle for obstacle in keepouts if id(obstacle) not in attached])
installed = STRtree(occupied)
permissions: dict[tuple[int, int], list[tuple[Attachment, BaseGeometry]]] = {} permissions: dict[tuple[int, int], list[tuple[Attachment, BaseGeometry]]] = {}
for attachment, pose, source in attachments: for attachment, pose, source in attachments:
if attachment is None: if attachment is None:
continue continue
validate_attachment(evaluator, attachment, pose, keepouts, face_tolerance, source=source) validate_attachment(evaluator, attachment, pose, keepouts, face_tolerance, source=source)
seam = face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, face_tolerance) seam = face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, face_tolerance)
if any(_violates_net_clearance(seam, shape, clearance) for shape in occupied): if any(_violates_net_clearance(seam, shape, clearance) for shape in _colliders(installed, (seam,), clearance)):
return "occupied_seam" return "occupied_seam"
ordered = range(len(path)) if source else reversed(range(len(path))) ordered = range(len(path)) if source else reversed(range(len(path)))
for index in ordered: for index in ordered:
@ -228,7 +243,11 @@ def verify_path(
return "fixed_attachment" return "fixed_attachment"
profiles = evaluator.catalog.profiles profiles = evaluator.catalog.profiles
for move in path: for move in path:
if error := verify_move(evaluator, move, board, ordinary_keepouts, occupied, clearance, face_tolerance): if error := verify_move(
evaluator, move, board,
_colliders(ordinary_keepouts, move.footprints, clearance), _colliders(installed, move.footprints, clearance),
clearance, face_tolerance,
):
return error return error
for left, right in zip(path[:-1], path[1:], strict=True): for left, right in zip(path[:-1], path[1:], strict=True):
width = profiles[left.end.profile].width width = profiles[left.end.profile].width

View file

@ -8,7 +8,7 @@ from shapely.geometry import LineString, Polygon, box
from inire._catalog import BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant from inire._catalog import BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant
from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout
from inire.router._catalog_search import _Proposals, search_path from inire.router._catalog_search import SearchBias, _Proposals, search_path
from inire.router._catalog_verify import verify_path from inire.router._catalog_verify import verify_path
@ -130,6 +130,31 @@ def test_search_retains_the_arrival_that_can_continue(monkeypatch) -> None:
assert search_path(evaluator, start, goal, board=board, node_limit=1).outcome == "node_limit" assert search_path(evaluator, start, goal, board=board, node_limit=1).outcome == "node_limit"
def test_search_defers_geometry_and_reorders_a_move_with_a_penalty() -> None:
start, target = Pose(10, 10, 0, "p"), Pose(30, 10, 0, "p")
detour = LineString(((10, 10), (14, 10), (14, 18), (26, 18), (26, 10), (30, 10)))
alternate = FixedVariant(
"detour", {"in": start, "out": target.reversed()},
(detour.buffer(0.2, cap_style="flat", join_style="round"),),
(("in", "out"),), (Orientation(),), 0.01, detour.length,
)
evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog(
"lazy geometry", {"p": Profile("ridge", 0.4)}, {"straight": StraightVariant("p", 1), "detour": alternate},
))
geometry = {"board": box(0, 0, 40, 25), "keepouts": (box(18, 11, 22, 12),)}
direct = search_path(evaluator, start, target, **geometry)
assert direct.path is not None
assert [move.move.variant for move in direct.path] == ["straight"]
assert direct.geometry_checks == 1
assert direct.proposed > direct.geometry_checks
biased = search_path(evaluator, start, target, bias=SearchBias(range=3, proximity=0.02), **geometry)
assert biased.path is not None
assert [move.move.variant for move in biased.path] == ["detour"]
assert verify_path(evaluator, biased.path, start, target, **geometry) is None
def test_refinement_prefers_the_cheaper_of_two_full_coverage_orders() -> None: def test_refinement_prefers_the_cheaper_of_two_full_coverage_orders() -> None:
catalog = Catalog("order", {"g": Profile("ridge", 2)}, { catalog = Catalog("order", {"g": Profile("ridge", 2)}, {
"s": StraightVariant("g", 1), "left": BendVariant("g", 90, 5, 0.01), "right": BendVariant("g", -90, 5, 0.01), "s": StraightVariant("g", 1), "left": BendVariant("g", 90, 5, 0.01), "right": BendVariant("g", -90, 5, 0.01),