1use crate::can_integrate::CanIntegrate1D;
6use lib_jsl_core::ErrorsJSL;
7use std::cmp::Ordering;
8use std::collections::BinaryHeap;
9
10#[allow(clippy::excessive_precision)] pub(crate) const GAUSS_LEGENDRE_WEIGHTS_7: [f64; 4] = [
15 0.417_959_183_673_469_387_755_102_040_816_327,
16 0.381_830_050_505_118_944_950_369_775_488_975,
17 0.279_705_391_489_276_667_901_467_771_423_780,
18 0.129_484_966_168_869_693_270_611_432_679_082,
19];
20
21#[allow(clippy::excessive_precision)] pub(crate) const KRONROD_NODES_15: [f64; 8] = [
25 0.0,
26 0.207_784_955_007_898_467_600_689_403_773_245,
27 0.405_845_151_377_397_166_906_606_412_076_961,
28 0.586_087_235_467_691_130_294_144_845_693_013,
29 0.741_531_185_599_394_439_863_864_773_280_788,
30 0.864_864_423_359_769_072_789_712_788_640_926,
31 0.949_107_912_342_758_524_526_189_684_047_851,
32 0.991_455_371_120_812_639_206_854_697_526_329,
33];
34
35#[allow(clippy::excessive_precision)] pub(crate) const KRONROD_WEIGHTS_15: [f64; 8] = [
38 0.209_482_141_084_727_828_012_999_174_891_714,
39 0.204_432_940_075_298_892_414_161_999_234_649,
40 0.190_350_578_064_785_409_913_256_402_421_014,
41 0.169_004_726_639_267_902_826_583_426_598_550,
42 0.140_653_259_715_525_918_745_189_590_510_238,
43 0.104_790_010_322_250_183_839_876_322_541_518,
44 0.063_092_092_629_978_553_290_700_663_189_204,
45 0.022_935_322_010_529_224_963_732_008_058_970,
46];
47#[derive(Debug, Clone, Copy)]
51struct Panel {
52 a: f64,
53 b: f64,
54 value: f64,
55 error: f64,
56}
57
58fn gauss_kronrod<F: Fn(f64) -> f64>(a: f64, b: f64, f: &F) -> Result<Panel, ErrorsJSL> {
61 let centre = 0.5 * (a + b);
62 let half = 0.5 * (b - a);
63 let f_centre = f(centre);
64 let mut kronrod = f_centre * KRONROD_WEIGHTS_15[0];
65 let mut gauss = f_centre * GAUSS_LEGENDRE_WEIGHTS_7[0];
66 let mut absolute = kronrod.abs();
67 let mut pairs = [(0.0, 0.0); 8];
68 for j in 1..8 {
69 let dx = half * KRONROD_NODES_15[j];
70 let (lo, hi) = (f(centre - dx), f(centre + dx));
71 pairs[j] = (lo, hi);
72 kronrod += KRONROD_WEIGHTS_15[j] * (lo + hi);
73 absolute += KRONROD_WEIGHTS_15[j] * (lo.abs() + hi.abs());
74 if j % 2 == 0 {
75 gauss += GAUSS_LEGENDRE_WEIGHTS_7[j / 2] * (lo + hi);
76 }
77 }
78 let mean = 0.5 * kronrod;
80 let mut deviation = KRONROD_WEIGHTS_15[0] * (f_centre - mean).abs();
81 for (j, &(lo, hi)) in pairs.iter().enumerate().skip(1) {
82 deviation += KRONROD_WEIGHTS_15[j] * ((lo - mean).abs() + (hi - mean).abs());
83 }
84 let (value, absolute, deviation) = (kronrod * half, absolute * half.abs(), deviation * half.abs());
85 let mut error = ((kronrod - gauss) * half).abs();
86 if deviation != 0.0 && error != 0.0 {
87 error = deviation * (200.0 * error / deviation).powf(1.5).min(1.0);
88 }
89 if absolute > f64::MIN_POSITIVE / (50.0 * f64::EPSILON) {
90 error = error.max(50.0 * f64::EPSILON * absolute);
91 }
92 if !value.is_finite() || !error.is_finite() {
93 return Err(ErrorsJSL::RuntimeError("Gauss-Kronrod: the integrand is not finite at a sample point"));
94 }
95 Ok(Panel { a, b, value, error })
96}
97struct ByError(Panel);
101
102impl PartialEq for ByError {
103 fn eq(&self, other: &Self) -> bool {
104 self.0.error == other.0.error
105 }
106}
107impl Eq for ByError {}
108impl PartialOrd for ByError {
109 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
110 Some(self.cmp(other))
111 }
112}
113impl Ord for ByError {
114 fn cmp(&self, other: &Self) -> Ordering {
115 self.0.error.total_cmp(&other.0.error)
116 }
117}
118
119pub struct AdaptiveGL7K15IntegrationEngine {
134 tolerance: f64,
135 lower_bound: f64,
136 upper_bound: f64,
137 pub max_subintervals: usize,
139}
140
141impl AdaptiveGL7K15IntegrationEngine {
142 pub fn new(tolerance: f64, lower_bound: f64, upper_bound: f64) -> Self {
144 AdaptiveGL7K15IntegrationEngine { tolerance, lower_bound, upper_bound, max_subintervals: 1000 }
145 }
146
147 pub fn set_tolerance(&mut self, x: f64) {
149 self.tolerance = x;
150 }
151
152 pub fn integrate_with_error<F: Fn(f64) -> f64>(&self, f: F) -> Result<(f64, f64, usize), ErrorsJSL> {
155 let first = gauss_kronrod(self.lower_bound, self.upper_bound, &f)?;
157 let (mut value, mut error) = (first.value, first.error);
158 let mut queue = BinaryHeap::from([ByError(first)]);
159 let mut evaluations = 15;
160 while error > self.tolerance.max(50.0 * f64::EPSILON * value.abs()) && queue.len() < self.max_subintervals {
161 let worst = queue.pop().expect("at least one panel").0;
162 let middle = 0.5 * (worst.a + worst.b);
163 if middle <= worst.a.min(worst.b) || middle >= worst.a.max(worst.b) {
164 queue.push(ByError(worst));
166 break;
167 }
168 let left = gauss_kronrod(worst.a, middle, &f)?;
169 let right = gauss_kronrod(middle, worst.b, &f)?;
170 evaluations += 30;
171 value += left.value + right.value - worst.value;
172 error += left.error + right.error - worst.error;
173 queue.push(ByError(left));
174 queue.push(ByError(right));
175 }
176 let value = queue.iter().map(|p| p.0.value).sum();
179 let error = queue.iter().map(|p| p.0.error).sum();
180 Ok((value, error, evaluations))
181 }
182}
183
184impl CanIntegrate1D for AdaptiveGL7K15IntegrationEngine {
185 fn integrate<F>(&self, f: F) -> Result<f64, ErrorsJSL>
186 where
187 F: Fn(f64) -> f64,
188 {
189 let (value, error, _) = self.integrate_with_error(f)?;
190 if error > self.tolerance.max(50.0 * f64::EPSILON * value.abs()) {
191 return Err(ErrorsJSL::RuntimeError("Gauss-Kronrod: the tolerance was not met within the subinterval limit"));
192 }
193 Ok(value)
194 }
195
196 fn set_lower_bound(&mut self, x: f64) {
197 self.lower_bound = x;
198 }
199
200 fn set_upper_bound(&mut self, x: f64) {
201 self.upper_bound = x;
202 }
203}
204
205#[cfg(test)]
206mod test {
207 use super::*;
208 use std::f64::consts::PI;
209
210 #[test]
211 fn test_gl7k15_adaptive_integration() {
212 let dut = AdaptiveGL7K15IntegrationEngine::new(1e-12, PI / 2.0, 0.0);
213 assert!((dut.integrate(f64::sin).unwrap() + 1.0).abs() < 1e-12);
214 let dut = AdaptiveGL7K15IntegrationEngine::new(1e-12, -PI / 2.0, PI / 2.0);
215 assert!(dut.integrate(f64::sin).unwrap().abs() < 1e-12);
216 }
217
218 #[test]
219 fn the_pair_has_the_expected_degrees_of_exactness() {
220 let exact = |k: i32| if k % 2 == 1 { 0.0 } else { 2.0 / (k + 1) as f64 };
222 for k in 0..=25 {
223 let p = gauss_kronrod(-1.0, 1.0, &|x: f64| x.powi(k)).unwrap();
224 if k <= 23 {
225 assert!((p.value - exact(k)).abs() < 2e-16, "Kronrod, degree {k}: {}", p.value - exact(k));
226 } else if k == 24 {
227 assert!((p.value - exact(k)).abs() > 1e-12, "Kronrod is not exact at degree 24");
228 }
229 }
230 let gauss = |k: i32| {
231 let (kn, g) = (KRONROD_NODES_15, GAUSS_LEGENDRE_WEIGHTS_7);
232 let x = [-kn[6], -kn[4], -kn[2], 0.0, kn[2], kn[4], kn[6]];
233 let w = [g[3], g[2], g[1], g[0], g[1], g[2], g[3]];
234 x.iter().zip(w).map(|(x, w)| w * x.powi(k)).sum::<f64>()
235 };
236 for k in 0..=13 {
237 assert!((gauss(k) - exact(k)).abs() < 1e-15, "Gauss, degree {k}: {}", gauss(k) - exact(k));
238 }
239 assert!((gauss(14) - exact(14)).abs() > 1e-6);
240 }
241
242 #[test]
243 fn difficult_integrands_and_failures() {
244 let dut = AdaptiveGL7K15IntegrationEngine::new(1e-10, 0.0, 1.0);
246 let (v, err, _) = dut.integrate_with_error(f64::ln).unwrap();
247 assert!((v + 1.0).abs() < 1e-10 && err < 1e-10, "{v} {err}");
248 let tiny = AdaptiveGL7K15IntegrationEngine::new(1e-30, 0.0, 1.0);
250 assert!((tiny.integrate(f64::exp).unwrap() - (std::f64::consts::E - 1.0)).abs() < 1e-15);
251 assert!(AdaptiveGL7K15IntegrationEngine::new(1e-8, -1.0, 1.0).integrate(|x| 1.0 / x).is_err());
253 let mut few = AdaptiveGL7K15IntegrationEngine::new(1e-14, 0.0, 1.0);
254 few.max_subintervals = 3;
255 assert!(few.integrate(|x: f64| x.powf(-0.9)).is_err());
256 }
257}