Skip to main content

lib_jsl_dsp/discrete/windows/
taylor.rs

1use std::f64::consts::PI;
2
3use super::{extend, len_guard, truncate};
4
5/// The Taylor window is defined by a specific mathematical formula that involves the hyperbolic cosine function and the inverse hyperbolic cosine function, as well as a set of coefficients that are computed based on the position within the window, the total length, and the parameters `nbar` and `sll`, which control the shape of the window and its spectral properties. The coefficients are computed using a specific algorithm that involves a product of terms based on the position within the window and the parameters, and then normalized to ensure that the maximum value of the window is 1.0 if `norm` is true.
6pub fn taylor(m: usize, nbar: usize, sll: f64, norm: bool, sym: bool) -> Vec<f64> {
7    if let Some(w) = len_guard(m) {
8        return w;
9    }
10    if nbar < 2 {
11        return vec![1.0; m];
12    }
13    let (m2, needs_trunc) = extend(m, sym);
14    let a = ((10_f64.powf(sll / 20.0)).acosh()) / PI;
15    let s2 = (nbar as f64).powi(2) / (a * a + (nbar as f64 - 0.5).powi(2));
16    let ma: Vec<f64> = (1..nbar).map(|x| x as f64).collect();
17    let m2v: Vec<f64> = ma.iter().map(|x| x * x).collect();
18
19    let mut fm = vec![0.0; nbar - 1];
20    for mi in 0..ma.len() {
21        let mval2 = m2v[mi];
22        let sign = if mi % 2 == 0 { 1.0 } else { -1.0 };
23        let mut numer = sign;
24        for ma_i in &ma {
25            numer *= 1.0 - mval2 / s2 / (a * a + (ma_i - 0.5).powi(2));
26        }
27        let mut denom = 2.0;
28        for &m2vj in m2v.iter().take(mi) {
29            denom *= 1.0 - mval2 / m2vj;
30        }
31        for &m2vj in m2v.iter().skip(mi + 1) {
32            denom *= 1.0 - mval2 / m2vj;
33        }
34        fm[mi] = numer / denom;
35    }
36
37    let mut w = vec![0.0; m2];
38    for (n, wn) in w.iter_mut().enumerate() {
39        let x = (n as f64) - m2 as f64 / 2.0 + 0.5;
40        let mut val = 1.0;
41        for (i, mval) in ma.iter().enumerate() {
42            val += 2.0 * fm[i] * (2.0 * PI * mval * x / m2 as f64).cos();
43        }
44        *wn = val;
45    }
46
47    if norm {
48        let x = (m2 as f64 - 1.0) / 2.0 - m2 as f64 / 2.0 + 0.5;
49        let mut wc = 1.0;
50        for (i, mval) in ma.iter().enumerate() {
51            wc += 2.0 * fm[i] * (2.0 * PI * mval * x / m2 as f64).cos();
52        }
53        if wc != 0.0 {
54            for v in &mut w {
55                *v /= wc;
56            }
57        }
58    }
59    truncate(w, needs_trunc)
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65    use crate::discrete::windows::test_support::assert_window;
66
67    #[test]
68    fn test_taylor() {
69        assert_window(include_str!("../test_data/taylor.csv"), taylor(7, 4, 30.0, true, true));
70    }
71}