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 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>,
{
let order = Order::Weighted(Weight::ONE);
Engine::new(graph, goal, heuristic, order).run([start], budget)
}
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,
{
Engine::new(graph, goal, Zero, Order::G).run([start], 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>,
{
Engine::new(graph, goal, heuristic, Order::Weighted(weight)).run([start], 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>,
{
Engine::new(graph, goal, heuristic, Order::H).run([start], 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>,
{
let order = Order::Weighted(Weight::ONE);
Engine::new(graph, goal, heuristic, order).run(starts, 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,
{
Engine::new(graph, goal, Zero, Order::G).run(starts, 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>,
{
Engine::new(graph, goal, heuristic, Order::Weighted(weight)).run(starts, 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>,
{
Engine::new(graph, goal, heuristic, Order::H).run(starts, budget)
}
#[derive(Clone, Copy)]
enum Order {
G,
Weighted(Weight),
H,
}
impl Order {
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,
}
}
fn reopens(self) -> bool {
!matches!(self, Self::H)
}
}
struct Engine<'a, G: Successors, T: ?Sized, H> {
graph: &'a G,
goal: &'a T,
heuristic: H,
order: Order,
stats: Stats,
h: Vec<Option<G::Cost>>,
closed: Vec<bool>,
buffer: Vec<(G::Action, G::State, 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) -> Self {
Self {
graph,
goal,
heuristic,
order,
stats: Stats::default(),
h: Vec::new(),
closed: Vec::new(),
buffer: Vec::new(),
}
}
fn run(
mut self,
starts: impl IntoIterator<Item = G::State>,
mut budget: impl Budget<Stats>,
) -> GraphResult<G> {
let (mut space, start_goal) = SearchSpace::seed(starts, self.goal);
if let Some(found) = start_goal {
return self.finish(Outcome::Found(space.solution(found)));
}
let mut open = OpenList::new();
for start in 0..space.len() {
self.open_if_alive(&space, &mut open, start);
}
while let Some(node) = open.pop_live(|id| space.g(id)) {
if self.goal.is_goal(space.state(node)) {
return self.finish(Outcome::Found(space.solution(node)));
}
if budget.exhausted(&self.stats) {
return self.finish(Outcome::LimitReached);
}
self.expand(&mut space, &mut open, node);
}
self.finish(Outcome::Unsolvable)
}
fn expand(
&mut self,
space: &mut SearchSpace<G::State, G::Action, G::Cost>,
open: &mut OpenList<G::Cost>,
node: NodeId,
) {
self.stats.expanded += 1;
self.closed[node] = true;
self.stats.generated += collect_successors(self.graph, space.state(node), &mut self.buffer);
let reopens = self.order.reopens();
let mut buffer = core::mem::take(&mut self.buffer);
for (action, state, cost) in buffer.drain(..) {
match space.reach(state, node, action, cost, reopens) {
Reach::New(id) => self.open_if_alive(space, open, id),
Reach::Improved(id) => self.reopen(space, open, id),
Reach::Stale => {}
}
}
self.buffer = buffer;
}
fn open_if_alive(
&mut self,
space: &SearchSpace<G::State, G::Action, G::Cost>,
open: &mut OpenList<G::Cost>,
id: NodeId,
) {
let h = self.heuristic.estimate(space.state(id));
self.record(id, h);
if let Some(h) = h {
let g = space.g(id);
open.push(id, self.order.key(g, h), g);
}
}
fn record(&mut self, id: NodeId, h: Option<G::Cost>) {
debug_assert_eq!(id, self.h.len(), "nodes are recorded in creation order");
self.h.push(h);
self.closed.push(false);
}
fn reopen(
&mut self,
space: &SearchSpace<G::State, G::Action, G::Cost>,
open: &mut OpenList<G::Cost>,
id: NodeId,
) {
let Some(h) = self.h[id] else {
return;
};
if self.closed[id] {
self.stats.reopened += 1;
}
let g = space.g(id);
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,
}
}
}