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

Partial fractions, zoom FFT and waveforms

ProblemExpand a rational transfer function into partial fractions and back; undo a convolution; convert between transfer-function, state-space and zero-pole-gain forms; compute the spectrum on a narrow band; generate standard test waveforms; approximate a time delay
Devised byOliver Heaviside (1890s), the cover-up method for partial fractions; J. F. Mahoney and B. D. Sivazlian (1983), the deflation algorithm SciPy uses; Lawrence Rabiner, Ronald Schafer and Charles Rader (1969), the chirp z-transform; Henri Padé (1892), rational approximation
AccuracyAgrees with SciPy to relative (chirps to ), including repeated and complex poles
CostPartial fractions: an eigenproblem for the poles and per residue. Zoom FFT: three FFTs of length
Read firstSpectra at chosen frequencies, Continuous-time systems
APIresidue, residuez, invres, invresz, unique_roots, deconvolve, tf2zpk, zpk2tf, ss2zpk, zpk2ss, pade_delay, zoom_fft, chirp, sweep_poly, gausspulse, sawtooth, square_wave

Overview

The last group of scipy.signal tools covered by the library:

  • Partial fractions. residue writes as a sum of simple terms plus a polynomial. Each term is a mode of the system, whose inverse Laplace transform is . residuez does the same in powers of for digital filters, where each term contributes to the impulse response. invres and invresz go back.
  • Deconvolution. deconvolve divides one polynomial by another, recovering from .
  • Zero-pole-gain form. tf2zpk, zpk2tf, ss2zpk and zpk2ss complete the conversions between the three representations of a linear system. default_response_times gives the time grid SciPy uses for step and impulse responses, and pade_delay approximates a time delay by a rational function.
  • Zoom FFT. zoom_fft evaluates the DFT on a narrow band of frequencies with fine spacing.
  • Waveforms. chirp, sweep_poly, gausspulse, sawtooth, square_wave and unit_impulse generate standard test signals.

Where it is used

Several tools for working with rational transfer functions and standard waveforms.

  • Control and circuits. Partial fractions turn a transfer function into a sum of simple terms whose inverse Laplace or z transform is known, giving the time response of a filter or plant.
  • Deconvolution. Undoing a known filter or channel on a measurement.
  • Test signals. Square, triangle, sawtooth and chirp waveforms for testing amplifiers, filters and sensors.

History

Partial fractions are as old as calculus: Leibniz and Johann Bernoulli used them to integrate rational functions. Oliver Heaviside’s operational calculus of the 1890s made them the standard way to solve circuit equations, with his “cover-up” rule for the residue at a simple pole. For repeated poles the residues involve derivatives. J. F. Mahoney and B. D. Sivazlian’s review (1983) compared the algorithms, and SciPy uses their “deflation through subtraction”.

Lawrence Rabiner, Ronald Schafer and Charles Rader (1969) introduced the chirp z-transform, which evaluates the z-transform on a spiral. The zoom FFT is its special case on an arc of the unit circle. Henri Padé (1892) studied the rational approximants that bear his name. In control engineering they became the standard way to fit a pure delay into a rational model.

The idea

Partial fractions

With the poles (roots of ) and the polynomial part removed by division, a simple pole has residue

Heaviside’s cover-up rule. A pole of multiplicity contributes . Deflation through subtraction finds these one power at a time. Divide the numerator and the product of the other factors by . The ratio of the remainders gives the coefficient of the current power, and subtracting its contribution leaves a numerator with one fewer power.

Numerically, a repeated pole is never computed as repeated. The eigenvalues of a companion matrix with a triple root spread by about . So poles closer than tol ( by default) are grouped by unique_roots and replaced by their mean. The expansion is then that of the grouped denominator, and the choice of tol can change the result. Poles are returned ordered by magnitude, with each conjugate pair listed with the positive imaginary part first. The companion matrix of a real polynomial is real, so its eigenvalues come in exact conjugate pairs. This matters: if the pairs are conjugate only to rounding, their order by magnitude depends on the last bit.

residuez applies the same algorithm to the reversed coefficients, in the variable . It then rescales each residue by to obtain the form .

Deconvolution

If , then , and is the quotient of a polynomial division. deconvolve computes it as the impulse response of for samples:

with the remainder . This is exact for exact data. With noise, the division is a recursive filter with poles at the zeros of . If any lie outside the unit circle, the errors grow exponentially: deconvolution by division is only stable for minimum-phase .

