TExcelTAD
Home › Signals, Systems & Digital Filters for Engineers › Mini Project: Analyse a Measured Signal and Design a Filter to Spec

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 157 Hz157\ \text{Hz} 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: fs=2 kSa/sf_s = 2\ \text{kSa/s}, 4 s4\ \text{s}, in units of gg (standard gravity). It contains the shaft rate (25 Hz25\ \text{Hz}, 0.5 g0.5\ g) and its second harmonic (50 Hz50\ \text{Hz}, 0.2 g0.2\ g), the gear-mesh tone (400 Hz400\ \text{Hz}, 0.3 g0.3\ g), the bearing tone (157 Hz157\ \text{Hz}, 0.03 g0.03\ g) and broadband noise (0.05 g0.05\ g 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 1.95 Hz1.95\ \text{Hz}, enough to separate the lines) with 50 %50\,\% overlap.

python · try it yourself
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 (25.425.4 instead of 25 Hz25\ \text{Hz}) and read 2 to 10 % low: scalloping of the Hann window, up to 1.4 dB1.4\ \text{dB} between bins (Leakage and Windows). For trending that is fine; for absolute amplitudes use a flat-top window. The noise floor matches the 0.05 g0.05\ g rms in the record.

2. The specification

The bearing tone is 24.9 dB24.9\ \text{dB} below the shaft line. To trend it, the band 130130 to 190 Hz190\ \text{Hz} must be isolated so that the strong lines leave less than 1 %1\,\% of the bearing tone's amplitude in the output. The shaft harmonic at 50 Hz50\ \text{Hz} (0.2 g0.2\ g) must therefore be attenuated by at least 20log⁡10(0.2/0.0003)=56.5 dB20\log_{10}(0.2/0.0003) = 56.5\ \text{dB}; we round the stopband requirement to 60 dB60\ \text{dB} and apply it to the gear mesh too.

Item Requirement
sampling rate 2 kSa/s2\ \text{kSa/s}
passband 130130 to 190 Hz190\ \text{Hz}, ripple ≤0.5 dB\le 0.5\ \text{dB}
lower stopband 00 to 70 Hz70\ \text{Hz}, attenuation ≥60 dB\ge 60\ \text{dB}
upper stopband 300 Hz300\ \text{Hz} to fs/2f_s/2, attenuation ≥60 dB\ge 60\ \text{dB}
delay ≤50 ms\le 50\ \text{ms} (the trend is updated once a second)
cost ≤100\le 100 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 (60 Hz60\ \text{Hz} 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.

python · try it yourself
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 0.9 dB0.9\ \text{dB}, 75 meet it with 0.3 dB0.3\ \text{dB} 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 13.613.6 to 46.3 ms46.3\ \text{ms} across the passband, largest at the band edges: inside the 50 ms50\ \text{ms} 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).

python · try it yourself
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 0.5 dB0.5\ \text{dB} (29.429.4 and 28.4 mg28.4\ \text{mg} against 30 mg30\ \text{mg}: 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 (15.2 mg15.2\ \text{mg} rms) is a little more than the noise in an ideal 60 Hz60\ \text{Hz} band (12.2 mg12.2\ \text{mg}) 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 1.0 dB1.0\ \text{dB}, the IIR passband ripple by 0.014 dB0.014\ \text{dB} and its stopband by 0.2 dB0.2\ \text{dB}. Designs that meet a mask exactly in floating point have no margin left for implementation. The fix is to design with margin (for example 63 dB63\ \text{dB} and 0.4 dB0.4\ \text{dB}), or to use 32-bit coefficients; the pole radii barely move (0.987550.98755 to 0.987560.98756), 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 63 dB63\ \text{dB} and 0.4 dB0.4\ \text{dB} 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.

  1. Purpose and requirement: the measurand (bearing-band vibration), the specification table, where each number came from.
  2. Data: sensor, mounting, sampling rate, record length, anti-alias filter (Anti-Alias Filters), units and calibration.
  3. Analysis: PSD method (window, segment length, overlap, number of averages, scaling), the lines found, the noise floor, the scalloping caveat.
  4. Design: methods tried, orders or lengths, cost, delay, phase behaviour; figures of the magnitude response over the mask.
  5. 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.
  6. Implementation notes: structure (direct-form II transposed biquads, symmetric FIR), word lengths, scaling, block size and latency (Real-Time DSP).
  7. Conclusion: which design is recommended and why; open risks.

6. Bench version (optional)

Hand calculation. Use two generator channels as the "machine": a 157 Hz157\ \text{Hz} tone of 30 mV30\ \text{mV} and a 50 Hz50\ \text{Hz} tone of 200 mV200\ \text{mV}, summed with resistors around a 1.5 V1.5\ \text{V} offset; after the band-pass, the 50 Hz50\ \text{Hz} residue should be about 0.2 mV0.2\ \text{mV} or less (60 dB60\ \text{dB}), far below the 30 mV30\ \text{mV} tone.

Simulation. The programs above, with your board's sampling rate.

What you would measure. Sample at 2 kSa/s2\ \text{kSa/s} on a microcontroller, run the chosen filter, and stream input and output. Expect the 157 Hz157\ \text{Hz} amplitude within ±0.5 dB\pm 0.5\ \text{dB} of its input and the 50 Hz50\ \text{Hz} residue at or below the ADC noise (a 12-bit ADC with a 3.3 V3.3\ \text{V} range has an LSB of 0.8 mV0.8\ \text{mV}, so the residue will be hidden in the noise: verify the stopband with a larger 50 Hz50\ \text{Hz} 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 00 to 3 V3\ \text{V} at the ADC; 1 kΩ1\ \text{k}\Omega 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 ∣analytic signal∣\lvert \text{analytic signal} \rvert (Modulation), low-pass and decimate (Multirate), and trend the envelope spectrum at the shaft rate.
  • Repeat the design at fs=8 kSa/sf_s = 8\ \text{kSa/s} 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?

  1. it is a standard value
  2. the 0.2 g line must leave less than 1 % of the 0.03 g tone, which needs about 56.5 dB
  3. elliptic filters always give 60 dB
  4. the ADC has 10 bits

The equiripple FIR needs far more multiplications than the elliptic IIR because

  1. FIR filters are always unstable
  2. an FIR filter has no poles, so a sharp transition needs many taps
  3. the sampling rate is too high
  4. FIR filters cannot be band-pass

Which requirement would make the FIR design the better choice?

  1. lowest cost
  2. a linear phase (constant delay) so the waveform shape survives
  3. lowest delay
  4. highest stopband attenuation

The Welch peaks read a few percent below the true amplitudes because of

  1. aliasing
  2. the Hann window's scalloping between bins
  3. quantisation
  4. the anti-alias filter