Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to save a function from lamdify? #484

Closed
xiang-yu opened this issue Nov 11, 2022 · 1 comment
Closed

How to save a function from lamdify? #484

xiang-yu opened this issue Nov 11, 2022 · 1 comment

Comments

@xiang-yu
Copy link

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
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants