TExcelTAD
Home › Signals, Systems & Digital Filters for Engineers › Decimation, Interpolation and Polyphase Filters

Decimation, Interpolation and Polyphase Filters

A vibration sensor is sampled at 48 kSa/s48\ \text{kSa/s} because the ADC's anti-alias filter is easy at that rate, but the analysis only needs content up to 6 kHz6\ \text{kHz}. A speech codec wants 16 kSa/s16\ \text{kSa/s} from a 48 kSa/s48\ \text{kSa/s} microphone. An audio player must turn 44.1 kSa/s44.1\ \text{kSa/s} files into the 48 kSa/s48\ \text{kSa/s} its DAC runs at. Changing the sampling rate inside the digital domain is multirate processing. Done naively it aliases or creates images; done with the right filter and the polyphase trick it costs less than filtering at a single rate. This lesson covers decimation, interpolation, rational rate changes and polyphase filters, with resample_poly and upfirdn. The sampling theory behind it is in The Sampling Theorem in Practice and Aliasing and Anti-Alias Filters.

Decimation: filter, then drop samples

Downsampling by an integer MM keeps every MM-th sample: y[m]=x[mM]y[m] = x[mM]. The new rate is fs/Mf_s/M and the new Nyquist frequency fs/(2M)f_s/(2M); every component above it aliases, exactly as in analog sampling. So a decimator first low-pass filters to below fs/(2M)f_s/(2M) and then downsamples:

y[m]=∑kh[k] x[mM−k],cutoff≤fs2My[m] = \sum_{k} h[k]\,x[mM - k], \qquad \text{cutoff} \le \frac{f_s}{2M}

In the frequency domain, downsampling stretches the spectrum by MM and adds M−1M - 1 shifted copies; the filter makes sure the copies do not overlap the band you keep.

Interpolation: insert zeros, then filter

Upsampling by LL inserts L−1L - 1 zeros between samples. The spectrum is unchanged in hertz, but now the band 0…Lfs/20 \ldots L f_s/2 contains L−1L - 1 images of the original baseband. An interpolator removes them with a low-pass at fs/2f_s/2 (the old Nyquist frequency) and a gain of LL, to make up for the zeros. A rational change by L/ML/M upsamples by LL, filters once with a cutoff at the lower of the two Nyquist frequencies, and downsamples by MM.

Worked example: 48 kSa/s to 16 kSa/s, and 44.1 to 48

Given: x[n]=sin⁡(2π⋅1 kHz⋅t)+0.5sin⁡(2π⋅10 kHz⋅t)x[n] = \sin(2\pi \cdot 1\ \text{kHz} \cdot t) + 0.5\sin(2\pi \cdot 10\ \text{kHz} \cdot t) sampled at 48 kSa/s48\ \text{kSa/s}; the 10 kHz10\ \text{kHz} part is unwanted.

Find: the amplitudes at 1 kHz1\ \text{kHz} and at the alias frequency of 10 kHz10\ \text{kHz} after decimating by 3, naively and with resample_poly; then the factors for 44.1→48 kHz44.1 \to 48\ \text{kHz}.

Solve: at 16 kSa/s16\ \text{kSa/s} the Nyquist frequency is 8 kHz8\ \text{kHz}, so 10 kHz10\ \text{kHz} folds to 16−10=6 kHz16 - 10 = 6\ \text{kHz}, inside the new band. Naive decimation keeps it at full amplitude; the filter should remove it. For 44.1→4844.1 \to 48: 48 000/44 100=160/14748\,000/44\,100 = 160/147 in lowest terms (gcd⁡=300\gcd = 300).

python · try it yourself
import numpy as np
from scipy import signal

fs, M = 48000, 3                                   # 48 kSa/s -> 16 kSa/s
t = np.arange(4800) / fs                           # 0.1 s
x = np.sin(2 * np.pi * 1000 * t) + 0.5 * np.sin(2 * np.pi * 10000 * t)   # wanted 1 kHz + unwanted 10 kHz

def amplitude(y, f, fs_y):                         # amplitude of the tone at f (Hz) by correlation over whole cycles
    n = np.arange(len(y))
    return 2 * abs(np.mean(y * np.exp(-2j * np.pi * f / fs_y * n)))

naive = x[::M]                                     # keep every 3rd sample, no filter
good = signal.resample_poly(x, 1, M)               # low-pass (Kaiser-window FIR) then keep every 3rd sample
fs2 = fs / M
for name, y in (("naive x[::3]", naive[32:-32]), ("resample_poly", good[32:-32])):   # drop the filter's edge transients
    print(f"{name:14s} 1 kHz: {amplitude(y, 1000, fs2):.4f}   alias of 10 kHz at {fs2 - 10000:.0f} Hz: {amplitude(y, 6000, fs2):.4f}")

