Zero-phase filtering
Every causal filter delays the signal. Filtering forwards and then backwards cancels the delay — and needs care at the edges.
- Measure the delay a causal filter introduces
- Explain why forward-backward filtering has zero phase and a squared magnitude response
- Handle edge effects with reflection padding
A causal filter can only use past samples, so its output lags its input. A symmetric FIR filter with \(N\) taps delays everything by \((N-1)/2\) samples; an IIR filter delays different frequencies by different amounts. For a recording that is already complete — an ECG, a seismogram, an experiment’s log — there is a better option: run the filter forwards, then backwards.
In the frequency domain the backward pass applies \(\overline{H(\omega)}\), the complex conjugate, so the two passes together apply \(H\overline{H} = \vert H\vert^2\): a real, non-negative response with no phase shift at all — and twice the attenuation in dB. fir_causal_zerpPhaseShift.m builds it by hand with filter and array flips, then confirms that MATLAB’s filtfilt gives the same.
lfilter once, twice, or filtfilt
3_filtfilt_vs_lfilter.py compares three ways of smoothing a noisy signal with a third-order Butterworth filter:
b, a = butter(3, 0.05)
zi = lfilter_zi(b, a)
z, _ = lfilter(b, a, xn, zi=zi*xn[0]) # once
z2, _ = lfilter(b, a, z, zi=zi*z[0]) # twice, both forward
y = filtfilt(b, a, xn) # forward and backward
At low frequencies this filter delays by about 13 samples — 0.13 s with the script’s sampling interval of 0.01 s. Filtering twice forwards doubles the delay to about 26 samples; only filtfilt lands on top of the signal. The zi=zi*xn[0] trick starts the filter in its steady state for the first sample, which removes the start-up transient a filter otherwise shows when it begins from zero.
Edges
The backward pass begins at the end of the signal, so both ends suffer start-up transients. edge_effect_with_reflection.m fixes this by mirroring order samples onto each end before filtering and cutting them off afterwards:
reflectsig = [signal(order:-1:1) signal signal(end:-1:end-order+1)];
reflectsig = filter(fkern,1,reflectsig);
reflectsig = filter(fkern,1,reflectsig(end:-1:1));
reflectsig = reflectsig(end:-1:1);
fsignal = reflectsig(order+1:end-order);
SciPy’s filtfilt does the same automatically (odd extension by default, length set by padlen), which is why 2_filtfilt.py passes padlen=150.
Try it yourself. In 3_filtfilt_vs_lfilter.py, cross-correlate xn with z, z2 and y using np.correlate(..., 'full') and read off each lag. One run gave 14, 27 and 1 samples. Then compute signal.group_delay((b, a)) — about 12.7 samples near DC — and explain the small difference.