Skip to main content

multiobjective_search/
reference_point.rs

1//! Reference-point search: Pareto-optimal solutions in order of a
2//! weighted Chebyshev distance to an aspiration point, for interactive
3//! use.
4//!
5//! The reference-point (achievement scalarizing) approach of Wierzbicki,
6//! as used by the interactive methods surveyed by Craveirinha et al.,
7//! Algorithms 17(6):222, 2024 (the INT class).
8
9use alloc::collections::{BTreeMap, BinaryHeap};
10use alloc::vec::Vec;
11use core::cmp::{Ordering, Reverse};
12
13use search_core::{Cost, Heuristic, WideMul};
14
15use crate::constrained::rebuild;
16use crate::cost::add;
17use crate::graph::Graph;
18use crate::output::{Solution, Stats};
19use crate::pareto::Front;
20
21/// A signed achievement value `max_i w_i · (c_i - r_i)`.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub enum Achievement<C> {
24    /// Negative: the cost beats the reference in every objective by at
25    /// least this weighted margin.
26    Below(C),
27    /// Non-negative: the weighted shortfall in the worst objective.
28    Above(C),
29}
30
31impl<C: Ord> PartialOrd for Achievement<C> {
32    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
33        Some(self.cmp(other))
34    }
35}
36
37impl<C: Ord> Ord for Achievement<C> {
38    fn cmp(&self, other: &Self) -> Ordering {
39        match (self, other) {
40            (Self::Below(a), Self::Below(b)) => b.cmp(a),
41            (Self::Above(a), Self::Above(b)) => a.cmp(b),
42            (Self::Below(_), Self::Above(_)) => Ordering::Less,
43            (Self::Above(_), Self::Below(_)) => Ordering::Greater,
44        }
45    }
46}
47
48/// The achievement of `cost`: `max_i weights[i] · (cost[i] -
49/// reference[i])`, the products saturating.
50#[must_use]
51pub fn achievement<C: Cost + WideMul, const N: usize>(
52    cost: &[C; N],
53    reference: &[C; N],
54    weights: &[u32; N],
55) -> Achievement<C> {
56    (0..N)
57        .map(|i| {
58            let gap = cost[i].abs_diff(reference[i]).saturating_times(weights[i]);
59            if cost[i] >= reference[i] {
60                Achievement::Above(gap)
61            } else {
62                Achievement::Below(gap)
63            }
64        })
65        .max()
66        .unwrap_or(Achievement::Above(C::ZERO))
67}
68
69/// An open-list key: the achievement of `f`, `f`, and the arena index.
70type Key<C, const N: usize> = (Achievement<C>, [C; N], usize);
71
72/// An interactive reference-point search: an iterator over the
73/// Pareto-optimal solutions from a start to a goal, the one closest to the
74/// reference point first, by the weighted Chebyshev achievement
75/// `max_i w_i · (c_i - r_i)`.
76///
77/// Best-first search on the achievement of `f = g + h`, a lower bound
78/// since the achievement is monotone; ties go to the lexicographically
79/// smaller `f`, so a solution comes before every one it dominates and only
80/// non-dominated solutions are returned. Labels are dropped when weakly
81/// dominated by a label expanded earlier at their state, or by a returned
82/// solution. [`Iterator::next`] continues the same search: it is the "next
83/// non-dominated solution" query of interactive methods.
84/// [`ReferencePoint::aim`] moves the reference or the weights between
85/// queries without losing the work done, and the solutions already
86/// returned are never proposed again.
87///
88/// Requirements, not checked at run time: non-negative costs and an
89/// admissible `heuristic`, zero on every goal; positive weights.
90///
91/// # Examples
92///
93/// ```
94/// use multiobjective_search::{Graph, ReferencePoint, ZeroHeuristic};
95///
96/// /// Three routes from 0 to 1: (time, money).
97/// struct Routes;
98///
99/// impl Graph for Routes {
100///     type State = u8;
101///     type Weight = [u32; 2];
102///
103///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
104///         if *state == 0 {
105///             out.extend([(1, [1, 9]), (1, [5, 5]), (1, [9, 1])]);
106///         }
107///     }
108/// }
109///
110/// let mut search = ReferencePoint::new(&Routes, ZeroHeuristic, 0, |s: &u8| *s == 1, [4, 4], [1, 1]);
111/// assert_eq!(search.next().map(|s| s.cost), Some([5, 5])); // closest to (4, 4)
112/// search.aim([0, 0], [1, 10]); // money matters ten times more now
113/// assert_eq!(search.next().map(|s| s.cost), Some([9, 1]));
114/// assert_eq!(search.next().map(|s| s.cost), Some([1, 9]));
115/// assert_eq!(search.next(), None);
116/// ```
117pub struct ReferencePoint<'a, G: Graph, H, C, P, const N: usize> {
118    /// The graph being searched.
119    graph: &'a G,
120    /// Lower bounds on the remaining cost.
121    heuristic: H,
122    /// Goal test.
123    is_goal: P,
124    /// The aspiration point.
125    reference: [C; N],
126    /// Positive weights per objective.
127    weights: [u32; N],
128    /// Every label: state, `g`, `f`, parent.
129    nodes: Vec<(G::State, [C; N], Option<usize>)>,
130    /// Open list on `(achievement of f, f, index)`.
131    open: BinaryHeap<Reverse<Key<C, N>>>,
132    /// `g` of the labels expanded per state.
133    closed: BTreeMap<G::State, Front<C, N>>,
134    /// Costs of the solutions returned so far.
135    returned: Front<C, N>,
136    /// Reused successor buffer.
137    successors: Vec<(G::State, [C; N])>,
138    /// Effort counters.
139    stats: Stats,
140}
141
142impl<'a, G, H, C, P, const N: usize> ReferencePoint<'a, G, H, C, P, N>
143where
144    G: Graph<Weight = [C; N]>,
145    H: Heuristic<G::State, [C; N]>,
146    C: Cost + WideMul,
147    P: Fn(&G::State) -> bool,
148{
149    /// Starts a search from `start` toward `reference` with `weights`.
150    pub fn new(
151        graph: &'a G,
152        mut heuristic: H,
153        start: G::State,
154        is_goal: P,
155        reference: [C; N],
156        weights: [u32; N],
157    ) -> Self {
158        let first = heuristic.estimate(&start);
159        let mut search = Self {
160            graph,
161            heuristic,
162            is_goal,
163            reference,
164            weights,
165            nodes: Vec::new(),
166            open: BinaryHeap::new(),
167            closed: BTreeMap::new(),
168            returned: Front::new(),
169            successors: Vec::new(),
170            stats: Stats::default(),
171        };
172
173        if let Some(h) = first {
174            search.push(start, [C::ZERO; N], h, None);
175        }
176
177        search
178    }
179
180    /// Moves the reference point and the weights for the following
181    /// queries; the open labels are re-ranked, nothing is searched again.
182    pub fn aim(&mut self, reference: [C; N], weights: [u32; N]) {
183        self.reference = reference;
184        self.weights = weights;
185
186        let entries: Vec<_> = self.open.drain().map(|Reverse((_, f, i))| (f, i)).collect();
187        for (f, index) in entries {
188            let key = achievement(&f, &self.reference, &self.weights);
189            self.open.push(Reverse((key, f, index)));
190        }
191    }
192
193    /// Effort counters so far.
194    #[must_use]
195    pub const fn stats(&self) -> Stats {
196        self.stats
197    }
198
199    /// Adds a label and queues it.
200    fn push(&mut self, state: G::State, g: [C; N], h: [C; N], parent: Option<usize>) {
201        let f = add(g, h);
202        let key = achievement(&f, &self.reference, &self.weights);
203        self.nodes.push((state, g, parent));
204        self.open.push(Reverse((key, f, self.nodes.len() - 1)));
205        self.stats.generated += 1;
206    }
207
208    /// Generates the successors of the label at `index`.
209    fn expand(&mut self, index: usize) {
210        self.stats.expanded += 1;
211
212        let mut successors = core::mem::take(&mut self.successors);
213        let (state, g) = (self.nodes[index].0.clone(), self.nodes[index].1);
214        self.graph.successors(&state, &mut successors);
215
216        for (next, weight) in successors.drain(..) {
217            let g_next = add(g, weight);
218            if self
219                .closed
220                .get(&next)
221                .is_some_and(|c| c.weakly_dominates(&g_next))
222            {
223                continue;
224            }
225
226            let Some(h) = self.heuristic.estimate(&next) else {
227                continue;
228            };
229
230            if !self.returned.weakly_dominates(&add(g_next, h)) {
231                self.push(next, g_next, h, Some(index));
232            }
233        }
234
235        self.successors = successors;
236    }
237}
238
239impl<G, H, C, P, const N: usize> Iterator for ReferencePoint<'_, G, H, C, P, N>
240where
241    G: Graph<Weight = [C; N]>,
242    H: Heuristic<G::State, [C; N]>,
243    C: Cost + WideMul,
244    P: Fn(&G::State) -> bool,
245{
246    type Item = Solution<G::State, [C; N]>;
247
248    /// The next non-dominated solution, by achievement.
249    fn next(&mut self) -> Option<Self::Item> {
250        while let Some(Reverse((_, f, index))) = self.open.pop() {
251            let (state, g) = (self.nodes[index].0.clone(), self.nodes[index].1);
252            if self.returned.weakly_dominates(&f)
253                || self
254                    .closed
255                    .get(&state)
256                    .is_some_and(|c| c.weakly_dominates(&g))
257            {
258                continue;
259            }
260
261            self.closed.entry(state.clone()).or_default().insert(g);
262            if (self.is_goal)(&state) {
263                self.returned.insert(g);
264                return Some(rebuild(&self.nodes, index));
265            }
266
267            self.expand(index);
268        }
269
270        None
271    }
272}