Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
Origin
Lennart Ljung, 1985

The empirical transfer function estimate, or ETFE, estimates the frequency response G(eiω)G(e^{i\omega}) of a linear system from one record of NN input and output samples, with no model structure. It takes the discrete Fourier transforms UkU_k and YkY_k of the input and the output and returns their ratio G^k=Yk/Uk\hat G_k = Y_k / U_k at the frequencies ωk=2πk/N\omega_k = 2\pi k / N where Uk≠0U_k \ne 0. With a fast Fourier transform this costs O(Nlog⁡N)O(N \log N). For a periodic input in periodic steady state the ratio is exact up to the noise term Vk/UkV_k / U_k, but that term does not shrink as NN grows: the raw estimate stays as noisy at N=4096N = 4096 as at N=256N = 256. A smoothed ETFE therefore averages the raw values over 2γ+12\gamma + 1 neighboring frequencies, weighted by a window and by ∣U∣2\lvert U \rvert^2, which trades a small bias for a variance that falls with γ\gamma.

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 u(0),…,u(N−1)u(0), \ldots, u(N-1) and y(0),…,y(N−1)y(0), \ldots, y(N-1) of a system y=G(q) u+vy = G(q)\, u + v with an additive disturbance vv, and a half width γ\gamma with 0≤γ<N/20 \le \gamma < N/2. The sampling period hh only rescales the frequency axis: ωk\omega_k corresponds to ωk/h\omega_k / h radians per unit time.

Transforms. Uk=∑t=0N−1u(t) e−iωktU_k = \sum_{t=0}^{N-1} u(t)\, e^{-i \omega_k t} and YkY_k likewise, with ωk=2πk/N\omega_k = 2\pi k/N.

Output. For k=0,…,⌊N/2⌋k = 0, \ldots, \lfloor N/2 \rfloor, an estimate G^k\hat G_k of G(eiωk)G(e^{i\omega_k}), or "undefined" where the input has no energy. The values for k>N/2k > N/2 are the complex conjugates, because the data are real.

The algorithm

  1. ETFE(y, u, ⟨γ⟩)
  2. 1Y ← DFT(y); U ← DFT(u)
  3. 2for k ← 0 to ⌊N/2⌋ do
  4. 3if γ = 0 and |U_k| ≤ tol · max |U| then G_k ← undefined
  5. 4else if γ = 0 then G_k ← Y_k / U_k
  6. 5else
  7. 6G_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
  8. 7return the pairs (ω_k, G_k)

Line L1 is two transforms, by the radix-2 FFT when NN 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 WjYmUm‾=Wj∣Um∣2⋅(Ym/Um)W_j Y_m \overline{U_m} = W_j \lvert U_m \rvert^2 \cdot (Y_m / U_m), it is the average of the raw ratios over the window, each weighted by Wj∣Um∣2W_j \lvert U_m \rvert^2; frequencies where the input is weak count little. With γ=0\gamma = 0 the formula of L6 reduces to the raw ratio of L4.

Example

Take G(q)=q−1/(1−0.5 q−1)G(q) = q^{-1}/(1 - 0.5\, q^{-1}), the input u=(1,1,−1,−1)u = (1, 1, -1, -1) repeated, and the output in periodic steady state, y=(−1.2,0.4,1.2,−0.4)y = (-1.2, 0.4, 1.2, -0.4); for instance y(0)=0.5 y(3)+u(3)=−0.2−1=−1.2y(0) = 0.5\, y(3) + u(3) = -0.2 - 1 = -1.2. Here N=4N = 4 and γ=0\gamma = 0.

kk ωk\omega_k UkU_k YkY_k G^k\hat G_k G(eiωk)G(e^{i\omega_k})
0 00 00 00 undefined 22
1 π/2\pi/2 2−2i2 - 2i −2.4−0.8i-2.4 - 0.8i −0.4−0.8i-0.4 - 0.8i −0.4−0.8i-0.4 - 0.8i
2 π\pi 00 00 undefined −2/3-2/3

