Skip to main content

lib_jsl_integration/
quasi_monte_carlo.rs

1//! Randomized quasi-Monte Carlo integration over boxes.
2//!
3//! See the book entry [Monte Carlo and quasi-Monte Carlo integration](https://jwkunz.github.io/lib_jsl/book/integration/monte-carlo.html).
4
5use lib_jsl_core::ErrorsJSL;
6use lib_jsl_random::quasi_random::{HaltonSequence, SobolSequence, random_shift};
7use lib_jsl_random::uniform_generator::UniformRNG;
8
9/// The low-discrepancy sequence to sample with.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum QuasiRandomSequence {
12    /// Sobol (up to 21201 dimensions); use a power of two for the number of points.
13    Sobol,
14    /// Halton (up to 100 dimensions).
15    Halton,
16}
17
18/// The outcome of [`quasi_monte_carlo_integration`].
19#[derive(Debug, Clone)]
20#[non_exhaustive]
21pub struct QuasiMonteCarloResult {
22    /// The mean of the replicate estimates.
23    pub value: f64,
24    /// Standard error from the spread of the replicates (NaN with a single replicate).
25    pub standard_error: f64,
26    /// The number of integrand evaluations (`points × replicates`).
27    pub nfev: usize,
28}
29
30/// Integrates `f` over the box `bounds` (one `(lower, upper)` pair per dimension) by randomized
31/// quasi-Monte Carlo: `replicates` independent Cranley-Patterson shifts of the first `points`
32/// points of a low-discrepancy sequence, each giving an unbiased estimate. The result is their
33/// mean, and their spread gives a standard error. For smooth integrands the error falls almost
34/// like `1/N`, against `1/√N` for plain Monte Carlo.
35pub fn quasi_monte_carlo_integration<F: Fn(&[f64]) -> f64>(
36    f: F,
37    bounds: &[(f64, f64)],
38    points: usize,
39    replicates: usize,
40    sequence: QuasiRandomSequence,
41    seed: u64,
42) -> Result<QuasiMonteCarloResult, ErrorsJSL> {
43    let d = bounds.len();
44    if d == 0 || points == 0 || replicates == 0 {
45        return Err(ErrorsJSL::InvalidInputRange("Dimensions, points and replicates must be positive."));
46    }
47    if bounds.iter().any(|(a, b)| !a.is_finite() || !b.is_finite()) {
48        return Err(ErrorsJSL::InvalidInputRange("The bounds must be finite."));
49    }
50    let base: Vec<Vec<f64>> = match sequence {
51        QuasiRandomSequence::Sobol => {
52            let mut s = SobolSequence::new(d)?;
53            (0..points).map(|_| s.next_point()).collect()
54        }
55        QuasiRandomSequence::Halton => {
56            let mut h = HaltonSequence::new(d)?;
57            (0..points).map(|_| h.next_point()).collect()
58        }
59    };
60    let volume: f64 = bounds.iter().map(|(a, b)| b - a).product();
61    let mut rng = UniformRNG::from_seed(seed);
62    let mut x = vec![0.0; d];
63    let estimates: Vec<f64> = (0..replicates)
64        .map(|_| {
65            let mut shifted = base.clone();
66            random_shift(&mut shifted, &mut rng);
67            let sum: f64 = shifted
68                .iter()
69                .map(|u| {
70                    for k in 0..d {
71                        x[k] = bounds[k].0 + u[k] * (bounds[k].1 - bounds[k].0);
72                    }
73                    f(&x)
74                })
75                .sum();
76            volume * sum / points as f64
77        })
78        .collect();
79    let r = replicates as f64;
80    let value = estimates.iter().sum::<f64>() / r;
81    let standard_error = if replicates > 1 {
82        (estimates.iter().map(|e| (e - value).powi(2)).sum::<f64>() / (r - 1.0) / r).sqrt()
83    } else {
84        f64::NAN
85    };
86    Ok(QuasiMonteCarloResult { value, standard_error, nfev: points * replicates })
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use lib_jsl_random::uniform_generator::UniformGenerator;
93    use std::f64::consts::PI;
94
95    /// Π (π/2) sin(π x_i) over the unit cube integrates to one.
96    fn product(x: &[f64]) -> f64 {
97        x.iter().map(|&v| 0.5 * PI * (PI * v).sin()).product()
98    }
99
100    #[test]
101    fn beats_plain_monte_carlo_and_reports_a_consistent_error() {
102        let bounds = vec![(0.0, 1.0); 5];
103        for sequence in [QuasiRandomSequence::Sobol, QuasiRandomSequence::Halton] {
104            let r = quasi_monte_carlo_integration(product, &bounds, 4096, 16, sequence, 7).unwrap();
105            let error = (r.value - 1.0).abs();
106            assert!(error < 2e-3 && error < 5.0 * r.standard_error + 1e-12, "{sequence:?}: {r:?}");
107            // Plain Monte Carlo with the same 65536 evaluations has a standard error near
108            // σ/√N ≈ 0.0045 for this integrand.
109            let mut rng = UniformRNG::from_seed(3);
110            let samples: Vec<f64> = (0..r.nfev).map(|_| product(&(0..5).map(|_| rng.next_f64()).collect::<Vec<_>>())).collect();
111            let mean = samples.iter().sum::<f64>() / samples.len() as f64;
112            let sd = (samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64).sqrt();
113            let mc_error = sd / (samples.len() as f64).sqrt();
114            assert!(r.standard_error < mc_error / 5.0, "{sequence:?}: qmc {} mc {mc_error}", r.standard_error);
115        }
116    }
117
118    #[test]
119    fn scales_to_the_box_and_validates() {
120        let r = quasi_monte_carlo_integration(|x| x[0] * x[1], &[(0.0, 2.0), (-1.0, 3.0)], 1024, 8, QuasiRandomSequence::Sobol, 1).unwrap();
121        assert!((r.value - 8.0).abs() < (4.0 * r.standard_error).min(0.05), "{r:?}");
122        let single = quasi_monte_carlo_integration(|x| x[0], &[(0.0, 1.0)], 256, 1, QuasiRandomSequence::Halton, 1).unwrap();
123        assert!(single.standard_error.is_nan() && (single.value - 0.5).abs() < 1e-2);
124        assert!(quasi_monte_carlo_integration(|x| x[0], &[(0.0, 1.0); 21202], 16, 2, QuasiRandomSequence::Sobol, 1).is_err());
125        assert!(quasi_monte_carlo_integration(|x| x[0], &[], 16, 2, QuasiRandomSequence::Sobol, 1).is_err());
126    }
127}