Mini Project: Analyse a Measured Signal and Design a Filter to Spec
The milestone of this course is to analyse a measured signal and design a filter to meet explicit performance requirements. In this project you do it end to end for a condition-monitoring channel: an accelerometer on a gearbox, where an early bearing defect shows up as a weak tone near under much stronger shaft and gear-mesh vibration. You will look at the record, turn a vague wish ("isolate the bearing band") into a written specification, meet it with two competing designs, verify them against the mask and on the signal, check what fixed-point coefficients do, and write it up. Every step links to the lesson that teaches it.
1. The record
The "measured" record is synthetic so that everyone gets the same numbers and you can compare your answer with the truth: , , in units of (standard gravity). It contains the shaft rate (, ) and its second harmonic (, ), the gear-mesh tone (, ), the bearing tone (, ) and broadband noise ( rms). On a real machine you would record it with an IEPE accelerometer and a DAQ (Measurements); the analysis below does not use the known values.
Analyse it with a Welch PSD (Spectral Estimation): Hann windows of 1024 samples (bins of , enough to separate the lines) with overlap.
import numpy as np
from scipy.signal import welch, find_peaks
fs, T = 2000.0, 4.0
t = np.arange(int(fs * T)) / fs
rng = np.random.default_rng(2026)
comps = {25: 0.5, 50: 0.2, 157: 0.03, 400: 0.3} # Hz: amplitude in g (the hidden truth)
x = sum(a * np.sin(2 * np.pi * f * t + rng.uniform(0, 2 * np.pi)) for f, a in comps.items())
x = x + 0.05 * rng.standard_normal(len(t))
f, P = welch(x, fs=fs, window="hann", nperseg=1024, noverlap=512, scaling="spectrum") # g^2 per line
pk, _ = find_peaks(10 * np.log10(P), prominence=15)
print(f"record: {len(x)} samples, rms {np.std(x):.3f} g; Welch bins {f[1]:.2f} Hz")
for k in pk:
print(f" line at {f[k]:6.1f} Hz: {np.sqrt(2 * P[k]):.3f} g amplitude ({10 * np.log10(P[k] / P[pk].max()):6.1f} dB re largest)")
f2, Pd = welch(x, fs=fs, window="hann", nperseg=1024, noverlap=512, scaling="density")
floor = np.median(Pd[(f2 > 600) & (f2 < 900)])
print(f"noise floor {np.sqrt(floor) * 1e3:.2f} mg/sqrt(Hz) -> {np.sqrt(floor * fs / 2):.3f} g rms over 0..fs/2")record: 8000 samples, rms 0.440 g; Welch bins 1.95 Hz
line at 25.4 Hz: 0.489 g amplitude ( 0.0 dB re largest)
line at 50.8 Hz: 0.180 g amplitude ( -8.7 dB re largest)
line at 156.2 Hz: 0.028 g amplitude ( -24.9 dB re largest)
line at 400.4 Hz: 0.292 g amplitude ( -4.5 dB re largest)
noise floor 1.56 mg/sqrt(Hz) -> 0.049 g rms over 0..fs/2
Read it critically. The peaks sit on the nearest bins ( instead of ) and read 2 to 10 % low: scalloping of the Hann window, up to between bins (Leakage and Windows). For trending that is fine; for absolute amplitudes use a flat-top window. The noise floor matches the rms in the record.
2. The specification
The bearing tone is below the shaft line. To trend it, the band to must be isolated so that the strong lines leave less than of the bearing tone's amplitude in the output. The shaft harmonic at () must therefore be attenuated by at least ; we round the stopband requirement to and apply it to the gear mesh too.
| Item | Requirement |
|---|---|
| sampling rate | |
| passband | to , ripple |
| lower stopband | to , attenuation |
| upper stopband | to , attenuation |
| delay | (the trend is updated once a second) |
| cost | multiply-accumulates per sample on the target processor |
| phase | not required to be linear (the envelope is trended, not the waveform) |
This is the format of Filter Specifications: bands, tolerances, and the non-magnitude requirements that decide between FIR and IIR.
3. Two designs
FIR, equiripple (Equiripple FIR): the narrower transition band ( wide on the low side) sets the length; start from Kaiser's estimate and increase until the mask is met. IIR, elliptic in second-order sections (Analog Prototypes, Biquads): ellipord gives the order directly.
import numpy as np
from scipy.signal import remez, freqz, ellip, ellipord, sosfreqz, group_delay
fs = 2000.0
Ap, As = 0.5, 60.0
fp, fst1, fst2 = (130.0, 190.0), 70.0, 300.0
grid = np.linspace(0, fs / 2, 8001)
def check(H, name, macs, delay_ms):
g = 20 * np.log10(np.maximum(np.abs(H), 1e-12))
pb = g[(grid >= fp[0]) & (grid <= fp[1])]
sb = np.concatenate([g[grid <= fst1], g[grid >= fst2]])
ok = (pb.max() - pb.min() <= Ap) and (-sb.max() >= As)
print(f"{name:22s} ripple {pb.max() - pb.min():.3f} dB, stopband {-sb.max():.1f} dB, "
f"{macs} MAC/sample, delay {delay_ms}, {'MEETS' if ok else 'fails'} the mask")
return ok
dp, ds = (10 ** (Ap / 20) - 1) / (10 ** (Ap / 20) + 1), 10 ** (-As / 20)
n_est = int(np.ceil((-20 * np.log10(np.sqrt(dp * ds)) - 13) / (14.6 * (fp[0] - fst1) / fs) + 1))
print(f"Kaiser length estimate: {n_est} taps")
for n in range(n_est - 6, n_est + 30, 2):
if n % 2 == 0:
n += 1 # odd length: type I linear phase
h = remez(n, [0, fst1, fp[0], fp[1], fst2, fs / 2], [0, 1, 0], weight=[dp / ds, 1, dp / ds], fs=fs)
_, H = freqz(h, 1, worN=grid, fs=fs)
if check(H, f"FIR remez, {n} taps", n, f"{1e3 * (n - 1) / 2 / fs:.1f} ms (constant)"):
break
order, wn = ellipord(fp, (fst1, fst2), Ap, As, fs=fs)
sos = ellip(order, Ap, As, wn, btype="bandpass", fs=fs, output="sos")
_, H = sosfreqz(sos, worN=grid, fs=fs)
gd_sos = np.zeros(3) # group delay of a cascade = sum of the sections'
for s in sos:
_, g = group_delay((s[:3], s[3:]), w=[130.0, 157.0, 190.0], fs=fs)
gd_sos += g
check(H, f"IIR elliptic, order {2 * order}", 5 * len(sos),
f"{1e3 * gd_sos.min() / fs:.1f} to {1e3 * gd_sos.max() / fs:.1f} ms (varies)")
print(f"elliptic: {len(sos)} biquads; group delay at 130/157/190 Hz = {np.round(1e3 * gd_sos / fs, 1)} ms")Kaiser length estimate: 75 taps
FIR remez, 69 taps ripple 0.814 dB, stopband 55.6 dB, 69 MAC/sample, delay 17.0 ms (constant), fails the mask
FIR remez, 71 taps ripple 0.701 dB, stopband 56.8 dB, 71 MAC/sample, delay 17.5 ms (constant), fails the mask
FIR remez, 73 taps ripple 0.555 dB, stopband 59.1 dB, 73 MAC/sample, delay 18.0 ms (constant), fails the mask
FIR remez, 75 taps ripple 0.481 dB, stopband 60.3 dB, 75 MAC/sample, delay 18.5 ms (constant), MEETS the mask
IIR elliptic, order 8 ripple 0.500 dB, stopband 60.0 dB, 20 MAC/sample, delay 13.6 to 46.3 ms (varies), MEETS the mask
elliptic: 4 biquads; group delay at 130/157/190 Hz = [46.3 13.6 32.7] ms
Kaiser's estimate (75 taps) was right on: 73 taps miss the stopband by , 75 meet it with to spare. The 8th-order elliptic filter (four biquads) meets the mask exactly, as ellipord designs it to, for 20 multiply-accumulates per sample against 75 (38 with a symmetric-FIR routine that adds mirrored samples before multiplying). Its group delay varies from to across the passband, largest at the band edges: inside the limit, but with little margin.
4. Verify on the signal and in fixed point
A mask check is necessary but not sufficient. Run both filters on the record and compare the output with the known bearing component; then quantise the coefficients to the target's word length (Q15, 16-bit) and check the mask again (Filter Structures and Fixed Point).
import numpy as np
from scipy.signal import remez, ellip, freqz, sosfreqz, lfilter, sosfilt
fs, T = 2000.0, 4.0
t = np.arange(int(fs * T)) / fs
rng = np.random.default_rng(2026)
comps = {25: 0.5, 50: 0.2, 157: 0.03, 400: 0.3}
phases = {f: rng.uniform(0, 2 * np.pi) for f in comps} # same draws as in step 1
x = sum(a * np.sin(2 * np.pi * f * t + phases[f]) for f, a in comps.items()) + 0.05 * rng.standard_normal(len(t))
truth = 0.03 * np.sin(2 * np.pi * 157 * t + phases[157])
dp, ds = (10 ** (0.5 / 20) - 1) / (10 ** (0.5 / 20) + 1), 1e-3
h = remez(75, [0, 70, 130, 190, 300, 1000], [0, 1, 0], weight=[dp / ds, 1, dp / ds], fs=fs)
sos = ellip(4, 0.5, 60, [130, 190], btype="bandpass", fs=fs, output="sos")
settle = int(0.5 * fs) # ignore the first 0.5 s (start-up transient)
d = (len(h) - 1) // 2 # FIR delay in samples, compensated below
y_fir = lfilter(h, 1, x)[d:]
y_iir = sosfilt(sos, x)
def amp157(y, tt):
return 2 * abs(np.mean(y * np.exp(-2j * np.pi * 157 * tt)))
for name, y, tt in (("FIR", y_fir[settle:], t[settle:len(y_fir)]), ("IIR", y_iir[settle:], t[settle:])):
print(f"{name}: 157 Hz amplitude {1e3 * amp157(y, tt):.2f} mg (true 30.00), output rms {1e3 * np.std(y):.2f} mg "
f"(tone alone {1e3 * 0.03 / np.sqrt(2):.2f}, plus in-band noise)")
r = y_fir[settle:] - truth[settle:len(y_fir)]
print(f"FIR output minus the true tone: rms {1e3 * np.std(r):.2f} mg (noise in the 60 Hz passband: {1e3 * 0.05 * np.sqrt(60 / 1000):.2f} mg)")
grid = np.linspace(0, fs / 2, 8001)
def margins(H):
g = 20 * np.log10(np.maximum(np.abs(H), 1e-12))
pb = g[(grid >= 130) & (grid <= 190)]
sb = np.concatenate([g[grid <= 70], g[grid >= 300]])
return pb.max() - pb.min(), -sb.max()
hq = np.round(h * 2**15) / 2**15 # Q15 FIR coefficients
sosq = np.round(sos * 2**14) / 2**14 # Q1.14 biquad coefficients (|a1| can reach 2)
for name, H in (("FIR float", freqz(h, 1, worN=grid, fs=fs)[1]), ("FIR Q15", freqz(hq, 1, worN=grid, fs=fs)[1]),
("IIR float", sosfreqz(sos, worN=grid, fs=fs)[1]), ("IIR Q1.14", sosfreqz(sosq, worN=grid, fs=fs)[1])):
rip, att = margins(H)
print(f"{name:10s}: ripple {rip:.3f} dB, stopband {att:.1f} dB")
print(f"largest IIR pole radius: float {max(np.abs(np.roots(s[3:])).max() for s in sos):.5f}, "
f"Q1.14 {max(np.abs(np.roots(s[3:])).max() for s in sosq):.5f}")FIR: 157 Hz amplitude 29.44 mg (true 30.00), output rms 25.72 mg (tone alone 21.21, plus in-band noise)
IIR: 157 Hz amplitude 28.42 mg (true 30.00), output rms 23.67 mg (tone alone 21.21, plus in-band noise)
FIR output minus the true tone: rms 15.18 mg (noise in the 60 Hz passband: 12.25 mg)
FIR float : ripple 0.481 dB, stopband 60.3 dB
FIR Q15 : ripple 0.482 dB, stopband 59.0 dB
IIR float : ripple 0.500 dB, stopband 60.0 dB
IIR Q1.14 : ripple 0.514 dB, stopband 59.8 dB
largest IIR pole radius: float 0.98755, Q1.14 0.98756
On the signal, both filters recover the bearing tone within about ( and against : passband ripple plus the noise that shares its frequency bins). The output still contains the in-band noise, which no filter can remove; the residual ( rms) is a little more than the noise in an ideal band () because the real filter also passes part of its transition bands.
The fixed-point check is the surprise: both designs fail the mask after rounding the coefficients, the FIR stopband by , the IIR passband ripple by and its stopband by . Designs that meet a mask exactly in floating point have no margin left for implementation. The fix is to design with margin (for example and ), or to use 32-bit coefficients; the pole radii barely move ( to ), so the biquads stay comfortably stable.
5. Decide and write up
Decision record. Both designs meet the specification in floating point, and both need some design margin (the and suggested above are comfortable) to survive 16-bit coefficients. The elliptic filter costs about a quarter of the multiplications of the FIR filter, but its group delay varies across the band (and approaches the delay limit at the band edges); since the project trends the envelope, not the waveform, that is acceptable. The FIR filter wins if the waveform shape matters (for example, for time-synchronous averaging of the gear signal) or if the target has a fast MAC unit and a symmetric-FIR library routine.
Report template.
- Purpose and requirement: the measurand (bearing-band vibration), the specification table, where each number came from.
- Data: sensor, mounting, sampling rate, record length, anti-alias filter (Anti-Alias Filters), units and calibration.
- Analysis: PSD method (window, segment length, overlap, number of averages, scaling), the lines found, the noise floor, the scalloping caveat.
- Design: methods tried, orders or lengths, cost, delay, phase behaviour; figures of the magnitude response over the mask.
- Verification: mask margins (passband ripple, worst stopband attenuation) in floating and fixed point; error of the filtered output against the reference; settling time after start-up.
- Implementation notes: structure (direct-form II transposed biquads, symmetric FIR), word lengths, scaling, block size and latency (Real-Time DSP).
- Conclusion: which design is recommended and why; open risks.
6. Bench version (optional)
Hand calculation. Use two generator channels as the "machine": a tone of and a tone of , summed with resistors around a offset; after the band-pass, the residue should be about or less (), far below the tone.
Simulation. The programs above, with your board's sampling rate.
What you would measure. Sample at on a microcontroller, run the chosen filter, and stream input and output. Expect the amplitude within of its input and the residue at or below the ADC noise (a 12-bit ADC with a range has an LSB of , so the residue will be hidden in the noise: verify the stopband with a larger amplitude if needed).
Hazards and safe setup. Generators and a USB-powered board only, never a real motor's supply; both channels checked on a scope to stay within to at the ADC; series resistors. Real machines (mains-powered drives, rotating parts) are outside this lab: the generator setup gives the same signals safely.
Extensions
- Add the envelope stage: rectify or take (Modulation), low-pass and decimate (Multirate), and trend the envelope spectrum at the shaft rate.
- Repeat the design at and compare the FIR length; then decimate by 4 first.
- Watch the bearing tone grow over a simulated week (raise its amplitude day by day) and set an alarm threshold from the noise statistics (Correlation and Matched Filtering).
Test yourself
Why is the stopband requirement in this project 60 dB?
- it is a standard value
- the 0.2 g line must leave less than 1 % of the 0.03 g tone, which needs about 56.5 dB
- elliptic filters always give 60 dB
- the ADC has 10 bits
The equiripple FIR needs far more multiplications than the elliptic IIR because
- FIR filters are always unstable
- an FIR filter has no poles, so a sharp transition needs many taps
- the sampling rate is too high
- FIR filters cannot be band-pass
Which requirement would make the FIR design the better choice?
- lowest cost
- a linear phase (constant delay) so the waveform shape survives
- lowest delay
- highest stopband attenuation
The Welch peaks read a few percent below the true amplitudes because of
- aliasing
- the Hann window's scalloping between bins
- quantisation
- the anti-alias filter