lib_jsl_dsp/discrete/windows/
kaiser.rs1use super::{extend, len_guard, truncate};
2
3pub(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
28pub 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
45pub 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
57pub 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
64pub 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 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}