Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Signal-processing utilities

ProblemAnalyse a filter’s delay; convert a linear-phase FIR filter to minimum phase; design an FIR filter by least squares; change a sampling rate by decimation or by the FFT; remove impulsive noise; extract an amplitude envelope; and measure how two signals are related across frequency
Devised byGroup delay: Harry Nyquist and Hendrik Bode (1930s); the cepstrum: Bruce Bogert, Michael Healy and John Tukey (1963), Alan Oppenheim and Ronald Schafer (homomorphic filtering, 1968); least-squares FIR design: Thomas Parks and Sidney Burrus (1987); the median filter: John Tukey (1974); coherence: Norbert Wiener (1930), Peter Welch (1967)
AccuracyAgrees with scipy.signal to or better; group delay of high-order IIR filters to , limited by cancellation in the polynomial evaluation
Costgroup_delay: per frequency. minimum_phase, resample: a few FFTs. firls: one solve for taps. medfilt: . csd: one FFT per segment and signal
Read firstFIR filter design, Power spectra, The Hilbert transform
APIsignal_tools: group_delay, minimum_phase, firls, decimate, resample, medfilt, envelope, csd, coherence

Overview

This entry collects nine functions of scipy.signal that the earlier entries used without providing:

  • group_delay, the delay a filter imposes on each frequency;
  • minimum_phase, which turns a linear-phase FIR filter into one with the same magnitude response and far less delay;
  • firls, FIR design by least squares, the counterpart of Parks-McClellan’s minimax design;
  • decimate and resample, rate changes by filtering and downsampling, or by the FFT;
  • medfilt, the median filter for impulsive noise;
  • envelope, the amplitude of the analytic signal;
  • csd and coherence, the cross spectrum and the frequency-by-frequency correlation of two signals.

Where it is used

Small utilities that every signal-processing project needs.

  • Group delay. How much a filter delays different frequencies, which matters in audio, control loops and communications.
  • Minimum-phase conversion. Getting the lowest-latency filter with a given magnitude response, as in real-time audio equalisation.
  • Least-squares FIR design. Fitting a filter to an arbitrary frequency response measured from a loudspeaker or a channel.

History

Harry Nyquist and Hendrik Bode related the phase of a feedback amplifier to its delay and its stability in the 1930s, and group delay became the standard measure of phase distortion. Bruce Bogert, Michael Healy and John Tukey (1963) defined the cepstrum, the spectrum of the logarithm of a spectrum, to detect echoes in seismograms. Alan Oppenheim and Ronald Schafer (1968) built homomorphic signal processing on it, including the construction of minimum-phase sequences. Least-squares FIR design goes back to the earliest digital filters and was put in its standard form by Thomas Parks and Sidney Burrus (1987). John Tukey introduced the running median for robust smoothing (1974). Norbert Wiener’s generalised harmonic analysis (1930) defined the cross spectrum, and Peter Welch’s averaged periodograms (1967) made it practical to estimate.

The idea

Group delay and minimum phase

A filter with frequency response delays a narrowband signal at frequency by the group delay samples. For the derivative has a closed form. With , the coefficients of ,

so no phase unwrapping or numerical differentiation is needed. A symmetric FIR filter of length has the constant delay : no phase distortion, but a long latency.

Among all filters with a given magnitude response, the minimum-phase one has all its zeros inside the unit circle and the least delay. The homomorphic method constructs it from the magnitude alone. The log magnitude and the phase of a minimum-phase filter are a Hilbert-transform pair, so its cepstrum is causal. Folding the negative quefrencies onto the positive ones, for , and exponentiating back gives the minimum-phase filter. Applied to the square root of the magnitude (half), this halves the length of a filter that is the square of a minimum-phase one, as a linear-phase filter designed by remez or firwin approximately is:

Figure 15.10. Minimum-phase taps.

Figure 15.11. Group delay.

The minimum-phase filter has half the taps, and in the passband about 1 sample of delay instead of 15. Its delay varies with frequency, so it distorts the waveform slightly. That is acceptable for audio and control, but not where the shape of a pulse matters.

Least-squares FIR design

A linear-phase filter of length has the zero-phase response . firls minimises the weighted squared error over the bands,

for a piecewise-linear desired response . The minimum solves the normal equations . Here splits into a Toeplitz and a Hankel matrix, and . Every integral has a closed form in terms of sinc functions. Unlike the minimax design, least squares spreads the error over the band. The ripple is largest near the band edges, but the energy in the stopband is smaller.

Rate changes

decimate keeps every -th sample after an anti-alias lowpass: SciPy’s order-8 Chebyshev type I filter with cutoff of Nyquist, applied forwards and backwards for zero phase. resample treats the signal as one period of a band-limited signal and changes its length by truncating or zero-padding the spectrum. It is exact for band-limited periodic signals and rings at discontinuities, including the jump between the last and first sample. A Nyquist bin of an even length has no partner, so it is split in two when upsampling and folded when downsampling.

Robust smoothing and envelopes

The median filter replaces each sample by the median of its neighbourhood. An isolated spike changes the median of a window of 3 or more samples hardly at all, so the filter removes impulsive noise that a linear filter would only smear, and it preserves steps. The envelope is , the instantaneous amplitude of the analytic signal.

