3
3
ModelingToolkit has a system for transformations of mathematical
4
4
systems. These transformations allow for symbolically changing
5
5
the representation of the model to problems that are easier to
6
- numerically solve. One simple to demonstrate transformation is the
6
+ numerically solve. One simple to demonstrate transformation, is
7
7
` structural_simplify ` , which does a lot of tricks, one being the
8
8
transformation that turns an Nth order ODE into N
9
9
coupled 1st order ODEs.
@@ -15,16 +15,28 @@ We utilize the derivative operator twice here to define the second order:
15
15
using ModelingToolkit, OrdinaryDiffEq
16
16
using ModelingToolkit: t_nounits as t, D_nounits as D
17
17
18
- @parameters σ ρ β
19
- @variables x(t) y(t) z(t)
20
-
21
- eqs = [D(D(x)) ~ σ * (y - x),
22
- D(y) ~ x * (ρ - z) - y,
23
- D(z) ~ x * y - β * z]
24
-
25
- @named sys = ODESystem(eqs, t)
18
+ @mtkmodel SECOND_ORDER begin
19
+ @parameters begin
20
+ σ = 28.0
21
+ ρ = 10.0
22
+ β = 8 / 3
23
+ end
24
+ @variables begin
25
+ x(t) = 1.0
26
+ y(t) = 0.0
27
+ z(t) = 0.0
28
+ end
29
+ @equations begin
30
+ D(D(x)) ~ σ * (y - x)
31
+ D(y) ~ x * (ρ - z) - y
32
+ D(z) ~ x * y - β * z
33
+ end
34
+ end
35
+ @mtkbuild sys = SECOND_ORDER()
26
36
```
27
37
38
+ The second order ODE has been automatically transformed to two first order ODEs.
39
+
28
40
Note that we could've used an alternative syntax for 2nd order, i.e.
29
41
` D = Differential(t)^2 ` and then ` D(x) ` would be the second derivative,
30
42
and this syntax extends to ` N ` -th order. Also, we can use ` * ` or ` ∘ ` to compose
@@ -33,28 +45,17 @@ and this syntax extends to `N`-th order. Also, we can use `*` or `∘` to compos
33
45
Now let's transform this into the ` ODESystem ` of first order components.
34
46
We do this by calling ` structural_simplify ` :
35
47
36
- ``` @example orderlowering
37
- sys = structural_simplify(sys)
38
- ```
39
-
40
48
Now we can directly numerically solve the lowered system. Note that,
41
49
following the original problem, the solution requires knowing the
42
- initial condition for ` x' ` , and thus we include that in our input
43
- specification:
50
+ initial condition for both ` x ` and ` D(x) ` .
51
+ The former already got assigned a default value in the ` @mtkmodel ` ,
52
+ but we still have to provide a value for the latter.
44
53
45
54
``` @example orderlowering
46
- u0 = [D(x) => 2.0,
47
- x => 1.0,
48
- y => 0.0,
49
- z => 0.0]
50
-
51
- p = [σ => 28.0,
52
- ρ => 10.0,
53
- β => 8 / 3]
54
-
55
+ u0 = [D(sys.x) => 2.0]
55
56
tspan = (0.0, 100.0)
56
- prob = ODEProblem(sys, u0, tspan, p , jac = true)
57
+ prob = ODEProblem(sys, u0, tspan, [] , jac = true)
57
58
sol = solve(prob, Tsit5())
58
- using Plots;
59
- plot(sol, idxs = (x, y));
59
+ using Plots
60
+ plot(sol, idxs = (sys. x, sys. y))
60
61
```
0 commit comments