Evaluating Mathematica expressions in Python/Scipy

In my research I am currently using both Python/Scipy and Mathematica, the former for data evaluation and the latter for symbolic computations. I currently have to transfer symbolic expressions computed in Mathematica to Python and evaluate them for given parameters – something I didn’t find a satisfying solution right away.

In order not to translate simple expressions by hand each time I was looking for a MathML/Latex to Python parser. Apparently Sympy offers MathML parsing, but I found a workaround, allowing you to copy/paste lengthy Mathematica expressions into your py code and evaluate them efficiently, using scipy.weave and Mathematica’s CForm.

  1. In Mathematica use CForm[Expression] to get a C version of your expression (using custom Mathematica functions, e.g. Power).
  2. Either copy the header file mdefs.h from Mathematica/SystemFiles/IncludeFiles/C to /usr/local/include or change the reference in the snippet below – I like my headers in one place.
  3. Then use scipy.weave.inline(code,args) to compile and execute your C code, but be sure to include the mdefs.h header. I wrote a quick wrapper for this:
    [code lang=”python”]
    from scipy import weave
    def evalcform(code,argdict):
    return weave.inline(‘#include “mdefs.h”\n’+code,
  4. You can now pass code and a dictionary of variables and values to the wrapper, which will be passed on to the compiled expression and evaluated. E.g.:
    [code lang=”python”]
    code = “””
    return_val = Power(A,2) + Power(B,0.5)*Sin(C*Pi);
    vars = {‘A’:2.,’B’:2.,’C’:.5}
    print mathematica.evalcform(code,vars)
    which (probably) evaluates to

Note that the C code will only be compiled once, until the code (not the values of your variables) changes, which is quite fast for plotting for example. Also mind this is only a fast workaround, and will work only for expressions involving standard trigonometrical, exponential and power functions (have a look into the mdefs.h for an overview).

    ← Previous post

    Next post →


    1. Thanks – this saved me from some terrible regex/substitution/eval() nightmare!

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    %d bloggers like this: