Skip to main content

multiobjective_search/
pareto.rs

1//! Pareto frontiers of cost vectors.
2
3mod indexed;
4mod tree;
5mod truncated;
6
7use alloc::vec::Vec;
8
9use search_core::Cost;
10
11use crate::cost::weakly_dominates;
12
13pub use indexed::{FrontIndex, IndexedFront};
14pub use tree::TreeFront;
15pub(crate) use truncated::{TruncatedFront, TruncatedTree};
16
17/// A Pareto frontier of `N`-objective cost vectors.
18///
19/// Holds mutually non-dominated points, at most one per distinct vector,
20/// sorted lexicographically ascending. For two objectives that means the
21/// first objective strictly ascending and the second strictly descending.
22///
23/// Only points that are lexicographically no greater than a probe can
24/// weakly dominate it, so queries binary-search that prefix first:
25///
26/// | Operation | `N <= 2` | `N > 2` |
27/// |---|---|---|
28/// | [`Front::weakly_dominates`] | `O(log n)` | `O(log n + k)`, `k` the prefix length |
29/// | [`Front::insert`] | `O(log n)` plus a tail shift | `O(n)` |
30///
31/// # Examples
32///
33/// ```
34/// use multiobjective_search::Front;
35///
36/// let mut front = Front::new();
37/// assert!(front.insert([1_u32, 2, 3]));
38/// assert!(front.insert([3, 2, 1]));
39/// assert!(!front.insert([3, 3, 3])); // dominated by both
40/// assert!(front.insert([1, 2, 2])); // replaces [1, 2, 3]
41/// assert_eq!(front.as_slice(), &[[1, 2, 2], [3, 2, 1]]);
42/// ```
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Front<C, const N: usize> {
45    /// Non-dominated points, strictly ascending in lexicographic order.
46    points: Vec<[C; N]>,
47}
48
49/// A Pareto frontier of two-objective cost vectors: [`Front`] with `N = 2`.
50///
51/// Dominance queries are a binary search, `O(log n)`; an insertion also
52/// shifts the tail, `O(n)` worst case.
53///
54/// # Examples
55///
56/// ```
57/// use multiobjective_search::BiFront;
58///
59/// let mut front = BiFront::new();
60/// assert!(front.insert([3_u32, 1]));
61/// assert!(front.insert([1, 3]));
62/// assert!(!front.insert([4, 4])); // dominated by [3, 1]
63/// assert!(front.insert([2, 2]));
64/// assert!(front.insert([1, 1])); // dominates everything else
65/// assert_eq!(front.as_slice(), &[[1, 1]]);
66/// ```
67pub type BiFront<C> = Front<C, 2>;
68
69impl<C, const N: usize> Default for Front<C, N> {
70    fn default() -> Self {
71        Self { points: Vec::new() }
72    }
73}
74
75impl<C: Cost, const N: usize> Front<C, N> {
76    /// Creates an empty frontier.
77    #[must_use]
78    pub const fn new() -> Self {
79        Self { points: Vec::new() }
80    }
81
82    /// Returns `true` if some point on the frontier is no worse than `point`
83    /// in every objective, equality included.
84    #[must_use]
85    pub fn weakly_dominates(&self, point: &[C; N]) -> bool {
86        let candidates = &self.points[..self.points.partition_point(|q| q <= point)];
87
88        if N <= 2 {
89            // Of all points lexicographically <= point, the last one has the
90            // smallest second cost.
91            candidates
92                .last()
93                .is_some_and(|q| weakly_dominates(q, point))
94        } else {
95            candidates.iter().any(|q| weakly_dominates(q, point))
96        }
97    }
98
99    /// Inserts `point` unless the frontier already weakly dominates it.
100    ///
101    /// Removes every point that `point` dominates. Returns `true` if the
102    /// point was inserted, `false` if it was dominated by or equal to an
103    /// existing point.
104    pub fn insert(&mut self, point: [C; N]) -> bool {
105        if self.weakly_dominates(&point) {
106            return false;
107        }
108
109        // Every point that `point` dominates is lexicographically greater.
110        let start = self.points.partition_point(|q| q < &point);
111
112        if N <= 2 {
113            // shortcut: Vec splice shifts the tail in O(n); use a balanced tree if profiles show it.
114            let dominated = self.points[start..].partition_point(|q| weakly_dominates(&point, q));
115            self.points.splice(start..start + dominated, [point]);
116        } else {
117            self.points.insert(start, point);
118            let mut index = 0;
119            self.points.retain(|q| {
120                let keep = index <= start || !weakly_dominates(&point, q);
121                index += 1;
122                keep
123            });
124        }
125
126        true
127    }
128
129    /// Number of points on the frontier.
130    #[must_use]
131    pub fn len(&self) -> usize {
132        self.points.len()
133    }
134
135    /// Returns `true` if the frontier holds no points.
136    #[must_use]
137    pub fn is_empty(&self) -> bool {
138        self.points.is_empty()
139    }
140
141    /// The points, strictly ascending in lexicographic order.
142    #[must_use]
143    pub fn as_slice(&self) -> &[[C; N]] {
144        &self.points
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    //! Unit tests for [`Front`] and [`BiFront`].
151
152    use super::{BiFront, Front};
153
154    /// Equal points are rejected and the frontier keeps one copy.
155    #[test]
156    fn rejects_equal_point() {
157        let mut front = BiFront::new();
158        assert!(front.insert([2_u8, 2]));
159        assert!(!front.insert([2, 2]));
160        assert_eq!(front.len(), 1);
161    }
162
163    /// A point with an equal first cost and a lower second cost replaces
164    /// the old one.
165    #[test]
166    fn replaces_point_with_equal_first_cost() {
167        let mut front = BiFront::new();
168        assert!(front.insert([1_u8, 5]));
169        assert!(front.insert([3, 3]));
170        assert!(front.insert([3, 2]));
171        assert_eq!(front.as_slice(), &[[1, 5], [3, 2]]);
172    }
173
174    /// Inserting in the middle removes only the run the point dominates.
175    #[test]
176    fn removes_only_dominated_run() {
177        let mut front = BiFront::new();
178        for p in [[0_u8, 9], [2, 7], [4, 5], [6, 3], [8, 1]] {
179            assert!(front.insert(p));
180        }
181
182        assert!(front.insert([3, 3]));
183        assert_eq!(front.as_slice(), &[[0, 9], [2, 7], [3, 3], [8, 1]]);
184    }
185
186    /// In three dimensions, dominated points need not be contiguous.
187    #[test]
188    fn removes_scattered_points_in_three_dimensions() {
189        let mut front = Front::new();
190        for p in [[1_u8, 1, 9], [2, 5, 5], [3, 9, 1], [4, 6, 4]] {
191            assert!(front.insert(p));
192        }
193
194        assert!(front.insert([2, 5, 4]));
195        assert_eq!(front.as_slice(), &[[1, 1, 9], [2, 5, 4], [3, 9, 1]]);
196    }
197}