Skip to content

Commit 8e42d4e

Browse files
add an example for parsing Julia expressions into ModelingToolkit solves
With known limitations documented in JuliaSymbolics/Symbolics.jl#808
1 parent b8dadbc commit 8e42d4e

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

docs/pages.jl

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ pages = [
99
"tutorials/parameter_identifiability.md"],
1010
"Examples" => Any["Basic Examples" => Any["examples/higher_order.md",
1111
"examples/spring_mass.md",
12-
"examples/modelingtoolkitize_index_reduction.md"],
12+
"examples/modelingtoolkitize_index_reduction.md",
13+
"examples/parsing.md"],
1314
"Advanced Examples" => Any["examples/tearing_parallelism.md",
1415
"examples/sparse_jacobians.md",
1516
"examples/perturbation.md"]],

docs/src/examples/parsing.md

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Parsing Expressions into Solvable Systems
2+
3+
Many times when creating DSLs or creating ModelingToolkit extensions to read new file formats,
4+
it can become imperative to parse expressions. In many cases, it can be easy to use `Base.parse`
5+
to take things to standard Julia expressions, but how can you take a `Base.Expr` and generate
6+
symbolic forms from that? For example, say we had the following system we wanted to solve:
7+
8+
```@example parsing
9+
ex = [:(y ~ x)
10+
:(y ~ -2x + 3 / z)
11+
:(z ~ 2)]
12+
```
13+
14+
We can use the function `parse_expr_to_symbolic` from Symbolics.jl to generate the symbolic
15+
form of the expression:
16+
17+
```@example parsing
18+
Symbolics
19+
eqs = parse_expr_to_symbolic.(ex, (Main,))
20+
```
21+
22+
From there, we can use ModelingToolkit to transform the symbolic equations into a numerical
23+
nonlinear solve:
24+
25+
```@example parsing
26+
using ModelingToolkit, NonlinearSolve
27+
vars = union(ModelingToolkit.vars.(eqs)...)
28+
@named ns = NonlinearSystem(eqs, vars, [])
29+
30+
prob = NonlinearProblem(ns,[1.0,1.0,1.0])
31+
sol = solve(prob,NewtonRaphson())
32+
```

0 commit comments

Comments
 (0)