use core::hash::Hash;
use alloc::vec::Vec;
use search_core::{Budget, Cost, Heuristic, Zero};
use crate::best_first::GraphResult;
use crate::bidirectional::mixed::{Mixed, MixedGraph, Split, unmix};
use crate::bidirectional::{
BidirectionalGraph, Core, Direction, Equality, MeetRelation, MeetResult, Meeting, Meets,
RegressionGraph,
};
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
use crate::problem::{Predecessors, Successors};
use crate::space::NodeId;
pub fn bidirectional_bfs<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,
{
bidirectional_bfs_multi(graph, [start], goals, budget)
}
pub fn bidirectional_bfs_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,
{
let unit = Unit(graph);
let core = Core::new(
&unit,
starts,
goals,
Zero,
Zero,
None::<Meeting<Unit<'_, G>, Equality>>,
);
weighted(layers(core, budget))
}
pub fn bidirectional_bfs_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,
M: MeetRelation<<G as Successors>::State, <G as Predecessors>::Node>,
{
let mixed = MixedGraph(graph);
let unit = Unit(&mixed);
let core = Core::new(
&unit,
starts.into_iter().map(Mixed::State),
goals.into_iter().map(Mixed::Node),
Zero,
Zero,
Some(Meeting::new(Split(meet))),
);
unmix(weighted(layers(core, budget)))
}
fn layers<G, M>(
mut core: Core<'_, G, Zero, Zero, M>,
mut budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: BidirectionalGraph,
G::State: Clone + Hash + Eq,
<G as Successors>::Action: Clone,
M: Meets<G::State>,
{
let mut frontiers = [Vec::new(), Vec::new()];
for direction in [Direction::Forward, Direction::Backward] {
frontiers[direction.index()] = (0..core.side(direction).space.len()).collect();
}
while core.meet.is_none() && frontiers.iter().all(|frontier| !frontier.is_empty()) {
let direction = if frontiers[0].len() <= frontiers[1].len() {
Direction::Forward
} else {
Direction::Backward
};
let layer = core::mem::take(&mut frontiers[direction.index()]);
let Some(next) = expand_layer(&mut core, direction, &layer, &mut budget) else {
return core.finish(false);
};
frontiers[direction.index()] = next;
}
core.finish(true)
}
fn expand_layer<G, HF, HB, M>(
core: &mut Core<'_, G, HF, HB, M>,
direction: Direction,
layer: &[NodeId],
budget: &mut impl Budget<Stats>,
) -> Option<Vec<NodeId>>
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>,
{
let mut next = Vec::new();
for &node in layer {
if budget.exhausted(&core.stats) {
return None;
}
core.expand(direction, node, false, &mut next);
}
Some(next)
}
fn weighted<S, A, C: Cost>(result: SearchResult<S, (A, C), u64>) -> SearchResult<S, A, C> {
let outcome = match result.outcome {
Outcome::Found(solution) => {
let (actions, costs): (Vec<A>, Vec<C>) = solution.actions.into_iter().unzip();
Outcome::Found(Solution {
states: solution.states,
actions,
cost: costs.into_iter().fold(C::ZERO, |sum, cost| sum + cost),
})
}
Outcome::Unsolvable => Outcome::Unsolvable,
Outcome::LimitReached => Outcome::LimitReached,
Outcome::Cutoff => Outcome::Cutoff,
};
SearchResult {
outcome,
stats: result.stats,
}
}
struct Unit<'a, G>(&'a G);
impl<G: Successors> Successors for Unit<'_, G> {
type State = G::State;
type Action = (<G as Successors>::Action, <G as Successors>::Cost);
type Cost = u64;
fn successors(&self, state: &G::State, mut emit: impl FnMut(Self::Action, G::State, u64)) {
self.0
.successors(state, |action, next, cost| emit((action, cost), next, 1));
}
}
impl<G: Predecessors> Predecessors for Unit<'_, G> {
type Node = G::Node;
type Action = (<G as Predecessors>::Action, <G as Predecessors>::Cost);
type Cost = u64;
fn predecessors(&self, node: &G::Node, mut emit: impl FnMut(Self::Action, G::Node, u64)) {
self.0.predecessors(node, |action, previous, cost| {
emit((action, cost), previous, 1);
});
}
}