At k=1k = 1, (−2.4−0.8i)/(2−2i)=(−2.4−0.8i)(2+2i)/8=(−3.2−6.4i)/8=−0.4−0.8i(-2.4 - 0.8i)/(2 - 2i) = (-2.4 - 0.8i)(2 + 2i)/8 = (-3.2 - 6.4i)/8 = -0.4 - 0.8i, and G(eiπ/2)=−i/(1+0.5i)=−0.4−0.8iG(e^{i\pi/2}) = -i/(1 + 0.5 i) = -0.4 - 0.8i, so the estimate is exact. The input has zero mean and alternates in pairs, so it has no energy at ω=0\omega = 0 or ω=π\omega = \pi, and L3 returns "undefined" there: the data say nothing about the gain at those frequencies.

Correctness

Claim. Suppose GG is BIBO stable, uu is periodic with period NN, and y=G(q) u+vy = G(q)\, u + v in periodic steady state. Then for every kk with Uk≠0U_k \ne 0, G^k=G(eiωk)+Vk/Uk\hat G_k = G(e^{i\omega_k}) + V_k / U_k, where VkV_k is the DFT of vv; with v=0v = 0 the raw ETFE is exact. If vv is white with variance σ2\sigma^2, then E∣G^k−G(eiωk)∣2=Nσ2/∣Uk∣2\mathbb{E} \lvert \hat G_k - G(e^{i\omega_k}) \rvert^2 = N \sigma^2 / \lvert U_k \rvert^2, and the smoothed value of L6 is the Wj∣U∣2W_j \lvert U \rvert^2-weighted average of the raw values.

Key invariant. For an NN-periodic input and an absolutely summable impulse response gg, a delay by ℓ\ell multiplies the DFT by e−iωkℓe^{-i\omega_k \ell}, so ∑ℓgℓ u(t−ℓ)\sum_\ell g_\ell\, u(t - \ell) has the DFT ∑ℓgℓe−iωkℓ Uk=G(eiωk) Uk\sum_\ell g_\ell e^{-i\omega_k \ell}\, U_k = G(e^{i\omega_k})\, U_k.

The noise formula follows because the DFTs of white noise at distinct frequencies of the grid are uncorrelated, each with variance Nσ2N\sigma^2. 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 cos⁡\cos and eixe^{ix} as exact operations. Fix N≥1N \ge 1 and write ωk=2πk/N\omega_k = 2\pi k / N and, for a sequence xx, Xk=∑t=0N−1x(t) e−iωktX_k = \sum_{t=0}^{N-1} x(t)\, e^{-i\omega_k t}. 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 xx is periodic with period NN, the sequence t↦x(t−ℓ)t \mapsto x(t - \ell) restricted to t=0,…,N−1t = 0, \ldots, N-1 has the DFT e−iωkℓXke^{-i\omega_k \ell} X_k for every integer ℓ\ell.

Proof. ∑t=0N−1x(t−ℓ) e−iωkt=e−iωkℓ∑t=0N−1x(t−ℓ) e−iωk(t−ℓ)\sum_{t=0}^{N-1} x(t - \ell)\, e^{-i\omega_k t} = e^{-i\omega_k \ell} \sum_{t=0}^{N-1} x(t - \ell)\, e^{-i\omega_k (t - \ell)}. The summand x(s) e−iωksx(s)\, e^{-i\omega_k s} is periodic in ss with period NN, because e−iωkN=e−2πik=1e^{-i\omega_k N} = e^{-2\pi i k} = 1, so the sum over the NN consecutive values s=t−ℓs = t - \ell equals the sum over s=0,…,N−1s = 0, \ldots, N-1, which is XkX_k. □\square

Lemma 2 (periodic steady state). Let GG be BIBO stable with impulse response gg, so ∑ℓ∣gℓ∣<∞\sum_\ell \lvert g_\ell \rvert < \infty, let uu be periodic with period NN and let y(t)=∑ℓ≥0gℓ u(t−ℓ)+v(t)y(t) = \sum_{\ell \ge 0} g_\ell\, u(t - \ell) + v(t). Then Yk=G(eiωk) Uk+VkY_k = G(e^{i\omega_k})\, U_k + V_k for every kk.

Proof. The input is bounded, so the series for y(t)y(t) converges absolutely, and the finite sum over tt may be exchanged with the sum over ℓ\ell. By Lemma 1, Yk=∑ℓgℓ e−iωkℓ Uk+Vk=G(eiωk) Uk+VkY_k = \sum_\ell g_\ell\, e^{-i\omega_k \ell}\, U_k + V_k = G(e^{i\omega_k})\, U_k + V_k, since G(eiω)=∑ℓgℓe−iωℓG(e^{i\omega}) = \sum_\ell g_\ell e^{-i\omega \ell}. □\square

