use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Mutex;
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};
#[expect(
clippy::needless_pass_by_value,
reason = "takes the heuristic by value like every other search; each thread clones it"
)]
pub fn parallel_moa_star<G, H, C, P, const N: usize>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
) -> Output<G::State, [C; N]>
where
G: Graph<Weight = [C; N]> + Sync,
G::State: Send + Sync,
H: Heuristic<G::State, [C; N]> + Clone + Send,
C: Cost + Send + Sync,
P: Fn(&G::State) -> bool + Sync,
{
let shared = Shared::<G::State, C, N> {
threads: (0..N)
.map(|_| {
Mutex::new(Found {
solutions: Vec::new(),
latest: None,
})
})
.collect(),
bounds: Mutex::new([None; N]),
stop: AtomicBool::new(false),
expanded: AtomicUsize::new(0),
generated: AtomicUsize::new(0),
};
std::thread::scope(|scope| {
for lead in 0..N {
let (shared, heuristic, is_goal, start) =
(&shared, heuristic.clone(), &is_goal, start.clone());
scope.spawn(move || Thread::new(graph, heuristic, is_goal, lead, shared).run(start));
}
});
merge(shared)
}
struct Found<S, C, const N: usize> {
solutions: Vec<Solution<S, [C; N]>>,
latest: Option<C>,
}
struct Shared<S, C, const N: usize> {
threads: Vec<Mutex<Found<S, C, N>>>,
bounds: Mutex<[Option<C>; N]>,
stop: AtomicBool,
expanded: AtomicUsize,
generated: AtomicUsize,
}
struct Thread<'a, G: Graph, H, C, P, const N: usize> {
graph: &'a G,
heuristic: H,
is_goal: &'a P,
lead: usize,
shared: &'a Shared<G::State, C, N>,
nodes: Vec<(G::State, [C; N], Option<usize>)>,
open: BinaryHeap<Reverse<([C; N], usize)>>,
closed: BTreeMap<G::State, TruncatedFront<C, N>>,
levels: Vec<Vec<[C; N]>>,
successors: Vec<(G::State, [C; N])>,
bounds: [Option<C>; N],
}
impl<'a, G, H, C, P, const N: usize> Thread<'a, G, H, C, P, N>
where
G: Graph<Weight = [C; N]>,
H: Heuristic<G::State, [C; N]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
fn new(
graph: &'a G,
heuristic: H,
is_goal: &'a P,
lead: usize,
shared: &'a Shared<G::State, C, N>,
) -> Self {
Self {
graph,
heuristic,
is_goal,
lead,
shared,
nodes: Vec::new(),
open: BinaryHeap::new(),
closed: BTreeMap::new(),
levels: (0..N).map(|_| Vec::new()).collect(),
successors: Vec::new(),
bounds: [None; N],
}
}
fn rotate(&self, v: [C; N]) -> [C; N] {
core::array::from_fn(|p| v[(self.lead + p) % N])
}
fn run(mut self, start: G::State) {
if let Some(h) = self.heuristic.estimate(&start) {
self.nodes.push((start, [C::ZERO; N], None));
self.open.push(Reverse((self.rotate(h), 0)));
self.shared.generated.fetch_add(1, Ordering::Relaxed);
}
while let Some(Reverse((f, index))) = self.open.pop() {
if self.shared.stop.load(Ordering::Relaxed) {
return;
}
self.bounds = *self
.shared
.bounds
.lock()
.expect("no thread panics holding the bounds");
if self.bounds[self.lead].is_some_and(|b| f[0] >= b) {
break;
}
let (state, g) = (
self.nodes[index].0.clone(),
self.rotate(self.nodes[index].1),
);
if self
.closed
.get(&state)
.is_some_and(|c| c.weakly_dominates(&g))
|| self.dominated(&f)
{
continue;
}
self.closed
.entry(state.clone())
.or_insert_with(TruncatedFront::new)
.insert(g);
if (self.is_goal)(&state) {
self.record(index, g);
continue;
}
self.expand(index);
}
self.shared.stop.store(true, Ordering::Relaxed);
}
fn expand(&mut self, index: usize) {
self.shared.expanded.fetch_add(1, Ordering::Relaxed);
let mut successors = core::mem::take(&mut self.successors);
let (state, g) = (self.nodes[index].0.clone(), self.nodes[index].1);
self.graph.successors(&state, &mut successors);
for (next, weight) in successors.drain(..) {
let Some(h) = self.heuristic.estimate(&next) else {
continue;
};
let g_next = add(g, weight);
let (g_rot, f_rot) = (self.rotate(g_next), self.rotate(add(g_next, h)));
if self
.closed
.get(&next)
.is_some_and(|c| c.weakly_dominates(&g_rot))
|| self.dominated(&f_rot)
{
continue;
}
self.nodes.push((next, g_next, Some(index)));
self.open.push(Reverse((f_rot, self.nodes.len() - 1)));
self.shared.generated.fetch_add(1, Ordering::Relaxed);
}
self.successors = successors;
}
fn dominated(&self, f: &[C; N]) -> bool {
let over = (0..N).any(|p| self.bounds[(self.lead + p) % N].is_some_and(|b| f[p] >= b));
over || (1..N).any(|level| {
let probe = zero_first(*f, level);
self.levels[level]
.iter()
.any(|v| weakly_dominates(v, &probe))
})
}
fn record(&mut self, index: usize, g: [C; N]) {
insert(&mut self.levels[1], zero_first(g, 1));
let solution = rebuild(&self.nodes, index);
{
let mut found = self.shared.threads[self.lead]
.lock()
.expect("no thread panics holding its solutions");
found.solutions.push(solution);
found.latest = Some(g[0]);
}
self.update_bounds();
}
fn update_bounds(&mut self) {
for level in 1..N.saturating_sub(1) {
let objective = (self.lead + level) % N;
let latest = self.shared.threads[objective]
.lock()
.expect("no thread panics holding its solutions")
.latest;
let Some(z) = latest else { continue };
let (moved, kept): (Vec<_>, Vec<_>) =
self.levels[level].drain(..).partition(|v| v[level] <= z);
self.levels[level] = kept;
for v in moved {
insert(&mut self.levels[level + 1], zero_first(v, level + 1));
}
}
if N < 2 {
return;
}
if let Some(scalar) = self.levels[N - 1].iter().map(|v| v[N - 1]).min() {
let objective = (self.lead + N - 1) % N;
let mut bounds = self
.shared
.bounds
.lock()
.expect("no thread panics holding the bounds");
if bounds[objective].is_none_or(|b| scalar < b) {
bounds[objective] = Some(scalar);
}
self.bounds = *bounds;
}
}
}
fn zero_first<C: Cost, const N: usize>(mut v: [C; N], count: usize) -> [C; N] {
for c in v.iter_mut().take(count) {
*c = C::ZERO;
}
v
}
fn insert<C: Cost, const N: usize>(list: &mut Vec<[C; N]>, v: [C; N]) {
if list.iter().any(|w| weakly_dominates(w, &v)) {
return;
}
list.retain(|w| !weakly_dominates(&v, w));
list.push(v);
}
fn rebuild<S: Clone, C: Copy, const N: usize>(
nodes: &[(S, [C; N], Option<usize>)],
index: usize,
) -> Solution<S, [C; N]> {
let mut path = Vec::new();
let mut current = Some(index);
while let Some(i) = current {
path.push(nodes[i].0.clone());
current = nodes[i].2;
}
path.reverse();
Solution {
cost: nodes[index].1,
path,
}
}
fn merge<S, C: Cost, const N: usize>(shared: Shared<S, C, N>) -> Output<S, [C; N]> {
let mut all: Vec<Solution<S, [C; N]>> = shared
.threads
.into_iter()
.flat_map(|t| t.into_inner().expect("no thread panicked").solutions)
.collect();
all.sort_by_key(|s| s.cost);
let mut front = Front::new();
let solutions = all.into_iter().filter(|s| front.insert(s.cost)).collect();
Output {
solutions,
stats: Stats {
expanded: shared.expanded.into_inner(),
generated: shared.generated.into_inner(),
},
}
}