mod anytime;
use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use core::mem;
use search_core::{Cost, Heuristic, WideMul};
use crate::cost::add;
use crate::epsilon::Epsilon;
use crate::graph::{Graph, ZeroHeuristic};
use crate::output::{Output, Solution, Stats};
use crate::pareto::{Front, TruncatedFront};
pub use anytime::{AnytimeApex, apex_star_anytime, apex_star_anytime_with};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum MergeRule {
#[default]
Greedy,
ReverseLex,
}
pub fn apex_star<G, H, C, P, const N: usize>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
eps: [Epsilon; N],
) -> Output<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_with(graph, heuristic, start, is_goal, eps, MergeRule::Greedy)
}
pub fn apex_star_with<G, H, C, P, const N: usize>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
eps: [Epsilon; N],
rule: MergeRule,
) -> Output<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 = Search::new(graph, heuristic, is_goal, eps, rule, false);
search.push_start(start);
search.run();
search.into_output()
}
struct PathNode<S, C, const N: usize> {
state: S,
g: [C; N],
parent: Option<usize>,
}
#[derive(Clone, Copy)]
struct Pair<C, const N: usize> {
apex: [C; N],
rep: usize,
h: [C; N],
alive: bool,
}
struct StateInfo<C, const N: usize> {
closed: TruncatedFront<C, N>,
open: Vec<usize>,
expanded: Front<C, N>,
}
struct Search<'a, G: Graph, H, C, P, const N: usize> {
graph: &'a G,
heuristic: H,
is_goal: P,
eps: [Epsilon; N],
rule: MergeRule,
paths: Vec<PathNode<G::State, C, N>>,
pairs: Vec<Pair<C, N>>,
open: BinaryHeap<Reverse<([C; N], usize)>>,
states: BTreeMap<G::State, StateInfo<C, N>>,
solutions: Vec<Pair<C, N>>,
successors: Vec<(G::State, [C; N])>,
record: bool,
stats: Stats,
}
pub(crate) fn expanded_apexes<G, C, const N: usize>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
eps: [Epsilon; N],
) -> BTreeMap<G::State, Front<C, N>>
where
G: Graph<Weight = [C; N]>,
C: Cost + WideMul,
{
let never = |_: &G::State| false;
let mut search = Search::new(graph, ZeroHeuristic, never, eps, MergeRule::Greedy, true);
for start in starts {
search.push_start(start);
}
search.run();
search
.states
.into_iter()
.filter(|(_, info)| !info.expanded.is_empty())
.map(|(state, info)| (state, info.expanded))
.collect()
}
impl<'a, G, H, C, P, const N: usize> Search<'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,
eps: [Epsilon; N],
rule: MergeRule,
record: bool,
) -> Self {
Self {
graph,
heuristic,
is_goal,
eps,
rule,
paths: Vec::new(),
pairs: Vec::new(),
open: BinaryHeap::new(),
states: BTreeMap::new(),
solutions: Vec::new(),
successors: Vec::new(),
record,
stats: Stats::default(),
}
}
fn run(&mut self) {
while let Some(Reverse((f, index))) = self.open.pop() {
self.process(f, index);
}
}
fn push_start(&mut self, start: G::State) {
if let Some(h) = self.heuristic.estimate(&start) {
let rep = self.new_path(start, [C::ZERO; N], None);
self.push(Pair {
apex: [C::ZERO; N],
rep,
h,
alive: true,
});
}
}
fn process(&mut self, f: [C; N], index: usize) {
let pair = self.pairs[index];
if !pair.alive {
return;
}
let state = self.paths[pair.rep].state.clone();
self.info_mut(&state).open.retain(|&i| i != index);
if self.is_pruned(&state, &pair.apex, &f) {
return;
}
let record = self.record;
let info = self.info_mut(&state);
info.closed.insert(pair.apex);
if record {
info.expanded.insert(pair.apex);
}
if (self.is_goal)(&state) {
self.insert_solution(pair);
} else {
self.expand(pair);
}
}
fn is_pruned(&mut self, state: &G::State, apex: &[C; N], f: &[C; N]) -> bool {
self.is_covered_by_solution(f)
|| self
.states
.get(state)
.is_some_and(|info| info.closed.weakly_dominates(apex))
}
fn is_covered_by_solution(&mut self, f: &[C; N]) -> bool {
let paths = &self.paths;
let eps = &self.eps;
let Some(solution) = self.solutions.iter_mut().find(|s| {
let g = &paths[s.rep].g;
(1..N).all(|i| eps[i].within(g[i], f[i]))
}) else {
return false;
};
solution.apex = core::array::from_fn(|i| solution.apex[i].min(f[i]));
true
}
fn within(&self, cost: &[C; N], bound: &[C; N]) -> bool {
(0..N).all(|i| self.eps[i].within(cost[i], bound[i]))
}
fn expand(&mut self, pair: Pair<C, N>) {
self.stats.expanded += 1;
let mut successors = mem::take(&mut self.successors);
let from = self.paths[pair.rep].state.clone();
self.graph.successors(&from, &mut successors);
for (state, weight) in successors.drain(..) {
let Some(h) = self.heuristic.estimate(&state) else {
continue;
};
let apex = add(pair.apex, weight);
if self.is_pruned(&state, &apex, &add(apex, h)) {
continue;
}
let g = add(self.paths[pair.rep].g, weight);
let rep = self.new_path(state, g, Some(pair.rep));
self.insert(Pair {
apex,
rep,
h,
alive: true,
});
}
self.successors = successors;
}
fn insert_solution(&mut self, pair: Pair<C, N>) {
let found = self
.solutions
.iter()
.enumerate()
.find_map(|(k, &other)| self.merge(pair, other).map(|merged| (k, merged)));
match found {
Some((k, merged)) => self.solutions[k] = merged,
None => self.solutions.push(pair),
}
}
fn insert(&mut self, pair: Pair<C, N>) {
let state = self.paths[pair.rep].state.clone();
let open = self
.states
.get(&state)
.map_or(&[][..], |info| &info.open[..]);
let found = open.iter().enumerate().find_map(|(position, &other)| {
self.merge(pair, self.pairs[other])
.map(|merged| (position, other, merged))
});
if let Some((position, other, merged)) = found {
self.pairs[other].alive = false;
self.info_mut(&state).open.swap_remove(position);
self.push(merged);
return;
}
self.push(pair);
}
fn merge(&self, a: Pair<C, N>, b: Pair<C, N>) -> Option<Pair<C, N>> {
let with_rep = |rep| Pair {
apex: core::array::from_fn(|i| a.apex[i].min(b.apex[i])),
rep,
h: a.h,
alive: true,
};
let (for_a, for_b) = (with_rep(a.rep), with_rep(b.rep));
match self.rule {
MergeRule::Greedy => {
let excess_a = self.excess(&for_a);
let excess_b = self.excess(&for_b);
match (excess_a, excess_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,
}
}
MergeRule::ReverseLex => {
let (ga, gb) = (&self.paths[a.rep].g, &self.paths[b.rep].g);
let merged = if gb.iter().rev().lt(ga.iter().rev()) {
for_b
} else {
for_a
};
self.is_bounded(&merged).then_some(merged)
}
}
}
fn is_bounded(&self, pair: &Pair<C, N>) -> bool {
let f_rep = add(self.paths[pair.rep].g, pair.h);
self.within(&f_rep, &add(pair.apex, pair.h))
}
fn excess(&self, pair: &Pair<C, N>) -> Option<Excess<C>> {
if !self.is_bounded(pair) {
return None;
}
let f_rep = add(self.paths[pair.rep].g, pair.h);
let f_apex = add(pair.apex, pair.h);
let ratios = (0..N).filter(|&i| f_rep[i] != f_apex[i]).map(|i| {
let eps = self.eps[i];
let over = f_rep[i].abs_diff(f_apex[i]).saturating_times(eps.den());
Excess::Ratio {
over,
of: f_apex[i].saturating_times(eps.num()),
}
});
Some(ratios.fold(Excess::Zero, |x, y| if y.is_greater(x) { y } else { x }))
}
fn push(&mut self, pair: Pair<C, N>) {
let index = self.pairs.len();
let state = self.paths[pair.rep].state.clone();
self.pairs.push(pair);
self.open.push(Reverse((add(pair.apex, pair.h), index)));
self.info_mut(&state).open.push(index);
self.stats.generated += 1;
}
fn new_path(&mut self, state: G::State, g: [C; N], parent: Option<usize>) -> usize {
self.paths.push(PathNode { state, g, parent });
self.paths.len() - 1
}
fn info_mut(&mut self, state: &G::State) -> &mut StateInfo<C, N> {
self.states
.entry(state.clone())
.or_insert_with(|| StateInfo {
closed: TruncatedFront::new(),
open: Vec::new(),
expanded: Front::new(),
})
}
fn into_output(self) -> Output<G::State, [C; N]> {
let mut reps: Vec<_> = self
.solutions
.iter()
.map(|s| (self.paths[s.rep].g, s.rep))
.collect();
reps.sort_unstable();
let mut front = Front::new();
let solutions = reps
.into_iter()
.filter(|&(cost, _)| front.insert(cost))
.map(|(cost, r)| self.solution(r, cost))
.collect();
Output {
solutions,
stats: self.stats,
}
}
fn solution(&self, index: usize, cost: [C; N]) -> Solution<G::State, [C; N]> {
let mut path = Vec::new();
let mut current = Some(index);
while let Some(i) = current {
path.push(self.paths[i].state.clone());
current = self.paths[i].parent;
}
path.reverse();
Solution { cost, path }
}
}
#[derive(Clone, Copy)]
enum Excess<C> {
Zero,
Ratio {
over: C,
of: C,
},
}
impl<C: WideMul> Excess<C> {
fn is_greater(self, other: Self) -> bool {
match (self, other) {
(Self::Ratio { over, of }, Self::Ratio { over: o, of: f }) => {
over.wide_mul(f) > o.wide_mul(of)
}
(Self::Ratio { .. }, Self::Zero) => true,
(Self::Zero, _) => false,
}
}
}