Lemma 3 (white noise on the grid). If v(0),…,v(N−1)v(0), \ldots, v(N-1) have zero mean, variance σ2\sigma^2 and are uncorrelated, then E VmVn‾=Nσ2\mathbb{E}\, V_m \overline{V_n} = N \sigma^2 if m=nm = n and 00 if m≠nm \ne n, for m,n∈{0,…,N−1}m, n \in \{0, \ldots, N-1\}.

Proof. E VmVn‾=∑t,sE v(t)v(s) e−iωmt+iωns=σ2∑t=0N−1e−i(ωm−ωn)t\mathbb{E}\, V_m \overline{V_n} = \sum_{t, s} \mathbb{E}\, v(t) v(s)\, e^{-i\omega_m t + i\omega_n s} = \sigma^2 \sum_{t=0}^{N-1} e^{-i(\omega_m - \omega_n) t}. For m=nm = n this is Nσ2N\sigma^2. For m≠nm \ne n, z=e−2πi(m−n)/N≠1z = e^{-2\pi i (m - n)/N} \ne 1 and zN=1z^N = 1, so the geometric sum (1−zN)/(1−z)(1 - z^N)/(1 - z) is 0. □\square

Theorem. Under the hypotheses of Lemma 2:

  1. for every kk with Uk≠0U_k \ne 0, the raw value of L4 is G^k=G(eiωk)+Vk/Uk\hat G_k = G(e^{i\omega_k}) + V_k / U_k; with v=0v = 0 it equals G(eiωk)G(e^{i\omega_k});
  2. if uu is fixed and vv is as in Lemma 3, E∣G^k−G(eiωk)∣2=Nσ2/∣Uk∣2\mathbb{E} \lvert \hat G_k - G(e^{i\omega_k}) \rvert^2 = N\sigma^2 / \lvert U_k \rvert^2;
  3. if the denominator Dk=∑∣j∣≤γWj∣Uk+j∣2D_k = \sum_{|j| \le \gamma} W_j \lvert U_{k+j} \rvert^2 of L6 is positive, the smoothed value is G~k=∑jλjG^k+j\tilde G_k = \sum_j \lambda_j \hat G_{k+j}, a convex combination of the raw values with λj=Wj∣Uk+j∣2/Dk\lambda_j = W_j \lvert U_{k+j} \rvert^2 / D_k, the sum running over the jj with Uk+j≠0U_{k+j} \ne 0;
  4. under the hypothesis of (2), G~k=∑jλjG(eiωk+j)+Ek\tilde G_k = \sum_j \lambda_j G(e^{i\omega_{k+j}}) + E_k with E Ek=0\mathbb{E}\, E_k = 0 and E∣Ek∣2=Nσ2∑jWj2∣Uk+j∣2/Dk2\mathbb{E} \lvert E_k \rvert^2 = N \sigma^2 \sum_j W_j^2 \lvert U_{k+j} \rvert^2 / D_k^2.

Proof. (1) Divide the identity of Lemma 2 by UkU_k.

(2) By (1) the error is Vk/UkV_k / U_k, and by Lemma 3 E∣Vk∣2=Nσ2\mathbb{E} \lvert V_k \rvert^2 = N\sigma^2.

(3) Every index m=k+jm = k + j is taken modulo NN. If Um=0U_m = 0, the terms WjYmUm‾W_j Y_m \overline{U_m} and Wj∣Um∣2W_j \lvert U_m \rvert^2 are both 0. If Um≠0U_m \ne 0, YmUm‾=∣Um∣2G^mY_m \overline{U_m} = \lvert U_m \rvert^2 \hat G_m. Hence the numerator of L6 is ∑jWj∣Um∣2G^m\sum_j W_j \lvert U_m \rvert^2 \hat G_m, and dividing by DkD_k gives the stated form. The weights Wj=(1+cos⁡(πj/(γ+1)))/2W_j = (1 + \cos(\pi j/(\gamma + 1)))/2 are nonnegative and the λj\lambda_j sum to 1, so the combination is convex.

