Skip to content

Commit

Permalink
Fix README example for #184
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisRackauckas committed Dec 12, 2019
1 parent c24b00c commit c89c417
Showing 1 changed file with 47 additions and 4 deletions.
51 changes: 47 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,22 +113,24 @@ based on internal cost models are a work-in-progress as well. This means DSLs bu
this as a model compiler can write domain-specific languages without having to write complex
optimized Julia function compilers.

### Example: Nonlinear System
### Example: Nonlinear System with NLsolve.jl

We can also build nonlinear systems. Let's say we wanted to solve for the steady
state of the previous ODE. This is the nonlinear system defined by where the
derivatives are zero. We use (unknown) variables for our nonlinear system.

```julia
using ModelingToolkit

@variables x y z
@parameters σ ρ β

# Define a nonlinear system
eqs = [0 ~ σ*(y-x),
0 ~ x*-z)-y,
0 ~ x*y - β*z]
ns = NonlinearSystem(eqs, [x,y,z])
nlsys_func = generate_function(ns, [x,y,z], [σ,ρ,β])[2] # second is the inplace version
ns = NonlinearSystem(eqs, [x,y,z], [σ,ρ,β])
nlsys_func = generate_function(ns)[2] # second is the inplace version
```

which generates:
Expand Down Expand Up @@ -158,12 +160,53 @@ du

#=
3-element Array{Float64,1}:
0.0
0.0
24.0
-1.33
=#
```

We can similarly ask to generate the in-place Jacobian function:

```julia
j_func = generate_jacobian(ns)[2] # second is in-place
j! = eval(j_func)
```

which gives:

```julia
:((var"##MTIIPVar#582", u, p)->begin
#= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:70 =#
#= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:71 =#
#= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:71 =# @inbounds begin
#= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:72 =#
#= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:53 =# @inbounds begin
#= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:53 =#
let (x, y, z, σ, ρ, β) = (u[1], u[2], u[3], p[1], p[2], p[3])
var"##MTIIPVar#582"[1] = (*)(σ, -1)
var"##MTIIPVar#582"[2] = (-)(ρ, z)
var"##MTIIPVar#582"[3] = y
var"##MTIIPVar#582"[4] = σ
var"##MTIIPVar#582"[5] = -1
var"##MTIIPVar#582"[6] = x
var"##MTIIPVar#582"[7] = 0
var"##MTIIPVar#582"[8] = (*)(x, -1)
var"##MTIIPVar#582"[9] = (*)(-1, β)
end
end
end
#= C:\Users\accou\.julia\dev\ModelingToolkit\src\utils.jl:74 =#
nothing
end)
```

Now we can call `nlsolve` by enclosing our parameters into the functions:

```julia
nlsolve((out, x) -> f(out, x, params), (out, x) -> j!(out, x, params), ones(3))
```

If one would like the generated function to be a Julia function instead of an expression, and allow this
function to be used from within the same world-age, one simply needs to pass `Val{false}` to tell it to
generate the function, i.e.:
Expand Down

0 comments on commit c89c417

Please sign in to comment.