Zoom FFT

The -point DFT samples the spectrum every . Evaluating points on a narrow band is a chirp z-transform with starting point and ratio . Bluestein’s algorithm computes it with three FFTs of length about , far cheaper than an FFT zero-padded to the same spacing. A zoom FFT only interpolates the spectrum of the data, though: it cannot separate two tones closer than about . That takes a longer record (Figure 15.12).

Figure 15.12. Two tones at 100.3 and 101.7 Hz sampled at 1 kHz. The 256-point FFT has bins 3.9 Hz apart. The zoom FFT of the same 256 samples traces the spectrum between the bins but shows one broad peak. With 1024 samples the two peaks separate.

Waveforms and delays

A chirp has instantaneous frequency , so the phase is the integral of the frequency law. A linear sweep from to over has phase with . A logarithmic (geometric) sweep has phase . sweep_poly integrates any polynomial frequency law. A Gaussian pulse has a Gaussian spectrum. gausspulse chooses so that the spectrum’s width at dB is a given fraction of .

A time delay is not rational. Its Padé approximant is

It is all-pass, with magnitude exactly 1, and its phase matches to order . It can be appended to a model with tf2ss.

Algorithm

residue(b, a):

  1. Strip leading zeros. The poles are the eigenvalues of the companion matrix of .
  2. If , divide to get the direct term .
  3. Group poles within tol and sort the groups by magnitude.
  4. For each group, compute the residues by deflation through subtraction, and divide them by .

zoom_fft(x, f₁, f₂, M, f_s): the chirp z-transform of with , and points (with endpoint, in ).

Implementation

