Applications: Audio, Sensor Filtering and Communications
The earlier lessons each solved one problem. Real products chain them: a sensor, an anti-alias filter, an ADC, a decimator, a filter, a feature such as a level or a spectrum, and a decision. This lesson walks through three short case studies that use the whole toolkit: cleaning an audio recording and metering it, rejecting spikes and noise in an industrial sensor, and detecting digital data in noise, a preview of the Communications course. Each one starts from a requirement and ends with numbers you could check on a bench.
Case 1: audio clean-up and level metering
Requirement. A voice recording has a DC offset from the interface, low-frequency rumble (handling noise near ) and hum. Remove the offset and rumble with a high-pass filter that leaves speech (above about ) within , notch the hum, and report the level in dBFS (decibels relative to a full-scale sine, so a full-scale sine is rms by the common AES convention).
Design. A 4th-order Butterworth high-pass at in second-order sections (Biquads) and a notch at (Poles and Zeros). Run them with sosfilt in blocks, the way a real-time plug-in would (Real-Time DSP).
import numpy as np
from scipy.signal import butter, iirnotch, sosfilt, tf2sos, sosfreqz
fs = 48000.0
t = np.arange(int(1.0 * fs)) / fs
rng = np.random.default_rng(2)
voice = 0.2 * np.sin(2 * np.pi * 220 * t) + 0.1 * np.sin(2 * np.pi * 1200 * t) # stand-in for speech
x = voice + 0.05 + 0.1 * np.sin(2 * np.pi * 20 * t) + 0.03 * np.sin(2 * np.pi * 50 * t) + 1e-3 * rng.standard_normal(len(t))
sos = np.vstack([butter(4, 60, btype="highpass", fs=fs, output="sos"),
tf2sos(*iirnotch(50, Q=10, fs=fs))])
_, H = sosfreqz(sos, worN=[20.0, 50.0, 100.0, 220.0, 1200.0], fs=fs)
print("chain gain (dB) at 20/50/100/220/1200 Hz:", " ".join(f"{20 * np.log10(max(abs(h), 1e-12)):.1f}" for h in H))
y, zi = np.zeros_like(x), np.zeros((sos.shape[0], 2))
for k in range(0, len(x), 256): # 256-sample blocks, state carried over
y[k:k + 256], zi = sosfilt(sos, x[k:k + 256], zi=zi)
def dbfs(sig): # rms relative to a full-scale sine (amplitude 1)
return 20 * np.log10(np.sqrt(np.mean(sig**2)) / (1 / np.sqrt(2)))
def tone(sig, f): # amplitude of one component (whole periods in 0.5 s)
return 2 * abs(np.mean(sig * np.exp(-2j * np.pi * f * t[late])))
late = slice(int(0.5 * fs), None) # after the filters have settled
print(f"level: input {dbfs(x[late]):.1f} dBFS, output {dbfs(y[late]):.1f} dBFS, voice alone {dbfs(voice[late]):.1f} dBFS")
print(f"DC {np.mean(x[late]):.3f} -> {np.mean(y[late]):.5f}; 20 Hz {tone(x[late], 20):.4f} -> {tone(y[late], 20):.4f}; "
f"50 Hz {tone(x[late], 50):.4f} -> {tone(y[late], 50):.5f}")chain gain (dB) at 20/50/100/220/1200 Hz: -38.2 -209.4 -0.1 -0.0 -0.0
level: input -11.8 dBFS, output -13.0 dBFS, voice alone -13.0 dBFS
DC 0.050 -> 0.00000; 20 Hz 0.1000 -> 0.0012; 50 Hz 0.0300 -> 0.00000
Check against the requirement. DC, rumble and hum are gone (the at is the exact zero of the notch, limited by rounding), and the output level equals the voice alone. The chain is at , inside the allowance, because a notch with is only wide. A wider notch (, more tolerant of a drifting hum frequency) costs at : still within the budget, but half the margin is gone (and with the high-pass moved to as well, the chain is and fails). Reading the requirement against the response of the whole chain, not the design intent of each filter, is the habit this course aims to build.
Case 2: industrial sensor with spikes
Requirement. A pressure transmitter sampled at shows occasional one-sample spikes from a nearby contactor, plus white noise. The control loop needs the step response to settle within and spikes reduced below of full scale.
Design. A linear filter spreads a spike out instead of removing it (Discrete Convolution). A median filter, a non-linear filter, removes isolated outliers entirely and keeps steps sharp, then a short moving average reduces the noise.
import numpy as np
from scipy.signal import medfilt, lfilter
rng = np.random.default_rng(4)
n = np.arange(200)
p = np.where(n >= 80, 60.0, 40.0) # % of full scale: step from 40 % to 60 %
x = p + 0.3 * rng.standard_normal(len(n))
spikes = [30, 120, 150]
x[spikes] += [25.0, -30.0, 20.0] # contactor spikes
y_ma = lfilter(np.ones(9) / 9, 1, x) # 9-sample moving average only
y_med = lfilter(np.ones(3) / 3, 1, medfilt(x, 5)) # 5-point median, then 3-sample average
def worst_spike(y):
return max(abs(y[k:k + 10] - p[k:k + 10]).max() for k in spikes)
def settle(y, tol=0.5): # samples after the step until within tol of 60 %
bad = np.where(np.abs(y[80:] - 60) > tol)[0]
return int(bad[bad < 30].max()) + 1 if np.any(bad < 30) else 0
for name, y in (("moving average 9", y_ma), ("median 5 + avg 3", y_med)):
print(f"{name:17s}: worst spike residue {worst_spike(y):5.2f} %FS, settles in {settle(y)} samples, "
f"noise {np.std(y[160:200] - 60):.3f} %FS")moving average 9 : worst spike residue 3.32 %FS, settles in 8 samples, noise 0.072 %FS
median 5 + avg 3 : worst spike residue 0.28 %FS, settles in 2 samples, noise 0.102 %FS
The moving average leaves spikes of (a spike divided by 9) and fails the requirement; the median-based chain removes them ( is noise) and settles faster ( samples instead of 8, both well inside ), at the cost of a little more noise ( against of full scale, since 3 samples are averaged instead of 9). The median filter is not linear, so it has no frequency response: test it with the signals it will meet, as here.
Case 3: detecting bits in noise
Requirement. Send binary data at as rectangular pulses (binary phase-shift keying at baseband), sampled at samples per bit, through a channel adding white noise, and estimate the bit error rate (BER) at .
Design. The receiver is a matched filter (an 8-sample sum for a rectangular pulse) sampled at the end of each bit, followed by a sign decision. Theory gives , with the Gaussian tail probability.
import numpy as np
from scipy.special import erfc
rng = np.random.default_rng(9)
nbits, sps = 200000, 8
ebn0_db = 6.0
bits = rng.integers(0, 2, nbits)
sym = 2.0 * bits - 1.0
tx = np.repeat(sym, sps) # rectangular pulses, 1 V per sample
Eb = sps * 1.0 # energy per bit (sum of squares)
N0 = Eb / 10 ** (ebn0_db / 10)
rx = tx + np.sqrt(N0 / 2) * rng.standard_normal(len(tx)) # white noise, variance N0/2 per sample
mf = rx.reshape(nbits, sps).sum(axis=1) # matched filter sampled once per bit
ber = np.mean((mf > 0) != (bits == 1))
theory = 0.5 * erfc(np.sqrt(10 ** (ebn0_db / 10))) # Q(sqrt(2 Eb/N0))
print(f"Eb/N0 = {ebn0_db:.0f} dB: simulated BER {ber:.2e} ({int(ber * nbits)} errors in {nbits} bits), theory {theory:.2e}")
naive = np.mean((rx[sps // 2::sps] > 0) != (bits == 1)) # one sample per bit, no filter
print(f"without the matched filter (one sample per bit): BER {naive:.2e}")Eb/N0 = 6 dB: simulated BER 2.32e-03 (464 errors in 200000 bits), theory 2.39e-03
without the matched filter (one sample per bit): BER 1.60e-01
The matched filter collects the energy of all 8 samples ( of processing gain) and meets the theory; deciding from one sample per bit wastes it and gives an error rate about 70 times worse. With 464 errors the simulated BER is uncertain by about (), enough to agree with ; count at least 100 errors before trusting a BER estimate. Pulse shaping, bandwidth, synchronisation and coding are the subject of the communications course.
Guided lab: an end-to-end audio measurement
Hand calculation. For the Case 1 chain: at , a null at , at , flat above.
Simulation. In Case 1, change the notch's Q to 2, then raise the high-pass corner to , and read the gains at and each time: the requirement trade-off in numbers.
What you would measure. Play a stepped sine sweep (20 Hz to 2 kHz) from a computer's audio output into a USB audio interface's line input through a cable (no loudspeaker needed), record at , run the chain on the recording and compare the per-frequency level before and after. Expect agreement with sosfreqz within about in the passband (the interface's own response is flat there to roughly that level); the notch depth is limited by the sweep's frequency accuracy and by the interface's noise floor (roughly to wideband, depending on the interface), not by the filter's exact null.
Hazards and safe setup. Line-level audio only (about ); start with the output volume low; no mains-powered equipment is opened, and headphones, if used, are kept at a comfortable level.
Pitfalls
- Specifying filters by their design parameters and never checking the cascade against the requirement.
- Using a linear filter on impulsive interference: medians or clipping first, linear smoothing after.
- Judging a BER from a handful of errors.
- Metering dBFS with inconsistent references (AES17 calls a full-scale sine , so a full-scale square wave reads , but some meters show the full-scale sine as ; state the convention).
Practice
- A full-scale sine has amplitude 1. What is the level in dBFS of a sine of amplitude 0.1?
- A 5-point median filter removes one-sample spikes. Does it also remove two-sample bursts of the same size next to each other, and three-sample ones?
- At , BPSK has a BER of about . How many bits must you simulate to see about 100 errors?
Answer
- .
- A 5-point median ignores up to 2 outliers in its window, so a 2-sample burst is also removed; a burst of 3 or more samples is not. (A 3-point median would fail on the 2-sample burst.)
- About bits.
Test yourself
Why is a median filter preferred to a moving average for isolated spikes?
- it is linear
- it removes outliers instead of spreading them, and keeps steps sharp
- it has a narrower passband
- it needs no memory
The bit error rate of BPSK with a matched filter in white noise is
- independent of noise
A filter chain meets its design targets individually but fails the requirement at 100 Hz. The best next step is
- ignore it
- check the cascade's response against the requirement and move corners or Q
- add more filters
- raise the sampling rate
A one-second recording at 48 kSa/s is processed in 256-sample blocks with sosfilt. To get the same output as one call on the whole signal you must
- reset the filter state for each block
- carry the filter state
zifrom block to block - overlap blocks by 50 %
- use
filtfilt