Skip to content
Merged
18 changes: 10 additions & 8 deletions docs/src/manual/nonlinmpc2.md
Original file line number Diff line number Diff line change
Expand Up @@ -298,24 +298,26 @@ disturbed by a random-walk, instead of the measured output. Among all the settin
`σR` and `σP_0`, and a past horizon `He` long enough to see the main dynamics can improve
the stability on a highly nonlinear and stiff plant model like here. An exact Hessian matrix
with `hessian=true` also helps for DAEs, since the dynamics are encoded in the nonlinear
equality constraints. We can also bound the three estimated states to positive values since
they are concentrations in mol/L:
equality constraints. We can also bound the three estimated states ``\mathbf{x̂}`` to
positive values since they are concentrations in mol/L, and the estimated algebraic
``\mathbf{â}`` to valid pH values:

```@example 1
nint_ym=0; nint_u=0; # disable the default stochastic model
He = 8; hessian = true
σQ = [0.5e-3, 0.5e-3, 0.9e-3]; σR=[0.05]; σP_0 = [0.05, 0.05, 1e-3]
mhe = MovingHorizonEstimator(model; nint_ym, nint_u, He, hessian, σQ, σR, σP_0)
using JuMP; unset_time_limit_sec(mhe.optim) # no wall time limit during optimization
mhe = setconstraint!(mhe, x̂min=[0, 0, 0])
mhe = setconstraint!(mhe, x̂min=[0, 0, 0], âmin=[1.0], âmax=[14.0])
```

The state constraints are shown in round brackets next to the decision variables. There are
27 of them (3 states × 8 datapoints in the past + 3 arrival estimates). The arrival
covariance ``\mathbf{P̄}`` is constant by default for [`NonLinModelDAE`](@ref), specified by
`σP_0` argument. A proper tuning of `σP_0` and `He` reduces the impact of the constant
arrival approximation. We can now reproduce the last simulated scenario and see how `mhe`
performs under pH and flow rate measurement noise:
45 of them (3 states × 8 datapoints in the past + 3 arrival point + 2 bounds × 1 alg. var. ×
8 datapoints in the past + 2 bounds × 1 arrival point). The arrival covariance ``\mathbf{P̄}``
is constant by default for [`NonLinModelDAE`](@ref), specified by `σP_0` argument. A proper
tuning of `σP_0` and `He` reduces the impact of the constant arrival approximation. We can
now reproduce the last simulated scenario and see how `mhe` performs under pH and flow rate
measurement noise:

