passagemath-repl 10.4.62__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- passagemath_repl-10.4.62.data/scripts/sage-cachegrind +25 -0
- passagemath_repl-10.4.62.data/scripts/sage-callgrind +16 -0
- passagemath_repl-10.4.62.data/scripts/sage-cleaner +230 -0
- passagemath_repl-10.4.62.data/scripts/sage-coverage +327 -0
- passagemath_repl-10.4.62.data/scripts/sage-eval +14 -0
- passagemath_repl-10.4.62.data/scripts/sage-fixdoctests +708 -0
- passagemath_repl-10.4.62.data/scripts/sage-inline-fortran +12 -0
- passagemath_repl-10.4.62.data/scripts/sage-ipynb2rst +50 -0
- passagemath_repl-10.4.62.data/scripts/sage-ipython +16 -0
- passagemath_repl-10.4.62.data/scripts/sage-massif +25 -0
- passagemath_repl-10.4.62.data/scripts/sage-notebook +267 -0
- passagemath_repl-10.4.62.data/scripts/sage-omega +25 -0
- passagemath_repl-10.4.62.data/scripts/sage-preparse +302 -0
- passagemath_repl-10.4.62.data/scripts/sage-run +27 -0
- passagemath_repl-10.4.62.data/scripts/sage-run-cython +10 -0
- passagemath_repl-10.4.62.data/scripts/sage-runtests +9 -0
- passagemath_repl-10.4.62.data/scripts/sage-startuptime.py +163 -0
- passagemath_repl-10.4.62.data/scripts/sage-valgrind +34 -0
- passagemath_repl-10.4.62.dist-info/METADATA +77 -0
- passagemath_repl-10.4.62.dist-info/RECORD +162 -0
- passagemath_repl-10.4.62.dist-info/WHEEL +5 -0
- passagemath_repl-10.4.62.dist-info/top_level.txt +1 -0
- sage/all__sagemath_repl.py +119 -0
- sage/doctest/__init__.py +4 -0
- sage/doctest/__main__.py +236 -0
- sage/doctest/all.py +4 -0
- sage/doctest/check_tolerance.py +261 -0
- sage/doctest/control.py +1727 -0
- sage/doctest/external.py +534 -0
- sage/doctest/fixtures.py +383 -0
- sage/doctest/forker.py +2665 -0
- sage/doctest/marked_output.py +102 -0
- sage/doctest/parsing.py +1708 -0
- sage/doctest/parsing_test.py +79 -0
- sage/doctest/reporting.py +733 -0
- sage/doctest/rif_tol.py +124 -0
- sage/doctest/sources.py +1657 -0
- sage/doctest/test.py +584 -0
- sage/doctest/tests/1second.rst +4 -0
- sage/doctest/tests/99seconds.rst +4 -0
- sage/doctest/tests/abort.rst +5 -0
- sage/doctest/tests/atexit.rst +7 -0
- sage/doctest/tests/fail_and_die.rst +6 -0
- sage/doctest/tests/initial.rst +15 -0
- sage/doctest/tests/interrupt.rst +7 -0
- sage/doctest/tests/interrupt_diehard.rst +14 -0
- sage/doctest/tests/keyboardinterrupt.rst +11 -0
- sage/doctest/tests/longtime.rst +5 -0
- sage/doctest/tests/nodoctest +5 -0
- sage/doctest/tests/random_seed.rst +4 -0
- sage/doctest/tests/show_skipped.rst +18 -0
- sage/doctest/tests/sig_on.rst +9 -0
- sage/doctest/tests/simple_failure.rst +8 -0
- sage/doctest/tests/sleep_and_raise.rst +106 -0
- sage/doctest/tests/tolerance.rst +31 -0
- sage/doctest/util.py +750 -0
- sage/interfaces/cleaner.py +48 -0
- sage/interfaces/quit.py +163 -0
- sage/misc/all__sagemath_repl.py +51 -0
- sage/misc/banner.py +235 -0
- sage/misc/benchmark.py +221 -0
- sage/misc/classgraph.py +131 -0
- sage/misc/copying.py +22 -0
- sage/misc/cython.py +694 -0
- sage/misc/dev_tools.py +745 -0
- sage/misc/edit_module.py +304 -0
- sage/misc/explain_pickle.py +3079 -0
- sage/misc/gperftools.py +361 -0
- sage/misc/inline_fortran.py +212 -0
- sage/misc/messaging.py +86 -0
- sage/misc/pager.py +21 -0
- sage/misc/profiler.py +179 -0
- sage/misc/python.py +70 -0
- sage/misc/remote_file.py +53 -0
- sage/misc/sage_eval.py +246 -0
- sage/misc/sage_input.py +3621 -0
- sage/misc/sagedoc.py +1742 -0
- sage/misc/sh.py +38 -0
- sage/misc/trace.py +90 -0
- sage/repl/__init__.py +16 -0
- sage/repl/all.py +15 -0
- sage/repl/attach.py +625 -0
- sage/repl/configuration.py +186 -0
- sage/repl/display/__init__.py +1 -0
- sage/repl/display/fancy_repr.py +354 -0
- sage/repl/display/formatter.py +318 -0
- sage/repl/display/jsmol_iframe.py +290 -0
- sage/repl/display/pretty_print.py +153 -0
- sage/repl/display/util.py +163 -0
- sage/repl/image.py +302 -0
- sage/repl/inputhook.py +91 -0
- sage/repl/interface_magic.py +298 -0
- sage/repl/interpreter.py +854 -0
- sage/repl/ipython_extension.py +593 -0
- sage/repl/ipython_kernel/__init__.py +1 -0
- sage/repl/ipython_kernel/__main__.py +4 -0
- sage/repl/ipython_kernel/all_jupyter.py +10 -0
- sage/repl/ipython_kernel/install.py +301 -0
- sage/repl/ipython_kernel/interact.py +278 -0
- sage/repl/ipython_kernel/kernel.py +217 -0
- sage/repl/ipython_kernel/widgets.py +466 -0
- sage/repl/ipython_kernel/widgets_sagenb.py +587 -0
- sage/repl/ipython_tests.py +163 -0
- sage/repl/load.py +326 -0
- sage/repl/preparse.py +2218 -0
- sage/repl/prompts.py +90 -0
- sage/repl/rich_output/__init__.py +4 -0
- sage/repl/rich_output/backend_base.py +648 -0
- sage/repl/rich_output/backend_doctest.py +316 -0
- sage/repl/rich_output/backend_emacs.py +151 -0
- sage/repl/rich_output/backend_ipython.py +596 -0
- sage/repl/rich_output/buffer.py +311 -0
- sage/repl/rich_output/display_manager.py +829 -0
- sage/repl/rich_output/example.avi +0 -0
- sage/repl/rich_output/example.canvas3d +1 -0
- sage/repl/rich_output/example.dvi +0 -0
- sage/repl/rich_output/example.flv +0 -0
- sage/repl/rich_output/example.gif +0 -0
- sage/repl/rich_output/example.jpg +0 -0
- sage/repl/rich_output/example.mkv +0 -0
- sage/repl/rich_output/example.mov +0 -0
- sage/repl/rich_output/example.mp4 +0 -0
- sage/repl/rich_output/example.ogv +0 -0
- sage/repl/rich_output/example.pdf +0 -0
- sage/repl/rich_output/example.png +0 -0
- sage/repl/rich_output/example.svg +54 -0
- sage/repl/rich_output/example.webm +0 -0
- sage/repl/rich_output/example.wmv +0 -0
- sage/repl/rich_output/example_jmol.spt.zip +0 -0
- sage/repl/rich_output/example_wavefront_scene.mtl +7 -0
- sage/repl/rich_output/example_wavefront_scene.obj +17 -0
- sage/repl/rich_output/output_basic.py +391 -0
- sage/repl/rich_output/output_browser.py +103 -0
- sage/repl/rich_output/output_catalog.py +54 -0
- sage/repl/rich_output/output_graphics.py +320 -0
- sage/repl/rich_output/output_graphics3d.py +345 -0
- sage/repl/rich_output/output_video.py +231 -0
- sage/repl/rich_output/preferences.py +432 -0
- sage/repl/rich_output/pretty_print.py +339 -0
- sage/repl/rich_output/test_backend.py +201 -0
- sage/repl/user_globals.py +214 -0
- sage/tests/__init__.py +1 -0
- sage/tests/all.py +3 -0
- sage/tests/article_heuberger_krenn_kropf_fsm-in-sage.py +630 -0
- sage/tests/arxiv_0812_2725.py +351 -0
- sage/tests/benchmark.py +1923 -0
- sage/tests/book_schilling_zabrocki_kschur_primer.py +795 -0
- sage/tests/book_stein_ent.py +651 -0
- sage/tests/book_stein_modform.py +558 -0
- sage/tests/cmdline.py +790 -0
- sage/tests/combinatorial_hopf_algebras.py +52 -0
- sage/tests/finite_poset.py +623 -0
- sage/tests/functools_partial_src.py +27 -0
- sage/tests/gosper-sum.py +218 -0
- sage/tests/lazy_imports.py +28 -0
- sage/tests/modular_group_cohomology.py +80 -0
- sage/tests/numpy.py +21 -0
- sage/tests/parigp.py +76 -0
- sage/tests/startup.py +27 -0
- sage/tests/symbolic-series.py +76 -0
- sage/tests/sympy.py +16 -0
- sage/tests/test_deprecation.py +31 -0
sage/misc/profiler.py
ADDED
@@ -0,0 +1,179 @@
|
|
1
|
+
# sage_setup: distribution = sagemath-repl
|
2
|
+
r"""
|
3
|
+
Simple profiling tool
|
4
|
+
|
5
|
+
AUTHORS:
|
6
|
+
|
7
|
+
- David Harvey (August 2006)
|
8
|
+
- Martin Albrecht
|
9
|
+
"""
|
10
|
+
|
11
|
+
# *****************************************************************************
|
12
|
+
# Copyright (C) 2006 William Stein <wstein@gmail.com>
|
13
|
+
# 2006 David Harvey <dmharvey@math.harvard.edu>
|
14
|
+
#
|
15
|
+
# Distributed under the terms of the GNU General Public License (GPL)
|
16
|
+
# http://www.gnu.org/licenses/
|
17
|
+
# *****************************************************************************
|
18
|
+
|
19
|
+
from sage.misc.timing import cputime
|
20
|
+
import inspect
|
21
|
+
import sys
|
22
|
+
|
23
|
+
|
24
|
+
class Profiler:
|
25
|
+
r"""
|
26
|
+
Keeps track of CPU time used between a series of user-defined checkpoints.
|
27
|
+
|
28
|
+
It's probably not a good idea to use this class in an inner loop :-)
|
29
|
+
|
30
|
+
EXAMPLES::
|
31
|
+
|
32
|
+
from sage.misc.profiler import Profiler
|
33
|
+
sage: def f(): # not tested
|
34
|
+
....: p = Profiler()
|
35
|
+
|
36
|
+
Calling ``p(message)`` creates a checkpoint::
|
37
|
+
|
38
|
+
sage: p("try factoring 15") # not tested
|
39
|
+
|
40
|
+
Do something time-consuming::
|
41
|
+
|
42
|
+
sage: x = factor(15) # not tested
|
43
|
+
|
44
|
+
You can create a checkpoints without a string; ``Profiler``
|
45
|
+
will use the source code instead::
|
46
|
+
|
47
|
+
sage: # not tested
|
48
|
+
sage: p()
|
49
|
+
sage: y = factor(25)
|
50
|
+
sage: p("last step")
|
51
|
+
sage: z = factor(35)
|
52
|
+
sage: p()
|
53
|
+
|
54
|
+
This will give a nice list of timings between checkpoints::
|
55
|
+
|
56
|
+
sage: print(p) # not tested
|
57
|
+
|
58
|
+
Let's try it out::
|
59
|
+
|
60
|
+
sage: f() # not tested
|
61
|
+
3.020s -- try factoring 15
|
62
|
+
15.240s -- line 17: y = factor(25)
|
63
|
+
5000.190s -- last step
|
64
|
+
|
65
|
+
.. SEEALSO:: :func:`runsnake`
|
66
|
+
|
67
|
+
.. TODO::
|
68
|
+
|
69
|
+
- Add Pyrex source code inspection (I assume it doesn't
|
70
|
+
currently do this)
|
71
|
+
- Add ability to sort output by time
|
72
|
+
- Add option to constructor to print timing immediately when
|
73
|
+
checkpoint is reached
|
74
|
+
- Migrate to Pyrex?
|
75
|
+
- Add ability to return timings in a more machine-friendly
|
76
|
+
format
|
77
|
+
|
78
|
+
AUTHOR:
|
79
|
+
|
80
|
+
- David Harvey (August 2006)
|
81
|
+
"""
|
82
|
+
|
83
|
+
def __init__(self, systems=[], verbose=False):
|
84
|
+
"""
|
85
|
+
INPUT:
|
86
|
+
|
87
|
+
- ``systems`` -- list of interfaces to other system which implements a
|
88
|
+
cputime method. The cputimes of all provided systems will be added
|
89
|
+
to the cputime of Sage itself.
|
90
|
+
"""
|
91
|
+
systems = [e.cputime for e in systems]
|
92
|
+
self._cputime_functions = [cputime] + list(systems)
|
93
|
+
self._verbose = bool(verbose)
|
94
|
+
self.clear()
|
95
|
+
|
96
|
+
def clear(self):
|
97
|
+
# _checkpoints is list of pairs (details, time), where time is a float
|
98
|
+
# and details is a triple (line_number, context, message)
|
99
|
+
self._checkpoints = []
|
100
|
+
self._active_details = None # details from the last __call__() call
|
101
|
+
self._last_cputime = [None]*len(self._cputime_functions)
|
102
|
+
|
103
|
+
def __call__(self, message=None):
|
104
|
+
""" Adds a checkpoint. """
|
105
|
+
entry_times = [fn() for fn in self._cputime_functions]
|
106
|
+
|
107
|
+
frame = inspect.currentframe().f_back
|
108
|
+
try:
|
109
|
+
frame_info = inspect.getframeinfo(frame, 9)
|
110
|
+
line_number = frame_info[1]
|
111
|
+
context = frame_info[3]
|
112
|
+
finally:
|
113
|
+
# This is here to prevent reference cycles
|
114
|
+
# (according to the warning in the python documentation:
|
115
|
+
# http://docs.python.org/lib/inspect-stack.html):
|
116
|
+
del frame_info
|
117
|
+
del frame
|
118
|
+
|
119
|
+
if self._active_details is not None:
|
120
|
+
_time = sum([entry_times[i]-self._last_cputime[i] for i in range(len(entry_times))])
|
121
|
+
self._checkpoints.append((self._active_details, _time))
|
122
|
+
|
123
|
+
self._active_details = (line_number, context, message)
|
124
|
+
|
125
|
+
self._last_cputime = [fn() for fn in self._cputime_functions]
|
126
|
+
if self._verbose:
|
127
|
+
print(self.print_last())
|
128
|
+
sys.stdout.flush()
|
129
|
+
|
130
|
+
def __repr__(self):
|
131
|
+
""" Returns a nicely formatted table of stored checkpoints and timings. """
|
132
|
+
if not self._checkpoints:
|
133
|
+
return "no checkpoints defined"
|
134
|
+
|
135
|
+
output = []
|
136
|
+
for ((line_number, context, message), time_used) in self._checkpoints:
|
137
|
+
if message is None:
|
138
|
+
# If the user hasn't given a message, we look for some
|
139
|
+
# source code to print instead
|
140
|
+
found = "(unknown)"
|
141
|
+
for line in context[5:]:
|
142
|
+
line = line.strip()
|
143
|
+
if line != "":
|
144
|
+
found = line
|
145
|
+
break
|
146
|
+
|
147
|
+
if len(found) > 60:
|
148
|
+
found = found[:60] + "..." # in case the source line is really long
|
149
|
+
message = "line %d: %s" % (line_number, found)
|
150
|
+
|
151
|
+
output.append("%9.3fs -- %s" % (time_used, message))
|
152
|
+
|
153
|
+
return "\n".join(output)
|
154
|
+
|
155
|
+
def print_last(self):
|
156
|
+
"""
|
157
|
+
Print the last profiler step.
|
158
|
+
"""
|
159
|
+
if not self._checkpoints:
|
160
|
+
return ""
|
161
|
+
|
162
|
+
((line_number, context, message), time_used) = self._checkpoints[-1]
|
163
|
+
if message is None:
|
164
|
+
# If the user hasn't given a message, we look for some
|
165
|
+
# source code to print instead
|
166
|
+
found = "(unknown)"
|
167
|
+
for line in context[5:]:
|
168
|
+
line = line.strip()
|
169
|
+
if line != "":
|
170
|
+
found = line
|
171
|
+
break
|
172
|
+
|
173
|
+
if len(found) > 60:
|
174
|
+
found = found[:60] + "..." # in case the source line is really long
|
175
|
+
message = "line %d: %s" % (line_number, found)
|
176
|
+
|
177
|
+
return "%9.3fs -- %s" % (time_used, message)
|
178
|
+
|
179
|
+
# end of file
|
sage/misc/python.py
ADDED
@@ -0,0 +1,70 @@
|
|
1
|
+
# sage_setup: distribution = sagemath-repl
|
2
|
+
"Evaluating Python code without any preparsing"
|
3
|
+
|
4
|
+
|
5
|
+
class Python:
|
6
|
+
"""
|
7
|
+
Allow for evaluating a chunk of code without any preparsing.
|
8
|
+
"""
|
9
|
+
|
10
|
+
def eval(self, x, globals, locals=None):
|
11
|
+
r"""
|
12
|
+
Evaluate x with given globals; locals is completely ignored.
|
13
|
+
|
14
|
+
This is specifically meant for evaluating code blocks with
|
15
|
+
``%python`` in the notebook.
|
16
|
+
|
17
|
+
INPUT:
|
18
|
+
|
19
|
+
- ``x`` -- string
|
20
|
+
- ``globals`` -- dictionary
|
21
|
+
- ``locals`` -- completely IGNORED
|
22
|
+
|
23
|
+
EXAMPLES::
|
24
|
+
|
25
|
+
sage: from sage.misc.python import Python
|
26
|
+
sage: python = Python()
|
27
|
+
sage: python.eval('2+2', globals())
|
28
|
+
4
|
29
|
+
''
|
30
|
+
|
31
|
+
Any variables that are set during evaluation of the block
|
32
|
+
will propagate to the globals dictionary. ::
|
33
|
+
|
34
|
+
sage: python.eval('a=5\nb=7\na+b', globals())
|
35
|
+
12
|
36
|
+
''
|
37
|
+
sage: b
|
38
|
+
7
|
39
|
+
|
40
|
+
The ``locals`` variable is ignored -- it is there only for
|
41
|
+
completeness. It is ignored since otherwise the following
|
42
|
+
will not work::
|
43
|
+
|
44
|
+
sage: python.eval("def foo():\n return 'foo'\nprint(foo())\ndef mumble():\n print('mumble {}'.format(foo()))\nmumble()", globals())
|
45
|
+
foo
|
46
|
+
mumble foo
|
47
|
+
''
|
48
|
+
sage: mumble
|
49
|
+
<function mumble at ...>
|
50
|
+
"""
|
51
|
+
x = x.strip()
|
52
|
+
y = x.split('\n')
|
53
|
+
if not y:
|
54
|
+
return ''
|
55
|
+
s = '\n'.join(y[:-1]) + '\n'
|
56
|
+
t = y[-1]
|
57
|
+
try:
|
58
|
+
z = compile(t + '\n', '', 'single')
|
59
|
+
except SyntaxError:
|
60
|
+
s += '\n' + t
|
61
|
+
z = None
|
62
|
+
|
63
|
+
eval(compile(s, '', 'exec'), globals, globals)
|
64
|
+
|
65
|
+
if z is not None:
|
66
|
+
eval(z, globals)
|
67
|
+
return ''
|
68
|
+
|
69
|
+
|
70
|
+
python = Python()
|
sage/misc/remote_file.py
ADDED
@@ -0,0 +1,53 @@
|
|
1
|
+
# sage_setup: distribution = sagemath-repl
|
2
|
+
"get_remote_file"
|
3
|
+
import os
|
4
|
+
from pathlib import Path
|
5
|
+
from urllib.request import Request, urlopen
|
6
|
+
from ssl import create_default_context as default_context
|
7
|
+
|
8
|
+
|
9
|
+
def get_remote_file(filename, verbose=True) -> Path:
|
10
|
+
"""
|
11
|
+
INPUT:
|
12
|
+
|
13
|
+
- ``filename`` -- the URL of a file on the web, e.g.,
|
14
|
+
``'http://modular.math.washington.edu/myfile.txt'``
|
15
|
+
|
16
|
+
- ``verbose`` -- whether to display download status
|
17
|
+
|
18
|
+
OUTPUT:
|
19
|
+
|
20
|
+
This creates a file in the temp directory and returns the absolute path
|
21
|
+
to that file as a :class:`Path` object.
|
22
|
+
|
23
|
+
EXAMPLES::
|
24
|
+
|
25
|
+
sage: url = 'https://www.sagemath.org/files/loadtest.py'
|
26
|
+
sage: g = get_remote_file(url, verbose=False) # optional - internet
|
27
|
+
sage: with open(g) as f: print(f.read()) # optional - internet
|
28
|
+
print("hi from the net")
|
29
|
+
<BLANKLINE>
|
30
|
+
print(2 + 3)
|
31
|
+
"""
|
32
|
+
if verbose:
|
33
|
+
print("Attempting to load remote file: " + filename)
|
34
|
+
|
35
|
+
from sage.misc.temporary_file import tmp_filename
|
36
|
+
ext = os.path.splitext(filename)[1]
|
37
|
+
temp_name = Path(tmp_filename(ext=ext))
|
38
|
+
# IMPORTANT -- urllib takes a long time to load,
|
39
|
+
# so do not import it in the module scope.
|
40
|
+
|
41
|
+
req = Request(filename, headers={"User-Agent": "sage-doctest"})
|
42
|
+
|
43
|
+
if verbose:
|
44
|
+
print("Loading started")
|
45
|
+
|
46
|
+
content = urlopen(req, timeout=1, context=default_context())
|
47
|
+
with temp_name.open('wb') as f:
|
48
|
+
f.write(content.read())
|
49
|
+
|
50
|
+
if verbose:
|
51
|
+
print("Loading ended")
|
52
|
+
|
53
|
+
return temp_name
|
sage/misc/sage_eval.py
ADDED
@@ -0,0 +1,246 @@
|
|
1
|
+
# sage_setup: distribution = sagemath-repl
|
2
|
+
r"""
|
3
|
+
Evaluating a String in Sage
|
4
|
+
"""
|
5
|
+
# ****************************************************************************
|
6
|
+
# Copyright (C) 2006 William Stein <wstein@gmail.com>
|
7
|
+
#
|
8
|
+
# Distributed under the terms of the GNU General Public License (GPL)
|
9
|
+
#
|
10
|
+
# https://www.gnu.org/licenses/
|
11
|
+
# ****************************************************************************
|
12
|
+
from copy import copy
|
13
|
+
import sage.repl.preparse as preparser
|
14
|
+
|
15
|
+
|
16
|
+
def sage_eval(source, locals=None, cmds='', preparse=True):
|
17
|
+
r"""
|
18
|
+
Obtain a Sage object from the input string by evaluating it using
|
19
|
+
Sage. This means calling eval after preparsing and with globals
|
20
|
+
equal to everything included in the scope of ``from sage.all
|
21
|
+
import *``.).
|
22
|
+
|
23
|
+
INPUT:
|
24
|
+
|
25
|
+
- ``source`` -- string or object with a ``_sage_``
|
26
|
+
method
|
27
|
+
|
28
|
+
- ``locals`` -- evaluate in namespace of :mod:`sage.all` plus
|
29
|
+
the locals dictionary
|
30
|
+
|
31
|
+
- ``cmds`` -- string; sequence of commands to be run
|
32
|
+
before source is evaluated
|
33
|
+
|
34
|
+
- ``preparse`` -- boolean (default: ``True``); if ``True``, preparse the
|
35
|
+
string expression
|
36
|
+
|
37
|
+
EXAMPLES: This example illustrates that preparsing is applied::
|
38
|
+
|
39
|
+
sage: eval('2^3')
|
40
|
+
1
|
41
|
+
sage: sage_eval('2^3')
|
42
|
+
8
|
43
|
+
|
44
|
+
However, preparsing can be turned off::
|
45
|
+
|
46
|
+
sage: sage_eval('2^3', preparse=False)
|
47
|
+
1
|
48
|
+
|
49
|
+
Note that you can explicitly define variables and pass them as the
|
50
|
+
second option::
|
51
|
+
|
52
|
+
sage: x = PolynomialRing(RationalField(),"x").gen()
|
53
|
+
sage: sage_eval('x^2+1', locals={'x':x})
|
54
|
+
x^2 + 1
|
55
|
+
|
56
|
+
This example illustrates that evaluation occurs in the context of
|
57
|
+
``from sage.all import *``. Even though ``bernoulli`` has
|
58
|
+
been redefined in the local scope, when calling
|
59
|
+
:func:`sage_eval` the default value meaning of :func:`bernoulli`
|
60
|
+
is used. Likewise for ``QQ`` below::
|
61
|
+
|
62
|
+
sage: bernoulli = lambda x : x^2
|
63
|
+
sage: bernoulli(6)
|
64
|
+
36
|
65
|
+
sage: eval('bernoulli(6)')
|
66
|
+
36
|
67
|
+
sage: sage_eval('bernoulli(6)') # needs sage.libs.flint
|
68
|
+
1/42
|
69
|
+
|
70
|
+
::
|
71
|
+
|
72
|
+
sage: QQ = lambda x : x^2
|
73
|
+
sage: QQ(2)
|
74
|
+
4
|
75
|
+
sage: sage_eval('QQ(2)')
|
76
|
+
2
|
77
|
+
sage: parent(sage_eval('QQ(2)'))
|
78
|
+
Rational Field
|
79
|
+
|
80
|
+
This example illustrates setting a variable for use in evaluation::
|
81
|
+
|
82
|
+
sage: x = 5
|
83
|
+
sage: eval('4//3 + x', {'x': 25})
|
84
|
+
26
|
85
|
+
sage: sage_eval('4/3 + x', locals={'x': 25})
|
86
|
+
79/3
|
87
|
+
|
88
|
+
You can also specify a sequence of commands to be run before the
|
89
|
+
expression is evaluated::
|
90
|
+
|
91
|
+
sage: sage_eval('p', cmds='K.<x> = QQ[]\np = x^2 + 1')
|
92
|
+
x^2 + 1
|
93
|
+
|
94
|
+
If you give commands to execute and a dictionary of variables, then
|
95
|
+
the dictionary will be modified by assignments in the commands::
|
96
|
+
|
97
|
+
sage: vars = {}
|
98
|
+
sage: sage_eval('None', cmds='y = 3', locals=vars)
|
99
|
+
sage: vars['y'], parent(vars['y'])
|
100
|
+
(3, Integer Ring)
|
101
|
+
|
102
|
+
You can also specify the object to evaluate as a tuple. A 2-tuple
|
103
|
+
is assumed to be a pair of a command sequence and an expression; a
|
104
|
+
3-tuple is assumed to be a triple of a command sequence, an
|
105
|
+
expression, and a dictionary holding local variables. (In this
|
106
|
+
case, the given dictionary will not be modified by assignments in
|
107
|
+
the commands.)
|
108
|
+
|
109
|
+
::
|
110
|
+
|
111
|
+
sage: sage_eval(('f(x) = x^2', 'f(3)')) # needs sage.symbolic
|
112
|
+
9
|
113
|
+
sage: vars = {'rt2': sqrt(2.0)}
|
114
|
+
sage: sage_eval(('rt2 += 1', 'rt2', vars))
|
115
|
+
2.41421356237309
|
116
|
+
sage: vars['rt2']
|
117
|
+
1.41421356237310
|
118
|
+
|
119
|
+
This example illustrates how :mod:`sage_eval` can be
|
120
|
+
useful when evaluating the output of other computer algebra
|
121
|
+
systems::
|
122
|
+
|
123
|
+
sage: # needs sage.libs.gap
|
124
|
+
sage: R.<x> = PolynomialRing(RationalField())
|
125
|
+
sage: gap.eval('R:=PolynomialRing(Rationals,["x"]);')
|
126
|
+
'Rationals[x]'
|
127
|
+
sage: ff = gap.eval('x:=IndeterminatesOfPolynomialRing(R);; f:=x^2+1;'); ff
|
128
|
+
'x^2+1'
|
129
|
+
sage: sage_eval(ff, locals={'x':x})
|
130
|
+
x^2 + 1
|
131
|
+
sage: eval(ff)
|
132
|
+
Traceback (most recent call last):
|
133
|
+
...
|
134
|
+
RuntimeError: Use ** for exponentiation, not '^', which means xor
|
135
|
+
in Python, and has the wrong precedence.
|
136
|
+
|
137
|
+
Here you can see that :func:`eval` simply will not work but
|
138
|
+
:func:`sage_eval` will.
|
139
|
+
|
140
|
+
TESTS:
|
141
|
+
|
142
|
+
We get a nice minimal error message for syntax errors, that still
|
143
|
+
points to the location of the error (in the input string)::
|
144
|
+
|
145
|
+
sage: sage_eval('RR(22/7]')
|
146
|
+
Traceback (most recent call last):
|
147
|
+
...
|
148
|
+
File "<string>", line 1
|
149
|
+
RR(Integer(22)/Integer(7)]
|
150
|
+
^
|
151
|
+
SyntaxError: ...
|
152
|
+
|
153
|
+
::
|
154
|
+
|
155
|
+
sage: sage_eval('None', cmds='$x = $y[3] # Does Perl syntax work?')
|
156
|
+
Traceback (most recent call last):
|
157
|
+
...
|
158
|
+
File "<string>", line 1
|
159
|
+
$x = $y[Integer(3)] # Does Perl syntax work?
|
160
|
+
^
|
161
|
+
SyntaxError: invalid ...
|
162
|
+
"""
|
163
|
+
if isinstance(source, (list, tuple)):
|
164
|
+
cmds = source[0]
|
165
|
+
if len(source) > 2:
|
166
|
+
locals = copy(source[2])
|
167
|
+
source = source[1]
|
168
|
+
|
169
|
+
if not isinstance(source, str):
|
170
|
+
raise TypeError("source must be a string.")
|
171
|
+
|
172
|
+
if locals is None:
|
173
|
+
locals = {}
|
174
|
+
|
175
|
+
try:
|
176
|
+
import sage.all as toplevel
|
177
|
+
except ImportError:
|
178
|
+
try:
|
179
|
+
import sage.all__sagemath_polyhedra as toplevel
|
180
|
+
except ImportError:
|
181
|
+
try:
|
182
|
+
import sage.all__sagemath_categories as toplevel
|
183
|
+
except ImportError:
|
184
|
+
import sage.all__sagemath_objects as toplevel
|
185
|
+
if cmds:
|
186
|
+
cmd_seq = cmds + '\n_sage_eval_returnval_ = ' + source
|
187
|
+
if preparse:
|
188
|
+
cmd_seq = preparser.preparse_file(cmd_seq)
|
189
|
+
else:
|
190
|
+
if preparse:
|
191
|
+
source = preparser.preparse(source)
|
192
|
+
|
193
|
+
if cmds:
|
194
|
+
exec(cmd_seq, toplevel.__dict__, locals)
|
195
|
+
return locals['_sage_eval_returnval_']
|
196
|
+
else:
|
197
|
+
return eval(source, toplevel.__dict__, locals)
|
198
|
+
|
199
|
+
|
200
|
+
def sageobj(x, vars=None):
|
201
|
+
"""
|
202
|
+
Return a native Sage object associated to ``x``, if possible and
|
203
|
+
implemented.
|
204
|
+
|
205
|
+
If the object has a ``_sage_`` method it is called and the value is
|
206
|
+
returned. Otherwise, :func:`str` is called on the object, and all preparsing
|
207
|
+
is applied and the resulting expression is evaluated in the context
|
208
|
+
of ``from sage.all import *``. To evaluate the
|
209
|
+
expression with certain variables set, use the ``vars`` argument, which
|
210
|
+
should be a dictionary.
|
211
|
+
|
212
|
+
EXAMPLES::
|
213
|
+
|
214
|
+
sage: type(sageobj(gp('34/56'))) # needs sage.libs.pari
|
215
|
+
<class 'sage.rings.rational.Rational'>
|
216
|
+
|
217
|
+
sage: n = 5/2
|
218
|
+
sage: sageobj(n) is n
|
219
|
+
True
|
220
|
+
sage: k = sageobj('Z(8^3/1)', {'Z':ZZ}); k
|
221
|
+
512
|
222
|
+
sage: type(k)
|
223
|
+
<class 'sage.rings.integer.Integer'>
|
224
|
+
|
225
|
+
This illustrates interfaces::
|
226
|
+
|
227
|
+
sage: # needs sage.libs.pari
|
228
|
+
sage: f = gp('2/3')
|
229
|
+
sage: type(f)
|
230
|
+
<class 'sage.interfaces.gp.GpElement'>
|
231
|
+
sage: f._sage_()
|
232
|
+
2/3
|
233
|
+
sage: type(f._sage_())
|
234
|
+
<class 'sage.rings.rational.Rational'>
|
235
|
+
|
236
|
+
sage: # needs sage.libs.gap
|
237
|
+
sage: a = gap(939393/2433)
|
238
|
+
sage: a._sage_()
|
239
|
+
313131/811
|
240
|
+
sage: type(a._sage_())
|
241
|
+
<class 'sage.rings.rational.Rational'>
|
242
|
+
"""
|
243
|
+
try:
|
244
|
+
return x._sage_()
|
245
|
+
except (TypeError, NotImplementedError, AttributeError):
|
246
|
+
return sage_eval(str(x), vars)
|