Overview
A filter replaces each sample with a weighted sum of itself and its neighbours. The weights decide which rhythms survive: equal weights average out fast wiggles and keep slow trends, which is a low-pass filter. There is an ideal set of weights that would keep everything below a cutoff frequency and remove everything above it, but it is infinitely long. So in practice you cut it to a finite length and taper its ends with a window, which costs a gradual transition where the ideal has a sharp edge. High-pass and band-pass filters are built from low-pass ones by subtraction. The median filter is a different tool: it removes isolated spikes without blurring edges.
A short history
Electrical filters date from the early telephone network, where they separated calls sharing a line. Norbert Wiener's work in the 1940s treated noise removal as a statistical problem. Digital filters followed in the 1960s, with window-based finite impulse response design, including James Kaiser's window, becoming a textbook method. John Tukey promoted the running median in the 1970s as a smoother that resists spikes.
How it works
- Choose which frequencies should pass: below a cutoff (lowpass), above it (highpass), between two edges (bandpass) or outside them (bandstop).
- Write the ideal low-pass weights for the cutoff: a sinc function centred in the middle of the filter.
- Multiply by a window such as Hamming so the weights fade to near zero at both ends, then scale them to sum to 1 so a constant signal passes unchanged.
- For a high-pass filter subtract the low-pass weights from a single unit impulse. For a band-pass filter subtract one low-pass filter from another with a higher cutoff.
- Slide the weights along the signal, and at each position take the weighted sum. The template centres the weights on each sample, so the output is not delayed.
- Inspect the result with gain or gain_db to see how much each frequency is scaled.
Watch out for
- No finite filter has a perfectly sharp edge. The transition band is roughly Hz wide for a Hamming window, so a narrow transition needs many taps.
- The first and last num_taps // 2 output samples are computed from mirrored data and are less reliable than the rest.
- The zero-delay result uses samples from both sides of each point, so it needs the whole signal in advance. A live system can only use past samples and must accept a delay of half the filter length.
- A moving average blurs sharp edges and lets some high frequencies leak through, because its frequency response has large side lobes.
- A median filter is not linear. It removes narrow spikes well, but it distorts smooth oscillations whose period is shorter than its window.
Use cases
When to use it
Removing hum, drift or high-frequency noise before analysis, isolating a band of interest, and preventing aliasing before a signal is downsampled.
In industry
- Medical devices
- ECG monitors apply a high-pass filter to remove baseline drift and a notch or low-pass filter to remove mains hum before the heartbeat is analysed.
- Audio
- Equalisers and loudspeaker crossovers split or shape frequency bands with low-pass, high-pass and band-pass filters.
- Sensors and control
- Embedded systems smooth accelerometer and temperature readings with moving averages, and use median filters to drop single-sample spikes.
Choosing it: what must hold
- A signal sampled at a uniform, known rate.
- Wanted and unwanted content that occupy different frequency bands, or noise that appears as isolated spikes.
- Cutoff frequencies below half the sample rate, and enough filter taps for the transition sharpness you need.
- Tolerance for the delay a filter adds, or an offline setting where it can be compensated.
When to choose something else
| If | Use instead |
|---|---|
| Signal and noise share the same frequency band | Wavelets, with denoising by thresholding detail coefficients |
| You need to see which frequencies are present before choosing cutoffs | Fourier transforms or spectral analysis |
| The goal is to change the sample rate | Resampling, which includes the needed low-pass filter |
Math foundations
Filtering is convolution
Each output sample is a weighted sum of input samples. The weights are called taps, and together they are the impulse response of the filter. Finite impulse response, or FIR, means there are finitely many.
Ideal low-pass weights
The weights whose frequency response is exactly 1 below the cutoff and 0 above it. Here runs over all integers and is the cutoff in cycles per sample. They never end, so they cannot be used as they are.
Windowed design
Shift the ideal weights to the middle of an -tap filter and taper them with a window. The taps stay symmetric, which gives every frequency the same delay (linear phase). The template then divides by their sum.
Other filter kinds
The impulse passes everything, so subtracting a low-pass filter leaves the high part. The difference of two low-pass filters keeps what lies between their cutoffs.
Frequency response
A sine at frequency comes out as a sine at the same frequency, scaled by . Gain in decibels is , so dB means one tenth of the amplitude.
Transition width
For a Hamming window, the width of the band between passing and blocking. Doubling the number of taps halves it. Other windows trade a wider transition for deeper suppression in the stop band.
Signal-to-noise ratio
The power of the clean signal over the power of what differs from it, in decibels. Each 10 dB is a factor of ten in power. Use it to measure whether a filter helped.
Symbols
- the input and output signals at sample
- the filter taps (taps in the code)
- the number of taps (num_taps), an odd number
- the sample rate in Hz
- the cutoff in Hz and in cycles per sample
- the lower and upper band edges (cutoff and cutoff_high)
- the window: Hamming, Hann, Blackman or rectangular
- the unit impulse: 1 at the centre tap and 0 elsewhere
- the complex frequency response
- the width of the transition band in Hz
- the clean reference signal
Worked by hand
First, the default filter: Hz with Hamming-windowed taps. Then smooth the five samples , a single spike, with a width-5 moving average and a width-5 median, and look at the centre sample.
With a 100 Hz cutoff the default filter moves from passing to blocking over roughly 33 Hz around the cutoff. The moving average spreads the spike into its neighbours and leaves a bump of height 2, while the median removes it entirely.
Visual example
Loading the example.
Try this
- Drop the taps to 11: the gain curve slopes so gently that the 120 Hz tone comes through.
- Switch to high-pass. The slow wave disappears and the 120 Hz tone and noise remain.
- Choose the rectangular window and look at the ripples beside the cutoff.
Code sample
import numpy as np
from impl import Filter, median_filter
from config import FilterConfig
sr = 1000.0
t = np.arange(2000) / sr
x = np.sin(2 * np.pi * 10 * t) + 0.5 * np.sin(2 * np.pi * 300 * t)
low = Filter(FilterConfig(kind="lowpass", sample_rate=sr, cutoff=100.0))
y = low.apply(x) # the 10 Hz sine; the 300 Hz part is gone
low.gain([10.0, 100.0, 300.0]) # about [1.0, 0.5, 0.0]
clean = median_filter(x, 5) # removes isolated spikesRead the implementation (111 lines)
"""Frequency-selective filtering and denoising.
`Filter` designs a linear-phase FIR filter by the windowed-sinc method (low-pass, high-pass, band-pass or
band-stop) and applies it with zero delay. `moving_average` and `median_filter` are the two standard
time-domain smoothers: the first for broadband noise, the second for isolated spikes.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import FilterConfig
except ImportError: # run from the template's own folder
from config import FilterConfig
def _window(name: str, n: int) -> np.ndarray:
phase = 2.0 * np.pi * np.arange(n) / (n - 1)
if name == "hamming":
return 0.54 - 0.46 * np.cos(phase)
if name == "hann":
return 0.5 - 0.5 * np.cos(phase)
if name == "blackman":
return 0.42 - 0.5 * np.cos(phase) + 0.08 * np.cos(2.0 * phase)
return np.ones(n)
def _pad(x: np.ndarray, half: int) -> np.ndarray:
"""Extend x by `half` samples on each side: mirrored when x is long enough, else by repeating the ends."""
return np.pad(x, half, mode="reflect" if x.size > half else "edge")
def moving_average(x, width: int) -> np.ndarray:
"""Mean of each sample and its neighbours in a centred window of odd `width`. Returns array of the same length."""
x = np.asarray(x, dtype=float).ravel()
if width < 1 or width % 2 == 0:
raise ValueError("width must be odd and at least 1")
return np.convolve(_pad(x, width // 2), np.full(width, 1.0 / width), mode="valid")
def median_filter(x, width: int) -> np.ndarray:
"""Median of each sample and its neighbours in a centred window of odd `width`. Returns array of the same length.
Removes spikes narrower than half the window and keeps edges sharp.
"""
x = np.asarray(x, dtype=float).ravel()
if width < 1 or width % 2 == 0:
raise ValueError("width must be odd and at least 1")
padded = _pad(x, width // 2)
index = np.arange(width)[None, :] + np.arange(x.size)[:, None]
return np.median(padded[index], axis=1)
def snr_db(clean, noisy) -> float:
"""Signal-to-noise ratio in decibels: 10 log10(power of clean / power of (noisy - clean))."""
clean, noisy = np.asarray(clean, dtype=float), np.asarray(noisy, dtype=float)
noise_power = float(np.mean((noisy - clean) ** 2))
return math.inf if noise_power == 0 else 10.0 * math.log10(float(np.mean(clean**2)) / noise_power)
class Filter:
"""Windowed-sinc FIR filter. `taps` holds the impulse response, array (num_taps,), symmetric."""
def __init__(self, config: FilterConfig | None = None) -> None:
self.config = config or FilterConfig()
self.taps = self._design()
def _lowpass(self, cutoff: float) -> np.ndarray:
"""Ideal low-pass impulse response (a sinc), windowed and scaled to gain 1 at 0 Hz."""
n = self.config.num_taps
fc = cutoff / self.config.sample_rate # cycles per sample
k = np.arange(n) - (n - 1) / 2.0
h = 2.0 * fc * np.sinc(2.0 * fc * k) * _window(self.config.window, n)
return h / h.sum()
def _design(self) -> np.ndarray:
cfg = self.config
delta = np.zeros(cfg.num_taps)
delta[cfg.num_taps // 2] = 1.0
if cfg.kind == "lowpass":
return self._lowpass(cfg.cutoff)
if cfg.kind == "highpass":
return delta - self._lowpass(cfg.cutoff) # everything minus the low part
band = self._lowpass(cfg.cutoff_high) - self._lowpass(cfg.cutoff)
return band if cfg.kind == "bandpass" else delta - band
def apply(self, x) -> np.ndarray:
"""Filter x, array (n,). Returns array (n,) aligned with the input (no delay).
The symmetric taps are centred on each sample, so the phase is untouched. The ends are extended by
reflection; the first and last num_taps // 2 samples are still less reliable than the rest.
"""
x = np.asarray(x, dtype=float).ravel()
return np.convolve(_pad(x, self.config.num_taps // 2), self.taps, mode="valid")
def frequency_response(self, freqs) -> np.ndarray:
"""Complex response H(f) at each frequency in Hz, array (m,) -> complex array (m,)."""
freqs = np.asarray(freqs, dtype=float)
k = np.arange(self.config.num_taps)
return np.exp(-2j * np.pi * np.outer(freqs, k) / self.config.sample_rate) @ self.taps
def gain(self, freqs) -> np.ndarray:
"""Magnitude |H(f)|: the factor by which a sine at each frequency is scaled."""
return np.abs(self.frequency_response(freqs))
def gain_db(self, freqs) -> np.ndarray:
"""Gain in decibels, 20 log10 |H(f)|, floored at -300 dB."""
return 20.0 * np.log10(np.maximum(self.gain(freqs), 1e-15))
__call__ = apply- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Build a 1000 Hz sampled signal that is the sum of a 5 Hz sine and a 200 Hz sine. Apply Filter() with the default low-pass config and confirm with gain([5, 100, 200]) that the 200 Hz part is removed. Then add a few large spikes to a clean sine and compare snr_db for moving_average(x, 5) and median_filter(x, 5).
Check on learning
- Why does cutting the ideal sinc to a finite length without a window give ripples in the frequency response, and how does tapering help?
A way to think about it
An abrupt cut is a multiplication by a rectangle. Consider what a sudden jump in the weights does compared with a smooth fade to zero.
- You need to separate 50 Hz from 60 Hz at a sample rate of 1000 Hz. Roughly how many Hamming taps does that take, and what is the cost?
A way to think about it
Set the transition width to about 10 Hz in the formula and solve for . Then think about delay in a live system and about the unreliable samples at each end.
- The taps are scaled to sum to 1. What does the sum of the taps equal in terms of the frequency response, and what would a sum of 0 mean?
A way to think about it
Evaluate at . A constant input is a signal of frequency zero.
- Spikes hit about one sample in fifty. Why is a median filter a better first step than a low-pass filter here?
A way to think about it
A spike contains all frequencies, so a linear filter can only spread it out. Ask what the middle value of a sorted window does with one extreme entry.
- The template filters with zero delay by centring the taps. Why is that impossible for a filter that runs on a live stream?
A way to think about it
Centring means using samples that come after the current one. Count how many future samples the output at time depends on.