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

Added the ability to pass known SymPy symbols to symbolics_to_sympy function #351

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 9 additions & 4 deletions src/init.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,26 @@ function __init__()
using Symbolics: value
using SymbolicUtils: istree, operation, arguments, symtype,
FnType, Symbolic
function symbolics_to_sympy(expr)
function symbolics_to_sympy(expr, symbols::Dict=Dict())
expr = value(expr)
expr isa Symbolic || return expr
if istree(expr)
sop = symbolics_to_sympy(operation(expr))
sargs = map(symbolics_to_sympy, arguments(expr))
sop = symbolics_to_sympy(operation(expr), symbols)
sargs = map(a->symbolics_to_sympy(a, symbols), arguments(expr))
if sop === (^) && length(sargs) == 2 && sargs[2] isa Number
return Base.literal_pow(^, sargs[1], Val(sargs[2]))
else
return sop(sargs...)
end
else # isa Symbolics.Sym
name = string(nameof(expr))
return symtype(expr) <: FnType ? SymPy.SymFunction(name) : SymPy.Sym(name)
return symtype(expr) <: FnType ? SymPy.SymFunction(name) : get(symbols, name, SymPy.Sym(name))
end
end

function symbolics_to_sympy(expr, symbols)
d = Dict(string(symbol) => symbol for symbol in symbols)
return symbolics_to_sympy(expr,d)
end

end # SymPy
Expand Down
9 changes: 9 additions & 0 deletions test/sympy.jl
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,12 @@ sexpr = symbolics_to_sympy(expr)
sp = symbolics_to_sympy(p)

@test SymPy.simplify(symbolics_to_sympy(Symbolics.solve_for(expr, p))) == SymPy.solve(sexpr, sp)[1]

@variables k
sk = symbols("k", positive = True)
@test symbolics_to_sympy(k) !== sk
@test symbolics_to_sympy(k, Dict()) != sk
@test symbolics_to_sympy(k, Dict("k"=>sk)) == sk
@test symbolics_to_sympy(k, Dict("x"=>sk)) != sk
@test symbolics_to_sympy(k, [sk]) == sk
@test symbolics_to_sympy(k, (sk,)) == sk