Skip to content

Instantly share code, notes, and snippets.

@mforets
Last active January 20, 2020 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mforets/8be4d0b1fc91800bcbd78f73dd87b379 to your computer and use it in GitHub Desktop.
Save mforets/8be4d0b1fc91800bcbd78f73dd87b379 to your computer and use it in GitHub Desktop.
ModelingToolkit.jl Examples

Expression substitution

# suggested on Slack (20/01/2020)

using ModelingToolkit
using MacroTools: postwalk

function replace(ex::ModelingToolkit.Expression, ps::Pair...)
    d = Dict(ps...)
    expr = postwalk(Expr(ex)) do x
        get(d, x, x)
    end
    eval(expr)
end

julia> @variables C, x
(C, x)
julia> replace(4 * (C + 1)/x, :C => 1)
8 / x

# Note: it would be preferable to to define a postwalk on Expression 
# instead of Expr and then do the replacements directly on the Expression. 
# This is not straightforward though, since ModelingToolkit.Variables are treated like function calls.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment