use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use search_core::{Cost, WideMul};
use crate::apex::expanded_apexes;
use crate::cost::add;
use crate::epsilon::Epsilon;
use crate::graph::{Graph, ReverseGraph};
use crate::mvh::MvHeuristic;
use crate::pareto::Front;
#[derive(Debug, Clone)]
pub struct MvhTable<S, C, const N: usize> {
sets: BTreeMap<S, Front<C, N>>,
}
impl<S: Ord, C: Cost, const N: usize> MvhTable<S, C, N> {
#[must_use]
pub fn get(&self, state: &S) -> &[[C; N]] {
self.sets.get(state).map_or(&[], Front::as_slice)
}
#[must_use]
pub fn size(&self) -> usize {
self.sets.values().map(Front::len).sum()
}
pub fn make_consistent<G>(&mut self, graph: &G)
where
S: Clone,
G: ReverseGraph<State = S, Weight = [C; N]>,
{
let mut work: Vec<S> = self.sets.keys().cloned().collect();
let mut queued: BTreeSet<S> = work.iter().cloned().collect();
let mut edges = Vec::new();
while let Some(target) = work.pop() {
queued.remove(&target);
let estimates = self.get(&target).to_vec();
graph.predecessors(&target, &mut edges);
for (source, weight) in edges.drain(..) {
if self.lower(&source, weight, &estimates) && queued.insert(source.clone()) {
work.push(source);
}
}
}
}
fn lower(&mut self, source: &S, weight: [C; N], estimates: &[[C; N]]) -> bool
where
S: Clone,
{
let set = self.sets.entry(source.clone()).or_default();
let mut changed = false;
for &h in estimates {
let bound = add(weight, h);
if !set.weakly_dominates(&bound) {
set.insert(bound);
changed = true;
}
}
changed
}
}
impl<S: Ord, C: Cost, const N: usize> MvHeuristic<S, [C; N]> for MvhTable<S, C, N> {
fn estimates(&mut self, state: &S, out: &mut Vec<[C; N]>) {
out.extend_from_slice(self.get(state));
}
}
impl<S: Ord, C: Cost, const N: usize> MvHeuristic<S, [C; N]> for &MvhTable<S, C, N> {
fn estimates(&mut self, state: &S, out: &mut Vec<[C; N]>) {
out.extend_from_slice(self.get(state));
}
}
pub fn apex_mvh<G, C, const N: usize>(
graph: &G,
goals: impl IntoIterator<Item = G::State>,
eps: [Epsilon; N],
) -> MvhTable<G::State, C, N>
where
G: ReverseGraph<Weight = [C; N]>,
C: Cost + WideMul,
{
MvhTable {
sets: expanded_apexes(&Reversed(graph), goals, eps),
}
}
struct Reversed<'a, G>(&'a G);
impl<G: ReverseGraph> Graph for Reversed<'_, G> {
type State = G::State;
type Weight = G::Weight;
fn successors(&self, state: &G::State, out: &mut Vec<(G::State, G::Weight)>) {
self.0.predecessors(state, out);
}
}