Skip to content

Commit 99cae97

Browse files
authored
Merge pull request #520 from JuliaControl/doc_d_support_MTK
doc: `ModelingToolkit` section in the manual now supports measured disturbances `d`
2 parents 568778c + 7b06b62 commit 99cae97

2 files changed

Lines changed: 80 additions & 31 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.3"
3+
version = "2.16.4"
44
authors = ["Francis Gagnon"]
55

66
[deps]

‎docs/src/manual/mtk.md‎

Lines changed: 79 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@ objects. This object is then used to design controllers similar to the previous
1515
!!! danger "Disclaimer"
1616
This simple example is not an official interface to `ModelingToolkit.jl`. It is provided
1717
as a basic starting template to combine both packages. There is no guarantee that it
18-
will work for all corner cases. For instance, measured disturbances are not supported in
19-
the current implementation (to be added).
18+
will work for all corner cases.
2019

2120
```@codeblocks
2221
line_counter = :continue
@@ -35,14 +34,17 @@ model, with combined differential states and algebraic variables in a single vec
3534
using ModelPredictiveControl, ModelingToolkit
3635
using ModelingToolkit: D_nounits as D, t_nounits as t
3736
38-
function generate_f_h_mtk(model, inputs, outputs)
37+
function generate_f_h_mtk(model, inputs, outputs, disturbances=nothing)
38+
known_disturbance_inputs = disturbances
3939
(_, f_ip), x_sym, p_sym, io_sys = ModelingToolkit.generate_control_function(
40-
model, inputs, split=false, simplify=true
40+
model, inputs; known_disturbance_inputs, split=false, simplify=true
4141
)
4242
i_alg = ModelingToolkit.is_alg_equation.(equations(io_sys))
43-
function f_mtk!(ẋ, x, u, _ , p)
43+
nd = isnothing(disturbances) ? 0 : length(disturbances)
44+
f_ip_with_d = (nd < 1) ? (ẋ, x, u, p, t, _ ) -> f_ip(ẋ, x, u, p, t) : f_ip
45+
function f_mtk!(ẋ, x, u, d, p)
4446
try
45-
f_ip(ẋ, x, u, p, nothing)
47+
f_ip_with_d(ẋ, x, u, p, nothing, d)
4648
catch err
4749
if err isa MethodError
4850
error("NonLinModel does not support a time argument t in the f "*
@@ -54,15 +56,16 @@ function generate_f_h_mtk(model, inputs, outputs)
5456
return nothing
5557
end
5658
(_, h_ip) = ModelingToolkit.build_explicit_observed_function(
57-
io_sys, outputs; inputs, return_inplace = true
59+
io_sys, outputs; inputs, known_disturbance_inputs, return_inplace = true
5860
)
61+
h_ip_with_d = (nd < 1) ? (y, x, u, p, t, _ ) -> h_ip(y, x, u, p, t) : h_ip
5962
u_nothing = fill(nothing, length(inputs))
60-
function h_mtk!(y, x, _ , p)
63+
function h_mtk!(y, x, d, p)
6164
try
6265
# MTK.jl supports a `u` argument in `h_ip` function but not this package. We
6366
# set `u` as a vector of nothing and `h_ip` function will presumably throw
6467
# an MethodError if this argument is used inside the function
65-
h_ip(y, x, u_nothing, p, nothing)
68+
h_ip_with_d(y, x, u_nothing, p, nothing, d)
6669
catch err
6770
if err isa MethodError
6871
error("NonLinModel only support strictly proper systems (no "*
@@ -99,10 +102,11 @@ this package's interface:
99102

100103
```@example 1
101104
function generate_model(
102-
f_mtk!::F, h_mtk!::H, Ts, i_alg, inputs, outputs, p;
103-
xs_mtk=zeros(length(i_alg)), unit="s", transcription=OrthogonalCollocation()
105+
f_mtk!::F, h_mtk!::H, Ts, i_alg, inputs, outputs, disturbances=nothing;
106+
p=nothing, xs_mtk=zeros(length(i_alg)), unit="s", transcription=OrthogonalCollocation()
104107
) where {F<:Function, H<:Function}
105108
nu, ny = length(inputs), length(outputs)
109+
nd = isnothing(disturbances) ? 0 : length(disturbances)
106110
nx_mtk::Int = length(i_alg)
107111
na::Int = sum(i_alg)
108112
nx::Int = nx_mtk - na
@@ -129,11 +133,11 @@ function generate_model(
129133
end
130134
xs_0, as_0 = xs_mtk[i_x], xs_mtk[i_a]
131135
model = NonLinModelDAE(
132-
fq!, h!, Ts, nu, nx, na, ny; p, unit, xs_0, as_0, transcription
136+
fq!, h!, Ts, nu, nx, na, ny, nd; p, unit, xs_0, as_0, transcription
133137
)
134138
else
135139
f!, h! = f_mtk!, h_mtk!
136-
model = NonLinModel(f!, h!, Ts, nu, nx, ny; p, unit)
140+
model = NonLinModel(f!, h!, Ts, nu, nx, ny, nd; p, unit)
137141
end
138142
return model # deliberately type unstable function
139143
end
@@ -178,7 +182,7 @@ We can now construct a [`SimModel`](@ref) with this specific state realization:
178182

179183
```@example 1
180184
Ts = 0.1
181-
model = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs, p)
185+
model = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs; p)
182186
vu, vx, vy = ["\$τ\$ (Nm)"], ["\$ω\$ (rad/s)", "\$θ\$ (rad)"], ["\$θ\$ (°)"]
183187
model = setname!(model; u=vu, x=vx, y=vy)
184188
```
@@ -191,11 +195,11 @@ coefficient ``K``:
191195
i_K = findfirst(==("K"), string.(p_sym))
192196
p2 = copy(p)
193197
p2[i_K] = 1.25*p[i_K]
194-
plant = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs, p2)
198+
plant = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs; p=p2)
195199
plant = setname!(plant; u=vu, x=vx, y=vy)
196200
```
197201

198-
## Pendulum Controller Design
202+
## Pendulum Controller
199203

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

242246
## Neutralization Reactor Model
243247

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

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

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

268275
```@example 1
269-
inputs, outputs = [q_Bin], [pH]
270-
f_mtk!, h_mtk!, p_sym, p, x_sym, x, i_alg = generate_f_h_mtk(mtk_model, inputs, outputs)
276+
inputs, outputs, disturbances = [q_Bin], [pH], [q_Ain]
277+
f_mtk!, h_mtk!, p_sym, p, x_sym, x, i_alg = generate_f_h_mtk(
278+
mtk_model, inputs, outputs, disturbances
279+
)
271280
[x_sym x]
272281
```
273282

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

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

301310
```@example 1
302311
using Plots
303-
u, x_0 = [10.0], [0.0495, 0.0505]
312+
u, d, x_0 = [10.0], [10.0], [0.0495, 0.0505]
304313
N = 21
305314
using Logging # hide
306315
res = with_logger(ConsoleLogger(stderr, Error)) do # hide
307-
res = sim!(model, N, u; x_0)
316+
res = sim!(model, N, u, d; x_0)
308317
end # hide
309318
p = plot(res)
310319
savefig(p, "plot3_MTK.svg") # hide
@@ -313,6 +322,46 @@ display(p) # hide
313322

