Algorithmcore
Empirical transfer function estimate
Also called ETFE.
Estimates the frequency response as the ratio of the DFTs of output and input, and smooths it with a window to cut the variance.
- Solves
- System identification
- Time
- O(N log N + N M) worst
- Space
- O(N) extra
- Where
- M = the half width gamma of the smoothing window; N = the number of samples
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Lennart Ljung, 1985
The empirical transfer function estimate, or ETFE, estimates the frequency response of a linear system from one record of input and output samples, with no model structure. It takes the discrete Fourier transforms and of the input and the output and returns their ratio at the frequencies where . With a fast Fourier transform this costs . For a periodic input in periodic steady state the ratio is exact up to the noise term , but that term does not shrink as grows: the raw estimate stays as noisy at as at . A smoothed ETFE therefore averages the raw values over neighboring frequencies, weighted by a window and by , which trades a small bias for a variance that falls with .
In plain words
Any input can be split into sine waves of different frequencies, and a linear system changes each sine wave only by scaling it and shifting it in time. So if you split both the input and the output into their sine waves and divide one by the other, frequency by frequency, you get the scaling and the shift at each frequency. That table is the frequency response, read straight off the data. The catch is noise: each frequency gets its own share of the noise, and recording for longer only gives you more frequencies, each one as noisy as before. To get a clean curve, you average each value with its neighbors, at the cost of blurring sharp peaks.
The problem
Input. Samples and of a system with an additive disturbance , and a half width with . The sampling period only rescales the frequency axis: corresponds to radians per unit time.
Transforms. and likewise, with .
Output. For , an estimate of , or "undefined" where the input has no energy. The values for are the complex conjugates, because the data are real.
The algorithm
ETFE(y, u, ⟨γ⟩)- 1
Y ← DFT(y); U ← DFT(u) - 2
for k ← 0 to ⌊N/2⌋ do - 3
if γ = 0 and |U_k| ≤ tol · max |U| then G_k ← undefined - 4
else if γ = 0 then G_k ← Y_k / U_k - 5
else - 6
G_k ← Σ_{|j| ≤ γ} W_j Y_{k+j} conj(U_{k+j}) / Σ_{|j| ≤ γ} W_j |U_{k+j}|^2, indices mod N, W_j = (1 + cos(π j / (γ + 1))) / 2; undefined if the denominator is 0 - 7
return the pairs (ω_k, G_k)
Line L1 is two transforms, by the radix-2 FFT when is a power of 2. Line L3 refuses to divide where the input has no energy; the relative tolerance tol treats rounding residue as zero. Line L6 is the smoothed estimate with a Hann window. Because , it is the average of the raw ratios over the window, each weighted by ; frequencies where the input is weak count little. With the formula of L6 reduces to the raw ratio of L4.
Example
Take , the input repeated, and the output in periodic steady state, ; for instance . Here and .
| 0 | undefined | ||||
| 1 | |||||
| 2 | undefined |
At , , and , so the estimate is exact. The input has zero mean and alternates in pairs, so it has no energy at or , and L3 returns "undefined" there: the data say nothing about the gain at those frequencies.
Correctness
Claim. Suppose is BIBO stable, is periodic with period , and in periodic steady state. Then for every with , , where is the DFT of ; with the raw ETFE is exact. If is white with variance , then , and the smoothed value of L6 is the -weighted average of the raw values.
Key invariant. For an -periodic input and an absolutely summable impulse response , a delay by multiplies the DFT by , so has the DFT .
The noise formula follows because the DFTs of white noise at distinct frequencies of the grid are uncorrelated, each with variance . The full proof is below.
Proof: The ETFE is exact in periodic steady state, its noise error does not shrink, and smoothing averages itfull
We work in exact real arithmetic, with and as exact operations. Fix and write and, for a sequence , . Line L1 computes exactly these sums: by the direct formula, or by the radix-2 FFT, which computes the same sums.
Lemma 1 (delay in a periodic signal). If is periodic with period , the sequence restricted to has the DFT for every integer .
Proof. . The summand is periodic in with period , because , so the sum over the consecutive values equals the sum over , which is .
Lemma 2 (periodic steady state). Let be BIBO stable with impulse response , so , let be periodic with period and let . Then for every .
Proof. The input is bounded, so the series for converges absolutely, and the finite sum over may be exchanged with the sum over . By Lemma 1, , since .
Lemma 3 (white noise on the grid). If have zero mean, variance and are uncorrelated, then if and if , for .
Proof. . For this is . For , and , so the geometric sum is 0.
Theorem. Under the hypotheses of Lemma 2:
- for every with , the raw value of L4 is ; with it equals ;
- if is fixed and is as in Lemma 3, ;
- if the denominator of L6 is positive, the smoothed value is , a convex combination of the raw values with , the sum running over the with ;
- under the hypothesis of (2), with and .
Proof. (1) Divide the identity of Lemma 2 by .
(2) By (1) the error is , and by Lemma 3 .
(3) Every index is taken modulo . If , the terms and are both 0. If , . Hence the numerator of L6 is , and dividing by gives the stated form. The weights are nonnegative and the sum to 1, so the combination is convex.
(4) By Lemma 2 the numerator of L6 is , so with and . Each has mean 0, so . Since , the indices are distinct, and Lemma 3 gives .
Corollary (the Hann factor). For , and . If for all in the window, then by (4) , which is times the raw mean square error of (2).
Proof. Let . The consecutive integers cover one full period of , so ; removing the term , which is , gives . In the same way they cover two full periods of , which has period , so , and removing the term gives . Then . With , , so . With constant , (4) gives , which is the stated value.
The sums of over a full period vanish because they are the real parts of sums of all the -th or -th roots of unity, each of which is 0 when the number of roots is at least 2.
Complexity
Line L1 costs with an FFT; the reference code uses the radix-2 FFT for powers of 2 and the direct sum otherwise. Lines L3 and L4 cost per frequency, and L6 costs , so the loop costs raw and smoothed. The total is arithmetic operations and evaluations of and in the real RAM, with extra space for the two transforms. Smoothing by a window of fixed shape is a circular convolution and can also be done by FFT in for any .
Properties
- Exact in periodic steady state (theorem). With a periodic input, a whole number of periods in the record and no noise, wherever ; with a PRBS of period every with is nonzero.
- Variance does not go to 0 (theorem). The error has mean square for white noise. For a signal of fixed power, grows like , so this stays about divided by the input power at that frequency; a longer record gives more frequencies, not more accurate ones. For a general disturbance and a random input the limit is the ratio of the disturbance and input spectra (Ljung 1999, Chapter 6).
- Measurement. For the system above with a white input and white output noise of standard deviation , the median squared error of the raw ETFE over the frequencies was , and for , and . With it was , and .
- Variance reduction by the Hann window (computation). For , and . Where is constant over the window, the smoothed error has variance times that of the raw error, for example for .
- Bias of smoothing. The smoothed value averages over a band of width about , so it flattens resonance peaks narrower than that band.
- Transients (theorem). For a nonperiodic input the record does not start in steady state, and gains an extra term . For a bounded input and a whose impulse response satisfies , is bounded by a constant independent of , while typically grows like , so this term falls like (Ljung 1999, Chapter 6).
Variants and improvements
- Periodic excitation and averaging over periods. Repeat a period of length several times, drop the first period, and average over periods before dividing. The noise variance then falls with the number of periods, with no smoothing bias.
- Spectral analysis. Estimate the cross spectrum and the input spectrum with a lag window or by Welch's method, and take their ratio. This is the same idea as L6 with a different window.
- Other windows. Bartlett, Parzen or rectangular frequency windows in place of the Hann weights in L6, with the same trade between bias and variance.
- Local polynomial and local rational methods. Fit a low-order polynomial in frequency to and around each , which also removes the transient term.
- Parametric fit in frequency. Fit an output error or other parametric model to the ETFE by weighted least squares in the frequency domain.
When to use it
Use it as the first look at new data: a Bode plot of the smoothed ETFE shows the bandwidth, resonances and delay before any model order is chosen, and it checks a parametric model. It is most accurate with a periodic input such as a PRBS of period in steady state. Do not use the raw estimate for design without smoothing or averaging, and do not use it on closed-loop data, where the ratio estimates a mixture of the plant and the inverse of the controller.
Pitfalls
- Dividing by an input with no energy. At a frequency where or nearly so, the ratio in L4 is undefined or pure noise. Keep the test of L3, and design the input so that is large at the frequencies of interest.
- Expecting a longer record to help. Computing L4 for a larger gives a finer grid with the same scatter. Use L5 and L6 with , or average over periods.
- Smoothing instead of . Averaging the raw ratios of L4 with equal weights lets frequencies with tiny dominate. L6 must weight by , as in the ratio of the window sums.
- A non-integer number of periods. With a periodic input, a record that does not hold a whole number of periods leaks energy between frequencies. In L1, transform an integer number of periods taken after the transient.
- Too wide a window. A large in L6 smears a sharp resonance over many frequencies and lowers its peak. Choose so that is well below the width of the narrowest peak.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/empirical-transfer-function-estimate/. The authors are listed in prov/H22G0R.jsonl.
"""Empirical transfer function estimate (ETFE), raw and smoothed.
For N samples of input u and output y, with the discrete Fourier transforms
U_k = sum over t of u(t) e^(-i w_k t), Y_k = the same for y,
w_k = 2 pi k / N,
the raw ETFE at w_k is G_k = Y_k / U_k. It is undefined where U_k = 0.
The smoothed ETFE with a Hann window of half width gamma is
G_k = sum_j W_j Y_(k+j) conj(U_(k+j)) / sum_j W_j |U_(k+j)|^2,
W_j = (1 + cos(pi j / (gamma + 1))) / 2 for |j| <= gamma,
with the indices taken modulo N. This is the |U|^2-weighted average of
the raw values over nearby frequencies.
Precondition: len(y) == len(u) = N >= 1 and 0 <= gamma < N / 2.
Cost: O(N log N) for the transforms when N is a power of 2 (O(N^2) by the
direct sum otherwise), O(N) for the raw ratios and O(N gamma) for the
smoothing, in the real RAM.
"""
import cmath
import math
from typing import List, Optional, Sequence, Tuple
def dft(x: Sequence) -> List[complex]:
"""Return X_k = sum_t x(t) e^(-2 pi i k t / N) for k = 0, ..., N-1.
Uses the iterative radix-2 FFT when N is a power of 2, and the direct
O(N^2) sum otherwise.
"""
n = len(x)
if n == 0:
return []
if n & (n - 1):
return [sum(x[t] * cmath.exp(-2j * math.pi * k * t / n) for t in range(n)) for k in range(n)]
a = [complex(v) for v in x]
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
w_step = cmath.exp(-2j * math.pi / size)
half = size // 2
for start in range(0, n, size):
w = 1 + 0j
for k in range(half):
p = a[start + k]
q = a[start + k + half] * w
a[start + k] = p + q
a[start + k + half] = p - q
w *= w_step
size *= 2
return a
def etfe(y: Sequence, u: Sequence, gamma: int = 0,
tol: float = 1e-12) -> List[Tuple[float, Optional[complex]]]:
"""Return [(w_k, G_k)] for k = 0, ..., N // 2.
gamma = 0 gives the raw ETFE; G_k is None where |U_k| <= tol * max|U|.
gamma > 0 gives the smoothed ETFE; G_k is None where the weighted sum of
|U|^2 is 0.
"""
n = len(u)
if len(y) != n or n == 0:
raise ValueError("y and u must have the same positive length")
if gamma < 0 or (gamma > 0 and 2 * gamma >= n):
raise ValueError("need 0 <= gamma < N / 2")
yk = dft(y) # @line L1
uk = dft(u)
big = max(abs(v) for v in uk)
out = []
for k in range(n // 2 + 1): # @line L2
w = 2 * math.pi * k / n
if gamma == 0:
if abs(uk[k]) <= tol * big: # @line L3
out.append((w, None))
else:
out.append((w, yk[k] / uk[k])) # @line L4
continue
num = 0j # @line L5
den = 0.0
for j in range(-gamma, gamma + 1):
wj = 0.5 * (1 + math.cos(math.pi * j / (gamma + 1)))
m = (k + j) % n
num += wj * yk[m] * uk[m].conjugate() # @line L6
den += wj * abs(uk[m]) ** 2
out.append((w, num / den if den > 0 else None))
return out # @line L7
test_empirical_transfer_function_estimate.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/empirical-transfer-function-estimate/. The authors are listed in prov/H22G0R.jsonl.
import cmath
import math
import random
import statistics
from empirical_transfer_function_estimate import dft, etfe
def _g(w):
z1 = cmath.exp(-1j * w)
return z1 / (1 - 0.5 * z1)
def _simulate(u, e=None):
# y(t) = 0.5 y(t-1) + u(t-1) + e(t), from rest.
y = []
x = 0.0
prev_u = 0.0
for t in range(len(u)):
x = 0.5 * x + prev_u
prev_u = u[t]
y.append(x + (e[t] if e else 0.0))
return y
def test_worked_example():
u = [1, 1, -1, -1]
y = [-1.2, 0.4, 1.2, -0.4]
out = etfe(y, u)
assert [w for w, _ in out] == [0.0, math.pi / 2, math.pi]
assert out[0][1] is None and out[2][1] is None
assert abs(out[1][1] - (-0.4 - 0.8j)) < 1e-12
assert abs(out[1][1] - _g(math.pi / 2)) < 1e-12
def test_random_fft_matches_direct_sum():
rng = random.Random(1)
for _ in range(500):
n = rng.choice([1, 2, 3, 4, 5, 6, 8, 12, 16])
x = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
got = dft(x)
for k in range(n):
want = sum(x[t] * cmath.exp(-2j * math.pi * k * t / n) for t in range(n))
assert abs(got[k] - want) < 1e-9
def test_exact_in_periodic_steady_state():
rng = random.Random(2)
period = 16
one = [rng.choice((-1.0, 1.0)) for _ in range(period)]
u = one * 8
y = _simulate(u)
out = etfe(y[-period:], u[-period:])
seen = 0
for w, g in out:
if g is not None:
assert abs(g - _g(w)) < 1e-9
seen += 1
assert seen >= 3
def _errors(n, gamma, seed):
rng = random.Random(seed)
burn = 200
u = [rng.choice((-1.0, 1.0)) for _ in range(n + burn)]
e = [rng.gauss(0.0, 0.5) for _ in range(n + burn)]
y = _simulate(u, e)
out = etfe(y[burn:], u[burn:], gamma)
return statistics.median(abs(g - _g(w)) ** 2 for w, g in out[1:-1] if g is not None)
def test_raw_error_does_not_fall_but_smoothed_error_does():
raw_small = _errors(256, 0, 7)
raw_big = _errors(4096, 0, 7)
assert 0.5 < raw_big / raw_small < 2.0
sm_small = _errors(256, 256 // 32, 7)
sm_big = _errors(4096, 4096 // 32, 7)
assert sm_big < sm_small / 8
assert sm_small < raw_small
def test_gamma_zero_is_raw_ratio():
rng = random.Random(3)
u = [rng.uniform(-1, 1) for _ in range(8)]
y = [rng.uniform(-1, 1) for _ in range(8)]
uu, yy = dft(u), dft(y)
for k, (w, g) in enumerate(etfe(y, u)):
assert abs(w - 2 * math.pi * k / 8) < 1e-15
assert abs(g - yy[k] / uu[k]) < 1e-12
def test_edges_and_bad_arguments():
assert etfe([2.0], [1.0]) == [(0.0, 2.0)]
assert etfe([0.0, 0.0], [0.0, 1.0])[0][1] == 0.0
for args in (([1.0], [1.0, 2.0]), ([], []), ([1.0] * 4, [1.0] * 4, 2), ([1.0] * 4, [1.0] * 4, -1)):
try:
etfe(*args)
except ValueError:
continue
raise AssertionError("expected ValueError for %r" % (args,))
History
Frequency analysis by sine wave tests and by Fourier transforms of input and output is the oldest way to identify a linear system. Smoothing of raw Fourier ratios follows the spectral analysis of Blackman and Tukey in 1958 and of Jenkins and Watts in 1968, where averaging over frequencies controls the variance of the periodogram. Ljung's 1985 paper on the estimation of transfer functions, and his textbook, treat the ratio as the empirical transfer function estimate, analyze its bias and variance and connect it to the frequency-domain view of parametric methods.
References
- Lennart Ljung, System Identification: Theory for the User, second edition, Prentice Hall, 1999, Chapter 6 (nonparametric frequency-domain methods: the empirical transfer function estimate, its bias and variance, and smoothing by spectral analysis)
- Lennart Ljung, On the estimation of transfer functions, Automatica 21(6), 677-696, 1985, nonparametric estimation of transfer functions and the frequency-domain view of bias and variance
- Torsten Söderström and Petre Stoica, System Identification, Prentice Hall, 1989, the chapter on nonparametric methods (frequency analysis, Fourier analysis and spectral analysis)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag H22G0R Edit this page History Report an error Markdown