applied-ai-018 commited on
Commit
1574eb8
·
verified ·
1 Parent(s): 17fe827

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/24.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step80/zero/6.post_attention_layernorm.weight/exp_avg.pt +3 -0
  3. ckpts/universal/global_step80/zero/6.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
  4. ckpts/universal/global_step80/zero/6.post_attention_layernorm.weight/fp32.pt +3 -0
  5. venv/lib/python3.10/site-packages/sympy/external/__init__.py +20 -0
  6. venv/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/sympy/external/gmpy.py +104 -0
  11. venv/lib/python3.10/site-packages/sympy/external/importtools.py +187 -0
  12. venv/lib/python3.10/site-packages/sympy/external/pythonmpq.py +341 -0
  13. venv/lib/python3.10/site-packages/sympy/external/tests/__init__.py +0 -0
  14. venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_autowrap.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_pythonmpq.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py +313 -0
  22. venv/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py +379 -0
  23. venv/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py +40 -0
  24. venv/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py +333 -0
  25. venv/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py +176 -0
  26. venv/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py +35 -0
  27. venv/lib/python3.10/site-packages/sympy/logic/__init__.py +12 -0
  28. venv/lib/python3.10/site-packages/sympy/logic/boolalg.py +0 -0
  29. venv/lib/python3.10/site-packages/sympy/logic/inference.py +329 -0
  30. venv/lib/python3.10/site-packages/sympy/logic/utilities/dimacs.py +70 -0
  31. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_aesaracode.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_c.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_codeprinter.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_conventions.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_cupy.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_cxx.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_dot.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_fortran.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_glsl.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_gtk.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_jax.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_jscode.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_julia.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_lambdarepr.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_latex.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_llvmjit.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_maple.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_mathematica.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_mathml.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/24.mlp.dense_4h_to_h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a62d245caaa871c386f1fc11beec7189512fb05b3a8f9de42bc60bb1d6bce086
