Skip to main content

lib_jsl_integration/
weighted.rs

1//! Integrals with a known difficult weight, the cases of SciPy's `quad(weight=…)` (QUADPACK's
2//! QAWO, QAWF, QAWS and QAWC): oscillatory `cos ωx` and `sin ωx` on finite and semi-infinite
3//! intervals, algebraic-logarithmic endpoint singularities `(x − a)^α (b − x)^β [log]`, and Cauchy
4//! principal values `⨍ f(x)/(x − c) dx`. Each uses a method suited to the weight rather than a
5//! port of QUADPACK's modified Clenshaw-Curtis moments; the results are compared with SciPy in the
6//! book.
7//!
8//! See the book entry [Vector integrands and weighted quadrature](https://jwkunz.github.io/lib_jsl/book/integration/vector-weighted.html#weighted-integrals).
9
10use crate::quad_vec::{QuadVecOptions, quad_vec};
11use crate::tanh_sinh::TanhSinhEngine;
12use lib_jsl_core::ErrorsJSL;
13use std::f64::consts::PI;
14
15/// Which logarithmic factors an algebraic weight carries.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum LogFactor {
19    /// `(x − a)^α (b − x)^β` (SciPy's `'alg'`).
20    None,
21    /// Times `ln(x − a)` (`'alg-loga'`).
22    Left,
23    /// Times `ln(b − x)` (`'alg-logb'`).
24    Right,
25    /// Times `ln(x − a) ln(b − x)` (`'alg-log'`).
26    Both,
27}
28
29/// The weight `w(x)` in `∫ f(x) w(x) dx`.
30#[derive(Clone, Copy, Debug, PartialEq)]
31#[non_exhaustive]
32pub enum Weight {
33    /// `cos ωx`; `b` may be `+∞` (Fourier integral).
34    Cos(f64),
35    /// `sin ωx`; `b` may be `+∞`.
36    Sin(f64),
37    /// `(x − a)^α (b − x)^β`, possibly with logarithms, `α, β > −1`, on a finite interval.
38    Algebraic { alpha: f64, beta: f64, log: LogFactor },
39    /// `1/(x − c)` with `a < c < b`: the Cauchy principal value.
40    Cauchy(f64),
41}
42
43/// Tolerances for [`quad_weighted`] (SciPy's `quad` defaults).
44#[derive(Clone, Copy, Debug)]
45pub struct WeightedOptions {
46    pub epsabs: f64,
47    pub epsrel: f64,
48    /// The most half-periods summed for a Fourier integral on `[a, ∞)`.
49    pub max_cycles: usize,
50}
51
52impl Default for WeightedOptions {
53    fn default() -> Self {
54        WeightedOptions { epsabs: 1.49e-8, epsrel: 1.49e-8, max_cycles: 500 }
55    }
56}
57
58/// The result of [`quad_weighted`].
59#[derive(Clone, Copy, Debug)]
60#[non_exhaustive]
61pub struct WeightedResult {
62    pub value: f64,
63    pub error: f64,
64    pub nfev: usize,
65    pub converged: bool,
66}
67
68fn scalar(f: &mut dyn FnMut(f64) -> f64, a: f64, b: f64, points: Vec<f64>, o: &WeightedOptions) -> Result<(f64, f64, usize, bool), ErrorsJSL> {
69    let opts = QuadVecOptions { epsabs: o.epsabs.max(1e-200), epsrel: o.epsrel, points, ..Default::default() };
70    let r = quad_vec(|x| vec![f(x)], a, b, &opts)?;
71    Ok((r.value[0], r.error, r.nfev, r.converged))
72}
73
74// ANCHOR: wynn
75/// Wynn's ε algorithm: the extrapolated limit of a sequence of partial sums, from its last
76/// entries, with an error estimate from the change between successive extrapolations.
77fn wynn_epsilon(sums: &[f64]) -> (f64, f64) {
78    let n = sums.len();
79    if n < 3 {
80        let last = sums[n - 1];
81        return (last, if n > 1 { (last - sums[n - 2]).abs() } else { f64::INFINITY });
82    }
83    // e[k][j]: the ε table, column k; even columns are estimates of the limit.
84    let mut prev: Vec<f64> = vec![0.0; n + 1];
85    let mut cur: Vec<f64> = sums.to_vec();
86    let mut best = (sums[n - 1], (sums[n - 1] - sums[n - 2]).abs());
87    let mut k = 0;
88    while cur.len() > 1 {
89        let next: Vec<f64> = (0..cur.len() - 1)
90            .map(|j| {
91                let d = cur[j + 1] - cur[j];
92                if d == 0.0 { f64::INFINITY } else { prev[j + 1] + 1.0 / d }
93            })
94            .collect();
95        k += 1;
96        if k % 2 == 0 && next.len() >= 2 {
97            let (a, b) = (next[next.len() - 1], next[next.len() - 2]);
98            if a.is_finite() && b.is_finite() {
99                let err = (a - b).abs();
100                if err < best.1 {
101                    best = (a, err);
102                }
103            }
104        }
105        prev = cur;
106        cur = next;
107    }
108    best
109}
110// ANCHOR_END: wynn
111
112/// `J_0(κ), …, J_L(κ)` for `κ ≥ 0`, by Miller's backward recurrence normalised with
113/// `J_0 + 2 Σ J_{2k} = 1`.
114fn bessel_j_all(kappa: f64, l: usize) -> Vec<f64> {
115    let mut j = vec![0.0; l + 1];
116    if kappa == 0.0 {
117        j[0] = 1.0;
118        return j;
119    }
120    let top = l.max(kappa as usize);
121    let mut start = top + (160.0 * top as f64).sqrt() as usize + 20;
122    start += start % 2;
123    let (mut next, mut cur) = (0.0f64, 1e-300f64);
124    let mut sum = 0.0;
125    for n in (1..=start).rev() {
126        let prev = 2.0 * n as f64 / kappa * cur - next;
127        next = cur;
128        cur = prev;
129        // cur is now J_{n−1} (unnormalised).
130        if n - 1 <= l {
131            j[n - 1] = cur;
132        }
133        if (n - 1) % 2 == 0 && n > 1 {
134            sum += 2.0 * cur;
135        }
136        if cur.abs() > 1e250 {
137            cur *= 1e-250;
138            next *= 1e-250;
139            sum *= 1e-250;
140            j.iter_mut().for_each(|v| *v *= 1e-250);
141        }
142    }
143    let norm = sum + cur;
144    j.iter_mut().for_each(|v| *v /= norm);
145    j
146}
147
148// ANCHOR: fcc_moments
149/// The modified moments `μ_k = ∫_{−1}^{1} T_k(t) e^{iκt} dt`, `k = 0..=n`, from the Jacobi-Anger
150/// expansion `e^{iκt} = Σ ε_m i^m J_m(κ) T_m(t)` (`ε_0 = 1`, otherwise 2) and the closed form of
151/// `∫ T_k T_m = 1/(1 − (k + m)²) + 1/(1 − (k − m)²)` for `k + m` even (zero otherwise). The cost
152/// is `O(n κ)` operations and no evaluations of the integrand.
153fn chebyshev_fourier_moments(kappa: f64, n: usize) -> Vec<(f64, f64)> {
154    let k_abs = kappa.abs();
155    let l = n + k_abs as usize + 40 + (10.0 * k_abs.cbrt()) as usize;
156    let j = bessel_j_all(k_abs, l);
157    (0..=n)
158        .map(|k| {
159            let (mut re, mut im) = (0.0, 0.0);
160            for (m, &jm) in j.iter().enumerate() {
161                if (k + m) % 2 == 1 {
162                    continue;
163                }
164                let (s, d) = ((k + m) as f64, k as f64 - m as f64);
165                let w = 1.0 / (1.0 - s * s) + 1.0 / (1.0 - d * d);
166                let c = if m == 0 { 1.0 } else { 2.0 } * jm * w;
167                // i^m: 1, i, −1, −i.
168                match m % 4 {
169                    0 => re += c,
170                    1 => im += c,
171                    2 => re -= c,
172                    _ => im -= c,
173                }
174            }
175            // e^{iκt} for κ < 0 is the conjugate of e^{i|κ|t}.
176            (re, if kappa < 0.0 { -im } else { im })
177        })
178        .collect()
179}
180// ANCHOR_END: fcc_moments
181
182// ANCHOR: filon
183/// `∫_a^b f(x) e^{iωx} dx` by adaptive Filon-Clenshaw-Curtis quadrature: on each subinterval,
184/// `f` alone is interpolated at 17, then 33, then 65 nested Chebyshev points, and the
185/// interpolant is integrated against `e^{iωx}` exactly through the modified moments. The error
186/// of a subinterval is estimated from the size of the last Chebyshev coefficients; the one with
187/// the largest error is bisected until the total meets the tolerance. Because only `f` is
188/// interpolated, the cost does not grow with `ω`. Returns `(re, im, error, nfev, converged)`.
189fn filon_clenshaw_curtis(f: &mut dyn FnMut(f64) -> f64, a: f64, b: f64, omega: f64, o: &WeightedOptions) -> (f64, f64, f64, usize, bool) {
190    let mut nfev = 0;
191    let mut panel = |x0: f64, x1: f64, nfev: &mut usize| -> ((f64, f64), f64) {
192        let (c, h) = (0.5 * (x0 + x1), 0.5 * (x1 - x0));
193        let mut values: Vec<f64> = Vec::new();
194        let mut last = ((0.0, 0.0), f64::INFINITY);
195        for n in [16usize, 32, 64] {
196            // Values at t_j = cos(jπ/n); the even-indexed ones are those of the previous level.
197            let mut g = vec![0.0; n + 1];
198            for (jj, gj) in g.iter_mut().enumerate() {
199                if n > 16 && jj % 2 == 0 {
200                    *gj = values[jj / 2];
201                } else {
202                    *gj = f(c + h * (jj as f64 * PI / n as f64).cos());
203                    *nfev += 1;
204                }
205            }
206            values = g;
207            let coef: Vec<f64> = (0..=n)
208                .map(|k| {
209                    let s: f64 = (0..=n).map(|jj| {
210                        let w = if jj == 0 || jj == n { 0.5 } else { 1.0 };
211                        w * values[jj] * ((jj * k) as f64 * PI / n as f64).cos()
212                    }).sum();
213                    let ck = 2.0 / n as f64 * s;
214                    if k == 0 || k == n { ck / 2.0 } else { ck }
215                })
216                .collect();
217            let mu = chebyshev_fourier_moments(omega * h, n);
218            let (mut re, mut im) = (0.0, 0.0);
219            for (ck, (mr, mi)) in coef.iter().zip(&mu) {
220                re += ck * mr;
221                im += ck * mi;
222            }
223            // Multiply by h e^{iωc}.
224            let (cs, sn) = ((omega * c).cos(), (omega * c).sin());
225            let value = (h * (re * cs - im * sn), h * (re * sn + im * cs));
226            let scale = values.iter().fold(0.0f64, |m, v| m.max(v.abs()));
227            let tail = coef[n - 2..].iter().map(|v| v.abs()).sum::<f64>();
228            let error = 2.0 * h.abs() * tail.max(50.0 * f64::EPSILON * scale);
229            last = (value, error);
230            let tol = o.epsabs.max(o.epsrel * value.0.hypot(value.1));
231            if error <= tol {
232                break;
233            }
234        }
235        last
236    };
237    let mut pieces = vec![(a, b, panel(a, b, &mut nfev))];
238    let limit = 200;
239    loop {
240        let (re, im): (f64, f64) = pieces.iter().fold((0.0, 0.0), |s, p| (s.0 + p.2.0.0, s.1 + p.2.0.1));
241        let error: f64 = pieces.iter().map(|p| p.2.1).sum();
242        let tol = o.epsabs.max(o.epsrel * re.hypot(im));
243        if error <= tol || pieces.len() >= limit {
244            return (re, im, error, nfev, error <= tol);
245        }
246        let worst = (0..pieces.len()).max_by(|&i, &j| pieces[i].2.1.total_cmp(&pieces[j].2.1)).expect("non-empty");
247        let (x0, x1, _) = pieces.swap_remove(worst);
248        let mid = 0.5 * (x0 + x1);
249        pieces.push((x0, mid, panel(x0, mid, &mut nfev)));
250        pieces.push((mid, x1, panel(mid, x1, &mut nfev)));
251    }
252}
253// ANCHOR_END: filon
254
255// ANCHOR: quad_weighted
256/// `∫_a^b f(x) w(x) dx` for the weights of SciPy's `quad(weight=…)`:
257///
258/// - `Cos(ω)`, `Sin(ω)` on `[a, b]`: adaptive Filon-Clenshaw-Curtis quadrature, which
259///   interpolates `f` alone and integrates the oscillation exactly, so its cost does not grow
260///   with `ω`; on `[a, ∞)`, the integrals over successive half-periods
261///   form an alternating series whose limit is extrapolated by Wynn's ε algorithm (QAWF's idea).
262/// - `Algebraic`: tanh-sinh quadrature of `f(x)w(x)`, which tolerates the integrable endpoint
263///   singularities; the endpoint distances are formed exactly, so `(b − x)^β` loses nothing near `b`.
264/// - `Cauchy(c)`: with `d = min(c − a, b − c)`, the principal value is
265///   `∫₀^d (f(c + t) − f(c − t))/t dt` (a smooth integrand) plus the ordinary integral of
266///   `f(x)/(x − c)` over the part of `[a, b]` outside `[c − d, c + d]`.
267#[allow(clippy::neg_cmp_op_on_partial_ord)] // the negations also reject NaN
268pub fn quad_weighted(mut f: impl FnMut(f64) -> f64, a: f64, b: f64, weight: Weight, options: &WeightedOptions) -> Result<WeightedResult, ErrorsJSL> {
269    if a.is_nan() || b.is_nan() || !a.is_finite() {
270        return Err(ErrorsJSL::InvalidInputRange("quad_weighted: a must be finite"));
271    }
272    match weight {
273        Weight::Cos(omega) | Weight::Sin(omega) => {
274            let cosine = matches!(weight, Weight::Cos(_));
275            let w = move |x: f64| if cosine { (omega * x).cos() } else { (omega * x).sin() };
276            if b.is_finite() {
277                if omega == 0.0 {
278                    let (v, e, n, c) = scalar(&mut |x| f(x) * w(x), a, b, Vec::new(), options)?;
279                    return Ok(WeightedResult { value: v, error: e, nfev: n, converged: c });
280                }
281                let (re, im, error, nfev, converged) = filon_clenshaw_curtis(&mut f, a, b, omega, options);
282                return Ok(WeightedResult { value: if cosine { re } else { im }, error, nfev, converged });
283            }
284            if b != f64::INFINITY || omega == 0.0 {
285                return Err(ErrorsJSL::InvalidInputRange("quad_weighted: a Fourier integral needs b = +∞ and ω ≠ 0"));
286            }
287            // Half-periods from a, aligned to the zeros of the weight after the first.
288            let half = PI / omega.abs();
289            let phase0 = if cosine { half / 2.0 } else { 0.0 };
290            let first_zero = ((a - phase0) / half).floor() * half + phase0 + half;
291            let mut edges = vec![a, first_zero];
292            let mut sums = Vec::new();
293            let mut total = 0.0;
294            let mut nfev = 0;
295            let mut err_sum = 0.0;
296            let mut best = (0.0, f64::INFINITY);
297            for k in 0..options.max_cycles {
298                let (x0, x1) = (edges[k], edges[k + 1]);
299                let (v, e, n, _) = scalar(&mut |x| f(x) * w(x), x0, x1, Vec::new(), options)?;
300                total += v;
301                err_sum += e;
302                nfev += n;
303                sums.push(total);
304                edges.push(x1 + half);
305                if sums.len() >= 4 {
306                    let start = sums.len().saturating_sub(40);
307                    best = wynn_epsilon(&sums[start..]);
308                    let tol = options.epsabs.max(options.epsrel * best.0.abs());
309                    if best.1 <= tol && sums.len() >= 8 {
310                        return Ok(WeightedResult { value: best.0, error: best.1 + err_sum, nfev, converged: true });
311                    }
312                }
313            }
314            Ok(WeightedResult { value: best.0, error: best.1 + err_sum, nfev, converged: false })
315        }
316        Weight::Algebraic { alpha, beta, log } => {
317            if !b.is_finite() || !(b > a) || !(alpha > -1.0) || !(beta > -1.0) {
318                return Err(ErrorsJSL::InvalidInputRange("quad_weighted: algebraic weights need a < b finite and α, β > −1"));
319            }
320            let width = b - a;
321            let mut engine = TanhSinhEngine::new(a, b);
322            engine.tolerance = options.epsrel.max(1e-15);
323            engine.max_levels = 12;
324            let calls = std::cell::Cell::new(0usize);
325            let fcell = std::cell::RefCell::new(&mut f);
326            // `c` is x − a in the lower half and x − b in the upper half, exactly.
327            let (value, error) = engine.integrate_with_complement(|x, c| {
328                calls.set(calls.get() + 1);
329                let (da, db) = if c >= 0.0 && x - a <= b - x { (c, width - c) } else { (width + c, -c) };
330                if da <= 0.0 || db <= 0.0 {
331                    return 0.0;
332                }
333                let mut wv = da.powf(alpha) * db.powf(beta);
334                match log {
335                    LogFactor::None => {}
336                    LogFactor::Left => wv *= da.ln(),
337                    LogFactor::Right => wv *= db.ln(),
338                    LogFactor::Both => wv *= da.ln() * db.ln(),
339                }
340                (fcell.borrow_mut())(x) * wv
341            })?;
342            let tol = options.epsabs.max(options.epsrel * value.abs());
343            Ok(WeightedResult { value, error, nfev: calls.get(), converged: error <= tol.max(1e-14 * value.abs()) })
344        }
345        Weight::Cauchy(c) => {
346            if !b.is_finite() || !(a < c && c < b) {
347                return Err(ErrorsJSL::InvalidInputRange("quad_weighted: a Cauchy weight needs a < c < b, finite"));
348            }
349            let d = (c - a).min(b - c);
350            let (v1, e1, n1, ok1) = scalar(&mut |t| (f(c + t) - f(c - t)) / t, 0.0, d, Vec::new(), options)?;
351            let (mut v, mut e, mut n, mut ok) = (v1, e1, n1, ok1);
352            if c + d < b {
353                let (v2, e2, n2, ok2) = scalar(&mut |x| f(x) / (x - c), c + d, b, Vec::new(), options)?;
354                v += v2;
355                e += e2;
356                n += n2;
357                ok &= ok2;
358            }
359            if c - d > a {
360                let (v2, e2, n2, ok2) = scalar(&mut |x| f(x) / (x - c), a, c - d, Vec::new(), options)?;
361                v += v2;
362                e += e2;
363                n += n2;
364                ok &= ok2;
365            }
366            Ok(WeightedResult { value: v, error: e, nfev: n, converged: ok })
367        }
368    }
369}
370// ANCHOR_END: quad_weighted
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn closed_forms() {
378        let o = WeightedOptions::default();
379        // ∫₀^π x cos(10x) dx = (cos 10π − 1)/100 = 0.
380        let r = quad_weighted(|x| x, 0.0, PI, Weight::Cos(10.0), &o).unwrap();
381        assert!(r.value.abs() < 1e-12, "{r:?}");
382        // ∫₀^∞ e^{−x} cos x dx = 1/2, ∫₀^∞ sin x / x dx = π/2.
383        let r = quad_weighted(|x| (-x).exp(), 0.0, f64::INFINITY, Weight::Cos(1.0), &o).unwrap();
384        assert!((r.value - 0.5).abs() < 1e-9, "{r:?}");
385        let r = quad_weighted(|x| if x == 0.0 { 1.0 } else { 1.0 / x }, 0.0, f64::INFINITY, Weight::Sin(1.0), &o).unwrap();
386        assert!((r.value - PI / 2.0).abs() < 1e-7, "{r:?}");
387        // ∫₀¹ x^{−1/2} (1 − x)^{−1/2} dx = π; ∫₀¹ ln x dx = −1.
388        let r = quad_weighted(|_| 1.0, 0.0, 1.0, Weight::Algebraic { alpha: -0.5, beta: -0.5, log: LogFactor::None }, &o).unwrap();
389        assert!((r.value - PI).abs() < 1e-10, "{r:?}");
390        let r = quad_weighted(|_| 1.0, 0.0, 1.0, Weight::Algebraic { alpha: 0.0, beta: 0.0, log: LogFactor::Left }, &o).unwrap();
391        assert!((r.value + 1.0).abs() < 1e-12, "{r:?}");
392        // ⨍₋₁² 1/(x − 0) dx = ln 2.
393        let r = quad_weighted(|_| 1.0, -1.0, 2.0, Weight::Cauchy(0.0), &o).unwrap();
394        assert!((r.value - 2f64.ln()).abs() < 1e-12, "{r:?}");
395    }
396
397    #[test]
398    fn filon_cost_does_not_grow_with_frequency() {
399        // ∫₀^π e^x cos(ωx) dx = (e^π (−1)^m − 1) / (1 + ω²) for integer ω = m, and the sine
400        // integral is −ω (e^π (−1)^m − 1) / (1 + ω²).
401        // An absolute tolerance: the integral shrinks like 1/ω, while rounding errors stay at
402        // ε max|f| (b − a), so a relative tolerance becomes unreachable at high frequency.
403        let o = WeightedOptions { epsabs: 1e-12, epsrel: 0.0, ..Default::default() };
404        let mut counts = Vec::new();
405        for m in [3.0f64, 50.0, 2000.0, 100_000.0] {
406            let sign = if m as i64 % 2 == 0 { 1.0 } else { -1.0 };
407            let c = (std::f64::consts::PI.exp() * sign - 1.0) / (1.0 + m * m);
408            let r = quad_weighted(f64::exp, 0.0, PI, Weight::Cos(m), &o).unwrap();
409            assert!(r.converged && (r.value - c).abs() < 1e-13, "ω = {m}: {r:?} vs {c}");
410            let s = quad_weighted(f64::exp, 0.0, PI, Weight::Sin(m), &o).unwrap();
411            assert!((s.value + m * c).abs() < 1e-13, "ω = {m}: {s:?}");
412            counts.push(r.nfev);
413        }
414        assert!(counts.iter().all(|&n| n == counts[0]), "{counts:?}");
415        // The Bessel functions behind the moments: J₀(1), J₁(1), J₅(10).
416        let j = bessel_j_all(1.0, 2);
417        assert!((j[0] - 0.765_197_686_557_966_6).abs() < 1e-15 && (j[1] - 0.440_050_585_744_933_5).abs() < 1e-15);
418        assert!((bessel_j_all(10.0, 5)[5] + 0.234_061_528_186_793_6).abs() < 1e-14);
419    }
420}