/// The partial-fraction expansion of `b(s)/a(s)` in positive powers (SciPy's `residue`):
/// `Σ rᵢ/(s − pᵢ) + k(s)`, with terms `r/(s − p)^j` for poles repeated within `tol`.
pub fn residue(b: &[f64], a: &[f64], tol: f64, rtype: RootType) -> Result<PartialFractions, ErrorsJSL> {
    let b = trim_front(b);
    let a = trim_front(a);
    if a.is_empty() {
        return Err(ErrorsJSL::InvalidInputRange("the denominator is zero"));
    }
    let mut poles = roots(&a)?;
    if b.is_empty() {
        return Ok(PartialFractions { r: vec![C::new(0.0, 0.0); poles.len()], p: cmplx_sort(&poles).0, k: Vec::new() });
    }
    let (k, bnum) = if b.len() < a.len() { (Vec::new(), to_c(&b)) } else { polydiv(&to_c(&b), &to_c(&a)) };
    let (unique, mult) = unique_roots(&poles, tol, rtype);
    let (unique, order) = cmplx_sort(&unique);
    let mult: Vec<usize> = order.iter().map(|&i| mult[i]).collect();
    let residues = compute_residues(&unique, &mult, &bnum);
    let mut index = 0;
    for (pole, &m) in unique.iter().zip(&mult) {
        for slot in poles.iter_mut().skip(index).take(m) {
            *slot = *pole;
        }
        index += m;
    }
    Ok(PartialFractions { r: residues.iter().map(|r| r / a[0]).collect(), p: poles, k: k.iter().map(|c| c.re).collect() })
}
/// The residues for poles of given multiplicity (SciPy's `_compute_residues`, "deflation through
/// subtraction", method 6 of Mahoney and Sivazlian): a simple pole's residue is
/// `b(p)/∏_{q≠p}(p − q)`; for a repeated pole, divide numerator and the cofactor by `(x − p)`
/// repeatedly, peeling off one residue per power and subtracting its contribution.
fn compute_residues(poles: &[C], mult: &[usize], numerator: &[C]) -> Vec<C> {
    let (factors, _) = compute_factors(poles, mult, false);
    let mut residues = Vec::new();
    for ((pole, &m), factor) in poles.iter().zip(mult).zip(&factors) {
        if m == 1 {
            residues.push(polyval(numerator, *pole) / polyval(factor, *pole));
        } else {
            let mono = vec![C::new(1.0, 0.0), -pole];
            let (factor, d) = polydiv(factor, &mono);
            let mut numer = numerator.to_vec();
            let mut block = Vec::new();
            for _ in 0..m {
                let (q, n) = polydiv(&numer, &mono);
                let r = n[0] / d[0];
                numer = polyadd(&q, &factor.iter().map(|f| -r * f).collect::<Vec<_>>());
                block.push(r);
            }
            block.reverse();
            residues.extend(block);
        }
    }
    residues
}
/// Inverse filtering (SciPy's `deconvolve`): the quotient `q` and remainder `r` with
/// `signal = divisor ∗ q + r`, `q` being the impulse response of `signal(z)/divisor(z)` for
/// `len(signal) − len(divisor) + 1` samples. It is polynomial division, so it is unstable when the
/// divisor has zeros outside the unit circle.
pub fn deconvolve(signal: &[f64], divisor: &[f64]) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
    let (n, d) = (signal.len(), divisor.len());
    if n == 0 || d == 0 {
        return Err(ErrorsJSL::InvalidInputRange("signal and divisor must be non-empty"));
    }
    if divisor[0] == 0.0 {
        return Err(ErrorsJSL::InvalidInputRange("the divisor's first coefficient must be non-zero"));
    }
    if d > n {
        return Ok((Vec::new(), signal.to_vec()));
    }
    let len = n - d + 1;
    let mut q = vec![0.0; len];
    for i in 0..len {
        let s: f64 = (1..d.min(i + 1)).map(|k| divisor[k] * q[i - k]).sum();
        q[i] = (signal[i] - s) / divisor[0];
    }
    let mut rem = signal.to_vec();
    for (i, qi) in q.iter().enumerate() {
        for (k, dk) in divisor.iter().enumerate() {
            rem[i + k] -= dk * qi;
        }
    }
    Ok((q, rem))
}
/// The DFT of `x` at `m` equally spaced frequencies from `f1` towards `f2` (SciPy's `zoom_fft`,
/// with the sample rate `fs`): the chirp z-transform on an arc of the unit circle starting at
/// `a = e^{2πi f1/fs}` with ratio `w = e^{−2πi (f2 − f1)/(fs m)}` (`(m − 1)` in place of `m` with
/// `endpoint`), computed by Bluestein's algorithm in `O((n + m) log(n + m))`.
pub fn zoom_fft(x: &[f64], f1: f64, f2: f64, m: usize, fs: f64, endpoint: bool) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
    if m == 0 || x.is_empty() {
        return Err(ErrorsJSL::InvalidInputRange("need a non-empty signal and m ≥ 1"));
    }
    let scale = if endpoint && m > 1 { (f2 - f1) * m as f64 / (fs * (m - 1) as f64) } else { (f2 - f1) / fs };
    let a = Complex::from_polar(1.0, 2.0 * PI * f1 / fs);
    let w = Complex::from_polar(1.0, -2.0 * PI * scale / m as f64);
    Ok(crate::discrete::spectral::chirpz::chirpz(x, Some(m), Some(w), Some(a))?.to_vec())
}
/// A swept-frequency cosine `cos(φ(t) + φ₀)` (SciPy's `chirp`, `phi` in degrees), where the phase
/// `φ(t) = 2π ∫₀ᵗ f(τ) dτ` integrates the instantaneous frequency of the chosen sweep.
pub fn chirp(t: &[f64], f0: f64, t1: f64, f1: f64, method: ChirpMethod, phi: f64) -> Result<Vec<f64>, ErrorsJSL> {
    let phase = |ti: f64| -> Result<f64, ErrorsJSL> {
        Ok(match method {
            ChirpMethod::Linear => TAU * (f0 * ti + 0.5 * (f1 - f0) / t1 * ti * ti),
            ChirpMethod::Quadratic { vertex_zero } => {
                let beta = (f1 - f0) / (t1 * t1);
                if vertex_zero { TAU * (f0 * ti + beta * ti.powi(3) / 3.0) } else { TAU * (f1 * ti + beta * ((t1 - ti).powi(3) - t1.powi(3)) / 3.0) }
            }
            ChirpMethod::Logarithmic => {
                if f0 * f1 <= 0.0 {
                    return Err(ErrorsJSL::InvalidInputRange("a logarithmic chirp needs f0 and f1 of the same sign"));
                }
                if f0 == f1 { TAU * f0 * ti } else { TAU * t1 / (f1 / f0).ln() * f0 * ((f1 / f0).powf(ti / t1) - 1.0) }
            }
            ChirpMethod::Hyperbolic => {
                if f0 == 0.0 || f1 == 0.0 {
                    return Err(ErrorsJSL::InvalidInputRange("a hyperbolic chirp needs non-zero f0 and f1"));
                }
                if f0 == f1 {
                    TAU * f0 * ti
                } else {
                    let sing = -f1 * t1 / (f0 - f1);
                    TAU * (-sing * f0) * (1.0 - ti / sing).abs().ln()
                }
            }
        })
    };
    t.iter().map(|&ti| Ok((phase(ti)? + phi.to_radians()).cos())).collect()
}
  • residue returns complex residues and poles, and a real direct term, as SciPy does for real input. invres returns complex polynomials, whose imaginary parts vanish to rounding for real systems.
  • Polynomial division follows NumPy’s polydiv, including its removal of leading remainder terms below in magnitude.
  • square_wave is named to avoid a clash with the existing square sources; it follows SciPy’s square.

