Skip to main content

multiobjective_search/
parallel_moa.rs

1//! Parallel MOA*: one lexicographic MOA* per cyclic objective order, with
2//! shared upper bounds.
3//!
4//! Ahmadi, Sturtevant, Raith, Harabor, Jalili: "Parallelizing
5//! Multi-objective A* Search", arXiv 2503.10075.
6
7use 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/// Parallel MOA*: finds one path for every Pareto-optimal cost vector from
21/// `start` to a state that satisfies `is_goal`, with `N` threads.
22///
23/// Thread `i` runs a lexicographic MOA* (lazy dominance checks, one
24/// truncated closed set per state, Algorithm 3) with objective `i` first
25/// and the others in cyclic order (Algorithm 2). Its solutions feed a
26/// multi-level upper bound (Algorithms 4 and 5): a solution's truncated
27/// cost moves one level down, dropping one more objective `j`, once thread
28/// `j` has found a solution at least as expensive in `j`, since every
29/// cheaper one in `j` is then known. A cost truncated `N - 1` times is a
30/// scalar bound on the last objective that every thread prunes against,
31/// and the thread led by that objective stops once its primary cost reaches
32/// it. The search ends when the first thread ends; the union of all
33/// threads' solutions, filtered to its non-dominated vectors, is the
34/// front, whatever the thread timing.
35///
36/// Requirements, not checked at run time:
37///
38/// - edge costs are non-negative;
39/// - `heuristic` is consistent in every objective and zero on every goal
40///   (each thread uses its own clone).
41///
42/// Solutions are sorted lexicographically, one per Pareto-optimal cost.
43///
44/// # Examples
45///
46/// ```
47/// use multiobjective_search::{Graph, ZeroHeuristic, namoa_star, parallel_moa_star};
48///
49/// /// A small diamond with three objectives.
50/// struct Diamond;
51///
52/// impl Graph for Diamond {
53///     type State = u8;
54///     type Weight = [u32; 3];
55///
56///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 3])>) {
57///         match state {
58///             0 => out.extend([(1, [1, 2, 3]), (2, [3, 2, 1]), (3, [5, 5, 5])]),
59///             1 | 2 => out.push((3, [1, 1, 1])),
60///             _ => {}
61///         }
62///     }
63/// }
64///
65/// let out = parallel_moa_star(&Diamond, ZeroHeuristic, 0, |s| *s == 3);
66/// let exact = namoa_star(&Diamond, ZeroHeuristic, 0, |s| *s == 3);
67/// let costs = |o: &multiobjective_search::Output<u8, [u32; 3]>| {
68///     o.solutions.iter().map(|s| s.cost).collect::<Vec<_>>()
69/// };
70/// assert_eq!(costs(&out), costs(&exact));
71/// ```
72///
73/// # Panics
74///
75/// Panics if a thread panics.
76#[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
119/// What one thread has found.
120struct Found<S, C, const N: usize> {
121    /// Its solutions, in the order found.
122    solutions: Vec<Solution<S, [C; N]>>,
123    /// The primary cost of its latest solution: every Pareto-optimal cost
124    /// with a smaller value in this thread's objective is in the union.
125    latest: Option<C>,
126}
127
128/// State shared by the threads.
129struct Shared<S, C, const N: usize> {
130    /// Per thread, its solutions.
131    threads: Vec<Mutex<Found<S, C, N>>>,
132    /// The global scalar upper bound per objective; `None` is infinite.
133    bounds: Mutex<[Option<C>; N]>,
134    /// Set by the first thread to finish.
135    stop: AtomicBool,
136    /// Expansions over all threads.
137    expanded: AtomicUsize,
138    /// Generations over all threads.
139    generated: AtomicUsize,
140}
141
142/// One thread's search.
143struct Thread<'a, G: Graph, H, C, P, const N: usize> {
144    /// The graph.
145    graph: &'a G,
146    /// This thread's heuristic.
147    heuristic: H,
148    /// Goal test.
149    is_goal: &'a P,
150    /// The objective that leads this thread's order.
151    lead: usize,
152    /// Shared state.
153    shared: &'a Shared<G::State, C, N>,
154    /// Labels: state, `g` (original order), parent.
155    nodes: Vec<(G::State, [C; N], Option<usize>)>,
156    /// Open list on rotated `f`.
157    open: BinaryHeap<Reverse<([C; N], usize)>>,
158    /// Rotated `g` of the labels expanded per state, truncated once.
159    closed: BTreeMap<G::State, TruncatedFront<C, N>>,
160    /// `levels[λ]`: rotated solution costs with their first `λ`
161    /// components zeroed (truncated `λ` times), mutually non-dominated.
162    levels: Vec<Vec<[C; N]>>,
163    /// Reused successor buffer.
164    successors: Vec<(G::State, [C; N])>,
165    /// The global bounds as last read, refreshed once per pop so that the
166    /// lock is not taken per generated child.
167    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    /// A thread led by objective `lead`.
178    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    /// `v` in this thread's order: objective `lead` first.
201    fn rotate(&self, v: [C; N]) -> [C; N] {
202        core::array::from_fn(|p| v[(self.lead + p) % N])
203    }
204
205    /// Runs until done or stopped (Algorithm 3), then stops the others.
206    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            // Early termination: the primary cost reached its global bound.
219            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    /// Generates the successors of the label at `index` (lines 16 to 23).
257    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    /// `IsDominatedMD` (Algorithm 4) on a rotated `f`: the global bounds,
289    /// then every truncation level.
290    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    /// Records a solution, publishes it, and updates the bounds (lines 13
302    /// and 14, Algorithm 5).
303    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    /// `UpdateUpperBound` (Algorithm 5): moves solution costs down the
319    /// levels while the next objective's thread has passed them, and turns
320    /// a fully truncated cost into a global bound.
321    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
358/// `v` with its first `count` components set to zero.
359fn 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
367/// Adds `v` to a mutually non-dominated list unless weakly dominated,
368/// dropping what it dominates.
369fn 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
378/// Rebuilds the path ending in label `index`.
379fn 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
399/// The union of the threads' solutions, non-dominated and sorted.
400fn 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    // In lexicographic order, a later vector cannot dominate an earlier one.
409    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}