Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,122 +1,95 @@
module ControlSystemsBaseImplicitDifferentiationExt
using ControlSystemsBase
import ControlSystemsBase: kalman, lqr, are, ContinuousType, DiscreteType
import ControlSystemsBase: lqr, are, ContinuousType, DiscreteType
using ForwardDiff
using ForwardDiff: Dual
using ImplicitDifferentiation
using ComponentArrays
using LinearAlgebra


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
ControlSystemsBase.are(Continuous, A, B, Q, R), 0
X, rest... = ControlSystemsBase.arec(A, B, R, Q; kw...)
X, rest
end

function conditions_arec(pars, X, noneed)
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...)
pars = ComponentVector(; A,B,Q,R)
X0, _ = implicit_arec(pars)
X = X0 isa AbstractMatrix ? X0 : reshape(X0, size(A))
X
end

"""
lqr(::Continuous, A, B, Q, R::AbstractMatrix{<:Dual})

To make the LQR solver work with dual numbers, make sure that the `R` matrix has the dual number element type.
"""
function lqr(::ContinuousType, A, B, Q, R::AbstractMatrix{<:Dual})
X = are(Continuous, A, B, Q, R)
R\(B'X)
end

"""
kalman(::Continuous, A, C, Q, R::AbstractMatrix{<:Dual})

To make the Kalman solver work with dual numbers, make sure that the `R` matrix has the dual number element type.
"""
function kalman(::ContinuousType, A, C, Q, R::AbstractMatrix{<:Dual})
X = are(Continuous, A', C', Q, R)
(R\(C*X))'
end



## Discrete


function forward_ared(pars)
function forward_ared(pars, kw)
(; A,B,Q,R) = pars
# Q = reshape(Q0, size(A))
ControlSystemsBase.are(Discrete, A, B, Q, R), 0
X, rest... = ControlSystemsBase.ared(A, B, R, Q; kw...)
X, rest
end

function conditions_ared(pars, X, noneed)
# 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)


"""
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.
"""
function are(::DiscreteType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual}; kwargs...)
# 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)
X0, _ = implicit_ared(pars)
X = X0 isa AbstractMatrix ? X0 : reshape(X0, size(A))
X
implicit = te isa ContinuousType ? implicit_arec : implicit_ared
X0, rest = implicit(pars, NamedTuple(kwargs))
reshape(X0, size(A)), rest
end

"""
lqr(::Discrete, A, B, Q, R::AbstractMatrix{<:Dual})
are(::Continuous, A, B, Q, R::AbstractMatrix{<:Dual}; kwargs...)
are(::Discrete, A, B, Q, R::AbstractMatrix{<:Dual}; kwargs...)

To make the LQR 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 lqr(::DiscreteType, A, B, Q, R::AbstractMatrix{<:Dual})
X = are(Discrete, A, B, Q, R)
BX = B'X
(R+BX*B)\(BX*A)
function are(te::ContinuousType, A::AbstractMatrix, B, Q, R::AbstractMatrix{<:Dual}; kwargs...)
first(_are_extra(te, A, B, Q, R; kwargs...))
end

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})
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 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})
X = are(Discrete, A', C', Q, R)
CX = C*X
(R+CX*C')\(CX*A')
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


Expand Down
2 changes: 1 addition & 1 deletion lib/ControlSystemsBase/src/synthesis.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
72 changes: 72 additions & 0 deletions lib/ControlSystemsBase/test/test_implicit_diff.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,78 @@ J2 = fdgrad(difffun, q)
@test J1 ≈ J2 rtol = 1e-6


## 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)
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)

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
end
Ts === nothing && @test_throws ErrorException kalman(P, Q, dualize(R); direct=true)

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
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)
K2, _ = kalman(Discrete, A, C, R1, R2, extra=Val(true))
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)
Expand Down
Loading