# Best Practices for converting a Mathematica expression to Julia

**URL:** https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335
**Category:** General Usage
**Tags:** sympy, mathematica
**Created:** [December 5, 2018, 5:00pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335 "2018-12-05T17:00:00Z")
**Posts on this page:** 14
**Page:** 2

<div class="post-metadata">

### Author: ![roi.holtzman](https://avatars.discourse-cdn.com/v4/letter/r/f05b48/32.png) [@roi.holtzman](https://discourse.julialang.org/u/roi.holtzman)
#### Post date: [August 14, 2023, 2:52pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/21 "2023-08-14T14:52:47Z")

</div>

Thanks. Never heard of this Github Copilot.  
Do you have an example of how you use it? It seems like a powerful thing.

Though it would be nice to find a julia solution…

---

<div class="post-metadata">

### Author: ![j\_verzani](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/j_verzani/32/8551_2.png) [@j\_verzani](https://discourse.julialang.org/u/j_verzani)
#### Post date: [August 14, 2023, 5:31pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/22 "2023-08-14T17:31:52Z")

</div>

Here is something you can copy and paste to see if it works for you:

```julia
using SymPy
const sympy_parsing_mathematica = SymPy.PyCall.pyimport("sympy.parsing.mathematica")

s = "(Sqrt[Pi])/(2*EllipticE[m])"
ex = sympy_parsing_mathematica.mathematica(s, Dict("EllipticE[x]"=>"elliptic_e(x)"))

SymPy.walk_expression(ex) #:((1 / 2) * pi ^ (1 / 2) * elliptic_e(m) ^ -1)

# or

SymPy.convert_expr(ex, use_julia_code=true) # :(sqrt(pi) ./ (2 * elliptic_e(m)))

```

---

<div class="post-metadata">

### Author: ![roi.holtzman](https://avatars.discourse-cdn.com/v4/letter/r/f05b48/32.png) [@roi.holtzman](https://discourse.julialang.org/u/roi.holtzman)
#### Post date: [August 14, 2023, 5:58pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/23 "2023-08-14T17:58:35Z")

</div>

That is phenomenal!

Some things still do not work as expected, though.

The `walk_expression` gives me something different, and I do not know why:

```julia
s = "(Sqrt[Pi])/(2*EllipticE[m])"
ex = sympy_parsing_mathematica.mathematica(s, Dict("EllipticE[x]"=>"elliptic_e(x)"))

SymPy.walk_expression(ex) # what I should get :((1 / 2) * pi ^ (1 / 2) * elliptic_e(m) ^ -1)
# what I get is
# :((1 / 2) * SymPy. __POW__ (pi, 1 / 2) * SymPy. __POW__ (elliptic_e(m), -1))

```

I can fix it using

```julia
SymPy.walk_expression(ex, fns=Dict("Pow"=>:^))
# :((1 / 2) * pi ^ (1 / 2) * elliptic_e(m) ^ -1)

```

The `convert_expr` does not work well.  
First, I do not like that it returns all operations with the vectorized dot notion like so

```julia
:(sqrt(pi) ./ (2 * elliptic_e(m)))

```

The more problematic issue is that it does not deal with this expression for some reason

```julia
s = "Sqrt[2]/q2 EllipticF[x, 1 - q1^2/q2^2]"
ex = sympy_parsing_mathematica.mathematica(s, Dict("EllipticF[x, y]"=>"elliptic_e(x, y)"))

SymPy.convert_expr(ex, use_julia_code=true)

```

gives

```julia
Base.Meta.ParseError("use \"x^y\" instead of \"x **y\" for exponentiation, and \"x...\" instead of \"** x\" for splatting.")

Stacktrace:
 [1] #parse#3
   @ ./meta.jl:236 [inlined]
 [2] parse
   @ ./meta.jl:232 [inlined]
 [3] parse(str::String; raise::Bool, depwarn::Bool)
   @ Base.Meta ./meta.jl:267
 [4] parse(str::String)
   @ Base.Meta ./meta.jl:266
 [5] convert_expr(ex::Sym; fns::Dict{Any, Any}, values::Dict{Any, Any}, use_julia_code::Bool)
   @ SymPy ~/.julia/packages/SymPy/mpN0u/src/lambdify.jl:260
 [6] top-level scope
   @ In[37]:5

```

---

<div class="post-metadata">

### Author: ![j\_verzani](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/j_verzani/32/8551_2.png) [@j\_verzani](https://discourse.julialang.org/u/j_verzani)
#### Post date: [August 14, 2023, 7:18pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/24 "2023-08-14T19:18:12Z")

