1use alloc::collections::{BTreeMap, BinaryHeap};
8use alloc::vec::Vec;
9use core::cmp::Reverse;
10use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
11use std::sync::Mutex;
12
13use search_core::{Cost, Heuristic};
14
15use crate::cost::{add, weakly_dominates};
16use crate::graph::Graph;
17use crate::output::{Output, Solution, Stats};
18use crate::pareto::{Front, TruncatedFront};
19
20#[expect(
77 clippy::needless_pass_by_value,
78 reason = "takes the heuristic by value like every other search; each thread clones it"
79)]
80pub fn parallel_moa_star<G, H, C, P, const N: usize>(
81 graph: &G,
82 heuristic: H,
83 start: G::State,
84 is_goal: P,
85) -> Output<G::State, [C; N]>
86where
87 G: Graph<Weight = [C; N]> + Sync,
88 G::State: Send + Sync,
89 H: Heuristic<G::State, [C; N]> + Clone + Send,
90 C: Cost + Send + Sync,
91 P: Fn(&G::State) -> bool + Sync,
92{
93 let shared = Shared::<G::State, C, N> {
94 threads: (0..N)
95 .map(|_| {
96 Mutex::new(Found {
97 solutions: Vec::new(),
98 latest: None,
99 })
100 })
101 .collect(),
102 bounds: Mutex::new([None; N]),
103 stop: AtomicBool::new(false),
104 expanded: AtomicUsize::new(0),
105 generated: AtomicUsize::new(0),
106 };
107
108 std::thread::scope(|scope| {
109 for lead in 0..N {
110 let (shared, heuristic, is_goal, start) =
111 (&shared, heuristic.clone(), &is_goal, start.clone());
112 scope.spawn(move || Thread::new(graph, heuristic, is_goal, lead, shared).run(start));
113 }
114 });
115
116 merge(shared)
117}
118
119struct Found<S, C, const N: usize> {
121 solutions: Vec<Solution<S, [C; N]>>,
123 latest: Option<C>,
126}
127
128struct Shared<S, C, const N: usize> {
130 threads: Vec<Mutex<Found<S, C, N>>>,
132 bounds: Mutex<[Option<C>; N]>,
134 stop: AtomicBool,
136 expanded: AtomicUsize,
138 generated: AtomicUsize,
140}
141
142struct Thread<'a, G: Graph, H, C, P, const N: usize> {
144 graph: &'a G,
146 heuristic: H,
148 is_goal: &'a P,
150 lead: usize,
152 shared: &'a Shared<G::State, C, N>,
154 nodes: Vec<(G::State, [C; N], Option<usize>)>,
156 open: BinaryHeap<Reverse<([C; N], usize)>>,
158 closed: BTreeMap<G::State, TruncatedFront<C, N>>,
160 levels: Vec<Vec<[C; N]>>,
163 successors: Vec<(G::State, [C; N])>,
165 bounds: [Option<C>; N],
168}
169
170impl<'a, G, H, C, P, const N: usize> Thread<'a, G, H, C, P, N>
171where
172 G: Graph<Weight = [C; N]>,
173 H: Heuristic<G::State, [C; N]>,
174 C: Cost,
175 P: Fn(&G::State) -> bool,
176{
177 fn new(
179 graph: &'a G,
180 heuristic: H,
181 is_goal: &'a P,
182 lead: usize,
183 shared: &'a Shared<G::State, C, N>,
184 ) -> Self {
185 Self {
186 graph,
187 heuristic,
188 is_goal,
189 lead,
190 shared,
191 nodes: Vec::new(),
192 open: BinaryHeap::new(),
193 closed: BTreeMap::new(),
194 levels: (0..N).map(|_| Vec::new()).collect(),
195 successors: Vec::new(),
196 bounds: [None; N],
197 }
198 }
199
200 fn rotate(&self, v: [C; N]) -> [C; N] {
202 core::array::from_fn(|p| v[(self.lead + p) % N])
203 }
204
205 fn run(mut self, start: G::State) {
207 if let Some(h) = self.heuristic.estimate(&start) {
208 self.nodes.push((start, [C::ZERO; N], None));
209 self.open.push(Reverse((self.rotate(h), 0)));
210 self.shared.generated.fetch_add(1, Ordering::Relaxed);
211 }
212
213 while let Some(Reverse((f, index))) = self.open.pop() {
214 if self.shared.stop.load(Ordering::Relaxed) {
215 return;
216 }
217
218 self.bounds = *self
220 .shared
221 .bounds
222 .lock()
223 .expect("no thread panics holding the bounds");
224 if self.bounds[self.lead].is_some_and(|b| f[0] >= b) {
225 break;
226 }
227
228 let (state, g) = (
229 self.nodes[index].0.clone(),
230 self.rotate(self.nodes[index].1),
231 );
232 if self
233 .closed
234 .get(&state)
235 .is_some_and(|c| c.weakly_dominates(&g))
236 || self.dominated(&f)
237 {
238 continue;
239 }
240
241 self.closed
242 .entry(state.clone())
243 .or_insert_with(TruncatedFront::new)
244 .insert(g);
245 if (self.is_goal)(&state) {
246 self.record(index, g);
247 continue;
248 }
249
250 self.expand(index);
251 }
252
253 self.shared.stop.store(true, Ordering::Relaxed);
254 }
255
256 fn expand(&mut self, index: usize) {
258 self.shared.expanded.fetch_add(1, Ordering::Relaxed);
259
260 let mut successors = core::mem::take(&mut self.successors);
261 let (state, g) = (self.nodes[index].0.clone(), self.nodes[index].1);
262 self.graph.successors(&state, &mut successors);
263
264 for (next, weight) in successors.drain(..) {
265 let Some(h) = self.heuristic.estimate(&next) else {
266 continue;
267 };
268
269 let g_next = add(g, weight);
270 let (g_rot, f_rot) = (self.rotate(g_next), self.rotate(add(g_next, h)));
271 if self
272 .closed
273 .get(&next)
274 .is_some_and(|c| c.weakly_dominates(&g_rot))
275 || self.dominated(&f_rot)
276 {
277 continue;
278 }
279
280 self.nodes.push((next, g_next, Some(index)));
281 self.open.push(Reverse((f_rot, self.nodes.len() - 1)));
282 self.shared.generated.fetch_add(1, Ordering::Relaxed);
283 }
284
285 self.successors = successors;
286 }
287
288 fn dominated(&self, f: &[C; N]) -> bool {
291 let over = (0..N).any(|p| self.bounds[(self.lead + p) % N].is_some_and(|b| f[p] >= b));
292
293 over || (1..N).any(|level| {
294 let probe = zero_first(*f, level);
295 self.levels[level]
296 .iter()
297 .any(|v| weakly_dominates(v, &probe))
298 })
299 }
300
301 fn record(&mut self, index: usize, g: [C; N]) {
304 insert(&mut self.levels[1], zero_first(g, 1));
305
306 let solution = rebuild(&self.nodes, index);
307 {
308 let mut found = self.shared.threads[self.lead]
309 .lock()
310 .expect("no thread panics holding its solutions");
311 found.solutions.push(solution);
312 found.latest = Some(g[0]);
313 }
314
315 self.update_bounds();
316 }
317
318 fn update_bounds(&mut self) {
322 for level in 1..N.saturating_sub(1) {
323 let objective = (self.lead + level) % N;
324 let latest = self.shared.threads[objective]
325 .lock()
326 .expect("no thread panics holding its solutions")
327 .latest;
328 let Some(z) = latest else { continue };
329
330 let (moved, kept): (Vec<_>, Vec<_>) =
331 self.levels[level].drain(..).partition(|v| v[level] <= z);
332 self.levels[level] = kept;
333 for v in moved {
334 insert(&mut self.levels[level + 1], zero_first(v, level + 1));
335 }
336 }
337
338 if N < 2 {
339 return;
340 }
341
342 if let Some(scalar) = self.levels[N - 1].iter().map(|v| v[N - 1]).min() {
343 let objective = (self.lead + N - 1) % N;
344 let mut bounds = self
345 .shared
346 .bounds
347 .lock()
348 .expect("no thread panics holding the bounds");
349 if bounds[objective].is_none_or(|b| scalar < b) {
350 bounds[objective] = Some(scalar);
351 }
352
353 self.bounds = *bounds;
354 }
355 }
356}
357
358fn zero_first<C: Cost, const N: usize>(mut v: [C; N], count: usize) -> [C; N] {
360 for c in v.iter_mut().take(count) {
361 *c = C::ZERO;
362 }
363
364 v
365}
366
367fn insert<C: Cost, const N: usize>(list: &mut Vec<[C; N]>, v: [C; N]) {
370 if list.iter().any(|w| weakly_dominates(w, &v)) {
371 return;
372 }
373
374 list.retain(|w| !weakly_dominates(&v, w));
375 list.push(v);
376}
377
378fn rebuild<S: Clone, C: Copy, const N: usize>(
380 nodes: &[(S, [C; N], Option<usize>)],
381 index: usize,
382) -> Solution<S, [C; N]> {
383 let mut path = Vec::new();
384 let mut current = Some(index);
385
386 while let Some(i) = current {
387 path.push(nodes[i].0.clone());
388 current = nodes[i].2;
389 }
390
391 path.reverse();
392
393 Solution {
394 cost: nodes[index].1,
395 path,
396 }
397}
398
399fn merge<S, C: Cost, const N: usize>(shared: Shared<S, C, N>) -> Output<S, [C; N]> {
401 let mut all: Vec<Solution<S, [C; N]>> = shared
402 .threads
403 .into_iter()
404 .flat_map(|t| t.into_inner().expect("no thread panicked").solutions)
405 .collect();
406 all.sort_by_key(|s| s.cost);
407
408 let mut front = Front::new();
410 let solutions = all.into_iter().filter(|s| front.insert(s.cost)).collect();
411
412 Output {
413 solutions,
414 stats: Stats {
415 expanded: shared.expanded.into_inner(),
416 generated: shared.generated.into_inner(),
417 },
418 }
419}