Skip to main content

lib_jsl_dsp/discrete/
signal_tools.rs

1//! Signal-processing utilities following `scipy.signal`: filter analysis ([`group_delay`],
2//! [`minimum_phase`]), least-squares FIR design ([`firls`]), rate changes ([`decimate`] and the
3//! FFT [`resample`]), [`medfilt`], the amplitude [`envelope`], and cross-spectral analysis
4//! ([`csd`], [`coherence`]).
5//!
6//! See the book entry [Signal-processing utilities](https://jwkunz.github.io/lib_jsl/book/spectral/signal-tools.html).
7
8use crate::discrete::filters::iir::chebyshev1::cheby1;
9use crate::discrete::filters::iir::butterworth::{ButterOutput, ButterOutputType};
10use crate::discrete::filters::iir::sos::{sosfilt, zpk2sos};
11use crate::discrete::filters::iir::zero_phase::{Padding, sosfiltfilt};
12use crate::discrete::spectral::hilbert::analytic_signal;
13use crate::discrete::spectral::welch::{Detrend, SpectralScaling, detrend_in_place};
14use crate::continuous::filter::design::IirFilterBandType;
15use lib_jsl_core::ErrorsJSL;
16use lib_jsl_ffts::{Fft, FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
17use lib_jsl_linalg::Solve;
18use ndarray::{Array1, Array2};
19use num_complex::Complex;
20use std::f64::consts::PI;
21
22type C = Complex<f64>;
23
24fn fft(x: &[C], inverse: bool) -> Result<Vec<C>, ErrorsJSL> {
25    let (scale, dir) = if inverse { (FftScaleFactor::N, FftDirection::Inverse) } else { (FftScaleFactor::None, FftDirection::Forward) };
26    Fft::with_plan(x.len(), scale, dir, FftOrdering::Standard)?.execute(x)
27}
28
29fn fft_real(x: &[f64], n: usize) -> Result<Vec<C>, ErrorsJSL> {
30    let mut buf: Vec<C> = x.iter().map(|&v| C::new(v, 0.0)).collect();
31    buf.resize(n, C::new(0.0, 0.0));
32    fft(&buf, false)
33}
34
35// ANCHOR: group_delay
36/// The group delay `−dφ/dω` of the filter `b(z)/a(z)` in samples at the normalised angular
37/// frequencies `w` (radians per sample) (SciPy's `group_delay`). With `c = b ∗ reverse(conj(a))`,
38/// `τ(ω) = Re(Σ k cₖ e^{−iωk} / Σ cₖ e^{−iωk}) − (len(a) − 1)`; at frequencies where the
39/// denominator vanishes the delay is set to 0, as in SciPy.
40pub fn group_delay(b: &[f64], a: &[f64], w: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
41    if b.is_empty() || a.is_empty() {
42        return Err(ErrorsJSL::InvalidInputRange("b and a must be non-empty"));
43    }
44    let mut c = vec![0.0; b.len() + a.len() - 1];
45    for (i, bi) in b.iter().enumerate() {
46        for (j, aj) in a.iter().rev().enumerate() {
47            c[i + j] += bi * aj;
48        }
49    }
50    Ok(w
51        .iter()
52        .map(|&wk| {
53            let z = C::from_polar(1.0, -wk);
54            let (mut num, mut den, mut zk) = (C::new(0.0, 0.0), C::new(0.0, 0.0), C::new(1.0, 0.0));
55            for (k, ck) in c.iter().enumerate() {
56                num += zk * ck * k as f64;
57                den += zk * ck;
58                zk *= z;
59            }
60            if den.norm() < 10.0 * f64::EPSILON * c.iter().map(|v| v.abs()).sum::<f64>() { 0.0 } else { (num / den).re - (a.len() as f64 - 1.0) }
61        })
62        .collect())
63}
64// ANCHOR_END: group_delay
65
66// ANCHOR: minimum_phase
67/// A minimum-phase FIR filter from a linear-phase one by the homomorphic method (SciPy's
68/// `minimum_phase(h, 'homomorphic')`): the real cepstrum of `|H|` (or of `|H|^{1/2}` with
69/// `half`, which preserves the magnitude of a filter that is the square of a minimum-phase one),
70/// folded onto positive quefrencies and exponentiated back. Returns `len(h)/2 + len(h) mod 2`
71/// coefficients with `half`, otherwise `len(h)`.
72pub fn minimum_phase(h: &[f64], half: bool, n_fft: Option<usize>) -> Result<Vec<f64>, ErrorsJSL> {
73    let n = h.len();
74    if n <= 2 {
75        return Err(ErrorsJSL::InvalidInputRange("h must have more than two taps"));
76    }
77    let n_fft = n_fft.unwrap_or(1 << (2.0 * (n - 1) as f64 / 0.01).log2().ceil() as u32);
78    if n_fft < n {
79        return Err(ErrorsJSL::InvalidInputRange("n_fft must be at least len(h)"));
80    }
81    let spectrum = fft_real(h, n_fft)?;
82    let mut mag: Vec<f64> = spectrum.iter().map(|z| z.norm()).collect();
83    let min_pos = mag.iter().copied().filter(|&v| v > 0.0).fold(f64::INFINITY, f64::min);
84    mag.iter_mut().for_each(|v| *v += 1e-7 * min_pos);
85    let mut logmag: Vec<C> = mag.iter().map(|v| C::new(v.ln() * if half { 0.5 } else { 1.0 }, 0.0)).collect();
86    // Real cepstrum, folded: c₀, 2c₁, …, 2c_{N/2−1}, (c_{N/2}), 0, ….
87    logmag = fft(&logmag, true)?;
88    let stop = n_fft / 2;
89    for (k, v) in logmag.iter_mut().enumerate() {
90        let w = if k == 0 {
91            1.0
92        } else if k < stop {
93            2.0
94        } else if k == stop && !n_fft.is_multiple_of(2) {
95            1.0
96        } else {
97            0.0
98        };
99        *v = C::new(v.re * w, 0.0);
100    }
101    let exp: Vec<C> = fft(&logmag, false)?.iter().map(|z| z.exp()).collect();
102    let hmin = fft(&exp, true)?;
103    let n_out = if half { n / 2 + n % 2 } else { n };
104    Ok(hmin[..n_out].iter().map(|z| z.re).collect())
105}
106// ANCHOR_END: minimum_phase
107
108// ANCHOR: firls
109/// A linear-phase FIR filter of odd length `numtaps` minimising the weighted integrated squared
110/// error to a piecewise-linear desired response (SciPy's `firls`). `bands` holds band edges in
111/// pairs and `desired` the gains at those edges, as fractions of the Nyquist frequency when `fs`
112/// is `None`.
113///
114/// For the cosine series `A(ω) = Σ aₙ cos(nω)`, the normal equations `Q a = b` have
115/// `Q = T + H` (a Toeplitz plus a Hankel matrix of integrals of `cos(nω)` over the bands) and `b`
116/// the integrals of the desired response times `cos(nω)`, all in closed form.
117pub fn firls(numtaps: usize, bands: &[f64], desired: &[f64], weight: Option<&[f64]>, fs: Option<f64>) -> Result<Vec<f64>, ErrorsJSL> {
118    if numtaps.is_multiple_of(2) || numtaps < 1 {
119        return Err(ErrorsJSL::InvalidInputRange("numtaps must be odd"));
120    }
121    if !bands.len().is_multiple_of(2) || bands.len() != desired.len() {
122        return Err(ErrorsJSL::InvalidInputRange("bands and desired need one value per band edge"));
123    }
124    let nyq = 0.5 * fs.unwrap_or(2.0);
125    let f: Vec<f64> = bands.iter().map(|v| v / nyq).collect();
126    if f.iter().any(|v| !(0.0..=1.0).contains(v)) || f.windows(2).any(|w| w[1] < w[0]) {
127        return Err(ErrorsJSL::InvalidInputRange("band edges must be increasing within [0, Nyquist]"));
128    }
129    let nb = f.len() / 2;
130    let ones = vec![1.0; nb];
131    let wts = weight.unwrap_or(&ones);
132    if wts.len() != nb {
133        return Err(ErrorsJSL::IncompatibleArraySizes((wts.len(), nb)));
134    }
135    let m = (numtaps - 1) / 2;
136    let sinc = |x: f64| if x == 0.0 { 1.0 } else { (PI * x).sin() / (PI * x) };
137    // q[n] = Σ_bands w (f₂ sinc(f₂ n) − f₁ sinc(f₁ n)).
138    let q: Vec<f64> = (0..numtaps).map(|n| (0..nb).map(|i| wts[i] * (f[2 * i + 1] * sinc(f[2 * i + 1] * n as f64) - f[2 * i] * sinc(f[2 * i] * n as f64))).sum()).collect();
139    let qm = Array2::from_shape_fn((m + 1, m + 1), |(i, j)| q[i.abs_diff(j)] + q[i + j]);
140    let mut b = vec![0.0; m + 1];
141    for i in 0..nb {
142        let (f1, f2) = (f[2 * i], f[2 * i + 1]);
143        let (d1, d2) = (desired[2 * i], desired[2 * i + 1]);
144        let slope = (d2 - d1) / (f2 - f1);
145        let c = d1 - f1 * slope;
146        for (n, bn) in b.iter_mut().enumerate() {
147            let nf = n as f64;
148            let term = |fe: f64| {
149                let mut t = fe * (slope * fe + c) * sinc(fe * nf);
150                if n == 0 {
151                    t -= slope * fe * fe / 2.0;
152                } else {
153                    t += slope * (nf * PI * fe).cos() / (PI * nf).powi(2);
154                }
155                t
156            };
157            *bn += wts[i] * (term(f2) - term(f1));
158        }
159    }
160    let a = qm.solve(&Array1::from(b)).map_err(|_| ErrorsJSL::RuntimeError("firls: the normal equations are singular"))?;
161    let mut h = Vec::with_capacity(numtaps);
162    h.extend(a.iter().skip(1).rev());
163    h.push(2.0 * a[0]);
164    h.extend(a.iter().skip(1));
165    Ok(h)
166}
167// ANCHOR_END: firls
168
169// ANCHOR: decimate
170/// Downsampling by an integer factor `q` after anti-alias filtering (SciPy's `decimate` with
171/// `ftype='iir'`): an order-8 Chebyshev type I lowpass with 0.05 dB ripple and cutoff `0.8/q` of
172/// Nyquist, applied forwards and backwards (`zero_phase`) or forwards only, then every `q`-th
173/// sample.
174pub fn decimate(x: &[f64], q: usize, zero_phase: bool) -> Result<Vec<f64>, ErrorsJSL> {
175    if q < 1 {
176        return Err(ErrorsJSL::InvalidInputRange("the factor must be at least 1"));
177    }
178    let ButterOutput::Zpk(z) = cheby1(8, 0.05, &[0.8 / q as f64], IirFilterBandType::Lowpass, Some(ButterOutputType::Zpk), None)? else {
179        return Err(ErrorsJSL::RuntimeError("cheby1 did not return zeros, poles and gain"));
180    };
181    let sos = zpk2sos(z.z.as_slice().unwrap_or(&[]), z.p.as_slice().unwrap_or(&[]), z.k.re)?;
182    let y = if zero_phase { sosfiltfilt(&sos, x, Padding::Odd, None)? } else { sosfilt(&sos, x, None)?.0 };
183    Ok(y.into_iter().step_by(q).collect())
184}
185// ANCHOR_END: decimate
186
187/// Resamples the real signal `x` to `num` samples by the FFT (SciPy's `resample`): the spectrum is
188/// truncated or zero-padded, with the unpaired Nyquist bin of an even length united when
189/// downsampling and split when upsampling. Exact for band-limited periodic signals.
190pub fn resample(x: &[f64], num: usize) -> Result<Vec<f64>, ErrorsJSL> {
191    let nx = x.len();
192    if nx == 0 || num == 0 {
193        return Err(ErrorsJSL::InvalidInputRange("lengths must be positive"));
194    }
195    let spectrum = fft_real(x, nx)?;
196    let m = num.min(nx);
197    let m2 = m / 2 + 1;
198    // The half spectrum of the output, as irfft(X[:m2], n=num) reads it.
199    let mut half = vec![C::new(0.0, 0.0); num / 2 + 1];
200    half[..m2.min(num / 2 + 1)].copy_from_slice(&spectrum[..m2.min(num / 2 + 1)]);
201    if m.is_multiple_of(2) && num != nx {
202        half[m / 2] *= if num < nx { 2.0 } else { 0.5 };
203    }
204    // Hermitian completion: real DC (and real Nyquist bin for even num).
205    let mut y = vec![C::new(0.0, 0.0); num];
206    y[0] = C::new(half[0].re, 0.0);
207    for k in 1..num.div_ceil(2) {
208        y[k] = half[k];
209        y[num - k] = half[k].conj();
210    }
211    if num.is_multiple_of(2) {
212        y[num / 2] = C::new(half[num / 2].re, 0.0);
213    }
214    let scale = num as f64 / nx as f64;
215    Ok(fft(&y, true)?.iter().map(|z| z.re * scale).collect())
216}
217
218/// A median filter with an odd `kernel_size`, the signal extended by zeros (SciPy's `medfilt`).
219pub fn medfilt(x: &[f64], kernel_size: usize) -> Result<Vec<f64>, ErrorsJSL> {
220    if kernel_size.is_multiple_of(2) {
221        return Err(ErrorsJSL::InvalidInputRange("the kernel size must be odd"));
222    }
223    let h = kernel_size / 2;
224    let n = x.len() as isize;
225    let mut window = vec![0.0; kernel_size];
226    Ok((0..n)
227        .map(|i| {
228            for (k, w) in window.iter_mut().enumerate() {
229                let j = i + k as isize - h as isize;
230                *w = if j < 0 || j >= n { 0.0 } else { x[j as usize] };
231            }
232            window.sort_by(f64::total_cmp);
233            window[h]
234        })
235        .collect())
236}
237
238/// The amplitude envelope `|x + i H{x}|`, the magnitude of the analytic signal (equal to SciPy's
239/// `abs(hilbert(x))`).
240pub fn envelope(x: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
241    Ok(analytic_signal(x)?.iter().map(|z| z.norm()).collect())
242}
243
244/// A one-sided cross spectral density estimate.
245#[derive(Clone, Debug)]
246pub struct CrossSpectrum {
247    pub frequencies: Vec<f64>,
248    pub values: Vec<C>,
249    pub segments: usize,
250}
251
252// ANCHOR: csd
253/// The cross spectral density `P_xy(f)` by Welch's method (SciPy's `csd`): segments of
254/// `window.len()` samples overlapping by `overlap`, detrended and windowed; the average of
255/// `conj(X) Y`, scaled as [`welch`](crate::discrete::spectral::welch::welch) and doubled except at
256/// DC and an even-length Nyquist bin.
257pub fn csd(x: &[f64], y: &[f64], fs: f64, window: &[f64], overlap: usize, detrend: Detrend, scaling: SpectralScaling) -> Result<CrossSpectrum, ErrorsJSL> {
258    let m = window.len();
259    if x.len() != y.len() {
260        return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), y.len())));
261    }
262    if m == 0 || overlap >= m || x.len() < m || !(fs > 0.0) {
263        return Err(ErrorsJSL::InvalidInputRange("need a positive rate and a window longer than the overlap and shorter than the signal"));
264    }
265    let step = m - overlap;
266    let segments = (x.len() - m) / step + 1;
267    let bins = m / 2 + 1;
268    let mut acc = vec![C::new(0.0, 0.0); bins];
269    let (mut sx, mut sy) = (vec![0.0; m], vec![0.0; m]);
270    for s in 0..segments {
271        sx.copy_from_slice(&x[s * step..s * step + m]);
272        sy.copy_from_slice(&y[s * step..s * step + m]);
273        detrend_in_place(&mut sx, detrend);
274        detrend_in_place(&mut sy, detrend);
275        sx.iter_mut().zip(window).for_each(|(v, w)| *v *= w);
276        sy.iter_mut().zip(window).for_each(|(v, w)| *v *= w);
277        let (fx, fy) = (fft_real(&sx, m)?, fft_real(&sy, m)?);
278        for k in 0..bins {
279            acc[k] += fx[k].conj() * fy[k];
280        }
281    }
282    let scale = match scaling {
283        SpectralScaling::Density => 1.0 / (fs * window.iter().map(|w| w * w).sum::<f64>()),
284        SpectralScaling::Spectrum => 1.0 / window.iter().sum::<f64>().powi(2),
285    } / segments as f64;
286    let last_doubled = if m.is_multiple_of(2) { bins - 1 } else { bins };
287    for (k, v) in acc.iter_mut().enumerate() {
288        *v *= scale * if k > 0 && k < last_doubled { 2.0 } else { 1.0 };
289    }
290    Ok(CrossSpectrum { frequencies: (0..bins).map(|k| k as f64 * fs / m as f64).collect(), values: acc, segments })
291}
292
293/// The magnitude-squared coherence `|P_xy|² / (P_xx P_yy)` (SciPy's `coherence`): 1 where `y` is
294/// a noise-free linear filtering of `x`, near 0 where they are unrelated.
295pub fn coherence(x: &[f64], y: &[f64], fs: f64, window: &[f64], overlap: usize, detrend: Detrend) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
296    let pxy = csd(x, y, fs, window, overlap, detrend, SpectralScaling::Density)?;
297    let pxx = csd(x, x, fs, window, overlap, detrend, SpectralScaling::Density)?;
298    let pyy = csd(y, y, fs, window, overlap, detrend, SpectralScaling::Density)?;
299    let c = (0..pxy.values.len()).map(|k| pxy.values[k].norm_sqr() / (pxx.values[k].re * pyy.values[k].re)).collect();
300    Ok((pxy.frequencies, c))
301}
302// ANCHOR_END: csd
303
304// ANCHOR: zoom_fft
305/// The DFT of `x` at `m` equally spaced frequencies from `f1` towards `f2` (SciPy's `zoom_fft`,
306/// with the sample rate `fs`): the chirp z-transform on an arc of the unit circle starting at
307/// `a = e^{2πi f1/fs}` with ratio `w = e^{−2πi (f2 − f1)/(fs m)}` (`(m − 1)` in place of `m` with
308/// `endpoint`), computed by Bluestein's algorithm in `O((n + m) log(n + m))`.
309pub fn zoom_fft(x: &[f64], f1: f64, f2: f64, m: usize, fs: f64, endpoint: bool) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
310    if m == 0 || x.is_empty() {
311        return Err(ErrorsJSL::InvalidInputRange("need a non-empty signal and m ≥ 1"));
312    }
313    let scale = if endpoint && m > 1 { (f2 - f1) * m as f64 / (fs * (m - 1) as f64) } else { (f2 - f1) / fs };
314    let a = Complex::from_polar(1.0, 2.0 * PI * f1 / fs);
315    let w = Complex::from_polar(1.0, -2.0 * PI * scale / m as f64);
316    Ok(crate::discrete::spectral::chirpz::chirpz(x, Some(m), Some(w), Some(a))?.to_vec())
317}
318// ANCHOR_END: zoom_fft
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323
324    #[test]
325    fn group_delay_of_a_pure_delay_and_a_symmetric_fir() {
326        let w: Vec<f64> = (0..10).map(|i| 0.1 + i as f64 * 0.25).collect();
327        let gd = group_delay(&[0.0, 0.0, 0.0, 1.0], &[1.0], &w).unwrap();
328        assert!(gd.iter().all(|g| (g - 3.0).abs() < 1e-12));
329        let gd = group_delay(&[0.2, 0.5, 1.0, 0.5, 0.2], &[1.0], &w).unwrap();
330        assert!(gd.iter().all(|g| (g - 2.0).abs() < 1e-9), "{gd:?}");
331    }
332
333    #[test]
334    fn resample_is_exact_for_band_limited_signals() {
335        let n = 32;
336        let x: Vec<f64> = (0..n).map(|i| (2.0 * PI * 3.0 * i as f64 / n as f64).sin()).collect();
337        for num in [20, 48, 64] {
338            let y = resample(&x, num).unwrap();
339            for (i, v) in y.iter().enumerate() {
340                assert!((v - (2.0 * PI * 3.0 * i as f64 / num as f64).sin()).abs() < 1e-12, "num = {num}");
341            }
342        }
343    }
344
345    #[test]
346    fn firls_lowpass_is_symmetric_and_matches_scipy_at_dc() {
347        let h = firls(31, &[0.0, 0.3, 0.4, 1.0], &[1.0, 1.0, 0.0, 0.0], None, None).unwrap();
348        assert_eq!(h.len(), 31);
349        assert!((0..15).all(|i| (h[i] - h[30 - i]).abs() < 1e-15));
350        // SciPy: Σh = 1.0033195062747546 (the passband ripple at DC).
351        assert!((h.iter().sum::<f64>() - 1.0033195062747546).abs() < 1e-12);
352    }
353}