Impulse Response and Discrete Convolution
A load cell is read at and the firmware averages the last five samples to calm the display. A colleague asks two questions: how long after a weight is placed does the reading settle, and what does the averager do to a short knock on the bench? Both answers come from one sequence, the impulse response (what the averager outputs when the input is a single 1 followed by zeros), and one operation, convolution. For any LTI system, the output for any input is the input convolved with . This lesson is the working engineer's version of Convolution and Impulse Response: by hand, by matrix and by numpy.
From impulses to the convolution sum
Any sequence is a sum of scaled, shifted impulses: . Linearity lets us push the sum through the system, and time invariance says the response to is . So
Read the second form as a recipe: the output now is a weighted sum of the present and past inputs, and the weights are the impulse response. For a causal FIR filter with taps , that is exactly the code running in the firmware.
Flip and slide. To get one output sample by hand, flip to , slide it by , multiply sample by sample with , and add.
Useful facts.
- Lengths: an input of samples and an impulse response of samples give output samples.
- Sums: , a quick check on any hand result. The sum of is the DC gain.
- Commutative (), associative (a cascade of filters is one filter with ) and distributive (parallel branches add their impulse responses).
- Step response , the running sum of ; its final value is the DC gain.
- FIR systems have a finite ; IIR systems (with feedback) have an infinite one, such as for the exponential smoother .
Worked example: a three-sample input through a three-tap filter
Given: for and a filter (dimensionless) for .
Find: .
Solve: the output has samples:
Check: and .
Three ways to compute it
import numpy as np
from scipy.signal import lfilter
from scipy.linalg import toeplitz
x = np.array([2.0, 1.0, -1.0])
h = np.array([1.0, 0.5, 0.25])
# 1. Direct double loop: the definition
y_loop = np.zeros(len(x) + len(h) - 1)
for n in range(len(y_loop)):
for k in range(len(h)):
if 0 <= n - k < len(x):
y_loop[n] += h[k] * x[n - k]
# 2. Library convolution
y_np = np.convolve(x, h)
# 3. Convolution as a matrix (Toeplitz): y = H x
col = np.concatenate([h, np.zeros(len(x) - 1)])
H = toeplitz(col, np.zeros(len(x)))
y_mat = H @ x
# 4. As a filter (the way firmware runs it); pad the input to flush the filter
y_filt = lfilter(h, [1.0], np.concatenate([x, np.zeros(len(h) - 1)]))
print("loop :", y_loop)
print("conv :", y_np)
print("matrix:", y_mat)
print("lfilter:", y_filt)
print("H =\n", H)
print("sum check:", y_np.sum(), "=", x.sum() * h.sum())loop : [ 2. 2. 0. -0.25 -0.25]
conv : [ 2. 2. 0. -0.25 -0.25]
matrix: [ 2. 2. 0. -0.25 -0.25]
lfilter: [ 2. 2. 0. -0.25 -0.25]
H =
[[1. 0. 0. ]
[0.5 1. 0. ]
[0.25 0.5 1. ]
[0. 0.25 0.5 ]
[0. 0. 0.25]]
sum check: 3.5 = 3.5
The matrix form shows why convolution is linear algebra: each column of is the impulse response shifted by one more sample. It is also how least-squares deconvolution and equalisers are set up.
The load-cell averager
Back to the opening question. A five-sample moving average has for , DC gain 1, and a step response that ramps over 5 samples. Its output lags the input by samples (the centre of mass of ), at .
import numpy as np
from scipy.signal import lfilter
fs = 100.0 # Sa/s
h_ma = np.ones(5) / 5 # 5-sample moving average
a = 0.8 # exponential smoother with a similar delay
rng = np.random.default_rng(3)
n = np.arange(80)
weight = np.where(n >= 5, 2.000, 0.0) # 2.000 kg placed at n = 5
knock = np.where(n == 60, 0.5, 0.0) # a 0.5 kg knock lasting one sample
x = weight + knock + 0.02 * rng.standard_normal(len(n))
y_ma = lfilter(h_ma, 1.0, x)
y_exp = lfilter([1 - a], [1, -a], x)
s_ma = np.cumsum(h_ma) # step response = running sum of h
print("MA step response:", np.round(s_ma, 2), "-> settles after", len(h_ma), "samples =", 1e3 * len(h_ma) / fs, "ms")
print(f"knock peak: raw {x[60] - 2:.3f} kg above the load, MA {y_ma[60:66].max() - 2:.3f} kg, exp {y_exp[60:66].max() - 2:.3f} kg")
z = rng.standard_normal(20000) # long noise-only run for the noise gain
print(f"noise std ratio out/in: MA {lfilter(h_ma, 1.0, z).std() / z.std():.3f}, exp {lfilter([1 - a], [1, -a], z).std() / z.std():.3f}")
k99 = int(np.argmax(np.cumsum((1 - a) * a ** np.arange(60)) >= 0.99))
print(f"exponential smoother reaches 99 % after {k99 + 1} samples = {1e3 * (k99 + 1) / fs:.0f} ms")MA step response: [0.2 0.4 0.6 0.8 1. ] -> settles after 5 samples = 50.0 ms
knock peak: raw 0.467 kg above the load, MA 0.095 kg, exp 0.092 kg
noise std ratio out/in: MA 0.447, exp 0.335
exponential smoother reaches 99 % after 21 samples = 210 ms
The averager settles in exactly 5 samples, while the exponential smoother (an IIR filter with an infinite ) never quite gets there: 99 % takes 21 samples. In exchange, the smoother removes more white noise: the noise standard deviation is scaled by , which is for the averager and for the smoother, as the long noise run confirms. A one-sample knock becomes a five-sample bump one fifth as high: convolution spreads it out by the length of .
Guided lab: a moving average on a microcontroller ADC
Hand calculation. Sample a square wave ( to ) at and apply an 8-sample moving average. Each edge becomes a ramp lasting 8 samples (), the flat parts keep their level (DC gain 1), and the output lags by samples ().
Simulation. Change h_ma above to np.ones(8) / 8, fs to 1000 and the input to a square wave; check the ramp length with np.cumsum(h_ma).
What you would measure. Stream raw and filtered samples over the serial port and plot both. Expect edge ramps of samples (the edge falls at a random point between two samples) and plateaus within a few LSB of the raw values. If the plateaus differ by more, the coefficient sum is not 1 (a common bug is dividing by 7 or using integer division too early).
Hazards and safe setup. Generator output set to to (offset and amplitude checked on a scope before connecting), a series resistor into the ADC pin, board powered from USB only.
Pitfalls
- Using
np.convolve(x, h, 'same')in a real-time comparison: it centres the output and hides the filter's delay. - Filtering a block with
lfilterand forgetting that the last output samples are still in the filter (flush with zeros, or carry the state withzi). - Forgetting that the DC gain is ; filters whose taps do not sum to 1 change the level.
- Convolving very long signals by loops: use
scipy.signal.fftconvolveoroaconvolve(Fast Convolution).
Practice
- Convolve with .
- A filter has . What are its DC gain and its step response?
- Two filters and are cascaded. What is the overall impulse response?
Answer
- (check: sums ).
- DC gain 1; .
- .
Test yourself
An input of 100 samples is convolved with a 31-tap FIR filter. How many output samples does full convolution give?
- 100
- 130
- 131
- 3100
The step response of an LTI system equals
- the derivative of
- the running sum of
- flipped
- squared
Two filters are cascaded. The overall impulse response is
- sample by sample
- the larger of the two
The output of a 9-tap moving average lags its input by
- 1 sample
- 4 samples
- 4.5 samples
- 9 samples