Frequency Response, Phase and Group Delay
A thermocouple amplifier sampled at picks up mains hum. A colleague suggests averaging 20 samples. Another suggests 16, "because powers of two are faster". Which one removes the hum, how much does each one dent a signal, and how late does the filtered reading arrive? Time-domain reasoning gets stuck here; the frequency response answers all three questions at a glance. This lesson computes it for digital filters with scipy.signal.freqz, reads magnitude in dB, phase and group delay, and measures it the way you would on a bench. The underlying theory is in Frequency Response; the analog version with Bode plots is in Circuit Theory.
Sinusoids in, scaled sinusoids out
A complex exponential is an eigenfunction of every LTI system: put in and convolution gives
A real sinusoid therefore leaves as : same frequency, scaled amplitude, shifted phase. Here is the frequency in radians per sample. Three consequences matter in practice:
- is periodic with period (i.e. ): a digital filter cannot tell from , the aliasing of Sampling. For real it is also conjugate-symmetric, so only needs plotting.
- Gains are quoted in decibels, : is , is , is .
- The group delay (samples) is the delay of the envelope of a narrow-band signal near . A filter with constant group delay (linear phase) delays every frequency equally, so pulse shapes survive; a symmetric FIR filter with taps has samples at every frequency.
For a recursive filter, , the ratio of the coefficient polynomials evaluated on the unit circle (made precise by the z-transform).
Worked example: the mains-rejecting average
Given: , an -sample moving average , , with or .
Find: the gain at and , and the delay.
Solve: summing the geometric series,
- : zeros wherever is a whole number, i.e. at : the hum and all its harmonics are rejected. At : , . Delay samples .
- : zeros at multiples of , so is not on a zero; see the code for how much survives.
Check: an average over exactly one mains period integrates a full sine cycle to zero, which is the same statement in the time domain. In a country with mains this filter gives only at ; average samples instead (not an integer at , so change to ).
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import freqz, group_delay
fs = 1000.0
f_check = [10.0, 50.0, 100.0, 60.0]
fig, ax = plt.subplots(figsize=(7, 3.2))
for M in (20, 16):
b = np.ones(M) / M
_, H = freqz(b, 1, worN=f_check, fs=fs)
gains = ", ".join(f"{f:.0f} Hz {20 * np.log10(max(abs(h), 1e-12)):7.1f} dB" for f, h in zip(f_check, H))
_, gd = group_delay((b, 1), w=[10.0, 30.0], fs=fs)
print(f"M = {M}: {gains}; group delay {gd[0]:.1f} samples at 10 Hz, {gd[1]:.1f} at 30 Hz")
f, Hf = freqz(b, 1, worN=2048, fs=fs)
ax.plot(f, 20 * np.log10(np.maximum(np.abs(Hf), 1e-6)), label=f"{M}-sample average")
ax.set(xlabel="frequency (Hz)", ylabel="gain (dB)", ylim=(-60, 3), xlim=(0, 500))
ax.axvline(50, color="gray", ls=":")
ax.legend(); ax.grid(True, alpha=0.3)
plt.tight_layout(); plt.show()M = 20: 10 Hz -0.6 dB, 50 Hz -240.0 dB, 100 Hz -240.0 dB, 60 Hz -16.1 dB; group delay 9.5 samples at 10 Hz, 9.5 at 30 Hz
M = 16: 10 Hz -0.4 dB, 50 Hz -12.6 dB, 100 Hz -14.3 dB, 60 Hz -27.6 dB; group delay 7.5 samples at 10 Hz, 7.5 at 30 Hz
The is the floor max(abs(h), 1e-12) puts on an exact zero. The 16-sample average leaves about a quarter of the hum () and is the wrong choice despite being faster to divide. The group delay is the same at every frequency ( samples), as for every symmetric FIR filter. Do not ask for it exactly on a zero of (for : ): there the phase jumps by , the group delay is undefined and group_delay warns and returns nonsense.
Measuring a frequency response
A frequency response can be measured exactly the way a network analyser does it: apply one sine at a time, wait for the transient to end, and compare amplitude and phase of output and input. Here the "device" is a recursive exponential smoother, whose group delay, unlike the average's, varies with frequency:
import numpy as np
from scipy.signal import lfilter, freqz, group_delay
fs, a = 1000.0, 0.9
b_s, a_s = [1 - a], [1, -a] # y[n] = 0.9 y[n-1] + 0.1 x[n]
n = np.arange(4000)
print(" f (Hz) measured |H| dB phase deg freqz |H| dB phase deg group delay (samples)")
for f in (1.0, 10.0, 50.0, 200.0):
x = np.cos(2 * np.pi * f * n / fs)
y = lfilter(b_s, a_s, x)[2000:] # discard the start-up transient
e = np.exp(-2j * np.pi * f * n[2000:] / fs) # lock-in: correlate with the test tone
Hm = (y @ e) / (x[2000:] @ e)
_, H = freqz(b_s, a_s, worN=[f], fs=fs)
_, gd = group_delay((b_s, a_s), w=[f], fs=fs)
print(f"{f:7.0f} {20 * np.log10(abs(Hm)):14.2f} {np.degrees(np.angle(Hm)):9.2f} {20 * np.log10(abs(H[0])):11.2f} {np.degrees(np.angle(H[0])):9.2f} {gd[0]:6.2f}") f (Hz) measured |H| dB phase deg freqz |H| dB phase deg group delay (samples)
1 -0.02 -3.24 -0.02 -3.24 8.97
10 -1.32 -29.04 -1.32 -29.04 6.51
50 -9.92 -62.62 -9.92 -62.62 0.47
200 -20.98 -49.86 -20.98 -49.86 -0.42
The "measured" and computed values agree to the printed digits. The smoother delays slow changes by 9 samples () but fast ones much less, so a sharp edge comes out smeared and skewed: a non-linear-phase filter distorts waveforms even where it barely attenuates.
Guided lab: measure the 20-sample average on a microcontroller
Hand calculation. With and : at (a amplitude becomes ), a null at , at , at .
Simulation. Change f_check to [25.0, 50.5] in the first program: is attenuated by only about . Notches are narrow.
What you would measure. Run the average on a board sampling at from a timer interrupt, feed sines from a function generator ( amplitude on a offset, i.e. inside to ) and log the output's amplitude over the serial port. Expect to at . The notch depth depends on how exactly the generator and the board's timer agree: a mismatch (a clock error) limits it to about , and ADC noise sets a floor of a few LSB. Real mains frequency drifts too: in Continental Europe it stays within most of the time, with as the steady-state limit (EU System Operation Guideline 2017/1485, Annex III; other grids differ), so the rejection of real hum is tens of dB, not infinite.
Hazards and safe setup. Never connect the board to mains to "test with real hum": use the generator. USB power, signals kept within to (checked on a scope first), series resistor at the ADC pin.
Pitfalls
- Plotting against without converting to hertz with the actual (
freqz(..., fs=fs)does it for you). - Calling a filter "linear phase" because its phase plot looks straight in a narrow band.
- Reading group delay at a frequency where .
- Using for power ratios (power uses ).
Practice
- A 4-sample average runs at . Where are its nulls, and what is its delay in milliseconds?
- A filter gives at some frequency. What is that in dB?
- A symmetric FIR filter has 41 taps and runs at . What is its group delay?
Answer
- Multiples of (50 and up to ); delay samples .
- .
- samples .
Test yourself
A 20-sample moving average at 1 kSa/s has nulls at
- 20 Hz and its multiples
- 50 Hz and its multiples
- only 500 Hz
- it has no nulls
Group delay is defined as
- in dB
- the length of
The frequency response of a digital filter repeats every
- it never repeats
Why does a non-linear-phase filter distort a pulse even in its passband?
- it adds noise
- different frequency components are delayed by different amounts
- it is unstable
- it changes the sampling rate