In practice

Every function is compared with SciPy 1.17.1 (references from book/generator/data/make_signal2_refs.py). Zeros and poles from tf2zpk and ss2zpk are matched as sets, because the order of the roots of a polynomial depends on the eigensolver:

Table 15.11. Partial fractions, conversions, zoom FFT and waveforms against SciPy.

computation (SciPy reference)largest difference (relative)
residue and invres, (s + 2)/(s² + 4s + 3)0
residue and invres, an improper fraction (direct term k)5e-16
residue and invres, a double pole4e-15
residue and invres, a triple pole and a complex pair2e-15
residuez and invresz, second order9e-16
residuez and invresz, a double pole at z = 0.54e-16
residuez and invresz, an FIR part (direct term k)0
deconvolve, a noisy 44-sample convolution by a 5-tap filter: quotient and remainder6e-16
tf2zpk (zeros and poles matched as sets)3e-16
zpk2tf back4e-16
ss2zpk (sets)8e-15
Default time grid of step (7 time constants of the slowest mode)3e-16
zoom_fft, 95–110 Hz in 128 points, endpoint false1e-14
zoom_fft, 95–110 Hz in 128 points, endpoint true6e-13
sawtooth (widths 1, 0.5, 0.25) and square (duty 0.3)6e-15
gausspulse: in-phase, quadrature, envelope and cutoff time4e-15
chirp, all four sweeps (and both quadratic vertices)1e-13
sweep_poly, a cubic frequency law7e-15

Strengths

  • Partial fractions with repeated and complex poles that agree with SciPy entry by entry, in the same order.
  • A zoom FFT on top of the library’s Bluestein-based chirp z-transform.
  • The common analysis waveforms, with SciPy’s conventions (phases in degrees, the quadratic sweep’s vertex choice).

Weaknesses

  • Partial fractions are ill-conditioned for clustered poles: the residues of nearly repeated poles are large and nearly cancel. The grouping tolerance decides the answer.
  • deconvolve is plain polynomial division and amplifies noise without bound for non-minimum-phase divisors. Regularised (Wiener) deconvolution is not provided.
  • No ZerosPolesGain system type: zero-pole-gain models are converted to state space or transfer functions to be simulated.

Exercises

  1. Expand by hand and find its impulse response.
  2. Show that the residues at a pole of multiplicity 2 are and .
  3. Why must the poles in invres be adjacent when repeated?
  4. Show that zoom_fft with , and is the ordinary DFT.
  5. Show that the Padé approximant of is all-pass.
Hints and answers
  1. , so .
  2. Multiply by and evaluate, then differentiate.
  3. Repeated poles are recognised by comparing each pole with its predecessor’s group (_group_poles), not by searching the whole list, so separated copies would be treated as distinct poles.
  4. Then and , and the chirp z-transform is the DFT.
  5. The numerator is the denominator with , so on it is the complex conjugate of the denominator, and their ratio has magnitude 1.

Further reading

  • J. F. Mahoney and B. D. Sivazlian, “Partial fractions expansion: a review of computational methodology and efficiency”, Journal of Computational and Applied Mathematics 9 (1983) 247–269.
  • L. R. Rabiner, R. W. Schafer and C. M. Rader, “The chirp z-transform algorithm”, IEEE Transactions on Audio and Electroacoustics 17 (1969) 86–92.
  • A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010, sections 3.3 (partial fractions) and 9.6 (the chirp z-transform).
  • G. F. Franklin, J. D. Powell and A. Emami-Naeini, Feedback Control of Dynamic Systems, 7th ed., Pearson, 2015, section 5.6 (Padé approximation of delays).