Skip to main content

lib_jsl_dsp/discrete/
windows.rs

1//! This module implements various window functions commonly used in signal processing applications. 
2//! Window functions are used to mitigate spectral leakage when performing Fourier analysis on finite-length signals, by tapering the edges of the signal to reduce discontinuities.
3//! The module includes implementations of standard window functions such as Hanning, Hamming, Blackman, and Kaiser windows, as well as more general functions that allow for custom parameters and shapes.
4//!
5//! See the book entry [Window functions](https://jwkunz.github.io/lib_jsl/book/spectral/windows.html).
6
7pub mod boxcar;
8pub mod triang;
9pub mod parzen;
10pub mod bohman;
11pub mod general_cosine;
12pub mod blackman;
13pub mod nuttall;
14pub mod blackmanharris;
15pub mod flattop;
16pub mod bartlett;
17pub mod barthann;
18pub mod hamming;
19pub mod hann;
20pub mod kaiser;
21pub mod kaiser_bessel_derived;
22pub mod gaussian;
23pub mod general_gaussian;
24pub mod chebwin;
25pub mod cosine;
26pub mod exponential;
27pub mod tukey;
28pub mod taylor;
29pub mod dpss;
30pub mod lanczos;
31
32pub use boxcar::{boxcar};
33pub use triang::{triang};
34pub use parzen::{parzen};
35pub use bohman::{bohman};
36pub use general_cosine::{general_cosine};
37pub use blackman::{blackman};
38pub use nuttall::{nuttall};
39pub use blackmanharris::{blackmanharris};
40pub use flattop::{flattop};
41pub use bartlett::{bartlett};
42pub use barthann::{barthann};
43pub use hamming::{general_hamming, hamming};
44pub use hann::{hann};
45pub use kaiser::{kaiser, kaiser_beta, kaiser_atten, kaiser_estimate_numtaps};
46pub use kaiser_bessel_derived::{kaiser_bessel_derived};
47pub use gaussian::{gaussian};
48pub use general_gaussian::{general_gaussian};
49pub use chebwin::{chebwin};
50pub use cosine::{cosine};
51pub use exponential::{exponential};
52pub use tukey::{tukey};
53pub use taylor::{taylor};
54pub use dpss::{dpss};
55pub use lanczos::{lanczos};
56
57/// These are helper functions used in the implementation of the window functions. They handle special cases for small window sizes, extend the window size for symmetric windows, and truncate the window back to the desired size if necessary.
58fn len_guard(m: usize) -> Option<Vec<f64>> {
59    if m <= 1 {
60        Some(vec![1.0; m])
61    } else {
62        None
63    }
64}
65
66fn extend(m: usize, sym: bool) -> (usize, bool) {
67    if sym {
68        (m, false)
69    } else {
70        (m + 1, true)
71    }
72}
73
74fn truncate(mut w: Vec<f64>, needed: bool) -> Vec<f64> {
75    if needed {
76        w.pop();
77    }
78    w
79}
80
81/// This function generates a linearly spaced vector of `n` points between `start` and `stop`. It is used in the implementation of various window functions to create the necessary input values for computing the window coefficients.
82fn linspace(start: f64, stop: f64, n: usize) -> Vec<f64> {
83    if n == 0 {
84        return vec![];
85    }
86    if n == 1 {
87        return vec![start];
88    }
89    let step = (stop - start) / (n - 1) as f64;
90    (0..n).map(|i| start + i as f64 * step).collect()
91}
92
93/// The `WindowType` enum defines the various types of window functions that can be generated. Each variant corresponds to a specific window function, and some variants include parameters that control the shape and spectral properties of the window. 
94/// This enum is used as an input to the `generate_window` function to specify which type of window to create based on the desired application and characteristics.
95pub enum WindowType {
96    Boxcar,
97    Triang,
98    Parzen,
99    Bohman,
100    Blackman,
101    Nuttall,
102    BlackmanHarris,
103    Flattop,
104    Bartlett,
105    Barthann,
106    Hamming,
107    Hann,
108    Kaiser { beta: f64 },
109    KaiserBesselDerived { beta: f64 },
110    Gaussian { std: f64 },
111    GeneralGaussian { p: f64, sig: f64 },
112    Chebwin { at: f64 },
113    Cosine,
114    Exponential { center: Option<f64>, tau: f64 },
115    Tukey { alpha: f64 },
116    Taylor { nbar: usize, sll: f64, norm: bool },
117    Dpss { nw: f64 },
118    Lanczos,
119}
120
121/// The following functions implement specific window types by calling the general cosine function with appropriate coefficients, or by directly computing the window coefficients based on their mathematical definitions. Each function takes the desired window length `m` and a boolean `sym` indicating whether the window should be symmetric or periodic, and returns a vector of window coefficients that can be applied to a signal for spectral analysis or other processing tasks.
122pub fn generate_window(window_type: WindowType, m: usize, sym: bool) -> Vec<f64> {
123    match window_type {
124        WindowType::Boxcar => boxcar(m, sym),
125        WindowType::Triang => triang(m, sym),
126        WindowType::Parzen => parzen(m, sym),
127        WindowType::Bohman => bohman(m, sym),
128        WindowType::Blackman => blackman(m, sym),
129        WindowType::Nuttall => nuttall(m, sym),
130        WindowType::BlackmanHarris => blackmanharris(m, sym),
131        WindowType::Flattop => flattop(m, sym),
132        WindowType::Bartlett => bartlett(m, sym),
133        WindowType::Barthann => barthann(m, sym),
134        WindowType::Hamming => hamming(m, sym),
135        WindowType::Hann => hann(m, sym),
136        WindowType::Kaiser { beta } => kaiser(m, beta, sym),
137        WindowType::KaiserBesselDerived { beta } => kaiser_bessel_derived(m, beta, sym),
138        WindowType::Gaussian { std } => gaussian(m, std, sym),
139        WindowType::GeneralGaussian { p, sig } => general_gaussian(m, p, sig, sym),
140        WindowType::Chebwin { at } => chebwin(m, at, sym),
141        WindowType::Cosine => cosine(m, sym),
142        WindowType::Exponential { center, tau } => exponential(m, center, tau, sym),
143        WindowType::Tukey { alpha } => tukey(m, alpha, sym),
144        WindowType::Taylor { nbar, sll, norm } => taylor(m, nbar, sll, norm, sym),
145        WindowType::Dpss { nw } => dpss(m, nw, sym),
146        WindowType::Lanczos => lanczos(m, sym),
147    }
148}
149
150#[cfg(test)]
151pub(crate) mod test_support {
152    fn parse_csv(csv: &str) -> Vec<f64> {
153        csv.lines()
154            .filter(|l| !l.trim().is_empty())
155            .map(|l| l.trim().parse::<f64>().unwrap())
156            .collect()
157    }
158
159    /// Compares a generated window against golden CSV contents to 1e-9.
160    pub(crate) fn assert_window(golden_csv: &str, actual: Vec<f64>) {
161        let expected = parse_csv(golden_csv);
162        assert_eq!(actual.len(), expected.len());
163        for (a, e) in actual.iter().zip(expected.iter()) {
164            assert!((a - e).abs() < 1e-9, "actual={a}, expected={e}, tol=1e-9");
165        }
166    }
167}