Skip to content

Commit 0c8bc8b

Browse files
baggepinnenclaude
andcommitted
Normalize the Welch noise spectrum by the window energy
- Normalize the Welch noise spectrum N by the number of windows times the window energy instead of by the number of samples, so that N is a spectral density in the same units as for method = :corr and does not depend on samples outside every window or on the window scaling. wcfft, wcfft_windows and foreach_window return this normalization. - Replace negative values of the residual spectrum by zero and bound the coherence to [0, 1]. - Reject frequency-domain data (InputOutputFreqData) in tfest and coherence. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 5ad8f87 commit 0c8bc8b

2 files changed

Lines changed: 102 additions & 29 deletions

File tree

‎src/frd.jl‎

Lines changed: 51 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ Both `H` and `N` are of type `FRD` (frequency-response data).
206206
207207
- `σ` determines the width of the Gaussian window applied to the estimated correlation functions before FFT. A larger `σ` implies less smoothing.
208208
- `H` = Syu/Suu Process transfer function
209-
- `N` = Sy - |Syu|²/Suu Estimated Noise PSD (also an estimate of the variance of ``H``). Note that a PSD is related to the "noise model" ``N_m`` used in the system identification literature as ``N_{psd} = N_m^* N_m``. The magnitude curve of the noise model can be visualized by plotting `√(N)`.
209+
- `N` = Sy - |Syu|²/Suu Estimated Noise PSD (also an estimate of the variance of ``H``). Note that a PSD is related to the "noise model" ``N_m`` used in the system identification literature as ``N_{psd} = N_m^* N_m``. The magnitude curve of the noise model can be visualized by plotting `√(N)`. `N` is a two-sided spectral density per sample, i.e., white noise of variance ``σ_n^2`` gives ``N ≈ σ_n^2``. With `method = :welch`, the spectral sums are normalized by the number of windows times the energy ``\\sum_t w_t^2`` of the window function ``w``. Negative values of the residual spectrum, caused by rounding errors, are replaced by zero.
210210
- `method`: `:welch` or `:corr`. `:welch` uses the Welch method to estimate the power spectral density, while `:corr` (default) uses the Correlogram approach. If `method = :welch`, the additional keyword arguments `n`, `noverlap` and `window` determine the number of samples per segment (default 10% of data), the number of samples to overlap between segments (default 50%), and the window function to use (default `hamming`), respectively.
211211
- `uncertainty`: `Val(false)` (default) or `Val(true)`. If `Val(true)`, a third return value `σH` is returned, an `FRD` containing the jackknife estimate of the standard deviation of the complex-valued estimate `H` at each frequency, i.e., ``σ_H = \\sqrt{\\operatorname{Var}(\\operatorname{Re} H) + \\operatorname{Var}(\\operatorname{Im} H)}``. Requires `method = :welch`, see Extended help.
212212
@@ -218,21 +218,23 @@ This estimation method is unbiased if the input ``u`` is uncorrelated with the n
218218
The uncertainty estimate is computed with a delete-one jackknife over the Welch windows: with ``K`` windows, ``K`` estimates ``H_{(k)}`` are formed from the spectral sums with the contribution of window ``k`` removed, and the variance is estimated as ``\\frac{K-1}{K} \\sum_k |H_{(k)} - \\bar H|^2``, where ``\\bar H`` is the mean of the ``H_{(k)}``. The estimate assumes that the windows are independent. Overlapping windows are correlated, the jackknife estimate is thus approximate and tends to underestimate the variance slightly for the default overlap of 50%. At least two windows are required, and the estimate is more reliable the more windows are used. The jackknife estimate does not account for bias, such as the bias caused by spectral leakage or by noise that is correlated with the input.
219219
"""
220220
function tfest(d::AbstractIdData, σ::Real = 0.05; method = :corr, n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, uncertainty::Val{U} = Val(false)) where U
221+
check_time_domain(d)
221222
d.nu == 1 || error("Cannot perform tfest on multiple-input data. Consider using time-domain estimation or statespace estimation.")
222223
U && check_uncertainty_method(method)
223224
if d.ny > 1
224225
return stack_outputs([tfest(d[i,1], σ; method, n, noverlap, window, uncertainty) for i in 1:d.ny], Val(U ? 3 : 2))
225226
end
226227
y, u, h = vec(output(d)), vec(input(d)), sampletime(d)
227228
if U
228-
return spectra2tfest_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h, length(y))
229+
return spectra2tfest_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h)
229230
end
230231
if method === :welch
231-
Syy, Suu, Syu = wcfft(y, u, n = n, noverlap = noverlap, window = window)
232+
Syy, Suu, Syu, L = wcfft(y, u, n = n, noverlap = noverlap, window = window)
232233
elseif method === :corr
233234
Syy, Suu, Syu = fft_corr(y, u, σ)
235+
L = length(y)
234236
else error("Unknown method $method") end
235-
return spectra2tfest(Syy, Suu, Syu, h, length(y))
237+
return spectra2tfest(Syy, Suu, Syu, h, L)
236238
end
237239

238240
"""
@@ -243,7 +245,7 @@ Estimate a transfer function using the Welch method, pooled over several data se
243245
244246
Every Welch window lies within a single segment. The cross- and auto-spectral sums are accumulated over the windows of all segments before `H` and `N` are formed, so that the result equals the Welch estimate over the union of the windows of all segments, rather than an average of per-segment estimates. A segment shorter than `n` contains no window and does not contribute. With a single segment, the result equals that of `tfest(ds[1]; method = :welch, n, noverlap, window)`.
245247
246-
The keyword arguments `n`, `noverlap` and `window` have the same meaning as for `tfest(d; method = :welch)`. The noise spectrum `N` is normalized by the total number of samples in the contributing segments. Only `method = :welch` is supported for multiple segments.
248+
The keyword arguments `n`, `noverlap` and `window` have the same meaning as for `tfest(d; method = :welch)`. The noise spectrum `N` is normalized by the number of windows times the energy ``\\sum_t w_t^2`` of the window function ``w``. Only `method = :welch` is supported for multiple segments.
247249
248250
If `uncertainty = Val(true)`, the jackknife estimate `σH` of the standard deviation of `H` is returned as well, computed by deleting one window at a time among the windows of all segments, see `tfest(d::AbstractIdData)`.
249251
@@ -257,27 +259,31 @@ function tfest(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = minimu
257259
end
258260
ys = [vec(output(d)) for d in ds]
259261
us = [vec(input(d)) for d in ds]
260-
L = sum(length(y) for y in ys if length(y) >= n; init = 0)
261262
if U
262-
return spectra2tfest_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h, L)
263+
return spectra2tfest_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h)
263264
end
264-
Syy, Suu, Syu = wcfft(ys, us; n, noverlap, window)
265+
Syy, Suu, Syu, L = wcfft(ys, us; n, noverlap, window)
265266
return spectra2tfest(Syy, Suu, Syu, h, L)
266267
end
267268

