From 2590bac345d955904aff59c12f13eed2cc10a9fc Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 2 Dec 2026 14:12:59 +0000 Subject: [PATCH 1/6] Jackknife uncertainty estimates for tfest and coherence Add the keyword argument `uncertainty::Val = Val(false)` to `tfest` and `coherence` (single dataset, vector of data segments, and multiple-input coherence). With `Val(true)`, the delete-one jackknife estimate of the standard deviation over the Welch windows is returned as an additional FRD. Only `method = :welch` is supported. The multiple-output branch of `tfest(d::AbstractIdData)` now forwards `method`, `n`, `noverlap` and `window` to the per-output estimates. Co-Authored-By: Claude Opus 5.5 --- docs/src/freq.md | 14 ++++ src/frd.jl | 210 +++++++++++++++++++++++++++++++++++++++-------- test/test_frd.jl | 96 ++++++++++++++++++++++ 3 files changed, 285 insertions(+), 35 deletions(-) diff --git a/docs/src/freq.md b/docs/src/freq.md index ae1eaef4..3dda399e 100644 --- a/docs/src/freq.md +++ b/docs/src/freq.md @@ -49,6 +49,20 @@ k = coherence(ds; n = 1000) nothing # hide ``` +### Uncertainty estimates +With the Welch method, [`tfest`](@ref) and [`coherence`](@ref) optionally return an estimate of the standard deviation of the estimates at each frequency. The standard deviation is estimated with a delete-one jackknife over the Welch windows, and is requested with the keyword argument `uncertainty = Val(true)`: +```@example npfreq +G, N, σG = tfest(dn; method = :welch, n = 1000, uncertainty = Val(true)) +k, σk = coherence(dn; n = 1000, uncertainty = Val(true)) +inds = 2:length(G.w) # exclude the zero frequency from the logarithmic axis +mag = abs.(G.r[inds]) +plot(G.w[inds], mag, ribbon = (min.(2σG.r[inds], 0.99mag), 2σG.r[inds]), xscale = :log10, yscale = :log10, lab = "|G| ± 2σ", layout = 2) +plot!(G.w[inds], abs.(vec(freqresp(c2d(sys, h), G.w[inds]))), sp = 1, lab = "True system", l = (:black, :dash)) +plot!(k.w[inds], k.r[inds], ribbon = 2σk.r[inds], xscale = :log10, yscale = :identity, ylims = (0, 1), sp = 2, lab = "κ² ± 2σ") +DisplayAs.PNG(current()) # hide +``` +The jackknife estimate treats the windows as independent. Overlapping windows are correlated, the estimate is therefore approximate. It does not account for bias, such as the bias caused by spectral leakage at sharp resonances. + See the [example notebooks](https://github.com/JuliaControl/ControlExamples.jl?files=1) for more details. ## Parametric estimation diff --git a/src/frd.jl b/src/frd.jl index a9ab25b4..872a90da 100644 --- a/src/frd.jl +++ b/src/frd.jl @@ -197,7 +197,8 @@ ControlSystemsBase.c2d(f::FRD, Ts::Real; kwargs...) = FRD(c2d(f.w, Ts; kwargs... """ - H, N = tfest(data, σ = 0.05, method = :corr) + H, N = tfest(data, σ = 0.05; method = :corr) + H, N, σH = tfest(data; method = :welch, uncertainty = Val(true)) Estimate a transfer function model using the Correlogram approach (default) using the signal model ``y = H(iω)u + n``. @@ -207,21 +208,25 @@ Both `H` and `N` are of type `FRD` (frequency-response data). - `H` = Syu/Suu Process transfer function - `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)`. - `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. +- `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. A Welch estimate pooled over several data segments is obtained by passing a vector of data objects, see `tfest(ds::AbstractVector{<:AbstractIdData})`. # Extended help This estimation method is unbiased if the input ``u`` is uncorrelated with the noise ``n``, but is otherwise biased (e.g., for identification in closed loop). + +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. """ -function tfest(d::AbstractIdData, σ::Real = 0.05; method = :corr, n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming) +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 d.nu == 1 || error("Cannot perform tfest on multiple-input data. Consider using time-domain estimation or statespace estimation.") + U && check_uncertainty_method(method) if d.ny > 1 - HNs = [tfest(d[i,1], σ) for i in 1:d.ny] - HR = reshape(reduce(vcat, [transpose(hn[1].r) for hn in HNs]), d.ny, 1, :) - NR = reshape(reduce(vcat, [transpose(hn[2].r) for hn in HNs]), d.ny, 1, :) - return FRD(HNs[1][1].w, HR), FRD(HNs[1][1].w, NR) + return stack_outputs([tfest(d[i,1], σ; method, n, noverlap, window, uncertainty) for i in 1:d.ny], Val(U ? 3 : 2)) end y, u, h = vec(output(d)), vec(input(d)), sampletime(d) + if U + return spectra2tfest_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h, length(y)) + end if method === :welch Syy, Suu, Syu = wcfft(y, u, n = n, noverlap = noverlap, window = window) elseif method === :corr @@ -232,6 +237,7 @@ end """ H, N = tfest(ds::AbstractVector{<:AbstractIdData}; n = minimum(length, ds) ÷ 10, noverlap = n ÷ 2, window = hamming) + H, N, σH = tfest(ds::AbstractVector{<:AbstractIdData}; uncertainty = Val(true), n, noverlap, window) Estimate a transfer function using the Welch method, pooled over several data segments `ds` (for example, separate experiments or disjoint parts of one experiment). The segments may have different lengths, but must share the sample time and the numbers of inputs and outputs. @@ -239,21 +245,23 @@ Every Welch window lies within a single segment. The cross- and auto-spectral su 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. +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)`. + See also [`coherence`](@ref), which accepts a vector of data segments in the same way. """ -function tfest(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = minimum(length, ds) ÷ 10, noverlap = n ÷ 2, window = hamming) +function tfest(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = minimum(length, ds) ÷ 10, noverlap = n ÷ 2, window = hamming, uncertainty::Val{U} = Val(false)) where U method === :welch || throw(ArgumentError("tfest with multiple data segments only supports method = :welch")) h, ny = check_segments(ds) if ny > 1 - HNs = [tfest([d[i,1] for d in ds]; n, noverlap, window) for i in 1:ny] - HR = reshape(reduce(vcat, [transpose(hn[1].r) for hn in HNs]), ny, 1, :) - NR = reshape(reduce(vcat, [transpose(hn[2].r) for hn in HNs]), ny, 1, :) - return FRD(HNs[1][1].w, HR), FRD(HNs[1][1].w, NR) + return stack_outputs([tfest([d[i,1] for d in ds]; n, noverlap, window, uncertainty) for i in 1:ny], Val(U ? 3 : 2)) end ys = [vec(output(d)) for d in ds] us = [vec(input(d)) for d in ds] + L = sum(length(y) for y in ys if length(y) >= n; init = 0) + if U + return spectra2tfest_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h, L) + end Syy, Suu, Syu = wcfft(ys, us; n, noverlap, window) - L = sum(length(y) for y in ys if length(y) >= n) return spectra2tfest(Syy, Suu, Syu, h, L) end @@ -264,6 +272,43 @@ function spectra2tfest(Syy, Suu, Syu, h, L) return H, N end +""" + H, N, σH = spectra2tfest_jackknife(Pyy, Puu, Pyu, h, L) + +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`. +""" +function spectra2tfest_jackknife(Pyy, Puu, Pyu, h, L) + Syy, Suu, Syu = vec(sum(Pyy, dims = 2)), vec(sum(Puu, dims = 2)), vec(sum(Pyu, dims = 2)) + H, N = spectra2tfest(Syy, Suu, Syu, h, L) + σH = jackknife_std((Syu .- Pyu) ./ (Suu .- Puu)) + return H, N, FRD(H.w, σH) +end + +""" + σ = jackknife_std(θ::AbstractMatrix) + +Delete-one jackknife estimate of the standard deviation of an estimator, given the delete-one estimates `θ[:, k]` (one column per deleted observation, one row per estimated quantity). For complex-valued `θ`, the result is the square root of the sum of the variances of the real and imaginary parts. +""" +function jackknife_std(θ::AbstractMatrix) + K = size(θ, 2) + K >= 2 || throw(ArgumentError("The jackknife uncertainty estimate requires at least two Welch windows, but only $K window is available. Decrease the window length `n`.")) + θ̄ = mean(θ, dims = 2) + sqrt.((K - 1) / K .* vec(sum(abs2, θ .- θ̄, dims = 2))) +end + +check_uncertainty_method(method) = method === :welch || throw(ArgumentError("The uncertainty estimate is only available for method = :welch, got method = $(repr(method))")) + +""" + stack_outputs(HNs, ::Val{M}) + +Combine a vector of `M`-tuples of single-output `FRD`s, one tuple per output, into an `M`-tuple of `FRD`s with response arrays of size `ny × 1 × nω`. +""" +function stack_outputs(HNs, ::Val{M}) where M + ny = length(HNs) + w = HNs[1][1].w + ntuple(j -> FRD(w, reshape(reduce(vcat, [transpose(hn[j].r) for hn in HNs]), ny, 1, :)), Val(M)) +end + """ h, ny = check_segments(ds) @@ -291,29 +336,35 @@ end """ κ² = coherence(d; n = length(d)÷10, noverlap = n÷2, window=hamming, method=:welch) + κ², σκ² = coherence(d; uncertainty = Val(true), n, noverlap, window) Calculates the magnitude-squared coherence Function. κ² close to 1 indicates a good explainability of energy in the output signal by energy in the input signal. κ² << 1 indicates that either the system is nonlinear, or a strong noise contributes to the output energy. - κ: Squared coherence function in the form of an [`FRD`](@ref). - `method`: `:welch` or `:corr`. `:welch` uses the Welch method to estimate the power spectral density, while `:corr` uses the Correlogram approach . For `method = :corr`, the additional keyword argument `σ` determines the width of the Gaussian window applied to the estimated correlation functions before FFT. A larger `σ` implies less smoothing. +- `uncertainty`: `Val(false)` (default) or `Val(true)`. If `Val(true)`, a second return value `σκ²` is returned, an `FRD` containing the delete-one jackknife estimate of the standard deviation of κ² over the Welch windows. Requires `method = :welch`. See the extended help of [`tfest`](@ref) for a description of the jackknife estimate and its limitations. For multiple inputs, the uncertainty of the multiple coherence is estimated in the same way. A Welch estimate pooled over several data segments is obtained by passing a vector of data objects, see `coherence(ds::AbstractVector{<:AbstractIdData})`. See also [`coherenceplot`](@ref) # Extended help: -For the signal model ``y = Gu + v``, ``κ²`` is defined as +For the signal model ``y = Gu + v``, ``κ²`` is defined as ```math κ(ω)^2 = \\dfrac{S_{uy}}{S_{uu} S_{yy}} = \\dfrac{|G(iω)|^2S_{uu}^2}{S_{uu} (|G(iω)|^2S_{uu}^2 + S_{vv})} = \\dfrac{1}{1 + \\dfrac{S_{vv}}{S_{uu}|G(iω)|^2}} ``` 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``. """ -function coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, method=:welch, σ = 0.05) +function coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, method=:welch, σ = 0.05, uncertainty::Val{U} = Val(false)) where U noutputs(d) == 1 || throw(ArgumentError("coherence only supports a single output. Index the data object like `d[i,:]` to obtain the `i`:th output.")) + U && check_uncertainty_method(method) if ninputs(d) > 1 - return multiple_coherence(d; n, noverlap, window, σ) + return multiple_coherence(d; n, noverlap, window, σ, uncertainty) end y, u, h = vec(output(d)), vec(input(d)), sampletime(d) + if U + return spectra2coherence_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h) + end if method === :welch Syy, Suu, Syu = wcfft(y, u, n = n, noverlap = noverlap, window = window) else @@ -326,16 +377,24 @@ end """ κ² = coherence(ds::AbstractVector{<:AbstractIdData}; n = minimum(length, ds) ÷ 10, noverlap = n ÷ 2, window = hamming) + κ², σκ² = coherence(ds::AbstractVector{<:AbstractIdData}; uncertainty = Val(true), n, noverlap, window) Calculate the magnitude-squared coherence function using the Welch method, pooled over several data segments `ds` of possibly different lengths. The cross- and auto-spectral sums are accumulated over the Welch windows of all segments, each window lying within a single segment, before the coherence is formed. A segment shorter than `n` does not contribute. With a single segment, the result equals that of `coherence(ds[1]; n, noverlap, window)`. +If `uncertainty = Val(true)`, the jackknife estimate `σκ²` of the standard deviation of κ² is returned as well, computed by deleting one window at a time among the windows of all segments. + Only single-input, single-output data and `method = :welch` are supported for multiple segments. See [`tfest`](@ref) for the corresponding transfer-function estimate. """ -function coherence(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = minimum(length, ds) ÷ 10, noverlap = n ÷ 2, window = hamming) +function coherence(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = minimum(length, ds) ÷ 10, noverlap = n ÷ 2, window = hamming, uncertainty::Val{U} = Val(false)) where U method === :welch || throw(ArgumentError("coherence with multiple data segments only supports method = :welch")) h, ny = check_segments(ds) ny == 1 || throw(ArgumentError("coherence only supports a single output. Index the data objects like `d[i,:]` to obtain the `i`:th output.")) - Syy, Suu, Syu = wcfft([vec(output(d)) for d in ds], [vec(input(d)) for d in ds]; n, noverlap, window) + ys = [vec(output(d)) for d in ds] + us = [vec(input(d)) for d in ds] + if U + return spectra2coherence_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h) + end + Syy, Suu, Syu = wcfft(ys, us; n, noverlap, window) return spectra2coherence(Syy, Suu, Syu, h) end @@ -344,6 +403,13 @@ function spectra2coherence(Syy, Suu, Syu, h) FRD(freqvec(h, k), k) end +function spectra2coherence_jackknife(Pyy, Puu, Pyu, h) + Syy, Suu, Syu = vec(sum(Pyy, dims = 2)), vec(sum(Puu, dims = 2)), vec(sum(Pyu, dims = 2)) + κ = spectra2coherence(Syy, Suu, Syu, h) + σκ = jackknife_std(@. abs2(Syu - Pyu) / ((Suu - Puu) * (Syy - Pyy))) + return κ, FRD(κ.w, σκ) +end + """ Syy, Suu, Syu = wcfft(y, u; n = length(y) ÷ 10, noverlap = n ÷ 2, window = hamming) Syy, Suu, Syu = wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window) @@ -351,18 +417,51 @@ end 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. 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. + +See also [`wcfft_windows`](@ref), which returns the periodograms of the individual windows. """ wcfft(y::AbstractVector{<:Number}, u::AbstractVector{<:Number}; n = length(y) ÷ 10, kwargs...) = wcfft([y], [u]; n, kwargs...) function wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n = minimum(length, ys) ÷ 10, noverlap = n ÷ 2, window = hamming) - length(ys) == length(us) || throw(DimensionMismatch("The numbers of output and input segments differ")) - win, norm2 = DSP.Periodograms.compute_window(window, n) - nfft = nextfastfft(n) - nf = nfft ÷ 2 + 1 + nf = nextfastfft(n) ÷ 2 + 1 Syy = zeros(nf) Suu = zeros(nf) Syu = zeros(ComplexF64, nf) + foreach_window(ys, us; n, noverlap, window) do xy, xu + @. Syu += xy * conj(xu) + @. Syy += abs2(xy) + @. Suu += abs2(xu) + end + Syy, Suu, Syu +end + +""" + Pyy, Puu, Pyu = wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window) + +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). +""" +function wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n = minimum(length, ys) ÷ 10, noverlap = n ÷ 2, window = hamming) + Xy = Vector{Vector{ComplexF64}}() + Xu = Vector{Vector{ComplexF64}}() + foreach_window(ys, us; n, noverlap, window) do xy, xu + push!(Xy, xy) + push!(Xu, xu) + end + Y = reduce(hcat, Xy) + X = reduce(hcat, Xu) + abs2.(Y), abs2.(X), Y .* conj.(X) +end + +""" + foreach_window(f, ys, us; n, noverlap, window) + +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. +""" +function foreach_window(f, ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window) + length(ys) == length(us) || throw(DimensionMismatch("The numbers of output and input segments differ")) + win, norm2 = DSP.Periodograms.compute_window(window, n) + nfft = nextfastfft(n) nwin = 0 for (y, u) in zip(ys, us) length(y) == length(u) || throw(DimensionMismatch("Input and output segments have different lengths")) @@ -370,43 +469,84 @@ function wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:Abstra uw = arraysplit(u, n, noverlap, nfft, win) yw = arraysplit(y, n, noverlap, nfft, win) for i in eachindex(uw) - xy = rfft(yw[i]) - xu = rfft(uw[i]) - @. Syu += xy * conj(xu) - @. Syy += abs2(xy) - @. Suu += abs2(xu) + f(rfft(yw[i]), rfft(uw[i])) end nwin += length(uw) end nwin > 0 || throw(ArgumentError("No data segment is at least as long as the window length n = $n")) - Syy, Suu, Syu + nothing end -function multiple_coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, σ = 0.05) +function multiple_coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, σ = 0.05, uncertainty::Val{U} = Val(false)) where U noutputs(d) == 1 || throw(ArgumentError("multiple_coherence only supports a single output.")) ninputs(d) > 1 || throw(ArgumentError("multiple_coherence requires multiple inputs. Use `coherence` for single input.")) - + y = vec(output(d)) u = time1(input(d)) h = sampletime(d) + U && return multiple_coherence_jackknife(y, u, h; n, noverlap, window) + Syy, Suu, Syu = wcfft_mimo(y, u, n = n, noverlap = noverlap, window = window) n_freqs = length(Syy) γ2 = zeros(n_freqs) - + for i in 1:n_freqs - s_xy = conj(Syu[i]) - num = real(dot(s_xy, Suu[i] \ s_xy)) - γ2[i] = num / Syy[i] + γ2[i] = multiple_coherence_value(Syy[i], Suu[i], Syu[i]) end - γ2 = clamp.(γ2, 0.0, 1.0) - Sch = FRD(freqvec(h, γ2), γ2) return Sch end +function multiple_coherence_value(Syy, Suu, Syu) + s_xy = conj(Syu) + num = real(dot(s_xy, Suu \ s_xy)) + clamp(num / Syy, 0.0, 1.0) +end + +function multiple_coherence_jackknife(y, u, h; n, noverlap, window) + Y, X = wcfft_mimo_windows(y, u; n, noverlap, window) + n_freqs, K = size(Y) + γ2 = zeros(n_freqs) + γ2j = zeros(n_freqs, K) + for f in 1:n_freqs + Xf = X[f, :, :] # n_inputs × K + Yf = Y[f, :] + Syy = sum(abs2, Yf) + Suu = Xf * Xf' + Syu = conj.(Xf) * Yf + γ2[f] = multiple_coherence_value(Syy, Suu, Syu) + for k in 1:K + xk = Xf[:, k] + γ2j[f, k] = multiple_coherence_value(Syy - abs2(Yf[k]), Suu - xk * xk', Syu - Yf[k] .* conj.(xk)) + end + end + w = freqvec(h, γ2) + FRD(w, γ2), FRD(w, jackknife_std(γ2j)) +end + +""" + Y, X = wcfft_mimo_windows(y, u; n, noverlap, window) + +Discrete Fourier transforms of the windows used in [`wcfft_mimo`](@ref): `Y` of size (number of frequency bins) × (number of windows) for the output, and `X` of size (number of frequency bins) × (number of inputs) × (number of windows) for the inputs. +""" +function wcfft_mimo_windows(y::AbstractVector, u::AbstractMatrix; n = length(y) ÷ 10, noverlap = n ÷ 2, window = hamming) + n_samples, n_inputs = size(u) + n_samples == length(y) || throw(DimensionMismatch("Input and output lengths differ")) + win, norm2 = DSP.Periodograms.compute_window(window, n) + starts = 1:(n - noverlap):(n_samples - n + 1) + n_freqs = n ÷ 2 + 1 + Y = zeros(ComplexF64, n_freqs, length(starts)) + X = zeros(ComplexF64, n_freqs, n_inputs, length(starts)) + for (k, i) in enumerate(starts) + Y[:, k] .= rfft(y[i:i+n-1] .* win) + X[:, :, k] .= rfft(u[i:i+n-1, :] .* win, 1) + end + Y, X +end + function wcfft_mimo(y::AbstractVector, u::AbstractMatrix; n = length(y) ÷ 10, noverlap = n ÷ 2, window = hamming) n_samples, n_inputs = size(u) n_samples == length(y) || throw(DimensionMismatch("Input and output lengths differ")) diff --git a/test/test_frd.jl b/test/test_frd.jl index 6daf6a2a..aee5c3dc 100644 --- a/test/test_frd.jl +++ b/test/test_frd.jl @@ -254,3 +254,99 @@ littlefrd = FRD([1, 2], [im, 2*im]) @test_throws ArgumentError tfest([ds[1], iddata(ds[2].y, ds[2].u, 2)]; kw...) @test_throws ArgumentError tfest(ds[1:2]; n = 10^5) end + +@testset "Jackknife uncertainty of tfest and coherence" begin + @info "Testing jackknife uncertainty of tfest and coherence" + Random.seed!(0) + G = tf([1, 0.5], [1, -0.9, 0.5], 1) + nw = 256 + kw = (; n = nw, noverlap = nw ÷ 2, window = DSP.hanning) + function simulate_data(N, σn) + u = randn(1, N) + iddata(lsim(G, u)[1] .+ σn .* randn(1, N), u, 1) + end + d = simulate_data(4000, 0.5) + + # The estimates are unaffected by the uncertainty option + H0, N0 = tfest(d; method = :welch, kw...) + H, N, σH = tfest(d; method = :welch, uncertainty = Val(true), kw...) + @test H.r ≈ H0.r + @test N.r ≈ N0.r + @test σH.w == H.w + @test eltype(σH.r) <: Real + @test all(≥(0), σH.r) + κ0 = coherence(d; kw...) + κ, σκ = coherence(d; uncertainty = Val(true), kw...) + @test κ.r ≈ κ0.r + @test σκ.w == κ.w + @test all(≥(0), σκ.r) + @test tfest(d; method = :welch, uncertainty = Val(false), kw...) isa Tuple{FRD, FRD} + @test coherence(d; uncertainty = Val(false), kw...) isa FRD + + # Manual delete-one jackknife over the Welch windows + Pyy, Puu, Pyu = CSI.wcfft_windows([vec(d.y)], [vec(d.u)]; kw...) + Syy, Suu, Syu = CSI.wcfft(vec(d.y), vec(d.u); kw...) + @test vec(sum(Pyy, dims = 2)) ≈ Syy + @test vec(sum(Pyu, dims = 2)) ≈ Syu + K = size(Pyu, 2) + Hj = [(Syu .- Pyu[:, k]) ./ (Suu .- Puu[:, k]) for k in 1:K] + Hjm = mean(Hj) + @test σH.r ≈ sqrt.((K - 1) / K .* sum(h -> abs2.(h .- Hjm), Hj)) + + # The jackknife standard deviation agrees with the spread over independent realizations + Hs = Vector{ComplexF64}[] + σHs = Vector{Float64}[] + κs = Vector{Float64}[] + σκs = Vector{Float64}[] + for i in 1:100 + di = simulate_data(4000, 0.5) + Hi, _, σHi = tfest(di; method = :welch, uncertainty = Val(true), kw...) + κi, σκi = coherence(di; uncertainty = Val(true), kw...) + push!(Hs, Hi.r); push!(σHs, σHi.r); push!(κs, κi.r); push!(σκs, σκi.r) + end + inner = 2:length(H.w)-1 # the jackknife estimate of a real-valued periodogram is not representative at 0 and the Nyquist frequency + Hm = reduce(hcat, Hs) + σH_mc = vec(sqrt.(sum(abs2, Hm .- mean(Hm, dims = 2), dims = 2) ./ (size(Hm, 2) - 1))) + rH = mean(σHs)[inner] ./ σH_mc[inner] + @test 0.8 < median(rH) < 1.25 + @test all(r -> 0.6 < r < 1.6, rH) + σκ_mc = vec(std(reduce(hcat, κs), dims = 2)) + rκ = mean(σκs)[inner] ./ σκ_mc[inner] + @test 0.8 < median(rκ) < 1.25 + @test all(r -> 0.6 < r < 1.6, rκ) + + # The uncertainty decreases with the amount of data + _, _, σH_long = tfest(simulate_data(40000, 0.5); method = :welch, uncertainty = Val(true), kw...) + @test median(σH_long.r[inner] ./ σH.r[inner]) < 0.5 + + # Multiple outputs + dm = iddata([vec(d.y) vec(d.y)]', d.u, 1) + Hm2, Nm2, σHm2 = tfest(dm; method = :welch, uncertainty = Val(true), kw...) + @test size(σHm2.r) == (2, 1, length(H.w)) + @test σHm2.r[2, 1, :] ≈ σH.r + @test Hm2.r[1, 1, :] ≈ H.r + + # Multiple data segments + d2 = simulate_data(3000, 0.5) + Hv, Nv, σHv = tfest([d, d2]; uncertainty = Val(true), kw...) + @test Hv.r ≈ tfest([d, d2]; kw...)[1].r + _, σH1 = tfest([d]; uncertainty = Val(true), kw...)[[1, 3]] + @test σH1.r ≈ σH.r + κv, σκv = coherence([d, d2]; uncertainty = Val(true), kw...) + @test κv.r ≈ coherence([d, d2]; kw...).r + @test coherence([d]; uncertainty = Val(true), kw...)[2].r ≈ σκ.r + + # Multiple inputs + u2 = randn(2, 4000) + y2 = lsim(ss(G), u2[1:1, :])[1] .+ 0.5 .* lsim(ss(G), u2[2:2, :])[1] .+ randn(1, 4000) + dmi = iddata(y2, u2, 1) + κmi, σκmi = coherence(dmi; uncertainty = Val(true), n = nw) + @test κmi.r ≈ coherence(dmi; n = nw).r + @test all(≥(0), σκmi.r) + @test 0 < median(σκmi.r) < 0.2 + + # Errors + @test_throws ArgumentError tfest(d; uncertainty = Val(true)) # default method = :corr + @test_throws ArgumentError coherence(d; method = :corr, uncertainty = Val(true)) + @test_throws ArgumentError tfest(d; method = :welch, uncertainty = Val(true), n = 4000) # a single window +end From 5ad8f8730a0d67fdd38f75413963d2837f775830 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 2 Dec 2026 14:25:09 +0000 Subject: [PATCH 2/6] Address review findings on jackknife uncertainty MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Form delete-one sums from prefix and suffix sums instead of subtracting each window from the total, which avoids cancellation when one window dominates. - Require at least three windows for the coherence uncertainty, and m + 2 windows for the multiple coherence with m inputs; with fewer, every delete-one coherence equals one. - Compute the multiple coherence from transforms along the time axis in both paths, and support window = nothing for multiple inputs. - Form per-window periodogram products in the precision of the transforms, as in wcfft. - Draw a ±2σ band in coherenceplot when uncertainty = Val(true) is passed. - Document the interpretation of σG and the behavior of the coherence uncertainty near zero coherence. Co-Authored-By: Claude Opus 5.5 --- docs/src/freq.md | 6 +- src/frd.jl | 154 +++++++++++++++++++---------------------------- src/plotting.jl | 6 +- test/test_frd.jl | 22 +++++++ 4 files changed, 93 insertions(+), 95 deletions(-) diff --git a/docs/src/freq.md b/docs/src/freq.md index 3dda399e..61d45e83 100644 --- a/docs/src/freq.md +++ b/docs/src/freq.md @@ -56,12 +56,14 @@ G, N, σG = tfest(dn; method = :welch, n = 1000, uncertainty = Val(true)) k, σk = coherence(dn; n = 1000, uncertainty = Val(true)) inds = 2:length(G.w) # exclude the zero frequency from the logarithmic axis mag = abs.(G.r[inds]) -plot(G.w[inds], mag, ribbon = (min.(2σG.r[inds], 0.99mag), 2σG.r[inds]), xscale = :log10, yscale = :log10, lab = "|G| ± 2σ", layout = 2) +plot(G.w[inds], mag, ribbon = (min.(2σG.r[inds], 0.99mag), 2σG.r[inds]), xscale = :log10, yscale = :log10, lab = "|G| ± 2σ_G", layout = 2) plot!(G.w[inds], abs.(vec(freqresp(c2d(sys, h), G.w[inds]))), sp = 1, lab = "True system", l = (:black, :dash)) plot!(k.w[inds], k.r[inds], ribbon = 2σk.r[inds], xscale = :log10, yscale = :identity, ylims = (0, 1), sp = 2, lab = "κ² ± 2σ") DisplayAs.PNG(current()) # hide ``` -The jackknife estimate treats the windows as independent. Overlapping windows are correlated, the estimate is therefore approximate. It does not account for bias, such as the bias caused by spectral leakage at sharp resonances. +Here, `σG` is the standard deviation of the complex-valued estimate, ``\sqrt{\operatorname{Var}(\operatorname{Re} G) + \operatorname{Var}(\operatorname{Im} G)}``, which is an upper bound on the standard deviation of the magnitude ``|G|`` to first order. The band in the left figure thus indicates the total error of the estimate, including the phase error. A band around the coherence is also drawn by `coherenceplot(dn, (; n = 1000, uncertainty = Val(true)))`. + +The jackknife estimate treats the windows as independent. Overlapping windows are correlated, the estimate is therefore approximate. It does not account for bias, such as the bias caused by spectral leakage at sharp resonances. For the coherence, the jackknife estimate is also inaccurate at frequencies where the true coherence is close to zero, where it overestimates the variance (by approximately a factor of two for vanishing coherence). The coherence uncertainty requires at least three windows, and at least `m + 2` windows for `m` inputs. See the [example notebooks](https://github.com/JuliaControl/ControlExamples.jl?files=1) for more details. diff --git a/src/frd.jl b/src/frd.jl index 872a90da..86f33410 100644 --- a/src/frd.jl +++ b/src/frd.jl @@ -280,10 +280,27 @@ Form `H` and `N` from the per-window periodograms `Pyy, Puu, Pyu` (frequency × function spectra2tfest_jackknife(Pyy, Puu, Pyu, h, L) Syy, Suu, Syu = vec(sum(Pyy, dims = 2)), vec(sum(Puu, dims = 2)), vec(sum(Pyu, dims = 2)) H, N = spectra2tfest(Syy, Suu, Syu, h, L) - σH = jackknife_std((Syu .- Pyu) ./ (Suu .- Puu)) + σH = jackknife_std(leave_one_out(Pyu) ./ leave_one_out(Puu)) return H, N, FRD(H.w, σH) end +""" + R = leave_one_out(P::AbstractMatrix) + +Sums over all columns of `P` except one, `R[:, k] = Σ_{j ≠ k} P[:, j]`. The sums are formed from prefix and suffix sums rather than by subtracting `P[:, k]` from the total, which avoids cancellation when a single column dominates the total. +""" +function leave_one_out(P::AbstractMatrix) + K = size(P, 2) + pre = cumsum(P, dims = 2) + suf = reverse(cumsum(reverse(P, dims = 2), dims = 2), dims = 2) + R = zero(P) + for k in 1:K + k > 1 && (R[:, k] .+= @view(pre[:, k-1])) + k < K && (R[:, k] .+= @view(suf[:, k+1])) + end + R +end + """ σ = jackknife_std(θ::AbstractMatrix) @@ -291,11 +308,18 @@ Delete-one jackknife estimate of the standard deviation of an estimator, given t """ function jackknife_std(θ::AbstractMatrix) K = size(θ, 2) - K >= 2 || throw(ArgumentError("The jackknife uncertainty estimate requires at least two Welch windows, but only $K window is available. Decrease the window length `n`.")) + check_window_count(K, 2) θ̄ = mean(θ, dims = 2) sqrt.((K - 1) / K .* vec(sum(abs2, θ .- θ̄, dims = 2))) end +""" + check_window_count(K, Kmin) + +Throw an `ArgumentError` if the number of Welch windows `K` is smaller than the number `Kmin` required by the jackknife uncertainty estimate. +""" +check_window_count(K, Kmin) = K >= Kmin || throw(ArgumentError("The jackknife uncertainty estimate requires at least $Kmin Welch windows, but only $K are available. Decrease the window length `n`.")) + check_uncertainty_method(method) = method === :welch || throw(ArgumentError("The uncertainty estimate is only available for method = :welch, got method = $(repr(method))")) """ @@ -405,8 +429,10 @@ end function spectra2coherence_jackknife(Pyy, Puu, Pyu, h) Syy, Suu, Syu = vec(sum(Pyy, dims = 2)), vec(sum(Puu, dims = 2)), vec(sum(Pyu, dims = 2)) + # With a single retained window, every delete-one coherence equals one + check_window_count(size(Pyu, 2), 3) κ = spectra2coherence(Syy, Suu, Syu, h) - σκ = jackknife_std(@. abs2(Syu - Pyu) / ((Suu - Puu) * (Syy - Pyy))) + σκ = jackknife_std(@. abs2($leave_one_out(Pyu)) / ($leave_one_out(Puu) * $leave_one_out(Pyy))) return κ, FRD(κ.w, σκ) end @@ -442,15 +468,16 @@ end 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). """ function wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n = minimum(length, ys) ÷ 10, noverlap = n ÷ 2, window = hamming) - Xy = Vector{Vector{ComplexF64}}() - Xu = Vector{Vector{ComplexF64}}() + Pyy = Vector{Vector{Float64}}() + Puu = Vector{Vector{Float64}}() + Pyu = Vector{Vector{ComplexF64}}() foreach_window(ys, us; n, noverlap, window) do xy, xu - push!(Xy, xy) - push!(Xu, xu) + # The products are formed in the precision of the transforms, as in wcfft + push!(Pyy, abs2.(xy)) + push!(Puu, abs2.(xu)) + push!(Pyu, xy .* conj.(xu)) end - Y = reduce(hcat, Xy) - X = reduce(hcat, Xu) - abs2.(Y), abs2.(X), Y .* conj.(X) + reduce(hcat, Pyy), reduce(hcat, Puu), reduce(hcat, Pyu) end """ @@ -485,116 +512,61 @@ function multiple_coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n u = time1(input(d)) h = sampletime(d) - U && return multiple_coherence_jackknife(y, u, h; n, noverlap, window) - - Syy, Suu, Syu = wcfft_mimo(y, u, n = n, noverlap = noverlap, window = window) - - n_freqs = length(Syy) - γ2 = zeros(n_freqs) - - for i in 1:n_freqs - γ2[i] = multiple_coherence_value(Syy[i], Suu[i], Syu[i]) - end - - Sch = FRD(freqvec(h, γ2), γ2) - return Sch -end - -function multiple_coherence_value(Syy, Suu, Syu) - s_xy = conj(Syu) - num = real(dot(s_xy, Suu \ s_xy)) - clamp(num / Syy, 0.0, 1.0) -end - -function multiple_coherence_jackknife(y, u, h; n, noverlap, window) Y, X = wcfft_mimo_windows(y, u; n, noverlap, window) n_freqs, K = size(Y) + n_inputs = size(X, 2) + # With fewer retained windows than inputs + 1, every delete-one multiple coherence equals one + U && check_window_count(K, n_inputs + 2) γ2 = zeros(n_freqs) - γ2j = zeros(n_freqs, K) + γ2j = zeros(n_freqs, U ? K : 0) for f in 1:n_freqs Xf = X[f, :, :] # n_inputs × K Yf = Y[f, :] - Syy = sum(abs2, Yf) - Suu = Xf * Xf' - Syu = conj.(Xf) * Yf - γ2[f] = multiple_coherence_value(Syy, Suu, Syu) + γ2[f] = multiple_coherence_value(Xf, Yf) + U || continue for k in 1:K - xk = Xf[:, k] - γ2j[f, k] = multiple_coherence_value(Syy - abs2(Yf[k]), Suu - xk * xk', Syu - Yf[k] .* conj.(xk)) + keep = [1:k-1; k+1:K] + γ2j[f, k] = multiple_coherence_value(Xf[:, keep], Yf[keep]) end end w = freqvec(h, γ2) - FRD(w, γ2), FRD(w, jackknife_std(γ2j)) + U ? (FRD(w, γ2), FRD(w, jackknife_std(γ2j))) : FRD(w, γ2) +end + +""" + γ² = multiple_coherence_value(X, Y) + +Multiple coherence at one frequency, given the transforms `X` (inputs × windows) and `Y` (windows) of the Welch windows. +""" +function multiple_coherence_value(X, Y) + Syy = sum(abs2, Y) + Suu = X * X' + s_xy = X * conj.(Y) + num = real(dot(s_xy, Suu \ s_xy)) + clamp(num / Syy, 0.0, 1.0) end """ Y, X = wcfft_mimo_windows(y, u; n, noverlap, window) -Discrete Fourier transforms of the windows used in [`wcfft_mimo`](@ref): `Y` of size (number of frequency bins) × (number of windows) for the output, and `X` of size (number of frequency bins) × (number of inputs) × (number of windows) for the inputs. +Discrete Fourier transforms (non-negative frequencies) of the Welch windows of the output `y` and the inputs `u` (time × inputs), taken along the time axis: `Y` of size (number of frequency bins) × (number of windows) and `X` of size (number of frequency bins) × (number of inputs) × (number of windows). """ function wcfft_mimo_windows(y::AbstractVector, u::AbstractMatrix; n = length(y) ÷ 10, noverlap = n ÷ 2, window = hamming) n_samples, n_inputs = size(u) n_samples == length(y) || throw(DimensionMismatch("Input and output lengths differ")) win, norm2 = DSP.Periodograms.compute_window(window, n) + applywin(x) = win === nothing ? x : x .* win starts = 1:(n - noverlap):(n_samples - n + 1) n_freqs = n ÷ 2 + 1 Y = zeros(ComplexF64, n_freqs, length(starts)) X = zeros(ComplexF64, n_freqs, n_inputs, length(starts)) for (k, i) in enumerate(starts) - Y[:, k] .= rfft(y[i:i+n-1] .* win) - X[:, :, k] .= rfft(u[i:i+n-1, :] .* win, 1) + Y[:, k] .= rfft(applywin(y[i:i+n-1])) + X[:, :, k] .= rfft(applywin(u[i:i+n-1, :]), 1) end Y, X end -function wcfft_mimo(y::AbstractVector, u::AbstractMatrix; n = length(y) ÷ 10, noverlap = n ÷ 2, window = hamming) - n_samples, n_inputs = size(u) - n_samples == length(y) || throw(DimensionMismatch("Input and output lengths differ")) - - win, norm2 = DSP.Periodograms.compute_window(window, n) - - # Dimensions for FFT - n_freqs = n ÷ 2 + 1 - - # Initialize Accumulators - Syy = zeros(Float64, n_freqs) - Suu = [zeros(ComplexF64, n_inputs, n_inputs) for _ in 1:n_freqs] - Syu = [zeros(ComplexF64, n_inputs) for _ in 1:n_freqs] # Vector of vectors - - # Calculate window stride - step = n - noverlap - - # Segment Loop (Manual splitting to handle Matrix u safely) - for i in 1:step:(n_samples - n + 1) - # Extract segments and apply window - y_seg = y[i:i+n-1] .* win - u_seg = u[i:i+n-1, :] .* win # Broadcast window across columns - - # Compute FFTs - Y_f = rfft(y_seg) - U_f = rfft(u_seg) # FFT along time dimension (dim 1) - - # Accumulate Spectra per frequency bin - for k in 1:n_freqs - Y_k = Y_f[k] # Scalar - U_k = U_f[k, :] # Vector (1 x Inputs) - - # Auto-spectrum Output (Scalar) - Syy[k] += abs2(Y_k) - - # Auto-spectral Matrix Input (Matrix: Inputs x Inputs) - # Outer product: U * U' - Suu[k] .+= U_k * U_k' - - # Cross-spectral Vector (Vector: Inputs) - # We compute S_yx = Y * U' (Output * conj(Input)) - Syu[k] .+= Y_k .* conj.(U_k) - end - end - - return Syy, Suu, Syu -end - """ diff --git a/src/plotting.jl b/src/plotting.jl index 841738e4..7cafca4c 100644 --- a/src/plotting.jl +++ b/src/plotting.jl @@ -259,7 +259,7 @@ Calculates and plots the (squared) coherence Function κ. κ close to 1 indicate `hz` indicates Hertz instead of rad/s -Keyword arguments to `coherence` are supplied as a named tuple as a second positional argument . +Keyword arguments to `coherence` are supplied as a named tuple as a second positional argument. If the named tuple contains `uncertainty = Val(true)`, a band of ± two jackknife standard deviations is drawn around the coherence. """ coherenceplot @@ -281,11 +281,13 @@ coherenceplot title --> "Coherence" label --> false for i = 1:d.ny - frd = coherence(d[i,:]; kwargs...) + res = coherence(d[i,:]; kwargs...) + frd, σ = res isa Tuple ? res : (res, nothing) @series begin inds = findall(x -> x == 0, frd.w) useinds = setdiff(1:length(frd.w), inds) label --> (d.ny == 1 ? "" : "To y_$i") + σ === nothing || (ribbon --> 2 .* σ.r[useinds]) (hz ? 1 / (2π) : 1) .* frd.w[useinds], abs.(frd.r[useinds]) end end diff --git a/test/test_frd.jl b/test/test_frd.jl index aee5c3dc..f3058522 100644 --- a/test/test_frd.jl +++ b/test/test_frd.jl @@ -345,7 +345,29 @@ end @test all(≥(0), σκmi.r) @test 0 < median(σκmi.r) < 0.2 + # A dominant window does not cause cancellation in the delete-one sums + ud = [1e9, 0, 1, 0, 1, 0] + yd = [1e9, 0, 1, 0, 3, 0] + dd = iddata(yd, ud, 1) + Hd, _, σHd = tfest(dd; method = :welch, uncertainty = Val(true), n = 2, noverlap = 0, window = nothing) + Hdj = [2.0, 1.0, 1.0] # transfer estimates with window 1, 2 and 3 deleted, at zero frequency + @test σHd.r[1] ≈ sqrt(2 / 3 * sum(abs2, Hdj .- mean(Hdj))) + @test all(isfinite, coherence(dd; uncertainty = Val(true), n = 2, noverlap = 0, window = nothing)[2].r) + + # Float32 data give the same estimates with and without the uncertainty option + d32 = iddata(Float32.(d.y), Float32.(d.u), 1) + @test tfest(d32; method = :welch, uncertainty = Val(true), kw...)[2].r ≈ tfest(d32; method = :welch, kw...)[2].r + + # Plotting with uncertainty + @test_nowarn coherenceplot(d, (; kw..., uncertainty = Val(true))) + + # Multiple inputs with a rectangular window + @test coherence(dmi; n = nw, window = nothing, uncertainty = Val(true))[1].r ≈ coherence(dmi; n = nw, window = nothing).r + # Errors + @test_throws ArgumentError coherence(d; uncertainty = Val(true), n = 2000, noverlap = 0) # two windows + @test coherence(dmi; uncertainty = Val(true), n = 1000, noverlap = 0) isa Tuple # two inputs: four windows suffice, three do not + @test_throws ArgumentError coherence(dmi; uncertainty = Val(true), n = 1300, noverlap = 0) @test_throws ArgumentError tfest(d; uncertainty = Val(true)) # default method = :corr @test_throws ArgumentError coherence(d; method = :corr, uncertainty = Val(true)) @test_throws ArgumentError tfest(d; method = :welch, uncertainty = Val(true), n = 4000) # a single window From 0c8bc8b080503b1105fb911cb2f7572e5eb5c115 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 2 Dec 2026 15:02:05 +0000 Subject: [PATCH 3/6] 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 --- src/frd.jl | 79 +++++++++++++++++++++++++++++++----------------- test/test_frd.jl | 52 ++++++++++++++++++++++++++++++- 2 files changed, 102 insertions(+), 29 deletions(-) diff --git a/src/frd.jl b/src/frd.jl index 86f33410..f406ee9b 100644 --- a/src/frd.jl +++ b/src/frd.jl @@ -206,7 +206,7 @@ Both `H` and `N` are of type `FRD` (frequency-response data). - `σ` determines the width of the Gaussian window applied to the estimated correlation functions before FFT. A larger `σ` implies less smoothing. - `H` = Syu/Suu Process transfer function -- `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` = 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. - `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. - `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. @@ -218,6 +218,7 @@ This estimation method is unbiased if the input ``u`` is uncorrelated with the n 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. """ 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 + check_time_domain(d) d.nu == 1 || error("Cannot perform tfest on multiple-input data. Consider using time-domain estimation or statespace estimation.") U && check_uncertainty_method(method) if d.ny > 1 @@ -225,14 +226,15 @@ function tfest(d::AbstractIdData, σ::Real = 0.05; method = :corr, n = length(d) end y, u, h = vec(output(d)), vec(input(d)), sampletime(d) if U - return spectra2tfest_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h, length(y)) + return spectra2tfest_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h) end if method === :welch - Syy, Suu, Syu = wcfft(y, u, n = n, noverlap = noverlap, window = window) + Syy, Suu, Syu, L = wcfft(y, u, n = n, noverlap = noverlap, window = window) elseif method === :corr Syy, Suu, Syu = fft_corr(y, u, σ) + L = length(y) else error("Unknown method $method") end - return spectra2tfest(Syy, Suu, Syu, h, length(y)) + return spectra2tfest(Syy, Suu, Syu, h, L) end """ @@ -243,7 +245,7 @@ Estimate a transfer function using the Welch method, pooled over several data se 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)`. -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. +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. 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)`. @@ -257,27 +259,31 @@ function tfest(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = minimu end ys = [vec(output(d)) for d in ds] us = [vec(input(d)) for d in ds] - L = sum(length(y) for y in ys if length(y) >= n; init = 0) if U - return spectra2tfest_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h, L) + return spectra2tfest_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h) end - Syy, Suu, Syu = wcfft(ys, us; n, noverlap, window) + Syy, Suu, Syu, L = wcfft(ys, us; n, noverlap, window) return spectra2tfest(Syy, Suu, Syu, h, L) end +""" + H, N = spectra2tfest(Syy, Suu, Syu, h, L) + +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. +""" function spectra2tfest(Syy, Suu, Syu, h, L) w = freqvec(h, Syu) H = FRD(w, Syu ./ Suu) - N = FRD(w, real.(Syy .- abs2.(Syu) ./ Suu) ./ L) + N = FRD(w, max.(real.(Syy .- abs2.(Syu) ./ Suu), 0) ./ L) return H, N end """ - H, N, σH = spectra2tfest_jackknife(Pyy, Puu, Pyu, h, L) + H, N, σH = spectra2tfest_jackknife(Pyy, Puu, Pyu, L, h) -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`. +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`. """ -function spectra2tfest_jackknife(Pyy, Puu, Pyu, h, L) +function spectra2tfest_jackknife(Pyy, Puu, Pyu, L, h) Syy, Suu, Syu = vec(sum(Pyy, dims = 2)), vec(sum(Puu, dims = 2)), vec(sum(Pyu, dims = 2)) H, N = spectra2tfest(Syy, Suu, Syu, h, L) σH = jackknife_std(leave_one_out(Pyu) ./ leave_one_out(Puu)) @@ -333,13 +339,22 @@ function stack_outputs(HNs, ::Val{M}) where M ntuple(j -> FRD(w, reshape(reduce(vcat, [transpose(hn[j].r) for hn in HNs]), ny, 1, :)), Val(M)) end +""" + check_time_domain(d) + +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. +""" +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`.")) +check_time_domain(d::AbstractIdData) = nothing + """ h, ny = check_segments(ds) -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. +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. """ function check_segments(ds::AbstractVector{<:AbstractIdData}) isempty(ds) && throw(ArgumentError("At least one data segment is required")) + foreach(check_time_domain, ds) allequal(sampletime(d) for d in ds) || throw(ArgumentError("All data segments must have the same sample time")) allequal(noutputs(d) for d in ds) || throw(ArgumentError("All data segments must have the same number of outputs")) 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 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``. """ function coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, method=:welch, σ = 0.05, uncertainty::Val{U} = Val(false)) where U + check_time_domain(d) noutputs(d) == 1 || throw(ArgumentError("coherence only supports a single output. Index the data object like `d[i,:]` to obtain the `i`:th output.")) U && check_uncertainty_method(method) if ninputs(d) > 1 @@ -423,24 +439,31 @@ function coherence(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = mi end function spectra2coherence(Syy, Suu, Syu, h) - k = @. abs2(Syu) / (Suu * Syy) + k = coherence_value.(Syy, Suu, Syu) FRD(freqvec(h, k), k) end -function spectra2coherence_jackknife(Pyy, Puu, Pyu, h) +""" + κ² = coherence_value(Syy, Suu, Syu) + +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. +""" +coherence_value(Syy, Suu, Syu) = clamp(abs2(Syu) / (Suu * Syy), 0, 1) + +function spectra2coherence_jackknife(Pyy, Puu, Pyu, L, h) Syy, Suu, Syu = vec(sum(Pyy, dims = 2)), vec(sum(Puu, dims = 2)), vec(sum(Pyu, dims = 2)) # With a single retained window, every delete-one coherence equals one check_window_count(size(Pyu, 2), 3) κ = spectra2coherence(Syy, Suu, Syu, h) - σκ = jackknife_std(@. abs2($leave_one_out(Pyu)) / ($leave_one_out(Puu) * $leave_one_out(Pyy))) + σκ = jackknife_std(coherence_value.(leave_one_out(Pyy), leave_one_out(Puu), leave_one_out(Pyu))) return κ, FRD(κ.w, σκ) end """ - Syy, Suu, Syu = wcfft(y, u; n = length(y) ÷ 10, noverlap = n ÷ 2, window = hamming) - Syy, Suu, Syu = wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window) + Syy, Suu, Syu, L = wcfft(y, u; n = length(y) ÷ 10, noverlap = n ÷ 2, window = hamming) + Syy, Suu, Syu, L = wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window) -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. +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. 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. @@ -454,36 +477,36 @@ function wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:Abstra Syy = zeros(nf) Suu = zeros(nf) Syu = zeros(ComplexF64, nf) - foreach_window(ys, us; n, noverlap, window) do xy, xu + L = foreach_window(ys, us; n, noverlap, window) do xy, xu @. Syu += xy * conj(xu) @. Syy += abs2(xy) @. Suu += abs2(xu) end - Syy, Suu, Syu + Syy, Suu, Syu, L end """ - Pyy, Puu, Pyu = wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window) + Pyy, Puu, Pyu, L = wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window) -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). +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). """ function wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n = minimum(length, ys) ÷ 10, noverlap = n ÷ 2, window = hamming) Pyy = Vector{Vector{Float64}}() Puu = Vector{Vector{Float64}}() Pyu = Vector{Vector{ComplexF64}}() - foreach_window(ys, us; n, noverlap, window) do xy, xu + L = foreach_window(ys, us; n, noverlap, window) do xy, xu # The products are formed in the precision of the transforms, as in wcfft push!(Pyy, abs2.(xy)) push!(Puu, abs2.(xu)) push!(Pyu, xy .* conj.(xu)) end - reduce(hcat, Pyy), reduce(hcat, Puu), reduce(hcat, Pyu) + reduce(hcat, Pyy), reduce(hcat, Puu), reduce(hcat, Pyu), L end """ - foreach_window(f, ys, us; n, noverlap, window) + L = foreach_window(f, ys, us; n, noverlap, window) -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. +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. """ function foreach_window(f, ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window) 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 nwin += length(uw) end nwin > 0 || throw(ArgumentError("No data segment is at least as long as the window length n = $n")) - nothing + nwin * norm2 end function multiple_coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, σ = 0.05, uncertainty::Val{U} = Val(false)) where U diff --git a/test/test_frd.jl b/test/test_frd.jl index f3058522..228eeb92 100644 --- a/test/test_frd.jl +++ b/test/test_frd.jl @@ -225,7 +225,9 @@ littlefrd = FRD([1, 2], [im, 2*im]) @test Ryu ≈ Syu H, N = tfest(ds; kw...) @test H.r ≈ Syu ./ Suu - @test N.r ≈ (Syy .- abs2.(Syu) ./ Suu) ./ sum(lengths[1:end-1]) + win = DSP.hanning(nw) + nwin = sum(length(1:nw÷2:N-nw+1) for N in lengths[1:end-1]) + @test N.r ≈ (Syy .- abs2.(Syu) ./ Suu) ./ (nwin * sum(abs2, win)) @test coherence(ds; kw...).r ≈ abs2.(Syu) ./ (Suu .* Syy) # A known transfer function is recovered from several noisy segments @@ -372,3 +374,51 @@ end @test_throws ArgumentError coherence(d; method = :corr, uncertainty = Val(true)) @test_throws ArgumentError tfest(d; method = :welch, uncertainty = Val(true), n = 4000) # a single window end + +@testset "Normalization and range of Welch spectral estimates" begin + @info "Testing normalization and range of Welch spectral estimates" + Random.seed!(0) + G = tf([1, 0.5], [1, -0.9, 0.5], 1) + σn = 0.3 + T = 20000 + u = randn(1, T) + d = iddata(lsim(G, u)[1] .+ σn .* randn(1, T), u, 1) + + # White noise of variance σn² gives a noise spectrum close to σn² for every window function + inner(N) = N.r[2:end-1] + dv = iddata(σn .* randn(1, T), u, 1) + for kw in ((; n = 256), (; n = 256, window = nothing), (; n = 256, noverlap = 0, window = DSP.hanning)) + _, N = tfest(dv; method = :welch, kw...) + @test mean(inner(N)) ≈ σn^2 rtol = 0.05 + _, Nv = tfest([dv[1:10000], dv[10001:end]]; kw...) + @test mean(inner(Nv)) ≈ σn^2 rtol = 0.05 + end + # The same holds with a dynamic system if the window function suppresses leakage + _, N = tfest(d; method = :welch, n = 256) + @test mean(inner(N)) ≈ σn^2 rtol = 0.1 + # The correlogram method has the same units, its estimate is biased low by the smoothing of the lag window + _, Nc = tfest(d; method = :corr) + @test mean(inner(Nc)) ≈ σn^2 rtol = 0.25 + + # Samples outside every window do not affect the noise spectrum + nw = 256 + kw = (; n = nw, noverlap = 0, window = nothing) + dsl = [d[1:2nw-1], d[2nw+1:4nw-1]] # each segment contains one window and nw - 1 unused samples + @test tfest([d[1:nw], d[2nw+1:3nw]]; kw...)[2].r ≈ tfest(dsl; kw...)[2].r + + # A single window gives a non-negative noise spectrum and a coherence in [0, 1] + _, N1 = tfest(d[1:nw]; method = :welch, n = nw) + @test all(≥(0), N1.r) + @test_nowarn sqrt(N1) + κ1 = coherence(d[1:nw]; n = nw) + @test all(k -> 0 ≤ k ≤ 1, κ1.r) + @test all(k -> 0 ≤ k ≤ 1, coherence(d; method = :corr).r) + + # Frequency-domain data are rejected + df = iddata(randn(1, 100), randn(1, 100), range(0, π, length = 100)) + @test_throws ArgumentError tfest(df; method = :welch, n = 20) + @test_throws ArgumentError tfest(df) + @test_throws ArgumentError coherence(df; n = 20) + @test_throws ArgumentError tfest([df]; n = 20) + @test_throws ArgumentError coherence([df]; n = 20) +end From 1e1e5a19da34cc9b281016a5ad439ffb2ef460af Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 2 Dec 2026 18:45:11 +0000 Subject: [PATCH 4/6] Analytic uncertainty estimates for tfest and coherence Add uncertainty = Val(:analytic) next to Val(:jackknife) (Val(true) is equivalent to Val(:jackknife)). - The standard deviation of the transfer-function estimate is computed from its conditional distribution given the input under Gaussian noise, including the correlation between overlapping Welch windows, with the noise power estimated without bias from the residual. - The standard deviation of the squared (multiple) coherence is computed from the distribution of Goodman (1963) for jointly Gaussian input and noise, as a negative binomial mixture of beta distributions, with the equivalent number of windows of Welch (1967) for overlapping windows. - The analytic estimate is available for method = :corr, using the equivalent number of independent windows of the lag window, for multiple data segments, and for multiple inputs. - foreach_window passes the start of each window on a common time axis. - Documentation section comparing the analytic and jackknife estimates with Monte Carlo simulations. Co-Authored-By: Claude Opus 5.5 --- docs/src/freq.md | 52 +++++++- src/frd.jl | 302 +++++++++++++++++++++++++++++++++++++++++------ test/test_frd.jl | 85 ++++++++++++- 3 files changed, 399 insertions(+), 40 deletions(-) diff --git a/docs/src/freq.md b/docs/src/freq.md index 61d45e83..7efe80ec 100644 --- a/docs/src/freq.md +++ b/docs/src/freq.md @@ -50,10 +50,12 @@ nothing # hide ``` ### Uncertainty estimates -With the Welch method, [`tfest`](@ref) and [`coherence`](@ref) optionally return an estimate of the standard deviation of the estimates at each frequency. The standard deviation is estimated with a delete-one jackknife over the Welch windows, and is requested with the keyword argument `uncertainty = Val(true)`: +[`tfest`](@ref) and [`coherence`](@ref) optionally return an estimate of the standard deviation of the estimates at each frequency, requested with the keyword argument `uncertainty`. Two estimates are available: +- `uncertainty = Val(:analytic)` computes the standard deviation from the distribution of the estimates under the assumption that the input and the noise are Gaussian processes. The transfer-function estimate is linear in the noise, and is therefore complex Gaussian conditional on the input, with a variance that is computed from the input spectrum and the residual noise power. The correlation between overlapping Welch windows is taken into account. The squared coherence follows the distribution of Goodman (1963). This estimate is available for both `method = :welch` and `method = :corr`. +- `uncertainty = Val(:jackknife)` (or `Val(true)`) computes a delete-one jackknife estimate over the Welch windows, i.e., the spread of the estimates obtained when one window at a time is left out. It does not rely on the Gaussian assumption, but treats the windows as independent, and is only available for `method = :welch`. ```@example npfreq -G, N, σG = tfest(dn; method = :welch, n = 1000, uncertainty = Val(true)) -k, σk = coherence(dn; n = 1000, uncertainty = Val(true)) +G, N, σG = tfest(dn; method = :welch, n = 1000, uncertainty = Val(:analytic)) +k, σk = coherence(dn; n = 1000, uncertainty = Val(:analytic)) inds = 2:length(G.w) # exclude the zero frequency from the logarithmic axis mag = abs.(G.r[inds]) plot(G.w[inds], mag, ribbon = (min.(2σG.r[inds], 0.99mag), 2σG.r[inds]), xscale = :log10, yscale = :log10, lab = "|G| ± 2σ_G", layout = 2) @@ -61,9 +63,49 @@ plot!(G.w[inds], abs.(vec(freqresp(c2d(sys, h), G.w[inds]))), sp = 1, lab = "Tru plot!(k.w[inds], k.r[inds], ribbon = 2σk.r[inds], xscale = :log10, yscale = :identity, ylims = (0, 1), sp = 2, lab = "κ² ± 2σ") DisplayAs.PNG(current()) # hide ``` -Here, `σG` is the standard deviation of the complex-valued estimate, ``\sqrt{\operatorname{Var}(\operatorname{Re} G) + \operatorname{Var}(\operatorname{Im} G)}``, which is an upper bound on the standard deviation of the magnitude ``|G|`` to first order. The band in the left figure thus indicates the total error of the estimate, including the phase error. A band around the coherence is also drawn by `coherenceplot(dn, (; n = 1000, uncertainty = Val(true)))`. +Here, `σG` is the standard deviation of the complex-valued estimate, ``\sqrt{\operatorname{Var}(\operatorname{Re} G) + \operatorname{Var}(\operatorname{Im} G)}``, which is an upper bound on the standard deviation of the magnitude ``|G|`` to first order. The band in the left figure thus indicates the total error of the estimate, including the phase error. A band around the coherence is also drawn by `coherenceplot(dn, (; n = 1000, uncertainty = Val(:analytic)))`. -The jackknife estimate treats the windows as independent. Overlapping windows are correlated, the estimate is therefore approximate. It does not account for bias, such as the bias caused by spectral leakage at sharp resonances. For the coherence, the jackknife estimate is also inaccurate at frequencies where the true coherence is close to zero, where it overestimates the variance (by approximately a factor of two for vanishing coherence). The coherence uncertainty requires at least three windows, and at least `m + 2` windows for `m` inputs. +#### Comparison of the analytic and jackknife estimates +To compare the two estimates with the actual variability of the estimates, we repeat the experiment 200 times with new realizations of the input and the noise, and compute the standard deviation of the estimates over the realizations. A shorter experiment with a window length of 2000 samples is used, which gives only 19 windows, such that the difference between the two estimates is visible. The figure shows the ratio between the uncertainty estimates and the Monte Carlo standard deviation. A ratio of one indicates a correct estimate. Each uncertainty estimate is computed from a single experiment. The lines show the median ratio over the realizations, and the bands the 10% and 90% quantiles, i.e., how much the uncertainty estimate obtained from a single experiment varies. +```@example npfreq +using Statistics +Tc = 20000 +function experiment() + u = randn(1, Tc) + y = lsim(sys, u, 1:Tc)[1] .+ lsim(sysn, randn(1, Tc), 1:Tc)[1] + iddata(y, u, h) +end +kw = (; method = :welch, n = 2000) +res = map(1:200) do _ + di = experiment() + G, _, σa = tfest(di; kw..., uncertainty = Val(:analytic)) + _, _, σj = tfest(di; kw..., uncertainty = Val(:jackknife)) + k, σka = coherence(di; kw..., uncertainty = Val(:analytic)) + _, σkj = coherence(di; kw..., uncertainty = Val(:jackknife)) + (; G = G.r, k = k.r, σa = σa.r, σj = σj.r, σka = σka.r, σkj = σkj.r) +end +w = tfest(experiment(); kw...)[1].w +inds = 2:length(w) +Gs = reduce(hcat, [r.G for r in res]) +σG_mc = vec(sqrt.(mean(abs2, Gs .- mean(Gs, dims = 2), dims = 2))) +σk_mc = vec(std(reduce(hcat, [r.k for r in res]), dims = 2)) +function band!(sp, field, σ_mc, lab, color) + M = reduce(hcat, [getfield(r, field) for r in res])[inds, :] ./ σ_mc[inds] + q10, q50, q90 = (mapslices(x -> quantile(x, q), M, dims = 2)[:] for q in (0.1, 0.5, 0.9)) + plot!(w[inds], q50, ribbon = (q50 .- q10, q90 .- q50), sp = sp, lab = lab, c = color, fillalpha = 0.3) +end +plot(layout = (1, 2), size = (800, 350), xscale = :log10, ylims = (0, 2), xlabel = "Frequency [rad/s]", ylabel = "Estimate / Monte Carlo", title = ["σ_G" "σ_κ²"]) +band!(1, :σa, σG_mc, "Analytic", 1) +band!(1, :σj, σG_mc, "Jackknife", 2) +band!(2, :σka, σk_mc, "Analytic", 1) +band!(2, :σkj, σk_mc, "Jackknife", 2) +hline!([1], c = :black, l = :dash, lab = "", sp = 1) +hline!([1], c = :black, l = :dash, lab = "", sp = 2) +DisplayAs.PNG(current()) # hide +``` +In this example, the median of the analytic estimates agrees with the Monte Carlo standard deviation, while the jackknife estimates are somewhat too small, by approximately 5% for `σ_G` and 10% for `σ_κ²`. The analytic estimate of `σ_G` obtained from a single experiment also varies less than the jackknife estimate (the 10%–90% range of the ratio is approximately 20% narrower), while the two estimates of `σ_κ²` vary similarly. Both estimates vary considerably between experiments when the number of windows is small. The analytic estimate accounts for the correlation between overlapping windows, which the jackknife estimate neglects: for an overlap of 75%, the jackknife estimate of `σ_G` is approximately 30% too small, while the analytic estimate is not affected. + +The analytic estimate is preferable when its assumptions hold approximately, i.e., when the noise is approximately Gaussian and stationary, and the input is either a Gaussian process (for the coherence) or known (for the transfer function). The jackknife estimate is more robust to violations of these assumptions, for example to noise that is not stationary over the duration of the experiment. Neither estimate accounts for bias, such as the bias caused by spectral leakage at sharp resonances, or by noise that is correlated with the input in closed-loop experiments. At frequencies where the true coherence is close to zero, both estimates overestimate the standard deviation of the coherence, by approximately 20%. The jackknife estimate of the coherence uncertainty requires at least three windows, and at least `m + 2` windows for `m` inputs. See the [example notebooks](https://github.com/JuliaControl/ControlExamples.jl?files=1) for more details. diff --git a/src/frd.jl b/src/frd.jl index f406ee9b..27be4cb0 100644 --- a/src/frd.jl +++ b/src/frd.jl @@ -198,7 +198,8 @@ ControlSystemsBase.c2d(f::FRD, Ts::Real; kwargs...) = FRD(c2d(f.w, Ts; kwargs... """ H, N = tfest(data, σ = 0.05; method = :corr) - H, N, σH = tfest(data; method = :welch, uncertainty = Val(true)) + H, N, σH = tfest(data, σ = 0.05; method, uncertainty = Val(:analytic)) + H, N, σH = tfest(data; method = :welch, uncertainty = Val(:jackknife)) Estimate a transfer function model using the Correlogram approach (default) using the signal model ``y = H(iω)u + n``. @@ -208,25 +209,44 @@ Both `H` and `N` are of type `FRD` (frequency-response data). - `H` = Syu/Suu Process transfer function - `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. - `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. -- `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. +- `uncertainty`: `Val(false)` (default), `Val(:analytic)` or `Val(:jackknife)` (`Val(true)` is equivalent to `Val(:jackknife)`). Unless `Val(false)`, a third return value `σH` is returned, an `FRD` containing an 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)}``. `Val(:analytic)` computes the standard deviation from the distribution of the estimate under the assumption of Gaussian noise and is available for both methods; `Val(:jackknife)` requires `method = :welch`. See Extended help. A Welch estimate pooled over several data segments is obtained by passing a vector of data objects, see `tfest(ds::AbstractVector{<:AbstractIdData})`. # Extended help This estimation method is unbiased if the input ``u`` is uncorrelated with the noise ``n``, but is otherwise biased (e.g., for identification in closed loop). -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. +## Analytic uncertainty estimate +With `uncertainty = Val(:analytic)`, the input is treated as known and the noise ``n`` as Gaussian and stationary, with a spectral density that varies slowly over the bandwidth of the window function. For the Welch method, with the transforms ``U_k, Y_k`` of window ``k = 1, …, K``, the model is ``Y_k = H U_k + V_k``. The estimate ``\\hat H = \\sum_k Y_k U_k^* / \\sum_k |U_k|^2`` is linear in the noise, so that, conditional on the input, ``\\hat H`` is complex Gaussian with variance + +```math +σ_H^2 = σ_V^2 \\frac{u^H C u}{(u^H u)^2}, +``` + +where ``u = (U_1, …, U_K)``, ``σ_V^2 = E|V_k|^2``, and ``C_{kj} = E[V_k V_j^*]/σ_V^2 = ρ(s_k - s_j) e^{iω(s_k - s_j)}`` accounts for the correlation between overlapping windows starting at samples ``s_k, s_j``, with ``ρ(Δ) = \\sum_t w_t w_{t+Δ} / \\sum_t w_t^2``. The noise variance is estimated without bias from the residual ``R = \\sum_k |Y_k - \\hat H U_k|^2`` as ``\\hat σ_V^2 = R / (K - q)``, with ``q = u^H C u / u^H u`` (``q = 1`` for windows that do not overlap). Windows in different data segments are uncorrelated. For the correlogram method, ``\\hat σ_H^2 = R / ((K_\\text{eff} - 1) S_{uu})`` with the spectral estimates ``S``, ``R = S_{yy} - |S_{yu}|^2/S_{uu}``, and the equivalent number of independent windows ``K_\\text{eff} = N / \\sum_τ w_τ^2`` of the lag window ``w``. + +Since the noise variance is estimated, ``|\\hat H - H|^2 / \\hat σ_H^2`` follows an ``F(2, 2(K-1))`` distribution for windows that do not overlap, which can be used to form confidence regions for small ``K``. The analytic estimate is more accurate than the jackknife estimate when its assumptions hold, in particular for a small number of windows, while the jackknife estimate does not rely on the Gaussian assumption. + +## Jackknife uncertainty estimate +With `uncertainty = Val(:jackknife)`, 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. """ 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 check_time_domain(d) d.nu == 1 || error("Cannot perform tfest on multiple-input data. Consider using time-domain estimation or statespace estimation.") - U && check_uncertainty_method(method) + um = uncertainty_method(U) + check_uncertainty_method(method, um) if d.ny > 1 - return stack_outputs([tfest(d[i,1], σ; method, n, noverlap, window, uncertainty) for i in 1:d.ny], Val(U ? 3 : 2)) + return stack_outputs([tfest(d[i,1], σ; method, n, noverlap, window, uncertainty) for i in 1:d.ny], Val(um === :none ? 2 : 3)) end y, u, h = vec(output(d)), vec(input(d)), sampletime(d) - if U + if um === :jackknife return spectra2tfest_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h) + elseif um === :analytic + if method === :welch + return tfest_analytic(welch_analytic([y], [u]; n, noverlap, window), h) + else + return tfest_analytic(corr_analytic(y, u, σ), h) + end end if method === :welch Syy, Suu, Syu, L = wcfft(y, u, n = n, noverlap = noverlap, window = window) @@ -239,7 +259,7 @@ end """ H, N = tfest(ds::AbstractVector{<:AbstractIdData}; n = minimum(length, ds) ÷ 10, noverlap = n ÷ 2, window = hamming) - H, N, σH = tfest(ds::AbstractVector{<:AbstractIdData}; uncertainty = Val(true), n, noverlap, window) + H, N, σH = tfest(ds::AbstractVector{<:AbstractIdData}; uncertainty = Val(:analytic), n, noverlap, window) Estimate a transfer function using the Welch method, pooled over several data segments `ds` (for example, separate experiments or disjoint parts of one experiment). The segments may have different lengths, but must share the sample time and the numbers of inputs and outputs. @@ -247,20 +267,23 @@ Every Welch window lies within a single segment. The cross- and auto-spectral su 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. -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)`. +If `uncertainty = Val(:analytic)` or `uncertainty = Val(:jackknife)`, an estimate `σH` of the standard deviation of `H` is returned as well, computed from the windows of all segments, see `tfest(d::AbstractIdData)`. Windows in different segments are treated as uncorrelated. See also [`coherence`](@ref), which accepts a vector of data segments in the same way. """ function tfest(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = minimum(length, ds) ÷ 10, noverlap = n ÷ 2, window = hamming, uncertainty::Val{U} = Val(false)) where U method === :welch || throw(ArgumentError("tfest with multiple data segments only supports method = :welch")) + um = uncertainty_method(U) h, ny = check_segments(ds) if ny > 1 - return stack_outputs([tfest([d[i,1] for d in ds]; n, noverlap, window, uncertainty) for i in 1:ny], Val(U ? 3 : 2)) + return stack_outputs([tfest([d[i,1] for d in ds]; n, noverlap, window, uncertainty) for i in 1:ny], Val(um === :none ? 2 : 3)) end ys = [vec(output(d)) for d in ds] us = [vec(input(d)) for d in ds] - if U + if um === :jackknife return spectra2tfest_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h) + elseif um === :analytic + return tfest_analytic(welch_analytic(ys, us; n, noverlap, window), h) end Syy, Suu, Syu, L = wcfft(ys, us; n, noverlap, window) return spectra2tfest(Syy, Suu, Syu, h, L) @@ -326,7 +349,22 @@ Throw an `ArgumentError` if the number of Welch windows `K` is smaller than the """ check_window_count(K, Kmin) = K >= Kmin || throw(ArgumentError("The jackknife uncertainty estimate requires at least $Kmin Welch windows, but only $K are available. Decrease the window length `n`.")) -check_uncertainty_method(method) = method === :welch || throw(ArgumentError("The uncertainty estimate is only available for method = :welch, got method = $(repr(method))")) +""" + uncertainty_method(U) + +The uncertainty estimate requested by the keyword argument `uncertainty::Val{U}`: `:none`, `:jackknife` or `:analytic`. +""" +function uncertainty_method(U) + U === false && return :none + (U === true || U === :jackknife) && return :jackknife + U === :analytic && return :analytic + throw(ArgumentError("The keyword argument `uncertainty` must be one of Val(false), Val(:analytic), Val(:jackknife) or Val(true), got Val($(repr(U)))")) +end + +function check_uncertainty_method(method, um) + um === :jackknife && method !== :welch && throw(ArgumentError("The jackknife uncertainty estimate is only available for method = :welch, got method = $(repr(method)). The analytic estimate, uncertainty = Val(:analytic), is available for both methods.")) + nothing +end """ stack_outputs(HNs, ::Val{M}) @@ -375,13 +413,13 @@ end """ κ² = coherence(d; n = length(d)÷10, noverlap = n÷2, window=hamming, method=:welch) - κ², σκ² = coherence(d; uncertainty = Val(true), n, noverlap, window) + κ², σκ² = coherence(d; uncertainty = Val(:analytic), n, noverlap, window) Calculates the magnitude-squared coherence Function. κ² close to 1 indicates a good explainability of energy in the output signal by energy in the input signal. κ² << 1 indicates that either the system is nonlinear, or a strong noise contributes to the output energy. - κ: Squared coherence function in the form of an [`FRD`](@ref). - `method`: `:welch` or `:corr`. `:welch` uses the Welch method to estimate the power spectral density, while `:corr` uses the Correlogram approach . For `method = :corr`, the additional keyword argument `σ` determines the width of the Gaussian window applied to the estimated correlation functions before FFT. A larger `σ` implies less smoothing. -- `uncertainty`: `Val(false)` (default) or `Val(true)`. If `Val(true)`, a second return value `σκ²` is returned, an `FRD` containing the delete-one jackknife estimate of the standard deviation of κ² over the Welch windows. Requires `method = :welch`. See the extended help of [`tfest`](@ref) for a description of the jackknife estimate and its limitations. For multiple inputs, the uncertainty of the multiple coherence is estimated in the same way. +- `uncertainty`: `Val(false)` (default), `Val(:analytic)` or `Val(:jackknife)` (`Val(true)` is equivalent to `Val(:jackknife)`). Unless `Val(false)`, a second return value `σκ²` is returned, an `FRD` containing an estimate of the standard deviation of κ². `Val(:jackknife)` computes the delete-one jackknife estimate over the Welch windows and requires `method = :welch`. `Val(:analytic)` computes the standard deviation of the distribution of κ² under the assumption of Gaussian noise, see Extended help, and is available for both methods. For multiple inputs, the uncertainty of the multiple coherence is estimated in the same ways. See the extended help of [`tfest`](@ref) for the assumptions and limitations of both estimates. A Welch estimate pooled over several data segments is obtained by passing a vector of data objects, see `coherence(ds::AbstractVector{<:AbstractIdData})`. @@ -393,17 +431,26 @@ For the signal model ``y = Gu + v``, ``κ²`` is defined as κ(ω)^2 = \\dfrac{S_{uy}}{S_{uu} S_{yy}} = \\dfrac{|G(iω)|^2S_{uu}^2}{S_{uu} (|G(iω)|^2S_{uu}^2 + S_{vv})} = \\dfrac{1}{1 + \\dfrac{S_{vv}}{S_{uu}|G(iω)|^2}} ``` 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``. + +With `uncertainty = Val(:analytic)`, the input and the noise are treated as jointly Gaussian processes. For ``K`` independent windows and ``m`` inputs, the estimate ``\\hat κ^2`` conditional on the input follows a noncentral beta distribution with parameters ``m``, ``K - m`` and noncentrality ``2|G|^2 S_{uu} / σ_V^2``, where ``σ_V^2`` is the noise power of a window. For Gaussian input, ``S_{uu}`` is gamma distributed, which results in the distribution of Goodman (1963), see also Carter, Knapp and Nuttall (1973). The signal-to-noise ratio ``κ^2 / (1 - κ^2)`` is estimated from the data without bias, overlapping windows are accounted for by the equivalent number of windows ``K_\\text{eff} = K^2 / \\sum_{k,j} ρ_{kj}^2`` (Welch, 1967), where ``ρ_{kj}`` is the correlation between windows ``k`` and ``j``, and the standard deviation of this distribution is returned. At the zero and Nyquist frequencies, the transforms are real-valued and the distribution with half the degrees of freedom is used. The distribution also shows that ``\\hat κ^2`` is biased upwards; for ``κ^2 = 0``, ``E[\\hat κ^2] = m / K``. """ function coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, method=:welch, σ = 0.05, uncertainty::Val{U} = Val(false)) where U check_time_domain(d) noutputs(d) == 1 || throw(ArgumentError("coherence only supports a single output. Index the data object like `d[i,:]` to obtain the `i`:th output.")) - U && check_uncertainty_method(method) + um = uncertainty_method(U) + check_uncertainty_method(method, um) if ninputs(d) > 1 return multiple_coherence(d; n, noverlap, window, σ, uncertainty) end y, u, h = vec(output(d)), vec(input(d)), sampletime(d) - if U + if um === :jackknife return spectra2coherence_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h) + elseif um === :analytic + if method === :welch + return coherence_analytic(welch_analytic([y], [u]; n, noverlap, window), h) + else + return coherence_analytic(corr_analytic(y, u, σ), h) + end end if method === :welch Syy, Suu, Syu = wcfft(y, u, n = n, noverlap = noverlap, window = window) @@ -417,11 +464,11 @@ end """ κ² = coherence(ds::AbstractVector{<:AbstractIdData}; n = minimum(length, ds) ÷ 10, noverlap = n ÷ 2, window = hamming) - κ², σκ² = coherence(ds::AbstractVector{<:AbstractIdData}; uncertainty = Val(true), n, noverlap, window) + κ², σκ² = coherence(ds::AbstractVector{<:AbstractIdData}; uncertainty = Val(:analytic), n, noverlap, window) Calculate the magnitude-squared coherence function using the Welch method, pooled over several data segments `ds` of possibly different lengths. The cross- and auto-spectral sums are accumulated over the Welch windows of all segments, each window lying within a single segment, before the coherence is formed. A segment shorter than `n` does not contribute. With a single segment, the result equals that of `coherence(ds[1]; n, noverlap, window)`. -If `uncertainty = Val(true)`, the jackknife estimate `σκ²` of the standard deviation of κ² is returned as well, computed by deleting one window at a time among the windows of all segments. +If `uncertainty = Val(:analytic)` or `uncertainty = Val(:jackknife)`, an estimate `σκ²` of the standard deviation of κ² is returned as well, computed from the windows of all segments, see `coherence(d::AbstractIdData)`. Only single-input, single-output data and `method = :welch` are supported for multiple segments. See [`tfest`](@ref) for the corresponding transfer-function estimate. """ @@ -429,10 +476,13 @@ function coherence(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = mi method === :welch || throw(ArgumentError("coherence with multiple data segments only supports method = :welch")) h, ny = check_segments(ds) ny == 1 || throw(ArgumentError("coherence only supports a single output. Index the data objects like `d[i,:]` to obtain the `i`:th output.")) + um = uncertainty_method(U) ys = [vec(output(d)) for d in ds] us = [vec(input(d)) for d in ds] - if U + if um === :jackknife return spectra2coherence_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h) + elseif um === :analytic + return coherence_analytic(welch_analytic(ys, us; n, noverlap, window), h) end Syy, Suu, Syu = wcfft(ys, us; n, noverlap, window) return spectra2coherence(Syy, Suu, Syu, h) @@ -477,7 +527,7 @@ function wcfft(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:Abstra Syy = zeros(nf) Suu = zeros(nf) Syu = zeros(ComplexF64, nf) - L = foreach_window(ys, us; n, noverlap, window) do xy, xu + L = foreach_window(ys, us; n, noverlap, window) do xy, xu, _ @. Syu += xy * conj(xu) @. Syy += abs2(xy) @. Suu += abs2(xu) @@ -494,7 +544,7 @@ function wcfft_windows(ys::AbstractVector{<:AbstractVector}, us::AbstractVector{ Pyy = Vector{Vector{Float64}}() Puu = Vector{Vector{Float64}}() Pyu = Vector{Vector{ComplexF64}}() - L = foreach_window(ys, us; n, noverlap, window) do xy, xu + L = foreach_window(ys, us; n, noverlap, window) do xy, xu, _ # The products are formed in the precision of the transforms, as in wcfft push!(Pyy, abs2.(xy)) push!(Puu, abs2.(xu)) @@ -506,28 +556,202 @@ end """ L = foreach_window(f, ys, us; n, noverlap, window) -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. +Call `f(xy, xu, s)` 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`, and the start `s` of the window on a common time axis on which consecutive signal segments are separated by at least `n` samples, such that windows of different segments do not overlap. 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. """ function foreach_window(f, ys::AbstractVector{<:AbstractVector}, us::AbstractVector{<:AbstractVector}; n, noverlap, window) length(ys) == length(us) || throw(DimensionMismatch("The numbers of output and input segments differ")) win, norm2 = DSP.Periodograms.compute_window(window, n) nfft = nextfastfft(n) nwin = 0 + offset = 0 for (y, u) in zip(ys, us) length(y) == length(u) || throw(DimensionMismatch("Input and output segments have different lengths")) - length(y) >= n || continue - uw = arraysplit(u, n, noverlap, nfft, win) - yw = arraysplit(y, n, noverlap, nfft, win) - for i in eachindex(uw) - f(rfft(yw[i]), rfft(uw[i])) + if length(y) >= n + uw = arraysplit(u, n, noverlap, nfft, win) + yw = arraysplit(y, n, noverlap, nfft, win) + for i in eachindex(uw) + f(rfft(yw[i]), rfft(uw[i]), offset + (i - 1) * (n - noverlap)) + end + nwin += length(uw) end - nwin += length(uw) + offset += length(y) + n end nwin > 0 || throw(ArgumentError("No data segment is at least as long as the window length n = $n")) nwin * norm2 end +""" + r = welch_analytic(ys, us; n, noverlap, window) + +Welch spectral sums of the signal segments `ys, us` together with the analytic estimates of the standard deviations of the transfer-function estimate and of the squared coherence, see the extended help of [`tfest`](@ref) and [`coherence`](@ref). Returns a named tuple with the fields `Syy, Suu, Syu, L, σH, σκ2`. +""" +function welch_analytic(ys, us; n, noverlap, window) + win, _ = DSP.Periodograms.compute_window(window, n) + nfft = nextfastfft(n) + Xy = Vector{Vector{ComplexF64}}() + Xu = Vector{Vector{ComplexF64}}() + starts = Int[] + L = foreach_window(ys, us; n, noverlap, window) do xy, xu, s + push!(Xy, xy) + push!(Xu, xu) + push!(starts, s) + end + Y = reduce(hcat, Xy) + X = reduce(hcat, Xu) + nf, K = size(Y) + check_window_count(K, 2) + pairs, Keff = window_pairs(starts, win, n) + σH = zeros(nf) + σκ2 = zeros(nf) + for f in 1:nf + r = analytic_frequency(reshape(X[f, :], K, 1), Y[f, :], pairs, 2π * (f - 1) / nfft, Keff, is_real_bin(f, nfft)) + σH[f] = sqrt(real(r.Σg[1, 1])) + σκ2[f] = r.σγ2 + end + Syy = vec(sum(abs2, Y, dims = 2)) + Suu = vec(sum(abs2, X, dims = 2)) + Syu = vec(sum(Y .* conj.(X), dims = 2)) + (; Syy, Suu, Syu, L, σH, σκ2) +end + +""" + r = corr_analytic(y, u, σ) + +Correlogram spectral estimates together with the analytic estimates of the standard deviations of the transfer-function estimate and of the squared coherence, based on the equivalent number of independent windows ``K_\\text{eff} = N / \\sum_τ w_τ^2`` of the lag window ``w``. Returns a named tuple with the fields `Syy, Suu, Syu, L, σH, σκ2`. +""" +function corr_analytic(y, u, σ) + N = length(y) + Syy0, Suu0, Syu = fft_corr(y, u, σ) + Syy, Suu = real(Syy0), real(Suu0) + Keff = N / sum(abs2, gaussian(2N - 1, σ)) + Keff > 2 || throw(ArgumentError("The lag window corresponds to $(round(Keff, digits=2)) independent windows, at least two are required for the analytic uncertainty estimate. Decrease the width σ of the lag window.")) + nf = length(Syu) + σH = zeros(nf) + σκ2 = zeros(nf) + for f in 1:nf + explained = abs2(Syu[f]) / Suu[f] + R = max(Syy[f] - explained, 0.0) + σH[f] = sqrt(R / ((Keff - 1) * Suu[f])) + δ = R > 0 ? max((Keff - 1) * explained / R - 1, 0.0) : Inf + σκ2[f] = coherence_std(1, Keff, δ / Keff, f == 1) # the transform length 2N - 1 is odd, only the zero frequency is real-valued + end + (; Syy, Suu, Syu, L = N, σH, σκ2) +end + +function tfest_analytic(r, h) + H, N = spectra2tfest(r.Syy, r.Suu, r.Syu, h, r.L) + H, N, FRD(H.w, r.σH) +end + +function coherence_analytic(r, h) + κ = spectra2coherence(r.Syy, r.Suu, r.Syu, h) + κ, FRD(κ.w, r.σκ2) +end + +""" + is_real_bin(f, nfft) + +Whether frequency bin `f` (one-based) of a real-valued transform of length `nfft` is the zero or Nyquist frequency, at which the transform of real-valued data is real-valued. +""" +is_real_bin(f, nfft) = f == 1 || 2(f - 1) == nfft + +""" + pairs, Keff = window_pairs(starts, win, n) + +The pairs of overlapping windows of length `n` starting at the samples `starts` (in increasing order), as tuples `(k, j, ρ, Δ)` with `k < j`, the correlation `ρ = Σ_t w_t w_{t+|Δ|} / Σ_t w_t²` of the window function `win` (`nothing` for a rectangular window) and the offset `Δ = starts[k] - starts[j]`. `Keff = K² / Σ_{k,j} ρ_{kj}²` is the equivalent number of independent windows (Welch, 1967). +""" +function window_pairs(starts::AbstractVector{<:Integer}, win, n) + w = win === nothing ? ones(n) : win + e = sum(abs2, w) + ρcache = Dict{Int, Float64}() + ρ(Δ) = get!(() -> sum(w[t] * w[t+Δ] for t in 1:n-Δ; init = 0.0) / e, ρcache, Δ) + K = length(starts) + pairs = Tuple{Int, Int, Float64, Int}[] + for k in 1:K + for j in k+1:K + Δ = starts[j] - starts[k] + Δ < n || break + push!(pairs, (k, j, ρ(Δ), -Δ)) + end + end + Keff = K^2 / (K + 2 * sum(p -> p[3]^2, pairs; init = 0.0)) + pairs, Keff +end + +""" + r = analytic_frequency(A, y, pairs, ω, Keff, realbin) + +Analytic uncertainty at one frequency for the model `y = A g + v`, where row `k` of `A` (windows × inputs) and `y[k]` are the input and output transforms of window `k`, and the noise transforms are Gaussian with covariance `σ_V² C`, `C[k, j] = ρ exp(iωΔ)` for the overlapping `pairs` (see [`window_pairs`](@ref)) and `C[k, k] = 1`. Returns a named tuple with the least-squares estimate `g`, its covariance `Σg` conditional on the input, the squared (multiple) coherence `γ2` and its standard deviation `σγ2` for Gaussian input, see [`coherence_std`](@ref). +""" +function analytic_frequency(A::AbstractMatrix, y::AbstractVector, pairs, ω, Keff, realbin) + K, m = size(A) + S = A' * A + b = A' * y + Si = inv(S) + g = Si * b + yy = sum(abs2, y) + explained = real(dot(b, g)) + R = max(yy - explained, 0.0) + M = Matrix{ComplexF64}(S) + for (k, j, ρ, Δ) in pairs + c = ρ * cis(ω * Δ) + ak = @view A[k, :] + aj = @view A[j, :] + M .+= c .* conj.(ak) .* transpose(aj) .+ conj(c) .* conj.(aj) .* transpose(ak) + end + q = real(tr(Si * M)) + σv2 = R / (K - q) + Σg = σv2 .* (Si * M * Si) + γ2 = clamp(explained / yy, 0.0, 1.0) + δ = σv2 > 0 ? max(explained / σv2 - q, 0.0) : Inf # unbiased estimate of g' S g / σ_V² + (; g, Σg, γ2, σγ2 = coherence_std(m, Keff, δ / K, realbin)) +end + +""" + coherence_std(m, Keff, θ, realbin) + +Standard deviation of the squared (multiple) coherence estimate with `m` inputs and `Keff` independent windows, for jointly Gaussian input and output with the signal-to-noise ratio `θ = γ² / (1 - γ²)` of the output. + +Conditional on the input, the estimate follows a noncentral beta distribution with parameters `m`, `Keff - m` and noncentrality `2δ`, where `δ = |G|² S_uu / σ_V²`, i.e., a Poisson(`δ`) mixture of beta distributions with parameters `m + j`, `Keff - m`. For Gaussian input, `δ / θ` is gamma distributed with shape parameter `Keff`, and the mixture weights are negative binomial with `Keff` trials and success probability `θ / (1 + θ)` (Goodman, 1963). For real-valued transforms (`realbin`), the degrees of freedom are halved. +""" +function coherence_std(m, Keff, θ, realbin) + isfinite(θ) || return 0.0 + realbin ? beta_mixture_std(m / 2, (Keff - m) / 2, Keff / 2, θ) : beta_mixture_std(m, Keff - m, Keff, θ) +end + +""" + beta_mixture_std(a, b, r, θ) + +Standard deviation of the mixture of beta distributions with parameters `a + j, b`, where `j` follows a negative binomial distribution with `r` trials and success probability `θ / (1 + θ)` (mean `rθ`). +""" +function beta_mixture_std(a, b, r, θ) + b > 0 || return NaN + θ > 0 || return sqrt(a * b / ((a + b)^2 * (a + b + 1))) + p = θ / (1 + θ) + μ, sd = r * θ, sqrt(r * θ * (1 + θ)) + jhi = ceil(Int, μ + 12sd + 10) + jlo = max(0, floor(Int, μ - 12sd - 10)) + jm = clamp(floor(Int, (r - 1) * θ), jlo, jhi) # mode + w = zeros(jhi - jlo + 1) # weights relative to the mode + w[jm - jlo + 1] = 1.0 + for j in jm:jhi-1 + w[j - jlo + 2] = w[j - jlo + 1] * (j + r) / (j + 1) * p + end + for j in jm:-1:jlo+1 + w[j - jlo] = w[j - jlo + 1] * j / ((j - 1 + r) * p) + end + w ./= sum(w) + m1 = m2 = 0.0 + for (i, j) in enumerate(jlo:jhi) + c = a + b + j + m1 += w[i] * (a + j) / c + m2 += w[i] * (a + j) * (a + j + 1) / (c * (c + 1)) + end + sqrt(max(m2 - m1^2, 0.0)) +end + function multiple_coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, σ = 0.05, uncertainty::Val{U} = Val(false)) where U + um = uncertainty_method(U) noutputs(d) == 1 || throw(ArgumentError("multiple_coherence only supports a single output.")) ninputs(d) > 1 || throw(ArgumentError("multiple_coherence requires multiple inputs. Use `coherence` for single input.")) @@ -539,21 +763,31 @@ function multiple_coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n n_freqs, K = size(Y) n_inputs = size(X, 2) # With fewer retained windows than inputs + 1, every delete-one multiple coherence equals one - U && check_window_count(K, n_inputs + 2) + um === :jackknife && check_window_count(K, n_inputs + 2) + if um === :analytic + check_window_count(K, n_inputs + 1) + win, _ = DSP.Periodograms.compute_window(window, n) + pairs, Keff = window_pairs(collect(0:(n - noverlap):(K - 1) * (n - noverlap)), win, n) + end γ2 = zeros(n_freqs) - γ2j = zeros(n_freqs, U ? K : 0) + γ2j = zeros(n_freqs, um === :jackknife ? K : 0) + σγ2 = zeros(n_freqs) for f in 1:n_freqs Xf = X[f, :, :] # n_inputs × K Yf = Y[f, :] γ2[f] = multiple_coherence_value(Xf, Yf) - U || continue - for k in 1:K - keep = [1:k-1; k+1:K] - γ2j[f, k] = multiple_coherence_value(Xf[:, keep], Yf[keep]) + if um === :jackknife + for k in 1:K + keep = [1:k-1; k+1:K] + γ2j[f, k] = multiple_coherence_value(Xf[:, keep], Yf[keep]) + end + elseif um === :analytic + σγ2[f] = analytic_frequency(transpose(Xf), Yf, pairs, 2π * (f - 1) / n, Keff, is_real_bin(f, n)).σγ2 end end w = freqvec(h, γ2) - U ? (FRD(w, γ2), FRD(w, jackknife_std(γ2j))) : FRD(w, γ2) + um === :none && return FRD(w, γ2) + FRD(w, γ2), FRD(w, um === :jackknife ? jackknife_std(γ2j) : σγ2) end """ diff --git a/test/test_frd.jl b/test/test_frd.jl index 228eeb92..2aeaea29 100644 --- a/test/test_frd.jl +++ b/test/test_frd.jl @@ -370,7 +370,7 @@ end @test_throws ArgumentError coherence(d; uncertainty = Val(true), n = 2000, noverlap = 0) # two windows @test coherence(dmi; uncertainty = Val(true), n = 1000, noverlap = 0) isa Tuple # two inputs: four windows suffice, three do not @test_throws ArgumentError coherence(dmi; uncertainty = Val(true), n = 1300, noverlap = 0) - @test_throws ArgumentError tfest(d; uncertainty = Val(true)) # default method = :corr + @test_throws ArgumentError tfest(d; uncertainty = Val(true)) # default method = :corr, jackknife requires :welch @test_throws ArgumentError coherence(d; method = :corr, uncertainty = Val(true)) @test_throws ArgumentError tfest(d; method = :welch, uncertainty = Val(true), n = 4000) # a single window end @@ -422,3 +422,86 @@ end @test_throws ArgumentError tfest([df]; n = 20) @test_throws ArgumentError coherence([df]; n = 20) end + +@testset "Analytic uncertainty of tfest and coherence" begin + @info "Testing analytic uncertainty of tfest and coherence" + Random.seed!(0) + G = tf([1, 0.5], [1, -0.9, 0.5], 1) + T = 4000 + function simulate_data(N, σn) + u = randn(1, N) + iddata(lsim(G, u)[1] .+ σn .* randn(1, N), u, 1) + end + d = simulate_data(T, 1.0) + kw = (; n = 256, window = DSP.hanning) + + # The estimates are unaffected by the uncertainty option + H0, N0 = tfest(d; method = :welch, kw...) + H, N, σH = tfest(d; method = :welch, uncertainty = Val(:analytic), kw...) + @test H.r ≈ H0.r + @test N.r ≈ N0.r + @test σH.w == H.w + @test all(≥(0), σH.r) + κ, σκ = coherence(d; uncertainty = Val(:analytic), kw...) + @test κ.r ≈ coherence(d; kw...).r + @test all(≥(0), σκ.r) + Hc, Nc, σHc = tfest(d; uncertainty = Val(:analytic)) # method = :corr + @test Hc.r ≈ tfest(d)[1].r + @test all(≥(0), σHc.r) + @test coherence(d; method = :corr, uncertainty = Val(:analytic))[1].r ≈ coherence(d; method = :corr).r + + # Without overlap, σH² = R / ((K - 1) Suu) + kw0 = (; n = 256, noverlap = 0, window = DSP.hanning) + Syy, Suu, Syu = CSI.wcfft(vec(d.y), vec(d.u); kw0...) + K = T ÷ 256 + _, _, σH0 = tfest(d; method = :welch, uncertainty = Val(:analytic), kw0...) + @test σH0.r ≈ sqrt.((Syy .- abs2.(Syu) ./ Suu) ./ ((K - 1) .* Suu)) + + # Without signal, the coherence estimate follows a Beta(1, K - 1) distribution at the interior frequencies + @test CSI.coherence_std(1, K, 0.0, false) ≈ sqrt((K - 1) / (K^2 * (K + 1))) + # The negative binomial mixture with θ → 0 approaches the Beta(1, K - 1) distribution + @test CSI.coherence_std(1, K, 1e-9, false) ≈ CSI.coherence_std(1, K, 0.0, false) rtol = 1e-6 + + # The analytic standard deviations agree with the spread over independent realizations + for (name, est) in (("Welch, 50% overlap", (; method = :welch, kw...)), + ("Welch, 75% overlap", (; method = :welch, n = 256, noverlap = 192, window = DSP.hanning)), + ("correlogram", (; method = :corr))) + Hs = Vector{ComplexF64}[] + σHs = Vector{Float64}[] + κs = Vector{Float64}[] + σκs = Vector{Float64}[] + for i in 1:100 + di = simulate_data(T, 1.0) + Hi, _, σHi = tfest(di; est..., uncertainty = Val(:analytic)) + κi, σκi = coherence(di; est..., uncertainty = Val(:analytic)) + push!(Hs, Hi.r); push!(σHs, σHi.r); push!(κs, κi.r); push!(σκs, σκi.r) + end + Hm = reduce(hcat, Hs) + σH_mc = vec(sqrt.(sum(abs2, Hm .- mean(Hm, dims = 2), dims = 2) ./ (size(Hm, 2) - 1))) + rH = mean(σHs) ./ σH_mc + rκ = mean(σκs) ./ vec(std(reduce(hcat, κs), dims = 2)) + @test 0.85 < median(rH) < 1.15 + @test 0.85 < median(rκ) < 1.2 + @test all(r -> 0.6 < r < 1.6, rH) + @test all(r -> 0.5 < r < 1.8, rκ) + end + + # Multiple outputs, multiple segments and multiple inputs + dm = iddata([vec(d.y) vec(d.y)]', d.u, 1) + @test tfest(dm; method = :welch, uncertainty = Val(:analytic), kw...)[3].r[2, 1, :] ≈ σH.r + @test tfest([d]; uncertainty = Val(:analytic), kw...)[3].r ≈ σH.r + @test coherence([d]; uncertainty = Val(:analytic), kw...)[2].r ≈ σκ.r + _, _, σHv = tfest([d[1:2000], d[2001:end]]; uncertainty = Val(:analytic), kw...) + @test all(isfinite, σHv.r) + u2 = randn(2, T) + y2 = lsim(ss(G), u2[1:1, :])[1] .+ 0.5 .* lsim(ss(G), u2[2:2, :])[1] .+ randn(1, T) + dmi = iddata(y2, u2, 1) + κmi, σκmi = coherence(dmi; n = 256, uncertainty = Val(:analytic)) + @test κmi.r ≈ coherence(dmi; n = 256).r + @test all(≥(0), σκmi.r) + + # Errors + @test_throws ArgumentError tfest(d; uncertainty = Val(:bootstrap)) + @test_throws ArgumentError coherence(d; method = :corr, uncertainty = Val(:jackknife)) + @test_throws ArgumentError tfest(d; method = :welch, uncertainty = Val(:analytic), n = T) # a single window +end From 42653b3fc84bb0cc634ecfb143316d8513266442 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 2 Dec 2026 19:05:55 +0000 Subject: [PATCH 5/6] Address review findings on the analytic uncertainty estimate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Compute the mixture moments of the coherence distribution with the law of total variance on the complement 1 - κ², which avoids cancellation at high coherence, and with bounded work (gamma approximation on a grid for large means); skip the coherence computation in tfest. - Compute the Welch residual directly from the fit, and estimate the signal-to-noise ratio with the bias correction for independent windows (real-valued bins included). - Return NaN at frequencies without input excitation or output power instead of aborting the estimate. - Validate `method`, reject method = :corr for multiple inputs (it was silently replaced by the Welch method), and require an equivalent number of windows larger than the number of inputs. - Correlogram: include the number of products per lag in the equivalent number of windows, reject lag windows that span too few lags, and document the approximations. - Document F(1, K - 1) at real-valued bins, correct the coherence formula in the extended help, and compare the mean predicted variance with the empirical variance in the documentation and tests. Co-Authored-By: Claude Opus 5.5 --- docs/src/freq.md | 11 ++-- src/frd.jl | 132 ++++++++++++++++++++++++++++++++--------------- test/test_frd.jl | 38 +++++++++++++- 3 files changed, 133 insertions(+), 48 deletions(-) diff --git a/docs/src/freq.md b/docs/src/freq.md index 7efe80ec..b1e6089a 100644 --- a/docs/src/freq.md +++ b/docs/src/freq.md @@ -51,7 +51,7 @@ nothing # hide ### Uncertainty estimates [`tfest`](@ref) and [`coherence`](@ref) optionally return an estimate of the standard deviation of the estimates at each frequency, requested with the keyword argument `uncertainty`. Two estimates are available: -- `uncertainty = Val(:analytic)` computes the standard deviation from the distribution of the estimates under the assumption that the input and the noise are Gaussian processes. The transfer-function estimate is linear in the noise, and is therefore complex Gaussian conditional on the input, with a variance that is computed from the input spectrum and the residual noise power. The correlation between overlapping Welch windows is taken into account. The squared coherence follows the distribution of Goodman (1963). This estimate is available for both `method = :welch` and `method = :corr`. +- `uncertainty = Val(:analytic)` computes the standard deviation from the distribution of the estimates under the assumption that the input and the noise are Gaussian processes. The transfer-function estimate is linear in the noise, and is therefore complex Gaussian conditional on the input, with a variance that is computed from the input spectrum and the residual noise power. The correlation between overlapping Welch windows is taken into account. The squared coherence follows the distribution of Goodman (1963) for independent windows, which is applied approximately with the equivalent number of independent windows for overlapping windows and for the lag window of the correlogram method. This estimate is available for both `method = :welch` and `method = :corr`. - `uncertainty = Val(:jackknife)` (or `Val(true)`) computes a delete-one jackknife estimate over the Welch windows, i.e., the spread of the estimates obtained when one window at a time is left out. It does not rely on the Gaussian assumption, but treats the windows as independent, and is only available for `method = :welch`. ```@example npfreq G, N, σG = tfest(dn; method = :welch, n = 1000, uncertainty = Val(:analytic)) @@ -66,7 +66,7 @@ DisplayAs.PNG(current()) # hide Here, `σG` is the standard deviation of the complex-valued estimate, ``\sqrt{\operatorname{Var}(\operatorname{Re} G) + \operatorname{Var}(\operatorname{Im} G)}``, which is an upper bound on the standard deviation of the magnitude ``|G|`` to first order. The band in the left figure thus indicates the total error of the estimate, including the phase error. A band around the coherence is also drawn by `coherenceplot(dn, (; n = 1000, uncertainty = Val(:analytic)))`. #### Comparison of the analytic and jackknife estimates -To compare the two estimates with the actual variability of the estimates, we repeat the experiment 200 times with new realizations of the input and the noise, and compute the standard deviation of the estimates over the realizations. A shorter experiment with a window length of 2000 samples is used, which gives only 19 windows, such that the difference between the two estimates is visible. The figure shows the ratio between the uncertainty estimates and the Monte Carlo standard deviation. A ratio of one indicates a correct estimate. Each uncertainty estimate is computed from a single experiment. The lines show the median ratio over the realizations, and the bands the 10% and 90% quantiles, i.e., how much the uncertainty estimate obtained from a single experiment varies. +To compare the two estimates with the actual variability of the estimates, we repeat the experiment 200 times with new realizations of the input and the noise, and compute the standard deviation of the estimates over the realizations. A shorter experiment with a window length of 2000 samples is used, which gives only 19 windows, such that the difference between the two estimates is visible. The figure shows the ratio between the uncertainty estimates and the Monte Carlo standard deviation. A ratio of one indicates a correct estimate. Each uncertainty estimate is computed from a single experiment. The lines show the ratio between the root-mean-square uncertainty estimate (the square root of the mean predicted variance) and the Monte Carlo standard deviation, and the bands the 10% and 90% quantiles of the ratios of the individual uncertainty estimates, i.e., how much the uncertainty estimate obtained from a single experiment varies. The transfer-function variance is computed conditional on the input; since the estimate is unbiased given the input, the mean conditional variance equals the variance over realizations with new inputs. ```@example npfreq using Statistics Tc = 20000 @@ -91,8 +91,9 @@ Gs = reduce(hcat, [r.G for r in res]) σk_mc = vec(std(reduce(hcat, [r.k for r in res]), dims = 2)) function band!(sp, field, σ_mc, lab, color) M = reduce(hcat, [getfield(r, field) for r in res])[inds, :] ./ σ_mc[inds] - q10, q50, q90 = (mapslices(x -> quantile(x, q), M, dims = 2)[:] for q in (0.1, 0.5, 0.9)) - plot!(w[inds], q50, ribbon = (q50 .- q10, q90 .- q50), sp = sp, lab = lab, c = color, fillalpha = 0.3) + q10, q90 = (mapslices(x -> quantile(x, q), M, dims = 2)[:] for q in (0.1, 0.9)) + rms = sqrt.(mean(abs2, M, dims = 2)[:]) + plot!(w[inds], rms, ribbon = (rms .- q10, q90 .- rms), sp = sp, lab = lab, c = color, fillalpha = 0.3) end plot(layout = (1, 2), size = (800, 350), xscale = :log10, ylims = (0, 2), xlabel = "Frequency [rad/s]", ylabel = "Estimate / Monte Carlo", title = ["σ_G" "σ_κ²"]) band!(1, :σa, σG_mc, "Analytic", 1) @@ -103,7 +104,7 @@ hline!([1], c = :black, l = :dash, lab = "", sp = 1) hline!([1], c = :black, l = :dash, lab = "", sp = 2) DisplayAs.PNG(current()) # hide ``` -In this example, the median of the analytic estimates agrees with the Monte Carlo standard deviation, while the jackknife estimates are somewhat too small, by approximately 5% for `σ_G` and 10% for `σ_κ²`. The analytic estimate of `σ_G` obtained from a single experiment also varies less than the jackknife estimate (the 10%–90% range of the ratio is approximately 20% narrower), while the two estimates of `σ_κ²` vary similarly. Both estimates vary considerably between experiments when the number of windows is small. The analytic estimate accounts for the correlation between overlapping windows, which the jackknife estimate neglects: for an overlap of 75%, the jackknife estimate of `σ_G` is approximately 30% too small, while the analytic estimate is not affected. +In this example, the root-mean-square values of both estimates of `σ_G` agree with the Monte Carlo standard deviation, and the analytic estimate obtained from a single experiment varies less than the jackknife estimate (the 10%–90% range of the ratio is approximately 15% narrower). For `σ_κ²`, the jackknife estimate agrees with the Monte Carlo standard deviation, while the analytic estimate is approximately 10%–20% too large on average. The analytic estimate evaluates the distribution of the coherence at the estimated signal-to-noise ratio, and the error in this estimate increases the predicted standard deviation on average, in particular where the coherence is high and the number of windows small. The analytic estimate accounts for the correlation between overlapping windows, which the jackknife estimate neglects: for an overlap of 75%, the jackknife estimates are approximately 30% too small, while the analytic estimates are not affected. The analytic estimate is preferable when its assumptions hold approximately, i.e., when the noise is approximately Gaussian and stationary, and the input is either a Gaussian process (for the coherence) or known (for the transfer function). The jackknife estimate is more robust to violations of these assumptions, for example to noise that is not stationary over the duration of the experiment. Neither estimate accounts for bias, such as the bias caused by spectral leakage at sharp resonances, or by noise that is correlated with the input in closed-loop experiments. At frequencies where the true coherence is close to zero, both estimates overestimate the standard deviation of the coherence, by approximately 20%. The jackknife estimate of the coherence uncertainty requires at least three windows, and at least `m + 2` windows for `m` inputs. diff --git a/src/frd.jl b/src/frd.jl index 27be4cb0..2fb30b93 100644 --- a/src/frd.jl +++ b/src/frd.jl @@ -225,7 +225,7 @@ With `uncertainty = Val(:analytic)`, the input is treated as known and the noise where ``u = (U_1, …, U_K)``, ``σ_V^2 = E|V_k|^2``, and ``C_{kj} = E[V_k V_j^*]/σ_V^2 = ρ(s_k - s_j) e^{iω(s_k - s_j)}`` accounts for the correlation between overlapping windows starting at samples ``s_k, s_j``, with ``ρ(Δ) = \\sum_t w_t w_{t+Δ} / \\sum_t w_t^2``. The noise variance is estimated without bias from the residual ``R = \\sum_k |Y_k - \\hat H U_k|^2`` as ``\\hat σ_V^2 = R / (K - q)``, with ``q = u^H C u / u^H u`` (``q = 1`` for windows that do not overlap). Windows in different data segments are uncorrelated. For the correlogram method, ``\\hat σ_H^2 = R / ((K_\\text{eff} - 1) S_{uu})`` with the spectral estimates ``S``, ``R = S_{yy} - |S_{yu}|^2/S_{uu}``, and the equivalent number of independent windows ``K_\\text{eff} = N / \\sum_τ w_τ^2`` of the lag window ``w``. -Since the noise variance is estimated, ``|\\hat H - H|^2 / \\hat σ_H^2`` follows an ``F(2, 2(K-1))`` distribution for windows that do not overlap, which can be used to form confidence regions for small ``K``. The analytic estimate is more accurate than the jackknife estimate when its assumptions hold, in particular for a small number of windows, while the jackknife estimate does not rely on the Gaussian assumption. +Since the noise variance is estimated, ``|\\hat H - H|^2 / \\hat σ_H^2`` follows an ``F(2, 2(K-1))`` distribution for windows that do not overlap, which can be used to form confidence regions for small ``K``. At the zero and Nyquist frequencies, where the transforms of real-valued data are real-valued, it follows an ``F(1, K-1)`` distribution. For the correlogram method, the estimate assumes an input spectrum that varies slowly over the bandwidth of the lag window, and requires a lag window that spans many lags. The distribution of the coherence estimated with a lag window is approximated by that of ``K_\\text{eff}`` independent windows, which tends to overestimate the standard deviation of the coherence where the coherence is high. With overlapping windows, the noise is assumed to be approximately white over the bandwidth of the window function. The analytic estimate is more accurate than the jackknife estimate when its assumptions hold, in particular for a small number of windows, while the jackknife estimate does not rely on the Gaussian assumption. ## Jackknife uncertainty estimate With `uncertainty = Val(:jackknife)`, 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. @@ -234,6 +234,7 @@ function tfest(d::AbstractIdData, σ::Real = 0.05; method = :corr, n = length(d) check_time_domain(d) d.nu == 1 || error("Cannot perform tfest on multiple-input data. Consider using time-domain estimation or statespace estimation.") um = uncertainty_method(U) + check_method(method) check_uncertainty_method(method, um) if d.ny > 1 return stack_outputs([tfest(d[i,1], σ; method, n, noverlap, window, uncertainty) for i in 1:d.ny], Val(um === :none ? 2 : 3)) @@ -243,9 +244,9 @@ function tfest(d::AbstractIdData, σ::Real = 0.05; method = :corr, n = length(d) return spectra2tfest_jackknife(wcfft_windows([y], [u]; n, noverlap, window)..., h) elseif um === :analytic if method === :welch - return tfest_analytic(welch_analytic([y], [u]; n, noverlap, window), h) + return tfest_analytic(welch_analytic([y], [u]; n, noverlap, window, coherence = false), h) else - return tfest_analytic(corr_analytic(y, u, σ), h) + return tfest_analytic(corr_analytic(y, u, σ; coherence = false), h) end end if method === :welch @@ -283,7 +284,7 @@ function tfest(ds::AbstractVector{<:AbstractIdData}; method = :welch, n = minimu if um === :jackknife return spectra2tfest_jackknife(wcfft_windows(ys, us; n, noverlap, window)..., h) elseif um === :analytic - return tfest_analytic(welch_analytic(ys, us; n, noverlap, window), h) + return tfest_analytic(welch_analytic(ys, us; n, noverlap, window, coherence = false), h) end Syy, Suu, Syu, L = wcfft(ys, us; n, noverlap, window) return spectra2tfest(Syy, Suu, Syu, h, L) @@ -347,7 +348,7 @@ end Throw an `ArgumentError` if the number of Welch windows `K` is smaller than the number `Kmin` required by the jackknife uncertainty estimate. """ -check_window_count(K, Kmin) = K >= Kmin || throw(ArgumentError("The jackknife uncertainty estimate requires at least $Kmin Welch windows, but only $K are available. Decrease the window length `n`.")) +check_window_count(K, Kmin) = K >= Kmin || throw(ArgumentError("The uncertainty estimate requires at least $Kmin Welch windows, but only $K are available. Decrease the window length `n`.")) """ uncertainty_method(U) @@ -361,6 +362,8 @@ function uncertainty_method(U) throw(ArgumentError("The keyword argument `uncertainty` must be one of Val(false), Val(:analytic), Val(:jackknife) or Val(true), got Val($(repr(U)))")) end +check_method(method) = method in (:welch, :corr) || throw(ArgumentError("Unknown method $(repr(method)), expected :welch or :corr")) + function check_uncertainty_method(method, um) um === :jackknife && method !== :welch && throw(ArgumentError("The jackknife uncertainty estimate is only available for method = :welch, got method = $(repr(method)). The analytic estimate, uncertainty = Val(:analytic), is available for both methods.")) nothing @@ -428,18 +431,20 @@ See also [`coherenceplot`](@ref) # Extended help: For the signal model ``y = Gu + v``, ``κ²`` is defined as ```math -κ(ω)^2 = \\dfrac{S_{uy}}{S_{uu} S_{yy}} = \\dfrac{|G(iω)|^2S_{uu}^2}{S_{uu} (|G(iω)|^2S_{uu}^2 + S_{vv})} = \\dfrac{1}{1 + \\dfrac{S_{vv}}{S_{uu}|G(iω)|^2}} +κ(ω)^2 = \\dfrac{|S_{uy}|^2}{S_{uu} S_{yy}} = \\dfrac{|G(iω)|^2S_{uu}^2}{S_{uu} (|G(iω)|^2S_{uu} + S_{vv})} = \\dfrac{1}{1 + \\dfrac{S_{vv}}{S_{uu}|G(iω)|^2}} ``` 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``. -With `uncertainty = Val(:analytic)`, the input and the noise are treated as jointly Gaussian processes. For ``K`` independent windows and ``m`` inputs, the estimate ``\\hat κ^2`` conditional on the input follows a noncentral beta distribution with parameters ``m``, ``K - m`` and noncentrality ``2|G|^2 S_{uu} / σ_V^2``, where ``σ_V^2`` is the noise power of a window. For Gaussian input, ``S_{uu}`` is gamma distributed, which results in the distribution of Goodman (1963), see also Carter, Knapp and Nuttall (1973). The signal-to-noise ratio ``κ^2 / (1 - κ^2)`` is estimated from the data without bias, overlapping windows are accounted for by the equivalent number of windows ``K_\\text{eff} = K^2 / \\sum_{k,j} ρ_{kj}^2`` (Welch, 1967), where ``ρ_{kj}`` is the correlation between windows ``k`` and ``j``, and the standard deviation of this distribution is returned. At the zero and Nyquist frequencies, the transforms are real-valued and the distribution with half the degrees of freedom is used. The distribution also shows that ``\\hat κ^2`` is biased upwards; for ``κ^2 = 0``, ``E[\\hat κ^2] = m / K``. +With `uncertainty = Val(:analytic)`, the input and the noise are treated as jointly Gaussian processes. For ``K`` independent windows and ``m`` inputs, the estimate ``\\hat κ^2`` conditional on the input follows a noncentral beta distribution with parameters ``m``, ``K - m`` and noncentrality ``2|G|^2 S_{uu} / σ_V^2``, where ``σ_V^2`` is the noise power of a window. For Gaussian input, ``S_{uu}`` is gamma distributed, which results in the distribution of Goodman (1963), see also Carter, Knapp and Nuttall (1973). The signal-to-noise ratio ``κ^2 / (1 - κ^2)`` is estimated from the data, without bias for independent windows before it is truncated at zero, and the standard deviation of the distribution at the estimated signal-to-noise ratio is returned. Overlapping windows are accounted for approximately by the equivalent number of windows ``K_\\text{eff} = K^2 / \\sum_{k,j} ρ_{kj}^2`` (Welch, 1967), where ``ρ_{kj}`` is the correlation between windows ``k`` and ``j``. Where the coherence is undefined (no output power, or no input excitation), the standard deviation is `NaN`. At the zero and Nyquist frequencies, the transforms are real-valued and the distribution with half the degrees of freedom is used. The distribution also shows that ``\\hat κ^2`` is biased upwards; for ``κ^2 = 0``, ``E[\\hat κ^2] = m / K``. """ function coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, method=:welch, σ = 0.05, uncertainty::Val{U} = Val(false)) where U check_time_domain(d) noutputs(d) == 1 || throw(ArgumentError("coherence only supports a single output. Index the data object like `d[i,:]` to obtain the `i`:th output.")) um = uncertainty_method(U) + check_method(method) check_uncertainty_method(method, um) if ninputs(d) > 1 + method === :welch || throw(ArgumentError("coherence with multiple inputs only supports method = :welch")) return multiple_coherence(d; n, noverlap, window, σ, uncertainty) end y, u, h = vec(output(d)), vec(input(d)), sampletime(d) @@ -583,9 +588,9 @@ end """ r = welch_analytic(ys, us; n, noverlap, window) -Welch spectral sums of the signal segments `ys, us` together with the analytic estimates of the standard deviations of the transfer-function estimate and of the squared coherence, see the extended help of [`tfest`](@ref) and [`coherence`](@ref). Returns a named tuple with the fields `Syy, Suu, Syu, L, σH, σκ2`. +Welch spectral sums of the signal segments `ys, us` together with the analytic estimates of the standard deviations of the transfer-function estimate and (if `coherence`) of the squared coherence, see the extended help of [`tfest`](@ref) and [`coherence`](@ref). Returns a named tuple with the fields `Syy, Suu, Syu, L, σH, σκ2`. """ -function welch_analytic(ys, us; n, noverlap, window) +function welch_analytic(ys, us; n, noverlap, window, coherence = true) win, _ = DSP.Periodograms.compute_window(window, n) nfft = nextfastfft(n) Xy = Vector{Vector{ComplexF64}}() @@ -601,10 +606,11 @@ function welch_analytic(ys, us; n, noverlap, window) nf, K = size(Y) check_window_count(K, 2) pairs, Keff = window_pairs(starts, win, n) + check_effective_windows(Keff, 1) σH = zeros(nf) σκ2 = zeros(nf) for f in 1:nf - r = analytic_frequency(reshape(X[f, :], K, 1), Y[f, :], pairs, 2π * (f - 1) / nfft, Keff, is_real_bin(f, nfft)) + r = analytic_frequency(reshape(X[f, :], K, 1), Y[f, :], pairs, 2π * (f - 1) / nfft, Keff, is_real_bin(f, nfft); coherence) σH[f] = sqrt(real(r.Σg[1, 1])) σκ2[f] = r.σγ2 end @@ -617,23 +623,31 @@ end """ r = corr_analytic(y, u, σ) -Correlogram spectral estimates together with the analytic estimates of the standard deviations of the transfer-function estimate and of the squared coherence, based on the equivalent number of independent windows ``K_\\text{eff} = N / \\sum_τ w_τ^2`` of the lag window ``w``. Returns a named tuple with the fields `Syy, Suu, Syu, L, σH, σκ2`. +Correlogram spectral estimates together with the analytic estimates of the standard deviations of the transfer-function estimate and (if `coherence`) of the squared coherence, based on the equivalent number of independent windows ``K_\\text{eff} = N / \\sum_τ w_τ^2 (1 - |τ|/N)`` of the lag window ``w``. The estimates assume an input spectrum that varies slowly over the bandwidth of the lag window. Returns a named tuple with the fields `Syy, Suu, Syu, L, σH, σκ2`. """ -function corr_analytic(y, u, σ) +function corr_analytic(y, u, σ; coherence = true) N = length(y) Syy0, Suu0, Syu = fft_corr(y, u, σ) Syy, Suu = real(Syy0), real(Suu0) - Keff = N / sum(abs2, gaussian(2N - 1, σ)) - Keff > 2 || throw(ArgumentError("The lag window corresponds to $(round(Keff, digits=2)) independent windows, at least two are required for the analytic uncertainty estimate. Decrease the width σ of the lag window.")) + # Squared lag window weighted by the number of products in each lag of the cross-correlation + w2 = sum(abs2(w) * (1 - abs(τ) / N) for (w, τ) in zip(gaussian(2N - 1, σ), -(N - 1):(N - 1))) + w2 >= 10 || throw(ArgumentError("The lag window is too narrow for the analytic uncertainty estimate (Σ_τ w_τ² = $(round(w2, sigdigits = 3)), at least 10 is required). Increase the width σ of the lag window.")) + Keff = N / w2 + check_effective_windows(Keff, 1) nf = length(Syu) σH = zeros(nf) - σκ2 = zeros(nf) + σκ2 = fill(NaN, nf) for f in 1:nf explained = abs2(Syu[f]) / Suu[f] R = max(Syy[f] - explained, 0.0) σH[f] = sqrt(R / ((Keff - 1) * Suu[f])) - δ = R > 0 ? max((Keff - 1) * explained / R - 1, 0.0) : Inf - σκ2[f] = coherence_std(1, Keff, δ / Keff, f == 1) # the transform length 2N - 1 is odd, only the zero frequency is real-valued + coherence || continue + # The transform length 2N - 1 is odd, only the zero frequency is real-valued + realbin = f == 1 + Syy[f] > 0 || continue + # The bias correction of snr_estimate assumes independent windows; for the lag window it + # overcorrects, so the signal-to-noise ratio is estimated without it + σκ2[f] = R > 0 ? coherence_std(1, Keff, max((Keff - 1) * explained / R - 1, 0.0) / Keff, realbin) : 0.0 end (; Syy, Suu, Syu, L = N, σH, σκ2) end @@ -683,15 +697,18 @@ end Analytic uncertainty at one frequency for the model `y = A g + v`, where row `k` of `A` (windows × inputs) and `y[k]` are the input and output transforms of window `k`, and the noise transforms are Gaussian with covariance `σ_V² C`, `C[k, j] = ρ exp(iωΔ)` for the overlapping `pairs` (see [`window_pairs`](@ref)) and `C[k, k] = 1`. Returns a named tuple with the least-squares estimate `g`, its covariance `Σg` conditional on the input, the squared (multiple) coherence `γ2` and its standard deviation `σγ2` for Gaussian input, see [`coherence_std`](@ref). """ -function analytic_frequency(A::AbstractMatrix, y::AbstractVector, pairs, ω, Keff, realbin) +function analytic_frequency(A::AbstractMatrix, y::AbstractVector, pairs, ω, Keff, realbin; coherence = true) K, m = size(A) S = A' * A + F = cholesky(Hermitian(S); check = false) + if !issuccess(F) # the input is not excited at this frequency + return (; g = fill(complex(NaN), m), Σg = fill(complex(NaN), m, m), γ2 = NaN, σγ2 = NaN) + end b = A' * y - Si = inv(S) - g = Si * b + g = F \ b yy = sum(abs2, y) + R = sum(abs2, y - A * g) explained = real(dot(b, g)) - R = max(yy - explained, 0.0) M = Matrix{ComplexF64}(S) for (k, j, ρ, Δ) in pairs c = ρ * cis(ω * Δ) @@ -699,14 +716,36 @@ function analytic_frequency(A::AbstractMatrix, y::AbstractVector, pairs, ω, Kef aj = @view A[j, :] M .+= c .* conj.(ak) .* transpose(aj) .+ conj(c) .* conj.(aj) .* transpose(ak) end + Si = inv(F) q = real(tr(Si * M)) σv2 = R / (K - q) Σg = σv2 .* (Si * M * Si) + if !coherence || yy == 0 # the coherence is undefined without output power + return (; g, Σg, γ2 = NaN, σγ2 = NaN) + end γ2 = clamp(explained / yy, 0.0, 1.0) - δ = σv2 > 0 ? max(explained / σv2 - q, 0.0) : Inf # unbiased estimate of g' S g / σ_V² - (; g, Σg, γ2, σγ2 = coherence_std(m, Keff, δ / K, realbin)) + σγ2 = R > 0 ? coherence_std(m, Keff, snr_estimate(explained / σv2, q, K, Keff - m, realbin), realbin) : 0.0 + (; g, Σg, γ2, σγ2) +end + +""" + θ = snr_estimate(r, q, K, ν, realbin) + +Estimate of the signal-to-noise ratio ``θ = |G|^2 Φ_u / Φ_v`` from the ratio `r` between the explained output power and the estimated noise power of a window, where `q` is the expected explained power of the noise in units of the noise power of a window, `K` the number of windows, and `ν` the (effective) number of degrees of freedom of the residual. For independent windows, `r (ν - c) / ν - q` is an unbiased estimate of ``Kθ``, with `c = 1` for complex-valued and `c = 2` for real-valued transforms (`realbin`). The estimate is truncated at zero, and for overlapping windows, `ν` is approximated by the equivalent number of windows. +""" +function snr_estimate(r, q, K, ν, realbin) + c = realbin ? 2 : 1 + factor = ν > c ? (ν - c) / ν : 1.0 + max(factor * r - q, 0.0) / K end +""" + check_effective_windows(Keff, m) + +Throw an `ArgumentError` unless the equivalent number of independent windows `Keff` exceeds the number of inputs `m`. +""" +check_effective_windows(Keff, m) = Keff > m || throw(ArgumentError("The windows correspond to $(round(Keff, sigdigits = 3)) independent windows, which is not more than the number of inputs ($m). The analytic uncertainty estimate requires more data, a shorter window length `n`, or less overlap `noverlap`.")) + """ coherence_std(m, Keff, θ, realbin) @@ -727,27 +766,37 @@ Standard deviation of the mixture of beta distributions with parameters `a + j, function beta_mixture_std(a, b, r, θ) b > 0 || return NaN θ > 0 || return sqrt(a * b / ((a + b)^2 * (a + b + 1))) - p = θ / (1 + θ) + # Conditional mean of the complement 1 - X ~ Beta(b, a + j) and conditional variance of X, + # combined by the law of total variance to avoid cancellation for X close to one + cmean(j) = b / (a + b + j) + cvar(j) = (a + j) * b / ((a + b + j)^2 * (a + b + j + 1)) μ, sd = r * θ, sqrt(r * θ * (1 + θ)) - jhi = ceil(Int, μ + 12sd + 10) - jlo = max(0, floor(Int, μ - 12sd - 10)) - jm = clamp(floor(Int, (r - 1) * θ), jlo, jhi) # mode - w = zeros(jhi - jlo + 1) # weights relative to the mode - w[jm - jlo + 1] = 1.0 - for j in jm:jhi-1 - w[j - jlo + 2] = w[j - jlo + 1] * (j + r) / (j + 1) * p - end - for j in jm:-1:jlo+1 - w[j - jlo] = w[j - jlo + 1] * j / ((j - 1 + r) * p) + if 24sd + 20 <= 20_000 + jlo = max(0, floor(Int, μ - 12sd - 10)) + jhi = ceil(Int, μ + 12sd + 10) + p = θ / (1 + θ) + js = jlo:jhi + jm = clamp(floor(Int, (r - 1) * θ), jlo, jhi) # mode + w = zeros(length(js)) # weights relative to the mode + w[jm - jlo + 1] = 1.0 + for j in jm:jhi-1 + w[j - jlo + 2] = w[j - jlo + 1] * (j + r) / (j + 1) * p + end + for j in jm:-1:jlo+1 + w[j - jlo] = w[j - jlo + 1] * j / ((j - 1 + r) * p) + end + else + # For large means, the negative binomial distribution is approximated by the gamma distribution + # with the same mean and variance, evaluated on a dense grid + k, s = μ^2 / sd^2, sd^2 / μ + js = range(max(0.0, μ - 12sd), μ + 12sd, length = 20_001) + logw = [(k - 1) * log(x) - x / s for x in js] + w = exp.(logw .- maximum(logw)) end w ./= sum(w) - m1 = m2 = 0.0 - for (i, j) in enumerate(jlo:jhi) - c = a + b + j - m1 += w[i] * (a + j) / c - m2 += w[i] * (a + j) * (a + j + 1) / (c * (c + 1)) - end - sqrt(max(m2 - m1^2, 0.0)) + m = sum(w[i] * cmean(j) for (i, j) in enumerate(js)) + v = sum(w[i] * (cvar(j) + (cmean(j) - m)^2) for (i, j) in enumerate(js)) + sqrt(v) end function multiple_coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n ÷ 2, window = hamming, σ = 0.05, uncertainty::Val{U} = Val(false)) where U @@ -768,6 +817,7 @@ function multiple_coherence(d::AbstractIdData; n = length(d) ÷ 10, noverlap = n check_window_count(K, n_inputs + 1) win, _ = DSP.Periodograms.compute_window(window, n) pairs, Keff = window_pairs(collect(0:(n - noverlap):(K - 1) * (n - noverlap)), win, n) + check_effective_windows(Keff, n_inputs) end γ2 = zeros(n_freqs) γ2j = zeros(n_freqs, um === :jackknife ? K : 0) diff --git a/test/test_frd.jl b/test/test_frd.jl index 2aeaea29..a6c246c0 100644 --- a/test/test_frd.jl +++ b/test/test_frd.jl @@ -478,8 +478,9 @@ end end Hm = reduce(hcat, Hs) σH_mc = vec(sqrt.(sum(abs2, Hm .- mean(Hm, dims = 2), dims = 2) ./ (size(Hm, 2) - 1))) - rH = mean(σHs) ./ σH_mc - rκ = mean(σκs) ./ vec(std(reduce(hcat, κs), dims = 2)) + # The mean predicted variance is compared with the empirical variance + rH = sqrt.(mean(σ -> σ .^ 2, σHs)) ./ σH_mc + rκ = sqrt.(mean(σ -> σ .^ 2, σκs)) ./ vec(std(reduce(hcat, κs), dims = 2)) @test 0.85 < median(rH) < 1.15 @test 0.85 < median(rκ) < 1.2 @test all(r -> 0.6 < r < 1.6, rH) @@ -500,7 +501,40 @@ end @test κmi.r ≈ coherence(dmi; n = 256).r @test all(≥(0), σκmi.r) + # High signal-to-noise ratio: bounded work and no cancellation + @test CSI.coherence_std(1, 19, 1e8, false) < 1e-8 + @test (@elapsed CSI.coherence_std(1, 19, 1e8, false)) < 1 + θ = 1e5 # compare with the standard deviation of the complement 1 - κ² obtained from simulation of the Goodman distribution + @test CSI.coherence_std(1, 19, θ, false) ≈ CSI.coherence_std(1, 19, θ * (1 + 1e-9), false) rtol = 1e-6 + # The discrete sum and the gamma approximation agree where they meet + θs = 1e3 # mean 19θ with spread well beyond the discrete limit + @test CSI.beta_mixture_std(1, 18, 19, θs) ≈ CSI.beta_mixture_std(1, 18, 19.0, θs) rtol = 1e-9 + σdisc = CSI.beta_mixture_std(1, 18, 19, 300.0) # discrete sum + σgrid = CSI.beta_mixture_std(1, 18, 19, 3000.0) # gamma approximation + @test σgrid < σdisc + # Noiseless data give zero uncertainty + dn0 = iddata(2 .* d.u, d.u, 1) + _, _, σH_n0 = tfest(dn0; method = :welch, uncertainty = Val(:analytic), kw...) + @test maximum(σH_n0.r) < 1e-12 + @test maximum(coherence(dn0; uncertainty = Val(:analytic), kw...)[2].r) < 1e-6 + # A frequency at which the input is not excited gives NaN at that frequency only + ualt = repeat([1.0, -1.0], T ÷ 2) + dalt = iddata(randn(T), ualt .+ 0 .* randn(T), 1) + Halt, _, σHalt = tfest(dalt; method = :welch, uncertainty = Val(:analytic), n = 64, window = nothing) + @test isnan(σHalt.r[1]) + @test all(isfinite, σHalt.r[end]) + κalt, σκalt = coherence(iddata(randn(T), ualt, 1); uncertainty = Val(:analytic), n = 64, window = nothing) + @test isnan(σκalt.r[1]) + # No output power: the coherence and its uncertainty are undefined + @test all(isnan, coherence(iddata(zeros(T), d.u, 1); uncertainty = Val(:analytic), kw...)[2].r) + # Errors + @test_throws ArgumentError tfest(d; method = :weclh, uncertainty = Val(:analytic)) + @test_throws ArgumentError coherence(d; method = :weclh) + @test_throws ArgumentError coherence(dmi; method = :corr, n = 256) + dmi3 = iddata(dmi.y[:, 1:66], dmi.u[:, 1:66], 1) # three heavily overlapping windows + @test_throws ArgumentError coherence(dmi3; uncertainty = Val(:analytic), n = 64, noverlap = 63, window = nothing) # Keff ≤ number of inputs + @test_throws ArgumentError tfest(d, 1e-4; uncertainty = Val(:analytic)) # too narrow lag window @test_throws ArgumentError tfest(d; uncertainty = Val(:bootstrap)) @test_throws ArgumentError coherence(d; method = :corr, uncertainty = Val(:jackknife)) @test_throws ArgumentError tfest(d; method = :welch, uncertainty = Val(:analytic), n = T) # a single window From 0888ea7e34432b9513eba5c849bfca0099bf0e3e Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 2 Dec 2026 19:13:41 +0000 Subject: [PATCH 6/6] Support vectors of data segments in coherenceplot coherenceplot accepts a vector of data segments and plots the Welch coherence pooled over the windows of all segments, one series per output, with the uncertainty band when `uncertainty` is passed. Co-Authored-By: Claude Opus 5.5 --- src/plotting.jl | 17 ++++++++++------- test/test_frd.jl | 6 ++++++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/plotting.jl b/src/plotting.jl index 7cafca4c..0f2b17b0 100644 --- a/src/plotting.jl +++ b/src/plotting.jl @@ -254,39 +254,42 @@ end @userplot Coherenceplot """ coherenceplot(d, [(;n=..., noverlap=...); hz=false) + coherenceplot(ds::AbstractVector{<:AbstractIdData}, [(;n=..., noverlap=...); hz=false) Calculates and plots the (squared) coherence Function κ. κ close to 1 indicates a good explainability of energy in the output signal by energy in the input signal. κ << 1 indicates that either the system is nonlinear, or a strong noise contributes to the output energy. `hz` indicates Hertz instead of rad/s -Keyword arguments to `coherence` are supplied as a named tuple as a second positional argument. If the named tuple contains `uncertainty = Val(true)`, a band of ± two jackknife standard deviations is drawn around the coherence. +If a vector of data segments `ds` is given, the Welch estimate pooled over the windows of all segments is plotted, see `coherence(ds::AbstractVector{<:AbstractIdData})`. + +Keyword arguments to `coherence` are supplied as a named tuple as a second positional argument. If the named tuple contains `uncertainty = Val(:analytic)` or `uncertainty = Val(:jackknife)`, a band of ± two estimated standard deviations is drawn around the coherence. """ coherenceplot @recipe function coherenceplot(p::Coherenceplot; hz = false) ae = - ArgumentError("Call like this: coherenceplot(iddata; hz=false)") + ArgumentError("Call like this: coherenceplot(iddata; hz=false) or coherenceplot([iddata1, iddata2, ...]; hz=false)") d = p.args[1] - d isa AbstractIdData || throw(ae) + d isa AbstractIdData || (d isa AbstractVector{<:AbstractIdData} && !isempty(d)) || throw(ae) + ny = d isa AbstractIdData ? d.ny : noutputs(d[1]) if length(p.args) >= 2 kwargs = p.args[2] else kwargs = NamedTuple() end - y, u, h = output(d), input(d), sampletime(d) yscale --> :identity xscale --> :log10 ylims --> (0, 1) xguide --> (hz ? "Frequency [Hz]" : "Frequency [rad/s]") title --> "Coherence" label --> false - for i = 1:d.ny - res = coherence(d[i,:]; kwargs...) + for i = 1:ny + res = coherence(d isa AbstractIdData ? d[i,:] : [di[i,:] for di in d]; kwargs...) frd, σ = res isa Tuple ? res : (res, nothing) @series begin inds = findall(x -> x == 0, frd.w) useinds = setdiff(1:length(frd.w), inds) - label --> (d.ny == 1 ? "" : "To y_$i") + label --> (ny == 1 ? "" : "To y_$i") σ === nothing || (ribbon --> 2 .* σ.r[useinds]) (hz ? 1 / (2π) : 1) .* frd.w[useinds], abs.(frd.r[useinds]) end diff --git a/test/test_frd.jl b/test/test_frd.jl index a6c246c0..410f8cb3 100644 --- a/test/test_frd.jl +++ b/test/test_frd.jl @@ -250,6 +250,12 @@ littlefrd = FRD([1, 2], [im, 2*im]) @test size(Hm.r) == (2, 1, length(Hs.w)) @test Hm.r[2, 1, :] ≈ Hs.r + # Plotting the pooled coherence + @test_nowarn coherenceplot(ds, kw) + @test_nowarn coherenceplot(ds, (; kw..., uncertainty = Val(:analytic))) + @test_nowarn coherenceplot(dsm, kw) # multiple outputs, one series per output + @test_throws ArgumentError coherenceplot(CSI.AbstractIdData[]) + # Errors @test_throws ArgumentError tfest(ds; method = :corr) @test_throws ArgumentError coherence(ds; method = :corr)