Decimation, Interpolation and Polyphase Filters
A vibration sensor is sampled at because the ADC's anti-alias filter is easy at that rate, but the analysis only needs content up to . A speech codec wants from a microphone. An audio player must turn files into the 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 keeps every -th sample: . The new rate is and the new Nyquist frequency ; every component above it aliases, exactly as in analog sampling. So a decimator first low-pass filters to below and then downsamples:
In the frequency domain, downsampling stretches the spectrum by and adds shifted copies; the filter makes sure the copies do not overlap the band you keep.
Interpolation: insert zeros, then filter
Upsampling by inserts zeros between samples. The spectrum is unchanged in hertz, but now the band contains images of the original baseband. An interpolator removes them with a low-pass at (the old Nyquist frequency) and a gain of , to make up for the zeros. A rational change by upsamples by , filters once with a cutoff at the lower of the two Nyquist frequencies, and downsamples by .
Worked example: 48 kSa/s to 16 kSa/s, and 44.1 to 48
Given: sampled at ; the part is unwanted.
Find: the amplitudes at and at the alias frequency of after decimating by 3, naively and with resample_poly; then the factors for .
Solve: at the Nyquist frequency is , so folds to , inside the new band. Naive decimation keeps it at full amplitude; the filter should remove it. For : in lowest terms ().
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 tone into a tone of amplitude , indistinguishable from a real one. resample_poly reduces it to (about down) and leaves the tone within . The conversion produces exactly samples and preserves the tone's amplitude to .
Simulation. The same folding happens when any signal is sampled. In the lab, a signal sampled at (the same ratios in hertz instead of kilohertz) reads an alias at , phase-reversed. Switch the anti-alias filter on: its 4th-order Butterworth at gives only at , 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.
Polyphase filters: never compute what you throw away
Filtering at and then discarding two outputs out of three wastes two thirds of the multiplications. The polyphase decomposition splits the filter into sub-filters ; by the noble identity (a filter in followed by equals followed by the filter in ) each sub-filter can run after the downsampler, at the low rate:
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 MACs per output sample instead of . For an interpolator the same idea works in reverse: the sub-filters each produce one of the 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 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 test tone decimated from to appears at without a filter; with resample_poly it should be about lower.
Simulation. Change the interferer to (just below the new Nyquist frequency) and to (just above). The filter's transition band is centred on : the tone comes through only down, and the tone folds onto attenuated by only about . Decimation filters need a guard band: keep the wanted band well below , or design the filter so that the stopband starts at .
What you would measure. With a USB audio interface at and a function generator, record plus (each about amplitude through a passive resistor mixer), decimate the recording both ways in Python and compare the spectra. Expect the alias at within about of the input level for the naive version, and about lower for the filtered one, as in the simulation. That residue is still above the interface's own noise floor (roughly to 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 . - Forgetting the gain of after zero insertion (the output is times too quiet).
- Upsampling by and downsampling by 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 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
- A tone is decimated from by 4 without a filter. Where does it appear?
- Find and for converting to .
- A 120-tap FIR decimates by 4. How many MACs per output sample does the polyphase form need, and the direct form?
Answer
- New rate , Nyquist : .
- : , .
- Polyphase: 120 per output sample (four 30-tap sub-filters); direct: .
Test yourself
Before downsampling by , the signal must be low-pass filtered to below
Inserting zeros between samples creates
- aliases
- images of the baseband that a low-pass must remove
- a gain of
- a delay of samples
A polyphase decimator by 3 with a 48-tap filter needs per output sample
- 16 MACs
- 48 MACs
- 144 MACs
- 3 MACs
Converting 44.1 kSa/s to 48 kSa/s uses
- an integer factor