ZTWHHH commited on
Commit
02477ab
·
verified ·
1 Parent(s): e531155

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. .gitattributes +1 -0
  2. wemm/lib/python3.10/site-packages/sympy/external/__init__.py +20 -0
  3. wemm/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc +0 -0
  4. wemm/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc +0 -0
  5. wemm/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc +0 -0
  6. wemm/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc +0 -0
  7. wemm/lib/python3.10/site-packages/sympy/external/gmpy.py +341 -0
  8. wemm/lib/python3.10/site-packages/sympy/external/ntheory.py +637 -0
  9. wemm/lib/python3.10/site-packages/sympy/external/pythonmpq.py +341 -0
  10. wemm/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  11. wemm/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py +379 -0
  12. wemm/lib/python3.10/site-packages/sympy/integrals/__pycache__/rde.cpython-310.pyc +0 -0
  13. wemm/lib/python3.10/site-packages/sympy/integrals/benchmarks/__init__.py +0 -0
  14. wemm/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  15. wemm/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_integrate.cpython-310.pyc +0 -0
  16. wemm/lib/python3.10/site-packages/sympy/interactive/__init__.py +8 -0
  17. wemm/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc +0 -0
  18. wemm/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc +0 -0
  19. wemm/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc +0 -0
  20. wemm/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc +0 -0
  21. wemm/lib/python3.10/site-packages/sympy/interactive/printing.py +562 -0
  22. wemm/lib/python3.10/site-packages/sympy/interactive/session.py +463 -0
  23. wemm/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py +0 -0
  24. wemm/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  25. wemm/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_interactive.cpython-310.pyc +0 -0
  26. wemm/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_ipython.cpython-310.pyc +0 -0
  27. wemm/lib/python3.10/site-packages/sympy/interactive/tests/test_interactive.py +10 -0
  28. wemm/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py +278 -0
  29. wemm/lib/python3.10/site-packages/sympy/interactive/traversal.py +95 -0
  30. wemm/lib/python3.10/site-packages/sympy/physics/__init__.py +12 -0
  31. wemm/lib/python3.10/site-packages/sympy/physics/hydrogen.py +265 -0
  32. wemm/lib/python3.10/site-packages/sympy/physics/matrices.py +176 -0
  33. wemm/lib/python3.10/site-packages/sympy/physics/paulialgebra.py +231 -0
  34. wemm/lib/python3.10/site-packages/sympy/physics/pring.py +94 -0
  35. wemm/lib/python3.10/site-packages/sympy/physics/qho_1d.py +88 -0
  36. wemm/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py +149 -0
  37. wemm/lib/python3.10/site-packages/sympy/physics/quantum/matrixcache.py +103 -0
  38. wemm/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py +413 -0
  39. wemm/lib/python3.10/site-packages/sympy/physics/quantum/state.py +1017 -0
  40. wemm/lib/python3.10/site-packages/sympy/physics/secondquant.py +3114 -0
  41. wemm/lib/python3.10/site-packages/sympy/physics/sho.py +95 -0
  42. wemm/lib/python3.10/site-packages/sympy/physics/units/__init__.py +453 -0
  43. wemm/lib/python3.10/site-packages/sympy/physics/units/__pycache__/dimensions.cpython-310.pyc +0 -0
  44. wemm/lib/python3.10/site-packages/sympy/physics/units/__pycache__/prefixes.cpython-310.pyc +0 -0
  45. wemm/lib/python3.10/site-packages/sympy/physics/units/__pycache__/unitsystem.cpython-310.pyc +0 -0
  46. wemm/lib/python3.10/site-packages/sympy/physics/units/__pycache__/util.cpython-310.pyc +0 -0
  47. wemm/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc +0 -0
  48. wemm/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-310.pyc +0 -0
  49. wemm/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-310.pyc +0 -0
  50. wemm/lib/python3.10/site-packages/sympy/physics/units/definitions/dimension_definitions.py +43 -0
.gitattributes CHANGED
@@ -191,3 +191,4 @@ wemm/lib/python3.10/site-packages/transformers/models/deta/__pycache__/modeling_
191
  wemm/lib/python3.10/site-packages/virtualenv/seed/wheels/embed/setuptools-75.3.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
192
  wemm/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so filter=lfs diff=lfs merge=lfs -text
193
  wemm/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
191
  wemm/lib/python3.10/site-packages/virtualenv/seed/wheels/embed/setuptools-75.3.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
192
  wemm/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so filter=lfs diff=lfs merge=lfs -text
193
  wemm/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