269+
"""
270+
H, N = spectra2tfest(Syy, Suu, Syu, h, L)
271+
272+
Form the transfer-function estimate `H` and the noise spectrum `N` from the spectral sums, where `L` is the normalization of the sums (the number of samples for the correlogram method, the number of windows times the window energy for the Welch method). Negative values of the residual spectrum, which arise from rounding errors (or, for the correlogram method, from the lag window), are replaced by zero.
273+
"""
268274
function spectra2tfest(Syy, Suu, Syu, h, L)
269275
w = freqvec(h, Syu)
270276
H = FRD(w, Syu ./ Suu)
271-
N = FRD(w, real.(Syy .- abs2.(Syu) ./ Suu) ./ L)
277+
N = FRD(w, max.(real.(Syy .- abs2.(Syu) ./ Suu), 0) ./ L)
272278
return H, N
273279
end
274280

275281
"""
276-
H, N, σH = spectra2tfest_jackknife(Pyy, Puu, Pyu, h, L)
282+
H, N, σH = spectra2tfest_jackknife(Pyy, Puu, Pyu, L, h)
277283
278-
Form `H` and `N` from the per-window periodograms `Pyy, Puu, Pyu` (frequency × window, see [`wcfft_windows`](@ref)), together with the delete-one jackknife estimate `σH` of the standard deviation of `H`.
284+
Form `H` and `N` from the per-window periodograms `Pyy, Puu, Pyu` (frequency × window) and the normalization `L`, see [`wcfft_windows`](@ref), together with the delete-one jackknife estimate `σH` of the standard deviation of `H`.
279285
"""
280-
function spectra2tfest_jackknife(Pyy, Puu, Pyu, h, L)
286+
function spectra2tfest_jackknife(Pyy, Puu, Pyu, L, h)
281287
Syy, Suu, Syu = vec(sum(Pyy, dims = 2)), vec(sum(Puu, dims = 2)), vec(sum(Pyu, dims = 2))
282288
H, N = spectra2tfest(Syy, Suu, Syu, h, L)
283289
σH = jackknife_std(leave_one_out(Pyu) ./ leave_one_out(Puu))
@@ -333,13 +339,22 @@ function stack_outputs(HNs, ::Val{M}) where M
333339
ntuple(j -> FRD(w, reshape(reduce(vcat, [transpose(hn[j].r) for hn in HNs]), ny, 1, :)), Val(M))
334340
end
335341

