Skip to main content

lib_jsl_integration/
quad_vec.rs

1//! Adaptive integration of vector-valued functions over finite or infinite intervals, a port of
2//! SciPy's `quad_vec`: every component shares one set of subintervals, chosen by a global
3//! Gauss-Kronrod error estimate in the 2-norm (or the max norm).
4//!
5//! See the book entry [Vector integrands and weighted quadrature](https://jwkunz.github.io/lib_jsl/book/integration/vector-weighted.html).
6
7#![allow(clippy::excessive_precision)] // Gauss-Kronrod nodes and weights as printed in SciPy.
8
9use lib_jsl_core::ErrorsJSL;
10use std::cmp::Ordering;
11use std::collections::{BinaryHeap, HashMap};
12
13/// How the error of a vector of integrals is measured.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum VecNorm {
17    /// The largest absolute component (SciPy's `'max'`).
18    Max,
19    /// The Euclidean norm (SciPy's default, `'2'`).
20    Euclidean,
21}
22
23/// The local rule applied to each subinterval.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum VecRule {
27    /// 21-point Gauss-Kronrod (SciPy's default on finite intervals).
28    GaussKronrod21,
29    /// 15-point Gauss-Kronrod (SciPy's default after mapping an infinite interval).
30    GaussKronrod15,
31    /// The trapezoid rule with a Richardson error estimate, for non-smooth integrands.
32    Trapezoid,
33}
34
35/// Options for [`quad_vec`] (SciPy's defaults).
36#[derive(Clone, Debug)]
37pub struct QuadVecOptions {
38    pub epsabs: f64,
39    pub epsrel: f64,
40    pub norm: VecNorm,
41    /// The rule; `None` chooses SciPy's default (21-point Gauss-Kronrod, or 15-point after mapping
42    /// an infinite interval).
43    pub rule: Option<VecRule>,
44    /// The largest number of subintervals.
45    pub limit: usize,
46    /// Interior points (discontinuities, kinks) where the interval is split from the start.
47    pub points: Vec<f64>,
48}
49
50impl Default for QuadVecOptions {
51    fn default() -> Self {
52        QuadVecOptions { epsabs: 1e-200, epsrel: 1e-8, norm: VecNorm::Euclidean, rule: None, limit: 10_000, points: Vec::new() }
53    }
54}
55
56/// The result of [`quad_vec`].
57#[derive(Clone, Debug)]
58#[non_exhaustive]
59pub struct QuadVecResult {
60    pub value: Vec<f64>,
61    /// The error estimate (in the chosen norm), including the rounding-error estimate.
62    pub error: f64,
63    pub nfev: usize,
64    pub converged: bool,
65    /// 0 converged, 1 subinterval limit reached, 2 limited by rounding error, 3 non-finite values.
66    pub status: i32,
67    /// The number of subintervals in the final partition.
68    pub intervals: usize,
69}
70
71const GK21_X: [f64; 21] = [
72    0.995657163025808080735527280689003, 0.973906528517171720077964012084452, 0.930157491355708226001207180059508,
73    0.865063366688984510732096688423493, 0.780817726586416897063717578345042, 0.679409568299024406234327365114874,
74    0.562757134668604683339000099272694, 0.433395394129247190799265943165784, 0.294392862701460198131126603103866,
75    0.148874338981631210884826001129720, 0.0, -0.148874338981631210884826001129720, -0.294392862701460198131126603103866,
76    -0.433395394129247190799265943165784, -0.562757134668604683339000099272694, -0.679409568299024406234327365114874,
77    -0.780817726586416897063717578345042, -0.865063366688984510732096688423493, -0.930157491355708226001207180059508,
78    -0.973906528517171720077964012084452, -0.995657163025808080735527280689003,
79];
80const GK21_W: [f64; 10] = [
81    0.066671344308688137593568809893332, 0.149451349150580593145776339657697, 0.219086362515982043995534934228163,
82    0.269266719309996355091226921569469, 0.295524224714752870173892994651338, 0.295524224714752870173892994651338,
83    0.269266719309996355091226921569469, 0.219086362515982043995534934228163, 0.149451349150580593145776339657697,
84    0.066671344308688137593568809893332,
85];
86const GK21_V: [f64; 21] = [
87    0.011694638867371874278064396062192, 0.032558162307964727478818972459390, 0.054755896574351996031381300244580,
88    0.075039674810919952767043140916190, 0.093125454583697605535065465083366, 0.109387158802297641899210590325805,
89    0.123491976262065851077958109831074, 0.134709217311473325928054001771707, 0.142775938577060080797094273138717,
90    0.147739104901338491374841515972068, 0.149445554002916905664936468389821, 0.147739104901338491374841515972068,
91    0.142775938577060080797094273138717, 0.134709217311473325928054001771707, 0.123491976262065851077958109831074,
92    0.109387158802297641899210590325805, 0.093125454583697605535065465083366, 0.075039674810919952767043140916190,
93    0.054755896574351996031381300244580, 0.032558162307964727478818972459390, 0.011694638867371874278064396062192,
94];
95const GK15_X: [f64; 15] = [
96    0.991455371120812639206854697526329, 0.949107912342758524526189684047851, 0.864864423359769072789712788640926,
97    0.741531185599394439863864773280788, 0.586087235467691130294144838258730, 0.405845151377397166906606412076961,
98    0.207784955007898467600689403773245, 0.0, -0.207784955007898467600689403773245, -0.405845151377397166906606412076961,
99    -0.586087235467691130294144838258730, -0.741531185599394439863864773280788, -0.864864423359769072789712788640926,
100    -0.949107912342758524526189684047851, -0.991455371120812639206854697526329,
101];
102const GK15_W: [f64; 7] = [
103    0.129484966168869693270611432679082, 0.279705391489276667901467771423780, 0.381830050505118944950369775488975,
104    0.417959183673469387755102040816327, 0.381830050505118944950369775488975, 0.279705391489276667901467771423780,
105    0.129484966168869693270611432679082,
106];
107const GK15_V: [f64; 15] = [
108    0.022935322010529224963732008058970, 0.063092092629978553290700663189204, 0.104790010322250183839876322541518,
109    0.140653259715525918745189590510238, 0.169004726639267902826583426598550, 0.190350578064785409913256402421014,
110    0.204432940075298892414161999234649, 0.209482141084727828012999174891714, 0.204432940075298892414161999234649,
111    0.190350578064785409913256402421014, 0.169004726639267902826583426598550, 0.140653259715525918745189590510238,
112    0.104790010322250183839876322541518, 0.063092092629978553290700663189204, 0.022935322010529224963732008058970,
113];
114
115fn norm_of(norm: VecNorm, v: &[f64]) -> f64 {
116    match norm {
117        VecNorm::Max => v.iter().fold(0.0f64, |m, x| m.max(x.abs())),
118        VecNorm::Euclidean => v.iter().map(|x| x * x).sum::<f64>().sqrt(),
119    }
120}
121
122/// One interval's estimate: the integral, its error, and its rounding-error estimate.
123type Estimate = (Vec<f64>, f64, f64);
124
125// ANCHOR: gk
126/// Gauss-Kronrod on `[a, b]` (SciPy's `_quadrature_gk`): the Kronrod sum and the embedded Gauss
127/// sum; the error `‖h (K − G)‖` is rescaled as in QUADPACK, `D min(1, (200 E / D)^{3/2})` with
128/// `D = ‖h Σ vᵢ |fᵢ − K/2|‖`, and is not allowed below the rounding estimate `‖50 ε h Σ vᵢ|fᵢ|‖`.
129fn gauss_kronrod(f: &mut dyn FnMut(f64) -> Vec<f64>, a: f64, b: f64, norm: VecNorm, x: &[f64], w: &[f64], v: &[f64]) -> Estimate {
130    let c = 0.5 * (a + b);
131    let h = 0.5 * (b - a);
132    let fv: Vec<Vec<f64>> = x.iter().map(|&xi| f(c + h * xi)).collect();
133    let m = fv[0].len();
134    let mut s_k = vec![0.0; m];
135    let mut s_k_abs = vec![0.0; m];
136    for (fi, &vi) in fv.iter().zip(v) {
137        for j in 0..m {
138            s_k[j] += vi * fi[j];
139            s_k_abs[j] += vi * fi[j].abs();
140        }
141    }
142    let mut s_g = vec![0.0; m];
143    for (i, &wi) in w.iter().enumerate() {
144        for j in 0..m {
145            s_g[j] += wi * fv[2 * i + 1][j];
146        }
147    }
148    let mut s_k_dabs = vec![0.0; m];
149    for (fi, &vi) in fv.iter().zip(v) {
150        for j in 0..m {
151            s_k_dabs[j] += vi * (fi[j] - s_k[j] / 2.0).abs();
152        }
153    }
154    let mut err = norm_of(norm, &(0..m).map(|j| (s_k[j] - s_g[j]) * h).collect::<Vec<_>>());
155    let dabs = norm_of(norm, &s_k_dabs.iter().map(|d| d * h).collect::<Vec<_>>());
156    if dabs != 0.0 && err != 0.0 {
157        err = dabs * (200.0 * err / dabs).powf(1.5).min(1.0);
158    }
159    let round_err = norm_of(norm, &s_k_abs.iter().map(|s| 50.0 * f64::EPSILON * h * s).collect::<Vec<_>>());
160    if round_err > f64::MIN_POSITIVE {
161        err = err.max(round_err);
162    }
163    (s_k.iter().map(|s| h * s).collect(), err, round_err)
164}
165// ANCHOR_END: gk
166
167fn trapezoid(f: &mut dyn FnMut(f64) -> Vec<f64>, a: f64, b: f64, norm: VecNorm) -> Estimate {
168    let x3 = 0.5 * (a + b);
169    let (f1, f2, f3) = (f(a), f(b), f(x3));
170    let m = f1.len();
171    let s2: Vec<f64> = (0..m).map(|j| 0.25 * (b - a) * (f1[j] + 2.0 * f3[j] + f2[j])).collect();
172    let round_err = 0.25 * (b - a).abs() * (norm_of(norm, &f1) + 2.0 * norm_of(norm, &f3) + norm_of(norm, &f2)) * 2e-16;
173    let s1: Vec<f64> = (0..m).map(|j| 0.5 * (b - a) * (f1[j] + f2[j])).collect();
174    let err = norm_of(norm, &(0..m).map(|j| s1[j] - s2[j]).collect::<Vec<_>>()) / 3.0;
175    (s2, err, round_err)
176}
177
178fn apply(rule: VecRule, f: &mut dyn FnMut(f64) -> Vec<f64>, a: f64, b: f64, norm: VecNorm) -> (Estimate, usize) {
179    match rule {
180        VecRule::GaussKronrod21 => (gauss_kronrod(f, a, b, norm, &GK21_X, &GK21_W, &GK21_V), 21),
181        VecRule::GaussKronrod15 => (gauss_kronrod(f, a, b, norm, &GK15_X, &GK15_W, &GK15_V), 15),
182        VecRule::Trapezoid => (trapezoid(f, a, b, norm), 3),
183    }
184}
185
186/// A subinterval in the priority queue, ordered as SciPy's heap of `(−error, a, b)`: the largest
187/// error first, ties broken by the smaller `a`, then the smaller `b`.
188#[derive(Debug, PartialEq)]
189struct Item {
190    err: f64,
191    a: f64,
192    b: f64,
193}
194
195impl Eq for Item {}
196
197impl Ord for Item {
198    fn cmp(&self, other: &Self) -> Ordering {
199        // BinaryHeap is a max-heap; "greater" pops first.
200        self.err.total_cmp(&other.err).then(other.a.total_cmp(&self.a)).then(other.b.total_cmp(&self.b))
201    }
202}
203
204impl PartialOrd for Item {
205    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
206        Some(self.cmp(other))
207    }
208}
209
210fn key(a: f64, b: f64) -> (u64, u64) {
211    (a.to_bits(), b.to_bits())
212}
213
214// ANCHOR: quad_vec
215/// `∫_a^b f(x) dx` for vector-valued `f` (SciPy's `quad_vec`), with infinite limits allowed. The
216/// interval list starts from `[a, b]` split at `points`; each round pops the subintervals with the
217/// largest errors (up to 128, while their errors exceed all but an eighth of the tolerance) and
218/// bisects them, updating the global integral and error by the differences. It stops when the
219/// global error is below `max(epsabs, epsrel ‖I‖)/8`, or when it falls below the accumulated
220/// rounding error, or at `limit` subintervals. Infinite intervals are first mapped to `[0, 1]`
221/// (`x = a + (1 − t)/t`) or `[−1, 1]` (`x = (1 − |t|)/t`).
222pub fn quad_vec(mut f: impl FnMut(f64) -> Vec<f64>, a: f64, b: f64, options: &QuadVecOptions) -> Result<QuadVecResult, ErrorsJSL> {
223    if a.is_nan() || b.is_nan() {
224        return Err(ErrorsJSL::InvalidInputRange("quad_vec: the limits must not be NaN"));
225    }
226    let tmin = f64::MIN_POSITIVE.sqrt();
227    // The number of components, from one evaluation at a finite point of the range (not counted
228    // in nfev, as SciPy's evaluations of the mapped integrand are the only ones it counts).
229    let probe_x = match (a.is_finite(), b.is_finite()) {
230        (true, true) => 0.5 * (a + b),
231        (true, false) => a + b.signum(),
232        (false, true) => b + a.signum(),
233        (false, false) => 0.0,
234    };
235    let dim = f(probe_x).len();
236    if dim == 0 {
237        return Err(ErrorsJSL::InvalidInputRange("quad_vec: the integrand returned an empty vector"));
238    }
239    if a.is_finite() && b.is_infinite() || b.is_finite() && a.is_infinite() {
240        let (start, sgn, flip) = if a.is_finite() { (a, b.signum(), 1.0) } else { (b, a.signum(), -1.0) };
241        let mut g = |t: f64| -> Vec<f64> {
242            if t < tmin {
243                return vec![0.0; dim];
244            }
245            let x = start + sgn * (1.0 - t) / t;
246            f(x).into_iter().map(|v| sgn * (v / t) / t).collect()
247        };
248        let points: Vec<f64> = options.points.iter().map(|&p| { let z = sgn * (p - start) + 1.0; if z == 0.0 { f64::INFINITY } else { 1.0 / z } }).collect();
249        let o = QuadVecOptions { rule: Some(options.rule.unwrap_or(VecRule::GaussKronrod15)), points, ..options.clone() };
250        let mut r = finite(&mut g, 0.0, 1.0, &o)?;
251        r.value.iter_mut().for_each(|v| *v *= flip);
252        return Ok(r);
253    }
254    if a.is_infinite() && b.is_infinite() {
255        let sgn = if b < a { -1.0 } else { 1.0 };
256        let mut g = |t: f64| -> Vec<f64> {
257            if t.abs() < tmin {
258                return vec![0.0; dim];
259            }
260            let x = (1.0 - t.abs()) / t;
261            f(x).into_iter().map(|v| (v / t) / t).collect()
262        };
263        let mut points = vec![0.0];
264        points.extend(options.points.iter().map(|&p| p.signum() / (p.abs() + 1.0)));
265        let o = QuadVecOptions { rule: Some(options.rule.unwrap_or(VecRule::GaussKronrod15)), points, ..options.clone() };
266        let mut r = if a != b { finite(&mut g, -1.0, 1.0, &o)? } else { finite(&mut g, 1.0, 1.0, &o)? };
267        r.value.iter_mut().for_each(|v| *v *= sgn);
268        return Ok(r);
269    }
270    let o = QuadVecOptions { rule: Some(options.rule.unwrap_or(VecRule::GaussKronrod21)), ..options.clone() };
271    finite(&mut f, a, b, &o)
272}
273// ANCHOR_END: quad_vec
274
275/// `quad_vec` on a finite interval.
276fn finite(eval: &mut dyn FnMut(f64) -> Vec<f64>, a: f64, b: f64, o: &QuadVecOptions) -> Result<QuadVecResult, ErrorsJSL> {
277    let rule = o.rule.unwrap_or(VecRule::GaussKronrod21);
278    let norm = o.norm;
279    let mut intervals_init = Vec::new();
280    let mut prev = a;
281    let mut pts = o.points.clone();
282    pts.sort_by(f64::total_cmp);
283    for p in pts {
284        if !(a < p && p < b) || p == prev {
285            continue;
286        }
287        intervals_init.push((prev, p));
288        prev = p;
289    }
290    intervals_init.push((prev, b));
291    let mut cache: HashMap<(u64, u64), Vec<f64>> = HashMap::new();
292    let mut heap = BinaryHeap::new();
293    let mut nfev = 0;
294    let mut global: Option<Vec<f64>> = None;
295    let (mut global_error, mut rounding) = (0.0, 0.0);
296    for (x1, x2) in intervals_init {
297        let ((ig, err, rnd), n) = apply(rule, eval, x1, x2, norm);
298        nfev += n;
299        match &mut global {
300            None => {
301                global = Some(ig.clone());
302                global_error = err;
303                rounding = rnd;
304            }
305            Some(g) => {
306                g.iter_mut().zip(&ig).for_each(|(a, b)| *a += b);
307                global_error += err;
308                rounding += rnd;
309            }
310        }
311        cache.insert(key(x1, x2), ig);
312        heap.push(Item { err, a: x1, b: x2 });
313    }
314    let mut global = global.expect("at least one interval");
315    let mut status = 1;
316    while !heap.is_empty() && heap.len() < o.limit {
317        let tol = o.epsabs.max(o.epsrel * norm_of(norm, &global));
318        let mut to_process = Vec::new();
319        let mut err_sum = 0.0;
320        for j in 0..128 {
321            if heap.is_empty() {
322                break;
323            }
324            if j > 0 && err_sum > global_error - tol / 8.0 {
325                break;
326            }
327            let it = heap.pop().expect("non-empty");
328            err_sum += it.err;
329            to_process.push(it);
330        }
331        for it in to_process {
332            let (x1, x2) = (it.a, it.b);
333            let c = 0.5 * (x1 + x2);
334            // As SciPy, the trapezoid rule caches values within one bisection, so the shared
335            // midpoint is evaluated once; the Gauss-Kronrod nodes of the halves never coincide.
336            let mut memo: HashMap<u64, Vec<f64>> = HashMap::new();
337            let mut misses = 0usize;
338            let mut cached = |x: f64| -> Vec<f64> {
339                if rule != VecRule::Trapezoid {
340                    misses += 1;
341                    return eval(x);
342                }
343                memo.entry(x.to_bits()).or_insert_with(|| {
344                    misses += 1;
345                    eval(x)
346                }).clone()
347            };
348            let ((s1, e1, r1), _) = apply(rule, &mut cached, x1, c, norm);
349            let ((s2, e2, r2), _) = apply(rule, &mut cached, c, x2, norm);
350            nfev += misses;
351            let old = match cache.remove(&key(x1, x2)) {
352                Some(v) => v,
353                None => {
354                    let ((v, _, _), n) = apply(rule, eval, x1, x2, norm);
355                    nfev += n;
356                    v
357                }
358            };
359            for j in 0..global.len() {
360                global[j] += s1[j] + s2[j] - old[j];
361            }
362            global_error += e1 + e2 - it.err;
363            rounding += r1 + r2;
364            cache.insert(key(x1, c), s1);
365            cache.insert(key(c, x2), s2);
366            heap.push(Item { err: e1, a: x1, b: c });
367            heap.push(Item { err: e2, a: c, b: x2 });
368        }
369        if heap.len() >= 2 {
370            let tol = o.epsabs.max(o.epsrel * norm_of(norm, &global));
371            if global_error < tol / 8.0 {
372                status = 0;
373                break;
374            }
375            if global_error < rounding {
376                status = 2;
377                break;
378            }
379        }
380        if !(global_error.is_finite() && rounding.is_finite()) {
381            status = 3;
382            break;
383        }
384    }
385    Ok(QuadVecResult { value: global, error: global_error + rounding, nfev, converged: status == 0, status, intervals: heap.len() })
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    #[test]
393    fn vector_of_powers_and_infinite_ranges() {
394        // ∫₀¹ (1, x, x², …, x⁹) dx = 1/(k + 1).
395        let r = quad_vec(|x| (0..10).map(|k| x.powi(k)).collect(), 0.0, 1.0, &QuadVecOptions::default()).unwrap();
396        assert!(r.converged);
397        for (k, v) in r.value.iter().enumerate() {
398            assert!((v - 1.0 / (k as f64 + 1.0)).abs() < 1e-14);
399        }
400        // ∫₀^∞ e^{−kx} dx = 1/k, and ∫_{−∞}^{∞} e^{−x²} = √π.
401        let r = quad_vec(|x| vec![(-x).exp(), (-2.0 * x).exp()], 0.0, f64::INFINITY, &QuadVecOptions::default()).unwrap();
402        assert!((r.value[0] - 1.0).abs() < 1e-10 && (r.value[1] - 0.5).abs() < 1e-10, "{r:?}");
403        let r = quad_vec(|x| vec![(-x * x).exp()], f64::NEG_INFINITY, f64::INFINITY, &QuadVecOptions::default()).unwrap();
404        assert!((r.value[0] - std::f64::consts::PI.sqrt()).abs() < 1e-10);
405        let r = quad_vec(|x| vec![x.exp()], f64::NEG_INFINITY, 0.0, &QuadVecOptions::default()).unwrap();
406        assert!((r.value[0] - 1.0).abs() < 1e-10);
407    }
408}