Skip to main content

lib_jsl_integration/
adaptive_gl7k15_integration_engine.rs

1//! Globally adaptive Gauss-Kronrod quadrature with the 7-point Gauss and 15-point Kronrod pair.
2//!
3//! See the book entry [Adaptive Gauss-Kronrod quadrature](https://jwkunz.github.io/lib_jsl/book/integration/gauss-kronrod.html).
4
5use crate::can_integrate::CanIntegrate1D;
6use lib_jsl_core::ErrorsJSL;
7use std::cmp::Ordering;
8use std::collections::BinaryHeap;
9
10// ANCHOR: constants
11/// Weights of the 7-point Gauss-Legendre rule at `0`, `±KRONROD_NODES_15[2]`, `[4]` and `[6]`
12/// (QUADPACK `qk15`, to full double precision).
13#[allow(clippy::excessive_precision)] // QUADPACK's published digits, kept verbatim
14pub(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/// The non-negative nodes of the 15-point Kronrod rule, from the centre outwards. The entries
22/// with even index are the nodes of the 7-point Gauss rule; the others are the Kronrod extension.
23#[allow(clippy::excessive_precision)] // QUADPACK's published digits, kept verbatim
24pub(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/// Weights of the 15-point Kronrod rule, matching [`KRONROD_NODES_15`].
36#[allow(clippy::excessive_precision)] // QUADPACK's published digits, kept verbatim
37pub(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// ANCHOR_END: constants
48
49/// The Kronrod estimate of `∫ₐᵇ f`, an estimate of its error, and whether every sample was finite.
50#[derive(Debug, Clone, Copy)]
51struct Panel {
52    a: f64,
53    b: f64,
54    value: f64,
55    error: f64,
56}
57
58// ANCHOR: gauss_kronrod_panel
59/// Applies the G7-K15 pair on `[a, b]` with QUADPACK's error estimate.
60fn 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    // ∫|f − mean| over the panel, which calibrates the raw difference |K − G|.
79    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}
97// ANCHOR_END: gauss_kronrod_panel
98
99/// Orders panels by error estimate, for the priority queue.
100struct 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
119/// Globally adaptive Gauss-Kronrod quadrature (the strategy of QUADPACK's `qag` with its 15-point
120/// rule): the interval with the largest error estimate is bisected until the estimates sum to
121/// less than the tolerance.
122///
123/// Each panel is integrated with the 15-point Kronrod rule, which contains the 7-point Gauss rule;
124/// their difference, calibrated as in QUADPACK, estimates the error of the (far more accurate)
125/// Kronrod value. The rule is exact for polynomials of degree 23 on each panel, so smooth
126/// integrands need very few panels, while kinks, peaks and integrable endpoint singularities
127/// draw the bisections towards themselves.
128///
129/// The tolerance is absolute, raised if necessary to the rounding-error level
130/// `50 ε ∫|f|`; [`integrate`](CanIntegrate1D::integrate) fails if it cannot be met within
131/// [`max_subintervals`](Self::max_subintervals) panels, and
132/// [`integrate_with_error`](Self::integrate_with_error) returns the estimate either way.
133pub struct AdaptiveGL7K15IntegrationEngine {
134    tolerance: f64,
135    lower_bound: f64,
136    upper_bound: f64,
137    /// The largest number of panels (default 1000).
138    pub max_subintervals: usize,
139}
140
141impl AdaptiveGL7K15IntegrationEngine {
142    /// An engine on `[lower_bound, upper_bound]` aiming for an absolute error below `tolerance`.
143    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    /// Changes the error tolerance.
148    pub fn set_tolerance(&mut self, x: f64) {
149        self.tolerance = x;
150    }
151
152    /// The integral, its error estimate and the number of evaluations of `f`. The estimate may
153    /// exceed the tolerance if `max_subintervals` was reached; a non-finite sample is an error.
154    pub fn integrate_with_error<F: Fn(f64) -> f64>(&self, f: F) -> Result<(f64, f64, usize), ErrorsJSL> {
155        // ANCHOR: global_adaptivity
156        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                // The panel cannot be split further in floating point.
165                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        // ANCHOR_END: global_adaptivity
177        // Re-sum to remove the rounding accumulated by the running updates.
178        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        // On [−1, 1]: Kronrod is exact to degree 23 (3·7 + 2 for odd 7), Gauss to degree 13 (2·7 − 1).
221        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        // An integrable endpoint singularity: ∫₀¹ ln x dx = −1.
245        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        // A tolerance below rounding level is raised rather than looping forever.
249        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        // A non-finite sample is an error, as is an unreachable tolerance.
252        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}