From 52f33cb9161544ca9369cf6590edae33cfed244b Mon Sep 17 00:00:00 2001 From: TommyDanMa <220606600+TommyDanMa@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:39:55 +0100 Subject: [PATCH] Add snapshot-based balanced POD --- docs/pages.jl | 5 +- docs/src/functions.md | 1 + docs/src/interfaces.md | 9 +- docs/src/tutorials/balanced_pod.md | 196 +++++++++++ src/ModelOrderReduction.jl | 3 + src/balanced_truncation.jl | 16 +- src/bpod.jl | 235 +++++++++++++ test/Project.toml | 2 + test/bpod.jl | 520 +++++++++++++++++++++++++++++ 9 files changed, 979 insertions(+), 8 deletions(-) create mode 100644 docs/src/tutorials/balanced_pod.md create mode 100644 src/bpod.jl create mode 100644 test/bpod.jl diff --git a/docs/pages.jl b/docs/pages.jl index 6fd3cb79..159f6db2 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -1,6 +1,9 @@ pages = [ "Home" => "index.md", - "Tutorials" => Any["tutorials/deim_FitzHugh-Nagumo.md"], + "Tutorials" => Any[ + "tutorials/deim_FitzHugh-Nagumo.md", + "tutorials/balanced_pod.md", + ], "Functions" => "functions.md", "Developer Interface" => "interfaces.md", ] diff --git a/docs/src/functions.md b/docs/src/functions.md index 89b24204..99dca590 100644 --- a/docs/src/functions.md +++ b/docs/src/functions.md @@ -10,6 +10,7 @@ RSVD deim pod baltrunc +bpod BalancedTruncation opinf OperatorInferenceModel diff --git a/docs/src/interfaces.md b/docs/src/interfaces.md index 0a103cf3..3fa1e1a2 100644 --- a/docs/src/interfaces.md +++ b/docs/src/interfaces.md @@ -3,9 +3,12 @@ The supported user workflow is deliberately small: construct a [`POD`](@ref) from state snapshots, then call [`reduce!`](@ref) with one of the built-in backends, [`SVD`](@ref), [`TSVD`](@ref), or [`RSVD`](@ref). Continuous-time LTI systems can be -reduced with [`baltrunc`](@ref), and polynomial reduced models can be learned from -snapshot/derivative data with [`opinf`](@ref). The public API does not require users -to interact with the abstract types described below. +reduced with [`baltrunc`](@ref). When the Gramians are replaced by already weighted +primal and adjoint impulse snapshots, [`bpod`](@ref) returns the same +[`BalancedTruncation`](@ref) result and does not generate those snapshots. +Polynomial reduced models can be learned from snapshot/derivative data with +[`opinf`](@ref). The public API does not require users to interact with the +abstract types described below. ## POD reduction contract diff --git a/docs/src/tutorials/balanced_pod.md b/docs/src/tutorials/balanced_pod.md new file mode 100644 index 00000000..61cb9f41 --- /dev/null +++ b/docs/src/tutorials/balanced_pod.md @@ -0,0 +1,196 @@ +# Balanced POD + +[`bpod`](@ref) reduces a continuous-time linear system +```math +\dot x = A x + B u, \qquad y = C x + D u +``` +from primal and adjoint impulse-response snapshots. The construction is the one in +Rowley, *International Journal of Bifurcation and Chaos* (2005). It approximates +square-root balanced truncation. [`baltrunc`](@ref) solves the two Gramian Lyapunov +equations directly and is the appropriate method when those solves are affordable. +[`bpod`](@ref) is the snapshot form of the same truncation: the caller supplies the +factors, and the function returns a [`BalancedTruncation`](@ref). + +The snapshot factors must already contain the quadrature weights. If `w_k` is the +quadrature weight at time `t_k`, the corresponding column of `X` is +`sqrt(w_k) * exp(A t_k) b_j` and the corresponding column of `Y` is +`sqrt(w_k) * exp(A' t_k) c_i`. The empirical Gramians are then `X X'` and `Y Y'`. +[`bpod`](@ref) does not form those products and does not generate the snapshots. +Applying the square-root weights a second time squares them. + +The product `Y' * X` is a dense matrix with one row per adjoint snapshot and one +column per primal snapshot. Decomposing it dominates the cost after the factors +exist. Sparse, diagonal, or banded `A`, `B`, and `C` do not change that product. + +A finite horizon omits the tail of the impulse response, and the quadrature rule +adds its own error. Both appear in the approximate Hankel singular values. +Finite-horizon balanced POD does not generally make the reduced model stable: `A` +can be Hurwitz while the reduced state matrix is not. When a stable reduced model +is required, inspect the eigenvalues of that matrix. If the original system is +unstable, the finite-horizon singular values are not the infinite-horizon Hankel +singular values of a stable system. When the retained factors span the state, the +full-order projector is a similarity and can reproduce the input-output map even +though the Hankel values are still inaccurate. Agreement of that full-order +reduction is therefore not evidence that the singular values have converged. The +example below keeps two modes and compares that reduced map with the original +system. + +## A stable system + +The eigenvalues of `A` are `-1`, `-2`, `-3`, and `-6`, so both the primal and +adjoint impulses decay. The slowest factor is `exp(-t)`. Over a horizon of length +16 that factor is about `1e-7`, so the horizon covers the decay of these impulses. +The step `Δt = 1/16` is a separate approximation. The feedthrough `D` is copied +unchanged. + +```@example balanced_pod +using LinearAlgebra +using ModelOrderReduction + +A = [ + -1.0 20.0 0.0 0.0 + 0.0 -2.0 15.0 0.0 + 0.0 0.0 -3.0 10.0 + 0.0 0.0 0.0 -6.0 +] +B = [ + 1.0 0.0 + 0.4 1.0 + 0.0 0.5 + 0.2 -0.3 +] +C = [ + 1.0 0.2 0.0 0.4 + 0.0 1.0 0.3 -0.2 +] +D = [ + 0.15 -0.02 + 0.01 0.08 +] +eigvals(A) +``` + +## Weighted impulses + +The time grid is uniform, with `T = 16` and `Δt = 1/16`. On a uniform grid the +composite trapezoidal rule assigns weight `Δt` to each interior node and weight +`Δt / 2` to the endpoints. Those weights sum to the horizon. The square root is +applied once, inside the snapshot matrix. + +`exp(A t)` is a dense exponential. It is a clear way to build this four-state +example, and it is not a large-scale snapshot algorithm. A large or sparse system +should advance the primal impulses `exp(A t) b_j` and the adjoint impulses +`exp(A' t) c_i` with a matrix-free exponential or an ODE solver, attach the same +square-root weights, and pass the resulting factors to [`bpod`](@ref). + +```@example balanced_pod +t = collect(range(0.0, 16.0; length = 257)) +dt = t[2] - t[1] +weights = fill(dt, length(t)) +weights[1] /= 2 +weights[end] /= 2 + +function weighted_impulses(generator, columns, t, weights) + n, m = size(columns) + nt = length(t) + X = zeros(n, m * nt) + for (k, tk) in pairs(t) + response = exp(generator * tk) + scale = sqrt(weights[k]) + for j in 1:m + X[:, (j - 1) * nt + k] = scale * (response * columns[:, j]) + end + end + return X +end + +X = weighted_impulses(A, B, t, weights) +Y = weighted_impulses(A', C', t, weights) +(size(X), sum(weights)) +``` + +## Reduced model + +With the default relative tolerance, this system retains every positive value, +because the smallest is still larger than one thousandth of the largest. Requesting +`n = 2` drops the two smaller values. The result is a [`BalancedTruncation`](@ref): +`rom.A`, `rom.B`, `rom.C`, and `rom.D` are the reduced system, `rom.hsv` contains +only the retained approximate Hankel singular values, `rom.Tr` reconstructs the +original state, and `rom.S` reduces it. The identity `rom.S * rom.Tr ≈ I` is the +biorthogonality of the projectors. It holds for a poor snapshot grid as well, so it +does not measure the accuracy of `rom.hsv`. + +A distinct singular value determines its left and right singular vectors up to +one shared sign. A repeated singular value determines only the subspace, which +may be rotated. Negating column `j` of `rom.Tr` and row `j` of `rom.S` together +changes the signs in `rom.A`, `rom.B`, and `rom.C` and leaves the input-output +map unchanged. + +```@example balanced_pod +spectrum = bpod(A, B, C, X, Y, D; n = 4, atol = 0.0, rtol = 0.0) +rom = bpod(A, B, C, X, Y, D; n = 2) +spectrum.hsv, rom.hsv, opnorm(rom.S * rom.Tr - I(2)), rom.D == D +``` + +## Output comparison + +For a constant input the state is `x(t) = A^{-1} (exp(A t) - I) B u` when `t > 0`. +The function below evaluates that output and the frequency response +`C (iω I - A)^{-1} B + D`. The comparison uses five output times and five +frequencies. It is a sample of the two maps, not a certified `H∞` norm. + +```@example balanced_pod +function step_output(A, B, C, D, u, t) + x = t == 0 ? zeros(size(A, 1)) : A \ (exp(A * t) * (B * u) - B * u) + return C * x + D * u +end + +function frequency_response(A, B, C, D, ω) + return C * (((im * ω) * I(size(A, 1)) - A) \ B) + D +end + +u = [1.0, -0.4] +times = (0.0, 0.5, 1.0, 2.0, 5.0) +frequencies = (0.1, 0.7, 1.0, 1.3, 10.0) +step_gap = maximum(times) do t + norm(step_output(A, B, C, D, u, t) - step_output(rom.A, rom.B, rom.C, rom.D, u, t)) +end +frequency_gap = maximum(frequencies) do ω + opnorm( + frequency_response(A, B, C, D, ω) - + frequency_response(rom.A, rom.B, rom.C, rom.D, ω) + ) +end +step_gap, frequency_gap +``` + +The printed gaps are samples of the difference between the original system and the +order-2 model. They combine the two discarded Hankel modes with the remaining +horizon and quadrature error, and they are not a bound at every frequency or input. +A coarser grid, such as `T = 2` and `Δt = 1`, leaves the projectors biorthogonal +while moving the approximate Hankel values, and with them this reduced response. +Refining the snapshot grid makes the model approach [`baltrunc`](@ref). It does +not remove the error of the order that was requested. + +[`baltrunc`](@ref) computes this same order from the infinite-horizon Gramians. +The first number below is its sampled distance from the plant. The second is the +sampled distance between that truncation and the snapshot model. On this grid the +two reduced models are close, and both remain separated from the plant by the two +discarded modes. Neither number is an `H∞` bound. + +```@example balanced_pod +reference = baltrunc(A, B, C, D; n = 2) +truncation_gap = maximum(frequencies) do ω + opnorm( + frequency_response(A, B, C, D, ω) - + frequency_response(reference.A, reference.B, reference.C, reference.D, ω) + ) +end +snapshot_gap = maximum(frequencies) do ω + opnorm( + frequency_response(reference.A, reference.B, reference.C, reference.D, ω) - + frequency_response(rom.A, rom.B, rom.C, rom.D, ω) + ) +end +truncation_gap, snapshot_gap +``` diff --git a/src/ModelOrderReduction.jl b/src/ModelOrderReduction.jl index 2019c68a..a738ea14 100644 --- a/src/ModelOrderReduction.jl +++ b/src/ModelOrderReduction.jl @@ -29,6 +29,9 @@ export pod include("balanced_truncation.jl") export BalancedTruncation, baltrunc +include("bpod.jl") +export bpod + include("operator_inference.jl") export OperatorInferenceModel, opinf, reduced_dynamics, quadratic_monomials diff --git a/src/balanced_truncation.jl b/src/balanced_truncation.jl index 7299057a..b00fa581 100644 --- a/src/balanced_truncation.jl +++ b/src/balanced_truncation.jl @@ -1,16 +1,24 @@ """ $(TYPEDEF) -Reduced continuous-time LTI model produced by [`baltrunc`](@ref). +Reduced continuous-time LTI model produced by [`baltrunc`](@ref) or [`bpod`](@ref). The reduced dynamics are ```math \\dot x_r = A_r x_r + B_r u,\\qquad y = C_r x_r + D_r u, ``` with reconstruction ``x \\approx T_r x_r`` and reduction ``x_r = S x`` for plain -truncation. When residualization is used, ``T_r`` is still the balanced truncation +truncation. [`baltrunc`](@ref) computes ``T_r``, ``S``, and the Hankel singular +values `hsv` from factors of the controllability and observability Gramians. +[`bpod`](@ref) computes the same projectors from already weighted snapshot +factors, so its `hsv` approximates those Hankel singular values. The retained +modes may change sign together in column ``j`` of ``T_r`` and row ``j`` of ``S`` +without changing the input-output map. + +When [`baltrunc`](@ref) residualizes, ``T_r`` is still the balanced truncation map for the retained states; the static contribution of the discarded states is folded -into ``(A_r, B_r, C_r, D_r)`` rather than into ``T_r``. +into ``(A_r, B_r, C_r, D_r)`` rather than into ``T_r``. [`bpod`](@ref) always +returns plain truncation. # Fields $(TYPEDFIELDS) @@ -24,7 +32,7 @@ struct BalancedTruncation{T <: AbstractFloat} C::Matrix{T} "feedthrough matrix ``D_r``" D::Matrix{T} - "retained Hankel singular values" + "retained Hankel singular values; approximate when returned by bpod" hsv::Vector{T} "right projector ``T_r`` with ``x \\approx T_r x_r`` under plain truncation" Tr::Matrix{T} diff --git a/src/bpod.jl b/src/bpod.jl new file mode 100644 index 00000000..ef5468f7 --- /dev/null +++ b/src/bpod.jl @@ -0,0 +1,235 @@ +""" + $(TYPEDSIGNATURES) + +Balanced proper orthogonal decomposition of a continuous-time linear system +```math +\\dot x = A x + B u,\\qquad y = C x + D u, +``` +from already weighted primal and adjoint snapshot factors. + +Let `A` be `nx × nx`, `B` be `nx × nu`, `C` be `ny × nx`, and `D` be `ny × nu`. +A vector `B` has length `nx` and is treated as `nu = 1`. The snapshot factors `X` +and `Y` are `nx × nX` and `nx × nY`. The two column counts need not agree. + +The factors follow Rowley (2005). Column `k` of `X` is a primal impulse response +`exp(A t) b_j` already multiplied by the square root of its quadrature weight, and +column `k` of `Y` is the corresponding adjoint impulse `exp(A' t) c_i` with the +same factor. The empirical Gramians are then ``X X'`` and ``Y Y'``. `bpod` does +not form those products, and it does not multiply the columns by the weights. A +second application of the weights squares them. + +The singular value decomposition ``Y' X = U \\Sigma V'`` supplies the projectors. +After the numerical-rank cutoff below, a leading part ``\\Sigma_r`` is retained: +```math +T_r = X V_r \\Sigma_r^{-1/2},\\qquad +S = \\Sigma_r^{-1/2} U_r' Y',\\qquad +A_r = S A T_r,\\; B_r = S B,\\; C_r = C T_r,\\; D_r = D. +``` +`D` is copied, or replaced by a zero matrix of size `ny × nu` when it is omitted. +The state is reconstructed by ``x \\approx T_r x_r`` and reduced by ``x_r = S x``. +A distinct singular value fixes its singular vectors up to one shared sign. +Repeated singular values fix only their subspace, which may be rotated. Changing +the sign of column ``j`` of ``T_r`` and row ``j`` of ``S`` together leaves +``S T_r``, the Hankel values, and the input-output map unchanged. + +Forming `Y' * X` produces a dense `nY × nX` matrix, and decomposing it dominates +the cost after the factors are available. That matrix has `nY * nX` entries +whether or not `A`, `B`, and `C` use the sparse or banded storage below. + +Singular values no larger than `max(eps(T)^(2/3) * σ₁, atol)` are dropped before +`1 / sqrt(σ)` is formed. If `n` is `nothing`, the reduced order is the number of +remaining values that are at least `rtol` times the largest. An explicit positive +integer `n` ignores `rtol` and must not exceed the number of values that survived +the cutoff. `hsv` contains only the retained values, in descending order. Pass +`n = nothing`, `atol = 0`, and `rtol = 0` to keep every value above the cutoff. + +`A`, `B`, `C`, `D`, `X`, and `Y` are promoted to one floating-point type before +any arithmetic. `Float32` and `Float64` are the supported, tested element types. +Standard integer element types become `Float64` through `float` of that promoted +type. Mixed `Float32` and `Float64` inputs use `Float64`. Complex inputs are +rejected. A sparse matrix, the adjoint or transpose of one, and a `Diagonal`, +`Bidiagonal`, `Tridiagonal`, or `SymTridiagonal` matrix keep that storage. A +`Symmetric` or `Hermitian` wrapper, including one around a sparse matrix, has no +such conversion and is not a supported sparse operator. The reduced products are +`S * (A * Tr)`, `S * B`, and `C * Tr`. + +This is plain truncation. It does not residualize, generate time nodes, choose +quadrature weights, or integrate the impulses. `A` is not required to be Hurwitz, +and a Hurwitz `A` does not make the reduced state matrix Hurwitz. Finite-horizon +factors can produce an unstable reduced model. When a stable reduced model is +required, inspect the eigenvalues of its state matrix. If `A` is not Hurwitz, the +singular values from a finite horizon are not the infinite-horizon Hankel singular +values of a stable system. The returned Hankel values are the retained singular +values of `Y' * X`. They approximate the infinite-horizon Hankel singular values +only to the extent that `X` and `Y` approximate factors of those Gramians. A finite +response horizon omits the tail, and the quadrature rule adds its own error. Both +errors pass into `hsv` and the reduced matrices. For a large system, compute the +impulse responses with a matrix-free exponential or an ODE solver and pass the +weighted factors in. A dense matrix exponential is appropriate only for a small +dense `A`. + +# Arguments +- `A::AbstractMatrix`: state matrix, size `nx × nx`. +- `B::AbstractVecOrMat`: input matrix, size `nx × nu`. A vector is one input. +- `C::AbstractMatrix`: output matrix, size `ny × nx`. +- `X::AbstractMatrix`: weighted primal snapshots, size `nx × nX`. +- `Y::AbstractMatrix`: weighted adjoint snapshots, size `nx × nY`. +- `D`: feedthrough matrix, size `ny × nu`. Defaults to zero. + +# Keywords +- `n = nothing`: reduced order. When `nothing`, choose the order from `atol` / `rtol`. +- `atol = 0`: absolute Hankel-singular-value cutoff. +- `rtol = 1e-3`: relative Hankel-singular-value cutoff, used only when `n` is `nothing`. + +# Returns +- [`BalancedTruncation`](@ref): reduced matrices `A`, `B`, `C`, and `D`; the retained + approximate Hankel singular values `hsv`; and the projectors `Tr` and `S`. + +# Throws +- `ArgumentError`: if the inputs do not promote to a real floating-point type, + contain a non-finite value, or have inconsistent dimensions; if `X` or `Y` has + no columns; if `n` is invalid or larger than the number of singular values above + the cutoff; or if no positive Hankel singular values satisfy the tolerances. + +# Examples +```jldoctest +julia> using ModelOrderReduction + +julia> A = [-1.0 0.0; 0.0 -2.0]; B = [1.0, 0.5]; C = [1.0 1.0]; + +julia> X = [1.0 0.0; 0.0 1.0]; Y = [1.0 0.0; 0.0 1.0]; # already weighted + +julia> rom = bpod(A, B, C, X, Y; n = 1); + +julia> size(rom.A) +(1, 1) +``` + +# References +- Rowley, C. W. (2005). Model reduction for fluids, using balanced proper orthogonal + decomposition. *International Journal of Bifurcation and Chaos*. +""" +function bpod( + A::AbstractMatrix, + B::AbstractVecOrMat, + C::AbstractMatrix, + X::AbstractMatrix, + Y::AbstractMatrix, + D::Union{AbstractMatrix, Nothing} = nothing; + n = nothing, + atol::Real = 0, + rtol::Real = 1.0e-3 + ) + TD = D === nothing ? eltype(A) : eltype(D) + T = float(promote_type(eltype(A), eltype(B), eltype(C), eltype(X), eltype(Y), TD)) + T <: AbstractFloat || + throw(ArgumentError("bpod currently supports real floating-point systems only")) + B = B isa AbstractVector ? reshape(B, length(B), 1) : B + nx = size(A, 1) + size(A, 2) == nx || throw(ArgumentError("A must be square")) + size(B, 1) == nx || throw(ArgumentError("B must have the same number of rows as A")) + size(C, 2) == nx || throw(ArgumentError("C must have the same number of columns as A")) + size(X, 1) == nx || throw(ArgumentError("X must have the same number of rows as A")) + size(Y, 1) == nx || throw(ArgumentError("Y must have the same number of rows as A")) + size(X, 2) > 0 || throw(ArgumentError("X must have at least one column")) + size(Y, 2) > 0 || throw(ArgumentError("Y must have at least one column")) + if D !== nothing && size(D) != (size(C, 1), size(B, 2)) + throw(ArgumentError("D must have size (size(C, 1), size(B, 2))")) + end + if n !== nothing + n isa Integer || throw(ArgumentError("n must be an Integer or `nothing`")) + n < 1 && throw(ArgumentError("n must be a positive Integer")) + end + + A = _coerce_operator(A, T) + B = _coerce_operator(B, T) + C = _coerce_operator(C, T) + X = X isa Matrix{T} ? X : Matrix{T}(X) + Y = Y isa Matrix{T} ? Y : Matrix{T}(Y) + if D === nothing + D = zeros(T, size(C, 1), size(B, 2)) + else + D = D isa Matrix{T} ? D : Matrix{T}(D) + end + _assert_finite("A", A) + _assert_finite("B", B) + _assert_finite("C", C) + _assert_finite("D", D) + _assert_finite("X", X) + _assert_finite("Y", Y) + + product = Matrix{T}(Y' * X) + _assert_finite("Y' * X", product) + F = svd(product; full = false) + # Same numerical-rank cutoff as `baltrunc`, applied before `inv(sqrt(σ))`. + σ = F.S + σtol = max(eps(T)^(2 / 3) * (isempty(σ) ? zero(T) : σ[1]), T(atol)) + keep = findall(>(σtol), σ) + isempty(keep) && + throw(ArgumentError("no Hankel singular values satisfy the truncation tolerances")) + U = F.U[:, keep] + σ = σ[keep] + V = F.V[:, keep] + + r = _select_order(σ, n, atol, rtol) + r == 0 && + throw(ArgumentError("no Hankel singular values satisfy the truncation tolerances")) + if n !== nothing && Int(n) > length(σ) + throw(ArgumentError("requested order n = $n exceeds the $(length(σ)) positive Hankel singular values")) + end + + σr = σ[1:r] + Σinvsqrt = Diagonal(inv.(sqrt.(σr))) + Tr = Matrix{T}(X * (V[:, 1:r] * Σinvsqrt)) + Sl = Matrix{T}((Σinvsqrt * U[:, 1:r]') * Y') + # Associate as `S * (A * Tr)` so a sparse or banded `A` is not materialized. + Ar = Matrix{T}(Sl * (A * Tr)) + Br = Matrix{T}(Sl * B) + Cr = Matrix{T}(C * Tr) + return BalancedTruncation{T}(Ar, Br, Cr, Matrix{T}(D), Vector{T}(σr), Tr, Sl) +end + +function _coerce_operator(A::AbstractMatrix, ::Type{T}) where {T <: AbstractFloat} + eltype(A) === T && return A + if A isa LinearAlgebra.Adjoint + return adjoint(_coerce_operator(parent(A), T)) + elseif A isa LinearAlgebra.Transpose + return transpose(_coerce_operator(parent(A), T)) + elseif A isa SparseMatrixCSC + return SparseMatrixCSC{T, Int}(A) + elseif A isa Diagonal + return Diagonal(Vector{T}(A.diag)) + elseif A isa LinearAlgebra.Bidiagonal + return LinearAlgebra.Bidiagonal(Vector{T}(A.dv), Vector{T}(A.ev), A.uplo) + elseif A isa LinearAlgebra.Tridiagonal + return LinearAlgebra.Tridiagonal(Vector{T}(A.dl), Vector{T}(A.d), Vector{T}(A.du)) + elseif A isa LinearAlgebra.SymTridiagonal + return LinearAlgebra.SymTridiagonal(Vector{T}(A.dv), Vector{T}(A.ev)) + else + return Matrix{T}(A) + end +end + +# Sparse `all` inspects stored entries and one structural zero. Banded storage and +# adjoint or transpose wrappers are reduced to those stored entries. Iterating the +# matrix would also visit its structural zeros. +function _stored_entries_finite(A::AbstractArray) + if A isa LinearAlgebra.Adjoint || A isa LinearAlgebra.Transpose + return _stored_entries_finite(parent(A)) + elseif A isa Diagonal + return all(isfinite, A.diag) + elseif A isa LinearAlgebra.Bidiagonal + return all(isfinite, A.dv) && all(isfinite, A.ev) + elseif A isa LinearAlgebra.Tridiagonal + return all(isfinite, A.dl) && all(isfinite, A.d) && all(isfinite, A.du) + elseif A isa LinearAlgebra.SymTridiagonal + return all(isfinite, A.dv) && all(isfinite, A.ev) + else + return all(isfinite, A) + end +end + +function _assert_finite(name::AbstractString, A::AbstractArray) + _stored_entries_finite(A) || throw(ArgumentError("$name contains non-finite entries")) + return nothing +end diff --git a/test/Project.toml b/test/Project.toml index 2c9d9088..67503af2 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -1,6 +1,7 @@ [deps] SymbolicIndexingInterface = "2efcf032-c050-4f8e-a9bb-153293bab1f5" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" MethodOfLines = "94925ecb-adb7-4558-8ed8-f975c56a0bf4" ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" OrdinaryDiffEq = "1dea7af3-3e70-54e6-95c3-0bf5283fa5ed" @@ -13,6 +14,7 @@ Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [compat] SymbolicIndexingInterface = "0.3" LinearAlgebra = "1, < 0.0.1" +SparseArrays = "1, < 0.0.1" MethodOfLines = "1" ModelingToolkit = "11.42" OrdinaryDiffEq = "7" diff --git a/test/bpod.jl b/test/bpod.jl new file mode 100644 index 00000000..f74e9e5d --- /dev/null +++ b/test/bpod.jl @@ -0,0 +1,520 @@ +using Test +using LinearAlgebra +using SparseArrays +using ModelOrderReduction + +const A_PLANT = [ + -1.0 20.0 0.0 0.0 + 0.0 -2.0 15.0 0.0 + 0.0 0.0 -3.0 10.0 + 0.0 0.0 0.0 -6.0 +] +const B_PLANT = [ + 1.0 0.0 + 0.4 1.0 + 0.0 0.5 + 0.2 -0.3 +] +const C_PLANT = [ + 1.0 0.2 0.0 0.4 + 0.0 1.0 0.3 -0.2 +] +const D_PLANT = [ + 0.15 -0.02 + 0.01 0.08 +] + +function psd_sqrt(W::AbstractMatrix{T}) where {T <: AbstractFloat} + F = eigen(Symmetric(Matrix{T}(W))) + λ = F.values + λmax = maximum(abs, λ) + thresh = eps(T) * λmax + kept = findall(≥(thresh), λ) + isempty(kept) && return zeros(T, size(W, 1), 0) + return F.vectors[:, kept] * Diagonal(sqrt.(λ[kept])) +end + +function exact_factors(A, B, C) + Pc = lyap(Matrix(A), Matrix(B) * Matrix(B)') + Po = lyap(Matrix(A)', Matrix(C)' * Matrix(C)) + return psd_sqrt(Pc), psd_sqrt(Po) +end + +function relative_error(got, reference) + return norm(got - reference) / norm(reference) +end + +function uniform_nodes(horizon::Real, dt::Real) + nsteps = round(Int, horizon / dt) + abs(nsteps * dt - horizon) <= 100 * eps(float(horizon)) * max(horizon, one(float(horizon))) || + throw(ArgumentError("dt = $dt does not divide the horizon T = $horizon")) + return collect(range(0.0, float(horizon); length = nsteps + 1)) +end + +function trapezoidal_weights(t::AbstractVector{<:Real}) + nt = length(t) + nt >= 2 || throw(ArgumentError("trapezoidal rule needs at least two nodes")) + all(>(0), diff(t)) || throw(ArgumentError("time nodes must be strictly increasing")) + w = similar(float.(t)) + w[1] = (t[2] - t[1]) / 2 + for k in 2:(nt - 1) + w[k] = (t[k + 1] - t[k - 1]) / 2 + end + w[end] = (t[end] - t[end - 1]) / 2 + return w +end + +function impulse_factor(generator::AbstractMatrix, columns::AbstractMatrix, t, w) + n, m = size(columns) + nt = length(t) + length(w) == nt || throw(ArgumentError("weights and nodes must have the same length")) + X = zeros(eltype(generator), n, m * nt) + for k in eachindex(t) + response = exp(generator * t[k]) + scale = sqrt(w[k]) + for j in 1:m + X[:, (j - 1) * nt + k] = scale * (response * columns[:, j]) + end + end + return X +end + +function weighted_impulses(A, B, C, t) + w = trapezoidal_weights(t) + return impulse_factor(A, B, t, w), impulse_factor(A', C', t, w) +end + +function component_relative_error(got, reference) + return [abs(got[i] - reference[i]) / reference[i] for i in eachindex(reference)] +end + +function transfer(A, B, C, D, ω) + n = size(A, 1) + return C * (((im * ω) * I(n) - A) \ B) + D +end + +function sampled_peak_difference(A, B, C, D, Ar, Br, Cr, Dr, frequencies) + return maximum(frequencies) do ω + opnorm(transfer(A, B, C, D, ω) - transfer(Ar, Br, Cr, Dr, ω)) + end +end + +function h2_difference(A, B, C, Ar, Br, Cr) + n = size(A, 1) + r = size(Ar, 1) + Ae = [A zeros(n, r); zeros(r, n) Ar] + maximum(real, eigvals(Ae)) < 0 || + error("the difference system must be Hurwitz before its Lyapunov solution is an H2 error") + Be = [B; Br] + Ce = [C -Cr] + P = lyap(Ae, Be * Be') + return sqrt(abs(tr(Ce * P * Ce'))) +end + +function align_signature(reference::BalancedTruncation, model::BalancedTruncation) + r = size(model.Tr, 2) + signs = ones(eltype(model.A), r) + for j in 1:r + if dot(reference.Tr[:, j], model.Tr[:, j]) < 0 + signs[j] = -1 + end + end + E = Diagonal(signs) + return BalancedTruncation( + E * model.A * E, + E * model.B, + model.C * E, + model.D, + copy(model.hsv), + model.Tr * E, + E * model.S + ) +end + +@testset "bpod: exact factors agree with baltrunc" begin + X, Y = exact_factors(A_PLANT, B_PLANT, C_PLANT) + for r in (2, 4) + reference = baltrunc(A_PLANT, B_PLANT, C_PLANT, D_PLANT; n = r, atol = 0.0, rtol = 0.0) + model = bpod(A_PLANT, B_PLANT, C_PLANT, X, Y, D_PLANT; n = r, atol = 0.0, rtol = 0.0) + aligned = align_signature(reference, model) + @test model isa BalancedTruncation + @test size(model.A) == (r, r) + @test size(model.Tr) == (4, r) + @test size(model.S) == (r, 4) + @test length(model.hsv) == r + @test model.hsv ≈ reference.hsv rtol = 1.0e-8 atol = 1.0e-8 + @test relative_error(aligned.A, reference.A) < 1.0e-8 + @test relative_error(aligned.B, reference.B) < 1.0e-8 + @test relative_error(aligned.C, reference.C) < 1.0e-8 + @test model.D == reference.D + @test model.D == D_PLANT + @test norm(model.S * model.Tr - I(r)) < 1.0e-10 + end +end + +@testset "bpod: mixed Float32 and Float64 promote to Float64" begin + X, Y = exact_factors(A_PLANT, B_PLANT, C_PLANT) + A32 = Float32.(A_PLANT) + X32 = Float32.(X) + promoted = bpod( + Float64.(A32), B_PLANT, C_PLANT, Float64.(X32), Y, D_PLANT; + n = 2, atol = 0.0, rtol = 0.0 + ) + mixed = bpod(A32, B_PLANT, C_PLANT, X32, Y, D_PLANT; n = 2, atol = 0.0, rtol = 0.0) + aligned = align_signature(promoted, mixed) + @test eltype(mixed.A) == Float64 + @test eltype(mixed.hsv) == Float64 + @test relative_error(aligned.A, promoted.A) < 1.0e-10 + @test relative_error(aligned.B, promoted.B) < 1.0e-10 + @test relative_error(aligned.C, promoted.C) < 1.0e-10 + @test aligned.hsv ≈ promoted.hsv rtol = 1.0e-10 atol = 1.0e-10 + @test mixed.D == promoted.D +end + +@testset "bpod: invalid input" begin + X, Y = exact_factors(A_PLANT, B_PLANT, C_PLANT) + @test_throws ArgumentError bpod([1.0 2.0], B_PLANT, C_PLANT, X, Y) + @test_throws ArgumentError bpod(A_PLANT, ones(1, 1), C_PLANT, X, Y) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, ones(2, 3), X, Y) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X, Y, ones(1, 1)) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X[1:3, :], Y) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X, Y[1:3, :]) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X[:, 1:0], Y) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X, Y[:, 1:0]) + @test_throws ArgumentError bpod(complex.(A_PLANT), B_PLANT, C_PLANT, X, Y) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X, Y; n = 0) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X, Y; n = -1) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X, Y; n = 1.5) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X, Y; n = 5) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, zeros(4, 2), zeros(4, 2); n = 1) + @test_throws ArgumentError bpod(A_PLANT, B_PLANT, C_PLANT, X, Y; n = 1, atol = 1.0e6) + + Xnan = copy(X) + Xnan[1, 1] = NaN + @test_throws "X contains non-finite" bpod(A_PLANT, B_PLANT, C_PLANT, Xnan, Y) + Yinf = copy(Y) + Yinf[1, 1] = Inf + @test_throws "Y contains non-finite" bpod(A_PLANT, B_PLANT, C_PLANT, X, Yinf) +end + +@testset "bpod: sparse Float32 operators stay sparse and match dense Float64" begin + X, Y = exact_factors(A_PLANT, B_PLANT, C_PLANT) + A32 = SparseMatrixCSC{Float32, Int32}(sparse(Float32.(A_PLANT))) + B32 = sparse(Float32.(B_PLANT)) + C32 = sparse(Float32.(C_PLANT)) + converted = ModelOrderReduction._coerce_operator(A32, Float64) + @test converted isa SparseMatrixCSC{Float64} + @test nnz(converted) == nnz(A32) + @test converted == Float64.(A32) + + dense = bpod( + Matrix{Float64}(A32), Matrix{Float64}(B32), Matrix{Float64}(C32), X, Y, D_PLANT; + n = 2, atol = 0.0, rtol = 0.0 + ) + sparse_model = bpod(A32, B32, C32, X, Y, D_PLANT; n = 2, atol = 0.0, rtol = 0.0) + aligned = align_signature(dense, sparse_model) + @test eltype(sparse_model.A) == Float64 + @test relative_error(aligned.A, dense.A) < 1.0e-10 + @test relative_error(aligned.B, dense.B) < 1.0e-10 + @test relative_error(aligned.C, dense.C) < 1.0e-10 + @test aligned.hsv ≈ dense.hsv rtol = 1.0e-10 atol = 1.0e-10 + + stored = sparse(Float64[1.0 0.0; 0.0 -2.0]) + @test ModelOrderReduction._assert_finite("A", stored) === nothing + stored[1, 1] = NaN + @test_throws "A contains non-finite" ModelOrderReduction._assert_finite("A", stored) +end + +@testset "bpod: order selection matches baltrunc" begin + A = Matrix(Diagonal([-1.0, -2.0, -50.0])) + B = Matrix{Float64}(I, 3, 3) + C = Matrix{Float64}(I, 3, 3) + X, Y = exact_factors(A, B, C) + # Margins stay away from the cutoffs. The Hankel values are about 0.5, 0.25, and 0.01. + for rtol in (0.0, 1.0e-2, 0.1) + reference = baltrunc(A, B, C; n = nothing, atol = 0.0, rtol = rtol) + model = bpod(A, B, C, X, Y; n = nothing, atol = 0.0, rtol = rtol) + aligned = align_signature(reference, model) + @test size(model.A, 1) == size(reference.A, 1) + @test issorted(model.hsv; rev = true) + @test model.hsv ≈ reference.hsv rtol = 1.0e-8 atol = 1.0e-8 + @test relative_error(aligned.A, reference.A) < 1.0e-8 + @test relative_error(aligned.B, reference.B) < 1.0e-8 + @test relative_error(aligned.C, reference.C) < 1.0e-8 + @test model.D == reference.D == zeros(3, 3) + end + @test_throws ArgumentError baltrunc(A, B, C; n = nothing, atol = 0.0, rtol = 2.0) + @test_throws "no Hankel singular values satisfy" bpod( + A, B, C, X, Y; n = nothing, atol = 0.0, rtol = 2.0 + ) + + X, Y = exact_factors(A_PLANT, B_PLANT, C_PLANT) + reference = baltrunc(A_PLANT, B_PLANT, C_PLANT, D_PLANT) + model = bpod(A_PLANT, B_PLANT, C_PLANT, X, Y, D_PLANT) + aligned = align_signature(reference, model) + @test size(model.A, 1) == size(reference.A, 1) == 4 + @test model.hsv ≈ reference.hsv rtol = 1.0e-8 atol = 1.0e-8 + @test relative_error(aligned.A, reference.A) < 1.0e-8 + @test model.D == reference.D == D_PLANT +end + +@testset "bpod: rank-deficient factors reject an oversized order" begin + X, Y = exact_factors(A_PLANT, B_PLANT, C_PLANT) + X1 = repeat(X[:, 1:1], 1, 2) + Y1 = repeat(Y[:, 1:1], 1, 2) + @test_throws "exceeds the 1 positive" bpod( + A_PLANT, B_PLANT, C_PLANT, X1, Y1; n = 2, atol = 0.0, rtol = 0.0 + ) + model = bpod(A_PLANT, B_PLANT, C_PLANT, X1, Y1; n = nothing, atol = 0.0, rtol = 0.0) + @test size(model.A) == (1, 1) + @test length(model.hsv) == 1 + @test only(model.hsv) > 0 + @test norm(model.S * model.Tr - I(1)) < 1.0e-10 +end + +@testset "bpod: vector input and omitted feedthrough" begin + X, Y = exact_factors(A_PLANT, B_PLANT, C_PLANT) + column = B_PLANT[:, 1] + feedthrough = D_PLANT[:, 1:1] + from_vector = bpod( + A_PLANT, column, C_PLANT, X, Y, feedthrough; n = 2, atol = 0.0, rtol = 0.0 + ) + from_matrix = bpod( + A_PLANT, reshape(column, :, 1), C_PLANT, X, Y, feedthrough; + n = 2, atol = 0.0, rtol = 0.0 + ) + @test from_vector.A == from_matrix.A + @test from_vector.B == from_matrix.B + @test from_vector.C == from_matrix.C + @test from_vector.D == from_matrix.D == feedthrough + @test from_vector.hsv == from_matrix.hsv + @test size(from_vector.B) == (2, 1) + + omitted = bpod(A_PLANT, B_PLANT, C_PLANT, X, Y; n = 2, atol = 0.0, rtol = 0.0) + explicit = bpod( + A_PLANT, B_PLANT, C_PLANT, X, Y, zeros(2, 2); n = 2, atol = 0.0, rtol = 0.0 + ) + reference = baltrunc(A_PLANT, B_PLANT, C_PLANT; n = 2, atol = 0.0, rtol = 0.0) + @test omitted.D == explicit.D == reference.D == zeros(2, 2) + @test omitted.A == explicit.A + @test omitted.B == explicit.B + @test omitted.C == explicit.C + @test omitted.hsv == explicit.hsv + single = bpod(A_PLANT, column, C_PLANT, X, Y; n = 1, atol = 0.0, rtol = 0.0) + @test single.D == zeros(2, 1) + @test size(single.B) == (1, 1) +end + +@testset "bpod: trapezoidal impulse snapshots" begin + # Composite trapezoidal weights integrate 3 + 2t exactly over [0, 1] (the + # integral is 4) and sum to the length of the interval. + irregular = [0.0, 0.2, 0.5, 0.9, 1.0] + weights = trapezoidal_weights(irregular) + @test abs(sum(weights .* (3 .+ 2 .* irregular)) - 4.0) < 1.0e-12 + @test abs(sum(weights) - 1.0) < 1.0e-12 + + classical = baltrunc(A_PLANT, B_PLANT, C_PLANT, D_PLANT; n = 4, atol = 0.0, rtol = 0.0) + classical_r2 = baltrunc(A_PLANT, B_PLANT, C_PLANT, D_PLANT; n = 2, atol = 0.0, rtol = 0.0) + coarse_t = uniform_nodes(2.0, 1.0) + Xc, Yc = weighted_impulses(A_PLANT, B_PLANT, C_PLANT, coarse_t) + coarse = bpod(A_PLANT, B_PLANT, C_PLANT, Xc, Yc, D_PLANT; n = 4, atol = 0.0, rtol = 0.0) + coarse_r2 = bpod(A_PLANT, B_PLANT, C_PLANT, Xc, Yc, D_PLANT; n = 2, atol = 0.0, rtol = 0.0) + coarse_hsv_error = maximum(component_relative_error(coarse.hsv, classical.hsv)) + coarse_r2_h2 = h2_difference(A_PLANT, B_PLANT, C_PLANT, coarse_r2.A, coarse_r2.B, coarse_r2.C) + classical_r2_h2 = h2_difference( + A_PLANT, B_PLANT, C_PLANT, classical_r2.A, classical_r2.B, classical_r2.C + ) + # On this mesh the projectors stay biorthogonal to about 1e-14, while the + # largest relative Hankel error is 0.343 and the order-2 H2 errors are 4.340 + # versus 2.548. The inequalities below are those recorded tolerances. + @test opnorm(coarse.S * coarse.Tr - I(4)) < 1.0e-8 + @test opnorm(coarse_r2.S * coarse_r2.Tr - I(2)) < 1.0e-8 + @test coarse_hsv_error > 0.2 + @test abs(coarse_r2_h2 - classical_r2_h2) / classical_r2_h2 > 0.2 + + # T = 16 and Δt = 1/16 has a negligible controllability tail. A reference + # quadrature table gives relative Hankel errors 1.879e-4 and 1.817e-3 for the + # first two values. Order-2 H2 errors at Δt = 1/128 differed by about 1.4e-5. + # Eightfold coarser steps scale a second-order error by 64, to about 9e-4. + # Each assertion allows about a factor of five over that evidence. + resolved_t = uniform_nodes(16.0, 1 / 16) + Xr, Yr = weighted_impulses(A_PLANT, B_PLANT, C_PLANT, resolved_t) + resolved = bpod(A_PLANT, B_PLANT, C_PLANT, Xr, Yr, D_PLANT; n = 4, atol = 0.0, rtol = 0.0) + resolved_r2 = bpod(A_PLANT, B_PLANT, C_PLANT, Xr, Yr, D_PLANT; n = 2, atol = 0.0, rtol = 0.0) + hsv_error = component_relative_error(resolved.hsv, classical.hsv) + resolved_r2_h2 = h2_difference( + A_PLANT, B_PLANT, C_PLANT, resolved_r2.A, resolved_r2.B, resolved_r2.C + ) + @test hsv_error[1] < 1.0e-3 + @test hsv_error[2] < 1.0e-2 + @test abs(resolved_r2_h2 - classical_r2_h2) / classical_r2_h2 < 5.0e-3 + @test abs(resolved_r2_h2 - classical_r2_h2) < abs(coarse_r2_h2 - classical_r2_h2) + # A reference sampled peak of 3.029e-4 between the order-2 frequency responses + # at Δt = 1/128, scaled by 64, is about 0.019. The maximum is over five + # frequencies, not a certified H∞ norm, and the tolerance allows about a + # factor of five. + frequencies = (0.1, 0.7, 1.0, 1.3, 10.0) + frequency_gap = sampled_peak_difference( + resolved_r2.A, resolved_r2.B, resolved_r2.C, resolved_r2.D, + classical_r2.A, classical_r2.B, classical_r2.C, classical_r2.D, + frequencies + ) + @test frequency_gap < 0.1 +end + +function agrees_with_dense(Aop, Bop, Cop, X, Y) + reference = bpod( + Matrix(Aop), Matrix(Bop), Matrix(Cop), X, Y; n = 2, atol = 0.0, rtol = 0.0 + ) + model = bpod(Aop, Bop, Cop, X, Y; n = 2, atol = 0.0, rtol = 0.0) + aligned = align_signature(reference, model) + @test relative_error(aligned.A, reference.A) < 1.0e-10 + @test relative_error(aligned.B, reference.B) < 1.0e-10 + @test relative_error(aligned.C, reference.C) < 1.0e-10 + @test aligned.hsv ≈ reference.hsv rtol = 1.0e-10 atol = 1.0e-10 + return nothing +end + +@testset "bpod: structured and sparse-adjoint operators match dense references" begin + Ad = Diagonal([-1.0, -2.0, -3.0, -4.0]) + Bd = Diagonal([1.0, 0.4, 0.2, 0.1]) + Cd = Diagonal([1.0, 0.5, 0.3, 0.2]) + @test ModelOrderReduction._coerce_operator(Ad, Float64) === Ad + Xd, Yd = exact_factors(Matrix(Ad), Matrix(Bd), Matrix(Cd)) + agrees_with_dense(Ad, Bd, Cd, Xd, Yd) + Ad32 = Diagonal(Float32.(diag(Ad))) + promoted_diag = ModelOrderReduction._coerce_operator(Ad32, Float64) + @test promoted_diag isa Diagonal{Float64} + @test promoted_diag.diag == diag(Ad) + agrees_with_dense(Ad32, Bd, Cd, Xd, Yd) + @test_throws "A contains non-finite" ModelOrderReduction._assert_finite( + "A", Diagonal([1.0, NaN, -3.0]) + ) + + At = Tridiagonal(fill(0.2, 3), [-1.0, -1.5, -2.0, -2.5], fill(0.3, 3)) + Bt = [1.0, 0.0, 0.0, 0.0] + Ct = [0.0 0.0 0.0 1.0] + @test ModelOrderReduction._coerce_operator(At, Float64) === At + Xt, Yt = exact_factors(Matrix(At), reshape(Bt, :, 1), Ct) + agrees_with_dense(At, reshape(Bt, :, 1), Ct, Xt, Yt) + At32 = Tridiagonal(fill(Float32(0.2), 3), Float32[-1.0, -1.5, -2.0, -2.5], fill(Float32(0.3), 3)) + promoted_tri = ModelOrderReduction._coerce_operator(At32, Float64) + @test promoted_tri isa Tridiagonal{Float64} + @test promoted_tri.d == Float64.(At32.d) + @test promoted_tri.dl == Float64.(At32.dl) + @test promoted_tri.du == Float64.(At32.du) + agrees_with_dense(At32, reshape(Bt, :, 1), Ct, Xt, Yt) + @test_throws "A contains non-finite" ModelOrderReduction._assert_finite( + "A", Tridiagonal([NaN], [-1.0, -2.0], [0.1]) + ) + + Ab32 = Bidiagonal(Float32[-1.0, -2.0, -3.0, -4.0], fill(Float32(0.2), 3), :L) + promoted_bi = ModelOrderReduction._coerce_operator(Ab32, Float64) + @test promoted_bi isa Bidiagonal{Float64} + @test promoted_bi.uplo == Ab32.uplo + @test promoted_bi.dv == Float64.(Ab32.dv) + @test promoted_bi.ev == Float64.(Ab32.ev) + Xb, Yb = exact_factors(Matrix(promoted_bi), reshape(Bt, :, 1), Ct) + agrees_with_dense(Ab32, reshape(Bt, :, 1), Ct, Xb, Yb) + + As32 = SymTridiagonal(Float32[-1.0, -2.0, -3.0, -4.0], fill(Float32(0.2), 3)) + promoted_sym = ModelOrderReduction._coerce_operator(As32, Float64) + @test promoted_sym isa SymTridiagonal{Float64} + @test promoted_sym.dv == Float64.(As32.dv) + @test promoted_sym.ev == Float64.(As32.ev) + Xs, Ys = exact_factors(Matrix(promoted_sym), reshape(Bt, :, 1), Ct) + agrees_with_dense(As32, reshape(Bt, :, 1), Ct, Xs, Ys) + + Aadj = adjoint(sparse(A_PLANT')) + Badj = adjoint(sparse(B_PLANT')) + Cadj = adjoint(sparse(C_PLANT')) + @test ModelOrderReduction._coerce_operator(Aadj, Float64) === Aadj + @test Matrix(Aadj) == A_PLANT + Xp, Yp = exact_factors(A_PLANT, B_PLANT, C_PLANT) + agrees_with_dense(Aadj, Badj, Cadj, Xp, Yp) + Aadj32 = adjoint(sparse(Float32.(A_PLANT'))) + promoted_adj = ModelOrderReduction._coerce_operator(Aadj32, Float64) + @test promoted_adj isa Adjoint{Float64, <:SparseMatrixCSC{Float64, Int}} + @test nnz(parent(promoted_adj)) == nnz(parent(Aadj32)) + @test Matrix(promoted_adj) == Float64.(Matrix(Aadj32)) + agrees_with_dense( + Aadj32, adjoint(sparse(Float32.(B_PLANT'))), adjoint(sparse(Float32.(C_PLANT'))), Xp, Yp + ) + poisoned = sparse(Float64[1.0 0.0; 0.0 -1.0]) + poisoned[2, 1] = NaN + @test_throws "A contains non-finite" ModelOrderReduction._assert_finite("A", adjoint(poisoned)) + @test_throws "A contains non-finite" ModelOrderReduction._assert_finite("A", transpose(poisoned)) +end + +@testset "bpod: Cholesky Gramian factors balance and preserve the full-order map" begin + # These factors come from cholesky, not from the eigenvalue factor helper. + Pc = lyap(A_PLANT, B_PLANT * B_PLANT') + Po = lyap(A_PLANT', C_PLANT' * C_PLANT) + X = Matrix(cholesky(Hermitian(Pc)).L) + Y = Matrix(cholesky(Hermitian(Po)).L) + model = bpod(A_PLANT, B_PLANT, C_PLANT, X, Y, D_PLANT; n = 4, atol = 0.0, rtol = 0.0) + @test model.S * Pc * model.S' ≈ Diagonal(model.hsv) rtol = 1.0e-8 atol = 1.0e-8 + @test model.Tr' * Po * model.Tr ≈ Diagonal(model.hsv) rtol = 1.0e-8 atol = 1.0e-8 + frequencies = (0.1, 1.0, 10.0) + @test sampled_peak_difference( + A_PLANT, B_PLANT, C_PLANT, D_PLANT, + model.A, model.B, model.C, model.D, frequencies + ) < 1.0e-8 +end + +@testset "bpod: unequal snapshot counts, Float32, repeated values, and integers" begin + b = B_PLANT[:, 1:1] + tX = uniform_nodes(1.0, 0.5) + tY = uniform_nodes(1.0, 0.25) + X = impulse_factor(A_PLANT, b, tX, trapezoidal_weights(tX)) + Y = impulse_factor(A_PLANT', C_PLANT', tY, trapezoidal_weights(tY)) + @test size(X, 2) == 3 + @test size(Y, 2) == 10 + unequal = bpod( + A_PLANT, b, C_PLANT, X, Y, D_PLANT[:, 1:1]; n = 2, atol = 0.0, rtol = 0.0 + ) + @test size(unequal.B) == (2, 1) + @test size(unequal.C) == (2, 2) + @test size(unequal.D) == (2, 1) + @test opnorm(unequal.S * unequal.Tr - I(2)) < 1.0e-8 + + Xf, Yf = exact_factors(A_PLANT, B_PLANT, C_PLANT) + narrow = bpod( + Float32.(A_PLANT), Float32.(B_PLANT), Float32.(C_PLANT), + Float32.(Xf), Float32.(Yf), Float32.(D_PLANT); n = 2, atol = 0.0, rtol = 0.0 + ) + wide = bpod( + Float64.(Float32.(A_PLANT)), Float64.(Float32.(B_PLANT)), Float64.(Float32.(C_PLANT)), + Float64.(Float32.(Xf)), Float64.(Float32.(Yf)), Float64.(Float32.(D_PLANT)); + n = 2, atol = 0.0, rtol = 0.0 + ) + aligned = align_signature(wide, narrow) + @test eltype(narrow.A) == Float32 + @test eltype(narrow.hsv) == Float32 + @test relative_error(aligned.A, wide.A) < 1.0e-5 + @test aligned.hsv ≈ wide.hsv rtol = 1.0e-5 atol = 1.0e-5 + + Ar = Matrix(-1.0I, 2, 2) + Br = Matrix{Float64}(I, 2, 2) + Pc = lyap(Ar, Br * Br') + factor = Matrix(cholesky(Hermitian(Pc)).L) + repeated = bpod(Ar, Br, Br, factor, factor; n = 2, atol = 0.0, rtol = 0.0) + @test repeated.hsv ≈ [0.5, 0.5] atol = 1.0e-10 + @test repeated.S * Pc * repeated.S' ≈ Diagonal(repeated.hsv) atol = 1.0e-8 + @test opnorm(repeated.S * repeated.Tr - I(2)) < 1.0e-10 + + integer = bpod([-1 0; 0 -2], [1, 0], [1 0], [1 0; 0 1], [1 0; 0 1]; n = 1) + @test eltype(integer.A) == Float64 + @test eltype(integer.hsv) == Float64 +end + +@testset "bpod: a short horizon can destabilize a Hurwitz system" begin + # Two nodes on [0, 0.25]. A reference evaluation puts the reduced pole near 2. + t = uniform_nodes(0.25, 0.25) + X, Y = weighted_impulses(A_PLANT, B_PLANT, C_PLANT, t) + reduced = bpod( + A_PLANT, B_PLANT, C_PLANT, X, Y, D_PLANT; n = 1, atol = 0.0, rtol = 0.0 + ) + @test maximum(real, eigvals(A_PLANT)) < 0 + @test maximum(real, eigvals(reduced.A)) > 0 +end