Skip to main content

multiobjective_search/
aggregate.rs

1//! Multi-objective search over objective-aggregation functions: solution
2//! objectives computed from hidden search objectives.
3//!
4//! Peer, Weiss, Alterovitz, Salzman: "Generalizing Multi-Objective Search
5//! via Objective-Aggregation Functions", arXiv 2509.22085.
6
7use alloc::collections::{BTreeMap, BinaryHeap};
8use alloc::vec::Vec;
9use core::cmp::Reverse;
10
11use search_core::{Cost, Heuristic};
12
13use crate::cost::add;
14use crate::epsilon::Epsilon;
15use crate::graph::Graph;
16use crate::output::{Output, Solution, Stats};
17use crate::pareto::Front;
18
19/// The functions that turn edge costs into `M` hidden objectives and those
20/// into `K` solution objectives.
21///
22/// - `extend` is the path-cost extension `F_ext(g, c)`: the hidden cost of
23///   a path extended by an edge of weight `c`. It must be monotone in `g`
24///   (`g <= g'` component-wise gives `F_ext(g, c) <= F_ext(g', c)`) and
25///   never decrease `g`. Plain addition is the usual additive case.
26/// - `aggregate` is the objective aggregation `F_agg`: the solution cost of
27///   a path's hidden cost. It must be monotone non-decreasing. The
28///   identity is the usual case.
29#[derive(Debug, Clone, Copy)]
30pub struct Aggregation<X, A> {
31    /// `F_ext`.
32    pub extend: X,
33    /// `F_agg`.
34    pub aggregate: A,
35}
36
37/// The result of [`aggregated_search`]: the solutions with their
38/// aggregated costs, and the hidden cost of each, in the same order.
39pub type Aggregated<S, C, const M: usize, const K: usize> = (Output<S, [C; K]>, Vec<[C; M]>);
40
41/// A solution with its hidden cost.
42type WithHidden<S, C, const M: usize, const K: usize> = (Solution<S, [C; K]>, [C; M]);
43
44/// `(k, m)`-MOS-A*: the paths from `start` to a goal whose aggregated
45/// solution costs `F_agg(c_ext(π))` are Pareto-optimal, or, with tolerances
46/// `eps`, a set that covers each of them within `1 + eps[i]`.
47///
48/// The paper's Algorithm 1 with its changes: the open list is ordered
49/// lexicographically by `F_agg(f)` with `f = g + h` in the hidden space,
50/// labels are pruned against labels expanded at their state by the hidden
51/// `g` (full weak dominance), and against solutions by the aggregated
52/// costs, with the tolerances for the approximate variant. Under the
53/// monotonicity requirements the result is the aggregated front
54/// (Theorem 1). Since the hidden dimension `M` is usually larger than `K`,
55/// this is much faster than the straw man that computes the hidden front
56/// first.
57///
58/// Requirements, not checked at run time: the conditions of
59/// [`Aggregation`], and a `heuristic` in the hidden space with
60/// `g + h(s) <=` the hidden cost of every completion through `s` (zero on
61/// goals). The zero heuristic always qualifies.
62///
63/// Solutions are sorted by aggregated cost, with their hidden costs
64/// alongside; dominated or duplicate aggregated costs are dropped.
65///
66/// # Examples
67///
68/// ```
69/// use multiobjective_search::{Aggregation, Epsilon, Graph, ZeroHeuristic, aggregated_search};
70///
71/// /// Two routes from 0 to 2 through two risky zones (hidden objectives:
72/// /// length, and the worst exposure in each zone).
73/// struct Map;
74///
75/// impl Graph for Map {
76///     type State = u8;
77///     type Weight = [u32; 3];
78///
79///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 3])>) {
80///         match state {
81///             0 => out.extend([(1, [1, 5, 0]), (1, [3, 1, 1])]),
82///             1 => out.push((2, [1, 0, 4])),
83///             _ => {}
84///         }
85///     }
86/// }
87///
88/// // Length adds up; each zone keeps its worst exposure; the solution
89/// // objectives are length and total exposure.
90/// let functions = Aggregation {
91///     extend: |g: &[u32; 3], c: &[u32; 3]| [g[0] + c[0], g[1].max(c[1]), g[2].max(c[2])],
92///     aggregate: |h: &[u32; 3]| [h[0], h[1] + h[2]],
93/// };
94/// let (out, hidden) = aggregated_search(&Map, ZeroHeuristic, 0, |s| *s == 2, functions, [Epsilon::ZERO; 2]);
95/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
96/// assert_eq!(costs, [[2, 9], [4, 5]]);
97/// assert_eq!(hidden, [[2, 5, 4], [4, 1, 4]]);
98/// ```
99pub fn aggregated_search<G, H, X, A, C, P, const M: usize, const K: usize>(
100    graph: &G,
101    mut heuristic: H,
102    start: G::State,
103    is_goal: P,
104    functions: Aggregation<X, A>,
105    eps: [Epsilon; K],
106) -> Aggregated<G::State, C, M, K>
107where
108    G: Graph,
109    H: Heuristic<G::State, [C; M]>,
110    X: Fn(&[C; M], &G::Weight) -> [C; M],
111    A: Fn(&[C; M]) -> [C; K],
112    C: Cost,
113    P: Fn(&G::State) -> bool,
114{
115    let Aggregation { extend, aggregate } = functions;
116    let mut nodes: Vec<(G::State, [C; M], Option<usize>)> = Vec::new();
117    let mut open = BinaryHeap::new();
118    let mut closed: BTreeMap<G::State, Front<C, M>> = BTreeMap::new();
119    let mut found: Vec<[C; K]> = Vec::new();
120    let mut solutions: Vec<WithHidden<G::State, C, M, K>> = Vec::new();
121    let mut successors = Vec::new();
122    let mut stats = Stats::default();
123    let covered = |found: &[[C; K]], f: &[C; K]| {
124        found
125            .iter()
126            .any(|s| (0..K).all(|i| eps[i].within(s[i], f[i])))
127    };
128
129    if let Some(h) = heuristic.estimate(&start) {
130        let g = [C::ZERO; M];
131        nodes.push((start, g, None));
132        open.push(Reverse((aggregate(&add(g, h)), add(g, h), 0)));
133        stats.generated += 1;
134    }
135
136    while let Some(Reverse((key, _, index))) = open.pop() {
137        let (here, g) = (nodes[index].0.clone(), nodes[index].1);
138        if covered(&found, &key) || closed.get(&here).is_some_and(|c| c.weakly_dominates(&g)) {
139            continue;
140        }
141
142        closed.entry(here.clone()).or_default().insert(g);
143        if is_goal(&here) {
144            found.push(aggregate(&g));
145            solutions.push((rebuild(&nodes, index, aggregate(&g)), g));
146            continue;
147        }
148
149        stats.expanded += 1;
150        graph.successors(&here, &mut successors);
151        for (next, weight) in successors.drain(..) {
152            let g_next = extend(&g, &weight);
153            if closed
154                .get(&next)
155                .is_some_and(|c| c.weakly_dominates(&g_next))
156            {
157                continue;
158            }
159
160            let Some(h) = heuristic.estimate(&next) else {
161                continue;
162            };
163
164            let f = add(g_next, h);
165            let key = aggregate(&f);
166            if !covered(&found, &key) {
167                nodes.push((next, g_next, Some(index)));
168                open.push(Reverse((key, f, nodes.len() - 1)));
169                stats.generated += 1;
170            }
171        }
172    }
173
174    solutions.sort_by_key(|(s, _)| s.cost);
175    let mut front = Front::new();
176    solutions.retain(|(s, _)| front.insert(s.cost));
177    let (solutions, hidden) = solutions.into_iter().unzip();
178
179    (Output { solutions, stats }, hidden)
180}
181
182/// Rebuilds the path ending in label `index` with solution cost `cost`.
183fn rebuild<S: Clone, C, const M: usize, const K: usize>(
184    nodes: &[(S, [C; M], Option<usize>)],
185    index: usize,
186    cost: [C; K],
187) -> Solution<S, [C; K]> {
188    let mut path = Vec::new();
189    let mut current = Some(index);
190
191    while let Some(i) = current {
192        path.push(nodes[i].0.clone());
193        current = nodes[i].2;
194    }
195
196    path.reverse();
197
198    Solution { cost, path }
199}