Skip to main content

multiobjective_search/
reference.rs

1//! A brute-force reference for cross-checking the search algorithms.
2
3use alloc::collections::BTreeSet;
4use alloc::vec::Vec;
5
6use search_core::Cost;
7
8use crate::cost::{Dominates, add};
9use crate::graph::Graph;
10use crate::output::{Output, Solution, Stats};
11
12/// Finds one path for every Pareto-optimal cost vector by enumerating
13/// every simple path from `start`, for any number of objectives.
14///
15/// Meant for tests on small graphs: it takes time exponential in the
16/// graph size, and recursion depth up to the longest simple path. With
17/// non-negative costs every Pareto-optimal cost vector is the cost of
18/// some simple path, so the result is exact. It shares no dominance code
19/// with the searches beyond [`Dominates`], so a disagreement points at the
20/// search. For a polynomial-per-label reference, use
21/// [`namoa_star`](crate::namoa_star) with
22/// [`ZeroHeuristic`](crate::ZeroHeuristic), the classic multi-objective
23/// label-setting algorithm.
24///
25/// Paths do not continue through a goal: with non-negative costs, a
26/// longer path to another goal is never cheaper. Solutions are sorted
27/// lexicographically ascending, one per cost vector; among equal-cost
28/// paths the first one found is kept. [`Output::stats`] counts the states
29/// visited by the enumeration as `expanded`, and the paths reaching a goal
30/// as `generated`.
31///
32/// # Examples
33///
34/// ```
35/// use multiobjective_search::{Graph, ZeroHeuristic, brute_force, namoa_star};
36///
37/// /// Two parallel routes from 0 to 1, plus a dominated one.
38/// struct Routes;
39///
40/// impl Graph for Routes {
41///     type State = u8;
42///     type Weight = [u32; 3];
43///
44///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 3])>) {
45///         if *state == 0 {
46///             out.extend([(1, [1, 2, 3]), (1, [3, 2, 1]), (1, [3, 3, 3])]);
47///         }
48///     }
49/// }
50///
51/// let reference = brute_force(&Routes, 0, |s| *s == 1);
52/// let search = namoa_star(&Routes, ZeroHeuristic, 0, |s| *s == 1);
53/// assert_eq!(reference.solutions, search.solutions);
54/// ```
55pub fn brute_force<G, C, P, const N: usize>(
56    graph: &G,
57    start: G::State,
58    is_goal: P,
59) -> Output<G::State, [C; N]>
60where
61    G: Graph<Weight = [C; N]>,
62    C: Cost,
63    P: Fn(&G::State) -> bool,
64{
65    let mut enumeration = Enumeration {
66        graph,
67        is_goal,
68        path: Vec::new(),
69        on_path: BTreeSet::new(),
70        found: Vec::new(),
71        stats: Stats::default(),
72    };
73    enumeration.visit(start, [C::ZERO; N]);
74
75    Output {
76        solutions: non_dominated(enumeration.found),
77        stats: enumeration.stats,
78    }
79}
80
81/// State of the depth-first enumeration of simple paths.
82struct Enumeration<'a, G: Graph, P, const N: usize> {
83    /// The graph being enumerated.
84    graph: &'a G,
85    /// Goal test.
86    is_goal: P,
87    /// States of the current path, from the start.
88    path: Vec<G::State>,
89    /// The same states as `path`, for `O(log n)` membership.
90    on_path: BTreeSet<G::State>,
91    /// Every start-to-goal path found, dominated ones included.
92    found: Vec<Solution<G::State, G::Weight>>,
93    /// Effort counters.
94    stats: Stats,
95}
96
97impl<G, C, P, const N: usize> Enumeration<'_, G, P, N>
98where
99    G: Graph<Weight = [C; N]>,
100    C: Cost,
101    P: Fn(&G::State) -> bool,
102{
103    /// Extends the current path by `state`, reached at cost `cost`, then
104    /// records it if `state` is a goal or recurses into every successor
105    /// not already on the path.
106    fn visit(&mut self, state: G::State, cost: [C; N]) {
107        self.stats.expanded += 1;
108        self.path.push(state.clone());
109
110        if (self.is_goal)(&state) {
111            self.stats.generated += 1;
112            self.found.push(Solution {
113                cost,
114                path: self.path.clone(),
115            });
116        } else {
117            let mut successors = Vec::new();
118            self.graph.successors(&state, &mut successors);
119            self.on_path.insert(state);
120
121            for (next, weight) in successors {
122                if !self.on_path.contains(&next) {
123                    self.visit(next, add(cost, weight));
124                }
125            }
126        }
127
128        if let Some(last) = self.path.pop() {
129            self.on_path.remove(&last);
130        }
131    }
132}
133
134/// Keeps one solution per non-dominated cost vector, sorted
135/// lexicographically by cost, with a naive `O(n²)` filter.
136fn non_dominated<S, C: Cost, const N: usize>(
137    found: Vec<Solution<S, [C; N]>>,
138) -> Vec<Solution<S, [C; N]>> {
139    let costs: Vec<_> = found.iter().map(|s| s.cost).collect();
140    let mut kept: Vec<_> = found
141        .into_iter()
142        .filter(|s| !costs.iter().any(|c| c.dominates(&s.cost)))
143        .collect();
144
145    // Stable, so the first path found wins among equal costs.
146    kept.sort_by_key(|s| s.cost);
147    kept.dedup_by_key(|s| s.cost);
148
149    kept
150}