Converting Mathematica to Python

I like Mathematica for working with symbolic expressions. I find that there are no free software alternatives that achieve its power in the tasks of solving complex integrals, working with limits, and helping me make sense of sophisticated differential equations. Until that is solved, I will find the need to export Mathematica expressions to other software that is more efficient on the numerical computing side. Or which simply does good plots in a less verbose way.

I have created a simple Mathematica notebook which you can download here (see attachment below). The notebook uses Mathematica's pattern matching to build a sophisticated parsing routine that converts Mathematica expressions to Python code.

See for instance the following examples which detect addition, division and exponentiation, and convert those to strings, either directly, or using wrappers that automate the case of binary operators and unitary expressions:

ToPython2[a_ - b_] := ToPythonOp["-", a, b]
ToPython2[a_/b_] := ToPythonOp["/", a, b]
ToPython2[a_^2] := "(" <> PythonWrap[a] <> "**2)"
ToPython2[a_^b_] := PythonWrap[ToPythonOp["**", a, b]]

The actual implementation makes use of ugly hacks, such as defining its own square root function (which accepts negative real arguments), or parenthesising more than needed, but it is fully functional and works nicely for my own purposes. For instance, the following complex Mathematica expression

Mathematica expression.jpg

is converted to 13 lines of Python code:


def mysqrt(x): return np.sqrt((1.+0j)*x)


Download the file.