Skip to main content

lib_jsl_integration/
monte_carlo_integration.rs

1//! Plain 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::uniform_generator::{UniformGenerator, UniformRNG};
7
8/// The outcome of [`monte_carlo`].
9#[derive(Debug, Clone, Copy)]
10#[non_exhaustive]
11pub struct MonteCarloResult {
12    /// The estimated integral.
13    pub value: f64,
14    /// The estimated standard deviation of `value`, `V σ̂ / √N` (`V` the volume of the box).
15    pub standard_error: f64,
16    /// The number of integrand evaluations.
17    pub nfev: usize,
18}
19
20fn check_bounds(bounds: &[(f64, f64)]) -> Result<f64, ErrorsJSL> {
21    if bounds.is_empty() {
22        return Err(ErrorsJSL::InvalidInputRange("The box needs at least one dimension."));
23    }
24    if bounds.iter().any(|(a, b)| !a.is_finite() || !b.is_finite()) {
25        return Err(ErrorsJSL::InvalidInputRange("The bounds must be finite."));
26    }
27    Ok(bounds.iter().map(|(a, b)| b - a).product())
28}
29
30/// Running mean and variance of the samples (Welford's algorithm), numerically stable.
31#[derive(Default)]
32struct Welford {
33    n: usize,
34    mean: f64,
35    m2: f64,
36}
37
38impl Welford {
39    // ANCHOR: welford
40    fn push(&mut self, y: f64) {
41        self.n += 1;
42        let delta = y - self.mean;
43        self.mean += delta / self.n as f64;
44        self.m2 += delta * (y - self.mean);
45    }
46
47    /// The standard error of the mean, `σ̂ / √n`.
48    fn standard_error(&self) -> f64 {
49        if self.n < 2 { f64::INFINITY } else { (self.m2 / (self.n - 1) as f64 / self.n as f64).sqrt() }
50    }
51    // ANCHOR_END: welford
52}
53
54/// Estimates `∫ f` over the box `bounds` (one `(lower, upper)` pair per dimension) from `samples`
55/// uniformly distributed points: the volume times the sample mean of `f`, with its standard error.
56/// The error falls like `1/√N` whatever the dimension. `seed` makes the result reproducible.
57pub fn monte_carlo<F: Fn(&[f64]) -> f64>(f: F, bounds: &[(f64, f64)], samples: usize, seed: u64) -> Result<MonteCarloResult, ErrorsJSL> {
58    let volume = check_bounds(bounds)?;
59    if samples == 0 {
60        return Err(ErrorsJSL::InvalidInputRange("At least one sample is needed."));
61    }
62    let mut rng = UniformRNG::from_seed(seed);
63    let mut x = vec![0.0; bounds.len()];
64    let mut stats = Welford::default();
65    for _ in 0..samples {
66        for (xi, (a, b)) in x.iter_mut().zip(bounds) {
67            *xi = a + rng.next_f64() * (b - a);
68        }
69        stats.push(f(&x));
70    }
71    Ok(MonteCarloResult { value: volume * stats.mean, standard_error: volume * stats.standard_error(), nfev: samples })
72}
73
74/// Monte Carlo integration until a target accuracy: samples are drawn in batches of
75/// `convergence_tuple.1` until the standard error of the estimate falls below
76/// `convergence_tuple.0` (an absolute error target), or until `max_samples` have been used, in
77/// which case the current estimate is returned. Without `max_samples`, failing to converge within
78/// 10⁹ samples is an error (the integrand may have infinite variance).
79///
80/// The standard error falls like `σ/√N`, so halving it costs four times the samples.
81pub fn monte_carlo_integration<F>(f: F, bounds: &[(f64, f64)], convergence_tuple: (f64, usize), max_samples: Option<usize>) -> Result<f64, ErrorsJSL>
82where
83    F: Fn(&[f64]) -> f64,
84{
85    let volume = check_bounds(bounds)?;
86    let (target, batch) = (convergence_tuple.0, convergence_tuple.1.max(2));
87    let limit = max_samples.unwrap_or(1_000_000_000);
88    let mut rng = UniformRNG::from_seed(0);
89    let mut x = vec![0.0; bounds.len()];
90    let mut stats = Welford::default();
91    loop {
92        for _ in 0..batch {
93            for (xi, (a, b)) in x.iter_mut().zip(bounds) {
94                *xi = a + rng.next_f64() * (b - a);
95            }
96            stats.push(f(&x));
97        }
98        if volume * stats.standard_error() < target {
99            return Ok(volume * stats.mean);
100        }
101        if stats.n >= limit {
102            return match max_samples {
103                Some(_) => Ok(volume * stats.mean),
104                None => Err(ErrorsJSL::RuntimeError("Monte Carlo: the target standard error was not reached in 10⁹ samples")),
105            };
106        }
107    }
108}
109
110#[cfg(test)]
111mod test {
112    use super::*;
113    use std::f64::consts::PI;
114
115    fn test_function(x: &[f64]) -> f64 {
116        x[0].sin() * x[1].sin() * x[2].sin()
117    }
118
119    #[test]
120    fn test_monte_carlos_integration() {
121        // ∫ over [0, π]³ of sin x sin y sin z = 8. Target a standard error of 0.02.
122        let result = monte_carlo_integration(test_function, &[(0.0, PI); 3], (0.02, 1000), None).unwrap();
123        assert!((8.0 - result).abs() < 0.1, "{result}");
124    }
125
126    #[test]
127    fn the_standard_error_is_honest() {
128        // Over many seeds, about 68% of estimates lie within one standard error of the truth.
129        let inside = (0..200u64)
130            .filter(|&seed| {
131                let r = monte_carlo(test_function, &[(0.0, PI); 3], 2000, seed).unwrap();
132                (r.value - 8.0).abs() < r.standard_error
133            })
134            .count();
135        assert!((110..=160).contains(&inside), "{inside} of 200");
136        // Quadrupling the samples halves the standard error.
137        let a = monte_carlo(test_function, &[(0.0, PI); 3], 10_000, 1).unwrap();
138        let b = monte_carlo(test_function, &[(0.0, PI); 3], 40_000, 1).unwrap();
139        assert!((a.standard_error / b.standard_error - 2.0).abs() < 0.1);
140    }
141
142    #[test]
143    fn validation_and_budgets() {
144        assert!(monte_carlo(test_function, &[], 10, 0).is_err());
145        assert!(monte_carlo(test_function, &[(0.0, f64::INFINITY)], 10, 0).is_err());
146        assert!(monte_carlo(test_function, &[(0.0, 1.0)], 0, 0).is_err());
147        // An unreachable target with a sample limit returns the estimate at the limit.
148        let v = monte_carlo_integration(|x| x[0], &[(0.0, 1.0)], (1e-12, 100), Some(1000)).unwrap();
149        assert!((v - 0.5).abs() < 0.05);
150    }
151}