mod bfs;
mod frontier;
mod meet;
mod mixed;
mod nbs;
pub use bfs::{bidirectional_bfs, bidirectional_bfs_meet, bidirectional_bfs_multi};
pub use frontier::{
bae_star, bae_star_meet, bae_star_multi, bidirectional_dijkstra, bidirectional_dijkstra_meet,
bidirectional_dijkstra_multi, dibbs, dibbs_meet, dibbs_multi,
};
pub use meet::{MeetFn, MeetRelation, MeetResult, ReplayError, meet_fn};
pub use mixed::RegressionGraph;
pub use nbs::{nbs, nbs_meet, nbs_multi};
use meet::{Direction, Equality, Meeting, Meets};
use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Cost, Heuristic};
use crate::best_first::GraphResult;
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
use crate::problem::{Predecessors, Successors, collect_predecessors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
pub trait BidirectionalGraph:
Successors
+ Predecessors<
Node = <Self as Successors>::State,
Action = <Self as Successors>::Action,
Cost = <Self as Successors>::Cost,
>
{
}
impl<G> BidirectionalGraph for G where
G: Successors
+ Predecessors<
Node = <G as Successors>::State,
Action = <G as Successors>::Action,
Cost = <G as Successors>::Cost,
>
{
}
struct Side<S, A, C> {
space: SearchSpace<S, A, C>,
h: Vec<Option<(C, C)>>,
closed: Vec<bool>,
}
#[derive(Debug, Clone, Copy)]
struct Meet<C> {
cost: C,
forward: NodeId,
backward: NodeId,
}
struct Core<'a, G: Successors, HF, HB, M = Equality> {
graph: &'a G,
forward_h: HF,
backward_h: HB,
sides: [Side<G::State, <G as Successors>::Action, <G as Successors>::Cost>; 2],
stats: Stats,
meet: Option<Meet<<G as Successors>::Cost>>,
buffer: Vec<(<G as Successors>::Action, G::State, <G as Successors>::Cost)>,
meeting: Option<Meeting<G, M>>,
candidates: Vec<NodeId>,
}
impl<'a, G, HF, HB, M> Core<'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(
graph: &'a G,
starts: impl IntoIterator<Item = G::State>,
goals: impl IntoIterator<Item = G::State>,
forward_h: HF,
backward_h: HB,
meeting: Option<Meeting<G, M>>,
) -> Self {
let never = |_: &G::State| false;
let side = |space: SearchSpace<_, _, _>| Side {
space,
h: Vec::new(),
closed: Vec::new(),
};
let mut core = Self {
graph,
forward_h,
backward_h,
sides: [
side(SearchSpace::seed(starts, &never).0),
side(SearchSpace::seed(goals, &never).0),
],
stats: Stats::default(),
meet: None,
buffer: Vec::new(),
meeting,
candidates: Vec::new(),
};
for direction in [Direction::Forward, Direction::Backward] {
for id in 0..core.side(direction).space.len() {
core.evaluate(direction, id);
core.index(direction, id);
core.check_meet(direction, id);
}
}
core
}
fn side(
&self,
direction: Direction,
) -> &Side<G::State, <G as Successors>::Action, <G as Successors>::Cost> {
&self.sides[direction.index()]
}
fn g(&self, direction: Direction, id: NodeId) -> <G as Successors>::Cost {
self.side(direction).space.g(id)
}
fn h(
&self,
direction: Direction,
id: NodeId,
) -> Option<(<G as Successors>::Cost, <G as Successors>::Cost)> {
self.side(direction).h[id]
}
fn mu(&self) -> Option<<G as Successors>::Cost> {
self.meet.map(|meet| meet.cost)
}
fn proven(&self, bound: <G as Successors>::Cost) -> bool {
self.mu().is_some_and(|mu| bound.cmp(&mu).is_ge())
}
fn expand(
&mut self,
direction: Direction,
node: NodeId,
improve: bool,
touched: &mut Vec<NodeId>,
) {
self.stats.expanded += 1;
self.sides[direction.index()].closed[node] = true;
self.generate(direction, node);
let mut buffer = core::mem::take(&mut self.buffer);
for (action, state, cost) in buffer.drain(..) {
let side = &mut self.sides[direction.index()];
let id = match side.space.reach(state, node, action, cost, improve) {
Reach::New(id) => {
self.evaluate(direction, id);
self.index(direction, id);
id
}
Reach::Improved(id) => {
if self.side(direction).closed[id] {
self.stats.reopened += 1;
}
id
}
Reach::Stale => continue,
};
self.check_meet(direction, id);
if self.h(direction, id).is_some() {
touched.push(id);
}
}
self.buffer = buffer;
}
fn generate(&mut self, direction: Direction, node: NodeId) {
let state = self.sides[direction.index()].space.state(node);
self.stats.generated += match direction {
Direction::Forward => collect_successors(self.graph, state, &mut self.buffer),
Direction::Backward => collect_predecessors(self.graph, state, &mut self.buffer),
};
}
fn evaluate(&mut self, direction: Direction, id: NodeId) {
let side = &mut self.sides[direction.index()];
let state = side.space.state(id);
let forward = self.forward_h.estimate(state);
let backward = self.backward_h.estimate(state);
let h = match direction {
Direction::Forward => forward.zip(backward),
Direction::Backward => backward.zip(forward),
};
debug_assert_eq!(id, side.h.len(), "nodes are evaluated in creation order");
side.h.push(h);
side.closed.push(false);
}
fn index(&mut self, direction: Direction, id: NodeId) {
if let Some(meeting) = &mut self.meeting {
let state = self.sides[direction.index()].space.state(id);
meeting.relation.insert(direction, id, state);
}
}
fn check_meet(&mut self, direction: Direction, id: NodeId) {
let other = direction.opposite();
let mut candidates = core::mem::take(&mut self.candidates);
let state = self.side(direction).space.state(id);
match &self.meeting {
None => candidates.extend(self.side(other).space.find(state)),
Some(meeting) => meeting
.relation
.meets(direction, state, |other_id| candidates.push(other_id)),
}
for other_id in candidates.drain(..) {
self.record_meet(direction, id, other_id);
}
self.candidates = candidates;
}
fn record_meet(&mut self, direction: Direction, id: NodeId, other_id: NodeId) {
let cost = self.g(direction, id) + self.g(direction.opposite(), other_id);
if self.mu().is_some_and(|mu| cost >= mu) {
return;
}
let (forward, backward) = match direction {
Direction::Forward => (id, other_id),
Direction::Backward => (other_id, id),
};
self.meet = Some(Meet {
cost,
forward,
backward,
});
}
fn solution(
&self,
) -> Option<Solution<G::State, <G as Successors>::Action, <G as Successors>::Cost>> {
let meet = self.meet?;
let mut path = self.side(Direction::Forward).space.solution(meet.forward);
let tail = self
.side(Direction::Backward)
.space
.walk_to_root(meet.backward);
if self.meeting.is_some() {
let (states, cost) = self.replay(path.goal(), &tail.actions);
let replayed = states.len();
path.states.extend(states);
path.states
.extend(tail.states.into_iter().skip(replayed + 1));
path.cost = path.cost + cost;
} else {
path.states.extend(tail.states.into_iter().skip(1));
path.cost = path.cost + tail.cost;
}
path.actions.extend(tail.actions);
Some(path)
}
fn replay(
&self,
from: &G::State,
actions: &[<G as Successors>::Action],
) -> (Vec<G::State>, <G as Successors>::Cost) {
let mut states: Vec<G::State> = Vec::with_capacity(actions.len());
let mut cost = <G as Successors>::Cost::ZERO;
let Some(meeting) = &self.meeting else {
return (states, cost);
};
for action in actions {
let current = states.last().unwrap_or(from);
let Some((next, step)) = (meeting.replay)(self.graph, current, action) else {
break;
};
states.push(next);
cost = cost + step;
}
(states, cost)
}
fn finish(self, decided: bool) -> GraphResult<G> {
let outcome = match (decided, self.solution()) {
(false, _) => Outcome::LimitReached,
(true, Some(solution)) => Outcome::Found(solution),
(true, None) => Outcome::Unsolvable,
};
SearchResult {
outcome,
stats: self.stats,
}
}
}