From 326fc7bc05029d14db81acfa5a819bc7555eaba3 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Thu, 19 Nov 2026 04:03:33 +0000 Subject: [PATCH 1/3] Support keyword arguments in kalman and lqr with dual numbers The methods of kalman and lqr for dual-number covariance matrices in the ImplicitDifferentiation extension now accept the keyword arguments `extra` and, for kalman, `direct`. Previously, any keyword argument caused dispatch to the generic method, which does not support dual numbers. The discrete-time kalman method for dual numbers returned the transpose of the Kalman gain; it now returns a matrix of size (nx, ny). Fixes JuliaControl/ControlSystems.jl#1105 Co-Authored-By: Claude Opus 5.5 --- ...olSystemsBaseImplicitDifferentiationExt.jl | 45 ++++++++++---- .../test/test_implicit_diff.jl | 61 +++++++++++++++++++ 2 files changed, 94 insertions(+), 12 deletions(-) diff --git a/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl b/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl index b88eb2722..e6917e265 100644 --- a/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl +++ b/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl @@ -38,24 +38,37 @@ function are(::ContinuousType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual X end +_primal(x::Dual) = _primal(ForwardDiff.value(x)) +_primal(x) = x + +# The closed-loop eigenvalues are computed from the primal values and carry no derivative information. +_closedloop_poles(A, B, K) = eigvals(_primal.(A - B*K)) + """ - lqr(::Continuous, A, B, Q, R::AbstractMatrix{<:Dual}) + lqr(::Continuous, A, B, Q, R::AbstractMatrix{<:Dual}; extra = Val(false)) To make the LQR solver work with dual numbers, make sure that the `R` matrix has the dual number element type. + +If `extra = Val(true)`, the function returns `K, S, p`, where the closed-loop eigenvalues `p` are computed from the primal values and carry no derivative information. """ -function lqr(::ContinuousType, A, B, Q, R::AbstractMatrix{<:Dual}) +function lqr(::ContinuousType, A, B, Q, R::AbstractMatrix{<:Dual}; extra::Val{E} = Val(false)) where E X = are(Continuous, A, B, Q, R) - R\(B'X) + K = R\(B'X) + E ? (K, X, _closedloop_poles(A, B, K)) : K end """ - kalman(::Continuous, A, C, Q, R::AbstractMatrix{<:Dual}) + kalman(::Continuous, A, C, Q, R::AbstractMatrix{<:Dual}; extra = Val(false)) To make the Kalman solver work with dual numbers, make sure that the `R` matrix has the dual number element type. + +If `extra = Val(true)`, the function returns `K, R∞, p`, where the eigenvalues `p` of `A-KC` are computed from the primal values and carry no derivative information. """ -function kalman(::ContinuousType, A, C, Q, R::AbstractMatrix{<:Dual}) +function kalman(::ContinuousType, A, C, Q, R::AbstractMatrix{<:Dual}; direct = false, extra::Val{E} = Val(false)) where E + direct && error("direct = true only applies to discrete-time systems") X = are(Continuous, A', C', Q, R) - (R\(C*X))' + K = Matrix((R\(C*X))') + E ? (K, X, _closedloop_poles(A, K, C)) : K end @@ -98,25 +111,33 @@ function are(::DiscreteType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual}; end """ - lqr(::Discrete, A, B, Q, R::AbstractMatrix{<:Dual}) + lqr(::Discrete, A, B, Q, R::AbstractMatrix{<:Dual}; extra = Val(false)) To make the LQR solver work with dual numbers, make sure that the `R` matrix has the dual number element type. + +If `extra = Val(true)`, the function returns `K, S, p`, where the closed-loop eigenvalues `p` are computed from the primal values and carry no derivative information. """ -function lqr(::DiscreteType, A, B, Q, R::AbstractMatrix{<:Dual}) +function lqr(::DiscreteType, A, B, Q, R::AbstractMatrix{<:Dual}; extra::Val{E} = Val(false)) where E X = are(Discrete, A, B, Q, R) BX = B'X - (R+BX*B)\(BX*A) + K = (R+BX*B)\(BX*A) + E ? (K, X, _closedloop_poles(A, B, K)) : K end """ - kalman(::Discrete, A, C, Q, R::AbstractMatrix{<:Dual}) + kalman(::Discrete, A, C, Q, R::AbstractMatrix{<:Dual}; direct = false, extra = Val(false)) To make the Kalman solver work with dual numbers, make sure that the `R` matrix has the dual number element type. + +If `extra = Val(true)`, the function returns `K, R∞, p`, where the eigenvalues `p` of `A-KC` are computed from the primal values and carry no derivative information. """ -function kalman(::DiscreteType, A, C, Q, R::AbstractMatrix{<:Dual}) +function kalman(::DiscreteType, A, C, Q, R::AbstractMatrix{<:Dual}; direct = false, extra::Val{E} = Val(false)) where E X = are(Discrete, A', C', Q, R) CX = C*X - (R+CX*C')\(CX*A') + S = R + CX*C' + Kp = Matrix(((S)\(CX*A'))') + K = direct ? Matrix((S\CX)') : Kp + E ? (K, X, _closedloop_poles(A, Kp, C)) : K end diff --git a/lib/ControlSystemsBase/test/test_implicit_diff.jl b/lib/ControlSystemsBase/test/test_implicit_diff.jl index 7a4cb513e..dc0e4bbdd 100644 --- a/lib/ControlSystemsBase/test/test_implicit_diff.jl +++ b/lib/ControlSystemsBase/test/test_implicit_diff.jl @@ -70,6 +70,67 @@ J2 = fdgrad(difffun, q) @test J1 ≈ J2 rtol = 1e-6 +## Keyword arguments and output sizes of kalman and lqr (ControlSystems.jl issue 1105) +dualize(R) = ForwardDiff.Dual{:test}.(R, 1.0) +let + for Ts in (nothing, 0.01) + P = Ts === nothing ? ssrand(2, 1, 3) : ssrand(2, 1, 3; Ts) + Q = [2.0 0.1 0; 0.1 2 0; 0 0 1] + R = [1.0 0.2; 0.2 1.5] + r = vec(R) + directs = Ts === nothing ? (false,) : (false, true) + for direct in directs + Kref, Xref, pref = kalman(P, Q, R; direct, extra=Val(true)) + Kd, Xd, pd = kalman(P, Q, dualize(R); direct, extra=Val(true)) + @test size(Kd) == size(Kref) == (P.nx, P.ny) + @test ForwardDiff.value.(Kd) ≈ Kref + @test ForwardDiff.value.(Xd) ≈ Xref + @test sort(pd, by=x->(real(x), imag(x))) ≈ sort(pref, by=x->(real(x), imag(x))) + @test size(kalman(P, Q, dualize(R); direct)) == (P.nx, P.ny) + + difffun = function (r) + Rd = reshape(r, 2, 2) + Rd = (Rd .+ Rd') ./ 2 + K = kalman(P, Q, Rd; direct) + sum(abs2, K * [1.0 2.0; 3.0 4.0]) + end + @test ForwardDiff.gradient(difffun, r) ≈ fdgrad(difffun, r) rtol = 1e-5 + + difffun_extra = function (r) + Rd = reshape(r, 2, 2) + Rd = (Rd .+ Rd') ./ 2 + K, X, _ = kalman(P, Q, Rd; direct, extra=Val(true)) + sum(abs2, K * [1.0 2.0; 3.0 4.0]) + sum(X) + end + @test ForwardDiff.gradient(difffun_extra, r) ≈ fdgrad(difffun_extra, r) rtol = 1e-5 + end + Ts === nothing && @test_throws ErrorException kalman(P, Q, dualize(R); direct=true) + + Pu = Ts === nothing ? ssrand(1, 2, 3) : ssrand(1, 2, 3; Ts) + Kref, Sref, pref = lqr(Pu, Q, R; extra=Val(true)) + Kd, Sd, pd = lqr(Pu, Q, dualize(R); extra=Val(true)) + @test size(Kd) == size(Kref) == (Pu.nu, Pu.nx) + @test ForwardDiff.value.(Kd) ≈ Kref + @test ForwardDiff.value.(Sd) ≈ Sref + @test sort(pd, by=x->(real(x), imag(x))) ≈ sort(pref, by=x->(real(x), imag(x))) + end + + # Example from the issue, with coupled state variables to obtain a nonzero derivative + function cost(p::T) where T <: Real + A = [0.9 0.1; 0.0 p] + C = [1.0 0.0] + R1 = Matrix{T}(I, 2, 2) + R2 = Matrix{T}(I, 1, 1) + K = kalman(Discrete, A, C, R1, R2, direct=true) + @test size(K) == (2, 1) + K2, _ = kalman(Discrete, A, C, R1, R2, extra=Val(true)) + @test size(K2) == (2, 1) + sum(K) + sum(K2) + end + @test ForwardDiff.derivative(cost, 0.1) ≈ central_fdm(5, 1)(cost, 0.1) rtol = 1e-6 +end + + # Diff w.r.t. plant P = ssrand(1, 1, 2) Q = I(P.nx) From 9808770a05d47bf458fe899a806dc44d6385e4e2 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Thu, 19 Nov 2026 05:02:09 +0000 Subject: [PATCH 2/3] Obtain closed-loop eigenvalues from the forward Riccati solve The forward functions of the implicit functions now call arec/ared and return the closed-loop eigenvalues as the non-differentiated byproduct, instead of computing eigvals of the primal closed-loop matrix afterwards. Co-Authored-By: Claude Opus 5.5 --- ...olSystemsBaseImplicitDifferentiationExt.jl | 60 +++++++++---------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl b/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl index e6917e265..67b91b6ed 100644 --- a/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl +++ b/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl @@ -8,12 +8,14 @@ using ComponentArrays using LinearAlgebra +# The second output (the closed-loop eigenvalues) is a byproduct that is not differentiated function forward_arec(pars) (; A,B,Q,R) = pars - ControlSystemsBase.are(Continuous, A, B, Q, R), 0 + X, p = ControlSystemsBase.arec(A, B, R, Q) + X, p end -function conditions_arec(pars, X, noneed) +function conditions_arec(pars, X, p) (; A,B,Q,R) = pars C = A'X C .+= C' @@ -32,29 +34,28 @@ const implicit_arec = ImplicitFunction(forward_arec, conditions_arec) To make the ARE solver work with dual numbers, make sure that the `R` matrix has the dual number element type. """ function are(::ContinuousType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual}; kwargs...) + first(_are_eigvals(Continuous, A, B, Q, R)) +end + +# Returns the solution X and the closed-loop eigenvalues p, which carry no derivative information +function _are_eigvals(te, A, B, Q, R) pars = ComponentVector(; A,B,Q,R) - X0, _ = implicit_arec(pars) + X0, p = (te isa ContinuousType ? implicit_arec : implicit_ared)(pars) X = X0 isa AbstractMatrix ? X0 : reshape(X0, size(A)) - X + X, p end -_primal(x::Dual) = _primal(ForwardDiff.value(x)) -_primal(x) = x - -# The closed-loop eigenvalues are computed from the primal values and carry no derivative information. -_closedloop_poles(A, B, K) = eigvals(_primal.(A - B*K)) - """ lqr(::Continuous, A, B, Q, R::AbstractMatrix{<:Dual}; extra = Val(false)) To make the LQR solver work with dual numbers, make sure that the `R` matrix has the dual number element type. -If `extra = Val(true)`, the function returns `K, S, p`, where the closed-loop eigenvalues `p` are computed from the primal values and carry no derivative information. +If `extra = Val(true)`, the function returns `K, S, p`, where the closed-loop eigenvalues `p` carry no derivative information. """ function lqr(::ContinuousType, A, B, Q, R::AbstractMatrix{<:Dual}; extra::Val{E} = Val(false)) where E - X = are(Continuous, A, B, Q, R) + X, p = _are_eigvals(Continuous, A, B, Q, R) K = R\(B'X) - E ? (K, X, _closedloop_poles(A, B, K)) : K + E ? (K, X, p) : K end """ @@ -62,13 +63,13 @@ end To make the Kalman solver work with dual numbers, make sure that the `R` matrix has the dual number element type. -If `extra = Val(true)`, the function returns `K, R∞, p`, where the eigenvalues `p` of `A-KC` are computed from the primal values and carry no derivative information. +If `extra = Val(true)`, the function returns `K, R∞, p`, where the eigenvalues `p` of `A-KC` carry no derivative information. """ function kalman(::ContinuousType, A, C, Q, R::AbstractMatrix{<:Dual}; direct = false, extra::Val{E} = Val(false)) where E direct && error("direct = true only applies to discrete-time systems") - X = are(Continuous, A', C', Q, R) + X, p = _are_eigvals(Continuous, A', C', Q, R) K = Matrix((R\(C*X))') - E ? (K, X, _closedloop_poles(A, K, C)) : K + E ? (K, X, p) : K end @@ -76,13 +77,14 @@ end ## Discrete +# The second output (the closed-loop eigenvalues) is a byproduct that is not differentiated function forward_ared(pars) (; A,B,Q,R) = pars - # Q = reshape(Q0, size(A)) - ControlSystemsBase.are(Discrete, A, B, Q, R), 0 + X, p = ControlSystemsBase.ared(A, B, R, Q) + X, p end -function conditions_ared(pars, X, noneed) +function conditions_ared(pars, X, p) # A'XA - X - (A'XB+S)(R+B'XB)^(-1)(B'XA+S') + Q = 0 # A'X*A - X - (A'X*B)*((R+B'X*B)\(B'X*A)) + Q (; A,B,Q,R) = pars @@ -104,10 +106,7 @@ const implicit_ared = ImplicitFunction(forward_ared, conditions_ared) To make the ARE solver work with dual numbers, make sure that the `R` matrix has the dual number element type. """ function are(::DiscreteType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual}; kwargs...) - pars = ComponentVector(; A,B,Q,R) - X0, _ = implicit_ared(pars) - X = X0 isa AbstractMatrix ? X0 : reshape(X0, size(A)) - X + first(_are_eigvals(Discrete, A, B, Q, R)) end """ @@ -115,13 +114,13 @@ end To make the LQR solver work with dual numbers, make sure that the `R` matrix has the dual number element type. -If `extra = Val(true)`, the function returns `K, S, p`, where the closed-loop eigenvalues `p` are computed from the primal values and carry no derivative information. +If `extra = Val(true)`, the function returns `K, S, p`, where the closed-loop eigenvalues `p` carry no derivative information. """ function lqr(::DiscreteType, A, B, Q, R::AbstractMatrix{<:Dual}; extra::Val{E} = Val(false)) where E - X = are(Discrete, A, B, Q, R) + X, p = _are_eigvals(Discrete, A, B, Q, R) BX = B'X K = (R+BX*B)\(BX*A) - E ? (K, X, _closedloop_poles(A, B, K)) : K + E ? (K, X, p) : K end """ @@ -129,15 +128,14 @@ end To make the Kalman solver work with dual numbers, make sure that the `R` matrix has the dual number element type. -If `extra = Val(true)`, the function returns `K, R∞, p`, where the eigenvalues `p` of `A-KC` are computed from the primal values and carry no derivative information. +If `extra = Val(true)`, the function returns `K, R∞, p`, where the eigenvalues `p` of `A-KC` carry no derivative information. """ function kalman(::DiscreteType, A, C, Q, R::AbstractMatrix{<:Dual}; direct = false, extra::Val{E} = Val(false)) where E - X = are(Discrete, A', C', Q, R) + X, p = _are_eigvals(Discrete, A', C', Q, R) CX = C*X S = R + CX*C' - Kp = Matrix(((S)\(CX*A'))') - K = direct ? Matrix((S\CX)') : Kp - E ? (K, X, _closedloop_poles(A, Kp, C)) : K + K = Matrix((S\(direct ? CX : CX*A'))') + E ? (K, X, p) : K end From 6aff7ce7b7f77f3885468ff89b80f7be1db763b6 Mon Sep 17 00:00:00 2001 From: Fredrik Bagge Carlson Date: Thu, 19 Nov 2026 05:18:21 +0000 Subject: [PATCH 3/3] Simplify the dual-number Riccati methods and pass solver keywords - Remove the dual-number kalman methods. The generic kalman calls the dual-number lqr method, which handles direct, extra and the continuous-time error without duplicated code. - Pass the keyword arguments of are and lqr to arec/ared as a constant argument of the implicit function; previously, keywords such as as = true were ignored. - Return all additional outputs of the Riccati solver with extra = Val(true), so that the number of outputs equals that of the generic methods. - Correct the kalman docstring: with direct = true, p are the eigenvalues of A-AKC. - Compare full Jacobians of K and X with finite differences in the tests. Co-Authored-By: Claude Opus 5.5 --- ...olSystemsBaseImplicitDifferentiationExt.jl | 134 ++++++------------ lib/ControlSystemsBase/src/synthesis.jl | 2 +- .../test/test_implicit_diff.jl | 83 ++++++----- 3 files changed, 92 insertions(+), 127 deletions(-) diff --git a/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl b/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl index 67b91b6ed..8aa332fe2 100644 --- a/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl +++ b/lib/ControlSystemsBase/ext/ControlSystemsBaseImplicitDifferentiationExt.jl @@ -1,6 +1,6 @@ module ControlSystemsBaseImplicitDifferentiationExt using ControlSystemsBase -import ControlSystemsBase: kalman, lqr, are, ContinuousType, DiscreteType +import ControlSystemsBase: lqr, are, ContinuousType, DiscreteType using ForwardDiff using ForwardDiff: Dual using ImplicitDifferentiation @@ -8,134 +8,88 @@ using ComponentArrays using LinearAlgebra -# The second output (the closed-loop eigenvalues) is a byproduct that is not differentiated -function forward_arec(pars) +# The solver keyword arguments `kw` are a constant argument of the implicit function. The +# byproduct contains the remaining outputs of the Riccati solver (closed-loop eigenvalues, gain etc.), +# which are not differentiated. +function forward_arec(pars, kw) (; A,B,Q,R) = pars - X, p = ControlSystemsBase.arec(A, B, R, Q) - X, p + X, rest... = ControlSystemsBase.arec(A, B, R, Q; kw...) + X, rest end -function conditions_arec(pars, X, p) +function conditions_arec(pars, X, rest, kw) (; A,B,Q,R) = pars C = A'X C .+= C' C .+= Q XB = X*B mul!(C, XB, R\XB', -1, 1) - # C .+ X .- X' # Does not seem to be needed end const implicit_arec = ImplicitFunction(forward_arec, conditions_arec) - -""" - are(::Continuous, A, B, Q, R::AbstractMatrix{<:Dual}; kwargs) - -To make the ARE solver work with dual numbers, make sure that the `R` matrix has the dual number element type. -""" -function are(::ContinuousType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual}; kwargs...) - first(_are_eigvals(Continuous, A, B, Q, R)) -end - -# Returns the solution X and the closed-loop eigenvalues p, which carry no derivative information -function _are_eigvals(te, A, B, Q, R) - pars = ComponentVector(; A,B,Q,R) - X0, p = (te isa ContinuousType ? implicit_arec : implicit_ared)(pars) - X = X0 isa AbstractMatrix ? X0 : reshape(X0, size(A)) - X, p -end - -""" - lqr(::Continuous, A, B, Q, R::AbstractMatrix{<:Dual}; extra = Val(false)) - -To make the LQR solver work with dual numbers, make sure that the `R` matrix has the dual number element type. - -If `extra = Val(true)`, the function returns `K, S, p`, where the closed-loop eigenvalues `p` carry no derivative information. -""" -function lqr(::ContinuousType, A, B, Q, R::AbstractMatrix{<:Dual}; extra::Val{E} = Val(false)) where E - X, p = _are_eigvals(Continuous, A, B, Q, R) - K = R\(B'X) - E ? (K, X, p) : K -end - -""" - kalman(::Continuous, A, C, Q, R::AbstractMatrix{<:Dual}; extra = Val(false)) - -To make the Kalman solver work with dual numbers, make sure that the `R` matrix has the dual number element type. - -If `extra = Val(true)`, the function returns `K, R∞, p`, where the eigenvalues `p` of `A-KC` carry no derivative information. -""" -function kalman(::ContinuousType, A, C, Q, R::AbstractMatrix{<:Dual}; direct = false, extra::Val{E} = Val(false)) where E - direct && error("direct = true only applies to discrete-time systems") - X, p = _are_eigvals(Continuous, A', C', Q, R) - K = Matrix((R\(C*X))') - E ? (K, X, p) : K -end - - - -## Discrete - - -# The second output (the closed-loop eigenvalues) is a byproduct that is not differentiated -function forward_ared(pars) +function forward_ared(pars, kw) (; A,B,Q,R) = pars - X, p = ControlSystemsBase.ared(A, B, R, Q) - X, p + X, rest... = ControlSystemsBase.ared(A, B, R, Q; kw...) + X, rest end -function conditions_ared(pars, X, p) - # A'XA - X - (A'XB+S)(R+B'XB)^(-1)(B'XA+S') + Q = 0 - # A'X*A - X - (A'X*B)*((R+B'X*B)\(B'X*A)) + Q +function conditions_ared(pars, X, rest, kw) + # A'XA - X - (A'XB)(R+B'XB)^(-1)(B'XA) + Q = 0 (; A,B,Q,R) = pars AX = A'X C = AX*A C .+= Q .- X' AXB = AX*B C .-= AXB*(((B'X*B) .+= R)\AXB') - # C .+= X .- X' C end const implicit_ared = ImplicitFunction(forward_ared, conditions_ared) +# Returns the solution X, differentiable with respect to all of A, B, Q, R, and the remaining +# outputs of the Riccati solver, starting with the closed-loop eigenvalues, which carry no +# derivative information. +function _are_extra(te, A, B, Q, R; kwargs...) + pars = ComponentVector(; A,B,Q,R) + implicit = te isa ContinuousType ? implicit_arec : implicit_ared + X0, rest = implicit(pars, NamedTuple(kwargs)) + reshape(X0, size(A)), rest +end """ - are(::Discrete, A, B, Q, R::AbstractMatrix{<:Dual}; kwargs) + are(::Continuous, A, B, Q, R::AbstractMatrix{<:Dual}; kwargs...) + are(::Discrete, A, B, Q, R::AbstractMatrix{<:Dual}; kwargs...) -To make the ARE solver work with dual numbers, make sure that the `R` matrix has the dual number element type. +To make the ARE solver work with dual numbers, make sure that the `R` matrix has the dual number element type. The keyword arguments are passed to the Riccati solver. """ -function are(::DiscreteType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual}; kwargs...) - first(_are_eigvals(Discrete, A, B, Q, R)) +function are(te::ContinuousType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual}; kwargs...) + first(_are_extra(te, A, B, Q, R; kwargs...)) end -""" - lqr(::Discrete, A, B, Q, R::AbstractMatrix{<:Dual}; extra = Val(false)) - -To make the LQR solver work with dual numbers, make sure that the `R` matrix has the dual number element type. - -If `extra = Val(true)`, the function returns `K, S, p`, where the closed-loop eigenvalues `p` carry no derivative information. -""" -function lqr(::DiscreteType, A, B, Q, R::AbstractMatrix{<:Dual}; extra::Val{E} = Val(false)) where E - X, p = _are_eigvals(Discrete, A, B, Q, R) - BX = B'X - K = (R+BX*B)\(BX*A) - E ? (K, X, p) : K +function are(te::DiscreteType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual}; kwargs...) + first(_are_extra(te, A, B, Q, R; kwargs...)) end """ - kalman(::Discrete, A, C, Q, R::AbstractMatrix{<:Dual}; direct = false, extra = Val(false)) + lqr(::Continuous, A, B, Q, R::AbstractMatrix{<:Dual}; extra = Val(false), kwargs...) + lqr(::Discrete, A, B, Q, R::AbstractMatrix{<:Dual}; extra = Val(false), kwargs...) -To make the Kalman solver work with dual numbers, make sure that the `R` matrix has the dual number element type. +To make the LQR solver work with dual numbers, make sure that the `R` matrix has the dual number element type. This method is also used by [`kalman`](@ref) when `R2` has the dual number element type. -If `extra = Val(true)`, the function returns `K, R∞, p`, where the eigenvalues `p` of `A-KC` carry no derivative information. +If `extra = Val(true)`, the outputs are the same as for the generic method. The closed-loop eigenvalues `p` and the additional outputs of the Riccati solver carry no derivative information. """ -function kalman(::DiscreteType, A, C, Q, R::AbstractMatrix{<:Dual}; direct = false, extra::Val{E} = Val(false)) where E - X, p = _are_eigvals(Discrete, A', C', Q, R) - CX = C*X - S = R + CX*C' - K = Matrix((S\(direct ? CX : CX*A'))') - E ? (K, X, p) : K +function lqr(te::ContinuousType, A, B, Q, R::AbstractMatrix{<:Dual}; extra::Val{E} = Val(false), kwargs...) where E + X, (p, _, rest...) = _are_extra(te, A, B, Q, R; kwargs...) + K = R\(B'X) + E ? (K, X, p, rest...) : K +end + +function lqr(te::DiscreteType, A, B, Q, R::AbstractMatrix{<:Dual}; extra::Val{E} = Val(false), kwargs...) where E + X, (p, _, rest...) = _are_extra(te, A, B, Q, R; kwargs...) + BX = B'X + K = (R+BX*B)\(BX*A) + E ? (K, X, p, rest...) : K end diff --git a/lib/ControlSystemsBase/src/synthesis.jl b/lib/ControlSystemsBase/src/synthesis.jl index 184cba0fb..e22ec8932 100644 --- a/lib/ControlSystemsBase/src/synthesis.jl +++ b/lib/ControlSystemsBase/src/synthesis.jl @@ -110,7 +110,7 @@ To obtain a discrete-time approximation to a continuous-time LQG problem, the fu To obtain an LTISystem that represents the Kalman filter, pass the obtained Kalman feedback gain into [`observer_filter`](@ref). To obtain an LQG controller, pass the obtained Kalman feedback gain as well as a state-feedback gain computed using [`lqr`](@ref) into [`observer_controller`](@ref). -If `extra = Val(true)`, the function returns `K, R∞, p`, where `R∞` is the solution to the Riccati equation (the stationary prediction-error covariance matrix, the covariance of ``x̃(t|t-1)``), and `p` are the eigenvalues of `A-KC`. In this case, the _filtering error_ covariance is given by ``(I-KC) R∞``, i.e., the covariance of ``x̃(t|t)``. +If `extra = Val(true)`, the function returns `K, R∞, p`, followed by the additional outputs of the Riccati solver, where `R∞` is the solution to the Riccati equation (the stationary prediction-error covariance matrix, the covariance of ``x̃(t|t-1)``), and `p` are the eigenvalues of `A-KC` if `direct = false` and of `A-AKC` if `direct = true`. In this case, the _filtering error_ covariance is given by ``(I-KC) R∞``, i.e., the covariance of ``x̃(t|t)``. The `args...; kwargs...` are sent to the Riccati solver, allowing specification of cross-covariance etc. See `?ControlSystemsBase.MatrixEquations.arec/ared` for more help. diff --git a/lib/ControlSystemsBase/test/test_implicit_diff.jl b/lib/ControlSystemsBase/test/test_implicit_diff.jl index dc0e4bbdd..105c0c881 100644 --- a/lib/ControlSystemsBase/test/test_implicit_diff.jl +++ b/lib/ControlSystemsBase/test/test_implicit_diff.jl @@ -70,49 +70,63 @@ J2 = fdgrad(difffun, q) @test J1 ≈ J2 rtol = 1e-6 -## Keyword arguments and output sizes of kalman and lqr (ControlSystems.jl issue 1105) +## Keyword arguments, outputs and derivatives of kalman, lqr and are (ControlSystems.jl issue 1105) dualize(R) = ForwardDiff.Dual{:test}.(R, 1.0) +fdjac(f, x) = FiniteDifferences.jacobian(central_fdm(5, 1), f, x) |> first +sortpoles(p) = sort(p, by=x->(real(x), imag(x))) let + Q = [2.0 0.1 0; 0.1 2 0; 0 0 1] + R = [1.0 0.2; 0.2 1.5] + r = vec(R) + symR(r) = (R = reshape(r, 2, 2); (R .+ R') ./ 2) for Ts in (nothing, 0.01) P = Ts === nothing ? ssrand(2, 1, 3) : ssrand(2, 1, 3; Ts) - Q = [2.0 0.1 0; 0.1 2 0; 0 0 1] - R = [1.0 0.2; 0.2 1.5] - r = vec(R) - directs = Ts === nothing ? (false,) : (false, true) - for direct in directs - Kref, Xref, pref = kalman(P, Q, R; direct, extra=Val(true)) - Kd, Xd, pd = kalman(P, Q, dualize(R); direct, extra=Val(true)) - @test size(Kd) == size(Kref) == (P.nx, P.ny) - @test ForwardDiff.value.(Kd) ≈ Kref - @test ForwardDiff.value.(Xd) ≈ Xref - @test sort(pd, by=x->(real(x), imag(x))) ≈ sort(pref, by=x->(real(x), imag(x))) + Pu = Ts === nothing ? ssrand(1, 2, 3) : ssrand(1, 2, 3; Ts) + A, C = P.A, P.C + + for direct in (Ts === nothing ? (false,) : (false, true)) + ref = kalman(P, Q, R; direct, extra=Val(true)) + res = kalman(P, Q, dualize(R); direct, extra=Val(true)) + @test length(res) == length(ref) + K, X, p = res + @test size(K) == size(ref[1]) == (P.nx, P.ny) + @test ForwardDiff.value.(K) ≈ ref[1] + @test ForwardDiff.value.(X) ≈ ref[2] + @test sortpoles(p) ≈ sortpoles(ref[3]) + Kp = direct ? A*ref[1] : ref[1] + @test sortpoles(p) ≈ sortpoles(eigvals(A - Kp*C)) @test size(kalman(P, Q, dualize(R); direct)) == (P.nx, P.ny) - difffun = function (r) - Rd = reshape(r, 2, 2) - Rd = (Rd .+ Rd') ./ 2 - K = kalman(P, Q, Rd; direct) - sum(abs2, K * [1.0 2.0; 3.0 4.0]) - end - @test ForwardDiff.gradient(difffun, r) ≈ fdgrad(difffun, r) rtol = 1e-5 - - difffun_extra = function (r) - Rd = reshape(r, 2, 2) - Rd = (Rd .+ Rd') ./ 2 - K, X, _ = kalman(P, Q, Rd; direct, extra=Val(true)) - sum(abs2, K * [1.0 2.0; 3.0 4.0]) + sum(X) + for extra in (Val(false), Val(true)) + f = function (r) + out = kalman(P, Q, symR(r); direct, extra) + extra isa Val{true} ? vcat(vec(out[1]), vec(out[2])) : vec(out) + end + @test ForwardDiff.jacobian(f, r) ≈ fdjac(f, r) rtol = 1e-5 end - @test ForwardDiff.gradient(difffun_extra, r) ≈ fdgrad(difffun_extra, r) rtol = 1e-5 end Ts === nothing && @test_throws ErrorException kalman(P, Q, dualize(R); direct=true) - Pu = Ts === nothing ? ssrand(1, 2, 3) : ssrand(1, 2, 3; Ts) - Kref, Sref, pref = lqr(Pu, Q, R; extra=Val(true)) - Kd, Sd, pd = lqr(Pu, Q, dualize(R); extra=Val(true)) - @test size(Kd) == size(Kref) == (Pu.nu, Pu.nx) - @test ForwardDiff.value.(Kd) ≈ Kref - @test ForwardDiff.value.(Sd) ≈ Sref - @test sort(pd, by=x->(real(x), imag(x))) ≈ sort(pref, by=x->(real(x), imag(x))) + ref = lqr(Pu, Q, R; extra=Val(true)) + res = lqr(Pu, Q, dualize(R); extra=Val(true)) + @test length(res) == length(ref) + K, X, p = res + @test size(K) == size(ref[1]) == (Pu.nu, Pu.nx) + @test ForwardDiff.value.(K) ≈ ref[1] + @test ForwardDiff.value.(X) ≈ ref[2] + @test sortpoles(p) ≈ sortpoles(ref[3]) + f = function (r) + K, X, _ = lqr(Pu, Q, symR(r); extra=Val(true)) + vcat(vec(K), vec(X)) + end + @test ForwardDiff.jacobian(f, r) ≈ fdjac(f, r) rtol = 1e-5 + + # Keyword arguments of the Riccati solver are not ignored + Xas = are(Pu, Q, R; as=true) + @test !(Xas ≈ are(Pu, Q, R)) + @test ForwardDiff.value.(are(Pu, Q, dualize(R); as=true)) ≈ Xas + f = r -> vec(are(Pu, Q, symR(r); as=true)) + @test ForwardDiff.jacobian(f, r) ≈ fdjac(f, r) rtol = 1e-5 end # Example from the issue, with coupled state variables to obtain a nonzero derivative @@ -122,15 +136,12 @@ let R1 = Matrix{T}(I, 2, 2) R2 = Matrix{T}(I, 1, 1) K = kalman(Discrete, A, C, R1, R2, direct=true) - @test size(K) == (2, 1) K2, _ = kalman(Discrete, A, C, R1, R2, extra=Val(true)) - @test size(K2) == (2, 1) sum(K) + sum(K2) end @test ForwardDiff.derivative(cost, 0.1) ≈ central_fdm(5, 1)(cost, 0.1) rtol = 1e-6 end - # Diff w.r.t. plant P = ssrand(1, 1, 2) Q = I(P.nx)