Skip to main content

multiobjective_search/
cost.rs

1//! Cost vectors and Pareto dominance.
2//!
3//! A cost vector is a plain array `[C; N]` of a scalar [`Cost`] from
4//! `search-core`. Arrays already provide `Copy` and lexicographic `Ord`, and
5//! `[C::ZERO; N]` is the zero vector, so no newtype is needed.
6
7use search_core::Cost;
8
9/// Pareto dominance between cost vectors.
10pub trait Dominates {
11    /// Returns `true` if `self` is no worse than `other` in every objective
12    /// and strictly better in at least one.
13    fn dominates(&self, other: &Self) -> bool;
14}
15
16impl<C: Cost, const N: usize> Dominates for [C; N] {
17    fn dominates(&self, other: &Self) -> bool {
18        weakly_dominates(self, other) && self != other
19    }
20}
21
22/// Returns `true` if `a` is no worse than `b` in every objective.
23///
24/// Unlike [`Dominates::dominates`], equal vectors weakly dominate each other.
25/// Pruning uses this form: a label equal to a known one adds no new cost
26/// vector to the result.
27#[must_use]
28pub fn weakly_dominates<C: Cost, const N: usize>(a: &[C; N], b: &[C; N]) -> bool {
29    a.iter().zip(b).all(|(x, y)| x <= y)
30}
31
32/// Adds two cost vectors component-wise.
33#[must_use]
34pub fn add<C: Cost, const N: usize>(a: [C; N], b: [C; N]) -> [C; N] {
35    core::array::from_fn(|i| a[i] + b[i])
36}
37
38#[cfg(test)]
39mod tests {
40    //! Unit tests for dominance and vector addition.
41
42    use super::{Dominates, add, weakly_dominates};
43
44    /// Strict dominance needs one strictly better component.
45    #[test]
46    fn dominance_is_strict() {
47        assert!([1_u32, 2].dominates(&[1, 3]));
48        assert!(![1_u32, 2].dominates(&[1, 2]));
49        assert!(![1_u32, 4].dominates(&[2, 3]));
50    }
51
52    /// Weak dominance accepts equal vectors.
53    #[test]
54    fn weak_dominance_accepts_equal() {
55        assert!(weakly_dominates(&[1_u32, 2], &[1, 2]));
56        assert!(!weakly_dominates(&[1_u32, 4], &[2, 3]));
57    }
58
59    /// Addition is component-wise.
60    #[test]
61    fn add_is_componentwise() {
62        assert_eq!(add([1_u8, 2, 3], [4, 5, 6]), [5, 7, 9]);
63    }
64}