Git Product home page Git Product logo

latex2sympy's Introduction

latex2sympy

latex2sympy parses LaTeX math expressions and converts it into the equivalent SymPy form.

Installation

ANTLR is used to generate the parser:

$ antlr4 PS.g4 -o gen

Usage

In Python 2.7:

from process_latex import process_sympy

process_sympy("\\frac{d}{dx} x^{2}")
# => "diff(x**(2), x)"

Examples

LaTeX Image Generated SymPy
x^{3} x**3
`\frac{d}{dx} t x`
\sum_{i = 1}^{n} i Sum(i, (i, 1, n))
\int_{a}^{b} \frac{dt}{t} Integral(1/t, (t, a, b))
`(2x^3 - x + z) _{x=3}`

Contributing

Contributors are welcome! Feel free to open a pull request or an issue.

latex2sympy's People

Contributors

augustt198 avatar hiamandeep avatar nicodjimenez avatar sindytn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

latex2sympy's Issues

Installation

I can't install the package on Mac OS (error : antlr4: command not found)
I've installed antlr4 but not working (error :

Exception in thread "main" java.lang.NoClassDefFoundError: org/antlr/v4/Tool
Caused by: java.lang.ClassNotFoundException: org.antlr.v4.Tool
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

)
Thank you for your help

Multi Character variable

How can we use a multi character variable
in latex suntax we use \mathit, and its not yet supported

Is this the only way??
process_sympy("{\frac {\OperationHours}{\TotalPossibleOperationHours}} \times \Mech 100")

Issues parsing 2d arrays

This latex gives the following stack trace.
A = \left( \begin{array} { l l l } { 2} & { 7} & { 3} \\ { 3} & { 5} & { 2} \\ { 9} & { 4} & { 1} \end{array} \right)

Traceback (most recent call last):
  File "test - Copy.py", line 17, in <module>
    out = process_sympy(json.loads(r.text)['latex'])
  File "E:\Dropbox\Projects\mathpix\latex2sympy\process_latex.py", line 29, in process_sympy
    relation = parser.math().relation()
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 391, in math
    self.relation(0)
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 480, in relation
    self.relation(3)
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 456, in relation
    self.expr()
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 574, in expr
    self.additive(0)
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 630, in additive
    self.mp(0)
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 726, in mp
    self.unary()
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 925, in unary
    self.postfix()
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 1072, in postfix
    self.exp(0)
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 1474, in exp
    self.comp()
  File "E:\Dropbox\Projects\mathpix\latex2sympy\gen\PSParser.py", line 1691, in comp
    la_ = self._interp.adaptivePredict(self._input,20,self._ctx)
  File "C:\Python27\lib\site-packages\antlr4\atn\ParserATNSimulator.py", line 337, in adaptivePredict
    alt = self.execATN(dfa, s0, input, index, outerContext)
  File "C:\Python27\lib\site-packages\antlr4\atn\ParserATNSimulator.py", line 460, in execATN
    input.consume()
  File "C:\Python27\lib\site-packages\antlr4\BufferedTokenStream.py", line 97, in consume
    if self.sync(self.index + 1):
  File "C:\Python27\lib\site-packages\antlr4\BufferedTokenStream.py", line 109, in sync
    fetched = self.fetch(n)
  File "C:\Python27\lib\site-packages\antlr4\BufferedTokenStream.py", line 121, in fetch
    t = self.tokenSource.nextToken()
  File "C:\Python27\lib\site-packages\antlr4\Lexer.py", line 125, in nextToken
    self.notifyListeners(e)             # report error
  File "C:\Python27\lib\site-packages\antlr4\Lexer.py", line 280, in notifyListeners
    listener.syntaxError(self, None, self._tokenStartLine, self._tokenStartColumn, msg, e)
  File "C:\Python27\lib\site-packages\antlr4\error\ErrorListener.py", line 60, in syntaxError
    delegate.syntaxError(recognizer, offendingSymbol, line, column, msg, e)
  File "E:\Dropbox\Projects\mathpix\latex2sympy\process_latex.py", line 58, in syntaxError
    raise Exception(err)
