If you record a filter’s input x and output y on the same time base, you can measure gain and phase even when you have no filter coefficients. Frequency bins where the input has little energy, or where measurement noise dominates the output, need to be screened before interpreting the estimate.
This example estimates the frequency response with SciPy’s csd and welch, calculates coherence, and compares the result with a known low-pass filter.
Why the input goes first in the H1 estimator
Split both recordings at the same indices and call their windowed segment FFTs \(X_k\)
and \(Y_k\)
. SciPy’s csd(x, y) averages \(X_k^*Y_k\)
across segments. The input Welch PSD averages \(|X_k|^2\)
. With matching window and scaling settings, the H1 estimate and magnitude-squared coherence are
For a linear, time-invariant system, write the output as \(Y=HX+N\) . When the output noise \(N\) is uncorrelated with the input, \(X^*N\) has zero expectation. Significant input measurement noise changes the situation. Independent noise in the recorded input adds power to the denominator and biases the H1 gain downward.
Using csd(y, x) while keeping welch(x) in the denominator conjugates the estimate. A magnitude-only check will miss the error. A known delay of \(d\)
samples is an easy phase check. Its unwrapped phase decreases with frequency at a slope of \(-2\pi d/f_s\)
.
Compare with the theoretical response in Python
Generate white noise at 2048 Hz and send it through a fourth-order Butterworth low-pass filter with a 160 Hz cutoff. Add five samples of delay and independent noise to the output. Include the delay in the theoretical response, then divide the estimate by that response to calculate gain and phase errors. The complex ratio also works when the reference phase wraps at ±180 degrees.
import numpy as np
from scipy import signal
fs = 2048
rng = np.random.default_rng(42)
sos = signal.butter(4, 160, fs=fs, output="sos")
delay = 5
x = rng.standard_normal(2**17)
z = signal.sosfilt(sos, x)
# np.roll would wrap the end of the record into its beginning.
y = np.r_[np.zeros(delay), z[:-delay]] + 0.03 * rng.standard_normal(x.size)
x, y = x[2048:], y[2048:] # Discard the transient at the same indices.
nperseg = 2048
params = dict(
fs=fs,
window=signal.windows.hann(nperseg, sym=False),
nperseg=nperseg,
noverlap=nperseg // 2,
detrend="constant",
scaling="density",
)
f, pxx = signal.welch(x, **params)
_, pyy = signal.welch(y, **params)
_, pxy = signal.csd(x, y, **params)
excited = (f > 0) & (pxx >= 1e-3 * pxx.max())
h1 = np.full(pxy.shape, np.nan + 1j * np.nan)
np.divide(pxy, pxx, out=h1, where=excited)
denom = pxx * pyy
coh = np.full(f.shape, np.nan)
np.divide(abs(pxy) ** 2, denom, out=coh, where=denom > 0)
valid = excited & (coh >= 0.90)
_, ref = signal.sosfreqz(sos, worN=f, fs=fs)
ref *= np.exp(-2j * np.pi * f * delay / fs)
print("Hz coherence gain error (dB) phase error (deg)")
for target in (64, 128, 160, 600):
i = np.argmin(abs(f - target))
if not valid[i]:
print(f"{f[i]:3.0f} {coh[i]:9.3f} masked")
continue
ratio = h1[i] / ref[i]
gain_error = 20 * np.log10(abs(ratio))
phase_error = np.angle(ratio, deg=True)
print(f"{f[i]:3.0f} {coh[i]:9.3f} {gain_error:+.3f} {phase_error:+.3f}")
| Frequency | Coherence | Gain error | Phase error |
|---|---|---|---|
| 64 Hz | 0.999 | −0.013 dB | +0.118° |
| 128 Hz | 0.998 | +0.004 dB | −0.156° |
| 160 Hz | 0.998 | +0.040 dB | +0.100° |
| 600 Hz | 0.004 | — | — |
The estimates at 64 Hz, 128 Hz, and 160 Hz are close to the theoretical response. At 600 Hz, the filter attenuates the part of the output due to the input, leaving the output dominated by noise. The coherence mask drops that bin. Omitting the delay from the theoretical response would give a phase error of about −112.5 degrees at 128 Hz.
Choose the frequency band you can interpret
- Check excitation using the input PSD. Avoiding division by zero still leaves bins with too little excitation to interpret. The example considers input PSD values within 30 dB of the peak. In a measurement, set the floor based on the acquisition noise and on which frequencies you intend to excite.
- Check coherence and the number of averages. The 0.90 threshold is an example. Choose it based on the record length and purpose of the measurement. With one segment, the numerator and denominator are algebraically equal wherever both PSDs are nonzero, yielding a coherence of 1. Record enough data for multiple averages. Overlapping segments are correlated.
- Unwrap phase within each contiguous valid band. An expression such as
np.unwrap(np.angle(h1[valid]))packs valid bins together and treats gaps with no usable estimates as though the phase were continuous. - Revisit detrending if you need DC or very low frequencies. The example removes each segment’s mean and excludes DC. If you need DC gain, measure the change in steady-state output between different steady input levels.
Verify the sample rates, start times, and any gaps in the two logs. A fixed acquisition offset adds a phase slope. Separating that slope from the delay of the system under test requires a timing calibration. With clocks that drift relative to one another, the phase shift changes over the record, which can make cross-spectrum averages cancel and lower coherence.
FAQ
Does the input or output go first in scipy.signal.csd?
Use the input first in csd(x, y) and divide by the input PSD. Reversing the order while keeping the same denominator reverses the sign of the phase.
Does high coherence mean the measured gain is accurate?
Coherence does not measure absolute gain accuracy. For example, a mistaken constant scale factor on the output cancels in the coherence formula.
Can one sine wave measure the full frequency response?
A single tone provides information near the excited frequency. To cover the full band, use broadband excitation with enough segments to average, or step through frequencies and analyze each steady portion separately.