From d5955dd7091914b32d719e3867a97a8b901aeb4f Mon Sep 17 00:00:00 2001 From: dongxuelian2 <2984896280@qq.com> Date: Thu, 22 Oct 2026 14:04:27 +0800 Subject: [PATCH 1/5] Improve numerical robustness of relative_gain_array --- lib/ControlSystemsBase/src/analysis.jl | 172 ++++++++++++++---- lib/ControlSystemsBase/test/test_analysis.jl | 2 + .../test/test_relative_gain_array.jl | 128 +++++++++++++ 3 files changed, 265 insertions(+), 37 deletions(-) create mode 100644 lib/ControlSystemsBase/test/test_relative_gain_array.jl diff --git a/lib/ControlSystemsBase/src/analysis.jl b/lib/ControlSystemsBase/src/analysis.jl index 3d3616f65..6fda742ec 100644 --- a/lib/ControlSystemsBase/src/analysis.jl +++ b/lib/ControlSystemsBase/src/analysis.jl @@ -446,7 +446,8 @@ end relative_gain_array(G, w::Number; balance=true) Calculate the relative gain array of `G` at frequencies `w`. -G(iω) .* pinv(tranpose(G(iω))) +For a nonsingular square response matrix `A = G(iω)`, this is +`A .* transpose(inv(A))`. The RGA can be used to find input-output pairings for MIMO control using individually tuned loops. Pair the inputs and outputs such that the RGA(ωc) at the crossover frequency becomes as close to diagonal as possible. Avoid pairings such that RGA(0) contains negative diagonal elements. @@ -463,7 +464,7 @@ The RGA can be used to find input-output pairings for MIMO control using individ between the transfer function elements. Therefore, diagonal input uncertainty (which is always present) is usually of more concern for plants with large RGA elements. -The relative gain array is computed using the The unit-consistent (UC) generalized inverse +For singular or rectangular matrices, the relative gain array uses the unit-consistent (UC) generalized inverse. Reference: "On the Relative Gain Array (RGA) with Singular and Rectangular Matrices" Jeffrey Uhlmann https://arxiv.org/pdf/1805.10312.pdf @@ -475,47 +476,144 @@ end relative_gain_array(G, w::Number; balance=true) = relative_gain_array(freqresp(G, w; balance)) """ - relative_gain_array(A::AbstractMatrix; tol = 1.0e-15) + relative_gain_array(A::AbstractMatrix; tol = eps(real(float(eltype(A)))), maxiter = 10000) + +Compute `A .* transpose(inv(A))` for a numerically nonsingular square matrix, +and the unit-consistent (UC) generalization for singular or rectangular matrices. +The UC inverse applies a Moore–Penrose inverse after diagonal scaling so that +the geometric mean of the nonzero magnitudes in every nonzero row and column +is one. Applying `pinv` directly to `A` does not preserve input/output scaling +invariance. + +`tol` bounds the logarithmic row/column scaling corrections; it does not set +the numerical rank tolerance. The scaling iteration also allows for rounding +at the precision of the working type, and throws an error after `maxiter` +iterations without convergence. Inputs must be finite. +If the normalized entries cannot be represented in the working type, an error +is thrown instead of silently dropping nonzero entries or returning nonfinite values. + +Well-conditioned square matrices use an LU inverse. Otherwise, for BLAS +floating-point types, numerical rank is determined on the scaled matrix using +the same relative cutoff as `pinv`: `min(size(A)...)*eps(T)`, where `T` is the +real working type. A large condition number caused only by channel units does +not imply rank deficiency. Directions below this cutoff are discarded; close +to the cutoff, neither rank nor scaling invariance can be guaranteed in finite +precision. Use higher-precision data when small independent directions matter. +Square matrices of other element types retain the LU inverse when it exists; +their singular/rectangular cases require an appropriate `svd` implementation. Reference: "On the Relative Gain Array (RGA) with Singular and Rectangular Matrices" Jeffrey Uhlmann https://arxiv.org/pdf/1805.10312.pdf """ -function relative_gain_array(A::AbstractMatrix; tol = 1e-15) +function relative_gain_array(A::AbstractMatrix; tol = eps(real(float(eltype(A)))), maxiter::Integer = 10000) + isfinite(tol) && tol > 0 || throw(ArgumentError("tol must be finite and positive")) + maxiter > 0 || throw(ArgumentError("maxiter must be positive")) + all(isfinite, A) || throw(ArgumentError("relative_gain_array requires finite entries")) + T = float(eltype(A)) + RT = real(T) m, n = size(A) - if m == n && LinearAlgebra.det(A) != 0 - return A .* inv(transpose(A)) - end - L = zeros(m, n) - M = ones(m, n) - S = sign.(A) - AA = abs.(A) - idx = findall(vec(AA) .> 0.0) - L[idx] = log.(AA[idx]) - idx = setdiff(1 : length(AA), idx) - L[idx] .= 0 - M[idx] .= 0 - r = sum(M, dims=2)[:] - c = sum(M, dims=1)[:] - u = zeros(m, 1) - v = zeros(1, n) - dx = 2*tol - while dx > tol - idx = c .> 0 - p = sum(L[:, idx], dims=1) ./ c[idx]' - L[:, idx] .-= p .* M[:, idx] - v[idx] .-= p' - dx = sum(abs, p)/length(p) - idx = r .> 0 - p = sum(L[idx, :], dims=2) ./ r[idx] - L[idx, :] .-= p .* M[idx, :] - u[idx] .-= p - dx += sum(abs, p)/length(p) - end - dl = exp.(u) - dr = exp.(v) - S = S .* exp.(L) - A .* transpose(pinv(S) .* (dl * dr)') + isempty(A) && return zeros(T, m, n) + if m == n + F = lu!(Matrix{T}(A); check=false) + if issuccess(F) + AI = inv(F) + # This is only a fast-path screen, not a rank decision. In + # particular, bad conditioning due to units needs equilibration. + κ = opnorm(A, Inf) * opnorm(AI, Inf) + if κ * sqrt(eps(RT)) < 1 || !(eltype(AI) <: LinearAlgebra.BlasFloat) + return A .* transpose(AI) + end + end + end + S, B = _rga_scale(A, tol, maxiter) + F = LinearAlgebra.svd(S) + cutoff = min(m, n) * eps(real(eltype(F.S))) * maximum(F.S) + if m == n && all(>(cutoff), F.S) + # Retain resolvable small directions. Binary scaling preserves the + # supplied entries exactly, avoiding extra rounding before inversion. + return B .* transpose(inv(B)) + end + si = map(s -> s > cutoff ? inv(s) : zero(s), F.S) + # For S = Dl*A*Dr, Aᵁ = Dr*pinv(S)*Dl. The diagonal factors + # cancel in the Hadamard product, so no inverse scales are needed. + S .* transpose(F.V * (si .* F.U')) +end + +function _rga_scale(A, tol, maxiter) + T = float(eltype(A)) + RT = real(T) + m, n = size(A) + L = zeros(RT, m, n) + M = .!iszero.(A) + r = vec(sum(M; dims=2)) + c = vec(sum(M; dims=1)) + for k in eachindex(L, A) + if M[k] + a = T(A[k]) + # The magnitude of a finite complex entry can itself overflow. + s = max(abs(real(a)), abs(imag(a))) + L[k] = log(s) + log(abs(a / s)) + end + end + u = zeros(RT, m) + v = zeros(RT, n) + converged = false + for _ in 1:maxiter + dx = zero(RT) + for j in 1:n + c[j] == 0 && continue + p = sum(@view L[:, j]) / c[j] + v[j] -= p + dx = max(dx, abs(p)) + for i in 1:m + M[i, j] && (L[i, j] -= p) + end + end + for i in 1:m + r[i] == 0 && continue + p = sum(@view L[i, :]) / r[i] + u[i] -= p + dx = max(dx, abs(p)) + for j in 1:n + M[i, j] && (L[i, j] -= p) + end + end + if dx <= max(tol, eps(RT) * max(one(RT), maximum(abs, L))) + converged = true + break + end + end + converged || error("relative_gain_array scaling did not converge in $maxiter iterations") + + # Scale the original entries, not exp.(L): a log/exp round trip can + # erase small, resolvable differences between nearly dependent entries. + # Split off binary exponents to avoid overflowing the diagonal factors + # or underflowing an intermediate row-scaled matrix. + logtwo = log(RT(2)) + ue = floor.(Int, u / logtwo) + ve = floor.(Int, v / logtwo) + us = exp.(u - ue * logtwo) + vs = exp.(v - ve * logtwo) + S = zeros(T, m, n) + B = zeros(T, m, n) + for j in 1:n, i in 1:m + a = T(A[i, j]) + iszero(a) && continue + _, e = frexp(max(abs(real(a)), abs(imag(a)))) + f = us[i] * vs[j] + ex = e + ue[i] + ve[j] + re = ldexp(ldexp(real(a), -e) * f, ex) + im = ldexp(ldexp(imag(a), -e) * f, ex) + S[i, j] = T <: Real ? re : complex(re, im) + bre = ldexp(real(a), ue[i] + ve[j]) + bim = ldexp(imag(a), ue[i] + ve[j]) + B[i, j] = T <: Real ? bre : complex(bre, bim) + iszero(S[i, j]) && error("relative_gain_array scaled entries underflow the working range") + iszero(B[i, j]) && error("relative_gain_array binary-scaled entries underflow the working range") + end + all(isfinite, S) || error("relative_gain_array scaled entries exceed the working range") + S, B end """ diff --git a/lib/ControlSystemsBase/test/test_analysis.jl b/lib/ControlSystemsBase/test/test_analysis.jl index a4c76751e..f265a2a38 100644 --- a/lib/ControlSystemsBase/test/test_analysis.jl +++ b/lib/ControlSystemsBase/test/test_analysis.jl @@ -612,6 +612,8 @@ R = [ M = [A B] @test relative_gain_array(M) ≈ 1/2 .* [R R] atol=0.01 +include("test_relative_gain_array.jl") + ## Gang of four P = ssrand(2,3,2) diff --git a/lib/ControlSystemsBase/test/test_relative_gain_array.jl b/lib/ControlSystemsBase/test/test_relative_gain_array.jl new file mode 100644 index 000000000..9191ed443 --- /dev/null +++ b/lib/ControlSystemsBase/test/test_relative_gain_array.jl @@ -0,0 +1,128 @@ +@testset "Relative gain array numerics" begin + rng = MersenneTwister(1081) + + # Independent UC reference: double-center log magnitudes in one step + # (full support), then use a known rank-two factorization in 256 bits. + A0 = [1 8 17; -4 6 8; -8 1 -6] # column 3 = column 1 + 2column 2 + Rref = setprecision(256) do + A = BigFloat.(A0) + L = log.(abs.(A)) + u = -sum(L; dims=2) / 3 + v = -sum(L; dims=1) / 3 .+ sum(L) / 9 + S = exp.(u) .* A .* exp.(v) + B = S[:, 1:2] + C = BigFloat[1 0 exp(v[3]-v[1]); 0 1 2exp(v[3]-v[2])] + SI = C' * inv(C*C') * inv(B'*B) * B' + S .* transpose(SI) + end + for T in (Float32, Float64) + τ = 100eps(T) + A = T.(A0) + @test eltype(@inferred relative_gain_array(A)) == T + for a in T.((1, 1e-3, 1e-12, 1e12)) + @test relative_gain_array(a*A) ≈ Rref rtol=τ + end + # A rank-one matrix stays rank one, including with zero rows/columns. + for (m,n) in ((2,3), (3,2), (3,3)) + A = T.(collect(1:m) * collect(1:n)') + @test relative_gain_array(A) ≈ fill(T(1)/(m*n),m,n) rtol=τ + Z = [zeros(T,1,n+1); zeros(T,m) A] + @test relative_gain_array(Z) ≈ [zeros(T,1,n+1); zeros(T,m) fill(T(1)/(m*n),m,n)] rtol=τ + end + @test relative_gain_array(zeros(T,2,3)) == zeros(T,2,3) + @test relative_gain_array(zeros(T,0,3)) == zeros(T,0,3) + @test relative_gain_array(zeros(T,3,0)) == zeros(T,3,0) + @test relative_gain_array(T[1 2 0 0; 2 4 0 0; 0 0 1 3]) ≈ + T[0.25 0.25 0 0; 0.25 0.25 0 0; 0 0 0.5 0.5] rtol=τ + + # Full-rank square, tall, wide and rank-deficient matrices, with + # independent signed input/output scalings and permutations. + for A in (T[4 1 2; 1 5 1; 2 1 6], T[1 2 0; 0 1 1], + T[1 0; 2 1; 0 1], T.(A0)) + m,n = size(A) + R = relative_gain_array(A) + d = T.((-1).^(1:m) .* exp10.(range(-8,8;length=m))) + e = T.((-1).^(1:n) .* exp10.(range(8,-8;length=n))) + for B in (T(1e-12)*A, d .* A, A .* e', d .* A .* e') + @test relative_gain_array(B) ≈ R rtol=τ + end + p = randperm(rng,m); q = randperm(rng,n) + @test relative_gain_array(A[p,q]) ≈ R[p,q] rtol=τ + @test relative_gain_array(transpose(A)) ≈ transpose(R) rtol=τ + @test sum(R) ≈ rank(A) rtol=τ + end + + # Random matrices checked against the inverse of the supplied input + # values, not against their pre-rounding generating matrix. + for _ in 1:10 + A = randn(rng,T,4,4) + 4I + R = relative_gain_array(A) + B = BigFloat.(A) + @test R ≈ B .* transpose(inv(B)) rtol=τ + d = T.(exp10.(range(-6,6;length=4))) + e = reverse(d) + @test relative_gain_array(d .* A .* e') ≈ R rtol=τ + @test vec(sum(R;dims=1)) ≈ ones(T,4) rtol=τ + @test vec(sum(R;dims=2)) ≈ ones(T,4) rtol=τ + end + + # A resolvable independent direction must not be discarded merely + # because it is below sqrt(eps). The exact 2x2 RGA is available. + δ = T === Float32 ? T(2)^(-12) : T(2)^(-40) + A = T[1 1; 1 1+δ] + B = BigFloat.(A) + @test relative_gain_array(A) ≈ B .* transpose(inv(B)) rtol=τ + @test maximum(abs,relative_gain_array(A)) > inv(2δ) + + CT = Complex{T} + for A in (CT[1+im 2-im; 3im 4], CT[1+im 2 3im; 2+2im 4 6im]) + R = relative_gain_array(A) + @test eltype(@inferred relative_gain_array(A)) == CT + if size(A,1) == size(A,2) + B = Complex{BigFloat}.(A) + @test R ≈ B .* transpose(inv(B)) rtol=τ + else + @test R ≈ fill(T(1)/6,size(A)) rtol=τ + end + d = CT[im, -2] + e = CT.((1:size(A,2)) .* (1+im)) + @test relative_gain_array(d .* A .* transpose(e)) ≈ R rtol=τ + @test relative_gain_array(conj.(A)) ≈ conj.(R) rtol=τ + end + end + + # Range-safe equilibration must preserve a correct RGA, not just + # invariance of an incorrect result. The raw inverse loses an entry here. + A = [1e300 1e-300; 1e300 2e-300] + @test relative_gain_array(A) ≈ [2 -1; -1 2] + @test relative_gain_array(Matrix(Diagonal([1e300,1e-300]))) ≈ Matrix(1.0I,2,2) + @test relative_gain_array(fill(nextfloat(0.0),2,3)) ≈ fill(1/6,2,3) + @test_throws ErrorException relative_gain_array([1e300 1e300 1e-300; 1e300 1e300 1e-300; 1e-300 1e-300 1e300]) + A = ComplexF64[floatmax()*(1+im) floatmax(); floatmax()*(1+im) floatmax()] + @test relative_gain_array(A) ≈ fill(0.25+0im,2,2) + @test relative_gain_array([1 2; 3 5]) ≈ [-5 6; 6 -5] + @test relative_gain_array(sparse([1.0 2 0; 0 1 1])) ≈ relative_gain_array([1.0 2 0; 0 1 1]) + @test relative_gain_array(BigFloat[1 2; 3 5]) ≈ BigFloat[-5 6; 6 -5] + @test_throws MethodError relative_gain_array(BigFloat[1 2 3; 2 4 6]) + + # Sparse support gives slow alternating projections. A finite cap must + # fail explicitly instead of returning an unconverged UC result. + A = [2.0 3 0; 0 4 5] + @test_throws ErrorException relative_gain_array(A; maxiter=1) + @test all(isfinite,relative_gain_array(A)) + @test relative_gain_array(1e100A) ≈ relative_gain_array(A) + A = zeros(32,33) + for i in 1:32 + A[i,i] = 2 + A[i,i+1] = 3 + end + @test_throws ErrorException relative_gain_array(A) + S = Float64.(A .!= 0) # On this tree support the UC magnitudes are all one. + @test relative_gain_array(A; maxiter=50000) ≈ S .* transpose(pinv(S)) + @test_throws ArgumentError relative_gain_array(A; tol=0) + @test_throws ArgumentError relative_gain_array(A; tol=-1) + @test_throws ArgumentError relative_gain_array(A; tol=NaN) + @test_throws ArgumentError relative_gain_array(A; maxiter=0) + @test_throws ArgumentError relative_gain_array([1.0 NaN]) + @test_throws ArgumentError relative_gain_array([1.0 Inf]) +end From 46fcd502ff14aafc78a3dc8209545b8a80d742b0 Mon Sep 17 00:00:00 2001 From: dongxuelian2 <2984896280@qq.com> Date: Thu, 22 Oct 2026 14:13:18 +0800 Subject: [PATCH 2/5] Preserve exact RGA inverses for rational square matrices --- lib/ControlSystemsBase/src/analysis.jl | 9 +++++++-- lib/ControlSystemsBase/test/test_relative_gain_array.jl | 3 +++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/ControlSystemsBase/src/analysis.jl b/lib/ControlSystemsBase/src/analysis.jl index 6fda742ec..aa1028eab 100644 --- a/lib/ControlSystemsBase/src/analysis.jl +++ b/lib/ControlSystemsBase/src/analysis.jl @@ -515,13 +515,18 @@ function relative_gain_array(A::AbstractMatrix; tol = eps(real(float(eltype(A))) m, n = size(A) isempty(A) && return zeros(T, m, n) if m == n - F = lu!(Matrix{T}(A); check=false) + # Preserve exact rational inverses; integers still promote for division. + LT = typeof(zero(eltype(A)) / one(eltype(A))) + F = lu!(Matrix{LT}(A); check=false) if issuccess(F) AI = inv(F) + if !(eltype(AI) <: LinearAlgebra.BlasFloat) + return A .* transpose(AI) + end # This is only a fast-path screen, not a rank decision. In # particular, bad conditioning due to units needs equilibration. κ = opnorm(A, Inf) * opnorm(AI, Inf) - if κ * sqrt(eps(RT)) < 1 || !(eltype(AI) <: LinearAlgebra.BlasFloat) + if κ * sqrt(eps(RT)) < 1 return A .* transpose(AI) end end diff --git a/lib/ControlSystemsBase/test/test_relative_gain_array.jl b/lib/ControlSystemsBase/test/test_relative_gain_array.jl index 9191ed443..16477c732 100644 --- a/lib/ControlSystemsBase/test/test_relative_gain_array.jl +++ b/lib/ControlSystemsBase/test/test_relative_gain_array.jl @@ -101,6 +101,9 @@ A = ComplexF64[floatmax()*(1+im) floatmax(); floatmax()*(1+im) floatmax()] @test relative_gain_array(A) ≈ fill(0.25+0im,2,2) @test relative_gain_array([1 2; 3 5]) ≈ [-5 6; 6 -5] + A = [1//1 2//1; 3//1 5//1] + @test relative_gain_array(A) == [-5 6; 6 -5] + @test eltype(relative_gain_array(A)) == eltype(A) @test relative_gain_array(sparse([1.0 2 0; 0 1 1])) ≈ relative_gain_array([1.0 2 0; 0 1 1]) @test relative_gain_array(BigFloat[1 2; 3 5]) ≈ BigFloat[-5 6; 6 -5] @test_throws MethodError relative_gain_array(BigFloat[1 2 3; 2 4 6]) From f0da64e76d3266575b72f820b6475d43dcbb49ff Mon Sep 17 00:00:00 2001 From: dongxuelian2 <2984896280@qq.com> Date: Thu, 22 Oct 2026 14:36:28 +0800 Subject: [PATCH 3/5] Preserve resolvable square directions before UC truncation --- lib/ControlSystemsBase/src/analysis.jl | 87 ++++++++++++++++++- .../test/test_relative_gain_array.jl | 15 ++++ 2 files changed, 99 insertions(+), 3 deletions(-) diff --git a/lib/ControlSystemsBase/src/analysis.jl b/lib/ControlSystemsBase/src/analysis.jl index aa1028eab..258499c2a 100644 --- a/lib/ControlSystemsBase/src/analysis.jl +++ b/lib/ControlSystemsBase/src/analysis.jl @@ -492,8 +492,12 @@ iterations without convergence. Inputs must be finite. If the normalized entries cannot be represented in the working type, an error is thrown instead of silently dropping nonzero entries or returning nonfinite values. -Well-conditioned square matrices use an LU inverse. Otherwise, for BLAS -floating-point types, numerical rank is determined on the scaled matrix using +Well-conditioned square matrices use an LU inverse. For BLAS floating-point +types, binary diagonal scaling based on a maximum-weight matching of element +exponents is also tried before discarding directions: geometric normalization +can itself worsen conditioning. Resolvable LU pivots on the balanced matrix +retain independent directions even when its inverse is sensitive. Otherwise, +numerical rank is determined on the geometrically scaled matrix using the same relative cutoff as `pinv`: `min(size(A)...)*eps(T)`, where `T` is the real working type. A large condition number caused only by channel units does not imply rank deficiency. Directions below this cutoff are discarded; close @@ -530,14 +534,36 @@ function relative_gain_array(A::AbstractMatrix; tol = eps(real(float(eltype(A))) return A .* transpose(AI) end end + if T <: LinearAlgebra.BlasFloat + B = _rga_binary_balance(A) + if B !== nothing + F = lu!(copy(B); check=false) + if issuccess(F) + BI = inv(F) + pivotmin = typemax(RT) + for i in 1:n + pivotmin = min(pivotmin, abs(F.factors[i,i])) + end + pivottol = n * eps(RT) * maximum(abs, F.factors) + if pivotmin > pivottol || opnorm(B, Inf) * opnorm(BI, Inf) * sqrt(eps(RT)) < 1 + R = B .* transpose(BI) + all(isfinite, R) || error("relative_gain_array inverse exceeds the working range") + return R + end + end + end + end end S, B = _rga_scale(A, tol, maxiter) F = LinearAlgebra.svd(S) + all(isfinite, F.S) || error("relative_gain_array singular values exceed the working range") cutoff = min(m, n) * eps(real(eltype(F.S))) * maximum(F.S) if m == n && all(>(cutoff), F.S) # Retain resolvable small directions. Binary scaling preserves the # supplied entries exactly, avoiding extra rounding before inversion. - return B .* transpose(inv(B)) + R = B .* transpose(inv(B)) + all(isfinite, R) || error("relative_gain_array inverse exceeds the working range") + return R end si = map(s -> s > cutoff ? inv(s) : zero(s), F.S) # For S = Dl*A*Dr, Aᵁ = Dr*pinv(S)*Dl. The diagonal factors @@ -545,6 +571,61 @@ function relative_gain_array(A::AbstractMatrix; tol = eps(real(float(eltype(A))) S .* transpose(F.V * (si .* F.U')) end +function _rga_binary_balance(A) + T = float(eltype(A)) + m, n = size(A) + # A maximum-weight matching of binary exponents supplies a diagonal + # scaling with matched maximum components in [1,2) and all other + # components below 2. + # This is only an inverse certificate, not the definition of the UC inverse. + E = fill(typemin(Int), m, n) + lo, hi = typemax(Int), typemin(Int) + for k in eachindex(A, E) + a = T(A[k]) + iszero(a) && continue + E[k] = exponent(max(abs(real(a)), abs(imag(a)))) + lo = min(lo, E[k]) + hi = max(hi, E[k]) + end + hi == typemin(Int) && return nothing + penalty = (hi - lo + 1) * n + C = map(e -> e == typemin(Int) ? penalty : hi - e, E) + p, _ = Hungarian.hungarian(C) + any(i -> p[i] == 0 || E[i,p[i]] == typemin(Int), 1:n) && return nothing + u = zeros(Int, n) + # Difference constraints for the matching dual, solved by bounded + # Bellman-Ford relaxation. Maximum weight excludes negative cycles. + for _ in 1:n-1 + changed = false + for k in 1:n, i in 1:n + j = p[k] + E[i,j] == typemin(Int) && continue + bound = u[k] + E[k,j] - E[i,j] + if u[i] > bound + u[i] = bound + changed = true + end + end + changed || break + end + v = zeros(Int, n) + for i in 1:n + v[p[i]] = -E[i,p[i]] - u[i] + end + B = zeros(T, m, n) + for j in 1:n, i in 1:m + a = T(A[i,j]) + iszero(a) && continue + e = u[i] + v[j] + re = ldexp(real(a), e) + im = ldexp(imag(a), e) + B[i,j] = T <: Real ? re : complex(re, im) + # An inconclusive certificate must not discard input support. + iszero(B[i,j]) && return nothing + end + B +end + function _rga_scale(A, tol, maxiter) T = float(eltype(A)) RT = real(T) diff --git a/lib/ControlSystemsBase/test/test_relative_gain_array.jl b/lib/ControlSystemsBase/test/test_relative_gain_array.jl index 16477c732..14011eac6 100644 --- a/lib/ControlSystemsBase/test/test_relative_gain_array.jl +++ b/lib/ControlSystemsBase/test/test_relative_gain_array.jl @@ -32,6 +32,11 @@ @test relative_gain_array(zeros(T,2,3)) == zeros(T,2,3) @test relative_gain_array(zeros(T,0,3)) == zeros(T,0,3) @test relative_gain_array(zeros(T,3,0)) == zeros(T,3,0) + # A large inverse norm does not remove the independent diagonal of + # a triangular matrix. Its RGA is exactly the identity. + ntri = T === Float32 ? 32 : 64 + Atri = Matrix{T}(I,ntri,ntri) - triu(ones(T,ntri,ntri),1) + @test relative_gain_array(Atri) ≈ Matrix{T}(I,ntri,ntri) @test relative_gain_array(T[1 2 0 0; 2 4 0 0; 0 0 1 3]) ≈ T[0.25 0.25 0 0; 0.25 0.25 0 0; 0 0 0.5 0.5] rtol=τ @@ -96,6 +101,16 @@ A = [1e300 1e-300; 1e300 2e-300] @test relative_gain_array(A) ≈ [2 -1; -1 2] @test relative_gain_array(Matrix(Diagonal([1e300,1e-300]))) ≈ Matrix(1.0I,2,2) + # Geometric normalization may be ill-conditioned even when A is not. + # This input remains reliably invertible after channel-unit changes. + A = [1.0 1e-100 0.1; 1e-100 1 0.1; 0.1 0.1 1] + B = BigFloat.(A) + ref = B .* transpose(inv(B)) + d = [1e100,1e-100,1.0] + @test relative_gain_array(A) ≈ ref + @test relative_gain_array(d .* A) ≈ ref + @test relative_gain_array(A .* d') ≈ ref + @test relative_gain_array(d .* A .* reverse(d)') ≈ ref @test relative_gain_array(fill(nextfloat(0.0),2,3)) ≈ fill(1/6,2,3) @test_throws ErrorException relative_gain_array([1e300 1e300 1e-300; 1e300 1e300 1e-300; 1e-300 1e-300 1e300]) A = ComplexF64[floatmax()*(1+im) floatmax(); floatmax()*(1+im) floatmax()] From e7a0b923118928676ac1197541a441237115502f Mon Sep 17 00:00:00 2001 From: dongxuelian2 <2984896280@qq.com> Date: Thu, 22 Oct 2026 14:54:17 +0800 Subject: [PATCH 4/5] Scale RGA pivot checks by the LU factor error model --- lib/ControlSystemsBase/src/analysis.jl | 8 +++++++- .../test/test_relative_gain_array.jl | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/ControlSystemsBase/src/analysis.jl b/lib/ControlSystemsBase/src/analysis.jl index 258499c2a..1d34822a1 100644 --- a/lib/ControlSystemsBase/src/analysis.jl +++ b/lib/ControlSystemsBase/src/analysis.jl @@ -544,7 +544,13 @@ function relative_gain_array(A::AbstractMatrix; tol = eps(real(float(eltype(A))) for i in 1:n pivotmin = min(pivotmin, abs(F.factors[i,i])) end - pivottol = n * eps(RT) * maximum(abs, F.factors) + # Use the LU backward-error scale, not just its largest + # entry: cancellation in complex elimination can leave a + # spurious pivot above n*eps*maximum(abs,U). + γ = n * eps(RT) + γ = γ < 1 ? γ / (1 - γ) : typemax(RT) + pivottol = γ * opnorm(LinearAlgebra.UnitLowerTriangular(F.factors), Inf) * + opnorm(LinearAlgebra.UpperTriangular(F.factors), Inf) if pivotmin > pivottol || opnorm(B, Inf) * opnorm(BI, Inf) * sqrt(eps(RT)) < 1 R = B .* transpose(BI) all(isfinite, R) || error("relative_gain_array inverse exceeds the working range") diff --git a/lib/ControlSystemsBase/test/test_relative_gain_array.jl b/lib/ControlSystemsBase/test/test_relative_gain_array.jl index 14011eac6..c4a236477 100644 --- a/lib/ControlSystemsBase/test/test_relative_gain_array.jl +++ b/lib/ControlSystemsBase/test/test_relative_gain_array.jl @@ -111,6 +111,25 @@ @test relative_gain_array(d .* A) ≈ ref @test relative_gain_array(A .* d') ≈ ref @test relative_gain_array(d .* A .* reverse(d)') ≈ ref + # Exact complex rank four: a cancellation-generated LU pivot can exceed + # n*eps*maximum(abs,U), while remaining within the factor error scale. + A = ComplexF32[-6-7im 1+11im 7-7im 13-2im -10-3im; + 9-11im 3-19im -12+15im -3+4im -28+9im; + -14-9im -3-17im 7+22im 4+10im 6+6im; + 24+15im 12-8im -18-7im -9-2im 11-8im; + 15-2im -6+11im -2-10im -3im 5+6im] + ref = setprecision(256) do + C = Complex{BigFloat}.(A) + L = log.(abs.(C)) + S = exp.(-sum(L;dims=2)/5) .* C .* + exp.(-sum(L;dims=1)/5 .+ sum(L)/25) + X = S[:,1:4] + Y = inv(X[1:4,:]) * S[1:4,:] + SI = Y' * inv(Y*Y') * inv(X'*X) * X' + S .* transpose(SI) + end + @test relative_gain_array(A) ≈ ref rtol=100eps(Float32) + @test relative_gain_array(ComplexF32[im,1+im,-1,2im,3] .* A) ≈ ref rtol=100eps(Float32) @test relative_gain_array(fill(nextfloat(0.0),2,3)) ≈ fill(1/6,2,3) @test_throws ErrorException relative_gain_array([1e300 1e300 1e-300; 1e300 1e300 1e-300; 1e-300 1e-300 1e300]) A = ComplexF64[floatmax()*(1+im) floatmax(); floatmax()*(1+im) floatmax()] From 0b26fa3898034cd099e3841db6dfe1ec74cc4a21 Mon Sep 17 00:00:00 2001 From: dongxuelian2 <2984896280@qq.com> Date: Sat, 21 Nov 2026 10:03:37 +0800 Subject: [PATCH 5/5] Test the relative gain array SVD fallback Exercise a resolved direction that survives scaled SVD when LU growth makes the binary-balanced pivot bound inconclusive. Codex assisted with the test and coverage verification. --- .../test/test_relative_gain_array.jl | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lib/ControlSystemsBase/test/test_relative_gain_array.jl b/lib/ControlSystemsBase/test/test_relative_gain_array.jl index c4a236477..0062133ac 100644 --- a/lib/ControlSystemsBase/test/test_relative_gain_array.jl +++ b/lib/ControlSystemsBase/test/test_relative_gain_array.jl @@ -111,6 +111,20 @@ @test relative_gain_array(d .* A) ≈ ref @test relative_gain_array(A .* d') ≈ ref @test relative_gain_array(d .* A .* reverse(d)') ≈ ref + + # LU growth in one block makes its pivot error bound inconclusive for a + # small but resolved direction in the other block. The scaled SVD should + # retain that direction and recover the classical RGA. + W = I - 0.75f0 * tril(ones(Float32, 8, 8), -1) + W[:, end] .= 1 + δ = 2.0f0^(-14) + A = zeros(Float32, 10, 10) + A[1:8, 1:8] = W + A[9:10, 9:10] = Float32[1 1; 1 1+δ] + R = relative_gain_array(A) + @test R[1:8, 1:8] ≈ W .* transpose(inv(W)) + @test R[9:10, 9:10] ≈ Float32[1+δ -1; -1 1+δ] / δ + # Exact complex rank four: a cancellation-generated LU pivot can exceed # n*eps*maximum(abs,U), while remaining within the factor error scale. A = ComplexF32[-6-7im 1+11im 7-7im 13-2im -10-3im;