Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +3 -0
- vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/INSTALLER +1 -0
- vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/LICENSE +20 -0
- vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/METADATA +46 -0
- vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/RECORD +44 -0
- vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/REQUESTED +0 -0
- vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/WHEEL +6 -0
- vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/top_level.txt +2 -0
- vllm/lib/python3.10/site-packages/opencensus-0.11.4.dist-info/top_level.txt +1 -0
- vllm/lib/python3.10/site-packages/sympy/__init__.py +542 -0
- vllm/lib/python3.10/site-packages/sympy/abc.py +111 -0
- vllm/lib/python3.10/site-packages/sympy/conftest.py +96 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/__init__.py +20 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/convolutions.py +597 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/recurrences.py +166 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py +392 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py +59 -0
- vllm/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py +154 -0
- vllm/lib/python3.10/site-packages/sympy/galgebra.py +1 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/__init__.py +11 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/conflict.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/core.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/dispatcher.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_conflict.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_core.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_core.py +213 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/__init__.py +4 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/ast_parser.py +79 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_build_latex_antlr.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/errors.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__init__.py +9 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/latex_parser.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/transformer.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/greek_symbols.lark +28 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/latex.lark +327 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/mathematica.py +1086 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/maxima.py +71 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/sym_expr.py +279 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/sympy_parser.py +1257 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/tests/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_ast_parser.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -1652,3 +1652,6 @@ vllm/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/model
|
|
| 1652 |
videollama2/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1653 |
vllm/lib/python3.10/site-packages/safetensors/_safetensors_rust.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1654 |
vllm/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 1652 |
videollama2/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 1653 |
vllm/lib/python3.10/site-packages/safetensors/_safetensors_rust.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1654 |
vllm/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1655 |
+
vllm/lib/python3.10/site-packages/transformers/__pycache__/modeling_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1656 |
+
vllm/lib/python3.10/site-packages/transformers/__pycache__/training_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1657 |
+
vllm/lib/python3.10/site-packages/transformers/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2017-2021 Ingy döt Net
|
| 2 |
+
Copyright (c) 2006-2016 Kirill Simonov
|
| 3 |
+
|
| 4 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
| 5 |
+
this software and associated documentation files (the "Software"), to deal in
|
| 6 |
+
the Software without restriction, including without limitation the rights to
|
| 7 |
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
| 8 |
+
of the Software, and to permit persons to whom the Software is furnished to do
|
| 9 |
+
so, subject to the following conditions:
|
| 10 |
+
|
| 11 |
+
The above copyright notice and this permission notice shall be included in all
|
| 12 |
+
copies or substantial portions of the Software.
|
| 13 |
+
|
| 14 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 15 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 16 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 17 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 18 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 19 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 20 |
+
SOFTWARE.
|
vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/METADATA
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: PyYAML
|
| 3 |
+
Version: 6.0.2
|
| 4 |
+
Summary: YAML parser and emitter for Python
|
| 5 |
+
Home-page: https://pyyaml.org/
|
| 6 |
+
Download-URL: https://pypi.org/project/PyYAML/
|
| 7 |
+
Author: Kirill Simonov
|
| 8 |
+
Author-email: xi@resolvent.net
|
| 9 |
+
License: MIT
|
| 10 |
+
Project-URL: Bug Tracker, https://github.com/yaml/pyyaml/issues
|
| 11 |
+
Project-URL: CI, https://github.com/yaml/pyyaml/actions
|
| 12 |
+
Project-URL: Documentation, https://pyyaml.org/wiki/PyYAMLDocumentation
|
| 13 |
+
Project-URL: Mailing lists, http://lists.sourceforge.net/lists/listinfo/yaml-core
|
| 14 |
+
Project-URL: Source Code, https://github.com/yaml/pyyaml
|
| 15 |
+
Platform: Any
|
| 16 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 17 |
+
Classifier: Intended Audience :: Developers
|
| 18 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 19 |
+
Classifier: Operating System :: OS Independent
|
| 20 |
+
Classifier: Programming Language :: Cython
|
| 21 |
+
Classifier: Programming Language :: Python
|
| 22 |
+
Classifier: Programming Language :: Python :: 3
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 26 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 27 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 28 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 29 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 30 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 31 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 32 |
+
Classifier: Topic :: Text Processing :: Markup
|
| 33 |
+
Requires-Python: >=3.8
|
| 34 |
+
License-File: LICENSE
|
| 35 |
+
|
| 36 |
+
YAML is a data serialization format designed for human readability
|
| 37 |
+
and interaction with scripting languages. PyYAML is a YAML parser
|
| 38 |
+
and emitter for Python.
|
| 39 |
+
|
| 40 |
+
PyYAML features a complete YAML 1.1 parser, Unicode support, pickle
|
| 41 |
+
support, capable extension API, and sensible error messages. PyYAML
|
| 42 |
+
supports standard YAML tags and provides Python-specific tags that
|
| 43 |
+
allow to represent an arbitrary Python object.
|
| 44 |
+
|
| 45 |
+
PyYAML is applicable for a broad range of tasks from complex
|
| 46 |
+
configuration files to object serialization and persistence.
|
vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/RECORD
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PyYAML-6.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
PyYAML-6.0.2.dist-info/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101
|
| 3 |
+
PyYAML-6.0.2.dist-info/METADATA,sha256=9-odFB5seu4pGPcEv7E8iyxNF51_uKnaNGjLAhz2lto,2060
|
| 4 |
+
PyYAML-6.0.2.dist-info/RECORD,,
|
| 5 |
+
PyYAML-6.0.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
PyYAML-6.0.2.dist-info/WHEEL,sha256=baMMpUvyD0gnRdCe6fvqCg8rft4FNTdLqZQ01WfKJmc,152
|
| 7 |
+
PyYAML-6.0.2.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11
|
| 8 |
+
_yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402
|
| 9 |
+
_yaml/__pycache__/__init__.cpython-310.pyc,,
|
| 10 |
+
yaml/__init__.py,sha256=N35S01HMesFTe0aRRMWkPj0Pa8IEbHpE9FK7cr5Bdtw,12311
|
| 11 |
+
yaml/__pycache__/__init__.cpython-310.pyc,,
|
| 12 |
+
yaml/__pycache__/composer.cpython-310.pyc,,
|
| 13 |
+
yaml/__pycache__/constructor.cpython-310.pyc,,
|
| 14 |
+
yaml/__pycache__/cyaml.cpython-310.pyc,,
|
| 15 |
+
yaml/__pycache__/dumper.cpython-310.pyc,,
|
| 16 |
+
yaml/__pycache__/emitter.cpython-310.pyc,,
|
| 17 |
+
yaml/__pycache__/error.cpython-310.pyc,,
|
| 18 |
+
yaml/__pycache__/events.cpython-310.pyc,,
|
| 19 |
+
yaml/__pycache__/loader.cpython-310.pyc,,
|
| 20 |
+
yaml/__pycache__/nodes.cpython-310.pyc,,
|
| 21 |
+
yaml/__pycache__/parser.cpython-310.pyc,,
|
| 22 |
+
yaml/__pycache__/reader.cpython-310.pyc,,
|
| 23 |
+
yaml/__pycache__/representer.cpython-310.pyc,,
|
| 24 |
+
yaml/__pycache__/resolver.cpython-310.pyc,,
|
| 25 |
+
yaml/__pycache__/scanner.cpython-310.pyc,,
|
| 26 |
+
yaml/__pycache__/serializer.cpython-310.pyc,,
|
| 27 |
+
yaml/__pycache__/tokens.cpython-310.pyc,,
|
| 28 |
+
yaml/_yaml.cpython-310-x86_64-linux-gnu.so,sha256=20HV-cVpIFuOuVUTmQ1-PQIbyt0n8ctfXq7JCMIfbrU,2383664
|
| 29 |
+
yaml/composer.py,sha256=_Ko30Wr6eDWUeUpauUGT3Lcg9QPBnOPVlTnIMRGJ9FM,4883
|
| 30 |
+
yaml/constructor.py,sha256=kNgkfaeLUkwQYY_Q6Ff1Tz2XVw_pG1xVE9Ak7z-viLA,28639
|
| 31 |
+
yaml/cyaml.py,sha256=6ZrAG9fAYvdVe2FK_w0hmXoG7ZYsoYUwapG8CiC72H0,3851
|
| 32 |
+
yaml/dumper.py,sha256=PLctZlYwZLp7XmeUdwRuv4nYOZ2UBnDIUy8-lKfLF-o,2837
|
| 33 |
+
yaml/emitter.py,sha256=jghtaU7eFwg31bG0B7RZea_29Adi9CKmXq_QjgQpCkQ,43006
|
| 34 |
+
yaml/error.py,sha256=Ah9z-toHJUbE9j-M8YpxgSRM5CgLCcwVzJgLLRF2Fxo,2533
|
| 35 |
+
yaml/events.py,sha256=50_TksgQiE4up-lKo_V-nBy-tAIxkIPQxY5qDhKCeHw,2445
|
| 36 |
+
yaml/loader.py,sha256=UVa-zIqmkFSCIYq_PgSGm4NSJttHY2Rf_zQ4_b1fHN0,2061
|
| 37 |
+
yaml/nodes.py,sha256=gPKNj8pKCdh2d4gr3gIYINnPOaOxGhJAUiYhGRnPE84,1440
|
| 38 |
+
yaml/parser.py,sha256=ilWp5vvgoHFGzvOZDItFoGjD6D42nhlZrZyjAwa0oJo,25495
|
| 39 |
+
yaml/reader.py,sha256=0dmzirOiDG4Xo41RnuQS7K9rkY3xjHiVasfDMNTqCNw,6794
|
| 40 |
+
yaml/representer.py,sha256=IuWP-cAW9sHKEnS0gCqSa894k1Bg4cgTxaDwIcbRQ-Y,14190
|
| 41 |
+
yaml/resolver.py,sha256=9L-VYfm4mWHxUD1Vg4X7rjDRK_7VZd6b92wzq7Y2IKY,9004
|
| 42 |
+
yaml/scanner.py,sha256=YEM3iLZSaQwXcQRg2l2R4MdT0zGP2F9eHkKGKnHyWQY,51279
|
| 43 |
+
yaml/serializer.py,sha256=ChuFgmhU01hj4xgI8GaKv6vfM2Bujwa9i7d2FAHj7cA,4165
|
| 44 |
+
yaml/tokens.py,sha256=lTQIzSVw8Mg9wv459-TjiOQe6wVziqaRlqX2_89rp54,2573
|
vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/REQUESTED
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.44.0)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp310-cp310-manylinux_2_17_x86_64
|
| 5 |
+
Tag: cp310-cp310-manylinux2014_x86_64
|
| 6 |
+
|
vllm/lib/python3.10/site-packages/PyYAML-6.0.2.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_yaml
|
| 2 |
+
yaml
|
vllm/lib/python3.10/site-packages/opencensus-0.11.4.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
opencensus
|
vllm/lib/python3.10/site-packages/sympy/__init__.py
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SymPy is a Python library for symbolic mathematics. It aims to become a
|
| 3 |
+
full-featured computer algebra system (CAS) while keeping the code as simple
|
| 4 |
+
as possible in order to be comprehensible and easily extensible. SymPy is
|
| 5 |
+
written entirely in Python. It depends on mpmath, and other external libraries
|
| 6 |
+
may be optionally for things like plotting support.
|
| 7 |
+
|
| 8 |
+
See the webpage for more information and documentation:
|
| 9 |
+
|
| 10 |
+
https://sympy.org
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
import sys
|
| 16 |
+
if sys.version_info < (3, 8):
|
| 17 |
+
raise ImportError("Python version 3.8 or above is required for SymPy.")
|
| 18 |
+
del sys
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import mpmath
|
| 23 |
+
except ImportError:
|
| 24 |
+
raise ImportError("SymPy now depends on mpmath as an external library. "
|
| 25 |
+
"See https://docs.sympy.org/latest/install.html#mpmath for more information.")
|
| 26 |
+
|
| 27 |
+
del mpmath
|
| 28 |
+
|
| 29 |
+
from sympy.release import __version__
|
| 30 |
+
from sympy.core.cache import lazy_function
|
| 31 |
+
|
| 32 |
+
if 'dev' in __version__:
|
| 33 |
+
def enable_warnings():
|
| 34 |
+
import warnings
|
| 35 |
+
warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*')
|
| 36 |
+
del warnings
|
| 37 |
+
enable_warnings()
|
| 38 |
+
del enable_warnings
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def __sympy_debug():
|
| 42 |
+
# helper function so we don't import os globally
|
| 43 |
+
import os
|
| 44 |
+
debug_str = os.getenv('SYMPY_DEBUG', 'False')
|
| 45 |
+
if debug_str in ('True', 'False'):
|
| 46 |
+
return eval(debug_str)
|
| 47 |
+
else:
|
| 48 |
+
raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
|
| 49 |
+
debug_str)
|
| 50 |
+
SYMPY_DEBUG = __sympy_debug() # type: bool
|
| 51 |
+
|
| 52 |
+
from .core import (sympify, SympifyError, cacheit, Basic, Atom,
|
| 53 |
+
preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol,
|
| 54 |
+
Wild, Dummy, symbols, var, Number, Float, Rational, Integer,
|
| 55 |
+
NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo,
|
| 56 |
+
AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log,
|
| 57 |
+
trailing, Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality,
|
| 58 |
+
GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan,
|
| 59 |
+
vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass,
|
| 60 |
+
Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log,
|
| 61 |
+
expand_func, expand_trig, expand_complex, expand_multinomial, nfloat,
|
| 62 |
+
expand_power_base, expand_power_exp, arity, PrecisionExhausted, N,
|
| 63 |
+
evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate,
|
| 64 |
+
Catalan, EulerGamma, GoldenRatio, TribonacciConstant, bottom_up, use,
|
| 65 |
+
postorder_traversal, default_sort_key, ordered, num_digits)
|
| 66 |
+
|
| 67 |
+
from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor,
|
| 68 |
+
Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map,
|
| 69 |
+
true, false, satisfiable)
|
| 70 |
+
|
| 71 |
+
from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext,
|
| 72 |
+
assuming, Q, ask, register_handler, remove_handler, refine)
|
| 73 |
+
|
| 74 |
+
from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr,
|
| 75 |
+
degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo,
|
| 76 |
+
pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert,
|
| 77 |
+
subresultants, resultant, discriminant, cofactors, gcd_list, gcd,
|
| 78 |
+
lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, compose,
|
| 79 |
+
decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf,
|
| 80 |
+
factor_list, factor, intervals, refine_root, count_roots, all_roots,
|
| 81 |
+
real_roots, nroots, ground_roots, nth_power_roots_poly, cancel,
|
| 82 |
+
reduced, groebner, is_zero_dimensional, GroebnerBasis, poly,
|
| 83 |
+
symmetrize, horner, interpolate, rational_interpolate, viete, together,
|
| 84 |
+
BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed,
|
| 85 |
+
OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed,
|
| 86 |
+
IsomorphismFailed, ExtraneousFactors, EvaluationFailed,
|
| 87 |
+
RefinementFailed, CoercionFailed, NotInvertible, NotReversible,
|
| 88 |
+
NotAlgebraic, DomainError, PolynomialError, UnificationFailed,
|
| 89 |
+
GeneratorsError, GeneratorsNeeded, ComputationFailed,
|
| 90 |
+
UnivariatePolynomialError, MultivariatePolynomialError,
|
| 91 |
+
PolificationFailed, OptionError, FlagError, minpoly,
|
| 92 |
+
minimal_polynomial, primitive_element, field_isomorphism,
|
| 93 |
+
to_number_field, isolate, round_two, prime_decomp, prime_valuation,
|
| 94 |
+
galois_group, itermonomials, Monomial, lex, grlex,
|
| 95 |
+
grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf,
|
| 96 |
+
ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing,
|
| 97 |
+
RationalField, RealField, ComplexField, PythonFiniteField,
|
| 98 |
+
GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational,
|
| 99 |
+
GMPYRationalField, AlgebraicField, PolynomialRing, FractionField,
|
| 100 |
+
ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python,
|
| 101 |
+
QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW,
|
| 102 |
+
construct_domain, swinnerton_dyer_poly, cyclotomic_poly,
|
| 103 |
+
symmetric_poly, random_poly, interpolating_poly, jacobi_poly,
|
| 104 |
+
chebyshevt_poly, chebyshevu_poly, hermite_poly, hermite_prob_poly,
|
| 105 |
+
legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list,
|
| 106 |
+
Options, ring, xring, vring, sring, field, xfield, vfield, sfield)
|
| 107 |
+
|
| 108 |
+
from .series import (Order, O, limit, Limit, gruntz, series, approximants,
|
| 109 |
+
residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul,
|
| 110 |
+
fourier_series, fps, difference_delta, limit_seq)
|
| 111 |
+
|
| 112 |
+
from .functions import (factorial, factorial2, rf, ff, binomial,
|
| 113 |
+
RisingFactorial, FallingFactorial, subfactorial, carmichael,
|
| 114 |
+
fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler,
|
| 115 |
+
catalan, genocchi, andre, partition, divisor_sigma, legendre_symbol,
|
| 116 |
+
jacobi_symbol, kronecker_symbol, mobius, primenu, primeomega,
|
| 117 |
+
totient, reduced_totient, primepi, sqrt, root, Min, Max, Id,
|
| 118 |
+
real_root, Rem, cbrt, re, im, sign, Abs, conjugate, arg, polar_lift,
|
| 119 |
+
periodic_argument, unbranched_argument, principal_branch, transpose,
|
| 120 |
+
adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc,
|
| 121 |
+
asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log,
|
| 122 |
+
LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh,
|
| 123 |
+
acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold,
|
| 124 |
+
piecewise_exclusive, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv,
|
| 125 |
+
Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma,
|
| 126 |
+
lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma,
|
| 127 |
+
multigamma, dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk,
|
| 128 |
+
LeviCivita, KroneckerDelta, SingularityFunction, DiracDelta, Heaviside,
|
| 129 |
+
bspline_basis, bspline_basis_set, interpolating_spline, besselj,
|
| 130 |
+
bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1,
|
| 131 |
+
hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper,
|
| 132 |
+
meijerg, appellf1, legendre, assoc_legendre, hermite, hermite_prob,
|
| 133 |
+
chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root, laguerre,
|
| 134 |
+
assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c,
|
| 135 |
+
Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus,
|
| 136 |
+
mathieuc, mathieusprime, mathieucprime, riemann_xi, betainc, betainc_regularized)
|
| 137 |
+
|
| 138 |
+
from .ntheory import (nextprime, prevprime, prime, primerange,
|
| 139 |
+
randprime, Sieve, sieve, primorial, cycle_length, composite,
|
| 140 |
+
compositepi, isprime, divisors, proper_divisors, factorint,
|
| 141 |
+
multiplicity, perfect_power, pollard_pm1, pollard_rho, primefactors,
|
| 142 |
+
divisor_count, proper_divisor_count,
|
| 143 |
+
factorrat,
|
| 144 |
+
mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant,
|
| 145 |
+
is_deficient, is_amicable, is_carmichael, abundance, npartitions, is_primitive_root,
|
| 146 |
+
is_quad_residue, n_order, sqrt_mod,
|
| 147 |
+
quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue,
|
| 148 |
+
sqrt_mod_iter, discrete_log, quadratic_congruence,
|
| 149 |
+
binomial_coefficients, binomial_coefficients_list,
|
| 150 |
+
multinomial_coefficients, continued_fraction_periodic,
|
| 151 |
+
continued_fraction_iterator, continued_fraction_reduce,
|
| 152 |
+
continued_fraction_convergents, continued_fraction, egyptian_fraction)
|
| 153 |
+
|
| 154 |
+
from .concrete import product, Product, summation, Sum
|
| 155 |
+
|
| 156 |
+
from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform,
|
| 157 |
+
inverse_mobius_transform, convolution, covering_product,
|
| 158 |
+
intersecting_product)
|
| 159 |
+
|
| 160 |
+
from .simplify import (simplify, hypersimp, hypersimilar, logcombine,
|
| 161 |
+
separatevars, posify, besselsimp, kroneckersimp, signsimp,
|
| 162 |
+
nsimplify, FU, fu, sqrtdenest, cse, epath, EPath, hyperexpand,
|
| 163 |
+
collect, rcollect, radsimp, collect_const, fraction, numer, denom,
|
| 164 |
+
trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp,
|
| 165 |
+
ratsimp, ratsimpmodprime)
|
| 166 |
+
|
| 167 |
+
from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet,
|
| 168 |
+
Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet,
|
| 169 |
+
Range, ComplexRegion, Complexes, Reals, Contains, ConditionSet, Ordinal,
|
| 170 |
+
OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet,
|
| 171 |
+
Integers, Rationals)
|
| 172 |
+
|
| 173 |
+
from .solvers import (solve, solve_linear_system, solve_linear_system_LU,
|
| 174 |
+
solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick,
|
| 175 |
+
inv_quick, check_assumptions, failing_assumptions, diophantine,
|
| 176 |
+
rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol,
|
| 177 |
+
classify_ode, dsolve, homogeneous_order, solve_poly_system,
|
| 178 |
+
solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul,
|
| 179 |
+
pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities,
|
| 180 |
+
reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality,
|
| 181 |
+
solve_rational_inequalities, solve_univariate_inequality, decompogen,
|
| 182 |
+
solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution)
|
| 183 |
+
|
| 184 |
+
from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt,
|
| 185 |
+
casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy,
|
| 186 |
+
matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
|
| 187 |
+
rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix,
|
| 188 |
+
DeferredVector, MatrixBase, Matrix, MutableMatrix,
|
| 189 |
+
MutableSparseMatrix, banded, ImmutableDenseMatrix,
|
| 190 |
+
ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice,
|
| 191 |
+
BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse,
|
| 192 |
+
MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose,
|
| 193 |
+
ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols,
|
| 194 |
+
Adjoint, hadamard_product, HadamardProduct, HadamardPower,
|
| 195 |
+
Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix,
|
| 196 |
+
DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct,
|
| 197 |
+
PermutationMatrix, MatrixPermute, Permanent, per, rot_ccw_axis1,
|
| 198 |
+
rot_ccw_axis2, rot_ccw_axis3, rot_givens)
|
| 199 |
+
|
| 200 |
+
from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D,
|
| 201 |
+
Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle,
|
| 202 |
+
Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid,
|
| 203 |
+
convex_hull, idiff, intersection, closest_points, farthest_points,
|
| 204 |
+
GeometryError, Curve, Parabola)
|
| 205 |
+
|
| 206 |
+
from .utilities import (flatten, group, take, subsets, variations,
|
| 207 |
+
numbered_symbols, cartes, capture, dict_merge, prefixes, postfixes,
|
| 208 |
+
sift, topological_sort, unflatten, has_dups, has_variety, reshape,
|
| 209 |
+
rotations, filldedent, lambdify,
|
| 210 |
+
threaded, xthreaded, public, memoize_property, timed)
|
| 211 |
+
|
| 212 |
+
from .integrals import (integrate, Integral, line_integrate, mellin_transform,
|
| 213 |
+
inverse_mellin_transform, MellinTransform, InverseMellinTransform,
|
| 214 |
+
laplace_transform, laplace_correspondence, laplace_initial_conds,
|
| 215 |
+
inverse_laplace_transform, LaplaceTransform,
|
| 216 |
+
InverseLaplaceTransform, fourier_transform, inverse_fourier_transform,
|
| 217 |
+
FourierTransform, InverseFourierTransform, sine_transform,
|
| 218 |
+
inverse_sine_transform, SineTransform, InverseSineTransform,
|
| 219 |
+
cosine_transform, inverse_cosine_transform, CosineTransform,
|
| 220 |
+
InverseCosineTransform, hankel_transform, inverse_hankel_transform,
|
| 221 |
+
HankelTransform, InverseHankelTransform, singularityintegrate)
|
| 222 |
+
|
| 223 |
+
from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure,
|
| 224 |
+
get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray,
|
| 225 |
+
MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray,
|
| 226 |
+
tensorproduct, tensorcontraction, tensordiagonal, derive_by_array,
|
| 227 |
+
permutedims, Array, DenseNDimArray, SparseNDimArray)
|
| 228 |
+
|
| 229 |
+
from .parsing import parse_expr
|
| 230 |
+
|
| 231 |
+
from .calculus import (euler_equations, singularities, is_increasing,
|
| 232 |
+
is_strictly_increasing, is_decreasing, is_strictly_decreasing,
|
| 233 |
+
is_monotonic, finite_diff_weights, apply_finite_diff,
|
| 234 |
+
differentiate_finite, periodicity, not_empty_in, AccumBounds,
|
| 235 |
+
is_convex, stationary_points, minimum, maximum)
|
| 236 |
+
|
| 237 |
+
from .algebras import Quaternion
|
| 238 |
+
|
| 239 |
+
from .printing import (pager_print, pretty, pretty_print, pprint,
|
| 240 |
+
pprint_use_unicode, pprint_try_use_unicode, latex, print_latex,
|
| 241 |
+
multiline_latex, mathml, print_mathml, python, print_python, pycode,
|
| 242 |
+
ccode, print_ccode, smtlib_code, glsl_code, print_glsl, cxxcode, fcode,
|
| 243 |
+
print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code,
|
| 244 |
+
mathematica_code, octave_code, rust_code, print_gtk, preview, srepr,
|
| 245 |
+
print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint,
|
| 246 |
+
maple_code, print_maple_code)
|
| 247 |
+
|
| 248 |
+
test = lazy_function('sympy.testing.runtests_pytest', 'test')
|
| 249 |
+
doctest = lazy_function('sympy.testing.runtests', 'doctest')
|
| 250 |
+
|
| 251 |
+
# This module causes conflicts with other modules:
|
| 252 |
+
# from .stats import *
|
| 253 |
+
# Adds about .04-.05 seconds of import time
|
| 254 |
+
# from combinatorics import *
|
| 255 |
+
# This module is slow to import:
|
| 256 |
+
#from physics import units
|
| 257 |
+
from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric
|
| 258 |
+
from .interactive import init_session, init_printing, interactive_traversal
|
| 259 |
+
|
| 260 |
+
evalf._create_evalf_table()
|
| 261 |
+
|
| 262 |
+
__all__ = [
|
| 263 |
+
'__version__',
|
| 264 |
+
|
| 265 |
+
# sympy.core
|
| 266 |
+
'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom',
|
| 267 |
+
'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr',
|
| 268 |
+
'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float',
|
| 269 |
+
'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm',
|
| 270 |
+
'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp',
|
| 271 |
+
'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'trailing', 'Mul', 'prod',
|
| 272 |
+
'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality',
|
| 273 |
+
'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan',
|
| 274 |
+
'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative',
|
| 275 |
+
'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError',
|
| 276 |
+
'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig',
|
| 277 |
+
'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base',
|
| 278 |
+
'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple',
|
| 279 |
+
'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan',
|
| 280 |
+
'EulerGamma', 'GoldenRatio', 'TribonacciConstant', 'bottom_up', 'use',
|
| 281 |
+
'postorder_traversal', 'default_sort_key', 'ordered', 'num_digits',
|
| 282 |
+
|
| 283 |
+
# sympy.logic
|
| 284 |
+
'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor',
|
| 285 |
+
'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic',
|
| 286 |
+
'bool_map', 'true', 'false', 'satisfiable',
|
| 287 |
+
|
| 288 |
+
# sympy.assumptions
|
| 289 |
+
'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q',
|
| 290 |
+
'ask', 'register_handler', 'remove_handler', 'refine',
|
| 291 |
+
|
| 292 |
+
# sympy.polys
|
| 293 |
+
'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree',
|
| 294 |
+
'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo',
|
| 295 |
+
'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert',
|
| 296 |
+
'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list',
|
| 297 |
+
'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content',
|
| 298 |
+
'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff',
|
| 299 |
+
'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor',
|
| 300 |
+
'intervals', 'refine_root', 'count_roots', 'all_roots', 'real_roots',
|
| 301 |
+
'nroots', 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced',
|
| 302 |
+
'groebner', 'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize',
|
| 303 |
+
'horner', 'interpolate', 'rational_interpolate', 'viete', 'together',
|
| 304 |
+
'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed',
|
| 305 |
+
'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed',
|
| 306 |
+
'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed',
|
| 307 |
+
'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible',
|
| 308 |
+
'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed',
|
| 309 |
+
'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed',
|
| 310 |
+
'UnivariatePolynomialError', 'MultivariatePolynomialError',
|
| 311 |
+
'PolificationFailed', 'OptionError', 'FlagError', 'minpoly',
|
| 312 |
+
'minimal_polynomial', 'primitive_element', 'field_isomorphism',
|
| 313 |
+
'to_number_field', 'isolate', 'round_two', 'prime_decomp',
|
| 314 |
+
'prime_valuation', 'galois_group', 'itermonomials', 'Monomial', 'lex', 'grlex',
|
| 315 |
+
'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf',
|
| 316 |
+
'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField',
|
| 317 |
+
'IntegerRing', 'RationalField', 'RealField', 'ComplexField',
|
| 318 |
+
'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing',
|
| 319 |
+
'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField',
|
| 320 |
+
'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain',
|
| 321 |
+
'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy',
|
| 322 |
+
'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW',
|
| 323 |
+
'construct_domain', 'swinnerton_dyer_poly', 'cyclotomic_poly',
|
| 324 |
+
'symmetric_poly', 'random_poly', 'interpolating_poly', 'jacobi_poly',
|
| 325 |
+
'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', 'hermite_prob_poly',
|
| 326 |
+
'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list',
|
| 327 |
+
'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield',
|
| 328 |
+
'sfield',
|
| 329 |
+
|
| 330 |
+
# sympy.series
|
| 331 |
+
'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants',
|
| 332 |
+
'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd',
|
| 333 |
+
'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq',
|
| 334 |
+
|
| 335 |
+
# sympy.functions
|
| 336 |
+
'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
|
| 337 |
+
'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas',
|
| 338 |
+
'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan',
|
| 339 |
+
'genocchi', 'andre', 'partition', 'divisor_sigma', 'legendre_symbol', 'jacobi_symbol',
|
| 340 |
+
'kronecker_symbol', 'mobius', 'primenu', 'primeomega', 'totient', 'primepi',
|
| 341 |
+
'reduced_totient', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root',
|
| 342 |
+
'Rem', 'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
|
| 343 |
+
'periodic_argument', 'unbranched_argument', 'principal_branch',
|
| 344 |
+
'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan',
|
| 345 |
+
'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc',
|
| 346 |
+
'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh',
|
| 347 |
+
'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
|
| 348 |
+
'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise',
|
| 349 |
+
'piecewise_fold', 'piecewise_exclusive', 'erf', 'erfc', 'erfi', 'erf2',
|
| 350 |
+
'erfinv', 'erfcinv', 'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si',
|
| 351 |
+
'Ci', 'Shi', 'Chi', 'fresnels', 'fresnelc', 'gamma', 'lowergamma',
|
| 352 |
+
'uppergamma', 'polygamma', 'loggamma', 'digamma', 'trigamma', 'multigamma',
|
| 353 |
+
'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita',
|
| 354 |
+
'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside',
|
| 355 |
+
'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj',
|
| 356 |
+
'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn',
|
| 357 |
+
'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
|
| 358 |
+
'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre',
|
| 359 |
+
'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt', 'chebyshevu',
|
| 360 |
+
'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre',
|
| 361 |
+
'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm',
|
| 362 |
+
'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta',
|
| 363 |
+
'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime', 'riemann_xi','betainc',
|
| 364 |
+
'betainc_regularized',
|
| 365 |
+
|
| 366 |
+
# sympy.ntheory
|
| 367 |
+
'nextprime', 'prevprime', 'prime', 'primerange', 'randprime',
|
| 368 |
+
'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi',
|
| 369 |
+
'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity',
|
| 370 |
+
'perfect_power', 'pollard_pm1', 'pollard_rho', 'primefactors',
|
| 371 |
+
'divisor_count', 'proper_divisor_count',
|
| 372 |
+
'factorrat',
|
| 373 |
+
'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime',
|
| 374 |
+
'is_abundant', 'is_deficient', 'is_amicable', 'is_carmichael', 'abundance',
|
| 375 |
+
'npartitions',
|
| 376 |
+
'is_primitive_root', 'is_quad_residue',
|
| 377 |
+
'n_order', 'sqrt_mod', 'quadratic_residues',
|
| 378 |
+
'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter',
|
| 379 |
+
'discrete_log', 'quadratic_congruence', 'binomial_coefficients',
|
| 380 |
+
'binomial_coefficients_list', 'multinomial_coefficients',
|
| 381 |
+
'continued_fraction_periodic', 'continued_fraction_iterator',
|
| 382 |
+
'continued_fraction_reduce', 'continued_fraction_convergents',
|
| 383 |
+
'continued_fraction', 'egyptian_fraction',
|
| 384 |
+
|
| 385 |
+
# sympy.concrete
|
| 386 |
+
'product', 'Product', 'summation', 'Sum',
|
| 387 |
+
|
| 388 |
+
# sympy.discrete
|
| 389 |
+
'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
|
| 390 |
+
'inverse_mobius_transform', 'convolution', 'covering_product',
|
| 391 |
+
'intersecting_product',
|
| 392 |
+
|
| 393 |
+
# sympy.simplify
|
| 394 |
+
'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars',
|
| 395 |
+
'posify', 'besselsimp', 'kroneckersimp', 'signsimp',
|
| 396 |
+
'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'epath', 'EPath',
|
| 397 |
+
'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const',
|
| 398 |
+
'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp',
|
| 399 |
+
'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime',
|
| 400 |
+
|
| 401 |
+
# sympy.sets
|
| 402 |
+
'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet',
|
| 403 |
+
'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference',
|
| 404 |
+
'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet',
|
| 405 |
+
'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Naturals',
|
| 406 |
+
'Naturals0', 'UniversalSet', 'Integers', 'Rationals', 'Complexes',
|
| 407 |
+
|
| 408 |
+
# sympy.solvers
|
| 409 |
+
'solve', 'solve_linear_system', 'solve_linear_system_LU',
|
| 410 |
+
'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol',
|
| 411 |
+
'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions',
|
| 412 |
+
'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper',
|
| 413 |
+
'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order',
|
| 414 |
+
'solve_poly_system', 'solve_triangulated', 'pde_separate',
|
| 415 |
+
'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde',
|
| 416 |
+
'checkpdesol', 'ode_order', 'reduce_inequalities',
|
| 417 |
+
'reduce_abs_inequality', 'reduce_abs_inequalities',
|
| 418 |
+
'solve_poly_inequality', 'solve_rational_inequalities',
|
| 419 |
+
'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve',
|
| 420 |
+
'linear_eq_to_matrix', 'nonlinsolve', 'substitution',
|
| 421 |
+
|
| 422 |
+
# sympy.matrices
|
| 423 |
+
'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag',
|
| 424 |
+
'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy',
|
| 425 |
+
'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1',
|
| 426 |
+
'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros',
|
| 427 |
+
'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix',
|
| 428 |
+
'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix',
|
| 429 |
+
'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice',
|
| 430 |
+
'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse',
|
| 431 |
+
'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace',
|
| 432 |
+
'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse',
|
| 433 |
+
'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct',
|
| 434 |
+
'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix',
|
| 435 |
+
'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct',
|
| 436 |
+
'kronecker_product', 'KroneckerProduct', 'PermutationMatrix',
|
| 437 |
+
'MatrixPermute', 'Permanent', 'per', 'rot_ccw_axis1', 'rot_ccw_axis2',
|
| 438 |
+
'rot_ccw_axis3', 'rot_givens',
|
| 439 |
+
|
| 440 |
+
# sympy.geometry
|
| 441 |
+
'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D',
|
| 442 |
+
'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse',
|
| 443 |
+
'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg',
|
| 444 |
+
'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection',
|
| 445 |
+
'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola',
|
| 446 |
+
|
| 447 |
+
# sympy.utilities
|
| 448 |
+
'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols',
|
| 449 |
+
'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift',
|
| 450 |
+
'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape',
|
| 451 |
+
'rotations', 'filldedent', 'lambdify', 'threaded', 'xthreaded',
|
| 452 |
+
'public', 'memoize_property', 'timed',
|
| 453 |
+
|
| 454 |
+
# sympy.integrals
|
| 455 |
+
'integrate', 'Integral', 'line_integrate', 'mellin_transform',
|
| 456 |
+
'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform',
|
| 457 |
+
'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform',
|
| 458 |
+
'laplace_correspondence', 'laplace_initial_conds',
|
| 459 |
+
'InverseLaplaceTransform', 'fourier_transform',
|
| 460 |
+
'inverse_fourier_transform', 'FourierTransform',
|
| 461 |
+
'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform',
|
| 462 |
+
'SineTransform', 'InverseSineTransform', 'cosine_transform',
|
| 463 |
+
'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform',
|
| 464 |
+
'hankel_transform', 'inverse_hankel_transform', 'HankelTransform',
|
| 465 |
+
'InverseHankelTransform', 'singularityintegrate',
|
| 466 |
+
|
| 467 |
+
# sympy.tensor
|
| 468 |
+
'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure',
|
| 469 |
+
'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
|
| 470 |
+
'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
|
| 471 |
+
'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array',
|
| 472 |
+
'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray',
|
| 473 |
+
|
| 474 |
+
# sympy.parsing
|
| 475 |
+
'parse_expr',
|
| 476 |
+
|
| 477 |
+
# sympy.calculus
|
| 478 |
+
'euler_equations', 'singularities', 'is_increasing',
|
| 479 |
+
'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing',
|
| 480 |
+
'is_monotonic', 'finite_diff_weights', 'apply_finite_diff',
|
| 481 |
+
'differentiate_finite', 'periodicity', 'not_empty_in',
|
| 482 |
+
'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum',
|
| 483 |
+
|
| 484 |
+
# sympy.algebras
|
| 485 |
+
'Quaternion',
|
| 486 |
+
|
| 487 |
+
# sympy.printing
|
| 488 |
+
'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
|
| 489 |
+
'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex',
|
| 490 |
+
'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode',
|
| 491 |
+
'print_ccode', 'smtlib_code', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode',
|
| 492 |
+
'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode',
|
| 493 |
+
'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk',
|
| 494 |
+
'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr',
|
| 495 |
+
'TableForm', 'dotprint', 'maple_code', 'print_maple_code',
|
| 496 |
+
|
| 497 |
+
# sympy.plotting
|
| 498 |
+
'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric',
|
| 499 |
+
|
| 500 |
+
# sympy.interactive
|
| 501 |
+
'init_session', 'init_printing', 'interactive_traversal',
|
| 502 |
+
|
| 503 |
+
# sympy.testing
|
| 504 |
+
'test', 'doctest',
|
| 505 |
+
]
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
#===========================================================================#
|
| 509 |
+
# #
|
| 510 |
+
# XXX: The names below were importable before SymPy 1.6 using #
|
| 511 |
+
# #
|
| 512 |
+
# from sympy import * #
|
| 513 |
+
# #
|
| 514 |
+
# This happened implicitly because there was no __all__ defined in this #
|
| 515 |
+
# __init__.py file. Not every package is imported. The list matches what #
|
| 516 |
+
# would have been imported before. It is possible that these packages will #
|
| 517 |
+
# not be imported by a star-import from sympy in future. #
|
| 518 |
+
# #
|
| 519 |
+
#===========================================================================#
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
__all__.extend((
|
| 523 |
+
'algebras',
|
| 524 |
+
'assumptions',
|
| 525 |
+
'calculus',
|
| 526 |
+
'concrete',
|
| 527 |
+
'discrete',
|
| 528 |
+
'external',
|
| 529 |
+
'functions',
|
| 530 |
+
'geometry',
|
| 531 |
+
'interactive',
|
| 532 |
+
'multipledispatch',
|
| 533 |
+
'ntheory',
|
| 534 |
+
'parsing',
|
| 535 |
+
'plotting',
|
| 536 |
+
'polys',
|
| 537 |
+
'printing',
|
| 538 |
+
'release',
|
| 539 |
+
'strategies',
|
| 540 |
+
'tensor',
|
| 541 |
+
'utilities',
|
| 542 |
+
))
|
vllm/lib/python3.10/site-packages/sympy/abc.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module exports all latin and greek letters as Symbols, so you can
|
| 3 |
+
conveniently do
|
| 4 |
+
|
| 5 |
+
>>> from sympy.abc import x, y
|
| 6 |
+
|
| 7 |
+
instead of the slightly more clunky-looking
|
| 8 |
+
|
| 9 |
+
>>> from sympy import symbols
|
| 10 |
+
>>> x, y = symbols('x y')
|
| 11 |
+
|
| 12 |
+
Caveats
|
| 13 |
+
=======
|
| 14 |
+
|
| 15 |
+
1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``,
|
| 16 |
+
``E``, and ``Q`` are colliding with names defined in SymPy. If you import them
|
| 17 |
+
from both ``sympy.abc`` and ``sympy``, the second import will "win".
|
| 18 |
+
This is an issue only for * imports, which should only be used for short-lived
|
| 19 |
+
code such as interactive sessions and throwaway scripts that do not survive
|
| 20 |
+
until the next SymPy upgrade, where ``sympy`` may contain a different set of
|
| 21 |
+
names.
|
| 22 |
+
|
| 23 |
+
2. This module does not define symbol names on demand, i.e.
|
| 24 |
+
``from sympy.abc import foo`` will be reported as an error because
|
| 25 |
+
``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``,
|
| 26 |
+
you still need to use ``Symbol('foo')`` or ``symbols('foo')``.
|
| 27 |
+
You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though
|
| 28 |
+
sticking with one and only one way to get the symbols does tend to make the code
|
| 29 |
+
more readable.
|
| 30 |
+
|
| 31 |
+
The module also defines some special names to help detect which names clash
|
| 32 |
+
with the default SymPy namespace.
|
| 33 |
+
|
| 34 |
+
``_clash1`` defines all the single letter variables that clash with
|
| 35 |
+
SymPy objects; ``_clash2`` defines the multi-letter clashing symbols;
|
| 36 |
+
and ``_clash`` is the union of both. These can be passed for ``locals``
|
| 37 |
+
during sympification if one desires Symbols rather than the non-Symbol
|
| 38 |
+
objects for those names.
|
| 39 |
+
|
| 40 |
+
Examples
|
| 41 |
+
========
|
| 42 |
+
|
| 43 |
+
>>> from sympy import S
|
| 44 |
+
>>> from sympy.abc import _clash1, _clash2, _clash
|
| 45 |
+
>>> S("Q & C", locals=_clash1)
|
| 46 |
+
C & Q
|
| 47 |
+
>>> S('pi(x)', locals=_clash2)
|
| 48 |
+
pi(x)
|
| 49 |
+
>>> S('pi(C, Q)', locals=_clash)
|
| 50 |
+
pi(C, Q)
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
from typing import Any, Dict as tDict
|
| 55 |
+
|
| 56 |
+
import string
|
| 57 |
+
|
| 58 |
+
from .core import Symbol, symbols
|
| 59 |
+
from .core.alphabets import greeks
|
| 60 |
+
from sympy.parsing.sympy_parser import null
|
| 61 |
+
|
| 62 |
+
##### Symbol definitions #####
|
| 63 |
+
|
| 64 |
+
# Implementation note: The easiest way to avoid typos in the symbols()
|
| 65 |
+
# parameter is to copy it from the left-hand side of the assignment.
|
| 66 |
+
|
| 67 |
+
a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j')
|
| 68 |
+
k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t')
|
| 69 |
+
u, v, w, x, y, z = symbols('u, v, w, x, y, z')
|
| 70 |
+
|
| 71 |
+
A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J')
|
| 72 |
+
K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T')
|
| 73 |
+
U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z')
|
| 74 |
+
|
| 75 |
+
alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta')
|
| 76 |
+
epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta')
|
| 77 |
+
iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu')
|
| 78 |
+
nu, xi, omicron, pi = symbols('nu, xi, omicron, pi')
|
| 79 |
+
rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon')
|
| 80 |
+
phi, chi, psi, omega = symbols('phi, chi, psi, omega')
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
##### Clashing-symbols diagnostics #####
|
| 84 |
+
|
| 85 |
+
# We want to know which names in SymPy collide with those in here.
|
| 86 |
+
# This is mostly for diagnosing SymPy's namespace during SymPy development.
|
| 87 |
+
|
| 88 |
+
_latin = list(string.ascii_letters)
|
| 89 |
+
# QOSINE should not be imported as they clash; gamma, pi and zeta clash, too
|
| 90 |
+
_greek = list(greeks) # make a copy, so we can mutate it
|
| 91 |
+
# Note: We import lamda since lambda is a reserved keyword in Python
|
| 92 |
+
_greek.remove("lambda")
|
| 93 |
+
_greek.append("lamda")
|
| 94 |
+
|
| 95 |
+
ns: tDict[str, Any] = {}
|
| 96 |
+
exec('from sympy import *', ns)
|
| 97 |
+
_clash1: tDict[str, Any] = {}
|
| 98 |
+
_clash2: tDict[str, Any] = {}
|
| 99 |
+
while ns:
|
| 100 |
+
_k, _ = ns.popitem()
|
| 101 |
+
if _k in _greek:
|
| 102 |
+
_clash2[_k] = null
|
| 103 |
+
_greek.remove(_k)
|
| 104 |
+
elif _k in _latin:
|
| 105 |
+
_clash1[_k] = null
|
| 106 |
+
_latin.remove(_k)
|
| 107 |
+
_clash = {}
|
| 108 |
+
_clash.update(_clash1)
|
| 109 |
+
_clash.update(_clash2)
|
| 110 |
+
|
| 111 |
+
del _latin, _greek, Symbol, _k, null
|
vllm/lib/python3.10/site-packages/sympy/conftest.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
sys._running_pytest = True # type: ignore
|
| 4 |
+
from sympy.external.importtools import version_tuple
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
from sympy.core.cache import clear_cache, USE_CACHE
|
| 8 |
+
from sympy.external.gmpy import GROUND_TYPES
|
| 9 |
+
from sympy.utilities.misc import ARCH
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
import hypothesis
|
| 14 |
+
|
| 15 |
+
hypothesis.settings.register_profile("sympy_hypothesis_profile", deadline=None)
|
| 16 |
+
hypothesis.settings.load_profile("sympy_hypothesis_profile")
|
| 17 |
+
except ImportError:
|
| 18 |
+
raise ImportError(
|
| 19 |
+
"hypothesis is a required dependency to run the SymPy test suite. "
|
| 20 |
+
"Install it with 'pip install hypothesis' or 'conda install -c conda-forge hypothesis'"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
sp = re.compile(r"([0-9]+)/([1-9][0-9]*)")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def process_split(config, items):
|
| 28 |
+
split = config.getoption("--split")
|
| 29 |
+
if not split:
|
| 30 |
+
return
|
| 31 |
+
m = sp.match(split)
|
| 32 |
+
if not m:
|
| 33 |
+
raise ValueError(
|
| 34 |
+
"split must be a string of the form a/b " "where a and b are ints."
|
| 35 |
+
)
|
| 36 |
+
i, t = map(int, m.groups())
|
| 37 |
+
start, end = (i - 1) * len(items) // t, i * len(items) // t
|
| 38 |
+
|
| 39 |
+
if i < t:
|
| 40 |
+
# remove elements from end of list first
|
| 41 |
+
del items[end:]
|
| 42 |
+
del items[:start]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def pytest_report_header(config):
|
| 46 |
+
s = "architecture: %s\n" % ARCH
|
| 47 |
+
s += "cache: %s\n" % USE_CACHE
|
| 48 |
+
version = ""
|
| 49 |
+
if GROUND_TYPES == "gmpy":
|
| 50 |
+
import gmpy2
|
| 51 |
+
|
| 52 |
+
version = gmpy2.version()
|
| 53 |
+
elif GROUND_TYPES == "flint":
|
| 54 |
+
try:
|
| 55 |
+
from flint import __version__
|
| 56 |
+
except ImportError:
|
| 57 |
+
version = "unknown"
|
| 58 |
+
else:
|
| 59 |
+
version = f'(python-flint=={__version__})'
|
| 60 |
+
s += "ground types: %s %s\n" % (GROUND_TYPES, version)
|
| 61 |
+
return s
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def pytest_terminal_summary(terminalreporter):
|
| 65 |
+
if terminalreporter.stats.get("error", None) or terminalreporter.stats.get(
|
| 66 |
+
"failed", None
|
| 67 |
+
):
|
| 68 |
+
terminalreporter.write_sep(" ", "DO *NOT* COMMIT!", red=True, bold=True)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def pytest_addoption(parser):
|
| 72 |
+
parser.addoption("--split", action="store", default="", help="split tests")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def pytest_collection_modifyitems(config, items):
|
| 76 |
+
"""pytest hook."""
|
| 77 |
+
# handle splits
|
| 78 |
+
process_split(config, items)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@pytest.fixture(autouse=True, scope="module")
|
| 82 |
+
def file_clear_cache():
|
| 83 |
+
clear_cache()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@pytest.fixture(autouse=True, scope="module")
|
| 87 |
+
def check_disabled(request):
|
| 88 |
+
if getattr(request.module, "disabled", False):
|
| 89 |
+
pytest.skip("test requirements not met.")
|
| 90 |
+
elif getattr(request.module, "ipython", False):
|
| 91 |
+
# need to check version and options for ipython tests
|
| 92 |
+
if (
|
| 93 |
+
version_tuple(pytest.__version__) < version_tuple("2.6.3")
|
| 94 |
+
and pytest.config.getvalue("-s") != "no"
|
| 95 |
+
):
|
| 96 |
+
pytest.skip("run py.test with -s or upgrade to newer version.")
|
vllm/lib/python3.10/site-packages/sympy/discrete/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module contains functions which operate on discrete sequences.
|
| 2 |
+
|
| 3 |
+
Transforms - ``fft``, ``ifft``, ``ntt``, ``intt``, ``fwht``, ``ifwht``,
|
| 4 |
+
``mobius_transform``, ``inverse_mobius_transform``
|
| 5 |
+
|
| 6 |
+
Convolutions - ``convolution``, ``convolution_fft``, ``convolution_ntt``,
|
| 7 |
+
``convolution_fwht``, ``convolution_subset``,
|
| 8 |
+
``covering_product``, ``intersecting_product``
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from .transforms import (fft, ifft, ntt, intt, fwht, ifwht,
|
| 12 |
+
mobius_transform, inverse_mobius_transform)
|
| 13 |
+
from .convolutions import convolution, covering_product, intersecting_product
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
|
| 17 |
+
'inverse_mobius_transform',
|
| 18 |
+
|
| 19 |
+
'convolution', 'covering_product', 'intersecting_product',
|
| 20 |
+
]
|
vllm/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/discrete/convolutions.py
ADDED
|
@@ -0,0 +1,597 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
| 1 |
+
"""
|
| 2 |
+
Convolution (using **FFT**, **NTT**, **FWHT**), Subset Convolution,
|
| 3 |
+
Covering Product, Intersecting Product
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from sympy.core import S, sympify, Rational
|
| 7 |
+
from sympy.core.function import expand_mul
|
| 8 |
+
from sympy.discrete.transforms import (
|
| 9 |
+
fft, ifft, ntt, intt, fwht, ifwht,
|
| 10 |
+
mobius_transform, inverse_mobius_transform)
|
| 11 |
+
from sympy.external.gmpy import MPZ, lcm
|
| 12 |
+
from sympy.utilities.iterables import iterable
|
| 13 |
+
from sympy.utilities.misc import as_int
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def convolution(a, b, cycle=0, dps=None, prime=None, dyadic=None, subset=None):
|
| 17 |
+
"""
|
| 18 |
+
Performs convolution by determining the type of desired
|
| 19 |
+
convolution using hints.
|
| 20 |
+
|
| 21 |
+
Exactly one of ``dps``, ``prime``, ``dyadic``, ``subset`` arguments
|
| 22 |
+
should be specified explicitly for identifying the type of convolution,
|
| 23 |
+
and the argument ``cycle`` can be specified optionally.
|
| 24 |
+
|
| 25 |
+
For the default arguments, linear convolution is performed using **FFT**.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
==========
|
| 29 |
+
|
| 30 |
+
a, b : iterables
|
| 31 |
+
The sequences for which convolution is performed.
|
| 32 |
+
cycle : Integer
|
| 33 |
+
Specifies the length for doing cyclic convolution.
|
| 34 |
+
dps : Integer
|
| 35 |
+
Specifies the number of decimal digits for precision for
|
| 36 |
+
performing **FFT** on the sequence.
|
| 37 |
+
prime : Integer
|
| 38 |
+
Prime modulus of the form `(m 2^k + 1)` to be used for
|
| 39 |
+
performing **NTT** on the sequence.
|
| 40 |
+
dyadic : bool
|
| 41 |
+
Identifies the convolution type as dyadic (*bitwise-XOR*)
|
| 42 |
+
convolution, which is performed using **FWHT**.
|
| 43 |
+
subset : bool
|
| 44 |
+
Identifies the convolution type as subset convolution.
|
| 45 |
+
|
| 46 |
+
Examples
|
| 47 |
+
========
|
| 48 |
+
|
| 49 |
+
>>> from sympy import convolution, symbols, S, I
|
| 50 |
+
>>> u, v, w, x, y, z = symbols('u v w x y z')
|
| 51 |
+
|
| 52 |
+
>>> convolution([1 + 2*I, 4 + 3*I], [S(5)/4, 6], dps=3)
|
| 53 |
+
[1.25 + 2.5*I, 11.0 + 15.8*I, 24.0 + 18.0*I]
|
| 54 |
+
>>> convolution([1, 2, 3], [4, 5, 6], cycle=3)
|
| 55 |
+
[31, 31, 28]
|
| 56 |
+
|
| 57 |
+
>>> convolution([111, 777], [888, 444], prime=19*2**10 + 1)
|
| 58 |
+
[1283, 19351, 14219]
|
| 59 |
+
>>> convolution([111, 777], [888, 444], prime=19*2**10 + 1, cycle=2)
|
| 60 |
+
[15502, 19351]
|
| 61 |
+
|
| 62 |
+
>>> convolution([u, v], [x, y, z], dyadic=True)
|
| 63 |
+
[u*x + v*y, u*y + v*x, u*z, v*z]
|
| 64 |
+
>>> convolution([u, v], [x, y, z], dyadic=True, cycle=2)
|
| 65 |
+
[u*x + u*z + v*y, u*y + v*x + v*z]
|
| 66 |
+
|
| 67 |
+
>>> convolution([u, v, w], [x, y, z], subset=True)
|
| 68 |
+
[u*x, u*y + v*x, u*z + w*x, v*z + w*y]
|
| 69 |
+
>>> convolution([u, v, w], [x, y, z], subset=True, cycle=3)
|
| 70 |
+
[u*x + v*z + w*y, u*y + v*x, u*z + w*x]
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
c = as_int(cycle)
|
| 75 |
+
if c < 0:
|
| 76 |
+
raise ValueError("The length for cyclic convolution "
|
| 77 |
+
"must be non-negative")
|
| 78 |
+
|
| 79 |
+
dyadic = True if dyadic else None
|
| 80 |
+
subset = True if subset else None
|
| 81 |
+
if sum(x is not None for x in (prime, dps, dyadic, subset)) > 1:
|
| 82 |
+
raise TypeError("Ambiguity in determining the type of convolution")
|
| 83 |
+
|
| 84 |
+
if prime is not None:
|
| 85 |
+
ls = convolution_ntt(a, b, prime=prime)
|
| 86 |
+
return ls if not c else [sum(ls[i::c]) % prime for i in range(c)]
|
| 87 |
+
|
| 88 |
+
if dyadic:
|
| 89 |
+
ls = convolution_fwht(a, b)
|
| 90 |
+
elif subset:
|
| 91 |
+
ls = convolution_subset(a, b)
|
| 92 |
+
else:
|
| 93 |
+
def loop(a):
|
| 94 |
+
dens = []
|
| 95 |
+
for i in a:
|
| 96 |
+
if isinstance(i, Rational) and i.q - 1:
|
| 97 |
+
dens.append(i.q)
|
| 98 |
+
elif not isinstance(i, int):
|
| 99 |
+
return
|
| 100 |
+
if dens:
|
| 101 |
+
l = lcm(*dens)
|
| 102 |
+
return [i*l if type(i) is int else i.p*(l//i.q) for i in a], l
|
| 103 |
+
# no lcm of den to deal with
|
| 104 |
+
return a, 1
|
| 105 |
+
ls = None
|
| 106 |
+
da = loop(a)
|
| 107 |
+
if da is not None:
|
| 108 |
+
db = loop(b)
|
| 109 |
+
if db is not None:
|
| 110 |
+
(ia, ma), (ib, mb) = da, db
|
| 111 |
+
den = ma*mb
|
| 112 |
+
ls = convolution_int(ia, ib)
|
| 113 |
+
if den != 1:
|
| 114 |
+
ls = [Rational(i, den) for i in ls]
|
| 115 |
+
if ls is None:
|
| 116 |
+
ls = convolution_fft(a, b, dps)
|
| 117 |
+
|
| 118 |
+
return ls if not c else [sum(ls[i::c]) for i in range(c)]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
#----------------------------------------------------------------------------#
|
| 122 |
+
# #
|
| 123 |
+
# Convolution for Complex domain #
|
| 124 |
+
# #
|
| 125 |
+
#----------------------------------------------------------------------------#
|
| 126 |
+
|
| 127 |
+
def convolution_fft(a, b, dps=None):
|
| 128 |
+
"""
|
| 129 |
+
Performs linear convolution using Fast Fourier Transform.
|
| 130 |
+
|
| 131 |
+
Parameters
|
| 132 |
+
==========
|
| 133 |
+
|
| 134 |
+
a, b : iterables
|
| 135 |
+
The sequences for which convolution is performed.
|
| 136 |
+
dps : Integer
|
| 137 |
+
Specifies the number of decimal digits for precision.
|
| 138 |
+
|
| 139 |
+
Examples
|
| 140 |
+
========
|
| 141 |
+
|
| 142 |
+
>>> from sympy import S, I
|
| 143 |
+
>>> from sympy.discrete.convolutions import convolution_fft
|
| 144 |
+
|
| 145 |
+
>>> convolution_fft([2, 3], [4, 5])
|
| 146 |
+
[8, 22, 15]
|
| 147 |
+
>>> convolution_fft([2, 5], [6, 7, 3])
|
| 148 |
+
[12, 44, 41, 15]
|
| 149 |
+
>>> convolution_fft([1 + 2*I, 4 + 3*I], [S(5)/4, 6])
|
| 150 |
+
[5/4 + 5*I/2, 11 + 63*I/4, 24 + 18*I]
|
| 151 |
+
|
| 152 |
+
References
|
| 153 |
+
==========
|
| 154 |
+
|
| 155 |
+
.. [1] https://en.wikipedia.org/wiki/Convolution_theorem
|
| 156 |
+
.. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
|
| 157 |
+
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
a, b = a[:], b[:]
|
| 161 |
+
n = m = len(a) + len(b) - 1 # convolution size
|
| 162 |
+
|
| 163 |
+
if n > 0 and n&(n - 1): # not a power of 2
|
| 164 |
+
n = 2**n.bit_length()
|
| 165 |
+
|
| 166 |
+
# padding with zeros
|
| 167 |
+
a += [S.Zero]*(n - len(a))
|
| 168 |
+
b += [S.Zero]*(n - len(b))
|
| 169 |
+
|
| 170 |
+
a, b = fft(a, dps), fft(b, dps)
|
| 171 |
+
a = [expand_mul(x*y) for x, y in zip(a, b)]
|
| 172 |
+
a = ifft(a, dps)[:m]
|
| 173 |
+
|
| 174 |
+
return a
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
#----------------------------------------------------------------------------#
|
| 178 |
+
# #
|
| 179 |
+
# Convolution for GF(p) #
|
| 180 |
+
# #
|
| 181 |
+
#----------------------------------------------------------------------------#
|
| 182 |
+
|
| 183 |
+
def convolution_ntt(a, b, prime):
|
| 184 |
+
"""
|
| 185 |
+
Performs linear convolution using Number Theoretic Transform.
|
| 186 |
+
|
| 187 |
+
Parameters
|
| 188 |
+
==========
|
| 189 |
+
|
| 190 |
+
a, b : iterables
|
| 191 |
+
The sequences for which convolution is performed.
|
| 192 |
+
prime : Integer
|
| 193 |
+
Prime modulus of the form `(m 2^k + 1)` to be used for performing
|
| 194 |
+
**NTT** on the sequence.
|
| 195 |
+
|
| 196 |
+
Examples
|
| 197 |
+
========
|
| 198 |
+
|
| 199 |
+
>>> from sympy.discrete.convolutions import convolution_ntt
|
| 200 |
+
>>> convolution_ntt([2, 3], [4, 5], prime=19*2**10 + 1)
|
| 201 |
+
[8, 22, 15]
|
| 202 |
+
>>> convolution_ntt([2, 5], [6, 7, 3], prime=19*2**10 + 1)
|
| 203 |
+
[12, 44, 41, 15]
|
| 204 |
+
>>> convolution_ntt([333, 555], [222, 666], prime=19*2**10 + 1)
|
| 205 |
+
[15555, 14219, 19404]
|
| 206 |
+
|
| 207 |
+
References
|
| 208 |
+
==========
|
| 209 |
+
|
| 210 |
+
.. [1] https://en.wikipedia.org/wiki/Convolution_theorem
|
| 211 |
+
.. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
|
| 212 |
+
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
a, b, p = a[:], b[:], as_int(prime)
|
| 216 |
+
n = m = len(a) + len(b) - 1 # convolution size
|
| 217 |
+
|
| 218 |
+
if n > 0 and n&(n - 1): # not a power of 2
|
| 219 |
+
n = 2**n.bit_length()
|
| 220 |
+
|
| 221 |
+
# padding with zeros
|
| 222 |
+
a += [0]*(n - len(a))
|
| 223 |
+
b += [0]*(n - len(b))
|
| 224 |
+
|
| 225 |
+
a, b = ntt(a, p), ntt(b, p)
|
| 226 |
+
a = [x*y % p for x, y in zip(a, b)]
|
| 227 |
+
a = intt(a, p)[:m]
|
| 228 |
+
|
| 229 |
+
return a
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
#----------------------------------------------------------------------------#
|
| 233 |
+
# #
|
| 234 |
+
# Convolution for 2**n-group #
|
| 235 |
+
# #
|
| 236 |
+
#----------------------------------------------------------------------------#
|
| 237 |
+
|
| 238 |
+
def convolution_fwht(a, b):
|
| 239 |
+
"""
|
| 240 |
+
Performs dyadic (*bitwise-XOR*) convolution using Fast Walsh Hadamard
|
| 241 |
+
Transform.
|
| 242 |
+
|
| 243 |
+
The convolution is automatically padded to the right with zeros, as the
|
| 244 |
+
*radix-2 FWHT* requires the number of sample points to be a power of 2.
|
| 245 |
+
|
| 246 |
+
Parameters
|
| 247 |
+
==========
|
| 248 |
+
|
| 249 |
+
a, b : iterables
|
| 250 |
+
The sequences for which convolution is performed.
|
| 251 |
+
|
| 252 |
+
Examples
|
| 253 |
+
========
|
| 254 |
+
|
| 255 |
+
>>> from sympy import symbols, S, I
|
| 256 |
+
>>> from sympy.discrete.convolutions import convolution_fwht
|
| 257 |
+
|
| 258 |
+
>>> u, v, x, y = symbols('u v x y')
|
| 259 |
+
>>> convolution_fwht([u, v], [x, y])
|
| 260 |
+
[u*x + v*y, u*y + v*x]
|
| 261 |
+
|
| 262 |
+
>>> convolution_fwht([2, 3], [4, 5])
|
| 263 |
+
[23, 22]
|
| 264 |
+
>>> convolution_fwht([2, 5 + 4*I, 7], [6*I, 7, 3 + 4*I])
|
| 265 |
+
[56 + 68*I, -10 + 30*I, 6 + 50*I, 48 + 32*I]
|
| 266 |
+
|
| 267 |
+
>>> convolution_fwht([S(33)/7, S(55)/6, S(7)/4], [S(2)/3, 5])
|
| 268 |
+
[2057/42, 1870/63, 7/6, 35/4]
|
| 269 |
+
|
| 270 |
+
References
|
| 271 |
+
==========
|
| 272 |
+
|
| 273 |
+
.. [1] https://www.radioeng.cz/fulltexts/2002/02_03_40_42.pdf
|
| 274 |
+
.. [2] https://en.wikipedia.org/wiki/Hadamard_transform
|
| 275 |
+
|
| 276 |
+
"""
|
| 277 |
+
|
| 278 |
+
if not a or not b:
|
| 279 |
+
return []
|
| 280 |
+
|
| 281 |
+
a, b = a[:], b[:]
|
| 282 |
+
n = max(len(a), len(b))
|
| 283 |
+
|
| 284 |
+
if n&(n - 1): # not a power of 2
|
| 285 |
+
n = 2**n.bit_length()
|
| 286 |
+
|
| 287 |
+
# padding with zeros
|
| 288 |
+
a += [S.Zero]*(n - len(a))
|
| 289 |
+
b += [S.Zero]*(n - len(b))
|
| 290 |
+
|
| 291 |
+
a, b = fwht(a), fwht(b)
|
| 292 |
+
a = [expand_mul(x*y) for x, y in zip(a, b)]
|
| 293 |
+
a = ifwht(a)
|
| 294 |
+
|
| 295 |
+
return a
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
#----------------------------------------------------------------------------#
|
| 299 |
+
# #
|
| 300 |
+
# Subset Convolution #
|
| 301 |
+
# #
|
| 302 |
+
#----------------------------------------------------------------------------#
|
| 303 |
+
|
| 304 |
+
def convolution_subset(a, b):
|
| 305 |
+
"""
|
| 306 |
+
Performs Subset Convolution of given sequences.
|
| 307 |
+
|
| 308 |
+
The indices of each argument, considered as bit strings, correspond to
|
| 309 |
+
subsets of a finite set.
|
| 310 |
+
|
| 311 |
+
The sequence is automatically padded to the right with zeros, as the
|
| 312 |
+
definition of subset based on bitmasks (indices) requires the size of
|
| 313 |
+
sequence to be a power of 2.
|
| 314 |
+
|
| 315 |
+
Parameters
|
| 316 |
+
==========
|
| 317 |
+
|
| 318 |
+
a, b : iterables
|
| 319 |
+
The sequences for which convolution is performed.
|
| 320 |
+
|
| 321 |
+
Examples
|
| 322 |
+
========
|
| 323 |
+
|
| 324 |
+
>>> from sympy import symbols, S
|
| 325 |
+
>>> from sympy.discrete.convolutions import convolution_subset
|
| 326 |
+
>>> u, v, x, y, z = symbols('u v x y z')
|
| 327 |
+
|
| 328 |
+
>>> convolution_subset([u, v], [x, y])
|
| 329 |
+
[u*x, u*y + v*x]
|
| 330 |
+
>>> convolution_subset([u, v, x], [y, z])
|
| 331 |
+
[u*y, u*z + v*y, x*y, x*z]
|
| 332 |
+
|
| 333 |
+
>>> convolution_subset([1, S(2)/3], [3, 4])
|
| 334 |
+
[3, 6]
|
| 335 |
+
>>> convolution_subset([1, 3, S(5)/7], [7])
|
| 336 |
+
[7, 21, 5, 0]
|
| 337 |
+
|
| 338 |
+
References
|
| 339 |
+
==========
|
| 340 |
+
|
| 341 |
+
.. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
|
| 342 |
+
|
| 343 |
+
"""
|
| 344 |
+
|
| 345 |
+
if not a or not b:
|
| 346 |
+
return []
|
| 347 |
+
|
| 348 |
+
if not iterable(a) or not iterable(b):
|
| 349 |
+
raise TypeError("Expected a sequence of coefficients for convolution")
|
| 350 |
+
|
| 351 |
+
a = [sympify(arg) for arg in a]
|
| 352 |
+
b = [sympify(arg) for arg in b]
|
| 353 |
+
n = max(len(a), len(b))
|
| 354 |
+
|
| 355 |
+
if n&(n - 1): # not a power of 2
|
| 356 |
+
n = 2**n.bit_length()
|
| 357 |
+
|
| 358 |
+
# padding with zeros
|
| 359 |
+
a += [S.Zero]*(n - len(a))
|
| 360 |
+
b += [S.Zero]*(n - len(b))
|
| 361 |
+
|
| 362 |
+
c = [S.Zero]*n
|
| 363 |
+
|
| 364 |
+
for mask in range(n):
|
| 365 |
+
smask = mask
|
| 366 |
+
while smask > 0:
|
| 367 |
+
c[mask] += expand_mul(a[smask] * b[mask^smask])
|
| 368 |
+
smask = (smask - 1)&mask
|
| 369 |
+
|
| 370 |
+
c[mask] += expand_mul(a[smask] * b[mask^smask])
|
| 371 |
+
|
| 372 |
+
return c
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
#----------------------------------------------------------------------------#
|
| 376 |
+
# #
|
| 377 |
+
# Covering Product #
|
| 378 |
+
# #
|
| 379 |
+
#----------------------------------------------------------------------------#
|
| 380 |
+
|
| 381 |
+
def covering_product(a, b):
|
| 382 |
+
"""
|
| 383 |
+
Returns the covering product of given sequences.
|
| 384 |
+
|
| 385 |
+
The indices of each argument, considered as bit strings, correspond to
|
| 386 |
+
subsets of a finite set.
|
| 387 |
+
|
| 388 |
+
The covering product of given sequences is a sequence which contains
|
| 389 |
+
the sum of products of the elements of the given sequences grouped by
|
| 390 |
+
the *bitwise-OR* of the corresponding indices.
|
| 391 |
+
|
| 392 |
+
The sequence is automatically padded to the right with zeros, as the
|
| 393 |
+
definition of subset based on bitmasks (indices) requires the size of
|
| 394 |
+
sequence to be a power of 2.
|
| 395 |
+
|
| 396 |
+
Parameters
|
| 397 |
+
==========
|
| 398 |
+
|
| 399 |
+
a, b : iterables
|
| 400 |
+
The sequences for which covering product is to be obtained.
|
| 401 |
+
|
| 402 |
+
Examples
|
| 403 |
+
========
|
| 404 |
+
|
| 405 |
+
>>> from sympy import symbols, S, I, covering_product
|
| 406 |
+
>>> u, v, x, y, z = symbols('u v x y z')
|
| 407 |
+
|
| 408 |
+
>>> covering_product([u, v], [x, y])
|
| 409 |
+
[u*x, u*y + v*x + v*y]
|
| 410 |
+
>>> covering_product([u, v, x], [y, z])
|
| 411 |
+
[u*y, u*z + v*y + v*z, x*y, x*z]
|
| 412 |
+
|
| 413 |
+
>>> covering_product([1, S(2)/3], [3, 4 + 5*I])
|
| 414 |
+
[3, 26/3 + 25*I/3]
|
| 415 |
+
>>> covering_product([1, 3, S(5)/7], [7, 8])
|
| 416 |
+
[7, 53, 5, 40/7]
|
| 417 |
+
|
| 418 |
+
References
|
| 419 |
+
==========
|
| 420 |
+
|
| 421 |
+
.. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
|
| 422 |
+
|
| 423 |
+
"""
|
| 424 |
+
|
| 425 |
+
if not a or not b:
|
| 426 |
+
return []
|
| 427 |
+
|
| 428 |
+
a, b = a[:], b[:]
|
| 429 |
+
n = max(len(a), len(b))
|
| 430 |
+
|
| 431 |
+
if n&(n - 1): # not a power of 2
|
| 432 |
+
n = 2**n.bit_length()
|
| 433 |
+
|
| 434 |
+
# padding with zeros
|
| 435 |
+
a += [S.Zero]*(n - len(a))
|
| 436 |
+
b += [S.Zero]*(n - len(b))
|
| 437 |
+
|
| 438 |
+
a, b = mobius_transform(a), mobius_transform(b)
|
| 439 |
+
a = [expand_mul(x*y) for x, y in zip(a, b)]
|
| 440 |
+
a = inverse_mobius_transform(a)
|
| 441 |
+
|
| 442 |
+
return a
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
#----------------------------------------------------------------------------#
|
| 446 |
+
# #
|
| 447 |
+
# Intersecting Product #
|
| 448 |
+
# #
|
| 449 |
+
#----------------------------------------------------------------------------#
|
| 450 |
+
|
| 451 |
+
def intersecting_product(a, b):
|
| 452 |
+
"""
|
| 453 |
+
Returns the intersecting product of given sequences.
|
| 454 |
+
|
| 455 |
+
The indices of each argument, considered as bit strings, correspond to
|
| 456 |
+
subsets of a finite set.
|
| 457 |
+
|
| 458 |
+
The intersecting product of given sequences is the sequence which
|
| 459 |
+
contains the sum of products of the elements of the given sequences
|
| 460 |
+
grouped by the *bitwise-AND* of the corresponding indices.
|
| 461 |
+
|
| 462 |
+
The sequence is automatically padded to the right with zeros, as the
|
| 463 |
+
definition of subset based on bitmasks (indices) requires the size of
|
| 464 |
+
sequence to be a power of 2.
|
| 465 |
+
|
| 466 |
+
Parameters
|
| 467 |
+
==========
|
| 468 |
+
|
| 469 |
+
a, b : iterables
|
| 470 |
+
The sequences for which intersecting product is to be obtained.
|
| 471 |
+
|
| 472 |
+
Examples
|
| 473 |
+
========
|
| 474 |
+
|
| 475 |
+
>>> from sympy import symbols, S, I, intersecting_product
|
| 476 |
+
>>> u, v, x, y, z = symbols('u v x y z')
|
| 477 |
+
|
| 478 |
+
>>> intersecting_product([u, v], [x, y])
|
| 479 |
+
[u*x + u*y + v*x, v*y]
|
| 480 |
+
>>> intersecting_product([u, v, x], [y, z])
|
| 481 |
+
[u*y + u*z + v*y + x*y + x*z, v*z, 0, 0]
|
| 482 |
+
|
| 483 |
+
>>> intersecting_product([1, S(2)/3], [3, 4 + 5*I])
|
| 484 |
+
[9 + 5*I, 8/3 + 10*I/3]
|
| 485 |
+
>>> intersecting_product([1, 3, S(5)/7], [7, 8])
|
| 486 |
+
[327/7, 24, 0, 0]
|
| 487 |
+
|
| 488 |
+
References
|
| 489 |
+
==========
|
| 490 |
+
|
| 491 |
+
.. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
|
| 492 |
+
|
| 493 |
+
"""
|
| 494 |
+
|
| 495 |
+
if not a or not b:
|
| 496 |
+
return []
|
| 497 |
+
|
| 498 |
+
a, b = a[:], b[:]
|
| 499 |
+
n = max(len(a), len(b))
|
| 500 |
+
|
| 501 |
+
if n&(n - 1): # not a power of 2
|
| 502 |
+
n = 2**n.bit_length()
|
| 503 |
+
|
| 504 |
+
# padding with zeros
|
| 505 |
+
a += [S.Zero]*(n - len(a))
|
| 506 |
+
b += [S.Zero]*(n - len(b))
|
| 507 |
+
|
| 508 |
+
a, b = mobius_transform(a, subset=False), mobius_transform(b, subset=False)
|
| 509 |
+
a = [expand_mul(x*y) for x, y in zip(a, b)]
|
| 510 |
+
a = inverse_mobius_transform(a, subset=False)
|
| 511 |
+
|
| 512 |
+
return a
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
#----------------------------------------------------------------------------#
|
| 516 |
+
# #
|
| 517 |
+
# Integer Convolutions #
|
| 518 |
+
# #
|
| 519 |
+
#----------------------------------------------------------------------------#
|
| 520 |
+
|
| 521 |
+
def convolution_int(a, b):
|
| 522 |
+
"""Return the convolution of two sequences as a list.
|
| 523 |
+
|
| 524 |
+
The iterables must consist solely of integers.
|
| 525 |
+
|
| 526 |
+
Parameters
|
| 527 |
+
==========
|
| 528 |
+
|
| 529 |
+
a, b : Sequence
|
| 530 |
+
The sequences for which convolution is performed.
|
| 531 |
+
|
| 532 |
+
Explanation
|
| 533 |
+
===========
|
| 534 |
+
|
| 535 |
+
This function performs the convolution of ``a`` and ``b`` by packing
|
| 536 |
+
each into a single integer, multiplying them together, and then
|
| 537 |
+
unpacking the result from the product. The intuition behind this is
|
| 538 |
+
that if we evaluate some polynomial [1]:
|
| 539 |
+
|
| 540 |
+
.. math ::
|
| 541 |
+
1156x^6 + 3808x^5 + 8440x^4 + 14856x^3 + 16164x^2 + 14040x + 8100
|
| 542 |
+
|
| 543 |
+
at say $x = 10^5$ we obtain $1156038080844014856161641404008100$.
|
| 544 |
+
Note we can read of the coefficients for each term every five digits.
|
| 545 |
+
If the $x$ we chose to evaluate at is large enough, the same will hold
|
| 546 |
+
for the product.
|
| 547 |
+
|
| 548 |
+
The idea now is since big integer multiplication in libraries such
|
| 549 |
+
as GMP is highly optimised, this will be reasonably fast.
|
| 550 |
+
|
| 551 |
+
Examples
|
| 552 |
+
========
|
| 553 |
+
|
| 554 |
+
>>> from sympy.discrete.convolutions import convolution_int
|
| 555 |
+
|
| 556 |
+
>>> convolution_int([2, 3], [4, 5])
|
| 557 |
+
[8, 22, 15]
|
| 558 |
+
>>> convolution_int([1, 1, -1], [1, 1])
|
| 559 |
+
[1, 2, 0, -1]
|
| 560 |
+
|
| 561 |
+
References
|
| 562 |
+
==========
|
| 563 |
+
|
| 564 |
+
.. [1] Fateman, Richard J.
|
| 565 |
+
Can you save time in multiplying polynomials by encoding them as integers?
|
| 566 |
+
University of California, Berkeley, California (2004).
|
| 567 |
+
https://people.eecs.berkeley.edu/~fateman/papers/polysbyGMP.pdf
|
| 568 |
+
"""
|
| 569 |
+
# An upper bound on the largest coefficient in p(x)q(x) is given by (1 + min(dp, dq))N(p)N(q)
|
| 570 |
+
# where dp = deg(p), dq = deg(q), N(f) denotes the coefficient of largest modulus in f [1]
|
| 571 |
+
B = max(abs(c) for c in a)*max(abs(c) for c in b)*(1 + min(len(a) - 1, len(b) - 1))
|
| 572 |
+
x, power = MPZ(1), 0
|
| 573 |
+
while x <= (2*B): # multiply by two for negative coefficients, see [1]
|
| 574 |
+
x <<= 1
|
| 575 |
+
power += 1
|
| 576 |
+
|
| 577 |
+
def to_integer(poly):
|
| 578 |
+
n, mul = MPZ(0), 0
|
| 579 |
+
for c in reversed(poly):
|
| 580 |
+
if c and not mul: mul = -1 if c < 0 else 1
|
| 581 |
+
n <<= power
|
| 582 |
+
n += mul*int(c)
|
| 583 |
+
return mul, n
|
| 584 |
+
|
| 585 |
+
# Perform packing and multiplication
|
| 586 |
+
(a_mul, a_packed), (b_mul, b_packed) = to_integer(a), to_integer(b)
|
| 587 |
+
result = a_packed * b_packed
|
| 588 |
+
|
| 589 |
+
# Perform unpacking
|
| 590 |
+
mul = a_mul * b_mul
|
| 591 |
+
mask, half, borrow, poly = x - 1, x >> 1, 0, []
|
| 592 |
+
while result or borrow:
|
| 593 |
+
coeff = (result & mask) + borrow
|
| 594 |
+
result >>= power
|
| 595 |
+
borrow = coeff >= half
|
| 596 |
+
poly.append(mul * int(coeff if coeff < half else coeff - x))
|
| 597 |
+
return poly or [0]
|
vllm/lib/python3.10/site-packages/sympy/discrete/recurrences.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Recurrences
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from sympy.core import S, sympify
|
| 6 |
+
from sympy.utilities.iterables import iterable
|
| 7 |
+
from sympy.utilities.misc import as_int
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def linrec(coeffs, init, n):
|
| 11 |
+
r"""
|
| 12 |
+
Evaluation of univariate linear recurrences of homogeneous type
|
| 13 |
+
having coefficients independent of the recurrence variable.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
==========
|
| 17 |
+
|
| 18 |
+
coeffs : iterable
|
| 19 |
+
Coefficients of the recurrence
|
| 20 |
+
init : iterable
|
| 21 |
+
Initial values of the recurrence
|
| 22 |
+
n : Integer
|
| 23 |
+
Point of evaluation for the recurrence
|
| 24 |
+
|
| 25 |
+
Notes
|
| 26 |
+
=====
|
| 27 |
+
|
| 28 |
+
Let `y(n)` be the recurrence of given type, ``c`` be the sequence
|
| 29 |
+
of coefficients, ``b`` be the sequence of initial/base values of the
|
| 30 |
+
recurrence and ``k`` (equal to ``len(c)``) be the order of recurrence.
|
| 31 |
+
Then,
|
| 32 |
+
|
| 33 |
+
.. math :: y(n) = \begin{cases} b_n & 0 \le n < k \\
|
| 34 |
+
c_0 y(n-1) + c_1 y(n-2) + \cdots + c_{k-1} y(n-k) & n \ge k
|
| 35 |
+
\end{cases}
|
| 36 |
+
|
| 37 |
+
Let `x_0, x_1, \ldots, x_n` be a sequence and consider the transformation
|
| 38 |
+
that maps each polynomial `f(x)` to `T(f(x))` where each power `x^i` is
|
| 39 |
+
replaced by the corresponding value `x_i`. The sequence is then a solution
|
| 40 |
+
of the recurrence if and only if `T(x^i p(x)) = 0` for each `i \ge 0` where
|
| 41 |
+
`p(x) = x^k - c_0 x^(k-1) - \cdots - c_{k-1}` is the characteristic
|
| 42 |
+
polynomial.
|
| 43 |
+
|
| 44 |
+
Then `T(f(x)p(x)) = 0` for each polynomial `f(x)` (as it is a linear
|
| 45 |
+
combination of powers `x^i`). Now, if `x^n` is congruent to
|
| 46 |
+
`g(x) = a_0 x^0 + a_1 x^1 + \cdots + a_{k-1} x^{k-1}` modulo `p(x)`, then
|
| 47 |
+
`T(x^n) = x_n` is equal to
|
| 48 |
+
`T(g(x)) = a_0 x_0 + a_1 x_1 + \cdots + a_{k-1} x_{k-1}`.
|
| 49 |
+
|
| 50 |
+
Computation of `x^n`,
|
| 51 |
+
given `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
|
| 52 |
+
is performed using exponentiation by squaring (refer to [1_]) with
|
| 53 |
+
an additional reduction step performed to retain only first `k` powers
|
| 54 |
+
of `x` in the representation of `x^n`.
|
| 55 |
+
|
| 56 |
+
Examples
|
| 57 |
+
========
|
| 58 |
+
|
| 59 |
+
>>> from sympy.discrete.recurrences import linrec
|
| 60 |
+
>>> from sympy.abc import x, y, z
|
| 61 |
+
|
| 62 |
+
>>> linrec(coeffs=[1, 1], init=[0, 1], n=10)
|
| 63 |
+
55
|
| 64 |
+
|
| 65 |
+
>>> linrec(coeffs=[1, 1], init=[x, y], n=10)
|
| 66 |
+
34*x + 55*y
|
| 67 |
+
|
| 68 |
+
>>> linrec(coeffs=[x, y], init=[0, 1], n=5)
|
| 69 |
+
x**2*y + x*(x**3 + 2*x*y) + y**2
|
| 70 |
+
|
| 71 |
+
>>> linrec(coeffs=[1, 2, 3, 0, 0, 4], init=[x, y, z], n=16)
|
| 72 |
+
13576*x + 5676*y + 2356*z
|
| 73 |
+
|
| 74 |
+
References
|
| 75 |
+
==========
|
| 76 |
+
|
| 77 |
+
.. [1] https://en.wikipedia.org/wiki/Exponentiation_by_squaring
|
| 78 |
+
.. [2] https://en.wikipedia.org/w/index.php?title=Modular_exponentiation§ion=6#Matrices
|
| 79 |
+
|
| 80 |
+
See Also
|
| 81 |
+
========
|
| 82 |
+
|
| 83 |
+
sympy.polys.agca.extensions.ExtensionElement.__pow__
|
| 84 |
+
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
if not coeffs:
|
| 88 |
+
return S.Zero
|
| 89 |
+
|
| 90 |
+
if not iterable(coeffs):
|
| 91 |
+
raise TypeError("Expected a sequence of coefficients for"
|
| 92 |
+
" the recurrence")
|
| 93 |
+
|
| 94 |
+
if not iterable(init):
|
| 95 |
+
raise TypeError("Expected a sequence of values for the initialization"
|
| 96 |
+
" of the recurrence")
|
| 97 |
+
|
| 98 |
+
n = as_int(n)
|
| 99 |
+
if n < 0:
|
| 100 |
+
raise ValueError("Point of evaluation of recurrence must be a "
|
| 101 |
+
"non-negative integer")
|
| 102 |
+
|
| 103 |
+
c = [sympify(arg) for arg in coeffs]
|
| 104 |
+
b = [sympify(arg) for arg in init]
|
| 105 |
+
k = len(c)
|
| 106 |
+
|
| 107 |
+
if len(b) > k:
|
| 108 |
+
raise TypeError("Count of initial values should not exceed the "
|
| 109 |
+
"order of the recurrence")
|
| 110 |
+
else:
|
| 111 |
+
b += [S.Zero]*(k - len(b)) # remaining initial values default to zero
|
| 112 |
+
|
| 113 |
+
if n < k:
|
| 114 |
+
return b[n]
|
| 115 |
+
terms = [u*v for u, v in zip(linrec_coeffs(c, n), b)]
|
| 116 |
+
return sum(terms[:-1], terms[-1])
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def linrec_coeffs(c, n):
|
| 120 |
+
r"""
|
| 121 |
+
Compute the coefficients of n'th term in linear recursion
|
| 122 |
+
sequence defined by c.
|
| 123 |
+
|
| 124 |
+
`x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`.
|
| 125 |
+
|
| 126 |
+
It computes the coefficients by using binary exponentiation.
|
| 127 |
+
This function is used by `linrec` and `_eval_pow_by_cayley`.
|
| 128 |
+
|
| 129 |
+
Parameters
|
| 130 |
+
==========
|
| 131 |
+
|
| 132 |
+
c = coefficients of the divisor polynomial
|
| 133 |
+
n = exponent of x, so dividend is x^n
|
| 134 |
+
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
k = len(c)
|
| 138 |
+
|
| 139 |
+
def _square_and_reduce(u, offset):
|
| 140 |
+
# squares `(u_0 + u_1 x + u_2 x^2 + \cdots + u_{k-1} x^k)` (and
|
| 141 |
+
# multiplies by `x` if offset is 1) and reduces the above result of
|
| 142 |
+
# length upto `2k` to `k` using the characteristic equation of the
|
| 143 |
+
# recurrence given by, `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
|
| 144 |
+
|
| 145 |
+
w = [S.Zero]*(2*len(u) - 1 + offset)
|
| 146 |
+
for i, p in enumerate(u):
|
| 147 |
+
for j, q in enumerate(u):
|
| 148 |
+
w[offset + i + j] += p*q
|
| 149 |
+
|
| 150 |
+
for j in range(len(w) - 1, k - 1, -1):
|
| 151 |
+
for i in range(k):
|
| 152 |
+
w[j - i - 1] += w[j]*c[i]
|
| 153 |
+
|
| 154 |
+
return w[:k]
|
| 155 |
+
|
| 156 |
+
def _final_coeffs(n):
|
| 157 |
+
# computes the final coefficient list - `cf` corresponding to the
|
| 158 |
+
# point at which recurrence is to be evalauted - `n`, such that,
|
| 159 |
+
# `y(n) = cf_0 y(k-1) + cf_1 y(k-2) + \cdots + cf_{k-1} y(0)`
|
| 160 |
+
|
| 161 |
+
if n < k:
|
| 162 |
+
return [S.Zero]*n + [S.One] + [S.Zero]*(k - n - 1)
|
| 163 |
+
else:
|
| 164 |
+
return _square_and_reduce(_final_coeffs(n // 2), n % 2)
|
| 165 |
+
|
| 166 |
+
return _final_coeffs(n)
|
vllm/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (170 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc
ADDED
|
Binary file (16.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc
ADDED
|
Binary file (3.43 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc
ADDED
|
Binary file (6.72 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import (E, Rational, pi)
|
| 2 |
+
from sympy.functions.elementary.exponential import exp
|
| 3 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 4 |
+
from sympy.core import S, symbols, I
|
| 5 |
+
from sympy.discrete.convolutions import (
|
| 6 |
+
convolution, convolution_fft, convolution_ntt, convolution_fwht,
|
| 7 |
+
convolution_subset, covering_product, intersecting_product,
|
| 8 |
+
convolution_int)
|
| 9 |
+
from sympy.testing.pytest import raises
|
| 10 |
+
from sympy.abc import x, y
|
| 11 |
+
|
| 12 |
+
def test_convolution():
|
| 13 |
+
# fft
|
| 14 |
+
a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
|
| 15 |
+
b = [9, 5, 5, 4, 3, 2]
|
| 16 |
+
c = [3, 5, 3, 7, 8]
|
| 17 |
+
d = [1422, 6572, 3213, 5552]
|
| 18 |
+
e = [-1, Rational(5, 3), Rational(7, 5)]
|
| 19 |
+
|
| 20 |
+
assert convolution(a, b) == convolution_fft(a, b)
|
| 21 |
+
assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9)
|
| 22 |
+
assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7)
|
| 23 |
+
assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3)
|
| 24 |
+
|
| 25 |
+
# prime moduli of the form (m*2**k + 1), sequence length
|
| 26 |
+
# should be a divisor of 2**k
|
| 27 |
+
p = 7*17*2**23 + 1
|
| 28 |
+
q = 19*2**10 + 1
|
| 29 |
+
|
| 30 |
+
# ntt
|
| 31 |
+
assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q)
|
| 32 |
+
assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p)
|
| 33 |
+
assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p)
|
| 34 |
+
raises(TypeError, lambda: convolution(b, d, dps=5, prime=q))
|
| 35 |
+
raises(TypeError, lambda: convolution(b, d, dps=6, prime=q))
|
| 36 |
+
|
| 37 |
+
# fwht
|
| 38 |
+
assert convolution(a, b, dyadic=True) == convolution_fwht(a, b)
|
| 39 |
+
assert convolution(a, b, dyadic=False) == convolution(a, b)
|
| 40 |
+
raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True))
|
| 41 |
+
raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True))
|
| 42 |
+
raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True))
|
| 43 |
+
raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True))
|
| 44 |
+
|
| 45 |
+
# subset
|
| 46 |
+
assert convolution(a, b, subset=True) == convolution_subset(a, b) == \
|
| 47 |
+
convolution(a, b, subset=True, dyadic=False) == \
|
| 48 |
+
convolution(a, b, subset=True)
|
| 49 |
+
assert convolution(a, b, subset=False) == convolution(a, b)
|
| 50 |
+
raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True))
|
| 51 |
+
raises(TypeError, lambda: convolution(c, d, subset=True, dps=6))
|
| 52 |
+
raises(TypeError, lambda: convolution(a, c, subset=True, prime=q))
|
| 53 |
+
|
| 54 |
+
# integer
|
| 55 |
+
assert convolution([0], [0]) == convolution_int([0], [0])
|
| 56 |
+
assert convolution(b, c) == convolution_int(b, c)
|
| 57 |
+
|
| 58 |
+
# rational
|
| 59 |
+
assert convolution([Rational(1,2)], [Rational(1,2)]) == [Rational(1, 4)]
|
| 60 |
+
assert convolution(b, e) == [-9, 10, Rational(239, 15), Rational(34, 3),
|
| 61 |
+
Rational(32, 3), Rational(43, 5), Rational(113, 15),
|
| 62 |
+
Rational(14, 5)]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_cyclic_convolution():
|
| 66 |
+
# fft
|
| 67 |
+
a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
|
| 68 |
+
b = [9, 5, 5, 4, 3, 2]
|
| 69 |
+
|
| 70 |
+
assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \
|
| 71 |
+
convolution([1, 2, 3], [4, 5, 6], cycle=5) == \
|
| 72 |
+
convolution([1, 2, 3], [4, 5, 6])
|
| 73 |
+
|
| 74 |
+
assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28]
|
| 75 |
+
|
| 76 |
+
a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)]
|
| 77 |
+
b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)]
|
| 78 |
+
|
| 79 |
+
assert convolution(a, b, cycle=0) == \
|
| 80 |
+
convolution(a, b, cycle=len(a) + len(b) - 1)
|
| 81 |
+
|
| 82 |
+
assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340),
|
| 83 |
+
Rational(11125, 4032), Rational(3653, 1080)]
|
| 84 |
+
|
| 85 |
+
assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24),
|
| 86 |
+
Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)]
|
| 87 |
+
|
| 88 |
+
assert convolution(a, b, cycle=9) == \
|
| 89 |
+
convolution(a, b, cycle=0) + [S.Zero]
|
| 90 |
+
|
| 91 |
+
# ntt
|
| 92 |
+
a = [2313, 5323532, S(3232), 42142, 42242421]
|
| 93 |
+
b = [S(33456), 56757, 45754, 432423]
|
| 94 |
+
|
| 95 |
+
assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \
|
| 96 |
+
convolution(a, b, prime=19*2**10 + 1, cycle=8) == \
|
| 97 |
+
convolution(a, b, prime=19*2**10 + 1)
|
| 98 |
+
|
| 99 |
+
assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664,
|
| 100 |
+
15534, 3517]
|
| 101 |
+
|
| 102 |
+
assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260,
|
| 103 |
+
15534, 3517, 16314, 13688]
|
| 104 |
+
|
| 105 |
+
assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \
|
| 106 |
+
convolution(a, b, prime=19*2**10 + 1) + [0]
|
| 107 |
+
|
| 108 |
+
# fwht
|
| 109 |
+
u, v, w, x, y = symbols('u v w x y')
|
| 110 |
+
p, q, r, s, t = symbols('p q r s t')
|
| 111 |
+
c = [u, v, w, x, y]
|
| 112 |
+
d = [p, q, r, s, t]
|
| 113 |
+
|
| 114 |
+
assert convolution(a, b, dyadic=True, cycle=3) == \
|
| 115 |
+
[2499522285783, 19861417974796, 4702176579021]
|
| 116 |
+
|
| 117 |
+
assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143,
|
| 118 |
+
2114320852171, 20571217906407, 246166418903, 1413262436976]
|
| 119 |
+
|
| 120 |
+
assert convolution(c, d, dyadic=True, cycle=4) == \
|
| 121 |
+
[p*u + p*y + q*v + r*w + s*x + t*u + t*y,
|
| 122 |
+
p*v + q*u + q*y + r*x + s*w + t*v,
|
| 123 |
+
p*w + q*x + r*u + r*y + s*v + t*w,
|
| 124 |
+
p*x + q*w + r*v + s*u + s*y + t*x]
|
| 125 |
+
|
| 126 |
+
assert convolution(c, d, dyadic=True, cycle=6) == \
|
| 127 |
+
[p*u + q*v + r*w + r*y + s*x + t*w + t*y,
|
| 128 |
+
p*v + q*u + r*x + s*w + s*y + t*x,
|
| 129 |
+
p*w + q*x + r*u + s*v,
|
| 130 |
+
p*x + q*w + r*v + s*u,
|
| 131 |
+
p*y + t*u,
|
| 132 |
+
q*y + t*v]
|
| 133 |
+
|
| 134 |
+
# subset
|
| 135 |
+
assert convolution(a, b, subset=True, cycle=7) == [18266671799811,
|
| 136 |
+
178235365533, 213958794, 246166418903, 1413262436976,
|
| 137 |
+
2397553088697, 1932759730434]
|
| 138 |
+
|
| 139 |
+
assert convolution(a[1:], b, subset=True, cycle=4) == \
|
| 140 |
+
[178104086592, 302255835516, 244982785880, 3717819845434]
|
| 141 |
+
|
| 142 |
+
assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162,
|
| 143 |
+
178235365533, 213958794, 245166224504, 1413262436976, 2397553088697]
|
| 144 |
+
|
| 145 |
+
assert convolution(c, d, subset=True, cycle=3) == \
|
| 146 |
+
[p*u + p*x + q*w + r*v + r*y + s*u + t*w,
|
| 147 |
+
p*v + p*y + q*u + s*y + t*u + t*x,
|
| 148 |
+
p*w + q*y + r*u + t*v]
|
| 149 |
+
|
| 150 |
+
assert convolution(c, d, subset=True, cycle=5) == \
|
| 151 |
+
[p*u + q*y + t*v,
|
| 152 |
+
p*v + q*u + r*y + t*w,
|
| 153 |
+
p*w + r*u + s*y + t*x,
|
| 154 |
+
p*x + q*w + r*v + s*u,
|
| 155 |
+
p*y + t*u]
|
| 156 |
+
|
| 157 |
+
raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def test_convolution_fft():
|
| 161 |
+
assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3))
|
| 162 |
+
assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
|
| 163 |
+
assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7]
|
| 164 |
+
assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
|
| 165 |
+
|
| 166 |
+
assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I]
|
| 167 |
+
assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + 3*I/5], [Rational(2, 5) + 4*I/7]) == \
|
| 168 |
+
[Rational(-26, 35) + I*48/35, Rational(-38, 35) + I*116/35, Rational(58, 35) + I*542/175]
|
| 169 |
+
|
| 170 |
+
assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \
|
| 171 |
+
[Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)]
|
| 172 |
+
|
| 173 |
+
assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \
|
| 174 |
+
[Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)]
|
| 175 |
+
|
| 176 |
+
assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \
|
| 177 |
+
[sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6),
|
| 178 |
+
sqrt(2)/pi + 1, sqrt(2)*exp(-1)]
|
| 179 |
+
|
| 180 |
+
assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \
|
| 181 |
+
[12350041, 190918524, 374911166, 2362431729]
|
| 182 |
+
|
| 183 |
+
assert convolution_fft([312313, 31278232], [32139631, 319631]) == \
|
| 184 |
+
[10037624576503, 1005370659728895, 9997492572392]
|
| 185 |
+
|
| 186 |
+
raises(TypeError, lambda: convolution_fft(x, y))
|
| 187 |
+
raises(ValueError, lambda: convolution_fft([x, y], [y, x]))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_convolution_ntt():
|
| 191 |
+
# prime moduli of the form (m*2**k + 1), sequence length
|
| 192 |
+
# should be a divisor of 2**k
|
| 193 |
+
p = 7*17*2**23 + 1
|
| 194 |
+
q = 19*2**10 + 1
|
| 195 |
+
r = 2*500000003 + 1 # only for sequences of length 1 or 2
|
| 196 |
+
# s = 2*3*5*7 # composite modulus
|
| 197 |
+
|
| 198 |
+
assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r))
|
| 199 |
+
assert convolution_ntt([2], [3], r) == [6]
|
| 200 |
+
assert convolution_ntt([2, 3], [4], r) == [8, 12]
|
| 201 |
+
|
| 202 |
+
assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619,
|
| 203 |
+
459741727, 79180879, 831885249, 381344700, 369993322]
|
| 204 |
+
assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \
|
| 205 |
+
[8158, 3065, 3682, 7090, 1239, 2232, 3744]
|
| 206 |
+
|
| 207 |
+
assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \
|
| 208 |
+
convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q)
|
| 209 |
+
assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \
|
| 210 |
+
convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q)
|
| 211 |
+
|
| 212 |
+
raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r))
|
| 213 |
+
raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q))
|
| 214 |
+
raises(TypeError, lambda: convolution_ntt(x, y, p))
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def test_convolution_fwht():
|
| 218 |
+
assert convolution_fwht([], []) == []
|
| 219 |
+
assert convolution_fwht([], [1]) == []
|
| 220 |
+
assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27]
|
| 221 |
+
|
| 222 |
+
assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \
|
| 223 |
+
[Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)]
|
| 224 |
+
|
| 225 |
+
a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I]
|
| 226 |
+
b = [94, 51, 53, 45, 31, 27, 13]
|
| 227 |
+
c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8]
|
| 228 |
+
|
| 229 |
+
assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I,
|
| 230 |
+
45*sqrt(3) + Rational(5848, 15) + 135*I,
|
| 231 |
+
94*sqrt(3) + Rational(1257, 5) + 65*I,
|
| 232 |
+
51*sqrt(3) + Rational(3974, 15),
|
| 233 |
+
13*sqrt(3) + 452 + 470*I,
|
| 234 |
+
Rational(4513, 15) + 255*I,
|
| 235 |
+
31*sqrt(3) + Rational(1314, 5) + 265*I,
|
| 236 |
+
27*sqrt(3) + Rational(3676, 15) + 225*I]
|
| 237 |
+
|
| 238 |
+
assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I,
|
| 239 |
+
Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I,
|
| 240 |
+
Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I]
|
| 241 |
+
|
| 242 |
+
assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*293/5, -1 + I*204/5,
|
| 243 |
+
Rational(133, 15) + I*35/6, Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0]
|
| 244 |
+
|
| 245 |
+
u, v, w, x, y, z = symbols('u v w x y z')
|
| 246 |
+
|
| 247 |
+
assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x]
|
| 248 |
+
|
| 249 |
+
assert convolution_fwht([u, v, w], [x, y]) == \
|
| 250 |
+
[u*x + v*y, u*y + v*x, w*x, w*y]
|
| 251 |
+
|
| 252 |
+
assert convolution_fwht([u, v, w], [x, y, z]) == \
|
| 253 |
+
[u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y]
|
| 254 |
+
|
| 255 |
+
raises(TypeError, lambda: convolution_fwht(x, y))
|
| 256 |
+
raises(TypeError, lambda: convolution_fwht(x*y, u + v))
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def test_convolution_subset():
|
| 260 |
+
assert convolution_subset([], []) == []
|
| 261 |
+
assert convolution_subset([], [Rational(1, 3)]) == []
|
| 262 |
+
assert convolution_subset([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
|
| 263 |
+
|
| 264 |
+
a = [1, Rational(5, 3), sqrt(3), 4 + 5*I]
|
| 265 |
+
b = [64, 71, 55, 47, 33, 29, 15]
|
| 266 |
+
c = [3 + I*2/3, 5 + 7*I, 7, Rational(7, 5), 9]
|
| 267 |
+
|
| 268 |
+
assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3),
|
| 269 |
+
71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84,
|
| 270 |
+
15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I]
|
| 271 |
+
|
| 272 |
+
assert convolution_subset(b, c) == [192 + I*128/3, 533 + I*1486/3,
|
| 273 |
+
613 + I*110/3, Rational(5013, 5) + I*1249/3,
|
| 274 |
+
675 + 22*I, 891 + I*751/3,
|
| 275 |
+
771 + 10*I, Rational(3736, 5) + 105*I]
|
| 276 |
+
|
| 277 |
+
assert convolution_subset(a, c) == convolution_subset(c, a)
|
| 278 |
+
assert convolution_subset(a[:2], b) == \
|
| 279 |
+
[64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25]
|
| 280 |
+
|
| 281 |
+
assert convolution_subset(a[:2], c) == \
|
| 282 |
+
[3 + I*2/3, 10 + I*73/9, 7, Rational(196, 15), 9, 15, 0, 0]
|
| 283 |
+
|
| 284 |
+
u, v, w, x, y, z = symbols('u v w x y z')
|
| 285 |
+
|
| 286 |
+
assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y]
|
| 287 |
+
assert convolution_subset([u, v, w, x], [y, z]) == \
|
| 288 |
+
[u*y, u*z + v*y, w*y, w*z + x*y]
|
| 289 |
+
|
| 290 |
+
assert convolution_subset([u, v], [x, y, z]) == \
|
| 291 |
+
convolution_subset([x, y, z], [u, v])
|
| 292 |
+
|
| 293 |
+
raises(TypeError, lambda: convolution_subset(x, z))
|
| 294 |
+
raises(TypeError, lambda: convolution_subset(Rational(7, 3), u))
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def test_covering_product():
|
| 298 |
+
assert covering_product([], []) == []
|
| 299 |
+
assert covering_product([], [Rational(1, 3)]) == []
|
| 300 |
+
assert covering_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
|
| 301 |
+
|
| 302 |
+
a = [1, Rational(5, 8), sqrt(7), 4 + 9*I]
|
| 303 |
+
b = [66, 81, 95, 49, 37, 89, 17]
|
| 304 |
+
c = [3 + I*2/3, 51 + 72*I, 7, Rational(7, 15), 91]
|
| 305 |
+
|
| 306 |
+
assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7),
|
| 307 |
+
130*sqrt(7) + 1303 + 2619*I, 37,
|
| 308 |
+
Rational(671, 4), 17 + 54*sqrt(7),
|
| 309 |
+
89*sqrt(7) + Rational(4661, 8) + 1287*I]
|
| 310 |
+
|
| 311 |
+
assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I,
|
| 312 |
+
1412 + I*190/3, Rational(42684, 5) + I*31202/3,
|
| 313 |
+
9484 + I*74/3, 22163 + I*27394/3,
|
| 314 |
+
10621 + I*34/3, Rational(90236, 15) + 1224*I]
|
| 315 |
+
|
| 316 |
+
assert covering_product(a, c) == covering_product(c, a)
|
| 317 |
+
assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I,
|
| 318 |
+
1412 + I*190/3, Rational(42684, 5) + I*31202/3,
|
| 319 |
+
111 + I*74/3, 6693 + I*27394/3,
|
| 320 |
+
429 + I*34/3, Rational(23351, 15) + 1224*I]
|
| 321 |
+
|
| 322 |
+
assert covering_product(a, c[:-1]) == [3 + I*2/3,
|
| 323 |
+
Rational(339, 4) + I*1409/12, 7 + 10*sqrt(7) + 2*sqrt(7)*I/3,
|
| 324 |
+
-403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*12658/15]
|
| 325 |
+
|
| 326 |
+
u, v, w, x, y, z = symbols('u v w x y z')
|
| 327 |
+
|
| 328 |
+
assert covering_product([u, v, w], [x, y]) == \
|
| 329 |
+
[u*x, u*y + v*x + v*y, w*x, w*y]
|
| 330 |
+
|
| 331 |
+
assert covering_product([u, v, w, x], [y, z]) == \
|
| 332 |
+
[u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z]
|
| 333 |
+
|
| 334 |
+
assert covering_product([u, v], [x, y, z]) == \
|
| 335 |
+
covering_product([x, y, z], [u, v])
|
| 336 |
+
|
| 337 |
+
raises(TypeError, lambda: covering_product(x, z))
|
| 338 |
+
raises(TypeError, lambda: covering_product(Rational(7, 3), u))
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def test_intersecting_product():
|
| 342 |
+
assert intersecting_product([], []) == []
|
| 343 |
+
assert intersecting_product([], [Rational(1, 3)]) == []
|
| 344 |
+
assert intersecting_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
|
| 345 |
+
|
| 346 |
+
a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I]
|
| 347 |
+
b = [67, 51, 65, 48, 36, 79, 27]
|
| 348 |
+
c = [3 + I*2/5, 5 + 9*I, 7, Rational(7, 19), 13]
|
| 349 |
+
|
| 350 |
+
assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I,
|
| 351 |
+
178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I,
|
| 352 |
+
192 + 336*I, 0, 0, 0, 0]
|
| 353 |
+
|
| 354 |
+
assert intersecting_product(b, c) == [Rational(128553, 19) + I*9521/5,
|
| 355 |
+
Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0]
|
| 356 |
+
|
| 357 |
+
assert intersecting_product(a, c) == intersecting_product(c, a)
|
| 358 |
+
assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*8622/5,
|
| 359 |
+
Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0]
|
| 360 |
+
|
| 361 |
+
assert intersecting_product(a, c[:-2]) == \
|
| 362 |
+
[Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*3021/40,
|
| 363 |
+
-43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0]
|
| 364 |
+
|
| 365 |
+
u, v, w, x, y, z = symbols('u v w x y z')
|
| 366 |
+
|
| 367 |
+
assert intersecting_product([u, v, w], [x, y]) == \
|
| 368 |
+
[u*x + u*y + v*x + w*x + w*y, v*y, 0, 0]
|
| 369 |
+
|
| 370 |
+
assert intersecting_product([u, v, w, x], [y, z]) == \
|
| 371 |
+
[u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0]
|
| 372 |
+
|
| 373 |
+
assert intersecting_product([u, v], [x, y, z]) == \
|
| 374 |
+
intersecting_product([x, y, z], [u, v])
|
| 375 |
+
|
| 376 |
+
raises(TypeError, lambda: intersecting_product(x, z))
|
| 377 |
+
raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def test_convolution_int():
|
| 381 |
+
assert convolution_int([1], [1]) == [1]
|
| 382 |
+
assert convolution_int([1, 1], [0]) == [0]
|
| 383 |
+
assert convolution_int([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
|
| 384 |
+
assert convolution_int([1], [5, 6, 7]) == [5, 6, 7]
|
| 385 |
+
assert convolution_int([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
|
| 386 |
+
assert convolution_int([10, -5, 1, 3], [-5, 6, 7]) == [-50, 85, 35, -44, 25, 21]
|
| 387 |
+
assert convolution_int([0, 1, 0, -1], [1, 0, -1, 0]) == [0, 1, 0, -2, 0, 1]
|
| 388 |
+
assert convolution_int(
|
| 389 |
+
[-341, -5, 1, 3, -71, -99, 43, 87],
|
| 390 |
+
[5, 6, 7, 12, 345, 21, -78, -7, -89]
|
| 391 |
+
) == [-1705, -2071, -2412, -4106, -118035, -9774, 25998, 2981, 5509,
|
| 392 |
+
-34317, 19228, 38870, 5485, 1724, -4436, -7743]
|
vllm/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import Rational
|
| 2 |
+
from sympy.functions.combinatorial.numbers import fibonacci
|
| 3 |
+
from sympy.core import S, symbols
|
| 4 |
+
from sympy.testing.pytest import raises
|
| 5 |
+
from sympy.discrete.recurrences import linrec
|
| 6 |
+
|
| 7 |
+
def test_linrec():
|
| 8 |
+
assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946
|
| 9 |
+
assert linrec(coeffs=[1, 2, 3, 4, 5], init=[1, 1, 0, 2], n=10) == 1040
|
| 10 |
+
assert linrec(coeffs=[0, 0, 11, 13], init=[23, 27], n=25) == 59628567384
|
| 11 |
+
assert linrec(coeffs=[0, 0, 1, 1, 2], init=[1, 5, 3], n=15) == 165
|
| 12 |
+
assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=70) == \
|
| 13 |
+
56889923441670659718376223533331214868804815612050381493741233489928913241
|
| 14 |
+
assert linrec(coeffs=[0]*55 + [1, 1, 2, 3], init=[0]*50 + [1, 2, 3], n=4000) == \
|
| 15 |
+
702633573874937994980598979769135096432444135301118916539
|
| 16 |
+
|
| 17 |
+
assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**4)
|
| 18 |
+
assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**5)
|
| 19 |
+
|
| 20 |
+
assert all(linrec(coeffs=[1, 1], init=[0, 1], n=n) == fibonacci(n)
|
| 21 |
+
for n in range(95, 115))
|
| 22 |
+
|
| 23 |
+
assert all(linrec(coeffs=[1, 1], init=[1, 1], n=n) == fibonacci(n + 1)
|
| 24 |
+
for n in range(595, 615))
|
| 25 |
+
|
| 26 |
+
a = [S.Half, Rational(3, 4), Rational(5, 6), 7, Rational(8, 9), Rational(3, 5)]
|
| 27 |
+
b = [1, 2, 8, Rational(5, 7), Rational(3, 7), Rational(2, 9), 6]
|
| 28 |
+
x, y, z = symbols('x y z')
|
| 29 |
+
|
| 30 |
+
assert linrec(coeffs=a[:5], init=b[:4], n=80) == \
|
| 31 |
+
Rational(1726244235456268979436592226626304376013002142588105090705187189,
|
| 32 |
+
1960143456748895967474334873705475211264)
|
| 33 |
+
|
| 34 |
+
assert linrec(coeffs=a[:4], init=b[:4], n=50) == \
|
| 35 |
+
Rational(368949940033050147080268092104304441, 504857282956046106624)
|
| 36 |
+
|
| 37 |
+
assert linrec(coeffs=a[3:], init=b[:3], n=35) == \
|
| 38 |
+
Rational(97409272177295731943657945116791049305244422833125109,
|
| 39 |
+
814315512679031689453125)
|
| 40 |
+
|
| 41 |
+
assert linrec(coeffs=[0]*60 + [Rational(2, 3), Rational(4, 5)], init=b, n=3000) == \
|
| 42 |
+
Rational(26777668739896791448594650497024, 48084516708184142230517578125)
|
| 43 |
+
|
| 44 |
+
raises(TypeError, lambda: linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4, 5], n=1))
|
| 45 |
+
raises(TypeError, lambda: linrec(coeffs=a[:4], init=b[:5], n=10000))
|
| 46 |
+
raises(ValueError, lambda: linrec(coeffs=a[:4], init=b[:4], n=-10000))
|
| 47 |
+
raises(TypeError, lambda: linrec(x, b, n=10000))
|
| 48 |
+
raises(TypeError, lambda: linrec(a, y, n=10000))
|
| 49 |
+
|
| 50 |
+
assert linrec(coeffs=[x, y, z], init=[1, 1, 1], n=4) == \
|
| 51 |
+
x**2 + x*y + x*z + y + z
|
| 52 |
+
assert linrec(coeffs=[1, 2, 1], init=[x, y, z], n=20) == \
|
| 53 |
+
269542*x + 664575*y + 578949*z
|
| 54 |
+
assert linrec(coeffs=[0, 3, 1, 2], init=[x, y], n=30) == \
|
| 55 |
+
58516436*x + 56372788*y
|
| 56 |
+
assert linrec(coeffs=[0]*50 + [1, 2, 3], init=[x, y, z], n=1000) == \
|
| 57 |
+
11477135884896*x + 25999077948732*y + 41975630244216*z
|
| 58 |
+
assert linrec(coeffs=[], init=[1, 1], n=20) == 0
|
| 59 |
+
assert linrec(coeffs=[x, y, z], init=[1, 2, 3], n=2) == 3
|
vllm/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 2 |
+
from sympy.core import S, Symbol, symbols, I, Rational
|
| 3 |
+
from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht,
|
| 4 |
+
mobius_transform, inverse_mobius_transform)
|
| 5 |
+
from sympy.testing.pytest import raises
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_fft_ifft():
|
| 9 |
+
assert all(tf(ls) == ls for tf in (fft, ifft)
|
| 10 |
+
for ls in ([], [Rational(5, 3)]))
|
| 11 |
+
|
| 12 |
+
ls = list(range(6))
|
| 13 |
+
fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I,
|
| 14 |
+
-4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3,
|
| 15 |
+
-4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I,
|
| 16 |
+
2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2]
|
| 17 |
+
|
| 18 |
+
assert fft(ls) == fls
|
| 19 |
+
assert ifft(fls) == ls + [S.Zero]*2
|
| 20 |
+
|
| 21 |
+
ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
|
| 22 |
+
ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4]
|
| 23 |
+
|
| 24 |
+
assert ifft(ls) == ifls
|
| 25 |
+
assert fft(ifls) == ls + [S.Zero]
|
| 26 |
+
|
| 27 |
+
x = Symbol('x', real=True)
|
| 28 |
+
raises(TypeError, lambda: fft(x))
|
| 29 |
+
raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3]))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_ntt_intt():
|
| 33 |
+
# prime moduli of the form (m*2**k + 1), sequence length
|
| 34 |
+
# should be a divisor of 2**k
|
| 35 |
+
p = 7*17*2**23 + 1
|
| 36 |
+
q = 2*500000003 + 1 # only for sequences of length 1 or 2
|
| 37 |
+
r = 2*3*5*7 # composite modulus
|
| 38 |
+
|
| 39 |
+
assert all(tf(ls, p) == ls for tf in (ntt, intt)
|
| 40 |
+
for ls in ([], [5]))
|
| 41 |
+
|
| 42 |
+
ls = list(range(6))
|
| 43 |
+
nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224,
|
| 44 |
+
259751156, 12232587]
|
| 45 |
+
|
| 46 |
+
assert ntt(ls, p) == nls
|
| 47 |
+
assert intt(nls, p) == ls + [0]*2
|
| 48 |
+
|
| 49 |
+
ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
|
| 50 |
+
x = Symbol('x', integer=True)
|
| 51 |
+
|
| 52 |
+
raises(TypeError, lambda: ntt(x, p))
|
| 53 |
+
raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p))
|
| 54 |
+
raises(ValueError, lambda: intt(ls, p))
|
| 55 |
+
raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p))
|
| 56 |
+
raises(ValueError, lambda: ntt([3, 5, 6], q))
|
| 57 |
+
raises(ValueError, lambda: ntt([4, 5, 7], r))
|
| 58 |
+
raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_fwht_ifwht():
|
| 62 |
+
assert all(tf(ls) == ls for tf in (fwht, ifwht) \
|
| 63 |
+
for ls in ([], [Rational(7, 4)]))
|
| 64 |
+
|
| 65 |
+
ls = [213, 321, 43235, 5325, 312, 53]
|
| 66 |
+
fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277]
|
| 67 |
+
|
| 68 |
+
assert fwht(ls) == fls
|
| 69 |
+
assert ifwht(fls) == ls + [S.Zero]*2
|
| 70 |
+
|
| 71 |
+
ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)]
|
| 72 |
+
ifls = [Rational(533, 672) + I*3/2, Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I,
|
| 73 |
+
Rational(155, 672) + I*3/2, Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I]
|
| 74 |
+
|
| 75 |
+
assert ifwht(ls) == ifls
|
| 76 |
+
assert fwht(ifls) == ls + [S.Zero]*3
|
| 77 |
+
|
| 78 |
+
x, y = symbols('x y')
|
| 79 |
+
|
| 80 |
+
raises(TypeError, lambda: fwht(x))
|
| 81 |
+
|
| 82 |
+
ls = [x, 2*x, 3*x**2, 4*x**3]
|
| 83 |
+
ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4),
|
| 84 |
+
-x**3 + 3*x**2/4 - x/4,
|
| 85 |
+
-x**3 - 3*x**2/4 + x*Rational(3, 4),
|
| 86 |
+
x**3 - 3*x**2/4 - x/4]
|
| 87 |
+
|
| 88 |
+
assert ifwht(ls) == ifls
|
| 89 |
+
assert fwht(ifls) == ls
|
| 90 |
+
|
| 91 |
+
ls = [x, y, x**2, y**2, x*y]
|
| 92 |
+
fls = [x**2 + x*y + x + y**2 + y,
|
| 93 |
+
x**2 + x*y + x - y**2 - y,
|
| 94 |
+
-x**2 + x*y + x - y**2 + y,
|
| 95 |
+
-x**2 + x*y + x + y**2 - y,
|
| 96 |
+
x**2 - x*y + x + y**2 + y,
|
| 97 |
+
x**2 - x*y + x - y**2 - y,
|
| 98 |
+
-x**2 - x*y + x - y**2 + y,
|
| 99 |
+
-x**2 - x*y + x + y**2 - y]
|
| 100 |
+
|
| 101 |
+
assert fwht(ls) == fls
|
| 102 |
+
assert ifwht(fls) == ls + [S.Zero]*3
|
| 103 |
+
|
| 104 |
+
ls = list(range(6))
|
| 105 |
+
|
| 106 |
+
assert fwht(ls) == [x*8 for x in ifwht(ls)]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_mobius_transform():
|
| 110 |
+
assert all(tf(ls, subset=subset) == ls
|
| 111 |
+
for ls in ([], [Rational(7, 4)]) for subset in (True, False)
|
| 112 |
+
for tf in (mobius_transform, inverse_mobius_transform))
|
| 113 |
+
|
| 114 |
+
w, x, y, z = symbols('w x y z')
|
| 115 |
+
|
| 116 |
+
assert mobius_transform([x, y]) == [x, x + y]
|
| 117 |
+
assert inverse_mobius_transform([x, x + y]) == [x, y]
|
| 118 |
+
assert mobius_transform([x, y], subset=False) == [x + y, y]
|
| 119 |
+
assert inverse_mobius_transform([x + y, y], subset=False) == [x, y]
|
| 120 |
+
|
| 121 |
+
assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z]
|
| 122 |
+
assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \
|
| 123 |
+
[w, x, y, z]
|
| 124 |
+
assert mobius_transform([w, x, y, z], subset=False) == \
|
| 125 |
+
[w + x + y + z, x + z, y + z, z]
|
| 126 |
+
assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \
|
| 127 |
+
[w, x, y, z]
|
| 128 |
+
|
| 129 |
+
ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I]
|
| 130 |
+
mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168),
|
| 131 |
+
Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I,
|
| 132 |
+
Rational(2153, 168) + 7*I]
|
| 133 |
+
|
| 134 |
+
assert mobius_transform(ls) == mls
|
| 135 |
+
assert inverse_mobius_transform(mls) == ls + [S.Zero]*3
|
| 136 |
+
|
| 137 |
+
mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0]
|
| 138 |
+
|
| 139 |
+
assert mobius_transform(ls, subset=False) == mls
|
| 140 |
+
assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3
|
| 141 |
+
|
| 142 |
+
ls = ls[:-1]
|
| 143 |
+
mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)]
|
| 144 |
+
|
| 145 |
+
assert mobius_transform(ls) == mls
|
| 146 |
+
assert inverse_mobius_transform(mls) == ls
|
| 147 |
+
|
| 148 |
+
mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9]
|
| 149 |
+
|
| 150 |
+
assert mobius_transform(ls, subset=False) == mls
|
| 151 |
+
assert inverse_mobius_transform(mls, subset=False) == ls
|
| 152 |
+
|
| 153 |
+
raises(TypeError, lambda: mobius_transform(x, subset=True))
|
| 154 |
+
raises(TypeError, lambda: inverse_mobius_transform(y, subset=False))
|
vllm/lib/python3.10/site-packages/sympy/galgebra.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
raise ImportError("""As of SymPy 1.0 the galgebra module is maintained separately at https://github.com/pygae/galgebra""")
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .core import dispatch
|
| 2 |
+
from .dispatcher import (Dispatcher, halt_ordering, restart_ordering,
|
| 3 |
+
MDNotImplementedError)
|
| 4 |
+
|
| 5 |
+
__version__ = '0.4.9'
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
'dispatch',
|
| 9 |
+
|
| 10 |
+
'Dispatcher', 'halt_ordering', 'restart_ordering', 'MDNotImplementedError',
|
| 11 |
+
]
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (409 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/conflict.cpython-310.pyc
ADDED
|
Binary file (3.77 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/core.cpython-310.pyc
ADDED
|
Binary file (2.36 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/dispatcher.cpython-310.pyc
ADDED
|
Binary file (13.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (3.6 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (178 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_conflict.cpython-310.pyc
ADDED
|
Binary file (2.47 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_core.cpython-310.pyc
ADDED
|
Binary file (7.37 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_core.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from sympy.multipledispatch import dispatch
|
| 5 |
+
from sympy.multipledispatch.conflict import AmbiguityWarning
|
| 6 |
+
from sympy.testing.pytest import raises, warns
|
| 7 |
+
from functools import partial
|
| 8 |
+
|
| 9 |
+
test_namespace: dict[str, Any] = {}
|
| 10 |
+
|
| 11 |
+
orig_dispatch = dispatch
|
| 12 |
+
dispatch = partial(dispatch, namespace=test_namespace)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_singledispatch():
|
| 16 |
+
@dispatch(int)
|
| 17 |
+
def f(x): # noqa:F811
|
| 18 |
+
return x + 1
|
| 19 |
+
|
| 20 |
+
@dispatch(int)
|
| 21 |
+
def g(x): # noqa:F811
|
| 22 |
+
return x + 2
|
| 23 |
+
|
| 24 |
+
@dispatch(float) # noqa:F811
|
| 25 |
+
def f(x): # noqa:F811
|
| 26 |
+
return x - 1
|
| 27 |
+
|
| 28 |
+
assert f(1) == 2
|
| 29 |
+
assert g(1) == 3
|
| 30 |
+
assert f(1.0) == 0
|
| 31 |
+
|
| 32 |
+
assert raises(NotImplementedError, lambda: f('hello'))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_multipledispatch():
|
| 36 |
+
@dispatch(int, int)
|
| 37 |
+
def f(x, y): # noqa:F811
|
| 38 |
+
return x + y
|
| 39 |
+
|
| 40 |
+
@dispatch(float, float) # noqa:F811
|
| 41 |
+
def f(x, y): # noqa:F811
|
| 42 |
+
return x - y
|
| 43 |
+
|
| 44 |
+
assert f(1, 2) == 3
|
| 45 |
+
assert f(1.0, 2.0) == -1.0
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class A: pass
|
| 49 |
+
class B: pass
|
| 50 |
+
class C(A): pass
|
| 51 |
+
class D(C): pass
|
| 52 |
+
class E(C): pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_inheritance():
|
| 56 |
+
@dispatch(A)
|
| 57 |
+
def f(x): # noqa:F811
|
| 58 |
+
return 'a'
|
| 59 |
+
|
| 60 |
+
@dispatch(B) # noqa:F811
|
| 61 |
+
def f(x): # noqa:F811
|
| 62 |
+
return 'b'
|
| 63 |
+
|
| 64 |
+
assert f(A()) == 'a'
|
| 65 |
+
assert f(B()) == 'b'
|
| 66 |
+
assert f(C()) == 'a'
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_inheritance_and_multiple_dispatch():
|
| 70 |
+
@dispatch(A, A)
|
| 71 |
+
def f(x, y): # noqa:F811
|
| 72 |
+
return type(x), type(y)
|
| 73 |
+
|
| 74 |
+
@dispatch(A, B) # noqa:F811
|
| 75 |
+
def f(x, y): # noqa:F811
|
| 76 |
+
return 0
|
| 77 |
+
|
| 78 |
+
assert f(A(), A()) == (A, A)
|
| 79 |
+
assert f(A(), C()) == (A, C)
|
| 80 |
+
assert f(A(), B()) == 0
|
| 81 |
+
assert f(C(), B()) == 0
|
| 82 |
+
assert raises(NotImplementedError, lambda: f(B(), B()))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_competing_solutions():
|
| 86 |
+
@dispatch(A)
|
| 87 |
+
def h(x): # noqa:F811
|
| 88 |
+
return 1
|
| 89 |
+
|
| 90 |
+
@dispatch(C) # noqa:F811
|
| 91 |
+
def h(x): # noqa:F811
|
| 92 |
+
return 2
|
| 93 |
+
|
| 94 |
+
assert h(D()) == 2
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_competing_multiple():
|
| 98 |
+
@dispatch(A, B)
|
| 99 |
+
def h(x, y): # noqa:F811
|
| 100 |
+
return 1
|
| 101 |
+
|
| 102 |
+
@dispatch(C, B) # noqa:F811
|
| 103 |
+
def h(x, y): # noqa:F811
|
| 104 |
+
return 2
|
| 105 |
+
|
| 106 |
+
assert h(D(), B()) == 2
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_competing_ambiguous():
|
| 110 |
+
test_namespace = {}
|
| 111 |
+
dispatch = partial(orig_dispatch, namespace=test_namespace)
|
| 112 |
+
|
| 113 |
+
@dispatch(A, C)
|
| 114 |
+
def f(x, y): # noqa:F811
|
| 115 |
+
return 2
|
| 116 |
+
|
| 117 |
+
with warns(AmbiguityWarning, test_stacklevel=False):
|
| 118 |
+
@dispatch(C, A) # noqa:F811
|
| 119 |
+
def f(x, y): # noqa:F811
|
| 120 |
+
return 2
|
| 121 |
+
|
| 122 |
+
assert f(A(), C()) == f(C(), A()) == 2
|
| 123 |
+
# assert raises(Warning, lambda : f(C(), C()))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_caching_correct_behavior():
|
| 127 |
+
@dispatch(A)
|
| 128 |
+
def f(x): # noqa:F811
|
| 129 |
+
return 1
|
| 130 |
+
|
| 131 |
+
assert f(C()) == 1
|
| 132 |
+
|
| 133 |
+
@dispatch(C)
|
| 134 |
+
def f(x): # noqa:F811
|
| 135 |
+
return 2
|
| 136 |
+
|
| 137 |
+
assert f(C()) == 2
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_union_types():
|
| 141 |
+
@dispatch((A, C))
|
| 142 |
+
def f(x): # noqa:F811
|
| 143 |
+
return 1
|
| 144 |
+
|
| 145 |
+
assert f(A()) == 1
|
| 146 |
+
assert f(C()) == 1
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_namespaces():
|
| 150 |
+
ns1 = {}
|
| 151 |
+
ns2 = {}
|
| 152 |
+
|
| 153 |
+
def foo(x):
|
| 154 |
+
return 1
|
| 155 |
+
foo1 = orig_dispatch(int, namespace=ns1)(foo)
|
| 156 |
+
|
| 157 |
+
def foo(x):
|
| 158 |
+
return 2
|
| 159 |
+
foo2 = orig_dispatch(int, namespace=ns2)(foo)
|
| 160 |
+
|
| 161 |
+
assert foo1(0) == 1
|
| 162 |
+
assert foo2(0) == 2
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
"""
|
| 166 |
+
Fails
|
| 167 |
+
def test_dispatch_on_dispatch():
|
| 168 |
+
@dispatch(A)
|
| 169 |
+
@dispatch(C)
|
| 170 |
+
def q(x): # noqa:F811
|
| 171 |
+
return 1
|
| 172 |
+
|
| 173 |
+
assert q(A()) == 1
|
| 174 |
+
assert q(C()) == 1
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def test_methods():
|
| 179 |
+
class Foo:
|
| 180 |
+
@dispatch(float)
|
| 181 |
+
def f(self, x): # noqa:F811
|
| 182 |
+
return x - 1
|
| 183 |
+
|
| 184 |
+
@dispatch(int) # noqa:F811
|
| 185 |
+
def f(self, x): # noqa:F811
|
| 186 |
+
return x + 1
|
| 187 |
+
|
| 188 |
+
@dispatch(int)
|
| 189 |
+
def g(self, x): # noqa:F811
|
| 190 |
+
return x + 3
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
foo = Foo()
|
| 194 |
+
assert foo.f(1) == 2
|
| 195 |
+
assert foo.f(1.0) == 0.0
|
| 196 |
+
assert foo.g(1) == 4
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def test_methods_multiple_dispatch():
|
| 200 |
+
class Foo:
|
| 201 |
+
@dispatch(A, A)
|
| 202 |
+
def f(x, y): # noqa:F811
|
| 203 |
+
return 1
|
| 204 |
+
|
| 205 |
+
@dispatch(A, C) # noqa:F811
|
| 206 |
+
def f(x, y): # noqa:F811
|
| 207 |
+
return 2
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
foo = Foo()
|
| 211 |
+
assert foo.f(A(), A()) == 1
|
| 212 |
+
assert foo.f(A(), C()) == 2
|
| 213 |
+
assert foo.f(C(), C()) == 2
|
vllm/lib/python3.10/site-packages/sympy/parsing/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Used for translating a string into a SymPy expression. """
|
| 2 |
+
__all__ = ['parse_expr']
|
| 3 |
+
|
| 4 |
+
from .sympy_parser import parse_expr
|
vllm/lib/python3.10/site-packages/sympy/parsing/ast_parser.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module implements the functionality to take any Python expression as a
|
| 3 |
+
string and fix all numbers and other things before evaluating it,
|
| 4 |
+
thus
|
| 5 |
+
|
| 6 |
+
1/2
|
| 7 |
+
|
| 8 |
+
returns
|
| 9 |
+
|
| 10 |
+
Integer(1)/Integer(2)
|
| 11 |
+
|
| 12 |
+
We use the ast module for this. It is well documented at docs.python.org.
|
| 13 |
+
|
| 14 |
+
Some tips to understand how this works: use dump() to get a nice
|
| 15 |
+
representation of any node. Then write a string of what you want to get,
|
| 16 |
+
e.g. "Integer(1)", parse it, dump it and you'll see that you need to do
|
| 17 |
+
"Call(Name('Integer', Load()), [node], [], None, None)". You do not need
|
| 18 |
+
to bother with lineno and col_offset, just call fix_missing_locations()
|
| 19 |
+
before returning the node.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from sympy.core.basic import Basic
|
| 23 |
+
from sympy.core.sympify import SympifyError
|
| 24 |
+
|
| 25 |
+
from ast import parse, NodeTransformer, Call, Name, Load, \
|
| 26 |
+
fix_missing_locations, Constant, Tuple
|
| 27 |
+
|
| 28 |
+
class Transform(NodeTransformer):
|
| 29 |
+
|
| 30 |
+
def __init__(self, local_dict, global_dict):
|
| 31 |
+
NodeTransformer.__init__(self)
|
| 32 |
+
self.local_dict = local_dict
|
| 33 |
+
self.global_dict = global_dict
|
| 34 |
+
|
| 35 |
+
def visit_Constant(self, node):
|
| 36 |
+
if isinstance(node.value, int):
|
| 37 |
+
return fix_missing_locations(Call(func=Name('Integer', Load()),
|
| 38 |
+
args=[node], keywords=[]))
|
| 39 |
+
elif isinstance(node.value, float):
|
| 40 |
+
return fix_missing_locations(Call(func=Name('Float', Load()),
|
| 41 |
+
args=[node], keywords=[]))
|
| 42 |
+
return node
|
| 43 |
+
|
| 44 |
+
def visit_Name(self, node):
|
| 45 |
+
if node.id in self.local_dict:
|
| 46 |
+
return node
|
| 47 |
+
elif node.id in self.global_dict:
|
| 48 |
+
name_obj = self.global_dict[node.id]
|
| 49 |
+
|
| 50 |
+
if isinstance(name_obj, (Basic, type)) or callable(name_obj):
|
| 51 |
+
return node
|
| 52 |
+
elif node.id in ['True', 'False']:
|
| 53 |
+
return node
|
| 54 |
+
return fix_missing_locations(Call(func=Name('Symbol', Load()),
|
| 55 |
+
args=[Constant(node.id)], keywords=[]))
|
| 56 |
+
|
| 57 |
+
def visit_Lambda(self, node):
|
| 58 |
+
args = [self.visit(arg) for arg in node.args.args]
|
| 59 |
+
body = self.visit(node.body)
|
| 60 |
+
n = Call(func=Name('Lambda', Load()),
|
| 61 |
+
args=[Tuple(args, Load()), body], keywords=[])
|
| 62 |
+
return fix_missing_locations(n)
|
| 63 |
+
|
| 64 |
+
def parse_expr(s, local_dict):
|
| 65 |
+
"""
|
| 66 |
+
Converts the string "s" to a SymPy expression, in local_dict.
|
| 67 |
+
|
| 68 |
+
It converts all numbers to Integers before feeding it to Python and
|
| 69 |
+
automatically creates Symbols.
|
| 70 |
+
"""
|
| 71 |
+
global_dict = {}
|
| 72 |
+
exec('from sympy import *', global_dict)
|
| 73 |
+
try:
|
| 74 |
+
a = parse(s.strip(), mode="eval")
|
| 75 |
+
except SyntaxError:
|
| 76 |
+
raise SympifyError("Cannot parse %s." % repr(s))
|
| 77 |
+
a = Transform(local_dict, global_dict).visit(a)
|
| 78 |
+
e = compile(a, "<string>", "eval")
|
| 79 |
+
return eval(e, global_dict, local_dict)
|
vllm/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/_build_latex_antlr.cpython-310.pyc
ADDED
|
Binary file (2.6 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/parsing/latex/__pycache__/errors.cpython-310.pyc
ADDED
|
Binary file (341 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
|
| 2 |
+
#
|
| 3 |
+
# Generated from ../LaTeX.g4, derived from latex2sympy
|
| 4 |
+
# latex2sympy is licensed under the MIT license
|
| 5 |
+
# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
|
| 6 |
+
#
|
| 7 |
+
# Generated with antlr4
|
| 8 |
+
# antlr4 is licensed under the BSD-3-Clause License
|
| 9 |
+
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
|
vllm/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/latex_parser.cpython-310.pyc
ADDED
|
Binary file (4.16 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/transformer.cpython-310.pyc
ADDED
|
Binary file (16.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/greek_symbols.lark
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Greek symbols
|
| 2 |
+
// TODO: Shouold we include the uppercase variants for the symbols where the uppercase variant doesn't have a separate meaning?
|
| 3 |
+
ALPHA: "\\alpha"
|
| 4 |
+
BETA: "\\beta"
|
| 5 |
+
GAMMA: "\\gamma"
|
| 6 |
+
DELTA: "\\delta" // TODO: Should this be included? Delta usually denotes other things.
|
| 7 |
+
EPSILON: "\\epsilon" | "\\varepsilon"
|
| 8 |
+
ZETA: "\\zeta"
|
| 9 |
+
ETA: "\\eta"
|
| 10 |
+
THETA: "\\theta" | "\\vartheta"
|
| 11 |
+
// TODO: Should I add iota to the list?
|
| 12 |
+
KAPPA: "\\kappa"
|
| 13 |
+
LAMBDA: "\\lambda" // TODO: What about the uppercase variant?
|
| 14 |
+
MU: "\\mu"
|
| 15 |
+
NU: "\\nu"
|
| 16 |
+
XI: "\\xi"
|
| 17 |
+
// TODO: Should there be a separate note for transforming \pi into sympy.pi?
|
| 18 |
+
RHO: "\\rho" | "\\varrho"
|
| 19 |
+
// TODO: What should we do about sigma?
|
| 20 |
+
TAU: "\\tau"
|
| 21 |
+
UPSILON: "\\upsilon"
|
| 22 |
+
PHI: "\\phi" | "\\varphi"
|
| 23 |
+
CHI: "\\chi"
|
| 24 |
+
PSI: "\\psi"
|
| 25 |
+
OMEGA: "\\omega"
|
| 26 |
+
|
| 27 |
+
GREEK_SYMBOL: ALPHA | BETA | GAMMA | DELTA | EPSILON | ZETA | ETA | THETA | KAPPA
|
| 28 |
+
| LAMBDA | MU | NU | XI | RHO | TAU | UPSILON | PHI | CHI | PSI | OMEGA
|
vllm/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/latex.lark
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
%ignore /[ \t\n\r]+/
|
| 2 |
+
|
| 3 |
+
%ignore "\\," | "\\thinspace" | "\\:" | "\\medspace" | "\\;" | "\\thickspace"
|
| 4 |
+
%ignore "\\quad" | "\\qquad"
|
| 5 |
+
%ignore "\\!" | "\\negthinspace" | "\\negmedspace" | "\\negthickspace"
|
| 6 |
+
%ignore "\\vrule" | "\\vcenter" | "\\vbox" | "\\vskip" | "\\vspace" | "\\hfill"
|
| 7 |
+
%ignore "\\*" | "\\-" | "\\." | "\\/" | "\\\\" | "\\(" | "\\="
|
| 8 |
+
|
| 9 |
+
%ignore "\\left" | "\\right"
|
| 10 |
+
%ignore "\\limits" | "\\nolimits"
|
| 11 |
+
%ignore "\\displaystyle"
|
| 12 |
+
|
| 13 |
+
///////////////////// tokens ///////////////////////
|
| 14 |
+
|
| 15 |
+
// basic binary operators
|
| 16 |
+
ADD: "+"
|
| 17 |
+
SUB: "-"
|
| 18 |
+
MUL: "*"
|
| 19 |
+
DIV: "/"
|
| 20 |
+
|
| 21 |
+
// tokens with distinct left and right symbols
|
| 22 |
+
L_BRACE: "{"
|
| 23 |
+
R_BRACE: "}"
|
| 24 |
+
L_BRACE_LITERAL: "\\{"
|
| 25 |
+
R_BRACE_LITERAL: "\\}"
|
| 26 |
+
L_BRACKET: "["
|
| 27 |
+
R_BRACKET: "]"
|
| 28 |
+
L_CEIL: "\\lceil"
|
| 29 |
+
R_CEIL: "\\rceil"
|
| 30 |
+
L_FLOOR: "\\lfloor"
|
| 31 |
+
R_FLOOR: "\\rfloor"
|
| 32 |
+
L_PAREN: "("
|
| 33 |
+
R_PAREN: ")"
|
| 34 |
+
|
| 35 |
+
// limit, integral, sum, and product symbols
|
| 36 |
+
FUNC_LIM: "\\lim"
|
| 37 |
+
LIM_APPROACH_SYM: "\\to" | "\\rightarrow" | "\\Rightarrow" | "\\longrightarrow" | "\\Longrightarrow"
|
| 38 |
+
FUNC_INT: "\\int" | "\\intop"
|
| 39 |
+
FUNC_SUM: "\\sum"
|
| 40 |
+
FUNC_PROD: "\\prod"
|
| 41 |
+
|
| 42 |
+
// common functions
|
| 43 |
+
FUNC_EXP: "\\exp"
|
| 44 |
+
FUNC_LOG: "\\log"
|
| 45 |
+
FUNC_LN: "\\ln"
|
| 46 |
+
FUNC_LG: "\\lg"
|
| 47 |
+
FUNC_MIN: "\\min"
|
| 48 |
+
FUNC_MAX: "\\max"
|
| 49 |
+
|
| 50 |
+
// trigonometric functions
|
| 51 |
+
FUNC_SIN: "\\sin"
|
| 52 |
+
FUNC_COS: "\\cos"
|
| 53 |
+
FUNC_TAN: "\\tan"
|
| 54 |
+
FUNC_CSC: "\\csc"
|
| 55 |
+
FUNC_SEC: "\\sec"
|
| 56 |
+
FUNC_COT: "\\cot"
|
| 57 |
+
|
| 58 |
+
// inverse trigonometric functions
|
| 59 |
+
FUNC_ARCSIN: "\\arcsin"
|
| 60 |
+
FUNC_ARCCOS: "\\arccos"
|
| 61 |
+
FUNC_ARCTAN: "\\arctan"
|
| 62 |
+
FUNC_ARCCSC: "\\arccsc"
|
| 63 |
+
FUNC_ARCSEC: "\\arcsec"
|
| 64 |
+
FUNC_ARCCOT: "\\arccot"
|
| 65 |
+
|
| 66 |
+
// hyperbolic trigonometric functions
|
| 67 |
+
FUNC_SINH: "\\sinh"
|
| 68 |
+
FUNC_COSH: "\\cosh"
|
| 69 |
+
FUNC_TANH: "\\tanh"
|
| 70 |
+
FUNC_ARSINH: "\\arsinh"
|
| 71 |
+
FUNC_ARCOSH: "\\arcosh"
|
| 72 |
+
FUNC_ARTANH: "\\artanh"
|
| 73 |
+
|
| 74 |
+
FUNC_SQRT: "\\sqrt"
|
| 75 |
+
|
| 76 |
+
// miscellaneous symbols
|
| 77 |
+
CMD_TIMES: "\\times"
|
| 78 |
+
CMD_CDOT: "\\cdot"
|
| 79 |
+
CMD_DIV: "\\div"
|
| 80 |
+
CMD_FRAC: "\\frac" | "\\dfrac" | "\\tfrac" | "\\nicefrac"
|
| 81 |
+
CMD_BINOM: "\\binom" | "\\dbinom" | "\\tbinom"
|
| 82 |
+
CMD_OVERLINE: "\\overline"
|
| 83 |
+
CMD_LANGLE: "\\langle"
|
| 84 |
+
CMD_RANGLE: "\\rangle"
|
| 85 |
+
|
| 86 |
+
CMD_MATHIT: "\\mathit"
|
| 87 |
+
|
| 88 |
+
CMD_INFTY: "\\infty"
|
| 89 |
+
|
| 90 |
+
BANG: "!"
|
| 91 |
+
BAR: "|"
|
| 92 |
+
CARET: "^"
|
| 93 |
+
COLON: ":"
|
| 94 |
+
UNDERSCORE: "_"
|
| 95 |
+
|
| 96 |
+
// relational symbols
|
| 97 |
+
EQUAL: "="
|
| 98 |
+
NOT_EQUAL: "\\neq" | "\\ne"
|
| 99 |
+
LT: "<"
|
| 100 |
+
LTE: "\\leq" | "\\le" | "\\leqslant"
|
| 101 |
+
GT: ">"
|
| 102 |
+
GTE: "\\geq" | "\\ge" | "\\geqslant"
|
| 103 |
+
|
| 104 |
+
DIV_SYMBOL: CMD_DIV | DIV
|
| 105 |
+
MUL_SYMBOL: MUL | CMD_TIMES | CMD_CDOT
|
| 106 |
+
|
| 107 |
+
%import .greek_symbols.GREEK_SYMBOL
|
| 108 |
+
|
| 109 |
+
UPRIGHT_DIFFERENTIAL_SYMBOL: "\\text{d}" | "\\mathrm{d}"
|
| 110 |
+
DIFFERENTIAL_SYMBOL: "d" | UPRIGHT_DIFFERENTIAL_SYMBOL
|
| 111 |
+
|
| 112 |
+
// disallow "d" as a variable name because we want to parse "d" as a differential symbol.
|
| 113 |
+
SYMBOL: /[a-zA-Z]/
|
| 114 |
+
BASIC_SUBSCRIPTED_SYMBOL: /([a-zA-Z])_(([A-Za-z0-9]|[a-zA-Z]+)|\{([A-Za-z0-9]|[a-zA-Z]+)\})/
|
| 115 |
+
SYMBOL_WITH_GREEK_SUBSCRIPT: /([a-zA-Z])_/ GREEK_SYMBOL | /([a-zA-Z])_/ L_BRACE GREEK_SYMBOL R_BRACE
|
| 116 |
+
// best to define the variant with braces like that instead of shoving it all into one case like in
|
| 117 |
+
// /([a-zA-Z])_/ L_BRACE? GREEK_SYMBOL R_BRACE? because then we can easily error out on input like
|
| 118 |
+
// r"h_{\theta"
|
| 119 |
+
GREEK_SUBSCRIPTED_SYMBOL: GREEK_SYMBOL /_(([A-Za-z0-9]|[a-zA-Z]+)|\{([A-Za-z0-9]|[a-zA-Z]+)\})/
|
| 120 |
+
|
| 121 |
+
%import common.DIGIT -> DIGIT
|
| 122 |
+
|
| 123 |
+
//////////////////// grammar //////////////////////
|
| 124 |
+
|
| 125 |
+
latex_string: _relation | _expression
|
| 126 |
+
|
| 127 |
+
_one_letter_symbol: SYMBOL
|
| 128 |
+
| BASIC_SUBSCRIPTED_SYMBOL
|
| 129 |
+
| SYMBOL_WITH_GREEK_SUBSCRIPT
|
| 130 |
+
| GREEK_SUBSCRIPTED_SYMBOL
|
| 131 |
+
| GREEK_SYMBOL
|
| 132 |
+
multi_letter_symbol: CMD_MATHIT L_BRACE /[a-zA-Z]+(\s+[a-zA-Z]+)*/ R_BRACE
|
| 133 |
+
number: /\d+(\.\d*)?/
|
| 134 |
+
|
| 135 |
+
_atomic_expr: _one_letter_symbol
|
| 136 |
+
| multi_letter_symbol
|
| 137 |
+
| number
|
| 138 |
+
| CMD_INFTY
|
| 139 |
+
|
| 140 |
+
group_round_parentheses: L_PAREN _expression R_PAREN
|
| 141 |
+
group_square_brackets: L_BRACKET _expression R_BRACKET
|
| 142 |
+
group_curly_parentheses: L_BRACE _expression R_BRACE
|
| 143 |
+
|
| 144 |
+
_relation: eq | ne | lt | lte | gt | gte
|
| 145 |
+
|
| 146 |
+
eq: _expression EQUAL _expression
|
| 147 |
+
ne: _expression NOT_EQUAL _expression
|
| 148 |
+
lt: _expression LT _expression
|
| 149 |
+
lte: _expression LTE _expression
|
| 150 |
+
gt: _expression GT _expression
|
| 151 |
+
gte: _expression GTE _expression
|
| 152 |
+
|
| 153 |
+
_expression_core: _atomic_expr | group_curly_parentheses
|
| 154 |
+
|
| 155 |
+
add: _expression ADD _expression_mul
|
| 156 |
+
sub: _expression SUB _expression_mul
|
| 157 |
+
| SUB _expression_mul
|
| 158 |
+
mul: _expression_mul MUL_SYMBOL _expression_power
|
| 159 |
+
div: _expression_mul DIV_SYMBOL _expression_power
|
| 160 |
+
|
| 161 |
+
adjacent_expressions: (_one_letter_symbol | number) _expression_mul
|
| 162 |
+
| group_round_parentheses (group_round_parentheses | _one_letter_symbol)
|
| 163 |
+
| _function _function
|
| 164 |
+
| fraction _expression
|
| 165 |
+
|
| 166 |
+
_expression_func: _expression_core
|
| 167 |
+
| group_round_parentheses
|
| 168 |
+
| fraction
|
| 169 |
+
| binomial
|
| 170 |
+
| _function
|
| 171 |
+
|
| 172 |
+
_expression_power: _expression_func | superscript
|
| 173 |
+
|
| 174 |
+
_expression_mul: _expression_power
|
| 175 |
+
| mul | div | adjacent_expressions
|
| 176 |
+
| _integral// | derivative
|
| 177 |
+
| summation | product
|
| 178 |
+
| limit
|
| 179 |
+
|
| 180 |
+
_expression: _expression_mul | add | sub
|
| 181 |
+
|
| 182 |
+
_limit_dir: "+" | "-" | L_BRACE ("+" | "-") R_BRACE
|
| 183 |
+
|
| 184 |
+
limit_dir_expr: _expression CARET _limit_dir
|
| 185 |
+
|
| 186 |
+
group_curly_parentheses_lim: L_BRACE _expression LIM_APPROACH_SYM (limit_dir_expr | _expression) R_BRACE
|
| 187 |
+
|
| 188 |
+
limit: FUNC_LIM UNDERSCORE group_curly_parentheses_lim _expression
|
| 189 |
+
|
| 190 |
+
differential: DIFFERENTIAL_SYMBOL _one_letter_symbol
|
| 191 |
+
|
| 192 |
+
//_derivative_operator: CMD_FRAC L_BRACE DIFFERENTIAL_SYMBOL R_BRACE L_BRACE differential R_BRACE
|
| 193 |
+
|
| 194 |
+
//derivative: _derivative_operator _expression
|
| 195 |
+
|
| 196 |
+
_integral: normal_integral | integral_with_special_fraction
|
| 197 |
+
|
| 198 |
+
normal_integral: FUNC_INT _expression DIFFERENTIAL_SYMBOL _one_letter_symbol
|
| 199 |
+
| FUNC_INT (CARET _expression_core UNDERSCORE _expression_core)? _expression? DIFFERENTIAL_SYMBOL _one_letter_symbol
|
| 200 |
+
| FUNC_INT (UNDERSCORE _expression_core CARET _expression_core)? _expression? DIFFERENTIAL_SYMBOL _one_letter_symbol
|
| 201 |
+
|
| 202 |
+
group_curly_parentheses_int: L_BRACE _expression? differential R_BRACE
|
| 203 |
+
|
| 204 |
+
special_fraction: CMD_FRAC group_curly_parentheses_int group_curly_parentheses
|
| 205 |
+
|
| 206 |
+
integral_with_special_fraction: FUNC_INT special_fraction
|
| 207 |
+
| FUNC_INT (CARET _expression_core UNDERSCORE _expression_core)? special_fraction
|
| 208 |
+
| FUNC_INT (UNDERSCORE _expression_core CARET _expression_core)? special_fraction
|
| 209 |
+
|
| 210 |
+
group_curly_parentheses_special: UNDERSCORE L_BRACE _atomic_expr EQUAL _atomic_expr R_BRACE CARET _expression_core
|
| 211 |
+
| CARET _expression_core UNDERSCORE L_BRACE _atomic_expr EQUAL _atomic_expr R_BRACE
|
| 212 |
+
|
| 213 |
+
summation: FUNC_SUM group_curly_parentheses_special _expression
|
| 214 |
+
| FUNC_SUM group_curly_parentheses_special _expression
|
| 215 |
+
|
| 216 |
+
product: FUNC_PROD group_curly_parentheses_special _expression
|
| 217 |
+
| FUNC_PROD group_curly_parentheses_special _expression
|
| 218 |
+
|
| 219 |
+
superscript: _expression_func CARET _expression_power
|
| 220 |
+
|
| 221 |
+
fraction: _basic_fraction
|
| 222 |
+
| _simple_fraction
|
| 223 |
+
| _general_fraction
|
| 224 |
+
|
| 225 |
+
_basic_fraction: CMD_FRAC DIGIT (DIGIT | SYMBOL | GREEK_SYMBOL)
|
| 226 |
+
|
| 227 |
+
_simple_fraction: CMD_FRAC DIGIT group_curly_parentheses
|
| 228 |
+
| CMD_FRAC group_curly_parentheses (DIGIT | SYMBOL | GREEK_SYMBOL)
|
| 229 |
+
|
| 230 |
+
_general_fraction: CMD_FRAC group_curly_parentheses group_curly_parentheses
|
| 231 |
+
|
| 232 |
+
binomial: _basic_binomial
|
| 233 |
+
| _simple_binomial
|
| 234 |
+
| _general_binomial
|
| 235 |
+
|
| 236 |
+
_basic_binomial: CMD_BINOM DIGIT (DIGIT | SYMBOL | GREEK_SYMBOL)
|
| 237 |
+
|
| 238 |
+
_simple_binomial: CMD_BINOM DIGIT group_curly_parentheses
|
| 239 |
+
| CMD_BINOM group_curly_parentheses (DIGIT | SYMBOL | GREEK_SYMBOL)
|
| 240 |
+
|
| 241 |
+
_general_binomial: CMD_BINOM group_curly_parentheses group_curly_parentheses
|
| 242 |
+
|
| 243 |
+
list_of_expressions: _expression ("," _expression)*
|
| 244 |
+
|
| 245 |
+
function_applied: _one_letter_symbol L_PAREN list_of_expressions R_PAREN
|
| 246 |
+
|
| 247 |
+
min: FUNC_MIN L_PAREN list_of_expressions R_PAREN
|
| 248 |
+
|
| 249 |
+
max: FUNC_MAX L_PAREN list_of_expressions R_PAREN
|
| 250 |
+
|
| 251 |
+
bra: CMD_LANGLE _expression BAR
|
| 252 |
+
|
| 253 |
+
ket: BAR _expression CMD_RANGLE
|
| 254 |
+
|
| 255 |
+
inner_product: CMD_LANGLE _expression BAR _expression CMD_RANGLE
|
| 256 |
+
|
| 257 |
+
_function: function_applied
|
| 258 |
+
| abs | floor | ceil
|
| 259 |
+
| _trigonometric_function | _inverse_trigonometric_function
|
| 260 |
+
| _trigonometric_function_power
|
| 261 |
+
| _hyperbolic_trigonometric_function | _inverse_hyperbolic_trigonometric_function
|
| 262 |
+
| exponential
|
| 263 |
+
| log
|
| 264 |
+
| square_root
|
| 265 |
+
| factorial
|
| 266 |
+
| conjugate
|
| 267 |
+
| max | min
|
| 268 |
+
| bra | ket | inner_product
|
| 269 |
+
|
| 270 |
+
exponential: FUNC_EXP _expression
|
| 271 |
+
|
| 272 |
+
log: FUNC_LOG _expression
|
| 273 |
+
| FUNC_LN _expression
|
| 274 |
+
| FUNC_LG _expression
|
| 275 |
+
| FUNC_LOG UNDERSCORE (DIGIT | _one_letter_symbol) _expression
|
| 276 |
+
| FUNC_LOG UNDERSCORE group_curly_parentheses _expression
|
| 277 |
+
|
| 278 |
+
square_root: FUNC_SQRT group_curly_parentheses
|
| 279 |
+
| FUNC_SQRT group_square_brackets group_curly_parentheses
|
| 280 |
+
|
| 281 |
+
factorial: _expression BANG
|
| 282 |
+
|
| 283 |
+
conjugate: CMD_OVERLINE group_curly_parentheses
|
| 284 |
+
| CMD_OVERLINE DIGIT
|
| 285 |
+
|
| 286 |
+
_trigonometric_function: sin | cos | tan | csc | sec | cot
|
| 287 |
+
|
| 288 |
+
sin: FUNC_SIN _expression
|
| 289 |
+
cos: FUNC_COS _expression
|
| 290 |
+
tan: FUNC_TAN _expression
|
| 291 |
+
csc: FUNC_CSC _expression
|
| 292 |
+
sec: FUNC_SEC _expression
|
| 293 |
+
cot: FUNC_COT _expression
|
| 294 |
+
|
| 295 |
+
_trigonometric_function_power: sin_power | cos_power | tan_power | csc_power | sec_power | cot_power
|
| 296 |
+
|
| 297 |
+
sin_power: FUNC_SIN CARET _expression_core _expression
|
| 298 |
+
cos_power: FUNC_COS CARET _expression_core _expression
|
| 299 |
+
tan_power: FUNC_TAN CARET _expression_core _expression
|
| 300 |
+
csc_power: FUNC_CSC CARET _expression_core _expression
|
| 301 |
+
sec_power: FUNC_SEC CARET _expression_core _expression
|
| 302 |
+
cot_power: FUNC_COT CARET _expression_core _expression
|
| 303 |
+
|
| 304 |
+
_hyperbolic_trigonometric_function: sinh | cosh | tanh
|
| 305 |
+
|
| 306 |
+
sinh: FUNC_SINH _expression
|
| 307 |
+
cosh: FUNC_COSH _expression
|
| 308 |
+
tanh: FUNC_TANH _expression
|
| 309 |
+
|
| 310 |
+
_inverse_trigonometric_function: arcsin | arccos | arctan | arccsc | arcsec | arccot
|
| 311 |
+
|
| 312 |
+
arcsin: FUNC_ARCSIN _expression
|
| 313 |
+
arccos: FUNC_ARCCOS _expression
|
| 314 |
+
arctan: FUNC_ARCTAN _expression
|
| 315 |
+
arccsc: FUNC_ARCCSC _expression
|
| 316 |
+
arcsec: FUNC_ARCSEC _expression
|
| 317 |
+
arccot: FUNC_ARCCOT _expression
|
| 318 |
+
|
| 319 |
+
_inverse_hyperbolic_trigonometric_function: asinh | acosh | atanh
|
| 320 |
+
|
| 321 |
+
asinh: FUNC_ARSINH _expression
|
| 322 |
+
acosh: FUNC_ARCOSH _expression
|
| 323 |
+
atanh: FUNC_ARTANH _expression
|
| 324 |
+
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import re
|
| 3 |
+
import typing
|
| 4 |
+
from itertools import product
|
| 5 |
+
from typing import Any, Callable
|
| 6 |
+
|
| 7 |
+
import sympy
|
| 8 |
+
from sympy import Mul, Add, Pow, Rational, log, exp, sqrt, cos, sin, tan, asin, acos, acot, asec, acsc, sinh, cosh, tanh, asinh, \
|
| 9 |
+
acosh, atanh, acoth, asech, acsch, expand, im, flatten, polylog, cancel, expand_trig, sign, simplify, \
|
| 10 |
+
UnevaluatedExpr, S, atan, atan2, Mod, Max, Min, rf, Ei, Si, Ci, airyai, airyaiprime, airybi, primepi, prime, \
|
| 11 |
+
isprime, cot, sec, csc, csch, sech, coth, Function, I, pi, Tuple, GreaterThan, StrictGreaterThan, StrictLessThan, \
|
| 12 |
+
LessThan, Equality, Or, And, Lambda, Integer, Dummy, symbols
|
| 13 |
+
from sympy.core.sympify import sympify, _sympify
|
| 14 |
+
from sympy.functions.special.bessel import airybiprime
|
| 15 |
+
from sympy.functions.special.error_functions import li
|
| 16 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def mathematica(s, additional_translations=None):
|
| 20 |
+
sympy_deprecation_warning(
|
| 21 |
+
"""The ``mathematica`` function for the Mathematica parser is now
|
| 22 |
+
deprecated. Use ``parse_mathematica`` instead.
|
| 23 |
+
The parameter ``additional_translation`` can be replaced by SymPy's
|
| 24 |
+
.replace( ) or .subs( ) methods on the output expression instead.""",
|
| 25 |
+
deprecated_since_version="1.11",
|
| 26 |
+
active_deprecations_target="mathematica-parser-new",
|
| 27 |
+
)
|
| 28 |
+
parser = MathematicaParser(additional_translations)
|
| 29 |
+
return sympify(parser._parse_old(s))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def parse_mathematica(s):
|
| 33 |
+
"""
|
| 34 |
+
Translate a string containing a Wolfram Mathematica expression to a SymPy
|
| 35 |
+
expression.
|
| 36 |
+
|
| 37 |
+
If the translator is unable to find a suitable SymPy expression, the
|
| 38 |
+
``FullForm`` of the Mathematica expression will be output, using SymPy
|
| 39 |
+
``Function`` objects as nodes of the syntax tree.
|
| 40 |
+
|
| 41 |
+
Examples
|
| 42 |
+
========
|
| 43 |
+
|
| 44 |
+
>>> from sympy.parsing.mathematica import parse_mathematica
|
| 45 |
+
>>> parse_mathematica("Sin[x]^2 Tan[y]")
|
| 46 |
+
sin(x)**2*tan(y)
|
| 47 |
+
>>> e = parse_mathematica("F[7,5,3]")
|
| 48 |
+
>>> e
|
| 49 |
+
F(7, 5, 3)
|
| 50 |
+
>>> from sympy import Function, Max, Min
|
| 51 |
+
>>> e.replace(Function("F"), lambda *x: Max(*x)*Min(*x))
|
| 52 |
+
21
|
| 53 |
+
|
| 54 |
+
Both standard input form and Mathematica full form are supported:
|
| 55 |
+
|
| 56 |
+
>>> parse_mathematica("x*(a + b)")
|
| 57 |
+
x*(a + b)
|
| 58 |
+
>>> parse_mathematica("Times[x, Plus[a, b]]")
|
| 59 |
+
x*(a + b)
|
| 60 |
+
|
| 61 |
+
To get a matrix from Wolfram's code:
|
| 62 |
+
|
| 63 |
+
>>> m = parse_mathematica("{{a, b}, {c, d}}")
|
| 64 |
+
>>> m
|
| 65 |
+
((a, b), (c, d))
|
| 66 |
+
>>> from sympy import Matrix
|
| 67 |
+
>>> Matrix(m)
|
| 68 |
+
Matrix([
|
| 69 |
+
[a, b],
|
| 70 |
+
[c, d]])
|
| 71 |
+
|
| 72 |
+
If the translation into equivalent SymPy expressions fails, an SymPy
|
| 73 |
+
expression equivalent to Wolfram Mathematica's "FullForm" will be created:
|
| 74 |
+
|
| 75 |
+
>>> parse_mathematica("x_.")
|
| 76 |
+
Optional(Pattern(x, Blank()))
|
| 77 |
+
>>> parse_mathematica("Plus @@ {x, y, z}")
|
| 78 |
+
Apply(Plus, (x, y, z))
|
| 79 |
+
>>> parse_mathematica("f[x_, 3] := x^3 /; x > 0")
|
| 80 |
+
SetDelayed(f(Pattern(x, Blank()), 3), Condition(x**3, x > 0))
|
| 81 |
+
"""
|
| 82 |
+
parser = MathematicaParser()
|
| 83 |
+
return parser.parse(s)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _parse_Function(*args):
|
| 87 |
+
if len(args) == 1:
|
| 88 |
+
arg = args[0]
|
| 89 |
+
Slot = Function("Slot")
|
| 90 |
+
slots = arg.atoms(Slot)
|
| 91 |
+
numbers = [a.args[0] for a in slots]
|
| 92 |
+
number_of_arguments = max(numbers)
|
| 93 |
+
if isinstance(number_of_arguments, Integer):
|
| 94 |
+
variables = symbols(f"dummy0:{number_of_arguments}", cls=Dummy)
|
| 95 |
+
return Lambda(variables, arg.xreplace({Slot(i+1): v for i, v in enumerate(variables)}))
|
| 96 |
+
return Lambda((), arg)
|
| 97 |
+
elif len(args) == 2:
|
| 98 |
+
variables = args[0]
|
| 99 |
+
body = args[1]
|
| 100 |
+
return Lambda(variables, body)
|
| 101 |
+
else:
|
| 102 |
+
raise SyntaxError("Function node expects 1 or 2 arguments")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _deco(cls):
|
| 106 |
+
cls._initialize_class()
|
| 107 |
+
return cls
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@_deco
|
| 111 |
+
class MathematicaParser:
|
| 112 |
+
"""
|
| 113 |
+
An instance of this class converts a string of a Wolfram Mathematica
|
| 114 |
+
expression to a SymPy expression.
|
| 115 |
+
|
| 116 |
+
The main parser acts internally in three stages:
|
| 117 |
+
|
| 118 |
+
1. tokenizer: tokenizes the Mathematica expression and adds the missing *
|
| 119 |
+
operators. Handled by ``_from_mathematica_to_tokens(...)``
|
| 120 |
+
2. full form list: sort the list of strings output by the tokenizer into a
|
| 121 |
+
syntax tree of nested lists and strings, equivalent to Mathematica's
|
| 122 |
+
``FullForm`` expression output. This is handled by the function
|
| 123 |
+
``_from_tokens_to_fullformlist(...)``.
|
| 124 |
+
3. SymPy expression: the syntax tree expressed as full form list is visited
|
| 125 |
+
and the nodes with equivalent classes in SymPy are replaced. Unknown
|
| 126 |
+
syntax tree nodes are cast to SymPy ``Function`` objects. This is
|
| 127 |
+
handled by ``_from_fullformlist_to_sympy(...)``.
|
| 128 |
+
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
# left: Mathematica, right: SymPy
|
| 132 |
+
CORRESPONDENCES = {
|
| 133 |
+
'Sqrt[x]': 'sqrt(x)',
|
| 134 |
+
'Rational[x,y]': 'Rational(x,y)',
|
| 135 |
+
'Exp[x]': 'exp(x)',
|
| 136 |
+
'Log[x]': 'log(x)',
|
| 137 |
+
'Log[x,y]': 'log(y,x)',
|
| 138 |
+
'Log2[x]': 'log(x,2)',
|
| 139 |
+
'Log10[x]': 'log(x,10)',
|
| 140 |
+
'Mod[x,y]': 'Mod(x,y)',
|
| 141 |
+
'Max[*x]': 'Max(*x)',
|
| 142 |
+
'Min[*x]': 'Min(*x)',
|
| 143 |
+
'Pochhammer[x,y]':'rf(x,y)',
|
| 144 |
+
'ArcTan[x,y]':'atan2(y,x)',
|
| 145 |
+
'ExpIntegralEi[x]': 'Ei(x)',
|
| 146 |
+
'SinIntegral[x]': 'Si(x)',
|
| 147 |
+
'CosIntegral[x]': 'Ci(x)',
|
| 148 |
+
'AiryAi[x]': 'airyai(x)',
|
| 149 |
+
'AiryAiPrime[x]': 'airyaiprime(x)',
|
| 150 |
+
'AiryBi[x]' :'airybi(x)',
|
| 151 |
+
'AiryBiPrime[x]' :'airybiprime(x)',
|
| 152 |
+
'LogIntegral[x]':' li(x)',
|
| 153 |
+
'PrimePi[x]': 'primepi(x)',
|
| 154 |
+
'Prime[x]': 'prime(x)',
|
| 155 |
+
'PrimeQ[x]': 'isprime(x)'
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
# trigonometric, e.t.c.
|
| 159 |
+
for arc, tri, h in product(('', 'Arc'), (
|
| 160 |
+
'Sin', 'Cos', 'Tan', 'Cot', 'Sec', 'Csc'), ('', 'h')):
|
| 161 |
+
fm = arc + tri + h + '[x]'
|
| 162 |
+
if arc: # arc func
|
| 163 |
+
fs = 'a' + tri.lower() + h + '(x)'
|
| 164 |
+
else: # non-arc func
|
| 165 |
+
fs = tri.lower() + h + '(x)'
|
| 166 |
+
CORRESPONDENCES.update({fm: fs})
|
| 167 |
+
|
| 168 |
+
REPLACEMENTS = {
|
| 169 |
+
' ': '',
|
| 170 |
+
'^': '**',
|
| 171 |
+
'{': '[',
|
| 172 |
+
'}': ']',
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
RULES = {
|
| 176 |
+
# a single whitespace to '*'
|
| 177 |
+
'whitespace': (
|
| 178 |
+
re.compile(r'''
|
| 179 |
+
(?:(?<=[a-zA-Z\d])|(?<=\d\.)) # a letter or a number
|
| 180 |
+
\s+ # any number of whitespaces
|
| 181 |
+
(?:(?=[a-zA-Z\d])|(?=\.\d)) # a letter or a number
|
| 182 |
+
''', re.VERBOSE),
|
| 183 |
+
'*'),
|
| 184 |
+
|
| 185 |
+
# add omitted '*' character
|
| 186 |
+
'add*_1': (
|
| 187 |
+
re.compile(r'''
|
| 188 |
+
(?:(?<=[])\d])|(?<=\d\.)) # ], ) or a number
|
| 189 |
+
# ''
|
| 190 |
+
(?=[(a-zA-Z]) # ( or a single letter
|
| 191 |
+
''', re.VERBOSE),
|
| 192 |
+
'*'),
|
| 193 |
+
|
| 194 |
+
# add omitted '*' character (variable letter preceding)
|
| 195 |
+
'add*_2': (
|
| 196 |
+
re.compile(r'''
|
| 197 |
+
(?<=[a-zA-Z]) # a letter
|
| 198 |
+
\( # ( as a character
|
| 199 |
+
(?=.) # any characters
|
| 200 |
+
''', re.VERBOSE),
|
| 201 |
+
'*('),
|
| 202 |
+
|
| 203 |
+
# convert 'Pi' to 'pi'
|
| 204 |
+
'Pi': (
|
| 205 |
+
re.compile(r'''
|
| 206 |
+
(?:
|
| 207 |
+
\A|(?<=[^a-zA-Z])
|
| 208 |
+
)
|
| 209 |
+
Pi # 'Pi' is 3.14159... in Mathematica
|
| 210 |
+
(?=[^a-zA-Z])
|
| 211 |
+
''', re.VERBOSE),
|
| 212 |
+
'pi'),
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
# Mathematica function name pattern
|
| 216 |
+
FM_PATTERN = re.compile(r'''
|
| 217 |
+
(?:
|
| 218 |
+
\A|(?<=[^a-zA-Z]) # at the top or a non-letter
|
| 219 |
+
)
|
| 220 |
+
[A-Z][a-zA-Z\d]* # Function
|
| 221 |
+
(?=\[) # [ as a character
|
| 222 |
+
''', re.VERBOSE)
|
| 223 |
+
|
| 224 |
+
# list or matrix pattern (for future usage)
|
| 225 |
+
ARG_MTRX_PATTERN = re.compile(r'''
|
| 226 |
+
\{.*\}
|
| 227 |
+
''', re.VERBOSE)
|
| 228 |
+
|
| 229 |
+
# regex string for function argument pattern
|
| 230 |
+
ARGS_PATTERN_TEMPLATE = r'''
|
| 231 |
+
(?:
|
| 232 |
+
\A|(?<=[^a-zA-Z])
|
| 233 |
+
)
|
| 234 |
+
{arguments} # model argument like x, y,...
|
| 235 |
+
(?=[^a-zA-Z])
|
| 236 |
+
'''
|
| 237 |
+
|
| 238 |
+
# will contain transformed CORRESPONDENCES dictionary
|
| 239 |
+
TRANSLATIONS: dict[tuple[str, int], dict[str, Any]] = {}
|
| 240 |
+
|
| 241 |
+
# cache for a raw users' translation dictionary
|
| 242 |
+
cache_original: dict[tuple[str, int], dict[str, Any]] = {}
|
| 243 |
+
|
| 244 |
+
# cache for a compiled users' translation dictionary
|
| 245 |
+
cache_compiled: dict[tuple[str, int], dict[str, Any]] = {}
|
| 246 |
+
|
| 247 |
+
@classmethod
|
| 248 |
+
def _initialize_class(cls):
|
| 249 |
+
# get a transformed CORRESPONDENCES dictionary
|
| 250 |
+
d = cls._compile_dictionary(cls.CORRESPONDENCES)
|
| 251 |
+
cls.TRANSLATIONS.update(d)
|
| 252 |
+
|
| 253 |
+
def __init__(self, additional_translations=None):
|
| 254 |
+
self.translations = {}
|
| 255 |
+
|
| 256 |
+
# update with TRANSLATIONS (class constant)
|
| 257 |
+
self.translations.update(self.TRANSLATIONS)
|
| 258 |
+
|
| 259 |
+
if additional_translations is None:
|
| 260 |
+
additional_translations = {}
|
| 261 |
+
|
| 262 |
+
# check the latest added translations
|
| 263 |
+
if self.__class__.cache_original != additional_translations:
|
| 264 |
+
if not isinstance(additional_translations, dict):
|
| 265 |
+
raise ValueError('The argument must be dict type')
|
| 266 |
+
|
| 267 |
+
# get a transformed additional_translations dictionary
|
| 268 |
+
d = self._compile_dictionary(additional_translations)
|
| 269 |
+
|
| 270 |
+
# update cache
|
| 271 |
+
self.__class__.cache_original = additional_translations
|
| 272 |
+
self.__class__.cache_compiled = d
|
| 273 |
+
|
| 274 |
+
# merge user's own translations
|
| 275 |
+
self.translations.update(self.__class__.cache_compiled)
|
| 276 |
+
|
| 277 |
+
@classmethod
|
| 278 |
+
def _compile_dictionary(cls, dic):
|
| 279 |
+
# for return
|
| 280 |
+
d = {}
|
| 281 |
+
|
| 282 |
+
for fm, fs in dic.items():
|
| 283 |
+
# check function form
|
| 284 |
+
cls._check_input(fm)
|
| 285 |
+
cls._check_input(fs)
|
| 286 |
+
|
| 287 |
+
# uncover '*' hiding behind a whitespace
|
| 288 |
+
fm = cls._apply_rules(fm, 'whitespace')
|
| 289 |
+
fs = cls._apply_rules(fs, 'whitespace')
|
| 290 |
+
|
| 291 |
+
# remove whitespace(s)
|
| 292 |
+
fm = cls._replace(fm, ' ')
|
| 293 |
+
fs = cls._replace(fs, ' ')
|
| 294 |
+
|
| 295 |
+
# search Mathematica function name
|
| 296 |
+
m = cls.FM_PATTERN.search(fm)
|
| 297 |
+
|
| 298 |
+
# if no-hit
|
| 299 |
+
if m is None:
|
| 300 |
+
err = "'{f}' function form is invalid.".format(f=fm)
|
| 301 |
+
raise ValueError(err)
|
| 302 |
+
|
| 303 |
+
# get Mathematica function name like 'Log'
|
| 304 |
+
fm_name = m.group()
|
| 305 |
+
|
| 306 |
+
# get arguments of Mathematica function
|
| 307 |
+
args, end = cls._get_args(m)
|
| 308 |
+
|
| 309 |
+
# function side check. (e.g.) '2*Func[x]' is invalid.
|
| 310 |
+
if m.start() != 0 or end != len(fm):
|
| 311 |
+
err = "'{f}' function form is invalid.".format(f=fm)
|
| 312 |
+
raise ValueError(err)
|
| 313 |
+
|
| 314 |
+
# check the last argument's 1st character
|
| 315 |
+
if args[-1][0] == '*':
|
| 316 |
+
key_arg = '*'
|
| 317 |
+
else:
|
| 318 |
+
key_arg = len(args)
|
| 319 |
+
|
| 320 |
+
key = (fm_name, key_arg)
|
| 321 |
+
|
| 322 |
+
# convert '*x' to '\\*x' for regex
|
| 323 |
+
re_args = [x if x[0] != '*' else '\\' + x for x in args]
|
| 324 |
+
|
| 325 |
+
# for regex. Example: (?:(x|y|z))
|
| 326 |
+
xyz = '(?:(' + '|'.join(re_args) + '))'
|
| 327 |
+
|
| 328 |
+
# string for regex compile
|
| 329 |
+
patStr = cls.ARGS_PATTERN_TEMPLATE.format(arguments=xyz)
|
| 330 |
+
|
| 331 |
+
pat = re.compile(patStr, re.VERBOSE)
|
| 332 |
+
|
| 333 |
+
# update dictionary
|
| 334 |
+
d[key] = {}
|
| 335 |
+
d[key]['fs'] = fs # SymPy function template
|
| 336 |
+
d[key]['args'] = args # args are ['x', 'y'] for example
|
| 337 |
+
d[key]['pat'] = pat
|
| 338 |
+
|
| 339 |
+
return d
|
| 340 |
+
|
| 341 |
+
def _convert_function(self, s):
|
| 342 |
+
'''Parse Mathematica function to SymPy one'''
|
| 343 |
+
|
| 344 |
+
# compiled regex object
|
| 345 |
+
pat = self.FM_PATTERN
|
| 346 |
+
|
| 347 |
+
scanned = '' # converted string
|
| 348 |
+
cur = 0 # position cursor
|
| 349 |
+
while True:
|
| 350 |
+
m = pat.search(s)
|
| 351 |
+
|
| 352 |
+
if m is None:
|
| 353 |
+
# append the rest of string
|
| 354 |
+
scanned += s
|
| 355 |
+
break
|
| 356 |
+
|
| 357 |
+
# get Mathematica function name
|
| 358 |
+
fm = m.group()
|
| 359 |
+
|
| 360 |
+
# get arguments, and the end position of fm function
|
| 361 |
+
args, end = self._get_args(m)
|
| 362 |
+
|
| 363 |
+
# the start position of fm function
|
| 364 |
+
bgn = m.start()
|
| 365 |
+
|
| 366 |
+
# convert Mathematica function to SymPy one
|
| 367 |
+
s = self._convert_one_function(s, fm, args, bgn, end)
|
| 368 |
+
|
| 369 |
+
# update cursor
|
| 370 |
+
cur = bgn
|
| 371 |
+
|
| 372 |
+
# append converted part
|
| 373 |
+
scanned += s[:cur]
|
| 374 |
+
|
| 375 |
+
# shrink s
|
| 376 |
+
s = s[cur:]
|
| 377 |
+
|
| 378 |
+
return scanned
|
| 379 |
+
|
| 380 |
+
def _convert_one_function(self, s, fm, args, bgn, end):
|
| 381 |
+
# no variable-length argument
|
| 382 |
+
if (fm, len(args)) in self.translations:
|
| 383 |
+
key = (fm, len(args))
|
| 384 |
+
|
| 385 |
+
# x, y,... model arguments
|
| 386 |
+
x_args = self.translations[key]['args']
|
| 387 |
+
|
| 388 |
+
# make CORRESPONDENCES between model arguments and actual ones
|
| 389 |
+
d = dict(zip(x_args, args))
|
| 390 |
+
|
| 391 |
+
# with variable-length argument
|
| 392 |
+
elif (fm, '*') in self.translations:
|
| 393 |
+
key = (fm, '*')
|
| 394 |
+
|
| 395 |
+
# x, y,..*args (model arguments)
|
| 396 |
+
x_args = self.translations[key]['args']
|
| 397 |
+
|
| 398 |
+
# make CORRESPONDENCES between model arguments and actual ones
|
| 399 |
+
d = {}
|
| 400 |
+
for i, x in enumerate(x_args):
|
| 401 |
+
if x[0] == '*':
|
| 402 |
+
d[x] = ','.join(args[i:])
|
| 403 |
+
break
|
| 404 |
+
d[x] = args[i]
|
| 405 |
+
|
| 406 |
+
# out of self.translations
|
| 407 |
+
else:
|
| 408 |
+
err = "'{f}' is out of the whitelist.".format(f=fm)
|
| 409 |
+
raise ValueError(err)
|
| 410 |
+
|
| 411 |
+
# template string of converted function
|
| 412 |
+
template = self.translations[key]['fs']
|
| 413 |
+
|
| 414 |
+
# regex pattern for x_args
|
| 415 |
+
pat = self.translations[key]['pat']
|
| 416 |
+
|
| 417 |
+
scanned = ''
|
| 418 |
+
cur = 0
|
| 419 |
+
while True:
|
| 420 |
+
m = pat.search(template)
|
| 421 |
+
|
| 422 |
+
if m is None:
|
| 423 |
+
scanned += template
|
| 424 |
+
break
|
| 425 |
+
|
| 426 |
+
# get model argument
|
| 427 |
+
x = m.group()
|
| 428 |
+
|
| 429 |
+
# get a start position of the model argument
|
| 430 |
+
xbgn = m.start()
|
| 431 |
+
|
| 432 |
+
# add the corresponding actual argument
|
| 433 |
+
scanned += template[:xbgn] + d[x]
|
| 434 |
+
|
| 435 |
+
# update cursor to the end of the model argument
|
| 436 |
+
cur = m.end()
|
| 437 |
+
|
| 438 |
+
# shrink template
|
| 439 |
+
template = template[cur:]
|
| 440 |
+
|
| 441 |
+
# update to swapped string
|
| 442 |
+
s = s[:bgn] + scanned + s[end:]
|
| 443 |
+
|
| 444 |
+
return s
|
| 445 |
+
|
| 446 |
+
@classmethod
|
| 447 |
+
def _get_args(cls, m):
|
| 448 |
+
'''Get arguments of a Mathematica function'''
|
| 449 |
+
|
| 450 |
+
s = m.string # whole string
|
| 451 |
+
anc = m.end() + 1 # pointing the first letter of arguments
|
| 452 |
+
square, curly = [], [] # stack for brakets
|
| 453 |
+
args = []
|
| 454 |
+
|
| 455 |
+
# current cursor
|
| 456 |
+
cur = anc
|
| 457 |
+
for i, c in enumerate(s[anc:], anc):
|
| 458 |
+
# extract one argument
|
| 459 |
+
if c == ',' and (not square) and (not curly):
|
| 460 |
+
args.append(s[cur:i]) # add an argument
|
| 461 |
+
cur = i + 1 # move cursor
|
| 462 |
+
|
| 463 |
+
# handle list or matrix (for future usage)
|
| 464 |
+
if c == '{':
|
| 465 |
+
curly.append(c)
|
| 466 |
+
elif c == '}':
|
| 467 |
+
curly.pop()
|
| 468 |
+
|
| 469 |
+
# seek corresponding ']' with skipping irrevant ones
|
| 470 |
+
if c == '[':
|
| 471 |
+
square.append(c)
|
| 472 |
+
elif c == ']':
|
| 473 |
+
if square:
|
| 474 |
+
square.pop()
|
| 475 |
+
else: # empty stack
|
| 476 |
+
args.append(s[cur:i])
|
| 477 |
+
break
|
| 478 |
+
|
| 479 |
+
# the next position to ']' bracket (the function end)
|
| 480 |
+
func_end = i + 1
|
| 481 |
+
|
| 482 |
+
return args, func_end
|
| 483 |
+
|
| 484 |
+
@classmethod
|
| 485 |
+
def _replace(cls, s, bef):
|
| 486 |
+
aft = cls.REPLACEMENTS[bef]
|
| 487 |
+
s = s.replace(bef, aft)
|
| 488 |
+
return s
|
| 489 |
+
|
| 490 |
+
@classmethod
|
| 491 |
+
def _apply_rules(cls, s, bef):
|
| 492 |
+
pat, aft = cls.RULES[bef]
|
| 493 |
+
return pat.sub(aft, s)
|
| 494 |
+
|
| 495 |
+
@classmethod
|
| 496 |
+
def _check_input(cls, s):
|
| 497 |
+
for bracket in (('[', ']'), ('{', '}'), ('(', ')')):
|
| 498 |
+
if s.count(bracket[0]) != s.count(bracket[1]):
|
| 499 |
+
err = "'{f}' function form is invalid.".format(f=s)
|
| 500 |
+
raise ValueError(err)
|
| 501 |
+
|
| 502 |
+
if '{' in s:
|
| 503 |
+
err = "Currently list is not supported."
|
| 504 |
+
raise ValueError(err)
|
| 505 |
+
|
| 506 |
+
def _parse_old(self, s):
|
| 507 |
+
# input check
|
| 508 |
+
self._check_input(s)
|
| 509 |
+
|
| 510 |
+
# uncover '*' hiding behind a whitespace
|
| 511 |
+
s = self._apply_rules(s, 'whitespace')
|
| 512 |
+
|
| 513 |
+
# remove whitespace(s)
|
| 514 |
+
s = self._replace(s, ' ')
|
| 515 |
+
|
| 516 |
+
# add omitted '*' character
|
| 517 |
+
s = self._apply_rules(s, 'add*_1')
|
| 518 |
+
s = self._apply_rules(s, 'add*_2')
|
| 519 |
+
|
| 520 |
+
# translate function
|
| 521 |
+
s = self._convert_function(s)
|
| 522 |
+
|
| 523 |
+
# '^' to '**'
|
| 524 |
+
s = self._replace(s, '^')
|
| 525 |
+
|
| 526 |
+
# 'Pi' to 'pi'
|
| 527 |
+
s = self._apply_rules(s, 'Pi')
|
| 528 |
+
|
| 529 |
+
# '{', '}' to '[', ']', respectively
|
| 530 |
+
# s = cls._replace(s, '{') # currently list is not taken into account
|
| 531 |
+
# s = cls._replace(s, '}')
|
| 532 |
+
|
| 533 |
+
return s
|
| 534 |
+
|
| 535 |
+
def parse(self, s):
|
| 536 |
+
s2 = self._from_mathematica_to_tokens(s)
|
| 537 |
+
s3 = self._from_tokens_to_fullformlist(s2)
|
| 538 |
+
s4 = self._from_fullformlist_to_sympy(s3)
|
| 539 |
+
return s4
|
| 540 |
+
|
| 541 |
+
INFIX = "Infix"
|
| 542 |
+
PREFIX = "Prefix"
|
| 543 |
+
POSTFIX = "Postfix"
|
| 544 |
+
FLAT = "Flat"
|
| 545 |
+
RIGHT = "Right"
|
| 546 |
+
LEFT = "Left"
|
| 547 |
+
|
| 548 |
+
_mathematica_op_precedence: list[tuple[str, str | None, dict[str, str | Callable]]] = [
|
| 549 |
+
(POSTFIX, None, {";": lambda x: x + ["Null"] if isinstance(x, list) and x and x[0] == "CompoundExpression" else ["CompoundExpression", x, "Null"]}),
|
| 550 |
+
(INFIX, FLAT, {";": "CompoundExpression"}),
|
| 551 |
+
(INFIX, RIGHT, {"=": "Set", ":=": "SetDelayed", "+=": "AddTo", "-=": "SubtractFrom", "*=": "TimesBy", "/=": "DivideBy"}),
|
| 552 |
+
(INFIX, LEFT, {"//": lambda x, y: [x, y]}),
|
| 553 |
+
(POSTFIX, None, {"&": "Function"}),
|
| 554 |
+
(INFIX, LEFT, {"/.": "ReplaceAll"}),
|
| 555 |
+
(INFIX, RIGHT, {"->": "Rule", ":>": "RuleDelayed"}),
|
| 556 |
+
(INFIX, LEFT, {"/;": "Condition"}),
|
| 557 |
+
(INFIX, FLAT, {"|": "Alternatives"}),
|
| 558 |
+
(POSTFIX, None, {"..": "Repeated", "...": "RepeatedNull"}),
|
| 559 |
+
(INFIX, FLAT, {"||": "Or"}),
|
| 560 |
+
(INFIX, FLAT, {"&&": "And"}),
|
| 561 |
+
(PREFIX, None, {"!": "Not"}),
|
| 562 |
+
(INFIX, FLAT, {"===": "SameQ", "=!=": "UnsameQ"}),
|
| 563 |
+
(INFIX, FLAT, {"==": "Equal", "!=": "Unequal", "<=": "LessEqual", "<": "Less", ">=": "GreaterEqual", ">": "Greater"}),
|
| 564 |
+
(INFIX, None, {";;": "Span"}),
|
| 565 |
+
(INFIX, FLAT, {"+": "Plus", "-": "Plus"}),
|
| 566 |
+
(INFIX, FLAT, {"*": "Times", "/": "Times"}),
|
| 567 |
+
(INFIX, FLAT, {".": "Dot"}),
|
| 568 |
+
(PREFIX, None, {"-": lambda x: MathematicaParser._get_neg(x),
|
| 569 |
+
"+": lambda x: x}),
|
| 570 |
+
(INFIX, RIGHT, {"^": "Power"}),
|
| 571 |
+
(INFIX, RIGHT, {"@@": "Apply", "/@": "Map", "//@": "MapAll", "@@@": lambda x, y: ["Apply", x, y, ["List", "1"]]}),
|
| 572 |
+
(POSTFIX, None, {"'": "Derivative", "!": "Factorial", "!!": "Factorial2", "--": "Decrement"}),
|
| 573 |
+
(INFIX, None, {"[": lambda x, y: [x, *y], "[[": lambda x, y: ["Part", x, *y]}),
|
| 574 |
+
(PREFIX, None, {"{": lambda x: ["List", *x], "(": lambda x: x[0]}),
|
| 575 |
+
(INFIX, None, {"?": "PatternTest"}),
|
| 576 |
+
(POSTFIX, None, {
|
| 577 |
+
"_": lambda x: ["Pattern", x, ["Blank"]],
|
| 578 |
+
"_.": lambda x: ["Optional", ["Pattern", x, ["Blank"]]],
|
| 579 |
+
"__": lambda x: ["Pattern", x, ["BlankSequence"]],
|
| 580 |
+
"___": lambda x: ["Pattern", x, ["BlankNullSequence"]],
|
| 581 |
+
}),
|
| 582 |
+
(INFIX, None, {"_": lambda x, y: ["Pattern", x, ["Blank", y]]}),
|
| 583 |
+
(PREFIX, None, {"#": "Slot", "##": "SlotSequence"}),
|
| 584 |
+
]
|
| 585 |
+
|
| 586 |
+
_missing_arguments_default = {
|
| 587 |
+
"#": lambda: ["Slot", "1"],
|
| 588 |
+
"##": lambda: ["SlotSequence", "1"],
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
_literal = r"[A-Za-z][A-Za-z0-9]*"
|
| 592 |
+
_number = r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)"
|
| 593 |
+
|
| 594 |
+
_enclosure_open = ["(", "[", "[[", "{"]
|
| 595 |
+
_enclosure_close = [")", "]", "]]", "}"]
|
| 596 |
+
|
| 597 |
+
@classmethod
|
| 598 |
+
def _get_neg(cls, x):
|
| 599 |
+
return f"-{x}" if isinstance(x, str) and re.match(MathematicaParser._number, x) else ["Times", "-1", x]
|
| 600 |
+
|
| 601 |
+
@classmethod
|
| 602 |
+
def _get_inv(cls, x):
|
| 603 |
+
return ["Power", x, "-1"]
|
| 604 |
+
|
| 605 |
+
_regex_tokenizer = None
|
| 606 |
+
|
| 607 |
+
def _get_tokenizer(self):
|
| 608 |
+
if self._regex_tokenizer is not None:
|
| 609 |
+
# Check if the regular expression has already been compiled:
|
| 610 |
+
return self._regex_tokenizer
|
| 611 |
+
tokens = [self._literal, self._number]
|
| 612 |
+
tokens_escape = self._enclosure_open[:] + self._enclosure_close[:]
|
| 613 |
+
for typ, strat, symdict in self._mathematica_op_precedence:
|
| 614 |
+
for k in symdict:
|
| 615 |
+
tokens_escape.append(k)
|
| 616 |
+
tokens_escape.sort(key=lambda x: -len(x))
|
| 617 |
+
tokens.extend(map(re.escape, tokens_escape))
|
| 618 |
+
tokens.append(",")
|
| 619 |
+
tokens.append("\n")
|
| 620 |
+
tokenizer = re.compile("(" + "|".join(tokens) + ")")
|
| 621 |
+
self._regex_tokenizer = tokenizer
|
| 622 |
+
return self._regex_tokenizer
|
| 623 |
+
|
| 624 |
+
def _from_mathematica_to_tokens(self, code: str):
|
| 625 |
+
tokenizer = self._get_tokenizer()
|
| 626 |
+
|
| 627 |
+
# Find strings:
|
| 628 |
+
code_splits: list[str | list] = []
|
| 629 |
+
while True:
|
| 630 |
+
string_start = code.find("\"")
|
| 631 |
+
if string_start == -1:
|
| 632 |
+
if len(code) > 0:
|
| 633 |
+
code_splits.append(code)
|
| 634 |
+
break
|
| 635 |
+
match_end = re.search(r'(?<!\\)"', code[string_start+1:])
|
| 636 |
+
if match_end is None:
|
| 637 |
+
raise SyntaxError('mismatch in string " " expression')
|
| 638 |
+
string_end = string_start + match_end.start() + 1
|
| 639 |
+
if string_start > 0:
|
| 640 |
+
code_splits.append(code[:string_start])
|
| 641 |
+
code_splits.append(["_Str", code[string_start+1:string_end].replace('\\"', '"')])
|
| 642 |
+
code = code[string_end+1:]
|
| 643 |
+
|
| 644 |
+
# Remove comments:
|
| 645 |
+
for i, code_split in enumerate(code_splits):
|
| 646 |
+
if isinstance(code_split, list):
|
| 647 |
+
continue
|
| 648 |
+
while True:
|
| 649 |
+
pos_comment_start = code_split.find("(*")
|
| 650 |
+
if pos_comment_start == -1:
|
| 651 |
+
break
|
| 652 |
+
pos_comment_end = code_split.find("*)")
|
| 653 |
+
if pos_comment_end == -1 or pos_comment_end < pos_comment_start:
|
| 654 |
+
raise SyntaxError("mismatch in comment (* *) code")
|
| 655 |
+
code_split = code_split[:pos_comment_start] + code_split[pos_comment_end+2:]
|
| 656 |
+
code_splits[i] = code_split
|
| 657 |
+
|
| 658 |
+
# Tokenize the input strings with a regular expression:
|
| 659 |
+
token_lists = [tokenizer.findall(i) if isinstance(i, str) and i.isascii() else [i] for i in code_splits]
|
| 660 |
+
tokens = [j for i in token_lists for j in i]
|
| 661 |
+
|
| 662 |
+
# Remove newlines at the beginning
|
| 663 |
+
while tokens and tokens[0] == "\n":
|
| 664 |
+
tokens.pop(0)
|
| 665 |
+
# Remove newlines at the end
|
| 666 |
+
while tokens and tokens[-1] == "\n":
|
| 667 |
+
tokens.pop(-1)
|
| 668 |
+
|
| 669 |
+
return tokens
|
| 670 |
+
|
| 671 |
+
def _is_op(self, token: str | list) -> bool:
|
| 672 |
+
if isinstance(token, list):
|
| 673 |
+
return False
|
| 674 |
+
if re.match(self._literal, token):
|
| 675 |
+
return False
|
| 676 |
+
if re.match("-?" + self._number, token):
|
| 677 |
+
return False
|
| 678 |
+
return True
|
| 679 |
+
|
| 680 |
+
def _is_valid_star1(self, token: str | list) -> bool:
|
| 681 |
+
if token in (")", "}"):
|
| 682 |
+
return True
|
| 683 |
+
return not self._is_op(token)
|
| 684 |
+
|
| 685 |
+
def _is_valid_star2(self, token: str | list) -> bool:
|
| 686 |
+
if token in ("(", "{"):
|
| 687 |
+
return True
|
| 688 |
+
return not self._is_op(token)
|
| 689 |
+
|
| 690 |
+
def _from_tokens_to_fullformlist(self, tokens: list):
|
| 691 |
+
stack: list[list] = [[]]
|
| 692 |
+
open_seq = []
|
| 693 |
+
pointer: int = 0
|
| 694 |
+
while pointer < len(tokens):
|
| 695 |
+
token = tokens[pointer]
|
| 696 |
+
if token in self._enclosure_open:
|
| 697 |
+
stack[-1].append(token)
|
| 698 |
+
open_seq.append(token)
|
| 699 |
+
stack.append([])
|
| 700 |
+
elif token == ",":
|
| 701 |
+
if len(stack[-1]) == 0 and stack[-2][-1] == open_seq[-1]:
|
| 702 |
+
raise SyntaxError("%s cannot be followed by comma ," % open_seq[-1])
|
| 703 |
+
stack[-1] = self._parse_after_braces(stack[-1])
|
| 704 |
+
stack.append([])
|
| 705 |
+
elif token in self._enclosure_close:
|
| 706 |
+
ind = self._enclosure_close.index(token)
|
| 707 |
+
if self._enclosure_open[ind] != open_seq[-1]:
|
| 708 |
+
unmatched_enclosure = SyntaxError("unmatched enclosure")
|
| 709 |
+
if token == "]]" and open_seq[-1] == "[":
|
| 710 |
+
if open_seq[-2] == "[":
|
| 711 |
+
# These two lines would be logically correct, but are
|
| 712 |
+
# unnecessary:
|
| 713 |
+
# token = "]"
|
| 714 |
+
# tokens[pointer] = "]"
|
| 715 |
+
tokens.insert(pointer+1, "]")
|
| 716 |
+
elif open_seq[-2] == "[[":
|
| 717 |
+
if tokens[pointer+1] == "]":
|
| 718 |
+
tokens[pointer+1] = "]]"
|
| 719 |
+
elif tokens[pointer+1] == "]]":
|
| 720 |
+
tokens[pointer+1] = "]]"
|
| 721 |
+
tokens.insert(pointer+2, "]")
|
| 722 |
+
else:
|
| 723 |
+
raise unmatched_enclosure
|
| 724 |
+
else:
|
| 725 |
+
raise unmatched_enclosure
|
| 726 |
+
if len(stack[-1]) == 0 and stack[-2][-1] == "(":
|
| 727 |
+
raise SyntaxError("( ) not valid syntax")
|
| 728 |
+
last_stack = self._parse_after_braces(stack[-1], True)
|
| 729 |
+
stack[-1] = last_stack
|
| 730 |
+
new_stack_element = []
|
| 731 |
+
while stack[-1][-1] != open_seq[-1]:
|
| 732 |
+
new_stack_element.append(stack.pop())
|
| 733 |
+
new_stack_element.reverse()
|
| 734 |
+
if open_seq[-1] == "(" and len(new_stack_element) != 1:
|
| 735 |
+
raise SyntaxError("( must be followed by one expression, %i detected" % len(new_stack_element))
|
| 736 |
+
stack[-1].append(new_stack_element)
|
| 737 |
+
open_seq.pop(-1)
|
| 738 |
+
else:
|
| 739 |
+
stack[-1].append(token)
|
| 740 |
+
pointer += 1
|
| 741 |
+
if len(stack) != 1:
|
| 742 |
+
raise RuntimeError("Stack should have only one element")
|
| 743 |
+
return self._parse_after_braces(stack[0])
|
| 744 |
+
|
| 745 |
+
def _util_remove_newlines(self, lines: list, tokens: list, inside_enclosure: bool):
|
| 746 |
+
pointer = 0
|
| 747 |
+
size = len(tokens)
|
| 748 |
+
while pointer < size:
|
| 749 |
+
token = tokens[pointer]
|
| 750 |
+
if token == "\n":
|
| 751 |
+
if inside_enclosure:
|
| 752 |
+
# Ignore newlines inside enclosures
|
| 753 |
+
tokens.pop(pointer)
|
| 754 |
+
size -= 1
|
| 755 |
+
continue
|
| 756 |
+
if pointer == 0:
|
| 757 |
+
tokens.pop(0)
|
| 758 |
+
size -= 1
|
| 759 |
+
continue
|
| 760 |
+
if pointer > 1:
|
| 761 |
+
try:
|
| 762 |
+
prev_expr = self._parse_after_braces(tokens[:pointer], inside_enclosure)
|
| 763 |
+
except SyntaxError:
|
| 764 |
+
tokens.pop(pointer)
|
| 765 |
+
size -= 1
|
| 766 |
+
continue
|
| 767 |
+
else:
|
| 768 |
+
prev_expr = tokens[0]
|
| 769 |
+
if len(prev_expr) > 0 and prev_expr[0] == "CompoundExpression":
|
| 770 |
+
lines.extend(prev_expr[1:])
|
| 771 |
+
else:
|
| 772 |
+
lines.append(prev_expr)
|
| 773 |
+
for i in range(pointer):
|
| 774 |
+
tokens.pop(0)
|
| 775 |
+
size -= pointer
|
| 776 |
+
pointer = 0
|
| 777 |
+
continue
|
| 778 |
+
pointer += 1
|
| 779 |
+
|
| 780 |
+
def _util_add_missing_asterisks(self, tokens: list):
|
| 781 |
+
size: int = len(tokens)
|
| 782 |
+
pointer: int = 0
|
| 783 |
+
while pointer < size:
|
| 784 |
+
if (pointer > 0 and
|
| 785 |
+
self._is_valid_star1(tokens[pointer - 1]) and
|
| 786 |
+
self._is_valid_star2(tokens[pointer])):
|
| 787 |
+
# This is a trick to add missing * operators in the expression,
|
| 788 |
+
# `"*" in op_dict` makes sure the precedence level is the same as "*",
|
| 789 |
+
# while `not self._is_op( ... )` makes sure this and the previous
|
| 790 |
+
# expression are not operators.
|
| 791 |
+
if tokens[pointer] == "(":
|
| 792 |
+
# ( has already been processed by now, replace:
|
| 793 |
+
tokens[pointer] = "*"
|
| 794 |
+
tokens[pointer + 1] = tokens[pointer + 1][0]
|
| 795 |
+
else:
|
| 796 |
+
tokens.insert(pointer, "*")
|
| 797 |
+
pointer += 1
|
| 798 |
+
size += 1
|
| 799 |
+
pointer += 1
|
| 800 |
+
|
| 801 |
+
def _parse_after_braces(self, tokens: list, inside_enclosure: bool = False):
|
| 802 |
+
op_dict: dict
|
| 803 |
+
changed: bool = False
|
| 804 |
+
lines: list = []
|
| 805 |
+
|
| 806 |
+
self._util_remove_newlines(lines, tokens, inside_enclosure)
|
| 807 |
+
|
| 808 |
+
for op_type, grouping_strat, op_dict in reversed(self._mathematica_op_precedence):
|
| 809 |
+
if "*" in op_dict:
|
| 810 |
+
self._util_add_missing_asterisks(tokens)
|
| 811 |
+
size: int = len(tokens)
|
| 812 |
+
pointer: int = 0
|
| 813 |
+
while pointer < size:
|
| 814 |
+
token = tokens[pointer]
|
| 815 |
+
if isinstance(token, str) and token in op_dict:
|
| 816 |
+
op_name: str | Callable = op_dict[token]
|
| 817 |
+
node: list
|
| 818 |
+
first_index: int
|
| 819 |
+
if isinstance(op_name, str):
|
| 820 |
+
node = [op_name]
|
| 821 |
+
first_index = 1
|
| 822 |
+
else:
|
| 823 |
+
node = []
|
| 824 |
+
first_index = 0
|
| 825 |
+
if token in ("+", "-") and op_type == self.PREFIX and pointer > 0 and not self._is_op(tokens[pointer - 1]):
|
| 826 |
+
# Make sure that PREFIX + - don't match expressions like a + b or a - b,
|
| 827 |
+
# the INFIX + - are supposed to match that expression:
|
| 828 |
+
pointer += 1
|
| 829 |
+
continue
|
| 830 |
+
if op_type == self.INFIX:
|
| 831 |
+
if pointer == 0 or pointer == size - 1 or self._is_op(tokens[pointer - 1]) or self._is_op(tokens[pointer + 1]):
|
| 832 |
+
pointer += 1
|
| 833 |
+
continue
|
| 834 |
+
changed = True
|
| 835 |
+
tokens[pointer] = node
|
| 836 |
+
if op_type == self.INFIX:
|
| 837 |
+
arg1 = tokens.pop(pointer-1)
|
| 838 |
+
arg2 = tokens.pop(pointer)
|
| 839 |
+
if token == "/":
|
| 840 |
+
arg2 = self._get_inv(arg2)
|
| 841 |
+
elif token == "-":
|
| 842 |
+
arg2 = self._get_neg(arg2)
|
| 843 |
+
pointer -= 1
|
| 844 |
+
size -= 2
|
| 845 |
+
node.append(arg1)
|
| 846 |
+
node_p = node
|
| 847 |
+
if grouping_strat == self.FLAT:
|
| 848 |
+
while pointer + 2 < size and self._check_op_compatible(tokens[pointer+1], token):
|
| 849 |
+
node_p.append(arg2)
|
| 850 |
+
other_op = tokens.pop(pointer+1)
|
| 851 |
+
arg2 = tokens.pop(pointer+1)
|
| 852 |
+
if other_op == "/":
|
| 853 |
+
arg2 = self._get_inv(arg2)
|
| 854 |
+
elif other_op == "-":
|
| 855 |
+
arg2 = self._get_neg(arg2)
|
| 856 |
+
size -= 2
|
| 857 |
+
node_p.append(arg2)
|
| 858 |
+
elif grouping_strat == self.RIGHT:
|
| 859 |
+
while pointer + 2 < size and tokens[pointer+1] == token:
|
| 860 |
+
node_p.append([op_name, arg2])
|
| 861 |
+
node_p = node_p[-1]
|
| 862 |
+
tokens.pop(pointer+1)
|
| 863 |
+
arg2 = tokens.pop(pointer+1)
|
| 864 |
+
size -= 2
|
| 865 |
+
node_p.append(arg2)
|
| 866 |
+
elif grouping_strat == self.LEFT:
|
| 867 |
+
while pointer + 1 < size and tokens[pointer+1] == token:
|
| 868 |
+
if isinstance(op_name, str):
|
| 869 |
+
node_p[first_index] = [op_name, node_p[first_index], arg2]
|
| 870 |
+
else:
|
| 871 |
+
node_p[first_index] = op_name(node_p[first_index], arg2)
|
| 872 |
+
tokens.pop(pointer+1)
|
| 873 |
+
arg2 = tokens.pop(pointer+1)
|
| 874 |
+
size -= 2
|
| 875 |
+
node_p.append(arg2)
|
| 876 |
+
else:
|
| 877 |
+
node.append(arg2)
|
| 878 |
+
elif op_type == self.PREFIX:
|
| 879 |
+
if grouping_strat is not None:
|
| 880 |
+
raise TypeError("'Prefix' op_type should not have a grouping strat")
|
| 881 |
+
if pointer == size - 1 or self._is_op(tokens[pointer + 1]):
|
| 882 |
+
tokens[pointer] = self._missing_arguments_default[token]()
|
| 883 |
+
else:
|
| 884 |
+
node.append(tokens.pop(pointer+1))
|
| 885 |
+
size -= 1
|
| 886 |
+
elif op_type == self.POSTFIX:
|
| 887 |
+
if grouping_strat is not None:
|
| 888 |
+
raise TypeError("'Prefix' op_type should not have a grouping strat")
|
| 889 |
+
if pointer == 0 or self._is_op(tokens[pointer - 1]):
|
| 890 |
+
tokens[pointer] = self._missing_arguments_default[token]()
|
| 891 |
+
else:
|
| 892 |
+
node.append(tokens.pop(pointer-1))
|
| 893 |
+
pointer -= 1
|
| 894 |
+
size -= 1
|
| 895 |
+
if isinstance(op_name, Callable): # type: ignore
|
| 896 |
+
op_call: Callable = typing.cast(Callable, op_name)
|
| 897 |
+
new_node = op_call(*node)
|
| 898 |
+
node.clear()
|
| 899 |
+
if isinstance(new_node, list):
|
| 900 |
+
node.extend(new_node)
|
| 901 |
+
else:
|
| 902 |
+
tokens[pointer] = new_node
|
| 903 |
+
pointer += 1
|
| 904 |
+
if len(tokens) > 1 or (len(lines) == 0 and len(tokens) == 0):
|
| 905 |
+
if changed:
|
| 906 |
+
# Trick to deal with cases in which an operator with lower
|
| 907 |
+
# precedence should be transformed before an operator of higher
|
| 908 |
+
# precedence. Such as in the case of `#&[x]` (that is
|
| 909 |
+
# equivalent to `Lambda(d_, d_)(x)` in SymPy). In this case the
|
| 910 |
+
# operator `&` has lower precedence than `[`, but needs to be
|
| 911 |
+
# evaluated first because otherwise `# (&[x])` is not a valid
|
| 912 |
+
# expression:
|
| 913 |
+
return self._parse_after_braces(tokens, inside_enclosure)
|
| 914 |
+
raise SyntaxError("unable to create a single AST for the expression")
|
| 915 |
+
if len(lines) > 0:
|
| 916 |
+
if tokens[0] and tokens[0][0] == "CompoundExpression":
|
| 917 |
+
tokens = tokens[0][1:]
|
| 918 |
+
compound_expression = ["CompoundExpression", *lines, *tokens]
|
| 919 |
+
return compound_expression
|
| 920 |
+
return tokens[0]
|
| 921 |
+
|
| 922 |
+
def _check_op_compatible(self, op1: str, op2: str):
|
| 923 |
+
if op1 == op2:
|
| 924 |
+
return True
|
| 925 |
+
muldiv = {"*", "/"}
|
| 926 |
+
addsub = {"+", "-"}
|
| 927 |
+
if op1 in muldiv and op2 in muldiv:
|
| 928 |
+
return True
|
| 929 |
+
if op1 in addsub and op2 in addsub:
|
| 930 |
+
return True
|
| 931 |
+
return False
|
| 932 |
+
|
| 933 |
+
def _from_fullform_to_fullformlist(self, wmexpr: str):
|
| 934 |
+
"""
|
| 935 |
+
Parses FullForm[Downvalues[]] generated by Mathematica
|
| 936 |
+
"""
|
| 937 |
+
out: list = []
|
| 938 |
+
stack = [out]
|
| 939 |
+
generator = re.finditer(r'[\[\],]', wmexpr)
|
| 940 |
+
last_pos = 0
|
| 941 |
+
for match in generator:
|
| 942 |
+
if match is None:
|
| 943 |
+
break
|
| 944 |
+
position = match.start()
|
| 945 |
+
last_expr = wmexpr[last_pos:position].replace(',', '').replace(']', '').replace('[', '').strip()
|
| 946 |
+
|
| 947 |
+
if match.group() == ',':
|
| 948 |
+
if last_expr != '':
|
| 949 |
+
stack[-1].append(last_expr)
|
| 950 |
+
elif match.group() == ']':
|
| 951 |
+
if last_expr != '':
|
| 952 |
+
stack[-1].append(last_expr)
|
| 953 |
+
stack.pop()
|
| 954 |
+
elif match.group() == '[':
|
| 955 |
+
stack[-1].append([last_expr])
|
| 956 |
+
stack.append(stack[-1][-1])
|
| 957 |
+
last_pos = match.end()
|
| 958 |
+
return out[0]
|
| 959 |
+
|
| 960 |
+
def _from_fullformlist_to_fullformsympy(self, pylist: list):
|
| 961 |
+
from sympy import Function, Symbol
|
| 962 |
+
|
| 963 |
+
def converter(expr):
|
| 964 |
+
if isinstance(expr, list):
|
| 965 |
+
if len(expr) > 0:
|
| 966 |
+
head = expr[0]
|
| 967 |
+
args = [converter(arg) for arg in expr[1:]]
|
| 968 |
+
return Function(head)(*args)
|
| 969 |
+
else:
|
| 970 |
+
raise ValueError("Empty list of expressions")
|
| 971 |
+
elif isinstance(expr, str):
|
| 972 |
+
return Symbol(expr)
|
| 973 |
+
else:
|
| 974 |
+
return _sympify(expr)
|
| 975 |
+
|
| 976 |
+
return converter(pylist)
|
| 977 |
+
|
| 978 |
+
_node_conversions = {
|
| 979 |
+
"Times": Mul,
|
| 980 |
+
"Plus": Add,
|
| 981 |
+
"Power": Pow,
|
| 982 |
+
"Rational": Rational,
|
| 983 |
+
"Log": lambda *a: log(*reversed(a)),
|
| 984 |
+
"Log2": lambda x: log(x, 2),
|
| 985 |
+
"Log10": lambda x: log(x, 10),
|
| 986 |
+
"Rational": Rational,
|
| 987 |
+
"Exp": exp,
|
| 988 |
+
"Sqrt": sqrt,
|
| 989 |
+
|
| 990 |
+
"Sin": sin,
|
| 991 |
+
"Cos": cos,
|
| 992 |
+
"Tan": tan,
|
| 993 |
+
"Cot": cot,
|
| 994 |
+
"Sec": sec,
|
| 995 |
+
"Csc": csc,
|
| 996 |
+
|
| 997 |
+
"ArcSin": asin,
|
| 998 |
+
"ArcCos": acos,
|
| 999 |
+
"ArcTan": lambda *a: atan2(*reversed(a)) if len(a) == 2 else atan(*a),
|
| 1000 |
+
"ArcCot": acot,
|
| 1001 |
+
"ArcSec": asec,
|
| 1002 |
+
"ArcCsc": acsc,
|
| 1003 |
+
|
| 1004 |
+
"Sinh": sinh,
|
| 1005 |
+
"Cosh": cosh,
|
| 1006 |
+
"Tanh": tanh,
|
| 1007 |
+
"Coth": coth,
|
| 1008 |
+
"Sech": sech,
|
| 1009 |
+
"Csch": csch,
|
| 1010 |
+
|
| 1011 |
+
"ArcSinh": asinh,
|
| 1012 |
+
"ArcCosh": acosh,
|
| 1013 |
+
"ArcTanh": atanh,
|
| 1014 |
+
"ArcCoth": acoth,
|
| 1015 |
+
"ArcSech": asech,
|
| 1016 |
+
"ArcCsch": acsch,
|
| 1017 |
+
|
| 1018 |
+
"Expand": expand,
|
| 1019 |
+
"Im": im,
|
| 1020 |
+
"Re": sympy.re,
|
| 1021 |
+
"Flatten": flatten,
|
| 1022 |
+
"Polylog": polylog,
|
| 1023 |
+
"Cancel": cancel,
|
| 1024 |
+
# Gamma=gamma,
|
| 1025 |
+
"TrigExpand": expand_trig,
|
| 1026 |
+
"Sign": sign,
|
| 1027 |
+
"Simplify": simplify,
|
| 1028 |
+
"Defer": UnevaluatedExpr,
|
| 1029 |
+
"Identity": S,
|
| 1030 |
+
# Sum=Sum_doit,
|
| 1031 |
+
# Module=With,
|
| 1032 |
+
# Block=With,
|
| 1033 |
+
"Null": lambda *a: S.Zero,
|
| 1034 |
+
"Mod": Mod,
|
| 1035 |
+
"Max": Max,
|
| 1036 |
+
"Min": Min,
|
| 1037 |
+
"Pochhammer": rf,
|
| 1038 |
+
"ExpIntegralEi": Ei,
|
| 1039 |
+
"SinIntegral": Si,
|
| 1040 |
+
"CosIntegral": Ci,
|
| 1041 |
+
"AiryAi": airyai,
|
| 1042 |
+
"AiryAiPrime": airyaiprime,
|
| 1043 |
+
"AiryBi": airybi,
|
| 1044 |
+
"AiryBiPrime": airybiprime,
|
| 1045 |
+
"LogIntegral": li,
|
| 1046 |
+
"PrimePi": primepi,
|
| 1047 |
+
"Prime": prime,
|
| 1048 |
+
"PrimeQ": isprime,
|
| 1049 |
+
|
| 1050 |
+
"List": Tuple,
|
| 1051 |
+
"Greater": StrictGreaterThan,
|
| 1052 |
+
"GreaterEqual": GreaterThan,
|
| 1053 |
+
"Less": StrictLessThan,
|
| 1054 |
+
"LessEqual": LessThan,
|
| 1055 |
+
"Equal": Equality,
|
| 1056 |
+
"Or": Or,
|
| 1057 |
+
"And": And,
|
| 1058 |
+
|
| 1059 |
+
"Function": _parse_Function,
|
| 1060 |
+
}
|
| 1061 |
+
|
| 1062 |
+
_atom_conversions = {
|
| 1063 |
+
"I": I,
|
| 1064 |
+
"Pi": pi,
|
| 1065 |
+
}
|
| 1066 |
+
|
| 1067 |
+
def _from_fullformlist_to_sympy(self, full_form_list):
|
| 1068 |
+
|
| 1069 |
+
def recurse(expr):
|
| 1070 |
+
if isinstance(expr, list):
|
| 1071 |
+
if isinstance(expr[0], list):
|
| 1072 |
+
head = recurse(expr[0])
|
| 1073 |
+
else:
|
| 1074 |
+
head = self._node_conversions.get(expr[0], Function(expr[0]))
|
| 1075 |
+
return head(*[recurse(arg) for arg in expr[1:]])
|
| 1076 |
+
else:
|
| 1077 |
+
return self._atom_conversions.get(expr, sympify(expr))
|
| 1078 |
+
|
| 1079 |
+
return recurse(full_form_list)
|
| 1080 |
+
|
| 1081 |
+
def _from_fullformsympy_to_sympy(self, mform):
|
| 1082 |
+
|
| 1083 |
+
expr = mform
|
| 1084 |
+
for mma_form, sympy_node in self._node_conversions.items():
|
| 1085 |
+
expr = expr.replace(Function(mma_form), sympy_node)
|
| 1086 |
+
return expr
|
vllm/lib/python3.10/site-packages/sympy/parsing/maxima.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from sympy.concrete.products import product
|
| 3 |
+
from sympy.concrete.summations import Sum
|
| 4 |
+
from sympy.core.sympify import sympify
|
| 5 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class MaximaHelpers:
|
| 9 |
+
def maxima_expand(expr):
|
| 10 |
+
return expr.expand()
|
| 11 |
+
|
| 12 |
+
def maxima_float(expr):
|
| 13 |
+
return expr.evalf()
|
| 14 |
+
|
| 15 |
+
def maxima_trigexpand(expr):
|
| 16 |
+
return expr.expand(trig=True)
|
| 17 |
+
|
| 18 |
+
def maxima_sum(a1, a2, a3, a4):
|
| 19 |
+
return Sum(a1, (a2, a3, a4)).doit()
|
| 20 |
+
|
| 21 |
+
def maxima_product(a1, a2, a3, a4):
|
| 22 |
+
return product(a1, (a2, a3, a4))
|
| 23 |
+
|
| 24 |
+
def maxima_csc(expr):
|
| 25 |
+
return 1/sin(expr)
|
| 26 |
+
|
| 27 |
+
def maxima_sec(expr):
|
| 28 |
+
return 1/cos(expr)
|
| 29 |
+
|
| 30 |
+
sub_dict = {
|
| 31 |
+
'pi': re.compile(r'%pi'),
|
| 32 |
+
'E': re.compile(r'%e'),
|
| 33 |
+
'I': re.compile(r'%i'),
|
| 34 |
+
'**': re.compile(r'\^'),
|
| 35 |
+
'oo': re.compile(r'\binf\b'),
|
| 36 |
+
'-oo': re.compile(r'\bminf\b'),
|
| 37 |
+
"'-'": re.compile(r'\bminus\b'),
|
| 38 |
+
'maxima_expand': re.compile(r'\bexpand\b'),
|
| 39 |
+
'maxima_float': re.compile(r'\bfloat\b'),
|
| 40 |
+
'maxima_trigexpand': re.compile(r'\btrigexpand'),
|
| 41 |
+
'maxima_sum': re.compile(r'\bsum\b'),
|
| 42 |
+
'maxima_product': re.compile(r'\bproduct\b'),
|
| 43 |
+
'cancel': re.compile(r'\bratsimp\b'),
|
| 44 |
+
'maxima_csc': re.compile(r'\bcsc\b'),
|
| 45 |
+
'maxima_sec': re.compile(r'\bsec\b')
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
var_name = re.compile(r'^\s*(\w+)\s*:')
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def parse_maxima(str, globals=None, name_dict={}):
|
| 52 |
+
str = str.strip()
|
| 53 |
+
str = str.rstrip('; ')
|
| 54 |
+
|
| 55 |
+
for k, v in sub_dict.items():
|
| 56 |
+
str = v.sub(k, str)
|
| 57 |
+
|
| 58 |
+
assign_var = None
|
| 59 |
+
var_match = var_name.search(str)
|
| 60 |
+
if var_match:
|
| 61 |
+
assign_var = var_match.group(1)
|
| 62 |
+
str = str[var_match.end():].strip()
|
| 63 |
+
|
| 64 |
+
dct = MaximaHelpers.__dict__.copy()
|
| 65 |
+
dct.update(name_dict)
|
| 66 |
+
obj = sympify(str, locals=dct)
|
| 67 |
+
|
| 68 |
+
if assign_var and globals:
|
| 69 |
+
globals[assign_var] = obj
|
| 70 |
+
|
| 71 |
+
return obj
|
vllm/lib/python3.10/site-packages/sympy/parsing/sym_expr.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.printing import pycode, ccode, fcode
|
| 2 |
+
from sympy.external import import_module
|
| 3 |
+
from sympy.utilities.decorator import doctest_depends_on
|
| 4 |
+
|
| 5 |
+
lfortran = import_module('lfortran')
|
| 6 |
+
cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
|
| 7 |
+
|
| 8 |
+
if lfortran:
|
| 9 |
+
from sympy.parsing.fortran.fortran_parser import src_to_sympy
|
| 10 |
+
if cin:
|
| 11 |
+
from sympy.parsing.c.c_parser import parse_c
|
| 12 |
+
|
| 13 |
+
@doctest_depends_on(modules=['lfortran', 'clang.cindex'])
|
| 14 |
+
class SymPyExpression: # type: ignore
|
| 15 |
+
"""Class to store and handle SymPy expressions
|
| 16 |
+
|
| 17 |
+
This class will hold SymPy Expressions and handle the API for the
|
| 18 |
+
conversion to and from different languages.
|
| 19 |
+
|
| 20 |
+
It works with the C and the Fortran Parser to generate SymPy expressions
|
| 21 |
+
which are stored here and which can be converted to multiple language's
|
| 22 |
+
source code.
|
| 23 |
+
|
| 24 |
+
Notes
|
| 25 |
+
=====
|
| 26 |
+
|
| 27 |
+
The module and its API are currently under development and experimental
|
| 28 |
+
and can be changed during development.
|
| 29 |
+
|
| 30 |
+
The Fortran parser does not support numeric assignments, so all the
|
| 31 |
+
variables have been Initialized to zero.
|
| 32 |
+
|
| 33 |
+
The module also depends on external dependencies:
|
| 34 |
+
|
| 35 |
+
- LFortran which is required to use the Fortran parser
|
| 36 |
+
- Clang which is required for the C parser
|
| 37 |
+
|
| 38 |
+
Examples
|
| 39 |
+
========
|
| 40 |
+
|
| 41 |
+
Example of parsing C code:
|
| 42 |
+
|
| 43 |
+
>>> from sympy.parsing.sym_expr import SymPyExpression
|
| 44 |
+
>>> src = '''
|
| 45 |
+
... int a,b;
|
| 46 |
+
... float c = 2, d =4;
|
| 47 |
+
... '''
|
| 48 |
+
>>> a = SymPyExpression(src, 'c')
|
| 49 |
+
>>> a.return_expr()
|
| 50 |
+
[Declaration(Variable(a, type=intc)),
|
| 51 |
+
Declaration(Variable(b, type=intc)),
|
| 52 |
+
Declaration(Variable(c, type=float32, value=2.0)),
|
| 53 |
+
Declaration(Variable(d, type=float32, value=4.0))]
|
| 54 |
+
|
| 55 |
+
An example of variable definition:
|
| 56 |
+
|
| 57 |
+
>>> from sympy.parsing.sym_expr import SymPyExpression
|
| 58 |
+
>>> src2 = '''
|
| 59 |
+
... integer :: a, b, c, d
|
| 60 |
+
... real :: p, q, r, s
|
| 61 |
+
... '''
|
| 62 |
+
>>> p = SymPyExpression()
|
| 63 |
+
>>> p.convert_to_expr(src2, 'f')
|
| 64 |
+
>>> p.convert_to_c()
|
| 65 |
+
['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']
|
| 66 |
+
|
| 67 |
+
An example of Assignment:
|
| 68 |
+
|
| 69 |
+
>>> from sympy.parsing.sym_expr import SymPyExpression
|
| 70 |
+
>>> src3 = '''
|
| 71 |
+
... integer :: a, b, c, d, e
|
| 72 |
+
... d = a + b - c
|
| 73 |
+
... e = b * d + c * e / a
|
| 74 |
+
... '''
|
| 75 |
+
>>> p = SymPyExpression(src3, 'f')
|
| 76 |
+
>>> p.convert_to_python()
|
| 77 |
+
['a = 0', 'b = 0', 'c = 0', 'd = 0', 'e = 0', 'd = a + b - c', 'e = b*d + c*e/a']
|
| 78 |
+
|
| 79 |
+
An example of function definition:
|
| 80 |
+
|
| 81 |
+
>>> from sympy.parsing.sym_expr import SymPyExpression
|
| 82 |
+
>>> src = '''
|
| 83 |
+
... integer function f(a,b)
|
| 84 |
+
... integer, intent(in) :: a, b
|
| 85 |
+
... integer :: r
|
| 86 |
+
... end function
|
| 87 |
+
... '''
|
| 88 |
+
>>> a = SymPyExpression(src, 'f')
|
| 89 |
+
>>> a.convert_to_python()
|
| 90 |
+
['def f(a, b):\\n f = 0\\n r = 0\\n return f']
|
| 91 |
+
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(self, source_code = None, mode = None):
|
| 95 |
+
"""Constructor for SymPyExpression class"""
|
| 96 |
+
super().__init__()
|
| 97 |
+
if not(mode or source_code):
|
| 98 |
+
self._expr = []
|
| 99 |
+
elif mode:
|
| 100 |
+
if source_code:
|
| 101 |
+
if mode.lower() == 'f':
|
| 102 |
+
if lfortran:
|
| 103 |
+
self._expr = src_to_sympy(source_code)
|
| 104 |
+
else:
|
| 105 |
+
raise ImportError("LFortran is not installed, cannot parse Fortran code")
|
| 106 |
+
elif mode.lower() == 'c':
|
| 107 |
+
if cin:
|
| 108 |
+
self._expr = parse_c(source_code)
|
| 109 |
+
else:
|
| 110 |
+
raise ImportError("Clang is not installed, cannot parse C code")
|
| 111 |
+
else:
|
| 112 |
+
raise NotImplementedError(
|
| 113 |
+
'Parser for specified language is not implemented'
|
| 114 |
+
)
|
| 115 |
+
else:
|
| 116 |
+
raise ValueError('Source code not present')
|
| 117 |
+
else:
|
| 118 |
+
raise ValueError('Please specify a mode for conversion')
|
| 119 |
+
|
| 120 |
+
def convert_to_expr(self, src_code, mode):
|
| 121 |
+
"""Converts the given source code to SymPy Expressions
|
| 122 |
+
|
| 123 |
+
Attributes
|
| 124 |
+
==========
|
| 125 |
+
|
| 126 |
+
src_code : String
|
| 127 |
+
the source code or filename of the source code that is to be
|
| 128 |
+
converted
|
| 129 |
+
|
| 130 |
+
mode: String
|
| 131 |
+
the mode to determine which parser is to be used according to
|
| 132 |
+
the language of the source code
|
| 133 |
+
f or F for Fortran
|
| 134 |
+
c or C for C/C++
|
| 135 |
+
|
| 136 |
+
Examples
|
| 137 |
+
========
|
| 138 |
+
|
| 139 |
+
>>> from sympy.parsing.sym_expr import SymPyExpression
|
| 140 |
+
>>> src3 = '''
|
| 141 |
+
... integer function f(a,b) result(r)
|
| 142 |
+
... integer, intent(in) :: a, b
|
| 143 |
+
... integer :: x
|
| 144 |
+
... r = a + b -x
|
| 145 |
+
... end function
|
| 146 |
+
... '''
|
| 147 |
+
>>> p = SymPyExpression()
|
| 148 |
+
>>> p.convert_to_expr(src3, 'f')
|
| 149 |
+
>>> p.return_expr()
|
| 150 |
+
[FunctionDefinition(integer, name=f, parameters=(Variable(a), Variable(b)), body=CodeBlock(
|
| 151 |
+
Declaration(Variable(r, type=integer, value=0)),
|
| 152 |
+
Declaration(Variable(x, type=integer, value=0)),
|
| 153 |
+
Assignment(Variable(r), a + b - x),
|
| 154 |
+
Return(Variable(r))
|
| 155 |
+
))]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
"""
|
| 161 |
+
if mode.lower() == 'f':
|
| 162 |
+
if lfortran:
|
| 163 |
+
self._expr = src_to_sympy(src_code)
|
| 164 |
+
else:
|
| 165 |
+
raise ImportError("LFortran is not installed, cannot parse Fortran code")
|
| 166 |
+
elif mode.lower() == 'c':
|
| 167 |
+
if cin:
|
| 168 |
+
self._expr = parse_c(src_code)
|
| 169 |
+
else:
|
| 170 |
+
raise ImportError("Clang is not installed, cannot parse C code")
|
| 171 |
+
else:
|
| 172 |
+
raise NotImplementedError(
|
| 173 |
+
"Parser for specified language has not been implemented"
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
def convert_to_python(self):
|
| 177 |
+
"""Returns a list with Python code for the SymPy expressions
|
| 178 |
+
|
| 179 |
+
Examples
|
| 180 |
+
========
|
| 181 |
+
|
| 182 |
+
>>> from sympy.parsing.sym_expr import SymPyExpression
|
| 183 |
+
>>> src2 = '''
|
| 184 |
+
... integer :: a, b, c, d
|
| 185 |
+
... real :: p, q, r, s
|
| 186 |
+
... c = a/b
|
| 187 |
+
... d = c/a
|
| 188 |
+
... s = p/q
|
| 189 |
+
... r = q/p
|
| 190 |
+
... '''
|
| 191 |
+
>>> p = SymPyExpression(src2, 'f')
|
| 192 |
+
>>> p.convert_to_python()
|
| 193 |
+
['a = 0', 'b = 0', 'c = 0', 'd = 0', 'p = 0.0', 'q = 0.0', 'r = 0.0', 's = 0.0', 'c = a/b', 'd = c/a', 's = p/q', 'r = q/p']
|
| 194 |
+
|
| 195 |
+
"""
|
| 196 |
+
self._pycode = []
|
| 197 |
+
for iter in self._expr:
|
| 198 |
+
self._pycode.append(pycode(iter))
|
| 199 |
+
return self._pycode
|
| 200 |
+
|
| 201 |
+
def convert_to_c(self):
|
| 202 |
+
"""Returns a list with the c source code for the SymPy expressions
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
Examples
|
| 206 |
+
========
|
| 207 |
+
|
| 208 |
+
>>> from sympy.parsing.sym_expr import SymPyExpression
|
| 209 |
+
>>> src2 = '''
|
| 210 |
+
... integer :: a, b, c, d
|
| 211 |
+
... real :: p, q, r, s
|
| 212 |
+
... c = a/b
|
| 213 |
+
... d = c/a
|
| 214 |
+
... s = p/q
|
| 215 |
+
... r = q/p
|
| 216 |
+
... '''
|
| 217 |
+
>>> p = SymPyExpression()
|
| 218 |
+
>>> p.convert_to_expr(src2, 'f')
|
| 219 |
+
>>> p.convert_to_c()
|
| 220 |
+
['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', 'c = a/b;', 'd = c/a;', 's = p/q;', 'r = q/p;']
|
| 221 |
+
|
| 222 |
+
"""
|
| 223 |
+
self._ccode = []
|
| 224 |
+
for iter in self._expr:
|
| 225 |
+
self._ccode.append(ccode(iter))
|
| 226 |
+
return self._ccode
|
| 227 |
+
|
| 228 |
+
def convert_to_fortran(self):
|
| 229 |
+
"""Returns a list with the fortran source code for the SymPy expressions
|
| 230 |
+
|
| 231 |
+
Examples
|
| 232 |
+
========
|
| 233 |
+
|
| 234 |
+
>>> from sympy.parsing.sym_expr import SymPyExpression
|
| 235 |
+
>>> src2 = '''
|
| 236 |
+
... integer :: a, b, c, d
|
| 237 |
+
... real :: p, q, r, s
|
| 238 |
+
... c = a/b
|
| 239 |
+
... d = c/a
|
| 240 |
+
... s = p/q
|
| 241 |
+
... r = q/p
|
| 242 |
+
... '''
|
| 243 |
+
>>> p = SymPyExpression(src2, 'f')
|
| 244 |
+
>>> p.convert_to_fortran()
|
| 245 |
+
[' integer*4 a', ' integer*4 b', ' integer*4 c', ' integer*4 d', ' real*8 p', ' real*8 q', ' real*8 r', ' real*8 s', ' c = a/b', ' d = c/a', ' s = p/q', ' r = q/p']
|
| 246 |
+
|
| 247 |
+
"""
|
| 248 |
+
self._fcode = []
|
| 249 |
+
for iter in self._expr:
|
| 250 |
+
self._fcode.append(fcode(iter))
|
| 251 |
+
return self._fcode
|
| 252 |
+
|
| 253 |
+
def return_expr(self):
|
| 254 |
+
"""Returns the expression list
|
| 255 |
+
|
| 256 |
+
Examples
|
| 257 |
+
========
|
| 258 |
+
|
| 259 |
+
>>> from sympy.parsing.sym_expr import SymPyExpression
|
| 260 |
+
>>> src3 = '''
|
| 261 |
+
... integer function f(a,b)
|
| 262 |
+
... integer, intent(in) :: a, b
|
| 263 |
+
... integer :: r
|
| 264 |
+
... r = a+b
|
| 265 |
+
... f = r
|
| 266 |
+
... end function
|
| 267 |
+
... '''
|
| 268 |
+
>>> p = SymPyExpression()
|
| 269 |
+
>>> p.convert_to_expr(src3, 'f')
|
| 270 |
+
>>> p.return_expr()
|
| 271 |
+
[FunctionDefinition(integer, name=f, parameters=(Variable(a), Variable(b)), body=CodeBlock(
|
| 272 |
+
Declaration(Variable(f, type=integer, value=0)),
|
| 273 |
+
Declaration(Variable(r, type=integer, value=0)),
|
| 274 |
+
Assignment(Variable(f), Variable(r)),
|
| 275 |
+
Return(Variable(f))
|
| 276 |
+
))]
|
| 277 |
+
|
| 278 |
+
"""
|
| 279 |
+
return self._expr
|
vllm/lib/python3.10/site-packages/sympy/parsing/sympy_parser.py
ADDED
|
@@ -0,0 +1,1257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transform a string with Python-like source code into SymPy expression. """
|
| 2 |
+
|
| 3 |
+
from tokenize import (generate_tokens, untokenize, TokenError,
|
| 4 |
+
NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN, NEWLINE)
|
| 5 |
+
|
| 6 |
+
from keyword import iskeyword
|
| 7 |
+
|
| 8 |
+
import ast
|
| 9 |
+
import unicodedata
|
| 10 |
+
from io import StringIO
|
| 11 |
+
import builtins
|
| 12 |
+
import types
|
| 13 |
+
from typing import Tuple as tTuple, Dict as tDict, Any, Callable, \
|
| 14 |
+
List, Optional, Union as tUnion
|
| 15 |
+
|
| 16 |
+
from sympy.assumptions.ask import AssumptionKeys
|
| 17 |
+
from sympy.core.basic import Basic
|
| 18 |
+
from sympy.core import Symbol
|
| 19 |
+
from sympy.core.function import Function
|
| 20 |
+
from sympy.utilities.misc import func_name
|
| 21 |
+
from sympy.functions.elementary.miscellaneous import Max, Min
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
null = ''
|
| 25 |
+
|
| 26 |
+
TOKEN = tTuple[int, str]
|
| 27 |
+
DICT = tDict[str, Any]
|
| 28 |
+
TRANS = Callable[[List[TOKEN], DICT, DICT], List[TOKEN]]
|
| 29 |
+
|
| 30 |
+
def _token_splittable(token_name: str) -> bool:
|
| 31 |
+
"""
|
| 32 |
+
Predicate for whether a token name can be split into multiple tokens.
|
| 33 |
+
|
| 34 |
+
A token is splittable if it does not contain an underscore character and
|
| 35 |
+
it is not the name of a Greek letter. This is used to implicitly convert
|
| 36 |
+
expressions like 'xyz' into 'x*y*z'.
|
| 37 |
+
"""
|
| 38 |
+
if '_' in token_name:
|
| 39 |
+
return False
|
| 40 |
+
try:
|
| 41 |
+
return not unicodedata.lookup('GREEK SMALL LETTER ' + token_name)
|
| 42 |
+
except KeyError:
|
| 43 |
+
return len(token_name) > 1
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _token_callable(token: TOKEN, local_dict: DICT, global_dict: DICT, nextToken=None):
|
| 47 |
+
"""
|
| 48 |
+
Predicate for whether a token name represents a callable function.
|
| 49 |
+
|
| 50 |
+
Essentially wraps ``callable``, but looks up the token name in the
|
| 51 |
+
locals and globals.
|
| 52 |
+
"""
|
| 53 |
+
func = local_dict.get(token[1])
|
| 54 |
+
if not func:
|
| 55 |
+
func = global_dict.get(token[1])
|
| 56 |
+
return callable(func) and not isinstance(func, Symbol)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _add_factorial_tokens(name: str, result: List[TOKEN]) -> List[TOKEN]:
|
| 60 |
+
if result == [] or result[-1][1] == '(':
|
| 61 |
+
raise TokenError()
|
| 62 |
+
|
| 63 |
+
beginning = [(NAME, name), (OP, '(')]
|
| 64 |
+
end = [(OP, ')')]
|
| 65 |
+
|
| 66 |
+
diff = 0
|
| 67 |
+
length = len(result)
|
| 68 |
+
|
| 69 |
+
for index, token in enumerate(result[::-1]):
|
| 70 |
+
toknum, tokval = token
|
| 71 |
+
i = length - index - 1
|
| 72 |
+
|
| 73 |
+
if tokval == ')':
|
| 74 |
+
diff += 1
|
| 75 |
+
elif tokval == '(':
|
| 76 |
+
diff -= 1
|
| 77 |
+
|
| 78 |
+
if diff == 0:
|
| 79 |
+
if i - 1 >= 0 and result[i - 1][0] == NAME:
|
| 80 |
+
return result[:i - 1] + beginning + result[i - 1:] + end
|
| 81 |
+
else:
|
| 82 |
+
return result[:i] + beginning + result[i:] + end
|
| 83 |
+
|
| 84 |
+
return result
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class ParenthesisGroup(List[TOKEN]):
|
| 88 |
+
"""List of tokens representing an expression in parentheses."""
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class AppliedFunction:
|
| 93 |
+
"""
|
| 94 |
+
A group of tokens representing a function and its arguments.
|
| 95 |
+
|
| 96 |
+
`exponent` is for handling the shorthand sin^2, ln^2, etc.
|
| 97 |
+
"""
|
| 98 |
+
def __init__(self, function: TOKEN, args: ParenthesisGroup, exponent=None):
|
| 99 |
+
if exponent is None:
|
| 100 |
+
exponent = []
|
| 101 |
+
self.function = function
|
| 102 |
+
self.args = args
|
| 103 |
+
self.exponent = exponent
|
| 104 |
+
self.items = ['function', 'args', 'exponent']
|
| 105 |
+
|
| 106 |
+
def expand(self) -> List[TOKEN]:
|
| 107 |
+
"""Return a list of tokens representing the function"""
|
| 108 |
+
return [self.function, *self.args]
|
| 109 |
+
|
| 110 |
+
def __getitem__(self, index):
|
| 111 |
+
return getattr(self, self.items[index])
|
| 112 |
+
|
| 113 |
+
def __repr__(self):
|
| 114 |
+
return "AppliedFunction(%s, %s, %s)" % (self.function, self.args,
|
| 115 |
+
self.exponent)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _flatten(result: List[tUnion[TOKEN, AppliedFunction]]):
|
| 119 |
+
result2: List[TOKEN] = []
|
| 120 |
+
for tok in result:
|
| 121 |
+
if isinstance(tok, AppliedFunction):
|
| 122 |
+
result2.extend(tok.expand())
|
| 123 |
+
else:
|
| 124 |
+
result2.append(tok)
|
| 125 |
+
return result2
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _group_parentheses(recursor: TRANS):
|
| 129 |
+
def _inner(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 130 |
+
"""Group tokens between parentheses with ParenthesisGroup.
|
| 131 |
+
|
| 132 |
+
Also processes those tokens recursively.
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
result: List[tUnion[TOKEN, ParenthesisGroup]] = []
|
| 136 |
+
stacks: List[ParenthesisGroup] = []
|
| 137 |
+
stacklevel = 0
|
| 138 |
+
for token in tokens:
|
| 139 |
+
if token[0] == OP:
|
| 140 |
+
if token[1] == '(':
|
| 141 |
+
stacks.append(ParenthesisGroup([]))
|
| 142 |
+
stacklevel += 1
|
| 143 |
+
elif token[1] == ')':
|
| 144 |
+
stacks[-1].append(token)
|
| 145 |
+
stack = stacks.pop()
|
| 146 |
+
|
| 147 |
+
if len(stacks) > 0:
|
| 148 |
+
# We don't recurse here since the upper-level stack
|
| 149 |
+
# would reprocess these tokens
|
| 150 |
+
stacks[-1].extend(stack)
|
| 151 |
+
else:
|
| 152 |
+
# Recurse here to handle nested parentheses
|
| 153 |
+
# Strip off the outer parentheses to avoid an infinite loop
|
| 154 |
+
inner = stack[1:-1]
|
| 155 |
+
inner = recursor(inner,
|
| 156 |
+
local_dict,
|
| 157 |
+
global_dict)
|
| 158 |
+
parenGroup = [stack[0]] + inner + [stack[-1]]
|
| 159 |
+
result.append(ParenthesisGroup(parenGroup))
|
| 160 |
+
stacklevel -= 1
|
| 161 |
+
continue
|
| 162 |
+
if stacklevel:
|
| 163 |
+
stacks[-1].append(token)
|
| 164 |
+
else:
|
| 165 |
+
result.append(token)
|
| 166 |
+
if stacklevel:
|
| 167 |
+
raise TokenError("Mismatched parentheses")
|
| 168 |
+
return result
|
| 169 |
+
return _inner
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _apply_functions(tokens: List[tUnion[TOKEN, ParenthesisGroup]], local_dict: DICT, global_dict: DICT):
|
| 173 |
+
"""Convert a NAME token + ParenthesisGroup into an AppliedFunction.
|
| 174 |
+
|
| 175 |
+
Note that ParenthesisGroups, if not applied to any function, are
|
| 176 |
+
converted back into lists of tokens.
|
| 177 |
+
|
| 178 |
+
"""
|
| 179 |
+
result: List[tUnion[TOKEN, AppliedFunction]] = []
|
| 180 |
+
symbol = None
|
| 181 |
+
for tok in tokens:
|
| 182 |
+
if isinstance(tok, ParenthesisGroup):
|
| 183 |
+
if symbol and _token_callable(symbol, local_dict, global_dict):
|
| 184 |
+
result[-1] = AppliedFunction(symbol, tok)
|
| 185 |
+
symbol = None
|
| 186 |
+
else:
|
| 187 |
+
result.extend(tok)
|
| 188 |
+
elif tok[0] == NAME:
|
| 189 |
+
symbol = tok
|
| 190 |
+
result.append(tok)
|
| 191 |
+
else:
|
| 192 |
+
symbol = None
|
| 193 |
+
result.append(tok)
|
| 194 |
+
return result
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def _implicit_multiplication(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT):
|
| 198 |
+
"""Implicitly adds '*' tokens.
|
| 199 |
+
|
| 200 |
+
Cases:
|
| 201 |
+
|
| 202 |
+
- Two AppliedFunctions next to each other ("sin(x)cos(x)")
|
| 203 |
+
|
| 204 |
+
- AppliedFunction next to an open parenthesis ("sin x (cos x + 1)")
|
| 205 |
+
|
| 206 |
+
- A close parenthesis next to an AppliedFunction ("(x+2)sin x")\
|
| 207 |
+
|
| 208 |
+
- A close parenthesis next to an open parenthesis ("(x+2)(x+3)")
|
| 209 |
+
|
| 210 |
+
- AppliedFunction next to an implicitly applied function ("sin(x)cos x")
|
| 211 |
+
|
| 212 |
+
"""
|
| 213 |
+
result: List[tUnion[TOKEN, AppliedFunction]] = []
|
| 214 |
+
skip = False
|
| 215 |
+
for tok, nextTok in zip(tokens, tokens[1:]):
|
| 216 |
+
result.append(tok)
|
| 217 |
+
if skip:
|
| 218 |
+
skip = False
|
| 219 |
+
continue
|
| 220 |
+
if tok[0] == OP and tok[1] == '.' and nextTok[0] == NAME:
|
| 221 |
+
# Dotted name. Do not do implicit multiplication
|
| 222 |
+
skip = True
|
| 223 |
+
continue
|
| 224 |
+
if isinstance(tok, AppliedFunction):
|
| 225 |
+
if isinstance(nextTok, AppliedFunction):
|
| 226 |
+
result.append((OP, '*'))
|
| 227 |
+
elif nextTok == (OP, '('):
|
| 228 |
+
# Applied function followed by an open parenthesis
|
| 229 |
+
if tok.function[1] == "Function":
|
| 230 |
+
tok.function = (tok.function[0], 'Symbol')
|
| 231 |
+
result.append((OP, '*'))
|
| 232 |
+
elif nextTok[0] == NAME:
|
| 233 |
+
# Applied function followed by implicitly applied function
|
| 234 |
+
result.append((OP, '*'))
|
| 235 |
+
else:
|
| 236 |
+
if tok == (OP, ')'):
|
| 237 |
+
if isinstance(nextTok, AppliedFunction):
|
| 238 |
+
# Close parenthesis followed by an applied function
|
| 239 |
+
result.append((OP, '*'))
|
| 240 |
+
elif nextTok[0] == NAME:
|
| 241 |
+
# Close parenthesis followed by an implicitly applied function
|
| 242 |
+
result.append((OP, '*'))
|
| 243 |
+
elif nextTok == (OP, '('):
|
| 244 |
+
# Close parenthesis followed by an open parenthesis
|
| 245 |
+
result.append((OP, '*'))
|
| 246 |
+
elif tok[0] == NAME and not _token_callable(tok, local_dict, global_dict):
|
| 247 |
+
if isinstance(nextTok, AppliedFunction) or \
|
| 248 |
+
(nextTok[0] == NAME and _token_callable(nextTok, local_dict, global_dict)):
|
| 249 |
+
# Constant followed by (implicitly applied) function
|
| 250 |
+
result.append((OP, '*'))
|
| 251 |
+
elif nextTok == (OP, '('):
|
| 252 |
+
# Constant followed by parenthesis
|
| 253 |
+
result.append((OP, '*'))
|
| 254 |
+
elif nextTok[0] == NAME:
|
| 255 |
+
# Constant followed by constant
|
| 256 |
+
result.append((OP, '*'))
|
| 257 |
+
if tokens:
|
| 258 |
+
result.append(tokens[-1])
|
| 259 |
+
return result
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _implicit_application(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT):
|
| 263 |
+
"""Adds parentheses as needed after functions."""
|
| 264 |
+
result: List[tUnion[TOKEN, AppliedFunction]] = []
|
| 265 |
+
appendParen = 0 # number of closing parentheses to add
|
| 266 |
+
skip = 0 # number of tokens to delay before adding a ')' (to
|
| 267 |
+
# capture **, ^, etc.)
|
| 268 |
+
exponentSkip = False # skipping tokens before inserting parentheses to
|
| 269 |
+
# work with function exponentiation
|
| 270 |
+
for tok, nextTok in zip(tokens, tokens[1:]):
|
| 271 |
+
result.append(tok)
|
| 272 |
+
if (tok[0] == NAME and nextTok[0] not in [OP, ENDMARKER, NEWLINE]):
|
| 273 |
+
if _token_callable(tok, local_dict, global_dict, nextTok): # type: ignore
|
| 274 |
+
result.append((OP, '('))
|
| 275 |
+
appendParen += 1
|
| 276 |
+
# name followed by exponent - function exponentiation
|
| 277 |
+
elif (tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**'):
|
| 278 |
+
if _token_callable(tok, local_dict, global_dict): # type: ignore
|
| 279 |
+
exponentSkip = True
|
| 280 |
+
elif exponentSkip:
|
| 281 |
+
# if the last token added was an applied function (i.e. the
|
| 282 |
+
# power of the function exponent) OR a multiplication (as
|
| 283 |
+
# implicit multiplication would have added an extraneous
|
| 284 |
+
# multiplication)
|
| 285 |
+
if (isinstance(tok, AppliedFunction)
|
| 286 |
+
or (tok[0] == OP and tok[1] == '*')):
|
| 287 |
+
# don't add anything if the next token is a multiplication
|
| 288 |
+
# or if there's already a parenthesis (if parenthesis, still
|
| 289 |
+
# stop skipping tokens)
|
| 290 |
+
if not (nextTok[0] == OP and nextTok[1] == '*'):
|
| 291 |
+
if not(nextTok[0] == OP and nextTok[1] == '('):
|
| 292 |
+
result.append((OP, '('))
|
| 293 |
+
appendParen += 1
|
| 294 |
+
exponentSkip = False
|
| 295 |
+
elif appendParen:
|
| 296 |
+
if nextTok[0] == OP and nextTok[1] in ('^', '**', '*'):
|
| 297 |
+
skip = 1
|
| 298 |
+
continue
|
| 299 |
+
if skip:
|
| 300 |
+
skip -= 1
|
| 301 |
+
continue
|
| 302 |
+
result.append((OP, ')'))
|
| 303 |
+
appendParen -= 1
|
| 304 |
+
|
| 305 |
+
if tokens:
|
| 306 |
+
result.append(tokens[-1])
|
| 307 |
+
|
| 308 |
+
if appendParen:
|
| 309 |
+
result.extend([(OP, ')')] * appendParen)
|
| 310 |
+
return result
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def function_exponentiation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 314 |
+
"""Allows functions to be exponentiated, e.g. ``cos**2(x)``.
|
| 315 |
+
|
| 316 |
+
Examples
|
| 317 |
+
========
|
| 318 |
+
|
| 319 |
+
>>> from sympy.parsing.sympy_parser import (parse_expr,
|
| 320 |
+
... standard_transformations, function_exponentiation)
|
| 321 |
+
>>> transformations = standard_transformations + (function_exponentiation,)
|
| 322 |
+
>>> parse_expr('sin**4(x)', transformations=transformations)
|
| 323 |
+
sin(x)**4
|
| 324 |
+
"""
|
| 325 |
+
result: List[TOKEN] = []
|
| 326 |
+
exponent: List[TOKEN] = []
|
| 327 |
+
consuming_exponent = False
|
| 328 |
+
level = 0
|
| 329 |
+
for tok, nextTok in zip(tokens, tokens[1:]):
|
| 330 |
+
if tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**':
|
| 331 |
+
if _token_callable(tok, local_dict, global_dict):
|
| 332 |
+
consuming_exponent = True
|
| 333 |
+
elif consuming_exponent:
|
| 334 |
+
if tok[0] == NAME and tok[1] == 'Function':
|
| 335 |
+
tok = (NAME, 'Symbol')
|
| 336 |
+
exponent.append(tok)
|
| 337 |
+
|
| 338 |
+
# only want to stop after hitting )
|
| 339 |
+
if tok[0] == nextTok[0] == OP and tok[1] == ')' and nextTok[1] == '(':
|
| 340 |
+
consuming_exponent = False
|
| 341 |
+
# if implicit multiplication was used, we may have )*( instead
|
| 342 |
+
if tok[0] == nextTok[0] == OP and tok[1] == '*' and nextTok[1] == '(':
|
| 343 |
+
consuming_exponent = False
|
| 344 |
+
del exponent[-1]
|
| 345 |
+
continue
|
| 346 |
+
elif exponent and not consuming_exponent:
|
| 347 |
+
if tok[0] == OP:
|
| 348 |
+
if tok[1] == '(':
|
| 349 |
+
level += 1
|
| 350 |
+
elif tok[1] == ')':
|
| 351 |
+
level -= 1
|
| 352 |
+
if level == 0:
|
| 353 |
+
result.append(tok)
|
| 354 |
+
result.extend(exponent)
|
| 355 |
+
exponent = []
|
| 356 |
+
continue
|
| 357 |
+
result.append(tok)
|
| 358 |
+
if tokens:
|
| 359 |
+
result.append(tokens[-1])
|
| 360 |
+
if exponent:
|
| 361 |
+
result.extend(exponent)
|
| 362 |
+
return result
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def split_symbols_custom(predicate: Callable[[str], bool]):
|
| 366 |
+
"""Creates a transformation that splits symbol names.
|
| 367 |
+
|
| 368 |
+
``predicate`` should return True if the symbol name is to be split.
|
| 369 |
+
|
| 370 |
+
For instance, to retain the default behavior but avoid splitting certain
|
| 371 |
+
symbol names, a predicate like this would work:
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
>>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable,
|
| 375 |
+
... standard_transformations, implicit_multiplication,
|
| 376 |
+
... split_symbols_custom)
|
| 377 |
+
>>> def can_split(symbol):
|
| 378 |
+
... if symbol not in ('list', 'of', 'unsplittable', 'names'):
|
| 379 |
+
... return _token_splittable(symbol)
|
| 380 |
+
... return False
|
| 381 |
+
...
|
| 382 |
+
>>> transformation = split_symbols_custom(can_split)
|
| 383 |
+
>>> parse_expr('unsplittable', transformations=standard_transformations +
|
| 384 |
+
... (transformation, implicit_multiplication))
|
| 385 |
+
unsplittable
|
| 386 |
+
"""
|
| 387 |
+
def _split_symbols(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 388 |
+
result: List[TOKEN] = []
|
| 389 |
+
split = False
|
| 390 |
+
split_previous=False
|
| 391 |
+
|
| 392 |
+
for tok in tokens:
|
| 393 |
+
if split_previous:
|
| 394 |
+
# throw out closing parenthesis of Symbol that was split
|
| 395 |
+
split_previous=False
|
| 396 |
+
continue
|
| 397 |
+
split_previous=False
|
| 398 |
+
|
| 399 |
+
if tok[0] == NAME and tok[1] in ['Symbol', 'Function']:
|
| 400 |
+
split = True
|
| 401 |
+
|
| 402 |
+
elif split and tok[0] == NAME:
|
| 403 |
+
symbol = tok[1][1:-1]
|
| 404 |
+
|
| 405 |
+
if predicate(symbol):
|
| 406 |
+
tok_type = result[-2][1] # Symbol or Function
|
| 407 |
+
del result[-2:] # Get rid of the call to Symbol
|
| 408 |
+
|
| 409 |
+
i = 0
|
| 410 |
+
while i < len(symbol):
|
| 411 |
+
char = symbol[i]
|
| 412 |
+
if char in local_dict or char in global_dict:
|
| 413 |
+
result.append((NAME, "%s" % char))
|
| 414 |
+
elif char.isdigit():
|
| 415 |
+
chars = [char]
|
| 416 |
+
for i in range(i + 1, len(symbol)):
|
| 417 |
+
if not symbol[i].isdigit():
|
| 418 |
+
i -= 1
|
| 419 |
+
break
|
| 420 |
+
chars.append(symbol[i])
|
| 421 |
+
char = ''.join(chars)
|
| 422 |
+
result.extend([(NAME, 'Number'), (OP, '('),
|
| 423 |
+
(NAME, "'%s'" % char), (OP, ')')])
|
| 424 |
+
else:
|
| 425 |
+
use = tok_type if i == len(symbol) else 'Symbol'
|
| 426 |
+
result.extend([(NAME, use), (OP, '('),
|
| 427 |
+
(NAME, "'%s'" % char), (OP, ')')])
|
| 428 |
+
i += 1
|
| 429 |
+
|
| 430 |
+
# Set split_previous=True so will skip
|
| 431 |
+
# the closing parenthesis of the original Symbol
|
| 432 |
+
split = False
|
| 433 |
+
split_previous = True
|
| 434 |
+
continue
|
| 435 |
+
|
| 436 |
+
else:
|
| 437 |
+
split = False
|
| 438 |
+
|
| 439 |
+
result.append(tok)
|
| 440 |
+
|
| 441 |
+
return result
|
| 442 |
+
|
| 443 |
+
return _split_symbols
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
#: Splits symbol names for implicit multiplication.
|
| 447 |
+
#:
|
| 448 |
+
#: Intended to let expressions like ``xyz`` be parsed as ``x*y*z``. Does not
|
| 449 |
+
#: split Greek character names, so ``theta`` will *not* become
|
| 450 |
+
#: ``t*h*e*t*a``. Generally this should be used with
|
| 451 |
+
#: ``implicit_multiplication``.
|
| 452 |
+
split_symbols = split_symbols_custom(_token_splittable)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def implicit_multiplication(tokens: List[TOKEN], local_dict: DICT,
|
| 456 |
+
global_dict: DICT) -> List[TOKEN]:
|
| 457 |
+
"""Makes the multiplication operator optional in most cases.
|
| 458 |
+
|
| 459 |
+
Use this before :func:`implicit_application`, otherwise expressions like
|
| 460 |
+
``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``.
|
| 461 |
+
|
| 462 |
+
Examples
|
| 463 |
+
========
|
| 464 |
+
|
| 465 |
+
>>> from sympy.parsing.sympy_parser import (parse_expr,
|
| 466 |
+
... standard_transformations, implicit_multiplication)
|
| 467 |
+
>>> transformations = standard_transformations + (implicit_multiplication,)
|
| 468 |
+
>>> parse_expr('3 x y', transformations=transformations)
|
| 469 |
+
3*x*y
|
| 470 |
+
"""
|
| 471 |
+
# These are interdependent steps, so we don't expose them separately
|
| 472 |
+
res1 = _group_parentheses(implicit_multiplication)(tokens, local_dict, global_dict)
|
| 473 |
+
res2 = _apply_functions(res1, local_dict, global_dict)
|
| 474 |
+
res3 = _implicit_multiplication(res2, local_dict, global_dict)
|
| 475 |
+
result = _flatten(res3)
|
| 476 |
+
return result
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def implicit_application(tokens: List[TOKEN], local_dict: DICT,
|
| 480 |
+
global_dict: DICT) -> List[TOKEN]:
|
| 481 |
+
"""Makes parentheses optional in some cases for function calls.
|
| 482 |
+
|
| 483 |
+
Use this after :func:`implicit_multiplication`, otherwise expressions
|
| 484 |
+
like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than
|
| 485 |
+
``sin(2*x)``.
|
| 486 |
+
|
| 487 |
+
Examples
|
| 488 |
+
========
|
| 489 |
+
|
| 490 |
+
>>> from sympy.parsing.sympy_parser import (parse_expr,
|
| 491 |
+
... standard_transformations, implicit_application)
|
| 492 |
+
>>> transformations = standard_transformations + (implicit_application,)
|
| 493 |
+
>>> parse_expr('cot z + csc z', transformations=transformations)
|
| 494 |
+
cot(z) + csc(z)
|
| 495 |
+
"""
|
| 496 |
+
res1 = _group_parentheses(implicit_application)(tokens, local_dict, global_dict)
|
| 497 |
+
res2 = _apply_functions(res1, local_dict, global_dict)
|
| 498 |
+
res3 = _implicit_application(res2, local_dict, global_dict)
|
| 499 |
+
result = _flatten(res3)
|
| 500 |
+
return result
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def implicit_multiplication_application(result: List[TOKEN], local_dict: DICT,
|
| 504 |
+
global_dict: DICT) -> List[TOKEN]:
|
| 505 |
+
"""Allows a slightly relaxed syntax.
|
| 506 |
+
|
| 507 |
+
- Parentheses for single-argument method calls are optional.
|
| 508 |
+
|
| 509 |
+
- Multiplication is implicit.
|
| 510 |
+
|
| 511 |
+
- Symbol names can be split (i.e. spaces are not needed between
|
| 512 |
+
symbols).
|
| 513 |
+
|
| 514 |
+
- Functions can be exponentiated.
|
| 515 |
+
|
| 516 |
+
Examples
|
| 517 |
+
========
|
| 518 |
+
|
| 519 |
+
>>> from sympy.parsing.sympy_parser import (parse_expr,
|
| 520 |
+
... standard_transformations, implicit_multiplication_application)
|
| 521 |
+
>>> parse_expr("10sin**2 x**2 + 3xyz + tan theta",
|
| 522 |
+
... transformations=(standard_transformations +
|
| 523 |
+
... (implicit_multiplication_application,)))
|
| 524 |
+
3*x*y*z + 10*sin(x**2)**2 + tan(theta)
|
| 525 |
+
|
| 526 |
+
"""
|
| 527 |
+
for step in (split_symbols, implicit_multiplication,
|
| 528 |
+
implicit_application, function_exponentiation):
|
| 529 |
+
result = step(result, local_dict, global_dict)
|
| 530 |
+
|
| 531 |
+
return result
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def auto_symbol(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 535 |
+
"""Inserts calls to ``Symbol``/``Function`` for undefined variables."""
|
| 536 |
+
result: List[TOKEN] = []
|
| 537 |
+
prevTok = (-1, '')
|
| 538 |
+
|
| 539 |
+
tokens.append((-1, '')) # so zip traverses all tokens
|
| 540 |
+
for tok, nextTok in zip(tokens, tokens[1:]):
|
| 541 |
+
tokNum, tokVal = tok
|
| 542 |
+
nextTokNum, nextTokVal = nextTok
|
| 543 |
+
if tokNum == NAME:
|
| 544 |
+
name = tokVal
|
| 545 |
+
|
| 546 |
+
if (name in ['True', 'False', 'None']
|
| 547 |
+
or iskeyword(name)
|
| 548 |
+
# Don't convert attribute access
|
| 549 |
+
or (prevTok[0] == OP and prevTok[1] == '.')
|
| 550 |
+
# Don't convert keyword arguments
|
| 551 |
+
or (prevTok[0] == OP and prevTok[1] in ('(', ',')
|
| 552 |
+
and nextTokNum == OP and nextTokVal == '=')
|
| 553 |
+
# the name has already been defined
|
| 554 |
+
or name in local_dict and local_dict[name] is not null):
|
| 555 |
+
result.append((NAME, name))
|
| 556 |
+
continue
|
| 557 |
+
elif name in local_dict:
|
| 558 |
+
local_dict.setdefault(null, set()).add(name)
|
| 559 |
+
if nextTokVal == '(':
|
| 560 |
+
local_dict[name] = Function(name)
|
| 561 |
+
else:
|
| 562 |
+
local_dict[name] = Symbol(name)
|
| 563 |
+
result.append((NAME, name))
|
| 564 |
+
continue
|
| 565 |
+
elif name in global_dict:
|
| 566 |
+
obj = global_dict[name]
|
| 567 |
+
if isinstance(obj, (AssumptionKeys, Basic, type)) or callable(obj):
|
| 568 |
+
result.append((NAME, name))
|
| 569 |
+
continue
|
| 570 |
+
|
| 571 |
+
result.extend([
|
| 572 |
+
(NAME, 'Symbol' if nextTokVal != '(' else 'Function'),
|
| 573 |
+
(OP, '('),
|
| 574 |
+
(NAME, repr(str(name))),
|
| 575 |
+
(OP, ')'),
|
| 576 |
+
])
|
| 577 |
+
else:
|
| 578 |
+
result.append((tokNum, tokVal))
|
| 579 |
+
|
| 580 |
+
prevTok = (tokNum, tokVal)
|
| 581 |
+
|
| 582 |
+
return result
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def lambda_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 586 |
+
"""Substitutes "lambda" with its SymPy equivalent Lambda().
|
| 587 |
+
However, the conversion does not take place if only "lambda"
|
| 588 |
+
is passed because that is a syntax error.
|
| 589 |
+
|
| 590 |
+
"""
|
| 591 |
+
result: List[TOKEN] = []
|
| 592 |
+
flag = False
|
| 593 |
+
toknum, tokval = tokens[0]
|
| 594 |
+
tokLen = len(tokens)
|
| 595 |
+
|
| 596 |
+
if toknum == NAME and tokval == 'lambda':
|
| 597 |
+
if tokLen == 2 or tokLen == 3 and tokens[1][0] == NEWLINE:
|
| 598 |
+
# In Python 3.6.7+, inputs without a newline get NEWLINE added to
|
| 599 |
+
# the tokens
|
| 600 |
+
result.extend(tokens)
|
| 601 |
+
elif tokLen > 2:
|
| 602 |
+
result.extend([
|
| 603 |
+
(NAME, 'Lambda'),
|
| 604 |
+
(OP, '('),
|
| 605 |
+
(OP, '('),
|
| 606 |
+
(OP, ')'),
|
| 607 |
+
(OP, ')'),
|
| 608 |
+
])
|
| 609 |
+
for tokNum, tokVal in tokens[1:]:
|
| 610 |
+
if tokNum == OP and tokVal == ':':
|
| 611 |
+
tokVal = ','
|
| 612 |
+
flag = True
|
| 613 |
+
if not flag and tokNum == OP and tokVal in ('*', '**'):
|
| 614 |
+
raise TokenError("Starred arguments in lambda not supported")
|
| 615 |
+
if flag:
|
| 616 |
+
result.insert(-1, (tokNum, tokVal))
|
| 617 |
+
else:
|
| 618 |
+
result.insert(-2, (tokNum, tokVal))
|
| 619 |
+
else:
|
| 620 |
+
result.extend(tokens)
|
| 621 |
+
|
| 622 |
+
return result
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def factorial_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 626 |
+
"""Allows standard notation for factorial."""
|
| 627 |
+
result: List[TOKEN] = []
|
| 628 |
+
nfactorial = 0
|
| 629 |
+
for toknum, tokval in tokens:
|
| 630 |
+
if toknum == OP and tokval == "!":
|
| 631 |
+
# In Python 3.12 "!" are OP instead of ERRORTOKEN
|
| 632 |
+
nfactorial += 1
|
| 633 |
+
elif toknum == ERRORTOKEN:
|
| 634 |
+
op = tokval
|
| 635 |
+
if op == '!':
|
| 636 |
+
nfactorial += 1
|
| 637 |
+
else:
|
| 638 |
+
nfactorial = 0
|
| 639 |
+
result.append((OP, op))
|
| 640 |
+
else:
|
| 641 |
+
if nfactorial == 1:
|
| 642 |
+
result = _add_factorial_tokens('factorial', result)
|
| 643 |
+
elif nfactorial == 2:
|
| 644 |
+
result = _add_factorial_tokens('factorial2', result)
|
| 645 |
+
elif nfactorial > 2:
|
| 646 |
+
raise TokenError
|
| 647 |
+
nfactorial = 0
|
| 648 |
+
result.append((toknum, tokval))
|
| 649 |
+
return result
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
def convert_xor(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 653 |
+
"""Treats XOR, ``^``, as exponentiation, ``**``."""
|
| 654 |
+
result: List[TOKEN] = []
|
| 655 |
+
for toknum, tokval in tokens:
|
| 656 |
+
if toknum == OP:
|
| 657 |
+
if tokval == '^':
|
| 658 |
+
result.append((OP, '**'))
|
| 659 |
+
else:
|
| 660 |
+
result.append((toknum, tokval))
|
| 661 |
+
else:
|
| 662 |
+
result.append((toknum, tokval))
|
| 663 |
+
|
| 664 |
+
return result
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def repeated_decimals(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 668 |
+
"""
|
| 669 |
+
Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90)
|
| 670 |
+
|
| 671 |
+
Run this before auto_number.
|
| 672 |
+
|
| 673 |
+
"""
|
| 674 |
+
result: List[TOKEN] = []
|
| 675 |
+
|
| 676 |
+
def is_digit(s):
|
| 677 |
+
return all(i in '0123456789_' for i in s)
|
| 678 |
+
|
| 679 |
+
# num will running match any DECIMAL [ INTEGER ]
|
| 680 |
+
num: List[TOKEN] = []
|
| 681 |
+
for toknum, tokval in tokens:
|
| 682 |
+
if toknum == NUMBER:
|
| 683 |
+
if (not num and '.' in tokval and 'e' not in tokval.lower() and
|
| 684 |
+
'j' not in tokval.lower()):
|
| 685 |
+
num.append((toknum, tokval))
|
| 686 |
+
elif is_digit(tokval)and len(num) == 2:
|
| 687 |
+
num.append((toknum, tokval))
|
| 688 |
+
elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]):
|
| 689 |
+
# Python 2 tokenizes 00123 as '00', '123'
|
| 690 |
+
# Python 3 tokenizes 01289 as '012', '89'
|
| 691 |
+
num.append((toknum, tokval))
|
| 692 |
+
else:
|
| 693 |
+
num = []
|
| 694 |
+
elif toknum == OP:
|
| 695 |
+
if tokval == '[' and len(num) == 1:
|
| 696 |
+
num.append((OP, tokval))
|
| 697 |
+
elif tokval == ']' and len(num) >= 3:
|
| 698 |
+
num.append((OP, tokval))
|
| 699 |
+
elif tokval == '.' and not num:
|
| 700 |
+
# handle .[1]
|
| 701 |
+
num.append((NUMBER, '0.'))
|
| 702 |
+
else:
|
| 703 |
+
num = []
|
| 704 |
+
else:
|
| 705 |
+
num = []
|
| 706 |
+
|
| 707 |
+
result.append((toknum, tokval))
|
| 708 |
+
|
| 709 |
+
if num and num[-1][1] == ']':
|
| 710 |
+
# pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post,
|
| 711 |
+
# and d/e = repetend
|
| 712 |
+
result = result[:-len(num)]
|
| 713 |
+
pre, post = num[0][1].split('.')
|
| 714 |
+
repetend = num[2][1]
|
| 715 |
+
if len(num) == 5:
|
| 716 |
+
repetend += num[3][1]
|
| 717 |
+
|
| 718 |
+
pre = pre.replace('_', '')
|
| 719 |
+
post = post.replace('_', '')
|
| 720 |
+
repetend = repetend.replace('_', '')
|
| 721 |
+
|
| 722 |
+
zeros = '0'*len(post)
|
| 723 |
+
post, repetends = [w.lstrip('0') for w in [post, repetend]]
|
| 724 |
+
# or else interpreted as octal
|
| 725 |
+
|
| 726 |
+
a = pre or '0'
|
| 727 |
+
b, c = post or '0', '1' + zeros
|
| 728 |
+
d, e = repetends, ('9'*len(repetend)) + zeros
|
| 729 |
+
|
| 730 |
+
seq = [
|
| 731 |
+
(OP, '('),
|
| 732 |
+
(NAME, 'Integer'),
|
| 733 |
+
(OP, '('),
|
| 734 |
+
(NUMBER, a),
|
| 735 |
+
(OP, ')'),
|
| 736 |
+
(OP, '+'),
|
| 737 |
+
(NAME, 'Rational'),
|
| 738 |
+
(OP, '('),
|
| 739 |
+
(NUMBER, b),
|
| 740 |
+
(OP, ','),
|
| 741 |
+
(NUMBER, c),
|
| 742 |
+
(OP, ')'),
|
| 743 |
+
(OP, '+'),
|
| 744 |
+
(NAME, 'Rational'),
|
| 745 |
+
(OP, '('),
|
| 746 |
+
(NUMBER, d),
|
| 747 |
+
(OP, ','),
|
| 748 |
+
(NUMBER, e),
|
| 749 |
+
(OP, ')'),
|
| 750 |
+
(OP, ')'),
|
| 751 |
+
]
|
| 752 |
+
result.extend(seq)
|
| 753 |
+
num = []
|
| 754 |
+
|
| 755 |
+
return result
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
def auto_number(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 759 |
+
"""
|
| 760 |
+
Converts numeric literals to use SymPy equivalents.
|
| 761 |
+
|
| 762 |
+
Complex numbers use ``I``, integer literals use ``Integer``, and float
|
| 763 |
+
literals use ``Float``.
|
| 764 |
+
|
| 765 |
+
"""
|
| 766 |
+
result: List[TOKEN] = []
|
| 767 |
+
|
| 768 |
+
for toknum, tokval in tokens:
|
| 769 |
+
if toknum == NUMBER:
|
| 770 |
+
number = tokval
|
| 771 |
+
postfix = []
|
| 772 |
+
|
| 773 |
+
if number.endswith(('j', 'J')):
|
| 774 |
+
number = number[:-1]
|
| 775 |
+
postfix = [(OP, '*'), (NAME, 'I')]
|
| 776 |
+
|
| 777 |
+
if '.' in number or (('e' in number or 'E' in number) and
|
| 778 |
+
not (number.startswith(('0x', '0X')))):
|
| 779 |
+
seq = [(NAME, 'Float'), (OP, '('),
|
| 780 |
+
(NUMBER, repr(str(number))), (OP, ')')]
|
| 781 |
+
else:
|
| 782 |
+
seq = [(NAME, 'Integer'), (OP, '('), (
|
| 783 |
+
NUMBER, number), (OP, ')')]
|
| 784 |
+
|
| 785 |
+
result.extend(seq + postfix)
|
| 786 |
+
else:
|
| 787 |
+
result.append((toknum, tokval))
|
| 788 |
+
|
| 789 |
+
return result
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
def rationalize(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 793 |
+
"""Converts floats into ``Rational``. Run AFTER ``auto_number``."""
|
| 794 |
+
result: List[TOKEN] = []
|
| 795 |
+
passed_float = False
|
| 796 |
+
for toknum, tokval in tokens:
|
| 797 |
+
if toknum == NAME:
|
| 798 |
+
if tokval == 'Float':
|
| 799 |
+
passed_float = True
|
| 800 |
+
tokval = 'Rational'
|
| 801 |
+
result.append((toknum, tokval))
|
| 802 |
+
elif passed_float == True and toknum == NUMBER:
|
| 803 |
+
passed_float = False
|
| 804 |
+
result.append((STRING, tokval))
|
| 805 |
+
else:
|
| 806 |
+
result.append((toknum, tokval))
|
| 807 |
+
|
| 808 |
+
return result
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def _transform_equals_sign(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
|
| 812 |
+
"""Transforms the equals sign ``=`` to instances of Eq.
|
| 813 |
+
|
| 814 |
+
This is a helper function for ``convert_equals_signs``.
|
| 815 |
+
Works with expressions containing one equals sign and no
|
| 816 |
+
nesting. Expressions like ``(1=2)=False`` will not work with this
|
| 817 |
+
and should be used with ``convert_equals_signs``.
|
| 818 |
+
|
| 819 |
+
Examples: 1=2 to Eq(1,2)
|
| 820 |
+
1*2=x to Eq(1*2, x)
|
| 821 |
+
|
| 822 |
+
This does not deal with function arguments yet.
|
| 823 |
+
|
| 824 |
+
"""
|
| 825 |
+
result: List[TOKEN] = []
|
| 826 |
+
if (OP, "=") in tokens:
|
| 827 |
+
result.append((NAME, "Eq"))
|
| 828 |
+
result.append((OP, "("))
|
| 829 |
+
for token in tokens:
|
| 830 |
+
if token == (OP, "="):
|
| 831 |
+
result.append((OP, ","))
|
| 832 |
+
continue
|
| 833 |
+
result.append(token)
|
| 834 |
+
result.append((OP, ")"))
|
| 835 |
+
else:
|
| 836 |
+
result = tokens
|
| 837 |
+
return result
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
def convert_equals_signs(tokens: List[TOKEN], local_dict: DICT,
|
| 841 |
+
global_dict: DICT) -> List[TOKEN]:
|
| 842 |
+
""" Transforms all the equals signs ``=`` to instances of Eq.
|
| 843 |
+
|
| 844 |
+
Parses the equals signs in the expression and replaces them with
|
| 845 |
+
appropriate Eq instances. Also works with nested equals signs.
|
| 846 |
+
|
| 847 |
+
Does not yet play well with function arguments.
|
| 848 |
+
For example, the expression ``(x=y)`` is ambiguous and can be interpreted
|
| 849 |
+
as x being an argument to a function and ``convert_equals_signs`` will not
|
| 850 |
+
work for this.
|
| 851 |
+
|
| 852 |
+
See also
|
| 853 |
+
========
|
| 854 |
+
convert_equality_operators
|
| 855 |
+
|
| 856 |
+
Examples
|
| 857 |
+
========
|
| 858 |
+
|
| 859 |
+
>>> from sympy.parsing.sympy_parser import (parse_expr,
|
| 860 |
+
... standard_transformations, convert_equals_signs)
|
| 861 |
+
>>> parse_expr("1*2=x", transformations=(
|
| 862 |
+
... standard_transformations + (convert_equals_signs,)))
|
| 863 |
+
Eq(2, x)
|
| 864 |
+
>>> parse_expr("(1*2=x)=False", transformations=(
|
| 865 |
+
... standard_transformations + (convert_equals_signs,)))
|
| 866 |
+
Eq(Eq(2, x), False)
|
| 867 |
+
|
| 868 |
+
"""
|
| 869 |
+
res1 = _group_parentheses(convert_equals_signs)(tokens, local_dict, global_dict)
|
| 870 |
+
res2 = _apply_functions(res1, local_dict, global_dict)
|
| 871 |
+
res3 = _transform_equals_sign(res2, local_dict, global_dict)
|
| 872 |
+
result = _flatten(res3)
|
| 873 |
+
return result
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
#: Standard transformations for :func:`parse_expr`.
|
| 877 |
+
#: Inserts calls to :class:`~.Symbol`, :class:`~.Integer`, and other SymPy
|
| 878 |
+
#: datatypes and allows the use of standard factorial notation (e.g. ``x!``).
|
| 879 |
+
standard_transformations: tTuple[TRANS, ...] \
|
| 880 |
+
= (lambda_notation, auto_symbol, repeated_decimals, auto_number,
|
| 881 |
+
factorial_notation)
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
def stringify_expr(s: str, local_dict: DICT, global_dict: DICT,
|
| 885 |
+
transformations: tTuple[TRANS, ...]) -> str:
|
| 886 |
+
"""
|
| 887 |
+
Converts the string ``s`` to Python code, in ``local_dict``
|
| 888 |
+
|
| 889 |
+
Generally, ``parse_expr`` should be used.
|
| 890 |
+
"""
|
| 891 |
+
|
| 892 |
+
tokens = []
|
| 893 |
+
input_code = StringIO(s.strip())
|
| 894 |
+
for toknum, tokval, _, _, _ in generate_tokens(input_code.readline):
|
| 895 |
+
tokens.append((toknum, tokval))
|
| 896 |
+
|
| 897 |
+
for transform in transformations:
|
| 898 |
+
tokens = transform(tokens, local_dict, global_dict)
|
| 899 |
+
|
| 900 |
+
return untokenize(tokens)
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def eval_expr(code, local_dict: DICT, global_dict: DICT):
|
| 904 |
+
"""
|
| 905 |
+
Evaluate Python code generated by ``stringify_expr``.
|
| 906 |
+
|
| 907 |
+
Generally, ``parse_expr`` should be used.
|
| 908 |
+
"""
|
| 909 |
+
expr = eval(
|
| 910 |
+
code, global_dict, local_dict) # take local objects in preference
|
| 911 |
+
return expr
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
def parse_expr(s: str, local_dict: Optional[DICT] = None,
|
| 915 |
+
transformations: tUnion[tTuple[TRANS, ...], str] \
|
| 916 |
+
= standard_transformations,
|
| 917 |
+
global_dict: Optional[DICT] = None, evaluate=True):
|
| 918 |
+
"""Converts the string ``s`` to a SymPy expression, in ``local_dict``.
|
| 919 |
+
|
| 920 |
+
Parameters
|
| 921 |
+
==========
|
| 922 |
+
|
| 923 |
+
s : str
|
| 924 |
+
The string to parse.
|
| 925 |
+
|
| 926 |
+
local_dict : dict, optional
|
| 927 |
+
A dictionary of local variables to use when parsing.
|
| 928 |
+
|
| 929 |
+
global_dict : dict, optional
|
| 930 |
+
A dictionary of global variables. By default, this is initialized
|
| 931 |
+
with ``from sympy import *``; provide this parameter to override
|
| 932 |
+
this behavior (for instance, to parse ``"Q & S"``).
|
| 933 |
+
|
| 934 |
+
transformations : tuple or str
|
| 935 |
+
A tuple of transformation functions used to modify the tokens of the
|
| 936 |
+
parsed expression before evaluation. The default transformations
|
| 937 |
+
convert numeric literals into their SymPy equivalents, convert
|
| 938 |
+
undefined variables into SymPy symbols, and allow the use of standard
|
| 939 |
+
mathematical factorial notation (e.g. ``x!``). Selection via
|
| 940 |
+
string is available (see below).
|
| 941 |
+
|
| 942 |
+
evaluate : bool, optional
|
| 943 |
+
When False, the order of the arguments will remain as they were in the
|
| 944 |
+
string and automatic simplification that would normally occur is
|
| 945 |
+
suppressed. (see examples)
|
| 946 |
+
|
| 947 |
+
Examples
|
| 948 |
+
========
|
| 949 |
+
|
| 950 |
+
>>> from sympy.parsing.sympy_parser import parse_expr
|
| 951 |
+
>>> parse_expr("1/2")
|
| 952 |
+
1/2
|
| 953 |
+
>>> type(_)
|
| 954 |
+
<class 'sympy.core.numbers.Half'>
|
| 955 |
+
>>> from sympy.parsing.sympy_parser import standard_transformations,\\
|
| 956 |
+
... implicit_multiplication_application
|
| 957 |
+
>>> transformations = (standard_transformations +
|
| 958 |
+
... (implicit_multiplication_application,))
|
| 959 |
+
>>> parse_expr("2x", transformations=transformations)
|
| 960 |
+
2*x
|
| 961 |
+
|
| 962 |
+
When evaluate=False, some automatic simplifications will not occur:
|
| 963 |
+
|
| 964 |
+
>>> parse_expr("2**3"), parse_expr("2**3", evaluate=False)
|
| 965 |
+
(8, 2**3)
|
| 966 |
+
|
| 967 |
+
In addition the order of the arguments will not be made canonical.
|
| 968 |
+
This feature allows one to tell exactly how the expression was entered:
|
| 969 |
+
|
| 970 |
+
>>> a = parse_expr('1 + x', evaluate=False)
|
| 971 |
+
>>> b = parse_expr('x + 1', evaluate=0)
|
| 972 |
+
>>> a == b
|
| 973 |
+
False
|
| 974 |
+
>>> a.args
|
| 975 |
+
(1, x)
|
| 976 |
+
>>> b.args
|
| 977 |
+
(x, 1)
|
| 978 |
+
|
| 979 |
+
Note, however, that when these expressions are printed they will
|
| 980 |
+
appear the same:
|
| 981 |
+
|
| 982 |
+
>>> assert str(a) == str(b)
|
| 983 |
+
|
| 984 |
+
As a convenience, transformations can be seen by printing ``transformations``:
|
| 985 |
+
|
| 986 |
+
>>> from sympy.parsing.sympy_parser import transformations
|
| 987 |
+
|
| 988 |
+
>>> print(transformations)
|
| 989 |
+
0: lambda_notation
|
| 990 |
+
1: auto_symbol
|
| 991 |
+
2: repeated_decimals
|
| 992 |
+
3: auto_number
|
| 993 |
+
4: factorial_notation
|
| 994 |
+
5: implicit_multiplication_application
|
| 995 |
+
6: convert_xor
|
| 996 |
+
7: implicit_application
|
| 997 |
+
8: implicit_multiplication
|
| 998 |
+
9: convert_equals_signs
|
| 999 |
+
10: function_exponentiation
|
| 1000 |
+
11: rationalize
|
| 1001 |
+
|
| 1002 |
+
The ``T`` object provides a way to select these transformations:
|
| 1003 |
+
|
| 1004 |
+
>>> from sympy.parsing.sympy_parser import T
|
| 1005 |
+
|
| 1006 |
+
If you print it, you will see the same list as shown above.
|
| 1007 |
+
|
| 1008 |
+
>>> str(T) == str(transformations)
|
| 1009 |
+
True
|
| 1010 |
+
|
| 1011 |
+
Standard slicing will return a tuple of transformations:
|
| 1012 |
+
|
| 1013 |
+
>>> T[:5] == standard_transformations
|
| 1014 |
+
True
|
| 1015 |
+
|
| 1016 |
+
So ``T`` can be used to specify the parsing transformations:
|
| 1017 |
+
|
| 1018 |
+
>>> parse_expr("2x", transformations=T[:5])
|
| 1019 |
+
Traceback (most recent call last):
|
| 1020 |
+
...
|
| 1021 |
+
SyntaxError: invalid syntax
|
| 1022 |
+
>>> parse_expr("2x", transformations=T[:6])
|
| 1023 |
+
2*x
|
| 1024 |
+
>>> parse_expr('.3', transformations=T[3, 11])
|
| 1025 |
+
3/10
|
| 1026 |
+
>>> parse_expr('.3x', transformations=T[:])
|
| 1027 |
+
3*x/10
|
| 1028 |
+
|
| 1029 |
+
As a further convenience, strings 'implicit' and 'all' can be used
|
| 1030 |
+
to select 0-5 and all the transformations, respectively.
|
| 1031 |
+
|
| 1032 |
+
>>> parse_expr('.3x', transformations='all')
|
| 1033 |
+
3*x/10
|
| 1034 |
+
|
| 1035 |
+
See Also
|
| 1036 |
+
========
|
| 1037 |
+
|
| 1038 |
+
stringify_expr, eval_expr, standard_transformations,
|
| 1039 |
+
implicit_multiplication_application
|
| 1040 |
+
|
| 1041 |
+
"""
|
| 1042 |
+
|
| 1043 |
+
if local_dict is None:
|
| 1044 |
+
local_dict = {}
|
| 1045 |
+
elif not isinstance(local_dict, dict):
|
| 1046 |
+
raise TypeError('expecting local_dict to be a dict')
|
| 1047 |
+
elif null in local_dict:
|
| 1048 |
+
raise ValueError('cannot use "" in local_dict')
|
| 1049 |
+
|
| 1050 |
+
if global_dict is None:
|
| 1051 |
+
global_dict = {}
|
| 1052 |
+
exec('from sympy import *', global_dict)
|
| 1053 |
+
|
| 1054 |
+
builtins_dict = vars(builtins)
|
| 1055 |
+
for name, obj in builtins_dict.items():
|
| 1056 |
+
if isinstance(obj, types.BuiltinFunctionType):
|
| 1057 |
+
global_dict[name] = obj
|
| 1058 |
+
global_dict['max'] = Max
|
| 1059 |
+
global_dict['min'] = Min
|
| 1060 |
+
|
| 1061 |
+
elif not isinstance(global_dict, dict):
|
| 1062 |
+
raise TypeError('expecting global_dict to be a dict')
|
| 1063 |
+
|
| 1064 |
+
transformations = transformations or ()
|
| 1065 |
+
if isinstance(transformations, str):
|
| 1066 |
+
if transformations == 'all':
|
| 1067 |
+
_transformations = T[:]
|
| 1068 |
+
elif transformations == 'implicit':
|
| 1069 |
+
_transformations = T[:6]
|
| 1070 |
+
else:
|
| 1071 |
+
raise ValueError('unknown transformation group name')
|
| 1072 |
+
else:
|
| 1073 |
+
_transformations = transformations
|
| 1074 |
+
|
| 1075 |
+
code = stringify_expr(s, local_dict, global_dict, _transformations)
|
| 1076 |
+
|
| 1077 |
+
if not evaluate:
|
| 1078 |
+
code = compile(evaluateFalse(code), '<string>', 'eval') # type: ignore
|
| 1079 |
+
|
| 1080 |
+
try:
|
| 1081 |
+
rv = eval_expr(code, local_dict, global_dict)
|
| 1082 |
+
# restore neutral definitions for names
|
| 1083 |
+
for i in local_dict.pop(null, ()):
|
| 1084 |
+
local_dict[i] = null
|
| 1085 |
+
return rv
|
| 1086 |
+
except Exception as e:
|
| 1087 |
+
# restore neutral definitions for names
|
| 1088 |
+
for i in local_dict.pop(null, ()):
|
| 1089 |
+
local_dict[i] = null
|
| 1090 |
+
raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
def evaluateFalse(s: str):
|
| 1094 |
+
"""
|
| 1095 |
+
Replaces operators with the SymPy equivalent and sets evaluate=False.
|
| 1096 |
+
"""
|
| 1097 |
+
node = ast.parse(s)
|
| 1098 |
+
transformed_node = EvaluateFalseTransformer().visit(node)
|
| 1099 |
+
# node is a Module, we want an Expression
|
| 1100 |
+
transformed_node = ast.Expression(transformed_node.body[0].value)
|
| 1101 |
+
|
| 1102 |
+
return ast.fix_missing_locations(transformed_node)
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
class EvaluateFalseTransformer(ast.NodeTransformer):
|
| 1106 |
+
operators = {
|
| 1107 |
+
ast.Add: 'Add',
|
| 1108 |
+
ast.Mult: 'Mul',
|
| 1109 |
+
ast.Pow: 'Pow',
|
| 1110 |
+
ast.Sub: 'Add',
|
| 1111 |
+
ast.Div: 'Mul',
|
| 1112 |
+
ast.BitOr: 'Or',
|
| 1113 |
+
ast.BitAnd: 'And',
|
| 1114 |
+
ast.BitXor: 'Not',
|
| 1115 |
+
}
|
| 1116 |
+
functions = (
|
| 1117 |
+
'Abs', 'im', 're', 'sign', 'arg', 'conjugate',
|
| 1118 |
+
'acos', 'acot', 'acsc', 'asec', 'asin', 'atan',
|
| 1119 |
+
'acosh', 'acoth', 'acsch', 'asech', 'asinh', 'atanh',
|
| 1120 |
+
'cos', 'cot', 'csc', 'sec', 'sin', 'tan',
|
| 1121 |
+
'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh',
|
| 1122 |
+
'exp', 'ln', 'log', 'sqrt', 'cbrt',
|
| 1123 |
+
)
|
| 1124 |
+
|
| 1125 |
+
relational_operators = {
|
| 1126 |
+
ast.NotEq: 'Ne',
|
| 1127 |
+
ast.Lt: 'Lt',
|
| 1128 |
+
ast.LtE: 'Le',
|
| 1129 |
+
ast.Gt: 'Gt',
|
| 1130 |
+
ast.GtE: 'Ge',
|
| 1131 |
+
ast.Eq: 'Eq'
|
| 1132 |
+
}
|
| 1133 |
+
def visit_Compare(self, node):
|
| 1134 |
+
if node.ops[0].__class__ in self.relational_operators:
|
| 1135 |
+
sympy_class = self.relational_operators[node.ops[0].__class__]
|
| 1136 |
+
right = self.visit(node.comparators[0])
|
| 1137 |
+
left = self.visit(node.left)
|
| 1138 |
+
new_node = ast.Call(
|
| 1139 |
+
func=ast.Name(id=sympy_class, ctx=ast.Load()),
|
| 1140 |
+
args=[left, right],
|
| 1141 |
+
keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
|
| 1142 |
+
)
|
| 1143 |
+
return new_node
|
| 1144 |
+
return node
|
| 1145 |
+
|
| 1146 |
+
def flatten(self, args, func):
|
| 1147 |
+
result = []
|
| 1148 |
+
for arg in args:
|
| 1149 |
+
if isinstance(arg, ast.Call):
|
| 1150 |
+
arg_func = arg.func
|
| 1151 |
+
if isinstance(arg_func, ast.Call):
|
| 1152 |
+
arg_func = arg_func.func
|
| 1153 |
+
if arg_func.id == func:
|
| 1154 |
+
result.extend(self.flatten(arg.args, func))
|
| 1155 |
+
else:
|
| 1156 |
+
result.append(arg)
|
| 1157 |
+
else:
|
| 1158 |
+
result.append(arg)
|
| 1159 |
+
return result
|
| 1160 |
+
|
| 1161 |
+
def visit_BinOp(self, node):
|
| 1162 |
+
if node.op.__class__ in self.operators:
|
| 1163 |
+
sympy_class = self.operators[node.op.__class__]
|
| 1164 |
+
right = self.visit(node.right)
|
| 1165 |
+
left = self.visit(node.left)
|
| 1166 |
+
|
| 1167 |
+
rev = False
|
| 1168 |
+
if isinstance(node.op, ast.Sub):
|
| 1169 |
+
right = ast.Call(
|
| 1170 |
+
func=ast.Name(id='Mul', ctx=ast.Load()),
|
| 1171 |
+
args=[ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1)), right],
|
| 1172 |
+
keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
|
| 1173 |
+
)
|
| 1174 |
+
elif isinstance(node.op, ast.Div):
|
| 1175 |
+
if isinstance(node.left, ast.UnaryOp):
|
| 1176 |
+
left, right = right, left
|
| 1177 |
+
rev = True
|
| 1178 |
+
left = ast.Call(
|
| 1179 |
+
func=ast.Name(id='Pow', ctx=ast.Load()),
|
| 1180 |
+
args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1))],
|
| 1181 |
+
keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
|
| 1182 |
+
)
|
| 1183 |
+
else:
|
| 1184 |
+
right = ast.Call(
|
| 1185 |
+
func=ast.Name(id='Pow', ctx=ast.Load()),
|
| 1186 |
+
args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1))],
|
| 1187 |
+
keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
|
| 1188 |
+
)
|
| 1189 |
+
|
| 1190 |
+
if rev: # undo reversal
|
| 1191 |
+
left, right = right, left
|
| 1192 |
+
new_node = ast.Call(
|
| 1193 |
+
func=ast.Name(id=sympy_class, ctx=ast.Load()),
|
| 1194 |
+
args=[left, right],
|
| 1195 |
+
keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
|
| 1196 |
+
)
|
| 1197 |
+
|
| 1198 |
+
if sympy_class in ('Add', 'Mul'):
|
| 1199 |
+
# Denest Add or Mul as appropriate
|
| 1200 |
+
new_node.args = self.flatten(new_node.args, sympy_class)
|
| 1201 |
+
|
| 1202 |
+
return new_node
|
| 1203 |
+
return node
|
| 1204 |
+
|
| 1205 |
+
def visit_Call(self, node):
|
| 1206 |
+
new_node = self.generic_visit(node)
|
| 1207 |
+
if isinstance(node.func, ast.Name) and node.func.id in self.functions:
|
| 1208 |
+
new_node.keywords.append(ast.keyword(arg='evaluate', value=ast.Constant(value=False)))
|
| 1209 |
+
return new_node
|
| 1210 |
+
|
| 1211 |
+
|
| 1212 |
+
_transformation = { # items can be added but never re-ordered
|
| 1213 |
+
0: lambda_notation,
|
| 1214 |
+
1: auto_symbol,
|
| 1215 |
+
2: repeated_decimals,
|
| 1216 |
+
3: auto_number,
|
| 1217 |
+
4: factorial_notation,
|
| 1218 |
+
5: implicit_multiplication_application,
|
| 1219 |
+
6: convert_xor,
|
| 1220 |
+
7: implicit_application,
|
| 1221 |
+
8: implicit_multiplication,
|
| 1222 |
+
9: convert_equals_signs,
|
| 1223 |
+
10: function_exponentiation,
|
| 1224 |
+
11: rationalize}
|
| 1225 |
+
|
| 1226 |
+
transformations = '\n'.join('%s: %s' % (i, func_name(f)) for i, f in _transformation.items())
|
| 1227 |
+
|
| 1228 |
+
|
| 1229 |
+
class _T():
|
| 1230 |
+
"""class to retrieve transformations from a given slice
|
| 1231 |
+
|
| 1232 |
+
EXAMPLES
|
| 1233 |
+
========
|
| 1234 |
+
|
| 1235 |
+
>>> from sympy.parsing.sympy_parser import T, standard_transformations
|
| 1236 |
+
>>> assert T[:5] == standard_transformations
|
| 1237 |
+
"""
|
| 1238 |
+
def __init__(self):
|
| 1239 |
+
self.N = len(_transformation)
|
| 1240 |
+
|
| 1241 |
+
def __str__(self):
|
| 1242 |
+
return transformations
|
| 1243 |
+
|
| 1244 |
+
def __getitem__(self, t):
|
| 1245 |
+
if not type(t) is tuple:
|
| 1246 |
+
t = (t,)
|
| 1247 |
+
i = []
|
| 1248 |
+
for ti in t:
|
| 1249 |
+
if type(ti) is int:
|
| 1250 |
+
i.append(range(self.N)[ti])
|
| 1251 |
+
elif type(ti) is slice:
|
| 1252 |
+
i.extend(range(*ti.indices(self.N)))
|
| 1253 |
+
else:
|
| 1254 |
+
raise TypeError('unexpected slice arg')
|
| 1255 |
+
return tuple([_transformation[_] for _ in i])
|
| 1256 |
+
|
| 1257 |
+
T = _T()
|
vllm/lib/python3.10/site-packages/sympy/parsing/tests/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/sympy/parsing/tests/__pycache__/test_ast_parser.cpython-310.pyc
ADDED
|
Binary file (1.08 kB). View file
|
|
|