Skip to main content

lib_jsl_dsp/discrete/spectral/
welch.rs

1//! Power spectral density estimation by Welch's method of averaged, windowed periodograms.
2//!
3//! See the book entry [Power spectra: periodogram, Welch, spectrogram and Lomb-Scargle](https://jwkunz.github.io/lib_jsl/book/spectral/power-spectra.html#variance-welch-averaging).
4
5use lib_jsl_core::ErrorsJSL;
6use lib_jsl_ffts::RealFft;
7
8/// How to scale a power spectrum.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum SpectralScaling {
11    /// Power spectral density, units²/Hz: integrating it over frequency gives the variance.
12    Density,
13    /// Power spectrum, units²: a sinusoid of amplitude `A` centred on a bin reads `A²/2`.
14    Spectrum,
15}
16
17/// Trend removed from each segment before windowing.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum Detrend {
20    None,
21    /// Subtract the segment mean.
22    Constant,
23    /// Subtract the least-squares line.
24    Linear,
25}
26
27/// A one-sided spectrum estimate of a real signal.
28#[derive(Debug, Clone)]
29pub struct PowerSpectrum {
30    /// Bin frequencies `k · fs / segment_length`, from 0 to the Nyquist frequency.
31    pub frequencies: Vec<f64>,
32    pub power: Vec<f64>,
33    /// Number of averaged segments.
34    pub segments: usize,
35}
36
37pub(crate) fn detrend_in_place(x: &mut [f64], detrend: Detrend) {
38    let n = x.len() as f64;
39    match detrend {
40        Detrend::None => {}
41        Detrend::Constant => {
42            let mean = x.iter().sum::<f64>() / n;
43            x.iter_mut().for_each(|v| *v -= mean);
44        }
45        Detrend::Linear => {
46            let tm = (n - 1.0) / 2.0;
47            let ym = x.iter().sum::<f64>() / n;
48            let sxy: f64 = x.iter().enumerate().map(|(i, v)| (i as f64 - tm) * (v - ym)).sum();
49            let sxx: f64 = (0..x.len()).map(|i| (i as f64 - tm).powi(2)).sum();
50            let slope = if sxx > 0.0 { sxy / sxx } else { 0.0 };
51            x.iter_mut().enumerate().for_each(|(i, v)| *v -= ym + slope * (i as f64 - tm));
52        }
53    }
54}
55
56/// Welch's estimate of the one-sided spectrum of the real signal `x` sampled at `fs`: the signal
57/// is cut into segments of `window.len()` samples overlapping by `overlap` samples, each is
58/// detrended, windowed and transformed, and the squared magnitudes are averaged. Averaging
59/// trades frequency resolution (`fs / segment`) for a variance reduced roughly by the number of
60/// segments. With a single segment spanning the signal this is the (modified) periodogram.
61///
62/// Scaling follows SciPy: `1 / (fs Σw²)` for density, `1 / (Σw)²` for spectrum, with all bins
63/// except DC (and Nyquist for even lengths) doubled to fold in the negative frequencies.
64pub fn welch(x: &[f64], fs: f64, window: &[f64], overlap: usize, detrend: Detrend, scaling: SpectralScaling) -> Result<PowerSpectrum, ErrorsJSL> {
65    let m = window.len();
66    if m == 0 || overlap >= m {
67        return Err(ErrorsJSL::InvalidInputRange("The window must be non-empty and longer than the overlap."));
68    }
69    if x.len() < m {
70        return Err(ErrorsJSL::InvalidInputRange("The signal is shorter than one segment."));
71    }
72    if fs.is_nan() || fs <= 0.0 {
73        return Err(ErrorsJSL::InvalidInputRange("The sampling rate must be positive."));
74    }
75    // ANCHOR: welch
76    let step = m - overlap;
77    let segments = (x.len() - m) / step + 1;
78    let mut fft = RealFft::new(m)?;
79    let bins = fft.spectrum_len();
80    let mut power = vec![0.0; bins];
81    let mut segment = vec![0.0; m];
82    for s in 0..segments {
83        segment.copy_from_slice(&x[s * step..s * step + m]);
84        detrend_in_place(&mut segment, detrend);
85        segment.iter_mut().zip(window).for_each(|(v, w)| *v *= w);
86        let spectrum = fft.forward(&segment)?;
87        power.iter_mut().zip(&spectrum).for_each(|(p, c)| *p += c.norm_sqr());
88    }
89    let scale = match scaling {
90        SpectralScaling::Density => 1.0 / (fs * window.iter().map(|w| w * w).sum::<f64>()),
91        SpectralScaling::Spectrum => 1.0 / window.iter().sum::<f64>().powi(2),
92    } / segments as f64;
93    let last_doubled = if m.is_multiple_of(2) { bins - 1 } else { bins };
94    for (k, p) in power.iter_mut().enumerate() {
95        *p *= scale * if k > 0 && k < last_doubled { 2.0 } else { 1.0 };
96    }
97    // ANCHOR_END: welch
98    let frequencies = (0..bins).map(|k| k as f64 * fs / m as f64).collect();
99    Ok(PowerSpectrum { frequencies, power, segments })
100}
101
102/// The periodogram of `x` with the given window spanning the whole signal.
103pub fn periodogram(x: &[f64], fs: f64, window: &[f64], detrend: Detrend, scaling: SpectralScaling) -> Result<PowerSpectrum, ErrorsJSL> {
104    if window.len() != x.len() {
105        return Err(ErrorsJSL::IncompatibleArraySizes((window.len(), x.len())));
106    }
107    welch(x, fs, window, 0, detrend, scaling)
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use crate::discrete::windows::{WindowType, generate_window};
114    use lib_jsl_random::distributions::gaussian_distribution_box_muller_vec;
115    use lib_jsl_random::uniform_generator::UniformRNG;
116    use std::f64::consts::TAU;
117
118    #[test]
119    fn white_noise_density_integrates_to_the_variance() {
120        let (fs, sigma) = (1000.0, 0.7);
121        let mut x = gaussian_distribution_box_muller_vec(200_000, &mut UniformRNG::from_seed(1), 0.0, sigma);
122        x.truncate(200_000);
123        let w = generate_window(WindowType::Hann, 512, false);
124        let psd = welch(&x, fs, &w, 256, Detrend::Constant, SpectralScaling::Density).unwrap();
125        assert_eq!(psd.segments, (200_000 - 512) / 256 + 1);
126        // Flat at 2σ²/fs (one-sided) and integrating to σ².
127        let level = 2.0 * sigma * sigma / fs;
128        let interior = &psd.power[5..250];
129        let mean = interior.iter().sum::<f64>() / interior.len() as f64;
130        assert!((mean / level - 1.0).abs() < 0.02, "{mean} vs {level}");
131        let df = fs / 512.0;
132        let total: f64 = psd.power.iter().sum::<f64>() * df;
133        assert!((total / (sigma * sigma) - 1.0).abs() < 0.02, "{total}");
134        // Averaging 780 segments leaves a relative standard deviation near 1/√780 · (overlap factor).
135        let sd = (interior.iter().map(|p| (p - mean).powi(2)).sum::<f64>() / interior.len() as f64).sqrt();
136        assert!(sd / mean < 0.06, "{}", sd / mean);
137    }
138
139    #[test]
140    fn sinusoid_power_and_frequency() {
141        let (fs, n, a, k) = (256.0, 1024, 3.0, 100);
142        let f0 = k as f64 * fs / n as f64;
143        let x: Vec<f64> = (0..n).map(|i| a * (TAU * f0 * i as f64 / fs).sin() + 5.0).collect();
144        let w = generate_window(WindowType::Hann, n, false);
145        let p = periodogram(&x, fs, &w, Detrend::Constant, SpectralScaling::Spectrum).unwrap();
146        let peak = (0..p.power.len()).max_by(|&i, &j| p.power[i].total_cmp(&p.power[j])).unwrap();
147        assert_eq!(peak, k);
148        assert!((p.frequencies[peak] - f0).abs() < 1e-12);
149        assert!((p.power[peak] - a * a / 2.0).abs() < 1e-9, "{}", p.power[peak]);
150        assert!(p.power[0] < 1e-20); // the offset is removed
151        // Linear detrending removes a ramp exactly.
152        let ramp: Vec<f64> = (0..64).map(|i| 2.0 + 0.5 * i as f64).collect();
153        let r = periodogram(&ramp, 1.0, &[1.0; 64], Detrend::Linear, SpectralScaling::Spectrum).unwrap();
154        assert!(r.power.iter().all(|&v| v < 1e-20));
155        assert!(welch(&x, fs, &w[..8], 8, Detrend::None, SpectralScaling::Density).is_err());
156        assert!(welch(&x[..4], fs, &w[..8], 0, Detrend::None, SpectralScaling::Density).is_err());
157    }
158}