use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
use alloc::vec::Vec;
use search_core::Cost;
use crate::cost::{add, weakly_dominates};
use crate::graph::Graph;
use crate::output::{Output, Solution, Stats};
use crate::pareto::Front;
pub fn label_correcting<G, C, P, const N: usize>(
graph: &G,
start: G::State,
is_goal: P,
) -> Output<G::State, [C; N]>
where
G: Graph<Weight = [C; N]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
let mut search = Search::new(start);
let mut goal_costs: Front<C, N> = Front::new();
let mut buffer = Vec::new();
while let Some(state) = search.queue.pop_front() {
search.queued.remove(&state);
let fresh = core::mem::take(
&mut search
.sets
.get_mut(&state)
.expect("queued states have labels")
.1,
);
if is_goal(&state) {
for &l in &fresh {
goal_costs.insert(search.labels[l].1);
}
continue;
}
graph.successors(&state, &mut buffer);
let edges = core::mem::take(&mut buffer);
for &l in &fresh {
let live = search.sets[&state].0.contains(&l);
if !live || goal_costs.weakly_dominates(&search.labels[l].1) {
continue;
}
search.stats.expanded += 1;
for (next, weight) in &edges {
search.extend(l, next, *weight);
}
}
}
search.into_output(&is_goal)
}
struct Search<S, C, const N: usize> {
labels: Vec<(S, [C; N], Option<usize>)>,
sets: BTreeMap<S, (Vec<usize>, Vec<usize>)>,
queue: VecDeque<S>,
queued: BTreeSet<S>,
stats: Stats,
}
impl<S: Clone + Ord, C: Cost, const N: usize> Search<S, C, N> {
fn new(start: S) -> Self {
Self {
labels: alloc::vec![(start.clone(), [C::ZERO; N], None)],
sets: BTreeMap::from([(start.clone(), (alloc::vec![0], alloc::vec![0]))]),
queue: VecDeque::from([start]),
queued: BTreeSet::new(),
stats: Stats {
expanded: 0,
generated: 1,
},
}
}
fn extend(&mut self, l: usize, next: &S, weight: [C; N]) {
let cost = add(self.labels[l].1, weight);
let labels = &self.labels;
let entry = self.sets.entry(next.clone()).or_default();
if entry
.0
.iter()
.any(|&k| weakly_dominates(&labels[k].1, &cost))
{
return;
}
entry.0.retain(|&k| !weakly_dominates(&cost, &labels[k].1));
entry.1.retain(|&k| !weakly_dominates(&cost, &labels[k].1));
let id = self.labels.len();
entry.0.push(id);
entry.1.push(id);
self.labels.push((next.clone(), cost, Some(l)));
self.stats.generated += 1;
if self.queued.insert(next.clone()) {
self.queue.push_back(next.clone());
}
}
fn into_output(self, is_goal: impl Fn(&S) -> bool) -> Output<S, [C; N]> {
let labels = self.labels;
let mut ends: Vec<usize> = self
.sets
.iter()
.filter(|(s, _)| is_goal(s))
.flat_map(|(_, (live, _))| live.iter().copied())
.collect();
ends.sort_by_key(|&l| labels[l].1);
let mut front = Front::new();
let solutions = ends
.into_iter()
.filter(|&l| front.insert(labels[l].1))
.map(|l| {
let mut path = Vec::new();
let mut at = Some(l);
while let Some(i) = at {
path.push(labels[i].0.clone());
at = labels[i].2;
}
path.reverse();
Solution {
cost: labels[l].1,
path,
}
})
.collect();
Output {
solutions,
stats: self.stats,
}
}
}