3
+ size 33555612
ckpts/universal/global_step80/zero/6.post_attention_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02c89447721eb2e482527ed966e2ff33b3d31914e3e796440a7cdc4fd8bdd6af
3
+ size 9372
ckpts/universal/global_step80/zero/6.post_attention_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:714fbf9f814fe5c8726abd24f878eca6c567d9e3fc61633c49505959f7a99ce4
3
+ size 9387
ckpts/universal/global_step80/zero/6.post_attention_layernorm.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:166df2ce979a63e5f8acf604604ec708b99632dc4deab848ec99934b2cf345ea
3
+ size 9293
venv/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']
venv/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (776 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc ADDED
Binary file (1.45 kB). View file
 
venv/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc ADDED
Binary file (5.53 kB). View file
 
venv/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc ADDED
Binary file (8.81 kB). View file
 
venv/lib/python3.10/site-packages/sympy/external/gmpy.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Tuple as tTuple, Type
3
+
4
+ import mpmath.libmp as mlib
5
+
6
+ from sympy.external import import_module
7
+
8
+ __all__ = [
9
+ # GROUND_TYPES is either 'gmpy' or 'python' depending on which is used. If
10
+ # gmpy is installed then it will be used unless the environment variable
11
+ # SYMPY_GROUND_TYPES is set to something other than 'auto', 'gmpy', or
12
+ # 'gmpy2'.
13
+ 'GROUND_TYPES',
14
+
15
+ # If HAS_GMPY is 0, no supported version of gmpy is available. Otherwise,
16
+ # HAS_GMPY will be 2 for gmpy2 if GROUND_TYPES is 'gmpy'. It used to be
17
+ # possible for HAS_GMPY to be 1 for gmpy but gmpy is no longer supported.
18
+ 'HAS_GMPY',
19
+
20
+ # SYMPY_INTS is a tuple containing the base types for valid integer types.
21
+ # This is either (int,) or (int, type(mpz(0))) depending on GROUND_TYPES.
22
+ 'SYMPY_INTS',
23
+
24
+ # MPQ is either gmpy.mpq or the Python equivalent from
25
+ # sympy.external.pythonmpq
26
+ 'MPQ',
27
+
28
+ # MPZ is either gmpy.mpz or int.
29
+ 'MPZ',
30
+
31
+ # Either the gmpy or the mpmath function
32
+ 'factorial',
33
+
34
+ # isqrt from gmpy or mpmath
35
+ 'sqrt',
36
+ ]
37
+
38
+
39
+ #
40
+ # SYMPY_GROUND_TYPES can be gmpy, gmpy2, python or auto
41
+ #
42
+ GROUND_TYPES = os.environ.get('SYMPY_GROUND_TYPES', 'auto').lower()
43
+
44
+
45
+ #
46
+ # Try to import gmpy2 by default. If gmpy or gmpy2 is specified in
47
+ # SYMPY_GROUND_TYPES then warn if gmpy2 is not found. In all cases there is a
48
+ # fallback based on pure Python int and PythonMPQ that should still work fine.
49
+ #
50
+ if GROUND_TYPES in ('auto', 'gmpy', 'gmpy2'):
51
+
52
+ # Actually import gmpy2
53
+ gmpy = import_module('gmpy2', min_module_version='2.0.0',
54
+ module_version_attr='version', module_version_attr_call_args=())
55
+
56
+ # Warn if user explicitly asked for gmpy but it isn't available.
57
+ if gmpy is None and GROUND_TYPES in ('gmpy', 'gmpy2'):
58
+ from warnings import warn
59
+ warn("gmpy library is not installed, switching to 'python' ground types")
60
+
61
+ elif GROUND_TYPES == 'python':
62
+
63
+ # The user asked for Python so ignore gmpy2 module.
64
+ gmpy = None
65
+
66
+ else:
67
+
68
+ # Invalid value for SYMPY_GROUND_TYPES. Ignore the gmpy2 module.
69
+ from warnings import warn
70
+ warn("SYMPY_GROUND_TYPES environment variable unrecognised. "
71
+ "Should be 'python', 'auto', 'gmpy', or 'gmpy2'")
72
+ gmpy = None
73
+
74
+
75
+ #
76
+ # At this point gmpy will be None if gmpy2 was not successfully imported or if
77
+ # the environment variable SYMPY_GROUND_TYPES was set to 'python' (or some
78
+ # unrecognised value). The two blocks below define the values exported by this
79
+ # module in each case.
80
+ #
81
+ SYMPY_INTS: tTuple[Type, ...]
82
+
83
+ if gmpy is not None:
84
+
85
+ HAS_GMPY = 2
86
+ GROUND_TYPES = 'gmpy'
87
+ SYMPY_INTS = (int, type(gmpy.mpz(0)))
88
+ MPZ = gmpy.mpz
89
+ MPQ = gmpy.mpq
90
+
91
+ factorial = gmpy.fac
92
+ sqrt = gmpy.isqrt
93
+
94
+ else:
95
+ from .pythonmpq import PythonMPQ
96
+
97
+ HAS_GMPY = 0
98
+ GROUND_TYPES = 'python'
99
+ SYMPY_INTS = (int,)
100
+ MPZ = int
101
+ MPQ = PythonMPQ
102
+
103
+ factorial = lambda x: int(mlib.ifac(x))
104
+ sqrt = lambda x: int(mlib.isqrt(x))
venv/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
venv/lib/python3.10/site-packages/sympy/external/pythonmpq.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
venv/lib/python3.10/site-packages/sympy/external/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_autowrap.cpython-310.pyc ADDED
Binary file (9.06 kB). View file
 
venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc ADDED
Binary file (9.63 kB). View file
 
venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_pythonmpq.cpython-310.pyc ADDED
Binary file (6.13 kB). View file
 
venv/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc ADDED
Binary file (1.05 kB). View file
 
venv/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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')
venv/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
venv/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')
venv/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
200
+ from numpy import array
201
+ return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
202
+ matarr = matarray()
203
+ assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
204
+
205
+
206
+ def test_matrix2numpy():
207
+ a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]]))
208
+ assert isinstance(a, ndarray)
209
+ assert a.shape == (2, 2)
210
+ assert a[0, 0] == 1
211
+ assert a[0, 1] == x**2
212
+ assert a[1, 0] == 3*sin(x)
213
+ assert a[1, 1] == 0
214
+
215
+
216
+ def test_matrix2numpy_conversion():
217
+ a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
218
+ b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
219
+ assert (matrix2numpy(a) == b).all()
220
+ assert matrix2numpy(a).dtype == numpy.dtype('object')
221
+
222
+ c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
223
+ d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
224
+ assert c.dtype == numpy.dtype('int8')
225
+ assert d.dtype == numpy.dtype('float64')
226
+
227
+
228
+ def test_issue_3728():
229
+ assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all()
230
+ assert (Rational(1, 2) + array(
231
+ [2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all()
232
+ assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all()
233
+ assert (Float("0.5") + array(
234
+ [2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all()
235
+
236
+
237
+ @conserve_mpmath_dps
238
+ def test_lambdify():
239
+ mpmath.mp.dps = 16
240
+ sin02 = mpmath.mpf("0.198669330795061215459412627")
241
+ f = lambdify(x, sin(x), "numpy")
242
+ prec = 1e-15
243
+ assert -prec < f(0.2) - sin02 < prec
244
+
245
+ # if this succeeds, it can't be a numpy function
246
+
247
+ if version_tuple(numpy.__version__) >= version_tuple('1.17'):
248
+ with raises(TypeError):
249
+ f(x)
250
+ else:
251
+ with raises(AttributeError):
252
+ f(x)
253
+
254
+
255
+ def test_lambdify_matrix():
256
+ f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"])
257
+ assert (f(1) == array([[1, 2], [1, 2]])).all()
258
+
259
+
260
+ def test_lambdify_matrix_multi_input():
261
+ M = sympy.Matrix([[x**2, x*y, x*z],
262
+ [y*x, y**2, y*z],
263
+ [z*x, z*y, z**2]])
264
+ f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"])
265
+
266
+ xh, yh, zh = 1.0, 2.0, 3.0
267
+ expected = array([[xh**2, xh*yh, xh*zh],
268
+ [yh*xh, yh**2, yh*zh],
269
+ [zh*xh, zh*yh, zh**2]])
270
+ actual = f(xh, yh, zh)
271
+ assert numpy.allclose(actual, expected)
272
+
273
+
274
+ def test_lambdify_matrix_vec_input():
275
+ X = sympy.DeferredVector('X')
276
+ M = Matrix([
277
+ [X[0]**2, X[0]*X[1], X[0]*X[2]],
278
+ [X[1]*X[0], X[1]**2, X[1]*X[2]],
279
+ [X[2]*X[0], X[2]*X[1], X[2]**2]])
280
+ f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"])
281
+
282
+ Xh = array([1.0, 2.0, 3.0])
283
+ expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]],
284
+ [Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]],
285
+ [Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]])
286
+ actual = f(Xh)
287
+ assert numpy.allclose(actual, expected)
288
+
289
+
290
+ def test_lambdify_transl():
291
+ from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
292
+ for sym, mat in NUMPY_TRANSLATIONS.items():
293
+ assert sym in sympy.__dict__
294
+ assert mat in numpy.__dict__
295
+
296
+
297
+ def test_symarray():
298
+ """Test creation of numpy arrays of SymPy symbols."""
299
+
300
+ import numpy as np
301
+ import numpy.testing as npt
302
+
303
+ syms = symbols('_0,_1,_2')
304
+ s1 = symarray("", 3)
305
+ s2 = symarray("", 3)
306
+ npt.assert_array_equal(s1, np.array(syms, dtype=object))
307
+ assert s1[0] == s2[0]
308
+
309
+ a = symarray('a', 3)
310
+ b = symarray('b', 3)
311
+ assert not(a[0] == b[0])
312
+
313
+ asyms = symbols('a_0,a_1,a_2')
314
+ npt.assert_array_equal(a, np.array(asyms, dtype=object))
315
+
316
+ # Multidimensional checks
317
+ a2d = symarray('a', (2, 3))
318
+ assert a2d.shape == (2, 3)
319
+ a00, a12 = symbols('a_0_0,a_1_2')
320
+ assert a2d[0, 0] == a00
321
+ assert a2d[1, 2] == a12
322
+
323
+ a3d = symarray('a', (2, 3, 2))
324
+ assert a3d.shape == (2, 3, 2)
325
+ a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
326
+ assert a3d[0, 0, 0] == a000
327
+ assert a3d[1, 2, 0] == a120
328
+ assert a3d[1, 2, 1] == a121
329
+
330
+
331
+ def test_vectorize():
332
+ assert (numpy.vectorize(
333
+ sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
venv/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)
venv/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])
venv/lib/python3.10/site-packages/sympy/logic/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .boolalg import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, Implies,
2
+ Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map, true, false,
3
+ gateinputcount)
4
+ from .inference import satisfiable
5
+
6
+ __all__ = [
7
+ 'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor',
8
+ 'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic',
9
+ 'bool_map', 'true', 'false', 'gateinputcount',
10
+
11
+ 'satisfiable',
12
+ ]
venv/lib/python3.10/site-packages/sympy/logic/boolalg.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/sympy/logic/inference.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference in propositional logic"""
2
+
3
+ from sympy.logic.boolalg import And, Not, conjuncts, to_cnf, BooleanFunction
4
+ from sympy.core.sorting import ordered
5
+ from sympy.core.sympify import sympify
6
+ from sympy.external.importtools import import_module
7
+
8
+
9
+ def literal_symbol(literal):
10
+ """
11
+ The symbol in this literal (without the negation).
12
+
13
+ Examples
14
+ ========
15
+
16
+ >>> from sympy.abc import A
17
+ >>> from sympy.logic.inference import literal_symbol
18
+ >>> literal_symbol(A)
19
+ A
20
+ >>> literal_symbol(~A)
21
+ A
22
+
23
+ """
24
+
25
+ if literal is True or literal is False:
26
+ return literal
27
+ try:
28
+ if literal.is_Symbol:
29
+ return literal
30
+ if literal.is_Not:
31
+ return literal_symbol(literal.args[0])
32
+ else:
33
+ raise ValueError
34
+ except (AttributeError, ValueError):
35
+ raise ValueError("Argument must be a boolean literal.")
36
+
37
+
38
+ def satisfiable(expr, algorithm=None, all_models=False, minimal=False):
39
+ """
40
+ Check satisfiability of a propositional sentence.
41
+ Returns a model when it succeeds.
42
+ Returns {true: true} for trivially true expressions.
43
+
44
+ On setting all_models to True, if given expr is satisfiable then
45
+ returns a generator of models. However, if expr is unsatisfiable
46
+ then returns a generator containing the single element False.
47
+
48
+ Examples
49
+ ========
50
+
51
+ >>> from sympy.abc import A, B
52
+ >>> from sympy.logic.inference import satisfiable
53
+ >>> satisfiable(A & ~B)
54
+ {A: True, B: False}
55
+ >>> satisfiable(A & ~A)
56
+ False
57
+ >>> satisfiable(True)
58
+ {True: True}
59
+ >>> next(satisfiable(A & ~A, all_models=True))
60
+ False
61
+ >>> models = satisfiable((A >> B) & B, all_models=True)
62
+ >>> next(models)
63
+ {A: False, B: True}
64
+ >>> next(models)
65
+ {A: True, B: True}
66
+ >>> def use_models(models):
67
+ ... for model in models:
68
+ ... if model:
69
+ ... # Do something with the model.
70
+ ... print(model)
71
+ ... else:
72
+ ... # Given expr is unsatisfiable.
73
+ ... print("UNSAT")
74
+ >>> use_models(satisfiable(A >> ~A, all_models=True))
75
+ {A: False}
76
+ >>> use_models(satisfiable(A ^ A, all_models=True))
77
+ UNSAT
78
+
79
+ """
80
+ if algorithm is None or algorithm == "pycosat":
81
+ pycosat = import_module('pycosat')
82
+ if pycosat is not None:
83
+ algorithm = "pycosat"
84
+ else:
85
+ if algorithm == "pycosat":
86
+ raise ImportError("pycosat module is not present")
87
+ # Silently fall back to dpll2 if pycosat
88
+ # is not installed
89
+ algorithm = "dpll2"
90
+
91
+ if algorithm=="minisat22":
92
+ pysat = import_module('pysat')
93
+ if pysat is None:
94
+ algorithm = "dpll2"
95
+
96
+ if algorithm == "dpll":
97
+ from sympy.logic.algorithms.dpll import dpll_satisfiable
98
+ return dpll_satisfiable(expr)
99
+ elif algorithm == "dpll2":
100
+ from sympy.logic.algorithms.dpll2 import dpll_satisfiable
101
+ return dpll_satisfiable(expr, all_models)
102
+ elif algorithm == "pycosat":
103
+ from sympy.logic.algorithms.pycosat_wrapper import pycosat_satisfiable
104
+ return pycosat_satisfiable(expr, all_models)
105
+ elif algorithm == "minisat22":
106
+ from sympy.logic.algorithms.minisat22_wrapper import minisat22_satisfiable
107
+ return minisat22_satisfiable(expr, all_models, minimal)
108
+ raise NotImplementedError
109
+
110
+
111
+ def valid(expr):
112
+ """
113
+ Check validity of a propositional sentence.
114
+ A valid propositional sentence is True under every assignment.
115
+
116
+ Examples
117
+ ========
118
+
119
+ >>> from sympy.abc import A, B
120
+ >>> from sympy.logic.inference import valid
121
+ >>> valid(A | ~A)
122
+ True
123
+ >>> valid(A | B)
124
+ False
125
+
126
+ References
127
+ ==========
128
+
129
+ .. [1] https://en.wikipedia.org/wiki/Validity
130
+
131
+ """
132
+ return not satisfiable(Not(expr))
133
+
134
+
135
+ def pl_true(expr, model=None, deep=False):
136
+ """
137
+ Returns whether the given assignment is a model or not.
138
+
139
+ If the assignment does not specify the value for every proposition,
140
+ this may return None to indicate 'not obvious'.
141
+
142
+ Parameters
143
+ ==========
144
+
145
+ model : dict, optional, default: {}
146
+ Mapping of symbols to boolean values to indicate assignment.
147
+ deep: boolean, optional, default: False
148
+ Gives the value of the expression under partial assignments
149
+ correctly. May still return None to indicate 'not obvious'.
150
+
151
+
152
+ Examples
153
+ ========
154
+
155
+ >>> from sympy.abc import A, B
156
+ >>> from sympy.logic.inference import pl_true
157
+ >>> pl_true( A & B, {A: True, B: True})
158
+ True
159
+ >>> pl_true(A & B, {A: False})
160
+ False
161
+ >>> pl_true(A & B, {A: True})
162
+ >>> pl_true(A & B, {A: True}, deep=True)
163
+ >>> pl_true(A >> (B >> A))
164
+ >>> pl_true(A >> (B >> A), deep=True)
165
+ True
166
+ >>> pl_true(A & ~A)
167
+ >>> pl_true(A & ~A, deep=True)
168
+ False
169
+ >>> pl_true(A & B & (~A | ~B), {A: True})
170
+ >>> pl_true(A & B & (~A | ~B), {A: True}, deep=True)
171
+ False
172
+
173
+ """
174
+
175
+ from sympy.core.symbol import Symbol
176
+
177
+ boolean = (True, False)
178
+
179
+ def _validate(expr):
180
+ if isinstance(expr, Symbol) or expr in boolean:
181
+ return True
182
+ if not isinstance(expr, BooleanFunction):
183
+ return False
184
+ return all(_validate(arg) for arg in expr.args)
185
+
186
+ if expr in boolean:
187
+ return expr
188
+ expr = sympify(expr)
189
+ if not _validate(expr):
190
+ raise ValueError("%s is not a valid boolean expression" % expr)
191
+ if not model:
192
+ model = {}
193
+ model = {k: v for k, v in model.items() if v in boolean}
194
+ result = expr.subs(model)
195
+ if result in boolean:
196
+ return bool(result)
197
+ if deep:
198
+ model = {k: True for k in result.atoms()}
199
+ if pl_true(result, model):
200
+ if valid(result):
201
+ return True
202
+ else:
203
+ if not satisfiable(result):
204
+ return False
205
+ return None
206
+
207
+
208
+ def entails(expr, formula_set=None):
209
+ """
210
+ Check whether the given expr_set entail an expr.
211
+ If formula_set is empty then it returns the validity of expr.
212
+
213
+ Examples
214
+ ========
215
+
216
+ >>> from sympy.abc import A, B, C
217
+ >>> from sympy.logic.inference import entails
218
+ >>> entails(A, [A >> B, B >> C])
219
+ False
220
+ >>> entails(C, [A >> B, B >> C, A])
221
+ True
222
+ >>> entails(A >> B)
223
+ False
224
+ >>> entails(A >> (B >> A))
225
+ True
226
+
227
+ References
228
+ ==========
229
+
230
+ .. [1] https://en.wikipedia.org/wiki/Logical_consequence
231
+
232
+ """
233
+ if formula_set:
234
+ formula_set = list(formula_set)
235
+ else:
236
+ formula_set = []
237
+ formula_set.append(Not(expr))
238
+ return not satisfiable(And(*formula_set))
239
+
240
+
241
+ class KB:
242
+ """Base class for all knowledge bases"""
243
+ def __init__(self, sentence=None):
244
+ self.clauses_ = set()
245
+ if sentence:
246
+ self.tell(sentence)
247
+
248
+ def tell(self, sentence):
249
+ raise NotImplementedError
250
+
251
+ def ask(self, query):
252
+ raise NotImplementedError
253
+
254
+ def retract(self, sentence):
255
+ raise NotImplementedError
256
+
257
+ @property
258
+ def clauses(self):
259
+ return list(ordered(self.clauses_))
260
+
261
+
262
+ class PropKB(KB):
263
+ """A KB for Propositional Logic. Inefficient, with no indexing."""
264
+
265
+ def tell(self, sentence):
266
+ """Add the sentence's clauses to the KB
267
+
268
+ Examples
269
+ ========
270
+
271
+ >>> from sympy.logic.inference import PropKB
272
+ >>> from sympy.abc import x, y
273
+ >>> l = PropKB()
274
+ >>> l.clauses
275
+ []
276
+
277
+ >>> l.tell(x | y)
278
+ >>> l.clauses
279
+ [x | y]
280
+
281
+ >>> l.tell(y)
282
+ >>> l.clauses
283
+ [y, x | y]
284
+
285
+ """
286
+ for c in conjuncts(to_cnf(sentence)):
287
+ self.clauses_.add(c)
288
+
289
+ def ask(self, query):
290
+ """Checks if the query is true given the set of clauses.
291
+
292
+ Examples
293
+ ========
294
+
295
+ >>> from sympy.logic.inference import PropKB
296
+ >>> from sympy.abc import x, y
297
+ >>> l = PropKB()
298
+ >>> l.tell(x & ~y)
299
+ >>> l.ask(x)
300
+ True
301
+ >>> l.ask(y)
302
+ False
303
+
304
+ """
305
+ return entails(query, self.clauses_)
306
+
307
+ def retract(self, sentence):
308
+ """Remove the sentence's clauses from the KB
309
+
310
+ Examples
311
+ ========
312
+
313
+ >>> from sympy.logic.inference import PropKB
314
+ >>> from sympy.abc import x, y
315
+ >>> l = PropKB()
316
+ >>> l.clauses
317
+ []
318
+
319
+ >>> l.tell(x | y)
320
+ >>> l.clauses
321
+ [x | y]
322
+
323
+ >>> l.retract(x | y)
324
+ >>> l.clauses
325
+ []
326
+
327
+ """
328
+ for c in conjuncts(to_cnf(sentence)):
329
+ self.clauses_.discard(c)
venv/lib/python3.10/site-packages/sympy/logic/utilities/dimacs.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """For reading in DIMACS file format
2
+
3
+ www.cs.ubc.ca/~hoos/SATLIB/Benchmarks/SAT/satformat.ps
4
+
5
+ """
6
+
7
+ from sympy.core import Symbol
8
+ from sympy.logic.boolalg import And, Or
9
+ import re
10
+
11
+
12
+ def load(s):
13
+ """Loads a boolean expression from a string.
14
+
15
+ Examples
16
+ ========
17
+
18
+ >>> from sympy.logic.utilities.dimacs import load
19
+ >>> load('1')
20
+ cnf_1
21
+ >>> load('1 2')
22
+ cnf_1 | cnf_2
23
+ >>> load('1 \\n 2')
24
+ cnf_1 & cnf_2
25
+ >>> load('1 2 \\n 3')
26
+ cnf_3 & (cnf_1 | cnf_2)
27
+ """
28
+ clauses = []
29
+
30
+ lines = s.split('\n')
31
+
32
+ pComment = re.compile(r'c.*')
33
+ pStats = re.compile(r'p\s*cnf\s*(\d*)\s*(\d*)')
34
+
35
+ while len(lines) > 0:
36
+ line = lines.pop(0)
37
+
38
+ # Only deal with lines that aren't comments
39
+ if not pComment.match(line):
40
+ m = pStats.match(line)
41
+
42
+ if not m:
43
+ nums = line.rstrip('\n').split(' ')
44
+ list = []
45
+ for lit in nums:
46
+ if lit != '':
47
+ if int(lit) == 0:
48
+ continue
49
+ num = abs(int(lit))
50
+ sign = True
51
+ if int(lit) < 0:
52
+ sign = False
53
+
54
+ if sign:
55
+ list.append(Symbol("cnf_%s" % num))
56
+ else:
57
+ list.append(~Symbol("cnf_%s" % num))
58
+
59
+ if len(list) > 0:
60
+ clauses.append(Or(*list))
61
+
62
+ return And(*clauses)
63
+
64
+
65
+ def load_file(location):
66
+ """Loads a boolean expression from a file."""
67
+ with open(location) as f:
68
+ s = f.read()
69
+
70
+ return load(s)
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_aesaracode.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_c.cpython-310.pyc ADDED
Binary file (30.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_codeprinter.cpython-310.pyc ADDED
Binary file (2.07 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_conventions.cpython-310.pyc ADDED
Binary file (3.83 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_cupy.cpython-310.pyc ADDED
Binary file (2.6 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_cxx.cpython-310.pyc ADDED
Binary file (3.38 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_dot.cpython-310.pyc ADDED
Binary file (5.95 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_fortran.cpython-310.pyc ADDED
Binary file (32.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_glsl.cpython-310.pyc ADDED
Binary file (26.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_gtk.cpython-310.pyc ADDED
Binary file (918 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_jax.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_jscode.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_julia.cpython-310.pyc ADDED
Binary file (14.8 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_lambdarepr.cpython-310.pyc ADDED
Binary file (7.14 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_latex.cpython-310.pyc ADDED
Binary file (127 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_llvmjit.cpython-310.pyc ADDED
Binary file (6.72 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_maple.cpython-310.pyc ADDED
Binary file (14.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_mathematica.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_mathml.cpython-310.pyc ADDED
Binary file (81.4 kB). View file