Exception: I don't understand this
A = \left( \begin{array} { l l l } { 2} & { 7} & { 3} \\ { 3} & { 5} & { 2} \\ { 9} & { 4} & { 1} \end{array} \right)

假分数

当使用print(process_sympy("2\frac{3}{5}"))时,输出为:2*(3/5)
但实际上这是一个假分数,结果应该是2+3/5

Antlr4 on Linux reference to undefined rule: exp

Hello,

This is what I get when I try installing latex2sympy on CentOS

[..latex2sympy]# java -jar antlr-4.5.3-complete.jar PS.g4 -o gen
error(56): PS.g4:113:9: reference to undefined rule: exp
error(56): PS.g4:114:16: reference to undefined rule: exp_nofunc
error(56): PS.g4:118:9: reference to undefined rule: eval_at_sup
error(56): PS.g4:118:37: reference to undefined rule: eval_at_sup

How to run the tests in test.py

I am having trouble running the tests in the test.py file. I have tried:

$python2 test.py
Traceback (most recent call last):
  File "test.py", line 64, in <module>
    ("f(x)", f(x)),
TypeError: 'Symbol' object is not callable

Does this mean that the tests should be ran in some other environment?

anltr4 module

The module process_latex.py imports a module called antlr4. What is this? Or, to put it another way, where can this be obtained?

I have installed the antlr4 command and used it to populate the gen directory. I have also used pip to install the antlr4-python2-runtime" package. But I have no idea where the antlr4` package might be.

Incorrect parsing of negative numbers

process_sympy("(-1) * 2") and process_sympy("-2") return the same result Mul(-1, 2). process_sympy("-2") should return -2 instead of Mul(-1, 2).

process_sympy("-2/3") returns Mul(Mul(-1, 2), Pow(3, -1)) instead of Rational(-2, 3).

Possibly include in SymPy

Your software solves a longstanding issue in SymPy:

sympy/sympy#5418

and is something that we'd really like to be included in SymPy.

Would you be interested in adding this to SymPy instead of having a standalone package? It'd certainly increase the usage and visibility.

Multiple \\int, \\sum, or \\prod statements

It seems that adding multiple expressions for \\int,\\sum, or \\prod together will cause an error to occur. For instance:
process_sympy("\\int_{-3}^{4} \\frac{1}{x}dx+\\int_{1.5}^{2} \\ln(x)dx")
Throws:

UnboundLocalError: local variable 'int_var' referenced before assignment

In PS.g4, I found a way to allow summing multiple integrals.
Change:
| FUNC_INT
(subexpr supexpr | supexpr subexpr)?
(additive? DIFFERENTIAL | frac | additive)

To:
| FUNC_INT
(subexpr supexpr | supexpr subexpr)?
(additive? DIFFERENTIAL)

Unfortunately, this doesn't allow differentials to be in fractional form. For example: \\int_{3}^{5} dx/x

Thanks for your time,
John

Reverse SymPy LaTeX printer

SymPy has a LaTeX printer, the function latex( ) returns the LaTeX representation of the string.

It would be good to add tests, to check that latex2sympy is able to parse back generated LaTeX strings to SymPy's original expression.

Given a SymPy expression, let's say expr, test could look like:

from sympy import latex
assert eval(process_latex(latex(expr))) == expr

This could be used to both:

  • detect bugs in SymPy's LaTeX printer.
  • detect bugs in latex2sympy

Missing files in gen folder

Hello,
I hope this is something I'm missing but the process_latex.py file is importing from the gen folder which is empty. Is there I way I can access the functionality of this package?

Thanks,

Jake Noble

PyPI package

I could not find a package on PyPI for this module. Can you create one?

Function raised to a power gives an error

Hello, I have noticed a few features that are not implemented yet. I have solved most of them by pre-processing input from MathQuill. I use this code:

string.replace('\\right', '') # right tag .replace('\\left', '') # left tag .replace("^x","^{(x)}") # powers .replace("\ ","") #Spaces

However, one thing I couldn't solve without changing latex2sympy code is when a user inputs a function raised to a power (say sin^nx instead of (sinx)^n) latex2sympy crashes and gives NoneType' object has no attribute 'additive'.
Also, I believe hyperbolic trig functions are not supported yet (might be a very simple addition)
Can you please correct this? Thank you in advance!

