Skip to main content

lib_jsl_dsp/discrete/windows/
chebwin.rs

1//! The Dolph-Chebyshev window.
2//!
3//! See the book entry [Window functions](https://jwkunz.github.io/lib_jsl/book/spectral/windows.html#the-dolph-chebyshev-and-dpss-windows).
4
5use std::f64::consts::PI;
6
7use super::{extend, len_guard, truncate};
8
9/// The Dolph-Chebyshev window of length `m` with side lobes `at` dB below the main lobe.
10///
11/// Its transform is the Chebyshev polynomial `T_{m−1}(β cos(πk/m))`, with
12/// `β = cosh(acosh(10^{at/20}) / (m − 1))`, which has all side lobes at the same level and the
13/// narrowest main lobe for that level. The window is obtained from it by a DFT, centred and
14/// normalised to a peak of 1, following SciPy's `chebwin`.
15pub fn chebwin(m: usize, at: f64, sym: bool) -> Vec<f64> {
16    if let Some(w) = len_guard(m) {
17        return w;
18    }
19    let (m2, needs_trunc) = extend(m, sym);
20    let order = m2 as f64 - 1.0;
21    let beta = ((10_f64.powf(at.abs() / 20.0)).acosh() / order).cosh();
22    let p: Vec<f64> = (0..m2)
23        .map(|k| {
24            let x = beta * (PI * k as f64 / m2 as f64).cos();
25            if x > 1.0 {
26                (order * x.acosh()).cosh()
27            } else if x < -1.0 {
28                let sign = if m2 % 2 == 1 { 1.0 } else { -1.0 };
29                sign * (order * (-x).acosh()).cosh()
30            } else {
31                (order * x.acos()).cos()
32            }
33        })
34        .collect();
35    // The real part of the DFT of p (with a half-sample shift for even lengths).
36    let shift = if m2 % 2 == 1 { 0.0 } else { PI / m2 as f64 };
37    let dft = |n: usize| -> f64 {
38        p.iter().enumerate().map(|(k, &pk)| pk * (shift * k as f64 - 2.0 * PI * (k * n) as f64 / m2 as f64).cos()).sum()
39    };
40    let mut w: Vec<f64> = if m2 % 2 == 1 {
41        let half = m2.div_ceil(2);
42        let tail: Vec<f64> = (0..half).map(dft).collect();
43        tail[1..].iter().rev().chain(tail.iter()).copied().collect()
44    } else {
45        let half = m2 / 2 + 1;
46        let tail: Vec<f64> = (0..half).map(dft).collect();
47        tail[1..].iter().rev().chain(tail[1..].iter()).copied().collect()
48    };
49    let maxv = w.iter().fold(0.0_f64, |a, &b| a.max(b));
50    w.iter_mut().for_each(|v| *v /= maxv);
51    truncate(w, needs_trunc)
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use crate::discrete::windows::test_support::assert_window;
58
59    #[test]
60    fn test_chebwin() {
61        assert_window(include_str!("../test_data/chebwin.csv"), chebwin(7, 100.0, true));
62    }
63}