Closed xiang-yu closed 1 year ago
Well it would need to be pieced together. Maybe this:
@syms a b c
ex = a^2 + b * c
convert(Expr, ex)
That should return the body of an expression. If more control is needed, SymPy.walk_expression
may be of use.
To convert to a function, you would want the free symbols. This helper might be of use for that:
using TermInterface
function free_symbols(ex)
out = Set{Symbol}()
istree(ex) || return (isa(ex,Symbol) ? Set((ex,)) : out)
for a ∈ arguments(ex)
for k ∈ free_symbols(a)
isa(k, Symbol) && push!(out, k)
end
end
out
end
With the body and the variables, you could make a function:
body = convert(Expr, ex)
args = collect(free_symbols(body))
λ = SymPy.eval(SymPy.expr_to_function(body, args))
If you have world age issues, you'd have to be more resourceful (e.g. see the docstring of lambdify
for GeneralizedGenerated
).
How to save a function generated from lamdify for later use? It can be either in json format or other format that can be read using Julia.
For example, symbolics.jl can build and save functions for numerical use,
https://symbolics.juliasymbolics.org/dev/manual/build_function/