use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Cost};
use crate::cost::Weight;
use crate::dynamic::incremental::{Estimate, Incremental};
use crate::dynamic::{DynamicGraph, DynamicResult, assert_weight};
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Rooted<V> {
Root,
Vertex(V),
}
struct RootedGraph<'g, G, V> {
graph: &'g G,
starts: &'g [V],
}
impl<G, V> DynamicGraph for RootedGraph<'_, G, V>
where
G: DynamicGraph<Vertex = V>,
V: Clone + Hash + Eq,
{
type Vertex = Rooted<V>;
type Cost = G::Cost;
fn successors(&self, vertex: &Rooted<V>, mut emit: impl FnMut(Rooted<V>, G::Cost)) {
match vertex {
Rooted::Root => {
for start in self.starts {
emit(Rooted::Vertex(start.clone()), G::Cost::ZERO);
}
}
Rooted::Vertex(vertex) => self
.graph
.successors(vertex, |next, cost| emit(Rooted::Vertex(next), cost)),
}
}
fn predecessors(&self, vertex: &Rooted<V>, mut emit: impl FnMut(Rooted<V>, G::Cost)) {
if let Rooted::Vertex(vertex) = vertex {
self.graph.predecessors(vertex, |previous, cost| {
emit(Rooted::Vertex(previous), cost);
});
if self.starts.contains(vertex) {
emit(Rooted::Root, G::Cost::ZERO);
}
}
}
}
struct RootedH<D, V> {
inner: D,
starts: Vec<V>,
}
impl<V, C: Cost, D: FnMut(&V, &V) -> C> Estimate<Rooted<V>, C> for RootedH<D, V> {
fn estimate(&mut self, from: &Rooted<V>, to: &Rooted<V>) -> C {
match (from, to) {
(Rooted::Vertex(from), Rooted::Vertex(to)) => (self.inner)(from, to),
(Rooted::Root, Rooted::Vertex(to)) => {
let inner = &mut self.inner;
self.starts
.iter()
.map(|start| inner(start, to))
.min()
.unwrap_or(C::ZERO)
}
(_, Rooted::Root) => C::ZERO,
}
}
}
struct Rooting<V, C, D> {
core: Incremental<Rooted<V>, C, RootedH<D, V>>,
starts: Vec<V>,
}
impl<V, C, D> Rooting<V, C, D>
where
V: Clone + Hash + Eq,
C: Cost,
D: FnMut(&V, &V) -> C,
{
fn new(
forward: bool,
starts: impl IntoIterator<Item = V>,
goal: V,
heuristic: D,
weight: Option<Weight>,
) -> Self {
let mut unique: Vec<V> = Vec::new();
for start in starts {
if !unique.contains(&start) {
unique.push(start);
}
}
let estimate = RootedH {
inner: heuristic,
starts: unique.clone(),
};
let goal = Rooted::Vertex(goal);
let mut core = if forward {
Incremental::new(true, Rooted::Root, goal, estimate, weight)
} else {
Incremental::new(false, goal, Rooted::Root, estimate, weight)
};
core.settle_ties = true;
Self {
core,
starts: unique,
}
}
fn compute<G: DynamicGraph<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
budget: impl Budget<Stats>,
) -> DynamicResult<G> {
let rooted = RootedGraph {
graph,
starts: &self.starts,
};
unroot(self.core.compute(&rooted, budget))
}
fn edge_changed<G: DynamicGraph<Vertex = V, Cost = C>>(&mut self, graph: &G, from: &V, to: &V) {
let rooted = RootedGraph {
graph,
starts: &self.starts,
};
let (from, to) = (Rooted::Vertex(from.clone()), Rooted::Vertex(to.clone()));
self.core.edge_changed(&rooted, &from, &to);
}
}
fn unroot<V, C>(result: SearchResult<Rooted<V>, (), C>) -> SearchResult<V, (), C> {
let outcome = match result.outcome {
Outcome::Found(solution) => {
let states: Vec<V> = solution
.states
.into_iter()
.filter_map(|vertex| match vertex {
Rooted::Vertex(vertex) => Some(vertex),
Rooted::Root => None,
})
.collect();
Outcome::Found(Solution {
actions: alloc::vec![(); states.len().saturating_sub(1)],
states,
cost: solution.cost,
})
}
Outcome::Unsolvable => Outcome::Unsolvable,
Outcome::LimitReached => Outcome::LimitReached,
Outcome::Cutoff => Outcome::Cutoff,
};
SearchResult {
outcome,
stats: result.stats,
}
}
macro_rules! multi_planner {
($(#[$doc:meta])* $name:ident, $single:literal, $forward:expr) => {
$(#[$doc])*
pub struct $name<V, C, D> {
rooting: Rooting<V, C, D>,
}
impl<V, C, D> $name<V, C, D>
where
V: Clone + Hash + Eq,
C: Cost,
D: FnMut(&V, &V) -> C,
{
#[doc = concat!("Repairs the tree after the latest changes and returns a path from the best start, as [`", $single, "`] does for one.")]
pub fn compute<G: DynamicGraph<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
budget: impl Budget<Stats>,
) -> DynamicResult<G> {
self.rooting.compute(graph, budget)
}
pub fn edge_changed<G: DynamicGraph<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
from: &V,
to: &V,
) {
self.rooting.edge_changed(graph, from, to);
}
#[must_use]
pub fn stats(&self) -> Stats {
self.rooting.core.total
}
#[must_use]
pub fn starts(&self) -> &[V] {
&self.rooting.starts
}
}
};
}
multi_planner!(
LpaStarMulti,
"crate::LpaStar::compute",
true
);
multi_planner!(
DStarLiteMulti,
"crate::DStarLite::compute",
false
);
multi_planner!(
AdStarMulti,
"crate::AdStar::compute",
false
);
impl<V, C, D> LpaStarMulti<V, C, D>
where
V: Clone + Hash + Eq,
C: Cost,
D: FnMut(&V, &V) -> C,
{
pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
_graph: &G,
starts: impl IntoIterator<Item = V>,
goal: V,
heuristic: D,
) -> Self {
Self {
rooting: Rooting::new(true, starts, goal, heuristic, None),
}
}
}
impl<V, C, D> DStarLiteMulti<V, C, D>
where
V: Clone + Hash + Eq,
C: Cost,
D: FnMut(&V, &V) -> C,
{
pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
_graph: &G,
starts: impl IntoIterator<Item = V>,
goal: V,
heuristic: D,
) -> Self {
Self {
rooting: Rooting::new(false, starts, goal, heuristic, None),
}
}
}
impl<V, C, D> AdStarMulti<V, C, D>
where
V: Clone + Hash + Eq,
C: Cost,
D: FnMut(&V, &V) -> C,
{
pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
_graph: &G,
starts: impl IntoIterator<Item = V>,
goal: V,
heuristic: D,
weight: Weight,
) -> Self {
assert_weight(weight);
Self {
rooting: Rooting::new(false, starts, goal, heuristic, Some(weight)),
}
}
pub fn set_weight(&mut self, weight: Weight) {
assert_weight(weight);
self.rooting.core.set_weight(weight);
}
#[must_use]
pub fn weight(&self) -> Weight {
self.rooting.core.weight()
}
}