use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use search_core::{Cost, Heuristic, WideMul};
use crate::graph::ReverseGraph;
#[derive(Debug, Clone)]
pub struct IdealPoint<S, C, const N: usize> {
table: BTreeMap<S, [C; N]>,
}
impl<S: Clone + Ord, C: Cost, const N: usize> IdealPoint<S, C, N> {
pub fn new<G>(graph: &G, goals: impl IntoIterator<Item = S>) -> Self
where
G: ReverseGraph<State = S, Weight = [C; N]>,
{
let goals: Vec<S> = goals.into_iter().collect();
let per_objective: Vec<BTreeMap<S, C>> = (0..N)
.map(|i| {
dijkstra(
goals.iter().cloned(),
|s, out| graph.predecessors(s, out),
i,
)
})
.collect();
let table = per_objective[0]
.keys()
.map(|s| (s.clone(), core::array::from_fn(|i| per_objective[i][s])))
.collect();
Self { table }
}
}
impl<S: Ord, C: Cost, const N: usize> Heuristic<S, [C; N]> for IdealPoint<S, C, N> {
fn estimate(&mut self, state: &S) -> Option<[C; N]> {
self.table.get(state).copied()
}
}
impl<S: Ord, C: Cost, const N: usize> Heuristic<S, [C; N]> for &IdealPoint<S, C, N> {
fn estimate(&mut self, state: &S) -> Option<[C; N]> {
self.table.get(state).copied()
}
}
fn dijkstra<S: Clone + Ord, C: Cost, const N: usize>(
sources: impl IntoIterator<Item = S>,
edges: impl Fn(&S, &mut Vec<(S, [C; N])>),
objective: usize,
) -> BTreeMap<S, C> {
let mut dist = BTreeMap::new();
let mut heap: BinaryHeap<Reverse<(C, S)>> =
sources.into_iter().map(|s| Reverse((C::ZERO, s))).collect();
let mut buffer = Vec::new();
while let Some(Reverse((d, s))) = heap.pop() {
if dist.contains_key(&s) {
continue;
}
edges(&s, &mut buffer);
for (t, w) in buffer.drain(..) {
if !dist.contains_key(&t) {
heap.push(Reverse((d + w[objective], t)));
}
}
dist.insert(s, d);
}
dist
}
#[derive(Debug, Clone)]
pub struct DifferentialHeuristic<S, C, const N: usize> {
from: Vec<Vec<BTreeMap<S, C>>>,
to: Vec<Vec<BTreeMap<S, C>>>,
}
impl<S: Clone + Ord, C: Cost + WideMul, const N: usize> DifferentialHeuristic<S, C, N> {
pub fn new<G>(graph: &G, landmarks: impl IntoIterator<Item = S>) -> Self
where
G: ReverseGraph<State = S, Weight = [C; N]>,
{
let (mut from, mut to) = (Vec::new(), Vec::new());
for landmark in landmarks {
from.push(
(0..N)
.map(|i| dijkstra([landmark.clone()], |s, out| graph.successors(s, out), i))
.collect(),
);
to.push(
(0..N)
.map(|i| dijkstra([landmark.clone()], |s, out| graph.predecessors(s, out), i))
.collect(),
);
}
Self { from, to }
}
#[must_use]
pub fn towards(&self, goal: &S) -> Towards<'_, S, C, N> {
Towards {
landmarks: self,
goal: goal.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct Towards<'a, S, C, const N: usize> {
landmarks: &'a DifferentialHeuristic<S, C, N>,
goal: S,
}
impl<S: Ord, C: Cost + WideMul, const N: usize> Heuristic<S, [C; N]> for Towards<'_, S, C, N> {
fn estimate(&mut self, state: &S) -> Option<[C; N]> {
let lm = self.landmarks;
let bound = |i: usize| {
let mut best = C::ZERO;
for l in 0..lm.from.len() {
let pairs = [
(lm.from[l][i].get(&self.goal), lm.from[l][i].get(state)),
(lm.to[l][i].get(state), lm.to[l][i].get(&self.goal)),
];
for (big, small) in pairs {
if let (Some(&big), Some(&small)) = (big, small) {
if big > small {
best = best.max(big.abs_diff(small));
}
}
}
}
best
};
Some(core::array::from_fn(bound))
}
}