(4) By Lemma 2 the numerator of L6 is ∑jWj(G(eiωm)∣Um∣2+VmUm‾)\sum_j W_j \big(G(e^{i\omega_m}) \lvert U_m \rvert^2 + V_m \overline{U_m}\big), so Ek=∑jcjVmjE_k = \sum_j c_j V_{m_j} with cj=WjUmj‾/Dkc_j = W_j \overline{U_{m_j}} / D_k and mj=(k+j) mod Nm_j = (k + j) \bmod N. Each VmV_m has mean 0, so E Ek=0\mathbb{E}\, E_k = 0. Since 2γ+1≤N2\gamma + 1 \le N, the indices mjm_j are distinct, and Lemma 3 gives E∣Ek∣2=∑j,j′cjcj′‾ E VmjVmj′‾=Nσ2∑j∣cj∣2\mathbb{E} \lvert E_k \rvert^2 = \sum_{j, j'} c_j \overline{c_{j'}}\, \mathbb{E}\, V_{m_j} \overline{V_{m_{j'}}} = N\sigma^2 \sum_j \lvert c_j \rvert^2. ■\blacksquare

Corollary (the Hann factor). For γ≥1\gamma \ge 1, ∑∣j∣≤γWj=γ+1\sum_{|j| \le \gamma} W_j = \gamma + 1 and ∑∣j∣≤γWj2=34(γ+1)\sum_{|j| \le \gamma} W_j^2 = \frac34 (\gamma + 1). If ∣Um∣2=c>0\lvert U_m \rvert^2 = c > 0 for all mm in the window, then by (4) E∣Ek∣2=Nσ2c⋅34(γ+1)\mathbb{E} \lvert E_k \rvert^2 = \frac{N\sigma^2}{c} \cdot \frac{3}{4(\gamma + 1)}, which is 34(γ+1)\frac{3}{4(\gamma + 1)} times the raw mean square error of (2).

Proof. Let α=π/(γ+1)\alpha = \pi/(\gamma + 1). The 2γ+22\gamma + 2 consecutive integers j=−γ,…,γ+1j = -\gamma, \ldots, \gamma + 1 cover one full period of cos⁡(αj)\cos(\alpha j), so ∑j=−γγ+1cos⁡(αj)=0\sum_{j=-\gamma}^{\gamma+1} \cos(\alpha j) = 0; removing the term j=γ+1j = \gamma + 1, which is cos⁡π=−1\cos \pi = -1, gives ∑∣j∣≤γcos⁡(αj)=1\sum_{|j| \le \gamma} \cos(\alpha j) = 1. In the same way they cover two full periods of cos⁡(2αj)\cos(2\alpha j), which has period γ+1≥2\gamma + 1 \ge 2, so ∑j=−γγ+1cos⁡(2αj)=0\sum_{j=-\gamma}^{\gamma+1} \cos(2\alpha j) = 0, and removing the term cos⁡2π=1\cos 2\pi = 1 gives ∑∣j∣≤γcos⁡(2αj)=−1\sum_{|j| \le \gamma} \cos(2\alpha j) = -1. Then ∑Wj=12(2γ+1)+12=γ+1\sum W_j = \frac12 (2\gamma + 1) + \frac12 = \gamma + 1. With cos⁡2x=(1+cos⁡2x)/2\cos^2 x = (1 + \cos 2x)/2, ∑cos⁡2(αj)=12(2γ+1)−12=γ\sum \cos^2(\alpha j) = \frac12 (2\gamma + 1) - \frac12 = \gamma, so ∑Wj2=14((2γ+1)+2+γ)=34(γ+1)\sum W_j^2 = \frac14 \big((2\gamma + 1) + 2 + \gamma\big) = \frac34 (\gamma + 1). With constant ∣U∣2=c\lvert U \rvert^2 = c, (4) gives Nσ2c∑Wj2/(c∑Wj)2N\sigma^2 c \sum W_j^2 / (c \sum W_j)^2, which is the stated value. □\square

The sums of cos⁡(αj)\cos(\alpha j) over a full period vanish because they are the real parts of sums of all the (2γ+2)(2\gamma + 2)-th or (γ+1)(\gamma + 1)-th roots of unity, each of which is 0 when the number of roots is at least 2.

Complexity

Line L1 costs O(Nlog⁡N)O(N \log N) with an FFT; the reference code uses the radix-2 FFT for powers of 2 and the direct O(N2)O(N^2) sum otherwise. Lines L3 and L4 cost O(1)O(1) per frequency, and L6 costs O(γ)O(\gamma), so the loop costs O(N)O(N) raw and O(Nγ)O(N \gamma) smoothed. The total is O(Nlog⁡N+Nγ)O(N \log N + N \gamma) arithmetic operations and evaluations of cos⁡\cos and eixe^{i x} in the real RAM, with O(N)O(N) 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 O(Nlog⁡N)O(N \log N) for any γ\gamma.

Properties

  • Exact in periodic steady state (theorem). With a periodic input, a whole number of periods in the record and no noise, G^k=G(eiωk)\hat G_k = G(e^{i\omega_k}) wherever Uk≠0U_k \ne 0; with a PRBS of period NN every UkU_k with k≠0k \ne 0 is nonzero.
  • Variance does not go to 0 (theorem). The error Vk/UkV_k / U_k has mean square Nσ2/∣Uk∣2N\sigma^2 / \lvert U_k \rvert^2 for white noise. For a signal of fixed power, ∣Uk∣2\lvert U_k \rvert^2 grows like NN, so this stays about σ2\sigma^2 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 Φv(ω)/Φu(ω)\Phi_v(\omega)/\Phi_u(\omega) of the disturbance and input spectra (Ljung 1999, Chapter 6).
  • Measurement. For the system above with a white ±1\pm 1 input and white output noise of standard deviation 0.50.5, the median squared error of the raw ETFE over the frequencies was 0.2570.257, 0.2690.269 and 0.2430.243 for N=256N = 256, 10241024 and 40964096. With γ=N/32\gamma = N/32 it was 0.02110.0211, 0.00410.0041 and 0.001060.00106.
  • Variance reduction by the Hann window (computation). For γ≥1\gamma \ge 1, ∑∣j∣≤γWj=γ+1\sum_{|j| \le \gamma} W_j = \gamma + 1 and ∑∣j∣≤γWj2=34(γ+1)\sum_{|j| \le \gamma} W_j^2 = \frac34 (\gamma + 1). Where ∣U∣\lvert U \rvert is constant over the window, the smoothed error has variance 34(γ+1)\frac{3}{4(\gamma + 1)} times that of the raw error, for example 316\frac{3}{16} for γ=3\gamma = 3.
  • Bias of smoothing. The smoothed value averages GG over a band of width about 4πγ/N4\pi\gamma/N, so it flattens resonance peaks narrower than that band.
  • Transients (theorem). For a nonperiodic input the record does not start in steady state, and G^k\hat G_k gains an extra term Tk/UkT_k / U_k. For a bounded input and a GG whose impulse response satisfies ∑ℓℓ∣gℓ∣<∞\sum_\ell \ell \lvert g_\ell \rvert < \infty, ∣Tk∣\lvert T_k \rvert is bounded by a constant independent of NN, while ∣Uk∣\lvert U_k \rvert typically grows like N\sqrt N, so this term falls like 1/N1/\sqrt N (Ljung 1999, Chapter 6).

Variants and improvements

  • Periodic excitation and averaging over periods. Repeat a period of length PP several times, drop the first period, and average YkY_k over periods before dividing. The noise variance then falls with the number of periods, with no smoothing bias.
  • Spectral analysis. Estimate the cross spectrum Φ^yu\hat\Phi_{yu} and the input spectrum Φ^u\hat\Phi_u 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 YY and UU around each ωk\omega_k, 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 NN 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 Uk=0U_k = 0 or nearly so, the ratio in L4 is undefined or pure noise. Keep the test of L3, and design the input so that ∣Uk∣\lvert U_k \rvert is large at the frequencies of interest.
  • Expecting a longer record to help. Computing L4 for a larger NN gives a finer grid with the same scatter. Use L5 and L6 with γ>0\gamma > 0, or average over periods.
  • Smoothing Y/UY/U instead of YU‾Y \overline U. Averaging the raw ratios of L4 with equal weights lets frequencies with tiny ∣Uk∣\lvert U_k \rvert dominate. L6 must weight by ∣U∣2\lvert U \rvert^2, 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 γ\gamma in L6 smears a sharp resonance over many frequencies and lowers its peak. Choose γ\gamma so that 4πγ/N4\pi\gamma/N 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.

empirical_transfer_function_estimate.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example