use alloc::vec::Vec;
use core::hash::Hash;
use core::iter::Peekable;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::anytime::{AnytimeGraphResult, AnytimeResult};
use crate::cost::Weight;
use crate::open_list::OpenList;
use crate::outcome::{Solution, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
pub fn ara_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
weights: impl IntoIterator<Item = Weight>,
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,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
ara_star_multi(
graph,
[start],
goal,
heuristic,
weights,
on_solution,
budget,
)
}
pub fn ara_star_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
weights: impl IntoIterator<Item = Weight>,
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,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let (space, start_goal) = SearchSpace::seed(starts, goal);
let ara = Ara {
graph,
goal,
heuristic,
space,
stats: Stats::default(),
h: Vec::new(),
closed_in: Vec::new(),
open_flag: Vec::new(),
parked_flag: Vec::new(),
parked: Vec::new(),
open: OpenList::new(),
incumbent: start_goal,
iteration: 0,
buffer: Vec::new(),
};
if start_goal.is_some() {
return ara.finish(true);
}
ara.run(weights.into_iter().peekable(), on_solution, budget)
}
enum Iteration {
Done,
Stopped,
}
struct Ara<'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_in: Vec<u32>,
open_flag: Vec<bool>,
parked_flag: Vec<bool>,
parked: Vec<NodeId>,
open: OpenList<G::Cost>,
incumbent: Option<NodeId>,
iteration: u32,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<G, T, H> Ara<'_, 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 run<I: Iterator<Item = Weight>>(
mut self,
mut weights: Peekable<I>,
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);
}
let mut reported: Option<G::Cost> = None;
let mut weight = weights.next().unwrap_or(Weight::ONE);
loop {
let last = weights.peek().is_none();
self.begin_iteration(weight);
if matches!(
self.improve_path(weight, last, &mut budget),
Iteration::Stopped
) {
return self.finish(false);
}
if let Some(cost) = self.incumbent_cost() {
let lower_bound = self.lower_bound(cost);
if reported.is_none_or(|old| cost.cmp(&old).is_lt()) {
reported = Some(cost);
on_solution(&self.incumbent_solution(), lower_bound);
}
if lower_bound.cmp(&cost).is_ge() {
return self.finish(true);
}
}
match weights.next() {
Some(next) if !last => weight = next,
_ => return self.finish(true),
}
}
}
fn begin_iteration(&mut self, weight: Weight) {
self.iteration += 1;
for node in core::mem::take(&mut self.parked) {
self.parked_flag[node] = false;
self.open_flag[node] = true;
}
self.open.clear();
for node in 0..self.space.len() {
if self.open_flag[node] {
self.push(node, weight);
}
}
}
fn improve_path(
&mut self,
weight: Weight,
last: bool,
budget: &mut impl Budget<Stats>,
) -> Iteration {
loop {
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 Some((node, key)) = self.open.peek_where(live) else {
return Iteration::Done;
};
let done = self.incumbent_cost().is_some_and(|cost| {
cost.saturating_times(weight.denominator())
.cmp(&key)
.is_le()
});
if done {
return Iteration::Done;
}
if budget.exhausted(&self.stats) {
return Iteration::Stopped;
}
self.open.pop_where(|_, _| true);
self.open_flag[node] = false;
self.expand(node, weight, last);
}
}
fn expand(&mut self, node: NodeId, weight: Weight, last: bool) {
self.stats.expanded += 1;
self.closed_in[node] = self.iteration;
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);
if self.open_flag[id] {
self.push(id, weight);
}
}
Reach::Improved(id) => self.improved(id, weight, last),
Reach::Stale => {}
}
}
self.buffer = buffer;
}
fn add_node(&mut self, id: NodeId) {
let is_goal = self.goal.is_goal(self.space.state(id));
let h = self.heuristic.estimate(self.space.state(id));
self.h.push(h);
self.closed_in.push(0);
self.open_flag.push(h.is_some() && !is_goal);
self.parked_flag.push(false);
if is_goal {
self.offer_incumbent(id);
}
}
fn improved(&mut self, id: NodeId, weight: Weight, last: bool) {
if self.goal.is_goal(self.space.state(id)) {
self.offer_incumbent(id);
return;
}
if self.h[id].is_none() {
return;
}
if self.closed_in[id] == self.iteration && !last {
if !self.parked_flag[id] {
self.parked_flag[id] = true;
self.parked.push(id);
}
return;
}
if self.closed_in[id] != 0 && !self.open_flag[id] {
self.stats.reopened += 1;
}
self.open_flag[id] = true;
self.push(id, weight);
}
fn offer_incumbent(&mut self, id: NodeId) {
let cheaper = self
.incumbent_cost()
.is_none_or(|cost| self.space.g(id).cmp(&cost).is_lt());
if cheaper {
self.incumbent = Some(id);
}
}
fn push(&mut self, id: NodeId, weight: Weight) {
let h = self.h[id].expect("only live nodes are opened");
let g = self.space.g(id);
let key = g
.saturating_times(weight.denominator())
.saturating_add(h.saturating_times(weight.numerator()));
self.open.push(id, key, g);
}
fn incumbent_cost(&self) -> Option<G::Cost> {
self.incumbent.map(|id| self.space.g(id))
}
fn lower_bound(&self, cost: G::Cost) -> G::Cost {
(0..self.space.len())
.filter(|&id| self.open_flag[id] || self.parked_flag[id])
.filter_map(|id| self.h[id].map(|h| self.space.g(id) + h))
.fold(
cost,
|bound, f| if f.cmp(&bound).is_lt() { f } else { bound },
)
}
fn incumbent_solution(&self) -> Solution<G::State, G::Action, G::Cost> {
self.space
.solution(self.incumbent.expect("called only with an incumbent"))
}
fn finish(self, complete: bool) -> AnytimeGraphResult<G> {
AnytimeResult {
solution: self.incumbent.map(|id| self.space.solution(id)),
complete,
stats: self.stats,
}
}
}