inire/inire/router/_catalog_search.py

780 lines
37 KiB
Python

"""Bounded detailed search over evaluated catalog moves."""
from __future__ import annotations
from dataclasses import dataclass, replace
from heapq import heappop, heappush
from itertools import chain, count, islice
from math import ceil, floor, fsum, hypot, inf, isfinite
from typing import TYPE_CHECKING, Literal
from shapely.geometry import LineString, Point
from shapely.strtree import STRtree
from inire._catalog import HEADING_STEPS, Move, Pose, StraightVariant, _require_integer
from inire.geometry.collision import _violates_net_clearance
from ._catalog_verify import (
_colliders, compatible_join, face_reservation, meets_attachment_clearance, replay_moves, validate_attachment,
verify_move, verify_path, wholly_in_attachment,
)
from ._jog import jog_launch_steps
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
from inire._catalog import Evaluation, MoveEvaluator
from ._catalog_guidance import Corridor
from ._catalog_verify import Attachment
@dataclass(frozen=True, slots=True)
class SearchBias:
"""Optional queue penalties in catalog cost units for nearby geometry."""
range: float = 1.0
proximity: float = 0.0
congestion: float = 0.0
guide: float = 0.0
def __post_init__(self) -> None:
if not isfinite(self.range) or self.range <= 0:
raise ValueError("Search bias range must be finite and positive")
if any(not isfinite(value) or value < 0 for value in (self.proximity, self.congestion, self.guide)):
raise ValueError("Search bias weights must be finite and nonnegative")
@dataclass(frozen=True, slots=True)
class SearchResult:
path: tuple[Evaluation, ...] | None
outcome: Literal["verified", "exhausted", "node_limit"]
expanded: int
proposed: int
coarse_expanded: int = 0
used_guidance: bool = False
guide_fallback: bool = False
profile_fallback: bool = False
geometry_checks: int = 0
geometry_cache_hits: int = 0
geometry_cache_entries: int = 0
budget_exhausted: bool = False
@property
def length(self) -> float | None:
if self.path is None or any(move.length is None for move in self.path):
return None
return fsum(move.length for move in self.path if move.length is not None)
@property
def cost(self) -> float | None:
return None if self.path is None else fsum(move.cost for move in self.path)
def including_work(self, earlier: SearchResult) -> SearchResult:
return replace(
self, expanded=self.expanded + earlier.expanded, proposed=self.proposed + earlier.proposed,
coarse_expanded=self.coarse_expanded + earlier.coarse_expanded,
geometry_checks=self.geometry_checks + earlier.geometry_checks,
geometry_cache_hits=self.geometry_cache_hits + earlier.geometry_cache_hits,
geometry_cache_entries=self.geometry_cache_entries + earlier.geometry_cache_entries,
)
@dataclass(frozen=True, slots=True)
class _Arrival:
move: Evaluation
previous: _Arrival | None
cost: float
length: float
unknown_lengths: int
source_can_attach: bool
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, ...]:
path = []
while arrival is not None:
path.append(arrival.move)
arrival = arrival.previous
return tuple(reversed(path))
def path_recipe(path: Sequence[Evaluation]) -> tuple[Move, ...]:
"""Identify the same run of straight material regardless of its segmentation."""
recipe: list[Move] = []
for part in path:
move = part.move
if recipe and move.steps is not None and recipe[-1].variant == move.variant and recipe[-1].steps is not None:
previous = recipe.pop()
assert previous.steps is not None
recipe.append(Move(move.variant, steps=previous.steps + move.steps))
else:
recipe.append(move)
return tuple(recipe)
def straight_replacements(evaluator: MoveEvaluator, original: Evaluation) -> Iterator[tuple[Move, ...]]:
"""Offer cheaper straight variants and centered profile changes on the same axis."""
start = original.start
steps = original.move.steps
if steps is None:
return
pitch = int(evaluator.grid.pitch)
dx, dy = HEADING_STEPS[start.heading]
denominator = pitch * (dx * dx + dy * dy)
def advance(end: Pose) -> int | None:
if end.heading != start.heading or dx * end.y != dy * end.x:
return None
along, remainder = divmod(dx * end.x + dy * end.y, denominator)
return along if not remainder and along >= 0 else None
straights: dict[str, list[str]] = {}
for name, variant in evaluator.catalog.variants.items():
if isinstance(variant, StraightVariant):
straights.setdefault(variant.profile, []).append(name)
if variant.profile == start.profile and name != original.move.variant:
yield (Move(name, steps=steps),)
for first, middle in evaluator.local_moves(start.profile, start.heading):
lead = advance(middle)
if middle.profile == start.profile or lead is None:
continue
for last, end in evaluator.local_moves(middle.profile, middle.heading):
tail = advance(end)
if end.profile != start.profile or tail is None or lead + tail >= steps:
continue
for straight in straights.get(middle.profile, ()):
yield first, Move(straight, steps=steps - lead - tail), last
COST_TOLERANCE = 1e-12
_TravelState = tuple[str, int]
_Position = tuple[int, int, int, str]
_BlockerProjection = tuple[float, float, tuple[float, ...]]
def _reverse_distances(
target: _TravelState, incoming: dict[_TravelState, list[tuple[_TravelState, float]]],
) -> dict[_TravelState, float]:
distances = {target: 0.0}
queue = [(0.0, target)]
while queue:
distance, state = heappop(queue)
if distance > distances[state]:
continue
for previous, change in incoming.get(state, ()):
estimate = distance + change
if estimate < distances.get(previous, inf):
distances[previous] = estimate
heappush(queue, (estimate, previous))
return distances
def _geometry_bias(move: Evaluation, blockers: STRtree, radius: float, weight: float, length_factor: float) -> float:
if not weight:
return 0.0
nearby = _colliders(blockers, move.footprints, radius)
if not nearby:
return 0.0
distance = min(shape.distance(other) for shape in move.footprints for other in nearby)
return weight * length_factor * max(0.0, 1 - distance / radius)
class _Proposals:
def __init__(
self, evaluator: MoveEvaluator, start: Pose, target: Pose, blockers: Sequence[BaseGeometry], clearance: float,
corridor: Corridor | None = None,
scan_steps: bool = False,
) -> None:
self.evaluator = evaluator
self.target = target
self.origin = start.x, start.y
self.clearance = clearance
self.guide_points = corridor.points if corridor is not None else ()
self.scan_steps = scan_steps
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] = {}
profiles = evaluator.catalog.profiles
self._straights: dict[str, list[str]] = {profile: [] for profile in profiles}
self._straight_prices: dict[str, float] = {}
for name, variant in evaluator.catalog.variants.items():
if isinstance(variant, StraightVariant):
self._straights[variant.profile].append(name)
self._straight_prices[name] = variant.cost_per_cm
self._direction = (
(target.x > start.x) - (target.x < start.x),
(target.y > start.y) - (target.y < start.y),
)
# Relax the problem to heading/profile changes and a linear distance
# term. The latter telescopes across a route regardless of detours.
incoming: dict[_TravelState, list[tuple[_TravelState, float, int, int]]] = {}
self._fixed_offsets: dict[_TravelState, dict[Move, tuple[Pose, float]]] = {}
for profile in profiles:
for heading in HEADING_STEPS:
offsets = self._fixed_offsets.setdefault((profile, heading), {})
for move, end in evaluator.local_moves(profile, heading):
variant = evaluator.catalog.variants[move.variant]
assert not isinstance(variant, StraightVariant)
offsets[move] = end, variant.cost
incoming.setdefault((end.profile, end.heading), []).append(
((profile, heading), variant.cost, end.x, end.y),
)
target_key = (target.profile, target.heading)
reachable = {target_key}
pending = [target_key]
while pending:
for previous, *_ in incoming.get(pending.pop(), ()):
if previous not in reachable:
reachable.add(previous)
pending.append(previous)
ratios = []
for state in sorted(reachable):
for _, cost, x, y in incoming.get(state, ()):
distance = self._projection(x, y)
if distance > 0:
ratios.append(cost / distance)
profile, heading = state
dx, dy = HEADING_STEPS[heading]
progress = self._projection(dx, dy)
if progress > 0:
for name in self._straights[profile]:
variant = evaluator.catalog.variants[name]
assert isinstance(variant, StraightVariant)
ratios.append(variant.cost_per_cm * evaluator.grid.meters_per_unit * 100 * hypot(dx, dy) / progress)
self.cost_per_unit = min(ratios, default=0.0)
self.residual_cost = _reverse_distances(target_key, {
state: [(previous, max(0.0, cost - self.cost_per_unit * self._projection(x, y))) for previous, cost, x, y in edges]
for state, edges in incoming.items()
})
self.minimum_progress: list[tuple[int, int, dict[_TravelState, float]]] = []
for axis in (0, 1):
for sign in (-1, 1):
if any(sign * HEADING_STEPS[heading][axis] < 0 for profile, heading in reachable if self._straights[profile]):
continue
progress = {
state: [(previous, sign * (x, y)[axis]) for previous, _, x, y in incoming.get(state, ())]
for state in reachable
}
if any(distance < 0 for edges in progress.values() for _, distance in edges):
continue
self.minimum_progress.append((axis, sign, _reverse_distances(target_key, progress)))
def _projection(self, x: int, y: int) -> int:
dx, dy = self._direction
return dx * x + dy * y
def lower_bound(self, position: _Position) -> float:
x, y, heading, profile = position
key = profile, heading
residual = self.residual_cost.get(key, 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):
return inf
if self._is_forward_only(profile, heading) and (dx * ty != dy * tx or dx * tx + dy * ty < 0):
return inf
return max(0.0, residual + self._projection(tx, ty) * self.cost_per_unit)
def _is_forward_only(self, profile: str, heading: int) -> bool:
key = profile, heading
if key not in self._forward_only:
dx, dy = HEADING_STEPS[heading]
profiles = {profile}
pending = [profile]
while pending:
current = pending.pop()
for _, end in self.evaluator.local_moves(current, heading):
if (end.profile, end.heading) not in self.residual_cost:
continue
if end.heading != heading or dx * end.y != dy * end.x or dx * end.x + dy * end.y < 0:
self._forward_only[key] = False
return False
if end.profile not in profiles:
profiles.add(end.profile)
pending.append(end.profile)
self._forward_only[key] = True
return self._forward_only[key]
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."""
if move.steps is not None:
dx, dy = HEADING_STEPS[start.heading]
pitch = int(self.evaluator.grid.pitch)
span = pitch * move.steps
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)
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, ...]]:
"""Solve the straight spans of a two-turn route between parallel terminals."""
target = self.target
if target.heading != start.heading:
return
ux, uy = HEADING_STEPS[start.heading]
tx, ty = target.x - start.x, target.y - start.y
if ux * ty == uy * tx:
return
pitch = int(self.evaluator.grid.pitch)
denominator = pitch * (ux * ux + uy * uy)
cheapest = {
key: min(names, key=self._straight_prices.__getitem__)
for key, names in self._straights.items() if names
}
if start.profile not in cheapest or target.profile not in cheapest:
return
candidates = []
for first, turn in self.evaluator.local_moves(start.profile, start.heading):
vx, vy = HEADING_STEPS[turn.heading]
divisor = pitch * (ux * vy - uy * vx)
if not divisor or turn.profile not in cheapest:
continue
for second, exit_pose in self.evaluator.local_moves(turn.profile, turn.heading):
if (exit_pose.heading, exit_pose.profile) != (target.heading, target.profile):
continue
x, y = tx - turn.x - exit_pose.x, ty - turn.y - exit_pose.y
across, remainder = divmod(ux * y - uy * x, divisor)
if remainder or across < 0:
continue
x -= across * pitch * vx
y -= across * pitch * vy
parallel, remainder = divmod(ux * x + uy * y, denominator)
if remainder or parallel < 0:
continue
before_id, middle_id, after_id = (cheapest[profile] for profile in (start.profile, turn.profile, target.profile))
if ux * vx + uy * vy == 0:
margin = self.clearance + max(self.evaluator.catalog.profiles[p].width for p in (
start.profile, turn.profile, target.profile,
)) / 2
advance = ux * (turn.x + exit_pose.x) + uy * (turn.y + exit_pose.y)
launch_steps = jog_launch_steps(
(start.x, start.y), (ux, uy), ux * ty - uy * tx, advance, parallel, pitch,
margin * (ux * ux + uy * uy), self.blocker_bounds,
)
else:
launch_steps = dict.fromkeys((0, parallel, parallel // 2))
for before in launch_steps:
after = parallel - before
recipe = (
*((Move(before_id, steps=before),) if before else ()), first,
*((Move(middle_id, steps=across),) if across else ()), second,
*((Move(after_id, steps=after),) if after else ()),
)
legs = ((before_id, before, ux, uy), (middle_id, across, vx, vy), (after_id, after, ux, uy))
price = fsum(self._straight_prices[name] * steps * hypot(dx, dy) for name, steps, dx, dy in legs)
price *= pitch * self.evaluator.grid.meters_per_unit * 100
for move in (first, second):
variant = self.evaluator.catalog.variants[move.variant]
assert not isinstance(variant, StraightVariant)
price += variant.cost
candidates.append((price, before, recipe))
for _, _, recipe in sorted(candidates, key=lambda item: item[:2]):
yield recipe
def direct_recipes(self, start: Pose) -> Iterator[tuple[Move, ...]]:
"""Connect the terminal rays with a straight or a single fixed move."""
tx, ty = self.target.x - start.x, self.target.y - start.y
ux, uy = HEADING_STEPS[start.heading]
vx, vy = HEADING_STEPS[self.target.heading]
pitch = int(self.evaluator.grid.pitch)
divisor = ux * vy - uy * vx
unit = pitch * self.evaluator.grid.meters_per_unit * 100
start_straights = self._straights[start.profile]
target_straights = self._straights[self.target.profile]
if start.heading == self.target.heading and start.profile == self.target.profile and ux * ty == uy * tx:
steps, remainder = divmod(ux * tx + uy * ty, pitch * (ux * ux + uy * uy))
if steps > 0 and not remainder:
for variant in sorted(start_straights, key=self._straight_prices.__getitem__):
yield (Move(variant, steps=steps),)
if not divisor:
return
candidates = []
for move, end in self.evaluator.local_moves(start.profile, start.heading):
if (end.heading, end.profile) != (self.target.heading, self.target.profile):
continue
x, y = tx - end.x, ty - end.y
lead, lead_rem = divmod(x * vy - y * vx, pitch * divisor)
tail, tail_rem = divmod(ux * y - uy * x, pitch * divisor)
if lead_rem or tail_rem or min(lead, tail) < 0:
continue
recipe: list[Move] = []
cost = self._fixed_offsets[start.profile, start.heading][move][1]
if lead:
if not start_straights:
continue
variant = min(start_straights, key=self._straight_prices.__getitem__)
recipe.append(Move(variant, steps=lead))
cost += self._straight_prices[variant] * lead * hypot(ux, uy) * unit
recipe.append(move)
if tail:
if not target_straights:
continue
variant = min(target_straights, key=self._straight_prices.__getitem__)
recipe.append(Move(variant, steps=tail))
cost += self._straight_prices[variant] * tail * hypot(vx, vy) * unit
candidates.append((cost, tuple(recipe)))
for _, recipe in sorted(candidates, key=lambda item: item[0]):
yield recipe
def from_pose(self, start: Pose, board_bounds: tuple[float, float, float, float]) -> Iterator[Move]:
fixed = self.evaluator.local_moves(start.profile, start.heading)
runs = self._straights[start.profile]
if not fixed:
dx, dy = HEADING_STEPS[start.heading]
tx, ty = self.target.x - start.x, self.target.y - start.y
if (start.heading, start.profile) == (self.target.heading, self.target.profile) and dx * ty == dy * tx:
steps = (dx * tx + dy * ty) // (int(self.evaluator.grid.pitch) * (dx * dx + dy * dy))
if steps > 0:
for name in runs:
yield Move(name, steps=steps)
return
if runs:
targets = self._straight_steps(start, fixed, board_bounds)
for steps in targets:
for name in runs:
yield Move(name, steps=steps)
for move, _ in fixed:
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(
self, start: Pose, fixed: Sequence[tuple[Move, Pose]], board_bounds: tuple[float, float, float, float],
) -> list[int]:
dx, dy = HEADING_STEPS[start.heading]
pitch = int(self.evaluator.grid.pitch)
x0, y0, x1, y1 = board_bounds
distance_x = (x1 - start.x) if dx > 0 else (start.x - x0) if dx < 0 else inf
distance_y = (y1 - start.y) if dy > 0 else (start.y - y0) if dy < 0 else inf
limit = floor(min(distance_x, distance_y) / pitch)
magnitude = dx * dx + dy * dy
tx, ty = self.target.x - start.x, self.target.y - start.y
steps = {limit}
def add_projection(x: float, y: float) -> None:
projected = (dx * x + dy * y) / (pitch * magnitude)
steps.update((floor(projected), ceil(projected)))
add_projection(tx, ty)
for x, y in self.guide_points:
add_projection(x - start.x, y - start.y)
for _, end in fixed:
add_projection(x - start.x - end.x, y - start.y - end.y)
for heading, offsets in self._aligned_exits(start.profile, start.heading, fixed).items():
ex, ey = HEADING_STEPS[heading]
divisor = pitch * (dx * ey - dy * ex)
if divisor:
target = tx * ey - ty * ex
for offset in offsets:
n, remainder = divmod(target - offset, divisor)
if not remainder:
steps.add(n)
else:
target = dx * tx + dy * ty
for offset in offsets:
span = (target - offset) / (pitch * magnitude)
steps.update((floor(span), ceil(span)))
# Obstacle edges and the inverse displacement of fixed cells create
# interior launch points even when a long straight has clear reach.
side_reach, offsets, blockers = self._project_blockers(start.profile, start.heading, fixed)
x, y = start.x - self.origin[0], start.y - self.origin[1]
side = dx * y - dy * x
along = dx * x + dy * y
divisor = pitch * magnitude
boundaries = set()
for lo, hi, projections in blockers:
if lo <= side + side_reach and hi >= side - side_reach:
boundaries.update(projections)
for boundary in boundaries:
distance = boundary - along
for offset in offsets:
span = (distance - offset) / divisor
steps.update((floor(span), ceil(span)))
if self.scan_steps and (boundaries or not self._is_forward_only(start.profile, start.heading)):
steps.add(1)
return sorted((n for n in steps if 0 < n <= limit), reverse=True)
def _continues(
evaluator: MoveEvaluator,
parent: _Arrival | None,
move: Evaluation,
occupied: STRtree,
clearance: float,
self_clearance: float,
face_tolerance: float,
) -> bool:
if parent is None:
return True
width = evaluator.catalog.profiles[move.start.profile].width
if not compatible_join(parent.move, move, width, face_tolerance):
return False
if len(occupied):
seam = face_reservation(move.start, width, face_tolerance)
if any(_violates_net_clearance(seam, other, clearance) for other in _colliders(occupied, (seam,), clearance)):
return False
earlier = parent.previous
while earlier is not None:
uncertain = parent.unknown_lengths != earlier.unknown_lengths
spacing = self_clearance if uncertain or parent.length - earlier.length >= self_clearance else 0.0
if any(_violates_net_clearance(a, b, spacing) for a in earlier.move.footprints for b in move.footprints):
return False
earlier = earlier.previous
return True
def search_path(
evaluator: MoveEvaluator,
start: Pose,
target: Pose,
*,
board: Polygon,
keepouts: Sequence[BaseGeometry] = (),
occupied: Sequence[BaseGeometry] = (),
clearance: float = 0.0,
self_clearance: float = 0.0,
face_tolerance: float = 0.0,
node_limit: int = 1000,
arrivals_per_pose: int = 3,
source_attachment: Attachment | None = None,
destination_attachment: Attachment | None = None,
excluded_paths: Sequence[tuple[Move, ...]] = (),
max_cost: float = inf,
corridor: Corridor | None = None,
scan_steps: bool = False,
bias: SearchBias | None = None,
method: Literal["detailed", "constructive_first", "constructive_only"] = "detailed",
) -> SearchResult:
"""Search physical paths while retaining a bounded number of distinct arrival histories."""
_require_integer(node_limit)
_require_integer(arrivals_per_pose)
if node_limit < 0 or arrivals_per_pose < 1:
raise ValueError("Search requires a nonnegative node limit and positive arrival limit")
if any(value < 0 or not isfinite(value) for value in (clearance, self_clearance, face_tolerance)):
raise ValueError("Clearance and face tolerance must be finite and nonnegative")
for port in (start, target):
if evaluator.grid.lattice_position(port.x, port.y) is None or port.profile not in evaluator.catalog.profiles:
raise ValueError(f"Invalid catalog terminal {port!r}")
attached = {}
end_permissions = []
for attachment, pose, source in ((source_attachment, start, True), (destination_attachment, target, False)):
if attachment is not None:
validate_attachment(evaluator, attachment, pose, keepouts, face_tolerance, source=source)
attached[id(attachment.obstacle)] = attachment.obstacle
seam = face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, face_tolerance)
end_permissions.append((attachment, seam, source))
ordinary_keepouts = STRtree([obstacle for obstacle in keepouts if id(obstacle) not in attached])
installed = STRtree(occupied)
guide_axis = LineString(corridor.points) if bias is not None and bias.guide and corridor is not None and len(corridor.points) > 1 else None
proposals = _Proposals(evaluator, start, target, (*keepouts, *occupied), clearance, corridor, scan_steps)
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:
return SearchResult(None, "exhausted", 0, 0)
incumbent = None
macro_trials = macro_checks = 0
recipes = proposals.two_turn_recipes(start)
if method != "detailed":
recipes = chain(proposals.direct_recipes(start), recipes)
for recipe in islice(recipes, min(node_limit // 2, 48)):
macro_trials += 1
if recipe in excluded_paths:
continue
path = replay_moves(evaluator, start, recipe)
if path is None or (corridor is not None and any(not corridor.admits(move.end) for move in path)):
continue
cost = fsum(move.cost for move in path)
if cost >= max_cost:
continue
macro_checks += 1
if 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:
incumbent = path
max_cost = cost
if method == "constructive_first":
return SearchResult(path, "verified", 0, macro_trials, geometry_checks=macro_checks)
if method == "constructive_only":
return SearchResult(incumbent, "verified" if incumbent is not None else "exhausted", 0, macro_trials, geometry_checks=macro_checks)
# 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()
queue: list[tuple[float, float, int, _Position, _Arrival | _PendingMove | None]] = [
(initial_bound, initial_bound, next(order), origin, None),
]
expanded = cache_hits = 0
proposed, geometry_checks = macro_trials, macro_checks
visits: dict[_Position, int] = {}
evaluated: dict[tuple[Pose, Move], Evaluation | None] = {}
board_bounds = board.bounds
while queue and expanded < node_limit:
priority, distance_cost, ordinal, position, pending = heappop(queue)
prior = visits.get(position, 0)
if prior >= arrivals_per_pose:
continue
if isinstance(pending, _PendingMove):
move_start, spec, parent = pending.start, pending.spec, pending.previous
if parent is not None and spec.steps is not None:
previous = parent.move.move
if previous.variant == spec.variant and previous.steps is not None:
combined = Move(spec.variant, steps=previous.steps + spec.steps)
if evaluated.get((parent.move.start, combined)) is not None:
continue
source_can_attach = parent is None or parent.source_can_attach
prefix_cost = parent.cost if parent is not None else 0.0
key = (move_start, spec)
if key not in evaluated:
move = evaluator.evaluate(spec, move_start)
if move is not None and corridor is not None and not corridor.admits(move.end):
move = None
if move is not None:
geometry_checks += 1
if verify_move(
evaluator, move, board,
_colliders(ordinary_keepouts, move.footprints, clearance), _colliders(installed, move.footprints, clearance),
clearance, face_tolerance,
):
move = None
evaluated[key] = move
else:
cache_hits += 1
move = evaluated[key]
if move is None:
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
# 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()):
continue
if not _continues(evaluator, parent, move, installed, clearance, self_clearance, face_tolerance):
continue
step_length = move.length if move.length is not None else hypot(move.end.x - move.start.x, move.end.y - move.start.y)
penalty = parent.priority_penalty if parent is not None else 0.0
if bias is not None:
length_factor = step_length / bias.range
penalty += _geometry_bias(move, ordinary_keepouts, bias.range, bias.proximity, length_factor)
penalty += _geometry_bias(move, installed, bias.range, bias.congestion, length_factor)
if guide_axis is not None:
penalty += bias.guide * length_factor * guide_axis.distance(Point(move.end.x, move.end.y)) / bias.range
arrival = _Arrival(
move, parent, prefix_cost + move.cost,
(parent.length if parent is not None else 0) + (move.length or 0.0),
(parent.unknown_lengths if parent is not None else 0) + (move.length is None),
source_can_attach and source_attachment is not None and wholly_in_attachment(move, source_attachment),
penalty,
)
if arrival.cost + distance_cost > max_cost + COST_TOLERANCE:
continue
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(
incumbent, "verified" if incumbent is not None else ("node_limit" if queue else "exhausted"),
expanded, proposed, geometry_checks=geometry_checks, geometry_cache_hits=cache_hits,
geometry_cache_entries=len(evaluated), budget_exhausted=bool(queue),
)