use core::cmp::Reverse;
use core::hash::Hash;
use alloc::vec::Vec;
use search_core::{Budget, Cost, Heuristic};
use crate::best_first::GraphResult;
use crate::bidirectional::mixed::{Both, Mixed, MixedGraph, Split, unmix};
use crate::bidirectional::{
BidirectionalGraph, Core, Direction, Equality, MeetRelation, MeetResult, Meeting, Meets,
RegressionGraph,
};
use crate::keyed_set::KeyedSet;
use crate::outcome::Stats;
use crate::problem::Predecessors;
use crate::problem::Successors;
use crate::space::NodeId;
pub fn nbs<G, HF, HB>(
graph: &G,
start: G::State,
goals: impl IntoIterator<Item = G::State>,
forward: HF,
backward: HB,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: BidirectionalGraph,
G::State: Clone + Hash + Eq,
<G as Successors>::Action: Clone,
HF: Heuristic<G::State, <G as Successors>::Cost>,
HB: Heuristic<G::State, <G as Successors>::Cost>,
{
nbs_multi(graph, [start], goals, forward, backward, budget)
}
pub fn nbs_multi<G, HF, HB>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goals: impl IntoIterator<Item = G::State>,
forward: HF,
backward: HB,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: BidirectionalGraph,
G::State: Clone + Hash + Eq,
<G as Successors>::Action: Clone,
HF: Heuristic<G::State, <G as Successors>::Cost>,
HB: Heuristic<G::State, <G as Successors>::Cost>,
{
let core = Core::new(
graph,
starts,
goals,
forward,
backward,
None::<Meeting<G, Equality>>,
);
Nbs::new(core).run(budget)
}
pub fn nbs_meet<G, HF, HB, M>(
graph: &G,
starts: impl IntoIterator<Item = <G as Successors>::State>,
goals: impl IntoIterator<Item = <G as Predecessors>::Node>,
forward: HF,
backward: HB,
meet: M,
budget: impl Budget<Stats>,
) -> MeetResult<G>
where
G: RegressionGraph,
<G as Successors>::State: Clone + Hash + Eq,
<G as Predecessors>::Node: Clone + Hash + Eq,
<G as Successors>::Action: Clone + PartialEq,
HF: Heuristic<<G as Successors>::State, <G as Successors>::Cost>
+ Heuristic<<G as Predecessors>::Node, <G as Successors>::Cost>,
HB: Heuristic<<G as Successors>::State, <G as Successors>::Cost>
+ Heuristic<<G as Predecessors>::Node, <G as Successors>::Cost>,
M: MeetRelation<<G as Successors>::State, <G as Predecessors>::Node>,
{
let mixed = MixedGraph(graph);
let core = Core::new(
&mixed,
starts.into_iter().map(Mixed::State),
goals.into_iter().map(Mixed::Node),
Both(forward),
Both(backward),
Some(Meeting::new(Split(meet))),
);
unmix(Nbs::new(core).run(budget))
}
type Key<C> = (C, Reverse<C>);
struct Nbs<'a, G: BidirectionalGraph, HF, HB, M> {
core: Core<'a, G, HF, HB, M>,
waiting: [KeyedSet<Key<<G as Successors>::Cost>>; 2],
ready: [KeyedSet<Key<<G as Successors>::Cost>>; 2],
clb: <G as Successors>::Cost,
}
impl<'a, G, HF, HB, M> Nbs<'a, G, HF, HB, M>
where
G: BidirectionalGraph,
G::State: Clone + Hash + Eq,
<G as Successors>::Action: Clone,
HF: Heuristic<G::State, <G as Successors>::Cost>,
HB: Heuristic<G::State, <G as Successors>::Cost>,
M: Meets<G::State>,
{
fn new(core: Core<'a, G, HF, HB, M>) -> Self {
let mut search = Self {
core,
waiting: [KeyedSet::new(), KeyedSet::new()],
ready: [KeyedSet::new(), KeyedSet::new()],
clb: <G as Successors>::Cost::ZERO,
};
for direction in [Direction::Forward, Direction::Backward] {
for id in 0..search.core.side(direction).space.len() {
search.queue(direction, id);
}
}
search
}
fn run(mut self, mut budget: impl Budget<Stats>) -> GraphResult<G> {
let mut touched = Vec::new();
while !self.side_exhausted() && !self.core.proven(self.clb) {
self.promote(Direction::Forward);
self.promote(Direction::Backward);
let Some((u, v)) = self.ready_pair() else {
self.raise_clb();
continue;
};
for (direction, node) in [(Direction::Forward, u), (Direction::Backward, v)] {
if budget.exhausted(&self.core.stats) {
return self.core.finish(false);
}
self.ready[direction.index()].remove(node);
self.core.expand(direction, node, true, &mut touched);
for id in touched.drain(..) {
self.queue(direction, id);
}
}
}
self.core.finish(true)
}
fn side_exhausted(&self) -> bool {
(0..2).any(|side| self.waiting[side].is_empty() && self.ready[side].is_empty())
}
fn promote(&mut self, direction: Direction) {
let side = direction.index();
while let Some((&(f, Reverse(g)), id)) = self.waiting[side].first() {
if f.cmp(&self.clb).is_gt() {
break;
}
self.waiting[side].remove(id);
self.ready[side].insert(id, (g, Reverse(f)));
}
}
fn ready_pair(&self) -> Option<(NodeId, NodeId)> {
let (forward, u) = self.ready[0].first()?;
let (backward, v) = self.ready[1].first()?;
(forward.0 + backward.0)
.cmp(&self.clb)
.is_le()
.then_some((u, v))
}
fn raise_clb(&mut self) {
let waiting = self
.waiting
.iter()
.filter_map(|queue| queue.first().map(|(key, _)| key.0));
let ready = match (self.ready[0].first(), self.ready[1].first()) {
(Some((forward, _)), Some((backward, _))) => Some(forward.0 + backward.0),
_ => None,
};
let next = waiting
.chain(ready)
.reduce(|a, b| if b.cmp(&a).is_lt() { b } else { a })
.expect("both sides have open states");
debug_assert!(next.cmp(&self.clb).is_gt(), "CLB must grow");
self.clb = next;
}
fn queue(&mut self, direction: Direction, id: NodeId) {
let Some((h, _)) = self.core.h(direction, id) else {
return;
};
let g = self.core.g(direction, id);
let side = direction.index();
self.ready[side].remove(id);
self.waiting[side].insert(id, (g + h, Reverse(g)));
}
}