Cross spectra and coherence

For two signals the cross spectral density is estimated, as Welch estimates a power spectrum, by averaging over windowed segments. Its phase is the phase lag of behind . Its magnitude, normalised as

is the coherence, the fraction of the power of at that a linear filter applied to explains. If with independent noise , then . The coherence is near 1 where the signal dominates and near 0 where the noise does. With averaged segments, the coherence of unrelated signals is still about , its bias.

Algorithm

minimum_phase(h, half): with , plus of its smallest non-zero value; (or ); multiply by ; ; keep the first (or ) values.

firls: , ; from the closed-form integrals of the linear desired response; solve; the taps are .

csd: segments of the window’s length stepped by length minus overlap; each detrended and windowed; accumulate ; scale by per segment and double the one-sided bins.

Implementation

/// A minimum-phase FIR filter from a linear-phase one by the homomorphic method (SciPy's
/// `minimum_phase(h, 'homomorphic')`): the real cepstrum of `|H|` (or of `|H|^{1/2}` with
/// `half`, which preserves the magnitude of a filter that is the square of a minimum-phase one),
/// folded onto positive quefrencies and exponentiated back. Returns `len(h)/2 + len(h) mod 2`
/// coefficients with `half`, otherwise `len(h)`.
pub fn minimum_phase(h: &[f64], half: bool, n_fft: Option<usize>) -> Result<Vec<f64>, ErrorsJSL> {
    let n = h.len();
    if n <= 2 {
        return Err(ErrorsJSL::InvalidInputRange("h must have more than two taps"));
    }
    let n_fft = n_fft.unwrap_or(1 << (2.0 * (n - 1) as f64 / 0.01).log2().ceil() as u32);
    if n_fft < n {
        return Err(ErrorsJSL::InvalidInputRange("n_fft must be at least len(h)"));
    }
    let spectrum = fft_real(h, n_fft)?;
    let mut mag: Vec<f64> = spectrum.iter().map(|z| z.norm()).collect();
    let min_pos = mag.iter().copied().filter(|&v| v > 0.0).fold(f64::INFINITY, f64::min);
    mag.iter_mut().for_each(|v| *v += 1e-7 * min_pos);
    let mut logmag: Vec<C> = mag.iter().map(|v| C::new(v.ln() * if half { 0.5 } else { 1.0 }, 0.0)).collect();
    // Real cepstrum, folded: c₀, 2c₁, …, 2c_{N/2−1}, (c_{N/2}), 0, ….
    logmag = fft(&logmag, true)?;
    let stop = n_fft / 2;
    for (k, v) in logmag.iter_mut().enumerate() {
        let w = if k == 0 {
            1.0
        } else if k < stop {
            2.0
        } else if k == stop && !n_fft.is_multiple_of(2) {
            1.0
        } else {
            0.0
        };
        *v = C::new(v.re * w, 0.0);
    }
    let exp: Vec<C> = fft(&logmag, false)?.iter().map(|z| z.exp()).collect();
    let hmin = fft(&exp, true)?;
    let n_out = if half { n / 2 + n % 2 } else { n };
    Ok(hmin[..n_out].iter().map(|z| z.re).collect())
}
/// A linear-phase FIR filter of odd length `numtaps` minimising the weighted integrated squared
/// error to a piecewise-linear desired response (SciPy's `firls`). `bands` holds band edges in
/// pairs and `desired` the gains at those edges, as fractions of the Nyquist frequency when `fs`
/// is `None`.
///
/// For the cosine series `A(ω) = Σ aₙ cos(nω)`, the normal equations `Q a = b` have
/// `Q = T + H` (a Toeplitz plus a Hankel matrix of integrals of `cos(nω)` over the bands) and `b`
/// the integrals of the desired response times `cos(nω)`, all in closed form.
pub fn firls(numtaps: usize, bands: &[f64], desired: &[f64], weight: Option<&[f64]>, fs: Option<f64>) -> Result<Vec<f64>, ErrorsJSL> {
    if numtaps.is_multiple_of(2) || numtaps < 1 {
        return Err(ErrorsJSL::InvalidInputRange("numtaps must be odd"));
    }
    if !bands.len().is_multiple_of(2) || bands.len() != desired.len() {
        return Err(ErrorsJSL::InvalidInputRange("bands and desired need one value per band edge"));
    }
    let nyq = 0.5 * fs.unwrap_or(2.0);
    let f: Vec<f64> = bands.iter().map(|v| v / nyq).collect();
    if f.iter().any(|v| !(0.0..=1.0).contains(v)) || f.windows(2).any(|w| w[1] < w[0]) {
        return Err(ErrorsJSL::InvalidInputRange("band edges must be increasing within [0, Nyquist]"));
    }
    let nb = f.len() / 2;
    let ones = vec![1.0; nb];
    let wts = weight.unwrap_or(&ones);
    if wts.len() != nb {
        return Err(ErrorsJSL::IncompatibleArraySizes((wts.len(), nb)));
    }
    let m = (numtaps - 1) / 2;
    let sinc = |x: f64| if x == 0.0 { 1.0 } else { (PI * x).sin() / (PI * x) };
    // q[n] = Σ_bands w (f₂ sinc(f₂ n) − f₁ sinc(f₁ n)).
    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();
    let qm = Array2::from_shape_fn((m + 1, m + 1), |(i, j)| q[i.abs_diff(j)] + q[i + j]);
    let mut b = vec![0.0; m + 1];
    for i in 0..nb {
        let (f1, f2) = (f[2 * i], f[2 * i + 1]);
        let (d1, d2) = (desired[2 * i], desired[2 * i + 1]);
        let slope = (d2 - d1) / (f2 - f1);
        let c = d1 - f1 * slope;
        for (n, bn) in b.iter_mut().enumerate() {
            let nf = n as f64;
            let term = |fe: f64| {
                let mut t = fe * (slope * fe + c) * sinc(fe * nf);
                if n == 0 {
                    t -= slope * fe * fe / 2.0;
                } else {
                    t += slope * (nf * PI * fe).cos() / (PI * nf).powi(2);
                }
                t
            };
            *bn += wts[i] * (term(f2) - term(f1));
        }
    }
    let a = qm.solve(&Array1::from(b)).map_err(|_| ErrorsJSL::RuntimeError("firls: the normal equations are singular"))?;
    let mut h = Vec::with_capacity(numtaps);
    h.extend(a.iter().skip(1).rev());
    h.push(2.0 * a[0]);
    h.extend(a.iter().skip(1));
    Ok(h)
}
  • decimate implements SciPy’s default IIR path. It designs the filter with cheby1, converts it to second-order sections and applies sosfiltfilt (or sosfilt).
  • minimum_phase implements the homomorphic method. SciPy’s alternative 'hilbert' method is not provided.
  • envelope is abs(hilbert(x)). SciPy’s newer envelope function adds band-pass filtering and residuals, which are not included.

