mod stack;
use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic};
pub use stack::{beam_stack_search, beam_stack_search_multi};
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 beam_search<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
width: usize,
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>,
{
beam_search_multi(graph, [start], goal, heuristic, width, budget)
}
pub fn beam_search_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
width: usize,
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>,
{
assert!(width > 0, "the beam width must be at least 1");
let (space, start_goal) = SearchSpace::seed(starts, goal);
let mut beam = Beam {
graph,
goal,
heuristic,
width,
space,
h: Vec::new(),
depth: Vec::new(),
pruned: false,
stats: Stats::default(),
buffer: Vec::new(),
};
let outcome = match start_goal {
Some(found) => Outcome::Found(beam.space.solution(found)),
None => beam.run(budget),
};
SearchResult {
outcome,
stats: beam.stats,
}
}
struct Beam<'a, G: Successors, T: ?Sized, H> {
graph: &'a G,
goal: &'a T,
heuristic: H,
width: usize,
space: SearchSpace<G::State, G::Action, G::Cost>,
h: Vec<Option<G::Cost>>,
depth: Vec<usize>,
pruned: bool,
stats: Stats,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<G, T, H> Beam<'_, 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(&mut self, mut budget: impl Budget<Stats>) -> Outcome<G::State, G::Action, G::Cost> {
let mut layer: Vec<NodeId> = (0..self.space.len())
.filter(|&id| self.evaluate(id, 0))
.collect();
for depth in 0.. {
self.keep_best(&mut layer);
if layer.is_empty() {
break;
}
let mut next = Vec::new();
for &id in &layer {
if self.goal.is_goal(self.space.state(id)) {
return Outcome::Found(self.space.solution(id));
}
if budget.exhausted(&self.stats) {
return Outcome::LimitReached;
}
self.expand(id, depth + 1, &mut next);
}
layer = next;
}
if self.pruned {
Outcome::Cutoff
} else {
Outcome::Unsolvable
}
}
fn expand(&mut self, id: NodeId, depth: usize, next: &mut Vec<NodeId>) {
self.stats.expanded += 1;
self.stats.generated +=
collect_successors(self.graph, self.space.state(id), &mut self.buffer);
let mut buffer = core::mem::take(&mut self.buffer);
for (action, state, cost) in buffer.drain(..) {
if self
.space
.find(&state)
.is_some_and(|known| self.depth[known] < depth)
{
continue;
}
if let Reach::New(child) = self.space.reach(state, id, action, cost, true) {
if self.evaluate(child, depth) {
next.push(child);
}
}
}
self.buffer = buffer;
}
fn evaluate(&mut self, id: NodeId, depth: usize) -> bool {
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.depth.push(depth);
h.is_some()
}
fn keep_best(&mut self, layer: &mut Vec<NodeId>) {
layer.sort_by_key(|&id| {
let h = self.h[id].expect("dead ends never join a layer");
self.space.g(id).saturating_add(h)
});
if layer.len() > self.width {
layer.truncate(self.width);
self.pruned = true;
}
}
}