lib_jsl_integration/
monte_carlo_integration.rs1use lib_jsl_core::ErrorsJSL;
6use lib_jsl_random::uniform_generator::{UniformGenerator, UniformRNG};
7
8#[derive(Debug, Clone, Copy)]
10#[non_exhaustive]
11pub struct MonteCarloResult {
12 pub value: f64,
14 pub standard_error: f64,
16 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#[derive(Default)]
32struct Welford {
33 n: usize,
34 mean: f64,
35 m2: f64,
36}
37
38impl Welford {
39 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 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 }
53
54pub 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
74pub 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 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 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 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 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}