314323
![plot3_MTK](plot3_MTK.svg)
315324

325+
## Neutralization Reactor Controller
326+
327+
We next configure the MHE, including an integrating state at the manipulated input:
328+
329+
```@example 1
330+
nint_u=[1] # integrating state at the q_Bin input
331+
He = 8; hessian = true
332+
σ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]
333+
mhe = MovingHorizonEstimator(model; nint_u, He, hessian, σQ, σR, σP_0, σQint_u, σPint_u_0)
334+
using JuMP; unset_time_limit_sec(mhe.optim) # no wall time limit during optimization
335+
mhe = setconstraint!(mhe, x̂min=[0, 0, -Inf])
336+
```
337+
338+
Using the MHE, we configure an NMPC to keep the pH within the desired range:
339+
340+
```@example 1
341+
nmpc = NonLinMPC(mhe, Hp=8, Hc=2, Nwt=[5.0], hessian=true)
342+
using JuMP; unset_time_limit_sec(nmpc.optim) # no wall time limit during optimization
343+
nmpc = setconstraint!(nmpc, ymin=[6], ymax=[8], umin=[0], umax=[20])
344+
```
345+
346+
Finally, we simulate the closed-loop response with a pH setpoint of 7:
347+
348+
```@example 1
349+
ry = [7.0]
350+
x_0, x̂_0 = [0.04, 0.07], [0.025, 0.025, 0]
351+
using Logging # hide
352+
res = with_logger(ConsoleLogger(stderr, Error)) do # hide
353+
res = sim!(nmpc, N, ry, d; x_0, x̂_0)
354+
end # hide
355+
p = plot(res, plotd=false, plotxwithx̂=true, plotx̂min=false, plotŷ=true)
356+
savefig(p, "plot4_MTK.svg") # hide
357+
display(p) # hide
358+
```
359+
360+
![plot4_MTK](plot4_MTK.svg)
361+
362+
As expected, the close-loop response is similar to the one of the [last section](@ref man_dae),
363+
but not identical since the stochastic model of the unmeasured disturbances is different.
364+
316365
## Acknowledgement
317366

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

0 commit comments

Comments
 (0)