Skip to main content

lib_jsl_dsp/discrete/windows/
kaiser.rs

1use super::{extend, len_guard, truncate};
2
3/// The modified Bessel function of the first kind of order zero, to full double precision: the
4/// power series `Σ (x²/4)^k / (k!)²` for `|x| < 30`, and above it the asymptotic series
5/// `eˣ / √(2πx) · Σ ((2k − 1)!!)² / (k! (8x)^k)`, whose terms shrink until `k ≈ 2x`.
6pub(crate) fn i0(x: f64) -> f64 {
7    let ax = x.abs();
8    if ax < 30.0 {
9        let q = 0.25 * ax * ax;
10        let (mut term, mut sum, mut k) = (1.0f64, 1.0f64, 0.0f64);
11        while term > 1e-17 * sum {
12            k += 1.0;
13            term *= q / (k * k);
14            sum += term;
15        }
16        sum
17    } else {
18        let (mut term, mut sum, mut k) = (1.0f64, 1.0f64, 0.0f64);
19        while term.abs() > 1e-17 * sum && k < 60.0 {
20            k += 1.0;
21            term *= (2.0 * k - 1.0).powi(2) / (k * 8.0 * ax);
22            sum += term;
23        }
24        ax.exp() / (2.0 * std::f64::consts::PI * ax).sqrt() * sum
25    }
26}
27
28/// The Kaiser window is defined by a specific mathematical formula that involves the modified Bessel function of the first kind. The coefficients are computed based on the position within the window, the total length, and the beta parameter, which controls the shape of the window and its spectral properties.
29pub fn kaiser(m: usize, beta: f64, sym: bool) -> Vec<f64> {
30    if let Some(w) = len_guard(m) {
31        return w;
32    }
33    let (m2, needs_trunc) = extend(m, sym);
34    let n: Vec<f64> = (0..m2).map(|i| i as f64).collect();
35    let alpha = (m2 as f64 - 1.0) / 2.0;
36    let i0b = i0(beta);
37    let mut w = vec![0.0; m2];
38    for (i, wn) in w.iter_mut().enumerate() {
39        let t = 1.0 - ((n[i] - alpha) / alpha).powi(2);
40        *wn = i0(beta * t.max(0.0).sqrt()) / i0b;
41    }
42    truncate(w, needs_trunc)
43}
44
45/// Kaiser's empirical `β` giving a stopband attenuation of `a` dB in a window-method FIR filter
46/// (as SciPy's `kaiser_beta`). Larger `β` lowers the side lobes and widens the main lobe.
47pub fn kaiser_beta(a: f64) -> f64 {
48    if a > 50.0 {
49        0.1102 * (a - 8.7)
50    } else if a > 21.0 {
51        0.5842 * (a - 21.0).powf(0.4) + 0.07886 * (a - 21.0)
52    } else {
53        0.0
54    }
55}
56
57/// Kaiser's estimate of the stopband attenuation in dB reached by a Kaiser-window FIR filter with
58/// `numtaps` taps and a transition `width` given as a fraction of the Nyquist frequency (as
59/// SciPy's `kaiser_atten`).
60pub fn kaiser_atten(numtaps: usize, width: f64) -> f64 {
61    2.285 * (numtaps as f64 - 1.0) * std::f64::consts::PI * width + 7.95
62}
63
64/// The number of taps Kaiser's formula predicts for an attenuation of `at` dB with a transition
65/// `width` given as a fraction of the Nyquist frequency (the inverse of [`kaiser_atten`]; the tap
66/// count of SciPy's `kaiserord`).
67pub fn kaiser_estimate_numtaps(at: f64, width: f64) -> usize {
68    ((at - 7.95) / (2.285 * std::f64::consts::PI * width)).ceil() as usize + 1
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74    use crate::discrete::windows::test_support::assert_window;
75
76    #[test]
77    fn bessel_i0_is_accurate_across_the_switch_to_the_asymptotic_series() {
78        // Values of I0 from mpmath to 17 digits.
79        for (x, want) in [(0.5, 1.0634833707413236), (6.0, 67.23440697647797), (29.9, 708478330489.0145), (30.1, 862432920031.7792), (60.0, 5.894077055609801e24)] {
80            assert!((i0(x) / want - 1.0).abs() < 4e-15, "{x}: {} against {want}", i0(x));
81        }
82    }
83
84    #[test]
85    fn test_kaiser() {
86        assert_window(include_str!("../test_data/kaiser.csv"), kaiser(7, 14.0, true));
87    }
88}