194
+ wemm/lib/python3.10/site-packages/transformers/utils/__pycache__/dummy_pt_objects.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
wemm/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']
wemm/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (758 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc ADDED
Binary file (5.37 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc ADDED
Binary file (5.51 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc ADDED
Binary file (8.79 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/external/gmpy.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
wemm/lib/python3.10/site-packages/sympy/external/ntheory.py ADDED
@@ -0,0 +1,637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
wemm/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)
wemm/lib/python3.10/site-packages/sympy/external/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
wemm/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)
wemm/lib/python3.10/site-packages/sympy/integrals/__pycache__/rde.cpython-310.pyc ADDED
Binary file (20.7 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/integrals/benchmarks/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_integrate.cpython-310.pyc ADDED
Binary file (901 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/interactive/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Helper module for setting up interactive SymPy sessions. """
2
+
3
+ from .printing import init_printing
4
+ from .session import init_session
5
+ from .traversal import interactive_traversal
6
+
7
+
8
+ __all__ = ['init_printing', 'init_session', 'interactive_traversal']
wemm/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (422 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc ADDED
Binary file (17.4 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc ADDED
Binary file (2.42 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/interactive/printing.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for setting up printing in interactive sessions. """
2
+
3
+ from sympy.external.importtools import version_tuple
4
+ from io import BytesIO
5
+
6
+ from sympy.printing.latex import latex as default_latex
7
+ from sympy.printing.preview import preview
8
+ from sympy.utilities.misc import debug
9
+ from sympy.printing.defaults import Printable
10
+
11
+
12
+ def _init_python_printing(stringify_func, **settings):
13
+ """Setup printing in Python interactive session. """
14
+ import sys
15
+ import builtins
16
+
17
+ def _displayhook(arg):
18
+ """Python's pretty-printer display hook.
19
+
20
+ This function was adapted from:
21
+
22
+ https://www.python.org/dev/peps/pep-0217/
23
+
24
+ """
25
+ if arg is not None:
26
+ builtins._ = None
27
+ print(stringify_func(arg, **settings))
28
+ builtins._ = arg
29
+
30
+ sys.displayhook = _displayhook
31
+
32
+
33
+ def _init_ipython_printing(ip, stringify_func, use_latex, euler, forecolor,
34
+ backcolor, fontsize, latex_mode, print_builtin,
35
+ latex_printer, scale, **settings):
36
+ """Setup printing in IPython interactive session. """
37
+ try:
38
+ from IPython.lib.latextools import latex_to_png
39
+ except ImportError:
40
+ pass
41
+
42
+ # Guess best font color if none was given based on the ip.colors string.
43
+ # From the IPython documentation:
44
+ # It has four case-insensitive values: 'nocolor', 'neutral', 'linux',
45
+ # 'lightbg'. The default is neutral, which should be legible on either
46
+ # dark or light terminal backgrounds. linux is optimised for dark
47
+ # backgrounds and lightbg for light ones.
48
+ if forecolor is None:
49
+ color = ip.colors.lower()
50
+ if color == 'lightbg':
51
+ forecolor = 'Black'
52
+ elif color == 'linux':
53
+ forecolor = 'White'
54
+ else:
55
+ # No idea, go with gray.
56
+ forecolor = 'Gray'
57
+ debug("init_printing: Automatic foreground color:", forecolor)
58
+
59
+ if use_latex == "svg":
60
+ extra_preamble = "\n\\special{color %s}" % forecolor
61
+ else:
62
+ extra_preamble = ""
63
+
64
+ imagesize = 'tight'
65
+ offset = "0cm,0cm"
66
+ resolution = round(150*scale)
67
+ dvi = r"-T %s -D %d -bg %s -fg %s -O %s" % (
68
+ imagesize, resolution, backcolor, forecolor, offset)
69
+ dvioptions = dvi.split()
70
+
71
+ svg_scale = 150/72*scale
72
+ dvioptions_svg = ["--no-fonts", "--scale={}".format(svg_scale)]
73
+
74
+ debug("init_printing: DVIOPTIONS:", dvioptions)
75
+ debug("init_printing: DVIOPTIONS_SVG:", dvioptions_svg)
76
+
77
+ latex = latex_printer or default_latex
78
+
79
+ def _print_plain(arg, p, cycle):
80
+ """caller for pretty, for use in IPython 0.11"""
81
+ if _can_print(arg):
82
+ p.text(stringify_func(arg))
83
+ else:
84
+ p.text(IPython.lib.pretty.pretty(arg))
85
+
86
+ def _preview_wrapper(o):
87
+ exprbuffer = BytesIO()
88
+ try:
89
+ preview(o, output='png', viewer='BytesIO', euler=euler,
90
+ outputbuffer=exprbuffer, extra_preamble=extra_preamble,
91
+ dvioptions=dvioptions, fontsize=fontsize)
92
+ except Exception as e:
93
+ # IPython swallows exceptions
94
+ debug("png printing:", "_preview_wrapper exception raised:",
95
+ repr(e))
96
+ raise
97
+ return exprbuffer.getvalue()
98
+
99
+ def _svg_wrapper(o):
100
+ exprbuffer = BytesIO()
101
+ try:
102
+ preview(o, output='svg', viewer='BytesIO', euler=euler,
103
+ outputbuffer=exprbuffer, extra_preamble=extra_preamble,
104
+ dvioptions=dvioptions_svg, fontsize=fontsize)
105
+ except Exception as e:
106
+ # IPython swallows exceptions
107
+ debug("svg printing:", "_preview_wrapper exception raised:",
108
+ repr(e))
109
+ raise
110
+ return exprbuffer.getvalue().decode('utf-8')
111
+
112
+ def _matplotlib_wrapper(o):
113
+ # mathtext can't render some LaTeX commands. For example, it can't
114
+ # render any LaTeX environments such as array or matrix. So here we
115
+ # ensure that if mathtext fails to render, we return None.
116
+ try:
117
+ try:
118
+ return latex_to_png(o, color=forecolor, scale=scale)
119
+ except TypeError: # Old IPython version without color and scale
120
+ return latex_to_png(o)
121
+ except ValueError as e:
122
+ debug('matplotlib exception caught:', repr(e))
123
+ return None
124
+
125
+
126
+ # Hook methods for builtin SymPy printers
127
+ printing_hooks = ('_latex', '_sympystr', '_pretty', '_sympyrepr')
128
+
129
+
130
+ def _can_print(o):
131
+ """Return True if type o can be printed with one of the SymPy printers.
132
+
133
+ If o is a container type, this is True if and only if every element of
134
+ o can be printed in this way.
135
+ """
136
+
137
+ try:
138
+ # If you're adding another type, make sure you add it to printable_types
139
+ # later in this file as well
140
+
141
+ builtin_types = (list, tuple, set, frozenset)
142
+ if isinstance(o, builtin_types):
143
+ # If the object is a custom subclass with a custom str or
144
+ # repr, use that instead.
145
+ if (type(o).__str__ not in (i.__str__ for i in builtin_types) or
146
+ type(o).__repr__ not in (i.__repr__ for i in builtin_types)):
147
+ return False
148
+ return all(_can_print(i) for i in o)
149
+ elif isinstance(o, dict):
150
+ return all(_can_print(i) and _can_print(o[i]) for i in o)
151
+ elif isinstance(o, bool):
152
+ return False
153
+ elif isinstance(o, Printable):
154
+ # types known to SymPy
155
+ return True
156
+ elif any(hasattr(o, hook) for hook in printing_hooks):
157
+ # types which add support themselves
158
+ return True
159
+ elif isinstance(o, (float, int)) and print_builtin:
160
+ return True
161
+ return False
162
+ except RuntimeError:
163
+ return False
164
+ # This is in case maximum recursion depth is reached.
165
+ # Since RecursionError is for versions of Python 3.5+
166
+ # so this is to guard against RecursionError for older versions.
167
+
168
+ def _print_latex_png(o):
169
+ """
170
+ A function that returns a png rendered by an external latex
171
+ distribution, falling back to matplotlib rendering
172
+ """
173
+ if _can_print(o):
174
+ s = latex(o, mode=latex_mode, **settings)
175
+ if latex_mode == 'plain':
176
+ s = '$\\displaystyle %s$' % s
177
+ try:
178
+ return _preview_wrapper(s)
179
+ except RuntimeError as e:
180
+ debug('preview failed with:', repr(e),
181
+ ' Falling back to matplotlib backend')
182
+ if latex_mode != 'inline':
183
+ s = latex(o, mode='inline', **settings)
184
+ return _matplotlib_wrapper(s)
185
+
186
+ def _print_latex_svg(o):
187
+ """
188
+ A function that returns a svg rendered by an external latex
189
+ distribution, no fallback available.
190
+ """
191
+ if _can_print(o):
192
+ s = latex(o, mode=latex_mode, **settings)
193
+ if latex_mode == 'plain':
194
+ s = '$\\displaystyle %s$' % s
195
+ try:
196
+ return _svg_wrapper(s)
197
+ except RuntimeError as e:
198
+ debug('preview failed with:', repr(e),
199
+ ' No fallback available.')
200
+
201
+ def _print_latex_matplotlib(o):
202
+ """
203
+ A function that returns a png rendered by mathtext
204
+ """
205
+ if _can_print(o):
206
+ s = latex(o, mode='inline', **settings)
207
+ return _matplotlib_wrapper(s)
208
+
209
+ def _print_latex_text(o):
210
+ """
211
+ A function to generate the latex representation of SymPy expressions.
212
+ """
213
+ if _can_print(o):
214
+ s = latex(o, mode=latex_mode, **settings)
215
+ if latex_mode == 'plain':
216
+ return '$\\displaystyle %s$' % s
217
+ return s
218
+
219
+ def _result_display(self, arg):
220
+ """IPython's pretty-printer display hook, for use in IPython 0.10
221
+
222
+ This function was adapted from:
223
+
224
+ ipython/IPython/hooks.py:155
225
+
226
+ """
227
+ if self.rc.pprint:
228
+ out = stringify_func(arg)
229
+
230
+ if '\n' in out:
231
+ print()
232
+
233
+ print(out)
234
+ else:
235
+ print(repr(arg))
236
+
237
+ import IPython
238
+ if version_tuple(IPython.__version__) >= version_tuple('0.11'):
239
+
240
+ # Printable is our own type, so we handle it with methods instead of
241
+ # the approach required by builtin types. This allows downstream
242
+ # packages to override the methods in their own subclasses of Printable,
243
+ # which avoids the effects of gh-16002.
244
+ printable_types = [float, tuple, list, set, frozenset, dict, int]
245
+
246
+ plaintext_formatter = ip.display_formatter.formatters['text/plain']
247
+
248
+ # Exception to the rule above: IPython has better dispatching rules
249
+ # for plaintext printing (xref ipython/ipython#8938), and we can't
250
+ # use `_repr_pretty_` without hitting a recursion error in _print_plain.
251
+ for cls in printable_types + [Printable]:
252
+ plaintext_formatter.for_type(cls, _print_plain)
253
+
254
+ svg_formatter = ip.display_formatter.formatters['image/svg+xml']
255
+ if use_latex in ('svg', ):
256
+ debug("init_printing: using svg formatter")
257
+ for cls in printable_types:
258
+ svg_formatter.for_type(cls, _print_latex_svg)
259
+ Printable._repr_svg_ = _print_latex_svg
260
+ else:
261
+ debug("init_printing: not using any svg formatter")
262
+ for cls in printable_types:
263
+ # Better way to set this, but currently does not work in IPython
264
+ #png_formatter.for_type(cls, None)
265
+ if cls in svg_formatter.type_printers:
266
+ svg_formatter.type_printers.pop(cls)
267
+ Printable._repr_svg_ = Printable._repr_disabled
268
+
269
+ png_formatter = ip.display_formatter.formatters['image/png']
270
+ if use_latex in (True, 'png'):
271
+ debug("init_printing: using png formatter")
272
+ for cls in printable_types:
273
+ png_formatter.for_type(cls, _print_latex_png)
274
+ Printable._repr_png_ = _print_latex_png
275
+ elif use_latex == 'matplotlib':
276
+ debug("init_printing: using matplotlib formatter")
277
+ for cls in printable_types:
278
+ png_formatter.for_type(cls, _print_latex_matplotlib)
279
+ Printable._repr_png_ = _print_latex_matplotlib
280
+ else:
281
+ debug("init_printing: not using any png formatter")
282
+ for cls in printable_types:
283
+ # Better way to set this, but currently does not work in IPython
284
+ #png_formatter.for_type(cls, None)
285
+ if cls in png_formatter.type_printers:
286
+ png_formatter.type_printers.pop(cls)
287
+ Printable._repr_png_ = Printable._repr_disabled
288
+
289
+ latex_formatter = ip.display_formatter.formatters['text/latex']
290
+ if use_latex in (True, 'mathjax'):
291
+ debug("init_printing: using mathjax formatter")
292
+ for cls in printable_types:
293
+ latex_formatter.for_type(cls, _print_latex_text)
294
+ Printable._repr_latex_ = _print_latex_text
295
+ else:
296
+ debug("init_printing: not using text/latex formatter")
297
+ for cls in printable_types:
298
+ # Better way to set this, but currently does not work in IPython
299
+ #latex_formatter.for_type(cls, None)
300
+ if cls in latex_formatter.type_printers:
301
+ latex_formatter.type_printers.pop(cls)
302
+ Printable._repr_latex_ = Printable._repr_disabled
303
+
304
+ else:
305
+ ip.set_hook('result_display', _result_display)
306
+
307
+ def _is_ipython(shell):
308
+ """Is a shell instance an IPython shell?"""
309
+ # shortcut, so we don't import IPython if we don't have to
310
+ from sys import modules
311
+ if 'IPython' not in modules:
312
+ return False
313
+ try:
314
+ from IPython.core.interactiveshell import InteractiveShell
315
+ except ImportError:
316
+ # IPython < 0.11
317
+ try:
318
+ from IPython.iplib import InteractiveShell
319
+ except ImportError:
320
+ # Reaching this points means IPython has changed in a backward-incompatible way
321
+ # that we don't know about. Warn?
322
+ return False
323
+ return isinstance(shell, InteractiveShell)
324
+
325
+ # Used by the doctester to override the default for no_global
326
+ NO_GLOBAL = False
327
+
328
+ def init_printing(pretty_print=True, order=None, use_unicode=None,
329
+ use_latex=None, wrap_line=None, num_columns=None,
330
+ no_global=False, ip=None, euler=False, forecolor=None,
331
+ backcolor='Transparent', fontsize='10pt',
332
+ latex_mode='plain', print_builtin=True,
333
+ str_printer=None, pretty_printer=None,
334
+ latex_printer=None, scale=1.0, **settings):
335
+ r"""
336
+ Initializes pretty-printer depending on the environment.
337
+
338
+ Parameters
339
+ ==========
340
+
341
+ pretty_print : bool, default=True
342
+ If ``True``, use :func:`~.pretty_print` to stringify or the provided pretty
343
+ printer; if ``False``, use :func:`~.sstrrepr` to stringify or the provided string
344
+ printer.
345
+ order : string or None, default='lex'
346
+ There are a few different settings for this parameter:
347
+ ``'lex'`` (default), which is lexographic order;
348
+ ``'grlex'``, which is graded lexographic order;
349
+ ``'grevlex'``, which is reversed graded lexographic order;
350
+ ``'old'``, which is used for compatibility reasons and for long expressions;
351
+ ``None``, which sets it to lex.
352
+ use_unicode : bool or None, default=None
353
+ If ``True``, use unicode characters;
354
+ if ``False``, do not use unicode characters;
355
+ if ``None``, make a guess based on the environment.
356
+ use_latex : string, bool, or None, default=None
357
+ If ``True``, use default LaTeX rendering in GUI interfaces (png and
358
+ mathjax);
359
+ if ``False``, do not use LaTeX rendering;
360
+ if ``None``, make a guess based on the environment;
361
+ if ``'png'``, enable LaTeX rendering with an external LaTeX compiler,
362
+ falling back to matplotlib if external compilation fails;
363
+ if ``'matplotlib'``, enable LaTeX rendering with matplotlib;
364
+ if ``'mathjax'``, enable LaTeX text generation, for example MathJax
365
+ rendering in IPython notebook or text rendering in LaTeX documents;
366
+ if ``'svg'``, enable LaTeX rendering with an external latex compiler,
367
+ no fallback
368
+ wrap_line : bool
369
+ If True, lines will wrap at the end; if False, they will not wrap
370
+ but continue as one line. This is only relevant if ``pretty_print`` is
371
+ True.
372
+ num_columns : int or None, default=None
373
+ If ``int``, number of columns before wrapping is set to num_columns; if
374
+ ``None``, number of columns before wrapping is set to terminal width.
375
+ This is only relevant if ``pretty_print`` is ``True``.
376
+ no_global : bool, default=False
377
+ If ``True``, the settings become system wide;
378
+ if ``False``, use just for this console/session.
379
+ ip : An interactive console
380
+ This can either be an instance of IPython,
381
+ or a class that derives from code.InteractiveConsole.
382
+ euler : bool, optional, default=False
383
+ Loads the euler package in the LaTeX preamble for handwritten style
384
+ fonts (https://www.ctan.org/pkg/euler).
385
+ forecolor : string or None, optional, default=None
386
+ DVI setting for foreground color. ``None`` means that either ``'Black'``,
387
+ ``'White'``, or ``'Gray'`` will be selected based on a guess of the IPython
388
+ terminal color setting. See notes.
389
+ backcolor : string, optional, default='Transparent'
390
+ DVI setting for background color. See notes.
391
+ fontsize : string or int, optional, default='10pt'
392
+ A font size to pass to the LaTeX documentclass function in the
393
+ preamble. Note that the options are limited by the documentclass.
394
+ Consider using scale instead.
395
+ latex_mode : string, optional, default='plain'
396
+ The mode used in the LaTeX printer. Can be one of:
397
+ ``{'inline'|'plain'|'equation'|'equation*'}``.
398
+ print_builtin : boolean, optional, default=True
399
+ If ``True`` then floats and integers will be printed. If ``False`` the
400
+ printer will only print SymPy types.
401
+ str_printer : function, optional, default=None
402
+ A custom string printer function. This should mimic
403
+ :func:`~.sstrrepr()`.
404
+ pretty_printer : function, optional, default=None
405
+ A custom pretty printer. This should mimic :func:`~.pretty()`.
406
+ latex_printer : function, optional, default=None
407
+ A custom LaTeX printer. This should mimic :func:`~.latex()`.
408
+ scale : float, optional, default=1.0
409
+ Scale the LaTeX output when using the ``'png'`` or ``'svg'`` backends.
410
+ Useful for high dpi screens.
411
+ settings :
412
+ Any additional settings for the ``latex`` and ``pretty`` commands can
413
+ be used to fine-tune the output.
414
+
415
+ Examples
416
+ ========
417
+
418
+ >>> from sympy.interactive import init_printing
419
+ >>> from sympy import Symbol, sqrt
420
+ >>> from sympy.abc import x, y
421
+ >>> sqrt(5)
422
+ sqrt(5)
423
+ >>> init_printing(pretty_print=True) # doctest: +SKIP
424
+ >>> sqrt(5) # doctest: +SKIP
425
+ ___
426
+ \/ 5
427
+ >>> theta = Symbol('theta') # doctest: +SKIP
428
+ >>> init_printing(use_unicode=True) # doctest: +SKIP
429
+ >>> theta # doctest: +SKIP
430
+ \u03b8
431
+ >>> init_printing(use_unicode=False) # doctest: +SKIP
432
+ >>> theta # doctest: +SKIP
433
+ theta
434
+ >>> init_printing(order='lex') # doctest: +SKIP
435
+ >>> str(y + x + y**2 + x**2) # doctest: +SKIP
436
+ x**2 + x + y**2 + y
437
+ >>> init_printing(order='grlex') # doctest: +SKIP
438
+ >>> str(y + x + y**2 + x**2) # doctest: +SKIP
439
+ x**2 + x + y**2 + y
440
+ >>> init_printing(order='grevlex') # doctest: +SKIP
441
+ >>> str(y * x**2 + x * y**2) # doctest: +SKIP
442
+ x**2*y + x*y**2
443
+ >>> init_printing(order='old') # doctest: +SKIP
444
+ >>> str(x**2 + y**2 + x + y) # doctest: +SKIP
445
+ x**2 + x + y**2 + y
446
+ >>> init_printing(num_columns=10) # doctest: +SKIP
447
+ >>> x**2 + x + y**2 + y # doctest: +SKIP
448
+ x + y +
449
+ x**2 + y**2
450
+
451
+ Notes
452
+ =====
453
+
454
+ The foreground and background colors can be selected when using ``'png'`` or
455
+ ``'svg'`` LaTeX rendering. Note that before the ``init_printing`` command is
456
+ executed, the LaTeX rendering is handled by the IPython console and not SymPy.
457
+
458
+ The colors can be selected among the 68 standard colors known to ``dvips``,
459
+ for a list see [1]_. In addition, the background color can be
460
+ set to ``'Transparent'`` (which is the default value).
461
+
462
+ When using the ``'Auto'`` foreground color, the guess is based on the
463
+ ``colors`` variable in the IPython console, see [2]_. Hence, if
464
+ that variable is set correctly in your IPython console, there is a high
465
+ chance that the output will be readable, although manual settings may be
466
+ needed.
467
+
468
+
469
+ References
470
+ ==========
471
+
472
+ .. [1] https://en.wikibooks.org/wiki/LaTeX/Colors#The_68_standard_colors_known_to_dvips
473
+
474
+ .. [2] https://ipython.readthedocs.io/en/stable/config/details.html#terminal-colors
475
+
476
+ See Also
477
+ ========
478
+
479
+ sympy.printing.latex
480
+ sympy.printing.pretty
481
+
482
+ """
483
+ import sys
484
+ from sympy.printing.printer import Printer
485
+
486
+ if pretty_print:
487
+ if pretty_printer is not None:
488
+ stringify_func = pretty_printer
489
+ else:
490
+ from sympy.printing import pretty as stringify_func
491
+ else:
492
+ if str_printer is not None:
493
+ stringify_func = str_printer
494
+ else:
495
+ from sympy.printing import sstrrepr as stringify_func
496
+
497
+ # Even if ip is not passed, double check that not in IPython shell
498
+ in_ipython = False
499
+ if ip is None:
500
+ try:
501
+ ip = get_ipython()
502
+ except NameError:
503
+ pass
504
+ else:
505
+ in_ipython = (ip is not None)
506
+
507
+ if ip and not in_ipython:
508
+ in_ipython = _is_ipython(ip)
509
+
510
+ if in_ipython and pretty_print:
511
+ try:
512
+ import IPython
513
+ # IPython 1.0 deprecates the frontend module, so we import directly
514
+ # from the terminal module to prevent a deprecation message from being
515
+ # shown.
516
+ if version_tuple(IPython.__version__) >= version_tuple('1.0'):
517
+ from IPython.terminal.interactiveshell import TerminalInteractiveShell
518
+ else:
519
+ from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
520
+ from code import InteractiveConsole
521
+ except ImportError:
522
+ pass
523
+ else:
524
+ # This will be True if we are in the qtconsole or notebook
525
+ if not isinstance(ip, (InteractiveConsole, TerminalInteractiveShell)) \
526
+ and 'ipython-console' not in ''.join(sys.argv):
527
+ if use_unicode is None:
528
+ debug("init_printing: Setting use_unicode to True")
529
+ use_unicode = True
530
+ if use_latex is None:
531
+ debug("init_printing: Setting use_latex to True")
532
+ use_latex = True
533
+
534
+ if not NO_GLOBAL and not no_global:
535
+ Printer.set_global_settings(order=order, use_unicode=use_unicode,
536
+ wrap_line=wrap_line, num_columns=num_columns)
537
+ else:
538
+ _stringify_func = stringify_func
539
+
540
+ if pretty_print:
541
+ stringify_func = lambda expr, **settings: \
542
+ _stringify_func(expr, order=order,
543
+ use_unicode=use_unicode,
544
+ wrap_line=wrap_line,
545
+ num_columns=num_columns,
546
+ **settings)
547
+ else:
548
+ stringify_func = \
549
+ lambda expr, **settings: _stringify_func(
550
+ expr, order=order, **settings)
551
+
552
+ if in_ipython:
553
+ mode_in_settings = settings.pop("mode", None)
554
+ if mode_in_settings:
555
+ debug("init_printing: Mode is not able to be set due to internals"
556
+ "of IPython printing")
557
+ _init_ipython_printing(ip, stringify_func, use_latex, euler,
558
+ forecolor, backcolor, fontsize, latex_mode,
559
+ print_builtin, latex_printer, scale,
560
+ **settings)
561
+ else:
562
+ _init_python_printing(stringify_func, **settings)
wemm/lib/python3.10/site-packages/sympy/interactive/session.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for setting up interactive sessions. """
2
+
3
+ from sympy.external.gmpy import GROUND_TYPES
4
+ from sympy.external.importtools import version_tuple
5
+
6
+ from sympy.interactive.printing import init_printing
7
+
8
+ from sympy.utilities.misc import ARCH
9
+
10
+ preexec_source = """\
11
+ from sympy import *
12
+ x, y, z, t = symbols('x y z t')
13
+ k, m, n = symbols('k m n', integer=True)
14
+ f, g, h = symbols('f g h', cls=Function)
15
+ init_printing()
16
+ """
17
+
18
+ verbose_message = """\
19
+ These commands were executed:
20
+ %(source)s
21
+ Documentation can be found at https://docs.sympy.org/%(version)s
22
+ """
23
+
24
+ no_ipython = """\
25
+ Could not locate IPython. Having IPython installed is greatly recommended.
26
+ See http://ipython.scipy.org for more details. If you use Debian/Ubuntu,
27
+ just install the 'ipython' package and start isympy again.
28
+ """
29
+
30
+
31
+ def _make_message(ipython=True, quiet=False, source=None):
32
+ """Create a banner for an interactive session. """
33
+ from sympy import __version__ as sympy_version
34
+ from sympy import SYMPY_DEBUG
35
+
36
+ import sys
37
+ import os
38
+
39
+ if quiet:
40
+ return ""
41
+
42
+ python_version = "%d.%d.%d" % sys.version_info[:3]
43
+
44
+ if ipython:
45
+ shell_name = "IPython"
46
+ else:
47
+ shell_name = "Python"
48
+
49
+ info = ['ground types: %s' % GROUND_TYPES]
50
+
51
+ cache = os.getenv('SYMPY_USE_CACHE')
52
+
53
+ if cache is not None and cache.lower() == 'no':
54
+ info.append('cache: off')
55
+
56
+ if SYMPY_DEBUG:
57
+ info.append('debugging: on')
58
+
59
+ args = shell_name, sympy_version, python_version, ARCH, ', '.join(info)
60
+ message = "%s console for SymPy %s (Python %s-%s) (%s)\n" % args
61
+
62
+ if source is None:
63
+ source = preexec_source
64
+
65
+ _source = ""
66
+
67
+ for line in source.split('\n')[:-1]:
68
+ if not line:
69
+ _source += '\n'
70
+ else:
71
+ _source += '>>> ' + line + '\n'
72
+
73
+ doc_version = sympy_version
74
+ if 'dev' in doc_version:
75
+ doc_version = "dev"
76
+ else:
77
+ doc_version = "%s/" % doc_version
78
+
79
+ message += '\n' + verbose_message % {'source': _source,
80
+ 'version': doc_version}
81
+
82
+ return message
83
+
84
+
85
+ def int_to_Integer(s):
86
+ """
87
+ Wrap integer literals with Integer.
88
+
89
+ This is based on the decistmt example from
90
+ https://docs.python.org/3/library/tokenize.html.
91
+
92
+ Only integer literals are converted. Float literals are left alone.
93
+
94
+ Examples
95
+ ========
96
+
97
+ >>> from sympy import Integer # noqa: F401
98
+ >>> from sympy.interactive.session import int_to_Integer
99
+ >>> s = '1.2 + 1/2 - 0x12 + a1'
100
+ >>> int_to_Integer(s)
101
+ '1.2 +Integer (1 )/Integer (2 )-Integer (0x12 )+a1 '
102
+ >>> s = 'print (1/2)'
103
+ >>> int_to_Integer(s)
104
+ 'print (Integer (1 )/Integer (2 ))'
105
+ >>> exec(s)
106
+ 0.5
107
+ >>> exec(int_to_Integer(s))
108
+ 1/2
109
+ """
110
+ from tokenize import generate_tokens, untokenize, NUMBER, NAME, OP
111
+ from io import StringIO
112
+
113
+ def _is_int(num):
114
+ """
115
+ Returns true if string value num (with token NUMBER) represents an integer.
116
+ """
117
+ # XXX: Is there something in the standard library that will do this?
118
+ if '.' in num or 'j' in num.lower() or 'e' in num.lower():
119
+ return False
120
+ return True
121
+
122
+ result = []
123
+ g = generate_tokens(StringIO(s).readline) # tokenize the string
124
+ for toknum, tokval, _, _, _ in g:
125
+ if toknum == NUMBER and _is_int(tokval): # replace NUMBER tokens
126
+ result.extend([
127
+ (NAME, 'Integer'),
128
+ (OP, '('),
129
+ (NUMBER, tokval),
130
+ (OP, ')')
131
+ ])
132
+ else:
133
+ result.append((toknum, tokval))
134
+ return untokenize(result)
135
+
136
+
137
+ def enable_automatic_int_sympification(shell):
138
+ """
139
+ Allow IPython to automatically convert integer literals to Integer.
140
+ """
141
+ import ast
142
+ old_run_cell = shell.run_cell
143
+
144
+ def my_run_cell(cell, *args, **kwargs):
145
+ try:
146
+ # Check the cell for syntax errors. This way, the syntax error
147
+ # will show the original input, not the transformed input. The
148
+ # downside here is that IPython magic like %timeit will not work
149
+ # with transformed input (but on the other hand, IPython magic
150
+ # that doesn't expect transformed input will continue to work).
151
+ ast.parse(cell)
152
+ except SyntaxError:
153
+ pass
154
+ else:
155
+ cell = int_to_Integer(cell)
156
+ return old_run_cell(cell, *args, **kwargs)
157
+
158
+ shell.run_cell = my_run_cell
159
+
160
+
161
+ def enable_automatic_symbols(shell):
162
+ """Allow IPython to automatically create symbols (``isympy -a``). """
163
+ # XXX: This should perhaps use tokenize, like int_to_Integer() above.
164
+ # This would avoid re-executing the code, which can lead to subtle
165
+ # issues. For example:
166
+ #
167
+ # In [1]: a = 1
168
+ #
169
+ # In [2]: for i in range(10):
170
+ # ...: a += 1
171
+ # ...:
172
+ #
173
+ # In [3]: a
174
+ # Out[3]: 11
175
+ #
176
+ # In [4]: a = 1
177
+ #
178
+ # In [5]: for i in range(10):
179
+ # ...: a += 1
180
+ # ...: print b
181
+ # ...:
182
+ # b
183
+ # b
184
+ # b
185
+ # b
186
+ # b
187
+ # b
188
+ # b
189
+ # b
190
+ # b
191
+ # b
192
+ #
193
+ # In [6]: a
194
+ # Out[6]: 12
195
+ #
196
+ # Note how the for loop is executed again because `b` was not defined, but `a`
197
+ # was already incremented once, so the result is that it is incremented
198
+ # multiple times.
199
+
200
+ import re
201
+ re_nameerror = re.compile(
202
+ "name '(?P<symbol>[A-Za-z_][A-Za-z0-9_]*)' is not defined")
203
+
204
+ def _handler(self, etype, value, tb, tb_offset=None):
205
+ """Handle :exc:`NameError` exception and allow injection of missing symbols. """
206
+ if etype is NameError and tb.tb_next and not tb.tb_next.tb_next:
207
+ match = re_nameerror.match(str(value))
208
+
209
+ if match is not None:
210
+ # XXX: Make sure Symbol is in scope. Otherwise you'll get infinite recursion.
211
+ self.run_cell("%(symbol)s = Symbol('%(symbol)s')" %
212
+ {'symbol': match.group("symbol")}, store_history=False)
213
+
214
+ try:
215
+ code = self.user_ns['In'][-1]
216
+ except (KeyError, IndexError):
217
+ pass
218
+ else:
219
+ self.run_cell(code, store_history=False)
220
+ return None
221
+ finally:
222
+ self.run_cell("del %s" % match.group("symbol"),
223
+ store_history=False)
224
+
225
+ stb = self.InteractiveTB.structured_traceback(
226
+ etype, value, tb, tb_offset=tb_offset)
227
+ self._showtraceback(etype, value, stb)
228
+
229
+ shell.set_custom_exc((NameError,), _handler)
230
+
231
+
232
+ def init_ipython_session(shell=None, argv=[], auto_symbols=False, auto_int_to_Integer=False):
233
+ """Construct new IPython session. """
234
+ import IPython
235
+
236
+ if version_tuple(IPython.__version__) >= version_tuple('0.11'):
237
+ if not shell:
238
+ # use an app to parse the command line, and init config
239
+ # IPython 1.0 deprecates the frontend module, so we import directly
240
+ # from the terminal module to prevent a deprecation message from being
241
+ # shown.
242
+ if version_tuple(IPython.__version__) >= version_tuple('1.0'):
243
+ from IPython.terminal import ipapp
244
+ else:
245
+ from IPython.frontend.terminal import ipapp
246
+ app = ipapp.TerminalIPythonApp()
247
+
248
+ # don't draw IPython banner during initialization:
249
+ app.display_banner = False
250
+ app.initialize(argv)
251
+
252
+ shell = app.shell
253
+
254
+ if auto_symbols:
255
+ enable_automatic_symbols(shell)
256
+ if auto_int_to_Integer:
257
+ enable_automatic_int_sympification(shell)
258
+
259
+ return shell
260
+ else:
261
+ from IPython.Shell import make_IPython
262
+ return make_IPython(argv)
263
+
264
+
265
+ def init_python_session():
266
+ """Construct new Python session. """
267
+ from code import InteractiveConsole
268
+
269
+ class SymPyConsole(InteractiveConsole):
270
+ """An interactive console with readline support. """
271
+
272
+ def __init__(self):
273
+ ns_locals = {}
274
+ InteractiveConsole.__init__(self, locals=ns_locals)
275
+ try:
276
+ import rlcompleter
277
+ import readline
278
+ except ImportError:
279
+ pass
280
+ else:
281
+ import os
282
+ import atexit
283
+
284
+ readline.set_completer(rlcompleter.Completer(ns_locals).complete)
285
+ readline.parse_and_bind('tab: complete')
286
+
287
+ if hasattr(readline, 'read_history_file'):
288
+ history = os.path.expanduser('~/.sympy-history')
289
+
290
+ try:
291
+ readline.read_history_file(history)
292
+ except OSError:
293
+ pass
294
+
295
+ atexit.register(readline.write_history_file, history)
296
+
297
+ return SymPyConsole()
298
+
299
+
300
+ def init_session(ipython=None, pretty_print=True, order=None,
301
+ use_unicode=None, use_latex=None, quiet=False, auto_symbols=False,
302
+ auto_int_to_Integer=False, str_printer=None, pretty_printer=None,
303
+ latex_printer=None, argv=[]):
304
+ """
305
+ Initialize an embedded IPython or Python session. The IPython session is
306
+ initiated with the --pylab option, without the numpy imports, so that
307
+ matplotlib plotting can be interactive.
308
+
309
+ Parameters
310
+ ==========
311
+
312
+ pretty_print: boolean
313
+ If True, use pretty_print to stringify;
314
+ if False, use sstrrepr to stringify.
315
+ order: string or None
316
+ There are a few different settings for this parameter:
317
+ lex (default), which is lexographic order;
318
+ grlex, which is graded lexographic order;
319
+ grevlex, which is reversed graded lexographic order;
320
+ old, which is used for compatibility reasons and for long expressions;
321
+ None, which sets it to lex.
322
+ use_unicode: boolean or None
323
+ If True, use unicode characters;
324
+ if False, do not use unicode characters.
325
+ use_latex: boolean or None
326
+ If True, use latex rendering if IPython GUI's;
327
+ if False, do not use latex rendering.
328
+ quiet: boolean
329
+ If True, init_session will not print messages regarding its status;
330
+ if False, init_session will print messages regarding its status.
331
+ auto_symbols: boolean
332
+ If True, IPython will automatically create symbols for you.
333
+ If False, it will not.
334
+ The default is False.
335
+ auto_int_to_Integer: boolean
336
+ If True, IPython will automatically wrap int literals with Integer, so
337
+ that things like 1/2 give Rational(1, 2).
338
+ If False, it will not.
339
+ The default is False.
340
+ ipython: boolean or None
341
+ If True, printing will initialize for an IPython console;
342
+ if False, printing will initialize for a normal console;
343
+ The default is None, which automatically determines whether we are in
344
+ an ipython instance or not.
345
+ str_printer: function, optional, default=None
346
+ A custom string printer function. This should mimic
347
+ sympy.printing.sstrrepr().
348
+ pretty_printer: function, optional, default=None
349
+ A custom pretty printer. This should mimic sympy.printing.pretty().
350
+ latex_printer: function, optional, default=None
351
+ A custom LaTeX printer. This should mimic sympy.printing.latex()
352
+ This should mimic sympy.printing.latex().
353
+ argv: list of arguments for IPython
354
+ See sympy.bin.isympy for options that can be used to initialize IPython.
355
+
356
+ See Also
357
+ ========
358
+
359
+ sympy.interactive.printing.init_printing: for examples and the rest of the parameters.
360
+
361
+
362
+ Examples
363
+ ========
364
+
365
+ >>> from sympy import init_session, Symbol, sin, sqrt
366
+ >>> sin(x) #doctest: +SKIP
367
+ NameError: name 'x' is not defined
368
+ >>> init_session() #doctest: +SKIP
369
+ >>> sin(x) #doctest: +SKIP
370
+ sin(x)
371
+ >>> sqrt(5) #doctest: +SKIP
372
+ ___
373
+ \\/ 5
374
+ >>> init_session(pretty_print=False) #doctest: +SKIP
375
+ >>> sqrt(5) #doctest: +SKIP
376
+ sqrt(5)
377
+ >>> y + x + y**2 + x**2 #doctest: +SKIP
378
+ x**2 + x + y**2 + y
379
+ >>> init_session(order='grlex') #doctest: +SKIP
380
+ >>> y + x + y**2 + x**2 #doctest: +SKIP
381
+ x**2 + y**2 + x + y
382
+ >>> init_session(order='grevlex') #doctest: +SKIP
383
+ >>> y * x**2 + x * y**2 #doctest: +SKIP
384
+ x**2*y + x*y**2
385
+ >>> init_session(order='old') #doctest: +SKIP
386
+ >>> x**2 + y**2 + x + y #doctest: +SKIP
387
+ x + y + x**2 + y**2
388
+ >>> theta = Symbol('theta') #doctest: +SKIP
389
+ >>> theta #doctest: +SKIP
390
+ theta
391
+ >>> init_session(use_unicode=True) #doctest: +SKIP
392
+ >>> theta # doctest: +SKIP
393
+ \u03b8
394
+ """
395
+ import sys
396
+
397
+ in_ipython = False
398
+
399
+ if ipython is not False:
400
+ try:
401
+ import IPython
402
+ except ImportError:
403
+ if ipython is True:
404
+ raise RuntimeError("IPython is not available on this system")
405
+ ip = None
406
+ else:
407
+ try:
408
+ from IPython import get_ipython
409
+ ip = get_ipython()
410
+ except ImportError:
411
+ ip = None
412
+ in_ipython = bool(ip)
413
+ if ipython is None:
414
+ ipython = in_ipython
415
+
416
+ if ipython is False:
417
+ ip = init_python_session()
418
+ mainloop = ip.interact
419
+ else:
420
+ ip = init_ipython_session(ip, argv=argv, auto_symbols=auto_symbols,
421
+ auto_int_to_Integer=auto_int_to_Integer)
422
+
423
+ if version_tuple(IPython.__version__) >= version_tuple('0.11'):
424
+ # runsource is gone, use run_cell instead, which doesn't
425
+ # take a symbol arg. The second arg is `store_history`,
426
+ # and False means don't add the line to IPython's history.
427
+ ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
428
+
429
+ # Enable interactive plotting using pylab.
430
+ try:
431
+ ip.enable_pylab(import_all=False)
432
+ except Exception:
433
+ # Causes an import error if matplotlib is not installed.
434
+ # Causes other errors (depending on the backend) if there
435
+ # is no display, or if there is some problem in the
436
+ # backend, so we have a bare "except Exception" here
437
+ pass
438
+ if not in_ipython:
439
+ mainloop = ip.mainloop
440
+
441
+ if auto_symbols and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')):
442
+ raise RuntimeError("automatic construction of symbols is possible only in IPython 0.11 or above")
443
+ if auto_int_to_Integer and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')):
444
+ raise RuntimeError("automatic int to Integer transformation is possible only in IPython 0.11 or above")
445
+
446
+ _preexec_source = preexec_source
447
+
448
+ ip.runsource(_preexec_source, symbol='exec')
449
+ init_printing(pretty_print=pretty_print, order=order,
450
+ use_unicode=use_unicode, use_latex=use_latex, ip=ip,
451
+ str_printer=str_printer, pretty_printer=pretty_printer,
452
+ latex_printer=latex_printer)
453
+
454
+ message = _make_message(ipython, quiet, _preexec_source)
455
+
456
+ if not in_ipython:
457
+ print(message)
458
+ mainloop()
459
+ sys.exit('Exiting ...')
460
+ else:
461
+ print(message)
462
+ import atexit
463
+ atexit.register(lambda: print("Exiting ...\n"))
wemm/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (173 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_interactive.cpython-310.pyc ADDED
Binary file (682 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_ipython.cpython-310.pyc ADDED
Binary file (6.64 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/interactive/tests/test_interactive.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.interactive.session import int_to_Integer
2
+
3
+
4
+ def test_int_to_Integer():
5
+ assert int_to_Integer("1 + 2.2 + 0x3 + 40") == \
6
+ 'Integer (1 )+2.2 +Integer (0x3 )+Integer (40 )'
7
+ assert int_to_Integer("0b101") == 'Integer (0b101 )'
8
+ assert int_to_Integer("ab1 + 1 + '1 + 2'") == "ab1 +Integer (1 )+'1 + 2'"
9
+ assert int_to_Integer("(2 + \n3)") == '(Integer (2 )+\nInteger (3 ))'
10
+ assert int_to_Integer("2 + 2.0 + 2j + 2e-10") == 'Integer (2 )+2.0 +2j +2e-10 '
wemm/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests of tools for setting up interactive IPython sessions. """
2
+
3
+ from sympy.interactive.session import (init_ipython_session,
4
+ enable_automatic_symbols, enable_automatic_int_sympification)
5
+
6
+ from sympy.core import Symbol, Rational, Integer
7
+ from sympy.external import import_module
8
+ from sympy.testing.pytest import raises
9
+
10
+ # TODO: The code below could be made more granular with something like:
11
+ #
12
+ # @requires('IPython', version=">=0.11")
13
+ # def test_automatic_symbols(ipython):
14
+
15
+ ipython = import_module("IPython", min_module_version="0.11")
16
+
17
+ if not ipython:
18
+ #bin/test will not execute any tests now
19
+ disabled = True
20
+
21
+ # WARNING: These tests will modify the existing IPython environment. IPython
22
+ # uses a single instance for its interpreter, so there is no way to isolate
23
+ # the test from another IPython session. It also means that if this test is
24
+ # run twice in the same Python session it will fail. This isn't usually a
25
+ # problem because the test suite is run in a subprocess by default, but if the
26
+ # tests are run with subprocess=False it can pollute the current IPython
27
+ # session. See the discussion in issue #15149.
28
+
29
+ def test_automatic_symbols():
30
+ # NOTE: Because of the way the hook works, you have to use run_cell(code,
31
+ # True). This means that the code must have no Out, or it will be printed
32
+ # during the tests.
33
+ app = init_ipython_session()
34
+ app.run_cell("from sympy import *")
35
+
36
+ enable_automatic_symbols(app)
37
+
38
+ symbol = "verylongsymbolname"
39
+ assert symbol not in app.user_ns
40
+ app.run_cell("a = %s" % symbol, True)
41
+ assert symbol not in app.user_ns
42
+ app.run_cell("a = type(%s)" % symbol, True)
43
+ assert app.user_ns['a'] == Symbol
44
+ app.run_cell("%s = Symbol('%s')" % (symbol, symbol), True)
45
+ assert symbol in app.user_ns
46
+
47
+ # Check that built-in names aren't overridden
48
+ app.run_cell("a = all == __builtin__.all", True)
49
+ assert "all" not in app.user_ns
50
+ assert app.user_ns['a'] is True
51
+
52
+ # Check that SymPy names aren't overridden
53
+ app.run_cell("import sympy")
54
+ app.run_cell("a = factorial == sympy.factorial", True)
55
+ assert app.user_ns['a'] is True
56
+
57
+
58
+ def test_int_to_Integer():
59
+ # XXX: Warning, don't test with == here. 0.5 == Rational(1, 2) is True!
60
+ app = init_ipython_session()
61
+ app.run_cell("from sympy import Integer")
62
+ app.run_cell("a = 1")
63
+ assert isinstance(app.user_ns['a'], int)
64
+
65
+ enable_automatic_int_sympification(app)
66
+ app.run_cell("a = 1/2")
67
+ assert isinstance(app.user_ns['a'], Rational)
68
+ app.run_cell("a = 1")
69
+ assert isinstance(app.user_ns['a'], Integer)
70
+ app.run_cell("a = int(1)")
71
+ assert isinstance(app.user_ns['a'], int)
72
+ app.run_cell("a = (1/\n2)")
73
+ assert app.user_ns['a'] == Rational(1, 2)
74
+ # TODO: How can we test that the output of a SyntaxError is the original
75
+ # input, not the transformed input?
76
+
77
+
78
+ def test_ipythonprinting():
79
+ # Initialize and setup IPython session
80
+ app = init_ipython_session()
81
+ app.run_cell("ip = get_ipython()")
82
+ app.run_cell("inst = ip.instance()")
83
+ app.run_cell("format = inst.display_formatter.format")
84
+ app.run_cell("from sympy import Symbol")
85
+
86
+ # Printing without printing extension
87
+ app.run_cell("a = format(Symbol('pi'))")
88
+ app.run_cell("a2 = format(Symbol('pi')**2)")
89
+ # Deal with API change starting at IPython 1.0
90
+ if int(ipython.__version__.split(".")[0]) < 1:
91
+ assert app.user_ns['a']['text/plain'] == "pi"
92
+ assert app.user_ns['a2']['text/plain'] == "pi**2"
93
+ else:
94
+ assert app.user_ns['a'][0]['text/plain'] == "pi"
95
+ assert app.user_ns['a2'][0]['text/plain'] == "pi**2"
96
+
97
+ # Load printing extension
98
+ app.run_cell("from sympy import init_printing")
99
+ app.run_cell("init_printing()")
100
+ # Printing with printing extension
101
+ app.run_cell("a = format(Symbol('pi'))")
102
+ app.run_cell("a2 = format(Symbol('pi')**2)")
103
+ # Deal with API change starting at IPython 1.0
104
+ if int(ipython.__version__.split(".")[0]) < 1:
105
+ assert app.user_ns['a']['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
106
+ assert app.user_ns['a2']['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ')
107
+ else:
108
+ assert app.user_ns['a'][0]['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
109
+ assert app.user_ns['a2'][0]['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ')
110
+
111
+
112
+ def test_print_builtin_option():
113
+ # Initialize and setup IPython session
114
+ app = init_ipython_session()
115
+ app.run_cell("ip = get_ipython()")
116
+ app.run_cell("inst = ip.instance()")
117
+ app.run_cell("format = inst.display_formatter.format")
118
+ app.run_cell("from sympy import Symbol")
119
+ app.run_cell("from sympy import init_printing")
120
+
121
+ app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
122
+ # Deal with API change starting at IPython 1.0
123
+ if int(ipython.__version__.split(".")[0]) < 1:
124
+ text = app.user_ns['a']['text/plain']
125
+ raises(KeyError, lambda: app.user_ns['a']['text/latex'])
126
+ else:
127
+ text = app.user_ns['a'][0]['text/plain']
128
+ raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
129
+ # XXX: How can we make this ignore the terminal width? This test fails if
130
+ # the terminal is too narrow.
131
+ assert text in ("{pi: 3.14, n_i: 3}",
132
+ '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
133
+ "{n_i: 3, pi: 3.14}",
134
+ '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
135
+
136
+ # If we enable the default printing, then the dictionary's should render
137
+ # as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
138
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
139
+ app.run_cell("init_printing(use_latex=True)")
140
+ app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
141
+ # Deal with API change starting at IPython 1.0
142
+ if int(ipython.__version__.split(".")[0]) < 1:
143
+ text = app.user_ns['a']['text/plain']
144
+ latex = app.user_ns['a']['text/latex']
145
+ else:
146
+ text = app.user_ns['a'][0]['text/plain']
147
+ latex = app.user_ns['a'][0]['text/latex']
148
+ assert text in ("{pi: 3.14, n_i: 3}",
149
+ '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
150
+ "{n_i: 3, pi: 3.14}",
151
+ '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
152
+ assert latex == r'$\displaystyle \left\{ n_{i} : 3, \ \pi : 3.14\right\}$'
153
+
154
+ # Objects with an _latex overload should also be handled by our tuple
155
+ # printer.
156
+ app.run_cell("""\
157
+ class WithOverload:
158
+ def _latex(self, printer):
159
+ return r"\\LaTeX"
160
+ """)
161
+ app.run_cell("a = format((WithOverload(),))")
162
+ # Deal with API change starting at IPython 1.0
163
+ if int(ipython.__version__.split(".")[0]) < 1:
164
+ latex = app.user_ns['a']['text/latex']
165
+ else:
166
+ latex = app.user_ns['a'][0]['text/latex']
167
+ assert latex == r'$\displaystyle \left( \LaTeX,\right)$'
168
+
169
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
170
+ app.run_cell("init_printing(use_latex=True, print_builtin=False)")
171
+ app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
172
+ # Deal with API change starting at IPython 1.0
173
+ if int(ipython.__version__.split(".")[0]) < 1:
174
+ text = app.user_ns['a']['text/plain']
175
+ raises(KeyError, lambda: app.user_ns['a']['text/latex'])
176
+ else:
177
+ text = app.user_ns['a'][0]['text/plain']
178
+ raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
179
+ # Note : In Python 3 we have one text type: str which holds Unicode data
180
+ # and two byte types bytes and bytearray.
181
+ # Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}'
182
+ # Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}'
183
+ assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}")
184
+
185
+
186
+ def test_builtin_containers():
187
+ # Initialize and setup IPython session
188
+ app = init_ipython_session()
189
+ app.run_cell("ip = get_ipython()")
190
+ app.run_cell("inst = ip.instance()")
191
+ app.run_cell("format = inst.display_formatter.format")
192
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
193
+ app.run_cell("from sympy import init_printing, Matrix")
194
+ app.run_cell('init_printing(use_latex=True, use_unicode=False)')
195
+
196
+ # Make sure containers that shouldn't pretty print don't.
197
+ app.run_cell('a = format((True, False))')
198
+ app.run_cell('import sys')
199
+ app.run_cell('b = format(sys.flags)')
200
+ app.run_cell('c = format((Matrix([1, 2]),))')
201
+ # Deal with API change starting at IPython 1.0
202
+ if int(ipython.__version__.split(".")[0]) < 1:
203
+ assert app.user_ns['a']['text/plain'] == '(True, False)'
204
+ assert 'text/latex' not in app.user_ns['a']
205
+ assert app.user_ns['b']['text/plain'][:10] == 'sys.flags('
206
+ assert 'text/latex' not in app.user_ns['b']
207
+ assert app.user_ns['c']['text/plain'] == \
208
+ """\
209
+ [1] \n\
210
+ ([ ],)
211
+ [2] \
212
+ """
213
+ assert app.user_ns['c']['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
214
+ else:
215
+ assert app.user_ns['a'][0]['text/plain'] == '(True, False)'
216
+ assert 'text/latex' not in app.user_ns['a'][0]
217
+ assert app.user_ns['b'][0]['text/plain'][:10] == 'sys.flags('
218
+ assert 'text/latex' not in app.user_ns['b'][0]
219
+ assert app.user_ns['c'][0]['text/plain'] == \
220
+ """\
221
+ [1] \n\
222
+ ([ ],)
223
+ [2] \
224
+ """
225
+ assert app.user_ns['c'][0]['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
226
+
227
+ def test_matplotlib_bad_latex():
228
+ # Initialize and setup IPython session
229
+ app = init_ipython_session()
230
+ app.run_cell("import IPython")
231
+ app.run_cell("ip = get_ipython()")
232
+ app.run_cell("inst = ip.instance()")
233
+ app.run_cell("format = inst.display_formatter.format")
234
+ app.run_cell("from sympy import init_printing, Matrix")
235
+ app.run_cell("init_printing(use_latex='matplotlib')")
236
+
237
+ # The png formatter is not enabled by default in this context
238
+ app.run_cell("inst.display_formatter.formatters['image/png'].enabled = True")
239
+
240
+ # Make sure no warnings are raised by IPython
241
+ app.run_cell("import warnings")
242
+ # IPython.core.formatters.FormatterWarning was introduced in IPython 2.0
243
+ if int(ipython.__version__.split(".")[0]) < 2:
244
+ app.run_cell("warnings.simplefilter('error')")
245
+ else:
246
+ app.run_cell("warnings.simplefilter('error', IPython.core.formatters.FormatterWarning)")
247
+
248
+ # This should not raise an exception
249
+ app.run_cell("a = format(Matrix([1, 2, 3]))")
250
+
251
+ # issue 9799
252
+ app.run_cell("from sympy import Piecewise, Symbol, Eq")
253
+ app.run_cell("x = Symbol('x'); pw = format(Piecewise((1, Eq(x, 0)), (0, True)))")
254
+
255
+
256
+ def test_override_repr_latex():
257
+ # Initialize and setup IPython session
258
+ app = init_ipython_session()
259
+ app.run_cell("import IPython")
260
+ app.run_cell("ip = get_ipython()")
261
+ app.run_cell("inst = ip.instance()")
262
+ app.run_cell("format = inst.display_formatter.format")
263
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
264
+ app.run_cell("from sympy import init_printing")
265
+ app.run_cell("from sympy import Symbol")
266
+ app.run_cell("init_printing(use_latex=True)")
267
+ app.run_cell("""\
268
+ class SymbolWithOverload(Symbol):
269
+ def _repr_latex_(self):
270
+ return r"Hello " + super()._repr_latex_() + " world"
271
+ """)
272
+ app.run_cell("a = format(SymbolWithOverload('s'))")
273
+
274
+ if int(ipython.__version__.split(".")[0]) < 1:
275
+ latex = app.user_ns['a']['text/latex']
276
+ else:
277
+ latex = app.user_ns['a'][0]['text/latex']
278
+ assert latex == r'Hello $\displaystyle s$ world'
wemm/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)
wemm/lib/python3.10/site-packages/sympy/physics/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A module that helps solving problems in physics.
3
+ """
4
+
5
+ from . import units
6
+ from .matrices import mgamma, msigma, minkowski_tensor, mdft
7
+
8
+ __all__ = [
9
+ 'units',
10
+
11
+ 'mgamma', 'msigma', 'minkowski_tensor', 'mdft',
12
+ ]
wemm/lib/python3.10/site-packages/sympy/physics/hydrogen.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Float
2
+ from sympy.core.singleton import S
3
+ from sympy.functions.combinatorial.factorials import factorial
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.special.polynomials import assoc_laguerre
7
+ from sympy.functions.special.spherical_harmonics import Ynm
8
+
9
+
10
+ def R_nl(n, l, r, Z=1):
11
+ """
12
+ Returns the Hydrogen radial wavefunction R_{nl}.
13
+
14
+ Parameters
15
+ ==========
16
+
17
+ n : integer
18
+ Principal Quantum Number which is
19
+ an integer with possible values as 1, 2, 3, 4,...
20
+ l : integer
21
+ ``l`` is the Angular Momentum Quantum Number with
22
+ values ranging from 0 to ``n-1``.
23
+ r :
24
+ Radial coordinate.
25
+ Z :
26
+ Atomic number (1 for Hydrogen, 2 for Helium, ...)
27
+
28
+ Everything is in Hartree atomic units.
29
+
30
+ Examples
31
+ ========
32
+
33
+ >>> from sympy.physics.hydrogen import R_nl
34
+ >>> from sympy.abc import r, Z
35
+ >>> R_nl(1, 0, r, Z)
36
+ 2*sqrt(Z**3)*exp(-Z*r)
37
+ >>> R_nl(2, 0, r, Z)
38
+ sqrt(2)*(-Z*r + 2)*sqrt(Z**3)*exp(-Z*r/2)/4
39
+ >>> R_nl(2, 1, r, Z)
40
+ sqrt(6)*Z*r*sqrt(Z**3)*exp(-Z*r/2)/12
41
+
42
+ For Hydrogen atom, you can just use the default value of Z=1:
43
+
44
+ >>> R_nl(1, 0, r)
45
+ 2*exp(-r)
46
+ >>> R_nl(2, 0, r)
47
+ sqrt(2)*(2 - r)*exp(-r/2)/4
48
+ >>> R_nl(3, 0, r)
49
+ 2*sqrt(3)*(2*r**2/9 - 2*r + 3)*exp(-r/3)/27
50
+
51
+ For Silver atom, you would use Z=47:
52
+
53
+ >>> R_nl(1, 0, r, Z=47)
54
+ 94*sqrt(47)*exp(-47*r)
55
+ >>> R_nl(2, 0, r, Z=47)
56
+ 47*sqrt(94)*(2 - 47*r)*exp(-47*r/2)/4
57
+ >>> R_nl(3, 0, r, Z=47)
58
+ 94*sqrt(141)*(4418*r**2/9 - 94*r + 3)*exp(-47*r/3)/27
59
+
60
+ The normalization of the radial wavefunction is:
61
+
62
+ >>> from sympy import integrate, oo
63
+ >>> integrate(R_nl(1, 0, r)**2 * r**2, (r, 0, oo))
64
+ 1
65
+ >>> integrate(R_nl(2, 0, r)**2 * r**2, (r, 0, oo))
66
+ 1
67
+ >>> integrate(R_nl(2, 1, r)**2 * r**2, (r, 0, oo))
68
+ 1
69
+
70
+ It holds for any atomic number:
71
+
72
+ >>> integrate(R_nl(1, 0, r, Z=2)**2 * r**2, (r, 0, oo))
73
+ 1
74
+ >>> integrate(R_nl(2, 0, r, Z=3)**2 * r**2, (r, 0, oo))
75
+ 1
76
+ >>> integrate(R_nl(2, 1, r, Z=4)**2 * r**2, (r, 0, oo))
77
+ 1
78
+
79
+ """
80
+ # sympify arguments
81
+ n, l, r, Z = map(S, [n, l, r, Z])
82
+ # radial quantum number
83
+ n_r = n - l - 1
84
+ # rescaled "r"
85
+ a = 1/Z # Bohr radius
86
+ r0 = 2 * r / (n * a)
87
+ # normalization coefficient
88
+ C = sqrt((S(2)/(n*a))**3 * factorial(n_r) / (2*n*factorial(n + l)))
89
+ # This is an equivalent normalization coefficient, that can be found in
90
+ # some books. Both coefficients seem to be the same fast:
91
+ # C = S(2)/n**2 * sqrt(1/a**3 * factorial(n_r) / (factorial(n+l)))
92
+ return C * r0**l * assoc_laguerre(n_r, 2*l + 1, r0).expand() * exp(-r0/2)
93
+
94
+
95
+ def Psi_nlm(n, l, m, r, phi, theta, Z=1):
96
+ """
97
+ Returns the Hydrogen wave function psi_{nlm}. It's the product of
98
+ the radial wavefunction R_{nl} and the spherical harmonic Y_{l}^{m}.
99
+
100
+ Parameters
101
+ ==========
102
+
103
+ n : integer
104
+ Principal Quantum Number which is
105
+ an integer with possible values as 1, 2, 3, 4,...
106
+ l : integer
107
+ ``l`` is the Angular Momentum Quantum Number with
108
+ values ranging from 0 to ``n-1``.
109
+ m : integer
110
+ ``m`` is the Magnetic Quantum Number with values
111
+ ranging from ``-l`` to ``l``.
112
+ r :
113
+ radial coordinate
114
+ phi :
115
+ azimuthal angle
116
+ theta :
117
+ polar angle
118
+ Z :
119
+ atomic number (1 for Hydrogen, 2 for Helium, ...)
120
+
121
+ Everything is in Hartree atomic units.
122
+
123
+ Examples
124
+ ========
125
+
126
+ >>> from sympy.physics.hydrogen import Psi_nlm
127
+ >>> from sympy import Symbol
128
+ >>> r=Symbol("r", positive=True)
129
+ >>> phi=Symbol("phi", real=True)
130
+ >>> theta=Symbol("theta", real=True)
131
+ >>> Z=Symbol("Z", positive=True, integer=True, nonzero=True)
132
+ >>> Psi_nlm(1,0,0,r,phi,theta,Z)
133
+ Z**(3/2)*exp(-Z*r)/sqrt(pi)
134
+ >>> Psi_nlm(2,1,1,r,phi,theta,Z)
135
+ -Z**(5/2)*r*exp(I*phi)*exp(-Z*r/2)*sin(theta)/(8*sqrt(pi))
136
+
137
+ Integrating the absolute square of a hydrogen wavefunction psi_{nlm}
138
+ over the whole space leads 1.
139
+
140
+ The normalization of the hydrogen wavefunctions Psi_nlm is:
141
+
142
+ >>> from sympy import integrate, conjugate, pi, oo, sin
143
+ >>> wf=Psi_nlm(2,1,1,r,phi,theta,Z)
144
+ >>> abs_sqrd=wf*conjugate(wf)
145
+ >>> jacobi=r**2*sin(theta)
146
+ >>> integrate(abs_sqrd*jacobi, (r,0,oo), (phi,0,2*pi), (theta,0,pi))
147
+ 1
148
+ """
149
+
150
+ # sympify arguments
151
+ n, l, m, r, phi, theta, Z = map(S, [n, l, m, r, phi, theta, Z])
152
+ # check if values for n,l,m make physically sense
153
+ if n.is_integer and n < 1:
154
+ raise ValueError("'n' must be positive integer")
155
+ if l.is_integer and not (n > l):
156
+ raise ValueError("'n' must be greater than 'l'")
157
+ if m.is_integer and not (abs(m) <= l):
158
+ raise ValueError("|'m'| must be less or equal 'l'")
159
+ # return the hydrogen wave function
160
+ return R_nl(n, l, r, Z)*Ynm(l, m, theta, phi).expand(func=True)
161
+
162
+
163
+ def E_nl(n, Z=1):
164
+ """
165
+ Returns the energy of the state (n, l) in Hartree atomic units.
166
+
167
+ The energy does not depend on "l".
168
+
169
+ Parameters
170
+ ==========
171
+
172
+ n : integer
173
+ Principal Quantum Number which is
174
+ an integer with possible values as 1, 2, 3, 4,...
175
+ Z :
176
+ Atomic number (1 for Hydrogen, 2 for Helium, ...)
177
+
178
+ Examples
179
+ ========
180
+
181
+ >>> from sympy.physics.hydrogen import E_nl
182
+ >>> from sympy.abc import n, Z
183
+ >>> E_nl(n, Z)
184
+ -Z**2/(2*n**2)
185
+ >>> E_nl(1)
186
+ -1/2
187
+ >>> E_nl(2)
188
+ -1/8
189
+ >>> E_nl(3)
190
+ -1/18
191
+ >>> E_nl(3, 47)
192
+ -2209/18
193
+
194
+ """
195
+ n, Z = S(n), S(Z)
196
+ if n.is_integer and (n < 1):
197
+ raise ValueError("'n' must be positive integer")
198
+ return -Z**2/(2*n**2)
199
+
200
+
201
+ def E_nl_dirac(n, l, spin_up=True, Z=1, c=Float("137.035999037")):
202
+ """
203
+ Returns the relativistic energy of the state (n, l, spin) in Hartree atomic
204
+ units.
205
+
206
+ The energy is calculated from the Dirac equation. The rest mass energy is
207
+ *not* included.
208
+
209
+ Parameters
210
+ ==========
211
+
212
+ n : integer
213
+ Principal Quantum Number which is
214
+ an integer with possible values as 1, 2, 3, 4,...
215
+ l : integer
216
+ ``l`` is the Angular Momentum Quantum Number with
217
+ values ranging from 0 to ``n-1``.
218
+ spin_up :
219
+ True if the electron spin is up (default), otherwise down
220
+ Z :
221
+ Atomic number (1 for Hydrogen, 2 for Helium, ...)
222
+ c :
223
+ Speed of light in atomic units. Default value is 137.035999037,
224
+ taken from https://arxiv.org/abs/1012.3627
225
+
226
+ Examples
227
+ ========
228
+
229
+ >>> from sympy.physics.hydrogen import E_nl_dirac
230
+ >>> E_nl_dirac(1, 0)
231
+ -0.500006656595360
232
+
233
+ >>> E_nl_dirac(2, 0)
234
+ -0.125002080189006
235
+ >>> E_nl_dirac(2, 1)
236
+ -0.125000416028342
237
+ >>> E_nl_dirac(2, 1, False)
238
+ -0.125002080189006
239
+
240
+ >>> E_nl_dirac(3, 0)
241
+ -0.0555562951740285
242
+ >>> E_nl_dirac(3, 1)
243
+ -0.0555558020932949
244
+ >>> E_nl_dirac(3, 1, False)
245
+ -0.0555562951740285
246
+ >>> E_nl_dirac(3, 2)
247
+ -0.0555556377366884
248
+ >>> E_nl_dirac(3, 2, False)
249
+ -0.0555558020932949
250
+
251
+ """
252
+ n, l, Z, c = map(S, [n, l, Z, c])
253
+ if not (l >= 0):
254
+ raise ValueError("'l' must be positive or zero")
255
+ if not (n > l):
256
+ raise ValueError("'n' must be greater than 'l'")
257
+ if (l == 0 and spin_up is False):
258
+ raise ValueError("Spin must be up for l==0.")
259
+ # skappa is sign*kappa, where sign contains the correct sign
260
+ if spin_up:
261
+ skappa = -l - 1
262
+ else:
263
+ skappa = -l
264
+ beta = sqrt(skappa**2 - Z**2/c**2)
265
+ return c**2/sqrt(1 + Z**2/(n + skappa + beta)**2/c**2) - c**2
wemm/lib/python3.10/site-packages/sympy/physics/matrices.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Known matrices related to physics"""
2
+
3
+ from sympy.core.numbers import I
4
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix
5
+ from sympy.utilities.decorator import deprecated
6
+
7
+
8
+ def msigma(i):
9
+ r"""Returns a Pauli matrix `\sigma_i` with `i=1,2,3`.
10
+
11
+ References
12
+ ==========
13
+
14
+ .. [1] https://en.wikipedia.org/wiki/Pauli_matrices
15
+
16
+ Examples
17
+ ========
18
+
19
+ >>> from sympy.physics.matrices import msigma
20
+ >>> msigma(1)
21
+ Matrix([
22
+ [0, 1],
23
+ [1, 0]])
24
+ """
25
+ if i == 1:
26
+ mat = (
27
+ (0, 1),
28
+ (1, 0)
29
+ )
30
+ elif i == 2:
31
+ mat = (
32
+ (0, -I),
33
+ (I, 0)
34
+ )
35
+ elif i == 3:
36
+ mat = (
37
+ (1, 0),
38
+ (0, -1)
39
+ )
40
+ else:
41
+ raise IndexError("Invalid Pauli index")
42
+ return Matrix(mat)
43
+
44
+
45
+ def pat_matrix(m, dx, dy, dz):
46
+ """Returns the Parallel Axis Theorem matrix to translate the inertia
47
+ matrix a distance of `(dx, dy, dz)` for a body of mass m.
48
+
49
+ Examples
50
+ ========
51
+
52
+ To translate a body having a mass of 2 units a distance of 1 unit along
53
+ the `x`-axis we get:
54
+
55
+ >>> from sympy.physics.matrices import pat_matrix
56
+ >>> pat_matrix(2, 1, 0, 0)
57
+ Matrix([
58
+ [0, 0, 0],
59
+ [0, 2, 0],
60
+ [0, 0, 2]])
61
+
62
+ """
63
+ dxdy = -dx*dy
64
+ dydz = -dy*dz
65
+ dzdx = -dz*dx
66
+ dxdx = dx**2
67
+ dydy = dy**2
68
+ dzdz = dz**2
69
+ mat = ((dydy + dzdz, dxdy, dzdx),
70
+ (dxdy, dxdx + dzdz, dydz),
71
+ (dzdx, dydz, dydy + dxdx))
72
+ return m*Matrix(mat)
73
+
74
+
75
+ def mgamma(mu, lower=False):
76
+ r"""Returns a Dirac gamma matrix `\gamma^\mu` in the standard
77
+ (Dirac) representation.
78
+
79
+ Explanation
80
+ ===========
81
+
82
+ If you want `\gamma_\mu`, use ``gamma(mu, True)``.
83
+
84
+ We use a convention:
85
+
86
+ `\gamma^5 = i \cdot \gamma^0 \cdot \gamma^1 \cdot \gamma^2 \cdot \gamma^3`
87
+
88
+ `\gamma_5 = i \cdot \gamma_0 \cdot \gamma_1 \cdot \gamma_2 \cdot \gamma_3 = - \gamma^5`
89
+
90
+ References
91
+ ==========
92
+
93
+ .. [1] https://en.wikipedia.org/wiki/Gamma_matrices
94
+
95
+ Examples
96
+ ========
97
+
98
+ >>> from sympy.physics.matrices import mgamma
99
+ >>> mgamma(1)
100
+ Matrix([
101
+ [ 0, 0, 0, 1],
102
+ [ 0, 0, 1, 0],
103
+ [ 0, -1, 0, 0],
104
+ [-1, 0, 0, 0]])
105
+ """
106
+ if mu not in (0, 1, 2, 3, 5):
107
+ raise IndexError("Invalid Dirac index")
108
+ if mu == 0:
109
+ mat = (
110
+ (1, 0, 0, 0),
111
+ (0, 1, 0, 0),
112
+ (0, 0, -1, 0),
113
+ (0, 0, 0, -1)
114
+ )
115
+ elif mu == 1:
116
+ mat = (
117
+ (0, 0, 0, 1),
118
+ (0, 0, 1, 0),
119
+ (0, -1, 0, 0),
120
+ (-1, 0, 0, 0)
121
+ )
122
+ elif mu == 2:
123
+ mat = (
124
+ (0, 0, 0, -I),
125
+ (0, 0, I, 0),
126
+ (0, I, 0, 0),
127
+ (-I, 0, 0, 0)
128
+ )
129
+ elif mu == 3:
130
+ mat = (
131
+ (0, 0, 1, 0),
132
+ (0, 0, 0, -1),
133
+ (-1, 0, 0, 0),
134
+ (0, 1, 0, 0)
135
+ )
136
+ elif mu == 5:
137
+ mat = (
138
+ (0, 0, 1, 0),
139
+ (0, 0, 0, 1),
140
+ (1, 0, 0, 0),
141
+ (0, 1, 0, 0)
142
+ )
143
+ m = Matrix(mat)
144
+ if lower:
145
+ if mu in (1, 2, 3, 5):
146
+ m = -m
147
+ return m
148
+
149
+ #Minkowski tensor using the convention (+,-,-,-) used in the Quantum Field
150
+ #Theory
151
+ minkowski_tensor = Matrix( (
152
+ (1, 0, 0, 0),
153
+ (0, -1, 0, 0),
154
+ (0, 0, -1, 0),
155
+ (0, 0, 0, -1)
156
+ ))
157
+
158
+
159
+ @deprecated(
160
+ """
161
+ The sympy.physics.matrices.mdft method is deprecated. Use
162
+ sympy.DFT(n).as_explicit() instead.
163
+ """,
164
+ deprecated_since_version="1.9",
165
+ active_deprecations_target="deprecated-physics-mdft",
166
+ )
167
+ def mdft(n):
168
+ r"""
169
+ .. deprecated:: 1.9
170
+
171
+ Use DFT from sympy.matrices.expressions.fourier instead.
172
+
173
+ To get identical behavior to ``mdft(n)``, use ``DFT(n).as_explicit()``.
174
+ """
175
+ from sympy.matrices.expressions.fourier import DFT
176
+ return DFT(n).as_mutable()
wemm/lib/python3.10/site-packages/sympy/physics/paulialgebra.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module implements Pauli algebra by subclassing Symbol. Only algebraic
3
+ properties of Pauli matrices are used (we do not use the Matrix class).
4
+
5
+ See the documentation to the class Pauli for examples.
6
+
7
+ References
8
+ ==========
9
+
10
+ .. [1] https://en.wikipedia.org/wiki/Pauli_matrices
11
+ """
12
+
13
+ from sympy.core.add import Add
14
+ from sympy.core.mul import Mul
15
+ from sympy.core.numbers import I
16
+ from sympy.core.power import Pow
17
+ from sympy.core.symbol import Symbol
18
+ from sympy.physics.quantum import TensorProduct
19
+
20
+ __all__ = ['evaluate_pauli_product']
21
+
22
+
23
+ def delta(i, j):
24
+ """
25
+ Returns 1 if ``i == j``, else 0.
26
+
27
+ This is used in the multiplication of Pauli matrices.
28
+
29
+ Examples
30
+ ========
31
+
32
+ >>> from sympy.physics.paulialgebra import delta
33
+ >>> delta(1, 1)
34
+ 1
35
+ >>> delta(2, 3)
36
+ 0
37
+ """
38
+ if i == j:
39
+ return 1
40
+ else:
41
+ return 0
42
+
43
+
44
+ def epsilon(i, j, k):
45
+ """
46
+ Return 1 if i,j,k is equal to (1,2,3), (2,3,1), or (3,1,2);
47
+ -1 if ``i``,``j``,``k`` is equal to (1,3,2), (3,2,1), or (2,1,3);
48
+ else return 0.
49
+
50
+ This is used in the multiplication of Pauli matrices.
51
+
52
+ Examples
53
+ ========
54
+
55
+ >>> from sympy.physics.paulialgebra import epsilon
56
+ >>> epsilon(1, 2, 3)
57
+ 1
58
+ >>> epsilon(1, 3, 2)
59
+ -1
60
+ """
61
+ if (i, j, k) in ((1, 2, 3), (2, 3, 1), (3, 1, 2)):
62
+ return 1
63
+ elif (i, j, k) in ((1, 3, 2), (3, 2, 1), (2, 1, 3)):
64
+ return -1
65
+ else:
66
+ return 0
67
+
68
+
69
+ class Pauli(Symbol):
70
+ """
71
+ The class representing algebraic properties of Pauli matrices.
72
+
73
+ Explanation
74
+ ===========
75
+
76
+ The symbol used to display the Pauli matrices can be changed with an
77
+ optional parameter ``label="sigma"``. Pauli matrices with different
78
+ ``label`` attributes cannot multiply together.
79
+
80
+ If the left multiplication of symbol or number with Pauli matrix is needed,
81
+ please use parentheses to separate Pauli and symbolic multiplication
82
+ (for example: 2*I*(Pauli(3)*Pauli(2))).
83
+
84
+ Another variant is to use evaluate_pauli_product function to evaluate
85
+ the product of Pauli matrices and other symbols (with commutative
86
+ multiply rules).
87
+
88
+ See Also
89
+ ========
90
+
91
+ evaluate_pauli_product
92
+
93
+ Examples
94
+ ========
95
+
96
+ >>> from sympy.physics.paulialgebra import Pauli
97
+ >>> Pauli(1)
98
+ sigma1
99
+ >>> Pauli(1)*Pauli(2)
100
+ I*sigma3
101
+ >>> Pauli(1)*Pauli(1)
102
+ 1
103
+ >>> Pauli(3)**4
104
+ 1
105
+ >>> Pauli(1)*Pauli(2)*Pauli(3)
106
+ I
107
+
108
+ >>> from sympy.physics.paulialgebra import Pauli
109
+ >>> Pauli(1, label="tau")
110
+ tau1
111
+ >>> Pauli(1)*Pauli(2, label="tau")
112
+ sigma1*tau2
113
+ >>> Pauli(1, label="tau")*Pauli(2, label="tau")
114
+ I*tau3
115
+
116
+ >>> from sympy import I
117
+ >>> I*(Pauli(2)*Pauli(3))
118
+ -sigma1
119
+
120
+ >>> from sympy.physics.paulialgebra import evaluate_pauli_product
121
+ >>> f = I*Pauli(2)*Pauli(3)
122
+ >>> f
123
+ I*sigma2*sigma3
124
+ >>> evaluate_pauli_product(f)
125
+ -sigma1
126
+ """
127
+
128
+ __slots__ = ("i", "label")
129
+
130
+ def __new__(cls, i, label="sigma"):
131
+ if i not in [1, 2, 3]:
132
+ raise IndexError("Invalid Pauli index")
133
+ obj = Symbol.__new__(cls, "%s%d" %(label,i), commutative=False, hermitian=True)
134
+ obj.i = i
135
+ obj.label = label
136
+ return obj
137
+
138
+ def __getnewargs_ex__(self):
139
+ return (self.i, self.label), {}
140
+
141
+ def _hashable_content(self):
142
+ return (self.i, self.label)
143
+
144
+ # FIXME don't work for -I*Pauli(2)*Pauli(3)
145
+ def __mul__(self, other):
146
+ if isinstance(other, Pauli):
147
+ j = self.i
148
+ k = other.i
149
+ jlab = self.label
150
+ klab = other.label
151
+
152
+ if jlab == klab:
153
+ return delta(j, k) \
154
+ + I*epsilon(j, k, 1)*Pauli(1,jlab) \
155
+ + I*epsilon(j, k, 2)*Pauli(2,jlab) \
156
+ + I*epsilon(j, k, 3)*Pauli(3,jlab)
157
+ return super().__mul__(other)
158
+
159
+ def _eval_power(b, e):
160
+ if e.is_Integer and e.is_positive:
161
+ return super().__pow__(int(e) % 2)
162
+
163
+
164
+ def evaluate_pauli_product(arg):
165
+ '''Help function to evaluate Pauli matrices product
166
+ with symbolic objects.
167
+
168
+ Parameters
169
+ ==========
170
+
171
+ arg: symbolic expression that contains Paulimatrices
172
+
173
+ Examples
174
+ ========
175
+
176
+ >>> from sympy.physics.paulialgebra import Pauli, evaluate_pauli_product
177
+ >>> from sympy import I
178
+ >>> evaluate_pauli_product(I*Pauli(1)*Pauli(2))
179
+ -sigma3
180
+
181
+ >>> from sympy.abc import x
182
+ >>> evaluate_pauli_product(x**2*Pauli(2)*Pauli(1))
183
+ -I*x**2*sigma3
184
+ '''
185
+ start = arg
186
+ end = arg
187
+
188
+ if isinstance(arg, Pow) and isinstance(arg.args[0], Pauli):
189
+ if arg.args[1].is_odd:
190
+ return arg.args[0]
191
+ else:
192
+ return 1
193
+
194
+ if isinstance(arg, Add):
195
+ return Add(*[evaluate_pauli_product(part) for part in arg.args])
196
+
197
+ if isinstance(arg, TensorProduct):
198
+ return TensorProduct(*[evaluate_pauli_product(part) for part in arg.args])
199
+
200
+ elif not(isinstance(arg, Mul)):
201
+ return arg
202
+
203
+ while not start == end or start == arg and end == arg:
204
+ start = end
205
+
206
+ tmp = start.as_coeff_mul()
207
+ sigma_product = 1
208
+ com_product = 1
209
+ keeper = 1
210
+
211
+ for el in tmp[1]:
212
+ if isinstance(el, Pauli):
213
+ sigma_product *= el
214
+ elif not el.is_commutative:
215
+ if isinstance(el, Pow) and isinstance(el.args[0], Pauli):
216
+ if el.args[1].is_odd:
217
+ sigma_product *= el.args[0]
218
+ elif isinstance(el, TensorProduct):
219
+ keeper = keeper*sigma_product*\
220
+ TensorProduct(
221
+ *[evaluate_pauli_product(part) for part in el.args]
222
+ )
223
+ sigma_product = 1
224
+ else:
225
+ keeper = keeper*sigma_product*el
226
+ sigma_product = 1
227
+ else:
228
+ com_product *= el
229
+ end = tmp[0]*keeper*sigma_product*com_product
230
+ if end == arg: break
231
+ return end
wemm/lib/python3.10/site-packages/sympy/physics/pring.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.functions.elementary.exponential import exp
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.physics.quantum.constants import hbar
6
+
7
+
8
+ def wavefunction(n, x):
9
+ """
10
+ Returns the wavefunction for particle on ring.
11
+
12
+ Parameters
13
+ ==========
14
+
15
+ n : The quantum number.
16
+ Here ``n`` can be positive as well as negative
17
+ which can be used to describe the direction of motion of particle.
18
+ x :
19
+ The angle.
20
+
21
+ Examples
22
+ ========
23
+
24
+ >>> from sympy.physics.pring import wavefunction
25
+ >>> from sympy import Symbol, integrate, pi
26
+ >>> x=Symbol("x")
27
+ >>> wavefunction(1, x)
28
+ sqrt(2)*exp(I*x)/(2*sqrt(pi))
29
+ >>> wavefunction(2, x)
30
+ sqrt(2)*exp(2*I*x)/(2*sqrt(pi))
31
+ >>> wavefunction(3, x)
32
+ sqrt(2)*exp(3*I*x)/(2*sqrt(pi))
33
+
34
+ The normalization of the wavefunction is:
35
+
36
+ >>> integrate(wavefunction(2, x)*wavefunction(-2, x), (x, 0, 2*pi))
37
+ 1
38
+ >>> integrate(wavefunction(4, x)*wavefunction(-4, x), (x, 0, 2*pi))
39
+ 1
40
+
41
+ References
42
+ ==========
43
+
44
+ .. [1] Atkins, Peter W.; Friedman, Ronald (2005). Molecular Quantum
45
+ Mechanics (4th ed.). Pages 71-73.
46
+
47
+ """
48
+ # sympify arguments
49
+ n, x = S(n), S(x)
50
+ return exp(n * I * x) / sqrt(2 * pi)
51
+
52
+
53
+ def energy(n, m, r):
54
+ """
55
+ Returns the energy of the state corresponding to quantum number ``n``.
56
+
57
+ E=(n**2 * (hcross)**2) / (2 * m * r**2)
58
+
59
+ Parameters
60
+ ==========
61
+
62
+ n :
63
+ The quantum number.
64
+ m :
65
+ Mass of the particle.
66
+ r :
67
+ Radius of circle.
68
+
69
+ Examples
70
+ ========
71
+
72
+ >>> from sympy.physics.pring import energy
73
+ >>> from sympy import Symbol
74
+ >>> m=Symbol("m")
75
+ >>> r=Symbol("r")
76
+ >>> energy(1, m, r)
77
+ hbar**2/(2*m*r**2)
78
+ >>> energy(2, m, r)
79
+ 2*hbar**2/(m*r**2)
80
+ >>> energy(-2, 2.0, 3.0)
81
+ 0.111111111111111*hbar**2
82
+
83
+ References
84
+ ==========
85
+
86
+ .. [1] Atkins, Peter W.; Friedman, Ronald (2005). Molecular Quantum
87
+ Mechanics (4th ed.). Pages 71-73.
88
+
89
+ """
90
+ n, m, r = S(n), S(m), S(r)
91
+ if n.is_integer:
92
+ return (n**2 * hbar**2) / (2 * m * r**2)
93
+ else:
94
+ raise ValueError("'n' must be integer")
wemm/lib/python3.10/site-packages/sympy/physics/qho_1d.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, pi, Rational
2
+ from sympy.functions import hermite, sqrt, exp, factorial, Abs
3
+ from sympy.physics.quantum.constants import hbar
4
+
5
+
6
+ def psi_n(n, x, m, omega):
7
+ """
8
+ Returns the wavefunction psi_{n} for the One-dimensional harmonic oscillator.
9
+
10
+ Parameters
11
+ ==========
12
+
13
+ n :
14
+ the "nodal" quantum number. Corresponds to the number of nodes in the
15
+ wavefunction. ``n >= 0``
16
+ x :
17
+ x coordinate.
18
+ m :
19
+ Mass of the particle.
20
+ omega :
21
+ Angular frequency of the oscillator.
22
+
23
+ Examples
24
+ ========
25
+
26
+ >>> from sympy.physics.qho_1d import psi_n
27
+ >>> from sympy.abc import m, x, omega
28
+ >>> psi_n(0, x, m, omega)
29
+ (m*omega)**(1/4)*exp(-m*omega*x**2/(2*hbar))/(hbar**(1/4)*pi**(1/4))
30
+
31
+ """
32
+
33
+ # sympify arguments
34
+ n, x, m, omega = map(S, [n, x, m, omega])
35
+ nu = m * omega / hbar
36
+ # normalization coefficient
37
+ C = (nu/pi)**Rational(1, 4) * sqrt(1/(2**n*factorial(n)))
38
+
39
+ return C * exp(-nu* x**2 /2) * hermite(n, sqrt(nu)*x)
40
+
41
+
42
+ def E_n(n, omega):
43
+ """
44
+ Returns the Energy of the One-dimensional harmonic oscillator.
45
+
46
+ Parameters
47
+ ==========
48
+
49
+ n :
50
+ The "nodal" quantum number.
51
+ omega :
52
+ The harmonic oscillator angular frequency.
53
+
54
+ Notes
55
+ =====
56
+
57
+ The unit of the returned value matches the unit of hw, since the energy is
58
+ calculated as:
59
+
60
+ E_n = hbar * omega*(n + 1/2)
61
+
62
+ Examples
63
+ ========
64
+
65
+ >>> from sympy.physics.qho_1d import E_n
66
+ >>> from sympy.abc import x, omega
67
+ >>> E_n(x, omega)
68
+ hbar*omega*(x + 1/2)
69
+ """
70
+
71
+ return hbar * omega * (n + S.Half)
72
+
73
+
74
+ def coherent_state(n, alpha):
75
+ """
76
+ Returns <n|alpha> for the coherent states of 1D harmonic oscillator.
77
+ See https://en.wikipedia.org/wiki/Coherent_states
78
+
79
+ Parameters
80
+ ==========
81
+
82
+ n :
83
+ The "nodal" quantum number.
84
+ alpha :
85
+ The eigen value of annihilation operator.
86
+ """
87
+
88
+ return exp(- Abs(alpha)**2/2)*(alpha**n)/sqrt(factorial(n))
wemm/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The anti-commutator: ``{A,B} = A*B + B*A``."""
2
+
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.mul import Mul
5
+ from sympy.core.numbers import Integer
6
+ from sympy.core.singleton import S
7
+ from sympy.printing.pretty.stringpict import prettyForm
8
+
9
+ from sympy.physics.quantum.operator import Operator
10
+ from sympy.physics.quantum.dagger import Dagger
11
+
12
+ __all__ = [
13
+ 'AntiCommutator'
14
+ ]
15
+
16
+ #-----------------------------------------------------------------------------
17
+ # Anti-commutator
18
+ #-----------------------------------------------------------------------------
19
+
20
+
21
+ class AntiCommutator(Expr):
22
+ """The standard anticommutator, in an unevaluated state.
23
+
24
+ Explanation
25
+ ===========
26
+
27
+ Evaluating an anticommutator is defined [1]_ as: ``{A, B} = A*B + B*A``.
28
+ This class returns the anticommutator in an unevaluated form. To evaluate
29
+ the anticommutator, use the ``.doit()`` method.
30
+
31
+ Canonical ordering of an anticommutator is ``{A, B}`` for ``A < B``. The
32
+ arguments of the anticommutator are put into canonical order using
33
+ ``__cmp__``. If ``B < A``, then ``{A, B}`` is returned as ``{B, A}``.
34
+
35
+ Parameters
36
+ ==========
37
+
38
+ A : Expr
39
+ The first argument of the anticommutator {A,B}.
40
+ B : Expr
41
+ The second argument of the anticommutator {A,B}.
42
+
43
+ Examples
44
+ ========
45
+
46
+ >>> from sympy import symbols
47
+ >>> from sympy.physics.quantum import AntiCommutator
48
+ >>> from sympy.physics.quantum import Operator, Dagger
49
+ >>> x, y = symbols('x,y')
50
+ >>> A = Operator('A')
51
+ >>> B = Operator('B')
52
+
53
+ Create an anticommutator and use ``doit()`` to multiply them out.
54
+
55
+ >>> ac = AntiCommutator(A,B); ac
56
+ {A,B}
57
+ >>> ac.doit()
58
+ A*B + B*A
59
+
60
+ The commutator orders it arguments in canonical order:
61
+
62
+ >>> ac = AntiCommutator(B,A); ac
63
+ {A,B}
64
+
65
+ Commutative constants are factored out:
66
+
67
+ >>> AntiCommutator(3*x*A,x*y*B)
68
+ 3*x**2*y*{A,B}
69
+
70
+ Adjoint operations applied to the anticommutator are properly applied to
71
+ the arguments:
72
+
73
+ >>> Dagger(AntiCommutator(A,B))
74
+ {Dagger(A),Dagger(B)}
75
+
76
+ References
77
+ ==========
78
+
79
+ .. [1] https://en.wikipedia.org/wiki/Commutator
80
+ """
81
+ is_commutative = False
82
+
83
+ def __new__(cls, A, B):
84
+ r = cls.eval(A, B)
85
+ if r is not None:
86
+ return r
87
+ obj = Expr.__new__(cls, A, B)
88
+ return obj
89
+
90
+ @classmethod
91
+ def eval(cls, a, b):
92
+ if not (a and b):
93
+ return S.Zero
94
+ if a == b:
95
+ return Integer(2)*a**2
96
+ if a.is_commutative or b.is_commutative:
97
+ return Integer(2)*a*b
98
+
99
+ # [xA,yB] -> xy*[A,B]
100
+ ca, nca = a.args_cnc()
101
+ cb, ncb = b.args_cnc()
102
+ c_part = ca + cb
103
+ if c_part:
104
+ return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
105
+
106
+ # Canonical ordering of arguments
107
+ #The Commutator [A,B] is on canonical form if A < B.
108
+ if a.compare(b) == 1:
109
+ return cls(b, a)
110
+
111
+ def doit(self, **hints):
112
+ """ Evaluate anticommutator """
113
+ A = self.args[0]
114
+ B = self.args[1]
115
+ if isinstance(A, Operator) and isinstance(B, Operator):
116
+ try:
117
+ comm = A._eval_anticommutator(B, **hints)
118
+ except NotImplementedError:
119
+ try:
120
+ comm = B._eval_anticommutator(A, **hints)
121
+ except NotImplementedError:
122
+ comm = None
123
+ if comm is not None:
124
+ return comm.doit(**hints)
125
+ return (A*B + B*A).doit(**hints)
126
+
127
+ def _eval_adjoint(self):
128
+ return AntiCommutator(Dagger(self.args[0]), Dagger(self.args[1]))
129
+
130
+ def _sympyrepr(self, printer, *args):
131
+ return "%s(%s,%s)" % (
132
+ self.__class__.__name__, printer._print(
133
+ self.args[0]), printer._print(self.args[1])
134
+ )
135
+
136
+ def _sympystr(self, printer, *args):
137
+ return "{%s,%s}" % (
138
+ printer._print(self.args[0]), printer._print(self.args[1]))
139
+
140
+ def _pretty(self, printer, *args):
141
+ pform = printer._print(self.args[0], *args)
142
+ pform = prettyForm(*pform.right(prettyForm(',')))
143
+ pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
144
+ pform = prettyForm(*pform.parens(left='{', right='}'))
145
+ return pform
146
+
147
+ def _latex(self, printer, *args):
148
+ return "\\left\\{%s,%s\\right\\}" % tuple([
149
+ printer._print(arg, *args) for arg in self.args])
wemm/lib/python3.10/site-packages/sympy/physics/quantum/matrixcache.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A cache for storing small matrices in multiple formats."""
2
+
3
+ from sympy.core.numbers import (I, Rational, pi)
4
+ from sympy.core.power import Pow
5
+ from sympy.functions.elementary.exponential import exp
6
+ from sympy.matrices.dense import Matrix
7
+
8
+ from sympy.physics.quantum.matrixutils import (
9
+ to_sympy, to_numpy, to_scipy_sparse
10
+ )
11
+
12
+
13
+ class MatrixCache:
14
+ """A cache for small matrices in different formats.
15
+
16
+ This class takes small matrices in the standard ``sympy.Matrix`` format,
17
+ and then converts these to both ``numpy.matrix`` and
18
+ ``scipy.sparse.csr_matrix`` matrices. These matrices are then stored for
19
+ future recovery.
20
+ """
21
+
22
+ def __init__(self, dtype='complex'):
23
+ self._cache = {}
24
+ self.dtype = dtype
25
+
26
+ def cache_matrix(self, name, m):
27
+ """Cache a matrix by its name.
28
+
29
+ Parameters
30
+ ----------
31
+ name : str
32
+ A descriptive name for the matrix, like "identity2".
33
+ m : list of lists
34
+ The raw matrix data as a SymPy Matrix.
35
+ """
36
+ try:
37
+ self._sympy_matrix(name, m)
38
+ except ImportError:
39
+ pass
40
+ try:
41
+ self._numpy_matrix(name, m)
42
+ except ImportError:
43
+ pass
44
+ try:
45
+ self._scipy_sparse_matrix(name, m)
46
+ except ImportError:
47
+ pass
48
+
49
+ def get_matrix(self, name, format):
50
+ """Get a cached matrix by name and format.
51
+
52
+ Parameters
53
+ ----------
54
+ name : str
55
+ A descriptive name for the matrix, like "identity2".
56
+ format : str
57
+ The format desired ('sympy', 'numpy', 'scipy.sparse')
58
+ """
59
+ m = self._cache.get((name, format))
60
+ if m is not None:
61
+ return m
62
+ raise NotImplementedError(
63
+ 'Matrix with name %s and format %s is not available.' %
64
+ (name, format)
65
+ )
66
+
67
+ def _store_matrix(self, name, format, m):
68
+ self._cache[(name, format)] = m
69
+
70
+ def _sympy_matrix(self, name, m):
71
+ self._store_matrix(name, 'sympy', to_sympy(m))
72
+
73
+ def _numpy_matrix(self, name, m):
74
+ m = to_numpy(m, dtype=self.dtype)
75
+ self._store_matrix(name, 'numpy', m)
76
+
77
+ def _scipy_sparse_matrix(self, name, m):
78
+ # TODO: explore different sparse formats. But sparse.kron will use
79
+ # coo in most cases, so we use that here.
80
+ m = to_scipy_sparse(m, dtype=self.dtype)
81
+ self._store_matrix(name, 'scipy.sparse', m)
82
+
83
+
84
+ sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False)
85
+
86
+ # Save the common matrices that we will need
87
+ matrix_cache = MatrixCache()
88
+ matrix_cache.cache_matrix('eye2', Matrix([[1, 0], [0, 1]]))
89
+ matrix_cache.cache_matrix('op11', Matrix([[0, 0], [0, 1]])) # |1><1|
90
+ matrix_cache.cache_matrix('op00', Matrix([[1, 0], [0, 0]])) # |0><0|
91
+ matrix_cache.cache_matrix('op10', Matrix([[0, 0], [1, 0]])) # |1><0|
92
+ matrix_cache.cache_matrix('op01', Matrix([[0, 1], [0, 0]])) # |0><1|
93
+ matrix_cache.cache_matrix('X', Matrix([[0, 1], [1, 0]]))
94
+ matrix_cache.cache_matrix('Y', Matrix([[0, -I], [I, 0]]))
95
+ matrix_cache.cache_matrix('Z', Matrix([[1, 0], [0, -1]]))
96
+ matrix_cache.cache_matrix('S', Matrix([[1, 0], [0, I]]))
97
+ matrix_cache.cache_matrix('T', Matrix([[1, 0], [0, exp(I*pi/4)]]))
98
+ matrix_cache.cache_matrix('H', sqrt2_inv*Matrix([[1, 1], [1, -1]]))
99
+ matrix_cache.cache_matrix('Hsqrt2', Matrix([[1, 1], [1, -1]]))
100
+ matrix_cache.cache_matrix(
101
+ 'SWAP', Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]))
102
+ matrix_cache.cache_matrix('ZX', sqrt2_inv*Matrix([[1, 1], [1, -1]]))
103
+ matrix_cache.cache_matrix('ZY', Matrix([[I, 0], [0, -I]]))
wemm/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import Expr
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.core.sympify import sympify
4
+ from sympy.matrices.dense import Matrix
5
+ from sympy.printing.pretty.stringpict import prettyForm
6
+ from sympy.core.containers import Tuple
7
+ from sympy.utilities.iterables import is_sequence
8
+
9
+ from sympy.physics.quantum.dagger import Dagger
10
+ from sympy.physics.quantum.matrixutils import (
11
+ numpy_ndarray, scipy_sparse_matrix,
12
+ to_sympy, to_numpy, to_scipy_sparse
13
+ )
14
+
15
+ __all__ = [
16
+ 'QuantumError',
17
+ 'QExpr'
18
+ ]
19
+
20
+
21
+ #-----------------------------------------------------------------------------
22
+ # Error handling
23
+ #-----------------------------------------------------------------------------
24
+
25
+ class QuantumError(Exception):
26
+ pass
27
+
28
+
29
+ def _qsympify_sequence(seq):
30
+ """Convert elements of a sequence to standard form.
31
+
32
+ This is like sympify, but it performs special logic for arguments passed
33
+ to QExpr. The following conversions are done:
34
+
35
+ * (list, tuple, Tuple) => _qsympify_sequence each element and convert
36
+ sequence to a Tuple.
37
+ * basestring => Symbol
38
+ * Matrix => Matrix
39
+ * other => sympify
40
+
41
+ Strings are passed to Symbol, not sympify to make sure that variables like
42
+ 'pi' are kept as Symbols, not the SymPy built-in number subclasses.
43
+
44
+ Examples
45
+ ========
46
+
47
+ >>> from sympy.physics.quantum.qexpr import _qsympify_sequence
48
+ >>> _qsympify_sequence((1,2,[3,4,[1,]]))
49
+ (1, 2, (3, 4, (1,)))
50
+
51
+ """
52
+
53
+ return tuple(__qsympify_sequence_helper(seq))
54
+
55
+
56
+ def __qsympify_sequence_helper(seq):
57
+ """
58
+ Helper function for _qsympify_sequence
59
+ This function does the actual work.
60
+ """
61
+ #base case. If not a list, do Sympification
62
+ if not is_sequence(seq):
63
+ if isinstance(seq, Matrix):
64
+ return seq
65
+ elif isinstance(seq, str):
66
+ return Symbol(seq)
67
+ else:
68
+ return sympify(seq)
69
+
70
+ # base condition, when seq is QExpr and also
71
+ # is iterable.
72
+ if isinstance(seq, QExpr):
73
+ return seq
74
+
75
+ #if list, recurse on each item in the list
76
+ result = [__qsympify_sequence_helper(item) for item in seq]
77
+
78
+ return Tuple(*result)
79
+
80
+
81
+ #-----------------------------------------------------------------------------
82
+ # Basic Quantum Expression from which all objects descend
83
+ #-----------------------------------------------------------------------------
84
+
85
+ class QExpr(Expr):
86
+ """A base class for all quantum object like operators and states."""
87
+
88
+ # In sympy, slots are for instance attributes that are computed
89
+ # dynamically by the __new__ method. They are not part of args, but they
90
+ # derive from args.
91
+
92
+ # The Hilbert space a quantum Object belongs to.
93
+ __slots__ = ('hilbert_space', )
94
+
95
+ is_commutative = False
96
+
97
+ # The separator used in printing the label.
98
+ _label_separator = ''
99
+
100
+ @property
101
+ def free_symbols(self):
102
+ return {self}
103
+
104
+ def __new__(cls, *args, **kwargs):
105
+ """Construct a new quantum object.
106
+
107
+ Parameters
108
+ ==========
109
+
110
+ args : tuple
111
+ The list of numbers or parameters that uniquely specify the
112
+ quantum object. For a state, this will be its symbol or its
113
+ set of quantum numbers.
114
+
115
+ Examples
116
+ ========
117
+
118
+ >>> from sympy.physics.quantum.qexpr import QExpr
119
+ >>> q = QExpr(0)
120
+ >>> q
121
+ 0
122
+ >>> q.label
123
+ (0,)
124
+ >>> q.hilbert_space
125
+ H
126
+ >>> q.args
127
+ (0,)
128
+ >>> q.is_commutative
129
+ False
130
+ """
131
+
132
+ # First compute args and call Expr.__new__ to create the instance
133
+ args = cls._eval_args(args, **kwargs)
134
+ if len(args) == 0:
135
+ args = cls._eval_args(tuple(cls.default_args()), **kwargs)
136
+ inst = Expr.__new__(cls, *args)
137
+ # Now set the slots on the instance
138
+ inst.hilbert_space = cls._eval_hilbert_space(args)
139
+ return inst
140
+
141
+ @classmethod
142
+ def _new_rawargs(cls, hilbert_space, *args, **old_assumptions):
143
+ """Create new instance of this class with hilbert_space and args.
144
+
145
+ This is used to bypass the more complex logic in the ``__new__``
146
+ method in cases where you already have the exact ``hilbert_space``
147
+ and ``args``. This should be used when you are positive these
148
+ arguments are valid, in their final, proper form and want to optimize
149
+ the creation of the object.
150
+ """
151
+
152
+ obj = Expr.__new__(cls, *args, **old_assumptions)
153
+ obj.hilbert_space = hilbert_space
154
+ return obj
155
+
156
+ #-------------------------------------------------------------------------
157
+ # Properties
158
+ #-------------------------------------------------------------------------
159
+
160
+ @property
161
+ def label(self):
162
+ """The label is the unique set of identifiers for the object.
163
+
164
+ Usually, this will include all of the information about the state
165
+ *except* the time (in the case of time-dependent objects).
166
+
167
+ This must be a tuple, rather than a Tuple.
168
+ """
169
+ if len(self.args) == 0: # If there is no label specified, return the default
170
+ return self._eval_args(list(self.default_args()))
171
+ else:
172
+ return self.args
173
+
174
+ @property
175
+ def is_symbolic(self):
176
+ return True
177
+
178
+ @classmethod
179
+ def default_args(self):
180
+ """If no arguments are specified, then this will return a default set
181
+ of arguments to be run through the constructor.
182
+
183
+ NOTE: Any classes that override this MUST return a tuple of arguments.
184
+ Should be overridden by subclasses to specify the default arguments for kets and operators
185
+ """
186
+ raise NotImplementedError("No default arguments for this class!")
187
+
188
+ #-------------------------------------------------------------------------
189
+ # _eval_* methods
190
+ #-------------------------------------------------------------------------
191
+
192
+ def _eval_adjoint(self):
193
+ obj = Expr._eval_adjoint(self)
194
+ if obj is None:
195
+ obj = Expr.__new__(Dagger, self)
196
+ if isinstance(obj, QExpr):
197
+ obj.hilbert_space = self.hilbert_space
198
+ return obj
199
+
200
+ @classmethod
201
+ def _eval_args(cls, args):
202
+ """Process the args passed to the __new__ method.
203
+
204
+ This simply runs args through _qsympify_sequence.
205
+ """
206
+ return _qsympify_sequence(args)
207
+
208
+ @classmethod
209
+ def _eval_hilbert_space(cls, args):
210
+ """Compute the Hilbert space instance from the args.
211
+ """
212
+ from sympy.physics.quantum.hilbert import HilbertSpace
213
+ return HilbertSpace()
214
+
215
+ #-------------------------------------------------------------------------
216
+ # Printing
217
+ #-------------------------------------------------------------------------
218
+
219
+ # Utilities for printing: these operate on raw SymPy objects
220
+
221
+ def _print_sequence(self, seq, sep, printer, *args):
222
+ result = []
223
+ for item in seq:
224
+ result.append(printer._print(item, *args))
225
+ return sep.join(result)
226
+
227
+ def _print_sequence_pretty(self, seq, sep, printer, *args):
228
+ pform = printer._print(seq[0], *args)
229
+ for item in seq[1:]:
230
+ pform = prettyForm(*pform.right(sep))
231
+ pform = prettyForm(*pform.right(printer._print(item, *args)))
232
+ return pform
233
+
234
+ # Utilities for printing: these operate prettyForm objects
235
+
236
+ def _print_subscript_pretty(self, a, b):
237
+ top = prettyForm(*b.left(' '*a.width()))
238
+ bot = prettyForm(*a.right(' '*b.width()))
239
+ return prettyForm(binding=prettyForm.POW, *bot.below(top))
240
+
241
+ def _print_superscript_pretty(self, a, b):
242
+ return a**b
243
+
244
+ def _print_parens_pretty(self, pform, left='(', right=')'):
245
+ return prettyForm(*pform.parens(left=left, right=right))
246
+
247
+ # Printing of labels (i.e. args)
248
+
249
+ def _print_label(self, printer, *args):
250
+ """Prints the label of the QExpr
251
+
252
+ This method prints self.label, using self._label_separator to separate
253
+ the elements. This method should not be overridden, instead, override
254
+ _print_contents to change printing behavior.
255
+ """
256
+ return self._print_sequence(
257
+ self.label, self._label_separator, printer, *args
258
+ )
259
+
260
+ def _print_label_repr(self, printer, *args):
261
+ return self._print_sequence(
262
+ self.label, ',', printer, *args
263
+ )
264
+
265
+ def _print_label_pretty(self, printer, *args):
266
+ return self._print_sequence_pretty(
267
+ self.label, self._label_separator, printer, *args
268
+ )
269
+
270
+ def _print_label_latex(self, printer, *args):
271
+ return self._print_sequence(
272
+ self.label, self._label_separator, printer, *args
273
+ )
274
+
275
+ # Printing of contents (default to label)
276
+
277
+ def _print_contents(self, printer, *args):
278
+ """Printer for contents of QExpr
279
+
280
+ Handles the printing of any unique identifying contents of a QExpr to
281
+ print as its contents, such as any variables or quantum numbers. The
282
+ default is to print the label, which is almost always the args. This
283
+ should not include printing of any brackets or parentheses.
284
+ """
285
+ return self._print_label(printer, *args)
286
+
287
+ def _print_contents_pretty(self, printer, *args):
288
+ return self._print_label_pretty(printer, *args)
289
+
290
+ def _print_contents_latex(self, printer, *args):
291
+ return self._print_label_latex(printer, *args)
292
+
293
+ # Main printing methods
294
+
295
+ def _sympystr(self, printer, *args):
296
+ """Default printing behavior of QExpr objects
297
+
298
+ Handles the default printing of a QExpr. To add other things to the
299
+ printing of the object, such as an operator name to operators or
300
+ brackets to states, the class should override the _print/_pretty/_latex
301
+ functions directly and make calls to _print_contents where appropriate.
302
+ This allows things like InnerProduct to easily control its printing the
303
+ printing of contents.
304
+ """
305
+ return self._print_contents(printer, *args)
306
+
307
+ def _sympyrepr(self, printer, *args):
308
+ classname = self.__class__.__name__
309
+ label = self._print_label_repr(printer, *args)
310
+ return '%s(%s)' % (classname, label)
311
+
312
+ def _pretty(self, printer, *args):
313
+ pform = self._print_contents_pretty(printer, *args)
314
+ return pform
315
+
316
+ def _latex(self, printer, *args):
317
+ return self._print_contents_latex(printer, *args)
318
+
319
+ #-------------------------------------------------------------------------
320
+ # Represent
321
+ #-------------------------------------------------------------------------
322
+
323
+ def _represent_default_basis(self, **options):
324
+ raise NotImplementedError('This object does not have a default basis')
325
+
326
+ def _represent(self, *, basis=None, **options):
327
+ """Represent this object in a given basis.
328
+
329
+ This method dispatches to the actual methods that perform the
330
+ representation. Subclases of QExpr should define various methods to
331
+ determine how the object will be represented in various bases. The
332
+ format of these methods is::
333
+
334
+ def _represent_BasisName(self, basis, **options):
335
+
336
+ Thus to define how a quantum object is represented in the basis of
337
+ the operator Position, you would define::
338
+
339
+ def _represent_Position(self, basis, **options):
340
+
341
+ Usually, basis object will be instances of Operator subclasses, but
342
+ there is a chance we will relax this in the future to accommodate other
343
+ types of basis sets that are not associated with an operator.
344
+
345
+ If the ``format`` option is given it can be ("sympy", "numpy",
346
+ "scipy.sparse"). This will ensure that any matrices that result from
347
+ representing the object are returned in the appropriate matrix format.
348
+
349
+ Parameters
350
+ ==========
351
+
352
+ basis : Operator
353
+ The Operator whose basis functions will be used as the basis for
354
+ representation.
355
+ options : dict
356
+ A dictionary of key/value pairs that give options and hints for
357
+ the representation, such as the number of basis functions to
358
+ be used.
359
+ """
360
+ if basis is None:
361
+ result = self._represent_default_basis(**options)
362
+ else:
363
+ result = dispatch_method(self, '_represent', basis, **options)
364
+
365
+ # If we get a matrix representation, convert it to the right format.
366
+ format = options.get('format', 'sympy')
367
+ result = self._format_represent(result, format)
368
+ return result
369
+
370
+ def _format_represent(self, result, format):
371
+ if format == 'sympy' and not isinstance(result, Matrix):
372
+ return to_sympy(result)
373
+ elif format == 'numpy' and not isinstance(result, numpy_ndarray):
374
+ return to_numpy(result)
375
+ elif format == 'scipy.sparse' and \
376
+ not isinstance(result, scipy_sparse_matrix):
377
+ return to_scipy_sparse(result)
378
+
379
+ return result
380
+
381
+
382
+ def split_commutative_parts(e):
383
+ """Split into commutative and non-commutative parts."""
384
+ c_part, nc_part = e.args_cnc()
385
+ c_part = list(c_part)
386
+ return c_part, nc_part
387
+
388
+
389
+ def split_qexpr_parts(e):
390
+ """Split an expression into Expr and noncommutative QExpr parts."""
391
+ expr_part = []
392
+ qexpr_part = []
393
+ for arg in e.args:
394
+ if not isinstance(arg, QExpr):
395
+ expr_part.append(arg)
396
+ else:
397
+ qexpr_part.append(arg)
398
+ return expr_part, qexpr_part
399
+
400
+
401
+ def dispatch_method(self, basename, arg, **options):
402
+ """Dispatch a method to the proper handlers."""
403
+ method_name = '%s_%s' % (basename, arg.__class__.__name__)
404
+ if hasattr(self, method_name):
405
+ f = getattr(self, method_name)
406
+ # This can raise and we will allow it to propagate.
407
+ result = f(arg, **options)
408
+ if result is not None:
409
+ return result
410
+ raise NotImplementedError(
411
+ "%s.%s cannot handle: %r" %
412
+ (self.__class__.__name__, basename, arg)
413
+ )
wemm/lib/python3.10/site-packages/sympy/physics/quantum/state.py ADDED
@@ -0,0 +1,1017 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dirac notation for states."""
2
+
3
+ from sympy.core.cache import cacheit
4
+ from sympy.core.containers import Tuple
5
+ from sympy.core.expr import Expr
6
+ from sympy.core.function import Function
7
+ from sympy.core.numbers import oo, equal_valued
8
+ from sympy.core.singleton import S
9
+ from sympy.functions.elementary.complexes import conjugate
10
+ from sympy.functions.elementary.miscellaneous import sqrt
11
+ from sympy.integrals.integrals import integrate
12
+ from sympy.printing.pretty.stringpict import stringPict
13
+ from sympy.physics.quantum.qexpr import QExpr, dispatch_method
14
+
15
+ __all__ = [
16
+ 'KetBase',
17
+ 'BraBase',
18
+ 'StateBase',
19
+ 'State',
20
+ 'Ket',
21
+ 'Bra',
22
+ 'TimeDepState',
23
+ 'TimeDepBra',
24
+ 'TimeDepKet',
25
+ 'OrthogonalKet',
26
+ 'OrthogonalBra',
27
+ 'OrthogonalState',
28
+ 'Wavefunction'
29
+ ]
30
+
31
+
32
+ #-----------------------------------------------------------------------------
33
+ # States, bras and kets.
34
+ #-----------------------------------------------------------------------------
35
+
36
+ # ASCII brackets
37
+ _lbracket = "<"
38
+ _rbracket = ">"
39
+ _straight_bracket = "|"
40
+
41
+
42
+ # Unicode brackets
43
+ # MATHEMATICAL ANGLE BRACKETS
44
+ _lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}"
45
+ _rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}"
46
+ # LIGHT VERTICAL BAR
47
+ _straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}"
48
+
49
+ # Other options for unicode printing of <, > and | for Dirac notation.
50
+
51
+ # LEFT-POINTING ANGLE BRACKET
52
+ # _lbracket = "\u2329"
53
+ # _rbracket = "\u232A"
54
+
55
+ # LEFT ANGLE BRACKET
56
+ # _lbracket = "\u3008"
57
+ # _rbracket = "\u3009"
58
+
59
+ # VERTICAL LINE
60
+ # _straight_bracket = "\u007C"
61
+
62
+
63
+ class StateBase(QExpr):
64
+ """Abstract base class for general abstract states in quantum mechanics.
65
+
66
+ All other state classes defined will need to inherit from this class. It
67
+ carries the basic structure for all other states such as dual, _eval_adjoint
68
+ and label.
69
+
70
+ This is an abstract base class and you should not instantiate it directly,
71
+ instead use State.
72
+ """
73
+
74
+ @classmethod
75
+ def _operators_to_state(self, ops, **options):
76
+ """ Returns the eigenstate instance for the passed operators.
77
+
78
+ This method should be overridden in subclasses. It will handle being
79
+ passed either an Operator instance or set of Operator instances. It
80
+ should return the corresponding state INSTANCE or simply raise a
81
+ NotImplementedError. See cartesian.py for an example.
82
+ """
83
+
84
+ raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!")
85
+
86
+ def _state_to_operators(self, op_classes, **options):
87
+ """ Returns the operators which this state instance is an eigenstate
88
+ of.
89
+
90
+ This method should be overridden in subclasses. It will be called on
91
+ state instances and be passed the operator classes that we wish to make
92
+ into instances. The state instance will then transform the classes
93
+ appropriately, or raise a NotImplementedError if it cannot return
94
+ operator instances. See cartesian.py for examples,
95
+ """
96
+
97
+ raise NotImplementedError(
98
+ "Cannot map this state to operators. Method not implemented!")
99
+
100
+ @property
101
+ def operators(self):
102
+ """Return the operator(s) that this state is an eigenstate of"""
103
+ from .operatorset import state_to_operators # import internally to avoid circular import errors
104
+ return state_to_operators(self)
105
+
106
+ def _enumerate_state(self, num_states, **options):
107
+ raise NotImplementedError("Cannot enumerate this state!")
108
+
109
+ def _represent_default_basis(self, **options):
110
+ return self._represent(basis=self.operators)
111
+
112
+ def _apply_operator(self, op, **options):
113
+ return None
114
+
115
+ #-------------------------------------------------------------------------
116
+ # Dagger/dual
117
+ #-------------------------------------------------------------------------
118
+
119
+ @property
120
+ def dual(self):
121
+ """Return the dual state of this one."""
122
+ return self.dual_class()._new_rawargs(self.hilbert_space, *self.args)
123
+
124
+ @classmethod
125
+ def dual_class(self):
126
+ """Return the class used to construct the dual."""
127
+ raise NotImplementedError(
128
+ 'dual_class must be implemented in a subclass'
129
+ )
130
+
131
+ def _eval_adjoint(self):
132
+ """Compute the dagger of this state using the dual."""
133
+ return self.dual
134
+
135
+ #-------------------------------------------------------------------------
136
+ # Printing
137
+ #-------------------------------------------------------------------------
138
+
139
+ def _pretty_brackets(self, height, use_unicode=True):
140
+ # Return pretty printed brackets for the state
141
+ # Ideally, this could be done by pform.parens but it does not support the angled < and >
142
+
143
+ # Setup for unicode vs ascii
144
+ if use_unicode:
145
+ lbracket, rbracket = getattr(self, 'lbracket_ucode', ""), getattr(self, 'rbracket_ucode', "")
146
+ slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \
147
+ '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \
148
+ '\N{BOX DRAWINGS LIGHT VERTICAL}'
149
+ else:
150
+ lbracket, rbracket = getattr(self, 'lbracket', ""), getattr(self, 'rbracket', "")
151
+ slash, bslash, vert = '/', '\\', '|'
152
+
153
+ # If height is 1, just return brackets
154
+ if height == 1:
155
+ return stringPict(lbracket), stringPict(rbracket)
156
+ # Make height even
157
+ height += (height % 2)
158
+
159
+ brackets = []
160
+ for bracket in lbracket, rbracket:
161
+ # Create left bracket
162
+ if bracket in {_lbracket, _lbracket_ucode}:
163
+ bracket_args = [ ' ' * (height//2 - i - 1) +
164
+ slash for i in range(height // 2)]
165
+ bracket_args.extend(
166
+ [' ' * i + bslash for i in range(height // 2)])
167
+ # Create right bracket
168
+ elif bracket in {_rbracket, _rbracket_ucode}:
169
+ bracket_args = [ ' ' * i + bslash for i in range(height // 2)]
170
+ bracket_args.extend([ ' ' * (
171
+ height//2 - i - 1) + slash for i in range(height // 2)])
172
+ # Create straight bracket
173
+ elif bracket in {_straight_bracket, _straight_bracket_ucode}:
174
+ bracket_args = [vert] * height
175
+ else:
176
+ raise ValueError(bracket)
177
+ brackets.append(
178
+ stringPict('\n'.join(bracket_args), baseline=height//2))
179
+ return brackets
180
+
181
+ def _sympystr(self, printer, *args):
182
+ contents = self._print_contents(printer, *args)
183
+ return '%s%s%s' % (getattr(self, 'lbracket', ""), contents, getattr(self, 'rbracket', ""))
184
+
185
+ def _pretty(self, printer, *args):
186
+ from sympy.printing.pretty.stringpict import prettyForm
187
+ # Get brackets
188
+ pform = self._print_contents_pretty(printer, *args)
189
+ lbracket, rbracket = self._pretty_brackets(
190
+ pform.height(), printer._use_unicode)
191
+ # Put together state
192
+ pform = prettyForm(*pform.left(lbracket))
193
+ pform = prettyForm(*pform.right(rbracket))
194
+ return pform
195
+
196
+ def _latex(self, printer, *args):
197
+ contents = self._print_contents_latex(printer, *args)
198
+ # The extra {} brackets are needed to get matplotlib's latex
199
+ # rendered to render this properly.
200
+ return '{%s%s%s}' % (getattr(self, 'lbracket_latex', ""), contents, getattr(self, 'rbracket_latex', ""))
201
+
202
+
203
+ class KetBase(StateBase):
204
+ """Base class for Kets.
205
+
206
+ This class defines the dual property and the brackets for printing. This is
207
+ an abstract base class and you should not instantiate it directly, instead
208
+ use Ket.
209
+ """
210
+
211
+ lbracket = _straight_bracket
212
+ rbracket = _rbracket
213
+ lbracket_ucode = _straight_bracket_ucode
214
+ rbracket_ucode = _rbracket_ucode
215
+ lbracket_latex = r'\left|'
216
+ rbracket_latex = r'\right\rangle '
217
+
218
+ @classmethod
219
+ def default_args(self):
220
+ return ("psi",)
221
+
222
+ @classmethod
223
+ def dual_class(self):
224
+ return BraBase
225
+
226
+ def __mul__(self, other):
227
+ """KetBase*other"""
228
+ from sympy.physics.quantum.operator import OuterProduct
229
+ if isinstance(other, BraBase):
230
+ return OuterProduct(self, other)
231
+ else:
232
+ return Expr.__mul__(self, other)
233
+
234
+ def __rmul__(self, other):
235
+ """other*KetBase"""
236
+ from sympy.physics.quantum.innerproduct import InnerProduct
237
+ if isinstance(other, BraBase):
238
+ return InnerProduct(other, self)
239
+ else:
240
+ return Expr.__rmul__(self, other)
241
+
242
+ #-------------------------------------------------------------------------
243
+ # _eval_* methods
244
+ #-------------------------------------------------------------------------
245
+
246
+ def _eval_innerproduct(self, bra, **hints):
247
+ """Evaluate the inner product between this ket and a bra.
248
+
249
+ This is called to compute <bra|ket>, where the ket is ``self``.
250
+
251
+ This method will dispatch to sub-methods having the format::
252
+
253
+ ``def _eval_innerproduct_BraClass(self, **hints):``
254
+
255
+ Subclasses should define these methods (one for each BraClass) to
256
+ teach the ket how to take inner products with bras.
257
+ """
258
+ return dispatch_method(self, '_eval_innerproduct', bra, **hints)
259
+
260
+ def _apply_from_right_to(self, op, **options):
261
+ """Apply an Operator to this Ket as Operator*Ket
262
+
263
+ This method will dispatch to methods having the format::
264
+
265
+ ``def _apply_from_right_to_OperatorName(op, **options):``
266
+
267
+ Subclasses should define these methods (one for each OperatorName) to
268
+ teach the Ket how to implement OperatorName*Ket
269
+
270
+ Parameters
271
+ ==========
272
+
273
+ op : Operator
274
+ The Operator that is acting on the Ket as op*Ket
275
+ options : dict
276
+ A dict of key/value pairs that control how the operator is applied
277
+ to the Ket.
278
+ """
279
+ return dispatch_method(self, '_apply_from_right_to', op, **options)
280
+
281
+
282
+ class BraBase(StateBase):
283
+ """Base class for Bras.
284
+
285
+ This class defines the dual property and the brackets for printing. This
286
+ is an abstract base class and you should not instantiate it directly,
287
+ instead use Bra.
288
+ """
289
+
290
+ lbracket = _lbracket
291
+ rbracket = _straight_bracket
292
+ lbracket_ucode = _lbracket_ucode
293
+ rbracket_ucode = _straight_bracket_ucode
294
+ lbracket_latex = r'\left\langle '
295
+ rbracket_latex = r'\right|'
296
+
297
+ @classmethod
298
+ def _operators_to_state(self, ops, **options):
299
+ state = self.dual_class()._operators_to_state(ops, **options)
300
+ return state.dual
301
+
302
+ def _state_to_operators(self, op_classes, **options):
303
+ return self.dual._state_to_operators(op_classes, **options)
304
+
305
+ def _enumerate_state(self, num_states, **options):
306
+ dual_states = self.dual._enumerate_state(num_states, **options)
307
+ return [x.dual for x in dual_states]
308
+
309
+ @classmethod
310
+ def default_args(self):
311
+ return self.dual_class().default_args()
312
+
313
+ @classmethod
314
+ def dual_class(self):
315
+ return KetBase
316
+
317
+ def __mul__(self, other):
318
+ """BraBase*other"""
319
+ from sympy.physics.quantum.innerproduct import InnerProduct
320
+ if isinstance(other, KetBase):
321
+ return InnerProduct(self, other)
322
+ else:
323
+ return Expr.__mul__(self, other)
324
+
325
+ def __rmul__(self, other):
326
+ """other*BraBase"""
327
+ from sympy.physics.quantum.operator import OuterProduct
328
+ if isinstance(other, KetBase):
329
+ return OuterProduct(other, self)
330
+ else:
331
+ return Expr.__rmul__(self, other)
332
+
333
+ def _represent(self, **options):
334
+ """A default represent that uses the Ket's version."""
335
+ from sympy.physics.quantum.dagger import Dagger
336
+ return Dagger(self.dual._represent(**options))
337
+
338
+
339
+ class State(StateBase):
340
+ """General abstract quantum state used as a base class for Ket and Bra."""
341
+ pass
342
+
343
+
344
+ class Ket(State, KetBase):
345
+ """A general time-independent Ket in quantum mechanics.
346
+
347
+ Inherits from State and KetBase. This class should be used as the base
348
+ class for all physical, time-independent Kets in a system. This class
349
+ and its subclasses will be the main classes that users will use for
350
+ expressing Kets in Dirac notation [1]_.
351
+
352
+ Parameters
353
+ ==========
354
+
355
+ args : tuple
356
+ The list of numbers or parameters that uniquely specify the
357
+ ket. This will usually be its symbol or its quantum numbers. For
358
+ time-dependent state, this will include the time.
359
+
360
+ Examples
361
+ ========
362
+
363
+ Create a simple Ket and looking at its properties::
364
+
365
+ >>> from sympy.physics.quantum import Ket
366
+ >>> from sympy import symbols, I
367
+ >>> k = Ket('psi')
368
+ >>> k
369
+ |psi>
370
+ >>> k.hilbert_space
371
+ H
372
+ >>> k.is_commutative
373
+ False
374
+ >>> k.label
375
+ (psi,)
376
+
377
+ Ket's know about their associated bra::
378
+
379
+ >>> k.dual
380
+ <psi|
381
+ >>> k.dual_class()
382
+ <class 'sympy.physics.quantum.state.Bra'>
383
+
384
+ Take a linear combination of two kets::
385
+
386
+ >>> k0 = Ket(0)
387
+ >>> k1 = Ket(1)
388
+ >>> 2*I*k0 - 4*k1
389
+ 2*I*|0> - 4*|1>
390
+
391
+ Compound labels are passed as tuples::
392
+
393
+ >>> n, m = symbols('n,m')
394
+ >>> k = Ket(n,m)
395
+ >>> k
396
+ |nm>
397
+
398
+ References
399
+ ==========
400
+
401
+ .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
402
+ """
403
+
404
+ @classmethod
405
+ def dual_class(self):
406
+ return Bra
407
+
408
+
409
+ class Bra(State, BraBase):
410
+ """A general time-independent Bra in quantum mechanics.
411
+
412
+ Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This
413
+ class and its subclasses will be the main classes that users will use for
414
+ expressing Bras in Dirac notation.
415
+
416
+ Parameters
417
+ ==========
418
+
419
+ args : tuple
420
+ The list of numbers or parameters that uniquely specify the
421
+ ket. This will usually be its symbol or its quantum numbers. For
422
+ time-dependent state, this will include the time.
423
+
424
+ Examples
425
+ ========
426
+
427
+ Create a simple Bra and look at its properties::
428
+
429
+ >>> from sympy.physics.quantum import Bra
430
+ >>> from sympy import symbols, I
431
+ >>> b = Bra('psi')
432
+ >>> b
433
+ <psi|
434
+ >>> b.hilbert_space
435
+ H
436
+ >>> b.is_commutative
437
+ False
438
+
439
+ Bra's know about their dual Ket's::
440
+
441
+ >>> b.dual
442
+ |psi>
443
+ >>> b.dual_class()
444
+ <class 'sympy.physics.quantum.state.Ket'>
445
+
446
+ Like Kets, Bras can have compound labels and be manipulated in a similar
447
+ manner::
448
+
449
+ >>> n, m = symbols('n,m')
450
+ >>> b = Bra(n,m) - I*Bra(m,n)
451
+ >>> b
452
+ -I*<mn| + <nm|
453
+
454
+ Symbols in a Bra can be substituted using ``.subs``::
455
+
456
+ >>> b.subs(n,m)
457
+ <mm| - I*<mm|
458
+
459
+ References
460
+ ==========
461
+
462
+ .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
463
+ """
464
+
465
+ @classmethod
466
+ def dual_class(self):
467
+ return Ket
468
+
469
+ #-----------------------------------------------------------------------------
470
+ # Time dependent states, bras and kets.
471
+ #-----------------------------------------------------------------------------
472
+
473
+
474
+ class TimeDepState(StateBase):
475
+ """Base class for a general time-dependent quantum state.
476
+
477
+ This class is used as a base class for any time-dependent state. The main
478
+ difference between this class and the time-independent state is that this
479
+ class takes a second argument that is the time in addition to the usual
480
+ label argument.
481
+
482
+ Parameters
483
+ ==========
484
+
485
+ args : tuple
486
+ The list of numbers or parameters that uniquely specify the ket. This
487
+ will usually be its symbol or its quantum numbers. For time-dependent
488
+ state, this will include the time as the final argument.
489
+ """
490
+
491
+ #-------------------------------------------------------------------------
492
+ # Initialization
493
+ #-------------------------------------------------------------------------
494
+
495
+ @classmethod
496
+ def default_args(self):
497
+ return ("psi", "t")
498
+
499
+ #-------------------------------------------------------------------------
500
+ # Properties
501
+ #-------------------------------------------------------------------------
502
+
503
+ @property
504
+ def label(self):
505
+ """The label of the state."""
506
+ return self.args[:-1]
507
+
508
+ @property
509
+ def time(self):
510
+ """The time of the state."""
511
+ return self.args[-1]
512
+
513
+ #-------------------------------------------------------------------------
514
+ # Printing
515
+ #-------------------------------------------------------------------------
516
+
517
+ def _print_time(self, printer, *args):
518
+ return printer._print(self.time, *args)
519
+
520
+ _print_time_repr = _print_time
521
+ _print_time_latex = _print_time
522
+
523
+ def _print_time_pretty(self, printer, *args):
524
+ pform = printer._print(self.time, *args)
525
+ return pform
526
+
527
+ def _print_contents(self, printer, *args):
528
+ label = self._print_label(printer, *args)
529
+ time = self._print_time(printer, *args)
530
+ return '%s;%s' % (label, time)
531
+
532
+ def _print_label_repr(self, printer, *args):
533
+ label = self._print_sequence(self.label, ',', printer, *args)
534
+ time = self._print_time_repr(printer, *args)
535
+ return '%s,%s' % (label, time)
536
+
537
+ def _print_contents_pretty(self, printer, *args):
538
+ label = self._print_label_pretty(printer, *args)
539
+ time = self._print_time_pretty(printer, *args)
540
+ return printer._print_seq((label, time), delimiter=';')
541
+
542
+ def _print_contents_latex(self, printer, *args):
543
+ label = self._print_sequence(
544
+ self.label, self._label_separator, printer, *args)
545
+ time = self._print_time_latex(printer, *args)
546
+ return '%s;%s' % (label, time)
547
+
548
+
549
+ class TimeDepKet(TimeDepState, KetBase):
550
+ """General time-dependent Ket in quantum mechanics.
551
+
552
+ This inherits from ``TimeDepState`` and ``KetBase`` and is the main class
553
+ that should be used for Kets that vary with time. Its dual is a
554
+ ``TimeDepBra``.
555
+
556
+ Parameters
557
+ ==========
558
+
559
+ args : tuple
560
+ The list of numbers or parameters that uniquely specify the ket. This
561
+ will usually be its symbol or its quantum numbers. For time-dependent
562
+ state, this will include the time as the final argument.
563
+
564
+ Examples
565
+ ========
566
+
567
+ Create a TimeDepKet and look at its attributes::
568
+
569
+ >>> from sympy.physics.quantum import TimeDepKet
570
+ >>> k = TimeDepKet('psi', 't')
571
+ >>> k
572
+ |psi;t>
573
+ >>> k.time
574
+ t
575
+ >>> k.label
576
+ (psi,)
577
+ >>> k.hilbert_space
578
+ H
579
+
580
+ TimeDepKets know about their dual bra::
581
+
582
+ >>> k.dual
583
+ <psi;t|
584
+ >>> k.dual_class()
585
+ <class 'sympy.physics.quantum.state.TimeDepBra'>
586
+ """
587
+
588
+ @classmethod
589
+ def dual_class(self):
590
+ return TimeDepBra
591
+
592
+
593
+ class TimeDepBra(TimeDepState, BraBase):
594
+ """General time-dependent Bra in quantum mechanics.
595
+
596
+ This inherits from TimeDepState and BraBase and is the main class that
597
+ should be used for Bras that vary with time. Its dual is a TimeDepBra.
598
+
599
+ Parameters
600
+ ==========
601
+
602
+ args : tuple
603
+ The list of numbers or parameters that uniquely specify the ket. This
604
+ will usually be its symbol or its quantum numbers. For time-dependent
605
+ state, this will include the time as the final argument.
606
+
607
+ Examples
608
+ ========
609
+
610
+ >>> from sympy.physics.quantum import TimeDepBra
611
+ >>> b = TimeDepBra('psi', 't')
612
+ >>> b
613
+ <psi;t|
614
+ >>> b.time
615
+ t
616
+ >>> b.label
617
+ (psi,)
618
+ >>> b.hilbert_space
619
+ H
620
+ >>> b.dual
621
+ |psi;t>
622
+ """
623
+
624
+ @classmethod
625
+ def dual_class(self):
626
+ return TimeDepKet
627
+
628
+
629
+ class OrthogonalState(State, StateBase):
630
+ """General abstract quantum state used as a base class for Ket and Bra."""
631
+ pass
632
+
633
+ class OrthogonalKet(OrthogonalState, KetBase):
634
+ """Orthogonal Ket in quantum mechanics.
635
+
636
+ The inner product of two states with different labels will give zero,
637
+ states with the same label will give one.
638
+
639
+ >>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet
640
+ >>> from sympy.abc import m, n
641
+ >>> (OrthogonalBra(n)*OrthogonalKet(n)).doit()
642
+ 1
643
+ >>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit()
644
+ 0
645
+ >>> (OrthogonalBra(n)*OrthogonalKet(m)).doit()
646
+ <n|m>
647
+ """
648
+
649
+ @classmethod
650
+ def dual_class(self):
651
+ return OrthogonalBra
652
+
653
+ def _eval_innerproduct(self, bra, **hints):
654
+
655
+ if len(self.args) != len(bra.args):
656
+ raise ValueError('Cannot multiply a ket that has a different number of labels.')
657
+
658
+ for arg, bra_arg in zip(self.args, bra.args):
659
+ diff = arg - bra_arg
660
+ diff = diff.expand()
661
+
662
+ is_zero = diff.is_zero
663
+
664
+ if is_zero is False:
665
+ return S.Zero # i.e. Integer(0)
666
+
667
+ if is_zero is None:
668
+ return None
669
+
670
+ return S.One # i.e. Integer(1)
671
+
672
+
673
+ class OrthogonalBra(OrthogonalState, BraBase):
674
+ """Orthogonal Bra in quantum mechanics.
675
+ """
676
+
677
+ @classmethod
678
+ def dual_class(self):
679
+ return OrthogonalKet
680
+
681
+
682
+ class Wavefunction(Function):
683
+ """Class for representations in continuous bases
684
+
685
+ This class takes an expression and coordinates in its constructor. It can
686
+ be used to easily calculate normalizations and probabilities.
687
+
688
+ Parameters
689
+ ==========
690
+
691
+ expr : Expr
692
+ The expression representing the functional form of the w.f.
693
+
694
+ coords : Symbol or tuple
695
+ The coordinates to be integrated over, and their bounds
696
+
697
+ Examples
698
+ ========
699
+
700
+ Particle in a box, specifying bounds in the more primitive way of using
701
+ Piecewise:
702
+
703
+ >>> from sympy import Symbol, Piecewise, pi, N
704
+ >>> from sympy.functions import sqrt, sin
705
+ >>> from sympy.physics.quantum.state import Wavefunction
706
+ >>> x = Symbol('x', real=True)
707
+ >>> n = 1
708
+ >>> L = 1
709
+ >>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
710
+ >>> f = Wavefunction(g, x)
711
+ >>> f.norm
712
+ 1
713
+ >>> f.is_normalized
714
+ True
715
+ >>> p = f.prob()
716
+ >>> p(0)
717
+ 0
718
+ >>> p(L)
719
+ 0
720
+ >>> p(0.5)
721
+ 2
722
+ >>> p(0.85*L)
723
+ 2*sin(0.85*pi)**2
724
+ >>> N(p(0.85*L))
725
+ 0.412214747707527
726
+
727
+ Additionally, you can specify the bounds of the function and the indices in
728
+ a more compact way:
729
+
730
+ >>> from sympy import symbols, pi, diff
731
+ >>> from sympy.functions import sqrt, sin
732
+ >>> from sympy.physics.quantum.state import Wavefunction
733
+ >>> x, L = symbols('x,L', positive=True)
734
+ >>> n = symbols('n', integer=True, positive=True)
735
+ >>> g = sqrt(2/L)*sin(n*pi*x/L)
736
+ >>> f = Wavefunction(g, (x, 0, L))
737
+ >>> f.norm
738
+ 1
739
+ >>> f(L+1)
740
+ 0
741
+ >>> f(L-1)
742
+ sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L)
743
+ >>> f(-1)
744
+ 0
745
+ >>> f(0.85)
746
+ sqrt(2)*sin(0.85*pi*n/L)/sqrt(L)
747
+ >>> f(0.85, n=1, L=1)
748
+ sqrt(2)*sin(0.85*pi)
749
+ >>> f.is_commutative
750
+ False
751
+
752
+ All arguments are automatically sympified, so you can define the variables
753
+ as strings rather than symbols:
754
+
755
+ >>> expr = x**2
756
+ >>> f = Wavefunction(expr, 'x')
757
+ >>> type(f.variables[0])
758
+ <class 'sympy.core.symbol.Symbol'>
759
+
760
+ Derivatives of Wavefunctions will return Wavefunctions:
761
+
762
+ >>> diff(f, x)
763
+ Wavefunction(2*x, x)
764
+
765
+ """
766
+
767
+ #Any passed tuples for coordinates and their bounds need to be
768
+ #converted to Tuples before Function's constructor is called, to
769
+ #avoid errors from calling is_Float in the constructor
770
+ def __new__(cls, *args, **options):
771
+ new_args = [None for i in args]
772
+ ct = 0
773
+ for arg in args:
774
+ if isinstance(arg, tuple):
775
+ new_args[ct] = Tuple(*arg)
776
+ else:
777
+ new_args[ct] = arg
778
+ ct += 1
779
+
780
+ return super().__new__(cls, *new_args, **options)
781
+
782
+ def __call__(self, *args, **options):
783
+ var = self.variables
784
+
785
+ if len(args) != len(var):
786
+ raise NotImplementedError(
787
+ "Incorrect number of arguments to function!")
788
+
789
+ ct = 0
790
+ #If the passed value is outside the specified bounds, return 0
791
+ for v in var:
792
+ lower, upper = self.limits[v]
793
+
794
+ #Do the comparison to limits only if the passed symbol is actually
795
+ #a symbol present in the limits;
796
+ #Had problems with a comparison of x > L
797
+ if isinstance(args[ct], Expr) and \
798
+ not (lower in args[ct].free_symbols
799
+ or upper in args[ct].free_symbols):
800
+ continue
801
+
802
+ if (args[ct] < lower) == True or (args[ct] > upper) == True:
803
+ return S.Zero
804
+
805
+ ct += 1
806
+
807
+ expr = self.expr
808
+
809
+ #Allows user to make a call like f(2, 4, m=1, n=1)
810
+ for symbol in list(expr.free_symbols):
811
+ if str(symbol) in options.keys():
812
+ val = options[str(symbol)]
813
+ expr = expr.subs(symbol, val)
814
+
815
+ return expr.subs(zip(var, args))
816
+
817
+ def _eval_derivative(self, symbol):
818
+ expr = self.expr
819
+ deriv = expr._eval_derivative(symbol)
820
+
821
+ return Wavefunction(deriv, *self.args[1:])
822
+
823
+ def _eval_conjugate(self):
824
+ return Wavefunction(conjugate(self.expr), *self.args[1:])
825
+
826
+ def _eval_transpose(self):
827
+ return self
828
+
829
+ @property
830
+ def free_symbols(self):
831
+ return self.expr.free_symbols
832
+
833
+ @property
834
+ def is_commutative(self):
835
+ """
836
+ Override Function's is_commutative so that order is preserved in
837
+ represented expressions
838
+ """
839
+ return False
840
+
841
+ @classmethod
842
+ def eval(self, *args):
843
+ return None
844
+
845
+ @property
846
+ def variables(self):
847
+ """
848
+ Return the coordinates which the wavefunction depends on
849
+
850
+ Examples
851
+ ========
852
+
853
+ >>> from sympy.physics.quantum.state import Wavefunction
854
+ >>> from sympy import symbols
855
+ >>> x,y = symbols('x,y')
856
+ >>> f = Wavefunction(x*y, x, y)
857
+ >>> f.variables
858
+ (x, y)
859
+ >>> g = Wavefunction(x*y, x)
860
+ >>> g.variables
861
+ (x,)
862
+
863
+ """
864
+ var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]]
865
+ return tuple(var)
866
+
867
+ @property
868
+ def limits(self):
869
+ """
870
+ Return the limits of the coordinates which the w.f. depends on If no
871
+ limits are specified, defaults to ``(-oo, oo)``.
872
+
873
+ Examples
874
+ ========
875
+
876
+ >>> from sympy.physics.quantum.state import Wavefunction
877
+ >>> from sympy import symbols
878
+ >>> x, y = symbols('x, y')
879
+ >>> f = Wavefunction(x**2, (x, 0, 1))
880
+ >>> f.limits
881
+ {x: (0, 1)}
882
+ >>> f = Wavefunction(x**2, x)
883
+ >>> f.limits
884
+ {x: (-oo, oo)}
885
+ >>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2))
886
+ >>> f.limits
887
+ {x: (-oo, oo), y: (-1, 2)}
888
+
889
+ """
890
+ limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo)
891
+ for g in self._args[1:]]
892
+ return dict(zip(self.variables, tuple(limits)))
893
+
894
+ @property
895
+ def expr(self):
896
+ """
897
+ Return the expression which is the functional form of the Wavefunction
898
+
899
+ Examples
900
+ ========
901
+
902
+ >>> from sympy.physics.quantum.state import Wavefunction
903
+ >>> from sympy import symbols
904
+ >>> x, y = symbols('x, y')
905
+ >>> f = Wavefunction(x**2, x)
906
+ >>> f.expr
907
+ x**2
908
+
909
+ """
910
+ return self._args[0]
911
+
912
+ @property
913
+ def is_normalized(self):
914
+ """
915
+ Returns true if the Wavefunction is properly normalized
916
+
917
+ Examples
918
+ ========
919
+
920
+ >>> from sympy import symbols, pi
921
+ >>> from sympy.functions import sqrt, sin
922
+ >>> from sympy.physics.quantum.state import Wavefunction
923
+ >>> x, L = symbols('x,L', positive=True)
924
+ >>> n = symbols('n', integer=True, positive=True)
925
+ >>> g = sqrt(2/L)*sin(n*pi*x/L)
926
+ >>> f = Wavefunction(g, (x, 0, L))
927
+ >>> f.is_normalized
928
+ True
929
+
930
+ """
931
+
932
+ return equal_valued(self.norm, 1)
933
+
934
+ @property # type: ignore
935
+ @cacheit
936
+ def norm(self):
937
+ """
938
+ Return the normalization of the specified functional form.
939
+
940
+ This function integrates over the coordinates of the Wavefunction, with
941
+ the bounds specified.
942
+
943
+ Examples
944
+ ========
945
+
946
+ >>> from sympy import symbols, pi
947
+ >>> from sympy.functions import sqrt, sin
948
+ >>> from sympy.physics.quantum.state import Wavefunction
949
+ >>> x, L = symbols('x,L', positive=True)
950
+ >>> n = symbols('n', integer=True, positive=True)
951
+ >>> g = sqrt(2/L)*sin(n*pi*x/L)
952
+ >>> f = Wavefunction(g, (x, 0, L))
953
+ >>> f.norm
954
+ 1
955
+ >>> g = sin(n*pi*x/L)
956
+ >>> f = Wavefunction(g, (x, 0, L))
957
+ >>> f.norm
958
+ sqrt(2)*sqrt(L)/2
959
+
960
+ """
961
+
962
+ exp = self.expr*conjugate(self.expr)
963
+ var = self.variables
964
+ limits = self.limits
965
+
966
+ for v in var:
967
+ curr_limits = limits[v]
968
+ exp = integrate(exp, (v, curr_limits[0], curr_limits[1]))
969
+
970
+ return sqrt(exp)
971
+
972
+ def normalize(self):
973
+ """
974
+ Return a normalized version of the Wavefunction
975
+
976
+ Examples
977
+ ========
978
+
979
+ >>> from sympy import symbols, pi
980
+ >>> from sympy.functions import sin
981
+ >>> from sympy.physics.quantum.state import Wavefunction
982
+ >>> x = symbols('x', real=True)
983
+ >>> L = symbols('L', positive=True)
984
+ >>> n = symbols('n', integer=True, positive=True)
985
+ >>> g = sin(n*pi*x/L)
986
+ >>> f = Wavefunction(g, (x, 0, L))
987
+ >>> f.normalize()
988
+ Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L))
989
+
990
+ """
991
+ const = self.norm
992
+
993
+ if const is oo:
994
+ raise NotImplementedError("The function is not normalizable!")
995
+ else:
996
+ return Wavefunction((const)**(-1)*self.expr, *self.args[1:])
997
+
998
+ def prob(self):
999
+ r"""
1000
+ Return the absolute magnitude of the w.f., `|\psi(x)|^2`
1001
+
1002
+ Examples
1003
+ ========
1004
+
1005
+ >>> from sympy import symbols, pi
1006
+ >>> from sympy.functions import sin
1007
+ >>> from sympy.physics.quantum.state import Wavefunction
1008
+ >>> x, L = symbols('x,L', real=True)
1009
+ >>> n = symbols('n', integer=True)
1010
+ >>> g = sin(n*pi*x/L)
1011
+ >>> f = Wavefunction(g, (x, 0, L))
1012
+ >>> f.prob()
1013
+ Wavefunction(sin(pi*n*x/L)**2, x)
1014
+
1015
+ """
1016
+
1017
+ return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
wemm/lib/python3.10/site-packages/sympy/physics/secondquant.py ADDED
@@ -0,0 +1,3114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Second quantization operators and states for bosons.
3
+
4
+ This follow the formulation of Fetter and Welecka, "Quantum Theory
5
+ of Many-Particle Systems."
6
+ """
7
+ from collections import defaultdict
8
+
9
+ from sympy.core.add import Add
10
+ from sympy.core.basic import Basic
11
+ from sympy.core.cache import cacheit
12
+ from sympy.core.containers import Tuple
13
+ from sympy.core.expr import Expr
14
+ from sympy.core.function import Function
15
+ from sympy.core.mul import Mul
16
+ from sympy.core.numbers import I
17
+ from sympy.core.power import Pow
18
+ from sympy.core.singleton import S
19
+ from sympy.core.sorting import default_sort_key
20
+ from sympy.core.symbol import Dummy, Symbol
21
+ from sympy.core.sympify import sympify
22
+ from sympy.functions.elementary.miscellaneous import sqrt
23
+ from sympy.functions.special.tensor_functions import KroneckerDelta
24
+ from sympy.matrices.dense import zeros
25
+ from sympy.printing.str import StrPrinter
26
+ from sympy.utilities.iterables import has_dups
27
+
28
+ __all__ = [
29
+ 'Dagger',
30
+ 'KroneckerDelta',
31
+ 'BosonicOperator',
32
+ 'AnnihilateBoson',
33
+ 'CreateBoson',
34
+ 'AnnihilateFermion',
35
+ 'CreateFermion',
36
+ 'FockState',
37
+ 'FockStateBra',
38
+ 'FockStateKet',
39
+ 'FockStateBosonKet',
40
+ 'FockStateBosonBra',
41
+ 'FockStateFermionKet',
42
+ 'FockStateFermionBra',
43
+ 'BBra',
44
+ 'BKet',
45
+ 'FBra',
46
+ 'FKet',
47
+ 'F',
48
+ 'Fd',
49
+ 'B',
50
+ 'Bd',
51
+ 'apply_operators',
52
+ 'InnerProduct',
53
+ 'BosonicBasis',
54
+ 'VarBosonicBasis',
55
+ 'FixedBosonicBasis',
56
+ 'Commutator',
57
+ 'matrix_rep',
58
+ 'contraction',
59
+ 'wicks',
60
+ 'NO',
61
+ 'evaluate_deltas',
62
+ 'AntiSymmetricTensor',
63
+ 'substitute_dummies',
64
+ 'PermutationOperator',
65
+ 'simplify_index_permutations',
66
+ ]
67
+
68
+
69
+ class SecondQuantizationError(Exception):
70
+ pass
71
+
72
+
73
+ class AppliesOnlyToSymbolicIndex(SecondQuantizationError):
74
+ pass
75
+
76
+
77
+ class ContractionAppliesOnlyToFermions(SecondQuantizationError):
78
+ pass
79
+
80
+
81
+ class ViolationOfPauliPrinciple(SecondQuantizationError):
82
+ pass
83
+
84
+
85
+ class SubstitutionOfAmbigousOperatorFailed(SecondQuantizationError):
86
+ pass
87
+
88
+
89
+ class WicksTheoremDoesNotApply(SecondQuantizationError):
90
+ pass
91
+
92
+
93
+ class Dagger(Expr):
94
+ """
95
+ Hermitian conjugate of creation/annihilation operators.
96
+
97
+ Examples
98
+ ========
99
+
100
+ >>> from sympy import I
101
+ >>> from sympy.physics.secondquant import Dagger, B, Bd
102
+ >>> Dagger(2*I)
103
+ -2*I
104
+ >>> Dagger(B(0))
105
+ CreateBoson(0)
106
+ >>> Dagger(Bd(0))
107
+ AnnihilateBoson(0)
108
+
109
+ """
110
+
111
+ def __new__(cls, arg):
112
+ arg = sympify(arg)
113
+ r = cls.eval(arg)
114
+ if isinstance(r, Basic):
115
+ return r
116
+ obj = Basic.__new__(cls, arg)
117
+ return obj
118
+
119
+ @classmethod
120
+ def eval(cls, arg):
121
+ """
122
+ Evaluates the Dagger instance.
123
+
124
+ Examples
125
+ ========
126
+
127
+ >>> from sympy import I
128
+ >>> from sympy.physics.secondquant import Dagger, B, Bd
129
+ >>> Dagger(2*I)
130
+ -2*I
131
+ >>> Dagger(B(0))
132
+ CreateBoson(0)
133
+ >>> Dagger(Bd(0))
134
+ AnnihilateBoson(0)
135
+
136
+ The eval() method is called automatically.
137
+
138
+ """
139
+ dagger = getattr(arg, '_dagger_', None)
140
+ if dagger is not None:
141
+ return dagger()
142
+ if isinstance(arg, Basic):
143
+ if arg.is_Add:
144
+ return Add(*tuple(map(Dagger, arg.args)))
145
+ if arg.is_Mul:
146
+ return Mul(*tuple(map(Dagger, reversed(arg.args))))
147
+ if arg.is_Number:
148
+ return arg
149
+ if arg.is_Pow:
150
+ return Pow(Dagger(arg.args[0]), arg.args[1])
151
+ if arg == I:
152
+ return -arg
153
+ else:
154
+ return None
155
+
156
+ def _dagger_(self):
157
+ return self.args[0]
158
+
159
+
160
+ class TensorSymbol(Expr):
161
+
162
+ is_commutative = True
163
+
164
+
165
+ class AntiSymmetricTensor(TensorSymbol):
166
+ """Stores upper and lower indices in separate Tuple's.
167
+
168
+ Each group of indices is assumed to be antisymmetric.
169
+
170
+ Examples
171
+ ========
172
+
173
+ >>> from sympy import symbols
174
+ >>> from sympy.physics.secondquant import AntiSymmetricTensor
175
+ >>> i, j = symbols('i j', below_fermi=True)
176
+ >>> a, b = symbols('a b', above_fermi=True)
177
+ >>> AntiSymmetricTensor('v', (a, i), (b, j))
178
+ AntiSymmetricTensor(v, (a, i), (b, j))
179
+ >>> AntiSymmetricTensor('v', (i, a), (b, j))
180
+ -AntiSymmetricTensor(v, (a, i), (b, j))
181
+
182
+ As you can see, the indices are automatically sorted to a canonical form.
183
+
184
+ """
185
+
186
+ def __new__(cls, symbol, upper, lower):
187
+
188
+ try:
189
+ upper, signu = _sort_anticommuting_fermions(
190
+ upper, key=cls._sortkey)
191
+ lower, signl = _sort_anticommuting_fermions(
192
+ lower, key=cls._sortkey)
193
+
194
+ except ViolationOfPauliPrinciple:
195
+ return S.Zero
196
+
197
+ symbol = sympify(symbol)
198
+ upper = Tuple(*upper)
199
+ lower = Tuple(*lower)
200
+
201
+ if (signu + signl) % 2:
202
+ return -TensorSymbol.__new__(cls, symbol, upper, lower)
203
+ else:
204
+
205
+ return TensorSymbol.__new__(cls, symbol, upper, lower)
206
+
207
+ @classmethod
208
+ def _sortkey(cls, index):
209
+ """Key for sorting of indices.
210
+
211
+ particle < hole < general
212
+
213
+ FIXME: This is a bottle-neck, can we do it faster?
214
+ """
215
+ h = hash(index)
216
+ label = str(index)
217
+ if isinstance(index, Dummy):
218
+ if index.assumptions0.get('above_fermi'):
219
+ return (20, label, h)
220
+ elif index.assumptions0.get('below_fermi'):
221
+ return (21, label, h)
222
+ else:
223
+ return (22, label, h)
224
+
225
+ if index.assumptions0.get('above_fermi'):
226
+ return (10, label, h)
227
+ elif index.assumptions0.get('below_fermi'):
228
+ return (11, label, h)
229
+ else:
230
+ return (12, label, h)
231
+
232
+ def _latex(self, printer):
233
+ return "{%s^{%s}_{%s}}" % (
234
+ self.symbol,
235
+ "".join([ i.name for i in self.args[1]]),
236
+ "".join([ i.name for i in self.args[2]])
237
+ )
238
+
239
+ @property
240
+ def symbol(self):
241
+ """
242
+ Returns the symbol of the tensor.
243
+
244
+ Examples
245
+ ========
246
+
247
+ >>> from sympy import symbols
248
+ >>> from sympy.physics.secondquant import AntiSymmetricTensor
249
+ >>> i, j = symbols('i,j', below_fermi=True)
250
+ >>> a, b = symbols('a,b', above_fermi=True)
251
+ >>> AntiSymmetricTensor('v', (a, i), (b, j))
252
+ AntiSymmetricTensor(v, (a, i), (b, j))
253
+ >>> AntiSymmetricTensor('v', (a, i), (b, j)).symbol
254
+ v
255
+
256
+ """
257
+ return self.args[0]
258
+
259
+ @property
260
+ def upper(self):
261
+ """
262
+ Returns the upper indices.
263
+
264
+ Examples
265
+ ========
266
+
267
+ >>> from sympy import symbols
268
+ >>> from sympy.physics.secondquant import AntiSymmetricTensor
269
+ >>> i, j = symbols('i,j', below_fermi=True)
270
+ >>> a, b = symbols('a,b', above_fermi=True)
271
+ >>> AntiSymmetricTensor('v', (a, i), (b, j))
272
+ AntiSymmetricTensor(v, (a, i), (b, j))
273
+ >>> AntiSymmetricTensor('v', (a, i), (b, j)).upper
274
+ (a, i)
275
+
276
+
277
+ """
278
+ return self.args[1]
279
+
280
+ @property
281
+ def lower(self):
282
+ """
283
+ Returns the lower indices.
284
+
285
+ Examples
286
+ ========
287
+
288
+ >>> from sympy import symbols
289
+ >>> from sympy.physics.secondquant import AntiSymmetricTensor
290
+ >>> i, j = symbols('i,j', below_fermi=True)
291
+ >>> a, b = symbols('a,b', above_fermi=True)
292
+ >>> AntiSymmetricTensor('v', (a, i), (b, j))
293
+ AntiSymmetricTensor(v, (a, i), (b, j))
294
+ >>> AntiSymmetricTensor('v', (a, i), (b, j)).lower
295
+ (b, j)
296
+
297
+ """
298
+ return self.args[2]
299
+
300
+ def __str__(self):
301
+ return "%s(%s,%s)" % self.args
302
+
303
+
304
+ class SqOperator(Expr):
305
+ """
306
+ Base class for Second Quantization operators.
307
+ """
308
+
309
+ op_symbol = 'sq'
310
+
311
+ is_commutative = False
312
+
313
+ def __new__(cls, k):
314
+ obj = Basic.__new__(cls, sympify(k))
315
+ return obj
316
+
317
+ @property
318
+ def state(self):
319
+ """
320
+ Returns the state index related to this operator.
321
+
322
+ Examples
323
+ ========
324
+
325
+ >>> from sympy import Symbol
326
+ >>> from sympy.physics.secondquant import F, Fd, B, Bd
327
+ >>> p = Symbol('p')
328
+ >>> F(p).state
329
+ p
330
+ >>> Fd(p).state
331
+ p
332
+ >>> B(p).state
333
+ p
334
+ >>> Bd(p).state
335
+ p
336
+
337
+ """
338
+ return self.args[0]
339
+
340
+ @property
341
+ def is_symbolic(self):
342
+ """
343
+ Returns True if the state is a symbol (as opposed to a number).
344
+
345
+ Examples
346
+ ========
347
+
348
+ >>> from sympy import Symbol
349
+ >>> from sympy.physics.secondquant import F
350
+ >>> p = Symbol('p')
351
+ >>> F(p).is_symbolic
352
+ True
353
+ >>> F(1).is_symbolic
354
+ False
355
+
356
+ """
357
+ if self.state.is_Integer:
358
+ return False
359
+ else:
360
+ return True
361
+
362
+ def __repr__(self):
363
+ return NotImplemented
364
+
365
+ def __str__(self):
366
+ return "%s(%r)" % (self.op_symbol, self.state)
367
+
368
+ def apply_operator(self, state):
369
+ """
370
+ Applies an operator to itself.
371
+ """
372
+ raise NotImplementedError('implement apply_operator in a subclass')
373
+
374
+
375
+ class BosonicOperator(SqOperator):
376
+ pass
377
+
378
+
379
+ class Annihilator(SqOperator):
380
+ pass
381
+
382
+
383
+ class Creator(SqOperator):
384
+ pass
385
+
386
+
387
+ class AnnihilateBoson(BosonicOperator, Annihilator):
388
+ """
389
+ Bosonic annihilation operator.
390
+
391
+ Examples
392
+ ========
393
+
394
+ >>> from sympy.physics.secondquant import B
395
+ >>> from sympy.abc import x
396
+ >>> B(x)
397
+ AnnihilateBoson(x)
398
+ """
399
+
400
+ op_symbol = 'b'
401
+
402
+ def _dagger_(self):
403
+ return CreateBoson(self.state)
404
+
405
+ def apply_operator(self, state):
406
+ """
407
+ Apply state to self if self is not symbolic and state is a FockStateKet, else
408
+ multiply self by state.
409
+
410
+ Examples
411
+ ========
412
+
413
+ >>> from sympy.physics.secondquant import B, BKet
414
+ >>> from sympy.abc import x, y, n
415
+ >>> B(x).apply_operator(y)
416
+ y*AnnihilateBoson(x)
417
+ >>> B(0).apply_operator(BKet((n,)))
418
+ sqrt(n)*FockStateBosonKet((n - 1,))
419
+
420
+ """
421
+ if not self.is_symbolic and isinstance(state, FockStateKet):
422
+ element = self.state
423
+ amp = sqrt(state[element])
424
+ return amp*state.down(element)
425
+ else:
426
+ return Mul(self, state)
427
+
428
+ def __repr__(self):
429
+ return "AnnihilateBoson(%s)" % self.state
430
+
431
+ def _latex(self, printer):
432
+ if self.state is S.Zero:
433
+ return "b_{0}"
434
+ else:
435
+ return "b_{%s}" % self.state.name
436
+
437
+ class CreateBoson(BosonicOperator, Creator):
438
+ """
439
+ Bosonic creation operator.
440
+ """
441
+
442
+ op_symbol = 'b+'
443
+
444
+ def _dagger_(self):
445
+ return AnnihilateBoson(self.state)
446
+
447
+ def apply_operator(self, state):
448
+ """
449
+ Apply state to self if self is not symbolic and state is a FockStateKet, else
450
+ multiply self by state.
451
+
452
+ Examples
453
+ ========
454
+
455
+ >>> from sympy.physics.secondquant import B, Dagger, BKet
456
+ >>> from sympy.abc import x, y, n
457
+ >>> Dagger(B(x)).apply_operator(y)
458
+ y*CreateBoson(x)
459
+ >>> B(0).apply_operator(BKet((n,)))
460
+ sqrt(n)*FockStateBosonKet((n - 1,))
461
+ """
462
+ if not self.is_symbolic and isinstance(state, FockStateKet):
463
+ element = self.state
464
+ amp = sqrt(state[element] + 1)
465
+ return amp*state.up(element)
466
+ else:
467
+ return Mul(self, state)
468
+
469
+ def __repr__(self):
470
+ return "CreateBoson(%s)" % self.state
471
+
472
+ def _latex(self, printer):
473
+ if self.state is S.Zero:
474
+ return "{b^\\dagger_{0}}"
475
+ else:
476
+ return "{b^\\dagger_{%s}}" % self.state.name
477
+
478
+ B = AnnihilateBoson
479
+ Bd = CreateBoson
480
+
481
+
482
+ class FermionicOperator(SqOperator):
483
+
484
+ @property
485
+ def is_restricted(self):
486
+ """
487
+ Is this FermionicOperator restricted with respect to fermi level?
488
+
489
+ Returns
490
+ =======
491
+
492
+ 1 : restricted to orbits above fermi
493
+ 0 : no restriction
494
+ -1 : restricted to orbits below fermi
495
+
496
+ Examples
497
+ ========
498
+
499
+ >>> from sympy import Symbol
500
+ >>> from sympy.physics.secondquant import F, Fd
501
+ >>> a = Symbol('a', above_fermi=True)
502
+ >>> i = Symbol('i', below_fermi=True)
503
+ >>> p = Symbol('p')
504
+
505
+ >>> F(a).is_restricted
506
+ 1
507
+ >>> Fd(a).is_restricted
508
+ 1
509
+ >>> F(i).is_restricted
510
+ -1
511
+ >>> Fd(i).is_restricted
512
+ -1
513
+ >>> F(p).is_restricted
514
+ 0
515
+ >>> Fd(p).is_restricted
516
+ 0
517
+
518
+ """
519
+ ass = self.args[0].assumptions0
520
+ if ass.get("below_fermi"):
521
+ return -1
522
+ if ass.get("above_fermi"):
523
+ return 1
524
+ return 0
525
+
526
+ @property
527
+ def is_above_fermi(self):
528
+ """
529
+ Does the index of this FermionicOperator allow values above fermi?
530
+
531
+ Examples
532
+ ========
533
+
534
+ >>> from sympy import Symbol
535
+ >>> from sympy.physics.secondquant import F
536
+ >>> a = Symbol('a', above_fermi=True)
537
+ >>> i = Symbol('i', below_fermi=True)
538
+ >>> p = Symbol('p')
539
+
540
+ >>> F(a).is_above_fermi
541
+ True
542
+ >>> F(i).is_above_fermi
543
+ False
544
+ >>> F(p).is_above_fermi
545
+ True
546
+
547
+ Note
548
+ ====
549
+
550
+ The same applies to creation operators Fd
551
+
552
+ """
553
+ return not self.args[0].assumptions0.get("below_fermi")
554
+
555
+ @property
556
+ def is_below_fermi(self):
557
+ """
558
+ Does the index of this FermionicOperator allow values below fermi?
559
+
560
+ Examples
561
+ ========
562
+
563
+ >>> from sympy import Symbol
564
+ >>> from sympy.physics.secondquant import F
565
+ >>> a = Symbol('a', above_fermi=True)
566
+ >>> i = Symbol('i', below_fermi=True)
567
+ >>> p = Symbol('p')
568
+
569
+ >>> F(a).is_below_fermi
570
+ False
571
+ >>> F(i).is_below_fermi
572
+ True
573
+ >>> F(p).is_below_fermi
574
+ True
575
+
576
+ The same applies to creation operators Fd
577
+
578
+ """
579
+ return not self.args[0].assumptions0.get("above_fermi")
580
+
581
+ @property
582
+ def is_only_below_fermi(self):
583
+ """
584
+ Is the index of this FermionicOperator restricted to values below fermi?
585
+
586
+ Examples
587
+ ========
588
+
589
+ >>> from sympy import Symbol
590
+ >>> from sympy.physics.secondquant import F
591
+ >>> a = Symbol('a', above_fermi=True)
592
+ >>> i = Symbol('i', below_fermi=True)
593
+ >>> p = Symbol('p')
594
+
595
+ >>> F(a).is_only_below_fermi
596
+ False
597
+ >>> F(i).is_only_below_fermi
598
+ True
599
+ >>> F(p).is_only_below_fermi
600
+ False
601
+
602
+ The same applies to creation operators Fd
603
+ """
604
+ return self.is_below_fermi and not self.is_above_fermi
605
+
606
+ @property
607
+ def is_only_above_fermi(self):
608
+ """
609
+ Is the index of this FermionicOperator restricted to values above fermi?
610
+
611
+ Examples
612
+ ========
613
+
614
+ >>> from sympy import Symbol
615
+ >>> from sympy.physics.secondquant import F
616
+ >>> a = Symbol('a', above_fermi=True)
617
+ >>> i = Symbol('i', below_fermi=True)
618
+ >>> p = Symbol('p')
619
+
620
+ >>> F(a).is_only_above_fermi
621
+ True
622
+ >>> F(i).is_only_above_fermi
623
+ False
624
+ >>> F(p).is_only_above_fermi
625
+ False
626
+
627
+ The same applies to creation operators Fd
628
+ """
629
+ return self.is_above_fermi and not self.is_below_fermi
630
+
631
+ def _sortkey(self):
632
+ h = hash(self)
633
+ label = str(self.args[0])
634
+
635
+ if self.is_only_q_creator:
636
+ return 1, label, h
637
+ if self.is_only_q_annihilator:
638
+ return 4, label, h
639
+ if isinstance(self, Annihilator):
640
+ return 3, label, h
641
+ if isinstance(self, Creator):
642
+ return 2, label, h
643
+
644
+
645
+ class AnnihilateFermion(FermionicOperator, Annihilator):
646
+ """
647
+ Fermionic annihilation operator.
648
+ """
649
+
650
+ op_symbol = 'f'
651
+
652
+ def _dagger_(self):
653
+ return CreateFermion(self.state)
654
+
655
+ def apply_operator(self, state):
656
+ """
657
+ Apply state to self if self is not symbolic and state is a FockStateKet, else
658
+ multiply self by state.
659
+
660
+ Examples
661
+ ========
662
+
663
+ >>> from sympy.physics.secondquant import B, Dagger, BKet
664
+ >>> from sympy.abc import x, y, n
665
+ >>> Dagger(B(x)).apply_operator(y)
666
+ y*CreateBoson(x)
667
+ >>> B(0).apply_operator(BKet((n,)))
668
+ sqrt(n)*FockStateBosonKet((n - 1,))
669
+ """
670
+ if isinstance(state, FockStateFermionKet):
671
+ element = self.state
672
+ return state.down(element)
673
+
674
+ elif isinstance(state, Mul):
675
+ c_part, nc_part = state.args_cnc()
676
+ if isinstance(nc_part[0], FockStateFermionKet):
677
+ element = self.state
678
+ return Mul(*(c_part + [nc_part[0].down(element)] + nc_part[1:]))
679
+ else:
680
+ return Mul(self, state)
681
+
682
+ else:
683
+ return Mul(self, state)
684
+
685
+ @property
686
+ def is_q_creator(self):
687
+ """
688
+ Can we create a quasi-particle? (create hole or create particle)
689
+ If so, would that be above or below the fermi surface?
690
+
691
+ Examples
692
+ ========
693
+
694
+ >>> from sympy import Symbol
695
+ >>> from sympy.physics.secondquant import F
696
+ >>> a = Symbol('a', above_fermi=True)
697
+ >>> i = Symbol('i', below_fermi=True)
698
+ >>> p = Symbol('p')
699
+
700
+ >>> F(a).is_q_creator
701
+ 0
702
+ >>> F(i).is_q_creator
703
+ -1
704
+ >>> F(p).is_q_creator
705
+ -1
706
+
707
+ """
708
+ if self.is_below_fermi:
709
+ return -1
710
+ return 0
711
+
712
+ @property
713
+ def is_q_annihilator(self):
714
+ """
715
+ Can we destroy a quasi-particle? (annihilate hole or annihilate particle)
716
+ If so, would that be above or below the fermi surface?
717
+
718
+ Examples
719
+ ========
720
+
721
+ >>> from sympy import Symbol
722
+ >>> from sympy.physics.secondquant import F
723
+ >>> a = Symbol('a', above_fermi=1)
724
+ >>> i = Symbol('i', below_fermi=1)
725
+ >>> p = Symbol('p')
726
+
727
+ >>> F(a).is_q_annihilator
728
+ 1
729
+ >>> F(i).is_q_annihilator
730
+ 0
731
+ >>> F(p).is_q_annihilator
732
+ 1
733
+
734
+ """
735
+ if self.is_above_fermi:
736
+ return 1
737
+ return 0
738
+
739
+ @property
740
+ def is_only_q_creator(self):
741
+ """
742
+ Always create a quasi-particle? (create hole or create particle)
743
+
744
+ Examples
745
+ ========
746
+
747
+ >>> from sympy import Symbol
748
+ >>> from sympy.physics.secondquant import F
749
+ >>> a = Symbol('a', above_fermi=True)
750
+ >>> i = Symbol('i', below_fermi=True)
751
+ >>> p = Symbol('p')
752
+
753
+ >>> F(a).is_only_q_creator
754
+ False
755
+ >>> F(i).is_only_q_creator
756
+ True
757
+ >>> F(p).is_only_q_creator
758
+ False
759
+
760
+ """
761
+ return self.is_only_below_fermi
762
+
763
+ @property
764
+ def is_only_q_annihilator(self):
765
+ """
766
+ Always destroy a quasi-particle? (annihilate hole or annihilate particle)
767
+
768
+ Examples
769
+ ========
770
+
771
+ >>> from sympy import Symbol
772
+ >>> from sympy.physics.secondquant import F
773
+ >>> a = Symbol('a', above_fermi=True)
774
+ >>> i = Symbol('i', below_fermi=True)
775
+ >>> p = Symbol('p')
776
+
777
+ >>> F(a).is_only_q_annihilator
778
+ True
779
+ >>> F(i).is_only_q_annihilator
780
+ False
781
+ >>> F(p).is_only_q_annihilator
782
+ False
783
+
784
+ """
785
+ return self.is_only_above_fermi
786
+
787
+ def __repr__(self):
788
+ return "AnnihilateFermion(%s)" % self.state
789
+
790
+ def _latex(self, printer):
791
+ if self.state is S.Zero:
792
+ return "a_{0}"
793
+ else:
794
+ return "a_{%s}" % self.state.name
795
+
796
+
797
+ class CreateFermion(FermionicOperator, Creator):
798
+ """
799
+ Fermionic creation operator.
800
+ """
801
+
802
+ op_symbol = 'f+'
803
+
804
+ def _dagger_(self):
805
+ return AnnihilateFermion(self.state)
806
+
807
+ def apply_operator(self, state):
808
+ """
809
+ Apply state to self if self is not symbolic and state is a FockStateKet, else
810
+ multiply self by state.
811
+
812
+ Examples
813
+ ========
814
+
815
+ >>> from sympy.physics.secondquant import B, Dagger, BKet
816
+ >>> from sympy.abc import x, y, n
817
+ >>> Dagger(B(x)).apply_operator(y)
818
+ y*CreateBoson(x)
819
+ >>> B(0).apply_operator(BKet((n,)))
820
+ sqrt(n)*FockStateBosonKet((n - 1,))
821
+ """
822
+ if isinstance(state, FockStateFermionKet):
823
+ element = self.state
824
+ return state.up(element)
825
+
826
+ elif isinstance(state, Mul):
827
+ c_part, nc_part = state.args_cnc()
828
+ if isinstance(nc_part[0], FockStateFermionKet):
829
+ element = self.state
830
+ return Mul(*(c_part + [nc_part[0].up(element)] + nc_part[1:]))
831
+
832
+ return Mul(self, state)
833
+
834
+ @property
835
+ def is_q_creator(self):
836
+ """
837
+ Can we create a quasi-particle? (create hole or create particle)
838
+ If so, would that be above or below the fermi surface?
839
+
840
+ Examples
841
+ ========
842
+
843
+ >>> from sympy import Symbol
844
+ >>> from sympy.physics.secondquant import Fd
845
+ >>> a = Symbol('a', above_fermi=True)
846
+ >>> i = Symbol('i', below_fermi=True)
847
+ >>> p = Symbol('p')
848
+
849
+ >>> Fd(a).is_q_creator
850
+ 1
851
+ >>> Fd(i).is_q_creator
852
+ 0
853
+ >>> Fd(p).is_q_creator
854
+ 1
855
+
856
+ """
857
+ if self.is_above_fermi:
858
+ return 1
859
+ return 0
860
+
861
+ @property
862
+ def is_q_annihilator(self):
863
+ """
864
+ Can we destroy a quasi-particle? (annihilate hole or annihilate particle)
865
+ If so, would that be above or below the fermi surface?
866
+
867
+ Examples
868
+ ========
869
+
870
+ >>> from sympy import Symbol
871
+ >>> from sympy.physics.secondquant import Fd
872
+ >>> a = Symbol('a', above_fermi=1)
873
+ >>> i = Symbol('i', below_fermi=1)
874
+ >>> p = Symbol('p')
875
+
876
+ >>> Fd(a).is_q_annihilator
877
+ 0
878
+ >>> Fd(i).is_q_annihilator
879
+ -1
880
+ >>> Fd(p).is_q_annihilator
881
+ -1
882
+
883
+ """
884
+ if self.is_below_fermi:
885
+ return -1
886
+ return 0
887
+
888
+ @property
889
+ def is_only_q_creator(self):
890
+ """
891
+ Always create a quasi-particle? (create hole or create particle)
892
+
893
+ Examples
894
+ ========
895
+
896
+ >>> from sympy import Symbol
897
+ >>> from sympy.physics.secondquant import Fd
898
+ >>> a = Symbol('a', above_fermi=True)
899
+ >>> i = Symbol('i', below_fermi=True)
900
+ >>> p = Symbol('p')
901
+
902
+ >>> Fd(a).is_only_q_creator
903
+ True
904
+ >>> Fd(i).is_only_q_creator
905
+ False
906
+ >>> Fd(p).is_only_q_creator
907
+ False
908
+
909
+ """
910
+ return self.is_only_above_fermi
911
+
912
+ @property
913
+ def is_only_q_annihilator(self):
914
+ """
915
+ Always destroy a quasi-particle? (annihilate hole or annihilate particle)
916
+
917
+ Examples
918
+ ========
919
+
920
+ >>> from sympy import Symbol
921
+ >>> from sympy.physics.secondquant import Fd
922
+ >>> a = Symbol('a', above_fermi=True)
923
+ >>> i = Symbol('i', below_fermi=True)
924
+ >>> p = Symbol('p')
925
+
926
+ >>> Fd(a).is_only_q_annihilator
927
+ False
928
+ >>> Fd(i).is_only_q_annihilator
929
+ True
930
+ >>> Fd(p).is_only_q_annihilator
931
+ False
932
+
933
+ """
934
+ return self.is_only_below_fermi
935
+
936
+ def __repr__(self):
937
+ return "CreateFermion(%s)" % self.state
938
+
939
+ def _latex(self, printer):
940
+ if self.state is S.Zero:
941
+ return "{a^\\dagger_{0}}"
942
+ else:
943
+ return "{a^\\dagger_{%s}}" % self.state.name
944
+
945
+ Fd = CreateFermion
946
+ F = AnnihilateFermion
947
+
948
+
949
+ class FockState(Expr):
950
+ """
951
+ Many particle Fock state with a sequence of occupation numbers.
952
+
953
+ Anywhere you can have a FockState, you can also have S.Zero.
954
+ All code must check for this!
955
+
956
+ Base class to represent FockStates.
957
+ """
958
+ is_commutative = False
959
+
960
+ def __new__(cls, occupations):
961
+ """
962
+ occupations is a list with two possible meanings:
963
+
964
+ - For bosons it is a list of occupation numbers.
965
+ Element i is the number of particles in state i.
966
+
967
+ - For fermions it is a list of occupied orbits.
968
+ Element 0 is the state that was occupied first, element i
969
+ is the i'th occupied state.
970
+ """
971
+ occupations = list(map(sympify, occupations))
972
+ obj = Basic.__new__(cls, Tuple(*occupations))
973
+ return obj
974
+
975
+ def __getitem__(self, i):
976
+ i = int(i)
977
+ return self.args[0][i]
978
+
979
+ def __repr__(self):
980
+ return ("FockState(%r)") % (self.args)
981
+
982
+ def __str__(self):
983
+ return "%s%r%s" % (getattr(self, 'lbracket', ""), self._labels(), getattr(self, 'rbracket', ""))
984
+
985
+ def _labels(self):
986
+ return self.args[0]
987
+
988
+ def __len__(self):
989
+ return len(self.args[0])
990
+
991
+ def _latex(self, printer):
992
+ return "%s%s%s" % (getattr(self, 'lbracket_latex', ""), printer._print(self._labels()), getattr(self, 'rbracket_latex', ""))
993
+
994
+
995
+ class BosonState(FockState):
996
+ """
997
+ Base class for FockStateBoson(Ket/Bra).
998
+ """
999
+
1000
+ def up(self, i):
1001
+ """
1002
+ Performs the action of a creation operator.
1003
+
1004
+ Examples
1005
+ ========
1006
+
1007
+ >>> from sympy.physics.secondquant import BBra
1008
+ >>> b = BBra([1, 2])
1009
+ >>> b
1010
+ FockStateBosonBra((1, 2))
1011
+ >>> b.up(1)
1012
+ FockStateBosonBra((1, 3))
1013
+ """
1014
+ i = int(i)
1015
+ new_occs = list(self.args[0])
1016
+ new_occs[i] = new_occs[i] + S.One
1017
+ return self.__class__(new_occs)
1018
+
1019
+ def down(self, i):
1020
+ """
1021
+ Performs the action of an annihilation operator.
1022
+
1023
+ Examples
1024
+ ========
1025
+
1026
+ >>> from sympy.physics.secondquant import BBra
1027
+ >>> b = BBra([1, 2])
1028
+ >>> b
1029
+ FockStateBosonBra((1, 2))
1030
+ >>> b.down(1)
1031
+ FockStateBosonBra((1, 1))
1032
+ """
1033
+ i = int(i)
1034
+ new_occs = list(self.args[0])
1035
+ if new_occs[i] == S.Zero:
1036
+ return S.Zero
1037
+ else:
1038
+ new_occs[i] = new_occs[i] - S.One
1039
+ return self.__class__(new_occs)
1040
+
1041
+
1042
+ class FermionState(FockState):
1043
+ """
1044
+ Base class for FockStateFermion(Ket/Bra).
1045
+ """
1046
+
1047
+ fermi_level = 0
1048
+
1049
+ def __new__(cls, occupations, fermi_level=0):
1050
+ occupations = list(map(sympify, occupations))
1051
+ if len(occupations) > 1:
1052
+ try:
1053
+ (occupations, sign) = _sort_anticommuting_fermions(
1054
+ occupations, key=hash)
1055
+ except ViolationOfPauliPrinciple:
1056
+ return S.Zero
1057
+ else:
1058
+ sign = 0
1059
+
1060
+ cls.fermi_level = fermi_level
1061
+
1062
+ if cls._count_holes(occupations) > fermi_level:
1063
+ return S.Zero
1064
+
1065
+ if sign % 2:
1066
+ return S.NegativeOne*FockState.__new__(cls, occupations)
1067
+ else:
1068
+ return FockState.__new__(cls, occupations)
1069
+
1070
+ def up(self, i):
1071
+ """
1072
+ Performs the action of a creation operator.
1073
+
1074
+ Explanation
1075
+ ===========
1076
+
1077
+ If below fermi we try to remove a hole,
1078
+ if above fermi we try to create a particle.
1079
+
1080
+ If general index p we return ``Kronecker(p,i)*self``
1081
+ where ``i`` is a new symbol with restriction above or below.
1082
+
1083
+ Examples
1084
+ ========
1085
+
1086
+ >>> from sympy import Symbol
1087
+ >>> from sympy.physics.secondquant import FKet
1088
+ >>> a = Symbol('a', above_fermi=True)
1089
+ >>> i = Symbol('i', below_fermi=True)
1090
+ >>> p = Symbol('p')
1091
+
1092
+ >>> FKet([]).up(a)
1093
+ FockStateFermionKet((a,))
1094
+
1095
+ A creator acting on vacuum below fermi vanishes
1096
+
1097
+ >>> FKet([]).up(i)
1098
+ 0
1099
+
1100
+
1101
+ """
1102
+ present = i in self.args[0]
1103
+
1104
+ if self._only_above_fermi(i):
1105
+ if present:
1106
+ return S.Zero
1107
+ else:
1108
+ return self._add_orbit(i)
1109
+ elif self._only_below_fermi(i):
1110
+ if present:
1111
+ return self._remove_orbit(i)
1112
+ else:
1113
+ return S.Zero
1114
+ else:
1115
+ if present:
1116
+ hole = Dummy("i", below_fermi=True)
1117
+ return KroneckerDelta(i, hole)*self._remove_orbit(i)
1118
+ else:
1119
+ particle = Dummy("a", above_fermi=True)
1120
+ return KroneckerDelta(i, particle)*self._add_orbit(i)
1121
+
1122
+ def down(self, i):
1123
+ """
1124
+ Performs the action of an annihilation operator.
1125
+
1126
+ Explanation
1127
+ ===========
1128
+
1129
+ If below fermi we try to create a hole,
1130
+ If above fermi we try to remove a particle.
1131
+
1132
+ If general index p we return ``Kronecker(p,i)*self``
1133
+ where ``i`` is a new symbol with restriction above or below.
1134
+
1135
+ Examples
1136
+ ========
1137
+
1138
+ >>> from sympy import Symbol
1139
+ >>> from sympy.physics.secondquant import FKet
1140
+ >>> a = Symbol('a', above_fermi=True)
1141
+ >>> i = Symbol('i', below_fermi=True)
1142
+ >>> p = Symbol('p')
1143
+
1144
+ An annihilator acting on vacuum above fermi vanishes
1145
+
1146
+ >>> FKet([]).down(a)
1147
+ 0
1148
+
1149
+ Also below fermi, it vanishes, unless we specify a fermi level > 0
1150
+
1151
+ >>> FKet([]).down(i)
1152
+ 0
1153
+ >>> FKet([],4).down(i)
1154
+ FockStateFermionKet((i,))
1155
+
1156
+ """
1157
+ present = i in self.args[0]
1158
+
1159
+ if self._only_above_fermi(i):
1160
+ if present:
1161
+ return self._remove_orbit(i)
1162
+ else:
1163
+ return S.Zero
1164
+
1165
+ elif self._only_below_fermi(i):
1166
+ if present:
1167
+ return S.Zero
1168
+ else:
1169
+ return self._add_orbit(i)
1170
+ else:
1171
+ if present:
1172
+ hole = Dummy("i", below_fermi=True)
1173
+ return KroneckerDelta(i, hole)*self._add_orbit(i)
1174
+ else:
1175
+ particle = Dummy("a", above_fermi=True)
1176
+ return KroneckerDelta(i, particle)*self._remove_orbit(i)
1177
+
1178
+ @classmethod
1179
+ def _only_below_fermi(cls, i):
1180
+ """
1181
+ Tests if given orbit is only below fermi surface.
1182
+
1183
+ If nothing can be concluded we return a conservative False.
1184
+ """
1185
+ if i.is_number:
1186
+ return i <= cls.fermi_level
1187
+ if i.assumptions0.get('below_fermi'):
1188
+ return True
1189
+ return False
1190
+
1191
+ @classmethod
1192
+ def _only_above_fermi(cls, i):
1193
+ """
1194
+ Tests if given orbit is only above fermi surface.
1195
+
1196
+ If fermi level has not been set we return True.
1197
+ If nothing can be concluded we return a conservative False.
1198
+ """
1199
+ if i.is_number:
1200
+ return i > cls.fermi_level
1201
+ if i.assumptions0.get('above_fermi'):
1202
+ return True
1203
+ return not cls.fermi_level
1204
+
1205
+ def _remove_orbit(self, i):
1206
+ """
1207
+ Removes particle/fills hole in orbit i. No input tests performed here.
1208
+ """
1209
+ new_occs = list(self.args[0])
1210
+ pos = new_occs.index(i)
1211
+ del new_occs[pos]
1212
+ if (pos) % 2:
1213
+ return S.NegativeOne*self.__class__(new_occs, self.fermi_level)
1214
+ else:
1215
+ return self.__class__(new_occs, self.fermi_level)
1216
+
1217
+ def _add_orbit(self, i):
1218
+ """
1219
+ Adds particle/creates hole in orbit i. No input tests performed here.
1220
+ """
1221
+ return self.__class__((i,) + self.args[0], self.fermi_level)
1222
+
1223
+ @classmethod
1224
+ def _count_holes(cls, list):
1225
+ """
1226
+ Returns the number of identified hole states in list.
1227
+ """
1228
+ return len([i for i in list if cls._only_below_fermi(i)])
1229
+
1230
+ def _negate_holes(self, list):
1231
+ return tuple([-i if i <= self.fermi_level else i for i in list])
1232
+
1233
+ def __repr__(self):
1234
+ if self.fermi_level:
1235
+ return "FockStateKet(%r, fermi_level=%s)" % (self.args[0], self.fermi_level)
1236
+ else:
1237
+ return "FockStateKet(%r)" % (self.args[0],)
1238
+
1239
+ def _labels(self):
1240
+ return self._negate_holes(self.args[0])
1241
+
1242
+
1243
+ class FockStateKet(FockState):
1244
+ """
1245
+ Representation of a ket.
1246
+ """
1247
+ lbracket = '|'
1248
+ rbracket = '>'
1249
+ lbracket_latex = r'\left|'
1250
+ rbracket_latex = r'\right\rangle'
1251
+
1252
+
1253
+ class FockStateBra(FockState):
1254
+ """
1255
+ Representation of a bra.
1256
+ """
1257
+ lbracket = '<'
1258
+ rbracket = '|'
1259
+ lbracket_latex = r'\left\langle'
1260
+ rbracket_latex = r'\right|'
1261
+
1262
+ def __mul__(self, other):
1263
+ if isinstance(other, FockStateKet):
1264
+ return InnerProduct(self, other)
1265
+ else:
1266
+ return Expr.__mul__(self, other)
1267
+
1268
+
1269
+ class FockStateBosonKet(BosonState, FockStateKet):
1270
+ """
1271
+ Many particle Fock state with a sequence of occupation numbers.
1272
+
1273
+ Occupation numbers can be any integer >= 0.
1274
+
1275
+ Examples
1276
+ ========
1277
+
1278
+ >>> from sympy.physics.secondquant import BKet
1279
+ >>> BKet([1, 2])
1280
+ FockStateBosonKet((1, 2))
1281
+ """
1282
+ def _dagger_(self):
1283
+ return FockStateBosonBra(*self.args)
1284
+
1285
+
1286
+ class FockStateBosonBra(BosonState, FockStateBra):
1287
+ """
1288
+ Describes a collection of BosonBra particles.
1289
+
1290
+ Examples
1291
+ ========
1292
+
1293
+ >>> from sympy.physics.secondquant import BBra
1294
+ >>> BBra([1, 2])
1295
+ FockStateBosonBra((1, 2))
1296
+ """
1297
+ def _dagger_(self):
1298
+ return FockStateBosonKet(*self.args)
1299
+
1300
+
1301
+ class FockStateFermionKet(FermionState, FockStateKet):
1302
+ """
1303
+ Many-particle Fock state with a sequence of occupied orbits.
1304
+
1305
+ Explanation
1306
+ ===========
1307
+
1308
+ Each state can only have one particle, so we choose to store a list of
1309
+ occupied orbits rather than a tuple with occupation numbers (zeros and ones).
1310
+
1311
+ states below fermi level are holes, and are represented by negative labels
1312
+ in the occupation list.
1313
+
1314
+ For symbolic state labels, the fermi_level caps the number of allowed hole-
1315
+ states.
1316
+
1317
+ Examples
1318
+ ========
1319
+
1320
+ >>> from sympy.physics.secondquant import FKet
1321
+ >>> FKet([1, 2])
1322
+ FockStateFermionKet((1, 2))
1323
+ """
1324
+ def _dagger_(self):
1325
+ return FockStateFermionBra(*self.args)
1326
+
1327
+
1328
+ class FockStateFermionBra(FermionState, FockStateBra):
1329
+ """
1330
+ See Also
1331
+ ========
1332
+
1333
+ FockStateFermionKet
1334
+
1335
+ Examples
1336
+ ========
1337
+
1338
+ >>> from sympy.physics.secondquant import FBra
1339
+ >>> FBra([1, 2])
1340
+ FockStateFermionBra((1, 2))
1341
+ """
1342
+ def _dagger_(self):
1343
+ return FockStateFermionKet(*self.args)
1344
+
1345
+ BBra = FockStateBosonBra
1346
+ BKet = FockStateBosonKet
1347
+ FBra = FockStateFermionBra
1348
+ FKet = FockStateFermionKet
1349
+
1350
+
1351
+ def _apply_Mul(m):
1352
+ """
1353
+ Take a Mul instance with operators and apply them to states.
1354
+
1355
+ Explanation
1356
+ ===========
1357
+
1358
+ This method applies all operators with integer state labels
1359
+ to the actual states. For symbolic state labels, nothing is done.
1360
+ When inner products of FockStates are encountered (like <a|b>),
1361
+ they are converted to instances of InnerProduct.
1362
+
1363
+ This does not currently work on double inner products like,
1364
+ <a|b><c|d>.
1365
+
1366
+ If the argument is not a Mul, it is simply returned as is.
1367
+ """
1368
+ if not isinstance(m, Mul):
1369
+ return m
1370
+ c_part, nc_part = m.args_cnc()
1371
+ n_nc = len(nc_part)
1372
+ if n_nc in (0, 1):
1373
+ return m
1374
+ else:
1375
+ last = nc_part[-1]
1376
+ next_to_last = nc_part[-2]
1377
+ if isinstance(last, FockStateKet):
1378
+ if isinstance(next_to_last, SqOperator):
1379
+ if next_to_last.is_symbolic:
1380
+ return m
1381
+ else:
1382
+ result = next_to_last.apply_operator(last)
1383
+ if result == 0:
1384
+ return S.Zero
1385
+ else:
1386
+ return _apply_Mul(Mul(*(c_part + nc_part[:-2] + [result])))
1387
+ elif isinstance(next_to_last, Pow):
1388
+ if isinstance(next_to_last.base, SqOperator) and \
1389
+ next_to_last.exp.is_Integer:
1390
+ if next_to_last.base.is_symbolic:
1391
+ return m
1392
+ else:
1393
+ result = last
1394
+ for i in range(next_to_last.exp):
1395
+ result = next_to_last.base.apply_operator(result)
1396
+ if result == 0:
1397
+ break
1398
+ if result == 0:
1399
+ return S.Zero
1400
+ else:
1401
+ return _apply_Mul(Mul(*(c_part + nc_part[:-2] + [result])))
1402
+ else:
1403
+ return m
1404
+ elif isinstance(next_to_last, FockStateBra):
1405
+ result = InnerProduct(next_to_last, last)
1406
+ if result == 0:
1407
+ return S.Zero
1408
+ else:
1409
+ return _apply_Mul(Mul(*(c_part + nc_part[:-2] + [result])))
1410
+ else:
1411
+ return m
1412
+ else:
1413
+ return m
1414
+
1415
+
1416
+ def apply_operators(e):
1417
+ """
1418
+ Take a SymPy expression with operators and states and apply the operators.
1419
+
1420
+ Examples
1421
+ ========
1422
+
1423
+ >>> from sympy.physics.secondquant import apply_operators
1424
+ >>> from sympy import sympify
1425
+ >>> apply_operators(sympify(3)+4)
1426
+ 7
1427
+ """
1428
+ e = e.expand()
1429
+ muls = e.atoms(Mul)
1430
+ subs_list = [(m, _apply_Mul(m)) for m in iter(muls)]
1431
+ return e.subs(subs_list)
1432
+
1433
+
1434
+ class InnerProduct(Basic):
1435
+ """
1436
+ An unevaluated inner product between a bra and ket.
1437
+
1438
+ Explanation
1439
+ ===========
1440
+
1441
+ Currently this class just reduces things to a product of
1442
+ Kronecker Deltas. In the future, we could introduce abstract
1443
+ states like ``|a>`` and ``|b>``, and leave the inner product unevaluated as
1444
+ ``<a|b>``.
1445
+
1446
+ """
1447
+ is_commutative = True
1448
+
1449
+ def __new__(cls, bra, ket):
1450
+ if not isinstance(bra, FockStateBra):
1451
+ raise TypeError("must be a bra")
1452
+ if not isinstance(ket, FockStateKet):
1453
+ raise TypeError("must be a ket")
1454
+ return cls.eval(bra, ket)
1455
+
1456
+ @classmethod
1457
+ def eval(cls, bra, ket):
1458
+ result = S.One
1459
+ for i, j in zip(bra.args[0], ket.args[0]):
1460
+ result *= KroneckerDelta(i, j)
1461
+ if result == 0:
1462
+ break
1463
+ return result
1464
+
1465
+ @property
1466
+ def bra(self):
1467
+ """Returns the bra part of the state"""
1468
+ return self.args[0]
1469
+
1470
+ @property
1471
+ def ket(self):
1472
+ """Returns the ket part of the state"""
1473
+ return self.args[1]
1474
+
1475
+ def __repr__(self):
1476
+ sbra = repr(self.bra)
1477
+ sket = repr(self.ket)
1478
+ return "%s|%s" % (sbra[:-1], sket[1:])
1479
+
1480
+ def __str__(self):
1481
+ return self.__repr__()
1482
+
1483
+
1484
+ def matrix_rep(op, basis):
1485
+ """
1486
+ Find the representation of an operator in a basis.
1487
+
1488
+ Examples
1489
+ ========
1490
+
1491
+ >>> from sympy.physics.secondquant import VarBosonicBasis, B, matrix_rep
1492
+ >>> b = VarBosonicBasis(5)
1493
+ >>> o = B(0)
1494
+ >>> matrix_rep(o, b)
1495
+ Matrix([
1496
+ [0, 1, 0, 0, 0],
1497
+ [0, 0, sqrt(2), 0, 0],
1498
+ [0, 0, 0, sqrt(3), 0],
1499
+ [0, 0, 0, 0, 2],
1500
+ [0, 0, 0, 0, 0]])
1501
+ """
1502
+ a = zeros(len(basis))
1503
+ for i in range(len(basis)):
1504
+ for j in range(len(basis)):
1505
+ a[i, j] = apply_operators(Dagger(basis[i])*op*basis[j])
1506
+ return a
1507
+
1508
+
1509
+ class BosonicBasis:
1510
+ """
1511
+ Base class for a basis set of bosonic Fock states.
1512
+ """
1513
+ pass
1514
+
1515
+
1516
+ class VarBosonicBasis:
1517
+ """
1518
+ A single state, variable particle number basis set.
1519
+
1520
+ Examples
1521
+ ========
1522
+
1523
+ >>> from sympy.physics.secondquant import VarBosonicBasis
1524
+ >>> b = VarBosonicBasis(5)
1525
+ >>> b
1526
+ [FockState((0,)), FockState((1,)), FockState((2,)),
1527
+ FockState((3,)), FockState((4,))]
1528
+ """
1529
+
1530
+ def __init__(self, n_max):
1531
+ self.n_max = n_max
1532
+ self._build_states()
1533
+
1534
+ def _build_states(self):
1535
+ self.basis = []
1536
+ for i in range(self.n_max):
1537
+ self.basis.append(FockStateBosonKet([i]))
1538
+ self.n_basis = len(self.basis)
1539
+
1540
+ def index(self, state):
1541
+ """
1542
+ Returns the index of state in basis.
1543
+
1544
+ Examples
1545
+ ========
1546
+
1547
+ >>> from sympy.physics.secondquant import VarBosonicBasis
1548
+ >>> b = VarBosonicBasis(3)
1549
+ >>> state = b.state(1)
1550
+ >>> b
1551
+ [FockState((0,)), FockState((1,)), FockState((2,))]
1552
+ >>> state
1553
+ FockStateBosonKet((1,))
1554
+ >>> b.index(state)
1555
+ 1
1556
+ """
1557
+ return self.basis.index(state)
1558
+
1559
+ def state(self, i):
1560
+ """
1561
+ The state of a single basis.
1562
+
1563
+ Examples
1564
+ ========
1565
+
1566
+ >>> from sympy.physics.secondquant import VarBosonicBasis
1567
+ >>> b = VarBosonicBasis(5)
1568
+ >>> b.state(3)
1569
+ FockStateBosonKet((3,))
1570
+ """
1571
+ return self.basis[i]
1572
+
1573
+ def __getitem__(self, i):
1574
+ return self.state(i)
1575
+
1576
+ def __len__(self):
1577
+ return len(self.basis)
1578
+
1579
+ def __repr__(self):
1580
+ return repr(self.basis)
1581
+
1582
+
1583
+ class FixedBosonicBasis(BosonicBasis):
1584
+ """
1585
+ Fixed particle number basis set.
1586
+
1587
+ Examples
1588
+ ========
1589
+
1590
+ >>> from sympy.physics.secondquant import FixedBosonicBasis
1591
+ >>> b = FixedBosonicBasis(2, 2)
1592
+ >>> state = b.state(1)
1593
+ >>> b
1594
+ [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]
1595
+ >>> state
1596
+ FockStateBosonKet((1, 1))
1597
+ >>> b.index(state)
1598
+ 1
1599
+ """
1600
+ def __init__(self, n_particles, n_levels):
1601
+ self.n_particles = n_particles
1602
+ self.n_levels = n_levels
1603
+ self._build_particle_locations()
1604
+ self._build_states()
1605
+
1606
+ def _build_particle_locations(self):
1607
+ tup = ["i%i" % i for i in range(self.n_particles)]
1608
+ first_loop = "for i0 in range(%i)" % self.n_levels
1609
+ other_loops = ''
1610
+ for cur, prev in zip(tup[1:], tup):
1611
+ temp = "for %s in range(%s + 1) " % (cur, prev)
1612
+ other_loops = other_loops + temp
1613
+ tup_string = "(%s)" % ", ".join(tup)
1614
+ list_comp = "[%s %s %s]" % (tup_string, first_loop, other_loops)
1615
+ result = eval(list_comp)
1616
+ if self.n_particles == 1:
1617
+ result = [(item,) for item in result]
1618
+ self.particle_locations = result
1619
+
1620
+ def _build_states(self):
1621
+ self.basis = []
1622
+ for tuple_of_indices in self.particle_locations:
1623
+ occ_numbers = self.n_levels*[0]
1624
+ for level in tuple_of_indices:
1625
+ occ_numbers[level] += 1
1626
+ self.basis.append(FockStateBosonKet(occ_numbers))
1627
+ self.n_basis = len(self.basis)
1628
+
1629
+ def index(self, state):
1630
+ """Returns the index of state in basis.
1631
+
1632
+ Examples
1633
+ ========
1634
+
1635
+ >>> from sympy.physics.secondquant import FixedBosonicBasis
1636
+ >>> b = FixedBosonicBasis(2, 3)
1637
+ >>> b.index(b.state(3))
1638
+ 3
1639
+ """
1640
+ return self.basis.index(state)
1641
+
1642
+ def state(self, i):
1643
+ """Returns the state that lies at index i of the basis
1644
+
1645
+ Examples
1646
+ ========
1647
+
1648
+ >>> from sympy.physics.secondquant import FixedBosonicBasis
1649
+ >>> b = FixedBosonicBasis(2, 3)
1650
+ >>> b.state(3)
1651
+ FockStateBosonKet((1, 0, 1))
1652
+ """
1653
+ return self.basis[i]
1654
+
1655
+ def __getitem__(self, i):
1656
+ return self.state(i)
1657
+
1658
+ def __len__(self):
1659
+ return len(self.basis)
1660
+
1661
+ def __repr__(self):
1662
+ return repr(self.basis)
1663
+
1664
+
1665
+ class Commutator(Function):
1666
+ """
1667
+ The Commutator: [A, B] = A*B - B*A
1668
+
1669
+ The arguments are ordered according to .__cmp__()
1670
+
1671
+ Examples
1672
+ ========
1673
+
1674
+ >>> from sympy import symbols
1675
+ >>> from sympy.physics.secondquant import Commutator
1676
+ >>> A, B = symbols('A,B', commutative=False)
1677
+ >>> Commutator(B, A)
1678
+ -Commutator(A, B)
1679
+
1680
+ Evaluate the commutator with .doit()
1681
+
1682
+ >>> comm = Commutator(A,B); comm
1683
+ Commutator(A, B)
1684
+ >>> comm.doit()
1685
+ A*B - B*A
1686
+
1687
+
1688
+ For two second quantization operators the commutator is evaluated
1689
+ immediately:
1690
+
1691
+ >>> from sympy.physics.secondquant import Fd, F
1692
+ >>> a = symbols('a', above_fermi=True)
1693
+ >>> i = symbols('i', below_fermi=True)
1694
+ >>> p,q = symbols('p,q')
1695
+
1696
+ >>> Commutator(Fd(a),Fd(i))
1697
+ 2*NO(CreateFermion(a)*CreateFermion(i))
1698
+
1699
+ But for more complicated expressions, the evaluation is triggered by
1700
+ a call to .doit()
1701
+
1702
+ >>> comm = Commutator(Fd(p)*Fd(q),F(i)); comm
1703
+ Commutator(CreateFermion(p)*CreateFermion(q), AnnihilateFermion(i))
1704
+ >>> comm.doit(wicks=True)
1705
+ -KroneckerDelta(i, p)*CreateFermion(q) +
1706
+ KroneckerDelta(i, q)*CreateFermion(p)
1707
+
1708
+ """
1709
+
1710
+ is_commutative = False
1711
+
1712
+ @classmethod
1713
+ def eval(cls, a, b):
1714
+ """
1715
+ The Commutator [A,B] is on canonical form if A < B.
1716
+
1717
+ Examples
1718
+ ========
1719
+
1720
+ >>> from sympy.physics.secondquant import Commutator, F, Fd
1721
+ >>> from sympy.abc import x
1722
+ >>> c1 = Commutator(F(x), Fd(x))
1723
+ >>> c2 = Commutator(Fd(x), F(x))
1724
+ >>> Commutator.eval(c1, c2)
1725
+ 0
1726
+ """
1727
+ if not (a and b):
1728
+ return S.Zero
1729
+ if a == b:
1730
+ return S.Zero
1731
+ if a.is_commutative or b.is_commutative:
1732
+ return S.Zero
1733
+
1734
+ #
1735
+ # [A+B,C] -> [A,C] + [B,C]
1736
+ #
1737
+ a = a.expand()
1738
+ if isinstance(a, Add):
1739
+ return Add(*[cls(term, b) for term in a.args])
1740
+ b = b.expand()
1741
+ if isinstance(b, Add):
1742
+ return Add(*[cls(a, term) for term in b.args])
1743
+
1744
+ #
1745
+ # [xA,yB] -> xy*[A,B]
1746
+ #
1747
+ ca, nca = a.args_cnc()
1748
+ cb, ncb = b.args_cnc()
1749
+ c_part = list(ca) + list(cb)
1750
+ if c_part:
1751
+ return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
1752
+
1753
+ #
1754
+ # single second quantization operators
1755
+ #
1756
+ if isinstance(a, BosonicOperator) and isinstance(b, BosonicOperator):
1757
+ if isinstance(b, CreateBoson) and isinstance(a, AnnihilateBoson):
1758
+ return KroneckerDelta(a.state, b.state)
1759
+ if isinstance(a, CreateBoson) and isinstance(b, AnnihilateBoson):
1760
+ return S.NegativeOne*KroneckerDelta(a.state, b.state)
1761
+ else:
1762
+ return S.Zero
1763
+ if isinstance(a, FermionicOperator) and isinstance(b, FermionicOperator):
1764
+ return wicks(a*b) - wicks(b*a)
1765
+
1766
+ #
1767
+ # Canonical ordering of arguments
1768
+ #
1769
+ if a.sort_key() > b.sort_key():
1770
+ return S.NegativeOne*cls(b, a)
1771
+
1772
+ def doit(self, **hints):
1773
+ """
1774
+ Enables the computation of complex expressions.
1775
+
1776
+ Examples
1777
+ ========
1778
+
1779
+ >>> from sympy.physics.secondquant import Commutator, F, Fd
1780
+ >>> from sympy import symbols
1781
+ >>> i, j = symbols('i,j', below_fermi=True)
1782
+ >>> a, b = symbols('a,b', above_fermi=True)
1783
+ >>> c = Commutator(Fd(a)*F(i),Fd(b)*F(j))
1784
+ >>> c.doit(wicks=True)
1785
+ 0
1786
+ """
1787
+ a = self.args[0]
1788
+ b = self.args[1]
1789
+
1790
+ if hints.get("wicks"):
1791
+ a = a.doit(**hints)
1792
+ b = b.doit(**hints)
1793
+ try:
1794
+ return wicks(a*b) - wicks(b*a)
1795
+ except ContractionAppliesOnlyToFermions:
1796
+ pass
1797
+ except WicksTheoremDoesNotApply:
1798
+ pass
1799
+
1800
+ return (a*b - b*a).doit(**hints)
1801
+
1802
+ def __repr__(self):
1803
+ return "Commutator(%s,%s)" % (self.args[0], self.args[1])
1804
+
1805
+ def __str__(self):
1806
+ return "[%s,%s]" % (self.args[0], self.args[1])
1807
+
1808
+ def _latex(self, printer):
1809
+ return "\\left[%s,%s\\right]" % tuple([
1810
+ printer._print(arg) for arg in self.args])
1811
+
1812
+
1813
+ class NO(Expr):
1814
+ """
1815
+ This Object is used to represent normal ordering brackets.
1816
+
1817
+ i.e. {abcd} sometimes written :abcd:
1818
+
1819
+ Explanation
1820
+ ===========
1821
+
1822
+ Applying the function NO(arg) to an argument means that all operators in
1823
+ the argument will be assumed to anticommute, and have vanishing
1824
+ contractions. This allows an immediate reordering to canonical form
1825
+ upon object creation.
1826
+
1827
+ Examples
1828
+ ========
1829
+
1830
+ >>> from sympy import symbols
1831
+ >>> from sympy.physics.secondquant import NO, F, Fd
1832
+ >>> p,q = symbols('p,q')
1833
+ >>> NO(Fd(p)*F(q))
1834
+ NO(CreateFermion(p)*AnnihilateFermion(q))
1835
+ >>> NO(F(q)*Fd(p))
1836
+ -NO(CreateFermion(p)*AnnihilateFermion(q))
1837
+
1838
+
1839
+ Note
1840
+ ====
1841
+
1842
+ If you want to generate a normal ordered equivalent of an expression, you
1843
+ should use the function wicks(). This class only indicates that all
1844
+ operators inside the brackets anticommute, and have vanishing contractions.
1845
+ Nothing more, nothing less.
1846
+
1847
+ """
1848
+ is_commutative = False
1849
+
1850
+ def __new__(cls, arg):
1851
+ """
1852
+ Use anticommutation to get canonical form of operators.
1853
+
1854
+ Explanation
1855
+ ===========
1856
+
1857
+ Employ associativity of normal ordered product: {ab{cd}} = {abcd}
1858
+ but note that {ab}{cd} /= {abcd}.
1859
+
1860
+ We also employ distributivity: {ab + cd} = {ab} + {cd}.
1861
+
1862
+ Canonical form also implies expand() {ab(c+d)} = {abc} + {abd}.
1863
+
1864
+ """
1865
+
1866
+ # {ab + cd} = {ab} + {cd}
1867
+ arg = sympify(arg)
1868
+ arg = arg.expand()
1869
+ if arg.is_Add:
1870
+ return Add(*[ cls(term) for term in arg.args])
1871
+
1872
+ if arg.is_Mul:
1873
+
1874
+ # take coefficient outside of normal ordering brackets
1875
+ c_part, seq = arg.args_cnc()
1876
+ if c_part:
1877
+ coeff = Mul(*c_part)
1878
+ if not seq:
1879
+ return coeff
1880
+ else:
1881
+ coeff = S.One
1882
+
1883
+ # {ab{cd}} = {abcd}
1884
+ newseq = []
1885
+ foundit = False
1886
+ for fac in seq:
1887
+ if isinstance(fac, NO):
1888
+ newseq.extend(fac.args)
1889
+ foundit = True
1890
+ else:
1891
+ newseq.append(fac)
1892
+ if foundit:
1893
+ return coeff*cls(Mul(*newseq))
1894
+
1895
+ # We assume that the user don't mix B and F operators
1896
+ if isinstance(seq[0], BosonicOperator):
1897
+ raise NotImplementedError
1898
+
1899
+ try:
1900
+ newseq, sign = _sort_anticommuting_fermions(seq)
1901
+ except ViolationOfPauliPrinciple:
1902
+ return S.Zero
1903
+
1904
+ if sign % 2:
1905
+ return (S.NegativeOne*coeff)*cls(Mul(*newseq))
1906
+ elif sign:
1907
+ return coeff*cls(Mul(*newseq))
1908
+ else:
1909
+ pass # since sign==0, no permutations was necessary
1910
+
1911
+ # if we couldn't do anything with Mul object, we just
1912
+ # mark it as normal ordered
1913
+ if coeff != S.One:
1914
+ return coeff*cls(Mul(*newseq))
1915
+ return Expr.__new__(cls, Mul(*newseq))
1916
+
1917
+ if isinstance(arg, NO):
1918
+ return arg
1919
+
1920
+ # if object was not Mul or Add, normal ordering does not apply
1921
+ return arg
1922
+
1923
+ @property
1924
+ def has_q_creators(self):
1925
+ """
1926
+ Return 0 if the leftmost argument of the first argument is a not a
1927
+ q_creator, else 1 if it is above fermi or -1 if it is below fermi.
1928
+
1929
+ Examples
1930
+ ========
1931
+
1932
+ >>> from sympy import symbols
1933
+ >>> from sympy.physics.secondquant import NO, F, Fd
1934
+
1935
+ >>> a = symbols('a', above_fermi=True)
1936
+ >>> i = symbols('i', below_fermi=True)
1937
+ >>> NO(Fd(a)*Fd(i)).has_q_creators
1938
+ 1
1939
+ >>> NO(F(i)*F(a)).has_q_creators
1940
+ -1
1941
+ >>> NO(Fd(i)*F(a)).has_q_creators #doctest: +SKIP
1942
+ 0
1943
+
1944
+ """
1945
+ return self.args[0].args[0].is_q_creator
1946
+
1947
+ @property
1948
+ def has_q_annihilators(self):
1949
+ """
1950
+ Return 0 if the rightmost argument of the first argument is a not a
1951
+ q_annihilator, else 1 if it is above fermi or -1 if it is below fermi.
1952
+
1953
+ Examples
1954
+ ========
1955
+
1956
+ >>> from sympy import symbols
1957
+ >>> from sympy.physics.secondquant import NO, F, Fd
1958
+
1959
+ >>> a = symbols('a', above_fermi=True)
1960
+ >>> i = symbols('i', below_fermi=True)
1961
+ >>> NO(Fd(a)*Fd(i)).has_q_annihilators
1962
+ -1
1963
+ >>> NO(F(i)*F(a)).has_q_annihilators
1964
+ 1
1965
+ >>> NO(Fd(a)*F(i)).has_q_annihilators
1966
+ 0
1967
+
1968
+ """
1969
+ return self.args[0].args[-1].is_q_annihilator
1970
+
1971
+ def doit(self, **hints):
1972
+ """
1973
+ Either removes the brackets or enables complex computations
1974
+ in its arguments.
1975
+
1976
+ Examples
1977
+ ========
1978
+
1979
+ >>> from sympy.physics.secondquant import NO, Fd, F
1980
+ >>> from textwrap import fill
1981
+ >>> from sympy import symbols, Dummy
1982
+ >>> p,q = symbols('p,q', cls=Dummy)
1983
+ >>> print(fill(str(NO(Fd(p)*F(q)).doit())))
1984
+ KroneckerDelta(_a, _p)*KroneckerDelta(_a,
1985
+ _q)*CreateFermion(_a)*AnnihilateFermion(_a) + KroneckerDelta(_a,
1986
+ _p)*KroneckerDelta(_i, _q)*CreateFermion(_a)*AnnihilateFermion(_i) -
1987
+ KroneckerDelta(_a, _q)*KroneckerDelta(_i,
1988
+ _p)*AnnihilateFermion(_a)*CreateFermion(_i) - KroneckerDelta(_i,
1989
+ _p)*KroneckerDelta(_i, _q)*AnnihilateFermion(_i)*CreateFermion(_i)
1990
+ """
1991
+ if hints.get("remove_brackets", True):
1992
+ return self._remove_brackets()
1993
+ else:
1994
+ return self.__new__(type(self), self.args[0].doit(**hints))
1995
+
1996
+ def _remove_brackets(self):
1997
+ """
1998
+ Returns the sorted string without normal order brackets.
1999
+
2000
+ The returned string have the property that no nonzero
2001
+ contractions exist.
2002
+ """
2003
+
2004
+ # check if any creator is also an annihilator
2005
+ subslist = []
2006
+ for i in self.iter_q_creators():
2007
+ if self[i].is_q_annihilator:
2008
+ assume = self[i].state.assumptions0
2009
+
2010
+ # only operators with a dummy index can be split in two terms
2011
+ if isinstance(self[i].state, Dummy):
2012
+
2013
+ # create indices with fermi restriction
2014
+ assume.pop("above_fermi", None)
2015
+ assume["below_fermi"] = True
2016
+ below = Dummy('i', **assume)
2017
+ assume.pop("below_fermi", None)
2018
+ assume["above_fermi"] = True
2019
+ above = Dummy('a', **assume)
2020
+
2021
+ cls = type(self[i])
2022
+ split = (
2023
+ self[i].__new__(cls, below)
2024
+ * KroneckerDelta(below, self[i].state)
2025
+ + self[i].__new__(cls, above)
2026
+ * KroneckerDelta(above, self[i].state)
2027
+ )
2028
+ subslist.append((self[i], split))
2029
+ else:
2030
+ raise SubstitutionOfAmbigousOperatorFailed(self[i])
2031
+ if subslist:
2032
+ result = NO(self.subs(subslist))
2033
+ if isinstance(result, Add):
2034
+ return Add(*[term.doit() for term in result.args])
2035
+ else:
2036
+ return self.args[0]
2037
+
2038
+ def _expand_operators(self):
2039
+ """
2040
+ Returns a sum of NO objects that contain no ambiguous q-operators.
2041
+
2042
+ Explanation
2043
+ ===========
2044
+
2045
+ If an index q has range both above and below fermi, the operator F(q)
2046
+ is ambiguous in the sense that it can be both a q-creator and a q-annihilator.
2047
+ If q is dummy, it is assumed to be a summation variable and this method
2048
+ rewrites it into a sum of NO terms with unambiguous operators:
2049
+
2050
+ {Fd(p)*F(q)} = {Fd(a)*F(b)} + {Fd(a)*F(i)} + {Fd(j)*F(b)} -{F(i)*Fd(j)}
2051
+
2052
+ where a,b are above and i,j are below fermi level.
2053
+ """
2054
+ return NO(self._remove_brackets)
2055
+
2056
+ def __getitem__(self, i):
2057
+ if isinstance(i, slice):
2058
+ indices = i.indices(len(self))
2059
+ return [self.args[0].args[i] for i in range(*indices)]
2060
+ else:
2061
+ return self.args[0].args[i]
2062
+
2063
+ def __len__(self):
2064
+ return len(self.args[0].args)
2065
+
2066
+ def iter_q_annihilators(self):
2067
+ """
2068
+ Iterates over the annihilation operators.
2069
+
2070
+ Examples
2071
+ ========
2072
+
2073
+ >>> from sympy import symbols
2074
+ >>> i, j = symbols('i j', below_fermi=True)
2075
+ >>> a, b = symbols('a b', above_fermi=True)
2076
+ >>> from sympy.physics.secondquant import NO, F, Fd
2077
+ >>> no = NO(Fd(a)*F(i)*F(b)*Fd(j))
2078
+
2079
+ >>> no.iter_q_creators()
2080
+ <generator object... at 0x...>
2081
+ >>> list(no.iter_q_creators())
2082
+ [0, 1]
2083
+ >>> list(no.iter_q_annihilators())
2084
+ [3, 2]
2085
+
2086
+ """
2087
+ ops = self.args[0].args
2088
+ iter = range(len(ops) - 1, -1, -1)
2089
+ for i in iter:
2090
+ if ops[i].is_q_annihilator:
2091
+ yield i
2092
+ else:
2093
+ break
2094
+
2095
+ def iter_q_creators(self):
2096
+ """
2097
+ Iterates over the creation operators.
2098
+
2099
+ Examples
2100
+ ========
2101
+
2102
+ >>> from sympy import symbols
2103
+ >>> i, j = symbols('i j', below_fermi=True)
2104
+ >>> a, b = symbols('a b', above_fermi=True)
2105
+ >>> from sympy.physics.secondquant import NO, F, Fd
2106
+ >>> no = NO(Fd(a)*F(i)*F(b)*Fd(j))
2107
+
2108
+ >>> no.iter_q_creators()
2109
+ <generator object... at 0x...>
2110
+ >>> list(no.iter_q_creators())
2111
+ [0, 1]
2112
+ >>> list(no.iter_q_annihilators())
2113
+ [3, 2]
2114
+
2115
+ """
2116
+
2117
+ ops = self.args[0].args
2118
+ iter = range(0, len(ops))
2119
+ for i in iter:
2120
+ if ops[i].is_q_creator:
2121
+ yield i
2122
+ else:
2123
+ break
2124
+
2125
+ def get_subNO(self, i):
2126
+ """
2127
+ Returns a NO() without FermionicOperator at index i.
2128
+
2129
+ Examples
2130
+ ========
2131
+
2132
+ >>> from sympy import symbols
2133
+ >>> from sympy.physics.secondquant import F, NO
2134
+ >>> p, q, r = symbols('p,q,r')
2135
+
2136
+ >>> NO(F(p)*F(q)*F(r)).get_subNO(1)
2137
+ NO(AnnihilateFermion(p)*AnnihilateFermion(r))
2138
+
2139
+ """
2140
+ arg0 = self.args[0] # it's a Mul by definition of how it's created
2141
+ mul = arg0._new_rawargs(*(arg0.args[:i] + arg0.args[i + 1:]))
2142
+ return NO(mul)
2143
+
2144
+ def _latex(self, printer):
2145
+ return "\\left\\{%s\\right\\}" % printer._print(self.args[0])
2146
+
2147
+ def __repr__(self):
2148
+ return "NO(%s)" % self.args[0]
2149
+
2150
+ def __str__(self):
2151
+ return ":%s:" % self.args[0]
2152
+
2153
+
2154
+ def contraction(a, b):
2155
+ """
2156
+ Calculates contraction of Fermionic operators a and b.
2157
+
2158
+ Examples
2159
+ ========
2160
+
2161
+ >>> from sympy import symbols
2162
+ >>> from sympy.physics.secondquant import F, Fd, contraction
2163
+ >>> p, q = symbols('p,q')
2164
+ >>> a, b = symbols('a,b', above_fermi=True)
2165
+ >>> i, j = symbols('i,j', below_fermi=True)
2166
+
2167
+ A contraction is non-zero only if a quasi-creator is to the right of a
2168
+ quasi-annihilator:
2169
+
2170
+ >>> contraction(F(a),Fd(b))
2171
+ KroneckerDelta(a, b)
2172
+ >>> contraction(Fd(i),F(j))
2173
+ KroneckerDelta(i, j)
2174
+
2175
+ For general indices a non-zero result restricts the indices to below/above
2176
+ the fermi surface:
2177
+
2178
+ >>> contraction(Fd(p),F(q))
2179
+ KroneckerDelta(_i, q)*KroneckerDelta(p, q)
2180
+ >>> contraction(F(p),Fd(q))
2181
+ KroneckerDelta(_a, q)*KroneckerDelta(p, q)
2182
+
2183
+ Two creators or two annihilators always vanishes:
2184
+
2185
+ >>> contraction(F(p),F(q))
2186
+ 0
2187
+ >>> contraction(Fd(p),Fd(q))
2188
+ 0
2189
+
2190
+ """
2191
+ if isinstance(b, FermionicOperator) and isinstance(a, FermionicOperator):
2192
+ if isinstance(a, AnnihilateFermion) and isinstance(b, CreateFermion):
2193
+ if b.state.assumptions0.get("below_fermi"):
2194
+ return S.Zero
2195
+ if a.state.assumptions0.get("below_fermi"):
2196
+ return S.Zero
2197
+ if b.state.assumptions0.get("above_fermi"):
2198
+ return KroneckerDelta(a.state, b.state)
2199
+ if a.state.assumptions0.get("above_fermi"):
2200
+ return KroneckerDelta(a.state, b.state)
2201
+
2202
+ return (KroneckerDelta(a.state, b.state)*
2203
+ KroneckerDelta(b.state, Dummy('a', above_fermi=True)))
2204
+ if isinstance(b, AnnihilateFermion) and isinstance(a, CreateFermion):
2205
+ if b.state.assumptions0.get("above_fermi"):
2206
+ return S.Zero
2207
+ if a.state.assumptions0.get("above_fermi"):
2208
+ return S.Zero
2209
+ if b.state.assumptions0.get("below_fermi"):
2210
+ return KroneckerDelta(a.state, b.state)
2211
+ if a.state.assumptions0.get("below_fermi"):
2212
+ return KroneckerDelta(a.state, b.state)
2213
+
2214
+ return (KroneckerDelta(a.state, b.state)*
2215
+ KroneckerDelta(b.state, Dummy('i', below_fermi=True)))
2216
+
2217
+ # vanish if 2xAnnihilator or 2xCreator
2218
+ return S.Zero
2219
+
2220
+ else:
2221
+ #not fermion operators
2222
+ t = ( isinstance(i, FermionicOperator) for i in (a, b) )
2223
+ raise ContractionAppliesOnlyToFermions(*t)
2224
+
2225
+
2226
+ def _sqkey(sq_operator):
2227
+ """Generates key for canonical sorting of SQ operators."""
2228
+ return sq_operator._sortkey()
2229
+
2230
+
2231
+ def _sort_anticommuting_fermions(string1, key=_sqkey):
2232
+ """Sort fermionic operators to canonical order, assuming all pairs anticommute.
2233
+
2234
+ Explanation
2235
+ ===========
2236
+
2237
+ Uses a bidirectional bubble sort. Items in string1 are not referenced
2238
+ so in principle they may be any comparable objects. The sorting depends on the
2239
+ operators '>' and '=='.
2240
+
2241
+ If the Pauli principle is violated, an exception is raised.
2242
+
2243
+ Returns
2244
+ =======
2245
+
2246
+ tuple (sorted_str, sign)
2247
+
2248
+ sorted_str: list containing the sorted operators
2249
+ sign: int telling how many times the sign should be changed
2250
+ (if sign==0 the string was already sorted)
2251
+ """
2252
+
2253
+ verified = False
2254
+ sign = 0
2255
+ rng = list(range(len(string1) - 1))
2256
+ rev = list(range(len(string1) - 3, -1, -1))
2257
+
2258
+ keys = list(map(key, string1))
2259
+ key_val = dict(list(zip(keys, string1)))
2260
+
2261
+ while not verified:
2262
+ verified = True
2263
+ for i in rng:
2264
+ left = keys[i]
2265
+ right = keys[i + 1]
2266
+ if left == right:
2267
+ raise ViolationOfPauliPrinciple([left, right])
2268
+ if left > right:
2269
+ verified = False
2270
+ keys[i:i + 2] = [right, left]
2271
+ sign = sign + 1
2272
+ if verified:
2273
+ break
2274
+ for i in rev:
2275
+ left = keys[i]
2276
+ right = keys[i + 1]
2277
+ if left == right:
2278
+ raise ViolationOfPauliPrinciple([left, right])
2279
+ if left > right:
2280
+ verified = False
2281
+ keys[i:i + 2] = [right, left]
2282
+ sign = sign + 1
2283
+ string1 = [ key_val[k] for k in keys ]
2284
+ return (string1, sign)
2285
+
2286
+
2287
+ def evaluate_deltas(e):
2288
+ """
2289
+ We evaluate KroneckerDelta symbols in the expression assuming Einstein summation.
2290
+
2291
+ Explanation
2292
+ ===========
2293
+
2294
+ If one index is repeated it is summed over and in effect substituted with
2295
+ the other one. If both indices are repeated we substitute according to what
2296
+ is the preferred index. this is determined by
2297
+ KroneckerDelta.preferred_index and KroneckerDelta.killable_index.
2298
+
2299
+ In case there are no possible substitutions or if a substitution would
2300
+ imply a loss of information, nothing is done.
2301
+
2302
+ In case an index appears in more than one KroneckerDelta, the resulting
2303
+ substitution depends on the order of the factors. Since the ordering is platform
2304
+ dependent, the literal expression resulting from this function may be hard to
2305
+ predict.
2306
+
2307
+ Examples
2308
+ ========
2309
+
2310
+ We assume the following:
2311
+
2312
+ >>> from sympy import symbols, Function, Dummy, KroneckerDelta
2313
+ >>> from sympy.physics.secondquant import evaluate_deltas
2314
+ >>> i,j = symbols('i j', below_fermi=True, cls=Dummy)
2315
+ >>> a,b = symbols('a b', above_fermi=True, cls=Dummy)
2316
+ >>> p,q = symbols('p q', cls=Dummy)
2317
+ >>> f = Function('f')
2318
+ >>> t = Function('t')
2319
+
2320
+ The order of preference for these indices according to KroneckerDelta is
2321
+ (a, b, i, j, p, q).
2322
+
2323
+ Trivial cases:
2324
+
2325
+ >>> evaluate_deltas(KroneckerDelta(i,j)*f(i)) # d_ij f(i) -> f(j)
2326
+ f(_j)
2327
+ >>> evaluate_deltas(KroneckerDelta(i,j)*f(j)) # d_ij f(j) -> f(i)
2328
+ f(_i)
2329
+ >>> evaluate_deltas(KroneckerDelta(i,p)*f(p)) # d_ip f(p) -> f(i)
2330
+ f(_i)
2331
+ >>> evaluate_deltas(KroneckerDelta(q,p)*f(p)) # d_qp f(p) -> f(q)
2332
+ f(_q)
2333
+ >>> evaluate_deltas(KroneckerDelta(q,p)*f(q)) # d_qp f(q) -> f(p)
2334
+ f(_p)
2335
+
2336
+ More interesting cases:
2337
+
2338
+ >>> evaluate_deltas(KroneckerDelta(i,p)*t(a,i)*f(p,q))
2339
+ f(_i, _q)*t(_a, _i)
2340
+ >>> evaluate_deltas(KroneckerDelta(a,p)*t(a,i)*f(p,q))
2341
+ f(_a, _q)*t(_a, _i)
2342
+ >>> evaluate_deltas(KroneckerDelta(p,q)*f(p,q))
2343
+ f(_p, _p)
2344
+
2345
+ Finally, here are some cases where nothing is done, because that would
2346
+ imply a loss of information:
2347
+
2348
+ >>> evaluate_deltas(KroneckerDelta(i,p)*f(q))
2349
+ f(_q)*KroneckerDelta(_i, _p)
2350
+ >>> evaluate_deltas(KroneckerDelta(i,p)*f(i))
2351
+ f(_i)*KroneckerDelta(_i, _p)
2352
+ """
2353
+
2354
+ # We treat Deltas only in mul objects
2355
+ # for general function objects we don't evaluate KroneckerDeltas in arguments,
2356
+ # but here we hard code exceptions to this rule
2357
+ accepted_functions = (
2358
+ Add,
2359
+ )
2360
+ if isinstance(e, accepted_functions):
2361
+ return e.func(*[evaluate_deltas(arg) for arg in e.args])
2362
+
2363
+ elif isinstance(e, Mul):
2364
+ # find all occurrences of delta function and count each index present in
2365
+ # expression.
2366
+ deltas = []
2367
+ indices = {}
2368
+ for i in e.args:
2369
+ for s in i.free_symbols:
2370
+ if s in indices:
2371
+ indices[s] += 1
2372
+ else:
2373
+ indices[s] = 0 # geek counting simplifies logic below
2374
+ if isinstance(i, KroneckerDelta):
2375
+ deltas.append(i)
2376
+
2377
+ for d in deltas:
2378
+ # If we do something, and there are more deltas, we should recurse
2379
+ # to treat the resulting expression properly
2380
+ if d.killable_index.is_Symbol and indices[d.killable_index]:
2381
+ e = e.subs(d.killable_index, d.preferred_index)
2382
+ if len(deltas) > 1:
2383
+ return evaluate_deltas(e)
2384
+ elif (d.preferred_index.is_Symbol and indices[d.preferred_index]
2385
+ and d.indices_contain_equal_information):
2386
+ e = e.subs(d.preferred_index, d.killable_index)
2387
+ if len(deltas) > 1:
2388
+ return evaluate_deltas(e)
2389
+ else:
2390
+ pass
2391
+
2392
+ return e
2393
+ # nothing to do, maybe we hit a Symbol or a number
2394
+ else:
2395
+ return e
2396
+
2397
+
2398
+ def substitute_dummies(expr, new_indices=False, pretty_indices={}):
2399
+ """
2400
+ Collect terms by substitution of dummy variables.
2401
+
2402
+ Explanation
2403
+ ===========
2404
+
2405
+ This routine allows simplification of Add expressions containing terms
2406
+ which differ only due to dummy variables.
2407
+
2408
+ The idea is to substitute all dummy variables consistently depending on
2409
+ the structure of the term. For each term, we obtain a sequence of all
2410
+ dummy variables, where the order is determined by the index range, what
2411
+ factors the index belongs to and its position in each factor. See
2412
+ _get_ordered_dummies() for more information about the sorting of dummies.
2413
+ The index sequence is then substituted consistently in each term.
2414
+
2415
+ Examples
2416
+ ========
2417
+
2418
+ >>> from sympy import symbols, Function, Dummy
2419
+ >>> from sympy.physics.secondquant import substitute_dummies
2420
+ >>> a,b,c,d = symbols('a b c d', above_fermi=True, cls=Dummy)
2421
+ >>> i,j = symbols('i j', below_fermi=True, cls=Dummy)
2422
+ >>> f = Function('f')
2423
+
2424
+ >>> expr = f(a,b) + f(c,d); expr
2425
+ f(_a, _b) + f(_c, _d)
2426
+
2427
+ Since a, b, c and d are equivalent summation indices, the expression can be
2428
+ simplified to a single term (for which the dummy indices are still summed over)
2429
+
2430
+ >>> substitute_dummies(expr)
2431
+ 2*f(_a, _b)
2432
+
2433
+
2434
+ Controlling output:
2435
+
2436
+ By default the dummy symbols that are already present in the expression
2437
+ will be reused in a different permutation. However, if new_indices=True,
2438
+ new dummies will be generated and inserted. The keyword 'pretty_indices'
2439
+ can be used to control this generation of new symbols.
2440
+
2441
+ By default the new dummies will be generated on the form i_1, i_2, a_1,
2442
+ etc. If you supply a dictionary with key:value pairs in the form:
2443
+
2444
+ { index_group: string_of_letters }
2445
+
2446
+ The letters will be used as labels for the new dummy symbols. The
2447
+ index_groups must be one of 'above', 'below' or 'general'.
2448
+
2449
+ >>> expr = f(a,b,i,j)
2450
+ >>> my_dummies = { 'above':'st', 'below':'uv' }
2451
+ >>> substitute_dummies(expr, new_indices=True, pretty_indices=my_dummies)
2452
+ f(_s, _t, _u, _v)
2453
+
2454
+ If we run out of letters, or if there is no keyword for some index_group
2455
+ the default dummy generator will be used as a fallback:
2456
+
2457
+ >>> p,q = symbols('p q', cls=Dummy) # general indices
2458
+ >>> expr = f(p,q)
2459
+ >>> substitute_dummies(expr, new_indices=True, pretty_indices=my_dummies)
2460
+ f(_p_0, _p_1)
2461
+
2462
+ """
2463
+
2464
+ # setup the replacing dummies
2465
+ if new_indices:
2466
+ letters_above = pretty_indices.get('above', "")
2467
+ letters_below = pretty_indices.get('below', "")
2468
+ letters_general = pretty_indices.get('general', "")
2469
+ len_above = len(letters_above)
2470
+ len_below = len(letters_below)
2471
+ len_general = len(letters_general)
2472
+
2473
+ def _i(number):
2474
+ try:
2475
+ return letters_below[number]
2476
+ except IndexError:
2477
+ return 'i_' + str(number - len_below)
2478
+
2479
+ def _a(number):
2480
+ try:
2481
+ return letters_above[number]
2482
+ except IndexError:
2483
+ return 'a_' + str(number - len_above)
2484
+
2485
+ def _p(number):
2486
+ try:
2487
+ return letters_general[number]
2488
+ except IndexError:
2489
+ return 'p_' + str(number - len_general)
2490
+
2491
+ aboves = []
2492
+ belows = []
2493
+ generals = []
2494
+
2495
+ dummies = expr.atoms(Dummy)
2496
+ if not new_indices:
2497
+ dummies = sorted(dummies, key=default_sort_key)
2498
+
2499
+ # generate lists with the dummies we will insert
2500
+ a = i = p = 0
2501
+ for d in dummies:
2502
+ assum = d.assumptions0
2503
+
2504
+ if assum.get("above_fermi"):
2505
+ if new_indices:
2506
+ sym = _a(a)
2507
+ a += 1
2508
+ l1 = aboves
2509
+ elif assum.get("below_fermi"):
2510
+ if new_indices:
2511
+ sym = _i(i)
2512
+ i += 1
2513
+ l1 = belows
2514
+ else:
2515
+ if new_indices:
2516
+ sym = _p(p)
2517
+ p += 1
2518
+ l1 = generals
2519
+
2520
+ if new_indices:
2521
+ l1.append(Dummy(sym, **assum))
2522
+ else:
2523
+ l1.append(d)
2524
+
2525
+ expr = expr.expand()
2526
+ terms = Add.make_args(expr)
2527
+ new_terms = []
2528
+ for term in terms:
2529
+ i = iter(belows)
2530
+ a = iter(aboves)
2531
+ p = iter(generals)
2532
+ ordered = _get_ordered_dummies(term)
2533
+ subsdict = {}
2534
+ for d in ordered:
2535
+ if d.assumptions0.get('below_fermi'):
2536
+ subsdict[d] = next(i)
2537
+ elif d.assumptions0.get('above_fermi'):
2538
+ subsdict[d] = next(a)
2539
+ else:
2540
+ subsdict[d] = next(p)
2541
+ subslist = []
2542
+ final_subs = []
2543
+ for k, v in subsdict.items():
2544
+ if k == v:
2545
+ continue
2546
+ if v in subsdict:
2547
+ # We check if the sequence of substitutions end quickly. In
2548
+ # that case, we can avoid temporary symbols if we ensure the
2549
+ # correct substitution order.
2550
+ if subsdict[v] in subsdict:
2551
+ # (x, y) -> (y, x), we need a temporary variable
2552
+ x = Dummy('x')
2553
+ subslist.append((k, x))
2554
+ final_subs.append((x, v))
2555
+ else:
2556
+ # (x, y) -> (y, a), x->y must be done last
2557
+ # but before temporary variables are resolved
2558
+ final_subs.insert(0, (k, v))
2559
+ else:
2560
+ subslist.append((k, v))
2561
+ subslist.extend(final_subs)
2562
+ new_terms.append(term.subs(subslist))
2563
+ return Add(*new_terms)
2564
+
2565
+
2566
+ class KeyPrinter(StrPrinter):
2567
+ """Printer for which only equal objects are equal in print"""
2568
+ def _print_Dummy(self, expr):
2569
+ return "(%s_%i)" % (expr.name, expr.dummy_index)
2570
+
2571
+
2572
+ def __kprint(expr):
2573
+ p = KeyPrinter()
2574
+ return p.doprint(expr)
2575
+
2576
+
2577
+ def _get_ordered_dummies(mul, verbose=False):
2578
+ """Returns all dummies in the mul sorted in canonical order.
2579
+
2580
+ Explanation
2581
+ ===========
2582
+
2583
+ The purpose of the canonical ordering is that dummies can be substituted
2584
+ consistently across terms with the result that equivalent terms can be
2585
+ simplified.
2586
+
2587
+ It is not possible to determine if two terms are equivalent based solely on
2588
+ the dummy order. However, a consistent substitution guided by the ordered
2589
+ dummies should lead to trivially (non-)equivalent terms, thereby revealing
2590
+ the equivalence. This also means that if two terms have identical sequences of
2591
+ dummies, the (non-)equivalence should already be apparent.
2592
+
2593
+ Strategy
2594
+ --------
2595
+
2596
+ The canonical order is given by an arbitrary sorting rule. A sort key
2597
+ is determined for each dummy as a tuple that depends on all factors where
2598
+ the index is present. The dummies are thereby sorted according to the
2599
+ contraction structure of the term, instead of sorting based solely on the
2600
+ dummy symbol itself.
2601
+
2602
+ After all dummies in the term has been assigned a key, we check for identical
2603
+ keys, i.e. unorderable dummies. If any are found, we call a specialized
2604
+ method, _determine_ambiguous(), that will determine a unique order based
2605
+ on recursive calls to _get_ordered_dummies().
2606
+
2607
+ Key description
2608
+ ---------------
2609
+
2610
+ A high level description of the sort key:
2611
+
2612
+ 1. Range of the dummy index
2613
+ 2. Relation to external (non-dummy) indices
2614
+ 3. Position of the index in the first factor
2615
+ 4. Position of the index in the second factor
2616
+
2617
+ The sort key is a tuple with the following components:
2618
+
2619
+ 1. A single character indicating the range of the dummy (above, below
2620
+ or general.)
2621
+ 2. A list of strings with fully masked string representations of all
2622
+ factors where the dummy is present. By masked, we mean that dummies
2623
+ are represented by a symbol to indicate either below fermi, above or
2624
+ general. No other information is displayed about the dummies at
2625
+ this point. The list is sorted stringwise.
2626
+ 3. An integer number indicating the position of the index, in the first
2627
+ factor as sorted in 2.
2628
+ 4. An integer number indicating the position of the index, in the second
2629
+ factor as sorted in 2.
2630
+
2631
+ If a factor is either of type AntiSymmetricTensor or SqOperator, the index
2632
+ position in items 3 and 4 is indicated as 'upper' or 'lower' only.
2633
+ (Creation operators are considered upper and annihilation operators lower.)
2634
+
2635
+ If the masked factors are identical, the two factors cannot be ordered
2636
+ unambiguously in item 2. In this case, items 3, 4 are left out. If several
2637
+ indices are contracted between the unorderable factors, it will be handled by
2638
+ _determine_ambiguous()
2639
+
2640
+
2641
+ """
2642
+ # setup dicts to avoid repeated calculations in key()
2643
+ args = Mul.make_args(mul)
2644
+ fac_dum = { fac: fac.atoms(Dummy) for fac in args }
2645
+ fac_repr = { fac: __kprint(fac) for fac in args }
2646
+ all_dums = set().union(*fac_dum.values())
2647
+ mask = {}
2648
+ for d in all_dums:
2649
+ if d.assumptions0.get('below_fermi'):
2650
+ mask[d] = '0'
2651
+ elif d.assumptions0.get('above_fermi'):
2652
+ mask[d] = '1'
2653
+ else:
2654
+ mask[d] = '2'
2655
+ dum_repr = {d: __kprint(d) for d in all_dums}
2656
+
2657
+ def _key(d):
2658
+ dumstruct = [ fac for fac in fac_dum if d in fac_dum[fac] ]
2659
+ other_dums = set().union(*[fac_dum[fac] for fac in dumstruct])
2660
+ fac = dumstruct[-1]
2661
+ if other_dums is fac_dum[fac]:
2662
+ other_dums = fac_dum[fac].copy()
2663
+ other_dums.remove(d)
2664
+ masked_facs = [ fac_repr[fac] for fac in dumstruct ]
2665
+ for d2 in other_dums:
2666
+ masked_facs = [ fac.replace(dum_repr[d2], mask[d2])
2667
+ for fac in masked_facs ]
2668
+ all_masked = [ fac.replace(dum_repr[d], mask[d])
2669
+ for fac in masked_facs ]
2670
+ masked_facs = dict(list(zip(dumstruct, masked_facs)))
2671
+
2672
+ # dummies for which the ordering cannot be determined
2673
+ if has_dups(all_masked):
2674
+ all_masked.sort()
2675
+ return mask[d], tuple(all_masked) # positions are ambiguous
2676
+
2677
+ # sort factors according to fully masked strings
2678
+ keydict = dict(list(zip(dumstruct, all_masked)))
2679
+ dumstruct.sort(key=lambda x: keydict[x])
2680
+ all_masked.sort()
2681
+
2682
+ pos_val = []
2683
+ for fac in dumstruct:
2684
+ if isinstance(fac, AntiSymmetricTensor):
2685
+ if d in fac.upper:
2686
+ pos_val.append('u')
2687
+ if d in fac.lower:
2688
+ pos_val.append('l')
2689
+ elif isinstance(fac, Creator):
2690
+ pos_val.append('u')
2691
+ elif isinstance(fac, Annihilator):
2692
+ pos_val.append('l')
2693
+ elif isinstance(fac, NO):
2694
+ ops = [ op for op in fac if op.has(d) ]
2695
+ for op in ops:
2696
+ if isinstance(op, Creator):
2697
+ pos_val.append('u')
2698
+ else:
2699
+ pos_val.append('l')
2700
+ else:
2701
+ # fallback to position in string representation
2702
+ facpos = -1
2703
+ while 1:
2704
+ facpos = masked_facs[fac].find(dum_repr[d], facpos + 1)
2705
+ if facpos == -1:
2706
+ break
2707
+ pos_val.append(facpos)
2708
+ return (mask[d], tuple(all_masked), pos_val[0], pos_val[-1])
2709
+ dumkey = dict(list(zip(all_dums, list(map(_key, all_dums)))))
2710
+ result = sorted(all_dums, key=lambda x: dumkey[x])
2711
+ if has_dups(iter(dumkey.values())):
2712
+ # We have ambiguities
2713
+ unordered = defaultdict(set)
2714
+ for d, k in dumkey.items():
2715
+ unordered[k].add(d)
2716
+ for k in [ k for k in unordered if len(unordered[k]) < 2 ]:
2717
+ del unordered[k]
2718
+
2719
+ unordered = [ unordered[k] for k in sorted(unordered) ]
2720
+ result = _determine_ambiguous(mul, result, unordered)
2721
+ return result
2722
+
2723
+
2724
+ def _determine_ambiguous(term, ordered, ambiguous_groups):
2725
+ # We encountered a term for which the dummy substitution is ambiguous.
2726
+ # This happens for terms with 2 or more contractions between factors that
2727
+ # cannot be uniquely ordered independent of summation indices. For
2728
+ # example:
2729
+ #
2730
+ # Sum(p, q) v^{p, .}_{q, .}v^{q, .}_{p, .}
2731
+ #
2732
+ # Assuming that the indices represented by . are dummies with the
2733
+ # same range, the factors cannot be ordered, and there is no
2734
+ # way to determine a consistent ordering of p and q.
2735
+ #
2736
+ # The strategy employed here, is to relabel all unambiguous dummies with
2737
+ # non-dummy symbols and call _get_ordered_dummies again. This procedure is
2738
+ # applied to the entire term so there is a possibility that
2739
+ # _determine_ambiguous() is called again from a deeper recursion level.
2740
+
2741
+ # break recursion if there are no ordered dummies
2742
+ all_ambiguous = set()
2743
+ for dummies in ambiguous_groups:
2744
+ all_ambiguous |= dummies
2745
+ all_ordered = set(ordered) - all_ambiguous
2746
+ if not all_ordered:
2747
+ # FIXME: If we arrive here, there are no ordered dummies. A method to
2748
+ # handle this needs to be implemented. In order to return something
2749
+ # useful nevertheless, we choose arbitrarily the first dummy and
2750
+ # determine the rest from this one. This method is dependent on the
2751
+ # actual dummy labels which violates an assumption for the
2752
+ # canonicalization procedure. A better implementation is needed.
2753
+ group = [ d for d in ordered if d in ambiguous_groups[0] ]
2754
+ d = group[0]
2755
+ all_ordered.add(d)
2756
+ ambiguous_groups[0].remove(d)
2757
+
2758
+ stored_counter = _symbol_factory._counter
2759
+ subslist = []
2760
+ for d in [ d for d in ordered if d in all_ordered ]:
2761
+ nondum = _symbol_factory._next()
2762
+ subslist.append((d, nondum))
2763
+ newterm = term.subs(subslist)
2764
+ neworder = _get_ordered_dummies(newterm)
2765
+ _symbol_factory._set_counter(stored_counter)
2766
+
2767
+ # update ordered list with new information
2768
+ for group in ambiguous_groups:
2769
+ ordered_group = [ d for d in neworder if d in group ]
2770
+ ordered_group.reverse()
2771
+ result = []
2772
+ for d in ordered:
2773
+ if d in group:
2774
+ result.append(ordered_group.pop())
2775
+ else:
2776
+ result.append(d)
2777
+ ordered = result
2778
+ return ordered
2779
+
2780
+
2781
+ class _SymbolFactory:
2782
+ def __init__(self, label):
2783
+ self._counterVar = 0
2784
+ self._label = label
2785
+
2786
+ def _set_counter(self, value):
2787
+ """
2788
+ Sets counter to value.
2789
+ """
2790
+ self._counterVar = value
2791
+
2792
+ @property
2793
+ def _counter(self):
2794
+ """
2795
+ What counter is currently at.
2796
+ """
2797
+ return self._counterVar
2798
+
2799
+ def _next(self):
2800
+ """
2801
+ Generates the next symbols and increments counter by 1.
2802
+ """
2803
+ s = Symbol("%s%i" % (self._label, self._counterVar))
2804
+ self._counterVar += 1
2805
+ return s
2806
+ _symbol_factory = _SymbolFactory('_]"]_') # most certainly a unique label
2807
+
2808
+
2809
+ @cacheit
2810
+ def _get_contractions(string1, keep_only_fully_contracted=False):
2811
+ """
2812
+ Returns Add-object with contracted terms.
2813
+
2814
+ Uses recursion to find all contractions. -- Internal helper function --
2815
+
2816
+ Will find nonzero contractions in string1 between indices given in
2817
+ leftrange and rightrange.
2818
+
2819
+ """
2820
+
2821
+ # Should we store current level of contraction?
2822
+ if keep_only_fully_contracted and string1:
2823
+ result = []
2824
+ else:
2825
+ result = [NO(Mul(*string1))]
2826
+
2827
+ for i in range(len(string1) - 1):
2828
+ for j in range(i + 1, len(string1)):
2829
+
2830
+ c = contraction(string1[i], string1[j])
2831
+
2832
+ if c:
2833
+ sign = (j - i + 1) % 2
2834
+ if sign:
2835
+ coeff = S.NegativeOne*c
2836
+ else:
2837
+ coeff = c
2838
+
2839
+ #
2840
+ # Call next level of recursion
2841
+ # ============================
2842
+ #
2843
+ # We now need to find more contractions among operators
2844
+ #
2845
+ # oplist = string1[:i]+ string1[i+1:j] + string1[j+1:]
2846
+ #
2847
+ # To prevent overcounting, we don't allow contractions
2848
+ # we have already encountered. i.e. contractions between
2849
+ # string1[:i] <---> string1[i+1:j]
2850
+ # and string1[:i] <---> string1[j+1:].
2851
+ #
2852
+ # This leaves the case:
2853
+ oplist = string1[i + 1:j] + string1[j + 1:]
2854
+
2855
+ if oplist:
2856
+
2857
+ result.append(coeff*NO(
2858
+ Mul(*string1[:i])*_get_contractions( oplist,
2859
+ keep_only_fully_contracted=keep_only_fully_contracted)))
2860
+
2861
+ else:
2862
+ result.append(coeff*NO( Mul(*string1[:i])))
2863
+
2864
+ if keep_only_fully_contracted:
2865
+ break # next iteration over i leaves leftmost operator string1[0] uncontracted
2866
+
2867
+ return Add(*result)
2868
+
2869
+
2870
+ def wicks(e, **kw_args):
2871
+ """
2872
+ Returns the normal ordered equivalent of an expression using Wicks Theorem.
2873
+
2874
+ Examples
2875
+ ========
2876
+
2877
+ >>> from sympy import symbols, Dummy
2878
+ >>> from sympy.physics.secondquant import wicks, F, Fd
2879
+ >>> p, q, r = symbols('p,q,r')
2880
+ >>> wicks(Fd(p)*F(q))
2881
+ KroneckerDelta(_i, q)*KroneckerDelta(p, q) + NO(CreateFermion(p)*AnnihilateFermion(q))
2882
+
2883
+ By default, the expression is expanded:
2884
+
2885
+ >>> wicks(F(p)*(F(q)+F(r)))
2886
+ NO(AnnihilateFermion(p)*AnnihilateFermion(q)) + NO(AnnihilateFermion(p)*AnnihilateFermion(r))
2887
+
2888
+ With the keyword 'keep_only_fully_contracted=True', only fully contracted
2889
+ terms are returned.
2890
+
2891
+ By request, the result can be simplified in the following order:
2892
+ -- KroneckerDelta functions are evaluated
2893
+ -- Dummy variables are substituted consistently across terms
2894
+
2895
+ >>> p, q, r = symbols('p q r', cls=Dummy)
2896
+ >>> wicks(Fd(p)*(F(q)+F(r)), keep_only_fully_contracted=True)
2897
+ KroneckerDelta(_i, _q)*KroneckerDelta(_p, _q) + KroneckerDelta(_i, _r)*KroneckerDelta(_p, _r)
2898
+
2899
+ """
2900
+
2901
+ if not e:
2902
+ return S.Zero
2903
+
2904
+ opts = {
2905
+ 'simplify_kronecker_deltas': False,
2906
+ 'expand': True,
2907
+ 'simplify_dummies': False,
2908
+ 'keep_only_fully_contracted': False
2909
+ }
2910
+ opts.update(kw_args)
2911
+
2912
+ # check if we are already normally ordered
2913
+ if isinstance(e, NO):
2914
+ if opts['keep_only_fully_contracted']:
2915
+ return S.Zero
2916
+ else:
2917
+ return e
2918
+ elif isinstance(e, FermionicOperator):
2919
+ if opts['keep_only_fully_contracted']:
2920
+ return S.Zero
2921
+ else:
2922
+ return e
2923
+
2924
+ # break up any NO-objects, and evaluate commutators
2925
+ e = e.doit(wicks=True)
2926
+
2927
+ # make sure we have only one term to consider
2928
+ e = e.expand()
2929
+ if isinstance(e, Add):
2930
+ if opts['simplify_dummies']:
2931
+ return substitute_dummies(Add(*[ wicks(term, **kw_args) for term in e.args]))
2932
+ else:
2933
+ return Add(*[ wicks(term, **kw_args) for term in e.args])
2934
+
2935
+ # For Mul-objects we can actually do something
2936
+ if isinstance(e, Mul):
2937
+
2938
+ # we don't want to mess around with commuting part of Mul
2939
+ # so we factorize it out before starting recursion
2940
+ c_part = []
2941
+ string1 = []
2942
+ for factor in e.args:
2943
+ if factor.is_commutative:
2944
+ c_part.append(factor)
2945
+ else:
2946
+ string1.append(factor)
2947
+ n = len(string1)
2948
+
2949
+ # catch trivial cases
2950
+ if n == 0:
2951
+ result = e
2952
+ elif n == 1:
2953
+ if opts['keep_only_fully_contracted']:
2954
+ return S.Zero
2955
+ else:
2956
+ result = e
2957
+
2958
+ else: # non-trivial
2959
+
2960
+ if isinstance(string1[0], BosonicOperator):
2961
+ raise NotImplementedError
2962
+
2963
+ string1 = tuple(string1)
2964
+
2965
+ # recursion over higher order contractions
2966
+ result = _get_contractions(string1,
2967
+ keep_only_fully_contracted=opts['keep_only_fully_contracted'] )
2968
+ result = Mul(*c_part)*result
2969
+
2970
+ if opts['expand']:
2971
+ result = result.expand()
2972
+ if opts['simplify_kronecker_deltas']:
2973
+ result = evaluate_deltas(result)
2974
+
2975
+ return result
2976
+
2977
+ # there was nothing to do
2978
+ return e
2979
+
2980
+
2981
+ class PermutationOperator(Expr):
2982
+ """
2983
+ Represents the index permutation operator P(ij).
2984
+
2985
+ P(ij)*f(i)*g(j) = f(i)*g(j) - f(j)*g(i)
2986
+ """
2987
+ is_commutative = True
2988
+
2989
+ def __new__(cls, i, j):
2990
+ i, j = sorted(map(sympify, (i, j)), key=default_sort_key)
2991
+ obj = Basic.__new__(cls, i, j)
2992
+ return obj
2993
+
2994
+ def get_permuted(self, expr):
2995
+ """
2996
+ Returns -expr with permuted indices.
2997
+
2998
+ Explanation
2999
+ ===========
3000
+
3001
+ >>> from sympy import symbols, Function
3002
+ >>> from sympy.physics.secondquant import PermutationOperator
3003
+ >>> p,q = symbols('p,q')
3004
+ >>> f = Function('f')
3005
+ >>> PermutationOperator(p,q).get_permuted(f(p,q))
3006
+ -f(q, p)
3007
+
3008
+ """
3009
+ i = self.args[0]
3010
+ j = self.args[1]
3011
+ if expr.has(i) and expr.has(j):
3012
+ tmp = Dummy()
3013
+ expr = expr.subs(i, tmp)
3014
+ expr = expr.subs(j, i)
3015
+ expr = expr.subs(tmp, j)
3016
+ return S.NegativeOne*expr
3017
+ else:
3018
+ return expr
3019
+
3020
+ def _latex(self, printer):
3021
+ return "P(%s%s)" % self.args
3022
+
3023
+
3024
+ def simplify_index_permutations(expr, permutation_operators):
3025
+ """
3026
+ Performs simplification by introducing PermutationOperators where appropriate.
3027
+
3028
+ Explanation
3029
+ ===========
3030
+
3031
+ Schematically:
3032
+ [abij] - [abji] - [baij] + [baji] -> P(ab)*P(ij)*[abij]
3033
+
3034
+ permutation_operators is a list of PermutationOperators to consider.
3035
+
3036
+ If permutation_operators=[P(ab),P(ij)] we will try to introduce the
3037
+ permutation operators P(ij) and P(ab) in the expression. If there are other
3038
+ possible simplifications, we ignore them.
3039
+
3040
+ >>> from sympy import symbols, Function
3041
+ >>> from sympy.physics.secondquant import simplify_index_permutations
3042
+ >>> from sympy.physics.secondquant import PermutationOperator
3043
+ >>> p,q,r,s = symbols('p,q,r,s')
3044
+ >>> f = Function('f')
3045
+ >>> g = Function('g')
3046
+
3047
+ >>> expr = f(p)*g(q) - f(q)*g(p); expr
3048
+ f(p)*g(q) - f(q)*g(p)
3049
+ >>> simplify_index_permutations(expr,[PermutationOperator(p,q)])
3050
+ f(p)*g(q)*PermutationOperator(p, q)
3051
+
3052
+ >>> PermutList = [PermutationOperator(p,q),PermutationOperator(r,s)]
3053
+ >>> expr = f(p,r)*g(q,s) - f(q,r)*g(p,s) + f(q,s)*g(p,r) - f(p,s)*g(q,r)
3054
+ >>> simplify_index_permutations(expr,PermutList)
3055
+ f(p, r)*g(q, s)*PermutationOperator(p, q)*PermutationOperator(r, s)
3056
+
3057
+ """
3058
+
3059
+ def _get_indices(expr, ind):
3060
+ """
3061
+ Collects indices recursively in predictable order.
3062
+ """
3063
+ result = []
3064
+ for arg in expr.args:
3065
+ if arg in ind:
3066
+ result.append(arg)
3067
+ else:
3068
+ if arg.args:
3069
+ result.extend(_get_indices(arg, ind))
3070
+ return result
3071
+
3072
+ def _choose_one_to_keep(a, b, ind):
3073
+ # we keep the one where indices in ind are in order ind[0] < ind[1]
3074
+ return min(a, b, key=lambda x: default_sort_key(_get_indices(x, ind)))
3075
+
3076
+ expr = expr.expand()
3077
+ if isinstance(expr, Add):
3078
+ terms = set(expr.args)
3079
+
3080
+ for P in permutation_operators:
3081
+ new_terms = set()
3082
+ on_hold = set()
3083
+ while terms:
3084
+ term = terms.pop()
3085
+ permuted = P.get_permuted(term)
3086
+ if permuted in terms | on_hold:
3087
+ try:
3088
+ terms.remove(permuted)
3089
+ except KeyError:
3090
+ on_hold.remove(permuted)
3091
+ keep = _choose_one_to_keep(term, permuted, P.args)
3092
+ new_terms.add(P*keep)
3093
+ else:
3094
+
3095
+ # Some terms must get a second chance because the permuted
3096
+ # term may already have canonical dummy ordering. Then
3097
+ # substitute_dummies() does nothing. However, the other
3098
+ # term, if it exists, will be able to match with us.
3099
+ permuted1 = permuted
3100
+ permuted = substitute_dummies(permuted)
3101
+ if permuted1 == permuted:
3102
+ on_hold.add(term)
3103
+ elif permuted in terms | on_hold:
3104
+ try:
3105
+ terms.remove(permuted)
3106
+ except KeyError:
3107
+ on_hold.remove(permuted)
3108
+ keep = _choose_one_to_keep(term, permuted, P.args)
3109
+ new_terms.add(P*keep)
3110
+ else:
3111
+ new_terms.add(term)
3112
+ terms = new_terms | on_hold
3113
+ return Add(*terms)
3114
+ return expr
wemm/lib/python3.10/site-packages/sympy/physics/sho.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, pi, Rational
2
+ from sympy.functions import assoc_laguerre, sqrt, exp, factorial, factorial2
3
+
4
+
5
+ def R_nl(n, l, nu, r):
6
+ """
7
+ Returns the radial wavefunction R_{nl} for a 3d isotropic harmonic
8
+ oscillator.
9
+
10
+ Parameters
11
+ ==========
12
+
13
+ n :
14
+ The "nodal" quantum number. Corresponds to the number of nodes in
15
+ the wavefunction. ``n >= 0``
16
+ l :
17
+ The quantum number for orbital angular momentum.
18
+ nu :
19
+ mass-scaled frequency: nu = m*omega/(2*hbar) where `m` is the mass
20
+ and `omega` the frequency of the oscillator.
21
+ (in atomic units ``nu == omega/2``)
22
+ r :
23
+ Radial coordinate.
24
+
25
+ Examples
26
+ ========
27
+
28
+ >>> from sympy.physics.sho import R_nl
29
+ >>> from sympy.abc import r, nu, l
30
+ >>> R_nl(0, 0, 1, r)
31
+ 2*2**(3/4)*exp(-r**2)/pi**(1/4)
32
+ >>> R_nl(1, 0, 1, r)
33
+ 4*2**(1/4)*sqrt(3)*(3/2 - 2*r**2)*exp(-r**2)/(3*pi**(1/4))
34
+
35
+ l, nu and r may be symbolic:
36
+
37
+ >>> R_nl(0, 0, nu, r)
38
+ 2*2**(3/4)*sqrt(nu**(3/2))*exp(-nu*r**2)/pi**(1/4)
39
+ >>> R_nl(0, l, 1, r)
40
+ r**l*sqrt(2**(l + 3/2)*2**(l + 2)/factorial2(2*l + 1))*exp(-r**2)/pi**(1/4)
41
+
42
+ The normalization of the radial wavefunction is:
43
+
44
+ >>> from sympy import Integral, oo
45
+ >>> Integral(R_nl(0, 0, 1, r)**2*r**2, (r, 0, oo)).n()
46
+ 1.00000000000000
47
+ >>> Integral(R_nl(1, 0, 1, r)**2*r**2, (r, 0, oo)).n()
48
+ 1.00000000000000
49
+ >>> Integral(R_nl(1, 1, 1, r)**2*r**2, (r, 0, oo)).n()
50
+ 1.00000000000000
51
+
52
+ """
53
+ n, l, nu, r = map(S, [n, l, nu, r])
54
+
55
+ # formula uses n >= 1 (instead of nodal n >= 0)
56
+ n = n + 1
57
+ C = sqrt(
58
+ ((2*nu)**(l + Rational(3, 2))*2**(n + l + 1)*factorial(n - 1))/
59
+ (sqrt(pi)*(factorial2(2*n + 2*l - 1)))
60
+ )
61
+ return C*r**(l)*exp(-nu*r**2)*assoc_laguerre(n - 1, l + S.Half, 2*nu*r**2)
62
+
63
+
64
+ def E_nl(n, l, hw):
65
+ """
66
+ Returns the Energy of an isotropic harmonic oscillator.
67
+
68
+ Parameters
69
+ ==========
70
+
71
+ n :
72
+ The "nodal" quantum number.
73
+ l :
74
+ The orbital angular momentum.
75
+ hw :
76
+ The harmonic oscillator parameter.
77
+
78
+ Notes
79
+ =====
80
+
81
+ The unit of the returned value matches the unit of hw, since the energy is
82
+ calculated as:
83
+
84
+ E_nl = (2*n + l + 3/2)*hw
85
+
86
+ Examples
87
+ ========
88
+
89
+ >>> from sympy.physics.sho import E_nl
90
+ >>> from sympy import symbols
91
+ >>> x, y, z = symbols('x, y, z')
92
+ >>> E_nl(x, y, z)
93
+ z*(2*x + y + 3/2)
94
+ """
95
+ return (2*n + l + Rational(3, 2))*hw
wemm/lib/python3.10/site-packages/sympy/physics/units/__init__.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # isort:skip_file
2
+ """
3
+ Dimensional analysis and unit systems.
4
+
5
+ This module defines dimension/unit systems and physical quantities. It is
6
+ based on a group-theoretical construction where dimensions are represented as
7
+ vectors (coefficients being the exponents), and units are defined as a dimension
8
+ to which we added a scale.
9
+
10
+ Quantities are built from a factor and a unit, and are the basic objects that
11
+ one will use when doing computations.
12
+
13
+ All objects except systems and prefixes can be used in SymPy expressions.
14
+ Note that as part of a CAS, various objects do not combine automatically
15
+ under operations.
16
+
17
+ Details about the implementation can be found in the documentation, and we
18
+ will not repeat all the explanations we gave there concerning our approach.
19
+ Ideas about future developments can be found on the `Github wiki
20
+ <https://github.com/sympy/sympy/wiki/Unit-systems>`_, and you should consult
21
+ this page if you are willing to help.
22
+
23
+ Useful functions:
24
+
25
+ - ``find_unit``: easily lookup pre-defined units.
26
+ - ``convert_to(expr, newunit)``: converts an expression into the same
27
+ expression expressed in another unit.
28
+
29
+ """
30
+
31
+ from .dimensions import Dimension, DimensionSystem
32
+ from .unitsystem import UnitSystem
33
+ from .util import convert_to
34
+ from .quantities import Quantity
35
+
36
+ from .definitions.dimension_definitions import (
37
+ amount_of_substance, acceleration, action, area,
38
+ capacitance, charge, conductance, current, energy,
39
+ force, frequency, impedance, inductance, length,
40
+ luminous_intensity, magnetic_density,
41
+ magnetic_flux, mass, momentum, power, pressure, temperature, time,
42
+ velocity, voltage, volume
43
+ )
44
+
45
+ Unit = Quantity
46
+
47
+ speed = velocity
48
+ luminosity = luminous_intensity
49
+ magnetic_flux_density = magnetic_density
50
+ amount = amount_of_substance
51
+
52
+ from .prefixes import (
53
+ # 10-power based:
54
+ yotta,
55
+ zetta,
56
+ exa,
57
+ peta,
58
+ tera,
59
+ giga,
60
+ mega,
61
+ kilo,
62
+ hecto,
63
+ deca,
64
+ deci,
65
+ centi,
66
+ milli,
67
+ micro,
68
+ nano,
69
+ pico,
70
+ femto,
71
+ atto,
72
+ zepto,
73
+ yocto,
74
+ # 2-power based:
75
+ kibi,
76
+ mebi,
77
+ gibi,
78
+ tebi,
79
+ pebi,
80
+ exbi,
81
+ )
82
+
83
+ from .definitions import (
84
+ percent, percents,
85
+ permille,
86
+ rad, radian, radians,
87
+ deg, degree, degrees,
88
+ sr, steradian, steradians,
89
+ mil, angular_mil, angular_mils,
90
+ m, meter, meters,
91
+ kg, kilogram, kilograms,
92
+ s, second, seconds,
93
+ A, ampere, amperes,
94
+ K, kelvin, kelvins,
95
+ mol, mole, moles,
96
+ cd, candela, candelas,
97
+ g, gram, grams,
98
+ mg, milligram, milligrams,
99
+ ug, microgram, micrograms,
100
+ t, tonne, metric_ton,
101
+ newton, newtons, N,
102
+ joule, joules, J,
103
+ watt, watts, W,
104
+ pascal, pascals, Pa, pa,
105
+ hertz, hz, Hz,
106
+ coulomb, coulombs, C,
107
+ volt, volts, v, V,
108
+ ohm, ohms,
109
+ siemens, S, mho, mhos,
110
+ farad, farads, F,
111
+ henry, henrys, H,
112
+ tesla, teslas, T,
113
+ weber, webers, Wb, wb,
114
+ optical_power, dioptre, D,
115
+ lux, lx,
116
+ katal, kat,
117
+ gray, Gy,
118
+ becquerel, Bq,
119
+ km, kilometer, kilometers,
120
+ dm, decimeter, decimeters,
121
+ cm, centimeter, centimeters,
122
+ mm, millimeter, millimeters,
123
+ um, micrometer, micrometers, micron, microns,
124
+ nm, nanometer, nanometers,
125
+ pm, picometer, picometers,
126
+ ft, foot, feet,
127
+ inch, inches,
128
+ yd, yard, yards,
129
+ mi, mile, miles,
130
+ nmi, nautical_mile, nautical_miles,
131
+ angstrom, angstroms,
132
+ ha, hectare,
133
+ l, L, liter, liters,
134
+ dl, dL, deciliter, deciliters,
135
+ cl, cL, centiliter, centiliters,
136
+ ml, mL, milliliter, milliliters,
137
+ ms, millisecond, milliseconds,
138
+ us, microsecond, microseconds,
139
+ ns, nanosecond, nanoseconds,
140
+ ps, picosecond, picoseconds,
141
+ minute, minutes,
142
+ h, hour, hours,
143
+ day, days,
144
+ anomalistic_year, anomalistic_years,
145
+ sidereal_year, sidereal_years,
146
+ tropical_year, tropical_years,
147
+ common_year, common_years,
148
+ julian_year, julian_years,
149
+ draconic_year, draconic_years,
150
+ gaussian_year, gaussian_years,
151
+ full_moon_cycle, full_moon_cycles,
152
+ year, years,
153
+ G, gravitational_constant,
154
+ c, speed_of_light,
155
+ elementary_charge,
156
+ hbar,
157
+ planck,
158
+ eV, electronvolt, electronvolts,
159
+ avogadro_number,
160
+ avogadro, avogadro_constant,
161
+ boltzmann, boltzmann_constant,
162
+ stefan, stefan_boltzmann_constant,
163
+ R, molar_gas_constant,
164
+ faraday_constant,
165
+ josephson_constant,
166
+ von_klitzing_constant,
167
+ Da, dalton, amu, amus, atomic_mass_unit, atomic_mass_constant,
168
+ me, electron_rest_mass,
169
+ gee, gees, acceleration_due_to_gravity,
170
+ u0, magnetic_constant, vacuum_permeability,
171
+ e0, electric_constant, vacuum_permittivity,
172
+ Z0, vacuum_impedance,
173
+ coulomb_constant, electric_force_constant,
174
+ atmosphere, atmospheres, atm,
175
+ kPa,
176
+ bar, bars,
177
+ pound, pounds,
178
+ psi,
179
+ dHg0,
180
+ mmHg, torr,
181
+ mmu, mmus, milli_mass_unit,
182
+ quart, quarts,
183
+ ly, lightyear, lightyears,
184
+ au, astronomical_unit, astronomical_units,
185
+ planck_mass,
186
+ planck_time,
187
+ planck_temperature,
188
+ planck_length,
189
+ planck_charge,
190
+ planck_area,
191
+ planck_volume,
192
+ planck_momentum,
193
+ planck_energy,
194
+ planck_force,
195
+ planck_power,
196
+ planck_density,
197
+ planck_energy_density,
198
+ planck_intensity,
199
+ planck_angular_frequency,
200
+ planck_pressure,
201
+ planck_current,
202
+ planck_voltage,
203
+ planck_impedance,
204
+ planck_acceleration,
205
+ bit, bits,
206
+ byte,
207
+ kibibyte, kibibytes,
208
+ mebibyte, mebibytes,
209
+ gibibyte, gibibytes,
210
+ tebibyte, tebibytes,
211
+ pebibyte, pebibytes,
212
+ exbibyte, exbibytes,
213
+ )
214
+
215
+ from .systems import (
216
+ mks, mksa, si
217
+ )
218
+
219
+
220
+ def find_unit(quantity, unit_system="SI"):
221
+ """
222
+ Return a list of matching units or dimension names.
223
+
224
+ - If ``quantity`` is a string -- units/dimensions containing the string
225
+ `quantity`.
226
+ - If ``quantity`` is a unit or dimension -- units having matching base
227
+ units or dimensions.
228
+
229
+ Examples
230
+ ========
231
+
232
+ >>> from sympy.physics import units as u
233
+ >>> u.find_unit('charge')
234
+ ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
235
+ >>> u.find_unit(u.charge)
236
+ ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
237
+ >>> u.find_unit("ampere")
238
+ ['ampere', 'amperes']
239
+ >>> u.find_unit('angstrom')
240
+ ['angstrom', 'angstroms']
241
+ >>> u.find_unit('volt')
242
+ ['volt', 'volts', 'electronvolt', 'electronvolts', 'planck_voltage']
243
+ >>> u.find_unit(u.inch**3)[:9]
244
+ ['L', 'l', 'cL', 'cl', 'dL', 'dl', 'mL', 'ml', 'liter']
245
+ """
246
+ unit_system = UnitSystem.get_unit_system(unit_system)
247
+
248
+ import sympy.physics.units as u
249
+ rv = []
250
+ if isinstance(quantity, str):
251
+ rv = [i for i in dir(u) if quantity in i and isinstance(getattr(u, i), Quantity)]
252
+ dim = getattr(u, quantity)
253
+ if isinstance(dim, Dimension):
254
+ rv.extend(find_unit(dim))
255
+ else:
256
+ for i in sorted(dir(u)):
257
+ other = getattr(u, i)
258
+ if not isinstance(other, Quantity):
259
+ continue
260
+ if isinstance(quantity, Quantity):
261
+ if quantity.dimension == other.dimension:
262
+ rv.append(str(i))
263
+ elif isinstance(quantity, Dimension):
264
+ if other.dimension == quantity:
265
+ rv.append(str(i))
266
+ elif other.dimension == Dimension(unit_system.get_dimensional_expr(quantity)):
267
+ rv.append(str(i))
268
+ return sorted(set(rv), key=lambda x: (len(x), x))
269
+
270
+ # NOTE: the old units module had additional variables:
271
+ # 'density', 'illuminance', 'resistance'.
272
+ # They were not dimensions, but units (old Unit class).
273
+
274
+ __all__ = [
275
+ 'Dimension', 'DimensionSystem',
276
+ 'UnitSystem',
277
+ 'convert_to',
278
+ 'Quantity',
279
+
280
+ 'amount_of_substance', 'acceleration', 'action', 'area',
281
+ 'capacitance', 'charge', 'conductance', 'current', 'energy',
282
+ 'force', 'frequency', 'impedance', 'inductance', 'length',
283
+ 'luminous_intensity', 'magnetic_density',
284
+ 'magnetic_flux', 'mass', 'momentum', 'power', 'pressure', 'temperature', 'time',
285
+ 'velocity', 'voltage', 'volume',
286
+
287
+ 'Unit',
288
+
289
+ 'speed',
290
+ 'luminosity',
291
+ 'magnetic_flux_density',
292
+ 'amount',
293
+
294
+ 'yotta',
295
+ 'zetta',
296
+ 'exa',
297
+ 'peta',
298
+ 'tera',
299
+ 'giga',
300
+ 'mega',
301
+ 'kilo',
302
+ 'hecto',
303
+ 'deca',
304
+ 'deci',
305
+ 'centi',
306
+ 'milli',
307
+ 'micro',
308
+ 'nano',
309
+ 'pico',
310
+ 'femto',
311
+ 'atto',
312
+ 'zepto',
313
+ 'yocto',
314
+
315
+ 'kibi',
316
+ 'mebi',
317
+ 'gibi',
318
+ 'tebi',
319
+ 'pebi',
320
+ 'exbi',
321
+
322
+ 'percent', 'percents',
323
+ 'permille',
324
+ 'rad', 'radian', 'radians',
325
+ 'deg', 'degree', 'degrees',
326
+ 'sr', 'steradian', 'steradians',
327
+ 'mil', 'angular_mil', 'angular_mils',
328
+ 'm', 'meter', 'meters',
329
+ 'kg', 'kilogram', 'kilograms',
330
+ 's', 'second', 'seconds',
331
+ 'A', 'ampere', 'amperes',
332
+ 'K', 'kelvin', 'kelvins',
333
+ 'mol', 'mole', 'moles',
334
+ 'cd', 'candela', 'candelas',
335
+ 'g', 'gram', 'grams',
336
+ 'mg', 'milligram', 'milligrams',
337
+ 'ug', 'microgram', 'micrograms',
338
+ 't', 'tonne', 'metric_ton',
339
+ 'newton', 'newtons', 'N',
340
+ 'joule', 'joules', 'J',
341
+ 'watt', 'watts', 'W',
342
+ 'pascal', 'pascals', 'Pa', 'pa',
343
+ 'hertz', 'hz', 'Hz',
344
+ 'coulomb', 'coulombs', 'C',
345
+ 'volt', 'volts', 'v', 'V',
346
+ 'ohm', 'ohms',
347
+ 'siemens', 'S', 'mho', 'mhos',
348
+ 'farad', 'farads', 'F',
349
+ 'henry', 'henrys', 'H',
350
+ 'tesla', 'teslas', 'T',
351
+ 'weber', 'webers', 'Wb', 'wb',
352
+ 'optical_power', 'dioptre', 'D',
353
+ 'lux', 'lx',
354
+ 'katal', 'kat',
355
+ 'gray', 'Gy',
356
+ 'becquerel', 'Bq',
357
+ 'km', 'kilometer', 'kilometers',
358
+ 'dm', 'decimeter', 'decimeters',
359
+ 'cm', 'centimeter', 'centimeters',
360
+ 'mm', 'millimeter', 'millimeters',
361
+ 'um', 'micrometer', 'micrometers', 'micron', 'microns',
362
+ 'nm', 'nanometer', 'nanometers',
363
+ 'pm', 'picometer', 'picometers',
364
+ 'ft', 'foot', 'feet',
365
+ 'inch', 'inches',
366
+ 'yd', 'yard', 'yards',
367
+ 'mi', 'mile', 'miles',
368
+ 'nmi', 'nautical_mile', 'nautical_miles',
369
+ 'angstrom', 'angstroms',
370
+ 'ha', 'hectare',
371
+ 'l', 'L', 'liter', 'liters',
372
+ 'dl', 'dL', 'deciliter', 'deciliters',
373
+ 'cl', 'cL', 'centiliter', 'centiliters',
374
+ 'ml', 'mL', 'milliliter', 'milliliters',
375
+ 'ms', 'millisecond', 'milliseconds',
376
+ 'us', 'microsecond', 'microseconds',
377
+ 'ns', 'nanosecond', 'nanoseconds',
378
+ 'ps', 'picosecond', 'picoseconds',
379
+ 'minute', 'minutes',
380
+ 'h', 'hour', 'hours',
381
+ 'day', 'days',
382
+ 'anomalistic_year', 'anomalistic_years',
383
+ 'sidereal_year', 'sidereal_years',
384
+ 'tropical_year', 'tropical_years',
385
+ 'common_year', 'common_years',
386
+ 'julian_year', 'julian_years',
387
+ 'draconic_year', 'draconic_years',
388
+ 'gaussian_year', 'gaussian_years',
389
+ 'full_moon_cycle', 'full_moon_cycles',
390
+ 'year', 'years',
391
+ 'G', 'gravitational_constant',
392
+ 'c', 'speed_of_light',
393
+ 'elementary_charge',
394
+ 'hbar',
395
+ 'planck',
396
+ 'eV', 'electronvolt', 'electronvolts',
397
+ 'avogadro_number',
398
+ 'avogadro', 'avogadro_constant',
399
+ 'boltzmann', 'boltzmann_constant',
400
+ 'stefan', 'stefan_boltzmann_constant',
401
+ 'R', 'molar_gas_constant',
402
+ 'faraday_constant',
403
+ 'josephson_constant',
404
+ 'von_klitzing_constant',
405
+ 'Da', 'dalton', 'amu', 'amus', 'atomic_mass_unit', 'atomic_mass_constant',
406
+ 'me', 'electron_rest_mass',
407
+ 'gee', 'gees', 'acceleration_due_to_gravity',
408
+ 'u0', 'magnetic_constant', 'vacuum_permeability',
409
+ 'e0', 'electric_constant', 'vacuum_permittivity',
410
+ 'Z0', 'vacuum_impedance',
411
+ 'coulomb_constant', 'electric_force_constant',
412
+ 'atmosphere', 'atmospheres', 'atm',
413
+ 'kPa',
414
+ 'bar', 'bars',
415
+ 'pound', 'pounds',
416
+ 'psi',
417
+ 'dHg0',
418
+ 'mmHg', 'torr',
419
+ 'mmu', 'mmus', 'milli_mass_unit',
420
+ 'quart', 'quarts',
421
+ 'ly', 'lightyear', 'lightyears',
422
+ 'au', 'astronomical_unit', 'astronomical_units',
423
+ 'planck_mass',
424
+ 'planck_time',
425
+ 'planck_temperature',
426
+ 'planck_length',
427
+ 'planck_charge',
428
+ 'planck_area',
429
+ 'planck_volume',
430
+ 'planck_momentum',
431
+ 'planck_energy',
432
+ 'planck_force',
433
+ 'planck_power',
434
+ 'planck_density',
435
+ 'planck_energy_density',
436
+ 'planck_intensity',
437
+ 'planck_angular_frequency',
438
+ 'planck_pressure',
439
+ 'planck_current',
440
+ 'planck_voltage',
441
+ 'planck_impedance',
442
+ 'planck_acceleration',
443
+ 'bit', 'bits',
444
+ 'byte',
445
+ 'kibibyte', 'kibibytes',
446
+ 'mebibyte', 'mebibytes',
447
+ 'gibibyte', 'gibibytes',
448
+ 'tebibyte', 'tebibytes',
449
+ 'pebibyte', 'pebibytes',
450
+ 'exbibyte', 'exbibytes',
451
+
452
+ 'mks', 'mksa', 'si',
453
+ ]
wemm/lib/python3.10/site-packages/sympy/physics/units/__pycache__/dimensions.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/physics/units/__pycache__/prefixes.cpython-310.pyc ADDED
Binary file (6.1 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/physics/units/__pycache__/unitsystem.cpython-310.pyc ADDED
Binary file (7.7 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/physics/units/__pycache__/util.cpython-310.pyc ADDED
Binary file (9.96 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (6.02 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-310.pyc ADDED
Binary file (1.1 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-310.pyc ADDED
Binary file (9.63 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/physics/units/definitions/dimension_definitions.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.units import Dimension
2
+
3
+
4
+ angle = Dimension(name="angle") # type: Dimension
5
+
6
+ # base dimensions (MKS)
7
+ length = Dimension(name="length", symbol="L")
8
+ mass = Dimension(name="mass", symbol="M")
9
+ time = Dimension(name="time", symbol="T")
10
+
11
+ # base dimensions (MKSA not in MKS)
12
+ current = Dimension(name='current', symbol='I') # type: Dimension
13
+
14
+ # other base dimensions:
15
+ temperature = Dimension("temperature", "T") # type: Dimension
16
+ amount_of_substance = Dimension("amount_of_substance") # type: Dimension
17
+ luminous_intensity = Dimension("luminous_intensity") # type: Dimension
18
+
19
+ # derived dimensions (MKS)
20
+ velocity = Dimension(name="velocity")
21
+ acceleration = Dimension(name="acceleration")
22
+ momentum = Dimension(name="momentum")
23
+ force = Dimension(name="force", symbol="F")
24
+ energy = Dimension(name="energy", symbol="E")
25
+ power = Dimension(name="power")
26
+ pressure = Dimension(name="pressure")
27
+ frequency = Dimension(name="frequency", symbol="f")
28
+ action = Dimension(name="action", symbol="A")
29
+ area = Dimension("area")
30
+ volume = Dimension("volume")
31
+
32
+ # derived dimensions (MKSA not in MKS)
33
+ voltage = Dimension(name='voltage', symbol='U') # type: Dimension
34
+ impedance = Dimension(name='impedance', symbol='Z') # type: Dimension
35
+ conductance = Dimension(name='conductance', symbol='G') # type: Dimension
36
+ capacitance = Dimension(name='capacitance') # type: Dimension
37
+ inductance = Dimension(name='inductance') # type: Dimension
38
+ charge = Dimension(name='charge', symbol='Q') # type: Dimension
39
+ magnetic_density = Dimension(name='magnetic_density', symbol='B') # type: Dimension
40
+ magnetic_flux = Dimension(name='magnetic_flux') # type: Dimension
41
+
42
+ # Dimensions in information theory:
43
+ information = Dimension(name='information') # type: Dimension