use core::cmp::Reverse;
use core::hash::Hash;
use alloc::collections::BinaryHeap;
use alloc::vec::Vec;
use search_core::{Budget, Cost, Heuristic, Zero};
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::cost::CostExt;
use crate::keyed_set::KeyedSet;
use crate::outcome::Stats;
use crate::problem::Predecessors;
use crate::problem::Successors;
use crate::space::NodeId;
pub fn bidirectional_dijkstra<G>(
graph: &G,
start: G::State,
goals: impl IntoIterator<Item = G::State>,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: BidirectionalGraph,
G::State: Clone + Hash + Eq,
<G as Successors>::Action: Clone,
<G as Successors>::Cost: CostExt,
{
bidirectional_dijkstra_multi(graph, [start], goals, budget)
}
pub fn bidirectional_dijkstra_multi<G>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goals: impl IntoIterator<Item = G::State>,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: BidirectionalGraph,
G::State: Clone + Hash + Eq,
<G as Successors>::Action: Clone,
<G as Successors>::Cost: CostExt,
{
let core = Core::new(
graph,
starts,
goals,
Zero,
Zero,
None::<Meeting<G, Equality>>,
);
Frontier::new(core, Rule::Dijkstra).run(budget)
}
pub fn dibbs<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,
<G as Successors>::Cost: CostExt,
HF: Heuristic<G::State, <G as Successors>::Cost>,
HB: Heuristic<G::State, <G as Successors>::Cost>,
{
dibbs_multi(graph, [start], goals, forward, backward, budget)
}
pub fn dibbs_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,
<G as Successors>::Cost: CostExt,
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>>,
);
Frontier::new(core, Rule::Dibbs).run(budget)
}
pub fn bae_star<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,
<G as Successors>::Cost: CostExt,
HF: Heuristic<G::State, <G as Successors>::Cost>,
HB: Heuristic<G::State, <G as Successors>::Cost>,
{
bae_star_multi(graph, [start], goals, forward, backward, budget)
}
pub fn bae_star_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,
<G as Successors>::Cost: CostExt,
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>>,
);
Frontier::new(core, Rule::Bae).run(budget)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Rule {
Dijkstra,
Dibbs,
Bae,
Mm,
}
type Key<C> = (C, Reverse<C>);
type Bound<C> = BinaryHeap<Reverse<(C, NodeId)>>;
pub fn bidirectional_dijkstra_meet<G, M>(
graph: &G,
starts: impl IntoIterator<Item = <G as Successors>::State>,
goals: impl IntoIterator<Item = <G as Predecessors>::Node>,
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,
<G as Successors>::Cost: CostExt,
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),
Zero,
Zero,
Some(Meeting::new(Split(meet))),
);
unmix(Frontier::new(core, Rule::Dijkstra).run(budget))
}
pub fn dibbs_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,
<G as Successors>::Cost: CostExt,
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(Frontier::new(core, Rule::Dibbs).run(budget))
}
pub fn bae_star_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,
<G as Successors>::Cost: CostExt,
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(Frontier::new(core, Rule::Bae).run(budget))
}
pub(super) struct Frontier<'a, G: BidirectionalGraph, HF, HB, M> {
core: Core<'a, G, HF, HB, M>,
open: [KeyedSet<Key<<G as Successors>::Cost>>; 2],
bounds: [[Bound<<G as Successors>::Cost>; 2]; 2],
bounded: bool,
rule: Rule,
}
impl<'a, G, HF, HB, M> Frontier<'a, G, HF, HB, M>
where
G: BidirectionalGraph,
G::State: Clone + Hash + Eq,
<G as Successors>::Action: Clone,
<G as Successors>::Cost: CostExt,
HF: Heuristic<G::State, <G as Successors>::Cost>,
HB: Heuristic<G::State, <G as Successors>::Cost>,
M: Meets<G::State>,
{
pub(super) fn new(core: Core<'a, G, HF, HB, M>, rule: Rule) -> Self {
let mut search = Self {
core,
open: [KeyedSet::new(), KeyedSet::new()],
bounds: [
[BinaryHeap::new(), BinaryHeap::new()],
[BinaryHeap::new(), BinaryHeap::new()],
],
bounded: false,
rule,
};
for direction in [Direction::Forward, Direction::Backward] {
for id in 0..search.core.side(direction).space.len() {
search.open(direction, id);
}
}
search
}
pub(super) fn run(mut self, mut budget: impl Budget<Stats>) -> GraphResult<G> {
let mut touched = Vec::new();
loop {
let (Some(forward), Some(backward)) = (
self.min_key(Direction::Forward),
self.min_key(Direction::Backward),
) else {
return self.core.finish(true);
};
if self.stops(forward, backward) {
return self.core.finish(true);
}
if budget.exhausted(&self.core.stats) {
return self.core.finish(false);
}
let direction = self.pick(forward, backward);
let (_, node) = self.open[direction.index()]
.first()
.expect("the side is not empty");
self.open[direction.index()].remove(node);
self.core.expand(direction, node, true, &mut touched);
for id in touched.drain(..) {
self.open(direction, id);
}
}
}
fn min_key(&self, direction: Direction) -> Option<<G as Successors>::Cost> {
self.open[direction.index()].first().map(|(key, _)| key.0)
}
fn stops(
&mut self,
forward: <G as Successors>::Cost,
backward: <G as Successors>::Cost,
) -> bool {
let sum = forward.saturating_add(backward);
match self.rule {
Rule::Dijkstra => self.core.proven(sum),
Rule::Dibbs | Rule::Bae => self
.core
.mu()
.is_some_and(|mu| sum.cmp(&mu.saturating_times(2)).is_ge()),
Rule::Mm => {
let Some(mu) = self.core.mu() else {
return false;
};
let reaches = |bound: <G as Successors>::Cost| bound.cmp(&mu).is_ge();
if reaches(forward.min(backward)) {
return true;
}
self.track();
reaches(self.bound(Direction::Forward, 0))
|| reaches(self.bound(Direction::Backward, 0))
|| reaches(
self.bound(Direction::Forward, 1)
.saturating_add(self.bound(Direction::Backward, 1)),
)
}
}
}
fn track(&mut self) {
if self.bounded {
return;
}
self.bounded = true;
for direction in [Direction::Forward, Direction::Backward] {
for id in 0..self.core.side(direction).space.len() {
if self.open[direction.index()].key(id).is_some() {
for which in 0..2 {
let value = self.value(direction, which, id);
self.bounds[direction.index()][which].push(Reverse((value, id)));
}
}
}
}
}
fn bound(&mut self, direction: Direction, which: usize) -> <G as Successors>::Cost {
while let Some(&Reverse((key, id))) = self.bounds[direction.index()][which].peek() {
if self.open[direction.index()].key(id).is_some()
&& self.value(direction, which, id) == key
{
return key;
}
self.bounds[direction.index()][which].pop();
}
<G as Successors>::Cost::ZERO
}
fn value(&self, direction: Direction, which: usize, id: NodeId) -> <G as Successors>::Cost {
let g = self.core.g(direction, id);
if which == 0 {
let (h, _) = self.core.h(direction, id).expect("open nodes are live");
g.saturating_add(h)
} else {
g
}
}
fn pick(
&self,
forward: <G as Successors>::Cost,
backward: <G as Successors>::Cost,
) -> Direction {
let forward_first = match self.rule {
Rule::Dijkstra | Rule::Dibbs | Rule::Mm => forward.cmp(&backward).is_le(),
Rule::Bae => self.open[0].len() <= self.open[1].len(),
};
if forward_first {
Direction::Forward
} else {
Direction::Backward
}
}
fn open(&mut self, direction: Direction, id: NodeId) {
let Some((h, h_opposite)) = self.core.h(direction, id) else {
return;
};
let g = self.core.g(direction, id);
let key = match self.rule {
Rule::Dijkstra => g,
Rule::Dibbs | Rule::Bae => (g + g + h).saturating_sub(h_opposite),
Rule::Mm => {
let f = g.saturating_add(h);
if self.bounded {
let bounds = &mut self.bounds[direction.index()];
bounds[0].push(Reverse((f, id)));
bounds[1].push(Reverse((g, id)));
}
f.max(g.saturating_times(2))
}
};
self.open[direction.index()].insert(id, (key, Reverse(g)));
}
}