Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/__init__.py +20 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/ntheory.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/gmpy.py +341 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/importtools.py +187 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/ntheory.py +637 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/pythonmpq.py +341 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__init__.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_autowrap.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_gmpy.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_ntheory.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_pythonmpq.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py +313 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py +379 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_gmpy.py +12 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py +40 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_ntheory.py +307 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py +335 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py +176 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py +35 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/integrals/benchmarks/bench_integrate.py +21 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/traversal.py +95 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt +21 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/LaTeX.g4 +312 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/__init__.py +2 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/latex_parser.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/transformer.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/greek_symbols.lark +28 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/latex.lark +327 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/latex_parser.py +146 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/transformer.py +557 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/activations.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/adapter.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/attention.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/attention_flax.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/attention_processor.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/downsampling.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/dual_transformer_2d.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/embeddings.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/lora.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/modeling_flax_pytorch_utils.cpython-310.pyc +0 -0
evalkit_internvl/lib/python3.10/site-packages/sympy/external/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unified place for determining if external dependencies are installed or not.
|
| 3 |
+
|
| 4 |
+
You should import all external modules using the import_module() function.
|
| 5 |
+
|
| 6 |
+
For example
|
| 7 |
+
|
| 8 |
+
>>> from sympy.external import import_module
|
| 9 |
+
>>> numpy = import_module('numpy')
|
| 10 |
+
|
| 11 |
+
If the resulting library is not installed, or if the installed version
|
| 12 |
+
is less than a given minimum version, the function will return None.
|
| 13 |
+
Otherwise, it will return the library. See the docstring of
|
| 14 |
+
import_module() for more information.
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from sympy.external.importtools import import_module
|
| 19 |
+
|
| 20 |
+
__all__ = ['import_module']
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc
ADDED
|
Binary file (5.38 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc
ADDED
|
Binary file (5.52 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/ntheory.cpython-310.pyc
ADDED
|
Binary file (14.3 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc
ADDED
|
Binary file (8.8 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/gmpy.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from ctypes import c_long, sizeof
|
| 3 |
+
from functools import reduce
|
| 4 |
+
from typing import Tuple as tTuple, Type
|
| 5 |
+
from warnings import warn
|
| 6 |
+
|
| 7 |
+
from sympy.external import import_module
|
| 8 |
+
|
| 9 |
+
from .pythonmpq import PythonMPQ
|
| 10 |
+
|
| 11 |
+
from .ntheory import (
|
| 12 |
+
bit_scan1 as python_bit_scan1,
|
| 13 |
+
bit_scan0 as python_bit_scan0,
|
| 14 |
+
remove as python_remove,
|
| 15 |
+
factorial as python_factorial,
|
| 16 |
+
sqrt as python_sqrt,
|
| 17 |
+
sqrtrem as python_sqrtrem,
|
| 18 |
+
gcd as python_gcd,
|
| 19 |
+
lcm as python_lcm,
|
| 20 |
+
gcdext as python_gcdext,
|
| 21 |
+
is_square as python_is_square,
|
| 22 |
+
invert as python_invert,
|
| 23 |
+
legendre as python_legendre,
|
| 24 |
+
jacobi as python_jacobi,
|
| 25 |
+
kronecker as python_kronecker,
|
| 26 |
+
iroot as python_iroot,
|
| 27 |
+
is_fermat_prp as python_is_fermat_prp,
|
| 28 |
+
is_euler_prp as python_is_euler_prp,
|
| 29 |
+
is_strong_prp as python_is_strong_prp,
|
| 30 |
+
is_fibonacci_prp as python_is_fibonacci_prp,
|
| 31 |
+
is_lucas_prp as python_is_lucas_prp,
|
| 32 |
+
is_selfridge_prp as python_is_selfridge_prp,
|
| 33 |
+
is_strong_lucas_prp as python_is_strong_lucas_prp,
|
| 34 |
+
is_strong_selfridge_prp as python_is_strong_selfridge_prp,
|
| 35 |
+
is_bpsw_prp as python_is_bpsw_prp,
|
| 36 |
+
is_strong_bpsw_prp as python_is_strong_bpsw_prp,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
__all__ = [
|
| 41 |
+
# GROUND_TYPES is either 'gmpy' or 'python' depending on which is used. If
|
| 42 |
+
# gmpy is installed then it will be used unless the environment variable
|
| 43 |
+
# SYMPY_GROUND_TYPES is set to something other than 'auto', 'gmpy', or
|
| 44 |
+
# 'gmpy2'.
|
| 45 |
+
'GROUND_TYPES',
|
| 46 |
+
|
| 47 |
+
# If HAS_GMPY is 0, no supported version of gmpy is available. Otherwise,
|
| 48 |
+
# HAS_GMPY will be 2 for gmpy2 if GROUND_TYPES is 'gmpy'. It used to be
|
| 49 |
+
# possible for HAS_GMPY to be 1 for gmpy but gmpy is no longer supported.
|
| 50 |
+
'HAS_GMPY',
|
| 51 |
+
|
| 52 |
+
# SYMPY_INTS is a tuple containing the base types for valid integer types.
|
| 53 |
+
# This is either (int,) or (int, type(mpz(0))) depending on GROUND_TYPES.
|
| 54 |
+
'SYMPY_INTS',
|
| 55 |
+
|
| 56 |
+
# MPQ is either gmpy.mpq or the Python equivalent from
|
| 57 |
+
# sympy.external.pythonmpq
|
| 58 |
+
'MPQ',
|
| 59 |
+
|
| 60 |
+
# MPZ is either gmpy.mpz or int.
|
| 61 |
+
'MPZ',
|
| 62 |
+
|
| 63 |
+
'bit_scan1',
|
| 64 |
+
'bit_scan0',
|
| 65 |
+
'remove',
|
| 66 |
+
'factorial',
|
| 67 |
+
'sqrt',
|
| 68 |
+
'is_square',
|
| 69 |
+
'sqrtrem',
|
| 70 |
+
'gcd',
|
| 71 |
+
'lcm',
|
| 72 |
+
'gcdext',
|
| 73 |
+
'invert',
|
| 74 |
+
'legendre',
|
| 75 |
+
'jacobi',
|
| 76 |
+
'kronecker',
|
| 77 |
+
'iroot',
|
| 78 |
+
'is_fermat_prp',
|
| 79 |
+
'is_euler_prp',
|
| 80 |
+
'is_strong_prp',
|
| 81 |
+
'is_fibonacci_prp',
|
| 82 |
+
'is_lucas_prp',
|
| 83 |
+
'is_selfridge_prp',
|
| 84 |
+
'is_strong_lucas_prp',
|
| 85 |
+
'is_strong_selfridge_prp',
|
| 86 |
+
'is_bpsw_prp',
|
| 87 |
+
'is_strong_bpsw_prp',
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
#
|
| 92 |
+
# Tested python-flint version. Future versions might work but we will only use
|
| 93 |
+
# them if explicitly requested by SYMPY_GROUND_TYPES=flint.
|
| 94 |
+
#
|
| 95 |
+
_PYTHON_FLINT_VERSION_NEEDED = ["0.6", "0.7", "0.8", "0.9"]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _flint_version_okay(flint_version):
|
| 99 |
+
major, minor = flint_version.split('.')[:2]
|
| 100 |
+
flint_ver = f'{major}.{minor}'
|
| 101 |
+
return flint_ver in _PYTHON_FLINT_VERSION_NEEDED
|
| 102 |
+
|
| 103 |
+
#
|
| 104 |
+
# We will only use gmpy2 >= 2.0.0
|
| 105 |
+
#
|
| 106 |
+
_GMPY2_MIN_VERSION = '2.0.0'
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _get_flint(sympy_ground_types):
|
| 110 |
+
if sympy_ground_types not in ('auto', 'flint'):
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
try:
|
| 114 |
+
import flint
|
| 115 |
+
# Earlier versions of python-flint may not have __version__.
|
| 116 |
+
from flint import __version__ as _flint_version
|
| 117 |
+
except ImportError:
|
| 118 |
+
if sympy_ground_types == 'flint':
|
| 119 |
+
warn("SYMPY_GROUND_TYPES was set to flint but python-flint is not "
|
| 120 |
+
"installed. Falling back to other ground types.")
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
if _flint_version_okay(_flint_version):
|
| 124 |
+
return flint
|
| 125 |
+
elif sympy_ground_types == 'auto':
|
| 126 |
+
return None
|
| 127 |
+
else:
|
| 128 |
+
warn(f"Using python-flint {_flint_version} because SYMPY_GROUND_TYPES "
|
| 129 |
+
f"is set to flint but this version of SymPy is only tested "
|
| 130 |
+
f"with python-flint versions {_PYTHON_FLINT_VERSION_NEEDED}.")
|
| 131 |
+
return flint
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _get_gmpy2(sympy_ground_types):
|
| 135 |
+
if sympy_ground_types not in ('auto', 'gmpy', 'gmpy2'):
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
gmpy = import_module('gmpy2', min_module_version=_GMPY2_MIN_VERSION,
|
| 139 |
+
module_version_attr='version', module_version_attr_call_args=())
|
| 140 |
+
|
| 141 |
+
if sympy_ground_types != 'auto' and gmpy is None:
|
| 142 |
+
warn("gmpy2 library is not installed, switching to 'python' ground types")
|
| 143 |
+
|
| 144 |
+
return gmpy
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
#
|
| 148 |
+
# SYMPY_GROUND_TYPES can be flint, gmpy, gmpy2, python or auto (default)
|
| 149 |
+
#
|
| 150 |
+
_SYMPY_GROUND_TYPES = os.environ.get('SYMPY_GROUND_TYPES', 'auto').lower()
|
| 151 |
+
_flint = None
|
| 152 |
+
_gmpy = None
|
| 153 |
+
|
| 154 |
+
#
|
| 155 |
+
# First handle auto-detection of flint/gmpy2. We will prefer flint if available
|
| 156 |
+
# or otherwise gmpy2 if available and then lastly the python types.
|
| 157 |
+
#
|
| 158 |
+
if _SYMPY_GROUND_TYPES in ('auto', 'flint'):
|
| 159 |
+
_flint = _get_flint(_SYMPY_GROUND_TYPES)
|
| 160 |
+
if _flint is not None:
|
| 161 |
+
_SYMPY_GROUND_TYPES = 'flint'
|
| 162 |
+
else:
|
| 163 |
+
_SYMPY_GROUND_TYPES = 'auto'
|
| 164 |
+
|
| 165 |
+
if _SYMPY_GROUND_TYPES in ('auto', 'gmpy', 'gmpy2'):
|
| 166 |
+
_gmpy = _get_gmpy2(_SYMPY_GROUND_TYPES)
|
| 167 |
+
if _gmpy is not None:
|
| 168 |
+
_SYMPY_GROUND_TYPES = 'gmpy'
|
| 169 |
+
else:
|
| 170 |
+
_SYMPY_GROUND_TYPES = 'python'
|
| 171 |
+
|
| 172 |
+
if _SYMPY_GROUND_TYPES not in ('flint', 'gmpy', 'python'):
|
| 173 |
+
warn("SYMPY_GROUND_TYPES environment variable unrecognised. "
|
| 174 |
+
"Should be 'auto', 'flint', 'gmpy', 'gmpy2' or 'python'.")
|
| 175 |
+
_SYMPY_GROUND_TYPES = 'python'
|
| 176 |
+
|
| 177 |
+
#
|
| 178 |
+
# At this point _SYMPY_GROUND_TYPES is either flint, gmpy or python. The blocks
|
| 179 |
+
# below define the values exported by this module in each case.
|
| 180 |
+
#
|
| 181 |
+
|
| 182 |
+
#
|
| 183 |
+
# In gmpy2 and flint, there are functions that take a long (or unsigned long)
|
| 184 |
+
# argument. That is, it is not possible to input a value larger than that.
|
| 185 |
+
#
|
| 186 |
+
LONG_MAX = (1 << (8*sizeof(c_long) - 1)) - 1
|
| 187 |
+
|
| 188 |
+
#
|
| 189 |
+
# Type checkers are confused by what SYMPY_INTS is. There may be a better type
|
| 190 |
+
# hint for this like Type[Integral] or something.
|
| 191 |
+
#
|
| 192 |
+
SYMPY_INTS: tTuple[Type, ...]
|
| 193 |
+
|
| 194 |
+
if _SYMPY_GROUND_TYPES == 'gmpy':
|
| 195 |
+
|
| 196 |
+
assert _gmpy is not None
|
| 197 |
+
|
| 198 |
+
flint = None
|
| 199 |
+
gmpy = _gmpy
|
| 200 |
+
|
| 201 |
+
HAS_GMPY = 2
|
| 202 |
+
GROUND_TYPES = 'gmpy'
|
| 203 |
+
SYMPY_INTS = (int, type(gmpy.mpz(0)))
|
| 204 |
+
MPZ = gmpy.mpz
|
| 205 |
+
MPQ = gmpy.mpq
|
| 206 |
+
|
| 207 |
+
bit_scan1 = gmpy.bit_scan1
|
| 208 |
+
bit_scan0 = gmpy.bit_scan0
|
| 209 |
+
remove = gmpy.remove
|
| 210 |
+
factorial = gmpy.fac
|
| 211 |
+
sqrt = gmpy.isqrt
|
| 212 |
+
is_square = gmpy.is_square
|
| 213 |
+
sqrtrem = gmpy.isqrt_rem
|
| 214 |
+
gcd = gmpy.gcd
|
| 215 |
+
lcm = gmpy.lcm
|
| 216 |
+
gcdext = gmpy.gcdext
|
| 217 |
+
invert = gmpy.invert
|
| 218 |
+
legendre = gmpy.legendre
|
| 219 |
+
jacobi = gmpy.jacobi
|
| 220 |
+
kronecker = gmpy.kronecker
|
| 221 |
+
|
| 222 |
+
def iroot(x, n):
|
| 223 |
+
# In the latest gmpy2, the threshold for n is ULONG_MAX,
|
| 224 |
+
# but adjust to the older one.
|
| 225 |
+
if n <= LONG_MAX:
|
| 226 |
+
return gmpy.iroot(x, n)
|
| 227 |
+
return python_iroot(x, n)
|
| 228 |
+
|
| 229 |
+
is_fermat_prp = gmpy.is_fermat_prp
|
| 230 |
+
is_euler_prp = gmpy.is_euler_prp
|
| 231 |
+
is_strong_prp = gmpy.is_strong_prp
|
| 232 |
+
is_fibonacci_prp = gmpy.is_fibonacci_prp
|
| 233 |
+
is_lucas_prp = gmpy.is_lucas_prp
|
| 234 |
+
is_selfridge_prp = gmpy.is_selfridge_prp
|
| 235 |
+
is_strong_lucas_prp = gmpy.is_strong_lucas_prp
|
| 236 |
+
is_strong_selfridge_prp = gmpy.is_strong_selfridge_prp
|
| 237 |
+
is_bpsw_prp = gmpy.is_bpsw_prp
|
| 238 |
+
is_strong_bpsw_prp = gmpy.is_strong_bpsw_prp
|
| 239 |
+
|
| 240 |
+
elif _SYMPY_GROUND_TYPES == 'flint':
|
| 241 |
+
|
| 242 |
+
assert _flint is not None
|
| 243 |
+
|
| 244 |
+
flint = _flint
|
| 245 |
+
gmpy = None
|
| 246 |
+
|
| 247 |
+
HAS_GMPY = 0
|
| 248 |
+
GROUND_TYPES = 'flint'
|
| 249 |
+
SYMPY_INTS = (int, flint.fmpz) # type: ignore
|
| 250 |
+
MPZ = flint.fmpz # type: ignore
|
| 251 |
+
MPQ = flint.fmpq # type: ignore
|
| 252 |
+
|
| 253 |
+
bit_scan1 = python_bit_scan1
|
| 254 |
+
bit_scan0 = python_bit_scan0
|
| 255 |
+
remove = python_remove
|
| 256 |
+
factorial = python_factorial
|
| 257 |
+
|
| 258 |
+
def sqrt(x):
|
| 259 |
+
return flint.fmpz(x).isqrt()
|
| 260 |
+
|
| 261 |
+
def is_square(x):
|
| 262 |
+
if x < 0:
|
| 263 |
+
return False
|
| 264 |
+
return flint.fmpz(x).sqrtrem()[1] == 0
|
| 265 |
+
|
| 266 |
+
def sqrtrem(x):
|
| 267 |
+
return flint.fmpz(x).sqrtrem()
|
| 268 |
+
|
| 269 |
+
def gcd(*args):
|
| 270 |
+
return reduce(flint.fmpz.gcd, args, flint.fmpz(0))
|
| 271 |
+
|
| 272 |
+
def lcm(*args):
|
| 273 |
+
return reduce(flint.fmpz.lcm, args, flint.fmpz(1))
|
| 274 |
+
|
| 275 |
+
gcdext = python_gcdext
|
| 276 |
+
invert = python_invert
|
| 277 |
+
legendre = python_legendre
|
| 278 |
+
|
| 279 |
+
def jacobi(x, y):
|
| 280 |
+
if y <= 0 or not y % 2:
|
| 281 |
+
raise ValueError("y should be an odd positive integer")
|
| 282 |
+
return flint.fmpz(x).jacobi(y)
|
| 283 |
+
|
| 284 |
+
kronecker = python_kronecker
|
| 285 |
+
|
| 286 |
+
def iroot(x, n):
|
| 287 |
+
if n <= LONG_MAX:
|
| 288 |
+
y = flint.fmpz(x).root(n)
|
| 289 |
+
return y, y**n == x
|
| 290 |
+
return python_iroot(x, n)
|
| 291 |
+
|
| 292 |
+
is_fermat_prp = python_is_fermat_prp
|
| 293 |
+
is_euler_prp = python_is_euler_prp
|
| 294 |
+
is_strong_prp = python_is_strong_prp
|
| 295 |
+
is_fibonacci_prp = python_is_fibonacci_prp
|
| 296 |
+
is_lucas_prp = python_is_lucas_prp
|
| 297 |
+
is_selfridge_prp = python_is_selfridge_prp
|
| 298 |
+
is_strong_lucas_prp = python_is_strong_lucas_prp
|
| 299 |
+
is_strong_selfridge_prp = python_is_strong_selfridge_prp
|
| 300 |
+
is_bpsw_prp = python_is_bpsw_prp
|
| 301 |
+
is_strong_bpsw_prp = python_is_strong_bpsw_prp
|
| 302 |
+
|
| 303 |
+
elif _SYMPY_GROUND_TYPES == 'python':
|
| 304 |
+
|
| 305 |
+
flint = None
|
| 306 |
+
gmpy = None
|
| 307 |
+
|
| 308 |
+
HAS_GMPY = 0
|
| 309 |
+
GROUND_TYPES = 'python'
|
| 310 |
+
SYMPY_INTS = (int,)
|
| 311 |
+
MPZ = int
|
| 312 |
+
MPQ = PythonMPQ
|
| 313 |
+
|
| 314 |
+
bit_scan1 = python_bit_scan1
|
| 315 |
+
bit_scan0 = python_bit_scan0
|
| 316 |
+
remove = python_remove
|
| 317 |
+
factorial = python_factorial
|
| 318 |
+
sqrt = python_sqrt
|
| 319 |
+
is_square = python_is_square
|
| 320 |
+
sqrtrem = python_sqrtrem
|
| 321 |
+
gcd = python_gcd
|
| 322 |
+
lcm = python_lcm
|
| 323 |
+
gcdext = python_gcdext
|
| 324 |
+
invert = python_invert
|
| 325 |
+
legendre = python_legendre
|
| 326 |
+
jacobi = python_jacobi
|
| 327 |
+
kronecker = python_kronecker
|
| 328 |
+
iroot = python_iroot
|
| 329 |
+
is_fermat_prp = python_is_fermat_prp
|
| 330 |
+
is_euler_prp = python_is_euler_prp
|
| 331 |
+
is_strong_prp = python_is_strong_prp
|
| 332 |
+
is_fibonacci_prp = python_is_fibonacci_prp
|
| 333 |
+
is_lucas_prp = python_is_lucas_prp
|
| 334 |
+
is_selfridge_prp = python_is_selfridge_prp
|
| 335 |
+
is_strong_lucas_prp = python_is_strong_lucas_prp
|
| 336 |
+
is_strong_selfridge_prp = python_is_strong_selfridge_prp
|
| 337 |
+
is_bpsw_prp = python_is_bpsw_prp
|
| 338 |
+
is_strong_bpsw_prp = python_is_strong_bpsw_prp
|
| 339 |
+
|
| 340 |
+
else:
|
| 341 |
+
assert False
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/importtools.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tools to assist importing optional external modules."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
# Override these in the module to change the default warning behavior.
|
| 7 |
+
# For example, you might set both to False before running the tests so that
|
| 8 |
+
# warnings are not printed to the console, or set both to True for debugging.
|
| 9 |
+
|
| 10 |
+
WARN_NOT_INSTALLED = None # Default is False
|
| 11 |
+
WARN_OLD_VERSION = None # Default is True
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __sympy_debug():
|
| 15 |
+
# helper function from sympy/__init__.py
|
| 16 |
+
# We don't just import SYMPY_DEBUG from that file because we don't want to
|
| 17 |
+
# import all of SymPy just to use this module.
|
| 18 |
+
import os
|
| 19 |
+
debug_str = os.getenv('SYMPY_DEBUG', 'False')
|
| 20 |
+
if debug_str in ('True', 'False'):
|
| 21 |
+
return eval(debug_str)
|
| 22 |
+
else:
|
| 23 |
+
raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
|
| 24 |
+
debug_str)
|
| 25 |
+
|
| 26 |
+
if __sympy_debug():
|
| 27 |
+
WARN_OLD_VERSION = True
|
| 28 |
+
WARN_NOT_INSTALLED = True
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
_component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
|
| 32 |
+
|
| 33 |
+
def version_tuple(vstring):
|
| 34 |
+
# Parse a version string to a tuple e.g. '1.2' -> (1, 2)
|
| 35 |
+
# Simplified from distutils.version.LooseVersion which was deprecated in
|
| 36 |
+
# Python 3.10.
|
| 37 |
+
components = []
|
| 38 |
+
for x in _component_re.split(vstring):
|
| 39 |
+
if x and x != '.':
|
| 40 |
+
try:
|
| 41 |
+
x = int(x)
|
| 42 |
+
except ValueError:
|
| 43 |
+
pass
|
| 44 |
+
components.append(x)
|
| 45 |
+
return tuple(components)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def import_module(module, min_module_version=None, min_python_version=None,
|
| 49 |
+
warn_not_installed=None, warn_old_version=None,
|
| 50 |
+
module_version_attr='__version__', module_version_attr_call_args=None,
|
| 51 |
+
import_kwargs={}, catch=()):
|
| 52 |
+
"""
|
| 53 |
+
Import and return a module if it is installed.
|
| 54 |
+
|
| 55 |
+
If the module is not installed, it returns None.
|
| 56 |
+
|
| 57 |
+
A minimum version for the module can be given as the keyword argument
|
| 58 |
+
min_module_version. This should be comparable against the module version.
|
| 59 |
+
By default, module.__version__ is used to get the module version. To
|
| 60 |
+
override this, set the module_version_attr keyword argument. If the
|
| 61 |
+
attribute of the module to get the version should be called (e.g.,
|
| 62 |
+
module.version()), then set module_version_attr_call_args to the args such
|
| 63 |
+
that module.module_version_attr(*module_version_attr_call_args) returns the
|
| 64 |
+
module's version.
|
| 65 |
+
|
| 66 |
+
If the module version is less than min_module_version using the Python <
|
| 67 |
+
comparison, None will be returned, even if the module is installed. You can
|
| 68 |
+
use this to keep from importing an incompatible older version of a module.
|
| 69 |
+
|
| 70 |
+
You can also specify a minimum Python version by using the
|
| 71 |
+
min_python_version keyword argument. This should be comparable against
|
| 72 |
+
sys.version_info.
|
| 73 |
+
|
| 74 |
+
If the keyword argument warn_not_installed is set to True, the function will
|
| 75 |
+
emit a UserWarning when the module is not installed.
|
| 76 |
+
|
| 77 |
+
If the keyword argument warn_old_version is set to True, the function will
|
| 78 |
+
emit a UserWarning when the library is installed, but cannot be imported
|
| 79 |
+
because of the min_module_version or min_python_version options.
|
| 80 |
+
|
| 81 |
+
Note that because of the way warnings are handled, a warning will be
|
| 82 |
+
emitted for each module only once. You can change the default warning
|
| 83 |
+
behavior by overriding the values of WARN_NOT_INSTALLED and WARN_OLD_VERSION
|
| 84 |
+
in sympy.external.importtools. By default, WARN_NOT_INSTALLED is False and
|
| 85 |
+
WARN_OLD_VERSION is True.
|
| 86 |
+
|
| 87 |
+
This function uses __import__() to import the module. To pass additional
|
| 88 |
+
options to __import__(), use the import_kwargs keyword argument. For
|
| 89 |
+
example, to import a submodule A.B, you must pass a nonempty fromlist option
|
| 90 |
+
to __import__. See the docstring of __import__().
|
| 91 |
+
|
| 92 |
+
This catches ImportError to determine if the module is not installed. To
|
| 93 |
+
catch additional errors, pass them as a tuple to the catch keyword
|
| 94 |
+
argument.
|
| 95 |
+
|
| 96 |
+
Examples
|
| 97 |
+
========
|
| 98 |
+
|
| 99 |
+
>>> from sympy.external import import_module
|
| 100 |
+
|
| 101 |
+
>>> numpy = import_module('numpy')
|
| 102 |
+
|
| 103 |
+
>>> numpy = import_module('numpy', min_python_version=(2, 7),
|
| 104 |
+
... warn_old_version=False)
|
| 105 |
+
|
| 106 |
+
>>> numpy = import_module('numpy', min_module_version='1.5',
|
| 107 |
+
... warn_old_version=False) # numpy.__version__ is a string
|
| 108 |
+
|
| 109 |
+
>>> # gmpy does not have __version__, but it does have gmpy.version()
|
| 110 |
+
|
| 111 |
+
>>> gmpy = import_module('gmpy', min_module_version='1.14',
|
| 112 |
+
... module_version_attr='version', module_version_attr_call_args=(),
|
| 113 |
+
... warn_old_version=False)
|
| 114 |
+
|
| 115 |
+
>>> # To import a submodule, you must pass a nonempty fromlist to
|
| 116 |
+
>>> # __import__(). The values do not matter.
|
| 117 |
+
>>> p3 = import_module('mpl_toolkits.mplot3d',
|
| 118 |
+
... import_kwargs={'fromlist':['something']})
|
| 119 |
+
|
| 120 |
+
>>> # matplotlib.pyplot can raise RuntimeError when the display cannot be opened
|
| 121 |
+
>>> matplotlib = import_module('matplotlib',
|
| 122 |
+
... import_kwargs={'fromlist':['pyplot']}, catch=(RuntimeError,))
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
# keyword argument overrides default, and global variable overrides
|
| 126 |
+
# keyword argument.
|
| 127 |
+
warn_old_version = (WARN_OLD_VERSION if WARN_OLD_VERSION is not None
|
| 128 |
+
else warn_old_version or True)
|
| 129 |
+
warn_not_installed = (WARN_NOT_INSTALLED if WARN_NOT_INSTALLED is not None
|
| 130 |
+
else warn_not_installed or False)
|
| 131 |
+
|
| 132 |
+
import warnings
|
| 133 |
+
|
| 134 |
+
# Check Python first so we don't waste time importing a module we can't use
|
| 135 |
+
if min_python_version:
|
| 136 |
+
if sys.version_info < min_python_version:
|
| 137 |
+
if warn_old_version:
|
| 138 |
+
warnings.warn("Python version is too old to use %s "
|
| 139 |
+
"(%s or newer required)" % (
|
| 140 |
+
module, '.'.join(map(str, min_python_version))),
|
| 141 |
+
UserWarning, stacklevel=2)
|
| 142 |
+
return
|
| 143 |
+
|
| 144 |
+
try:
|
| 145 |
+
mod = __import__(module, **import_kwargs)
|
| 146 |
+
|
| 147 |
+
## there's something funny about imports with matplotlib and py3k. doing
|
| 148 |
+
## from matplotlib import collections
|
| 149 |
+
## gives python's stdlib collections module. explicitly re-importing
|
| 150 |
+
## the module fixes this.
|
| 151 |
+
from_list = import_kwargs.get('fromlist', ())
|
| 152 |
+
for submod in from_list:
|
| 153 |
+
if submod == 'collections' and mod.__name__ == 'matplotlib':
|
| 154 |
+
__import__(module + '.' + submod)
|
| 155 |
+
except ImportError:
|
| 156 |
+
if warn_not_installed:
|
| 157 |
+
warnings.warn("%s module is not installed" % module, UserWarning,
|
| 158 |
+
stacklevel=2)
|
| 159 |
+
return
|
| 160 |
+
except catch as e:
|
| 161 |
+
if warn_not_installed:
|
| 162 |
+
warnings.warn(
|
| 163 |
+
"%s module could not be used (%s)" % (module, repr(e)),
|
| 164 |
+
stacklevel=2)
|
| 165 |
+
return
|
| 166 |
+
|
| 167 |
+
if min_module_version:
|
| 168 |
+
modversion = getattr(mod, module_version_attr)
|
| 169 |
+
if module_version_attr_call_args is not None:
|
| 170 |
+
modversion = modversion(*module_version_attr_call_args)
|
| 171 |
+
if version_tuple(modversion) < version_tuple(min_module_version):
|
| 172 |
+
if warn_old_version:
|
| 173 |
+
# Attempt to create a pretty string version of the version
|
| 174 |
+
if isinstance(min_module_version, str):
|
| 175 |
+
verstr = min_module_version
|
| 176 |
+
elif isinstance(min_module_version, (tuple, list)):
|
| 177 |
+
verstr = '.'.join(map(str, min_module_version))
|
| 178 |
+
else:
|
| 179 |
+
# Either don't know what this is. Hopefully
|
| 180 |
+
# it's something that has a nice str version, like an int.
|
| 181 |
+
verstr = str(min_module_version)
|
| 182 |
+
warnings.warn("%s version is too old to use "
|
| 183 |
+
"(%s or newer required)" % (module, verstr),
|
| 184 |
+
UserWarning, stacklevel=2)
|
| 185 |
+
return
|
| 186 |
+
|
| 187 |
+
return mod
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/ntheory.py
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# sympy.external.ntheory
|
| 2 |
+
#
|
| 3 |
+
# This module provides pure Python implementations of some number theory
|
| 4 |
+
# functions that are alternately used from gmpy2 if it is installed.
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
import math
|
| 8 |
+
|
| 9 |
+
import mpmath.libmp as mlib
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
_small_trailing = [0] * 256
|
| 13 |
+
for j in range(1, 8):
|
| 14 |
+
_small_trailing[1 << j :: 1 << (j + 1)] = [j] * (1 << (7 - j))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def bit_scan1(x, n=0):
|
| 18 |
+
if not x:
|
| 19 |
+
return
|
| 20 |
+
x = abs(x >> n)
|
| 21 |
+
low_byte = x & 0xFF
|
| 22 |
+
if low_byte:
|
| 23 |
+
return _small_trailing[low_byte] + n
|
| 24 |
+
|
| 25 |
+
t = 8 + n
|
| 26 |
+
x >>= 8
|
| 27 |
+
# 2**m is quick for z up through 2**30
|
| 28 |
+
z = x.bit_length() - 1
|
| 29 |
+
if x == 1 << z:
|
| 30 |
+
return z + t
|
| 31 |
+
|
| 32 |
+
if z < 300:
|
| 33 |
+
# fixed 8-byte reduction
|
| 34 |
+
while not x & 0xFF:
|
| 35 |
+
x >>= 8
|
| 36 |
+
t += 8
|
| 37 |
+
else:
|
| 38 |
+
# binary reduction important when there might be a large
|
| 39 |
+
# number of trailing 0s
|
| 40 |
+
p = z >> 1
|
| 41 |
+
while not x & 0xFF:
|
| 42 |
+
while x & ((1 << p) - 1):
|
| 43 |
+
p >>= 1
|
| 44 |
+
x >>= p
|
| 45 |
+
t += p
|
| 46 |
+
return t + _small_trailing[x & 0xFF]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def bit_scan0(x, n=0):
|
| 50 |
+
return bit_scan1(x + (1 << n), n)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def remove(x, f):
|
| 54 |
+
if f < 2:
|
| 55 |
+
raise ValueError("factor must be > 1")
|
| 56 |
+
if x == 0:
|
| 57 |
+
return 0, 0
|
| 58 |
+
if f == 2:
|
| 59 |
+
b = bit_scan1(x)
|
| 60 |
+
return x >> b, b
|
| 61 |
+
m = 0
|
| 62 |
+
y, rem = divmod(x, f)
|
| 63 |
+
while not rem:
|
| 64 |
+
x = y
|
| 65 |
+
m += 1
|
| 66 |
+
if m > 5:
|
| 67 |
+
pow_list = [f**2]
|
| 68 |
+
while pow_list:
|
| 69 |
+
_f = pow_list[-1]
|
| 70 |
+
y, rem = divmod(x, _f)
|
| 71 |
+
if not rem:
|
| 72 |
+
m += 1 << len(pow_list)
|
| 73 |
+
x = y
|
| 74 |
+
pow_list.append(_f**2)
|
| 75 |
+
else:
|
| 76 |
+
pow_list.pop()
|
| 77 |
+
y, rem = divmod(x, f)
|
| 78 |
+
return x, m
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def factorial(x):
|
| 82 |
+
"""Return x!."""
|
| 83 |
+
return int(mlib.ifac(int(x)))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def sqrt(x):
|
| 87 |
+
"""Integer square root of x."""
|
| 88 |
+
return int(mlib.isqrt(int(x)))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def sqrtrem(x):
|
| 92 |
+
"""Integer square root of x and remainder."""
|
| 93 |
+
s, r = mlib.sqrtrem(int(x))
|
| 94 |
+
return (int(s), int(r))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if sys.version_info[:2] >= (3, 9):
|
| 98 |
+
# As of Python 3.9 these can take multiple arguments
|
| 99 |
+
gcd = math.gcd
|
| 100 |
+
lcm = math.lcm
|
| 101 |
+
|
| 102 |
+
else:
|
| 103 |
+
# Until python 3.8 is no longer supported
|
| 104 |
+
from functools import reduce
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def gcd(*args):
|
| 108 |
+
"""gcd of multiple integers."""
|
| 109 |
+
return reduce(math.gcd, args, 0)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def lcm(*args):
|
| 113 |
+
"""lcm of multiple integers."""
|
| 114 |
+
if 0 in args:
|
| 115 |
+
return 0
|
| 116 |
+
return reduce(lambda x, y: x*y//math.gcd(x, y), args, 1)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _sign(n):
|
| 120 |
+
if n < 0:
|
| 121 |
+
return -1, -n
|
| 122 |
+
return 1, n
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def gcdext(a, b):
|
| 126 |
+
if not a or not b:
|
| 127 |
+
g = abs(a) or abs(b)
|
| 128 |
+
if not g:
|
| 129 |
+
return (0, 0, 0)
|
| 130 |
+
return (g, a // g, b // g)
|
| 131 |
+
|
| 132 |
+
x_sign, a = _sign(a)
|
| 133 |
+
y_sign, b = _sign(b)
|
| 134 |
+
x, r = 1, 0
|
| 135 |
+
y, s = 0, 1
|
| 136 |
+
|
| 137 |
+
while b:
|
| 138 |
+
q, c = divmod(a, b)
|
| 139 |
+
a, b = b, c
|
| 140 |
+
x, r = r, x - q*r
|
| 141 |
+
y, s = s, y - q*s
|
| 142 |
+
|
| 143 |
+
return (a, x * x_sign, y * y_sign)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def is_square(x):
|
| 147 |
+
"""Return True if x is a square number."""
|
| 148 |
+
if x < 0:
|
| 149 |
+
return False
|
| 150 |
+
|
| 151 |
+
# Note that the possible values of y**2 % n for a given n are limited.
|
| 152 |
+
# For example, when n=4, y**2 % n can only take 0 or 1.
|
| 153 |
+
# In other words, if x % 4 is 2 or 3, then x is not a square number.
|
| 154 |
+
# Mathematically, it determines if it belongs to the set {y**2 % n},
|
| 155 |
+
# but implementationally, it can be realized as a logical conjunction
|
| 156 |
+
# with an n-bit integer.
|
| 157 |
+
# see https://mersenneforum.org/showpost.php?p=110896
|
| 158 |
+
# def magic(n):
|
| 159 |
+
# s = {y**2 % n for y in range(n)}
|
| 160 |
+
# s = set(range(n)) - s
|
| 161 |
+
# return sum(1 << bit for bit in s)
|
| 162 |
+
# >>> print(hex(magic(128)))
|
| 163 |
+
# 0xfdfdfdedfdfdfdecfdfdfdedfdfcfdec
|
| 164 |
+
# >>> print(hex(magic(99)))
|
| 165 |
+
# 0x5f6f9ffb6fb7ddfcb75befdec
|
| 166 |
+
# >>> print(hex(magic(91)))
|
| 167 |
+
# 0x6fd1bfcfed5f3679d3ebdec
|
| 168 |
+
# >>> print(hex(magic(85)))
|
| 169 |
+
# 0xdef9ae771ffe3b9d67dec
|
| 170 |
+
if 0xfdfdfdedfdfdfdecfdfdfdedfdfcfdec & (1 << (x & 127)):
|
| 171 |
+
return False # e.g. 2, 3
|
| 172 |
+
m = x % 765765 # 765765 = 99 * 91 * 85
|
| 173 |
+
if 0x5f6f9ffb6fb7ddfcb75befdec & (1 << (m % 99)):
|
| 174 |
+
return False # e.g. 17, 68
|
| 175 |
+
if 0x6fd1bfcfed5f3679d3ebdec & (1 << (m % 91)):
|
| 176 |
+
return False # e.g. 97, 388
|
| 177 |
+
if 0xdef9ae771ffe3b9d67dec & (1 << (m % 85)):
|
| 178 |
+
return False # e.g. 793, 1408
|
| 179 |
+
return mlib.sqrtrem(int(x))[1] == 0
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def invert(x, m):
|
| 183 |
+
"""Modular inverse of x modulo m.
|
| 184 |
+
|
| 185 |
+
Returns y such that x*y == 1 mod m.
|
| 186 |
+
|
| 187 |
+
Uses ``math.pow`` but reproduces the behaviour of ``gmpy2.invert``
|
| 188 |
+
which raises ZeroDivisionError if no inverse exists.
|
| 189 |
+
"""
|
| 190 |
+
try:
|
| 191 |
+
return pow(x, -1, m)
|
| 192 |
+
except ValueError:
|
| 193 |
+
raise ZeroDivisionError("invert() no inverse exists")
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def legendre(x, y):
|
| 197 |
+
"""Legendre symbol (x / y).
|
| 198 |
+
|
| 199 |
+
Following the implementation of gmpy2,
|
| 200 |
+
the error is raised only when y is an even number.
|
| 201 |
+
"""
|
| 202 |
+
if y <= 0 or not y % 2:
|
| 203 |
+
raise ValueError("y should be an odd prime")
|
| 204 |
+
x %= y
|
| 205 |
+
if not x:
|
| 206 |
+
return 0
|
| 207 |
+
if pow(x, (y - 1) // 2, y) == 1:
|
| 208 |
+
return 1
|
| 209 |
+
return -1
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def jacobi(x, y):
|
| 213 |
+
"""Jacobi symbol (x / y)."""
|
| 214 |
+
if y <= 0 or not y % 2:
|
| 215 |
+
raise ValueError("y should be an odd positive integer")
|
| 216 |
+
x %= y
|
| 217 |
+
if not x:
|
| 218 |
+
return int(y == 1)
|
| 219 |
+
if y == 1 or x == 1:
|
| 220 |
+
return 1
|
| 221 |
+
if gcd(x, y) != 1:
|
| 222 |
+
return 0
|
| 223 |
+
j = 1
|
| 224 |
+
while x != 0:
|
| 225 |
+
while x % 2 == 0 and x > 0:
|
| 226 |
+
x >>= 1
|
| 227 |
+
if y % 8 in [3, 5]:
|
| 228 |
+
j = -j
|
| 229 |
+
x, y = y, x
|
| 230 |
+
if x % 4 == y % 4 == 3:
|
| 231 |
+
j = -j
|
| 232 |
+
x %= y
|
| 233 |
+
return j
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def kronecker(x, y):
|
| 237 |
+
"""Kronecker symbol (x / y)."""
|
| 238 |
+
if gcd(x, y) != 1:
|
| 239 |
+
return 0
|
| 240 |
+
if y == 0:
|
| 241 |
+
return 1
|
| 242 |
+
sign = -1 if y < 0 and x < 0 else 1
|
| 243 |
+
y = abs(y)
|
| 244 |
+
s = bit_scan1(y)
|
| 245 |
+
y >>= s
|
| 246 |
+
if s % 2 and x % 8 in [3, 5]:
|
| 247 |
+
sign = -sign
|
| 248 |
+
return sign * jacobi(x, y)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def iroot(y, n):
|
| 252 |
+
if y < 0:
|
| 253 |
+
raise ValueError("y must be nonnegative")
|
| 254 |
+
if n < 1:
|
| 255 |
+
raise ValueError("n must be positive")
|
| 256 |
+
if y in (0, 1):
|
| 257 |
+
return y, True
|
| 258 |
+
if n == 1:
|
| 259 |
+
return y, True
|
| 260 |
+
if n == 2:
|
| 261 |
+
x, rem = mlib.sqrtrem(y)
|
| 262 |
+
return int(x), not rem
|
| 263 |
+
if n >= y.bit_length():
|
| 264 |
+
return 1, False
|
| 265 |
+
# Get initial estimate for Newton's method. Care must be taken to
|
| 266 |
+
# avoid overflow
|
| 267 |
+
try:
|
| 268 |
+
guess = int(y**(1./n) + 0.5)
|
| 269 |
+
except OverflowError:
|
| 270 |
+
exp = math.log2(y)/n
|
| 271 |
+
if exp > 53:
|
| 272 |
+
shift = int(exp - 53)
|
| 273 |
+
guess = int(2.0**(exp - shift) + 1) << shift
|
| 274 |
+
else:
|
| 275 |
+
guess = int(2.0**exp)
|
| 276 |
+
if guess > 2**50:
|
| 277 |
+
# Newton iteration
|
| 278 |
+
xprev, x = -1, guess
|
| 279 |
+
while 1:
|
| 280 |
+
t = x**(n - 1)
|
| 281 |
+
xprev, x = x, ((n - 1)*x + y//t)//n
|
| 282 |
+
if abs(x - xprev) < 2:
|
| 283 |
+
break
|
| 284 |
+
else:
|
| 285 |
+
x = guess
|
| 286 |
+
# Compensate
|
| 287 |
+
t = x**n
|
| 288 |
+
while t < y:
|
| 289 |
+
x += 1
|
| 290 |
+
t = x**n
|
| 291 |
+
while t > y:
|
| 292 |
+
x -= 1
|
| 293 |
+
t = x**n
|
| 294 |
+
return x, t == y
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def is_fermat_prp(n, a):
|
| 298 |
+
if a < 2:
|
| 299 |
+
raise ValueError("is_fermat_prp() requires 'a' greater than or equal to 2")
|
| 300 |
+
if n < 1:
|
| 301 |
+
raise ValueError("is_fermat_prp() requires 'n' be greater than 0")
|
| 302 |
+
if n == 1:
|
| 303 |
+
return False
|
| 304 |
+
if n % 2 == 0:
|
| 305 |
+
return n == 2
|
| 306 |
+
a %= n
|
| 307 |
+
if gcd(n, a) != 1:
|
| 308 |
+
raise ValueError("is_fermat_prp() requires gcd(n,a) == 1")
|
| 309 |
+
return pow(a, n - 1, n) == 1
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def is_euler_prp(n, a):
|
| 313 |
+
if a < 2:
|
| 314 |
+
raise ValueError("is_euler_prp() requires 'a' greater than or equal to 2")
|
| 315 |
+
if n < 1:
|
| 316 |
+
raise ValueError("is_euler_prp() requires 'n' be greater than 0")
|
| 317 |
+
if n == 1:
|
| 318 |
+
return False
|
| 319 |
+
if n % 2 == 0:
|
| 320 |
+
return n == 2
|
| 321 |
+
a %= n
|
| 322 |
+
if gcd(n, a) != 1:
|
| 323 |
+
raise ValueError("is_euler_prp() requires gcd(n,a) == 1")
|
| 324 |
+
return pow(a, n >> 1, n) == jacobi(a, n) % n
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _is_strong_prp(n, a):
|
| 328 |
+
s = bit_scan1(n - 1)
|
| 329 |
+
a = pow(a, n >> s, n)
|
| 330 |
+
if a == 1 or a == n - 1:
|
| 331 |
+
return True
|
| 332 |
+
for _ in range(s - 1):
|
| 333 |
+
a = pow(a, 2, n)
|
| 334 |
+
if a == n - 1:
|
| 335 |
+
return True
|
| 336 |
+
if a == 1:
|
| 337 |
+
return False
|
| 338 |
+
return False
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def is_strong_prp(n, a):
|
| 342 |
+
if a < 2:
|
| 343 |
+
raise ValueError("is_strong_prp() requires 'a' greater than or equal to 2")
|
| 344 |
+
if n < 1:
|
| 345 |
+
raise ValueError("is_strong_prp() requires 'n' be greater than 0")
|
| 346 |
+
if n == 1:
|
| 347 |
+
return False
|
| 348 |
+
if n % 2 == 0:
|
| 349 |
+
return n == 2
|
| 350 |
+
a %= n
|
| 351 |
+
if gcd(n, a) != 1:
|
| 352 |
+
raise ValueError("is_strong_prp() requires gcd(n,a) == 1")
|
| 353 |
+
return _is_strong_prp(n, a)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def _lucas_sequence(n, P, Q, k):
|
| 357 |
+
r"""Return the modular Lucas sequence (U_k, V_k, Q_k).
|
| 358 |
+
|
| 359 |
+
Explanation
|
| 360 |
+
===========
|
| 361 |
+
|
| 362 |
+
Given a Lucas sequence defined by P, Q, returns the kth values for
|
| 363 |
+
U and V, along with Q^k, all modulo n. This is intended for use with
|
| 364 |
+
possibly very large values of n and k, where the combinatorial functions
|
| 365 |
+
would be completely unusable.
|
| 366 |
+
|
| 367 |
+
.. math ::
|
| 368 |
+
U_k = \begin{cases}
|
| 369 |
+
0 & \text{if } k = 0\\
|
| 370 |
+
1 & \text{if } k = 1\\
|
| 371 |
+
PU_{k-1} - QU_{k-2} & \text{if } k > 1
|
| 372 |
+
\end{cases}\\
|
| 373 |
+
V_k = \begin{cases}
|
| 374 |
+
2 & \text{if } k = 0\\
|
| 375 |
+
P & \text{if } k = 1\\
|
| 376 |
+
PV_{k-1} - QV_{k-2} & \text{if } k > 1
|
| 377 |
+
\end{cases}
|
| 378 |
+
|
| 379 |
+
The modular Lucas sequences are used in numerous places in number theory,
|
| 380 |
+
especially in the Lucas compositeness tests and the various n + 1 proofs.
|
| 381 |
+
|
| 382 |
+
Parameters
|
| 383 |
+
==========
|
| 384 |
+
|
| 385 |
+
n : int
|
| 386 |
+
n is an odd number greater than or equal to 3
|
| 387 |
+
P : int
|
| 388 |
+
Q : int
|
| 389 |
+
D determined by D = P**2 - 4*Q is non-zero
|
| 390 |
+
k : int
|
| 391 |
+
k is a nonnegative integer
|
| 392 |
+
|
| 393 |
+
Returns
|
| 394 |
+
=======
|
| 395 |
+
|
| 396 |
+
U, V, Qk : (int, int, int)
|
| 397 |
+
`(U_k \bmod{n}, V_k \bmod{n}, Q^k \bmod{n})`
|
| 398 |
+
|
| 399 |
+
Examples
|
| 400 |
+
========
|
| 401 |
+
|
| 402 |
+
>>> from sympy.external.ntheory import _lucas_sequence
|
| 403 |
+
>>> N = 10**2000 + 4561
|
| 404 |
+
>>> sol = U, V, Qk = _lucas_sequence(N, 3, 1, N//2); sol
|
| 405 |
+
(0, 2, 1)
|
| 406 |
+
|
| 407 |
+
References
|
| 408 |
+
==========
|
| 409 |
+
|
| 410 |
+
.. [1] https://en.wikipedia.org/wiki/Lucas_sequence
|
| 411 |
+
|
| 412 |
+
"""
|
| 413 |
+
if k == 0:
|
| 414 |
+
return (0, 2, 1)
|
| 415 |
+
D = P**2 - 4*Q
|
| 416 |
+
U = 1
|
| 417 |
+
V = P
|
| 418 |
+
Qk = Q % n
|
| 419 |
+
if Q == 1:
|
| 420 |
+
# Optimization for extra strong tests.
|
| 421 |
+
for b in bin(k)[3:]:
|
| 422 |
+
U = (U*V) % n
|
| 423 |
+
V = (V*V - 2) % n
|
| 424 |
+
if b == "1":
|
| 425 |
+
U, V = U*P + V, V*P + U*D
|
| 426 |
+
if U & 1:
|
| 427 |
+
U += n
|
| 428 |
+
if V & 1:
|
| 429 |
+
V += n
|
| 430 |
+
U, V = U >> 1, V >> 1
|
| 431 |
+
elif P == 1 and Q == -1:
|
| 432 |
+
# Small optimization for 50% of Selfridge parameters.
|
| 433 |
+
for b in bin(k)[3:]:
|
| 434 |
+
U = (U*V) % n
|
| 435 |
+
if Qk == 1:
|
| 436 |
+
V = (V*V - 2) % n
|
| 437 |
+
else:
|
| 438 |
+
V = (V*V + 2) % n
|
| 439 |
+
Qk = 1
|
| 440 |
+
if b == "1":
|
| 441 |
+
# new_U = (U + V) // 2
|
| 442 |
+
# new_V = (5*U + V) // 2 = 2*U + new_U
|
| 443 |
+
U, V = U + V, U << 1
|
| 444 |
+
if U & 1:
|
| 445 |
+
U += n
|
| 446 |
+
U >>= 1
|
| 447 |
+
V += U
|
| 448 |
+
Qk = -1
|
| 449 |
+
Qk %= n
|
| 450 |
+
elif P == 1:
|
| 451 |
+
for b in bin(k)[3:]:
|
| 452 |
+
U = (U*V) % n
|
| 453 |
+
V = (V*V - 2*Qk) % n
|
| 454 |
+
Qk *= Qk
|
| 455 |
+
if b == "1":
|
| 456 |
+
# new_U = (U + V) // 2
|
| 457 |
+
# new_V = new_U - 2*Q*U
|
| 458 |
+
U, V = U + V, (Q*U) << 1
|
| 459 |
+
if U & 1:
|
| 460 |
+
U += n
|
| 461 |
+
U >>= 1
|
| 462 |
+
V = U - V
|
| 463 |
+
Qk *= Q
|
| 464 |
+
Qk %= n
|
| 465 |
+
else:
|
| 466 |
+
# The general case with any P and Q.
|
| 467 |
+
for b in bin(k)[3:]:
|
| 468 |
+
U = (U*V) % n
|
| 469 |
+
V = (V*V - 2*Qk) % n
|
| 470 |
+
Qk *= Qk
|
| 471 |
+
if b == "1":
|
| 472 |
+
U, V = U*P + V, V*P + U*D
|
| 473 |
+
if U & 1:
|
| 474 |
+
U += n
|
| 475 |
+
if V & 1:
|
| 476 |
+
V += n
|
| 477 |
+
U, V = U >> 1, V >> 1
|
| 478 |
+
Qk *= Q
|
| 479 |
+
Qk %= n
|
| 480 |
+
return (U % n, V % n, Qk)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def is_fibonacci_prp(n, p, q):
|
| 484 |
+
d = p**2 - 4*q
|
| 485 |
+
if d == 0 or p <= 0 or q not in [1, -1]:
|
| 486 |
+
raise ValueError("invalid values for p,q in is_fibonacci_prp()")
|
| 487 |
+
if n < 1:
|
| 488 |
+
raise ValueError("is_fibonacci_prp() requires 'n' be greater than 0")
|
| 489 |
+
if n == 1:
|
| 490 |
+
return False
|
| 491 |
+
if n % 2 == 0:
|
| 492 |
+
return n == 2
|
| 493 |
+
return _lucas_sequence(n, p, q, n)[1] == p % n
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def is_lucas_prp(n, p, q):
|
| 497 |
+
d = p**2 - 4*q
|
| 498 |
+
if d == 0:
|
| 499 |
+
raise ValueError("invalid values for p,q in is_lucas_prp()")
|
| 500 |
+
if n < 1:
|
| 501 |
+
raise ValueError("is_lucas_prp() requires 'n' be greater than 0")
|
| 502 |
+
if n == 1:
|
| 503 |
+
return False
|
| 504 |
+
if n % 2 == 0:
|
| 505 |
+
return n == 2
|
| 506 |
+
if gcd(n, q*d) not in [1, n]:
|
| 507 |
+
raise ValueError("is_lucas_prp() requires gcd(n,2*q*D) == 1")
|
| 508 |
+
return _lucas_sequence(n, p, q, n - jacobi(d, n))[0] == 0
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _is_selfridge_prp(n):
|
| 512 |
+
"""Lucas compositeness test with the Selfridge parameters for n.
|
| 513 |
+
|
| 514 |
+
Explanation
|
| 515 |
+
===========
|
| 516 |
+
|
| 517 |
+
The Lucas compositeness test checks whether n is a prime number.
|
| 518 |
+
The test can be run with arbitrary parameters ``P`` and ``Q``, which also change the performance of the test.
|
| 519 |
+
So, which parameters are most effective for running the Lucas compositeness test?
|
| 520 |
+
As an algorithm for determining ``P`` and ``Q``, Selfridge proposed method A [1]_ page 1401
|
| 521 |
+
(Since two methods were proposed, referred to simply as A and B in the paper,
|
| 522 |
+
we will refer to one of them as "method A").
|
| 523 |
+
|
| 524 |
+
method A fixes ``P = 1``. Then, ``D`` defined by ``D = P**2 - 4Q`` is varied from 5, -7, 9, -11, 13, and so on,
|
| 525 |
+
with the first ``D`` being ``jacobi(D, n) == -1``. Once ``D`` is determined,
|
| 526 |
+
``Q`` is determined to be ``(P**2 - D)//4``.
|
| 527 |
+
|
| 528 |
+
References
|
| 529 |
+
==========
|
| 530 |
+
|
| 531 |
+
.. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
|
| 532 |
+
Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
|
| 533 |
+
https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
|
| 534 |
+
http://mpqs.free.fr/LucasPseudoprimes.pdf
|
| 535 |
+
|
| 536 |
+
"""
|
| 537 |
+
for D in range(5, 1_000_000, 2):
|
| 538 |
+
if D & 2: # if D % 4 == 3
|
| 539 |
+
D = -D
|
| 540 |
+
j = jacobi(D, n)
|
| 541 |
+
if j == -1:
|
| 542 |
+
return _lucas_sequence(n, 1, (1-D) // 4, n + 1)[0] == 0
|
| 543 |
+
if j == 0 and D % n:
|
| 544 |
+
return False
|
| 545 |
+
# When j == -1 is hard to find, suspect a square number
|
| 546 |
+
if D == 13 and is_square(n):
|
| 547 |
+
return False
|
| 548 |
+
raise ValueError("appropriate value for D cannot be found in is_selfridge_prp()")
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def is_selfridge_prp(n):
|
| 552 |
+
if n < 1:
|
| 553 |
+
raise ValueError("is_selfridge_prp() requires 'n' be greater than 0")
|
| 554 |
+
if n == 1:
|
| 555 |
+
return False
|
| 556 |
+
if n % 2 == 0:
|
| 557 |
+
return n == 2
|
| 558 |
+
return _is_selfridge_prp(n)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def is_strong_lucas_prp(n, p, q):
|
| 562 |
+
D = p**2 - 4*q
|
| 563 |
+
if D == 0:
|
| 564 |
+
raise ValueError("invalid values for p,q in is_strong_lucas_prp()")
|
| 565 |
+
if n < 1:
|
| 566 |
+
raise ValueError("is_selfridge_prp() requires 'n' be greater than 0")
|
| 567 |
+
if n == 1:
|
| 568 |
+
return False
|
| 569 |
+
if n % 2 == 0:
|
| 570 |
+
return n == 2
|
| 571 |
+
if gcd(n, q*D) not in [1, n]:
|
| 572 |
+
raise ValueError("is_strong_lucas_prp() requires gcd(n,2*q*D) == 1")
|
| 573 |
+
j = jacobi(D, n)
|
| 574 |
+
s = bit_scan1(n - j)
|
| 575 |
+
U, V, Qk = _lucas_sequence(n, p, q, (n - j) >> s)
|
| 576 |
+
if U == 0 or V == 0:
|
| 577 |
+
return True
|
| 578 |
+
for _ in range(s - 1):
|
| 579 |
+
V = (V*V - 2*Qk) % n
|
| 580 |
+
if V == 0:
|
| 581 |
+
return True
|
| 582 |
+
Qk = pow(Qk, 2, n)
|
| 583 |
+
return False
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def _is_strong_selfridge_prp(n):
|
| 587 |
+
for D in range(5, 1_000_000, 2):
|
| 588 |
+
if D & 2: # if D % 4 == 3
|
| 589 |
+
D = -D
|
| 590 |
+
j = jacobi(D, n)
|
| 591 |
+
if j == -1:
|
| 592 |
+
s = bit_scan1(n + 1)
|
| 593 |
+
U, V, Qk = _lucas_sequence(n, 1, (1-D) // 4, (n + 1) >> s)
|
| 594 |
+
if U == 0 or V == 0:
|
| 595 |
+
return True
|
| 596 |
+
for _ in range(s - 1):
|
| 597 |
+
V = (V*V - 2*Qk) % n
|
| 598 |
+
if V == 0:
|
| 599 |
+
return True
|
| 600 |
+
Qk = pow(Qk, 2, n)
|
| 601 |
+
return False
|
| 602 |
+
if j == 0 and D % n:
|
| 603 |
+
return False
|
| 604 |
+
# When j == -1 is hard to find, suspect a square number
|
| 605 |
+
if D == 13 and is_square(n):
|
| 606 |
+
return False
|
| 607 |
+
raise ValueError("appropriate value for D cannot be found in is_strong_selfridge_prp()")
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def is_strong_selfridge_prp(n):
|
| 611 |
+
if n < 1:
|
| 612 |
+
raise ValueError("is_strong_selfridge_prp() requires 'n' be greater than 0")
|
| 613 |
+
if n == 1:
|
| 614 |
+
return False
|
| 615 |
+
if n % 2 == 0:
|
| 616 |
+
return n == 2
|
| 617 |
+
return _is_strong_selfridge_prp(n)
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def is_bpsw_prp(n):
|
| 621 |
+
if n < 1:
|
| 622 |
+
raise ValueError("is_bpsw_prp() requires 'n' be greater than 0")
|
| 623 |
+
if n == 1:
|
| 624 |
+
return False
|
| 625 |
+
if n % 2 == 0:
|
| 626 |
+
return n == 2
|
| 627 |
+
return _is_strong_prp(n, 2) and _is_selfridge_prp(n)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def is_strong_bpsw_prp(n):
|
| 631 |
+
if n < 1:
|
| 632 |
+
raise ValueError("is_strong_bpsw_prp() requires 'n' be greater than 0")
|
| 633 |
+
if n == 1:
|
| 634 |
+
return False
|
| 635 |
+
if n % 2 == 0:
|
| 636 |
+
return n == 2
|
| 637 |
+
return _is_strong_prp(n, 2) and _is_strong_selfridge_prp(n)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/pythonmpq.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PythonMPQ: Rational number type based on Python integers.
|
| 3 |
+
|
| 4 |
+
This class is intended as a pure Python fallback for when gmpy2 is not
|
| 5 |
+
installed. If gmpy2 is installed then its mpq type will be used instead. The
|
| 6 |
+
mpq type is around 20x faster. We could just use the stdlib Fraction class
|
| 7 |
+
here but that is slower:
|
| 8 |
+
|
| 9 |
+
from fractions import Fraction
|
| 10 |
+
from sympy.external.pythonmpq import PythonMPQ
|
| 11 |
+
nums = range(1000)
|
| 12 |
+
dens = range(5, 1005)
|
| 13 |
+
rats = [Fraction(n, d) for n, d in zip(nums, dens)]
|
| 14 |
+
sum(rats) # <--- 24 milliseconds
|
| 15 |
+
rats = [PythonMPQ(n, d) for n, d in zip(nums, dens)]
|
| 16 |
+
sum(rats) # <--- 7 milliseconds
|
| 17 |
+
|
| 18 |
+
Both mpq and Fraction have some awkward features like the behaviour of
|
| 19 |
+
division with // and %:
|
| 20 |
+
|
| 21 |
+
>>> from fractions import Fraction
|
| 22 |
+
>>> Fraction(2, 3) % Fraction(1, 4)
|
| 23 |
+
1/6
|
| 24 |
+
|
| 25 |
+
For the QQ domain we do not want this behaviour because there should be no
|
| 26 |
+
remainder when dividing rational numbers. SymPy does not make use of this
|
| 27 |
+
aspect of mpq when gmpy2 is installed. Since this class is a fallback for that
|
| 28 |
+
case we do not bother implementing e.g. __mod__ so that we can be sure we
|
| 29 |
+
are not using it when gmpy2 is installed either.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
import operator
|
| 34 |
+
from math import gcd
|
| 35 |
+
from decimal import Decimal
|
| 36 |
+
from fractions import Fraction
|
| 37 |
+
import sys
|
| 38 |
+
from typing import Tuple as tTuple, Type
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Used for __hash__
|
| 42 |
+
_PyHASH_MODULUS = sys.hash_info.modulus
|
| 43 |
+
_PyHASH_INF = sys.hash_info.inf
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class PythonMPQ:
|
| 47 |
+
"""Rational number implementation that is intended to be compatible with
|
| 48 |
+
gmpy2's mpq.
|
| 49 |
+
|
| 50 |
+
Also slightly faster than fractions.Fraction.
|
| 51 |
+
|
| 52 |
+
PythonMPQ should be treated as immutable although no effort is made to
|
| 53 |
+
prevent mutation (since that might slow down calculations).
|
| 54 |
+
"""
|
| 55 |
+
__slots__ = ('numerator', 'denominator')
|
| 56 |
+
|
| 57 |
+
def __new__(cls, numerator, denominator=None):
|
| 58 |
+
"""Construct PythonMPQ with gcd computation and checks"""
|
| 59 |
+
if denominator is not None:
|
| 60 |
+
#
|
| 61 |
+
# PythonMPQ(n, d): require n and d to be int and d != 0
|
| 62 |
+
#
|
| 63 |
+
if isinstance(numerator, int) and isinstance(denominator, int):
|
| 64 |
+
# This is the slow part:
|
| 65 |
+
divisor = gcd(numerator, denominator)
|
| 66 |
+
numerator //= divisor
|
| 67 |
+
denominator //= divisor
|
| 68 |
+
return cls._new_check(numerator, denominator)
|
| 69 |
+
else:
|
| 70 |
+
#
|
| 71 |
+
# PythonMPQ(q)
|
| 72 |
+
#
|
| 73 |
+
# Here q can be PythonMPQ, int, Decimal, float, Fraction or str
|
| 74 |
+
#
|
| 75 |
+
if isinstance(numerator, int):
|
| 76 |
+
return cls._new(numerator, 1)
|
| 77 |
+
elif isinstance(numerator, PythonMPQ):
|
| 78 |
+
return cls._new(numerator.numerator, numerator.denominator)
|
| 79 |
+
|
| 80 |
+
# Let Fraction handle Decimal/float conversion and str parsing
|
| 81 |
+
if isinstance(numerator, (Decimal, float, str)):
|
| 82 |
+
numerator = Fraction(numerator)
|
| 83 |
+
if isinstance(numerator, Fraction):
|
| 84 |
+
return cls._new(numerator.numerator, numerator.denominator)
|
| 85 |
+
#
|
| 86 |
+
# Reject everything else. This is more strict than mpq which allows
|
| 87 |
+
# things like mpq(Fraction, Fraction) or mpq(Decimal, any). The mpq
|
| 88 |
+
# behaviour is somewhat inconsistent so we choose to accept only a
|
| 89 |
+
# more strict subset of what mpq allows.
|
| 90 |
+
#
|
| 91 |
+
raise TypeError("PythonMPQ() requires numeric or string argument")
|
| 92 |
+
|
| 93 |
+
@classmethod
|
| 94 |
+
def _new_check(cls, numerator, denominator):
|
| 95 |
+
"""Construct PythonMPQ, check divide by zero and canonicalize signs"""
|
| 96 |
+
if not denominator:
|
| 97 |
+
raise ZeroDivisionError(f'Zero divisor {numerator}/{denominator}')
|
| 98 |
+
elif denominator < 0:
|
| 99 |
+
numerator = -numerator
|
| 100 |
+
denominator = -denominator
|
| 101 |
+
return cls._new(numerator, denominator)
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def _new(cls, numerator, denominator):
|
| 105 |
+
"""Construct PythonMPQ efficiently (no checks)"""
|
| 106 |
+
obj = super().__new__(cls)
|
| 107 |
+
obj.numerator = numerator
|
| 108 |
+
obj.denominator = denominator
|
| 109 |
+
return obj
|
| 110 |
+
|
| 111 |
+
def __int__(self):
|
| 112 |
+
"""Convert to int (truncates towards zero)"""
|
| 113 |
+
p, q = self.numerator, self.denominator
|
| 114 |
+
if p < 0:
|
| 115 |
+
return -(-p//q)
|
| 116 |
+
return p//q
|
| 117 |
+
|
| 118 |
+
def __float__(self):
|
| 119 |
+
"""Convert to float (approximately)"""
|
| 120 |
+
return self.numerator / self.denominator
|
| 121 |
+
|
| 122 |
+
def __bool__(self):
|
| 123 |
+
"""True/False if nonzero/zero"""
|
| 124 |
+
return bool(self.numerator)
|
| 125 |
+
|
| 126 |
+
def __eq__(self, other):
|
| 127 |
+
"""Compare equal with PythonMPQ, int, float, Decimal or Fraction"""
|
| 128 |
+
if isinstance(other, PythonMPQ):
|
| 129 |
+
return (self.numerator == other.numerator
|
| 130 |
+
and self.denominator == other.denominator)
|
| 131 |
+
elif isinstance(other, self._compatible_types):
|
| 132 |
+
return self.__eq__(PythonMPQ(other))
|
| 133 |
+
else:
|
| 134 |
+
return NotImplemented
|
| 135 |
+
|
| 136 |
+
def __hash__(self):
|
| 137 |
+
"""hash - same as mpq/Fraction"""
|
| 138 |
+
try:
|
| 139 |
+
dinv = pow(self.denominator, -1, _PyHASH_MODULUS)
|
| 140 |
+
except ValueError:
|
| 141 |
+
hash_ = _PyHASH_INF
|
| 142 |
+
else:
|
| 143 |
+
hash_ = hash(hash(abs(self.numerator)) * dinv)
|
| 144 |
+
result = hash_ if self.numerator >= 0 else -hash_
|
| 145 |
+
return -2 if result == -1 else result
|
| 146 |
+
|
| 147 |
+
def __reduce__(self):
|
| 148 |
+
"""Deconstruct for pickling"""
|
| 149 |
+
return type(self), (self.numerator, self.denominator)
|
| 150 |
+
|
| 151 |
+
def __str__(self):
|
| 152 |
+
"""Convert to string"""
|
| 153 |
+
if self.denominator != 1:
|
| 154 |
+
return f"{self.numerator}/{self.denominator}"
|
| 155 |
+
else:
|
| 156 |
+
return f"{self.numerator}"
|
| 157 |
+
|
| 158 |
+
def __repr__(self):
|
| 159 |
+
"""Convert to string"""
|
| 160 |
+
return f"MPQ({self.numerator},{self.denominator})"
|
| 161 |
+
|
| 162 |
+
def _cmp(self, other, op):
|
| 163 |
+
"""Helper for lt/le/gt/ge"""
|
| 164 |
+
if not isinstance(other, self._compatible_types):
|
| 165 |
+
return NotImplemented
|
| 166 |
+
lhs = self.numerator * other.denominator
|
| 167 |
+
rhs = other.numerator * self.denominator
|
| 168 |
+
return op(lhs, rhs)
|
| 169 |
+
|
| 170 |
+
def __lt__(self, other):
|
| 171 |
+
"""self < other"""
|
| 172 |
+
return self._cmp(other, operator.lt)
|
| 173 |
+
|
| 174 |
+
def __le__(self, other):
|
| 175 |
+
"""self <= other"""
|
| 176 |
+
return self._cmp(other, operator.le)
|
| 177 |
+
|
| 178 |
+
def __gt__(self, other):
|
| 179 |
+
"""self > other"""
|
| 180 |
+
return self._cmp(other, operator.gt)
|
| 181 |
+
|
| 182 |
+
def __ge__(self, other):
|
| 183 |
+
"""self >= other"""
|
| 184 |
+
return self._cmp(other, operator.ge)
|
| 185 |
+
|
| 186 |
+
def __abs__(self):
|
| 187 |
+
"""abs(q)"""
|
| 188 |
+
return self._new(abs(self.numerator), self.denominator)
|
| 189 |
+
|
| 190 |
+
def __pos__(self):
|
| 191 |
+
"""+q"""
|
| 192 |
+
return self
|
| 193 |
+
|
| 194 |
+
def __neg__(self):
|
| 195 |
+
"""-q"""
|
| 196 |
+
return self._new(-self.numerator, self.denominator)
|
| 197 |
+
|
| 198 |
+
def __add__(self, other):
|
| 199 |
+
"""q1 + q2"""
|
| 200 |
+
if isinstance(other, PythonMPQ):
|
| 201 |
+
#
|
| 202 |
+
# This is much faster than the naive method used in the stdlib
|
| 203 |
+
# fractions module. Not sure where this method comes from
|
| 204 |
+
# though...
|
| 205 |
+
#
|
| 206 |
+
# Compare timings for something like:
|
| 207 |
+
# nums = range(1000)
|
| 208 |
+
# rats = [PythonMPQ(n, d) for n, d in zip(nums[:-5], nums[5:])]
|
| 209 |
+
# sum(rats) # <-- time this
|
| 210 |
+
#
|
| 211 |
+
ap, aq = self.numerator, self.denominator
|
| 212 |
+
bp, bq = other.numerator, other.denominator
|
| 213 |
+
g = gcd(aq, bq)
|
| 214 |
+
if g == 1:
|
| 215 |
+
p = ap*bq + aq*bp
|
| 216 |
+
q = bq*aq
|
| 217 |
+
else:
|
| 218 |
+
q1, q2 = aq//g, bq//g
|
| 219 |
+
p, q = ap*q2 + bp*q1, q1*q2
|
| 220 |
+
g2 = gcd(p, g)
|
| 221 |
+
p, q = (p // g2), q * (g // g2)
|
| 222 |
+
|
| 223 |
+
elif isinstance(other, int):
|
| 224 |
+
p = self.numerator + self.denominator * other
|
| 225 |
+
q = self.denominator
|
| 226 |
+
else:
|
| 227 |
+
return NotImplemented
|
| 228 |
+
|
| 229 |
+
return self._new(p, q)
|
| 230 |
+
|
| 231 |
+
def __radd__(self, other):
|
| 232 |
+
"""z1 + q2"""
|
| 233 |
+
if isinstance(other, int):
|
| 234 |
+
p = self.numerator + self.denominator * other
|
| 235 |
+
q = self.denominator
|
| 236 |
+
return self._new(p, q)
|
| 237 |
+
else:
|
| 238 |
+
return NotImplemented
|
| 239 |
+
|
| 240 |
+
def __sub__(self ,other):
|
| 241 |
+
"""q1 - q2"""
|
| 242 |
+
if isinstance(other, PythonMPQ):
|
| 243 |
+
ap, aq = self.numerator, self.denominator
|
| 244 |
+
bp, bq = other.numerator, other.denominator
|
| 245 |
+
g = gcd(aq, bq)
|
| 246 |
+
if g == 1:
|
| 247 |
+
p = ap*bq - aq*bp
|
| 248 |
+
q = bq*aq
|
| 249 |
+
else:
|
| 250 |
+
q1, q2 = aq//g, bq//g
|
| 251 |
+
p, q = ap*q2 - bp*q1, q1*q2
|
| 252 |
+
g2 = gcd(p, g)
|
| 253 |
+
p, q = (p // g2), q * (g // g2)
|
| 254 |
+
elif isinstance(other, int):
|
| 255 |
+
p = self.numerator - self.denominator*other
|
| 256 |
+
q = self.denominator
|
| 257 |
+
else:
|
| 258 |
+
return NotImplemented
|
| 259 |
+
|
| 260 |
+
return self._new(p, q)
|
| 261 |
+
|
| 262 |
+
def __rsub__(self, other):
|
| 263 |
+
"""z1 - q2"""
|
| 264 |
+
if isinstance(other, int):
|
| 265 |
+
p = self.denominator * other - self.numerator
|
| 266 |
+
q = self.denominator
|
| 267 |
+
return self._new(p, q)
|
| 268 |
+
else:
|
| 269 |
+
return NotImplemented
|
| 270 |
+
|
| 271 |
+
def __mul__(self, other):
|
| 272 |
+
"""q1 * q2"""
|
| 273 |
+
if isinstance(other, PythonMPQ):
|
| 274 |
+
ap, aq = self.numerator, self.denominator
|
| 275 |
+
bp, bq = other.numerator, other.denominator
|
| 276 |
+
x1 = gcd(ap, bq)
|
| 277 |
+
x2 = gcd(bp, aq)
|
| 278 |
+
p, q = ((ap//x1)*(bp//x2), (aq//x2)*(bq//x1))
|
| 279 |
+
elif isinstance(other, int):
|
| 280 |
+
x = gcd(other, self.denominator)
|
| 281 |
+
p = self.numerator*(other//x)
|
| 282 |
+
q = self.denominator//x
|
| 283 |
+
else:
|
| 284 |
+
return NotImplemented
|
| 285 |
+
|
| 286 |
+
return self._new(p, q)
|
| 287 |
+
|
| 288 |
+
def __rmul__(self, other):
|
| 289 |
+
"""z1 * q2"""
|
| 290 |
+
if isinstance(other, int):
|
| 291 |
+
x = gcd(self.denominator, other)
|
| 292 |
+
p = self.numerator*(other//x)
|
| 293 |
+
q = self.denominator//x
|
| 294 |
+
return self._new(p, q)
|
| 295 |
+
else:
|
| 296 |
+
return NotImplemented
|
| 297 |
+
|
| 298 |
+
def __pow__(self, exp):
|
| 299 |
+
"""q ** z"""
|
| 300 |
+
p, q = self.numerator, self.denominator
|
| 301 |
+
|
| 302 |
+
if exp < 0:
|
| 303 |
+
p, q, exp = q, p, -exp
|
| 304 |
+
|
| 305 |
+
return self._new_check(p**exp, q**exp)
|
| 306 |
+
|
| 307 |
+
def __truediv__(self, other):
|
| 308 |
+
"""q1 / q2"""
|
| 309 |
+
if isinstance(other, PythonMPQ):
|
| 310 |
+
ap, aq = self.numerator, self.denominator
|
| 311 |
+
bp, bq = other.numerator, other.denominator
|
| 312 |
+
x1 = gcd(ap, bp)
|
| 313 |
+
x2 = gcd(bq, aq)
|
| 314 |
+
p, q = ((ap//x1)*(bq//x2), (aq//x2)*(bp//x1))
|
| 315 |
+
elif isinstance(other, int):
|
| 316 |
+
x = gcd(other, self.numerator)
|
| 317 |
+
p = self.numerator//x
|
| 318 |
+
q = self.denominator*(other//x)
|
| 319 |
+
else:
|
| 320 |
+
return NotImplemented
|
| 321 |
+
|
| 322 |
+
return self._new_check(p, q)
|
| 323 |
+
|
| 324 |
+
def __rtruediv__(self, other):
|
| 325 |
+
"""z / q"""
|
| 326 |
+
if isinstance(other, int):
|
| 327 |
+
x = gcd(self.numerator, other)
|
| 328 |
+
p = self.denominator*(other//x)
|
| 329 |
+
q = self.numerator//x
|
| 330 |
+
return self._new_check(p, q)
|
| 331 |
+
else:
|
| 332 |
+
return NotImplemented
|
| 333 |
+
|
| 334 |
+
_compatible_types: tTuple[Type, ...] = ()
|
| 335 |
+
|
| 336 |
+
#
|
| 337 |
+
# These are the types that PythonMPQ will interoperate with for operations
|
| 338 |
+
# and comparisons such as ==, + etc. We define this down here so that we can
|
| 339 |
+
# include PythonMPQ in the list as well.
|
| 340 |
+
#
|
| 341 |
+
PythonMPQ._compatible_types = (PythonMPQ, int, Decimal, Fraction)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__init__.py
ADDED
|
File without changes
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (182 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_autowrap.cpython-310.pyc
ADDED
|
Binary file (9.05 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc
ADDED
|
Binary file (9.62 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_gmpy.cpython-310.pyc
ADDED
|
Binary file (892 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc
ADDED
|
Binary file (1.47 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_ntheory.cpython-310.pyc
ADDED
|
Binary file (9.05 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_pythonmpq.cpython-310.pyc
ADDED
|
Binary file (6.13 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc
ADDED
|
Binary file (1.05 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sympy
|
| 2 |
+
import tempfile
|
| 3 |
+
import os
|
| 4 |
+
from sympy.core.mod import Mod
|
| 5 |
+
from sympy.core.relational import Eq
|
| 6 |
+
from sympy.core.symbol import symbols
|
| 7 |
+
from sympy.external import import_module
|
| 8 |
+
from sympy.tensor import IndexedBase, Idx
|
| 9 |
+
from sympy.utilities.autowrap import autowrap, ufuncify, CodeWrapError
|
| 10 |
+
from sympy.testing.pytest import skip
|
| 11 |
+
|
| 12 |
+
numpy = import_module('numpy', min_module_version='1.6.1')
|
| 13 |
+
Cython = import_module('Cython', min_module_version='0.15.1')
|
| 14 |
+
f2py = import_module('numpy.f2py', import_kwargs={'fromlist': ['f2py']})
|
| 15 |
+
|
| 16 |
+
f2pyworks = False
|
| 17 |
+
if f2py:
|
| 18 |
+
try:
|
| 19 |
+
autowrap(symbols('x'), 'f95', 'f2py')
|
| 20 |
+
except (CodeWrapError, ImportError, OSError):
|
| 21 |
+
f2pyworks = False
|
| 22 |
+
else:
|
| 23 |
+
f2pyworks = True
|
| 24 |
+
|
| 25 |
+
a, b, c = symbols('a b c')
|
| 26 |
+
n, m, d = symbols('n m d', integer=True)
|
| 27 |
+
A, B, C = symbols('A B C', cls=IndexedBase)
|
| 28 |
+
i = Idx('i', m)
|
| 29 |
+
j = Idx('j', n)
|
| 30 |
+
k = Idx('k', d)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def has_module(module):
|
| 34 |
+
"""
|
| 35 |
+
Return True if module exists, otherwise run skip().
|
| 36 |
+
|
| 37 |
+
module should be a string.
|
| 38 |
+
"""
|
| 39 |
+
# To give a string of the module name to skip(), this function takes a
|
| 40 |
+
# string. So we don't waste time running import_module() more than once,
|
| 41 |
+
# just map the three modules tested here in this dict.
|
| 42 |
+
modnames = {'numpy': numpy, 'Cython': Cython, 'f2py': f2py}
|
| 43 |
+
|
| 44 |
+
if modnames[module]:
|
| 45 |
+
if module == 'f2py' and not f2pyworks:
|
| 46 |
+
skip("Couldn't run f2py.")
|
| 47 |
+
return True
|
| 48 |
+
skip("Couldn't import %s." % module)
|
| 49 |
+
|
| 50 |
+
#
|
| 51 |
+
# test runners used by several language-backend combinations
|
| 52 |
+
#
|
| 53 |
+
|
| 54 |
+
def runtest_autowrap_twice(language, backend):
|
| 55 |
+
f = autowrap((((a + b)/c)**5).expand(), language, backend)
|
| 56 |
+
g = autowrap((((a + b)/c)**4).expand(), language, backend)
|
| 57 |
+
|
| 58 |
+
# check that autowrap updates the module name. Else, g gives the same as f
|
| 59 |
+
assert f(1, -2, 1) == -1.0
|
| 60 |
+
assert g(1, -2, 1) == 1.0
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def runtest_autowrap_trace(language, backend):
|
| 64 |
+
has_module('numpy')
|
| 65 |
+
trace = autowrap(A[i, i], language, backend)
|
| 66 |
+
assert trace(numpy.eye(100)) == 100
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def runtest_autowrap_matrix_vector(language, backend):
|
| 70 |
+
has_module('numpy')
|
| 71 |
+
x, y = symbols('x y', cls=IndexedBase)
|
| 72 |
+
expr = Eq(y[i], A[i, j]*x[j])
|
| 73 |
+
mv = autowrap(expr, language, backend)
|
| 74 |
+
|
| 75 |
+
# compare with numpy's dot product
|
| 76 |
+
M = numpy.random.rand(10, 20)
|
| 77 |
+
x = numpy.random.rand(20)
|
| 78 |
+
y = numpy.dot(M, x)
|
| 79 |
+
assert numpy.sum(numpy.abs(y - mv(M, x))) < 1e-13
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def runtest_autowrap_matrix_matrix(language, backend):
|
| 83 |
+
has_module('numpy')
|
| 84 |
+
expr = Eq(C[i, j], A[i, k]*B[k, j])
|
| 85 |
+
matmat = autowrap(expr, language, backend)
|
| 86 |
+
|
| 87 |
+
# compare with numpy's dot product
|
| 88 |
+
M1 = numpy.random.rand(10, 20)
|
| 89 |
+
M2 = numpy.random.rand(20, 15)
|
| 90 |
+
M3 = numpy.dot(M1, M2)
|
| 91 |
+
assert numpy.sum(numpy.abs(M3 - matmat(M1, M2))) < 1e-13
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def runtest_ufuncify(language, backend):
|
| 95 |
+
has_module('numpy')
|
| 96 |
+
a, b, c = symbols('a b c')
|
| 97 |
+
fabc = ufuncify([a, b, c], a*b + c, backend=backend)
|
| 98 |
+
facb = ufuncify([a, c, b], a*b + c, backend=backend)
|
| 99 |
+
grid = numpy.linspace(-2, 2, 50)
|
| 100 |
+
b = numpy.linspace(-5, 4, 50)
|
| 101 |
+
c = numpy.linspace(-1, 1, 50)
|
| 102 |
+
expected = grid*b + c
|
| 103 |
+
numpy.testing.assert_allclose(fabc(grid, b, c), expected)
|
| 104 |
+
numpy.testing.assert_allclose(facb(grid, c, b), expected)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def runtest_issue_10274(language, backend):
|
| 108 |
+
expr = (a - b + c)**(13)
|
| 109 |
+
tmp = tempfile.mkdtemp()
|
| 110 |
+
f = autowrap(expr, language, backend, tempdir=tmp,
|
| 111 |
+
helpers=('helper', a - b + c, (a, b, c)))
|
| 112 |
+
assert f(1, 1, 1) == 1
|
| 113 |
+
|
| 114 |
+
for file in os.listdir(tmp):
|
| 115 |
+
if not (file.startswith("wrapped_code_") and file.endswith(".c")):
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
with open(tmp + '/' + file) as fil:
|
| 119 |
+
lines = fil.readlines()
|
| 120 |
+
assert lines[0] == "/******************************************************************************\n"
|
| 121 |
+
assert "Code generated with SymPy " + sympy.__version__ in lines[1]
|
| 122 |
+
assert lines[2:] == [
|
| 123 |
+
" * *\n",
|
| 124 |
+
" * See http://www.sympy.org/ for more information. *\n",
|
| 125 |
+
" * *\n",
|
| 126 |
+
" * This file is part of 'autowrap' *\n",
|
| 127 |
+
" ******************************************************************************/\n",
|
| 128 |
+
"#include " + '"' + file[:-1]+ 'h"' + "\n",
|
| 129 |
+
"#include <math.h>\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"double helper(double a, double b, double c) {\n",
|
| 132 |
+
"\n",
|
| 133 |
+
" double helper_result;\n",
|
| 134 |
+
" helper_result = a - b + c;\n",
|
| 135 |
+
" return helper_result;\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"}\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"double autofunc(double a, double b, double c) {\n",
|
| 140 |
+
"\n",
|
| 141 |
+
" double autofunc_result;\n",
|
| 142 |
+
" autofunc_result = pow(helper(a, b, c), 13);\n",
|
| 143 |
+
" return autofunc_result;\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"}\n",
|
| 146 |
+
]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def runtest_issue_15337(language, backend):
|
| 150 |
+
has_module('numpy')
|
| 151 |
+
# NOTE : autowrap was originally designed to only accept an iterable for
|
| 152 |
+
# the kwarg "helpers", but in issue 10274 the user mistakenly thought that
|
| 153 |
+
# if there was only a single helper it did not need to be passed via an
|
| 154 |
+
# iterable that wrapped the helper tuple. There were no tests for this
|
| 155 |
+
# behavior so when the code was changed to accept a single tuple it broke
|
| 156 |
+
# the original behavior. These tests below ensure that both now work.
|
| 157 |
+
a, b, c, d, e = symbols('a, b, c, d, e')
|
| 158 |
+
expr = (a - b + c - d + e)**13
|
| 159 |
+
exp_res = (1. - 2. + 3. - 4. + 5.)**13
|
| 160 |
+
|
| 161 |
+
f = autowrap(expr, language, backend, args=(a, b, c, d, e),
|
| 162 |
+
helpers=('f1', a - b + c, (a, b, c)))
|
| 163 |
+
numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res)
|
| 164 |
+
|
| 165 |
+
f = autowrap(expr, language, backend, args=(a, b, c, d, e),
|
| 166 |
+
helpers=(('f1', a - b, (a, b)), ('f2', c - d, (c, d))))
|
| 167 |
+
numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def test_issue_15230():
|
| 171 |
+
has_module('f2py')
|
| 172 |
+
|
| 173 |
+
x, y = symbols('x, y')
|
| 174 |
+
expr = Mod(x, 3.0) - Mod(y, -2.0)
|
| 175 |
+
f = autowrap(expr, args=[x, y], language='F95')
|
| 176 |
+
exp_res = float(expr.xreplace({x: 3.5, y: 2.7}).evalf())
|
| 177 |
+
assert abs(f(3.5, 2.7) - exp_res) < 1e-14
|
| 178 |
+
|
| 179 |
+
x, y = symbols('x, y', integer=True)
|
| 180 |
+
expr = Mod(x, 3) - Mod(y, -2)
|
| 181 |
+
f = autowrap(expr, args=[x, y], language='F95')
|
| 182 |
+
assert f(3, 2) == expr.xreplace({x: 3, y: 2})
|
| 183 |
+
|
| 184 |
+
#
|
| 185 |
+
# tests of language-backend combinations
|
| 186 |
+
#
|
| 187 |
+
|
| 188 |
+
# f2py
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_wrap_twice_f95_f2py():
|
| 192 |
+
has_module('f2py')
|
| 193 |
+
runtest_autowrap_twice('f95', 'f2py')
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def test_autowrap_trace_f95_f2py():
|
| 197 |
+
has_module('f2py')
|
| 198 |
+
runtest_autowrap_trace('f95', 'f2py')
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def test_autowrap_matrix_vector_f95_f2py():
|
| 202 |
+
has_module('f2py')
|
| 203 |
+
runtest_autowrap_matrix_vector('f95', 'f2py')
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def test_autowrap_matrix_matrix_f95_f2py():
|
| 207 |
+
has_module('f2py')
|
| 208 |
+
runtest_autowrap_matrix_matrix('f95', 'f2py')
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def test_ufuncify_f95_f2py():
|
| 212 |
+
has_module('f2py')
|
| 213 |
+
runtest_ufuncify('f95', 'f2py')
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def test_issue_15337_f95_f2py():
|
| 217 |
+
has_module('f2py')
|
| 218 |
+
runtest_issue_15337('f95', 'f2py')
|
| 219 |
+
|
| 220 |
+
# Cython
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def test_wrap_twice_c_cython():
|
| 224 |
+
has_module('Cython')
|
| 225 |
+
runtest_autowrap_twice('C', 'cython')
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def test_autowrap_trace_C_Cython():
|
| 229 |
+
has_module('Cython')
|
| 230 |
+
runtest_autowrap_trace('C99', 'cython')
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def test_autowrap_matrix_vector_C_cython():
|
| 234 |
+
has_module('Cython')
|
| 235 |
+
runtest_autowrap_matrix_vector('C99', 'cython')
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def test_autowrap_matrix_matrix_C_cython():
|
| 239 |
+
has_module('Cython')
|
| 240 |
+
runtest_autowrap_matrix_matrix('C99', 'cython')
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def test_ufuncify_C_Cython():
|
| 244 |
+
has_module('Cython')
|
| 245 |
+
runtest_ufuncify('C99', 'cython')
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def test_issue_10274_C_cython():
|
| 249 |
+
has_module('Cython')
|
| 250 |
+
runtest_issue_10274('C89', 'cython')
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def test_issue_15337_C_cython():
|
| 254 |
+
has_module('Cython')
|
| 255 |
+
runtest_issue_15337('C89', 'cython')
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def test_autowrap_custom_printer():
|
| 259 |
+
has_module('Cython')
|
| 260 |
+
|
| 261 |
+
from sympy.core.numbers import pi
|
| 262 |
+
from sympy.utilities.codegen import C99CodeGen
|
| 263 |
+
from sympy.printing.c import C99CodePrinter
|
| 264 |
+
|
| 265 |
+
class PiPrinter(C99CodePrinter):
|
| 266 |
+
def _print_Pi(self, expr):
|
| 267 |
+
return "S_PI"
|
| 268 |
+
|
| 269 |
+
printer = PiPrinter()
|
| 270 |
+
gen = C99CodeGen(printer=printer)
|
| 271 |
+
gen.preprocessor_statements.append('#include "shortpi.h"')
|
| 272 |
+
|
| 273 |
+
expr = pi * a
|
| 274 |
+
|
| 275 |
+
expected = (
|
| 276 |
+
'#include "%s"\n'
|
| 277 |
+
'#include <math.h>\n'
|
| 278 |
+
'#include "shortpi.h"\n'
|
| 279 |
+
'\n'
|
| 280 |
+
'double autofunc(double a) {\n'
|
| 281 |
+
'\n'
|
| 282 |
+
' double autofunc_result;\n'
|
| 283 |
+
' autofunc_result = S_PI*a;\n'
|
| 284 |
+
' return autofunc_result;\n'
|
| 285 |
+
'\n'
|
| 286 |
+
'}\n'
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
tmpdir = tempfile.mkdtemp()
|
| 290 |
+
# write a trivial header file to use in the generated code
|
| 291 |
+
with open(os.path.join(tmpdir, 'shortpi.h'), 'w') as f:
|
| 292 |
+
f.write('#define S_PI 3.14')
|
| 293 |
+
|
| 294 |
+
func = autowrap(expr, backend='cython', tempdir=tmpdir, code_gen=gen)
|
| 295 |
+
|
| 296 |
+
assert func(4.2) == 3.14 * 4.2
|
| 297 |
+
|
| 298 |
+
# check that the generated code is correct
|
| 299 |
+
for filename in os.listdir(tmpdir):
|
| 300 |
+
if filename.startswith('wrapped_code') and filename.endswith('.c'):
|
| 301 |
+
with open(os.path.join(tmpdir, filename)) as f:
|
| 302 |
+
lines = f.readlines()
|
| 303 |
+
expected = expected % filename.replace('.c', '.h')
|
| 304 |
+
assert ''.join(lines[7:]) == expected
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
# Numpy
|
| 308 |
+
|
| 309 |
+
def test_ufuncify_numpy():
|
| 310 |
+
# This test doesn't use Cython, but if Cython works, then there is a valid
|
| 311 |
+
# C compiler, which is needed.
|
| 312 |
+
has_module('Cython')
|
| 313 |
+
runtest_ufuncify('C99', 'numpy')
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This tests the compilation and execution of the source code generated with
|
| 2 |
+
# utilities.codegen. The compilation takes place in a temporary directory that
|
| 3 |
+
# is removed after the test. By default the test directory is always removed,
|
| 4 |
+
# but this behavior can be changed by setting the environment variable
|
| 5 |
+
# SYMPY_TEST_CLEAN_TEMP to:
|
| 6 |
+
# export SYMPY_TEST_CLEAN_TEMP=always : the default behavior.
|
| 7 |
+
# export SYMPY_TEST_CLEAN_TEMP=success : only remove the directories of working tests.
|
| 8 |
+
# export SYMPY_TEST_CLEAN_TEMP=never : never remove the directories with the test code.
|
| 9 |
+
# When a directory is not removed, the necessary information is printed on
|
| 10 |
+
# screen to find the files that belong to the (failed) tests. If a test does
|
| 11 |
+
# not fail, py.test captures all the output and you will not see the directories
|
| 12 |
+
# corresponding to the successful tests. Use the --nocapture option to see all
|
| 13 |
+
# the output.
|
| 14 |
+
|
| 15 |
+
# All tests below have a counterpart in utilities/test/test_codegen.py. In the
|
| 16 |
+
# latter file, the resulting code is compared with predefined strings, without
|
| 17 |
+
# compilation or execution.
|
| 18 |
+
|
| 19 |
+
# All the generated Fortran code should conform with the Fortran 95 standard,
|
| 20 |
+
# and all the generated C code should be ANSI C, which facilitates the
|
| 21 |
+
# incorporation in various projects. The tests below assume that the binary cc
|
| 22 |
+
# is somewhere in the path and that it can compile ANSI C code.
|
| 23 |
+
|
| 24 |
+
from sympy.abc import x, y, z
|
| 25 |
+
from sympy.external import import_module
|
| 26 |
+
from sympy.testing.pytest import skip
|
| 27 |
+
from sympy.utilities.codegen import codegen, make_routine, get_code_generator
|
| 28 |
+
import sys
|
| 29 |
+
import os
|
| 30 |
+
import tempfile
|
| 31 |
+
import subprocess
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
pyodide_js = import_module('pyodide_js')
|
| 35 |
+
|
| 36 |
+
# templates for the main program that will test the generated code.
|
| 37 |
+
|
| 38 |
+
main_template = {}
|
| 39 |
+
main_template['F95'] = """
|
| 40 |
+
program main
|
| 41 |
+
include "codegen.h"
|
| 42 |
+
integer :: result;
|
| 43 |
+
result = 0
|
| 44 |
+
|
| 45 |
+
%(statements)s
|
| 46 |
+
|
| 47 |
+
call exit(result)
|
| 48 |
+
end program
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
main_template['C89'] = """
|
| 52 |
+
#include "codegen.h"
|
| 53 |
+
#include <stdio.h>
|
| 54 |
+
#include <math.h>
|
| 55 |
+
|
| 56 |
+
int main() {
|
| 57 |
+
int result = 0;
|
| 58 |
+
|
| 59 |
+
%(statements)s
|
| 60 |
+
|
| 61 |
+
return result;
|
| 62 |
+
}
|
| 63 |
+
"""
|
| 64 |
+
main_template['C99'] = main_template['C89']
|
| 65 |
+
# templates for the numerical tests
|
| 66 |
+
|
| 67 |
+
numerical_test_template = {}
|
| 68 |
+
numerical_test_template['C89'] = """
|
| 69 |
+
if (fabs(%(call)s)>%(threshold)s) {
|
| 70 |
+
printf("Numerical validation failed: %(call)s=%%e threshold=%(threshold)s\\n", %(call)s);
|
| 71 |
+
result = -1;
|
| 72 |
+
}
|
| 73 |
+
"""
|
| 74 |
+
numerical_test_template['C99'] = numerical_test_template['C89']
|
| 75 |
+
|
| 76 |
+
numerical_test_template['F95'] = """
|
| 77 |
+
if (abs(%(call)s)>%(threshold)s) then
|
| 78 |
+
write(6,"('Numerical validation failed:')")
|
| 79 |
+
write(6,"('%(call)s=',e15.5,'threshold=',e15.5)") %(call)s, %(threshold)s
|
| 80 |
+
result = -1;
|
| 81 |
+
end if
|
| 82 |
+
"""
|
| 83 |
+
# command sequences for supported compilers
|
| 84 |
+
|
| 85 |
+
compile_commands = {}
|
| 86 |
+
compile_commands['cc'] = [
|
| 87 |
+
"cc -c codegen.c -o codegen.o",
|
| 88 |
+
"cc -c main.c -o main.o",
|
| 89 |
+
"cc main.o codegen.o -lm -o test.exe"
|
| 90 |
+
]
|
| 91 |
+
|
| 92 |
+
compile_commands['gfortran'] = [
|
| 93 |
+
"gfortran -c codegen.f90 -o codegen.o",
|
| 94 |
+
"gfortran -ffree-line-length-none -c main.f90 -o main.o",
|
| 95 |
+
"gfortran main.o codegen.o -o test.exe"
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
compile_commands['g95'] = [
|
| 99 |
+
"g95 -c codegen.f90 -o codegen.o",
|
| 100 |
+
"g95 -ffree-line-length-huge -c main.f90 -o main.o",
|
| 101 |
+
"g95 main.o codegen.o -o test.exe"
|
| 102 |
+
]
|
| 103 |
+
|
| 104 |
+
compile_commands['ifort'] = [
|
| 105 |
+
"ifort -c codegen.f90 -o codegen.o",
|
| 106 |
+
"ifort -c main.f90 -o main.o",
|
| 107 |
+
"ifort main.o codegen.o -o test.exe"
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
combinations_lang_compiler = [
|
| 111 |
+
('C89', 'cc'),
|
| 112 |
+
('C99', 'cc'),
|
| 113 |
+
('F95', 'ifort'),
|
| 114 |
+
('F95', 'gfortran'),
|
| 115 |
+
('F95', 'g95')
|
| 116 |
+
]
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def try_run(commands):
|
| 120 |
+
"""Run a series of commands and only return True if all ran fine."""
|
| 121 |
+
if pyodide_js:
|
| 122 |
+
return False
|
| 123 |
+
with open(os.devnull, 'w') as null:
|
| 124 |
+
for command in commands:
|
| 125 |
+
retcode = subprocess.call(command, stdout=null, shell=True,
|
| 126 |
+
stderr=subprocess.STDOUT)
|
| 127 |
+
if retcode != 0:
|
| 128 |
+
return False
|
| 129 |
+
return True
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def run_test(label, routines, numerical_tests, language, commands, friendly=True):
|
| 133 |
+
"""A driver for the codegen tests.
|
| 134 |
+
|
| 135 |
+
This driver assumes that a compiler ifort is present in the PATH and that
|
| 136 |
+
ifort is (at least) a Fortran 90 compiler. The generated code is written in
|
| 137 |
+
a temporary directory, together with a main program that validates the
|
| 138 |
+
generated code. The test passes when the compilation and the validation
|
| 139 |
+
run correctly.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
# Check input arguments before touching the file system
|
| 143 |
+
language = language.upper()
|
| 144 |
+
assert language in main_template
|
| 145 |
+
assert language in numerical_test_template
|
| 146 |
+
|
| 147 |
+
# Check that environment variable makes sense
|
| 148 |
+
clean = os.getenv('SYMPY_TEST_CLEAN_TEMP', 'always').lower()
|
| 149 |
+
if clean not in ('always', 'success', 'never'):
|
| 150 |
+
raise ValueError("SYMPY_TEST_CLEAN_TEMP must be one of the following: 'always', 'success' or 'never'.")
|
| 151 |
+
|
| 152 |
+
# Do all the magic to compile, run and validate the test code
|
| 153 |
+
# 1) prepare the temporary working directory, switch to that dir
|
| 154 |
+
work = tempfile.mkdtemp("_sympy_%s_test" % language, "%s_" % label)
|
| 155 |
+
oldwork = os.getcwd()
|
| 156 |
+
os.chdir(work)
|
| 157 |
+
|
| 158 |
+
# 2) write the generated code
|
| 159 |
+
if friendly:
|
| 160 |
+
# interpret the routines as a name_expr list and call the friendly
|
| 161 |
+
# function codegen
|
| 162 |
+
codegen(routines, language, "codegen", to_files=True)
|
| 163 |
+
else:
|
| 164 |
+
code_gen = get_code_generator(language, "codegen")
|
| 165 |
+
code_gen.write(routines, "codegen", to_files=True)
|
| 166 |
+
|
| 167 |
+
# 3) write a simple main program that links to the generated code, and that
|
| 168 |
+
# includes the numerical tests
|
| 169 |
+
test_strings = []
|
| 170 |
+
for fn_name, args, expected, threshold in numerical_tests:
|
| 171 |
+
call_string = "%s(%s)-(%s)" % (
|
| 172 |
+
fn_name, ",".join(str(arg) for arg in args), expected)
|
| 173 |
+
if language == "F95":
|
| 174 |
+
call_string = fortranize_double_constants(call_string)
|
| 175 |
+
threshold = fortranize_double_constants(str(threshold))
|
| 176 |
+
test_strings.append(numerical_test_template[language] % {
|
| 177 |
+
"call": call_string,
|
| 178 |
+
"threshold": threshold,
|
| 179 |
+
})
|
| 180 |
+
|
| 181 |
+
if language == "F95":
|
| 182 |
+
f_name = "main.f90"
|
| 183 |
+
elif language.startswith("C"):
|
| 184 |
+
f_name = "main.c"
|
| 185 |
+
else:
|
| 186 |
+
raise NotImplementedError(
|
| 187 |
+
"FIXME: filename extension unknown for language: %s" % language)
|
| 188 |
+
|
| 189 |
+
with open(f_name, "w") as f:
|
| 190 |
+
f.write(
|
| 191 |
+
main_template[language] % {'statements': "".join(test_strings)})
|
| 192 |
+
|
| 193 |
+
# 4) Compile and link
|
| 194 |
+
compiled = try_run(commands)
|
| 195 |
+
|
| 196 |
+
# 5) Run if compiled
|
| 197 |
+
if compiled:
|
| 198 |
+
executed = try_run(["./test.exe"])
|
| 199 |
+
else:
|
| 200 |
+
executed = False
|
| 201 |
+
|
| 202 |
+
# 6) Clean up stuff
|
| 203 |
+
if clean == 'always' or (clean == 'success' and compiled and executed):
|
| 204 |
+
def safe_remove(filename):
|
| 205 |
+
if os.path.isfile(filename):
|
| 206 |
+
os.remove(filename)
|
| 207 |
+
safe_remove("codegen.f90")
|
| 208 |
+
safe_remove("codegen.c")
|
| 209 |
+
safe_remove("codegen.h")
|
| 210 |
+
safe_remove("codegen.o")
|
| 211 |
+
safe_remove("main.f90")
|
| 212 |
+
safe_remove("main.c")
|
| 213 |
+
safe_remove("main.o")
|
| 214 |
+
safe_remove("test.exe")
|
| 215 |
+
os.chdir(oldwork)
|
| 216 |
+
os.rmdir(work)
|
| 217 |
+
else:
|
| 218 |
+
print("TEST NOT REMOVED: %s" % work, file=sys.stderr)
|
| 219 |
+
os.chdir(oldwork)
|
| 220 |
+
|
| 221 |
+
# 7) Do the assertions in the end
|
| 222 |
+
assert compiled, "failed to compile %s code with:\n%s" % (
|
| 223 |
+
language, "\n".join(commands))
|
| 224 |
+
assert executed, "failed to execute %s code from:\n%s" % (
|
| 225 |
+
language, "\n".join(commands))
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def fortranize_double_constants(code_string):
|
| 229 |
+
"""
|
| 230 |
+
Replaces every literal float with literal doubles
|
| 231 |
+
"""
|
| 232 |
+
import re
|
| 233 |
+
pattern_exp = re.compile(r'\d+(\.)?\d*[eE]-?\d+')
|
| 234 |
+
pattern_float = re.compile(r'\d+\.\d*(?!\d*d)')
|
| 235 |
+
|
| 236 |
+
def subs_exp(matchobj):
|
| 237 |
+
return re.sub('[eE]', 'd', matchobj.group(0))
|
| 238 |
+
|
| 239 |
+
def subs_float(matchobj):
|
| 240 |
+
return "%sd0" % matchobj.group(0)
|
| 241 |
+
|
| 242 |
+
code_string = pattern_exp.sub(subs_exp, code_string)
|
| 243 |
+
code_string = pattern_float.sub(subs_float, code_string)
|
| 244 |
+
|
| 245 |
+
return code_string
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def is_feasible(language, commands):
|
| 249 |
+
# This test should always work, otherwise the compiler is not present.
|
| 250 |
+
routine = make_routine("test", x)
|
| 251 |
+
numerical_tests = [
|
| 252 |
+
("test", ( 1.0,), 1.0, 1e-15),
|
| 253 |
+
("test", (-1.0,), -1.0, 1e-15),
|
| 254 |
+
]
|
| 255 |
+
try:
|
| 256 |
+
run_test("is_feasible", [routine], numerical_tests, language, commands,
|
| 257 |
+
friendly=False)
|
| 258 |
+
return True
|
| 259 |
+
except AssertionError:
|
| 260 |
+
return False
|
| 261 |
+
|
| 262 |
+
valid_lang_commands = []
|
| 263 |
+
invalid_lang_compilers = []
|
| 264 |
+
for lang, compiler in combinations_lang_compiler:
|
| 265 |
+
commands = compile_commands[compiler]
|
| 266 |
+
if is_feasible(lang, commands):
|
| 267 |
+
valid_lang_commands.append((lang, commands))
|
| 268 |
+
else:
|
| 269 |
+
invalid_lang_compilers.append((lang, compiler))
|
| 270 |
+
|
| 271 |
+
# We test all language-compiler combinations, just to report what is skipped
|
| 272 |
+
|
| 273 |
+
def test_C89_cc():
|
| 274 |
+
if ("C89", 'cc') in invalid_lang_compilers:
|
| 275 |
+
skip("`cc' command didn't work as expected (C89)")
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def test_C99_cc():
|
| 279 |
+
if ("C99", 'cc') in invalid_lang_compilers:
|
| 280 |
+
skip("`cc' command didn't work as expected (C99)")
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def test_F95_ifort():
|
| 284 |
+
if ("F95", 'ifort') in invalid_lang_compilers:
|
| 285 |
+
skip("`ifort' command didn't work as expected")
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def test_F95_gfortran():
|
| 289 |
+
if ("F95", 'gfortran') in invalid_lang_compilers:
|
| 290 |
+
skip("`gfortran' command didn't work as expected")
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def test_F95_g95():
|
| 294 |
+
if ("F95", 'g95') in invalid_lang_compilers:
|
| 295 |
+
skip("`g95' command didn't work as expected")
|
| 296 |
+
|
| 297 |
+
# Here comes the actual tests
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def test_basic_codegen():
|
| 301 |
+
numerical_tests = [
|
| 302 |
+
("test", (1.0, 6.0, 3.0), 21.0, 1e-15),
|
| 303 |
+
("test", (-1.0, 2.0, -2.5), -2.5, 1e-15),
|
| 304 |
+
]
|
| 305 |
+
name_expr = [("test", (x + y)*z)]
|
| 306 |
+
for lang, commands in valid_lang_commands:
|
| 307 |
+
run_test("basic_codegen", name_expr, numerical_tests, lang, commands)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def test_intrinsic_math1_codegen():
|
| 311 |
+
# not included: log10
|
| 312 |
+
from sympy.core.evalf import N
|
| 313 |
+
from sympy.functions import ln
|
| 314 |
+
from sympy.functions.elementary.exponential import log
|
| 315 |
+
from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
|
| 316 |
+
from sympy.functions.elementary.integers import (ceiling, floor)
|
| 317 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 318 |
+
from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan)
|
| 319 |
+
name_expr = [
|
| 320 |
+
("test_fabs", abs(x)),
|
| 321 |
+
("test_acos", acos(x)),
|
| 322 |
+
("test_asin", asin(x)),
|
| 323 |
+
("test_atan", atan(x)),
|
| 324 |
+
("test_cos", cos(x)),
|
| 325 |
+
("test_cosh", cosh(x)),
|
| 326 |
+
("test_log", log(x)),
|
| 327 |
+
("test_ln", ln(x)),
|
| 328 |
+
("test_sin", sin(x)),
|
| 329 |
+
("test_sinh", sinh(x)),
|
| 330 |
+
("test_sqrt", sqrt(x)),
|
| 331 |
+
("test_tan", tan(x)),
|
| 332 |
+
("test_tanh", tanh(x)),
|
| 333 |
+
]
|
| 334 |
+
numerical_tests = []
|
| 335 |
+
for name, expr in name_expr:
|
| 336 |
+
for xval in 0.2, 0.5, 0.8:
|
| 337 |
+
expected = N(expr.subs(x, xval))
|
| 338 |
+
numerical_tests.append((name, (xval,), expected, 1e-14))
|
| 339 |
+
for lang, commands in valid_lang_commands:
|
| 340 |
+
if lang.startswith("C"):
|
| 341 |
+
name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))]
|
| 342 |
+
else:
|
| 343 |
+
name_expr_C = []
|
| 344 |
+
run_test("intrinsic_math1", name_expr + name_expr_C,
|
| 345 |
+
numerical_tests, lang, commands)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def test_instrinsic_math2_codegen():
|
| 349 |
+
# not included: frexp, ldexp, modf, fmod
|
| 350 |
+
from sympy.core.evalf import N
|
| 351 |
+
from sympy.functions.elementary.trigonometric import atan2
|
| 352 |
+
name_expr = [
|
| 353 |
+
("test_atan2", atan2(x, y)),
|
| 354 |
+
("test_pow", x**y),
|
| 355 |
+
]
|
| 356 |
+
numerical_tests = []
|
| 357 |
+
for name, expr in name_expr:
|
| 358 |
+
for xval, yval in (0.2, 1.3), (0.5, -0.2), (0.8, 0.8):
|
| 359 |
+
expected = N(expr.subs(x, xval).subs(y, yval))
|
| 360 |
+
numerical_tests.append((name, (xval, yval), expected, 1e-14))
|
| 361 |
+
for lang, commands in valid_lang_commands:
|
| 362 |
+
run_test("intrinsic_math2", name_expr, numerical_tests, lang, commands)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def test_complicated_codegen():
|
| 366 |
+
from sympy.core.evalf import N
|
| 367 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
|
| 368 |
+
name_expr = [
|
| 369 |
+
("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
|
| 370 |
+
("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
|
| 371 |
+
]
|
| 372 |
+
numerical_tests = []
|
| 373 |
+
for name, expr in name_expr:
|
| 374 |
+
for xval, yval, zval in (0.2, 1.3, -0.3), (0.5, -0.2, 0.0), (0.8, 2.1, 0.8):
|
| 375 |
+
expected = N(expr.subs(x, xval).subs(y, yval).subs(z, zval))
|
| 376 |
+
numerical_tests.append((name, (xval, yval, zval), expected, 1e-12))
|
| 377 |
+
for lang, commands in valid_lang_commands:
|
| 378 |
+
run_test(
|
| 379 |
+
"complicated_codegen", name_expr, numerical_tests, lang, commands)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_gmpy.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.external.gmpy import LONG_MAX, iroot
|
| 2 |
+
from sympy.testing.pytest import raises
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_iroot():
|
| 6 |
+
assert iroot(2, LONG_MAX) == (1, False)
|
| 7 |
+
assert iroot(2, LONG_MAX + 1) == (1, False)
|
| 8 |
+
for x in range(3):
|
| 9 |
+
assert iroot(x, 1) == (x, True)
|
| 10 |
+
raises(ValueError, lambda: iroot(-1, 1))
|
| 11 |
+
raises(ValueError, lambda: iroot(0, 0))
|
| 12 |
+
raises(ValueError, lambda: iroot(0, -1))
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.external import import_module
|
| 2 |
+
from sympy.testing.pytest import warns
|
| 3 |
+
|
| 4 |
+
# fixes issue that arose in addressing issue 6533
|
| 5 |
+
def test_no_stdlib_collections():
|
| 6 |
+
'''
|
| 7 |
+
make sure we get the right collections when it is not part of a
|
| 8 |
+
larger list
|
| 9 |
+
'''
|
| 10 |
+
import collections
|
| 11 |
+
matplotlib = import_module('matplotlib',
|
| 12 |
+
import_kwargs={'fromlist': ['cm', 'collections']},
|
| 13 |
+
min_module_version='1.1.0', catch=(RuntimeError,))
|
| 14 |
+
if matplotlib:
|
| 15 |
+
assert collections != matplotlib.collections
|
| 16 |
+
|
| 17 |
+
def test_no_stdlib_collections2():
|
| 18 |
+
'''
|
| 19 |
+
make sure we get the right collections when it is not part of a
|
| 20 |
+
larger list
|
| 21 |
+
'''
|
| 22 |
+
import collections
|
| 23 |
+
matplotlib = import_module('matplotlib',
|
| 24 |
+
import_kwargs={'fromlist': ['collections']},
|
| 25 |
+
min_module_version='1.1.0', catch=(RuntimeError,))
|
| 26 |
+
if matplotlib:
|
| 27 |
+
assert collections != matplotlib.collections
|
| 28 |
+
|
| 29 |
+
def test_no_stdlib_collections3():
|
| 30 |
+
'''make sure we get the right collections with no catch'''
|
| 31 |
+
import collections
|
| 32 |
+
matplotlib = import_module('matplotlib',
|
| 33 |
+
import_kwargs={'fromlist': ['cm', 'collections']},
|
| 34 |
+
min_module_version='1.1.0')
|
| 35 |
+
if matplotlib:
|
| 36 |
+
assert collections != matplotlib.collections
|
| 37 |
+
|
| 38 |
+
def test_min_module_version_python3_basestring_error():
|
| 39 |
+
with warns(UserWarning):
|
| 40 |
+
import_module('mpmath', min_module_version='1000.0.1')
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_ntheory.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import permutations
|
| 2 |
+
|
| 3 |
+
from sympy.external.ntheory import (bit_scan1, remove, bit_scan0, is_fermat_prp,
|
| 4 |
+
is_euler_prp, is_strong_prp, gcdext, _lucas_sequence,
|
| 5 |
+
is_fibonacci_prp, is_lucas_prp, is_selfridge_prp,
|
| 6 |
+
is_strong_lucas_prp, is_strong_selfridge_prp,
|
| 7 |
+
is_bpsw_prp, is_strong_bpsw_prp)
|
| 8 |
+
from sympy.testing.pytest import raises
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_bit_scan1():
|
| 12 |
+
assert bit_scan1(0) is None
|
| 13 |
+
assert bit_scan1(1) == 0
|
| 14 |
+
assert bit_scan1(-1) == 0
|
| 15 |
+
assert bit_scan1(2) == 1
|
| 16 |
+
assert bit_scan1(7) == 0
|
| 17 |
+
assert bit_scan1(-7) == 0
|
| 18 |
+
for i in range(100):
|
| 19 |
+
assert bit_scan1(1 << i) == i
|
| 20 |
+
assert bit_scan1((1 << i) * 31337) == i
|
| 21 |
+
for i in range(500):
|
| 22 |
+
n = (1 << 500) + (1 << i)
|
| 23 |
+
assert bit_scan1(n) == i
|
| 24 |
+
assert bit_scan1(1 << 1000001) == 1000001
|
| 25 |
+
assert bit_scan1((1 << 273956)*7**37) == 273956
|
| 26 |
+
# issue 12709
|
| 27 |
+
for i in range(1, 10):
|
| 28 |
+
big = 1 << i
|
| 29 |
+
assert bit_scan1(-big) == bit_scan1(big)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_bit_scan0():
|
| 33 |
+
assert bit_scan0(-1) is None
|
| 34 |
+
assert bit_scan0(0) == 0
|
| 35 |
+
assert bit_scan0(1) == 1
|
| 36 |
+
assert bit_scan0(-2) == 0
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_remove():
|
| 40 |
+
raises(ValueError, lambda: remove(1, 1))
|
| 41 |
+
assert remove(0, 3) == (0, 0)
|
| 42 |
+
for f in range(2, 10):
|
| 43 |
+
for y in range(2, 1000):
|
| 44 |
+
for z in [1, 17, 101, 1009]:
|
| 45 |
+
assert remove(z*f**y, f) == (z, y)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_gcdext():
|
| 49 |
+
assert gcdext(0, 0) == (0, 0, 0)
|
| 50 |
+
assert gcdext(3, 0) == (3, 1, 0)
|
| 51 |
+
assert gcdext(0, 4) == (4, 0, 1)
|
| 52 |
+
|
| 53 |
+
for n in range(1, 10):
|
| 54 |
+
assert gcdext(n, 1) == gcdext(-n, 1) == (1, 0, 1)
|
| 55 |
+
assert gcdext(n, -1) == gcdext(-n, -1) == (1, 0, -1)
|
| 56 |
+
assert gcdext(n, n) == gcdext(-n, n) == (n, 0, 1)
|
| 57 |
+
assert gcdext(n, -n) == gcdext(-n, -n) == (n, 0, -1)
|
| 58 |
+
|
| 59 |
+
for n in range(2, 10):
|
| 60 |
+
assert gcdext(1, n) == gcdext(1, -n) == (1, 1, 0)
|
| 61 |
+
assert gcdext(-1, n) == gcdext(-1, -n) == (1, -1, 0)
|
| 62 |
+
|
| 63 |
+
for a, b in permutations([2**5, 3, 5, 7**2, 11], 2):
|
| 64 |
+
g, x, y = gcdext(a, b)
|
| 65 |
+
assert g == a*x + b*y == 1
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_is_fermat_prp():
|
| 69 |
+
# invalid input
|
| 70 |
+
raises(ValueError, lambda: is_fermat_prp(0, 10))
|
| 71 |
+
raises(ValueError, lambda: is_fermat_prp(5, 1))
|
| 72 |
+
|
| 73 |
+
# n = 1
|
| 74 |
+
assert not is_fermat_prp(1, 3)
|
| 75 |
+
|
| 76 |
+
# n is prime
|
| 77 |
+
assert is_fermat_prp(2, 4)
|
| 78 |
+
assert is_fermat_prp(3, 2)
|
| 79 |
+
assert is_fermat_prp(11, 3)
|
| 80 |
+
assert is_fermat_prp(2**31-1, 5)
|
| 81 |
+
|
| 82 |
+
# A001567
|
| 83 |
+
pseudorpime = [341, 561, 645, 1105, 1387, 1729, 1905, 2047,
|
| 84 |
+
2465, 2701, 2821, 3277, 4033, 4369, 4371, 4681]
|
| 85 |
+
for n in pseudorpime:
|
| 86 |
+
assert is_fermat_prp(n, 2)
|
| 87 |
+
|
| 88 |
+
# A020136
|
| 89 |
+
pseudorpime = [15, 85, 91, 341, 435, 451, 561, 645, 703, 1105,
|
| 90 |
+
1247, 1271, 1387, 1581, 1695, 1729, 1891, 1905]
|
| 91 |
+
for n in pseudorpime:
|
| 92 |
+
assert is_fermat_prp(n, 4)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_is_euler_prp():
|
| 96 |
+
# invalid input
|
| 97 |
+
raises(ValueError, lambda: is_euler_prp(0, 10))
|
| 98 |
+
raises(ValueError, lambda: is_euler_prp(5, 1))
|
| 99 |
+
|
| 100 |
+
# n = 1
|
| 101 |
+
assert not is_euler_prp(1, 3)
|
| 102 |
+
|
| 103 |
+
# n is prime
|
| 104 |
+
assert is_euler_prp(2, 4)
|
| 105 |
+
assert is_euler_prp(3, 2)
|
| 106 |
+
assert is_euler_prp(11, 3)
|
| 107 |
+
assert is_euler_prp(2**31-1, 5)
|
| 108 |
+
|
| 109 |
+
# A047713
|
| 110 |
+
pseudorpime = [561, 1105, 1729, 1905, 2047, 2465, 3277, 4033,
|
| 111 |
+
4681, 6601, 8321, 8481, 10585, 12801, 15841]
|
| 112 |
+
for n in pseudorpime:
|
| 113 |
+
assert is_euler_prp(n, 2)
|
| 114 |
+
|
| 115 |
+
# A048950
|
| 116 |
+
pseudorpime = [121, 703, 1729, 1891, 2821, 3281, 7381, 8401,
|
| 117 |
+
8911, 10585, 12403, 15457, 15841, 16531, 18721]
|
| 118 |
+
for n in pseudorpime:
|
| 119 |
+
assert is_euler_prp(n, 3)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_is_strong_prp():
|
| 123 |
+
# invalid input
|
| 124 |
+
raises(ValueError, lambda: is_strong_prp(0, 10))
|
| 125 |
+
raises(ValueError, lambda: is_strong_prp(5, 1))
|
| 126 |
+
|
| 127 |
+
# n = 1
|
| 128 |
+
assert not is_strong_prp(1, 3)
|
| 129 |
+
|
| 130 |
+
# n is prime
|
| 131 |
+
assert is_strong_prp(2, 4)
|
| 132 |
+
assert is_strong_prp(3, 2)
|
| 133 |
+
assert is_strong_prp(11, 3)
|
| 134 |
+
assert is_strong_prp(2**31-1, 5)
|
| 135 |
+
|
| 136 |
+
# A001262
|
| 137 |
+
pseudorpime = [2047, 3277, 4033, 4681, 8321, 15841, 29341,
|
| 138 |
+
42799, 49141, 52633, 65281, 74665, 80581]
|
| 139 |
+
for n in pseudorpime:
|
| 140 |
+
assert is_strong_prp(n, 2)
|
| 141 |
+
|
| 142 |
+
# A020229
|
| 143 |
+
pseudorpime = [121, 703, 1891, 3281, 8401, 8911, 10585, 12403,
|
| 144 |
+
16531, 18721, 19345, 23521, 31621, 44287, 47197]
|
| 145 |
+
for n in pseudorpime:
|
| 146 |
+
assert is_strong_prp(n, 3)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_lucas_sequence():
|
| 150 |
+
def lucas_u(P, Q, length):
|
| 151 |
+
array = [0] * length
|
| 152 |
+
array[1] = 1
|
| 153 |
+
for k in range(2, length):
|
| 154 |
+
array[k] = P * array[k - 1] - Q * array[k - 2]
|
| 155 |
+
return array
|
| 156 |
+
|
| 157 |
+
def lucas_v(P, Q, length):
|
| 158 |
+
array = [0] * length
|
| 159 |
+
array[0] = 2
|
| 160 |
+
array[1] = P
|
| 161 |
+
for k in range(2, length):
|
| 162 |
+
array[k] = P * array[k - 1] - Q * array[k - 2]
|
| 163 |
+
return array
|
| 164 |
+
|
| 165 |
+
length = 20
|
| 166 |
+
for P in range(-10, 10):
|
| 167 |
+
for Q in range(-10, 10):
|
| 168 |
+
D = P**2 - 4*Q
|
| 169 |
+
if D == 0:
|
| 170 |
+
continue
|
| 171 |
+
us = lucas_u(P, Q, length)
|
| 172 |
+
vs = lucas_v(P, Q, length)
|
| 173 |
+
for n in range(3, 100, 2):
|
| 174 |
+
for k in range(length):
|
| 175 |
+
U, V, Qk = _lucas_sequence(n, P, Q, k)
|
| 176 |
+
assert U == us[k] % n
|
| 177 |
+
assert V == vs[k] % n
|
| 178 |
+
assert pow(Q, k, n) == Qk
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_is_fibonacci_prp():
|
| 182 |
+
# invalid input
|
| 183 |
+
raises(ValueError, lambda: is_fibonacci_prp(3, 2, 1))
|
| 184 |
+
raises(ValueError, lambda: is_fibonacci_prp(3, -5, 1))
|
| 185 |
+
raises(ValueError, lambda: is_fibonacci_prp(3, 5, 2))
|
| 186 |
+
raises(ValueError, lambda: is_fibonacci_prp(0, 5, -1))
|
| 187 |
+
|
| 188 |
+
# n = 1
|
| 189 |
+
assert not is_fibonacci_prp(1, 3, 1)
|
| 190 |
+
|
| 191 |
+
# n is prime
|
| 192 |
+
assert is_fibonacci_prp(2, 5, 1)
|
| 193 |
+
assert is_fibonacci_prp(3, 6, -1)
|
| 194 |
+
assert is_fibonacci_prp(11, 7, 1)
|
| 195 |
+
assert is_fibonacci_prp(2**31-1, 8, -1)
|
| 196 |
+
|
| 197 |
+
# A005845
|
| 198 |
+
pseudorpime = [705, 2465, 2737, 3745, 4181, 5777, 6721,
|
| 199 |
+
10877, 13201, 15251, 24465, 29281, 34561]
|
| 200 |
+
for n in pseudorpime:
|
| 201 |
+
assert is_fibonacci_prp(n, 1, -1)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def test_is_lucas_prp():
|
| 205 |
+
# invalid input
|
| 206 |
+
raises(ValueError, lambda: is_lucas_prp(3, 2, 1))
|
| 207 |
+
raises(ValueError, lambda: is_lucas_prp(0, 5, -1))
|
| 208 |
+
raises(ValueError, lambda: is_lucas_prp(15, 3, 1))
|
| 209 |
+
|
| 210 |
+
# n = 1
|
| 211 |
+
assert not is_lucas_prp(1, 3, 1)
|
| 212 |
+
|
| 213 |
+
# n is prime
|
| 214 |
+
assert is_lucas_prp(2, 5, 2)
|
| 215 |
+
assert is_lucas_prp(3, 6, -1)
|
| 216 |
+
assert is_lucas_prp(11, 7, 5)
|
| 217 |
+
assert is_lucas_prp(2**31-1, 8, -3)
|
| 218 |
+
|
| 219 |
+
# A081264
|
| 220 |
+
pseudorpime = [323, 377, 1891, 3827, 4181, 5777, 6601, 6721,
|
| 221 |
+
8149, 10877, 11663, 13201, 13981, 15251, 17119]
|
| 222 |
+
for n in pseudorpime:
|
| 223 |
+
assert is_lucas_prp(n, 1, -1)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def test_is_selfridge_prp():
|
| 227 |
+
# invalid input
|
| 228 |
+
raises(ValueError, lambda: is_selfridge_prp(0))
|
| 229 |
+
|
| 230 |
+
# n = 1
|
| 231 |
+
assert not is_selfridge_prp(1)
|
| 232 |
+
|
| 233 |
+
# n is prime
|
| 234 |
+
assert is_selfridge_prp(2)
|
| 235 |
+
assert is_selfridge_prp(3)
|
| 236 |
+
assert is_selfridge_prp(11)
|
| 237 |
+
assert is_selfridge_prp(2**31-1)
|
| 238 |
+
|
| 239 |
+
# A217120
|
| 240 |
+
pseudorpime = [323, 377, 1159, 1829, 3827, 5459, 5777, 9071,
|
| 241 |
+
9179, 10877, 11419, 11663, 13919, 14839, 16109]
|
| 242 |
+
for n in pseudorpime:
|
| 243 |
+
assert is_selfridge_prp(n)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def test_is_strong_lucas_prp():
|
| 247 |
+
# invalid input
|
| 248 |
+
raises(ValueError, lambda: is_strong_lucas_prp(3, 2, 1))
|
| 249 |
+
raises(ValueError, lambda: is_strong_lucas_prp(0, 5, -1))
|
| 250 |
+
raises(ValueError, lambda: is_strong_lucas_prp(15, 3, 1))
|
| 251 |
+
|
| 252 |
+
# n = 1
|
| 253 |
+
assert not is_strong_lucas_prp(1, 3, 1)
|
| 254 |
+
|
| 255 |
+
# n is prime
|
| 256 |
+
assert is_strong_lucas_prp(2, 5, 2)
|
| 257 |
+
assert is_strong_lucas_prp(3, 6, -1)
|
| 258 |
+
assert is_strong_lucas_prp(11, 7, 5)
|
| 259 |
+
assert is_strong_lucas_prp(2**31-1, 8, -3)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def test_is_strong_selfridge_prp():
|
| 263 |
+
# invalid input
|
| 264 |
+
raises(ValueError, lambda: is_strong_selfridge_prp(0))
|
| 265 |
+
|
| 266 |
+
# n = 1
|
| 267 |
+
assert not is_strong_selfridge_prp(1)
|
| 268 |
+
|
| 269 |
+
# n is prime
|
| 270 |
+
assert is_strong_selfridge_prp(2)
|
| 271 |
+
assert is_strong_selfridge_prp(3)
|
| 272 |
+
assert is_strong_selfridge_prp(11)
|
| 273 |
+
assert is_strong_selfridge_prp(2**31-1)
|
| 274 |
+
|
| 275 |
+
# A217255
|
| 276 |
+
pseudorpime = [5459, 5777, 10877, 16109, 18971, 22499, 24569,
|
| 277 |
+
25199, 40309, 58519, 75077, 97439, 100127, 113573]
|
| 278 |
+
for n in pseudorpime:
|
| 279 |
+
assert is_strong_selfridge_prp(n)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def test_is_bpsw_prp():
|
| 283 |
+
# invalid input
|
| 284 |
+
raises(ValueError, lambda: is_bpsw_prp(0))
|
| 285 |
+
|
| 286 |
+
# n = 1
|
| 287 |
+
assert not is_bpsw_prp(1)
|
| 288 |
+
|
| 289 |
+
# n is prime
|
| 290 |
+
assert is_bpsw_prp(2)
|
| 291 |
+
assert is_bpsw_prp(3)
|
| 292 |
+
assert is_bpsw_prp(11)
|
| 293 |
+
assert is_bpsw_prp(2**31-1)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def test_is_strong_bpsw_prp():
|
| 297 |
+
# invalid input
|
| 298 |
+
raises(ValueError, lambda: is_strong_bpsw_prp(0))
|
| 299 |
+
|
| 300 |
+
# n = 1
|
| 301 |
+
assert not is_strong_bpsw_prp(1)
|
| 302 |
+
|
| 303 |
+
# n is prime
|
| 304 |
+
assert is_strong_bpsw_prp(2)
|
| 305 |
+
assert is_strong_bpsw_prp(3)
|
| 306 |
+
assert is_strong_bpsw_prp(11)
|
| 307 |
+
assert is_strong_bpsw_prp(2**31-1)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This testfile tests SymPy <-> NumPy compatibility
|
| 2 |
+
|
| 3 |
+
# Don't test any SymPy features here. Just pure interaction with NumPy.
|
| 4 |
+
# Always write regular SymPy tests for anything, that can be tested in pure
|
| 5 |
+
# Python (without numpy). Here we test everything, that a user may need when
|
| 6 |
+
# using SymPy with NumPy
|
| 7 |
+
from sympy.external.importtools import version_tuple
|
| 8 |
+
from sympy.external import import_module
|
| 9 |
+
|
| 10 |
+
numpy = import_module('numpy')
|
| 11 |
+
if numpy:
|
| 12 |
+
array, matrix, ndarray = numpy.array, numpy.matrix, numpy.ndarray
|
| 13 |
+
else:
|
| 14 |
+
#bin/test will not execute any tests now
|
| 15 |
+
disabled = True
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from sympy.core.numbers import (Float, Integer, Rational)
|
| 19 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 20 |
+
from sympy.functions.elementary.trigonometric import sin
|
| 21 |
+
from sympy.matrices.dense import (Matrix, list2numpy, matrix2numpy, symarray)
|
| 22 |
+
from sympy.utilities.lambdify import lambdify
|
| 23 |
+
import sympy
|
| 24 |
+
|
| 25 |
+
import mpmath
|
| 26 |
+
from sympy.abc import x, y, z
|
| 27 |
+
from sympy.utilities.decorator import conserve_mpmath_dps
|
| 28 |
+
from sympy.utilities.exceptions import ignore_warnings
|
| 29 |
+
from sympy.testing.pytest import raises
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# first, systematically check, that all operations are implemented and don't
|
| 33 |
+
# raise an exception
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_systematic_basic():
|
| 37 |
+
def s(sympy_object, numpy_array):
|
| 38 |
+
_ = [sympy_object + numpy_array,
|
| 39 |
+
numpy_array + sympy_object,
|
| 40 |
+
sympy_object - numpy_array,
|
| 41 |
+
numpy_array - sympy_object,
|
| 42 |
+
sympy_object * numpy_array,
|
| 43 |
+
numpy_array * sympy_object,
|
| 44 |
+
sympy_object / numpy_array,
|
| 45 |
+
numpy_array / sympy_object,
|
| 46 |
+
sympy_object ** numpy_array,
|
| 47 |
+
numpy_array ** sympy_object]
|
| 48 |
+
x = Symbol("x")
|
| 49 |
+
y = Symbol("y")
|
| 50 |
+
sympy_objs = [
|
| 51 |
+
Rational(2, 3),
|
| 52 |
+
Float("1.3"),
|
| 53 |
+
x,
|
| 54 |
+
y,
|
| 55 |
+
pow(x, y)*y,
|
| 56 |
+
Integer(5),
|
| 57 |
+
Float(5.5),
|
| 58 |
+
]
|
| 59 |
+
numpy_objs = [
|
| 60 |
+
array([1]),
|
| 61 |
+
array([3, 8, -1]),
|
| 62 |
+
array([x, x**2, Rational(5)]),
|
| 63 |
+
array([x/y*sin(y), 5, Rational(5)]),
|
| 64 |
+
]
|
| 65 |
+
for x in sympy_objs:
|
| 66 |
+
for y in numpy_objs:
|
| 67 |
+
s(x, y)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# now some random tests, that test particular problems and that also
|
| 71 |
+
# check that the results of the operations are correct
|
| 72 |
+
|
| 73 |
+
def test_basics():
|
| 74 |
+
one = Rational(1)
|
| 75 |
+
zero = Rational(0)
|
| 76 |
+
assert array(1) == array(one)
|
| 77 |
+
assert array([one]) == array([one])
|
| 78 |
+
assert array([x]) == array([x])
|
| 79 |
+
assert array(x) == array(Symbol("x"))
|
| 80 |
+
assert array(one + x) == array(1 + x)
|
| 81 |
+
|
| 82 |
+
X = array([one, zero, zero])
|
| 83 |
+
assert (X == array([one, zero, zero])).all()
|
| 84 |
+
assert (X == array([one, 0, 0])).all()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_arrays():
|
| 88 |
+
one = Rational(1)
|
| 89 |
+
zero = Rational(0)
|
| 90 |
+
X = array([one, zero, zero])
|
| 91 |
+
Y = one*X
|
| 92 |
+
X = array([Symbol("a") + Rational(1, 2)])
|
| 93 |
+
Y = X + X
|
| 94 |
+
assert Y == array([1 + 2*Symbol("a")])
|
| 95 |
+
Y = Y + 1
|
| 96 |
+
assert Y == array([2 + 2*Symbol("a")])
|
| 97 |
+
Y = X - X
|
| 98 |
+
assert Y == array([0])
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_conversion1():
|
| 102 |
+
a = list2numpy([x**2, x])
|
| 103 |
+
#looks like an array?
|
| 104 |
+
assert isinstance(a, ndarray)
|
| 105 |
+
assert a[0] == x**2
|
| 106 |
+
assert a[1] == x
|
| 107 |
+
assert len(a) == 2
|
| 108 |
+
#yes, it's the array
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_conversion2():
|
| 112 |
+
a = 2*list2numpy([x**2, x])
|
| 113 |
+
b = list2numpy([2*x**2, 2*x])
|
| 114 |
+
assert (a == b).all()
|
| 115 |
+
|
| 116 |
+
one = Rational(1)
|
| 117 |
+
zero = Rational(0)
|
| 118 |
+
X = list2numpy([one, zero, zero])
|
| 119 |
+
Y = one*X
|
| 120 |
+
X = list2numpy([Symbol("a") + Rational(1, 2)])
|
| 121 |
+
Y = X + X
|
| 122 |
+
assert Y == array([1 + 2*Symbol("a")])
|
| 123 |
+
Y = Y + 1
|
| 124 |
+
assert Y == array([2 + 2*Symbol("a")])
|
| 125 |
+
Y = X - X
|
| 126 |
+
assert Y == array([0])
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_list2numpy():
|
| 130 |
+
assert (array([x**2, x]) == list2numpy([x**2, x])).all()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_Matrix1():
|
| 134 |
+
m = Matrix([[x, x**2], [5, 2/x]])
|
| 135 |
+
assert (array(m.subs(x, 2)) == array([[2, 4], [5, 1]])).all()
|
| 136 |
+
m = Matrix([[sin(x), x**2], [5, 2/x]])
|
| 137 |
+
assert (array(m.subs(x, 2)) == array([[sin(2), 4], [5, 1]])).all()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_Matrix2():
|
| 141 |
+
m = Matrix([[x, x**2], [5, 2/x]])
|
| 142 |
+
with ignore_warnings(PendingDeprecationWarning):
|
| 143 |
+
assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all()
|
| 144 |
+
m = Matrix([[sin(x), x**2], [5, 2/x]])
|
| 145 |
+
with ignore_warnings(PendingDeprecationWarning):
|
| 146 |
+
assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all()
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_Matrix3():
|
| 150 |
+
a = array([[2, 4], [5, 1]])
|
| 151 |
+
assert Matrix(a) == Matrix([[2, 4], [5, 1]])
|
| 152 |
+
assert Matrix(a) != Matrix([[2, 4], [5, 2]])
|
| 153 |
+
a = array([[sin(2), 4], [5, 1]])
|
| 154 |
+
assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
|
| 155 |
+
assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def test_Matrix4():
|
| 159 |
+
with ignore_warnings(PendingDeprecationWarning):
|
| 160 |
+
a = matrix([[2, 4], [5, 1]])
|
| 161 |
+
assert Matrix(a) == Matrix([[2, 4], [5, 1]])
|
| 162 |
+
assert Matrix(a) != Matrix([[2, 4], [5, 2]])
|
| 163 |
+
with ignore_warnings(PendingDeprecationWarning):
|
| 164 |
+
a = matrix([[sin(2), 4], [5, 1]])
|
| 165 |
+
assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
|
| 166 |
+
assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def test_Matrix_sum():
|
| 170 |
+
M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
|
| 171 |
+
with ignore_warnings(PendingDeprecationWarning):
|
| 172 |
+
m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]])
|
| 173 |
+
assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
|
| 174 |
+
assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
|
| 175 |
+
assert M + m == M.add(m)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def test_Matrix_mul():
|
| 179 |
+
M = Matrix([[1, 2, 3], [x, y, x]])
|
| 180 |
+
with ignore_warnings(PendingDeprecationWarning):
|
| 181 |
+
m = matrix([[2, 4], [x, 6], [x, z**2]])
|
| 182 |
+
assert M*m == Matrix([
|
| 183 |
+
[ 2 + 5*x, 16 + 3*z**2],
|
| 184 |
+
[2*x + x*y + x**2, 4*x + 6*y + x*z**2],
|
| 185 |
+
])
|
| 186 |
+
|
| 187 |
+
assert m*M == Matrix([
|
| 188 |
+
[ 2 + 4*x, 4 + 4*y, 6 + 4*x],
|
| 189 |
+
[ 7*x, 2*x + 6*y, 9*x],
|
| 190 |
+
[x + x*z**2, 2*x + y*z**2, 3*x + x*z**2],
|
| 191 |
+
])
|
| 192 |
+
a = array([2])
|
| 193 |
+
assert a[0] * M == 2 * M
|
| 194 |
+
assert M * a[0] == 2 * M
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_Matrix_array():
|
| 198 |
+
class matarray:
|
| 199 |
+
def __array__(self, dtype=object, copy=None):
|
| 200 |
+
if copy is not None and not copy:
|
| 201 |
+
raise TypeError("Cannot implement copy=False when converting Matrix to ndarray")
|
| 202 |
+
from numpy import array
|
| 203 |
+
return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 204 |
+
matarr = matarray()
|
| 205 |
+
assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def test_matrix2numpy():
|
| 209 |
+
a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]]))
|
| 210 |
+
assert isinstance(a, ndarray)
|
| 211 |
+
assert a.shape == (2, 2)
|
| 212 |
+
assert a[0, 0] == 1
|
| 213 |
+
assert a[0, 1] == x**2
|
| 214 |
+
assert a[1, 0] == 3*sin(x)
|
| 215 |
+
assert a[1, 1] == 0
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def test_matrix2numpy_conversion():
|
| 219 |
+
a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
|
| 220 |
+
b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
|
| 221 |
+
assert (matrix2numpy(a) == b).all()
|
| 222 |
+
assert matrix2numpy(a).dtype == numpy.dtype('object')
|
| 223 |
+
|
| 224 |
+
c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
|
| 225 |
+
d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
|
| 226 |
+
assert c.dtype == numpy.dtype('int8')
|
| 227 |
+
assert d.dtype == numpy.dtype('float64')
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def test_issue_3728():
|
| 231 |
+
assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all()
|
| 232 |
+
assert (Rational(1, 2) + array(
|
| 233 |
+
[2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all()
|
| 234 |
+
assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all()
|
| 235 |
+
assert (Float("0.5") + array(
|
| 236 |
+
[2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@conserve_mpmath_dps
|
| 240 |
+
def test_lambdify():
|
| 241 |
+
mpmath.mp.dps = 16
|
| 242 |
+
sin02 = mpmath.mpf("0.198669330795061215459412627")
|
| 243 |
+
f = lambdify(x, sin(x), "numpy")
|
| 244 |
+
prec = 1e-15
|
| 245 |
+
assert -prec < f(0.2) - sin02 < prec
|
| 246 |
+
|
| 247 |
+
# if this succeeds, it can't be a numpy function
|
| 248 |
+
|
| 249 |
+
if version_tuple(numpy.__version__) >= version_tuple('1.17'):
|
| 250 |
+
with raises(TypeError):
|
| 251 |
+
f(x)
|
| 252 |
+
else:
|
| 253 |
+
with raises(AttributeError):
|
| 254 |
+
f(x)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def test_lambdify_matrix():
|
| 258 |
+
f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"])
|
| 259 |
+
assert (f(1) == array([[1, 2], [1, 2]])).all()
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def test_lambdify_matrix_multi_input():
|
| 263 |
+
M = sympy.Matrix([[x**2, x*y, x*z],
|
| 264 |
+
[y*x, y**2, y*z],
|
| 265 |
+
[z*x, z*y, z**2]])
|
| 266 |
+
f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"])
|
| 267 |
+
|
| 268 |
+
xh, yh, zh = 1.0, 2.0, 3.0
|
| 269 |
+
expected = array([[xh**2, xh*yh, xh*zh],
|
| 270 |
+
[yh*xh, yh**2, yh*zh],
|
| 271 |
+
[zh*xh, zh*yh, zh**2]])
|
| 272 |
+
actual = f(xh, yh, zh)
|
| 273 |
+
assert numpy.allclose(actual, expected)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def test_lambdify_matrix_vec_input():
|
| 277 |
+
X = sympy.DeferredVector('X')
|
| 278 |
+
M = Matrix([
|
| 279 |
+
[X[0]**2, X[0]*X[1], X[0]*X[2]],
|
| 280 |
+
[X[1]*X[0], X[1]**2, X[1]*X[2]],
|
| 281 |
+
[X[2]*X[0], X[2]*X[1], X[2]**2]])
|
| 282 |
+
f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"])
|
| 283 |
+
|
| 284 |
+
Xh = array([1.0, 2.0, 3.0])
|
| 285 |
+
expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]],
|
| 286 |
+
[Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]],
|
| 287 |
+
[Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]])
|
| 288 |
+
actual = f(Xh)
|
| 289 |
+
assert numpy.allclose(actual, expected)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_lambdify_transl():
|
| 293 |
+
from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
|
| 294 |
+
for sym, mat in NUMPY_TRANSLATIONS.items():
|
| 295 |
+
assert sym in sympy.__dict__
|
| 296 |
+
assert mat in numpy.__dict__
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def test_symarray():
|
| 300 |
+
"""Test creation of numpy arrays of SymPy symbols."""
|
| 301 |
+
|
| 302 |
+
import numpy as np
|
| 303 |
+
import numpy.testing as npt
|
| 304 |
+
|
| 305 |
+
syms = symbols('_0,_1,_2')
|
| 306 |
+
s1 = symarray("", 3)
|
| 307 |
+
s2 = symarray("", 3)
|
| 308 |
+
npt.assert_array_equal(s1, np.array(syms, dtype=object))
|
| 309 |
+
assert s1[0] == s2[0]
|
| 310 |
+
|
| 311 |
+
a = symarray('a', 3)
|
| 312 |
+
b = symarray('b', 3)
|
| 313 |
+
assert not(a[0] == b[0])
|
| 314 |
+
|
| 315 |
+
asyms = symbols('a_0,a_1,a_2')
|
| 316 |
+
npt.assert_array_equal(a, np.array(asyms, dtype=object))
|
| 317 |
+
|
| 318 |
+
# Multidimensional checks
|
| 319 |
+
a2d = symarray('a', (2, 3))
|
| 320 |
+
assert a2d.shape == (2, 3)
|
| 321 |
+
a00, a12 = symbols('a_0_0,a_1_2')
|
| 322 |
+
assert a2d[0, 0] == a00
|
| 323 |
+
assert a2d[1, 2] == a12
|
| 324 |
+
|
| 325 |
+
a3d = symarray('a', (2, 3, 2))
|
| 326 |
+
assert a3d.shape == (2, 3, 2)
|
| 327 |
+
a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
|
| 328 |
+
assert a3d[0, 0, 0] == a000
|
| 329 |
+
assert a3d[1, 2, 0] == a120
|
| 330 |
+
assert a3d[1, 2, 1] == a121
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def test_vectorize():
|
| 334 |
+
assert (numpy.vectorize(
|
| 335 |
+
sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_pythonmpq.py
|
| 3 |
+
|
| 4 |
+
Test the PythonMPQ class for consistency with gmpy2's mpq type. If gmpy2 is
|
| 5 |
+
installed run the same tests for both.
|
| 6 |
+
"""
|
| 7 |
+
from fractions import Fraction
|
| 8 |
+
from decimal import Decimal
|
| 9 |
+
import pickle
|
| 10 |
+
from typing import Callable, List, Tuple, Type
|
| 11 |
+
|
| 12 |
+
from sympy.testing.pytest import raises
|
| 13 |
+
|
| 14 |
+
from sympy.external.pythonmpq import PythonMPQ
|
| 15 |
+
|
| 16 |
+
#
|
| 17 |
+
# If gmpy2 is installed then run the tests for both mpq and PythonMPQ.
|
| 18 |
+
# That should ensure consistency between the implementation here and mpq.
|
| 19 |
+
#
|
| 20 |
+
rational_types: List[Tuple[Callable, Type, Callable, Type]]
|
| 21 |
+
rational_types = [(PythonMPQ, PythonMPQ, int, int)]
|
| 22 |
+
try:
|
| 23 |
+
from gmpy2 import mpq, mpz
|
| 24 |
+
rational_types.append((mpq, type(mpq(1)), mpz, type(mpz(1))))
|
| 25 |
+
except ImportError:
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_PythonMPQ():
|
| 30 |
+
#
|
| 31 |
+
# Test PythonMPQ and also mpq if gmpy/gmpy2 is installed.
|
| 32 |
+
#
|
| 33 |
+
for Q, TQ, Z, TZ in rational_types:
|
| 34 |
+
|
| 35 |
+
def check_Q(q):
|
| 36 |
+
assert isinstance(q, TQ)
|
| 37 |
+
assert isinstance(q.numerator, TZ)
|
| 38 |
+
assert isinstance(q.denominator, TZ)
|
| 39 |
+
return q.numerator, q.denominator
|
| 40 |
+
|
| 41 |
+
# Check construction from different types
|
| 42 |
+
assert check_Q(Q(3)) == (3, 1)
|
| 43 |
+
assert check_Q(Q(3, 5)) == (3, 5)
|
| 44 |
+
assert check_Q(Q(Q(3, 5))) == (3, 5)
|
| 45 |
+
assert check_Q(Q(0.5)) == (1, 2)
|
| 46 |
+
assert check_Q(Q('0.5')) == (1, 2)
|
| 47 |
+
assert check_Q(Q(Fraction(3, 5))) == (3, 5)
|
| 48 |
+
|
| 49 |
+
# https://github.com/aleaxit/gmpy/issues/327
|
| 50 |
+
if Q is PythonMPQ:
|
| 51 |
+
assert check_Q(Q(Decimal('0.6'))) == (3, 5)
|
| 52 |
+
|
| 53 |
+
# Invalid types
|
| 54 |
+
raises(TypeError, lambda: Q([]))
|
| 55 |
+
raises(TypeError, lambda: Q([], []))
|
| 56 |
+
|
| 57 |
+
# Check normalisation of signs
|
| 58 |
+
assert check_Q(Q(2, 3)) == (2, 3)
|
| 59 |
+
assert check_Q(Q(-2, 3)) == (-2, 3)
|
| 60 |
+
assert check_Q(Q(2, -3)) == (-2, 3)
|
| 61 |
+
assert check_Q(Q(-2, -3)) == (2, 3)
|
| 62 |
+
|
| 63 |
+
# Check gcd calculation
|
| 64 |
+
assert check_Q(Q(12, 8)) == (3, 2)
|
| 65 |
+
|
| 66 |
+
# __int__/__float__
|
| 67 |
+
assert int(Q(5, 3)) == 1
|
| 68 |
+
assert int(Q(-5, 3)) == -1
|
| 69 |
+
assert float(Q(5, 2)) == 2.5
|
| 70 |
+
assert float(Q(-5, 2)) == -2.5
|
| 71 |
+
|
| 72 |
+
# __str__/__repr__
|
| 73 |
+
assert str(Q(2, 1)) == "2"
|
| 74 |
+
assert str(Q(1, 2)) == "1/2"
|
| 75 |
+
if Q is PythonMPQ:
|
| 76 |
+
assert repr(Q(2, 1)) == "MPQ(2,1)"
|
| 77 |
+
assert repr(Q(1, 2)) == "MPQ(1,2)"
|
| 78 |
+
else:
|
| 79 |
+
assert repr(Q(2, 1)) == "mpq(2,1)"
|
| 80 |
+
assert repr(Q(1, 2)) == "mpq(1,2)"
|
| 81 |
+
|
| 82 |
+
# __bool__
|
| 83 |
+
assert bool(Q(1, 2)) is True
|
| 84 |
+
assert bool(Q(0)) is False
|
| 85 |
+
|
| 86 |
+
# __eq__/__ne__
|
| 87 |
+
assert (Q(2, 3) == Q(2, 3)) is True
|
| 88 |
+
assert (Q(2, 3) == Q(2, 5)) is False
|
| 89 |
+
assert (Q(2, 3) != Q(2, 3)) is False
|
| 90 |
+
assert (Q(2, 3) != Q(2, 5)) is True
|
| 91 |
+
|
| 92 |
+
# __hash__
|
| 93 |
+
assert hash(Q(3, 5)) == hash(Fraction(3, 5))
|
| 94 |
+
|
| 95 |
+
# __reduce__
|
| 96 |
+
q = Q(2, 3)
|
| 97 |
+
assert pickle.loads(pickle.dumps(q)) == q
|
| 98 |
+
|
| 99 |
+
# __ge__/__gt__/__le__/__lt__
|
| 100 |
+
assert (Q(1, 3) < Q(2, 3)) is True
|
| 101 |
+
assert (Q(2, 3) < Q(2, 3)) is False
|
| 102 |
+
assert (Q(2, 3) < Q(1, 3)) is False
|
| 103 |
+
assert (Q(-2, 3) < Q(1, 3)) is True
|
| 104 |
+
assert (Q(1, 3) < Q(-2, 3)) is False
|
| 105 |
+
|
| 106 |
+
assert (Q(1, 3) <= Q(2, 3)) is True
|
| 107 |
+
assert (Q(2, 3) <= Q(2, 3)) is True
|
| 108 |
+
assert (Q(2, 3) <= Q(1, 3)) is False
|
| 109 |
+
assert (Q(-2, 3) <= Q(1, 3)) is True
|
| 110 |
+
assert (Q(1, 3) <= Q(-2, 3)) is False
|
| 111 |
+
|
| 112 |
+
assert (Q(1, 3) > Q(2, 3)) is False
|
| 113 |
+
assert (Q(2, 3) > Q(2, 3)) is False
|
| 114 |
+
assert (Q(2, 3) > Q(1, 3)) is True
|
| 115 |
+
assert (Q(-2, 3) > Q(1, 3)) is False
|
| 116 |
+
assert (Q(1, 3) > Q(-2, 3)) is True
|
| 117 |
+
|
| 118 |
+
assert (Q(1, 3) >= Q(2, 3)) is False
|
| 119 |
+
assert (Q(2, 3) >= Q(2, 3)) is True
|
| 120 |
+
assert (Q(2, 3) >= Q(1, 3)) is True
|
| 121 |
+
assert (Q(-2, 3) >= Q(1, 3)) is False
|
| 122 |
+
assert (Q(1, 3) >= Q(-2, 3)) is True
|
| 123 |
+
|
| 124 |
+
# __abs__/__pos__/__neg__
|
| 125 |
+
assert abs(Q(2, 3)) == abs(Q(-2, 3)) == Q(2, 3)
|
| 126 |
+
assert +Q(2, 3) == Q(2, 3)
|
| 127 |
+
assert -Q(2, 3) == Q(-2, 3)
|
| 128 |
+
|
| 129 |
+
# __add__/__radd__
|
| 130 |
+
assert Q(2, 3) + Q(5, 7) == Q(29, 21)
|
| 131 |
+
assert Q(2, 3) + 1 == Q(5, 3)
|
| 132 |
+
assert 1 + Q(2, 3) == Q(5, 3)
|
| 133 |
+
raises(TypeError, lambda: [] + Q(1))
|
| 134 |
+
raises(TypeError, lambda: Q(1) + [])
|
| 135 |
+
|
| 136 |
+
# __sub__/__rsub__
|
| 137 |
+
assert Q(2, 3) - Q(5, 7) == Q(-1, 21)
|
| 138 |
+
assert Q(2, 3) - 1 == Q(-1, 3)
|
| 139 |
+
assert 1 - Q(2, 3) == Q(1, 3)
|
| 140 |
+
raises(TypeError, lambda: [] - Q(1))
|
| 141 |
+
raises(TypeError, lambda: Q(1) - [])
|
| 142 |
+
|
| 143 |
+
# __mul__/__rmul__
|
| 144 |
+
assert Q(2, 3) * Q(5, 7) == Q(10, 21)
|
| 145 |
+
assert Q(2, 3) * 1 == Q(2, 3)
|
| 146 |
+
assert 1 * Q(2, 3) == Q(2, 3)
|
| 147 |
+
raises(TypeError, lambda: [] * Q(1))
|
| 148 |
+
raises(TypeError, lambda: Q(1) * [])
|
| 149 |
+
|
| 150 |
+
# __pow__/__rpow__
|
| 151 |
+
assert Q(2, 3) ** 2 == Q(4, 9)
|
| 152 |
+
assert Q(2, 3) ** 1 == Q(2, 3)
|
| 153 |
+
assert Q(-2, 3) ** 2 == Q(4, 9)
|
| 154 |
+
assert Q(-2, 3) ** -1 == Q(-3, 2)
|
| 155 |
+
if Q is PythonMPQ:
|
| 156 |
+
raises(TypeError, lambda: 1 ** Q(2, 3))
|
| 157 |
+
raises(TypeError, lambda: Q(1, 4) ** Q(1, 2))
|
| 158 |
+
raises(TypeError, lambda: [] ** Q(1))
|
| 159 |
+
raises(TypeError, lambda: Q(1) ** [])
|
| 160 |
+
|
| 161 |
+
# __div__/__rdiv__
|
| 162 |
+
assert Q(2, 3) / Q(5, 7) == Q(14, 15)
|
| 163 |
+
assert Q(2, 3) / 1 == Q(2, 3)
|
| 164 |
+
assert 1 / Q(2, 3) == Q(3, 2)
|
| 165 |
+
raises(TypeError, lambda: [] / Q(1))
|
| 166 |
+
raises(TypeError, lambda: Q(1) / [])
|
| 167 |
+
raises(ZeroDivisionError, lambda: Q(1, 2) / Q(0))
|
| 168 |
+
|
| 169 |
+
# __divmod__
|
| 170 |
+
if Q is PythonMPQ:
|
| 171 |
+
raises(TypeError, lambda: Q(2, 3) // Q(1, 3))
|
| 172 |
+
raises(TypeError, lambda: Q(2, 3) % Q(1, 3))
|
| 173 |
+
raises(TypeError, lambda: 1 // Q(1, 3))
|
| 174 |
+
raises(TypeError, lambda: 1 % Q(1, 3))
|
| 175 |
+
raises(TypeError, lambda: Q(2, 3) // 1)
|
| 176 |
+
raises(TypeError, lambda: Q(2, 3) % 1)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This testfile tests SymPy <-> SciPy compatibility
|
| 2 |
+
|
| 3 |
+
# Don't test any SymPy features here. Just pure interaction with SciPy.
|
| 4 |
+
# Always write regular SymPy tests for anything, that can be tested in pure
|
| 5 |
+
# Python (without scipy). Here we test everything, that a user may need when
|
| 6 |
+
# using SymPy with SciPy
|
| 7 |
+
|
| 8 |
+
from sympy.external import import_module
|
| 9 |
+
|
| 10 |
+
scipy = import_module('scipy')
|
| 11 |
+
if not scipy:
|
| 12 |
+
#bin/test will not execute any tests now
|
| 13 |
+
disabled = True
|
| 14 |
+
|
| 15 |
+
from sympy.functions.special.bessel import jn_zeros
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def eq(a, b, tol=1e-6):
|
| 19 |
+
for x, y in zip(a, b):
|
| 20 |
+
if not (abs(x - y) < tol):
|
| 21 |
+
return False
|
| 22 |
+
return True
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_jn_zeros():
|
| 26 |
+
assert eq(jn_zeros(0, 4, method="scipy"),
|
| 27 |
+
[3.141592, 6.283185, 9.424777, 12.566370])
|
| 28 |
+
assert eq(jn_zeros(1, 4, method="scipy"),
|
| 29 |
+
[4.493409, 7.725251, 10.904121, 14.066193])
|
| 30 |
+
assert eq(jn_zeros(2, 4, method="scipy"),
|
| 31 |
+
[5.763459, 9.095011, 12.322940, 15.514603])
|
| 32 |
+
assert eq(jn_zeros(3, 4, method="scipy"),
|
| 33 |
+
[6.987932, 10.417118, 13.698023, 16.923621])
|
| 34 |
+
assert eq(jn_zeros(4, 4, method="scipy"),
|
| 35 |
+
[8.182561, 11.704907, 15.039664, 18.301255])
|
evalkit_internvl/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (188 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/integrals/benchmarks/bench_integrate.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.symbol import Symbol
|
| 2 |
+
from sympy.functions.elementary.trigonometric import sin
|
| 3 |
+
from sympy.integrals.integrals import integrate
|
| 4 |
+
|
| 5 |
+
x = Symbol('x')
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def bench_integrate_sin():
|
| 9 |
+
integrate(sin(x), x)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def bench_integrate_x1sin():
|
| 13 |
+
integrate(x**1*sin(x), x)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def bench_integrate_x2sin():
|
| 17 |
+
integrate(x**2*sin(x), x)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def bench_integrate_x3sin():
|
| 21 |
+
integrate(x**3*sin(x), x)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/traversal.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.basic import Basic
|
| 2 |
+
from sympy.printing import pprint
|
| 3 |
+
|
| 4 |
+
import random
|
| 5 |
+
|
| 6 |
+
def interactive_traversal(expr):
|
| 7 |
+
"""Traverse a tree asking a user which branch to choose. """
|
| 8 |
+
|
| 9 |
+
RED, BRED = '\033[0;31m', '\033[1;31m'
|
| 10 |
+
GREEN, BGREEN = '\033[0;32m', '\033[1;32m'
|
| 11 |
+
YELLOW, BYELLOW = '\033[0;33m', '\033[1;33m' # noqa
|
| 12 |
+
BLUE, BBLUE = '\033[0;34m', '\033[1;34m' # noqa
|
| 13 |
+
MAGENTA, BMAGENTA = '\033[0;35m', '\033[1;35m'# noqa
|
| 14 |
+
CYAN, BCYAN = '\033[0;36m', '\033[1;36m' # noqa
|
| 15 |
+
END = '\033[0m'
|
| 16 |
+
|
| 17 |
+
def cprint(*args):
|
| 18 |
+
print("".join(map(str, args)) + END)
|
| 19 |
+
|
| 20 |
+
def _interactive_traversal(expr, stage):
|
| 21 |
+
if stage > 0:
|
| 22 |
+
print()
|
| 23 |
+
|
| 24 |
+
cprint("Current expression (stage ", BYELLOW, stage, END, "):")
|
| 25 |
+
print(BCYAN)
|
| 26 |
+
pprint(expr)
|
| 27 |
+
print(END)
|
| 28 |
+
|
| 29 |
+
if isinstance(expr, Basic):
|
| 30 |
+
if expr.is_Add:
|
| 31 |
+
args = expr.as_ordered_terms()
|
| 32 |
+
elif expr.is_Mul:
|
| 33 |
+
args = expr.as_ordered_factors()
|
| 34 |
+
else:
|
| 35 |
+
args = expr.args
|
| 36 |
+
elif hasattr(expr, "__iter__"):
|
| 37 |
+
args = list(expr)
|
| 38 |
+
else:
|
| 39 |
+
return expr
|
| 40 |
+
|
| 41 |
+
n_args = len(args)
|
| 42 |
+
|
| 43 |
+
if not n_args:
|
| 44 |
+
return expr
|
| 45 |
+
|
| 46 |
+
for i, arg in enumerate(args):
|
| 47 |
+
cprint(GREEN, "[", BGREEN, i, GREEN, "] ", BLUE, type(arg), END)
|
| 48 |
+
pprint(arg)
|
| 49 |
+
print()
|
| 50 |
+
|
| 51 |
+
if n_args == 1:
|
| 52 |
+
choices = '0'
|
| 53 |
+
else:
|
| 54 |
+
choices = '0-%d' % (n_args - 1)
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
choice = input("Your choice [%s,f,l,r,d,?]: " % choices)
|
| 58 |
+
except EOFError:
|
| 59 |
+
result = expr
|
| 60 |
+
print()
|
| 61 |
+
else:
|
| 62 |
+
if choice == '?':
|
| 63 |
+
cprint(RED, "%s - select subexpression with the given index" %
|
| 64 |
+
choices)
|
| 65 |
+
cprint(RED, "f - select the first subexpression")
|
| 66 |
+
cprint(RED, "l - select the last subexpression")
|
| 67 |
+
cprint(RED, "r - select a random subexpression")
|
| 68 |
+
cprint(RED, "d - done\n")
|
| 69 |
+
|
| 70 |
+
result = _interactive_traversal(expr, stage)
|
| 71 |
+
elif choice in ('d', ''):
|
| 72 |
+
result = expr
|
| 73 |
+
elif choice == 'f':
|
| 74 |
+
result = _interactive_traversal(args[0], stage + 1)
|
| 75 |
+
elif choice == 'l':
|
| 76 |
+
result = _interactive_traversal(args[-1], stage + 1)
|
| 77 |
+
elif choice == 'r':
|
| 78 |
+
result = _interactive_traversal(random.choice(args), stage + 1)
|
| 79 |
+
else:
|
| 80 |
+
try:
|
| 81 |
+
choice = int(choice)
|
| 82 |
+
except ValueError:
|
| 83 |
+
cprint(BRED,
|
| 84 |
+
"Choice must be a number in %s range\n" % choices)
|
| 85 |
+
result = _interactive_traversal(expr, stage)
|
| 86 |
+
else:
|
| 87 |
+
if choice < 0 or choice >= n_args:
|
| 88 |
+
cprint(BRED, "Choice must be in %s range\n" % choices)
|
| 89 |
+
result = _interactive_traversal(expr, stage)
|
| 90 |
+
else:
|
| 91 |
+
result = _interactive_traversal(args[choice], stage + 1)
|
| 92 |
+
|
| 93 |
+
return result
|
| 94 |
+
|
| 95 |
+
return _interactive_traversal(expr, 0)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License (MIT)
|
| 2 |
+
|
| 3 |
+
Copyright 2016, latex2sympy
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/LaTeX.g4
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
ANTLR4 LaTeX Math Grammar
|
| 3 |
+
|
| 4 |
+
Ported from latex2sympy by @augustt198 https://github.com/augustt198/latex2sympy See license in
|
| 5 |
+
LICENSE.txt
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
/*
|
| 9 |
+
After changing this file, it is necessary to run `python setup.py antlr` in the root directory of
|
| 10 |
+
the repository. This will regenerate the code in `sympy/parsing/latex/_antlr/*.py`.
|
| 11 |
+
*/
|
| 12 |
+
|
| 13 |
+
grammar LaTeX;
|
| 14 |
+
|
| 15 |
+
options {
|
| 16 |
+
language = Python3;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
WS: [ \t\r\n]+ -> skip;
|
| 20 |
+
THINSPACE: ('\\,' | '\\thinspace') -> skip;
|
| 21 |
+
MEDSPACE: ('\\:' | '\\medspace') -> skip;
|
| 22 |
+
THICKSPACE: ('\\;' | '\\thickspace') -> skip;
|
| 23 |
+
QUAD: '\\quad' -> skip;
|
| 24 |
+
QQUAD: '\\qquad' -> skip;
|
| 25 |
+
NEGTHINSPACE: ('\\!' | '\\negthinspace') -> skip;
|
| 26 |
+
NEGMEDSPACE: '\\negmedspace' -> skip;
|
| 27 |
+
NEGTHICKSPACE: '\\negthickspace' -> skip;
|
| 28 |
+
CMD_LEFT: '\\left' -> skip;
|
| 29 |
+
CMD_RIGHT: '\\right' -> skip;
|
| 30 |
+
|
| 31 |
+
IGNORE:
|
| 32 |
+
(
|
| 33 |
+
'\\vrule'
|
| 34 |
+
| '\\vcenter'
|
| 35 |
+
| '\\vbox'
|
| 36 |
+
| '\\vskip'
|
| 37 |
+
| '\\vspace'
|
| 38 |
+
| '\\hfil'
|
| 39 |
+
| '\\*'
|
| 40 |
+
| '\\-'
|
| 41 |
+
| '\\.'
|
| 42 |
+
| '\\/'
|
| 43 |
+
| '\\"'
|
| 44 |
+
| '\\('
|
| 45 |
+
| '\\='
|
| 46 |
+
) -> skip;
|
| 47 |
+
|
| 48 |
+
ADD: '+';
|
| 49 |
+
SUB: '-';
|
| 50 |
+
MUL: '*';
|
| 51 |
+
DIV: '/';
|
| 52 |
+
|
| 53 |
+
L_PAREN: '(';
|
| 54 |
+
R_PAREN: ')';
|
| 55 |
+
L_BRACE: '{';
|
| 56 |
+
R_BRACE: '}';
|
| 57 |
+
L_BRACE_LITERAL: '\\{';
|
| 58 |
+
R_BRACE_LITERAL: '\\}';
|
| 59 |
+
L_BRACKET: '[';
|
| 60 |
+
R_BRACKET: ']';
|
| 61 |
+
|
| 62 |
+
BAR: '|';
|
| 63 |
+
|
| 64 |
+
R_BAR: '\\right|';
|
| 65 |
+
L_BAR: '\\left|';
|
| 66 |
+
|
| 67 |
+
L_ANGLE: '\\langle';
|
| 68 |
+
R_ANGLE: '\\rangle';
|
| 69 |
+
FUNC_LIM: '\\lim';
|
| 70 |
+
LIM_APPROACH_SYM:
|
| 71 |
+
'\\to'
|
| 72 |
+
| '\\rightarrow'
|
| 73 |
+
| '\\Rightarrow'
|
| 74 |
+
| '\\longrightarrow'
|
| 75 |
+
| '\\Longrightarrow';
|
| 76 |
+
FUNC_INT:
|
| 77 |
+
'\\int'
|
| 78 |
+
| '\\int\\limits';
|
| 79 |
+
FUNC_SUM: '\\sum';
|
| 80 |
+
FUNC_PROD: '\\prod';
|
| 81 |
+
|
| 82 |
+
FUNC_EXP: '\\exp';
|
| 83 |
+
FUNC_LOG: '\\log';
|
| 84 |
+
FUNC_LG: '\\lg';
|
| 85 |
+
FUNC_LN: '\\ln';
|
| 86 |
+
FUNC_SIN: '\\sin';
|
| 87 |
+
FUNC_COS: '\\cos';
|
| 88 |
+
FUNC_TAN: '\\tan';
|
| 89 |
+
FUNC_CSC: '\\csc';
|
| 90 |
+
FUNC_SEC: '\\sec';
|
| 91 |
+
FUNC_COT: '\\cot';
|
| 92 |
+
|
| 93 |
+
FUNC_ARCSIN: '\\arcsin';
|
| 94 |
+
FUNC_ARCCOS: '\\arccos';
|
| 95 |
+
FUNC_ARCTAN: '\\arctan';
|
| 96 |
+
FUNC_ARCCSC: '\\arccsc';
|
| 97 |
+
FUNC_ARCSEC: '\\arcsec';
|
| 98 |
+
FUNC_ARCCOT: '\\arccot';
|
| 99 |
+
|
| 100 |
+
FUNC_SINH: '\\sinh';
|
| 101 |
+
FUNC_COSH: '\\cosh';
|
| 102 |
+
FUNC_TANH: '\\tanh';
|
| 103 |
+
FUNC_ARSINH: '\\arsinh';
|
| 104 |
+
FUNC_ARCOSH: '\\arcosh';
|
| 105 |
+
FUNC_ARTANH: '\\artanh';
|
| 106 |
+
|
| 107 |
+
L_FLOOR: '\\lfloor';
|
| 108 |
+
R_FLOOR: '\\rfloor';
|
| 109 |
+
L_CEIL: '\\lceil';
|
| 110 |
+
R_CEIL: '\\rceil';
|
| 111 |
+
|
| 112 |
+
FUNC_SQRT: '\\sqrt';
|
| 113 |
+
FUNC_OVERLINE: '\\overline';
|
| 114 |
+
|
| 115 |
+
CMD_TIMES: '\\times';
|
| 116 |
+
CMD_CDOT: '\\cdot';
|
| 117 |
+
CMD_DIV: '\\div';
|
| 118 |
+
CMD_FRAC:
|
| 119 |
+
'\\frac'
|
| 120 |
+
| '\\dfrac'
|
| 121 |
+
| '\\tfrac';
|
| 122 |
+
CMD_BINOM: '\\binom';
|
| 123 |
+
CMD_DBINOM: '\\dbinom';
|
| 124 |
+
CMD_TBINOM: '\\tbinom';
|
| 125 |
+
|
| 126 |
+
CMD_MATHIT: '\\mathit';
|
| 127 |
+
|
| 128 |
+
UNDERSCORE: '_';
|
| 129 |
+
CARET: '^';
|
| 130 |
+
COLON: ':';
|
| 131 |
+
|
| 132 |
+
fragment WS_CHAR: [ \t\r\n];
|
| 133 |
+
DIFFERENTIAL: 'd' WS_CHAR*? ([a-zA-Z] | '\\' [a-zA-Z]+);
|
| 134 |
+
|
| 135 |
+
LETTER: [a-zA-Z];
|
| 136 |
+
DIGIT: [0-9];
|
| 137 |
+
|
| 138 |
+
EQUAL: (('&' WS_CHAR*?)? '=') | ('=' (WS_CHAR*? '&')?);
|
| 139 |
+
NEQ: '\\neq';
|
| 140 |
+
|
| 141 |
+
LT: '<';
|
| 142 |
+
LTE: ('\\leq' | '\\le' | LTE_Q | LTE_S);
|
| 143 |
+
LTE_Q: '\\leqq';
|
| 144 |
+
LTE_S: '\\leqslant';
|
| 145 |
+
|
| 146 |
+
GT: '>';
|
| 147 |
+
GTE: ('\\geq' | '\\ge' | GTE_Q | GTE_S);
|
| 148 |
+
GTE_Q: '\\geqq';
|
| 149 |
+
GTE_S: '\\geqslant';
|
| 150 |
+
|
| 151 |
+
BANG: '!';
|
| 152 |
+
|
| 153 |
+
SINGLE_QUOTES: '\''+;
|
| 154 |
+
|
| 155 |
+
SYMBOL: '\\' [a-zA-Z]+;
|
| 156 |
+
|
| 157 |
+
math: relation;
|
| 158 |
+
|
| 159 |
+
relation:
|
| 160 |
+
relation (EQUAL | LT | LTE | GT | GTE | NEQ) relation
|
| 161 |
+
| expr;
|
| 162 |
+
|
| 163 |
+
equality: expr EQUAL expr;
|
| 164 |
+
|
| 165 |
+
expr: additive;
|
| 166 |
+
|
| 167 |
+
additive: additive (ADD | SUB) additive | mp;
|
| 168 |
+
|
| 169 |
+
// mult part
|
| 170 |
+
mp:
|
| 171 |
+
mp (MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV | COLON) mp
|
| 172 |
+
| unary;
|
| 173 |
+
|
| 174 |
+
mp_nofunc:
|
| 175 |
+
mp_nofunc (
|
| 176 |
+
MUL
|
| 177 |
+
| CMD_TIMES
|
| 178 |
+
| CMD_CDOT
|
| 179 |
+
| DIV
|
| 180 |
+
| CMD_DIV
|
| 181 |
+
| COLON
|
| 182 |
+
) mp_nofunc
|
| 183 |
+
| unary_nofunc;
|
| 184 |
+
|
| 185 |
+
unary: (ADD | SUB) unary | postfix+;
|
| 186 |
+
|
| 187 |
+
unary_nofunc:
|
| 188 |
+
(ADD | SUB) unary_nofunc
|
| 189 |
+
| postfix postfix_nofunc*;
|
| 190 |
+
|
| 191 |
+
postfix: exp postfix_op*;
|
| 192 |
+
postfix_nofunc: exp_nofunc postfix_op*;
|
| 193 |
+
postfix_op: BANG | eval_at;
|
| 194 |
+
|
| 195 |
+
eval_at:
|
| 196 |
+
BAR (eval_at_sup | eval_at_sub | eval_at_sup eval_at_sub);
|
| 197 |
+
|
| 198 |
+
eval_at_sub: UNDERSCORE L_BRACE (expr | equality) R_BRACE;
|
| 199 |
+
|
| 200 |
+
eval_at_sup: CARET L_BRACE (expr | equality) R_BRACE;
|
| 201 |
+
|
| 202 |
+
exp: exp CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp;
|
| 203 |
+
|
| 204 |
+
exp_nofunc:
|
| 205 |
+
exp_nofunc CARET (atom | L_BRACE expr R_BRACE) subexpr?
|
| 206 |
+
| comp_nofunc;
|
| 207 |
+
|
| 208 |
+
comp:
|
| 209 |
+
group
|
| 210 |
+
| abs_group
|
| 211 |
+
| func
|
| 212 |
+
| atom
|
| 213 |
+
| floor
|
| 214 |
+
| ceil;
|
| 215 |
+
|
| 216 |
+
comp_nofunc:
|
| 217 |
+
group
|
| 218 |
+
| abs_group
|
| 219 |
+
| atom
|
| 220 |
+
| floor
|
| 221 |
+
| ceil;
|
| 222 |
+
|
| 223 |
+
group:
|
| 224 |
+
L_PAREN expr R_PAREN
|
| 225 |
+
| L_BRACKET expr R_BRACKET
|
| 226 |
+
| L_BRACE expr R_BRACE
|
| 227 |
+
| L_BRACE_LITERAL expr R_BRACE_LITERAL;
|
| 228 |
+
|
| 229 |
+
abs_group: BAR expr BAR;
|
| 230 |
+
|
| 231 |
+
number: DIGIT+ (',' DIGIT DIGIT DIGIT)* ('.' DIGIT+)?;
|
| 232 |
+
|
| 233 |
+
atom: (LETTER | SYMBOL) (subexpr? SINGLE_QUOTES? | SINGLE_QUOTES? subexpr?)
|
| 234 |
+
| number
|
| 235 |
+
| DIFFERENTIAL
|
| 236 |
+
| mathit
|
| 237 |
+
| frac
|
| 238 |
+
| binom
|
| 239 |
+
| bra
|
| 240 |
+
| ket;
|
| 241 |
+
|
| 242 |
+
bra: L_ANGLE expr (R_BAR | BAR);
|
| 243 |
+
ket: (L_BAR | BAR) expr R_ANGLE;
|
| 244 |
+
|
| 245 |
+
mathit: CMD_MATHIT L_BRACE mathit_text R_BRACE;
|
| 246 |
+
mathit_text: LETTER*;
|
| 247 |
+
|
| 248 |
+
frac: CMD_FRAC (upperd = DIGIT | L_BRACE upper = expr R_BRACE)
|
| 249 |
+
(lowerd = DIGIT | L_BRACE lower = expr R_BRACE);
|
| 250 |
+
|
| 251 |
+
binom:
|
| 252 |
+
(CMD_BINOM | CMD_DBINOM | CMD_TBINOM) L_BRACE n = expr R_BRACE L_BRACE k = expr R_BRACE;
|
| 253 |
+
|
| 254 |
+
floor: L_FLOOR val = expr R_FLOOR;
|
| 255 |
+
ceil: L_CEIL val = expr R_CEIL;
|
| 256 |
+
|
| 257 |
+
func_normal:
|
| 258 |
+
FUNC_EXP
|
| 259 |
+
| FUNC_LOG
|
| 260 |
+
| FUNC_LG
|
| 261 |
+
| FUNC_LN
|
| 262 |
+
| FUNC_SIN
|
| 263 |
+
| FUNC_COS
|
| 264 |
+
| FUNC_TAN
|
| 265 |
+
| FUNC_CSC
|
| 266 |
+
| FUNC_SEC
|
| 267 |
+
| FUNC_COT
|
| 268 |
+
| FUNC_ARCSIN
|
| 269 |
+
| FUNC_ARCCOS
|
| 270 |
+
| FUNC_ARCTAN
|
| 271 |
+
| FUNC_ARCCSC
|
| 272 |
+
| FUNC_ARCSEC
|
| 273 |
+
| FUNC_ARCCOT
|
| 274 |
+
| FUNC_SINH
|
| 275 |
+
| FUNC_COSH
|
| 276 |
+
| FUNC_TANH
|
| 277 |
+
| FUNC_ARSINH
|
| 278 |
+
| FUNC_ARCOSH
|
| 279 |
+
| FUNC_ARTANH;
|
| 280 |
+
|
| 281 |
+
func:
|
| 282 |
+
func_normal (subexpr? supexpr? | supexpr? subexpr?) (
|
| 283 |
+
L_PAREN func_arg R_PAREN
|
| 284 |
+
| func_arg_noparens
|
| 285 |
+
)
|
| 286 |
+
| (LETTER | SYMBOL) (subexpr? SINGLE_QUOTES? | SINGLE_QUOTES? subexpr?) // e.g. f(x), f_1'(x)
|
| 287 |
+
L_PAREN args R_PAREN
|
| 288 |
+
| FUNC_INT (subexpr supexpr | supexpr subexpr)? (
|
| 289 |
+
additive? DIFFERENTIAL
|
| 290 |
+
| frac
|
| 291 |
+
| additive
|
| 292 |
+
)
|
| 293 |
+
| FUNC_SQRT (L_BRACKET root = expr R_BRACKET)? L_BRACE base = expr R_BRACE
|
| 294 |
+
| FUNC_OVERLINE L_BRACE base = expr R_BRACE
|
| 295 |
+
| (FUNC_SUM | FUNC_PROD) (subeq supexpr | supexpr subeq) mp
|
| 296 |
+
| FUNC_LIM limit_sub mp;
|
| 297 |
+
|
| 298 |
+
args: (expr ',' args) | expr;
|
| 299 |
+
|
| 300 |
+
limit_sub:
|
| 301 |
+
UNDERSCORE L_BRACE (LETTER | SYMBOL) LIM_APPROACH_SYM expr (
|
| 302 |
+
CARET ((L_BRACE (ADD | SUB) R_BRACE) | ADD | SUB)
|
| 303 |
+
)? R_BRACE;
|
| 304 |
+
|
| 305 |
+
func_arg: expr | (expr ',' func_arg);
|
| 306 |
+
func_arg_noparens: mp_nofunc;
|
| 307 |
+
|
| 308 |
+
subexpr: UNDERSCORE (atom | L_BRACE expr R_BRACE);
|
| 309 |
+
supexpr: CARET (atom | L_BRACE expr R_BRACE);
|
| 310 |
+
|
| 311 |
+
subeq: UNDERSCORE L_BRACE equality R_BRACE;
|
| 312 |
+
supeq: UNDERSCORE L_BRACE equality R_BRACE;
|
evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .latex_parser import parse_latex_lark, LarkLaTeXParser # noqa
|
| 2 |
+
from .transformer import TransformToSymPyExpr # noqa
|
evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (321 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/latex_parser.cpython-310.pyc
ADDED
|
Binary file (4.17 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/__pycache__/transformer.cpython-310.pyc
ADDED
|
Binary file (16.9 kB). View file
|
|
|
evalkit_internvl/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
|
evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/latex.lark
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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\\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 |
+
|
| 325 |
+
abs: BAR _expression BAR
|
| 326 |
+
floor: L_FLOOR _expression R_FLOOR
|
| 327 |
+
ceil: L_CEIL _expression R_CEIL
|
evalkit_internvl/lib/python3.10/site-packages/sympy/parsing/latex/lark/latex_parser.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
from sympy.external import import_module
|
| 6 |
+
from sympy.parsing.latex.lark.transformer import TransformToSymPyExpr
|
| 7 |
+
|
| 8 |
+
_lark = import_module("lark")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class LarkLaTeXParser:
|
| 12 |
+
r"""Class for converting input `\mathrm{\LaTeX}` strings into SymPy Expressions.
|
| 13 |
+
It holds all the necessary internal data for doing so, and exposes hooks for
|
| 14 |
+
customizing its behavior.
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
==========
|
| 18 |
+
|
| 19 |
+
print_debug_output : bool, optional
|
| 20 |
+
|
| 21 |
+
If set to ``True``, prints debug output to the logger. Defaults to ``False``.
|
| 22 |
+
|
| 23 |
+
transform : bool, optional
|
| 24 |
+
|
| 25 |
+
If set to ``True``, the class runs the Transformer class on the parse tree
|
| 26 |
+
generated by running ``Lark.parse`` on the input string. Defaults to ``True``.
|
| 27 |
+
|
| 28 |
+
Setting it to ``False`` can help with debugging the `\mathrm{\LaTeX}` grammar.
|
| 29 |
+
|
| 30 |
+
grammar_file : str, optional
|
| 31 |
+
|
| 32 |
+
The path to the grammar file that the parser should use. If set to ``None``,
|
| 33 |
+
it uses the default grammar, which is in ``grammar/latex.lark``, relative to
|
| 34 |
+
the ``sympy/parsing/latex/lark/`` directory.
|
| 35 |
+
|
| 36 |
+
transformer : str, optional
|
| 37 |
+
|
| 38 |
+
The name of the Transformer class to use. If set to ``None``, it uses the
|
| 39 |
+
default transformer class, which is :py:func:`TransformToSymPyExpr`.
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
def __init__(self, print_debug_output=False, transform=True, grammar_file=None, transformer=None):
|
| 43 |
+
grammar_dir_path = os.path.join(os.path.dirname(__file__), "grammar/")
|
| 44 |
+
|
| 45 |
+
if grammar_file is None:
|
| 46 |
+
with open(os.path.join(grammar_dir_path, "latex.lark"), encoding="utf-8") as f:
|
| 47 |
+
latex_grammar = f.read()
|
| 48 |
+
else:
|
| 49 |
+
with open(grammar_file, encoding="utf-8") as f:
|
| 50 |
+
latex_grammar = f.read()
|
| 51 |
+
|
| 52 |
+
self.parser = _lark.Lark(
|
| 53 |
+
latex_grammar,
|
| 54 |
+
source_path=grammar_dir_path,
|
| 55 |
+
parser="earley",
|
| 56 |
+
start="latex_string",
|
| 57 |
+
lexer="auto",
|
| 58 |
+
ambiguity="explicit",
|
| 59 |
+
propagate_positions=False,
|
| 60 |
+
maybe_placeholders=False,
|
| 61 |
+
keep_all_tokens=True)
|
| 62 |
+
|
| 63 |
+
self.print_debug_output = print_debug_output
|
| 64 |
+
self.transform_expr = transform
|
| 65 |
+
|
| 66 |
+
if transformer is None:
|
| 67 |
+
self.transformer = TransformToSymPyExpr()
|
| 68 |
+
else:
|
| 69 |
+
self.transformer = transformer()
|
| 70 |
+
|
| 71 |
+
def doparse(self, s: str):
|
| 72 |
+
if self.print_debug_output:
|
| 73 |
+
_lark.logger.setLevel(logging.DEBUG)
|
| 74 |
+
|
| 75 |
+
parse_tree = self.parser.parse(s)
|
| 76 |
+
|
| 77 |
+
if not self.transform_expr:
|
| 78 |
+
# exit early and return the parse tree
|
| 79 |
+
_lark.logger.debug("expression = %s", s)
|
| 80 |
+
_lark.logger.debug(parse_tree)
|
| 81 |
+
_lark.logger.debug(parse_tree.pretty())
|
| 82 |
+
return parse_tree
|
| 83 |
+
|
| 84 |
+
if self.print_debug_output:
|
| 85 |
+
# print this stuff before attempting to run the transformer
|
| 86 |
+
_lark.logger.debug("expression = %s", s)
|
| 87 |
+
# print the `parse_tree` variable
|
| 88 |
+
_lark.logger.debug(parse_tree.pretty())
|
| 89 |
+
|
| 90 |
+
sympy_expression = self.transformer.transform(parse_tree)
|
| 91 |
+
|
| 92 |
+
if self.print_debug_output:
|
| 93 |
+
_lark.logger.debug("SymPy expression = %s", sympy_expression)
|
| 94 |
+
|
| 95 |
+
return sympy_expression
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if _lark is not None:
|
| 99 |
+
_lark_latex_parser = LarkLaTeXParser()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def parse_latex_lark(s: str):
|
| 103 |
+
"""
|
| 104 |
+
Experimental LaTeX parser using Lark.
|
| 105 |
+
|
| 106 |
+
This function is still under development and its API may change with the
|
| 107 |
+
next releases of SymPy.
|
| 108 |
+
"""
|
| 109 |
+
if _lark is None:
|
| 110 |
+
raise ImportError("Lark is probably not installed")
|
| 111 |
+
return _lark_latex_parser.doparse(s)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _pretty_print_lark_trees(tree, indent=0, show_expr=True):
|
| 115 |
+
if isinstance(tree, _lark.Token):
|
| 116 |
+
return tree.value
|
| 117 |
+
|
| 118 |
+
data = str(tree.data)
|
| 119 |
+
|
| 120 |
+
is_expr = data.startswith("expression")
|
| 121 |
+
|
| 122 |
+
if is_expr:
|
| 123 |
+
data = re.sub(r"^expression", "E", data)
|
| 124 |
+
|
| 125 |
+
is_ambig = (data == "_ambig")
|
| 126 |
+
|
| 127 |
+
if is_ambig:
|
| 128 |
+
new_indent = indent + 2
|
| 129 |
+
else:
|
| 130 |
+
new_indent = indent
|
| 131 |
+
|
| 132 |
+
output = ""
|
| 133 |
+
show_node = not is_expr or show_expr
|
| 134 |
+
|
| 135 |
+
if show_node:
|
| 136 |
+
output += str(data) + "("
|
| 137 |
+
|
| 138 |
+
if is_ambig:
|
| 139 |
+
output += "\n" + "\n".join([" " * new_indent + _pretty_print_lark_trees(i, new_indent, show_expr) for i in tree.children])
|
| 140 |
+
else:
|
| 141 |
+
output += ",".join([_pretty_print_lark_trees(i, new_indent, show_expr) for i in tree.children])
|
| 142 |
+
|
| 143 |
+
if show_node:
|
| 144 |
+
output += ")"
|
| 145 |
+
|
| 146 |
+
return output
|
evalkit_internvl/lib/python3.10/site-pack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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import sympy
|
| 4 |
+
from sympy.external import import_module
|
| 5 |
+
from sympy.parsing.latex.errors import LaTeXParsingError
|
| 6 |
+
|
| 7 |
+
lark = import_module("lark")
|
| 8 |
+
|
| 9 |
+
if lark:
|
| 10 |
+
from lark import Transformer, Token # type: ignore
|
| 11 |
+
else:
|
| 12 |
+
class Transformer: # type: ignore
|
| 13 |
+
def transform(self, *args):
|
| 14 |
+
pass
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Token: # type: ignore
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# noinspection PyPep8Naming,PyMethodMayBeStatic
|
| 22 |
+
class TransformToSymPyExpr(Transformer):
|
| 23 |
+
"""Returns a SymPy expression that is generated by traversing the ``lark.Tree``
|
| 24 |
+
passed to the ``.transform()`` function.
|
| 25 |
+
|
| 26 |
+
Notes
|
| 27 |
+
=====
|
| 28 |
+
|
| 29 |
+
**This class is never supposed to be used directly.**
|
| 30 |
+
|
| 31 |
+
In order to tweak the behavior of this class, it has to be subclassed and then after
|
| 32 |
+
the required modifications are made, the name of the new class should be passed to
|
| 33 |
+
the :py:class:`LarkLaTeXParser` class by using the ``transformer`` argument in the
|
| 34 |
+
constructor.
|
| 35 |
+
|
| 36 |
+
Parameters
|
| 37 |
+
==========
|
| 38 |
+
|
| 39 |
+
visit_tokens : bool, optional
|
| 40 |
+
For information about what this option does, see `here
|
| 41 |
+
<https://lark-parser.readthedocs.io/en/latest/visitors.html#lark.visitors.Transformer>`_.
|
| 42 |
+
|
| 43 |
+
Note that the option must be set to ``True`` for the default parser to work.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
SYMBOL = sympy.Symbol
|
| 47 |
+
DIGIT = sympy.core.numbers.Integer
|
| 48 |
+
|
| 49 |
+
def CMD_INFTY(self, tokens):
|
| 50 |
+
return sympy.oo
|
| 51 |
+
|
| 52 |
+
def GREEK_SYMBOL(self, tokens):
|
| 53 |
+
# we omit the first character because it is a backslash. Also, if the variable name has "var" in it,
|
| 54 |
+
# like "varphi" or "varepsilon", we remove that too
|
| 55 |
+
variable_name = re.sub("var", "", tokens[1:])
|
| 56 |
+
|
| 57 |
+
return sympy.Symbol(variable_name)
|
| 58 |
+
|
| 59 |
+
def BASIC_SUBSCRIPTED_SYMBOL(self, tokens):
|
| 60 |
+
symbol, sub = tokens.value.split("_")
|
| 61 |
+
if sub.startswith("{"):
|
| 62 |
+
return sympy.Symbol("%s_{%s}" % (symbol, sub[1:-1]))
|
| 63 |
+
else:
|
| 64 |
+
return sympy.Symbol("%s_{%s}" % (symbol, sub))
|
| 65 |
+
|
| 66 |
+
def GREEK_SUBSCRIPTED_SYMBOL(self, tokens):
|
| 67 |
+
greek_letter, sub = tokens.value.split("_")
|
| 68 |
+
greek_letter = re.sub("var", "", greek_letter[1:])
|
| 69 |
+
|
| 70 |
+
if sub.startswith("{"):
|
| 71 |
+
return sympy.Symbol("%s_{%s}" % (greek_letter, sub[1:-1]))
|
| 72 |
+
else:
|
| 73 |
+
return sympy.Symbol("%s_{%s}" % (greek_letter, sub))
|
| 74 |
+
|
| 75 |
+
def SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens):
|
| 76 |
+
symbol, sub = tokens.value.split("_")
|
| 77 |
+
if sub.startswith("{"):
|
| 78 |
+
greek_letter = sub[2:-1]
|
| 79 |
+
greek_letter = re.sub("var", "", greek_letter)
|
| 80 |
+
|
| 81 |
+
return sympy.Symbol("%s_{%s}" % (symbol, greek_letter))
|
| 82 |
+
else:
|
| 83 |
+
greek_letter = sub[1:]
|
| 84 |
+
greek_letter = re.sub("var", "", greek_letter)
|
| 85 |
+
|
| 86 |
+
return sympy.Symbol("%s_{%s}" % (symbol, greek_letter))
|
| 87 |
+
|
| 88 |
+
def multi_letter_symbol(self, tokens):
|
| 89 |
+
return sympy.Symbol(tokens[2])
|
| 90 |
+
|
| 91 |
+
def number(self, tokens):
|
| 92 |
+
if "." in tokens[0]:
|
| 93 |
+
return sympy.core.numbers.Float(tokens[0])
|
| 94 |
+
else:
|
| 95 |
+
return sympy.core.numbers.Integer(tokens[0])
|
| 96 |
+
|
| 97 |
+
def latex_string(self, tokens):
|
| 98 |
+
return tokens[0]
|
| 99 |
+
|
| 100 |
+
def group_round_parentheses(self, tokens):
|
| 101 |
+
return tokens[1]
|
| 102 |
+
|
| 103 |
+
def group_square_brackets(self, tokens):
|
| 104 |
+
return tokens[1]
|
| 105 |
+
|
| 106 |
+
def group_curly_parentheses(self, tokens):
|
| 107 |
+
return tokens[1]
|
| 108 |
+
|
| 109 |
+
def eq(self, tokens):
|
| 110 |
+
return sympy.Eq(tokens[0], tokens[2])
|
| 111 |
+
|
| 112 |
+
def ne(self, tokens):
|
| 113 |
+
return sympy.Ne(tokens[0], tokens[2])
|
| 114 |
+
|
| 115 |
+
def lt(self, tokens):
|
| 116 |
+
return sympy.Lt(tokens[0], tokens[2])
|
| 117 |
+
|
| 118 |
+
def lte(self, tokens):
|
| 119 |
+
return sympy.Le(tokens[0], tokens[2])
|
| 120 |
+
|
| 121 |
+
def gt(self, tokens):
|
| 122 |
+
return sympy.Gt(tokens[0], tokens[2])
|
| 123 |
+
|
| 124 |
+
def gte(self, tokens):
|
| 125 |
+
return sympy.Ge(tokens[0], tokens[2])
|
| 126 |
+
|
| 127 |
+
def add(self, tokens):
|
| 128 |
+
return sympy.Add(tokens[0], tokens[2])
|
| 129 |
+
|
| 130 |
+
def sub(self, tokens):
|
| 131 |
+
if len(tokens) == 2:
|
| 132 |
+
return -tokens[1]
|
| 133 |
+
elif len(tokens) == 3:
|
| 134 |
+
return sympy.Add(tokens[0], -tokens[2])
|
| 135 |
+
|
| 136 |
+
def mul(self, tokens):
|
| 137 |
+
return sympy.Mul(tokens[0], tokens[2])
|
| 138 |
+
|
| 139 |
+
def div(self, tokens):
|
| 140 |
+
return sympy.Mul(tokens[0], sympy.Pow(tokens[2], -1))
|
| 141 |
+
|
| 142 |
+
def adjacent_expressions(self, tokens):
|
| 143 |
+
# Most of the time, if two expressions are next to each other, it means implicit multiplication,
|
| 144 |
+
# but not always
|
| 145 |
+
from sympy.physics.quantum import Bra, Ket
|
| 146 |
+
if isinstance(tokens[0], Ket) and isinstance(tokens[1], Bra):
|
| 147 |
+
from sympy.physics.quantum import OuterProduct
|
| 148 |
+
return OuterProduct(tokens[0], tokens[1])
|
| 149 |
+
elif tokens[0] == sympy.Symbol("d"):
|
| 150 |
+
# If the leftmost token is a "d", then it is highly likely that this is a differential
|
| 151 |
+
return tokens[0], tokens[1]
|
| 152 |
+
elif isinstance(tokens[0], tuple):
|
| 153 |
+
# then we have a derivative
|
| 154 |
+
return sympy.Derivative(tokens[1], tokens[0][1])
|
| 155 |
+
else:
|
| 156 |
+
return sympy.Mul(tokens[0], tokens[1])
|
| 157 |
+
|
| 158 |
+
def superscript(self, tokens):
|
| 159 |
+
return sympy.Pow(tokens[0], tokens[2])
|
| 160 |
+
|
| 161 |
+
def fraction(self, tokens):
|
| 162 |
+
numerator = tokens[1]
|
| 163 |
+
if isinstance(tokens[2], tuple):
|
| 164 |
+
# we only need the variable w.r.t. which we are differentiating
|
| 165 |
+
_, variable = tokens[2]
|
| 166 |
+
|
| 167 |
+
# we will pass this information upwards
|
| 168 |
+
return "derivative", variable
|
| 169 |
+
else:
|
| 170 |
+
denominator = tokens[2]
|
| 171 |
+
return sympy.Mul(numerator, sympy.Pow(denominator, -1))
|
| 172 |
+
|
| 173 |
+
def binomial(self, tokens):
|
| 174 |
+
return sympy.binomial(tokens[1], tokens[2])
|
| 175 |
+
|
| 176 |
+
def normal_integral(self, tokens):
|
| 177 |
+
underscore_index = None
|
| 178 |
+
caret_index = None
|
| 179 |
+
|
| 180 |
+
if "_" in tokens:
|
| 181 |
+
# we need to know the index because the next item in the list is the
|
| 182 |
+
# arguments for the lower bound of the integral
|
| 183 |
+
underscore_index = tokens.index("_")
|
| 184 |
+
|
| 185 |
+
if "^" in tokens:
|
| 186 |
+
# we need to know the index because the next item in the list is the
|
| 187 |
+
# arguments for the upper bound of the integral
|
| 188 |
+
caret_index = tokens.index("^")
|
| 189 |
+
|
| 190 |
+
lower_bound = tokens[underscore_index + 1] if underscore_index else None
|
| 191 |
+
upper_bound = tokens[caret_index + 1] if caret_index else None
|
| 192 |
+
|
| 193 |
+
differential_symbol = self._extract_differential_symbol(tokens)
|
| 194 |
+
|
| 195 |
+
if differential_symbol is None:
|
| 196 |
+
raise LaTeXParsingError("Differential symbol was not found in the expression."
|
| 197 |
+
"Valid differential symbols are \"d\", \"\\text{d}, and \"\\mathrm{d}\".")
|
| 198 |
+
|
| 199 |
+
# else we can assume that a differential symbol was found
|
| 200 |
+
differential_variable_index = tokens.index(differential_symbol) + 1
|
| 201 |
+
differential_variable = tokens[differential_variable_index]
|
| 202 |
+
|
| 203 |
+
# we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
|
| 204 |
+
# evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
|
| 205 |
+
if lower_bound is not None and upper_bound is None:
|
| 206 |
+
# then one was given and the other wasn't
|
| 207 |
+
raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
|
| 208 |
+
|
| 209 |
+
if upper_bound is not None and lower_bound is None:
|
| 210 |
+
# then one was given and the other wasn't
|
| 211 |
+
raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
|
| 212 |
+
|
| 213 |
+
# check if any expression was given or not. If it wasn't, then set the integrand to 1.
|
| 214 |
+
if underscore_index is not None and underscore_index == differential_variable_index - 3:
|
| 215 |
+
# The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
|
| 216 |
+
# backwards after that gives us the underscore, then that means that there _was_ no integrand.
|
| 217 |
+
# Example: \int^7_0 dx
|
| 218 |
+
integrand = 1
|
| 219 |
+
elif caret_index is not None and caret_index == differential_variable_index - 3:
|
| 220 |
+
# The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
|
| 221 |
+
# backwards after that gives us the caret, then that means that there _was_ no integrand.
|
| 222 |
+
# Example: \int_0^7 dx
|
| 223 |
+
integrand = 1
|
| 224 |
+
elif differential_variable_index == 2:
|
| 225 |
+
# this means we have something like "\int dx", because the "\int" symbol will always be
|
| 226 |
+
# at index 0 in `tokens`
|
| 227 |
+
integrand = 1
|
| 228 |
+
else:
|
| 229 |
+
# The Token at differential_variable_index - 1 is the differential symbol itself, so we need to go one
|
| 230 |
+
# more step before that.
|
| 231 |
+
integrand = tokens[differential_variable_index - 2]
|
| 232 |
+
|
| 233 |
+
if lower_bound is not None:
|
| 234 |
+
# then we have a definite integral
|
| 235 |
+
|
| 236 |
+
# we can assume that either both the lower and upper bounds are given, or
|
| 237 |
+
# neither of them are
|
| 238 |
+
return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
|
| 239 |
+
else:
|
| 240 |
+
# we have an indefinite integral
|
| 241 |
+
return sympy.Integral(integrand, differential_variable)
|
| 242 |
+
|
| 243 |
+
def group_curly_parentheses_int(self, tokens):
|
| 244 |
+
# return signature is a tuple consisting of the expression in the numerator, along with the variable of
|
| 245 |
+
# integration
|
| 246 |
+
if len(tokens) == 3:
|
| 247 |
+
return 1, tokens[1]
|
| 248 |
+
elif len(tokens) == 4:
|
| 249 |
+
return tokens[1], tokens[2]
|
| 250 |
+
# there are no other possibilities
|
| 251 |
+
|
| 252 |
+
def special_fraction(self, tokens):
|
| 253 |
+
numerator, variable = tokens[1]
|
| 254 |
+
denominator = tokens[2]
|
| 255 |
+
|
| 256 |
+
# We pass the integrand, along with information about the variable of integration, upw
|
| 257 |
+
return sympy.Mul(numerator, sympy.Pow(denominator, -1)), variable
|
| 258 |
+
|
| 259 |
+
def integral_with_special_fraction(self, tokens):
|
| 260 |
+
underscore_index = None
|
| 261 |
+
caret_index = None
|
| 262 |
+
|
| 263 |
+
if "_" in tokens:
|
| 264 |
+
# we need to know the index because the next item in the list is the
|
| 265 |
+
# arguments for the lower bound of the integral
|
| 266 |
+
underscore_index = tokens.index("_")
|
| 267 |
+
|
| 268 |
+
if "^" in tokens:
|
| 269 |
+
# we need to know the index because the next item in the list is the
|
| 270 |
+
# arguments for the upper bound of the integral
|
| 271 |
+
caret_index = tokens.index("^")
|
| 272 |
+
|
| 273 |
+
lower_bound = tokens[underscore_index + 1] if underscore_index else None
|
| 274 |
+
upper_bound = tokens[caret_index + 1] if caret_index else None
|
| 275 |
+
|
| 276 |
+
# we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
|
| 277 |
+
# evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
|
| 278 |
+
if lower_bound is not None and upper_bound is None:
|
| 279 |
+
# then one was given and the other wasn't
|
| 280 |
+
raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
|
| 281 |
+
|
| 282 |
+
if upper_bound is not None and lower_bound is None:
|
| 283 |
+
# then one was given and the other wasn't
|
| 284 |
+
raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
|
| 285 |
+
|
| 286 |
+
integrand, differential_variable = tokens[-1]
|
| 287 |
+
|
| 288 |
+
if lower_bound is not None:
|
| 289 |
+
# then we have a definite integral
|
| 290 |
+
|
| 291 |
+
# we can assume that either both the lower and upper bounds are given, or
|
| 292 |
+
# neither of them are
|
| 293 |
+
return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
|
| 294 |
+
else:
|
| 295 |
+
# we have an indefinite integral
|
| 296 |
+
return sympy.Integral(integrand, differential_variable)
|
| 297 |
+
|
| 298 |
+
def group_curly_parentheses_special(self, tokens):
|
| 299 |
+
underscore_index = tokens.index("_")
|
| 300 |
+
caret_index = tokens.index("^")
|
| 301 |
+
|
| 302 |
+
# given the type of expressions we are parsing, we can assume that the lower limit
|
| 303 |
+
# will always use braces around its arguments. This is because we don't support
|
| 304 |
+
# converting unconstrained sums into SymPy expressions.
|
| 305 |
+
|
| 306 |
+
# first we isolate the bottom limit
|
| 307 |
+
left_brace_index = tokens.index("{", underscore_index)
|
| 308 |
+
right_brace_index = tokens.index("}", underscore_index)
|
| 309 |
+
|
| 310 |
+
bottom_limit = tokens[left_brace_index + 1: right_brace_index]
|
| 311 |
+
|
| 312 |
+
# next, we isolate the upper limit
|
| 313 |
+
top_limit = tokens[caret_index + 1:]
|
| 314 |
+
|
| 315 |
+
# the code below will be useful for supporting things like `\sum_{n = 0}^{n = 5} n^2`
|
| 316 |
+
# if "{" in top_limit:
|
| 317 |
+
# left_brace_index = tokens.index("{", caret_index)
|
| 318 |
+
# if left_brace_index != -1:
|
| 319 |
+
# # then there's a left brace in the string, and we need to find the closing right brace
|
| 320 |
+
# right_brace_index = tokens.index("}", caret_index)
|
| 321 |
+
# top_limit = tokens[left_brace_index + 1: right_brace_index]
|
| 322 |
+
|
| 323 |
+
# print(f"top limit = {top_limit}")
|
| 324 |
+
|
| 325 |
+
index_variable = bottom_limit[0]
|
| 326 |
+
lower_limit = bottom_limit[-1]
|
| 327 |
+
upper_limit = top_limit[0] # for now, the index will always be 0
|
| 328 |
+
|
| 329 |
+
# print(f"return value = ({index_variable}, {lower_limit}, {upper_limit})")
|
| 330 |
+
|
| 331 |
+
return index_variable, lower_limit, upper_limit
|
| 332 |
+
|
| 333 |
+
def summation(self, tokens):
|
| 334 |
+
return sympy.Sum(tokens[2], tokens[1])
|
| 335 |
+
|
| 336 |
+
def product(self, tokens):
|
| 337 |
+
return sympy.Product(tokens[2], tokens[1])
|
| 338 |
+
|
| 339 |
+
def limit_dir_expr(self, tokens):
|
| 340 |
+
caret_index = tokens.index("^")
|
| 341 |
+
|
| 342 |
+
if "{" in tokens:
|
| 343 |
+
left_curly_brace_index = tokens.index("{", caret_index)
|
| 344 |
+
direction = tokens[left_curly_brace_index + 1]
|
| 345 |
+
else:
|
| 346 |
+
direction = tokens[caret_index + 1]
|
| 347 |
+
|
| 348 |
+
if direction == "+":
|
| 349 |
+
return tokens[0], "+"
|
| 350 |
+
elif direction == "-":
|
| 351 |
+
return tokens[0], "-"
|
| 352 |
+
else:
|
| 353 |
+
return tokens[0], "+-"
|
| 354 |
+
|
| 355 |
+
def group_curly_parentheses_lim(self, tokens):
|
| 356 |
+
limit_variable = tokens[1]
|
| 357 |
+
if isinstance(tokens[3], tuple):
|
| 358 |
+
destination, direction = tokens[3]
|
| 359 |
+
else:
|
| 360 |
+
destination = tokens[3]
|
| 361 |
+
direction = "+-"
|
| 362 |
+
|
| 363 |
+
return limit_variable, destination, direction
|
| 364 |
+
|
| 365 |
+
def limit(self, tokens):
|
| 366 |
+
limit_variable, destination, direction = tokens[2]
|
| 367 |
+
|
| 368 |
+
return sympy.Limit(tokens[-1], limit_variable, destination, direction)
|
| 369 |
+
|
| 370 |
+
def differential(self, tokens):
|
| 371 |
+
return tokens[1]
|
| 372 |
+
|
| 373 |
+
def derivative(self, tokens):
|
| 374 |
+
return sympy.Derivative(tokens[-1], tokens[5])
|
| 375 |
+
|
| 376 |
+
def list_of_expressions(self, tokens):
|
| 377 |
+
if len(tokens) == 1:
|
| 378 |
+
# we return it verbatim because the function_applied node expects
|
| 379 |
+
# a list
|
| 380 |
+
return tokens
|
| 381 |
+
else:
|
| 382 |
+
def remove_tokens(args):
|
| 383 |
+
if isinstance(args, Token):
|
| 384 |
+
if args.type != "COMMA":
|
| 385 |
+
# An unexpected token was encountered
|
| 386 |
+
raise LaTeXParsingError("A comma token was expected, but some other token was encountered.")
|
| 387 |
+
return False
|
| 388 |
+
return True
|
| 389 |
+
|
| 390 |
+
return filter(remove_tokens, tokens)
|
| 391 |
+
|
| 392 |
+
def function_applied(self, tokens):
|
| 393 |
+
return sympy.Function(tokens[0])(*tokens[2])
|
| 394 |
+
|
| 395 |
+
def min(self, tokens):
|
| 396 |
+
return sympy.Min(*tokens[2])
|
| 397 |
+
|
| 398 |
+
def max(self, tokens):
|
| 399 |
+
return sympy.Max(*tokens[2])
|
| 400 |
+
|
| 401 |
+
def bra(self, tokens):
|
| 402 |
+
from sympy.physics.quantum import Bra
|
| 403 |
+
return Bra(tokens[1])
|
| 404 |
+
|
| 405 |
+
def ket(self, tokens):
|
| 406 |
+
from sympy.physics.quantum import Ket
|
| 407 |
+
return Ket(tokens[1])
|
| 408 |
+
|
| 409 |
+
def inner_product(self, tokens):
|
| 410 |
+
from sympy.physics.quantum import Bra, Ket, InnerProduct
|
| 411 |
+
return InnerProduct(Bra(tokens[1]), Ket(tokens[3]))
|
| 412 |
+
|
| 413 |
+
def sin(self, tokens):
|
| 414 |
+
return sympy.sin(tokens[1])
|
| 415 |
+
|
| 416 |
+
def cos(self, tokens):
|
| 417 |
+
return sympy.cos(tokens[1])
|
| 418 |
+
|
| 419 |
+
def tan(self, tokens):
|
| 420 |
+
return sympy.tan(tokens[1])
|
| 421 |
+
|
| 422 |
+
def csc(self, tokens):
|
| 423 |
+
return sympy.csc(tokens[1])
|
| 424 |
+
|
| 425 |
+
def sec(self, tokens):
|
| 426 |
+
return sympy.sec(tokens[1])
|
| 427 |
+
|
| 428 |
+
def cot(self, tokens):
|
| 429 |
+
return sympy.cot(tokens[1])
|
| 430 |
+
|
| 431 |
+
def sin_power(self, tokens):
|
| 432 |
+
exponent = tokens[2]
|
| 433 |
+
if exponent == -1:
|
| 434 |
+
return sympy.asin(tokens[-1])
|
| 435 |
+
else:
|
| 436 |
+
return sympy.Pow(sympy.sin(tokens[-1]), exponent)
|
| 437 |
+
|
| 438 |
+
def cos_power(self, tokens):
|
| 439 |
+
exponent = tokens[2]
|
| 440 |
+
if exponent == -1:
|
| 441 |
+
return sympy.acos(tokens[-1])
|
| 442 |
+
else:
|
| 443 |
+
return sympy.Pow(sympy.cos(tokens[-1]), exponent)
|
| 444 |
+
|
| 445 |
+
def tan_power(self, tokens):
|
| 446 |
+
exponent = tokens[2]
|
| 447 |
+
if exponent == -1:
|
| 448 |
+
return sympy.atan(tokens[-1])
|
| 449 |
+
else:
|
| 450 |
+
return sympy.Pow(sympy.tan(tokens[-1]), exponent)
|
| 451 |
+
|
| 452 |
+
def csc_power(self, tokens):
|
| 453 |
+
exponent = tokens[2]
|
| 454 |
+
if exponent == -1:
|
| 455 |
+
return sympy.acsc(tokens[-1])
|
| 456 |
+
else:
|
| 457 |
+
return sympy.Pow(sympy.csc(tokens[-1]), exponent)
|
| 458 |
+
|
| 459 |
+
def sec_power(self, tokens):
|
| 460 |
+
exponent = tokens[2]
|
| 461 |
+
if exponent == -1:
|
| 462 |
+
return sympy.asec(tokens[-1])
|
| 463 |
+
else:
|
| 464 |
+
return sympy.Pow(sympy.sec(tokens[-1]), exponent)
|
| 465 |
+
|
| 466 |
+
def cot_power(self, tokens):
|
| 467 |
+
exponent = tokens[2]
|
| 468 |
+
if exponent == -1:
|
| 469 |
+
return sympy.acot(tokens[-1])
|
| 470 |
+
else:
|
| 471 |
+
return sympy.Pow(sympy.cot(tokens[-1]), exponent)
|
| 472 |
+
|
| 473 |
+
def arcsin(self, tokens):
|
| 474 |
+
return sympy.asin(tokens[1])
|
| 475 |
+
|
| 476 |
+
def arccos(self, tokens):
|
| 477 |
+
return sympy.acos(tokens[1])
|
| 478 |
+
|
| 479 |
+
def arctan(self, tokens):
|
| 480 |
+
return sympy.atan(tokens[1])
|
| 481 |
+
|
| 482 |
+
def arccsc(self, tokens):
|
| 483 |
+
return sympy.acsc(tokens[1])
|
| 484 |
+
|
| 485 |
+
def arcsec(self, tokens):
|
| 486 |
+
return sympy.asec(tokens[1])
|
| 487 |
+
|
| 488 |
+
def arccot(self, tokens):
|
| 489 |
+
return sympy.acot(tokens[1])
|
| 490 |
+
|
| 491 |
+
def sinh(self, tokens):
|
| 492 |
+
return sympy.sinh(tokens[1])
|
| 493 |
+
|
| 494 |
+
def cosh(self, tokens):
|
| 495 |
+
return sympy.cosh(tokens[1])
|
| 496 |
+
|
| 497 |
+
def tanh(self, tokens):
|
| 498 |
+
return sympy.tanh(tokens[1])
|
| 499 |
+
|
| 500 |
+
def asinh(self, tokens):
|
| 501 |
+
return sympy.asinh(tokens[1])
|
| 502 |
+
|
| 503 |
+
def acosh(self, tokens):
|
| 504 |
+
return sympy.acosh(tokens[1])
|
| 505 |
+
|
| 506 |
+
def atanh(self, tokens):
|
| 507 |
+
return sympy.atanh(tokens[1])
|
| 508 |
+
|
| 509 |
+
def abs(self, tokens):
|
| 510 |
+
return sympy.Abs(tokens[1])
|
| 511 |
+
|
| 512 |
+
def floor(self, tokens):
|
| 513 |
+
return sympy.floor(tokens[1])
|
| 514 |
+
|
| 515 |
+
def ceil(self, tokens):
|
| 516 |
+
return sympy.ceiling(tokens[1])
|
| 517 |
+
|
| 518 |
+
def factorial(self, tokens):
|
| 519 |
+
return sympy.factorial(tokens[0])
|
| 520 |
+
|
| 521 |
+
def conjugate(self, tokens):
|
| 522 |
+
return sympy.conjugate(tokens[1])
|
| 523 |
+
|
| 524 |
+
def square_root(self, tokens):
|
| 525 |
+
if len(tokens) == 2:
|
| 526 |
+
# then there was no square bracket argument
|
| 527 |
+
return sympy.sqrt(tokens[1])
|
| 528 |
+
elif len(tokens) == 3:
|
| 529 |
+
# then there _was_ a square bracket argument
|
| 530 |
+
return sympy.root(tokens[2], tokens[1])
|
| 531 |
+
|
| 532 |
+
def exponential(self, tokens):
|
| 533 |
+
return sympy.exp(tokens[1])
|
| 534 |
+
|
| 535 |
+
def log(self, tokens):
|
| 536 |
+
if tokens[0].type == "FUNC_LG":
|
| 537 |
+
# we don't need to check if there's an underscore or not because having one
|
| 538 |
+
# in this case would be meaningless
|
| 539 |
+
# TODO: ANTLR refers to ISO 80000-2:2019. should we keep base 10 or base 2?
|
| 540 |
+
return sympy.log(tokens[1], 10)
|
| 541 |
+
elif tokens[0].type == "FUNC_LN":
|
| 542 |
+
return sympy.log(tokens[1])
|
| 543 |
+
elif tokens[0].type == "FUNC_LOG":
|
| 544 |
+
# we check if a base was specified or not
|
| 545 |
+
if "_" in tokens:
|
| 546 |
+
# then a base was specified
|
| 547 |
+
return sympy.log(tokens[3], tokens[2])
|
| 548 |
+
else:
|
| 549 |
+
# a base was not specified
|
| 550 |
+
return sympy.log(tokens[1])
|
| 551 |
+
|
| 552 |
+
def _extract_differential_symbol(self, s: str):
|
| 553 |
+
differential_symbols = {"d", r"\text{d}", r"\mathrm{d}"}
|
| 554 |
+
|
| 555 |
+
differential_symbol = next((symbol for symbol in differential_symbols if symbol in s), None)
|
| 556 |
+
|
| 557 |
+
return differential_symbol
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/activations.cpython-310.pyc
ADDED
|
Binary file (4.71 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/adapter.cpython-310.pyc
ADDED
|
Binary file (21.8 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/attention.cpython-310.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/attention_flax.cpython-310.pyc
ADDED
|
Binary file (15.4 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/attention_processor.cpython-310.pyc
ADDED
|
Binary file (57.7 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/downsampling.cpython-310.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/dual_transformer_2d.cpython-310.pyc
ADDED
|
Binary file (756 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/embeddings.cpython-310.pyc
ADDED
|
Binary file (27.8 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/lora.cpython-310.pyc
ADDED
|
Binary file (13.2 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/__pycache__/modeling_flax_pytorch_utils.cpython-310.pyc
ADDED
|
Binary file (2.91 kB). View file
|
|
|