JuliaPy / PythonCall.jl

Python and Julia in harmony.
https://juliapy.github.io/PythonCall.jl/stable/
MIT License
722 stars 61 forks source link

Adding a custom rule to convert sympy Symbol to Symbolics Num #349

Closed jClugstor closed 10 months ago

jClugstor commented 10 months ago

I’m trying to convert a Sympy symbol into a Symbolics.jl Num type. When I use pyconvert_add_rule to add the rule, and then try to convert it using pyconvert, it says that it can’t convert the sympy symbol to a Symbolics Num. The function that I wrote to handle the conversion does what it’s supposed to, it’s just that it seems that adding the rule did not work. I'm not sure if it's a bug or if I'm just doing something wrong. I thought I followed the docs, and I looked at examples of conversion functions and using the add rules function in the source as well, and it seems like I'm doing the same thing.


using Symbolics
using CondaPkg

CondaPkg.add("sympy")

sp = pyimport("sympy")

sympt = sp.Symbol("t")

typeof(Symbolics.variable(Symbol(pyconvert(Symbol,sympt.name))))

function pysym_to_Num(::Type{Symbolics.Num}, x::Py)
    if !pyisinstance(x,sp.Symbol)
        return PythonCall.pyconvert_unconverted()
    end
    name = PythonCall.pyconvert(Symbol,x.name)
    return PythonCall.pyconvert_return(Symbolics.variable(name))
end

#convertedt = pysym_to_Num(Symbolics.Num, sympt)

PythonCall.pyconvert_add_rule("sympy:Symbol",Symbolics.Num, pysym_to_Num)

PythonCall.pyconvert(Symbolics.Num, sympt)```

Result:
```ERROR: cannot convert this Python 'Symbol' to a Julia 'Num'
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:35
 [2] macro expansion
   @ ~/.julia/packages/PythonCall/qTEA1/src/convert.jl:355 [inlined]
 [3] macro expansion
   @ ~/.julia/packages/PythonCall/qTEA1/src/Py.jl:131 [inlined]
 [4] pyconvert(#unused#::Type{Num}, x::Py)
   @ PythonCall ~/.julia/packages/PythonCall/qTEA1/src/convert.jl:370
 [5] top-level scope
   @ ~/Documents/Work/dev/PythonModelingToolkit/SympytoSymbolics.jl:25```
jClugstor commented 10 months ago

The issue was not using the full name of the sympy symbol. It needs to be pyconvert_add_rule("sympy.core.symbol:Symbol",Symbolics.Num,pysym_to_Num)