sampling_planning/sampler/
informed.rs1use rand_core::Rng;
4
5use super::unit_f64;
6use crate::radius::{count_to_f64, unit_ball_volume};
7
8#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct ProlateHyperspheroid<const N: usize> {
37 center: [f64; N],
39 focus_a: [f64; N],
41 focus_b: [f64; N],
43 reflection: Option<[f64; N]>,
46 major_radius: f64,
48 minor_radius: f64,
50}
51
52impl<const N: usize> ProlateHyperspheroid<N> {
53 #[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 #[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 #[must_use]
87 pub fn contains(&self, x: &[f64; N]) -> bool {
88 self.cost_through(x) <= 2.0 * self.major_radius
89 }
90
91 #[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 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
122fn norm<const N: usize>(v: &[f64; N]) -> f64 {
124 libm::sqrt(v.iter().map(|x| x * x).sum())
125}
126
127fn 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
135fn 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 (norm(&v) > 1e-12).then_some(v)
150}
151
152fn 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
163fn 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
178fn 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 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 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 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 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}