use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use search_core::{Budget, Cost, Heuristic, WideMul};
use super::Excess;
use crate::anytime_boa::{AnytimeFront, ApproxFactor};
use crate::cost::{add, weakly_dominates};
use crate::epsilon::Epsilon;
use crate::graph::Graph;
use crate::output::{Solution, Stats};
use crate::pareto::Front;
use crate::pp_a::iterative::as_factor;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AnytimeApex {
#[default]
Reuse,
ReuseEnhanced,
Restart,
Hybrid {
threshold: u32,
},
}
pub fn apex_star_anytime<G, H, C, P, const N: usize>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
schedule: impl IntoIterator<Item = [Epsilon; N]>,
on_front: impl FnMut(&[Solution<G::State, [C; N]>], ApproxFactor<C>),
budget: impl Budget<Stats>,
) -> AnytimeFront<G::State, C, N>
where
G: Graph<Weight = [C; N]>,
H: Heuristic<G::State, [C; N]>,
C: Cost + WideMul,
P: Fn(&G::State) -> bool,
{
apex_star_anytime_with(
graph,
heuristic,
start,
is_goal,
schedule,
AnytimeApex::Reuse,
on_front,
budget,
)
}
#[expect(
clippy::too_many_arguments,
reason = "the anytime search inputs plus the variant"
)]
pub fn apex_star_anytime_with<G, H, C, P, const N: usize>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
schedule: impl IntoIterator<Item = [Epsilon; N]>,
variant: AnytimeApex,
mut on_front: impl FnMut(&[Solution<G::State, [C; N]>], ApproxFactor<C>),
mut budget: impl Budget<Stats>,
) -> AnytimeFront<G::State, C, N>
where
G: Graph<Weight = [C; N]>,
H: Heuristic<G::State, [C; N]>,
C: Cost + WideMul,
P: Fn(&G::State) -> bool,
{
let mut search = Anytime::new(graph, heuristic, is_goal, variant, start);
let mut reported: Option<ApproxFactor<C>> = None;
let mut complete = false;
let mut reuse = matches!(variant, AnytimeApex::Reuse | AnytimeApex::ReuseEnhanced);
for eps in schedule {
if reported.is_some() && budget.exhausted(&search.stats) {
break;
}
let (expanded, pruned) = search.iterate(eps, reuse);
if let AnytimeApex::Hybrid { threshold } = variant {
reuse = reuse || expanded > pruned.saturating_mul(threshold as usize);
}
complete = search.pruned.is_empty();
let front = search.front();
let factor = if complete {
ApproxFactor::Zero
} else {
as_factor(widest(eps), &front)
};
if reported.is_none_or(|r| factor < r) {
reported = Some(factor);
on_front(&front, factor);
}
if complete {
break;
}
}
AnytimeFront {
solutions: search.front(),
factor: reported.unwrap_or(ApproxFactor::Infinite),
complete,
stats: search.stats,
}
}
fn widest<const N: usize>(eps: [Epsilon; N]) -> Epsilon {
eps.into_iter()
.reduce(|a, b| {
let larger =
u64::from(b.num()) * u64::from(a.den()) > u64::from(a.num()) * u64::from(b.den());
if larger { b } else { a }
})
.unwrap_or(Epsilon::ZERO)
}
#[derive(Clone, Copy)]
struct Pair<C, const N: usize> {
apex: [C; N],
rep: usize,
h: [C; N],
alive: bool,
}
struct Anytime<'a, G: Graph, H, C, P, const N: usize> {
graph: &'a G,
heuristic: H,
is_goal: P,
variant: AnytimeApex,
start: G::State,
paths: Vec<(G::State, [C; N], Option<usize>)>,
pairs: Vec<Pair<C, N>>,
open: BinaryHeap<Reverse<([C; N], usize)>>,
open_at: BTreeMap<G::State, Vec<usize>>,
closed: BTreeMap<G::State, Vec<([C; N], usize)>>,
expanded: BTreeMap<G::State, Front<C, N>>,
solutions: Vec<usize>,
pruned: Vec<usize>,
eps: [Epsilon; N],
stats: Stats,
}
impl<'a, G, H, C, P, const N: usize> Anytime<'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,
{
fn new(graph: &'a G, heuristic: H, is_goal: P, variant: AnytimeApex, start: G::State) -> Self {
let mut search = Self {
graph,
heuristic,
is_goal,
variant,
start: start.clone(),
paths: Vec::new(),
pairs: Vec::new(),
open: BinaryHeap::new(),
open_at: BTreeMap::new(),
closed: BTreeMap::new(),
expanded: BTreeMap::new(),
solutions: Vec::new(),
pruned: Vec::new(),
eps: [Epsilon::ZERO; N],
stats: Stats::default(),
};
search.paths.push((start, [C::ZERO; N], None));
search.pruned.push(0);
search
}
fn iterate(&mut self, eps: [Epsilon; N], reuse: bool) -> (usize, usize) {
self.eps = eps;
self.pairs.clear();
self.open.clear();
self.open_at.clear();
self.closed.clear();
let before = self.stats.expanded;
let seeds = core::mem::take(&mut self.pruned);
let seeds = if reuse {
seeds
} else {
self.paths.push((self.start.clone(), [C::ZERO; N], None));
alloc::vec![self.paths.len() - 1]
};
for path in seeds {
let (state, cost) = (self.paths[path].0.clone(), self.paths[path].1);
if let Some(h) = self.heuristic.estimate(&state) {
self.add_to_open(Pair {
apex: cost,
rep: path,
h,
alive: true,
});
}
}
self.find_approx_front();
(self.stats.expanded - before, self.pruned.len())
}
fn find_approx_front(&mut self) {
while let Some(Reverse((_, index))) = self.open.pop() {
let pair = self.pairs[index];
if !pair.alive {
continue;
}
let state = self.paths[pair.rep].0.clone();
if let Some(list) = self.open_at.get_mut(&state) {
list.retain(|&i| i != index);
}
if self.is_dominated(&pair) {
continue;
}
self.closed
.entry(state.clone())
.or_default()
.push((pair.apex, pair.rep));
if self.variant == AnytimeApex::ReuseEnhanced {
let cost = self.paths[pair.rep].1;
self.expanded.entry(state.clone()).or_default().insert(cost);
}
if (self.is_goal)(&state) {
let cost = self.paths[pair.rep].1;
let paths = &self.paths;
self.solutions
.retain(|&s| !weakly_dominates(&cost, &paths[s].1));
self.solutions.push(pair.rep);
continue;
}
self.expand(pair);
}
}
fn expand(&mut self, pair: Pair<C, N>) {
self.stats.expanded += 1;
let state = self.paths[pair.rep].0.clone();
let mut edges = Vec::new();
self.graph.successors(&state, &mut edges);
for (next, weight) in edges {
let Some(h) = self.heuristic.estimate(&next) else {
continue;
};
let cost = add(self.paths[pair.rep].1, weight);
self.paths.push((next, cost, Some(pair.rep)));
let child = Pair {
apex: add(pair.apex, weight),
rep: self.paths.len() - 1,
h,
alive: true,
};
if !self.is_dominated(&child) {
self.add_to_open(child);
self.stats.generated += 1;
}
}
}
fn is_dominated(&mut self, pair: &Pair<C, N>) -> bool {
let (state, rep_cost) = (self.paths[pair.rep].0.clone(), self.paths[pair.rep].1);
let f = add(pair.apex, pair.h);
let rep_f = add(rep_cost, pair.h);
let covering = self
.solutions
.iter()
.map(|&s| self.paths[s].1)
.find(|c| (0..N).all(|i| self.eps[i].within(c[i], f[i])));
if let Some(c) = covering {
if !weakly_dominates(&c, &rep_f) {
self.pruned.push(pair.rep);
}
return true;
}
let dominator = self.closed.get(&state).and_then(|list| {
list.iter()
.find(|(x, _)| (1..N).all(|i| x[i] <= pair.apex[i]))
.map(|&(_, r)| r)
});
if let Some(r) = dominator {
if !weakly_dominates(&self.paths[r].1, &rep_cost) {
self.pruned.push(pair.rep);
}
return true;
}
self.variant == AnytimeApex::ReuseEnhanced
&& self
.expanded
.get(&state)
.is_some_and(|c| c.weakly_dominates(&pair.apex))
}
fn add_to_open(&mut self, pair: Pair<C, N>) {
let state = self.paths[pair.rep].0.clone();
let candidates = self.open_at.get(&state).cloned().unwrap_or_default();
for other in candidates {
let Some(merged) = self.merge(pair, self.pairs[other]) else {
continue;
};
self.pairs[other].alive = false;
if let Some(list) = self.open_at.get_mut(&state) {
list.retain(|&i| i != other);
}
let dropped = if merged.rep == pair.rep {
self.pairs[other].rep
} else {
pair.rep
};
if !weakly_dominates(&self.paths[merged.rep].1, &self.paths[dropped].1) {
self.pruned.push(dropped);
}
self.push(merged);
return;
}
self.push(pair);
}
fn push(&mut self, pair: Pair<C, N>) {
let state = self.paths[pair.rep].0.clone();
self.pairs.push(pair);
let index = self.pairs.len() - 1;
self.open.push(Reverse((add(pair.apex, pair.h), index)));
self.open_at.entry(state).or_default().push(index);
}
fn merge(&self, a: Pair<C, N>, b: Pair<C, N>) -> Option<Pair<C, N>> {
let apex = core::array::from_fn(|i| a.apex[i].min(b.apex[i]));
let for_a = Pair {
apex,
rep: a.rep,
h: a.h,
alive: true,
};
let for_b = Pair {
apex,
rep: b.rep,
h: a.h,
alive: true,
};
match (self.excess(&for_a), self.excess(&for_b)) {
(Some(x), Some(y)) if x.is_greater(y) => Some(for_b),
(Some(_), _) => Some(for_a),
(None, Some(_)) => Some(for_b),
(None, None) => None,
}
}
fn excess(&self, pair: &Pair<C, N>) -> Option<Excess<C>> {
let f_rep = add(self.paths[pair.rep].1, pair.h);
let f_apex = add(pair.apex, pair.h);
if !(0..N).all(|i| self.eps[i].within(f_rep[i], f_apex[i])) {
return None;
}
let ratios = (0..N)
.filter(|&i| f_rep[i] != f_apex[i])
.map(|i| Excess::Ratio {
over: f_rep[i]
.abs_diff(f_apex[i])
.saturating_times(self.eps[i].den()),
of: f_apex[i].saturating_times(self.eps[i].num()),
});
Some(ratios.fold(Excess::Zero, |x, y| if y.is_greater(x) { y } else { x }))
}
fn front(&self) -> Vec<Solution<G::State, [C; N]>> {
let mut out: Vec<_> = self.solutions.iter().map(|&s| self.solution(s)).collect();
out.sort_by_key(|s| s.cost);
out
}
fn solution(&self, index: usize) -> Solution<G::State, [C; N]> {
let mut path = Vec::new();
let mut at = Some(index);
while let Some(i) = at {
path.push(self.paths[i].0.clone());
at = self.paths[i].2;
}
path.reverse();
Solution {
cost: self.paths[index].1,
path,
}
}
}