Skip to main content

lib_jsl_ffts/
fftlog.rs

1//! The fast Hankel transform by Hamilton's FFTLog (SciPy's `fft.fht`, `fft.ifht` and
2//! `fft.fhtoffset`), and FFTs of Hermitian-symmetric signals (`fft.hfft`, `fft.ihfft`).
3//!
4//! The Hankel transform `A(k) = ∫₀^∞ a(r) J_μ(kr) k dr` of a function sampled at logarithmically
5//! spaced points becomes a convolution in `ln r`, which FFTLog evaluates with two real FFTs and a
6//! multiplication by the Mellin transform of the Bessel kernel, a ratio of gamma functions.
7//!
8//! See the book entry [Real QZ, reordering and Hankel transforms](https://jwkunz.github.io/lib_jsl/book/linear_algebra/qz-reordering.html#the-fast-hankel-transform).
9
10use crate::real_fft::{irfft, rfft};
11use lib_jsl_core::ErrorsJSL;
12use num_complex::Complex;
13
14type C64 = Complex<f64>;
15
16const LN_2: f64 = std::f64::consts::LN_2;
17
18/// `ln Γ(z)` for complex `z` away from the poles: the recurrence `Γ(z) = Γ(z + N)/(z(z+1)…)`
19/// moves the argument to `|z| ≥ 15`, where Stirling's series with eight terms is accurate to
20/// rounding. (The imaginary part is determined only modulo 2π, which is all FFTLog needs.)
21pub fn ln_gamma_complex(z: C64) -> C64 {
22    let mut z = z;
23    let mut shift = C64::new(0.0, 0.0);
24    while z.re < 15.0 || z.norm() < 15.0 {
25        shift += z.ln();
26        z += 1.0;
27        if z.re > 1e6 {
28            break;
29        }
30    }
31    const B: [f64; 8] = [1.0 / 6.0, -1.0 / 30.0, 1.0 / 42.0, -1.0 / 30.0, 5.0 / 66.0, -691.0 / 2730.0, 7.0 / 6.0, -3617.0 / 510.0];
32    let mut series = C64::new(0.0, 0.0);
33    let z2 = z * z;
34    let mut zp = z;
35    for (k, b) in B.iter().enumerate() {
36        let k2 = 2.0 * (k + 1) as f64;
37        series += b / (k2 * (k2 - 1.0)) / zp;
38        zp *= z2;
39    }
40    (z - 0.5) * z.ln() - z + 0.5 * (2.0 * std::f64::consts::PI).ln() + series - shift
41}
42
43/// `Γ(a + m)/Γ(a)` at real arguments, with the limits at the poles.
44fn poch(a: f64, m: f64) -> f64 {
45    let pole = |x: f64| x <= 0.0 && x == x.floor();
46    let b = a + m;
47    match (pole(b), pole(a)) {
48        (true, true) => {
49            // Ratio of residues (−1)ⁿ/n!.
50            let (nb, na) = (-b, -a);
51            let sign = if ((nb - na) as i64).rem_euclid(2) == 0 { 1.0 } else { -1.0 };
52            sign * (ln_gamma_complex(C64::new(na + 1.0, 0.0)).re - ln_gamma_complex(C64::new(nb + 1.0, 0.0)).re).exp()
53        }
54        (true, false) => f64::INFINITY,
55        (false, true) => 0.0,
56        _ => {
57            let g = |x: f64| -> (f64, f64) {
58                let l = ln_gamma_complex(C64::new(x, 0.0));
59                let sign = if x > 0.0 || (x.floor() as i64).rem_euclid(2) == 0 { 1.0 } else { -1.0 };
60                (l.re, sign)
61            };
62            let (lb, sb) = g(b);
63            let (la, sa) = g(a);
64            sb * sa * (lb - la).exp()
65        }
66    }
67}
68
69/// The FFTLog coefficients `u_m` (SciPy's `fhtcoeff`).
70fn fhtcoeff(n: usize, dln: f64, mu: f64, offset: f64, bias: f64, inverse: bool) -> Vec<C64> {
71    let (lnkr, q) = (offset, bias);
72    let xp = (mu + 1.0 + q) / 2.0;
73    let xm = (mu + 1.0 - q) / 2.0;
74    let m = n / 2 + 1;
75    let mut u: Vec<C64> = (0..m)
76        .map(|i| {
77            let y = if m > 1 { std::f64::consts::PI * (n / 2) as f64 / (n as f64 * dln) * i as f64 / (m - 1) as f64 } else { 0.0 };
78            let v = ln_gamma_complex(C64::new(xm, y));
79            let w = ln_gamma_complex(C64::new(xp, y));
80            let re = w.re - v.re + LN_2 * q;
81            let im = w.im + v.im + 2.0 * (LN_2 - lnkr) * y;
82            C64::new(re, im).exp()
83        })
84        .collect();
85    if n.is_multiple_of(2) {
86        let last = u.len() - 1;
87        u[last].im = 0.0;
88    }
89    if !(u[0].re.is_finite() && u[0].im.is_finite()) {
90        u[0] = C64::new(2f64.powf(q) * poch(xm, xp - xm), 0.0);
91    }
92    if !inverse && u[0].re.is_infinite() {
93        u[0] = C64::new(0.0, 0.0);
94    } else if inverse && u[0] == C64::new(0.0, 0.0) {
95        u[0] = C64::new(f64::INFINITY, 0.0);
96    }
97    u
98}
99
100fn fhtq(a: &[f64], u: &[C64], inverse: bool) -> Result<Vec<f64>, ErrorsJSL> {
101    let n = a.len();
102    let mut spec = rfft(a)?;
103    for (s, &c) in spec.iter_mut().zip(u) {
104        *s = if inverse { *s / c.conj() } else { *s * c };
105    }
106    let mut out = irfft(&spec, n)?;
107    out.reverse();
108    Ok(out)
109}
110
111// ANCHOR: fht
112/// The fast Hankel transform (SciPy's `fht`) of `a`, sampled at `r_j = r_c exp((j − j_c) dln)`,
113/// `j_c = (n − 1)/2`: approximately `A(k_j) = ∫₀^∞ a(r) J_μ(k_j r) k_j dr` at
114/// `k_j = exp(offset)/r_c · exp((j − j_c) dln)`. With `bias = q` the input is multiplied by
115/// `(r/r_c)^{−q}` and the output by `(k/k_c)^{−q}`, which can reduce ringing. FFTLog computes it
116/// exactly for the periodic, log-spaced interpolant of `a`: an rFFT, multiplication by
117/// `u_m = 2^{q} Γ((μ+1+q+iy_m)/2)/Γ((μ+1−q−iy_m)/2) · e^{i y_m (ln 2 − offset)}`, an inverse rFFT
118/// and a reversal.
119pub fn fht(a: &[f64], dln: f64, mu: f64, offset: f64, bias: f64) -> Result<Vec<f64>, ErrorsJSL> {
120    let n = a.len();
121    if n == 0 || dln.is_nan() || dln <= 0.0 {
122        return Err(ErrorsJSL::InvalidInputRange("fht: need a non-empty input and dln > 0"));
123    }
124    let jc = (n as f64 - 1.0) / 2.0;
125    let biased: Vec<f64> = if bias != 0.0 { a.iter().enumerate().map(|(j, &v)| v * (-bias * (j as f64 - jc) * dln).exp()).collect() } else { a.to_vec() };
126    let u = fhtcoeff(n, dln, mu, offset, bias, false);
127    let mut out = fhtq(&biased, &u, false)?;
128    if bias != 0.0 {
129        for (j, v) in out.iter_mut().enumerate() {
130            *v *= (-bias * ((j as f64 - jc) * dln + offset)).exp();
131        }
132    }
133    Ok(out)
134}
135// ANCHOR_END: fht
136
137/// The inverse fast Hankel transform (SciPy's `ifht`), undoing [`fht`] with the same parameters.
138pub fn ifht(big_a: &[f64], dln: f64, mu: f64, offset: f64, bias: f64) -> Result<Vec<f64>, ErrorsJSL> {
139    let n = big_a.len();
140    if n == 0 || dln.is_nan() || dln <= 0.0 {
141        return Err(ErrorsJSL::InvalidInputRange("ifht: need a non-empty input and dln > 0"));
142    }
143    let jc = (n as f64 - 1.0) / 2.0;
144    let biased: Vec<f64> = if bias != 0.0 { big_a.iter().enumerate().map(|(j, &v)| v * (bias * ((j as f64 - jc) * dln + offset)).exp()).collect() } else { big_a.to_vec() };
145    let u = fhtcoeff(n, dln, mu, offset, bias, true);
146    let mut out = fhtq(&biased, &u, true)?;
147    if bias != 0.0 {
148        for (j, v) in out.iter_mut().enumerate() {
149            *v /= (-bias * (j as f64 - jc) * dln).exp();
150        }
151    }
152    Ok(out)
153}
154
155/// The offset closest to `initial` that satisfies Hamilton's low-ringing condition for the given
156/// spacing, order and bias (SciPy's `fhtoffset`).
157pub fn fhtoffset(dln: f64, mu: f64, initial: f64, bias: f64) -> f64 {
158    let (lnkr, q) = (initial, bias);
159    let xp = (mu + 1.0 + q) / 2.0;
160    let xm = (mu + 1.0 - q) / 2.0;
161    let y = std::f64::consts::PI / (2.0 * dln);
162    let zp = ln_gamma_complex(C64::new(xp, y));
163    let zm = ln_gamma_complex(C64::new(xm, y));
164    let arg = (LN_2 - lnkr) / dln + (zp.im + zm.im) / std::f64::consts::PI;
165    lnkr + (arg - arg.round_ties_even()) * dln
166}
167
168// ANCHOR: hfft
169/// The FFT of a signal with Hermitian symmetry, given by its first half (SciPy's `hfft`): a real
170/// spectrum of length `n` (default `2(m − 1)` for `m` inputs), `n · irfft(conj(x), n)`.
171pub fn hfft(x: &[C64], n: Option<usize>) -> Result<Vec<f64>, ErrorsJSL> {
172    let n = n.unwrap_or(2 * x.len().saturating_sub(1));
173    if n == 0 {
174        return Err(ErrorsJSL::InvalidInputRange("hfft: the output length must be positive"));
175    }
176    let m = n / 2 + 1;
177    let mut c: Vec<C64> = x.iter().take(m).map(|v| v.conj()).collect();
178    c.resize(m, C64::new(0.0, 0.0));
179    Ok(irfft(&c, n)?.into_iter().map(|v| v * n as f64).collect())
180}
181
182/// The inverse of [`hfft`] (SciPy's `ihfft`): the first `n/2 + 1` bins of the Hermitian signal
183/// whose FFT is the real `x`, `conj(rfft(x))/n`.
184pub fn ihfft(x: &[f64]) -> Result<Vec<C64>, ErrorsJSL> {
185    let n = x.len();
186    if n == 0 {
187        return Err(ErrorsJSL::InvalidInputRange("ihfft: empty input"));
188    }
189    Ok(rfft(x)?.into_iter().map(|v| v.conj() / n as f64).collect())
190}
191// ANCHOR_END: hfft
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    #[test]
198    fn hankel_transform_of_a_gaussian_and_round_trips() {
199        // ∫ r e^{−r²/2} J₀(kr) dr = e^{−k²/2}: with a(r) = r e^{−r²/2}, A(k) = k e^{−k²/2}.
200        let n = 128;
201        let dln = 0.1;
202        let jc = (n as f64 - 1.0) / 2.0;
203        let r: Vec<f64> = (0..n).map(|j| ((j as f64 - jc) * dln).exp()).collect();
204        let a: Vec<f64> = r.iter().map(|&x| x * (-x * x / 2.0).exp()).collect();
205        let offset = fhtoffset(dln, 0.0, 0.0, 0.0);
206        let big = fht(&a, dln, 0.0, offset, 0.0).unwrap();
207        // SciPy's values (the low-k entries show FFTLog's aliasing, not k e^{−k²/2}).
208        assert!((offset - 0.047483887457456575).abs() < 1e-15);
209        for (j, want) in [(0, 0.001048823960070111), (10, 0.00441039992322376), (30, 0.03656836034489455), (64, 0.600405791157053), (100, 5.5817333906249544e-05)] {
210            assert!((big[j] - want).abs() < 1e-12 * want.abs().max(1e-3), "{j}: {} vs {want}", big[j]);
211        }
212        let k64 = offset.exp() * ((64.0 - jc) * dln).exp();
213        assert!((big[64] - k64 * (-k64 * k64 / 2.0).exp()).abs() < 1e-3);
214        let back = ifht(&big, dln, 0.0, offset, 0.0).unwrap();
215        assert!(back.iter().zip(&a).all(|(x, y)| (x - y).abs() < 1e-10));
216        // Γ(1/2) = √π, Γ(5) = 24, Γ(1 + i) known value.
217        assert!((ln_gamma_complex(C64::new(0.5, 0.0)).re - std::f64::consts::PI.sqrt().ln()).abs() < 1e-14);
218        assert!((ln_gamma_complex(C64::new(5.0, 0.0)).re - 24f64.ln()).abs() < 1e-14);
219        let g = ln_gamma_complex(C64::new(1.0, 1.0)).exp();
220        assert!((g - C64::new(0.498015668118356, -0.154949828301811)).norm() < 1e-13);
221        // hfft and ihfft invert each other.
222        let x: Vec<f64> = (0..10).map(|i| (i as f64 * 0.7).sin() + 0.1 * i as f64).collect();
223        let h = ihfft(&x).unwrap();
224        let y = hfft(&h, Some(10)).unwrap();
225        assert!(x.iter().zip(&y).all(|(p, q)| (p - q).abs() < 1e-13));
226    }
227}