inire/inire/router/_search.py

161 lines
6 KiB
Python

from __future__ import annotations
import heapq
from dataclasses import replace
from math import inf
from typing import TYPE_CHECKING
from inire.constants import TOLERANCE_LINEAR
from ._astar_admission import process_move
from ._astar_moves import expand_moves as _expand_moves
from ._astar_types import AStarContext, AStarMetrics, AStarNode as _AStarNode, CongestionCaches, SearchRunConfig
if TYPE_CHECKING:
from collections.abc import Sequence
from inire.geometry.components import ComponentResult
from inire.geometry.primitives import Port
from inire.results import RoutingResult
from inire.seeds import BendDirection, PathSegmentSeed
def incumbent_guidance(
result: RoutingResult | None,
bend_penalty: float,
) -> tuple[tuple[PathSegmentSeed, ...] | None, float]:
if result is None or not result.reached_target or not result.path:
return None, 0.0
return path_guidance(result.path, bend_penalty)
def path_guidance(path: Sequence[ComponentResult], bend_penalty: float) -> tuple[tuple[PathSegmentSeed, ...], float]:
return tuple(component.move_spec for component in path), max(10.0, bend_penalty * 0.25)
def _reconstruct_path(end_node: _AStarNode) -> list[ComponentResult]:
path = []
curr: _AStarNode | None = end_node
while curr and curr.component_result:
path.append(curr.component_result)
curr = curr.parent
return path[::-1]
def _distance_to_terminal(port: Port, target: Port) -> tuple[float, float]:
turn = (port.r - target.r) % 360
return abs(port.x - target.x) + abs(port.y - target.y), min(turn, 360 - turn)
def route_astar(
start: Port,
target: Port,
net_width: float,
context: AStarContext,
*,
metrics: AStarMetrics | None = None,
net_id: str = "default",
config: SearchRunConfig,
) -> list[ComponentResult] | None:
if metrics is None:
metrics = AStarMetrics()
metrics.reset_per_route()
search = context.options.search
if search.sbend_outlines and search.active_sbend_outlines:
config = replace(config, sbend_templates=search._sbend_templates_for_width(net_width))
context.ensure_static_caches_current()
context.cost_evaluator.set_target(target)
open_set: list[_AStarNode] = []
closed_set: dict[tuple[int, int, int], float] = {}
deferred_turns: list[tuple[_AStarNode, float, BendDirection]] = []
congestion = CongestionCaches()
start_node = _AStarNode(
start,
0.0,
config.estimate_remaining_cost(start, target, context),
seed_index=0 if config.guidance_seed else None,
)
heapq.heappush(open_set, start_node)
best_node = start_node
best_distance = _distance_to_terminal(start, target)
nodes_expanded = 0
# A short forward scan has to piece together progress one local move at a
# time. Give the preferred frontier more room when long straights are available.
scan_spans = context.options.search.max_straight_length / max(1.0, context.min_bend_radius)
preferred = 2 * min(scan_spans, config.node_limit) ** 2
if config.node_limit <= 16:
release_turns_at = 0
else:
reserved = max(1, config.node_limit // 10)
release_turns_at = min(config.node_limit - reserved, max(config.node_limit // 20, preferred))
while open_set or deferred_turns:
if nodes_expanded >= config.node_limit or (config.expired is not None and nodes_expanded % 32 == 0 and config.expired()):
return _reconstruct_path(best_node) if config.return_partial else None
if deferred_turns and (not open_set or nodes_expanded >= release_turns_at):
for index, (parent, radius, direction) in enumerate(deferred_turns):
if config.expired is not None and index % 32 == 0 and config.expired():
return _reconstruct_path(best_node) if config.return_partial else None
process_move(
parent, target, net_width, net_id, open_set, closed_set, context, metrics, congestion, config, "bend90", (radius, direction)
)
deferred_turns.clear()
if not open_set:
break
if len(open_set) > 50_000:
retained = heapq.nsmallest(
40_000,
(node for node in open_set if closed_set.get(node.port.as_tuple(), inf) > node.g_cost + TOLERANCE_LINEAR),
)
metrics.total_frontier_trim_events += 1
metrics.total_frontier_nodes_discarded += len(open_set) - len(retained)
open_set = retained
if not open_set:
continue
current = heapq.heappop(open_set)
if config.max_cost is not None and current.fh_cost[0] > config.max_cost:
metrics.pruned_cost += 1
metrics.total_pruned_cost += 1
continue
state = current.port.as_tuple()
if state in closed_set and closed_set[state] <= current.g_cost + TOLERANCE_LINEAR:
continue
if current.port == target and config.expired is not None and config.expired():
return _reconstruct_path(best_node) if config.return_partial else None
closed_set[state] = current.g_cost
if config.return_partial:
distance = _distance_to_terminal(current.port, target)
if distance < best_distance:
best_node, best_distance = current, distance
if config.store_expanded:
metrics.last_expanded_nodes.append(state)
nodes_expanded += 1
metrics.total_nodes_expanded += 1
metrics.reroute_work += 1
metrics.nodes_expanded += 1
if current.port == target:
return _reconstruct_path(current)
_expand_moves(
current,
target,
net_width,
net_id,
open_set,
closed_set,
context,
metrics,
congestion,
config=config,
deferred_turns=deferred_turns if nodes_expanded <= release_turns_at else None,
)
return _reconstruct_path(best_node) if config.return_partial else None