pub(crate) mod iterative;
use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use core::mem;
pub use iterative::pp_a_star_iterative;
use search_core::{Cost, Heuristic};
use crate::cost::add;
use crate::epsilon::Epsilon;
use crate::graph::Graph;
use crate::output::{Output, Solution, Stats};
pub fn pp_a_star<G, H, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
eps: [Epsilon; 2],
) -> Output<G::State, [C; 2]>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
let mut search = Search {
graph,
heuristic,
is_goal,
eps,
paths: Vec::new(),
pairs: Vec::new(),
open: BinaryHeap::new(),
states: BTreeMap::new(),
solutions: Vec::new(),
successors: Vec::new(),
stats: Stats::default(),
};
search.push_start(start);
while let Some(Reverse((_, index))) = search.open.pop() {
search.process(index);
}
search.into_output()
}
struct PathNode<S, C> {
state: S,
g: [C; 2],
parent: Option<usize>,
}
#[derive(Clone, Copy)]
struct Pair<C> {
tl: usize,
br: usize,
h: [C; 2],
alive: bool,
}
struct StateInfo<C> {
g2_min: Option<C>,
open: Vec<usize>,
}
struct Search<'a, G: Graph, H, C, P> {
graph: &'a G,
heuristic: H,
is_goal: P,
eps: [Epsilon; 2],
paths: Vec<PathNode<G::State, C>>,
pairs: Vec<Pair<C>>,
open: BinaryHeap<Reverse<([C; 2], usize)>>,
states: BTreeMap<G::State, StateInfo<C>>,
solutions: Vec<(usize, usize)>,
successors: Vec<(G::State, [C; 2])>,
stats: Stats,
}
impl<G, H, C, P> Search<'_, G, H, C, P>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
fn push_start(&mut self, start: G::State) {
if let Some(h) = self.heuristic.estimate(&start) {
let path = self.new_path(start, [C::ZERO; 2], None);
self.push(Pair {
tl: path,
br: path,
h,
alive: true,
});
}
}
fn process(&mut self, index: usize) {
let pair = self.pairs[index];
if !pair.alive {
return;
}
let state = self.paths[pair.br].state.clone();
let info = self.info_mut(&state);
info.open.retain(|&i| i != index);
let g2 = self.paths[pair.br].g[1];
if self.is_dominated(&state, g2, g2 + pair.h[1]) {
return;
}
self.info_mut(&state).g2_min = Some(g2);
if (self.is_goal)(&state) {
self.add_solution(pair);
} else {
self.expand(pair);
}
}
fn is_dominated(&self, state: &G::State, g2: C, f2: C) -> bool {
self.best_g2()
.is_some_and(|best| self.eps[1].within(best, f2))
|| self
.states
.get(state)
.and_then(|info| info.g2_min)
.is_some_and(|min| g2 >= min)
}
fn best_g2(&self) -> Option<C> {
self.solutions.last().map(|&(_, br)| self.paths[br].g[1])
}
fn add_solution(&mut self, pair: Pair<C>) {
if let Some(last) = self.solutions.last_mut() {
if self.eps[0].within(self.paths[pair.br].g[0], self.paths[last.0].g[0]) {
last.1 = pair.br;
return;
}
}
self.solutions.push((pair.tl, pair.br));
}
fn expand(&mut self, pair: Pair<C>) {
self.stats.expanded += 1;
let mut successors = mem::take(&mut self.successors);
let from = self.paths[pair.br].state.clone();
self.graph.successors(&from, &mut successors);
for (state, weight) in successors.drain(..) {
let Some(h) = self.heuristic.estimate(&state) else {
continue;
};
let g_br = add(self.paths[pair.br].g, weight);
if self.is_dominated(&state, g_br[1], g_br[1] + h[1]) {
continue;
}
let br = self.new_path(state.clone(), g_br, Some(pair.br));
let tl = if pair.tl == pair.br {
br
} else {
let g_tl = add(self.paths[pair.tl].g, weight);
self.new_path(state, g_tl, Some(pair.tl))
};
self.insert(Pair {
tl,
br,
h,
alive: true,
});
}
self.successors = successors;
}
fn insert(&mut self, pair: Pair<C>) {
let state = self.paths[pair.br].state.clone();
let open = self
.states
.get(&state)
.map_or(&[][..], |info| &info.open[..]);
let found = open.iter().enumerate().find_map(|(position, &other)| {
let merged = self.merge(pair, self.pairs[other]);
self.is_bounded(merged).then_some((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>, b: Pair<C>) -> Pair<C> {
let first = |i: usize| self.paths[i].g[0];
let second = |i: usize| self.paths[i].g[1];
Pair {
tl: if first(b.tl) < first(a.tl) {
b.tl
} else {
a.tl
},
br: if second(b.br) < second(a.br) {
b.br
} else {
a.br
},
h: a.h,
alive: true,
}
}
fn is_bounded(&self, pair: Pair<C>) -> bool {
self.eps[0].within(self.paths[pair.br].g[0], self.paths[pair.tl].g[0])
}
fn push(&mut self, pair: Pair<C>) {
let index = self.pairs.len();
let apex = [
self.paths[pair.tl].g[0] + pair.h[0],
self.paths[pair.br].g[1] + pair.h[1],
];
let state = self.paths[pair.br].state.clone();
self.pairs.push(pair);
self.open.push(Reverse((apex, index)));
self.info_mut(&state).open.push(index);
self.stats.generated += 1;
}
fn new_path(&mut self, state: G::State, g: [C; 2], 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> {
self.states
.entry(state.clone())
.or_insert_with(|| StateInfo {
g2_min: None,
open: Vec::new(),
})
}
fn into_output(self) -> Output<G::State, [C; 2]> {
let mut costs: Vec<_> = self
.solutions
.iter()
.map(|&(_, br)| (self.paths[br].g, br))
.collect();
costs.sort_unstable();
let mut solutions: Vec<Solution<G::State, [C; 2]>> = Vec::new();
for (cost, br) in costs {
if solutions.last().is_none_or(|last| cost[1] < last.cost[1]) {
solutions.push(self.solution(br, cost));
}
}
Output {
solutions,
stats: self.stats,
}
}
fn solution(&self, index: usize, cost: [C; 2]) -> Solution<G::State, [C; 2]> {
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 }
}
}