Skip to content

Commit 3ab73ae

Browse files
authored
Merge pull request #518 from JuliaControl/doc_mtk_dae
doc: `ModelingToolkit` section in the manual now supports DAEs
2 parents 9d6601a + 8a613d3 commit 3ab73ae

2 files changed

Lines changed: 191 additions & 47 deletions

File tree

‎docs/src/manual/mtk.md‎

Lines changed: 190 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -4,56 +4,49 @@
44
Pages = ["mtk.md"]
55
```
66

7-
## Pendulum Model
7+
## Introduction
88

9-
This example integrates the simple pendulum model of the [penultimate section](@ref man_nonlin)
10-
in [`ModelingToolkit`](https://docs.sciml.ai/ModelingToolkit/stable/) (MTK) framework and
11-
extracts appropriate `f!` and `h!` functions to construct a [`NonLinModel`](@ref). An
12-
[`NonLinMPC`](@ref) is designed from this model and simulated to reproduce the results of
13-
the last section.
9+
This example integrates the simple pendulum and pH neutralization models of the
10+
[penultimate section](@ref man_nonlin) and [ultimate section](@ref man_dae), respectively,
11+
in the [`ModelingToolkit`](https://docs.sciml.ai/ModelingToolkit/stable/) (MTK) framework.
12+
It then extracts functions with appropriate signature to construct [`SimModel`](@ref)
13+
objects. This object is then used to design controllers similar to the previous sections.
1414

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.
19-
20-
We first construct and instantiate the pendulum model:
18+
will work for all corner cases. For instance, measured disturbances are not supported in
19+
the current implementation (to be added).
2120

2221
```@codeblocks
2322
line_counter = :continue
2423
```
2524

25+
## MTK Model Conversion
26+
27+
We first define two methods that convert MTK model to either a [`NonLinModel`](@ref) or a
28+
[`NonLinModelDAE`](@ref), depending on the presence of algebraic equations. The methods rely
29+
on [input-output systems](https://docs.sciml.ai/ModelingToolkit/stable/basics/InputOutput/).
30+
The `generate_f_h_mtk` method extracts the `f_mtk!` and `h_mtk!` functions from the MTK
31+
model, with combined differential states and algebraic variables in a single vector. The
32+
`i_alg` boolean vector indicates which elements of the state vector are algebraic variables:
33+
2634
```@example 1
2735
using ModelPredictiveControl, ModelingToolkit
2836
using ModelingToolkit: D_nounits as D, t_nounits as t
29-
@parameters g=9.8 L=0.4 K=1.2 m=0.3
30-
@variables θ(t)=0 ω(t)=0 τ(t)=0 y(t)
31-
eqs = [
32-
D(θ) ~ ω
33-
D(ω) ~ -g/L*sin(θ) - K/m*ω + τ/m/L^2
34-
y ~ θ * 180 / π
35-
]
36-
@named mtk_model = System(eqs, t)
37-
```
3837
39-
We than convert the MTK model to an [input-output system](https://docs.sciml.ai/ModelingToolkit/stable/basics/InputOutput/):
40-
41-
```@example 1
42-
function generate_f_h(model, inputs, outputs)
38+
function generate_f_h_mtk(model, inputs, outputs)
4339
(_, f_ip), x_sym, p_sym, io_sys = ModelingToolkit.generate_control_function(
4440
model, inputs, split=false, simplify=true
4541
)
46-
if any(ModelingToolkit.is_alg_equation, equations(io_sys))
47-
error("Systems with algebraic equations are not supported")
48-
end
49-
nu, nx, ny = length(inputs), length(x_sym), length(outputs)
50-
function f!(ẋ, x, u, _ , p)
42+
i_alg = ModelingToolkit.is_alg_equation.(equations(io_sys))
43+
function f_mtk!(ẋ, x, u, _ , p)
5144
try
5245
f_ip(ẋ, x, u, p, nothing)
5346
catch err
5447
if err isa MethodError
5548
error("NonLinModel does not support a time argument t in the f "*
56-
"function, see the constructor docstring for a workaround.")
49+
"function, see the constructor docstring for a workaround.")
5750
else
5851
rethrow()
5952
end
@@ -63,8 +56,8 @@ function generate_f_h(model, inputs, outputs)
6356
(_, h_ip) = ModelingToolkit.build_explicit_observed_function(
6457
io_sys, outputs; inputs, return_inplace = true
6558
)
66-
u_nothing = fill(nothing, nu)
67-
function h!(y, x, _ , p)
59+
u_nothing = fill(nothing, length(inputs))
60+
function h_mtk!(y, x, _ , p)
6861
try
6962
# MTK.jl supports a `u` argument in `h_ip` function but not this package. We
7063
# set `u` as a vector of nothing and `h_ip` function will presumably throw
@@ -81,8 +74,11 @@ function generate_f_h(model, inputs, outputs)
8174
return nothing
8275
end
8376
ic = initial_conditions(io_sys)
84-
p_map = try
85-
Dict(sym => ic[sym] for sym in p_sym)
77+
p_map, x_map = try
78+
(
79+
Dict(sym => ic[sym] for sym in p_sym),
80+
Dict(sym => ic[sym] for sym in x_sym)
81+
)
8682
catch err
8783
if err isa KeyError # the key presumably appears in `bindings(io_sys)`:
8884
error("Non-constant parameter values are not supported (a.k.a. bindings)")
@@ -91,43 +87,117 @@ function generate_f_h(model, inputs, outputs)
9187
end
9288
end
9389
p = ModelingToolkit.varmap_to_vars(p_map, p_sym)
94-
return f!, h!, p, x_sym, p_sym, nu, nx, ny
90+
x = ModelingToolkit.varmap_to_vars(x_map, x_sym)
91+
return f_mtk!, h_mtk!, p_sym, p, x_sym, x, i_alg
92+
end
93+
nothing # hide
94+
```
95+
96+
The `generate_model` method then constructs an adequate [`SimModel`](@ref) object that
97+
internally separates the differential states and algebraic variables, if any, to comply with
98+
this package's interface:
99+
100+
```@example 1
101+
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()
104+
) where {F<:Function, H<:Function}
105+
nu, ny = length(inputs), length(outputs)
106+
nx_mtk::Int = length(i_alg)
107+
na::Int = sum(i_alg)
108+
nx::Int = nx_mtk - na
109+
i_x::Vector{Int} = findall(iszero, i_alg)
110+
i_a::Vector{Int} = findall(isone, i_alg)
111+
if na > 0
112+
function fq!(ẋ, res, x, a, u, d, p)
113+
T = promote_type(eltype(x), eltype(a), eltype(u))
114+
ẋ_mtk, x_mtk = similar(ẋ, T, nx_mtk), similar(x, T, nx_mtk)
115+
x_mtk[i_x] .= x
116+
x_mtk[i_a] .= a
117+
f_mtk!(ẋ_mtk, x_mtk, u, d, p)
118+
ẋ .= @views ẋ_mtk[i_x]
119+
res .= @views ẋ_mtk[i_a]
120+
return nothing
121+
end
122+
function h!(y, x, a, d, p)
123+
T = promote_type(eltype(x), eltype(a))
124+
x_mtk = similar(x, T, nx_mtk)
125+
x_mtk[i_x] .= x
126+
x_mtk[i_a] .= a
127+
h_mtk!(y, x_mtk, d, p)
128+
return nothing
129+
end
130+
xs_0, as_0 = xs_mtk[i_x], xs_mtk[i_a]
131+
model = NonLinModelDAE(
132+
fq!, h!, Ts, nu, nx, na, ny; p, unit, xs_0, as_0, transcription
133+
)
134+
else
135+
f!, h! = f_mtk!, h_mtk!
136+
model = NonLinModel(f!, h!, Ts, nu, nx, ny; p, unit)
137+
end
138+
return model # deliberately type unstable function
95139
end
140+
nothing # hide
141+
```
142+
143+
## Pendulum Model
144+
145+
We first construct and instantiate the pendulum model as a MTK `System` object:
146+
147+
```@example 1
148+
@parameters g=9.8 L=0.4 K=1.2 m=0.3
149+
@variables θ(t)=0 ω(t)=0 τ(t)=0 y(t)
150+
eqs = [
151+
D(θ) ~ ω
152+
D(ω) ~ -g/L*sin(θ) - K/m*ω + τ/m/L^2
153+
y ~ θ * 180 / π
154+
]
155+
@named mtk_model = System(eqs, t)
156+
```
157+
158+
We can now convert the MTK model:
159+
160+
```@example 1
96161
inputs, outputs = [τ], [y]
97-
f!, h!, p, x_sym, p_sym, nu, nx, ny = generate_f_h(mtk_model, inputs, outputs)
98-
x_sym
162+
f_mtk!, h_mtk!, p_sym, p, x_sym, x, i_alg = generate_f_h_mtk(mtk_model, inputs, outputs)
163+
[x_sym x]
99164
```
100165

101-
Since MTK is an acausal modeling framework, we do not have the control on the state
166+
Since MTK is an acausal modeling framework, we do not have control over the state
102167
realization chosen by the package. The content of `x_sym` above shows it settled for the
103168
state vector ``\mathbf{x}(t) = [\begin{smallmatrix}ω(t) && θ(t)\end{smallmatrix}]'``,
104-
that is, the states of the [last section](@ref man_nonlin) in the reverse order. As the same
105-
also applies for the parameters, the `p_sym` object informs on how the `p` vector is sorted:
169+
that is, the states of the [pendulum section](@ref man_nonlin) in the reverse order. As the
170+
same also applies to the parameters, the `p_sym` object informs on how the `p` vector is
171+
sorted:
106172

107173
```@example 1
108174
[p_sym p]
109175
```
110176

111-
We can now construct a [`NonLinModel`](@ref) with this specific state realization:
177+
We can now construct a [`SimModel`](@ref) with this specific state realization:
112178

113179
```@example 1
114-
vu, vx, vy = ["\$τ\$ (Nm)"], ["\$ω\$ (rad/s)", "\$θ\$ (rad)"], ["\$θ\$ (°)"]
115180
Ts = 0.1
116-
model = setname!(NonLinModel(f!, h!, Ts, nu, nx, ny; p); u=vu, x=vx, y=vy)
181+
model = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs, p)
182+
vu, vx, vy = ["\$τ\$ (Nm)"], ["\$ω\$ (rad/s)", "\$θ\$ (rad)"], ["\$θ\$ (°)"]
183+
model = setname!(model; u=vu, x=vx, y=vy)
117184
```
118185

119-
We also instantiate a plant model with a 25 % larger friction coefficient ``K``:
186+
As expected, the returned model is a [`NonLinModel`](@ref) object, since the pendulum model
187+
has no algebraic equations. We also instantiate a plant model with a 25 % larger friction
188+
coefficient ``K``:
120189

121190
```@example 1
122191
i_K = findfirst(==("K"), string.(p_sym))
123192
p2 = copy(p)
124193
p2[i_K] = 1.25*p[i_K]
125-
plant = setname!(NonLinModel(f!, h!, Ts, nu, nx, ny; p=p2), u=vu, x=vx, y=vy)
194+
plant = generate_model(f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs, p2)
195+
plant = setname!(plant; u=vu, x=vx, y=vy)
126196
```
127197

128-
## Controller Design
198+
## Pendulum Controller Design
129199

130-
We can than reproduce the Kalman filter and the controller design of the [last section](@ref man_nonlin)
200+
We can then reproduce the Kalman filter and the controller design of the [penultimate section](@ref man_nonlin)
131201
by reversing the order of `σQ` vector, because of the different state realization:
132202

133203
```@example 1
@@ -144,7 +214,7 @@ The 180° setpoint response is identical:
144214
```@example 1
145215
using Plots
146216
N = 35
147-
using JuMP; unset_time_limit_sec(nmpc.optim) # hide
217+
import JuMP; JuMP.unset_time_limit_sec(nmpc.optim) # hide
148218
using Logging # hide
149219
res_ry = with_logger(ConsoleLogger(stderr, Error)) do # hide
150220
res_ry = sim!(nmpc, N, [180.0], plant=plant, x_0=[0, 0], x̂_0=[0, 0, 0])
@@ -169,6 +239,80 @@ display(p) # hide
169239

170240
![plot2_MTK](plot2_MTK.svg)
171241

242+
## Neutralization Reactor Model
243+
244+
!!! todo "Under Construction"
245+
This section is not finished, only the model conversion is written for now.
246+
247+
The MTK model of the neutralization reactor from the [last section](@ref man_dae) is
248+
constructed as follows:
249+
250+
```@example 1
251+
@parameters c_Ain=0.1 c_Bin=0.1 Kw=1e-14 Ka=1.75e-5 V=1000 q_Ain=10
252+
@variables c_A(t)=0.025 c_B(t)=0.025 q_Bin(t)=10 pH(t)=7.0
253+
@variables q_out(t) c_Aout(t) c_Bout(t)
254+
eqs = [
255+
D(c_A) ~ 60/V*(q_Ain * c_Ain - q_out * c_Aout)
256+
D(c_B) ~ 60/V*(q_Bin * c_Bin - q_out * c_Bout)
257+
0 ~ 10^(-pH) + c_B - (Kw / 10^(-pH)) - (Ka * c_A / (Ka + 10^(-pH)))
258+
q_out ~ q_Ain + q_Bin
259+
c_Aout ~ c_A
260+
c_Bout ~ c_B
261+
]
262+
@named mtk_model = System(eqs, t)
263+
```
264+
265+
The substitution ``a_H = 10^{-\mathrm{pH}}`` is explicitly applied in the algebraic equation
266+
to improve the numerical conditioning of the system. The converted model is:
267+
268+
```@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)
271+
[x_sym x]
272+
```
273+
274+
The content of `x_sym` shows that it chose for the combined state and algebraic vector
275+
``[\begin{smallmatrix}c_B(t) && c_A(t) && \mathrm{pH}(t)\end{smallmatrix}]'``. The states
276+
are thus in the reverse order of the [last section](@ref man_dae). The order of the
277+
parameters is:
278+
279+
```@example 1
280+
[p_sym p]
281+
```
282+
283+
We can now construct a [`SimModel`](@ref) with this realization:
284+
285+
```@example 1
286+
Ts, unit = 0.5, "h"
287+
xs_mtk = x
288+
transcription = TrapezoidalCollocation()
289+
model = generate_model(
290+
f_mtk!, h_mtk!, Ts, i_alg, inputs, outputs, p; xs_mtk, unit, transcription
291+
)
292+
vu = [raw"$q_{Bin}$ (L/min)"]
293+
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)
295+
```
296+
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):
300+
301+
```@example 1
302+
using Plots
303+
u, x_0 = [10.0], [0.0495, 0.0505]
304+
N = 21
305+
using Logging # hide
306+
res = with_logger(ConsoleLogger(stderr, Error)) do # hide
307+
res = sim!(model, N, u; x_0)
308+
end # hide
309+
p = plot(res)
310+
savefig(p, "plot3_MTK.svg") # hide
311+
display(p) # hide
312+
```
313+
314+
![plot3_MTK](plot3_MTK.svg)
315+
172316
## Acknowledgement
173317

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

‎docs/src/manual/nonlinmpc2.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ display(p) # hide
459459

460460
![plot4_DAEpH](plot4_DAEpH.svg)
461461

462-
Finally, we benchmark the total runtime for this scenario, including estimation, control,
462+
Finally, we benchmark the total runtime for this scenario, including estimation, control,
463463
and plant simulation:
464464

465465
```@example 1

0 commit comments

Comments
 (0)