use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic};
use super::{Engine, Order, Workspace};
use crate::cost::Weight;
use crate::outcome::{Outcome, SearchResult, Stats};
use crate::problem::Successors;
use crate::space::NodeId;
pub struct AStarSearch<S, A, C, H> {
heuristic: H,
work: Workspace<S, A, C>,
start_goal: Option<NodeId>,
total: Stats,
}
impl<S, A, C, H> AStarSearch<S, A, C, H>
where
S: Clone + Hash + Eq,
A: Clone,
C: Cost,
H: Heuristic<S, C>,
{
const ORDER: Order = Order::Weighted(Weight::ONE);
pub fn new<G, T>(graph: &G, start: S, goal: &T, heuristic: H) -> Self
where
G: Successors<State = S, Action = A, Cost = C>,
T: Goal<S> + ?Sized,
{
Self::new_multi(graph, [start], goal, heuristic)
}
pub fn new_multi<G, T>(
graph: &G,
starts: impl IntoIterator<Item = S>,
goal: &T,
mut heuristic: H,
) -> Self
where
G: Successors<State = S, Action = A, Cost = C>,
T: Goal<S> + ?Sized,
{
let mut work = Workspace::new();
let start_goal =
Engine::new(graph, goal, &mut heuristic, Self::ORDER, &mut work).seed(starts);
Self {
heuristic,
work,
start_goal,
total: Stats::default(),
}
}
pub fn compute<G, T>(
&mut self,
graph: &G,
goal: &T,
budget: impl Budget<Stats>,
) -> SearchResult<S, A, C>
where
G: Successors<State = S, Action = A, Cost = C>,
T: Goal<S> + ?Sized,
{
if let Some(found) = self.start_goal {
return SearchResult {
outcome: Outcome::Found(self.work.space.solution(found)),
stats: Stats::default(),
};
}
let mut engine = Engine::new(
graph,
goal,
&mut self.heuristic,
Self::ORDER,
&mut self.work,
);
let outcome = engine.advance(budget).unwrap_or(Outcome::LimitReached);
let stats = engine.stats;
self.total = self.total.plus(stats);
SearchResult { outcome, stats }
}
#[must_use]
pub fn stats(&self) -> Stats {
self.total
}
}