Skip to main content

multiobjective_search/apex/
anytime.rs

1//! A-A*pex: anytime A*pex that reuses its search effort across tolerance
2//! iterations (Zhang, Salzman, Felner, Hernández Ulloa, Koenig, "A-A*pex:
3//! Efficient Anytime Approximate Multi-Objective Search", `SoCS` 2024,
4//! Algorithm 2).
5
6use alloc::collections::{BTreeMap, BinaryHeap};
7use alloc::vec::Vec;
8use core::cmp::Reverse;
9
10use search_core::{Budget, Cost, Heuristic, WideMul};
11
12use super::Excess;
13use crate::anytime_boa::{AnytimeFront, ApproxFactor};
14use crate::cost::{add, weakly_dominates};
15use crate::epsilon::Epsilon;
16use crate::graph::Graph;
17use crate::output::{Solution, Stats};
18use crate::pareto::Front;
19use crate::pp_a::iterative::as_factor;
20
21/// How A-A*pex starts each iteration (the paper's Section 4 variants).
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum AnytimeApex {
24    /// A-A*pex-reuse (Algorithm 2): start from the representative paths
25    /// earlier iterations pruned or discarded while merging.
26    #[default]
27    Reuse,
28    /// A-A*pex-reuse-enh: as [`AnytimeApex::Reuse`], and also prune a pair
29    /// whose apex a representative expanded in an earlier iteration at its
30    /// state weakly dominates.
31    ReuseEnhanced,
32    /// A-A*pex-restart: start every iteration from the start state, keeping
33    /// only the solutions.
34    Restart,
35    /// A-A*pex-hybrid: restart until an iteration expands more than
36    /// `threshold` times as many pairs as it prunes paths (the paper uses
37    /// 5), then reuse.
38    Hybrid {
39        /// The expansions-to-pruned-paths ratio that switches to reuse.
40        threshold: u32,
41    },
42}
43
44/// A-A*pex: anytime approximate search for any number of objectives,
45/// [`AnytimeApex::Reuse`] with [`apex_star_anytime_with`].
46///
47/// # Examples
48///
49/// ```
50/// use multiobjective_search::{Epsilon, Graph, ZeroHeuristic, apex_star_anytime};
51///
52/// /// Three routes from 0 to 1 with three objectives.
53/// struct Routes;
54///
55/// impl Graph for Routes {
56///     type State = u8;
57///     type Weight = [u32; 3];
58///
59///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 3])>) {
60///         if *state == 0 {
61///             out.extend([(1, [100, 100, 50]), (1, [104, 98, 51]), (1, [50, 200, 100])]);
62///         }
63///     }
64/// }
65///
66/// let schedule = [[Epsilon::new(1, 10); 3], [Epsilon::ZERO; 3]];
67/// let mut sizes = Vec::new();
68/// let result = apex_star_anytime(&Routes, ZeroHeuristic, 0, |s| *s == 1, schedule, |front, _| sizes.push(front.len()), |_: &_| false);
69/// assert!(result.complete && result.factor.is_zero());
70/// assert_eq!(sizes, [2, 3]);
71/// ```
72pub fn apex_star_anytime<G, H, C, P, const N: usize>(
73    graph: &G,
74    heuristic: H,
75    start: G::State,
76    is_goal: P,
77    schedule: impl IntoIterator<Item = [Epsilon; N]>,
78    on_front: impl FnMut(&[Solution<G::State, [C; N]>], ApproxFactor<C>),
79    budget: impl Budget<Stats>,
80) -> AnytimeFront<G::State, C, N>
81where
82    G: Graph<Weight = [C; N]>,
83    H: Heuristic<G::State, [C; N]>,
84    C: Cost + WideMul,
85    P: Fn(&G::State) -> bool,
86{
87    apex_star_anytime_with(
88        graph,
89        heuristic,
90        start,
91        is_goal,
92        schedule,
93        AnytimeApex::Reuse,
94        on_front,
95        budget,
96    )
97}
98
99/// A-A*pex with a chosen variant.
100///
101/// Each iteration takes the next tolerance vector `ε` from `schedule` (the
102/// paper's `getNextEps`; it uses 0.1 divided by `η` each time) and runs
103/// A*pex's `findApproxPF` with `ε` (Algorithm 1 as the paper restates it:
104/// solutions are plain paths, a pair is pruned when a solution is within
105/// `ε` of its `f` in every objective or a pair expanded at its state in this
106/// iteration weakly dominates it in objectives `1..N`, and new pairs merge
107/// greedily into an open pair at their state when the result is
108/// ε-bounded). The solutions persist across iterations. Whatever a pruning
109/// or a merge drops but might still lead to a Pareto-optimal solution goes
110/// to the list `Pruned` (lines 53-54, 57-59, 68-70), and the next iteration
111/// starts from those paths as pairs `⟨c(π), π⟩` instead of from the start
112/// (lines 42-45), which recovers the paths a merge represented. After an
113/// iteration the solutions are an `ε`-approximate front (Theorem 1); once an
114/// iteration ends with `Pruned` empty they are the exact front (Theorem 2)
115/// and the search stops, possibly before the schedule ends. A schedule that
116/// ends with zero tolerances always gets there.
117///
118/// `on_front` gets the solutions after every iteration that lowers the
119/// factor (the iteration's largest tolerance, zero once exact). `budget` is
120/// checked between iterations.
121///
122/// Requirements as for [`apex_star`](crate::apex_star): non-negative costs,
123/// a consistent heuristic zero on goals.
124///
125/// # Panics
126///
127/// Panics if a solution path is malformed, which cannot happen.
128#[expect(
129    clippy::too_many_arguments,
130    reason = "the anytime search inputs plus the variant"
131)]
132pub fn apex_star_anytime_with<G, H, C, P, const N: usize>(
133    graph: &G,
134    heuristic: H,
135    start: G::State,
136    is_goal: P,
137    schedule: impl IntoIterator<Item = [Epsilon; N]>,
138    variant: AnytimeApex,
139    mut on_front: impl FnMut(&[Solution<G::State, [C; N]>], ApproxFactor<C>),
140    mut budget: impl Budget<Stats>,
141) -> AnytimeFront<G::State, C, N>
142where
143    G: Graph<Weight = [C; N]>,
144    H: Heuristic<G::State, [C; N]>,
145    C: Cost + WideMul,
146    P: Fn(&G::State) -> bool,
147{
148    let mut search = Anytime::new(graph, heuristic, is_goal, variant, start);
149    let mut reported: Option<ApproxFactor<C>> = None;
150    let mut complete = false;
151    let mut reuse = matches!(variant, AnytimeApex::Reuse | AnytimeApex::ReuseEnhanced);
152
153    for eps in schedule {
154        if reported.is_some() && budget.exhausted(&search.stats) {
155            break;
156        }
157
158        let (expanded, pruned) = search.iterate(eps, reuse);
159        if let AnytimeApex::Hybrid { threshold } = variant {
160            reuse = reuse || expanded > pruned.saturating_mul(threshold as usize);
161        }
162
163        complete = search.pruned.is_empty();
164        let front = search.front();
165        let factor = if complete {
166            ApproxFactor::Zero
167        } else {
168            as_factor(widest(eps), &front)
169        };
170        if reported.is_none_or(|r| factor < r) {
171            reported = Some(factor);
172            on_front(&front, factor);
173        }
174
175        if complete {
176            break;
177        }
178    }
179
180    AnytimeFront {
181        solutions: search.front(),
182        factor: reported.unwrap_or(ApproxFactor::Infinite),
183        complete,
184        stats: search.stats,
185    }
186}
187
188/// The largest tolerance of `eps`.
189fn widest<const N: usize>(eps: [Epsilon; N]) -> Epsilon {
190    eps.into_iter()
191        .reduce(|a, b| {
192            let larger =
193                u64::from(b.num()) * u64::from(a.den()) > u64::from(a.num()) * u64::from(b.den());
194            if larger { b } else { a }
195        })
196        .unwrap_or(Epsilon::ZERO)
197}
198
199/// An apex-path pair.
200#[derive(Clone, Copy)]
201struct Pair<C, const N: usize> {
202    /// The apex.
203    apex: [C; N],
204    /// The representative path, an index into the path arena.
205    rep: usize,
206    /// The heuristic at the pair's state.
207    h: [C; N],
208    /// `false` once merged away.
209    alive: bool,
210}
211
212/// The state of one A-A*pex run across its iterations.
213struct Anytime<'a, G: Graph, H, C, P, const N: usize> {
214    /// The graph.
215    graph: &'a G,
216    /// The heuristic.
217    heuristic: H,
218    /// Goal test.
219    is_goal: P,
220    /// Which variant runs.
221    variant: AnytimeApex,
222    /// The start state.
223    start: G::State,
224    /// Every path: state, cost, parent.
225    paths: Vec<(G::State, [C; N], Option<usize>)>,
226    /// Pairs of the current iteration.
227    pairs: Vec<Pair<C, N>>,
228    /// Open list on `(f, pair index)`.
229    open: BinaryHeap<Reverse<([C; N], usize)>>,
230    /// Open pairs per state, for merging.
231    open_at: BTreeMap<G::State, Vec<usize>>,
232    /// `G^Tr_cl` of this iteration: per state, the apexes expanded (compared
233    /// on objectives `1..N`) with their representatives.
234    closed: BTreeMap<G::State, Vec<([C; N], usize)>>,
235    /// `C(s)` of the enhanced checks: per state, the costs of the
236    /// representatives expanded in any iteration.
237    expanded: BTreeMap<G::State, Front<C, N>>,
238    /// Solution paths, mutually non-dominated.
239    solutions: Vec<usize>,
240    /// `Pruned`: paths that may still lead to Pareto-optimal solutions.
241    pruned: Vec<usize>,
242    /// The tolerances of the current iteration.
243    eps: [Epsilon; N],
244    /// Effort counters over all iterations.
245    stats: Stats,
246}
247
248impl<'a, G, H, C, P, const N: usize> Anytime<'a, G, H, C, P, N>
249where
250    G: Graph<Weight = [C; N]>,
251    H: Heuristic<G::State, [C; N]>,
252    C: Cost + WideMul,
253    P: Fn(&G::State) -> bool,
254{
255    /// A run with `Pruned = {[s_start]}` (line 38).
256    fn new(graph: &'a G, heuristic: H, is_goal: P, variant: AnytimeApex, start: G::State) -> Self {
257        let mut search = Self {
258            graph,
259            heuristic,
260            is_goal,
261            variant,
262            start: start.clone(),
263            paths: Vec::new(),
264            pairs: Vec::new(),
265            open: BinaryHeap::new(),
266            open_at: BTreeMap::new(),
267            closed: BTreeMap::new(),
268            expanded: BTreeMap::new(),
269            solutions: Vec::new(),
270            pruned: Vec::new(),
271            eps: [Epsilon::ZERO; N],
272            stats: Stats::default(),
273        };
274        search.paths.push((start, [C::ZERO; N], None));
275        search.pruned.push(0);
276        search
277    }
278
279    /// One iteration (lines 41-46); returns its expansions and the number
280    /// of paths it pruned.
281    fn iterate(&mut self, eps: [Epsilon; N], reuse: bool) -> (usize, usize) {
282        self.eps = eps;
283        self.pairs.clear();
284        self.open.clear();
285        self.open_at.clear();
286        self.closed.clear();
287        let before = self.stats.expanded;
288
289        let seeds = core::mem::take(&mut self.pruned);
290        let seeds = if reuse {
291            seeds
292        } else {
293            self.paths.push((self.start.clone(), [C::ZERO; N], None));
294            alloc::vec![self.paths.len() - 1]
295        };
296
297        for path in seeds {
298            let (state, cost) = (self.paths[path].0.clone(), self.paths[path].1);
299            if let Some(h) = self.heuristic.estimate(&state) {
300                self.add_to_open(Pair {
301                    apex: cost,
302                    rep: path,
303                    h,
304                    alive: true,
305                });
306            }
307        }
308
309        self.find_approx_front();
310        (self.stats.expanded - before, self.pruned.len())
311    }
312
313    /// `findApproxPF` (lines 8-21).
314    fn find_approx_front(&mut self) {
315        while let Some(Reverse((_, index))) = self.open.pop() {
316            let pair = self.pairs[index];
317            if !pair.alive {
318                continue;
319            }
320
321            let state = self.paths[pair.rep].0.clone();
322            if let Some(list) = self.open_at.get_mut(&state) {
323                list.retain(|&i| i != index);
324            }
325
326            if self.is_dominated(&pair) {
327                continue;
328            }
329
330            self.closed
331                .entry(state.clone())
332                .or_default()
333                .push((pair.apex, pair.rep));
334            if self.variant == AnytimeApex::ReuseEnhanced {
335                let cost = self.paths[pair.rep].1;
336                self.expanded.entry(state.clone()).or_default().insert(cost);
337            }
338
339            if (self.is_goal)(&state) {
340                let cost = self.paths[pair.rep].1;
341                let paths = &self.paths;
342                self.solutions
343                    .retain(|&s| !weakly_dominates(&cost, &paths[s].1));
344                self.solutions.push(pair.rep);
345                continue;
346            }
347
348            self.expand(pair);
349        }
350    }
351
352    /// Lines 17-21: the children of `pair`.
353    fn expand(&mut self, pair: Pair<C, N>) {
354        self.stats.expanded += 1;
355
356        let state = self.paths[pair.rep].0.clone();
357        let mut edges = Vec::new();
358        self.graph.successors(&state, &mut edges);
359        for (next, weight) in edges {
360            let Some(h) = self.heuristic.estimate(&next) else {
361                continue;
362            };
363
364            let cost = add(self.paths[pair.rep].1, weight);
365            self.paths.push((next, cost, Some(pair.rep)));
366            let child = Pair {
367                apex: add(pair.apex, weight),
368                rep: self.paths.len() - 1,
369                h,
370                alive: true,
371            };
372            if !self.is_dominated(&child) {
373                self.add_to_open(child);
374                self.stats.generated += 1;
375            }
376        }
377    }
378
379    /// `isDominated` (lines 51-61), adding to `Pruned` what may still lead
380    /// to a Pareto-optimal solution.
381    fn is_dominated(&mut self, pair: &Pair<C, N>) -> bool {
382        let (state, rep_cost) = (self.paths[pair.rep].0.clone(), self.paths[pair.rep].1);
383        let f = add(pair.apex, pair.h);
384        let rep_f = add(rep_cost, pair.h);
385
386        let covering = self
387            .solutions
388            .iter()
389            .map(|&s| self.paths[s].1)
390            .find(|c| (0..N).all(|i| self.eps[i].within(c[i], f[i])));
391        if let Some(c) = covering {
392            if !weakly_dominates(&c, &rep_f) {
393                self.pruned.push(pair.rep);
394            }
395
396            return true;
397        }
398
399        let dominator = self.closed.get(&state).and_then(|list| {
400            list.iter()
401                .find(|(x, _)| (1..N).all(|i| x[i] <= pair.apex[i]))
402                .map(|&(_, r)| r)
403        });
404        if let Some(r) = dominator {
405            if !weakly_dominates(&self.paths[r].1, &rep_cost) {
406                self.pruned.push(pair.rep);
407            }
408
409            return true;
410        }
411
412        self.variant == AnytimeApex::ReuseEnhanced
413            && self
414                .expanded
415                .get(&state)
416                .is_some_and(|c| c.weakly_dominates(&pair.apex))
417    }
418
419    /// `addToOpen` (lines 62-73): merges into the first open pair at the
420    /// state that gives an ε-bounded pair, sending the dropped
421    /// representative to `Pruned` unless the kept one dominates it.
422    fn add_to_open(&mut self, pair: Pair<C, N>) {
423        let state = self.paths[pair.rep].0.clone();
424        let candidates = self.open_at.get(&state).cloned().unwrap_or_default();
425        for other in candidates {
426            let Some(merged) = self.merge(pair, self.pairs[other]) else {
427                continue;
428            };
429
430            self.pairs[other].alive = false;
431            if let Some(list) = self.open_at.get_mut(&state) {
432                list.retain(|&i| i != other);
433            }
434
435            let dropped = if merged.rep == pair.rep {
436                self.pairs[other].rep
437            } else {
438                pair.rep
439            };
440            if !weakly_dominates(&self.paths[merged.rep].1, &self.paths[dropped].1) {
441                self.pruned.push(dropped);
442            }
443
444            self.push(merged);
445            return;
446        }
447
448        self.push(pair);
449    }
450
451    /// Queues a pair.
452    fn push(&mut self, pair: Pair<C, N>) {
453        let state = self.paths[pair.rep].0.clone();
454        self.pairs.push(pair);
455        let index = self.pairs.len() - 1;
456        self.open.push(Reverse((add(pair.apex, pair.h), index)));
457        self.open_at.entry(state).or_default().push(index);
458    }
459
460    /// The greedy merge of A*pex: the component-wise minimum apex and the
461    /// representative with the smaller worst excess, if one is ε-bounded.
462    fn merge(&self, a: Pair<C, N>, b: Pair<C, N>) -> Option<Pair<C, N>> {
463        let apex = core::array::from_fn(|i| a.apex[i].min(b.apex[i]));
464        let for_a = Pair {
465            apex,
466            rep: a.rep,
467            h: a.h,
468            alive: true,
469        };
470        let for_b = Pair {
471            apex,
472            rep: b.rep,
473            h: a.h,
474            alive: true,
475        };
476
477        match (self.excess(&for_a), self.excess(&for_b)) {
478            (Some(x), Some(y)) if x.is_greater(y) => Some(for_b),
479            (Some(_), _) => Some(for_a),
480            (None, Some(_)) => Some(for_b),
481            (None, None) => None,
482        }
483    }
484
485    /// The worst relative excess of the representative's `f` over the
486    /// apex's, or `None` if the pair is not ε-bounded.
487    fn excess(&self, pair: &Pair<C, N>) -> Option<Excess<C>> {
488        let f_rep = add(self.paths[pair.rep].1, pair.h);
489        let f_apex = add(pair.apex, pair.h);
490        if !(0..N).all(|i| self.eps[i].within(f_rep[i], f_apex[i])) {
491            return None;
492        }
493
494        let ratios = (0..N)
495            .filter(|&i| f_rep[i] != f_apex[i])
496            .map(|i| Excess::Ratio {
497                over: f_rep[i]
498                    .abs_diff(f_apex[i])
499                    .saturating_times(self.eps[i].den()),
500                of: f_apex[i].saturating_times(self.eps[i].num()),
501            });
502
503        Some(ratios.fold(Excess::Zero, |x, y| if y.is_greater(x) { y } else { x }))
504    }
505
506    /// The solutions so far, sorted by cost.
507    fn front(&self) -> Vec<Solution<G::State, [C; N]>> {
508        let mut out: Vec<_> = self.solutions.iter().map(|&s| self.solution(s)).collect();
509        out.sort_by_key(|s| s.cost);
510        out
511    }
512
513    /// The solution for path `index`.
514    fn solution(&self, index: usize) -> Solution<G::State, [C; N]> {
515        let mut path = Vec::new();
516        let mut at = Some(index);
517        while let Some(i) = at {
518            path.push(self.paths[i].0.clone());
519            at = self.paths[i].2;
520        }
521
522        path.reverse();
523        Solution {
524            cost: self.paths[index].1,
525            path,
526        }
527    }
528}