mod resumable;
use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic, Zero};
use crate::cost::Weight;
use crate::open_list::OpenList;
use crate::outcome::{Outcome, SearchResult, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
pub use resumable::AStarSearch;
pub type GraphResult<G> =
SearchResult<<G as Successors>::State, <G as Successors>::Action, <G as Successors>::Cost>;
pub fn a_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
a_star_in(&mut Workspace::new(), graph, start, goal, heuristic, budget)
}
#[cfg(feature = "float")]
pub(crate) fn a_star_below<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
bound: G::Cost,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let mut work = Workspace::new();
let mut engine = Engine::new(
graph,
goal,
heuristic,
Order::Weighted(Weight::ONE),
&mut work,
);
engine.bound = Some(bound);
engine.run([start], crate::outcome::Limits::NONE)
}
pub fn dijkstra<G, T>(
graph: &G,
start: G::State,
goal: &T,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
dijkstra_in(&mut Workspace::new(), graph, start, goal, budget)
}
pub fn weighted_a_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
weight: Weight,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
weighted_a_star_in(
&mut Workspace::new(),
graph,
start,
goal,
heuristic,
weight,
budget,
)
}
pub fn gbfs<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
gbfs_in(&mut Workspace::new(), graph, start, goal, heuristic, budget)
}
pub fn a_star_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
a_star_multi_in(
&mut Workspace::new(),
graph,
starts,
goal,
heuristic,
budget,
)
}
pub fn dijkstra_multi<G, T>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
dijkstra_multi_in(&mut Workspace::new(), graph, starts, goal, budget)
}
pub fn weighted_a_star_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
weight: Weight,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
weighted_a_star_multi_in(
&mut Workspace::new(),
graph,
starts,
goal,
heuristic,
weight,
budget,
)
}
pub fn gbfs_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
gbfs_multi_in(
&mut Workspace::new(),
graph,
starts,
goal,
heuristic,
budget,
)
}
pub fn a_star_in<G, T, H>(
workspace: &mut Workspace<G::State, G::Action, G::Cost>,
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let order = Order::Weighted(Weight::ONE);
Engine::new(graph, goal, heuristic, order, workspace).run([start], budget)
}
pub fn dijkstra_in<G, T>(
workspace: &mut Workspace<G::State, G::Action, G::Cost>,
graph: &G,
start: G::State,
goal: &T,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
Engine::new(graph, goal, Zero, Order::G, workspace).run([start], budget)
}
pub fn weighted_a_star_in<G, T, H>(
workspace: &mut Workspace<G::State, G::Action, G::Cost>,
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
weight: Weight,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let order = Order::Weighted(weight);
Engine::new(graph, goal, heuristic, order, workspace).run([start], budget)
}
pub fn gbfs_in<G, T, H>(
workspace: &mut Workspace<G::State, G::Action, G::Cost>,
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
Engine::new(graph, goal, heuristic, Order::H, workspace).run([start], budget)
}
pub fn a_star_multi_in<G, T, H>(
workspace: &mut Workspace<G::State, G::Action, G::Cost>,
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let order = Order::Weighted(Weight::ONE);
Engine::new(graph, goal, heuristic, order, workspace).run(starts, budget)
}
pub fn dijkstra_multi_in<G, T>(
workspace: &mut Workspace<G::State, G::Action, G::Cost>,
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
Engine::new(graph, goal, Zero, Order::G, workspace).run(starts, budget)
}
pub fn weighted_a_star_multi_in<G, T, H>(
workspace: &mut Workspace<G::State, G::Action, G::Cost>,
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
weight: Weight,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let order = Order::Weighted(weight);
Engine::new(graph, goal, heuristic, order, workspace).run(starts, budget)
}
pub fn gbfs_multi_in<G, T, H>(
workspace: &mut Workspace<G::State, G::Action, G::Cost>,
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
Engine::new(graph, goal, heuristic, Order::H, workspace).run(starts, budget)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Order {
G,
Weighted(Weight),
H,
}
impl Order {
pub(crate) fn key<C: Cost>(self, g: C, h: C) -> C {
match self {
Self::G => g,
Self::Weighted(weight) => g
.saturating_times(weight.denominator())
.saturating_add(h.saturating_times(weight.numerator())),
Self::H => h,
}
}
pub(crate) fn reopens(self) -> bool {
!matches!(self, Self::H)
}
}
pub struct Workspace<S, A, C> {
space: SearchSpace<S, A, C>,
open: OpenList<C>,
h: Vec<Option<C>>,
closed: Vec<bool>,
buffer: Vec<(A, S, C)>,
}
impl<S: Hash + Eq, A, C: Cost> Workspace<S, A, C> {
#[must_use]
pub fn new() -> Self {
Self {
space: SearchSpace::new(),
open: OpenList::new(),
h: Vec::new(),
closed: Vec::new(),
buffer: Vec::new(),
}
}
fn clear(&mut self) {
self.open.clear();
self.h.clear();
self.closed.clear();
self.buffer.clear();
}
}
impl<S, A, C> Workspace<S, A, C> {
pub(crate) fn space(&self) -> &SearchSpace<S, A, C> {
&self.space
}
pub(crate) fn is_closed(&self, id: NodeId) -> bool {
self.closed[id]
}
}
impl<S: Hash + Eq, A, C: Cost> Default for Workspace<S, A, C> {
fn default() -> Self {
Self::new()
}
}
struct Engine<'a, G: Successors, T: ?Sized, H> {
graph: &'a G,
goal: &'a T,
heuristic: H,
order: Order,
stats: Stats,
work: &'a mut Workspace<G::State, G::Action, G::Cost>,
bound: Option<G::Cost>,
}
impl<'a, G, T, H> Engine<'a, G, T, H>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
fn new(
graph: &'a G,
goal: &'a T,
heuristic: H,
order: Order,
work: &'a mut Workspace<G::State, G::Action, G::Cost>,
) -> Self {
Self {
graph,
goal,
heuristic,
order,
stats: Stats::default(),
work,
bound: None,
}
}
fn run(
mut self,
starts: impl IntoIterator<Item = G::State>,
budget: impl Budget<Stats>,
) -> GraphResult<G> {
if let Some(found) = self.seed(starts) {
let solution = self.work.space.solution(found);
return self.finish(Outcome::Found(solution));
}
let outcome = self.advance(budget).unwrap_or(Outcome::LimitReached);
self.finish(outcome)
}
fn seed(&mut self, starts: impl IntoIterator<Item = G::State>) -> Option<NodeId> {
self.work.clear();
if let Some(found) = self.work.space.reseed(starts, self.goal) {
return Some(found);
}
for start in 0..self.work.space.len() {
self.open_if_alive(start);
}
None
}
fn advance(
&mut self,
mut budget: impl Budget<Stats>,
) -> Option<Outcome<G::State, G::Action, G::Cost>> {
loop {
let work = &mut *self.work;
let space = &work.space;
let Some((node, key)) = work.open.peek_where(|id, g| g.cmp(&space.g(id)).is_eq())
else {
return Some(Outcome::Unsolvable);
};
if self.bound.is_some_and(|bound| key >= bound) {
return Some(Outcome::Unsolvable);
}
if self.goal.is_goal(space.state(node)) {
return Some(Outcome::Found(space.solution(node)));
}
if budget.exhausted(&self.stats) {
return None;
}
work.open.pop_where(|_, _| true);
self.expand(node);
}
}
fn expand(&mut self, node: NodeId) {
self.stats.expanded += 1;
let work = &mut *self.work;
work.closed[node] = true;
self.stats.generated +=
collect_successors(self.graph, work.space.state(node), &mut work.buffer);
let reopens = self.order.reopens();
let mut buffer = core::mem::take(&mut work.buffer);
for (action, state, cost) in buffer.drain(..) {
match self.work.space.reach(state, node, action, cost, reopens) {
Reach::New(id) => self.open_if_alive(id),
Reach::Improved(id) => self.reopen(id),
Reach::Stale => {}
}
}
self.work.buffer = buffer;
}
fn open_if_alive(&mut self, id: NodeId) {
let work = &mut *self.work;
let h = self.heuristic.estimate(work.space.state(id));
debug_assert_eq!(id, work.h.len(), "nodes are recorded in creation order");
work.h.push(h);
work.closed.push(false);
if let Some(h) = h {
let g = work.space.g(id);
work.open.push(id, self.order.key(g, h), g);
}
}
fn reopen(&mut self, id: NodeId) {
let work = &mut *self.work;
let Some(h) = work.h[id] else {
return;
};
if work.closed[id] {
self.stats.reopened += 1;
}
let g = work.space.g(id);
work.open.push(id, self.order.key(g, h), g);
}
fn finish(self, outcome: Outcome<G::State, G::Action, G::Cost>) -> GraphResult<G> {
SearchResult {
outcome,
stats: self.stats,
}
}
}