Skip to main content

multiobjective_search/pareto/
indexed.rs

1//! An immutable, indexed set of cost vectors for fast "is this weakly
2//! dominated?" queries: the base of SIP-MOSP's frontier snapshots.
3
4use alloc::vec::Vec;
5
6use search_core::Cost;
7
8/// How an [`IndexedFront`] summarizes its vectors.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10pub enum FrontIndex {
11    /// No summary: queries scan the lexicographic prefix.
12    None,
13    /// Component-wise minima of fixed-size blocks of this many vectors
14    /// (SIP-MOSP-BM). A block whose minimum exceeds the query in some
15    /// objective is skipped whole.
16    #[default]
17    Blocks,
18    /// Component-wise minima in a segment tree over the vectors
19    /// (SIP-MOSP-ST), which skips ranges at every granularity.
20    Tree,
21}
22
23/// Default vectors per block of [`FrontIndex::Blocks`].
24pub const DEFAULT_BLOCK: usize = 16;
25
26/// An immutable set of `N`-objective cost vectors, sorted
27/// lexicographically, with a range-minimum index (Xu et al., "Asynchronous
28/// Parallel Search for Exact Multi-Objective Shortest Paths with Versioned
29/// Frontier Snapshots and Indexed Dominance Pruning", arXiv 2609.11944,
30/// Algorithms 4 and 5).
31///
32/// A query `q` first binary-searches the prefix of vectors that are
33/// lexicographically no greater than `q`, since only those can weakly
34/// dominate it. The index then discards every block or tree range whose
35/// component-wise minimum exceeds `q` in some objective; the vectors that
36/// survive are compared exactly, so the answer is the plain dominance
37/// test. The index pays off when the prefix is long and the vectors spread
38/// across objectives; its worst case stays linear.
39///
40/// The vectors need not be mutually non-dominated.
41///
42/// # Examples
43///
44/// ```
45/// use multiobjective_search::{FrontIndex, IndexedFront};
46///
47/// // The base of the paper's Figure 2.
48/// let base = vec![
49///     [4_u32, 9, 9], [5, 8, 7], [6, 4, 9], [6, 7, 8],
50///     [7, 3, 7], [7, 5, 5], [8, 1, 1], [9, 0, 0],
51/// ];
52/// for index in [FrontIndex::None, FrontIndex::Blocks, FrontIndex::Tree] {
53///     let front = IndexedFront::new(base.clone(), index);
54///     assert!(front.weakly_dominates(&[7, 6, 6])); // by [7, 5, 5]
55///     assert!(!front.weakly_dominates(&[6, 6, 6]));
56/// }
57/// ```
58#[derive(Debug, Clone)]
59pub struct IndexedFront<C, const N: usize> {
60    /// The vectors, sorted lexicographically ascending.
61    points: Vec<[C; N]>,
62    /// The summary chosen at construction.
63    index: Summary<C, N>,
64    /// Vectors per block of [`FrontIndex::Blocks`]; at least 1.
65    block: usize,
66}
67
68/// The range minima of an [`IndexedFront`].
69#[derive(Debug, Clone)]
70enum Summary<C, const N: usize> {
71    /// No index.
72    None,
73    /// `mins[k]` is the component-wise minimum of block `k`.
74    Blocks(Vec<[C; N]>),
75    /// A segment tree in heap layout over `leaves` leaf slots (a power of
76    /// two); node 1 is the root, node `i` has children `2i` and `2i + 1`,
77    /// and leaf `j` is node `leaves + j`. Unused leaves are absent.
78    Tree {
79        /// Number of leaf slots, a power of two at least `points.len()`.
80        leaves: usize,
81        /// Range minima per node; `None` for an empty range.
82        mins: Vec<Option<[C; N]>>,
83    },
84}
85
86impl<C: Cost, const N: usize> IndexedFront<C, N> {
87    /// Sorts `points` and builds the chosen index over them, with blocks of
88    /// 16 vectors for [`FrontIndex::Blocks`].
89    #[must_use]
90    pub fn new(points: Vec<[C; N]>, index: FrontIndex) -> Self {
91        Self::with_block_size(points, index, DEFAULT_BLOCK)
92    }
93
94    /// [`IndexedFront::new`] with `block` vectors per block of
95    /// [`FrontIndex::Blocks`] (ignored by the other indexes).
96    ///
97    /// # Panics
98    ///
99    /// Panics if `block` is zero.
100    #[must_use]
101    pub fn with_block_size(mut points: Vec<[C; N]>, index: FrontIndex, block: usize) -> Self {
102        assert!(block > 0, "the block size must be positive");
103        points.sort_unstable();
104        let index = match index {
105            FrontIndex::None => Summary::None,
106            FrontIndex::Blocks => Summary::Blocks(points.chunks(block).map(minimum).collect()),
107            FrontIndex::Tree => tree(&points),
108        };
109
110        Self {
111            points,
112            index,
113            block,
114        }
115    }
116
117    /// The vectors, sorted lexicographically ascending.
118    #[must_use]
119    pub fn as_slice(&self) -> &[[C; N]] {
120        &self.points
121    }
122
123    /// The number of vectors.
124    #[must_use]
125    pub fn len(&self) -> usize {
126        self.points.len()
127    }
128
129    /// Returns `true` if the set is empty.
130    #[must_use]
131    pub fn is_empty(&self) -> bool {
132        self.points.is_empty()
133    }
134
135    /// Returns `true` if some vector is no worse than `q` in every
136    /// objective.
137    #[must_use]
138    pub fn weakly_dominates(&self, q: &[C; N]) -> bool {
139        let prefix = self.points.partition_point(|p| p <= q);
140        let candidates = &self.points[..prefix];
141
142        match &self.index {
143            Summary::None => candidates.iter().any(|p| below(p, q)),
144            Summary::Blocks(mins) => candidates
145                .chunks(self.block)
146                .zip(mins)
147                .any(|(block, min)| below_tail(min, q) && block.iter().any(|p| below(p, q))),
148            Summary::Tree { leaves, mins } => self.tree_dominates(*leaves, mins, prefix, q),
149        }
150    }
151
152    /// The segment-tree query of Algorithm 5: descend from the root into
153    /// ranges inside the prefix whose minima do not exceed `q`.
154    fn tree_dominates(
155        &self,
156        leaves: usize,
157        mins: &[Option<[C; N]>],
158        prefix: usize,
159        q: &[C; N],
160    ) -> bool {
161        // (node, first leaf, number of leaves) of the ranges still to visit.
162        let mut stack = alloc::vec![(1, 0, leaves)];
163
164        while let Some((node, first, width)) = stack.pop() {
165            if first >= prefix {
166                continue;
167            }
168
169            let Some(min) = &mins[node] else { continue };
170            if !below_tail(min, q) {
171                continue;
172            }
173
174            if width == 1 {
175                if below(&self.points[first], q) {
176                    return true;
177                }
178
179                continue;
180            }
181
182            let half = width / 2;
183            stack.push((2 * node + 1, first + half, half));
184            stack.push((2 * node, first, half));
185        }
186
187        false
188    }
189}
190
191/// Builds the segment tree of [`Summary::Tree`].
192fn tree<C: Cost, const N: usize>(points: &[[C; N]]) -> Summary<C, N> {
193    let leaves = points.len().max(1).next_power_of_two();
194    let mut mins = alloc::vec![None; 2 * leaves];
195    for (j, p) in points.iter().enumerate() {
196        mins[leaves + j] = Some(*p);
197    }
198
199    for node in (1..leaves).rev() {
200        mins[node] = match (mins[2 * node], mins[2 * node + 1]) {
201            (Some(a), Some(b)) => Some(core::array::from_fn(|i| a[i].min(b[i]))),
202            (a, b) => a.or(b),
203        };
204    }
205
206    Summary::Tree { leaves, mins }
207}
208
209/// The component-wise minimum of a non-empty block.
210fn minimum<C: Cost, const N: usize>(block: &[[C; N]]) -> [C; N] {
211    block
212        .iter()
213        .copied()
214        .reduce(|a, b| core::array::from_fn(|i| a[i].min(b[i])))
215        .expect("chunks are never empty")
216}
217
218/// Returns `true` if `p <= q` in every objective.
219fn below<C: Cost, const N: usize>(p: &[C; N], q: &[C; N]) -> bool {
220    p.iter().zip(q).all(|(a, b)| a <= b)
221}
222
223/// Returns `true` if `p <= q` in objectives `1..N`; the prefix already
224/// guarantees the first.
225fn below_tail<C: Cost, const N: usize>(p: &[C; N], q: &[C; N]) -> bool {
226    p[1..].iter().zip(&q[1..]).all(|(a, b)| a <= b)
227}
228
229#[cfg(test)]
230mod tests {
231    //! Property tests: every index answers like the plain scan.
232
233    use alloc::vec::Vec;
234
235    use proptest::prelude::*;
236
237    use super::{FrontIndex, IndexedFront};
238
239    proptest! {
240        /// All three indexes agree with exhaustive dominance.
241        #[test]
242        fn indexes_match_scan(
243            points in prop::collection::vec(prop::array::uniform3(0..20_u32), 0..80),
244            queries in prop::collection::vec(prop::array::uniform3(0..20_u32), 1..20),
245        ) {
246            let fronts: Vec<_> = [FrontIndex::None, FrontIndex::Blocks, FrontIndex::Tree]
247                .into_iter()
248                .map(|index| IndexedFront::new(points.clone(), index))
249                .collect();
250
251            for q in &queries {
252                let expected = points.iter().any(|p| (0..3).all(|i| p[i] <= q[i]));
253                for front in &fronts {
254                    prop_assert_eq!(front.weakly_dominates(q), expected);
255                }
256            }
257        }
258    }
259}