Skip to content

Commit de351a0

Browse files
authored
Merge pull request #529 from JuliaControl/weight_cov
added: `ExplicitMPC` now support AD with `Mooncake.jl` + `warn_cond` kwarg
2 parents dd67ee0 + a7346af commit de351a0

10 files changed

Lines changed: 117 additions & 101 deletions

File tree

‎Project.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "ModelPredictiveControl"
22
uuid = "61f9bdb8-6ae4-484a-811f-bbf86720c31c"
3-
version = "2.16.6"
3+
version = "2.16.7"
44
authors = ["Francis Gagnon"]
55

66
[deps]

‎src/controller/construct.jl‎

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -573,12 +573,29 @@ reset_nonlincon!(::PredictiveController) = nothing
573573
Estimate the default prediction horizon `Hp` for [`LinModel`](@ref).
574574
"""
575575
default_Hp(model::LinModel) = DEFAULT_HP0 + estimate_delays(model)
576-
"Throw an error when model is not a [`LinModel`](@ref)."
576+
"Throw an error when `model` is not a [`LinModel`](@ref)."
577577
function default_Hp(::SimModelODE)
578578
msg = "Prediction horizon Hp must be explicitly specified if model is not a LinModel."
579579
throw(ArgumentError(msg))
580580
end
581581

582+
"Warn if `Hp ≤ nk`, where `nk` is the estimated delays `model`."
583+
function verify_delays(model::LinModel, Hp)
584+
nk = try
585+
estimate_delays(model)
586+
catch
587+
NaN
588+
end
589+
if Hp ≤ nk
590+
@warn("prediction horizon Hp ($Hp) ≤ estimated number of delays in model "*
591+
"($nk), the closed-loop system may be unstable or zero-gain (unresponsive)")
592+
end
593+
isnan(nk) && @warn("could not estimate the model delay, Hp ($Hp) might be too small.")
594+
return nothing
595+
end
596+
"Do nothing when `model` is not a [`LinModel`](@ref)."
597+
verify_delays(::SimModel, _ ) = nothing
598+
582599
"""
583600
estimate_delays(model::LinModel)
584601
@@ -846,37 +863,31 @@ function init_quadprog(
846863
)
847864
M_Hp, Ñ_Hc, L_Hp = weights.M_Hp, weights.Ñ_Hc, weights.L_Hp
848865
H̃ = Hermitian(2*(Ẽ'*M_Hp*Ẽ + P̃Δu'*Ñ_Hc*P̃Δu + P̃u'*L_Hp*P̃u), :L)
866+
warn_cond = isinf(warn_cond) ? nothing : warn_cond
849867
verify_cond(transcription, H̃, warn_cond)
850868
return H̃
851869
end
852870
"Return empty matrix if `model` is not a [`LinModel`](@ref)."
853871
function init_quadprog(
854-
::SimModel{NT}, ::TranscriptionMethod, ::ControllerWeights, args...; kwargs...
855-
) where {NT<:Real}
856-
H̃ = Hermitian(zeros(NT, 0, 0), :L)
857-
return H̃
872+
::SimModel, ::TranscriptionMethod, weights::ControllerWeights, args...; kwargs...
873+
)
874+
return empty_similar(weights.M_Hp)
858875
end
859876

860877
"Check the condition number of `H̃` and display a `@warn` if `cond(H̃) > warn_cond`."
861-
function verify_cond(::SingleShooting, H̃, warn_cond)
862-
if !isinf(warn_cond)
863-
cond_H̃ = try
864-
cond(H̃)
865-
catch
866-
NaN
867-
end
868-
cond_H̃ > warn_cond && @warn(
869-
"The Hessian condition number cond_H̃ > $warn_cond. The optimization " *
870-
"problem may be ill-conditioned.\n Consider changing the tunings, using " *
871-
"MultipleShooting, or using an optimizer more robust to this like DAQP.",
872-
cond_H̃,
873-
)
874-
isnan(cond_H̃) && @warn("could not validate the condition number of the QP Hessian.")
875-
end
878+
function verify_cond(::SingleShooting, H̃, warn_cond::Real)
879+
cond_H̃ = cond(H̃)
880+
cond_H̃ > warn_cond && @warn(
881+
"The Hessian condition number cond_H̃ > $warn_cond. The optimization " *
882+
"problem may be ill-conditioned.\n Consider changing the tunings, using " *
883+
"MultipleShooting, or using an optimizer more robust to this like DAQP.",
884+
cond_H̃,
885+
)
876886
return nothing
877887
end
878-
"No check if `transcription` is not a `SingleShooting`."
879-
verify_cond(::TranscriptionMethod, _, _) = nothing
888+
"No check if `transcription` is not a `SingleShooting` or `isnothing(warn_cond)`."
889+
verify_cond(::TranscriptionMethod, _ , ::Any) = nothing
890+
verify_cond(::SingleShooting, _ , ::Nothing) = nothing
880891

881892
"""
882893
init_defaultcon_mpc(

‎src/controller/explicitmpc.jl‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ struct ExplicitMPC{
4141
Dop::Vector{NT}
4242
buffer::PredictiveControllerBuffer{NT}
4343
function ExplicitMPC{NT}(
44-
estim::SE, Hp, Hc, nb, weights::CW
44+
estim::SE, Hp, Hc, nb, weights::CW;
45+
warn_cond=1e6
4546
) where {NT<:Real, SE<:StateEstimator, CW<:ControllerWeights}
4647
model = estim.model
4748
nu, ny, nd, nx̂ = model.nu, model.ny, model.nd, estim.nx̂
@@ -57,7 +58,7 @@ struct ExplicitMPC{
5758
E, G, J, K, V, B = init_predmat(model, estim, transcription, Hp, Hc, nb)
5859
F = zeros(NT, ny*Hp) # dummy value (updated just before optimization)
5960
P̃Δu, P̃u, Ẽ = PΔu, Pu, E # no slack variable ϵ for ExplicitMPC
60-
H̃ = init_quadprog(model, transcription, weights, Ẽ, P̃Δu, P̃u)
61+
H̃ = init_quadprog(model, transcription, weights, Ẽ, P̃Δu, P̃u; warn_cond)
6162
# dummy vals (updated just before optimization):
6263
q̃, r = zeros(NT, size(H̃, 1)), zeros(NT, 1)
6364
H̃_chol = cholesky(H̃)
@@ -142,10 +143,11 @@ function ExplicitMPC(
142143
M_Hp = Diagonal(repeat(Mwt, Hp)),
143144
N_Hc = Diagonal(repeat(Nwt, get_Hc(move_blocking(Hp, Hc)))),
144145
L_Hp = Diagonal(repeat(Lwt, Hp)),
146+
warn_cond=1e6,
145147
kwargs...
146148
)
147149
estim = SteadyKalmanFilter(model; kwargs...)
148-
return ExplicitMPC(estim; Hp, Hc, Mwt, Nwt, Lwt, M_Hp, N_Hc, L_Hp)
150+
return ExplicitMPC(estim; Hp, Hc, Mwt, Nwt, Lwt, M_Hp, N_Hc, L_Hp, warn_cond)
149151
end
150152

151153
"""
@@ -165,29 +167,21 @@ function ExplicitMPC(
165167
M_Hp = Diagonal(repeat(Mwt, Hp)),
166168
N_Hc = Diagonal(repeat(Nwt, get_Hc(move_blocking(Hp, Hc)))),
167169
L_Hp = Diagonal(repeat(Lwt, Hp)),
170+
warn_cond=1e6,
168171
) where {NT<:Real, SE<:StateEstimator{NT}}
169172
isa(estim.model, LinModel) || error(MSG_LINMODEL_ERR)
170-
nk = try
171-
estimate_delays(estim.model)
172-
catch myerr
173-
NaN
174-
end
175-
if Hp ≤ nk
176-
@warn("prediction horizon Hp ($Hp) ≤ estimated number of delays in model "*
177-
"($nk), the closed-loop system may be unstable or zero-gain (unresponsive)")
178-
end
179-
isnan(nk) && @warn("could not estimate the model delay, Hp ($Hp) might be too small.")
173+
verify_delays(estim.model, Hp)
180174
nb = move_blocking(Hp, Hc)
181175
Hc = get_Hc(nb)
182176
weights = ControllerWeights(estim.model, Hp, Hc, M_Hp, N_Hc, L_Hp)
183-
return ExplicitMPC{NT}(estim, Hp, Hc, nb, weights)
177+
return ExplicitMPC{NT}(estim, Hp, Hc, nb, weights; warn_cond)
184178
end
185179

186180
setconstraint!(::ExplicitMPC; kwargs...) = error("ExplicitMPC does not support constraints.")
187181

188182
function Base.show(io::IO, mpc::ExplicitMPC)
189183
estim, model = mpc.estim, mpc.estim.model
190-
Hp, Hc, nϵ = mpc.Hp, mpc.Hc, mpc.nϵ
184+
Hp, Hc = mpc.Hp, mpc.Hc
191185
nu, nd = model.nu, model.nd
192186
nx̂, nym, nyu = estim.nx̂, estim.nym, estim.nyu
193187
n = maximum(ndigits.((Hp, Hc, nu, nx̂, nym, nyu, nd))) + 1

‎src/controller/linmpc.jl‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ struct LinMPC{
4848
function LinMPC{NT}(
4949
estim::SE, Hp, Hc, nb, weights::CW,
5050
Wy, Wu, Wd, Wr,
51-
transcription::TM, optim::JM
51+
transcription::TM, optim::JM;
52+
warn_cond=1e6
5253
) where {
5354
NT<:Real,
5455
SE<:StateEstimator,
@@ -79,7 +80,7 @@ struct LinMPC{
7980
ES, GS, JS, KS, VS, BS,
8081
Wy, Wu, Wd, Wr
8182
)
82-
H̃ = init_quadprog(model, transcription, weights, Ẽ, P̃Δu, P̃u)
83+
H̃ = init_quadprog(model, transcription, weights, Ẽ, P̃Δu, P̃u; warn_cond)
8384
# dummy vals (updated just before optimization):
8485
q̃, r = zeros(NT, size(H̃, 1)), zeros(NT, 1)
8586
Ks, Ps = init_stochpred(estim, Hp)
@@ -168,6 +169,8 @@ arguments. This controller allocates memory at each time step for the optimizati
168169
- `optim=JuMP.Model(OSQP.MathOptInterfaceOSQP.Optimizer)` : quadratic optimizer used in
169170
the predictive controller, provided as a [`JuMP.Model`](@extref) object (default to
170171
[`OSQP`](https://osqp.org/docs/parsers/jump.html) optimizer).
172+
- `warn_cond=1e6` : warn if the condition number of the Hessian for the QP exceeds this
173+
value, use `warn_cond=Inf` to skip the check.
171174
- additional keyword arguments are passed to [`SteadyKalmanFilter`](@ref) constructor.
172175
173176
# Examples
@@ -242,12 +245,14 @@ function LinMPC(
242245
Cwt = DEFAULT_CWT,
243246
transcription::ShootingMethod = SingleShooting(),
244247
optim::JuMP.GenericModel = JuMP.Model(DEFAULT_QP_OPTIMIZER, add_bridges=true),
248+
warn_cond=1e6,
245249
kwargs...
246250
)
247251
estim = SteadyKalmanFilter(model; kwargs...)
248252
return LinMPC(
249-
estim;
250-
Hp, Hc, Mwt, Nwt, Lwt, Cwt, M_Hp, N_Hc, L_Hp, Wy, Wu, Wd, Wr, transcription, optim
253+
estim;
254+
Hp, Hc, Mwt, Nwt, Lwt, Cwt, M_Hp, N_Hc, L_Hp, Wy, Wu, Wd, Wr,
255+
transcription, optim, warn_cond
251256
)
252257
end
253258

@@ -300,18 +305,17 @@ function LinMPC(
300305
Wr = nothing,
301306
Cwt = DEFAULT_CWT,
302307
transcription::ShootingMethod = SingleShooting(),
303-
optim::JM = JuMP.Model(DEFAULT_QP_OPTIMIZER, add_bridges=true)
308+
optim::JM = JuMP.Model(DEFAULT_QP_OPTIMIZER, add_bridges=true),
309+
warn_cond=1e6
304310
) where {NT<:Real, SE<:StateEstimator{NT}, JM<:JuMP.GenericModel}
305311
isa(estim.model, LinModel) || error(MSG_LINMODEL_ERR)
306-
nk = estimate_delays(estim.model)
307-
if Hp ≤ nk
308-
@warn("prediction horizon Hp ($Hp) ≤ estimated number of delays in model "*
309-
"($nk), the closed-loop system may be unstable or zero-gain (unresponsive)")
310-
end
312+
verify_delays(estim.model, Hp)
311313
nb = move_blocking(Hp, Hc)
312314
Hc = get_Hc(nb)
313315
weights = ControllerWeights(estim.model, Hp, Hc, M_Hp, N_Hc, L_Hp, Cwt)
314-
return LinMPC{NT}(estim, Hp, Hc, nb, weights, Wy, Wu, Wd, Wr, transcription, optim)
316+
return LinMPC{NT}(
317+
estim, Hp, Hc, nb, weights, Wy, Wu, Wd, Wr, transcription, optim; warn_cond
318+
)
315319
end
316320

317321
"""

‎src/controller/nonlinmpc.jl‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -449,11 +449,7 @@ function NonLinMPC(
449449
NT<:Real,
450450
SE<:StateEstimator{NT}
451451
}
452-
nk = estimate_delays(estim.model)
453-
if Hp ≤ nk
454-
@warn("prediction horizon Hp ($Hp) ≤ estimated number of delays in model "*
455-
"($nk), the closed-loop system may be unstable or zero-gain (unresponsive)")
456-
end
452+
verify_delays(estim.model, Hp)
457453
nb = move_blocking(Hp, Hc)
458454
Hc = get_Hc(nb)
459455
validate_JE(NT, JE)

‎src/controller/transcription.jl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -572,7 +572,7 @@ function init_defectmat(
572572
model::SimModel, estim::InternalModel{NT}, transcription::OrthogonalCollocation,
573573
Hp, Hc, _ , Co, λo
574574
) where {NT<:Real}
575-
As, nxs = zeros(NT, 0, 0), 0 # the state vector is not augmented, no stochastic defects
575+
As, nxs = empty_similar(estim.As), 0 # state vector not augmented, no stochastic defects
576576
return init_defectmat_orthocolloc(model, estim, transcription, Hp, Hc, Co, λo, As, nxs)
577577
end
578578

‎src/estimator/construct.jl‎

Lines changed: 24 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -87,58 +87,42 @@ struct KalmanCovariances{
8787
invQ̂_He::Hermitian{NT, Q̂C}
8888
invR̂_He::Hermitian{NT, R̂C}
8989
function KalmanCovariances{NT}(
90-
Q̂::Q̂C, R̂::R̂C, P̂_0, He
90+
Q̂::Q̂C, R̂::R̂C, P̂_0=nothing, He=nothing
9191
) where {NT<:Real, Q̂C<:AbstractMatrix{NT}, R̂C<:AbstractMatrix{NT}}
9292
if isnothing(P̂_0)
93-
P̂_0 = Hermitian(zeros(NT, 0, 0), :L) # don't apply to SteadyKalmanFilter
94-
P̂ = Hermitian(zeros(NT, size(Q̂)), :L) # will hold the steady-state error covariance
95-
invP̄ = copy(P̂_0)
93+
P̂ = Hermitian(zeros(NT, size(Q̂)), :L) # will hold steady-state error covariance
94+
P̂_0 = empty_similar(P̂) # don't apply to SteadyKalmanFilter
95+
invP̄ = empty_similar(P̂) # don't apply to SteadyKalmanFilter
9696
else
97-
P̂_0 = Hermitian(P̂_0, :L)
98-
P̂, invP̄ = copy(P̂_0), copy(P̂_0)
99-
try
100-
inv!(invP̄)
101-
catch err
102-
if err isa PosDefException
103-
error("P̂_0 is not positive definite")
104-
else
105-
rethrow()
97+
P̂_0 = Hermitian(P̂_0, :L)
98+
P̂ = copy(P̂_0)
99+
if isnothing(He) # invP̄ is only necessary for MovingHorizonEstimator:
100+
invP̄ = empty_similar(P̂_0)
101+
else
102+
invP̄ = copy(P̂_0)
103+
inv!(invP̄)
106104
end
107105
end
108-
end
109-
P̂_0 = Hermitian(P̂_0, :L)
110-
P̂ = Hermitian(P̂, :L)
111-
Q̂ = Hermitian(Q̂, :L)
112-
R̂ = Hermitian(R̂, :L)
113-
# the following variables are only for the moving horizon estimator:
114-
invQ̂, invR̂ = copy(Q̂), copy(R̂)
115-
try
106+
Q̂ = Hermitian(Q̂, :L)
107+
R̂ = Hermitian(R̂, :L)
108+
if isnothing(He) # the following variables are only for MovingHorizonEstimator:
109+
invQ̂_He = empty_similar(Q̂)
110+
invR̂_He = empty_similar(R̂)
111+
else
112+
invQ̂ = copy(Q̂)
116113
inv!(invQ̂)
117-
catch err
118-
if err isa PosDefException
119-
error("Q̂ is not positive definite")
120-
else
121-
rethrow()
122-
end
123-
end
124-
invQ̂_He = Hermitian(repeatdiag(invQ̂, He), :L)
125-
try
114+
invQ̂_He = Hermitian(repeatdiag(invQ̂, He), :L)
115+
invR̂ = copy(R̂)
126116
inv!(invR̂)
127-
catch err
128-
if err isa PosDefException
129-
error("R̂ is not positive definite")
130-
else
131-
rethrow()
132-
end
117+
invR̂_He = Hermitian(repeatdiag(invR̂, He), :L)
133118
end
134-
invR̂_He = Hermitian(repeatdiag(invR̂, He), :L)
135119
return new{NT, Q̂C, R̂C}(P̂_0, P̂, Q̂, R̂, invP̄, invQ̂_He, invR̂_He)
136120
end
137121
end
138122

139123
"Outer constructor to validate and convert covariance matrices if necessary."
140124
function KalmanCovariances(
141-
model::SimModel{NT}, i_ym, nint_u, nint_ym, Q̂, R̂, P̂_0=nothing, He=1
125+
model::SimModel{NT}, i_ym, nint_u, nint_ym, Q̂, R̂, P̂_0=nothing, He=nothing
142126
) where {NT<:Real}
143127
validate_kfcov(model, i_ym, nint_u, nint_ym, Q̂, R̂, P̂_0)
144128
Q̂ = eltype(Q̂) == NT ? Q̂ : NT.(Q̂)
@@ -200,7 +184,8 @@ function init_estimstoch(
200184
nu, ny, nym = model.nu, model.ny, length(i_ym)
201185
As_u , Cs_u , nint_u = init_integrators(nint_u , nu , "u")
202186
As_ym, Cs_ym, nint_ym = init_integrators(nint_ym, nym, "ym")
203-
As_y, _ , Cs_y = stoch_ym2y(model, i_ym, As_ym, zeros(NT, 0, 0), Cs_ym, zeros(NT, 0, 0))
187+
Bs_ym = Ds_ym = empty_similar(As_ym)
188+
As_y, _ , Cs_y = stoch_ym2y(model, i_ym, As_ym, Bs_ym, Cs_ym, Ds_ym)
204189
nxs_u, nxs_y = size(As_u, 1), size(As_y, 1)
205190
# combines input and output stochastic models:
206191
As = [As_u zeros(NT, nxs_u, nxs_y); zeros(NT, nxs_y, nxs_u) As_y]

‎src/general.jl‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,12 +269,17 @@ to_mat(A::AbstractVector, _ ...) = reshape(A, length(A), 1)
269269
to_mat(A::AbstractMatrix, _ ...) = A
270270
to_mat(A::Real, dims...) = fill(A, dims)
271271

272-
"Convert 1-element vectors and normal matrices to Hermitians."
272+
"Convert 1-element vectors and normal matrices to `Hermitian`s."
273273
to_hermitian(A::AbstractVector) = Hermitian(reshape(A, 1, 1), :L)
274274
to_hermitian(A::AbstractMatrix) = Hermitian(A, :L)
275275
to_hermitian(A::Hermitian) = A
276276
to_hermitian(A) = A
277277

278+
"Return a 0×0 matrix with the same type as `A`, and assert an identical returned type."
279+
empty_similar(A::AbstractMatrix) = similar(A, (0, 0))::typeof(A)
280+
empty_similar(A::Diagonal) = Diagonal(similar(A.diag, (0,)))::typeof(A)
281+
empty_similar(A::Hermitian) = to_hermitian(empty_similar(parent(A)))::typeof(A)
282+
278283
"""
279284
Compute the inverse of a the Hermitian positive definite matrix `A` in-place and return it.
280285

‎test/2_test_state_estim.jl‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,15 +1020,34 @@ end
10201020
He = 3
10211021
nx̂ = linmodel.nx
10221022
nc = nx̂*(He+1)
1023-
mhe = MovingHorizonEstimator(linmodel, nint_ym=0, Cwt=1e5, He=He, gc=gcl, nc=nc, p=nc)
1024-
@test mhe.con.nc == nc
1025-
@test mhe.nε > 0
1026-
@test mhe.He == 3
1027-
1023+
mhe16 = MovingHorizonEstimator(linmodel, nint_ym=0, Cwt=1e5, He=He, gc=gcl, nc=nc, p=nc)
1024+
@test mhe16.con.nc == nc
1025+
@test mhe16.nε > 0
1026+
@test mhe16.He == 3
1027+
1028+
He, i_ym, nint_u, nint_ym = 1, 1:2, 0, 0
1029+
P̂_0 = fill(0.5, 4, 4)
1030+
P̂_0[diagind(P̂_0)] .= 1.0
1031+
Q̂, R̂ = 0.5*P̂_0, [0.1 0.01; 0.01 0.1]
1032+
mhe17 = MovingHorizonEstimator(linmodel, He, i_ym, nint_u, nint_ym, P̂_0, Q̂, R̂)
1033+
@test mhe17.cov.invP̄ ≈ inv(P̂_0)
1034+
@test mhe17.cov.invQ̂_He ≈ inv(Q̂)
1035+
@test mhe17.cov.invR̂_He ≈ inv(R̂)
1036+
10281037
@test_throws ArgumentError MovingHorizonEstimator(linmodel)
10291038
@test_throws ArgumentError MovingHorizonEstimator(linmodel, He=0)
10301039
@test_throws ArgumentError MovingHorizonEstimator(linmodel, Cwt=-1)
10311040
@test_throws ArgumentError MovingHorizonEstimator(linmodel, He=1, σP_0=nothing)
1041+
@test_throws PosDefException MovingHorizonEstimator(
1042+
linmodel, He, i_ym, nint_u, nint_ym, zeros(4, 4), Q̂, R̂
1043+
)
1044+
@test_throws PosDefException MovingHorizonEstimator(
1045+
linmodel, He, i_ym, nint_u, nint_ym, P̂_0, zeros(4, 4), R̂
1046+
)
1047+
@test_throws PosDefException MovingHorizonEstimator(
1048+
linmodel, He, i_ym, nint_u, nint_ym, P̂_0, Q̂, zeros(2, 2)
1049+
)
1050+
10321051
end
10331052

10341053
@testitem "MHE construction (NonLinModel)" setup=[SetupMPCtests] begin

0 commit comments

Comments
 (0)