exponent problem

x^b is a valid Latex expression but process_sympy() requires x^{b} for conversion to sympy.

Handling `mod` operator in the parser

Mod operator has not been handled. Is there any reason why this has been skipped ?
Mod is a standard operator in sympy supported operators collection.

Unable to handle sympy Integral class latex

When parsing back the obtained latex on a sympy Integral object to process_sympy(), it throws an exception. Adding code snippet and error log. Occurs on python 2.7 and 3.

The error occurs due to the extra "," being generated and if I add this line
latex_expr = latex_expr.replace("\,", "")
before passing latex_expr back to process_sympy() it seems to be working fine.


from sympy import *
from sympy.abc import *
from process_latex import process_sympy

expr = Integral((x+1)**2, x)
latex_expr = latex(expr)
back_to_expr = process_sympy(latex_expr)


Exception: I don't understand this
\int \left(x + 1\right)^{2}, dx


----

Not parsing integrals correctly

\int^{3}_{1} x^{2} + \frac{1}{x} dx

gets parsed to:

integrate (x*_(2),(x,1,3))+((1)/(x))_d*x

It seems the integral is not capturing the whole expression up to dx.

fix undefined symbols problem

pm is used to show plus-minus, is yet not implemented into sympy. #5305
Example latex: \frac{-b\pm\sqrt{b^2-4ac}}{2a}
when converted into sympy using latex2sympy, I get
-b*pm*sqrt(-4*a*c + b**2)/(2*a)

So, the undefined pm simply gets multiplied. Hence getting wrong expression.
It should have probably shown an error.

In fact, any undefined thing simply gets multiplied
Ex: -b*pm*blabla*(-4*a*c + b**2)/(2*a)

Sympy does not evaluate Latex2sympy conversion for sin(-x) or sin(pi)

Hi,

I have been using Latex2SymPy for a while successfully to handle all sorts of LaTeX inputs, but I have been running into troubles with a few functions. For instance:

from latex2sympy.process_latex import process_sympy
from sympy import *

inputLatex = '\\sin{-x}\\sin{-x}'
trigsimp(process_sympy(inputLatex))

Result: sin(x)**2

That works great: trigsimp handled the simplification well. Now, if I try:

 inputLatex = '\\sin{-x}'
 trigsimp(process_sympy(inputLatex))

Result: sin(-x)

Even though this is obviously correct, I expected trigsimp() to give me -sin(x) as an answer. In fact, if I run trigsimp straight from a sympy expression:

 trigsimp(sin(-x))

Result: -sin(x)

This is what I expect. Even running sin(-x) without the trigsimp() command returns me -sin(x). I checked the object type of my process_sympy('\sin{-x}') call, and it is 'sin'.

I thought this might be something related with the way x is transformed into a Symbol type, but I then tried putting pi in the sin function.

inputLatex = '\\sin{\\pi}'
trigsimp(process_sympy(inputLatex))

Result: sin(pi)

If I run straight sin(pi), I get 0 as an answer, with or without trigsimp().

Has anyone bumped into any issue like that before? Any ideas on how to solve_

\\ or \

Hello,

I have been checking your examples and LaTex and found out, that frac with single slash (\frac) doesn't work. At the same time \ \frac is working.
screenshot_5

Meanwhile, \sum, \int_ , \infty, \sqrt, \pi (with single ) are working, but binom needs \ \ (and convert to binom_(k_n), instead of binomial(k,n) in sympy ).
So, what to use? If we should strictly use , add this please to the documentation.

Add python version to README

Hello, thank you for your lib!
Can you please add required python version for your readme. I have had a hard time with python 3.5 and syntax error in lib, python 2.7 (via anaconda) works perfectly.

Construct SymPy objects directly

This parser translates LaTeX into a string to be parsed again by SymPy.

It would be more efficient (and less error-prone) if process_sympy gave a SymPy expression directly.

Can't parse expr like "2x"

2x in latex format should be convert to 2*x in sympy format, however, latex2sympy converted it to 2 x

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.