use core::hash::Hash;
use search_core::{Budget, Cost};
use crate::best_first::{Workspace, dijkstra_multi_in};
use crate::outcome::{Outcome, Solution, Stats};
use crate::problem::{Predecessors, Successors};
use crate::space::NodeId;
pub struct FlowField<S, A, C> {
work: Workspace<S, A, C>,
stats: Stats,
complete: bool,
}
impl<S, A, C> FlowField<S, A, C>
where
S: Clone + Hash + Eq,
A: Clone,
C: Cost,
{
pub fn build<G>(
graph: &G,
goals: impl IntoIterator<Item = S>,
budget: impl Budget<Stats>,
) -> Self
where
G: Predecessors<Node = S, Action = A, Cost = C>,
{
let mut work = Workspace::new();
let never = |_: &S| false;
let result = dijkstra_multi_in(&mut work, &Backward(graph), goals, &never, budget);
Self {
work,
stats: result.stats,
complete: matches!(result.outcome, Outcome::Unsolvable),
}
}
#[must_use]
pub fn cost(&self, state: &S) -> Option<C> {
self.settled(state).map(|id| self.work.space().g(id))
}
#[must_use]
pub fn next(&self, state: &S) -> Option<(&A, &S, C)> {
let space = self.work.space();
let (parent, action, cost) = space.parent(self.settled(state)?)?;
Some((action, space.state(parent), cost))
}
#[must_use]
pub fn path(&self, start: &S) -> Option<Solution<S, A, C>> {
self.settled(start)
.map(|id| self.work.space().walk_to_root(id))
}
#[must_use]
pub fn is_complete(&self) -> bool {
self.complete
}
#[must_use]
pub fn stats(&self) -> Stats {
self.stats
}
fn settled(&self, state: &S) -> Option<NodeId> {
let id = self.work.space().find(state)?;
self.work.is_closed(id).then_some(id)
}
}
struct Backward<'a, G>(&'a G);
impl<G: Predecessors> Successors for Backward<'_, G> {
type State = G::Node;
type Action = G::Action;
type Cost = G::Cost;
fn successors(&self, node: &G::Node, emit: impl FnMut(G::Action, G::Node, G::Cost)) {
self.0.predecessors(node, emit);
}
}