use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use core::mem;
use search_core::{Cost, Heuristic};
use crate::cost::add;
use crate::epsilon::Epsilon;
use crate::graph::Graph;
use crate::output::{Output, Solution, Stats};
pub fn boa_star<G, H, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
) -> Output<G::State, [C; 2]>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
run(graph, heuristic, start, is_goal, Tolerance::EXACT)
}
pub fn boa_star_approx<G, H, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
slack: C,
) -> Output<G::State, [C; 2]>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
run(graph, heuristic, start, is_goal, Tolerance::Additive(slack))
}
pub fn boa_star_eps<G, H, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
eps: Epsilon,
) -> Output<G::State, [C; 2]>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
run(graph, heuristic, start, is_goal, Tolerance::Relative(eps))
}
fn run<G, H, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
tolerance: Tolerance<C>,
) -> Output<G::State, [C; 2]>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
let mut search = Search::new(graph, heuristic, is_goal, tolerance);
search.push_start(start);
while search.step() {}
search.into_output()
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Tolerance<C> {
Additive(C),
Relative(Epsilon),
}
impl<C: Cost> Tolerance<C> {
pub(crate) const EXACT: Self = Self::Additive(C::ZERO);
fn covers(self, best: C, f2: C) -> bool {
match self {
Self::Additive(slack) => f2 + slack >= best,
Self::Relative(eps) => eps.within(best, f2),
}
}
}
pub(crate) struct Completion<C> {
pub(crate) primary: C,
pub(crate) secondary: C,
pub(crate) terminal: bool,
}
pub(crate) trait Completions<S, C> {
fn completion(&self, state: &S) -> Option<Completion<C>>;
fn suffix(&self, state: &S, out: &mut Vec<S>);
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct NoCompletions;
impl<S, C> Completions<S, C> for NoCompletions {
fn completion(&self, _state: &S) -> Option<Completion<C>> {
None
}
fn suffix(&self, _state: &S, _out: &mut Vec<S>) {}
}
struct Node<S, C> {
state: S,
g: [C; 2],
parent: Option<usize>,
}
pub(crate) struct Search<'a, G: Graph, H, C, P, K = NoCompletions> {
graph: &'a G,
heuristic: H,
is_goal: P,
tolerance: Tolerance<C>,
primary_bound: Option<C>,
nodes: Vec<Node<G::State, C>>,
open: BinaryHeap<Reverse<([C; 2], usize)>>,
g2_min: BTreeMap<G::State, C>,
best_goal_g2: Option<C>,
solutions: Vec<Solution<G::State, [C; 2]>>,
successors: Vec<(G::State, [C; 2])>,
stats: Stats,
completions: K,
secondary_floor: BTreeMap<G::State, C>,
first_expansion: Option<(G::State, C)>,
}
impl<'a, G, H, C, P> Search<'a, G, H, C, P>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
pub(crate) fn new(graph: &'a G, heuristic: H, is_goal: P, tolerance: Tolerance<C>) -> Self {
Search::with_completions(graph, heuristic, is_goal, tolerance, NoCompletions)
}
}
impl<'a, G, H, C, P, K> Search<'a, G, H, C, P, K>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost,
P: Fn(&G::State) -> bool,
K: Completions<G::State, C>,
{
pub(crate) fn with_completions(
graph: &'a G,
heuristic: H,
is_goal: P,
tolerance: Tolerance<C>,
completions: K,
) -> Self {
Self {
graph,
heuristic,
is_goal,
tolerance,
primary_bound: None,
nodes: Vec::new(),
open: BinaryHeap::new(),
g2_min: BTreeMap::new(),
best_goal_g2: None,
solutions: Vec::new(),
successors: Vec::new(),
stats: Stats::default(),
completions,
secondary_floor: BTreeMap::new(),
first_expansion: None,
}
}
pub(crate) fn raise_secondary(&mut self, state: G::State, floor: C) {
let entry = self.secondary_floor.entry(state).or_insert(floor);
*entry = (*entry).max(floor);
}
pub(crate) fn take_first_expansion(&mut self) -> Option<(G::State, C)> {
self.first_expansion.take()
}
pub(crate) fn step(&mut self) -> bool {
let Some(Reverse((f, index))) = self.open.pop() else {
return false;
};
if self.primary_bound.is_some_and(|bound| f[0] >= bound) {
return false;
}
self.process(f, index);
true
}
pub(crate) fn secondary_bound(&self) -> Option<C> {
self.best_goal_g2
}
pub(crate) fn set_primary_bound(&mut self, bound: Option<C>) {
self.primary_bound = bound;
}
pub(crate) fn into_output(self) -> Output<G::State, [C; 2]> {
Output {
solutions: self.solutions,
stats: self.stats,
}
}
pub(crate) fn push_start(&mut self, start: G::State) {
if let Some(h) = self.estimate(&start) {
self.push(start, [C::ZERO; 2], h, None);
}
}
fn estimate(&mut self, state: &G::State) -> Option<[C; 2]> {
let mut h = self.heuristic.estimate(state)?;
if let Some(&floor) = self.secondary_floor.get(state) {
h[1] = h[1].max(floor);
}
Some(h)
}
fn process(&mut self, f: [C; 2], index: usize) {
let node = &self.nodes[index];
if self.is_dominated(&node.state, node.g[1], f) {
return;
}
let (state, g) = (node.state.clone(), node.g);
if self.g2_min.insert(state.clone(), g[1]).is_none() {
self.first_expansion = Some((state.clone(), g[0]));
}
if let Some(completion) = self.completions.completion(&state) {
let cost = [g[0] + completion.primary, g[1] + completion.secondary];
if self.best_goal_g2.is_none_or(|best| cost[1] < best) {
let solution = self.early_solution(index, cost);
self.add_solution(solution);
}
if completion.terminal {
return;
}
}
if (self.is_goal)(&state) {
let solution = self.solution(index);
self.add_solution(solution);
} else {
self.expand(index);
}
}
fn add_solution(&mut self, solution: Solution<G::State, [C; 2]>) {
self.best_goal_g2 = Some(solution.cost[1]);
if self
.solutions
.last()
.is_some_and(|last| last.cost[0] == solution.cost[0])
{
self.solutions.pop();
}
self.solutions.push(solution);
}
fn early_solution(&self, index: usize, cost: [C; 2]) -> Solution<G::State, [C; 2]> {
let mut solution = self.solution(index);
self.completions
.suffix(&self.nodes[index].state, &mut solution.path);
solution.cost = cost;
solution
}
fn expand(&mut self, index: usize) {
self.stats.expanded += 1;
let mut successors = mem::take(&mut self.successors);
let g = self.nodes[index].g;
self.graph
.successors(&self.nodes[index].state, &mut successors);
for (state, weight) in successors.drain(..) {
let Some(h) = self.estimate(&state) else {
continue;
};
let g_next = add(g, weight);
if !self.is_dominated(&state, g_next[1], add(g_next, h)) {
self.push(state, g_next, h, Some(index));
}
}
self.successors = successors;
}
fn is_dominated(&self, state: &G::State, g2: C, f: [C; 2]) -> bool {
self.g2_min.get(state).is_some_and(|&min| g2 >= min)
|| self
.best_goal_g2
.is_some_and(|best| self.tolerance.covers(best, f[1]))
|| self.primary_bound.is_some_and(|bound| f[0] >= bound)
}
fn push(&mut self, state: G::State, g: [C; 2], h: [C; 2], parent: Option<usize>) {
let index = self.nodes.len();
self.nodes.push(Node { state, g, parent });
self.open.push(Reverse((add(g, h), index)));
self.stats.generated += 1;
}
fn solution(&self, index: usize) -> Solution<G::State, [C; 2]> {
let mut path = Vec::new();
let mut current = Some(index);
while let Some(i) = current {
path.push(self.nodes[i].state.clone());
current = self.nodes[i].parent;
}
path.reverse();
Solution {
cost: self.nodes[index].g,
path,
}
}
}