Skip to content

Commit 42e2727

Browse files
simplified_expr
1 parent bdcf035 commit 42e2727

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/ModelingToolkit.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ module ModelingToolkit
33
export Operation, Expression
44
export calculate_jacobian, generate_jacobian, generate_function
55
export independent_variables, dependent_variables, parameters
6+
export simplified_expr
67
export @register
78
export modelingtoolkitize
89

src/simplify.jl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,19 @@ function _simplify_constants(O::Operation, shorten_tree)
7575
end
7676
_simplify_constants(x, shorten_tree) = x
7777
_simplify_constants(x) = _simplify_constants(x, true)
78+
79+
function simplified_expr(O::Operation)
80+
if O isa Constant
81+
return O.value
82+
elseif isa(O.op, Differential)
83+
return :(derivative($(simplified_expr(O.args[1])),$(simplified_expr(O.op.x))))
84+
elseif isa(O.op, Variable)
85+
isempty(O.args) && return O.op.name
86+
return Expr(:call, Symbol(O.op), simplified_expr.(O.args)...)
87+
end
88+
return Expr(:call, Symbol(O.op), simplified_expr.(O.args)...)
89+
end
90+
91+
function simplified_expr(eq::Equation)
92+
Expr(:(=), simplified_expr(eq.lhs), simplified_expr(eq.rhs))
93+
end

test/system_construction.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,20 @@ end
3030
eqs = [D(x) ~ σ*(y-x),
3131
D(y) ~ x*-z)-y,
3232
D(z) ~ x*y - β*z]
33+
34+
simpexpr = [
35+
:(derivative(x(t), t) = σ * (y(t) - x(t)))
36+
:(derivative(y(t), t) = x(t) *- z(t)) - y(t))
37+
:(derivative(z(t), t) = x(t) * y(t) - β * z(t))
38+
]
39+
40+
for i in 1:3
41+
@test ModelingToolkit.simplified_expr.(eqs)[i].args[1] == simpexpr[i].args[1]
42+
@test ModelingToolkit.simplified_expr.(eqs)[i].args[2] == simpexpr[i].args[2].args[2]
43+
end
44+
45+
ModelingToolkit.simplified_expr.(eqs)[1]
46+
:(derivative(x(t), t) = σ * (y(t) - x(t))).args
3347
de = ODESystem(eqs)
3448
test_diffeq_inference("standard", de, t, (x, y, z), (σ, ρ, β))
3549
generate_function(de, [x,y,z], [σ,ρ,β])

0 commit comments

Comments
 (0)