multiobjective_search/pareto/tree.rs
1//! A Pareto frontier in a balanced search tree, for four or more objectives.
2//!
3//! [`Front`](crate::Front) keeps its points in a sorted `Vec`. For three or
4//! more objectives its dominance query scans the whole lexicographic prefix
5//! below the probe, and an insertion shifts the tail. [`TreeFront`] keeps the
6//! same points in a treap (a randomized balanced binary search tree, keyed
7//! lexicographically) whose nodes also store the component-wise minimum and
8//! maximum of their subtree. A query descends only into subtrees whose
9//! minimum is no worse than the probe in every objective, so whole regions
10//! of the frontier are skipped at once. This is the balanced-tree frontier
11//! of EMOA* (Ren et al., `SoCS` 2022), with bounding boxes for the pruning.
12//!
13//! ```mermaid
14//! graph TD
15//! q[weakly_dominates p] --> box{subtree min <= p?}
16//! box -- no --> skip[skip subtree]
17//! box -- yes --> here{node <= p?}
18//! here -- yes --> hit[true]
19//! here -- no --> left[search left]
20//! left --> right{node < p lexicographically?}
21//! right -- yes --> rs[search right]
22//! right -- no --> skip
23//! ```
24//!
25//! Structure operations take expected `O(log n)`. A dominance query is
26//! output-sensitive: it visits the nodes whose bounding box admits the probe,
27//! which is far fewer than `n` on typical fronts but `O(n)` in the worst
28//! case. No dynamic structure with cheap updates answers `d >= 3`
29//! dominance queries in polylogarithmic worst-case time; range trees would,
30//! at `O(log^(d-1) n)` per query and much costlier updates.
31
32use alloc::vec::Vec;
33
34use search_core::Cost;
35
36use crate::cost::weakly_dominates;
37
38/// A Pareto frontier of `N`-objective cost vectors in a balanced tree.
39///
40/// Holds the same points as [`Front`](crate::Front) and answers the same
41/// queries, but with sublinear typical cost for many objectives; see the
42/// module documentation. Prefer [`Front`](crate::Front) for one to three
43/// objectives, where its sorted `Vec` is faster.
44///
45/// # Examples
46///
47/// ```
48/// use multiobjective_search::TreeFront;
49///
50/// let mut front = TreeFront::new();
51/// assert!(front.insert([1_u32, 2, 3, 4]));
52/// assert!(front.insert([4, 3, 2, 1]));
53/// assert!(!front.insert([4, 4, 4, 4])); // dominated by both
54/// assert!(front.insert([1, 2, 3, 3])); // replaces [1, 2, 3, 4]
55/// assert_eq!(front.to_vec(), [[1, 2, 3, 3], [4, 3, 2, 1]]);
56/// assert!(front.weakly_dominates(&[5, 5, 5, 5]));
57/// ```
58#[derive(Debug, Clone)]
59pub struct TreeFront<C, const N: usize> {
60 /// Node arena; freed slots are listed in [`TreeFront::free`].
61 nodes: Vec<TreeNode<C, N>>,
62 /// Arena indices of removed nodes, reused by later insertions.
63 free: Vec<usize>,
64 /// Root of the treap; `None` when empty.
65 root: Option<usize>,
66 /// Number of points stored.
67 len: usize,
68 /// State of the xorshift generator that draws node priorities. Fixed
69 /// seed, so runs are deterministic.
70 rng: u64,
71}
72
73/// One point of a [`TreeFront`] with its subtree summary.
74#[derive(Debug, Clone)]
75struct TreeNode<C, const N: usize> {
76 /// The stored cost vector; the lexicographic search key.
77 point: [C; N],
78 /// Component-wise minimum over this node's subtree, itself included.
79 min: [C; N],
80 /// Component-wise maximum over this node's subtree, itself included.
81 max: [C; N],
82 /// Heap priority: a parent's is at least its children's.
83 priority: u64,
84 /// Subtree of lexicographically smaller points.
85 left: Option<usize>,
86 /// Subtree of lexicographically greater points.
87 right: Option<usize>,
88}
89
90impl<C, const N: usize> Default for TreeFront<C, N> {
91 fn default() -> Self {
92 Self::new()
93 }
94}
95
96impl<C, const N: usize> TreeFront<C, N> {
97 /// Creates an empty frontier.
98 #[must_use]
99 pub const fn new() -> Self {
100 Self {
101 nodes: Vec::new(),
102 free: Vec::new(),
103 root: None,
104 len: 0,
105 rng: 0x9e37_79b9_7f4a_7c15,
106 }
107 }
108
109 /// Number of points on the frontier.
110 #[must_use]
111 pub fn len(&self) -> usize {
112 self.len
113 }
114
115 /// Returns `true` if the frontier holds no points.
116 #[must_use]
117 pub fn is_empty(&self) -> bool {
118 self.len == 0
119 }
120}
121
122impl<C: Cost, const N: usize> TreeFront<C, N> {
123 /// Returns `true` if some point on the frontier is no worse than `point`
124 /// in every objective, equality included.
125 #[must_use]
126 pub fn weakly_dominates(&self, point: &[C; N]) -> bool {
127 self.any_below(self.root, point)
128 }
129
130 /// Inserts `point` unless the frontier already weakly dominates it.
131 ///
132 /// Removes every point that `point` dominates. Returns `true` if the
133 /// point was inserted, `false` if it was dominated by or equal to an
134 /// existing point.
135 pub fn insert(&mut self, point: [C; N]) -> bool {
136 if self.weakly_dominates(&point) {
137 return false;
138 }
139
140 self.root = self.remove_dominated(self.root, &point);
141
142 let node = self.allocate(point);
143 let (less, greater) = self.split(self.root, |q| q < &point);
144 let less = self.merge(less, Some(node));
145 self.root = self.merge(less, greater);
146 self.len += 1;
147
148 true
149 }
150
151 /// The points, strictly ascending in lexicographic order.
152 #[must_use]
153 pub fn to_vec(&self) -> Vec<[C; N]> {
154 let mut out = Vec::with_capacity(self.len);
155 self.collect_in_order(self.root, &mut out);
156
157 out
158 }
159
160 /// Appends the points of the subtree at `node` to `out` in order.
161 fn collect_in_order(&self, node: Option<usize>, out: &mut Vec<[C; N]>) {
162 if let Some(index) = node {
163 let n = &self.nodes[index];
164 self.collect_in_order(n.left, out);
165 out.push(n.point);
166 self.collect_in_order(n.right, out);
167 }
168 }
169
170 /// Returns `true` if the subtree at `node` holds a point that weakly
171 /// dominates `point`.
172 fn any_below(&self, node: Option<usize>, point: &[C; N]) -> bool {
173 let Some(index) = node else {
174 return false;
175 };
176
177 let n = &self.nodes[index];
178 if !weakly_dominates(&n.min, point) {
179 return false;
180 }
181
182 if weakly_dominates(&n.point, point) || self.any_below(n.left, point) {
183 return true;
184 }
185
186 // Points greater than `point` lexicographically cannot be <= it.
187 n.point < *point && self.any_below(n.right, point)
188 }
189
190 /// Removes from the subtree at `node` every point that `point` weakly
191 /// dominates and returns the new subtree root.
192 fn remove_dominated(&mut self, node: Option<usize>, point: &[C; N]) -> Option<usize> {
193 let index = node?;
194 if !weakly_dominates(point, &self.nodes[index].max) {
195 return node;
196 }
197
198 // Points smaller than `point` lexicographically cannot be >= it.
199 if self.nodes[index].point > *point {
200 let left = self.remove_dominated(self.nodes[index].left, point);
201 self.nodes[index].left = left;
202 }
203
204 let right = self.remove_dominated(self.nodes[index].right, point);
205 self.nodes[index].right = right;
206
207 if weakly_dominates(point, &self.nodes[index].point) {
208 self.free.push(index);
209 self.len -= 1;
210 return self.merge(self.nodes[index].left, self.nodes[index].right);
211 }
212
213 self.update(index);
214 node
215 }
216
217 /// Stores a new leaf node for `point` and returns its arena index.
218 fn allocate(&mut self, point: [C; N]) -> usize {
219 let node = TreeNode {
220 point,
221 min: point,
222 max: point,
223 priority: self.next_priority(),
224 left: None,
225 right: None,
226 };
227
228 if let Some(index) = self.free.pop() {
229 self.nodes[index] = node;
230 index
231 } else {
232 self.nodes.push(node);
233 self.nodes.len() - 1
234 }
235 }
236
237 /// Draws the next node priority (xorshift64).
238 fn next_priority(&mut self) -> u64 {
239 self.rng ^= self.rng << 13;
240 self.rng ^= self.rng >> 7;
241 self.rng ^= self.rng << 17;
242 self.rng
243 }
244
245 /// Splits the subtree at `node` into the points for which `goes_left`
246 /// holds and the rest. `goes_left` must be monotone: true on a prefix of
247 /// the lexicographic order.
248 fn split(
249 &mut self,
250 node: Option<usize>,
251 goes_left: impl Fn(&[C; N]) -> bool + Copy,
252 ) -> (Option<usize>, Option<usize>) {
253 let Some(index) = node else {
254 return (None, None);
255 };
256
257 if goes_left(&self.nodes[index].point) {
258 let (middle, right) = self.split(self.nodes[index].right, goes_left);
259 self.nodes[index].right = middle;
260 self.update(index);
261 (Some(index), right)
262 } else {
263 let (left, middle) = self.split(self.nodes[index].left, goes_left);
264 self.nodes[index].left = middle;
265 self.update(index);
266 (left, Some(index))
267 }
268 }
269
270 /// Joins two subtrees where every point of `left` is lexicographically
271 /// smaller than every point of `right`.
272 fn merge(&mut self, left: Option<usize>, right: Option<usize>) -> Option<usize> {
273 let (l, r) = match (left, right) {
274 (None, tree) | (tree, None) => return tree,
275 (Some(l), Some(r)) => (l, r),
276 };
277
278 if self.nodes[l].priority >= self.nodes[r].priority {
279 let merged = self.merge(self.nodes[l].right, Some(r));
280 self.nodes[l].right = merged;
281 self.update(l);
282 Some(l)
283 } else {
284 let merged = self.merge(Some(l), self.nodes[r].left);
285 self.nodes[r].left = merged;
286 self.update(r);
287 Some(r)
288 }
289 }
290
291 /// Recomputes the subtree bounds of `index` from its children.
292 fn update(&mut self, index: usize) {
293 let n = &self.nodes[index];
294 let (mut min, mut max) = (n.point, n.point);
295
296 for child in [n.left, n.right].into_iter().flatten() {
297 let c = &self.nodes[child];
298 for i in 0..N {
299 min[i] = min[i].min(c.min[i]);
300 max[i] = max[i].max(c.max[i]);
301 }
302 }
303
304 let n = &mut self.nodes[index];
305 n.min = min;
306 n.max = max;
307 }
308}
309
310impl<C: Cost, const N: usize> PartialEq for TreeFront<C, N> {
311 /// Two frontiers are equal when they hold the same points.
312 fn eq(&self, other: &Self) -> bool {
313 self.len == other.len && self.to_vec() == other.to_vec()
314 }
315}
316
317impl<C: Cost, const N: usize> Eq for TreeFront<C, N> {}
318
319#[cfg(test)]
320mod tests {
321 //! Unit tests for [`TreeFront`]; the property tests in `tests/it/front.rs`
322 //! cross-check it against [`Front`](crate::Front).
323
324 use super::TreeFront;
325
326 /// Equal points are rejected and the frontier keeps one copy.
327 #[test]
328 fn rejects_equal_point() {
329 let mut front = TreeFront::new();
330 assert!(front.insert([2_u8, 2, 2, 2]));
331 assert!(!front.insert([2, 2, 2, 2]));
332 assert_eq!(front.len(), 1);
333 }
334
335 /// A point that dominates scattered points removes exactly those.
336 #[test]
337 fn removes_scattered_dominated_points() {
338 let mut front = TreeFront::new();
339 for p in [[1_u8, 1, 9, 9], [2, 5, 5, 5], [3, 9, 1, 1], [4, 6, 4, 6]] {
340 assert!(front.insert(p));
341 }
342
343 assert!(front.insert([2, 5, 4, 5]));
344 assert_eq!(front.to_vec(), [[1, 1, 9, 9], [2, 5, 4, 5], [3, 9, 1, 1]]);
345 assert_eq!(front.len(), 3);
346 }
347
348 /// Freed arena slots are reused.
349 #[test]
350 fn reuses_freed_slots() {
351 let mut front = TreeFront::new();
352 for i in 0..8_u8 {
353 assert!(front.insert([i, 8 - i, 1, 1]));
354 }
355
356 assert!(front.insert([0, 0, 0, 0]));
357 assert_eq!(front.to_vec(), [[0, 0, 0, 0]]);
358 assert_eq!(front.nodes.len(), 8);
359 }
360}