use alloc::vec::Vec;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::best_first::GraphResult;
use crate::cost::Extended;
use crate::depth_first::{distinct, goal_root};
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
use crate::problem::{Successors, collect_successors};
pub fn rbfs<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
rbfs_multi(graph, [start], goal, heuristic, budget)
}
pub fn rbfs_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 + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let roots = distinct(starts);
if let Some(solution) = goal_root(&roots, goal) {
return SearchResult {
outcome: Outcome::Found(solution),
stats: Stats::default(),
};
}
let mut search = Rbfs {
graph,
goal,
heuristic,
stats: Stats::default(),
};
let outcome = search.run(roots, budget);
SearchResult {
outcome,
stats: search.stats,
}
}
struct Child<S, A, C> {
state: S,
via: Option<(A, C)>,
g: C,
f: Extended<C>,
value: Extended<C>,
}
struct Frame<S, A, C> {
node: Child<S, A, C>,
index: usize,
bound: Extended<C>,
children: Vec<Child<S, A, C>>,
}
struct Rbfs<'a, G, T: ?Sized, H> {
graph: &'a G,
goal: &'a T,
heuristic: H,
stats: Stats,
}
impl<G, T, H> Rbfs<'_, G, T, H>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
fn run(
&mut self,
roots: Vec<G::State>,
mut budget: impl Budget<Stats>,
) -> Outcome<G::State, G::Action, G::Cost> {
let mut base: Vec<_> = roots
.into_iter()
.map(|state| self.child(state, None, G::Cost::ZERO, None))
.collect();
let mut stack: Vec<Frame<G::State, G::Action, G::Cost>> = Vec::new();
loop {
let (children, bound) = stack.last().map_or((&base, Extended::Infinite), |frame| {
(&frame.children, frame.bound)
});
let (best, second) = best_two(children);
let Some(best) = best.filter(|&best| {
let value = children[best].value;
value <= bound && value != Extended::Infinite
}) else {
let value = best.map_or(Extended::Infinite, |best| children[best].value);
let Some(frame) = stack.pop() else {
return Outcome::Unsolvable;
};
let parent = stack
.last_mut()
.map_or(&mut base, |frame| &mut frame.children);
parent[frame.index].value = value;
continue;
};
let node = &children[best];
if self.goal.is_goal(&node.state) {
return Outcome::Found(path(&stack, node));
}
if budget.exhausted(&self.stats) {
return Outcome::LimitReached;
}
let frame = self.descend(&stack, node, best, bound.min(second));
stack.push(frame);
}
}
fn descend(
&mut self,
stack: &[Frame<G::State, G::Action, G::Cost>],
node: &Child<G::State, G::Action, G::Cost>,
index: usize,
bound: Extended<G::Cost>,
) -> Frame<G::State, G::Action, G::Cost> {
let mut edges = Vec::new();
self.stats.expanded += 1;
self.stats.generated += collect_successors(self.graph, &node.state, &mut edges);
let inherited = (node.f < node.value).then_some(node.value);
let children = edges
.into_iter()
.filter(|(_, state, _)| {
*state != node.state && stack.iter().all(|frame| frame.node.state != *state)
})
.map(|(action, state, cost)| {
let mut child = self.child(state, Some((action, cost)), node.g + cost, inherited);
child.value = child.value.max(child.f);
child
})
.collect();
Frame {
node: Child {
state: node.state.clone(),
via: node.via.clone(),
g: node.g,
f: node.f,
value: node.value,
},
index,
bound,
children,
}
}
fn child(
&mut self,
state: G::State,
via: Option<(G::Action, G::Cost)>,
g: G::Cost,
inherited: Option<Extended<G::Cost>>,
) -> Child<G::State, G::Action, G::Cost> {
let f = Extended::f(g, self.heuristic.estimate(&state));
Child {
state,
via,
g,
f,
value: inherited.unwrap_or(f),
}
}
}
fn best_two<S, A, C: Cost>(children: &[Child<S, A, C>]) -> (Option<usize>, Extended<C>) {
let mut best: Option<usize> = None;
let mut second = Extended::Infinite;
for (index, child) in children.iter().enumerate() {
match best {
Some(current) if child.value >= children[current].value => {
second = second.min(child.value);
}
Some(current) => {
second = second.min(children[current].value);
best = Some(index);
}
None => best = Some(index),
}
}
(best, second)
}
fn path<S: Clone, A: Clone, C: Cost>(
stack: &[Frame<S, A, C>],
last: &Child<S, A, C>,
) -> Solution<S, A, C> {
let nodes = || stack.iter().map(|frame| &frame.node).chain([last]);
let states = nodes().map(|node| node.state.clone()).collect();
let actions = nodes()
.filter_map(|node| node.via.as_ref().map(|(action, _)| action.clone()))
.collect();
let cost = nodes()
.filter_map(|node| node.via.as_ref().map(|&(_, cost)| cost))
.fold(C::ZERO, |sum, cost| sum + cost);
Solution {
states,
actions,
cost,
}
}