Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. Β
See raw diff
- evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/__init__.py +8 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/printing.py +562 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/session.py +463 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_interactive.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_ipython.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/test_interactive.py +10 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py +278 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/__init__.py +12 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/hydrogen.py +265 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/matrices.py +176 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/paulialgebra.py +231 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/pring.py +94 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/qho_1d.py +88 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/secondquant.py +3114 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/sho.py +95 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/__init__.py +453 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/__init__.py +265 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/dimension_definitions.py +43 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/unit_definitions.py +407 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/dimensions.py +590 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/prefixes.py +219 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/quantities.py +152 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/systems/__init__.py +6 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/length_weight_time.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/mksa.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/__init__.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensions.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensionsystem.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_quantities.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensions.py +150 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensionsystem.py +95 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_prefixes.py +86 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_quantities.py +575 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_unit_system_cgs_gauss.py +55 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_unitsystem.py +86 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_util.py +178 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/unitsystem.py +205 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/util.py +265 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/physics/wigner.py +1191 -0
evalkit_internvl/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (770 Bytes). View file
|
|
|
evalkit_internvl/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']
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (434 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc
ADDED
|
Binary file (17.4 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc
ADDED
|
Binary file (11.8 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc
ADDED
|
Binary file (2.44 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/printing.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/session.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"))
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py
ADDED
|
File without changes
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (185 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_interactive.cpython-310.pyc
ADDED
|
Binary file (694 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_ipython.cpython-310.pyc
ADDED
|
Binary file (6.65 kB). View file
|
|
|
evalkit_internvl/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 '
|
evalkit_internvl/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'
|
evalkit_internvl/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,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/matrices.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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()
|
evalkit_internvl/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
|
evalkit_internvl/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")
|
evalkit_internvl/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))
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/secondquant.py
ADDED
|
@@ -0,0 +1,3114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
evalkit_internvl/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
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/__init__.py
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/__init__.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .unit_definitions import (
|
| 2 |
+
percent, percents,
|
| 3 |
+
permille,
|
| 4 |
+
rad, radian, radians,
|
| 5 |
+
deg, degree, degrees,
|
| 6 |
+
sr, steradian, steradians,
|
| 7 |
+
mil, angular_mil, angular_mils,
|
| 8 |
+
m, meter, meters,
|
| 9 |
+
kg, kilogram, kilograms,
|
| 10 |
+
s, second, seconds,
|
| 11 |
+
A, ampere, amperes,
|
| 12 |
+
K, kelvin, kelvins,
|
| 13 |
+
mol, mole, moles,
|
| 14 |
+
cd, candela, candelas,
|
| 15 |
+
g, gram, grams,
|
| 16 |
+
mg, milligram, milligrams,
|
| 17 |
+
ug, microgram, micrograms,
|
| 18 |
+
t, tonne, metric_ton,
|
| 19 |
+
newton, newtons, N,
|
| 20 |
+
joule, joules, J,
|
| 21 |
+
watt, watts, W,
|
| 22 |
+
pascal, pascals, Pa, pa,
|
| 23 |
+
hertz, hz, Hz,
|
| 24 |
+
coulomb, coulombs, C,
|
| 25 |
+
volt, volts, v, V,
|
| 26 |
+
ohm, ohms,
|
| 27 |
+
siemens, S, mho, mhos,
|
| 28 |
+
farad, farads, F,
|
| 29 |
+
henry, henrys, H,
|
| 30 |
+
tesla, teslas, T,
|
| 31 |
+
weber, webers, Wb, wb,
|
| 32 |
+
optical_power, dioptre, D,
|
| 33 |
+
lux, lx,
|
| 34 |
+
katal, kat,
|
| 35 |
+
gray, Gy,
|
| 36 |
+
becquerel, Bq,
|
| 37 |
+
km, kilometer, kilometers,
|
| 38 |
+
dm, decimeter, decimeters,
|
| 39 |
+
cm, centimeter, centimeters,
|
| 40 |
+
mm, millimeter, millimeters,
|
| 41 |
+
um, micrometer, micrometers, micron, microns,
|
| 42 |
+
nm, nanometer, nanometers,
|
| 43 |
+
pm, picometer, picometers,
|
| 44 |
+
ft, foot, feet,
|
| 45 |
+
inch, inches,
|
| 46 |
+
yd, yard, yards,
|
| 47 |
+
mi, mile, miles,
|
| 48 |
+
nmi, nautical_mile, nautical_miles,
|
| 49 |
+
ha, hectare,
|
| 50 |
+
l, L, liter, liters,
|
| 51 |
+
dl, dL, deciliter, deciliters,
|
| 52 |
+
cl, cL, centiliter, centiliters,
|
| 53 |
+
ml, mL, milliliter, milliliters,
|
| 54 |
+
ms, millisecond, milliseconds,
|
| 55 |
+
us, microsecond, microseconds,
|
| 56 |
+
ns, nanosecond, nanoseconds,
|
| 57 |
+
ps, picosecond, picoseconds,
|
| 58 |
+
minute, minutes,
|
| 59 |
+
h, hour, hours,
|
| 60 |
+
day, days,
|
| 61 |
+
anomalistic_year, anomalistic_years,
|
| 62 |
+
sidereal_year, sidereal_years,
|
| 63 |
+
tropical_year, tropical_years,
|
| 64 |
+
common_year, common_years,
|
| 65 |
+
julian_year, julian_years,
|
| 66 |
+
draconic_year, draconic_years,
|
| 67 |
+
gaussian_year, gaussian_years,
|
| 68 |
+
full_moon_cycle, full_moon_cycles,
|
| 69 |
+
year, years,
|
| 70 |
+
G, gravitational_constant,
|
| 71 |
+
c, speed_of_light,
|
| 72 |
+
elementary_charge,
|
| 73 |
+
hbar,
|
| 74 |
+
planck,
|
| 75 |
+
eV, electronvolt, electronvolts,
|
| 76 |
+
avogadro_number,
|
| 77 |
+
avogadro, avogadro_constant,
|
| 78 |
+
boltzmann, boltzmann_constant,
|
| 79 |
+
stefan, stefan_boltzmann_constant,
|
| 80 |
+
R, molar_gas_constant,
|
| 81 |
+
faraday_constant,
|
| 82 |
+
josephson_constant,
|
| 83 |
+
von_klitzing_constant,
|
| 84 |
+
Da, dalton, amu, amus, atomic_mass_unit, atomic_mass_constant,
|
| 85 |
+
me, electron_rest_mass,
|
| 86 |
+
gee, gees, acceleration_due_to_gravity,
|
| 87 |
+
u0, magnetic_constant, vacuum_permeability,
|
| 88 |
+
e0, electric_constant, vacuum_permittivity,
|
| 89 |
+
Z0, vacuum_impedance,
|
| 90 |
+
coulomb_constant, coulombs_constant, electric_force_constant,
|
| 91 |
+
atmosphere, atmospheres, atm,
|
| 92 |
+
kPa, kilopascal,
|
| 93 |
+
bar, bars,
|
| 94 |
+
pound, pounds,
|
| 95 |
+
psi,
|
| 96 |
+
dHg0,
|
| 97 |
+
mmHg, torr,
|
| 98 |
+
mmu, mmus, milli_mass_unit,
|
| 99 |
+
quart, quarts,
|
| 100 |
+
angstrom, angstroms,
|
| 101 |
+
ly, lightyear, lightyears,
|
| 102 |
+
au, astronomical_unit, astronomical_units,
|
| 103 |
+
planck_mass,
|
| 104 |
+
planck_time,
|
| 105 |
+
planck_temperature,
|
| 106 |
+
planck_length,
|
| 107 |
+
planck_charge,
|
| 108 |
+
planck_area,
|
| 109 |
+
planck_volume,
|
| 110 |
+
planck_momentum,
|
| 111 |
+
planck_energy,
|
| 112 |
+
planck_force,
|
| 113 |
+
planck_power,
|
| 114 |
+
planck_density,
|
| 115 |
+
planck_energy_density,
|
| 116 |
+
planck_intensity,
|
| 117 |
+
planck_angular_frequency,
|
| 118 |
+
planck_pressure,
|
| 119 |
+
planck_current,
|
| 120 |
+
planck_voltage,
|
| 121 |
+
planck_impedance,
|
| 122 |
+
planck_acceleration,
|
| 123 |
+
bit, bits,
|
| 124 |
+
byte,
|
| 125 |
+
kibibyte, kibibytes,
|
| 126 |
+
mebibyte, mebibytes,
|
| 127 |
+
gibibyte, gibibytes,
|
| 128 |
+
tebibyte, tebibytes,
|
| 129 |
+
pebibyte, pebibytes,
|
| 130 |
+
exbibyte, exbibytes,
|
| 131 |
+
curie, rutherford
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
__all__ = [
|
| 135 |
+
'percent', 'percents',
|
| 136 |
+
'permille',
|
| 137 |
+
'rad', 'radian', 'radians',
|
| 138 |
+
'deg', 'degree', 'degrees',
|
| 139 |
+
'sr', 'steradian', 'steradians',
|
| 140 |
+
'mil', 'angular_mil', 'angular_mils',
|
| 141 |
+
'm', 'meter', 'meters',
|
| 142 |
+
'kg', 'kilogram', 'kilograms',
|
| 143 |
+
's', 'second', 'seconds',
|
| 144 |
+
'A', 'ampere', 'amperes',
|
| 145 |
+
'K', 'kelvin', 'kelvins',
|
| 146 |
+
'mol', 'mole', 'moles',
|
| 147 |
+
'cd', 'candela', 'candelas',
|
| 148 |
+
'g', 'gram', 'grams',
|
| 149 |
+
'mg', 'milligram', 'milligrams',
|
| 150 |
+
'ug', 'microgram', 'micrograms',
|
| 151 |
+
't', 'tonne', 'metric_ton',
|
| 152 |
+
'newton', 'newtons', 'N',
|
| 153 |
+
'joule', 'joules', 'J',
|
| 154 |
+
'watt', 'watts', 'W',
|
| 155 |
+
'pascal', 'pascals', 'Pa', 'pa',
|
| 156 |
+
'hertz', 'hz', 'Hz',
|
| 157 |
+
'coulomb', 'coulombs', 'C',
|
| 158 |
+
'volt', 'volts', 'v', 'V',
|
| 159 |
+
'ohm', 'ohms',
|
| 160 |
+
'siemens', 'S', 'mho', 'mhos',
|
| 161 |
+
'farad', 'farads', 'F',
|
| 162 |
+
'henry', 'henrys', 'H',
|
| 163 |
+
'tesla', 'teslas', 'T',
|
| 164 |
+
'weber', 'webers', 'Wb', 'wb',
|
| 165 |
+
'optical_power', 'dioptre', 'D',
|
| 166 |
+
'lux', 'lx',
|
| 167 |
+
'katal', 'kat',
|
| 168 |
+
'gray', 'Gy',
|
| 169 |
+
'becquerel', 'Bq',
|
| 170 |
+
'km', 'kilometer', 'kilometers',
|
| 171 |
+
'dm', 'decimeter', 'decimeters',
|
| 172 |
+
'cm', 'centimeter', 'centimeters',
|
| 173 |
+
'mm', 'millimeter', 'millimeters',
|
| 174 |
+
'um', 'micrometer', 'micrometers', 'micron', 'microns',
|
| 175 |
+
'nm', 'nanometer', 'nanometers',
|
| 176 |
+
'pm', 'picometer', 'picometers',
|
| 177 |
+
'ft', 'foot', 'feet',
|
| 178 |
+
'inch', 'inches',
|
| 179 |
+
'yd', 'yard', 'yards',
|
| 180 |
+
'mi', 'mile', 'miles',
|
| 181 |
+
'nmi', 'nautical_mile', 'nautical_miles',
|
| 182 |
+
'ha', 'hectare',
|
| 183 |
+
'l', 'L', 'liter', 'liters',
|
| 184 |
+
'dl', 'dL', 'deciliter', 'deciliters',
|
| 185 |
+
'cl', 'cL', 'centiliter', 'centiliters',
|
| 186 |
+
'ml', 'mL', 'milliliter', 'milliliters',
|
| 187 |
+
'ms', 'millisecond', 'milliseconds',
|
| 188 |
+
'us', 'microsecond', 'microseconds',
|
| 189 |
+
'ns', 'nanosecond', 'nanoseconds',
|
| 190 |
+
'ps', 'picosecond', 'picoseconds',
|
| 191 |
+
'minute', 'minutes',
|
| 192 |
+
'h', 'hour', 'hours',
|
| 193 |
+
'day', 'days',
|
| 194 |
+
'anomalistic_year', 'anomalistic_years',
|
| 195 |
+
'sidereal_year', 'sidereal_years',
|
| 196 |
+
'tropical_year', 'tropical_years',
|
| 197 |
+
'common_year', 'common_years',
|
| 198 |
+
'julian_year', 'julian_years',
|
| 199 |
+
'draconic_year', 'draconic_years',
|
| 200 |
+
'gaussian_year', 'gaussian_years',
|
| 201 |
+
'full_moon_cycle', 'full_moon_cycles',
|
| 202 |
+
'year', 'years',
|
| 203 |
+
'G', 'gravitational_constant',
|
| 204 |
+
'c', 'speed_of_light',
|
| 205 |
+
'elementary_charge',
|
| 206 |
+
'hbar',
|
| 207 |
+
'planck',
|
| 208 |
+
'eV', 'electronvolt', 'electronvolts',
|
| 209 |
+
'avogadro_number',
|
| 210 |
+
'avogadro', 'avogadro_constant',
|
| 211 |
+
'boltzmann', 'boltzmann_constant',
|
| 212 |
+
'stefan', 'stefan_boltzmann_constant',
|
| 213 |
+
'R', 'molar_gas_constant',
|
| 214 |
+
'faraday_constant',
|
| 215 |
+
'josephson_constant',
|
| 216 |
+
'von_klitzing_constant',
|
| 217 |
+
'Da', 'dalton', 'amu', 'amus', 'atomic_mass_unit', 'atomic_mass_constant',
|
| 218 |
+
'me', 'electron_rest_mass',
|
| 219 |
+
'gee', 'gees', 'acceleration_due_to_gravity',
|
| 220 |
+
'u0', 'magnetic_constant', 'vacuum_permeability',
|
| 221 |
+
'e0', 'electric_constant', 'vacuum_permittivity',
|
| 222 |
+
'Z0', 'vacuum_impedance',
|
| 223 |
+
'coulomb_constant', 'coulombs_constant', 'electric_force_constant',
|
| 224 |
+
'atmosphere', 'atmospheres', 'atm',
|
| 225 |
+
'kPa', 'kilopascal',
|
| 226 |
+
'bar', 'bars',
|
| 227 |
+
'pound', 'pounds',
|
| 228 |
+
'psi',
|
| 229 |
+
'dHg0',
|
| 230 |
+
'mmHg', 'torr',
|
| 231 |
+
'mmu', 'mmus', 'milli_mass_unit',
|
| 232 |
+
'quart', 'quarts',
|
| 233 |
+
'angstrom', 'angstroms',
|
| 234 |
+
'ly', 'lightyear', 'lightyears',
|
| 235 |
+
'au', 'astronomical_unit', 'astronomical_units',
|
| 236 |
+
'planck_mass',
|
| 237 |
+
'planck_time',
|
| 238 |
+
'planck_temperature',
|
| 239 |
+
'planck_length',
|
| 240 |
+
'planck_charge',
|
| 241 |
+
'planck_area',
|
| 242 |
+
'planck_volume',
|
| 243 |
+
'planck_momentum',
|
| 244 |
+
'planck_energy',
|
| 245 |
+
'planck_force',
|
| 246 |
+
'planck_power',
|
| 247 |
+
'planck_density',
|
| 248 |
+
'planck_energy_density',
|
| 249 |
+
'planck_intensity',
|
| 250 |
+
'planck_angular_frequency',
|
| 251 |
+
'planck_pressure',
|
| 252 |
+
'planck_current',
|
| 253 |
+
'planck_voltage',
|
| 254 |
+
'planck_impedance',
|
| 255 |
+
'planck_acceleration',
|
| 256 |
+
'bit', 'bits',
|
| 257 |
+
'byte',
|
| 258 |
+
'kibibyte', 'kibibytes',
|
| 259 |
+
'mebibyte', 'mebibytes',
|
| 260 |
+
'gibibyte', 'gibibytes',
|
| 261 |
+
'tebibyte', 'tebibytes',
|
| 262 |
+
'pebibyte', 'pebibytes',
|
| 263 |
+
'exbibyte', 'exbibytes',
|
| 264 |
+
'curie', 'rutherford',
|
| 265 |
+
]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (6.03 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-310.pyc
ADDED
|
Binary file (1.12 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-310.pyc
ADDED
|
Binary file (9.64 kB). View file
|
|
|
evalkit_internvl/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
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/definitions/unit_definitions.py
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.physics.units.definitions.dimension_definitions import current, temperature, amount_of_substance, \
|
| 2 |
+
luminous_intensity, angle, charge, voltage, impedance, conductance, capacitance, inductance, magnetic_density, \
|
| 3 |
+
magnetic_flux, information
|
| 4 |
+
|
| 5 |
+
from sympy.core.numbers import (Rational, pi)
|
| 6 |
+
from sympy.core.singleton import S as S_singleton
|
| 7 |
+
from sympy.physics.units.prefixes import kilo, mega, milli, micro, deci, centi, nano, pico, kibi, mebi, gibi, tebi, pebi, exbi
|
| 8 |
+
from sympy.physics.units.quantities import PhysicalConstant, Quantity
|
| 9 |
+
|
| 10 |
+
One = S_singleton.One
|
| 11 |
+
|
| 12 |
+
#### UNITS ####
|
| 13 |
+
|
| 14 |
+
# Dimensionless:
|
| 15 |
+
percent = percents = Quantity("percent", latex_repr=r"\%")
|
| 16 |
+
percent.set_global_relative_scale_factor(Rational(1, 100), One)
|
| 17 |
+
|
| 18 |
+
permille = Quantity("permille")
|
| 19 |
+
permille.set_global_relative_scale_factor(Rational(1, 1000), One)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Angular units (dimensionless)
|
| 23 |
+
rad = radian = radians = Quantity("radian", abbrev="rad")
|
| 24 |
+
radian.set_global_dimension(angle)
|
| 25 |
+
deg = degree = degrees = Quantity("degree", abbrev="deg", latex_repr=r"^\circ")
|
| 26 |
+
degree.set_global_relative_scale_factor(pi/180, radian)
|
| 27 |
+
sr = steradian = steradians = Quantity("steradian", abbrev="sr")
|
| 28 |
+
mil = angular_mil = angular_mils = Quantity("angular_mil", abbrev="mil")
|
| 29 |
+
|
| 30 |
+
# Base units:
|
| 31 |
+
m = meter = meters = Quantity("meter", abbrev="m")
|
| 32 |
+
|
| 33 |
+
# gram; used to define its prefixed units
|
| 34 |
+
g = gram = grams = Quantity("gram", abbrev="g")
|
| 35 |
+
|
| 36 |
+
# NOTE: the `kilogram` has scale factor 1000. In SI, kg is a base unit, but
|
| 37 |
+
# nonetheless we are trying to be compatible with the `kilo` prefix. In a
|
| 38 |
+
# similar manner, people using CGS or gaussian units could argue that the
|
| 39 |
+
# `centimeter` rather than `meter` is the fundamental unit for length, but the
|
| 40 |
+
# scale factor of `centimeter` will be kept as 1/100 to be compatible with the
|
| 41 |
+
# `centi` prefix. The current state of the code assumes SI unit dimensions, in
|
| 42 |
+
# the future this module will be modified in order to be unit system-neutral
|
| 43 |
+
# (that is, support all kinds of unit systems).
|
| 44 |
+
kg = kilogram = kilograms = Quantity("kilogram", abbrev="kg")
|
| 45 |
+
kg.set_global_relative_scale_factor(kilo, gram)
|
| 46 |
+
|
| 47 |
+
s = second = seconds = Quantity("second", abbrev="s")
|
| 48 |
+
A = ampere = amperes = Quantity("ampere", abbrev='A')
|
| 49 |
+
ampere.set_global_dimension(current)
|
| 50 |
+
K = kelvin = kelvins = Quantity("kelvin", abbrev='K')
|
| 51 |
+
kelvin.set_global_dimension(temperature)
|
| 52 |
+
mol = mole = moles = Quantity("mole", abbrev="mol")
|
| 53 |
+
mole.set_global_dimension(amount_of_substance)
|
| 54 |
+
cd = candela = candelas = Quantity("candela", abbrev="cd")
|
| 55 |
+
candela.set_global_dimension(luminous_intensity)
|
| 56 |
+
|
| 57 |
+
# derived units
|
| 58 |
+
newton = newtons = N = Quantity("newton", abbrev="N")
|
| 59 |
+
|
| 60 |
+
kilonewton = kilonewtons = kN = Quantity("kilonewton", abbrev="kN")
|
| 61 |
+
kilonewton.set_global_relative_scale_factor(kilo, newton)
|
| 62 |
+
|
| 63 |
+
meganewton = meganewtons = MN = Quantity("meganewton", abbrev="MN")
|
| 64 |
+
meganewton.set_global_relative_scale_factor(mega, newton)
|
| 65 |
+
|
| 66 |
+
joule = joules = J = Quantity("joule", abbrev="J")
|
| 67 |
+
watt = watts = W = Quantity("watt", abbrev="W")
|
| 68 |
+
pascal = pascals = Pa = pa = Quantity("pascal", abbrev="Pa")
|
| 69 |
+
hertz = hz = Hz = Quantity("hertz", abbrev="Hz")
|
| 70 |
+
|
| 71 |
+
# CGS derived units:
|
| 72 |
+
dyne = Quantity("dyne")
|
| 73 |
+
dyne.set_global_relative_scale_factor(One/10**5, newton)
|
| 74 |
+
erg = Quantity("erg")
|
| 75 |
+
erg.set_global_relative_scale_factor(One/10**7, joule)
|
| 76 |
+
|
| 77 |
+
# MKSA extension to MKS: derived units
|
| 78 |
+
coulomb = coulombs = C = Quantity("coulomb", abbrev='C')
|
| 79 |
+
coulomb.set_global_dimension(charge)
|
| 80 |
+
volt = volts = v = V = Quantity("volt", abbrev='V')
|
| 81 |
+
volt.set_global_dimension(voltage)
|
| 82 |
+
ohm = ohms = Quantity("ohm", abbrev='ohm', latex_repr=r"\Omega")
|
| 83 |
+
ohm.set_global_dimension(impedance)
|
| 84 |
+
siemens = S = mho = mhos = Quantity("siemens", abbrev='S')
|
| 85 |
+
siemens.set_global_dimension(conductance)
|
| 86 |
+
farad = farads = F = Quantity("farad", abbrev='F')
|
| 87 |
+
farad.set_global_dimension(capacitance)
|
| 88 |
+
henry = henrys = H = Quantity("henry", abbrev='H')
|
| 89 |
+
henry.set_global_dimension(inductance)
|
| 90 |
+
tesla = teslas = T = Quantity("tesla", abbrev='T')
|
| 91 |
+
tesla.set_global_dimension(magnetic_density)
|
| 92 |
+
weber = webers = Wb = wb = Quantity("weber", abbrev='Wb')
|
| 93 |
+
weber.set_global_dimension(magnetic_flux)
|
| 94 |
+
|
| 95 |
+
# CGS units for electromagnetic quantities:
|
| 96 |
+
statampere = Quantity("statampere")
|
| 97 |
+
statcoulomb = statC = franklin = Quantity("statcoulomb", abbrev="statC")
|
| 98 |
+
statvolt = Quantity("statvolt")
|
| 99 |
+
gauss = Quantity("gauss")
|
| 100 |
+
maxwell = Quantity("maxwell")
|
| 101 |
+
debye = Quantity("debye")
|
| 102 |
+
oersted = Quantity("oersted")
|
| 103 |
+
|
| 104 |
+
# Other derived units:
|
| 105 |
+
optical_power = dioptre = diopter = D = Quantity("dioptre")
|
| 106 |
+
lux = lx = Quantity("lux", abbrev="lx")
|
| 107 |
+
|
| 108 |
+
# katal is the SI unit of catalytic activity
|
| 109 |
+
katal = kat = Quantity("katal", abbrev="kat")
|
| 110 |
+
|
| 111 |
+
# gray is the SI unit of absorbed dose
|
| 112 |
+
gray = Gy = Quantity("gray")
|
| 113 |
+
|
| 114 |
+
# becquerel is the SI unit of radioactivity
|
| 115 |
+
becquerel = Bq = Quantity("becquerel", abbrev="Bq")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# Common mass units
|
| 119 |
+
|
| 120 |
+
mg = milligram = milligrams = Quantity("milligram", abbrev="mg")
|
| 121 |
+
mg.set_global_relative_scale_factor(milli, gram)
|
| 122 |
+
|
| 123 |
+
ug = microgram = micrograms = Quantity("microgram", abbrev="ug", latex_repr=r"\mu\text{g}")
|
| 124 |
+
ug.set_global_relative_scale_factor(micro, gram)
|
| 125 |
+
|
| 126 |
+
# Atomic mass constant
|
| 127 |
+
Da = dalton = amu = amus = atomic_mass_unit = atomic_mass_constant = PhysicalConstant("atomic_mass_constant")
|
| 128 |
+
|
| 129 |
+
t = metric_ton = tonne = Quantity("tonne", abbrev="t")
|
| 130 |
+
tonne.set_global_relative_scale_factor(mega, gram)
|
| 131 |
+
|
| 132 |
+
# Electron rest mass
|
| 133 |
+
me = electron_rest_mass = Quantity("electron_rest_mass", abbrev="me")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# Common length units
|
| 137 |
+
|
| 138 |
+
km = kilometer = kilometers = Quantity("kilometer", abbrev="km")
|
| 139 |
+
km.set_global_relative_scale_factor(kilo, meter)
|
| 140 |
+
|
| 141 |
+
dm = decimeter = decimeters = Quantity("decimeter", abbrev="dm")
|
| 142 |
+
dm.set_global_relative_scale_factor(deci, meter)
|
| 143 |
+
|
| 144 |
+
cm = centimeter = centimeters = Quantity("centimeter", abbrev="cm")
|
| 145 |
+
cm.set_global_relative_scale_factor(centi, meter)
|
| 146 |
+
|
| 147 |
+
mm = millimeter = millimeters = Quantity("millimeter", abbrev="mm")
|
| 148 |
+
mm.set_global_relative_scale_factor(milli, meter)
|
| 149 |
+
|
| 150 |
+
um = micrometer = micrometers = micron = microns = \
|
| 151 |
+
Quantity("micrometer", abbrev="um", latex_repr=r'\mu\text{m}')
|
| 152 |
+
um.set_global_relative_scale_factor(micro, meter)
|
| 153 |
+
|
| 154 |
+
nm = nanometer = nanometers = Quantity("nanometer", abbrev="nm")
|
| 155 |
+
nm.set_global_relative_scale_factor(nano, meter)
|
| 156 |
+
|
| 157 |
+
pm = picometer = picometers = Quantity("picometer", abbrev="pm")
|
| 158 |
+
pm.set_global_relative_scale_factor(pico, meter)
|
| 159 |
+
|
| 160 |
+
ft = foot = feet = Quantity("foot", abbrev="ft")
|
| 161 |
+
ft.set_global_relative_scale_factor(Rational(3048, 10000), meter)
|
| 162 |
+
|
| 163 |
+
inch = inches = Quantity("inch")
|
| 164 |
+
inch.set_global_relative_scale_factor(Rational(1, 12), foot)
|
| 165 |
+
|
| 166 |
+
yd = yard = yards = Quantity("yard", abbrev="yd")
|
| 167 |
+
yd.set_global_relative_scale_factor(3, feet)
|
| 168 |
+
|
| 169 |
+
mi = mile = miles = Quantity("mile")
|
| 170 |
+
mi.set_global_relative_scale_factor(5280, feet)
|
| 171 |
+
|
| 172 |
+
nmi = nautical_mile = nautical_miles = Quantity("nautical_mile")
|
| 173 |
+
nmi.set_global_relative_scale_factor(6076, feet)
|
| 174 |
+
|
| 175 |
+
angstrom = angstroms = Quantity("angstrom", latex_repr=r'\r{A}')
|
| 176 |
+
angstrom.set_global_relative_scale_factor(Rational(1, 10**10), meter)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# Common volume and area units
|
| 180 |
+
|
| 181 |
+
ha = hectare = Quantity("hectare", abbrev="ha")
|
| 182 |
+
|
| 183 |
+
l = L = liter = liters = Quantity("liter", abbrev="l")
|
| 184 |
+
|
| 185 |
+
dl = dL = deciliter = deciliters = Quantity("deciliter", abbrev="dl")
|
| 186 |
+
dl.set_global_relative_scale_factor(Rational(1, 10), liter)
|
| 187 |
+
|
| 188 |
+
cl = cL = centiliter = centiliters = Quantity("centiliter", abbrev="cl")
|
| 189 |
+
cl.set_global_relative_scale_factor(Rational(1, 100), liter)
|
| 190 |
+
|
| 191 |
+
ml = mL = milliliter = milliliters = Quantity("milliliter", abbrev="ml")
|
| 192 |
+
ml.set_global_relative_scale_factor(Rational(1, 1000), liter)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# Common time units
|
| 196 |
+
|
| 197 |
+
ms = millisecond = milliseconds = Quantity("millisecond", abbrev="ms")
|
| 198 |
+
millisecond.set_global_relative_scale_factor(milli, second)
|
| 199 |
+
|
| 200 |
+
us = microsecond = microseconds = Quantity("microsecond", abbrev="us", latex_repr=r'\mu\text{s}')
|
| 201 |
+
microsecond.set_global_relative_scale_factor(micro, second)
|
| 202 |
+
|
| 203 |
+
ns = nanosecond = nanoseconds = Quantity("nanosecond", abbrev="ns")
|
| 204 |
+
nanosecond.set_global_relative_scale_factor(nano, second)
|
| 205 |
+
|
| 206 |
+
ps = picosecond = picoseconds = Quantity("picosecond", abbrev="ps")
|
| 207 |
+
picosecond.set_global_relative_scale_factor(pico, second)
|
| 208 |
+
|
| 209 |
+
minute = minutes = Quantity("minute")
|
| 210 |
+
minute.set_global_relative_scale_factor(60, second)
|
| 211 |
+
|
| 212 |
+
h = hour = hours = Quantity("hour")
|
| 213 |
+
hour.set_global_relative_scale_factor(60, minute)
|
| 214 |
+
|
| 215 |
+
day = days = Quantity("day")
|
| 216 |
+
day.set_global_relative_scale_factor(24, hour)
|
| 217 |
+
|
| 218 |
+
anomalistic_year = anomalistic_years = Quantity("anomalistic_year")
|
| 219 |
+
anomalistic_year.set_global_relative_scale_factor(365.259636, day)
|
| 220 |
+
|
| 221 |
+
sidereal_year = sidereal_years = Quantity("sidereal_year")
|
| 222 |
+
sidereal_year.set_global_relative_scale_factor(31558149.540, seconds)
|
| 223 |
+
|
| 224 |
+
tropical_year = tropical_years = Quantity("tropical_year")
|
| 225 |
+
tropical_year.set_global_relative_scale_factor(365.24219, day)
|
| 226 |
+
|
| 227 |
+
common_year = common_years = Quantity("common_year")
|
| 228 |
+
common_year.set_global_relative_scale_factor(365, day)
|
| 229 |
+
|
| 230 |
+
julian_year = julian_years = Quantity("julian_year")
|
| 231 |
+
julian_year.set_global_relative_scale_factor((365 + One/4), day)
|
| 232 |
+
|
| 233 |
+
draconic_year = draconic_years = Quantity("draconic_year")
|
| 234 |
+
draconic_year.set_global_relative_scale_factor(346.62, day)
|
| 235 |
+
|
| 236 |
+
gaussian_year = gaussian_years = Quantity("gaussian_year")
|
| 237 |
+
gaussian_year.set_global_relative_scale_factor(365.2568983, day)
|
| 238 |
+
|
| 239 |
+
full_moon_cycle = full_moon_cycles = Quantity("full_moon_cycle")
|
| 240 |
+
full_moon_cycle.set_global_relative_scale_factor(411.78443029, day)
|
| 241 |
+
|
| 242 |
+
year = years = tropical_year
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
#### CONSTANTS ####
|
| 246 |
+
|
| 247 |
+
# Newton constant
|
| 248 |
+
G = gravitational_constant = PhysicalConstant("gravitational_constant", abbrev="G")
|
| 249 |
+
|
| 250 |
+
# speed of light
|
| 251 |
+
c = speed_of_light = PhysicalConstant("speed_of_light", abbrev="c")
|
| 252 |
+
|
| 253 |
+
# elementary charge
|
| 254 |
+
elementary_charge = PhysicalConstant("elementary_charge", abbrev="e")
|
| 255 |
+
|
| 256 |
+
# Planck constant
|
| 257 |
+
planck = PhysicalConstant("planck", abbrev="h")
|
| 258 |
+
|
| 259 |
+
# Reduced Planck constant
|
| 260 |
+
hbar = PhysicalConstant("hbar", abbrev="hbar")
|
| 261 |
+
|
| 262 |
+
# Electronvolt
|
| 263 |
+
eV = electronvolt = electronvolts = PhysicalConstant("electronvolt", abbrev="eV")
|
| 264 |
+
|
| 265 |
+
# Avogadro number
|
| 266 |
+
avogadro_number = PhysicalConstant("avogadro_number")
|
| 267 |
+
|
| 268 |
+
# Avogadro constant
|
| 269 |
+
avogadro = avogadro_constant = PhysicalConstant("avogadro_constant")
|
| 270 |
+
|
| 271 |
+
# Boltzmann constant
|
| 272 |
+
boltzmann = boltzmann_constant = PhysicalConstant("boltzmann_constant")
|
| 273 |
+
|
| 274 |
+
# Stefan-Boltzmann constant
|
| 275 |
+
stefan = stefan_boltzmann_constant = PhysicalConstant("stefan_boltzmann_constant")
|
| 276 |
+
|
| 277 |
+
# Molar gas constant
|
| 278 |
+
R = molar_gas_constant = PhysicalConstant("molar_gas_constant", abbrev="R")
|
| 279 |
+
|
| 280 |
+
# Faraday constant
|
| 281 |
+
faraday_constant = PhysicalConstant("faraday_constant")
|
| 282 |
+
|
| 283 |
+
# Josephson constant
|
| 284 |
+
josephson_constant = PhysicalConstant("josephson_constant", abbrev="K_j")
|
| 285 |
+
|
| 286 |
+
# Von Klitzing constant
|
| 287 |
+
von_klitzing_constant = PhysicalConstant("von_klitzing_constant", abbrev="R_k")
|
| 288 |
+
|
| 289 |
+
# Acceleration due to gravity (on the Earth surface)
|
| 290 |
+
gee = gees = acceleration_due_to_gravity = PhysicalConstant("acceleration_due_to_gravity", abbrev="g")
|
| 291 |
+
|
| 292 |
+
# magnetic constant:
|
| 293 |
+
u0 = magnetic_constant = vacuum_permeability = PhysicalConstant("magnetic_constant")
|
| 294 |
+
|
| 295 |
+
# electric constat:
|
| 296 |
+
e0 = electric_constant = vacuum_permittivity = PhysicalConstant("vacuum_permittivity")
|
| 297 |
+
|
| 298 |
+
# vacuum impedance:
|
| 299 |
+
Z0 = vacuum_impedance = PhysicalConstant("vacuum_impedance", abbrev='Z_0', latex_repr=r'Z_{0}')
|
| 300 |
+
|
| 301 |
+
# Coulomb's constant:
|
| 302 |
+
coulomb_constant = coulombs_constant = electric_force_constant = \
|
| 303 |
+
PhysicalConstant("coulomb_constant", abbrev="k_e")
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
atmosphere = atmospheres = atm = Quantity("atmosphere", abbrev="atm")
|
| 307 |
+
|
| 308 |
+
kPa = kilopascal = Quantity("kilopascal", abbrev="kPa")
|
| 309 |
+
kilopascal.set_global_relative_scale_factor(kilo, Pa)
|
| 310 |
+
|
| 311 |
+
bar = bars = Quantity("bar", abbrev="bar")
|
| 312 |
+
|
| 313 |
+
pound = pounds = Quantity("pound") # exact
|
| 314 |
+
|
| 315 |
+
psi = Quantity("psi")
|
| 316 |
+
|
| 317 |
+
dHg0 = 13.5951 # approx value at 0 C
|
| 318 |
+
mmHg = torr = Quantity("mmHg")
|
| 319 |
+
|
| 320 |
+
atmosphere.set_global_relative_scale_factor(101325, pascal)
|
| 321 |
+
bar.set_global_relative_scale_factor(100, kPa)
|
| 322 |
+
pound.set_global_relative_scale_factor(Rational(45359237, 100000000), kg)
|
| 323 |
+
|
| 324 |
+
mmu = mmus = milli_mass_unit = Quantity("milli_mass_unit")
|
| 325 |
+
|
| 326 |
+
quart = quarts = Quantity("quart")
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# Other convenient units and magnitudes
|
| 330 |
+
|
| 331 |
+
ly = lightyear = lightyears = Quantity("lightyear", abbrev="ly")
|
| 332 |
+
|
| 333 |
+
au = astronomical_unit = astronomical_units = Quantity("astronomical_unit", abbrev="AU")
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
# Fundamental Planck units:
|
| 337 |
+
planck_mass = Quantity("planck_mass", abbrev="m_P", latex_repr=r'm_\text{P}')
|
| 338 |
+
|
| 339 |
+
planck_time = Quantity("planck_time", abbrev="t_P", latex_repr=r't_\text{P}')
|
| 340 |
+
|
| 341 |
+
planck_temperature = Quantity("planck_temperature", abbrev="T_P",
|
| 342 |
+
latex_repr=r'T_\text{P}')
|
| 343 |
+
|
| 344 |
+
planck_length = Quantity("planck_length", abbrev="l_P", latex_repr=r'l_\text{P}')
|
| 345 |
+
|
| 346 |
+
planck_charge = Quantity("planck_charge", abbrev="q_P", latex_repr=r'q_\text{P}')
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
# Derived Planck units:
|
| 350 |
+
planck_area = Quantity("planck_area")
|
| 351 |
+
|
| 352 |
+
planck_volume = Quantity("planck_volume")
|
| 353 |
+
|
| 354 |
+
planck_momentum = Quantity("planck_momentum")
|
| 355 |
+
|
| 356 |
+
planck_energy = Quantity("planck_energy", abbrev="E_P", latex_repr=r'E_\text{P}')
|
| 357 |
+
|
| 358 |
+
planck_force = Quantity("planck_force", abbrev="F_P", latex_repr=r'F_\text{P}')
|
| 359 |
+
|
| 360 |
+
planck_power = Quantity("planck_power", abbrev="P_P", latex_repr=r'P_\text{P}')
|
| 361 |
+
|
| 362 |
+
planck_density = Quantity("planck_density", abbrev="rho_P", latex_repr=r'\rho_\text{P}')
|
| 363 |
+
|
| 364 |
+
planck_energy_density = Quantity("planck_energy_density", abbrev="rho^E_P")
|
| 365 |
+
|
| 366 |
+
planck_intensity = Quantity("planck_intensity", abbrev="I_P", latex_repr=r'I_\text{P}')
|
| 367 |
+
|
| 368 |
+
planck_angular_frequency = Quantity("planck_angular_frequency", abbrev="omega_P",
|
| 369 |
+
latex_repr=r'\omega_\text{P}')
|
| 370 |
+
|
| 371 |
+
planck_pressure = Quantity("planck_pressure", abbrev="p_P", latex_repr=r'p_\text{P}')
|
| 372 |
+
|
| 373 |
+
planck_current = Quantity("planck_current", abbrev="I_P", latex_repr=r'I_\text{P}')
|
| 374 |
+
|
| 375 |
+
planck_voltage = Quantity("planck_voltage", abbrev="V_P", latex_repr=r'V_\text{P}')
|
| 376 |
+
|
| 377 |
+
planck_impedance = Quantity("planck_impedance", abbrev="Z_P", latex_repr=r'Z_\text{P}')
|
| 378 |
+
|
| 379 |
+
planck_acceleration = Quantity("planck_acceleration", abbrev="a_P",
|
| 380 |
+
latex_repr=r'a_\text{P}')
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
# Information theory units:
|
| 384 |
+
bit = bits = Quantity("bit")
|
| 385 |
+
bit.set_global_dimension(information)
|
| 386 |
+
|
| 387 |
+
byte = bytes = Quantity("byte")
|
| 388 |
+
|
| 389 |
+
kibibyte = kibibytes = Quantity("kibibyte")
|
| 390 |
+
mebibyte = mebibytes = Quantity("mebibyte")
|
| 391 |
+
gibibyte = gibibytes = Quantity("gibibyte")
|
| 392 |
+
tebibyte = tebibytes = Quantity("tebibyte")
|
| 393 |
+
pebibyte = pebibytes = Quantity("pebibyte")
|
| 394 |
+
exbibyte = exbibytes = Quantity("exbibyte")
|
| 395 |
+
|
| 396 |
+
byte.set_global_relative_scale_factor(8, bit)
|
| 397 |
+
kibibyte.set_global_relative_scale_factor(kibi, byte)
|
| 398 |
+
mebibyte.set_global_relative_scale_factor(mebi, byte)
|
| 399 |
+
gibibyte.set_global_relative_scale_factor(gibi, byte)
|
| 400 |
+
tebibyte.set_global_relative_scale_factor(tebi, byte)
|
| 401 |
+
pebibyte.set_global_relative_scale_factor(pebi, byte)
|
| 402 |
+
exbibyte.set_global_relative_scale_factor(exbi, byte)
|
| 403 |
+
|
| 404 |
+
# Older units for radioactivity
|
| 405 |
+
curie = Ci = Quantity("curie", abbrev="Ci")
|
| 406 |
+
|
| 407 |
+
rutherford = Rd = Quantity("rutherford", abbrev="Rd")
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/dimensions.py
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Definition of physical dimensions.
|
| 3 |
+
|
| 4 |
+
Unit systems will be constructed on top of these dimensions.
|
| 5 |
+
|
| 6 |
+
Most of the examples in the doc use MKS system and are presented from the
|
| 7 |
+
computer point of view: from a human point, adding length to time is not legal
|
| 8 |
+
in MKS but it is in natural system; for a computer in natural system there is
|
| 9 |
+
no time dimension (but a velocity dimension instead) - in the basis - so the
|
| 10 |
+
question of adding time to length has no meaning.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import collections
|
| 16 |
+
from functools import reduce
|
| 17 |
+
|
| 18 |
+
from sympy.core.basic import Basic
|
| 19 |
+
from sympy.core.containers import (Dict, Tuple)
|
| 20 |
+
from sympy.core.singleton import S
|
| 21 |
+
from sympy.core.sorting import default_sort_key
|
| 22 |
+
from sympy.core.symbol import Symbol
|
| 23 |
+
from sympy.core.sympify import sympify
|
| 24 |
+
from sympy.matrices.dense import Matrix
|
| 25 |
+
from sympy.functions.elementary.trigonometric import TrigonometricFunction
|
| 26 |
+
from sympy.core.expr import Expr
|
| 27 |
+
from sympy.core.power import Pow
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class _QuantityMapper:
|
| 31 |
+
|
| 32 |
+
_quantity_scale_factors_global: dict[Expr, Expr] = {}
|
| 33 |
+
_quantity_dimensional_equivalence_map_global: dict[Expr, Expr] = {}
|
| 34 |
+
_quantity_dimension_global: dict[Expr, Expr] = {}
|
| 35 |
+
|
| 36 |
+
def __init__(self, *args, **kwargs):
|
| 37 |
+
self._quantity_dimension_map = {}
|
| 38 |
+
self._quantity_scale_factors = {}
|
| 39 |
+
|
| 40 |
+
def set_quantity_dimension(self, quantity, dimension):
|
| 41 |
+
"""
|
| 42 |
+
Set the dimension for the quantity in a unit system.
|
| 43 |
+
|
| 44 |
+
If this relation is valid in every unit system, use
|
| 45 |
+
``quantity.set_global_dimension(dimension)`` instead.
|
| 46 |
+
"""
|
| 47 |
+
from sympy.physics.units import Quantity
|
| 48 |
+
dimension = sympify(dimension)
|
| 49 |
+
if not isinstance(dimension, Dimension):
|
| 50 |
+
if dimension == 1:
|
| 51 |
+
dimension = Dimension(1)
|
| 52 |
+
else:
|
| 53 |
+
raise ValueError("expected dimension or 1")
|
| 54 |
+
elif isinstance(dimension, Quantity):
|
| 55 |
+
dimension = self.get_quantity_dimension(dimension)
|
| 56 |
+
self._quantity_dimension_map[quantity] = dimension
|
| 57 |
+
|
| 58 |
+
def set_quantity_scale_factor(self, quantity, scale_factor):
|
| 59 |
+
"""
|
| 60 |
+
Set the scale factor of a quantity relative to another quantity.
|
| 61 |
+
|
| 62 |
+
It should be used only once per quantity to just one other quantity,
|
| 63 |
+
the algorithm will then be able to compute the scale factors to all
|
| 64 |
+
other quantities.
|
| 65 |
+
|
| 66 |
+
In case the scale factor is valid in every unit system, please use
|
| 67 |
+
``quantity.set_global_relative_scale_factor(scale_factor)`` instead.
|
| 68 |
+
"""
|
| 69 |
+
from sympy.physics.units import Quantity
|
| 70 |
+
from sympy.physics.units.prefixes import Prefix
|
| 71 |
+
scale_factor = sympify(scale_factor)
|
| 72 |
+
# replace all prefixes by their ratio to canonical units:
|
| 73 |
+
scale_factor = scale_factor.replace(
|
| 74 |
+
lambda x: isinstance(x, Prefix),
|
| 75 |
+
lambda x: x.scale_factor
|
| 76 |
+
)
|
| 77 |
+
# replace all quantities by their ratio to canonical units:
|
| 78 |
+
scale_factor = scale_factor.replace(
|
| 79 |
+
lambda x: isinstance(x, Quantity),
|
| 80 |
+
lambda x: self.get_quantity_scale_factor(x)
|
| 81 |
+
)
|
| 82 |
+
self._quantity_scale_factors[quantity] = scale_factor
|
| 83 |
+
|
| 84 |
+
def get_quantity_dimension(self, unit):
|
| 85 |
+
from sympy.physics.units import Quantity
|
| 86 |
+
# First look-up the local dimension map, then the global one:
|
| 87 |
+
if unit in self._quantity_dimension_map:
|
| 88 |
+
return self._quantity_dimension_map[unit]
|
| 89 |
+
if unit in self._quantity_dimension_global:
|
| 90 |
+
return self._quantity_dimension_global[unit]
|
| 91 |
+
if unit in self._quantity_dimensional_equivalence_map_global:
|
| 92 |
+
dep_unit = self._quantity_dimensional_equivalence_map_global[unit]
|
| 93 |
+
if isinstance(dep_unit, Quantity):
|
| 94 |
+
return self.get_quantity_dimension(dep_unit)
|
| 95 |
+
else:
|
| 96 |
+
return Dimension(self.get_dimensional_expr(dep_unit))
|
| 97 |
+
if isinstance(unit, Quantity):
|
| 98 |
+
return Dimension(unit.name)
|
| 99 |
+
else:
|
| 100 |
+
return Dimension(1)
|
| 101 |
+
|
| 102 |
+
def get_quantity_scale_factor(self, unit):
|
| 103 |
+
if unit in self._quantity_scale_factors:
|
| 104 |
+
return self._quantity_scale_factors[unit]
|
| 105 |
+
if unit in self._quantity_scale_factors_global:
|
| 106 |
+
mul_factor, other_unit = self._quantity_scale_factors_global[unit]
|
| 107 |
+
return mul_factor*self.get_quantity_scale_factor(other_unit)
|
| 108 |
+
return S.One
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class Dimension(Expr):
|
| 112 |
+
"""
|
| 113 |
+
This class represent the dimension of a physical quantities.
|
| 114 |
+
|
| 115 |
+
The ``Dimension`` constructor takes as parameters a name and an optional
|
| 116 |
+
symbol.
|
| 117 |
+
|
| 118 |
+
For example, in classical mechanics we know that time is different from
|
| 119 |
+
temperature and dimensions make this difference (but they do not provide
|
| 120 |
+
any measure of these quantites.
|
| 121 |
+
|
| 122 |
+
>>> from sympy.physics.units import Dimension
|
| 123 |
+
>>> length = Dimension('length')
|
| 124 |
+
>>> length
|
| 125 |
+
Dimension(length)
|
| 126 |
+
>>> time = Dimension('time')
|
| 127 |
+
>>> time
|
| 128 |
+
Dimension(time)
|
| 129 |
+
|
| 130 |
+
Dimensions can be composed using multiplication, division and
|
| 131 |
+
exponentiation (by a number) to give new dimensions. Addition and
|
| 132 |
+
subtraction is defined only when the two objects are the same dimension.
|
| 133 |
+
|
| 134 |
+
>>> velocity = length / time
|
| 135 |
+
>>> velocity
|
| 136 |
+
Dimension(length/time)
|
| 137 |
+
|
| 138 |
+
It is possible to use a dimension system object to get the dimensionsal
|
| 139 |
+
dependencies of a dimension, for example the dimension system used by the
|
| 140 |
+
SI units convention can be used:
|
| 141 |
+
|
| 142 |
+
>>> from sympy.physics.units.systems.si import dimsys_SI
|
| 143 |
+
>>> dimsys_SI.get_dimensional_dependencies(velocity)
|
| 144 |
+
{Dimension(length, L): 1, Dimension(time, T): -1}
|
| 145 |
+
>>> length + length
|
| 146 |
+
Dimension(length)
|
| 147 |
+
>>> l2 = length**2
|
| 148 |
+
>>> l2
|
| 149 |
+
Dimension(length**2)
|
| 150 |
+
>>> dimsys_SI.get_dimensional_dependencies(l2)
|
| 151 |
+
{Dimension(length, L): 2}
|
| 152 |
+
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
_op_priority = 13.0
|
| 156 |
+
|
| 157 |
+
# XXX: This doesn't seem to be used anywhere...
|
| 158 |
+
_dimensional_dependencies = {} # type: ignore
|
| 159 |
+
|
| 160 |
+
is_commutative = True
|
| 161 |
+
is_number = False
|
| 162 |
+
# make sqrt(M**2) --> M
|
| 163 |
+
is_positive = True
|
| 164 |
+
is_real = True
|
| 165 |
+
|
| 166 |
+
def __new__(cls, name, symbol=None):
|
| 167 |
+
|
| 168 |
+
if isinstance(name, str):
|
| 169 |
+
name = Symbol(name)
|
| 170 |
+
else:
|
| 171 |
+
name = sympify(name)
|
| 172 |
+
|
| 173 |
+
if not isinstance(name, Expr):
|
| 174 |
+
raise TypeError("Dimension name needs to be a valid math expression")
|
| 175 |
+
|
| 176 |
+
if isinstance(symbol, str):
|
| 177 |
+
symbol = Symbol(symbol)
|
| 178 |
+
elif symbol is not None:
|
| 179 |
+
assert isinstance(symbol, Symbol)
|
| 180 |
+
|
| 181 |
+
obj = Expr.__new__(cls, name)
|
| 182 |
+
|
| 183 |
+
obj._name = name
|
| 184 |
+
obj._symbol = symbol
|
| 185 |
+
return obj
|
| 186 |
+
|
| 187 |
+
@property
|
| 188 |
+
def name(self):
|
| 189 |
+
return self._name
|
| 190 |
+
|
| 191 |
+
@property
|
| 192 |
+
def symbol(self):
|
| 193 |
+
return self._symbol
|
| 194 |
+
|
| 195 |
+
def __str__(self):
|
| 196 |
+
"""
|
| 197 |
+
Display the string representation of the dimension.
|
| 198 |
+
"""
|
| 199 |
+
if self.symbol is None:
|
| 200 |
+
return "Dimension(%s)" % (self.name)
|
| 201 |
+
else:
|
| 202 |
+
return "Dimension(%s, %s)" % (self.name, self.symbol)
|
| 203 |
+
|
| 204 |
+
def __repr__(self):
|
| 205 |
+
return self.__str__()
|
| 206 |
+
|
| 207 |
+
def __neg__(self):
|
| 208 |
+
return self
|
| 209 |
+
|
| 210 |
+
def __add__(self, other):
|
| 211 |
+
from sympy.physics.units.quantities import Quantity
|
| 212 |
+
other = sympify(other)
|
| 213 |
+
if isinstance(other, Basic):
|
| 214 |
+
if other.has(Quantity):
|
| 215 |
+
raise TypeError("cannot sum dimension and quantity")
|
| 216 |
+
if isinstance(other, Dimension) and self == other:
|
| 217 |
+
return self
|
| 218 |
+
return super().__add__(other)
|
| 219 |
+
return self
|
| 220 |
+
|
| 221 |
+
def __radd__(self, other):
|
| 222 |
+
return self.__add__(other)
|
| 223 |
+
|
| 224 |
+
def __sub__(self, other):
|
| 225 |
+
# there is no notion of ordering (or magnitude) among dimension,
|
| 226 |
+
# subtraction is equivalent to addition when the operation is legal
|
| 227 |
+
return self + other
|
| 228 |
+
|
| 229 |
+
def __rsub__(self, other):
|
| 230 |
+
# there is no notion of ordering (or magnitude) among dimension,
|
| 231 |
+
# subtraction is equivalent to addition when the operation is legal
|
| 232 |
+
return self + other
|
| 233 |
+
|
| 234 |
+
def __pow__(self, other):
|
| 235 |
+
return self._eval_power(other)
|
| 236 |
+
|
| 237 |
+
def _eval_power(self, other):
|
| 238 |
+
other = sympify(other)
|
| 239 |
+
return Dimension(self.name**other)
|
| 240 |
+
|
| 241 |
+
def __mul__(self, other):
|
| 242 |
+
from sympy.physics.units.quantities import Quantity
|
| 243 |
+
if isinstance(other, Basic):
|
| 244 |
+
if other.has(Quantity):
|
| 245 |
+
raise TypeError("cannot sum dimension and quantity")
|
| 246 |
+
if isinstance(other, Dimension):
|
| 247 |
+
return Dimension(self.name*other.name)
|
| 248 |
+
if not other.free_symbols: # other.is_number cannot be used
|
| 249 |
+
return self
|
| 250 |
+
return super().__mul__(other)
|
| 251 |
+
return self
|
| 252 |
+
|
| 253 |
+
def __rmul__(self, other):
|
| 254 |
+
return self.__mul__(other)
|
| 255 |
+
|
| 256 |
+
def __truediv__(self, other):
|
| 257 |
+
return self*Pow(other, -1)
|
| 258 |
+
|
| 259 |
+
def __rtruediv__(self, other):
|
| 260 |
+
return other * pow(self, -1)
|
| 261 |
+
|
| 262 |
+
@classmethod
|
| 263 |
+
def _from_dimensional_dependencies(cls, dependencies):
|
| 264 |
+
return reduce(lambda x, y: x * y, (
|
| 265 |
+
d**e for d, e in dependencies.items()
|
| 266 |
+
), 1)
|
| 267 |
+
|
| 268 |
+
def has_integer_powers(self, dim_sys):
|
| 269 |
+
"""
|
| 270 |
+
Check if the dimension object has only integer powers.
|
| 271 |
+
|
| 272 |
+
All the dimension powers should be integers, but rational powers may
|
| 273 |
+
appear in intermediate steps. This method may be used to check that the
|
| 274 |
+
final result is well-defined.
|
| 275 |
+
"""
|
| 276 |
+
|
| 277 |
+
return all(dpow.is_Integer for dpow in dim_sys.get_dimensional_dependencies(self).values())
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# Create dimensions according to the base units in MKSA.
|
| 281 |
+
# For other unit systems, they can be derived by transforming the base
|
| 282 |
+
# dimensional dependency dictionary.
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class DimensionSystem(Basic, _QuantityMapper):
|
| 286 |
+
r"""
|
| 287 |
+
DimensionSystem represents a coherent set of dimensions.
|
| 288 |
+
|
| 289 |
+
The constructor takes three parameters:
|
| 290 |
+
|
| 291 |
+
- base dimensions;
|
| 292 |
+
- derived dimensions: these are defined in terms of the base dimensions
|
| 293 |
+
(for example velocity is defined from the division of length by time);
|
| 294 |
+
- dependency of dimensions: how the derived dimensions depend
|
| 295 |
+
on the base dimensions.
|
| 296 |
+
|
| 297 |
+
Optionally either the ``derived_dims`` or the ``dimensional_dependencies``
|
| 298 |
+
may be omitted.
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
def __new__(cls, base_dims, derived_dims=(), dimensional_dependencies={}):
|
| 302 |
+
dimensional_dependencies = dict(dimensional_dependencies)
|
| 303 |
+
|
| 304 |
+
def parse_dim(dim):
|
| 305 |
+
if isinstance(dim, str):
|
| 306 |
+
dim = Dimension(Symbol(dim))
|
| 307 |
+
elif isinstance(dim, Dimension):
|
| 308 |
+
pass
|
| 309 |
+
elif isinstance(dim, Symbol):
|
| 310 |
+
dim = Dimension(dim)
|
| 311 |
+
else:
|
| 312 |
+
raise TypeError("%s wrong type" % dim)
|
| 313 |
+
return dim
|
| 314 |
+
|
| 315 |
+
base_dims = [parse_dim(i) for i in base_dims]
|
| 316 |
+
derived_dims = [parse_dim(i) for i in derived_dims]
|
| 317 |
+
|
| 318 |
+
for dim in base_dims:
|
| 319 |
+
if (dim in dimensional_dependencies
|
| 320 |
+
and (len(dimensional_dependencies[dim]) != 1 or
|
| 321 |
+
dimensional_dependencies[dim].get(dim, None) != 1)):
|
| 322 |
+
raise IndexError("Repeated value in base dimensions")
|
| 323 |
+
dimensional_dependencies[dim] = Dict({dim: 1})
|
| 324 |
+
|
| 325 |
+
def parse_dim_name(dim):
|
| 326 |
+
if isinstance(dim, Dimension):
|
| 327 |
+
return dim
|
| 328 |
+
elif isinstance(dim, str):
|
| 329 |
+
return Dimension(Symbol(dim))
|
| 330 |
+
elif isinstance(dim, Symbol):
|
| 331 |
+
return Dimension(dim)
|
| 332 |
+
else:
|
| 333 |
+
raise TypeError("unrecognized type %s for %s" % (type(dim), dim))
|
| 334 |
+
|
| 335 |
+
for dim in dimensional_dependencies.keys():
|
| 336 |
+
dim = parse_dim(dim)
|
| 337 |
+
if (dim not in derived_dims) and (dim not in base_dims):
|
| 338 |
+
derived_dims.append(dim)
|
| 339 |
+
|
| 340 |
+
def parse_dict(d):
|
| 341 |
+
return Dict({parse_dim_name(i): j for i, j in d.items()})
|
| 342 |
+
|
| 343 |
+
# Make sure everything is a SymPy type:
|
| 344 |
+
dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in
|
| 345 |
+
dimensional_dependencies.items()}
|
| 346 |
+
|
| 347 |
+
for dim in derived_dims:
|
| 348 |
+
if dim in base_dims:
|
| 349 |
+
raise ValueError("Dimension %s both in base and derived" % dim)
|
| 350 |
+
if dim not in dimensional_dependencies:
|
| 351 |
+
# TODO: should this raise a warning?
|
| 352 |
+
dimensional_dependencies[dim] = Dict({dim: 1})
|
| 353 |
+
|
| 354 |
+
base_dims.sort(key=default_sort_key)
|
| 355 |
+
derived_dims.sort(key=default_sort_key)
|
| 356 |
+
|
| 357 |
+
base_dims = Tuple(*base_dims)
|
| 358 |
+
derived_dims = Tuple(*derived_dims)
|
| 359 |
+
dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()})
|
| 360 |
+
obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies)
|
| 361 |
+
return obj
|
| 362 |
+
|
| 363 |
+
@property
|
| 364 |
+
def base_dims(self):
|
| 365 |
+
return self.args[0]
|
| 366 |
+
|
| 367 |
+
@property
|
| 368 |
+
def derived_dims(self):
|
| 369 |
+
return self.args[1]
|
| 370 |
+
|
| 371 |
+
@property
|
| 372 |
+
def dimensional_dependencies(self):
|
| 373 |
+
return self.args[2]
|
| 374 |
+
|
| 375 |
+
def _get_dimensional_dependencies_for_name(self, dimension):
|
| 376 |
+
if isinstance(dimension, str):
|
| 377 |
+
dimension = Dimension(Symbol(dimension))
|
| 378 |
+
elif not isinstance(dimension, Dimension):
|
| 379 |
+
dimension = Dimension(dimension)
|
| 380 |
+
|
| 381 |
+
if dimension.name.is_Symbol:
|
| 382 |
+
# Dimensions not included in the dependencies are considered
|
| 383 |
+
# as base dimensions:
|
| 384 |
+
return dict(self.dimensional_dependencies.get(dimension, {dimension: 1}))
|
| 385 |
+
|
| 386 |
+
if dimension.name.is_number or dimension.name.is_NumberSymbol:
|
| 387 |
+
return {}
|
| 388 |
+
|
| 389 |
+
get_for_name = self._get_dimensional_dependencies_for_name
|
| 390 |
+
|
| 391 |
+
if dimension.name.is_Mul:
|
| 392 |
+
ret = collections.defaultdict(int)
|
| 393 |
+
dicts = [get_for_name(i) for i in dimension.name.args]
|
| 394 |
+
for d in dicts:
|
| 395 |
+
for k, v in d.items():
|
| 396 |
+
ret[k] += v
|
| 397 |
+
return {k: v for (k, v) in ret.items() if v != 0}
|
| 398 |
+
|
| 399 |
+
if dimension.name.is_Add:
|
| 400 |
+
dicts = [get_for_name(i) for i in dimension.name.args]
|
| 401 |
+
if all(d == dicts[0] for d in dicts[1:]):
|
| 402 |
+
return dicts[0]
|
| 403 |
+
raise TypeError("Only equivalent dimensions can be added or subtracted.")
|
| 404 |
+
|
| 405 |
+
if dimension.name.is_Pow:
|
| 406 |
+
dim_base = get_for_name(dimension.name.base)
|
| 407 |
+
dim_exp = get_for_name(dimension.name.exp)
|
| 408 |
+
if dim_exp == {} or dimension.name.exp.is_Symbol:
|
| 409 |
+
return {k: v * dimension.name.exp for (k, v) in dim_base.items()}
|
| 410 |
+
else:
|
| 411 |
+
raise TypeError("The exponent for the power operator must be a Symbol or dimensionless.")
|
| 412 |
+
|
| 413 |
+
if dimension.name.is_Function:
|
| 414 |
+
args = (Dimension._from_dimensional_dependencies(
|
| 415 |
+
get_for_name(arg)) for arg in dimension.name.args)
|
| 416 |
+
result = dimension.name.func(*args)
|
| 417 |
+
|
| 418 |
+
dicts = [get_for_name(i) for i in dimension.name.args]
|
| 419 |
+
|
| 420 |
+
if isinstance(result, Dimension):
|
| 421 |
+
return self.get_dimensional_dependencies(result)
|
| 422 |
+
elif result.func == dimension.name.func:
|
| 423 |
+
if isinstance(dimension.name, TrigonometricFunction):
|
| 424 |
+
if dicts[0] in ({}, {Dimension('angle'): 1}):
|
| 425 |
+
return {}
|
| 426 |
+
else:
|
| 427 |
+
raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(dimension.func))
|
| 428 |
+
else:
|
| 429 |
+
if all(item == {} for item in dicts):
|
| 430 |
+
return {}
|
| 431 |
+
else:
|
| 432 |
+
raise TypeError("The input arguments for the function {} must be dimensionless.".format(dimension.func))
|
| 433 |
+
else:
|
| 434 |
+
return get_for_name(result)
|
| 435 |
+
|
| 436 |
+
raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(dimension.name)))
|
| 437 |
+
|
| 438 |
+
def get_dimensional_dependencies(self, name, mark_dimensionless=False):
|
| 439 |
+
dimdep = self._get_dimensional_dependencies_for_name(name)
|
| 440 |
+
if mark_dimensionless and dimdep == {}:
|
| 441 |
+
return {Dimension(1): 1}
|
| 442 |
+
return dict(dimdep.items())
|
| 443 |
+
|
| 444 |
+
def equivalent_dims(self, dim1, dim2):
|
| 445 |
+
deps1 = self.get_dimensional_dependencies(dim1)
|
| 446 |
+
deps2 = self.get_dimensional_dependencies(dim2)
|
| 447 |
+
return deps1 == deps2
|
| 448 |
+
|
| 449 |
+
def extend(self, new_base_dims, new_derived_dims=(), new_dim_deps=None):
|
| 450 |
+
deps = dict(self.dimensional_dependencies)
|
| 451 |
+
if new_dim_deps:
|
| 452 |
+
deps.update(new_dim_deps)
|
| 453 |
+
|
| 454 |
+
new_dim_sys = DimensionSystem(
|
| 455 |
+
tuple(self.base_dims) + tuple(new_base_dims),
|
| 456 |
+
tuple(self.derived_dims) + tuple(new_derived_dims),
|
| 457 |
+
deps
|
| 458 |
+
)
|
| 459 |
+
new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map)
|
| 460 |
+
new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors)
|
| 461 |
+
return new_dim_sys
|
| 462 |
+
|
| 463 |
+
def is_dimensionless(self, dimension):
|
| 464 |
+
"""
|
| 465 |
+
Check if the dimension object really has a dimension.
|
| 466 |
+
|
| 467 |
+
A dimension should have at least one component with non-zero power.
|
| 468 |
+
"""
|
| 469 |
+
if dimension.name == 1:
|
| 470 |
+
return True
|
| 471 |
+
return self.get_dimensional_dependencies(dimension) == {}
|
| 472 |
+
|
| 473 |
+
@property
|
| 474 |
+
def list_can_dims(self):
|
| 475 |
+
"""
|
| 476 |
+
Useless method, kept for compatibility with previous versions.
|
| 477 |
+
|
| 478 |
+
DO NOT USE.
|
| 479 |
+
|
| 480 |
+
List all canonical dimension names.
|
| 481 |
+
"""
|
| 482 |
+
dimset = set()
|
| 483 |
+
for i in self.base_dims:
|
| 484 |
+
dimset.update(set(self.get_dimensional_dependencies(i).keys()))
|
| 485 |
+
return tuple(sorted(dimset, key=str))
|
| 486 |
+
|
| 487 |
+
@property
|
| 488 |
+
def inv_can_transf_matrix(self):
|
| 489 |
+
"""
|
| 490 |
+
Useless method, kept for compatibility with previous versions.
|
| 491 |
+
|
| 492 |
+
DO NOT USE.
|
| 493 |
+
|
| 494 |
+
Compute the inverse transformation matrix from the base to the
|
| 495 |
+
canonical dimension basis.
|
| 496 |
+
|
| 497 |
+
It corresponds to the matrix where columns are the vector of base
|
| 498 |
+
dimensions in canonical basis.
|
| 499 |
+
|
| 500 |
+
This matrix will almost never be used because dimensions are always
|
| 501 |
+
defined with respect to the canonical basis, so no work has to be done
|
| 502 |
+
to get them in this basis. Nonetheless if this matrix is not square
|
| 503 |
+
(or not invertible) it means that we have chosen a bad basis.
|
| 504 |
+
"""
|
| 505 |
+
matrix = reduce(lambda x, y: x.row_join(y),
|
| 506 |
+
[self.dim_can_vector(d) for d in self.base_dims])
|
| 507 |
+
return matrix
|
| 508 |
+
|
| 509 |
+
@property
|
| 510 |
+
def can_transf_matrix(self):
|
| 511 |
+
"""
|
| 512 |
+
Useless method, kept for compatibility with previous versions.
|
| 513 |
+
|
| 514 |
+
DO NOT USE.
|
| 515 |
+
|
| 516 |
+
Return the canonical transformation matrix from the canonical to the
|
| 517 |
+
base dimension basis.
|
| 518 |
+
|
| 519 |
+
It is the inverse of the matrix computed with inv_can_transf_matrix().
|
| 520 |
+
"""
|
| 521 |
+
|
| 522 |
+
#TODO: the inversion will fail if the system is inconsistent, for
|
| 523 |
+
# example if the matrix is not a square
|
| 524 |
+
return reduce(lambda x, y: x.row_join(y),
|
| 525 |
+
[self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)]
|
| 526 |
+
).inv()
|
| 527 |
+
|
| 528 |
+
def dim_can_vector(self, dim):
|
| 529 |
+
"""
|
| 530 |
+
Useless method, kept for compatibility with previous versions.
|
| 531 |
+
|
| 532 |
+
DO NOT USE.
|
| 533 |
+
|
| 534 |
+
Dimensional representation in terms of the canonical base dimensions.
|
| 535 |
+
"""
|
| 536 |
+
|
| 537 |
+
vec = []
|
| 538 |
+
for d in self.list_can_dims:
|
| 539 |
+
vec.append(self.get_dimensional_dependencies(dim).get(d, 0))
|
| 540 |
+
return Matrix(vec)
|
| 541 |
+
|
| 542 |
+
def dim_vector(self, dim):
|
| 543 |
+
"""
|
| 544 |
+
Useless method, kept for compatibility with previous versions.
|
| 545 |
+
|
| 546 |
+
DO NOT USE.
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
Vector representation in terms of the base dimensions.
|
| 550 |
+
"""
|
| 551 |
+
return self.can_transf_matrix * Matrix(self.dim_can_vector(dim))
|
| 552 |
+
|
| 553 |
+
def print_dim_base(self, dim):
|
| 554 |
+
"""
|
| 555 |
+
Give the string expression of a dimension in term of the basis symbols.
|
| 556 |
+
"""
|
| 557 |
+
dims = self.dim_vector(dim)
|
| 558 |
+
symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims]
|
| 559 |
+
res = S.One
|
| 560 |
+
for (s, p) in zip(symbols, dims):
|
| 561 |
+
res *= s**p
|
| 562 |
+
return res
|
| 563 |
+
|
| 564 |
+
@property
|
| 565 |
+
def dim(self):
|
| 566 |
+
"""
|
| 567 |
+
Useless method, kept for compatibility with previous versions.
|
| 568 |
+
|
| 569 |
+
DO NOT USE.
|
| 570 |
+
|
| 571 |
+
Give the dimension of the system.
|
| 572 |
+
|
| 573 |
+
That is return the number of dimensions forming the basis.
|
| 574 |
+
"""
|
| 575 |
+
return len(self.base_dims)
|
| 576 |
+
|
| 577 |
+
@property
|
| 578 |
+
def is_consistent(self):
|
| 579 |
+
"""
|
| 580 |
+
Useless method, kept for compatibility with previous versions.
|
| 581 |
+
|
| 582 |
+
DO NOT USE.
|
| 583 |
+
|
| 584 |
+
Check if the system is well defined.
|
| 585 |
+
"""
|
| 586 |
+
|
| 587 |
+
# not enough or too many base dimensions compared to independent
|
| 588 |
+
# dimensions
|
| 589 |
+
# in vector language: the set of vectors do not form a basis
|
| 590 |
+
return self.inv_can_transf_matrix.is_square
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/prefixes.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module defining unit prefixe class and some constants.
|
| 3 |
+
|
| 4 |
+
Constant dict for SI and binary prefixes are defined as PREFIXES and
|
| 5 |
+
BIN_PREFIXES.
|
| 6 |
+
"""
|
| 7 |
+
from sympy.core.expr import Expr
|
| 8 |
+
from sympy.core.sympify import sympify
|
| 9 |
+
from sympy.core.singleton import S
|
| 10 |
+
|
| 11 |
+
class Prefix(Expr):
|
| 12 |
+
"""
|
| 13 |
+
This class represent prefixes, with their name, symbol and factor.
|
| 14 |
+
|
| 15 |
+
Prefixes are used to create derived units from a given unit. They should
|
| 16 |
+
always be encapsulated into units.
|
| 17 |
+
|
| 18 |
+
The factor is constructed from a base (default is 10) to some power, and
|
| 19 |
+
it gives the total multiple or fraction. For example the kilometer km
|
| 20 |
+
is constructed from the meter (factor 1) and the kilo (10 to the power 3,
|
| 21 |
+
i.e. 1000). The base can be changed to allow e.g. binary prefixes.
|
| 22 |
+
|
| 23 |
+
A prefix multiplied by something will always return the product of this
|
| 24 |
+
other object times the factor, except if the other object:
|
| 25 |
+
|
| 26 |
+
- is a prefix and they can be combined into a new prefix;
|
| 27 |
+
- defines multiplication with prefixes (which is the case for the Unit
|
| 28 |
+
class).
|
| 29 |
+
"""
|
| 30 |
+
_op_priority = 13.0
|
| 31 |
+
is_commutative = True
|
| 32 |
+
|
| 33 |
+
def __new__(cls, name, abbrev, exponent, base=sympify(10), latex_repr=None):
|
| 34 |
+
|
| 35 |
+
name = sympify(name)
|
| 36 |
+
abbrev = sympify(abbrev)
|
| 37 |
+
exponent = sympify(exponent)
|
| 38 |
+
base = sympify(base)
|
| 39 |
+
|
| 40 |
+
obj = Expr.__new__(cls, name, abbrev, exponent, base)
|
| 41 |
+
obj._name = name
|
| 42 |
+
obj._abbrev = abbrev
|
| 43 |
+
obj._scale_factor = base**exponent
|
| 44 |
+
obj._exponent = exponent
|
| 45 |
+
obj._base = base
|
| 46 |
+
obj._latex_repr = latex_repr
|
| 47 |
+
return obj
|
| 48 |
+
|
| 49 |
+
@property
|
| 50 |
+
def name(self):
|
| 51 |
+
return self._name
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
def abbrev(self):
|
| 55 |
+
return self._abbrev
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def scale_factor(self):
|
| 59 |
+
return self._scale_factor
|
| 60 |
+
|
| 61 |
+
def _latex(self, printer):
|
| 62 |
+
if self._latex_repr is None:
|
| 63 |
+
return r'\text{%s}' % self._abbrev
|
| 64 |
+
return self._latex_repr
|
| 65 |
+
|
| 66 |
+
@property
|
| 67 |
+
def base(self):
|
| 68 |
+
return self._base
|
| 69 |
+
|
| 70 |
+
def __str__(self):
|
| 71 |
+
return str(self._abbrev)
|
| 72 |
+
|
| 73 |
+
def __repr__(self):
|
| 74 |
+
if self.base == 10:
|
| 75 |
+
return "Prefix(%r, %r, %r)" % (
|
| 76 |
+
str(self.name), str(self.abbrev), self._exponent)
|
| 77 |
+
else:
|
| 78 |
+
return "Prefix(%r, %r, %r, %r)" % (
|
| 79 |
+
str(self.name), str(self.abbrev), self._exponent, self.base)
|
| 80 |
+
|
| 81 |
+
def __mul__(self, other):
|
| 82 |
+
from sympy.physics.units import Quantity
|
| 83 |
+
if not isinstance(other, (Quantity, Prefix)):
|
| 84 |
+
return super().__mul__(other)
|
| 85 |
+
|
| 86 |
+
fact = self.scale_factor * other.scale_factor
|
| 87 |
+
|
| 88 |
+
if isinstance(other, Prefix):
|
| 89 |
+
if fact == 1:
|
| 90 |
+
return S.One
|
| 91 |
+
# simplify prefix
|
| 92 |
+
for p in PREFIXES:
|
| 93 |
+
if PREFIXES[p].scale_factor == fact:
|
| 94 |
+
return PREFIXES[p]
|
| 95 |
+
return fact
|
| 96 |
+
|
| 97 |
+
return self.scale_factor * other
|
| 98 |
+
|
| 99 |
+
def __truediv__(self, other):
|
| 100 |
+
if not hasattr(other, "scale_factor"):
|
| 101 |
+
return super().__truediv__(other)
|
| 102 |
+
|
| 103 |
+
fact = self.scale_factor / other.scale_factor
|
| 104 |
+
|
| 105 |
+
if fact == 1:
|
| 106 |
+
return S.One
|
| 107 |
+
elif isinstance(other, Prefix):
|
| 108 |
+
for p in PREFIXES:
|
| 109 |
+
if PREFIXES[p].scale_factor == fact:
|
| 110 |
+
return PREFIXES[p]
|
| 111 |
+
return fact
|
| 112 |
+
|
| 113 |
+
return self.scale_factor / other
|
| 114 |
+
|
| 115 |
+
def __rtruediv__(self, other):
|
| 116 |
+
if other == 1:
|
| 117 |
+
for p in PREFIXES:
|
| 118 |
+
if PREFIXES[p].scale_factor == 1 / self.scale_factor:
|
| 119 |
+
return PREFIXES[p]
|
| 120 |
+
return other / self.scale_factor
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def prefix_unit(unit, prefixes):
|
| 124 |
+
"""
|
| 125 |
+
Return a list of all units formed by unit and the given prefixes.
|
| 126 |
+
|
| 127 |
+
You can use the predefined PREFIXES or BIN_PREFIXES, but you can also
|
| 128 |
+
pass as argument a subdict of them if you do not want all prefixed units.
|
| 129 |
+
|
| 130 |
+
>>> from sympy.physics.units.prefixes import (PREFIXES,
|
| 131 |
+
... prefix_unit)
|
| 132 |
+
>>> from sympy.physics.units import m
|
| 133 |
+
>>> pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]}
|
| 134 |
+
>>> prefix_unit(m, pref) # doctest: +SKIP
|
| 135 |
+
[millimeter, centimeter, decimeter]
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
from sympy.physics.units.quantities import Quantity
|
| 139 |
+
from sympy.physics.units import UnitSystem
|
| 140 |
+
|
| 141 |
+
prefixed_units = []
|
| 142 |
+
|
| 143 |
+
for prefix in prefixes.values():
|
| 144 |
+
quantity = Quantity(
|
| 145 |
+
"%s%s" % (prefix.name, unit.name),
|
| 146 |
+
abbrev=("%s%s" % (prefix.abbrev, unit.abbrev)),
|
| 147 |
+
is_prefixed=True,
|
| 148 |
+
)
|
| 149 |
+
UnitSystem._quantity_dimensional_equivalence_map_global[quantity] = unit
|
| 150 |
+
UnitSystem._quantity_scale_factors_global[quantity] = (prefix.scale_factor, unit)
|
| 151 |
+
prefixed_units.append(quantity)
|
| 152 |
+
|
| 153 |
+
return prefixed_units
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
yotta = Prefix('yotta', 'Y', 24)
|
| 157 |
+
zetta = Prefix('zetta', 'Z', 21)
|
| 158 |
+
exa = Prefix('exa', 'E', 18)
|
| 159 |
+
peta = Prefix('peta', 'P', 15)
|
| 160 |
+
tera = Prefix('tera', 'T', 12)
|
| 161 |
+
giga = Prefix('giga', 'G', 9)
|
| 162 |
+
mega = Prefix('mega', 'M', 6)
|
| 163 |
+
kilo = Prefix('kilo', 'k', 3)
|
| 164 |
+
hecto = Prefix('hecto', 'h', 2)
|
| 165 |
+
deca = Prefix('deca', 'da', 1)
|
| 166 |
+
deci = Prefix('deci', 'd', -1)
|
| 167 |
+
centi = Prefix('centi', 'c', -2)
|
| 168 |
+
milli = Prefix('milli', 'm', -3)
|
| 169 |
+
micro = Prefix('micro', 'mu', -6, latex_repr=r"\mu")
|
| 170 |
+
nano = Prefix('nano', 'n', -9)
|
| 171 |
+
pico = Prefix('pico', 'p', -12)
|
| 172 |
+
femto = Prefix('femto', 'f', -15)
|
| 173 |
+
atto = Prefix('atto', 'a', -18)
|
| 174 |
+
zepto = Prefix('zepto', 'z', -21)
|
| 175 |
+
yocto = Prefix('yocto', 'y', -24)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# https://physics.nist.gov/cuu/Units/prefixes.html
|
| 179 |
+
PREFIXES = {
|
| 180 |
+
'Y': yotta,
|
| 181 |
+
'Z': zetta,
|
| 182 |
+
'E': exa,
|
| 183 |
+
'P': peta,
|
| 184 |
+
'T': tera,
|
| 185 |
+
'G': giga,
|
| 186 |
+
'M': mega,
|
| 187 |
+
'k': kilo,
|
| 188 |
+
'h': hecto,
|
| 189 |
+
'da': deca,
|
| 190 |
+
'd': deci,
|
| 191 |
+
'c': centi,
|
| 192 |
+
'm': milli,
|
| 193 |
+
'mu': micro,
|
| 194 |
+
'n': nano,
|
| 195 |
+
'p': pico,
|
| 196 |
+
'f': femto,
|
| 197 |
+
'a': atto,
|
| 198 |
+
'z': zepto,
|
| 199 |
+
'y': yocto,
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
kibi = Prefix('kibi', 'Y', 10, 2)
|
| 204 |
+
mebi = Prefix('mebi', 'Y', 20, 2)
|
| 205 |
+
gibi = Prefix('gibi', 'Y', 30, 2)
|
| 206 |
+
tebi = Prefix('tebi', 'Y', 40, 2)
|
| 207 |
+
pebi = Prefix('pebi', 'Y', 50, 2)
|
| 208 |
+
exbi = Prefix('exbi', 'Y', 60, 2)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# https://physics.nist.gov/cuu/Units/binary.html
|
| 212 |
+
BIN_PREFIXES = {
|
| 213 |
+
'Ki': kibi,
|
| 214 |
+
'Mi': mebi,
|
| 215 |
+
'Gi': gibi,
|
| 216 |
+
'Ti': tebi,
|
| 217 |
+
'Pi': pebi,
|
| 218 |
+
'Ei': exbi,
|
| 219 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/quantities.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Physical quantities.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from sympy.core.expr import AtomicExpr
|
| 6 |
+
from sympy.core.symbol import Symbol
|
| 7 |
+
from sympy.core.sympify import sympify
|
| 8 |
+
from sympy.physics.units.dimensions import _QuantityMapper
|
| 9 |
+
from sympy.physics.units.prefixes import Prefix
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Quantity(AtomicExpr):
|
| 13 |
+
"""
|
| 14 |
+
Physical quantity: can be a unit of measure, a constant or a generic quantity.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
is_commutative = True
|
| 18 |
+
is_real = True
|
| 19 |
+
is_number = False
|
| 20 |
+
is_nonzero = True
|
| 21 |
+
is_physical_constant = False
|
| 22 |
+
_diff_wrt = True
|
| 23 |
+
|
| 24 |
+
def __new__(cls, name, abbrev=None,
|
| 25 |
+
latex_repr=None, pretty_unicode_repr=None,
|
| 26 |
+
pretty_ascii_repr=None, mathml_presentation_repr=None,
|
| 27 |
+
is_prefixed=False,
|
| 28 |
+
**assumptions):
|
| 29 |
+
|
| 30 |
+
if not isinstance(name, Symbol):
|
| 31 |
+
name = Symbol(name)
|
| 32 |
+
|
| 33 |
+
if abbrev is None:
|
| 34 |
+
abbrev = name
|
| 35 |
+
elif isinstance(abbrev, str):
|
| 36 |
+
abbrev = Symbol(abbrev)
|
| 37 |
+
|
| 38 |
+
# HACK: These are here purely for type checking. They actually get assigned below.
|
| 39 |
+
cls._is_prefixed = is_prefixed
|
| 40 |
+
|
| 41 |
+
obj = AtomicExpr.__new__(cls, name, abbrev)
|
| 42 |
+
obj._name = name
|
| 43 |
+
obj._abbrev = abbrev
|
| 44 |
+
obj._latex_repr = latex_repr
|
| 45 |
+
obj._unicode_repr = pretty_unicode_repr
|
| 46 |
+
obj._ascii_repr = pretty_ascii_repr
|
| 47 |
+
obj._mathml_repr = mathml_presentation_repr
|
| 48 |
+
obj._is_prefixed = is_prefixed
|
| 49 |
+
return obj
|
| 50 |
+
|
| 51 |
+
def set_global_dimension(self, dimension):
|
| 52 |
+
_QuantityMapper._quantity_dimension_global[self] = dimension
|
| 53 |
+
|
| 54 |
+
def set_global_relative_scale_factor(self, scale_factor, reference_quantity):
|
| 55 |
+
"""
|
| 56 |
+
Setting a scale factor that is valid across all unit system.
|
| 57 |
+
"""
|
| 58 |
+
from sympy.physics.units import UnitSystem
|
| 59 |
+
scale_factor = sympify(scale_factor)
|
| 60 |
+
if isinstance(scale_factor, Prefix):
|
| 61 |
+
self._is_prefixed = True
|
| 62 |
+
# replace all prefixes by their ratio to canonical units:
|
| 63 |
+
scale_factor = scale_factor.replace(
|
| 64 |
+
lambda x: isinstance(x, Prefix),
|
| 65 |
+
lambda x: x.scale_factor
|
| 66 |
+
)
|
| 67 |
+
scale_factor = sympify(scale_factor)
|
| 68 |
+
UnitSystem._quantity_scale_factors_global[self] = (scale_factor, reference_quantity)
|
| 69 |
+
UnitSystem._quantity_dimensional_equivalence_map_global[self] = reference_quantity
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def name(self):
|
| 73 |
+
return self._name
|
| 74 |
+
|
| 75 |
+
@property
|
| 76 |
+
def dimension(self):
|
| 77 |
+
from sympy.physics.units import UnitSystem
|
| 78 |
+
unit_system = UnitSystem.get_default_unit_system()
|
| 79 |
+
return unit_system.get_quantity_dimension(self)
|
| 80 |
+
|
| 81 |
+
@property
|
| 82 |
+
def abbrev(self):
|
| 83 |
+
"""
|
| 84 |
+
Symbol representing the unit name.
|
| 85 |
+
|
| 86 |
+
Prepend the abbreviation with the prefix symbol if it is defines.
|
| 87 |
+
"""
|
| 88 |
+
return self._abbrev
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def scale_factor(self):
|
| 92 |
+
"""
|
| 93 |
+
Overall magnitude of the quantity as compared to the canonical units.
|
| 94 |
+
"""
|
| 95 |
+
from sympy.physics.units import UnitSystem
|
| 96 |
+
unit_system = UnitSystem.get_default_unit_system()
|
| 97 |
+
return unit_system.get_quantity_scale_factor(self)
|
| 98 |
+
|
| 99 |
+
def _eval_is_positive(self):
|
| 100 |
+
return True
|
| 101 |
+
|
| 102 |
+
def _eval_is_constant(self):
|
| 103 |
+
return True
|
| 104 |
+
|
| 105 |
+
def _eval_Abs(self):
|
| 106 |
+
return self
|
| 107 |
+
|
| 108 |
+
def _eval_subs(self, old, new):
|
| 109 |
+
if isinstance(new, Quantity) and self != old:
|
| 110 |
+
return self
|
| 111 |
+
|
| 112 |
+
def _latex(self, printer):
|
| 113 |
+
if self._latex_repr:
|
| 114 |
+
return self._latex_repr
|
| 115 |
+
else:
|
| 116 |
+
return r'\text{{{}}}'.format(self.args[1] \
|
| 117 |
+
if len(self.args) >= 2 else self.args[0])
|
| 118 |
+
|
| 119 |
+
def convert_to(self, other, unit_system="SI"):
|
| 120 |
+
"""
|
| 121 |
+
Convert the quantity to another quantity of same dimensions.
|
| 122 |
+
|
| 123 |
+
Examples
|
| 124 |
+
========
|
| 125 |
+
|
| 126 |
+
>>> from sympy.physics.units import speed_of_light, meter, second
|
| 127 |
+
>>> speed_of_light
|
| 128 |
+
speed_of_light
|
| 129 |
+
>>> speed_of_light.convert_to(meter/second)
|
| 130 |
+
299792458*meter/second
|
| 131 |
+
|
| 132 |
+
>>> from sympy.physics.units import liter
|
| 133 |
+
>>> liter.convert_to(meter**3)
|
| 134 |
+
meter**3/1000
|
| 135 |
+
"""
|
| 136 |
+
from .util import convert_to
|
| 137 |
+
return convert_to(self, other, unit_system)
|
| 138 |
+
|
| 139 |
+
@property
|
| 140 |
+
def free_symbols(self):
|
| 141 |
+
"""Return free symbols from quantity."""
|
| 142 |
+
return set()
|
| 143 |
+
|
| 144 |
+
@property
|
| 145 |
+
def is_prefixed(self):
|
| 146 |
+
"""Whether or not the quantity is prefixed. Eg. `kilogram` is prefixed, but `gram` is not."""
|
| 147 |
+
return self._is_prefixed
|
| 148 |
+
|
| 149 |
+
class PhysicalConstant(Quantity):
|
| 150 |
+
"""Represents a physical constant, eg. `speed_of_light` or `avogadro_constant`."""
|
| 151 |
+
|
| 152 |
+
is_physical_constant = True
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/systems/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.physics.units.systems.mks import MKS
|
| 2 |
+
from sympy.physics.units.systems.mksa import MKSA
|
| 3 |
+
from sympy.physics.units.systems.natural import natural
|
| 4 |
+
from sympy.physics.units.systems.si import SI
|
| 5 |
+
|
| 6 |
+
__all__ = ['MKS', 'MKSA', 'natural', 'SI']
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (474 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/length_weight_time.cpython-310.pyc
ADDED
|
Binary file (4.87 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/systems/__pycache__/mksa.cpython-310.pyc
ADDED
|
Binary file (1.68 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/__init__.py
ADDED
|
File without changes
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensions.cpython-310.pyc
ADDED
|
Binary file (6.12 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensionsystem.cpython-310.pyc
ADDED
|
Binary file (2.83 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_quantities.cpython-310.pyc
ADDED
|
Binary file (17.4 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensions.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.physics.units.systems.si import dimsys_SI
|
| 2 |
+
|
| 3 |
+
from sympy.core.numbers import pi
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.core.symbol import Symbol
|
| 6 |
+
from sympy.functions.elementary.complexes import Abs
|
| 7 |
+
from sympy.functions.elementary.exponential import log
|
| 8 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 9 |
+
from sympy.functions.elementary.trigonometric import (acos, atan2, cos)
|
| 10 |
+
from sympy.physics.units.dimensions import Dimension
|
| 11 |
+
from sympy.physics.units.definitions.dimension_definitions import (
|
| 12 |
+
length, time, mass, force, pressure, angle
|
| 13 |
+
)
|
| 14 |
+
from sympy.physics.units import foot
|
| 15 |
+
from sympy.testing.pytest import raises
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_Dimension_definition():
|
| 19 |
+
assert dimsys_SI.get_dimensional_dependencies(length) == {length: 1}
|
| 20 |
+
assert length.name == Symbol("length")
|
| 21 |
+
assert length.symbol == Symbol("L")
|
| 22 |
+
|
| 23 |
+
halflength = sqrt(length)
|
| 24 |
+
assert dimsys_SI.get_dimensional_dependencies(halflength) == {length: S.Half}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_Dimension_error_definition():
|
| 28 |
+
# tuple with more or less than two entries
|
| 29 |
+
raises(TypeError, lambda: Dimension(("length", 1, 2)))
|
| 30 |
+
raises(TypeError, lambda: Dimension(["length"]))
|
| 31 |
+
|
| 32 |
+
# non-number power
|
| 33 |
+
raises(TypeError, lambda: Dimension({"length": "a"}))
|
| 34 |
+
|
| 35 |
+
# non-number with named argument
|
| 36 |
+
raises(TypeError, lambda: Dimension({"length": (1, 2)}))
|
| 37 |
+
|
| 38 |
+
# symbol should by Symbol or str
|
| 39 |
+
raises(AssertionError, lambda: Dimension("length", symbol=1))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_str():
|
| 43 |
+
assert str(Dimension("length")) == "Dimension(length)"
|
| 44 |
+
assert str(Dimension("length", "L")) == "Dimension(length, L)"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_Dimension_properties():
|
| 48 |
+
assert dimsys_SI.is_dimensionless(length) is False
|
| 49 |
+
assert dimsys_SI.is_dimensionless(length/length) is True
|
| 50 |
+
assert dimsys_SI.is_dimensionless(Dimension("undefined")) is False
|
| 51 |
+
|
| 52 |
+
assert length.has_integer_powers(dimsys_SI) is True
|
| 53 |
+
assert (length**(-1)).has_integer_powers(dimsys_SI) is True
|
| 54 |
+
assert (length**1.5).has_integer_powers(dimsys_SI) is False
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_Dimension_add_sub():
|
| 58 |
+
assert length + length == length
|
| 59 |
+
assert length - length == length
|
| 60 |
+
assert -length == length
|
| 61 |
+
|
| 62 |
+
raises(TypeError, lambda: length + foot)
|
| 63 |
+
raises(TypeError, lambda: foot + length)
|
| 64 |
+
raises(TypeError, lambda: length - foot)
|
| 65 |
+
raises(TypeError, lambda: foot - length)
|
| 66 |
+
|
| 67 |
+
# issue 14547 - only raise error for dimensional args; allow
|
| 68 |
+
# others to pass
|
| 69 |
+
x = Symbol('x')
|
| 70 |
+
e = length + x
|
| 71 |
+
assert e == x + length and e.is_Add and set(e.args) == {length, x}
|
| 72 |
+
e = length + 1
|
| 73 |
+
assert e == 1 + length == 1 - length and e.is_Add and set(e.args) == {length, 1}
|
| 74 |
+
|
| 75 |
+
assert dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + force) == \
|
| 76 |
+
{length: 1, mass: 1, time: -2}
|
| 77 |
+
assert dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + force -
|
| 78 |
+
pressure * length**2) == \
|
| 79 |
+
{length: 1, mass: 1, time: -2}
|
| 80 |
+
|
| 81 |
+
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + pressure))
|
| 82 |
+
|
| 83 |
+
def test_Dimension_mul_div_exp():
|
| 84 |
+
assert 2*length == length*2 == length/2 == length
|
| 85 |
+
assert 2/length == 1/length
|
| 86 |
+
x = Symbol('x')
|
| 87 |
+
m = x*length
|
| 88 |
+
assert m == length*x and m.is_Mul and set(m.args) == {x, length}
|
| 89 |
+
d = x/length
|
| 90 |
+
assert d == x*length**-1 and d.is_Mul and set(d.args) == {x, 1/length}
|
| 91 |
+
d = length/x
|
| 92 |
+
assert d == length*x**-1 and d.is_Mul and set(d.args) == {1/x, length}
|
| 93 |
+
|
| 94 |
+
velo = length / time
|
| 95 |
+
|
| 96 |
+
assert (length * length) == length ** 2
|
| 97 |
+
|
| 98 |
+
assert dimsys_SI.get_dimensional_dependencies(length * length) == {length: 2}
|
| 99 |
+
assert dimsys_SI.get_dimensional_dependencies(length ** 2) == {length: 2}
|
| 100 |
+
assert dimsys_SI.get_dimensional_dependencies(length * time) == {length: 1, time: 1}
|
| 101 |
+
assert dimsys_SI.get_dimensional_dependencies(velo) == {length: 1, time: -1}
|
| 102 |
+
assert dimsys_SI.get_dimensional_dependencies(velo ** 2) == {length: 2, time: -2}
|
| 103 |
+
|
| 104 |
+
assert dimsys_SI.get_dimensional_dependencies(length / length) == {}
|
| 105 |
+
assert dimsys_SI.get_dimensional_dependencies(velo / length * time) == {}
|
| 106 |
+
assert dimsys_SI.get_dimensional_dependencies(length ** -1) == {length: -1}
|
| 107 |
+
assert dimsys_SI.get_dimensional_dependencies(velo ** -1.5) == {length: -1.5, time: 1.5}
|
| 108 |
+
|
| 109 |
+
length_a = length**"a"
|
| 110 |
+
assert dimsys_SI.get_dimensional_dependencies(length_a) == {length: Symbol("a")}
|
| 111 |
+
|
| 112 |
+
assert dimsys_SI.get_dimensional_dependencies(length**pi) == {length: pi}
|
| 113 |
+
assert dimsys_SI.get_dimensional_dependencies(length**(length/length)) == {length: Dimension(1)}
|
| 114 |
+
|
| 115 |
+
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(length**length))
|
| 116 |
+
|
| 117 |
+
assert length != 1
|
| 118 |
+
assert length / length != 1
|
| 119 |
+
|
| 120 |
+
length_0 = length ** 0
|
| 121 |
+
assert dimsys_SI.get_dimensional_dependencies(length_0) == {}
|
| 122 |
+
|
| 123 |
+
# issue 18738
|
| 124 |
+
a = Symbol('a')
|
| 125 |
+
b = Symbol('b')
|
| 126 |
+
c = sqrt(a**2 + b**2)
|
| 127 |
+
c_dim = c.subs({a: length, b: length})
|
| 128 |
+
assert dimsys_SI.equivalent_dims(c_dim, length)
|
| 129 |
+
|
| 130 |
+
def test_Dimension_functions():
|
| 131 |
+
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(cos(length)))
|
| 132 |
+
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(acos(angle)))
|
| 133 |
+
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(atan2(length, time)))
|
| 134 |
+
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(length)))
|
| 135 |
+
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(100, length)))
|
| 136 |
+
raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(length, 10)))
|
| 137 |
+
|
| 138 |
+
assert dimsys_SI.get_dimensional_dependencies(pi) == {}
|
| 139 |
+
|
| 140 |
+
assert dimsys_SI.get_dimensional_dependencies(cos(1)) == {}
|
| 141 |
+
assert dimsys_SI.get_dimensional_dependencies(cos(angle)) == {}
|
| 142 |
+
|
| 143 |
+
assert dimsys_SI.get_dimensional_dependencies(atan2(length, length)) == {}
|
| 144 |
+
|
| 145 |
+
assert dimsys_SI.get_dimensional_dependencies(log(length / length, length / length)) == {}
|
| 146 |
+
|
| 147 |
+
assert dimsys_SI.get_dimensional_dependencies(Abs(length)) == {length: 1}
|
| 148 |
+
assert dimsys_SI.get_dimensional_dependencies(Abs(length / length)) == {}
|
| 149 |
+
|
| 150 |
+
assert dimsys_SI.get_dimensional_dependencies(sqrt(-1)) == {}
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensionsystem.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.symbol import symbols
|
| 2 |
+
from sympy.matrices.dense import (Matrix, eye)
|
| 3 |
+
from sympy.physics.units.definitions.dimension_definitions import (
|
| 4 |
+
action, current, length, mass, time,
|
| 5 |
+
velocity)
|
| 6 |
+
from sympy.physics.units.dimensions import DimensionSystem
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_extend():
|
| 10 |
+
ms = DimensionSystem((length, time), (velocity,))
|
| 11 |
+
|
| 12 |
+
mks = ms.extend((mass,), (action,))
|
| 13 |
+
|
| 14 |
+
res = DimensionSystem((length, time, mass), (velocity, action))
|
| 15 |
+
assert mks.base_dims == res.base_dims
|
| 16 |
+
assert mks.derived_dims == res.derived_dims
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_list_dims():
|
| 20 |
+
dimsys = DimensionSystem((length, time, mass))
|
| 21 |
+
|
| 22 |
+
assert dimsys.list_can_dims == (length, mass, time)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_dim_can_vector():
|
| 26 |
+
dimsys = DimensionSystem(
|
| 27 |
+
[length, mass, time],
|
| 28 |
+
[velocity, action],
|
| 29 |
+
{
|
| 30 |
+
velocity: {length: 1, time: -1}
|
| 31 |
+
}
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
assert dimsys.dim_can_vector(length) == Matrix([1, 0, 0])
|
| 35 |
+
assert dimsys.dim_can_vector(velocity) == Matrix([1, 0, -1])
|
| 36 |
+
|
| 37 |
+
dimsys = DimensionSystem(
|
| 38 |
+
(length, velocity, action),
|
| 39 |
+
(mass, time),
|
| 40 |
+
{
|
| 41 |
+
time: {length: 1, velocity: -1}
|
| 42 |
+
}
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
assert dimsys.dim_can_vector(length) == Matrix([0, 1, 0])
|
| 46 |
+
assert dimsys.dim_can_vector(velocity) == Matrix([0, 0, 1])
|
| 47 |
+
assert dimsys.dim_can_vector(time) == Matrix([0, 1, -1])
|
| 48 |
+
|
| 49 |
+
dimsys = DimensionSystem(
|
| 50 |
+
(length, mass, time),
|
| 51 |
+
(velocity, action),
|
| 52 |
+
{velocity: {length: 1, time: -1},
|
| 53 |
+
action: {mass: 1, length: 2, time: -1}})
|
| 54 |
+
|
| 55 |
+
assert dimsys.dim_vector(length) == Matrix([1, 0, 0])
|
| 56 |
+
assert dimsys.dim_vector(velocity) == Matrix([1, 0, -1])
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_inv_can_transf_matrix():
|
| 60 |
+
dimsys = DimensionSystem((length, mass, time))
|
| 61 |
+
assert dimsys.inv_can_transf_matrix == eye(3)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_can_transf_matrix():
|
| 65 |
+
dimsys = DimensionSystem((length, mass, time))
|
| 66 |
+
assert dimsys.can_transf_matrix == eye(3)
|
| 67 |
+
|
| 68 |
+
dimsys = DimensionSystem((length, velocity, action))
|
| 69 |
+
assert dimsys.can_transf_matrix == eye(3)
|
| 70 |
+
|
| 71 |
+
dimsys = DimensionSystem((length, time), (velocity,), {velocity: {length: 1, time: -1}})
|
| 72 |
+
assert dimsys.can_transf_matrix == eye(2)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_is_consistent():
|
| 76 |
+
assert DimensionSystem((length, time)).is_consistent is True
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_print_dim_base():
|
| 80 |
+
mksa = DimensionSystem(
|
| 81 |
+
(length, time, mass, current),
|
| 82 |
+
(action,),
|
| 83 |
+
{action: {mass: 1, length: 2, time: -1}})
|
| 84 |
+
L, M, T = symbols("L M T")
|
| 85 |
+
assert mksa.print_dim_base(action) == L**2*M/T
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_dim():
|
| 89 |
+
dimsys = DimensionSystem(
|
| 90 |
+
(length, mass, time),
|
| 91 |
+
(velocity, action),
|
| 92 |
+
{velocity: {length: 1, time: -1},
|
| 93 |
+
action: {mass: 1, length: 2, time: -1}}
|
| 94 |
+
)
|
| 95 |
+
assert dimsys.dim == 3
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_prefixes.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.mul import Mul
|
| 2 |
+
from sympy.core.numbers import Rational
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 5 |
+
from sympy.physics.units import Quantity, length, meter, W
|
| 6 |
+
from sympy.physics.units.prefixes import PREFIXES, Prefix, prefix_unit, kilo, \
|
| 7 |
+
kibi
|
| 8 |
+
from sympy.physics.units.systems import SI
|
| 9 |
+
|
| 10 |
+
x = Symbol('x')
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_prefix_operations():
|
| 14 |
+
m = PREFIXES['m']
|
| 15 |
+
k = PREFIXES['k']
|
| 16 |
+
M = PREFIXES['M']
|
| 17 |
+
|
| 18 |
+
dodeca = Prefix('dodeca', 'dd', 1, base=12)
|
| 19 |
+
|
| 20 |
+
assert m * k is S.One
|
| 21 |
+
assert m * W == W / 1000
|
| 22 |
+
assert k * k == M
|
| 23 |
+
assert 1 / m == k
|
| 24 |
+
assert k / m == M
|
| 25 |
+
|
| 26 |
+
assert dodeca * dodeca == 144
|
| 27 |
+
assert 1 / dodeca == S.One / 12
|
| 28 |
+
assert k / dodeca == S(1000) / 12
|
| 29 |
+
assert dodeca / dodeca is S.One
|
| 30 |
+
|
| 31 |
+
m = Quantity("fake_meter")
|
| 32 |
+
SI.set_quantity_dimension(m, S.One)
|
| 33 |
+
SI.set_quantity_scale_factor(m, S.One)
|
| 34 |
+
|
| 35 |
+
assert dodeca * m == 12 * m
|
| 36 |
+
assert dodeca / m == 12 / m
|
| 37 |
+
|
| 38 |
+
expr1 = kilo * 3
|
| 39 |
+
assert isinstance(expr1, Mul)
|
| 40 |
+
assert expr1.args == (3, kilo)
|
| 41 |
+
|
| 42 |
+
expr2 = kilo * x
|
| 43 |
+
assert isinstance(expr2, Mul)
|
| 44 |
+
assert expr2.args == (x, kilo)
|
| 45 |
+
|
| 46 |
+
expr3 = kilo / 3
|
| 47 |
+
assert isinstance(expr3, Mul)
|
| 48 |
+
assert expr3.args == (Rational(1, 3), kilo)
|
| 49 |
+
assert expr3.args == (S.One/3, kilo)
|
| 50 |
+
|
| 51 |
+
expr4 = kilo / x
|
| 52 |
+
assert isinstance(expr4, Mul)
|
| 53 |
+
assert expr4.args == (1/x, kilo)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_prefix_unit():
|
| 57 |
+
m = Quantity("fake_meter", abbrev="m")
|
| 58 |
+
m.set_global_relative_scale_factor(1, meter)
|
| 59 |
+
|
| 60 |
+
pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]}
|
| 61 |
+
|
| 62 |
+
q1 = Quantity("millifake_meter", abbrev="mm")
|
| 63 |
+
q2 = Quantity("centifake_meter", abbrev="cm")
|
| 64 |
+
q3 = Quantity("decifake_meter", abbrev="dm")
|
| 65 |
+
|
| 66 |
+
SI.set_quantity_dimension(q1, length)
|
| 67 |
+
|
| 68 |
+
SI.set_quantity_scale_factor(q1, PREFIXES["m"])
|
| 69 |
+
SI.set_quantity_scale_factor(q1, PREFIXES["c"])
|
| 70 |
+
SI.set_quantity_scale_factor(q1, PREFIXES["d"])
|
| 71 |
+
|
| 72 |
+
res = [q1, q2, q3]
|
| 73 |
+
|
| 74 |
+
prefs = prefix_unit(m, pref)
|
| 75 |
+
assert set(prefs) == set(res)
|
| 76 |
+
assert {v.abbrev for v in prefs} == set(symbols("mm,cm,dm"))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_bases():
|
| 80 |
+
assert kilo.base == 10
|
| 81 |
+
assert kibi.base == 2
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_repr():
|
| 85 |
+
assert eval(repr(kilo)) == kilo
|
| 86 |
+
assert eval(repr(kibi)) == kibi
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_quantities.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 2 |
+
|
| 3 |
+
from sympy.core.add import Add
|
| 4 |
+
from sympy.core.function import (Function, diff)
|
| 5 |
+
from sympy.core.numbers import (Number, Rational)
|
| 6 |
+
from sympy.core.singleton import S
|
| 7 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 8 |
+
from sympy.functions.elementary.complexes import Abs
|
| 9 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 10 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 11 |
+
from sympy.functions.elementary.trigonometric import sin
|
| 12 |
+
from sympy.integrals.integrals import integrate
|
| 13 |
+
from sympy.physics.units import (amount_of_substance, area, convert_to, find_unit,
|
| 14 |
+
volume, kilometer, joule, molar_gas_constant,
|
| 15 |
+
vacuum_permittivity, elementary_charge, volt,
|
| 16 |
+
ohm)
|
| 17 |
+
from sympy.physics.units.definitions import (amu, au, centimeter, coulomb,
|
| 18 |
+
day, foot, grams, hour, inch, kg, km, m, meter, millimeter,
|
| 19 |
+
minute, quart, s, second, speed_of_light, bit,
|
| 20 |
+
byte, kibibyte, mebibyte, gibibyte, tebibyte, pebibyte, exbibyte,
|
| 21 |
+
kilogram, gravitational_constant, electron_rest_mass)
|
| 22 |
+
|
| 23 |
+
from sympy.physics.units.definitions.dimension_definitions import (
|
| 24 |
+
Dimension, charge, length, time, temperature, pressure,
|
| 25 |
+
energy, mass
|
| 26 |
+
)
|
| 27 |
+
from sympy.physics.units.prefixes import PREFIXES, kilo
|
| 28 |
+
from sympy.physics.units.quantities import PhysicalConstant, Quantity
|
| 29 |
+
from sympy.physics.units.systems import SI
|
| 30 |
+
from sympy.testing.pytest import raises
|
| 31 |
+
|
| 32 |
+
k = PREFIXES["k"]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_str_repr():
|
| 36 |
+
assert str(kg) == "kilogram"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_eq():
|
| 40 |
+
# simple test
|
| 41 |
+
assert 10*m == 10*m
|
| 42 |
+
assert 10*m != 10*s
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_convert_to():
|
| 46 |
+
q = Quantity("q1")
|
| 47 |
+
q.set_global_relative_scale_factor(S(5000), meter)
|
| 48 |
+
|
| 49 |
+
assert q.convert_to(m) == 5000*m
|
| 50 |
+
|
| 51 |
+
assert speed_of_light.convert_to(m / s) == 299792458 * m / s
|
| 52 |
+
assert day.convert_to(s) == 86400*s
|
| 53 |
+
|
| 54 |
+
# Wrong dimension to convert:
|
| 55 |
+
assert q.convert_to(s) == q
|
| 56 |
+
assert speed_of_light.convert_to(m) == speed_of_light
|
| 57 |
+
|
| 58 |
+
expr = joule*second
|
| 59 |
+
conv = convert_to(expr, joule)
|
| 60 |
+
assert conv == joule*second
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_Quantity_definition():
|
| 64 |
+
q = Quantity("s10", abbrev="sabbr")
|
| 65 |
+
q.set_global_relative_scale_factor(10, second)
|
| 66 |
+
u = Quantity("u", abbrev="dam")
|
| 67 |
+
u.set_global_relative_scale_factor(10, meter)
|
| 68 |
+
km = Quantity("km")
|
| 69 |
+
km.set_global_relative_scale_factor(kilo, meter)
|
| 70 |
+
v = Quantity("u")
|
| 71 |
+
v.set_global_relative_scale_factor(5*kilo, meter)
|
| 72 |
+
|
| 73 |
+
assert q.scale_factor == 10
|
| 74 |
+
assert q.dimension == time
|
| 75 |
+
assert q.abbrev == Symbol("sabbr")
|
| 76 |
+
|
| 77 |
+
assert u.dimension == length
|
| 78 |
+
assert u.scale_factor == 10
|
| 79 |
+
assert u.abbrev == Symbol("dam")
|
| 80 |
+
|
| 81 |
+
assert km.scale_factor == 1000
|
| 82 |
+
assert km.func(*km.args) == km
|
| 83 |
+
assert km.func(*km.args).args == km.args
|
| 84 |
+
|
| 85 |
+
assert v.dimension == length
|
| 86 |
+
assert v.scale_factor == 5000
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_abbrev():
|
| 90 |
+
u = Quantity("u")
|
| 91 |
+
u.set_global_relative_scale_factor(S.One, meter)
|
| 92 |
+
|
| 93 |
+
assert u.name == Symbol("u")
|
| 94 |
+
assert u.abbrev == Symbol("u")
|
| 95 |
+
|
| 96 |
+
u = Quantity("u", abbrev="om")
|
| 97 |
+
u.set_global_relative_scale_factor(S(2), meter)
|
| 98 |
+
|
| 99 |
+
assert u.name == Symbol("u")
|
| 100 |
+
assert u.abbrev == Symbol("om")
|
| 101 |
+
assert u.scale_factor == 2
|
| 102 |
+
assert isinstance(u.scale_factor, Number)
|
| 103 |
+
|
| 104 |
+
u = Quantity("u", abbrev="ikm")
|
| 105 |
+
u.set_global_relative_scale_factor(3*kilo, meter)
|
| 106 |
+
|
| 107 |
+
assert u.abbrev == Symbol("ikm")
|
| 108 |
+
assert u.scale_factor == 3000
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_print():
|
| 112 |
+
u = Quantity("unitname", abbrev="dam")
|
| 113 |
+
assert repr(u) == "unitname"
|
| 114 |
+
assert str(u) == "unitname"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_Quantity_eq():
|
| 118 |
+
u = Quantity("u", abbrev="dam")
|
| 119 |
+
v = Quantity("v1")
|
| 120 |
+
assert u != v
|
| 121 |
+
v = Quantity("v2", abbrev="ds")
|
| 122 |
+
assert u != v
|
| 123 |
+
v = Quantity("v3", abbrev="dm")
|
| 124 |
+
assert u != v
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def test_add_sub():
|
| 128 |
+
u = Quantity("u")
|
| 129 |
+
v = Quantity("v")
|
| 130 |
+
w = Quantity("w")
|
| 131 |
+
|
| 132 |
+
u.set_global_relative_scale_factor(S(10), meter)
|
| 133 |
+
v.set_global_relative_scale_factor(S(5), meter)
|
| 134 |
+
w.set_global_relative_scale_factor(S(2), second)
|
| 135 |
+
|
| 136 |
+
assert isinstance(u + v, Add)
|
| 137 |
+
assert (u + v.convert_to(u)) == (1 + S.Half)*u
|
| 138 |
+
assert isinstance(u - v, Add)
|
| 139 |
+
assert (u - v.convert_to(u)) == S.Half*u
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def test_quantity_abs():
|
| 143 |
+
v_w1 = Quantity('v_w1')
|
| 144 |
+
v_w2 = Quantity('v_w2')
|
| 145 |
+
v_w3 = Quantity('v_w3')
|
| 146 |
+
|
| 147 |
+
v_w1.set_global_relative_scale_factor(1, meter/second)
|
| 148 |
+
v_w2.set_global_relative_scale_factor(1, meter/second)
|
| 149 |
+
v_w3.set_global_relative_scale_factor(1, meter/second)
|
| 150 |
+
|
| 151 |
+
expr = v_w3 - Abs(v_w1 - v_w2)
|
| 152 |
+
|
| 153 |
+
assert SI.get_dimensional_expr(v_w1) == (length/time).name
|
| 154 |
+
|
| 155 |
+
Dq = Dimension(SI.get_dimensional_expr(expr))
|
| 156 |
+
|
| 157 |
+
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
|
| 158 |
+
length: 1,
|
| 159 |
+
time: -1,
|
| 160 |
+
}
|
| 161 |
+
assert meter == sqrt(meter**2)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def test_check_unit_consistency():
|
| 165 |
+
u = Quantity("u")
|
| 166 |
+
v = Quantity("v")
|
| 167 |
+
w = Quantity("w")
|
| 168 |
+
|
| 169 |
+
u.set_global_relative_scale_factor(S(10), meter)
|
| 170 |
+
v.set_global_relative_scale_factor(S(5), meter)
|
| 171 |
+
w.set_global_relative_scale_factor(S(2), second)
|
| 172 |
+
|
| 173 |
+
def check_unit_consistency(expr):
|
| 174 |
+
SI._collect_factor_and_dimension(expr)
|
| 175 |
+
|
| 176 |
+
raises(ValueError, lambda: check_unit_consistency(u + w))
|
| 177 |
+
raises(ValueError, lambda: check_unit_consistency(u - w))
|
| 178 |
+
raises(ValueError, lambda: check_unit_consistency(u + 1))
|
| 179 |
+
raises(ValueError, lambda: check_unit_consistency(u - 1))
|
| 180 |
+
raises(ValueError, lambda: check_unit_consistency(1 - exp(u / w)))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_mul_div():
|
| 184 |
+
u = Quantity("u")
|
| 185 |
+
v = Quantity("v")
|
| 186 |
+
t = Quantity("t")
|
| 187 |
+
ut = Quantity("ut")
|
| 188 |
+
v2 = Quantity("v")
|
| 189 |
+
|
| 190 |
+
u.set_global_relative_scale_factor(S(10), meter)
|
| 191 |
+
v.set_global_relative_scale_factor(S(5), meter)
|
| 192 |
+
t.set_global_relative_scale_factor(S(2), second)
|
| 193 |
+
ut.set_global_relative_scale_factor(S(20), meter*second)
|
| 194 |
+
v2.set_global_relative_scale_factor(S(5), meter/second)
|
| 195 |
+
|
| 196 |
+
assert 1 / u == u**(-1)
|
| 197 |
+
assert u / 1 == u
|
| 198 |
+
|
| 199 |
+
v1 = u / t
|
| 200 |
+
v2 = v
|
| 201 |
+
|
| 202 |
+
# Pow only supports structural equality:
|
| 203 |
+
assert v1 != v2
|
| 204 |
+
assert v1 == v2.convert_to(v1)
|
| 205 |
+
|
| 206 |
+
# TODO: decide whether to allow such expression in the future
|
| 207 |
+
# (requires somehow manipulating the core).
|
| 208 |
+
# assert u / Quantity('l2', dimension=length, scale_factor=2) == 5
|
| 209 |
+
|
| 210 |
+
assert u * 1 == u
|
| 211 |
+
|
| 212 |
+
ut1 = u * t
|
| 213 |
+
ut2 = ut
|
| 214 |
+
|
| 215 |
+
# Mul only supports structural equality:
|
| 216 |
+
assert ut1 != ut2
|
| 217 |
+
assert ut1 == ut2.convert_to(ut1)
|
| 218 |
+
|
| 219 |
+
# Mul only supports structural equality:
|
| 220 |
+
lp1 = Quantity("lp1")
|
| 221 |
+
lp1.set_global_relative_scale_factor(S(2), 1/meter)
|
| 222 |
+
assert u * lp1 != 20
|
| 223 |
+
|
| 224 |
+
assert u**0 == 1
|
| 225 |
+
assert u**1 == u
|
| 226 |
+
|
| 227 |
+
# TODO: Pow only support structural equality:
|
| 228 |
+
u2 = Quantity("u2")
|
| 229 |
+
u3 = Quantity("u3")
|
| 230 |
+
u2.set_global_relative_scale_factor(S(100), meter**2)
|
| 231 |
+
u3.set_global_relative_scale_factor(Rational(1, 10), 1/meter)
|
| 232 |
+
|
| 233 |
+
assert u ** 2 != u2
|
| 234 |
+
assert u ** -1 != u3
|
| 235 |
+
|
| 236 |
+
assert u ** 2 == u2.convert_to(u)
|
| 237 |
+
assert u ** -1 == u3.convert_to(u)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def test_units():
|
| 241 |
+
assert convert_to((5*m/s * day) / km, 1) == 432
|
| 242 |
+
assert convert_to(foot / meter, meter) == Rational(3048, 10000)
|
| 243 |
+
# amu is a pure mass so mass/mass gives a number, not an amount (mol)
|
| 244 |
+
# TODO: need better simplification routine:
|
| 245 |
+
assert str(convert_to(grams/amu, grams).n(2)) == '6.0e+23'
|
| 246 |
+
|
| 247 |
+
# Light from the sun needs about 8.3 minutes to reach earth
|
| 248 |
+
t = (1*au / speed_of_light) / minute
|
| 249 |
+
# TODO: need a better way to simplify expressions containing units:
|
| 250 |
+
t = convert_to(convert_to(t, meter / minute), meter)
|
| 251 |
+
assert t.simplify() == Rational(49865956897, 5995849160)
|
| 252 |
+
|
| 253 |
+
# TODO: fix this, it should give `m` without `Abs`
|
| 254 |
+
assert sqrt(m**2) == m
|
| 255 |
+
assert (sqrt(m))**2 == m
|
| 256 |
+
|
| 257 |
+
t = Symbol('t')
|
| 258 |
+
assert integrate(t*m/s, (t, 1*s, 5*s)) == 12*m*s
|
| 259 |
+
assert (t * m/s).integrate((t, 1*s, 5*s)) == 12*m*s
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def test_issue_quart():
|
| 263 |
+
assert convert_to(4 * quart / inch ** 3, meter) == 231
|
| 264 |
+
assert convert_to(4 * quart / inch ** 3, millimeter) == 231
|
| 265 |
+
|
| 266 |
+
def test_electron_rest_mass():
|
| 267 |
+
assert convert_to(electron_rest_mass, kilogram) == 9.1093837015e-31*kilogram
|
| 268 |
+
assert convert_to(electron_rest_mass, grams) == 9.1093837015e-28*grams
|
| 269 |
+
|
| 270 |
+
def test_issue_5565():
|
| 271 |
+
assert (m < s).is_Relational
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def test_find_unit():
|
| 275 |
+
assert find_unit('coulomb') == ['coulomb', 'coulombs', 'coulomb_constant']
|
| 276 |
+
assert find_unit(coulomb) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
|
| 277 |
+
assert find_unit(charge) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
|
| 278 |
+
assert find_unit(inch) == [
|
| 279 |
+
'm', 'au', 'cm', 'dm', 'ft', 'km', 'ly', 'mi', 'mm', 'nm', 'pm', 'um', 'yd',
|
| 280 |
+
'nmi', 'feet', 'foot', 'inch', 'mile', 'yard', 'meter', 'miles', 'yards',
|
| 281 |
+
'inches', 'meters', 'micron', 'microns', 'angstrom', 'angstroms', 'decimeter',
|
| 282 |
+
'kilometer', 'lightyear', 'nanometer', 'picometer', 'centimeter', 'decimeters',
|
| 283 |
+
'kilometers', 'lightyears', 'micrometer', 'millimeter', 'nanometers', 'picometers',
|
| 284 |
+
'centimeters', 'micrometers', 'millimeters', 'nautical_mile', 'planck_length',
|
| 285 |
+
'nautical_miles', 'astronomical_unit', 'astronomical_units']
|
| 286 |
+
assert find_unit(inch**-1) == ['D', 'dioptre', 'optical_power']
|
| 287 |
+
assert find_unit(length**-1) == ['D', 'dioptre', 'optical_power']
|
| 288 |
+
assert find_unit(inch ** 2) == ['ha', 'hectare', 'planck_area']
|
| 289 |
+
assert find_unit(inch ** 3) == [
|
| 290 |
+
'L', 'l', 'cL', 'cl', 'dL', 'dl', 'mL', 'ml', 'liter', 'quart', 'liters', 'quarts',
|
| 291 |
+
'deciliter', 'centiliter', 'deciliters', 'milliliter',
|
| 292 |
+
'centiliters', 'milliliters', 'planck_volume']
|
| 293 |
+
assert find_unit('voltage') == ['V', 'v', 'volt', 'volts', 'planck_voltage']
|
| 294 |
+
assert find_unit(grams) == ['g', 't', 'Da', 'kg', 'me', 'mg', 'ug', 'amu', 'mmu', 'amus',
|
| 295 |
+
'gram', 'mmus', 'grams', 'pound', 'tonne', 'dalton', 'pounds',
|
| 296 |
+
'kilogram', 'kilograms', 'microgram', 'milligram', 'metric_ton',
|
| 297 |
+
'micrograms', 'milligrams', 'planck_mass', 'milli_mass_unit', 'atomic_mass_unit',
|
| 298 |
+
'electron_rest_mass', 'atomic_mass_constant']
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def test_Quantity_derivative():
|
| 302 |
+
x = symbols("x")
|
| 303 |
+
assert diff(x*meter, x) == meter
|
| 304 |
+
assert diff(x**3*meter**2, x) == 3*x**2*meter**2
|
| 305 |
+
assert diff(meter, meter) == 1
|
| 306 |
+
assert diff(meter**2, meter) == 2*meter
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def test_quantity_postprocessing():
|
| 310 |
+
q1 = Quantity('q1')
|
| 311 |
+
q2 = Quantity('q2')
|
| 312 |
+
|
| 313 |
+
SI.set_quantity_dimension(q1, length*pressure**2*temperature/time)
|
| 314 |
+
SI.set_quantity_dimension(q2, energy*pressure*temperature/(length**2*time))
|
| 315 |
+
|
| 316 |
+
assert q1 + q2
|
| 317 |
+
q = q1 + q2
|
| 318 |
+
Dq = Dimension(SI.get_dimensional_expr(q))
|
| 319 |
+
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
|
| 320 |
+
length: -1,
|
| 321 |
+
mass: 2,
|
| 322 |
+
temperature: 1,
|
| 323 |
+
time: -5,
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def test_factor_and_dimension():
|
| 328 |
+
assert (3000, Dimension(1)) == SI._collect_factor_and_dimension(3000)
|
| 329 |
+
assert (1001, length) == SI._collect_factor_and_dimension(meter + km)
|
| 330 |
+
assert (2, length/time) == SI._collect_factor_and_dimension(
|
| 331 |
+
meter/second + 36*km/(10*hour))
|
| 332 |
+
|
| 333 |
+
x, y = symbols('x y')
|
| 334 |
+
assert (x + y/100, length) == SI._collect_factor_and_dimension(
|
| 335 |
+
x*m + y*centimeter)
|
| 336 |
+
|
| 337 |
+
cH = Quantity('cH')
|
| 338 |
+
SI.set_quantity_dimension(cH, amount_of_substance/volume)
|
| 339 |
+
|
| 340 |
+
pH = -log(cH)
|
| 341 |
+
|
| 342 |
+
assert (1, volume/amount_of_substance) == SI._collect_factor_and_dimension(
|
| 343 |
+
exp(pH))
|
| 344 |
+
|
| 345 |
+
v_w1 = Quantity('v_w1')
|
| 346 |
+
v_w2 = Quantity('v_w2')
|
| 347 |
+
|
| 348 |
+
v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second)
|
| 349 |
+
v_w2.set_global_relative_scale_factor(2, meter/second)
|
| 350 |
+
|
| 351 |
+
expr = Abs(v_w1/2 - v_w2)
|
| 352 |
+
assert (Rational(5, 4), length/time) == \
|
| 353 |
+
SI._collect_factor_and_dimension(expr)
|
| 354 |
+
|
| 355 |
+
expr = Rational(5, 2)*second/meter*v_w1 - 3000
|
| 356 |
+
assert (-(2996 + Rational(1, 4)), Dimension(1)) == \
|
| 357 |
+
SI._collect_factor_and_dimension(expr)
|
| 358 |
+
|
| 359 |
+
expr = v_w1**(v_w2/v_w1)
|
| 360 |
+
assert ((Rational(3, 2))**Rational(4, 3), (length/time)**Rational(4, 3)) == \
|
| 361 |
+
SI._collect_factor_and_dimension(expr)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def test_dimensional_expr_of_derivative():
|
| 365 |
+
l = Quantity('l')
|
| 366 |
+
t = Quantity('t')
|
| 367 |
+
t1 = Quantity('t1')
|
| 368 |
+
l.set_global_relative_scale_factor(36, km)
|
| 369 |
+
t.set_global_relative_scale_factor(1, hour)
|
| 370 |
+
t1.set_global_relative_scale_factor(1, second)
|
| 371 |
+
x = Symbol('x')
|
| 372 |
+
y = Symbol('y')
|
| 373 |
+
f = Function('f')
|
| 374 |
+
dfdx = f(x, y).diff(x, y)
|
| 375 |
+
dl_dt = dfdx.subs({f(x, y): l, x: t, y: t1})
|
| 376 |
+
assert SI.get_dimensional_expr(dl_dt) ==\
|
| 377 |
+
SI.get_dimensional_expr(l / t / t1) ==\
|
| 378 |
+
Symbol("length")/Symbol("time")**2
|
| 379 |
+
assert SI._collect_factor_and_dimension(dl_dt) ==\
|
| 380 |
+
SI._collect_factor_and_dimension(l / t / t1) ==\
|
| 381 |
+
(10, length/time**2)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def test_get_dimensional_expr_with_function():
|
| 385 |
+
v_w1 = Quantity('v_w1')
|
| 386 |
+
v_w2 = Quantity('v_w2')
|
| 387 |
+
v_w1.set_global_relative_scale_factor(1, meter/second)
|
| 388 |
+
v_w2.set_global_relative_scale_factor(1, meter/second)
|
| 389 |
+
|
| 390 |
+
assert SI.get_dimensional_expr(sin(v_w1)) == \
|
| 391 |
+
sin(SI.get_dimensional_expr(v_w1))
|
| 392 |
+
assert SI.get_dimensional_expr(sin(v_w1/v_w2)) == 1
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def test_binary_information():
|
| 396 |
+
assert convert_to(kibibyte, byte) == 1024*byte
|
| 397 |
+
assert convert_to(mebibyte, byte) == 1024**2*byte
|
| 398 |
+
assert convert_to(gibibyte, byte) == 1024**3*byte
|
| 399 |
+
assert convert_to(tebibyte, byte) == 1024**4*byte
|
| 400 |
+
assert convert_to(pebibyte, byte) == 1024**5*byte
|
| 401 |
+
assert convert_to(exbibyte, byte) == 1024**6*byte
|
| 402 |
+
|
| 403 |
+
assert kibibyte.convert_to(bit) == 8*1024*bit
|
| 404 |
+
assert byte.convert_to(bit) == 8*bit
|
| 405 |
+
|
| 406 |
+
a = 10*kibibyte*hour
|
| 407 |
+
|
| 408 |
+
assert convert_to(a, byte) == 10240*byte*hour
|
| 409 |
+
assert convert_to(a, minute) == 600*kibibyte*minute
|
| 410 |
+
assert convert_to(a, [byte, minute]) == 614400*byte*minute
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def test_conversion_with_2_nonstandard_dimensions():
|
| 414 |
+
good_grade = Quantity("good_grade")
|
| 415 |
+
kilo_good_grade = Quantity("kilo_good_grade")
|
| 416 |
+
centi_good_grade = Quantity("centi_good_grade")
|
| 417 |
+
|
| 418 |
+
kilo_good_grade.set_global_relative_scale_factor(1000, good_grade)
|
| 419 |
+
centi_good_grade.set_global_relative_scale_factor(S.One/10**5, kilo_good_grade)
|
| 420 |
+
|
| 421 |
+
charity_points = Quantity("charity_points")
|
| 422 |
+
milli_charity_points = Quantity("milli_charity_points")
|
| 423 |
+
missions = Quantity("missions")
|
| 424 |
+
|
| 425 |
+
milli_charity_points.set_global_relative_scale_factor(S.One/1000, charity_points)
|
| 426 |
+
missions.set_global_relative_scale_factor(251, charity_points)
|
| 427 |
+
|
| 428 |
+
assert convert_to(
|
| 429 |
+
kilo_good_grade*milli_charity_points*millimeter,
|
| 430 |
+
[centi_good_grade, missions, centimeter]
|
| 431 |
+
) == S.One * 10**5 / (251*1000) / 10 * centi_good_grade*missions*centimeter
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def test_eval_subs():
|
| 435 |
+
energy, mass, force = symbols('energy mass force')
|
| 436 |
+
expr1 = energy/mass
|
| 437 |
+
units = {energy: kilogram*meter**2/second**2, mass: kilogram}
|
| 438 |
+
assert expr1.subs(units) == meter**2/second**2
|
| 439 |
+
expr2 = force/mass
|
| 440 |
+
units = {force:gravitational_constant*kilogram**2/meter**2, mass:kilogram}
|
| 441 |
+
assert expr2.subs(units) == gravitational_constant*kilogram/meter**2
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def test_issue_14932():
|
| 445 |
+
assert (log(inch) - log(2)).simplify() == log(inch/2)
|
| 446 |
+
assert (log(inch) - log(foot)).simplify() == -log(12)
|
| 447 |
+
p = symbols('p', positive=True)
|
| 448 |
+
assert (log(inch) - log(p)).simplify() == log(inch/p)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def test_issue_14547():
|
| 452 |
+
# the root issue is that an argument with dimensions should
|
| 453 |
+
# not raise an error when the `arg - 1` calculation is
|
| 454 |
+
# performed in the assumptions system
|
| 455 |
+
from sympy.physics.units import foot, inch
|
| 456 |
+
from sympy.core.relational import Eq
|
| 457 |
+
assert log(foot).is_zero is None
|
| 458 |
+
assert log(foot).is_positive is None
|
| 459 |
+
assert log(foot).is_nonnegative is None
|
| 460 |
+
assert log(foot).is_negative is None
|
| 461 |
+
assert log(foot).is_algebraic is None
|
| 462 |
+
assert log(foot).is_rational is None
|
| 463 |
+
# doesn't raise error
|
| 464 |
+
assert Eq(log(foot), log(inch)) is not None # might be False or unevaluated
|
| 465 |
+
|
| 466 |
+
x = Symbol('x')
|
| 467 |
+
e = foot + x
|
| 468 |
+
assert e.is_Add and set(e.args) == {foot, x}
|
| 469 |
+
e = foot + 1
|
| 470 |
+
assert e.is_Add and set(e.args) == {foot, 1}
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def test_issue_22164():
|
| 474 |
+
warnings.simplefilter("error")
|
| 475 |
+
dm = Quantity("dm")
|
| 476 |
+
SI.set_quantity_dimension(dm, length)
|
| 477 |
+
SI.set_quantity_scale_factor(dm, 1)
|
| 478 |
+
|
| 479 |
+
bad_exp = Quantity("bad_exp")
|
| 480 |
+
SI.set_quantity_dimension(bad_exp, length)
|
| 481 |
+
SI.set_quantity_scale_factor(bad_exp, 1)
|
| 482 |
+
|
| 483 |
+
expr = dm ** bad_exp
|
| 484 |
+
|
| 485 |
+
# deprecation warning is not expected here
|
| 486 |
+
SI._collect_factor_and_dimension(expr)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def test_issue_22819():
|
| 490 |
+
from sympy.physics.units import tonne, gram, Da
|
| 491 |
+
from sympy.physics.units.systems.si import dimsys_SI
|
| 492 |
+
assert tonne.convert_to(gram) == 1000000*gram
|
| 493 |
+
assert dimsys_SI.get_dimensional_dependencies(area) == {length: 2}
|
| 494 |
+
assert Da.scale_factor == 1.66053906660000e-24
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def test_issue_20288():
|
| 498 |
+
from sympy.core.numbers import E
|
| 499 |
+
from sympy.physics.units import energy
|
| 500 |
+
u = Quantity('u')
|
| 501 |
+
v = Quantity('v')
|
| 502 |
+
SI.set_quantity_dimension(u, energy)
|
| 503 |
+
SI.set_quantity_dimension(v, energy)
|
| 504 |
+
u.set_global_relative_scale_factor(1, joule)
|
| 505 |
+
v.set_global_relative_scale_factor(1, joule)
|
| 506 |
+
expr = 1 + exp(u**2/v**2)
|
| 507 |
+
assert SI._collect_factor_and_dimension(expr) == (1 + E, Dimension(1))
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def test_issue_24062():
|
| 511 |
+
from sympy.core.numbers import E
|
| 512 |
+
from sympy.physics.units import impedance, capacitance, time, ohm, farad, second
|
| 513 |
+
|
| 514 |
+
R = Quantity('R')
|
| 515 |
+
C = Quantity('C')
|
| 516 |
+
T = Quantity('T')
|
| 517 |
+
SI.set_quantity_dimension(R, impedance)
|
| 518 |
+
SI.set_quantity_dimension(C, capacitance)
|
| 519 |
+
SI.set_quantity_dimension(T, time)
|
| 520 |
+
R.set_global_relative_scale_factor(1, ohm)
|
| 521 |
+
C.set_global_relative_scale_factor(1, farad)
|
| 522 |
+
T.set_global_relative_scale_factor(1, second)
|
| 523 |
+
expr = T / (R * C)
|
| 524 |
+
dim = SI._collect_factor_and_dimension(expr)[1]
|
| 525 |
+
assert SI.get_dimension_system().is_dimensionless(dim)
|
| 526 |
+
|
| 527 |
+
exp_expr = 1 + exp(expr)
|
| 528 |
+
assert SI._collect_factor_and_dimension(exp_expr) == (1 + E, Dimension(1))
|
| 529 |
+
|
| 530 |
+
def test_issue_24211():
|
| 531 |
+
from sympy.physics.units import time, velocity, acceleration, second, meter
|
| 532 |
+
V1 = Quantity('V1')
|
| 533 |
+
SI.set_quantity_dimension(V1, velocity)
|
| 534 |
+
SI.set_quantity_scale_factor(V1, 1 * meter / second)
|
| 535 |
+
A1 = Quantity('A1')
|
| 536 |
+
SI.set_quantity_dimension(A1, acceleration)
|
| 537 |
+
SI.set_quantity_scale_factor(A1, 1 * meter / second**2)
|
| 538 |
+
T1 = Quantity('T1')
|
| 539 |
+
SI.set_quantity_dimension(T1, time)
|
| 540 |
+
SI.set_quantity_scale_factor(T1, 1 * second)
|
| 541 |
+
|
| 542 |
+
expr = A1*T1 + V1
|
| 543 |
+
# should not throw ValueError here
|
| 544 |
+
SI._collect_factor_and_dimension(expr)
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def test_prefixed_property():
|
| 548 |
+
assert not meter.is_prefixed
|
| 549 |
+
assert not joule.is_prefixed
|
| 550 |
+
assert not day.is_prefixed
|
| 551 |
+
assert not second.is_prefixed
|
| 552 |
+
assert not volt.is_prefixed
|
| 553 |
+
assert not ohm.is_prefixed
|
| 554 |
+
assert centimeter.is_prefixed
|
| 555 |
+
assert kilometer.is_prefixed
|
| 556 |
+
assert kilogram.is_prefixed
|
| 557 |
+
assert pebibyte.is_prefixed
|
| 558 |
+
|
| 559 |
+
def test_physics_constant():
|
| 560 |
+
from sympy.physics.units import definitions
|
| 561 |
+
|
| 562 |
+
for name in dir(definitions):
|
| 563 |
+
quantity = getattr(definitions, name)
|
| 564 |
+
if not isinstance(quantity, Quantity):
|
| 565 |
+
continue
|
| 566 |
+
if name.endswith('_constant'):
|
| 567 |
+
assert isinstance(quantity, PhysicalConstant), f"{quantity} must be PhysicalConstant, but is {type(quantity)}"
|
| 568 |
+
assert quantity.is_physical_constant, f"{name} is not marked as physics constant when it should be"
|
| 569 |
+
|
| 570 |
+
for const in [gravitational_constant, molar_gas_constant, vacuum_permittivity, speed_of_light, elementary_charge]:
|
| 571 |
+
assert isinstance(const, PhysicalConstant), f"{const} must be PhysicalConstant, but is {type(const)}"
|
| 572 |
+
assert const.is_physical_constant, f"{const} is not marked as physics constant when it should be"
|
| 573 |
+
|
| 574 |
+
assert not meter.is_physical_constant
|
| 575 |
+
assert not joule.is_physical_constant
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_unit_system_cgs_gauss.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.concrete.tests.test_sums_products import NS
|
| 2 |
+
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 5 |
+
from sympy.physics.units import convert_to, coulomb_constant, elementary_charge, gravitational_constant, planck
|
| 6 |
+
from sympy.physics.units.definitions.unit_definitions import angstrom, statcoulomb, coulomb, second, gram, centimeter, erg, \
|
| 7 |
+
newton, joule, dyne, speed_of_light, meter, farad, henry, statvolt, volt, ohm
|
| 8 |
+
from sympy.physics.units.systems import SI
|
| 9 |
+
from sympy.physics.units.systems.cgs import cgs_gauss
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_conversion_to_from_si():
|
| 13 |
+
assert convert_to(statcoulomb, coulomb, cgs_gauss) == coulomb/2997924580
|
| 14 |
+
assert convert_to(coulomb, statcoulomb, cgs_gauss) == 2997924580*statcoulomb
|
| 15 |
+
assert convert_to(statcoulomb, sqrt(gram*centimeter**3)/second, cgs_gauss) == centimeter**(S(3)/2)*sqrt(gram)/second
|
| 16 |
+
assert convert_to(coulomb, sqrt(gram*centimeter**3)/second, cgs_gauss) == 2997924580*centimeter**(S(3)/2)*sqrt(gram)/second
|
| 17 |
+
|
| 18 |
+
# SI units have an additional base unit, no conversion in case of electromagnetism:
|
| 19 |
+
assert convert_to(coulomb, statcoulomb, SI) == coulomb
|
| 20 |
+
assert convert_to(statcoulomb, coulomb, SI) == statcoulomb
|
| 21 |
+
|
| 22 |
+
# SI without electromagnetism:
|
| 23 |
+
assert convert_to(erg, joule, SI) == joule/10**7
|
| 24 |
+
assert convert_to(erg, joule, cgs_gauss) == joule/10**7
|
| 25 |
+
assert convert_to(joule, erg, SI) == 10**7*erg
|
| 26 |
+
assert convert_to(joule, erg, cgs_gauss) == 10**7*erg
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
assert convert_to(dyne, newton, SI) == newton/10**5
|
| 30 |
+
assert convert_to(dyne, newton, cgs_gauss) == newton/10**5
|
| 31 |
+
assert convert_to(newton, dyne, SI) == 10**5*dyne
|
| 32 |
+
assert convert_to(newton, dyne, cgs_gauss) == 10**5*dyne
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_cgs_gauss_convert_constants():
|
| 36 |
+
|
| 37 |
+
assert convert_to(speed_of_light, centimeter/second, cgs_gauss) == 29979245800*centimeter/second
|
| 38 |
+
|
| 39 |
+
assert convert_to(coulomb_constant, 1, cgs_gauss) == 1
|
| 40 |
+
assert convert_to(coulomb_constant, newton*meter**2/coulomb**2, cgs_gauss) == 22468879468420441*meter**2*newton/(2500000*coulomb**2)
|
| 41 |
+
assert convert_to(coulomb_constant, newton*meter**2/coulomb**2, SI) == 22468879468420441*meter**2*newton/(2500000*coulomb**2)
|
| 42 |
+
assert convert_to(coulomb_constant, dyne*centimeter**2/statcoulomb**2, cgs_gauss) == centimeter**2*dyne/statcoulomb**2
|
| 43 |
+
assert convert_to(coulomb_constant, 1, SI) == coulomb_constant
|
| 44 |
+
assert NS(convert_to(coulomb_constant, newton*meter**2/coulomb**2, SI)) == '8987551787.36818*meter**2*newton/coulomb**2'
|
| 45 |
+
|
| 46 |
+
assert convert_to(elementary_charge, statcoulomb, cgs_gauss)
|
| 47 |
+
assert convert_to(angstrom, centimeter, cgs_gauss) == 1*centimeter/10**8
|
| 48 |
+
assert convert_to(gravitational_constant, dyne*centimeter**2/gram**2, cgs_gauss)
|
| 49 |
+
assert NS(convert_to(planck, erg*second, cgs_gauss)) == '6.62607015e-27*erg*second'
|
| 50 |
+
|
| 51 |
+
spc = 25000*second/(22468879468420441*centimeter)
|
| 52 |
+
assert convert_to(ohm, second/centimeter, cgs_gauss) == spc
|
| 53 |
+
assert convert_to(henry, second**2/centimeter, cgs_gauss) == spc*second
|
| 54 |
+
assert convert_to(volt, statvolt, cgs_gauss) == 10**6*statvolt/299792458
|
| 55 |
+
assert convert_to(farad, centimeter, cgs_gauss) == 299792458**2*centimeter/10**5
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_unitsystem.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.physics.units import DimensionSystem, joule, second, ampere
|
| 2 |
+
|
| 3 |
+
from sympy.core.numbers import Rational
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.physics.units.definitions import c, kg, m, s
|
| 6 |
+
from sympy.physics.units.definitions.dimension_definitions import length, time
|
| 7 |
+
from sympy.physics.units.quantities import Quantity
|
| 8 |
+
from sympy.physics.units.unitsystem import UnitSystem
|
| 9 |
+
from sympy.physics.units.util import convert_to
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_definition():
|
| 13 |
+
# want to test if the system can have several units of the same dimension
|
| 14 |
+
dm = Quantity("dm")
|
| 15 |
+
base = (m, s)
|
| 16 |
+
# base_dim = (m.dimension, s.dimension)
|
| 17 |
+
ms = UnitSystem(base, (c, dm), "MS", "MS system")
|
| 18 |
+
ms.set_quantity_dimension(dm, length)
|
| 19 |
+
ms.set_quantity_scale_factor(dm, Rational(1, 10))
|
| 20 |
+
|
| 21 |
+
assert set(ms._base_units) == set(base)
|
| 22 |
+
assert set(ms._units) == {m, s, c, dm}
|
| 23 |
+
# assert ms._units == DimensionSystem._sort_dims(base + (velocity,))
|
| 24 |
+
assert ms.name == "MS"
|
| 25 |
+
assert ms.descr == "MS system"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_str_repr():
|
| 29 |
+
assert str(UnitSystem((m, s), name="MS")) == "MS"
|
| 30 |
+
assert str(UnitSystem((m, s))) == "UnitSystem((meter, second))"
|
| 31 |
+
|
| 32 |
+
assert repr(UnitSystem((m, s))) == "<UnitSystem: (%s, %s)>" % (m, s)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_convert_to():
|
| 36 |
+
A = Quantity("A")
|
| 37 |
+
A.set_global_relative_scale_factor(S.One, ampere)
|
| 38 |
+
|
| 39 |
+
Js = Quantity("Js")
|
| 40 |
+
Js.set_global_relative_scale_factor(S.One, joule*second)
|
| 41 |
+
|
| 42 |
+
mksa = UnitSystem((m, kg, s, A), (Js,))
|
| 43 |
+
assert convert_to(Js, mksa._base_units) == m**2*kg*s**-1/1000
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_extend():
|
| 47 |
+
ms = UnitSystem((m, s), (c,))
|
| 48 |
+
Js = Quantity("Js")
|
| 49 |
+
Js.set_global_relative_scale_factor(1, joule*second)
|
| 50 |
+
mks = ms.extend((kg,), (Js,))
|
| 51 |
+
|
| 52 |
+
res = UnitSystem((m, s, kg), (c, Js))
|
| 53 |
+
assert set(mks._base_units) == set(res._base_units)
|
| 54 |
+
assert set(mks._units) == set(res._units)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_dim():
|
| 58 |
+
dimsys = UnitSystem((m, kg, s), (c,))
|
| 59 |
+
assert dimsys.dim == 3
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_is_consistent():
|
| 63 |
+
dimension_system = DimensionSystem([length, time])
|
| 64 |
+
us = UnitSystem([m, s], dimension_system=dimension_system)
|
| 65 |
+
assert us.is_consistent == True
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_get_units_non_prefixed():
|
| 69 |
+
from sympy.physics.units import volt, ohm
|
| 70 |
+
unit_system = UnitSystem.get_unit_system("SI")
|
| 71 |
+
units = unit_system.get_units_non_prefixed()
|
| 72 |
+
for prefix in ["giga", "tera", "peta", "exa", "zetta", "yotta", "kilo", "hecto", "deca", "deci", "centi", "milli", "micro", "nano", "pico", "femto", "atto", "zepto", "yocto"]:
|
| 73 |
+
for unit in units:
|
| 74 |
+
assert isinstance(unit, Quantity), f"{unit} must be a Quantity, not {type(unit)}"
|
| 75 |
+
assert not unit.is_prefixed, f"{unit} is marked as prefixed"
|
| 76 |
+
assert not unit.is_physical_constant, f"{unit} is marked as physics constant"
|
| 77 |
+
assert not unit.name.name.startswith(prefix), f"Unit {unit.name} has prefix {prefix}"
|
| 78 |
+
assert volt in units
|
| 79 |
+
assert ohm in units
|
| 80 |
+
|
| 81 |
+
def test_derived_units_must_exist_in_unit_system():
|
| 82 |
+
for unit_system in UnitSystem._unit_systems.values():
|
| 83 |
+
for preferred_unit in unit_system.derived_units.values():
|
| 84 |
+
units = preferred_unit.atoms(Quantity)
|
| 85 |
+
for unit in units:
|
| 86 |
+
assert unit in unit_system._units, f"Unit {unit} is not in unit system {unit_system}"
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/tests/test_util.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.containers import Tuple
|
| 2 |
+
from sympy.core.numbers import pi
|
| 3 |
+
from sympy.core.power import Pow
|
| 4 |
+
from sympy.core.symbol import symbols
|
| 5 |
+
from sympy.core.sympify import sympify
|
| 6 |
+
from sympy.printing.str import sstr
|
| 7 |
+
from sympy.physics.units import (
|
| 8 |
+
G, centimeter, coulomb, day, degree, gram, hbar, hour, inch, joule, kelvin,
|
| 9 |
+
kilogram, kilometer, length, meter, mile, minute, newton, planck,
|
| 10 |
+
planck_length, planck_mass, planck_temperature, planck_time, radians,
|
| 11 |
+
second, speed_of_light, steradian, time, km)
|
| 12 |
+
from sympy.physics.units.util import convert_to, check_dimensions
|
| 13 |
+
from sympy.testing.pytest import raises
|
| 14 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def NS(e, n=15, **options):
|
| 18 |
+
return sstr(sympify(e).evalf(n, **options), full_prec=True)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
L = length
|
| 22 |
+
T = time
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_dim_simplify_add():
|
| 26 |
+
# assert Add(L, L) == L
|
| 27 |
+
assert L + L == L
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_dim_simplify_mul():
|
| 31 |
+
# assert Mul(L, T) == L*T
|
| 32 |
+
assert L*T == L*T
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_dim_simplify_pow():
|
| 36 |
+
assert Pow(L, 2) == L**2
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_dim_simplify_rec():
|
| 40 |
+
# assert Mul(Add(L, L), T) == L*T
|
| 41 |
+
assert (L + L) * T == L*T
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_convert_to_quantities():
|
| 45 |
+
assert convert_to(3, meter) == 3
|
| 46 |
+
|
| 47 |
+
assert convert_to(mile, kilometer) == 25146*kilometer/15625
|
| 48 |
+
assert convert_to(meter/second, speed_of_light) == speed_of_light/299792458
|
| 49 |
+
assert convert_to(299792458*meter/second, speed_of_light) == speed_of_light
|
| 50 |
+
assert convert_to(2*299792458*meter/second, speed_of_light) == 2*speed_of_light
|
| 51 |
+
assert convert_to(speed_of_light, meter/second) == 299792458*meter/second
|
| 52 |
+
assert convert_to(2*speed_of_light, meter/second) == 599584916*meter/second
|
| 53 |
+
assert convert_to(day, second) == 86400*second
|
| 54 |
+
assert convert_to(2*hour, minute) == 120*minute
|
| 55 |
+
assert convert_to(mile, meter) == 201168*meter/125
|
| 56 |
+
assert convert_to(mile/hour, kilometer/hour) == 25146*kilometer/(15625*hour)
|
| 57 |
+
assert convert_to(3*newton, meter/second) == 3*newton
|
| 58 |
+
assert convert_to(3*newton, kilogram*meter/second**2) == 3*meter*kilogram/second**2
|
| 59 |
+
assert convert_to(kilometer + mile, meter) == 326168*meter/125
|
| 60 |
+
assert convert_to(2*kilometer + 3*mile, meter) == 853504*meter/125
|
| 61 |
+
assert convert_to(inch**2, meter**2) == 16129*meter**2/25000000
|
| 62 |
+
assert convert_to(3*inch**2, meter) == 48387*meter**2/25000000
|
| 63 |
+
assert convert_to(2*kilometer/hour + 3*mile/hour, meter/second) == 53344*meter/(28125*second)
|
| 64 |
+
assert convert_to(2*kilometer/hour + 3*mile/hour, centimeter/second) == 213376*centimeter/(1125*second)
|
| 65 |
+
assert convert_to(kilometer * (mile + kilometer), meter) == 2609344 * meter ** 2
|
| 66 |
+
|
| 67 |
+
assert convert_to(steradian, coulomb) == steradian
|
| 68 |
+
assert convert_to(radians, degree) == 180*degree/pi
|
| 69 |
+
assert convert_to(radians, [meter, degree]) == 180*degree/pi
|
| 70 |
+
assert convert_to(pi*radians, degree) == 180*degree
|
| 71 |
+
assert convert_to(pi, degree) == 180*degree
|
| 72 |
+
|
| 73 |
+
# https://github.com/sympy/sympy/issues/26263
|
| 74 |
+
assert convert_to(sqrt(meter**2 + meter**2.0), meter) == sqrt(meter**2 + meter**2.0)
|
| 75 |
+
assert convert_to((meter**2 + meter**2.0)**2, meter) == (meter**2 + meter**2.0)**2
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_convert_to_tuples_of_quantities():
|
| 79 |
+
from sympy.core.symbol import symbols
|
| 80 |
+
|
| 81 |
+
alpha, beta = symbols('alpha beta')
|
| 82 |
+
|
| 83 |
+
assert convert_to(speed_of_light, [meter, second]) == 299792458 * meter / second
|
| 84 |
+
assert convert_to(speed_of_light, (meter, second)) == 299792458 * meter / second
|
| 85 |
+
assert convert_to(speed_of_light, Tuple(meter, second)) == 299792458 * meter / second
|
| 86 |
+
assert convert_to(joule, [meter, kilogram, second]) == kilogram*meter**2/second**2
|
| 87 |
+
assert convert_to(joule, [centimeter, gram, second]) == 10000000*centimeter**2*gram/second**2
|
| 88 |
+
assert convert_to(299792458*meter/second, [speed_of_light]) == speed_of_light
|
| 89 |
+
assert convert_to(speed_of_light / 2, [meter, second, kilogram]) == meter/second*299792458 / 2
|
| 90 |
+
# This doesn't make physically sense, but let's keep it as a conversion test:
|
| 91 |
+
assert convert_to(2 * speed_of_light, [meter, second, kilogram]) == 2 * 299792458 * meter / second
|
| 92 |
+
assert convert_to(G, [G, speed_of_light, planck]) == 1.0*G
|
| 93 |
+
|
| 94 |
+
assert NS(convert_to(meter, [G, speed_of_light, hbar]), n=7) == '6.187142e+34*gravitational_constant**0.5000000*hbar**0.5000000/speed_of_light**1.500000'
|
| 95 |
+
assert NS(convert_to(planck_mass, kilogram), n=7) == '2.176434e-8*kilogram'
|
| 96 |
+
assert NS(convert_to(planck_length, meter), n=7) == '1.616255e-35*meter'
|
| 97 |
+
assert NS(convert_to(planck_time, second), n=6) == '5.39125e-44*second'
|
| 98 |
+
assert NS(convert_to(planck_temperature, kelvin), n=7) == '1.416784e+32*kelvin'
|
| 99 |
+
assert NS(convert_to(convert_to(meter, [G, speed_of_light, planck]), meter), n=10) == '1.000000000*meter'
|
| 100 |
+
|
| 101 |
+
# similar to https://github.com/sympy/sympy/issues/26263
|
| 102 |
+
assert convert_to(sqrt(meter**2 + second**2.0), [meter, second]) == sqrt(meter**2 + second**2.0)
|
| 103 |
+
assert convert_to((meter**2 + second**2.0)**2, [meter, second]) == (meter**2 + second**2.0)**2
|
| 104 |
+
|
| 105 |
+
# similar to https://github.com/sympy/sympy/issues/21463
|
| 106 |
+
assert convert_to(1/(beta*meter + meter), 1/meter) == 1/(beta*meter + meter)
|
| 107 |
+
assert convert_to(1/(beta*meter + alpha*meter), 1/kilometer) == (1/(kilometer*beta/1000 + alpha*kilometer/1000))
|
| 108 |
+
|
| 109 |
+
def test_eval_simplify():
|
| 110 |
+
from sympy.physics.units import cm, mm, km, m, K, kilo
|
| 111 |
+
from sympy.core.symbol import symbols
|
| 112 |
+
|
| 113 |
+
x, y = symbols('x y')
|
| 114 |
+
|
| 115 |
+
assert (cm/mm).simplify() == 10
|
| 116 |
+
assert (km/m).simplify() == 1000
|
| 117 |
+
assert (km/cm).simplify() == 100000
|
| 118 |
+
assert (10*x*K*km**2/m/cm).simplify() == 1000000000*x*kelvin
|
| 119 |
+
assert (cm/km/m).simplify() == 1/(10000000*centimeter)
|
| 120 |
+
|
| 121 |
+
assert (3*kilo*meter).simplify() == 3000*meter
|
| 122 |
+
assert (4*kilo*meter/(2*kilometer)).simplify() == 2
|
| 123 |
+
assert (4*kilometer**2/(kilo*meter)**2).simplify() == 4
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_quantity_simplify():
|
| 127 |
+
from sympy.physics.units.util import quantity_simplify
|
| 128 |
+
from sympy.physics.units import kilo, foot
|
| 129 |
+
from sympy.core.symbol import symbols
|
| 130 |
+
|
| 131 |
+
x, y = symbols('x y')
|
| 132 |
+
|
| 133 |
+
assert quantity_simplify(x*(8*kilo*newton*meter + y)) == x*(8000*meter*newton + y)
|
| 134 |
+
assert quantity_simplify(foot*inch*(foot + inch)) == foot**2*(foot + foot/12)/12
|
| 135 |
+
assert quantity_simplify(foot*inch*(foot*foot + inch*(foot + inch))) == foot**2*(foot**2 + foot/12*(foot + foot/12))/12
|
| 136 |
+
assert quantity_simplify(2**(foot/inch*kilo/1000)*inch) == 4096*foot/12
|
| 137 |
+
assert quantity_simplify(foot**2*inch + inch**2*foot) == 13*foot**3/144
|
| 138 |
+
|
| 139 |
+
def test_quantity_simplify_across_dimensions():
|
| 140 |
+
from sympy.physics.units.util import quantity_simplify
|
| 141 |
+
from sympy.physics.units import ampere, ohm, volt, joule, pascal, farad, second, watt, siemens, henry, tesla, weber, hour, newton
|
| 142 |
+
|
| 143 |
+
assert quantity_simplify(ampere*ohm, across_dimensions=True, unit_system="SI") == volt
|
| 144 |
+
assert quantity_simplify(6*ampere*ohm, across_dimensions=True, unit_system="SI") == 6*volt
|
| 145 |
+
assert quantity_simplify(volt/ampere, across_dimensions=True, unit_system="SI") == ohm
|
| 146 |
+
assert quantity_simplify(volt/ohm, across_dimensions=True, unit_system="SI") == ampere
|
| 147 |
+
assert quantity_simplify(joule/meter**3, across_dimensions=True, unit_system="SI") == pascal
|
| 148 |
+
assert quantity_simplify(farad*ohm, across_dimensions=True, unit_system="SI") == second
|
| 149 |
+
assert quantity_simplify(joule/second, across_dimensions=True, unit_system="SI") == watt
|
| 150 |
+
assert quantity_simplify(meter**3/second, across_dimensions=True, unit_system="SI") == meter**3/second
|
| 151 |
+
assert quantity_simplify(joule/second, across_dimensions=True, unit_system="SI") == watt
|
| 152 |
+
|
| 153 |
+
assert quantity_simplify(joule/coulomb, across_dimensions=True, unit_system="SI") == volt
|
| 154 |
+
assert quantity_simplify(volt/ampere, across_dimensions=True, unit_system="SI") == ohm
|
| 155 |
+
assert quantity_simplify(ampere/volt, across_dimensions=True, unit_system="SI") == siemens
|
| 156 |
+
assert quantity_simplify(coulomb/volt, across_dimensions=True, unit_system="SI") == farad
|
| 157 |
+
assert quantity_simplify(volt*second/ampere, across_dimensions=True, unit_system="SI") == henry
|
| 158 |
+
assert quantity_simplify(volt*second/meter**2, across_dimensions=True, unit_system="SI") == tesla
|
| 159 |
+
assert quantity_simplify(joule/ampere, across_dimensions=True, unit_system="SI") == weber
|
| 160 |
+
|
| 161 |
+
assert quantity_simplify(5*kilometer/hour, across_dimensions=True, unit_system="SI") == 25*meter/(18*second)
|
| 162 |
+
assert quantity_simplify(5*kilogram*meter/second**2, across_dimensions=True, unit_system="SI") == 5*newton
|
| 163 |
+
|
| 164 |
+
def test_check_dimensions():
|
| 165 |
+
x = symbols('x')
|
| 166 |
+
assert check_dimensions(inch + x) == inch + x
|
| 167 |
+
assert check_dimensions(length + x) == length + x
|
| 168 |
+
# after subs we get 2*length; check will clear the constant
|
| 169 |
+
assert check_dimensions((length + x).subs(x, length)) == length
|
| 170 |
+
assert check_dimensions(newton*meter + joule) == joule + meter*newton
|
| 171 |
+
raises(ValueError, lambda: check_dimensions(inch + 1))
|
| 172 |
+
raises(ValueError, lambda: check_dimensions(length + 1))
|
| 173 |
+
raises(ValueError, lambda: check_dimensions(length + time))
|
| 174 |
+
raises(ValueError, lambda: check_dimensions(meter + second))
|
| 175 |
+
raises(ValueError, lambda: check_dimensions(2 * meter + second))
|
| 176 |
+
raises(ValueError, lambda: check_dimensions(2 * meter + 3 * second))
|
| 177 |
+
raises(ValueError, lambda: check_dimensions(1 / second + 1 / meter))
|
| 178 |
+
raises(ValueError, lambda: check_dimensions(2 * meter*(mile + centimeter) + km))
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/unitsystem.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unit system for physical quantities; include definition of constants.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Dict as tDict, Set as tSet
|
| 6 |
+
|
| 7 |
+
from sympy.core.add import Add
|
| 8 |
+
from sympy.core.function import (Derivative, Function)
|
| 9 |
+
from sympy.core.mul import Mul
|
| 10 |
+
from sympy.core.power import Pow
|
| 11 |
+
from sympy.core.singleton import S
|
| 12 |
+
from sympy.physics.units.dimensions import _QuantityMapper
|
| 13 |
+
from sympy.physics.units.quantities import Quantity
|
| 14 |
+
|
| 15 |
+
from .dimensions import Dimension
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class UnitSystem(_QuantityMapper):
|
| 19 |
+
"""
|
| 20 |
+
UnitSystem represents a coherent set of units.
|
| 21 |
+
|
| 22 |
+
A unit system is basically a dimension system with notions of scales. Many
|
| 23 |
+
of the methods are defined in the same way.
|
| 24 |
+
|
| 25 |
+
It is much better if all base units have a symbol.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
_unit_systems = {} # type: tDict[str, UnitSystem]
|
| 29 |
+
|
| 30 |
+
def __init__(self, base_units, units=(), name="", descr="", dimension_system=None, derived_units: tDict[Dimension, Quantity]={}):
|
| 31 |
+
|
| 32 |
+
UnitSystem._unit_systems[name] = self
|
| 33 |
+
|
| 34 |
+
self.name = name
|
| 35 |
+
self.descr = descr
|
| 36 |
+
|
| 37 |
+
self._base_units = base_units
|
| 38 |
+
self._dimension_system = dimension_system
|
| 39 |
+
self._units = tuple(set(base_units) | set(units))
|
| 40 |
+
self._base_units = tuple(base_units)
|
| 41 |
+
self._derived_units = derived_units
|
| 42 |
+
|
| 43 |
+
super().__init__()
|
| 44 |
+
|
| 45 |
+
def __str__(self):
|
| 46 |
+
"""
|
| 47 |
+
Return the name of the system.
|
| 48 |
+
|
| 49 |
+
If it does not exist, then it makes a list of symbols (or names) of
|
| 50 |
+
the base dimensions.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
if self.name != "":
|
| 54 |
+
return self.name
|
| 55 |
+
else:
|
| 56 |
+
return "UnitSystem((%s))" % ", ".join(
|
| 57 |
+
str(d) for d in self._base_units)
|
| 58 |
+
|
| 59 |
+
def __repr__(self):
|
| 60 |
+
return '<UnitSystem: %s>' % repr(self._base_units)
|
| 61 |
+
|
| 62 |
+
def extend(self, base, units=(), name="", description="", dimension_system=None, derived_units: tDict[Dimension, Quantity]={}):
|
| 63 |
+
"""Extend the current system into a new one.
|
| 64 |
+
|
| 65 |
+
Take the base and normal units of the current system to merge
|
| 66 |
+
them to the base and normal units given in argument.
|
| 67 |
+
If not provided, name and description are overridden by empty strings.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
base = self._base_units + tuple(base)
|
| 71 |
+
units = self._units + tuple(units)
|
| 72 |
+
|
| 73 |
+
return UnitSystem(base, units, name, description, dimension_system, {**self._derived_units, **derived_units})
|
| 74 |
+
|
| 75 |
+
def get_dimension_system(self):
|
| 76 |
+
return self._dimension_system
|
| 77 |
+
|
| 78 |
+
def get_quantity_dimension(self, unit):
|
| 79 |
+
qdm = self.get_dimension_system()._quantity_dimension_map
|
| 80 |
+
if unit in qdm:
|
| 81 |
+
return qdm[unit]
|
| 82 |
+
return super().get_quantity_dimension(unit)
|
| 83 |
+
|
| 84 |
+
def get_quantity_scale_factor(self, unit):
|
| 85 |
+
qsfm = self.get_dimension_system()._quantity_scale_factors
|
| 86 |
+
if unit in qsfm:
|
| 87 |
+
return qsfm[unit]
|
| 88 |
+
return super().get_quantity_scale_factor(unit)
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def get_unit_system(unit_system):
|
| 92 |
+
if isinstance(unit_system, UnitSystem):
|
| 93 |
+
return unit_system
|
| 94 |
+
|
| 95 |
+
if unit_system not in UnitSystem._unit_systems:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
"Unit system is not supported. Currently"
|
| 98 |
+
"supported unit systems are {}".format(
|
| 99 |
+
", ".join(sorted(UnitSystem._unit_systems))
|
| 100 |
+
)
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
return UnitSystem._unit_systems[unit_system]
|
| 104 |
+
|
| 105 |
+
@staticmethod
|
| 106 |
+
def get_default_unit_system():
|
| 107 |
+
return UnitSystem._unit_systems["SI"]
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def dim(self):
|
| 111 |
+
"""
|
| 112 |
+
Give the dimension of the system.
|
| 113 |
+
|
| 114 |
+
That is return the number of units forming the basis.
|
| 115 |
+
"""
|
| 116 |
+
return len(self._base_units)
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def is_consistent(self):
|
| 120 |
+
"""
|
| 121 |
+
Check if the underlying dimension system is consistent.
|
| 122 |
+
"""
|
| 123 |
+
# test is performed in DimensionSystem
|
| 124 |
+
return self.get_dimension_system().is_consistent
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def derived_units(self) -> tDict[Dimension, Quantity]:
|
| 128 |
+
return self._derived_units
|
| 129 |
+
|
| 130 |
+
def get_dimensional_expr(self, expr):
|
| 131 |
+
from sympy.physics.units import Quantity
|
| 132 |
+
if isinstance(expr, Mul):
|
| 133 |
+
return Mul(*[self.get_dimensional_expr(i) for i in expr.args])
|
| 134 |
+
elif isinstance(expr, Pow):
|
| 135 |
+
return self.get_dimensional_expr(expr.base) ** expr.exp
|
| 136 |
+
elif isinstance(expr, Add):
|
| 137 |
+
return self.get_dimensional_expr(expr.args[0])
|
| 138 |
+
elif isinstance(expr, Derivative):
|
| 139 |
+
dim = self.get_dimensional_expr(expr.expr)
|
| 140 |
+
for independent, count in expr.variable_count:
|
| 141 |
+
dim /= self.get_dimensional_expr(independent)**count
|
| 142 |
+
return dim
|
| 143 |
+
elif isinstance(expr, Function):
|
| 144 |
+
args = [self.get_dimensional_expr(arg) for arg in expr.args]
|
| 145 |
+
if all(i == 1 for i in args):
|
| 146 |
+
return S.One
|
| 147 |
+
return expr.func(*args)
|
| 148 |
+
elif isinstance(expr, Quantity):
|
| 149 |
+
return self.get_quantity_dimension(expr).name
|
| 150 |
+
return S.One
|
| 151 |
+
|
| 152 |
+
def _collect_factor_and_dimension(self, expr):
|
| 153 |
+
"""
|
| 154 |
+
Return tuple with scale factor expression and dimension expression.
|
| 155 |
+
"""
|
| 156 |
+
from sympy.physics.units import Quantity
|
| 157 |
+
if isinstance(expr, Quantity):
|
| 158 |
+
return expr.scale_factor, expr.dimension
|
| 159 |
+
elif isinstance(expr, Mul):
|
| 160 |
+
factor = 1
|
| 161 |
+
dimension = Dimension(1)
|
| 162 |
+
for arg in expr.args:
|
| 163 |
+
arg_factor, arg_dim = self._collect_factor_and_dimension(arg)
|
| 164 |
+
factor *= arg_factor
|
| 165 |
+
dimension *= arg_dim
|
| 166 |
+
return factor, dimension
|
| 167 |
+
elif isinstance(expr, Pow):
|
| 168 |
+
factor, dim = self._collect_factor_and_dimension(expr.base)
|
| 169 |
+
exp_factor, exp_dim = self._collect_factor_and_dimension(expr.exp)
|
| 170 |
+
if self.get_dimension_system().is_dimensionless(exp_dim):
|
| 171 |
+
exp_dim = 1
|
| 172 |
+
return factor ** exp_factor, dim ** (exp_factor * exp_dim)
|
| 173 |
+
elif isinstance(expr, Add):
|
| 174 |
+
factor, dim = self._collect_factor_and_dimension(expr.args[0])
|
| 175 |
+
for addend in expr.args[1:]:
|
| 176 |
+
addend_factor, addend_dim = \
|
| 177 |
+
self._collect_factor_and_dimension(addend)
|
| 178 |
+
if not self.get_dimension_system().equivalent_dims(dim, addend_dim):
|
| 179 |
+
raise ValueError(
|
| 180 |
+
'Dimension of "{}" is {}, '
|
| 181 |
+
'but it should be {}'.format(
|
| 182 |
+
addend, addend_dim, dim))
|
| 183 |
+
factor += addend_factor
|
| 184 |
+
return factor, dim
|
| 185 |
+
elif isinstance(expr, Derivative):
|
| 186 |
+
factor, dim = self._collect_factor_and_dimension(expr.args[0])
|
| 187 |
+
for independent, count in expr.variable_count:
|
| 188 |
+
ifactor, idim = self._collect_factor_and_dimension(independent)
|
| 189 |
+
factor /= ifactor**count
|
| 190 |
+
dim /= idim**count
|
| 191 |
+
return factor, dim
|
| 192 |
+
elif isinstance(expr, Function):
|
| 193 |
+
fds = [self._collect_factor_and_dimension(arg) for arg in expr.args]
|
| 194 |
+
dims = [Dimension(1) if self.get_dimension_system().is_dimensionless(d[1]) else d[1] for d in fds]
|
| 195 |
+
return (expr.func(*(f[0] for f in fds)), *dims)
|
| 196 |
+
elif isinstance(expr, Dimension):
|
| 197 |
+
return S.One, expr
|
| 198 |
+
else:
|
| 199 |
+
return expr, Dimension(1)
|
| 200 |
+
|
| 201 |
+
def get_units_non_prefixed(self) -> tSet[Quantity]:
|
| 202 |
+
"""
|
| 203 |
+
Return the units of the system that do not have a prefix.
|
| 204 |
+
"""
|
| 205 |
+
return set(filter(lambda u: not u.is_prefixed and not u.is_physical_constant, self._units))
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/units/util.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Several methods to simplify expressions involving unit objects.
|
| 3 |
+
"""
|
| 4 |
+
from functools import reduce
|
| 5 |
+
from collections.abc import Iterable
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
from sympy import default_sort_key
|
| 9 |
+
from sympy.core.add import Add
|
| 10 |
+
from sympy.core.containers import Tuple
|
| 11 |
+
from sympy.core.mul import Mul
|
| 12 |
+
from sympy.core.power import Pow
|
| 13 |
+
from sympy.core.sorting import ordered
|
| 14 |
+
from sympy.core.sympify import sympify
|
| 15 |
+
from sympy.core.function import Function
|
| 16 |
+
from sympy.matrices.exceptions import NonInvertibleMatrixError
|
| 17 |
+
from sympy.physics.units.dimensions import Dimension, DimensionSystem
|
| 18 |
+
from sympy.physics.units.prefixes import Prefix
|
| 19 |
+
from sympy.physics.units.quantities import Quantity
|
| 20 |
+
from sympy.physics.units.unitsystem import UnitSystem
|
| 21 |
+
from sympy.utilities.iterables import sift
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _get_conversion_matrix_for_expr(expr, target_units, unit_system):
|
| 25 |
+
from sympy.matrices.dense import Matrix
|
| 26 |
+
|
| 27 |
+
dimension_system = unit_system.get_dimension_system()
|
| 28 |
+
|
| 29 |
+
expr_dim = Dimension(unit_system.get_dimensional_expr(expr))
|
| 30 |
+
dim_dependencies = dimension_system.get_dimensional_dependencies(expr_dim, mark_dimensionless=True)
|
| 31 |
+
target_dims = [Dimension(unit_system.get_dimensional_expr(x)) for x in target_units]
|
| 32 |
+
canon_dim_units = [i for x in target_dims for i in dimension_system.get_dimensional_dependencies(x, mark_dimensionless=True)]
|
| 33 |
+
canon_expr_units = set(dim_dependencies)
|
| 34 |
+
|
| 35 |
+
if not canon_expr_units.issubset(set(canon_dim_units)):
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
seen = set()
|
| 39 |
+
canon_dim_units = [i for i in canon_dim_units if not (i in seen or seen.add(i))]
|
| 40 |
+
|
| 41 |
+
camat = Matrix([[dimension_system.get_dimensional_dependencies(i, mark_dimensionless=True).get(j, 0) for i in target_dims] for j in canon_dim_units])
|
| 42 |
+
exprmat = Matrix([dim_dependencies.get(k, 0) for k in canon_dim_units])
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
res_exponents = camat.solve(exprmat)
|
| 46 |
+
except NonInvertibleMatrixError:
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
return res_exponents
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def convert_to(expr, target_units, unit_system="SI"):
|
| 53 |
+
"""
|
| 54 |
+
Convert ``expr`` to the same expression with all of its units and quantities
|
| 55 |
+
represented as factors of ``target_units``, whenever the dimension is compatible.
|
| 56 |
+
|
| 57 |
+
``target_units`` may be a single unit/quantity, or a collection of
|
| 58 |
+
units/quantities.
|
| 59 |
+
|
| 60 |
+
Examples
|
| 61 |
+
========
|
| 62 |
+
|
| 63 |
+
>>> from sympy.physics.units import speed_of_light, meter, gram, second, day
|
| 64 |
+
>>> from sympy.physics.units import mile, newton, kilogram, atomic_mass_constant
|
| 65 |
+
>>> from sympy.physics.units import kilometer, centimeter
|
| 66 |
+
>>> from sympy.physics.units import gravitational_constant, hbar
|
| 67 |
+
>>> from sympy.physics.units import convert_to
|
| 68 |
+
>>> convert_to(mile, kilometer)
|
| 69 |
+
25146*kilometer/15625
|
| 70 |
+
>>> convert_to(mile, kilometer).n()
|
| 71 |
+
1.609344*kilometer
|
| 72 |
+
>>> convert_to(speed_of_light, meter/second)
|
| 73 |
+
299792458*meter/second
|
| 74 |
+
>>> convert_to(day, second)
|
| 75 |
+
86400*second
|
| 76 |
+
>>> 3*newton
|
| 77 |
+
3*newton
|
| 78 |
+
>>> convert_to(3*newton, kilogram*meter/second**2)
|
| 79 |
+
3*kilogram*meter/second**2
|
| 80 |
+
>>> convert_to(atomic_mass_constant, gram)
|
| 81 |
+
1.660539060e-24*gram
|
| 82 |
+
|
| 83 |
+
Conversion to multiple units:
|
| 84 |
+
|
| 85 |
+
>>> convert_to(speed_of_light, [meter, second])
|
| 86 |
+
299792458*meter/second
|
| 87 |
+
>>> convert_to(3*newton, [centimeter, gram, second])
|
| 88 |
+
300000*centimeter*gram/second**2
|
| 89 |
+
|
| 90 |
+
Conversion to Planck units:
|
| 91 |
+
|
| 92 |
+
>>> convert_to(atomic_mass_constant, [gravitational_constant, speed_of_light, hbar]).n()
|
| 93 |
+
7.62963087839509e-20*hbar**0.5*speed_of_light**0.5/gravitational_constant**0.5
|
| 94 |
+
|
| 95 |
+
"""
|
| 96 |
+
from sympy.physics.units import UnitSystem
|
| 97 |
+
unit_system = UnitSystem.get_unit_system(unit_system)
|
| 98 |
+
|
| 99 |
+
if not isinstance(target_units, (Iterable, Tuple)):
|
| 100 |
+
target_units = [target_units]
|
| 101 |
+
|
| 102 |
+
def handle_Adds(expr):
|
| 103 |
+
return Add.fromiter(convert_to(i, target_units, unit_system)
|
| 104 |
+
for i in expr.args)
|
| 105 |
+
|
| 106 |
+
if isinstance(expr, Add):
|
| 107 |
+
return handle_Adds(expr)
|
| 108 |
+
elif isinstance(expr, Pow) and isinstance(expr.base, Add):
|
| 109 |
+
return handle_Adds(expr.base) ** expr.exp
|
| 110 |
+
|
| 111 |
+
expr = sympify(expr)
|
| 112 |
+
target_units = sympify(target_units)
|
| 113 |
+
|
| 114 |
+
if isinstance(expr, Function):
|
| 115 |
+
expr = expr.together()
|
| 116 |
+
|
| 117 |
+
if not isinstance(expr, Quantity) and expr.has(Quantity):
|
| 118 |
+
expr = expr.replace(lambda x: isinstance(x, Quantity),
|
| 119 |
+
lambda x: x.convert_to(target_units, unit_system))
|
| 120 |
+
|
| 121 |
+
def get_total_scale_factor(expr):
|
| 122 |
+
if isinstance(expr, Mul):
|
| 123 |
+
return reduce(lambda x, y: x * y,
|
| 124 |
+
[get_total_scale_factor(i) for i in expr.args])
|
| 125 |
+
elif isinstance(expr, Pow):
|
| 126 |
+
return get_total_scale_factor(expr.base) ** expr.exp
|
| 127 |
+
elif isinstance(expr, Quantity):
|
| 128 |
+
return unit_system.get_quantity_scale_factor(expr)
|
| 129 |
+
return expr
|
| 130 |
+
|
| 131 |
+
depmat = _get_conversion_matrix_for_expr(expr, target_units, unit_system)
|
| 132 |
+
if depmat is None:
|
| 133 |
+
return expr
|
| 134 |
+
|
| 135 |
+
expr_scale_factor = get_total_scale_factor(expr)
|
| 136 |
+
return expr_scale_factor * Mul.fromiter(
|
| 137 |
+
(1/get_total_scale_factor(u)*u)**p for u, p in
|
| 138 |
+
zip(target_units, depmat))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def quantity_simplify(expr, across_dimensions: bool=False, unit_system=None):
|
| 142 |
+
"""Return an equivalent expression in which prefixes are replaced
|
| 143 |
+
with numerical values and all units of a given dimension are the
|
| 144 |
+
unified in a canonical manner by default. `across_dimensions` allows
|
| 145 |
+
for units of different dimensions to be simplified together.
|
| 146 |
+
|
| 147 |
+
`unit_system` must be specified if `across_dimensions` is True.
|
| 148 |
+
|
| 149 |
+
Examples
|
| 150 |
+
========
|
| 151 |
+
|
| 152 |
+
>>> from sympy.physics.units.util import quantity_simplify
|
| 153 |
+
>>> from sympy.physics.units.prefixes import kilo
|
| 154 |
+
>>> from sympy.physics.units import foot, inch, joule, coulomb
|
| 155 |
+
>>> quantity_simplify(kilo*foot*inch)
|
| 156 |
+
250*foot**2/3
|
| 157 |
+
>>> quantity_simplify(foot - 6*inch)
|
| 158 |
+
foot/2
|
| 159 |
+
>>> quantity_simplify(5*joule/coulomb, across_dimensions=True, unit_system="SI")
|
| 160 |
+
5*volt
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
if expr.is_Atom or not expr.has(Prefix, Quantity):
|
| 164 |
+
return expr
|
| 165 |
+
|
| 166 |
+
# replace all prefixes with numerical values
|
| 167 |
+
p = expr.atoms(Prefix)
|
| 168 |
+
expr = expr.xreplace({p: p.scale_factor for p in p})
|
| 169 |
+
|
| 170 |
+
# replace all quantities of given dimension with a canonical
|
| 171 |
+
# quantity, chosen from those in the expression
|
| 172 |
+
d = sift(expr.atoms(Quantity), lambda i: i.dimension)
|
| 173 |
+
for k in d:
|
| 174 |
+
if len(d[k]) == 1:
|
| 175 |
+
continue
|
| 176 |
+
v = list(ordered(d[k]))
|
| 177 |
+
ref = v[0]/v[0].scale_factor
|
| 178 |
+
expr = expr.xreplace({vi: ref*vi.scale_factor for vi in v[1:]})
|
| 179 |
+
|
| 180 |
+
if across_dimensions:
|
| 181 |
+
# combine quantities of different dimensions into a single
|
| 182 |
+
# quantity that is equivalent to the original expression
|
| 183 |
+
|
| 184 |
+
if unit_system is None:
|
| 185 |
+
raise ValueError("unit_system must be specified if across_dimensions is True")
|
| 186 |
+
|
| 187 |
+
unit_system = UnitSystem.get_unit_system(unit_system)
|
| 188 |
+
dimension_system: DimensionSystem = unit_system.get_dimension_system()
|
| 189 |
+
dim_expr = unit_system.get_dimensional_expr(expr)
|
| 190 |
+
dim_deps = dimension_system.get_dimensional_dependencies(dim_expr, mark_dimensionless=True)
|
| 191 |
+
|
| 192 |
+
target_dimension: Optional[Dimension] = None
|
| 193 |
+
for ds_dim, ds_dim_deps in dimension_system.dimensional_dependencies.items():
|
| 194 |
+
if ds_dim_deps == dim_deps:
|
| 195 |
+
target_dimension = ds_dim
|
| 196 |
+
break
|
| 197 |
+
|
| 198 |
+
if target_dimension is None:
|
| 199 |
+
# if we can't find a target dimension, we can't do anything. unsure how to handle this case.
|
| 200 |
+
return expr
|
| 201 |
+
|
| 202 |
+
target_unit = unit_system.derived_units.get(target_dimension)
|
| 203 |
+
if target_unit:
|
| 204 |
+
expr = convert_to(expr, target_unit, unit_system)
|
| 205 |
+
|
| 206 |
+
return expr
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def check_dimensions(expr, unit_system="SI"):
|
| 210 |
+
"""Return expr if units in addends have the same
|
| 211 |
+
base dimensions, else raise a ValueError."""
|
| 212 |
+
# the case of adding a number to a dimensional quantity
|
| 213 |
+
# is ignored for the sake of SymPy core routines, so this
|
| 214 |
+
# function will raise an error now if such an addend is
|
| 215 |
+
# found.
|
| 216 |
+
# Also, when doing substitutions, multiplicative constants
|
| 217 |
+
# might be introduced, so remove those now
|
| 218 |
+
|
| 219 |
+
from sympy.physics.units import UnitSystem
|
| 220 |
+
unit_system = UnitSystem.get_unit_system(unit_system)
|
| 221 |
+
|
| 222 |
+
def addDict(dict1, dict2):
|
| 223 |
+
"""Merge dictionaries by adding values of common keys and
|
| 224 |
+
removing keys with value of 0."""
|
| 225 |
+
dict3 = {**dict1, **dict2}
|
| 226 |
+
for key, value in dict3.items():
|
| 227 |
+
if key in dict1 and key in dict2:
|
| 228 |
+
dict3[key] = value + dict1[key]
|
| 229 |
+
return {key:val for key, val in dict3.items() if val != 0}
|
| 230 |
+
|
| 231 |
+
adds = expr.atoms(Add)
|
| 232 |
+
DIM_OF = unit_system.get_dimension_system().get_dimensional_dependencies
|
| 233 |
+
for a in adds:
|
| 234 |
+
deset = set()
|
| 235 |
+
for ai in a.args:
|
| 236 |
+
if ai.is_number:
|
| 237 |
+
deset.add(())
|
| 238 |
+
continue
|
| 239 |
+
dims = []
|
| 240 |
+
skip = False
|
| 241 |
+
dimdict = {}
|
| 242 |
+
for i in Mul.make_args(ai):
|
| 243 |
+
if i.has(Quantity):
|
| 244 |
+
i = Dimension(unit_system.get_dimensional_expr(i))
|
| 245 |
+
if i.has(Dimension):
|
| 246 |
+
dimdict = addDict(dimdict, DIM_OF(i))
|
| 247 |
+
elif i.free_symbols:
|
| 248 |
+
skip = True
|
| 249 |
+
break
|
| 250 |
+
dims.extend(dimdict.items())
|
| 251 |
+
if not skip:
|
| 252 |
+
deset.add(tuple(sorted(dims, key=default_sort_key)))
|
| 253 |
+
if len(deset) > 1:
|
| 254 |
+
raise ValueError(
|
| 255 |
+
"addends have incompatible dimensions: {}".format(deset))
|
| 256 |
+
|
| 257 |
+
# clear multiplicative constants on Dimensions which may be
|
| 258 |
+
# left after substitution
|
| 259 |
+
reps = {}
|
| 260 |
+
for m in expr.atoms(Mul):
|
| 261 |
+
if any(isinstance(i, Dimension) for i in m.args):
|
| 262 |
+
reps[m] = m.func(*[
|
| 263 |
+
i for i in m.args if not i.is_number])
|
| 264 |
+
|
| 265 |
+
return expr.xreplace(reps)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/wigner.py
ADDED
|
@@ -0,0 +1,1191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
r"""
|
| 3 |
+
Wigner, Clebsch-Gordan, Racah, and Gaunt coefficients
|
| 4 |
+
|
| 5 |
+
Collection of functions for calculating Wigner 3j, 6j, 9j,
|
| 6 |
+
Clebsch-Gordan, Racah as well as Gaunt coefficients exactly, all
|
| 7 |
+
evaluating to a rational number times the square root of a rational
|
| 8 |
+
number [Rasch03]_.
|
| 9 |
+
|
| 10 |
+
Please see the description of the individual functions for further
|
| 11 |
+
details and examples.
|
| 12 |
+
|
| 13 |
+
References
|
| 14 |
+
==========
|
| 15 |
+
|
| 16 |
+
.. [Regge58] 'Symmetry Properties of Clebsch-Gordan Coefficients',
|
| 17 |
+
T. Regge, Nuovo Cimento, Volume 10, pp. 544 (1958)
|
| 18 |
+
.. [Regge59] 'Symmetry Properties of Racah Coefficients',
|
| 19 |
+
T. Regge, Nuovo Cimento, Volume 11, pp. 116 (1959)
|
| 20 |
+
.. [Edmonds74] A. R. Edmonds. Angular momentum in quantum mechanics.
|
| 21 |
+
Investigations in physics, 4.; Investigations in physics, no. 4.
|
| 22 |
+
Princeton, N.J., Princeton University Press, 1957.
|
| 23 |
+
.. [Rasch03] J. Rasch and A. C. H. Yu, 'Efficient Storage Scheme for
|
| 24 |
+
Pre-calculated Wigner 3j, 6j and Gaunt Coefficients', SIAM
|
| 25 |
+
J. Sci. Comput. Volume 25, Issue 4, pp. 1416-1428 (2003)
|
| 26 |
+
.. [Liberatodebrito82] 'FORTRAN program for the integral of three
|
| 27 |
+
spherical harmonics', A. Liberato de Brito,
|
| 28 |
+
Comput. Phys. Commun., Volume 25, pp. 81-85 (1982)
|
| 29 |
+
.. [Homeier96] 'Some Properties of the Coupling Coefficients of Real
|
| 30 |
+
Spherical Harmonics and Their Relation to Gaunt Coefficients',
|
| 31 |
+
H. H. H. Homeier and E. O. Steinborn J. Mol. Struct., Volume 368,
|
| 32 |
+
pp. 31-37 (1996)
|
| 33 |
+
|
| 34 |
+
Credits and Copyright
|
| 35 |
+
=====================
|
| 36 |
+
|
| 37 |
+
This code was taken from Sage with the permission of all authors:
|
| 38 |
+
|
| 39 |
+
https://groups.google.com/forum/#!topic/sage-devel/M4NZdu-7O38
|
| 40 |
+
|
| 41 |
+
Authors
|
| 42 |
+
=======
|
| 43 |
+
|
| 44 |
+
- Jens Rasch (2009-03-24): initial version for Sage
|
| 45 |
+
|
| 46 |
+
- Jens Rasch (2009-05-31): updated to sage-4.0
|
| 47 |
+
|
| 48 |
+
- Oscar Gerardo Lazo Arjona (2017-06-18): added Wigner D matrices
|
| 49 |
+
|
| 50 |
+
- Phil Adam LeMaitre (2022-09-19): added real Gaunt coefficient
|
| 51 |
+
|
| 52 |
+
Copyright (C) 2008 Jens Rasch <jyr2000@gmail.com>
|
| 53 |
+
|
| 54 |
+
"""
|
| 55 |
+
from sympy.concrete.summations import Sum
|
| 56 |
+
from sympy.core.add import Add
|
| 57 |
+
from sympy.core.numbers import int_valued
|
| 58 |
+
from sympy.core.function import Function
|
| 59 |
+
from sympy.core.numbers import (Float, I, Integer, pi, Rational)
|
| 60 |
+
from sympy.core.singleton import S
|
| 61 |
+
from sympy.core.symbol import Dummy
|
| 62 |
+
from sympy.core.sympify import sympify
|
| 63 |
+
from sympy.functions.combinatorial.factorials import (binomial, factorial)
|
| 64 |
+
from sympy.functions.elementary.complexes import re
|
| 65 |
+
from sympy.functions.elementary.exponential import exp
|
| 66 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 67 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 68 |
+
from sympy.functions.special.spherical_harmonics import Ynm
|
| 69 |
+
from sympy.matrices.dense import zeros
|
| 70 |
+
from sympy.matrices.immutable import ImmutableMatrix
|
| 71 |
+
from sympy.utilities.misc import as_int
|
| 72 |
+
|
| 73 |
+
# This list of precomputed factorials is needed to massively
|
| 74 |
+
# accelerate future calculations of the various coefficients
|
| 75 |
+
_Factlist = [1]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _calc_factlist(nn):
|
| 79 |
+
r"""
|
| 80 |
+
Function calculates a list of precomputed factorials in order to
|
| 81 |
+
massively accelerate future calculations of the various
|
| 82 |
+
coefficients.
|
| 83 |
+
|
| 84 |
+
Parameters
|
| 85 |
+
==========
|
| 86 |
+
|
| 87 |
+
nn : integer
|
| 88 |
+
Highest factorial to be computed.
|
| 89 |
+
|
| 90 |
+
Returns
|
| 91 |
+
=======
|
| 92 |
+
|
| 93 |
+
list of integers :
|
| 94 |
+
The list of precomputed factorials.
|
| 95 |
+
|
| 96 |
+
Examples
|
| 97 |
+
========
|
| 98 |
+
|
| 99 |
+
Calculate list of factorials::
|
| 100 |
+
|
| 101 |
+
sage: from sage.functions.wigner import _calc_factlist
|
| 102 |
+
sage: _calc_factlist(10)
|
| 103 |
+
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
|
| 104 |
+
"""
|
| 105 |
+
if nn >= len(_Factlist):
|
| 106 |
+
for ii in range(len(_Factlist), int(nn + 1)):
|
| 107 |
+
_Factlist.append(_Factlist[ii - 1] * ii)
|
| 108 |
+
return _Factlist[:int(nn) + 1]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _int_or_halfint(value):
|
| 112 |
+
"""return Python int unless value is half-int (then return float)"""
|
| 113 |
+
if isinstance(value, int):
|
| 114 |
+
return value
|
| 115 |
+
elif type(value) is float:
|
| 116 |
+
if value.is_integer():
|
| 117 |
+
return int(value) # an int
|
| 118 |
+
if (2*value).is_integer():
|
| 119 |
+
return value # a float
|
| 120 |
+
elif isinstance(value, Rational):
|
| 121 |
+
if value.q == 2:
|
| 122 |
+
return value.p/value.q # a float
|
| 123 |
+
elif value.q == 1:
|
| 124 |
+
return value.p # an int
|
| 125 |
+
elif isinstance(value, Float):
|
| 126 |
+
return _int_or_halfint(float(value))
|
| 127 |
+
raise ValueError("expecting integer or half-integer, got %s" % value)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def wigner_3j(j_1, j_2, j_3, m_1, m_2, m_3):
|
| 131 |
+
r"""
|
| 132 |
+
Calculate the Wigner 3j symbol `\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)`.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
==========
|
| 136 |
+
|
| 137 |
+
j_1, j_2, j_3, m_1, m_2, m_3 :
|
| 138 |
+
Integer or half integer.
|
| 139 |
+
|
| 140 |
+
Returns
|
| 141 |
+
=======
|
| 142 |
+
|
| 143 |
+
Rational number times the square root of a rational number.
|
| 144 |
+
|
| 145 |
+
Examples
|
| 146 |
+
========
|
| 147 |
+
|
| 148 |
+
>>> from sympy.physics.wigner import wigner_3j
|
| 149 |
+
>>> wigner_3j(2, 6, 4, 0, 0, 0)
|
| 150 |
+
sqrt(715)/143
|
| 151 |
+
>>> wigner_3j(2, 6, 4, 0, 0, 1)
|
| 152 |
+
0
|
| 153 |
+
|
| 154 |
+
It is an error to have arguments that are not integer or half
|
| 155 |
+
integer values::
|
| 156 |
+
|
| 157 |
+
sage: wigner_3j(2.1, 6, 4, 0, 0, 0)
|
| 158 |
+
Traceback (most recent call last):
|
| 159 |
+
...
|
| 160 |
+
ValueError: j values must be integer or half integer
|
| 161 |
+
sage: wigner_3j(2, 6, 4, 1, 0, -1.1)
|
| 162 |
+
Traceback (most recent call last):
|
| 163 |
+
...
|
| 164 |
+
ValueError: m values must be integer or half integer
|
| 165 |
+
|
| 166 |
+
Notes
|
| 167 |
+
=====
|
| 168 |
+
|
| 169 |
+
The Wigner 3j symbol obeys the following symmetry rules:
|
| 170 |
+
|
| 171 |
+
- invariant under any permutation of the columns (with the
|
| 172 |
+
exception of a sign change where `J:=j_1+j_2+j_3`):
|
| 173 |
+
|
| 174 |
+
.. math::
|
| 175 |
+
|
| 176 |
+
\begin{aligned}
|
| 177 |
+
\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)
|
| 178 |
+
&=\operatorname{Wigner3j}(j_3,j_1,j_2,m_3,m_1,m_2) \\
|
| 179 |
+
&=\operatorname{Wigner3j}(j_2,j_3,j_1,m_2,m_3,m_1) \\
|
| 180 |
+
&=(-1)^J \operatorname{Wigner3j}(j_3,j_2,j_1,m_3,m_2,m_1) \\
|
| 181 |
+
&=(-1)^J \operatorname{Wigner3j}(j_1,j_3,j_2,m_1,m_3,m_2) \\
|
| 182 |
+
&=(-1)^J \operatorname{Wigner3j}(j_2,j_1,j_3,m_2,m_1,m_3)
|
| 183 |
+
\end{aligned}
|
| 184 |
+
|
| 185 |
+
- invariant under space inflection, i.e.
|
| 186 |
+
|
| 187 |
+
.. math::
|
| 188 |
+
|
| 189 |
+
\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)
|
| 190 |
+
=(-1)^J \operatorname{Wigner3j}(j_1,j_2,j_3,-m_1,-m_2,-m_3)
|
| 191 |
+
|
| 192 |
+
- symmetric with respect to the 72 additional symmetries based on
|
| 193 |
+
the work by [Regge58]_
|
| 194 |
+
|
| 195 |
+
- zero for `j_1`, `j_2`, `j_3` not fulfilling triangle relation
|
| 196 |
+
|
| 197 |
+
- zero for `m_1 + m_2 + m_3 \neq 0`
|
| 198 |
+
|
| 199 |
+
- zero for violating any one of the conditions
|
| 200 |
+
`m_1 \in \{-|j_1|, \ldots, |j_1|\}`,
|
| 201 |
+
`m_2 \in \{-|j_2|, \ldots, |j_2|\}`,
|
| 202 |
+
`m_3 \in \{-|j_3|, \ldots, |j_3|\}`
|
| 203 |
+
|
| 204 |
+
Algorithm
|
| 205 |
+
=========
|
| 206 |
+
|
| 207 |
+
This function uses the algorithm of [Edmonds74]_ to calculate the
|
| 208 |
+
value of the 3j symbol exactly. Note that the formula contains
|
| 209 |
+
alternating sums over large factorials and is therefore unsuitable
|
| 210 |
+
for finite precision arithmetic and only useful for a computer
|
| 211 |
+
algebra system [Rasch03]_.
|
| 212 |
+
|
| 213 |
+
Authors
|
| 214 |
+
=======
|
| 215 |
+
|
| 216 |
+
- Jens Rasch (2009-03-24): initial version
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
j_1, j_2, j_3, m_1, m_2, m_3 = map(_int_or_halfint,
|
| 220 |
+
[j_1, j_2, j_3, m_1, m_2, m_3])
|
| 221 |
+
|
| 222 |
+
if m_1 + m_2 + m_3 != 0:
|
| 223 |
+
return S.Zero
|
| 224 |
+
a1 = j_1 + j_2 - j_3
|
| 225 |
+
if a1 < 0:
|
| 226 |
+
return S.Zero
|
| 227 |
+
a2 = j_1 - j_2 + j_3
|
| 228 |
+
if a2 < 0:
|
| 229 |
+
return S.Zero
|
| 230 |
+
a3 = -j_1 + j_2 + j_3
|
| 231 |
+
if a3 < 0:
|
| 232 |
+
return S.Zero
|
| 233 |
+
if (abs(m_1) > j_1) or (abs(m_2) > j_2) or (abs(m_3) > j_3):
|
| 234 |
+
return S.Zero
|
| 235 |
+
if not (int_valued(j_1 - m_1) and \
|
| 236 |
+
int_valued(j_2 - m_2) and \
|
| 237 |
+
int_valued(j_3 - m_3)):
|
| 238 |
+
return S.Zero
|
| 239 |
+
|
| 240 |
+
maxfact = max(j_1 + j_2 + j_3 + 1, j_1 + abs(m_1), j_2 + abs(m_2),
|
| 241 |
+
j_3 + abs(m_3))
|
| 242 |
+
_calc_factlist(int(maxfact))
|
| 243 |
+
|
| 244 |
+
argsqrt = Integer(_Factlist[int(j_1 + j_2 - j_3)] *
|
| 245 |
+
_Factlist[int(j_1 - j_2 + j_3)] *
|
| 246 |
+
_Factlist[int(-j_1 + j_2 + j_3)] *
|
| 247 |
+
_Factlist[int(j_1 - m_1)] *
|
| 248 |
+
_Factlist[int(j_1 + m_1)] *
|
| 249 |
+
_Factlist[int(j_2 - m_2)] *
|
| 250 |
+
_Factlist[int(j_2 + m_2)] *
|
| 251 |
+
_Factlist[int(j_3 - m_3)] *
|
| 252 |
+
_Factlist[int(j_3 + m_3)]) / \
|
| 253 |
+
_Factlist[int(j_1 + j_2 + j_3 + 1)]
|
| 254 |
+
|
| 255 |
+
ressqrt = sqrt(argsqrt)
|
| 256 |
+
if ressqrt.is_complex or ressqrt.is_infinite:
|
| 257 |
+
ressqrt = ressqrt.as_real_imag()[0]
|
| 258 |
+
|
| 259 |
+
imin = max(-j_3 + j_1 + m_2, -j_3 + j_2 - m_1, 0)
|
| 260 |
+
imax = min(j_2 + m_2, j_1 - m_1, j_1 + j_2 - j_3)
|
| 261 |
+
sumres = 0
|
| 262 |
+
for ii in range(int(imin), int(imax) + 1):
|
| 263 |
+
den = _Factlist[ii] * \
|
| 264 |
+
_Factlist[int(ii + j_3 - j_1 - m_2)] * \
|
| 265 |
+
_Factlist[int(j_2 + m_2 - ii)] * \
|
| 266 |
+
_Factlist[int(j_1 - ii - m_1)] * \
|
| 267 |
+
_Factlist[int(ii + j_3 - j_2 + m_1)] * \
|
| 268 |
+
_Factlist[int(j_1 + j_2 - j_3 - ii)]
|
| 269 |
+
sumres = sumres + Integer((-1) ** ii) / den
|
| 270 |
+
|
| 271 |
+
prefid = Integer((-1) ** int(j_1 - j_2 - m_3))
|
| 272 |
+
res = ressqrt * sumres * prefid
|
| 273 |
+
return res
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def clebsch_gordan(j_1, j_2, j_3, m_1, m_2, m_3):
|
| 277 |
+
r"""
|
| 278 |
+
Calculates the Clebsch-Gordan coefficient.
|
| 279 |
+
`\left\langle j_1 m_1 \; j_2 m_2 | j_3 m_3 \right\rangle`.
|
| 280 |
+
|
| 281 |
+
The reference for this function is [Edmonds74]_.
|
| 282 |
+
|
| 283 |
+
Parameters
|
| 284 |
+
==========
|
| 285 |
+
|
| 286 |
+
j_1, j_2, j_3, m_1, m_2, m_3 :
|
| 287 |
+
Integer or half integer.
|
| 288 |
+
|
| 289 |
+
Returns
|
| 290 |
+
=======
|
| 291 |
+
|
| 292 |
+
Rational number times the square root of a rational number.
|
| 293 |
+
|
| 294 |
+
Examples
|
| 295 |
+
========
|
| 296 |
+
|
| 297 |
+
>>> from sympy import S
|
| 298 |
+
>>> from sympy.physics.wigner import clebsch_gordan
|
| 299 |
+
>>> clebsch_gordan(S(3)/2, S(1)/2, 2, S(3)/2, S(1)/2, 2)
|
| 300 |
+
1
|
| 301 |
+
>>> clebsch_gordan(S(3)/2, S(1)/2, 1, S(3)/2, -S(1)/2, 1)
|
| 302 |
+
sqrt(3)/2
|
| 303 |
+
>>> clebsch_gordan(S(3)/2, S(1)/2, 1, -S(1)/2, S(1)/2, 0)
|
| 304 |
+
-sqrt(2)/2
|
| 305 |
+
|
| 306 |
+
Notes
|
| 307 |
+
=====
|
| 308 |
+
|
| 309 |
+
The Clebsch-Gordan coefficient will be evaluated via its relation
|
| 310 |
+
to Wigner 3j symbols:
|
| 311 |
+
|
| 312 |
+
.. math::
|
| 313 |
+
|
| 314 |
+
\left\langle j_1 m_1 \; j_2 m_2 | j_3 m_3 \right\rangle
|
| 315 |
+
=(-1)^{j_1-j_2+m_3} \sqrt{2j_3+1}
|
| 316 |
+
\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,-m_3)
|
| 317 |
+
|
| 318 |
+
See also the documentation on Wigner 3j symbols which exhibit much
|
| 319 |
+
higher symmetry relations than the Clebsch-Gordan coefficient.
|
| 320 |
+
|
| 321 |
+
Authors
|
| 322 |
+
=======
|
| 323 |
+
|
| 324 |
+
- Jens Rasch (2009-03-24): initial version
|
| 325 |
+
"""
|
| 326 |
+
j_1 = sympify(j_1)
|
| 327 |
+
j_2 = sympify(j_2)
|
| 328 |
+
j_3 = sympify(j_3)
|
| 329 |
+
m_1 = sympify(m_1)
|
| 330 |
+
m_2 = sympify(m_2)
|
| 331 |
+
m_3 = sympify(m_3)
|
| 332 |
+
|
| 333 |
+
w = wigner_3j(j_1, j_2, j_3, m_1, m_2, -m_3)
|
| 334 |
+
|
| 335 |
+
return (-1) ** (j_1 - j_2 + m_3) * sqrt(2 * j_3 + 1) * w
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _big_delta_coeff(aa, bb, cc, prec=None):
|
| 339 |
+
r"""
|
| 340 |
+
Calculates the Delta coefficient of the 3 angular momenta for
|
| 341 |
+
Racah symbols. Also checks that the differences are of integer
|
| 342 |
+
value.
|
| 343 |
+
|
| 344 |
+
Parameters
|
| 345 |
+
==========
|
| 346 |
+
|
| 347 |
+
aa :
|
| 348 |
+
First angular momentum, integer or half integer.
|
| 349 |
+
bb :
|
| 350 |
+
Second angular momentum, integer or half integer.
|
| 351 |
+
cc :
|
| 352 |
+
Third angular momentum, integer or half integer.
|
| 353 |
+
prec :
|
| 354 |
+
Precision of the ``sqrt()`` calculation.
|
| 355 |
+
|
| 356 |
+
Returns
|
| 357 |
+
=======
|
| 358 |
+
|
| 359 |
+
double : Value of the Delta coefficient.
|
| 360 |
+
|
| 361 |
+
Examples
|
| 362 |
+
========
|
| 363 |
+
|
| 364 |
+
sage: from sage.functions.wigner import _big_delta_coeff
|
| 365 |
+
sage: _big_delta_coeff(1,1,1)
|
| 366 |
+
1/2*sqrt(1/6)
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
# the triangle test will only pass if a) all 3 values are ints or
|
| 370 |
+
# b) 1 is an int and the other two are half-ints
|
| 371 |
+
if not int_valued(aa + bb - cc):
|
| 372 |
+
raise ValueError("j values must be integer or half integer and fulfill the triangle relation")
|
| 373 |
+
if not int_valued(aa + cc - bb):
|
| 374 |
+
raise ValueError("j values must be integer or half integer and fulfill the triangle relation")
|
| 375 |
+
if not int_valued(bb + cc - aa):
|
| 376 |
+
raise ValueError("j values must be integer or half integer and fulfill the triangle relation")
|
| 377 |
+
if (aa + bb - cc) < 0:
|
| 378 |
+
return S.Zero
|
| 379 |
+
if (aa + cc - bb) < 0:
|
| 380 |
+
return S.Zero
|
| 381 |
+
if (bb + cc - aa) < 0:
|
| 382 |
+
return S.Zero
|
| 383 |
+
|
| 384 |
+
maxfact = max(aa + bb - cc, aa + cc - bb, bb + cc - aa, aa + bb + cc + 1)
|
| 385 |
+
_calc_factlist(maxfact)
|
| 386 |
+
|
| 387 |
+
argsqrt = Integer(_Factlist[int(aa + bb - cc)] *
|
| 388 |
+
_Factlist[int(aa + cc - bb)] *
|
| 389 |
+
_Factlist[int(bb + cc - aa)]) / \
|
| 390 |
+
Integer(_Factlist[int(aa + bb + cc + 1)])
|
| 391 |
+
|
| 392 |
+
ressqrt = sqrt(argsqrt)
|
| 393 |
+
if prec:
|
| 394 |
+
ressqrt = ressqrt.evalf(prec).as_real_imag()[0]
|
| 395 |
+
return ressqrt
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def racah(aa, bb, cc, dd, ee, ff, prec=None):
|
| 399 |
+
r"""
|
| 400 |
+
Calculate the Racah symbol `W(a,b,c,d;e,f)`.
|
| 401 |
+
|
| 402 |
+
Parameters
|
| 403 |
+
==========
|
| 404 |
+
|
| 405 |
+
a, ..., f :
|
| 406 |
+
Integer or half integer.
|
| 407 |
+
prec :
|
| 408 |
+
Precision, default: ``None``. Providing a precision can
|
| 409 |
+
drastically speed up the calculation.
|
| 410 |
+
|
| 411 |
+
Returns
|
| 412 |
+
=======
|
| 413 |
+
|
| 414 |
+
Rational number times the square root of a rational number
|
| 415 |
+
(if ``prec=None``), or real number if a precision is given.
|
| 416 |
+
|
| 417 |
+
Examples
|
| 418 |
+
========
|
| 419 |
+
|
| 420 |
+
>>> from sympy.physics.wigner import racah
|
| 421 |
+
>>> racah(3,3,3,3,3,3)
|
| 422 |
+
-1/14
|
| 423 |
+
|
| 424 |
+
Notes
|
| 425 |
+
=====
|
| 426 |
+
|
| 427 |
+
The Racah symbol is related to the Wigner 6j symbol:
|
| 428 |
+
|
| 429 |
+
.. math::
|
| 430 |
+
|
| 431 |
+
\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
|
| 432 |
+
=(-1)^{j_1+j_2+j_4+j_5} W(j_1,j_2,j_5,j_4,j_3,j_6)
|
| 433 |
+
|
| 434 |
+
Please see the 6j symbol for its much richer symmetries and for
|
| 435 |
+
additional properties.
|
| 436 |
+
|
| 437 |
+
Algorithm
|
| 438 |
+
=========
|
| 439 |
+
|
| 440 |
+
This function uses the algorithm of [Edmonds74]_ to calculate the
|
| 441 |
+
value of the 6j symbol exactly. Note that the formula contains
|
| 442 |
+
alternating sums over large factorials and is therefore unsuitable
|
| 443 |
+
for finite precision arithmetic and only useful for a computer
|
| 444 |
+
algebra system [Rasch03]_.
|
| 445 |
+
|
| 446 |
+
Authors
|
| 447 |
+
=======
|
| 448 |
+
|
| 449 |
+
- Jens Rasch (2009-03-24): initial version
|
| 450 |
+
"""
|
| 451 |
+
prefac = _big_delta_coeff(aa, bb, ee, prec) * \
|
| 452 |
+
_big_delta_coeff(cc, dd, ee, prec) * \
|
| 453 |
+
_big_delta_coeff(aa, cc, ff, prec) * \
|
| 454 |
+
_big_delta_coeff(bb, dd, ff, prec)
|
| 455 |
+
if prefac == 0:
|
| 456 |
+
return S.Zero
|
| 457 |
+
imin = max(aa + bb + ee, cc + dd + ee, aa + cc + ff, bb + dd + ff)
|
| 458 |
+
imax = min(aa + bb + cc + dd, aa + dd + ee + ff, bb + cc + ee + ff)
|
| 459 |
+
|
| 460 |
+
maxfact = max(imax + 1, aa + bb + cc + dd, aa + dd + ee + ff,
|
| 461 |
+
bb + cc + ee + ff)
|
| 462 |
+
_calc_factlist(maxfact)
|
| 463 |
+
|
| 464 |
+
sumres = 0
|
| 465 |
+
for kk in range(int(imin), int(imax) + 1):
|
| 466 |
+
den = _Factlist[int(kk - aa - bb - ee)] * \
|
| 467 |
+
_Factlist[int(kk - cc - dd - ee)] * \
|
| 468 |
+
_Factlist[int(kk - aa - cc - ff)] * \
|
| 469 |
+
_Factlist[int(kk - bb - dd - ff)] * \
|
| 470 |
+
_Factlist[int(aa + bb + cc + dd - kk)] * \
|
| 471 |
+
_Factlist[int(aa + dd + ee + ff - kk)] * \
|
| 472 |
+
_Factlist[int(bb + cc + ee + ff - kk)]
|
| 473 |
+
sumres = sumres + Integer((-1) ** kk * _Factlist[kk + 1]) / den
|
| 474 |
+
|
| 475 |
+
res = prefac * sumres * (-1) ** int(aa + bb + cc + dd)
|
| 476 |
+
return res
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def wigner_6j(j_1, j_2, j_3, j_4, j_5, j_6, prec=None):
|
| 480 |
+
r"""
|
| 481 |
+
Calculate the Wigner 6j symbol `\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)`.
|
| 482 |
+
|
| 483 |
+
Parameters
|
| 484 |
+
==========
|
| 485 |
+
|
| 486 |
+
j_1, ..., j_6 :
|
| 487 |
+
Integer or half integer.
|
| 488 |
+
prec :
|
| 489 |
+
Precision, default: ``None``. Providing a precision can
|
| 490 |
+
drastically speed up the calculation.
|
| 491 |
+
|
| 492 |
+
Returns
|
| 493 |
+
=======
|
| 494 |
+
|
| 495 |
+
Rational number times the square root of a rational number
|
| 496 |
+
(if ``prec=None``), or real number if a precision is given.
|
| 497 |
+
|
| 498 |
+
Examples
|
| 499 |
+
========
|
| 500 |
+
|
| 501 |
+
>>> from sympy.physics.wigner import wigner_6j
|
| 502 |
+
>>> wigner_6j(3,3,3,3,3,3)
|
| 503 |
+
-1/14
|
| 504 |
+
>>> wigner_6j(5,5,5,5,5,5)
|
| 505 |
+
1/52
|
| 506 |
+
|
| 507 |
+
It is an error to have arguments that are not integer or half
|
| 508 |
+
integer values or do not fulfill the triangle relation::
|
| 509 |
+
|
| 510 |
+
sage: wigner_6j(2.5,2.5,2.5,2.5,2.5,2.5)
|
| 511 |
+
Traceback (most recent call last):
|
| 512 |
+
...
|
| 513 |
+
ValueError: j values must be integer or half integer and fulfill the triangle relation
|
| 514 |
+
sage: wigner_6j(0.5,0.5,1.1,0.5,0.5,1.1)
|
| 515 |
+
Traceback (most recent call last):
|
| 516 |
+
...
|
| 517 |
+
ValueError: j values must be integer or half integer and fulfill the triangle relation
|
| 518 |
+
|
| 519 |
+
Notes
|
| 520 |
+
=====
|
| 521 |
+
|
| 522 |
+
The Wigner 6j symbol is related to the Racah symbol but exhibits
|
| 523 |
+
more symmetries as detailed below.
|
| 524 |
+
|
| 525 |
+
.. math::
|
| 526 |
+
|
| 527 |
+
\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
|
| 528 |
+
=(-1)^{j_1+j_2+j_4+j_5} W(j_1,j_2,j_5,j_4,j_3,j_6)
|
| 529 |
+
|
| 530 |
+
The Wigner 6j symbol obeys the following symmetry rules:
|
| 531 |
+
|
| 532 |
+
- Wigner 6j symbols are left invariant under any permutation of
|
| 533 |
+
the columns:
|
| 534 |
+
|
| 535 |
+
.. math::
|
| 536 |
+
|
| 537 |
+
\begin{aligned}
|
| 538 |
+
\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
|
| 539 |
+
&=\operatorname{Wigner6j}(j_3,j_1,j_2,j_6,j_4,j_5) \\
|
| 540 |
+
&=\operatorname{Wigner6j}(j_2,j_3,j_1,j_5,j_6,j_4) \\
|
| 541 |
+
&=\operatorname{Wigner6j}(j_3,j_2,j_1,j_6,j_5,j_4) \\
|
| 542 |
+
&=\operatorname{Wigner6j}(j_1,j_3,j_2,j_4,j_6,j_5) \\
|
| 543 |
+
&=\operatorname{Wigner6j}(j_2,j_1,j_3,j_5,j_4,j_6)
|
| 544 |
+
\end{aligned}
|
| 545 |
+
|
| 546 |
+
- They are invariant under the exchange of the upper and lower
|
| 547 |
+
arguments in each of any two columns, i.e.
|
| 548 |
+
|
| 549 |
+
.. math::
|
| 550 |
+
|
| 551 |
+
\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
|
| 552 |
+
=\operatorname{Wigner6j}(j_1,j_5,j_6,j_4,j_2,j_3)
|
| 553 |
+
=\operatorname{Wigner6j}(j_4,j_2,j_6,j_1,j_5,j_3)
|
| 554 |
+
=\operatorname{Wigner6j}(j_4,j_5,j_3,j_1,j_2,j_6)
|
| 555 |
+
|
| 556 |
+
- additional 6 symmetries [Regge59]_ giving rise to 144 symmetries
|
| 557 |
+
in total
|
| 558 |
+
|
| 559 |
+
- only non-zero if any triple of `j`'s fulfill a triangle relation
|
| 560 |
+
|
| 561 |
+
Algorithm
|
| 562 |
+
=========
|
| 563 |
+
|
| 564 |
+
This function uses the algorithm of [Edmonds74]_ to calculate the
|
| 565 |
+
value of the 6j symbol exactly. Note that the formula contains
|
| 566 |
+
alternating sums over large factorials and is therefore unsuitable
|
| 567 |
+
for finite precision arithmetic and only useful for a computer
|
| 568 |
+
algebra system [Rasch03]_.
|
| 569 |
+
|
| 570 |
+
"""
|
| 571 |
+
res = (-1) ** int(j_1 + j_2 + j_4 + j_5) * \
|
| 572 |
+
racah(j_1, j_2, j_5, j_4, j_3, j_6, prec)
|
| 573 |
+
return res
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def wigner_9j(j_1, j_2, j_3, j_4, j_5, j_6, j_7, j_8, j_9, prec=None):
|
| 577 |
+
r"""
|
| 578 |
+
Calculate the Wigner 9j symbol
|
| 579 |
+
`\operatorname{Wigner9j}(j_1,j_2,j_3,j_4,j_5,j_6,j_7,j_8,j_9)`.
|
| 580 |
+
|
| 581 |
+
Parameters
|
| 582 |
+
==========
|
| 583 |
+
|
| 584 |
+
j_1, ..., j_9 :
|
| 585 |
+
Integer or half integer.
|
| 586 |
+
prec : precision, default
|
| 587 |
+
``None``. Providing a precision can
|
| 588 |
+
drastically speed up the calculation.
|
| 589 |
+
|
| 590 |
+
Returns
|
| 591 |
+
=======
|
| 592 |
+
|
| 593 |
+
Rational number times the square root of a rational number
|
| 594 |
+
(if ``prec=None``), or real number if a precision is given.
|
| 595 |
+
|
| 596 |
+
Examples
|
| 597 |
+
========
|
| 598 |
+
|
| 599 |
+
>>> from sympy.physics.wigner import wigner_9j
|
| 600 |
+
>>> wigner_9j(1,1,1, 1,1,1, 1,1,0, prec=64)
|
| 601 |
+
0.05555555555555555555555555555555555555555555555555555555555555555
|
| 602 |
+
|
| 603 |
+
>>> wigner_9j(1/2,1/2,0, 1/2,3/2,1, 0,1,1, prec=64)
|
| 604 |
+
0.1666666666666666666666666666666666666666666666666666666666666667
|
| 605 |
+
|
| 606 |
+
It is an error to have arguments that are not integer or half
|
| 607 |
+
integer values or do not fulfill the triangle relation::
|
| 608 |
+
|
| 609 |
+
sage: wigner_9j(0.5,0.5,0.5, 0.5,0.5,0.5, 0.5,0.5,0.5,prec=64)
|
| 610 |
+
Traceback (most recent call last):
|
| 611 |
+
...
|
| 612 |
+
ValueError: j values must be integer or half integer and fulfill the triangle relation
|
| 613 |
+
sage: wigner_9j(1,1,1, 0.5,1,1.5, 0.5,1,2.5,prec=64)
|
| 614 |
+
Traceback (most recent call last):
|
| 615 |
+
...
|
| 616 |
+
ValueError: j values must be integer or half integer and fulfill the triangle relation
|
| 617 |
+
|
| 618 |
+
Algorithm
|
| 619 |
+
=========
|
| 620 |
+
|
| 621 |
+
This function uses the algorithm of [Edmonds74]_ to calculate the
|
| 622 |
+
value of the 3j symbol exactly. Note that the formula contains
|
| 623 |
+
alternating sums over large factorials and is therefore unsuitable
|
| 624 |
+
for finite precision arithmetic and only useful for a computer
|
| 625 |
+
algebra system [Rasch03]_.
|
| 626 |
+
"""
|
| 627 |
+
imax = int(min(j_1 + j_9, j_2 + j_6, j_4 + j_8) * 2)
|
| 628 |
+
imin = imax % 2
|
| 629 |
+
sumres = 0
|
| 630 |
+
for kk in range(imin, int(imax) + 1, 2):
|
| 631 |
+
sumres = sumres + (kk + 1) * \
|
| 632 |
+
racah(j_1, j_2, j_9, j_6, j_3, kk / 2, prec) * \
|
| 633 |
+
racah(j_4, j_6, j_8, j_2, j_5, kk / 2, prec) * \
|
| 634 |
+
racah(j_1, j_4, j_9, j_8, j_7, kk / 2, prec)
|
| 635 |
+
return sumres
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None):
|
| 639 |
+
r"""
|
| 640 |
+
Calculate the Gaunt coefficient.
|
| 641 |
+
|
| 642 |
+
Explanation
|
| 643 |
+
===========
|
| 644 |
+
|
| 645 |
+
The Gaunt coefficient is defined as the integral over three
|
| 646 |
+
spherical harmonics:
|
| 647 |
+
|
| 648 |
+
.. math::
|
| 649 |
+
|
| 650 |
+
\begin{aligned}
|
| 651 |
+
\operatorname{Gaunt}(l_1,l_2,l_3,m_1,m_2,m_3)
|
| 652 |
+
&=\int Y_{l_1,m_1}(\Omega)
|
| 653 |
+
Y_{l_2,m_2}(\Omega) Y_{l_3,m_3}(\Omega) \,d\Omega \\
|
| 654 |
+
&=\sqrt{\frac{(2l_1+1)(2l_2+1)(2l_3+1)}{4\pi}}
|
| 655 |
+
\operatorname{Wigner3j}(l_1,l_2,l_3,0,0,0)
|
| 656 |
+
\operatorname{Wigner3j}(l_1,l_2,l_3,m_1,m_2,m_3)
|
| 657 |
+
\end{aligned}
|
| 658 |
+
|
| 659 |
+
Parameters
|
| 660 |
+
==========
|
| 661 |
+
|
| 662 |
+
l_1, l_2, l_3, m_1, m_2, m_3 :
|
| 663 |
+
Integer.
|
| 664 |
+
prec - precision, default: ``None``.
|
| 665 |
+
Providing a precision can
|
| 666 |
+
drastically speed up the calculation.
|
| 667 |
+
|
| 668 |
+
Returns
|
| 669 |
+
=======
|
| 670 |
+
|
| 671 |
+
Rational number times the square root of a rational number
|
| 672 |
+
(if ``prec=None``), or real number if a precision is given.
|
| 673 |
+
|
| 674 |
+
Examples
|
| 675 |
+
========
|
| 676 |
+
|
| 677 |
+
>>> from sympy.physics.wigner import gaunt
|
| 678 |
+
>>> gaunt(1,0,1,1,0,-1)
|
| 679 |
+
-1/(2*sqrt(pi))
|
| 680 |
+
>>> gaunt(1000,1000,1200,9,3,-12).n(64)
|
| 681 |
+
0.006895004219221134484332976156744208248842039317638217822322799675
|
| 682 |
+
|
| 683 |
+
It is an error to use non-integer values for `l` and `m`::
|
| 684 |
+
|
| 685 |
+
sage: gaunt(1.2,0,1.2,0,0,0)
|
| 686 |
+
Traceback (most recent call last):
|
| 687 |
+
...
|
| 688 |
+
ValueError: l values must be integer
|
| 689 |
+
sage: gaunt(1,0,1,1.1,0,-1.1)
|
| 690 |
+
Traceback (most recent call last):
|
| 691 |
+
...
|
| 692 |
+
ValueError: m values must be integer
|
| 693 |
+
|
| 694 |
+
Notes
|
| 695 |
+
=====
|
| 696 |
+
|
| 697 |
+
The Gaunt coefficient obeys the following symmetry rules:
|
| 698 |
+
|
| 699 |
+
- invariant under any permutation of the columns
|
| 700 |
+
|
| 701 |
+
.. math::
|
| 702 |
+
\begin{aligned}
|
| 703 |
+
Y(l_1,l_2,l_3,m_1,m_2,m_3)
|
| 704 |
+
&=Y(l_3,l_1,l_2,m_3,m_1,m_2) \\
|
| 705 |
+
&=Y(l_2,l_3,l_1,m_2,m_3,m_1) \\
|
| 706 |
+
&=Y(l_3,l_2,l_1,m_3,m_2,m_1) \\
|
| 707 |
+
&=Y(l_1,l_3,l_2,m_1,m_3,m_2) \\
|
| 708 |
+
&=Y(l_2,l_1,l_3,m_2,m_1,m_3)
|
| 709 |
+
\end{aligned}
|
| 710 |
+
|
| 711 |
+
- invariant under space inflection, i.e.
|
| 712 |
+
|
| 713 |
+
.. math::
|
| 714 |
+
Y(l_1,l_2,l_3,m_1,m_2,m_3)
|
| 715 |
+
=Y(l_1,l_2,l_3,-m_1,-m_2,-m_3)
|
| 716 |
+
|
| 717 |
+
- symmetric with respect to the 72 Regge symmetries as inherited
|
| 718 |
+
for the `3j` symbols [Regge58]_
|
| 719 |
+
|
| 720 |
+
- zero for `l_1`, `l_2`, `l_3` not fulfilling triangle relation
|
| 721 |
+
|
| 722 |
+
- zero for violating any one of the conditions: `l_1 \ge |m_1|`,
|
| 723 |
+
`l_2 \ge |m_2|`, `l_3 \ge |m_3|`
|
| 724 |
+
|
| 725 |
+
- non-zero only for an even sum of the `l_i`, i.e.
|
| 726 |
+
`L = l_1 + l_2 + l_3 = 2n` for `n` in `\mathbb{N}`
|
| 727 |
+
|
| 728 |
+
Algorithms
|
| 729 |
+
==========
|
| 730 |
+
|
| 731 |
+
This function uses the algorithm of [Liberatodebrito82]_ to
|
| 732 |
+
calculate the value of the Gaunt coefficient exactly. Note that
|
| 733 |
+
the formula contains alternating sums over large factorials and is
|
| 734 |
+
therefore unsuitable for finite precision arithmetic and only
|
| 735 |
+
useful for a computer algebra system [Rasch03]_.
|
| 736 |
+
|
| 737 |
+
Authors
|
| 738 |
+
=======
|
| 739 |
+
|
| 740 |
+
Jens Rasch (2009-03-24): initial version for Sage.
|
| 741 |
+
"""
|
| 742 |
+
l_1, l_2, l_3, m_1, m_2, m_3 = [
|
| 743 |
+
as_int(i) for i in (l_1, l_2, l_3, m_1, m_2, m_3)]
|
| 744 |
+
|
| 745 |
+
if l_1 + l_2 - l_3 < 0:
|
| 746 |
+
return S.Zero
|
| 747 |
+
if l_1 - l_2 + l_3 < 0:
|
| 748 |
+
return S.Zero
|
| 749 |
+
if -l_1 + l_2 + l_3 < 0:
|
| 750 |
+
return S.Zero
|
| 751 |
+
if (m_1 + m_2 + m_3) != 0:
|
| 752 |
+
return S.Zero
|
| 753 |
+
if (abs(m_1) > l_1) or (abs(m_2) > l_2) or (abs(m_3) > l_3):
|
| 754 |
+
return S.Zero
|
| 755 |
+
bigL, remL = divmod(l_1 + l_2 + l_3, 2)
|
| 756 |
+
if remL % 2:
|
| 757 |
+
return S.Zero
|
| 758 |
+
|
| 759 |
+
imin = max(-l_3 + l_1 + m_2, -l_3 + l_2 - m_1, 0)
|
| 760 |
+
imax = min(l_2 + m_2, l_1 - m_1, l_1 + l_2 - l_3)
|
| 761 |
+
|
| 762 |
+
_calc_factlist(max(l_1 + l_2 + l_3 + 1, imax + 1))
|
| 763 |
+
|
| 764 |
+
ressqrt = sqrt((2 * l_1 + 1) * (2 * l_2 + 1) * (2 * l_3 + 1) * \
|
| 765 |
+
_Factlist[l_1 - m_1] * _Factlist[l_1 + m_1] * _Factlist[l_2 - m_2] * \
|
| 766 |
+
_Factlist[l_2 + m_2] * _Factlist[l_3 - m_3] * _Factlist[l_3 + m_3] / \
|
| 767 |
+
(4*pi))
|
| 768 |
+
|
| 769 |
+
prefac = Integer(_Factlist[bigL] * _Factlist[l_2 - l_1 + l_3] *
|
| 770 |
+
_Factlist[l_1 - l_2 + l_3] * _Factlist[l_1 + l_2 - l_3])/ \
|
| 771 |
+
_Factlist[2 * bigL + 1]/ \
|
| 772 |
+
(_Factlist[bigL - l_1] *
|
| 773 |
+
_Factlist[bigL - l_2] * _Factlist[bigL - l_3])
|
| 774 |
+
|
| 775 |
+
sumres = 0
|
| 776 |
+
for ii in range(int(imin), int(imax) + 1):
|
| 777 |
+
den = _Factlist[ii] * _Factlist[ii + l_3 - l_1 - m_2] * \
|
| 778 |
+
_Factlist[l_2 + m_2 - ii] * _Factlist[l_1 - ii - m_1] * \
|
| 779 |
+
_Factlist[ii + l_3 - l_2 + m_1] * _Factlist[l_1 + l_2 - l_3 - ii]
|
| 780 |
+
sumres = sumres + Integer((-1) ** ii) / den
|
| 781 |
+
|
| 782 |
+
res = ressqrt * prefac * sumres * Integer((-1) ** (bigL + l_3 + m_1 - m_2))
|
| 783 |
+
if prec is not None:
|
| 784 |
+
res = res.n(prec)
|
| 785 |
+
return res
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def real_gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None):
|
| 789 |
+
r"""
|
| 790 |
+
Calculate the real Gaunt coefficient.
|
| 791 |
+
|
| 792 |
+
Explanation
|
| 793 |
+
===========
|
| 794 |
+
|
| 795 |
+
The real Gaunt coefficient is defined as the integral over three
|
| 796 |
+
real spherical harmonics:
|
| 797 |
+
|
| 798 |
+
.. math::
|
| 799 |
+
\begin{aligned}
|
| 800 |
+
\operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3)
|
| 801 |
+
&=\int Z^{m_1}_{l_1}(\Omega)
|
| 802 |
+
Z^{m_2}_{l_2}(\Omega) Z^{m_3}_{l_3}(\Omega) \,d\Omega \\
|
| 803 |
+
\end{aligned}
|
| 804 |
+
|
| 805 |
+
Alternatively, it can be defined in terms of the standard Gaunt
|
| 806 |
+
coefficient by relating the real spherical harmonics to the standard
|
| 807 |
+
spherical harmonics via a unitary transformation `U`, i.e.
|
| 808 |
+
`Z^{m}_{l}(\Omega)=\sum_{m'}U^{m}_{m'}Y^{m'}_{l}(\Omega)` [Homeier96]_.
|
| 809 |
+
The real Gaunt coefficient is then defined as
|
| 810 |
+
|
| 811 |
+
.. math::
|
| 812 |
+
\begin{aligned}
|
| 813 |
+
\operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3)
|
| 814 |
+
&=\int Z^{m_1}_{l_1}(\Omega)
|
| 815 |
+
Z^{m_2}_{l_2}(\Omega) Z^{m_3}_{l_3}(\Omega) \,d\Omega \\
|
| 816 |
+
&=\sum_{m'_1 m'_2 m'_3} U^{m_1}_{m'_1}U^{m_2}_{m'_2}U^{m_3}_{m'_3}
|
| 817 |
+
\operatorname{Gaunt}(l_1,l_2,l_3,m'_1,m'_2,m'_3)
|
| 818 |
+
\end{aligned}
|
| 819 |
+
|
| 820 |
+
The unitary matrix `U` has components
|
| 821 |
+
|
| 822 |
+
.. math::
|
| 823 |
+
\begin{aligned}
|
| 824 |
+
U^m_{m'} = \delta_{|m||m'|}*(\delta_{m'0}\delta_{m0} + \frac{1}{\sqrt{2}}\big[\Theta(m)
|
| 825 |
+
\big(\delta_{m'm}+(-1)^{m'}\delta_{m'-m}\big)+i\Theta(-m)\big((-1)^{-m}
|
| 826 |
+
\delta_{m'-m}-\delta_{m'm}*(-1)^{m'-m}\big)\big])
|
| 827 |
+
\end{aligned}
|
| 828 |
+
|
| 829 |
+
where `\delta_{ij}` is the Kronecker delta symbol and `\Theta` is a step
|
| 830 |
+
function defined as
|
| 831 |
+
|
| 832 |
+
.. math::
|
| 833 |
+
\begin{aligned}
|
| 834 |
+
\Theta(x) = \begin{cases} 1 \,\text{for}\, x > 0 \\ 0 \,\text{for}\, x \leq 0 \end{cases}
|
| 835 |
+
\end{aligned}
|
| 836 |
+
|
| 837 |
+
Parameters
|
| 838 |
+
==========
|
| 839 |
+
|
| 840 |
+
l_1, l_2, l_3, m_1, m_2, m_3 :
|
| 841 |
+
Integer.
|
| 842 |
+
|
| 843 |
+
prec - precision, default: ``None``.
|
| 844 |
+
Providing a precision can
|
| 845 |
+
drastically speed up the calculation.
|
| 846 |
+
|
| 847 |
+
Returns
|
| 848 |
+
=======
|
| 849 |
+
|
| 850 |
+
Rational number times the square root of a rational number.
|
| 851 |
+
|
| 852 |
+
Examples
|
| 853 |
+
========
|
| 854 |
+
|
| 855 |
+
>>> from sympy.physics.wigner import real_gaunt
|
| 856 |
+
>>> real_gaunt(2,2,4,-1,-1,0)
|
| 857 |
+
-2/(7*sqrt(pi))
|
| 858 |
+
>>> real_gaunt(10,10,20,-9,-9,0).n(64)
|
| 859 |
+
-0.00002480019791932209313156167176797577821140084216297395518482071448
|
| 860 |
+
|
| 861 |
+
It is an error to use non-integer values for `l` and `m`::
|
| 862 |
+
real_gaunt(2.8,0.5,1.3,0,0,0)
|
| 863 |
+
Traceback (most recent call last):
|
| 864 |
+
...
|
| 865 |
+
ValueError: l values must be integer
|
| 866 |
+
real_gaunt(2,2,4,0.7,1,-3.4)
|
| 867 |
+
Traceback (most recent call last):
|
| 868 |
+
...
|
| 869 |
+
ValueError: m values must be integer
|
| 870 |
+
|
| 871 |
+
Notes
|
| 872 |
+
=====
|
| 873 |
+
|
| 874 |
+
The real Gaunt coefficient inherits from the standard Gaunt coefficient,
|
| 875 |
+
the invariance under any permutation of the pairs `(l_i, m_i)` and the
|
| 876 |
+
requirement that the sum of the `l_i` be even to yield a non-zero value.
|
| 877 |
+
It also obeys the following symmetry rules:
|
| 878 |
+
|
| 879 |
+
- zero for `l_1`, `l_2`, `l_3` not fulfiling the condition
|
| 880 |
+
`l_1 \in \{l_{\text{max}}, l_{\text{max}}-2, \ldots, l_{\text{min}}\}`,
|
| 881 |
+
where `l_{\text{max}} = l_2+l_3`,
|
| 882 |
+
|
| 883 |
+
.. math::
|
| 884 |
+
\begin{aligned}
|
| 885 |
+
l_{\text{min}} = \begin{cases} \kappa(l_2, l_3, m_2, m_3) & \text{if}\,
|
| 886 |
+
\kappa(l_2, l_3, m_2, m_3) + l_{\text{max}}\, \text{is even} \\
|
| 887 |
+
\kappa(l_2, l_3, m_2, m_3)+1 & \text{if}\, \kappa(l_2, l_3, m_2, m_3) +
|
| 888 |
+
l_{\text{max}}\, \text{is odd}\end{cases}
|
| 889 |
+
\end{aligned}
|
| 890 |
+
|
| 891 |
+
and `\kappa(l_2, l_3, m_2, m_3) = \max{\big(|l_2-l_3|, \min{\big(|m_2+m_3|,
|
| 892 |
+
|m_2-m_3|\big)}\big)}`
|
| 893 |
+
|
| 894 |
+
- zero for an odd number of negative `m_i`
|
| 895 |
+
|
| 896 |
+
Algorithms
|
| 897 |
+
==========
|
| 898 |
+
|
| 899 |
+
This function uses the algorithms of [Homeier96]_ and [Rasch03]_ to
|
| 900 |
+
calculate the value of the real Gaunt coefficient exactly. Note that
|
| 901 |
+
the formula used in [Rasch03]_ contains alternating sums over large
|
| 902 |
+
factorials and is therefore unsuitable for finite precision arithmetic
|
| 903 |
+
and only useful for a computer algebra system [Rasch03]_. However, this
|
| 904 |
+
function can in principle use any algorithm that computes the Gaunt
|
| 905 |
+
coefficient, so it is suitable for finite precision arithmetic in so far
|
| 906 |
+
as the algorithm which computes the Gaunt coefficient is.
|
| 907 |
+
"""
|
| 908 |
+
l_1, l_2, l_3, m_1, m_2, m_3 = [
|
| 909 |
+
as_int(i) for i in (l_1, l_2, l_3, m_1, m_2, m_3)]
|
| 910 |
+
|
| 911 |
+
# check for quick exits
|
| 912 |
+
if sum(1 for i in (m_1, m_2, m_3) if i < 0) % 2:
|
| 913 |
+
return S.Zero # odd number of negative m
|
| 914 |
+
if (l_1 + l_2 + l_3) % 2:
|
| 915 |
+
return S.Zero # sum of l is odd
|
| 916 |
+
lmax = l_2 + l_3
|
| 917 |
+
lmin = max(abs(l_2 - l_3), min(abs(m_2 + m_3), abs(m_2 - m_3)))
|
| 918 |
+
if (lmin + lmax) % 2:
|
| 919 |
+
lmin += 1
|
| 920 |
+
if lmin not in range(lmax, lmin - 2, -2):
|
| 921 |
+
return S.Zero
|
| 922 |
+
|
| 923 |
+
kron_del = lambda i, j: 1 if i == j else 0
|
| 924 |
+
s = lambda e: -1 if e % 2 else 1 # (-1)**e to give +/-1, avoiding float when e<0
|
| 925 |
+
A = lambda a, b: (-kron_del(a, b)*s(a-b) + kron_del(a, -b)*
|
| 926 |
+
s(b)) if b < 0 else 0
|
| 927 |
+
B = lambda a, b: (kron_del(a, b) + kron_del(a, -b)*s(a)) if b > 0 else 0
|
| 928 |
+
C = lambda a, b: kron_del(abs(a), abs(b))*(kron_del(a, 0)*kron_del(b, 0) +
|
| 929 |
+
(B(a, b) + I*A(a, b))/sqrt(2))
|
| 930 |
+
ugnt = 0
|
| 931 |
+
for i in range(-l_1, l_1+1):
|
| 932 |
+
U1 = C(i, m_1)
|
| 933 |
+
for j in range(-l_2, l_2+1):
|
| 934 |
+
U2 = C(j, m_2)
|
| 935 |
+
U3 = C(-i-j, m_3)
|
| 936 |
+
ugnt = ugnt + re(U1*U2*U3)*gaunt(l_1, l_2, l_3, i, j, -i-j)
|
| 937 |
+
|
| 938 |
+
if prec is not None:
|
| 939 |
+
ugnt = ugnt.n(prec)
|
| 940 |
+
return ugnt
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
class Wigner3j(Function):
|
| 944 |
+
|
| 945 |
+
def doit(self, **hints):
|
| 946 |
+
if all(obj.is_number for obj in self.args):
|
| 947 |
+
return wigner_3j(*self.args)
|
| 948 |
+
else:
|
| 949 |
+
return self
|
| 950 |
+
|
| 951 |
+
def dot_rot_grad_Ynm(j, p, l, m, theta, phi):
|
| 952 |
+
r"""
|
| 953 |
+
Returns dot product of rotational gradients of spherical harmonics.
|
| 954 |
+
|
| 955 |
+
Explanation
|
| 956 |
+
===========
|
| 957 |
+
|
| 958 |
+
This function returns the right hand side of the following expression:
|
| 959 |
+
|
| 960 |
+
.. math ::
|
| 961 |
+
\vec{R}Y{_j^{p}} \cdot \vec{R}Y{_l^{m}} = (-1)^{m+p}
|
| 962 |
+
\sum\limits_{k=|l-j|}^{l+j}Y{_k^{m+p}} * \alpha_{l,m,j,p,k} *
|
| 963 |
+
\frac{1}{2} (k^2-j^2-l^2+k-j-l)
|
| 964 |
+
|
| 965 |
+
|
| 966 |
+
Arguments
|
| 967 |
+
=========
|
| 968 |
+
|
| 969 |
+
j, p, l, m .... indices in spherical harmonics (expressions or integers)
|
| 970 |
+
theta, phi .... angle arguments in spherical harmonics
|
| 971 |
+
|
| 972 |
+
Example
|
| 973 |
+
=======
|
| 974 |
+
|
| 975 |
+
>>> from sympy import symbols
|
| 976 |
+
>>> from sympy.physics.wigner import dot_rot_grad_Ynm
|
| 977 |
+
>>> theta, phi = symbols("theta phi")
|
| 978 |
+
>>> dot_rot_grad_Ynm(3, 2, 2, 0, theta, phi).doit()
|
| 979 |
+
3*sqrt(55)*Ynm(5, 2, theta, phi)/(11*sqrt(pi))
|
| 980 |
+
|
| 981 |
+
"""
|
| 982 |
+
j = sympify(j)
|
| 983 |
+
p = sympify(p)
|
| 984 |
+
l = sympify(l)
|
| 985 |
+
m = sympify(m)
|
| 986 |
+
theta = sympify(theta)
|
| 987 |
+
phi = sympify(phi)
|
| 988 |
+
k = Dummy("k")
|
| 989 |
+
|
| 990 |
+
def alpha(l,m,j,p,k):
|
| 991 |
+
return sqrt((2*l+1)*(2*j+1)*(2*k+1)/(4*pi)) * \
|
| 992 |
+
Wigner3j(j, l, k, S.Zero, S.Zero, S.Zero) * \
|
| 993 |
+
Wigner3j(j, l, k, p, m, -m-p)
|
| 994 |
+
|
| 995 |
+
return (S.NegativeOne)**(m+p) * Sum(Ynm(k, m+p, theta, phi) * alpha(l,m,j,p,k) / 2 \
|
| 996 |
+
*(k**2-j**2-l**2+k-j-l), (k, abs(l-j), l+j))
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
def wigner_d_small(J, beta):
|
| 1000 |
+
"""Return the small Wigner d matrix for angular momentum J.
|
| 1001 |
+
|
| 1002 |
+
Explanation
|
| 1003 |
+
===========
|
| 1004 |
+
|
| 1005 |
+
J : An integer, half-integer, or SymPy symbol for the total angular
|
| 1006 |
+
momentum of the angular momentum space being rotated.
|
| 1007 |
+
beta : A real number representing the Euler angle of rotation about
|
| 1008 |
+
the so-called line of nodes. See [Edmonds74]_.
|
| 1009 |
+
|
| 1010 |
+
Returns
|
| 1011 |
+
=======
|
| 1012 |
+
|
| 1013 |
+
A matrix representing the corresponding Euler angle rotation( in the basis
|
| 1014 |
+
of eigenvectors of `J_z`).
|
| 1015 |
+
|
| 1016 |
+
.. math ::
|
| 1017 |
+
\\mathcal{d}_{\\beta} = \\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big)
|
| 1018 |
+
|
| 1019 |
+
The components are calculated using the general form [Edmonds74]_,
|
| 1020 |
+
equation 4.1.15.
|
| 1021 |
+
|
| 1022 |
+
Examples
|
| 1023 |
+
========
|
| 1024 |
+
|
| 1025 |
+
>>> from sympy import Integer, symbols, pi, pprint
|
| 1026 |
+
>>> from sympy.physics.wigner import wigner_d_small
|
| 1027 |
+
>>> half = 1/Integer(2)
|
| 1028 |
+
>>> beta = symbols("beta", real=True)
|
| 1029 |
+
>>> pprint(wigner_d_small(half, beta), use_unicode=True)
|
| 1030 |
+
β‘ βΞ²β βΞ²ββ€
|
| 1031 |
+
β’cosβββ sinββββ₯
|
| 1032 |
+
β’ β2β β2β β₯
|
| 1033 |
+
β’ β₯
|
| 1034 |
+
β’ βΞ²β βΞ²ββ₯
|
| 1035 |
+
β’-sinβββ cosββββ₯
|
| 1036 |
+
β£ β2β β2β β¦
|
| 1037 |
+
|
| 1038 |
+
>>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
|
| 1039 |
+
β‘ 2βΞ²β βΞ²β βΞ²β 2βΞ²β β€
|
| 1040 |
+
β’ cos βββ β2β
sinββββ
cosβββ sin βββ β₯
|
| 1041 |
+
β’ β2β β2β β2β β2β β₯
|
| 1042 |
+
β’ β₯
|
| 1043 |
+
β’ βΞ²β βΞ²β 2βΞ²β 2βΞ²β βΞ²β βΞ²ββ₯
|
| 1044 |
+
β’-β2β
sinββββ
cosβββ - sin βββ + cos βββ β2β
sinββββ
cosββββ₯
|
| 1045 |
+
β’ β2β β2β β2β β2β β2β β2β β₯
|
| 1046 |
+
β’ β₯
|
| 1047 |
+
β’ 2βΞ²β βΞ²β βΞ²β 2βΞ²β β₯
|
| 1048 |
+
β’ sin βββ -β2β
sinββββ
cosβββ cos βββ β₯
|
| 1049 |
+
β£ β2β β2β β2β β2β β¦
|
| 1050 |
+
|
| 1051 |
+
From table 4 in [Edmonds74]_
|
| 1052 |
+
|
| 1053 |
+
>>> pprint(wigner_d_small(half, beta).subs({beta:pi/2}), use_unicode=True)
|
| 1054 |
+
β‘ β2 β2β€
|
| 1055 |
+
β’ ββ βββ₯
|
| 1056 |
+
β’ 2 2 β₯
|
| 1057 |
+
β’ β₯
|
| 1058 |
+
β’-β2 β2β₯
|
| 1059 |
+
β’ββββ βββ₯
|
| 1060 |
+
β£ 2 2 β¦
|
| 1061 |
+
|
| 1062 |
+
>>> pprint(wigner_d_small(2*half, beta).subs({beta:pi/2}),
|
| 1063 |
+
... use_unicode=True)
|
| 1064 |
+
β‘ β2 β€
|
| 1065 |
+
β’1/2 ββ 1/2β₯
|
| 1066 |
+
β’ 2 β₯
|
| 1067 |
+
β’ β₯
|
| 1068 |
+
β’-β2 β2 β₯
|
| 1069 |
+
β’ββββ 0 ββ β₯
|
| 1070 |
+
β’ 2 2 β₯
|
| 1071 |
+
β’ β₯
|
| 1072 |
+
β’ -β2 β₯
|
| 1073 |
+
β’1/2 ββββ 1/2β₯
|
| 1074 |
+
β£ 2 β¦
|
| 1075 |
+
|
| 1076 |
+
>>> pprint(wigner_d_small(3*half, beta).subs({beta:pi/2}),
|
| 1077 |
+
... use_unicode=True)
|
| 1078 |
+
β‘ β2 β6 β6 β2β€
|
| 1079 |
+
β’ ββ ββ ββ βββ₯
|
| 1080 |
+
β’ 4 4 4 4 β₯
|
| 1081 |
+
β’ β₯
|
| 1082 |
+
β’-β6 -β2 β2 β6β₯
|
| 1083 |
+
β’ββββ ββββ ββ βββ₯
|
| 1084 |
+
β’ 4 4 4 4 β₯
|
| 1085 |
+
β’ β₯
|
| 1086 |
+
β’ β6 -β2 -β2 β6β₯
|
| 1087 |
+
β’ ββ ββββ ββββ βββ₯
|
| 1088 |
+
β’ 4 4 4 4 β₯
|
| 1089 |
+
β’ β₯
|
| 1090 |
+
β’-β2 β6 -β6 β2β₯
|
| 1091 |
+
β’ββββ ββ ββββ βββ₯
|
| 1092 |
+
β£ 4 4 4 4 β¦
|
| 1093 |
+
|
| 1094 |
+
>>> pprint(wigner_d_small(4*half, beta).subs({beta:pi/2}),
|
| 1095 |
+
... use_unicode=True)
|
| 1096 |
+
β‘ β6 β€
|
| 1097 |
+
β’1/4 1/2 ββ 1/2 1/4β₯
|
| 1098 |
+
β’ 4 β₯
|
| 1099 |
+
β’ β₯
|
| 1100 |
+
β’-1/2 -1/2 0 1/2 1/2β₯
|
| 1101 |
+
β’ β₯
|
| 1102 |
+
β’ β6 β6 β₯
|
| 1103 |
+
β’ ββ 0 -1/2 0 ββ β₯
|
| 1104 |
+
β’ 4 4 β₯
|
| 1105 |
+
β’ β₯
|
| 1106 |
+
β’-1/2 1/2 0 -1/2 1/2β₯
|
| 1107 |
+
β’ β₯
|
| 1108 |
+
β’ β6 β₯
|
| 1109 |
+
β’1/4 -1/2 ββ -1/2 1/4β₯
|
| 1110 |
+
β£ 4 β¦
|
| 1111 |
+
|
| 1112 |
+
"""
|
| 1113 |
+
M = [J-i for i in range(2*J+1)]
|
| 1114 |
+
d = zeros(2*J+1)
|
| 1115 |
+
for i, Mi in enumerate(M):
|
| 1116 |
+
for j, Mj in enumerate(M):
|
| 1117 |
+
|
| 1118 |
+
# We get the maximum and minimum value of sigma.
|
| 1119 |
+
sigmamax = min([J-Mi, J-Mj])
|
| 1120 |
+
sigmamin = max([0, -Mi-Mj])
|
| 1121 |
+
|
| 1122 |
+
dij = sqrt(factorial(J+Mi)*factorial(J-Mi) /
|
| 1123 |
+
factorial(J+Mj)/factorial(J-Mj))
|
| 1124 |
+
terms = [(-1)**(J-Mi-s) *
|
| 1125 |
+
binomial(J+Mj, J-Mi-s) *
|
| 1126 |
+
binomial(J-Mj, s) *
|
| 1127 |
+
cos(beta/2)**(2*s+Mi+Mj) *
|
| 1128 |
+
sin(beta/2)**(2*J-2*s-Mj-Mi)
|
| 1129 |
+
for s in range(sigmamin, sigmamax+1)]
|
| 1130 |
+
|
| 1131 |
+
d[i, j] = dij*Add(*terms)
|
| 1132 |
+
|
| 1133 |
+
return ImmutableMatrix(d)
|
| 1134 |
+
|
| 1135 |
+
|
| 1136 |
+
def wigner_d(J, alpha, beta, gamma):
|
| 1137 |
+
"""Return the Wigner D matrix for angular momentum J.
|
| 1138 |
+
|
| 1139 |
+
Explanation
|
| 1140 |
+
===========
|
| 1141 |
+
|
| 1142 |
+
J :
|
| 1143 |
+
An integer, half-integer, or SymPy symbol for the total angular
|
| 1144 |
+
momentum of the angular momentum space being rotated.
|
| 1145 |
+
alpha, beta, gamma - Real numbers representing the Euler.
|
| 1146 |
+
Angles of rotation about the so-called vertical, line of nodes, and
|
| 1147 |
+
figure axes. See [Edmonds74]_.
|
| 1148 |
+
|
| 1149 |
+
Returns
|
| 1150 |
+
=======
|
| 1151 |
+
|
| 1152 |
+
A matrix representing the corresponding Euler angle rotation( in the basis
|
| 1153 |
+
of eigenvectors of `J_z`).
|
| 1154 |
+
|
| 1155 |
+
.. math ::
|
| 1156 |
+
\\mathcal{D}_{\\alpha \\beta \\gamma} =
|
| 1157 |
+
\\exp\\big( \\frac{i\\alpha}{\\hbar} J_z\\big)
|
| 1158 |
+
\\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big)
|
| 1159 |
+
\\exp\\big( \\frac{i\\gamma}{\\hbar} J_z\\big)
|
| 1160 |
+
|
| 1161 |
+
The components are calculated using the general form [Edmonds74]_,
|
| 1162 |
+
equation 4.1.12.
|
| 1163 |
+
|
| 1164 |
+
Examples
|
| 1165 |
+
========
|
| 1166 |
+
|
| 1167 |
+
The simplest possible example:
|
| 1168 |
+
|
| 1169 |
+
>>> from sympy.physics.wigner import wigner_d
|
| 1170 |
+
>>> from sympy import Integer, symbols, pprint
|
| 1171 |
+
>>> half = 1/Integer(2)
|
| 1172 |
+
>>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
|
| 1173 |
+
>>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
|
| 1174 |
+
β‘ β
β
Ξ± β
β
Ξ³ β
β
Ξ± -β
β
Ξ³ β€
|
| 1175 |
+
β’ βββ βββ βββ βββββ β₯
|
| 1176 |
+
β’ 2 2 βΞ²β 2 2 βΞ²β β₯
|
| 1177 |
+
β’ β― β
β― β
cosβββ β― β
β― β
sinβββ β₯
|
| 1178 |
+
β’ β2β β2β β₯
|
| 1179 |
+
β’ β₯
|
| 1180 |
+
β’ -β
β
Ξ± β
β
Ξ³ -β
β
Ξ± -β
β
Ξ³ β₯
|
| 1181 |
+
β’ βββββ βββ βββββ βββββ β₯
|
| 1182 |
+
β’ 2 2 βΞ²β 2 2 βΞ²ββ₯
|
| 1183 |
+
β’-β― β
β― β
sinβββ β― β
β― β
cosββββ₯
|
| 1184 |
+
β£ β2β β2β β¦
|
| 1185 |
+
|
| 1186 |
+
"""
|
| 1187 |
+
d = wigner_d_small(J, beta)
|
| 1188 |
+
M = [J-i for i in range(2*J+1)]
|
| 1189 |
+
D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma)
|
| 1190 |
+
for j, Mj in enumerate(M)] for i, Mi in enumerate(M)]
|
| 1191 |
+
return ImmutableMatrix(D)
|