342+
"""
343+
check_time_domain(d)
344+
345+
Throw an `ArgumentError` if `d` is not time-domain input-output data. Spectral estimation treats the samples of `d` as a time series, which does not apply to frequency-domain data.
346+
"""
347+
check_time_domain(d::InputOutputFreqData) = throw(ArgumentError("Spectral estimation requires time-domain data, but frequency-domain data of type InputOutputFreqData was given. Frequency-response data can be represented as an FRD, see `FRD`."))
348+
check_time_domain(d::AbstractIdData) = nothing
349+
336350
"""
337351
h, ny = check_segments(ds)
338352
339-
Verify that the data segments `ds` are non-empty, single-input, and share the sample time and the number of outputs. Returns the common sample time and number of outputs.
353+
Verify that the data segments `ds` are non-empty, time-domain, single-input, and share the sample time and the number of outputs. Returns the common sample time and number of outputs.
340354
"""
341355
function check_segments(ds::AbstractVector{<:AbstractIdData})
342356
isempty(ds) && throw(ArgumentError("At least one data segment is required"))
357+
foreach(check_time_domain, ds)
343358
allequal(sampletime(d) for d in ds) || throw(ArgumentError("All data segments must have the same sample time"))
344359
allequal(noutputs(d) for d in ds) || throw(ArgumentError("All data segments must have the same number of outputs"))
345360
all(ninputs(d) == 1 for d in ds) || throw(ArgumentError("Spectral estimation with multiple data segments only supports single-input data"))
@@ -380,6 +395,7 @@ For the signal model ``y = Gu + v``, ``κ²`` is defined as
380395
from which it is obvious that ``0 ≤ κ² ≤ 1`` and that κ² is close to 1 if the noise energy ``S_{vv}`` is small compared to the output energy due to the input ``S_{uu}|G(iω)|^2``.
381396
"""
382397
function coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, method=:welch, σ = 0.05, uncertainty::Val{U} = Val(false)) where U
398+
check_time_domain(d)
383399
noutputs(d) == 1 || throw(ArgumentError("coherence only supports a single output. Index the data object like `d[i,:]` to obtain the `i`:th output."))
384400
U && check_uncertainty_method(method)
385401
if ninputs(d) > 1
@@ -423,24 +439,31 @@ function coherence(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = mi
423439
end
424440

425441
function spectra2coherence(Syy, Suu, Syu, h)
426-
k = @. abs2(Syu) / (Suu * Syy)
442+
k = coherence_value.(Syy, Suu, Syu)
427443
FRD(freqvec(h, k), k)
428444
end
429445

430-
function spectra2coherence_jackknife(Pyy, Puu, Pyu, h)
446+
"""
447+
κ² = coherence_value(Syy, Suu, Syu)
448+
449+
Squared coherence at one frequency, bounded to ``[0, 1]``. Values outside this interval arise from rounding errors, or, for the correlogram method, from the lag window.
450+
"""
451+
coherence_value(Syy, Suu, Syu) = clamp(abs2(Syu) / (Suu * Syy), 0, 1)
452+
453+
function spectra2coherence_jackknife(Pyy, Puu, Pyu, L, h)
431454
Syy, Suu, Syu = vec(sum(Pyy, dims = 2)), vec(sum(Puu, dims = 2)), vec(sum(Pyu, dims = 2))
432455
# With a single retained window, every delete-one coherence equals one
433456
check_window_count(size(Pyu, 2), 3)
434457
κ = spectra2coherence(Syy, Suu, Syu, h)
435-
σκ = jackknife_std(@. abs2($leave_one_out(Pyu)) / ($leave_one_out(Puu) * $leave_one_out(Pyy)))
458+
σκ = jackknife_std(coherence_value.(leave_one_out(Pyy), leave_one_out(Puu), leave_one_out(Pyu)))
436459
return κ, FRD(κ.w, σκ)
437460
end
438461

439462
"""
440-
Syy, Suu, Syu = wcfft(y, u; n = length(y) ÷ 10, noverlap = n ÷ 2, window = hamming)
441-
Syy, Suu, Syu = wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window)
463+
Syy, Suu, Syu, L = wcfft(y, u; n = length(y) ÷ 10, noverlap = n ÷ 2, window = hamming)
464+
Syy, Suu, Syu, L = wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window)
442465
443-
Sums of the windowed periodograms (Welch method) of the output `y` and input `u`: the auto-spectral sums `Syy`, `Suu` and the cross-spectral sum `Syu`, over the non-negative frequency bins. The sums are not normalized by the number of windows.
466+
Sums of the windowed periodograms (Welch method) of the output `y` and input `u`: the auto-spectral sums `Syy`, `Suu` and the cross-spectral sum `Syu`, over the non-negative frequency bins. The sums are not normalized; `L` is the number of windows times the energy ``\\sum_t w_t^2`` of the window function ``w``, such that `Syy ./ L` is an estimate of the (two-sided) power spectral density of `y` per sample.
444467
445468
If vectors of signal segments `ys, us` are given, the sums are accumulated over the windows of all segments, with every window lying within a single segment. A segment shorter than `n` contributes no window.
446469
@@ -454,36 +477,36 @@ function wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:Abstra
454477
Syy = zeros(nf)
455478
Suu = zeros(nf)
456479
Syu = zeros(ComplexF64, nf)
457-
foreach_window(ys, us; n, noverlap, window) do xy, xu
480+
L = foreach_window(ys, us; n, noverlap, window) do xy, xu
458481
@. Syu += xy * conj(xu)
459482
@. Syy += abs2(xy)
460483
@. Suu += abs2(xu)
461484
end
462-
Syy, Suu, Syu
485+
Syy, Suu, Syu, L
463486
end
464487

