Skip to main content

lib_jsl_statistics/
qmc_normal.rs

1//! Quasi-Monte Carlo samples from a multivariate normal distribution (SciPy's
2//! `stats.qmc.MultivariateNormalQMC`).
3//!
4//! See the book entry [Multivariate distribution functions and quasi-Monte Carlo sampling](https://jwkunz.github.io/lib_jsl/book/statistics/mvn-cdf.html#quasi-monte-carlo-normal-samples).
5
6use lib_jsl_core::ErrorsJSL;
7use lib_jsl_random::quasi_random::SobolSequence;
8use lib_jsl_special_functions::normal_quantile;
9
10/// A generator of low-discrepancy multivariate normal samples: Sobol points mapped to standard
11/// normals, then correlated by a square root of the covariance.
12#[derive(Clone, Debug)]
13pub struct MultivariateNormalQmc {
14    mean: Vec<f64>,
15    /// `d × d`: `x = μ + R z`.
16    root: Vec<Vec<f64>>,
17    inv_transform: bool,
18    engine: SobolSequence,
19}
20
21// ANCHOR: mvn_qmc
22impl MultivariateNormalQmc {
23    /// Samples from `N(mean, cov)` driven by `engine`, a Sobol sequence of dimension `d` (or
24    /// `2⌈d/2⌉` with `inv_transform = false`), plain or scrambled. With `inv_transform`, each
25    /// coordinate is `Φ⁻¹(½ + (1 − 10⁻¹⁰)(u − ½))` (SciPy's default); otherwise pairs of
26    /// coordinates go through the Box-Muller transform. The covariance's square root is its
27    /// Cholesky factor, or `V √Λ` from its eigendecomposition when it is only semidefinite.
28    pub fn new(mean: Vec<f64>, cov: &[Vec<f64>], inv_transform: bool, engine: SobolSequence) -> Result<Self, ErrorsJSL> {
29        let d = mean.len();
30        if d == 0 || cov.len() != d || cov.iter().any(|r| r.len() != d) {
31            return Err(ErrorsJSL::InvalidInputRange("MultivariateNormalQmc: the mean and covariance must have one dimension"));
32        }
33        let need = if inv_transform { d } else { 2 * d.div_ceil(2) };
34        if engine.dimension() != need {
35            return Err(ErrorsJSL::InvalidInputRange("MultivariateNormalQmc: the engine's dimension must be d (or 2⌈d/2⌉ without the inverse transform)"));
36        }
37        let root = match cholesky(cov) {
38            Some(l) => l,
39            None => {
40                let (lam, v) = crate::multivariate::symmetric_eigen_pub(cov);
41                if lam.iter().any(|&l| l < -1e-8) {
42                    return Err(ErrorsJSL::InvalidInputRange("MultivariateNormalQmc: the covariance is not positive semidefinite"));
43                }
44                (0..d).map(|i| (0..d).map(|j| v[i][j] * lam[j].max(0.0).sqrt()).collect()).collect()
45            }
46        };
47        Ok(MultivariateNormalQmc { mean, root, inv_transform, engine })
48    }
49
50    /// The next `n` samples.
51    pub fn random(&mut self, n: usize) -> Vec<Vec<f64>> {
52        let d = self.mean.len();
53        (0..n)
54            .map(|_| {
55                let u = self.engine.next_point();
56                let z: Vec<f64> = if self.inv_transform {
57                    u.iter().map(|&v| normal_quantile(0.5 + (1.0 - 1e-10) * (v - 0.5), 0.0, 1.0)).collect()
58                } else {
59                    let mut z = Vec::with_capacity(u.len());
60                    for p in u.chunks(2) {
61                        let r = (-2.0 * p[0].ln()).sqrt();
62                        let t = 2.0 * std::f64::consts::PI * p[1];
63                        z.push(r * t.cos());
64                        z.push(r * t.sin());
65                    }
66                    z.truncate(d);
67                    z
68                };
69                (0..d).map(|i| self.mean[i] + (0..d).map(|k| self.root[i][k] * z[k]).sum::<f64>()).collect()
70            })
71            .collect()
72    }
73}
74// ANCHOR_END: mvn_qmc
75
76fn cholesky(a: &[Vec<f64>]) -> Option<Vec<Vec<f64>>> {
77    let n = a.len();
78    let mut l = vec![vec![0.0; n]; n];
79    for j in 0..n {
80        let d = a[j][j] - (0..j).map(|k| l[j][k] * l[j][k]).sum::<f64>();
81        if d <= 0.0 || !d.is_finite() {
82            return None;
83        }
84        l[j][j] = d.sqrt();
85        for i in j + 1..n {
86            l[i][j] = (a[i][j] - (0..j).map(|k| l[i][k] * l[j][k]).sum::<f64>()) / l[j][j];
87        }
88    }
89    Some(l)
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    #[test]
97    fn moments_converge_quickly() {
98        let cov = vec![vec![2.0, 0.6], vec![0.6, 1.0]];
99        let mut g = MultivariateNormalQmc::new(vec![1.0, -1.0], &cov, true, SobolSequence::new(2).unwrap()).unwrap();
100        let s = g.random(4096);
101        let n = s.len() as f64;
102        let m0 = s.iter().map(|p| p[0]).sum::<f64>() / n;
103        let c01 = s.iter().map(|p| (p[0] - 1.0) * (p[1] + 1.0)).sum::<f64>() / n;
104        // (The first, unscrambled Sobol point is 0, which maps to −6.5: a small bias, as in SciPy.)
105        assert!((m0 - 1.0).abs() < 5e-3 && (c01 - 0.6).abs() < 3e-2, "{m0} {c01}");
106        // Singular covariance: the samples lie on the line x₁ = x₀.
107        let mut g = MultivariateNormalQmc::new(vec![0.0, 0.0], &[vec![1.0, 1.0], vec![1.0, 1.0]], false, SobolSequence::new(2).unwrap()).unwrap();
108        g.random(1);
109        assert!(g.random(10).iter().all(|p| (p[0] - p[1]).abs() < 1e-12));
110    }
111}