From 4e8f95385a18b8a00d2a1f97dca2545751e243d3 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 2 Dec 2026 21:21:45 +0000 Subject: [PATCH 1/2] Add delete-one-block jackknife uncertainty to subspaceid subspaceid(data, nx; uncertainty = Val(:jackknife), nblocks) returns the model together with a SubspaceJackknife object holding one estimate per left-out block of data matrix columns, transformed to the state basis of the full-data model through the extended observability matrix. jackknife_std, jackknife_cov and pole_std compute standard deviations and covariances from these replicates. Co-Authored-By: Claude Opus 5.5 --- docs/src/ss.md | 24 ++++ src/ControlSystemIdentification.jl | 1 + src/subspace2.jl | 181 ++++++++++++++++++++++++++--- test/test_subspace.jl | 82 +++++++++++++ 4 files changed, 271 insertions(+), 17 deletions(-) diff --git a/docs/src/ss.md b/docs/src/ss.md index ea64743a..bb0f4647 100644 --- a/docs/src/ss.md +++ b/docs/src/ss.md @@ -51,6 +51,26 @@ The subspace-based estimation algorithms have a number of parameters that can be - `zeroD` allows you to force the estimated ``D`` matrix to be zero (a strictly proper model). - It is possible to select the weight type `W`, choose between `:MOESP, :CVA, :N4SID, :IVM`. The default is `:MOESP`. +### Uncertainty estimates +With the keyword argument `uncertainty = Val(:jackknife)`, [`subspaceid`](@ref) additionally returns a [`SubspaceJackknife`](@ref) object. The data is partitioned into `nblocks` contiguous blocks, and the model is estimated once for each block with that block left out. The resulting models are transformed to the state basis of the full-data model, and [`jackknife_std`](@ref) computes the jackknife standard deviation of any quantity computed from a model. The example below computes the standard deviation of the magnitude of the frequency response and of the poles. +```@example ss +using LinearAlgebra +u2 = randn(1, 10000) +y2 = lsim(G, u2).y .+ 0.5 .* randn.() +d2 = iddata(y2, u2, Ts) +sysu, unc = subspaceid(d2, G.nx; zeroD = true, uncertainty = Val(:jackknife), nblocks = 10) +w = exp10.(range(-1, log10(pi/Ts), length = 300)) +mag = vec(abs.(freqresp(sysu, w))) +σmag = jackknife_std(s -> vec(abs.(freqresp(s, w))), unc) +plot(w, vec(abs.(freqresp(G, w))), lab = "True", xscale = :log10, yscale = :log10, xlabel = "Frequency [rad/s]", ylabel = "Magnitude") +plot!(w, mag, ribbon = (min.(2σmag, 0.99mag), 2σmag), lab = "subspace ± 2σ") +``` +```@example ss +[poles(sysu) pole_std(sysu, unc)] +``` +The jackknife covariance of the model parameters `[vec(A); vec(B); vec(C); vec(D); vec(K)]` is obtained with [`jackknife_cov`](@ref). + +The variance estimate assumes that the blocks are approximately independent. The blocks must therefore be long compared with the horizons `r`, `s1`, `s2` and with the time constants of the system and the noise model. When the distribution of the estimate is close to Gaussian, the jackknife standard deviation agrees with the standard deviation over independent noise realizations. When the amount of data is small relative to the noise level, the distribution of the subspace estimate has heavier tails than a Gaussian distribution and the jackknife standard deviation is larger than the standard deviation over noise realizations, typically by a factor of up to two. See the docstrings of [`subspaceid`](@ref) and [`n4sid`](@ref) for additional arguments and more details. @@ -196,6 +216,10 @@ Pages = ["ss.md"] ControlSystemIdentification.newpem ControlSystemIdentification.structured_pem ControlSystemIdentification.subspaceid +ControlSystemIdentification.SubspaceJackknife +ControlSystemIdentification.jackknife_std +ControlSystemIdentification.jackknife_cov +ControlSystemIdentification.pole_std ControlSystemIdentification.n4sid ControlSystemIdentification.era ControlSystemIdentification.okid diff --git a/src/ControlSystemIdentification.jl b/src/ControlSystemIdentification.jl index 2b38353c..f6ddd8b6 100644 --- a/src/ControlSystemIdentification.jl +++ b/src/ControlSystemIdentification.jl @@ -49,6 +49,7 @@ export AbstractPredictionStateSpace, PredictionStateSpace, N4SIDStateSpace, pem, newpem, structured_pem, prediction_error, prediction_error_filter, predictiondata, predict, simulate, noise_model, estimate_x0 export LPVStateSpace, lpv_pem, lpv_warmstart export n4sid, subspaceid, era, okid, find_similarity_transform, schur_stab +export SubspaceJackknife, jackknife_std, jackknife_cov, pole_std export getARXregressor, getARregressor, find_na, diff --git a/src/subspace2.jl b/src/subspace2.jl index bbf6251f..d97b14f3 100644 --- a/src/subspace2.jl +++ b/src/subspace2.jl @@ -1,5 +1,5 @@ -function find_BD(A,K,C,U,Y,m, zeroD=false, estimator=\, weights=nothing) +function find_BD(A,K,C,U,Y,m, zeroD=false, estimator=\, weights=nothing, keep=nothing) T = eltype(A) nx = size(A, 1) p = size(C, 1) @@ -42,10 +42,17 @@ function find_BD(A,K,C,U,Y,m, zeroD=false, estimator=\, weights=nothing) φ3 = zeroD ? cat(φB, φx0, dims=Val(3)) : cat(φB, φx0, φD, dims=Val(3)) # φ4 = permutedims(φ3, (1,3,2)) φ = reshape(φ3, p*N, :) + yv = vec(Y .- ε) + if keep !== nothing # regression over the retained time instants only, rows are ordered with the output index fastest + rows = repeat(keep, inner=p) + φ = φ[rows, :] + yv = yv[rows] + weights === nothing || (weights = weights[rows]) + end if weights === nothing - BD = estimator(φ, vec(Y .- ε)) + BD = estimator(φ, yv) else - BD = estimator(φ, vec(Y .- ε), weights) + BD = estimator(φ, yv, weights) end B = copy(reshape(BD[1:m*nx], nx, m)) x0 = BD[m*nx .+ (1:nx)] @@ -173,7 +180,10 @@ end Aestimator::F2 = \\, Bestimator::F3 = \\, weights = nothing, - ) + uncertainty = Val(false), + nblocks = 10, + ) + model, unc = subspaceid(data, nx; uncertainty = Val(:jackknife), kwargs...) Estimate a state-space model using subspace-based identification. Several different subspace-based algorithms are available, and can be chosen using the `W` keyword. Options are `:MOESP, :CVA, :N4SID, :IVM`. @@ -199,6 +209,19 @@ The returned model is of type `N4SIDStateSpace` and contains the field `sys` wit - `Aestimator`: Estimator function used to estimate `A,C`. The default is `\`, i.e., least squares, but robust estimators, such as `irls, flts, rtls` from [TotalLeastSquares.jl](https://github.com/baggepinnen/TotalLeastSquares.jl/), can be used to gain resistance against outliers. - `Bestimator`: Estimator function used to estimate `B,D`. Weighted estimation can be eachieved by passing `wls` from TotalLeastSquares.jl together with the `weights` keyword argument. - `weights`: A vector of weights can be provided if the `Bestimator` is `wls`. +- `uncertainty`: `Val(false)` (default) returns the model only. `Val(:jackknife)` (or `Val(true)`) additionally returns a [`SubspaceJackknife`](@ref) object containing the estimates obtained with one block of data left out at a time, see below. +- `nblocks`: The number of contiguous blocks of data used by the jackknife. + +# Uncertainty +With `uncertainty = Val(:jackknife)`, the data matrices are partitioned into `nblocks` contiguous blocks of time instants, and the model is estimated `nblocks` additional times with one block left out (delete-one-block jackknife). The model order of these estimates is the order of `model`, also when `nx = :auto`. Since a state-space realization is determined only up to a change of state basis, each estimate is transformed to the state basis of `model` using its extended observability matrix. The jackknife standard deviation of any quantity computed from the model is obtained with [`jackknife_std`](@ref), for example +```julia +model, unc = subspaceid(d, 4; uncertainty = Val(:jackknife)) +w = exp10.(range(-2, log10(pi), length = 200)) +σmag = jackknife_std(s -> vec(abs.(freqresp(s, w))), unc) # standard deviation of the magnitude of a SISO frequency response +σp = pole_std(model, unc) # standard deviation of the poles, ordered as poles(model) +Σθ = jackknife_cov(unc) # covariance of the model parameters +``` +The variance estimate assumes that the blocks are approximately independent, which requires blocks that are long compared with the horizons `r`, `s1`, `s2` and with the time constants of the system and the noise model. The quantity of interest is assumed to depend smoothly on the data. Eigenvalue reflection of unstable estimates of `A` and estimation of an order close to rank deficiency violate this assumption. The jackknife covariance of a parameter vector has rank at most `nblocks - 1`. # Extended help A more accurate prediciton model can sometimes be obtained using [`newpem`](@ref), which is also unbiased for closed-loop data (`subspaceid` is biased for closed-loop data, see example in the docs). The prediction-error method is iterative and generally more expensive than `subspaceid`, and uses this function (by default) to form the initial guess for the optimization. @@ -220,8 +243,11 @@ function subspaceid( Aestimator::F2 = \, Bestimator::F3 = \, weights = nothing, -) where {F1,F2,F3} + uncertainty::Val{UM} = Val(false), + nblocks::Integer = 10, +) where {F1,F2,F3,UM} + UM === false || UM === true || UM === :jackknife || throw(ArgumentError("Unknown uncertainty method $(repr(UM)), choose Val(false) or Val(:jackknife)")) nx !== :auto && r < nx && throw(ArgumentError("r must be at least nx")) y, u = copy(time1(output(data))), copy(time1(input(data))) if scaleU @@ -260,6 +286,135 @@ function subspaceid( Φ = reduce(hcat, [φs(t) for t ∈ t0:t0+N-1]) # 10.108. Note, t can not start at 1 as in the book since that would access invalid indices for u/y. At time t=t0, φs(t0-1) is the first "past" value @assert size(Φ) == (s, N) + if UM !== false + blocks = jackknife_blocks(N, nblocks, r, s1, s2, size(U, 1) + size(Φ, 1) + size(Y, 1)) + end + est = subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd, Aestimator, verbose) + (; A, C, K, n) = est + + # 4. Estimate B, D, x0 by linear regression + B,D,x0 = find_BD(A, (focus === :prediction)*K, C, transpose(u), transpose(y), m, zeroD, Bestimator, weights) + # TODO: iterate find C/D and find B/D a couple of times + + if scaleU + B ./= CU + D ./= CU + end + sys = N4SIDStateSpace(ss(A, B, C, D, data.Ts), est.Q, est.R, est.S, K, est.P, x0, est.sv, est.fve) + UM === false && return sys + + Or = est.Or[:, 1:n] + replicates = map(blocks) do blk + keepcols = trues(N) + keepcols[blk] .= false + e = subspace_core(U[:, keepcols], Φ[:, keepcols], Y[:, keepcols], n, p, m, r, s1, s2, W, svd, Aestimator, false) + keepsamples = trues(t) + keepsamples[blk .+ (t0 - 1)] .= false + Bb, Db, _ = find_BD(e.A, (focus === :prediction)*e.K, e.C, transpose(u), transpose(y), m, zeroD, Bestimator, weights, keepsamples) + if scaleU + Bb ./= CU + Db ./= CU + end + T = e.Or[:, 1:n] \ Or # change of basis to the state basis of the full-data estimate + Ti = inv(T) + PredictionStateSpace(ss(Ti*e.A*T, Ti*Bb, e.C*T, Db, data.Ts), Ti*e.K, Ti*e.Q*Ti', e.R, Ti*e.S) + end + sys, SubspaceJackknife(replicates, [blk .+ (t0 - 1) for blk in blocks]) +end + +""" + SubspaceJackknife + +Delete-one-block jackknife estimates returned by [`subspaceid`](@ref) with `uncertainty = Val(:jackknife)`. + +# Fields: +- `replicates`: One [`PredictionStateSpace`](@ref) per block, estimated with that block of data left out and expressed in the state basis of the full-data model. +- `blocks`: The sample indices of the data matrices' columns that were left out for each replicate. A column at sample index `t` contains the outputs and inputs at times `t, …, t+r-1` and the past data at times `t-max(s1,s2), …, t-1`. + +See [`jackknife_std`](@ref), [`jackknife_cov`](@ref) and [`pole_std`](@ref). +""" +struct SubspaceJackknife{RT} + replicates::Vector{RT} + blocks::Vector{UnitRange{Int}} +end + +function Base.show(io::IO, unc::SubspaceJackknife) + print(io, "SubspaceJackknife with $(length(unc.replicates)) replicates") +end + +""" + σ = jackknife_std(f, unc::SubspaceJackknife) + +Jackknife standard deviation of `f(model)`, where `f` maps a state-space model to a number or an array of numbers, for example a frequency response, a step response or a gain. `f` is applied to each replicate in `unc.replicates`, and +```math +σ^2 = \\frac{K-1}{K} \\sum_{k=1}^{K} |f_k - \\bar f|^2 +``` +elementwise, where ``K`` is the number of replicates and ``\\bar f`` their mean. For complex values, ``σ^2`` is the sum of the variances of the real and imaginary parts. Quantities that depend on the state basis, such as individual entries of `A`, are expressed in the state basis of the full-data model. +""" +function jackknife_std(f, unc::SubspaceJackknife) + vals = map(f, unc.replicates) + K = length(vals) + μ = sum(vals) / K + sqrt.((K - 1) / K .* sum(v -> abs2.(v .- μ), vals)) +end + +""" + Σ = jackknife_cov(unc::SubspaceJackknife) + Σ = jackknife_cov(f, unc::SubspaceJackknife) + +Jackknife covariance matrix of the real vector `f(model)`. The default `f` returns the parameter vector `[vec(A); vec(B); vec(C); vec(D); vec(K)]` in the state basis of the full-data model. The rank of `Σ` is at most the number of replicates minus one. +""" +function jackknife_cov(f, unc::SubspaceJackknife) + vals = map(f, unc.replicates) + K = length(vals) + μ = sum(vals) / K + (K - 1) / K * sum(v -> (v - μ) * (v - μ)', vals) +end +jackknife_cov(unc::SubspaceJackknife) = jackknife_cov(statespace_parameters, unc) + +statespace_parameters(sys) = [vec(sys.A); vec(sys.B); vec(sys.C); vec(sys.D); vec(sys.K)] + +""" + σ = pole_std(model, unc::SubspaceJackknife) + +Jackknife standard deviation of the poles of `model`, ordered as `poles(model)`. The poles of each replicate are assigned to the poles of `model` in order of increasing distance. For a complex pole, `σ` is the square root of the sum of the variances of the real and imaginary parts. +""" +function pole_std(model, unc::SubspaceJackknife) + p0 = complex.(poles(model)) + jackknife_std(s -> match_poles(complex.(poles(s)), p0), unc) +end + +function match_poles(p, p0) + n = length(p0) + dist = abs.(p0 .- transpose(p)) + out = similar(p, n) + for _ in 1:n + i, j = Tuple(argmin(dist)) + out[i] = p[j] + dist[i, :] .= Inf + dist[:, j] .= Inf + end + out +end + +function jackknife_blocks(N, nblocks, r, s1, s2, nrows) + nblocks ≥ 2 || throw(ArgumentError("The jackknife requires at least two blocks, got nblocks = $nblocks.")) + edges = round.(Int, range(0, N, length = nblocks + 1)) + blocks = [edges[i]+1:edges[i+1] for i in 1:nblocks] + span = r + max(s1, s2) + minimum(length, blocks) ≥ span || throw(ArgumentError("The $nblocks jackknife blocks contain $(minimum(length, blocks)) time instants each, fewer than the span r + max(s1, s2) = $span of one column of the data matrices. Use fewer blocks (nblocks), shorter horizons (r, s1, s2) or more data.")) + N - maximum(length, blocks) ≥ nrows || throw(ArgumentError("After leaving out one jackknife block, $(N - maximum(length, blocks)) time instants remain, fewer than the $nrows rows of the data matrices. Use more blocks (nblocks), shorter horizons (r, s1, s2) or more data.")) + blocks +end + +""" + subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd, Aestimator, verbose) + +Estimate `A`, `C`, the extended observability matrix `Or` and the Kalman-filter quantities from the data matrices of [`subspaceid`](@ref). The columns of `U`, `Φ` and `Y` correspond to time instants, so that a subset of the columns gives the estimate from a subset of the data. +""" +function subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd::F1, Aestimator::F2, verbose) where {F1,F2} + N = size(Y, 2) + s = size(Φ, 1) UΦY = [U; Φ; Y] l = lq!(UΦY) L = l.L @@ -343,16 +498,6 @@ function subspaceid( end P, K, Qc, Rc, Sc = find_PK(L1,L2,Or,n,p,m,r,s1,s2,A,C) - - # 4. Estimate B, D, x0 by linear regression - B,D,x0 = find_BD(A, (focus === :prediction)*K, C, transpose(u), transpose(y), m, zeroD, Bestimator, weights) - # TODO: iterate find C/D and find B/D a couple of times - - if scaleU - B ./= CU - D ./= CU - end - # 5. If noise model, form Xh from (10.123) and estimate noise contributions using (10.124) # Yh,Xh = let # # if W === :N4SID @@ -375,8 +520,8 @@ function subspaceid( # AB = Xh[:, 2:end]/[Xh[:, 1:end-1]; U[1:m, 1:end-1]] # A2 = AB[1:n, 1:n] # B2 = AB[1:n, n+1:end] - - N4SIDStateSpace(ss(A, B, C, D, data.Ts), Qc,Rc,Sc,K,P,x0,sv,fve) + + (; A, C, K, P, Q=Qc, R=Rc, S=Sc, Or, sv, fve, n) end """ @@ -449,8 +594,10 @@ function subspaceid( Aestimator::F2 = \, Bestimator::F3 = \, weights = nothing, + uncertainty::Val = Val(false), ) where {F1,F2,F3} + uncertainty === Val(false) || throw(ArgumentError("Uncertainty estimation is supported for time-domain data only.")) verbose && @info "Estimating with r = $r and stability constraint = $stable" w = data.w Ts ≤ 2π/maximum(w) || error("Highest frequency ($(maximum(w))) is larger that the Nyquist frequency for sample time Ts = $Ts") diff --git a/test/test_subspace.jl b/test/test_subspace.jl index ef0bdb14..7f078ba7 100644 --- a/test/test_subspace.jl +++ b/test/test_subspace.jl @@ -438,3 +438,85 @@ Modal form of the estimated system gets one pole in 1, and the B and C matrix en The disturbance state is observable but not controllable =# end + +@testset "subspaceid jackknife uncertainty" begin + @info "Testing subspaceid jackknife uncertainty" + Ts = 0.1 + G = c2d(tf(1, [1, 0.4, 1]) * tf(1, [1, 1]), Ts) |> ss + w = exp10.(range(-1, log10(0.9pi/Ts), length = 6)) + N = 3000 + rng = MersenneTwister(1) + u = randn(rng, 1, N) + y = lsim(G, u).y .+ 0.05 .* randn(rng, 1, N) + d = iddata(y, u, Ts) + + sys0 = subspaceid(d, 3) + @test sys0 isa N4SIDStateSpace + sys, unc = subspaceid(d, 3; uncertainty = Val(:jackknife), nblocks = 8) + @test sys.A == sys0.A && sys.B == sys0.B && sys.C == sys0.C && sys.D == sys0.D && sys.K == sys0.K + @test unc isa SubspaceJackknife + @test length(unc.replicates) == length(unc.blocks) == 8 + @test all(isdisjoint(unc.blocks[i], unc.blocks[i+1]) && last(unc.blocks[i]) + 1 == first(unc.blocks[i+1]) for i in 1:7) + # Replicates are expressed in the state basis of the full-data model + @test all(norm(r.A - sys.A) < 0.1norm(sys.A) for r in unc.replicates) + @test all(norm(r.C - sys.C) < 0.1norm(sys.C) for r in unc.replicates) + @test all(r.nx == 3 for r in unc.replicates) + + _, unct = subspaceid(d, 3; uncertainty = Val(true), nblocks = 8) + @test all(r1.A == r2.A for (r1, r2) in zip(unc.replicates, unct.replicates)) + + σ = jackknife_std(s -> vec(freqresp(s, w)), unc) + @test size(σ) == (length(w),) && all(σ .> 0) + @test jackknife_std(s -> dcgain(s)[], unc) isa Real + σp = pole_std(sys, unc) + @test length(σp) == 3 && all(isfinite, σp) && all(σp .> 0) + Σ = jackknife_cov(unc) + np = 3*3 + 3 + 3 + 1 + 3 + @test size(Σ) == (np, np) && Σ ≈ Σ' && rank(Σ) ≤ 7 && minimum(eigvals(Symmetric(Σ))) > -1e-10 + @test diag(jackknife_cov(s -> vec(s.A), unc)) ≈ vec(jackknife_std(s -> s.A, unc)).^2 + + # Order selected automatically is used for all replicates + sysa, unca = subspaceid(d; uncertainty = Val(:jackknife), nblocks = 4) + @test all(r.nx == sysa.nx for r in unca.replicates) + + # Other options + for kw in ((; W = :CVA), (; W = :IVM), (; W = :N4SID), (; zeroD = true), (; focus = :simulation), (; scaleU = false)) + s, un = subspaceid(d, 3; uncertainty = Val(:jackknife), nblocks = 5, kw...) + @test all(isfinite, jackknife_std(s -> vec(freqresp(s, w)), un)) + @test all(norm(r.A - s.A) < 0.2norm(s.A) for r in un.replicates) + end + # Uniform weights give the same estimates as no weights + wls_test(A, y, w) = (Diagonal(sqrt.(w)) * A) \ (Diagonal(sqrt.(w)) * y) + _, unw = subspaceid(d, 3; uncertainty = Val(:jackknife), nblocks = 5, Bestimator = wls_test, weights = ones(N)) + _, un1 = subspaceid(d, 3; uncertainty = Val(:jackknife), nblocks = 5) + @test all(r1.B ≈ r2.B for (r1, r2) in zip(unw.replicates, un1.replicates)) + + # Multiple inputs and outputs + G2 = ssrand(2, 2, 3, Ts = Ts, proper = true, stable = true) + u2 = randn(rng, 2, N) + d2 = iddata(lsim(G2, u2).y .+ 0.05 .* randn(rng, 2, N), u2, Ts) + s2, un2 = subspaceid(d2, 3; uncertainty = Val(:jackknife), nblocks = 6) + @test size(jackknife_std(s -> freqresp(s, w), un2)) == (2, 2, length(w)) + @test size(jackknife_cov(un2), 1) == 9 + 6 + 6 + 4 + 6 + + # Errors + @test_throws ArgumentError subspaceid(d, 3; uncertainty = Val(:bootstrap)) + @test_throws ArgumentError subspaceid(d, 3; uncertainty = Val(:jackknife), nblocks = 1) + @test_throws ArgumentError subspaceid(d, 3; uncertainty = Val(:jackknife), nblocks = 200) + @test_throws ArgumentError subspaceid(d[1:150], 3; uncertainty = Val(:jackknife), nblocks = 2) + df = iddata(rand(ComplexF64, 1, 50), rand(ComplexF64, 1, 50), range(0, pi/Ts, length = 50)) + @test_throws ArgumentError subspaceid(df, Ts, 3; uncertainty = Val(:jackknife)) + + # Monte Carlo calibration: jackknife standard deviation compared with the standard deviation over noise realizations for a fixed input + M = 100 + res = map(1:M) do i + r = MersenneTwister(100 + i) + di = iddata(lsim(G, u).y .+ 0.02 .* randn(r, 1, N), u, Ts) + si, ui = subspaceid(di, 3; uncertainty = Val(:jackknife), nblocks = 10) + f(s) = vec(real.(freqresp(s, w))) + f(si), jackknife_std(f, ui) + end + emp = vec(std(reduce(hcat, first.(res)), dims = 2)) + pred = vec(sqrt.(mean(abs2, reduce(hcat, last.(res)), dims = 2))) + @test all(0.7 .< pred ./ emp .< 1.6) +end From b119dd71bda0de79910764bf967ceaa086de8073 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 2 Dec 2026 21:45:48 +0000 Subject: [PATCH 2/2] Address review findings for the subspaceid jackknife - Normalize the residual covariance in find_PK by the number of data matrix columns; Q, R, S and P previously grew linearly with the record length. - Honor stable = false (eigenvalue reflection was applied unconditionally). - Assign the samples before the first and after the last Hankel column to the first and last block, so that the blocks partition the record. - Detect replicates whose observable subspace differs from the full-data model (smallest principal-angle cosine below 0.5), keep them in their own basis, warn, and record this in SubspaceJackknife.aligned; jackknife_cov(unc) throws in that case. - Support covariance-type weight matrices in the B/D regression. - Match poles by minimum total distance (Hungarian algorithm). - State the observed calibration in the documentation. Co-Authored-By: Claude Opus 5.5 --- docs/src/ss.md | 2 +- src/subspace2.jl | 142 +++++++++++++++++++++++++++++++++--------- test/test_subspace.jl | 41 ++++++++++++ 3 files changed, 153 insertions(+), 32 deletions(-) diff --git a/docs/src/ss.md b/docs/src/ss.md index bb0f4647..c4f246e6 100644 --- a/docs/src/ss.md +++ b/docs/src/ss.md @@ -70,7 +70,7 @@ plot!(w, mag, ribbon = (min.(2σmag, 0.99mag), 2σmag), lab = "subspace ± 2σ") ``` The jackknife covariance of the model parameters `[vec(A); vec(B); vec(C); vec(D); vec(K)]` is obtained with [`jackknife_cov`](@ref). -The variance estimate assumes that the blocks are approximately independent. The blocks must therefore be long compared with the horizons `r`, `s1`, `s2` and with the time constants of the system and the noise model. When the distribution of the estimate is close to Gaussian, the jackknife standard deviation agrees with the standard deviation over independent noise realizations. When the amount of data is small relative to the noise level, the distribution of the subspace estimate has heavier tails than a Gaussian distribution and the jackknife standard deviation is larger than the standard deviation over noise realizations, typically by a factor of up to two. +The variance estimate assumes that the blocks are approximately independent. The blocks must therefore be long compared with the horizons `r`, `s1`, `s2` and with the time constants of the system and the noise model. The accuracy of the jackknife variance is not guaranteed. In Monte Carlo experiments with a third-order system, a fixed white-noise input and independent white measurement noise, the root-mean-square jackknife standard deviation of the frequency response and of the poles was 0.9–1.25 times the standard deviation over noise realizations with 8000 samples. With 2000 samples and a lower signal-to-noise ratio, the distribution of the estimate had heavier tails than a Gaussian distribution, and the jackknife standard deviation of the frequency response was up to 1.9 times, and that of a weakly determined real pole up to 4 times, the standard deviation over noise realizations. See the docstrings of [`subspaceid`](@ref) and [`n4sid`](@ref) for additional arguments and more details. diff --git a/src/subspace2.jl b/src/subspace2.jl index d97b14f3..8b72d69c 100644 --- a/src/subspace2.jl +++ b/src/subspace2.jl @@ -47,7 +47,11 @@ function find_BD(A,K,C,U,Y,m, zeroD=false, estimator=\, weights=nothing, keep=no rows = repeat(keep, inner=p) φ = φ[rows, :] yv = yv[rows] - weights === nothing || (weights = weights[rows]) + if weights isa AbstractMatrix # covariance-type weights, retain the principal submatrix + weights = weights[rows, rows] + elseif weights !== nothing + weights = weights[rows] + end end if weights === nothing BD = estimator(φ, yv) @@ -213,7 +217,7 @@ The returned model is of type `N4SIDStateSpace` and contains the field `sys` wit - `nblocks`: The number of contiguous blocks of data used by the jackknife. # Uncertainty -With `uncertainty = Val(:jackknife)`, the data matrices are partitioned into `nblocks` contiguous blocks of time instants, and the model is estimated `nblocks` additional times with one block left out (delete-one-block jackknife). The model order of these estimates is the order of `model`, also when `nx = :auto`. Since a state-space realization is determined only up to a change of state basis, each estimate is transformed to the state basis of `model` using its extended observability matrix. The jackknife standard deviation of any quantity computed from the model is obtained with [`jackknife_std`](@ref), for example +With `uncertainty = Val(:jackknife)`, the record is partitioned into `nblocks` contiguous blocks of time instants, and the model is estimated `nblocks` additional times with one block left out (delete-one-block jackknife). Leaving out a block removes the columns of the data matrices that start in the block, and the samples in the block from the regression for `B` and `D`. With `focus = :prediction`, the outputs in a left-out block still enter the predictor that forms the regressors of later samples. The model order of these estimates is the order of `model`, also when `nx = :auto`. Since a state-space realization is determined only up to a change of state basis, each estimate is transformed to the state basis of `model` using its extended observability matrix. The jackknife standard deviation of any quantity computed from the model is obtained with [`jackknife_std`](@ref), for example ```julia model, unc = subspaceid(d, 4; uncertainty = Val(:jackknife)) w = exp10.(range(-2, log10(pi), length = 200)) @@ -221,7 +225,7 @@ w = exp10.(range(-2, log10(pi), length = 200)) σp = pole_std(model, unc) # standard deviation of the poles, ordered as poles(model) Σθ = jackknife_cov(unc) # covariance of the model parameters ``` -The variance estimate assumes that the blocks are approximately independent, which requires blocks that are long compared with the horizons `r`, `s1`, `s2` and with the time constants of the system and the noise model. The quantity of interest is assumed to depend smoothly on the data. Eigenvalue reflection of unstable estimates of `A` and estimation of an order close to rank deficiency violate this assumption. The jackknife covariance of a parameter vector has rank at most `nblocks - 1`. +The variance estimate assumes that the blocks are approximately independent, which requires blocks that are long compared with the horizons `r`, `s1`, `s2` and with the time constants of the system and the noise model. The quantity of interest is assumed to depend smoothly on the data. This assumption is violated when an eigenvalue of the estimated `A` crosses the unit circle with `stable = true` (eigenvalue reflection), and when the model order is close to the number of modes that the data determines, in which case the observable subspaces of the replicates may differ (see `unc.aligned`). The jackknife variance is an approximation whose accuracy is not guaranteed; in simulation studies it was both close to and larger than the variance over noise realizations, see the documentation. The jackknife covariance of a parameter vector has rank at most `nblocks - 1`. # Extended help A more accurate prediciton model can sometimes be obtained using [`newpem`](@ref), which is also unbiased for closed-loop data (`subspaceid` is biased for closed-loop data, see example in the docs). The prediction-error method is iterative and generally more expensive than `subspaceid`, and uses this function (by default) to form the initial guess for the optimization. @@ -289,7 +293,7 @@ function subspaceid( if UM !== false blocks = jackknife_blocks(N, nblocks, r, s1, s2, size(U, 1) + size(Φ, 1) + size(Y, 1)) end - est = subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd, Aestimator, verbose) + est = subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd, Aestimator, stable, verbose) (; A, C, K, n) = est # 4. Estimate B, D, x0 by linear regression @@ -304,22 +308,43 @@ function subspaceid( UM === false && return sys Or = est.Or[:, 1:n] - replicates = map(blocks) do blk + # The regression for B, D uses all samples 1:t, the samples before the first and after the last Hankel column start are assigned to the first and last block + sampleblocks = [blk .+ (t0 - 1) for blk in blocks] + sampleblocks[1] = 1:last(sampleblocks[1]) + sampleblocks[end] = first(sampleblocks[end]):t + results = map(blocks, sampleblocks) do blk, sblk keepcols = trues(N) keepcols[blk] .= false - e = subspace_core(U[:, keepcols], Φ[:, keepcols], Y[:, keepcols], n, p, m, r, s1, s2, W, svd, Aestimator, false) + e = subspace_core(U[:, keepcols], Φ[:, keepcols], Y[:, keepcols], n, p, m, r, s1, s2, W, svd, Aestimator, stable, false) keepsamples = trues(t) - keepsamples[blk .+ (t0 - 1)] .= false + keepsamples[sblk] .= false Bb, Db, _ = find_BD(e.A, (focus === :prediction)*e.K, e.C, transpose(u), transpose(y), m, zeroD, Bestimator, weights, keepsamples) if scaleU Bb ./= CU Db ./= CU end - T = e.Or[:, 1:n] \ Or # change of basis to the state basis of the full-data estimate - Ti = inv(T) - PredictionStateSpace(ss(Ti*e.A*T, Ti*Bb, e.C*T, Db, data.Ts), Ti*e.K, Ti*e.Q*Ti', e.R, Ti*e.S) + Orb = e.Or[:, 1:n] + aligned = subspace_cosine(Orb, Or) ≥ 0.5 + if aligned + T = Orb \ Or # change of basis to the state basis of the full-data estimate + Ti = inv(T) + rep = PredictionStateSpace(ss(Ti*e.A*T, Ti*Bb, e.C*T, Db, data.Ts), Ti*e.K, Ti*e.Q*Ti', e.R, Ti*e.S) + else + rep = PredictionStateSpace(ss(e.A, Bb, e.C, Db, data.Ts), e.K, Matrix(e.Q), e.R, e.S) + end + rep, aligned end - sys, SubspaceJackknife(replicates, [blk .+ (t0 - 1) for blk in blocks]) + aligned = collect(Bool, last.(results)) + all(aligned) || @warn "The observable subspace of $(count(!, aligned)) of $(length(aligned)) jackknife replicates differs substantially from that of the full-data model. These replicates are not transformed to the state basis of the full-data model, and quantities that depend on the state basis (jackknife_cov(unc), entries of A, B, C, K) are not meaningful. A lower model order or more data may be required." + sys, SubspaceJackknife(first.(results), sampleblocks, aligned) +end + +# Smallest cosine of the principal angles between the column spaces of X and Y +function subspace_cosine(X, Y) + n = size(X, 2) + QX = Matrix(qr(X).Q)[:, 1:n] + QY = Matrix(qr(Y).Q)[:, 1:n] + minimum(svdvals(QX' * QY)) end """ @@ -329,13 +354,15 @@ Delete-one-block jackknife estimates returned by [`subspaceid`](@ref) with `unce # Fields: - `replicates`: One [`PredictionStateSpace`](@ref) per block, estimated with that block of data left out and expressed in the state basis of the full-data model. -- `blocks`: The sample indices of the data matrices' columns that were left out for each replicate. A column at sample index `t` contains the outputs and inputs at times `t, …, t+r-1` and the past data at times `t-max(s1,s2), …, t-1`. +- `blocks`: The sample indices left out for each replicate. They partition the record. The columns of the data matrices whose first future sample lies in a block are left out of the estimation of `A`, `C` and `K`, and the samples in the block are left out of the regression for `B` and `D`. A column with first future sample `t` contains the outputs and inputs at times `t, …, t+r-1` and the past data at times `t-max(s1,s2), …, t-1`, so samples near the boundaries of a block also enter retained columns. +- `aligned`: `aligned[k]` is `true` if replicate `k` is expressed in the state basis of the full-data model. A replicate is not transformed if the smallest cosine of the principal angles between its estimated observable subspace and that of the full-data model is below 0.5, in which case it is expressed in its own state basis. See [`jackknife_std`](@ref), [`jackknife_cov`](@ref) and [`pole_std`](@ref). """ struct SubspaceJackknife{RT} replicates::Vector{RT} blocks::Vector{UnitRange{Int}} + aligned::Vector{Bool} end function Base.show(io::IO, unc::SubspaceJackknife) @@ -349,7 +376,7 @@ Jackknife standard deviation of `f(model)`, where `f` maps a state-space model t ```math σ^2 = \\frac{K-1}{K} \\sum_{k=1}^{K} |f_k - \\bar f|^2 ``` -elementwise, where ``K`` is the number of replicates and ``\\bar f`` their mean. For complex values, ``σ^2`` is the sum of the variances of the real and imaginary parts. Quantities that depend on the state basis, such as individual entries of `A`, are expressed in the state basis of the full-data model. +elementwise, where ``K`` is the number of replicates and ``\\bar f`` their mean. For complex values, ``σ^2`` is the sum of the variances of the real and imaginary parts. Quantities that depend on the state basis, such as individual entries of `A`, are expressed in the state basis of the full-data model, provided that `all(unc.aligned)`. The scaling assumes blocks of equal length; the block lengths differ by at most one sample. """ function jackknife_std(f, unc::SubspaceJackknife) vals = map(f, unc.replicates) @@ -370,14 +397,17 @@ function jackknife_cov(f, unc::SubspaceJackknife) μ = sum(vals) / K (K - 1) / K * sum(v -> (v - μ) * (v - μ)', vals) end -jackknife_cov(unc::SubspaceJackknife) = jackknife_cov(statespace_parameters, unc) +function jackknife_cov(unc::SubspaceJackknife) + all(unc.aligned) || throw(ArgumentError("Not all jackknife replicates are expressed in the state basis of the full-data model (see unc.aligned), so the parameter covariance is not defined.")) + jackknife_cov(statespace_parameters, unc) +end statespace_parameters(sys) = [vec(sys.A); vec(sys.B); vec(sys.C); vec(sys.D); vec(sys.K)] """ σ = pole_std(model, unc::SubspaceJackknife) -Jackknife standard deviation of the poles of `model`, ordered as `poles(model)`. The poles of each replicate are assigned to the poles of `model` in order of increasing distance. For a complex pole, `σ` is the square root of the sum of the variances of the real and imaginary parts. +Jackknife standard deviation of the poles of `model`, ordered as `poles(model)`. The poles of each replicate are assigned to the poles of `model` by the assignment that minimizes the sum of the distances. For a complex pole, `σ` is the square root of the sum of the variances of the real and imaginary parts. For repeated poles, or poles whose distance is comparable to their standard deviation, the assignment is ambiguous and the result is not reliable. """ function pole_std(model, unc::SubspaceJackknife) p0 = complex.(poles(model)) @@ -385,16 +415,66 @@ function pole_std(model, unc::SubspaceJackknife) end function match_poles(p, p0) - n = length(p0) - dist = abs.(p0 .- transpose(p)) - out = similar(p, n) - for _ in 1:n - i, j = Tuple(argmin(dist)) - out[i] = p[j] - dist[i, :] .= Inf - dist[:, j] .= Inf - end - out + assignment = min_cost_assignment(abs.(p0 .- transpose(p))) + p[assignment] +end + +""" + assignment = min_cost_assignment(cost) + +Solve the linear assignment problem for the square matrix `cost` with the Hungarian algorithm, row `i` is assigned to column `assignment[i]`. +""" +function min_cost_assignment(cost::AbstractMatrix{T}) where T + n = size(cost, 1) + size(cost, 2) == n || throw(ArgumentError("The cost matrix must be square")) + u = zeros(T, n + 1) + v = zeros(T, n + 1) + match = zeros(Int, n + 1) # match[j] is the row assigned to column j, index n+1 is an auxiliary column + way = zeros(Int, n + 1) + for i in 1:n + match[n+1] = i + j0 = n + 1 + minv = fill(typemax(T), n + 1) + used = falses(n + 1) + while true + used[j0] = true + i0 = match[j0] + δ = typemax(T) + j1 = 0 + for j in 1:n + used[j] && continue + c = cost[i0, j] - u[i0] - v[j] + if c < minv[j] + minv[j] = c + way[j] = j0 + end + if minv[j] < δ + δ = minv[j] + j1 = j + end + end + for j in 1:n+1 + if used[j] + u[match[j]] += δ + v[j] -= δ + else + minv[j] -= δ + end + end + j0 = j1 + match[j0] == 0 && break + end + while j0 != n + 1 + j1 = way[j0] + match[j0] = match[j1] + j0 = j1 + end + end + assignment = zeros(Int, n) + for j in 1:n + assignment[match[j]] = j + end + assignment end function jackknife_blocks(N, nblocks, r, s1, s2, nrows) @@ -408,11 +488,11 @@ function jackknife_blocks(N, nblocks, r, s1, s2, nrows) end """ - subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd, Aestimator, verbose) + subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd, Aestimator, stable, verbose) Estimate `A`, `C`, the extended observability matrix `Or` and the Kalman-filter quantities from the data matrices of [`subspaceid`](@ref). The columns of `U`, `Φ` and `Y` correspond to time instants, so that a subset of the columns gives the estimate from a subset of the data. """ -function subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd::F1, Aestimator::F2, verbose) where {F1,F2} +function subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd::F1, Aestimator::F2, stable, verbose) where {F1,F2} N = size(Y, 2) s = size(Φ, 1) UΦY = [U; Φ; Y] @@ -492,12 +572,12 @@ function subspace_core(U, Φ, Y, nx, p, m, r, s1, s2, W, svd::F1, Aestimator::F2 C = Or[1:p, 1:n] A = Aestimator(Or[1:p*(r-1), 1:n] , Or[p+1:p*r, 1:n]) - if !all(e->abs(e)<=1, eigvals(A)) + if stable && !all(e->abs(e)<=1, eigvals(A)) verbose && @info "A matrix unstable, stabilizing by reflection" A = reflectd(A) end - P, K, Qc, Rc, Sc = find_PK(L1,L2,Or,n,p,m,r,s1,s2,A,C) + P, K, Qc, Rc, Sc = find_PK(L1,L2,Or,n,p,m,r,s1,s2,A,C,N) # 5. If noise model, form Xh from (10.123) and estimate noise contributions using (10.124) # Yh,Xh = let # # if W === :N4SID @@ -668,7 +748,7 @@ function subspaceid( end -function find_PK(L1,L2,Or,n,p,m,r,s1,s2,A,C) +function find_PK(L1,L2,Or,n,p,m,r,s1,s2,A,C,N) X1 = L2[p+1:r*p, 1:m*(s2+r)+p*s1+p] X2 = [L2[1:r*p,1:m*(s2+r)+p*s1] zeros(r*p,p)] vl = [Or[1:(r-1)*p, 1:n]\X1; L2[1:p, 1:m*(s2+r)+p*s1+p]] @@ -676,7 +756,7 @@ function find_PK(L1,L2,Or,n,p,m,r,s1,s2,A,C) K0 = vl*pinv(hl) W = (vl - K0*hl)*(vl-K0*hl)' - W ./= (length(vl) - length(K0)) + W ./= N # the residual cross product sums over the N columns of the data matrices Q = W[1:n,1:n] |> Hermitian S = W[1:n,n+1:n+p] diff --git a/test/test_subspace.jl b/test/test_subspace.jl index 7f078ba7..674e3e04 100644 --- a/test/test_subspace.jl +++ b/test/test_subspace.jl @@ -461,6 +461,11 @@ end @test all(norm(r.A - sys.A) < 0.1norm(sys.A) for r in unc.replicates) @test all(norm(r.C - sys.C) < 0.1norm(sys.C) for r in unc.replicates) @test all(r.nx == 3 for r in unc.replicates) + @test all(unc.aligned) + @test reduce(vcat, collect.(unc.blocks)) == 1:N # the blocks partition the record + # Noise covariances do not scale with the amount of data + @test 0.5 < sys.R[] / 0.05^2 < 2 + @test all(0.8 < r.R[] / sys.R[] < 1.25 for r in unc.replicates) _, unct = subspaceid(d, 3; uncertainty = Val(true), nblocks = 8) @test all(r1.A == r2.A for (r1, r2) in zip(unc.replicates, unct.replicates)) @@ -490,6 +495,42 @@ end _, unw = subspaceid(d, 3; uncertainty = Val(:jackknife), nblocks = 5, Bestimator = wls_test, weights = ones(N)) _, un1 = subspaceid(d, 3; uncertainty = Val(:jackknife), nblocks = 5) @test all(r1.B ≈ r2.B for (r1, r2) in zip(unw.replicates, un1.replicates)) + wls_mat(A, y, Wm) = (size(Wm) == (length(y), length(y)) || error("weight size"); (sqrt(Wm) * A) \ (sqrt(Wm) * y)) # weight matrix + _, unm = subspaceid(d, 3; uncertainty = Val(:jackknife), nblocks = 5, Bestimator = wls_mat, weights = Diagonal(ones(N))) + @test all(r1.B ≈ r2.B for (r1, r2) in zip(unm.replicates, un1.replicates)) + + # stable = false disables eigenvalue reflection + sun = subspaceid(d, 1; stable = false, Aestimator = (X, Y) -> fill(1.25, 1, 1)) + @test sun.A[] ≈ 1.25 + @test subspaceid(d, 1; Aestimator = (X, Y) -> fill(1.25, 1, 1)).A[] ≈ 0.8 + + # Pole matching minimizes the total distance + @test ControlSystemIdentification.match_poles(ComplexF64[0.26, 0.4], ComplexF64[0.2, 0.3]) == [0.26, 0.4] + for _ in 1:20 + c = rand(rng, 5, 5) + a = ControlSystemIdentification.min_cost_assignment(c) + @test sort(a) == 1:5 + best = minimum(sum(c[i, q[i]] for i in 1:5) for q in Iterators.product(ntuple(_ -> 1:5, 5)...) if allunique(q)) + @test sum(c[i, a[i]] for i in 1:5) ≈ best + end + + # Replicates whose observable subspace differs from that of the full-data model are detected + let rng = MersenneTwister(215) + ua = zeros(2, 308); ya = zeros(2, 308) + for block in 1:3, ch in 1:2 + ts = (100(block-1) + 8 + 46(ch-1)) .+ (0:34) + gain = ch == 2 ? 2.0 : (block == 1 ? 6.0 : 0.2) + ua[ch, ts] .= gain .* randn(rng, length(ts)) + ya[ch, ts .+ 1] .= ua[ch, ts] .+ 0.02randn(rng, length(ts)) + end + da = iddata(ya, ua, 1.0) + for W in (:MOESP, :CVA) + sa, ua_ = (@test_logs (:warn,) subspaceid(da, 1; r = 4, nblocks = 3, uncertainty = Val(true), W)) + @test !all(ua_.aligned) + @test all(r -> all(isfinite, r.B), ua_.replicates) + @test_throws ArgumentError jackknife_cov(ua_) + end + end # Multiple inputs and outputs G2 = ssrand(2, 2, 3, Ts = Ts, proper = true, stable = true)