use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::{Ordering, Reverse};
use search_core::{Cost, Heuristic, WideMul};
use crate::constrained::rebuild;
use crate::cost::add;
use crate::graph::Graph;
use crate::output::{Solution, Stats};
use crate::pareto::Front;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Achievement<C> {
Below(C),
Above(C),
}
impl<C: Ord> PartialOrd for Achievement<C> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<C: Ord> Ord for Achievement<C> {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(Self::Below(a), Self::Below(b)) => b.cmp(a),
(Self::Above(a), Self::Above(b)) => a.cmp(b),
(Self::Below(_), Self::Above(_)) => Ordering::Less,
(Self::Above(_), Self::Below(_)) => Ordering::Greater,
}
}
}
#[must_use]
pub fn achievement<C: Cost + WideMul, const N: usize>(
cost: &[C; N],
reference: &[C; N],
weights: &[u32; N],
) -> Achievement<C> {
(0..N)
.map(|i| {
let gap = cost[i].abs_diff(reference[i]).saturating_times(weights[i]);
if cost[i] >= reference[i] {
Achievement::Above(gap)
} else {
Achievement::Below(gap)
}
})
.max()
.unwrap_or(Achievement::Above(C::ZERO))
}
type Key<C, const N: usize> = (Achievement<C>, [C; N], usize);
pub struct ReferencePoint<'a, G: Graph, H, C, P, const N: usize> {
graph: &'a G,
heuristic: H,
is_goal: P,
reference: [C; N],
weights: [u32; N],
nodes: Vec<(G::State, [C; N], Option<usize>)>,
open: BinaryHeap<Reverse<Key<C, N>>>,
closed: BTreeMap<G::State, Front<C, N>>,
returned: Front<C, N>,
successors: Vec<(G::State, [C; N])>,
stats: Stats,
}
impl<'a, G, H, C, P, const N: usize> ReferencePoint<'a, G, H, C, P, N>
where
G: Graph<Weight = [C; N]>,
H: Heuristic<G::State, [C; N]>,
C: Cost + WideMul,
P: Fn(&G::State) -> bool,
{
pub fn new(
graph: &'a G,
mut heuristic: H,
start: G::State,
is_goal: P,
reference: [C; N],
weights: [u32; N],
) -> Self {
let first = heuristic.estimate(&start);
let mut search = Self {
graph,
heuristic,
is_goal,
reference,
weights,
nodes: Vec::new(),
open: BinaryHeap::new(),
closed: BTreeMap::new(),
returned: Front::new(),
successors: Vec::new(),
stats: Stats::default(),
};
if let Some(h) = first {
search.push(start, [C::ZERO; N], h, None);
}
search
}
pub fn aim(&mut self, reference: [C; N], weights: [u32; N]) {
self.reference = reference;
self.weights = weights;
let entries: Vec<_> = self.open.drain().map(|Reverse((_, f, i))| (f, i)).collect();
for (f, index) in entries {
let key = achievement(&f, &self.reference, &self.weights);
self.open.push(Reverse((key, f, index)));
}
}
#[must_use]
pub const fn stats(&self) -> Stats {
self.stats
}
fn push(&mut self, state: G::State, g: [C; N], h: [C; N], parent: Option<usize>) {
let f = add(g, h);
let key = achievement(&f, &self.reference, &self.weights);
self.nodes.push((state, g, parent));
self.open.push(Reverse((key, f, self.nodes.len() - 1)));
self.stats.generated += 1;
}
fn expand(&mut self, index: usize) {
self.stats.expanded += 1;
let mut successors = core::mem::take(&mut self.successors);
let (state, g) = (self.nodes[index].0.clone(), self.nodes[index].1);
self.graph.successors(&state, &mut successors);
for (next, weight) in successors.drain(..) {
let g_next = add(g, weight);
if self
.closed
.get(&next)
.is_some_and(|c| c.weakly_dominates(&g_next))
{
continue;
}
let Some(h) = self.heuristic.estimate(&next) else {
continue;
};
if !self.returned.weakly_dominates(&add(g_next, h)) {
self.push(next, g_next, h, Some(index));
}
}
self.successors = successors;
}
}
impl<G, H, C, P, const N: usize> Iterator for ReferencePoint<'_, G, H, C, P, N>
where
G: Graph<Weight = [C; N]>,
H: Heuristic<G::State, [C; N]>,
C: Cost + WideMul,
P: Fn(&G::State) -> bool,
{
type Item = Solution<G::State, [C; N]>;
fn next(&mut self) -> Option<Self::Item> {
while let Some(Reverse((_, f, index))) = self.open.pop() {
let (state, g) = (self.nodes[index].0.clone(), self.nodes[index].1);
if self.returned.weakly_dominates(&f)
|| self
.closed
.get(&state)
.is_some_and(|c| c.weakly_dominates(&g))
{
continue;
}
self.closed.entry(state.clone()).or_default().insert(g);
if (self.is_goal)(&state) {
self.returned.insert(g);
return Some(rebuild(&self.nodes, index));
}
self.expand(index);
}
None
}
}