Skip to content

Commit 56aa83a

Browse files
authored
Merge pull request #425 from JuliaControl/mhe_tc
added: 🟨📐 `TrapezoidalCollocation` 🟨📐 for `MovingHorizonEstimator`
2 parents 7ac8a4d + dd8843c commit 56aa83a

8 files changed

Lines changed: 155 additions & 38 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.10.1"
3+
version = "2.11.0"
44
authors = ["Francis Gagnon"]
55

66
[deps]

‎src/controller/nonlinmpc.jl‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,7 @@ function addinfo!(info, mpc::NonLinMPC{NT}) where NT<:Real
584584
hess = mpc.hessian
585585
transcription = mpc.transcription
586586
nu, ny, nx̂, nϵ = model.nu, model.ny, mpc.estim.nx̂, mpc.nϵ
587-
nk = get_nk_mpc(model, transcription)
587+
nk = get_nk(model, transcription)
588588
Hp, Hc = mpc.Hp, mpc.Hc
589589
i_g = findall(mpc.con.i_g) # convert to non-logical indices for non-allocating @views
590590
ng, ngi = length(mpc.con.i_g), sum(mpc.con.i_g)
@@ -823,7 +823,7 @@ function get_nonlinobj_op(mpc::NonLinMPC, optim::JuMP.GenericModel{JNT}) where J
823823
transcription = mpc.transcription
824824
grad, hess = mpc.gradient, mpc.hessian
825825
nu, ny, nx̂, nϵ = model.nu, model.ny, mpc.estim.nx̂, mpc.nϵ
826-
nk = get_nk_mpc(model, transcription)
826+
nk = get_nk(model, transcription)
827827
Hp, Hc = mpc.Hp, mpc.Hc
828828
ng = length(mpc.con.i_g)
829829
nc, neq = mpc.con.nc, mpc.con.neq
@@ -949,7 +949,7 @@ function get_nonlincon_oracle(mpc::NonLinMPC, ::JuMP.GenericModel{JNT}) where JN
949949
transcription = mpc.transcription
950950
jac, hess = mpc.jacobian, mpc.hessian
951951
nu, ny, nx̂, nϵ = model.nu, model.ny, mpc.estim.nx̂, mpc.nϵ
952-
nk = get_nk_mpc(model, transcription)
952+
nk = get_nk(model, transcription)
953953
Hp, Hc = mpc.Hp, mpc.Hc
954954
i_g = findall(mpc.con.i_g) # convert to non-logical indices for non-allocating @views
955955
ng, ngi = length(mpc.con.i_g), sum(mpc.con.i_g)

