Skip to main content

multiobjective_search/
boa.rs

1//! BOA*: bi-objective A* search.
2//!
3//! Hernández, Yeoh, Baier, Zhang, Suazo, Koenig, Salzman: "A Simple and
4//! Fast Bi-Objective Search Algorithm", ICAPS 2020.
5//!
6//! Labels leave the open list in lexicographic `(f1, f2)` order. With a
7//! consistent heuristic, a label is then dominated exactly when its `g2` is
8//! no smaller than the smallest `g2` already expanded at its state, or its
9//! `f2` is no smaller than the `g2` of the last solution found. Both checks
10//! are `O(1)` per state, so BOA* needs no per-state frontier.
11//!
12//! ```mermaid
13//! graph TD
14//!     pop[Pop min f1, f2] --> pruned{Dominated?}
15//!     pruned -- yes --> pop
16//!     pruned -- no --> record[g2_min of state = g2]
17//!     record --> goal{Goal?}
18//!     goal -- yes --> solution[Add solution] --> pop
19//!     goal -- no --> expand[Generate successors, prune, push] --> pop
20//! ```
21
22use alloc::collections::{BTreeMap, BinaryHeap};
23use alloc::vec::Vec;
24use core::cmp::Reverse;
25use core::mem;
26
27use search_core::{Cost, Heuristic};
28
29use crate::cost::add;
30use crate::epsilon::Epsilon;
31use crate::graph::Graph;
32use crate::output::{Output, Solution, Stats};
33
34/// Finds one path for every Pareto-optimal cost vector from `start` to a
35/// state that satisfies `is_goal`.
36///
37/// Requirements, not checked at run time:
38///
39/// - edge costs are non-negative;
40/// - `heuristic` is consistent in both objectives and zero on every goal.
41///
42/// With [`ZeroHeuristic`](crate::ZeroHeuristic) the search is a
43/// bi-objective Dijkstra. Solutions are sorted by the first objective
44/// ascending and so by the second strictly descending.
45///
46/// # Examples
47///
48/// ```
49/// use multiobjective_search::{Graph, ZeroHeuristic, boa_star};
50///
51/// /// Two routes from 0 to 2: fast but costly, or slow but cheap.
52/// struct Routes;
53///
54/// impl Graph for Routes {
55///     type State = u8;
56///     type Weight = [u32; 2];
57///
58///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
59///         match state {
60///             0 => out.extend([(1, [1, 5]), (2, [4, 1])]),
61///             1 => out.push((2, [1, 5])),
62///             _ => {}
63///         }
64///     }
65/// }
66///
67/// let out = boa_star(&Routes, ZeroHeuristic, 0, |s| *s == 2);
68/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
69/// assert_eq!(costs, [[2, 10], [4, 1]]);
70/// assert_eq!(out.solutions[0].path, [0, 1, 2]);
71/// ```
72pub fn boa_star<G, H, C, P>(
73    graph: &G,
74    heuristic: H,
75    start: G::State,
76    is_goal: P,
77) -> Output<G::State, [C; 2]>
78where
79    G: Graph<Weight = [C; 2]>,
80    H: Heuristic<G::State, [C; 2]>,
81    C: Cost,
82    P: Fn(&G::State) -> bool,
83{
84    run(graph, heuristic, start, is_goal, Tolerance::EXACT)
85}
86
87/// [`boa_star`] with an additive tolerance `slack` on the second
88/// objective: returns a subset of the Pareto-optimal solutions that covers
89/// every Pareto-optimal cost vector within `slack`.
90///
91/// Guarantees, under the requirements of [`boa_star`]:
92///
93/// - every returned solution is Pareto-optimal, and they are sorted as in
94///   [`boa_star`];
95/// - for every Pareto-optimal cost vector `s` some returned solution `r`
96///   has `r[0] <= s[0]` and `r[1] <= s[1] + slack`.
97///
98/// `slack = 0` is exactly [`boa_star`]. The only change is the pruning by
99/// solutions: a label is dropped once `f2 + slack` reaches the second cost
100/// of the last solution, so larger tolerances expand fewer labels. The
101/// first objective is never relaxed.
102///
103/// This is an additive variant of the multiplicative
104/// [`boa_star_eps`] (BOA*ε); [`pp_a_star`](crate::pp_a_star) also relaxes the
105/// first objective.
106///
107/// `f2 + slack` must not overflow `C`: a slack near `C::MAX` panics in
108/// debug builds and wraps in release builds.
109///
110/// # Examples
111///
112/// ```
113/// use multiobjective_search::{Graph, ZeroHeuristic, boa_star_approx};
114///
115/// /// Three routes from 0 to 1 whose second costs differ by one each.
116/// struct Routes;
117///
118/// impl Graph for Routes {
119///     type State = u8;
120///     type Weight = [u32; 2];
121///
122///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
123///         if *state == 0 {
124///             out.extend([(1, [1, 3]), (1, [2, 2]), (1, [3, 1])]);
125///         }
126///     }
127/// }
128///
129/// let out = boa_star_approx(&Routes, ZeroHeuristic, 0, |s| *s == 1, 1);
130/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
131/// assert_eq!(costs, [[1, 3], [3, 1]]); // [2, 2] is within 1 of [1, 3]
132/// ```
133pub fn boa_star_approx<G, H, C, P>(
134    graph: &G,
135    heuristic: H,
136    start: G::State,
137    is_goal: P,
138    slack: C,
139) -> Output<G::State, [C; 2]>
140where
141    G: Graph<Weight = [C; 2]>,
142    H: Heuristic<G::State, [C; 2]>,
143    C: Cost,
144    P: Fn(&G::State) -> bool,
145{
146    run(graph, heuristic, start, is_goal, Tolerance::Additive(slack))
147}
148
149/// BOA*ε: [`boa_star`] with a multiplicative tolerance `1 + eps` on the
150/// second objective.
151///
152/// Guarantees, under the requirements of [`boa_star`]:
153///
154/// - every returned solution is Pareto-optimal, and they are sorted as in
155///   [`boa_star`];
156/// - for every Pareto-optimal cost vector `s` some returned solution `r`
157///   has `r[0] <= s[0]` and `r[1] <= (1 + eps) · s[1]`.
158///
159/// As in Goldin and Salzman's BOA*ε (ICAPS 2021, eq. 2), the only change to
160/// [`boa_star`] is the pruning by solutions: a label is dropped once
161/// `(1 + eps) · f2` reaches the second cost of the last solution. The
162/// per-state pruning stays exact, so the first objective is never relaxed;
163/// [`pp_a_star`](crate::pp_a_star) relaxes both. `eps` = [`Epsilon::ZERO`]
164/// is exactly [`boa_star`].
165///
166/// # Why the guarantee holds
167///
168/// Labels leave the open list in lexicographic `f` order, so a solution
169/// `r` found before a label `x` has `r[0] <= f1(x)`. A label dropped because
170/// `r[1] <= (1 + eps) · f2(x)` only leads to solutions `s >= f(x)`, which
171/// `r` covers. A label dropped by the exact per-state test is dominated by
172/// an expanded label at the same state, whose completions dominate its own.
173/// A returned solution `r'` passed the test against every earlier `r`, so
174/// `(1 + eps) · r'[1] < r[1]`; a pruned path `s` with `r[1] <= (1 + eps) ·
175/// s[1]` then has `s[1] > r'[1]` and cannot dominate `r'`.
176///
177/// # Examples
178///
179/// ```
180/// use multiobjective_search::{Epsilon, Graph, ZeroHeuristic, boa_star_eps};
181///
182/// /// Three routes from 0 to 1.
183/// struct Routes;
184///
185/// impl Graph for Routes {
186///     type State = u8;
187///     type Weight = [u32; 2];
188///
189///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
190///         if *state == 0 {
191///             out.extend([(1, [1, 110]), (1, [2, 100]), (1, [3, 50])]);
192///         }
193///     }
194/// }
195///
196/// let out = boa_star_eps(&Routes, ZeroHeuristic, 0, |s| *s == 1, Epsilon::new(1, 10));
197/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
198/// assert_eq!(costs, [[1, 110], [3, 50]]); // 110 <= 1.1 * 100
199/// ```
200pub fn boa_star_eps<G, H, C, P>(
201    graph: &G,
202    heuristic: H,
203    start: G::State,
204    is_goal: P,
205    eps: Epsilon,
206) -> Output<G::State, [C; 2]>
207where
208    G: Graph<Weight = [C; 2]>,
209    H: Heuristic<G::State, [C; 2]>,
210    C: Cost,
211    P: Fn(&G::State) -> bool,
212{
213    run(graph, heuristic, start, is_goal, Tolerance::Relative(eps))
214}
215
216/// Runs one unidirectional BOA* search with the given solution-pruning
217/// tolerance.
218fn run<G, H, C, P>(
219    graph: &G,
220    heuristic: H,
221    start: G::State,
222    is_goal: P,
223    tolerance: Tolerance<C>,
224) -> Output<G::State, [C; 2]>
225where
226    G: Graph<Weight = [C; 2]>,
227    H: Heuristic<G::State, [C; 2]>,
228    C: Cost,
229    P: Fn(&G::State) -> bool,
230{
231    let mut search = Search::new(graph, heuristic, is_goal, tolerance);
232    search.push_start(start);
233    while search.step() {}
234
235    search.into_output()
236}
237
238/// How much worse in the second objective a pruned label may be than the
239/// last solution that prunes it.
240#[derive(Debug, Clone, Copy)]
241pub(crate) enum Tolerance<C> {
242    /// Prune when `f2 + slack >= best`.
243    Additive(C),
244    /// Prune when `best <= (1 + ε) · f2`.
245    Relative(Epsilon),
246}
247
248impl<C: Cost> Tolerance<C> {
249    /// No tolerance: exact BOA* pruning, `f2 >= best`.
250    pub(crate) const EXACT: Self = Self::Additive(C::ZERO);
251
252    /// Returns `true` if a solution with second cost `best` covers every
253    /// completion of a label with second estimate `f2`.
254    fn covers(self, best: C, f2: C) -> bool {
255        match self {
256            Self::Additive(slack) => f2 + slack >= best,
257            Self::Relative(eps) => eps.within(best, f2),
258        }
259    }
260}
261
262/// A known completion of a state to the target, for BOBA*'s early
263/// solution update: the cost of the completion that is optimal in the
264/// primary objective (ties broken by the secondary one).
265pub(crate) struct Completion<C> {
266    /// Primary cost of the completion, the exact primary distance.
267    pub(crate) primary: C,
268    /// Secondary cost of the same completion.
269    pub(crate) secondary: C,
270    /// `true` if the completion is also optimal in the secondary
271    /// objective, so it dominates every other completion and the state
272    /// need not be expanded.
273    pub(crate) terminal: bool,
274}
275
276/// Completions of states to the target, known before the search runs.
277pub(crate) trait Completions<S, C> {
278    /// The primary-optimal completion of `state`, or `None` if unknown.
279    fn completion(&self, state: &S) -> Option<Completion<C>>;
280
281    /// Appends the states of that completion after `state`, target
282    /// included.
283    fn suffix(&self, state: &S, out: &mut Vec<S>);
284}
285
286/// No known completions: plain BOA*.
287#[derive(Debug, Clone, Copy, Default)]
288pub(crate) struct NoCompletions;
289
290impl<S, C> Completions<S, C> for NoCompletions {
291    fn completion(&self, _state: &S) -> Option<Completion<C>> {
292        None
293    }
294
295    fn suffix(&self, _state: &S, _out: &mut Vec<S>) {}
296}
297
298/// A search label: one path to a state, stored in the node arena.
299struct Node<S, C> {
300    /// The state this path ends in.
301    state: S,
302    /// Cost vector of the path from the start.
303    g: [C; 2],
304    /// Arena index of the predecessor label; `None` for the start.
305    parent: Option<usize>,
306}
307
308/// Mutable state of one BOA* run.
309///
310/// Also one direction of BOBA*, which drives two of these step by step and
311/// exchanges their bounds; see [`Search::set_primary_bound`].
312pub(crate) struct Search<'a, G: Graph, H, C, P, K = NoCompletions> {
313    /// The graph being searched.
314    graph: &'a G,
315    /// Per-objective lower bounds on the remaining cost.
316    heuristic: H,
317    /// Goal test.
318    is_goal: P,
319    /// Tolerance on the second objective when pruning by solutions.
320    /// Additive zero for exact search.
321    tolerance: Tolerance<C>,
322    /// Labels with `f1` at or above this bound are pruned, and the search
323    /// stops once the open list reaches it. `None` (no bound) except in
324    /// BOBA*, where it is the first cost of the other direction's last
325    /// solution.
326    primary_bound: Option<C>,
327    /// Every generated label; open-list entries and parents index into it.
328    nodes: Vec<Node<G::State, C>>,
329    /// Open list as a min-heap on `(f, arena index)`, `f` compared
330    /// lexicographically. The index breaks ties deterministically.
331    open: BinaryHeap<Reverse<([C; 2], usize)>>,
332    /// Smallest `g2` of any label expanded (or recorded as solution) per
333    /// state. Absent means "not reached yet".
334    g2_min: BTreeMap<G::State, C>,
335    /// `g2` of the most recent solution, which is the smallest so far;
336    /// `None` until the first solution.
337    best_goal_g2: Option<C>,
338    /// Solutions in the order found, first objective ascending.
339    solutions: Vec<Solution<G::State, [C; 2]>>,
340    /// Reused successor buffer, empty between expansions.
341    successors: Vec<(G::State, [C; 2])>,
342    /// Effort counters.
343    stats: Stats,
344    /// Known completions for the early solution update; [`NoCompletions`]
345    /// outside BOBA*'s own heuristics.
346    completions: K,
347    /// Raised lower bounds on the secondary heuristic per state, from the
348    /// other direction's first expansions (BOBA*'s heuristic tuning).
349    secondary_floor: BTreeMap<G::State, C>,
350    /// The state and primary `g` of the latest first expansion of a state,
351    /// until [`Search::take_first_expansion`] collects it.
352    first_expansion: Option<(G::State, C)>,
353}
354
355impl<'a, G, H, C, P> Search<'a, G, H, C, P>
356where
357    G: Graph<Weight = [C; 2]>,
358    H: Heuristic<G::State, [C; 2]>,
359    C: Cost,
360    P: Fn(&G::State) -> bool,
361{
362    /// Creates an empty plain BOA* search with no labels.
363    pub(crate) fn new(graph: &'a G, heuristic: H, is_goal: P, tolerance: Tolerance<C>) -> Self {
364        Search::with_completions(graph, heuristic, is_goal, tolerance, NoCompletions)
365    }
366}
367
368impl<'a, G, H, C, P, K> Search<'a, G, H, C, P, K>
369where
370    G: Graph<Weight = [C; 2]>,
371    H: Heuristic<G::State, [C; 2]>,
372    C: Cost,
373    P: Fn(&G::State) -> bool,
374    K: Completions<G::State, C>,
375{
376    /// Creates an empty search with no labels that uses `completions` for
377    /// the early solution update.
378    pub(crate) fn with_completions(
379        graph: &'a G,
380        heuristic: H,
381        is_goal: P,
382        tolerance: Tolerance<C>,
383        completions: K,
384    ) -> Self {
385        Self {
386            graph,
387            heuristic,
388            is_goal,
389            tolerance,
390            primary_bound: None,
391            nodes: Vec::new(),
392            open: BinaryHeap::new(),
393            g2_min: BTreeMap::new(),
394            best_goal_g2: None,
395            solutions: Vec::new(),
396            successors: Vec::new(),
397            stats: Stats::default(),
398            completions,
399            secondary_floor: BTreeMap::new(),
400            first_expansion: None,
401        }
402    }
403
404    /// Raises the secondary heuristic of `state` to at least `floor`, from
405    /// the other direction's first expansion of `state`.
406    pub(crate) fn raise_secondary(&mut self, state: G::State, floor: C) {
407        let entry = self.secondary_floor.entry(state).or_insert(floor);
408        *entry = (*entry).max(floor);
409    }
410
411    /// The state and primary `g` of the latest first expansion of a state
412    /// since the last call, if any.
413    pub(crate) fn take_first_expansion(&mut self) -> Option<(G::State, C)> {
414        self.first_expansion.take()
415    }
416
417    /// Processes the next label from the open list.
418    ///
419    /// Returns `false`, without processing anything, once the search is
420    /// done: the open list is empty or its best label has `f1` at or above
421    /// the primary bound.
422    pub(crate) fn step(&mut self) -> bool {
423        let Some(Reverse((f, index))) = self.open.pop() else {
424            return false;
425        };
426
427        if self.primary_bound.is_some_and(|bound| f[0] >= bound) {
428            return false;
429        }
430
431        self.process(f, index);
432
433        true
434    }
435
436    /// The second cost of the last solution found, which is the smallest
437    /// so far; `None` before the first one.
438    pub(crate) fn secondary_bound(&self) -> Option<C> {
439        self.best_goal_g2
440    }
441
442    /// Sets the bound on `f1` beyond which labels cannot lead to new
443    /// solutions. Only ever lowered, by the BOBA* driver.
444    pub(crate) fn set_primary_bound(&mut self, bound: Option<C>) {
445        self.primary_bound = bound;
446    }
447
448    /// Consumes the search and returns its solutions and counters.
449    pub(crate) fn into_output(self) -> Output<G::State, [C; 2]> {
450        Output {
451            solutions: self.solutions,
452            stats: self.stats,
453        }
454    }
455
456    /// Pushes the start label, unless the heuristic reports it as a dead end.
457    pub(crate) fn push_start(&mut self, start: G::State) {
458        if let Some(h) = self.estimate(&start) {
459            self.push(start, [C::ZERO; 2], h, None);
460        }
461    }
462
463    /// The heuristic estimate of `state`, with the secondary objective
464    /// raised to its tuned floor.
465    fn estimate(&mut self, state: &G::State) -> Option<[C; 2]> {
466        let mut h = self.heuristic.estimate(state)?;
467        if let Some(&floor) = self.secondary_floor.get(state) {
468            h[1] = h[1].max(floor);
469        }
470
471        Some(h)
472    }
473
474    /// Handles one label taken from the open list: prune, record a
475    /// solution (early, through a known completion, or at a goal), or
476    /// expand.
477    fn process(&mut self, f: [C; 2], index: usize) {
478        let node = &self.nodes[index];
479        if self.is_dominated(&node.state, node.g[1], f) {
480            return;
481        }
482
483        let (state, g) = (node.state.clone(), node.g);
484        if self.g2_min.insert(state.clone(), g[1]).is_none() {
485            self.first_expansion = Some((state.clone(), g[0]));
486        }
487
488        if let Some(completion) = self.completions.completion(&state) {
489            let cost = [g[0] + completion.primary, g[1] + completion.secondary];
490            if self.best_goal_g2.is_none_or(|best| cost[1] < best) {
491                let solution = self.early_solution(index, cost);
492                self.add_solution(solution);
493            }
494
495            if completion.terminal {
496                return;
497            }
498        }
499
500        if (self.is_goal)(&state) {
501            let solution = self.solution(index);
502            self.add_solution(solution);
503        } else {
504            self.expand(index);
505        }
506    }
507
508    /// Records a solution; it replaces the last one if both have the same
509    /// first cost (the new one then has the smaller second cost).
510    fn add_solution(&mut self, solution: Solution<G::State, [C; 2]>) {
511        self.best_goal_g2 = Some(solution.cost[1]);
512        if self
513            .solutions
514            .last()
515            .is_some_and(|last| last.cost[0] == solution.cost[0])
516        {
517            self.solutions.pop();
518        }
519
520        self.solutions.push(solution);
521    }
522
523    /// The path of the label at `index` joined with the known completion of
524    /// its state, at total cost `cost`.
525    fn early_solution(&self, index: usize, cost: [C; 2]) -> Solution<G::State, [C; 2]> {
526        let mut solution = self.solution(index);
527        self.completions
528            .suffix(&self.nodes[index].state, &mut solution.path);
529
530        solution.cost = cost;
531        solution
532    }
533
534    /// Generates the successors of a label and pushes those that survive
535    /// pruning.
536    fn expand(&mut self, index: usize) {
537        self.stats.expanded += 1;
538
539        let mut successors = mem::take(&mut self.successors);
540        let g = self.nodes[index].g;
541        self.graph
542            .successors(&self.nodes[index].state, &mut successors);
543
544        for (state, weight) in successors.drain(..) {
545            let Some(h) = self.estimate(&state) else {
546                continue;
547            };
548
549            let g_next = add(g, weight);
550            if !self.is_dominated(&state, g_next[1], add(g_next, h)) {
551                self.push(state, g_next, h, Some(index));
552            }
553        }
554
555        self.successors = successors;
556    }
557
558    /// Returns `true` if a label at `state` with second cost `g2` and
559    /// estimate `f` is weakly dominated by an expanded label or by a
560    /// solution (within the tolerance), or is beyond the primary bound.
561    fn is_dominated(&self, state: &G::State, g2: C, f: [C; 2]) -> bool {
562        self.g2_min.get(state).is_some_and(|&min| g2 >= min)
563            || self
564                .best_goal_g2
565                .is_some_and(|best| self.tolerance.covers(best, f[1]))
566            || self.primary_bound.is_some_and(|bound| f[0] >= bound)
567    }
568
569    /// Adds a label to the arena and the open list.
570    fn push(&mut self, state: G::State, g: [C; 2], h: [C; 2], parent: Option<usize>) {
571        let index = self.nodes.len();
572        self.nodes.push(Node { state, g, parent });
573        self.open.push(Reverse((add(g, h), index)));
574        self.stats.generated += 1;
575    }
576
577    /// Rebuilds the path ending in the label at `index`.
578    fn solution(&self, index: usize) -> Solution<G::State, [C; 2]> {
579        let mut path = Vec::new();
580        let mut current = Some(index);
581
582        while let Some(i) = current {
583            path.push(self.nodes[i].state.clone());
584            current = self.nodes[i].parent;
585        }
586
587        path.reverse();
588
589        Solution {
590            cost: self.nodes[index].g,
591            path,
592        }
593    }
594}