Skip to main content

sampling_planning/sampler/
uniform_box.rs

1//! Uniform sampling in an axis-aligned box.
2
3use super::{ProlateHyperspheroid, Sampler, unit_f64};
4use crate::StateSpace;
5use rand_core::Rng;
6
7/// Samples uniformly from the axis-aligned box `[lower, upper)` in R^N.
8#[derive(Debug, Clone, Copy, PartialEq)]
9pub struct UniformBox<const N: usize> {
10    /// Inclusive lower corner.
11    lower: [f64; N],
12    /// Exclusive upper corner; at least `lower` on every axis.
13    upper: [f64; N],
14}
15
16impl<const N: usize> UniformBox<N> {
17    /// Creates a sampler for the box spanned by `lower` and `upper`.
18    ///
19    /// # Panics
20    ///
21    /// Panics if any bound is not finite or `lower > upper` on any axis.
22    #[must_use]
23    pub fn new(lower: [f64; N], upper: [f64; N]) -> Self {
24        for (lo, hi) in lower.iter().zip(&upper) {
25            assert!(
26                lo.is_finite() && hi.is_finite(),
27                "box bounds must be finite"
28            );
29            assert!(lo <= hi, "box lower bound exceeds upper bound");
30        }
31
32        Self { lower, upper }
33    }
34
35    /// The inclusive lower corner.
36    #[must_use]
37    pub const fn lower(&self) -> &[f64; N] {
38        &self.lower
39    }
40
41    /// The upper corner.
42    #[must_use]
43    pub const fn upper(&self) -> &[f64; N] {
44        &self.upper
45    }
46
47    /// The volume of the box.
48    #[must_use]
49    pub fn volume(&self) -> f64 {
50        self.lower
51            .iter()
52            .zip(&self.upper)
53            .map(|(lo, hi)| hi - lo)
54            .product()
55    }
56
57    /// Whether `state` lies inside the closed box.
58    #[must_use]
59    pub fn contains(&self, state: &[f64; N]) -> bool {
60        (0..N).all(|i| (self.lower[i]..=self.upper[i]).contains(&state[i]))
61    }
62}
63
64impl<const N: usize> Sampler<[f64; N]> for UniformBox<N> {
65    fn sample<R: Rng + ?Sized>(&mut self, rng: &mut R) -> [f64; N] {
66        core::array::from_fn(|i| self.lower[i] + (self.upper[i] - self.lower[i]) * unit_f64(rng))
67    }
68
69    /// Samples the [`ProlateHyperspheroid`] with foci `start` and `goal` and transverse diameter
70    /// `max_cost`, rejecting samples outside the box, which is uniform over the intersection.
71    ///
72    /// Returns `None` without drawing when `space` is not
73    /// [Euclidean](StateSpace::is_euclidean), the set is degenerate, or its volume is at least
74    /// the box volume (then rejection from the box accepts more often). Returns `None` after
75    /// [`INFORMED_BOX_ATTEMPTS`] samples outside the box, which happens when the set reaches
76    /// far out of the box.
77    fn sample_informed<Sp, R>(
78        &mut self,
79        space: &Sp,
80        rng: &mut R,
81        start: &[f64; N],
82        goal: &[f64; N],
83        max_cost: f64,
84    ) -> Option<[f64; N]>
85    where
86        Sp: StateSpace<State = [f64; N]>,
87        R: Rng + ?Sized,
88    {
89        if !space.is_euclidean() {
90            return None;
91        }
92
93        let set = ProlateHyperspheroid::new(*start, *goal, max_cost)?;
94        if set.volume() >= self.volume() {
95            return None;
96        }
97
98        (0..INFORMED_BOX_ATTEMPTS)
99            .map(|_| set.sample(rng))
100            .find(|state| self.contains(state))
101    }
102}
103
104/// The most hyperspheroid samples [`UniformBox`]'s direct informed sampling draws before it
105/// gives up because they keep falling outside the box.
106pub const INFORMED_BOX_ATTEMPTS: usize = 64;
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111    use rand_core::SeedableRng;
112
113    #[test]
114    fn samples_stay_in_box() {
115        let mut sampler = UniformBox::new([-1.0, 2.0, 0.0], [1.0, 5.0, 0.0]);
116        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(3);
117
118        for _ in 0..1000 {
119            let state = sampler.sample(&mut rng);
120            assert!(sampler.contains(&state));
121        }
122    }
123
124    #[test]
125    fn informed_samples_stay_in_the_box_and_the_set() {
126        let mut sampler = UniformBox::new([0.0, 0.0], [10.0, 4.0]);
127        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(5);
128        let (start, goal) = ([1.0, 1.0], [9.0, 1.0]);
129        let space = crate::Euclidean::<2>;
130
131        for _ in 0..1000 {
132            let state = sampler
133                .sample_informed(&space, &mut rng, &start, &goal, 9.0)
134                .expect("a thin ellipse is sampled directly");
135            assert!(sampler.contains(&state));
136            assert!(space.distance(&start, &state) + space.distance(&state, &goal) <= 9.0 + 1e-9);
137        }
138    }
139
140    #[test]
141    fn informed_sampling_declines_without_drawing() {
142        /// An RNG that panics when used.
143        struct NoDraw;
144
145        impl rand_core::TryRng for NoDraw {
146            type Error = core::convert::Infallible;
147
148            fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
149                unreachable!("declining must not draw")
150            }
151
152            fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
153                unreachable!("declining must not draw")
154            }
155
156            fn try_fill_bytes(&mut self, _: &mut [u8]) -> Result<(), Self::Error> {
157                unreachable!("declining must not draw")
158            }
159        }
160
161        let mut sampler = UniformBox::new([0.0, 0.0], [10.0, 10.0]);
162        let (start, goal) = ([1.0, 1.0], [9.0, 9.0]);
163        let euclidean = crate::Euclidean::<2>;
164
165        // Larger than the box, degenerate, and a space that is not Euclidean.
166        assert!(
167            sampler
168                .sample_informed(&euclidean, &mut NoDraw, &start, &goal, 40.0)
169                .is_none()
170        );
171        assert!(
172            sampler
173                .sample_informed(&euclidean, &mut NoDraw, &start, &goal, 1.0)
174                .is_none()
175        );
176        assert!(
177            sampler
178                .sample_informed(&Taxicab, &mut NoDraw, &start, &goal, 12.0)
179                .is_none()
180        );
181    }
182
183    /// The L1 metric on R^2, a space that is not Euclidean.
184    struct Taxicab;
185
186    impl StateSpace for Taxicab {
187        type State = [f64; 2];
188
189        fn dimension(&self) -> usize {
190            2
191        }
192
193        fn distance(&self, a: &[f64; 2], b: &[f64; 2]) -> f64 {
194            libm::fabs(a[0] - b[0]) + libm::fabs(a[1] - b[1])
195        }
196
197        fn interpolate(&self, a: &[f64; 2], b: &[f64; 2], t: f64) -> [f64; 2] {
198            crate::Euclidean::<2>.interpolate(a, b, t)
199        }
200    }
201
202    #[test]
203    #[should_panic(expected = "lower bound exceeds")]
204    fn rejects_inverted_box() {
205        let _ = UniformBox::new([1.0], [0.0]);
206    }
207}