use alloc::vec::Vec;
use core::cmp::Reverse;
use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::best_first::GraphResult;
use crate::cost::{Weight, within};
use crate::focal::FocalList;
use crate::keyed_set::KeyedSet;
use crate::outcome::{Outcome, SearchResult, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
#[derive(Debug, Clone, Copy, Default)]
pub struct EesEstimates<H, Hh, D> {
pub admissible: H,
pub cost_to_go: Hh,
pub distance_to_go: D,
}
pub fn ees<G, T, H, Hh, D, Dc>(
graph: &G,
start: G::State,
goal: &T,
estimates: EesEstimates<H, Hh, D>,
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>,
Hh: Heuristic<G::State, G::Cost>,
D: Heuristic<G::State, Dc>,
Dc: Cost,
{
ees_multi(graph, [start], goal, estimates, weight, budget)
}
pub fn ees_multi<G, T, H, Hh, D, Dc>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
estimates: EesEstimates<H, Hh, D>,
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>,
Hh: Heuristic<G::State, G::Cost>,
D: Heuristic<G::State, Dc>,
Dc: Cost,
{
let (space, start_goal) = SearchSpace::seed(starts, goal);
let search = Ees {
graph,
estimates,
weight,
space,
focal: FocalList::new(weight),
cleanup: KeyedSet::new(),
stats: Stats::default(),
values: Vec::new(),
closed: Vec::new(),
buffer: Vec::new(),
};
if let Some(found) = start_goal {
let solution = search.space.solution(found);
return search.finish(Outcome::Found(solution));
}
search.run(goal, budget)
}
type Values<C, Dc> = (C, C, Dc);
type CleanupKey<C> = (C, Reverse<C>);
struct Ees<'a, G: Successors, H, Hh, D, Dc> {
graph: &'a G,
estimates: EesEstimates<H, Hh, D>,
weight: Weight,
space: SearchSpace<G::State, G::Action, G::Cost>,
focal: FocalList<G::Cost, Dc>,
cleanup: KeyedSet<CleanupKey<G::Cost>>,
stats: Stats,
values: Vec<Option<Values<G::Cost, Dc>>>,
closed: Vec<bool>,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<G, H, Hh, D, Dc> Ees<'_, G, H, Hh, D, Dc>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
H: Heuristic<G::State, G::Cost>,
Hh: Heuristic<G::State, G::Cost>,
D: Heuristic<G::State, Dc>,
Dc: Cost,
{
fn run<T: Goal<G::State> + ?Sized>(
mut self,
goal: &T,
mut budget: impl Budget<Stats>,
) -> GraphResult<G> {
for start in 0..self.space.len() {
self.add_node(start);
}
while let Some(node) = self.select() {
self.focal.remove(node);
self.cleanup.remove(node);
if goal.is_goal(self.space.state(node)) {
let solution = self.space.solution(node);
return self.finish(Outcome::Found(solution));
}
if budget.exhausted(&self.stats) {
return self.finish(Outcome::LimitReached);
}
self.expand(node);
}
self.finish(Outcome::Unsolvable)
}
fn select(&self) -> Option<NodeId> {
let (key, best_f) = self.cleanup.first()?;
let f_min = key.0;
let acceptable = |id: NodeId| {
self.focal
.f(id)
.is_some_and(|f_hat| within(f_hat, self.weight, f_min))
};
[self.focal.peek(), self.focal.peek_min_f()]
.into_iter()
.flatten()
.find(|&id| acceptable(id))
.or(Some(best_f))
}
fn expand(&mut self, node: NodeId) {
self.stats.expanded += 1;
self.closed[node] = true;
self.stats.generated +=
collect_successors(self.graph, self.space.state(node), &mut self.buffer);
let mut buffer = core::mem::take(&mut self.buffer);
for (action, state, cost) in buffer.drain(..) {
match self.space.reach(state, node, action, cost, true) {
Reach::New(id) => self.add_node(id),
Reach::Improved(id) => self.reopen(id),
Reach::Stale => {}
}
}
self.buffer = buffer;
}
fn add_node(&mut self, id: NodeId) {
let state = self.space.state(id);
let values = self.estimates.admissible.estimate(state).and_then(|h| {
let h_hat = self.estimates.cost_to_go.estimate(state)?;
let d_hat = self.estimates.distance_to_go.estimate(state)?;
Some((h, h_hat, d_hat))
});
self.values.push(values);
self.closed.push(false);
self.open(id);
}
fn reopen(&mut self, id: NodeId) {
if self.values[id].is_some() && self.closed[id] && self.cleanup.key(id).is_none() {
self.stats.reopened += 1;
}
self.open(id);
}
fn open(&mut self, id: NodeId) {
let Some((h, h_hat, d_hat)) = self.values[id] else {
return;
};
let g = self.space.g(id);
self.focal.push(id, g + h_hat, g, d_hat);
self.cleanup.insert(id, (g + h, Reverse(g)));
}
fn finish(self, outcome: Outcome<G::State, G::Action, G::Cost>) -> GraphResult<G> {
SearchResult {
outcome,
stats: self.stats,
}
}
}