# Rational change 44.1 kHz -> 48 kHz
from math import gcd
L, Mr = 48000 // gcd(48000, 44100), 44100 // gcd(48000, 44100)
print(f"44.1 kHz -> 48 kHz: up by L = {L}, down by M = {Mr}")
x2 = np.sin(2 * np.pi * 1000 * np.arange(4410) / 44100)          # 0.1 s of 1 kHz at 44.1 kHz
y2 = signal.resample_poly(x2, L, Mr)
print(f"{len(x2)} samples in -> {len(y2)} samples out; 1 kHz amplitude after conversion {amplitude(y2[240:-240], 1000, 48000):.4f}")
naive x[::3]   1 kHz: 1.0000   alias of 10 kHz at 6000 Hz: 0.5000
resample_poly  1 kHz: 1.0010   alias of 10 kHz at 6000 Hz: 0.0007
44.1 kHz -> 48 kHz: up by L = 160, down by M = 147
4410 samples in -> 4800 samples out; 1 kHz amplitude after conversion 1.0006

Check: naive decimation turns the unwanted 10 kHz10\ \text{kHz} tone into a 6 kHz6\ \text{kHz} tone of amplitude 0.50.5, indistinguishable from a real one. resample_poly reduces it to 0.00070.0007 (about 57 dB57\ \text{dB} down) and leaves the 1 kHz1\ \text{kHz} tone within 0.1 %0.1\,\%. The 44.1→4844.1 \to 48 conversion produces exactly 4410×160/147=48004410 \times 160/147 = 4800 samples and preserves the tone's amplitude to 0.06 %0.06\,\%.

Simulation. The same folding happens when any signal is sampled. In the lab, a 10 Hz10\ \text{Hz} signal sampled at 16 Hz16\ \text{Hz} (the same ratios in hertz instead of kilohertz) reads an alias at 6.000 Hz6.000\ \text{Hz}, phase-reversed. Switch the anti-alias filter on: its 4th-order Butterworth at 0.4fs0.4 f_s gives only −15.63 dB-15.63\ \text{dB} at 10 Hz10\ \text{Hz}, far less than the digital decimation filter above. Digital filters can be much sharper than practical analog ones, which is why systems sample fast with a gentle analog filter and then decimate digitally.

-A0+A0.0 s0.2 s0.4 s0.6 s0.8 s1.0 sx (V)input 10.0 Hzreconstructed 6.00 Hzsamples, fs = 16.0 Hz0A0102030405060708090100f (Hz)fs/2faliasaliased: f > fs/2 = 8.00 Hz

Polyphase filters: never compute what you throw away

Filtering at 48 kSa/s48\ \text{kSa/s} and then discarding two outputs out of three wastes two thirds of the multiplications. The polyphase decomposition splits the filter h[n]h[n] into MM sub-filters Ek[m]=h[mM+k]E_k[m] = h[mM + k]; by the noble identity (a filter in zMz^M followed by ↓M\downarrow M equals ↓M\downarrow M followed by the filter in zz) each sub-filter can run after the downsampler, at the low rate:

x[n] H(z) 48 taps down 3 y[m] (N MACs per input sample) polyphase: x[n] down 3 E0(z) z^-1 down 3 E1(z) z^-2 down 3 E2(z) + y[m] E_k[m] = h[3m + k] 16 taps each, run at the low rate
python · try it yourself
import numpy as np
from scipy import signal

M, N = 3, 48                                     # decimate by 3 with a 48-tap low-pass (cutoff fs/(2M))
h = signal.firwin(N, 1 / M)                      # cutoff as a fraction of Nyquist: 1/3 of it = 8 kHz at 48 kHz
rng = np.random.default_rng(5)
x = rng.standard_normal(3000)

# 1) Filter at the high rate, then keep every M-th output: N MACs per INPUT sample, 2/3 of them thrown away
y_direct = signal.lfilter(h, 1, x)[::M]

