use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use core::mem;
use search_core::{Cost, Heuristic};
use crate::cost::{add, weakly_dominates};
use crate::graph::Graph;
use crate::output::{Output, Solution, Stats};
use crate::pareto::{Front, TruncatedFront, TruncatedTree};
pub(crate) trait Archive<C, const N: usize> {
fn empty() -> Self;
fn weakly_dominates(&self, point: &[C; N]) -> bool;
fn add(&mut self, point: [C; N]);
}
impl<C: Cost, const N: usize> Archive<C, N> for Front<C, N> {
fn empty() -> Self {
Self::new()
}
fn weakly_dominates(&self, point: &[C; N]) -> bool {
Front::weakly_dominates(self, point)
}
fn add(&mut self, point: [C; N]) {
self.insert(point);
}
}
impl<C: Cost, const N: usize> Archive<C, N> for TruncatedFront<C, N> {
fn empty() -> Self {
Self::new()
}
fn weakly_dominates(&self, point: &[C; N]) -> bool {
TruncatedFront::weakly_dominates(self, point)
}
fn add(&mut self, point: [C; N]) {
self.insert(point);
}
}
impl<C: Cost, const N: usize> Archive<C, N> for TruncatedTree<C, N> {
fn empty() -> Self {
Self::new()
}
fn weakly_dominates(&self, point: &[C; N]) -> bool {
TruncatedTree::weakly_dominates(self, point)
}
fn add(&mut self, point: [C; N]) {
self.insert(point);
}
}
pub(crate) fn run<G, H, C, P, A, const N: usize>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
track_open: bool,
) -> Output<G::State, [C; N]>
where
G: Graph<Weight = [C; N]>,
H: Heuristic<G::State, [C; N]>,
C: Cost,
P: Fn(&G::State) -> bool,
A: Archive<C, N>,
{
let mut search = Search::<G, H, C, P, A, N>::new(graph, heuristic, is_goal, track_open);
search.push_start(start);
while let Some(Reverse((f, index))) = search.open.pop() {
search.process(f, index);
}
Output {
solutions: search.solutions,
stats: search.stats,
}
}
struct Node<S, C, const N: usize> {
state: S,
g: [C; N],
parent: Option<usize>,
alive: bool,
}
struct StateLabels<A> {
open: Vec<usize>,
closed: A,
}
struct Search<'a, G: Graph, H, C, P, A, const N: usize> {
graph: &'a G,
heuristic: H,
is_goal: P,
track_open: bool,
nodes: Vec<Node<G::State, C, N>>,
open: BinaryHeap<Reverse<([C; N], usize)>>,
labels: BTreeMap<G::State, StateLabels<A>>,
costs: A,
solutions: Vec<Solution<G::State, [C; N]>>,
successors: Vec<(G::State, [C; N])>,
stats: Stats,
}
impl<'a, G, H, C, P, A, const N: usize> Search<'a, G, H, C, P, A, N>
where
G: Graph<Weight = [C; N]>,
H: Heuristic<G::State, [C; N]>,
C: Cost,
P: Fn(&G::State) -> bool,
A: Archive<C, N>,
{
fn new(graph: &'a G, heuristic: H, is_goal: P, track_open: bool) -> Self {
Self {
graph,
heuristic,
is_goal,
track_open,
nodes: Vec::new(),
open: BinaryHeap::new(),
labels: BTreeMap::new(),
costs: A::empty(),
solutions: Vec::new(),
successors: Vec::new(),
stats: Stats::default(),
}
}
fn push_start(&mut self, start: G::State) {
if let Some(h) = self.heuristic.estimate(&start) {
self.push(start, [C::ZERO; N], h, None);
}
}
fn process(&mut self, f: [C; N], index: usize) {
if !self.nodes[index].alive {
return;
}
self.leave_open(index);
if self.is_stale(f, index) {
return;
}
let node = &self.nodes[index];
let g = node.g;
let goal = (self.is_goal)(&node.state);
self.labels_mut(index).closed.add(g);
if goal {
self.costs.add(g);
let solution = self.solution(index);
self.solutions.push(solution);
} else {
self.expand(index);
}
}
fn is_stale(&self, f: [C; N], index: usize) -> bool {
let node = &self.nodes[index];
self.costs.weakly_dominates(&f)
|| self
.labels
.get(&node.state)
.is_some_and(|labels| labels.closed.weakly_dominates(&node.g))
}
fn leave_open(&mut self, index: usize) {
if self.track_open {
self.labels_mut(index).open.retain(|&i| i != index);
}
}
fn labels_mut(&mut self, index: usize) -> &mut StateLabels<A> {
self.labels
.entry(self.nodes[index].state.clone())
.or_insert_with(|| StateLabels {
open: Vec::new(),
closed: A::empty(),
})
}
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 Some(h) = self.heuristic.estimate(&state) else {
continue;
};
let g_next = add(g, weight);
if self.admits(&state, g_next, add(g_next, h)) {
self.push(state, g_next, h, Some(index));
}
}
self.successors = successors;
}
fn admits(&mut self, state: &G::State, g: [C; N], f: [C; N]) -> bool {
if self.costs.weakly_dominates(&f) {
return false;
}
let Some(labels) = self.labels.get_mut(state) else {
return true;
};
if labels.closed.weakly_dominates(&g) {
return false;
}
if !self.track_open {
return true;
}
let nodes = &mut self.nodes;
if labels
.open
.iter()
.any(|&i| weakly_dominates(&nodes[i].g, &g))
{
return false;
}
labels.open.retain(|&i| {
let dominated = weakly_dominates(&g, &nodes[i].g);
if dominated {
nodes[i].alive = false;
}
!dominated
});
true
}
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,
alive: true,
});
self.open.push(Reverse((add(g, h), index)));
self.stats.generated += 1;
if self.track_open {
self.labels_mut(index).open.push(index);
}
}
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,
}
}
}