Skip to main content

sampling_planning/sampler/
informed.rs

1//! Direct sampling of the informed set of a Euclidean path-length problem.
2
3use rand_core::Rng;
4
5use super::unit_f64;
6use crate::radius::{count_to_f64, unit_ball_volume};
7
8/// The prolate hyperspheroid `{x : |x - a| + |x - b| <= max_cost}` in R^N: every state that can
9/// lie on a path from `a` to `b` of Euclidean length at most `max_cost`.
10///
11/// This is the informed set of Informed RRT* and BIT* (Gammell, Srinivasa and Barfoot 2014,
12/// "Informed RRT*: Optimal sampling-based path planning focused via direct sampling of an
13/// admissible ellipsoidal heuristic"). Its foci are `a` and `b`, its transverse diameter is
14/// `max_cost`, and all conjugate diameters are `sqrt(max_cost^2 - |b - a|^2)`.
15///
16/// [`ProlateHyperspheroid::sample`] maps a uniform sample of the unit ball through the
17/// scaling `diag(r_1, r_2, ..., r_2)` and a rotation that takes the first axis onto `b - a`. A
18/// linear map keeps the distribution uniform. The rotation is a Householder reflection rather
19/// than the SVD of Gammell et al.: with all conjugate radii equal, only the first axis has to
20/// be placed, and any orthogonal map that places it yields the same set.
21///
22/// # Examples
23///
24/// ```
25/// use rand_core::SeedableRng;
26/// use sampling_planning::ProlateHyperspheroid;
27///
28/// let ellipse = ProlateHyperspheroid::new([0.0, 0.0], [4.0, 0.0], 5.0).expect("non-degenerate");
29/// let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
30///
31/// for _ in 0..100 {
32///     assert!(ellipse.contains(&ellipse.sample(&mut rng)));
33/// }
34/// ```
35#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct ProlateHyperspheroid<const N: usize> {
37    /// The midpoint of the foci.
38    center: [f64; N],
39    /// The first focus.
40    focus_a: [f64; N],
41    /// The second focus.
42    focus_b: [f64; N],
43    /// The Householder vector `e_1 - (b - a) / |b - a|`, or `None` when no reflection is needed
44    /// (coincident foci, or `b - a` already along the first axis).
45    reflection: Option<[f64; N]>,
46    /// The transverse radius `max_cost / 2`.
47    major_radius: f64,
48    /// The conjugate radius `sqrt(max_cost^2 - |b - a|^2) / 2`; positive.
49    minor_radius: f64,
50}
51
52impl<const N: usize> ProlateHyperspheroid<N> {
53    /// The hyperspheroid with foci `a` and `b` and transverse diameter `max_cost`.
54    ///
55    /// Returns `None` when the set has no interior: `N == 0`, `max_cost` not finite, or
56    /// `max_cost <= |b - a|` (no path is that short, or only the straight segment is).
57    #[must_use]
58    pub fn new(a: [f64; N], b: [f64; N], max_cost: f64) -> Option<Self> {
59        let axis: [f64; N] = core::array::from_fn(|i| b[i] - a[i]);
60        let focal_distance = norm(&axis);
61
62        if N == 0 || !max_cost.is_finite() || max_cost <= focal_distance {
63            return None;
64        }
65
66        Some(Self {
67            center: core::array::from_fn(|i| f64::midpoint(a[i], b[i])),
68            focus_a: a,
69            focus_b: b,
70            reflection: householder_vector(&axis, focal_distance),
71            major_radius: 0.5 * max_cost,
72            minor_radius: 0.5
73                * libm::sqrt((max_cost - focal_distance) * (max_cost + focal_distance)),
74        })
75    }
76
77    /// The Lebesgue measure of the set: `zeta_N r_1 r_2^(N - 1)`.
78    #[must_use]
79    pub fn volume(&self) -> f64 {
80        let n = count_to_f64(N);
81
82        unit_ball_volume(n) * self.major_radius * libm::pow(self.minor_radius, n - 1.0)
83    }
84
85    /// Whether `x` lies in the closed set: `|x - a| + |x - b| <= max_cost`.
86    #[must_use]
87    pub fn contains(&self, x: &[f64; N]) -> bool {
88        self.cost_through(x) <= 2.0 * self.major_radius
89    }
90
91    /// The length `|x - a| + |x - b|` of the shortest path from `a` through `x` to `b`.
92    #[must_use]
93    pub fn cost_through(&self, x: &[f64; N]) -> f64 {
94        distance(&self.focus_a, x) + distance(x, &self.focus_b)
95    }
96
97    /// Draws a state uniformly from the set.
98    ///
99    /// Uses `N + 1` RNG draws when `N` is even and `N + 2` when it is odd (Box-Muller pairs and
100    /// one draw for the radius), plus a retry in the probability-zero case of an all-zero
101    /// Gaussian vector.
102    pub fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> [f64; N] {
103        let ball = unit_ball_sample::<N, R>(rng);
104        let mut x: [f64; N] = core::array::from_fn(|i| {
105            let radius = if i == 0 {
106                self.major_radius
107            } else {
108                self.minor_radius
109            };
110
111            radius * ball[i]
112        });
113
114        if let Some(v) = &self.reflection {
115            reflect(&mut x, v);
116        }
117
118        core::array::from_fn(|i| self.center[i] + x[i])
119    }
120}
121
122/// The Euclidean norm of `v`.
123fn norm<const N: usize>(v: &[f64; N]) -> f64 {
124    libm::sqrt(v.iter().map(|x| x * x).sum())
125}
126
127/// The Euclidean distance between `a` and `b`, computed like
128/// [`Euclidean::distance`](crate::StateSpace::distance).
129fn distance<const N: usize>(a: &[f64; N], b: &[f64; N]) -> f64 {
130    let squared: f64 = a.iter().zip(b).map(|(p, q)| (q - p) * (q - p)).sum();
131
132    libm::sqrt(squared)
133}
134
135/// The Householder vector `v = e_1 - axis / length` whose reflection `I - 2 v v^T / v^T v`
136/// maps `e_1` onto the unit vector along `axis`, or `None` if the identity already does.
137fn householder_vector<const N: usize>(axis: &[f64; N], length: f64) -> Option<[f64; N]> {
138    if length == 0.0 {
139        return None;
140    }
141
142    let v: [f64; N] = core::array::from_fn(|i| {
143        let unit = axis[i] / length;
144
145        if i == 0 { 1.0 - unit } else { -unit }
146    });
147
148    // Below this the reflection is numerically the identity and `v^T v` would underflow.
149    (norm(&v) > 1e-12).then_some(v)
150}
151
152/// Applies the Householder reflection with vector `v` to `x` in place.
153fn reflect<const N: usize>(x: &mut [f64; N], v: &[f64; N]) {
154    let vv: f64 = v.iter().map(|c| c * c).sum();
155    let vx: f64 = v.iter().zip(x.iter()).map(|(a, b)| a * b).sum();
156    let scale = 2.0 * vx / vv;
157
158    for (xi, vi) in x.iter_mut().zip(v) {
159        *xi -= scale * vi;
160    }
161}
162
163/// A uniform sample of the closed unit ball in R^N: a normalized Gaussian vector (uniform on
164/// the sphere) scaled by `u^(1/N)`.
165fn unit_ball_sample<const N: usize, R: Rng + ?Sized>(rng: &mut R) -> [f64; N] {
166    loop {
167        let direction = gaussian_vector::<N, R>(rng);
168        let length = norm(&direction);
169
170        if length > 0.0 {
171            let radius = libm::pow(unit_f64(rng), 1.0 / count_to_f64(N));
172
173            return core::array::from_fn(|i| direction[i] * radius / length);
174        }
175    }
176}
177
178/// `N` independent standard normal values from Box-Muller pairs.
179fn gaussian_vector<const N: usize, R: Rng + ?Sized>(rng: &mut R) -> [f64; N] {
180    let mut out = [0.0; N];
181
182    for pair in out.chunks_mut(2) {
183        // `1 - u` lies in (0, 1], so the logarithm is finite.
184        let radius = libm::sqrt(-2.0 * libm::log(1.0 - unit_f64(rng)));
185        let angle = 2.0 * core::f64::consts::PI * unit_f64(rng);
186
187        pair[0] = radius * libm::cos(angle);
188        if let Some(second) = pair.get_mut(1) {
189            *second = radius * libm::sin(angle);
190        }
191    }
192
193    out
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use rand_core::SeedableRng;
200
201    #[test]
202    fn degenerate_sets_are_rejected() {
203        assert!(ProlateHyperspheroid::new([0.0, 0.0], [3.0, 4.0], 5.0).is_none());
204        assert!(ProlateHyperspheroid::new([0.0, 0.0], [3.0, 4.0], f64::INFINITY).is_none());
205        assert!(ProlateHyperspheroid::<0>::new([], [], 1.0).is_none());
206    }
207
208    #[test]
209    fn volume_matches_the_closed_form_ellipse_area() {
210        let ellipse = ProlateHyperspheroid::new([-3.0, 0.0], [3.0, 0.0], 10.0).expect("valid");
211
212        // Semi-axes 5 and 4.
213        assert!((ellipse.volume() - core::f64::consts::PI * 20.0).abs() < 1e-9);
214    }
215
216    #[test]
217    fn samples_are_inside_and_fill_the_set_uniformly() {
218        // A tilted 3D spheroid; coincident-direction and coincident-foci cases below.
219        for (a, b) in [
220            ([1.0, 2.0, 3.0], [4.0, -2.0, 5.0]),
221            ([0.0, 0.0, 0.0], [2.0, 0.0, 0.0]),
222            ([1.0, 1.0, 1.0], [1.0, 1.0, 1.0]),
223        ] {
224            let max_cost = distance(&a, &b) + 2.0;
225            let set = ProlateHyperspheroid::new(a, b, max_cost).expect("valid");
226            assert_uniform(&set);
227        }
228    }
229
230    /// Asserts that samples of `set` stay inside and that the share of samples in the inner
231    /// copy `cost_through <= c_min + (c - c_min) / 2` matches its volume share.
232    fn assert_uniform(set: &ProlateHyperspheroid<3>) {
233        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(4);
234        let c_min = distance(&set.focus_a, &set.focus_b);
235        let c_max = 2.0 * set.major_radius;
236        let inner_cost = f64::midpoint(c_min, c_max);
237        let inner = ProlateHyperspheroid::new(set.focus_a, set.focus_b, inner_cost).expect("valid");
238        let samples = 40_000;
239        let mut hits = 0_u32;
240        let mut mean = [0.0; 3];
241
242        for _ in 0..samples {
243            let x = set.sample(&mut rng);
244            assert!(set.cost_through(&x) <= c_max + 1e-9, "{x:?} outside");
245
246            hits += u32::from(set.cost_through(&x) <= inner_cost);
247            for (m, xi) in mean.iter_mut().zip(x) {
248                *m += xi / f64::from(samples);
249            }
250        }
251
252        let share = f64::from(hits) / f64::from(samples);
253        let expected = inner.volume() / set.volume();
254        assert!((share - expected).abs() < 0.01, "{share} vs {expected}");
255
256        for (m, c) in mean.iter().zip(set.center) {
257            assert!((m - c).abs() < 0.03 * set.major_radius, "mean {mean:?}");
258        }
259    }
260}