```@example 1
using Random
Expand Down
18 changes: 9 additions & 9 deletions src/estimator/mhe/construct.jl
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,7 @@ end
Set the bound constraint parameters of the [`MovingHorizonEstimator`](@ref) `estim`.
It supports both soft and hard constraints on the estimated state ``\mathbf{x̂}``, algebraic
variable ``\mathbf{â}`` (for [`NonLinModelDAE](@ref)), process noise ``\mathbf{ŵ}`` and
variable ``\mathbf{â}`` (for [`NonLinModelDAE`](@ref)), process noise ``\mathbf{ŵ}`` and
sensor noise ``\mathbf{v̂}``:
```math
\begin{alignat*}{3}
Expand Down Expand Up @@ -898,7 +898,7 @@ MovingHorizonEstimator estimator with a sample time Ts = 1.0 s:
- `Âmin` / `Âmax` / `C_âmin` / `C_âmax` : ``\mathbf{Â_e}`` constraints `(na*(He+1),)`.
- `Ŵmin` / `Ŵmax` / `C_ŵmin` / `C_ŵmax` : ``\mathbf{Ŵ}`` constraints `(nx̂*He,)`.
- `V̂min` / `V̂max` / `C_v̂min` / `C_v̂max` : ``\mathbf{V̂}`` constraints `(nym*He,)`.
The subscript ``\mathbf{e}`` stands for extended with the arrival estimate.
The subscript ``\mathbf{e}`` stands for "extended with the arrival estimate".
"""
function setconstraint!(
estim::MovingHorizonEstimator;
Expand Down Expand Up @@ -974,7 +974,7 @@ function setconstraint!(
con.Âmin .= Âmin
end
if isnothing(Âmax) && !isnothing(âmax)
size(âmax) == (na,) || throw(DimensionMismatch("âmax size must be $((nxa,))"))
size(âmax) == (na,) || throw(DimensionMismatch("âmax size must be $((na,))"))
for i in 1:(na*(He+1))
con.Âmax[i] = âmax[(i-1) % na + 1]
end
Expand Down Expand Up @@ -1052,12 +1052,12 @@ function setconstraint!(
if !isnothing(C_âmin)
size(C_âmin) == (nÂe,) || throw(DimensionMismatch("C_âmin size must be $((nÂe,))"))
any(C_âmin .< 0) && error("C_âmin weights should be non-negative")
con.A_âmin[:, begin] .= @. -C_âmin
con.A_Âmin[:, begin] .= @. -C_âmin
end
if !isnothing(C_âmax)
size(C_âmax) == (nÂe,) || throw(DimensionMismatch("C_âmax size must be $((nÂe,))"))
any(C_âmax .< 0) && error("C_âmax weights should be non-negative")
con.A_âmax[:, begin] .= @. -C_âmax
con.A_Âmax[:, begin] .= @. -C_âmax
end
if !isnothing(C_ŵmin)
size(C_ŵmin) == (nŵ*He,) || throw(DimensionMismatch("C_ŵmin size must be $((nŵ*He,))"))
Expand Down Expand Up @@ -1212,8 +1212,8 @@ function init_defaultcon_mhe(
Z̃min, Z̃max = init_boxconstraint_mhe(
model, transcription, He, nx̂, nŵ, nε,
x̂0min, x̂0max, X̂0min, X̂0max, Âmin, Âmax, Ŵmin, Ŵmax,
A_x̂min, A_x̂max, A_Âmin, A_Âmax,
C_x̂min, C_x̂max, A_Ŵmin, A_Ŵmax
A_x̂min, A_x̂max, C_x̂min, C_x̂max,
A_Âmin, A_Âmax, A_Ŵmin, A_Ŵmax
)
i_b, i_g, A, Aeq, neq = init_matconstraint_mhe(
model, transcription, Z̃min, Z̃max, nc, nε,
Expand Down Expand Up @@ -1403,7 +1403,7 @@ end
"""
init_boxconstraint_mhe(
model::SimModel, transcription::TranscriptionMethod, He, nx̂, nŵ, nε,
x̂0min, x̂0max, X̂0min, X̂0max, Âmin, Âmax, Ŵmin, Ŵmax,
x̂0min, x̂0max, X̂0min, X̂0max, Âmin, Âmax, Ŵmin, Ŵmax,
A_x̂min, A_x̂max, C_x̂min, C_x̂max,
A_Âmin, A_Âmax, A_Ŵmin, A_Ŵmax
) -> Z̃min, Z̃max
Expand All @@ -1412,7 +1412,7 @@ Init the decision variable box constraints `Z̃min` and `Z̃max` for [`MovingHor
"""
function init_boxconstraint_mhe(
model::SimModel{NT}, transcription::TranscriptionMethod, He, nx̂, nŵ, nε,
x̂0min, x̂0max, X̂0min, X̂0max, Âmin, Âmax, Ŵmin, Ŵmax,
x̂0min, x̂0max, X̂0min, X̂0max, Âmin, Âmax, Ŵmin, Ŵmax,
A_x̂min, A_x̂max, C_x̂min, C_x̂max,
A_Âmin, A_Âmax, A_Ŵmin, A_Ŵmax
) where {NT<:Real}
Expand Down
11 changes: 5 additions & 6 deletions src/estimator/mhe/execute.jl
Original file line number Diff line number Diff line change
Expand Up @@ -583,12 +583,11 @@ function add_data_windows!(estim::MovingHorizonEstimator, y0m, d0, u0=estim.last
return ismoving
end

"Truncate the bounds `Bmin` and `Bmax` to the window size `Nk` if `Nk < He`."
function trunc_bounds(estim::MovingHorizonEstimator{NT}, Bmin, Bmax, n) where NT<:Real
He, Nk = estim.He, estim.Nk[]
if Nk < He
nB = n*Nk
Bmin_t, Bmax_t = similar(Bmin), similar(Bmax)
"Truncate the bounds `Bmin` and `Bmax` to the window size `N` if `Nk < He`."
function trunc_bounds(estim::MovingHorizonEstimator, Bmin, Bmax, n, N=estim.Nk[])
if estim.Nk[] < estim.He
nB = n*N
Bmin_t, Bmax_t = similar(Bmin), similar(Bmax)
Bmin_t[1:nB] .= @views Bmin[end-nB+1:end]
Bmin_t[nB+1:end] .= -Inf
Bmax_t[1:nB] .= @views Bmax[end-nB+1:end]
Expand Down
12 changes: 8 additions & 4 deletions src/estimator/mhe/transcription.jl
Original file line number Diff line number Diff line change
Expand Up @@ -897,7 +897,6 @@ function linconstraint!(
model.nd > 0 && mul!(FX̂, JX̂, D0, 1, 1)
# --- update b vector for linear inequality constraints ---
nX̂_He, nŴ_He, nV̂_He = length(X̂0min), length(Ŵmin), length(V̂min)
nx̂ = length(estim.con.x̂0min)
n = 0
estim.con.b[(n+1):(n+nx̂)] .= @. -estim.con.x̂0min
n += nx̂
Expand All @@ -923,14 +922,15 @@ end

"Set `b` excluding sensor noise bounds if not a `LinModel` and non-`SingleShooting`."
function linconstraint!(
estim::MovingHorizonEstimator, ::SimModel, ::TranscriptionMethod
estim::MovingHorizonEstimator, model::SimModel, ::TranscriptionMethod
)
nx̂, nŵ = estim.nx̂, estim.nx̂
nx̂, nŵ, na = estim.nx̂, estim.nx̂, get_na(model)
# --- truncate vector and matrices if necessary ---
X̂0min, X̂0max = trunc_bounds(estim, estim.con.X̂0min, estim.con.X̂0max, nx̂)
Ŵmin, Ŵmax = trunc_bounds(estim, estim.con.Ŵmin, estim.con.Ŵmax, nŵ)
Âmin, Âmax = trunc_bounds(estim, estim.con.Âmin, estim.con.Âmax, na, estim.Nk[]+1)
# --- update b vector for linear inequality constraints ---
nx̂, nŴ_He, nX̂_He = length(estim.con.x̂0min), length(Ŵmin), length(X̂0min)
nŴ_He, nX̂_He, nÂe_He = length(Ŵmin), length(X̂0min), length(Âmin)
n = 0
estim.con.b[(n+1):(n+nx̂)] .= @. -estim.con.x̂0min
n += nx̂
Expand All @@ -940,6 +940,10 @@ function linconstraint!(
n += nX̂_He
estim.con.b[(n+1):(n+nX̂_He)] .= @. +X̂0max - estim.con.FX̂
n += nX̂_He
estim.con.b[(n+1):(n+nÂe_He)] .= @. -Âmin
n += nÂe_He
estim.con.b[(n+1):(n+nÂe_He)] .= @. +Âmax
n += nÂe_He
estim.con.b[(n+1):(n+nŴ_He)] .= @. -Ŵmin
n += nŴ_He
estim.con.b[(n+1):(n+nŴ_He)] .= @. +Ŵmax
Expand Down
53 changes: 53 additions & 0 deletions test/2_test_state_estim.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2007,6 +2007,59 @@ end
@test getinfo(mhe2)[:Ŵ] ≈ zeros(nx̂) atol=5e-2
end

@testitem "MHE constraint violation (NonLinModelDAE)" setup=[SetupMPCtests] begin
using .SetupMPCtests, ControlSystemsBase, LinearAlgebra

function fq!(ẋ, res, x, a, u, d, p)
ẋ[] = -p[] * (x[] - 0.2 * u[] - 0.2 * d[])
res[] = x[] - a[]
return nothing
end
function h!(y, x, a, d, _ )
y[] = 2 * x[] + a[] + 0.1 * d[]
end
p = [0.001]
as_0, xs_0 = [-1.0], [1.0]
dae = NonLinModelDAE(fq!, h!, 1000.0, 1, 1, 1, 1, 1; p, xs_0, as_0)

transcription = TrapezoidalCollocation()
mhe2 = MovingHorizonEstimator(dae, He=1, nint_ym=0; transcription)

setconstraint!(mhe2, âmin=[1], âmax=[100])
preparestate!(mhe2, [0.0], [0.0])
updatestate!(mhe2, [10.0], [0.0], [0.0])

info = getinfo(mhe2)
@test info[:â] ≈ [1.0] atol=5e-2

setconstraint!(mhe2, âmin=[-100], âmax=[-1])
preparestate!(mhe2, [0.0], [0.0])
updatestate!(mhe2, [10.0], [0.0], [0.0])

info = getinfo(mhe2)
@test info[:â] ≈ [-1.0] atol=5e-2

transcription = OrthogonalCollocation(0, 2, roots=:gausslegendre)
mhe3 = MovingHorizonEstimator(dae; He=1, nint_ym=0, Cwt=1e4, transcription)

setconstraint!(mhe3, c_âmin=[1], c_âmax=[1])

setconstraint!(mhe3, âmin=[1], âmax=[100])
preparestate!(mhe3, [0.0], [0.0])
updatestate!(mhe3, [10.0], [0.0], [0.0])

info = getinfo(mhe3)
@test info[:â] ≈ [1.0] atol=5e-2

setconstraint!(mhe3, âmin=[-100], âmax=[-1])
preparestate!(mhe3, [0.0], [0.0])
updatestate!(mhe3, [10.0], [0.0], [0.0])

info = getinfo(mhe3)
@test info[:â] ≈ [-1.0] atol=5e-2

end

@testitem "MHE set model" setup=[SetupMPCtests] begin
using .SetupMPCtests, ControlSystemsBase, LinearAlgebra
linmodel = LinModel([0.5], [0.3], [1.0], 0, 0, 10.0)
Expand Down
Loading