465488
"""
466-
Pyy, Puu, Pyu = wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window)
489+
Pyy, Puu, Pyu, L = wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window)
467490
468-
Windowed periodograms of the individual Welch windows of the signal segments `ys, us`, as matrices of size (number of frequency bins) × (number of windows). The row sums equal the sums returned by [`wcfft`](@ref).
491+
Windowed periodograms of the individual Welch windows of the signal segments `ys, us`, as matrices of size (number of frequency bins) × (number of windows). The row sums and the normalization `L` equal those returned by [`wcfft`](@ref).
469492
"""
470493
function wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n = minimum(length, ys) ÷ 10, noverlap = n ÷ 2, window = hamming)
471494
Pyy = Vector{Vector{Float64}}()
472495
Puu = Vector{Vector{Float64}}()
473496
Pyu = Vector{Vector{ComplexF64}}()
474-
foreach_window(ys, us; n, noverlap, window) do xy, xu
497+
L = foreach_window(ys, us; n, noverlap, window) do xy, xu
475498
# The products are formed in the precision of the transforms, as in wcfft
476499
push!(Pyy, abs2.(xy))
477500
push!(Puu, abs2.(xu))
478501
push!(Pyu, xy .* conj.(xu))
479502
end
480-
reduce(hcat, Pyy), reduce(hcat, Puu), reduce(hcat, Pyu)
503+
reduce(hcat, Pyy), reduce(hcat, Puu), reduce(hcat, Pyu), L
481504
end
482505

483506
"""
484-
foreach_window(f, ys, us; n, noverlap, window)
507+
L = foreach_window(f, ys, us; n, noverlap, window)
485508
486-
Call `f(xy, xu)` with the discrete Fourier transforms (non-negative frequencies) of every windowed segment of length `n` of the output and input signals, for the windows of all signal segments in `ys, us`. Every window lies within a single segment, and a segment shorter than `n` contributes no window.
509+
Call `f(xy, xu)` with the discrete Fourier transforms (non-negative frequencies) of every windowed segment of length `n` of the output and input signals, for the windows of all signal segments in `ys, us`. Every window lies within a single segment, and a segment shorter than `n` contributes no window. Returns the number of windows times the energy ``\\sum_t w_t^2`` of the window function.
487510
"""
488511
function foreach_window(f, ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window)
489512
length(ys) == length(us) || throw(DimensionMismatch("The numbers of output and input segments differ"))
@@ -501,7 +524,7 @@ function foreach_window(f, ys::AbstractVector{<:AbstractVector}, us::AbstractVec
501524
nwin += length(uw)
502525
end
503526
nwin > 0 || throw(ArgumentError("No data segment is at least as long as the window length n = $n"))
504-
nothing
527+
nwin * norm2
505528
end
506529

507530
function multiple_coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, σ = 0.05, uncertainty::Val{U} = Val(false)) where U

