Wednesday, July 29, 2020

function Latex for Sympy

I am interested in parsing functions written in Latex into a Sympy representation. For simple examples, this currently works:

>>> import sympy 
>>> sympy.__version__ 
'1.5.1' 
>>> from sympy.parsing.latex import parse_latex
>>> sympy.srepr(parse_latex('f(x)'))
"Function('f')(Symbol('x'))"

That's good. Sympy also supports expressions like

>>> sympy.srepr(parse_latex('x=0'))
"Equality(Symbol('x'), Integer(0))"

However, a function with a constraint written in Latex is not parsed correctly:

>>> sympy.srepr(parse_latex('f(x = 0)'))
"Symbol('f')"

The opposite direction does work (from Sympy to Latex)

>>> sympy.latex(sympy.Function('f')(sympy.Equality(sympy.Symbol('x'), sympy.Integer(0))))
'f{\\left(x = 0 \\right)}'

Similarly, we can get more complicated expressions from Sympy to Latex

>>> sympy.latex(sympy.Equality(sympy.Function('f')(sympy.Equality(sympy.Symbol('x'), sympy.Integer(0))),sympy.Symbol('a')))
'f{\\left(x = 0 \\right)} = a'

but the opposite (Latex to Sympy) is not working:

>>> sympy.srepr(parse_latex('f{\\left(x = 0 \\right)} = a'))
"Symbol('f')"

No comments:

Post a Comment