Skip to main content

lib_jsl_dsp/discrete/spectral/
stft.rs

1//! The short-time Fourier transform, its inverse and the spectrogram.
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#the-short-time-fourier-transform-and-the-spectrogram).
4
5use super::welch::SpectralScaling;
6use lib_jsl_core::ErrorsJSL;
7use lib_jsl_ffts::RealFft;
8use ndarray::Array2;
9use num_complex::Complex;
10
11/// The one-sided STFT of a real signal: row `t` holds the spectrum (`window.len()/2 + 1` bins)
12/// of the frame starting at sample `t · hop`, windowed by `window`. Frames run while they fit
13/// entirely inside the signal (pad the signal first to cover its edges).
14pub fn stft(x: &[f64], window: &[f64], hop: usize) -> Result<Array2<Complex<f64>>, ErrorsJSL> {
15    let m = window.len();
16    if m == 0 || hop == 0 || hop > m {
17        return Err(ErrorsJSL::InvalidInputRange("Need a non-empty window and 0 < hop <= window length."));
18    }
19    if x.len() < m {
20        return Err(ErrorsJSL::InvalidInputRange("The signal is shorter than one frame."));
21    }
22    let frames = (x.len() - m) / hop + 1;
23    let mut fft = RealFft::new(m)?;
24    let mut out = Array2::zeros((frames, fft.spectrum_len()));
25    let mut frame = vec![0.0; m];
26    for t in 0..frames {
27        frame.iter_mut().zip(&x[t * hop..t * hop + m]).zip(window).for_each(|((f, v), w)| *f = v * w);
28        let spectrum = fft.forward(&frame)?;
29        out.row_mut(t).iter_mut().zip(spectrum).for_each(|(o, s)| *o = s);
30    }
31    Ok(out)
32}
33
34/// Inverts [`stft`] by weighted overlap-add, `x[n] = Σ_t w[n − t·hop] y_t[n − t·hop] / Σ_t w²`,
35/// the least-squares signal for possibly modified frames (Griffin and Lim). Exact for an
36/// unmodified STFT wherever `Σ w² > 0`; samples not covered by any frame are zero.
37pub fn istft(frames: &Array2<Complex<f64>>, window: &[f64], hop: usize) -> Result<Vec<f64>, ErrorsJSL> {
38    let m = window.len();
39    if m == 0 || hop == 0 || frames.ncols() != m / 2 + 1 {
40        return Err(ErrorsJSL::InvalidInputRange("The frames do not match the window."));
41    }
42    let count = frames.nrows();
43    let length = if count == 0 { 0 } else { (count - 1) * hop + m };
44    let mut fft = RealFft::new(m)?;
45    let mut x = vec![0.0; length];
46    let mut weight = vec![0.0; length];
47    for t in 0..count {
48        let frame = fft.inverse(&frames.row(t).to_vec())?;
49        for i in 0..m {
50            x[t * hop + i] += window[i] * frame[i];
51            weight[t * hop + i] += window[i] * window[i];
52        }
53    }
54    x.iter_mut().zip(&weight).for_each(|(v, w)| if *w > 1e-12 { *v /= w } else { *v = 0.0 });
55    Ok(x)
56}
57
58/// A spectrogram: per-frame one-sided power with Welch's scaling, and the frame times and bin
59/// frequencies.
60#[derive(Debug, Clone)]
61pub struct Spectrogram {
62    /// `power[[t, k]]`.
63    pub power: Array2<f64>,
64    /// Centre time of each frame (seconds).
65    pub times: Vec<f64>,
66    pub frequencies: Vec<f64>,
67}
68
69/// The spectrogram `|STFT|²` of `x` sampled at `fs`, scaled as a density or spectrum like
70/// [`super::welch::welch`] (each row is a single-segment periodogram).
71pub fn spectrogram(x: &[f64], fs: f64, window: &[f64], hop: usize, scaling: SpectralScaling) -> Result<Spectrogram, ErrorsJSL> {
72    let s = stft(x, window, hop)?;
73    let m = window.len();
74    let scale = match scaling {
75        SpectralScaling::Density => 1.0 / (fs * window.iter().map(|w| w * w).sum::<f64>()),
76        SpectralScaling::Spectrum => 1.0 / window.iter().sum::<f64>().powi(2),
77    };
78    let bins = s.ncols();
79    let last_doubled = if m.is_multiple_of(2) { bins - 1 } else { bins };
80    let power = Array2::from_shape_fn(s.dim(), |(t, k)| s[[t, k]].norm_sqr() * scale * if k > 0 && k < last_doubled { 2.0 } else { 1.0 });
81    let times = (0..s.nrows()).map(|t| (t * hop) as f64 / fs + (m as f64 / 2.0) / fs).collect();
82    let frequencies = (0..bins).map(|k| k as f64 * fs / m as f64).collect();
83    Ok(Spectrogram { power, times, frequencies })
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use crate::discrete::windows::{WindowType, generate_window};
90    use std::f64::consts::TAU;
91
92    #[test]
93    fn istft_reconstructs_the_signal() {
94        let x: Vec<f64> = (0..2000).map(|i| (0.013 * i as f64).sin() + 0.3 * (0.21 * i as f64).cos() + ((i * 7) % 11) as f64 * 0.01).collect();
95        // Hann windows overlapped, and a boxcar without overlap (Hann would leave the frame
96        // starts, where w = 0, unrecoverable).
97        for (m, hop, kind) in [(256, 64, WindowType::Hann), (255, 100, WindowType::Hann), (64, 64, WindowType::Boxcar)] {
98            let w = generate_window(kind, m, false);
99            let s = stft(&x, &w, hop).unwrap();
100            let y = istft(&s, &w, hop).unwrap();
101            // Every interior sample (with non-zero window weight) is recovered.
102            let worst = (m..y.len() - m).map(|i| (y[i] - x[i]).abs()).fold(0.0, f64::max);
103            assert!(worst < 1e-12, "m={m} hop={hop}: {worst}");
104        }
105    }
106
107    #[test]
108    fn spectrogram_tracks_a_linear_chirp() {
109        let fs = 8000.0;
110        let n = 16000;
111        // Instantaneous frequency 500 + 1000 t Hz over two seconds.
112        let x: Vec<f64> = (0..n).map(|i| { let t = i as f64 / fs; (TAU * (500.0 * t + 500.0 * t * t)).cos() }).collect();
113        let w = generate_window(WindowType::Hann, 512, false);
114        let sg = spectrogram(&x, fs, &w, 128, SpectralScaling::Spectrum).unwrap();
115        for (t, &time) in sg.times.iter().enumerate().step_by(10) {
116            let row = sg.power.row(t);
117            let peak = (0..row.len()).max_by(|&i, &j| row[i].total_cmp(&row[j])).unwrap();
118            let expected = 500.0 + 1000.0 * time;
119            assert!((sg.frequencies[peak] - expected).abs() < 2.0 * fs / 512.0, "t={time}: {} vs {expected}", sg.frequencies[peak]);
120        }
121        assert!(stft(&x, &w, 0).is_err() && stft(&x[..10], &w, 1).is_err());
122    }
123}