Skip to main content

lib_jsl_random/
qmc.rs

1//! Tools for quasi-Monte Carlo sampling, following `scipy.stats.qmc`: Latin hypercube samples,
2//! the discrepancy of a point set (how far it is from uniform), and scaling between the unit cube
3//! and a box. The low-discrepancy sequences themselves, plain or scrambled, are
4//! [`SobolSequence`](crate::quasi_random::SobolSequence) and
5//! [`HaltonSequence`](crate::quasi_random::HaltonSequence).
6//!
7//! See the book entry [Quasi-random sequences](https://jwkunz.github.io/lib_jsl/book/random/quasi-random.html).
8
9use crate::uniform_generator::UniformGenerator;
10use lib_jsl_core::ErrorsJSL;
11
12/// A discrepancy measure (SciPy's `method`). All are `L²` discrepancies with closed forms that
13/// cost `O(n² d)`; each is the worst-case integration error, over a unit ball of functions, of
14/// the equal-weight rule on the points.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum Discrepancy {
18    /// Centered `L²` discrepancy (`'CD'`, SciPy's default): boxes with a corner at the nearest
19    /// vertex of the cube. Invariant under reflections `x_k → 1 − x_k`.
20    Centered,
21    /// Wrap-around `L²` discrepancy (`'WD'`): boxes that wrap around the torus. Invariant under
22    /// shifts modulo 1.
23    WrapAround,
24    /// Mixture discrepancy (`'MD'`), which combines the two and avoids some of their blind spots.
25    Mixture,
26    /// The `L²`-star discrepancy (`'L2-star'`): boxes anchored at the origin, Warnock's formula.
27    /// Returned as the discrepancy itself; the others are returned squared, as SciPy does.
28    L2Star,
29}
30
31// ANCHOR: discrepancy
32/// The discrepancy of `points` in `[0, 1]^d` (SciPy's `qmc.discrepancy`): smaller is more uniform.
33pub fn discrepancy(points: &[Vec<f64>], method: Discrepancy) -> Result<f64, ErrorsJSL> {
34    let n = points.len();
35    let d = points.first().map_or(0, |p| p.len());
36    if n == 0 || d == 0 || points.iter().any(|p| p.len() != d) {
37        return Err(ErrorsJSL::InvalidInputRange("discrepancy: need a non-empty set of points of one dimension"));
38    }
39    if points.iter().flatten().any(|x| !(0.0..=1.0).contains(x)) {
40        return Err(ErrorsJSL::InvalidInputRange("discrepancy: the points must lie in the unit cube"));
41    }
42    let nf = n as f64;
43    let df = d as i32;
44    // Σ_i Π_k f(x_ik) and Σ_i Σ_j Π_k g(x_ik, x_jk).
45    let single = |f: &dyn Fn(f64) -> f64| points.iter().map(|p| p.iter().map(|&x| f(x)).product::<f64>()).sum::<f64>();
46    let pairs = |g: &dyn Fn(f64, f64) -> f64| {
47        let mut total = 0.0;
48        for p in points {
49            for q in points {
50                total += p.iter().zip(q).map(|(&x, &y)| g(x, y)).product::<f64>();
51            }
52        }
53        total
54    };
55    Ok(match method {
56        Discrepancy::Centered => {
57            let s1 = single(&|x| 1.0 + 0.5 * (x - 0.5).abs() - 0.5 * (x - 0.5).powi(2));
58            let s2 = pairs(&|x, y| 1.0 + 0.5 * (x - 0.5).abs() + 0.5 * (y - 0.5).abs() - 0.5 * (x - y).abs());
59            (13.0f64 / 12.0).powi(df) - 2.0 / nf * s1 + s2 / (nf * nf)
60        }
61        Discrepancy::WrapAround => {
62            let s2 = pairs(&|x, y| {
63                let t = (x - y).abs();
64                1.5 - t * (1.0 - t)
65            });
66            -(4.0f64 / 3.0).powi(df) + s2 / (nf * nf)
67        }
68        Discrepancy::Mixture => {
69            let s1 = single(&|x| 5.0 / 3.0 - 0.25 * (x - 0.5).abs() - 0.25 * (x - 0.5).powi(2));
70            let s2 = pairs(&|x, y| 15.0 / 8.0 - 0.25 * (x - 0.5).abs() - 0.25 * (y - 0.5).abs() - 0.75 * (x - y).abs() + 0.5 * (x - y).powi(2));
71            (19.0f64 / 12.0).powi(df) - 2.0 / nf * s1 + s2 / (nf * nf)
72        }
73        Discrepancy::L2Star => {
74            let s1 = single(&|x| 1.0 - x * x);
75            let s2 = pairs(&|x, y| 1.0 - x.max(y));
76            (3.0f64.powi(-df) - 2.0f64.powi(1 - df) / nf * s1 + s2 / (nf * nf)).max(0.0).sqrt()
77        }
78    })
79}
80// ANCHOR_END: discrepancy
81
82// ANCHOR: latin_hypercube
83/// `n` points of a Latin hypercube in `[0, 1)^d` (SciPy's `qmc.LatinHypercube`): in every
84/// coordinate, each of the `n` intervals `[i/n, (i+1)/n)` holds exactly one point. Each coordinate
85/// takes an independent random permutation of the intervals; the point is placed uniformly in its
86/// cell, or at the cell's centre when `centered` (SciPy's `scramble=False`).
87pub fn latin_hypercube<G: UniformGenerator>(n: usize, d: usize, centered: bool, rng: &mut G) -> Vec<Vec<f64>> {
88    let mut points = vec![vec![0.0; d]; n];
89    for k in 0..d {
90        let mut perm: Vec<usize> = (0..n).collect();
91        for i in (1..n).rev() {
92            let j = (rng.next_u64() % (i as u64 + 1)) as usize;
93            perm.swap(i, j);
94        }
95        for (p, &cell) in points.iter_mut().zip(&perm) {
96            let offset = if centered { 0.5 } else { rng.next_f64() };
97            p[k] = (cell as f64 + offset) / n as f64;
98        }
99    }
100    points
101}
102// ANCHOR_END: latin_hypercube
103
104/// Maps points from the unit cube to the box `[lower, upper]` (SciPy's `qmc.scale`), or back
105/// when `reverse`.
106pub fn scale(points: &[Vec<f64>], lower: &[f64], upper: &[f64], reverse: bool) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
107    let d = lower.len();
108    if upper.len() != d || points.iter().any(|p| p.len() != d) {
109        return Err(ErrorsJSL::InvalidInputRange("scale: the bounds and points must have one dimension"));
110    }
111    if lower.iter().zip(upper).any(|(l, u)| l.partial_cmp(u) != Some(std::cmp::Ordering::Less)) {
112        return Err(ErrorsJSL::InvalidInputRange("scale: need lower < upper in every coordinate"));
113    }
114    Ok(points
115        .iter()
116        .map(|p| p.iter().zip(lower.iter().zip(upper)).map(|(&x, (&l, &u))| if reverse { (x - l) / (u - l) } else { l + x * (u - l) }).collect())
117        .collect())
118}
119
120
121/// How [`PoissonDisk`] draws candidates around a centre (SciPy's `hypersphere`).
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123#[non_exhaustive]
124pub enum Hypersphere {
125    /// Uniformly in the ball of radius `2r` (the default).
126    Volume,
127    /// On the sphere of radius `1.001 r`, which packs more densely.
128    Surface,
129}
130
131/// Poisson-disk sampling in a box (SciPy's `qmc.PoissonDisk`): random points no two of which are
132/// closer than `radius`, by Bridson's algorithm. A background grid with cells of side `r/√d`
133/// holds at most one point each, so the test for nearby points looks only at the surrounding
134/// cells; new points are drawn as candidates around a random active point and kept if no
135/// existing point is within `r`.
136#[derive(Clone, Debug)]
137pub struct PoissonDisk {
138    d: usize,
139    radius: f64,
140    hypersphere: Hypersphere,
141    ncandidates: usize,
142    lower: Vec<f64>,
143    upper: Vec<f64>,
144    cell: f64,
145    grid_size: Vec<usize>,
146    grid: Vec<Option<usize>>,
147    points: Vec<Vec<f64>>,
148    pool: Vec<usize>,
149}
150
151impl PoissonDisk {
152    /// A sampler in `[lower, upper]` (the unit cube by default, `None`), with SciPy's defaults
153    /// `ncandidates = 30` and [`Hypersphere::Volume`].
154    pub fn new(d: usize, radius: f64, hypersphere: Hypersphere, ncandidates: usize, bounds: Option<(&[f64], &[f64])>) -> Result<Self, ErrorsJSL> {
155        if d == 0 || radius.is_nan() || radius <= 0.0 || ncandidates == 0 {
156            return Err(ErrorsJSL::InvalidInputRange("PoissonDisk: need d ≥ 1, radius > 0 and at least one candidate"));
157        }
158        let (lower, upper) = match bounds {
159            Some((l, u)) if l.len() == d && u.len() == d && l.iter().zip(u).all(|(a, b)| a < b) => (l.to_vec(), u.to_vec()),
160            Some(_) => return Err(ErrorsJSL::InvalidInputRange("PoissonDisk: bounds must have d entries with lower < upper")),
161            None => (vec![0.0; d], vec![1.0; d]),
162        };
163        let cell = radius / (d as f64).sqrt();
164        let grid_size: Vec<usize> = (0..d).map(|k| ((upper[k] - lower[k]) / cell).ceil().max(1.0) as usize).collect();
165        let cells = grid_size.iter().try_fold(1usize, |acc, &g| acc.checked_mul(g)).filter(|&c| c <= 50_000_000).ok_or(ErrorsJSL::InvalidInputRange("PoissonDisk: the radius is too small for the grid"))?;
166        Ok(PoissonDisk { d, radius, hypersphere, ncandidates, lower, upper, cell, grid_size, grid: vec![None; cells], points: Vec::new(), pool: Vec::new() })
167    }
168
169    fn cell_of(&self, p: &[f64]) -> Vec<usize> {
170        (0..self.d).map(|k| (((p[k] - self.lower[k]) / self.cell) as usize).min(self.grid_size[k] - 1)).collect()
171    }
172
173    fn flat(&self, idx: &[usize]) -> usize {
174        idx.iter().zip(&self.grid_size).fold(0, |acc, (&i, &g)| acc * g + i)
175    }
176
177    fn too_close(&self, p: &[f64]) -> bool {
178        let idx = self.cell_of(p);
179        let lo: Vec<usize> = idx.iter().map(|&i| i.saturating_sub(2)).collect();
180        let hi: Vec<usize> = idx.iter().zip(&self.grid_size).map(|(&i, &g)| (i + 3).min(g)).collect();
181        let mut cur = lo.clone();
182        loop {
183            if let Some(j) = self.grid[self.flat(&cur)] {
184                let d2: f64 = self.points[j].iter().zip(p).map(|(a, b)| (a - b) * (a - b)).sum();
185                if d2 < self.radius * self.radius {
186                    return true;
187                }
188            }
189            let mut k = self.d;
190            loop {
191                if k == 0 {
192                    return false;
193                }
194                k -= 1;
195                cur[k] += 1;
196                if cur[k] < hi[k] {
197                    break;
198                }
199                cur[k] = lo[k];
200            }
201        }
202    }
203
204    fn add(&mut self, p: Vec<f64>, out: &mut Vec<Vec<f64>>) {
205        let f = self.flat(&self.cell_of(&p));
206        self.grid[f] = Some(self.points.len());
207        self.pool.push(self.points.len());
208        self.points.push(p.clone());
209        out.push(p);
210    }
211
212    fn normal<G: UniformGenerator>(rng: &mut G) -> f64 {
213        let u = rng.next_f64().max(f64::MIN_POSITIVE);
214        let v = rng.next_f64();
215        (-2.0 * u.ln()).sqrt() * (2.0 * std::f64::consts::PI * v).cos()
216    }
217
218    // ANCHOR: poisson_disk
219    /// Up to `n` new points (fewer when the box is full).
220    pub fn random<G: UniformGenerator>(&mut self, n: usize, rng: &mut G) -> Vec<Vec<f64>> {
221        let mut out = Vec::new();
222        if n == 0 {
223            return out;
224        }
225        if self.points.is_empty() {
226            let p: Vec<f64> = (0..self.d).map(|k| self.lower[k] + rng.next_f64() * (self.upper[k] - self.lower[k])).collect();
227            self.add(p, &mut out);
228        }
229        while !self.pool.is_empty() && out.len() < n {
230            let at = (rng.next_u64() % self.pool.len() as u64) as usize;
231            let centre = self.points[self.pool.swap_remove(at)].clone();
232            for _ in 0..self.ncandidates {
233                let dir: Vec<f64> = (0..self.d).map(|_| Self::normal(rng)).collect();
234                let norm = dir.iter().map(|v| v * v).sum::<f64>().sqrt().max(f64::MIN_POSITIVE);
235                let r = match self.hypersphere {
236                    Hypersphere::Volume => 2.0 * self.radius * rng.next_f64().powf(1.0 / self.d as f64),
237                    Hypersphere::Surface => 1.001 * self.radius,
238                };
239                let cand: Vec<f64> = centre.iter().zip(&dir).map(|(c, v)| c + r * v / norm).collect();
240                if cand.iter().enumerate().any(|(k, &v)| v < self.lower[k] || v > self.upper[k]) || self.too_close(&cand) {
241                    continue;
242                }
243                self.add(cand, &mut out);
244                if out.len() >= n {
245                    break;
246                }
247            }
248        }
249        out
250    }
251    // ANCHOR_END: poisson_disk
252
253    /// Points until no more fit (SciPy's `fill_space`).
254    pub fn fill_space<G: UniformGenerator>(&mut self, rng: &mut G) -> Vec<Vec<f64>> {
255        self.random(usize::MAX, rng)
256    }
257
258    /// Forget all points (SciPy's `reset`).
259    pub fn reset(&mut self) {
260        self.grid.iter_mut().for_each(|c| *c = None);
261        self.points.clear();
262        self.pool.clear();
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269    use crate::quasi_random::{HaltonSequence, SobolSequence};
270    use crate::uniform_generator::UniformRNG;
271
272    #[test]
273    fn discrepancy_of_small_sets() {
274        // One point at the centre of the unit interval: the centered discrepancy is
275        // 13/12 − 2(1) + 1 = 1/12; the L²-star discrepancy is √(1/3 − 3/4 + 1/2) = √(1/12).
276        let p = vec![vec![0.5]];
277        assert!((discrepancy(&p, Discrepancy::Centered).unwrap() - 1.0 / 12.0).abs() < 1e-15);
278        assert!((discrepancy(&p, Discrepancy::L2Star).unwrap() - (1.0f64 / 12.0).sqrt()).abs() < 1e-15);
279        assert!(discrepancy(&[vec![1.5]], Discrepancy::Centered).is_err());
280        assert!(discrepancy(&[], Discrepancy::Centered).is_err());
281    }
282
283    #[test]
284    fn scrambled_sequences_beat_random_points() {
285        let mut rng = UniformRNG::from_seed(7);
286        let n = 256;
287        let random: Vec<Vec<f64>> = (0..n).map(|_| (0..4).map(|_| rng.next_f64()).collect()).collect();
288        let mut sobol = SobolSequence::scrambled(4, &mut rng).unwrap();
289        let sobol_pts: Vec<Vec<f64>> = (0..n).map(|_| sobol.next_point()).collect();
290        let mut halton = HaltonSequence::scrambled(4, &mut rng).unwrap();
291        let halton_pts: Vec<Vec<f64>> = (0..n).map(|_| halton.next_point()).collect();
292        let lhs = latin_hypercube(n, 4, false, &mut rng);
293        let cd = |p: &[Vec<f64>]| discrepancy(p, Discrepancy::Centered).unwrap();
294        assert!(cd(&sobol_pts) < cd(&random) / 10.0, "{} {}", cd(&sobol_pts), cd(&random));
295        assert!(cd(&halton_pts) < cd(&random) / 10.0);
296        assert!(cd(&lhs) < cd(&random));
297        // Scrambled Sobol keeps the net property: each 1-D projection of 256 points is stratified.
298        for k in 0..4 {
299            let mut cells: Vec<usize> = sobol_pts.iter().map(|p| (p[k] * 256.0) as usize).collect();
300            cells.sort_unstable();
301            assert!(cells.iter().enumerate().all(|(i, &c)| c == i));
302            let mut cells: Vec<usize> = lhs.iter().map(|p| (p[k] * 256.0) as usize).collect();
303            cells.sort_unstable();
304            assert!(cells.iter().enumerate().all(|(i, &c)| c == i));
305        }
306        assert!(sobol_pts.iter().chain(&halton_pts).flatten().all(|&x| (0.0..1.0).contains(&x)));
307        let boxed = scale(&lhs, &[-1.0; 4], &[3.0; 4], false).unwrap();
308        let back = scale(&boxed, &[-1.0; 4], &[3.0; 4], true).unwrap();
309        assert!(back.iter().flatten().zip(lhs.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-15));
310    }
311
312    #[test]
313    fn poisson_disk_spacing_and_coverage() {
314        let mut rng = crate::uniform_generator::UniformRNG::from_seed(5);
315        for hs in [Hypersphere::Volume, Hypersphere::Surface] {
316            let mut pd = PoissonDisk::new(2, 0.05, hs, 30, None).unwrap();
317            let pts = pd.fill_space(&mut rng);
318            for i in 0..pts.len() {
319                for j in 0..i {
320                    let d = ((pts[i][0] - pts[j][0]).powi(2) + (pts[i][1] - pts[j][1]).powi(2)).sqrt();
321                    assert!(d >= 0.05, "{d}");
322                }
323            }
324            // A maximal packing: every point of a fine grid is within 2r of some sample.
325            for a in 0..20 {
326                for b in 0..20 {
327                    let q = [(a as f64 + 0.5) / 20.0, (b as f64 + 0.5) / 20.0];
328                    assert!(pts.iter().any(|p| ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt() < 0.1));
329                }
330            }
331            assert!(pts.len() > 150, "{}", pts.len());
332        }
333    }
334}