Skip to content

Commit 8c274a7

Browse files
add get_variables
didnt commit uniqueness add in substitution logic add subs Update src/utils.jl Co-Authored-By: Christopher Rackauckas <accounts@chrisrackauckas.com> Update src/utils.jl Co-Authored-By: Christopher Rackauckas <accounts@chrisrackauckas.com> add generic method for is_singleton [ci skip] clean up get_variables [ci skip] clean up substitution Update src/utils.jl Co-Authored-By: Christopher Rackauckas <accounts@chrisrackauckas.com> fix up get variable and substitution fix up getting and substitution
1 parent 5220a41 commit 8c274a7

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/utils.jl

+26
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,29 @@ function vars!(vars, O)
144144

145145
return vars
146146
end
147+
148+
# variable extraction
149+
is_singleton(e) = false
150+
is_singleton(e::Operation) = e.op isa Variable
151+
152+
get_variables(e::Constant, vars = Operation[]) = vars
153+
function get_variables(e::Operation, vars = Operation[])
154+
if is_singleton(e)
155+
push!(vars, e)
156+
else
157+
foreach(x -> get_variables(x, vars), e.args)
158+
end
159+
return unique(vars)
160+
end
161+
162+
# variable substitution
163+
substitute_expr!(expr::Constant, s::Pair{Operation, Operation}) = nothing
164+
function substitute_expr!(expr::Operation, s::Pair{Operation, Operation})
165+
if !is_singleton(expr)
166+
expr.args .= replace(expr.args, s)
167+
for arg in expr.args
168+
substitute_expr!(arg, s)
169+
end
170+
end
171+
return nothing
172+
end

test/variable_utils.jl

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
using ModelingToolkit, Test
2+
@parameters α β δ
3+
expr = (((1 / β - 1) + δ) / α) ^ (1 /- 1))
4+
ref = [β, δ, α]
5+
sol = ModelingToolkit.get_variables(expr)
6+
@test all([sol[i].op.name == ref[i].op.name for i in 1:3])
7+
8+
@parameters γ
9+
s = α => γ
10+
new = (((1 / β - 1) + δ) / γ) ^ (1 /- 1))
11+
ModelingToolkit.substitute_expr!(expr, s)
12+
@test isequal(expr, new)

0 commit comments

Comments
 (0)