‎test/test_frd.jl‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,9 @@ littlefrd = FRD([1, 2], [im, 2*im])
225225
@test Ryu ≈ Syu
226226
H, N = tfest(ds; kw...)
227227
@test H.r ≈ Syu ./ Suu
228-
@test N.r ≈ (Syy .- abs2.(Syu) ./ Suu) ./ sum(lengths[1:end-1])
228+
win = DSP.hanning(nw)
229+
nwin = sum(length(1:nw÷2:N-nw+1) for N in lengths[1:end-1])
230+
@test N.r ≈ (Syy .- abs2.(Syu) ./ Suu) ./ (nwin * sum(abs2, win))
229231
@test coherence(ds; kw...).r ≈ abs2.(Syu) ./ (Suu .* Syy)
230232

231233
# A known transfer function is recovered from several noisy segments
@@ -372,3 +374,51 @@ end
372374
@test_throws ArgumentError coherence(d; method = :corr, uncertainty = Val(true))
373375
@test_throws ArgumentError tfest(d; method = :welch, uncertainty = Val(true), n = 4000) # a single window
374376
end
377+
378+
@testset "Normalization and range of Welch spectral estimates" begin
379+
@info "Testing normalization and range of Welch spectral estimates"
380+
Random.seed!(0)
381+
G = tf([1, 0.5], [1, -0.9, 0.5], 1)
382+
σn = 0.3
383+
T = 20000
384+
u = randn(1, T)
385+
d = iddata(lsim(G, u)[1] .+ σn .* randn(1, T), u, 1)
386+
387+
# White noise of variance σn² gives a noise spectrum close to σn² for every window function
388+
inner(N) = N.r[2:end-1]
389+
dv = iddata(σn .* randn(1, T), u, 1)
390+
for kw in ((; n = 256), (; n = 256, window = nothing), (; n = 256, noverlap = 0, window = DSP.hanning))
391+
_, N = tfest(dv; method = :welch, kw...)
392+
@test mean(inner(N)) ≈ σn^2 rtol = 0.05
393+
_, Nv = tfest([dv[1:10000], dv[10001:end]]; kw...)
394+
@test mean(inner(Nv)) ≈ σn^2 rtol = 0.05
395+
end
396+
# The same holds with a dynamic system if the window function suppresses leakage
397+
_, N = tfest(d; method = :welch, n = 256)
398+
@test mean(inner(N)) ≈ σn^2 rtol = 0.1
399+
# The correlogram method has the same units, its estimate is biased low by the smoothing of the lag window
400+
_, Nc = tfest(d; method = :corr)
401+
@test mean(inner(Nc)) ≈ σn^2 rtol = 0.25
402+
403+
# Samples outside every window do not affect the noise spectrum
404+
nw = 256
405+
kw = (; n = nw, noverlap = 0, window = nothing)
406+
dsl = [d[1:2nw-1], d[2nw+1:4nw-1]] # each segment contains one window and nw - 1 unused samples
407+
@test tfest([d[1:nw], d[2nw+1:3nw]]; kw...)[2].r ≈ tfest(dsl; kw...)[2].r
408+
409+
# A single window gives a non-negative noise spectrum and a coherence in [0, 1]
410+
_, N1 = tfest(d[1:nw]; method = :welch, n = nw)
411+
@test all(≥(0), N1.r)
412+
@test_nowarn sqrt(N1)
413+
κ1 = coherence(d[1:nw]; n = nw)
414+
@test all(k -> 0 ≤ k ≤ 1, κ1.r)
415+
@test all(k -> 0 ≤ k ≤ 1, coherence(d; method = :corr).r)
416+
417+
# Frequency-domain data are rejected
418+
df = iddata(randn(1, 100), randn(1, 100), range(0, π, length = 100))
419+
@test_throws ArgumentError tfest(df; method = :welch, n = 20)
420+
@test_throws ArgumentError tfest(df)
421+
@test_throws ArgumentError coherence(df; n = 20)
422+
@test_throws ArgumentError tfest([df]; n = 20)
423+
@test_throws ArgumentError coherence([df]; n = 20)
424+
end

0 commit comments

Comments
 (0)