@@ -113,22 +113,24 @@ based on internal cost models are a work-in-progress as well. This means DSLs bu
113113this as a model compiler can write domain-specific languages without having to write complex
114114optimized Julia function compilers.
115115
116- ### Example: Nonlinear System
116+ ### Example: Nonlinear System with NLsolve.jl
117117
118118We can also build nonlinear systems. Let's say we wanted to solve for the steady
119119state of the previous ODE. This is the nonlinear system defined by where the
120120derivatives are zero. We use (unknown) variables for our nonlinear system.
121121
122122``` julia
123+ using ModelingToolkit
124+
123125@variables x y z
124126@parameters σ ρ β
125127
126128# Define a nonlinear system
127129eqs = [0 ~ σ* (y- x),
128130 0 ~ x* (ρ- z)- y,
129131 0 ~ x* y - β* z]
130- ns = NonlinearSystem (eqs, [x,y,z])
131- nlsys_func = generate_function (ns, [x,y,z], [σ,ρ,β] )[2 ] # second is the inplace version
132+ ns = NonlinearSystem (eqs, [x,y,z], [σ,ρ,β] )
133+ nlsys_func = generate_function (ns)[2 ] # second is the inplace version
132134```
133135
134136which generates:
158160
159161#=
1601623-element Array{Float64,1}:
161- 0.0
163+ 0.0
162164 24.0
163165 -1.33
164166 =#
165167```
166168
169+ We can similarly ask to generate the in-place Jacobian function:
170+
171+ ``` julia
172+ j_func = generate_jacobian (ns)[2 ] # second is in-place
173+ j! = eval (j_func)
174+ ```
175+
176+ which gives:
177+
178+ ``` julia
179+ :((var"##MTIIPVar#582" , u, p)-> begin
180+ #= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:70 =#
181+ #= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:71 =#
182+ #= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:71 =# @inbounds begin
183+ #= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:72 =#
184+ #= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:53 =# @inbounds begin
185+ #= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:53 =#
186+ let (x, y, z, σ, ρ, β) = (u[1 ], u[2 ], u[3 ], p[1 ], p[2 ], p[3 ])
187+ var"##MTIIPVar#582" [1 ] = (* )(σ, - 1 )
188+ var"##MTIIPVar#582" [2 ] = (- )(ρ, z)
189+ var"##MTIIPVar#582" [3 ] = y
190+ var"##MTIIPVar#582" [4 ] = σ
191+ var"##MTIIPVar#582" [5 ] = - 1
192+ var"##MTIIPVar#582" [6 ] = x
193+ var"##MTIIPVar#582" [7 ] = 0
194+ var"##MTIIPVar#582" [8 ] = (* )(x, - 1 )
195+ var"##MTIIPVar#582" [9 ] = (* )(- 1 , β)
196+ end
197+ end
198+ end
199+ #= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:74 =#
200+ nothing
201+ end )
202+ ```
203+
204+ Now we can call ` nlsolve ` by enclosing our parameters into the functions:
205+
206+ ``` julia
207+ nlsolve ((out, x) -> f (out, x, params), (out, x) -> j! (out, x, params), ones (3 ))
208+ ```
209+
167210If one would like the generated function to be a Julia function instead of an expression, and allow this
168211function to be used from within the same world-age, one simply needs to pass ` Val{false} ` to tell it to
169212generate the function, i.e.:
0 commit comments