</div>

Sorry, `convert_expr` has some issues like this, hence the need for `walk_expression`. However, I realize I had some unpushed changes that are causing the differences you see with my example with `walk_expression`. I just made a PR, which I hope to tag once all the tests pass.

---

<div class="post-metadata">

### Author: ![roi.holtzman](https://avatars.discourse-cdn.com/v4/letter/r/f05b48/32.png) [@roi.holtzman](https://discourse.julialang.org/u/roi.holtzman)
#### Post date: [August 14, 2023, 7:43pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/25 "2023-08-14T19:43:24Z")

</div>

Thanks again!

I see that the `walk_expression` does not know how to handle `sqrt` and it gives a power of `1/2` instead as can be seen here

> [@roi.holtzman](#):
>
> ```julia
> SymPy.walk_expression(ex, fns=Dict("Pow"=>:^))
> # :((1 / 2) * pi ^ (1 / 2) * elliptic_e(m) ^ -1)
> 
> ```

Is there a way to get the `sqrt` from the `walk_expression`?  
(The `convert_expr` gives `sqrt`, but as you said it has some issues).

Let me also mention for completeness that in the first time I run these functions I get the following warning:

```julia
sys:1: SymPyDeprecationWarning: 

The ``mathematica`` function for the Mathematica parser is now
deprecated. Use ``parse_mathematica`` instead.
The parameter ``additional_translation`` can be replaced by SymPy's
.replace( ) or .subs( ) methods on the output expression instead.

See https://docs.sympy.org/latest/explanation/active-deprecations.html#mathematica-parser-new
for details.

This has been deprecated since SymPy version 1.11. It
will be removed in a future version of SymPy.

```

---

<div class="post-metadata">

### Author: ![j\_verzani](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/j_verzani/32/8551_2.png) [@j\_verzani](https://discourse.julialang.org/u/j_verzani)
#### Post date: [August 14, 2023, 9:21pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/26 "2023-08-14T21:21:33Z")

</div>

Thanks. Looks like a need to update my sympy library!

Anyways, I just registered a fix to `lambdify` that should also give back `sqrt`, as you wanted.

---

<div class="post-metadata">

### Author: ![roi.holtzman](https://avatars.discourse-cdn.com/v4/letter/r/f05b48/32.png) [@roi.holtzman](https://discourse.julialang.org/u/roi.holtzman)
#### Post date: [August 15, 2023, 8:58pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/27 "2023-08-15T20:58:50Z")

</div>

Great. I saw that the `sqrt` was fixed!

Just mentioning that the issue with `convert_expr` is still there:

> [@roi.holtzman](#):
>
> `Base.Meta.ParseError("use \"x^y\" instead of \"x **y\" for exponentiation, and \"x...\" instead of \"** x\" for splatting.")`

And also, this issue is still thereL

> [@roi.holtzman](#):
>
> ```julia
> sys:1: SymPyDeprecationWarning: 
> 
> The ``mathematica`` function for the Mathematica parser is now
> deprecated. Use ``parse_mathematica`` instead.
> The parameter ``additional_translation`` can be replaced by SymPy's
> .replace( ) or .subs( ) methods on the output expression instead.
> 
> See https://docs.sympy.org/latest/explanation/active-deprecations.html#mathematica-parser-new
> for details.
> 
> This has been deprecated since SymPy version 1.11. It
> will be removed in a future version of SymPy.
> 
> ```

---

<div class="post-metadata">

### Author: ![nathan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nathan/32/209855_2.png) [@nathan](https://discourse.julialang.org/u/nathan)
#### Post date: [September 14, 2023, 7:27pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/28 "2023-09-14T19:27:56Z")

</div>

I extended @gangchern’s example to a package ([GitHub - musoke/WolframExpr.jl](https://github.com/musoke/WolframExpr.jl/)). It’s bare bones, but does the basics of converting algebraic expressions from Mathematica to Julia. You can define mappings for special functions.

Example:

```julia
julia> using WolframExpr

julia> f = string_to_function("A[x,y]+y", [:A, :x, :y]);

julia> A(x, y) = x^2 + y^2;

julia> f(A, 1, 2)
7

```

---

<div class="post-metadata">

### Author: ![roi.holtzman](https://avatars.discourse-cdn.com/v4/letter/r/f05b48/32.png) [@roi.holtzman](https://discourse.julialang.org/u/roi.holtzman)
#### Post date: [February 6, 2024, 3:17pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/29 "2024-02-06T15:17:32Z")

</div>

Running now on Julia 1.9.3, with `SymPy v2.0.1`, it does not have `convert_expr` and `walk_expression`.  
Does anyone know what is the alternative to these functions?

---

<div class="post-metadata">

### Author: ![j\_verzani](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/j_verzani/32/8551_2.png) [@j\_verzani](https://discourse.julialang.org/u/j_verzani)
#### Post date: [February 7, 2024, 8:09pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/30 "2024-02-07T20:09:40Z")

</div>

They are buried behind another module now. For `ex` coming from `sympy_parsing_mathematica.mathematica` try:

```julia
SymPy.SymPyCore.walk_expression(Sym(ex))

```

---

<div class="post-metadata">

### Author: ![roi.holtzman](https://avatars.discourse-cdn.com/v4/letter/r/f05b48/32.png) [@roi.holtzman](https://discourse.julialang.org/u/roi.holtzman)
#### Post date: [February 8, 2024, 12:11pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/31 "2024-02-08T12:11:32Z")

</div>

Wonderful! that indeed works! thanks so much!

---

<div class="post-metadata">

### Author: ![roi.holtzman](https://avatars.discourse-cdn.com/v4/letter/r/f05b48/32.png) [@roi.holtzman](https://discourse.julialang.org/u/roi.holtzman)
#### Post date: [February 11, 2024, 9:42am UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/32 "2024-02-11T09:42:01Z")

</div>

I have an issue with the `//` operation. The expression I get from sympy does not have parenthesis around the numbers, which causes then an error when I copy the expression into a function.

Here is an example:

```julia
using SymPy
const sympy_parsing_mathematica = SymPy.PyCall.pyimport("sympy.parsing.mathematica")

s = raw"1/Sqrt[(x+y)^3]"
ex = sympy_parsing_mathematica.mathematica(s)
SymPy.SymPyCore.walk_expression(Sym(ex))
# :(((x + y) ^ 3) ^ -1//2)

# my goal is to take the above output and make a function out of it.
# I want to do it often, so I want to automate it as much as possible.
# defining
ftest(x, y) = (((x + y) ^ 3) ^ -1//2)
# then results in an error
ftest(1, 1)

```

Here is the error:

```julia
MethodError: no method matching //(::Float64, ::Int64)

Closest candidates are:
  //(::Integer, ::Integer)
   @ Base rational.jl:62
  //(::Rational, ::Integer)
   @ Base rational.jl:64
  //(::Complex, ::Real)
   @ Base rational.jl:78
  ...

Stacktrace:
 [1] ftest(x::Int64, y::Int64)
   @ Main ./In[58]:1
 [2] top-level scope
   @ In[59]:1

```

Putting parenthesis around the `//` operation will solve it, but I want to do it automatically in the parsing. Is there a way to do that?

---

<div class="post-metadata">

### Author: ![roi.holtzman](https://avatars.discourse-cdn.com/v4/letter/r/f05b48/32.png) [@roi.holtzman](https://discourse.julialang.org/u/roi.holtzman)
#### Post date: [February 11, 2024, 10:22am UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/33 "2024-02-11T10:22:30Z")

</div>

I have found some resolution using `@generated` macro:

```julia
s = raw"1/Sqrt[(x+y)^3]"
ex = sympy_parsing_mathematica.mathematica(s)
f_expr = SymPy.SymPyCore.walk_expression(Sym(ex))
# :(((x + y) ^ 3) ^ -1//2)
@generated ftest(x,y) = f_expr
ftest(1,0)
# 1.

```

UPDATE:  
Let me mention that SymPyCore is not needed anymore, and one should use `f_expr = SymPy.walk_expression(Sym(ex))` in the above code.

---

<div class="post-metadata">

### Author: ![moble](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/moble/32/23535_2.png) [@moble](https://discourse.julialang.org/u/moble)
#### Post date: [April 11, 2024, 8:24pm UTC](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335/34 "2024-04-11T20:24:36Z")

</div>

Looks like there’s still a long way to go, but MathLink.jl now has [`W2JuliaExpr`](https://github.com/JuliaInterop/MathLink.jl/issues/85#issuecomment-1987241374). Its approach looks roughly similar to WolframExpr.jl, which certainly has lighter dependencies, but maybe closer integration with Wolfram could enable more flexible transformations.

[Previous page](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335.md?page=1)
