Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.data/data/share/man/man1/isympy.1Added+188
- ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/METADATAAdded+319
- ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/RECORDAdded
- ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/WHEELAdded+5
- ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/entry_points.txtAdded+2
- ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/licenses/AUTHORSAdded+1379
- ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/licenses/LICENSEAdded+153
- ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/top_level.txtAdded+2
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.pyAdded+55
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.alAdded+25
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.pyAdded+39
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.alAdded+19
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.pyAdded+31
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.alAdded+20
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.pyAdded+36
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/c/__init__.pyAdded+1
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/c/c_parser.pyAdded+1059
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/fortran/__init__.pyAdded+1
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/fortran/fortran_parser.pyAdded+347
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/LICENSE.txtAdded+21
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/LaTeX.g4Added+312
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/__init__.pyAdded+204
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_antlr/__init__.pyAdded+9
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_antlr/latexlexer.pyAdded+512
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_antlr/latexparser.pyAdded
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_build_latex_antlr.pyAdded+91
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_parse_latex_antlr.pyAdded+607
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/errors.pyAdded+2
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/__init__.pyAdded+2
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/grammar/greek_symbols.larkAdded+28
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/grammar/latex.larkAdded+403
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/latex_parser.pyAdded+145
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/transformer.pyAdded+730
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/__init__.pyAdded
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_ast_parser.pyAdded+25
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_autolev.pyAdded+178
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_c_parser.pyAdded
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_custom_latex.pyAdded+69
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_fortran_parser.pyAdded+406
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_implicit_multiplication_application.pyAdded+195
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_latex.pyAdded+358
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_latex_deps.pyAdded+16
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_latex_lark.pyAdded+872
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_mathematica.pyAdded+280
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_maxima.pyAdded+50
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_sym_expr.pyAdded+209
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_sympy_parser.pyAdded+371
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/physics/__init__.pyAdded+12
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/physics/biomechanics/__init__.pyAdded+53
- ScaleDF_rebuttal/python_dedup_pkgs/sympy/physics/biomechanics/_mixin.pyAdded+53
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188'\" -*- coding: us-ascii -*-.if \n(.g .ds T< \\FC.if \n(.g .ds T> \\F[\n[.fam]].de URL\\$2 \(la\\$1\(ra\\$3...if \n(.g .mso www.tmac.TH isympy 1 2007-10-8 "" "".SH NAMEisympy \- interactive shell for SymPy.SH SYNOPSIS'nh.fi.ad l\fBisympy\fR \kx.if (\nx>(\n(.l/2)) .nr x (\n(.l/5)'in \n(.iu+\nxu[\fB-c\fR | \fB--console\fR] [\fB-p\fR ENCODING | \fB--pretty\fR ENCODING] [\fB-t\fR TYPE | \fB--types\fR TYPE] [\fB-o\fR ORDER | \fB--order\fR ORDER] [\fB-q\fR | \fB--quiet\fR] [\fB-d\fR | \fB--doctest\fR] [\fB-C\fR | \fB--no-cache\fR] [\fB-a\fR | \fB--auto\fR] [\fB-D\fR | \fB--debug\fR] [-- | PYTHONOPTIONS]'in \n(.iu-\nxu.ad b'hy'nh.fi.ad l\fBisympy\fR \kx.if (\nx>(\n(.l/2)) .nr x (\n(.l/5)'in \n(.iu+\nxu[{\fB-h\fR | \fB--help\fR}|{\fB-v\fR | \fB--version\fR}]'in \n(.iu-\nxu.ad b'hy.SH DESCRIPTIONisympy is a Python shell for SymPy. It is just a normal python shell(ipython shell if you have the ipython package installed) that executesthe following commands so that you don't have to:.PP.nf\*(T<>>> from __future__ import division>>> from sympy import *>>> x, y, z = symbols("x,y,z")>>> k, m, n = symbols("k,m,n", integer=True) \*(T>.fi.PPSo starting isympy is equivalent to starting python (or ipython) andexecuting the above commands by hand. It is intended for easy and quickexperimentation with SymPy. For more complicated programs, it is recommendedto write a script and import things explicitly (using the "from sympyimport sin, log, Symbol, ..." idiom)..SH OPTIONS.TP\*(T<\fB\-c \fR\*(T>\fISHELL\fR, \*(T<\fB\-\-console=\fR\*(T>\fISHELL\fRUse the specified shell (python or ipython) asconsole backend instead of the default one (ipythonif present or python otherwise).
Example: isympy -c python
\fISHELL\fR could be either\&'ipython' or 'python'.TP\*(T<\fB\-p \fR\*(T>\fIENCODING\fR, \*(T<\fB\-\-pretty=\fR\*(T>\fIENCODING\fRSetup pretty printing in SymPy. By default, the most pretty, unicodeprinting is enabled (if the terminal supports it). You can use lesspretty ASCII printing instead or no pretty printing at all.
Example: isympy -p no
\fIENCODING\fR must be one of 'unicode',\&'ascii' or 'no'..TP\*(T<\fB\-t \fR\*(T>\fITYPE\fR, \*(T<\fB\-\-types=\fR\*(T>\fITYPE\fRSetup the ground types for the polys. By default, gmpy ground typesare used if gmpy2 or gmpy is installed, otherwise it falls back to pythonground types, which are a little bit slower. You can manuallychoose python ground types even if gmpy is installed (e.g., for testing purposes).
Note that sympy ground types are not supported, and should be usedonly for experimental purposes.
Note that the gmpy1 ground type is primarily intended for testing; it theuse of gmpy even if gmpy2 is available.
This is the same as setting the environment variableSYMPY_GROUND_TYPES to the given ground type (e.g.,SYMPY_GROUND_TYPES='gmpy')
The ground types can be determined interactively from the variablesympy.polys.domains.GROUND_TYPES inside the isympy shell itself.
Example: isympy -t python
\fITYPE\fR must be one of 'gmpy',\&'gmpy1' or 'python'..TP\*(T<\fB\-o \fR\*(T>\fIORDER\fR, \*(T<\fB\-\-order=\fR\*(T>\fIORDER\fRSetup the ordering of terms for printing. The default is lex, whichorders terms lexicographically (e.g., x**2 + x + 1). You can chooseother orderings, such as rev-lex, which will use reverselexicographic ordering (e.g., 1 + x + x**2).
Note that for very large expressions, ORDER='none' may speed upprinting considerably, with the tradeoff that the order of the termsin the printed expression will have no canonical order
Example: isympy -o rev-lax
\fIORDER\fR must be one of 'lex', 'rev-lex', 'grlex',\&'rev-grlex', 'grevlex', 'rev-grevlex', 'old', or 'none'..TP\*(T<\fB\-q\fR\*(T>, \*(T<\fB\-\-quiet\fR\*(T>Print only Python's and SymPy's versions to stdout at startup, and nothing else..TP\*(T<\fB\-d\fR\*(T>, \*(T<\fB\-\-doctest\fR\*(T>Use the same format that should be used for doctests. This isequivalent to '\fIisympy -c python -p no\fR'..TP\*(T<\fB\-C\fR\*(T>, \*(T<\fB\-\-no\-cache\fR\*(T>Disable the caching mechanism. Disabling the cache may slow certainoperations down considerably. This is useful for testing the cache,or for benchmarking, as the cache can result in deceptive benchmark timings.
This is the same as setting the environment variable SYMPY_USE_CACHEto 'no'..TP\*(T<\fB\-a\fR\*(T>, \*(T<\fB\-\-auto\fR\*(T>Automatically create missing symbols. Normally, typing a name of aSymbol that has not been instantiated first would raise NameError,but with this option enabled, any undefined name will beautomatically created as a Symbol. This only works in IPython 0.11.
Note that this is intended only for interactive, calculator styleusage. In a script that uses SymPy, Symbols should be instantiatedat the top, so that it's clear what they are.
This will not override any names that are already defined, whichincludes the single character letters represented by the mnemonicQCOSINE (see the "Gotchas and Pitfalls" document in thedocumentation). You can delete existing names by executing "delname" in the shell itself. You can see if a name is defined by typing"'name' in globals()".
The Symbols that are created using this have default assumptions.If you want to place assumptions on symbols, you should create themusing symbols() or var().
Finally, this only works in the top level namespace. So, forexample, if you define a function in isympy with an undefinedSymbol, it will not work..TP\*(T<\fB\-D\fR\*(T>, \*(T<\fB\-\-debug\fR\*(T>Enable debugging output. This is the same as setting theenvironment variable SYMPY_DEBUG to 'True'. The debug status is setin the variable SYMPY_DEBUG within isympy..TP-- \fIPYTHONOPTIONS\fRThese options will be passed on to \fIipython (1)\fR shell.Only supported when ipython is being used (standard python shell not supported).
Two dashes (--) are required to separate \fIPYTHONOPTIONS\fRfrom the other isympy options.
For example, to run iSymPy without startup banner and colors:
isympy -q -c ipython -- --colors=NoColor.TP\*(T<\fB\-h\fR\*(T>, \*(T<\fB\-\-help\fR\*(T>Print help output and exit..TP\*(T<\fB\-v\fR\*(T>, \*(T<\fB\-\-version\fR\*(T>Print isympy version information and exit..SH FILES.TP\*(T<\fI${HOME}/.sympy\-history\fR\*(T>Saves the history of commands when using the pythonshell as backend..SH BUGSThe upstreams BTS can be found at \(lahttps://github.com/sympy/sympy/issues\(raPlease report all bugs that you find in there, this will help improvethe overall quality of SymPy..SH "SEE ALSO"\fBipython\fR(1), \fBpython\fR(1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319Metadata-Version: 2.4Name: sympyVersion: 1.14.0Summary: Computer algebra system (CAS) in PythonHome-page: https://sympy.orgAuthor: SymPy development teamAuthor-email: sympy@googlegroups.comLicense: BSDProject-URL: Source, https://github.com/sympy/sympyKeywords: Math CASClassifier: License :: OSI Approved :: BSD LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Topic :: Scientific/EngineeringClassifier: Topic :: Scientific/Engineering :: MathematicsClassifier: Topic :: Scientific/Engineering :: PhysicsClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyRequires-Python: >=3.9Description-Content-Type: text/markdownLicense-File: LICENSELicense-File: AUTHORSRequires-Dist: mpmath<1.4,>=1.1.0Provides-Extra: devRequires-Dist: pytest>=7.1.0; extra == "dev"Requires-Dist: hypothesis>=6.70.0; extra == "dev"Dynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: description-content-typeDynamic: home-pageDynamic: keywordsDynamic: licenseDynamic: license-fileDynamic: project-urlDynamic: provides-extraDynamic: requires-distDynamic: requires-pythonDynamic: summary
# SymPy
[](https://pypi.python.org/pypi/sympy)[](https://gitter.im/sympy/sympy?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)[](https://zenodo.org/badge/latestdoi/18918/sympy/sympy)[](https://pepy.tech/project/sympy)[](https://github.com/sympy/sympy/issues)[](https://git-scm.com/book/en/v2/GitHub-Contributing-to-a-Project)[](https://numfocus.org)[](https://github.com/sympy/sympy/releases)
[](https://sympy.org/)
See the [AUTHORS](AUTHORS) file for the list of authors.
And many more people helped on the SymPy mailing list, reported bugs,helped organize SymPy's participation in the Google Summer of Code, theGoogle Highly Open Participation Contest, Google Code-In, wrote andblogged about SymPy...
License: New BSD License (see the [LICENSE](LICENSE) file for details) covers allfiles in the sympy repository unless stated otherwise.
Our mailing list is at<https://groups.google.com/forum/?fromgroups#!forum/sympy>.
We have a community chat at [Gitter](https://gitter.im/sympy/sympy). Feelfree to ask us anything there. We have a very welcoming and helpfulcommunity.
## Download
The recommended installation method is through Anaconda,<https://www.anaconda.com/products/distribution>
You can also get the latest version of SymPy from<https://pypi.python.org/pypi/sympy/>
To get the git version do
$ git clone https://github.com/sympy/sympy.git
For other options (tarballs, debs, etc.), see<https://docs.sympy.org/dev/install.html>.
## Documentation and Usage
For in-depth instructions on installation and building thedocumentation, see the [SymPy Documentation Style Guide](https://docs.sympy.org/dev/documentation-style-guide.html).
Everything is at:
<https://docs.sympy.org/>
You can generate everything at the above site in your local copy ofSymPy by:
$ cd doc $ make html
Then the docs will be in <span class="title-ref">\_build/html</span>. Ifyou don't want to read that, here is a short usage:
From this directory, start Python and:
``` python>>> from sympy import Symbol, cos>>> x = Symbol('x')>>> e = 1/cos(x)>>> print(e.series(x, 0, 10))1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + 277*x**8/8064 + O(x**10)```
SymPy also comes with a console that is a simple wrapper around theclassic python console (or IPython when available) that loads the SymPynamespace and executes some common commands for you.
To start it, issue:
$ bin/isympy
from this directory, if SymPy is not installed or simply:
$ isympy
if SymPy is installed.
## Installation
To install SymPy using PyPI, run the following command:
$ pip install sympy
To install SymPy using Anaconda, run the following command:
$ conda install -c anaconda sympy
To install SymPy from GitHub source, first clone SymPy using `git`:
$ git clone https://github.com/sympy/sympy.git
Then, in the `sympy` repository that you cloned, simply run:
$ pip install .
See <https://docs.sympy.org/dev/install.html> for more information.
## Contributing
We welcome contributions from anyone, even if you are new to opensource. Please read our [Introduction to Contributing](https://docs.sympy.org/dev/contributing/introduction-to-contributing.html)page and the [SymPy Documentation Style Guide](https://docs.sympy.org/dev/documentation-style-guide.html). If youare new and looking for some way to contribute, a good place to start isto look at the issues tagged [Easy to Fix](https://github.com/sympy/sympy/issues?q=is%3Aopen+is%3Aissue+label%3A%22Easy+to+Fix%22).
Please note that all participants in this project are expected to followour Code of Conduct. By participating in this project you agree to abideby its terms. See [CODE\_OF\_CONDUCT.md](CODE_OF_CONDUCT.md).
## Tests
To execute all tests, run:
$./setup.py test
in the current directory.
For the more fine-grained running of tests or doctests, use `bin/test`or respectively `bin/doctest`. The master branch is automatically testedby GitHub Actions.
To test pull requests, use[sympy-bot](https://github.com/sympy/sympy-bot).
## Regenerate Experimental <span class="title-ref">LaTeX</span> Parser/Lexer
The parser and lexer were generated with the [ANTLR4](http://antlr4.org)toolchain in `sympy/parsing/latex/_antlr` and checked into the repo.Presently, most users should not need to regenerate these files, butif you plan to work on this feature, you will need the `antlr4`command-line tool (and you must ensure that it is in your `PATH`).One way to get it is:
$ conda install -c conda-forge antlr=4.11.1
Alternatively, follow the instructions on the ANTLR website and downloadthe `antlr-4.11.1-complete.jar`. Then export the `CLASSPATH` as instructedand instead of creating `antlr4` as an alias, make it an executable filewith the following contents:``` bash#!/bin/bashjava -jar /usr/local/lib/antlr-4.11.1-complete.jar "$@"```
After making changes to `sympy/parsing/latex/LaTeX.g4`, run:
$ ./setup.py antlr
## Clean
To clean everything (thus getting the same tree as in the repository):
$ git clean -Xdf
which will clear everything ignored by `.gitignore`, and:
$ git clean -df
to clear all untracked files. You can revert the most recent changes ingit with:
$ git reset --hard
WARNING: The above commands will all clear changes you may have made,and you will lose them forever. Be sure to check things with `gitstatus`, `git diff`, `git clean -Xn`, and `git clean -n` before doing anyof those.
## Bugs
Our issue tracker is at <https://github.com/sympy/sympy/issues>. Pleasereport any bugs that you find. Or, even better, fork the repository onGitHub and create a pull request. We welcome all changes, big or small,and we will help you make the pull request if you are new to git (justask on our mailing list or Gitter Channel). If you further have any queries, you can find answerson Stack Overflow using the [sympy](https://stackoverflow.com/questions/tagged/sympy) tag.
## Brief History
SymPy was started by Ondřej Čertík in 2005, he wrote some code duringthe summer, then he wrote some more code during summer 2006. In February2007, Fabian Pedregosa joined the project and helped fix many things,contributed documentation, and made it alive again. 5 students (MateuszPaprocki, Brian Jorgensen, Jason Gedge, Robert Schwarz, and Chris Wu)improved SymPy incredibly during summer 2007 as part of the GoogleSummer of Code. Pearu Peterson joined the development during the summer2007 and he has made SymPy much more competitive by rewriting the corefrom scratch, which has made it from 10x to 100x faster. Jurjen N.E. Boshas contributed pretty-printing and other patches. Fredrik Johansson haswritten mpmath and contributed a lot of patches.
SymPy has participated in every Google Summer of Code since 2007. Youcan see <https://github.com/sympy/sympy/wiki#google-summer-of-code> forfull details. Each year has improved SymPy by bounds. Most of SymPy'sdevelopment has come from Google Summer of Code students.
In 2011, Ondřej Čertík stepped down as lead developer, with AaronMeurer, who also started as a Google Summer of Code student, taking hisplace. Ondřej Čertík is still active in the community but is too busywith work and family to play a lead development role.
Since then, a lot more people have joined the development and somepeople have also left. You can see the full list in doc/src/aboutus.rst,or online at:
<https://docs.sympy.org/dev/aboutus.html#sympy-development-team>
The git history goes back to 2007 when development moved from svn to hg.To see the history before that point, look at<https://github.com/sympy/sympy-old>.
You can use git to see the biggest developers. The command:
$ git shortlog -ns
will show each developer, sorted by commits to the project. The command:
$ git shortlog -ns --since="1 year"
will show the top developers from the last year.
## Citation
To cite SymPy in publications use
> Meurer A, Smith CP, Paprocki M, Čertík O, Kirpichev SB, Rocklin M,> Kumar A, Ivanov S, Moore JK, Singh S, Rathnayake T, Vig S, Granger BE,> Muller RP, Bonazzi F, Gupta H, Vats S, Johansson F, Pedregosa F, Curry> MJ, Terrel AR, Roučka Š, Saboo A, Fernando I, Kulal S, Cimrman R,> Scopatz A. (2017) SymPy: symbolic computing in Python. *PeerJ Computer> Science* 3:e103 <https://doi.org/10.7717/peerj-cs.103>
A BibTeX entry for LaTeX users is
``` bibtex@article{10.7717/peerj-cs.103, title = {SymPy: symbolic computing in Python}, author = {Meurer, Aaron and Smith, Christopher P. and Paprocki, Mateusz and \v{C}ert\'{i}k, Ond\v{r}ej and Kirpichev, Sergey B. and Rocklin, Matthew and Kumar, Amit and Ivanov, Sergiu and Moore, Jason K. and Singh, Sartaj and Rathnayake, Thilina and Vig, Sean and Granger, Brian E. and Muller, Richard P. and Bonazzi, Francesco and Gupta, Harsh and Vats, Shivam and Johansson, Fredrik and Pedregosa, Fabian and Curry, Matthew J. and Terrel, Andy R. and Rou\v{c}ka, \v{S}t\v{e}p\'{a}n and Saboo, Ashutosh and Fernando, Isuru and Kulal, Sumith and Cimrman, Robert and Scopatz, Anthony}, year = 2017, month = Jan, keywords = {Python, Computer algebra system, Symbolics}, abstract = { SymPy is an open-source computer algebra system written in pure Python. It is built with a focus on extensibility and ease of use, through both interactive and programmatic applications. These characteristics have led SymPy to become a popular symbolic library for the scientific Python ecosystem. This paper presents the architecture of SymPy, a description of its features, and a discussion of select submodules. The supplementary material provides additional examples and further outlines details of the architecture and features of SymPy. }, volume = 3, pages = {e103}, journal = {PeerJ Computer Science}, issn = {2376-5992}, url = {https://doi.org/10.7717/peerj-cs.103}, doi = {10.7717/peerj-cs.103}}```
SymPy is BSD licensed, so you are free to use it whatever you like, beit academic, commercial, creating forks or derivatives, as long as youcopy the BSD statement if you redistribute it (see the LICENSE file fordetails). That said, although not required by the SymPy license, if itis convenient for you, please cite SymPy when using it in your work andalso consider contributing all your changes back, so that we canincorporate it and all of us will benefit in the end.12345Wheel-Version: 1.0Generator: setuptools (79.0.1)Root-Is-Purelib: trueTag: py3-none-any
12[console_scripts]isympy = isympy:main12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379All people who contributed to SymPy by sending at least a patch ormore (in the order of the date of their first contribution), exceptthose who explicitly didn't want to be mentioned. People with a * nextto their names are not found in the metadata of the git history. Thisfile is generated automatically by running `./bin/authors_update.py`.
There are a total of 1371 authors.
Ondřej Čertík <ondrej@certik.cz>Fabian Pedregosa <fabian@fseoane.net>Jurjen N.E. Bos <jnebos@gmail.com>Mateusz Paprocki <mattpap@gmail.com>*Marc-Etienne M.Leveille <protonyc@gmail.com>Brian Jorgensen <brian.jorgensen@gmail.com>Jason Gedge <inferno1386@gmail.com>Robert Schwarz <lethargo@googlemail.com>Pearu Peterson <pearu.peterson@gmail.com>Fredrik Johansson <fredrik.johansson@gmail.com>Chris Wu <chris.wu@gmail.com>*Ulrich Hecht <ulrich.hecht@gmail.com>Goutham Lakshminarayan <dl.goutham@gmail.com>David Lawrence <dmlawrence@gmail.com>Jaroslaw Tworek <dev.jrx@gmail.com>David Marek <h4wk.cz@gmail.com>Bernhard R. Link <brlink@debian.org>Andrej Tokarčík <androsis@gmail.com>Or Dvory <gidesa@gmail.com>Saroj Adhikari <adh.saroj@gmail.com>Pauli Virtanen <pav@iki.fi>Robert Kern <robert.kern@gmail.com>James Aspnes <aspnes@cs.yale.edu>Nimish Telang <ntelang@gmail.com>Abderrahim Kitouni <a.kitouni@gmail.com>Pan Peng <pengpanster@gmail.com>Friedrich Hagedorn <friedrich_h@gmx.de>Elrond der Elbenfuerst <elrond+sympy.org@samba-tng.org>Rizgar Mella <rizgar.mella@gmail.com>Felix Kaiser <felix.kaiser@fxkr.net>Roberto Nobrega <rwnobrega@gmail.com>David Roberts <dvdr18@gmail.com>Sebastian Krämer <basti.kr@gmail.com>Vinzent Steinberg <vinzent.steinberg@gmail.com>Riccardo Gori <goriccardo@gmail.com>Case Van Horsen <casevh@gmail.com>Stepan Roucka <stepan@roucka.eu>Ali Raza Syed <arsyed@gmail.com>Stefano Maggiolo <s.maggiolo@gmail.com>Robert Cimrman <cimrman3@ntc.zcu.cz>Bastian Weber <bastian.weber@gmx-topmail.de>Sebastian Krause <sebastian.krause@gmx.de>Sebastian Kreft <skreft@gmail.com>*Dan <coolg49964@gmail.com>Alan Bromborsky <abrombo@verizon.net>Boris Timokhin <qoqenator@gmail.com>Robert <average.programmer@gmail.com>Andy R. Terrel <aterrel@uchicago.edu>Hubert Tsang <intsangity@gmail.com>Konrad Meyer <konrad.meyer@gmail.com>Henrik Johansson <henjo2006@gmail.com>Priit Laes <plaes@plaes.org>Freddie Witherden <freddie@witherden.org>Brian E. Granger <ellisonbg@gmail.com>Andrew Straw <strawman@astraw.com>Kaifeng Zhu <cafeeee@gmail.com>Ted Horst <ted.horst@earthlink.net>Andrew Docherty <andrewd@maths.usyd.edu.au>Akshay Srinivasan <akshaysrinivasan@gmail.com>Aaron Meurer <asmeurer@gmail.com>Barry Wardell <barry.wardell@gmail.com>Tomasz Buchert <thinred@gmail.com>Vinay Kumar <gnulinooks@gmail.com>Johann Cohen-Tanugi <johann.cohentanugi@gmail.com>Jochen Voss <voss@seehuhn.de>Luke Peterson <hazelnusse@gmail.com>Chris Smith <smichr@gmail.com>Thomas Sidoti <TSidoti@gmail.com>Florian Mickler <florian@mickler.org>Nicolas Pourcelot <nicolas.pourcelot@gmail.com>Ben Goodrich <goodrich.ben@gmail.com>Toon Verstraelen <Toon.Verstraelen@UGent.be>Ronan Lamy <ronan.lamy@gmail.com>James Abbatiello <abbeyj@gmail.com>Ryan Krauss <ryanlists@gmail.com>Bill Flynn <wflynny@gmail.com>Kevin Goodsell <kevin-opensource@omegacrash.net>Jorn Baayen <jorn.baayen@gmail.com>Eh Tan <tan2tan2@gmail.com>Renato Coutinho <renato.coutinho@gmail.com>Oscar Benjamin <oscar.j.benjamin@gmail.com>Øyvind Jensen <jensen.oyvind@gmail.com>Julio Idichekop Filho <idichekop@yahoo.com.br>Łukasz Pankowski <lukpank@o2.pl>*Chu-Ching Huang <cchuang@mail.cgu.edu.tw>Fernando Perez <Fernando.Perez@berkeley.edu>Raffaele De Feo <alberthilbert@gmail.com>Christian Muise <christian.muise@gmail.com>Matt Curry <mattjcurry@gmail.com>Kazuo Thow <kazuo.thow@gmail.com>Christian Schubert <chr.schubert@gmx.de>Jezreel Ng <jezreel@gmail.com>James Pearson <xiong.chiamiov@gmail.com>Matthew Brett <matthew.brett@gmail.com>Addison Cugini <ajcugini@gmail.com>Nicholas J.S. Kinar <n.kinar@usask.ca>Harold Erbin <harold.erbin@gmail.com>Thomas Dixon <thom@thomdixon.org>Cristóvão Sousa <crisjss@gmail.com>Andre de Fortier Smit <freevryheid@gmail.com>Mark Dewing <markdewing@gmail.com>Alexey U. Gudchenko <proga@goodok.ru>Gary Kerr <gary.kerr@blueyonder.co.uk>Sherjil Ozair <sherjilozair@gmail.com>Oleksandr Gituliar <gituliar@gmail.com>Sean Vig <sean.v.775@gmail.com>Prafullkumar P. Tale <hector1618@gmail.com>Vladimir Perić <vlada.peric@gmail.com>Tom Bachmann <e_mc_h2@web.de>Yuri Karadzhov <yuri.karadzhov@gmail.com>Vladimir Lagunov <werehuman@gmail.com>Matthew Rocklin <mrocklin@cs.uchicago.edu>Saptarshi Mandal <sapta.iitkgp@gmail.com>Gilbert Gede <gilbertgede@gmail.com>Anatolii Koval <weralwolf@gmail.com>Tomo Lazovich <lazovich@gmail.com>Pavel Fedotov <fedotovp@gmail.com>Jack McCaffery <jpmccaffery@gmail.com>Jeremias Yehdegho <j.yehdegho@gmail.com>Kibeom Kim <kk1674@nyu.edu>Gregory Ksionda <ksiondag846@gmail.com>Tomáš Bambas <tomas.bambas@gmail.com>Raymond Wong <rayman_407@yahoo.com>Luca Weihs <astronomicalcuriosity@gmail.com>Shai 'Deshe' Wyborski <shaide@cs.huji.ac.il>Thomas Wiecki <thomas.wiecki@gmail.com>Óscar Nájera <najera.oscar@gmail.com>Mario Pernici <mario.pernici@gmail.com>Benjamin McDonald <mcdonald.ben@gmail.com>Sam Magura <samtheman132@gmail.com>Stefan Krastanov <krastanov.stefan@gmail.com>Bradley Froehle <brad.froehle@gmail.com>Min Ragan-Kelley <benjaminrk@gmail.com>Emma Hogan <ehogan@gemini.edu>Nikhil Sarda <diff.operator@gmail.com>Julien Rioux <julien.rioux@gmail.com>Roberto Colistete, Jr. <roberto.colistete@gmail.com>Raoul Bourquin <raoulb@bluewin.ch>Gert-Ludwig Ingold <gert.ingold@physik.uni-augsburg.de>Srinivas Vasudevan <srvasude@gmail.com>Jason Moore <moorepants@gmail.com>Miha Marolt <tloramus@gmail.com>Tim Lahey <tim.lahey@gmail.com>Luis Garcia <ppn.online@me.com>Matt Rajca <matt.rajca@me.com>David Li <l33tnerd.li@gmail.com>Alexandr Gudulin <alexandr.gudulin@gmail.com>Bilal Akhtar <bilalakhtar@ubuntu.com>Grzegorz Świrski <sognat@gmail.com>Matt Habel <habelinc@gmail.com>David Ju <Sgtmook314@gmail.com>Nichita Utiu <nikita.utiu+github@gmail.com>Nikolay Lazarov <qwerqwerqwer@abv.bg>Steve Anton <anxuiz.nx@gmail.com>Imran Ahmed Manzoor <imran.manzoor31@gmail.com>Ljubiša Moćić <3rdslasher@gmail.com>Piotr Korgul <p.korgul@gmail.com>Jim Zhang <Hyriodula@gmail.com>Sam Sleight <samuel.sleight@gmail.com>tborisova <ts.borisova3@gmail.com>Chancellor Arkantos <Chancellor_Arkantos@hotmail.co.uk>Stepan Simsa <simsa.st@gmail.com>Tobias Lenz <t_lenz94@web.de>Siddhanathan Shanmugam <siddhanathan@gmail.com>Tiffany Zhu <bubble.wubble.303@gmail.com>Tristan Hume <tris.hume@gmail.com>Alexey Subach <alexey.subach@gmail.com>Joan Creus <joan.creus.c@gmail.com>Geoffry Song <goffrie@gmail.com>Puneeth Chaganti <punchagan@gmail.com>Marcin Kostrzewa <>Natalia Nawara <fankalemura@gmail.com>vishal <vishal.panjwani15@gmail.com>Shruti Mangipudi <shruti2395@gmail.com>Davy Mao <e_equals_mass_speed_light_squared@hotmail.com>Swapnil Agarwal <swapnilag29@gmail.com>Dhia Kennouche <kendhia@gmail.com>jerryma1121 <jerryma1121@gmail.com>Joachim Durchholz <jo@durchholz.org>Martin Povišer <martin.povik@gmail.com>Siddhant Jain <getsiddhant@gmail.com>Kevin Hunter <hunteke@earlham.edu>Michael Mayorov <marchael@kb.csu.ru>Nathan Alison <nathan.f.alison@gmail.com>Christian Bühler <christian@cbuehler.de>Carsten Knoll <CarstenKnoll@gmx.de>Bharath M R <catchmrbharath@gmail.com>Matthias Toews <mat.toews@googlemail.com>Sergiu Ivanov <unlimitedscolobb@gmail.com>Jorge E. Cardona <jorgeecardona@gmail.com>Sanket Agarwal <sanket@sanketagarwal.com>Manoj Babu K. <manoj.babu2378@gmail.com>Sai Nikhil <tsnlegend@gmail.com>Aleksandar Makelov <amakelov@college.harvard.edu>Sachin Irukula <sachin.irukula@gmail.com>Raphael Michel <webmaster@raphaelmichel.de>Ashwini Oruganti <ashwini.oruganti@gmail.com>Andreas Klöckner <inform@tiker.net>Prateek Papriwal <papriwalprateek@gmail.com>Arpit Goyal <agmps18@gmail.com>Angadh Nanjangud <angadh.n@gmail.com>Comer Duncan <comer.duncan@gmail.com>Jens H. Nielsen <jenshnielsen@gmail.com>Joseph Dougherty <Github@JWDougherty.com>Elliot Marshall <Marshall2389@gmail.com>Guru Devanla <grdvnl@gmail.com>George Waksman <waksman@gwax.com>Alexandr Popov <alexandr.s.popov@gmail.com>Tarun Gaba <tarun.gaba7@gmail.com>Takafumi Arakaki <aka.tkf@gmail.com>Saurabh Jha <saurabh.jhaa@gmail.com>Rom le Clair <jacen.guardian@gmail.com>Angus Griffith <16sn6uv@gmail.com>Timothy Reluga <treluga@math.psu.edu>Brian Stephanik <xoedusk@gmail.com>Alexander Eberspächer <alex.eberspaecher@gmail.com>Sachin Joglekar <srjoglekar246@gmail.com>Tyler Pirtle <teeler@gmail.com>Vasily Povalyaev <vapovalyaev@gmail.com>Colleen Lee <colleenclee@gmail.com>Matthew Hoff <mhoff14@gmail.com>Niklas Thörne <notrupertthorne@gmail.com>Huijun Mai <m.maihuijun@gmail.com>Marek Šuppa <mr@shu.io>Ramana Venkata <idlike2dream@gmail.com>Prasoon Shukla <prasoon92.iitr@gmail.com>Stefen Yin <zqyin@ucdavis.edu>Thomas Hisch <t.hisch@gmail.com>Madeleine Ball <mpball@gmail.com>Mary Clark <mary.spriteling@gmail.com>Rishabh Dixit <rishabhdixit11@gmail.com>Manoj Kumar <manojkumarsivaraj334@gmail.com>Akshit Agarwal <akshit.jiit@gmail.com>CJ Carey <perimosocordiae@gmail.com>Patrick Lacasse <patrick.m.lacasse@gmail.com>Ananya H <ananyaha93@gmail.com>Tarang Patel <tarangrockr@gmail.com>Christopher Dembia <cld72@cornell.edu>Benjamin Fishbein <fishbeinb@gmail.com>Sean Ge <seange727@gmail.com>Amit Jamadagni <bitsjamadagni@gmail.com>Ankit Agrawal <aaaagrawal@iitb.ac.in>Björn Dahlgren <bjodah@gmail.com>Christophe Saint-Jean <christophe.saint-jean@univ-lr.fr>Demian Wassermann <demian@bwh.harvard.edu>Khagesh Patel <khageshpatel93@gmail.com>Stephen Loo <shikil@yahoo.com>hm <hacman0@gmail.com>Patrick Poitras <acebulf@gmail.com>Katja Sophie Hotz <katja.sophie.hotz@student.tuwien.ac.at>Varun Joshi <joshi.142@osu.edu>Chetna Gupta <cheta.gup@gmail.com>Thilina Rathnayake <thilinarmtb@gmail.com>Max Hutchinson <maxhutch@gmail.com>Shravas K Rao <shravas@gmail.com>Matthew Tadd <matt.tadd@gmail.com>Alexander Hirzel <alex@hirzel.us>Randy Heydon <randy.heydon@clockworklab.net>Oliver Lee <oliverzlee@gmail.com>Seshagiri Prabhu <seshagiriprabhu@gmail.com>Pradyumna <pradyu1993@gmail.com>Erik Welch <erik.n.welch@gmail.com>Eric Nelson <eric.the.red.XLII@gmail.com>Roland Puntaier <roland.puntaier@chello.at>Chris Conley <chrisconley15@gmail.com>Tim Swast <tswast@gmail.com>Dmitry Batkovich <batya239@gmail.com>Francesco Bonazzi <franz.bonazzi@gmail.com>Yuriy Demidov <iurii.demidov@gmail.com>Rick Muller <rpmuller@gmail.com>Manish Gill <gill.manish90@gmail.com>Markus Müller <markus.mueller.1.g@googlemail.com>Amit Saha <amitsaha.in@gmail.com>Jeremy <twobitlogic@gmail.com>QuaBoo <kisonchristian@gmail.com>Stefan van der Walt <stefan@sun.ac.za>David Joyner <wdjoyner@gmail.com>Lars Buitinck <larsmans@gmail.com>Alkiviadis G. Akritas <akritas@uth.gr>Vinit Ravishankar <vinit.ravishankar@gmail.com>Michael Boyle <michael.oliver.boyle@gmail.com>Heiner Kirchhoffer <Heiner.Kirchhoffer@gmail.com>Pablo Puente <ppuedom@gmail.com>James Fiedler <jrfiedler@gmail.com>Harsh Gupta <mail@hargup.in>Tuomas Airaksinen <tuomas.airaksinen@gmail.com>Paul Strickland <p.e.strickland@gmail.com>James Goppert <james.goppert@gmail.com>rathmann <rathmann.os@gmail.com>Avichal Dayal <avichal.dayal@gmail.com>Paul Scott <paul.scott@nicta.com.au>Shipra Banga <bangashipra@gmail.com>Pramod Ch <pramodch14@gmail.com>Akshay <akshaynukala95@gmail.com>Buck Shlegeris <buck2@bruceh15.anu.edu.au>Jonathan Miller <jdmiller93@gmail.com>Edward Schembor <eschemb1@jhu.edu>Rajath Shashidhara <rajaths.rajaths@gmail.com>Zamrath Nizam <zamiguy_ni@yahoo.com>Aditya Shah <adityashah30@gmail.com>Rajat Aggarwal <rajataggarwal1975@gmail.com>Sambuddha Basu <sammygamer@live.com>Zeel Shah <kshah215@gmail.com>Abhinav Chanda <abhinavchanda01@gmail.com>Jim Crist <crist042@umn.edu>Sudhanshu Mishra <mrsud94@gmail.com>Anurag Sharma <anurags92@gmail.com>Soumya Dipta Biswas <sdb1323@gmail.com>Sushant Hiray <hiraysushant@gmail.com>Ben Lucato <ben.lucato@gmail.com>Kunal Arora <kunalarora.135@gmail.com>Henry Gebhardt <hsggebhardt@gmail.com>Dammina Sahabandu <dmsahabandu@gmail.com>Manish Shukla <manish.shukla393@gmail>Ralph Bean <rbean@redhat.com>richierichrawr <richierichrawr@users.noreply.github.com>John Connor <john.theman.connor@gmail.com>Juan Luis Cano Rodríguez <juanlu001@gmail.com>Sahil Shekhawat <sahilshekhawat01@gmail.com>Kundan Kumar <kundankumar18581@gmail.com>Stas Kelvich <stanconn@gmail.com>sevaader <sevaader@gmail.com>Dhruvesh Vijay Parikh <parikhdhruvesh1@gmail.com>Venkatesh Halli <venkatesh.fatality@gmail.com>Lennart Fricke <lennart@die-frickes.eu>Vlad Seghete <vlad.seghete@gmail.com>Shashank Agarwal <shashank.agarwal94@gmail.com>carstimon <carstimon@gmail.com>Pierre Haessig <pierre.haessig@crans.org>Maciej Baranski <getrox.sc@gmail.com>Benjamin Gudehus <hastebrot@gmail.com>Faisal Anees <faisal.iiit@gmail.com>Mark Shoulson <mark@kli.org>Robert Johansson <jrjohansson@gmail.com>Kalevi Suominen <jksuom@gmail.com>Kaushik Varanasi <kaushik.varanasi1@gmail.com>Fawaz Alazemi <Mba7eth@gmail.com>Ambar Mehrotra <mehrotraambar@gmail.com>David P. Sanders <dpsanders@gmail.com>Peter Brady <petertbrady@gmail.com>John V. Siratt <jvsiratt@gmail.com>Sarwar Chahal <chahal.sarwar98@gmail.com>Nathan Woods <charlesnwoods@gmail.com>Colin B. Macdonald <cbm@m.fsf.org>Marcus Näslund <naslundx@gmail.com>Clemens Novak <clemens@familie-novak.net>Mridul Seth <seth.mridul@gmail.com>Craig A. Stoudt <craig.stoudt@gmail.com>Raj <raj454raj@gmail.com>Mihai A. Ionescu <ionescu.a.mihai@gmail.com>immerrr <immerrr@gmail.com>Chai Wah Wu <cwwuieee@gmail.com>Leonid Blouvshtein <leonidbl91@gmail.com>Peleg Michaeli <freepeleg@gmail.com>ck Lux <lux.r.ck@gmail.com>zsc347 <zsc347@gmail.com>Hamish Dickson <hamish.dickson@gmail.com>Michael Gallaspy <gallaspy.michael@gmail.com>Roman Inflianskas <infroma@gmail.com>Duane Nykamp <nykamp@umn.edu>Ted Dokos <tdokos@gmail.com>Sunny Aggarwal <sunnyaggarwal1994@gmail.com>Victor Brebenar <v.brebenar@gmail.com>Akshat Jain <akshat.jain@students.iiit.ac.in>Shivam Vats <shivamvats.iitkgp@gmail.com>Longqi Wang <iqgnol@gmail.com>Juan Felipe Osorio <jfosorio@gmail.com>Ray Cathcart <github@cathcart.us>Lukas Zorich <lukas.zorich@gmail.com>Eric Miller <emiller42@gmail.com>Cody Herbst <cyherbst@gmail.com>Nishith Shah <nishithshah.2211@gmail.com>Amit Kumar <dtu.amit@gmail.com>Yury G. Kudryashov <urkud.urkud@gmail.com>Guillaume Gay <contact@damcb.com>Mihir Wadwekar <m.mihirw@gmail.com>Tuan Manh Lai <laituan245@gmail.com>Asish Panda <asishrocks95@gmail.com>Darshan Chaudhary <deathbullet@gmail.com>Alec Kalinin <alec.kalinin@gmail.com>Ralf Stephan <ralf@ark.in-berlin.de>Aaditya Nair <aadityanair6494@gmail.com>Jayesh Lahori <jlahori92@gmail.com>Harshil Goel <harshil158@gmail.com>Luv Agarwal <agarwal.iiit@gmail.com>Jason Ly <jason.ly@gmail.com>Lokesh Sharma <lokeshhsharma@gmail.com>Sartaj Singh <singhsartaj94@gmail.com>Chris Swierczewski <cswiercz@gmail.com>Konstantin Togoi <konstantin.togoi@gmail.com>Param Singh <paramsingh258@gmail.com>Sumith Kulal <sumith1896@gmail.com>Juha Remes <jremes@outlook.com>Philippe Bouafia <philippe.bouafia@ensea.fr>Peter Schmidt <peter@peterjs.com>Jiaxing Liang <liangjiaxing57@gmail.com>Lucas Jones <lucas@lucasjones.co.uk>Gregory Ashton <gash789@gmail.com>Jennifer White <jcrw122@googlemail.com>Renato Orsino <renato.orsino@gmail.com>Alistair Lynn <arplynn@gmail.com>Govind Sahai <gsiitbhu@gmail.com>Adam Bloomston <adam@glitterfram.es>Kyle McDaniel <mcdanie5@illinois.edu>Nguyen Truong Duy <truongduy134@yahoo.com>Alex Lindsay <adlinds3@ncsu.edu>Mathew Chong <mathewchong.dev@gmail.com>Jason Siefken <siefkenj@gmail.com>Gaurav Dhingra <gauravdhingra.gxyd@gmail.com>Gao, Xiang <qasdfgtyuiop@gmail.com>Kevin Ventullo <kevin.ventullo@gmail.com>mao8 <thisisma08@gmail.com>Isuru Fernando <isuruf@gmail.com>Shivam Tyagi <shivam.tyagi.apm13@itbhu.ac.in>Richard Otis <richard.otis@outlook.com>Rich LaSota <rjlasota@gmail.com>dustyrockpyle <dustyrockpyle@gmail.com>Anton Akhmerov <anton.akhmerov@gmail.com>Michael Zingale <michael.zingale@stonybrook.edu>Chak-Pong Chung <chakpongchung@gmail.com>David T <derDavidT@users.noreply.github.com>Phil Ruffwind <rf@rufflewind.com>Sebastian Koslowski <koslowski@kit.edu>Kumar Krishna Agrawal <kumar.1994.14@gmail.com>Dustin Gadal <Dustin.Gadal@gmail.com>João Moura <operte@gmail.com>Yu Kobayashi <yukoba@accelart.jp>Shashank Kumar <shashank.kumar.apc13@iitbhu.ac.in>Timothy Cyrus <tcyrus@users.noreply.github.com>Devyani Kota <devyanikota@gmail.com>Keval Shah <kevalshah_96@yahoo.co.in>Dzhelil Rufat <drufat@caltech.edu>Pastafarianist <mr.pastafarianist@gmail.com>Sourav Singh <souravsingh@users.noreply.github.com>Jacob Garber <jgarber1@ualberta.ca>Vinay Singh <csvinay.d@gmail.com>GolimarOurHero <metalera94@hotmail.com>Prashant Tyagi <prashanttyagi221295@gmail.com>Matthew Davis <davisml.md@gmail.com>Tschijnmo TSCHAU <tschijnmotschau@gmail.com>Alexander Bentkamp <bentkamp@gmail.com>Jack Kemp <metaknightdrake-git@yahoo.co.uk>Kshitij Saraogi <KshitijSaraogi@gmail.com>Thomas Baruchel <baruchel@gmx.com>Nicolás Guarín-Zapata <nicoguarin@gmail.com>Jens Jørgen Mortensen <jj@smoerhul.dk>Sampad Kumar Saha <sampadsaha5@gmail.com>Eva Charlotte Mayer <eva-charlotte.mayer@posteo.de>Laura Domine <temigo@gmx.com>Justin Blythe <jblythe29@gmail.com>Meghana Madhyastha <meghana.madhyastha@gmail.com>Tanu Hari Dixit <tokencolour@gmail.com>Shekhar Prasad Rajak <shekharrajak@live.com>Aqnouch Mohammed <aqnouch.mohammed@gmail.com>Arafat Dad Khan <arafat.da.khan@gmail.com>Boris Atamanovskiy <shaomoron@gmail.com>Sam Tygier <sam.tygier@hep.manchester.ac.uk>Jai Luthra <me@jailuthra.in>Guo Xingjian <Seeker1995@gmail.com>Sandeep Veethu <sandeep.veethu@gmail.com>Archit Verma <architv07@gmail.com>Shubham Tibra <shubh.tibra@gmail.com>Ashutosh Saboo <ashutosh.saboo96@gmail.com>Michael S. Hansen <michael.hansen@nih.gov>Anish Shah <shah.anish07@gmail.com>Guillaume Jacquenot <guillaume.jacquenot@gmail.com>Bhautik Mavani <mavanibhautik@gmail.com>Michał Radwański <enedil.isildur@gmail.com>Jerry Li <jerry@jerryli.ca>Pablo Zubieta <pabloferz@yahoo.com.mx>Shivam Agarwal <knowthyself2503@gmail.com>Chaitanya Sai Alaparthi <achaitanyasai@gmail.com>Arihant Parsoya <parsoyaarihant@gmail.com>Ruslan Pisarev <rpisarev@cloudlinux.com>Akash Trehan <akash.trehan123@gmail.com>Nishant Nikhil <nishantiam@gmail.com>Vladimir Poluhsin <vovapolu@gmail.com>Akshay Nagar <awesomeay13@yahoo.com>James Brandon Milam <jmilam343@gmail.com>Abhinav Agarwal <abhinavagarwal1996@gmail.com>Rishabh Daal <rishabhdaal@gmail.com>Sanya Khurana <sanya@monica.in>Aman Deep <amandeep1024@gmail.com>Aravind Reddy <aravindreddy255@gmail.com>Abhishek Verma <iamvermaabhishek@gmail.com>Matthew Parnell <matt@parnmatt.co.uk>Thomas Hickman <Thomas.Hickman42@gmail.com>Akshay Siramdas <akshaysiramdas@gmail.com>YiDing Jiang <yidinggjiangg@gmail.com>Jatin Yadav <jatinyadav25@gmail.com>Matthew Thomas <mnmt@users.noreply.github.com>Rehas Sachdeva <aquannie@gmail.com>Michael Mueller <michaeldmueller7@gmail.com>Srajan Garg <srajan.garg@gmail.com>Prabhjot Singh <prabhjot.nith@gmail.com>Haruki Moriguchi <harukimoriguchi@gmail.com>Tom Gijselinck <tomgijselinck@gmail.com>Nitin Chaudhary <nitinmax1000@gmail.com>Alex Argunov <sajkoooo@gmail.com>Nathan Musoke <nathan.musoke@gmail.com>Abhishek Garg <abhishekgarg119@gmail.com>Dana Jacobsen <dana@acm.org>Vasiliy Dommes <vasdommes@gmail.com>Phillip Berndt <phillip.berndt@googlemail.com>Haimo Zhang <zh.hammer.dev@gmail.com>Anthony Scopatz <scopatz@gmail.com>bluebrook <perl4logic@gmail.com>Leonid Kovalev <leonidvkovalev@gmail.com>Josh Burkart <jburkart@gmail.com>Dimitra Konomi <t8130064@dias.aueb.gr>Christina Zografou <t8130048@dias.aueb.gr>Fiach Antaw <fiach.antaw+github@gmail.com>Langston Barrett <langston.barrett@gmail.com>Krit Karan <kritkaran.b13@iiits.in>G. D. McBain <gdmcbain@protonmail.com>Prempal Singh <prempal.42@gmail.com>Gabriel Orisaka <orisaka@gmail.com>Matthias Bussonnier <bussonniermatthias@gmail.com>rahuldan <rahul02013@gmail.com>Colin Marquardt <github@marquardt-home.de>Andrew Taber <andrew.e.taber@gmail.com>Yash Reddy <write2yashreddy@gmail.com>Peter Stangl <peter.stangl@ph.tum.de>elvis-sik <e.sikora@grad.ufsc.br>Nikos Karagiannakis <nikoskaragiannakis@gmail.com>Jainul Vaghasia <jainulvaghasia@gmail.com>Dennis Meckel <meckel@datenschuppen.de>Harshil Meena <harshil.7535@gmail.com>Micky <mickydroch@gmail.com>Nick Curtis <nicholas.curtis@uconn.edu>Michele Zaffalon <michele.zaffalon@gmail.com>Martha Giannoudovardi <maapxa@gmail.com>Devang Kulshreshtha <devang.kulshreshtha.cse14@itbhu.ac.in>Steph Papanik <spapanik21@gmail.com>Mohammad Sadeq Dousti <msdousti@gmail.com>Arif Ahmed <arif.ahmed.5.10.1995@gmail.com>Abdullah Javed Nesar <abduljaved1994@gmail.com>Lakshya Agrawal <zeeshan.lakshya@gmail.com>shruti <shrutishrm512@gmail.com>Rohit Rango <rohit.rango@gmail.com>Hong Xu <hong@topbug.net>Ivan Petuhov <ivan@ostrovok.ru>Alsheh <alsheh@rpi.edu>Marcel Stimberg <marcel.stimberg@ens.fr>Alexey Pakhocmhik <cool.Bakov@yandex.ru>Tommy Olofsson <tommy.olofsson.90@gmail.com>Zulfikar <zulfikar97@gmail.com>Blair Azzopardi <blairuk@gmail.com>Danny Hermes <daniel.j.hermes@gmail.com>Sergey Pestov <pestov-sa@yandex.ru>Mohit Chandra <mohit.chandra@research.iiit.ac.in>Karthik Chintapalli <karthik.chintapalli@students.iiit.ac.in>Marcin Briański <marcin.brianski@student.uj.edu.pl>andreo <andrey.torba@gmail.com>Flamy Owl <flamyowl@protonmail.ch>Yicong Guo <guoyicong100@gmail.com>Varun Garg <varun.garg03@gmail.com>Rishabh Madan <rishabhmadan96@gmail.com>Aditya Kapoor <aditya.kapoor.apm12@itbhu.ac.in>Karan Sharma <karan1276@gmail.com>Vedant Rathore <vedantr1998@gmail.com>Johan Blåbäck <johan_bluecreek@riseup.net>Pranjal Tale <pranjaltale16@gmail.com>Jason Tokayer <jason.tokayer@gmail.com>Raghav Jajodia <jajodia.raghav@gmail.com>Rajat Thakur <rajatthakur1997@gmail.com>Dhruv Bhanushali <dhruv_b@live.com>Anjul Kumar Tyagi <anjul.ten@gmail.com>Barun Parruck <barun.parruck@gmail.com>Bao Chau <chauquocbao0907@gmail.com>Tanay Agrawal <tanay_agrawal@hotmail.com>Ranjith Kumar <ranjith.dakshana2015@gmail.com>Shikhar Makhija <shikharmakhija2@gmail.com>Yathartha Joshi <yathartha32@gmail.com>Valeriia Gladkova <valeriia.gladkova@gmail.com>Sagar Bharadwaj <sagarbharadwaj50@gmail.com>Daniel Mahler <dmahler@gmail.com>Ka Yi <chua.kayi@yahoo.com.sg>Rishat Iskhakov <iskhakov@frtk.ru>Szymon Mieszczak <szymon.mieszczak@gmail.com>Sachin Agarwal <sachinagarwal0499@gmail.com>Priyank Patel <pspbot7@gmail.com>Satya Prakash Dwibedi <akash581050@gmail.com>tools4origins <tools4origins@gmail.com>Nico Schlömer <nico.schloemer@gmail.com>Fermi Paradox <FermiParadox@users.noreply.github.com>Ekansh Purohit <purohit.e15@gmail.com>Vedarth Sharma <vedarth.sharma@gmail.com>Peeyush Kushwaha <peeyush.p97@gmail.com>Jayjayyy <vfhsln8s3l4b87t4c3@byom.de>Christopher J. Wright <cjwright4242gh@gmail.com>Jakub Wilk <jwilk@jwilk.net>Mauro Garavello <mauro.garavello@unimib.it>Chris Tefer <ctefer@gmail.com>Shikhar Jaiswal <jaiswalshikhar87@gmail.com>Chiu-Hsiang Hsu <wdv4758h@gmail.com>Carlos Cordoba <ccordoba12@gmail.com>Fabian Ball <fabian.ball@kit.edu>Yerniyaz <yerniyaz.nurgabylov@nu.edu.kz>Christiano Anderson <canderson@riseup.net>Robin Neatherway <robin.neatherway@gmail.com>Thomas Hunt <thomashunt13@gmail.com>Theodore Han <theodorehan@hotmail.com>Duc-Minh Phan <alephvn@gmail.com>Lejla Metohajrova <l.metohajrova@gmail.com>Samyak Jain <samyak.jain2016a@vitstudent.ac.in>Aditya Rohan <riyuzakiiitk@gmail.com>Vincent Delecroix <vincent.delecroix@labri.fr>Michael Sparapany <msparapa@purdue.edu>Harsh Jain <harshjniitr@gmail.com>Nathan Goldbaum <ngoldbau@illinois.edu>latot <felipematas@yahoo.com>Kenneth Lyons <ixjlyons@gmail.com>Stan Schymanski <stan.schymanski@env.ethz.ch>David Daly <david.daly12@kzoo.edu>Ayush Shridhar <ayush.shridhar1999@gmail.com>Javed Nissar <javednissar@gmail.com>Jiri Kuncar <jiri.kuncar@gmail.com>vedantc98 <vedantc98@gmail.com>Rupesh Harode <rupeshharode@gmail.com>Rob Zinkov <rob@zinkov.com>James Harrop <ebc121@gmail.com>James Taylor <user234683@tutanota.com>Ishan Joshi <ishanaj98@gmail.com>Marco Mancini <marco.mancini@obspm.fr>Boris Ettinger <ettinger.boris@gmail.com>Micah Fitch <micahscopes@gmail.com>Daniel Wennberg <daniel.wennberg@gmail.com>ylemkimon <ylemkimon@naver.com>Akash Vaish <akash.9712@gmail.com>Peter Enenkel <peter.enenkel+git@gmail.com>Waldir Pimenta <waldyrious@gmail.com>Jithin D. George <jithindgeorge93@gmail.com>Lev Chelyadinov <leva181777@gmail.com>Lucas Wiman <lucas.wiman@gmail.com>Rhea Parekh <rheaparekh12@gmail.com>James Cotton <peabody124@gmail.com>Robert Pollak <robert.pollak@posteo.net>anca-mc <anca-mc@users.noreply.github.com>Sourav Ghosh <souravghosh2197@gmail.com>Jonathan Allan <jjallan@users.noreply.github.com>Nikhil Pappu <nkhlpappu@gmail.com>Ethan Ward <etkewa@gmail.com>Cezary Marczak <zeddq1@gmail.com>dps7ud <dps7ud@virginia.edu>Nilabja Bhattacharya <nilabja10201992@gmail.com>Itay4 <31018228+Itay4@users.noreply.github.com>Poom Chiarawongse <eight1911@gmail.com>Yang Yang <wdscxsj@gmail.com>Cavendish McKay <cmckay@tachycline.com>Bradley Gannon <bradley.m.gannon@gmail.com>B McG <bmcg0890@gmail.com>Rob Drynkin <rob.drynkin@gmail.com>Seth Ebner <murgrehk@gmail.com>Akash Kundu <sk.sayakkundu1997@gmail.com>Mark Jeromin <mark.jeromin@sysfrog.net>Roberto Díaz Pérez <r.r.1994a@gmail.com>Gleb Siroki <g.shiroki@gmail.com>Segev Finer <segev208@gmail.com>Alex Lubbock <code@alexlubbock.com>Ayodeji Ige <ayodeji18@outlook.com>Matthew Wardrop <matthew.wardrop@airbnb.com>Hugo van Kemenade <hugovk@users.noreply.github.com>Austin Palmer <ap4000@nyu.edu>der-blaue-elefant <github@kklein.de>Filip Gokstorp <filip@gokstorp.se>Yuki Matsuda <yuki.matsuda.w@gmail.com>Aaron Miller <acmiller273@gmail.com>Salil Vishnu Kapur <salilvishnukapur@gmail.com>Atharva Khare <khareatharva@gmail.com>Shubham Maheshwari <rmaheshwari05@gmail.com>Pavel Tkachenko <paveltkachenko@email.com>Ashish Kumar Gaurav <ashishkg0022@gmail.com>Rajeev Singh <rajs2010@gmail.com>Keno Goertz <keno@goertz-berlin.com>Lucas Gallindo <lgallindo@gmail.com>Himanshu <hs80941@gmail.com>David Menéndez Hurtado <david.menendez.hurtado@scilifelab.se>Amit Manchanda <amitdelhi1995@gmail.com>Rohit Jain <rohitjain3241@gmail.com>Jonathan A. Gross <jarthurgross@gmail.com>Unknown <kunda@scribus.net>Sayan Goswami <Sayan98@users.noreply.github.com>Subhash Saurabh <subhashsaurabh419@gmail.com>Rastislav Rabatin <rastislav.rabatin@gmail.com>Vishal <vishalg2235@gmail.com>Jeremey Gluck <jeremygluck@yahoo.com>Akshat Maheshwari <akshat14714@gmail.com>symbolique <symbolique@users.noreply.github.com>Saloni Jain <tosalonijain@gmail.com>Arighna Chakrabarty <arighna.chakrabarty100@gmail.com>Abhigyan Khaund <mail@abhigyan.xyz>Jashanpreet Singh <jashansingh.4398@gmail.com>Saurabh Agarwal <shourabh.agarwal@gmail.com>luzpaz <luzpaz@users.noreply.github.com>P. Sai Prasanth <psai.prasanth.min16@itbhu.ac.in>Nirmal Sarswat <nirmalsarswat400@gmail.com>Cristian Di Pietrantonio <cristiandipietrantonio@gmail.com>Ravi charan <ravicharan.vsp@gmail.com>Nityananda Gohain <nityanandagohain@gmail.com>Cédric Travelletti <cedrictravelletti@gmail.com>Nicholas Bollweg <nick.bollweg@gmail.com>Himanshu Ladia <hladia199811@gmail.com>Adwait Baokar <adwaitbaokar18@gmail.com>Mihail Tarigradschi <m.tarigradschi@gmail.com>Saketh <alurusaisaketh@gmail.com>rushyam <rushyamsonu@gmail.com>sfoo <sfoohei@gmail.com>Rahil Hastu <rahilhastu@gmail.com>Zach Raines <raineszm@gmail.com>Sidhant Nagpal <sidhantnagpal97@gmail.com>Gagandeep Singh <singh.23@iitj.ac.in>Rishav Chakraborty <annonymousxyz@outlook.com>Malkhan Singh <malkhansinghrathaur@gmail.com>Joaquim Monserrat <qmonserrat@mailoo.org>Mayank Singh <mayank.singh081997@gmail.com>Rémy Léone <rleone@online.net>Maxence Mayrand <35958639+maxencemayrand@users.noreply.github.com>Nikoleta Glynatsi <GlynatsiNE@cardiff.ac.uk>helo9 <helo9@users.noreply.github.com>Ken Wakita <wakita@is.titech.ac.jp>Carl Sandrock <carl.sandrock@up.ac.za>Fredrik Eriksson <freeriks@student.chalmers.se>Ian Swire <oversizedpenguin@gmail.com>Bulat <daianovich@mail.ru>Ehren Metcalfe <ehren.m@gmail.com>Dmitry Savransky <dsavransky@gmail.com>Kiyohito Yamazaki <kyamaz@openql.org>Caley Finn <caleyreuben@gmail.com>Zhi-Qiang Zhou <zzq_890709@hotmail.com>Alexander Pozdneev <pozdneev@users.noreply.github.com>Wes Turner <50891+westurner@users.noreply.github.com>JMSS-Unknown <31131631+JMSS-Unknown@users.noreply.github.com>Arshdeep Singh <singh.arshdeep1999@gmail.com>cym1 <16437732+cym1@users.noreply.github.com>Stewart Wadsworth <stewart.wadsworth@gmail.com>Jared Lumpe <mjlumpe@gmail.com>Avi Shrivastava <shrivastavaavi123@gmail.com>ramvenkat98 <ramvenkat98@gmail.com>Bilal Ahmed <b.ahmed0918@gmail.com>Dimas Abreu Archanjo Dutra <dimasad@ufmg.br>Yatna Verma <yatnavermaa@gmail.com>S.Y. Lee <sylee957@gmail.com>Miro Hrončok <miro@hroncok.cz>Sudarshan Kamath <sudarshan.kamath97@gmail.com>Ayushman Koul <ayushmankoul4570@gmail.com>Robert Dougherty-Bliss <robert.w.bliss@gmail.com>Andrey Grozin <A.G.Grozin@inp.nsk.su>Bavish Kulur <bavishkulur@gmail.com>Arun Singh <arunsin997@gmail.com>sirnicolaf <43586954+sirnicolaf@users.noreply.github.com>Zachariah Etienne <zachetie@gmail.com>Prayush Dawda <35144226+iamprayush@users.noreply.github.com>2torus <boris.ettinger@gmail.com>Faisal Riyaz <faisalriyaz011@gmail.com>Martin Roelfs <u0114255@kuleuven.be>SirJohnFranklin <sirjfu@googlemail.com>Anthony Sottile <asottile@umich.edu>ViacheslavP <public.viacheslav@gmail.com>Safiya03 <safiyanesar@gmail.com>Alexander Dunlap <alexander.dunlap@gmail.com>Rohit Sharma <31184621+rohitx007@users.noreply.github.com>Jonathan Warner <warnerjon12@gmail.com>Mohit Balwani <mohitbalwani.ict17@gmail.com>Marduk Bolaños <mardukbp@mac.com>amsuhane <ayushsuhane99@iitkgp.ac.in>Matthias Geier <Matthias.Geier@gmail.com>klaasvanaarsen <44929042+klaasvanaarsen@users.noreply.github.com>Shubham Kumar Jha <skjha832@gmail.com>rationa-kunal <kunalgk1999@gmail.com>Animesh Sinha <animeshsinha1309@gmail.com>Gaurang Tandon <1gaurangtandon@gmail.com>Matthew Craven <clyring@users.noreply.github.com>Daniel Ingram <ingramds@appstate.edu>Jogi Miglani <jmig5776@gmail.com>Takumasa Nakamura <n.takumasa@gmail.com>Ritu Raj Singh <RituRajSingh878@gmail.com>Rajiv Ranjan Singh <rajivperfect007@gmail.com>Vera Lozhkina <veralozhkina@gmail.com>adhoc-king <46354827+adhoc-king@users.noreply.github.com>Mikel Rouco <mikel.mrm@gmail.com>Oscar Gustafsson <oscar.gustafsson@gmail.com>damianos <damianos@semmle.com>Supreet Agrawal <supreet11agrawal@gmail.com>shiksha11 <shiksharawat01@gmail.com>Martin Ueding <dev@martin-ueding.de>sharma-kunal <kunalsharma6914@gmail.com>Divyanshu Thakur <divyanshu@iiitmanipur.ac.in>Susumu Ishizuka <susumu.ishizuka@kii.com>Samnan Rahee <namanush.rsr.16@gmail.com>Fredrik Andersson <fredrik.andersson@fcc.chalmers.se>Bhavya Srivastava <bhavya17037@iiitd.ac.in>Alpesh Jamgade <alpeshjamgade21@gmail.com>Shubham Abhang <shubhamabhang77@gmail.com>Vishesh Mangla <manglavishesh64@gmail.com>Nicko van Someren <nicko@nicko.org>dandiez <47832466+dandiez@users.noreply.github.com>Frédéric Chapoton <fchapoton2@gmail.com>jhanwar <f2015463@pilani.bits-pilani.ac.in>Noumbissi valere Gille Geovan <noumbissivalere@gmail.com>Salmista-94 <alejandrogroso@hotmail.com>Shivani Kohli <shivanikohli.09@gmail.com>Parker Berry <parkereberry@gmail.com>Pragyan Mehrotra <pragyan18168@iiitd.ac.in>Nabanita Dash <dashnabanita@gmail.com>Gaetano Guerriero <x.guerriero@tin.it>Ankit Raj Pandey <pandeyan@grinnell.edu>Ritesh Kumar <ritesh99rakesh@gmail.com>kangzhiq <709563092@qq.com>Jun Lin <junlin0604@gmail.com>Petr Kungurtsev <corwinat@gmail.com>Anway De <anway1756@gmail.com>znxftw <vishnu2101@gmail.com>Denis Ivanenko <ivanenko@ucu.edu.ua>Orestis Vaggelis <orestisvaggelis@mail.com>Nikhil Maan <nikhilmaan22@gmail.com>Abhinav Anand <abhinav.anand2807@gmail.com>Qingsha Shi <googol.sqs@gmail.com>Juan Barbosa <js.barbosa10@uniandes.edu.co>Prionti Nasir <pdn3628@rit.edu>Bharat Raghunathan <bharatraghunthan9767@gmail.com>arooshiverma <av22@iitbbs.ac.in>Christoph Gohle <ctg@mpq.mpg.de>Charalampos Tsiagkalis <ctsiagkalis@uth.gr>Daniel Sears <highpost@users.noreply.github.com>Megan Ly <megan.ly@learnosity.com>Sean P. Cornelius <spcornelius@gmail.com>Erik R. Gomez <gomez@kth.se>Riccardo Magliocchetti <riccardo.magliocchetti@gmail.com>Henry Metlov <genrih.metlov@gmail.com>pekochun <hamburg_hamburger2000@yahoo.co.jp>Bendik Samseth <b.samseth@gmail.com>Vighnesh Shenoy <vighneshq@gmail.com>Versus Void <versusvoid@gmail.com>Denys Rybalka <rybalka.denis@gmail.com>Mark Dickinson <dickinsm@gmail.com>Rimi <rimibis@umich.edu>rimibis <33387803+rimibis@users.noreply.github.com>Steven Lee <stevenlee123@protonmail.com>Gilles Schintgen <gschintgen@hambier.lu>Abhi58 <abhijithbharadwaj58@gmail.com>Tomasz Pytel <tompytel@gmail.com>Aadit Kamat <aadit.k12@gmail.com>Samesh <samesh.lakhotia@gmail.com>Velibor Zeli <velibor@mech.kth.se>Gabriel Bernardino <gabriel.bernardino@upf.edu>Joseph Redfern <joseph@redfern.me>Evelyn King <evelyn.cameron.king@gmail.com>Miguel Marco <mmarco@unizar.es>David Hagen <david@drhagen.com>Hannah Kari <hannah.kari@marquette.edu>Soniya Nayak <soniyanayak51@gmail.com>Harsh Agarwal <hagarwal9200@gmail.com>Enric Florit <efz1005@gmail.com>Yogesh Mishra <ymishra013@gmail.com>Denis Rykov <rykovd@gmail.com>Ivan Tkachenko <me@ratijas.tk>Kenneth Emeka Odoh <kenneth.odoh@gmail.com>Stephan Seitz <stephan.seitz@fau.de>Yeshwanth N <yeshsurya@gmail.com>Oscar Gerardo Lazo Arjona <oscar.lazoarjona@physics.ox.ac.uk>Srinivasa Arun Yeragudipati <ysarun1999@gmail.com>Kirtan Mali <kirtanmali555@gmail.com>TitanSnow <sweeto@live.cn>Pengning Chao <8857165+PengningChao@users.noreply.github.com>Louis Abraham <louis.abraham@yahoo.fr>Morten Olsen Lysgaard <morten@lysgaard.no>Akash Nagaraj (akasnaga) <akasnaga@cisco.com>Akash Nagaraj <grassknoted@gmail.com>Lauren Glattly <laurenglattly@gmail.com>Hou-Rui <houruinus@gmail.com>George Korepanov <gkorepanov.gk@gmail.com>dranknight09 <cbhaavan@gmail.com>aditisingh2362 <aditisingh2362@gmail.com>Gina <Dr-G@users.noreply.github.com>gregmedlock <gmedlo@gmail.com>Georgios Giapitzakis Tzintanos <giorgosgiapis@mail.com>Eric Wieser <wieser.eric@gmail.com>Bradley Dowling <34559056+btdow@users.noreply.github.com>Maria Marginean <33810762+mmargin@users.noreply.github.com>Akash Agrawall <akash.wanted@gmail.com>jgulian <josephdgulian@gmail.com>Sourav Goyal <souravgl0@gmail.com>Zlatan Vasović <zlatanvasovic@gmail.com>Alex Meiburg <timeroot.alex@gmail.com>Smit Lunagariya <smitlunagariya.mat18@itbhu.ac.in>Naman Gera <namangera15@gmail.com>Julien Palard <julien@palard.fr>Dhruv Mendiratta <dhruvmendiratta6@gmail.com>erdOne <36414270+erdOne@users.noreply.github.com>risubaba <risubhjain1010@gmail.com>abhinav28071999 <41710346+abhinav28071999@users.noreply.github.com>Jisoo Song <jeesoo9595@snu.ac.kr>Jaime R <38530589+Jaime02@users.noreply.github.com>Vikrant Malik <vikrantmalik051@gmail.com>Hardik Saini <43683678+Guardianofgotham@users.noreply.github.com>Abhishek <uchiha@pop-os.localdomain>Johannes Hartung <joha2@gmx.net>Milan Jolly <milan.cs16@iitp.ac.in>faizan2700 <syedfaizan824@gmail.com>mohit <39158356+mohitacecode@users.noreply.github.com>Mohit Gupta <mohitgupta@gmail.com>Psycho-Pirate <prakharsaxena.civ18@iitbhu.ac.in>Chanakya-Ekbote <ca10@iitbbs.ac.in>Rashmi Shehana <rashmi.watagedara@syscolabs.com>Jonty16117 <jonty@DESKTOP-J1O6ANP.localdomain>Anubhav Gupta <anubhav.gupta.cse19@itbhu.ac.in>Michal Grňo <m93a.cz@gmail.com>vezeli <37907135+vezeli@users.noreply.github.com>Tim Gates <tim.gates@iress.com>Sandeep Murthy <smurthy@protonmail.ch>Neil <mistersheik@gmail.com>V1krant <46847915+V1krant@users.noreply.github.com>alejandro <amartinhernan@gmail.com>Riyan Dhiman <Riyandhiman14@gmail.com>sbt4104 <sthorat661@gmail.com>Seth Troisi <sethtroisi@google.com>Bhaskar Gupta <guptabhanu1999@gmail.com>Smit Gajjar <smitgajjar.gs@gmail.com>rbl <rlee@grove.co>Ilya Pchelintsev <ilya.pchelintsev@outlook.com>Omar Wagih <o.wagih.ow@gmail.com>prshnt19 <prashant.rawat216@gmail.com>Johan Guzman <jguzm022@ucr.edu>Vasileios Kalos <kalosbasileios@gmail.com>BasileiosKal <61801875+BasileiosKal@users.noreply.github.com>Shubham Thorat <37049710+sbt4104@users.noreply.github.com>Arpan Chattopadhyay <f20180319@pilani.bits-pilani.ac.in>Ashutosh Hathidara <ashutoshhathidara98@gmail.com>Moses Paul R <iammosespaulr@gmail.com>Saanidhya vats <saanidhyavats@gmail.com>tnzl <you@example.com>Vatsal Srivastava <alstav.trivas.sava@gmail.com>Jean-Luc Herren <jlh@gmx.ch>Dhruv Kothari <dhruvkothari22@gmail.com>seadavis <45022599+seadavis@users.noreply.github.com>kamimura <kamimura@live.jp>slacker404 <pchantza@gmail.com>Jaime Resano <gemailpersonal02@gmail.com>Ebrahim Byagowi <ebrahim@gnu.org>wuyudi <wuyudi119@163.com>Akira Kyle <ak@akirakyle.com>Calvin Jay Ross <calvinjayross@gmail.com>Martin Thoma <info@martin-thoma.de>Thomas A Caswell <tcaswell@gmail.com>Lagaras Stelios <stel.lag@hotmail.com>Jerry James <loganjerry@gmail.com>Jan Kruse <janckruse@t-online.de>Nathan Taylor <pecan.pine@gmail.com>Vaishnav Damani <vaishnavdamani3496@gmail.com>Mohit Shah <mohitshah3111999@gmail.com>Mathias Louboutin <mathias.louboutin@gmail.com>Marijan Smetko <marijansmetko123@gmail.com>Dave Witte Morris <Dave.Morris@uleth.ca>soumi7 <soumibardhan10@gmail.com>Zhongshi <zj495@nyu.edu>Wes Galbraith <galbwe92@gmail.com>KaustubhDamania <kaustubh.damania@gmail.com>w495 <w495@yandex-team.ru>Akhil Rajput <akh1lrjput@gmail.com>Markus Mohrhard <markus.mohrhard@googlemail.com>Benjamin Wolba <mail@benjaminwolba.com>彭于斌 <1931127624@qq.com>Rudr Tiwari <rudrtiwari@gmail.com>Aaryan Dewan <aaryandewan@yahoo.com>Benedikt Placke <benedikt.placke@outlook.com>Sneha Goddu <s.goddu@wustl.edu>goddus <39923708+goddus@users.noreply.github.com>Shivang Dubey <shivangdubey8@gmail.com>Michael Greminger <michael.greminger@gmail.com>Peter Cock <p.j.a.cock@googlemail.com>Willem Melching <willem.melching@gmail.com>Elias Basler <e.e.basler@protonmail.com>Brandon David <brandon.david@zoho.com>Abhay_Dhiman <abhaysdhimans@gmail.com>Tasha Kim <jae_young_kim@brown.edu>Ayush Malik <ayushmalik779@gmail.com>Devesh Sawant <devesh47cool@gmail.com>Wolfgang Stöcher <wolfgang@stoecher.com>Sudeep Sidhu <sudeepmanilsidhu@gmail.com>foice <foice.news@gmail.com>Ben Payne <ben.is.located@gmail.com>Muskan Kumar <31043527+muskanvk@users.noreply.github.com>noam simcha finkelstein <noam.finkelstein@protonmail.com>Garrett Folbe <gmfolbe@yahoo.com>Islam Mansour <is3mansour@gmail.com>Sayandip Halder <sayandiph4@gmail.com>Shubham Agrawal <shubham.ag6845@gmail.com>numbermaniac <5206120+numbermaniac@users.noreply.github.com>Sakirul Alam <binarysakir@gmail.com>Mohammed Bilal <r.mohammedbilal@gmail.com>Chris du Plessis <christopherjonduplessis@gmail.com>Coder-RG <rgoel1999@gmail.com>Ansh Mishra <anshmishra471@gmail.com>Alex Malins <github@alexmalins.com>Lorenzo Contento <lorenzo.contento@gmail.com>Naveen Sai <naveensaisreenivas@gmail.com>Shital Mule <shitalmule04@gmail.com>Amanda Dsouza <meezamanda@yahoo.com>Nijso Beishuizen <nijso@koolmees.numerically-related.com>Harry Zheng <harry@harryzheng.com>Felix Yan <felixonmars@archlinux.org>Constantin Mateescu <costica1234@me.com>Eva Tiwari <eva.tiwari@gmail.com>Aditya Kumar Sinha <adityakumar113141@gmail.com>Soumi Bardhan <51290447+Soumi7@users.noreply.github.com>Kaustubh Chaudhari <ckaustubhm06@gmail.com>Kristian Brünn <hello@kristianbrunn.com>Neel Gorasiya <mgorasiya1974@gmail.com>Akshat Sood <68052998+akshatsood2249@users.noreply.github.com>Jose M. Gomez <chemoki@gmail.com>Stefan Petrea <stefan@garage-coding.com>Praveen Sahu <povinsahu@gmail.com>Mark Bell <mark00bell@googlemail.com>AlexCQY <alex_chua@u.nus.edu>Fabian Froehlich <fabian@schaluck.com>Nikhil Gopalam <gopalamn@umich.edu>Kartik Sethi <kartiks31416@gmail.com>Muhammed Abdul Quadir Owais <quadirowais200@gmail.com>Harshit Yadav <harshityadav2k@gmail.com>Sidharth Mundhra <sidharthmundhra16@gmail.com>Suryam Arnav Kalra <suryamkalra35@gmail.com>Prince Gupta <codemastercpp@gmail.com>Kunal Singh <ksingh19136@gmail.com>Mayank Raj <mayank_1901cs35@iitp.ac.in>Achal Jain <2achaljain@gmail.com>Mario Maio <mario.maio@aruba.it>Aaron Stiff <69512633+AaronStiff@users.noreply.github.com>Wyatt Peak <wyattpeak@gmail.com>Bhaskar Joshi <bhaskar.joshi@research.iiit.ac.in>Aditya Jindal <jaditya8889@gmail.com>Vaibhav Bhat <vaibhav.bhat2097@gmail.com>Priyansh Rathi <techiepriyansh@gmail.com>Saket Kumar Singh <saketkumar1202@gmail.com>Yukai Chou <muzimuzhi@gmail.com>Qijia Liu <liumeo@pku.edu.cn>Paul Mandel <paulmandel@google.com>Nisarg Chaudhari <54911392+Nisarg-Chaudhari@users.noreply.github.com>Dominik Stańczak <stanczakdominik@gmail.com>Rodrigo Luger <rodluger@gmail.com>Marco Antônio Habitzreuter <mahabitzreuter@gmail.com>Ayush Bisht <bisht.ayush2001@gmail.com>Akshansh Bhatt <akshansh@tuta.io>Brandon T. Willard <brandonwillard@users.noreply.github.com>Thomas Aarholt <thomasaarholt@gmail.com>Hiren Chalodiya <hirenchalodiya99@gmail.com>Roland Dixon <rols121@gmail.com>dimasvq <dimas.vq.2020@bristol.ac.uk>Sagar231 <sagarfeb298@gmail.com>Michael Chu <michael02chu@gmail.com>Abby Ng <abigailjng@gmail.com>Angad Sandhu <55819847+angadsinghsandhu@users.noreply.github.com>Alexander Cockburn <alexander_cockburn12@hotmail.com>Yaser AlOsh <yaseralosh@outlook.com>Davide Sandonà <sandona.davide@gmail.com>Jonathan Gutow <gutow@uwosh.edu>Nihir Agarwal <f20180701@pilani.bits-pilani.ac.in>Lee Johnston <lee.johnston.100@gmail.com>Zach Carmichael <20629897+craymichael@users.noreply.github.com>Vijairam Ganesh Moorthy <vijairamg@gmail.com>Hanspeter Schmid <hanspeter.schmid@fhnw.ch>Ben Oostendorp <oostben@umich.edu>Nikita <nikita.student.cse19@itbhu.ac.in>Aman <amanmourya295@gmail.com>Shashank KS <shashankks0987@gmail.com>Aman Sharma <amansharma110603@gmail.com>Anup Parikh <parikhanupk@gmail.com>Lucy Mountain <lucymountain1@icloud.com>Miguel Torres Costa <miguelptcosta1995@gmail.com>Rikard Nordgren <rikard.nordgren@farmaci.uu.se>Arun sanganal <74652697+ArunSanganal@users.noreply.github.com>Kamlesh Joshi <72374645+kamleshjoshi8102@users.noreply.github.com>Joseph Rance <56409230+Joseph-Rance@users.noreply.github.com>Huangduirong <huangduirong@huawei.com>Nils Schulte <47043622+Schnilz@users.noreply.github.com>Matt Bogosian <matt@bogosian.net>Elisha Hollander <just4now666666@gmail.com>Aditya Ravuri <infprobscix@gmail.com>Mamidi Ratna Praneeth <praneethratna@gmail.com>Jeffrey Ryan <jeffaryan7@gmail.com>Jonathan Daniel <36337649+jond01@users.noreply.github.com>Robin Richard <raisin@ecomail.fr>Gautam Menghani <gum3ng@protonmail.com>Remco de Boer <29308176+redeboer@users.noreply.github.com>Sebastian East <sebastianeast@ymail.com>Evani Balasubramanyam <balasubramanyam.evani@gmail.com>Rahil Parikh <r.parikh@somaiya.edu>Jason Ross <jasonross1024@gmail.com>Joannah Nanjekye <joannah.nanjekye@ibm.com>Ayush Kumar <ayushk7102@gmail.com>Kshitij <kshitijparwani.mat18@itbhu.ac.in>Daniel Hyams <dhyams@gmail.com>alijosephine <alijosephine@gmail.com>Matthias Köppe <mkoeppe@math.ucdavis.edu>mohajain <mohajain99@gmail.com>Anibal M. Medina-Mardones <ammedmar@gmail.com>Travis Ens <ens.travis@gmail.com>Evgenia Karunus <lakesare@gmail.com>Risiraj Dey <risirajdey@gmail.com>lastcodestanding <rohang71604@gmail.com>Andrey Lekar <andrey_lekar@adoriasoft.com>Abbas Mohammed <42001049+iam-abbas@users.noreply.github.com>Anutosh Bhat <andersonbhat491@gmail.com>Steve Kieffer <sk@skieffer.info>Paul Spiering <paul@spiering.org>Pieter Gijsbers <p.gijsbers@tue.nl>Wang Ran (汪然) <wangr@smail.nju.edu.cn>naelsondouglas <naelson17@gmail.com>Aman Thakur <thakuraman22july@gmail.com>S. Hanko <suzy.hanko@gmail.com>Dennis Sweeney <sweeney.427@osu.edu>Gurpartap Singh <dhaliwal.gurpartap@gmail.com>Hampus Malmberg <hampus.malmberg88@gmail.com>scimax <max.kellermeier@hotmail.de>Nikhil Date <nikhil.s.date@gmail.com>Kuldeep Borkar Jr <kuldeepborkarjr765@gmail.com>AkuBrain <76952313+Franck2111@users.noreply.github.com>Leo Battle <leowbattle@gmail.com>Advait Pote <apote2050@gmail.com>Anurag Bhat <bhat.1@iitj.ac.in>Jeremy Monat <jemonat@calalum.org>Diane Tchuindjo <dtchuindjo@gmail.com>Tom Fryers <61272761+TomFryers@users.noreply.github.com>Zouhair <zouhair.mahboubi@gmail.com>zzj <29055749+zjzh@users.noreply.github.com>shubhayu09 <guptashubhayu601@gmail.com>Siddhant Jain <siddhantashoknagar@gmail.com>Tirthankar Mazumder <63574588+wermos@users.noreply.github.com>Sumit Kumar <mr.sumitkrr@gmail.com>Shivam Sagar <technoshivam12@gmail.com>Gaurav Jain <gjain369@gmail.com>Andrii Oriekhov <andriyorehov@gmail.com>Luis Talavera <luisfertalavera15@gmail.com>Arie Bovenberg <a.c.bovenberg@gmail.com>Carson McManus <carson.mcmanus1@gmail.com>Jack Schmidt <1107865+jackschmidt@users.noreply.github.com>Riley Britten <nrb1324@hotmail.com>Georges Khaznadar <georgesk@debian.org>Donald Wilson <donwilson1029@gmail.com>Timo Stienstra <timostienstra00@gmail.com>dispasha <dispasha@users.noreply.github.com>Saksham Alok <sakshamalok13@gmail.com>Varenyam Bhardwaj <varenyambhardwaj123@gmail.com>oittaa <8972248+oittaa@users.noreply.github.com>Omkaar <79257339+Pysics@users.noreply.github.com>Islem BOUZENIA <fi_bouzenia@esi.dz>extraymond <extraymond@gmail.com>Alexander Behrens <alex.git@gmx.net>user202729 <25191436+user202729@users.noreply.github.com>Pieter Eendebak <pieter.eendebak@gmail.com>Zaz Brown <zazbrown@zazbrown.com>ritikBhandari <ritikbhandari68@gmail.com>viocha <66580331+viocha@users.noreply.github.com>Arthur Ryman <arthur.ryman@gmail.com>Xiang Wu <hsiangwu@fb.com>tttc3 <T.Coxon2@lboro.ac.uk>Seth Poulsen <poulsenseth@yahoo.com>cocolato <haiizhu@outlook.com>Anton Golovanov <agolovanov256@gmail.com>Gareth Ma <grhkm21@gmail.com>Clément M.T. Robert <cr52@protonmail.com>Glenn Horton-Smith <glenn.hortonsmith@gmail.com>Karan <grgkaran03@gmail.com>Stefan Behnle <84378403+behnle@users.noreply.github.com>Shreyash Mishra <72146041+Shreyash-cyber@users.noreply.github.com>Arthur Milchior <arthur@milchior.fr>NotWearingPants <26556598+NotWearingPants@users.noreply.github.com>Ishan Pandhare <ishan9096137017@gmail.com>Carlos García Montoro <TrilceAC@gmail.com>Parcly Taxel <reddeloostw@gmail.com>Saicharan <saicharanhahaha@gmail.com>Kunal Sheth <kunal@kunalsheth.info>Biswadeep Purkayastha <98874428+metabiswadeep@users.noreply.github.com>Jyn Spring 琴春 <me@vx.st>Phil LeMaitre <phil_lemaitre@live.ca>Chris Kerr <chris.kerr@mykolab.ch>José Senart <jose.senart@gmail.com>Uwe L. Korn <uwelk@xhochy.com>ForeverHaibara <69423537+ForeverHaibara@users.noreply.github.com>Yves Tumushimire <yvestumushimire@gmail.com>wookie184 <wookie1840@gmail.com>Costor <pcs2009@web.de>Klaus Rettinghaus <klaus.rettinghaus@enote.com>Sam Brockie <sambrockie@icloud.com>Abhishek Patidar <1e9abhi1e10@gmail.com>Eric Demer <demer@mailbox.org>Pontus von Brömssen <pontus.vonbromssen+github@gmail.com>Victor Immanuel <chrollolucilfer1402@gmail.com>Evandro Bernardes <evbernardes@gmail.com>Michele Ceccacci <michelececcacci1@gmail.com>Ayush Aryan <ayush.aryan71@gmail.com>Kishore Gopalakrishnan <kishore96@gmail.com>Jan-Philipp Hoffmann <sonntagsgesicht@icloud.com>Daiki Takahashi <haru.td@gmail.com>Sayan Mitra <ee18b156@smail.iitm.ac.in>Aman Kumar Shukla <theprofessionalaman@gmail.com>Zoufiné Lauer-Baré <raszoufine@gmail.com>Charles Harris <erdos4d@gmail.com>Tejaswini Sanapathi <sastejaswini2002@gmail.com>Devansh <be19b002@smail.iitm.ac.in>Aaron Gokaslan <aaronGokaslan@gmail.com>Daan Koning (he/him) <daanolivierkoning@gmail.com>Steven Burns <royalstream@hotmail.com>Jay Patankar <patankarjays@gmail.com>Vivek Soni <sonisheela1977@gmail.com>Le Cong Minh Hieu <hieu.lecongminh@gmail.com>Sam Ritchie <sam@mentat.org>Maciej Skórski <maciej.skorski@gmail.com>Tilo Reneau-Cardoso <tiloreneau@gmail.com>Laurence Warne <laurencewarne@gmail.com>Lukas Molleman <Lukas.Molleman@gmail.com>Konstantinos Riganas <kostasriganas24@gmail.com>Grace Su <grace.duansu@gmail.com>Pedro Rosa <pedro_sxbr@usp.br>Abhinav Cillanki <abhinavcillanki@kgpian.iitkgp.ac.in>Baiyuan Qiu <1061688677@qq.com>Liwei Cai <cai.lw123@gmail.com>Daniel Weindl <daniel.weindl@helmholtz-muenchen.de>Isidora Araya <iarayaday@gmail.com>Seb Tiburzio <sebtiburzio@gmail.com>Victory Omole <vtomole2@gmail.com>Abhishek Chaudhary <ac5003@columbia.edu>Alexander Zhura <nice.zhura@list.ru>Shuai Zhou <shuaivzhou@berkeley.edu>Martin Manns <mmanns@gmx.net>John Möller <john.moller@outlook.com>zzc <1378113190@qq.com>Pablo Galindo Salgado <pablogsal@gmail.com>Johannes Kasimir <johannes.kasimir@math.lu.se>Theodore Dias <theodore.dias@hotmail.co.uk>Kaustubh <90597818+kaustubh-765@users.noreply.github.com>Idan Pazi <idan.kp@gmail.com>Bobby Palmer <bobbyp@umich.edu>Saikat Das <saikatdchhe@gmail.com>Suman mondal <smondal.qwerty@gmail.com>Taylan Sahin <info@taylansahin.net>Fabio Luporini <fabio@devitocodes.com>Oriel Malihi <orielmalihi1@gmail.com>Geetika Vadali <geetika.vadali4@gmail.com>Matthias Rettl <matthias.rettl@stud.unileoben.ac.at>Mikhail Remnev <maremnev@gmail.com>philwillnyc <56197213+philwillnyc@users.noreply.github.com>Raphael Lehner <raphael.lehner@gmail.com>Harry Mountain <harrymountain1@icloud.com>Bhavik Sachdev <b.sachdev1904@gmail.com>袁野 (Yuan Ye) <yuanyelele@tutanota.com>fazledyn-or <ataf@openrefactory.com>mohammedouahman <simofun85@gmail.com>K. Kraus <laqueray@googlemail.com>Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com>platypus <platypus.computerchip@gmail.com>codecruisader <nnisarg55@gmail.com>James Whitehead <whiteheadj@gmail.com>atharvParlikar <atharvparlikar@gmail.com>Ivan Petukhov <satels@gmail.com>Augusto Borges <borges.augustoar@gmail.com>Han Wei Ang <ang.h.w@u.nus.edu>Congxu Yang <u7189828@anu.edu.au>Saicharan <62512681+saicharan2804@users.noreply.github.com>Arnab Nandi <arnabnandi2002@gmail.com>Harrison Oates <48871176+HarrisonOates@users.noreply.github.com>Corey Cerovsek <corey@cerovsek.com>Harsh Kasat <hkasat@waymore.io>omahs <73983677+omahs@users.noreply.github.com>Pascal Gitz <pascal.gitz@hotmail.ch>Ravindu-Hirimuthugoda <ravindu.18@cse.mrt.ac.lk>Sophia Pustova <tripplezzed@gmail.com>George Pittock <gpittock4@gmail.com>Warren Jacinto <warrenjacinto@gmail.com>Sachin Singh <sachinishu02@gmail.com>Zedmat <104870914+harshkasat@users.noreply.github.com>Soumendra Ganguly <soumendraganguly@gmail.com>Samith Karunathilake <55777141+samithkavishke@users.noreply.github.com>Viraj Vekaria <virajv5593@gmail.com>Shishir Kushwaha <kushwahashishir1112@gmail.com>Ankit Kumar Singh <ankitdiswar10@gmail.com>Abhishek Kumar <abhishek.nitdelhi@gmail.com>Mohak Malviya <mohakmalviya2000@gmail.com>Matthias Liesenfeld <116307294+maliesen@users.noreply.github.com>dodo <palumbododo@gmail.com>Mohamed Rezk <mohrizq895@gmail.com>Tommaso Vaccari <05-gesto-follemente@icloud.com>Alexis Schotte <alexis.schotte@gmail.com>Lauren Yim <31467609+cherryblossom000@users.noreply.github.com>Prey Patel <patel.prey@iitgn.ac.in>Riccardo Di Girolamo <riccardodigirolamo01@gmail.com>Abhishek kumar <kumar325571@gmail.com>Sam Lubelsky <sammy56lt@gmail.com>Henrique Soares <henrique.c.soares@tecnico.ulisboa.pt>Vladimir Sereda <voffch@gmail.com>Hwayeon Kang <hwayeonniii@gmail.com>Raj Sapale <raj4sapale4@gmail.com>Gerald Teschl <gerald.teschl@univie.ac.at>Richard Samuel <98638849+samuelard7@users.noreply.github.com>HeeJae Chang <hechang@microsoft.com>Nick Harder <nharder@umich.edu>Ethan DeGuire <ethandeguire@gmail.com>Lorenz Winkler <lorenz.winkler@tuwien.ac.at>Richard Rodenbusch <rrodenbusch@gmail.com>Zhenxu Zhu <xzdlj@outlook.com>Mark van Gelder <m.j.vangelder@student.tudelft.nl>Mark van Gelder <mvgmvgmvg@live.com>Ishan Pandhare <91841626+Ishanned@users.noreply.github.com>James A. Preiss <jamesalanpreiss@gmail.com>Emile Fourcini <emile.fourcin1@gmail.com>Alberto Jiménez Ruiz <Alberto.Jimenez@uclm.es>João Bravo <joaocgbravo@tecnico.ulisboa.pt>Dean Price <dean1357price1357@gmail.com>Edward Z. Yang <ezyang@mit.edu>James Titus <titusjames299@gmail.com>Zhuoyuan Li <zy.li@stu.pku.edu.cn>Hugo Kerstens <hugo@kerstens.me>Jan Jancar <johny@neuromancer.sk>Andrew Mosson <amosson@yahoo.com>Marek Madejski <marekmadejski@yandex.com>Gonzalo Tornaría <tornaria@cmat.edu.uy>Peter Stahlecker <peter.stahlecker@gmail.com>Jean-François B <2589111+jfbu@users.noreply.github.com>Zexuan Zhou (Bruce) <zzx498636727@gmail.com>George Frolov <gosha@fro.lv>Corbet Elkins <corbet286@gmail.com>Håkon Kvernmoen <haakon.kvernmoen@gmail.com>Muhammad Maaz <mmaaz6004@gmail.com>Shishir Kushwaha <138311586+shishir-11@users.noreply.github.com>Matt Wang <mattwang44@gmail.com>bharatAmeria <21001019007@jcboseust.ac.in>Amir Ebrahimi <github@aebrahimi.com>Steven Esquea <steven.esquea@irreverente.net>Rishabh Kamboj <111004091+VectorNd@users.noreply.github.com>Aasim Ali <aasim250205@gmail.com>Ivan A. Melnikov <iv@altlinux.org>Borek Saheli <boreksaheli@gmail.com>Guido Roncarolo <guido.roncarolo@gmail.com>Quek Zi Yao <ziyaoqzy2001@gmail.com>Roelof Rietbroek <r.rietbroek@utwente.nl>MostafaGalal1 <mostafag649.mg@gmail.com>Au Huishan <huishan_au@outlook.com>Kris Katterjohn <katterjohn@gmail.com>Shiyao Guo <mivikq@gmail.com>Rushabh Mehta <mehtarushabh2005@gmail.com>Temiloluwa Yusuf ytemiloluwa@gmail.com ytemiloluwa <ytemiloluwa@gmail.com>Davi Laerte <davilae011@gmail.com>Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com>Harshit Gupta <harshithigh2001@gmail.com>Praveen Perumal <ppraveen98841@gmail.com>Kevin McWhirter <klmcw@yahoo.com>Prayag V <v.prayag2005@gmail.com>Lucas Kletzander <lucas.kletzander@gmail.com>Pratyksh Gupta <pratykshgupta9999@gmail.com>Leonardo Mangani <leomangani4@gmail.com>Karan Anand <anandkarancompsci@gmail.com>Gagan Mishra <simonsimple305@gmail.com>Krishnav Bajoria <bajoriakrishnav@gmail.com>Matt Ord <matthew.ord1@gmail.com>Jatin Bhardwaj <bhardwajjatin093@gmail.com>Prashant Tandon <tandonprashant101@gmail.com>Paramjit Singh <paramjit1071@gmail.com>João Rodrigues <abcjoao@hotmail.com>Alejandro García Prada <114813960+AlexGarciaPrada@users.noreply.github.com>Matthew Treinish <mtreinish@kortar.org>Clayton Rabideau <claytonrabideau@gmail.com>Victoria Koval <bictoriakoval16@gmail.com>Voaides Negustor Robert <134785947+voaidesr@users.noreply.github.com>Ovsk Mendov <bbb23exposed@gmail.com>David Brooks <dave@bcs.co.nz>Nicholas Laustrup <124007393+nicklaustrup@users.noreply.github.com>Harikrishna Srinivasan <harikrishnasri3@gmail.com>Mathis Cros <mathis.cros@telecom-paris.fr>Arnav Mummineni <45217840+RCoder01@users.noreply.github.com>Thangaraju Sibiraj <85477603+t-sibiraj@users.noreply.github.com>KJaybhaye <krushnajaybhaye01@gmail.com>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153Copyright (c) 2006-2023 SymPy Development Team
All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
a. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. b. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. c. Neither the name of SymPy nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSEARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FORANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICTLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAYOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCHDAMAGE.
--------------------------------------------------------------------------------
Patches that were taken from the Diofant project (https://github.com/diofant/diofant)are licensed as:
Copyright (c) 2006-2018 SymPy Development Team, 2013-2023 Sergey B Kirpichev
All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
a. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. b. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. c. Neither the name of Diofant or SymPy nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSEARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FORANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICTLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAYOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCHDAMAGE.
--------------------------------------------------------------------------------
Submodules taken from the multipledispatch project (https://github.com/mrocklin/multipledispatch)are licensed as:
Copyright (c) 2014 Matthew Rocklin
All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
a. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. b. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. c. Neither the name of multipledispatch nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSEARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FORANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICTLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAYOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCHDAMAGE.
--------------------------------------------------------------------------------
The files under the directory sympy/parsing/autolev/tests/pydy-example-repoare directly copied from PyDy project and are licensed as:
Copyright (c) 2009-2023, PyDy AuthorsAll rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.* Neither the name of this project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ANDANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL PYDY AUTHORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCEOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IFADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
The files under the directory sympy/parsing/latex are directly copied from latex2sympy project and are licensed as:
Copyright 2016, latex2sympy
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.12isympysympy12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import sympy.physics.mechanics as _meimport sympy as _smimport math as mimport numpy as _np
g, lb, w, h = _sm.symbols('g lb w h', real=True)theta, phi, omega, alpha = _me.dynamicsymbols('theta phi omega alpha')theta_d, phi_d, omega_d, alpha_d = _me.dynamicsymbols('theta_ phi_ omega_ alpha_', 1)theta_dd, phi_dd = _me.dynamicsymbols('theta_ phi_', 2)frame_n = _me.ReferenceFrame('n')body_a_cm = _me.Point('a_cm')body_a_cm.set_vel(frame_n, 0)body_a_f = _me.ReferenceFrame('a_f')body_a = _me.RigidBody('a', body_a_cm, body_a_f, _sm.symbols('m'), (_me.outer(body_a_f.x,body_a_f.x),body_a_cm))body_b_cm = _me.Point('b_cm')body_b_cm.set_vel(frame_n, 0)body_b_f = _me.ReferenceFrame('b_f')body_b = _me.RigidBody('b', body_b_cm, body_b_f, _sm.symbols('m'), (_me.outer(body_b_f.x,body_b_f.x),body_b_cm))body_a_f.orient(frame_n, 'Axis', [theta, frame_n.y])body_b_f.orient(body_a_f, 'Axis', [phi, body_a_f.z])point_o = _me.Point('o')la = (lb-h/2)/2body_a_cm.set_pos(point_o, la*body_a_f.z)body_b_cm.set_pos(point_o, lb*body_a_f.z)body_a_f.set_ang_vel(frame_n, omega*frame_n.y)body_b_f.set_ang_vel(body_a_f, alpha*body_a_f.z)point_o.set_vel(frame_n, 0)body_a_cm.v2pt_theory(point_o,frame_n,body_a_f)body_b_cm.v2pt_theory(point_o,frame_n,body_a_f)ma = _sm.symbols('ma')body_a.mass = mamb = _sm.symbols('mb')body_b.mass = mbiaxx = 1/12*ma*(2*la)**2iayy = iaxxiazz = 0ibxx = 1/12*mb*h**2ibyy = 1/12*mb*(w**2+h**2)ibzz = 1/12*mb*w**2body_a.inertia = (_me.inertia(body_a_f, iaxx, iayy, iazz, 0, 0, 0), body_a_cm)body_b.inertia = (_me.inertia(body_b_f, ibxx, ibyy, ibzz, 0, 0, 0), body_b_cm)force_a = body_a.mass*(g*frame_n.z)force_b = body_b.mass*(g*frame_n.z)kd_eqs = [theta_d - omega, phi_d - alpha]forceList = [(body_a.masscenter,body_a.mass*(g*frame_n.z)), (body_b.masscenter,body_b.mass*(g*frame_n.z))]kane = _me.KanesMethod(frame_n, q_ind=[theta,phi], u_ind=[omega, alpha], kd_eqs = kd_eqs)fr, frstar = kane.kanes_equations([body_a, body_b], forceList)zero = fr+frstarfrom pydy.system import Systemsys = System(kane, constants = {g:9.81, lb:0.2, w:0.2, h:0.1, ma:0.01, mb:0.1},specifieds={},initial_conditions={theta:_np.deg2rad(90), phi:_np.deg2rad(0.5), omega:0, alpha:0},times = _np.linspace(0.0, 10, 10/0.02))
y=sys.integrate()12345678910111213141516171819202122232425MOTIONVARIABLES' Q{2}', U{2}'CONSTANTS L,M,GNEWTONIAN NFRAMES A,BSIMPROT(N, A, 3, Q1)SIMPROT(N, B, 3, Q2)W_A_N>=U1*N3>W_B_N>=U2*N3>POINT OPARTICLES P,RP_O_P> = L*A1>P_P_R> = L*B1>V_O_N> = 0>V2PTS(N, A, O, P)V2PTS(N, B, P, R)MASS P=M, R=MQ1' = U1Q2' = U2GRAVITY(G*N1>)ZERO = FR() + FRSTAR()KANE()INPUT M=1,G=9.81,L=1INPUT Q1=.1,Q2=.2,U1=0,U2=0INPUT TFINAL=10, INTEGSTP=.01CODE DYNAMICS() some_filename.c123456789101112131415161718192021222324252627282930313233343536373839import sympy.physics.mechanics as _meimport sympy as _smimport math as mimport numpy as _np
q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)l, m, g = _sm.symbols('l m g', real=True)frame_n = _me.ReferenceFrame('n')frame_a = _me.ReferenceFrame('a')frame_b = _me.ReferenceFrame('b')frame_a.orient(frame_n, 'Axis', [q1, frame_n.z])frame_b.orient(frame_n, 'Axis', [q2, frame_n.z])frame_a.set_ang_vel(frame_n, u1*frame_n.z)frame_b.set_ang_vel(frame_n, u2*frame_n.z)point_o = _me.Point('o')particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m'))particle_p.point.set_pos(point_o, l*frame_a.x)particle_r.point.set_pos(particle_p.point, l*frame_b.x)point_o.set_vel(frame_n, 0)particle_p.point.v2pt_theory(point_o,frame_n,frame_a)particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b)particle_p.mass = mparticle_r.mass = mforce_p = particle_p.mass*(g*frame_n.x)force_r = particle_r.mass*(g*frame_n.x)kd_eqs = [q1_d - u1, q2_d - u2]forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))]kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs)fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList)zero = fr+frstarfrom pydy.system import Systemsys = System(kane, constants = {l:1, m:1, g:9.81},specifieds={},initial_conditions={q1:.1, q2:.2, u1:0, u2:0},times = _np.linspace(0.0, 10, 10/.01))
y=sys.integrate()12345678910111213141516171819CONSTANTS M,K,B,GMOTIONVARIABLES' POSITION',SPEED'VARIABLES OFORCE = O*SIN(T)NEWTONIAN CEILINGPOINTS ORIGINV_ORIGIN_CEILING> = 0>PARTICLES BLOCKP_ORIGIN_BLOCK> = POSITION*CEILING1>MASS BLOCK=MV_BLOCK_CEILING>=SPEED*CEILING1>POSITION' = SPEEDFORCE_MAGNITUDE = M*G-K*POSITION-B*SPEED+FORCEFORCE_BLOCK>=EXPLICIT(FORCE_MAGNITUDE*CEILING1>)ZERO = FR() + FRSTAR()KANE()INPUT TFINAL=10.0, INTEGSTP=0.01INPUT M=1.0, K=1.0, B=0.2, G=9.8, POSITION=0.1, SPEED=-1.0, O=2CODE DYNAMICS() dummy_file.c12345678910111213141516171819202122232425262728293031import sympy.physics.mechanics as _meimport sympy as _smimport math as mimport numpy as _np
m, k, b, g = _sm.symbols('m k b g', real=True)position, speed = _me.dynamicsymbols('position speed')position_d, speed_d = _me.dynamicsymbols('position_ speed_', 1)o = _me.dynamicsymbols('o')force = o*_sm.sin(_me.dynamicsymbols._t)frame_ceiling = _me.ReferenceFrame('ceiling')point_origin = _me.Point('origin')point_origin.set_vel(frame_ceiling, 0)particle_block = _me.Particle('block', _me.Point('block_pt'), _sm.Symbol('m'))particle_block.point.set_pos(point_origin, position*frame_ceiling.x)particle_block.mass = mparticle_block.point.set_vel(frame_ceiling, speed*frame_ceiling.x)force_magnitude = m*g-k*position-b*speed+forceforce_block = (force_magnitude*frame_ceiling.x).subs({position_d:speed})kd_eqs = [position_d - speed]forceList = [(particle_block.point,(force_magnitude*frame_ceiling.x).subs({position_d:speed}))]kane = _me.KanesMethod(frame_ceiling, q_ind=[position], u_ind=[speed], kd_eqs = kd_eqs)fr, frstar = kane.kanes_equations([particle_block], forceList)zero = fr+frstarfrom pydy.system import Systemsys = System(kane, constants = {m:1.0, k:1.0, b:0.2, g:9.8},specifieds={_me.dynamicsymbols('t'):lambda x, t: t, o:2},initial_conditions={position:0.1, speed:-1*1.0},times = _np.linspace(0.0, 10.0, 10.0/0.01))
y=sys.integrate()1234567891011121314151617181920MOTIONVARIABLES' Q{2}''CONSTANTS L,M,GNEWTONIAN NPOINT PNV_PN_N> = 0>THETA1 = ATAN(Q2/Q1)FRAMES ASIMPROT(N, A, 3, THETA1)PARTICLES PP_PN_P> = Q1*N1>+Q2*N2>MASS P=MV_P_N>=DT(P_P_PN>, N)F_V = DOT(EXPRESS(V_P_N>,A), A1>)GRAVITY(G*N1>)DEPENDENT[1] = F_VCONSTRAIN(DEPENDENT[Q1'])ZERO=FR()+FRSTAR()F_C = MAG(P_P_PN>)-LCONFIG[1]=F_CZERO[2]=CONFIG[1]123456789101112131415161718192021222324252627282930313233343536import sympy.physics.mechanics as _meimport sympy as _smimport math as mimport numpy as _np
q1, q2 = _me.dynamicsymbols('q1 q2')q1_d, q2_d = _me.dynamicsymbols('q1_ q2_', 1)q1_dd, q2_dd = _me.dynamicsymbols('q1_ q2_', 2)l, m, g = _sm.symbols('l m g', real=True)frame_n = _me.ReferenceFrame('n')point_pn = _me.Point('pn')point_pn.set_vel(frame_n, 0)theta1 = _sm.atan(q2/q1)frame_a = _me.ReferenceFrame('a')frame_a.orient(frame_n, 'Axis', [theta1, frame_n.z])particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))particle_p.point.set_pos(point_pn, q1*frame_n.x+q2*frame_n.y)particle_p.mass = mparticle_p.point.set_vel(frame_n, (point_pn.pos_from(particle_p.point)).dt(frame_n))f_v = _me.dot((particle_p.point.vel(frame_n)).express(frame_a), frame_a.x)force_p = particle_p.mass*(g*frame_n.x)dependent = _sm.Matrix([[0]])dependent[0] = f_vvelocity_constraints = [i for i in dependent]u_q1_d = _me.dynamicsymbols('u_q1_d')u_q2_d = _me.dynamicsymbols('u_q2_d')kd_eqs = [q1_d-u_q1_d, q2_d-u_q2_d]forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x))]kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u_q2_d], u_dependent=[u_q1_d], kd_eqs = kd_eqs, velocity_constraints = velocity_constraints)fr, frstar = kane.kanes_equations([particle_p], forceList)zero = fr+frstarf_c = point_pn.pos_from(particle_p.point).magnitude()-lconfig = _sm.Matrix([[0]])config[0] = f_czero = zero.row_insert(zero.shape[0], _sm.Matrix([[0]]))zero[zero.shape[0]-1] = config[0]1"""Used for translating C source code into a SymPy expression"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059from sympy.external import import_moduleimport os
cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
"""This module contains all the necessary Classes and Function used to Parse C andC++ code into SymPy expressionThe module serves as a backend for SymPyExpression to parse C codeIt is also dependent on Clang's AST and SymPy's Codegen AST.The module only supports the features currently supported by the Clang andcodegen AST which will be updated as the development of codegen AST and thismodule progresses.You might find unexpected bugs and exceptions while using the module, feel freeto report them to the SymPy Issue Tracker
Features Supported==================
- Variable Declarations (integers and reals)- Assignment (using integer & floating literal and function calls)- Function Definitions and Declaration- Function Calls- Compound statements, Return statements
Notes=====
The module is dependent on an external dependency which needs to be installedto use the features of this module.
Clang: The C and C++ compiler which is used to extract an AST from the providedC source code.
References==========
.. [1] https://github.com/sympy/sympy/issues.. [2] https://clang.llvm.org/docs/.. [3] https://clang.llvm.org/docs/IntroductionToTheClangAST.html
"""
if cin: from sympy.codegen.ast import (Variable, Integer, Float, FunctionPrototype, FunctionDefinition, FunctionCall, none, Return, Assignment, intc, int8, int16, int64, uint8, uint16, uint32, uint64, float32, float64, float80, aug_assign, bool_, While, CodeBlock) from sympy.codegen.cnodes import (PreDecrement, PostDecrement, PreIncrement, PostIncrement) from sympy.core import Add, Mod, Mul, Pow, Rel from sympy.logic.boolalg import And, as_Boolean, Not, Or from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.logic.boolalg import (false, true) import sys import tempfile
class BaseParser: """Base Class for the C parser"""
def __init__(self): """Initializes the Base parser creating a Clang AST index""" self.index = cin.Index.create()
def diagnostics(self, out): """Diagostics function for the Clang AST""" for diag in self.tu.diagnostics: # tu = translation unit print('%s %s (line %s, col %s) %s' % ( { 4: 'FATAL', 3: 'ERROR', 2: 'WARNING', 1: 'NOTE', 0: 'IGNORED', }[diag.severity], diag.location.file, diag.location.line, diag.location.column, diag.spelling ), file=out)
class CCodeConverter(BaseParser): """The Code Convereter for Clang AST
The converter object takes the C source code or file as input and converts them to SymPy Expressions. """
def __init__(self): """Initializes the code converter""" super().__init__() self._py_nodes = [] self._data_types = { "void": { cin.TypeKind.VOID: none }, "bool": { cin.TypeKind.BOOL: bool_ }, "int": { cin.TypeKind.SCHAR: int8, cin.TypeKind.SHORT: int16, cin.TypeKind.INT: intc, cin.TypeKind.LONG: int64, cin.TypeKind.UCHAR: uint8, cin.TypeKind.USHORT: uint16, cin.TypeKind.UINT: uint32, cin.TypeKind.ULONG: uint64 }, "float": { cin.TypeKind.FLOAT: float32, cin.TypeKind.DOUBLE: float64, cin.TypeKind.LONGDOUBLE: float80 } }
def parse(self, filename, flags): """Function to parse a file with C source code
It takes the filename as an attribute and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the translation unit, whose results are collected into a list which is returned by the function.
Parameters ==========
filename : string Path to the C file to be parsed
flags: list Arguments to be passed to Clang while parsing the C code
Returns =======
py_nodes: list A list of SymPy AST nodes
""" filepath = os.path.abspath(filename) self.tu = self.index.parse( filepath, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL or child.kind == cin.CursorKind.FUNCTION_DECL: self._py_nodes.append(self.transform(child)) return self._py_nodes
def parse_str(self, source, flags): """Function to parse a string with C source code
It takes the source code as an attribute, stores it in a temporary file and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the translation unit, whose results are collected into a list which is returned by the function.
Parameters ==========
source : string A string containing the C source code to be parsed
flags: list Arguments to be passed to Clang while parsing the C code
Returns =======
py_nodes: list A list of SymPy AST nodes
""" file = tempfile.NamedTemporaryFile(mode = 'w+', suffix = '.cpp') file.write(source) file.flush() file.seek(0) self.tu = self.index.parse( file.name, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) file.close() for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL or child.kind == cin.CursorKind.FUNCTION_DECL: self._py_nodes.append(self.transform(child)) return self._py_nodes
def transform(self, node): """Transformation Function for Clang AST nodes
It determines the kind of node and calls the respective transformation function for that node.
Raises ======
NotImplementedError : if the transformation for the provided node is not implemented
""" handler = getattr(self, 'transform_%s' % node.kind.name.lower(), None)
if handler is None: print( "Ignoring node of type %s (%s)" % ( node.kind, ' '.join( t.spelling for t in node.get_tokens()) ), file=sys.stderr )
return handler(node)
def transform_var_decl(self, node): """Transformation Function for Variable Declaration
Used to create nodes for variable declarations and assignments with values or function call for the respective nodes in the clang AST
Returns =======
A variable node as Declaration, with the initial value if given
Raises ======
NotImplementedError : if called for data types not currently implemented
Notes =====
The function currently supports following data types:
Boolean: bool, _Bool
Integer: 8-bit: signed char and unsigned char 16-bit: short, short int, signed short, signed short int, unsigned short, unsigned short int 32-bit: int, signed int, unsigned int 64-bit: long, long int, signed long, signed long int, unsigned long, unsigned long int
Floating point: Single Precision: float Double Precision: double Extended Precision: long double
""" if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children)
#ignoring namespace and type details for the variable while child.kind == cin.CursorKind.NAMESPACE_REF or child.kind == cin.CursorKind.TYPE_REF: child = next(children)
val = self.transform(child)
supported_rhs = [ cin.CursorKind.INTEGER_LITERAL, cin.CursorKind.FLOATING_LITERAL, cin.CursorKind.UNEXPOSED_EXPR, cin.CursorKind.BINARY_OPERATOR, cin.CursorKind.PAREN_EXPR, cin.CursorKind.UNARY_OPERATOR, cin.CursorKind.CXX_BOOL_LITERAL_EXPR ]
if child.kind in supported_rhs: if isinstance(val, str): value = Symbol(val) elif isinstance(val, bool): if node.type.kind in self._data_types["int"]: value = Integer(0) if val == False else Integer(1) elif node.type.kind in self._data_types["float"]: value = Float(0.0) if val == False else Float(1.0) elif node.type.kind in self._data_types["bool"]: value = sympify(val) elif isinstance(val, (Integer, int, Float, float)): if node.type.kind in self._data_types["int"]: value = Integer(val) elif node.type.kind in self._data_types["float"]: value = Float(val) elif node.type.kind in self._data_types["bool"]: value = sympify(bool(val)) else: value = val
return Variable( node.spelling ).as_Declaration( type = type, value = value )
elif child.kind == cin.CursorKind.CALL_EXPR: return Variable( node.spelling ).as_Declaration( value = val )
else: raise NotImplementedError("Given " "variable declaration \"{}\" " "is not possible to parse yet!" .format(" ".join( t.spelling for t in node.get_tokens() ) ))
except StopIteration: return Variable( node.spelling ).as_Declaration( type = type )
def transform_function_decl(self, node): """Transformation Function For Function Declaration
Used to create nodes for function declarations and definitions for the respective nodes in the clang AST
Returns =======
function : Codegen AST node - FunctionPrototype node if function body is not present - FunctionDefinition node if the function body is present
"""
if node.result_type.kind in self._data_types["int"]: ret_type = self._data_types["int"][node.result_type.kind] elif node.result_type.kind in self._data_types["float"]: ret_type = self._data_types["float"][node.result_type.kind] elif node.result_type.kind in self._data_types["bool"]: ret_type = self._data_types["bool"][node.result_type.kind] elif node.result_type.kind in self._data_types["void"]: ret_type = self._data_types["void"][node.result_type.kind] else: raise NotImplementedError("Only void, bool, int " "and float are supported") body = [] param = []
# Subsequent nodes will be the parameters for the function. for child in node.get_children(): decl = self.transform(child) if child.kind == cin.CursorKind.PARM_DECL: param.append(decl) elif child.kind == cin.CursorKind.COMPOUND_STMT: for val in decl: body.append(val) else: body.append(decl)
if body == []: function = FunctionPrototype( return_type = ret_type, name = node.spelling, parameters = param ) else: function = FunctionDefinition( return_type = ret_type, name = node.spelling, parameters = param, body = body ) return function
def transform_parm_decl(self, node): """Transformation function for Parameter Declaration
Used to create parameter nodes for the required functions for the respective nodes in the clang AST
Returns =======
param : Codegen AST Node Variable node with the value and type of the variable
Raises ======
ValueError if multiple children encountered in the parameter node
""" if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children)
# Any namespace nodes can be ignored while child.kind in [cin.CursorKind.NAMESPACE_REF, cin.CursorKind.TYPE_REF, cin.CursorKind.TEMPLATE_REF]: child = next(children)
# If there is a child, it is the default value of the parameter. lit = self.transform(child) if node.type.kind in self._data_types["int"]: val = Integer(lit) elif node.type.kind in self._data_types["float"]: val = Float(lit) elif node.type.kind in self._data_types["bool"]: val = sympify(bool(lit)) else: raise NotImplementedError("Only bool, int " "and float are supported")
param = Variable( node.spelling ).as_Declaration( type = type, value = val ) except StopIteration: param = Variable( node.spelling ).as_Declaration( type = type )
try: self.transform(next(children)) raise ValueError("Can't handle multiple children on parameter") except StopIteration: pass
return param
def transform_integer_literal(self, node): """Transformation function for integer literal
Used to get the value and type of the given integer literal.
Returns =======
val : list List with two arguments type and Value type contains the type of the integer value contains the value stored in the variable
Notes =====
Only Base Integer type supported for now
""" try: value = next(node.get_tokens()).spelling except StopIteration: # No tokens value = node.literal return int(value)
def transform_floating_literal(self, node): """Transformation function for floating literal
Used to get the value and type of the given floating literal.
Returns =======
val : list List with two arguments type and Value type contains the type of float value contains the value stored in the variable
Notes =====
Only Base Float type supported for now
""" try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return float(value)
def transform_string_literal(self, node): #TODO: No string type in AST #type = #try: # value = next(node.get_tokens()).spelling #except (StopIteration, ValueError): # No tokens # value = node.literal #val = [type, value] #return val pass
def transform_character_literal(self, node): """Transformation function for character literal
Used to get the value of the given character literal.
Returns =======
val : int val contains the ascii value of the character literal
Notes =====
Only for cases where character is assigned to a integer value, since character literal is not in SymPy AST
""" try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return ord(str(value[1]))
def transform_cxx_bool_literal_expr(self, node): """Transformation function for boolean literal
Used to get the value of the given boolean literal.
Returns =======
value : bool value contains the boolean value of the variable
""" try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): value = node.literal return True if value == 'true' else False
def transform_unexposed_decl(self,node): """Transformation function for unexposed declarations""" pass
def transform_unexposed_expr(self, node): """Transformation function for unexposed expression
Unexposed expressions are used to wrap float, double literals and expressions
Returns =======
expr : Codegen AST Node the result from the wrapped expression
None : NoneType No children are found for the node
Raises ======
ValueError if the expression contains multiple children
""" # Ignore unexposed nodes; pass whatever is the first # (and should be only) child unaltered. try: children = node.get_children() expr = self.transform(next(children)) except StopIteration: return None
try: next(children) raise ValueError("Unexposed expression has > 1 children.") except StopIteration: pass
return expr
def transform_decl_ref_expr(self, node): """Returns the name of the declaration reference""" return node.spelling
def transform_call_expr(self, node): """Transformation function for a call expression
Used to create function call nodes for the function calls present in the C code
Returns =======
FunctionCall : Codegen AST Node FunctionCall node with parameters if any parameters are present
""" param = [] children = node.get_children() child = next(children)
while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children)
first_child = self.transform(child) try: for child in children: arg = self.transform(child) if child.kind == cin.CursorKind.INTEGER_LITERAL: param.append(Integer(arg)) elif child.kind == cin.CursorKind.FLOATING_LITERAL: param.append(Float(arg)) else: param.append(arg) return FunctionCall(first_child, param)
except StopIteration: return FunctionCall(first_child)
def transform_return_stmt(self, node): """Returns the Return Node for a return statement""" return Return(next(node.get_children()).spelling)
def transform_compound_stmt(self, node): """Transformation function for compound statements
Returns =======
expr : list list of Nodes for the expressions present in the statement
None : NoneType if the compound statement is empty
""" expr = [] children = node.get_children()
for child in children: expr.append(self.transform(child)) return expr
def transform_decl_stmt(self, node): """Transformation function for declaration statements
These statements are used to wrap different kinds of declararions like variable or function declaration The function calls the transformer function for the child of the given node
Returns =======
statement : Codegen AST Node contains the node returned by the children node for the type of declaration
Raises ======
ValueError if multiple children present
""" try: children = node.get_children() statement = self.transform(next(children)) except StopIteration: pass
try: self.transform(next(children)) raise ValueError("Don't know how to handle multiple statements") except StopIteration: pass
return statement
def transform_paren_expr(self, node): """Transformation function for Parenthesized expressions
Returns the result from its children nodes
""" return self.transform(next(node.get_children()))
def transform_compound_assignment_operator(self, node): """Transformation function for handling shorthand operators
Returns =======
augmented_assignment_expression: Codegen AST node shorthand assignment expression represented as Codegen AST
Raises ======
NotImplementedError If the shorthand operator for bitwise operators (~=, ^=, &=, |=, <<=, >>=) is encountered
""" return self.transform_binary_operator(node)
def transform_unary_operator(self, node): """Transformation function for handling unary operators
Returns =======
unary_expression: Codegen AST node simplified unary expression represented as Codegen AST
Raises ======
NotImplementedError If dereferencing operator(*), address operator(&) or bitwise NOT operator(~) is encountered
""" # supported operators list operators_list = ['+', '-', '++', '--', '!'] tokens = list(node.get_tokens())
# it can be either pre increment/decrement or any other operator from the list if tokens[0].spelling in operators_list: child = self.transform(next(node.get_children())) # (decl_ref) e.g.; int a = ++b; or simply ++b; if isinstance(child, str): if tokens[0].spelling == '+': return Symbol(child) if tokens[0].spelling == '-': return Mul(Symbol(child), -1) if tokens[0].spelling == '++': return PreIncrement(Symbol(child)) if tokens[0].spelling == '--': return PreDecrement(Symbol(child)) if tokens[0].spelling == '!': return Not(Symbol(child)) # e.g.; int a = -1; or int b = -(1 + 2); else: if tokens[0].spelling == '+': return child if tokens[0].spelling == '-': return Mul(child, -1) if tokens[0].spelling == '!': return Not(sympify(bool(child)))
# it can be either post increment/decrement # since variable name is obtained in token[0].spelling elif tokens[1].spelling in ['++', '--']: child = self.transform(next(node.get_children())) if tokens[1].spelling == '++': return PostIncrement(Symbol(child)) if tokens[1].spelling == '--': return PostDecrement(Symbol(child)) else: raise NotImplementedError("Dereferencing operator, " "Address operator and bitwise NOT operator " "have not been implemented yet!")
def transform_binary_operator(self, node): """Transformation function for handling binary operators
Returns =======
binary_expression: Codegen AST node simplified binary expression represented as Codegen AST
Raises ======
NotImplementedError If a bitwise operator or unary operator(which is a child of any binary operator in Clang AST) is encountered
""" # get all the tokens of assignment # and store it in the tokens list tokens = list(node.get_tokens())
# supported operators list operators_list = ['+', '-', '*', '/', '%','=', '>', '>=', '<', '<=', '==', '!=', '&&', '||', '+=', '-=', '*=', '/=', '%=']
# this stack will contain variable content # and type of variable in the rhs combined_variables_stack = []
# this stack will contain operators # to be processed in the rhs operators_stack = []
# iterate through every token for token in tokens: # token is either '(', ')' or # any of the supported operators from the operator list if token.kind == cin.TokenKind.PUNCTUATION:
# push '(' to the operators stack if token.spelling == '(': operators_stack.append('(')
elif token.spelling == ')': # keep adding the expression to the # combined variables stack unless # '(' is found while (operators_stack and operators_stack[-1] != '('): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator))
# pop '(' operators_stack.pop()
# token is an operator (supported) elif token.spelling in operators_list: while (operators_stack and self.priority_of(token.spelling) <= self.priority_of( operators_stack[-1])): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator))
# push current operator operators_stack.append(token.spelling)
# token is a bitwise operator elif token.spelling in ['&', '|', '^', '<<', '>>']: raise NotImplementedError( "Bitwise operator has not been " "implemented yet!")
# token is a shorthand bitwise operator elif token.spelling in ['&=', '|=', '^=', '<<=', '>>=']: raise NotImplementedError( "Shorthand bitwise operator has not been " "implemented yet!") else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling))
# token is an identifier(variable) elif token.kind == cin.TokenKind.IDENTIFIER: combined_variables_stack.append( [token.spelling, 'identifier'])
# token is a literal elif token.kind == cin.TokenKind.LITERAL: combined_variables_stack.append( [token.spelling, 'literal'])
# token is a keyword, either true or false elif (token.kind == cin.TokenKind.KEYWORD and token.spelling in ['true', 'false']): combined_variables_stack.append( [token.spelling, 'boolean']) else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling))
# process remaining operators while operators_stack: if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation(lhs, rhs, operator))
return combined_variables_stack[-1][0]
def priority_of(self, op): """To get the priority of given operator""" if op in ['=', '+=', '-=', '*=', '/=', '%=']: return 1 if op in ['&&', '||']: return 2 if op in ['<', '<=', '>', '>=', '==', '!=']: return 3 if op in ['+', '-']: return 4 if op in ['*', '/', '%']: return 5 return 0
def perform_operation(self, lhs, rhs, op): """Performs operation supported by the SymPy core
Returns =======
combined_variable: list contains variable content and type of variable
""" lhs_value = self.get_expr_for_operand(lhs) rhs_value = self.get_expr_for_operand(rhs) if op == '+': return [Add(lhs_value, rhs_value), 'expr'] if op == '-': return [Add(lhs_value, -rhs_value), 'expr'] if op == '*': return [Mul(lhs_value, rhs_value), 'expr'] if op == '/': return [Mul(lhs_value, Pow(rhs_value, Integer(-1))), 'expr'] if op == '%': return [Mod(lhs_value, rhs_value), 'expr'] if op in ['<', '<=', '>', '>=', '==', '!=']: return [Rel(lhs_value, rhs_value, op), 'expr'] if op == '&&': return [And(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '||': return [Or(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '=': return [Assignment(Variable(lhs_value), rhs_value), 'expr'] if op in ['+=', '-=', '*=', '/=', '%=']: return [aug_assign(Variable(lhs_value), op[0], rhs_value), 'expr']
def get_expr_for_operand(self, combined_variable): """Gives out SymPy Codegen AST node
AST node returned is corresponding to combined variable passed.Combined variable contains variable content and type of variable
""" if combined_variable[1] == 'identifier': return Symbol(combined_variable[0]) if combined_variable[1] == 'literal': if '.' in combined_variable[0]: return Float(float(combined_variable[0])) else: return Integer(int(combined_variable[0])) if combined_variable[1] == 'expr': return combined_variable[0] if combined_variable[1] == 'boolean': return true if combined_variable[0] == 'true' else false
def transform_null_stmt(self, node): """Handles Null Statement and returns None""" return none
def transform_while_stmt(self, node): """Transformation function for handling while statement
Returns =======
while statement : Codegen AST Node contains the while statement node having condition and statement block
""" children = node.get_children()
condition = self.transform(next(children)) statements = self.transform(next(children))
if isinstance(statements, list): statement_block = CodeBlock(*statements) else: statement_block = CodeBlock(statements)
return While(condition, statement_block)
else: class CCodeConverter(): # type: ignore def __init__(self, *args, **kwargs): raise ImportError("Module not Installed")
def parse_c(source): """Function for converting a C source code
The function reads the source code present in the given file and parses it to give out SymPy Expressions
Returns =======
src : list List of Python expression strings
""" converter = CCodeConverter() if os.path.exists(source): src = converter.parse(source, flags = []) else: src = converter.parse_str(source, flags = []) return src1"""Used for translating Fortran source code into a SymPy expression. """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347from sympy.external import import_module
lfortran = import_module('lfortran')
if lfortran: from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String, Return, FunctionDefinition, Assignment) from sympy.core import Add, Mul, Integer, Float from sympy.core.symbol import Symbol
asr_mod = lfortran.asr asr = lfortran.asr.asr src_to_ast = lfortran.ast.src_to_ast ast_to_asr = lfortran.semantic.ast_to_asr.ast_to_asr
""" This module contains all the necessary Classes and Function used to Parse Fortran code into SymPy expression
The module and its API are currently under development and experimental. It is also dependent on LFortran for the ASR that is converted to SymPy syntax which is also under development. The module only supports the features currently supported by the LFortran ASR which will be updated as the development of LFortran and this module progresses
You might find unexpected bugs and exceptions while using the module, feel free to report them to the SymPy Issue Tracker
The API for the module might also change while in development if better and more effective ways are discovered for the process
Features Supported ==================
- Variable Declarations (integers and reals) - Function Definitions - Assignments and Basic Binary Operations
Notes =====
The module depends on an external dependency
LFortran : Required to parse Fortran source code into ASR
References ==========
.. [1] https://github.com/sympy/sympy/issues .. [2] https://gitlab.com/lfortran/lfortran .. [3] https://docs.lfortran.org/
"""
class ASR2PyVisitor(asr.ASTVisitor): # type: ignore """ Visitor Class for LFortran ASR
It is a Visitor class derived from asr.ASRVisitor which visits all the nodes of the LFortran ASR and creates corresponding AST node for each ASR node
"""
def __init__(self): """Initialize the Parser""" self._py_ast = []
def visit_TranslationUnit(self, node): """ Function to visit all the elements of the Translation Unit created by LFortran ASR """ for s in node.global_scope.symbols: sym = node.global_scope.symbols[s] self.visit(sym) for item in node.items: self.visit(item)
def visit_Assignment(self, node): """Visitor Function for Assignment
Visits each Assignment is the LFortran ASR and creates corresponding assignment for SymPy.
Notes =====
The function currently only supports variable assignment and binary operation assignments of varying multitudes. Any type of numberS or array is not supported.
Raises ======
NotImplementedError() when called for Numeric assignments or Arrays
""" # TODO: Arithmetic Assignment if isinstance(node.target, asr.Variable): target = node.target value = node.value if isinstance(value, asr.Variable): new_node = Assignment( Variable( target.name ), Variable( value.name ) ) elif (type(value) == asr.BinOp): exp_ast = call_visitor(value) for expr in exp_ast: new_node = Assignment( Variable(target.name), expr ) else: raise NotImplementedError("Numeric assignments not supported") else: raise NotImplementedError("Arrays not supported") self._py_ast.append(new_node)
def visit_BinOp(self, node): """Visitor Function for Binary Operations
Visits each binary operation present in the LFortran ASR like addition, subtraction, multiplication, division and creates the corresponding operation node in SymPy's AST
In case of more than one binary operations, the function calls the call_visitor() function on the child nodes of the binary operations recursively until all the operations have been processed.
Notes =====
The function currently only supports binary operations with Variables or other binary operations. Numerics are not supported as of yet.
Raises ======
NotImplementedError() when called for Numeric assignments
""" # TODO: Integer Binary Operations op = node.op lhs = node.left rhs = node.right
if (type(lhs) == asr.Variable): left_value = Symbol(lhs.name) elif(type(lhs) == asr.BinOp): l_exp_ast = call_visitor(lhs) for exp in l_exp_ast: left_value = exp else: raise NotImplementedError("Numbers Currently not supported")
if (type(rhs) == asr.Variable): right_value = Symbol(rhs.name) elif(type(rhs) == asr.BinOp): r_exp_ast = call_visitor(rhs) for exp in r_exp_ast: right_value = exp else: raise NotImplementedError("Numbers Currently not supported")
if isinstance(op, asr.Add): new_node = Add(left_value, right_value) elif isinstance(op, asr.Sub): new_node = Add(left_value, -right_value) elif isinstance(op, asr.Div): new_node = Mul(left_value, 1/right_value) elif isinstance(op, asr.Mul): new_node = Mul(left_value, right_value)
self._py_ast.append(new_node)
def visit_Variable(self, node): """Visitor Function for Variable Declaration
Visits each variable declaration present in the ASR and creates a Symbol declaration for each variable
Notes =====
The functions currently only support declaration of integer and real variables. Other data types are still under development.
Raises ======
NotImplementedError() when called for unsupported data types
""" if isinstance(node.type, asr.Integer): var_type = IntBaseType(String('integer')) value = Integer(0) elif isinstance(node.type, asr.Real): var_type = FloatBaseType(String('real')) value = Float(0.0) else: raise NotImplementedError("Data type not supported")
if not (node.intent == 'in'): new_node = Variable( node.name ).as_Declaration( type = var_type, value = value ) self._py_ast.append(new_node)
def visit_Sequence(self, seq): """Visitor Function for code sequence
Visits a code sequence/ block and calls the visitor function on all the children of the code block to create corresponding code in python
""" if seq is not None: for node in seq: self._py_ast.append(call_visitor(node))
def visit_Num(self, node): """Visitor Function for Numbers in ASR
This function is currently under development and will be updated with improvements in the LFortran ASR
""" # TODO:Numbers when the LFortran ASR is updated # self._py_ast.append(Integer(node.n)) pass
def visit_Function(self, node): """Visitor Function for function Definitions
Visits each function definition present in the ASR and creates a function definition node in the Python AST with all the elements of the given function
The functions declare all the variables required as SymPy symbols in the function before the function definition
This function also the call_visior_function to parse the contents of the function body
""" # TODO: Return statement, variable declaration fn_args = [Variable(arg_iter.name) for arg_iter in node.args] fn_body = [] fn_name = node.name for i in node.body: fn_ast = call_visitor(i) try: fn_body_expr = fn_ast except UnboundLocalError: fn_body_expr = [] for sym in node.symtab.symbols: decl = call_visitor(node.symtab.symbols[sym]) for symbols in decl: fn_body.append(symbols) for elem in fn_body_expr: fn_body.append(elem) fn_body.append( Return( Variable( node.return_var.name ) ) ) if isinstance(node.return_var.type, asr.Integer): ret_type = IntBaseType(String('integer')) elif isinstance(node.return_var.type, asr.Real): ret_type = FloatBaseType(String('real')) else: raise NotImplementedError("Data type not supported") new_node = FunctionDefinition( return_type = ret_type, name = fn_name, parameters = fn_args, body = fn_body ) self._py_ast.append(new_node)
def ret_ast(self): """Returns the AST nodes""" return self._py_astelse: class ASR2PyVisitor(): # type: ignore def __init__(self, *args, **kwargs): raise ImportError('lfortran not available')
def call_visitor(fort_node): """Calls the AST Visitor on the Module
This function is used to call the AST visitor for a program or module It imports all the required modules and calls the visit() function on the given node
Parameters ==========
fort_node : LFortran ASR object Node for the operation for which the NodeVisitor is called
Returns =======
res_ast : list list of SymPy AST Nodes
""" v = ASR2PyVisitor() v.visit(fort_node) res_ast = v.ret_ast() return res_ast
def src_to_sympy(src): """Wrapper function to convert the given Fortran source code to SymPy Expressions
Parameters ==========
src : string A string with the Fortran source code
Returns =======
py_src : string A string with the Python source code compatible with SymPy
""" a_ast = src_to_ast(src, translation_unit=False) a = ast_to_asr(a_ast) py_src = call_visitor(a) return py_src123456789101112131415161718192021The MIT License (MIT)
Copyright 2016, latex2sympy
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312/* ANTLR4 LaTeX Math Grammar
Ported from latex2sympy by @augustt198 https://github.com/augustt198/latex2sympy See license in LICENSE.txt */
/* After changing this file, it is necessary to run `python setup.py antlr` in the root directory of the repository. This will regenerate the code in `sympy/parsing/latex/_antlr/*.py`. */
grammar LaTeX;
options { language = Python3;}
WS: [ \t\r\n]+ -> skip;THINSPACE: ('\\,' | '\\thinspace') -> skip;MEDSPACE: ('\\:' | '\\medspace') -> skip;THICKSPACE: ('\\;' | '\\thickspace') -> skip;QUAD: '\\quad' -> skip;QQUAD: '\\qquad' -> skip;NEGTHINSPACE: ('\\!' | '\\negthinspace') -> skip;NEGMEDSPACE: '\\negmedspace' -> skip;NEGTHICKSPACE: '\\negthickspace' -> skip;CMD_LEFT: '\\left' -> skip;CMD_RIGHT: '\\right' -> skip;
IGNORE: ( '\\vrule' | '\\vcenter' | '\\vbox' | '\\vskip' | '\\vspace' | '\\hfil' | '\\*' | '\\-' | '\\.' | '\\/' | '\\"' | '\\(' | '\\=' ) -> skip;
ADD: '+';SUB: '-';MUL: '*';DIV: '/';
L_PAREN: '(';R_PAREN: ')';L_BRACE: '{';R_BRACE: '}';L_BRACE_LITERAL: '\\{';R_BRACE_LITERAL: '\\}';L_BRACKET: '[';R_BRACKET: ']';
BAR: '|';
R_BAR: '\\right|';L_BAR: '\\left|';
L_ANGLE: '\\langle';R_ANGLE: '\\rangle';FUNC_LIM: '\\lim';LIM_APPROACH_SYM: '\\to' | '\\rightarrow' | '\\Rightarrow' | '\\longrightarrow' | '\\Longrightarrow';FUNC_INT: '\\int' | '\\int\\limits';FUNC_SUM: '\\sum';FUNC_PROD: '\\prod';
FUNC_EXP: '\\exp';FUNC_LOG: '\\log';FUNC_LG: '\\lg';FUNC_LN: '\\ln';FUNC_SIN: '\\sin';FUNC_COS: '\\cos';FUNC_TAN: '\\tan';FUNC_CSC: '\\csc';FUNC_SEC: '\\sec';FUNC_COT: '\\cot';
FUNC_ARCSIN: '\\arcsin';FUNC_ARCCOS: '\\arccos';FUNC_ARCTAN: '\\arctan';FUNC_ARCCSC: '\\arccsc';FUNC_ARCSEC: '\\arcsec';FUNC_ARCCOT: '\\arccot';
FUNC_SINH: '\\sinh';FUNC_COSH: '\\cosh';FUNC_TANH: '\\tanh';FUNC_ARSINH: '\\arsinh';FUNC_ARCOSH: '\\arcosh';FUNC_ARTANH: '\\artanh';
L_FLOOR: '\\lfloor';R_FLOOR: '\\rfloor';L_CEIL: '\\lceil';R_CEIL: '\\rceil';
FUNC_SQRT: '\\sqrt';FUNC_OVERLINE: '\\overline';
CMD_TIMES: '\\times';CMD_CDOT: '\\cdot';CMD_DIV: '\\div';CMD_FRAC: '\\frac' | '\\dfrac' | '\\tfrac';CMD_BINOM: '\\binom';CMD_DBINOM: '\\dbinom';CMD_TBINOM: '\\tbinom';
CMD_MATHIT: '\\mathit';
UNDERSCORE: '_';CARET: '^';COLON: ':';
fragment WS_CHAR: [ \t\r\n];DIFFERENTIAL: 'd' WS_CHAR*? ([a-zA-Z] | '\\' [a-zA-Z]+);
LETTER: [a-zA-Z];DIGIT: [0-9];
EQUAL: (('&' WS_CHAR*?)? '=') | ('=' (WS_CHAR*? '&')?);NEQ: '\\neq';
LT: '<';LTE: ('\\leq' | '\\le' | LTE_Q | LTE_S);LTE_Q: '\\leqq';LTE_S: '\\leqslant';
GT: '>';GTE: ('\\geq' | '\\ge' | GTE_Q | GTE_S);GTE_Q: '\\geqq';GTE_S: '\\geqslant';
BANG: '!';
SINGLE_QUOTES: '\''+;
SYMBOL: '\\' [a-zA-Z]+;
math: relation;
relation: relation (EQUAL | LT | LTE | GT | GTE | NEQ) relation | expr;
equality: expr EQUAL expr;
expr: additive;
additive: additive (ADD | SUB) additive | mp;
// mult partmp: mp (MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV | COLON) mp | unary;
mp_nofunc: mp_nofunc ( MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV | COLON ) mp_nofunc | unary_nofunc;
unary: (ADD | SUB) unary | postfix+;
unary_nofunc: (ADD | SUB) unary_nofunc | postfix postfix_nofunc*;
postfix: exp postfix_op*;postfix_nofunc: exp_nofunc postfix_op*;postfix_op: BANG | eval_at;
eval_at: BAR (eval_at_sup | eval_at_sub | eval_at_sup eval_at_sub);
eval_at_sub: UNDERSCORE L_BRACE (expr | equality) R_BRACE;
eval_at_sup: CARET L_BRACE (expr | equality) R_BRACE;
exp: exp CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp;
exp_nofunc: exp_nofunc CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp_nofunc;
comp: group | abs_group | func | atom | floor | ceil;
comp_nofunc: group | abs_group | atom | floor | ceil;
group: L_PAREN expr R_PAREN | L_BRACKET expr R_BRACKET | L_BRACE expr R_BRACE | L_BRACE_LITERAL expr R_BRACE_LITERAL;
abs_group: BAR expr BAR;
number: DIGIT+ (',' DIGIT DIGIT DIGIT)* ('.' DIGIT+)?;
atom: (LETTER | SYMBOL) (subexpr? SINGLE_QUOTES? | SINGLE_QUOTES? subexpr?) | number | DIFFERENTIAL | mathit | frac | binom | bra | ket;
bra: L_ANGLE expr (R_BAR | BAR);ket: (L_BAR | BAR) expr R_ANGLE;
mathit: CMD_MATHIT L_BRACE mathit_text R_BRACE;mathit_text: LETTER*;
frac: CMD_FRAC (upperd = DIGIT | L_BRACE upper = expr R_BRACE) (lowerd = DIGIT | L_BRACE lower = expr R_BRACE);
binom: (CMD_BINOM | CMD_DBINOM | CMD_TBINOM) L_BRACE n = expr R_BRACE L_BRACE k = expr R_BRACE;
floor: L_FLOOR val = expr R_FLOOR;ceil: L_CEIL val = expr R_CEIL;
func_normal: FUNC_EXP | FUNC_LOG | FUNC_LG | FUNC_LN | FUNC_SIN | FUNC_COS | FUNC_TAN | FUNC_CSC | FUNC_SEC | FUNC_COT | FUNC_ARCSIN | FUNC_ARCCOS | FUNC_ARCTAN | FUNC_ARCCSC | FUNC_ARCSEC | FUNC_ARCCOT | FUNC_SINH | FUNC_COSH | FUNC_TANH | FUNC_ARSINH | FUNC_ARCOSH | FUNC_ARTANH;
func: func_normal (subexpr? supexpr? | supexpr? subexpr?) ( L_PAREN func_arg R_PAREN | func_arg_noparens ) | (LETTER | SYMBOL) (subexpr? SINGLE_QUOTES? | SINGLE_QUOTES? subexpr?) // e.g. f(x), f_1'(x) L_PAREN args R_PAREN | FUNC_INT (subexpr supexpr | supexpr subexpr)? ( additive? DIFFERENTIAL | frac | additive ) | FUNC_SQRT (L_BRACKET root = expr R_BRACKET)? L_BRACE base = expr R_BRACE | FUNC_OVERLINE L_BRACE base = expr R_BRACE | (FUNC_SUM | FUNC_PROD) (subeq supexpr | supexpr subeq) mp | FUNC_LIM limit_sub mp;
args: (expr ',' args) | expr;
limit_sub: UNDERSCORE L_BRACE (LETTER | SYMBOL) LIM_APPROACH_SYM expr ( CARET ((L_BRACE (ADD | SUB) R_BRACE) | ADD | SUB) )? R_BRACE;
func_arg: expr | (expr ',' func_arg);func_arg_noparens: mp_nofunc;
subexpr: UNDERSCORE (atom | L_BRACE expr R_BRACE);supexpr: CARET (atom | L_BRACE expr R_BRACE);
subeq: UNDERSCORE L_BRACE equality R_BRACE;supeq: UNDERSCORE L_BRACE equality R_BRACE;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204from sympy.external import import_modulefrom sympy.utilities.decorator import doctest_depends_onfrom re import compile as rcompile
from sympy.parsing.latex.lark import LarkLaTeXParser, TransformToSymPyExpr, parse_latex_lark # noqa
from .errors import LaTeXParsingError # noqa
IGNORE_L = r"\s*[{]*\s*"IGNORE_R = r"\s*[}]*\s*"NO_LEFT = r"(?<!\\left)"BEGIN_AMS_MAT = r"\\begin{matrix}"END_AMS_MAT = r"\\end{matrix}"BEGIN_ARR = r"\\begin{array}{.*?}"END_ARR = r"\\end{array}"
# begin_delim_regex: end_delim_regexMATRIX_DELIMS = {fr"\\left\({IGNORE_L}{BEGIN_AMS_MAT}": fr"{END_AMS_MAT}{IGNORE_R}\\right\)", fr"{NO_LEFT}\({IGNORE_L}{BEGIN_AMS_MAT}": fr"{END_AMS_MAT}{IGNORE_R}\)", fr"\\left\[{IGNORE_L}{BEGIN_AMS_MAT}": fr"{END_AMS_MAT}{IGNORE_R}\\right\]", fr"{NO_LEFT}\[{IGNORE_L}{BEGIN_AMS_MAT}": fr"{END_AMS_MAT}{IGNORE_R}\]", fr"\\left\|{IGNORE_L}{BEGIN_AMS_MAT}": fr"{END_AMS_MAT}{IGNORE_R}\\right\|", fr"{NO_LEFT}\|{IGNORE_L}{BEGIN_AMS_MAT}": fr"{END_AMS_MAT}{IGNORE_R}\|", r"\\begin{pmatrix}": r"\\end{pmatrix}", r"\\begin{bmatrix}": r"\\end{bmatrix}", r"\\begin{vmatrix}": r"\\end{vmatrix}", fr"\\left\({IGNORE_L}{BEGIN_ARR}": fr"{END_ARR}{IGNORE_R}\\right\)", fr"{NO_LEFT}\({IGNORE_L}{BEGIN_ARR}": fr"{END_ARR}{IGNORE_R}\)", fr"\\left\[{IGNORE_L}{BEGIN_ARR}": fr"{END_ARR}{IGNORE_R}\\right\]", fr"{NO_LEFT}\[{IGNORE_L}{BEGIN_ARR}": fr"{END_ARR}{IGNORE_R}\]", fr"\\left\|{IGNORE_L}{BEGIN_ARR}": fr"{END_ARR}{IGNORE_R}\\right\|", fr"{NO_LEFT}\|{IGNORE_L}{BEGIN_ARR}": fr"{END_ARR}{IGNORE_R}\|" }
MATRIX_DELIMS_INV = {v: k for k, v in MATRIX_DELIMS.items()}
# begin_delim_regex: ideal_begin_delim_representativeBEGIN_DELIM_REPR = {fr"\\left\({IGNORE_L}{BEGIN_AMS_MAT}": "\\left(\\begin{matrix}", fr"{NO_LEFT}\({IGNORE_L}{BEGIN_AMS_MAT}": "(\\begin{matrix}", fr"\\left\[{IGNORE_L}{BEGIN_AMS_MAT}": "\\left[\\begin{matrix}", fr"{NO_LEFT}\[{IGNORE_L}{BEGIN_AMS_MAT}": "[\\begin{matrix}", fr"\\left\|{IGNORE_L}{BEGIN_AMS_MAT}": "\\left|\\begin{matrix}", fr"{NO_LEFT}\|{IGNORE_L}{BEGIN_AMS_MAT}": "|\\begin{matrix}", r"\\begin{pmatrix}": "\\begin{pmatrix}", r"\\begin{bmatrix}": "\\begin{bmatrix}", r"\\begin{vmatrix}": "\\begin{vmatrix}", fr"\\left\({IGNORE_L}{BEGIN_ARR}": "\\left(\\begin{array}{COLUMN_SPECIFIERS}", fr"{NO_LEFT}\({IGNORE_L}{BEGIN_ARR}": "(\\begin{array}{COLUMN_SPECIFIERS}", fr"\\left\[{IGNORE_L}{BEGIN_ARR}": "\\left[\\begin{array}{COLUMN_SPECIFIERS}", fr"{NO_LEFT}\[{IGNORE_L}{BEGIN_ARR}": "[\\begin{array}{COLUMN_SPECIFIERS}", fr"\\left\|{IGNORE_L}{BEGIN_ARR}": "\\left|\\begin{array}{COLUMN_SPECIFIERS}", fr"{NO_LEFT}\|{IGNORE_L}{BEGIN_ARR}": "|\\begin{array}{COLUMN_SPECIFIERS}" }
# end_delim_regex: ideal_end_delim_representativeEND_DELIM_REPR = {fr"{END_AMS_MAT}{IGNORE_R}\\right\)": "\\end{matrix}\\right)", fr"{END_AMS_MAT}{IGNORE_R}\)": "\\end{matrix})", fr"{END_AMS_MAT}{IGNORE_R}\\right\]": "\\end{matrix}\\right]", fr"{END_AMS_MAT}{IGNORE_R}\]": "\\end{matrix}]", fr"{END_AMS_MAT}{IGNORE_R}\\right\|": "\\end{matrix}\\right|", fr"{END_AMS_MAT}{IGNORE_R}\|": "\\end{matrix}|", r"\\end{pmatrix}": "\\end{pmatrix}", r"\\end{bmatrix}": "\\end{bmatrix}", r"\\end{vmatrix}": "\\end{vmatrix}", fr"{END_ARR}{IGNORE_R}\\right\)": "\\end{array}\\right)", fr"{END_ARR}{IGNORE_R}\)": "\\end{array})", fr"{END_ARR}{IGNORE_R}\\right\]": "\\end{array}\\right]", fr"{END_ARR}{IGNORE_R}\]": "\\end{array}]", fr"{END_ARR}{IGNORE_R}\\right\|": "\\end{array}\\right|", fr"{END_ARR}{IGNORE_R}\|": "\\end{array}|" }
def check_matrix_delimiters(latex_str): """Report mismatched, excess, or missing matrix delimiters.""" spans = [] for begin_delim in MATRIX_DELIMS: end_delim = MATRIX_DELIMS[begin_delim]
p = rcompile(begin_delim) q = rcompile(end_delim)
spans.extend([(*m.span(), m.group(), begin_delim) for m in p.finditer(latex_str)]) spans.extend([(*m.span(), m.group(), end_delim) for m in q.finditer(latex_str)])
spans.sort(key=(lambda x: x[0])) if len(spans) % 2 == 1: # Odd number of delimiters; therefore something # is wrong. We do not complain yet; let's see if # we can pinpoint the actual error. spans.append((None, None, None, None))
spans = [(*x, *y) for (x, y) in zip(spans[::2], spans[1::2])] for x in spans: # x is supposed to be an 8-tuple of the following form: # # (begin_delim_span_start, begin_delim_span_end, # begin_delim_match, begin_delim_regex, # end_delim_span_start, end_delim_span_end, # end_delim_match, end_delim_regex)
sellipsis = "..." s = x[0] - 10 if s < 0: s = 0 sellipsis = ""
eellipsis = "..." e = x[1] + 10 if e > len(latex_str): e = len(latex_str) eellipsis = ""
if x[3] in END_DELIM_REPR: err = (f"Extra '{x[2]}' at index {x[0]} or " "missing corresponding " f"'{BEGIN_DELIM_REPR[MATRIX_DELIMS_INV[x[3]]]}' " f"in LaTeX string: {sellipsis}{latex_str[s:e]}" f"{eellipsis}") raise LaTeXParsingError(err)
if x[7] is None: err = (f"Extra '{x[2]}' at index {x[0]} or " "missing corresponding " f"'{END_DELIM_REPR[MATRIX_DELIMS[x[3]]]}' " f"in LaTeX string: {sellipsis}{latex_str[s:e]}" f"{eellipsis}") raise LaTeXParsingError(err)
correct_end_regex = MATRIX_DELIMS[x[3]] sellipsis = "..." if x[0] > 0 else "" eellipsis = "..." if x[5] < len(latex_str) else "" if x[7] != correct_end_regex: err = ("Expected " f"'{END_DELIM_REPR[correct_end_regex]}' " f"to close the '{x[2]}' at index {x[0]} but " f"found '{x[6]}' at index {x[4]} of LaTeX " f"string instead: {sellipsis}{latex_str[x[0]:x[5]]}" f"{eellipsis}") raise LaTeXParsingError(err)
__doctest_requires__ = {('parse_latex',): ['antlr4', 'lark']}
@doctest_depends_on(modules=('antlr4', 'lark'))def parse_latex(s, strict=False, backend="antlr"): r"""Converts the input LaTeX string ``s`` to a SymPy ``Expr``.
Parameters ==========
s : str The LaTeX string to parse. In Python source containing LaTeX, *raw strings* (denoted with ``r"``, like this one) are preferred, as LaTeX makes liberal use of the ``\`` character, which would trigger escaping in normal Python strings. backend : str, optional Currently, there are two backends supported: ANTLR, and Lark. The default setting is to use the ANTLR backend, which can be changed to Lark if preferred.
Use ``backend="antlr"`` for the ANTLR-based parser, and ``backend="lark"`` for the Lark-based parser.
The ``backend`` option is case-sensitive, and must be in all lowercase. strict : bool, optional This option is only available with the ANTLR backend.
If True, raise an exception if the string cannot be parsed as valid LaTeX. If False, try to recover gracefully from common mistakes.
Examples ========
>>> from sympy.parsing.latex import parse_latex >>> expr = parse_latex(r"\frac {1 + \sqrt {\a}} {\b}") >>> expr (sqrt(a) + 1)/b >>> expr.evalf(4, subs=dict(a=5, b=2)) 1.618 >>> func = parse_latex(r"\int_1^\alpha \dfrac{\mathrm{d}t}{t}", backend="lark") >>> func.evalf(subs={"alpha": 2}) 0.693147180559945 """
check_matrix_delimiters(s)
if backend == "antlr": _latex = import_module( 'sympy.parsing.latex._parse_latex_antlr', import_kwargs={'fromlist': ['X']})
if _latex is not None: return _latex.parse_latex(s, strict) elif backend == "lark": return parse_latex_lark(s) else: raise NotImplementedError(f"Using the '{backend}' backend in the LaTeX" \ " parser is not supported.")123456789# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***## Generated from ../LaTeX.g4, derived from latex2sympy# latex2sympy is licensed under the MIT license# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt## Generated with antlr4# antlr4 is licensed under the BSD-3-Clause License# https://github.com/antlr/antlr4/blob/master/LICENSE.txt123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***## Generated from ../LaTeX.g4, derived from latex2sympy# latex2sympy is licensed under the MIT license# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt## Generated with antlr4# antlr4 is licensed under the BSD-3-Clause License# https://github.com/antlr/antlr4/blob/master/LICENSE.txtfrom antlr4 import *from io import StringIOimport sysif sys.version_info[1] > 5: from typing import TextIOelse: from typing.io import TextIO
def serializedATN(): return [ 4,0,91,911,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5, 2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2, 13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7, 19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2, 26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7, 32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2, 39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7, 45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,2,51,7,51,2, 52,7,52,2,53,7,53,2,54,7,54,2,55,7,55,2,56,7,56,2,57,7,57,2,58,7, 58,2,59,7,59,2,60,7,60,2,61,7,61,2,62,7,62,2,63,7,63,2,64,7,64,2, 65,7,65,2,66,7,66,2,67,7,67,2,68,7,68,2,69,7,69,2,70,7,70,2,71,7, 71,2,72,7,72,2,73,7,73,2,74,7,74,2,75,7,75,2,76,7,76,2,77,7,77,2, 78,7,78,2,79,7,79,2,80,7,80,2,81,7,81,2,82,7,82,2,83,7,83,2,84,7, 84,2,85,7,85,2,86,7,86,2,87,7,87,2,88,7,88,2,89,7,89,2,90,7,90,2, 91,7,91,1,0,1,0,1,1,1,1,1,2,4,2,191,8,2,11,2,12,2,192,1,2,1,2,1, 3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,3,3,209,8,3,1,3,1, 3,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,3,4,224,8,4,1,4,1, 4,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,3,5,241,8, 5,1,5,1,5,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,7,1,7,1,7,1,7,1,7,1, 7,1,7,1,7,1,7,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1, 8,1,8,1,8,3,8,277,8,8,1,8,1,8,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1, 9,1,9,1,9,1,9,1,9,1,9,1,9,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10, 1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,11,1,11,1,11,1,11, 1,11,1,11,1,11,1,11,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12, 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13, 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13, 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13, 1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,3,13, 381,8,13,1,13,1,13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18, 1,18,1,19,1,19,1,20,1,20,1,21,1,21,1,22,1,22,1,22,1,23,1,23,1,23, 1,24,1,24,1,25,1,25,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1,27, 1,27,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,29,1,29,1,29,1,29,1,29, 1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,31,1,31, 1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32, 1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32, 1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32, 1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32, 1,32,1,32,1,32,1,32,1,32,1,32,3,32,504,8,32,1,33,1,33,1,33,1,33, 1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,3,33,521, 8,33,1,34,1,34,1,34,1,34,1,34,1,35,1,35,1,35,1,35,1,35,1,35,1,36, 1,36,1,36,1,36,1,36,1,37,1,37,1,37,1,37,1,37,1,38,1,38,1,38,1,38, 1,39,1,39,1,39,1,39,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41, 1,41,1,42,1,42,1,42,1,42,1,42,1,43,1,43,1,43,1,43,1,43,1,44,1,44, 1,44,1,44,1,44,1,45,1,45,1,45,1,45,1,45,1,46,1,46,1,46,1,46,1,46, 1,46,1,46,1,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,48,1,48, 1,48,1,48,1,48,1,48,1,48,1,48,1,49,1,49,1,49,1,49,1,49,1,49,1,49, 1,49,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,51,1,51,1,51,1,51, 1,51,1,51,1,51,1,51,1,52,1,52,1,52,1,52,1,52,1,52,1,53,1,53,1,53, 1,53,1,53,1,53,1,54,1,54,1,54,1,54,1,54,1,54,1,55,1,55,1,55,1,55, 1,55,1,55,1,55,1,55,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,57, 1,57,1,57,1,57,1,57,1,57,1,57,1,57,1,58,1,58,1,58,1,58,1,58,1,58, 1,58,1,58,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,60,1,60,1,60, 1,60,1,60,1,60,1,60,1,61,1,61,1,61,1,61,1,61,1,61,1,61,1,62,1,62, 1,62,1,62,1,62,1,62,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63, 1,63,1,64,1,64,1,64,1,64,1,64,1,64,1,64,1,65,1,65,1,65,1,65,1,65, 1,65,1,66,1,66,1,66,1,66,1,66,1,67,1,67,1,67,1,67,1,67,1,67,1,67, 1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,3,67,753,8,67, 1,68,1,68,1,68,1,68,1,68,1,68,1,68,1,69,1,69,1,69,1,69,1,69,1,69, 1,69,1,69,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,71,1,71,1,71, 1,71,1,71,1,71,1,71,1,71,1,72,1,72,1,73,1,73,1,74,1,74,1,75,1,75, 1,76,1,76,5,76,796,8,76,10,76,12,76,799,9,76,1,76,1,76,1,76,4,76, 804,8,76,11,76,12,76,805,3,76,808,8,76,1,77,1,77,1,78,1,78,1,79, 1,79,5,79,816,8,79,10,79,12,79,819,9,79,3,79,821,8,79,1,79,1,79, 1,79,5,79,826,8,79,10,79,12,79,829,9,79,1,79,3,79,832,8,79,3,79, 834,8,79,1,80,1,80,1,80,1,80,1,80,1,81,1,81,1,82,1,82,1,82,1,82, 1,82,1,82,1,82,1,82,1,82,3,82,852,8,82,1,83,1,83,1,83,1,83,1,83, 1,83,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,85,1,85, 1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,3,86,881,8,86,1,87, 1,87,1,87,1,87,1,87,1,87,1,88,1,88,1,88,1,88,1,88,1,88,1,88,1,88, 1,88,1,88,1,89,1,89,1,90,4,90,902,8,90,11,90,12,90,903,1,91,1,91, 4,91,908,8,91,11,91,12,91,909,3,797,817,827,0,92,1,1,3,2,5,3,7,4, 9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,27,14,29,15,31,16, 33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24,49,25,51,26,53,27, 55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35,71,36,73,37,75,38, 77,39,79,40,81,41,83,42,85,43,87,44,89,45,91,46,93,47,95,48,97,49, 99,50,101,51,103,52,105,53,107,54,109,55,111,56,113,57,115,58,117, 59,119,60,121,61,123,62,125,63,127,64,129,65,131,66,133,67,135,68, 137,69,139,70,141,71,143,72,145,73,147,74,149,75,151,0,153,76,155, 77,157,78,159,79,161,80,163,81,165,82,167,83,169,84,171,85,173,86, 175,87,177,88,179,89,181,90,183,91,1,0,3,3,0,9,10,13,13,32,32,2, 0,65,90,97,122,1,0,48,57,949,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0, 0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0, 17,1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0, 27,1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0, 37,1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0, 47,1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0, 57,1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0, 67,1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0, 77,1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0, 87,1,0,0,0,0,89,1,0,0,0,0,91,1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0, 97,1,0,0,0,0,99,1,0,0,0,0,101,1,0,0,0,0,103,1,0,0,0,0,105,1,0,0, 0,0,107,1,0,0,0,0,109,1,0,0,0,0,111,1,0,0,0,0,113,1,0,0,0,0,115, 1,0,0,0,0,117,1,0,0,0,0,119,1,0,0,0,0,121,1,0,0,0,0,123,1,0,0,0, 0,125,1,0,0,0,0,127,1,0,0,0,0,129,1,0,0,0,0,131,1,0,0,0,0,133,1, 0,0,0,0,135,1,0,0,0,0,137,1,0,0,0,0,139,1,0,0,0,0,141,1,0,0,0,0, 143,1,0,0,0,0,145,1,0,0,0,0,147,1,0,0,0,0,149,1,0,0,0,0,153,1,0, 0,0,0,155,1,0,0,0,0,157,1,0,0,0,0,159,1,0,0,0,0,161,1,0,0,0,0,163, 1,0,0,0,0,165,1,0,0,0,0,167,1,0,0,0,0,169,1,0,0,0,0,171,1,0,0,0, 0,173,1,0,0,0,0,175,1,0,0,0,0,177,1,0,0,0,0,179,1,0,0,0,0,181,1, 0,0,0,0,183,1,0,0,0,1,185,1,0,0,0,3,187,1,0,0,0,5,190,1,0,0,0,7, 208,1,0,0,0,9,223,1,0,0,0,11,240,1,0,0,0,13,244,1,0,0,0,15,252,1, 0,0,0,17,276,1,0,0,0,19,280,1,0,0,0,21,295,1,0,0,0,23,312,1,0,0, 0,25,320,1,0,0,0,27,380,1,0,0,0,29,384,1,0,0,0,31,386,1,0,0,0,33, 388,1,0,0,0,35,390,1,0,0,0,37,392,1,0,0,0,39,394,1,0,0,0,41,396, 1,0,0,0,43,398,1,0,0,0,45,400,1,0,0,0,47,403,1,0,0,0,49,406,1,0, 0,0,51,408,1,0,0,0,53,410,1,0,0,0,55,412,1,0,0,0,57,420,1,0,0,0, 59,427,1,0,0,0,61,435,1,0,0,0,63,443,1,0,0,0,65,503,1,0,0,0,67,520, 1,0,0,0,69,522,1,0,0,0,71,527,1,0,0,0,73,533,1,0,0,0,75,538,1,0, 0,0,77,543,1,0,0,0,79,547,1,0,0,0,81,551,1,0,0,0,83,556,1,0,0,0, 85,561,1,0,0,0,87,566,1,0,0,0,89,571,1,0,0,0,91,576,1,0,0,0,93,581, 1,0,0,0,95,589,1,0,0,0,97,597,1,0,0,0,99,605,1,0,0,0,101,613,1,0, 0,0,103,621,1,0,0,0,105,629,1,0,0,0,107,635,1,0,0,0,109,641,1,0, 0,0,111,647,1,0,0,0,113,655,1,0,0,0,115,663,1,0,0,0,117,671,1,0, 0,0,119,679,1,0,0,0,121,687,1,0,0,0,123,694,1,0,0,0,125,701,1,0, 0,0,127,707,1,0,0,0,129,717,1,0,0,0,131,724,1,0,0,0,133,730,1,0, 0,0,135,752,1,0,0,0,137,754,1,0,0,0,139,761,1,0,0,0,141,769,1,0, 0,0,143,777,1,0,0,0,145,785,1,0,0,0,147,787,1,0,0,0,149,789,1,0, 0,0,151,791,1,0,0,0,153,793,1,0,0,0,155,809,1,0,0,0,157,811,1,0, 0,0,159,833,1,0,0,0,161,835,1,0,0,0,163,840,1,0,0,0,165,851,1,0, 0,0,167,853,1,0,0,0,169,859,1,0,0,0,171,869,1,0,0,0,173,880,1,0, 0,0,175,882,1,0,0,0,177,888,1,0,0,0,179,898,1,0,0,0,181,901,1,0, 0,0,183,905,1,0,0,0,185,186,5,44,0,0,186,2,1,0,0,0,187,188,5,46, 0,0,188,4,1,0,0,0,189,191,7,0,0,0,190,189,1,0,0,0,191,192,1,0,0, 0,192,190,1,0,0,0,192,193,1,0,0,0,193,194,1,0,0,0,194,195,6,2,0, 0,195,6,1,0,0,0,196,197,5,92,0,0,197,209,5,44,0,0,198,199,5,92,0, 0,199,200,5,116,0,0,200,201,5,104,0,0,201,202,5,105,0,0,202,203, 5,110,0,0,203,204,5,115,0,0,204,205,5,112,0,0,205,206,5,97,0,0,206, 207,5,99,0,0,207,209,5,101,0,0,208,196,1,0,0,0,208,198,1,0,0,0,209, 210,1,0,0,0,210,211,6,3,0,0,211,8,1,0,0,0,212,213,5,92,0,0,213,224, 5,58,0,0,214,215,5,92,0,0,215,216,5,109,0,0,216,217,5,101,0,0,217, 218,5,100,0,0,218,219,5,115,0,0,219,220,5,112,0,0,220,221,5,97,0, 0,221,222,5,99,0,0,222,224,5,101,0,0,223,212,1,0,0,0,223,214,1,0, 0,0,224,225,1,0,0,0,225,226,6,4,0,0,226,10,1,0,0,0,227,228,5,92, 0,0,228,241,5,59,0,0,229,230,5,92,0,0,230,231,5,116,0,0,231,232, 5,104,0,0,232,233,5,105,0,0,233,234,5,99,0,0,234,235,5,107,0,0,235, 236,5,115,0,0,236,237,5,112,0,0,237,238,5,97,0,0,238,239,5,99,0, 0,239,241,5,101,0,0,240,227,1,0,0,0,240,229,1,0,0,0,241,242,1,0, 0,0,242,243,6,5,0,0,243,12,1,0,0,0,244,245,5,92,0,0,245,246,5,113, 0,0,246,247,5,117,0,0,247,248,5,97,0,0,248,249,5,100,0,0,249,250, 1,0,0,0,250,251,6,6,0,0,251,14,1,0,0,0,252,253,5,92,0,0,253,254, 5,113,0,0,254,255,5,113,0,0,255,256,5,117,0,0,256,257,5,97,0,0,257, 258,5,100,0,0,258,259,1,0,0,0,259,260,6,7,0,0,260,16,1,0,0,0,261, 262,5,92,0,0,262,277,5,33,0,0,263,264,5,92,0,0,264,265,5,110,0,0, 265,266,5,101,0,0,266,267,5,103,0,0,267,268,5,116,0,0,268,269,5, 104,0,0,269,270,5,105,0,0,270,271,5,110,0,0,271,272,5,115,0,0,272, 273,5,112,0,0,273,274,5,97,0,0,274,275,5,99,0,0,275,277,5,101,0, 0,276,261,1,0,0,0,276,263,1,0,0,0,277,278,1,0,0,0,278,279,6,8,0, 0,279,18,1,0,0,0,280,281,5,92,0,0,281,282,5,110,0,0,282,283,5,101, 0,0,283,284,5,103,0,0,284,285,5,109,0,0,285,286,5,101,0,0,286,287, 5,100,0,0,287,288,5,115,0,0,288,289,5,112,0,0,289,290,5,97,0,0,290, 291,5,99,0,0,291,292,5,101,0,0,292,293,1,0,0,0,293,294,6,9,0,0,294, 20,1,0,0,0,295,296,5,92,0,0,296,297,5,110,0,0,297,298,5,101,0,0, 298,299,5,103,0,0,299,300,5,116,0,0,300,301,5,104,0,0,301,302,5, 105,0,0,302,303,5,99,0,0,303,304,5,107,0,0,304,305,5,115,0,0,305, 306,5,112,0,0,306,307,5,97,0,0,307,308,5,99,0,0,308,309,5,101,0, 0,309,310,1,0,0,0,310,311,6,10,0,0,311,22,1,0,0,0,312,313,5,92,0, 0,313,314,5,108,0,0,314,315,5,101,0,0,315,316,5,102,0,0,316,317, 5,116,0,0,317,318,1,0,0,0,318,319,6,11,0,0,319,24,1,0,0,0,320,321, 5,92,0,0,321,322,5,114,0,0,322,323,5,105,0,0,323,324,5,103,0,0,324, 325,5,104,0,0,325,326,5,116,0,0,326,327,1,0,0,0,327,328,6,12,0,0, 328,26,1,0,0,0,329,330,5,92,0,0,330,331,5,118,0,0,331,332,5,114, 0,0,332,333,5,117,0,0,333,334,5,108,0,0,334,381,5,101,0,0,335,336, 5,92,0,0,336,337,5,118,0,0,337,338,5,99,0,0,338,339,5,101,0,0,339, 340,5,110,0,0,340,341,5,116,0,0,341,342,5,101,0,0,342,381,5,114, 0,0,343,344,5,92,0,0,344,345,5,118,0,0,345,346,5,98,0,0,346,347, 5,111,0,0,347,381,5,120,0,0,348,349,5,92,0,0,349,350,5,118,0,0,350, 351,5,115,0,0,351,352,5,107,0,0,352,353,5,105,0,0,353,381,5,112, 0,0,354,355,5,92,0,0,355,356,5,118,0,0,356,357,5,115,0,0,357,358, 5,112,0,0,358,359,5,97,0,0,359,360,5,99,0,0,360,381,5,101,0,0,361, 362,5,92,0,0,362,363,5,104,0,0,363,364,5,102,0,0,364,365,5,105,0, 0,365,381,5,108,0,0,366,367,5,92,0,0,367,381,5,42,0,0,368,369,5, 92,0,0,369,381,5,45,0,0,370,371,5,92,0,0,371,381,5,46,0,0,372,373, 5,92,0,0,373,381,5,47,0,0,374,375,5,92,0,0,375,381,5,34,0,0,376, 377,5,92,0,0,377,381,5,40,0,0,378,379,5,92,0,0,379,381,5,61,0,0, 380,329,1,0,0,0,380,335,1,0,0,0,380,343,1,0,0,0,380,348,1,0,0,0, 380,354,1,0,0,0,380,361,1,0,0,0,380,366,1,0,0,0,380,368,1,0,0,0, 380,370,1,0,0,0,380,372,1,0,0,0,380,374,1,0,0,0,380,376,1,0,0,0, 380,378,1,0,0,0,381,382,1,0,0,0,382,383,6,13,0,0,383,28,1,0,0,0, 384,385,5,43,0,0,385,30,1,0,0,0,386,387,5,45,0,0,387,32,1,0,0,0, 388,389,5,42,0,0,389,34,1,0,0,0,390,391,5,47,0,0,391,36,1,0,0,0, 392,393,5,40,0,0,393,38,1,0,0,0,394,395,5,41,0,0,395,40,1,0,0,0, 396,397,5,123,0,0,397,42,1,0,0,0,398,399,5,125,0,0,399,44,1,0,0, 0,400,401,5,92,0,0,401,402,5,123,0,0,402,46,1,0,0,0,403,404,5,92, 0,0,404,405,5,125,0,0,405,48,1,0,0,0,406,407,5,91,0,0,407,50,1,0, 0,0,408,409,5,93,0,0,409,52,1,0,0,0,410,411,5,124,0,0,411,54,1,0, 0,0,412,413,5,92,0,0,413,414,5,114,0,0,414,415,5,105,0,0,415,416, 5,103,0,0,416,417,5,104,0,0,417,418,5,116,0,0,418,419,5,124,0,0, 419,56,1,0,0,0,420,421,5,92,0,0,421,422,5,108,0,0,422,423,5,101, 0,0,423,424,5,102,0,0,424,425,5,116,0,0,425,426,5,124,0,0,426,58, 1,0,0,0,427,428,5,92,0,0,428,429,5,108,0,0,429,430,5,97,0,0,430, 431,5,110,0,0,431,432,5,103,0,0,432,433,5,108,0,0,433,434,5,101, 0,0,434,60,1,0,0,0,435,436,5,92,0,0,436,437,5,114,0,0,437,438,5, 97,0,0,438,439,5,110,0,0,439,440,5,103,0,0,440,441,5,108,0,0,441, 442,5,101,0,0,442,62,1,0,0,0,443,444,5,92,0,0,444,445,5,108,0,0, 445,446,5,105,0,0,446,447,5,109,0,0,447,64,1,0,0,0,448,449,5,92, 0,0,449,450,5,116,0,0,450,504,5,111,0,0,451,452,5,92,0,0,452,453, 5,114,0,0,453,454,5,105,0,0,454,455,5,103,0,0,455,456,5,104,0,0, 456,457,5,116,0,0,457,458,5,97,0,0,458,459,5,114,0,0,459,460,5,114, 0,0,460,461,5,111,0,0,461,504,5,119,0,0,462,463,5,92,0,0,463,464, 5,82,0,0,464,465,5,105,0,0,465,466,5,103,0,0,466,467,5,104,0,0,467, 468,5,116,0,0,468,469,5,97,0,0,469,470,5,114,0,0,470,471,5,114,0, 0,471,472,5,111,0,0,472,504,5,119,0,0,473,474,5,92,0,0,474,475,5, 108,0,0,475,476,5,111,0,0,476,477,5,110,0,0,477,478,5,103,0,0,478, 479,5,114,0,0,479,480,5,105,0,0,480,481,5,103,0,0,481,482,5,104, 0,0,482,483,5,116,0,0,483,484,5,97,0,0,484,485,5,114,0,0,485,486, 5,114,0,0,486,487,5,111,0,0,487,504,5,119,0,0,488,489,5,92,0,0,489, 490,5,76,0,0,490,491,5,111,0,0,491,492,5,110,0,0,492,493,5,103,0, 0,493,494,5,114,0,0,494,495,5,105,0,0,495,496,5,103,0,0,496,497, 5,104,0,0,497,498,5,116,0,0,498,499,5,97,0,0,499,500,5,114,0,0,500, 501,5,114,0,0,501,502,5,111,0,0,502,504,5,119,0,0,503,448,1,0,0, 0,503,451,1,0,0,0,503,462,1,0,0,0,503,473,1,0,0,0,503,488,1,0,0, 0,504,66,1,0,0,0,505,506,5,92,0,0,506,507,5,105,0,0,507,508,5,110, 0,0,508,521,5,116,0,0,509,510,5,92,0,0,510,511,5,105,0,0,511,512, 5,110,0,0,512,513,5,116,0,0,513,514,5,92,0,0,514,515,5,108,0,0,515, 516,5,105,0,0,516,517,5,109,0,0,517,518,5,105,0,0,518,519,5,116, 0,0,519,521,5,115,0,0,520,505,1,0,0,0,520,509,1,0,0,0,521,68,1,0, 0,0,522,523,5,92,0,0,523,524,5,115,0,0,524,525,5,117,0,0,525,526, 5,109,0,0,526,70,1,0,0,0,527,528,5,92,0,0,528,529,5,112,0,0,529, 530,5,114,0,0,530,531,5,111,0,0,531,532,5,100,0,0,532,72,1,0,0,0, 533,534,5,92,0,0,534,535,5,101,0,0,535,536,5,120,0,0,536,537,5,112, 0,0,537,74,1,0,0,0,538,539,5,92,0,0,539,540,5,108,0,0,540,541,5, 111,0,0,541,542,5,103,0,0,542,76,1,0,0,0,543,544,5,92,0,0,544,545, 5,108,0,0,545,546,5,103,0,0,546,78,1,0,0,0,547,548,5,92,0,0,548, 549,5,108,0,0,549,550,5,110,0,0,550,80,1,0,0,0,551,552,5,92,0,0, 552,553,5,115,0,0,553,554,5,105,0,0,554,555,5,110,0,0,555,82,1,0, 0,0,556,557,5,92,0,0,557,558,5,99,0,0,558,559,5,111,0,0,559,560, 5,115,0,0,560,84,1,0,0,0,561,562,5,92,0,0,562,563,5,116,0,0,563, 564,5,97,0,0,564,565,5,110,0,0,565,86,1,0,0,0,566,567,5,92,0,0,567, 568,5,99,0,0,568,569,5,115,0,0,569,570,5,99,0,0,570,88,1,0,0,0,571, 572,5,92,0,0,572,573,5,115,0,0,573,574,5,101,0,0,574,575,5,99,0, 0,575,90,1,0,0,0,576,577,5,92,0,0,577,578,5,99,0,0,578,579,5,111, 0,0,579,580,5,116,0,0,580,92,1,0,0,0,581,582,5,92,0,0,582,583,5, 97,0,0,583,584,5,114,0,0,584,585,5,99,0,0,585,586,5,115,0,0,586, 587,5,105,0,0,587,588,5,110,0,0,588,94,1,0,0,0,589,590,5,92,0,0, 590,591,5,97,0,0,591,592,5,114,0,0,592,593,5,99,0,0,593,594,5,99, 0,0,594,595,5,111,0,0,595,596,5,115,0,0,596,96,1,0,0,0,597,598,5, 92,0,0,598,599,5,97,0,0,599,600,5,114,0,0,600,601,5,99,0,0,601,602, 5,116,0,0,602,603,5,97,0,0,603,604,5,110,0,0,604,98,1,0,0,0,605, 606,5,92,0,0,606,607,5,97,0,0,607,608,5,114,0,0,608,609,5,99,0,0, 609,610,5,99,0,0,610,611,5,115,0,0,611,612,5,99,0,0,612,100,1,0, 0,0,613,614,5,92,0,0,614,615,5,97,0,0,615,616,5,114,0,0,616,617, 5,99,0,0,617,618,5,115,0,0,618,619,5,101,0,0,619,620,5,99,0,0,620, 102,1,0,0,0,621,622,5,92,0,0,622,623,5,97,0,0,623,624,5,114,0,0, 624,625,5,99,0,0,625,626,5,99,0,0,626,627,5,111,0,0,627,628,5,116, 0,0,628,104,1,0,0,0,629,630,5,92,0,0,630,631,5,115,0,0,631,632,5, 105,0,0,632,633,5,110,0,0,633,634,5,104,0,0,634,106,1,0,0,0,635, 636,5,92,0,0,636,637,5,99,0,0,637,638,5,111,0,0,638,639,5,115,0, 0,639,640,5,104,0,0,640,108,1,0,0,0,641,642,5,92,0,0,642,643,5,116, 0,0,643,644,5,97,0,0,644,645,5,110,0,0,645,646,5,104,0,0,646,110, 1,0,0,0,647,648,5,92,0,0,648,649,5,97,0,0,649,650,5,114,0,0,650, 651,5,115,0,0,651,652,5,105,0,0,652,653,5,110,0,0,653,654,5,104, 0,0,654,112,1,0,0,0,655,656,5,92,0,0,656,657,5,97,0,0,657,658,5, 114,0,0,658,659,5,99,0,0,659,660,5,111,0,0,660,661,5,115,0,0,661, 662,5,104,0,0,662,114,1,0,0,0,663,664,5,92,0,0,664,665,5,97,0,0, 665,666,5,114,0,0,666,667,5,116,0,0,667,668,5,97,0,0,668,669,5,110, 0,0,669,670,5,104,0,0,670,116,1,0,0,0,671,672,5,92,0,0,672,673,5, 108,0,0,673,674,5,102,0,0,674,675,5,108,0,0,675,676,5,111,0,0,676, 677,5,111,0,0,677,678,5,114,0,0,678,118,1,0,0,0,679,680,5,92,0,0, 680,681,5,114,0,0,681,682,5,102,0,0,682,683,5,108,0,0,683,684,5, 111,0,0,684,685,5,111,0,0,685,686,5,114,0,0,686,120,1,0,0,0,687, 688,5,92,0,0,688,689,5,108,0,0,689,690,5,99,0,0,690,691,5,101,0, 0,691,692,5,105,0,0,692,693,5,108,0,0,693,122,1,0,0,0,694,695,5, 92,0,0,695,696,5,114,0,0,696,697,5,99,0,0,697,698,5,101,0,0,698, 699,5,105,0,0,699,700,5,108,0,0,700,124,1,0,0,0,701,702,5,92,0,0, 702,703,5,115,0,0,703,704,5,113,0,0,704,705,5,114,0,0,705,706,5, 116,0,0,706,126,1,0,0,0,707,708,5,92,0,0,708,709,5,111,0,0,709,710, 5,118,0,0,710,711,5,101,0,0,711,712,5,114,0,0,712,713,5,108,0,0, 713,714,5,105,0,0,714,715,5,110,0,0,715,716,5,101,0,0,716,128,1, 0,0,0,717,718,5,92,0,0,718,719,5,116,0,0,719,720,5,105,0,0,720,721, 5,109,0,0,721,722,5,101,0,0,722,723,5,115,0,0,723,130,1,0,0,0,724, 725,5,92,0,0,725,726,5,99,0,0,726,727,5,100,0,0,727,728,5,111,0, 0,728,729,5,116,0,0,729,132,1,0,0,0,730,731,5,92,0,0,731,732,5,100, 0,0,732,733,5,105,0,0,733,734,5,118,0,0,734,134,1,0,0,0,735,736, 5,92,0,0,736,737,5,102,0,0,737,738,5,114,0,0,738,739,5,97,0,0,739, 753,5,99,0,0,740,741,5,92,0,0,741,742,5,100,0,0,742,743,5,102,0, 0,743,744,5,114,0,0,744,745,5,97,0,0,745,753,5,99,0,0,746,747,5, 92,0,0,747,748,5,116,0,0,748,749,5,102,0,0,749,750,5,114,0,0,750, 751,5,97,0,0,751,753,5,99,0,0,752,735,1,0,0,0,752,740,1,0,0,0,752, 746,1,0,0,0,753,136,1,0,0,0,754,755,5,92,0,0,755,756,5,98,0,0,756, 757,5,105,0,0,757,758,5,110,0,0,758,759,5,111,0,0,759,760,5,109, 0,0,760,138,1,0,0,0,761,762,5,92,0,0,762,763,5,100,0,0,763,764,5, 98,0,0,764,765,5,105,0,0,765,766,5,110,0,0,766,767,5,111,0,0,767, 768,5,109,0,0,768,140,1,0,0,0,769,770,5,92,0,0,770,771,5,116,0,0, 771,772,5,98,0,0,772,773,5,105,0,0,773,774,5,110,0,0,774,775,5,111, 0,0,775,776,5,109,0,0,776,142,1,0,0,0,777,778,5,92,0,0,778,779,5, 109,0,0,779,780,5,97,0,0,780,781,5,116,0,0,781,782,5,104,0,0,782, 783,5,105,0,0,783,784,5,116,0,0,784,144,1,0,0,0,785,786,5,95,0,0, 786,146,1,0,0,0,787,788,5,94,0,0,788,148,1,0,0,0,789,790,5,58,0, 0,790,150,1,0,0,0,791,792,7,0,0,0,792,152,1,0,0,0,793,797,5,100, 0,0,794,796,3,151,75,0,795,794,1,0,0,0,796,799,1,0,0,0,797,798,1, 0,0,0,797,795,1,0,0,0,798,807,1,0,0,0,799,797,1,0,0,0,800,808,7, 1,0,0,801,803,5,92,0,0,802,804,7,1,0,0,803,802,1,0,0,0,804,805,1, 0,0,0,805,803,1,0,0,0,805,806,1,0,0,0,806,808,1,0,0,0,807,800,1, 0,0,0,807,801,1,0,0,0,808,154,1,0,0,0,809,810,7,1,0,0,810,156,1, 0,0,0,811,812,7,2,0,0,812,158,1,0,0,0,813,817,5,38,0,0,814,816,3, 151,75,0,815,814,1,0,0,0,816,819,1,0,0,0,817,818,1,0,0,0,817,815, 1,0,0,0,818,821,1,0,0,0,819,817,1,0,0,0,820,813,1,0,0,0,820,821, 1,0,0,0,821,822,1,0,0,0,822,834,5,61,0,0,823,831,5,61,0,0,824,826, 3,151,75,0,825,824,1,0,0,0,826,829,1,0,0,0,827,828,1,0,0,0,827,825, 1,0,0,0,828,830,1,0,0,0,829,827,1,0,0,0,830,832,5,38,0,0,831,827, 1,0,0,0,831,832,1,0,0,0,832,834,1,0,0,0,833,820,1,0,0,0,833,823, 1,0,0,0,834,160,1,0,0,0,835,836,5,92,0,0,836,837,5,110,0,0,837,838, 5,101,0,0,838,839,5,113,0,0,839,162,1,0,0,0,840,841,5,60,0,0,841, 164,1,0,0,0,842,843,5,92,0,0,843,844,5,108,0,0,844,845,5,101,0,0, 845,852,5,113,0,0,846,847,5,92,0,0,847,848,5,108,0,0,848,852,5,101, 0,0,849,852,3,167,83,0,850,852,3,169,84,0,851,842,1,0,0,0,851,846, 1,0,0,0,851,849,1,0,0,0,851,850,1,0,0,0,852,166,1,0,0,0,853,854, 5,92,0,0,854,855,5,108,0,0,855,856,5,101,0,0,856,857,5,113,0,0,857, 858,5,113,0,0,858,168,1,0,0,0,859,860,5,92,0,0,860,861,5,108,0,0, 861,862,5,101,0,0,862,863,5,113,0,0,863,864,5,115,0,0,864,865,5, 108,0,0,865,866,5,97,0,0,866,867,5,110,0,0,867,868,5,116,0,0,868, 170,1,0,0,0,869,870,5,62,0,0,870,172,1,0,0,0,871,872,5,92,0,0,872, 873,5,103,0,0,873,874,5,101,0,0,874,881,5,113,0,0,875,876,5,92,0, 0,876,877,5,103,0,0,877,881,5,101,0,0,878,881,3,175,87,0,879,881, 3,177,88,0,880,871,1,0,0,0,880,875,1,0,0,0,880,878,1,0,0,0,880,879, 1,0,0,0,881,174,1,0,0,0,882,883,5,92,0,0,883,884,5,103,0,0,884,885, 5,101,0,0,885,886,5,113,0,0,886,887,5,113,0,0,887,176,1,0,0,0,888, 889,5,92,0,0,889,890,5,103,0,0,890,891,5,101,0,0,891,892,5,113,0, 0,892,893,5,115,0,0,893,894,5,108,0,0,894,895,5,97,0,0,895,896,5, 110,0,0,896,897,5,116,0,0,897,178,1,0,0,0,898,899,5,33,0,0,899,180, 1,0,0,0,900,902,5,39,0,0,901,900,1,0,0,0,902,903,1,0,0,0,903,901, 1,0,0,0,903,904,1,0,0,0,904,182,1,0,0,0,905,907,5,92,0,0,906,908, 7,1,0,0,907,906,1,0,0,0,908,909,1,0,0,0,909,907,1,0,0,0,909,910, 1,0,0,0,910,184,1,0,0,0,22,0,192,208,223,240,276,380,503,520,752, 797,805,807,817,820,827,831,833,851,880,903,909,1,6,0,0 ]
class LaTeXLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
T__0 = 1 T__1 = 2 WS = 3 THINSPACE = 4 MEDSPACE = 5 THICKSPACE = 6 QUAD = 7 QQUAD = 8 NEGTHINSPACE = 9 NEGMEDSPACE = 10 NEGTHICKSPACE = 11 CMD_LEFT = 12 CMD_RIGHT = 13 IGNORE = 14 ADD = 15 SUB = 16 MUL = 17 DIV = 18 L_PAREN = 19 R_PAREN = 20 L_BRACE = 21 R_BRACE = 22 L_BRACE_LITERAL = 23 R_BRACE_LITERAL = 24 L_BRACKET = 25 R_BRACKET = 26 BAR = 27 R_BAR = 28 L_BAR = 29 L_ANGLE = 30 R_ANGLE = 31 FUNC_LIM = 32 LIM_APPROACH_SYM = 33 FUNC_INT = 34 FUNC_SUM = 35 FUNC_PROD = 36 FUNC_EXP = 37 FUNC_LOG = 38 FUNC_LG = 39 FUNC_LN = 40 FUNC_SIN = 41 FUNC_COS = 42 FUNC_TAN = 43 FUNC_CSC = 44 FUNC_SEC = 45 FUNC_COT = 46 FUNC_ARCSIN = 47 FUNC_ARCCOS = 48 FUNC_ARCTAN = 49 FUNC_ARCCSC = 50 FUNC_ARCSEC = 51 FUNC_ARCCOT = 52 FUNC_SINH = 53 FUNC_COSH = 54 FUNC_TANH = 55 FUNC_ARSINH = 56 FUNC_ARCOSH = 57 FUNC_ARTANH = 58 L_FLOOR = 59 R_FLOOR = 60 L_CEIL = 61 R_CEIL = 62 FUNC_SQRT = 63 FUNC_OVERLINE = 64 CMD_TIMES = 65 CMD_CDOT = 66 CMD_DIV = 67 CMD_FRAC = 68 CMD_BINOM = 69 CMD_DBINOM = 70 CMD_TBINOM = 71 CMD_MATHIT = 72 UNDERSCORE = 73 CARET = 74 COLON = 75 DIFFERENTIAL = 76 LETTER = 77 DIGIT = 78 EQUAL = 79 NEQ = 80 LT = 81 LTE = 82 LTE_Q = 83 LTE_S = 84 GT = 85 GTE = 86 GTE_Q = 87 GTE_S = 88 BANG = 89 SINGLE_QUOTES = 90 SYMBOL = 91
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>", "','", "'.'", "'\\quad'", "'\\qquad'", "'\\negmedspace'", "'\\negthickspace'", "'\\left'", "'\\right'", "'+'", "'-'", "'*'", "'/'", "'('", "')'", "'{'", "'}'", "'\\{'", "'\\}'", "'['", "']'", "'|'", "'\\right|'", "'\\left|'", "'\\langle'", "'\\rangle'", "'\\lim'", "'\\sum'", "'\\prod'", "'\\exp'", "'\\log'", "'\\lg'", "'\\ln'", "'\\sin'", "'\\cos'", "'\\tan'", "'\\csc'", "'\\sec'", "'\\cot'", "'\\arcsin'", "'\\arccos'", "'\\arctan'", "'\\arccsc'", "'\\arcsec'", "'\\arccot'", "'\\sinh'", "'\\cosh'", "'\\tanh'", "'\\arsinh'", "'\\arcosh'", "'\\artanh'", "'\\lfloor'", "'\\rfloor'", "'\\lceil'", "'\\rceil'", "'\\sqrt'", "'\\overline'", "'\\times'", "'\\cdot'", "'\\div'", "'\\binom'", "'\\dbinom'", "'\\tbinom'", "'\\mathit'", "'_'", "'^'", "':'", "'\\neq'", "'<'", "'\\leqq'", "'\\leqslant'", "'>'", "'\\geqq'", "'\\geqslant'", "'!'" ]
symbolicNames = [ "<INVALID>", "WS", "THINSPACE", "MEDSPACE", "THICKSPACE", "QUAD", "QQUAD", "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT", "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN", "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL", "L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR", "L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM", "FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG", "FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN", "FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN", "FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC", "FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH", "FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR", "L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES", "CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM", "CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON", "DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT", "LTE", "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES", "SYMBOL" ]
ruleNames = [ "T__0", "T__1", "WS", "THINSPACE", "MEDSPACE", "THICKSPACE", "QUAD", "QQUAD", "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT", "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN", "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL", "L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR", "L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM", "FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG", "FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN", "FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN", "FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC", "FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH", "FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR", "L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES", "CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM", "CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON", "WS_CHAR", "DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT", "LTE", "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES", "SYMBOL" ]
grammarFileName = "LaTeX.g4"
def __init__(self, input=None, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.11.1") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import osimport subprocessimport glob
from sympy.utilities.misc import debug
here = os.path.dirname(__file__)grammar_file = os.path.abspath(os.path.join(here, "LaTeX.g4"))dir_latex_antlr = os.path.join(here, "_antlr")
header = '''\# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***## Generated from ../LaTeX.g4, derived from latex2sympy# latex2sympy is licensed under the MIT license# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt## Generated with antlr4# antlr4 is licensed under the BSD-3-Clause License# https://github.com/antlr/antlr4/blob/master/LICENSE.txt'''
def check_antlr_version(): debug("Checking antlr4 version...")
try: debug(subprocess.check_output(["antlr4"]) .decode('utf-8').split("\n")[0]) return True except (subprocess.CalledProcessError, FileNotFoundError): debug("The 'antlr4' command line tool is not installed, " "or not on your PATH.\n" "> Please refer to the README.md file for more information.") return False
def build_parser(output_dir=dir_latex_antlr): check_antlr_version()
debug("Updating ANTLR-generated code in {}".format(output_dir))
if not os.path.exists(output_dir): os.makedirs(output_dir)
with open(os.path.join(output_dir, "__init__.py"), "w+") as fp: fp.write(header)
args = [ "antlr4", grammar_file, "-o", output_dir, # for now, not generating these as latex2sympy did not use them "-no-visitor", "-no-listener", ]
debug("Running code generation...\n\t$ {}".format(" ".join(args))) subprocess.check_output(args, cwd=output_dir)
debug("Applying headers, removing unnecessary files and renaming...") # Handle case insensitive file systems. If the files are already # generated, they will be written to latex* but LaTeX*.* won't match them. for path in (glob.glob(os.path.join(output_dir, "LaTeX*.*")) or glob.glob(os.path.join(output_dir, "latex*.*"))):
# Remove files ending in .interp or .tokens as they are not needed. if not path.endswith(".py"): os.unlink(path) continue
new_path = os.path.join(output_dir, os.path.basename(path).lower()) with open(path, 'r') as f: lines = [line.rstrip() + '\n' for line in f]
os.unlink(path)
with open(new_path, "w") as out_file: offset = 0 while lines[offset].startswith('#'): offset += 1 out_file.write(header) out_file.writelines(lines[offset:])
debug("\t{}".format(new_path))
return True
if __name__ == "__main__": build_parser()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607# Ported from latex2sympy by @augustt198# https://github.com/augustt198/latex2sympy# See license in LICENSE.txtfrom importlib.metadata import versionimport sympyfrom sympy.external import import_modulefrom sympy.printing.str import StrPrinterfrom sympy.physics.quantum.state import Bra, Ket
from .errors import LaTeXParsingError
LaTeXParser = LaTeXLexer = MathErrorListener = None
try: LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser', import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer', import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexerexcept Exception: pass
ErrorListener = import_module('antlr4.error.ErrorListener', warn_not_installed=True, import_kwargs={'fromlist': ['ErrorListener']} )
if ErrorListener: class MathErrorListener(ErrorListener.ErrorListener): # type:ignore # noqa:F811 def __init__(self, src): super(ErrorListener.ErrorListener, self).__init__() self.src = src
def syntaxError(self, recog, symbol, line, col, msg, e): fmt = "%s\n%s\n%s" marker = "~" * col + "^"
if msg.startswith("missing"): err = fmt % (msg, self.src, marker) elif msg.startswith("no viable"): err = fmt % ("I expected something else here", self.src, marker) elif msg.startswith("mismatched"): names = LaTeXParser.literalNames expected = [ names[i] for i in e.getExpectedTokens() if i < len(names) ] if len(expected) < 10: expected = " ".join(expected) err = (fmt % ("I expected one of these: " + expected, self.src, marker)) else: err = (fmt % ("I expected something else here", self.src, marker)) else: err = fmt % ("I don't understand this", self.src, marker) raise LaTeXParsingError(err)
def parse_latex(sympy, strict=False): antlr4 = import_module('antlr4')
if None in [antlr4, MathErrorListener] or \ not version('antlr4-python3-runtime').startswith('4.11'): raise ImportError("LaTeX parsing requires the antlr4 Python package," " provided by pip (antlr4-python3-runtime) or" " conda (antlr-python-runtime), version 4.11")
sympy = sympy.strip() matherror = MathErrorListener(sympy)
stream = antlr4.InputStream(sympy) lex = LaTeXLexer(stream) lex.removeErrorListeners() lex.addErrorListener(matherror)
tokens = antlr4.CommonTokenStream(lex) parser = LaTeXParser(tokens)
# remove default console error listener parser.removeErrorListeners() parser.addErrorListener(matherror)
relation = parser.math().relation() if strict and (relation.start.start != 0 or relation.stop.stop != len(sympy) - 1): raise LaTeXParsingError("Invalid LaTeX") expr = convert_relation(relation)
return expr
def convert_relation(rel): if rel.expr(): return convert_expr(rel.expr())
lh = convert_relation(rel.relation(0)) rh = convert_relation(rel.relation(1)) if rel.LT(): return sympy.StrictLessThan(lh, rh) elif rel.LTE(): return sympy.LessThan(lh, rh) elif rel.GT(): return sympy.StrictGreaterThan(lh, rh) elif rel.GTE(): return sympy.GreaterThan(lh, rh) elif rel.EQUAL(): return sympy.Eq(lh, rh) elif rel.NEQ(): return sympy.Ne(lh, rh)
def convert_expr(expr): return convert_add(expr.additive())
def convert_add(add): if add.ADD(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) return sympy.Add(lh, rh, evaluate=False) elif add.SUB(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) if hasattr(rh, "is_Atom") and rh.is_Atom: return sympy.Add(lh, -1 * rh, evaluate=False) return sympy.Add(lh, sympy.Mul(-1, rh, evaluate=False), evaluate=False) else: return convert_mp(add.mp())
def convert_mp(mp): if hasattr(mp, 'mp'): mp_left = mp.mp(0) mp_right = mp.mp(1) else: mp_left = mp.mp_nofunc(0) mp_right = mp.mp_nofunc(1)
if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, rh, evaluate=False) elif mp.DIV() or mp.CMD_DIV() or mp.COLON(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False) else: if hasattr(mp, 'unary'): return convert_unary(mp.unary()) else: return convert_unary(mp.unary_nofunc())
def convert_unary(unary): if hasattr(unary, 'unary'): nested_unary = unary.unary() else: nested_unary = unary.unary_nofunc() if hasattr(unary, 'postfix_nofunc'): first = unary.postfix() tail = unary.postfix_nofunc() postfix = [first] + tail else: postfix = unary.postfix()
if unary.ADD(): return convert_unary(nested_unary) elif unary.SUB(): numabs = convert_unary(nested_unary) # Use Integer(-n) instead of Mul(-1, n) return -numabs elif postfix: return convert_postfix_list(postfix)
def convert_postfix_list(arr, i=0): if i >= len(arr): raise LaTeXParsingError("Index out of bounds")
res = convert_postfix(arr[i]) if isinstance(res, sympy.Expr): if i == len(arr) - 1: return res # nothing to multiply by else: if i > 0: left = convert_postfix(arr[i - 1]) right = convert_postfix(arr[i + 1]) if isinstance(left, sympy.Expr) and isinstance( right, sympy.Expr): left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol) right_syms = convert_postfix(arr[i + 1]).atoms( sympy.Symbol) # if the left and right sides contain no variables and the # symbol in between is 'x', treat as multiplication. if not (left_syms or right_syms) and str(res) == 'x': return convert_postfix_list(arr, i + 1) # multiply by next return sympy.Mul( res, convert_postfix_list(arr, i + 1), evaluate=False) else: # must be derivative wrt = res[0] if i == len(arr) - 1: raise LaTeXParsingError("Expected expression for derivative") else: expr = convert_postfix_list(arr, i + 1) return sympy.Derivative(expr, wrt)
def do_subs(expr, at): if at.expr(): at_expr = convert_expr(at.expr()) syms = at_expr.atoms(sympy.Symbol) if len(syms) == 0: return expr elif len(syms) > 0: sym = next(iter(syms)) return expr.subs(sym, at_expr) elif at.equality(): lh = convert_expr(at.equality().expr(0)) rh = convert_expr(at.equality().expr(1)) return expr.subs(lh, rh)
def convert_postfix(postfix): if hasattr(postfix, 'exp'): exp_nested = postfix.exp() else: exp_nested = postfix.exp_nofunc()
exp = convert_exp(exp_nested) for op in postfix.postfix_op(): if op.BANG(): if isinstance(exp, list): raise LaTeXParsingError("Cannot apply postfix to derivative") exp = sympy.factorial(exp, evaluate=False) elif op.eval_at(): ev = op.eval_at() at_b = None at_a = None if ev.eval_at_sup(): at_b = do_subs(exp, ev.eval_at_sup()) if ev.eval_at_sub(): at_a = do_subs(exp, ev.eval_at_sub()) if at_b is not None and at_a is not None: exp = sympy.Add(at_b, -1 * at_a, evaluate=False) elif at_b is not None: exp = at_b elif at_a is not None: exp = at_a
return exp
def convert_exp(exp): if hasattr(exp, 'exp'): exp_nested = exp.exp() else: exp_nested = exp.exp_nofunc()
if exp_nested: base = convert_exp(exp_nested) if isinstance(base, list): raise LaTeXParsingError("Cannot raise derivative to power") if exp.atom(): exponent = convert_atom(exp.atom()) elif exp.expr(): exponent = convert_expr(exp.expr()) return sympy.Pow(base, exponent, evaluate=False) else: if hasattr(exp, 'comp'): return convert_comp(exp.comp()) else: return convert_comp(exp.comp_nofunc())
def convert_comp(comp): if comp.group(): return convert_expr(comp.group().expr()) elif comp.abs_group(): return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False) elif comp.atom(): return convert_atom(comp.atom()) elif comp.floor(): return convert_floor(comp.floor()) elif comp.ceil(): return convert_ceil(comp.ceil()) elif comp.func(): return convert_func(comp.func())
def convert_atom(atom): if atom.LETTER(): sname = atom.LETTER().getText() if atom.subexpr(): if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) sname += '_{' + StrPrinter().doprint(subscript) + '}' if atom.SINGLE_QUOTES(): sname += atom.SINGLE_QUOTES().getText() # put after subscript for easy identify return sympy.Symbol(sname) elif atom.SYMBOL(): s = atom.SYMBOL().getText()[1:] if s == "infty": return sympy.oo else: if atom.subexpr(): subscript = None if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) s += '_{' + subscriptName + '}' return sympy.Symbol(s) elif atom.number(): s = atom.number().getText().replace(",", "") return sympy.Number(s) elif atom.DIFFERENTIAL(): var = get_differential_var(atom.DIFFERENTIAL()) return sympy.Symbol('d' + var.name) elif atom.mathit(): text = rule2text(atom.mathit().mathit_text()) return sympy.Symbol(text) elif atom.frac(): return convert_frac(atom.frac()) elif atom.binom(): return convert_binom(atom.binom()) elif atom.bra(): val = convert_expr(atom.bra().expr()) return Bra(val) elif atom.ket(): val = convert_expr(atom.ket().expr()) return Ket(val)
def rule2text(ctx): stream = ctx.start.getInputStream() # starting index of starting token startIdx = ctx.start.start # stopping index of stopping token stopIdx = ctx.stop.stop
return stream.getText(startIdx, stopIdx)
def convert_frac(frac): diff_op = False partial_op = False if frac.lower and frac.upper: lower_itv = frac.lower.getSourceInterval() lower_itv_len = lower_itv[1] - lower_itv[0] + 1 if (frac.lower.start == frac.lower.stop and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL): wrt = get_differential_var_str(frac.lower.start.text) diff_op = True elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL and frac.lower.start.text == '\\partial' and (frac.lower.stop.type == LaTeXLexer.LETTER or frac.lower.stop.type == LaTeXLexer.SYMBOL)): partial_op = True wrt = frac.lower.stop.text if frac.lower.stop.type == LaTeXLexer.SYMBOL: wrt = wrt[1:]
if diff_op or partial_op: wrt = sympy.Symbol(wrt) if (diff_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.LETTER and frac.upper.start.text == 'd'): return [wrt] elif (partial_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.SYMBOL and frac.upper.start.text == '\\partial'): return [wrt] upper_text = rule2text(frac.upper)
expr_top = None if diff_op and upper_text.startswith('d'): expr_top = parse_latex(upper_text[1:]) elif partial_op and frac.upper.start.text == '\\partial': expr_top = parse_latex(upper_text[len('\\partial'):]) if expr_top: return sympy.Derivative(expr_top, wrt) if frac.upper: expr_top = convert_expr(frac.upper) else: expr_top = sympy.Number(frac.upperd.text) if frac.lower: expr_bot = convert_expr(frac.lower) else: expr_bot = sympy.Number(frac.lowerd.text) inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False) if expr_top == 1: return inverse_denom else: return sympy.Mul(expr_top, inverse_denom, evaluate=False)
def convert_binom(binom): expr_n = convert_expr(binom.n) expr_k = convert_expr(binom.k) return sympy.binomial(expr_n, expr_k, evaluate=False)
def convert_floor(floor): val = convert_expr(floor.val) return sympy.floor(val, evaluate=False)
def convert_ceil(ceil): val = convert_expr(ceil.val) return sympy.ceiling(val, evaluate=False)
def convert_func(func): if func.func_normal(): if func.L_PAREN(): # function called with parenthesis arg = convert_func_arg(func.func_arg()) else: arg = convert_func_arg(func.func_arg_noparens())
name = func.func_normal().start.text[1:]
# change arc<trig> -> a<trig> if name in [ "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot" ]: name = "a" + name[3:] expr = getattr(sympy.functions, name)(arg, evaluate=False) if name in ["arsinh", "arcosh", "artanh"]: name = "a" + name[2:] expr = getattr(sympy.functions, name)(arg, evaluate=False)
if name == "exp": expr = sympy.exp(arg, evaluate=False)
if name in ("log", "lg", "ln"): if func.subexpr(): if func.subexpr().expr(): base = convert_expr(func.subexpr().expr()) else: base = convert_atom(func.subexpr().atom()) elif name == "lg": # ISO 80000-2:2019 base = 10 elif name in ("ln", "log"): # SymPy's latex printer prints ln as log by default base = sympy.E expr = sympy.log(arg, base, evaluate=False)
func_pow = None should_pow = True if func.supexpr(): if func.supexpr().expr(): func_pow = convert_expr(func.supexpr().expr()) else: func_pow = convert_atom(func.supexpr().atom())
if name in [ "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh", "tanh" ]: if func_pow == -1: name = "a" + name should_pow = False expr = getattr(sympy.functions, name)(arg, evaluate=False)
if func_pow and should_pow: expr = sympy.Pow(expr, func_pow, evaluate=False)
return expr elif func.LETTER() or func.SYMBOL(): if func.LETTER(): fname = func.LETTER().getText() elif func.SYMBOL(): fname = func.SYMBOL().getText()[1:] fname = str(fname) # can't be unicode if func.subexpr(): if func.subexpr().expr(): # subscript is expr subscript = convert_expr(func.subexpr().expr()) else: # subscript is atom subscript = convert_atom(func.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) fname += '_{' + subscriptName + '}' if func.SINGLE_QUOTES(): fname += func.SINGLE_QUOTES().getText() input_args = func.args() output_args = [] while input_args.args(): # handle multiple arguments to function output_args.append(convert_expr(input_args.expr())) input_args = input_args.args() output_args.append(convert_expr(input_args.expr())) return sympy.Function(fname)(*output_args) elif func.FUNC_INT(): return handle_integral(func) elif func.FUNC_SQRT(): expr = convert_expr(func.base) if func.root: r = convert_expr(func.root) return sympy.root(expr, r, evaluate=False) else: return sympy.sqrt(expr, evaluate=False) elif func.FUNC_OVERLINE(): expr = convert_expr(func.base) return sympy.conjugate(expr, evaluate=False) elif func.FUNC_SUM(): return handle_sum_or_prod(func, "summation") elif func.FUNC_PROD(): return handle_sum_or_prod(func, "product") elif func.FUNC_LIM(): return handle_limit(func)
def convert_func_arg(arg): if hasattr(arg, 'expr'): return convert_expr(arg.expr()) else: return convert_mp(arg.mp_nofunc())
def handle_integral(func): if func.additive(): integrand = convert_add(func.additive()) elif func.frac(): integrand = convert_frac(func.frac()) else: integrand = 1
int_var = None if func.DIFFERENTIAL(): int_var = get_differential_var(func.DIFFERENTIAL()) else: for sym in integrand.atoms(sympy.Symbol): s = str(sym) if len(s) > 1 and s[0] == 'd': if s[1] == '\\': int_var = sympy.Symbol(s[2:]) else: int_var = sympy.Symbol(s[1:]) int_sym = sym if int_var: integrand = integrand.subs(int_sym, 1) else: # Assume dx by default int_var = sympy.Symbol('x')
if func.subexpr(): if func.subexpr().atom(): lower = convert_atom(func.subexpr().atom()) else: lower = convert_expr(func.subexpr().expr()) if func.supexpr().atom(): upper = convert_atom(func.supexpr().atom()) else: upper = convert_expr(func.supexpr().expr()) return sympy.Integral(integrand, (int_var, lower, upper)) else: return sympy.Integral(integrand, int_var)
def handle_sum_or_prod(func, name): val = convert_mp(func.mp()) iter_var = convert_expr(func.subeq().equality().expr(0)) start = convert_expr(func.subeq().equality().expr(1)) if func.supexpr().expr(): # ^{expr} end = convert_expr(func.supexpr().expr()) else: # ^atom end = convert_atom(func.supexpr().atom())
if name == "summation": return sympy.Sum(val, (iter_var, start, end)) elif name == "product": return sympy.Product(val, (iter_var, start, end))
def handle_limit(func): sub = func.limit_sub() if sub.LETTER(): var = sympy.Symbol(sub.LETTER().getText()) elif sub.SYMBOL(): var = sympy.Symbol(sub.SYMBOL().getText()[1:]) else: var = sympy.Symbol('x') if sub.SUB(): direction = "-" elif sub.ADD(): direction = "+" else: direction = "+-" approaching = convert_expr(sub.expr()) content = convert_mp(func.mp())
return sympy.Limit(content, var, approaching, direction)
def get_differential_var(d): text = get_differential_var_str(d.getText()) return sympy.Symbol(text)
def get_differential_var_str(text): for i in range(1, len(text)): c = text[i] if not (c == " " or c == "\r" or c == "\n" or c == "\t"): idx = i break text = text[idx:] if text[0] == "\\": text = text[1:] return text12class LaTeXParsingError(Exception): pass12from .latex_parser import parse_latex_lark, LarkLaTeXParser # noqafrom .transformer import TransformToSymPyExpr # noqa12345678910111213141516171819202122232425262728// Greek symbols// TODO: Shouold we include the uppercase variants for the symbols where the uppercase variant doesn't have a separate meaning?ALPHA: "\\alpha"BETA: "\\beta"GAMMA: "\\gamma"DELTA: "\\delta" // TODO: Should this be included? Delta usually denotes other things.EPSILON: "\\epsilon" | "\\varepsilon"ZETA: "\\zeta"ETA: "\\eta"THETA: "\\theta" | "\\vartheta"// TODO: Should I add iota to the list?KAPPA: "\\kappa"LAMBDA: "\\lambda" // TODO: What about the uppercase variant?MU: "\\mu"NU: "\\nu"XI: "\\xi"// TODO: Should there be a separate note for transforming \pi into sympy.pi?RHO: "\\rho" | "\\varrho"// TODO: What should we do about sigma?TAU: "\\tau"UPSILON: "\\upsilon"PHI: "\\phi" | "\\varphi"CHI: "\\chi"PSI: "\\psi"OMEGA: "\\omega"
GREEK_SYMBOL: ALPHA | BETA | GAMMA | DELTA | EPSILON | ZETA | ETA | THETA | KAPPA | LAMBDA | MU | NU | XI | RHO | TAU | UPSILON | PHI | CHI | PSI | OMEGA123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403%ignore /[ \t\n\r]+/
%ignore "\\," | "\\thinspace" | "\\:" | "\\medspace" | "\\;" | "\\thickspace"%ignore "\\quad" | "\\qquad"%ignore "\\!" | "\\negthinspace" | "\\negmedspace" | "\\negthickspace"%ignore "\\vrule" | "\\vcenter" | "\\vbox" | "\\vskip" | "\\vspace" | "\\hfill"%ignore "\\*" | "\\-" | "\\." | "\\/" | "\\(" | "\\="
%ignore "\\left" | "\\right"%ignore "\\limits" | "\\nolimits"%ignore "\\displaystyle"
///////////////////// tokens ///////////////////////
// basic binary operatorsADD: "+"SUB: "-"MUL: "*"DIV: "/"
// tokens with distinct left and right symbolsL_BRACE: "{"R_BRACE: "}"L_BRACE_LITERAL: "\\{"R_BRACE_LITERAL: "\\}"L_BRACKET: "["R_BRACKET: "]"L_CEIL: "\\lceil"R_CEIL: "\\rceil"L_FLOOR: "\\lfloor"R_FLOOR: "\\rfloor"L_PAREN: "("R_PAREN: ")"
// limit, integral, sum, and product symbolsFUNC_LIM: "\\lim"LIM_APPROACH_SYM: "\\to" | "\\rightarrow" | "\\Rightarrow" | "\\longrightarrow" | "\\Longrightarrow"FUNC_INT: "\\int" | "\\intop"FUNC_SUM: "\\sum"FUNC_PROD: "\\prod"
// common functionsFUNC_EXP: "\\exp"FUNC_LOG: "\\log"FUNC_LN: "\\ln"FUNC_LG: "\\lg"FUNC_MIN: "\\min"FUNC_MAX: "\\max"
// trigonometric functionsFUNC_SIN: "\\sin"FUNC_COS: "\\cos"FUNC_TAN: "\\tan"FUNC_CSC: "\\csc"FUNC_SEC: "\\sec"FUNC_COT: "\\cot"
// inverse trigonometric functionsFUNC_ARCSIN: "\\arcsin"FUNC_ARCCOS: "\\arccos"FUNC_ARCTAN: "\\arctan"FUNC_ARCCSC: "\\arccsc"FUNC_ARCSEC: "\\arcsec"FUNC_ARCCOT: "\\arccot"
// hyperbolic trigonometric functionsFUNC_SINH: "\\sinh"FUNC_COSH: "\\cosh"FUNC_TANH: "\\tanh"FUNC_ARSINH: "\\arsinh"FUNC_ARCOSH: "\\arcosh"FUNC_ARTANH: "\\artanh"
FUNC_SQRT: "\\sqrt"
// miscellaneous symbolsCMD_TIMES: "\\times"CMD_CDOT: "\\cdot"CMD_DIV: "\\div"CMD_FRAC: "\\frac" | "\\dfrac" | "\\tfrac" | "\\nicefrac"CMD_BINOM: "\\binom" | "\\dbinom" | "\\tbinom"CMD_OVERLINE: "\\overline"CMD_LANGLE: "\\langle"CMD_RANGLE: "\\rangle"
CMD_MATHIT: "\\mathit"
CMD_INFTY: "\\infty"
BANG: "!"BAR: "|"CARET: "^"COLON: ":"UNDERSCORE: "_"
// relational symbolsEQUAL: "="NOT_EQUAL: "\\neq" | "\\ne"LT: "<"LTE: "\\leq" | "\\le" | "\\leqslant"GT: ">"GTE: "\\geq" | "\\ge" | "\\geqslant"
DIV_SYMBOL: CMD_DIV | DIVMUL_SYMBOL: MUL | CMD_TIMES | CMD_CDOT
%import .greek_symbols.GREEK_SYMBOL
UPRIGHT_DIFFERENTIAL_SYMBOL: "\\text{d}" | "\\mathrm{d}"DIFFERENTIAL_SYMBOL: "d" | UPRIGHT_DIFFERENTIAL_SYMBOL
// disallow "d" as a variable name because we want to parse "d" as a differential symbol.SYMBOL: /[a-zA-Z]'*/GREEK_SYMBOL_WITH_PRIMES: GREEK_SYMBOL "'"*LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT: /([a-zA-Z]'*)_(([A-Za-z0-9]|[a-zA-Z]+)|\{([A-Za-z0-9]|[a-zA-Z]+'*)\})/LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT: /([a-zA-Z]'*)_/ GREEK_SYMBOL | /([a-zA-Z]'*)_/ L_BRACE GREEK_SYMBOL_WITH_PRIMES R_BRACE// best to define the variant with braces like that instead of shoving it all into one case like in// /([a-zA-Z])_/ L_BRACE? GREEK_SYMBOL R_BRACE? because then we can easily error out on input like// r"h_{\theta"GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT: GREEK_SYMBOL_WITH_PRIMES /_(([A-Za-z0-9]|[a-zA-Z]+)|\{([A-Za-z0-9]|[a-zA-Z]+'*)\})/GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT: GREEK_SYMBOL_WITH_PRIMES /_/ (GREEK_SYMBOL | L_BRACE GREEK_SYMBOL_WITH_PRIMES R_BRACE)MULTI_LETTER_SYMBOL: /[a-zA-Z]+(\s+[a-zA-Z]+)*'*/
%import common.DIGIT -> DIGIT
CMD_PRIME: "\\prime"CMD_ASTERISK: "\\ast"
PRIMES: "'"+STARS: "*"+PRIMES_VIA_CMD: CMD_PRIME+STARS_VIA_CMD: CMD_ASTERISK+
CMD_IMAGINARY_UNIT: "\\imaginaryunit"
CMD_BEGIN: "\\begin"CMD_END: "\\end"
// matricesIGNORE_L: /[ \t\n\r]*/ L_BRACE* /[ \t\n\r]*/IGNORE_R: /[ \t\n\r]*/ R_BRACE* /[ \t\n\r]*/ARRAY_MATRIX_BEGIN: L_BRACE "array" R_BRACE L_BRACE /[^}]*/ R_BRACEARRAY_MATRIX_END: L_BRACE "array" R_BRACEAMSMATH_MATRIX: L_BRACE "matrix" R_BRACEAMSMATH_PMATRIX: L_BRACE "pmatrix" R_BRACEAMSMATH_BMATRIX: L_BRACE "bmatrix" R_BRACE// Without the (L|R)_PARENs and (L|R)_BRACKETs, a matrix defined using// \begin{array}...\end{array} or \begin{matrix}...\end{matrix} must// not qualify as a complete matrix expression; this is done so that// if we have \begin{array}...\end{array} or \begin{matrix}...\end{matrix}// between BAR pairs, then they should be interpreted as determinants as// opposed to sympy.Abs (absolute value) applied to a matrix.CMD_BEGIN_AMSPMATRIX_AMSBMATRIX: CMD_BEGIN (AMSMATH_PMATRIX | AMSMATH_BMATRIX)CMD_BEGIN_ARRAY_AMSMATRIX: (L_PAREN | L_BRACKET) IGNORE_L CMD_BEGIN (ARRAY_MATRIX_BEGIN | AMSMATH_MATRIX)CMD_MATRIX_BEGIN: CMD_BEGIN_AMSPMATRIX_AMSBMATRIX | CMD_BEGIN_ARRAY_AMSMATRIXCMD_END_AMSPMATRIX_AMSBMATRIX: CMD_END (AMSMATH_PMATRIX | AMSMATH_BMATRIX)CMD_END_ARRAY_AMSMATRIX: CMD_END (ARRAY_MATRIX_END | AMSMATH_MATRIX) IGNORE_R "\\right"? (R_PAREN | R_BRACKET)CMD_MATRIX_END: CMD_END_AMSPMATRIX_AMSBMATRIX | CMD_END_ARRAY_AMSMATRIXMATRIX_COL_DELIM: "&"MATRIX_ROW_DELIM: "\\\\"FUNC_MATRIX_TRACE: "\\trace"FUNC_MATRIX_ADJUGATE: "\\adjugate"
// determinantsAMSMATH_VMATRIX: L_BRACE "vmatrix" R_BRACECMD_DETERMINANT_BEGIN_SIMPLE: CMD_BEGIN AMSMATH_VMATRIXCMD_DETERMINANT_BEGIN_VARIANT: BAR IGNORE_L CMD_BEGIN (ARRAY_MATRIX_BEGIN | AMSMATH_MATRIX)CMD_DETERMINANT_BEGIN: CMD_DETERMINANT_BEGIN_SIMPLE | CMD_DETERMINANT_BEGIN_VARIANTCMD_DETERMINANT_END_SIMPLE: CMD_END AMSMATH_VMATRIXCMD_DETERMINANT_END_VARIANT: CMD_END (ARRAY_MATRIX_END | AMSMATH_MATRIX) IGNORE_R "\\right"? BARCMD_DETERMINANT_END: CMD_DETERMINANT_END_SIMPLE | CMD_DETERMINANT_END_VARIANTFUNC_DETERMINANT: "\\det"
//////////////////// grammar //////////////////////
latex_string: _relation | _expression
_one_letter_symbol: SYMBOL | LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT | LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT | GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT | GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT | GREEK_SYMBOL_WITH_PRIMES// LuaTeX-generated outputs of \mathit{foo'} and \mathit{foo}'// seem to be the same on the surface. We allow both styles.multi_letter_symbol: CMD_MATHIT L_BRACE MULTI_LETTER_SYMBOL R_BRACE | CMD_MATHIT L_BRACE MULTI_LETTER_SYMBOL R_BRACE /'+/number: /\d+(\.\d*)?/ | CMD_IMAGINARY_UNIT
_atomic_expr: _one_letter_symbol | multi_letter_symbol | number | CMD_INFTY
group_round_parentheses: L_PAREN _expression R_PARENgroup_square_brackets: L_BRACKET _expression R_BRACKETgroup_curly_parentheses: L_BRACE _expression R_BRACE
_relation: eq | ne | lt | lte | gt | gte
eq: _expression EQUAL _expressionne: _expression NOT_EQUAL _expressionlt: _expression LT _expressionlte: _expression LTE _expressiongt: _expression GT _expressiongte: _expression GTE _expression
_expression_core: _atomic_expr | group_curly_parentheses
add: _expression ADD _expression_mul | ADD _expression_mulsub: _expression SUB _expression_mul | SUB _expression_mulmul: _expression_mul MUL_SYMBOL _expression_powerdiv: _expression_mul DIV_SYMBOL _expression_power
adjacent_expressions: (_one_letter_symbol | number) _expression_mul | group_round_parentheses (group_round_parentheses | _one_letter_symbol) | _function _function | fraction _expression_mul
_expression_func: _expression_core | group_round_parentheses | fraction | binomial | _function | _integral// | derivative | limit | matrix
_expression_power: _expression_func | superscript | matrix_prime | symbol_prime
_expression_mul: _expression_power | mul | div | adjacent_expressions | summation | product
_expression: _expression_mul | add | sub
_limit_dir: "+" | "-" | L_BRACE ("+" | "-") R_BRACE
limit_dir_expr: _expression CARET _limit_dir
group_curly_parentheses_lim: L_BRACE _expression LIM_APPROACH_SYM (limit_dir_expr | _expression) R_BRACE
limit: FUNC_LIM UNDERSCORE group_curly_parentheses_lim _expression
differential: DIFFERENTIAL_SYMBOL _one_letter_symbol
//_derivative_operator: CMD_FRAC L_BRACE DIFFERENTIAL_SYMBOL R_BRACE L_BRACE differential R_BRACE
//derivative: _derivative_operator _expression
_integral: normal_integral | integral_with_special_fraction
normal_integral: FUNC_INT _expression DIFFERENTIAL_SYMBOL _one_letter_symbol | FUNC_INT (CARET _expression_core UNDERSCORE _expression_core)? _expression? DIFFERENTIAL_SYMBOL _one_letter_symbol | FUNC_INT (UNDERSCORE _expression_core CARET _expression_core)? _expression? DIFFERENTIAL_SYMBOL _one_letter_symbol
group_curly_parentheses_int: L_BRACE _expression? differential R_BRACE
special_fraction: CMD_FRAC group_curly_parentheses_int group_curly_parentheses
integral_with_special_fraction: FUNC_INT special_fraction | FUNC_INT (CARET _expression_core UNDERSCORE _expression_core)? special_fraction | FUNC_INT (UNDERSCORE _expression_core CARET _expression_core)? special_fraction
group_curly_parentheses_special: UNDERSCORE L_BRACE _atomic_expr EQUAL _atomic_expr R_BRACE CARET _expression_core | CARET _expression_core UNDERSCORE L_BRACE _atomic_expr EQUAL _atomic_expr R_BRACE
summation: FUNC_SUM group_curly_parentheses_special _expression | FUNC_SUM group_curly_parentheses_special _expression
product: FUNC_PROD group_curly_parentheses_special _expression | FUNC_PROD group_curly_parentheses_special _expression
superscript: _expression_func CARET (_expression_power | CMD_PRIME | CMD_ASTERISK) | _expression_func CARET L_BRACE (PRIMES | STARS | PRIMES_VIA_CMD | STARS_VIA_CMD) R_BRACE
matrix_prime: (matrix | group_round_parentheses) PRIMES
symbol_prime: (LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT | LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT | GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT | GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT) PRIMES
fraction: _basic_fraction | _simple_fraction | _general_fraction
_basic_fraction: CMD_FRAC DIGIT (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES)
_simple_fraction: CMD_FRAC DIGIT group_curly_parentheses | CMD_FRAC group_curly_parentheses (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES)
_general_fraction: CMD_FRAC group_curly_parentheses group_curly_parentheses
binomial: _basic_binomial | _simple_binomial | _general_binomial
_basic_binomial: CMD_BINOM DIGIT (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES)
_simple_binomial: CMD_BINOM DIGIT group_curly_parentheses | CMD_BINOM group_curly_parentheses (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES)
_general_binomial: CMD_BINOM group_curly_parentheses group_curly_parentheses
list_of_expressions: _expression ("," _expression)*
function_applied: _one_letter_symbol L_PAREN list_of_expressions R_PAREN
min: FUNC_MIN L_PAREN list_of_expressions R_PAREN
max: FUNC_MAX L_PAREN list_of_expressions R_PAREN
bra: CMD_LANGLE _expression BAR
ket: BAR _expression CMD_RANGLE
inner_product: CMD_LANGLE _expression BAR _expression CMD_RANGLE
_function: function_applied | abs | floor | ceil | _trigonometric_function | _inverse_trigonometric_function | _trigonometric_function_power | _hyperbolic_trigonometric_function | _inverse_hyperbolic_trigonometric_function | exponential | log | square_root | factorial | conjugate | max | min | bra | ket | inner_product | determinant | trace | adjugate
exponential: FUNC_EXP _expression
log: FUNC_LOG _expression | FUNC_LN _expression | FUNC_LG _expression | FUNC_LOG UNDERSCORE (DIGIT | _one_letter_symbol) _expression | FUNC_LOG UNDERSCORE group_curly_parentheses _expression
square_root: FUNC_SQRT group_curly_parentheses | FUNC_SQRT group_square_brackets group_curly_parentheses
factorial: _expression_func BANG
conjugate: CMD_OVERLINE group_curly_parentheses | CMD_OVERLINE DIGIT
_trigonometric_function: sin | cos | tan | csc | sec | cot
sin: FUNC_SIN _expressioncos: FUNC_COS _expressiontan: FUNC_TAN _expressioncsc: FUNC_CSC _expressionsec: FUNC_SEC _expressioncot: FUNC_COT _expression
_trigonometric_function_power: sin_power | cos_power | tan_power | csc_power | sec_power | cot_power
sin_power: FUNC_SIN CARET _expression_core _expressioncos_power: FUNC_COS CARET _expression_core _expressiontan_power: FUNC_TAN CARET _expression_core _expressioncsc_power: FUNC_CSC CARET _expression_core _expressionsec_power: FUNC_SEC CARET _expression_core _expressioncot_power: FUNC_COT CARET _expression_core _expression
_hyperbolic_trigonometric_function: sinh | cosh | tanh
sinh: FUNC_SINH _expressioncosh: FUNC_COSH _expressiontanh: FUNC_TANH _expression
_inverse_trigonometric_function: arcsin | arccos | arctan | arccsc | arcsec | arccot
arcsin: FUNC_ARCSIN _expressionarccos: FUNC_ARCCOS _expressionarctan: FUNC_ARCTAN _expressionarccsc: FUNC_ARCCSC _expressionarcsec: FUNC_ARCSEC _expressionarccot: FUNC_ARCCOT _expression
_inverse_hyperbolic_trigonometric_function: asinh | acosh | atanh
asinh: FUNC_ARSINH _expressionacosh: FUNC_ARCOSH _expressionatanh: FUNC_ARTANH _expression
abs: BAR _expression BARfloor: L_FLOOR _expression R_FLOORceil: L_CEIL _expression R_CEIL
matrix: CMD_MATRIX_BEGIN matrix_body CMD_MATRIX_ENDmatrix_body: matrix_row (MATRIX_ROW_DELIM matrix_row)* (MATRIX_ROW_DELIM)?matrix_row: _expression (MATRIX_COL_DELIM _expression)*determinant: (CMD_DETERMINANT_BEGIN matrix_body CMD_DETERMINANT_END) | FUNC_DETERMINANT _expressiontrace: FUNC_MATRIX_TRACE _expressionadjugate: FUNC_MATRIX_ADJUGATE _expression123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import osimport loggingimport refrom pathlib import Path
from sympy.external import import_modulefrom sympy.parsing.latex.lark.transformer import TransformToSymPyExpr
_lark = import_module("lark")
class LarkLaTeXParser: r"""Class for converting input `\mathrm{\LaTeX}` strings into SymPy Expressions. It holds all the necessary internal data for doing so, and exposes hooks for customizing its behavior.
Parameters ==========
print_debug_output : bool, optional
If set to ``True``, prints debug output to the logger. Defaults to ``False``.
transform : bool, optional
If set to ``True``, the class runs the Transformer class on the parse tree generated by running ``Lark.parse`` on the input string. Defaults to ``True``.
Setting it to ``False`` can help with debugging the `\mathrm{\LaTeX}` grammar.
grammar_file : str, optional
The path to the grammar file that the parser should use. If set to ``None``, it uses the default grammar, which is in ``grammar/latex.lark``, relative to the ``sympy/parsing/latex/lark/`` directory.
transformer : str, optional
The name of the Transformer class to use. If set to ``None``, it uses the default transformer class, which is :py:func:`TransformToSymPyExpr`.
""" def __init__(self, print_debug_output=False, transform=True, grammar_file=None, transformer=None): grammar_dir_path = os.path.join(os.path.dirname(__file__), "grammar/")
if grammar_file is None: latex_grammar = Path(os.path.join(grammar_dir_path, "latex.lark")).read_text(encoding="utf-8") else: latex_grammar = Path(grammar_file).read_text(encoding="utf-8")
self.parser = _lark.Lark( latex_grammar, source_path=grammar_dir_path, parser="earley", start="latex_string", lexer="auto", ambiguity="explicit", propagate_positions=False, maybe_placeholders=False, keep_all_tokens=True)
self.print_debug_output = print_debug_output self.transform_expr = transform
if transformer is None: self.transformer = TransformToSymPyExpr() else: self.transformer = transformer()
def doparse(self, s: str): if self.print_debug_output: _lark.logger.setLevel(logging.DEBUG)
parse_tree = self.parser.parse(s)
if not self.transform_expr: # exit early and return the parse tree _lark.logger.debug("expression = %s", s) _lark.logger.debug(parse_tree) _lark.logger.debug(parse_tree.pretty()) return parse_tree
if self.print_debug_output: # print this stuff before attempting to run the transformer _lark.logger.debug("expression = %s", s) # print the `parse_tree` variable _lark.logger.debug(parse_tree.pretty())
sympy_expression = self.transformer.transform(parse_tree)
if self.print_debug_output: _lark.logger.debug("SymPy expression = %s", sympy_expression)
return sympy_expression
if _lark is not None: _lark_latex_parser = LarkLaTeXParser()
def parse_latex_lark(s: str): """ Experimental LaTeX parser using Lark.
This function is still under development and its API may change with the next releases of SymPy. """ if _lark is None: raise ImportError("Lark is probably not installed") return _lark_latex_parser.doparse(s)
def _pretty_print_lark_trees(tree, indent=0, show_expr=True): if isinstance(tree, _lark.Token): return tree.value
data = str(tree.data)
is_expr = data.startswith("expression")
if is_expr: data = re.sub(r"^expression", "E", data)
is_ambig = (data == "_ambig")
if is_ambig: new_indent = indent + 2 else: new_indent = indent
output = "" show_node = not is_expr or show_expr
if show_node: output += str(data) + "("
if is_ambig: output += "\n" + "\n".join([" " * new_indent + _pretty_print_lark_trees(i, new_indent, show_expr) for i in tree.children]) else: output += ",".join([_pretty_print_lark_trees(i, new_indent, show_expr) for i in tree.children])
if show_node: output += ")"
return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730import re
import sympyfrom sympy.external import import_modulefrom sympy.parsing.latex.errors import LaTeXParsingError
lark = import_module("lark")
if lark: from lark import Transformer, Token, Tree # type: ignoreelse: class Transformer: # type: ignore def transform(self, *args): pass
class Token: # type: ignore pass
class Tree: # type: ignore pass
# noinspection PyPep8Naming,PyMethodMayBeStaticclass TransformToSymPyExpr(Transformer): """Returns a SymPy expression that is generated by traversing the ``lark.Tree`` passed to the ``.transform()`` function.
Notes =====
**This class is never supposed to be used directly.**
In order to tweak the behavior of this class, it has to be subclassed and then after the required modifications are made, the name of the new class should be passed to the :py:class:`LarkLaTeXParser` class by using the ``transformer`` argument in the constructor.
Parameters ==========
visit_tokens : bool, optional For information about what this option does, see `here <https://lark-parser.readthedocs.io/en/latest/visitors.html#lark.visitors.Transformer>`_.
Note that the option must be set to ``True`` for the default parser to work. """
SYMBOL = sympy.Symbol DIGIT = sympy.core.numbers.Integer
def CMD_INFTY(self, tokens): return sympy.oo
def GREEK_SYMBOL_WITH_PRIMES(self, tokens): # we omit the first character because it is a backslash. Also, if the variable name has "var" in it, # like "varphi" or "varepsilon", we remove that too variable_name = re.sub("var", "", tokens[1:])
return sympy.Symbol(variable_name)
def LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens): base, sub = tokens.value.split("_") if sub.startswith("{"): return sympy.Symbol("%s_{%s}" % (base, sub[1:-1])) else: return sympy.Symbol("%s_{%s}" % (base, sub))
def GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens): base, sub = tokens.value.split("_") greek_letter = re.sub("var", "", base[1:])
if sub.startswith("{"): return sympy.Symbol("%s_{%s}" % (greek_letter, sub[1:-1])) else: return sympy.Symbol("%s_{%s}" % (greek_letter, sub))
def LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens): base, sub = tokens.value.split("_") if sub.startswith("{"): greek_letter = sub[2:-1] else: greek_letter = sub[1:]
greek_letter = re.sub("var", "", greek_letter) return sympy.Symbol("%s_{%s}" % (base, greek_letter))
def GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens): base, sub = tokens.value.split("_") greek_base = re.sub("var", "", base[1:])
if sub.startswith("{"): greek_sub = sub[2:-1] else: greek_sub = sub[1:]
greek_sub = re.sub("var", "", greek_sub) return sympy.Symbol("%s_{%s}" % (greek_base, greek_sub))
def multi_letter_symbol(self, tokens): if len(tokens) == 4: # no primes (single quotes) on symbol return sympy.Symbol(tokens[2]) if len(tokens) == 5: # there are primes on the symbol return sympy.Symbol(tokens[2] + tokens[4])
def number(self, tokens): if tokens[0].type == "CMD_IMAGINARY_UNIT": return sympy.I
if "." in tokens[0]: return sympy.core.numbers.Float(tokens[0]) else: return sympy.core.numbers.Integer(tokens[0])
def latex_string(self, tokens): return tokens[0]
def group_round_parentheses(self, tokens): return tokens[1]
def group_square_brackets(self, tokens): return tokens[1]
def group_curly_parentheses(self, tokens): return tokens[1]
def eq(self, tokens): return sympy.Eq(tokens[0], tokens[2])
def ne(self, tokens): return sympy.Ne(tokens[0], tokens[2])
def lt(self, tokens): return sympy.Lt(tokens[0], tokens[2])
def lte(self, tokens): return sympy.Le(tokens[0], tokens[2])
def gt(self, tokens): return sympy.Gt(tokens[0], tokens[2])
def gte(self, tokens): return sympy.Ge(tokens[0], tokens[2])
def add(self, tokens): if len(tokens) == 2: # +a return tokens[1] if len(tokens) == 3: # a + b lh = tokens[0] rh = tokens[2]
if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh): return sympy.MatAdd(lh, rh)
return sympy.Add(lh, rh)
def sub(self, tokens): if len(tokens) == 2: # -a x = tokens[1]
if self._obj_is_sympy_Matrix(x): return sympy.MatMul(-1, x)
return -x if len(tokens) == 3: # a - b lh = tokens[0] rh = tokens[2]
if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh): return sympy.MatAdd(lh, sympy.MatMul(-1, rh))
return sympy.Add(lh, -rh)
def mul(self, tokens): lh = tokens[0] rh = tokens[2]
if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh): return sympy.MatMul(lh, rh)
return sympy.Mul(lh, rh)
def div(self, tokens): return self._handle_division(tokens[0], tokens[2])
def adjacent_expressions(self, tokens): # Most of the time, if two expressions are next to each other, it means implicit multiplication, # but not always from sympy.physics.quantum import Bra, Ket if isinstance(tokens[0], Ket) and isinstance(tokens[1], Bra): from sympy.physics.quantum import OuterProduct return OuterProduct(tokens[0], tokens[1]) elif tokens[0] == sympy.Symbol("d"): # If the leftmost token is a "d", then it is highly likely that this is a differential return tokens[0], tokens[1] elif isinstance(tokens[0], tuple): # then we have a derivative return sympy.Derivative(tokens[1], tokens[0][1]) else: return sympy.Mul(tokens[0], tokens[1])
def superscript(self, tokens): def isprime(x): return isinstance(x, Token) and x.type == "PRIMES"
def iscmdprime(x): return isinstance(x, Token) and (x.type == "PRIMES_VIA_CMD" or x.type == "CMD_PRIME")
def isstar(x): return isinstance(x, Token) and x.type == "STARS"
def iscmdstar(x): return isinstance(x, Token) and (x.type == "STARS_VIA_CMD" or x.type == "CMD_ASTERISK")
base = tokens[0] if len(tokens) == 3: # a^b OR a^\prime OR a^\ast sup = tokens[2] if len(tokens) == 5: # a^{'}, a^{''}, ... OR # a^{*}, a^{**}, ... OR # a^{\prime}, a^{\prime\prime}, ... OR # a^{\ast}, a^{\ast\ast}, ... sup = tokens[3]
if self._obj_is_sympy_Matrix(base): if sup == sympy.Symbol("T"): return sympy.Transpose(base) if sup == sympy.Symbol("H"): return sympy.adjoint(base) if isprime(sup): sup = sup.value if len(sup) % 2 == 0: return base return sympy.Transpose(base) if iscmdprime(sup): sup = sup.value if (len(sup)/len(r"\prime")) % 2 == 0: return base return sympy.Transpose(base) if isstar(sup): sup = sup.value # need .doit() in order to be consistent with # sympy.adjoint() which returns the evaluated adjoint # of a matrix if len(sup) % 2 == 0: return base.doit() return sympy.adjoint(base) if iscmdstar(sup): sup = sup.value # need .doit() for same reason as above if (len(sup)/len(r"\ast")) % 2 == 0: return base.doit() return sympy.adjoint(base)
if isprime(sup) or iscmdprime(sup) or isstar(sup) or iscmdstar(sup): raise LaTeXParsingError(f"{base} with superscript {sup} is not understood.")
return sympy.Pow(base, sup)
def matrix_prime(self, tokens): base = tokens[0] primes = tokens[1].value
if not self._obj_is_sympy_Matrix(base): raise LaTeXParsingError(f"({base}){primes} is not understood.")
if len(primes) % 2 == 0: return base
return sympy.Transpose(base)
def symbol_prime(self, tokens): base = tokens[0] primes = tokens[1].value
return sympy.Symbol(f"{base.name}{primes}")
def fraction(self, tokens): numerator = tokens[1] if isinstance(tokens[2], tuple): # we only need the variable w.r.t. which we are differentiating _, variable = tokens[2]
# we will pass this information upwards return "derivative", variable else: denominator = tokens[2] return self._handle_division(numerator, denominator)
def binomial(self, tokens): return sympy.binomial(tokens[1], tokens[2])
def normal_integral(self, tokens): underscore_index = None caret_index = None
if "_" in tokens: # we need to know the index because the next item in the list is the # arguments for the lower bound of the integral underscore_index = tokens.index("_")
if "^" in tokens: # we need to know the index because the next item in the list is the # arguments for the upper bound of the integral caret_index = tokens.index("^")
lower_bound = tokens[underscore_index + 1] if underscore_index else None upper_bound = tokens[caret_index + 1] if caret_index else None
differential_symbol = self._extract_differential_symbol(tokens)
if differential_symbol is None: raise LaTeXParsingError("Differential symbol was not found in the expression." "Valid differential symbols are \"d\", \"\\text{d}, and \"\\mathrm{d}\".")
# else we can assume that a differential symbol was found differential_variable_index = tokens.index(differential_symbol) + 1 differential_variable = tokens[differential_variable_index]
# we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would # evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero if lower_bound is not None and upper_bound is None: # then one was given and the other wasn't raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
if upper_bound is not None and lower_bound is None: # then one was given and the other wasn't raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
# check if any expression was given or not. If it wasn't, then set the integrand to 1. if underscore_index is not None and underscore_index == differential_variable_index - 3: # The Token at differential_variable_index - 2 should be the integrand. However, if going one more step # backwards after that gives us the underscore, then that means that there _was_ no integrand. # Example: \int^7_0 dx integrand = 1 elif caret_index is not None and caret_index == differential_variable_index - 3: # The Token at differential_variable_index - 2 should be the integrand. However, if going one more step # backwards after that gives us the caret, then that means that there _was_ no integrand. # Example: \int_0^7 dx integrand = 1 elif differential_variable_index == 2: # this means we have something like "\int dx", because the "\int" symbol will always be # at index 0 in `tokens` integrand = 1 else: # The Token at differential_variable_index - 1 is the differential symbol itself, so we need to go one # more step before that. integrand = tokens[differential_variable_index - 2]
if lower_bound is not None: # then we have a definite integral
# we can assume that either both the lower and upper bounds are given, or # neither of them are return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound)) else: # we have an indefinite integral return sympy.Integral(integrand, differential_variable)
def group_curly_parentheses_int(self, tokens): # return signature is a tuple consisting of the expression in the numerator, along with the variable of # integration if len(tokens) == 3: return 1, tokens[1] elif len(tokens) == 4: return tokens[1], tokens[2] # there are no other possibilities
def special_fraction(self, tokens): numerator, variable = tokens[1] denominator = tokens[2]
# We pass the integrand, along with information about the variable of integration, upw return sympy.Mul(numerator, sympy.Pow(denominator, -1)), variable
def integral_with_special_fraction(self, tokens): underscore_index = None caret_index = None
if "_" in tokens: # we need to know the index because the next item in the list is the # arguments for the lower bound of the integral underscore_index = tokens.index("_")
if "^" in tokens: # we need to know the index because the next item in the list is the # arguments for the upper bound of the integral caret_index = tokens.index("^")
lower_bound = tokens[underscore_index + 1] if underscore_index else None upper_bound = tokens[caret_index + 1] if caret_index else None
# we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would # evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero if lower_bound is not None and upper_bound is None: # then one was given and the other wasn't raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
if upper_bound is not None and lower_bound is None: # then one was given and the other wasn't raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
integrand, differential_variable = tokens[-1]
if lower_bound is not None: # then we have a definite integral
# we can assume that either both the lower and upper bounds are given, or # neither of them are return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound)) else: # we have an indefinite integral return sympy.Integral(integrand, differential_variable)
def group_curly_parentheses_special(self, tokens): underscore_index = tokens.index("_") caret_index = tokens.index("^")
# given the type of expressions we are parsing, we can assume that the lower limit # will always use braces around its arguments. This is because we don't support # converting unconstrained sums into SymPy expressions.
# first we isolate the bottom limit left_brace_index = tokens.index("{", underscore_index) right_brace_index = tokens.index("}", underscore_index)
bottom_limit = tokens[left_brace_index + 1: right_brace_index]
# next, we isolate the upper limit top_limit = tokens[caret_index + 1:]
# the code below will be useful for supporting things like `\sum_{n = 0}^{n = 5} n^2` # if "{" in top_limit: # left_brace_index = tokens.index("{", caret_index) # if left_brace_index != -1: # # then there's a left brace in the string, and we need to find the closing right brace # right_brace_index = tokens.index("}", caret_index) # top_limit = tokens[left_brace_index + 1: right_brace_index]
# print(f"top limit = {top_limit}")
index_variable = bottom_limit[0] lower_limit = bottom_limit[-1] upper_limit = top_limit[0] # for now, the index will always be 0
# print(f"return value = ({index_variable}, {lower_limit}, {upper_limit})")
return index_variable, lower_limit, upper_limit
def summation(self, tokens): return sympy.Sum(tokens[2], tokens[1])
def product(self, tokens): return sympy.Product(tokens[2], tokens[1])
def limit_dir_expr(self, tokens): caret_index = tokens.index("^")
if "{" in tokens: left_curly_brace_index = tokens.index("{", caret_index) direction = tokens[left_curly_brace_index + 1] else: direction = tokens[caret_index + 1]
if direction == "+": return tokens[0], "+" elif direction == "-": return tokens[0], "-" else: return tokens[0], "+-"
def group_curly_parentheses_lim(self, tokens): limit_variable = tokens[1] if isinstance(tokens[3], tuple): destination, direction = tokens[3] else: destination = tokens[3] direction = "+-"
return limit_variable, destination, direction
def limit(self, tokens): limit_variable, destination, direction = tokens[2]
return sympy.Limit(tokens[-1], limit_variable, destination, direction)
def differential(self, tokens): return tokens[1]
def derivative(self, tokens): return sympy.Derivative(tokens[-1], tokens[5])
def list_of_expressions(self, tokens): if len(tokens) == 1: # we return it verbatim because the function_applied node expects # a list return tokens else: def remove_tokens(args): if isinstance(args, Token): if args.type != "COMMA": # An unexpected token was encountered raise LaTeXParsingError("A comma token was expected, but some other token was encountered.") return False return True
return filter(remove_tokens, tokens)
def function_applied(self, tokens): return sympy.Function(tokens[0])(*tokens[2])
def min(self, tokens): return sympy.Min(*tokens[2])
def max(self, tokens): return sympy.Max(*tokens[2])
def bra(self, tokens): from sympy.physics.quantum import Bra return Bra(tokens[1])
def ket(self, tokens): from sympy.physics.quantum import Ket return Ket(tokens[1])
def inner_product(self, tokens): from sympy.physics.quantum import Bra, Ket, InnerProduct return InnerProduct(Bra(tokens[1]), Ket(tokens[3]))
def sin(self, tokens): return sympy.sin(tokens[1])
def cos(self, tokens): return sympy.cos(tokens[1])
def tan(self, tokens): return sympy.tan(tokens[1])
def csc(self, tokens): return sympy.csc(tokens[1])
def sec(self, tokens): return sympy.sec(tokens[1])
def cot(self, tokens): return sympy.cot(tokens[1])
def sin_power(self, tokens): exponent = tokens[2] if exponent == -1: return sympy.asin(tokens[-1]) else: return sympy.Pow(sympy.sin(tokens[-1]), exponent)
def cos_power(self, tokens): exponent = tokens[2] if exponent == -1: return sympy.acos(tokens[-1]) else: return sympy.Pow(sympy.cos(tokens[-1]), exponent)
def tan_power(self, tokens): exponent = tokens[2] if exponent == -1: return sympy.atan(tokens[-1]) else: return sympy.Pow(sympy.tan(tokens[-1]), exponent)
def csc_power(self, tokens): exponent = tokens[2] if exponent == -1: return sympy.acsc(tokens[-1]) else: return sympy.Pow(sympy.csc(tokens[-1]), exponent)
def sec_power(self, tokens): exponent = tokens[2] if exponent == -1: return sympy.asec(tokens[-1]) else: return sympy.Pow(sympy.sec(tokens[-1]), exponent)
def cot_power(self, tokens): exponent = tokens[2] if exponent == -1: return sympy.acot(tokens[-1]) else: return sympy.Pow(sympy.cot(tokens[-1]), exponent)
def arcsin(self, tokens): return sympy.asin(tokens[1])
def arccos(self, tokens): return sympy.acos(tokens[1])
def arctan(self, tokens): return sympy.atan(tokens[1])
def arccsc(self, tokens): return sympy.acsc(tokens[1])
def arcsec(self, tokens): return sympy.asec(tokens[1])
def arccot(self, tokens): return sympy.acot(tokens[1])
def sinh(self, tokens): return sympy.sinh(tokens[1])
def cosh(self, tokens): return sympy.cosh(tokens[1])
def tanh(self, tokens): return sympy.tanh(tokens[1])
def asinh(self, tokens): return sympy.asinh(tokens[1])
def acosh(self, tokens): return sympy.acosh(tokens[1])
def atanh(self, tokens): return sympy.atanh(tokens[1])
def abs(self, tokens): return sympy.Abs(tokens[1])
def floor(self, tokens): return sympy.floor(tokens[1])
def ceil(self, tokens): return sympy.ceiling(tokens[1])
def factorial(self, tokens): return sympy.factorial(tokens[0])
def conjugate(self, tokens): return sympy.conjugate(tokens[1])
def square_root(self, tokens): if len(tokens) == 2: # then there was no square bracket argument return sympy.sqrt(tokens[1]) elif len(tokens) == 3: # then there _was_ a square bracket argument return sympy.root(tokens[2], tokens[1])
def exponential(self, tokens): return sympy.exp(tokens[1])
def log(self, tokens): if tokens[0].type == "FUNC_LG": # we don't need to check if there's an underscore or not because having one # in this case would be meaningless # TODO: ANTLR refers to ISO 80000-2:2019. should we keep base 10 or base 2? return sympy.log(tokens[1], 10) elif tokens[0].type == "FUNC_LN": return sympy.log(tokens[1]) elif tokens[0].type == "FUNC_LOG": # we check if a base was specified or not if "_" in tokens: # then a base was specified return sympy.log(tokens[3], tokens[2]) else: # a base was not specified return sympy.log(tokens[1])
def _extract_differential_symbol(self, s: str): differential_symbols = {"d", r"\text{d}", r"\mathrm{d}"}
differential_symbol = next((symbol for symbol in differential_symbols if symbol in s), None)
return differential_symbol
def matrix(self, tokens): def is_matrix_row(x): return (isinstance(x, Tree) and x.data == "matrix_row")
def is_not_col_delim(y): return (not isinstance(y, Token) or y.type != "MATRIX_COL_DELIM")
matrix_body = tokens[1].children return sympy.Matrix([[y for y in x.children if is_not_col_delim(y)] for x in matrix_body if is_matrix_row(x)])
def determinant(self, tokens): if len(tokens) == 2: # \det A if not self._obj_is_sympy_Matrix(tokens[1]): raise LaTeXParsingError("Cannot take determinant of non-matrix.")
return tokens[1].det()
if len(tokens) == 3: # | A | return self.matrix(tokens).det()
def trace(self, tokens): if not self._obj_is_sympy_Matrix(tokens[1]): raise LaTeXParsingError("Cannot take trace of non-matrix.")
return sympy.Trace(tokens[1])
def adjugate(self, tokens): if not self._obj_is_sympy_Matrix(tokens[1]): raise LaTeXParsingError("Cannot take adjugate of non-matrix.")
# need .doit() since MatAdd does not support .adjugate() method return tokens[1].doit().adjugate()
def _obj_is_sympy_Matrix(self, obj): if hasattr(obj, "is_Matrix"): return obj.is_Matrix
return isinstance(obj, sympy.Matrix)
def _handle_division(self, numerator, denominator): if self._obj_is_sympy_Matrix(denominator): raise LaTeXParsingError("Cannot divide by matrices like this since " "it is not clear if left or right multiplication " "by the inverse is intended. Try explicitly " "multiplying by the inverse instead.")
if self._obj_is_sympy_Matrix(numerator): return sympy.MatMul(numerator, sympy.Pow(denominator, -1))
return sympy.Mul(numerator, sympy.Pow(denominator, -1))12345678910111213141516171819202122232425from sympy.core.singleton import Sfrom sympy.core.symbol import symbolsfrom sympy.parsing.ast_parser import parse_exprfrom sympy.testing.pytest import raisesfrom sympy.core.sympify import SympifyErrorimport warnings
def test_parse_expr(): a, b = symbols('a, b') # tests issue_16393 assert parse_expr('a + b', {}) == a + b raises(SympifyError, lambda: parse_expr('a + ', {}))
# tests Transform.visit_Constant assert parse_expr('1 + 2', {}) == S(3) assert parse_expr('1 + 2.0', {}) == S(3.0)
# tests Transform.visit_Name assert parse_expr('Rational(1, 2)', {}) == S(1)/2 assert parse_expr('a', {'a': a}) == a
# tests issue_23092 with warnings.catch_warnings(): warnings.simplefilter('error') assert parse_expr('6 * 7', {}) == S(42)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178import os
from sympy.functions.elementary.trigonometric import (cos, sin)from sympy.external import import_modulefrom sympy.testing.pytest import skipfrom sympy.parsing.autolev import parse_autolev
antlr4 = import_module("antlr4")
if not antlr4: disabled = True
FILE_DIR = os.path.dirname( os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
def _test_examples(in_filename, out_filename, test_name=""):
in_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples', in_filename) correct_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples', out_filename) with open(in_file_path) as f: generated_code = parse_autolev(f, include_numeric=True)
with open(correct_file_path) as f: for idx, line1 in enumerate(f): if line1.startswith("#"): break try: line2 = generated_code.split('\n')[idx] assert line1.rstrip() == line2.rstrip() except Exception: msg = 'mismatch in ' + test_name + ' in line no: {0}' raise AssertionError(msg.format(idx+1))
def test_rule_tests():
l = ["ruletest1", "ruletest2", "ruletest3", "ruletest4", "ruletest5", "ruletest6", "ruletest7", "ruletest8", "ruletest9", "ruletest10", "ruletest11", "ruletest12"]
for i in l: in_filepath = i + ".al" out_filepath = i + ".py" _test_examples(in_filepath, out_filepath, i)
def test_pydy_examples():
l = ["mass_spring_damper", "chaos_pendulum", "double_pendulum", "non_min_pendulum"]
for i in l: in_filepath = os.path.join("pydy-example-repo", i + ".al") out_filepath = os.path.join("pydy-example-repo", i + ".py") _test_examples(in_filepath, out_filepath, i)
def test_autolev_tutorial():
dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples', 'autolev-tutorial')
if os.path.isdir(dir_path): l = ["tutor1", "tutor2", "tutor3", "tutor4", "tutor5", "tutor6", "tutor7"] for i in l: in_filepath = os.path.join("autolev-tutorial", i + ".al") out_filepath = os.path.join("autolev-tutorial", i + ".py") _test_examples(in_filepath, out_filepath, i)
def test_dynamics_online():
dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples', 'dynamics-online')
if os.path.isdir(dir_path): ch1 = ["1-4", "1-5", "1-6", "1-7", "1-8", "1-9_1", "1-9_2", "1-9_3"] ch2 = ["2-1", "2-2", "2-3", "2-4", "2-5", "2-6", "2-7", "2-8", "2-9", "circular"] ch3 = ["3-1_1", "3-1_2", "3-2_1", "3-2_2", "3-2_3", "3-2_4", "3-2_5", "3-3"] ch4 = ["4-1_1", "4-2_1", "4-4_1", "4-4_2", "4-5_1", "4-5_2"] chapters = [(ch1, "ch1"), (ch2, "ch2"), (ch3, "ch3"), (ch4, "ch4")] for ch, name in chapters: for i in ch: in_filepath = os.path.join("dynamics-online", name, i + ".al") out_filepath = os.path.join("dynamics-online", name, i + ".py") _test_examples(in_filepath, out_filepath, i)
def test_output_01(): """Autolev example calculates the position, velocity, and acceleration of a point and expresses in a single reference frame::
(1) FRAMES C,D,F (2) VARIABLES FD'',DC'' (3) CONSTANTS R,L (4) POINTS O,E (5) SIMPROT(F,D,1,FD) -> (6) F_D = [1, 0, 0; 0, COS(FD), -SIN(FD); 0, SIN(FD), COS(FD)] (7) SIMPROT(D,C,2,DC) -> (8) D_C = [COS(DC), 0, SIN(DC); 0, 1, 0; -SIN(DC), 0, COS(DC)] (9) W_C_F> = EXPRESS(W_C_F>, F) -> (10) W_C_F> = FD'*F1> + COS(FD)*DC'*F2> + SIN(FD)*DC'*F3> (11) P_O_E>=R*D2>-L*C1> (12) P_O_E>=EXPRESS(P_O_E>, D) -> (13) P_O_E> = -L*COS(DC)*D1> + R*D2> + L*SIN(DC)*D3> (14) V_E_F>=EXPRESS(DT(P_O_E>,F),D) -> (15) V_E_F> = L*SIN(DC)*DC'*D1> - L*SIN(DC)*FD'*D2> + (R*FD'+L*COS(DC)*DC')*D3> (16) A_E_F>=EXPRESS(DT(V_E_F>,F),D) -> (17) A_E_F> = L*(COS(DC)*DC'^2+SIN(DC)*DC'')*D1> + (-R*FD'^2-2*L*COS(DC)*DC'*FD'-L*SIN(DC)*FD'')*D2> + (R*FD''+L*COS(DC)*DC''-L*SIN(DC)*DC'^2-L*SIN(DC)*FD'^2)*D3>
"""
if not antlr4: skip('Test skipped: antlr4 is not installed.')
autolev_input = """\FRAMES C,D,FVARIABLES FD'',DC''CONSTANTS R,LPOINTS O,ESIMPROT(F,D,1,FD)SIMPROT(D,C,2,DC)W_C_F>=EXPRESS(W_C_F>,F)P_O_E>=R*D2>-L*C1>P_O_E>=EXPRESS(P_O_E>,D)V_E_F>=EXPRESS(DT(P_O_E>,F),D)A_E_F>=EXPRESS(DT(V_E_F>,F),D)\"""
sympy_input = parse_autolev(autolev_input)
g = {} l = {} exec(sympy_input, g, l)
w_c_f = l['frame_c'].ang_vel_in(l['frame_f']) # P_O_E> means "the position of point E wrt to point O" p_o_e = l['point_e'].pos_from(l['point_o']) v_e_f = l['point_e'].vel(l['frame_f']) a_e_f = l['point_e'].acc(l['frame_f'])
# NOTE : The Autolev outputs above were manually transformed into # equivalent SymPy physics vector expressions. Would be nice to automate # this transformation. expected_w_c_f = (l['fd'].diff()*l['frame_f'].x + cos(l['fd'])*l['dc'].diff()*l['frame_f'].y + sin(l['fd'])*l['dc'].diff()*l['frame_f'].z)
assert (w_c_f - expected_w_c_f).simplify() == 0
expected_p_o_e = (-l['l']*cos(l['dc'])*l['frame_d'].x + l['r']*l['frame_d'].y + l['l']*sin(l['dc'])*l['frame_d'].z)
assert (p_o_e - expected_p_o_e).simplify() == 0
expected_v_e_f = (l['l']*sin(l['dc'])*l['dc'].diff()*l['frame_d'].x - l['l']*sin(l['dc'])*l['fd'].diff()*l['frame_d'].y + (l['r']*l['fd'].diff() + l['l']*cos(l['dc'])*l['dc'].diff())*l['frame_d'].z) assert (v_e_f - expected_v_e_f).simplify() == 0
expected_a_e_f = (l['l']*(cos(l['dc'])*l['dc'].diff()**2 + sin(l['dc'])*l['dc'].diff().diff())*l['frame_d'].x + (-l['r']*l['fd'].diff()**2 - 2*l['l']*cos(l['dc'])*l['dc'].diff()*l['fd'].diff() - l['l']*sin(l['dc'])*l['fd'].diff().diff())*l['frame_d'].y + (l['r']*l['fd'].diff().diff() + l['l']*cos(l['dc'])*l['dc'].diff().diff() - l['l']*sin(l['dc'])*l['dc'].diff()**2 - l['l']*sin(l['dc'])*l['fd'].diff()**2)*l['frame_d'].z) assert (a_e_f - expected_a_e_f).simplify() == 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import osimport tempfilefrom pathlib import Path
import sympyfrom sympy.testing.pytest import raisesfrom sympy.parsing.latex.lark import LarkLaTeXParser, TransformToSymPyExpr, parse_latex_larkfrom sympy.external import import_module
lark = import_module("lark")
# disable tests if lark is not presentdisabled = lark is None
grammar_file = os.path.join(os.path.dirname(__file__), "../latex/lark/grammar/latex.lark")
modification1 = """%override DIV_SYMBOL: DIV%override MUL_SYMBOL: MUL | CMD_TIMES"""
modification2 = r"""%override number: /\d+(,\d*)?/"""
def init_custom_parser(modification, transformer=None): latex_grammar = Path(grammar_file).read_text(encoding="utf-8") latex_grammar += modification
with tempfile.NamedTemporaryFile() as f: f.write(bytes(latex_grammar, encoding="utf8")) f.flush()
parser = LarkLaTeXParser(grammar_file=f.name, transformer=transformer)
return parser
def test_custom1(): # Removes the parser's ability to understand \cdot and \div.
parser = init_custom_parser(modification1)
with raises(lark.exceptions.UnexpectedCharacters): parser.doparse(r"a \cdot b") parser.doparse(r"x \div y")
class CustomTransformer(TransformToSymPyExpr): def number(self, tokens): if "," in tokens[0]: # The Float constructor expects a dot as the decimal separator return sympy.core.numbers.Float(tokens[0].replace(",", ".")) else: return sympy.core.numbers.Integer(tokens[0])
def test_custom2(): # Makes the parser parse commas as the decimal separator instead of dots
parser = init_custom_parser(modification2, CustomTransformer)
with raises(lark.exceptions.UnexpectedCharacters): # Asserting that the default parser cannot parse numbers which have commas as # the decimal separator parse_latex_lark("100,1") parse_latex_lark("0,009")
parser.doparse("100,1") parser.doparse("0,009") parser.doparse("2,71828") parser.doparse("3,14159")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406from sympy.testing.pytest import raisesfrom sympy.parsing.sym_expr import SymPyExpressionfrom sympy.external import import_module
lfortran = import_module('lfortran')
if lfortran: from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String, Return, FunctionDefinition, Assignment, Declaration, CodeBlock) from sympy.core import Integer, Float, Add from sympy.core.symbol import Symbol
expr1 = SymPyExpression() expr2 = SymPyExpression() src = """\ integer :: a, b, c, d real :: p, q, r, s """
def test_sym_expr(): src1 = ( src + """\ d = a + b -c """ ) expr3 = SymPyExpression(src,'f') expr4 = SymPyExpression(src1,'f') ls1 = expr3.return_expr() ls2 = expr4.return_expr() for i in range(0, 7): assert isinstance(ls1[i], Declaration) assert isinstance(ls2[i], Declaration) assert isinstance(ls2[8], Assignment) assert ls1[0] == Declaration( Variable( Symbol('a'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls1[1] == Declaration( Variable( Symbol('b'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls1[2] == Declaration( Variable( Symbol('c'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls1[3] == Declaration( Variable( Symbol('d'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls1[4] == Declaration( Variable( Symbol('p'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls1[5] == Declaration( Variable( Symbol('q'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls1[6] == Declaration( Variable( Symbol('r'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls1[7] == Declaration( Variable( Symbol('s'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls2[8] == Assignment( Variable(Symbol('d')), Symbol('a') + Symbol('b') - Symbol('c') )
def test_assignment(): src1 = ( src + """\ a = b c = d p = q r = s """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(0, 12): if iter < 8: assert isinstance(ls1[iter], Declaration) else: assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('a')), Variable(Symbol('b')) ) assert ls1[9] == Assignment( Variable(Symbol('c')), Variable(Symbol('d')) ) assert ls1[10] == Assignment( Variable(Symbol('p')), Variable(Symbol('q')) ) assert ls1[11] == Assignment( Variable(Symbol('r')), Variable(Symbol('s')) )
def test_binop_add(): src1 = ( src + """\ c = a + b d = a + c s = p + q + r """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 11): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('c')), Symbol('a') + Symbol('b') ) assert ls1[9] == Assignment( Variable(Symbol('d')), Symbol('a') + Symbol('c') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') + Symbol('q') + Symbol('r') )
def test_binop_sub(): src1 = ( src + """\ c = a - b d = a - c s = p - q - r """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 11): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('c')), Symbol('a') - Symbol('b') ) assert ls1[9] == Assignment( Variable(Symbol('d')), Symbol('a') - Symbol('c') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') - Symbol('q') - Symbol('r') )
def test_binop_mul(): src1 = ( src + """\ c = a * b d = a * c s = p * q * r """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 11): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('c')), Symbol('a') * Symbol('b') ) assert ls1[9] == Assignment( Variable(Symbol('d')), Symbol('a') * Symbol('c') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') * Symbol('q') * Symbol('r') )
def test_binop_div(): src1 = ( src + """\ c = a / b d = a / c s = p / q r = q / p """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 12): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('c')), Symbol('a') / Symbol('b') ) assert ls1[9] == Assignment( Variable(Symbol('d')), Symbol('a') / Symbol('c') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') / Symbol('q') ) assert ls1[11] == Assignment( Variable(Symbol('r')), Symbol('q') / Symbol('p') )
def test_mul_binop(): src1 = ( src + """\ d = a + b - c c = a * b + d s = p * q / r r = p * s + q / p """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 12): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('d')), Symbol('a') + Symbol('b') - Symbol('c') ) assert ls1[9] == Assignment( Variable(Symbol('c')), Symbol('a') * Symbol('b') + Symbol('d') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') * Symbol('q') / Symbol('r') ) assert ls1[11] == Assignment( Variable(Symbol('r')), Symbol('p') * Symbol('s') + Symbol('q') / Symbol('p') )
def test_function(): src1 = """\ integer function f(a,b) integer :: x, y f = x + y end function """ expr1.convert_to_expr(src1, 'f') for iter in expr1.return_expr(): assert isinstance(iter, FunctionDefinition) assert iter == FunctionDefinition( IntBaseType(String('integer')), name=String('f'), parameters=( Variable(Symbol('a')), Variable(Symbol('b')) ), body=CodeBlock( Declaration( Variable( Symbol('a'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Declaration( Variable( Symbol('b'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Declaration( Variable( Symbol('f'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Declaration( Variable( Symbol('x'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Declaration( Variable( Symbol('y'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Assignment( Variable(Symbol('f')), Add(Symbol('x'), Symbol('y')) ), Return(Variable(Symbol('f'))) ) )
def test_var(): expr1.convert_to_expr(src, 'f') ls = expr1.return_expr() for iter in expr1.return_expr(): assert isinstance(iter, Declaration) assert ls[0] == Declaration( Variable( Symbol('a'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls[1] == Declaration( Variable( Symbol('b'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls[2] == Declaration( Variable( Symbol('c'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls[3] == Declaration( Variable( Symbol('d'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls[4] == Declaration( Variable( Symbol('p'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls[5] == Declaration( Variable( Symbol('q'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls[6] == Declaration( Variable( Symbol('r'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls[7] == Declaration( Variable( Symbol('s'), type = FloatBaseType(String('real')), value = Float(0.0) ) )
else: def test_raise(): from sympy.parsing.fortran.fortran_parser import ASR2PyVisitor raises(ImportError, lambda: ASR2PyVisitor()) raises(ImportError, lambda: SymPyExpression(' ', mode = 'f'))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195import sympyfrom sympy.parsing.sympy_parser import ( parse_expr, standard_transformations, convert_xor, implicit_multiplication_application, implicit_multiplication, implicit_application, function_exponentiation, split_symbols, split_symbols_custom, _token_splittable)from sympy.testing.pytest import raises
def test_implicit_multiplication(): cases = { '5x': '5*x', 'abc': 'a*b*c', '3sin(x)': '3*sin(x)', '(x+1)(x+2)': '(x+1)*(x+2)', '(5 x**2)sin(x)': '(5*x**2)*sin(x)', '2 sin(x) cos(x)': '2*sin(x)*cos(x)', 'pi x': 'pi*x', 'x pi': 'x*pi', 'E x': 'E*x', 'EulerGamma y': 'EulerGamma*y', 'E pi': 'E*pi', 'pi (x + 2)': 'pi*(x+2)', '(x + 2) pi': '(x+2)*pi', 'pi sin(x)': 'pi*sin(x)', } transformations = standard_transformations + (convert_xor,) transformations2 = transformations + (split_symbols, implicit_multiplication) for case in cases: implicit = parse_expr(case, transformations=transformations2) normal = parse_expr(cases[case], transformations=transformations) assert(implicit == normal)
application = ['sin x', 'cos 2*x', 'sin cos x'] for case in application: raises(SyntaxError, lambda: parse_expr(case, transformations=transformations2)) raises(TypeError, lambda: parse_expr('sin**2(x)', transformations=transformations2))
def test_implicit_application(): cases = { 'factorial': 'factorial', 'sin x': 'sin(x)', 'tan y**3': 'tan(y**3)', 'cos 2*x': 'cos(2*x)', '(cot)': 'cot', 'sin cos tan x': 'sin(cos(tan(x)))' } transformations = standard_transformations + (convert_xor,) transformations2 = transformations + (implicit_application,) for case in cases: implicit = parse_expr(case, transformations=transformations2) normal = parse_expr(cases[case], transformations=transformations) assert(implicit == normal), (implicit, normal)
multiplication = ['x y', 'x sin x', '2x'] for case in multiplication: raises(SyntaxError, lambda: parse_expr(case, transformations=transformations2)) raises(TypeError, lambda: parse_expr('sin**2(x)', transformations=transformations2))
def test_function_exponentiation(): cases = { 'sin**2(x)': 'sin(x)**2', 'exp^y(z)': 'exp(z)^y', 'sin**2(E^(x))': 'sin(E^(x))**2' } transformations = standard_transformations + (convert_xor,) transformations2 = transformations + (function_exponentiation,) for case in cases: implicit = parse_expr(case, transformations=transformations2) normal = parse_expr(cases[case], transformations=transformations) assert(implicit == normal)
other_implicit = ['x y', 'x sin x', '2x', 'sin x', 'cos 2*x', 'sin cos x'] for case in other_implicit: raises(SyntaxError, lambda: parse_expr(case, transformations=transformations2))
assert parse_expr('x**2', local_dict={ 'x': sympy.Symbol('x') }, transformations=transformations2) == parse_expr('x**2')
def test_symbol_splitting(): # By default Greek letter names should not be split (lambda is a keyword # so skip it) transformations = standard_transformations + (split_symbols,) greek_letters = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')
for letter in greek_letters: assert(parse_expr(letter, transformations=transformations) == parse_expr(letter))
# Make sure symbol splitting resolves names transformations += (implicit_multiplication,) local_dict = { 'e': sympy.E } cases = { 'xe': 'E*x', 'Iy': 'I*y', 'ee': 'E*E', } for case, expected in cases.items(): assert(parse_expr(case, local_dict=local_dict, transformations=transformations) == parse_expr(expected))
# Make sure custom splitting works def can_split(symbol): if symbol not in ('unsplittable', 'names'): return _token_splittable(symbol) return False transformations = standard_transformations transformations += (split_symbols_custom(can_split), implicit_multiplication)
assert(parse_expr('unsplittable', transformations=transformations) == parse_expr('unsplittable')) assert(parse_expr('names', transformations=transformations) == parse_expr('names')) assert(parse_expr('xy', transformations=transformations) == parse_expr('x*y')) for letter in greek_letters: assert(parse_expr(letter, transformations=transformations) == parse_expr(letter))
def test_all_implicit_steps(): cases = { '2x': '2*x', # implicit multiplication 'x y': 'x*y', 'xy': 'x*y', 'sin x': 'sin(x)', # add parentheses '2sin x': '2*sin(x)', 'x y z': 'x*y*z', 'sin(2 * 3x)': 'sin(2 * 3 * x)', 'sin(x) (1 + cos(x))': 'sin(x) * (1 + cos(x))', '(x + 2) sin(x)': '(x + 2) * sin(x)', '(x + 2) sin x': '(x + 2) * sin(x)', 'sin(sin x)': 'sin(sin(x))', 'sin x!': 'sin(factorial(x))', 'sin x!!': 'sin(factorial2(x))', 'factorial': 'factorial', # don't apply a bare function 'x sin x': 'x * sin(x)', # both application and multiplication 'xy sin x': 'x * y * sin(x)', '(x+2)(x+3)': '(x + 2) * (x+3)', 'x**2 + 2xy + y**2': 'x**2 + 2 * x * y + y**2', # split the xy 'pi': 'pi', # don't mess with constants 'None': 'None', 'ln sin x': 'ln(sin(x))', # multiple implicit function applications 'sin x**2': 'sin(x**2)', # implicit application to an exponential 'alpha': 'Symbol("alpha")', # don't split Greek letters/subscripts 'x_2': 'Symbol("x_2")', 'sin^2 x**2': 'sin(x**2)**2', # function raised to a power 'sin**3(x)': 'sin(x)**3', '(factorial)': 'factorial', 'tan 3x': 'tan(3*x)', 'sin^2(3*E^(x))': 'sin(3*E**(x))**2', 'sin**2(E^(3x))': 'sin(E**(3*x))**2', 'sin^2 (3x*E^(x))': 'sin(3*x*E^x)**2', 'pi sin x': 'pi*sin(x)', } transformations = standard_transformations + (convert_xor,) transformations2 = transformations + (implicit_multiplication_application,) for case in cases: implicit = parse_expr(case, transformations=transformations2) normal = parse_expr(cases[case], transformations=transformations) assert(implicit == normal)
def test_no_methods_implicit_multiplication(): # Issue 21020 u = sympy.Symbol('u') transformations = standard_transformations + \ (implicit_multiplication,) expr = parse_expr('x.is_polynomial(x)', transformations=transformations) assert expr == True expr = parse_expr('(exp(x) / (1 + exp(2x))).subs(exp(x), u)', transformations=transformations) assert expr == u/(u**2 + 1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358from sympy.testing.pytest import raises, XFAILfrom sympy.external import import_module
from sympy.concrete.products import Productfrom sympy.concrete.summations import Sumfrom sympy.core.add import Addfrom sympy.core.function import (Derivative, Function)from sympy.core.mul import Mulfrom sympy.core.numbers import (E, oo)from sympy.core.power import Powfrom sympy.core.relational import (GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Unequality)from sympy.core.symbol import Symbolfrom sympy.functions.combinatorial.factorials import (binomial, factorial)from sympy.functions.elementary.complexes import (Abs, conjugate)from sympy.functions.elementary.exponential import (exp, log)from sympy.functions.elementary.integers import (ceiling, floor)from sympy.functions.elementary.miscellaneous import (root, sqrt)from sympy.functions.elementary.trigonometric import (asin, cos, csc, sec, sin, tan)from sympy.integrals.integrals import Integralfrom sympy.series.limits import Limit
from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Gefrom sympy.physics.quantum.state import Bra, Ketfrom sympy.abc import x, y, z, a, b, c, t, k, nantlr4 = import_module("antlr4")
# disable tests if antlr4-python3-runtime is not presentdisabled = antlr4 is None
theta = Symbol('theta')f = Function('f')
# shorthand definitionsdef _Add(a, b): return Add(a, b, evaluate=False)
def _Mul(a, b): return Mul(a, b, evaluate=False)
def _Pow(a, b): return Pow(a, b, evaluate=False)
def _Sqrt(a): return sqrt(a, evaluate=False)
def _Conjugate(a): return conjugate(a, evaluate=False)
def _Abs(a): return Abs(a, evaluate=False)
def _factorial(a): return factorial(a, evaluate=False)
def _exp(a): return exp(a, evaluate=False)
def _log(a, b): return log(a, b, evaluate=False)
def _binomial(n, k): return binomial(n, k, evaluate=False)
def test_import(): from sympy.parsing.latex._build_latex_antlr import ( build_parser, check_antlr_version, dir_latex_antlr ) # XXX: It would be better to come up with a test for these... del build_parser, check_antlr_version, dir_latex_antlr
# These LaTeX strings should parse to the corresponding SymPy expressionGOOD_PAIRS = [ (r"0", 0), (r"1", 1), (r"-3.14", -3.14), (r"(-7.13)(1.5)", _Mul(-7.13, 1.5)), (r"x", x), (r"2x", 2*x), (r"x^2", x**2), (r"x^\frac{1}{2}", _Pow(x, _Pow(2, -1))), (r"x^{3 + 1}", x**_Add(3, 1)), (r"-c", -c), (r"a \cdot b", a * b), (r"a / b", a / b), (r"a \div b", a / b), (r"a + b", a + b), (r"a + b - a", _Add(a+b, -a)), (r"a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)), (r"(x + y) z", _Mul(_Add(x, y), z)), (r"a'b+ab'", _Add(_Mul(Symbol("a'"), b), _Mul(a, Symbol("b'")))), (r"y''_1", Symbol("y_{1}''")), (r"y_1''", Symbol("y_{1}''")), (r"\left(x + y\right) z", _Mul(_Add(x, y), z)), (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)), (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)), (r"\left[x + y\right] z", _Mul(_Add(x, y), z)), (r"\left\{x + y\right\} z", _Mul(_Add(x, y), z)), (r"1+1", _Add(1, 1)), (r"0+1", _Add(0, 1)), (r"1*2", _Mul(1, 2)), (r"0*1", _Mul(0, 1)), (r"1 \times 2 ", _Mul(1, 2)), (r"x = y", Eq(x, y)), (r"x \neq y", Ne(x, y)), (r"x < y", Lt(x, y)), (r"x > y", Gt(x, y)), (r"x \leq y", Le(x, y)), (r"x \geq y", Ge(x, y)), (r"x \le y", Le(x, y)), (r"x \ge y", Ge(x, y)), (r"\lfloor x \rfloor", floor(x)), (r"\lceil x \rceil", ceiling(x)), (r"\langle x |", Bra('x')), (r"| x \rangle", Ket('x')), (r"\sin \theta", sin(theta)), (r"\sin(\theta)", sin(theta)), (r"\sin^{-1} a", asin(a)), (r"\sin a \cos b", _Mul(sin(a), cos(b))), (r"\sin \cos \theta", sin(cos(theta))), (r"\sin(\cos \theta)", sin(cos(theta))), (r"\frac{a}{b}", a / b), (r"\dfrac{a}{b}", a / b), (r"\tfrac{a}{b}", a / b), (r"\frac12", _Pow(2, -1)), (r"\frac12y", _Mul(_Pow(2, -1), y)), (r"\frac1234", _Mul(_Pow(2, -1), 34)), (r"\frac2{3}", _Mul(2, _Pow(3, -1))), (r"\frac{\sin{x}}2", _Mul(sin(x), _Pow(2, -1))), (r"\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))), (r"\frac{7}{3}", _Mul(7, _Pow(3, -1))), (r"(\csc x)(\sec y)", csc(x)*sec(y)), (r"\lim_{x \to 3} a", Limit(a, x, 3, dir='+-')), (r"\lim_{x \rightarrow 3} a", Limit(a, x, 3, dir='+-')), (r"\lim_{x \Rightarrow 3} a", Limit(a, x, 3, dir='+-')), (r"\lim_{x \longrightarrow 3} a", Limit(a, x, 3, dir='+-')), (r"\lim_{x \Longrightarrow 3} a", Limit(a, x, 3, dir='+-')), (r"\lim_{x \to 3^{+}} a", Limit(a, x, 3, dir='+')), (r"\lim_{x \to 3^{-}} a", Limit(a, x, 3, dir='-')), (r"\lim_{x \to 3^+} a", Limit(a, x, 3, dir='+')), (r"\lim_{x \to 3^-} a", Limit(a, x, 3, dir='-')), (r"\infty", oo), (r"\lim_{x \to \infty} \frac{1}{x}", Limit(_Pow(x, -1), x, oo)), (r"\frac{d}{dx} x", Derivative(x, x)), (r"\frac{d}{dt} x", Derivative(x, t)), (r"f(x)", f(x)), (r"f(x, y)", f(x, y)), (r"f(x, y, z)", f(x, y, z)), (r"f'_1(x)", Function("f_{1}'")(x)), (r"f_{1}''(x+y)", Function("f_{1}''")(x+y)), (r"\frac{d f(x)}{dx}", Derivative(f(x), x)), (r"\frac{d\theta(x)}{dx}", Derivative(Function('theta')(x), x)), (r"x \neq y", Unequality(x, y)), (r"|x|", _Abs(x)), (r"||x||", _Abs(Abs(x))), (r"|x||y|", _Abs(x)*_Abs(y)), (r"||x||y||", _Abs(_Abs(x)*_Abs(y))), (r"\pi^{|xy|}", Symbol('pi')**_Abs(x*y)), (r"\int x dx", Integral(x, x)), (r"\int x d\theta", Integral(x, theta)), (r"\int (x^2 - y)dx", Integral(x**2 - y, x)), (r"\int x + a dx", Integral(_Add(x, a), x)), (r"\int da", Integral(1, a)), (r"\int_0^7 dx", Integral(1, (x, 0, 7))), (r"\int\limits_{0}^{1} x dx", Integral(x, (x, 0, 1))), (r"\int_a^b x dx", Integral(x, (x, a, b))), (r"\int^b_a x dx", Integral(x, (x, a, b))), (r"\int_{a}^b x dx", Integral(x, (x, a, b))), (r"\int^{b}_a x dx", Integral(x, (x, a, b))), (r"\int_{a}^{b} x dx", Integral(x, (x, a, b))), (r"\int^{b}_{a} x dx", Integral(x, (x, a, b))), (r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))), (r"\int (x+a)", Integral(_Add(x, a), x)), (r"\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)), (r"\int \frac{dz}{z}", Integral(Pow(z, -1), z)), (r"\int \frac{3 dz}{z}", Integral(3*Pow(z, -1), z)), (r"\int \frac{1}{x} dx", Integral(Pow(x, -1), x)), (r"\int \frac{1}{a} + \frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)), (r"\int \frac{3 \cdot d\theta}{\theta}", Integral(3*_Pow(theta, -1), theta)), (r"\int \frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)), (r"x_0", Symbol('x_{0}')), (r"x_{1}", Symbol('x_{1}')), (r"x_a", Symbol('x_{a}')), (r"x_{b}", Symbol('x_{b}')), (r"h_\theta", Symbol('h_{theta}')), (r"h_{\theta}", Symbol('h_{theta}')), (r"h_{\theta}(x_0, x_1)", Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))), (r"x!", _factorial(x)), (r"100!", _factorial(100)), (r"\theta!", _factorial(theta)), (r"(x + 1)!", _factorial(_Add(x, 1))), (r"(x!)!", _factorial(_factorial(x))), (r"x!!!", _factorial(_factorial(_factorial(x)))), (r"5!7!", _Mul(_factorial(5), _factorial(7))), (r"\sqrt{x}", sqrt(x)), (r"\sqrt{x + b}", sqrt(_Add(x, b))), (r"\sqrt[3]{\sin x}", root(sin(x), 3)), (r"\sqrt[y]{\sin x}", root(sin(x), y)), (r"\sqrt[\theta]{\sin x}", root(sin(x), theta)), (r"\sqrt{\frac{12}{6}}", _Sqrt(_Mul(12, _Pow(6, -1)))), (r"\overline{z}", _Conjugate(z)), (r"\overline{\overline{z}}", _Conjugate(_Conjugate(z))), (r"\overline{x + y}", _Conjugate(_Add(x, y))), (r"\overline{x} + \overline{y}", _Conjugate(x) + _Conjugate(y)), (r"x < y", StrictLessThan(x, y)), (r"x \leq y", LessThan(x, y)), (r"x > y", StrictGreaterThan(x, y)), (r"x \geq y", GreaterThan(x, y)), (r"\mathit{x}", Symbol('x')), (r"\mathit{test}", Symbol('test')), (r"\mathit{TEST}", Symbol('TEST')), (r"\mathit{HELLO world}", Symbol('HELLO world')), (r"\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))), (r"\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))), (r"\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))), (r"\sum^3_{k = 1} c", Sum(c, (k, 1, 3))), (r"\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))), (r"\sum_{n = 0}^{\infty} \frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))), (r"\prod_{a = b}^{c} x", Product(x, (a, b, c))), (r"\prod_{a = b}^c x", Product(x, (a, b, c))), (r"\prod^{c}_{a = b} x", Product(x, (a, b, c))), (r"\prod^c_{a = b} x", Product(x, (a, b, c))), (r"\exp x", _exp(x)), (r"\exp(x)", _exp(x)), (r"\lg x", _log(x, 10)), (r"\ln x", _log(x, E)), (r"\ln xy", _log(x*y, E)), (r"\log x", _log(x, E)), (r"\log xy", _log(x*y, E)), (r"\log_{2} x", _log(x, 2)), (r"\log_{a} x", _log(x, a)), (r"\log_{11} x", _log(x, 11)), (r"\log_{a^2} x", _log(x, _Pow(a, 2))), (r"[x]", x), (r"[a + b]", _Add(a, b)), (r"\frac{d}{dx} [ \tan x ]", Derivative(tan(x), x)), (r"\binom{n}{k}", _binomial(n, k)), (r"\tbinom{n}{k}", _binomial(n, k)), (r"\dbinom{n}{k}", _binomial(n, k)), (r"\binom{n}{0}", _binomial(n, 0)), (r"x^\binom{n}{k}", _Pow(x, _binomial(n, k))), (r"a \, b", _Mul(a, b)), (r"a \thinspace b", _Mul(a, b)), (r"a \: b", _Mul(a, b)), (r"a \medspace b", _Mul(a, b)), (r"a \; b", _Mul(a, b)), (r"a \thickspace b", _Mul(a, b)), (r"a \quad b", _Mul(a, b)), (r"a \qquad b", _Mul(a, b)), (r"a \! b", _Mul(a, b)), (r"a \negthinspace b", _Mul(a, b)), (r"a \negmedspace b", _Mul(a, b)), (r"a \negthickspace b", _Mul(a, b)), (r"\int x \, dx", Integral(x, x)), (r"\log_2 x", _log(x, 2)), (r"\log_a x", _log(x, a)), (r"5^0 - 4^0", _Add(_Pow(5, 0), _Mul(-1, _Pow(4, 0)))), (r"3x - 1", _Add(_Mul(3, x), -1))]
def test_parseable(): from sympy.parsing.latex import parse_latex for latex_str, sympy_expr in GOOD_PAIRS: assert parse_latex(latex_str) == sympy_expr, latex_str
# These bad LaTeX strings should raise a LaTeXParsingError when parsedBAD_STRINGS = [ r"(", r")", r"\frac{d}{dx}", r"(\frac{d}{dx})", r"\sqrt{}", r"\sqrt", r"\overline{}", r"\overline", r"{", r"}", r"\mathit{x + y}", r"\mathit{21}", r"\frac{2}{}", r"\frac{}{2}", r"\int", r"!", r"!0", r"_", r"^", r"|", r"||x|", r"()", r"((((((((((((((((()))))))))))))))))", r"-", r"\frac{d}{dx} + \frac{d}{dt}", r"f(x,,y)", r"f(x,y,", r"\sin^x", r"\cos^2", r"@", r"#", r"$", r"%", r"&", r"*", r"" "\\", r"~", r"\frac{(2 + x}{1 - x)}",]
def test_not_parseable(): from sympy.parsing.latex import parse_latex, LaTeXParsingError for latex_str in BAD_STRINGS: with raises(LaTeXParsingError): parse_latex(latex_str)
# At time of migration from latex2sympy, should fail but doesn'tFAILING_BAD_STRINGS = [ r"\cos 1 \cos", r"f(,", r"f()", r"a \div \div b", r"a \cdot \cdot b", r"a // b", r"a +", r"1.1.1", r"1 +", r"a / b /",]
@XFAILdef test_failing_not_parseable(): from sympy.parsing.latex import parse_latex, LaTeXParsingError for latex_str in FAILING_BAD_STRINGS: with raises(LaTeXParsingError): parse_latex(latex_str)
# In strict mode, FAILING_BAD_STRINGS would faildef test_strict_mode(): from sympy.parsing.latex import parse_latex, LaTeXParsingError for latex_str in FAILING_BAD_STRINGS: with raises(LaTeXParsingError): parse_latex(latex_str, strict=True)12345678910111213141516from sympy.external import import_modulefrom sympy.testing.pytest import ignore_warnings, raises
antlr4 = import_module("antlr4", warn_not_installed=False)
# disable tests if antlr4-python3-runtime is not presentif antlr4: disabled = True
def test_no_import(): from sympy.parsing.latex import parse_latex
with ignore_warnings(UserWarning): with raises(ImportError): parse_latex('1 + 1')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872from sympy.testing.pytest import XFAILfrom sympy.parsing.latex.lark import parse_latex_larkfrom sympy.external import import_module
from sympy.concrete.products import Productfrom sympy.concrete.summations import Sumfrom sympy.core.function import Derivative, Functionfrom sympy.core.numbers import E, oo, Rationalfrom sympy.core.power import Powfrom sympy.core.parameters import evaluatefrom sympy.core.relational import GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Unequalityfrom sympy.core.symbol import Symbolfrom sympy.functions.combinatorial.factorials import binomial, factorialfrom sympy.functions.elementary.complexes import Abs, conjugatefrom sympy.functions.elementary.exponential import exp, logfrom sympy.functions.elementary.integers import ceiling, floorfrom sympy.functions.elementary.miscellaneous import root, sqrt, Min, Maxfrom sympy.functions.elementary.trigonometric import asin, cos, csc, sec, sin, tanfrom sympy.integrals.integrals import Integralfrom sympy.series.limits import Limitfrom sympy import Matrix, MatAdd, MatMul, Transpose, Tracefrom sympy import I
from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Gefrom sympy.physics.quantum import Bra, Ket, InnerProductfrom sympy.abc import x, y, z, a, b, c, d, t, k, n
from .test_latex import theta, f, _Add, _Mul, _Pow, _Sqrt, _Conjugate, _Abs, _factorial, _exp, _binomial
lark = import_module("lark")
# disable tests if lark is not presentdisabled = lark is None
# shorthand definitions that are only needed for the Lark LaTeX parserdef _Min(*args): return Min(*args, evaluate=False)
def _Max(*args): return Max(*args, evaluate=False)
def _log(a, b=E): if b == E: return log(a, evaluate=False) else: return log(a, b, evaluate=False)
def _MatAdd(a, b): return MatAdd(a, b, evaluate=False)
def _MatMul(a, b): return MatMul(a, b, evaluate=False)
# These LaTeX strings should parse to the corresponding SymPy expressionSYMBOL_EXPRESSION_PAIRS = [ (r"x_0", Symbol('x_{0}')), (r"x_{1}", Symbol('x_{1}')), (r"x_a", Symbol('x_{a}')), (r"x_{b}", Symbol('x_{b}')), (r"h_\theta", Symbol('h_{theta}')), (r"h_{\theta}", Symbol('h_{theta}')), (r"y''_1", Symbol("y''_{1}")), (r"y_1''", Symbol("y_{1}''")), (r"\mathit{x}", Symbol('x')), (r"\mathit{test}", Symbol('test')), (r"\mathit{TEST}", Symbol('TEST')), (r"\mathit{HELLO world}", Symbol('HELLO world')), (r"a'", Symbol("a'")), (r"a''", Symbol("a''")), (r"\alpha'", Symbol("alpha'")), (r"\alpha''", Symbol("alpha''")), (r"a_b", Symbol("a_{b}")), (r"a_b'", Symbol("a_{b}'")), (r"a'_b", Symbol("a'_{b}")), (r"a'_b'", Symbol("a'_{b}'")), (r"a_{b'}", Symbol("a_{b'}")), (r"a_{b'}'", Symbol("a_{b'}'")), (r"a'_{b'}", Symbol("a'_{b'}")), (r"a'_{b'}'", Symbol("a'_{b'}'")), (r"\mathit{foo}'", Symbol("foo'")), (r"\mathit{foo'}", Symbol("foo'")), (r"\mathit{foo'}'", Symbol("foo''")), (r"a_b''", Symbol("a_{b}''")), (r"a''_b", Symbol("a''_{b}")), (r"a''_b'''", Symbol("a''_{b}'''")), (r"a_{b''}", Symbol("a_{b''}")), (r"a_{b''}''", Symbol("a_{b''}''")), (r"a''_{b''}", Symbol("a''_{b''}")), (r"a''_{b''}'''", Symbol("a''_{b''}'''")), (r"\mathit{foo}''", Symbol("foo''")), (r"\mathit{foo''}", Symbol("foo''")), (r"\mathit{foo''}'''", Symbol("foo'''''")), (r"a_\alpha", Symbol("a_{alpha}")), (r"a_\alpha'", Symbol("a_{alpha}'")), (r"a'_\alpha", Symbol("a'_{alpha}")), (r"a'_\alpha'", Symbol("a'_{alpha}'")), (r"a_{\alpha'}", Symbol("a_{alpha'}")), (r"a_{\alpha'}'", Symbol("a_{alpha'}'")), (r"a'_{\alpha'}", Symbol("a'_{alpha'}")), (r"a'_{\alpha'}'", Symbol("a'_{alpha'}'")), (r"a_\alpha''", Symbol("a_{alpha}''")), (r"a''_\alpha", Symbol("a''_{alpha}")), (r"a''_\alpha'''", Symbol("a''_{alpha}'''")), (r"a_{\alpha''}", Symbol("a_{alpha''}")), (r"a_{\alpha''}''", Symbol("a_{alpha''}''")), (r"a''_{\alpha''}", Symbol("a''_{alpha''}")), (r"a''_{\alpha''}'''", Symbol("a''_{alpha''}'''")), (r"\alpha_b", Symbol("alpha_{b}")), (r"\alpha_b'", Symbol("alpha_{b}'")), (r"\alpha'_b", Symbol("alpha'_{b}")), (r"\alpha'_b'", Symbol("alpha'_{b}'")), (r"\alpha_{b'}", Symbol("alpha_{b'}")), (r"\alpha_{b'}'", Symbol("alpha_{b'}'")), (r"\alpha'_{b'}", Symbol("alpha'_{b'}")), (r"\alpha'_{b'}'", Symbol("alpha'_{b'}'")), (r"\alpha_b''", Symbol("alpha_{b}''")), (r"\alpha''_b", Symbol("alpha''_{b}")), (r"\alpha''_b'''", Symbol("alpha''_{b}'''")), (r"\alpha_{b''}", Symbol("alpha_{b''}")), (r"\alpha_{b''}''", Symbol("alpha_{b''}''")), (r"\alpha''_{b''}", Symbol("alpha''_{b''}")), (r"\alpha''_{b''}'''", Symbol("alpha''_{b''}'''")), (r"\alpha_\beta", Symbol("alpha_{beta}")), (r"\alpha_{\beta}", Symbol("alpha_{beta}")), (r"\alpha_{\beta'}", Symbol("alpha_{beta'}")), (r"\alpha_{\beta''}", Symbol("alpha_{beta''}")), (r"\alpha'_\beta", Symbol("alpha'_{beta}")), (r"\alpha'_{\beta}", Symbol("alpha'_{beta}")), (r"\alpha'_{\beta'}", Symbol("alpha'_{beta'}")), (r"\alpha'_{\beta''}", Symbol("alpha'_{beta''}")), (r"\alpha''_\beta", Symbol("alpha''_{beta}")), (r"\alpha''_{\beta}", Symbol("alpha''_{beta}")), (r"\alpha''_{\beta'}", Symbol("alpha''_{beta'}")), (r"\alpha''_{\beta''}", Symbol("alpha''_{beta''}")), (r"\alpha_\beta'", Symbol("alpha_{beta}'")), (r"\alpha_{\beta}'", Symbol("alpha_{beta}'")), (r"\alpha_{\beta'}'", Symbol("alpha_{beta'}'")), (r"\alpha_{\beta''}'", Symbol("alpha_{beta''}'")), (r"\alpha'_\beta'", Symbol("alpha'_{beta}'")), (r"\alpha'_{\beta}'", Symbol("alpha'_{beta}'")), (r"\alpha'_{\beta'}'", Symbol("alpha'_{beta'}'")), (r"\alpha'_{\beta''}'", Symbol("alpha'_{beta''}'")), (r"\alpha''_\beta'", Symbol("alpha''_{beta}'")), (r"\alpha''_{\beta}'", Symbol("alpha''_{beta}'")), (r"\alpha''_{\beta'}'", Symbol("alpha''_{beta'}'")), (r"\alpha''_{\beta''}'", Symbol("alpha''_{beta''}'")), (r"\alpha_\beta''", Symbol("alpha_{beta}''")), (r"\alpha_{\beta}''", Symbol("alpha_{beta}''")), (r"\alpha_{\beta'}''", Symbol("alpha_{beta'}''")), (r"\alpha_{\beta''}''", Symbol("alpha_{beta''}''")), (r"\alpha'_\beta''", Symbol("alpha'_{beta}''")), (r"\alpha'_{\beta}''", Symbol("alpha'_{beta}''")), (r"\alpha'_{\beta'}''", Symbol("alpha'_{beta'}''")), (r"\alpha'_{\beta''}''", Symbol("alpha'_{beta''}''")), (r"\alpha''_\beta''", Symbol("alpha''_{beta}''")), (r"\alpha''_{\beta}''", Symbol("alpha''_{beta}''")), (r"\alpha''_{\beta'}''", Symbol("alpha''_{beta'}''")), (r"\alpha''_{\beta''}''", Symbol("alpha''_{beta''}''"))
]
UNEVALUATED_SIMPLE_EXPRESSION_PAIRS = [ (r"0", 0), (r"1", 1), (r"-3.14", -3.14), (r"(-7.13)(1.5)", _Mul(-7.13, 1.5)), (r"1+1", _Add(1, 1)), (r"0+1", _Add(0, 1)), (r"1*2", _Mul(1, 2)), (r"0*1", _Mul(0, 1)), (r"x", x), (r"2x", 2 * x), (r"3x - 1", _Add(_Mul(3, x), -1)), (r"-c", -c), (r"\infty", oo), (r"a \cdot b", a * b), (r"1 \times 2 ", _Mul(1, 2)), (r"a / b", a / b), (r"a \div b", a / b), (r"a + b", a + b), (r"a + b - a", _Add(a + b, -a)), (r"(x + y) z", _Mul(_Add(x, y), z)), (r"a'b+ab'", _Add(_Mul(Symbol("a'"), b), _Mul(a, Symbol("b'"))))]
EVALUATED_SIMPLE_EXPRESSION_PAIRS = [ (r"(-7.13)(1.5)", -10.695), (r"1+1", 2), (r"0+1", 1), (r"1*2", 2), (r"0*1", 0), (r"2x", 2 * x), (r"3x - 1", 3 * x - 1), (r"-c", -c), (r"a \cdot b", a * b), (r"1 \times 2 ", 2), (r"a / b", a / b), (r"a \div b", a / b), (r"a + b", a + b), (r"a + b - a", b), (r"(x + y) z", (x + y) * z),]
UNEVALUATED_FRACTION_EXPRESSION_PAIRS = [ (r"\frac{a}{b}", a / b), (r"\dfrac{a}{b}", a / b), (r"\tfrac{a}{b}", a / b), (r"\frac12", _Mul(1, _Pow(2, -1))), (r"\frac12y", _Mul(_Mul(1, _Pow(2, -1)), y)), (r"\frac1234", _Mul(_Mul(1, _Pow(2, -1)), 34)), (r"\frac2{3}", _Mul(2, _Pow(3, -1))), (r"\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))), (r"\frac{7}{3}", _Mul(7, _Pow(3, -1)))]
EVALUATED_FRACTION_EXPRESSION_PAIRS = [ (r"\frac{a}{b}", a / b), (r"\dfrac{a}{b}", a / b), (r"\tfrac{a}{b}", a / b), (r"\frac12", Rational(1, 2)), (r"\frac12y", y / 2), (r"\frac1234", 17), (r"\frac2{3}", Rational(2, 3)), (r"\frac{a + b}{c}", (a + b) / c), (r"\frac{7}{3}", Rational(7, 3))]
RELATION_EXPRESSION_PAIRS = [ (r"x = y", Eq(x, y)), (r"x \neq y", Ne(x, y)), (r"x < y", Lt(x, y)), (r"x > y", Gt(x, y)), (r"x \leq y", Le(x, y)), (r"x \geq y", Ge(x, y)), (r"x \le y", Le(x, y)), (r"x \ge y", Ge(x, y)), (r"x < y", StrictLessThan(x, y)), (r"x \leq y", LessThan(x, y)), (r"x > y", StrictGreaterThan(x, y)), (r"x \geq y", GreaterThan(x, y)), (r"x \neq y", Unequality(x, y)), # same as 2nd one in the list (r"a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2))]
UNEVALUATED_POWER_EXPRESSION_PAIRS = [ (r"x^2", x ** 2), (r"x^\frac{1}{2}", _Pow(x, _Mul(1, _Pow(2, -1)))), (r"x^{3 + 1}", x ** _Add(3, 1)), (r"\pi^{|xy|}", Symbol('pi') ** _Abs(x * y)), (r"5^0 - 4^0", _Add(_Pow(5, 0), _Mul(-1, _Pow(4, 0))))]
EVALUATED_POWER_EXPRESSION_PAIRS = [ (r"x^2", x ** 2), (r"x^\frac{1}{2}", sqrt(x)), (r"x^{3 + 1}", x ** 4), (r"\pi^{|xy|}", Symbol('pi') ** _Abs(x * y)), (r"5^0 - 4^0", 0)]
UNEVALUATED_INTEGRAL_EXPRESSION_PAIRS = [ (r"\int x dx", Integral(_Mul(1, x), x)), (r"\int x \, dx", Integral(_Mul(1, x), x)), (r"\int x d\theta", Integral(_Mul(1, x), theta)), (r"\int (x^2 - y)dx", Integral(_Mul(1, x ** 2 - y), x)), (r"\int x + a dx", Integral(_Mul(1, _Add(x, a)), x)), (r"\int da", Integral(_Mul(1, 1), a)), (r"\int_0^7 dx", Integral(_Mul(1, 1), (x, 0, 7))), (r"\int\limits_{0}^{1} x dx", Integral(_Mul(1, x), (x, 0, 1))), (r"\int_a^b x dx", Integral(_Mul(1, x), (x, a, b))), (r"\int^b_a x dx", Integral(_Mul(1, x), (x, a, b))), (r"\int_{a}^b x dx", Integral(_Mul(1, x), (x, a, b))), (r"\int^{b}_a x dx", Integral(_Mul(1, x), (x, a, b))), (r"\int_{a}^{b} x dx", Integral(_Mul(1, x), (x, a, b))), (r"\int^{b}_{a} x dx", Integral(_Mul(1, x), (x, a, b))), (r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))), (r"\int a + b + c dx", Integral(_Mul(1, _Add(_Add(a, b), c)), x)), (r"\int \frac{dz}{z}", Integral(_Mul(1, _Mul(1, Pow(z, -1))), z)), (r"\int \frac{3 dz}{z}", Integral(_Mul(1, _Mul(3, _Pow(z, -1))), z)), (r"\int \frac{1}{x} dx", Integral(_Mul(1, _Mul(1, Pow(x, -1))), x)), (r"\int \frac{1}{a} + \frac{1}{b} dx", Integral(_Mul(1, _Add(_Mul(1, _Pow(a, -1)), _Mul(1, Pow(b, -1)))), x)), (r"\int \frac{1}{x} + 1 dx", Integral(_Mul(1, _Add(_Mul(1, _Pow(x, -1)), 1)), x))]
EVALUATED_INTEGRAL_EXPRESSION_PAIRS = [ (r"\int x dx", Integral(x, x)), (r"\int x \, dx", Integral(x, x)), (r"\int x d\theta", Integral(x, theta)), (r"\int (x^2 - y)dx", Integral(x ** 2 - y, x)), (r"\int x + a dx", Integral(x + a, x)), (r"\int da", Integral(1, a)), (r"\int_0^7 dx", Integral(1, (x, 0, 7))), (r"\int\limits_{0}^{1} x dx", Integral(x, (x, 0, 1))), (r"\int_a^b x dx", Integral(x, (x, a, b))), (r"\int^b_a x dx", Integral(x, (x, a, b))), (r"\int_{a}^b x dx", Integral(x, (x, a, b))), (r"\int^{b}_a x dx", Integral(x, (x, a, b))), (r"\int_{a}^{b} x dx", Integral(x, (x, a, b))), (r"\int^{b}_{a} x dx", Integral(x, (x, a, b))), (r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))), (r"\int a + b + c dx", Integral(a + b + c, x)), (r"\int \frac{dz}{z}", Integral(Pow(z, -1), z)), (r"\int \frac{3 dz}{z}", Integral(3 * Pow(z, -1), z)), (r"\int \frac{1}{x} dx", Integral(1 / x, x)), (r"\int \frac{1}{a} + \frac{1}{b} dx", Integral(1 / a + 1 / b, x)), (r"\int \frac{1}{a} - \frac{1}{b} dx", Integral(1 / a - 1 / b, x)), (r"\int \frac{1}{x} + 1 dx", Integral(1 / x + 1, x))]
DERIVATIVE_EXPRESSION_PAIRS = [ (r"\frac{d}{dx} x", Derivative(x, x)), (r"\frac{d}{dt} x", Derivative(x, t)), (r"\frac{d}{dx} ( \tan x )", Derivative(tan(x), x)), (r"\frac{d f(x)}{dx}", Derivative(f(x), x)), (r"\frac{d\theta(x)}{dx}", Derivative(Function('theta')(x), x))]
TRIGONOMETRIC_EXPRESSION_PAIRS = [ (r"\sin \theta", sin(theta)), (r"\sin(\theta)", sin(theta)), (r"\sin^{-1} a", asin(a)), (r"\sin a \cos b", _Mul(sin(a), cos(b))), (r"\sin \cos \theta", sin(cos(theta))), (r"\sin(\cos \theta)", sin(cos(theta))), (r"(\csc x)(\sec y)", csc(x) * sec(y)), (r"\frac{\sin{x}}2", _Mul(sin(x), _Pow(2, -1)))]
UNEVALUATED_LIMIT_EXPRESSION_PAIRS = [ (r"\lim_{x \to 3} a", Limit(a, x, 3, dir="+-")), (r"\lim_{x \rightarrow 3} a", Limit(a, x, 3, dir="+-")), (r"\lim_{x \Rightarrow 3} a", Limit(a, x, 3, dir="+-")), (r"\lim_{x \longrightarrow 3} a", Limit(a, x, 3, dir="+-")), (r"\lim_{x \Longrightarrow 3} a", Limit(a, x, 3, dir="+-")), (r"\lim_{x \to 3^{+}} a", Limit(a, x, 3, dir="+")), (r"\lim_{x \to 3^{-}} a", Limit(a, x, 3, dir="-")), (r"\lim_{x \to 3^+} a", Limit(a, x, 3, dir="+")), (r"\lim_{x \to 3^-} a", Limit(a, x, 3, dir="-")), (r"\lim_{x \to \infty} \frac{1}{x}", Limit(_Mul(1, _Pow(x, -1)), x, oo))]
EVALUATED_LIMIT_EXPRESSION_PAIRS = [ (r"\lim_{x \to \infty} \frac{1}{x}", Limit(1 / x, x, oo))]
UNEVALUATED_SQRT_EXPRESSION_PAIRS = [ (r"\sqrt{x}", sqrt(x)), (r"\sqrt{x + b}", sqrt(_Add(x, b))), (r"\sqrt[3]{\sin x}", _Pow(sin(x), _Pow(3, -1))), # the above test needed to be handled differently than the ones below because root # acts differently if its second argument is a number (r"\sqrt[y]{\sin x}", root(sin(x), y)), (r"\sqrt[\theta]{\sin x}", root(sin(x), theta)), (r"\sqrt{\frac{12}{6}}", _Sqrt(_Mul(12, _Pow(6, -1))))]
EVALUATED_SQRT_EXPRESSION_PAIRS = [ (r"\sqrt{x}", sqrt(x)), (r"\sqrt{x + b}", sqrt(x + b)), (r"\sqrt[3]{\sin x}", root(sin(x), 3)), (r"\sqrt[y]{\sin x}", root(sin(x), y)), (r"\sqrt[\theta]{\sin x}", root(sin(x), theta)), (r"\sqrt{\frac{12}{6}}", sqrt(2))]
UNEVALUATED_FACTORIAL_EXPRESSION_PAIRS = [ (r"x!", _factorial(x)), (r"100!", _factorial(100)), (r"\theta!", _factorial(theta)), (r"(x + 1)!", _factorial(_Add(x, 1))), (r"(x!)!", _factorial(_factorial(x))), (r"x!!!", _factorial(_factorial(_factorial(x)))), (r"5!7!", _Mul(_factorial(5), _factorial(7)))]
EVALUATED_FACTORIAL_EXPRESSION_PAIRS = [ (r"x!", factorial(x)), (r"100!", factorial(100)), (r"\theta!", factorial(theta)), (r"(x + 1)!", factorial(x + 1)), (r"(x!)!", factorial(factorial(x))), (r"x!!!", factorial(factorial(factorial(x)))), (r"5!7!", factorial(5) * factorial(7)), (r"24! \times 24!", factorial(24) * factorial(24))]
UNEVALUATED_SUM_EXPRESSION_PAIRS = [ (r"\sum_{k = 1}^{3} c", Sum(_Mul(1, c), (k, 1, 3))), (r"\sum_{k = 1}^3 c", Sum(_Mul(1, c), (k, 1, 3))), (r"\sum^{3}_{k = 1} c", Sum(_Mul(1, c), (k, 1, 3))), (r"\sum^3_{k = 1} c", Sum(_Mul(1, c), (k, 1, 3))), (r"\sum_{k = 1}^{10} k^2", Sum(_Mul(1, k ** 2), (k, 1, 10))), (r"\sum_{n = 0}^{\infty} \frac{1}{n!}", Sum(_Mul(1, _Mul(1, _Pow(_factorial(n), -1))), (n, 0, oo)))]
EVALUATED_SUM_EXPRESSION_PAIRS = [ (r"\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))), (r"\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))), (r"\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))), (r"\sum^3_{k = 1} c", Sum(c, (k, 1, 3))), (r"\sum_{k = 1}^{10} k^2", Sum(k ** 2, (k, 1, 10))), (r"\sum_{n = 0}^{\infty} \frac{1}{n!}", Sum(1 / factorial(n), (n, 0, oo)))]
UNEVALUATED_PRODUCT_EXPRESSION_PAIRS = [ (r"\prod_{a = b}^{c} x", Product(x, (a, b, c))), (r"\prod_{a = b}^c x", Product(x, (a, b, c))), (r"\prod^{c}_{a = b} x", Product(x, (a, b, c))), (r"\prod^c_{a = b} x", Product(x, (a, b, c)))]
APPLIED_FUNCTION_EXPRESSION_PAIRS = [ (r"f(x)", f(x)), (r"f(x, y)", f(x, y)), (r"f(x, y, z)", f(x, y, z)), (r"f'_1(x)", Function("f_{1}'")(x)), (r"f_{1}''(x+y)", Function("f_{1}''")(x + y)), (r"h_{\theta}(x_0, x_1)", Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}')))]
UNEVALUATED_COMMON_FUNCTION_EXPRESSION_PAIRS = [ (r"|x|", _Abs(x)), (r"||x||", _Abs(Abs(x))), (r"|x||y|", _Abs(x) * _Abs(y)), (r"||x||y||", _Abs(_Abs(x) * _Abs(y))), (r"\lfloor x \rfloor", floor(x)), (r"\lceil x \rceil", ceiling(x)), (r"\exp x", _exp(x)), (r"\exp(x)", _exp(x)), (r"\lg x", _log(x, 10)), (r"\ln x", _log(x)), (r"\ln xy", _log(x * y)), (r"\log x", _log(x)), (r"\log xy", _log(x * y)), (r"\log_{2} x", _log(x, 2)), (r"\log_{a} x", _log(x, a)), (r"\log_{11} x", _log(x, 11)), (r"\log_{a^2} x", _log(x, _Pow(a, 2))), (r"\log_2 x", _log(x, 2)), (r"\log_a x", _log(x, a)), (r"\overline{z}", _Conjugate(z)), (r"\overline{\overline{z}}", _Conjugate(_Conjugate(z))), (r"\overline{x + y}", _Conjugate(_Add(x, y))), (r"\overline{x} + \overline{y}", _Conjugate(x) + _Conjugate(y)), (r"\min(a, b)", _Min(a, b)), (r"\min(a, b, c - d, xy)", _Min(a, b, c - d, x * y)), (r"\max(a, b)", _Max(a, b)), (r"\max(a, b, c - d, xy)", _Max(a, b, c - d, x * y)), # physics things don't have an `evaluate=False` variant (r"\langle x |", Bra('x')), (r"| x \rangle", Ket('x')), (r"\langle x | y \rangle", InnerProduct(Bra('x'), Ket('y'))),]
EVALUATED_COMMON_FUNCTION_EXPRESSION_PAIRS = [ (r"|x|", Abs(x)), (r"||x||", Abs(Abs(x))), (r"|x||y|", Abs(x) * Abs(y)), (r"||x||y||", Abs(Abs(x) * Abs(y))), (r"\lfloor x \rfloor", floor(x)), (r"\lceil x \rceil", ceiling(x)), (r"\exp x", exp(x)), (r"\exp(x)", exp(x)), (r"\lg x", log(x, 10)), (r"\ln x", log(x)), (r"\ln xy", log(x * y)), (r"\log x", log(x)), (r"\log xy", log(x * y)), (r"\log_{2} x", log(x, 2)), (r"\log_{a} x", log(x, a)), (r"\log_{11} x", log(x, 11)), (r"\log_{a^2} x", log(x, _Pow(a, 2))), (r"\log_2 x", log(x, 2)), (r"\log_a x", log(x, a)), (r"\overline{z}", conjugate(z)), (r"\overline{\overline{z}}", conjugate(conjugate(z))), (r"\overline{x + y}", conjugate(x + y)), (r"\overline{x} + \overline{y}", conjugate(x) + conjugate(y)), (r"\min(a, b)", Min(a, b)), (r"\min(a, b, c - d, xy)", Min(a, b, c - d, x * y)), (r"\max(a, b)", Max(a, b)), (r"\max(a, b, c - d, xy)", Max(a, b, c - d, x * y)), (r"\langle x |", Bra('x')), (r"| x \rangle", Ket('x')), (r"\langle x | y \rangle", InnerProduct(Bra('x'), Ket('y'))),]
SPACING_RELATED_EXPRESSION_PAIRS = [ (r"a \, b", _Mul(a, b)), (r"a \thinspace b", _Mul(a, b)), (r"a \: b", _Mul(a, b)), (r"a \medspace b", _Mul(a, b)), (r"a \; b", _Mul(a, b)), (r"a \thickspace b", _Mul(a, b)), (r"a \quad b", _Mul(a, b)), (r"a \qquad b", _Mul(a, b)), (r"a \! b", _Mul(a, b)), (r"a \negthinspace b", _Mul(a, b)), (r"a \negmedspace b", _Mul(a, b)), (r"a \negthickspace b", _Mul(a, b))]
UNEVALUATED_BINOMIAL_EXPRESSION_PAIRS = [ (r"\binom{n}{k}", _binomial(n, k)), (r"\tbinom{n}{k}", _binomial(n, k)), (r"\dbinom{n}{k}", _binomial(n, k)), (r"\binom{n}{0}", _binomial(n, 0)), (r"x^\binom{n}{k}", _Pow(x, _binomial(n, k)))]
EVALUATED_BINOMIAL_EXPRESSION_PAIRS = [ (r"\binom{n}{k}", binomial(n, k)), (r"\tbinom{n}{k}", binomial(n, k)), (r"\dbinom{n}{k}", binomial(n, k)), (r"\binom{n}{0}", binomial(n, 0)), (r"x^\binom{n}{k}", x ** binomial(n, k))]
MISCELLANEOUS_EXPRESSION_PAIRS = [ (r"\left(x + y\right) z", _Mul(_Add(x, y), z)), (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)), (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)),]
UNEVALUATED_LITERAL_COMPLEX_NUMBER_EXPRESSION_PAIRS = [ (r"\imaginaryunit^2", _Pow(I, 2)), (r"|\imaginaryunit|", _Abs(I)), (r"\overline{\imaginaryunit}", _Conjugate(I)), (r"\imaginaryunit+\imaginaryunit", _Add(I, I)), (r"\imaginaryunit-\imaginaryunit", _Add(I, -I)), (r"\imaginaryunit*\imaginaryunit", _Mul(I, I)), (r"\imaginaryunit/\imaginaryunit", _Mul(I, _Pow(I, -1))), (r"(1+\imaginaryunit)/|1+\imaginaryunit|", _Mul(_Add(1, I), _Pow(_Abs(_Add(1, I)), -1)))]
UNEVALUATED_MATRIX_EXPRESSION_PAIRS = [ (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}", Matrix([[a, b], [x, y]])), (r"\begin{pmatrix}a & b \\x & y\\\end{pmatrix}", Matrix([[a, b], [x, y]])), (r"\begin{bmatrix}a & b \\x & y\end{bmatrix}", Matrix([[a, b], [x, y]])), (r"\left(\begin{matrix}a & b \\x & y\end{matrix}\right)", Matrix([[a, b], [x, y]])), (r"\left[\begin{matrix}a & b \\x & y\end{matrix}\right]", Matrix([[a, b], [x, y]])), (r"\left[\begin{array}{cc}a & b \\x & y\end{array}\right]", Matrix([[a, b], [x, y]])), (r"\left(\begin{array}{cc}a & b \\x & y\end{array}\right)", Matrix([[a, b], [x, y]])), (r"\left( { \begin{array}{cc}a & b \\x & y\end{array} } \right)", Matrix([[a, b], [x, y]])), (r"+\begin{pmatrix}a & b \\x & y\end{pmatrix}", Matrix([[a, b], [x, y]])), ((r"\begin{pmatrix}x & y \\a & b\end{pmatrix}+" r"\begin{pmatrix}a & b \\x & y\end{pmatrix}"), _MatAdd(Matrix([[x, y], [a, b]]), Matrix([[a, b], [x, y]]))), (r"-\begin{pmatrix}a & b \\x & y\end{pmatrix}", _MatMul(-1, Matrix([[a, b], [x, y]]))), ((r"\begin{pmatrix}x & y \\a & b\end{pmatrix}-" r"\begin{pmatrix}a & b \\x & y\end{pmatrix}"), _MatAdd(Matrix([[x, y], [a, b]]), _MatMul(-1, Matrix([[a, b], [x, y]])))), ((r"\begin{pmatrix}a & b & c \\x & y & z \\a & b & c \end{pmatrix}*" r"\begin{pmatrix}x & y & z \\a & b & c \\a & b & c \end{pmatrix}*" r"\begin{pmatrix}a & b & c \\x & y & z \\x & y & z \end{pmatrix}"), _MatMul(_MatMul(Matrix([[a, b, c], [x, y, z], [a, b, c]]), Matrix([[x, y, z], [a, b, c], [a, b, c]])), Matrix([[a, b, c], [x, y, z], [x, y, z]]))), (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}/2", _MatMul(Matrix([[a, b], [x, y]]), _Pow(2, -1))), (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^2", _Pow(Matrix([[a, b], [x, y]]), 2)), (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^{-1}", _Pow(Matrix([[a, b], [x, y]]), -1)), (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^T", Transpose(Matrix([[a, b], [x, y]]))), (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^{T}", Transpose(Matrix([[a, b], [x, y]]))), (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^\mathit{T}", Transpose(Matrix([[a, b], [x, y]]))), (r"\begin{pmatrix}1 & 2 \\3 & 4\end{pmatrix}^T", Transpose(Matrix([[1, 2], [3, 4]]))), ((r"(\begin{pmatrix}1 & 2 \\3 & 4\end{pmatrix}+" r"\begin{pmatrix}1 & 2 \\3 & 4\end{pmatrix}^T)*" r"\begin{bmatrix}1\\0\end{bmatrix}"), _MatMul(_MatAdd(Matrix([[1, 2], [3, 4]]), Transpose(Matrix([[1, 2], [3, 4]]))), Matrix([[1], [0]]))), ((r"(\begin{pmatrix}a & b \\x & y\end{pmatrix}+" r"\begin{pmatrix}x & y \\a & b\end{pmatrix})^2"), _Pow(_MatAdd(Matrix([[a, b], [x, y]]), Matrix([[x, y], [a, b]])), 2)), ((r"(\begin{pmatrix}a & b \\x & y\end{pmatrix}+" r"\begin{pmatrix}x & y \\a & b\end{pmatrix})^T"), Transpose(_MatAdd(Matrix([[a, b], [x, y]]), Matrix([[x, y], [a, b]])))), (r"\overline{\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}}", _Conjugate(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]]))))]
EVALUATED_MATRIX_EXPRESSION_PAIRS = [ (r"\det\left(\left[ { \begin{array}{cc}a&b\\x&y\end{array} } \right]\right)", Matrix([[a, b], [x, y]]).det()), (r"\det \begin{pmatrix}1&2\\3&4\end{pmatrix}", -2), (r"\det{\begin{pmatrix}1&2\\3&4\end{pmatrix}}", -2), (r"\det(\begin{pmatrix}1&2\\3&4\end{pmatrix})", -2), (r"\det\left(\begin{pmatrix}1&2\\3&4\end{pmatrix}\right)", -2), (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}/\begin{vmatrix}a & b \\x & y\end{vmatrix}", _MatMul(Matrix([[a, b], [x, y]]), _Pow(Matrix([[a, b], [x, y]]).det(), -1))), (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}/|\begin{matrix}a & b \\x & y\end{matrix}|", _MatMul(Matrix([[a, b], [x, y]]), _Pow(Matrix([[a, b], [x, y]]).det(), -1))), (r"\frac{\begin{pmatrix}a & b \\x & y\end{pmatrix}}{| { \begin{matrix}a & b \\x & y\end{matrix} } |}", _MatMul(Matrix([[a, b], [x, y]]), _Pow(Matrix([[a, b], [x, y]]).det(), -1))), (r"\overline{\begin{pmatrix}\imaginaryunit & 1+\imaginaryunit \\-\imaginaryunit & 4\end{pmatrix}}", Matrix([[-I, 1-I], [I, 4]])), (r"\begin{pmatrix}\imaginaryunit & 1+\imaginaryunit \\-\imaginaryunit & 4\end{pmatrix}^H", Matrix([[-I, I], [1-I, 4]])), (r"\trace(\begin{pmatrix}\imaginaryunit & 1+\imaginaryunit \\-\imaginaryunit & 4\end{pmatrix})", Trace(Matrix([[I, 1+I], [-I, 4]]))), (r"\adjugate(\begin{pmatrix}1 & 2 \\3 & 4\end{pmatrix})", Matrix([[4, -2], [-3, 1]])), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^\ast", Matrix([[-2*I, 6], [4, 8]])), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\ast}", Matrix([[-2*I, 6], [4, 8]])), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\ast\ast}", Matrix([[2*I, 4], [6, 8]])), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\ast\ast\ast}", Matrix([[-2*I, 6], [4, 8]])), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{*}", Matrix([[-2*I, 6], [4, 8]])), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{**}", Matrix([[2*I, 4], [6, 8]])), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{***}", Matrix([[-2*I, 6], [4, 8]])), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^\prime", Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]])))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\prime}", Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]])))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\prime\prime}", _MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]]))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\prime\prime\prime}", Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]])))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{'}", Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]])))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{''}", _MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]]))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{'''}", Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]])))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})'", Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]])))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})''", _MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]]))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})'''", Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]])))), (r"\det(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})", (_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]]))).det()), (r"\trace(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})", Trace(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]])))), (r"\adjugate(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})", (Matrix([[8, -4], [-6, 2*I]]))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^T", Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]), Matrix([[I, 2], [3, 4]])))), (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^H", (Matrix([[-2*I, 6], [4, 8]])))]
def test_symbol_expressions(): expected_failures = {6, 7} for i, (latex_str, sympy_expr) in enumerate(SYMBOL_EXPRESSION_PAIRS): if i in expected_failures: continue with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_simple_expressions(): expected_failures = {20} for i, (latex_str, sympy_expr) in enumerate(UNEVALUATED_SIMPLE_EXPRESSION_PAIRS): if i in expected_failures: continue with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for i, (latex_str, sympy_expr) in enumerate(EVALUATED_SIMPLE_EXPRESSION_PAIRS): if i in expected_failures: continue assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_fraction_expressions(): for latex_str, sympy_expr in UNEVALUATED_FRACTION_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for latex_str, sympy_expr in EVALUATED_FRACTION_EXPRESSION_PAIRS: assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_relation_expressions(): for latex_str, sympy_expr in RELATION_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_power_expressions(): expected_failures = {3} for i, (latex_str, sympy_expr) in enumerate(UNEVALUATED_POWER_EXPRESSION_PAIRS): if i in expected_failures: continue with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for i, (latex_str, sympy_expr) in enumerate(EVALUATED_POWER_EXPRESSION_PAIRS): if i in expected_failures: continue assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_integral_expressions(): expected_failures = {14} for i, (latex_str, sympy_expr) in enumerate(UNEVALUATED_INTEGRAL_EXPRESSION_PAIRS): if i in expected_failures: continue with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, i
for i, (latex_str, sympy_expr) in enumerate(EVALUATED_INTEGRAL_EXPRESSION_PAIRS): if i in expected_failures: continue assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_derivative_expressions(): expected_failures = {3, 4} for i, (latex_str, sympy_expr) in enumerate(DERIVATIVE_EXPRESSION_PAIRS): if i in expected_failures: continue with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for i, (latex_str, sympy_expr) in enumerate(DERIVATIVE_EXPRESSION_PAIRS): if i in expected_failures: continue assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_trigonometric_expressions(): expected_failures = {3} for i, (latex_str, sympy_expr) in enumerate(TRIGONOMETRIC_EXPRESSION_PAIRS): if i in expected_failures: continue with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_limit_expressions(): for latex_str, sympy_expr in UNEVALUATED_LIMIT_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_square_root_expressions(): for latex_str, sympy_expr in UNEVALUATED_SQRT_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for latex_str, sympy_expr in EVALUATED_SQRT_EXPRESSION_PAIRS: assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_factorial_expressions(): for latex_str, sympy_expr in UNEVALUATED_FACTORIAL_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for latex_str, sympy_expr in EVALUATED_FACTORIAL_EXPRESSION_PAIRS: assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_sum_expressions(): for latex_str, sympy_expr in UNEVALUATED_SUM_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for latex_str, sympy_expr in EVALUATED_SUM_EXPRESSION_PAIRS: assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_product_expressions(): for latex_str, sympy_expr in UNEVALUATED_PRODUCT_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
@XFAILdef test_applied_function_expressions(): expected_failures = {0, 3, 4} # 0 is ambiguous, and the others require not-yet-added features # not sure why 1, and 2 are failing for i, (latex_str, sympy_expr) in enumerate(APPLIED_FUNCTION_EXPRESSION_PAIRS): if i in expected_failures: continue with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_common_function_expressions(): for latex_str, sympy_expr in UNEVALUATED_COMMON_FUNCTION_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for latex_str, sympy_expr in EVALUATED_COMMON_FUNCTION_EXPRESSION_PAIRS: assert parse_latex_lark(latex_str) == sympy_expr, latex_str
# unhandled bug causing these to fail@XFAILdef test_spacing(): for latex_str, sympy_expr in SPACING_RELATED_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_binomial_expressions(): for latex_str, sympy_expr in UNEVALUATED_BINOMIAL_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for latex_str, sympy_expr in EVALUATED_BINOMIAL_EXPRESSION_PAIRS: assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_miscellaneous_expressions(): for latex_str, sympy_expr in MISCELLANEOUS_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_literal_complex_number_expressions(): for latex_str, sympy_expr in UNEVALUATED_LITERAL_COMPLEX_NUMBER_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
def test_matrix_expressions(): for latex_str, sympy_expr in UNEVALUATED_MATRIX_EXPRESSION_PAIRS: with evaluate(False): assert parse_latex_lark(latex_str) == sympy_expr, latex_str
for latex_str, sympy_expr in EVALUATED_MATRIX_EXPRESSION_PAIRS: assert parse_latex_lark(latex_str) == sympy_expr, latex_str123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280from sympy import sin, Function, symbols, Dummy, Lambda, cosfrom sympy.parsing.mathematica import parse_mathematica, MathematicaParserfrom sympy.core.sympify import sympifyfrom sympy.abc import n, w, x, y, zfrom sympy.testing.pytest import raises
def test_mathematica(): d = { '- 6x': '-6*x', 'Sin[x]^2': 'sin(x)**2', '2(x-1)': '2*(x-1)', '3y+8': '3*y+8', 'ArcSin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x', 'x+y': 'x+y', '355/113': '355/113', '2.718281828': '2.718281828', 'Cos(1/2 * π)': 'Cos(π/2)', 'Sin[12]': 'sin(12)', 'Exp[Log[4]]': 'exp(log(4))', '(x+1)(x+3)': '(x+1)*(x+3)', 'Cos[ArcCos[3.6]]': 'cos(acos(3.6))', 'Cos[x]==Sin[y]': 'Eq(cos(x), sin(y))', '2*Sin[x+y]': '2*sin(x+y)', 'Sin[x]+Cos[y]': 'sin(x)+cos(y)', 'Sin[Cos[x]]': 'sin(cos(x))', '2*Sqrt[x+y]': '2*sqrt(x+y)', # Test case from the issue 4259 '+Sqrt[2]': 'sqrt(2)', '-Sqrt[2]': '-sqrt(2)', '-1/Sqrt[2]': '-1/sqrt(2)', '-(1/Sqrt[3])': '-(1/sqrt(3))', '1/(2*Sqrt[5])': '1/(2*sqrt(5))', 'Mod[5,3]': 'Mod(5,3)', '-Mod[5,3]': '-Mod(5,3)', '(x+1)y': '(x+1)*y', 'x(y+1)': 'x*(y+1)', 'Sin[x]Cos[y]': 'sin(x)*cos(y)', 'Sin[x]^2Cos[y]^2': 'sin(x)**2*cos(y)**2', 'Cos[x]^2(1 - Cos[y]^2)': 'cos(x)**2*(1-cos(y)**2)', 'x y': 'x*y', 'x y': 'x*y', '2 x': '2*x', 'x 8': 'x*8', '2 8': '2*8', '4.x': '4.*x', '4. 3': '4.*3', '4. 3.': '4.*3.', '1 2 3': '1*2*3', ' - 2 * Sqrt[ 2 3 * ( 1 + 5 ) ] ': '-2*sqrt(2*3*(1+5))', 'Log[2,4]': 'log(4,2)', 'Log[Log[2,4],4]': 'log(4,log(4,2))', 'Exp[Sqrt[2]^2Log[2, 8]]': 'exp(sqrt(2)**2*log(8,2))', 'ArcSin[Cos[0]]': 'asin(cos(0))', 'Log2[16]': 'log(16,2)', 'Max[1,-2,3,-4]': 'Max(1,-2,3,-4)', 'Min[1,-2,3]': 'Min(1,-2,3)', 'Exp[I Pi/2]': 'exp(I*pi/2)', 'ArcTan[x,y]': 'atan2(y,x)', 'Pochhammer[x,y]': 'rf(x,y)', 'ExpIntegralEi[x]': 'Ei(x)', 'SinIntegral[x]': 'Si(x)', 'CosIntegral[x]': 'Ci(x)', 'AiryAi[x]': 'airyai(x)', 'AiryAiPrime[5]': 'airyaiprime(5)', 'AiryBi[x]': 'airybi(x)', 'AiryBiPrime[7]': 'airybiprime(7)', 'LogIntegral[4]': ' li(4)', 'PrimePi[7]': 'primepi(7)', 'Prime[5]': 'prime(5)', 'PrimeQ[5]': 'isprime(5)', 'Rational[2,19]': 'Rational(2,19)', # test case for issue 25716 }
for e in d: assert parse_mathematica(e) == sympify(d[e])
# The parsed form of this expression should not evaluate the Lambda object: assert parse_mathematica("Sin[#]^2 + Cos[#]^2 &[x]") == sin(x)**2 + cos(x)**2
d1, d2, d3 = symbols("d1:4", cls=Dummy) assert parse_mathematica("Sin[#] + Cos[#3] &").dummy_eq(Lambda((d1, d2, d3), sin(d1) + cos(d3))) assert parse_mathematica("Sin[#^2] &").dummy_eq(Lambda(d1, sin(d1**2))) assert parse_mathematica("Function[x, x^3]") == Lambda(x, x**3) assert parse_mathematica("Function[{x, y}, x^2 + y^2]") == Lambda((x, y), x**2 + y**2)
def test_parser_mathematica_tokenizer(): parser = MathematicaParser()
chain = lambda expr: parser._from_tokens_to_fullformlist(parser._from_mathematica_to_tokens(expr))
# Basic patterns assert chain("x") == "x" assert chain("42") == "42" assert chain(".2") == ".2" assert chain("+x") == "x" assert chain("-1") == "-1" assert chain("- 3") == "-3" assert chain("α") == "α" assert chain("+Sin[x]") == ["Sin", "x"] assert chain("-Sin[x]") == ["Times", "-1", ["Sin", "x"]] assert chain("x(a+1)") == ["Times", "x", ["Plus", "a", "1"]] assert chain("(x)") == "x" assert chain("(+x)") == "x" assert chain("-a") == ["Times", "-1", "a"] assert chain("(-x)") == ["Times", "-1", "x"] assert chain("(x + y)") == ["Plus", "x", "y"] assert chain("3 + 4") == ["Plus", "3", "4"] assert chain("a - 3") == ["Plus", "a", "-3"] assert chain("a - b") == ["Plus", "a", ["Times", "-1", "b"]] assert chain("7 * 8") == ["Times", "7", "8"] assert chain("a + b*c") == ["Plus", "a", ["Times", "b", "c"]] assert chain("a + b* c* d + 2 * e") == ["Plus", "a", ["Times", "b", "c", "d"], ["Times", "2", "e"]] assert chain("a / b") == ["Times", "a", ["Power", "b", "-1"]]
# Missing asterisk (*) patterns: assert chain("x y") == ["Times", "x", "y"] assert chain("3 4") == ["Times", "3", "4"] assert chain("a[b] c") == ["Times", ["a", "b"], "c"] assert chain("(x) (y)") == ["Times", "x", "y"] assert chain("3 (a)") == ["Times", "3", "a"] assert chain("(a) b") == ["Times", "a", "b"] assert chain("4.2") == "4.2" assert chain("4 2") == ["Times", "4", "2"] assert chain("4 2") == ["Times", "4", "2"] assert chain("3 . 4") == ["Dot", "3", "4"] assert chain("4. 2") == ["Times", "4.", "2"] assert chain("x.y") == ["Dot", "x", "y"] assert chain("4.y") == ["Times", "4.", "y"] assert chain("4 .y") == ["Dot", "4", "y"] assert chain("x.4") == ["Times", "x", ".4"] assert chain("x0.3") == ["Times", "x0", ".3"] assert chain("x. 4") == ["Dot", "x", "4"]
# Comments assert chain("a (* +b *) + c") == ["Plus", "a", "c"] assert chain("a (* + b *) + (**)c (* +d *) + e") == ["Plus", "a", "c", "e"] assert chain("""a + (* + b *) c + (* d *) e """) == ["Plus", "a", "c", "e"]
# Operators couples + and -, * and / are mutually associative: # (i.e. expression gets flattened when mixing these operators) assert chain("a*b/c") == ["Times", "a", "b", ["Power", "c", "-1"]] assert chain("a/b*c") == ["Times", "a", ["Power", "b", "-1"], "c"] assert chain("a+b-c") == ["Plus", "a", "b", ["Times", "-1", "c"]] assert chain("a-b+c") == ["Plus", "a", ["Times", "-1", "b"], "c"] assert chain("-a + b -c ") == ["Plus", ["Times", "-1", "a"], "b", ["Times", "-1", "c"]] assert chain("a/b/c*d") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"], "d"] assert chain("a/b/c") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"]] assert chain("a-b-c") == ["Plus", "a", ["Times", "-1", "b"], ["Times", "-1", "c"]] assert chain("1/a") == ["Times", "1", ["Power", "a", "-1"]] assert chain("1/a/b") == ["Times", "1", ["Power", "a", "-1"], ["Power", "b", "-1"]] assert chain("-1/a*b") == ["Times", "-1", ["Power", "a", "-1"], "b"]
# Enclosures of various kinds, i.e. ( ) [ ] [[ ]] { } assert chain("(a + b) + c") == ["Plus", ["Plus", "a", "b"], "c"] assert chain(" a + (b + c) + d ") == ["Plus", "a", ["Plus", "b", "c"], "d"] assert chain("a * (b + c)") == ["Times", "a", ["Plus", "b", "c"]] assert chain("a b (c d)") == ["Times", "a", "b", ["Times", "c", "d"]] assert chain("{a, b, 2, c}") == ["List", "a", "b", "2", "c"] assert chain("{a, {b, c}}") == ["List", "a", ["List", "b", "c"]] assert chain("{{a}}") == ["List", ["List", "a"]] assert chain("a[b, c]") == ["a", "b", "c"] assert chain("a[[b, c]]") == ["Part", "a", "b", "c"] assert chain("a[b[c]]") == ["a", ["b", "c"]] assert chain("a[[b, c[[d, {e,f}]]]]") == ["Part", "a", "b", ["Part", "c", "d", ["List", "e", "f"]]] assert chain("a[b[[c,d]]]") == ["a", ["Part", "b", "c", "d"]] assert chain("a[[b[c]]]") == ["Part", "a", ["b", "c"]] assert chain("a[[b[[c]]]]") == ["Part", "a", ["Part", "b", "c"]] assert chain("a[[b[c[[d]]]]]") == ["Part", "a", ["b", ["Part", "c", "d"]]] assert chain("a[b[[c[d]]]]") == ["a", ["Part", "b", ["c", "d"]]] assert chain("x[[a+1, b+2, c+3]]") == ["Part", "x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] assert chain("x[a+1, b+2, c+3]") == ["x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] assert chain("{a+1, b+2, c+3}") == ["List", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]]
# Flat operator: assert chain("a*b*c*d*e") == ["Times", "a", "b", "c", "d", "e"] assert chain("a +b + c+ d+e") == ["Plus", "a", "b", "c", "d", "e"]
# Right priority operator: assert chain("a^b") == ["Power", "a", "b"] assert chain("a^b^c") == ["Power", "a", ["Power", "b", "c"]] assert chain("a^b^c^d") == ["Power", "a", ["Power", "b", ["Power", "c", "d"]]]
# Left priority operator: assert chain("a/.b") == ["ReplaceAll", "a", "b"] assert chain("a/.b/.c/.d") == ["ReplaceAll", ["ReplaceAll", ["ReplaceAll", "a", "b"], "c"], "d"]
assert chain("a//b") == ["a", "b"] assert chain("a//b//c") == [["a", "b"], "c"] assert chain("a//b//c//d") == [[["a", "b"], "c"], "d"]
# Compound expressions assert chain("a;b") == ["CompoundExpression", "a", "b"] assert chain("a;") == ["CompoundExpression", "a", "Null"] assert chain("a;b;") == ["CompoundExpression", "a", "b", "Null"] assert chain("a[b;c]") == ["a", ["CompoundExpression", "b", "c"]] assert chain("a[b,c;d,e]") == ["a", "b", ["CompoundExpression", "c", "d"], "e"] assert chain("a[b,c;,d]") == ["a", "b", ["CompoundExpression", "c", "Null"], "d"]
# New lines assert chain("a\nb\n") == ["CompoundExpression", "a", "b"] assert chain("a\n\nb\n (c \nd) \n") == ["CompoundExpression", "a", "b", ["Times", "c", "d"]] assert chain("\na; b\nc") == ["CompoundExpression", "a", "b", "c"] assert chain("a + \nb\n") == ["Plus", "a", "b"] assert chain("a\nb; c; d\n e; (f \n g); h + \n i") == ["CompoundExpression", "a", "b", "c", "d", "e", ["Times", "f", "g"], ["Plus", "h", "i"]] assert chain("\n{\na\nb; c; d\n e (f \n g); h + \n i\n\n}\n") == ["List", ["CompoundExpression", ["Times", "a", "b"], "c", ["Times", "d", "e", ["Times", "f", "g"]], ["Plus", "h", "i"]]]
# Patterns assert chain("y_") == ["Pattern", "y", ["Blank"]] assert chain("y_.") == ["Optional", ["Pattern", "y", ["Blank"]]] assert chain("y__") == ["Pattern", "y", ["BlankSequence"]] assert chain("y___") == ["Pattern", "y", ["BlankNullSequence"]] assert chain("a[b_.,c_]") == ["a", ["Optional", ["Pattern", "b", ["Blank"]]], ["Pattern", "c", ["Blank"]]] assert chain("b_. c") == ["Times", ["Optional", ["Pattern", "b", ["Blank"]]], "c"]
# Slots for lambda functions assert chain("#") == ["Slot", "1"] assert chain("#3") == ["Slot", "3"] assert chain("#n") == ["Slot", "n"] assert chain("##") == ["SlotSequence", "1"] assert chain("##a") == ["SlotSequence", "a"]
# Lambda functions assert chain("x&") == ["Function", "x"] assert chain("#&") == ["Function", ["Slot", "1"]] assert chain("#+3&") == ["Function", ["Plus", ["Slot", "1"], "3"]] assert chain("#1 + #2&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]] assert chain("# + #&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "1"]]] assert chain("#&[x]") == [["Function", ["Slot", "1"]], "x"] assert chain("#1 + #2 & [x, y]") == [["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]], "x", "y"] assert chain("#1^2#2^3&") == ["Function", ["Times", ["Power", ["Slot", "1"], "2"], ["Power", ["Slot", "2"], "3"]]]
# Strings inside Mathematica expressions: assert chain('"abc"') == ["_Str", "abc"] assert chain('"a\\"b"') == ["_Str", 'a"b'] # This expression does not make sense mathematically, it's just testing the parser: assert chain('x + "abc" ^ 3') == ["Plus", "x", ["Power", ["_Str", "abc"], "3"]] assert chain('"a (* b *) c"') == ["_Str", "a (* b *) c"] assert chain('"a" (* b *) ') == ["_Str", "a"] assert chain('"a [ b] "') == ["_Str", "a [ b] "] raises(SyntaxError, lambda: chain('"')) raises(SyntaxError, lambda: chain('"\\"')) raises(SyntaxError, lambda: chain('"abc')) raises(SyntaxError, lambda: chain('"abc\\"def'))
# Invalid expressions: raises(SyntaxError, lambda: chain("(,")) raises(SyntaxError, lambda: chain("()")) raises(SyntaxError, lambda: chain("a (* b"))
def test_parser_mathematica_exp_alt(): parser = MathematicaParser()
convert_chain2 = lambda expr: parser._from_fullformlist_to_fullformsympy(parser._from_fullform_to_fullformlist(expr)) convert_chain3 = lambda expr: parser._from_fullformsympy_to_sympy(convert_chain2(expr))
Sin, Times, Plus, Power = symbols("Sin Times Plus Power", cls=Function)
full_form1 = "Sin[Times[x, y]]" full_form2 = "Plus[Times[x, y], z]" full_form3 = "Sin[Times[x, Plus[y, z], Power[w, n]]]]" full_form4 = "Rational[Rational[x, y], z]"
assert parser._from_fullform_to_fullformlist(full_form1) == ["Sin", ["Times", "x", "y"]] assert parser._from_fullform_to_fullformlist(full_form2) == ["Plus", ["Times", "x", "y"], "z"] assert parser._from_fullform_to_fullformlist(full_form3) == ["Sin", ["Times", "x", ["Plus", "y", "z"], ["Power", "w", "n"]]] assert parser._from_fullform_to_fullformlist(full_form4) == ["Rational", ["Rational", "x", "y"], "z"]
assert convert_chain2(full_form1) == Sin(Times(x, y)) assert convert_chain2(full_form2) == Plus(Times(x, y), z) assert convert_chain2(full_form3) == Sin(Times(x, Plus(y, z), Power(w, n)))
assert convert_chain3(full_form1) == sin(x*y) assert convert_chain3(full_form2) == x*y + z assert convert_chain3(full_form3) == sin(x*(y + z)*w**n)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950from sympy.parsing.maxima import parse_maximafrom sympy.core.numbers import (E, Rational, oo)from sympy.core.symbol import Symbolfrom sympy.functions.combinatorial.factorials import factorialfrom sympy.functions.elementary.complexes import Absfrom sympy.functions.elementary.exponential import logfrom sympy.functions.elementary.trigonometric import (cos, sin)from sympy.abc import x
n = Symbol('n', integer=True)
def test_parser(): assert Abs(parse_maxima('float(1/3)') - 0.333333333) < 10**(-5) assert parse_maxima('13^26') == 91733330193268616658399616009 assert parse_maxima('sin(%pi/2) + cos(%pi/3)') == Rational(3, 2) assert parse_maxima('log(%e)') == 1
def test_injection(): parse_maxima('c: x+1', globals=globals()) # c created by parse_maxima assert c == x + 1 # noqa:F821
parse_maxima('g: sqrt(81)', globals=globals()) # g created by parse_maxima assert g == 9 # noqa:F821
def test_maxima_functions(): assert parse_maxima('expand( (x+1)^2)') == x**2 + 2*x + 1 assert parse_maxima('factor( x**2 + 2*x + 1)') == (x + 1)**2 assert parse_maxima('2*cos(x)^2 + sin(x)^2') == 2*cos(x)**2 + sin(x)**2 assert parse_maxima('trigexpand(sin(2*x)+cos(2*x))') == \ -1 + 2*cos(x)**2 + 2*cos(x)*sin(x) assert parse_maxima('solve(x^2-4,x)') == [-2, 2] assert parse_maxima('limit((1+1/x)^x,x,inf)') == E assert parse_maxima('limit(sqrt(-x)/x,x,0,minus)') is -oo assert parse_maxima('diff(x^x, x)') == x**x*(1 + log(x)) assert parse_maxima('sum(k, k, 1, n)', name_dict={ "n": Symbol('n', integer=True), "k": Symbol('k', integer=True) }) == (n**2 + n)/2 assert parse_maxima('product(k, k, 1, n)', name_dict={ "n": Symbol('n', integer=True), "k": Symbol('k', integer=True) }) == factorial(n) assert parse_maxima('ratsimp((x^2-1)/(x+1))') == x - 1 assert Abs( parse_maxima( 'float(sec(%pi/3) + csc(%pi/3))') - 3.154700538379252) < 10**(-5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209from sympy.parsing.sym_expr import SymPyExpressionfrom sympy.testing.pytest import raisesfrom sympy.external import import_module
lfortran = import_module('lfortran')cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
if lfortran and cin: from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String, Declaration, FloatType) from sympy.core import Integer, Float from sympy.core.symbol import Symbol
expr1 = SymPyExpression() src = """\ integer :: a, b, c, d real :: p, q, r, s """
def test_c_parse(): src1 = """\ int a, b = 4; float c, d = 2.4; """ expr1.convert_to_expr(src1, 'c') ls = expr1.return_expr()
assert ls[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')) ) ) assert ls[1] == Declaration( Variable( Symbol('b'), type=IntBaseType(String('intc')), value=Integer(4) ) ) assert ls[2] == Declaration( Variable( Symbol('c'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ) assert ls[3] == Declaration( Variable( Symbol('d'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.3999999999999999', precision=53) ) )
def test_fortran_parse(): expr = SymPyExpression(src, 'f') ls = expr.return_expr()
assert ls[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('integer')), value=Integer(0) ) ) assert ls[1] == Declaration( Variable( Symbol('b'), type=IntBaseType(String('integer')), value=Integer(0) ) ) assert ls[2] == Declaration( Variable( Symbol('c'), type=IntBaseType(String('integer')), value=Integer(0) ) ) assert ls[3] == Declaration( Variable( Symbol('d'), type=IntBaseType(String('integer')), value=Integer(0) ) ) assert ls[4] == Declaration( Variable( Symbol('p'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53) ) ) assert ls[5] == Declaration( Variable( Symbol('q'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53) ) ) assert ls[6] == Declaration( Variable( Symbol('r'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53) ) ) assert ls[7] == Declaration( Variable( Symbol('s'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53) ) )
def test_convert_py(): src1 = ( src + """\ a = b + c s = p * q / r """ ) expr1.convert_to_expr(src1, 'f') exp_py = expr1.convert_to_python() assert exp_py == [ 'a = 0', 'b = 0', 'c = 0', 'd = 0', 'p = 0.0', 'q = 0.0', 'r = 0.0', 's = 0.0', 'a = b + c', 's = p*q/r' ]
def test_convert_fort(): src1 = ( src + """\ a = b + c s = p * q / r """ ) expr1.convert_to_expr(src1, 'f') exp_fort = expr1.convert_to_fortran() assert exp_fort == [ ' integer*4 a', ' integer*4 b', ' integer*4 c', ' integer*4 d', ' real*8 p', ' real*8 q', ' real*8 r', ' real*8 s', ' a = b + c', ' s = p*q/r' ]
def test_convert_c(): src1 = ( src + """\ a = b + c s = p * q / r """ ) expr1.convert_to_expr(src1, 'f') exp_c = expr1.convert_to_c() assert exp_c == [ 'int a = 0', 'int b = 0', 'int c = 0', 'int d = 0', 'double p = 0.0', 'double q = 0.0', 'double r = 0.0', 'double s = 0.0', 'a = b + c;', 's = p*q/r;' ]
def test_exceptions(): src = 'int a;' raises(ValueError, lambda: SymPyExpression(src)) raises(ValueError, lambda: SymPyExpression(mode = 'c')) raises(NotImplementedError, lambda: SymPyExpression(src, mode = 'd'))
elif not lfortran and not cin: def test_raise(): raises(ImportError, lambda: SymPyExpression('int a;', 'c')) raises(ImportError, lambda: SymPyExpression('integer :: a', 'f'))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371# -*- coding: utf-8 -*-
import builtinsimport types
from sympy.assumptions import Qfrom sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq, Lt, Le, Gt, Ge, Nefrom sympy.functions import exp, factorial, factorial2, sin, Min, Maxfrom sympy.logic import Andfrom sympy.series import Limitfrom sympy.testing.pytest import raises
from sympy.parsing.sympy_parser import ( parse_expr, standard_transformations, rationalize, TokenError, split_symbols, implicit_multiplication, convert_equals_signs, convert_xor, function_exponentiation, lambda_notation, auto_symbol, repeated_decimals, implicit_multiplication_application, auto_number, factorial_notation, implicit_application, _transformation, T )
def test_sympy_parser(): x = Symbol('x') inputs = { '2*x': 2 * x, '3.00': Float(3), '22/7': Rational(22, 7), '2+3j': 2 + 3*I, 'exp(x)': exp(x), 'x!': factorial(x), 'x!!': factorial2(x), '(x + 1)! - 1': factorial(x + 1) - 1, '3.[3]': Rational(10, 3), '.0[3]': Rational(1, 30), '3.2[3]': Rational(97, 30), '1.3[12]': Rational(433, 330), '1 + 3.[3]': Rational(13, 3), '1 + .0[3]': Rational(31, 30), '1 + 3.2[3]': Rational(127, 30), '.[0011]': Rational(1, 909), '0.1[00102] + 1': Rational(366697, 333330), '1.[0191]': Rational(10190, 9999), '10!': 3628800, '-(2)': -Integer(2), '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)], 'Symbol("x").free_symbols': x.free_symbols, "S('S(3).n(n=3)')": Float(3, 3), 'factorint(12, visual=True)': Mul( Pow(2, 2, evaluate=False), Pow(3, 1, evaluate=False), evaluate=False), 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'), 'Q.even(x)': Q.even(x),
} for text, result in inputs.items(): assert parse_expr(text) == result
raises(TypeError, lambda: parse_expr('x', standard_transformations)) raises(TypeError, lambda: parse_expr('x', transformations=lambda x,y: 1)) raises(TypeError, lambda: parse_expr('x', transformations=(lambda x,y: 1,))) raises(TypeError, lambda: parse_expr('x', transformations=((),))) raises(TypeError, lambda: parse_expr('x', {}, [], [])) raises(TypeError, lambda: parse_expr('x', [], [], {})) raises(TypeError, lambda: parse_expr('x', [], [], {}))
def test_rationalize(): inputs = { '0.123': Rational(123, 1000) } transformations = standard_transformations + (rationalize,) for text, result in inputs.items(): assert parse_expr(text, transformations=transformations) == result
def test_factorial_fail(): inputs = ['x!!!', 'x!!!!', '(!)']
for text in inputs: try: parse_expr(text) assert False except TokenError: assert True
def test_repeated_fail(): inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]', '0.1[[1]]', '0x1.1[1]']
# All are valid Python, so only raise TypeError for invalid indexing for text in inputs: raises(TypeError, lambda: parse_expr(text))
inputs = ['0.1[', '0.1[1', '0.1[]'] for text in inputs: raises((TokenError, SyntaxError), lambda: parse_expr(text))
def test_repeated_dot_only(): assert parse_expr('.[1]') == Rational(1, 9) assert parse_expr('1 + .[1]') == Rational(10, 9)
def test_local_dict(): local_dict = { 'my_function': lambda x: x + 2 } inputs = { 'my_function(2)': Integer(4) } for text, result in inputs.items(): assert parse_expr(text, local_dict=local_dict) == result
def test_local_dict_split_implmult(): t = standard_transformations + (split_symbols, implicit_multiplication,) w = Symbol('w', real=True) y = Symbol('y') assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w
def test_local_dict_symbol_to_fcn(): x = Symbol('x') d = {'foo': Function('bar')} assert parse_expr('foo(x)', local_dict=d) == d['foo'](x) d = {'foo': Symbol('baz')} raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d))
def test_global_dict(): global_dict = { 'Symbol': Symbol } inputs = { 'Q & S': And(Symbol('Q'), Symbol('S')) } for text, result in inputs.items(): assert parse_expr(text, global_dict=global_dict) == result
def test_no_globals():
# Replicate creating the default global_dict: default_globals = {} exec('from sympy import *', default_globals) builtins_dict = vars(builtins) for name, obj in builtins_dict.items(): if isinstance(obj, types.BuiltinFunctionType): default_globals[name] = obj default_globals['max'] = Max default_globals['min'] = Min
# Need to include Symbol or parse_expr will not work: default_globals.pop('Symbol') global_dict = {'Symbol':Symbol}
for name in default_globals: obj = parse_expr(name, global_dict=global_dict) assert obj == Symbol(name)
def test_issue_2515(): raises(TokenError, lambda: parse_expr('(()')) raises(TokenError, lambda: parse_expr('"""'))
def test_issue_7663(): x = Symbol('x') e = '2*(x+1)' assert parse_expr(e, evaluate=False) == parse_expr(e, evaluate=False) assert parse_expr(e, evaluate=False).equals(2*(x+1))
def test_recursive_evaluate_false_10560(): inputs = { '4*-3' : '4*-3', '-4*3' : '(-4)*3', "-2*x*y": '(-2)*x*y', "x*-4*x": "x*(-4)*x" } for text, result in inputs.items(): assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
def test_function_evaluate_false(): inputs = [ 'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)', 'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)', 'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)', 'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)', 'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)', 'exp(0)', 'log(0)', 'sqrt(0)', ] for case in inputs: expr = parse_expr(case, evaluate=False) assert case == str(expr) != str(expr.doit()) assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)' assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)'
def test_issue_10773(): inputs = { '-10/5': '(-10)/5', '-10/-5' : '(-10)/(-5)', } for text, result in inputs.items(): assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
def test_split_symbols(): transformations = standard_transformations + \ (split_symbols, implicit_multiplication,) x = Symbol('x') y = Symbol('y') xy = Symbol('xy')
assert parse_expr("xy") == xy assert parse_expr("xy", transformations=transformations) == x*y
def test_split_symbols_function(): transformations = standard_transformations + \ (split_symbols, implicit_multiplication,) x = Symbol('x') y = Symbol('y') a = Symbol('a') f = Function('f')
assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1) assert parse_expr("af(x+1)", transformations=transformations, local_dict={'f':f}) == a*f(x+1)
def test_functional_exponent(): t = standard_transformations + (convert_xor, function_exponentiation) x = Symbol('x') y = Symbol('y') a = Symbol('a') yfcn = Function('y') assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2 assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x)) assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x))
def test_match_parentheses_implicit_multiplication(): transformations = standard_transformations + \ (implicit_multiplication,) raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations))
def test_convert_equals_signs(): transformations = standard_transformations + \ (convert_equals_signs, ) x = Symbol('x') y = Symbol('y') assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x) assert parse_expr("y = x", transformations=transformations) == Eq(y, x) assert parse_expr("(2*y = x) = False", transformations=transformations) == Eq(Eq(2*y, x), False)
def test_parse_function_issue_3539(): x = Symbol('x') f = Function('f') assert parse_expr('f(x)') == f(x)
def test_issue_24288(): assert parse_expr("1 < 2", evaluate=False) == Lt(1, 2, evaluate=False) assert parse_expr("1 <= 2", evaluate=False) == Le(1, 2, evaluate=False) assert parse_expr("1 > 2", evaluate=False) == Gt(1, 2, evaluate=False) assert parse_expr("1 >= 2", evaluate=False) == Ge(1, 2, evaluate=False) assert parse_expr("1 != 2", evaluate=False) == Ne(1, 2, evaluate=False) assert parse_expr("1 == 2", evaluate=False) == Eq(1, 2, evaluate=False) assert parse_expr("1 < 2 < 3", evaluate=False) == And(Lt(1, 2, evaluate=False), Lt(2, 3, evaluate=False), evaluate=False) assert parse_expr("1 <= 2 <= 3", evaluate=False) == And(Le(1, 2, evaluate=False), Le(2, 3, evaluate=False), evaluate=False) assert parse_expr("1 < 2 <= 3 < 4", evaluate=False) == \ And(Lt(1, 2, evaluate=False), Le(2, 3, evaluate=False), Lt(3, 4, evaluate=False), evaluate=False) # Valid Python relational operators that SymPy does not decide how to handle them yet raises(ValueError, lambda: parse_expr("1 in 2", evaluate=False)) raises(ValueError, lambda: parse_expr("1 is 2", evaluate=False)) raises(ValueError, lambda: parse_expr("1 not in 2", evaluate=False)) raises(ValueError, lambda: parse_expr("1 is not 2", evaluate=False))
def test_split_symbols_numeric(): transformations = ( standard_transformations + (implicit_multiplication_application,))
n = Symbol('n') expr1 = parse_expr('2**n * 3**n') expr2 = parse_expr('2**n3**n', transformations=transformations) assert expr1 == expr2 == 2**n*3**n
expr1 = parse_expr('n12n34', transformations=transformations) assert expr1 == n*12*n*34
def test_unicode_names(): assert parse_expr('α') == Symbol('α')
def test_python3_features(): assert parse_expr("123_456") == 123456 assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495) assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333) assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99) assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990) assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000)
def test_issue_19501(): x = Symbol('x') eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=( standard_transformations + (implicit_multiplication_application,))) assert eq.free_symbols == {x}
def test_parsing_definitions(): from sympy.abc import x assert len(_transformation) == 12 # if this changes, extend below assert _transformation[0] == lambda_notation assert _transformation[1] == auto_symbol assert _transformation[2] == repeated_decimals assert _transformation[3] == auto_number assert _transformation[4] == factorial_notation assert _transformation[5] == implicit_multiplication_application assert _transformation[6] == convert_xor assert _transformation[7] == implicit_application assert _transformation[8] == implicit_multiplication assert _transformation[9] == convert_equals_signs assert _transformation[10] == function_exponentiation assert _transformation[11] == rationalize assert T[:5] == T[0,1,2,3,4] == standard_transformations t = _transformation assert T[-1, 0] == (t[len(t) - 1], t[0]) assert T[:5, 8] == standard_transformations + (t[8],) assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10 assert parse_expr('sin 3x', transformations='implicit') == sin(3*x)
def test_builtins(): cases = [ ('abs(x)', 'Abs(x)'), ('max(x, y)', 'Max(x, y)'), ('min(x, y)', 'Min(x, y)'), ('pow(x, y)', 'Pow(x, y)'), ] for built_in_func_call, sympy_func_call in cases: assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call) assert str(parse_expr('pow(38, -1, 97)')) == '23'
def test_issue_22822(): raises(ValueError, lambda: parse_expr('x', {'': 1})) data = {'some_parameter': None} assert parse_expr('some_parameter is None', data) is True123456789101112"""A module that helps solving problems in physics."""
from . import unitsfrom .matrices import mgamma, msigma, minkowski_tensor, mdft
__all__ = [ 'units',
'mgamma', 'msigma', 'minkowski_tensor', 'mdft',]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Biomechanics extension for SymPy.
Includes biomechanics-related constructs which allows users to extend multibodymodels created using `sympy.physics.mechanics` into biomechanical ormusculoskeletal models involding musculotendons and activation dynamics.
"""
from .activation import ( ActivationBase, FirstOrderActivationDeGroote2016, ZerothOrderActivation,)from .curve import ( CharacteristicCurveCollection, CharacteristicCurveFunction, FiberForceLengthActiveDeGroote2016, FiberForceLengthPassiveDeGroote2016, FiberForceLengthPassiveInverseDeGroote2016, FiberForceVelocityDeGroote2016, FiberForceVelocityInverseDeGroote2016, TendonForceLengthDeGroote2016, TendonForceLengthInverseDeGroote2016,)from .musculotendon import ( MusculotendonBase, MusculotendonDeGroote2016, MusculotendonFormulation,)
__all__ = [ # Musculotendon characteristic curve functions 'CharacteristicCurveCollection', 'CharacteristicCurveFunction', 'FiberForceLengthActiveDeGroote2016', 'FiberForceLengthPassiveDeGroote2016', 'FiberForceLengthPassiveInverseDeGroote2016', 'FiberForceVelocityDeGroote2016', 'FiberForceVelocityInverseDeGroote2016', 'TendonForceLengthDeGroote2016', 'TendonForceLengthInverseDeGroote2016',
# Activation dynamics classes 'ActivationBase', 'FirstOrderActivationDeGroote2016', 'ZerothOrderActivation',
# Musculotendon classes 'MusculotendonBase', 'MusculotendonDeGroote2016', 'MusculotendonFormulation',]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Mixin classes for sharing functionality between unrelated classes.
This module is named with a leading underscore to signify to users that it's"private" and only intended for internal use by the biomechanics module.
"""
__all__ = ['_NamedMixin']
class _NamedMixin: """Mixin class for adding `name` properties.
Valid names, as will typically be used by subclasses as a suffix when naming automatically-instantiated symbol attributes, must be nonzero length strings.
Attributes ==========
name : str The name identifier associated with the instance. Must be a string of length at least 1.
"""
@property def name(self) -> str: """The name associated with the class instance.""" return self._name
@name.setter def name(self, name: str) -> None: if hasattr(self, '_name'): msg = ( f'Can\'t set attribute `name` to {repr(name)} as it is ' f'immutable.' ) raise AttributeError(msg) if not isinstance(name, str): msg = ( f'Name {repr(name)} passed to `name` was of type ' f'{type(name)}, must be {str}.' ) raise TypeError(msg) if name in {''}: msg = ( f'Name {repr(name)} is invalid, must be a nonzero length ' f'{type(str)}.' ) raise ValueError(msg) self._name = nameScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.data/data/share/man/man1/isympy.1Added+188
ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/METADATAAdded+319
ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/RECORDAdded
ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/WHEELAdded+5
ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/entry_points.txtAdded+2
ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/licenses/AUTHORSAdded+1379
ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/licenses/LICENSEAdded+153
ScaleDF_rebuttal/python_dedup_pkgs/sympy-1.14.0.dist-info/top_level.txtAdded+2
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.pyAdded+55
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.alAdded+25
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.pyAdded+39
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.alAdded+19
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.pyAdded+31
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.alAdded+20
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.pyAdded+36
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/c/__init__.pyAdded+1
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/c/c_parser.pyAdded+1059
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/fortran/__init__.pyAdded+1
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/fortran/fortran_parser.pyAdded+347
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/LICENSE.txtAdded+21
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/LaTeX.g4Added+312
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/__init__.pyAdded+204
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_antlr/__init__.pyAdded+9
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_antlr/latexlexer.pyAdded+512
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_antlr/latexparser.pyAdded
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_build_latex_antlr.pyAdded+91
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/_parse_latex_antlr.pyAdded+607
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/errors.pyAdded+2
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/__init__.pyAdded+2
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/grammar/greek_symbols.larkAdded+28
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/grammar/latex.larkAdded+403
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/latex_parser.pyAdded+145
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/latex/lark/transformer.pyAdded+730
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/__init__.pyAdded
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_ast_parser.pyAdded+25
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_autolev.pyAdded+178
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_c_parser.pyAdded
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_custom_latex.pyAdded+69
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_fortran_parser.pyAdded+406
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_implicit_multiplication_application.pyAdded+195
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_latex.pyAdded+358
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_latex_deps.pyAdded+16
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_latex_lark.pyAdded+872
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_mathematica.pyAdded+280
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_maxima.pyAdded+50
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_sym_expr.pyAdded+209
ScaleDF_rebuttal/python_dedup_pkgs/sympy/parsing/tests/test_sympy_parser.pyAdded+371
ScaleDF_rebuttal/python_dedup_pkgs/sympy/physics/__init__.pyAdded+12
ScaleDF_rebuttal/python_dedup_pkgs/sympy/physics/biomechanics/__init__.pyAdded+53
ScaleDF_rebuttal/python_dedup_pkgs/sympy/physics/biomechanics/_mixin.pyAdded+53