You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 0c8bc8b
Browse filesBrowse the repository at this point in the historyBrowse files
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>
Copy file name to clipboardExpand all lines: src/frd.jl
+51-28Lines changed: 51 additions & 28 deletions
Original file line number
Diff line number
Diff line change
@@ -206,7 +206,7 @@ Both `H` and `N` are of type `FRD` (frequency-response data).
206
206
207
207
- `σ` determines the width of the Gaussian window applied to the estimated correlation functions before FFT. A larger `σ` implies less smoothing.
208
208
- `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.
210
210
- `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.
211
211
- `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.
212
212
@@ -218,21 +218,23 @@ This estimation method is unbiased if the input ``u`` is uncorrelated with the n
218
218
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.
219
219
"""
220
220
functiontfest(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)
221
222
d.nu ==1||error("Cannot perform tfest on multiple-input data. Consider using time-domain estimation or statespace estimation.")
222
223
U &&check_uncertainty_method(method)
223
224
if d.ny >1
224
225
returnstack_outputs([tfest(d[i,1], σ; method, n, noverlap, window, uncertainty) for i in1:d.ny], Val(U ?3:2))
225
226
end
226
227
y, u, h =vec(output(d)), vec(input(d)), sampletime(d)
227
228
if U
228
-
returnspectra2tfest_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h, length(y))
229
+
returnspectra2tfest_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h)
229
230
end
230
231
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)
232
233
elseif method ===:corr
233
234
Syy, Suu, Syu =fft_corr(y, u, σ)
235
+
L =length(y)
234
236
elseerror("Unknown method $method") end
235
-
returnspectra2tfest(Syy, Suu, Syu, h, length(y))
237
+
returnspectra2tfest(Syy, Suu, Syu, h, L)
236
238
end
237
239
238
240
"""
@@ -243,7 +245,7 @@ Estimate a transfer function using the Welch method, pooled over several data se
243
245
244
246
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)`.
245
247
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.
247
249
248
250
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)`.
249
251
@@ -257,27 +259,31 @@ function tfest(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = minimu
257
259
end
258
260
ys = [vec(output(d)) for d in ds]
259
261
us = [vec(input(d)) for d in ds]
260
-
L =sum(length(y) for y in ys iflength(y) >= n; init =0)
261
262
if U
262
-
returnspectra2tfest_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h, L)
263
+
returnspectra2tfest_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h)
263
264
end
264
-
Syy, Suu, Syu =wcfft(ys, us; n, noverlap, window)
265
+
Syy, Suu, Syu, L=wcfft(ys, us; n, noverlap, window)
265
266
returnspectra2tfest(Syy, Suu, Syu, h, L)
266
267
end
267
268
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
+
"""
268
274
functionspectra2tfest(Syy, Suu, Syu, h, L)
269
275
w =freqvec(h, Syu)
270
276
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)
272
278
return H, N
273
279
end
274
280
275
281
"""
276
-
H, N, σH = spectra2tfest_jackknife(Pyy, Puu, Pyu, h, L)
282
+
H, N, σH = spectra2tfest_jackknife(Pyy, Puu, Pyu, L, h)
277
283
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`.
@@ -333,13 +339,22 @@ function stack_outputs(HNs, ::Val{M}) where M
333
339
ntuple(j ->FRD(w, reshape(reduce(vcat, [transpose(hn[j].r) for hn in HNs]), ny, 1, :)), Val(M))
334
340
end
335
341
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
+
336
350
"""
337
351
h, ny = check_segments(ds)
338
352
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.
isempty(ds) &&throw(ArgumentError("At least one data segment is required"))
357
+
foreach(check_time_domain, ds)
343
358
allequal(sampletime(d) for d in ds) ||throw(ArgumentError("All data segments must have the same sample time"))
344
359
allequal(noutputs(d) for d in ds) ||throw(ArgumentError("All data segments must have the same number of outputs"))
345
360
all(ninputs(d) ==1for 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
380
395
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``.
381
396
"""
382
397
functioncoherence(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)
383
399
noutputs(d) ==1||throw(ArgumentError("coherence only supports a single output. Index the data object like `d[i,:]` to obtain the `i`:th output."))
384
400
U &&check_uncertainty_method(method)
385
401
ifninputs(d) >1
@@ -423,24 +439,31 @@ function coherence(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = mi
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.
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)
442
465
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.
444
467
445
468
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.
446
469
@@ -454,36 +477,36 @@ function wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:Abstra
454
477
Syy =zeros(nf)
455
478
Suu =zeros(nf)
456
479
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
458
481
@. Syu += xy *conj(xu)
459
482
@. Syy +=abs2(xy)
460
483
@. Suu +=abs2(xu)
461
484
end
462
-
Syy, Suu, Syu
485
+
Syy, Suu, Syu, L
463
486
end
464
487
465
488
"""
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)
467
490
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).
469
492
"""
470
493
functionwcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n =minimum(length, ys) ÷10, noverlap = n ÷2, window = hamming)
471
494
Pyy =Vector{Vector{Float64}}()
472
495
Puu =Vector{Vector{Float64}}()
473
496
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
475
498
# The products are formed in the precision of the transforms, as in wcfft
reduce(hcat, Pyy), reduce(hcat, Puu), reduce(hcat, Pyu), L
481
504
end
482
505
483
506
"""
484
-
foreach_window(f, ys, us; n, noverlap, window)
507
+
L = foreach_window(f, ys, us; n, noverlap, window)
485
508
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.
487
510
"""
488
511
functionforeach_window(f, ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window)
489
512
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
501
524
nwin +=length(uw)
502
525
end
503
526
nwin >0||throw(ArgumentError("No data segment is at least as long as the window length n = $n"))
504
-
nothing
527
+
nwin * norm2
505
528
end
506
529
507
530
functionmultiple_coherence(d::AbstractIdData; n =length(d) ÷10, noverlap = n ÷2, window = hamming, σ =0.05, uncertainty::Val{U}=Val(false)) where U
0 commit comments