use alloc::vec::Vec;
use core::cmp::Ordering;
use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::anytime::{AnytimeGraphResult, AnytimeResult};
use crate::cost::CostExt;
use crate::open_list::OpenList;
use crate::outcome::{Solution, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
pub fn ana_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
on_solution: impl FnMut(&Solution<G::State, G::Action, G::Cost>, G::Cost),
budget: impl Budget<Stats>,
) -> AnytimeGraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
G::Cost: CostExt,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
ana_star_multi(graph, [start], goal, heuristic, on_solution, budget)
}
pub fn ana_star_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
on_solution: impl FnMut(&Solution<G::State, G::Action, G::Cost>, G::Cost),
budget: impl Budget<Stats>,
) -> AnytimeGraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
G::Cost: CostExt,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let (space, start_goal) = SearchSpace::seed(starts, goal);
let ana = Ana {
graph,
goal,
heuristic,
space,
stats: Stats::default(),
h: Vec::new(),
closed: Vec::new(),
open_flag: Vec::new(),
open: OpenList::new(),
incumbent: start_goal,
best: start_goal.map(|_| G::Cost::ZERO),
buffer: Vec::new(),
};
if start_goal.is_some() {
return ana.finish(true);
}
ana.run(on_solution, budget)
}
struct Ana<'a, G: Successors, T: ?Sized, H> {
graph: &'a G,
goal: &'a T,
heuristic: H,
space: SearchSpace<G::State, G::Action, G::Cost>,
stats: Stats,
h: Vec<Option<G::Cost>>,
closed: Vec<bool>,
open_flag: Vec<bool>,
open: OpenList<Priority, G::Cost>,
incumbent: Option<NodeId>,
best: Option<G::Cost>,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<G, T, H> Ana<'_, G, T, H>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
G::Cost: CostExt,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
fn run(
mut self,
mut on_solution: impl FnMut(&Solution<G::State, G::Action, G::Cost>, G::Cost),
mut budget: impl Budget<Stats>,
) -> AnytimeGraphResult<G> {
for start in 0..self.space.len() {
self.add_node(start);
}
while let Some(node) = self.pop() {
if self.goal.is_goal(self.space.state(node)) {
self.incumbent = Some(node);
self.best = Some(self.space.g(node));
self.prune();
on_solution(&self.space.solution(node), self.lower_bound());
continue;
}
if budget.exhausted(&self.stats) {
return self.finish(false);
}
self.expand(node);
}
self.finish(true)
}
fn pop(&mut self) -> Option<NodeId> {
let (space, open_flag) = (&self.space, &self.open_flag);
let live = |node: NodeId, g: G::Cost| open_flag[node] && g.cmp(&space.g(node)).is_eq();
let (node, _) = self.open.pop_where(live)?;
self.open_flag[node] = false;
Some(node)
}
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.open_if_promising(id),
Reach::Stale => {}
}
}
self.buffer = buffer;
}
fn add_node(&mut self, id: NodeId) {
let h = self.heuristic.estimate(self.space.state(id));
self.h.push(h);
self.closed.push(false);
self.open_flag.push(false);
self.open_if_promising(id);
}
fn open_if_promising(&mut self, id: NodeId) {
let Some(key) = self.key(id) else {
return;
};
if self.closed[id] && !self.open_flag[id] {
self.stats.reopened += 1;
}
self.open_flag[id] = true;
self.open.push(id, key, self.space.g(id));
}
fn key(&self, id: NodeId) -> Option<Priority> {
let h = self.h[id]?;
let g = self.space.g(id);
let Some(incumbent) = self.best else {
return Some(Priority(h.to_f64()));
};
if (g + h).cmp(&incumbent).is_ge() {
return None;
}
let slack = incumbent.saturating_sub(g).to_f64();
let h = h.to_f64();
Some(Priority(if h > 0.0 {
-slack / h
} else {
f64::NEG_INFINITY
}))
}
fn prune(&mut self) {
self.open.clear();
for id in 0..self.space.len() {
if !self.open_flag[id] {
continue;
}
match self.key(id) {
Some(key) => self.open.push(id, key, self.space.g(id)),
None => self.open_flag[id] = false,
}
}
}
fn lower_bound(&self) -> G::Cost {
let incumbent = self.best.expect("called with an incumbent");
(0..self.space.len())
.filter(|&id| self.open_flag[id])
.filter_map(|id| self.h[id].map(|h| self.space.g(id) + h))
.fold(
incumbent,
|bound, f| {
if f.cmp(&bound).is_lt() { f } else { bound }
},
)
}
fn finish(self, complete: bool) -> AnytimeGraphResult<G> {
AnytimeResult {
solution: self.incumbent.map(|id| self.space.solution(id)),
complete,
stats: self.stats,
}
}
}
#[derive(Debug, Clone, Copy)]
struct Priority(f64);
impl PartialEq for Priority {
fn eq(&self, other: &Self) -> bool {
self.cmp(other).is_eq()
}
}
impl Eq for Priority {}
impl PartialOrd for Priority {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Priority {
fn cmp(&self, other: &Self) -> Ordering {
self.0.total_cmp(&other.0)
}
}