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
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "ModelPredictiveControl"
uuid = "61f9bdb8-6ae4-484a-811f-bbf86720c31c"
version = "2.16.3"
version = "2.16.4"
authors = ["Francis Gagnon"]

[deps]
Expand Down
109 changes: 79 additions & 30 deletions docs/src/manual/mtk.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ objects. This object is then used to design controllers similar to the previous
!!! danger "Disclaimer"
This simple example is not an official interface to `ModelingToolkit.jl`. It is provided
as a basic starting template to combine both packages. There is no guarantee that it
will work for all corner cases. For instance, measured disturbances are not supported in
the current implementation (to be added).
will work for all corner cases.

```@codeblocks
line_counter = :continue
Expand All @@ -35,14 +34,17 @@ model, with combined differential states and algebraic variables in a single vec
using ModelPredictiveControl, ModelingToolkit
using ModelingToolkit: D_nounits as D, t_nounits as t

function generate_f_h_mtk(model, inputs, outputs)
function generate_f_h_mtk(model, inputs, outputs, disturbances=nothing)
known_disturbance_inputs = disturbances
(_, f_ip), x_sym, p_sym, io_sys = ModelingToolkit.generate_control_function(
model, inputs, split=false, simplify=true
model, inputs; known_disturbance_inputs, split=false, simplify=true
)
i_alg = ModelingToolkit.is_alg_equation.(equations(io_sys))
function f_mtk!(ẋ, x, u, _ , p)
nd = isnothing(disturbances) ? 0 : length(disturbances)
f_ip_with_d = (nd < 1) ? (ẋ, x, u, p, t, _ ) -> f_ip(ẋ, x, u, p, t) : f_ip
function f_mtk!(ẋ, x, u, d, p)
try
f_ip(ẋ, x, u, p, nothing)
f_ip_with_d(ẋ, x, u, p, nothing, d)
catch err
if err isa MethodError
error("NonLinModel does not support a time argument t in the f "*
Expand All @@ -54,15 +56,16 @@ function generate_f_h_mtk(model, inputs, outputs)
return nothing
end
(_, h_ip) = ModelingToolkit.build_explicit_observed_function(
io_sys, outputs; inputs, return_inplace = true
io_sys, outputs; inputs, known_disturbance_inputs, return_inplace = true
)
h_ip_with_d = (nd < 1) ? (y, x, u, p, t, _ ) -> h_ip(y, x, u, p, t) : h_ip
u_nothing = fill(nothing, length(inputs))
function h_mtk!(y, x, _ , p)
function h_mtk!(y, x, d, p)
try
# MTK.jl supports a `u` argument in `h_ip` function but not this package. We
# set `u` as a vector of nothing and `h_ip` function will presumably throw
# an MethodError if this argument is used inside the function
h_ip(y, x, u_nothing, p, nothing)
h_ip_with_d(y, x, u_nothing, p, nothing, d)
catch err
if err isa MethodError
error("NonLinModel only support strictly proper systems (no "*
Expand Down Expand Up @@ -99,10 +102,11 @@ this package's interface:

```@example 1
function generate_model(
f_mtk!::F, h_mtk!::H, Ts, i_alg, inputs, outputs, p;
xs_mtk=zeros(length(i_alg)), unit="s", transcription=OrthogonalCollocation()
f_mtk!::F, h_mtk!::H, Ts, i_alg, inputs, outputs, disturbances=nothing;
p=nothing, xs_mtk=zeros(length(i_alg)), unit="s", transcription=OrthogonalCollocation()
) where {F<:Function, H<:Function}
nu, ny = length(inputs), length(outputs)
nd = isnothing(disturbances) ? 0 : length(disturbances)
nx_mtk::Int = length(i_alg)
na::Int = sum(i_alg)
nx::Int = nx_mtk - na
Expand All @@ -129,11 +133,11 @@ function generate_model(
end
xs_0, as_0 = xs_mtk[i_x], xs_mtk[i_a]
model = NonLinModelDAE(
fq!, h!, Ts, nu, nx, na, ny; p, unit, xs_0, as_0, transcription
fq!, h!, Ts, nu, nx, na, ny, nd; p, unit, xs_0, as_0, transcription
)
else
f!, h! = f_mtk!, h_mtk!
model = NonLinModel(f!, h!, Ts, nu, nx, ny; p, unit)
model = NonLinModel(f!, h!, Ts, nu, nx, ny, nd; p, unit)
end
return model # deliberately type unstable function
end
Expand Down Expand Up @@ -178,7 +182,7 @@ We can now construct a [`SimModel`](@ref) with this specific state realization:

```@example 1
Ts = 0.1
model = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs, p)
model = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs; p)
vu, vx, vy = ["\$τ\$ (Nm)"], ["\$ω\$ (rad/s)", "\$θ\$ (rad)"], ["\$θ\$ (°)"]
model = setname!(model; u=vu, x=vx, y=vy)
```
Expand All @@ -191,11 +195,11 @@ coefficient ``K``:
i_K = findfirst(==("K"), string.(p_sym))
p2 = copy(p)
p2[i_K] = 1.25*p[i_K]
plant = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs, p2)
plant = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs; p=p2)
plant = setname!(plant; u=vu, x=vx, y=vy)
```

## Pendulum Controller Design
## Pendulum Controller

We can then reproduce the Kalman filter and the controller design of the [penultimate section](@ref man_nonlin)
by reversing the order of `σQ` vector, because of the different state realization:
Expand Down Expand Up @@ -241,14 +245,17 @@ display(p) # hide

## Neutralization Reactor Model

!!! todo "Under Construction"
This section is not finished, only the model conversion is written for now.
This example repeats the neutralization reactor setup from the previous section but with
MTK. The observer and controller are non-adaptive to simplify the design. Instead of
estimating the acid feed concentration, an integrating state is added at the manipulated
input ``q_{Bin}``.

The MTK model of the neutralization reactor from the [last section](@ref man_dae) is
constructed as follows:

```@example 1
@parameters c_Ain=0.1 c_Bin=0.1 Kw=1e-14 Ka=1.75e-5 V=1000 q_Ain=10
@parameters c_Ain=0.1 c_Bin=0.1 Kw=1e-14 Ka=1.75e-5 V=1000
@variables q_Ain(t)=10
@variables c_A(t)=0.025 c_B(t)=0.025 q_Bin(t)=10 pH(t)=7.0
@variables q_out(t) c_Aout(t) c_Bout(t)
eqs = [
Expand All @@ -266,12 +273,14 @@ The substitution ``a_H = 10^{-\mathrm{pH}}`` is explicitly applied in the algebr
to improve the numerical conditioning of the system. The converted model is:

```@example 1
inputs, outputs = [q_Bin], [pH]
f_mtk!, h_mtk!, p_sym, p, x_sym, x, i_alg = generate_f_h_mtk(mtk_model, inputs, outputs)
inputs, outputs, disturbances = [q_Bin], [pH], [q_Ain]
f_mtk!, h_mtk!, p_sym, p, x_sym, x, i_alg = generate_f_h_mtk(
mtk_model, inputs, outputs, disturbances
)
[x_sym x]
```

The content of `x_sym` shows that it chose for the combined state and algebraic vector
The content of `x_sym` shows that it chose for the combined state and algebraic vector this:
``[\begin{smallmatrix}c_B(t) && c_A(t) && \mathrm{pH}(t)\end{smallmatrix}]'``. The states
are thus in the reverse order of the [last section](@ref man_dae). The order of the
parameters is:
Expand All @@ -287,24 +296,24 @@ Ts, unit = 0.5, "h"
xs_mtk = x
transcription = TrapezoidalCollocation()
model = generate_model(
f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs, p; xs_mtk, unit, transcription
f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs, disturbances;
p, xs_mtk, unit, transcription
)
vu = [raw"$q_{Bin}$ (L/min)"]
vu, vd = [raw"$q_{Bin}$ (L/min)"], [raw"$q_{Ain}$ (L/min)"]
vx, vy = [raw"$c_B$ (mol/L)", raw"$c_A$ (mol/L)"], [raw"$\mathrm{pH}$"]
model = setname!(model, u=vu, y=vy, x=vx)
model = setname!(model, u=vu, d=vd, y=vy, x=vx)
```

The returned value is a [`NonLinModelDAE`](@ref) object, as expected. The transient
response is identical to the first 10 hours of the open-loop simulations of the
[last section](@ref man_dae):
The returned value is a [`NonLinModelDAE`](@ref) object, as expected. The transient response
is identical to the first 10 hours of the open-loop simulations in the [last section](@ref man_dae):

```@example 1
using Plots
u, x_0 = [10.0], [0.0495, 0.0505]
u, d, x_0 = [10.0], [10.0], [0.0495, 0.0505]
N = 21
using Logging # hide
res = with_logger(ConsoleLogger(stderr, Error)) do # hide
res = sim!(model, N, u; x_0)
res = sim!(model, N, u, d; x_0)
end # hide
p = plot(res)
savefig(p, "plot3_MTK.svg") # hide
Expand All @@ -313,6 +322,46 @@ display(p) # hide

![plot3_MTK](plot3_MTK.svg)

## Neutralization Reactor Controller

We next configure the MHE, including an integrating state at the manipulated input:

```@example 1
nint_u=[1] # integrating state at the q_Bin input
He = 8; hessian = true
σQ = [0.5e-3, 0.5e-3]; σR=[0.05]; σP_0 = [0.05, 0.05]; σQint_u=[0.15]; σPint_u_0=[0.075]
mhe = MovingHorizonEstimator(model; nint_u, He, hessian, σQ, σR, σP_0, σQint_u, σPint_u_0)
using JuMP; unset_time_limit_sec(mhe.optim) # no wall time limit during optimization
mhe = setconstraint!(mhe, x̂min=[0, 0, -Inf])
```

Using the MHE, we configure an NMPC to keep the pH within the desired range:

```@example 1
nmpc = NonLinMPC(mhe, Hp=8, Hc=2, Nwt=[5.0], hessian=true)
using JuMP; unset_time_limit_sec(nmpc.optim) # no wall time limit during optimization
nmpc = setconstraint!(nmpc, ymin=[6], ymax=[8], umin=[0], umax=[20])
```

Finally, we simulate the closed-loop response with a pH setpoint of 7:

```@example 1
ry = [7.0]
x_0, x̂_0 = [0.04, 0.07], [0.025, 0.025, 0]
using Logging # hide
res = with_logger(ConsoleLogger(stderr, Error)) do # hide
res = sim!(nmpc, N, ry, d; x_0, x̂_0)
end # hide
p = plot(res, plotd=false, plotxwithx̂=true, plotx̂min=false, plotŷ=true)
savefig(p, "plot4_MTK.svg") # hide
display(p) # hide
```

![plot4_MTK](plot4_MTK.svg)

As expected, the close-loop response is similar to the one of the [last section](@ref man_dae),
but not identical since the stochastic model of the unmeasured disturbances is different.

## Acknowledgement

Authored by `1-Bart-1` and `baggepinnen`, thanks for the contribution.
Loading