use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::best_first::GraphResult;
use crate::outcome::{Outcome, SearchResult, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
pub fn fringe_search<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
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>,
{
fringe_search_multi(graph, [start], goal, heuristic, budget)
}
pub fn fringe_search_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
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>,
{
let (space, start_goal) = SearchSpace::seed(starts, goal);
let mut fringe = Fringe::new(graph, goal, heuristic, space);
if let Some(found) = start_goal {
return fringe.finish(Outcome::Found(fringe.space.solution(found)));
}
let outcome = fringe.run(budget);
fringe.finish(outcome)
}
type GraphOutcome<G> =
Outcome<<G as Successors>::State, <G as Successors>::Action, <G as Successors>::Cost>;
const UNLISTED: u64 = u64::MAX;
type Entry = (NodeId, u64);
struct Fringe<'a, G: Successors, T: ?Sized, H> {
graph: &'a G,
goal: &'a T,
heuristic: H,
space: SearchSpace<G::State, G::Action, G::Cost>,
h: Vec<Option<G::Cost>>,
ticket: Vec<u64>,
tickets: u64,
now: Vec<Entry>,
later: Vec<Entry>,
stats: Stats,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<'a, G, T, H> Fringe<'a, 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 new(
graph: &'a G,
goal: &'a T,
heuristic: H,
space: SearchSpace<G::State, G::Action, G::Cost>,
) -> Self {
Self {
graph,
goal,
heuristic,
space,
h: Vec::new(),
ticket: Vec::new(),
tickets: 0,
now: Vec::new(),
later: Vec::new(),
stats: Stats::default(),
buffer: Vec::new(),
}
}
fn run(&mut self, mut budget: impl Budget<Stats>) -> GraphOutcome<G> {
for start in 0..self.space.len() {
self.evaluate(start);
}
self.now.reverse();
let Some(mut threshold) = self.now.iter().filter_map(|&(id, _)| self.f(id)).min() else {
return Outcome::Unsolvable;
};
loop {
let deferred = match self.iterate(threshold, &mut budget) {
Ok(deferred) => deferred,
Err(outcome) => return outcome,
};
let Some(next) = deferred else {
return Outcome::Unsolvable;
};
threshold = next;
core::mem::swap(&mut self.now, &mut self.later);
self.now.reverse();
}
}
fn iterate(
&mut self,
threshold: G::Cost,
budget: &mut impl Budget<Stats>,
) -> Result<Option<G::Cost>, GraphOutcome<G>> {
let mut deferred: Option<G::Cost> = None;
while let Some((id, ticket)) = self.now.pop() {
if ticket != self.ticket[id] {
continue;
}
let f = self.f(id).expect("dead ends are never listed");
if f > threshold {
deferred = Some(deferred.map_or(f, |old| old.min(f)));
self.later.push((id, ticket));
continue;
}
if self.goal.is_goal(self.space.state(id)) {
return Err(Outcome::Found(self.space.solution(id)));
}
if budget.exhausted(&self.stats) {
return Err(Outcome::LimitReached);
}
self.expand(id);
}
Ok(deferred)
}
fn expand(&mut self, id: NodeId) {
self.stats.expanded += 1;
self.ticket[id] = UNLISTED;
self.stats.generated +=
collect_successors(self.graph, self.space.state(id), &mut self.buffer);
let first = self.now.len();
let mut buffer = core::mem::take(&mut self.buffer);
for (action, state, cost) in buffer.drain(..) {
match self.space.reach(state, id, action, cost, true) {
Reach::New(child) => self.evaluate(child),
Reach::Improved(child) => self.relist(child),
Reach::Stale => {}
}
}
self.buffer = buffer;
self.now[first..].reverse();
}
fn evaluate(&mut self, id: NodeId) {
debug_assert_eq!(id, self.h.len(), "nodes are evaluated in creation order");
let h = self.heuristic.estimate(self.space.state(id));
self.h.push(h);
self.ticket.push(UNLISTED);
if h.is_some() {
self.list(id);
}
}
fn relist(&mut self, id: NodeId) {
if self.h[id].is_none() {
return;
}
if self.ticket[id] == UNLISTED {
self.stats.reopened += 1;
}
self.list(id);
}
fn list(&mut self, id: NodeId) {
self.ticket[id] = self.tickets;
self.now.push((id, self.tickets));
self.tickets += 1;
}
fn f(&self, id: NodeId) -> Option<G::Cost> {
self.h[id].map(|h| self.space.g(id).saturating_add(h))
}
fn finish(&self, outcome: GraphOutcome<G>) -> GraphResult<G> {
SearchResult {
outcome,
stats: self.stats,
}
}
}