use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use core::mem;
use search_core::Cost;
use crate::cost::add;
use crate::graph::Graph;
use crate::mvh::MvHeuristic;
use crate::output::{Output, Solution, Stats};
use crate::pareto::{Front, TruncatedFront};
pub fn namoa_star_dr_mvh_lazy<G, M, C, P, const N: usize>(
graph: &G,
heuristic: M,
start: G::State,
is_goal: P,
) -> Output<G::State, [C; N]>
where
G: Graph<Weight = [C; N]>,
M: MvHeuristic<G::State, [C; N]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
let mut search = Search::new(graph, heuristic, is_goal);
search.push_start(start);
while let Some(Reverse((f, index))) = search.open.pop() {
search.process(f, index);
}
search.into_output()
}
struct Node<S, C, const N: usize> {
state: S,
g: [C; N],
parent: Option<usize>,
}
struct StateInfo<C, const N: usize> {
estimates: Vec<[C; N]>,
closed_tail: TruncatedFront<C, N>,
closed: Front<C, N>,
max_g1: Option<C>,
}
struct Search<'a, G: Graph, M, C, P, const N: usize> {
graph: &'a G,
heuristic: M,
is_goal: P,
nodes: Vec<Node<G::State, C, N>>,
open: BinaryHeap<Reverse<([C; N], usize)>>,
states: BTreeMap<G::State, StateInfo<C, N>>,
costs: TruncatedFront<C, N>,
solutions: Vec<usize>,
successors: Vec<(G::State, [C; N])>,
validate_order: bool,
stats: Stats,
}
impl<'a, G, M, C, P, const N: usize> Search<'a, G, M, C, P, N>
where
G: Graph<Weight = [C; N]>,
M: MvHeuristic<G::State, [C; N]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
fn new(graph: &'a G, heuristic: M, is_goal: P) -> Self {
Self {
graph,
heuristic,
is_goal,
nodes: Vec::new(),
open: BinaryHeap::new(),
states: BTreeMap::new(),
costs: TruncatedFront::new(),
solutions: Vec::new(),
successors: Vec::new(),
validate_order: true,
stats: Stats::default(),
}
}
fn push_start(&mut self, start: G::State) {
self.reach(&start);
if let Some(h) = self.choose_h(&start, &[C::ZERO; N]) {
self.push(start, [C::ZERO; N], h, None);
}
}
fn process(&mut self, f: [C; N], index: usize) {
let state = self.nodes[index].state.clone();
let g = self.nodes[index].g;
if self.costs.weakly_dominates(&f) {
if let Some(h) = self.choose_h(&state, &g) {
self.open.push(Reverse((add(g, h), index)));
}
return;
}
if self.is_locally_dominated(&state, &g) {
return;
}
self.close(&state, g);
if (self.is_goal)(&state) {
self.costs.insert(g);
self.solutions.push(index);
} else {
self.expand(index);
}
}
fn expand(&mut self, index: usize) {
self.stats.expanded += 1;
let mut successors = mem::take(&mut self.successors);
let g = self.nodes[index].g;
self.graph
.successors(&self.nodes[index].state, &mut successors);
for (state, weight) in successors.drain(..) {
let g_next = add(g, weight);
self.reach(&state);
let Some(h) = self.choose_h(&state, &g_next) else {
continue;
};
if !self.is_locally_dominated(&state, &g_next) {
self.push(state, g_next, h, Some(index));
}
}
self.successors = successors;
}
fn choose_h(&self, state: &G::State, g: &[C; N]) -> Option<[C; N]> {
self.states[state]
.estimates
.iter()
.copied()
.find(|&h| !self.costs.weakly_dominates(&add(*g, h)))
}
fn is_locally_dominated(&self, state: &G::State, g: &[C; N]) -> bool {
let Some(info) = self.states.get(state) else {
return false;
};
if !info.closed_tail.weakly_dominates(g) {
return false;
}
let in_order = info.max_g1.is_none_or(|max| max <= g[0]);
if in_order || !self.validate_order {
return true;
}
info.closed.weakly_dominates(g)
}
fn close(&mut self, state: &G::State, g: [C; N]) {
let info = self.states.get_mut(state).expect("reached before closed");
info.closed_tail.insert(g);
info.closed.insert(g);
info.max_g1 = Some(info.max_g1.map_or(g[0], |max| max.max(g[0])));
}
fn reach(&mut self, state: &G::State) {
if self.states.contains_key(state) {
return;
}
let mut estimates = Vec::new();
self.heuristic.estimates(state, &mut estimates);
estimates.sort_unstable();
estimates.dedup();
self.states.insert(
state.clone(),
StateInfo {
estimates,
closed_tail: TruncatedFront::new(),
closed: Front::new(),
max_g1: None,
},
);
}
fn push(&mut self, state: G::State, g: [C; N], h: [C; N], parent: Option<usize>) {
let index = self.nodes.len();
self.nodes.push(Node { state, g, parent });
self.open.push(Reverse((add(g, h), index)));
self.stats.generated += 1;
}
fn into_output(self) -> Output<G::State, [C; N]> {
let mut solutions: Vec<_> = self.solutions.iter().map(|&i| self.solution(i)).collect();
debug_assert!(
solutions.windows(2).all(|w| w[0].cost < w[1].cost),
"solutions not found in lexicographic order"
);
solutions.sort_by_key(|s| s.cost);
Output {
solutions,
stats: self.stats,
}
}
fn solution(&self, index: usize) -> Solution<G::State, [C; N]> {
let mut path = Vec::new();
let mut current = Some(index);
while let Some(i) = current {
path.push(self.nodes[i].state.clone());
current = self.nodes[i].parent;
}
path.reverse();
Solution {
cost: self.nodes[index].g,
path,
}
}
}
#[cfg(test)]
mod tests {
use alloc::vec;
use alloc::vec::Vec;
use core::cmp::Reverse;
use super::Search;
use crate::graph::Graph;
use crate::mvh::mv_heuristic_fn;
const START: u8 = 0;
const S1: u8 = 1;
const S2: u8 = 2;
const S3: u8 = 3;
const GOAL: u8 = 4;
struct Figure2;
impl Graph for Figure2 {
type State = u8;
type Weight = [u32; 2];
fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
match *state {
START => out.extend([(GOAL, [3, 15]), (S1, [7, 9]), (S3, [10, 6])]),
S1 => out.push((S3, [1, 1])),
S3 => out.extend([(GOAL, [2, 7]), (S2, [7, 1])]),
S2 => out.push((GOAL, [1, 1])),
_ => {}
}
}
}
fn run(validate_order: bool) -> Vec<[u32; 2]> {
let table = mv_heuristic_fn(|s: &u8, out: &mut Vec<[u32; 2]>| match *s {
START => out.extend([[2, 14], [11, 12], [15, 11], [17, 7]]),
S1 => out.extend([[2, 7], [8, 2]]),
S2 => out.push([1, 1]),
S3 => out.extend([[1, 6], [7, 1]]),
_ => out.push([0, 0]),
});
let mut search = Search::new(&Figure2, table, |s: &u8| *s == GOAL);
search.validate_order = validate_order;
search.push_start(START);
while let Some(Reverse((f, index))) = search.open.pop() {
search.process(f, index);
}
search
.into_output()
.solutions
.iter()
.map(|s| s.cost)
.collect()
}
#[test]
fn naive_dimensionality_reduction_loses_a_solution() {
assert_eq!(run(false), vec![[3, 15], [12, 13], [18, 8]]);
assert_eq!(run(true), vec![[3, 15], [12, 13], [16, 12], [18, 8]]);
}
}