Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step120/zero/11.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step120/zero/11.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step120/zero/13.input_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step120/zero/13.input_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step120/zero/15.post_attention_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step120/zero/15.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step120/zero/15.post_attention_layernorm.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/add.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/alphabets.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/basic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/coreerrors.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/decorators.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/evalf.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/exprtools.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/kind.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/logic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/mul.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/operations.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/parameters.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/power.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/random.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/symbol.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/sympify.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/trace.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/__pycache__/traversal.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/interactive/__init__.py +8 -0
- venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/interactive/printing.py +562 -0
- venv/lib/python3.10/site-packages/sympy/interactive/session.py +463 -0
- venv/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_interactive.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_ipython.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/interactive/tests/test_interactive.py +10 -0
- venv/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py +278 -0
- venv/lib/python3.10/site-packages/sympy/interactive/traversal.py +95 -0
- venv/lib/python3.10/site-packages/sympy/sandbox/__init__.py +8 -0
- venv/lib/python3.10/site-packages/sympy/sandbox/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/sandbox/__pycache__/indexed_integrals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/sandbox/indexed_integrals.py +72 -0
- venv/lib/python3.10/site-packages/sympy/sandbox/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/test_indexed_integrals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/sandbox/tests/test_indexed_integrals.py +25 -0
- venv/lib/python3.10/site-packages/sympy/series/__init__.py +23 -0
- venv/lib/python3.10/site-packages/sympy/series/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/series/__pycache__/acceleration.cpython-310.pyc +0 -0
ckpts/universal/global_step120/zero/11.mlp.dense_h_to_4h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:79d5981c6b9f707c95f78abe258b25887908f5a9aeeca64a98cf58a060b7f70f
|
3 |
+
size 33555612
|
ckpts/universal/global_step120/zero/11.mlp.dense_h_to_4h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:82b31d6e34d7fe0722fbd5fe8457b71da70beb18c746c12c6bdcbeb5ec890f8f
|
3 |
+
size 33555627
|
ckpts/universal/global_step120/zero/13.input_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b026f5e579465bbde90b1fc8e34a14f3d3192bfbe2fccf71b80eac1ff933cd51
|
3 |
+
size 9372
|
ckpts/universal/global_step120/zero/13.input_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:80209a4256d6162fccc1cc771903879dc8a205253874b9ad3b36f8682a619ea6
|
3 |
+
size 9293
|
ckpts/universal/global_step120/zero/15.post_attention_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7374d9ec2726959309869b11276997845b0b532884970876d404ad233cfd563a
|
3 |
+
size 9372
|
ckpts/universal/global_step120/zero/15.post_attention_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2a17892f0e12f0805b1479a66efeaae8d5b202d325249ae4ef66ae8c5d567489
|
3 |
+
size 9387
|
ckpts/universal/global_step120/zero/15.post_attention_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:09f163f365a376e3f08b8b464bcf7cd6391733e651aec4de147ca95063fd8803
|
3 |
+
size 9293
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/add.cpython-310.pyc
ADDED
Binary file (35.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/alphabets.cpython-310.pyc
ADDED
Binary file (338 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/basic.cpython-310.pyc
ADDED
Binary file (66.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/coreerrors.cpython-310.pyc
ADDED
Binary file (666 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/decorators.cpython-310.pyc
ADDED
Binary file (7.88 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/evalf.cpython-310.pyc
ADDED
Binary file (42.6 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/exprtools.cpython-310.pyc
ADDED
Binary file (41 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/kind.cpython-310.pyc
ADDED
Binary file (11.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/logic.cpython-310.pyc
ADDED
Binary file (10.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/mul.cpython-310.pyc
ADDED
Binary file (54.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/operations.cpython-310.pyc
ADDED
Binary file (20.5 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/parameters.cpython-310.pyc
ADDED
Binary file (4.09 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/power.cpython-310.pyc
ADDED
Binary file (50.1 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/random.cpython-310.pyc
ADDED
Binary file (6.95 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/symbol.cpython-310.pyc
ADDED
Binary file (27 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/sympify.cpython-310.pyc
ADDED
Binary file (16.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/trace.cpython-310.pyc
ADDED
Binary file (508 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/__pycache__/traversal.cpython-310.pyc
ADDED
Binary file (9.22 kB). View file
|
|
venv/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']
|
venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (440 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc
ADDED
Binary file (17.4 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc
ADDED
Binary file (11.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc
ADDED
Binary file (2.44 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/interactive/printing.py
ADDED
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tools for setting up printing in interactive sessions. """
|
2 |
+
|
3 |
+
from sympy.external.importtools import version_tuple
|
4 |
+
from io import BytesIO
|
5 |
+
|
6 |
+
from sympy.printing.latex import latex as default_latex
|
7 |
+
from sympy.printing.preview import preview
|
8 |
+
from sympy.utilities.misc import debug
|
9 |
+
from sympy.printing.defaults import Printable
|
10 |
+
|
11 |
+
|
12 |
+
def _init_python_printing(stringify_func, **settings):
|
13 |
+
"""Setup printing in Python interactive session. """
|
14 |
+
import sys
|
15 |
+
import builtins
|
16 |
+
|
17 |
+
def _displayhook(arg):
|
18 |
+
"""Python's pretty-printer display hook.
|
19 |
+
|
20 |
+
This function was adapted from:
|
21 |
+
|
22 |
+
https://www.python.org/dev/peps/pep-0217/
|
23 |
+
|
24 |
+
"""
|
25 |
+
if arg is not None:
|
26 |
+
builtins._ = None
|
27 |
+
print(stringify_func(arg, **settings))
|
28 |
+
builtins._ = arg
|
29 |
+
|
30 |
+
sys.displayhook = _displayhook
|
31 |
+
|
32 |
+
|
33 |
+
def _init_ipython_printing(ip, stringify_func, use_latex, euler, forecolor,
|
34 |
+
backcolor, fontsize, latex_mode, print_builtin,
|
35 |
+
latex_printer, scale, **settings):
|
36 |
+
"""Setup printing in IPython interactive session. """
|
37 |
+
try:
|
38 |
+
from IPython.lib.latextools import latex_to_png
|
39 |
+
except ImportError:
|
40 |
+
pass
|
41 |
+
|
42 |
+
# Guess best font color if none was given based on the ip.colors string.
|
43 |
+
# From the IPython documentation:
|
44 |
+
# It has four case-insensitive values: 'nocolor', 'neutral', 'linux',
|
45 |
+
# 'lightbg'. The default is neutral, which should be legible on either
|
46 |
+
# dark or light terminal backgrounds. linux is optimised for dark
|
47 |
+
# backgrounds and lightbg for light ones.
|
48 |
+
if forecolor is None:
|
49 |
+
color = ip.colors.lower()
|
50 |
+
if color == 'lightbg':
|
51 |
+
forecolor = 'Black'
|
52 |
+
elif color == 'linux':
|
53 |
+
forecolor = 'White'
|
54 |
+
else:
|
55 |
+
# No idea, go with gray.
|
56 |
+
forecolor = 'Gray'
|
57 |
+
debug("init_printing: Automatic foreground color:", forecolor)
|
58 |
+
|
59 |
+
if use_latex == "svg":
|
60 |
+
extra_preamble = "\n\\special{color %s}" % forecolor
|
61 |
+
else:
|
62 |
+
extra_preamble = ""
|
63 |
+
|
64 |
+
imagesize = 'tight'
|
65 |
+
offset = "0cm,0cm"
|
66 |
+
resolution = round(150*scale)
|
67 |
+
dvi = r"-T %s -D %d -bg %s -fg %s -O %s" % (
|
68 |
+
imagesize, resolution, backcolor, forecolor, offset)
|
69 |
+
dvioptions = dvi.split()
|
70 |
+
|
71 |
+
svg_scale = 150/72*scale
|
72 |
+
dvioptions_svg = ["--no-fonts", "--scale={}".format(svg_scale)]
|
73 |
+
|
74 |
+
debug("init_printing: DVIOPTIONS:", dvioptions)
|
75 |
+
debug("init_printing: DVIOPTIONS_SVG:", dvioptions_svg)
|
76 |
+
|
77 |
+
latex = latex_printer or default_latex
|
78 |
+
|
79 |
+
def _print_plain(arg, p, cycle):
|
80 |
+
"""caller for pretty, for use in IPython 0.11"""
|
81 |
+
if _can_print(arg):
|
82 |
+
p.text(stringify_func(arg))
|
83 |
+
else:
|
84 |
+
p.text(IPython.lib.pretty.pretty(arg))
|
85 |
+
|
86 |
+
def _preview_wrapper(o):
|
87 |
+
exprbuffer = BytesIO()
|
88 |
+
try:
|
89 |
+
preview(o, output='png', viewer='BytesIO', euler=euler,
|
90 |
+
outputbuffer=exprbuffer, extra_preamble=extra_preamble,
|
91 |
+
dvioptions=dvioptions, fontsize=fontsize)
|
92 |
+
except Exception as e:
|
93 |
+
# IPython swallows exceptions
|
94 |
+
debug("png printing:", "_preview_wrapper exception raised:",
|
95 |
+
repr(e))
|
96 |
+
raise
|
97 |
+
return exprbuffer.getvalue()
|
98 |
+
|
99 |
+
def _svg_wrapper(o):
|
100 |
+
exprbuffer = BytesIO()
|
101 |
+
try:
|
102 |
+
preview(o, output='svg', viewer='BytesIO', euler=euler,
|
103 |
+
outputbuffer=exprbuffer, extra_preamble=extra_preamble,
|
104 |
+
dvioptions=dvioptions_svg, fontsize=fontsize)
|
105 |
+
except Exception as e:
|
106 |
+
# IPython swallows exceptions
|
107 |
+
debug("svg printing:", "_preview_wrapper exception raised:",
|
108 |
+
repr(e))
|
109 |
+
raise
|
110 |
+
return exprbuffer.getvalue().decode('utf-8')
|
111 |
+
|
112 |
+
def _matplotlib_wrapper(o):
|
113 |
+
# mathtext can't render some LaTeX commands. For example, it can't
|
114 |
+
# render any LaTeX environments such as array or matrix. So here we
|
115 |
+
# ensure that if mathtext fails to render, we return None.
|
116 |
+
try:
|
117 |
+
try:
|
118 |
+
return latex_to_png(o, color=forecolor, scale=scale)
|
119 |
+
except TypeError: # Old IPython version without color and scale
|
120 |
+
return latex_to_png(o)
|
121 |
+
except ValueError as e:
|
122 |
+
debug('matplotlib exception caught:', repr(e))
|
123 |
+
return None
|
124 |
+
|
125 |
+
|
126 |
+
# Hook methods for builtin SymPy printers
|
127 |
+
printing_hooks = ('_latex', '_sympystr', '_pretty', '_sympyrepr')
|
128 |
+
|
129 |
+
|
130 |
+
def _can_print(o):
|
131 |
+
"""Return True if type o can be printed with one of the SymPy printers.
|
132 |
+
|
133 |
+
If o is a container type, this is True if and only if every element of
|
134 |
+
o can be printed in this way.
|
135 |
+
"""
|
136 |
+
|
137 |
+
try:
|
138 |
+
# If you're adding another type, make sure you add it to printable_types
|
139 |
+
# later in this file as well
|
140 |
+
|
141 |
+
builtin_types = (list, tuple, set, frozenset)
|
142 |
+
if isinstance(o, builtin_types):
|
143 |
+
# If the object is a custom subclass with a custom str or
|
144 |
+
# repr, use that instead.
|
145 |
+
if (type(o).__str__ not in (i.__str__ for i in builtin_types) or
|
146 |
+
type(o).__repr__ not in (i.__repr__ for i in builtin_types)):
|
147 |
+
return False
|
148 |
+
return all(_can_print(i) for i in o)
|
149 |
+
elif isinstance(o, dict):
|
150 |
+
return all(_can_print(i) and _can_print(o[i]) for i in o)
|
151 |
+
elif isinstance(o, bool):
|
152 |
+
return False
|
153 |
+
elif isinstance(o, Printable):
|
154 |
+
# types known to SymPy
|
155 |
+
return True
|
156 |
+
elif any(hasattr(o, hook) for hook in printing_hooks):
|
157 |
+
# types which add support themselves
|
158 |
+
return True
|
159 |
+
elif isinstance(o, (float, int)) and print_builtin:
|
160 |
+
return True
|
161 |
+
return False
|
162 |
+
except RuntimeError:
|
163 |
+
return False
|
164 |
+
# This is in case maximum recursion depth is reached.
|
165 |
+
# Since RecursionError is for versions of Python 3.5+
|
166 |
+
# so this is to guard against RecursionError for older versions.
|
167 |
+
|
168 |
+
def _print_latex_png(o):
|
169 |
+
"""
|
170 |
+
A function that returns a png rendered by an external latex
|
171 |
+
distribution, falling back to matplotlib rendering
|
172 |
+
"""
|
173 |
+
if _can_print(o):
|
174 |
+
s = latex(o, mode=latex_mode, **settings)
|
175 |
+
if latex_mode == 'plain':
|
176 |
+
s = '$\\displaystyle %s$' % s
|
177 |
+
try:
|
178 |
+
return _preview_wrapper(s)
|
179 |
+
except RuntimeError as e:
|
180 |
+
debug('preview failed with:', repr(e),
|
181 |
+
' Falling back to matplotlib backend')
|
182 |
+
if latex_mode != 'inline':
|
183 |
+
s = latex(o, mode='inline', **settings)
|
184 |
+
return _matplotlib_wrapper(s)
|
185 |
+
|
186 |
+
def _print_latex_svg(o):
|
187 |
+
"""
|
188 |
+
A function that returns a svg rendered by an external latex
|
189 |
+
distribution, no fallback available.
|
190 |
+
"""
|
191 |
+
if _can_print(o):
|
192 |
+
s = latex(o, mode=latex_mode, **settings)
|
193 |
+
if latex_mode == 'plain':
|
194 |
+
s = '$\\displaystyle %s$' % s
|
195 |
+
try:
|
196 |
+
return _svg_wrapper(s)
|
197 |
+
except RuntimeError as e:
|
198 |
+
debug('preview failed with:', repr(e),
|
199 |
+
' No fallback available.')
|
200 |
+
|
201 |
+
def _print_latex_matplotlib(o):
|
202 |
+
"""
|
203 |
+
A function that returns a png rendered by mathtext
|
204 |
+
"""
|
205 |
+
if _can_print(o):
|
206 |
+
s = latex(o, mode='inline', **settings)
|
207 |
+
return _matplotlib_wrapper(s)
|
208 |
+
|
209 |
+
def _print_latex_text(o):
|
210 |
+
"""
|
211 |
+
A function to generate the latex representation of SymPy expressions.
|
212 |
+
"""
|
213 |
+
if _can_print(o):
|
214 |
+
s = latex(o, mode=latex_mode, **settings)
|
215 |
+
if latex_mode == 'plain':
|
216 |
+
return '$\\displaystyle %s$' % s
|
217 |
+
return s
|
218 |
+
|
219 |
+
def _result_display(self, arg):
|
220 |
+
"""IPython's pretty-printer display hook, for use in IPython 0.10
|
221 |
+
|
222 |
+
This function was adapted from:
|
223 |
+
|
224 |
+
ipython/IPython/hooks.py:155
|
225 |
+
|
226 |
+
"""
|
227 |
+
if self.rc.pprint:
|
228 |
+
out = stringify_func(arg)
|
229 |
+
|
230 |
+
if '\n' in out:
|
231 |
+
print()
|
232 |
+
|
233 |
+
print(out)
|
234 |
+
else:
|
235 |
+
print(repr(arg))
|
236 |
+
|
237 |
+
import IPython
|
238 |
+
if version_tuple(IPython.__version__) >= version_tuple('0.11'):
|
239 |
+
|
240 |
+
# Printable is our own type, so we handle it with methods instead of
|
241 |
+
# the approach required by builtin types. This allows downstream
|
242 |
+
# packages to override the methods in their own subclasses of Printable,
|
243 |
+
# which avoids the effects of gh-16002.
|
244 |
+
printable_types = [float, tuple, list, set, frozenset, dict, int]
|
245 |
+
|
246 |
+
plaintext_formatter = ip.display_formatter.formatters['text/plain']
|
247 |
+
|
248 |
+
# Exception to the rule above: IPython has better dispatching rules
|
249 |
+
# for plaintext printing (xref ipython/ipython#8938), and we can't
|
250 |
+
# use `_repr_pretty_` without hitting a recursion error in _print_plain.
|
251 |
+
for cls in printable_types + [Printable]:
|
252 |
+
plaintext_formatter.for_type(cls, _print_plain)
|
253 |
+
|
254 |
+
svg_formatter = ip.display_formatter.formatters['image/svg+xml']
|
255 |
+
if use_latex in ('svg', ):
|
256 |
+
debug("init_printing: using svg formatter")
|
257 |
+
for cls in printable_types:
|
258 |
+
svg_formatter.for_type(cls, _print_latex_svg)
|
259 |
+
Printable._repr_svg_ = _print_latex_svg
|
260 |
+
else:
|
261 |
+
debug("init_printing: not using any svg formatter")
|
262 |
+
for cls in printable_types:
|
263 |
+
# Better way to set this, but currently does not work in IPython
|
264 |
+
#png_formatter.for_type(cls, None)
|
265 |
+
if cls in svg_formatter.type_printers:
|
266 |
+
svg_formatter.type_printers.pop(cls)
|
267 |
+
Printable._repr_svg_ = Printable._repr_disabled
|
268 |
+
|
269 |
+
png_formatter = ip.display_formatter.formatters['image/png']
|
270 |
+
if use_latex in (True, 'png'):
|
271 |
+
debug("init_printing: using png formatter")
|
272 |
+
for cls in printable_types:
|
273 |
+
png_formatter.for_type(cls, _print_latex_png)
|
274 |
+
Printable._repr_png_ = _print_latex_png
|
275 |
+
elif use_latex == 'matplotlib':
|
276 |
+
debug("init_printing: using matplotlib formatter")
|
277 |
+
for cls in printable_types:
|
278 |
+
png_formatter.for_type(cls, _print_latex_matplotlib)
|
279 |
+
Printable._repr_png_ = _print_latex_matplotlib
|
280 |
+
else:
|
281 |
+
debug("init_printing: not using any png formatter")
|
282 |
+
for cls in printable_types:
|
283 |
+
# Better way to set this, but currently does not work in IPython
|
284 |
+
#png_formatter.for_type(cls, None)
|
285 |
+
if cls in png_formatter.type_printers:
|
286 |
+
png_formatter.type_printers.pop(cls)
|
287 |
+
Printable._repr_png_ = Printable._repr_disabled
|
288 |
+
|
289 |
+
latex_formatter = ip.display_formatter.formatters['text/latex']
|
290 |
+
if use_latex in (True, 'mathjax'):
|
291 |
+
debug("init_printing: using mathjax formatter")
|
292 |
+
for cls in printable_types:
|
293 |
+
latex_formatter.for_type(cls, _print_latex_text)
|
294 |
+
Printable._repr_latex_ = _print_latex_text
|
295 |
+
else:
|
296 |
+
debug("init_printing: not using text/latex formatter")
|
297 |
+
for cls in printable_types:
|
298 |
+
# Better way to set this, but currently does not work in IPython
|
299 |
+
#latex_formatter.for_type(cls, None)
|
300 |
+
if cls in latex_formatter.type_printers:
|
301 |
+
latex_formatter.type_printers.pop(cls)
|
302 |
+
Printable._repr_latex_ = Printable._repr_disabled
|
303 |
+
|
304 |
+
else:
|
305 |
+
ip.set_hook('result_display', _result_display)
|
306 |
+
|
307 |
+
def _is_ipython(shell):
|
308 |
+
"""Is a shell instance an IPython shell?"""
|
309 |
+
# shortcut, so we don't import IPython if we don't have to
|
310 |
+
from sys import modules
|
311 |
+
if 'IPython' not in modules:
|
312 |
+
return False
|
313 |
+
try:
|
314 |
+
from IPython.core.interactiveshell import InteractiveShell
|
315 |
+
except ImportError:
|
316 |
+
# IPython < 0.11
|
317 |
+
try:
|
318 |
+
from IPython.iplib import InteractiveShell
|
319 |
+
except ImportError:
|
320 |
+
# Reaching this points means IPython has changed in a backward-incompatible way
|
321 |
+
# that we don't know about. Warn?
|
322 |
+
return False
|
323 |
+
return isinstance(shell, InteractiveShell)
|
324 |
+
|
325 |
+
# Used by the doctester to override the default for no_global
|
326 |
+
NO_GLOBAL = False
|
327 |
+
|
328 |
+
def init_printing(pretty_print=True, order=None, use_unicode=None,
|
329 |
+
use_latex=None, wrap_line=None, num_columns=None,
|
330 |
+
no_global=False, ip=None, euler=False, forecolor=None,
|
331 |
+
backcolor='Transparent', fontsize='10pt',
|
332 |
+
latex_mode='plain', print_builtin=True,
|
333 |
+
str_printer=None, pretty_printer=None,
|
334 |
+
latex_printer=None, scale=1.0, **settings):
|
335 |
+
r"""
|
336 |
+
Initializes pretty-printer depending on the environment.
|
337 |
+
|
338 |
+
Parameters
|
339 |
+
==========
|
340 |
+
|
341 |
+
pretty_print : bool, default=True
|
342 |
+
If ``True``, use :func:`~.pretty_print` to stringify or the provided pretty
|
343 |
+
printer; if ``False``, use :func:`~.sstrrepr` to stringify or the provided string
|
344 |
+
printer.
|
345 |
+
order : string or None, default='lex'
|
346 |
+
There are a few different settings for this parameter:
|
347 |
+
``'lex'`` (default), which is lexographic order;
|
348 |
+
``'grlex'``, which is graded lexographic order;
|
349 |
+
``'grevlex'``, which is reversed graded lexographic order;
|
350 |
+
``'old'``, which is used for compatibility reasons and for long expressions;
|
351 |
+
``None``, which sets it to lex.
|
352 |
+
use_unicode : bool or None, default=None
|
353 |
+
If ``True``, use unicode characters;
|
354 |
+
if ``False``, do not use unicode characters;
|
355 |
+
if ``None``, make a guess based on the environment.
|
356 |
+
use_latex : string, bool, or None, default=None
|
357 |
+
If ``True``, use default LaTeX rendering in GUI interfaces (png and
|
358 |
+
mathjax);
|
359 |
+
if ``False``, do not use LaTeX rendering;
|
360 |
+
if ``None``, make a guess based on the environment;
|
361 |
+
if ``'png'``, enable LaTeX rendering with an external LaTeX compiler,
|
362 |
+
falling back to matplotlib if external compilation fails;
|
363 |
+
if ``'matplotlib'``, enable LaTeX rendering with matplotlib;
|
364 |
+
if ``'mathjax'``, enable LaTeX text generation, for example MathJax
|
365 |
+
rendering in IPython notebook or text rendering in LaTeX documents;
|
366 |
+
if ``'svg'``, enable LaTeX rendering with an external latex compiler,
|
367 |
+
no fallback
|
368 |
+
wrap_line : bool
|
369 |
+
If True, lines will wrap at the end; if False, they will not wrap
|
370 |
+
but continue as one line. This is only relevant if ``pretty_print`` is
|
371 |
+
True.
|
372 |
+
num_columns : int or None, default=None
|
373 |
+
If ``int``, number of columns before wrapping is set to num_columns; if
|
374 |
+
``None``, number of columns before wrapping is set to terminal width.
|
375 |
+
This is only relevant if ``pretty_print`` is ``True``.
|
376 |
+
no_global : bool, default=False
|
377 |
+
If ``True``, the settings become system wide;
|
378 |
+
if ``False``, use just for this console/session.
|
379 |
+
ip : An interactive console
|
380 |
+
This can either be an instance of IPython,
|
381 |
+
or a class that derives from code.InteractiveConsole.
|
382 |
+
euler : bool, optional, default=False
|
383 |
+
Loads the euler package in the LaTeX preamble for handwritten style
|
384 |
+
fonts (https://www.ctan.org/pkg/euler).
|
385 |
+
forecolor : string or None, optional, default=None
|
386 |
+
DVI setting for foreground color. ``None`` means that either ``'Black'``,
|
387 |
+
``'White'``, or ``'Gray'`` will be selected based on a guess of the IPython
|
388 |
+
terminal color setting. See notes.
|
389 |
+
backcolor : string, optional, default='Transparent'
|
390 |
+
DVI setting for background color. See notes.
|
391 |
+
fontsize : string or int, optional, default='10pt'
|
392 |
+
A font size to pass to the LaTeX documentclass function in the
|
393 |
+
preamble. Note that the options are limited by the documentclass.
|
394 |
+
Consider using scale instead.
|
395 |
+
latex_mode : string, optional, default='plain'
|
396 |
+
The mode used in the LaTeX printer. Can be one of:
|
397 |
+
``{'inline'|'plain'|'equation'|'equation*'}``.
|
398 |
+
print_builtin : boolean, optional, default=True
|
399 |
+
If ``True`` then floats and integers will be printed. If ``False`` the
|
400 |
+
printer will only print SymPy types.
|
401 |
+
str_printer : function, optional, default=None
|
402 |
+
A custom string printer function. This should mimic
|
403 |
+
:func:`~.sstrrepr()`.
|
404 |
+
pretty_printer : function, optional, default=None
|
405 |
+
A custom pretty printer. This should mimic :func:`~.pretty()`.
|
406 |
+
latex_printer : function, optional, default=None
|
407 |
+
A custom LaTeX printer. This should mimic :func:`~.latex()`.
|
408 |
+
scale : float, optional, default=1.0
|
409 |
+
Scale the LaTeX output when using the ``'png'`` or ``'svg'`` backends.
|
410 |
+
Useful for high dpi screens.
|
411 |
+
settings :
|
412 |
+
Any additional settings for the ``latex`` and ``pretty`` commands can
|
413 |
+
be used to fine-tune the output.
|
414 |
+
|
415 |
+
Examples
|
416 |
+
========
|
417 |
+
|
418 |
+
>>> from sympy.interactive import init_printing
|
419 |
+
>>> from sympy import Symbol, sqrt
|
420 |
+
>>> from sympy.abc import x, y
|
421 |
+
>>> sqrt(5)
|
422 |
+
sqrt(5)
|
423 |
+
>>> init_printing(pretty_print=True) # doctest: +SKIP
|
424 |
+
>>> sqrt(5) # doctest: +SKIP
|
425 |
+
___
|
426 |
+
\/ 5
|
427 |
+
>>> theta = Symbol('theta') # doctest: +SKIP
|
428 |
+
>>> init_printing(use_unicode=True) # doctest: +SKIP
|
429 |
+
>>> theta # doctest: +SKIP
|
430 |
+
\u03b8
|
431 |
+
>>> init_printing(use_unicode=False) # doctest: +SKIP
|
432 |
+
>>> theta # doctest: +SKIP
|
433 |
+
theta
|
434 |
+
>>> init_printing(order='lex') # doctest: +SKIP
|
435 |
+
>>> str(y + x + y**2 + x**2) # doctest: +SKIP
|
436 |
+
x**2 + x + y**2 + y
|
437 |
+
>>> init_printing(order='grlex') # doctest: +SKIP
|
438 |
+
>>> str(y + x + y**2 + x**2) # doctest: +SKIP
|
439 |
+
x**2 + x + y**2 + y
|
440 |
+
>>> init_printing(order='grevlex') # doctest: +SKIP
|
441 |
+
>>> str(y * x**2 + x * y**2) # doctest: +SKIP
|
442 |
+
x**2*y + x*y**2
|
443 |
+
>>> init_printing(order='old') # doctest: +SKIP
|
444 |
+
>>> str(x**2 + y**2 + x + y) # doctest: +SKIP
|
445 |
+
x**2 + x + y**2 + y
|
446 |
+
>>> init_printing(num_columns=10) # doctest: +SKIP
|
447 |
+
>>> x**2 + x + y**2 + y # doctest: +SKIP
|
448 |
+
x + y +
|
449 |
+
x**2 + y**2
|
450 |
+
|
451 |
+
Notes
|
452 |
+
=====
|
453 |
+
|
454 |
+
The foreground and background colors can be selected when using ``'png'`` or
|
455 |
+
``'svg'`` LaTeX rendering. Note that before the ``init_printing`` command is
|
456 |
+
executed, the LaTeX rendering is handled by the IPython console and not SymPy.
|
457 |
+
|
458 |
+
The colors can be selected among the 68 standard colors known to ``dvips``,
|
459 |
+
for a list see [1]_. In addition, the background color can be
|
460 |
+
set to ``'Transparent'`` (which is the default value).
|
461 |
+
|
462 |
+
When using the ``'Auto'`` foreground color, the guess is based on the
|
463 |
+
``colors`` variable in the IPython console, see [2]_. Hence, if
|
464 |
+
that variable is set correctly in your IPython console, there is a high
|
465 |
+
chance that the output will be readable, although manual settings may be
|
466 |
+
needed.
|
467 |
+
|
468 |
+
|
469 |
+
References
|
470 |
+
==========
|
471 |
+
|
472 |
+
.. [1] https://en.wikibooks.org/wiki/LaTeX/Colors#The_68_standard_colors_known_to_dvips
|
473 |
+
|
474 |
+
.. [2] https://ipython.readthedocs.io/en/stable/config/details.html#terminal-colors
|
475 |
+
|
476 |
+
See Also
|
477 |
+
========
|
478 |
+
|
479 |
+
sympy.printing.latex
|
480 |
+
sympy.printing.pretty
|
481 |
+
|
482 |
+
"""
|
483 |
+
import sys
|
484 |
+
from sympy.printing.printer import Printer
|
485 |
+
|
486 |
+
if pretty_print:
|
487 |
+
if pretty_printer is not None:
|
488 |
+
stringify_func = pretty_printer
|
489 |
+
else:
|
490 |
+
from sympy.printing import pretty as stringify_func
|
491 |
+
else:
|
492 |
+
if str_printer is not None:
|
493 |
+
stringify_func = str_printer
|
494 |
+
else:
|
495 |
+
from sympy.printing import sstrrepr as stringify_func
|
496 |
+
|
497 |
+
# Even if ip is not passed, double check that not in IPython shell
|
498 |
+
in_ipython = False
|
499 |
+
if ip is None:
|
500 |
+
try:
|
501 |
+
ip = get_ipython()
|
502 |
+
except NameError:
|
503 |
+
pass
|
504 |
+
else:
|
505 |
+
in_ipython = (ip is not None)
|
506 |
+
|
507 |
+
if ip and not in_ipython:
|
508 |
+
in_ipython = _is_ipython(ip)
|
509 |
+
|
510 |
+
if in_ipython and pretty_print:
|
511 |
+
try:
|
512 |
+
import IPython
|
513 |
+
# IPython 1.0 deprecates the frontend module, so we import directly
|
514 |
+
# from the terminal module to prevent a deprecation message from being
|
515 |
+
# shown.
|
516 |
+
if version_tuple(IPython.__version__) >= version_tuple('1.0'):
|
517 |
+
from IPython.terminal.interactiveshell import TerminalInteractiveShell
|
518 |
+
else:
|
519 |
+
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
|
520 |
+
from code import InteractiveConsole
|
521 |
+
except ImportError:
|
522 |
+
pass
|
523 |
+
else:
|
524 |
+
# This will be True if we are in the qtconsole or notebook
|
525 |
+
if not isinstance(ip, (InteractiveConsole, TerminalInteractiveShell)) \
|
526 |
+
and 'ipython-console' not in ''.join(sys.argv):
|
527 |
+
if use_unicode is None:
|
528 |
+
debug("init_printing: Setting use_unicode to True")
|
529 |
+
use_unicode = True
|
530 |
+
if use_latex is None:
|
531 |
+
debug("init_printing: Setting use_latex to True")
|
532 |
+
use_latex = True
|
533 |
+
|
534 |
+
if not NO_GLOBAL and not no_global:
|
535 |
+
Printer.set_global_settings(order=order, use_unicode=use_unicode,
|
536 |
+
wrap_line=wrap_line, num_columns=num_columns)
|
537 |
+
else:
|
538 |
+
_stringify_func = stringify_func
|
539 |
+
|
540 |
+
if pretty_print:
|
541 |
+
stringify_func = lambda expr, **settings: \
|
542 |
+
_stringify_func(expr, order=order,
|
543 |
+
use_unicode=use_unicode,
|
544 |
+
wrap_line=wrap_line,
|
545 |
+
num_columns=num_columns,
|
546 |
+
**settings)
|
547 |
+
else:
|
548 |
+
stringify_func = \
|
549 |
+
lambda expr, **settings: _stringify_func(
|
550 |
+
expr, order=order, **settings)
|
551 |
+
|
552 |
+
if in_ipython:
|
553 |
+
mode_in_settings = settings.pop("mode", None)
|
554 |
+
if mode_in_settings:
|
555 |
+
debug("init_printing: Mode is not able to be set due to internals"
|
556 |
+
"of IPython printing")
|
557 |
+
_init_ipython_printing(ip, stringify_func, use_latex, euler,
|
558 |
+
forecolor, backcolor, fontsize, latex_mode,
|
559 |
+
print_builtin, latex_printer, scale,
|
560 |
+
**settings)
|
561 |
+
else:
|
562 |
+
_init_python_printing(stringify_func, **settings)
|
venv/lib/python3.10/site-packages/sympy/interactive/session.py
ADDED
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tools for setting up interactive sessions. """
|
2 |
+
|
3 |
+
from sympy.external.gmpy import GROUND_TYPES
|
4 |
+
from sympy.external.importtools import version_tuple
|
5 |
+
|
6 |
+
from sympy.interactive.printing import init_printing
|
7 |
+
|
8 |
+
from sympy.utilities.misc import ARCH
|
9 |
+
|
10 |
+
preexec_source = """\
|
11 |
+
from sympy import *
|
12 |
+
x, y, z, t = symbols('x y z t')
|
13 |
+
k, m, n = symbols('k m n', integer=True)
|
14 |
+
f, g, h = symbols('f g h', cls=Function)
|
15 |
+
init_printing()
|
16 |
+
"""
|
17 |
+
|
18 |
+
verbose_message = """\
|
19 |
+
These commands were executed:
|
20 |
+
%(source)s
|
21 |
+
Documentation can be found at https://docs.sympy.org/%(version)s
|
22 |
+
"""
|
23 |
+
|
24 |
+
no_ipython = """\
|
25 |
+
Could not locate IPython. Having IPython installed is greatly recommended.
|
26 |
+
See http://ipython.scipy.org for more details. If you use Debian/Ubuntu,
|
27 |
+
just install the 'ipython' package and start isympy again.
|
28 |
+
"""
|
29 |
+
|
30 |
+
|
31 |
+
def _make_message(ipython=True, quiet=False, source=None):
|
32 |
+
"""Create a banner for an interactive session. """
|
33 |
+
from sympy import __version__ as sympy_version
|
34 |
+
from sympy import SYMPY_DEBUG
|
35 |
+
|
36 |
+
import sys
|
37 |
+
import os
|
38 |
+
|
39 |
+
if quiet:
|
40 |
+
return ""
|
41 |
+
|
42 |
+
python_version = "%d.%d.%d" % sys.version_info[:3]
|
43 |
+
|
44 |
+
if ipython:
|
45 |
+
shell_name = "IPython"
|
46 |
+
else:
|
47 |
+
shell_name = "Python"
|
48 |
+
|
49 |
+
info = ['ground types: %s' % GROUND_TYPES]
|
50 |
+
|
51 |
+
cache = os.getenv('SYMPY_USE_CACHE')
|
52 |
+
|
53 |
+
if cache is not None and cache.lower() == 'no':
|
54 |
+
info.append('cache: off')
|
55 |
+
|
56 |
+
if SYMPY_DEBUG:
|
57 |
+
info.append('debugging: on')
|
58 |
+
|
59 |
+
args = shell_name, sympy_version, python_version, ARCH, ', '.join(info)
|
60 |
+
message = "%s console for SymPy %s (Python %s-%s) (%s)\n" % args
|
61 |
+
|
62 |
+
if source is None:
|
63 |
+
source = preexec_source
|
64 |
+
|
65 |
+
_source = ""
|
66 |
+
|
67 |
+
for line in source.split('\n')[:-1]:
|
68 |
+
if not line:
|
69 |
+
_source += '\n'
|
70 |
+
else:
|
71 |
+
_source += '>>> ' + line + '\n'
|
72 |
+
|
73 |
+
doc_version = sympy_version
|
74 |
+
if 'dev' in doc_version:
|
75 |
+
doc_version = "dev"
|
76 |
+
else:
|
77 |
+
doc_version = "%s/" % doc_version
|
78 |
+
|
79 |
+
message += '\n' + verbose_message % {'source': _source,
|
80 |
+
'version': doc_version}
|
81 |
+
|
82 |
+
return message
|
83 |
+
|
84 |
+
|
85 |
+
def int_to_Integer(s):
|
86 |
+
"""
|
87 |
+
Wrap integer literals with Integer.
|
88 |
+
|
89 |
+
This is based on the decistmt example from
|
90 |
+
https://docs.python.org/3/library/tokenize.html.
|
91 |
+
|
92 |
+
Only integer literals are converted. Float literals are left alone.
|
93 |
+
|
94 |
+
Examples
|
95 |
+
========
|
96 |
+
|
97 |
+
>>> from sympy import Integer # noqa: F401
|
98 |
+
>>> from sympy.interactive.session import int_to_Integer
|
99 |
+
>>> s = '1.2 + 1/2 - 0x12 + a1'
|
100 |
+
>>> int_to_Integer(s)
|
101 |
+
'1.2 +Integer (1 )/Integer (2 )-Integer (0x12 )+a1 '
|
102 |
+
>>> s = 'print (1/2)'
|
103 |
+
>>> int_to_Integer(s)
|
104 |
+
'print (Integer (1 )/Integer (2 ))'
|
105 |
+
>>> exec(s)
|
106 |
+
0.5
|
107 |
+
>>> exec(int_to_Integer(s))
|
108 |
+
1/2
|
109 |
+
"""
|
110 |
+
from tokenize import generate_tokens, untokenize, NUMBER, NAME, OP
|
111 |
+
from io import StringIO
|
112 |
+
|
113 |
+
def _is_int(num):
|
114 |
+
"""
|
115 |
+
Returns true if string value num (with token NUMBER) represents an integer.
|
116 |
+
"""
|
117 |
+
# XXX: Is there something in the standard library that will do this?
|
118 |
+
if '.' in num or 'j' in num.lower() or 'e' in num.lower():
|
119 |
+
return False
|
120 |
+
return True
|
121 |
+
|
122 |
+
result = []
|
123 |
+
g = generate_tokens(StringIO(s).readline) # tokenize the string
|
124 |
+
for toknum, tokval, _, _, _ in g:
|
125 |
+
if toknum == NUMBER and _is_int(tokval): # replace NUMBER tokens
|
126 |
+
result.extend([
|
127 |
+
(NAME, 'Integer'),
|
128 |
+
(OP, '('),
|
129 |
+
(NUMBER, tokval),
|
130 |
+
(OP, ')')
|
131 |
+
])
|
132 |
+
else:
|
133 |
+
result.append((toknum, tokval))
|
134 |
+
return untokenize(result)
|
135 |
+
|
136 |
+
|
137 |
+
def enable_automatic_int_sympification(shell):
|
138 |
+
"""
|
139 |
+
Allow IPython to automatically convert integer literals to Integer.
|
140 |
+
"""
|
141 |
+
import ast
|
142 |
+
old_run_cell = shell.run_cell
|
143 |
+
|
144 |
+
def my_run_cell(cell, *args, **kwargs):
|
145 |
+
try:
|
146 |
+
# Check the cell for syntax errors. This way, the syntax error
|
147 |
+
# will show the original input, not the transformed input. The
|
148 |
+
# downside here is that IPython magic like %timeit will not work
|
149 |
+
# with transformed input (but on the other hand, IPython magic
|
150 |
+
# that doesn't expect transformed input will continue to work).
|
151 |
+
ast.parse(cell)
|
152 |
+
except SyntaxError:
|
153 |
+
pass
|
154 |
+
else:
|
155 |
+
cell = int_to_Integer(cell)
|
156 |
+
return old_run_cell(cell, *args, **kwargs)
|
157 |
+
|
158 |
+
shell.run_cell = my_run_cell
|
159 |
+
|
160 |
+
|
161 |
+
def enable_automatic_symbols(shell):
|
162 |
+
"""Allow IPython to automatically create symbols (``isympy -a``). """
|
163 |
+
# XXX: This should perhaps use tokenize, like int_to_Integer() above.
|
164 |
+
# This would avoid re-executing the code, which can lead to subtle
|
165 |
+
# issues. For example:
|
166 |
+
#
|
167 |
+
# In [1]: a = 1
|
168 |
+
#
|
169 |
+
# In [2]: for i in range(10):
|
170 |
+
# ...: a += 1
|
171 |
+
# ...:
|
172 |
+
#
|
173 |
+
# In [3]: a
|
174 |
+
# Out[3]: 11
|
175 |
+
#
|
176 |
+
# In [4]: a = 1
|
177 |
+
#
|
178 |
+
# In [5]: for i in range(10):
|
179 |
+
# ...: a += 1
|
180 |
+
# ...: print b
|
181 |
+
# ...:
|
182 |
+
# b
|
183 |
+
# b
|
184 |
+
# b
|
185 |
+
# b
|
186 |
+
# b
|
187 |
+
# b
|
188 |
+
# b
|
189 |
+
# b
|
190 |
+
# b
|
191 |
+
# b
|
192 |
+
#
|
193 |
+
# In [6]: a
|
194 |
+
# Out[6]: 12
|
195 |
+
#
|
196 |
+
# Note how the for loop is executed again because `b` was not defined, but `a`
|
197 |
+
# was already incremented once, so the result is that it is incremented
|
198 |
+
# multiple times.
|
199 |
+
|
200 |
+
import re
|
201 |
+
re_nameerror = re.compile(
|
202 |
+
"name '(?P<symbol>[A-Za-z_][A-Za-z0-9_]*)' is not defined")
|
203 |
+
|
204 |
+
def _handler(self, etype, value, tb, tb_offset=None):
|
205 |
+
"""Handle :exc:`NameError` exception and allow injection of missing symbols. """
|
206 |
+
if etype is NameError and tb.tb_next and not tb.tb_next.tb_next:
|
207 |
+
match = re_nameerror.match(str(value))
|
208 |
+
|
209 |
+
if match is not None:
|
210 |
+
# XXX: Make sure Symbol is in scope. Otherwise you'll get infinite recursion.
|
211 |
+
self.run_cell("%(symbol)s = Symbol('%(symbol)s')" %
|
212 |
+
{'symbol': match.group("symbol")}, store_history=False)
|
213 |
+
|
214 |
+
try:
|
215 |
+
code = self.user_ns['In'][-1]
|
216 |
+
except (KeyError, IndexError):
|
217 |
+
pass
|
218 |
+
else:
|
219 |
+
self.run_cell(code, store_history=False)
|
220 |
+
return None
|
221 |
+
finally:
|
222 |
+
self.run_cell("del %s" % match.group("symbol"),
|
223 |
+
store_history=False)
|
224 |
+
|
225 |
+
stb = self.InteractiveTB.structured_traceback(
|
226 |
+
etype, value, tb, tb_offset=tb_offset)
|
227 |
+
self._showtraceback(etype, value, stb)
|
228 |
+
|
229 |
+
shell.set_custom_exc((NameError,), _handler)
|
230 |
+
|
231 |
+
|
232 |
+
def init_ipython_session(shell=None, argv=[], auto_symbols=False, auto_int_to_Integer=False):
|
233 |
+
"""Construct new IPython session. """
|
234 |
+
import IPython
|
235 |
+
|
236 |
+
if version_tuple(IPython.__version__) >= version_tuple('0.11'):
|
237 |
+
if not shell:
|
238 |
+
# use an app to parse the command line, and init config
|
239 |
+
# IPython 1.0 deprecates the frontend module, so we import directly
|
240 |
+
# from the terminal module to prevent a deprecation message from being
|
241 |
+
# shown.
|
242 |
+
if version_tuple(IPython.__version__) >= version_tuple('1.0'):
|
243 |
+
from IPython.terminal import ipapp
|
244 |
+
else:
|
245 |
+
from IPython.frontend.terminal import ipapp
|
246 |
+
app = ipapp.TerminalIPythonApp()
|
247 |
+
|
248 |
+
# don't draw IPython banner during initialization:
|
249 |
+
app.display_banner = False
|
250 |
+
app.initialize(argv)
|
251 |
+
|
252 |
+
shell = app.shell
|
253 |
+
|
254 |
+
if auto_symbols:
|
255 |
+
enable_automatic_symbols(shell)
|
256 |
+
if auto_int_to_Integer:
|
257 |
+
enable_automatic_int_sympification(shell)
|
258 |
+
|
259 |
+
return shell
|
260 |
+
else:
|
261 |
+
from IPython.Shell import make_IPython
|
262 |
+
return make_IPython(argv)
|
263 |
+
|
264 |
+
|
265 |
+
def init_python_session():
|
266 |
+
"""Construct new Python session. """
|
267 |
+
from code import InteractiveConsole
|
268 |
+
|
269 |
+
class SymPyConsole(InteractiveConsole):
|
270 |
+
"""An interactive console with readline support. """
|
271 |
+
|
272 |
+
def __init__(self):
|
273 |
+
ns_locals = {}
|
274 |
+
InteractiveConsole.__init__(self, locals=ns_locals)
|
275 |
+
try:
|
276 |
+
import rlcompleter
|
277 |
+
import readline
|
278 |
+
except ImportError:
|
279 |
+
pass
|
280 |
+
else:
|
281 |
+
import os
|
282 |
+
import atexit
|
283 |
+
|
284 |
+
readline.set_completer(rlcompleter.Completer(ns_locals).complete)
|
285 |
+
readline.parse_and_bind('tab: complete')
|
286 |
+
|
287 |
+
if hasattr(readline, 'read_history_file'):
|
288 |
+
history = os.path.expanduser('~/.sympy-history')
|
289 |
+
|
290 |
+
try:
|
291 |
+
readline.read_history_file(history)
|
292 |
+
except OSError:
|
293 |
+
pass
|
294 |
+
|
295 |
+
atexit.register(readline.write_history_file, history)
|
296 |
+
|
297 |
+
return SymPyConsole()
|
298 |
+
|
299 |
+
|
300 |
+
def init_session(ipython=None, pretty_print=True, order=None,
|
301 |
+
use_unicode=None, use_latex=None, quiet=False, auto_symbols=False,
|
302 |
+
auto_int_to_Integer=False, str_printer=None, pretty_printer=None,
|
303 |
+
latex_printer=None, argv=[]):
|
304 |
+
"""
|
305 |
+
Initialize an embedded IPython or Python session. The IPython session is
|
306 |
+
initiated with the --pylab option, without the numpy imports, so that
|
307 |
+
matplotlib plotting can be interactive.
|
308 |
+
|
309 |
+
Parameters
|
310 |
+
==========
|
311 |
+
|
312 |
+
pretty_print: boolean
|
313 |
+
If True, use pretty_print to stringify;
|
314 |
+
if False, use sstrrepr to stringify.
|
315 |
+
order: string or None
|
316 |
+
There are a few different settings for this parameter:
|
317 |
+
lex (default), which is lexographic order;
|
318 |
+
grlex, which is graded lexographic order;
|
319 |
+
grevlex, which is reversed graded lexographic order;
|
320 |
+
old, which is used for compatibility reasons and for long expressions;
|
321 |
+
None, which sets it to lex.
|
322 |
+
use_unicode: boolean or None
|
323 |
+
If True, use unicode characters;
|
324 |
+
if False, do not use unicode characters.
|
325 |
+
use_latex: boolean or None
|
326 |
+
If True, use latex rendering if IPython GUI's;
|
327 |
+
if False, do not use latex rendering.
|
328 |
+
quiet: boolean
|
329 |
+
If True, init_session will not print messages regarding its status;
|
330 |
+
if False, init_session will print messages regarding its status.
|
331 |
+
auto_symbols: boolean
|
332 |
+
If True, IPython will automatically create symbols for you.
|
333 |
+
If False, it will not.
|
334 |
+
The default is False.
|
335 |
+
auto_int_to_Integer: boolean
|
336 |
+
If True, IPython will automatically wrap int literals with Integer, so
|
337 |
+
that things like 1/2 give Rational(1, 2).
|
338 |
+
If False, it will not.
|
339 |
+
The default is False.
|
340 |
+
ipython: boolean or None
|
341 |
+
If True, printing will initialize for an IPython console;
|
342 |
+
if False, printing will initialize for a normal console;
|
343 |
+
The default is None, which automatically determines whether we are in
|
344 |
+
an ipython instance or not.
|
345 |
+
str_printer: function, optional, default=None
|
346 |
+
A custom string printer function. This should mimic
|
347 |
+
sympy.printing.sstrrepr().
|
348 |
+
pretty_printer: function, optional, default=None
|
349 |
+
A custom pretty printer. This should mimic sympy.printing.pretty().
|
350 |
+
latex_printer: function, optional, default=None
|
351 |
+
A custom LaTeX printer. This should mimic sympy.printing.latex()
|
352 |
+
This should mimic sympy.printing.latex().
|
353 |
+
argv: list of arguments for IPython
|
354 |
+
See sympy.bin.isympy for options that can be used to initialize IPython.
|
355 |
+
|
356 |
+
See Also
|
357 |
+
========
|
358 |
+
|
359 |
+
sympy.interactive.printing.init_printing: for examples and the rest of the parameters.
|
360 |
+
|
361 |
+
|
362 |
+
Examples
|
363 |
+
========
|
364 |
+
|
365 |
+
>>> from sympy import init_session, Symbol, sin, sqrt
|
366 |
+
>>> sin(x) #doctest: +SKIP
|
367 |
+
NameError: name 'x' is not defined
|
368 |
+
>>> init_session() #doctest: +SKIP
|
369 |
+
>>> sin(x) #doctest: +SKIP
|
370 |
+
sin(x)
|
371 |
+
>>> sqrt(5) #doctest: +SKIP
|
372 |
+
___
|
373 |
+
\\/ 5
|
374 |
+
>>> init_session(pretty_print=False) #doctest: +SKIP
|
375 |
+
>>> sqrt(5) #doctest: +SKIP
|
376 |
+
sqrt(5)
|
377 |
+
>>> y + x + y**2 + x**2 #doctest: +SKIP
|
378 |
+
x**2 + x + y**2 + y
|
379 |
+
>>> init_session(order='grlex') #doctest: +SKIP
|
380 |
+
>>> y + x + y**2 + x**2 #doctest: +SKIP
|
381 |
+
x**2 + y**2 + x + y
|
382 |
+
>>> init_session(order='grevlex') #doctest: +SKIP
|
383 |
+
>>> y * x**2 + x * y**2 #doctest: +SKIP
|
384 |
+
x**2*y + x*y**2
|
385 |
+
>>> init_session(order='old') #doctest: +SKIP
|
386 |
+
>>> x**2 + y**2 + x + y #doctest: +SKIP
|
387 |
+
x + y + x**2 + y**2
|
388 |
+
>>> theta = Symbol('theta') #doctest: +SKIP
|
389 |
+
>>> theta #doctest: +SKIP
|
390 |
+
theta
|
391 |
+
>>> init_session(use_unicode=True) #doctest: +SKIP
|
392 |
+
>>> theta # doctest: +SKIP
|
393 |
+
\u03b8
|
394 |
+
"""
|
395 |
+
import sys
|
396 |
+
|
397 |
+
in_ipython = False
|
398 |
+
|
399 |
+
if ipython is not False:
|
400 |
+
try:
|
401 |
+
import IPython
|
402 |
+
except ImportError:
|
403 |
+
if ipython is True:
|
404 |
+
raise RuntimeError("IPython is not available on this system")
|
405 |
+
ip = None
|
406 |
+
else:
|
407 |
+
try:
|
408 |
+
from IPython import get_ipython
|
409 |
+
ip = get_ipython()
|
410 |
+
except ImportError:
|
411 |
+
ip = None
|
412 |
+
in_ipython = bool(ip)
|
413 |
+
if ipython is None:
|
414 |
+
ipython = in_ipython
|
415 |
+
|
416 |
+
if ipython is False:
|
417 |
+
ip = init_python_session()
|
418 |
+
mainloop = ip.interact
|
419 |
+
else:
|
420 |
+
ip = init_ipython_session(ip, argv=argv, auto_symbols=auto_symbols,
|
421 |
+
auto_int_to_Integer=auto_int_to_Integer)
|
422 |
+
|
423 |
+
if version_tuple(IPython.__version__) >= version_tuple('0.11'):
|
424 |
+
# runsource is gone, use run_cell instead, which doesn't
|
425 |
+
# take a symbol arg. The second arg is `store_history`,
|
426 |
+
# and False means don't add the line to IPython's history.
|
427 |
+
ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
|
428 |
+
|
429 |
+
# Enable interactive plotting using pylab.
|
430 |
+
try:
|
431 |
+
ip.enable_pylab(import_all=False)
|
432 |
+
except Exception:
|
433 |
+
# Causes an import error if matplotlib is not installed.
|
434 |
+
# Causes other errors (depending on the backend) if there
|
435 |
+
# is no display, or if there is some problem in the
|
436 |
+
# backend, so we have a bare "except Exception" here
|
437 |
+
pass
|
438 |
+
if not in_ipython:
|
439 |
+
mainloop = ip.mainloop
|
440 |
+
|
441 |
+
if auto_symbols and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')):
|
442 |
+
raise RuntimeError("automatic construction of symbols is possible only in IPython 0.11 or above")
|
443 |
+
if auto_int_to_Integer and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')):
|
444 |
+
raise RuntimeError("automatic int to Integer transformation is possible only in IPython 0.11 or above")
|
445 |
+
|
446 |
+
_preexec_source = preexec_source
|
447 |
+
|
448 |
+
ip.runsource(_preexec_source, symbol='exec')
|
449 |
+
init_printing(pretty_print=pretty_print, order=order,
|
450 |
+
use_unicode=use_unicode, use_latex=use_latex, ip=ip,
|
451 |
+
str_printer=str_printer, pretty_printer=pretty_printer,
|
452 |
+
latex_printer=latex_printer)
|
453 |
+
|
454 |
+
message = _make_message(ipython, quiet, _preexec_source)
|
455 |
+
|
456 |
+
if not in_ipython:
|
457 |
+
print(message)
|
458 |
+
mainloop()
|
459 |
+
sys.exit('Exiting ...')
|
460 |
+
else:
|
461 |
+
print(message)
|
462 |
+
import atexit
|
463 |
+
atexit.register(lambda: print("Exiting ...\n"))
|
venv/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (191 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_interactive.cpython-310.pyc
ADDED
Binary file (700 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_ipython.cpython-310.pyc
ADDED
Binary file (6.66 kB). View file
|
|
venv/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 '
|
venv/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py
ADDED
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tests of tools for setting up interactive IPython sessions. """
|
2 |
+
|
3 |
+
from sympy.interactive.session import (init_ipython_session,
|
4 |
+
enable_automatic_symbols, enable_automatic_int_sympification)
|
5 |
+
|
6 |
+
from sympy.core import Symbol, Rational, Integer
|
7 |
+
from sympy.external import import_module
|
8 |
+
from sympy.testing.pytest import raises
|
9 |
+
|
10 |
+
# TODO: The code below could be made more granular with something like:
|
11 |
+
#
|
12 |
+
# @requires('IPython', version=">=0.11")
|
13 |
+
# def test_automatic_symbols(ipython):
|
14 |
+
|
15 |
+
ipython = import_module("IPython", min_module_version="0.11")
|
16 |
+
|
17 |
+
if not ipython:
|
18 |
+
#bin/test will not execute any tests now
|
19 |
+
disabled = True
|
20 |
+
|
21 |
+
# WARNING: These tests will modify the existing IPython environment. IPython
|
22 |
+
# uses a single instance for its interpreter, so there is no way to isolate
|
23 |
+
# the test from another IPython session. It also means that if this test is
|
24 |
+
# run twice in the same Python session it will fail. This isn't usually a
|
25 |
+
# problem because the test suite is run in a subprocess by default, but if the
|
26 |
+
# tests are run with subprocess=False it can pollute the current IPython
|
27 |
+
# session. See the discussion in issue #15149.
|
28 |
+
|
29 |
+
def test_automatic_symbols():
|
30 |
+
# NOTE: Because of the way the hook works, you have to use run_cell(code,
|
31 |
+
# True). This means that the code must have no Out, or it will be printed
|
32 |
+
# during the tests.
|
33 |
+
app = init_ipython_session()
|
34 |
+
app.run_cell("from sympy import *")
|
35 |
+
|
36 |
+
enable_automatic_symbols(app)
|
37 |
+
|
38 |
+
symbol = "verylongsymbolname"
|
39 |
+
assert symbol not in app.user_ns
|
40 |
+
app.run_cell("a = %s" % symbol, True)
|
41 |
+
assert symbol not in app.user_ns
|
42 |
+
app.run_cell("a = type(%s)" % symbol, True)
|
43 |
+
assert app.user_ns['a'] == Symbol
|
44 |
+
app.run_cell("%s = Symbol('%s')" % (symbol, symbol), True)
|
45 |
+
assert symbol in app.user_ns
|
46 |
+
|
47 |
+
# Check that built-in names aren't overridden
|
48 |
+
app.run_cell("a = all == __builtin__.all", True)
|
49 |
+
assert "all" not in app.user_ns
|
50 |
+
assert app.user_ns['a'] is True
|
51 |
+
|
52 |
+
# Check that SymPy names aren't overridden
|
53 |
+
app.run_cell("import sympy")
|
54 |
+
app.run_cell("a = factorial == sympy.factorial", True)
|
55 |
+
assert app.user_ns['a'] is True
|
56 |
+
|
57 |
+
|
58 |
+
def test_int_to_Integer():
|
59 |
+
# XXX: Warning, don't test with == here. 0.5 == Rational(1, 2) is True!
|
60 |
+
app = init_ipython_session()
|
61 |
+
app.run_cell("from sympy import Integer")
|
62 |
+
app.run_cell("a = 1")
|
63 |
+
assert isinstance(app.user_ns['a'], int)
|
64 |
+
|
65 |
+
enable_automatic_int_sympification(app)
|
66 |
+
app.run_cell("a = 1/2")
|
67 |
+
assert isinstance(app.user_ns['a'], Rational)
|
68 |
+
app.run_cell("a = 1")
|
69 |
+
assert isinstance(app.user_ns['a'], Integer)
|
70 |
+
app.run_cell("a = int(1)")
|
71 |
+
assert isinstance(app.user_ns['a'], int)
|
72 |
+
app.run_cell("a = (1/\n2)")
|
73 |
+
assert app.user_ns['a'] == Rational(1, 2)
|
74 |
+
# TODO: How can we test that the output of a SyntaxError is the original
|
75 |
+
# input, not the transformed input?
|
76 |
+
|
77 |
+
|
78 |
+
def test_ipythonprinting():
|
79 |
+
# Initialize and setup IPython session
|
80 |
+
app = init_ipython_session()
|
81 |
+
app.run_cell("ip = get_ipython()")
|
82 |
+
app.run_cell("inst = ip.instance()")
|
83 |
+
app.run_cell("format = inst.display_formatter.format")
|
84 |
+
app.run_cell("from sympy import Symbol")
|
85 |
+
|
86 |
+
# Printing without printing extension
|
87 |
+
app.run_cell("a = format(Symbol('pi'))")
|
88 |
+
app.run_cell("a2 = format(Symbol('pi')**2)")
|
89 |
+
# Deal with API change starting at IPython 1.0
|
90 |
+
if int(ipython.__version__.split(".")[0]) < 1:
|
91 |
+
assert app.user_ns['a']['text/plain'] == "pi"
|
92 |
+
assert app.user_ns['a2']['text/plain'] == "pi**2"
|
93 |
+
else:
|
94 |
+
assert app.user_ns['a'][0]['text/plain'] == "pi"
|
95 |
+
assert app.user_ns['a2'][0]['text/plain'] == "pi**2"
|
96 |
+
|
97 |
+
# Load printing extension
|
98 |
+
app.run_cell("from sympy import init_printing")
|
99 |
+
app.run_cell("init_printing()")
|
100 |
+
# Printing with printing extension
|
101 |
+
app.run_cell("a = format(Symbol('pi'))")
|
102 |
+
app.run_cell("a2 = format(Symbol('pi')**2)")
|
103 |
+
# Deal with API change starting at IPython 1.0
|
104 |
+
if int(ipython.__version__.split(".")[0]) < 1:
|
105 |
+
assert app.user_ns['a']['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
|
106 |
+
assert app.user_ns['a2']['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ')
|
107 |
+
else:
|
108 |
+
assert app.user_ns['a'][0]['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
|
109 |
+
assert app.user_ns['a2'][0]['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ')
|
110 |
+
|
111 |
+
|
112 |
+
def test_print_builtin_option():
|
113 |
+
# Initialize and setup IPython session
|
114 |
+
app = init_ipython_session()
|
115 |
+
app.run_cell("ip = get_ipython()")
|
116 |
+
app.run_cell("inst = ip.instance()")
|
117 |
+
app.run_cell("format = inst.display_formatter.format")
|
118 |
+
app.run_cell("from sympy import Symbol")
|
119 |
+
app.run_cell("from sympy import init_printing")
|
120 |
+
|
121 |
+
app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
|
122 |
+
# Deal with API change starting at IPython 1.0
|
123 |
+
if int(ipython.__version__.split(".")[0]) < 1:
|
124 |
+
text = app.user_ns['a']['text/plain']
|
125 |
+
raises(KeyError, lambda: app.user_ns['a']['text/latex'])
|
126 |
+
else:
|
127 |
+
text = app.user_ns['a'][0]['text/plain']
|
128 |
+
raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
|
129 |
+
# XXX: How can we make this ignore the terminal width? This test fails if
|
130 |
+
# the terminal is too narrow.
|
131 |
+
assert text in ("{pi: 3.14, n_i: 3}",
|
132 |
+
'{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
|
133 |
+
"{n_i: 3, pi: 3.14}",
|
134 |
+
'{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
|
135 |
+
|
136 |
+
# If we enable the default printing, then the dictionary's should render
|
137 |
+
# as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
|
138 |
+
app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
|
139 |
+
app.run_cell("init_printing(use_latex=True)")
|
140 |
+
app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
|
141 |
+
# Deal with API change starting at IPython 1.0
|
142 |
+
if int(ipython.__version__.split(".")[0]) < 1:
|
143 |
+
text = app.user_ns['a']['text/plain']
|
144 |
+
latex = app.user_ns['a']['text/latex']
|
145 |
+
else:
|
146 |
+
text = app.user_ns['a'][0]['text/plain']
|
147 |
+
latex = app.user_ns['a'][0]['text/latex']
|
148 |
+
assert text in ("{pi: 3.14, n_i: 3}",
|
149 |
+
'{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
|
150 |
+
"{n_i: 3, pi: 3.14}",
|
151 |
+
'{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
|
152 |
+
assert latex == r'$\displaystyle \left\{ n_{i} : 3, \ \pi : 3.14\right\}$'
|
153 |
+
|
154 |
+
# Objects with an _latex overload should also be handled by our tuple
|
155 |
+
# printer.
|
156 |
+
app.run_cell("""\
|
157 |
+
class WithOverload:
|
158 |
+
def _latex(self, printer):
|
159 |
+
return r"\\LaTeX"
|
160 |
+
""")
|
161 |
+
app.run_cell("a = format((WithOverload(),))")
|
162 |
+
# Deal with API change starting at IPython 1.0
|
163 |
+
if int(ipython.__version__.split(".")[0]) < 1:
|
164 |
+
latex = app.user_ns['a']['text/latex']
|
165 |
+
else:
|
166 |
+
latex = app.user_ns['a'][0]['text/latex']
|
167 |
+
assert latex == r'$\displaystyle \left( \LaTeX,\right)$'
|
168 |
+
|
169 |
+
app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
|
170 |
+
app.run_cell("init_printing(use_latex=True, print_builtin=False)")
|
171 |
+
app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
|
172 |
+
# Deal with API change starting at IPython 1.0
|
173 |
+
if int(ipython.__version__.split(".")[0]) < 1:
|
174 |
+
text = app.user_ns['a']['text/plain']
|
175 |
+
raises(KeyError, lambda: app.user_ns['a']['text/latex'])
|
176 |
+
else:
|
177 |
+
text = app.user_ns['a'][0]['text/plain']
|
178 |
+
raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
|
179 |
+
# Note : In Python 3 we have one text type: str which holds Unicode data
|
180 |
+
# and two byte types bytes and bytearray.
|
181 |
+
# Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}'
|
182 |
+
# Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}'
|
183 |
+
assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}")
|
184 |
+
|
185 |
+
|
186 |
+
def test_builtin_containers():
|
187 |
+
# Initialize and setup IPython session
|
188 |
+
app = init_ipython_session()
|
189 |
+
app.run_cell("ip = get_ipython()")
|
190 |
+
app.run_cell("inst = ip.instance()")
|
191 |
+
app.run_cell("format = inst.display_formatter.format")
|
192 |
+
app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
|
193 |
+
app.run_cell("from sympy import init_printing, Matrix")
|
194 |
+
app.run_cell('init_printing(use_latex=True, use_unicode=False)')
|
195 |
+
|
196 |
+
# Make sure containers that shouldn't pretty print don't.
|
197 |
+
app.run_cell('a = format((True, False))')
|
198 |
+
app.run_cell('import sys')
|
199 |
+
app.run_cell('b = format(sys.flags)')
|
200 |
+
app.run_cell('c = format((Matrix([1, 2]),))')
|
201 |
+
# Deal with API change starting at IPython 1.0
|
202 |
+
if int(ipython.__version__.split(".")[0]) < 1:
|
203 |
+
assert app.user_ns['a']['text/plain'] == '(True, False)'
|
204 |
+
assert 'text/latex' not in app.user_ns['a']
|
205 |
+
assert app.user_ns['b']['text/plain'][:10] == 'sys.flags('
|
206 |
+
assert 'text/latex' not in app.user_ns['b']
|
207 |
+
assert app.user_ns['c']['text/plain'] == \
|
208 |
+
"""\
|
209 |
+
[1] \n\
|
210 |
+
([ ],)
|
211 |
+
[2] \
|
212 |
+
"""
|
213 |
+
assert app.user_ns['c']['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
|
214 |
+
else:
|
215 |
+
assert app.user_ns['a'][0]['text/plain'] == '(True, False)'
|
216 |
+
assert 'text/latex' not in app.user_ns['a'][0]
|
217 |
+
assert app.user_ns['b'][0]['text/plain'][:10] == 'sys.flags('
|
218 |
+
assert 'text/latex' not in app.user_ns['b'][0]
|
219 |
+
assert app.user_ns['c'][0]['text/plain'] == \
|
220 |
+
"""\
|
221 |
+
[1] \n\
|
222 |
+
([ ],)
|
223 |
+
[2] \
|
224 |
+
"""
|
225 |
+
assert app.user_ns['c'][0]['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
|
226 |
+
|
227 |
+
def test_matplotlib_bad_latex():
|
228 |
+
# Initialize and setup IPython session
|
229 |
+
app = init_ipython_session()
|
230 |
+
app.run_cell("import IPython")
|
231 |
+
app.run_cell("ip = get_ipython()")
|
232 |
+
app.run_cell("inst = ip.instance()")
|
233 |
+
app.run_cell("format = inst.display_formatter.format")
|
234 |
+
app.run_cell("from sympy import init_printing, Matrix")
|
235 |
+
app.run_cell("init_printing(use_latex='matplotlib')")
|
236 |
+
|
237 |
+
# The png formatter is not enabled by default in this context
|
238 |
+
app.run_cell("inst.display_formatter.formatters['image/png'].enabled = True")
|
239 |
+
|
240 |
+
# Make sure no warnings are raised by IPython
|
241 |
+
app.run_cell("import warnings")
|
242 |
+
# IPython.core.formatters.FormatterWarning was introduced in IPython 2.0
|
243 |
+
if int(ipython.__version__.split(".")[0]) < 2:
|
244 |
+
app.run_cell("warnings.simplefilter('error')")
|
245 |
+
else:
|
246 |
+
app.run_cell("warnings.simplefilter('error', IPython.core.formatters.FormatterWarning)")
|
247 |
+
|
248 |
+
# This should not raise an exception
|
249 |
+
app.run_cell("a = format(Matrix([1, 2, 3]))")
|
250 |
+
|
251 |
+
# issue 9799
|
252 |
+
app.run_cell("from sympy import Piecewise, Symbol, Eq")
|
253 |
+
app.run_cell("x = Symbol('x'); pw = format(Piecewise((1, Eq(x, 0)), (0, True)))")
|
254 |
+
|
255 |
+
|
256 |
+
def test_override_repr_latex():
|
257 |
+
# Initialize and setup IPython session
|
258 |
+
app = init_ipython_session()
|
259 |
+
app.run_cell("import IPython")
|
260 |
+
app.run_cell("ip = get_ipython()")
|
261 |
+
app.run_cell("inst = ip.instance()")
|
262 |
+
app.run_cell("format = inst.display_formatter.format")
|
263 |
+
app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
|
264 |
+
app.run_cell("from sympy import init_printing")
|
265 |
+
app.run_cell("from sympy import Symbol")
|
266 |
+
app.run_cell("init_printing(use_latex=True)")
|
267 |
+
app.run_cell("""\
|
268 |
+
class SymbolWithOverload(Symbol):
|
269 |
+
def _repr_latex_(self):
|
270 |
+
return r"Hello " + super()._repr_latex_() + " world"
|
271 |
+
""")
|
272 |
+
app.run_cell("a = format(SymbolWithOverload('s'))")
|
273 |
+
|
274 |
+
if int(ipython.__version__.split(".")[0]) < 1:
|
275 |
+
latex = app.user_ns['a']['text/latex']
|
276 |
+
else:
|
277 |
+
latex = app.user_ns['a'][0]['text/latex']
|
278 |
+
assert latex == r'Hello $\displaystyle s$ world'
|
venv/lib/python3.10/site-packages/sympy/interactive/traversal.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.basic import Basic
|
2 |
+
from sympy.printing import pprint
|
3 |
+
|
4 |
+
import random
|
5 |
+
|
6 |
+
def interactive_traversal(expr):
|
7 |
+
"""Traverse a tree asking a user which branch to choose. """
|
8 |
+
|
9 |
+
RED, BRED = '\033[0;31m', '\033[1;31m'
|
10 |
+
GREEN, BGREEN = '\033[0;32m', '\033[1;32m'
|
11 |
+
YELLOW, BYELLOW = '\033[0;33m', '\033[1;33m' # noqa
|
12 |
+
BLUE, BBLUE = '\033[0;34m', '\033[1;34m' # noqa
|
13 |
+
MAGENTA, BMAGENTA = '\033[0;35m', '\033[1;35m'# noqa
|
14 |
+
CYAN, BCYAN = '\033[0;36m', '\033[1;36m' # noqa
|
15 |
+
END = '\033[0m'
|
16 |
+
|
17 |
+
def cprint(*args):
|
18 |
+
print("".join(map(str, args)) + END)
|
19 |
+
|
20 |
+
def _interactive_traversal(expr, stage):
|
21 |
+
if stage > 0:
|
22 |
+
print()
|
23 |
+
|
24 |
+
cprint("Current expression (stage ", BYELLOW, stage, END, "):")
|
25 |
+
print(BCYAN)
|
26 |
+
pprint(expr)
|
27 |
+
print(END)
|
28 |
+
|
29 |
+
if isinstance(expr, Basic):
|
30 |
+
if expr.is_Add:
|
31 |
+
args = expr.as_ordered_terms()
|
32 |
+
elif expr.is_Mul:
|
33 |
+
args = expr.as_ordered_factors()
|
34 |
+
else:
|
35 |
+
args = expr.args
|
36 |
+
elif hasattr(expr, "__iter__"):
|
37 |
+
args = list(expr)
|
38 |
+
else:
|
39 |
+
return expr
|
40 |
+
|
41 |
+
n_args = len(args)
|
42 |
+
|
43 |
+
if not n_args:
|
44 |
+
return expr
|
45 |
+
|
46 |
+
for i, arg in enumerate(args):
|
47 |
+
cprint(GREEN, "[", BGREEN, i, GREEN, "] ", BLUE, type(arg), END)
|
48 |
+
pprint(arg)
|
49 |
+
print()
|
50 |
+
|
51 |
+
if n_args == 1:
|
52 |
+
choices = '0'
|
53 |
+
else:
|
54 |
+
choices = '0-%d' % (n_args - 1)
|
55 |
+
|
56 |
+
try:
|
57 |
+
choice = input("Your choice [%s,f,l,r,d,?]: " % choices)
|
58 |
+
except EOFError:
|
59 |
+
result = expr
|
60 |
+
print()
|
61 |
+
else:
|
62 |
+
if choice == '?':
|
63 |
+
cprint(RED, "%s - select subexpression with the given index" %
|
64 |
+
choices)
|
65 |
+
cprint(RED, "f - select the first subexpression")
|
66 |
+
cprint(RED, "l - select the last subexpression")
|
67 |
+
cprint(RED, "r - select a random subexpression")
|
68 |
+
cprint(RED, "d - done\n")
|
69 |
+
|
70 |
+
result = _interactive_traversal(expr, stage)
|
71 |
+
elif choice in ('d', ''):
|
72 |
+
result = expr
|
73 |
+
elif choice == 'f':
|
74 |
+
result = _interactive_traversal(args[0], stage + 1)
|
75 |
+
elif choice == 'l':
|
76 |
+
result = _interactive_traversal(args[-1], stage + 1)
|
77 |
+
elif choice == 'r':
|
78 |
+
result = _interactive_traversal(random.choice(args), stage + 1)
|
79 |
+
else:
|
80 |
+
try:
|
81 |
+
choice = int(choice)
|
82 |
+
except ValueError:
|
83 |
+
cprint(BRED,
|
84 |
+
"Choice must be a number in %s range\n" % choices)
|
85 |
+
result = _interactive_traversal(expr, stage)
|
86 |
+
else:
|
87 |
+
if choice < 0 or choice >= n_args:
|
88 |
+
cprint(BRED, "Choice must be in %s range\n" % choices)
|
89 |
+
result = _interactive_traversal(expr, stage)
|
90 |
+
else:
|
91 |
+
result = _interactive_traversal(args[choice], stage + 1)
|
92 |
+
|
93 |
+
return result
|
94 |
+
|
95 |
+
return _interactive_traversal(expr, 0)
|
venv/lib/python3.10/site-packages/sympy/sandbox/__init__.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Sandbox module of SymPy.
|
3 |
+
|
4 |
+
This module contains experimental code, use at your own risk!
|
5 |
+
|
6 |
+
There is no warranty that this code will still be located here in future
|
7 |
+
versions of SymPy.
|
8 |
+
"""
|
venv/lib/python3.10/site-packages/sympy/sandbox/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (375 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/sandbox/__pycache__/indexed_integrals.cpython-310.pyc
ADDED
Binary file (2.57 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/sandbox/indexed_integrals.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.tensor import Indexed
|
2 |
+
from sympy.core.containers import Tuple
|
3 |
+
from sympy.core.symbol import Dummy
|
4 |
+
from sympy.core.sympify import sympify
|
5 |
+
from sympy.integrals.integrals import Integral
|
6 |
+
|
7 |
+
|
8 |
+
class IndexedIntegral(Integral):
|
9 |
+
"""
|
10 |
+
Experimental class to test integration by indexed variables.
|
11 |
+
|
12 |
+
Usage is analogue to ``Integral``, it simply adds awareness of
|
13 |
+
integration over indices.
|
14 |
+
|
15 |
+
Contraction of non-identical index symbols referring to the same
|
16 |
+
``IndexedBase`` is not yet supported.
|
17 |
+
|
18 |
+
Examples
|
19 |
+
========
|
20 |
+
|
21 |
+
>>> from sympy.sandbox.indexed_integrals import IndexedIntegral
|
22 |
+
>>> from sympy import IndexedBase, symbols
|
23 |
+
>>> A = IndexedBase('A')
|
24 |
+
>>> i, j = symbols('i j', integer=True)
|
25 |
+
>>> ii = IndexedIntegral(A[i], A[i])
|
26 |
+
>>> ii
|
27 |
+
Integral(_A[i], _A[i])
|
28 |
+
>>> ii.doit()
|
29 |
+
A[i]**2/2
|
30 |
+
|
31 |
+
If the indices are different, indexed objects are considered to be
|
32 |
+
different variables:
|
33 |
+
|
34 |
+
>>> i2 = IndexedIntegral(A[j], A[i])
|
35 |
+
>>> i2
|
36 |
+
Integral(A[j], _A[i])
|
37 |
+
>>> i2.doit()
|
38 |
+
A[i]*A[j]
|
39 |
+
"""
|
40 |
+
|
41 |
+
def __new__(cls, function, *limits, **assumptions):
|
42 |
+
repl, limits = IndexedIntegral._indexed_process_limits(limits)
|
43 |
+
function = sympify(function)
|
44 |
+
function = function.xreplace(repl)
|
45 |
+
obj = Integral.__new__(cls, function, *limits, **assumptions)
|
46 |
+
obj._indexed_repl = repl
|
47 |
+
obj._indexed_reverse_repl = {val: key for key, val in repl.items()}
|
48 |
+
return obj
|
49 |
+
|
50 |
+
def doit(self):
|
51 |
+
res = super().doit()
|
52 |
+
return res.xreplace(self._indexed_reverse_repl)
|
53 |
+
|
54 |
+
@staticmethod
|
55 |
+
def _indexed_process_limits(limits):
|
56 |
+
repl = {}
|
57 |
+
newlimits = []
|
58 |
+
for i in limits:
|
59 |
+
if isinstance(i, (tuple, list, Tuple)):
|
60 |
+
v = i[0]
|
61 |
+
vrest = i[1:]
|
62 |
+
else:
|
63 |
+
v = i
|
64 |
+
vrest = ()
|
65 |
+
if isinstance(v, Indexed):
|
66 |
+
if v not in repl:
|
67 |
+
r = Dummy(str(v))
|
68 |
+
repl[v] = r
|
69 |
+
newlimits.append((r,)+vrest)
|
70 |
+
else:
|
71 |
+
newlimits.append(i)
|
72 |
+
return repl, newlimits
|
venv/lib/python3.10/site-packages/sympy/sandbox/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (187 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/test_indexed_integrals.cpython-310.pyc
ADDED
Binary file (1.31 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/sandbox/tests/test_indexed_integrals.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.sandbox.indexed_integrals import IndexedIntegral
|
2 |
+
from sympy.core.symbol import symbols
|
3 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
4 |
+
from sympy.tensor.indexed import (Idx, IndexedBase)
|
5 |
+
|
6 |
+
|
7 |
+
def test_indexed_integrals():
|
8 |
+
A = IndexedBase('A')
|
9 |
+
i, j = symbols('i j', integer=True)
|
10 |
+
a1, a2 = symbols('a1:3', cls=Idx)
|
11 |
+
assert isinstance(a1, Idx)
|
12 |
+
|
13 |
+
assert IndexedIntegral(1, A[i]).doit() == A[i]
|
14 |
+
assert IndexedIntegral(A[i], A[i]).doit() == A[i] ** 2 / 2
|
15 |
+
assert IndexedIntegral(A[j], A[i]).doit() == A[i] * A[j]
|
16 |
+
assert IndexedIntegral(A[i] * A[j], A[i]).doit() == A[i] ** 2 * A[j] / 2
|
17 |
+
assert IndexedIntegral(sin(A[i]), A[i]).doit() == -cos(A[i])
|
18 |
+
assert IndexedIntegral(sin(A[j]), A[i]).doit() == sin(A[j]) * A[i]
|
19 |
+
|
20 |
+
assert IndexedIntegral(1, A[a1]).doit() == A[a1]
|
21 |
+
assert IndexedIntegral(A[a1], A[a1]).doit() == A[a1] ** 2 / 2
|
22 |
+
assert IndexedIntegral(A[a2], A[a1]).doit() == A[a1] * A[a2]
|
23 |
+
assert IndexedIntegral(A[a1] * A[a2], A[a1]).doit() == A[a1] ** 2 * A[a2] / 2
|
24 |
+
assert IndexedIntegral(sin(A[a1]), A[a1]).doit() == -cos(A[a1])
|
25 |
+
assert IndexedIntegral(sin(A[a2]), A[a1]).doit() == sin(A[a2]) * A[a1]
|
venv/lib/python3.10/site-packages/sympy/series/__init__.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""A module that handles series: find a limit, order the series etc.
|
2 |
+
"""
|
3 |
+
from .order import Order
|
4 |
+
from .limits import limit, Limit
|
5 |
+
from .gruntz import gruntz
|
6 |
+
from .series import series
|
7 |
+
from .approximants import approximants
|
8 |
+
from .residues import residue
|
9 |
+
from .sequences import SeqPer, SeqFormula, sequence, SeqAdd, SeqMul
|
10 |
+
from .fourier import fourier_series
|
11 |
+
from .formal import fps
|
12 |
+
from .limitseq import difference_delta, limit_seq
|
13 |
+
|
14 |
+
from sympy.core.singleton import S
|
15 |
+
EmptySequence = S.EmptySequence
|
16 |
+
|
17 |
+
O = Order
|
18 |
+
|
19 |
+
__all__ = ['Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants',
|
20 |
+
'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence',
|
21 |
+
'SeqAdd', 'SeqMul', 'fourier_series', 'fps', 'difference_delta',
|
22 |
+
'limit_seq'
|
23 |
+
]
|
venv/lib/python3.10/site-packages/sympy/series/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (940 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/series/__pycache__/acceleration.cpython-310.pyc
ADDED
Binary file (3.83 kB). View file
|
|