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,
order: Order,
}
impl<S, A, C, H> AStarSearch<S, A, C, H>
where
S: Clone + Hash + Eq,
A: Clone,
C: Cost,
H: Heuristic<S, C>,
{
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,
heuristic: H,
) -> Self
where
G: Successors<State = S, Action = A, Cost = C>,
T: Goal<S> + ?Sized,
{
Self::seeded(graph, starts, goal, heuristic, Order::Weighted(Weight::ONE))
}
pub fn new_weighted<G, T>(graph: &G, start: S, goal: &T, heuristic: H, weight: Weight) -> Self
where
G: Successors<State = S, Action = A, Cost = C>,
T: Goal<S> + ?Sized,
{
Self::new_weighted_multi(graph, [start], goal, heuristic, weight)
}
pub fn new_weighted_multi<G, T>(
graph: &G,
starts: impl IntoIterator<Item = S>,
goal: &T,
heuristic: H,
weight: Weight,
) -> Self
where
G: Successors<State = S, Action = A, Cost = C>,
T: Goal<S> + ?Sized,
{
Self::seeded(graph, starts, goal, heuristic, Order::Weighted(weight))
}
pub fn new_gbfs<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_gbfs_multi(graph, [start], goal, heuristic)
}
pub fn new_gbfs_multi<G, T>(
graph: &G,
starts: impl IntoIterator<Item = S>,
goal: &T,
heuristic: H,
) -> Self
where
G: Successors<State = S, Action = A, Cost = C>,
T: Goal<S> + ?Sized,
{
Self::seeded(graph, starts, goal, heuristic, Order::H)
}
fn seeded<G, T>(
graph: &G,
starts: impl IntoIterator<Item = S>,
goal: &T,
mut heuristic: H,
order: Order,
) -> 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, order, &mut work).seed(starts);
Self {
heuristic,
work,
start_goal,
total: Stats::default(),
order,
}
}
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
}
}