use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use search_core::Cost;
use crate::boa::{Completion, Completions};
pub(super) struct Bounds<S, C> {
from_start_1: Lex<S, C>,
from_start_2: Lex<S, C>,
to_goal_1: Lex<S, C>,
to_goal_2: Lex<S, C>,
}
impl<S: Clone + Ord, C: Cost> Bounds<S, C> {
pub(super) fn new(
start: &S,
goal: &S,
successors: impl Fn(&S, &mut Vec<(S, [C; 2])>),
predecessors: impl Fn(&S, &mut Vec<(S, [C; 2])>),
) -> Option<Self> {
let none = |_: &S| Some(C::ZERO);
let mut a = Lex::new(start.clone(), 0);
let ub2 = a.run_to(goal, &successors, &none)?;
let mut b = Lex::new(goal.clone(), 1);
let ub1 = b.run_to(start, &predecessors, &none)?;
a.run_within(ub1, &successors, &none);
b.run_within(ub2, &predecessors, &none);
let mut c = Lex::new(start.clone(), 1);
c.run_within(ub2, &successors, &|s| b.distance(s));
let mut d = Lex::new(goal.clone(), 0);
d.run_within(ub1, &predecessors, &|s| a.distance(s));
Some(Self {
from_start_1: a,
from_start_2: c,
to_goal_1: d,
to_goal_2: b,
})
}
#[cfg(feature = "parallel")]
pub(super) fn new_parallel(
start: &S,
goal: &S,
successors: impl Fn(&S, &mut Vec<(S, [C; 2])>) + Sync,
predecessors: impl Fn(&S, &mut Vec<(S, [C; 2])>) + Sync,
) -> Option<Self>
where
S: Send + Sync,
C: Send + Sync,
{
let none = |_: &S| Some(C::ZERO);
let (successors, predecessors) = (&successors, &predecessors);
let ((mut a, ub2), (mut b, ub1)) = std::thread::scope(|scope| {
let a = scope.spawn(|| {
let mut a = Lex::new(start.clone(), 0);
let ub2 = a.run_to(goal, successors, &none);
(a, ub2)
});
let mut b = Lex::new(goal.clone(), 1);
let ub1 = b.run_to(start, predecessors, &none);
(a.join().expect("search A panicked"), (b, ub1))
});
let (ub1, ub2) = (ub1?, ub2?);
std::thread::scope(|scope| {
scope.spawn(|| a.run_within(ub1, successors, &none));
b.run_within(ub2, predecessors, &none);
});
let (c, d) = std::thread::scope(|scope| {
let c = scope.spawn(|| {
let mut c = Lex::new(start.clone(), 1);
c.run_within(ub2, successors, &|s| b.distance(s));
c
});
let mut d = Lex::new(goal.clone(), 0);
d.run_within(ub1, predecessors, &|s| a.distance(s));
(c.join().expect("search C panicked"), d)
});
Some(Self {
from_start_1: a,
from_start_2: c,
to_goal_1: d,
to_goal_2: b,
})
}
pub(super) fn forward(&self, state: &S) -> Option<[C; 2]> {
Some([
self.to_goal_1.distance(state)?,
self.to_goal_2.distance(state)?,
])
}
pub(super) fn backward(&self, state: &S) -> Option<[C; 2]> {
Some([
self.from_start_1.distance(state)?,
self.from_start_2.distance(state)?,
])
}
}
pub(super) struct Forward<'a, S, C>(pub(super) &'a Bounds<S, C>);
impl<S: Clone + Ord, C: Cost> Completions<S, C> for Forward<'_, S, C> {
fn completion(&self, state: &S) -> Option<Completion<C>> {
let [primary, secondary] = self.0.to_goal_1.closed_cost(state)?;
let ub1 = self.0.to_goal_2.closed_cost(state)?[1];
Some(Completion {
primary,
secondary,
terminal: primary == ub1,
})
}
fn suffix(&self, state: &S, out: &mut Vec<S>) {
self.0.to_goal_1.path_to_source(state, out);
}
}
pub(super) struct Backward<'a, S, C>(pub(super) &'a Bounds<S, C>);
impl<S: Clone + Ord, C: Cost> Completions<S, C> for Backward<'_, S, C> {
fn completion(&self, state: &S) -> Option<Completion<C>> {
let [primary, secondary] = self.0.from_start_2.closed_cost(state)?;
let ub2 = self.0.from_start_1.closed_cost(state)?[1];
Some(Completion {
primary,
secondary,
terminal: primary == ub2,
})
}
fn suffix(&self, state: &S, out: &mut Vec<S>) {
self.0.from_start_2.path_to_source(state, out);
}
}
struct Lex<S, C> {
primary: usize,
open: BinaryHeap<Reverse<OpenEntry<S, C>>>,
labels: BTreeMap<S, Label<S, C>>,
edges: Vec<(S, [C; 2])>,
}
struct Label<S, C> {
g: [C; 2],
closed: bool,
parent: Option<S>,
}
type OpenEntry<S, C> = ([C; 2], C, S);
impl<S: Clone + Ord, C: Cost> Lex<S, C> {
fn new(source: S, primary: usize) -> Self {
let mut open = BinaryHeap::new();
let mut labels = BTreeMap::new();
labels.insert(
source.clone(),
Label {
g: [C::ZERO; 2],
closed: false,
parent: None,
},
);
open.push(Reverse(([C::ZERO; 2], C::ZERO, source)));
Self {
primary,
open,
labels,
edges: Vec::new(),
}
}
fn distance(&self, state: &S) -> Option<C> {
self.closed_cost(state).map(|g| g[0])
}
fn closed_cost(&self, state: &S) -> Option<[C; 2]> {
self.labels
.get(state)
.and_then(|label| label.closed.then_some(label.g))
}
fn path_to_source(&self, state: &S, out: &mut Vec<S>) {
let mut current = self.labels.get(state).and_then(|l| l.parent.as_ref());
while let Some(next) = current {
out.push(next.clone());
current = self.labels.get(next).and_then(|l| l.parent.as_ref());
}
}
fn run_to(
&mut self,
target: &S,
neighbours: &impl Fn(&S, &mut Vec<(S, [C; 2])>),
heuristic: &impl Fn(&S) -> Option<C>,
) -> Option<C> {
loop {
let ([_, g_secondary], state) = self.expand_next(neighbours, heuristic)?;
if state == *target {
return Some(g_secondary);
}
}
}
fn run_within(
&mut self,
bound: C,
neighbours: &impl Fn(&S, &mut Vec<(S, [C; 2])>),
heuristic: &impl Fn(&S) -> Option<C>,
) {
while self
.open
.peek()
.is_some_and(|Reverse((key, _, _))| key[0] <= bound)
{
self.expand_next(neighbours, heuristic);
}
}
fn expand_next(
&mut self,
neighbours: &impl Fn(&S, &mut Vec<(S, [C; 2])>),
heuristic: &impl Fn(&S) -> Option<C>,
) -> Option<([C; 2], S)> {
loop {
let Reverse((key, g_primary, state)) = self.open.pop()?;
let label = self
.labels
.get_mut(&state)
.expect("pushed states have a label");
if label.closed {
continue;
}
label.closed = true;
self.push_neighbours(&state, [g_primary, key[1]], neighbours, heuristic);
return Some((key, state));
}
}
fn push_neighbours(
&mut self,
state: &S,
g: [C; 2],
neighbours: &impl Fn(&S, &mut Vec<(S, [C; 2])>),
heuristic: &impl Fn(&S) -> Option<C>,
) {
let secondary = 1 - self.primary;
neighbours(state, &mut self.edges);
for (next, weight) in self.edges.drain(..) {
let g_next = [g[0] + weight[self.primary], g[1] + weight[secondary]];
let label = self.labels.get(&next);
if label.is_some_and(|label| label.closed || label.g <= g_next) {
continue;
}
let Some(h) = heuristic(&next) else {
continue;
};
self.labels.insert(
next.clone(),
Label {
g: g_next,
closed: false,
parent: Some(state.clone()),
},
);
self.open
.push(Reverse(([g_next[0] + h, g_next[1]], g_next[0], next)));
}
}
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use super::Bounds;
const EDGES: [(u8, u8, [u32; 2]); 5] = [
(0, 1, [1, 9]),
(0, 2, [5, 1]),
(2, 1, [5, 1]),
(1, 3, [1, 1]),
(0, 4, [50, 50]),
];
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "the neighbour callback signature"
)]
fn successors(s: &u8, out: &mut Vec<(u8, [u32; 2])>) {
out.extend(EDGES.iter().filter(|e| e.0 == *s).map(|e| (e.1, e.2)));
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "the neighbour callback signature"
)]
fn predecessors(s: &u8, out: &mut Vec<(u8, [u32; 2])>) {
out.extend(EDGES.iter().filter(|e| e.1 == *s).map(|e| (e.0, e.2)));
}
#[test]
fn bounded_distances() {
let bounds = Bounds::new(&0, &3, successors, predecessors).expect("reachable");
assert_eq!(bounds.forward(&0), Some([2, 3]));
assert_eq!(bounds.forward(&2), Some([6, 2]));
assert_eq!(bounds.backward(&3), Some([2, 3]));
assert_eq!(bounds.backward(&1), Some([1, 2]));
assert_eq!(bounds.backward(&4), None);
assert_eq!(bounds.forward(&4), None);
}
#[test]
fn unreachable_goal() {
assert!(Bounds::new(&3, &0, successors, predecessors).is_none());
}
}