# 2) Polyphase: split h into M sub-filters E_k[m] = h[mM + k], each fed every M-th input sample, at the low rate
y_poly = np.zeros(len(x) // M)
for k in range(M):
    ek = h[k::M]                                 # sub-filter k (16 taps)
    xk = np.concatenate((np.zeros(k), x))[::M][:len(y_poly)]     # input branch k: x[nM - k]
    y_poly += signal.lfilter(ek, 1, xk)
print("polyphase output equals filter-then-downsample:", bool(np.allclose(y_poly, y_direct)))
print(f"MACs per output sample: direct {N * M}, polyphase {N}  (saving factor {M})")
print(f"sub-filter lengths: {[len(h[k::M]) for k in range(M)]}")
y_up = signal.upfirdn(h, x, up=1, down=M)        # SciPy's polyphase routine does the same
print("upfirdn agrees:", bool(np.allclose(y_up[:len(y_poly)], y_poly)))
polyphase output equals filter-then-downsample: True
MACs per output sample: direct 144, polyphase 48  (saving factor 3)
sub-filter lengths: [16, 16, 16]
upfirdn agrees: True

The polyphase decimator computes the identical output with N=48N = 48 MACs per output sample instead of NM=144N M = 144. For an interpolator the same idea works in reverse: the LL sub-filters each produce one of the LL output phases, and the zeros are never multiplied. upfirdn (upsample, FIR filter, downsample) and resample_poly implement this; resample_poly also designs a Kaiser-window low-pass for you. For large ratios, decimate in stages (for example 8=2×2×28 = 2 \times 2 \times 2 or a CIC filter followed by a short FIR): early stages run at the high rate but can have wide transition bands, so the total work drops further.

Guided lab: hearing aliasing in decimation

Hand calculation. A 10 kHz10\ \text{kHz} test tone decimated from 4848 to 16 kSa/s16\ \text{kSa/s} appears at 6 kHz6\ \text{kHz} without a filter; with resample_poly it should be about 57 dB57\ \text{dB} lower.

Simulation. Change the interferer to 7.5 kHz7.5\ \text{kHz} (just below the new Nyquist frequency) and to 8.5 kHz8.5\ \text{kHz} (just above). The filter's transition band is centred on 8 kHz8\ \text{kHz}: the 7.5 kHz7.5\ \text{kHz} tone comes through only 1.8 dB1.8\ \text{dB} down, and the 8.5 kHz8.5\ \text{kHz} tone folds onto 7.5 kHz7.5\ \text{kHz} attenuated by only about 14 dB14\ \text{dB}. Decimation filters need a guard band: keep the wanted band well below fs/(2M)f_s/(2M), or design the filter so that the stopband starts at fs/(2M)f_s/(2M).

What you would measure. With a USB audio interface at 48 kSa/s48\ \text{kSa/s} and a function generator, record 1 kHz1\ \text{kHz} plus 10 kHz10\ \text{kHz} (each about 0.2 V0.2\ \text{V} amplitude through a passive resistor mixer), decimate the recording both ways in Python and compare the spectra. Expect the alias at 6 kHz6\ \text{kHz} within about ±0.5 dB\pm 0.5\ \text{dB} of the 10 kHz10\ \text{kHz} input level for the naive version, and about 57 dB57\ \text{dB} lower for the filtered one, as in the simulation. That residue is still above the interface's own noise floor (roughly −90-90 to −110 dBFS-110\ \text{dBFS} wideband depending on the interface, and lower still in a single FFT bin), so you can see it and confirm the filter's stopband.

Hazards and safe setup. Function generator into a line input at a few hundred millivolts; USB-powered interface; no mains equipment opened. Listen at low volume.

Pitfalls

  • Using x[::M] on a signal that has content above fs/(2M)f_s/(2M).
  • Forgetting the gain of LL after zero insertion (the output is LL times too quiet).
  • Upsampling by LL and downsampling by MM with two separate filters instead of one at the lower cutoff.
  • Writing a decimator that filters at the high rate and then discards samples: correct but MM times too expensive.
  • Expecting multirate filters to be time invariant: a decimator is linear but periodically time-varying (shifting the input by one sample changes more than a shift of the output).

Practice

  1. A 3 kHz3\ \text{kHz} tone is decimated from 16 kSa/s16\ \text{kSa/s} by 4 without a filter. Where does it appear?
  2. Find LL and MM for converting 32 kSa/s32\ \text{kSa/s} to 44.1 kSa/s44.1\ \text{kSa/s}.
  3. A 120-tap FIR decimates by 4. How many MACs per output sample does the polyphase form need, and the direct form?
Answer
  1. New rate 4 kSa/s4\ \text{kSa/s}, Nyquist 2 kHz2\ \text{kHz}: ∣3−4∣=1 kHz\lvert 3 - 4 \rvert = 1\ \text{kHz}.
  2. 44 100/32 000=441/32044\,100/32\,000 = 441/320: L=441L = 441, M=320M = 320.
  3. Polyphase: 120 per output sample (four 30-tap sub-filters); direct: 120×4=480120 \times 4 = 480.

Test yourself

Before downsampling by MM, the signal must be low-pass filtered to below

  1. fs/2f_s/2
  2. fs/Mf_s/M
  3. fs/(2M)f_s/(2M)
  4. MfsM f_s

Inserting L−1L - 1 zeros between samples creates

  1. aliases
  2. images of the baseband that a low-pass must remove
  3. a gain of LL
  4. a delay of LL samples

A polyphase decimator by 3 with a 48-tap filter needs per output sample

  1. 16 MACs
  2. 48 MACs
  3. 144 MACs
  4. 3 MACs

Converting 44.1 kSa/s to 48 kSa/s uses

  1. L/M=48/44L/M = 48/44
  2. L/M=160/147L/M = 160/147
  3. L/M=441/480L/M = 441/480
  4. an integer factor