use alloc::vec::Vec;
use core::hash::{BuildHasher, Hash};
use hashbrown::{DefaultHashBuilder, HashTable};
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::anytime::{AnytimeGraphResult, AnytimeResult};
use crate::cost::Extended;
use crate::outcome::{Solution, Stats};
use crate::problem::{Successors, collect_successors};
pub fn beam_stack_search<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
width: usize,
on_solution: impl FnMut(&Solution<G::State, G::Action, 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>,
{
beam_stack_search_multi(graph, [start], goal, heuristic, width, on_solution, budget)
}
pub fn beam_stack_search_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
width: usize,
on_solution: impl FnMut(&Solution<G::State, G::Action, 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>,
{
assert!(width > 0, "the beam width must be at least 1");
let mut search = BeamStack {
graph,
goal,
heuristic,
width,
layers: Vec::new(),
items: Vec::new(),
index: HashTable::new(),
hasher: DefaultHashBuilder::default(),
upper: Extended::Infinite,
best: None,
stats: Stats::default(),
buffer: Vec::new(),
};
let complete = search.run(starts, on_solution, budget);
AnytimeResult {
solution: search.best,
complete,
stats: search.stats,
}
}
struct Node<S, A, C> {
state: S,
g: C,
f: C,
parent: Option<(usize, A, C)>,
}
struct Layer<S, A, C> {
nodes: Vec<Node<S, A, C>>,
expanded: usize,
}
impl<S, A, C> Layer<S, A, C> {
fn new() -> Self {
Self {
nodes: Vec::new(),
expanded: 0,
}
}
}
struct Item<C> {
low: C,
high: Extended<C>,
}
impl<C: Cost> Item<C> {
fn full() -> Self {
Self {
low: C::ZERO,
high: Extended::Infinite,
}
}
}
type Slot = (usize, usize);
struct BeamStack<'a, G: Successors, T: ?Sized, H> {
graph: &'a G,
goal: &'a T,
heuristic: H,
width: usize,
layers: Vec<Layer<G::State, G::Action, G::Cost>>,
items: Vec<Item<G::Cost>>,
index: HashTable<Slot>,
hasher: DefaultHashBuilder,
upper: Extended<G::Cost>,
best: Option<Solution<G::State, G::Action, G::Cost>>,
stats: Stats,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<G, T, H> BeamStack<'_, 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,
starts: impl IntoIterator<Item = G::State>,
mut on_solution: impl FnMut(&Solution<G::State, G::Action, G::Cost>),
mut budget: impl Budget<Stats>,
) -> bool {
if self.seed(starts) {
return true;
}
loop {
if !self.sweep(&mut on_solution, &mut budget) {
return false;
}
if !self.backtrack() {
return true;
}
}
}
fn seed(&mut self, starts: impl IntoIterator<Item = G::State>) -> bool {
self.layers.push(Layer::new());
for start in starts {
if self.find(&start, 0).is_some() {
continue;
}
if self.goal.is_goal(&start) {
self.best = Some(Solution {
states: alloc::vec![start],
actions: Vec::new(),
cost: G::Cost::ZERO,
});
return true;
}
if let Some(h) = self.heuristic.estimate(&start) {
self.insert(Node {
state: start,
g: G::Cost::ZERO,
f: h,
parent: None,
});
}
}
self.complete_layer(0);
self.layers.push(Layer::new());
self.items.push(Item::full());
false
}
fn sweep(
&mut self,
on_solution: &mut impl FnMut(&Solution<G::State, G::Action, G::Cost>),
budget: &mut impl Budget<Stats>,
) -> bool {
loop {
let depth = self.layers.len() - 2;
let Some(position) = self.next_open(depth) else {
self.complete_layer(depth + 1);
if self.layers[depth + 1].nodes.is_empty() {
return true;
}
self.layers.push(Layer::new());
self.items.push(Item::full());
continue;
};
let node = &self.layers[depth].nodes[position];
if self.goal.is_goal(&node.state) {
self.upper = Extended::Finite(node.g);
let solution = self.solution(depth, position);
on_solution(&solution);
self.best = Some(solution);
continue;
}
if budget.exhausted(&self.stats) {
return false;
}
self.expand(depth, position);
}
}
fn next_open(&mut self, depth: usize) -> Option<usize> {
let upper = self.upper;
let layer = &mut self.layers[depth];
while let Some(node) = layer.nodes.get(layer.expanded) {
layer.expanded += 1;
if Extended::Finite(node.f) < upper {
return Some(layer.expanded - 1);
}
}
None
}
fn expand(&mut self, depth: usize, position: usize) {
let node = &self.layers[depth].nodes[position];
let g = node.g;
self.stats.expanded += 1;
self.stats.generated += collect_successors(self.graph, &node.state, &mut self.buffer);
let mut buffer = core::mem::take(&mut self.buffer);
for (action, state, cost) in buffer.drain(..) {
self.admit(depth + 1, state, g + cost, (position, action, cost));
}
self.buffer = buffer;
}
fn admit(
&mut self,
depth: usize,
state: G::State,
g: G::Cost,
parent: (usize, G::Action, G::Cost),
) {
let mut same_layer = None;
for &(layer, position) in self.index.iter_hash(self.hasher.hash_one(&state)) {
let node = &self.layers[layer].nodes[position];
if node.state != state {
continue;
}
if node.g <= g {
return;
}
if layer == depth {
same_layer = Some(position);
}
}
let Some(h) = self.heuristic.estimate(&state) else {
return;
};
let f = g.saturating_add(h);
let item = &self.items[depth - 1];
if f < item.low || Extended::Finite(f) >= item.high.min(self.upper) {
return;
}
let node = Node {
state,
g,
f,
parent: Some(parent),
};
match same_layer {
Some(position) => self.layers[depth].nodes[position] = node,
None => self.insert(node),
}
}
fn complete_layer(&mut self, depth: usize) {
self.unindex(depth);
let upper = self.upper;
let width = self.width;
let nodes = &mut self.layers[depth].nodes;
nodes.retain(|node| Extended::Finite(node.f) < upper);
nodes.sort_by_key(|node| node.f);
if depth > 0 && nodes.len() > width {
let last = nodes[width - 1].f;
let keep = nodes.partition_point(|node| node.f <= last);
if keep < nodes.len() {
let pruned = nodes[keep].f;
nodes.truncate(keep);
self.items[depth - 1].high = Extended::Finite(pruned);
}
}
self.reindex(depth);
}
fn backtrack(&mut self) -> bool {
while self
.items
.last()
.is_some_and(|item| item.high >= self.upper)
{
self.items.pop();
}
let Some(item) = self.items.last_mut() else {
return false;
};
let Extended::Finite(high) = item.high else {
unreachable!("an infinite interval end is popped");
};
item.low = high;
item.high = Extended::Infinite;
let depth = self.items.len() - 1;
while self.layers.len() > depth + 1 {
let last = self.layers.len() - 1;
self.unindex(last);
self.layers.pop();
}
self.layers[depth].expanded = 0;
self.layers.push(Layer::new());
true
}
fn solution(&self, depth: usize, position: usize) -> Solution<G::State, G::Action, G::Cost> {
let mut states = Vec::new();
let mut actions = Vec::new();
let mut cost = G::Cost::ZERO;
let mut at = (depth, position);
loop {
let node = &self.layers[at.0].nodes[at.1];
states.push(node.state.clone());
let Some((parent, action, edge_cost)) = &node.parent else {
break;
};
actions.push(action.clone());
cost = cost + *edge_cost;
at = (at.0 - 1, *parent);
}
states.reverse();
actions.reverse();
Solution {
states,
actions,
cost,
}
}
fn find(&self, state: &G::State, depth: usize) -> Option<usize> {
self.index
.find(self.hasher.hash_one(state), |&(layer, position)| {
layer == depth && self.layers[layer].nodes[position].state == *state
})
.map(|&(_, position)| position)
}
fn insert(&mut self, node: Node<G::State, G::Action, G::Cost>) {
let depth = self.layers.len() - 1;
let position = self.layers[depth].nodes.len();
let hash = self.hasher.hash_one(&node.state);
self.layers[depth].nodes.push(node);
let (layers, hasher) = (&self.layers, &self.hasher);
self.index
.insert_unique(hash, (depth, position), |&(layer, position)| {
hasher.hash_one(&layers[layer].nodes[position].state)
});
}
fn unindex(&mut self, depth: usize) {
let layers = &self.layers;
for (position, node) in layers[depth].nodes.iter().enumerate() {
let hash = self.hasher.hash_one(&node.state);
if let Ok(entry) = self
.index
.find_entry(hash, |&slot| slot == (depth, position))
{
entry.remove();
}
}
}
fn reindex(&mut self, depth: usize) {
let (layers, hasher) = (&self.layers, &self.hasher);
for (position, node) in layers[depth].nodes.iter().enumerate() {
self.index.insert_unique(
hasher.hash_one(&node.state),
(depth, position),
|&(layer, position)| hasher.hash_one(&layers[layer].nodes[position].state),
);
}
}
}