Skip to main content

lib_jsl_special_functions/
faddeeva.rs

1//! The Faddeeva function `w(z) = e^{−z²} erfc(−iz)` (SciPy's `wofz`) and the Voigt profile, the
2//! convolution of a Gaussian and a Lorentzian (SciPy's `voigt_profile`).
3//!
4//! See the book entry [Faddeeva, Struve, Kelvin and Hankel functions](https://jwkunz.github.io/lib_jsl/book/special_functions/faddeeva-struve-kelvin.html).
5
6use crate::dawsons_integral::dawson_integral;
7use num_complex::Complex;
8use std::f64::consts::PI;
9use std::sync::OnceLock;
10
11type C = Complex<f64>;
12
13/// Terms of Weideman's rational approximation.
14const N: usize = 40;
15
16/// The coefficients of Weideman's (1994) expansion of `w` in powers of `Z = (L + iz)/(L − iz)`,
17/// from a discrete Fourier transform of `e^{−t²}(L² + t²)` sampled at `t = L tan(θ/2)`.
18fn weideman_coefficients() -> &'static (f64, Vec<f64>) {
19    static COEF: OnceLock<(f64, Vec<f64>)> = OnceLock::new();
20    COEF.get_or_init(|| {
21        let m = 2 * N;
22        let m2 = 2 * m;
23        let l = (N as f64 / 2f64.sqrt()).sqrt();
24        // f over k = −M+1..M−1, preceded by a zero: 2M samples.
25        let mut f = vec![0.0; 2 * m];
26        for (idx, k) in (-(m as isize) + 1..m as isize).enumerate() {
27            let theta = k as f64 * PI / m as f64;
28            let t = l * (theta / 2.0).tan();
29            f[idx + 1] = (-t * t).exp() * (l * l + t * t);
30        }
31        // fftshift, then the real part of the DFT, divided by 2M·2 = M2.
32        let len = f.len();
33        let shifted: Vec<f64> = (0..len).map(|i| f[(i + len / 2) % len]).collect();
34        let a: Vec<f64> = (0..len)
35            .map(|j| shifted.iter().enumerate().map(|(n, v)| v * (2.0 * PI * (j * n) as f64 / len as f64).cos()).sum::<f64>() / m2 as f64)
36            .collect();
37        // a(2..N+1), reversed: the polynomial's coefficients from the highest power.
38        let coef: Vec<f64> = a[1..=N].iter().rev().copied().collect();
39        (l, coef)
40    })
41}
42
43fn weideman(z: C) -> C {
44    let (l, coef) = weideman_coefficients();
45    let i = C::new(0.0, 1.0);
46    let zz = (*l + i * z) / (*l - i * z);
47    let p = coef.iter().fold(C::new(0.0, 0.0), |acc, &c| acc * zz + c);
48    p * 2.0 / ((*l - i * z) * (*l - i * z)) + 1.0 / (PI.sqrt() * (*l - i * z))
49}
50
51/// Laplace's continued fraction `w(z) = (i/√π) / (z − ½/(z − 1/(z − (3/2)/(z − …))))`, which
52/// converges quickly for large `|z|` in the upper half plane.
53fn continued_fraction(z: C) -> C {
54    let mut t = z;
55    for k in (1..=40).rev() {
56        t = z - (k as f64 / 2.0) / t;
57    }
58    C::new(0.0, 1.0 / PI.sqrt()) / t
59}
60
61/// The Taylor series about the real axis, `w(x + iy) = Σ w⁽ⁿ⁾(x) (iy)ⁿ/n!`, with
62/// `w(x) = e^{−x²} + (2i/√π) D(x)`, `w' = −2zw + 2i/√π` and `w⁽ⁿ⁺¹⁾ = −2x w⁽ⁿ⁾ − 2n w⁽ⁿ⁻¹⁾`. Near the
63/// real axis `Re w` is much smaller than `|w|`, so the other methods, accurate relative to `|w|`,
64/// lose its digits; the series keeps both parts to about 10⁻¹⁴ for `0 < y ≤ ½`, `|x| < 9`.
65fn taylor_near_real_axis(x: f64, y: f64) -> C {
66    let c = 2.0 / PI.sqrt();
67    let w0 = C::new((-x * x).exp(), c * dawson_integral(x));
68    let mut prev = w0;
69    let mut cur = -2.0 * x * w0 + C::new(0.0, c);
70    let mut sum = w0;
71    let mut t = C::new(0.0, y);
72    for n in 1..60 {
73        sum += cur * t;
74        let next = -2.0 * x * cur - 2.0 * n as f64 * prev;
75        prev = cur;
76        cur = next;
77        t *= C::new(0.0, y / (n + 1) as f64);
78        if t.norm() == 0.0 {
79            break;
80        }
81    }
82    sum
83}
84
85// ANCHOR: wofz
86/// The Faddeeva function `w(z) = e^{−z²} erfc(−iz)` (SciPy's `wofz`). On the real axis it is
87/// `e^{−x²} + (2i/√π) D(x)` with Dawson's integral `D`; just above it (`0 < y ≤ ½`, `|x| < 9`) the
88/// Taylor series in `y` about that, which keeps the small real part accurate; elsewhere in the
89/// upper half plane, Weideman's rational approximation with 40 terms for `|z| < 6` and Laplace's
90/// continued fraction beyond;
91/// in the lower half plane, the reflection `w(z) = 2 e^{−z²} − w(−z)`. Relative accuracy about
92/// 10⁻¹⁴ in the upper half plane, for the real and imaginary parts separately.
93pub fn wofz(z: C) -> C {
94    if z.re.is_nan() || z.im.is_nan() {
95        return C::new(f64::NAN, f64::NAN);
96    }
97    if z.im == 0.0 {
98        let x = z.re;
99        return C::new((-x * x).exp(), 2.0 / PI.sqrt() * dawson_integral(x));
100    }
101    if z.im < 0.0 {
102        return (-z * z).exp() * 2.0 - wofz(-z);
103    }
104    if z.im <= 0.5 && z.re.abs() < 9.0 {
105        taylor_near_real_axis(z.re, z.im)
106    } else if z.norm() >= 6.0 {
107        continued_fraction(z)
108    } else {
109        weideman(z)
110    }
111}
112// ANCHOR_END: wofz
113
114// ANCHOR: voigt
115/// The Voigt profile (SciPy's `voigt_profile`): the density of the sum of a normal variable with
116/// standard deviation `σ` and a Cauchy variable with half-width `γ`,
117/// `V(x) = Re w((x + iγ)/(σ√2)) / (σ√(2π))`. With `σ = 0` it is the Lorentzian, with `γ = 0` the
118/// Gaussian.
119pub fn voigt_profile(x: f64, sigma: f64, gamma: f64) -> f64 {
120    if !(sigma >= 0.0) || !(gamma >= 0.0) {
121        return f64::NAN;
122    }
123    if sigma == 0.0 {
124        return if gamma == 0.0 { if x == 0.0 { f64::INFINITY } else { 0.0 } } else { gamma / (PI * (x * x + gamma * gamma)) };
125    }
126    let s = sigma * 2f64.sqrt();
127    wofz(C::new(x / s, gamma / s)).re / (sigma * (2.0 * PI).sqrt())
128}
129// ANCHOR_END: voigt
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn identities_and_limits() {
137        // w(iy) = e^{y²} erfc(y), real.
138        for &y in &[0.1, 0.8, 3.0, 10.0] {
139            let w = wofz(C::new(0.0, y));
140            let want = (y * y).exp() * crate::error_function::erfc(y);
141            assert!((w.re - want).abs() < 1e-13 * want && w.im.abs() < 1e-14 * want, "{y}");
142        }
143        // w(−z̄) = conj(w(z)), across all regions.
144        for &(x, y) in &[(0.3, 0.2), (2.0, 1.0), (7.0, 0.1), (3.0, 4.0), (-5.0, 9.0), (1.0, -0.7)] {
145            let (a, b) = (wofz(C::new(x, y)), wofz(C::new(-x, y)));
146            assert!((a - b.conj()).norm() < 1e-14 * a.norm(), "{x} {y}");
147        }
148        // Continuity across the switch between methods.
149        for &(x, y) in &[(8.999, 0.3), (9.001, 0.3), (2.0, 0.4999), (2.0, 0.5001), (4.2, 4.3)] {
150            let (a, b) = (wofz(C::new(x, y)), wofz(C::new(x + 1e-9, y + 1e-9)));
151            assert!((a - b).norm() < 1e-8 * a.norm(), "{x} {y}");
152        }
153        // The Voigt profile integrates to one and has the right limits.
154        let h = 0.01;
155        let area: f64 = (-40000..=40000).map(|i| voigt_profile(i as f64 * h, 0.7, 0.3)).sum::<f64>() * h;
156        assert!((area - 1.0).abs() < 1e-3, "{area}");
157        assert!((voigt_profile(0.4, 1.0, 0.0) - (-0.08f64).exp() / (2.0 * PI).sqrt()).abs() < 1e-15);
158    }
159}