From 5391cb55100fe25eb3a51e0ffc7123f1b66d9674 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Thu, 22 Oct 2026 14:11:05 +0000 Subject: [PATCH 1/3] Compute signed phase margins independently of Bode phase branches --- lib/ControlSystemsBase/src/analysis.jl | 44 ++++++------ lib/ControlSystemsBase/test/runtests.jl | 1 + lib/ControlSystemsBase/test/test_analysis.jl | 2 +- .../test/test_margin_phase.jl | 67 +++++++++++++++++++ 4 files changed, 88 insertions(+), 26 deletions(-) create mode 100644 lib/ControlSystemsBase/test/test_margin_phase.jl diff --git a/lib/ControlSystemsBase/src/analysis.jl b/lib/ControlSystemsBase/src/analysis.jl index 3d3616f65..335673c3a 100644 --- a/lib/ControlSystemsBase/src/analysis.jl +++ b/lib/ControlSystemsBase/src/analysis.jl @@ -523,13 +523,14 @@ end returns frequencies for gain margins, gain margins (magnitude), frequencies for phase margins, phase margins (degrees) -- If `!allMargins`, return only the smallest margin +- Phase margins are signed angles in `[-180°, 180°)`, independent of the unwrapped Bode phase. +- If `!allMargins`, return the smallest gain margin and the phase margin closest to zero - If `full` return also `fullPhase` - If `w` is omitted, a gain-aware default frequency range is computed for each input-output channel separately, so that `margin(sys)` and `margin(sys[i, j])` agree for channel `(i, j)`. An explicit frequency vector is used for all channels and limits margin detection to that range. -- `adjust_phase_start`: If true, the phase will be adjusted so that it starts at -90*intexcess degrees, where `intexcess` is the integrator excess of the system. +- `adjust_phase_start`: If true, adjust the unwrapped phase returned with `full=true` and used for plotting so that it starts at -90*intexcess degrees, where `intexcess` is the integrator excess. This does not affect the margins. - `balance`: Call [`balance_statespace`](@ref) on each SISO channel before computing the frequency response, see [`freqresp`](@ref). See also [`delaymargin`](@ref) and [`RobustAndOptimalControl.diskmargin`](https://juliacontrol.github.io/RobustAndOptimalControl.jl/dev/api/#RobustAndOptimalControl.diskmargin) @@ -576,7 +577,7 @@ _sminreal(sys::LTISystem) = sys """ ωgm, gm, ωpm, pm = sisomargin(sys::LTISystem, w::Vector; full=false, allMargins=false, adjust_phase_start=true, balance=true)) -Return frequencies for gain margins, gain margins, frequencies for phase margins, phase margins. If `allMargins=false`, only the smallest margins are returned. +Return gain-margin frequencies, gain margins, phase-margin frequencies, and signed phase margins in `[-180°, 180°)`. If `allMargins=false`, return the smallest gain margin and the phase margin closest to zero. `balance`: Call [`balance_statespace`](@ref) on the system before computing the frequency response, see [`freqresp`](@ref). """ @@ -612,18 +613,15 @@ function sisomargin(sys::LTISystem, w::AbstractVector{<:Real}; full=false, allMa wpm, fi = _allGainCrossings(w, mag) pm = similar(wpm) for i = eachindex(wpm) - # We have to access the actual phase value from the `phase` array to get unwrapped phase. This value is not fully accurate since it is computed at a grid point, so we compute the more accurate phase at the interpolated frequency. This accurate value is not unwrapped, so we add an integer multiple of 360 to get the closest unwrapped phase. - φ_nom = rad2deg(angle(freqresp(sys, wpm[i]; balance=false)[1])) - φ_rounded = phase[clamp(round(Int, fi[i]), 1, length(phase))] # fi is interpolated, so we round to the closest integer - φ_int = φ_nom - 360 * round( (φ_nom - φ_rounded) / 360 ) - - # Now compute phase margin relative to -180: - pm[i] = 180 + φ_int + # Measure the signed angle to the nearest negative-real-axis crossing. + φ = rad2deg(angle(freqresp(sys, wpm[i]; balance=false)[1])) + pm[i] = mod(φ, 360) - 180 end if !allMargins #Only output the smallest margins gm, idx = findmin([gm;Inf]) wgm = [wgm;NaN][idx] - pm, idx = findmin([pm;Inf]) + _, idx = findmin(abs.([pm;Inf])) + pm = [pm;Inf][idx] fi = [fi;NaN][idx] wpm = [wpm;NaN][idx] if full @@ -639,18 +637,13 @@ function sisomargin(sys::LTISystem, w::AbstractVector{<:Real}; full=false, allMa fullPhase = interpolate(fi, phase) end end - if adjust_phase_start && isrational(sys) - intexcess, p, z, tol = integrator_excess_with_tol(sys) - n_unstable_poles = - iscontinuous(sys) ? count(real(pi) > tol for pi in p) : - count(abs(pi) > 1 + tol for pi in p) + if full && adjust_phase_start && isrational(sys) + intexcess = integrator_excess(sys) first_positive_freq_ind = findfirst(>(0), w) if intexcess != 0 && (first_positive_freq_ind !== nothing) # Snap phase so that it starts at -90*intexcess nineties = round(Int, phase[first_positive_freq_ind] / 90) adjust = ((90*(-intexcess-nineties)) ÷ 360) * 360 - pm_unstable_adjust = n_unstable_poles*360 # count the number of unstable poles, and remove 360 for each. Be careful with poles that are counted as integrators - pm = pm .+ adjust .- pm_unstable_adjust phase .+= adjust fullPhase = fullPhase .+ adjust end @@ -716,7 +709,7 @@ end Return the delay margin, dₘ. For discrete-time systems, the delay margin is normalized by the sample time, i.e., the value represents the margin in number of sample times. Only supports SISO systems. -The delay margin is computed as the phase margin in radians divided by the cross-over frequency in rad/s. The delay margin is the maximum time delay that can be added to the system before it becomes unstable. +For a nominally stable closed loop, the delay margin is the maximum additional time delay before loss of stability. At each gain crossover, the nonnegative phase lag to the negative real axis is divided by the absolute crossover frequency. The smallest of these delays is returned. Closed-loop stability without delay is assumed, not checked. `balance`: Call [`balance_statespace`](@ref) on the system before computing the frequency response, see [`freqresp`](@ref). """ @@ -725,13 +718,14 @@ function delaymargin(G::LTISystem; balance=true) issiso(G) || error("delaymargin only supports SISO systems") ωgₘ, gₘ, ωϕₘa, ϕₘa = margin(G; allMargins=true, balance) isempty(ϕₘa[1]) && return Inf - ϕₘ, i = findmin(sign.(ωϕₘa[1]) .* ϕₘa[1]) # flip sign of negative frequency margins - ϕₘ *= π/180 - ωϕₘ = ωϕₘa[1][i] - if numeric_type(G) <: Real - ωϕₘ = abs(ωϕₘ) + dₘ = oftype(float(real(zero(numeric_type(G)))), Inf) + for (ω, ϕ) in zip(ωϕₘa[1], ϕₘa[1]) + ω, ϕ = real(ω), real(ϕ) + # A delay rotates positive and negative frequencies in opposite directions. + lag = mod(ω < 0 ? -ϕ : ϕ, 360) + candidate = iszero(ω) ? (iszero(lag) ? zero(dₘ) : oftype(dₘ, Inf)) : deg2rad(lag)/abs(ω) + dₘ = min(dₘ, candidate) end - dₘ = ϕₘ/ωϕₘ if isdiscrete(G) dₘ /= G.Ts # Give delay margin in number of sample times, as matlab does end diff --git a/lib/ControlSystemsBase/test/runtests.jl b/lib/ControlSystemsBase/test/runtests.jl index 5f63ea64b..3fa62e450 100644 --- a/lib/ControlSystemsBase/test/runtests.jl +++ b/lib/ControlSystemsBase/test/runtests.jl @@ -38,6 +38,7 @@ my_tests = [ "test_freqresp", "test_timeresp", "test_analysis", + "test_margin_phase", "test_matrix_comps", "test_synthesis", "test_pid_design", diff --git a/lib/ControlSystemsBase/test/test_analysis.jl b/lib/ControlSystemsBase/test/test_analysis.jl index a4c76751e..78c423808 100644 --- a/lib/ControlSystemsBase/test/test_analysis.jl +++ b/lib/ControlSystemsBase/test/test_analysis.jl @@ -491,7 +491,7 @@ OL = (ss(Cb)*ss(C1)*ss(C2)*ss(C3)*exp(-3*tau*s))/((C1 - a*s)*(C2 - a*s)*(C3 - a* @test ControlSystemsBase._default_freq_vector(OL, Val(:margin)) == ControlSystemsBase._default_freq_vector(OL, Val(:bode)) wgm, gm, ωϕₘ, ϕₘ = margin(OL; full=true, allMargins=true) -@test ϕₘ[][] ≈ -320 rtol=1e-2 +@test ϕₘ[][] ≈ 40 atol=0.1 for wgm in wgm[] @test mod(rad2deg(angle(freqresp(OL, wgm)[])), 360)-180 ≈ 0 atol=1e-1 end diff --git a/lib/ControlSystemsBase/test/test_margin_phase.jl b/lib/ControlSystemsBase/test/test_margin_phase.jl new file mode 100644 index 000000000..24c2a872f --- /dev/null +++ b/lib/ControlSystemsBase/test/test_margin_phase.jl @@ -0,0 +1,67 @@ +@testset "Phase margin branches" begin + s = tf("s") + for ε in (0.0, 1e-6, 1e-4), representation in (tf, zpk, ss) + L = representation(2.7(s+1)^2/((s-ε)^2*(s+ε))) + @test isstable(feedback(L)) + ε == 0 || @test ControlSystemsBase.count_integrators(L) == 0 + for adjust in (false, true) + m = margin(L; full=true, adjust_phase_start=adjust) + ω = m.wpm[] + expected = rad2deg(2atan(ω) - π/2 - atan(ε/ω)) + @test m.pm[] ≈ expected atol=1e-7 + @test margin(L; adjust_phase_start=adjust).pm[] ≈ m.pm[] + all = margin(L; allMargins=true, adjust_phase_start=adjust) + @test only(all.pm[]) ≈ m.pm[] + @test only(all.wpm[]) ≈ ω + @test rem(m.fullPhase[] - m.pm[] + 180, 360, RoundNearest) ≈ 0 atol=0.02 + end + τ = delaymargin(L) + @test τ ≈ (2atan(3) - π/2 - atan(ε/3))/3 rtol=5e-4 + @test isstable(feedback(L*pade(0.95τ, 6))) + @test !isstable(feedback(L*pade(1.05τ, 6))) + end + + # Starting the grid above the displaced poles selects a different Bode phase branch. + L = ss(2.7(s+1)^2/((s-1e-4)^2*(s+1e-4))) + local_grid = [2.0, 3.0, 4.0] + wide_grid = [0.0; exp10.(range(-7, 0; length=100)); local_grid] + @test margin(L, local_grid).pm[] ≈ margin(L, wide_grid).pm[] + + # Excess phase lag must produce a negative signed margin. + L = 27/(s+1)^3 + m = margin(L, [1.0, sqrt(8), 4.0]) + @test m.pm[] ≈ 180 - 3rad2deg(atan(sqrt(8))) atol=0.02 + @test m.pm[] < 0 + + # Delay contributes phase revolutions without changing gain crossovers. + L = 2/(s+1) + ω = margin(L).wpm[] + m = margin(L*delay(2π/ω)) + @test m.pm[] ≈ margin(L).pm[] atol=0.02 + + # Discrete-time delay margins are measured in sample intervals. + Ts = 0.2 + Ld = tf([0.5], [1, -1], Ts) + ω = 2asin(0.25)/Ts + expected = (π/2 - ω*Ts/2)/(ω*Ts) + @test delaymargin(Ld) ≈ expected rtol=1e-3 + + # The smallest phase margin and smallest delay occur at different crossovers. + L = 0.5/(s^2+0.2s+1) + 20/(s^2+2s+100) + @test isstable(feedback(L)) + @test length(margin(L; allMargins=true).wpm[]) == 4 + @test margin(L).wpm[] ≈ 1.16742 rtol=1e-3 + τ = delaymargin(L) + @test τ ≈ 0.15874 rtol=1e-3 + @test isstable(feedback(L*pade(0.95τ, 6))) + @test !isstable(feedback(L*pade(1.05τ, 6))) + + # Select the margin closest to zero, rather than the most negative margin. + m = margin(-L) + @test m.pm[] ≈ -9.37304 atol=0.02 + @test m.wpm[] ≈ 0.62356 rtol=1e-3 + + @test delaymargin(tf(0.1, [1, 1])) == Inf + @test delaymargin(tf(1, [1, 1])) == Inf + @test delaymargin(tf(-1, [1, 1])) == 0 +end From 417051b32b04be5aeeac6bcab650dcc15f0f4538 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Tue, 3 Nov 2026 07:21:31 +0000 Subject: [PATCH 2/3] Determine closed-loop stability in delaymargin and add delay_stability_intervals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The delay margin was computed from the phase margins under the assumption of a nominally stable closed loop, and returned a positive finite value for unstable closed loops. The closed-loop poles of 1 + G(s)e^{-sθ} reach the imaginary axis only at the gain crossovers of G, for total delays θ_k = (lag + 2πk)/ω, and the sign of the real part of ds/dθ is -sign(ω d|G|/dω). Starting from the number of unstable poles of feedback(G), the number of unstable poles for every delay follows by counting the crossings. This applies to rational loops and to loops G(s)e^{-sT} with a single input or output delay. - delaymargin returns NaN for an unstable closed loop, 0 for a closed loop with poles on the stability boundary, and the first loss of stability otherwise. Other delay systems retain the previous computation with a warning. - delay_stability_intervals returns all intervals of additional delay with an asymptotically stable closed loop. - Gain crossover frequencies are refined by Newton iteration, which corrects the delay margin of the four-crossover test loop from 0.15874 to 0.15644. - Marginplots select the displayed phase margins by absolute value. - Tests use an argument-principle count of the exact delayed loop as the reference instead of Padé approximations. Co-Authored-By: Claude Opus 5.5 --- .../src/ControlSystemsBase.jl | 1 + lib/ControlSystemsBase/src/analysis.jl | 231 +++++++++++++++++- lib/ControlSystemsBase/src/plotting.jl | 2 +- lib/ControlSystemsBase/test/test_freqresp.jl | 2 +- .../test/test_margin_phase.jl | 125 +++++++++- 5 files changed, 344 insertions(+), 17 deletions(-) diff --git a/lib/ControlSystemsBase/src/ControlSystemsBase.jl b/lib/ControlSystemsBase/src/ControlSystemsBase.jl index daa8f6b1d..1b8bc4a29 100644 --- a/lib/ControlSystemsBase/src/ControlSystemsBase.jl +++ b/lib/ControlSystemsBase/src/ControlSystemsBase.jl @@ -65,6 +65,7 @@ export LTISystem, markovparam, margin, delaymargin, + delay_stability_intervals, gangoffour, extended_gangoffour, relative_gain_array, diff --git a/lib/ControlSystemsBase/src/analysis.jl b/lib/ControlSystemsBase/src/analysis.jl index 335673c3a..760aa1c3e 100644 --- a/lib/ControlSystemsBase/src/analysis.jl +++ b/lib/ControlSystemsBase/src/analysis.jl @@ -525,6 +525,7 @@ returns frequencies for gain margins, gain margins (magnitude), frequencies for - Phase margins are signed angles in `[-180°, 180°)`, independent of the unwrapped Bode phase. - If `!allMargins`, return the smallest gain margin and the phase margin closest to zero +- The sign of a phase margin does not determine the stability of the closed loop. An open-loop unstable system may have a stable closed loop with a negative phase margin, and a system with several gain crossovers may have an unstable closed loop with a positive phase margin at the crossover closest to zero. Use [`isstable`](@ref)`(feedback(sys))`, [`delaymargin`](@ref), or a Nyquist plot to assess stability. - If `full` return also `fullPhase` - If `w` is omitted, a gain-aware default frequency range is computed for each input-output channel separately, so that `margin(sys)` and `margin(sys[i, j])` @@ -533,7 +534,7 @@ returns frequencies for gain margins, gain margins (magnitude), frequencies for - `adjust_phase_start`: If true, adjust the unwrapped phase returned with `full=true` and used for plotting so that it starts at -90*intexcess degrees, where `intexcess` is the integrator excess. This does not affect the margins. - `balance`: Call [`balance_statespace`](@ref) on each SISO channel before computing the frequency response, see [`freqresp`](@ref). -See also [`delaymargin`](@ref) and [`RobustAndOptimalControl.diskmargin`](https://juliacontrol.github.io/RobustAndOptimalControl.jl/dev/api/#RobustAndOptimalControl.diskmargin) +See also [`delaymargin`](@ref), [`delay_stability_intervals`](@ref) and [`RobustAndOptimalControl.diskmargin`](https://juliacontrol.github.io/RobustAndOptimalControl.jl/dev/api/#RobustAndOptimalControl.diskmargin) """ margin(sys::LTISystem, w::AbstractVector{<:Real}; kwargs...) = _margin(sys, (i, j) -> w; kwargs...) @@ -704,18 +705,232 @@ function _findCrossings(w, n, res; filter_th=Inf) end """ - dₘ = delaymargin(G::LTISystem; balance=true) + dₘ = delaymargin(L::LTISystem; balance=true) -Return the delay margin, dₘ. For discrete-time systems, the delay margin is normalized by the sample time, i.e., the value represents the margin in number of sample times. -Only supports SISO systems. +Return the delay margin dₘ of the negative feedback interconnection with the SISO loop-transfer function `L`. The delay margin is the largest additional time delay such that the closed loop is asymptotically stable for every additional delay in `[0, dₘ)`. For discrete-time systems, the delay margin is normalized by the sample time, i.e., the value represents the margin in number of sample intervals. -For a nominally stable closed loop, the delay margin is the maximum additional time delay before loss of stability. At each gain crossover, the nonnegative phase lag to the negative real axis is divided by the absolute crossover frequency. The smallest of these delays is returned. Closed-loop stability without delay is assumed, not checked. +- `dₘ = Inf` if no additional delay results in loss of stability. +- `dₘ = 0` if the closed loop without additional delay has poles on the stability boundary, or if every positive additional delay results in an unstable closed loop (continuous-time `L` with `|L(j∞)| ≥ 1`). +- `dₘ = NaN` if the closed loop without additional delay is unstable. The delay margin is not defined in this case. Some intervals of additional delay may nevertheless result in a stable closed loop, see [`delay_stability_intervals`](@ref). + +The stability of the closed loop without additional delay is determined if `L` is rational or of the form `G(s)e^{-sT}` with rational `G`, i.e., a loop with a single input or output delay. For other delay systems, it cannot be determined; a warning is emitted, nominal stability is assumed, and the margin is computed from the phase margins at the gain crossovers. + +See [`delay_stability_intervals`](@ref) for a description of the method. + +`balance`: Call [`balance_statespace`](@ref) on the system before computing the frequency response, see [`freqresp`](@ref). +""" +function delaymargin(L::LTISystem; balance=true) + issiso(L) || error("delaymargin only supports SISO systems") + G, T = _delay_free_part(L) + G === nothing && return _delaymargin_assuming_stability(L; balance) + data = _delay_crossing_data(G; balance) + F = typeof(data.scale) + T = F(T) + if data.neutral + # A root chain approaches the imaginary axis from the right for every positive total delay + dₘ = iszero(T) && data.Z0 == 0 ? zero(F) : F(NaN) + else + Z, onaxis = _unstable_count_at(data, T) + if Z > 0 + dₘ = F(NaN) + elseif data.axis_root || onaxis + dₘ = zero(F) + else + dₘ = _next_crossing(data, T) - T + end + end + isdiscrete(L) ? dₘ / L.Ts : dₘ +end + +""" + intervals = delay_stability_intervals(L::LTISystem; balance=true) + +Return the open intervals `(τ₁, τ₂)` of additional time delay `τ` for which the negative feedback interconnection with the SISO loop-transfer function `L(s)e^{-sτ}` is asymptotically stable, in increasing order. The vector is empty if no additional delay results in a stable closed loop. For discrete-time systems, the delays are given in sample intervals, and only integer delays are realizable. + +`L` must be rational or of the form `G(s)e^{-sT}` with rational `G`, i.e., a loop with a single input or output delay `T`. Negative values of `τ`, down to `-T`, correspond to a reduction of the delay `T`. + +The first interval contains `τ = 0` if and only if the closed loop without additional delay is asymptotically stable, and its upper bound is then the delay margin, see [`delaymargin`](@ref). Further intervals arise if the closed loop regains stability for larger delays, or if the closed loop is unstable without additional delay but is stabilized by a delay. + +# Method +The closed-loop poles are the roots of `1 + G(s)e^{-sθ} = 0`, where `θ = T + τ` is the total delay. Since `|e^{-jωθ}| = 1`, a root is located on the imaginary axis at `s = jω` only if `ω` is a gain crossover frequency, `|G(jω)| = 1`, and only for the total delays +```math +θ_k = \\frac{\\operatorname{mod}(\\arg G(jω) + π, 2π) + 2πk}{ω}, \\quad k = 0, 1, 2, … +``` +Implicit differentiation of the characteristic equation yields +```math +\\operatorname{sign} \\operatorname{Re} \\frac{ds}{dθ} = -\\operatorname{sign}\\left(ω \\frac{d|G(jω)|}{dω}\\right), +``` +i.e., a pair of roots enters the right half-plane at a crossover at which `|G|` decreases with frequency, and leaves it at a crossover at which `|G|` increases with frequency, independently of `θ`. The number of unstable closed-loop poles for `θ = 0` is computed from the poles of `feedback(G)`, and the number for every other total delay follows by counting the crossings. For continuous-time `G` with `|G(j∞)| < 1`, the destabilizing crossings occur more frequently than the stabilizing crossings, so the number of stable intervals is finite. For `|G(j∞)| ≥ 1`, the delayed loop is of neutral type and is not asymptotically stable for any positive total delay. + +The gain crossovers are located by [`margin`](@ref) on its default frequency grid and subsequently refined. A crossover that is not detected on the grid is not taken into account. `balance`: Call [`balance_statespace`](@ref) on the system before computing the frequency response, see [`freqresp`](@ref). """ -function delaymargin(G::LTISystem; balance=true) - # Phase margin in radians divided by cross-over frequency in rad/s. - issiso(G) || error("delaymargin only supports SISO systems") +function delay_stability_intervals(L::LTISystem; balance=true) + issiso(L) || error("delay_stability_intervals only supports SISO systems") + G, T = _delay_free_part(L) + G === nothing && throw(ArgumentError("delay_stability_intervals requires a rational loop-transfer function or a rational loop-transfer function with a single input or output delay")) + data = _delay_crossing_data(G; balance) + F = typeof(data.scale) + T = F(T) + intervals = Tuple{F,F}[] + (data.neutral || data.axis_root) && return intervals + crossings = data.crossings + twoπ = 2*F(π) + if isempty(crossings) + data.Z0 == 0 && push!(intervals, (zero(F), F(Inf))) + else + destab = filter(c -> c.dir > 0, crossings) + stab = filter(c -> c.dir < 0, crossings) + Ωd = sum(c -> c.w*c.ω, destab; init=zero(F)) + Ωs = sum(c -> c.w*c.ω, stab; init=zero(F)) + Ωd > Ωs || throw(ArgumentError("The stabilizing crossings occur at least as frequently as the destabilizing crossings, so the stable delay intervals are not bounded. This occurs for a discrete-time loop gain larger than one at the Nyquist frequency.")) + # For total delays above θmax, a lower bound of the number of unstable poles is positive + num = sum(c -> c.w*c.lag, destab; init=zero(F)) - sum(c -> c.w*c.lag, stab; init=zero(F)) + + twoπ*(sum(c -> c.w, stab; init=0) - data.Z0) + θmax = max(zero(F), num/(Ωd - Ωs)) + events = Tuple{F,Int}[] + for c in crossings, k in 0:floor(Int, (c.ω*θmax - c.lag)/twoπ) + if iszero(c.lag) && k == 0 + # Z0 does not count the root on the imaginary axis at θ = 0 + push!(events, (zero(F), c.dir > 0 ? c.w : 0)) + else + push!(events, ((c.lag + twoπ*k)/c.ω, c.w*c.dir)) + end + end + sort!(events, by=first) + Z = data.Z0 + prev = zero(F) + i = 1 + while i <= length(events) + θ = events[i][1] + ΔZ = 0 + while i <= length(events) && events[i][1] - θ <= _delay_tol(data, θ) + ΔZ += events[i][2] + i += 1 + end + Z == 0 && θ - prev > _delay_tol(data, prev) && push!(intervals, (prev, θ)) + Z += ΔZ + Z < 0 && @warn "The computed number of unstable closed-loop poles is negative. A gain crossover may have been missed." maxlog=1 + prev = θ + end + Z == 0 && push!(intervals, (prev, _next_crossing(data, prev))) + end + Ts = isdiscrete(L) ? F(L.Ts) : one(F) + Tuple{F,F}[((a - T)/Ts, (b - T)/Ts) for (a, b) in intervals] +end + +# Return a rational G and a delay T such that L(s) = G(s)e^{-sT}, or (nothing, 0) if L does not have this form +_delay_free_part(L::LTISystem) = isrational(L) ? (L, 0) : (nothing, 0) +function _delay_free_part(L::DelayLtiSystem) + P, Tau = L.P, L.Tau + isempty(Tau) && return P.P, 0 + all(==(Tau[1]), Tau) || return nothing, 0 + P11 = ss(P.A, P.B1, P.C1, P.D11) + P22 = ss(P.A, P.B2, P.C2, P.D22) + (_iszero_transfer(P11) && _iszero_transfer(P22)) || return nothing, 0 + # With P11 = P22 = 0 and equal delays, L = P12*P21*e^{-sT} + G = sminreal(ss(P.A, P.B2, P.C1, P.D12) * ss(P.A, P.B1, P.C2, P.D21)) + if G.nx > P.P.nx + # The series connection duplicates the common dynamics + G = robust_minreal(G) + end + G, Tau[1] +end + +function _iszero_transfer(sys::AbstractStateSpace) + s = sminreal(sys) + iszero(s.D) && (s.nx == 0 || iszero(s.B) || iszero(s.C)) +end + +function _delay_crossing_data(G::LTISystem; balance) + sys = _balance(_sminreal(ss(G)), balance) + F = float(real(numeric_type(sys))) + realsys = numeric_type(sys) <: Real + resp(ω) = freqresp(sys, ω; balance=false)[1] + function dlogmag(ω) + h = cbrt(eps(F))*abs(ω) + (log(abs(resp(ω + h))) - log(abs(resp(ω - h))))/(2h) + end + m = margin(sys; allMargins=true, balance=false) + crossings = NamedTuple{(:ω, :lag, :w, :dir), Tuple{F,F,Int,Int}}[] + axis_root = false + refined = F[] + for ω in m.wpm[1] + ω = F(real(ω)) + if iszero(ω) + # The root is located at s = 0 for every delay if G(0) = -1 + axis_root |= abs(resp(ω) + 1) <= sqrt(eps(F)) + continue + end + realsys && ω < 0 && continue + # Newton iteration on log|G(jω)| = 0 refines the interpolated crossover frequency + for _ in 1:10 + step = log(abs(resp(ω)))/dlogmag(ω) + ωnew = ω - step + (isfinite(step) && abs(step) < abs(ω)/10) || break + isdiscrete(sys) && abs(ωnew)*sys.Ts > π && break + ω = ωnew + abs(step) <= 4eps(F)*abs(ω) && break + end + # Two grid crossings may converge to the same crossover + any(ωr -> abs(ωr - ω) <= sqrt(eps(F))*abs(ω), refined) && continue + push!(refined, ω) + a = dlogmag(ω) + abs(a*ω) > sqrt(eps(F)) || error("The gain crossover at ω = $ω is tangential, the direction in which the closed-loop poles cross the imaginary axis is undetermined") + φ = F(angle(resp(ω))) + # A delay θ places a root at s = jω if ωθ ≡ arg G(jω) + π (mod 2π) + lag = mod(ω > 0 ? φ + F(π) : -(φ + F(π)), 2*F(π)) + lag > 2*F(π) - sqrt(eps(F)) && (lag = zero(F)) + # A real-coefficient system has a complex-conjugate pair of crossing roots, except for a real root at the Nyquist frequency + w = realsys && !(isdiscrete(sys) && abs(abs(ω)*sys.Ts - π) <= sqrt(eps(F))) ? 2 : 1 + push!(crossings, (; ω=abs(ω), lag, w, dir=-Int(sign(ω*a)))) + end + p = poles(feedback(sys)) + Z0 = isdiscrete(sys) ? count(p -> abs(p) > 1 + sqrt(eps(F)), p) : + count(p -> real(p) > sqrt(eps(F))*max(1, abs(p)), p) + neutral = iscontinuous(sys) && abs(sys.D[1]) >= 1 + scale = isempty(crossings) ? one(F) : inv(maximum(c -> c.ω, crossings)) + (; crossings, Z0, axis_root, neutral, scale) +end + +_delay_tol(data, θ) = sqrt(eps(typeof(data.scale)))*(abs(θ) + data.scale) + +# Number of closed-loop poles in the open right half-plane for the total delay θ, and whether a pole is located on the imaginary axis +function _unstable_count_at(data, θ) + F = typeof(data.scale) + tol = _delay_tol(data, θ) + Z = data.Z0 + onaxis = false + for c in data.crossings, k in 0:floor(Int, (c.ω*(θ + tol) - c.lag)/(2*F(π))) + θk = (c.lag + 2*F(π)*k)/c.ω + atzero = iszero(c.lag) && k == 0 # Z0 does not count the root on the imaginary axis at θ = 0 + if abs(θk - θ) <= tol + onaxis = true + !atzero && c.dir < 0 && (Z -= c.w) + elseif atzero + c.dir > 0 && (Z += c.w) + else + Z += c.w*c.dir + end + end + Z, onaxis +end + +# The smallest total delay larger than θ for which a closed-loop pole is located on the imaginary axis +function _next_crossing(data, θ) + F = typeof(data.scale) + tol = _delay_tol(data, θ) + θnext = F(Inf) + for c in data.crossings + k = max(0, floor(Int, (c.ω*(θ + tol) - c.lag)/(2*F(π))) + 1) + θnext = min(θnext, (c.lag + 2*F(π)*k)/c.ω) + end + θnext +end + +function _delaymargin_assuming_stability(G::LTISystem; balance) + @warn "The stability of the closed loop without additional delay cannot be determined for this delay system and is assumed in the computation of the delay margin." maxlog=1 ωgₘ, gₘ, ωϕₘa, ϕₘa = margin(G; allMargins=true, balance) isempty(ϕₘa[1]) && return Inf dₘ = oftype(float(real(zero(numeric_type(G)))), Inf) diff --git a/lib/ControlSystemsBase/src/plotting.jl b/lib/ControlSystemsBase/src/plotting.jl index e6acd6e43..b54bf3b69 100644 --- a/lib/ControlSystemsBase/src/plotting.jl +++ b/lib/ControlSystemsBase/src/plotting.jl @@ -918,7 +918,7 @@ marginplot # Let's be reasonable, only plot 5 smallest phase margins if length(pm) > 5 @warn "Only showing \"smallest\" 5 out of $(length(pm)) phase margins" - idx = sortperm(pm) + idx = sortperm(pm; by=abs) wpm = wpm[idx[1:5]] pm = pm[idx[1:5]] fullPhase = fullPhase[idx[1:5]] diff --git a/lib/ControlSystemsBase/test/test_freqresp.jl b/lib/ControlSystemsBase/test/test_freqresp.jl index d08c8c2fb..c0c9bb8bc 100644 --- a/lib/ControlSystemsBase/test/test_freqresp.jl +++ b/lib/ControlSystemsBase/test/test_freqresp.jl @@ -263,7 +263,7 @@ end @test relative_gain_array(Gbal, wbal) ≈ relative_gain_array(Gbal, wbal; balance=false) @test relative_gain_array(Gbal, 1.0) ≈ relative_gain_array(Gbal, 1.0; balance=false) @test margin(Gsiso, wbal).gm ≈ margin(Gsiso, wbal; balance=false).gm - @test delaymargin(Gsiso) ≈ delaymargin(Gsiso; balance=false) + @test delaymargin(Gsiso) ≈ delaymargin(Gsiso; balance=false) nans=true @test hinfnorm(Gbal)[1] ≈ hinfnorm(Gbal; balance=false)[1] rtol=1e-6 @test linfnorm(Gbal)[1] ≈ linfnorm(Gbal; balance=false)[1] rtol=1e-6 @test norm(Gbal) ≈ norm(Gbal; balance=false) rtol=1e-8 diff --git a/lib/ControlSystemsBase/test/test_margin_phase.jl b/lib/ControlSystemsBase/test/test_margin_phase.jl index 24c2a872f..5cced5376 100644 --- a/lib/ControlSystemsBase/test/test_margin_phase.jl +++ b/lib/ControlSystemsBase/test/test_margin_phase.jl @@ -1,3 +1,39 @@ +# Number of roots of 1 + G(s)e^{-sθ} with Re s > σ for rational G, computed with the argument principle along the line Re s = σ with an adaptively refined frequency grid. This is used as a reference that is independent of rational delay approximations. +function n_unstable_delayed(G, θ; σ=1e-7, wmax=1e7) + g = ss(G) + P = count(p -> real(p) > σ, poles(g)) + f(ω) = 1 + evalfr(g, σ + im*ω)[1]*exp(-(σ + im*ω)*θ) + w = exp10.(range(-10, log10(wmax), length=2000)) + w = [-reverse(w); 0; w] + total = 0.0 + stack = [(w[i], w[i+1], f(w[i]), f(w[i+1])) for i in length(w)-1:-1:1] + while !isempty(stack) + a, b, fa, fb = pop!(stack) + d = angle(fb/fa) + if abs(d) > 0.2 && b - a > 1e-14*max(abs(a), abs(b), 1) + m = (a + b)/2 + fm = f(m) + push!(stack, (m, b, fm, fb)) + push!(stack, (a, m, fa, fm)) + else + total += d + end + end + round(Int, P - total/2π) +end + +# Check every interval returned by delay_stability_intervals against the reference, with the total delay θ = T + τ +function check_delay_intervals(G, T, intervals) + for (a, b) in intervals + hi = isfinite(b) ? b : a + 1 + for x in range(a, hi, length=5)[2:end-1] + @test n_unstable_delayed(G, T + x) == 0 + end + T + a > 1e-6 && @test n_unstable_delayed(G, T + a - 1e-3*(b - a)) > 0 + isfinite(b) && @test n_unstable_delayed(G, T + b + 1e-3*(b - a)) > 0 + end +end + @testset "Phase margin branches" begin s = tf("s") for ε in (0.0, 1e-6, 1e-4), representation in (tf, zpk, ss) @@ -16,10 +52,12 @@ @test rem(m.fullPhase[] - m.pm[] + 180, 360, RoundNearest) ≈ 0 atol=0.02 end τ = delaymargin(L) - @test τ ≈ (2atan(3) - π/2 - atan(ε/3))/3 rtol=5e-4 - @test isstable(feedback(L*pade(0.95τ, 6))) - @test !isstable(feedback(L*pade(1.05τ, 6))) + @test τ ≈ (2atan(3) - π/2 - atan(ε/3))/3 rtol=1e-8 + intervals = delay_stability_intervals(L) + @test only(intervals) == (0, τ) end + L = 2.7(s+1)^2/((s-1e-4)^2*(s+1e-4)) + check_delay_intervals(L, 0, delay_stability_intervals(L)) # Starting the grid above the displaced poles selects a different Bode phase branch. L = ss(2.7(s+1)^2/((s-1e-4)^2*(s+1e-4))) @@ -27,6 +65,14 @@ wide_grid = [0.0; exp10.(range(-7, 0; length=100)); local_grid] @test margin(L, local_grid).pm[] ≈ margin(L, wide_grid).pm[] + # The integrator classification does not change the margins. + L = (s+0.1)^2/(s^3*(0.01s+1)) + @test margin(L; adjust_phase_start=true).pm[] == margin(L; adjust_phase_start=false).pm[] + @test margin((s+1e-9)/(s^2*(s+1))).pm[] ≈ 51.8273 atol=1e-2 + @test margin(tf([0.01], [1, -(1-1e-9)], 0.01)).pm[] ≈ 89.7135 atol=1e-2 + @test margin(tf(Float32[2.7, 5.4, 2.7], Float32[1, -1f-4, -1f-8, 1f-12])).pm[] ≈ 53.138 atol=1e-2 + @test delaymargin(tf(Float32[2.7, 5.4, 2.7], Float32[1, -1f-4, -1f-8, 1f-12])) isa Float32 + # Excess phase lag must produce a negative signed margin. L = 27/(s+1)^3 m = margin(L, [1.0, sqrt(8), 4.0]) @@ -44,7 +90,8 @@ Ld = tf([0.5], [1, -1], Ts) ω = 2asin(0.25)/Ts expected = (π/2 - ω*Ts/2)/(ω*Ts) - @test delaymargin(Ld) ≈ expected rtol=1e-3 + @test delaymargin(Ld) ≈ expected rtol=1e-8 + @test only(delay_stability_intervals(Ld)) == (0, delaymargin(Ld)) # The smallest phase margin and smallest delay occur at different crossovers. L = 0.5/(s^2+0.2s+1) + 20/(s^2+2s+100) @@ -52,9 +99,13 @@ @test length(margin(L; allMargins=true).wpm[]) == 4 @test margin(L).wpm[] ≈ 1.16742 rtol=1e-3 τ = delaymargin(L) - @test τ ≈ 0.15874 rtol=1e-3 - @test isstable(feedback(L*pade(0.95τ, 6))) - @test !isstable(feedback(L*pade(1.05τ, 6))) + @test n_unstable_delayed(L, 0.995τ) == 0 + @test n_unstable_delayed(L, 1.005τ) > 0 + # The closed loop regains stability for larger delays. + intervals = delay_stability_intervals(L) + @test length(intervals) > 1 + @test intervals[1] == (0, τ) + check_delay_intervals(L, 0, intervals) # Select the margin closest to zero, rather than the most negative margin. m = margin(-L) @@ -63,5 +114,65 @@ @test delaymargin(tf(0.1, [1, 1])) == Inf @test delaymargin(tf(1, [1, 1])) == Inf + @test only(delay_stability_intervals(tf(0.1, [1, 1]))) == (0, Inf) + # The closed-loop pole at the origin does not depend on the delay. @test delaymargin(tf(-1, [1, 1])) == 0 + @test isempty(delay_stability_intervals(tf(-1, [1, 1]))) +end + +@testset "Delay margin and closed-loop stability" begin + s = tf("s") + + # Open-loop unstable, and widely separated time scales + for L in (4(s+1)^2/((s-1)^2*(0.1s+1)), 1e7/((s+1e-4)*(s+1e4))) + τ = delaymargin(L) + @test n_unstable_delayed(L, 0.995τ) == 0 + @test n_unstable_delayed(L, 1.005τ) > 0 + @test only(delay_stability_intervals(L)) == (0, τ) + end + @test delaymargin(4(s+1)^2/((s-1)^2*(0.1s+1))) ≈ 0.04442 rtol=1e-3 + @test delaymargin(1e7/((s+1e-4)*(s+1e4))) ≈ 0.0014789 rtol=1e-3 + + # Unstable closed loops without additional delay do not have a delay margin. + for L in (27/(s+1)^3, 0.999/(s*(s^2+0.002s+1)), 2(s^2+0.01s+1.0201)/(s*(s^2+0.01s+1)*(s+1))) + @test n_unstable_delayed(L, 0) > 0 + @test isnan(delaymargin(L)) + @test isempty(delay_stability_intervals(L)) + end + + # An unstable closed loop that is stabilized by an interval of delays + L = 0.5/(s^2 - 0.1s + 1) + @test isnan(delaymargin(L)) + intervals = delay_stability_intervals(L) + @test length(intervals) == 1 + @test intervals[1][1] > 0 + check_delay_intervals(L, 0, intervals) + + # Input or output delays are part of the nominal loop. + G = 2/(s+1) + T = 0.3 + for L in (G*delay(T), delay(T)*G, ss(G)*delay(T)) + @test delaymargin(L) ≈ delaymargin(G) - T rtol=1e-8 + @test only(delay_stability_intervals(L)) == (-T, delaymargin(L)) + end + check_delay_intervals(G, T, delay_stability_intervals(G*delay(T))) + + # The phase margin of an integrator with delay π/2 is zero for unit gain. + for k in (0.9, 0.999) + @test delaymargin(k/s*delay(π/2)) ≈ π/(2k) - π/2 rtol=1e-8 + end + @test delaymargin(1/s*delay(π/2)) == 0 + @test isnan(delaymargin(1.001/s*delay(π/2))) + @test delay_stability_intervals(1.001/s*delay(π/2))[1][2] < 0 + + # A delayed loop of neutral type, |L(j∞)| > 1, is unstable for every positive delay. + L = (2s+1)/(s+3) + @test delaymargin(L) == 0 + @test isnan(delaymargin(L*delay(0.1))) + @test isempty(delay_stability_intervals(L)) + + # Internal delays: nominal stability cannot be determined. + L = feedback(1/(s+1)*delay(0.1))*(5/(s+1)) + @test_logs (:warn, r"cannot be determined") delaymargin(L) + @test_throws ArgumentError delay_stability_intervals(L) end From 2f45ed0df229dc8890063aaf6bf4266e8341a31b Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Tue, 3 Nov 2026 08:25:36 +0000 Subject: [PATCH 3/3] Address review of the delay-margin computation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Locate gain crossovers by bisection within the brackets of the default frequency grid, with an analytic derivative and a residual check, instead of Newton iteration, which left the crossover of narrow resonances. - Discrete time: count unstable poles for integer delays exactly. In addition to the interior crossings, each sample of delay adds one unstable pole if |G(-1)| > 1. delay_stability_intervals returns ranges of stable integer delays for discrete-time systems. - Mirror the frequency grid to negative frequencies for systems with complex coefficients. - Evaluate G(0) (G(1) in discrete time) directly to detect a closed-loop pole at the origin for every delay. - Scale the pole tolerance by the norm of the closed-loop system matrix, and snap small positive lags to zero. - Define stability as exponential stability, so that loops with |L(j∞)| = 1 have delay margin 0. - Harden the argument-principle reference in the tests, add a direct discrete-time reference, test all review counterexamples, and check that no stable interval is omitted. Co-Authored-By: Claude Opus 5.5 --- lib/ControlSystemsBase/src/analysis.jl | 301 +++++++++++------- .../test/test_margin_phase.jl | 104 +++++- 2 files changed, 285 insertions(+), 120 deletions(-) diff --git a/lib/ControlSystemsBase/src/analysis.jl b/lib/ControlSystemsBase/src/analysis.jl index 760aa1c3e..5603c715e 100644 --- a/lib/ControlSystemsBase/src/analysis.jl +++ b/lib/ControlSystemsBase/src/analysis.jl @@ -707,12 +707,14 @@ end """ dₘ = delaymargin(L::LTISystem; balance=true) -Return the delay margin dₘ of the negative feedback interconnection with the SISO loop-transfer function `L`. The delay margin is the largest additional time delay such that the closed loop is asymptotically stable for every additional delay in `[0, dₘ)`. For discrete-time systems, the delay margin is normalized by the sample time, i.e., the value represents the margin in number of sample intervals. +Return the delay margin dₘ of the negative feedback interconnection with the SISO loop-transfer function `L`. The delay margin is the largest additional time delay such that the closed loop is exponentially stable for every additional delay in `[0, dₘ)`. For loops with `|L(j∞)| < 1`, exponential stability is equivalent to asymptotic stability, i.e., all closed-loop poles are located in the open left half-plane. - `dₘ = Inf` if no additional delay results in loss of stability. -- `dₘ = 0` if the closed loop without additional delay has poles on the stability boundary, or if every positive additional delay results in an unstable closed loop (continuous-time `L` with `|L(j∞)| ≥ 1`). +- `dₘ = 0` if the closed loop without additional delay has poles on the stability boundary, or if every positive additional delay results in loss of exponential stability (continuous-time `L` with `|L(j∞)| ≥ 1`). - `dₘ = NaN` if the closed loop without additional delay is unstable. The delay margin is not defined in this case. Some intervals of additional delay may nevertheless result in a stable closed loop, see [`delay_stability_intervals`](@ref). +For discrete-time systems, the delay margin is normalized by the sample time, i.e., the value represents the margin in number of sample intervals. It is the smallest delay, in general a fraction of a sample interval, at which the phase of the delayed loop-transfer function at a gain crossover reaches -180°, or one sample interval if a delay of one sample results in loss of stability before that. + The stability of the closed loop without additional delay is determined if `L` is rational or of the form `G(s)e^{-sT}` with rational `G`, i.e., a loop with a single input or output delay. For other delay systems, it cannot be determined; a warning is emitted, nominal stability is assumed, and the margin is computed from the phase margins at the gain crossovers. See [`delay_stability_intervals`](@ref) for a description of the method. @@ -727,29 +729,34 @@ function delaymargin(L::LTISystem; balance=true) F = typeof(data.scale) T = F(T) if data.neutral - # A root chain approaches the imaginary axis from the right for every positive total delay - dₘ = iszero(T) && data.Z0 == 0 ? zero(F) : F(NaN) - else - Z, onaxis = _unstable_count_at(data, T) - if Z > 0 - dₘ = F(NaN) - elseif data.axis_root || onaxis - dₘ = zero(F) - else - dₘ = _next_crossing(data, T) - T - end + # For |G(j∞)| ≥ 1, a chain of roots approaches or crosses the imaginary axis for every positive total delay + data.Z0 > 0 && return F(NaN) + iszero(T) && return zero(F) + return data.Dmag > 1 + sqrt(eps(F)) ? F(NaN) : zero(F) + end + Z, onaxis = _unstable_count_at(data, T) + Z > 0 && return F(NaN) + onaxis && return zero(F) + θ1 = _next_crossing(data, T) + if data.discrete + # Between interior crossings, the count changes only at the Nyquist frequency, so a delay of one sample is the only additional candidate + Z1, onaxis1 = _unstable_count_at(data, one(F)) + θ1 > 1 && (Z1 > 0 || onaxis1) && return one(F) + return θ1 end - isdiscrete(L) ? dₘ / L.Ts : dₘ + θ1 - T end """ intervals = delay_stability_intervals(L::LTISystem; balance=true) -Return the open intervals `(τ₁, τ₂)` of additional time delay `τ` for which the negative feedback interconnection with the SISO loop-transfer function `L(s)e^{-sτ}` is asymptotically stable, in increasing order. The vector is empty if no additional delay results in a stable closed loop. For discrete-time systems, the delays are given in sample intervals, and only integer delays are realizable. +Return the additional time delays `τ` for which the negative feedback interconnection with the SISO loop-transfer function `L(s)e^{-sτ}` is exponentially stable, in increasing order. + +For continuous-time systems, the result is a vector of open intervals `(τ₁, τ₂)`. `L` must be rational or of the form `G(s)e^{-sT}` with rational `G`, i.e., a loop with a single input or output delay `T`. Negative values of `τ`, down to `-T`, correspond to a reduction of the delay `T`. The vector is empty if no additional delay results in a stable closed loop. -`L` must be rational or of the form `G(s)e^{-sT}` with rational `G`, i.e., a loop with a single input or output delay `T`. Negative values of `τ`, down to `-T`, correspond to a reduction of the delay `T`. +For discrete-time systems, the result is a vector of ranges of the integer numbers of sample intervals `d ≥ 0` for which the closed loop with loop-transfer function `L(z)z^{-d}` is stable. A range that is not bounded ends at `typemax(Int)`. -The first interval contains `τ = 0` if and only if the closed loop without additional delay is asymptotically stable, and its upper bound is then the delay margin, see [`delaymargin`](@ref). Further intervals arise if the closed loop regains stability for larger delays, or if the closed loop is unstable without additional delay but is stabilized by a delay. +If the closed loop without additional delay is stable, the first interval has the lower bound `-T` (continuous time) or the first range starts with `0` (discrete time), and the delay margin is the upper bound of this interval, see [`delaymargin`](@ref). Further intervals arise if the closed loop regains stability for larger delays, or if the closed loop is unstable without additional delay but is stabilized by a delay. # Method The closed-loop poles are the roots of `1 + G(s)e^{-sθ} = 0`, where `θ = T + τ` is the total delay. Since `|e^{-jωθ}| = 1`, a root is located on the imaginary axis at `s = jω` only if `ω` is a gain crossover frequency, `|G(jω)| = 1`, and only for the total delays @@ -760,9 +767,11 @@ Implicit differentiation of the characteristic equation yields ```math \\operatorname{sign} \\operatorname{Re} \\frac{ds}{dθ} = -\\operatorname{sign}\\left(ω \\frac{d|G(jω)|}{dω}\\right), ``` -i.e., a pair of roots enters the right half-plane at a crossover at which `|G|` decreases with frequency, and leaves it at a crossover at which `|G|` increases with frequency, independently of `θ`. The number of unstable closed-loop poles for `θ = 0` is computed from the poles of `feedback(G)`, and the number for every other total delay follows by counting the crossings. For continuous-time `G` with `|G(j∞)| < 1`, the destabilizing crossings occur more frequently than the stabilizing crossings, so the number of stable intervals is finite. For `|G(j∞)| ≥ 1`, the delayed loop is of neutral type and is not asymptotically stable for any positive total delay. +i.e., a pair of roots enters the right half-plane at a crossover at which `|G|` decreases with frequency, and leaves it at a crossover at which `|G|` increases with frequency, independently of `θ`. The number of unstable closed-loop poles for `θ = 0` is computed from the poles of `feedback(G)`, and the number for every other total delay follows by counting the crossings. For continuous-time `G` with `|G(j∞)| < 1`, the destabilizing crossings occur more frequently than the stabilizing crossings, so the number of stable intervals is finite. For `|G(j∞)| ≥ 1`, the delayed loop is of neutral type and is not exponentially stable for any positive total delay. -The gain crossovers are located by [`margin`](@ref) on its default frequency grid and subsequently refined. A crossover that is not detected on the grid is not taken into account. +For discrete-time systems, the number of closed-loop poles outside the unit circle is determined by the argument principle on the unit circle. In addition to the crossings at the gain crossovers in the interior of the Nyquist band, each additional sample of delay adds one unstable pole if `|G(-1)| > 1`. + +The gain crossovers are located on the default frequency grid of [`margin`](@ref), extended to negative frequencies for systems with complex coefficients, and are refined by bisection. A crossover that is not detected on the grid is not taken into account. `balance`: Call [`balance_statespace`](@ref) on the system before computing the frequency response, see [`freqresp`](@ref). """ @@ -773,51 +782,54 @@ function delay_stability_intervals(L::LTISystem; balance=true) data = _delay_crossing_data(G; balance) F = typeof(data.scale) T = F(T) - intervals = Tuple{F,F}[] - (data.neutral || data.axis_root) && return intervals - crossings = data.crossings - twoπ = 2*F(π) - if isempty(crossings) - data.Z0 == 0 && push!(intervals, (zero(F), F(Inf))) - else - destab = filter(c -> c.dir > 0, crossings) - stab = filter(c -> c.dir < 0, crossings) - Ωd = sum(c -> c.w*c.ω, destab; init=zero(F)) - Ωs = sum(c -> c.w*c.ω, stab; init=zero(F)) - Ωd > Ωs || throw(ArgumentError("The stabilizing crossings occur at least as frequently as the destabilizing crossings, so the stable delay intervals are not bounded. This occurs for a discrete-time loop gain larger than one at the Nyquist frequency.")) - # For total delays above θmax, a lower bound of the number of unstable poles is positive - num = sum(c -> c.w*c.lag, destab; init=zero(F)) - sum(c -> c.w*c.lag, stab; init=zero(F)) + - twoπ*(sum(c -> c.w, stab; init=0) - data.Z0) - θmax = max(zero(F), num/(Ωd - Ωs)) - events = Tuple{F,Int}[] - for c in crossings, k in 0:floor(Int, (c.ω*θmax - c.lag)/twoπ) - if iszero(c.lag) && k == 0 - # Z0 does not count the root on the imaginary axis at θ = 0 - push!(events, (zero(F), c.dir > 0 ? c.w : 0)) - else - push!(events, ((c.lag + twoπ*k)/c.ω, c.w*c.dir)) - end + if data.discrete + ranges = UnitRange{Int}[] + (data.neutral || data.axis_root) && return ranges + if isempty(data.crossings) && data.nyq_rate == 0 && !data.nyq_marginal + data.Z0 == 0 && push!(ranges, 0:typemax(Int)) + return ranges end - sort!(events, by=first) - Z = data.Z0 - prev = zero(F) - i = 1 - while i <= length(events) - θ = events[i][1] - ΔZ = 0 - while i <= length(events) && events[i][1] - θ <= _delay_tol(data, θ) - ΔZ += events[i][2] - i += 1 + dmax = ceil(Int, _delay_horizon(data)) + 1 + stable = [(Z = _unstable_count_at(data, F(d)); Z[1] == 0 && !Z[2]) for d in 0:dmax] + d = 0 + while d <= dmax + if stable[d+1] + d0 = d + while d < dmax && stable[d+2] + d += 1 + end + push!(ranges, d0:d) end - Z == 0 && θ - prev > _delay_tol(data, prev) && push!(intervals, (prev, θ)) - Z += ΔZ - Z < 0 && @warn "The computed number of unstable closed-loop poles is negative. A gain crossover may have been missed." maxlog=1 - prev = θ + d += 1 + end + return ranges + end + intervals = Tuple{F,F}[] + (data.neutral || data.axis_root) && return intervals + if isempty(data.crossings) + data.Z0 == 0 && push!(intervals, (-T, F(Inf))) + return intervals + end + events = _delay_events(data, _delay_horizon(data)) + Z = data.Z0 + prev = zero(F) + i = 1 + while i <= length(events) + θ = events[i].θ + ΔZ = 0 + while i <= length(events) && events[i].θ - θ <= _delay_tol(data, θ) + e = events[i] + # Z0 does not count the root on the imaginary axis at θ = 0 + ΔZ += e.atzero ? (e.dir > 0 ? e.w : 0) : e.w*e.dir + i += 1 end - Z == 0 && push!(intervals, (prev, _next_crossing(data, prev))) + Z == 0 && θ - prev > _delay_tol(data, prev) && push!(intervals, (prev - T, θ - T)) + Z += ΔZ + Z < 0 && @warn "The computed number of unstable closed-loop poles is negative. A gain crossover may have been missed." maxlog=1 + prev = θ end - Ts = isdiscrete(L) ? F(L.Ts) : one(F) - Tuple{F,F}[((a - T)/Ts, (b - T)/Ts) for (a, b) in intervals] + Z == 0 && push!(intervals, (prev - T, _next_crossing(data, prev) - T)) + intervals end # Return a rational G and a delay T such that L(s) = G(s)e^{-sT}, or (nothing, 0) if L does not have this form @@ -843,81 +855,146 @@ function _iszero_transfer(sys::AbstractStateSpace) iszero(s.D) && (s.nx == 0 || iszero(s.B) || iszero(s.C)) end +# Transfer function value and its derivative with respect to x ∈ {s, z} of a SISO state-space system +function _eval_with_derivative(A, B, C, D, x) + R = x*I - A + v = R \ B + (C*v)[1] + D[1], -(C*(R \ v))[1] +end + +# Frequencies are normalized by the sample time for discrete-time systems, so that ω is given in rad/sample and delays in samples function _delay_crossing_data(G::LTISystem; balance) sys = _balance(_sminreal(ss(G)), balance) F = float(real(numeric_type(sys))) + CF = Complex{F} realsys = numeric_type(sys) <: Real - resp(ω) = freqresp(sys, ω; balance=false)[1] + discrete = isdiscrete(sys) + A, B, C, D = (Matrix{CF}(M) for M in (sys.A, sys.B, sys.C, sys.D)) + x(ω) = discrete ? cis(ω) : im*ω + resp(ω) = _eval_with_derivative(A, B, C, D, x(ω))[1] function dlogmag(ω) - h = cbrt(eps(F))*abs(ω) - (log(abs(resp(ω + h))) - log(abs(resp(ω - h))))/(2h) + g, dg = _eval_with_derivative(A, B, C, D, x(ω)) + # dG/dω = j dG/ds = j z dG/dz + real(dg*(discrete ? im*cis(ω) : im)/g) + end + ϵ = sqrt(eps(F)) + + # Closed-loop poles without delay + Acl = feedback(sys).A + nrm = isempty(Acl) ? zero(F) : F(opnorm(Acl, 1)) + p = eigvals(Acl) + Z0 = discrete ? count(p -> abs(p) > 1 + 100eps(F)*max(1, nrm), p) : + count(p -> real(p) > 100eps(F)*nrm, p) + # A root at s = 0 (z = 1) for every delay if G = -1 there + g0 = try + resp(zero(F)) + catch + CF(Inf) end - m = margin(sys; allMargins=true, balance=false) + axis_root = isfinite(g0) && abs(g0 + 1) <= ϵ + Dmag = F(abs(sys.D[1])) + neutral = !discrete && Dmag >= 1 - ϵ + gN = discrete ? (try resp(F(π)) catch; CF(Inf) end) : CF(NaN) + nyq_rate = discrete && abs(gN) > 1 + ϵ ? 1 : 0 + nyq_marginal = discrete && isfinite(gN) && abs(abs(gN) - 1) <= ϵ + crossings = NamedTuple{(:ω, :lag, :w, :dir), Tuple{F,F,Int,Int}}[] - axis_root = false - refined = F[] - for ω in m.wpm[1] - ω = F(real(ω)) - if iszero(ω) - # The root is located at s = 0 for every delay if G(0) = -1 - axis_root |= abs(resp(ω) + 1) <= sqrt(eps(F)) - continue - end - realsys && ω < 0 && continue - # Newton iteration on log|G(jω)| = 0 refines the interpolated crossover frequency - for _ in 1:10 - step = log(abs(resp(ω)))/dlogmag(ω) - ωnew = ω - step - (isfinite(step) && abs(step) < abs(ω)/10) || break - isdiscrete(sys) && abs(ωnew)*sys.Ts > π && break - ω = ωnew - abs(step) <= 4eps(F)*abs(ω) && break + if !neutral + wpos = F.(_default_freq_vector(sys, Val{:margin}()) .* (discrete ? sys.Ts : 1)) + w = realsys ? wpos : [-reverse(wpos); wpos] + f(ω) = abs(resp(ω)) - 1 + fw = f.(w) + found = F[] + for i in 1:length(w) + ω = if fw[i] == 0 + w[i] + elseif i < length(w) && fw[i+1] != 0 && signbit(fw[i]) != signbit(fw[i+1]) && isfinite(fw[i]) && isfinite(fw[i+1]) + a, b, fa = w[i], w[i+1], fw[i] + for _ in 1:200 + m = (a + b)/2 + (m == a || m == b) && break + fm = f(m) + fm == 0 && (a = b = m; break) + if signbit(fm) == signbit(fa) + a, fa = m, fm + else + b = m + end + end + (a + b)/2 + else + continue + end + iszero(ω) && continue # Handled by axis_root + discrete && abs(ω) >= F(π)*(1 - ϵ) && continue # Handled by the Nyquist-frequency count + abs(log(abs(resp(ω)))) <= ϵ || continue # Not a crossover, e.g., a discontinuity of the computed response + any(ωr -> abs(ωr - ω) <= ϵ*abs(ω), found) && continue + push!(found, ω) + a = dlogmag(ω) + abs(a*ω) > ϵ || error("The gain crossover at ω = $(discrete ? ω/sys.Ts : ω) is tangential, the direction in which the closed-loop poles cross the stability boundary is undetermined") + φ = F(angle(resp(ω))) + # A delay θ places a root at s = jω if ωθ ≡ arg G(jω) + π (mod 2π) + lag = mod(ω > 0 ? φ + F(π) : -(φ + F(π)), 2*F(π)) + (lag < ϵ || lag > 2*F(π) - ϵ) && (lag = zero(F)) + # A real-coefficient system has a complex-conjugate pair of crossing roots + push!(crossings, (; ω=abs(ω), lag, w=realsys ? 2 : 1, dir=-Int(sign(ω*a)))) end - # Two grid crossings may converge to the same crossover - any(ωr -> abs(ωr - ω) <= sqrt(eps(F))*abs(ω), refined) && continue - push!(refined, ω) - a = dlogmag(ω) - abs(a*ω) > sqrt(eps(F)) || error("The gain crossover at ω = $ω is tangential, the direction in which the closed-loop poles cross the imaginary axis is undetermined") - φ = F(angle(resp(ω))) - # A delay θ places a root at s = jω if ωθ ≡ arg G(jω) + π (mod 2π) - lag = mod(ω > 0 ? φ + F(π) : -(φ + F(π)), 2*F(π)) - lag > 2*F(π) - sqrt(eps(F)) && (lag = zero(F)) - # A real-coefficient system has a complex-conjugate pair of crossing roots, except for a real root at the Nyquist frequency - w = realsys && !(isdiscrete(sys) && abs(abs(ω)*sys.Ts - π) <= sqrt(eps(F))) ? 2 : 1 - push!(crossings, (; ω=abs(ω), lag, w, dir=-Int(sign(ω*a)))) - end - p = poles(feedback(sys)) - Z0 = isdiscrete(sys) ? count(p -> abs(p) > 1 + sqrt(eps(F)), p) : - count(p -> real(p) > sqrt(eps(F))*max(1, abs(p)), p) - neutral = iscontinuous(sys) && abs(sys.D[1]) >= 1 + end scale = isempty(crossings) ? one(F) : inv(maximum(c -> c.ω, crossings)) - (; crossings, Z0, axis_root, neutral, scale) + (; crossings, Z0, axis_root, neutral, Dmag, discrete, gN, nyq_rate, nyq_marginal, scale) end _delay_tol(data, θ) = sqrt(eps(typeof(data.scale)))*(abs(θ) + data.scale) -# Number of closed-loop poles in the open right half-plane for the total delay θ, and whether a pole is located on the imaginary axis -function _unstable_count_at(data, θ) +# A total delay above which a lower bound of the number of unstable closed-loop poles is positive +function _delay_horizon(data) F = typeof(data.scale) + twoπ = 2*F(π) + destab = filter(c -> c.dir > 0, data.crossings) + stab = filter(c -> c.dir < 0, data.crossings) + rate = sum(c -> c.w*c.ω, destab; init=zero(F)) - sum(c -> c.w*c.ω, stab; init=zero(F)) + twoπ*data.nyq_rate + rate > 0 || throw(ArgumentError("The stabilizing crossings occur at least as frequently as the destabilizing crossings, so the stable delay intervals are not bounded")) + num = sum(c -> c.w*c.lag, destab; init=zero(F)) - sum(c -> c.w*c.lag, stab; init=zero(F)) + + twoπ*(sum(c -> c.w, stab; init=0) - data.Z0) + max(zero(F), num/rate) +end + +# All crossing events with total delay at most θmax, sorted by delay +function _delay_events(data, θmax) + F = typeof(data.scale) + twoπ = 2*F(π) + events = NamedTuple{(:θ, :w, :dir, :atzero), Tuple{F,Int,Int,Bool}}[] + for c in data.crossings, k in 0:floor(Int, (c.ω*θmax - c.lag)/twoπ) + push!(events, (; θ=(c.lag + twoπ*k)/c.ω, c.w, c.dir, atzero=iszero(c.lag) && k == 0)) + end + sort!(events, by=e -> e.θ) +end + +# Number of unstable closed-loop poles for the total delay θ, and whether a pole is located on the stability boundary. For discrete-time systems, θ must be an integer number of samples. +function _unstable_count_at(data, θ) tol = _delay_tol(data, θ) Z = data.Z0 - onaxis = false - for c in data.crossings, k in 0:floor(Int, (c.ω*(θ + tol) - c.lag)/(2*F(π))) - θk = (c.lag + 2*F(π)*k)/c.ω - atzero = iszero(c.lag) && k == 0 # Z0 does not count the root on the imaginary axis at θ = 0 - if abs(θk - θ) <= tol + onaxis = data.axis_root + for e in _delay_events(data, θ + tol) + if abs(e.θ - θ) <= tol onaxis = true - !atzero && c.dir < 0 && (Z -= c.w) - elseif atzero - c.dir > 0 && (Z += c.w) + !e.atzero && e.dir < 0 && (Z -= e.w) + elseif e.atzero + # Z0 does not count the root on the imaginary axis at θ = 0 + e.dir > 0 && (Z += e.w) else - Z += c.w*c.dir + Z += e.w*e.dir end end + if data.discrete + d = round(Int, θ) + Z += data.nyq_rate*d + data.nyq_marginal && abs(data.gN*(-1)^d + 1) <= sqrt(eps(typeof(data.scale))) && (onaxis = true) + end Z, onaxis end -# The smallest total delay larger than θ for which a closed-loop pole is located on the imaginary axis +# The smallest total delay larger than θ at which a crossing occurs at a gain crossover in the interior of the frequency range function _next_crossing(data, θ) F = typeof(data.scale) tol = _delay_tol(data, θ) diff --git a/lib/ControlSystemsBase/test/test_margin_phase.jl b/lib/ControlSystemsBase/test/test_margin_phase.jl index 5cced5376..5063b0d08 100644 --- a/lib/ControlSystemsBase/test/test_margin_phase.jl +++ b/lib/ControlSystemsBase/test/test_margin_phase.jl @@ -1,18 +1,25 @@ -# Number of roots of 1 + G(s)e^{-sθ} with Re s > σ for rational G, computed with the argument principle along the line Re s = σ with an adaptively refined frequency grid. This is used as a reference that is independent of rational delay approximations. -function n_unstable_delayed(G, θ; σ=1e-7, wmax=1e7) +# Number of roots of 1 + G(s)e^{-sθ} with Re s > σ for rational G, computed with the argument principle along the line Re s = σ. This is used as a reference that is independent of rational delay approximations. The frequency grid is refined where the curve changes rapidly relative to its distance from the origin, where the delay rotates the curve by more than half a radian while |G| is not small, and around the imaginary parts of the poles of G. +function n_unstable_delayed(G, θ; σ=1e-9, wmax=1e7) g = ss(G) - P = count(p -> real(p) > σ, poles(g)) + pg = poles(g) + P = count(p -> real(p) > σ, pg) f(ω) = 1 + evalfr(g, σ + im*ω)[1]*exp(-(σ + im*ω)*θ) w = exp10.(range(-10, log10(wmax), length=2000)) w = [-reverse(w); 0; w] + for p in pg + append!(w, imag(p) .+ (abs(real(p)) + σ) .* range(-50, 50, length=201)) + end + w = sort!(unique!(filter!(ω -> abs(ω) <= wmax, w))) total = 0.0 stack = [(w[i], w[i+1], f(w[i]), f(w[i+1])) for i in length(w)-1:-1:1] while !isempty(stack) a, b, fa, fb = pop!(stack) + m = (a + b)/2 + fm = f(m) d = angle(fb/fa) - if abs(d) > 0.2 && b - a > 1e-14*max(abs(a), abs(b), 1) - m = (a + b)/2 - fm = f(m) + coarse = abs(d) > 0.2 || abs(fm - (fa + fb)/2) > 0.1min(abs(fa), abs(fb)) || + (θ*(b - a) > 0.5 && max(abs(fa - 1), abs(fb - 1)) > 0.25) + if coarse && b - a > 1e-14*max(abs(a), abs(b), 1) push!(stack, (m, b, fm, fb)) push!(stack, (a, m, fa, fm)) else @@ -22,6 +29,9 @@ function n_unstable_delayed(G, θ; σ=1e-7, wmax=1e7) round(Int, P - total/2π) end +# Number of closed-loop poles outside the unit circle for the discrete-time loop G(z)z^{-d} +n_unstable_discrete(G, d) = count(p -> abs(p) > 1 + 1e-9, poles(feedback(ss(G)*ss(tf(1, [1; zeros(d)], G.Ts))))) + # Check every interval returned by delay_stability_intervals against the reference, with the total delay θ = T + τ function check_delay_intervals(G, T, intervals) for (a, b) in intervals @@ -32,6 +42,14 @@ function check_delay_intervals(G, T, intervals) T + a > 1e-6 && @test n_unstable_delayed(G, T + a - 1e-3*(b - a)) > 0 isfinite(b) && @test n_unstable_delayed(G, T + b + 1e-3*(b - a)) > 0 end + # Delays outside the returned intervals result in an unstable closed loop, so no stable interval is omitted + bounds = filter(isfinite, [x for iv in intervals for x in iv]) + upper = 1.5*maximum(bounds; init=1.0) + 1 + for x in range(-T, upper, length=41) + inside = any(a < x < b for (a, b) in intervals) + near = any(abs(x - y) < 1e-3*(1 + abs(y)) for y in bounds) + (inside || near) || @test n_unstable_delayed(G, T + x) > 0 + end end @testset "Phase margin branches" begin @@ -71,7 +89,9 @@ end @test margin((s+1e-9)/(s^2*(s+1))).pm[] ≈ 51.8273 atol=1e-2 @test margin(tf([0.01], [1, -(1-1e-9)], 0.01)).pm[] ≈ 89.7135 atol=1e-2 @test margin(tf(Float32[2.7, 5.4, 2.7], Float32[1, -1f-4, -1f-8, 1f-12])).pm[] ≈ 53.138 atol=1e-2 - @test delaymargin(tf(Float32[2.7, 5.4, 2.7], Float32[1, -1f-4, -1f-8, 1f-12])) isa Float32 + dm32 = delaymargin(tf(Float32[2.7, 5.4, 2.7], Float32[1, -1f-4, -1f-8, 1f-12])) + @test dm32 isa Float32 + @test dm32 ≈ (2atan(3) - π/2 - atan(1e-4/3))/3 rtol=1e-4 # Excess phase lag must produce a negative signed margin. L = 27/(s+1)^3 @@ -91,7 +111,8 @@ end ω = 2asin(0.25)/Ts expected = (π/2 - ω*Ts/2)/(ω*Ts) @test delaymargin(Ld) ≈ expected rtol=1e-8 - @test only(delay_stability_intervals(Ld)) == (0, delaymargin(Ld)) + @test delay_stability_intervals(Ld) == [0:2] + @test [n_unstable_discrete(Ld, d) == 0 for d in 0:5] == [true, true, true, false, false, false] # The smallest phase margin and smallest delay occur at different crossovers. L = 0.5/(s^2+0.2s+1) + 20/(s^2+2s+100) @@ -176,3 +197,70 @@ end @test_logs (:warn, r"cannot be determined") delaymargin(L) @test_throws ArgumentError delay_stability_intervals(L) end + +@testset "Delay margin edge cases" begin + s = tf("s") + + # The reference counts roots of lightly damped and strongly delayed loops. + @test n_unstable_delayed(tf([4e-5], [1, 2e-5, 1]), 1.0) == 2 + @test n_unstable_delayed(2/(s+1), 1000.0) == 552 + + # Nominal closed-loop poles at ±j, with a crossing at zero delay that leaves the right half-plane + d = 0.5352016707409908 + G = tf([-d, -0.5], [1, d, 1.5]) + @test delaymargin(G) == 0 + intervals = delay_stability_intervals(G) + @test intervals[1][1] == 0 + @test intervals[1][2] ≈ 3.6172795537 rtol=1e-6 + check_delay_intervals(G, 0, intervals) + @test n_unstable_delayed(G, 4.0) > 0 + @test isnan(delaymargin(G*delay(4))) + + # Slow unstable closed-loop poles + @test isnan(delaymargin(1e-9/(s-2e-9))) + @test isempty(delay_stability_intervals(1e-9/(s-2e-9))) + @test isnan(delaymargin(tf(Float32[1e-4], Float32[1, -2f-4]))) + @test isnan(delaymargin(tf([1e-10], [1, -(1+3e-10)], 1))) + + # Discrete-time loops with a gain larger than one at the Nyquist frequency + G = ss(2.0, 1.0) + @test delaymargin(G) == 1 + @test delay_stability_intervals(G) == [0:0] + G = tf([-1.2], [1, 0.5], 1) + @test delaymargin(G) == 1 + @test n_unstable_discrete(G, 1) > 0 + ranges = delay_stability_intervals(G) + @test [any(d in r for r in ranges) for d in 0:30] == [n_unstable_discrete(G, d) == 0 for d in 0:30] + # A lightly damped discrete-time loop with stability switches + G = c2d(ss(0.5/(s^2+0.2s+1)) + ss(20/(s^2+2s+100)), 0.05) + ranges = delay_stability_intervals(G) + @test length(ranges) > 1 + @test [any(d in r for r in ranges) for d in 0:150] == [n_unstable_discrete(G, d) == 0 for d in 0:150] + @test floor(delaymargin(G)) == last(ranges[1]) + + # Gain crossover at the Nyquist frequency with a closed-loop pole at z = -1 + @test delaymargin(tf([0.5], [1, 0.5], 1)) == 0 + @test delaymargin(tf([-0.5], [1, 0.5], 1)) == 1 + + # Complex coefficients: the crossover is located at a negative frequency + G = ss(-1-2im, 1, 2, 0) + τ = delaymargin(G) + @test τ ≈ (2π/3)/(2+√3) rtol=1e-8 + @test n_unstable_delayed(G, 0.995τ) == 0 + @test n_unstable_delayed(G, 1.005τ) > 0 + check_delay_intervals(G, 0, delay_stability_intervals(G)) + + # A closed-loop pole at the origin for every delay, with a computed DC gain that differs from -1 by rounding + for k in (49.0, 98.0) + @test delaymargin(tf([-k], [1, k])) == 0 + @test isempty(delay_stability_intervals(tf([-k], [1, k]))) + end + + # Narrow resonances + @test delaymargin(tf([4e-7], [1, 2e-7, 1])) ≈ π/6 rtol=1e-6 + @test delaymargin(tf(Float32[0.004], Float32[1, 0.002, 1])) ≈ 0.52369187 rtol=1e-3 + + # |L(j∞)| = 1: asymptotically, but not exponentially, stable for positive delays + @test delaymargin((s+1)/(s+2)) == 0 + @test delaymargin(ss(1.0)) == 0 +end