21

I want to parse LaTeX formulas and directly use them as SymPy expressions. In other words, what I need is something similar to sympify:

from sympy import sympify
f = sympify('x^2 + sin(y) + 1/2')
print f

but that can take LaTeX expressions (strings) as input, for example:

f = latex_sympify('\frac{x}{1+x}')

Given that sympify is able to convert a string with a regular mathematical expression into a SymPy object, if there is anything that can convert LaTeX into a regular mathematical expression, I guess that would do the trick---but I would prefer to do everything within Python.

Any suggestions will be much appreciated.

user2243748
  • 235
  • 1
  • 2
  • 7
  • I guess something like this doesn't exist... Anyway, LaTeX has tons of features for formulas, so which one should be included at the least? Do you need to handle arrays/matrices/binomials etc.? – Bakuriu Apr 04 '13 at 16:00
  • There is no SymPy function for this yet. See https://code.google.com/p/sympy/issues/detail?id=2319. You might be able to find a secondary parser that can convert LaTeX to something Python-like, which SymPy can then parse. – asmeurer Apr 04 '13 at 18:49
  • Also patches welcome :) – asmeurer Apr 04 '13 at 18:50
  • Thank you for your comments and for the pointer to the SymPy issue tracker (and sorry for not finding that myself). With regards to what should be included, I am of the same opinion as the comment asmeurer makes in the tracker--some functionality is better than none so maybe it'd be smart to start with simple expressions and go from there. – user2243748 Apr 05 '13 at 13:17
  • were you able to find out any solution of this ?? – gsagrawal Sep 17 '13 at 10:39
  • Mathematica does have some of this functionality but we are currently working to do something similar in Python. We'll add new information if/when we have something usable. – user2243748 Sep 17 '13 at 19:15

3 Answers3

10

Take a look at this Latex -> Sympy converter, it works great for a big subset of Latex:

https://github.com/augustt198/latex2sympy

nicodjimenez
  • 1,180
  • 17
  • 15
3

I would look at tools that convert latex to mathml, such as (via google search): http://www.mathtowebonline.com/

Then you can process the XML that comes out of this. However, you should be careful interpreting the result as a mathematical expression. Such tools may guarantee the textual representation is equal, but the bracketing (grouping) of operands with their operators may not be what you expect. In general you will see less nesting. Operators that are just next to each other that we interpret by convention as being nested will simply be converted to sibling elements in the XML format. If you try to interpret this as formulas there is still some work left to be done (recovering the nested structure in the right way).

Jurgen Vinju
  • 6,393
  • 1
  • 15
  • 26
2

You can use latex2sympy2

from latex2sympy2 import latex2sympy
f = r"\frac{x}{1+x}"
latex2sympy(f)
Andre9
  • 43
  • 5