JuliaPy / SymPy.jl

Julia interface to SymPy via PyCall
http://juliapy.github.io/SymPy.jl/
MIT License
268 stars 62 forks source link

How to save a function from lamdify? #484

Closed xiang-yu closed 1 year ago

xiang-yu commented 1 year ago

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/

jverzani commented 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).