‎src/controller/transcription.jl‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,6 @@ function get_nZ_mpc(estim::StateEstimator, transcription::OrthogonalCollocation,
99
return estim.model.nu*Hc + estim.nx̂*Hp + estim.model.nx*transcription.no*Hp
1010
end
1111

12-
"Get length of the `k` vector with all the solver intermediate steps or all the collocation pts."
13-
get_nk_mpc(model::SimModel, ::ShootingMethod) = model.nk
14-
get_nk_mpc(model::SimModel, transcription::CollocationMethod) = model.nx*transcription.no
15-
1612
@doc raw"""
1713
init_predmat(
1814
model::LinModel, estim, transcription::SingleShooting, Hp, Hc, nb
@@ -561,7 +557,7 @@ function init_defectmat_orthocolloc(
561557
Hp, Hc, Co, λo, As, nxs
562558
) where {NT<:Real}
563559
nu, nx, nd, nx̂ = model.nu, model.nx, model.nd, estim.nx̂
564-
nk = get_nk_mpc(model, transcription)
560+
nk = get_nk(model, transcription)
565561
λo_I = λo*I(nx)
566562
# --- current state estimates x̂0 ---
567563
KS = zeros(NT, nx̂*Hp, nx̂)
@@ -1049,7 +1045,7 @@ function set_warmstart_mpc!(
10491045
)
10501046
nu, nx̂ = mpc.estim.model.nu, mpc.estim.nx̂
10511047
Hp, Hc, Z̃s = mpc.Hp, mpc.Hc, mpc.buffer.Z̃
1052-
nk = get_nk_mpc(mpc.estim.model, transcription)
1048+
nk = get_nk(mpc.estim.model, transcription)
10531049
nΔU, nX̂, nK = nu*Hc, nx̂*Hp, nk*Hp
10541050
# --- input increments ΔU ---
10551051
Z̃s[1:(nΔU-nu)] .= @views mpc.Z̃[(nu+1):(nΔU)]
@@ -1403,7 +1399,7 @@ function con_nonlinprogeq!(
14031399
nΔU, nX̂ = nu*Hc, nx̂*Hp
14041400
f_threads = transcription.f_threads
14051401
Ts, p = model.Ts, model.p
1406-
nk = get_nk_mpc(model, transcription)
1402+
nk = get_nk(model, transcription)
14071403
D̂0 = mpc.D̂0
14081404
X̂0_Z̃ = @views Z̃[(nΔU+1):(nΔU+nX̂)]
14091405
Û0 = disturbedinput!(Û0, mpc.estim, mpc.estim.x̂0, X̂0_Z̃, U0)
@@ -1498,7 +1494,7 @@ function con_nonlinprogeq!(
14981494
f_threads = transcription.f_threads
14991495
p = model.p
15001496
Mo, no, τ = mpc.Mo, transcription.no, transcription.τ
1501-
nk = get_nk_mpc(model, transcription)
1497+
nk = get_nk(model, transcription)
15021498
D̂0 = mpc.D̂0
15031499
X̂0_Z̃, K_Z̃ = @views Z̃[(nΔU+1):(nΔU+nX̂)], Z̃[(nΔU+nX̂+1):(nΔU+nX̂+nk*Hp)]
15041500
D̂temp = mpc.buffer.D̂

‎src/estimator/mhe/construct.jl‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,10 @@ struct MovingHorizonEstimator{
170170
He < 1 && throw(ArgumentError("Estimation horizon He should be ≥ 1"))
171171
Cwt < 0 && throw(ArgumentError("Cwt weight should be ≥ 0"))
172172
nym, nyu = validate_ym(model, i_ym)
173+
validate_transcription(model, transcription)
174+
if transcription isa OrthogonalCollocation
175+
error("OrthogonalCollocation is not supported for the MHE for now.")
176+
end
173177
As, Cs_u, Cs_y, nint_u, nint_ym = init_estimstoch(model, i_ym, nint_u, nint_ym)
174178
nxs = size(As, 1)
175179
nx̂ = model.nx + nxs
@@ -329,7 +333,7 @@ at each time step for the optimization.
329333
(details in Extended Help).
330334
- `nc=0` : number of custom nonlinear inequality constraints.
331335
- `p=model.p` : ``\mathbf{g_c}`` functions parameter ``\mathbf{p}`` (any type).
332-
- `transcription=SingleShooting()` : [`SingleShooting`](@ref) or [`MultipleShooting`](@ref).
336+
- `transcription=SingleShooting()` : a [`TranscriptionMethod`](@ref) for the optimization.
333337
- `optim=default_optim_mhe(model,nc)` : a [`JuMP.Model`](@extref) object with a quadratic or
334338
nonlinear optimizer for solving (default to [`Ipopt`](https://github.com/jump-dev/Ipopt.jl),
335339
or [`OSQP`](https://osqp.org/docs/parsers/jump.html) if `model` is a [`LinModel`](@ref)).
@@ -539,7 +543,7 @@ function MovingHorizonEstimator(
539543
gc ::Function = gc!,
540544
nc ::Int = 0,
541545
p = model.p,
542-
transcription::ShootingMethod = DEFAULT_MHE_TRANSCRIPTION,
546+
transcription::TranscriptionMethod = DEFAULT_MHE_TRANSCRIPTION,
543547
optim::JM = default_optim_mhe(model, nc),
544548
gradient::AbstractADType = DEFAULT_GRADIENT,
545549
jacobian::AbstractADType = default_jacobian(transcription),
@@ -593,7 +597,7 @@ function MovingHorizonEstimator(
593597
gc ::Function = gc!,
594598
nc = 0,
595599
p = model.p,
596-
transcription::ShootingMethod = DEFAULT_MHE_TRANSCRIPTION,
600+
transcription::TranscriptionMethod = DEFAULT_MHE_TRANSCRIPTION,
597601
optim::JM = default_optim_mhe(model, nc),
598602
gradient::AbstractADType = DEFAULT_GRADIENT,
599603
jacobian::AbstractADType = default_jacobian(transcription),
@@ -1416,7 +1420,8 @@ function get_nonlinobj_op(
14161420
) where JNT<:Real
14171421
model, con = estim.model, estim.con
14181422
grad, hess = estim.gradient, estim.hessian
1419-
nx̂, nym, nŷ, nu, nk = estim.nx̂, estim.nym, model.ny, model.nu, model.nk
1423+
nx̂, nym, nŷ, nu = estim.nx̂, estim.nym, model.ny, model.nu
1424+
nk = get_nk(model, estim.transcription)
14201425
He = estim.He
14211426
nc, neq, ng = con.nc, con.neq, length(con.i_g)
14221427
nŴ, nV̂, nX̂, ng, nZ̃ = He*nx̂, He*nym, He*nx̂, length(con.i_g), length(estim.Z̃)
@@ -1531,7 +1536,8 @@ function get_nonlincon_oracle(
15311536
# ----------- common cache for all functions ----------------------------------------
15321537
model, con = estim.model, estim.con
15331538
jac, hess = estim.jacobian, estim.hessian
1534-
nx̂, nym, nŷ, nu, nk = estim.nx̂, estim.nym, model.ny, model.nu, model.nk
1539+
nx̂, nym, nŷ, nu = estim.nx̂, estim.nym, model.ny, model.nu
1540+
nk = get_nk(model, estim.transcription)
15351541
He = estim.He
15361542
nc, neq, ng = con.nc, con.neq, length(con.i_g)
15371543
i_g = findall(con.i_g) # convert to non-logical indices for non-allocating @views

‎src/estimator/mhe/execute.jl‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,8 @@ function addinfo!(info, estim::MovingHorizonEstimator{NT}, model::SimModel) wher
213213
# --- objective derivatives ---
214214
optim, con = estim.optim, estim.con
215215
hess = estim.hessian
216-
nx̂, nym, nŷ, nu, nk, nc = estim.nx̂, estim.nym, model.ny, model.nu, model.nk, con.nc
216+
nx̂, nym, nŷ, nu, nc = estim.nx̂, estim.nym, model.ny, model.nu, con.nc
217+
nk = get_nk(model, estim.transcription)
217218
He = estim.He
218219
nc, neq, ng = con.nc, con.neq, length(con.i_g)
219220
i_g = findall(con.i_g) # convert to non-logical indices for non-allocating @views

‎src/estimator/mhe/transcription.jl‎

Lines changed: 90 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -914,7 +914,7 @@ function linconstrainteq!(
914914
JuMP.delete(optim, optim[:linconstrainteq_temp])
915915
JuMP.unregister(optim, :linconstrainteq_temp)
916916
end
917-
if estim.Nk[] < estim.He
917+
if Nk < estim.He
918918
if haskey(optim, :linconstrainteq)
919919
JuMP.delete(optim, optim[:linconstrainteq])
920920
JuMP.unregister(optim, :linconstrainteq)
@@ -1002,10 +1002,10 @@ end
10021002

10031003
@doc raw"""
10041004
set_warmstart_mhe!(
1005-
estim::MovingHorizonEstimator, transcription::MultipleShooting, Z̃var
1005+
estim::MovingHorizonEstimator, transcription::TranscriptionMethod, Z̃var
10061006
) -> Z̃s
10071007
1008-
Do the same but based on a [`MultipleShooting`](@ref) transcription.
1008+
Do the same but for other transcription [`TranscriptionMethod`](@ref).
10091009
10101010
If supported by `estim.optim`, it warm-starts the solver at:
10111011
```math
@@ -1035,7 +1035,7 @@ last control period ``k-1``, expressed as a deviation from the operating point
10351035
of vectors ``\mathbf{0_x̂}`` and ``\mathbf{0_ŵ}``.
10361036
"""
10371037
function set_warmstart_mhe!(
1038-
estim::MovingHorizonEstimator{NT}, transcription::MultipleShooting, Z̃var
1038+
estim::MovingHorizonEstimator{NT}, transcription::TranscriptionMethod, Z̃var
10391039
) where NT<:Real
10401040
model, buffer = estim.model, estim.buffer
10411041
nu, nk = model.nu, model.nk
@@ -1342,13 +1342,14 @@ end
13421342
13431343
Nonlinear MHE equality constrains for [`NonLinModel`](@ref) and [`MultipleShooting`](@ref).
13441344
1345-
The method mutates the `geq`, `X̂0`, `Û0` and `K` vectors in argument. The defects of the
1346-
estimated states are computed with:
1345+
The method mutates the `geq`, `X̂0`, `Û0` and `K` vectors in argument. By introducing
1346+
the integer ``ℓ = k - N_k + p`` to shorten the notation, the defects of the estimated states
1347+
are computed with:
13471348
```math
1348-
\mathbf{ŝ}(k+j+1) = \mathbf{f̂}\Big(\mathbf{x̂_0}(k+j), \mathbf{u_0}(k+j), \mathbf{d_0}(k+j)\Big)
1349-
- \mathbf{x̂_0}(k+j+1)
1349+
\mathbf{ŝ}(ℓ+j+1) = \mathbf{f̂}\Big(\mathbf{x̂_0}(ℓ+j), \mathbf{u_0}(ℓ+j), \mathbf{d_0}(ℓ+j)\Big)
1350+
+ \mathbf{ŵ}(ℓ+j) - \mathbf{x̂_0}(ℓ+j+1)
13501351
```
1351-
for ``j = 0, 1, ... , H_p-1`` and in which the augmented state vectors ``\mathbf{x̂_0}`` are
1352+
for ``j = 0, 1, ... , N_k-1`` and in which the augmented state vectors ``\mathbf{x̂_0}`` are
13521353
extracted from the decision variable `Z̃`. The function ``\mathbf{f̂}`` is defined at [`f̂!`](@ref).
13531354
"""
13541355
function con_nonlinprogeq_mhe!(
@@ -1385,5 +1386,85 @@ function con_nonlinprogeq_mhe!(
13851386
Nk < He && (geq[nx̂*Nk+1:end] .= 0)
13861387
return geq
13871388
end
1389+
1390+
@doc raw"""
1391+
con_nonlinprogeq_mhe!(
1392+
geq, X̂0, Û0, K̇,
1393+
estim::MovingHorizonEstimator, model::NonLinModel, ::TrapezoidalCollocation,
1394+
x̂0arr, Ŵ, Z̃
1395+
) -> geq
1396+
1397+
Nonlinear MHE equality constrains for [`NonLinModel`](@ref) and [`TrapezoidalCollocation`](@ref).
1398+
1399+
By introducing the integer ``ℓ = k - N_k + p`` to shorten the notation, the deterministic
1400+
state defects are computed with:
1401+
```math
1402+
\mathbf{ŝ_d}(ℓ+j+1) = \mathbf{x̂_d}(ℓ+j) + 0.5 T_s [\mathbf{k̇}_1(ℓ+j) + \mathbf{k̇}_2(ℓ+j)]
1403+
+ \mathbf{ŵ_d}(ℓ+j) - \mathbf{x̂_d}(ℓ+j+1)
1404+
```
1405+
for ``j = 0, 1, ... , N_k-1``, and in which ``\mathbf{x̂_d}`` and ``\mathbf{ŵ_d}`` are the
1406+
deterministic state and process noise estimates, respectively, extracted from the decision
1407+
variable `Z̃`. The ``\mathbf{k̇}`` coefficients are evaluated from the continuous-time
1408+
function `model.f!` and:
1409+
```math
1410+
\begin{aligned}
1411+
\mathbf{k̇}_1(ℓ+j) &= \mathbf{f}\Big(\mathbf{x̂_d}(ℓ+j), \mathbf{û_0}(ℓ+j), \mathbf{d̂_0}(ℓ+j), \mathbf{p}\Big) \\
1412+
\mathbf{k̇}_2(ℓ+j) &= \mathbf{f}\Big(\mathbf{x̂_d}(ℓ+j+1), \mathbf{û_0}(ℓ+j+h), \mathbf{d̂_0}(ℓ+j+1), \mathbf{p}\Big)
1413+
\end{aligned}
1414+
```
1415+
in which ``h`` is the hold order `transcription.h` and the disturbed input ``\mathbf{û_0}``
1416+
is defined in [`f̂!`](@ref) documentation.
1417+
"""
1418+
function con_nonlinprogeq_mhe!(
1419+
geq, _ , Û0, K̇,
1420+
estim::MovingHorizonEstimator, model::NonLinModel, transcription::TrapezoidalCollocation,
1421+
x̂0arr, Ŵ, Z̃
1422+
)
1423+
nu, nx, nd, h = model.nu, model.nx, model.nd, transcription.h
1424+
nx̂, nxs, nŵ, He = estim.nx̂, estim.nxs, estim.nx̂, estim.He
1425+
Nk = estim.Nk[]
1426+
f_threads = transcription.f_threads
1427+
Ts = model.Ts
1428+
nk = get_nk(model, transcription)
1429+
nw = nŵ - nxs
1430+
nx̃ = estim.nε + nx̂
1431+
p = estim.direct ? 0 : 1
1432+
X̂0_Z̃ = @views Z̃[(nx̃+1):(nx̃+nx̂*He)]
1433+
Û0 = disturbedinput!(Û0, estim, x̂0arr, X̂0_Z̃, estim.U0)
1434+
@threadsif f_threads for j=1:Nk
1435+
if j < 2
1436+
x̂d_Z̃ = @views x̂0arr[1:nx]
1437+
else
1438+
x̂d_Z̃ = @views X̂0_Z̃[(1 + nx̂*(j-2)):(nx̂*(j-2) + nx)]
1439+
end
1440+
d0 = @views estim.D0[(1 + nd*(j+p-1)):(nd*(j+p))]
1441+
û0 = @views Û0[(1 + nu*(j-1)):(nu*j)]
1442+
k̇ = @views K̇[(1 + nk*(j-1)):(nk*j)]
1443+
ŵd = @views Ŵ[(1 + nŵ*(j-1)):(nŵ*(j-1) + nw)]
1444+
x̂dnext_Z̃ = @views X̂0_Z̃[(1 + nx̂*(j-1)):(nx̂*(j-1) + nx)]
1445+
sdnext = @views geq[(1 + nx*(j-1)):(nx*j)]
1446+
k̇1, k̇2 = @views k̇[1:nx], k̇[nx+1:2*nx]
1447+
d0next = @views estim.D0[(1 + nd*(j+p)):(nd*(j+p+1))]
1448+
if f_threads || h < 1 || j < 2
1449+
# we need to recompute k1 with multi-threading, even with h==1, since the
1450+
# last iteration (j-1) may not be executed (iterations are re-orderable)
1451+
model.f!(k̇1, x̂d_Z̃, û0, d0, model.p)
1452+
else
1453+
k̇1 .= @views K̇[(1 + nk*(j-1)-nx):(nk*(j-1))] # k2 of of the last iter. j-1
1454+
end
1455+
if h < 1
1456+
model.f!(k̇2, x̂dnext_Z̃, û0, d0next, model.p)
1457+
else
1458+
# special case: û0(k+p) ≈ û0(k+p-1), since û0(k+p) is not available at k!
1459+
û0next = @views j ≥ Nk ? û0 : Û0[(1 + nu*j):(nu*(j+1))]
1460+
model.f!(k̇2, x̂dnext_Z̃, û0next, d0next, model.p)
1461+
end
1462+
sdnext .= @. x̂d_Z̃ - x̂dnext_Z̃ + 0.5*Ts*(k̇1 + k̇2)
1463+
sdnext .+= ŵd
1464+
end
1465+
Nk < He && (geq[nx̂*Nk+1:end] .= 0)
1466+
return geq
1467+
end
1468+
13881469
"No nonlinear eq. const. for other cases e.g. [`SingleShooting`](@ref), returns `geq` unchanged."
13891470
con_nonlinprogeq_mhe!(geq,_,_,_,::MovingHorizonEstimator, ::SimModel, ::TranscriptionMethod, _,_,_) = geq

‎src/transcription.jl‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,11 @@ equality constraint function and by using the implicit trapezoidal rule. It can
136136
moderately stiff systems and is A-stable. See Extended Help for more details.
137137
138138
!!! warning
139-
The built-in [`StateEstimator`](@ref) will still use the `solver` provided at the
140-
construction of the [`NonLinModel`](@ref) to estimate the plant states, not the
141-
trapezoidal rule (see `supersample` option of [`RungeKutta`](@ref) for stiff systems).
139+
Except if you construct your MPC with a [`MovingHorizonEstimator`](@ref) based on a
140+
`TrapezoidalCollocation` transcription, the built-in [`StateEstimator`](@ref) will
141+
still use the `solver` provided at the construction of the [`NonLinModel`](@ref) to
142+
estimate the plant states, not the trapezoidal rule (see `supersample` option of
143+
[`RungeKutta`](@ref) for stiff systems).
142144
143145
Sparse optimizers like `Ipopt` and sparse Jacobian computations are recommended for this
144146
transcription method.
@@ -149,7 +151,7 @@ transcription method.
149151
as described in [`ModelPredictiveControl.init_estimstoch`](@ref). Collocation methods
150152
require continuous-time dynamics. Because of this, the stochastic states are transcribed
151153
separately using a [`MultipleShooting`](@ref) method. See [`con_nonlinprogeq!`](@ref)
152-
for more details.
154+
and [`con_nonlinprogeq_mhe!`](@ref) for more details.
153155
"""
154156
struct TrapezoidalCollocation <: CollocationMethod
155157
h::Int
@@ -200,7 +202,8 @@ Gauss-Legendre quadrature, respectively. See [`MultipleShooting`](@ref) docstrin
200202
descriptions of `f_threads` and `h_threads` keywords. This transcription computes the
201203
predictions by enforcing the collocation and continuity constraints at the collocation
202204
points. It is efficient for highly stiff systems, but generally more expensive than the
203-
other methods for non-stiff systems. See Extended Help for more details.
205+
other methods for non-stiff systems. This transcription is not supported by the
206+
[`MovingHorizonEstimator`](@ref) for now. See Extended Help for more details.
204207
205208
!!! warning
206209
The built-in [`StateEstimator`](@ref) will still use the `solver` provided at the
@@ -352,3 +355,7 @@ function validate_transcription(::NonLinModel{<:Real, <:EmptySolver}, ::Collocat
352355
return nothing
353356
end
354357
validate_transcription(::SimModel, ::TranscriptionMethod) = nothing
358+
359+
"Get length of the `k` vector with all the solver intermediate steps or all the collocation pts."
360+
get_nk(model::SimModel, ::ShootingMethod) = model.nk
361+
get_nk(model::SimModel, transcription::CollocationMethod) = model.nx*transcription.no

0 commit comments

Comments
 (0)