Overview
A sampled signal can only hold frequencies up to half its sample rate, a limit called the Nyquist frequency. To lower the rate you keep fewer samples, but anything above the new limit must be filtered out first. Otherwise it folds down and appears as a false low frequency, an alias. To raise the rate you need new samples between the old ones. Placing zeros there creates the right number of samples but also mirror copies of the spectrum, which a low-pass filter removes, and the filter fills the zeros with smoothly interpolated values. A general ratio such as 3 to 2 does both in sequence, with one filter doing both jobs.
A short history
The practice rests on the sampling theorem, stated by Harry Nyquist in 1928 and proved in its familiar form by Claude Shannon in 1949: a signal is captured fully only if sampled above twice its highest frequency. Multirate digital signal processing grew up in the 1970s, and Ronald Crochiere and Lawrence Rabiner set out the upsample, filter, downsample method in their 1983 book. Polyphase filters made it cheap enough for real-time use.
How it works
- Write the rate change as a fraction in lowest terms: is the upsampling factor and the downsampling factor.
- Insert zeros after every input sample. The signal now runs at times the input rate.
- Design a low-pass filter at that intermediate rate, with its cutoff at the lower of the input and output Nyquist frequencies.
- Apply the filter. It removes the spectral copies created by the zeros and any content that the output rate cannot hold.
- Keep every -th sample of the filtered signal. The result has the output rate.
- For a pure decrease set (decimation), and for a pure increase set (interpolation).
Watch out for
- Dropping samples without filtering first lets everything above the new Nyquist frequency fold back into the signal. Once mixed in, an alias cannot be removed.
- The filter is not ideal. A band just below the new Nyquist frequency is attenuated, and a little content just above it leaks through. A larger half_width narrows that band and costs more computation.
- About half_width samples at each end of the output are less accurate, because the filter sees zeros beyond the edges of the signal.
- resample_fft treats the signal as one period of a repeating pattern. A signal whose two ends do not match will ring near the edges.
- Linear interpolation is a weak low-pass filter. It dulls high frequencies and does not prevent aliasing when the rate goes down.
Use cases
When to use it
Bringing recordings made at different rates to one common rate before training, and reducing the rate to save computation when the content of interest is at low frequencies.
In industry
- Audio production
- Studio audio at 48 kHz is converted to 44.1 kHz for CD, a ratio of 147 to 160, with a low-pass filter to prevent aliasing.
- Speech and machine learning
- Recordings from many sources are resampled to 16 kHz before training or running a speech recogniser, so the model sees one rate.
- Software radio
- Receivers decimate a wideband sampled signal in stages to reach the narrow channel of interest at a low rate.
Choosing it: what must hold
- A uniformly sampled signal with a known original rate.
- A target rate that is a ratio of whole numbers to the original rate.
- When reducing the rate, acceptance that content above half the new rate is removed by the filter.
- A low-pass filter long enough to give the stopband rejection you need.
When to choose something else
| If | Use instead |
|---|---|
| Samples are irregularly spaced in time | Interpolation onto a regular grid first |
| You only want to remove a frequency band and keep the rate | Filtering |
| The ratio is not a simple fraction or changes over time | An arbitrary-ratio resampler based on interpolation, for example a windowed-sinc interpolator |
Math foundations
The rate change
The output rate for upsampling by and downsampling by . The template divides both by their greatest common divisor first. Going from 44100 Hz to 48000 Hz needs and .
Zero stuffing
The signal at the intermediate rate . Its spectrum holds the original plus shifted copies, called images, that the filter must remove.
The filter's cutoff
The filter must block the images, which start at the input Nyquist frequency, and everything the output cannot hold, which starts at the output Nyquist frequency. The lower of the two limits covers both.
The filter's taps
A sinc tapered by a Hamming window, for from to with equal to half_width times . The constant is chosen so the taps sum to , which restores the level lost when of every samples were set to zero.
The whole conversion
Stuffing, filtering and keeping every -th sample collapse into one formula. Output sample sits at input position and is a weighted sum of the input samples around that position.
Where an alias lands
A tone at sampled at rate is indistinguishable from one at this frequency, which always lies between 0 and . If is already below then and nothing changes.
Symbols
- the input and output sample rates
- the upsampling and downsampling factors (up and down in the config)
- the input signal
- the zero-stuffed signal at the intermediate rate
- the taps of the low-pass filter
- the Hamming window
- the scaling constant that makes the taps sum to
- half the filter length: half_width times
- the output signal
- a tone's frequency and the rate it is sampled at
- the frequency at which the tone appears after sampling
Worked by hand
Convert a recording from 48 kHz to 16 kHz with the default half_width of 10. The fraction is , so and . Suppose the recording contains a 10 kHz tone.
The 10 kHz tone is above the new 8 kHz limit. Kept unfiltered it would appear as a false 6 kHz tone, so the 61-tap filter removes it before every third sample is kept.
Visual example
Loading the example.
Try this
- Leave the tone at 10 kHz with M = 3 and bypass the filter: the output shows a 6 kHz wave that is not in the input.
- Turn the filter back on and lower the tone below 8 kHz. Now it passes at full amplitude.
- Set L = 2 and M = 1 and click Zero stuffing, then Low-pass filter, to watch the zeros get filled in.
Code sample
import numpy as np
from impl import Resampler, downsample
from config import ResamplerConfig
sr = 48000
x = np.sin(2 * np.pi * 440 * np.arange(4800) / sr)
r = Resampler(ResamplerConfig(up=1, down=3)) # 48 kHz -> 16 kHz
y = r.resample(x) # (1600,), filtered then thinned
r.output_rate(sr) # 16000.0
z = Resampler(ResamplerConfig(up=147, down=160)).resample(x) # 48 kHz -> 44.1 kHzRead the implementation (129 lines)
"""Changing the sample rate of a signal.
`Resampler` converts by a rational factor up / down: insert zeros, low-pass filter with a windowed sinc, keep
every down-th sample. With up = 1 this is decimation, with down = 1 interpolation. `resample_fft` resamples a
periodic signal exactly in the frequency domain, `resample_linear` joins the dots, and `upsample_zero_stuff`
and `downsample` are the raw building blocks without any filtering.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import ResamplerConfig
except ImportError: # run from the template's own folder
from config import ResamplerConfig
def upsample_zero_stuff(x, factor: int) -> np.ndarray:
"""Insert factor - 1 zeros after every sample. Returns array (len(x) * factor,).
This raises the rate but leaves copies (images) of the spectrum that a low-pass filter must remove.
"""
x = np.asarray(x, dtype=float).ravel()
if factor < 1:
raise ValueError("factor must be at least 1")
out = np.zeros(x.size * factor)
out[::factor] = x
return out
def downsample(x, factor: int) -> np.ndarray:
"""Keep every factor-th sample, with no filtering. Returns array (ceil(len(x) / factor),).
Anything above the new Nyquist frequency folds back (aliases) into the result. Use `Resampler.decimate`
unless the signal is already band-limited.
"""
if factor < 1:
raise ValueError("factor must be at least 1")
return np.asarray(x, dtype=float).ravel()[::factor].copy()
def resample_fft(x, num: int) -> np.ndarray:
"""Resample x to `num` samples by truncating or zero-padding its spectrum. Returns array (num,).
Exact for a periodic, band-limited signal sampled over a whole number of periods. Other signals ring at
the ends, because the method treats x as one period of an endless repetition.
"""
x = np.asarray(x, dtype=float).ravel()
n = x.size
if n == 0 or num < 1:
raise ValueError("x must be non-empty and num at least 1")
spectrum = np.fft.rfft(x)
out = np.zeros(num // 2 + 1, dtype=complex)
keep = min(spectrum.size, out.size)
out[:keep] = spectrum[:keep]
if num > n and n % 2 == 0:
out[n // 2] *= 0.5 # the old Nyquist bin is shared between +f and -f in the longer spectrum
elif num < n and num % 2 == 0:
out[num // 2] = 2.0 * spectrum[num // 2].real # the new Nyquist bin collects +f and -f
return np.fft.irfft(out, num) * (num / n)
def resample_linear(x, num: int) -> np.ndarray:
"""Resample x to `num` samples covering the same span by linear interpolation. Returns array (num,)."""
x = np.asarray(x, dtype=float).ravel()
if x.size == 0 or num < 1:
raise ValueError("x must be non-empty and num at least 1")
return np.interp(np.linspace(0.0, x.size - 1.0, num), np.arange(x.size), x)
class Resampler:
"""Rational-rate resampling by up / down with a windowed-sinc anti-aliasing filter."""
def __init__(self, config: ResamplerConfig | None = None) -> None:
self.config = config or ResamplerConfig()
g = math.gcd(self.config.up, self.config.down)
self.up, self.down = self.config.up // g, self.config.down // g
def design_filter(self, up: int, down: int) -> np.ndarray:
"""Low-pass FIR used at the intermediate rate (input rate times up). Returns array (taps,), odd length.
The cutoff is the lower of the input and output Nyquist frequencies. The taps sum to `up`, which
restores the amplitude lost by zero stuffing.
"""
widest = max(up, down)
half = self.config.half_width * widest
k = np.arange(-half, half + 1)
window = 0.54 + 0.46 * np.cos(np.pi * k / half) # Hamming, centred on k = 0
taps = np.sinc(k / widest) * window
return taps * (up / taps.sum())
def _convert(self, x, up: int, down: int) -> np.ndarray:
x = np.asarray(x, dtype=float).ravel()
if up == 1 and down == 1:
return x.copy()
taps = self.design_filter(up, down)
stuffed = upsample_zero_stuff(x, up)
half = taps.size // 2
filtered = np.convolve(stuffed, taps, mode="full")[half: half + stuffed.size]
return filtered[::down]
def resample(self, x) -> np.ndarray:
"""Change the rate of x, array (n,), by up / down. Returns array (ceil(n * up / down),).
Sample i of the output sits at input position i * down / up, so the first samples line up. Outside the
signal the filter sees zeros, so about half_width samples at each end are less accurate.
"""
return self._convert(x, self.up, self.down)
def decimate(self, x, factor: int | None = None) -> np.ndarray:
"""Low-pass filter, then keep every factor-th sample. factor defaults to the configured `down`."""
return self._convert(x, 1, self.config.down if factor is None else factor)
def interpolate(self, x, factor: int | None = None) -> np.ndarray:
"""Insert zeros, then low-pass filter: factor times as many samples. factor defaults to the configured `up`.
The filter is zero at every factor-th tap but the centre, so the original samples come through
unchanged apart from the overall gain normalization (a fraction of a percent).
"""
return self._convert(x, self.config.up if factor is None else factor, 1)
def output_length(self, n: int) -> int:
"""Number of samples `resample` returns for an input of n samples."""
return -(-n * self.up // self.down)
def output_rate(self, sample_rate: float) -> float:
"""Sample rate of the output, given the rate of the input."""
return sample_rate * self.up / self.down- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Make one second of a 10 kHz sine sampled at 48 kHz. Compare downsample(x, 3) with Resampler(ResamplerConfig(up=1, down=3)).resample(x), using an FFT of each to see where the energy lands. Then resample a 440 Hz sine from 44100 Hz to 48000 Hz with up=160 and down=147 and check output_length and output_rate.
Check on learning
- Why must the low-pass filter come before the samples are dropped when decimating, and not after?
A way to think about it
Once high and low frequencies give the same sample values they are the same data. Ask what a filter could look at to tell them apart afterwards.
- When upsampling, zero stuffing makes the signal quieter by a factor of . Where did the energy per sample go, and how does the filter put the level back?
A way to think about it
Only one sample in is non-zero, so the average is times smaller. Look at what the taps are scaled to sum to.
- For a 3 to 2 conversion the filter cutoff is set by the smaller of two Nyquist frequencies. Which one is smaller here, and which would it be for 2 to 3?
A way to think about it
Compute in each case and compare it with . The filter has to satisfy whichever limit is tighter.
- resample_fft is exact for a sine that completes a whole number of cycles in the record. Why does it ring for a signal that jumps between its last and first sample?
A way to think about it
The method assumes the record repeats for ever. A mismatch at the seam is a sharp step, and a step needs high frequencies that are being cut off.
- Upsampling by 160 and downsampling by 147 uses a filter thousands of taps long. Why so many, and is every multiplication needed?
A way to think about it
The filter runs at 160 times the input rate, so its cutoff is a tiny fraction of that rate. Then note that most of the stuffed samples it multiplies are zeros.