From 9c57347cdf2336edaeac271974830a5b0e5c8d0f Mon Sep 17 00:00:00 2001 From: dongxuelian2 <2984896280@qq.com> Date: Wed, 21 Oct 2026 23:21:54 +0800 Subject: [PATCH 1/3] Use relative pole-zero distances by default in minreal --- .../src/types/SisoTfTypes/SisoRational.jl | 4 +- .../src/types/SisoTfTypes/SisoZpk.jl | 33 ++++- .../src/types/TransferFunction.jl | 30 +++- lib/ControlSystemsBase/test/runtests.jl | 1 + .../test/test_conversion.jl | 12 +- lib/ControlSystemsBase/test/test_minreal.jl | 131 ++++++++++++++++++ 6 files changed, 189 insertions(+), 22 deletions(-) create mode 100644 lib/ControlSystemsBase/test/test_minreal.jl diff --git a/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoRational.jl b/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoRational.jl index 87643556d..fc7e1be5d 100644 --- a/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoRational.jl +++ b/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoRational.jl @@ -38,9 +38,9 @@ Base.zero(f::SisoRational) = zero(typeof(f)) isproper(f::SisoRational) = (length(f.num) <= length(f.den)) -function minreal(sys::SisoRational{T}, eps::Real=sqrt(eps())) where T +function minreal(sys::SisoRational{T}, tol::Union{Real,Nothing}=nothing) where T T2 = typeof(oneunit(T)/oneunit(T)) - return convert(SisoRational{T2}, minreal(convert(SisoZpk,sys), eps)) + return convert(SisoRational{T2}, minreal(convert(SisoZpk,sys), tol)) end function print_siso(io::IO, f::SisoRational, var=:s) diff --git a/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoZpk.jl b/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoZpk.jl index 9e3f87f54..6ff4bb619 100644 --- a/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoZpk.jl +++ b/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoZpk.jl @@ -62,13 +62,31 @@ isproper(f::SisoZpk) = (length(f.z) <= length(f.p)) # Will not be able to create complex polynomials without type instability -function minreal(sys::SisoZpk{T,TR}, eps::Real) where {T, TR} +# Normalize the distance rather than multiplying a tolerance by the root scale, +# which can underflow for very small roots. No global scale should make distinct +# slow roots eligible for cancellation. +function _relative_root_distance(p, z) + p, z = float(p), float(z) + p == z && return zero(real(p)) + scale = max(abs(p), abs(z)) + if isinf(scale) + # Finite complex components can have an overflowing absolute value. + scale = max(abs(real(p)), abs(imag(p)), abs(real(z)), abs(imag(z))) + p, z = p/scale, z/scale + scale = max(abs(p), abs(z)) + end + return abs(p-z)/scale +end + +function minreal(sys::SisoZpk{T,TR}, tol::Union{Real,Nothing}=nothing) where {T, TR} if length(sys.p) == 0 return sys end newZ = copy(sys.z) newP = Vector{TR}() + relative = tol === nothing + threshold = relative ? sqrt(eps(real(float(one(TR))))) : tol pidx = 1 p = sys.p[pidx] @@ -76,9 +94,13 @@ function minreal(sys::SisoZpk{T,TR}, eps::Real) where {T, TR} if isempty(newZ) push!(newP, p) else - distance, zidx = findmin(abs.(p .- newZ)) + distance, zidx = if relative + findmin(_relative_root_distance.(p, newZ)) + else + findmin(abs.(p .- newZ)) + end - if distance < eps + if distance < threshold if imag(p) == 0 && imag(newZ[zidx]) != 0 && zidx < length(newZ) newZ[zidx+1] = real(newZ[zidx+1]) end @@ -241,10 +263,7 @@ function +(f1::SisoZpk{T1,TR1}, f2::SisoZpk{T2,TR2}) where {T1<:Number,T2<:Numbe p = TRnew[] end - # FIXME: - # Threshold for pole-zero cancellation should depend on the roots of the system - # Note the difference between continuous and discrete-time systems... - minreal(SisoZpk(z::Vector{TRnew},p::Vector{TRnew},k), sqrt(eps())) # type assert required or inference + minreal(SisoZpk(z::Vector{TRnew},p::Vector{TRnew},k)) # type assert required for inference end diff --git a/lib/ControlSystemsBase/src/types/TransferFunction.jl b/lib/ControlSystemsBase/src/types/TransferFunction.jl index c84779560..7bd6dc116 100644 --- a/lib/ControlSystemsBase/src/types/TransferFunction.jl +++ b/lib/ControlSystemsBase/src/types/TransferFunction.jl @@ -75,15 +75,31 @@ numpoly(G::TransferFunction) = map(numpoly, G.matrix) denpoly(G::TransferFunction) = map(denpoly, G.matrix) """ - minreal(tf::TransferFunction, eps=sqrt(eps())) - -Create a minimal representation of each transfer function in `tf` by cancelling poles and zeros -will promote system to an appropriate numeric type + minreal(G::TransferFunction) + minreal(G::TransferFunction, tol::Real) + +Reduce each transfer function in `G` by cancelling nearby poles and zeros, promoting +to an appropriate numeric type if needed. + +By default, roots are matched by their relative distance +`abs(p-z)/max(abs(p), abs(z)) < sqrt(eps(T))`, where `T` is the real floating-point +type of the roots. Exactly equal roots (including two roots at zero) are matched. +There is no absolute tolerance floor: a root at zero only matches another root at +zero. This criterion is invariant under a common scaling of the roots, up to +floating-point rounding. + +An explicit positional `tol` retains the absolute-distance criterion +`abs(p-z) < tol`. + +Root proximity is a heuristic, not a bound on the response error. In particular, +nearby roots close to the imaginary axis (or the unit circle in discrete time) +can have substantially different responses. Ill-conditioned or repeated roots +computed from polynomial coefficients may require an explicit tolerance. """ -function minreal(G::TransferFunction, eps::Real=sqrt(eps())) - matrix = similar(G.matrix, typeof(minreal(one(first(G.matrix)), eps))) +function minreal(G::TransferFunction, tol::Union{Real,Nothing}=nothing) + matrix = similar(G.matrix, typeof(minreal(one(first(G.matrix)), tol))) for i = eachindex(G.matrix) - matrix[i] = minreal(G.matrix[i], eps) + matrix[i] = minreal(G.matrix[i], tol) end return TransferFunction(matrix, G.timeevol) end diff --git a/lib/ControlSystemsBase/test/runtests.jl b/lib/ControlSystemsBase/test/runtests.jl index 34342de32..624dfca93 100644 --- a/lib/ControlSystemsBase/test/runtests.jl +++ b/lib/ControlSystemsBase/test/runtests.jl @@ -27,6 +27,7 @@ my_tests = [ "test_staticsystems", "test_transferfunction", "test_zpk", + "test_minreal", "test_promotion", "test_connections", "test_discrete", diff --git a/lib/ControlSystemsBase/test/test_conversion.jl b/lib/ControlSystemsBase/test/test_conversion.jl index e6cb13dd8..ef1c05d9e 100644 --- a/lib/ControlSystemsBase/test/test_conversion.jl +++ b/lib/ControlSystemsBase/test/test_conversion.jl @@ -207,11 +207,11 @@ C = tf('s') @test norm(P*C - C*P) < 1e-10 # The difference below is analytically zero but contains near pole-zero cancellations on # the stability boundary. An explicit minreal tolerance is required to reliably remove the -# nearly non-minimal modes; the default tolerance occasionally leaves a weakly coupled -# boundary pole for which hinfnorm correctly returns Inf. The modes truncated by minreal -# may contribute a gain on the order of the truncation tolerance, hence the test threshold -# is above the minreal tolerance. -mp = minreal(minreal(tf(P)*C) - P*C, 1e-9) +# nearly non-minimal modes. Use it for both reductions: conversion from state space +# can perturb a pole at zero, which a relative root criterion does not match with +# an exact zero. The modes truncated by minreal may contribute a gain on the order +# of the truncation tolerance, hence the test threshold is above the minreal tolerance. +mp = minreal(minreal(tf(P)*C, 1e-9) - P*C, 1e-9) @test hinfnorm(mp)[1] < 1e-8 @inferred P*C @@ -223,7 +223,7 @@ mp = minreal(minreal(tf(P)*C) - P*C, 1e-9) P = c2d(P, 0.01, :fwdeuler) # to get poles exactly at 1 C = tf('z', 0.01)-1 @test norm(minreal(P*C - C*P)) < 1e-10 -mp = minreal(minreal(tf(P)*C) - P*C, 1e-9) # see comment on the continuous-time case above +mp = minreal(minreal(tf(P)*C, 1e-9) - P*C, 1e-9) # see comment on the continuous-time case above @test hinfnorm(mp)[1] < 1e-8 @inferred P*C diff --git a/lib/ControlSystemsBase/test/test_minreal.jl b/lib/ControlSystemsBase/test/test_minreal.jl new file mode 100644 index 000000000..5173b81c1 --- /dev/null +++ b/lib/ControlSystemsBase/test/test_minreal.jl @@ -0,0 +1,131 @@ +@testset "Transfer-function minreal tolerances" begin + # Inspect the stored roots: poles(::TransferFunction) can itself remove + # common factors through MatrixPencils and would hide a missed cancellation. + function roots_of(G) + z, p, _ = zpkdata(G) + return only(z), only(p) + end + + @testset "Slow dynamics (#1081)" begin + G = tf([1, 1.5e-8], [1, 1e-8]) + R = minreal(G) + @test dcgain(R)[] ≈ 1.5 + @test length(last(roots_of(R))) == 1 + @test freqresp(R, [0, 1e-8, 1]) ≈ freqresp(G, [0, 1e-8, 1]) + for a in (1e-12, 1, 1e12) + H = minreal(time_scale(G, a)) + @test length(last(roots_of(H))) == 1 + @test dcgain(H)[] ≈ 1.5 + @test freqresp(H, a.*[0, 1e-8, 1]) ≈ freqresp(G, [0, 1e-8, 1]) + end + @test dcgain(zpk([], [-1e-8], 1e-8) + 1)[] ≈ 2 + + # An unrelated fast pole must not enlarge the cancellation threshold. + G = zpk([-1.5e-8], [-1e-8, -1e12], 1e12) + @test roots_of(minreal(G)) == roots_of(G) + @test dcgain(minreal(G))[] ≈ 1.5 + + # Explicit tolerances retain their absolute meaning, including zero. + @test isempty(last(roots_of(minreal(zpk([-1.5e-8], [-1e-8], 1), 1e-8)))) + G = zpk([-1.0], [-1.0], 1) + @test roots_of(minreal(G, 0)) == roots_of(G) + end + + @testset "Root types and scales" begin + for T in (Float32, Float64, BigFloat), scale in T.((1e-12, 1, 1e12)) + δ = eps(T)*4 + G = zpk(T[-scale*(1+δ)], T[-scale], one(T)) + @test isempty(last(roots_of(@inferred minreal(G)))) + @test !isempty(last(roots_of(minreal(G, zero(T))))) + G = zpk(T[-1.5scale], T[-scale], one(T)) + @test roots_of(minreal(G)) == roots_of(G) + G = tf(T[1, 1.5scale], T[1, scale]) + @test dcgain(minreal(G))[] ≈ T(1.5) + @test length(last(roots_of(minreal(G)))) == 1 + + # An exact common root, including repeated roots and the origin. + G = zpk(T[0, -scale, -scale], T[0, -scale, -scale, -2scale], one(T)) + @test roots_of(minreal(G)) == (T[], T[-2scale]) + G = zpk(T[0], T[-scale], one(T)) + @test roots_of(minreal(G)) == roots_of(G) + G = zpk(T[scale], T[-scale], one(T)) + @test roots_of(minreal(G)) == roots_of(G) + end + + # Distances must not lose the type's precision to Float64 defaults. + setprecision(256) do + G = zpk(BigFloat[-1- big"1e-30"], BigFloat[-1], big"1") + @test roots_of(minreal(G)) == roots_of(G) + end + for T in (Float32, Float64) + scale = nextfloat(zero(T)) + G = zpk(T[-2scale], T[-scale], one(T)) + @test roots_of(minreal(G)) == roots_of(G) + # abs(complex root) overflows although its components are finite. + p = complex(floatmax(T), floatmax(T)) + G = zpk([p/2], [p], complex(one(T))) + @test roots_of(minreal(G)) == roots_of(G) + G = zpk([p*(1-4eps(T))], [p], complex(one(T))) + @test isempty(last(roots_of(minreal(G)))) + end + end + + @testset "Conjugates, ordering, and time evolution" begin + for T in (Float32, Float64), scale in T.((1e-12, 1, 1e12)) + c = complex(-scale, scale) + δ = eps(T)*4 + G = zpk([c*(1+δ), conj(c)*(1+δ), -2scale], + [c, conj(c), -3scale], one(T)) + R = minreal(G) + @test roots_of(R) == (Complex{T}[-2scale], Complex{T}[-3scale]) + # Evaluate in Float64 to avoid overflow in Float32 cubic products. + w = Float64.(scale.*T[0, 0.5, 1, 2, 10]) + @test freqresp(R, w) ≈ freqresp(G, w) rtol=sqrt(eps(T)) + # Retain distinct conjugate pairs in an actual real polynomial TF. + G = tf(T[1, 2scale, 2scale^2], T[1, 2scale, 3scale^2]) + @test length(last(roots_of(minreal(G)))) == 2 + + # Multiple nearby roots must consume a matching zero only once. + G = zpk(T[-scale, -scale*(1+8sqrt(eps(T)))], T[-scale, -scale], one(T)) + R = minreal(G) + @test length(first(roots_of(R))) == length(last(roots_of(R))) == 1 + end + for Ts in (0.01, 1, 100) + G = zpk([0.25, 0.5], [0.25, 0.75], 2.0, Ts) + R = minreal(G) + @test R.Ts == Ts + @test roots_of(R) == ([0.5], [0.75]) + @test freqresp(R, [0, 0.1, 1]./Ts) ≈ freqresp(G, [0, 0.1, 1]./Ts) + end + f = zpk([-2e6], [-1e6, -3e6, -4e6], 1e12) + @test length(last(roots_of(f+f))) == 3 + @test evalfr(f+f, 1e6im) ≈ 2evalfr(f, 1e6im) + + # Apply the policy independently to every matrix entry. + G = [tf([1, 1.5e-8], [1, 1e-8]) tf([1, 2, 1], [1, 3, 2])] + _, ps, _ = zpkdata(minreal(G)) + @test length.(ps) == [1 1] + @test dcgain(minreal(G)) ≈ dcgain(G) + end + + @testset "Independent polynomial common factors" begin + rng = MersenneTwister(1081) + for T in (Float32, Float64), scale in T.((1e-12, 1, 1e12)), _ in 1:20 + # Separated simple roots keep conditioning out of this regression. + c, a, b = T(0.5)+rand(rng,T), T(3)+rand(rng,T), T(6)+rand(rng,T) + G = tf(T[1, (c+a)*scale, c*a*scale^2], + T[1, (c+b)*scale, c*b*scale^2]) + R = minreal(G) + @test length(first(roots_of(R))) == length(last(roots_of(R))) == 1 + @test dcgain(R)[] ≈ a/b rtol=sqrt(eps(T)) + @test freqresp(R, scale.*T[0, 1, 10]) ≈ + freqresp(G, scale.*T[0, 1, 10]) rtol=sqrt(eps(T)) + # Independently evaluate the original rounded coefficients, without + # computing their roots or using the same frequency-response path. + s = Complex{BigFloat}(0, BigFloat(scale)) + reference = evalpoly(s, reverse(BigFloat.(only(numvec(G))))) / + evalpoly(s, reverse(BigFloat.(only(denvec(G))))) + @test evalfr(R, s)[] ≈ reference rtol=sqrt(eps(T)) + end + end +end From bd67a1b75ece81e68518a8c2c2de21ac0077b616 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Wed, 21 Oct 2026 19:22:42 +0000 Subject: [PATCH 2/3] Preserve unmatched roots in complex minreal cancellation --- .../src/types/SisoTfTypes/SisoZpk.jl | 5 ++- lib/ControlSystemsBase/test/test_minreal.jl | 40 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoZpk.jl b/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoZpk.jl index 6ff4bb619..dfe5c24e2 100644 --- a/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoZpk.jl +++ b/lib/ControlSystemsBase/src/types/SisoTfTypes/SisoZpk.jl @@ -101,10 +101,11 @@ function minreal(sys::SisoZpk{T,TR}, tol::Union{Real,Nothing}=nothing) where {T, end if distance < threshold - if imag(p) == 0 && imag(newZ[zidx]) != 0 && zidx < length(newZ) + # Only real-coefficient models enforce adjacent conjugate pairs. + if T <: Real && imag(p) == 0 && imag(newZ[zidx]) != 0 && zidx < length(newZ) newZ[zidx+1] = real(newZ[zidx+1]) end - if imag(newZ[zidx]) == 0 && imag(p) != 0 + if T <: Real && imag(newZ[zidx]) == 0 && imag(p) != 0 pidx += 1 pidx > length(sys.p) && (deleteat!(newZ, zidx); break) p = real(sys.p[pidx]) diff --git a/lib/ControlSystemsBase/test/test_minreal.jl b/lib/ControlSystemsBase/test/test_minreal.jl index 5173b81c1..e1145cfb6 100644 --- a/lib/ControlSystemsBase/test/test_minreal.jl +++ b/lib/ControlSystemsBase/test/test_minreal.jl @@ -108,6 +108,46 @@ @test dcgain(minreal(G)) ≈ dcgain(G) end + @testset "Cancellation in complex-coefficient models" begin + for scale in (1.0, 1e6), k in (1.0+0im, 1.0+im), + tol in (nothing, 1e-8scale), reverse_order in (false, true) + r = complex(-scale) + c = r + 1e-10scale*im + q = 2scale*im + roots = reverse_order ? [q, c] : [c, q] + G = zpk([r], roots, k) + H = zpk(roots, [r], k) + for (model, expected) in ((G, (ComplexF64[], [q])), + (H, ([q], ComplexF64[]))) + original = deepcopy(zpkdata(model)) + reduced = @inferred minreal(model, tol) + @test roots_of(reduced) == expected + @test zpkdata(reduced)[3][] == k + @test evalfr(reduced, 0) ≈ evalfr(model, 0) rtol=1e-8 + @test zpkdata(model) == original + end + end + + # Only real-coefficient models require the remaining conjugate to be real. + r = -2.0 + c = r + 1e-10im + for tol in (nothing, sqrt(eps())) + for k in (1.0, 1.0+0im) + remaining = k isa Real ? complex(r) : conj(c) + G = zpk([r], [c, conj(c)], k) + H = zpk([c, conj(c)], [r], k) + @test roots_of(minreal(G, tol)) == (ComplexF64[], [remaining]) + @test roots_of(minreal(H, tol)) == ([remaining], ComplexF64[]) + end + end + + G = zpk(ComplexF64[-1e6], ComplexF64[-1e6+0.001im, 2e6im], 1.0+0im) + expected = (ComplexF64[], ComplexF64[2e6im]) + @test roots_of(minreal(G)) == expected + @test roots_of(G + 0) == expected + @test evalfr(minreal(tf(G)), 0) ≈ evalfr(G, 0) rtol=1e-8 + end + @testset "Independent polynomial common factors" begin rng = MersenneTwister(1081) for T in (Float32, Float64), scale in T.((1e-12, 1, 1e12)), _ in 1:20 From 9e834100167b3a47bfc70a448ca63a9c5320b680 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Thu, 22 Oct 2026 05:27:45 +0000 Subject: [PATCH 3/3] Clarify transfer-function minreal test filename --- lib/ControlSystemsBase/test/runtests.jl | 2 +- .../test/{test_minreal.jl => test_tf_minreal.jl} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename lib/ControlSystemsBase/test/{test_minreal.jl => test_tf_minreal.jl} (100%) diff --git a/lib/ControlSystemsBase/test/runtests.jl b/lib/ControlSystemsBase/test/runtests.jl index 624dfca93..5f63ea64b 100644 --- a/lib/ControlSystemsBase/test/runtests.jl +++ b/lib/ControlSystemsBase/test/runtests.jl @@ -27,7 +27,7 @@ my_tests = [ "test_staticsystems", "test_transferfunction", "test_zpk", - "test_minreal", + "test_tf_minreal", "test_promotion", "test_connections", "test_discrete", diff --git a/lib/ControlSystemsBase/test/test_minreal.jl b/lib/ControlSystemsBase/test/test_tf_minreal.jl similarity index 100% rename from lib/ControlSystemsBase/test/test_minreal.jl rename to lib/ControlSystemsBase/test/test_tf_minreal.jl