In practice

Every function is compared with scipy.signal from SciPy 1.17.1 (references from book/generator/data/make_signal_tools_refs.py):

Table 15.10. Signal-processing utilities against SciPy.

computation (SciPy reference)largest difference (relative to the largest value)
group_delay, Chebyshev I, order 62e-8
group_delay, linear-phase FIR, 41 taps2e-10
minimum_phase, homomorphic, half (31 → 16 taps)1e-14
minimum_phase, homomorphic, full length2e-14
firls, lowpass, 41 taps2e-16
firls, weighted bandpass, 63 taps7e-14
firls, differentiator (sloped band), 31 taps4e-16
decimate by 2, zero-phase IIR3e-15
decimate by 5, zero-phase IIR1e-14
decimate by 3, causal IIR2e-15
resample, 400 → 150 samples9e-16
resample, 400 → 401 samples2e-15
resample, 400 → 1000 samples1e-15
medfilt, kernel 3, signal with spikes0
medfilt, kernel 7, signal with spikes0
envelope (abs(hilbert(x)))1e-15
csd, Hann window of 64, overlap 329e-17
coherence7e-16

Strengths

  • Exact closed forms: the group delay without differentiation, firls without numerical integration.
  • Minimum-phase conversion halves the length and most of the delay of a linear-phase design.
  • Coherence separates linear relationships from noise frequency by frequency.

Weaknesses

  • decimate has only the IIR filter. For FIR anti-aliasing, use the polyphase resampler.
  • resample assumes periodicity. For non-periodic signals, a polyphase resampler avoids the wrap-around ringing.
  • The group delay of high-order IIR filters near their poles is sensitive to rounding. Second-order sections, analysed one at a time, are more accurate.

Exercises

  1. Show that the group delay of is , and that of a symmetric FIR filter of length is .
  2. Show that reflecting a zero outside the unit circle to leaves unchanged up to a constant, and reduces the group delay.
  3. Derive the closed form of , and hence the entries of firls.
  4. Show that the coherence of (no noise) is 1 at every frequency where .
  5. Explain why resample of a ramp shows large ringing at both ends.
Hints and answers
  1. . A symmetric filter is times a real function of .
  2. on the unit circle. A zero inside the circle contributes a smaller phase change, and hence less delay, than its reflection outside.
  3. with . The products split into and , which give the Toeplitz and Hankel parts.
  4. and , so . The estimate from windowed segments is close to 1 but not exactly, because the filter’s response to one segment spills into the next.
  5. Periodically extended, the ramp has a jump of between its last and first samples. Its spectrum decays only like , so truncating it rings (the Gibbs phenomenon).

Further reading

  • A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010, chapters 5 (group delay, minimum phase) and 13 (cepstrum).
  • T. W. Parks and C. S. Burrus, Digital Filter Design, Wiley, 1987, chapter 3 (least-squares design).
  • J. S. Bendat and A. G. Piersol, Random Data: Analysis and Measurement Procedures, 4th ed., Wiley, 2010 (cross spectra and coherence).
  • J. W. Tukey, “Nonlinear (nonsuperposable) methods for smoothing data”, Proceedings of the EASCON (1974) 673–681.