Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__init__.py +22 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/experimental_lambdify.py +641 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/plot.py +1234 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/plot_implicit.py +233 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/plotgrid.py +188 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__init__.py +138 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/color_scheme.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/managed_window.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_axes.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_controller.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_curve.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_modes.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_object.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_rotation.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_surface.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_window.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/color_scheme.py +336 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/managed_window.py +106 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot.py +464 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_axes.py +251 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_camera.py +124 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_controller.py +218 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_curve.py +82 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_interval.py +181 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode.py +400 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode_base.py +378 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_modes.py +209 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_object.py +17 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_rotation.py +68 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_surface.py +102 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_window.py +144 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__init__.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/test_plotting.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/test_plotting.py +88 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/util.py +188 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/series.py +2591 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/textplot.py +168 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/utils.py +323 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/sandbox/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_wester.cpython-310.pyc +3 -0
- evalkit_tf437/lib/python3.10/site-packages/sklearn/decomposition/_factor_analysis.py +457 -0
- evalkit_tf437/lib/python3.10/site-packages/sklearn/decomposition/_incremental_pca.py +426 -0
.gitattributes
CHANGED
@@ -1631,3 +1631,5 @@ evalkit_internvl/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/t
|
|
1631 |
evalkit_internvl/lib/python3.10/site-packages/sympy/printing/__pycache__/latex.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
1632 |
evalkit_internvl/lib/python3.10/site-packages/sympy/printing/pretty/tests/__pycache__/test_pretty.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
1633 |
evalkit_tf437/lib/python3.10/site-packages/pyarrow/libarrow_substrait.so.1800 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
1631 |
evalkit_internvl/lib/python3.10/site-packages/sympy/printing/__pycache__/latex.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
1632 |
evalkit_internvl/lib/python3.10/site-packages/sympy/printing/pretty/tests/__pycache__/test_pretty.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
1633 |
evalkit_tf437/lib/python3.10/site-packages/pyarrow/libarrow_substrait.so.1800 filter=lfs diff=lfs merge=lfs -text
|
1634 |
+
falcon/bin/python filter=lfs diff=lfs merge=lfs -text
|
1635 |
+
evalkit_internvl/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_wester.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__init__.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .plot import plot_backends
|
2 |
+
from .plot_implicit import plot_implicit
|
3 |
+
from .textplot import textplot
|
4 |
+
from .pygletplot import PygletPlot
|
5 |
+
from .plot import PlotGrid
|
6 |
+
from .plot import (plot, plot_parametric, plot3d, plot3d_parametric_surface,
|
7 |
+
plot3d_parametric_line, plot_contour)
|
8 |
+
|
9 |
+
__all__ = [
|
10 |
+
'plot_backends',
|
11 |
+
|
12 |
+
'plot_implicit',
|
13 |
+
|
14 |
+
'textplot',
|
15 |
+
|
16 |
+
'PygletPlot',
|
17 |
+
|
18 |
+
'PlotGrid',
|
19 |
+
|
20 |
+
'plot', 'plot_parametric', 'plot3d', 'plot3d_parametric_surface',
|
21 |
+
'plot3d_parametric_line', 'plot_contour'
|
22 |
+
]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/experimental_lambdify.py
ADDED
@@ -0,0 +1,641 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" rewrite of lambdify - This stuff is not stable at all.
|
2 |
+
|
3 |
+
It is for internal use in the new plotting module.
|
4 |
+
It may (will! see the Q'n'A in the source) be rewritten.
|
5 |
+
|
6 |
+
It's completely self contained. Especially it does not use lambdarepr.
|
7 |
+
|
8 |
+
It does not aim to replace the current lambdify. Most importantly it will never
|
9 |
+
ever support anything else than SymPy expressions (no Matrices, dictionaries
|
10 |
+
and so on).
|
11 |
+
"""
|
12 |
+
|
13 |
+
|
14 |
+
import re
|
15 |
+
from sympy.core.numbers import (I, NumberSymbol, oo, zoo)
|
16 |
+
from sympy.core.symbol import Symbol
|
17 |
+
from sympy.utilities.iterables import numbered_symbols
|
18 |
+
|
19 |
+
# We parse the expression string into a tree that identifies functions. Then
|
20 |
+
# we translate the names of the functions and we translate also some strings
|
21 |
+
# that are not names of functions (all this according to translation
|
22 |
+
# dictionaries).
|
23 |
+
# If the translation goes to another module (like numpy) the
|
24 |
+
# module is imported and 'func' is translated to 'module.func'.
|
25 |
+
# If a function can not be translated, the inner nodes of that part of the
|
26 |
+
# tree are not translated. So if we have Integral(sqrt(x)), sqrt is not
|
27 |
+
# translated to np.sqrt and the Integral does not crash.
|
28 |
+
# A namespace for all this is generated by crawling the (func, args) tree of
|
29 |
+
# the expression. The creation of this namespace involves many ugly
|
30 |
+
# workarounds.
|
31 |
+
# The namespace consists of all the names needed for the SymPy expression and
|
32 |
+
# all the name of modules used for translation. Those modules are imported only
|
33 |
+
# as a name (import numpy as np) in order to keep the namespace small and
|
34 |
+
# manageable.
|
35 |
+
|
36 |
+
# Please, if there is a bug, do not try to fix it here! Rewrite this by using
|
37 |
+
# the method proposed in the last Q'n'A below. That way the new function will
|
38 |
+
# work just as well, be just as simple, but it wont need any new workarounds.
|
39 |
+
# If you insist on fixing it here, look at the workarounds in the function
|
40 |
+
# sympy_expression_namespace and in lambdify.
|
41 |
+
|
42 |
+
# Q: Why are you not using Python abstract syntax tree?
|
43 |
+
# A: Because it is more complicated and not much more powerful in this case.
|
44 |
+
|
45 |
+
# Q: What if I have Symbol('sin') or g=Function('f')?
|
46 |
+
# A: You will break the algorithm. We should use srepr to defend against this?
|
47 |
+
# The problem with Symbol('sin') is that it will be printed as 'sin'. The
|
48 |
+
# parser will distinguish it from the function 'sin' because functions are
|
49 |
+
# detected thanks to the opening parenthesis, but the lambda expression won't
|
50 |
+
# understand the difference if we have also the sin function.
|
51 |
+
# The solution (complicated) is to use srepr and maybe ast.
|
52 |
+
# The problem with the g=Function('f') is that it will be printed as 'f' but in
|
53 |
+
# the global namespace we have only 'g'. But as the same printer is used in the
|
54 |
+
# constructor of the namespace there will be no problem.
|
55 |
+
|
56 |
+
# Q: What if some of the printers are not printing as expected?
|
57 |
+
# A: The algorithm wont work. You must use srepr for those cases. But even
|
58 |
+
# srepr may not print well. All problems with printers should be considered
|
59 |
+
# bugs.
|
60 |
+
|
61 |
+
# Q: What about _imp_ functions?
|
62 |
+
# A: Those are taken care for by evalf. A special case treatment will work
|
63 |
+
# faster but it's not worth the code complexity.
|
64 |
+
|
65 |
+
# Q: Will ast fix all possible problems?
|
66 |
+
# A: No. You will always have to use some printer. Even srepr may not work in
|
67 |
+
# some cases. But if the printer does not work, that should be considered a
|
68 |
+
# bug.
|
69 |
+
|
70 |
+
# Q: Is there same way to fix all possible problems?
|
71 |
+
# A: Probably by constructing our strings ourself by traversing the (func,
|
72 |
+
# args) tree and creating the namespace at the same time. That actually sounds
|
73 |
+
# good.
|
74 |
+
|
75 |
+
from sympy.external import import_module
|
76 |
+
import warnings
|
77 |
+
|
78 |
+
#TODO debugging output
|
79 |
+
|
80 |
+
|
81 |
+
class vectorized_lambdify:
|
82 |
+
""" Return a sufficiently smart, vectorized and lambdified function.
|
83 |
+
|
84 |
+
Returns only reals.
|
85 |
+
|
86 |
+
Explanation
|
87 |
+
===========
|
88 |
+
|
89 |
+
This function uses experimental_lambdify to created a lambdified
|
90 |
+
expression ready to be used with numpy. Many of the functions in SymPy
|
91 |
+
are not implemented in numpy so in some cases we resort to Python cmath or
|
92 |
+
even to evalf.
|
93 |
+
|
94 |
+
The following translations are tried:
|
95 |
+
only numpy complex
|
96 |
+
- on errors raised by SymPy trying to work with ndarray:
|
97 |
+
only Python cmath and then vectorize complex128
|
98 |
+
|
99 |
+
When using Python cmath there is no need for evalf or float/complex
|
100 |
+
because Python cmath calls those.
|
101 |
+
|
102 |
+
This function never tries to mix numpy directly with evalf because numpy
|
103 |
+
does not understand SymPy Float. If this is needed one can use the
|
104 |
+
float_wrap_evalf/complex_wrap_evalf options of experimental_lambdify or
|
105 |
+
better one can be explicit about the dtypes that numpy works with.
|
106 |
+
Check numpy bug http://projects.scipy.org/numpy/ticket/1013 to know what
|
107 |
+
types of errors to expect.
|
108 |
+
"""
|
109 |
+
def __init__(self, args, expr):
|
110 |
+
self.args = args
|
111 |
+
self.expr = expr
|
112 |
+
self.np = import_module('numpy')
|
113 |
+
|
114 |
+
self.lambda_func_1 = experimental_lambdify(
|
115 |
+
args, expr, use_np=True)
|
116 |
+
self.vector_func_1 = self.lambda_func_1
|
117 |
+
|
118 |
+
self.lambda_func_2 = experimental_lambdify(
|
119 |
+
args, expr, use_python_cmath=True)
|
120 |
+
self.vector_func_2 = self.np.vectorize(
|
121 |
+
self.lambda_func_2, otypes=[complex])
|
122 |
+
|
123 |
+
self.vector_func = self.vector_func_1
|
124 |
+
self.failure = False
|
125 |
+
|
126 |
+
def __call__(self, *args):
|
127 |
+
np = self.np
|
128 |
+
|
129 |
+
try:
|
130 |
+
temp_args = (np.array(a, dtype=complex) for a in args)
|
131 |
+
results = self.vector_func(*temp_args)
|
132 |
+
results = np.ma.masked_where(
|
133 |
+
np.abs(results.imag) > 1e-7 * np.abs(results),
|
134 |
+
results.real, copy=False)
|
135 |
+
return results
|
136 |
+
except ValueError:
|
137 |
+
if self.failure:
|
138 |
+
raise
|
139 |
+
|
140 |
+
self.failure = True
|
141 |
+
self.vector_func = self.vector_func_2
|
142 |
+
warnings.warn(
|
143 |
+
'The evaluation of the expression is problematic. '
|
144 |
+
'We are trying a failback method that may still work. '
|
145 |
+
'Please report this as a bug.')
|
146 |
+
return self.__call__(*args)
|
147 |
+
|
148 |
+
|
149 |
+
class lambdify:
|
150 |
+
"""Returns the lambdified function.
|
151 |
+
|
152 |
+
Explanation
|
153 |
+
===========
|
154 |
+
|
155 |
+
This function uses experimental_lambdify to create a lambdified
|
156 |
+
expression. It uses cmath to lambdify the expression. If the function
|
157 |
+
is not implemented in Python cmath, Python cmath calls evalf on those
|
158 |
+
functions.
|
159 |
+
"""
|
160 |
+
|
161 |
+
def __init__(self, args, expr):
|
162 |
+
self.args = args
|
163 |
+
self.expr = expr
|
164 |
+
self.lambda_func_1 = experimental_lambdify(
|
165 |
+
args, expr, use_python_cmath=True, use_evalf=True)
|
166 |
+
self.lambda_func_2 = experimental_lambdify(
|
167 |
+
args, expr, use_python_math=True, use_evalf=True)
|
168 |
+
self.lambda_func_3 = experimental_lambdify(
|
169 |
+
args, expr, use_evalf=True, complex_wrap_evalf=True)
|
170 |
+
self.lambda_func = self.lambda_func_1
|
171 |
+
self.failure = False
|
172 |
+
|
173 |
+
def __call__(self, args):
|
174 |
+
try:
|
175 |
+
#The result can be sympy.Float. Hence wrap it with complex type.
|
176 |
+
result = complex(self.lambda_func(args))
|
177 |
+
if abs(result.imag) > 1e-7 * abs(result):
|
178 |
+
return None
|
179 |
+
return result.real
|
180 |
+
except (ZeroDivisionError, OverflowError):
|
181 |
+
return None
|
182 |
+
except TypeError as e:
|
183 |
+
if self.failure:
|
184 |
+
raise e
|
185 |
+
|
186 |
+
if self.lambda_func == self.lambda_func_1:
|
187 |
+
self.lambda_func = self.lambda_func_2
|
188 |
+
return self.__call__(args)
|
189 |
+
|
190 |
+
self.failure = True
|
191 |
+
self.lambda_func = self.lambda_func_3
|
192 |
+
warnings.warn(
|
193 |
+
'The evaluation of the expression is problematic. '
|
194 |
+
'We are trying a failback method that may still work. '
|
195 |
+
'Please report this as a bug.', stacklevel=2)
|
196 |
+
return self.__call__(args)
|
197 |
+
|
198 |
+
|
199 |
+
def experimental_lambdify(*args, **kwargs):
|
200 |
+
l = Lambdifier(*args, **kwargs)
|
201 |
+
return l
|
202 |
+
|
203 |
+
|
204 |
+
class Lambdifier:
|
205 |
+
def __init__(self, args, expr, print_lambda=False, use_evalf=False,
|
206 |
+
float_wrap_evalf=False, complex_wrap_evalf=False,
|
207 |
+
use_np=False, use_python_math=False, use_python_cmath=False,
|
208 |
+
use_interval=False):
|
209 |
+
|
210 |
+
self.print_lambda = print_lambda
|
211 |
+
self.use_evalf = use_evalf
|
212 |
+
self.float_wrap_evalf = float_wrap_evalf
|
213 |
+
self.complex_wrap_evalf = complex_wrap_evalf
|
214 |
+
self.use_np = use_np
|
215 |
+
self.use_python_math = use_python_math
|
216 |
+
self.use_python_cmath = use_python_cmath
|
217 |
+
self.use_interval = use_interval
|
218 |
+
|
219 |
+
# Constructing the argument string
|
220 |
+
# - check
|
221 |
+
if not all(isinstance(a, Symbol) for a in args):
|
222 |
+
raise ValueError('The arguments must be Symbols.')
|
223 |
+
# - use numbered symbols
|
224 |
+
syms = numbered_symbols(exclude=expr.free_symbols)
|
225 |
+
newargs = [next(syms) for _ in args]
|
226 |
+
expr = expr.xreplace(dict(zip(args, newargs)))
|
227 |
+
argstr = ', '.join([str(a) for a in newargs])
|
228 |
+
del syms, newargs, args
|
229 |
+
|
230 |
+
# Constructing the translation dictionaries and making the translation
|
231 |
+
self.dict_str = self.get_dict_str()
|
232 |
+
self.dict_fun = self.get_dict_fun()
|
233 |
+
exprstr = str(expr)
|
234 |
+
newexpr = self.tree2str_translate(self.str2tree(exprstr))
|
235 |
+
|
236 |
+
# Constructing the namespaces
|
237 |
+
namespace = {}
|
238 |
+
namespace.update(self.sympy_atoms_namespace(expr))
|
239 |
+
namespace.update(self.sympy_expression_namespace(expr))
|
240 |
+
# XXX Workaround
|
241 |
+
# Ugly workaround because Pow(a,Half) prints as sqrt(a)
|
242 |
+
# and sympy_expression_namespace can not catch it.
|
243 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
244 |
+
namespace.update({'sqrt': sqrt})
|
245 |
+
namespace.update({'Eq': lambda x, y: x == y})
|
246 |
+
namespace.update({'Ne': lambda x, y: x != y})
|
247 |
+
# End workaround.
|
248 |
+
if use_python_math:
|
249 |
+
namespace.update({'math': __import__('math')})
|
250 |
+
if use_python_cmath:
|
251 |
+
namespace.update({'cmath': __import__('cmath')})
|
252 |
+
if use_np:
|
253 |
+
try:
|
254 |
+
namespace.update({'np': __import__('numpy')})
|
255 |
+
except ImportError:
|
256 |
+
raise ImportError(
|
257 |
+
'experimental_lambdify failed to import numpy.')
|
258 |
+
if use_interval:
|
259 |
+
namespace.update({'imath': __import__(
|
260 |
+
'sympy.plotting.intervalmath', fromlist=['intervalmath'])})
|
261 |
+
namespace.update({'math': __import__('math')})
|
262 |
+
|
263 |
+
# Construct the lambda
|
264 |
+
if self.print_lambda:
|
265 |
+
print(newexpr)
|
266 |
+
eval_str = 'lambda %s : ( %s )' % (argstr, newexpr)
|
267 |
+
self.eval_str = eval_str
|
268 |
+
exec("MYNEWLAMBDA = %s" % eval_str, namespace)
|
269 |
+
self.lambda_func = namespace['MYNEWLAMBDA']
|
270 |
+
|
271 |
+
def __call__(self, *args, **kwargs):
|
272 |
+
return self.lambda_func(*args, **kwargs)
|
273 |
+
|
274 |
+
|
275 |
+
##############################################################################
|
276 |
+
# Dicts for translating from SymPy to other modules
|
277 |
+
##############################################################################
|
278 |
+
###
|
279 |
+
# builtins
|
280 |
+
###
|
281 |
+
# Functions with different names in builtins
|
282 |
+
builtin_functions_different = {
|
283 |
+
'Min': 'min',
|
284 |
+
'Max': 'max',
|
285 |
+
'Abs': 'abs',
|
286 |
+
}
|
287 |
+
|
288 |
+
# Strings that should be translated
|
289 |
+
builtin_not_functions = {
|
290 |
+
'I': '1j',
|
291 |
+
# 'oo': '1e400',
|
292 |
+
}
|
293 |
+
|
294 |
+
###
|
295 |
+
# numpy
|
296 |
+
###
|
297 |
+
|
298 |
+
# Functions that are the same in numpy
|
299 |
+
numpy_functions_same = [
|
300 |
+
'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'exp', 'log',
|
301 |
+
'sqrt', 'floor', 'conjugate', 'sign',
|
302 |
+
]
|
303 |
+
|
304 |
+
# Functions with different names in numpy
|
305 |
+
numpy_functions_different = {
|
306 |
+
"acos": "arccos",
|
307 |
+
"acosh": "arccosh",
|
308 |
+
"arg": "angle",
|
309 |
+
"asin": "arcsin",
|
310 |
+
"asinh": "arcsinh",
|
311 |
+
"atan": "arctan",
|
312 |
+
"atan2": "arctan2",
|
313 |
+
"atanh": "arctanh",
|
314 |
+
"ceiling": "ceil",
|
315 |
+
"im": "imag",
|
316 |
+
"ln": "log",
|
317 |
+
"Max": "amax",
|
318 |
+
"Min": "amin",
|
319 |
+
"re": "real",
|
320 |
+
"Abs": "abs",
|
321 |
+
}
|
322 |
+
|
323 |
+
# Strings that should be translated
|
324 |
+
numpy_not_functions = {
|
325 |
+
'pi': 'np.pi',
|
326 |
+
'oo': 'np.inf',
|
327 |
+
'E': 'np.e',
|
328 |
+
}
|
329 |
+
|
330 |
+
###
|
331 |
+
# Python math
|
332 |
+
###
|
333 |
+
|
334 |
+
# Functions that are the same in math
|
335 |
+
math_functions_same = [
|
336 |
+
'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2',
|
337 |
+
'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh',
|
338 |
+
'exp', 'log', 'erf', 'sqrt', 'floor', 'factorial', 'gamma',
|
339 |
+
]
|
340 |
+
|
341 |
+
# Functions with different names in math
|
342 |
+
math_functions_different = {
|
343 |
+
'ceiling': 'ceil',
|
344 |
+
'ln': 'log',
|
345 |
+
'loggamma': 'lgamma'
|
346 |
+
}
|
347 |
+
|
348 |
+
# Strings that should be translated
|
349 |
+
math_not_functions = {
|
350 |
+
'pi': 'math.pi',
|
351 |
+
'E': 'math.e',
|
352 |
+
}
|
353 |
+
|
354 |
+
###
|
355 |
+
# Python cmath
|
356 |
+
###
|
357 |
+
|
358 |
+
# Functions that are the same in cmath
|
359 |
+
cmath_functions_same = [
|
360 |
+
'sin', 'cos', 'tan', 'asin', 'acos', 'atan',
|
361 |
+
'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh',
|
362 |
+
'exp', 'log', 'sqrt',
|
363 |
+
]
|
364 |
+
|
365 |
+
# Functions with different names in cmath
|
366 |
+
cmath_functions_different = {
|
367 |
+
'ln': 'log',
|
368 |
+
'arg': 'phase',
|
369 |
+
}
|
370 |
+
|
371 |
+
# Strings that should be translated
|
372 |
+
cmath_not_functions = {
|
373 |
+
'pi': 'cmath.pi',
|
374 |
+
'E': 'cmath.e',
|
375 |
+
}
|
376 |
+
|
377 |
+
###
|
378 |
+
# intervalmath
|
379 |
+
###
|
380 |
+
|
381 |
+
interval_not_functions = {
|
382 |
+
'pi': 'math.pi',
|
383 |
+
'E': 'math.e'
|
384 |
+
}
|
385 |
+
|
386 |
+
interval_functions_same = [
|
387 |
+
'sin', 'cos', 'exp', 'tan', 'atan', 'log',
|
388 |
+
'sqrt', 'cosh', 'sinh', 'tanh', 'floor',
|
389 |
+
'acos', 'asin', 'acosh', 'asinh', 'atanh',
|
390 |
+
'Abs', 'And', 'Or'
|
391 |
+
]
|
392 |
+
|
393 |
+
interval_functions_different = {
|
394 |
+
'Min': 'imin',
|
395 |
+
'Max': 'imax',
|
396 |
+
'ceiling': 'ceil',
|
397 |
+
|
398 |
+
}
|
399 |
+
|
400 |
+
###
|
401 |
+
# mpmath, etc
|
402 |
+
###
|
403 |
+
#TODO
|
404 |
+
|
405 |
+
###
|
406 |
+
# Create the final ordered tuples of dictionaries
|
407 |
+
###
|
408 |
+
|
409 |
+
# For strings
|
410 |
+
def get_dict_str(self):
|
411 |
+
dict_str = dict(self.builtin_not_functions)
|
412 |
+
if self.use_np:
|
413 |
+
dict_str.update(self.numpy_not_functions)
|
414 |
+
if self.use_python_math:
|
415 |
+
dict_str.update(self.math_not_functions)
|
416 |
+
if self.use_python_cmath:
|
417 |
+
dict_str.update(self.cmath_not_functions)
|
418 |
+
if self.use_interval:
|
419 |
+
dict_str.update(self.interval_not_functions)
|
420 |
+
return dict_str
|
421 |
+
|
422 |
+
# For functions
|
423 |
+
def get_dict_fun(self):
|
424 |
+
dict_fun = dict(self.builtin_functions_different)
|
425 |
+
if self.use_np:
|
426 |
+
for s in self.numpy_functions_same:
|
427 |
+
dict_fun[s] = 'np.' + s
|
428 |
+
for k, v in self.numpy_functions_different.items():
|
429 |
+
dict_fun[k] = 'np.' + v
|
430 |
+
if self.use_python_math:
|
431 |
+
for s in self.math_functions_same:
|
432 |
+
dict_fun[s] = 'math.' + s
|
433 |
+
for k, v in self.math_functions_different.items():
|
434 |
+
dict_fun[k] = 'math.' + v
|
435 |
+
if self.use_python_cmath:
|
436 |
+
for s in self.cmath_functions_same:
|
437 |
+
dict_fun[s] = 'cmath.' + s
|
438 |
+
for k, v in self.cmath_functions_different.items():
|
439 |
+
dict_fun[k] = 'cmath.' + v
|
440 |
+
if self.use_interval:
|
441 |
+
for s in self.interval_functions_same:
|
442 |
+
dict_fun[s] = 'imath.' + s
|
443 |
+
for k, v in self.interval_functions_different.items():
|
444 |
+
dict_fun[k] = 'imath.' + v
|
445 |
+
return dict_fun
|
446 |
+
|
447 |
+
##############################################################################
|
448 |
+
# The translator functions, tree parsers, etc.
|
449 |
+
##############################################################################
|
450 |
+
|
451 |
+
def str2tree(self, exprstr):
|
452 |
+
"""Converts an expression string to a tree.
|
453 |
+
|
454 |
+
Explanation
|
455 |
+
===========
|
456 |
+
|
457 |
+
Functions are represented by ('func_name(', tree_of_arguments).
|
458 |
+
Other expressions are (head_string, mid_tree, tail_str).
|
459 |
+
Expressions that do not contain functions are directly returned.
|
460 |
+
|
461 |
+
Examples
|
462 |
+
========
|
463 |
+
|
464 |
+
>>> from sympy.abc import x, y, z
|
465 |
+
>>> from sympy import Integral, sin
|
466 |
+
>>> from sympy.plotting.experimental_lambdify import Lambdifier
|
467 |
+
>>> str2tree = Lambdifier([x], x).str2tree
|
468 |
+
|
469 |
+
>>> str2tree(str(Integral(x, (x, 1, y))))
|
470 |
+
('', ('Integral(', 'x, (x, 1, y)'), ')')
|
471 |
+
>>> str2tree(str(x+y))
|
472 |
+
'x + y'
|
473 |
+
>>> str2tree(str(x+y*sin(z)+1))
|
474 |
+
('x + y*', ('sin(', 'z'), ') + 1')
|
475 |
+
>>> str2tree('sin(y*(y + 1.1) + (sin(y)))')
|
476 |
+
('', ('sin(', ('y*(y + 1.1) + (', ('sin(', 'y'), '))')), ')')
|
477 |
+
"""
|
478 |
+
#matches the first 'function_name('
|
479 |
+
first_par = re.search(r'(\w+\()', exprstr)
|
480 |
+
if first_par is None:
|
481 |
+
return exprstr
|
482 |
+
else:
|
483 |
+
start = first_par.start()
|
484 |
+
end = first_par.end()
|
485 |
+
head = exprstr[:start]
|
486 |
+
func = exprstr[start:end]
|
487 |
+
tail = exprstr[end:]
|
488 |
+
count = 0
|
489 |
+
for i, c in enumerate(tail):
|
490 |
+
if c == '(':
|
491 |
+
count += 1
|
492 |
+
elif c == ')':
|
493 |
+
count -= 1
|
494 |
+
if count == -1:
|
495 |
+
break
|
496 |
+
func_tail = self.str2tree(tail[:i])
|
497 |
+
tail = self.str2tree(tail[i:])
|
498 |
+
return (head, (func, func_tail), tail)
|
499 |
+
|
500 |
+
@classmethod
|
501 |
+
def tree2str(cls, tree):
|
502 |
+
"""Converts a tree to string without translations.
|
503 |
+
|
504 |
+
Examples
|
505 |
+
========
|
506 |
+
|
507 |
+
>>> from sympy.abc import x, y, z
|
508 |
+
>>> from sympy import sin
|
509 |
+
>>> from sympy.plotting.experimental_lambdify import Lambdifier
|
510 |
+
>>> str2tree = Lambdifier([x], x).str2tree
|
511 |
+
>>> tree2str = Lambdifier([x], x).tree2str
|
512 |
+
|
513 |
+
>>> tree2str(str2tree(str(x+y*sin(z)+1)))
|
514 |
+
'x + y*sin(z) + 1'
|
515 |
+
"""
|
516 |
+
if isinstance(tree, str):
|
517 |
+
return tree
|
518 |
+
else:
|
519 |
+
return ''.join(map(cls.tree2str, tree))
|
520 |
+
|
521 |
+
def tree2str_translate(self, tree):
|
522 |
+
"""Converts a tree to string with translations.
|
523 |
+
|
524 |
+
Explanation
|
525 |
+
===========
|
526 |
+
|
527 |
+
Function names are translated by translate_func.
|
528 |
+
Other strings are translated by translate_str.
|
529 |
+
"""
|
530 |
+
if isinstance(tree, str):
|
531 |
+
return self.translate_str(tree)
|
532 |
+
elif isinstance(tree, tuple) and len(tree) == 2:
|
533 |
+
return self.translate_func(tree[0][:-1], tree[1])
|
534 |
+
else:
|
535 |
+
return ''.join([self.tree2str_translate(t) for t in tree])
|
536 |
+
|
537 |
+
def translate_str(self, estr):
|
538 |
+
"""Translate substrings of estr using in order the dictionaries in
|
539 |
+
dict_tuple_str."""
|
540 |
+
for pattern, repl in self.dict_str.items():
|
541 |
+
estr = re.sub(pattern, repl, estr)
|
542 |
+
return estr
|
543 |
+
|
544 |
+
def translate_func(self, func_name, argtree):
|
545 |
+
"""Translate function names and the tree of arguments.
|
546 |
+
|
547 |
+
Explanation
|
548 |
+
===========
|
549 |
+
|
550 |
+
If the function name is not in the dictionaries of dict_tuple_fun then the
|
551 |
+
function is surrounded by a float((...).evalf()).
|
552 |
+
|
553 |
+
The use of float is necessary as np.<function>(sympy.Float(..)) raises an
|
554 |
+
error."""
|
555 |
+
if func_name in self.dict_fun:
|
556 |
+
new_name = self.dict_fun[func_name]
|
557 |
+
argstr = self.tree2str_translate(argtree)
|
558 |
+
return new_name + '(' + argstr
|
559 |
+
elif func_name in ['Eq', 'Ne']:
|
560 |
+
op = {'Eq': '==', 'Ne': '!='}
|
561 |
+
return "(lambda x, y: x {} y)({}".format(op[func_name], self.tree2str_translate(argtree))
|
562 |
+
else:
|
563 |
+
template = '(%s(%s)).evalf(' if self.use_evalf else '%s(%s'
|
564 |
+
if self.float_wrap_evalf:
|
565 |
+
template = 'float(%s)' % template
|
566 |
+
elif self.complex_wrap_evalf:
|
567 |
+
template = 'complex(%s)' % template
|
568 |
+
|
569 |
+
# Wrapping should only happen on the outermost expression, which
|
570 |
+
# is the only thing we know will be a number.
|
571 |
+
float_wrap_evalf = self.float_wrap_evalf
|
572 |
+
complex_wrap_evalf = self.complex_wrap_evalf
|
573 |
+
self.float_wrap_evalf = False
|
574 |
+
self.complex_wrap_evalf = False
|
575 |
+
ret = template % (func_name, self.tree2str_translate(argtree))
|
576 |
+
self.float_wrap_evalf = float_wrap_evalf
|
577 |
+
self.complex_wrap_evalf = complex_wrap_evalf
|
578 |
+
return ret
|
579 |
+
|
580 |
+
##############################################################################
|
581 |
+
# The namespace constructors
|
582 |
+
##############################################################################
|
583 |
+
|
584 |
+
@classmethod
|
585 |
+
def sympy_expression_namespace(cls, expr):
|
586 |
+
"""Traverses the (func, args) tree of an expression and creates a SymPy
|
587 |
+
namespace. All other modules are imported only as a module name. That way
|
588 |
+
the namespace is not polluted and rests quite small. It probably causes much
|
589 |
+
more variable lookups and so it takes more time, but there are no tests on
|
590 |
+
that for the moment."""
|
591 |
+
if expr is None:
|
592 |
+
return {}
|
593 |
+
else:
|
594 |
+
funcname = str(expr.func)
|
595 |
+
# XXX Workaround
|
596 |
+
# Here we add an ugly workaround because str(func(x))
|
597 |
+
# is not always the same as str(func). Eg
|
598 |
+
# >>> str(Integral(x))
|
599 |
+
# "Integral(x)"
|
600 |
+
# >>> str(Integral)
|
601 |
+
# "<class 'sympy.integrals.integrals.Integral'>"
|
602 |
+
# >>> str(sqrt(x))
|
603 |
+
# "sqrt(x)"
|
604 |
+
# >>> str(sqrt)
|
605 |
+
# "<function sqrt at 0x3d92de8>"
|
606 |
+
# >>> str(sin(x))
|
607 |
+
# "sin(x)"
|
608 |
+
# >>> str(sin)
|
609 |
+
# "sin"
|
610 |
+
# Either one of those can be used but not all at the same time.
|
611 |
+
# The code considers the sin example as the right one.
|
612 |
+
regexlist = [
|
613 |
+
r'<class \'sympy[\w.]*?.([\w]*)\'>$',
|
614 |
+
# the example Integral
|
615 |
+
r'<function ([\w]*) at 0x[\w]*>$', # the example sqrt
|
616 |
+
]
|
617 |
+
for r in regexlist:
|
618 |
+
m = re.match(r, funcname)
|
619 |
+
if m is not None:
|
620 |
+
funcname = m.groups()[0]
|
621 |
+
# End of the workaround
|
622 |
+
# XXX debug: print funcname
|
623 |
+
args_dict = {}
|
624 |
+
for a in expr.args:
|
625 |
+
if (isinstance(a, (Symbol, NumberSymbol)) or a in [I, zoo, oo]):
|
626 |
+
continue
|
627 |
+
else:
|
628 |
+
args_dict.update(cls.sympy_expression_namespace(a))
|
629 |
+
args_dict.update({funcname: expr.func})
|
630 |
+
return args_dict
|
631 |
+
|
632 |
+
@staticmethod
|
633 |
+
def sympy_atoms_namespace(expr):
|
634 |
+
"""For no real reason this function is separated from
|
635 |
+
sympy_expression_namespace. It can be moved to it."""
|
636 |
+
atoms = expr.atoms(Symbol, NumberSymbol, I, zoo, oo)
|
637 |
+
d = {}
|
638 |
+
for a in atoms:
|
639 |
+
# XXX debug: print 'atom:' + str(a)
|
640 |
+
d[str(a)] = a
|
641 |
+
return d
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/plot.py
ADDED
@@ -0,0 +1,1234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Plotting module for SymPy.
|
2 |
+
|
3 |
+
A plot is represented by the ``Plot`` class that contains a reference to the
|
4 |
+
backend and a list of the data series to be plotted. The data series are
|
5 |
+
instances of classes meant to simplify getting points and meshes from SymPy
|
6 |
+
expressions. ``plot_backends`` is a dictionary with all the backends.
|
7 |
+
|
8 |
+
This module gives only the essential. For all the fancy stuff use directly
|
9 |
+
the backend. You can get the backend wrapper for every plot from the
|
10 |
+
``_backend`` attribute. Moreover the data series classes have various useful
|
11 |
+
methods like ``get_points``, ``get_meshes``, etc, that may
|
12 |
+
be useful if you wish to use another plotting library.
|
13 |
+
|
14 |
+
Especially if you need publication ready graphs and this module is not enough
|
15 |
+
for you - just get the ``_backend`` attribute and add whatever you want
|
16 |
+
directly to it. In the case of matplotlib (the common way to graph data in
|
17 |
+
python) just copy ``_backend.fig`` which is the figure and ``_backend.ax``
|
18 |
+
which is the axis and work on them as you would on any other matplotlib object.
|
19 |
+
|
20 |
+
Simplicity of code takes much greater importance than performance. Do not use it
|
21 |
+
if you care at all about performance. A new backend instance is initialized
|
22 |
+
every time you call ``show()`` and the old one is left to the garbage collector.
|
23 |
+
"""
|
24 |
+
|
25 |
+
from sympy.concrete.summations import Sum
|
26 |
+
from sympy.core.containers import Tuple
|
27 |
+
from sympy.core.expr import Expr
|
28 |
+
from sympy.core.function import Function, AppliedUndef
|
29 |
+
from sympy.core.symbol import (Dummy, Symbol, Wild)
|
30 |
+
from sympy.external import import_module
|
31 |
+
from sympy.functions import sign
|
32 |
+
from sympy.plotting.backends.base_backend import Plot
|
33 |
+
from sympy.plotting.backends.matplotlibbackend import MatplotlibBackend
|
34 |
+
from sympy.plotting.backends.textbackend import TextBackend
|
35 |
+
from sympy.plotting.series import (
|
36 |
+
LineOver1DRangeSeries, Parametric2DLineSeries, Parametric3DLineSeries,
|
37 |
+
ParametricSurfaceSeries, SurfaceOver2DRangeSeries, ContourSeries)
|
38 |
+
from sympy.plotting.utils import _check_arguments, _plot_sympify
|
39 |
+
from sympy.tensor.indexed import Indexed
|
40 |
+
# to maintain back-compatibility
|
41 |
+
from sympy.plotting.plotgrid import PlotGrid # noqa: F401
|
42 |
+
from sympy.plotting.series import BaseSeries # noqa: F401
|
43 |
+
from sympy.plotting.series import Line2DBaseSeries # noqa: F401
|
44 |
+
from sympy.plotting.series import Line3DBaseSeries # noqa: F401
|
45 |
+
from sympy.plotting.series import SurfaceBaseSeries # noqa: F401
|
46 |
+
from sympy.plotting.series import List2DSeries # noqa: F401
|
47 |
+
from sympy.plotting.series import GenericDataSeries # noqa: F401
|
48 |
+
from sympy.plotting.series import centers_of_faces # noqa: F401
|
49 |
+
from sympy.plotting.series import centers_of_segments # noqa: F401
|
50 |
+
from sympy.plotting.series import flat # noqa: F401
|
51 |
+
from sympy.plotting.backends.base_backend import unset_show # noqa: F401
|
52 |
+
from sympy.plotting.backends.matplotlibbackend import _matplotlib_list # noqa: F401
|
53 |
+
from sympy.plotting.textplot import textplot # noqa: F401
|
54 |
+
|
55 |
+
|
56 |
+
__doctest_requires__ = {
|
57 |
+
('plot3d',
|
58 |
+
'plot3d_parametric_line',
|
59 |
+
'plot3d_parametric_surface',
|
60 |
+
'plot_parametric'): ['matplotlib'],
|
61 |
+
# XXX: The plot doctest possibly should not require matplotlib. It fails at
|
62 |
+
# plot(x**2, (x, -5, 5)) which should be fine for text backend.
|
63 |
+
('plot',): ['matplotlib'],
|
64 |
+
}
|
65 |
+
|
66 |
+
|
67 |
+
def _process_summations(sum_bound, *args):
|
68 |
+
"""Substitute oo (infinity) in the lower/upper bounds of a summation with
|
69 |
+
some integer number.
|
70 |
+
|
71 |
+
Parameters
|
72 |
+
==========
|
73 |
+
|
74 |
+
sum_bound : int
|
75 |
+
oo will be substituted with this integer number.
|
76 |
+
*args : list/tuple
|
77 |
+
pre-processed arguments of the form (expr, range, ...)
|
78 |
+
|
79 |
+
Notes
|
80 |
+
=====
|
81 |
+
Let's consider the following summation: ``Sum(1 / x**2, (x, 1, oo))``.
|
82 |
+
The current implementation of lambdify (SymPy 1.12 at the time of
|
83 |
+
writing this) will create something of this form:
|
84 |
+
``sum(1 / x**2 for x in range(1, INF))``
|
85 |
+
The problem is that ``type(INF)`` is float, while ``range`` requires
|
86 |
+
integers: the evaluation fails.
|
87 |
+
Instead of modifying ``lambdify`` (which requires a deep knowledge), just
|
88 |
+
replace it with some integer number.
|
89 |
+
"""
|
90 |
+
def new_bound(t, bound):
|
91 |
+
if (not t.is_number) or t.is_finite:
|
92 |
+
return t
|
93 |
+
if sign(t) >= 0:
|
94 |
+
return bound
|
95 |
+
return -bound
|
96 |
+
|
97 |
+
args = list(args)
|
98 |
+
expr = args[0]
|
99 |
+
|
100 |
+
# select summations whose lower/upper bound is infinity
|
101 |
+
w = Wild("w", properties=[
|
102 |
+
lambda t: isinstance(t, Sum),
|
103 |
+
lambda t: any((not a[1].is_finite) or (not a[2].is_finite) for i, a in enumerate(t.args) if i > 0)
|
104 |
+
])
|
105 |
+
|
106 |
+
for t in list(expr.find(w)):
|
107 |
+
sums_args = list(t.args)
|
108 |
+
for i, a in enumerate(sums_args):
|
109 |
+
if i > 0:
|
110 |
+
sums_args[i] = (a[0], new_bound(a[1], sum_bound),
|
111 |
+
new_bound(a[2], sum_bound))
|
112 |
+
s = Sum(*sums_args)
|
113 |
+
expr = expr.subs(t, s)
|
114 |
+
args[0] = expr
|
115 |
+
return args
|
116 |
+
|
117 |
+
|
118 |
+
def _build_line_series(*args, **kwargs):
|
119 |
+
"""Loop over the provided arguments and create the necessary line series.
|
120 |
+
"""
|
121 |
+
series = []
|
122 |
+
sum_bound = int(kwargs.get("sum_bound", 1000))
|
123 |
+
for arg in args:
|
124 |
+
expr, r, label, rendering_kw = arg
|
125 |
+
kw = kwargs.copy()
|
126 |
+
if rendering_kw is not None:
|
127 |
+
kw["rendering_kw"] = rendering_kw
|
128 |
+
# TODO: _process_piecewise check goes here
|
129 |
+
if not callable(expr):
|
130 |
+
arg = _process_summations(sum_bound, *arg)
|
131 |
+
series.append(LineOver1DRangeSeries(*arg[:-1], **kw))
|
132 |
+
return series
|
133 |
+
|
134 |
+
|
135 |
+
def _create_series(series_type, plot_expr, **kwargs):
|
136 |
+
"""Extract the rendering_kw dictionary from the provided arguments and
|
137 |
+
create an appropriate data series.
|
138 |
+
"""
|
139 |
+
series = []
|
140 |
+
for args in plot_expr:
|
141 |
+
kw = kwargs.copy()
|
142 |
+
if args[-1] is not None:
|
143 |
+
kw["rendering_kw"] = args[-1]
|
144 |
+
series.append(series_type(*args[:-1], **kw))
|
145 |
+
return series
|
146 |
+
|
147 |
+
|
148 |
+
def _set_labels(series, labels, rendering_kw):
|
149 |
+
"""Apply the `label` and `rendering_kw` keyword arguments to the series.
|
150 |
+
"""
|
151 |
+
if not isinstance(labels, (list, tuple)):
|
152 |
+
labels = [labels]
|
153 |
+
if len(labels) > 0:
|
154 |
+
if len(labels) == 1 and len(series) > 1:
|
155 |
+
# if one label is provided and multiple series are being plotted,
|
156 |
+
# set the same label to all data series. It maintains
|
157 |
+
# back-compatibility
|
158 |
+
labels *= len(series)
|
159 |
+
if len(series) != len(labels):
|
160 |
+
raise ValueError("The number of labels must be equal to the "
|
161 |
+
"number of expressions being plotted.\nReceived "
|
162 |
+
f"{len(series)} expressions and {len(labels)} labels")
|
163 |
+
|
164 |
+
for s, l in zip(series, labels):
|
165 |
+
s.label = l
|
166 |
+
|
167 |
+
if rendering_kw:
|
168 |
+
if isinstance(rendering_kw, dict):
|
169 |
+
rendering_kw = [rendering_kw]
|
170 |
+
if len(rendering_kw) == 1:
|
171 |
+
rendering_kw *= len(series)
|
172 |
+
elif len(series) != len(rendering_kw):
|
173 |
+
raise ValueError("The number of rendering dictionaries must be "
|
174 |
+
"equal to the number of expressions being plotted.\nReceived "
|
175 |
+
f"{len(series)} expressions and {len(labels)} labels")
|
176 |
+
for s, r in zip(series, rendering_kw):
|
177 |
+
s.rendering_kw = r
|
178 |
+
|
179 |
+
|
180 |
+
def plot_factory(*args, **kwargs):
|
181 |
+
backend = kwargs.pop("backend", "default")
|
182 |
+
if isinstance(backend, str):
|
183 |
+
if backend == "default":
|
184 |
+
matplotlib = import_module('matplotlib',
|
185 |
+
min_module_version='1.1.0', catch=(RuntimeError,))
|
186 |
+
if matplotlib:
|
187 |
+
return MatplotlibBackend(*args, **kwargs)
|
188 |
+
return TextBackend(*args, **kwargs)
|
189 |
+
return plot_backends[backend](*args, **kwargs)
|
190 |
+
elif (type(backend) == type) and issubclass(backend, Plot):
|
191 |
+
return backend(*args, **kwargs)
|
192 |
+
else:
|
193 |
+
raise TypeError("backend must be either a string or a subclass of ``Plot``.")
|
194 |
+
|
195 |
+
|
196 |
+
plot_backends = {
|
197 |
+
'matplotlib': MatplotlibBackend,
|
198 |
+
'text': TextBackend,
|
199 |
+
}
|
200 |
+
|
201 |
+
|
202 |
+
####New API for plotting module ####
|
203 |
+
|
204 |
+
# TODO: Add color arrays for plots.
|
205 |
+
# TODO: Add more plotting options for 3d plots.
|
206 |
+
# TODO: Adaptive sampling for 3D plots.
|
207 |
+
|
208 |
+
def plot(*args, show=True, **kwargs):
|
209 |
+
"""Plots a function of a single variable as a curve.
|
210 |
+
|
211 |
+
Parameters
|
212 |
+
==========
|
213 |
+
|
214 |
+
args :
|
215 |
+
The first argument is the expression representing the function
|
216 |
+
of single variable to be plotted.
|
217 |
+
|
218 |
+
The last argument is a 3-tuple denoting the range of the free
|
219 |
+
variable. e.g. ``(x, 0, 5)``
|
220 |
+
|
221 |
+
Typical usage examples are in the following:
|
222 |
+
|
223 |
+
- Plotting a single expression with a single range.
|
224 |
+
``plot(expr, range, **kwargs)``
|
225 |
+
- Plotting a single expression with the default range (-10, 10).
|
226 |
+
``plot(expr, **kwargs)``
|
227 |
+
- Plotting multiple expressions with a single range.
|
228 |
+
``plot(expr1, expr2, ..., range, **kwargs)``
|
229 |
+
- Plotting multiple expressions with multiple ranges.
|
230 |
+
``plot((expr1, range1), (expr2, range2), ..., **kwargs)``
|
231 |
+
|
232 |
+
It is best practice to specify range explicitly because default
|
233 |
+
range may change in the future if a more advanced default range
|
234 |
+
detection algorithm is implemented.
|
235 |
+
|
236 |
+
show : bool, optional
|
237 |
+
The default value is set to ``True``. Set show to ``False`` and
|
238 |
+
the function will not display the plot. The returned instance of
|
239 |
+
the ``Plot`` class can then be used to save or display the plot
|
240 |
+
by calling the ``save()`` and ``show()`` methods respectively.
|
241 |
+
|
242 |
+
line_color : string, or float, or function, optional
|
243 |
+
Specifies the color for the plot.
|
244 |
+
See ``Plot`` to see how to set color for the plots.
|
245 |
+
Note that by setting ``line_color``, it would be applied simultaneously
|
246 |
+
to all the series.
|
247 |
+
|
248 |
+
title : str, optional
|
249 |
+
Title of the plot. It is set to the latex representation of
|
250 |
+
the expression, if the plot has only one expression.
|
251 |
+
|
252 |
+
label : str, optional
|
253 |
+
The label of the expression in the plot. It will be used when
|
254 |
+
called with ``legend``. Default is the name of the expression.
|
255 |
+
e.g. ``sin(x)``
|
256 |
+
|
257 |
+
xlabel : str or expression, optional
|
258 |
+
Label for the x-axis.
|
259 |
+
|
260 |
+
ylabel : str or expression, optional
|
261 |
+
Label for the y-axis.
|
262 |
+
|
263 |
+
xscale : 'linear' or 'log', optional
|
264 |
+
Sets the scaling of the x-axis.
|
265 |
+
|
266 |
+
yscale : 'linear' or 'log', optional
|
267 |
+
Sets the scaling of the y-axis.
|
268 |
+
|
269 |
+
axis_center : (float, float), optional
|
270 |
+
Tuple of two floats denoting the coordinates of the center or
|
271 |
+
{'center', 'auto'}
|
272 |
+
|
273 |
+
xlim : (float, float), optional
|
274 |
+
Denotes the x-axis limits, ``(min, max)```.
|
275 |
+
|
276 |
+
ylim : (float, float), optional
|
277 |
+
Denotes the y-axis limits, ``(min, max)```.
|
278 |
+
|
279 |
+
annotations : list, optional
|
280 |
+
A list of dictionaries specifying the type of annotation
|
281 |
+
required. The keys in the dictionary should be equivalent
|
282 |
+
to the arguments of the :external:mod:`matplotlib`'s
|
283 |
+
:external:meth:`~matplotlib.axes.Axes.annotate` method.
|
284 |
+
|
285 |
+
markers : list, optional
|
286 |
+
A list of dictionaries specifying the type the markers required.
|
287 |
+
The keys in the dictionary should be equivalent to the arguments
|
288 |
+
of the :external:mod:`matplotlib`'s :external:func:`~matplotlib.pyplot.plot()` function
|
289 |
+
along with the marker related keyworded arguments.
|
290 |
+
|
291 |
+
rectangles : list, optional
|
292 |
+
A list of dictionaries specifying the dimensions of the
|
293 |
+
rectangles to be plotted. The keys in the dictionary should be
|
294 |
+
equivalent to the arguments of the :external:mod:`matplotlib`'s
|
295 |
+
:external:class:`~matplotlib.patches.Rectangle` class.
|
296 |
+
|
297 |
+
fill : dict, optional
|
298 |
+
A dictionary specifying the type of color filling required in
|
299 |
+
the plot. The keys in the dictionary should be equivalent to the
|
300 |
+
arguments of the :external:mod:`matplotlib`'s
|
301 |
+
:external:meth:`~matplotlib.axes.Axes.fill_between` method.
|
302 |
+
|
303 |
+
adaptive : bool, optional
|
304 |
+
The default value is set to ``True``. Set adaptive to ``False``
|
305 |
+
and specify ``n`` if uniform sampling is required.
|
306 |
+
|
307 |
+
The plotting uses an adaptive algorithm which samples
|
308 |
+
recursively to accurately plot. The adaptive algorithm uses a
|
309 |
+
random point near the midpoint of two points that has to be
|
310 |
+
further sampled. Hence the same plots can appear slightly
|
311 |
+
different.
|
312 |
+
|
313 |
+
depth : int, optional
|
314 |
+
Recursion depth of the adaptive algorithm. A depth of value
|
315 |
+
`n` samples a maximum of `2^{n}` points.
|
316 |
+
|
317 |
+
If the ``adaptive`` flag is set to ``False``, this will be
|
318 |
+
ignored.
|
319 |
+
|
320 |
+
n : int, optional
|
321 |
+
Used when the ``adaptive`` is set to ``False``. The function
|
322 |
+
is uniformly sampled at ``n`` number of points. If the ``adaptive``
|
323 |
+
flag is set to ``True``, this will be ignored.
|
324 |
+
This keyword argument replaces ``nb_of_points``, which should be
|
325 |
+
considered deprecated.
|
326 |
+
|
327 |
+
size : (float, float), optional
|
328 |
+
A tuple in the form (width, height) in inches to specify the size of
|
329 |
+
the overall figure. The default value is set to ``None``, meaning
|
330 |
+
the size will be set by the default backend.
|
331 |
+
|
332 |
+
Examples
|
333 |
+
========
|
334 |
+
|
335 |
+
.. plot::
|
336 |
+
:context: close-figs
|
337 |
+
:format: doctest
|
338 |
+
:include-source: True
|
339 |
+
|
340 |
+
>>> from sympy import symbols
|
341 |
+
>>> from sympy.plotting import plot
|
342 |
+
>>> x = symbols('x')
|
343 |
+
|
344 |
+
Single Plot
|
345 |
+
|
346 |
+
.. plot::
|
347 |
+
:context: close-figs
|
348 |
+
:format: doctest
|
349 |
+
:include-source: True
|
350 |
+
|
351 |
+
>>> plot(x**2, (x, -5, 5))
|
352 |
+
Plot object containing:
|
353 |
+
[0]: cartesian line: x**2 for x over (-5.0, 5.0)
|
354 |
+
|
355 |
+
Multiple plots with single range.
|
356 |
+
|
357 |
+
.. plot::
|
358 |
+
:context: close-figs
|
359 |
+
:format: doctest
|
360 |
+
:include-source: True
|
361 |
+
|
362 |
+
>>> plot(x, x**2, x**3, (x, -5, 5))
|
363 |
+
Plot object containing:
|
364 |
+
[0]: cartesian line: x for x over (-5.0, 5.0)
|
365 |
+
[1]: cartesian line: x**2 for x over (-5.0, 5.0)
|
366 |
+
[2]: cartesian line: x**3 for x over (-5.0, 5.0)
|
367 |
+
|
368 |
+
Multiple plots with different ranges.
|
369 |
+
|
370 |
+
.. plot::
|
371 |
+
:context: close-figs
|
372 |
+
:format: doctest
|
373 |
+
:include-source: True
|
374 |
+
|
375 |
+
>>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
|
376 |
+
Plot object containing:
|
377 |
+
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
|
378 |
+
[1]: cartesian line: x for x over (-5.0, 5.0)
|
379 |
+
|
380 |
+
No adaptive sampling.
|
381 |
+
|
382 |
+
.. plot::
|
383 |
+
:context: close-figs
|
384 |
+
:format: doctest
|
385 |
+
:include-source: True
|
386 |
+
|
387 |
+
>>> plot(x**2, adaptive=False, n=400)
|
388 |
+
Plot object containing:
|
389 |
+
[0]: cartesian line: x**2 for x over (-10.0, 10.0)
|
390 |
+
|
391 |
+
See Also
|
392 |
+
========
|
393 |
+
|
394 |
+
Plot, LineOver1DRangeSeries
|
395 |
+
|
396 |
+
"""
|
397 |
+
args = _plot_sympify(args)
|
398 |
+
plot_expr = _check_arguments(args, 1, 1, **kwargs)
|
399 |
+
params = kwargs.get("params", None)
|
400 |
+
free = set()
|
401 |
+
for p in plot_expr:
|
402 |
+
if not isinstance(p[1][0], str):
|
403 |
+
free |= {p[1][0]}
|
404 |
+
else:
|
405 |
+
free |= {Symbol(p[1][0])}
|
406 |
+
if params:
|
407 |
+
free = free.difference(params.keys())
|
408 |
+
x = free.pop() if free else Symbol("x")
|
409 |
+
kwargs.setdefault('xlabel', x)
|
410 |
+
kwargs.setdefault('ylabel', Function('f')(x))
|
411 |
+
|
412 |
+
labels = kwargs.pop("label", [])
|
413 |
+
rendering_kw = kwargs.pop("rendering_kw", None)
|
414 |
+
series = _build_line_series(*plot_expr, **kwargs)
|
415 |
+
_set_labels(series, labels, rendering_kw)
|
416 |
+
|
417 |
+
plots = plot_factory(*series, **kwargs)
|
418 |
+
if show:
|
419 |
+
plots.show()
|
420 |
+
return plots
|
421 |
+
|
422 |
+
|
423 |
+
def plot_parametric(*args, show=True, **kwargs):
|
424 |
+
"""
|
425 |
+
Plots a 2D parametric curve.
|
426 |
+
|
427 |
+
Parameters
|
428 |
+
==========
|
429 |
+
|
430 |
+
args
|
431 |
+
Common specifications are:
|
432 |
+
|
433 |
+
- Plotting a single parametric curve with a range
|
434 |
+
``plot_parametric((expr_x, expr_y), range)``
|
435 |
+
- Plotting multiple parametric curves with the same range
|
436 |
+
``plot_parametric((expr_x, expr_y), ..., range)``
|
437 |
+
- Plotting multiple parametric curves with different ranges
|
438 |
+
``plot_parametric((expr_x, expr_y, range), ...)``
|
439 |
+
|
440 |
+
``expr_x`` is the expression representing $x$ component of the
|
441 |
+
parametric function.
|
442 |
+
|
443 |
+
``expr_y`` is the expression representing $y$ component of the
|
444 |
+
parametric function.
|
445 |
+
|
446 |
+
``range`` is a 3-tuple denoting the parameter symbol, start and
|
447 |
+
stop. For example, ``(u, 0, 5)``.
|
448 |
+
|
449 |
+
If the range is not specified, then a default range of (-10, 10)
|
450 |
+
is used.
|
451 |
+
|
452 |
+
However, if the arguments are specified as
|
453 |
+
``(expr_x, expr_y, range), ...``, you must specify the ranges
|
454 |
+
for each expressions manually.
|
455 |
+
|
456 |
+
Default range may change in the future if a more advanced
|
457 |
+
algorithm is implemented.
|
458 |
+
|
459 |
+
adaptive : bool, optional
|
460 |
+
Specifies whether to use the adaptive sampling or not.
|
461 |
+
|
462 |
+
The default value is set to ``True``. Set adaptive to ``False``
|
463 |
+
and specify ``n`` if uniform sampling is required.
|
464 |
+
|
465 |
+
depth : int, optional
|
466 |
+
The recursion depth of the adaptive algorithm. A depth of
|
467 |
+
value $n$ samples a maximum of $2^n$ points.
|
468 |
+
|
469 |
+
n : int, optional
|
470 |
+
Used when the ``adaptive`` flag is set to ``False``. Specifies the
|
471 |
+
number of the points used for the uniform sampling.
|
472 |
+
This keyword argument replaces ``nb_of_points``, which should be
|
473 |
+
considered deprecated.
|
474 |
+
|
475 |
+
line_color : string, or float, or function, optional
|
476 |
+
Specifies the color for the plot.
|
477 |
+
See ``Plot`` to see how to set color for the plots.
|
478 |
+
Note that by setting ``line_color``, it would be applied simultaneously
|
479 |
+
to all the series.
|
480 |
+
|
481 |
+
label : str, optional
|
482 |
+
The label of the expression in the plot. It will be used when
|
483 |
+
called with ``legend``. Default is the name of the expression.
|
484 |
+
e.g. ``sin(x)``
|
485 |
+
|
486 |
+
xlabel : str, optional
|
487 |
+
Label for the x-axis.
|
488 |
+
|
489 |
+
ylabel : str, optional
|
490 |
+
Label for the y-axis.
|
491 |
+
|
492 |
+
xscale : 'linear' or 'log', optional
|
493 |
+
Sets the scaling of the x-axis.
|
494 |
+
|
495 |
+
yscale : 'linear' or 'log', optional
|
496 |
+
Sets the scaling of the y-axis.
|
497 |
+
|
498 |
+
axis_center : (float, float), optional
|
499 |
+
Tuple of two floats denoting the coordinates of the center or
|
500 |
+
{'center', 'auto'}
|
501 |
+
|
502 |
+
xlim : (float, float), optional
|
503 |
+
Denotes the x-axis limits, ``(min, max)```.
|
504 |
+
|
505 |
+
ylim : (float, float), optional
|
506 |
+
Denotes the y-axis limits, ``(min, max)```.
|
507 |
+
|
508 |
+
size : (float, float), optional
|
509 |
+
A tuple in the form (width, height) in inches to specify the size of
|
510 |
+
the overall figure. The default value is set to ``None``, meaning
|
511 |
+
the size will be set by the default backend.
|
512 |
+
|
513 |
+
Examples
|
514 |
+
========
|
515 |
+
|
516 |
+
.. plot::
|
517 |
+
:context: reset
|
518 |
+
:format: doctest
|
519 |
+
:include-source: True
|
520 |
+
|
521 |
+
>>> from sympy import plot_parametric, symbols, cos, sin
|
522 |
+
>>> u = symbols('u')
|
523 |
+
|
524 |
+
A parametric plot with a single expression:
|
525 |
+
|
526 |
+
.. plot::
|
527 |
+
:context: close-figs
|
528 |
+
:format: doctest
|
529 |
+
:include-source: True
|
530 |
+
|
531 |
+
>>> plot_parametric((cos(u), sin(u)), (u, -5, 5))
|
532 |
+
Plot object containing:
|
533 |
+
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
|
534 |
+
|
535 |
+
A parametric plot with multiple expressions with the same range:
|
536 |
+
|
537 |
+
.. plot::
|
538 |
+
:context: close-figs
|
539 |
+
:format: doctest
|
540 |
+
:include-source: True
|
541 |
+
|
542 |
+
>>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10))
|
543 |
+
Plot object containing:
|
544 |
+
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0)
|
545 |
+
[1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0)
|
546 |
+
|
547 |
+
A parametric plot with multiple expressions with different ranges
|
548 |
+
for each curve:
|
549 |
+
|
550 |
+
.. plot::
|
551 |
+
:context: close-figs
|
552 |
+
:format: doctest
|
553 |
+
:include-source: True
|
554 |
+
|
555 |
+
>>> plot_parametric((cos(u), sin(u), (u, -5, 5)),
|
556 |
+
... (cos(u), u, (u, -5, 5)))
|
557 |
+
Plot object containing:
|
558 |
+
[0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
|
559 |
+
[1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0)
|
560 |
+
|
561 |
+
Notes
|
562 |
+
=====
|
563 |
+
|
564 |
+
The plotting uses an adaptive algorithm which samples recursively to
|
565 |
+
accurately plot the curve. The adaptive algorithm uses a random point
|
566 |
+
near the midpoint of two points that has to be further sampled.
|
567 |
+
Hence, repeating the same plot command can give slightly different
|
568 |
+
results because of the random sampling.
|
569 |
+
|
570 |
+
If there are multiple plots, then the same optional arguments are
|
571 |
+
applied to all the plots drawn in the same canvas. If you want to
|
572 |
+
set these options separately, you can index the returned ``Plot``
|
573 |
+
object and set it.
|
574 |
+
|
575 |
+
For example, when you specify ``line_color`` once, it would be
|
576 |
+
applied simultaneously to both series.
|
577 |
+
|
578 |
+
.. plot::
|
579 |
+
:context: close-figs
|
580 |
+
:format: doctest
|
581 |
+
:include-source: True
|
582 |
+
|
583 |
+
>>> from sympy import pi
|
584 |
+
>>> expr1 = (u, cos(2*pi*u)/2 + 1/2)
|
585 |
+
>>> expr2 = (u, sin(2*pi*u)/2 + 1/2)
|
586 |
+
>>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue')
|
587 |
+
|
588 |
+
If you want to specify the line color for the specific series, you
|
589 |
+
should index each item and apply the property manually.
|
590 |
+
|
591 |
+
.. plot::
|
592 |
+
:context: close-figs
|
593 |
+
:format: doctest
|
594 |
+
:include-source: True
|
595 |
+
|
596 |
+
>>> p[0].line_color = 'red'
|
597 |
+
>>> p.show()
|
598 |
+
|
599 |
+
See Also
|
600 |
+
========
|
601 |
+
|
602 |
+
Plot, Parametric2DLineSeries
|
603 |
+
"""
|
604 |
+
args = _plot_sympify(args)
|
605 |
+
plot_expr = _check_arguments(args, 2, 1, **kwargs)
|
606 |
+
|
607 |
+
labels = kwargs.pop("label", [])
|
608 |
+
rendering_kw = kwargs.pop("rendering_kw", None)
|
609 |
+
series = _create_series(Parametric2DLineSeries, plot_expr, **kwargs)
|
610 |
+
_set_labels(series, labels, rendering_kw)
|
611 |
+
|
612 |
+
plots = plot_factory(*series, **kwargs)
|
613 |
+
if show:
|
614 |
+
plots.show()
|
615 |
+
return plots
|
616 |
+
|
617 |
+
|
618 |
+
def plot3d_parametric_line(*args, show=True, **kwargs):
|
619 |
+
"""
|
620 |
+
Plots a 3D parametric line plot.
|
621 |
+
|
622 |
+
Usage
|
623 |
+
=====
|
624 |
+
|
625 |
+
Single plot:
|
626 |
+
|
627 |
+
``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)``
|
628 |
+
|
629 |
+
If the range is not specified, then a default range of (-10, 10) is used.
|
630 |
+
|
631 |
+
Multiple plots.
|
632 |
+
|
633 |
+
``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)``
|
634 |
+
|
635 |
+
Ranges have to be specified for every expression.
|
636 |
+
|
637 |
+
Default range may change in the future if a more advanced default range
|
638 |
+
detection algorithm is implemented.
|
639 |
+
|
640 |
+
Arguments
|
641 |
+
=========
|
642 |
+
|
643 |
+
expr_x : Expression representing the function along x.
|
644 |
+
|
645 |
+
expr_y : Expression representing the function along y.
|
646 |
+
|
647 |
+
expr_z : Expression representing the function along z.
|
648 |
+
|
649 |
+
range : (:class:`~.Symbol`, float, float)
|
650 |
+
A 3-tuple denoting the range of the parameter variable, e.g., (u, 0, 5).
|
651 |
+
|
652 |
+
Keyword Arguments
|
653 |
+
=================
|
654 |
+
|
655 |
+
Arguments for ``Parametric3DLineSeries`` class.
|
656 |
+
|
657 |
+
n : int
|
658 |
+
The range is uniformly sampled at ``n`` number of points.
|
659 |
+
This keyword argument replaces ``nb_of_points``, which should be
|
660 |
+
considered deprecated.
|
661 |
+
|
662 |
+
Aesthetics:
|
663 |
+
|
664 |
+
line_color : string, or float, or function, optional
|
665 |
+
Specifies the color for the plot.
|
666 |
+
See ``Plot`` to see how to set color for the plots.
|
667 |
+
Note that by setting ``line_color``, it would be applied simultaneously
|
668 |
+
to all the series.
|
669 |
+
|
670 |
+
label : str
|
671 |
+
The label to the plot. It will be used when called with ``legend=True``
|
672 |
+
to denote the function with the given label in the plot.
|
673 |
+
|
674 |
+
If there are multiple plots, then the same series arguments are applied to
|
675 |
+
all the plots. If you want to set these options separately, you can index
|
676 |
+
the returned ``Plot`` object and set it.
|
677 |
+
|
678 |
+
Arguments for ``Plot`` class.
|
679 |
+
|
680 |
+
title : str
|
681 |
+
Title of the plot.
|
682 |
+
|
683 |
+
size : (float, float), optional
|
684 |
+
A tuple in the form (width, height) in inches to specify the size of
|
685 |
+
the overall figure. The default value is set to ``None``, meaning
|
686 |
+
the size will be set by the default backend.
|
687 |
+
|
688 |
+
Examples
|
689 |
+
========
|
690 |
+
|
691 |
+
.. plot::
|
692 |
+
:context: reset
|
693 |
+
:format: doctest
|
694 |
+
:include-source: True
|
695 |
+
|
696 |
+
>>> from sympy import symbols, cos, sin
|
697 |
+
>>> from sympy.plotting import plot3d_parametric_line
|
698 |
+
>>> u = symbols('u')
|
699 |
+
|
700 |
+
Single plot.
|
701 |
+
|
702 |
+
.. plot::
|
703 |
+
:context: close-figs
|
704 |
+
:format: doctest
|
705 |
+
:include-source: True
|
706 |
+
|
707 |
+
>>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5))
|
708 |
+
Plot object containing:
|
709 |
+
[0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
|
710 |
+
|
711 |
+
|
712 |
+
Multiple plots.
|
713 |
+
|
714 |
+
.. plot::
|
715 |
+
:context: close-figs
|
716 |
+
:format: doctest
|
717 |
+
:include-source: True
|
718 |
+
|
719 |
+
>>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)),
|
720 |
+
... (sin(u), u**2, u, (u, -5, 5)))
|
721 |
+
Plot object containing:
|
722 |
+
[0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
|
723 |
+
[1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0)
|
724 |
+
|
725 |
+
|
726 |
+
See Also
|
727 |
+
========
|
728 |
+
|
729 |
+
Plot, Parametric3DLineSeries
|
730 |
+
|
731 |
+
"""
|
732 |
+
args = _plot_sympify(args)
|
733 |
+
plot_expr = _check_arguments(args, 3, 1, **kwargs)
|
734 |
+
kwargs.setdefault("xlabel", "x")
|
735 |
+
kwargs.setdefault("ylabel", "y")
|
736 |
+
kwargs.setdefault("zlabel", "z")
|
737 |
+
|
738 |
+
labels = kwargs.pop("label", [])
|
739 |
+
rendering_kw = kwargs.pop("rendering_kw", None)
|
740 |
+
series = _create_series(Parametric3DLineSeries, plot_expr, **kwargs)
|
741 |
+
_set_labels(series, labels, rendering_kw)
|
742 |
+
|
743 |
+
plots = plot_factory(*series, **kwargs)
|
744 |
+
if show:
|
745 |
+
plots.show()
|
746 |
+
return plots
|
747 |
+
|
748 |
+
|
749 |
+
def _plot3d_plot_contour_helper(Series, *args, **kwargs):
|
750 |
+
"""plot3d and plot_contour are structurally identical. Let's reduce
|
751 |
+
code repetition.
|
752 |
+
"""
|
753 |
+
# NOTE: if this import would be at the top-module level, it would trigger
|
754 |
+
# SymPy's optional-dependencies tests to fail.
|
755 |
+
from sympy.vector import BaseScalar
|
756 |
+
|
757 |
+
args = _plot_sympify(args)
|
758 |
+
plot_expr = _check_arguments(args, 1, 2, **kwargs)
|
759 |
+
|
760 |
+
free_x = set()
|
761 |
+
free_y = set()
|
762 |
+
_types = (Symbol, BaseScalar, Indexed, AppliedUndef)
|
763 |
+
for p in plot_expr:
|
764 |
+
free_x |= {p[1][0]} if isinstance(p[1][0], _types) else {Symbol(p[1][0])}
|
765 |
+
free_y |= {p[2][0]} if isinstance(p[2][0], _types) else {Symbol(p[2][0])}
|
766 |
+
x = free_x.pop() if free_x else Symbol("x")
|
767 |
+
y = free_y.pop() if free_y else Symbol("y")
|
768 |
+
kwargs.setdefault("xlabel", x)
|
769 |
+
kwargs.setdefault("ylabel", y)
|
770 |
+
kwargs.setdefault("zlabel", Function('f')(x, y))
|
771 |
+
|
772 |
+
# if a polar discretization is requested and automatic labelling has ben
|
773 |
+
# applied, hide the labels on the x-y axis.
|
774 |
+
if kwargs.get("is_polar", False):
|
775 |
+
if callable(kwargs["xlabel"]):
|
776 |
+
kwargs["xlabel"] = ""
|
777 |
+
if callable(kwargs["ylabel"]):
|
778 |
+
kwargs["ylabel"] = ""
|
779 |
+
|
780 |
+
labels = kwargs.pop("label", [])
|
781 |
+
rendering_kw = kwargs.pop("rendering_kw", None)
|
782 |
+
series = _create_series(Series, plot_expr, **kwargs)
|
783 |
+
_set_labels(series, labels, rendering_kw)
|
784 |
+
plots = plot_factory(*series, **kwargs)
|
785 |
+
if kwargs.get("show", True):
|
786 |
+
plots.show()
|
787 |
+
return plots
|
788 |
+
|
789 |
+
|
790 |
+
def plot3d(*args, show=True, **kwargs):
|
791 |
+
"""
|
792 |
+
Plots a 3D surface plot.
|
793 |
+
|
794 |
+
Usage
|
795 |
+
=====
|
796 |
+
|
797 |
+
Single plot
|
798 |
+
|
799 |
+
``plot3d(expr, range_x, range_y, **kwargs)``
|
800 |
+
|
801 |
+
If the ranges are not specified, then a default range of (-10, 10) is used.
|
802 |
+
|
803 |
+
Multiple plot with the same range.
|
804 |
+
|
805 |
+
``plot3d(expr1, expr2, range_x, range_y, **kwargs)``
|
806 |
+
|
807 |
+
If the ranges are not specified, then a default range of (-10, 10) is used.
|
808 |
+
|
809 |
+
Multiple plots with different ranges.
|
810 |
+
|
811 |
+
``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
|
812 |
+
|
813 |
+
Ranges have to be specified for every expression.
|
814 |
+
|
815 |
+
Default range may change in the future if a more advanced default range
|
816 |
+
detection algorithm is implemented.
|
817 |
+
|
818 |
+
Arguments
|
819 |
+
=========
|
820 |
+
|
821 |
+
expr : Expression representing the function along x.
|
822 |
+
|
823 |
+
range_x : (:class:`~.Symbol`, float, float)
|
824 |
+
A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).
|
825 |
+
|
826 |
+
range_y : (:class:`~.Symbol`, float, float)
|
827 |
+
A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).
|
828 |
+
|
829 |
+
Keyword Arguments
|
830 |
+
=================
|
831 |
+
|
832 |
+
Arguments for ``SurfaceOver2DRangeSeries`` class:
|
833 |
+
|
834 |
+
n1 : int
|
835 |
+
The x range is sampled uniformly at ``n1`` of points.
|
836 |
+
This keyword argument replaces ``nb_of_points_x``, which should be
|
837 |
+
considered deprecated.
|
838 |
+
|
839 |
+
n2 : int
|
840 |
+
The y range is sampled uniformly at ``n2`` of points.
|
841 |
+
This keyword argument replaces ``nb_of_points_y``, which should be
|
842 |
+
considered deprecated.
|
843 |
+
|
844 |
+
Aesthetics:
|
845 |
+
|
846 |
+
surface_color : Function which returns a float
|
847 |
+
Specifies the color for the surface of the plot.
|
848 |
+
See :class:`~.Plot` for more details.
|
849 |
+
|
850 |
+
If there are multiple plots, then the same series arguments are applied to
|
851 |
+
all the plots. If you want to set these options separately, you can index
|
852 |
+
the returned ``Plot`` object and set it.
|
853 |
+
|
854 |
+
Arguments for ``Plot`` class:
|
855 |
+
|
856 |
+
title : str
|
857 |
+
Title of the plot.
|
858 |
+
|
859 |
+
size : (float, float), optional
|
860 |
+
A tuple in the form (width, height) in inches to specify the size of the
|
861 |
+
overall figure. The default value is set to ``None``, meaning the size will
|
862 |
+
be set by the default backend.
|
863 |
+
|
864 |
+
Examples
|
865 |
+
========
|
866 |
+
|
867 |
+
.. plot::
|
868 |
+
:context: reset
|
869 |
+
:format: doctest
|
870 |
+
:include-source: True
|
871 |
+
|
872 |
+
>>> from sympy import symbols
|
873 |
+
>>> from sympy.plotting import plot3d
|
874 |
+
>>> x, y = symbols('x y')
|
875 |
+
|
876 |
+
Single plot
|
877 |
+
|
878 |
+
.. plot::
|
879 |
+
:context: close-figs
|
880 |
+
:format: doctest
|
881 |
+
:include-source: True
|
882 |
+
|
883 |
+
>>> plot3d(x*y, (x, -5, 5), (y, -5, 5))
|
884 |
+
Plot object containing:
|
885 |
+
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
|
886 |
+
|
887 |
+
|
888 |
+
Multiple plots with same range
|
889 |
+
|
890 |
+
.. plot::
|
891 |
+
:context: close-figs
|
892 |
+
:format: doctest
|
893 |
+
:include-source: True
|
894 |
+
|
895 |
+
>>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
|
896 |
+
Plot object containing:
|
897 |
+
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
|
898 |
+
[1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
|
899 |
+
|
900 |
+
|
901 |
+
Multiple plots with different ranges.
|
902 |
+
|
903 |
+
.. plot::
|
904 |
+
:context: close-figs
|
905 |
+
:format: doctest
|
906 |
+
:include-source: True
|
907 |
+
|
908 |
+
>>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)),
|
909 |
+
... (x*y, (x, -3, 3), (y, -3, 3)))
|
910 |
+
Plot object containing:
|
911 |
+
[0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0)
|
912 |
+
[1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0)
|
913 |
+
|
914 |
+
|
915 |
+
See Also
|
916 |
+
========
|
917 |
+
|
918 |
+
Plot, SurfaceOver2DRangeSeries
|
919 |
+
|
920 |
+
"""
|
921 |
+
kwargs.setdefault("show", show)
|
922 |
+
return _plot3d_plot_contour_helper(
|
923 |
+
SurfaceOver2DRangeSeries, *args, **kwargs)
|
924 |
+
|
925 |
+
|
926 |
+
def plot3d_parametric_surface(*args, show=True, **kwargs):
|
927 |
+
"""
|
928 |
+
Plots a 3D parametric surface plot.
|
929 |
+
|
930 |
+
Explanation
|
931 |
+
===========
|
932 |
+
|
933 |
+
Single plot.
|
934 |
+
|
935 |
+
``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)``
|
936 |
+
|
937 |
+
If the ranges is not specified, then a default range of (-10, 10) is used.
|
938 |
+
|
939 |
+
Multiple plots.
|
940 |
+
|
941 |
+
``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)``
|
942 |
+
|
943 |
+
Ranges have to be specified for every expression.
|
944 |
+
|
945 |
+
Default range may change in the future if a more advanced default range
|
946 |
+
detection algorithm is implemented.
|
947 |
+
|
948 |
+
Arguments
|
949 |
+
=========
|
950 |
+
|
951 |
+
expr_x : Expression representing the function along ``x``.
|
952 |
+
|
953 |
+
expr_y : Expression representing the function along ``y``.
|
954 |
+
|
955 |
+
expr_z : Expression representing the function along ``z``.
|
956 |
+
|
957 |
+
range_u : (:class:`~.Symbol`, float, float)
|
958 |
+
A 3-tuple denoting the range of the u variable, e.g. (u, 0, 5).
|
959 |
+
|
960 |
+
range_v : (:class:`~.Symbol`, float, float)
|
961 |
+
A 3-tuple denoting the range of the v variable, e.g. (v, 0, 5).
|
962 |
+
|
963 |
+
Keyword Arguments
|
964 |
+
=================
|
965 |
+
|
966 |
+
Arguments for ``ParametricSurfaceSeries`` class:
|
967 |
+
|
968 |
+
n1 : int
|
969 |
+
The ``u`` range is sampled uniformly at ``n1`` of points.
|
970 |
+
This keyword argument replaces ``nb_of_points_u``, which should be
|
971 |
+
considered deprecated.
|
972 |
+
|
973 |
+
n2 : int
|
974 |
+
The ``v`` range is sampled uniformly at ``n2`` of points.
|
975 |
+
This keyword argument replaces ``nb_of_points_v``, which should be
|
976 |
+
considered deprecated.
|
977 |
+
|
978 |
+
Aesthetics:
|
979 |
+
|
980 |
+
surface_color : Function which returns a float
|
981 |
+
Specifies the color for the surface of the plot. See
|
982 |
+
:class:`~Plot` for more details.
|
983 |
+
|
984 |
+
If there are multiple plots, then the same series arguments are applied for
|
985 |
+
all the plots. If you want to set these options separately, you can index
|
986 |
+
the returned ``Plot`` object and set it.
|
987 |
+
|
988 |
+
|
989 |
+
Arguments for ``Plot`` class:
|
990 |
+
|
991 |
+
title : str
|
992 |
+
Title of the plot.
|
993 |
+
|
994 |
+
size : (float, float), optional
|
995 |
+
A tuple in the form (width, height) in inches to specify the size of the
|
996 |
+
overall figure. The default value is set to ``None``, meaning the size will
|
997 |
+
be set by the default backend.
|
998 |
+
|
999 |
+
Examples
|
1000 |
+
========
|
1001 |
+
|
1002 |
+
.. plot::
|
1003 |
+
:context: reset
|
1004 |
+
:format: doctest
|
1005 |
+
:include-source: True
|
1006 |
+
|
1007 |
+
>>> from sympy import symbols, cos, sin
|
1008 |
+
>>> from sympy.plotting import plot3d_parametric_surface
|
1009 |
+
>>> u, v = symbols('u v')
|
1010 |
+
|
1011 |
+
Single plot.
|
1012 |
+
|
1013 |
+
.. plot::
|
1014 |
+
:context: close-figs
|
1015 |
+
:format: doctest
|
1016 |
+
:include-source: True
|
1017 |
+
|
1018 |
+
>>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v,
|
1019 |
+
... (u, -5, 5), (v, -5, 5))
|
1020 |
+
Plot object containing:
|
1021 |
+
[0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0)
|
1022 |
+
|
1023 |
+
|
1024 |
+
See Also
|
1025 |
+
========
|
1026 |
+
|
1027 |
+
Plot, ParametricSurfaceSeries
|
1028 |
+
|
1029 |
+
"""
|
1030 |
+
|
1031 |
+
args = _plot_sympify(args)
|
1032 |
+
plot_expr = _check_arguments(args, 3, 2, **kwargs)
|
1033 |
+
kwargs.setdefault("xlabel", "x")
|
1034 |
+
kwargs.setdefault("ylabel", "y")
|
1035 |
+
kwargs.setdefault("zlabel", "z")
|
1036 |
+
|
1037 |
+
labels = kwargs.pop("label", [])
|
1038 |
+
rendering_kw = kwargs.pop("rendering_kw", None)
|
1039 |
+
series = _create_series(ParametricSurfaceSeries, plot_expr, **kwargs)
|
1040 |
+
_set_labels(series, labels, rendering_kw)
|
1041 |
+
|
1042 |
+
plots = plot_factory(*series, **kwargs)
|
1043 |
+
if show:
|
1044 |
+
plots.show()
|
1045 |
+
return plots
|
1046 |
+
|
1047 |
+
def plot_contour(*args, show=True, **kwargs):
|
1048 |
+
"""
|
1049 |
+
Draws contour plot of a function
|
1050 |
+
|
1051 |
+
Usage
|
1052 |
+
=====
|
1053 |
+
|
1054 |
+
Single plot
|
1055 |
+
|
1056 |
+
``plot_contour(expr, range_x, range_y, **kwargs)``
|
1057 |
+
|
1058 |
+
If the ranges are not specified, then a default range of (-10, 10) is used.
|
1059 |
+
|
1060 |
+
Multiple plot with the same range.
|
1061 |
+
|
1062 |
+
``plot_contour(expr1, expr2, range_x, range_y, **kwargs)``
|
1063 |
+
|
1064 |
+
If the ranges are not specified, then a default range of (-10, 10) is used.
|
1065 |
+
|
1066 |
+
Multiple plots with different ranges.
|
1067 |
+
|
1068 |
+
``plot_contour((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
|
1069 |
+
|
1070 |
+
Ranges have to be specified for every expression.
|
1071 |
+
|
1072 |
+
Default range may change in the future if a more advanced default range
|
1073 |
+
detection algorithm is implemented.
|
1074 |
+
|
1075 |
+
Arguments
|
1076 |
+
=========
|
1077 |
+
|
1078 |
+
expr : Expression representing the function along x.
|
1079 |
+
|
1080 |
+
range_x : (:class:`Symbol`, float, float)
|
1081 |
+
A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).
|
1082 |
+
|
1083 |
+
range_y : (:class:`Symbol`, float, float)
|
1084 |
+
A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).
|
1085 |
+
|
1086 |
+
Keyword Arguments
|
1087 |
+
=================
|
1088 |
+
|
1089 |
+
Arguments for ``ContourSeries`` class:
|
1090 |
+
|
1091 |
+
n1 : int
|
1092 |
+
The x range is sampled uniformly at ``n1`` of points.
|
1093 |
+
This keyword argument replaces ``nb_of_points_x``, which should be
|
1094 |
+
considered deprecated.
|
1095 |
+
|
1096 |
+
n2 : int
|
1097 |
+
The y range is sampled uniformly at ``n2`` of points.
|
1098 |
+
This keyword argument replaces ``nb_of_points_y``, which should be
|
1099 |
+
considered deprecated.
|
1100 |
+
|
1101 |
+
Aesthetics:
|
1102 |
+
|
1103 |
+
surface_color : Function which returns a float
|
1104 |
+
Specifies the color for the surface of the plot. See
|
1105 |
+
:class:`sympy.plotting.Plot` for more details.
|
1106 |
+
|
1107 |
+
If there are multiple plots, then the same series arguments are applied to
|
1108 |
+
all the plots. If you want to set these options separately, you can index
|
1109 |
+
the returned ``Plot`` object and set it.
|
1110 |
+
|
1111 |
+
Arguments for ``Plot`` class:
|
1112 |
+
|
1113 |
+
title : str
|
1114 |
+
Title of the plot.
|
1115 |
+
|
1116 |
+
size : (float, float), optional
|
1117 |
+
A tuple in the form (width, height) in inches to specify the size of
|
1118 |
+
the overall figure. The default value is set to ``None``, meaning
|
1119 |
+
the size will be set by the default backend.
|
1120 |
+
|
1121 |
+
See Also
|
1122 |
+
========
|
1123 |
+
|
1124 |
+
Plot, ContourSeries
|
1125 |
+
|
1126 |
+
"""
|
1127 |
+
kwargs.setdefault("show", show)
|
1128 |
+
return _plot3d_plot_contour_helper(ContourSeries, *args, **kwargs)
|
1129 |
+
|
1130 |
+
|
1131 |
+
def check_arguments(args, expr_len, nb_of_free_symbols):
|
1132 |
+
"""
|
1133 |
+
Checks the arguments and converts into tuples of the
|
1134 |
+
form (exprs, ranges).
|
1135 |
+
|
1136 |
+
Examples
|
1137 |
+
========
|
1138 |
+
|
1139 |
+
.. plot::
|
1140 |
+
:context: reset
|
1141 |
+
:format: doctest
|
1142 |
+
:include-source: True
|
1143 |
+
|
1144 |
+
>>> from sympy import cos, sin, symbols
|
1145 |
+
>>> from sympy.plotting.plot import check_arguments
|
1146 |
+
>>> x = symbols('x')
|
1147 |
+
>>> check_arguments([cos(x), sin(x)], 2, 1)
|
1148 |
+
[(cos(x), sin(x), (x, -10, 10))]
|
1149 |
+
|
1150 |
+
>>> check_arguments([x, x**2], 1, 1)
|
1151 |
+
[(x, (x, -10, 10)), (x**2, (x, -10, 10))]
|
1152 |
+
"""
|
1153 |
+
if not args:
|
1154 |
+
return []
|
1155 |
+
if expr_len > 1 and isinstance(args[0], Expr):
|
1156 |
+
# Multiple expressions same range.
|
1157 |
+
# The arguments are tuples when the expression length is
|
1158 |
+
# greater than 1.
|
1159 |
+
if len(args) < expr_len:
|
1160 |
+
raise ValueError("len(args) should not be less than expr_len")
|
1161 |
+
for i in range(len(args)):
|
1162 |
+
if isinstance(args[i], Tuple):
|
1163 |
+
break
|
1164 |
+
else:
|
1165 |
+
i = len(args) + 1
|
1166 |
+
|
1167 |
+
exprs = Tuple(*args[:i])
|
1168 |
+
free_symbols = list(set().union(*[e.free_symbols for e in exprs]))
|
1169 |
+
if len(args) == expr_len + nb_of_free_symbols:
|
1170 |
+
#Ranges given
|
1171 |
+
plots = [exprs + Tuple(*args[expr_len:])]
|
1172 |
+
else:
|
1173 |
+
default_range = Tuple(-10, 10)
|
1174 |
+
ranges = []
|
1175 |
+
for symbol in free_symbols:
|
1176 |
+
ranges.append(Tuple(symbol) + default_range)
|
1177 |
+
|
1178 |
+
for i in range(len(free_symbols) - nb_of_free_symbols):
|
1179 |
+
ranges.append(Tuple(Dummy()) + default_range)
|
1180 |
+
plots = [exprs + Tuple(*ranges)]
|
1181 |
+
return plots
|
1182 |
+
|
1183 |
+
if isinstance(args[0], Expr) or (isinstance(args[0], Tuple) and
|
1184 |
+
len(args[0]) == expr_len and
|
1185 |
+
expr_len != 3):
|
1186 |
+
# Cannot handle expressions with number of expression = 3. It is
|
1187 |
+
# not possible to differentiate between expressions and ranges.
|
1188 |
+
#Series of plots with same range
|
1189 |
+
for i in range(len(args)):
|
1190 |
+
if isinstance(args[i], Tuple) and len(args[i]) != expr_len:
|
1191 |
+
break
|
1192 |
+
if not isinstance(args[i], Tuple):
|
1193 |
+
args[i] = Tuple(args[i])
|
1194 |
+
else:
|
1195 |
+
i = len(args) + 1
|
1196 |
+
|
1197 |
+
exprs = args[:i]
|
1198 |
+
assert all(isinstance(e, Expr) for expr in exprs for e in expr)
|
1199 |
+
free_symbols = list(set().union(*[e.free_symbols for expr in exprs
|
1200 |
+
for e in expr]))
|
1201 |
+
|
1202 |
+
if len(free_symbols) > nb_of_free_symbols:
|
1203 |
+
raise ValueError("The number of free_symbols in the expression "
|
1204 |
+
"is greater than %d" % nb_of_free_symbols)
|
1205 |
+
if len(args) == i + nb_of_free_symbols and isinstance(args[i], Tuple):
|
1206 |
+
ranges = Tuple(*list(args[
|
1207 |
+
i:i + nb_of_free_symbols]))
|
1208 |
+
plots = [expr + ranges for expr in exprs]
|
1209 |
+
return plots
|
1210 |
+
else:
|
1211 |
+
# Use default ranges.
|
1212 |
+
default_range = Tuple(-10, 10)
|
1213 |
+
ranges = []
|
1214 |
+
for symbol in free_symbols:
|
1215 |
+
ranges.append(Tuple(symbol) + default_range)
|
1216 |
+
|
1217 |
+
for i in range(nb_of_free_symbols - len(free_symbols)):
|
1218 |
+
ranges.append(Tuple(Dummy()) + default_range)
|
1219 |
+
ranges = Tuple(*ranges)
|
1220 |
+
plots = [expr + ranges for expr in exprs]
|
1221 |
+
return plots
|
1222 |
+
|
1223 |
+
elif isinstance(args[0], Tuple) and len(args[0]) == expr_len + nb_of_free_symbols:
|
1224 |
+
# Multiple plots with different ranges.
|
1225 |
+
for arg in args:
|
1226 |
+
for i in range(expr_len):
|
1227 |
+
if not isinstance(arg[i], Expr):
|
1228 |
+
raise ValueError("Expected an expression, given %s" %
|
1229 |
+
str(arg[i]))
|
1230 |
+
for i in range(nb_of_free_symbols):
|
1231 |
+
if not len(arg[i + expr_len]) == 3:
|
1232 |
+
raise ValueError("The ranges should be a tuple of "
|
1233 |
+
"length 3, got %s" % str(arg[i + expr_len]))
|
1234 |
+
return args
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/plot_implicit.py
ADDED
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Implicit plotting module for SymPy.
|
2 |
+
|
3 |
+
Explanation
|
4 |
+
===========
|
5 |
+
|
6 |
+
The module implements a data series called ImplicitSeries which is used by
|
7 |
+
``Plot`` class to plot implicit plots for different backends. The module,
|
8 |
+
by default, implements plotting using interval arithmetic. It switches to a
|
9 |
+
fall back algorithm if the expression cannot be plotted using interval arithmetic.
|
10 |
+
It is also possible to specify to use the fall back algorithm for all plots.
|
11 |
+
|
12 |
+
Boolean combinations of expressions cannot be plotted by the fall back
|
13 |
+
algorithm.
|
14 |
+
|
15 |
+
See Also
|
16 |
+
========
|
17 |
+
|
18 |
+
sympy.plotting.plot
|
19 |
+
|
20 |
+
References
|
21 |
+
==========
|
22 |
+
|
23 |
+
.. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for
|
24 |
+
Mathematical Formulae with Two Free Variables.
|
25 |
+
|
26 |
+
.. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval
|
27 |
+
Arithmetic. Master's thesis. University of Toronto, 1996
|
28 |
+
|
29 |
+
"""
|
30 |
+
|
31 |
+
|
32 |
+
from sympy.core.containers import Tuple
|
33 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
34 |
+
from sympy.polys.polyutils import _sort_gens
|
35 |
+
from sympy.plotting.series import ImplicitSeries, _set_discretization_points
|
36 |
+
from sympy.plotting.plot import plot_factory
|
37 |
+
from sympy.utilities.decorator import doctest_depends_on
|
38 |
+
from sympy.utilities.iterables import flatten
|
39 |
+
|
40 |
+
|
41 |
+
__doctest_requires__ = {'plot_implicit': ['matplotlib']}
|
42 |
+
|
43 |
+
|
44 |
+
@doctest_depends_on(modules=('matplotlib',))
|
45 |
+
def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0,
|
46 |
+
n=300, line_color="blue", show=True, **kwargs):
|
47 |
+
"""A plot function to plot implicit equations / inequalities.
|
48 |
+
|
49 |
+
Arguments
|
50 |
+
=========
|
51 |
+
|
52 |
+
- expr : The equation / inequality that is to be plotted.
|
53 |
+
- x_var (optional) : symbol to plot on x-axis or tuple giving symbol
|
54 |
+
and range as ``(symbol, xmin, xmax)``
|
55 |
+
- y_var (optional) : symbol to plot on y-axis or tuple giving symbol
|
56 |
+
and range as ``(symbol, ymin, ymax)``
|
57 |
+
|
58 |
+
If neither ``x_var`` nor ``y_var`` are given then the free symbols in the
|
59 |
+
expression will be assigned in the order they are sorted.
|
60 |
+
|
61 |
+
The following keyword arguments can also be used:
|
62 |
+
|
63 |
+
- ``adaptive`` Boolean. The default value is set to True. It has to be
|
64 |
+
set to False if you want to use a mesh grid.
|
65 |
+
|
66 |
+
- ``depth`` integer. The depth of recursion for adaptive mesh grid.
|
67 |
+
Default value is 0. Takes value in the range (0, 4).
|
68 |
+
|
69 |
+
- ``n`` integer. The number of points if adaptive mesh grid is not
|
70 |
+
used. Default value is 300. This keyword argument replaces ``points``,
|
71 |
+
which should be considered deprecated.
|
72 |
+
|
73 |
+
- ``show`` Boolean. Default value is True. If set to False, the plot will
|
74 |
+
not be shown. See ``Plot`` for further information.
|
75 |
+
|
76 |
+
- ``title`` string. The title for the plot.
|
77 |
+
|
78 |
+
- ``xlabel`` string. The label for the x-axis
|
79 |
+
|
80 |
+
- ``ylabel`` string. The label for the y-axis
|
81 |
+
|
82 |
+
Aesthetics options:
|
83 |
+
|
84 |
+
- ``line_color``: float or string. Specifies the color for the plot.
|
85 |
+
See ``Plot`` to see how to set color for the plots.
|
86 |
+
Default value is "Blue"
|
87 |
+
|
88 |
+
plot_implicit, by default, uses interval arithmetic to plot functions. If
|
89 |
+
the expression cannot be plotted using interval arithmetic, it defaults to
|
90 |
+
a generating a contour using a mesh grid of fixed number of points. By
|
91 |
+
setting adaptive to False, you can force plot_implicit to use the mesh
|
92 |
+
grid. The mesh grid method can be effective when adaptive plotting using
|
93 |
+
interval arithmetic, fails to plot with small line width.
|
94 |
+
|
95 |
+
Examples
|
96 |
+
========
|
97 |
+
|
98 |
+
Plot expressions:
|
99 |
+
|
100 |
+
.. plot::
|
101 |
+
:context: reset
|
102 |
+
:format: doctest
|
103 |
+
:include-source: True
|
104 |
+
|
105 |
+
>>> from sympy import plot_implicit, symbols, Eq, And
|
106 |
+
>>> x, y = symbols('x y')
|
107 |
+
|
108 |
+
Without any ranges for the symbols in the expression:
|
109 |
+
|
110 |
+
.. plot::
|
111 |
+
:context: close-figs
|
112 |
+
:format: doctest
|
113 |
+
:include-source: True
|
114 |
+
|
115 |
+
>>> p1 = plot_implicit(Eq(x**2 + y**2, 5))
|
116 |
+
|
117 |
+
With the range for the symbols:
|
118 |
+
|
119 |
+
.. plot::
|
120 |
+
:context: close-figs
|
121 |
+
:format: doctest
|
122 |
+
:include-source: True
|
123 |
+
|
124 |
+
>>> p2 = plot_implicit(
|
125 |
+
... Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3))
|
126 |
+
|
127 |
+
With depth of recursion as argument:
|
128 |
+
|
129 |
+
.. plot::
|
130 |
+
:context: close-figs
|
131 |
+
:format: doctest
|
132 |
+
:include-source: True
|
133 |
+
|
134 |
+
>>> p3 = plot_implicit(
|
135 |
+
... Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2)
|
136 |
+
|
137 |
+
Using mesh grid and not using adaptive meshing:
|
138 |
+
|
139 |
+
.. plot::
|
140 |
+
:context: close-figs
|
141 |
+
:format: doctest
|
142 |
+
:include-source: True
|
143 |
+
|
144 |
+
>>> p4 = plot_implicit(
|
145 |
+
... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
|
146 |
+
... adaptive=False)
|
147 |
+
|
148 |
+
Using mesh grid without using adaptive meshing with number of points
|
149 |
+
specified:
|
150 |
+
|
151 |
+
.. plot::
|
152 |
+
:context: close-figs
|
153 |
+
:format: doctest
|
154 |
+
:include-source: True
|
155 |
+
|
156 |
+
>>> p5 = plot_implicit(
|
157 |
+
... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
|
158 |
+
... adaptive=False, n=400)
|
159 |
+
|
160 |
+
Plotting regions:
|
161 |
+
|
162 |
+
.. plot::
|
163 |
+
:context: close-figs
|
164 |
+
:format: doctest
|
165 |
+
:include-source: True
|
166 |
+
|
167 |
+
>>> p6 = plot_implicit(y > x**2)
|
168 |
+
|
169 |
+
Plotting Using boolean conjunctions:
|
170 |
+
|
171 |
+
.. plot::
|
172 |
+
:context: close-figs
|
173 |
+
:format: doctest
|
174 |
+
:include-source: True
|
175 |
+
|
176 |
+
>>> p7 = plot_implicit(And(y > x, y > -x))
|
177 |
+
|
178 |
+
When plotting an expression with a single variable (y - 1, for example),
|
179 |
+
specify the x or the y variable explicitly:
|
180 |
+
|
181 |
+
.. plot::
|
182 |
+
:context: close-figs
|
183 |
+
:format: doctest
|
184 |
+
:include-source: True
|
185 |
+
|
186 |
+
>>> p8 = plot_implicit(y - 1, y_var=y)
|
187 |
+
>>> p9 = plot_implicit(x - 1, x_var=x)
|
188 |
+
"""
|
189 |
+
|
190 |
+
xyvar = [i for i in (x_var, y_var) if i is not None]
|
191 |
+
free_symbols = expr.free_symbols
|
192 |
+
range_symbols = Tuple(*flatten(xyvar)).free_symbols
|
193 |
+
undeclared = free_symbols - range_symbols
|
194 |
+
if len(free_symbols & range_symbols) > 2:
|
195 |
+
raise NotImplementedError("Implicit plotting is not implemented for "
|
196 |
+
"more than 2 variables")
|
197 |
+
|
198 |
+
#Create default ranges if the range is not provided.
|
199 |
+
default_range = Tuple(-5, 5)
|
200 |
+
def _range_tuple(s):
|
201 |
+
if isinstance(s, Symbol):
|
202 |
+
return Tuple(s) + default_range
|
203 |
+
if len(s) == 3:
|
204 |
+
return Tuple(*s)
|
205 |
+
raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s)
|
206 |
+
|
207 |
+
if len(xyvar) == 0:
|
208 |
+
xyvar = list(_sort_gens(free_symbols))
|
209 |
+
var_start_end_x = _range_tuple(xyvar[0])
|
210 |
+
x = var_start_end_x[0]
|
211 |
+
if len(xyvar) != 2:
|
212 |
+
if x in undeclared or not undeclared:
|
213 |
+
xyvar.append(Dummy('f(%s)' % x.name))
|
214 |
+
else:
|
215 |
+
xyvar.append(undeclared.pop())
|
216 |
+
var_start_end_y = _range_tuple(xyvar[1])
|
217 |
+
|
218 |
+
kwargs = _set_discretization_points(kwargs, ImplicitSeries)
|
219 |
+
series_argument = ImplicitSeries(
|
220 |
+
expr, var_start_end_x, var_start_end_y,
|
221 |
+
adaptive=adaptive, depth=depth,
|
222 |
+
n=n, line_color=line_color)
|
223 |
+
|
224 |
+
#set the x and y limits
|
225 |
+
kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
|
226 |
+
kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
|
227 |
+
# set the x and y labels
|
228 |
+
kwargs.setdefault('xlabel', var_start_end_x[0])
|
229 |
+
kwargs.setdefault('ylabel', var_start_end_y[0])
|
230 |
+
p = plot_factory(series_argument, **kwargs)
|
231 |
+
if show:
|
232 |
+
p.show()
|
233 |
+
return p
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/plotgrid.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from sympy.external import import_module
|
3 |
+
import sympy.plotting.backends.base_backend as base_backend
|
4 |
+
|
5 |
+
|
6 |
+
# N.B.
|
7 |
+
# When changing the minimum module version for matplotlib, please change
|
8 |
+
# the same in the `SymPyDocTestFinder`` in `sympy/testing/runtests.py`
|
9 |
+
|
10 |
+
|
11 |
+
__doctest_requires__ = {
|
12 |
+
("PlotGrid",): ["matplotlib"],
|
13 |
+
}
|
14 |
+
|
15 |
+
|
16 |
+
class PlotGrid:
|
17 |
+
"""This class helps to plot subplots from already created SymPy plots
|
18 |
+
in a single figure.
|
19 |
+
|
20 |
+
Examples
|
21 |
+
========
|
22 |
+
|
23 |
+
.. plot::
|
24 |
+
:context: close-figs
|
25 |
+
:format: doctest
|
26 |
+
:include-source: True
|
27 |
+
|
28 |
+
>>> from sympy import symbols
|
29 |
+
>>> from sympy.plotting import plot, plot3d, PlotGrid
|
30 |
+
>>> x, y = symbols('x, y')
|
31 |
+
>>> p1 = plot(x, x**2, x**3, (x, -5, 5))
|
32 |
+
>>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
|
33 |
+
>>> p3 = plot(x**3, (x, -5, 5))
|
34 |
+
>>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))
|
35 |
+
|
36 |
+
Plotting vertically in a single line:
|
37 |
+
|
38 |
+
.. plot::
|
39 |
+
:context: close-figs
|
40 |
+
:format: doctest
|
41 |
+
:include-source: True
|
42 |
+
|
43 |
+
>>> PlotGrid(2, 1, p1, p2)
|
44 |
+
PlotGrid object containing:
|
45 |
+
Plot[0]:Plot object containing:
|
46 |
+
[0]: cartesian line: x for x over (-5.0, 5.0)
|
47 |
+
[1]: cartesian line: x**2 for x over (-5.0, 5.0)
|
48 |
+
[2]: cartesian line: x**3 for x over (-5.0, 5.0)
|
49 |
+
Plot[1]:Plot object containing:
|
50 |
+
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
|
51 |
+
[1]: cartesian line: x for x over (-5.0, 5.0)
|
52 |
+
|
53 |
+
Plotting horizontally in a single line:
|
54 |
+
|
55 |
+
.. plot::
|
56 |
+
:context: close-figs
|
57 |
+
:format: doctest
|
58 |
+
:include-source: True
|
59 |
+
|
60 |
+
>>> PlotGrid(1, 3, p2, p3, p4)
|
61 |
+
PlotGrid object containing:
|
62 |
+
Plot[0]:Plot object containing:
|
63 |
+
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
|
64 |
+
[1]: cartesian line: x for x over (-5.0, 5.0)
|
65 |
+
Plot[1]:Plot object containing:
|
66 |
+
[0]: cartesian line: x**3 for x over (-5.0, 5.0)
|
67 |
+
Plot[2]:Plot object containing:
|
68 |
+
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
|
69 |
+
|
70 |
+
Plotting in a grid form:
|
71 |
+
|
72 |
+
.. plot::
|
73 |
+
:context: close-figs
|
74 |
+
:format: doctest
|
75 |
+
:include-source: True
|
76 |
+
|
77 |
+
>>> PlotGrid(2, 2, p1, p2, p3, p4)
|
78 |
+
PlotGrid object containing:
|
79 |
+
Plot[0]:Plot object containing:
|
80 |
+
[0]: cartesian line: x for x over (-5.0, 5.0)
|
81 |
+
[1]: cartesian line: x**2 for x over (-5.0, 5.0)
|
82 |
+
[2]: cartesian line: x**3 for x over (-5.0, 5.0)
|
83 |
+
Plot[1]:Plot object containing:
|
84 |
+
[0]: cartesian line: x**2 for x over (-6.0, 6.0)
|
85 |
+
[1]: cartesian line: x for x over (-5.0, 5.0)
|
86 |
+
Plot[2]:Plot object containing:
|
87 |
+
[0]: cartesian line: x**3 for x over (-5.0, 5.0)
|
88 |
+
Plot[3]:Plot object containing:
|
89 |
+
[0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
|
90 |
+
|
91 |
+
"""
|
92 |
+
def __init__(self, nrows, ncolumns, *args, show=True, size=None, **kwargs):
|
93 |
+
"""
|
94 |
+
Parameters
|
95 |
+
==========
|
96 |
+
|
97 |
+
nrows :
|
98 |
+
The number of rows that should be in the grid of the
|
99 |
+
required subplot.
|
100 |
+
ncolumns :
|
101 |
+
The number of columns that should be in the grid
|
102 |
+
of the required subplot.
|
103 |
+
|
104 |
+
nrows and ncolumns together define the required grid.
|
105 |
+
|
106 |
+
Arguments
|
107 |
+
=========
|
108 |
+
|
109 |
+
A list of predefined plot objects entered in a row-wise sequence
|
110 |
+
i.e. plot objects which are to be in the top row of the required
|
111 |
+
grid are written first, then the second row objects and so on
|
112 |
+
|
113 |
+
Keyword arguments
|
114 |
+
=================
|
115 |
+
|
116 |
+
show : Boolean
|
117 |
+
The default value is set to ``True``. Set show to ``False`` and
|
118 |
+
the function will not display the subplot. The returned instance
|
119 |
+
of the ``PlotGrid`` class can then be used to save or display the
|
120 |
+
plot by calling the ``save()`` and ``show()`` methods
|
121 |
+
respectively.
|
122 |
+
size : (float, float), optional
|
123 |
+
A tuple in the form (width, height) in inches to specify the size of
|
124 |
+
the overall figure. The default value is set to ``None``, meaning
|
125 |
+
the size will be set by the default backend.
|
126 |
+
"""
|
127 |
+
self.matplotlib = import_module('matplotlib',
|
128 |
+
import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']},
|
129 |
+
min_module_version='1.1.0', catch=(RuntimeError,))
|
130 |
+
self.nrows = nrows
|
131 |
+
self.ncolumns = ncolumns
|
132 |
+
self._series = []
|
133 |
+
self._fig = None
|
134 |
+
self.args = args
|
135 |
+
for arg in args:
|
136 |
+
self._series.append(arg._series)
|
137 |
+
self.size = size
|
138 |
+
if show and self.matplotlib:
|
139 |
+
self.show()
|
140 |
+
|
141 |
+
def _create_figure(self):
|
142 |
+
gs = self.matplotlib.gridspec.GridSpec(self.nrows, self.ncolumns)
|
143 |
+
mapping = {}
|
144 |
+
c = 0
|
145 |
+
for i in range(self.nrows):
|
146 |
+
for j in range(self.ncolumns):
|
147 |
+
if c < len(self.args):
|
148 |
+
mapping[gs[i, j]] = self.args[c]
|
149 |
+
c += 1
|
150 |
+
|
151 |
+
kw = {} if not self.size else {"figsize": self.size}
|
152 |
+
self._fig = self.matplotlib.pyplot.figure(**kw)
|
153 |
+
for spec, p in mapping.items():
|
154 |
+
kw = ({"projection": "3d"} if (len(p._series) > 0 and
|
155 |
+
p._series[0].is_3D) else {})
|
156 |
+
cur_ax = self._fig.add_subplot(spec, **kw)
|
157 |
+
p._plotgrid_fig = self._fig
|
158 |
+
p._plotgrid_ax = cur_ax
|
159 |
+
p.process_series()
|
160 |
+
|
161 |
+
@property
|
162 |
+
def fig(self):
|
163 |
+
if not self._fig:
|
164 |
+
self._create_figure()
|
165 |
+
return self._fig
|
166 |
+
|
167 |
+
@property
|
168 |
+
def _backend(self):
|
169 |
+
return self
|
170 |
+
|
171 |
+
def close(self):
|
172 |
+
self.matplotlib.pyplot.close(self.fig)
|
173 |
+
|
174 |
+
def show(self):
|
175 |
+
if base_backend._show:
|
176 |
+
self.fig.tight_layout()
|
177 |
+
self.matplotlib.pyplot.show()
|
178 |
+
else:
|
179 |
+
self.close()
|
180 |
+
|
181 |
+
def save(self, path):
|
182 |
+
self.fig.savefig(path)
|
183 |
+
|
184 |
+
def __str__(self):
|
185 |
+
plot_strs = [('Plot[%d]:' % i) + str(plot)
|
186 |
+
for i, plot in enumerate(self.args)]
|
187 |
+
|
188 |
+
return 'PlotGrid object containing:\n' + '\n'.join(plot_strs)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__init__.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Plotting module that can plot 2D and 3D functions
|
2 |
+
"""
|
3 |
+
|
4 |
+
from sympy.utilities.decorator import doctest_depends_on
|
5 |
+
|
6 |
+
@doctest_depends_on(modules=('pyglet',))
|
7 |
+
def PygletPlot(*args, **kwargs):
|
8 |
+
"""
|
9 |
+
|
10 |
+
Plot Examples
|
11 |
+
=============
|
12 |
+
|
13 |
+
See examples/advanced/pyglet_plotting.py for many more examples.
|
14 |
+
|
15 |
+
>>> from sympy.plotting.pygletplot import PygletPlot as Plot
|
16 |
+
>>> from sympy.abc import x, y, z
|
17 |
+
|
18 |
+
>>> Plot(x*y**3-y*x**3)
|
19 |
+
[0]: -x**3*y + x*y**3, 'mode=cartesian'
|
20 |
+
|
21 |
+
>>> p = Plot()
|
22 |
+
>>> p[1] = x*y
|
23 |
+
>>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
|
24 |
+
|
25 |
+
>>> p = Plot()
|
26 |
+
>>> p[1] = x**2+y**2
|
27 |
+
>>> p[2] = -x**2-y**2
|
28 |
+
|
29 |
+
|
30 |
+
Variable Intervals
|
31 |
+
==================
|
32 |
+
|
33 |
+
The basic format is [var, min, max, steps], but the
|
34 |
+
syntax is flexible and arguments left out are taken
|
35 |
+
from the defaults for the current coordinate mode:
|
36 |
+
|
37 |
+
>>> Plot(x**2) # implies [x,-5,5,100]
|
38 |
+
[0]: x**2, 'mode=cartesian'
|
39 |
+
|
40 |
+
>>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40]
|
41 |
+
[0]: x**2, 'mode=cartesian'
|
42 |
+
>>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100]
|
43 |
+
[0]: x**2 - y**2, 'mode=cartesian'
|
44 |
+
>>> Plot(x**2, [x,-13,13,100])
|
45 |
+
[0]: x**2, 'mode=cartesian'
|
46 |
+
>>> Plot(x**2, [-13,13]) # [x,-13,13,100]
|
47 |
+
[0]: x**2, 'mode=cartesian'
|
48 |
+
>>> Plot(x**2, [x,-13,13]) # [x,-13,13,100]
|
49 |
+
[0]: x**2, 'mode=cartesian'
|
50 |
+
>>> Plot(1*x, [], [x], mode='cylindrical')
|
51 |
+
... # [unbound_theta,0,2*Pi,40], [x,-1,1,20]
|
52 |
+
[0]: x, 'mode=cartesian'
|
53 |
+
|
54 |
+
|
55 |
+
Coordinate Modes
|
56 |
+
================
|
57 |
+
|
58 |
+
Plot supports several curvilinear coordinate modes, and
|
59 |
+
they independent for each plotted function. You can specify
|
60 |
+
a coordinate mode explicitly with the 'mode' named argument,
|
61 |
+
but it can be automatically determined for Cartesian or
|
62 |
+
parametric plots, and therefore must only be specified for
|
63 |
+
polar, cylindrical, and spherical modes.
|
64 |
+
|
65 |
+
Specifically, Plot(function arguments) and Plot[n] =
|
66 |
+
(function arguments) will interpret your arguments as a
|
67 |
+
Cartesian plot if you provide one function and a parametric
|
68 |
+
plot if you provide two or three functions. Similarly, the
|
69 |
+
arguments will be interpreted as a curve if one variable is
|
70 |
+
used, and a surface if two are used.
|
71 |
+
|
72 |
+
Supported mode names by number of variables:
|
73 |
+
|
74 |
+
1: parametric, cartesian, polar
|
75 |
+
2: parametric, cartesian, cylindrical = polar, spherical
|
76 |
+
|
77 |
+
>>> Plot(1, mode='spherical')
|
78 |
+
|
79 |
+
|
80 |
+
Calculator-like Interface
|
81 |
+
=========================
|
82 |
+
|
83 |
+
>>> p = Plot(visible=False)
|
84 |
+
>>> f = x**2
|
85 |
+
>>> p[1] = f
|
86 |
+
>>> p[2] = f.diff(x)
|
87 |
+
>>> p[3] = f.diff(x).diff(x)
|
88 |
+
>>> p
|
89 |
+
[1]: x**2, 'mode=cartesian'
|
90 |
+
[2]: 2*x, 'mode=cartesian'
|
91 |
+
[3]: 2, 'mode=cartesian'
|
92 |
+
>>> p.show()
|
93 |
+
>>> p.clear()
|
94 |
+
>>> p
|
95 |
+
<blank plot>
|
96 |
+
>>> p[1] = x**2+y**2
|
97 |
+
>>> p[1].style = 'solid'
|
98 |
+
>>> p[2] = -x**2-y**2
|
99 |
+
>>> p[2].style = 'wireframe'
|
100 |
+
>>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
|
101 |
+
>>> p[1].style = 'both'
|
102 |
+
>>> p[2].style = 'both'
|
103 |
+
>>> p.close()
|
104 |
+
|
105 |
+
|
106 |
+
Plot Window Keyboard Controls
|
107 |
+
=============================
|
108 |
+
|
109 |
+
Screen Rotation:
|
110 |
+
X,Y axis Arrow Keys, A,S,D,W, Numpad 4,6,8,2
|
111 |
+
Z axis Q,E, Numpad 7,9
|
112 |
+
|
113 |
+
Model Rotation:
|
114 |
+
Z axis Z,C, Numpad 1,3
|
115 |
+
|
116 |
+
Zoom: R,F, PgUp,PgDn, Numpad +,-
|
117 |
+
|
118 |
+
Reset Camera: X, Numpad 5
|
119 |
+
|
120 |
+
Camera Presets:
|
121 |
+
XY F1
|
122 |
+
XZ F2
|
123 |
+
YZ F3
|
124 |
+
Perspective F4
|
125 |
+
|
126 |
+
Sensitivity Modifier: SHIFT
|
127 |
+
|
128 |
+
Axes Toggle:
|
129 |
+
Visible F5
|
130 |
+
Colors F6
|
131 |
+
|
132 |
+
Close Window: ESCAPE
|
133 |
+
|
134 |
+
=============================
|
135 |
+
"""
|
136 |
+
|
137 |
+
from sympy.plotting.pygletplot.plot import PygletPlot
|
138 |
+
return PygletPlot(*args, **kwargs)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (3.99 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/color_scheme.cpython-310.pyc
ADDED
Binary file (9.98 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/managed_window.cpython-310.pyc
ADDED
Binary file (3.3 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot.cpython-310.pyc
ADDED
Binary file (13.7 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_axes.cpython-310.pyc
ADDED
Binary file (8.51 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-310.pyc
ADDED
Binary file (4.25 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_controller.cpython-310.pyc
ADDED
Binary file (5.01 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_curve.cpython-310.pyc
ADDED
Binary file (2.92 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-310.pyc
ADDED
Binary file (5.84 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-310.pyc
ADDED
Binary file (9.36 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-310.pyc
ADDED
Binary file (10.1 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_modes.cpython-310.pyc
ADDED
Binary file (7.33 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_object.cpython-310.pyc
ADDED
Binary file (795 Bytes). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_rotation.cpython-310.pyc
ADDED
Binary file (2.01 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_surface.cpython-310.pyc
ADDED
Binary file (3.32 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_window.cpython-310.pyc
ADDED
Binary file (3.88 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/color_scheme.py
ADDED
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.basic import Basic
|
2 |
+
from sympy.core.symbol import (Symbol, symbols)
|
3 |
+
from sympy.utilities.lambdify import lambdify
|
4 |
+
from .util import interpolate, rinterpolate, create_bounds, update_bounds
|
5 |
+
from sympy.utilities.iterables import sift
|
6 |
+
|
7 |
+
|
8 |
+
class ColorGradient:
|
9 |
+
colors = [0.4, 0.4, 0.4], [0.9, 0.9, 0.9]
|
10 |
+
intervals = 0.0, 1.0
|
11 |
+
|
12 |
+
def __init__(self, *args):
|
13 |
+
if len(args) == 2:
|
14 |
+
self.colors = list(args)
|
15 |
+
self.intervals = [0.0, 1.0]
|
16 |
+
elif len(args) > 0:
|
17 |
+
if len(args) % 2 != 0:
|
18 |
+
raise ValueError("len(args) should be even")
|
19 |
+
self.colors = [args[i] for i in range(1, len(args), 2)]
|
20 |
+
self.intervals = [args[i] for i in range(0, len(args), 2)]
|
21 |
+
assert len(self.colors) == len(self.intervals)
|
22 |
+
|
23 |
+
def copy(self):
|
24 |
+
c = ColorGradient()
|
25 |
+
c.colors = [e[::] for e in self.colors]
|
26 |
+
c.intervals = self.intervals[::]
|
27 |
+
return c
|
28 |
+
|
29 |
+
def _find_interval(self, v):
|
30 |
+
m = len(self.intervals)
|
31 |
+
i = 0
|
32 |
+
while i < m - 1 and self.intervals[i] <= v:
|
33 |
+
i += 1
|
34 |
+
return i
|
35 |
+
|
36 |
+
def _interpolate_axis(self, axis, v):
|
37 |
+
i = self._find_interval(v)
|
38 |
+
v = rinterpolate(self.intervals[i - 1], self.intervals[i], v)
|
39 |
+
return interpolate(self.colors[i - 1][axis], self.colors[i][axis], v)
|
40 |
+
|
41 |
+
def __call__(self, r, g, b):
|
42 |
+
c = self._interpolate_axis
|
43 |
+
return c(0, r), c(1, g), c(2, b)
|
44 |
+
|
45 |
+
default_color_schemes = {} # defined at the bottom of this file
|
46 |
+
|
47 |
+
|
48 |
+
class ColorScheme:
|
49 |
+
|
50 |
+
def __init__(self, *args, **kwargs):
|
51 |
+
self.args = args
|
52 |
+
self.f, self.gradient = None, ColorGradient()
|
53 |
+
|
54 |
+
if len(args) == 1 and not isinstance(args[0], Basic) and callable(args[0]):
|
55 |
+
self.f = args[0]
|
56 |
+
elif len(args) == 1 and isinstance(args[0], str):
|
57 |
+
if args[0] in default_color_schemes:
|
58 |
+
cs = default_color_schemes[args[0]]
|
59 |
+
self.f, self.gradient = cs.f, cs.gradient.copy()
|
60 |
+
else:
|
61 |
+
self.f = lambdify('x,y,z,u,v', args[0])
|
62 |
+
else:
|
63 |
+
self.f, self.gradient = self._interpret_args(args)
|
64 |
+
self._test_color_function()
|
65 |
+
if not isinstance(self.gradient, ColorGradient):
|
66 |
+
raise ValueError("Color gradient not properly initialized. "
|
67 |
+
"(Not a ColorGradient instance.)")
|
68 |
+
|
69 |
+
def _interpret_args(self, args):
|
70 |
+
f, gradient = None, self.gradient
|
71 |
+
atoms, lists = self._sort_args(args)
|
72 |
+
s = self._pop_symbol_list(lists)
|
73 |
+
s = self._fill_in_vars(s)
|
74 |
+
|
75 |
+
# prepare the error message for lambdification failure
|
76 |
+
f_str = ', '.join(str(fa) for fa in atoms)
|
77 |
+
s_str = (str(sa) for sa in s)
|
78 |
+
s_str = ', '.join(sa for sa in s_str if sa.find('unbound') < 0)
|
79 |
+
f_error = ValueError("Could not interpret arguments "
|
80 |
+
"%s as functions of %s." % (f_str, s_str))
|
81 |
+
|
82 |
+
# try to lambdify args
|
83 |
+
if len(atoms) == 1:
|
84 |
+
fv = atoms[0]
|
85 |
+
try:
|
86 |
+
f = lambdify(s, [fv, fv, fv])
|
87 |
+
except TypeError:
|
88 |
+
raise f_error
|
89 |
+
|
90 |
+
elif len(atoms) == 3:
|
91 |
+
fr, fg, fb = atoms
|
92 |
+
try:
|
93 |
+
f = lambdify(s, [fr, fg, fb])
|
94 |
+
except TypeError:
|
95 |
+
raise f_error
|
96 |
+
|
97 |
+
else:
|
98 |
+
raise ValueError("A ColorScheme must provide 1 or 3 "
|
99 |
+
"functions in x, y, z, u, and/or v.")
|
100 |
+
|
101 |
+
# try to intrepret any given color information
|
102 |
+
if len(lists) == 0:
|
103 |
+
gargs = []
|
104 |
+
|
105 |
+
elif len(lists) == 1:
|
106 |
+
gargs = lists[0]
|
107 |
+
|
108 |
+
elif len(lists) == 2:
|
109 |
+
try:
|
110 |
+
(r1, g1, b1), (r2, g2, b2) = lists
|
111 |
+
except TypeError:
|
112 |
+
raise ValueError("If two color arguments are given, "
|
113 |
+
"they must be given in the format "
|
114 |
+
"(r1, g1, b1), (r2, g2, b2).")
|
115 |
+
gargs = lists
|
116 |
+
|
117 |
+
elif len(lists) == 3:
|
118 |
+
try:
|
119 |
+
(r1, r2), (g1, g2), (b1, b2) = lists
|
120 |
+
except Exception:
|
121 |
+
raise ValueError("If three color arguments are given, "
|
122 |
+
"they must be given in the format "
|
123 |
+
"(r1, r2), (g1, g2), (b1, b2). To create "
|
124 |
+
"a multi-step gradient, use the syntax "
|
125 |
+
"[0, colorStart, step1, color1, ..., 1, "
|
126 |
+
"colorEnd].")
|
127 |
+
gargs = [[r1, g1, b1], [r2, g2, b2]]
|
128 |
+
|
129 |
+
else:
|
130 |
+
raise ValueError("Don't know what to do with collection "
|
131 |
+
"arguments %s." % (', '.join(str(l) for l in lists)))
|
132 |
+
|
133 |
+
if gargs:
|
134 |
+
try:
|
135 |
+
gradient = ColorGradient(*gargs)
|
136 |
+
except Exception as ex:
|
137 |
+
raise ValueError(("Could not initialize a gradient "
|
138 |
+
"with arguments %s. Inner "
|
139 |
+
"exception: %s") % (gargs, str(ex)))
|
140 |
+
|
141 |
+
return f, gradient
|
142 |
+
|
143 |
+
def _pop_symbol_list(self, lists):
|
144 |
+
symbol_lists = []
|
145 |
+
for l in lists:
|
146 |
+
mark = True
|
147 |
+
for s in l:
|
148 |
+
if s is not None and not isinstance(s, Symbol):
|
149 |
+
mark = False
|
150 |
+
break
|
151 |
+
if mark:
|
152 |
+
lists.remove(l)
|
153 |
+
symbol_lists.append(l)
|
154 |
+
if len(symbol_lists) == 1:
|
155 |
+
return symbol_lists[0]
|
156 |
+
elif len(symbol_lists) == 0:
|
157 |
+
return []
|
158 |
+
else:
|
159 |
+
raise ValueError("Only one list of Symbols "
|
160 |
+
"can be given for a color scheme.")
|
161 |
+
|
162 |
+
def _fill_in_vars(self, args):
|
163 |
+
defaults = symbols('x,y,z,u,v')
|
164 |
+
v_error = ValueError("Could not find what to plot.")
|
165 |
+
if len(args) == 0:
|
166 |
+
return defaults
|
167 |
+
if not isinstance(args, (tuple, list)):
|
168 |
+
raise v_error
|
169 |
+
if len(args) == 0:
|
170 |
+
return defaults
|
171 |
+
for s in args:
|
172 |
+
if s is not None and not isinstance(s, Symbol):
|
173 |
+
raise v_error
|
174 |
+
# when vars are given explicitly, any vars
|
175 |
+
# not given are marked 'unbound' as to not
|
176 |
+
# be accidentally used in an expression
|
177 |
+
vars = [Symbol('unbound%i' % (i)) for i in range(1, 6)]
|
178 |
+
# interpret as t
|
179 |
+
if len(args) == 1:
|
180 |
+
vars[3] = args[0]
|
181 |
+
# interpret as u,v
|
182 |
+
elif len(args) == 2:
|
183 |
+
if args[0] is not None:
|
184 |
+
vars[3] = args[0]
|
185 |
+
if args[1] is not None:
|
186 |
+
vars[4] = args[1]
|
187 |
+
# interpret as x,y,z
|
188 |
+
elif len(args) >= 3:
|
189 |
+
# allow some of x,y,z to be
|
190 |
+
# left unbound if not given
|
191 |
+
if args[0] is not None:
|
192 |
+
vars[0] = args[0]
|
193 |
+
if args[1] is not None:
|
194 |
+
vars[1] = args[1]
|
195 |
+
if args[2] is not None:
|
196 |
+
vars[2] = args[2]
|
197 |
+
# interpret the rest as t
|
198 |
+
if len(args) >= 4:
|
199 |
+
vars[3] = args[3]
|
200 |
+
# ...or u,v
|
201 |
+
if len(args) >= 5:
|
202 |
+
vars[4] = args[4]
|
203 |
+
return vars
|
204 |
+
|
205 |
+
def _sort_args(self, args):
|
206 |
+
lists, atoms = sift(args,
|
207 |
+
lambda a: isinstance(a, (tuple, list)), binary=True)
|
208 |
+
return atoms, lists
|
209 |
+
|
210 |
+
def _test_color_function(self):
|
211 |
+
if not callable(self.f):
|
212 |
+
raise ValueError("Color function is not callable.")
|
213 |
+
try:
|
214 |
+
result = self.f(0, 0, 0, 0, 0)
|
215 |
+
if len(result) != 3:
|
216 |
+
raise ValueError("length should be equal to 3")
|
217 |
+
except TypeError:
|
218 |
+
raise ValueError("Color function needs to accept x,y,z,u,v, "
|
219 |
+
"as arguments even if it doesn't use all of them.")
|
220 |
+
except AssertionError:
|
221 |
+
raise ValueError("Color function needs to return 3-tuple r,g,b.")
|
222 |
+
except Exception:
|
223 |
+
pass # color function probably not valid at 0,0,0,0,0
|
224 |
+
|
225 |
+
def __call__(self, x, y, z, u, v):
|
226 |
+
try:
|
227 |
+
return self.f(x, y, z, u, v)
|
228 |
+
except Exception:
|
229 |
+
return None
|
230 |
+
|
231 |
+
def apply_to_curve(self, verts, u_set, set_len=None, inc_pos=None):
|
232 |
+
"""
|
233 |
+
Apply this color scheme to a
|
234 |
+
set of vertices over a single
|
235 |
+
independent variable u.
|
236 |
+
"""
|
237 |
+
bounds = create_bounds()
|
238 |
+
cverts = []
|
239 |
+
if callable(set_len):
|
240 |
+
set_len(len(u_set)*2)
|
241 |
+
# calculate f() = r,g,b for each vert
|
242 |
+
# and find the min and max for r,g,b
|
243 |
+
for _u in range(len(u_set)):
|
244 |
+
if verts[_u] is None:
|
245 |
+
cverts.append(None)
|
246 |
+
else:
|
247 |
+
x, y, z = verts[_u]
|
248 |
+
u, v = u_set[_u], None
|
249 |
+
c = self(x, y, z, u, v)
|
250 |
+
if c is not None:
|
251 |
+
c = list(c)
|
252 |
+
update_bounds(bounds, c)
|
253 |
+
cverts.append(c)
|
254 |
+
if callable(inc_pos):
|
255 |
+
inc_pos()
|
256 |
+
# scale and apply gradient
|
257 |
+
for _u in range(len(u_set)):
|
258 |
+
if cverts[_u] is not None:
|
259 |
+
for _c in range(3):
|
260 |
+
# scale from [f_min, f_max] to [0,1]
|
261 |
+
cverts[_u][_c] = rinterpolate(bounds[_c][0], bounds[_c][1],
|
262 |
+
cverts[_u][_c])
|
263 |
+
# apply gradient
|
264 |
+
cverts[_u] = self.gradient(*cverts[_u])
|
265 |
+
if callable(inc_pos):
|
266 |
+
inc_pos()
|
267 |
+
return cverts
|
268 |
+
|
269 |
+
def apply_to_surface(self, verts, u_set, v_set, set_len=None, inc_pos=None):
|
270 |
+
"""
|
271 |
+
Apply this color scheme to a
|
272 |
+
set of vertices over two
|
273 |
+
independent variables u and v.
|
274 |
+
"""
|
275 |
+
bounds = create_bounds()
|
276 |
+
cverts = []
|
277 |
+
if callable(set_len):
|
278 |
+
set_len(len(u_set)*len(v_set)*2)
|
279 |
+
# calculate f() = r,g,b for each vert
|
280 |
+
# and find the min and max for r,g,b
|
281 |
+
for _u in range(len(u_set)):
|
282 |
+
column = []
|
283 |
+
for _v in range(len(v_set)):
|
284 |
+
if verts[_u][_v] is None:
|
285 |
+
column.append(None)
|
286 |
+
else:
|
287 |
+
x, y, z = verts[_u][_v]
|
288 |
+
u, v = u_set[_u], v_set[_v]
|
289 |
+
c = self(x, y, z, u, v)
|
290 |
+
if c is not None:
|
291 |
+
c = list(c)
|
292 |
+
update_bounds(bounds, c)
|
293 |
+
column.append(c)
|
294 |
+
if callable(inc_pos):
|
295 |
+
inc_pos()
|
296 |
+
cverts.append(column)
|
297 |
+
# scale and apply gradient
|
298 |
+
for _u in range(len(u_set)):
|
299 |
+
for _v in range(len(v_set)):
|
300 |
+
if cverts[_u][_v] is not None:
|
301 |
+
# scale from [f_min, f_max] to [0,1]
|
302 |
+
for _c in range(3):
|
303 |
+
cverts[_u][_v][_c] = rinterpolate(bounds[_c][0],
|
304 |
+
bounds[_c][1], cverts[_u][_v][_c])
|
305 |
+
# apply gradient
|
306 |
+
cverts[_u][_v] = self.gradient(*cverts[_u][_v])
|
307 |
+
if callable(inc_pos):
|
308 |
+
inc_pos()
|
309 |
+
return cverts
|
310 |
+
|
311 |
+
def str_base(self):
|
312 |
+
return ", ".join(str(a) for a in self.args)
|
313 |
+
|
314 |
+
def __repr__(self):
|
315 |
+
return "%s" % (self.str_base())
|
316 |
+
|
317 |
+
|
318 |
+
x, y, z, t, u, v = symbols('x,y,z,t,u,v')
|
319 |
+
|
320 |
+
default_color_schemes['rainbow'] = ColorScheme(z, y, x)
|
321 |
+
default_color_schemes['zfade'] = ColorScheme(z, (0.4, 0.4, 0.97),
|
322 |
+
(0.97, 0.4, 0.4), (None, None, z))
|
323 |
+
default_color_schemes['zfade3'] = ColorScheme(z, (None, None, z),
|
324 |
+
[0.00, (0.2, 0.2, 1.0),
|
325 |
+
0.35, (0.2, 0.8, 0.4),
|
326 |
+
0.50, (0.3, 0.9, 0.3),
|
327 |
+
0.65, (0.4, 0.8, 0.2),
|
328 |
+
1.00, (1.0, 0.2, 0.2)])
|
329 |
+
|
330 |
+
default_color_schemes['zfade4'] = ColorScheme(z, (None, None, z),
|
331 |
+
[0.0, (0.3, 0.3, 1.0),
|
332 |
+
0.30, (0.3, 1.0, 0.3),
|
333 |
+
0.55, (0.95, 1.0, 0.2),
|
334 |
+
0.65, (1.0, 0.95, 0.2),
|
335 |
+
0.85, (1.0, 0.7, 0.2),
|
336 |
+
1.0, (1.0, 0.3, 0.2)])
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/managed_window.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pyglet.window import Window
|
2 |
+
from pyglet.clock import Clock
|
3 |
+
|
4 |
+
from threading import Thread, Lock
|
5 |
+
|
6 |
+
gl_lock = Lock()
|
7 |
+
|
8 |
+
|
9 |
+
class ManagedWindow(Window):
|
10 |
+
"""
|
11 |
+
A pyglet window with an event loop which executes automatically
|
12 |
+
in a separate thread. Behavior is added by creating a subclass
|
13 |
+
which overrides setup, update, and/or draw.
|
14 |
+
"""
|
15 |
+
fps_limit = 30
|
16 |
+
default_win_args = {"width": 600,
|
17 |
+
"height": 500,
|
18 |
+
"vsync": False,
|
19 |
+
"resizable": True}
|
20 |
+
|
21 |
+
def __init__(self, **win_args):
|
22 |
+
"""
|
23 |
+
It is best not to override this function in the child
|
24 |
+
class, unless you need to take additional arguments.
|
25 |
+
Do any OpenGL initialization calls in setup().
|
26 |
+
"""
|
27 |
+
|
28 |
+
# check if this is run from the doctester
|
29 |
+
if win_args.get('runfromdoctester', False):
|
30 |
+
return
|
31 |
+
|
32 |
+
self.win_args = dict(self.default_win_args, **win_args)
|
33 |
+
self.Thread = Thread(target=self.__event_loop__)
|
34 |
+
self.Thread.start()
|
35 |
+
|
36 |
+
def __event_loop__(self, **win_args):
|
37 |
+
"""
|
38 |
+
The event loop thread function. Do not override or call
|
39 |
+
directly (it is called by __init__).
|
40 |
+
"""
|
41 |
+
gl_lock.acquire()
|
42 |
+
try:
|
43 |
+
try:
|
44 |
+
super().__init__(**self.win_args)
|
45 |
+
self.switch_to()
|
46 |
+
self.setup()
|
47 |
+
except Exception as e:
|
48 |
+
print("Window initialization failed: %s" % (str(e)))
|
49 |
+
self.has_exit = True
|
50 |
+
finally:
|
51 |
+
gl_lock.release()
|
52 |
+
|
53 |
+
clock = Clock()
|
54 |
+
clock.fps_limit = self.fps_limit
|
55 |
+
while not self.has_exit:
|
56 |
+
dt = clock.tick()
|
57 |
+
gl_lock.acquire()
|
58 |
+
try:
|
59 |
+
try:
|
60 |
+
self.switch_to()
|
61 |
+
self.dispatch_events()
|
62 |
+
self.clear()
|
63 |
+
self.update(dt)
|
64 |
+
self.draw()
|
65 |
+
self.flip()
|
66 |
+
except Exception as e:
|
67 |
+
print("Uncaught exception in event loop: %s" % str(e))
|
68 |
+
self.has_exit = True
|
69 |
+
finally:
|
70 |
+
gl_lock.release()
|
71 |
+
super().close()
|
72 |
+
|
73 |
+
def close(self):
|
74 |
+
"""
|
75 |
+
Closes the window.
|
76 |
+
"""
|
77 |
+
self.has_exit = True
|
78 |
+
|
79 |
+
def setup(self):
|
80 |
+
"""
|
81 |
+
Called once before the event loop begins.
|
82 |
+
Override this method in a child class. This
|
83 |
+
is the best place to put things like OpenGL
|
84 |
+
initialization calls.
|
85 |
+
"""
|
86 |
+
pass
|
87 |
+
|
88 |
+
def update(self, dt):
|
89 |
+
"""
|
90 |
+
Called before draw during each iteration of
|
91 |
+
the event loop. dt is the elapsed time in
|
92 |
+
seconds since the last update. OpenGL rendering
|
93 |
+
calls are best put in draw() rather than here.
|
94 |
+
"""
|
95 |
+
pass
|
96 |
+
|
97 |
+
def draw(self):
|
98 |
+
"""
|
99 |
+
Called after update during each iteration of
|
100 |
+
the event loop. Put OpenGL rendering calls
|
101 |
+
here.
|
102 |
+
"""
|
103 |
+
pass
|
104 |
+
|
105 |
+
if __name__ == '__main__':
|
106 |
+
ManagedWindow()
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot.py
ADDED
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from threading import RLock
|
2 |
+
|
3 |
+
# it is sufficient to import "pyglet" here once
|
4 |
+
try:
|
5 |
+
import pyglet.gl as pgl
|
6 |
+
except ImportError:
|
7 |
+
raise ImportError("pyglet is required for plotting.\n "
|
8 |
+
"visit https://pyglet.org/")
|
9 |
+
|
10 |
+
from sympy.core.numbers import Integer
|
11 |
+
from sympy.external.gmpy import SYMPY_INTS
|
12 |
+
from sympy.geometry.entity import GeometryEntity
|
13 |
+
from sympy.plotting.pygletplot.plot_axes import PlotAxes
|
14 |
+
from sympy.plotting.pygletplot.plot_mode import PlotMode
|
15 |
+
from sympy.plotting.pygletplot.plot_object import PlotObject
|
16 |
+
from sympy.plotting.pygletplot.plot_window import PlotWindow
|
17 |
+
from sympy.plotting.pygletplot.util import parse_option_string
|
18 |
+
from sympy.utilities.decorator import doctest_depends_on
|
19 |
+
from sympy.utilities.iterables import is_sequence
|
20 |
+
|
21 |
+
from time import sleep
|
22 |
+
from os import getcwd, listdir
|
23 |
+
|
24 |
+
import ctypes
|
25 |
+
|
26 |
+
@doctest_depends_on(modules=('pyglet',))
|
27 |
+
class PygletPlot:
|
28 |
+
"""
|
29 |
+
Plot Examples
|
30 |
+
=============
|
31 |
+
|
32 |
+
See examples/advanced/pyglet_plotting.py for many more examples.
|
33 |
+
|
34 |
+
>>> from sympy.plotting.pygletplot import PygletPlot as Plot
|
35 |
+
>>> from sympy.abc import x, y, z
|
36 |
+
|
37 |
+
>>> Plot(x*y**3-y*x**3)
|
38 |
+
[0]: -x**3*y + x*y**3, 'mode=cartesian'
|
39 |
+
|
40 |
+
>>> p = Plot()
|
41 |
+
>>> p[1] = x*y
|
42 |
+
>>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
|
43 |
+
|
44 |
+
>>> p = Plot()
|
45 |
+
>>> p[1] = x**2+y**2
|
46 |
+
>>> p[2] = -x**2-y**2
|
47 |
+
|
48 |
+
|
49 |
+
Variable Intervals
|
50 |
+
==================
|
51 |
+
|
52 |
+
The basic format is [var, min, max, steps], but the
|
53 |
+
syntax is flexible and arguments left out are taken
|
54 |
+
from the defaults for the current coordinate mode:
|
55 |
+
|
56 |
+
>>> Plot(x**2) # implies [x,-5,5,100]
|
57 |
+
[0]: x**2, 'mode=cartesian'
|
58 |
+
>>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40]
|
59 |
+
[0]: x**2, 'mode=cartesian'
|
60 |
+
>>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100]
|
61 |
+
[0]: x**2 - y**2, 'mode=cartesian'
|
62 |
+
>>> Plot(x**2, [x,-13,13,100])
|
63 |
+
[0]: x**2, 'mode=cartesian'
|
64 |
+
>>> Plot(x**2, [-13,13]) # [x,-13,13,100]
|
65 |
+
[0]: x**2, 'mode=cartesian'
|
66 |
+
>>> Plot(x**2, [x,-13,13]) # [x,-13,13,10]
|
67 |
+
[0]: x**2, 'mode=cartesian'
|
68 |
+
>>> Plot(1*x, [], [x], mode='cylindrical')
|
69 |
+
... # [unbound_theta,0,2*Pi,40], [x,-1,1,20]
|
70 |
+
[0]: x, 'mode=cartesian'
|
71 |
+
|
72 |
+
|
73 |
+
Coordinate Modes
|
74 |
+
================
|
75 |
+
|
76 |
+
Plot supports several curvilinear coordinate modes, and
|
77 |
+
they independent for each plotted function. You can specify
|
78 |
+
a coordinate mode explicitly with the 'mode' named argument,
|
79 |
+
but it can be automatically determined for Cartesian or
|
80 |
+
parametric plots, and therefore must only be specified for
|
81 |
+
polar, cylindrical, and spherical modes.
|
82 |
+
|
83 |
+
Specifically, Plot(function arguments) and Plot[n] =
|
84 |
+
(function arguments) will interpret your arguments as a
|
85 |
+
Cartesian plot if you provide one function and a parametric
|
86 |
+
plot if you provide two or three functions. Similarly, the
|
87 |
+
arguments will be interpreted as a curve if one variable is
|
88 |
+
used, and a surface if two are used.
|
89 |
+
|
90 |
+
Supported mode names by number of variables:
|
91 |
+
|
92 |
+
1: parametric, cartesian, polar
|
93 |
+
2: parametric, cartesian, cylindrical = polar, spherical
|
94 |
+
|
95 |
+
>>> Plot(1, mode='spherical')
|
96 |
+
|
97 |
+
|
98 |
+
Calculator-like Interface
|
99 |
+
=========================
|
100 |
+
|
101 |
+
>>> p = Plot(visible=False)
|
102 |
+
>>> f = x**2
|
103 |
+
>>> p[1] = f
|
104 |
+
>>> p[2] = f.diff(x)
|
105 |
+
>>> p[3] = f.diff(x).diff(x)
|
106 |
+
>>> p
|
107 |
+
[1]: x**2, 'mode=cartesian'
|
108 |
+
[2]: 2*x, 'mode=cartesian'
|
109 |
+
[3]: 2, 'mode=cartesian'
|
110 |
+
>>> p.show()
|
111 |
+
>>> p.clear()
|
112 |
+
>>> p
|
113 |
+
<blank plot>
|
114 |
+
>>> p[1] = x**2+y**2
|
115 |
+
>>> p[1].style = 'solid'
|
116 |
+
>>> p[2] = -x**2-y**2
|
117 |
+
>>> p[2].style = 'wireframe'
|
118 |
+
>>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
|
119 |
+
>>> p[1].style = 'both'
|
120 |
+
>>> p[2].style = 'both'
|
121 |
+
>>> p.close()
|
122 |
+
|
123 |
+
|
124 |
+
Plot Window Keyboard Controls
|
125 |
+
=============================
|
126 |
+
|
127 |
+
Screen Rotation:
|
128 |
+
X,Y axis Arrow Keys, A,S,D,W, Numpad 4,6,8,2
|
129 |
+
Z axis Q,E, Numpad 7,9
|
130 |
+
|
131 |
+
Model Rotation:
|
132 |
+
Z axis Z,C, Numpad 1,3
|
133 |
+
|
134 |
+
Zoom: R,F, PgUp,PgDn, Numpad +,-
|
135 |
+
|
136 |
+
Reset Camera: X, Numpad 5
|
137 |
+
|
138 |
+
Camera Presets:
|
139 |
+
XY F1
|
140 |
+
XZ F2
|
141 |
+
YZ F3
|
142 |
+
Perspective F4
|
143 |
+
|
144 |
+
Sensitivity Modifier: SHIFT
|
145 |
+
|
146 |
+
Axes Toggle:
|
147 |
+
Visible F5
|
148 |
+
Colors F6
|
149 |
+
|
150 |
+
Close Window: ESCAPE
|
151 |
+
|
152 |
+
=============================
|
153 |
+
|
154 |
+
"""
|
155 |
+
|
156 |
+
@doctest_depends_on(modules=('pyglet',))
|
157 |
+
def __init__(self, *fargs, **win_args):
|
158 |
+
"""
|
159 |
+
Positional Arguments
|
160 |
+
====================
|
161 |
+
|
162 |
+
Any given positional arguments are used to
|
163 |
+
initialize a plot function at index 1. In
|
164 |
+
other words...
|
165 |
+
|
166 |
+
>>> from sympy.plotting.pygletplot import PygletPlot as Plot
|
167 |
+
>>> from sympy.abc import x
|
168 |
+
>>> p = Plot(x**2, visible=False)
|
169 |
+
|
170 |
+
...is equivalent to...
|
171 |
+
|
172 |
+
>>> p = Plot(visible=False)
|
173 |
+
>>> p[1] = x**2
|
174 |
+
|
175 |
+
Note that in earlier versions of the plotting
|
176 |
+
module, you were able to specify multiple
|
177 |
+
functions in the initializer. This functionality
|
178 |
+
has been dropped in favor of better automatic
|
179 |
+
plot plot_mode detection.
|
180 |
+
|
181 |
+
|
182 |
+
Named Arguments
|
183 |
+
===============
|
184 |
+
|
185 |
+
axes
|
186 |
+
An option string of the form
|
187 |
+
"key1=value1; key2 = value2" which
|
188 |
+
can use the following options:
|
189 |
+
|
190 |
+
style = ordinate
|
191 |
+
none OR frame OR box OR ordinate
|
192 |
+
|
193 |
+
stride = 0.25
|
194 |
+
val OR (val_x, val_y, val_z)
|
195 |
+
|
196 |
+
overlay = True (draw on top of plot)
|
197 |
+
True OR False
|
198 |
+
|
199 |
+
colored = False (False uses Black,
|
200 |
+
True uses colors
|
201 |
+
R,G,B = X,Y,Z)
|
202 |
+
True OR False
|
203 |
+
|
204 |
+
label_axes = False (display axis names
|
205 |
+
at endpoints)
|
206 |
+
True OR False
|
207 |
+
|
208 |
+
visible = True (show immediately
|
209 |
+
True OR False
|
210 |
+
|
211 |
+
|
212 |
+
The following named arguments are passed as
|
213 |
+
arguments to window initialization:
|
214 |
+
|
215 |
+
antialiasing = True
|
216 |
+
True OR False
|
217 |
+
|
218 |
+
ortho = False
|
219 |
+
True OR False
|
220 |
+
|
221 |
+
invert_mouse_zoom = False
|
222 |
+
True OR False
|
223 |
+
|
224 |
+
"""
|
225 |
+
# Register the plot modes
|
226 |
+
from . import plot_modes # noqa
|
227 |
+
|
228 |
+
self._win_args = win_args
|
229 |
+
self._window = None
|
230 |
+
|
231 |
+
self._render_lock = RLock()
|
232 |
+
|
233 |
+
self._functions = {}
|
234 |
+
self._pobjects = []
|
235 |
+
self._screenshot = ScreenShot(self)
|
236 |
+
|
237 |
+
axe_options = parse_option_string(win_args.pop('axes', ''))
|
238 |
+
self.axes = PlotAxes(**axe_options)
|
239 |
+
self._pobjects.append(self.axes)
|
240 |
+
|
241 |
+
self[0] = fargs
|
242 |
+
if win_args.get('visible', True):
|
243 |
+
self.show()
|
244 |
+
|
245 |
+
## Window Interfaces
|
246 |
+
|
247 |
+
def show(self):
|
248 |
+
"""
|
249 |
+
Creates and displays a plot window, or activates it
|
250 |
+
(gives it focus) if it has already been created.
|
251 |
+
"""
|
252 |
+
if self._window and not self._window.has_exit:
|
253 |
+
self._window.activate()
|
254 |
+
else:
|
255 |
+
self._win_args['visible'] = True
|
256 |
+
self.axes.reset_resources()
|
257 |
+
|
258 |
+
#if hasattr(self, '_doctest_depends_on'):
|
259 |
+
# self._win_args['runfromdoctester'] = True
|
260 |
+
|
261 |
+
self._window = PlotWindow(self, **self._win_args)
|
262 |
+
|
263 |
+
def close(self):
|
264 |
+
"""
|
265 |
+
Closes the plot window.
|
266 |
+
"""
|
267 |
+
if self._window:
|
268 |
+
self._window.close()
|
269 |
+
|
270 |
+
def saveimage(self, outfile=None, format='', size=(600, 500)):
|
271 |
+
"""
|
272 |
+
Saves a screen capture of the plot window to an
|
273 |
+
image file.
|
274 |
+
|
275 |
+
If outfile is given, it can either be a path
|
276 |
+
or a file object. Otherwise a png image will
|
277 |
+
be saved to the current working directory.
|
278 |
+
If the format is omitted, it is determined from
|
279 |
+
the filename extension.
|
280 |
+
"""
|
281 |
+
self._screenshot.save(outfile, format, size)
|
282 |
+
|
283 |
+
## Function List Interfaces
|
284 |
+
|
285 |
+
def clear(self):
|
286 |
+
"""
|
287 |
+
Clears the function list of this plot.
|
288 |
+
"""
|
289 |
+
self._render_lock.acquire()
|
290 |
+
self._functions = {}
|
291 |
+
self.adjust_all_bounds()
|
292 |
+
self._render_lock.release()
|
293 |
+
|
294 |
+
def __getitem__(self, i):
|
295 |
+
"""
|
296 |
+
Returns the function at position i in the
|
297 |
+
function list.
|
298 |
+
"""
|
299 |
+
return self._functions[i]
|
300 |
+
|
301 |
+
def __setitem__(self, i, args):
|
302 |
+
"""
|
303 |
+
Parses and adds a PlotMode to the function
|
304 |
+
list.
|
305 |
+
"""
|
306 |
+
if not (isinstance(i, (SYMPY_INTS, Integer)) and i >= 0):
|
307 |
+
raise ValueError("Function index must "
|
308 |
+
"be an integer >= 0.")
|
309 |
+
|
310 |
+
if isinstance(args, PlotObject):
|
311 |
+
f = args
|
312 |
+
else:
|
313 |
+
if (not is_sequence(args)) or isinstance(args, GeometryEntity):
|
314 |
+
args = [args]
|
315 |
+
if len(args) == 0:
|
316 |
+
return # no arguments given
|
317 |
+
kwargs = {"bounds_callback": self.adjust_all_bounds}
|
318 |
+
f = PlotMode(*args, **kwargs)
|
319 |
+
|
320 |
+
if f:
|
321 |
+
self._render_lock.acquire()
|
322 |
+
self._functions[i] = f
|
323 |
+
self._render_lock.release()
|
324 |
+
else:
|
325 |
+
raise ValueError("Failed to parse '%s'."
|
326 |
+
% ', '.join(str(a) for a in args))
|
327 |
+
|
328 |
+
def __delitem__(self, i):
|
329 |
+
"""
|
330 |
+
Removes the function in the function list at
|
331 |
+
position i.
|
332 |
+
"""
|
333 |
+
self._render_lock.acquire()
|
334 |
+
del self._functions[i]
|
335 |
+
self.adjust_all_bounds()
|
336 |
+
self._render_lock.release()
|
337 |
+
|
338 |
+
def firstavailableindex(self):
|
339 |
+
"""
|
340 |
+
Returns the first unused index in the function list.
|
341 |
+
"""
|
342 |
+
i = 0
|
343 |
+
self._render_lock.acquire()
|
344 |
+
while i in self._functions:
|
345 |
+
i += 1
|
346 |
+
self._render_lock.release()
|
347 |
+
return i
|
348 |
+
|
349 |
+
def append(self, *args):
|
350 |
+
"""
|
351 |
+
Parses and adds a PlotMode to the function
|
352 |
+
list at the first available index.
|
353 |
+
"""
|
354 |
+
self.__setitem__(self.firstavailableindex(), args)
|
355 |
+
|
356 |
+
def __len__(self):
|
357 |
+
"""
|
358 |
+
Returns the number of functions in the function list.
|
359 |
+
"""
|
360 |
+
return len(self._functions)
|
361 |
+
|
362 |
+
def __iter__(self):
|
363 |
+
"""
|
364 |
+
Allows iteration of the function list.
|
365 |
+
"""
|
366 |
+
return self._functions.itervalues()
|
367 |
+
|
368 |
+
def __repr__(self):
|
369 |
+
return str(self)
|
370 |
+
|
371 |
+
def __str__(self):
|
372 |
+
"""
|
373 |
+
Returns a string containing a new-line separated
|
374 |
+
list of the functions in the function list.
|
375 |
+
"""
|
376 |
+
s = ""
|
377 |
+
if len(self._functions) == 0:
|
378 |
+
s += "<blank plot>"
|
379 |
+
else:
|
380 |
+
self._render_lock.acquire()
|
381 |
+
s += "\n".join(["%s[%i]: %s" % ("", i, str(self._functions[i]))
|
382 |
+
for i in self._functions])
|
383 |
+
self._render_lock.release()
|
384 |
+
return s
|
385 |
+
|
386 |
+
def adjust_all_bounds(self):
|
387 |
+
self._render_lock.acquire()
|
388 |
+
self.axes.reset_bounding_box()
|
389 |
+
for f in self._functions:
|
390 |
+
self.axes.adjust_bounds(self._functions[f].bounds)
|
391 |
+
self._render_lock.release()
|
392 |
+
|
393 |
+
def wait_for_calculations(self):
|
394 |
+
sleep(0)
|
395 |
+
self._render_lock.acquire()
|
396 |
+
for f in self._functions:
|
397 |
+
a = self._functions[f]._get_calculating_verts
|
398 |
+
b = self._functions[f]._get_calculating_cverts
|
399 |
+
while a() or b():
|
400 |
+
sleep(0)
|
401 |
+
self._render_lock.release()
|
402 |
+
|
403 |
+
class ScreenShot:
|
404 |
+
def __init__(self, plot):
|
405 |
+
self._plot = plot
|
406 |
+
self.screenshot_requested = False
|
407 |
+
self.outfile = None
|
408 |
+
self.format = ''
|
409 |
+
self.invisibleMode = False
|
410 |
+
self.flag = 0
|
411 |
+
|
412 |
+
def __bool__(self):
|
413 |
+
return self.screenshot_requested
|
414 |
+
|
415 |
+
def _execute_saving(self):
|
416 |
+
if self.flag < 3:
|
417 |
+
self.flag += 1
|
418 |
+
return
|
419 |
+
|
420 |
+
size_x, size_y = self._plot._window.get_size()
|
421 |
+
size = size_x*size_y*4*ctypes.sizeof(ctypes.c_ubyte)
|
422 |
+
image = ctypes.create_string_buffer(size)
|
423 |
+
pgl.glReadPixels(0, 0, size_x, size_y, pgl.GL_RGBA, pgl.GL_UNSIGNED_BYTE, image)
|
424 |
+
from PIL import Image
|
425 |
+
im = Image.frombuffer('RGBA', (size_x, size_y),
|
426 |
+
image.raw, 'raw', 'RGBA', 0, 1)
|
427 |
+
im.transpose(Image.FLIP_TOP_BOTTOM).save(self.outfile, self.format)
|
428 |
+
|
429 |
+
self.flag = 0
|
430 |
+
self.screenshot_requested = False
|
431 |
+
if self.invisibleMode:
|
432 |
+
self._plot._window.close()
|
433 |
+
|
434 |
+
def save(self, outfile=None, format='', size=(600, 500)):
|
435 |
+
self.outfile = outfile
|
436 |
+
self.format = format
|
437 |
+
self.size = size
|
438 |
+
self.screenshot_requested = True
|
439 |
+
|
440 |
+
if not self._plot._window or self._plot._window.has_exit:
|
441 |
+
self._plot._win_args['visible'] = False
|
442 |
+
|
443 |
+
self._plot._win_args['width'] = size[0]
|
444 |
+
self._plot._win_args['height'] = size[1]
|
445 |
+
|
446 |
+
self._plot.axes.reset_resources()
|
447 |
+
self._plot._window = PlotWindow(self._plot, **self._plot._win_args)
|
448 |
+
self.invisibleMode = True
|
449 |
+
|
450 |
+
if self.outfile is None:
|
451 |
+
self.outfile = self._create_unique_path()
|
452 |
+
print(self.outfile)
|
453 |
+
|
454 |
+
def _create_unique_path(self):
|
455 |
+
cwd = getcwd()
|
456 |
+
l = listdir(cwd)
|
457 |
+
path = ''
|
458 |
+
i = 0
|
459 |
+
while True:
|
460 |
+
if not 'plot_%s.png' % i in l:
|
461 |
+
path = cwd + '/plot_%s.png' % i
|
462 |
+
break
|
463 |
+
i += 1
|
464 |
+
return path
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_axes.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pyglet.gl as pgl
|
2 |
+
from pyglet import font
|
3 |
+
|
4 |
+
from sympy.core import S
|
5 |
+
from sympy.plotting.pygletplot.plot_object import PlotObject
|
6 |
+
from sympy.plotting.pygletplot.util import billboard_matrix, dot_product, \
|
7 |
+
get_direction_vectors, strided_range, vec_mag, vec_sub
|
8 |
+
from sympy.utilities.iterables import is_sequence
|
9 |
+
|
10 |
+
|
11 |
+
class PlotAxes(PlotObject):
|
12 |
+
|
13 |
+
def __init__(self, *args,
|
14 |
+
style='', none=None, frame=None, box=None, ordinate=None,
|
15 |
+
stride=0.25,
|
16 |
+
visible='', overlay='', colored='', label_axes='', label_ticks='',
|
17 |
+
tick_length=0.1,
|
18 |
+
font_face='Arial', font_size=28,
|
19 |
+
**kwargs):
|
20 |
+
# initialize style parameter
|
21 |
+
style = style.lower()
|
22 |
+
|
23 |
+
# allow alias kwargs to override style kwarg
|
24 |
+
if none is not None:
|
25 |
+
style = 'none'
|
26 |
+
if frame is not None:
|
27 |
+
style = 'frame'
|
28 |
+
if box is not None:
|
29 |
+
style = 'box'
|
30 |
+
if ordinate is not None:
|
31 |
+
style = 'ordinate'
|
32 |
+
|
33 |
+
if style in ['', 'ordinate']:
|
34 |
+
self._render_object = PlotAxesOrdinate(self)
|
35 |
+
elif style in ['frame', 'box']:
|
36 |
+
self._render_object = PlotAxesFrame(self)
|
37 |
+
elif style in ['none']:
|
38 |
+
self._render_object = None
|
39 |
+
else:
|
40 |
+
raise ValueError(("Unrecognized axes style %s.") % (style))
|
41 |
+
|
42 |
+
# initialize stride parameter
|
43 |
+
try:
|
44 |
+
stride = eval(stride)
|
45 |
+
except TypeError:
|
46 |
+
pass
|
47 |
+
if is_sequence(stride):
|
48 |
+
if len(stride) != 3:
|
49 |
+
raise ValueError("length should be equal to 3")
|
50 |
+
self._stride = stride
|
51 |
+
else:
|
52 |
+
self._stride = [stride, stride, stride]
|
53 |
+
self._tick_length = float(tick_length)
|
54 |
+
|
55 |
+
# setup bounding box and ticks
|
56 |
+
self._origin = [0, 0, 0]
|
57 |
+
self.reset_bounding_box()
|
58 |
+
|
59 |
+
def flexible_boolean(input, default):
|
60 |
+
if input in [True, False]:
|
61 |
+
return input
|
62 |
+
if input in ('f', 'F', 'false', 'False'):
|
63 |
+
return False
|
64 |
+
if input in ('t', 'T', 'true', 'True'):
|
65 |
+
return True
|
66 |
+
return default
|
67 |
+
|
68 |
+
# initialize remaining parameters
|
69 |
+
self.visible = flexible_boolean(kwargs, True)
|
70 |
+
self._overlay = flexible_boolean(overlay, True)
|
71 |
+
self._colored = flexible_boolean(colored, False)
|
72 |
+
self._label_axes = flexible_boolean(label_axes, False)
|
73 |
+
self._label_ticks = flexible_boolean(label_ticks, True)
|
74 |
+
|
75 |
+
# setup label font
|
76 |
+
self.font_face = font_face
|
77 |
+
self.font_size = font_size
|
78 |
+
|
79 |
+
# this is also used to reinit the
|
80 |
+
# font on window close/reopen
|
81 |
+
self.reset_resources()
|
82 |
+
|
83 |
+
def reset_resources(self):
|
84 |
+
self.label_font = None
|
85 |
+
|
86 |
+
def reset_bounding_box(self):
|
87 |
+
self._bounding_box = [[None, None], [None, None], [None, None]]
|
88 |
+
self._axis_ticks = [[], [], []]
|
89 |
+
|
90 |
+
def draw(self):
|
91 |
+
if self._render_object:
|
92 |
+
pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT | pgl.GL_DEPTH_BUFFER_BIT)
|
93 |
+
if self._overlay:
|
94 |
+
pgl.glDisable(pgl.GL_DEPTH_TEST)
|
95 |
+
self._render_object.draw()
|
96 |
+
pgl.glPopAttrib()
|
97 |
+
|
98 |
+
def adjust_bounds(self, child_bounds):
|
99 |
+
b = self._bounding_box
|
100 |
+
c = child_bounds
|
101 |
+
for i in range(3):
|
102 |
+
if abs(c[i][0]) is S.Infinity or abs(c[i][1]) is S.Infinity:
|
103 |
+
continue
|
104 |
+
b[i][0] = c[i][0] if b[i][0] is None else min([b[i][0], c[i][0]])
|
105 |
+
b[i][1] = c[i][1] if b[i][1] is None else max([b[i][1], c[i][1]])
|
106 |
+
self._bounding_box = b
|
107 |
+
self._recalculate_axis_ticks(i)
|
108 |
+
|
109 |
+
def _recalculate_axis_ticks(self, axis):
|
110 |
+
b = self._bounding_box
|
111 |
+
if b[axis][0] is None or b[axis][1] is None:
|
112 |
+
self._axis_ticks[axis] = []
|
113 |
+
else:
|
114 |
+
self._axis_ticks[axis] = strided_range(b[axis][0], b[axis][1],
|
115 |
+
self._stride[axis])
|
116 |
+
|
117 |
+
def toggle_visible(self):
|
118 |
+
self.visible = not self.visible
|
119 |
+
|
120 |
+
def toggle_colors(self):
|
121 |
+
self._colored = not self._colored
|
122 |
+
|
123 |
+
|
124 |
+
class PlotAxesBase(PlotObject):
|
125 |
+
|
126 |
+
def __init__(self, parent_axes):
|
127 |
+
self._p = parent_axes
|
128 |
+
|
129 |
+
def draw(self):
|
130 |
+
color = [([0.2, 0.1, 0.3], [0.2, 0.1, 0.3], [0.2, 0.1, 0.3]),
|
131 |
+
([0.9, 0.3, 0.5], [0.5, 1.0, 0.5], [0.3, 0.3, 0.9])][self._p._colored]
|
132 |
+
self.draw_background(color)
|
133 |
+
self.draw_axis(2, color[2])
|
134 |
+
self.draw_axis(1, color[1])
|
135 |
+
self.draw_axis(0, color[0])
|
136 |
+
|
137 |
+
def draw_background(self, color):
|
138 |
+
pass # optional
|
139 |
+
|
140 |
+
def draw_axis(self, axis, color):
|
141 |
+
raise NotImplementedError()
|
142 |
+
|
143 |
+
def draw_text(self, text, position, color, scale=1.0):
|
144 |
+
if len(color) == 3:
|
145 |
+
color = (color[0], color[1], color[2], 1.0)
|
146 |
+
|
147 |
+
if self._p.label_font is None:
|
148 |
+
self._p.label_font = font.load(self._p.font_face,
|
149 |
+
self._p.font_size,
|
150 |
+
bold=True, italic=False)
|
151 |
+
|
152 |
+
label = font.Text(self._p.label_font, text,
|
153 |
+
color=color,
|
154 |
+
valign=font.Text.BASELINE,
|
155 |
+
halign=font.Text.CENTER)
|
156 |
+
|
157 |
+
pgl.glPushMatrix()
|
158 |
+
pgl.glTranslatef(*position)
|
159 |
+
billboard_matrix()
|
160 |
+
scale_factor = 0.005 * scale
|
161 |
+
pgl.glScalef(scale_factor, scale_factor, scale_factor)
|
162 |
+
pgl.glColor4f(0, 0, 0, 0)
|
163 |
+
label.draw()
|
164 |
+
pgl.glPopMatrix()
|
165 |
+
|
166 |
+
def draw_line(self, v, color):
|
167 |
+
o = self._p._origin
|
168 |
+
pgl.glBegin(pgl.GL_LINES)
|
169 |
+
pgl.glColor3f(*color)
|
170 |
+
pgl.glVertex3f(v[0][0] + o[0], v[0][1] + o[1], v[0][2] + o[2])
|
171 |
+
pgl.glVertex3f(v[1][0] + o[0], v[1][1] + o[1], v[1][2] + o[2])
|
172 |
+
pgl.glEnd()
|
173 |
+
|
174 |
+
|
175 |
+
class PlotAxesOrdinate(PlotAxesBase):
|
176 |
+
|
177 |
+
def __init__(self, parent_axes):
|
178 |
+
super().__init__(parent_axes)
|
179 |
+
|
180 |
+
def draw_axis(self, axis, color):
|
181 |
+
ticks = self._p._axis_ticks[axis]
|
182 |
+
radius = self._p._tick_length / 2.0
|
183 |
+
if len(ticks) < 2:
|
184 |
+
return
|
185 |
+
|
186 |
+
# calculate the vector for this axis
|
187 |
+
axis_lines = [[0, 0, 0], [0, 0, 0]]
|
188 |
+
axis_lines[0][axis], axis_lines[1][axis] = ticks[0], ticks[-1]
|
189 |
+
axis_vector = vec_sub(axis_lines[1], axis_lines[0])
|
190 |
+
|
191 |
+
# calculate angle to the z direction vector
|
192 |
+
pos_z = get_direction_vectors()[2]
|
193 |
+
d = abs(dot_product(axis_vector, pos_z))
|
194 |
+
d = d / vec_mag(axis_vector)
|
195 |
+
|
196 |
+
# don't draw labels if we're looking down the axis
|
197 |
+
labels_visible = abs(d - 1.0) > 0.02
|
198 |
+
|
199 |
+
# draw the ticks and labels
|
200 |
+
for tick in ticks:
|
201 |
+
self.draw_tick_line(axis, color, radius, tick, labels_visible)
|
202 |
+
|
203 |
+
# draw the axis line and labels
|
204 |
+
self.draw_axis_line(axis, color, ticks[0], ticks[-1], labels_visible)
|
205 |
+
|
206 |
+
def draw_axis_line(self, axis, color, a_min, a_max, labels_visible):
|
207 |
+
axis_line = [[0, 0, 0], [0, 0, 0]]
|
208 |
+
axis_line[0][axis], axis_line[1][axis] = a_min, a_max
|
209 |
+
self.draw_line(axis_line, color)
|
210 |
+
if labels_visible:
|
211 |
+
self.draw_axis_line_labels(axis, color, axis_line)
|
212 |
+
|
213 |
+
def draw_axis_line_labels(self, axis, color, axis_line):
|
214 |
+
if not self._p._label_axes:
|
215 |
+
return
|
216 |
+
axis_labels = [axis_line[0][::], axis_line[1][::]]
|
217 |
+
axis_labels[0][axis] -= 0.3
|
218 |
+
axis_labels[1][axis] += 0.3
|
219 |
+
a_str = ['X', 'Y', 'Z'][axis]
|
220 |
+
self.draw_text("-" + a_str, axis_labels[0], color)
|
221 |
+
self.draw_text("+" + a_str, axis_labels[1], color)
|
222 |
+
|
223 |
+
def draw_tick_line(self, axis, color, radius, tick, labels_visible):
|
224 |
+
tick_axis = {0: 1, 1: 0, 2: 1}[axis]
|
225 |
+
tick_line = [[0, 0, 0], [0, 0, 0]]
|
226 |
+
tick_line[0][axis] = tick_line[1][axis] = tick
|
227 |
+
tick_line[0][tick_axis], tick_line[1][tick_axis] = -radius, radius
|
228 |
+
self.draw_line(tick_line, color)
|
229 |
+
if labels_visible:
|
230 |
+
self.draw_tick_line_label(axis, color, radius, tick)
|
231 |
+
|
232 |
+
def draw_tick_line_label(self, axis, color, radius, tick):
|
233 |
+
if not self._p._label_axes:
|
234 |
+
return
|
235 |
+
tick_label_vector = [0, 0, 0]
|
236 |
+
tick_label_vector[axis] = tick
|
237 |
+
tick_label_vector[{0: 1, 1: 0, 2: 1}[axis]] = [-1, 1, 1][
|
238 |
+
axis] * radius * 3.5
|
239 |
+
self.draw_text(str(tick), tick_label_vector, color, scale=0.5)
|
240 |
+
|
241 |
+
|
242 |
+
class PlotAxesFrame(PlotAxesBase):
|
243 |
+
|
244 |
+
def __init__(self, parent_axes):
|
245 |
+
super().__init__(parent_axes)
|
246 |
+
|
247 |
+
def draw_background(self, color):
|
248 |
+
pass
|
249 |
+
|
250 |
+
def draw_axis(self, axis, color):
|
251 |
+
raise NotImplementedError()
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_camera.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pyglet.gl as pgl
|
2 |
+
from sympy.plotting.pygletplot.plot_rotation import get_spherical_rotatation
|
3 |
+
from sympy.plotting.pygletplot.util import get_model_matrix, model_to_screen, \
|
4 |
+
screen_to_model, vec_subs
|
5 |
+
|
6 |
+
|
7 |
+
class PlotCamera:
|
8 |
+
|
9 |
+
min_dist = 0.05
|
10 |
+
max_dist = 500.0
|
11 |
+
|
12 |
+
min_ortho_dist = 100.0
|
13 |
+
max_ortho_dist = 10000.0
|
14 |
+
|
15 |
+
_default_dist = 6.0
|
16 |
+
_default_ortho_dist = 600.0
|
17 |
+
|
18 |
+
rot_presets = {
|
19 |
+
'xy': (0, 0, 0),
|
20 |
+
'xz': (-90, 0, 0),
|
21 |
+
'yz': (0, 90, 0),
|
22 |
+
'perspective': (-45, 0, -45)
|
23 |
+
}
|
24 |
+
|
25 |
+
def __init__(self, window, ortho=False):
|
26 |
+
self.window = window
|
27 |
+
self.axes = self.window.plot.axes
|
28 |
+
self.ortho = ortho
|
29 |
+
self.reset()
|
30 |
+
|
31 |
+
def init_rot_matrix(self):
|
32 |
+
pgl.glPushMatrix()
|
33 |
+
pgl.glLoadIdentity()
|
34 |
+
self._rot = get_model_matrix()
|
35 |
+
pgl.glPopMatrix()
|
36 |
+
|
37 |
+
def set_rot_preset(self, preset_name):
|
38 |
+
self.init_rot_matrix()
|
39 |
+
if preset_name not in self.rot_presets:
|
40 |
+
raise ValueError(
|
41 |
+
"%s is not a valid rotation preset." % preset_name)
|
42 |
+
r = self.rot_presets[preset_name]
|
43 |
+
self.euler_rotate(r[0], 1, 0, 0)
|
44 |
+
self.euler_rotate(r[1], 0, 1, 0)
|
45 |
+
self.euler_rotate(r[2], 0, 0, 1)
|
46 |
+
|
47 |
+
def reset(self):
|
48 |
+
self._dist = 0.0
|
49 |
+
self._x, self._y = 0.0, 0.0
|
50 |
+
self._rot = None
|
51 |
+
if self.ortho:
|
52 |
+
self._dist = self._default_ortho_dist
|
53 |
+
else:
|
54 |
+
self._dist = self._default_dist
|
55 |
+
self.init_rot_matrix()
|
56 |
+
|
57 |
+
def mult_rot_matrix(self, rot):
|
58 |
+
pgl.glPushMatrix()
|
59 |
+
pgl.glLoadMatrixf(rot)
|
60 |
+
pgl.glMultMatrixf(self._rot)
|
61 |
+
self._rot = get_model_matrix()
|
62 |
+
pgl.glPopMatrix()
|
63 |
+
|
64 |
+
def setup_projection(self):
|
65 |
+
pgl.glMatrixMode(pgl.GL_PROJECTION)
|
66 |
+
pgl.glLoadIdentity()
|
67 |
+
if self.ortho:
|
68 |
+
# yep, this is pseudo ortho (don't tell anyone)
|
69 |
+
pgl.gluPerspective(
|
70 |
+
0.3, float(self.window.width)/float(self.window.height),
|
71 |
+
self.min_ortho_dist - 0.01, self.max_ortho_dist + 0.01)
|
72 |
+
else:
|
73 |
+
pgl.gluPerspective(
|
74 |
+
30.0, float(self.window.width)/float(self.window.height),
|
75 |
+
self.min_dist - 0.01, self.max_dist + 0.01)
|
76 |
+
pgl.glMatrixMode(pgl.GL_MODELVIEW)
|
77 |
+
|
78 |
+
def _get_scale(self):
|
79 |
+
return 1.0, 1.0, 1.0
|
80 |
+
|
81 |
+
def apply_transformation(self):
|
82 |
+
pgl.glLoadIdentity()
|
83 |
+
pgl.glTranslatef(self._x, self._y, -self._dist)
|
84 |
+
if self._rot is not None:
|
85 |
+
pgl.glMultMatrixf(self._rot)
|
86 |
+
pgl.glScalef(*self._get_scale())
|
87 |
+
|
88 |
+
def spherical_rotate(self, p1, p2, sensitivity=1.0):
|
89 |
+
mat = get_spherical_rotatation(p1, p2, self.window.width,
|
90 |
+
self.window.height, sensitivity)
|
91 |
+
if mat is not None:
|
92 |
+
self.mult_rot_matrix(mat)
|
93 |
+
|
94 |
+
def euler_rotate(self, angle, x, y, z):
|
95 |
+
pgl.glPushMatrix()
|
96 |
+
pgl.glLoadMatrixf(self._rot)
|
97 |
+
pgl.glRotatef(angle, x, y, z)
|
98 |
+
self._rot = get_model_matrix()
|
99 |
+
pgl.glPopMatrix()
|
100 |
+
|
101 |
+
def zoom_relative(self, clicks, sensitivity):
|
102 |
+
|
103 |
+
if self.ortho:
|
104 |
+
dist_d = clicks * sensitivity * 50.0
|
105 |
+
min_dist = self.min_ortho_dist
|
106 |
+
max_dist = self.max_ortho_dist
|
107 |
+
else:
|
108 |
+
dist_d = clicks * sensitivity
|
109 |
+
min_dist = self.min_dist
|
110 |
+
max_dist = self.max_dist
|
111 |
+
|
112 |
+
new_dist = (self._dist - dist_d)
|
113 |
+
if (clicks < 0 and new_dist < max_dist) or new_dist > min_dist:
|
114 |
+
self._dist = new_dist
|
115 |
+
|
116 |
+
def mouse_translate(self, x, y, dx, dy):
|
117 |
+
pgl.glPushMatrix()
|
118 |
+
pgl.glLoadIdentity()
|
119 |
+
pgl.glTranslatef(0, 0, -self._dist)
|
120 |
+
z = model_to_screen(0, 0, 0)[2]
|
121 |
+
d = vec_subs(screen_to_model(x, y, z), screen_to_model(x - dx, y - dy, z))
|
122 |
+
pgl.glPopMatrix()
|
123 |
+
self._x += d[0]
|
124 |
+
self._y += d[1]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_controller.py
ADDED
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pyglet.window import key
|
2 |
+
from pyglet.window.mouse import LEFT, RIGHT, MIDDLE
|
3 |
+
from sympy.plotting.pygletplot.util import get_direction_vectors, get_basis_vectors
|
4 |
+
|
5 |
+
|
6 |
+
class PlotController:
|
7 |
+
|
8 |
+
normal_mouse_sensitivity = 4.0
|
9 |
+
modified_mouse_sensitivity = 1.0
|
10 |
+
|
11 |
+
normal_key_sensitivity = 160.0
|
12 |
+
modified_key_sensitivity = 40.0
|
13 |
+
|
14 |
+
keymap = {
|
15 |
+
key.LEFT: 'left',
|
16 |
+
key.A: 'left',
|
17 |
+
key.NUM_4: 'left',
|
18 |
+
|
19 |
+
key.RIGHT: 'right',
|
20 |
+
key.D: 'right',
|
21 |
+
key.NUM_6: 'right',
|
22 |
+
|
23 |
+
key.UP: 'up',
|
24 |
+
key.W: 'up',
|
25 |
+
key.NUM_8: 'up',
|
26 |
+
|
27 |
+
key.DOWN: 'down',
|
28 |
+
key.S: 'down',
|
29 |
+
key.NUM_2: 'down',
|
30 |
+
|
31 |
+
key.Z: 'rotate_z_neg',
|
32 |
+
key.NUM_1: 'rotate_z_neg',
|
33 |
+
|
34 |
+
key.C: 'rotate_z_pos',
|
35 |
+
key.NUM_3: 'rotate_z_pos',
|
36 |
+
|
37 |
+
key.Q: 'spin_left',
|
38 |
+
key.NUM_7: 'spin_left',
|
39 |
+
key.E: 'spin_right',
|
40 |
+
key.NUM_9: 'spin_right',
|
41 |
+
|
42 |
+
key.X: 'reset_camera',
|
43 |
+
key.NUM_5: 'reset_camera',
|
44 |
+
|
45 |
+
key.NUM_ADD: 'zoom_in',
|
46 |
+
key.PAGEUP: 'zoom_in',
|
47 |
+
key.R: 'zoom_in',
|
48 |
+
|
49 |
+
key.NUM_SUBTRACT: 'zoom_out',
|
50 |
+
key.PAGEDOWN: 'zoom_out',
|
51 |
+
key.F: 'zoom_out',
|
52 |
+
|
53 |
+
key.RSHIFT: 'modify_sensitivity',
|
54 |
+
key.LSHIFT: 'modify_sensitivity',
|
55 |
+
|
56 |
+
key.F1: 'rot_preset_xy',
|
57 |
+
key.F2: 'rot_preset_xz',
|
58 |
+
key.F3: 'rot_preset_yz',
|
59 |
+
key.F4: 'rot_preset_perspective',
|
60 |
+
|
61 |
+
key.F5: 'toggle_axes',
|
62 |
+
key.F6: 'toggle_axe_colors',
|
63 |
+
|
64 |
+
key.F8: 'save_image'
|
65 |
+
}
|
66 |
+
|
67 |
+
def __init__(self, window, *, invert_mouse_zoom=False, **kwargs):
|
68 |
+
self.invert_mouse_zoom = invert_mouse_zoom
|
69 |
+
self.window = window
|
70 |
+
self.camera = window.camera
|
71 |
+
self.action = {
|
72 |
+
# Rotation around the view Y (up) vector
|
73 |
+
'left': False,
|
74 |
+
'right': False,
|
75 |
+
# Rotation around the view X vector
|
76 |
+
'up': False,
|
77 |
+
'down': False,
|
78 |
+
# Rotation around the view Z vector
|
79 |
+
'spin_left': False,
|
80 |
+
'spin_right': False,
|
81 |
+
# Rotation around the model Z vector
|
82 |
+
'rotate_z_neg': False,
|
83 |
+
'rotate_z_pos': False,
|
84 |
+
# Reset to the default rotation
|
85 |
+
'reset_camera': False,
|
86 |
+
# Performs camera z-translation
|
87 |
+
'zoom_in': False,
|
88 |
+
'zoom_out': False,
|
89 |
+
# Use alternative sensitivity (speed)
|
90 |
+
'modify_sensitivity': False,
|
91 |
+
# Rotation presets
|
92 |
+
'rot_preset_xy': False,
|
93 |
+
'rot_preset_xz': False,
|
94 |
+
'rot_preset_yz': False,
|
95 |
+
'rot_preset_perspective': False,
|
96 |
+
# axes
|
97 |
+
'toggle_axes': False,
|
98 |
+
'toggle_axe_colors': False,
|
99 |
+
# screenshot
|
100 |
+
'save_image': False
|
101 |
+
}
|
102 |
+
|
103 |
+
def update(self, dt):
|
104 |
+
z = 0
|
105 |
+
if self.action['zoom_out']:
|
106 |
+
z -= 1
|
107 |
+
if self.action['zoom_in']:
|
108 |
+
z += 1
|
109 |
+
if z != 0:
|
110 |
+
self.camera.zoom_relative(z/10.0, self.get_key_sensitivity()/10.0)
|
111 |
+
|
112 |
+
dx, dy, dz = 0, 0, 0
|
113 |
+
if self.action['left']:
|
114 |
+
dx -= 1
|
115 |
+
if self.action['right']:
|
116 |
+
dx += 1
|
117 |
+
if self.action['up']:
|
118 |
+
dy -= 1
|
119 |
+
if self.action['down']:
|
120 |
+
dy += 1
|
121 |
+
if self.action['spin_left']:
|
122 |
+
dz += 1
|
123 |
+
if self.action['spin_right']:
|
124 |
+
dz -= 1
|
125 |
+
|
126 |
+
if not self.is_2D():
|
127 |
+
if dx != 0:
|
128 |
+
self.camera.euler_rotate(dx*dt*self.get_key_sensitivity(),
|
129 |
+
*(get_direction_vectors()[1]))
|
130 |
+
if dy != 0:
|
131 |
+
self.camera.euler_rotate(dy*dt*self.get_key_sensitivity(),
|
132 |
+
*(get_direction_vectors()[0]))
|
133 |
+
if dz != 0:
|
134 |
+
self.camera.euler_rotate(dz*dt*self.get_key_sensitivity(),
|
135 |
+
*(get_direction_vectors()[2]))
|
136 |
+
else:
|
137 |
+
self.camera.mouse_translate(0, 0, dx*dt*self.get_key_sensitivity(),
|
138 |
+
-dy*dt*self.get_key_sensitivity())
|
139 |
+
|
140 |
+
rz = 0
|
141 |
+
if self.action['rotate_z_neg'] and not self.is_2D():
|
142 |
+
rz -= 1
|
143 |
+
if self.action['rotate_z_pos'] and not self.is_2D():
|
144 |
+
rz += 1
|
145 |
+
|
146 |
+
if rz != 0:
|
147 |
+
self.camera.euler_rotate(rz*dt*self.get_key_sensitivity(),
|
148 |
+
*(get_basis_vectors()[2]))
|
149 |
+
|
150 |
+
if self.action['reset_camera']:
|
151 |
+
self.camera.reset()
|
152 |
+
|
153 |
+
if self.action['rot_preset_xy']:
|
154 |
+
self.camera.set_rot_preset('xy')
|
155 |
+
if self.action['rot_preset_xz']:
|
156 |
+
self.camera.set_rot_preset('xz')
|
157 |
+
if self.action['rot_preset_yz']:
|
158 |
+
self.camera.set_rot_preset('yz')
|
159 |
+
if self.action['rot_preset_perspective']:
|
160 |
+
self.camera.set_rot_preset('perspective')
|
161 |
+
|
162 |
+
if self.action['toggle_axes']:
|
163 |
+
self.action['toggle_axes'] = False
|
164 |
+
self.camera.axes.toggle_visible()
|
165 |
+
|
166 |
+
if self.action['toggle_axe_colors']:
|
167 |
+
self.action['toggle_axe_colors'] = False
|
168 |
+
self.camera.axes.toggle_colors()
|
169 |
+
|
170 |
+
if self.action['save_image']:
|
171 |
+
self.action['save_image'] = False
|
172 |
+
self.window.plot.saveimage()
|
173 |
+
|
174 |
+
return True
|
175 |
+
|
176 |
+
def get_mouse_sensitivity(self):
|
177 |
+
if self.action['modify_sensitivity']:
|
178 |
+
return self.modified_mouse_sensitivity
|
179 |
+
else:
|
180 |
+
return self.normal_mouse_sensitivity
|
181 |
+
|
182 |
+
def get_key_sensitivity(self):
|
183 |
+
if self.action['modify_sensitivity']:
|
184 |
+
return self.modified_key_sensitivity
|
185 |
+
else:
|
186 |
+
return self.normal_key_sensitivity
|
187 |
+
|
188 |
+
def on_key_press(self, symbol, modifiers):
|
189 |
+
if symbol in self.keymap:
|
190 |
+
self.action[self.keymap[symbol]] = True
|
191 |
+
|
192 |
+
def on_key_release(self, symbol, modifiers):
|
193 |
+
if symbol in self.keymap:
|
194 |
+
self.action[self.keymap[symbol]] = False
|
195 |
+
|
196 |
+
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
|
197 |
+
if buttons & LEFT:
|
198 |
+
if self.is_2D():
|
199 |
+
self.camera.mouse_translate(x, y, dx, dy)
|
200 |
+
else:
|
201 |
+
self.camera.spherical_rotate((x - dx, y - dy), (x, y),
|
202 |
+
self.get_mouse_sensitivity())
|
203 |
+
if buttons & MIDDLE:
|
204 |
+
self.camera.zoom_relative([1, -1][self.invert_mouse_zoom]*dy,
|
205 |
+
self.get_mouse_sensitivity()/20.0)
|
206 |
+
if buttons & RIGHT:
|
207 |
+
self.camera.mouse_translate(x, y, dx, dy)
|
208 |
+
|
209 |
+
def on_mouse_scroll(self, x, y, dx, dy):
|
210 |
+
self.camera.zoom_relative([1, -1][self.invert_mouse_zoom]*dy,
|
211 |
+
self.get_mouse_sensitivity())
|
212 |
+
|
213 |
+
def is_2D(self):
|
214 |
+
functions = self.window.plot._functions
|
215 |
+
for i in functions:
|
216 |
+
if len(functions[i].i_vars) > 1 or len(functions[i].d_vars) > 2:
|
217 |
+
return False
|
218 |
+
return True
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_curve.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pyglet.gl as pgl
|
2 |
+
from sympy.core import S
|
3 |
+
from sympy.plotting.pygletplot.plot_mode_base import PlotModeBase
|
4 |
+
|
5 |
+
|
6 |
+
class PlotCurve(PlotModeBase):
|
7 |
+
|
8 |
+
style_override = 'wireframe'
|
9 |
+
|
10 |
+
def _on_calculate_verts(self):
|
11 |
+
self.t_interval = self.intervals[0]
|
12 |
+
self.t_set = list(self.t_interval.frange())
|
13 |
+
self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
|
14 |
+
[S.Infinity, S.NegativeInfinity, 0],
|
15 |
+
[S.Infinity, S.NegativeInfinity, 0]]
|
16 |
+
evaluate = self._get_evaluator()
|
17 |
+
|
18 |
+
self._calculating_verts_pos = 0.0
|
19 |
+
self._calculating_verts_len = float(self.t_interval.v_len)
|
20 |
+
|
21 |
+
self.verts = []
|
22 |
+
b = self.bounds
|
23 |
+
for t in self.t_set:
|
24 |
+
try:
|
25 |
+
_e = evaluate(t) # calculate vertex
|
26 |
+
except (NameError, ZeroDivisionError):
|
27 |
+
_e = None
|
28 |
+
if _e is not None: # update bounding box
|
29 |
+
for axis in range(3):
|
30 |
+
b[axis][0] = min([b[axis][0], _e[axis]])
|
31 |
+
b[axis][1] = max([b[axis][1], _e[axis]])
|
32 |
+
self.verts.append(_e)
|
33 |
+
self._calculating_verts_pos += 1.0
|
34 |
+
|
35 |
+
for axis in range(3):
|
36 |
+
b[axis][2] = b[axis][1] - b[axis][0]
|
37 |
+
if b[axis][2] == 0.0:
|
38 |
+
b[axis][2] = 1.0
|
39 |
+
|
40 |
+
self.push_wireframe(self.draw_verts(False))
|
41 |
+
|
42 |
+
def _on_calculate_cverts(self):
|
43 |
+
if not self.verts or not self.color:
|
44 |
+
return
|
45 |
+
|
46 |
+
def set_work_len(n):
|
47 |
+
self._calculating_cverts_len = float(n)
|
48 |
+
|
49 |
+
def inc_work_pos():
|
50 |
+
self._calculating_cverts_pos += 1.0
|
51 |
+
set_work_len(1)
|
52 |
+
self._calculating_cverts_pos = 0
|
53 |
+
self.cverts = self.color.apply_to_curve(self.verts,
|
54 |
+
self.t_set,
|
55 |
+
set_len=set_work_len,
|
56 |
+
inc_pos=inc_work_pos)
|
57 |
+
self.push_wireframe(self.draw_verts(True))
|
58 |
+
|
59 |
+
def calculate_one_cvert(self, t):
|
60 |
+
vert = self.verts[t]
|
61 |
+
return self.color(vert[0], vert[1], vert[2],
|
62 |
+
self.t_set[t], None)
|
63 |
+
|
64 |
+
def draw_verts(self, use_cverts):
|
65 |
+
def f():
|
66 |
+
pgl.glBegin(pgl.GL_LINE_STRIP)
|
67 |
+
for t in range(len(self.t_set)):
|
68 |
+
p = self.verts[t]
|
69 |
+
if p is None:
|
70 |
+
pgl.glEnd()
|
71 |
+
pgl.glBegin(pgl.GL_LINE_STRIP)
|
72 |
+
continue
|
73 |
+
if use_cverts:
|
74 |
+
c = self.cverts[t]
|
75 |
+
if c is None:
|
76 |
+
c = (0, 0, 0)
|
77 |
+
pgl.glColor3f(*c)
|
78 |
+
else:
|
79 |
+
pgl.glColor3f(*self.default_wireframe_color)
|
80 |
+
pgl.glVertex3f(*p)
|
81 |
+
pgl.glEnd()
|
82 |
+
return f
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_interval.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.singleton import S
|
2 |
+
from sympy.core.symbol import Symbol
|
3 |
+
from sympy.core.sympify import sympify
|
4 |
+
from sympy.core.numbers import Integer
|
5 |
+
|
6 |
+
|
7 |
+
class PlotInterval:
|
8 |
+
"""
|
9 |
+
"""
|
10 |
+
_v, _v_min, _v_max, _v_steps = None, None, None, None
|
11 |
+
|
12 |
+
def require_all_args(f):
|
13 |
+
def check(self, *args, **kwargs):
|
14 |
+
for g in [self._v, self._v_min, self._v_max, self._v_steps]:
|
15 |
+
if g is None:
|
16 |
+
raise ValueError("PlotInterval is incomplete.")
|
17 |
+
return f(self, *args, **kwargs)
|
18 |
+
return check
|
19 |
+
|
20 |
+
def __init__(self, *args):
|
21 |
+
if len(args) == 1:
|
22 |
+
if isinstance(args[0], PlotInterval):
|
23 |
+
self.fill_from(args[0])
|
24 |
+
return
|
25 |
+
elif isinstance(args[0], str):
|
26 |
+
try:
|
27 |
+
args = eval(args[0])
|
28 |
+
except TypeError:
|
29 |
+
s_eval_error = "Could not interpret string %s."
|
30 |
+
raise ValueError(s_eval_error % (args[0]))
|
31 |
+
elif isinstance(args[0], (tuple, list)):
|
32 |
+
args = args[0]
|
33 |
+
else:
|
34 |
+
raise ValueError("Not an interval.")
|
35 |
+
if not isinstance(args, (tuple, list)) or len(args) > 4:
|
36 |
+
f_error = "PlotInterval must be a tuple or list of length 4 or less."
|
37 |
+
raise ValueError(f_error)
|
38 |
+
|
39 |
+
args = list(args)
|
40 |
+
if len(args) > 0 and (args[0] is None or isinstance(args[0], Symbol)):
|
41 |
+
self.v = args.pop(0)
|
42 |
+
if len(args) in [2, 3]:
|
43 |
+
self.v_min = args.pop(0)
|
44 |
+
self.v_max = args.pop(0)
|
45 |
+
if len(args) == 1:
|
46 |
+
self.v_steps = args.pop(0)
|
47 |
+
elif len(args) == 1:
|
48 |
+
self.v_steps = args.pop(0)
|
49 |
+
|
50 |
+
def get_v(self):
|
51 |
+
return self._v
|
52 |
+
|
53 |
+
def set_v(self, v):
|
54 |
+
if v is None:
|
55 |
+
self._v = None
|
56 |
+
return
|
57 |
+
if not isinstance(v, Symbol):
|
58 |
+
raise ValueError("v must be a SymPy Symbol.")
|
59 |
+
self._v = v
|
60 |
+
|
61 |
+
def get_v_min(self):
|
62 |
+
return self._v_min
|
63 |
+
|
64 |
+
def set_v_min(self, v_min):
|
65 |
+
if v_min is None:
|
66 |
+
self._v_min = None
|
67 |
+
return
|
68 |
+
try:
|
69 |
+
self._v_min = sympify(v_min)
|
70 |
+
float(self._v_min.evalf())
|
71 |
+
except TypeError:
|
72 |
+
raise ValueError("v_min could not be interpreted as a number.")
|
73 |
+
|
74 |
+
def get_v_max(self):
|
75 |
+
return self._v_max
|
76 |
+
|
77 |
+
def set_v_max(self, v_max):
|
78 |
+
if v_max is None:
|
79 |
+
self._v_max = None
|
80 |
+
return
|
81 |
+
try:
|
82 |
+
self._v_max = sympify(v_max)
|
83 |
+
float(self._v_max.evalf())
|
84 |
+
except TypeError:
|
85 |
+
raise ValueError("v_max could not be interpreted as a number.")
|
86 |
+
|
87 |
+
def get_v_steps(self):
|
88 |
+
return self._v_steps
|
89 |
+
|
90 |
+
def set_v_steps(self, v_steps):
|
91 |
+
if v_steps is None:
|
92 |
+
self._v_steps = None
|
93 |
+
return
|
94 |
+
if isinstance(v_steps, int):
|
95 |
+
v_steps = Integer(v_steps)
|
96 |
+
elif not isinstance(v_steps, Integer):
|
97 |
+
raise ValueError("v_steps must be an int or SymPy Integer.")
|
98 |
+
if v_steps <= S.Zero:
|
99 |
+
raise ValueError("v_steps must be positive.")
|
100 |
+
self._v_steps = v_steps
|
101 |
+
|
102 |
+
@require_all_args
|
103 |
+
def get_v_len(self):
|
104 |
+
return self.v_steps + 1
|
105 |
+
|
106 |
+
v = property(get_v, set_v)
|
107 |
+
v_min = property(get_v_min, set_v_min)
|
108 |
+
v_max = property(get_v_max, set_v_max)
|
109 |
+
v_steps = property(get_v_steps, set_v_steps)
|
110 |
+
v_len = property(get_v_len)
|
111 |
+
|
112 |
+
def fill_from(self, b):
|
113 |
+
if b.v is not None:
|
114 |
+
self.v = b.v
|
115 |
+
if b.v_min is not None:
|
116 |
+
self.v_min = b.v_min
|
117 |
+
if b.v_max is not None:
|
118 |
+
self.v_max = b.v_max
|
119 |
+
if b.v_steps is not None:
|
120 |
+
self.v_steps = b.v_steps
|
121 |
+
|
122 |
+
@staticmethod
|
123 |
+
def try_parse(*args):
|
124 |
+
"""
|
125 |
+
Returns a PlotInterval if args can be interpreted
|
126 |
+
as such, otherwise None.
|
127 |
+
"""
|
128 |
+
if len(args) == 1 and isinstance(args[0], PlotInterval):
|
129 |
+
return args[0]
|
130 |
+
try:
|
131 |
+
return PlotInterval(*args)
|
132 |
+
except ValueError:
|
133 |
+
return None
|
134 |
+
|
135 |
+
def _str_base(self):
|
136 |
+
return ",".join([str(self.v), str(self.v_min),
|
137 |
+
str(self.v_max), str(self.v_steps)])
|
138 |
+
|
139 |
+
def __repr__(self):
|
140 |
+
"""
|
141 |
+
A string representing the interval in class constructor form.
|
142 |
+
"""
|
143 |
+
return "PlotInterval(%s)" % (self._str_base())
|
144 |
+
|
145 |
+
def __str__(self):
|
146 |
+
"""
|
147 |
+
A string representing the interval in list form.
|
148 |
+
"""
|
149 |
+
return "[%s]" % (self._str_base())
|
150 |
+
|
151 |
+
@require_all_args
|
152 |
+
def assert_complete(self):
|
153 |
+
pass
|
154 |
+
|
155 |
+
@require_all_args
|
156 |
+
def vrange(self):
|
157 |
+
"""
|
158 |
+
Yields v_steps+1 SymPy numbers ranging from
|
159 |
+
v_min to v_max.
|
160 |
+
"""
|
161 |
+
d = (self.v_max - self.v_min) / self.v_steps
|
162 |
+
for i in range(self.v_steps + 1):
|
163 |
+
a = self.v_min + (d * Integer(i))
|
164 |
+
yield a
|
165 |
+
|
166 |
+
@require_all_args
|
167 |
+
def vrange2(self):
|
168 |
+
"""
|
169 |
+
Yields v_steps pairs of SymPy numbers ranging from
|
170 |
+
(v_min, v_min + step) to (v_max - step, v_max).
|
171 |
+
"""
|
172 |
+
d = (self.v_max - self.v_min) / self.v_steps
|
173 |
+
a = self.v_min + (d * S.Zero)
|
174 |
+
for i in range(self.v_steps):
|
175 |
+
b = self.v_min + (d * Integer(i + 1))
|
176 |
+
yield a, b
|
177 |
+
a = b
|
178 |
+
|
179 |
+
def frange(self):
|
180 |
+
for i in self.vrange():
|
181 |
+
yield float(i.evalf())
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode.py
ADDED
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .plot_interval import PlotInterval
|
2 |
+
from .plot_object import PlotObject
|
3 |
+
from .util import parse_option_string
|
4 |
+
from sympy.core.symbol import Symbol
|
5 |
+
from sympy.core.sympify import sympify
|
6 |
+
from sympy.geometry.entity import GeometryEntity
|
7 |
+
from sympy.utilities.iterables import is_sequence
|
8 |
+
|
9 |
+
|
10 |
+
class PlotMode(PlotObject):
|
11 |
+
"""
|
12 |
+
Grandparent class for plotting
|
13 |
+
modes. Serves as interface for
|
14 |
+
registration, lookup, and init
|
15 |
+
of modes.
|
16 |
+
|
17 |
+
To create a new plot mode,
|
18 |
+
inherit from PlotModeBase
|
19 |
+
or one of its children, such
|
20 |
+
as PlotSurface or PlotCurve.
|
21 |
+
"""
|
22 |
+
|
23 |
+
## Class-level attributes
|
24 |
+
## used to register and lookup
|
25 |
+
## plot modes. See PlotModeBase
|
26 |
+
## for descriptions and usage.
|
27 |
+
|
28 |
+
i_vars, d_vars = '', ''
|
29 |
+
intervals = []
|
30 |
+
aliases = []
|
31 |
+
is_default = False
|
32 |
+
|
33 |
+
## Draw is the only method here which
|
34 |
+
## is meant to be overridden in child
|
35 |
+
## classes, and PlotModeBase provides
|
36 |
+
## a base implementation.
|
37 |
+
def draw(self):
|
38 |
+
raise NotImplementedError()
|
39 |
+
|
40 |
+
## Everything else in this file has to
|
41 |
+
## do with registration and retrieval
|
42 |
+
## of plot modes. This is where I've
|
43 |
+
## hidden much of the ugliness of automatic
|
44 |
+
## plot mode divination...
|
45 |
+
|
46 |
+
## Plot mode registry data structures
|
47 |
+
_mode_alias_list = []
|
48 |
+
_mode_map = {
|
49 |
+
1: {1: {}, 2: {}},
|
50 |
+
2: {1: {}, 2: {}},
|
51 |
+
3: {1: {}, 2: {}},
|
52 |
+
} # [d][i][alias_str]: class
|
53 |
+
_mode_default_map = {
|
54 |
+
1: {},
|
55 |
+
2: {},
|
56 |
+
3: {},
|
57 |
+
} # [d][i]: class
|
58 |
+
_i_var_max, _d_var_max = 2, 3
|
59 |
+
|
60 |
+
def __new__(cls, *args, **kwargs):
|
61 |
+
"""
|
62 |
+
This is the function which interprets
|
63 |
+
arguments given to Plot.__init__ and
|
64 |
+
Plot.__setattr__. Returns an initialized
|
65 |
+
instance of the appropriate child class.
|
66 |
+
"""
|
67 |
+
|
68 |
+
newargs, newkwargs = PlotMode._extract_options(args, kwargs)
|
69 |
+
mode_arg = newkwargs.get('mode', '')
|
70 |
+
|
71 |
+
# Interpret the arguments
|
72 |
+
d_vars, intervals = PlotMode._interpret_args(newargs)
|
73 |
+
i_vars = PlotMode._find_i_vars(d_vars, intervals)
|
74 |
+
i, d = max([len(i_vars), len(intervals)]), len(d_vars)
|
75 |
+
|
76 |
+
# Find the appropriate mode
|
77 |
+
subcls = PlotMode._get_mode(mode_arg, i, d)
|
78 |
+
|
79 |
+
# Create the object
|
80 |
+
o = object.__new__(subcls)
|
81 |
+
|
82 |
+
# Do some setup for the mode instance
|
83 |
+
o.d_vars = d_vars
|
84 |
+
o._fill_i_vars(i_vars)
|
85 |
+
o._fill_intervals(intervals)
|
86 |
+
o.options = newkwargs
|
87 |
+
|
88 |
+
return o
|
89 |
+
|
90 |
+
@staticmethod
|
91 |
+
def _get_mode(mode_arg, i_var_count, d_var_count):
|
92 |
+
"""
|
93 |
+
Tries to return an appropriate mode class.
|
94 |
+
Intended to be called only by __new__.
|
95 |
+
|
96 |
+
mode_arg
|
97 |
+
Can be a string or a class. If it is a
|
98 |
+
PlotMode subclass, it is simply returned.
|
99 |
+
If it is a string, it can an alias for
|
100 |
+
a mode or an empty string. In the latter
|
101 |
+
case, we try to find a default mode for
|
102 |
+
the i_var_count and d_var_count.
|
103 |
+
|
104 |
+
i_var_count
|
105 |
+
The number of independent variables
|
106 |
+
needed to evaluate the d_vars.
|
107 |
+
|
108 |
+
d_var_count
|
109 |
+
The number of dependent variables;
|
110 |
+
usually the number of functions to
|
111 |
+
be evaluated in plotting.
|
112 |
+
|
113 |
+
For example, a Cartesian function y = f(x) has
|
114 |
+
one i_var (x) and one d_var (y). A parametric
|
115 |
+
form x,y,z = f(u,v), f(u,v), f(u,v) has two
|
116 |
+
two i_vars (u,v) and three d_vars (x,y,z).
|
117 |
+
"""
|
118 |
+
# if the mode_arg is simply a PlotMode class,
|
119 |
+
# check that the mode supports the numbers
|
120 |
+
# of independent and dependent vars, then
|
121 |
+
# return it
|
122 |
+
try:
|
123 |
+
m = None
|
124 |
+
if issubclass(mode_arg, PlotMode):
|
125 |
+
m = mode_arg
|
126 |
+
except TypeError:
|
127 |
+
pass
|
128 |
+
if m:
|
129 |
+
if not m._was_initialized:
|
130 |
+
raise ValueError(("To use unregistered plot mode %s "
|
131 |
+
"you must first call %s._init_mode().")
|
132 |
+
% (m.__name__, m.__name__))
|
133 |
+
if d_var_count != m.d_var_count:
|
134 |
+
raise ValueError(("%s can only plot functions "
|
135 |
+
"with %i dependent variables.")
|
136 |
+
% (m.__name__,
|
137 |
+
m.d_var_count))
|
138 |
+
if i_var_count > m.i_var_count:
|
139 |
+
raise ValueError(("%s cannot plot functions "
|
140 |
+
"with more than %i independent "
|
141 |
+
"variables.")
|
142 |
+
% (m.__name__,
|
143 |
+
m.i_var_count))
|
144 |
+
return m
|
145 |
+
# If it is a string, there are two possibilities.
|
146 |
+
if isinstance(mode_arg, str):
|
147 |
+
i, d = i_var_count, d_var_count
|
148 |
+
if i > PlotMode._i_var_max:
|
149 |
+
raise ValueError(var_count_error(True, True))
|
150 |
+
if d > PlotMode._d_var_max:
|
151 |
+
raise ValueError(var_count_error(False, True))
|
152 |
+
# If the string is '', try to find a suitable
|
153 |
+
# default mode
|
154 |
+
if not mode_arg:
|
155 |
+
return PlotMode._get_default_mode(i, d)
|
156 |
+
# Otherwise, interpret the string as a mode
|
157 |
+
# alias (e.g. 'cartesian', 'parametric', etc)
|
158 |
+
else:
|
159 |
+
return PlotMode._get_aliased_mode(mode_arg, i, d)
|
160 |
+
else:
|
161 |
+
raise ValueError("PlotMode argument must be "
|
162 |
+
"a class or a string")
|
163 |
+
|
164 |
+
@staticmethod
|
165 |
+
def _get_default_mode(i, d, i_vars=-1):
|
166 |
+
if i_vars == -1:
|
167 |
+
i_vars = i
|
168 |
+
try:
|
169 |
+
return PlotMode._mode_default_map[d][i]
|
170 |
+
except KeyError:
|
171 |
+
# Keep looking for modes in higher i var counts
|
172 |
+
# which support the given d var count until we
|
173 |
+
# reach the max i_var count.
|
174 |
+
if i < PlotMode._i_var_max:
|
175 |
+
return PlotMode._get_default_mode(i + 1, d, i_vars)
|
176 |
+
else:
|
177 |
+
raise ValueError(("Couldn't find a default mode "
|
178 |
+
"for %i independent and %i "
|
179 |
+
"dependent variables.") % (i_vars, d))
|
180 |
+
|
181 |
+
@staticmethod
|
182 |
+
def _get_aliased_mode(alias, i, d, i_vars=-1):
|
183 |
+
if i_vars == -1:
|
184 |
+
i_vars = i
|
185 |
+
if alias not in PlotMode._mode_alias_list:
|
186 |
+
raise ValueError(("Couldn't find a mode called"
|
187 |
+
" %s. Known modes: %s.")
|
188 |
+
% (alias, ", ".join(PlotMode._mode_alias_list)))
|
189 |
+
try:
|
190 |
+
return PlotMode._mode_map[d][i][alias]
|
191 |
+
except TypeError:
|
192 |
+
# Keep looking for modes in higher i var counts
|
193 |
+
# which support the given d var count and alias
|
194 |
+
# until we reach the max i_var count.
|
195 |
+
if i < PlotMode._i_var_max:
|
196 |
+
return PlotMode._get_aliased_mode(alias, i + 1, d, i_vars)
|
197 |
+
else:
|
198 |
+
raise ValueError(("Couldn't find a %s mode "
|
199 |
+
"for %i independent and %i "
|
200 |
+
"dependent variables.")
|
201 |
+
% (alias, i_vars, d))
|
202 |
+
|
203 |
+
@classmethod
|
204 |
+
def _register(cls):
|
205 |
+
"""
|
206 |
+
Called once for each user-usable plot mode.
|
207 |
+
For Cartesian2D, it is invoked after the
|
208 |
+
class definition: Cartesian2D._register()
|
209 |
+
"""
|
210 |
+
name = cls.__name__
|
211 |
+
cls._init_mode()
|
212 |
+
|
213 |
+
try:
|
214 |
+
i, d = cls.i_var_count, cls.d_var_count
|
215 |
+
# Add the mode to _mode_map under all
|
216 |
+
# given aliases
|
217 |
+
for a in cls.aliases:
|
218 |
+
if a not in PlotMode._mode_alias_list:
|
219 |
+
# Also track valid aliases, so
|
220 |
+
# we can quickly know when given
|
221 |
+
# an invalid one in _get_mode.
|
222 |
+
PlotMode._mode_alias_list.append(a)
|
223 |
+
PlotMode._mode_map[d][i][a] = cls
|
224 |
+
if cls.is_default:
|
225 |
+
# If this mode was marked as the
|
226 |
+
# default for this d,i combination,
|
227 |
+
# also set that.
|
228 |
+
PlotMode._mode_default_map[d][i] = cls
|
229 |
+
|
230 |
+
except Exception as e:
|
231 |
+
raise RuntimeError(("Failed to register "
|
232 |
+
"plot mode %s. Reason: %s")
|
233 |
+
% (name, (str(e))))
|
234 |
+
|
235 |
+
@classmethod
|
236 |
+
def _init_mode(cls):
|
237 |
+
"""
|
238 |
+
Initializes the plot mode based on
|
239 |
+
the 'mode-specific parameters' above.
|
240 |
+
Only intended to be called by
|
241 |
+
PlotMode._register(). To use a mode without
|
242 |
+
registering it, you can directly call
|
243 |
+
ModeSubclass._init_mode().
|
244 |
+
"""
|
245 |
+
def symbols_list(symbol_str):
|
246 |
+
return [Symbol(s) for s in symbol_str]
|
247 |
+
|
248 |
+
# Convert the vars strs into
|
249 |
+
# lists of symbols.
|
250 |
+
cls.i_vars = symbols_list(cls.i_vars)
|
251 |
+
cls.d_vars = symbols_list(cls.d_vars)
|
252 |
+
|
253 |
+
# Var count is used often, calculate
|
254 |
+
# it once here
|
255 |
+
cls.i_var_count = len(cls.i_vars)
|
256 |
+
cls.d_var_count = len(cls.d_vars)
|
257 |
+
|
258 |
+
if cls.i_var_count > PlotMode._i_var_max:
|
259 |
+
raise ValueError(var_count_error(True, False))
|
260 |
+
if cls.d_var_count > PlotMode._d_var_max:
|
261 |
+
raise ValueError(var_count_error(False, False))
|
262 |
+
|
263 |
+
# Try to use first alias as primary_alias
|
264 |
+
if len(cls.aliases) > 0:
|
265 |
+
cls.primary_alias = cls.aliases[0]
|
266 |
+
else:
|
267 |
+
cls.primary_alias = cls.__name__
|
268 |
+
|
269 |
+
di = cls.intervals
|
270 |
+
if len(di) != cls.i_var_count:
|
271 |
+
raise ValueError("Plot mode must provide a "
|
272 |
+
"default interval for each i_var.")
|
273 |
+
for i in range(cls.i_var_count):
|
274 |
+
# default intervals must be given [min,max,steps]
|
275 |
+
# (no var, but they must be in the same order as i_vars)
|
276 |
+
if len(di[i]) != 3:
|
277 |
+
raise ValueError("length should be equal to 3")
|
278 |
+
|
279 |
+
# Initialize an incomplete interval,
|
280 |
+
# to later be filled with a var when
|
281 |
+
# the mode is instantiated.
|
282 |
+
di[i] = PlotInterval(None, *di[i])
|
283 |
+
|
284 |
+
# To prevent people from using modes
|
285 |
+
# without these required fields set up.
|
286 |
+
cls._was_initialized = True
|
287 |
+
|
288 |
+
_was_initialized = False
|
289 |
+
|
290 |
+
## Initializer Helper Methods
|
291 |
+
|
292 |
+
@staticmethod
|
293 |
+
def _find_i_vars(functions, intervals):
|
294 |
+
i_vars = []
|
295 |
+
|
296 |
+
# First, collect i_vars in the
|
297 |
+
# order they are given in any
|
298 |
+
# intervals.
|
299 |
+
for i in intervals:
|
300 |
+
if i.v is None:
|
301 |
+
continue
|
302 |
+
elif i.v in i_vars:
|
303 |
+
raise ValueError(("Multiple intervals given "
|
304 |
+
"for %s.") % (str(i.v)))
|
305 |
+
i_vars.append(i.v)
|
306 |
+
|
307 |
+
# Then, find any remaining
|
308 |
+
# i_vars in given functions
|
309 |
+
# (aka d_vars)
|
310 |
+
for f in functions:
|
311 |
+
for a in f.free_symbols:
|
312 |
+
if a not in i_vars:
|
313 |
+
i_vars.append(a)
|
314 |
+
|
315 |
+
return i_vars
|
316 |
+
|
317 |
+
def _fill_i_vars(self, i_vars):
|
318 |
+
# copy default i_vars
|
319 |
+
self.i_vars = [Symbol(str(i)) for i in self.i_vars]
|
320 |
+
# replace with given i_vars
|
321 |
+
for i in range(len(i_vars)):
|
322 |
+
self.i_vars[i] = i_vars[i]
|
323 |
+
|
324 |
+
def _fill_intervals(self, intervals):
|
325 |
+
# copy default intervals
|
326 |
+
self.intervals = [PlotInterval(i) for i in self.intervals]
|
327 |
+
# track i_vars used so far
|
328 |
+
v_used = []
|
329 |
+
# fill copy of default
|
330 |
+
# intervals with given info
|
331 |
+
for i in range(len(intervals)):
|
332 |
+
self.intervals[i].fill_from(intervals[i])
|
333 |
+
if self.intervals[i].v is not None:
|
334 |
+
v_used.append(self.intervals[i].v)
|
335 |
+
# Find any orphan intervals and
|
336 |
+
# assign them i_vars
|
337 |
+
for i in range(len(self.intervals)):
|
338 |
+
if self.intervals[i].v is None:
|
339 |
+
u = [v for v in self.i_vars if v not in v_used]
|
340 |
+
if len(u) == 0:
|
341 |
+
raise ValueError("length should not be equal to 0")
|
342 |
+
self.intervals[i].v = u[0]
|
343 |
+
v_used.append(u[0])
|
344 |
+
|
345 |
+
@staticmethod
|
346 |
+
def _interpret_args(args):
|
347 |
+
interval_wrong_order = "PlotInterval %s was given before any function(s)."
|
348 |
+
interpret_error = "Could not interpret %s as a function or interval."
|
349 |
+
|
350 |
+
functions, intervals = [], []
|
351 |
+
if isinstance(args[0], GeometryEntity):
|
352 |
+
for coords in list(args[0].arbitrary_point()):
|
353 |
+
functions.append(coords)
|
354 |
+
intervals.append(PlotInterval.try_parse(args[0].plot_interval()))
|
355 |
+
else:
|
356 |
+
for a in args:
|
357 |
+
i = PlotInterval.try_parse(a)
|
358 |
+
if i is not None:
|
359 |
+
if len(functions) == 0:
|
360 |
+
raise ValueError(interval_wrong_order % (str(i)))
|
361 |
+
else:
|
362 |
+
intervals.append(i)
|
363 |
+
else:
|
364 |
+
if is_sequence(a, include=str):
|
365 |
+
raise ValueError(interpret_error % (str(a)))
|
366 |
+
try:
|
367 |
+
f = sympify(a)
|
368 |
+
functions.append(f)
|
369 |
+
except TypeError:
|
370 |
+
raise ValueError(interpret_error % str(a))
|
371 |
+
|
372 |
+
return functions, intervals
|
373 |
+
|
374 |
+
@staticmethod
|
375 |
+
def _extract_options(args, kwargs):
|
376 |
+
newkwargs, newargs = {}, []
|
377 |
+
for a in args:
|
378 |
+
if isinstance(a, str):
|
379 |
+
newkwargs = dict(newkwargs, **parse_option_string(a))
|
380 |
+
else:
|
381 |
+
newargs.append(a)
|
382 |
+
newkwargs = dict(newkwargs, **kwargs)
|
383 |
+
return newargs, newkwargs
|
384 |
+
|
385 |
+
|
386 |
+
def var_count_error(is_independent, is_plotting):
|
387 |
+
"""
|
388 |
+
Used to format an error message which differs
|
389 |
+
slightly in 4 places.
|
390 |
+
"""
|
391 |
+
if is_plotting:
|
392 |
+
v = "Plotting"
|
393 |
+
else:
|
394 |
+
v = "Registering plot modes"
|
395 |
+
if is_independent:
|
396 |
+
n, s = PlotMode._i_var_max, "independent"
|
397 |
+
else:
|
398 |
+
n, s = PlotMode._d_var_max, "dependent"
|
399 |
+
return ("%s with more than %i %s variables "
|
400 |
+
"is not supported.") % (v, n, s)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode_base.py
ADDED
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pyglet.gl as pgl
|
2 |
+
from sympy.core import S
|
3 |
+
from sympy.plotting.pygletplot.color_scheme import ColorScheme
|
4 |
+
from sympy.plotting.pygletplot.plot_mode import PlotMode
|
5 |
+
from sympy.utilities.iterables import is_sequence
|
6 |
+
from time import sleep
|
7 |
+
from threading import Thread, Event, RLock
|
8 |
+
import warnings
|
9 |
+
|
10 |
+
|
11 |
+
class PlotModeBase(PlotMode):
|
12 |
+
"""
|
13 |
+
Intended parent class for plotting
|
14 |
+
modes. Provides base functionality
|
15 |
+
in conjunction with its parent,
|
16 |
+
PlotMode.
|
17 |
+
"""
|
18 |
+
|
19 |
+
##
|
20 |
+
## Class-Level Attributes
|
21 |
+
##
|
22 |
+
|
23 |
+
"""
|
24 |
+
The following attributes are meant
|
25 |
+
to be set at the class level, and serve
|
26 |
+
as parameters to the plot mode registry
|
27 |
+
(in PlotMode). See plot_modes.py for
|
28 |
+
concrete examples.
|
29 |
+
"""
|
30 |
+
|
31 |
+
"""
|
32 |
+
i_vars
|
33 |
+
'x' for Cartesian2D
|
34 |
+
'xy' for Cartesian3D
|
35 |
+
etc.
|
36 |
+
|
37 |
+
d_vars
|
38 |
+
'y' for Cartesian2D
|
39 |
+
'r' for Polar
|
40 |
+
etc.
|
41 |
+
"""
|
42 |
+
i_vars, d_vars = '', ''
|
43 |
+
|
44 |
+
"""
|
45 |
+
intervals
|
46 |
+
Default intervals for each i_var, and in the
|
47 |
+
same order. Specified [min, max, steps].
|
48 |
+
No variable can be given (it is bound later).
|
49 |
+
"""
|
50 |
+
intervals = []
|
51 |
+
|
52 |
+
"""
|
53 |
+
aliases
|
54 |
+
A list of strings which can be used to
|
55 |
+
access this mode.
|
56 |
+
'cartesian' for Cartesian2D and Cartesian3D
|
57 |
+
'polar' for Polar
|
58 |
+
'cylindrical', 'polar' for Cylindrical
|
59 |
+
|
60 |
+
Note that _init_mode chooses the first alias
|
61 |
+
in the list as the mode's primary_alias, which
|
62 |
+
will be displayed to the end user in certain
|
63 |
+
contexts.
|
64 |
+
"""
|
65 |
+
aliases = []
|
66 |
+
|
67 |
+
"""
|
68 |
+
is_default
|
69 |
+
Whether to set this mode as the default
|
70 |
+
for arguments passed to PlotMode() containing
|
71 |
+
the same number of d_vars as this mode and
|
72 |
+
at most the same number of i_vars.
|
73 |
+
"""
|
74 |
+
is_default = False
|
75 |
+
|
76 |
+
"""
|
77 |
+
All of the above attributes are defined in PlotMode.
|
78 |
+
The following ones are specific to PlotModeBase.
|
79 |
+
"""
|
80 |
+
|
81 |
+
"""
|
82 |
+
A list of the render styles. Do not modify.
|
83 |
+
"""
|
84 |
+
styles = {'wireframe': 1, 'solid': 2, 'both': 3}
|
85 |
+
|
86 |
+
"""
|
87 |
+
style_override
|
88 |
+
Always use this style if not blank.
|
89 |
+
"""
|
90 |
+
style_override = ''
|
91 |
+
|
92 |
+
"""
|
93 |
+
default_wireframe_color
|
94 |
+
default_solid_color
|
95 |
+
Can be used when color is None or being calculated.
|
96 |
+
Used by PlotCurve and PlotSurface, but not anywhere
|
97 |
+
in PlotModeBase.
|
98 |
+
"""
|
99 |
+
|
100 |
+
default_wireframe_color = (0.85, 0.85, 0.85)
|
101 |
+
default_solid_color = (0.6, 0.6, 0.9)
|
102 |
+
default_rot_preset = 'xy'
|
103 |
+
|
104 |
+
##
|
105 |
+
## Instance-Level Attributes
|
106 |
+
##
|
107 |
+
|
108 |
+
## 'Abstract' member functions
|
109 |
+
def _get_evaluator(self):
|
110 |
+
if self.use_lambda_eval:
|
111 |
+
try:
|
112 |
+
e = self._get_lambda_evaluator()
|
113 |
+
return e
|
114 |
+
except Exception:
|
115 |
+
warnings.warn("\nWarning: creating lambda evaluator failed. "
|
116 |
+
"Falling back on SymPy subs evaluator.")
|
117 |
+
return self._get_sympy_evaluator()
|
118 |
+
|
119 |
+
def _get_sympy_evaluator(self):
|
120 |
+
raise NotImplementedError()
|
121 |
+
|
122 |
+
def _get_lambda_evaluator(self):
|
123 |
+
raise NotImplementedError()
|
124 |
+
|
125 |
+
def _on_calculate_verts(self):
|
126 |
+
raise NotImplementedError()
|
127 |
+
|
128 |
+
def _on_calculate_cverts(self):
|
129 |
+
raise NotImplementedError()
|
130 |
+
|
131 |
+
## Base member functions
|
132 |
+
def __init__(self, *args, bounds_callback=None, **kwargs):
|
133 |
+
self.verts = []
|
134 |
+
self.cverts = []
|
135 |
+
self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
|
136 |
+
[S.Infinity, S.NegativeInfinity, 0],
|
137 |
+
[S.Infinity, S.NegativeInfinity, 0]]
|
138 |
+
self.cbounds = [[S.Infinity, S.NegativeInfinity, 0],
|
139 |
+
[S.Infinity, S.NegativeInfinity, 0],
|
140 |
+
[S.Infinity, S.NegativeInfinity, 0]]
|
141 |
+
|
142 |
+
self._draw_lock = RLock()
|
143 |
+
|
144 |
+
self._calculating_verts = Event()
|
145 |
+
self._calculating_cverts = Event()
|
146 |
+
self._calculating_verts_pos = 0.0
|
147 |
+
self._calculating_verts_len = 0.0
|
148 |
+
self._calculating_cverts_pos = 0.0
|
149 |
+
self._calculating_cverts_len = 0.0
|
150 |
+
|
151 |
+
self._max_render_stack_size = 3
|
152 |
+
self._draw_wireframe = [-1]
|
153 |
+
self._draw_solid = [-1]
|
154 |
+
|
155 |
+
self._style = None
|
156 |
+
self._color = None
|
157 |
+
|
158 |
+
self.predraw = []
|
159 |
+
self.postdraw = []
|
160 |
+
|
161 |
+
self.use_lambda_eval = self.options.pop('use_sympy_eval', None) is None
|
162 |
+
self.style = self.options.pop('style', '')
|
163 |
+
self.color = self.options.pop('color', 'rainbow')
|
164 |
+
self.bounds_callback = bounds_callback
|
165 |
+
|
166 |
+
self._on_calculate()
|
167 |
+
|
168 |
+
def synchronized(f):
|
169 |
+
def w(self, *args, **kwargs):
|
170 |
+
self._draw_lock.acquire()
|
171 |
+
try:
|
172 |
+
r = f(self, *args, **kwargs)
|
173 |
+
return r
|
174 |
+
finally:
|
175 |
+
self._draw_lock.release()
|
176 |
+
return w
|
177 |
+
|
178 |
+
@synchronized
|
179 |
+
def push_wireframe(self, function):
|
180 |
+
"""
|
181 |
+
Push a function which performs gl commands
|
182 |
+
used to build a display list. (The list is
|
183 |
+
built outside of the function)
|
184 |
+
"""
|
185 |
+
assert callable(function)
|
186 |
+
self._draw_wireframe.append(function)
|
187 |
+
if len(self._draw_wireframe) > self._max_render_stack_size:
|
188 |
+
del self._draw_wireframe[1] # leave marker element
|
189 |
+
|
190 |
+
@synchronized
|
191 |
+
def push_solid(self, function):
|
192 |
+
"""
|
193 |
+
Push a function which performs gl commands
|
194 |
+
used to build a display list. (The list is
|
195 |
+
built outside of the function)
|
196 |
+
"""
|
197 |
+
assert callable(function)
|
198 |
+
self._draw_solid.append(function)
|
199 |
+
if len(self._draw_solid) > self._max_render_stack_size:
|
200 |
+
del self._draw_solid[1] # leave marker element
|
201 |
+
|
202 |
+
def _create_display_list(self, function):
|
203 |
+
dl = pgl.glGenLists(1)
|
204 |
+
pgl.glNewList(dl, pgl.GL_COMPILE)
|
205 |
+
function()
|
206 |
+
pgl.glEndList()
|
207 |
+
return dl
|
208 |
+
|
209 |
+
def _render_stack_top(self, render_stack):
|
210 |
+
top = render_stack[-1]
|
211 |
+
if top == -1:
|
212 |
+
return -1 # nothing to display
|
213 |
+
elif callable(top):
|
214 |
+
dl = self._create_display_list(top)
|
215 |
+
render_stack[-1] = (dl, top)
|
216 |
+
return dl # display newly added list
|
217 |
+
elif len(top) == 2:
|
218 |
+
if pgl.GL_TRUE == pgl.glIsList(top[0]):
|
219 |
+
return top[0] # display stored list
|
220 |
+
dl = self._create_display_list(top[1])
|
221 |
+
render_stack[-1] = (dl, top[1])
|
222 |
+
return dl # display regenerated list
|
223 |
+
|
224 |
+
def _draw_solid_display_list(self, dl):
|
225 |
+
pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT)
|
226 |
+
pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_FILL)
|
227 |
+
pgl.glCallList(dl)
|
228 |
+
pgl.glPopAttrib()
|
229 |
+
|
230 |
+
def _draw_wireframe_display_list(self, dl):
|
231 |
+
pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT)
|
232 |
+
pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_LINE)
|
233 |
+
pgl.glEnable(pgl.GL_POLYGON_OFFSET_LINE)
|
234 |
+
pgl.glPolygonOffset(-0.005, -50.0)
|
235 |
+
pgl.glCallList(dl)
|
236 |
+
pgl.glPopAttrib()
|
237 |
+
|
238 |
+
@synchronized
|
239 |
+
def draw(self):
|
240 |
+
for f in self.predraw:
|
241 |
+
if callable(f):
|
242 |
+
f()
|
243 |
+
if self.style_override:
|
244 |
+
style = self.styles[self.style_override]
|
245 |
+
else:
|
246 |
+
style = self.styles[self._style]
|
247 |
+
# Draw solid component if style includes solid
|
248 |
+
if style & 2:
|
249 |
+
dl = self._render_stack_top(self._draw_solid)
|
250 |
+
if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl):
|
251 |
+
self._draw_solid_display_list(dl)
|
252 |
+
# Draw wireframe component if style includes wireframe
|
253 |
+
if style & 1:
|
254 |
+
dl = self._render_stack_top(self._draw_wireframe)
|
255 |
+
if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl):
|
256 |
+
self._draw_wireframe_display_list(dl)
|
257 |
+
for f in self.postdraw:
|
258 |
+
if callable(f):
|
259 |
+
f()
|
260 |
+
|
261 |
+
def _on_change_color(self, color):
|
262 |
+
Thread(target=self._calculate_cverts).start()
|
263 |
+
|
264 |
+
def _on_calculate(self):
|
265 |
+
Thread(target=self._calculate_all).start()
|
266 |
+
|
267 |
+
def _calculate_all(self):
|
268 |
+
self._calculate_verts()
|
269 |
+
self._calculate_cverts()
|
270 |
+
|
271 |
+
def _calculate_verts(self):
|
272 |
+
if self._calculating_verts.is_set():
|
273 |
+
return
|
274 |
+
self._calculating_verts.set()
|
275 |
+
try:
|
276 |
+
self._on_calculate_verts()
|
277 |
+
finally:
|
278 |
+
self._calculating_verts.clear()
|
279 |
+
if callable(self.bounds_callback):
|
280 |
+
self.bounds_callback()
|
281 |
+
|
282 |
+
def _calculate_cverts(self):
|
283 |
+
if self._calculating_verts.is_set():
|
284 |
+
return
|
285 |
+
while self._calculating_cverts.is_set():
|
286 |
+
sleep(0) # wait for previous calculation
|
287 |
+
self._calculating_cverts.set()
|
288 |
+
try:
|
289 |
+
self._on_calculate_cverts()
|
290 |
+
finally:
|
291 |
+
self._calculating_cverts.clear()
|
292 |
+
|
293 |
+
def _get_calculating_verts(self):
|
294 |
+
return self._calculating_verts.is_set()
|
295 |
+
|
296 |
+
def _get_calculating_verts_pos(self):
|
297 |
+
return self._calculating_verts_pos
|
298 |
+
|
299 |
+
def _get_calculating_verts_len(self):
|
300 |
+
return self._calculating_verts_len
|
301 |
+
|
302 |
+
def _get_calculating_cverts(self):
|
303 |
+
return self._calculating_cverts.is_set()
|
304 |
+
|
305 |
+
def _get_calculating_cverts_pos(self):
|
306 |
+
return self._calculating_cverts_pos
|
307 |
+
|
308 |
+
def _get_calculating_cverts_len(self):
|
309 |
+
return self._calculating_cverts_len
|
310 |
+
|
311 |
+
## Property handlers
|
312 |
+
def _get_style(self):
|
313 |
+
return self._style
|
314 |
+
|
315 |
+
@synchronized
|
316 |
+
def _set_style(self, v):
|
317 |
+
if v is None:
|
318 |
+
return
|
319 |
+
if v == '':
|
320 |
+
step_max = 0
|
321 |
+
for i in self.intervals:
|
322 |
+
if i.v_steps is None:
|
323 |
+
continue
|
324 |
+
step_max = max([step_max, int(i.v_steps)])
|
325 |
+
v = ['both', 'solid'][step_max > 40]
|
326 |
+
if v not in self.styles:
|
327 |
+
raise ValueError("v should be there in self.styles")
|
328 |
+
if v == self._style:
|
329 |
+
return
|
330 |
+
self._style = v
|
331 |
+
|
332 |
+
def _get_color(self):
|
333 |
+
return self._color
|
334 |
+
|
335 |
+
@synchronized
|
336 |
+
def _set_color(self, v):
|
337 |
+
try:
|
338 |
+
if v is not None:
|
339 |
+
if is_sequence(v):
|
340 |
+
v = ColorScheme(*v)
|
341 |
+
else:
|
342 |
+
v = ColorScheme(v)
|
343 |
+
if repr(v) == repr(self._color):
|
344 |
+
return
|
345 |
+
self._on_change_color(v)
|
346 |
+
self._color = v
|
347 |
+
except Exception as e:
|
348 |
+
raise RuntimeError("Color change failed. "
|
349 |
+
"Reason: %s" % (str(e)))
|
350 |
+
|
351 |
+
style = property(_get_style, _set_style)
|
352 |
+
color = property(_get_color, _set_color)
|
353 |
+
|
354 |
+
calculating_verts = property(_get_calculating_verts)
|
355 |
+
calculating_verts_pos = property(_get_calculating_verts_pos)
|
356 |
+
calculating_verts_len = property(_get_calculating_verts_len)
|
357 |
+
|
358 |
+
calculating_cverts = property(_get_calculating_cverts)
|
359 |
+
calculating_cverts_pos = property(_get_calculating_cverts_pos)
|
360 |
+
calculating_cverts_len = property(_get_calculating_cverts_len)
|
361 |
+
|
362 |
+
## String representations
|
363 |
+
|
364 |
+
def __str__(self):
|
365 |
+
f = ", ".join(str(d) for d in self.d_vars)
|
366 |
+
o = "'mode=%s'" % (self.primary_alias)
|
367 |
+
return ", ".join([f, o])
|
368 |
+
|
369 |
+
def __repr__(self):
|
370 |
+
f = ", ".join(str(d) for d in self.d_vars)
|
371 |
+
i = ", ".join(str(i) for i in self.intervals)
|
372 |
+
d = [('mode', self.primary_alias),
|
373 |
+
('color', str(self.color)),
|
374 |
+
('style', str(self.style))]
|
375 |
+
|
376 |
+
o = "'%s'" % ("; ".join("%s=%s" % (k, v)
|
377 |
+
for k, v in d if v != 'None'))
|
378 |
+
return ", ".join([f, i, o])
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_modes.py
ADDED
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.utilities.lambdify import lambdify
|
2 |
+
from sympy.core.numbers import pi
|
3 |
+
from sympy.functions import sin, cos
|
4 |
+
from sympy.plotting.pygletplot.plot_curve import PlotCurve
|
5 |
+
from sympy.plotting.pygletplot.plot_surface import PlotSurface
|
6 |
+
|
7 |
+
from math import sin as p_sin
|
8 |
+
from math import cos as p_cos
|
9 |
+
|
10 |
+
|
11 |
+
def float_vec3(f):
|
12 |
+
def inner(*args):
|
13 |
+
v = f(*args)
|
14 |
+
return float(v[0]), float(v[1]), float(v[2])
|
15 |
+
return inner
|
16 |
+
|
17 |
+
|
18 |
+
class Cartesian2D(PlotCurve):
|
19 |
+
i_vars, d_vars = 'x', 'y'
|
20 |
+
intervals = [[-5, 5, 100]]
|
21 |
+
aliases = ['cartesian']
|
22 |
+
is_default = True
|
23 |
+
|
24 |
+
def _get_sympy_evaluator(self):
|
25 |
+
fy = self.d_vars[0]
|
26 |
+
x = self.t_interval.v
|
27 |
+
|
28 |
+
@float_vec3
|
29 |
+
def e(_x):
|
30 |
+
return (_x, fy.subs(x, _x), 0.0)
|
31 |
+
return e
|
32 |
+
|
33 |
+
def _get_lambda_evaluator(self):
|
34 |
+
fy = self.d_vars[0]
|
35 |
+
x = self.t_interval.v
|
36 |
+
return lambdify([x], [x, fy, 0.0])
|
37 |
+
|
38 |
+
|
39 |
+
class Cartesian3D(PlotSurface):
|
40 |
+
i_vars, d_vars = 'xy', 'z'
|
41 |
+
intervals = [[-1, 1, 40], [-1, 1, 40]]
|
42 |
+
aliases = ['cartesian', 'monge']
|
43 |
+
is_default = True
|
44 |
+
|
45 |
+
def _get_sympy_evaluator(self):
|
46 |
+
fz = self.d_vars[0]
|
47 |
+
x = self.u_interval.v
|
48 |
+
y = self.v_interval.v
|
49 |
+
|
50 |
+
@float_vec3
|
51 |
+
def e(_x, _y):
|
52 |
+
return (_x, _y, fz.subs(x, _x).subs(y, _y))
|
53 |
+
return e
|
54 |
+
|
55 |
+
def _get_lambda_evaluator(self):
|
56 |
+
fz = self.d_vars[0]
|
57 |
+
x = self.u_interval.v
|
58 |
+
y = self.v_interval.v
|
59 |
+
return lambdify([x, y], [x, y, fz])
|
60 |
+
|
61 |
+
|
62 |
+
class ParametricCurve2D(PlotCurve):
|
63 |
+
i_vars, d_vars = 't', 'xy'
|
64 |
+
intervals = [[0, 2*pi, 100]]
|
65 |
+
aliases = ['parametric']
|
66 |
+
is_default = True
|
67 |
+
|
68 |
+
def _get_sympy_evaluator(self):
|
69 |
+
fx, fy = self.d_vars
|
70 |
+
t = self.t_interval.v
|
71 |
+
|
72 |
+
@float_vec3
|
73 |
+
def e(_t):
|
74 |
+
return (fx.subs(t, _t), fy.subs(t, _t), 0.0)
|
75 |
+
return e
|
76 |
+
|
77 |
+
def _get_lambda_evaluator(self):
|
78 |
+
fx, fy = self.d_vars
|
79 |
+
t = self.t_interval.v
|
80 |
+
return lambdify([t], [fx, fy, 0.0])
|
81 |
+
|
82 |
+
|
83 |
+
class ParametricCurve3D(PlotCurve):
|
84 |
+
i_vars, d_vars = 't', 'xyz'
|
85 |
+
intervals = [[0, 2*pi, 100]]
|
86 |
+
aliases = ['parametric']
|
87 |
+
is_default = True
|
88 |
+
|
89 |
+
def _get_sympy_evaluator(self):
|
90 |
+
fx, fy, fz = self.d_vars
|
91 |
+
t = self.t_interval.v
|
92 |
+
|
93 |
+
@float_vec3
|
94 |
+
def e(_t):
|
95 |
+
return (fx.subs(t, _t), fy.subs(t, _t), fz.subs(t, _t))
|
96 |
+
return e
|
97 |
+
|
98 |
+
def _get_lambda_evaluator(self):
|
99 |
+
fx, fy, fz = self.d_vars
|
100 |
+
t = self.t_interval.v
|
101 |
+
return lambdify([t], [fx, fy, fz])
|
102 |
+
|
103 |
+
|
104 |
+
class ParametricSurface(PlotSurface):
|
105 |
+
i_vars, d_vars = 'uv', 'xyz'
|
106 |
+
intervals = [[-1, 1, 40], [-1, 1, 40]]
|
107 |
+
aliases = ['parametric']
|
108 |
+
is_default = True
|
109 |
+
|
110 |
+
def _get_sympy_evaluator(self):
|
111 |
+
fx, fy, fz = self.d_vars
|
112 |
+
u = self.u_interval.v
|
113 |
+
v = self.v_interval.v
|
114 |
+
|
115 |
+
@float_vec3
|
116 |
+
def e(_u, _v):
|
117 |
+
return (fx.subs(u, _u).subs(v, _v),
|
118 |
+
fy.subs(u, _u).subs(v, _v),
|
119 |
+
fz.subs(u, _u).subs(v, _v))
|
120 |
+
return e
|
121 |
+
|
122 |
+
def _get_lambda_evaluator(self):
|
123 |
+
fx, fy, fz = self.d_vars
|
124 |
+
u = self.u_interval.v
|
125 |
+
v = self.v_interval.v
|
126 |
+
return lambdify([u, v], [fx, fy, fz])
|
127 |
+
|
128 |
+
|
129 |
+
class Polar(PlotCurve):
|
130 |
+
i_vars, d_vars = 't', 'r'
|
131 |
+
intervals = [[0, 2*pi, 100]]
|
132 |
+
aliases = ['polar']
|
133 |
+
is_default = False
|
134 |
+
|
135 |
+
def _get_sympy_evaluator(self):
|
136 |
+
fr = self.d_vars[0]
|
137 |
+
t = self.t_interval.v
|
138 |
+
|
139 |
+
def e(_t):
|
140 |
+
_r = float(fr.subs(t, _t))
|
141 |
+
return (_r*p_cos(_t), _r*p_sin(_t), 0.0)
|
142 |
+
return e
|
143 |
+
|
144 |
+
def _get_lambda_evaluator(self):
|
145 |
+
fr = self.d_vars[0]
|
146 |
+
t = self.t_interval.v
|
147 |
+
fx, fy = fr*cos(t), fr*sin(t)
|
148 |
+
return lambdify([t], [fx, fy, 0.0])
|
149 |
+
|
150 |
+
|
151 |
+
class Cylindrical(PlotSurface):
|
152 |
+
i_vars, d_vars = 'th', 'r'
|
153 |
+
intervals = [[0, 2*pi, 40], [-1, 1, 20]]
|
154 |
+
aliases = ['cylindrical', 'polar']
|
155 |
+
is_default = False
|
156 |
+
|
157 |
+
def _get_sympy_evaluator(self):
|
158 |
+
fr = self.d_vars[0]
|
159 |
+
t = self.u_interval.v
|
160 |
+
h = self.v_interval.v
|
161 |
+
|
162 |
+
def e(_t, _h):
|
163 |
+
_r = float(fr.subs(t, _t).subs(h, _h))
|
164 |
+
return (_r*p_cos(_t), _r*p_sin(_t), _h)
|
165 |
+
return e
|
166 |
+
|
167 |
+
def _get_lambda_evaluator(self):
|
168 |
+
fr = self.d_vars[0]
|
169 |
+
t = self.u_interval.v
|
170 |
+
h = self.v_interval.v
|
171 |
+
fx, fy = fr*cos(t), fr*sin(t)
|
172 |
+
return lambdify([t, h], [fx, fy, h])
|
173 |
+
|
174 |
+
|
175 |
+
class Spherical(PlotSurface):
|
176 |
+
i_vars, d_vars = 'tp', 'r'
|
177 |
+
intervals = [[0, 2*pi, 40], [0, pi, 20]]
|
178 |
+
aliases = ['spherical']
|
179 |
+
is_default = False
|
180 |
+
|
181 |
+
def _get_sympy_evaluator(self):
|
182 |
+
fr = self.d_vars[0]
|
183 |
+
t = self.u_interval.v
|
184 |
+
p = self.v_interval.v
|
185 |
+
|
186 |
+
def e(_t, _p):
|
187 |
+
_r = float(fr.subs(t, _t).subs(p, _p))
|
188 |
+
return (_r*p_cos(_t)*p_sin(_p),
|
189 |
+
_r*p_sin(_t)*p_sin(_p),
|
190 |
+
_r*p_cos(_p))
|
191 |
+
return e
|
192 |
+
|
193 |
+
def _get_lambda_evaluator(self):
|
194 |
+
fr = self.d_vars[0]
|
195 |
+
t = self.u_interval.v
|
196 |
+
p = self.v_interval.v
|
197 |
+
fx = fr * cos(t) * sin(p)
|
198 |
+
fy = fr * sin(t) * sin(p)
|
199 |
+
fz = fr * cos(p)
|
200 |
+
return lambdify([t, p], [fx, fy, fz])
|
201 |
+
|
202 |
+
Cartesian2D._register()
|
203 |
+
Cartesian3D._register()
|
204 |
+
ParametricCurve2D._register()
|
205 |
+
ParametricCurve3D._register()
|
206 |
+
ParametricSurface._register()
|
207 |
+
Polar._register()
|
208 |
+
Cylindrical._register()
|
209 |
+
Spherical._register()
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_object.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
class PlotObject:
|
2 |
+
"""
|
3 |
+
Base class for objects which can be displayed in
|
4 |
+
a Plot.
|
5 |
+
"""
|
6 |
+
visible = True
|
7 |
+
|
8 |
+
def _draw(self):
|
9 |
+
if self.visible:
|
10 |
+
self.draw()
|
11 |
+
|
12 |
+
def draw(self):
|
13 |
+
"""
|
14 |
+
OpenGL rendering code for the plot object.
|
15 |
+
Override in base class.
|
16 |
+
"""
|
17 |
+
pass
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_rotation.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
try:
|
2 |
+
from ctypes import c_float
|
3 |
+
except ImportError:
|
4 |
+
pass
|
5 |
+
|
6 |
+
import pyglet.gl as pgl
|
7 |
+
from math import sqrt as _sqrt, acos as _acos
|
8 |
+
|
9 |
+
|
10 |
+
def cross(a, b):
|
11 |
+
return (a[1] * b[2] - a[2] * b[1],
|
12 |
+
a[2] * b[0] - a[0] * b[2],
|
13 |
+
a[0] * b[1] - a[1] * b[0])
|
14 |
+
|
15 |
+
|
16 |
+
def dot(a, b):
|
17 |
+
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
18 |
+
|
19 |
+
|
20 |
+
def mag(a):
|
21 |
+
return _sqrt(a[0]**2 + a[1]**2 + a[2]**2)
|
22 |
+
|
23 |
+
|
24 |
+
def norm(a):
|
25 |
+
m = mag(a)
|
26 |
+
return (a[0] / m, a[1] / m, a[2] / m)
|
27 |
+
|
28 |
+
|
29 |
+
def get_sphere_mapping(x, y, width, height):
|
30 |
+
x = min([max([x, 0]), width])
|
31 |
+
y = min([max([y, 0]), height])
|
32 |
+
|
33 |
+
sr = _sqrt((width/2)**2 + (height/2)**2)
|
34 |
+
sx = ((x - width / 2) / sr)
|
35 |
+
sy = ((y - height / 2) / sr)
|
36 |
+
|
37 |
+
sz = 1.0 - sx**2 - sy**2
|
38 |
+
|
39 |
+
if sz > 0.0:
|
40 |
+
sz = _sqrt(sz)
|
41 |
+
return (sx, sy, sz)
|
42 |
+
else:
|
43 |
+
sz = 0
|
44 |
+
return norm((sx, sy, sz))
|
45 |
+
|
46 |
+
rad2deg = 180.0 / 3.141592
|
47 |
+
|
48 |
+
|
49 |
+
def get_spherical_rotatation(p1, p2, width, height, theta_multiplier):
|
50 |
+
v1 = get_sphere_mapping(p1[0], p1[1], width, height)
|
51 |
+
v2 = get_sphere_mapping(p2[0], p2[1], width, height)
|
52 |
+
|
53 |
+
d = min(max([dot(v1, v2), -1]), 1)
|
54 |
+
|
55 |
+
if abs(d - 1.0) < 0.000001:
|
56 |
+
return None
|
57 |
+
|
58 |
+
raxis = norm( cross(v1, v2) )
|
59 |
+
rtheta = theta_multiplier * rad2deg * _acos(d)
|
60 |
+
|
61 |
+
pgl.glPushMatrix()
|
62 |
+
pgl.glLoadIdentity()
|
63 |
+
pgl.glRotatef(rtheta, *raxis)
|
64 |
+
mat = (c_float*16)()
|
65 |
+
pgl.glGetFloatv(pgl.GL_MODELVIEW_MATRIX, mat)
|
66 |
+
pgl.glPopMatrix()
|
67 |
+
|
68 |
+
return mat
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_surface.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pyglet.gl as pgl
|
2 |
+
|
3 |
+
from sympy.core import S
|
4 |
+
from sympy.plotting.pygletplot.plot_mode_base import PlotModeBase
|
5 |
+
|
6 |
+
|
7 |
+
class PlotSurface(PlotModeBase):
|
8 |
+
|
9 |
+
default_rot_preset = 'perspective'
|
10 |
+
|
11 |
+
def _on_calculate_verts(self):
|
12 |
+
self.u_interval = self.intervals[0]
|
13 |
+
self.u_set = list(self.u_interval.frange())
|
14 |
+
self.v_interval = self.intervals[1]
|
15 |
+
self.v_set = list(self.v_interval.frange())
|
16 |
+
self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
|
17 |
+
[S.Infinity, S.NegativeInfinity, 0],
|
18 |
+
[S.Infinity, S.NegativeInfinity, 0]]
|
19 |
+
evaluate = self._get_evaluator()
|
20 |
+
|
21 |
+
self._calculating_verts_pos = 0.0
|
22 |
+
self._calculating_verts_len = float(
|
23 |
+
self.u_interval.v_len*self.v_interval.v_len)
|
24 |
+
|
25 |
+
verts = []
|
26 |
+
b = self.bounds
|
27 |
+
for u in self.u_set:
|
28 |
+
column = []
|
29 |
+
for v in self.v_set:
|
30 |
+
try:
|
31 |
+
_e = evaluate(u, v) # calculate vertex
|
32 |
+
except ZeroDivisionError:
|
33 |
+
_e = None
|
34 |
+
if _e is not None: # update bounding box
|
35 |
+
for axis in range(3):
|
36 |
+
b[axis][0] = min([b[axis][0], _e[axis]])
|
37 |
+
b[axis][1] = max([b[axis][1], _e[axis]])
|
38 |
+
column.append(_e)
|
39 |
+
self._calculating_verts_pos += 1.0
|
40 |
+
|
41 |
+
verts.append(column)
|
42 |
+
for axis in range(3):
|
43 |
+
b[axis][2] = b[axis][1] - b[axis][0]
|
44 |
+
if b[axis][2] == 0.0:
|
45 |
+
b[axis][2] = 1.0
|
46 |
+
|
47 |
+
self.verts = verts
|
48 |
+
self.push_wireframe(self.draw_verts(False, False))
|
49 |
+
self.push_solid(self.draw_verts(False, True))
|
50 |
+
|
51 |
+
def _on_calculate_cverts(self):
|
52 |
+
if not self.verts or not self.color:
|
53 |
+
return
|
54 |
+
|
55 |
+
def set_work_len(n):
|
56 |
+
self._calculating_cverts_len = float(n)
|
57 |
+
|
58 |
+
def inc_work_pos():
|
59 |
+
self._calculating_cverts_pos += 1.0
|
60 |
+
set_work_len(1)
|
61 |
+
self._calculating_cverts_pos = 0
|
62 |
+
self.cverts = self.color.apply_to_surface(self.verts,
|
63 |
+
self.u_set,
|
64 |
+
self.v_set,
|
65 |
+
set_len=set_work_len,
|
66 |
+
inc_pos=inc_work_pos)
|
67 |
+
self.push_solid(self.draw_verts(True, True))
|
68 |
+
|
69 |
+
def calculate_one_cvert(self, u, v):
|
70 |
+
vert = self.verts[u][v]
|
71 |
+
return self.color(vert[0], vert[1], vert[2],
|
72 |
+
self.u_set[u], self.v_set[v])
|
73 |
+
|
74 |
+
def draw_verts(self, use_cverts, use_solid_color):
|
75 |
+
def f():
|
76 |
+
for u in range(1, len(self.u_set)):
|
77 |
+
pgl.glBegin(pgl.GL_QUAD_STRIP)
|
78 |
+
for v in range(len(self.v_set)):
|
79 |
+
pa = self.verts[u - 1][v]
|
80 |
+
pb = self.verts[u][v]
|
81 |
+
if pa is None or pb is None:
|
82 |
+
pgl.glEnd()
|
83 |
+
pgl.glBegin(pgl.GL_QUAD_STRIP)
|
84 |
+
continue
|
85 |
+
if use_cverts:
|
86 |
+
ca = self.cverts[u - 1][v]
|
87 |
+
cb = self.cverts[u][v]
|
88 |
+
if ca is None:
|
89 |
+
ca = (0, 0, 0)
|
90 |
+
if cb is None:
|
91 |
+
cb = (0, 0, 0)
|
92 |
+
else:
|
93 |
+
if use_solid_color:
|
94 |
+
ca = cb = self.default_solid_color
|
95 |
+
else:
|
96 |
+
ca = cb = self.default_wireframe_color
|
97 |
+
pgl.glColor3f(*ca)
|
98 |
+
pgl.glVertex3f(*pa)
|
99 |
+
pgl.glColor3f(*cb)
|
100 |
+
pgl.glVertex3f(*pb)
|
101 |
+
pgl.glEnd()
|
102 |
+
return f
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_window.py
ADDED
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from time import perf_counter
|
2 |
+
|
3 |
+
|
4 |
+
import pyglet.gl as pgl
|
5 |
+
|
6 |
+
from sympy.plotting.pygletplot.managed_window import ManagedWindow
|
7 |
+
from sympy.plotting.pygletplot.plot_camera import PlotCamera
|
8 |
+
from sympy.plotting.pygletplot.plot_controller import PlotController
|
9 |
+
|
10 |
+
|
11 |
+
class PlotWindow(ManagedWindow):
|
12 |
+
|
13 |
+
def __init__(self, plot, antialiasing=True, ortho=False,
|
14 |
+
invert_mouse_zoom=False, linewidth=1.5, caption="SymPy Plot",
|
15 |
+
**kwargs):
|
16 |
+
"""
|
17 |
+
Named Arguments
|
18 |
+
===============
|
19 |
+
|
20 |
+
antialiasing = True
|
21 |
+
True OR False
|
22 |
+
ortho = False
|
23 |
+
True OR False
|
24 |
+
invert_mouse_zoom = False
|
25 |
+
True OR False
|
26 |
+
"""
|
27 |
+
self.plot = plot
|
28 |
+
|
29 |
+
self.camera = None
|
30 |
+
self._calculating = False
|
31 |
+
|
32 |
+
self.antialiasing = antialiasing
|
33 |
+
self.ortho = ortho
|
34 |
+
self.invert_mouse_zoom = invert_mouse_zoom
|
35 |
+
self.linewidth = linewidth
|
36 |
+
self.title = caption
|
37 |
+
self.last_caption_update = 0
|
38 |
+
self.caption_update_interval = 0.2
|
39 |
+
self.drawing_first_object = True
|
40 |
+
|
41 |
+
super().__init__(**kwargs)
|
42 |
+
|
43 |
+
def setup(self):
|
44 |
+
self.camera = PlotCamera(self, ortho=self.ortho)
|
45 |
+
self.controller = PlotController(self,
|
46 |
+
invert_mouse_zoom=self.invert_mouse_zoom)
|
47 |
+
self.push_handlers(self.controller)
|
48 |
+
|
49 |
+
pgl.glClearColor(1.0, 1.0, 1.0, 0.0)
|
50 |
+
pgl.glClearDepth(1.0)
|
51 |
+
|
52 |
+
pgl.glDepthFunc(pgl.GL_LESS)
|
53 |
+
pgl.glEnable(pgl.GL_DEPTH_TEST)
|
54 |
+
|
55 |
+
pgl.glEnable(pgl.GL_LINE_SMOOTH)
|
56 |
+
pgl.glShadeModel(pgl.GL_SMOOTH)
|
57 |
+
pgl.glLineWidth(self.linewidth)
|
58 |
+
|
59 |
+
pgl.glEnable(pgl.GL_BLEND)
|
60 |
+
pgl.glBlendFunc(pgl.GL_SRC_ALPHA, pgl.GL_ONE_MINUS_SRC_ALPHA)
|
61 |
+
|
62 |
+
if self.antialiasing:
|
63 |
+
pgl.glHint(pgl.GL_LINE_SMOOTH_HINT, pgl.GL_NICEST)
|
64 |
+
pgl.glHint(pgl.GL_POLYGON_SMOOTH_HINT, pgl.GL_NICEST)
|
65 |
+
|
66 |
+
self.camera.setup_projection()
|
67 |
+
|
68 |
+
def on_resize(self, w, h):
|
69 |
+
super().on_resize(w, h)
|
70 |
+
if self.camera is not None:
|
71 |
+
self.camera.setup_projection()
|
72 |
+
|
73 |
+
def update(self, dt):
|
74 |
+
self.controller.update(dt)
|
75 |
+
|
76 |
+
def draw(self):
|
77 |
+
self.plot._render_lock.acquire()
|
78 |
+
self.camera.apply_transformation()
|
79 |
+
|
80 |
+
calc_verts_pos, calc_verts_len = 0, 0
|
81 |
+
calc_cverts_pos, calc_cverts_len = 0, 0
|
82 |
+
|
83 |
+
should_update_caption = (perf_counter() - self.last_caption_update >
|
84 |
+
self.caption_update_interval)
|
85 |
+
|
86 |
+
if len(self.plot._functions.values()) == 0:
|
87 |
+
self.drawing_first_object = True
|
88 |
+
|
89 |
+
iterfunctions = iter(self.plot._functions.values())
|
90 |
+
|
91 |
+
for r in iterfunctions:
|
92 |
+
if self.drawing_first_object:
|
93 |
+
self.camera.set_rot_preset(r.default_rot_preset)
|
94 |
+
self.drawing_first_object = False
|
95 |
+
|
96 |
+
pgl.glPushMatrix()
|
97 |
+
r._draw()
|
98 |
+
pgl.glPopMatrix()
|
99 |
+
|
100 |
+
# might as well do this while we are
|
101 |
+
# iterating and have the lock rather
|
102 |
+
# than locking and iterating twice
|
103 |
+
# per frame:
|
104 |
+
|
105 |
+
if should_update_caption:
|
106 |
+
try:
|
107 |
+
if r.calculating_verts:
|
108 |
+
calc_verts_pos += r.calculating_verts_pos
|
109 |
+
calc_verts_len += r.calculating_verts_len
|
110 |
+
if r.calculating_cverts:
|
111 |
+
calc_cverts_pos += r.calculating_cverts_pos
|
112 |
+
calc_cverts_len += r.calculating_cverts_len
|
113 |
+
except ValueError:
|
114 |
+
pass
|
115 |
+
|
116 |
+
for r in self.plot._pobjects:
|
117 |
+
pgl.glPushMatrix()
|
118 |
+
r._draw()
|
119 |
+
pgl.glPopMatrix()
|
120 |
+
|
121 |
+
if should_update_caption:
|
122 |
+
self.update_caption(calc_verts_pos, calc_verts_len,
|
123 |
+
calc_cverts_pos, calc_cverts_len)
|
124 |
+
self.last_caption_update = perf_counter()
|
125 |
+
|
126 |
+
if self.plot._screenshot:
|
127 |
+
self.plot._screenshot._execute_saving()
|
128 |
+
|
129 |
+
self.plot._render_lock.release()
|
130 |
+
|
131 |
+
def update_caption(self, calc_verts_pos, calc_verts_len,
|
132 |
+
calc_cverts_pos, calc_cverts_len):
|
133 |
+
caption = self.title
|
134 |
+
if calc_verts_len or calc_cverts_len:
|
135 |
+
caption += " (calculating"
|
136 |
+
if calc_verts_len > 0:
|
137 |
+
p = (calc_verts_pos / calc_verts_len) * 100
|
138 |
+
caption += " vertices %i%%" % (p)
|
139 |
+
if calc_cverts_len > 0:
|
140 |
+
p = (calc_cverts_pos / calc_cverts_len) * 100
|
141 |
+
caption += " colors %i%%" % (p)
|
142 |
+
caption += ")"
|
143 |
+
if self.caption != caption:
|
144 |
+
self.set_caption(caption)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__init__.py
ADDED
File without changes
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (193 Bytes). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__pycache__/test_plotting.cpython-310.pyc
ADDED
Binary file (3.2 kB). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/test_plotting.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.external.importtools import import_module
|
2 |
+
|
3 |
+
disabled = False
|
4 |
+
|
5 |
+
# if pyglet.gl fails to import, e.g. opengl is missing, we disable the tests
|
6 |
+
pyglet_gl = import_module("pyglet.gl", catch=(OSError,))
|
7 |
+
pyglet_window = import_module("pyglet.window", catch=(OSError,))
|
8 |
+
if not pyglet_gl or not pyglet_window:
|
9 |
+
disabled = True
|
10 |
+
|
11 |
+
|
12 |
+
from sympy.core.symbol import symbols
|
13 |
+
from sympy.functions.elementary.exponential import log
|
14 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
15 |
+
x, y, z = symbols('x, y, z')
|
16 |
+
|
17 |
+
|
18 |
+
def test_plot_2d():
|
19 |
+
from sympy.plotting.pygletplot import PygletPlot
|
20 |
+
p = PygletPlot(x, [x, -5, 5, 4], visible=False)
|
21 |
+
p.wait_for_calculations()
|
22 |
+
|
23 |
+
|
24 |
+
def test_plot_2d_discontinuous():
|
25 |
+
from sympy.plotting.pygletplot import PygletPlot
|
26 |
+
p = PygletPlot(1/x, [x, -1, 1, 2], visible=False)
|
27 |
+
p.wait_for_calculations()
|
28 |
+
|
29 |
+
|
30 |
+
def test_plot_3d():
|
31 |
+
from sympy.plotting.pygletplot import PygletPlot
|
32 |
+
p = PygletPlot(x*y, [x, -5, 5, 5], [y, -5, 5, 5], visible=False)
|
33 |
+
p.wait_for_calculations()
|
34 |
+
|
35 |
+
|
36 |
+
def test_plot_3d_discontinuous():
|
37 |
+
from sympy.plotting.pygletplot import PygletPlot
|
38 |
+
p = PygletPlot(1/x, [x, -3, 3, 6], [y, -1, 1, 1], visible=False)
|
39 |
+
p.wait_for_calculations()
|
40 |
+
|
41 |
+
|
42 |
+
def test_plot_2d_polar():
|
43 |
+
from sympy.plotting.pygletplot import PygletPlot
|
44 |
+
p = PygletPlot(1/x, [x, -1, 1, 4], 'mode=polar', visible=False)
|
45 |
+
p.wait_for_calculations()
|
46 |
+
|
47 |
+
|
48 |
+
def test_plot_3d_cylinder():
|
49 |
+
from sympy.plotting.pygletplot import PygletPlot
|
50 |
+
p = PygletPlot(
|
51 |
+
1/y, [x, 0, 6.282, 4], [y, -1, 1, 4], 'mode=polar;style=solid',
|
52 |
+
visible=False)
|
53 |
+
p.wait_for_calculations()
|
54 |
+
|
55 |
+
|
56 |
+
def test_plot_3d_spherical():
|
57 |
+
from sympy.plotting.pygletplot import PygletPlot
|
58 |
+
p = PygletPlot(
|
59 |
+
1, [x, 0, 6.282, 4], [y, 0, 3.141,
|
60 |
+
4], 'mode=spherical;style=wireframe',
|
61 |
+
visible=False)
|
62 |
+
p.wait_for_calculations()
|
63 |
+
|
64 |
+
|
65 |
+
def test_plot_2d_parametric():
|
66 |
+
from sympy.plotting.pygletplot import PygletPlot
|
67 |
+
p = PygletPlot(sin(x), cos(x), [x, 0, 6.282, 4], visible=False)
|
68 |
+
p.wait_for_calculations()
|
69 |
+
|
70 |
+
|
71 |
+
def test_plot_3d_parametric():
|
72 |
+
from sympy.plotting.pygletplot import PygletPlot
|
73 |
+
p = PygletPlot(sin(x), cos(x), x/5.0, [x, 0, 6.282, 4], visible=False)
|
74 |
+
p.wait_for_calculations()
|
75 |
+
|
76 |
+
|
77 |
+
def _test_plot_log():
|
78 |
+
from sympy.plotting.pygletplot import PygletPlot
|
79 |
+
p = PygletPlot(log(x), [x, 0, 6.282, 4], 'mode=polar', visible=False)
|
80 |
+
p.wait_for_calculations()
|
81 |
+
|
82 |
+
|
83 |
+
def test_plot_integral():
|
84 |
+
# Make sure it doesn't treat x as an independent variable
|
85 |
+
from sympy.plotting.pygletplot import PygletPlot
|
86 |
+
from sympy.integrals.integrals import Integral
|
87 |
+
p = PygletPlot(Integral(z*x, (x, 1, z), (z, 1, y)), visible=False)
|
88 |
+
p.wait_for_calculations()
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/pygletplot/util.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
try:
|
2 |
+
from ctypes import c_float, c_int, c_double
|
3 |
+
except ImportError:
|
4 |
+
pass
|
5 |
+
|
6 |
+
import pyglet.gl as pgl
|
7 |
+
from sympy.core import S
|
8 |
+
|
9 |
+
|
10 |
+
def get_model_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv):
|
11 |
+
"""
|
12 |
+
Returns the current modelview matrix.
|
13 |
+
"""
|
14 |
+
m = (array_type*16)()
|
15 |
+
glGetMethod(pgl.GL_MODELVIEW_MATRIX, m)
|
16 |
+
return m
|
17 |
+
|
18 |
+
|
19 |
+
def get_projection_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv):
|
20 |
+
"""
|
21 |
+
Returns the current modelview matrix.
|
22 |
+
"""
|
23 |
+
m = (array_type*16)()
|
24 |
+
glGetMethod(pgl.GL_PROJECTION_MATRIX, m)
|
25 |
+
return m
|
26 |
+
|
27 |
+
|
28 |
+
def get_viewport():
|
29 |
+
"""
|
30 |
+
Returns the current viewport.
|
31 |
+
"""
|
32 |
+
m = (c_int*4)()
|
33 |
+
pgl.glGetIntegerv(pgl.GL_VIEWPORT, m)
|
34 |
+
return m
|
35 |
+
|
36 |
+
|
37 |
+
def get_direction_vectors():
|
38 |
+
m = get_model_matrix()
|
39 |
+
return ((m[0], m[4], m[8]),
|
40 |
+
(m[1], m[5], m[9]),
|
41 |
+
(m[2], m[6], m[10]))
|
42 |
+
|
43 |
+
|
44 |
+
def get_view_direction_vectors():
|
45 |
+
m = get_model_matrix()
|
46 |
+
return ((m[0], m[1], m[2]),
|
47 |
+
(m[4], m[5], m[6]),
|
48 |
+
(m[8], m[9], m[10]))
|
49 |
+
|
50 |
+
|
51 |
+
def get_basis_vectors():
|
52 |
+
return ((1, 0, 0), (0, 1, 0), (0, 0, 1))
|
53 |
+
|
54 |
+
|
55 |
+
def screen_to_model(x, y, z):
|
56 |
+
m = get_model_matrix(c_double, pgl.glGetDoublev)
|
57 |
+
p = get_projection_matrix(c_double, pgl.glGetDoublev)
|
58 |
+
w = get_viewport()
|
59 |
+
mx, my, mz = c_double(), c_double(), c_double()
|
60 |
+
pgl.gluUnProject(x, y, z, m, p, w, mx, my, mz)
|
61 |
+
return float(mx.value), float(my.value), float(mz.value)
|
62 |
+
|
63 |
+
|
64 |
+
def model_to_screen(x, y, z):
|
65 |
+
m = get_model_matrix(c_double, pgl.glGetDoublev)
|
66 |
+
p = get_projection_matrix(c_double, pgl.glGetDoublev)
|
67 |
+
w = get_viewport()
|
68 |
+
mx, my, mz = c_double(), c_double(), c_double()
|
69 |
+
pgl.gluProject(x, y, z, m, p, w, mx, my, mz)
|
70 |
+
return float(mx.value), float(my.value), float(mz.value)
|
71 |
+
|
72 |
+
|
73 |
+
def vec_subs(a, b):
|
74 |
+
return tuple(a[i] - b[i] for i in range(len(a)))
|
75 |
+
|
76 |
+
|
77 |
+
def billboard_matrix():
|
78 |
+
"""
|
79 |
+
Removes rotational components of
|
80 |
+
current matrix so that primitives
|
81 |
+
are always drawn facing the viewer.
|
82 |
+
|
83 |
+
|1|0|0|x|
|
84 |
+
|0|1|0|x|
|
85 |
+
|0|0|1|x| (x means left unchanged)
|
86 |
+
|x|x|x|x|
|
87 |
+
"""
|
88 |
+
m = get_model_matrix()
|
89 |
+
# XXX: for i in range(11): m[i] = i ?
|
90 |
+
m[0] = 1
|
91 |
+
m[1] = 0
|
92 |
+
m[2] = 0
|
93 |
+
m[4] = 0
|
94 |
+
m[5] = 1
|
95 |
+
m[6] = 0
|
96 |
+
m[8] = 0
|
97 |
+
m[9] = 0
|
98 |
+
m[10] = 1
|
99 |
+
pgl.glLoadMatrixf(m)
|
100 |
+
|
101 |
+
|
102 |
+
def create_bounds():
|
103 |
+
return [[S.Infinity, S.NegativeInfinity, 0],
|
104 |
+
[S.Infinity, S.NegativeInfinity, 0],
|
105 |
+
[S.Infinity, S.NegativeInfinity, 0]]
|
106 |
+
|
107 |
+
|
108 |
+
def update_bounds(b, v):
|
109 |
+
if v is None:
|
110 |
+
return
|
111 |
+
for axis in range(3):
|
112 |
+
b[axis][0] = min([b[axis][0], v[axis]])
|
113 |
+
b[axis][1] = max([b[axis][1], v[axis]])
|
114 |
+
|
115 |
+
|
116 |
+
def interpolate(a_min, a_max, a_ratio):
|
117 |
+
return a_min + a_ratio * (a_max - a_min)
|
118 |
+
|
119 |
+
|
120 |
+
def rinterpolate(a_min, a_max, a_value):
|
121 |
+
a_range = a_max - a_min
|
122 |
+
if a_max == a_min:
|
123 |
+
a_range = 1.0
|
124 |
+
return (a_value - a_min) / float(a_range)
|
125 |
+
|
126 |
+
|
127 |
+
def interpolate_color(color1, color2, ratio):
|
128 |
+
return tuple(interpolate(color1[i], color2[i], ratio) for i in range(3))
|
129 |
+
|
130 |
+
|
131 |
+
def scale_value(v, v_min, v_len):
|
132 |
+
return (v - v_min) / v_len
|
133 |
+
|
134 |
+
|
135 |
+
def scale_value_list(flist):
|
136 |
+
v_min, v_max = min(flist), max(flist)
|
137 |
+
v_len = v_max - v_min
|
138 |
+
return [scale_value(f, v_min, v_len) for f in flist]
|
139 |
+
|
140 |
+
|
141 |
+
def strided_range(r_min, r_max, stride, max_steps=50):
|
142 |
+
o_min, o_max = r_min, r_max
|
143 |
+
if abs(r_min - r_max) < 0.001:
|
144 |
+
return []
|
145 |
+
try:
|
146 |
+
range(int(r_min - r_max))
|
147 |
+
except (TypeError, OverflowError):
|
148 |
+
return []
|
149 |
+
if r_min > r_max:
|
150 |
+
raise ValueError("r_min cannot be greater than r_max")
|
151 |
+
r_min_s = (r_min % stride)
|
152 |
+
r_max_s = stride - (r_max % stride)
|
153 |
+
if abs(r_max_s - stride) < 0.001:
|
154 |
+
r_max_s = 0.0
|
155 |
+
r_min -= r_min_s
|
156 |
+
r_max += r_max_s
|
157 |
+
r_steps = int((r_max - r_min)/stride)
|
158 |
+
if max_steps and r_steps > max_steps:
|
159 |
+
return strided_range(o_min, o_max, stride*2)
|
160 |
+
return [r_min] + [r_min + e*stride for e in range(1, r_steps + 1)] + [r_max]
|
161 |
+
|
162 |
+
|
163 |
+
def parse_option_string(s):
|
164 |
+
if not isinstance(s, str):
|
165 |
+
return None
|
166 |
+
options = {}
|
167 |
+
for token in s.split(';'):
|
168 |
+
pieces = token.split('=')
|
169 |
+
if len(pieces) == 1:
|
170 |
+
option, value = pieces[0], ""
|
171 |
+
elif len(pieces) == 2:
|
172 |
+
option, value = pieces
|
173 |
+
else:
|
174 |
+
raise ValueError("Plot option string '%s' is malformed." % (s))
|
175 |
+
options[option.strip()] = value.strip()
|
176 |
+
return options
|
177 |
+
|
178 |
+
|
179 |
+
def dot_product(v1, v2):
|
180 |
+
return sum(v1[i]*v2[i] for i in range(3))
|
181 |
+
|
182 |
+
|
183 |
+
def vec_sub(v1, v2):
|
184 |
+
return tuple(v1[i] - v2[i] for i in range(3))
|
185 |
+
|
186 |
+
|
187 |
+
def vec_mag(v):
|
188 |
+
return sum(v[i]**2 for i in range(3))**(0.5)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/series.py
ADDED
@@ -0,0 +1,2591 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### The base class for all series
|
2 |
+
from collections.abc import Callable
|
3 |
+
from sympy.calculus.util import continuous_domain
|
4 |
+
from sympy.concrete import Sum, Product
|
5 |
+
from sympy.core.containers import Tuple
|
6 |
+
from sympy.core.expr import Expr
|
7 |
+
from sympy.core.function import arity
|
8 |
+
from sympy.core.sorting import default_sort_key
|
9 |
+
from sympy.core.symbol import Symbol
|
10 |
+
from sympy.functions import atan2, zeta, frac, ceiling, floor, im
|
11 |
+
from sympy.core.relational import (Equality, GreaterThan,
|
12 |
+
LessThan, Relational, Ne)
|
13 |
+
from sympy.core.sympify import sympify
|
14 |
+
from sympy.external import import_module
|
15 |
+
from sympy.logic.boolalg import BooleanFunction
|
16 |
+
from sympy.plotting.utils import _get_free_symbols, extract_solution
|
17 |
+
from sympy.printing.latex import latex
|
18 |
+
from sympy.printing.pycode import PythonCodePrinter
|
19 |
+
from sympy.printing.precedence import precedence
|
20 |
+
from sympy.sets.sets import Set, Interval, Union
|
21 |
+
from sympy.simplify.simplify import nsimplify
|
22 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
23 |
+
from sympy.utilities.lambdify import lambdify
|
24 |
+
from .intervalmath import interval
|
25 |
+
import warnings
|
26 |
+
|
27 |
+
|
28 |
+
class IntervalMathPrinter(PythonCodePrinter):
|
29 |
+
"""A printer to be used inside `plot_implicit` when `adaptive=True`,
|
30 |
+
in which case the interval arithmetic module is going to be used, which
|
31 |
+
requires the following edits.
|
32 |
+
"""
|
33 |
+
def _print_And(self, expr):
|
34 |
+
PREC = precedence(expr)
|
35 |
+
return " & ".join(self.parenthesize(a, PREC)
|
36 |
+
for a in sorted(expr.args, key=default_sort_key))
|
37 |
+
|
38 |
+
def _print_Or(self, expr):
|
39 |
+
PREC = precedence(expr)
|
40 |
+
return " | ".join(self.parenthesize(a, PREC)
|
41 |
+
for a in sorted(expr.args, key=default_sort_key))
|
42 |
+
|
43 |
+
|
44 |
+
def _uniform_eval(f1, f2, *args, modules=None,
|
45 |
+
force_real_eval=False, has_sum=False):
|
46 |
+
"""
|
47 |
+
Note: this is an experimental function, as such it is prone to changes.
|
48 |
+
Please, do not use it in your code.
|
49 |
+
"""
|
50 |
+
np = import_module('numpy')
|
51 |
+
|
52 |
+
def wrapper_func(func, *args):
|
53 |
+
try:
|
54 |
+
return complex(func(*args))
|
55 |
+
except (ZeroDivisionError, OverflowError):
|
56 |
+
return complex(np.nan, np.nan)
|
57 |
+
|
58 |
+
# NOTE: np.vectorize is much slower than numpy vectorized operations.
|
59 |
+
# However, this modules must be able to evaluate functions also with
|
60 |
+
# mpmath or sympy.
|
61 |
+
wrapper_func = np.vectorize(wrapper_func, otypes=[complex])
|
62 |
+
|
63 |
+
def _eval_with_sympy(err=None):
|
64 |
+
if f2 is None:
|
65 |
+
msg = "Impossible to evaluate the provided numerical function"
|
66 |
+
if err is None:
|
67 |
+
msg += "."
|
68 |
+
else:
|
69 |
+
msg += "because the following exception was raised:\n"
|
70 |
+
"{}: {}".format(type(err).__name__, err)
|
71 |
+
raise RuntimeError(msg)
|
72 |
+
if err:
|
73 |
+
warnings.warn(
|
74 |
+
"The evaluation with %s failed.\n" % (
|
75 |
+
"NumPy/SciPy" if not modules else modules) +
|
76 |
+
"{}: {}\n".format(type(err).__name__, err) +
|
77 |
+
"Trying to evaluate the expression with Sympy, but it might "
|
78 |
+
"be a slow operation."
|
79 |
+
)
|
80 |
+
return wrapper_func(f2, *args)
|
81 |
+
|
82 |
+
if modules == "sympy":
|
83 |
+
return _eval_with_sympy()
|
84 |
+
|
85 |
+
try:
|
86 |
+
return wrapper_func(f1, *args)
|
87 |
+
except Exception as err:
|
88 |
+
return _eval_with_sympy(err)
|
89 |
+
|
90 |
+
|
91 |
+
def _adaptive_eval(f, x):
|
92 |
+
"""Evaluate f(x) with an adaptive algorithm. Post-process the result.
|
93 |
+
If a symbolic expression is evaluated with SymPy, it might returns
|
94 |
+
another symbolic expression, containing additions, ...
|
95 |
+
Force evaluation to a float.
|
96 |
+
|
97 |
+
Parameters
|
98 |
+
==========
|
99 |
+
f : callable
|
100 |
+
x : float
|
101 |
+
"""
|
102 |
+
np = import_module('numpy')
|
103 |
+
|
104 |
+
y = f(x)
|
105 |
+
if isinstance(y, Expr) and (not y.is_Number):
|
106 |
+
y = y.evalf()
|
107 |
+
y = complex(y)
|
108 |
+
if y.imag > 1e-08:
|
109 |
+
return np.nan
|
110 |
+
return y.real
|
111 |
+
|
112 |
+
|
113 |
+
def _get_wrapper_for_expr(ret):
|
114 |
+
wrapper = "%s"
|
115 |
+
if ret == "real":
|
116 |
+
wrapper = "re(%s)"
|
117 |
+
elif ret == "imag":
|
118 |
+
wrapper = "im(%s)"
|
119 |
+
elif ret == "abs":
|
120 |
+
wrapper = "abs(%s)"
|
121 |
+
elif ret == "arg":
|
122 |
+
wrapper = "arg(%s)"
|
123 |
+
return wrapper
|
124 |
+
|
125 |
+
|
126 |
+
class BaseSeries:
|
127 |
+
"""Base class for the data objects containing stuff to be plotted.
|
128 |
+
|
129 |
+
Notes
|
130 |
+
=====
|
131 |
+
|
132 |
+
The backend should check if it supports the data series that is given.
|
133 |
+
(e.g. TextBackend supports only LineOver1DRangeSeries).
|
134 |
+
It is the backend responsibility to know how to use the class of
|
135 |
+
data series that is given.
|
136 |
+
|
137 |
+
Some data series classes are grouped (using a class attribute like is_2Dline)
|
138 |
+
according to the api they present (based only on convention). The backend is
|
139 |
+
not obliged to use that api (e.g. LineOver1DRangeSeries belongs to the
|
140 |
+
is_2Dline group and presents the get_points method, but the
|
141 |
+
TextBackend does not use the get_points method).
|
142 |
+
|
143 |
+
BaseSeries
|
144 |
+
"""
|
145 |
+
|
146 |
+
# Some flags follow. The rationale for using flags instead of checking base
|
147 |
+
# classes is that setting multiple flags is simpler than multiple
|
148 |
+
# inheritance.
|
149 |
+
|
150 |
+
is_2Dline = False
|
151 |
+
# Some of the backends expect:
|
152 |
+
# - get_points returning 1D np.arrays list_x, list_y
|
153 |
+
# - get_color_array returning 1D np.array (done in Line2DBaseSeries)
|
154 |
+
# with the colors calculated at the points from get_points
|
155 |
+
|
156 |
+
is_3Dline = False
|
157 |
+
# Some of the backends expect:
|
158 |
+
# - get_points returning 1D np.arrays list_x, list_y, list_y
|
159 |
+
# - get_color_array returning 1D np.array (done in Line2DBaseSeries)
|
160 |
+
# with the colors calculated at the points from get_points
|
161 |
+
|
162 |
+
is_3Dsurface = False
|
163 |
+
# Some of the backends expect:
|
164 |
+
# - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
|
165 |
+
# - get_points an alias for get_meshes
|
166 |
+
|
167 |
+
is_contour = False
|
168 |
+
# Some of the backends expect:
|
169 |
+
# - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
|
170 |
+
# - get_points an alias for get_meshes
|
171 |
+
|
172 |
+
is_implicit = False
|
173 |
+
# Some of the backends expect:
|
174 |
+
# - get_meshes returning mesh_x (1D array), mesh_y(1D array,
|
175 |
+
# mesh_z (2D np.arrays)
|
176 |
+
# - get_points an alias for get_meshes
|
177 |
+
# Different from is_contour as the colormap in backend will be
|
178 |
+
# different
|
179 |
+
|
180 |
+
is_interactive = False
|
181 |
+
# An interactive series can update its data.
|
182 |
+
|
183 |
+
is_parametric = False
|
184 |
+
# The calculation of aesthetics expects:
|
185 |
+
# - get_parameter_points returning one or two np.arrays (1D or 2D)
|
186 |
+
# used for calculation aesthetics
|
187 |
+
|
188 |
+
is_generic = False
|
189 |
+
# Represent generic user-provided numerical data
|
190 |
+
|
191 |
+
is_vector = False
|
192 |
+
is_2Dvector = False
|
193 |
+
is_3Dvector = False
|
194 |
+
# Represents a 2D or 3D vector data series
|
195 |
+
|
196 |
+
_N = 100
|
197 |
+
# default number of discretization points for uniform sampling. Each
|
198 |
+
# subclass can set its number.
|
199 |
+
|
200 |
+
def __init__(self, *args, **kwargs):
|
201 |
+
kwargs = _set_discretization_points(kwargs.copy(), type(self))
|
202 |
+
# discretize the domain using only integer numbers
|
203 |
+
self.only_integers = kwargs.get("only_integers", False)
|
204 |
+
# represents the evaluation modules to be used by lambdify
|
205 |
+
self.modules = kwargs.get("modules", None)
|
206 |
+
# plot functions might create data series that might not be useful to
|
207 |
+
# be shown on the legend, for example wireframe lines on 3D plots.
|
208 |
+
self.show_in_legend = kwargs.get("show_in_legend", True)
|
209 |
+
# line and surface series can show data with a colormap, hence a
|
210 |
+
# colorbar is essential to understand the data. However, sometime it
|
211 |
+
# is useful to hide it on series-by-series base. The following keyword
|
212 |
+
# controls wheter the series should show a colorbar or not.
|
213 |
+
self.colorbar = kwargs.get("colorbar", True)
|
214 |
+
# Some series might use a colormap as default coloring. Setting this
|
215 |
+
# attribute to False will inform the backends to use solid color.
|
216 |
+
self.use_cm = kwargs.get("use_cm", False)
|
217 |
+
# If True, the backend will attempt to render it on a polar-projection
|
218 |
+
# axis, or using a polar discretization if a 3D plot is requested
|
219 |
+
self.is_polar = kwargs.get("is_polar", kwargs.get("polar", False))
|
220 |
+
# If True, the rendering will use points, not lines.
|
221 |
+
self.is_point = kwargs.get("is_point", kwargs.get("point", False))
|
222 |
+
# some backend is able to render latex, other needs standard text
|
223 |
+
self._label = self._latex_label = ""
|
224 |
+
|
225 |
+
self._ranges = []
|
226 |
+
self._n = [
|
227 |
+
int(kwargs.get("n1", self._N)),
|
228 |
+
int(kwargs.get("n2", self._N)),
|
229 |
+
int(kwargs.get("n3", self._N))
|
230 |
+
]
|
231 |
+
self._scales = [
|
232 |
+
kwargs.get("xscale", "linear"),
|
233 |
+
kwargs.get("yscale", "linear"),
|
234 |
+
kwargs.get("zscale", "linear")
|
235 |
+
]
|
236 |
+
|
237 |
+
# enable interactive widget plots
|
238 |
+
self._params = kwargs.get("params", {})
|
239 |
+
if not isinstance(self._params, dict):
|
240 |
+
raise TypeError("`params` must be a dictionary mapping symbols "
|
241 |
+
"to numeric values.")
|
242 |
+
if len(self._params) > 0:
|
243 |
+
self.is_interactive = True
|
244 |
+
|
245 |
+
# contains keyword arguments that will be passed to the rendering
|
246 |
+
# function of the chosen plotting library
|
247 |
+
self.rendering_kw = kwargs.get("rendering_kw", {})
|
248 |
+
|
249 |
+
# numerical transformation functions to be applied to the output data:
|
250 |
+
# x, y, z (coordinates), p (parameter on parametric plots)
|
251 |
+
self._tx = kwargs.get("tx", None)
|
252 |
+
self._ty = kwargs.get("ty", None)
|
253 |
+
self._tz = kwargs.get("tz", None)
|
254 |
+
self._tp = kwargs.get("tp", None)
|
255 |
+
if not all(callable(t) or (t is None) for t in
|
256 |
+
[self._tx, self._ty, self._tz, self._tp]):
|
257 |
+
raise TypeError("`tx`, `ty`, `tz`, `tp` must be functions.")
|
258 |
+
|
259 |
+
# list of numerical functions representing the expressions to evaluate
|
260 |
+
self._functions = []
|
261 |
+
# signature for the numerical functions
|
262 |
+
self._signature = []
|
263 |
+
# some expressions don't like to be evaluated over complex data.
|
264 |
+
# if that's the case, set this to True
|
265 |
+
self._force_real_eval = kwargs.get("force_real_eval", None)
|
266 |
+
# this attribute will eventually contain a dictionary with the
|
267 |
+
# discretized ranges
|
268 |
+
self._discretized_domain = None
|
269 |
+
# wheter the series contains any interactive range, which is a range
|
270 |
+
# where the minimum and maximum values can be changed with an
|
271 |
+
# interactive widget
|
272 |
+
self._interactive_ranges = False
|
273 |
+
# NOTE: consider a generic summation, for example:
|
274 |
+
# s = Sum(cos(pi * x), (x, 1, y))
|
275 |
+
# This gets lambdified to something:
|
276 |
+
# sum(cos(pi*x) for x in range(1, y+1))
|
277 |
+
# Hence, y needs to be an integer, otherwise it raises:
|
278 |
+
# TypeError: 'complex' object cannot be interpreted as an integer
|
279 |
+
# This list will contains symbols that are upper bound to summations
|
280 |
+
# or products
|
281 |
+
self._needs_to_be_int = []
|
282 |
+
# a color function will be responsible to set the line/surface color
|
283 |
+
# according to some logic. Each data series will et an appropriate
|
284 |
+
# default value.
|
285 |
+
self.color_func = None
|
286 |
+
# NOTE: color_func usually receives numerical functions that are going
|
287 |
+
# to be evaluated over the coordinates of the computed points (or the
|
288 |
+
# discretized meshes).
|
289 |
+
# However, if an expression is given to color_func, then it will be
|
290 |
+
# lambdified with symbols in self._signature, and it will be evaluated
|
291 |
+
# with the same data used to evaluate the plotted expression.
|
292 |
+
self._eval_color_func_with_signature = False
|
293 |
+
|
294 |
+
def _block_lambda_functions(self, *exprs):
|
295 |
+
"""Some data series can be used to plot numerical functions, others
|
296 |
+
cannot. Execute this method inside the `__init__` to prevent the
|
297 |
+
processing of numerical functions.
|
298 |
+
"""
|
299 |
+
if any(callable(e) for e in exprs):
|
300 |
+
raise TypeError(type(self).__name__ + " requires a symbolic "
|
301 |
+
"expression.")
|
302 |
+
|
303 |
+
def _check_fs(self):
|
304 |
+
""" Checks if there are enogh parameters and free symbols.
|
305 |
+
"""
|
306 |
+
exprs, ranges = self.expr, self.ranges
|
307 |
+
params, label = self.params, self.label
|
308 |
+
exprs = exprs if hasattr(exprs, "__iter__") else [exprs]
|
309 |
+
if any(callable(e) for e in exprs):
|
310 |
+
return
|
311 |
+
|
312 |
+
# from the expression's free symbols, remove the ones used in
|
313 |
+
# the parameters and the ranges
|
314 |
+
fs = _get_free_symbols(exprs)
|
315 |
+
fs = fs.difference(params.keys())
|
316 |
+
if ranges is not None:
|
317 |
+
fs = fs.difference([r[0] for r in ranges])
|
318 |
+
|
319 |
+
if len(fs) > 0:
|
320 |
+
raise ValueError(
|
321 |
+
"Incompatible expression and parameters.\n"
|
322 |
+
+ "Expression: {}\n".format(
|
323 |
+
(exprs, ranges, label) if ranges is not None else (exprs, label))
|
324 |
+
+ "params: {}\n".format(params)
|
325 |
+
+ "Specify what these symbols represent: {}\n".format(fs)
|
326 |
+
+ "Are they ranges or parameters?"
|
327 |
+
)
|
328 |
+
|
329 |
+
# verify that all symbols are known (they either represent plotting
|
330 |
+
# ranges or parameters)
|
331 |
+
range_symbols = [r[0] for r in ranges]
|
332 |
+
for r in ranges:
|
333 |
+
fs = set().union(*[e.free_symbols for e in r[1:]])
|
334 |
+
if any(t in fs for t in range_symbols):
|
335 |
+
# ranges can't depend on each other, for example this are
|
336 |
+
# not allowed:
|
337 |
+
# (x, 0, y), (y, 0, 3)
|
338 |
+
# (x, 0, y), (y, x + 2, 3)
|
339 |
+
raise ValueError("Range symbols can't be included into "
|
340 |
+
"minimum and maximum of a range. "
|
341 |
+
"Received range: %s" % str(r))
|
342 |
+
if len(fs) > 0:
|
343 |
+
self._interactive_ranges = True
|
344 |
+
remaining_fs = fs.difference(params.keys())
|
345 |
+
if len(remaining_fs) > 0:
|
346 |
+
raise ValueError(
|
347 |
+
"Unkown symbols found in plotting range: %s. " % (r,) +
|
348 |
+
"Are the following parameters? %s" % remaining_fs)
|
349 |
+
|
350 |
+
def _create_lambda_func(self):
|
351 |
+
"""Create the lambda functions to be used by the uniform meshing
|
352 |
+
strategy.
|
353 |
+
|
354 |
+
Notes
|
355 |
+
=====
|
356 |
+
The old sympy.plotting used experimental_lambdify. It created one
|
357 |
+
lambda function each time an evaluation was requested. If that failed,
|
358 |
+
it went on to create a different lambda function and evaluated it,
|
359 |
+
and so on.
|
360 |
+
|
361 |
+
This new module changes strategy: it creates right away the default
|
362 |
+
lambda function as well as the backup one. The reason is that the
|
363 |
+
series could be interactive, hence the numerical function will be
|
364 |
+
evaluated multiple times. So, let's create the functions just once.
|
365 |
+
|
366 |
+
This approach works fine for the majority of cases, in which the
|
367 |
+
symbolic expression is relatively short, hence the lambdification
|
368 |
+
is fast. If the expression is very long, this approach takes twice
|
369 |
+
the time to create the lambda functions. Be aware of that!
|
370 |
+
"""
|
371 |
+
exprs = self.expr if hasattr(self.expr, "__iter__") else [self.expr]
|
372 |
+
if not any(callable(e) for e in exprs):
|
373 |
+
fs = _get_free_symbols(exprs)
|
374 |
+
self._signature = sorted(fs, key=lambda t: t.name)
|
375 |
+
|
376 |
+
# Generate a list of lambda functions, two for each expression:
|
377 |
+
# 1. the default one.
|
378 |
+
# 2. the backup one, in case of failures with the default one.
|
379 |
+
self._functions = []
|
380 |
+
for e in exprs:
|
381 |
+
# TODO: set cse=True once this issue is solved:
|
382 |
+
# https://github.com/sympy/sympy/issues/24246
|
383 |
+
self._functions.append([
|
384 |
+
lambdify(self._signature, e, modules=self.modules),
|
385 |
+
lambdify(self._signature, e, modules="sympy", dummify=True),
|
386 |
+
])
|
387 |
+
else:
|
388 |
+
self._signature = sorted([r[0] for r in self.ranges], key=lambda t: t.name)
|
389 |
+
self._functions = [(e, None) for e in exprs]
|
390 |
+
|
391 |
+
# deal with symbolic color_func
|
392 |
+
if isinstance(self.color_func, Expr):
|
393 |
+
self.color_func = lambdify(self._signature, self.color_func)
|
394 |
+
self._eval_color_func_with_signature = True
|
395 |
+
|
396 |
+
def _update_range_value(self, t):
|
397 |
+
"""If the value of a plotting range is a symbolic expression,
|
398 |
+
substitute the parameters in order to get a numerical value.
|
399 |
+
"""
|
400 |
+
if not self._interactive_ranges:
|
401 |
+
return complex(t)
|
402 |
+
return complex(t.subs(self.params))
|
403 |
+
|
404 |
+
def _create_discretized_domain(self):
|
405 |
+
"""Discretize the ranges for uniform meshing strategy.
|
406 |
+
"""
|
407 |
+
# NOTE: the goal is to create a dictionary stored in
|
408 |
+
# self._discretized_domain, mapping symbols to a numpy array
|
409 |
+
# representing the discretization
|
410 |
+
discr_symbols = []
|
411 |
+
discretizations = []
|
412 |
+
|
413 |
+
# create a 1D discretization
|
414 |
+
for i, r in enumerate(self.ranges):
|
415 |
+
discr_symbols.append(r[0])
|
416 |
+
c_start = self._update_range_value(r[1])
|
417 |
+
c_end = self._update_range_value(r[2])
|
418 |
+
start = c_start.real if c_start.imag == c_end.imag == 0 else c_start
|
419 |
+
end = c_end.real if c_start.imag == c_end.imag == 0 else c_end
|
420 |
+
needs_integer_discr = self.only_integers or (r[0] in self._needs_to_be_int)
|
421 |
+
d = BaseSeries._discretize(start, end, self.n[i],
|
422 |
+
scale=self.scales[i],
|
423 |
+
only_integers=needs_integer_discr)
|
424 |
+
|
425 |
+
if ((not self._force_real_eval) and (not needs_integer_discr) and
|
426 |
+
(d.dtype != "complex")):
|
427 |
+
d = d + 1j * c_start.imag
|
428 |
+
|
429 |
+
if needs_integer_discr:
|
430 |
+
d = d.astype(int)
|
431 |
+
|
432 |
+
discretizations.append(d)
|
433 |
+
|
434 |
+
# create 2D or 3D
|
435 |
+
self._create_discretized_domain_helper(discr_symbols, discretizations)
|
436 |
+
|
437 |
+
def _create_discretized_domain_helper(self, discr_symbols, discretizations):
|
438 |
+
"""Create 2D or 3D discretized grids.
|
439 |
+
|
440 |
+
Subclasses should override this method in order to implement a
|
441 |
+
different behaviour.
|
442 |
+
"""
|
443 |
+
np = import_module('numpy')
|
444 |
+
|
445 |
+
# discretization suitable for 2D line plots, 3D surface plots,
|
446 |
+
# contours plots, vector plots
|
447 |
+
# NOTE: why indexing='ij'? Because it produces consistent results with
|
448 |
+
# np.mgrid. This is important as Mayavi requires this indexing
|
449 |
+
# to correctly compute 3D streamlines. While VTK is able to compute
|
450 |
+
# streamlines regardless of the indexing, with indexing='xy' it
|
451 |
+
# produces "strange" results with "voids" into the
|
452 |
+
# discretization volume. indexing='ij' solves the problem.
|
453 |
+
# Also note that matplotlib 2D streamlines requires indexing='xy'.
|
454 |
+
indexing = "xy"
|
455 |
+
if self.is_3Dvector or (self.is_3Dsurface and self.is_implicit):
|
456 |
+
indexing = "ij"
|
457 |
+
meshes = np.meshgrid(*discretizations, indexing=indexing)
|
458 |
+
self._discretized_domain = dict(zip(discr_symbols, meshes))
|
459 |
+
|
460 |
+
def _evaluate(self, cast_to_real=True):
|
461 |
+
"""Evaluation of the symbolic expression (or expressions) with the
|
462 |
+
uniform meshing strategy, based on current values of the parameters.
|
463 |
+
"""
|
464 |
+
np = import_module('numpy')
|
465 |
+
|
466 |
+
# create lambda functions
|
467 |
+
if not self._functions:
|
468 |
+
self._create_lambda_func()
|
469 |
+
# create (or update) the discretized domain
|
470 |
+
if (not self._discretized_domain) or self._interactive_ranges:
|
471 |
+
self._create_discretized_domain()
|
472 |
+
# ensure that discretized domains are returned with the proper order
|
473 |
+
discr = [self._discretized_domain[s[0]] for s in self.ranges]
|
474 |
+
|
475 |
+
args = self._aggregate_args()
|
476 |
+
|
477 |
+
results = []
|
478 |
+
for f in self._functions:
|
479 |
+
r = _uniform_eval(*f, *args)
|
480 |
+
# the evaluation might produce an int/float. Need this correction.
|
481 |
+
r = self._correct_shape(np.array(r), discr[0])
|
482 |
+
# sometime the evaluation is performed over arrays of type object.
|
483 |
+
# hence, `result` might be of type object, which don't work well
|
484 |
+
# with numpy real and imag functions.
|
485 |
+
r = r.astype(complex)
|
486 |
+
results.append(r)
|
487 |
+
|
488 |
+
if cast_to_real:
|
489 |
+
discr = [np.real(d.astype(complex)) for d in discr]
|
490 |
+
return [*discr, *results]
|
491 |
+
|
492 |
+
def _aggregate_args(self):
|
493 |
+
"""Create a list of arguments to be passed to the lambda function,
|
494 |
+
sorted accoring to self._signature.
|
495 |
+
"""
|
496 |
+
args = []
|
497 |
+
for s in self._signature:
|
498 |
+
if s in self._params.keys():
|
499 |
+
args.append(
|
500 |
+
int(self._params[s]) if s in self._needs_to_be_int else
|
501 |
+
self._params[s] if self._force_real_eval
|
502 |
+
else complex(self._params[s]))
|
503 |
+
else:
|
504 |
+
args.append(self._discretized_domain[s])
|
505 |
+
return args
|
506 |
+
|
507 |
+
@property
|
508 |
+
def expr(self):
|
509 |
+
"""Return the expression (or expressions) of the series."""
|
510 |
+
return self._expr
|
511 |
+
|
512 |
+
@expr.setter
|
513 |
+
def expr(self, e):
|
514 |
+
"""Set the expression (or expressions) of the series."""
|
515 |
+
is_iter = hasattr(e, "__iter__")
|
516 |
+
is_callable = callable(e) if not is_iter else any(callable(t) for t in e)
|
517 |
+
if is_callable:
|
518 |
+
self._expr = e
|
519 |
+
else:
|
520 |
+
self._expr = sympify(e) if not is_iter else Tuple(*e)
|
521 |
+
|
522 |
+
# look for the upper bound of summations and products
|
523 |
+
s = set()
|
524 |
+
for e in self._expr.atoms(Sum, Product):
|
525 |
+
for a in e.args[1:]:
|
526 |
+
if isinstance(a[-1], Symbol):
|
527 |
+
s.add(a[-1])
|
528 |
+
self._needs_to_be_int = list(s)
|
529 |
+
|
530 |
+
# list of sympy functions that when lambdified, the corresponding
|
531 |
+
# numpy functions don't like complex-type arguments
|
532 |
+
pf = [ceiling, floor, atan2, frac, zeta]
|
533 |
+
if self._force_real_eval is not True:
|
534 |
+
check_res = [self._expr.has(f) for f in pf]
|
535 |
+
self._force_real_eval = any(check_res)
|
536 |
+
if self._force_real_eval and ((self.modules is None) or
|
537 |
+
(isinstance(self.modules, str) and "numpy" in self.modules)):
|
538 |
+
funcs = [f for f, c in zip(pf, check_res) if c]
|
539 |
+
warnings.warn("NumPy is unable to evaluate with complex "
|
540 |
+
"numbers some of the functions included in this "
|
541 |
+
"symbolic expression: %s. " % funcs +
|
542 |
+
"Hence, the evaluation will use real numbers. "
|
543 |
+
"If you believe the resulting plot is incorrect, "
|
544 |
+
"change the evaluation module by setting the "
|
545 |
+
"`modules` keyword argument.")
|
546 |
+
if self._functions:
|
547 |
+
# update lambda functions
|
548 |
+
self._create_lambda_func()
|
549 |
+
|
550 |
+
@property
|
551 |
+
def is_3D(self):
|
552 |
+
flags3D = [self.is_3Dline, self.is_3Dsurface, self.is_3Dvector]
|
553 |
+
return any(flags3D)
|
554 |
+
|
555 |
+
@property
|
556 |
+
def is_line(self):
|
557 |
+
flagslines = [self.is_2Dline, self.is_3Dline]
|
558 |
+
return any(flagslines)
|
559 |
+
|
560 |
+
def _line_surface_color(self, prop, val):
|
561 |
+
"""This method enables back-compatibility with old sympy.plotting"""
|
562 |
+
# NOTE: color_func is set inside the init method of the series.
|
563 |
+
# If line_color/surface_color is not a callable, then color_func will
|
564 |
+
# be set to None.
|
565 |
+
setattr(self, prop, val)
|
566 |
+
if callable(val) or isinstance(val, Expr):
|
567 |
+
self.color_func = val
|
568 |
+
setattr(self, prop, None)
|
569 |
+
elif val is not None:
|
570 |
+
self.color_func = None
|
571 |
+
|
572 |
+
@property
|
573 |
+
def line_color(self):
|
574 |
+
return self._line_color
|
575 |
+
|
576 |
+
@line_color.setter
|
577 |
+
def line_color(self, val):
|
578 |
+
self._line_surface_color("_line_color", val)
|
579 |
+
|
580 |
+
@property
|
581 |
+
def n(self):
|
582 |
+
"""Returns a list [n1, n2, n3] of numbers of discratization points.
|
583 |
+
"""
|
584 |
+
return self._n
|
585 |
+
|
586 |
+
@n.setter
|
587 |
+
def n(self, v):
|
588 |
+
"""Set the numbers of discretization points. ``v`` must be an int or
|
589 |
+
a list.
|
590 |
+
|
591 |
+
Let ``s`` be a series. Then:
|
592 |
+
|
593 |
+
* to set the number of discretization points along the x direction (or
|
594 |
+
first parameter): ``s.n = 10``
|
595 |
+
* to set the number of discretization points along the x and y
|
596 |
+
directions (or first and second parameters): ``s.n = [10, 15]``
|
597 |
+
* to set the number of discretization points along the x, y and z
|
598 |
+
directions: ``s.n = [10, 15, 20]``
|
599 |
+
|
600 |
+
The following is highly unreccomended, because it prevents
|
601 |
+
the execution of necessary code in order to keep updated data:
|
602 |
+
``s.n[1] = 15``
|
603 |
+
"""
|
604 |
+
if not hasattr(v, "__iter__"):
|
605 |
+
self._n[0] = v
|
606 |
+
else:
|
607 |
+
self._n[:len(v)] = v
|
608 |
+
if self._discretized_domain:
|
609 |
+
# update the discretized domain
|
610 |
+
self._create_discretized_domain()
|
611 |
+
|
612 |
+
@property
|
613 |
+
def params(self):
|
614 |
+
"""Get or set the current parameters dictionary.
|
615 |
+
|
616 |
+
Parameters
|
617 |
+
==========
|
618 |
+
|
619 |
+
p : dict
|
620 |
+
|
621 |
+
* key: symbol associated to the parameter
|
622 |
+
* val: the numeric value
|
623 |
+
"""
|
624 |
+
return self._params
|
625 |
+
|
626 |
+
@params.setter
|
627 |
+
def params(self, p):
|
628 |
+
self._params = p
|
629 |
+
|
630 |
+
def _post_init(self):
|
631 |
+
exprs = self.expr if hasattr(self.expr, "__iter__") else [self.expr]
|
632 |
+
if any(callable(e) for e in exprs) and self.params:
|
633 |
+
raise TypeError("`params` was provided, hence an interactive plot "
|
634 |
+
"is expected. However, interactive plots do not support "
|
635 |
+
"user-provided numerical functions.")
|
636 |
+
|
637 |
+
# if the expressions is a lambda function and no label has been
|
638 |
+
# provided, then its better to do the following in order to avoid
|
639 |
+
# suprises on the backend
|
640 |
+
if any(callable(e) for e in exprs):
|
641 |
+
if self._label == str(self.expr):
|
642 |
+
self.label = ""
|
643 |
+
|
644 |
+
self._check_fs()
|
645 |
+
|
646 |
+
if hasattr(self, "adaptive") and self.adaptive and self.params:
|
647 |
+
warnings.warn("`params` was provided, hence an interactive plot "
|
648 |
+
"is expected. However, interactive plots do not support "
|
649 |
+
"adaptive evaluation. Automatically switched to "
|
650 |
+
"adaptive=False.")
|
651 |
+
self.adaptive = False
|
652 |
+
|
653 |
+
@property
|
654 |
+
def scales(self):
|
655 |
+
return self._scales
|
656 |
+
|
657 |
+
@scales.setter
|
658 |
+
def scales(self, v):
|
659 |
+
if isinstance(v, str):
|
660 |
+
self._scales[0] = v
|
661 |
+
else:
|
662 |
+
self._scales[:len(v)] = v
|
663 |
+
|
664 |
+
@property
|
665 |
+
def surface_color(self):
|
666 |
+
return self._surface_color
|
667 |
+
|
668 |
+
@surface_color.setter
|
669 |
+
def surface_color(self, val):
|
670 |
+
self._line_surface_color("_surface_color", val)
|
671 |
+
|
672 |
+
@property
|
673 |
+
def rendering_kw(self):
|
674 |
+
return self._rendering_kw
|
675 |
+
|
676 |
+
@rendering_kw.setter
|
677 |
+
def rendering_kw(self, kwargs):
|
678 |
+
if isinstance(kwargs, dict):
|
679 |
+
self._rendering_kw = kwargs
|
680 |
+
else:
|
681 |
+
self._rendering_kw = {}
|
682 |
+
if kwargs is not None:
|
683 |
+
warnings.warn(
|
684 |
+
"`rendering_kw` must be a dictionary, instead an "
|
685 |
+
"object of type %s was received. " % type(kwargs) +
|
686 |
+
"Automatically setting `rendering_kw` to an empty "
|
687 |
+
"dictionary")
|
688 |
+
|
689 |
+
@staticmethod
|
690 |
+
def _discretize(start, end, N, scale="linear", only_integers=False):
|
691 |
+
"""Discretize a 1D domain.
|
692 |
+
|
693 |
+
Returns
|
694 |
+
=======
|
695 |
+
|
696 |
+
domain : np.ndarray with dtype=float or complex
|
697 |
+
The domain's dtype will be float or complex (depending on the
|
698 |
+
type of start/end) even if only_integers=True. It is left for
|
699 |
+
the downstream code to perform further casting, if necessary.
|
700 |
+
"""
|
701 |
+
np = import_module('numpy')
|
702 |
+
|
703 |
+
if only_integers is True:
|
704 |
+
start, end = int(start), int(end)
|
705 |
+
N = end - start + 1
|
706 |
+
|
707 |
+
if scale == "linear":
|
708 |
+
return np.linspace(start, end, N)
|
709 |
+
return np.geomspace(start, end, N)
|
710 |
+
|
711 |
+
@staticmethod
|
712 |
+
def _correct_shape(a, b):
|
713 |
+
"""Convert ``a`` to a np.ndarray of the same shape of ``b``.
|
714 |
+
|
715 |
+
Parameters
|
716 |
+
==========
|
717 |
+
|
718 |
+
a : int, float, complex, np.ndarray
|
719 |
+
Usually, this is the result of a numerical evaluation of a
|
720 |
+
symbolic expression. Even if a discretized domain was used to
|
721 |
+
evaluate the function, the result can be a scalar (int, float,
|
722 |
+
complex). Think for example to ``expr = Float(2)`` and
|
723 |
+
``f = lambdify(x, expr)``. No matter the shape of the numerical
|
724 |
+
array representing x, the result of the evaluation will be
|
725 |
+
a single value.
|
726 |
+
|
727 |
+
b : np.ndarray
|
728 |
+
It represents the correct shape that ``a`` should have.
|
729 |
+
|
730 |
+
Returns
|
731 |
+
=======
|
732 |
+
new_a : np.ndarray
|
733 |
+
An array with the correct shape.
|
734 |
+
"""
|
735 |
+
np = import_module('numpy')
|
736 |
+
|
737 |
+
if not isinstance(a, np.ndarray):
|
738 |
+
a = np.array(a)
|
739 |
+
if a.shape != b.shape:
|
740 |
+
if a.shape == ():
|
741 |
+
a = a * np.ones_like(b)
|
742 |
+
else:
|
743 |
+
a = a.reshape(b.shape)
|
744 |
+
return a
|
745 |
+
|
746 |
+
def eval_color_func(self, *args):
|
747 |
+
"""Evaluate the color function.
|
748 |
+
|
749 |
+
Parameters
|
750 |
+
==========
|
751 |
+
|
752 |
+
args : tuple
|
753 |
+
Arguments to be passed to the coloring function. Can be coordinates
|
754 |
+
or parameters or both.
|
755 |
+
|
756 |
+
Notes
|
757 |
+
=====
|
758 |
+
|
759 |
+
The backend will request the data series to generate the numerical
|
760 |
+
data. Depending on the data series, either the data series itself or
|
761 |
+
the backend will eventually execute this function to generate the
|
762 |
+
appropriate coloring value.
|
763 |
+
"""
|
764 |
+
np = import_module('numpy')
|
765 |
+
if self.color_func is None:
|
766 |
+
# NOTE: with the line_color and surface_color attributes
|
767 |
+
# (back-compatibility with the old sympy.plotting module) it is
|
768 |
+
# possible to create a plot with a callable line_color (or
|
769 |
+
# surface_color). For example:
|
770 |
+
# p = plot(sin(x), line_color=lambda x, y: -y)
|
771 |
+
# This creates a ColoredLineOver1DRangeSeries with line_color=None
|
772 |
+
# and color_func=lambda x, y: -y, which efffectively is a
|
773 |
+
# parametric series. Later we could change it to a string value:
|
774 |
+
# p[0].line_color = "red"
|
775 |
+
# However, this sets ine_color="red" and color_func=None, but the
|
776 |
+
# series is still ColoredLineOver1DRangeSeries (a parametric
|
777 |
+
# series), which will render using a color_func...
|
778 |
+
warnings.warn("This is likely not the result you were "
|
779 |
+
"looking for. Please, re-execute the plot command, this time "
|
780 |
+
"with the appropriate an appropriate value to line_color "
|
781 |
+
"or surface_color.")
|
782 |
+
return np.ones_like(args[0])
|
783 |
+
|
784 |
+
if self._eval_color_func_with_signature:
|
785 |
+
args = self._aggregate_args()
|
786 |
+
color = self.color_func(*args)
|
787 |
+
_re, _im = np.real(color), np.imag(color)
|
788 |
+
_re[np.invert(np.isclose(_im, np.zeros_like(_im)))] = np.nan
|
789 |
+
return _re
|
790 |
+
|
791 |
+
nargs = arity(self.color_func)
|
792 |
+
if nargs == 1:
|
793 |
+
if self.is_2Dline and self.is_parametric:
|
794 |
+
if len(args) == 2:
|
795 |
+
# ColoredLineOver1DRangeSeries
|
796 |
+
return self._correct_shape(self.color_func(args[0]), args[0])
|
797 |
+
# Parametric2DLineSeries
|
798 |
+
return self._correct_shape(self.color_func(args[2]), args[2])
|
799 |
+
elif self.is_3Dline and self.is_parametric:
|
800 |
+
return self._correct_shape(self.color_func(args[3]), args[3])
|
801 |
+
elif self.is_3Dsurface and self.is_parametric:
|
802 |
+
return self._correct_shape(self.color_func(args[3]), args[3])
|
803 |
+
return self._correct_shape(self.color_func(args[0]), args[0])
|
804 |
+
elif nargs == 2:
|
805 |
+
if self.is_3Dsurface and self.is_parametric:
|
806 |
+
return self._correct_shape(self.color_func(*args[3:]), args[3])
|
807 |
+
return self._correct_shape(self.color_func(*args[:2]), args[0])
|
808 |
+
return self._correct_shape(self.color_func(*args[:nargs]), args[0])
|
809 |
+
|
810 |
+
def get_data(self):
|
811 |
+
"""Compute and returns the numerical data.
|
812 |
+
|
813 |
+
The number of parameters returned by this method depends on the
|
814 |
+
specific instance. If ``s`` is the series, make sure to read
|
815 |
+
``help(s.get_data)`` to understand what it returns.
|
816 |
+
"""
|
817 |
+
raise NotImplementedError
|
818 |
+
|
819 |
+
def _get_wrapped_label(self, label, wrapper):
|
820 |
+
"""Given a latex representation of an expression, wrap it inside
|
821 |
+
some characters. Matplotlib needs "$%s%$", K3D-Jupyter needs "%s".
|
822 |
+
"""
|
823 |
+
return wrapper % label
|
824 |
+
|
825 |
+
def get_label(self, use_latex=False, wrapper="$%s$"):
|
826 |
+
"""Return the label to be used to display the expression.
|
827 |
+
|
828 |
+
Parameters
|
829 |
+
==========
|
830 |
+
use_latex : bool
|
831 |
+
If False, the string representation of the expression is returned.
|
832 |
+
If True, the latex representation is returned.
|
833 |
+
wrapper : str
|
834 |
+
The backend might need the latex representation to be wrapped by
|
835 |
+
some characters. Default to ``"$%s$"``.
|
836 |
+
|
837 |
+
Returns
|
838 |
+
=======
|
839 |
+
label : str
|
840 |
+
"""
|
841 |
+
if use_latex is False:
|
842 |
+
return self._label
|
843 |
+
if self._label == str(self.expr):
|
844 |
+
# when the backend requests a latex label and user didn't provide
|
845 |
+
# any label
|
846 |
+
return self._get_wrapped_label(self._latex_label, wrapper)
|
847 |
+
return self._latex_label
|
848 |
+
|
849 |
+
@property
|
850 |
+
def label(self):
|
851 |
+
return self.get_label()
|
852 |
+
|
853 |
+
@label.setter
|
854 |
+
def label(self, val):
|
855 |
+
"""Set the labels associated to this series."""
|
856 |
+
# NOTE: the init method of any series requires a label. If the user do
|
857 |
+
# not provide it, the preprocessing function will set label=None, which
|
858 |
+
# informs the series to initialize two attributes:
|
859 |
+
# _label contains the string representation of the expression.
|
860 |
+
# _latex_label contains the latex representation of the expression.
|
861 |
+
self._label = self._latex_label = val
|
862 |
+
|
863 |
+
@property
|
864 |
+
def ranges(self):
|
865 |
+
return self._ranges
|
866 |
+
|
867 |
+
@ranges.setter
|
868 |
+
def ranges(self, val):
|
869 |
+
new_vals = []
|
870 |
+
for v in val:
|
871 |
+
if v is not None:
|
872 |
+
new_vals.append(tuple([sympify(t) for t in v]))
|
873 |
+
self._ranges = new_vals
|
874 |
+
|
875 |
+
def _apply_transform(self, *args):
|
876 |
+
"""Apply transformations to the results of numerical evaluation.
|
877 |
+
|
878 |
+
Parameters
|
879 |
+
==========
|
880 |
+
args : tuple
|
881 |
+
Results of numerical evaluation.
|
882 |
+
|
883 |
+
Returns
|
884 |
+
=======
|
885 |
+
transformed_args : tuple
|
886 |
+
Tuple containing the transformed results.
|
887 |
+
"""
|
888 |
+
t = lambda x, transform: x if transform is None else transform(x)
|
889 |
+
x, y, z = None, None, None
|
890 |
+
if len(args) == 2:
|
891 |
+
x, y = args
|
892 |
+
return t(x, self._tx), t(y, self._ty)
|
893 |
+
elif (len(args) == 3) and isinstance(self, Parametric2DLineSeries):
|
894 |
+
x, y, u = args
|
895 |
+
return (t(x, self._tx), t(y, self._ty), t(u, self._tp))
|
896 |
+
elif len(args) == 3:
|
897 |
+
x, y, z = args
|
898 |
+
return t(x, self._tx), t(y, self._ty), t(z, self._tz)
|
899 |
+
elif (len(args) == 4) and isinstance(self, Parametric3DLineSeries):
|
900 |
+
x, y, z, u = args
|
901 |
+
return (t(x, self._tx), t(y, self._ty), t(z, self._tz), t(u, self._tp))
|
902 |
+
elif len(args) == 4: # 2D vector plot
|
903 |
+
x, y, u, v = args
|
904 |
+
return (
|
905 |
+
t(x, self._tx), t(y, self._ty),
|
906 |
+
t(u, self._tx), t(v, self._ty)
|
907 |
+
)
|
908 |
+
elif (len(args) == 5) and isinstance(self, ParametricSurfaceSeries):
|
909 |
+
x, y, z, u, v = args
|
910 |
+
return (t(x, self._tx), t(y, self._ty), t(z, self._tz), u, v)
|
911 |
+
elif (len(args) == 6) and self.is_3Dvector: # 3D vector plot
|
912 |
+
x, y, z, u, v, w = args
|
913 |
+
return (
|
914 |
+
t(x, self._tx), t(y, self._ty), t(z, self._tz),
|
915 |
+
t(u, self._tx), t(v, self._ty), t(w, self._tz)
|
916 |
+
)
|
917 |
+
elif len(args) == 6: # complex plot
|
918 |
+
x, y, _abs, _arg, img, colors = args
|
919 |
+
return (
|
920 |
+
x, y, t(_abs, self._tz), _arg, img, colors)
|
921 |
+
return args
|
922 |
+
|
923 |
+
def _str_helper(self, s):
|
924 |
+
pre, post = "", ""
|
925 |
+
if self.is_interactive:
|
926 |
+
pre = "interactive "
|
927 |
+
post = " and parameters " + str(tuple(self.params.keys()))
|
928 |
+
return pre + s + post
|
929 |
+
|
930 |
+
|
931 |
+
def _detect_poles_numerical_helper(x, y, eps=0.01, expr=None, symb=None, symbolic=False):
|
932 |
+
"""Compute the steepness of each segment. If it's greater than a
|
933 |
+
threshold, set the right-point y-value non NaN and record the
|
934 |
+
corresponding x-location for further processing.
|
935 |
+
|
936 |
+
Returns
|
937 |
+
=======
|
938 |
+
x : np.ndarray
|
939 |
+
Unchanged x-data.
|
940 |
+
yy : np.ndarray
|
941 |
+
Modified y-data with NaN values.
|
942 |
+
"""
|
943 |
+
np = import_module('numpy')
|
944 |
+
|
945 |
+
yy = y.copy()
|
946 |
+
threshold = np.pi / 2 - eps
|
947 |
+
for i in range(len(x) - 1):
|
948 |
+
dx = x[i + 1] - x[i]
|
949 |
+
dy = abs(y[i + 1] - y[i])
|
950 |
+
angle = np.arctan(dy / dx)
|
951 |
+
if abs(angle) >= threshold:
|
952 |
+
yy[i + 1] = np.nan
|
953 |
+
|
954 |
+
return x, yy
|
955 |
+
|
956 |
+
def _detect_poles_symbolic_helper(expr, symb, start, end):
|
957 |
+
"""Attempts to compute symbolic discontinuities.
|
958 |
+
|
959 |
+
Returns
|
960 |
+
=======
|
961 |
+
pole : list
|
962 |
+
List of symbolic poles, possibily empty.
|
963 |
+
"""
|
964 |
+
poles = []
|
965 |
+
interval = Interval(nsimplify(start), nsimplify(end))
|
966 |
+
res = continuous_domain(expr, symb, interval)
|
967 |
+
res = res.simplify()
|
968 |
+
if res == interval:
|
969 |
+
pass
|
970 |
+
elif (isinstance(res, Union) and
|
971 |
+
all(isinstance(t, Interval) for t in res.args)):
|
972 |
+
poles = []
|
973 |
+
for s in res.args:
|
974 |
+
if s.left_open:
|
975 |
+
poles.append(s.left)
|
976 |
+
if s.right_open:
|
977 |
+
poles.append(s.right)
|
978 |
+
poles = list(set(poles))
|
979 |
+
else:
|
980 |
+
raise ValueError(
|
981 |
+
f"Could not parse the following object: {res} .\n"
|
982 |
+
"Please, submit this as a bug. Consider also to set "
|
983 |
+
"`detect_poles=True`."
|
984 |
+
)
|
985 |
+
return poles
|
986 |
+
|
987 |
+
|
988 |
+
### 2D lines
|
989 |
+
class Line2DBaseSeries(BaseSeries):
|
990 |
+
"""A base class for 2D lines.
|
991 |
+
|
992 |
+
- adding the label, steps and only_integers options
|
993 |
+
- making is_2Dline true
|
994 |
+
- defining get_segments and get_color_array
|
995 |
+
"""
|
996 |
+
|
997 |
+
is_2Dline = True
|
998 |
+
_dim = 2
|
999 |
+
_N = 1000
|
1000 |
+
|
1001 |
+
def __init__(self, **kwargs):
|
1002 |
+
super().__init__(**kwargs)
|
1003 |
+
self.steps = kwargs.get("steps", False)
|
1004 |
+
self.is_point = kwargs.get("is_point", kwargs.get("point", False))
|
1005 |
+
self.is_filled = kwargs.get("is_filled", kwargs.get("fill", True))
|
1006 |
+
self.adaptive = kwargs.get("adaptive", False)
|
1007 |
+
self.depth = kwargs.get('depth', 12)
|
1008 |
+
self.use_cm = kwargs.get("use_cm", False)
|
1009 |
+
self.color_func = kwargs.get("color_func", None)
|
1010 |
+
self.line_color = kwargs.get("line_color", None)
|
1011 |
+
self.detect_poles = kwargs.get("detect_poles", False)
|
1012 |
+
self.eps = kwargs.get("eps", 0.01)
|
1013 |
+
self.is_polar = kwargs.get("is_polar", kwargs.get("polar", False))
|
1014 |
+
self.unwrap = kwargs.get("unwrap", False)
|
1015 |
+
# when detect_poles="symbolic", stores the location of poles so that
|
1016 |
+
# they can be appropriately rendered
|
1017 |
+
self.poles_locations = []
|
1018 |
+
exclude = kwargs.get("exclude", [])
|
1019 |
+
if isinstance(exclude, Set):
|
1020 |
+
exclude = list(extract_solution(exclude, n=100))
|
1021 |
+
if not hasattr(exclude, "__iter__"):
|
1022 |
+
exclude = [exclude]
|
1023 |
+
exclude = [float(e) for e in exclude]
|
1024 |
+
self.exclude = sorted(exclude)
|
1025 |
+
|
1026 |
+
def get_data(self):
|
1027 |
+
"""Return coordinates for plotting the line.
|
1028 |
+
|
1029 |
+
Returns
|
1030 |
+
=======
|
1031 |
+
|
1032 |
+
x: np.ndarray
|
1033 |
+
x-coordinates
|
1034 |
+
|
1035 |
+
y: np.ndarray
|
1036 |
+
y-coordinates
|
1037 |
+
|
1038 |
+
z: np.ndarray (optional)
|
1039 |
+
z-coordinates in case of Parametric3DLineSeries,
|
1040 |
+
Parametric3DLineInteractiveSeries
|
1041 |
+
|
1042 |
+
param : np.ndarray (optional)
|
1043 |
+
The parameter in case of Parametric2DLineSeries,
|
1044 |
+
Parametric3DLineSeries or AbsArgLineSeries (and their
|
1045 |
+
corresponding interactive series).
|
1046 |
+
"""
|
1047 |
+
np = import_module('numpy')
|
1048 |
+
points = self._get_data_helper()
|
1049 |
+
|
1050 |
+
if (isinstance(self, LineOver1DRangeSeries) and
|
1051 |
+
(self.detect_poles == "symbolic")):
|
1052 |
+
poles = _detect_poles_symbolic_helper(
|
1053 |
+
self.expr.subs(self.params), *self.ranges[0])
|
1054 |
+
poles = np.array([float(t) for t in poles])
|
1055 |
+
t = lambda x, transform: x if transform is None else transform(x)
|
1056 |
+
self.poles_locations = t(np.array(poles), self._tx)
|
1057 |
+
|
1058 |
+
# postprocessing
|
1059 |
+
points = self._apply_transform(*points)
|
1060 |
+
|
1061 |
+
if self.is_2Dline and self.detect_poles:
|
1062 |
+
if len(points) == 2:
|
1063 |
+
x, y = points
|
1064 |
+
x, y = _detect_poles_numerical_helper(
|
1065 |
+
x, y, self.eps)
|
1066 |
+
points = (x, y)
|
1067 |
+
else:
|
1068 |
+
x, y, p = points
|
1069 |
+
x, y = _detect_poles_numerical_helper(x, y, self.eps)
|
1070 |
+
points = (x, y, p)
|
1071 |
+
|
1072 |
+
if self.unwrap:
|
1073 |
+
kw = {}
|
1074 |
+
if self.unwrap is not True:
|
1075 |
+
kw = self.unwrap
|
1076 |
+
if self.is_2Dline:
|
1077 |
+
if len(points) == 2:
|
1078 |
+
x, y = points
|
1079 |
+
y = np.unwrap(y, **kw)
|
1080 |
+
points = (x, y)
|
1081 |
+
else:
|
1082 |
+
x, y, p = points
|
1083 |
+
y = np.unwrap(y, **kw)
|
1084 |
+
points = (x, y, p)
|
1085 |
+
|
1086 |
+
if self.steps is True:
|
1087 |
+
if self.is_2Dline:
|
1088 |
+
x, y = points[0], points[1]
|
1089 |
+
x = np.array((x, x)).T.flatten()[1:]
|
1090 |
+
y = np.array((y, y)).T.flatten()[:-1]
|
1091 |
+
if self.is_parametric:
|
1092 |
+
points = (x, y, points[2])
|
1093 |
+
else:
|
1094 |
+
points = (x, y)
|
1095 |
+
elif self.is_3Dline:
|
1096 |
+
x = np.repeat(points[0], 3)[2:]
|
1097 |
+
y = np.repeat(points[1], 3)[:-2]
|
1098 |
+
z = np.repeat(points[2], 3)[1:-1]
|
1099 |
+
if len(points) > 3:
|
1100 |
+
points = (x, y, z, points[3])
|
1101 |
+
else:
|
1102 |
+
points = (x, y, z)
|
1103 |
+
|
1104 |
+
if len(self.exclude) > 0:
|
1105 |
+
points = self._insert_exclusions(points)
|
1106 |
+
return points
|
1107 |
+
|
1108 |
+
def get_segments(self):
|
1109 |
+
sympy_deprecation_warning(
|
1110 |
+
"""
|
1111 |
+
The Line2DBaseSeries.get_segments() method is deprecated.
|
1112 |
+
|
1113 |
+
Instead, use the MatplotlibBackend.get_segments() method, or use
|
1114 |
+
The get_points() or get_data() methods.
|
1115 |
+
""",
|
1116 |
+
deprecated_since_version="1.9",
|
1117 |
+
active_deprecations_target="deprecated-get-segments")
|
1118 |
+
|
1119 |
+
np = import_module('numpy')
|
1120 |
+
points = type(self).get_data(self)
|
1121 |
+
points = np.ma.array(points).T.reshape(-1, 1, self._dim)
|
1122 |
+
return np.ma.concatenate([points[:-1], points[1:]], axis=1)
|
1123 |
+
|
1124 |
+
def _insert_exclusions(self, points):
|
1125 |
+
"""Add NaN to each of the exclusion point. Practically, this adds a
|
1126 |
+
NaN to the exlusion point, plus two other nearby points evaluated with
|
1127 |
+
the numerical functions associated to this data series.
|
1128 |
+
These nearby points are important when the number of discretization
|
1129 |
+
points is low, or the scale is logarithm.
|
1130 |
+
|
1131 |
+
NOTE: it would be easier to just add exclusion points to the
|
1132 |
+
discretized domain before evaluation, then after evaluation add NaN
|
1133 |
+
to the exclusion points. But that's only work with adaptive=False.
|
1134 |
+
The following approach work even with adaptive=True.
|
1135 |
+
"""
|
1136 |
+
np = import_module("numpy")
|
1137 |
+
points = list(points)
|
1138 |
+
n = len(points)
|
1139 |
+
# index of the x-coordinate (for 2d plots) or parameter (for 2d/3d
|
1140 |
+
# parametric plots)
|
1141 |
+
k = n - 1
|
1142 |
+
if n == 2:
|
1143 |
+
k = 0
|
1144 |
+
# indeces of the other coordinates
|
1145 |
+
j_indeces = sorted(set(range(n)).difference([k]))
|
1146 |
+
# TODO: for now, I assume that numpy functions are going to succeed
|
1147 |
+
funcs = [f[0] for f in self._functions]
|
1148 |
+
|
1149 |
+
for e in self.exclude:
|
1150 |
+
res = points[k] - e >= 0
|
1151 |
+
# if res contains both True and False, ie, if e is found
|
1152 |
+
if any(res) and any(~res):
|
1153 |
+
idx = np.nanargmax(res)
|
1154 |
+
# select the previous point with respect to e
|
1155 |
+
idx -= 1
|
1156 |
+
# TODO: what if points[k][idx]==e or points[k][idx+1]==e?
|
1157 |
+
|
1158 |
+
if idx > 0 and idx < len(points[k]) - 1:
|
1159 |
+
delta_prev = abs(e - points[k][idx])
|
1160 |
+
delta_post = abs(e - points[k][idx + 1])
|
1161 |
+
delta = min(delta_prev, delta_post) / 100
|
1162 |
+
prev = e - delta
|
1163 |
+
post = e + delta
|
1164 |
+
|
1165 |
+
# add points to the x-coord or the parameter
|
1166 |
+
points[k] = np.concatenate(
|
1167 |
+
(points[k][:idx], [prev, e, post], points[k][idx+1:]))
|
1168 |
+
|
1169 |
+
# add points to the other coordinates
|
1170 |
+
c = 0
|
1171 |
+
for j in j_indeces:
|
1172 |
+
values = funcs[c](np.array([prev, post]))
|
1173 |
+
c += 1
|
1174 |
+
points[j] = np.concatenate(
|
1175 |
+
(points[j][:idx], [values[0], np.nan, values[1]], points[j][idx+1:]))
|
1176 |
+
return points
|
1177 |
+
|
1178 |
+
@property
|
1179 |
+
def var(self):
|
1180 |
+
return None if not self.ranges else self.ranges[0][0]
|
1181 |
+
|
1182 |
+
@property
|
1183 |
+
def start(self):
|
1184 |
+
if not self.ranges:
|
1185 |
+
return None
|
1186 |
+
try:
|
1187 |
+
return self._cast(self.ranges[0][1])
|
1188 |
+
except TypeError:
|
1189 |
+
return self.ranges[0][1]
|
1190 |
+
|
1191 |
+
@property
|
1192 |
+
def end(self):
|
1193 |
+
if not self.ranges:
|
1194 |
+
return None
|
1195 |
+
try:
|
1196 |
+
return self._cast(self.ranges[0][2])
|
1197 |
+
except TypeError:
|
1198 |
+
return self.ranges[0][2]
|
1199 |
+
|
1200 |
+
@property
|
1201 |
+
def xscale(self):
|
1202 |
+
return self._scales[0]
|
1203 |
+
|
1204 |
+
@xscale.setter
|
1205 |
+
def xscale(self, v):
|
1206 |
+
self.scales = v
|
1207 |
+
|
1208 |
+
def get_color_array(self):
|
1209 |
+
np = import_module('numpy')
|
1210 |
+
c = self.line_color
|
1211 |
+
if hasattr(c, '__call__'):
|
1212 |
+
f = np.vectorize(c)
|
1213 |
+
nargs = arity(c)
|
1214 |
+
if nargs == 1 and self.is_parametric:
|
1215 |
+
x = self.get_parameter_points()
|
1216 |
+
return f(centers_of_segments(x))
|
1217 |
+
else:
|
1218 |
+
variables = list(map(centers_of_segments, self.get_points()))
|
1219 |
+
if nargs == 1:
|
1220 |
+
return f(variables[0])
|
1221 |
+
elif nargs == 2:
|
1222 |
+
return f(*variables[:2])
|
1223 |
+
else: # only if the line is 3D (otherwise raises an error)
|
1224 |
+
return f(*variables)
|
1225 |
+
else:
|
1226 |
+
return c*np.ones(self.nb_of_points)
|
1227 |
+
|
1228 |
+
|
1229 |
+
class List2DSeries(Line2DBaseSeries):
|
1230 |
+
"""Representation for a line consisting of list of points."""
|
1231 |
+
|
1232 |
+
def __init__(self, list_x, list_y, label="", **kwargs):
|
1233 |
+
super().__init__(**kwargs)
|
1234 |
+
np = import_module('numpy')
|
1235 |
+
if len(list_x) != len(list_y):
|
1236 |
+
raise ValueError(
|
1237 |
+
"The two lists of coordinates must have the same "
|
1238 |
+
"number of elements.\n"
|
1239 |
+
"Received: len(list_x) = {} ".format(len(list_x)) +
|
1240 |
+
"and len(list_y) = {}".format(len(list_y))
|
1241 |
+
)
|
1242 |
+
self._block_lambda_functions(list_x, list_y)
|
1243 |
+
check = lambda l: [isinstance(t, Expr) and (not t.is_number) for t in l]
|
1244 |
+
if any(check(list_x) + check(list_y)) or self.params:
|
1245 |
+
if not self.params:
|
1246 |
+
raise ValueError("Some or all elements of the provided lists "
|
1247 |
+
"are symbolic expressions, but the ``params`` dictionary "
|
1248 |
+
"was not provided: those elements can't be evaluated.")
|
1249 |
+
self.list_x = Tuple(*list_x)
|
1250 |
+
self.list_y = Tuple(*list_y)
|
1251 |
+
else:
|
1252 |
+
self.list_x = np.array(list_x, dtype=np.float64)
|
1253 |
+
self.list_y = np.array(list_y, dtype=np.float64)
|
1254 |
+
|
1255 |
+
self._expr = (self.list_x, self.list_y)
|
1256 |
+
if not any(isinstance(t, np.ndarray) for t in [self.list_x, self.list_y]):
|
1257 |
+
self._check_fs()
|
1258 |
+
self.is_polar = kwargs.get("is_polar", kwargs.get("polar", False))
|
1259 |
+
self.label = label
|
1260 |
+
self.rendering_kw = kwargs.get("rendering_kw", {})
|
1261 |
+
if self.use_cm and self.color_func:
|
1262 |
+
self.is_parametric = True
|
1263 |
+
if isinstance(self.color_func, Expr):
|
1264 |
+
raise TypeError(
|
1265 |
+
"%s don't support symbolic " % self.__class__.__name__ +
|
1266 |
+
"expression for `color_func`.")
|
1267 |
+
|
1268 |
+
def __str__(self):
|
1269 |
+
return "2D list plot"
|
1270 |
+
|
1271 |
+
def _get_data_helper(self):
|
1272 |
+
"""Returns coordinates that needs to be postprocessed."""
|
1273 |
+
lx, ly = self.list_x, self.list_y
|
1274 |
+
|
1275 |
+
if not self.is_interactive:
|
1276 |
+
return self._eval_color_func_and_return(lx, ly)
|
1277 |
+
|
1278 |
+
np = import_module('numpy')
|
1279 |
+
lx = np.array([t.evalf(subs=self.params) for t in lx], dtype=float)
|
1280 |
+
ly = np.array([t.evalf(subs=self.params) for t in ly], dtype=float)
|
1281 |
+
return self._eval_color_func_and_return(lx, ly)
|
1282 |
+
|
1283 |
+
def _eval_color_func_and_return(self, *data):
|
1284 |
+
if self.use_cm and callable(self.color_func):
|
1285 |
+
return [*data, self.eval_color_func(*data)]
|
1286 |
+
return data
|
1287 |
+
|
1288 |
+
|
1289 |
+
class LineOver1DRangeSeries(Line2DBaseSeries):
|
1290 |
+
"""Representation for a line consisting of a SymPy expression over a range."""
|
1291 |
+
|
1292 |
+
def __init__(self, expr, var_start_end, label="", **kwargs):
|
1293 |
+
super().__init__(**kwargs)
|
1294 |
+
self.expr = expr if callable(expr) else sympify(expr)
|
1295 |
+
self._label = str(self.expr) if label is None else label
|
1296 |
+
self._latex_label = latex(self.expr) if label is None else label
|
1297 |
+
self.ranges = [var_start_end]
|
1298 |
+
self._cast = complex
|
1299 |
+
# for complex-related data series, this determines what data to return
|
1300 |
+
# on the y-axis
|
1301 |
+
self._return = kwargs.get("return", None)
|
1302 |
+
self._post_init()
|
1303 |
+
|
1304 |
+
if not self._interactive_ranges:
|
1305 |
+
# NOTE: the following check is only possible when the minimum and
|
1306 |
+
# maximum values of a plotting range are numeric
|
1307 |
+
start, end = [complex(t) for t in self.ranges[0][1:]]
|
1308 |
+
if im(start) != im(end):
|
1309 |
+
raise ValueError(
|
1310 |
+
"%s requires the imaginary " % self.__class__.__name__ +
|
1311 |
+
"part of the start and end values of the range "
|
1312 |
+
"to be the same.")
|
1313 |
+
|
1314 |
+
if self.adaptive and self._return:
|
1315 |
+
warnings.warn("The adaptive algorithm is unable to deal with "
|
1316 |
+
"complex numbers. Automatically switching to uniform meshing.")
|
1317 |
+
self.adaptive = False
|
1318 |
+
|
1319 |
+
@property
|
1320 |
+
def nb_of_points(self):
|
1321 |
+
return self.n[0]
|
1322 |
+
|
1323 |
+
@nb_of_points.setter
|
1324 |
+
def nb_of_points(self, v):
|
1325 |
+
self.n = v
|
1326 |
+
|
1327 |
+
def __str__(self):
|
1328 |
+
def f(t):
|
1329 |
+
if isinstance(t, complex):
|
1330 |
+
if t.imag != 0:
|
1331 |
+
return t
|
1332 |
+
return t.real
|
1333 |
+
return t
|
1334 |
+
pre = "interactive " if self.is_interactive else ""
|
1335 |
+
post = ""
|
1336 |
+
if self.is_interactive:
|
1337 |
+
post = " and parameters " + str(tuple(self.params.keys()))
|
1338 |
+
wrapper = _get_wrapper_for_expr(self._return)
|
1339 |
+
return pre + "cartesian line: %s for %s over %s" % (
|
1340 |
+
wrapper % self.expr,
|
1341 |
+
str(self.var),
|
1342 |
+
str((f(self.start), f(self.end))),
|
1343 |
+
) + post
|
1344 |
+
|
1345 |
+
def get_points(self):
|
1346 |
+
"""Return lists of coordinates for plotting. Depending on the
|
1347 |
+
``adaptive`` option, this function will either use an adaptive algorithm
|
1348 |
+
or it will uniformly sample the expression over the provided range.
|
1349 |
+
|
1350 |
+
This function is available for back-compatibility purposes. Consider
|
1351 |
+
using ``get_data()`` instead.
|
1352 |
+
|
1353 |
+
Returns
|
1354 |
+
=======
|
1355 |
+
x : list
|
1356 |
+
List of x-coordinates
|
1357 |
+
|
1358 |
+
y : list
|
1359 |
+
List of y-coordinates
|
1360 |
+
"""
|
1361 |
+
return self._get_data_helper()
|
1362 |
+
|
1363 |
+
def _adaptive_sampling(self):
|
1364 |
+
try:
|
1365 |
+
if callable(self.expr):
|
1366 |
+
f = self.expr
|
1367 |
+
else:
|
1368 |
+
f = lambdify([self.var], self.expr, self.modules)
|
1369 |
+
x, y = self._adaptive_sampling_helper(f)
|
1370 |
+
except Exception as err:
|
1371 |
+
warnings.warn(
|
1372 |
+
"The evaluation with %s failed.\n" % (
|
1373 |
+
"NumPy/SciPy" if not self.modules else self.modules) +
|
1374 |
+
"{}: {}\n".format(type(err).__name__, err) +
|
1375 |
+
"Trying to evaluate the expression with Sympy, but it might "
|
1376 |
+
"be a slow operation."
|
1377 |
+
)
|
1378 |
+
f = lambdify([self.var], self.expr, "sympy")
|
1379 |
+
x, y = self._adaptive_sampling_helper(f)
|
1380 |
+
return x, y
|
1381 |
+
|
1382 |
+
def _adaptive_sampling_helper(self, f):
|
1383 |
+
"""The adaptive sampling is done by recursively checking if three
|
1384 |
+
points are almost collinear. If they are not collinear, then more
|
1385 |
+
points are added between those points.
|
1386 |
+
|
1387 |
+
References
|
1388 |
+
==========
|
1389 |
+
|
1390 |
+
.. [1] Adaptive polygonal approximation of parametric curves,
|
1391 |
+
Luiz Henrique de Figueiredo.
|
1392 |
+
"""
|
1393 |
+
np = import_module('numpy')
|
1394 |
+
|
1395 |
+
x_coords = []
|
1396 |
+
y_coords = []
|
1397 |
+
def sample(p, q, depth):
|
1398 |
+
""" Samples recursively if three points are almost collinear.
|
1399 |
+
For depth < 6, points are added irrespective of whether they
|
1400 |
+
satisfy the collinearity condition or not. The maximum depth
|
1401 |
+
allowed is 12.
|
1402 |
+
"""
|
1403 |
+
# Randomly sample to avoid aliasing.
|
1404 |
+
random = 0.45 + np.random.rand() * 0.1
|
1405 |
+
if self.xscale == 'log':
|
1406 |
+
xnew = 10**(np.log10(p[0]) + random * (np.log10(q[0]) -
|
1407 |
+
np.log10(p[0])))
|
1408 |
+
else:
|
1409 |
+
xnew = p[0] + random * (q[0] - p[0])
|
1410 |
+
ynew = _adaptive_eval(f, xnew)
|
1411 |
+
new_point = np.array([xnew, ynew])
|
1412 |
+
|
1413 |
+
# Maximum depth
|
1414 |
+
if depth > self.depth:
|
1415 |
+
x_coords.append(q[0])
|
1416 |
+
y_coords.append(q[1])
|
1417 |
+
|
1418 |
+
# Sample to depth of 6 (whether the line is flat or not)
|
1419 |
+
# without using linspace (to avoid aliasing).
|
1420 |
+
elif depth < 6:
|
1421 |
+
sample(p, new_point, depth + 1)
|
1422 |
+
sample(new_point, q, depth + 1)
|
1423 |
+
|
1424 |
+
# Sample ten points if complex values are encountered
|
1425 |
+
# at both ends. If there is a real value in between, then
|
1426 |
+
# sample those points further.
|
1427 |
+
elif p[1] is None and q[1] is None:
|
1428 |
+
if self.xscale == 'log':
|
1429 |
+
xarray = np.logspace(p[0], q[0], 10)
|
1430 |
+
else:
|
1431 |
+
xarray = np.linspace(p[0], q[0], 10)
|
1432 |
+
yarray = list(map(f, xarray))
|
1433 |
+
if not all(y is None for y in yarray):
|
1434 |
+
for i in range(len(yarray) - 1):
|
1435 |
+
if not (yarray[i] is None and yarray[i + 1] is None):
|
1436 |
+
sample([xarray[i], yarray[i]],
|
1437 |
+
[xarray[i + 1], yarray[i + 1]], depth + 1)
|
1438 |
+
|
1439 |
+
# Sample further if one of the end points in None (i.e. a
|
1440 |
+
# complex value) or the three points are not almost collinear.
|
1441 |
+
elif (p[1] is None or q[1] is None or new_point[1] is None
|
1442 |
+
or not flat(p, new_point, q)):
|
1443 |
+
sample(p, new_point, depth + 1)
|
1444 |
+
sample(new_point, q, depth + 1)
|
1445 |
+
else:
|
1446 |
+
x_coords.append(q[0])
|
1447 |
+
y_coords.append(q[1])
|
1448 |
+
|
1449 |
+
f_start = _adaptive_eval(f, self.start.real)
|
1450 |
+
f_end = _adaptive_eval(f, self.end.real)
|
1451 |
+
x_coords.append(self.start.real)
|
1452 |
+
y_coords.append(f_start)
|
1453 |
+
sample(np.array([self.start.real, f_start]),
|
1454 |
+
np.array([self.end.real, f_end]), 0)
|
1455 |
+
|
1456 |
+
return (x_coords, y_coords)
|
1457 |
+
|
1458 |
+
def _uniform_sampling(self):
|
1459 |
+
np = import_module('numpy')
|
1460 |
+
|
1461 |
+
x, result = self._evaluate()
|
1462 |
+
_re, _im = np.real(result), np.imag(result)
|
1463 |
+
_re = self._correct_shape(_re, x)
|
1464 |
+
_im = self._correct_shape(_im, x)
|
1465 |
+
return x, _re, _im
|
1466 |
+
|
1467 |
+
def _get_data_helper(self):
|
1468 |
+
"""Returns coordinates that needs to be postprocessed.
|
1469 |
+
"""
|
1470 |
+
np = import_module('numpy')
|
1471 |
+
if self.adaptive and (not self.only_integers):
|
1472 |
+
x, y = self._adaptive_sampling()
|
1473 |
+
return [np.array(t) for t in [x, y]]
|
1474 |
+
|
1475 |
+
x, _re, _im = self._uniform_sampling()
|
1476 |
+
|
1477 |
+
if self._return is None:
|
1478 |
+
# The evaluation could produce complex numbers. Set real elements
|
1479 |
+
# to NaN where there are non-zero imaginary elements
|
1480 |
+
_re[np.invert(np.isclose(_im, np.zeros_like(_im)))] = np.nan
|
1481 |
+
elif self._return == "real":
|
1482 |
+
pass
|
1483 |
+
elif self._return == "imag":
|
1484 |
+
_re = _im
|
1485 |
+
elif self._return == "abs":
|
1486 |
+
_re = np.sqrt(_re**2 + _im**2)
|
1487 |
+
elif self._return == "arg":
|
1488 |
+
_re = np.arctan2(_im, _re)
|
1489 |
+
else:
|
1490 |
+
raise ValueError("`_return` not recognized. "
|
1491 |
+
"Received: %s" % self._return)
|
1492 |
+
|
1493 |
+
return x, _re
|
1494 |
+
|
1495 |
+
|
1496 |
+
class ParametricLineBaseSeries(Line2DBaseSeries):
|
1497 |
+
is_parametric = True
|
1498 |
+
|
1499 |
+
def _set_parametric_line_label(self, label):
|
1500 |
+
"""Logic to set the correct label to be shown on the plot.
|
1501 |
+
If `use_cm=True` there will be a colorbar, so we show the parameter.
|
1502 |
+
If `use_cm=False`, there might be a legend, so we show the expressions.
|
1503 |
+
|
1504 |
+
Parameters
|
1505 |
+
==========
|
1506 |
+
label : str
|
1507 |
+
label passed in by the pre-processor or the user
|
1508 |
+
"""
|
1509 |
+
self._label = str(self.var) if label is None else label
|
1510 |
+
self._latex_label = latex(self.var) if label is None else label
|
1511 |
+
if (self.use_cm is False) and (self._label == str(self.var)):
|
1512 |
+
self._label = str(self.expr)
|
1513 |
+
self._latex_label = latex(self.expr)
|
1514 |
+
# if the expressions is a lambda function and use_cm=False and no label
|
1515 |
+
# has been provided, then its better to do the following in order to
|
1516 |
+
# avoid suprises on the backend
|
1517 |
+
if any(callable(e) for e in self.expr) and (not self.use_cm):
|
1518 |
+
if self._label == str(self.expr):
|
1519 |
+
self._label = ""
|
1520 |
+
|
1521 |
+
def get_label(self, use_latex=False, wrapper="$%s$"):
|
1522 |
+
# parametric lines returns the representation of the parameter to be
|
1523 |
+
# shown on the colorbar if `use_cm=True`, otherwise it returns the
|
1524 |
+
# representation of the expression to be placed on the legend.
|
1525 |
+
if self.use_cm:
|
1526 |
+
if str(self.var) == self._label:
|
1527 |
+
if use_latex:
|
1528 |
+
return self._get_wrapped_label(latex(self.var), wrapper)
|
1529 |
+
return str(self.var)
|
1530 |
+
# here the user has provided a custom label
|
1531 |
+
return self._label
|
1532 |
+
if use_latex:
|
1533 |
+
if self._label != str(self.expr):
|
1534 |
+
return self._latex_label
|
1535 |
+
return self._get_wrapped_label(self._latex_label, wrapper)
|
1536 |
+
return self._label
|
1537 |
+
|
1538 |
+
def _get_data_helper(self):
|
1539 |
+
"""Returns coordinates that needs to be postprocessed.
|
1540 |
+
Depending on the `adaptive` option, this function will either use an
|
1541 |
+
adaptive algorithm or it will uniformly sample the expression over the
|
1542 |
+
provided range.
|
1543 |
+
"""
|
1544 |
+
if self.adaptive:
|
1545 |
+
np = import_module("numpy")
|
1546 |
+
coords = self._adaptive_sampling()
|
1547 |
+
coords = [np.array(t) for t in coords]
|
1548 |
+
else:
|
1549 |
+
coords = self._uniform_sampling()
|
1550 |
+
|
1551 |
+
if self.is_2Dline and self.is_polar:
|
1552 |
+
# when plot_polar is executed with polar_axis=True
|
1553 |
+
np = import_module('numpy')
|
1554 |
+
x, y, _ = coords
|
1555 |
+
r = np.sqrt(x**2 + y**2)
|
1556 |
+
t = np.arctan2(y, x)
|
1557 |
+
coords = [t, r, coords[-1]]
|
1558 |
+
|
1559 |
+
if callable(self.color_func):
|
1560 |
+
coords = list(coords)
|
1561 |
+
coords[-1] = self.eval_color_func(*coords)
|
1562 |
+
|
1563 |
+
return coords
|
1564 |
+
|
1565 |
+
def _uniform_sampling(self):
|
1566 |
+
"""Returns coordinates that needs to be postprocessed."""
|
1567 |
+
np = import_module('numpy')
|
1568 |
+
|
1569 |
+
results = self._evaluate()
|
1570 |
+
for i, r in enumerate(results):
|
1571 |
+
_re, _im = np.real(r), np.imag(r)
|
1572 |
+
_re[np.invert(np.isclose(_im, np.zeros_like(_im)))] = np.nan
|
1573 |
+
results[i] = _re
|
1574 |
+
|
1575 |
+
return [*results[1:], results[0]]
|
1576 |
+
|
1577 |
+
def get_parameter_points(self):
|
1578 |
+
return self.get_data()[-1]
|
1579 |
+
|
1580 |
+
def get_points(self):
|
1581 |
+
""" Return lists of coordinates for plotting. Depending on the
|
1582 |
+
``adaptive`` option, this function will either use an adaptive algorithm
|
1583 |
+
or it will uniformly sample the expression over the provided range.
|
1584 |
+
|
1585 |
+
This function is available for back-compatibility purposes. Consider
|
1586 |
+
using ``get_data()`` instead.
|
1587 |
+
|
1588 |
+
Returns
|
1589 |
+
=======
|
1590 |
+
x : list
|
1591 |
+
List of x-coordinates
|
1592 |
+
y : list
|
1593 |
+
List of y-coordinates
|
1594 |
+
z : list
|
1595 |
+
List of z-coordinates, only for 3D parametric line plot.
|
1596 |
+
"""
|
1597 |
+
return self._get_data_helper()[:-1]
|
1598 |
+
|
1599 |
+
@property
|
1600 |
+
def nb_of_points(self):
|
1601 |
+
return self.n[0]
|
1602 |
+
|
1603 |
+
@nb_of_points.setter
|
1604 |
+
def nb_of_points(self, v):
|
1605 |
+
self.n = v
|
1606 |
+
|
1607 |
+
|
1608 |
+
class Parametric2DLineSeries(ParametricLineBaseSeries):
|
1609 |
+
"""Representation for a line consisting of two parametric SymPy expressions
|
1610 |
+
over a range."""
|
1611 |
+
|
1612 |
+
is_2Dline = True
|
1613 |
+
|
1614 |
+
def __init__(self, expr_x, expr_y, var_start_end, label="", **kwargs):
|
1615 |
+
super().__init__(**kwargs)
|
1616 |
+
self.expr_x = expr_x if callable(expr_x) else sympify(expr_x)
|
1617 |
+
self.expr_y = expr_y if callable(expr_y) else sympify(expr_y)
|
1618 |
+
self.expr = (self.expr_x, self.expr_y)
|
1619 |
+
self.ranges = [var_start_end]
|
1620 |
+
self._cast = float
|
1621 |
+
self.use_cm = kwargs.get("use_cm", True)
|
1622 |
+
self._set_parametric_line_label(label)
|
1623 |
+
self._post_init()
|
1624 |
+
|
1625 |
+
def __str__(self):
|
1626 |
+
return self._str_helper(
|
1627 |
+
"parametric cartesian line: (%s, %s) for %s over %s" % (
|
1628 |
+
str(self.expr_x),
|
1629 |
+
str(self.expr_y),
|
1630 |
+
str(self.var),
|
1631 |
+
str((self.start, self.end))
|
1632 |
+
))
|
1633 |
+
|
1634 |
+
def _adaptive_sampling(self):
|
1635 |
+
try:
|
1636 |
+
if callable(self.expr_x) and callable(self.expr_y):
|
1637 |
+
f_x = self.expr_x
|
1638 |
+
f_y = self.expr_y
|
1639 |
+
else:
|
1640 |
+
f_x = lambdify([self.var], self.expr_x)
|
1641 |
+
f_y = lambdify([self.var], self.expr_y)
|
1642 |
+
x, y, p = self._adaptive_sampling_helper(f_x, f_y)
|
1643 |
+
except Exception as err:
|
1644 |
+
warnings.warn(
|
1645 |
+
"The evaluation with %s failed.\n" % (
|
1646 |
+
"NumPy/SciPy" if not self.modules else self.modules) +
|
1647 |
+
"{}: {}\n".format(type(err).__name__, err) +
|
1648 |
+
"Trying to evaluate the expression with Sympy, but it might "
|
1649 |
+
"be a slow operation."
|
1650 |
+
)
|
1651 |
+
f_x = lambdify([self.var], self.expr_x, "sympy")
|
1652 |
+
f_y = lambdify([self.var], self.expr_y, "sympy")
|
1653 |
+
x, y, p = self._adaptive_sampling_helper(f_x, f_y)
|
1654 |
+
return x, y, p
|
1655 |
+
|
1656 |
+
def _adaptive_sampling_helper(self, f_x, f_y):
|
1657 |
+
"""The adaptive sampling is done by recursively checking if three
|
1658 |
+
points are almost collinear. If they are not collinear, then more
|
1659 |
+
points are added between those points.
|
1660 |
+
|
1661 |
+
References
|
1662 |
+
==========
|
1663 |
+
|
1664 |
+
.. [1] Adaptive polygonal approximation of parametric curves,
|
1665 |
+
Luiz Henrique de Figueiredo.
|
1666 |
+
"""
|
1667 |
+
x_coords = []
|
1668 |
+
y_coords = []
|
1669 |
+
param = []
|
1670 |
+
|
1671 |
+
def sample(param_p, param_q, p, q, depth):
|
1672 |
+
""" Samples recursively if three points are almost collinear.
|
1673 |
+
For depth < 6, points are added irrespective of whether they
|
1674 |
+
satisfy the collinearity condition or not. The maximum depth
|
1675 |
+
allowed is 12.
|
1676 |
+
"""
|
1677 |
+
# Randomly sample to avoid aliasing.
|
1678 |
+
np = import_module('numpy')
|
1679 |
+
random = 0.45 + np.random.rand() * 0.1
|
1680 |
+
param_new = param_p + random * (param_q - param_p)
|
1681 |
+
xnew = _adaptive_eval(f_x, param_new)
|
1682 |
+
ynew = _adaptive_eval(f_y, param_new)
|
1683 |
+
new_point = np.array([xnew, ynew])
|
1684 |
+
|
1685 |
+
# Maximum depth
|
1686 |
+
if depth > self.depth:
|
1687 |
+
x_coords.append(q[0])
|
1688 |
+
y_coords.append(q[1])
|
1689 |
+
param.append(param_p)
|
1690 |
+
|
1691 |
+
# Sample irrespective of whether the line is flat till the
|
1692 |
+
# depth of 6. We are not using linspace to avoid aliasing.
|
1693 |
+
elif depth < 6:
|
1694 |
+
sample(param_p, param_new, p, new_point, depth + 1)
|
1695 |
+
sample(param_new, param_q, new_point, q, depth + 1)
|
1696 |
+
|
1697 |
+
# Sample ten points if complex values are encountered
|
1698 |
+
# at both ends. If there is a real value in between, then
|
1699 |
+
# sample those points further.
|
1700 |
+
elif ((p[0] is None and q[1] is None) or
|
1701 |
+
(p[1] is None and q[1] is None)):
|
1702 |
+
param_array = np.linspace(param_p, param_q, 10)
|
1703 |
+
x_array = [_adaptive_eval(f_x, t) for t in param_array]
|
1704 |
+
y_array = [_adaptive_eval(f_y, t) for t in param_array]
|
1705 |
+
if not all(x is None and y is None
|
1706 |
+
for x, y in zip(x_array, y_array)):
|
1707 |
+
for i in range(len(y_array) - 1):
|
1708 |
+
if ((x_array[i] is not None and y_array[i] is not None) or
|
1709 |
+
(x_array[i + 1] is not None and y_array[i + 1] is not None)):
|
1710 |
+
point_a = [x_array[i], y_array[i]]
|
1711 |
+
point_b = [x_array[i + 1], y_array[i + 1]]
|
1712 |
+
sample(param_array[i], param_array[i], point_a,
|
1713 |
+
point_b, depth + 1)
|
1714 |
+
|
1715 |
+
# Sample further if one of the end points in None (i.e. a complex
|
1716 |
+
# value) or the three points are not almost collinear.
|
1717 |
+
elif (p[0] is None or p[1] is None
|
1718 |
+
or q[1] is None or q[0] is None
|
1719 |
+
or not flat(p, new_point, q)):
|
1720 |
+
sample(param_p, param_new, p, new_point, depth + 1)
|
1721 |
+
sample(param_new, param_q, new_point, q, depth + 1)
|
1722 |
+
else:
|
1723 |
+
x_coords.append(q[0])
|
1724 |
+
y_coords.append(q[1])
|
1725 |
+
param.append(param_p)
|
1726 |
+
|
1727 |
+
f_start_x = _adaptive_eval(f_x, self.start)
|
1728 |
+
f_start_y = _adaptive_eval(f_y, self.start)
|
1729 |
+
start = [f_start_x, f_start_y]
|
1730 |
+
f_end_x = _adaptive_eval(f_x, self.end)
|
1731 |
+
f_end_y = _adaptive_eval(f_y, self.end)
|
1732 |
+
end = [f_end_x, f_end_y]
|
1733 |
+
x_coords.append(f_start_x)
|
1734 |
+
y_coords.append(f_start_y)
|
1735 |
+
param.append(self.start)
|
1736 |
+
sample(self.start, self.end, start, end, 0)
|
1737 |
+
|
1738 |
+
return x_coords, y_coords, param
|
1739 |
+
|
1740 |
+
|
1741 |
+
### 3D lines
|
1742 |
+
class Line3DBaseSeries(Line2DBaseSeries):
|
1743 |
+
"""A base class for 3D lines.
|
1744 |
+
|
1745 |
+
Most of the stuff is derived from Line2DBaseSeries."""
|
1746 |
+
|
1747 |
+
is_2Dline = False
|
1748 |
+
is_3Dline = True
|
1749 |
+
_dim = 3
|
1750 |
+
|
1751 |
+
def __init__(self):
|
1752 |
+
super().__init__()
|
1753 |
+
|
1754 |
+
|
1755 |
+
class Parametric3DLineSeries(ParametricLineBaseSeries):
|
1756 |
+
"""Representation for a 3D line consisting of three parametric SymPy
|
1757 |
+
expressions and a range."""
|
1758 |
+
|
1759 |
+
is_2Dline = False
|
1760 |
+
is_3Dline = True
|
1761 |
+
|
1762 |
+
def __init__(self, expr_x, expr_y, expr_z, var_start_end, label="", **kwargs):
|
1763 |
+
super().__init__(**kwargs)
|
1764 |
+
self.expr_x = expr_x if callable(expr_x) else sympify(expr_x)
|
1765 |
+
self.expr_y = expr_y if callable(expr_y) else sympify(expr_y)
|
1766 |
+
self.expr_z = expr_z if callable(expr_z) else sympify(expr_z)
|
1767 |
+
self.expr = (self.expr_x, self.expr_y, self.expr_z)
|
1768 |
+
self.ranges = [var_start_end]
|
1769 |
+
self._cast = float
|
1770 |
+
self.adaptive = False
|
1771 |
+
self.use_cm = kwargs.get("use_cm", True)
|
1772 |
+
self._set_parametric_line_label(label)
|
1773 |
+
self._post_init()
|
1774 |
+
# TODO: remove this
|
1775 |
+
self._xlim = None
|
1776 |
+
self._ylim = None
|
1777 |
+
self._zlim = None
|
1778 |
+
|
1779 |
+
def __str__(self):
|
1780 |
+
return self._str_helper(
|
1781 |
+
"3D parametric cartesian line: (%s, %s, %s) for %s over %s" % (
|
1782 |
+
str(self.expr_x),
|
1783 |
+
str(self.expr_y),
|
1784 |
+
str(self.expr_z),
|
1785 |
+
str(self.var),
|
1786 |
+
str((self.start, self.end))
|
1787 |
+
))
|
1788 |
+
|
1789 |
+
def get_data(self):
|
1790 |
+
# TODO: remove this
|
1791 |
+
np = import_module("numpy")
|
1792 |
+
x, y, z, p = super().get_data()
|
1793 |
+
self._xlim = (np.amin(x), np.amax(x))
|
1794 |
+
self._ylim = (np.amin(y), np.amax(y))
|
1795 |
+
self._zlim = (np.amin(z), np.amax(z))
|
1796 |
+
return x, y, z, p
|
1797 |
+
|
1798 |
+
|
1799 |
+
### Surfaces
|
1800 |
+
class SurfaceBaseSeries(BaseSeries):
|
1801 |
+
"""A base class for 3D surfaces."""
|
1802 |
+
|
1803 |
+
is_3Dsurface = True
|
1804 |
+
|
1805 |
+
def __init__(self, *args, **kwargs):
|
1806 |
+
super().__init__(**kwargs)
|
1807 |
+
self.use_cm = kwargs.get("use_cm", False)
|
1808 |
+
# NOTE: why should SurfaceOver2DRangeSeries support is polar?
|
1809 |
+
# After all, the same result can be achieve with
|
1810 |
+
# ParametricSurfaceSeries. For example:
|
1811 |
+
# sin(r) for (r, 0, 2 * pi) and (theta, 0, pi/2) can be parameterized
|
1812 |
+
# as (r * cos(theta), r * sin(theta), sin(t)) for (r, 0, 2 * pi) and
|
1813 |
+
# (theta, 0, pi/2).
|
1814 |
+
# Because it is faster to evaluate (important for interactive plots).
|
1815 |
+
self.is_polar = kwargs.get("is_polar", kwargs.get("polar", False))
|
1816 |
+
self.surface_color = kwargs.get("surface_color", None)
|
1817 |
+
self.color_func = kwargs.get("color_func", lambda x, y, z: z)
|
1818 |
+
if callable(self.surface_color):
|
1819 |
+
self.color_func = self.surface_color
|
1820 |
+
self.surface_color = None
|
1821 |
+
|
1822 |
+
def _set_surface_label(self, label):
|
1823 |
+
exprs = self.expr
|
1824 |
+
self._label = str(exprs) if label is None else label
|
1825 |
+
self._latex_label = latex(exprs) if label is None else label
|
1826 |
+
# if the expressions is a lambda function and no label
|
1827 |
+
# has been provided, then its better to do the following to avoid
|
1828 |
+
# suprises on the backend
|
1829 |
+
is_lambda = (callable(exprs) if not hasattr(exprs, "__iter__")
|
1830 |
+
else any(callable(e) for e in exprs))
|
1831 |
+
if is_lambda and (self._label == str(exprs)):
|
1832 |
+
self._label = ""
|
1833 |
+
self._latex_label = ""
|
1834 |
+
|
1835 |
+
def get_color_array(self):
|
1836 |
+
np = import_module('numpy')
|
1837 |
+
c = self.surface_color
|
1838 |
+
if isinstance(c, Callable):
|
1839 |
+
f = np.vectorize(c)
|
1840 |
+
nargs = arity(c)
|
1841 |
+
if self.is_parametric:
|
1842 |
+
variables = list(map(centers_of_faces, self.get_parameter_meshes()))
|
1843 |
+
if nargs == 1:
|
1844 |
+
return f(variables[0])
|
1845 |
+
elif nargs == 2:
|
1846 |
+
return f(*variables)
|
1847 |
+
variables = list(map(centers_of_faces, self.get_meshes()))
|
1848 |
+
if nargs == 1:
|
1849 |
+
return f(variables[0])
|
1850 |
+
elif nargs == 2:
|
1851 |
+
return f(*variables[:2])
|
1852 |
+
else:
|
1853 |
+
return f(*variables)
|
1854 |
+
else:
|
1855 |
+
if isinstance(self, SurfaceOver2DRangeSeries):
|
1856 |
+
return c*np.ones(min(self.nb_of_points_x, self.nb_of_points_y))
|
1857 |
+
else:
|
1858 |
+
return c*np.ones(min(self.nb_of_points_u, self.nb_of_points_v))
|
1859 |
+
|
1860 |
+
|
1861 |
+
class SurfaceOver2DRangeSeries(SurfaceBaseSeries):
|
1862 |
+
"""Representation for a 3D surface consisting of a SymPy expression and 2D
|
1863 |
+
range."""
|
1864 |
+
|
1865 |
+
def __init__(self, expr, var_start_end_x, var_start_end_y, label="", **kwargs):
|
1866 |
+
super().__init__(**kwargs)
|
1867 |
+
self.expr = expr if callable(expr) else sympify(expr)
|
1868 |
+
self.ranges = [var_start_end_x, var_start_end_y]
|
1869 |
+
self._set_surface_label(label)
|
1870 |
+
self._post_init()
|
1871 |
+
# TODO: remove this
|
1872 |
+
self._xlim = (self.start_x, self.end_x)
|
1873 |
+
self._ylim = (self.start_y, self.end_y)
|
1874 |
+
|
1875 |
+
@property
|
1876 |
+
def var_x(self):
|
1877 |
+
return self.ranges[0][0]
|
1878 |
+
|
1879 |
+
@property
|
1880 |
+
def var_y(self):
|
1881 |
+
return self.ranges[1][0]
|
1882 |
+
|
1883 |
+
@property
|
1884 |
+
def start_x(self):
|
1885 |
+
try:
|
1886 |
+
return float(self.ranges[0][1])
|
1887 |
+
except TypeError:
|
1888 |
+
return self.ranges[0][1]
|
1889 |
+
|
1890 |
+
@property
|
1891 |
+
def end_x(self):
|
1892 |
+
try:
|
1893 |
+
return float(self.ranges[0][2])
|
1894 |
+
except TypeError:
|
1895 |
+
return self.ranges[0][2]
|
1896 |
+
|
1897 |
+
@property
|
1898 |
+
def start_y(self):
|
1899 |
+
try:
|
1900 |
+
return float(self.ranges[1][1])
|
1901 |
+
except TypeError:
|
1902 |
+
return self.ranges[1][1]
|
1903 |
+
|
1904 |
+
@property
|
1905 |
+
def end_y(self):
|
1906 |
+
try:
|
1907 |
+
return float(self.ranges[1][2])
|
1908 |
+
except TypeError:
|
1909 |
+
return self.ranges[1][2]
|
1910 |
+
|
1911 |
+
@property
|
1912 |
+
def nb_of_points_x(self):
|
1913 |
+
return self.n[0]
|
1914 |
+
|
1915 |
+
@nb_of_points_x.setter
|
1916 |
+
def nb_of_points_x(self, v):
|
1917 |
+
n = self.n
|
1918 |
+
self.n = [v, n[1:]]
|
1919 |
+
|
1920 |
+
@property
|
1921 |
+
def nb_of_points_y(self):
|
1922 |
+
return self.n[1]
|
1923 |
+
|
1924 |
+
@nb_of_points_y.setter
|
1925 |
+
def nb_of_points_y(self, v):
|
1926 |
+
n = self.n
|
1927 |
+
self.n = [n[0], v, n[2]]
|
1928 |
+
|
1929 |
+
def __str__(self):
|
1930 |
+
series_type = "cartesian surface" if self.is_3Dsurface else "contour"
|
1931 |
+
return self._str_helper(
|
1932 |
+
series_type + ": %s for" " %s over %s and %s over %s" % (
|
1933 |
+
str(self.expr),
|
1934 |
+
str(self.var_x), str((self.start_x, self.end_x)),
|
1935 |
+
str(self.var_y), str((self.start_y, self.end_y)),
|
1936 |
+
))
|
1937 |
+
|
1938 |
+
def get_meshes(self):
|
1939 |
+
"""Return the x,y,z coordinates for plotting the surface.
|
1940 |
+
This function is available for back-compatibility purposes. Consider
|
1941 |
+
using ``get_data()`` instead.
|
1942 |
+
"""
|
1943 |
+
return self.get_data()
|
1944 |
+
|
1945 |
+
def get_data(self):
|
1946 |
+
"""Return arrays of coordinates for plotting.
|
1947 |
+
|
1948 |
+
Returns
|
1949 |
+
=======
|
1950 |
+
mesh_x : np.ndarray
|
1951 |
+
Discretized x-domain.
|
1952 |
+
mesh_y : np.ndarray
|
1953 |
+
Discretized y-domain.
|
1954 |
+
mesh_z : np.ndarray
|
1955 |
+
Results of the evaluation.
|
1956 |
+
"""
|
1957 |
+
np = import_module('numpy')
|
1958 |
+
|
1959 |
+
results = self._evaluate()
|
1960 |
+
# mask out complex values
|
1961 |
+
for i, r in enumerate(results):
|
1962 |
+
_re, _im = np.real(r), np.imag(r)
|
1963 |
+
_re[np.invert(np.isclose(_im, np.zeros_like(_im)))] = np.nan
|
1964 |
+
results[i] = _re
|
1965 |
+
|
1966 |
+
x, y, z = results
|
1967 |
+
if self.is_polar and self.is_3Dsurface:
|
1968 |
+
r = x.copy()
|
1969 |
+
x = r * np.cos(y)
|
1970 |
+
y = r * np.sin(y)
|
1971 |
+
|
1972 |
+
# TODO: remove this
|
1973 |
+
self._zlim = (np.amin(z), np.amax(z))
|
1974 |
+
|
1975 |
+
return self._apply_transform(x, y, z)
|
1976 |
+
|
1977 |
+
|
1978 |
+
class ParametricSurfaceSeries(SurfaceBaseSeries):
|
1979 |
+
"""Representation for a 3D surface consisting of three parametric SymPy
|
1980 |
+
expressions and a range."""
|
1981 |
+
|
1982 |
+
is_parametric = True
|
1983 |
+
|
1984 |
+
def __init__(self, expr_x, expr_y, expr_z,
|
1985 |
+
var_start_end_u, var_start_end_v, label="", **kwargs):
|
1986 |
+
super().__init__(**kwargs)
|
1987 |
+
self.expr_x = expr_x if callable(expr_x) else sympify(expr_x)
|
1988 |
+
self.expr_y = expr_y if callable(expr_y) else sympify(expr_y)
|
1989 |
+
self.expr_z = expr_z if callable(expr_z) else sympify(expr_z)
|
1990 |
+
self.expr = (self.expr_x, self.expr_y, self.expr_z)
|
1991 |
+
self.ranges = [var_start_end_u, var_start_end_v]
|
1992 |
+
self.color_func = kwargs.get("color_func", lambda x, y, z, u, v: z)
|
1993 |
+
self._set_surface_label(label)
|
1994 |
+
self._post_init()
|
1995 |
+
|
1996 |
+
@property
|
1997 |
+
def var_u(self):
|
1998 |
+
return self.ranges[0][0]
|
1999 |
+
|
2000 |
+
@property
|
2001 |
+
def var_v(self):
|
2002 |
+
return self.ranges[1][0]
|
2003 |
+
|
2004 |
+
@property
|
2005 |
+
def start_u(self):
|
2006 |
+
try:
|
2007 |
+
return float(self.ranges[0][1])
|
2008 |
+
except TypeError:
|
2009 |
+
return self.ranges[0][1]
|
2010 |
+
|
2011 |
+
@property
|
2012 |
+
def end_u(self):
|
2013 |
+
try:
|
2014 |
+
return float(self.ranges[0][2])
|
2015 |
+
except TypeError:
|
2016 |
+
return self.ranges[0][2]
|
2017 |
+
|
2018 |
+
@property
|
2019 |
+
def start_v(self):
|
2020 |
+
try:
|
2021 |
+
return float(self.ranges[1][1])
|
2022 |
+
except TypeError:
|
2023 |
+
return self.ranges[1][1]
|
2024 |
+
|
2025 |
+
@property
|
2026 |
+
def end_v(self):
|
2027 |
+
try:
|
2028 |
+
return float(self.ranges[1][2])
|
2029 |
+
except TypeError:
|
2030 |
+
return self.ranges[1][2]
|
2031 |
+
|
2032 |
+
@property
|
2033 |
+
def nb_of_points_u(self):
|
2034 |
+
return self.n[0]
|
2035 |
+
|
2036 |
+
@nb_of_points_u.setter
|
2037 |
+
def nb_of_points_u(self, v):
|
2038 |
+
n = self.n
|
2039 |
+
self.n = [v, n[1:]]
|
2040 |
+
|
2041 |
+
@property
|
2042 |
+
def nb_of_points_v(self):
|
2043 |
+
return self.n[1]
|
2044 |
+
|
2045 |
+
@nb_of_points_v.setter
|
2046 |
+
def nb_of_points_v(self, v):
|
2047 |
+
n = self.n
|
2048 |
+
self.n = [n[0], v, n[2]]
|
2049 |
+
|
2050 |
+
def __str__(self):
|
2051 |
+
return self._str_helper(
|
2052 |
+
"parametric cartesian surface: (%s, %s, %s) for"
|
2053 |
+
" %s over %s and %s over %s" % (
|
2054 |
+
str(self.expr_x), str(self.expr_y), str(self.expr_z),
|
2055 |
+
str(self.var_u), str((self.start_u, self.end_u)),
|
2056 |
+
str(self.var_v), str((self.start_v, self.end_v)),
|
2057 |
+
))
|
2058 |
+
|
2059 |
+
def get_parameter_meshes(self):
|
2060 |
+
return self.get_data()[3:]
|
2061 |
+
|
2062 |
+
def get_meshes(self):
|
2063 |
+
"""Return the x,y,z coordinates for plotting the surface.
|
2064 |
+
This function is available for back-compatibility purposes. Consider
|
2065 |
+
using ``get_data()`` instead.
|
2066 |
+
"""
|
2067 |
+
return self.get_data()[:3]
|
2068 |
+
|
2069 |
+
def get_data(self):
|
2070 |
+
"""Return arrays of coordinates for plotting.
|
2071 |
+
|
2072 |
+
Returns
|
2073 |
+
=======
|
2074 |
+
x : np.ndarray [n2 x n1]
|
2075 |
+
x-coordinates.
|
2076 |
+
y : np.ndarray [n2 x n1]
|
2077 |
+
y-coordinates.
|
2078 |
+
z : np.ndarray [n2 x n1]
|
2079 |
+
z-coordinates.
|
2080 |
+
mesh_u : np.ndarray [n2 x n1]
|
2081 |
+
Discretized u range.
|
2082 |
+
mesh_v : np.ndarray [n2 x n1]
|
2083 |
+
Discretized v range.
|
2084 |
+
"""
|
2085 |
+
np = import_module('numpy')
|
2086 |
+
|
2087 |
+
results = self._evaluate()
|
2088 |
+
# mask out complex values
|
2089 |
+
for i, r in enumerate(results):
|
2090 |
+
_re, _im = np.real(r), np.imag(r)
|
2091 |
+
_re[np.invert(np.isclose(_im, np.zeros_like(_im)))] = np.nan
|
2092 |
+
results[i] = _re
|
2093 |
+
|
2094 |
+
# TODO: remove this
|
2095 |
+
x, y, z = results[2:]
|
2096 |
+
self._xlim = (np.amin(x), np.amax(x))
|
2097 |
+
self._ylim = (np.amin(y), np.amax(y))
|
2098 |
+
self._zlim = (np.amin(z), np.amax(z))
|
2099 |
+
|
2100 |
+
return self._apply_transform(*results[2:], *results[:2])
|
2101 |
+
|
2102 |
+
|
2103 |
+
### Contours
|
2104 |
+
class ContourSeries(SurfaceOver2DRangeSeries):
|
2105 |
+
"""Representation for a contour plot."""
|
2106 |
+
|
2107 |
+
is_3Dsurface = False
|
2108 |
+
is_contour = True
|
2109 |
+
|
2110 |
+
def __init__(self, *args, **kwargs):
|
2111 |
+
super().__init__(*args, **kwargs)
|
2112 |
+
self.is_filled = kwargs.get("is_filled", kwargs.get("fill", True))
|
2113 |
+
self.show_clabels = kwargs.get("clabels", True)
|
2114 |
+
|
2115 |
+
# NOTE: contour plots are used by plot_contour, plot_vector and
|
2116 |
+
# plot_complex_vector. By implementing contour_kw we are able to
|
2117 |
+
# quickly target the contour plot.
|
2118 |
+
self.rendering_kw = kwargs.get("contour_kw",
|
2119 |
+
kwargs.get("rendering_kw", {}))
|
2120 |
+
|
2121 |
+
|
2122 |
+
class GenericDataSeries(BaseSeries):
|
2123 |
+
"""Represents generic numerical data.
|
2124 |
+
|
2125 |
+
Notes
|
2126 |
+
=====
|
2127 |
+
This class serves the purpose of back-compatibility with the "markers,
|
2128 |
+
annotations, fill, rectangles" keyword arguments that represent
|
2129 |
+
user-provided numerical data. In particular, it solves the problem of
|
2130 |
+
combining together two or more plot-objects with the ``extend`` or
|
2131 |
+
``append`` methods: user-provided numerical data is also taken into
|
2132 |
+
consideration because it is stored in this series class.
|
2133 |
+
|
2134 |
+
Also note that the current implementation is far from optimal, as each
|
2135 |
+
keyword argument is stored into an attribute in the ``Plot`` class, which
|
2136 |
+
requires a hard-coded if-statement in the ``MatplotlibBackend`` class.
|
2137 |
+
The implementation suggests that it is ok to add attributes and
|
2138 |
+
if-statements to provide more and more functionalities for user-provided
|
2139 |
+
numerical data (e.g. adding horizontal lines, or vertical lines, or bar
|
2140 |
+
plots, etc). However, in doing so one would reinvent the wheel: plotting
|
2141 |
+
libraries (like Matplotlib) already implements the necessary API.
|
2142 |
+
|
2143 |
+
Instead of adding more keyword arguments and attributes, users interested
|
2144 |
+
in adding custom numerical data to a plot should retrieve the figure
|
2145 |
+
created by this plotting module. For example, this code:
|
2146 |
+
|
2147 |
+
.. plot::
|
2148 |
+
:context: close-figs
|
2149 |
+
:include-source: True
|
2150 |
+
|
2151 |
+
from sympy import Symbol, plot, cos
|
2152 |
+
x = Symbol("x")
|
2153 |
+
p = plot(cos(x), markers=[{"args": [[0, 1, 2], [0, 1, -1], "*"]}])
|
2154 |
+
|
2155 |
+
Becomes:
|
2156 |
+
|
2157 |
+
.. plot::
|
2158 |
+
:context: close-figs
|
2159 |
+
:include-source: True
|
2160 |
+
|
2161 |
+
p = plot(cos(x), backend="matplotlib")
|
2162 |
+
fig, ax = p._backend.fig, p._backend.ax[0]
|
2163 |
+
ax.plot([0, 1, 2], [0, 1, -1], "*")
|
2164 |
+
fig
|
2165 |
+
|
2166 |
+
Which is far better in terms of readibility. Also, it gives access to the
|
2167 |
+
full plotting library capabilities, without the need to reinvent the wheel.
|
2168 |
+
"""
|
2169 |
+
is_generic = True
|
2170 |
+
|
2171 |
+
def __init__(self, tp, *args, **kwargs):
|
2172 |
+
self.type = tp
|
2173 |
+
self.args = args
|
2174 |
+
self.rendering_kw = kwargs
|
2175 |
+
|
2176 |
+
def get_data(self):
|
2177 |
+
return self.args
|
2178 |
+
|
2179 |
+
|
2180 |
+
class ImplicitSeries(BaseSeries):
|
2181 |
+
"""Representation for 2D Implicit plot."""
|
2182 |
+
|
2183 |
+
is_implicit = True
|
2184 |
+
use_cm = False
|
2185 |
+
_N = 100
|
2186 |
+
|
2187 |
+
def __init__(self, expr, var_start_end_x, var_start_end_y, label="", **kwargs):
|
2188 |
+
super().__init__(**kwargs)
|
2189 |
+
self.adaptive = kwargs.get("adaptive", False)
|
2190 |
+
self.expr = expr
|
2191 |
+
self._label = str(expr) if label is None else label
|
2192 |
+
self._latex_label = latex(expr) if label is None else label
|
2193 |
+
self.ranges = [var_start_end_x, var_start_end_y]
|
2194 |
+
self.var_x, self.start_x, self.end_x = self.ranges[0]
|
2195 |
+
self.var_y, self.start_y, self.end_y = self.ranges[1]
|
2196 |
+
self._color = kwargs.get("color", kwargs.get("line_color", None))
|
2197 |
+
|
2198 |
+
if self.is_interactive and self.adaptive:
|
2199 |
+
raise NotImplementedError("Interactive plot with `adaptive=True` "
|
2200 |
+
"is not supported.")
|
2201 |
+
|
2202 |
+
# Check whether the depth is greater than 4 or less than 0.
|
2203 |
+
depth = kwargs.get("depth", 0)
|
2204 |
+
if depth > 4:
|
2205 |
+
depth = 4
|
2206 |
+
elif depth < 0:
|
2207 |
+
depth = 0
|
2208 |
+
self.depth = 4 + depth
|
2209 |
+
self._post_init()
|
2210 |
+
|
2211 |
+
@property
|
2212 |
+
def expr(self):
|
2213 |
+
if self.adaptive:
|
2214 |
+
return self._adaptive_expr
|
2215 |
+
return self._non_adaptive_expr
|
2216 |
+
|
2217 |
+
@expr.setter
|
2218 |
+
def expr(self, expr):
|
2219 |
+
self._block_lambda_functions(expr)
|
2220 |
+
# these are needed for adaptive evaluation
|
2221 |
+
expr, has_equality = self._has_equality(sympify(expr))
|
2222 |
+
self._adaptive_expr = expr
|
2223 |
+
self.has_equality = has_equality
|
2224 |
+
self._label = str(expr)
|
2225 |
+
self._latex_label = latex(expr)
|
2226 |
+
|
2227 |
+
if isinstance(expr, (BooleanFunction, Ne)) and (not self.adaptive):
|
2228 |
+
self.adaptive = True
|
2229 |
+
msg = "contains Boolean functions. "
|
2230 |
+
if isinstance(expr, Ne):
|
2231 |
+
msg = "is an unequality. "
|
2232 |
+
warnings.warn(
|
2233 |
+
"The provided expression " + msg
|
2234 |
+
+ "In order to plot the expression, the algorithm "
|
2235 |
+
+ "automatically switched to an adaptive sampling."
|
2236 |
+
)
|
2237 |
+
|
2238 |
+
if isinstance(expr, BooleanFunction):
|
2239 |
+
self._non_adaptive_expr = None
|
2240 |
+
self._is_equality = False
|
2241 |
+
else:
|
2242 |
+
# these are needed for uniform meshing evaluation
|
2243 |
+
expr, is_equality = self._preprocess_meshgrid_expression(expr, self.adaptive)
|
2244 |
+
self._non_adaptive_expr = expr
|
2245 |
+
self._is_equality = is_equality
|
2246 |
+
|
2247 |
+
@property
|
2248 |
+
def line_color(self):
|
2249 |
+
return self._color
|
2250 |
+
|
2251 |
+
@line_color.setter
|
2252 |
+
def line_color(self, v):
|
2253 |
+
self._color = v
|
2254 |
+
|
2255 |
+
color = line_color
|
2256 |
+
|
2257 |
+
def _has_equality(self, expr):
|
2258 |
+
# Represents whether the expression contains an Equality, GreaterThan
|
2259 |
+
# or LessThan
|
2260 |
+
has_equality = False
|
2261 |
+
|
2262 |
+
def arg_expand(bool_expr):
|
2263 |
+
"""Recursively expands the arguments of an Boolean Function"""
|
2264 |
+
for arg in bool_expr.args:
|
2265 |
+
if isinstance(arg, BooleanFunction):
|
2266 |
+
arg_expand(arg)
|
2267 |
+
elif isinstance(arg, Relational):
|
2268 |
+
arg_list.append(arg)
|
2269 |
+
|
2270 |
+
arg_list = []
|
2271 |
+
if isinstance(expr, BooleanFunction):
|
2272 |
+
arg_expand(expr)
|
2273 |
+
# Check whether there is an equality in the expression provided.
|
2274 |
+
if any(isinstance(e, (Equality, GreaterThan, LessThan)) for e in arg_list):
|
2275 |
+
has_equality = True
|
2276 |
+
elif not isinstance(expr, Relational):
|
2277 |
+
expr = Equality(expr, 0)
|
2278 |
+
has_equality = True
|
2279 |
+
elif isinstance(expr, (Equality, GreaterThan, LessThan)):
|
2280 |
+
has_equality = True
|
2281 |
+
|
2282 |
+
return expr, has_equality
|
2283 |
+
|
2284 |
+
def __str__(self):
|
2285 |
+
f = lambda t: float(t) if len(t.free_symbols) == 0 else t
|
2286 |
+
|
2287 |
+
return self._str_helper(
|
2288 |
+
"Implicit expression: %s for %s over %s and %s over %s") % (
|
2289 |
+
str(self._adaptive_expr),
|
2290 |
+
str(self.var_x),
|
2291 |
+
str((f(self.start_x), f(self.end_x))),
|
2292 |
+
str(self.var_y),
|
2293 |
+
str((f(self.start_y), f(self.end_y))),
|
2294 |
+
)
|
2295 |
+
|
2296 |
+
def get_data(self):
|
2297 |
+
"""Returns numerical data.
|
2298 |
+
|
2299 |
+
Returns
|
2300 |
+
=======
|
2301 |
+
|
2302 |
+
If the series is evaluated with the `adaptive=True` it returns:
|
2303 |
+
|
2304 |
+
interval_list : list
|
2305 |
+
List of bounding rectangular intervals to be postprocessed and
|
2306 |
+
eventually used with Matplotlib's ``fill`` command.
|
2307 |
+
dummy : str
|
2308 |
+
A string containing ``"fill"``.
|
2309 |
+
|
2310 |
+
Otherwise, it returns 2D numpy arrays to be used with Matplotlib's
|
2311 |
+
``contour`` or ``contourf`` commands:
|
2312 |
+
|
2313 |
+
x_array : np.ndarray
|
2314 |
+
y_array : np.ndarray
|
2315 |
+
z_array : np.ndarray
|
2316 |
+
plot_type : str
|
2317 |
+
A string specifying which plot command to use, ``"contour"``
|
2318 |
+
or ``"contourf"``.
|
2319 |
+
"""
|
2320 |
+
if self.adaptive:
|
2321 |
+
data = self._adaptive_eval()
|
2322 |
+
if data is not None:
|
2323 |
+
return data
|
2324 |
+
|
2325 |
+
return self._get_meshes_grid()
|
2326 |
+
|
2327 |
+
def _adaptive_eval(self):
|
2328 |
+
"""
|
2329 |
+
References
|
2330 |
+
==========
|
2331 |
+
|
2332 |
+
.. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for
|
2333 |
+
Mathematical Formulae with Two Free Variables.
|
2334 |
+
|
2335 |
+
.. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval
|
2336 |
+
Arithmetic. Master's thesis. University of Toronto, 1996
|
2337 |
+
"""
|
2338 |
+
import sympy.plotting.intervalmath.lib_interval as li
|
2339 |
+
|
2340 |
+
user_functions = {}
|
2341 |
+
printer = IntervalMathPrinter({
|
2342 |
+
'fully_qualified_modules': False, 'inline': True,
|
2343 |
+
'allow_unknown_functions': True,
|
2344 |
+
'user_functions': user_functions})
|
2345 |
+
|
2346 |
+
keys = [t for t in dir(li) if ("__" not in t) and (t not in ["import_module", "interval"])]
|
2347 |
+
vals = [getattr(li, k) for k in keys]
|
2348 |
+
d = dict(zip(keys, vals))
|
2349 |
+
func = lambdify((self.var_x, self.var_y), self.expr, modules=[d], printer=printer)
|
2350 |
+
data = None
|
2351 |
+
|
2352 |
+
try:
|
2353 |
+
data = self._get_raster_interval(func)
|
2354 |
+
except NameError as err:
|
2355 |
+
warnings.warn(
|
2356 |
+
"Adaptive meshing could not be applied to the"
|
2357 |
+
" expression, as some functions are not yet implemented"
|
2358 |
+
" in the interval math module:\n\n"
|
2359 |
+
"NameError: %s\n\n" % err +
|
2360 |
+
"Proceeding with uniform meshing."
|
2361 |
+
)
|
2362 |
+
self.adaptive = False
|
2363 |
+
except TypeError:
|
2364 |
+
warnings.warn(
|
2365 |
+
"Adaptive meshing could not be applied to the"
|
2366 |
+
" expression. Using uniform meshing.")
|
2367 |
+
self.adaptive = False
|
2368 |
+
|
2369 |
+
return data
|
2370 |
+
|
2371 |
+
def _get_raster_interval(self, func):
|
2372 |
+
"""Uses interval math to adaptively mesh and obtain the plot"""
|
2373 |
+
np = import_module('numpy')
|
2374 |
+
|
2375 |
+
k = self.depth
|
2376 |
+
interval_list = []
|
2377 |
+
sx, sy = [float(t) for t in [self.start_x, self.start_y]]
|
2378 |
+
ex, ey = [float(t) for t in [self.end_x, self.end_y]]
|
2379 |
+
# Create initial 32 divisions
|
2380 |
+
xsample = np.linspace(sx, ex, 33)
|
2381 |
+
ysample = np.linspace(sy, ey, 33)
|
2382 |
+
|
2383 |
+
# Add a small jitter so that there are no false positives for equality.
|
2384 |
+
# Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2)
|
2385 |
+
# which will draw a rectangle.
|
2386 |
+
jitterx = (
|
2387 |
+
(np.random.rand(len(xsample)) * 2 - 1)
|
2388 |
+
* (ex - sx)
|
2389 |
+
/ 2 ** 20
|
2390 |
+
)
|
2391 |
+
jittery = (
|
2392 |
+
(np.random.rand(len(ysample)) * 2 - 1)
|
2393 |
+
* (ey - sy)
|
2394 |
+
/ 2 ** 20
|
2395 |
+
)
|
2396 |
+
xsample += jitterx
|
2397 |
+
ysample += jittery
|
2398 |
+
|
2399 |
+
xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1], xsample[1:])]
|
2400 |
+
yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1], ysample[1:])]
|
2401 |
+
interval_list = [[x, y] for x in xinter for y in yinter]
|
2402 |
+
plot_list = []
|
2403 |
+
|
2404 |
+
# recursive call refinepixels which subdivides the intervals which are
|
2405 |
+
# neither True nor False according to the expression.
|
2406 |
+
def refine_pixels(interval_list):
|
2407 |
+
"""Evaluates the intervals and subdivides the interval if the
|
2408 |
+
expression is partially satisfied."""
|
2409 |
+
temp_interval_list = []
|
2410 |
+
plot_list = []
|
2411 |
+
for intervals in interval_list:
|
2412 |
+
|
2413 |
+
# Convert the array indices to x and y values
|
2414 |
+
intervalx = intervals[0]
|
2415 |
+
intervaly = intervals[1]
|
2416 |
+
func_eval = func(intervalx, intervaly)
|
2417 |
+
# The expression is valid in the interval. Change the contour
|
2418 |
+
# array values to 1.
|
2419 |
+
if func_eval[1] is False or func_eval[0] is False:
|
2420 |
+
pass
|
2421 |
+
elif func_eval == (True, True):
|
2422 |
+
plot_list.append([intervalx, intervaly])
|
2423 |
+
elif func_eval[1] is None or func_eval[0] is None:
|
2424 |
+
# Subdivide
|
2425 |
+
avgx = intervalx.mid
|
2426 |
+
avgy = intervaly.mid
|
2427 |
+
a = interval(intervalx.start, avgx)
|
2428 |
+
b = interval(avgx, intervalx.end)
|
2429 |
+
c = interval(intervaly.start, avgy)
|
2430 |
+
d = interval(avgy, intervaly.end)
|
2431 |
+
temp_interval_list.append([a, c])
|
2432 |
+
temp_interval_list.append([a, d])
|
2433 |
+
temp_interval_list.append([b, c])
|
2434 |
+
temp_interval_list.append([b, d])
|
2435 |
+
return temp_interval_list, plot_list
|
2436 |
+
|
2437 |
+
while k >= 0 and len(interval_list):
|
2438 |
+
interval_list, plot_list_temp = refine_pixels(interval_list)
|
2439 |
+
plot_list.extend(plot_list_temp)
|
2440 |
+
k = k - 1
|
2441 |
+
# Check whether the expression represents an equality
|
2442 |
+
# If it represents an equality, then none of the intervals
|
2443 |
+
# would have satisfied the expression due to floating point
|
2444 |
+
# differences. Add all the undecided values to the plot.
|
2445 |
+
if self.has_equality:
|
2446 |
+
for intervals in interval_list:
|
2447 |
+
intervalx = intervals[0]
|
2448 |
+
intervaly = intervals[1]
|
2449 |
+
func_eval = func(intervalx, intervaly)
|
2450 |
+
if func_eval[1] and func_eval[0] is not False:
|
2451 |
+
plot_list.append([intervalx, intervaly])
|
2452 |
+
return plot_list, "fill"
|
2453 |
+
|
2454 |
+
def _get_meshes_grid(self):
|
2455 |
+
"""Generates the mesh for generating a contour.
|
2456 |
+
|
2457 |
+
In the case of equality, ``contour`` function of matplotlib can
|
2458 |
+
be used. In other cases, matplotlib's ``contourf`` is used.
|
2459 |
+
"""
|
2460 |
+
np = import_module('numpy')
|
2461 |
+
|
2462 |
+
xarray, yarray, z_grid = self._evaluate()
|
2463 |
+
_re, _im = np.real(z_grid), np.imag(z_grid)
|
2464 |
+
_re[np.invert(np.isclose(_im, np.zeros_like(_im)))] = np.nan
|
2465 |
+
if self._is_equality:
|
2466 |
+
return xarray, yarray, _re, 'contour'
|
2467 |
+
return xarray, yarray, _re, 'contourf'
|
2468 |
+
|
2469 |
+
@staticmethod
|
2470 |
+
def _preprocess_meshgrid_expression(expr, adaptive):
|
2471 |
+
"""If the expression is a Relational, rewrite it as a single
|
2472 |
+
expression.
|
2473 |
+
|
2474 |
+
Returns
|
2475 |
+
=======
|
2476 |
+
|
2477 |
+
expr : Expr
|
2478 |
+
The rewritten expression
|
2479 |
+
|
2480 |
+
equality : Boolean
|
2481 |
+
Wheter the original expression was an Equality or not.
|
2482 |
+
"""
|
2483 |
+
equality = False
|
2484 |
+
if isinstance(expr, Equality):
|
2485 |
+
expr = expr.lhs - expr.rhs
|
2486 |
+
equality = True
|
2487 |
+
elif isinstance(expr, Relational):
|
2488 |
+
expr = expr.gts - expr.lts
|
2489 |
+
elif not adaptive:
|
2490 |
+
raise NotImplementedError(
|
2491 |
+
"The expression is not supported for "
|
2492 |
+
"plotting in uniform meshed plot."
|
2493 |
+
)
|
2494 |
+
return expr, equality
|
2495 |
+
|
2496 |
+
def get_label(self, use_latex=False, wrapper="$%s$"):
|
2497 |
+
"""Return the label to be used to display the expression.
|
2498 |
+
|
2499 |
+
Parameters
|
2500 |
+
==========
|
2501 |
+
use_latex : bool
|
2502 |
+
If False, the string representation of the expression is returned.
|
2503 |
+
If True, the latex representation is returned.
|
2504 |
+
wrapper : str
|
2505 |
+
The backend might need the latex representation to be wrapped by
|
2506 |
+
some characters. Default to ``"$%s$"``.
|
2507 |
+
|
2508 |
+
Returns
|
2509 |
+
=======
|
2510 |
+
label : str
|
2511 |
+
"""
|
2512 |
+
if use_latex is False:
|
2513 |
+
return self._label
|
2514 |
+
if self._label == str(self._adaptive_expr):
|
2515 |
+
return self._get_wrapped_label(self._latex_label, wrapper)
|
2516 |
+
return self._latex_label
|
2517 |
+
|
2518 |
+
|
2519 |
+
##############################################################################
|
2520 |
+
# Finding the centers of line segments or mesh faces
|
2521 |
+
##############################################################################
|
2522 |
+
|
2523 |
+
def centers_of_segments(array):
|
2524 |
+
np = import_module('numpy')
|
2525 |
+
return np.mean(np.vstack((array[:-1], array[1:])), 0)
|
2526 |
+
|
2527 |
+
|
2528 |
+
def centers_of_faces(array):
|
2529 |
+
np = import_module('numpy')
|
2530 |
+
return np.mean(np.dstack((array[:-1, :-1],
|
2531 |
+
array[1:, :-1],
|
2532 |
+
array[:-1, 1:],
|
2533 |
+
array[:-1, :-1],
|
2534 |
+
)), 2)
|
2535 |
+
|
2536 |
+
|
2537 |
+
def flat(x, y, z, eps=1e-3):
|
2538 |
+
"""Checks whether three points are almost collinear"""
|
2539 |
+
np = import_module('numpy')
|
2540 |
+
# Workaround plotting piecewise (#8577)
|
2541 |
+
vector_a = (x - y).astype(float)
|
2542 |
+
vector_b = (z - y).astype(float)
|
2543 |
+
dot_product = np.dot(vector_a, vector_b)
|
2544 |
+
vector_a_norm = np.linalg.norm(vector_a)
|
2545 |
+
vector_b_norm = np.linalg.norm(vector_b)
|
2546 |
+
cos_theta = dot_product / (vector_a_norm * vector_b_norm)
|
2547 |
+
return abs(cos_theta + 1) < eps
|
2548 |
+
|
2549 |
+
|
2550 |
+
def _set_discretization_points(kwargs, pt):
|
2551 |
+
"""Allow the use of the keyword arguments ``n, n1, n2`` to
|
2552 |
+
specify the number of discretization points in one and two
|
2553 |
+
directions, while keeping back-compatibility with older keyword arguments
|
2554 |
+
like, ``nb_of_points, nb_of_points_*, points``.
|
2555 |
+
|
2556 |
+
Parameters
|
2557 |
+
==========
|
2558 |
+
|
2559 |
+
kwargs : dict
|
2560 |
+
Dictionary of keyword arguments passed into a plotting function.
|
2561 |
+
pt : type
|
2562 |
+
The type of the series, which indicates the kind of plot we are
|
2563 |
+
trying to create.
|
2564 |
+
"""
|
2565 |
+
replace_old_keywords = {
|
2566 |
+
"nb_of_points": "n",
|
2567 |
+
"nb_of_points_x": "n1",
|
2568 |
+
"nb_of_points_y": "n2",
|
2569 |
+
"nb_of_points_u": "n1",
|
2570 |
+
"nb_of_points_v": "n2",
|
2571 |
+
"points": "n"
|
2572 |
+
}
|
2573 |
+
for k, v in replace_old_keywords.items():
|
2574 |
+
if k in kwargs.keys():
|
2575 |
+
kwargs[v] = kwargs.pop(k)
|
2576 |
+
|
2577 |
+
if pt in [LineOver1DRangeSeries, Parametric2DLineSeries,
|
2578 |
+
Parametric3DLineSeries]:
|
2579 |
+
if "n" in kwargs.keys():
|
2580 |
+
kwargs["n1"] = kwargs["n"]
|
2581 |
+
if hasattr(kwargs["n"], "__iter__") and (len(kwargs["n"]) > 0):
|
2582 |
+
kwargs["n1"] = kwargs["n"][0]
|
2583 |
+
elif pt in [SurfaceOver2DRangeSeries, ContourSeries,
|
2584 |
+
ParametricSurfaceSeries, ImplicitSeries]:
|
2585 |
+
if "n" in kwargs.keys():
|
2586 |
+
if hasattr(kwargs["n"], "__iter__") and (len(kwargs["n"]) > 1):
|
2587 |
+
kwargs["n1"] = kwargs["n"][0]
|
2588 |
+
kwargs["n2"] = kwargs["n"][1]
|
2589 |
+
else:
|
2590 |
+
kwargs["n1"] = kwargs["n2"] = kwargs["n"]
|
2591 |
+
return kwargs
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/textplot.py
ADDED
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import Float
|
2 |
+
from sympy.core.symbol import Dummy
|
3 |
+
from sympy.utilities.lambdify import lambdify
|
4 |
+
|
5 |
+
import math
|
6 |
+
|
7 |
+
|
8 |
+
def is_valid(x):
|
9 |
+
"""Check if a floating point number is valid"""
|
10 |
+
if x is None:
|
11 |
+
return False
|
12 |
+
if isinstance(x, complex):
|
13 |
+
return False
|
14 |
+
return not math.isinf(x) and not math.isnan(x)
|
15 |
+
|
16 |
+
|
17 |
+
def rescale(y, W, H, mi, ma):
|
18 |
+
"""Rescale the given array `y` to fit into the integer values
|
19 |
+
between `0` and `H-1` for the values between ``mi`` and ``ma``.
|
20 |
+
"""
|
21 |
+
y_new = []
|
22 |
+
|
23 |
+
norm = ma - mi
|
24 |
+
offset = (ma + mi) / 2
|
25 |
+
|
26 |
+
for x in range(W):
|
27 |
+
if is_valid(y[x]):
|
28 |
+
normalized = (y[x] - offset) / norm
|
29 |
+
if not is_valid(normalized):
|
30 |
+
y_new.append(None)
|
31 |
+
else:
|
32 |
+
rescaled = Float((normalized*H + H/2) * (H-1)/H).round()
|
33 |
+
rescaled = int(rescaled)
|
34 |
+
y_new.append(rescaled)
|
35 |
+
else:
|
36 |
+
y_new.append(None)
|
37 |
+
return y_new
|
38 |
+
|
39 |
+
|
40 |
+
def linspace(start, stop, num):
|
41 |
+
return [start + (stop - start) * x / (num-1) for x in range(num)]
|
42 |
+
|
43 |
+
|
44 |
+
def textplot_str(expr, a, b, W=55, H=21):
|
45 |
+
"""Generator for the lines of the plot"""
|
46 |
+
free = expr.free_symbols
|
47 |
+
if len(free) > 1:
|
48 |
+
raise ValueError(
|
49 |
+
"The expression must have a single variable. (Got {})"
|
50 |
+
.format(free))
|
51 |
+
x = free.pop() if free else Dummy()
|
52 |
+
f = lambdify([x], expr)
|
53 |
+
if isinstance(a, complex):
|
54 |
+
if a.imag == 0:
|
55 |
+
a = a.real
|
56 |
+
if isinstance(b, complex):
|
57 |
+
if b.imag == 0:
|
58 |
+
b = b.real
|
59 |
+
a = float(a)
|
60 |
+
b = float(b)
|
61 |
+
|
62 |
+
# Calculate function values
|
63 |
+
x = linspace(a, b, W)
|
64 |
+
y = []
|
65 |
+
for val in x:
|
66 |
+
try:
|
67 |
+
y.append(f(val))
|
68 |
+
# Not sure what exceptions to catch here or why...
|
69 |
+
except (ValueError, TypeError, ZeroDivisionError):
|
70 |
+
y.append(None)
|
71 |
+
|
72 |
+
# Normalize height to screen space
|
73 |
+
y_valid = list(filter(is_valid, y))
|
74 |
+
if y_valid:
|
75 |
+
ma = max(y_valid)
|
76 |
+
mi = min(y_valid)
|
77 |
+
if ma == mi:
|
78 |
+
if ma:
|
79 |
+
mi, ma = sorted([0, 2*ma])
|
80 |
+
else:
|
81 |
+
mi, ma = -1, 1
|
82 |
+
else:
|
83 |
+
mi, ma = -1, 1
|
84 |
+
y_range = ma - mi
|
85 |
+
precision = math.floor(math.log10(y_range)) - 1
|
86 |
+
precision *= -1
|
87 |
+
mi = round(mi, precision)
|
88 |
+
ma = round(ma, precision)
|
89 |
+
y = rescale(y, W, H, mi, ma)
|
90 |
+
|
91 |
+
y_bins = linspace(mi, ma, H)
|
92 |
+
|
93 |
+
# Draw plot
|
94 |
+
margin = 7
|
95 |
+
for h in range(H - 1, -1, -1):
|
96 |
+
s = [' '] * W
|
97 |
+
for i in range(W):
|
98 |
+
if y[i] == h:
|
99 |
+
if (i == 0 or y[i - 1] == h - 1) and (i == W - 1 or y[i + 1] == h + 1):
|
100 |
+
s[i] = '/'
|
101 |
+
elif (i == 0 or y[i - 1] == h + 1) and (i == W - 1 or y[i + 1] == h - 1):
|
102 |
+
s[i] = '\\'
|
103 |
+
else:
|
104 |
+
s[i] = '.'
|
105 |
+
|
106 |
+
if h == 0:
|
107 |
+
for i in range(W):
|
108 |
+
s[i] = '_'
|
109 |
+
|
110 |
+
# Print y values
|
111 |
+
if h in (0, H//2, H - 1):
|
112 |
+
prefix = ("%g" % y_bins[h]).rjust(margin)[:margin]
|
113 |
+
else:
|
114 |
+
prefix = " "*margin
|
115 |
+
s = "".join(s)
|
116 |
+
if h == H//2:
|
117 |
+
s = s.replace(" ", "-")
|
118 |
+
yield prefix + " |" + s
|
119 |
+
|
120 |
+
# Print x values
|
121 |
+
bottom = " " * (margin + 2)
|
122 |
+
bottom += ("%g" % x[0]).ljust(W//2)
|
123 |
+
if W % 2 == 1:
|
124 |
+
bottom += ("%g" % x[W//2]).ljust(W//2)
|
125 |
+
else:
|
126 |
+
bottom += ("%g" % x[W//2]).ljust(W//2-1)
|
127 |
+
bottom += "%g" % x[-1]
|
128 |
+
yield bottom
|
129 |
+
|
130 |
+
|
131 |
+
def textplot(expr, a, b, W=55, H=21):
|
132 |
+
r"""
|
133 |
+
Print a crude ASCII art plot of the SymPy expression 'expr' (which
|
134 |
+
should contain a single symbol, e.g. x or something else) over the
|
135 |
+
interval [a, b].
|
136 |
+
|
137 |
+
Examples
|
138 |
+
========
|
139 |
+
|
140 |
+
>>> from sympy import Symbol, sin
|
141 |
+
>>> from sympy.plotting import textplot
|
142 |
+
>>> t = Symbol('t')
|
143 |
+
>>> textplot(sin(t)*t, 0, 15)
|
144 |
+
14 | ...
|
145 |
+
| .
|
146 |
+
| .
|
147 |
+
| .
|
148 |
+
| .
|
149 |
+
| ...
|
150 |
+
| / . .
|
151 |
+
| /
|
152 |
+
| / .
|
153 |
+
| . . .
|
154 |
+
1.5 |----.......--------------------------------------------
|
155 |
+
|.... \ . .
|
156 |
+
| \ / .
|
157 |
+
| .. / .
|
158 |
+
| \ / .
|
159 |
+
| ....
|
160 |
+
| .
|
161 |
+
| . .
|
162 |
+
|
|
163 |
+
| . .
|
164 |
+
-11 |_______________________________________________________
|
165 |
+
0 7.5 15
|
166 |
+
"""
|
167 |
+
for line in textplot_str(expr, a, b, W, H):
|
168 |
+
print(line)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/utils.py
ADDED
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.containers import Tuple
|
2 |
+
from sympy.core.basic import Basic
|
3 |
+
from sympy.core.expr import Expr
|
4 |
+
from sympy.core.function import AppliedUndef
|
5 |
+
from sympy.core.relational import Relational
|
6 |
+
from sympy.core.symbol import Dummy
|
7 |
+
from sympy.core.sympify import sympify
|
8 |
+
from sympy.logic.boolalg import BooleanFunction
|
9 |
+
from sympy.sets.fancysets import ImageSet
|
10 |
+
from sympy.sets.sets import FiniteSet
|
11 |
+
from sympy.tensor.indexed import Indexed
|
12 |
+
|
13 |
+
|
14 |
+
def _get_free_symbols(exprs):
|
15 |
+
"""Returns the free symbols of a symbolic expression.
|
16 |
+
|
17 |
+
If the expression contains any of these elements, assume that they are
|
18 |
+
the "free symbols" of the expression:
|
19 |
+
|
20 |
+
* indexed objects
|
21 |
+
* applied undefined function (useful for sympy.physics.mechanics module)
|
22 |
+
"""
|
23 |
+
if not isinstance(exprs, (list, tuple, set)):
|
24 |
+
exprs = [exprs]
|
25 |
+
if all(callable(e) for e in exprs):
|
26 |
+
return set()
|
27 |
+
|
28 |
+
free = set().union(*[e.atoms(Indexed) for e in exprs])
|
29 |
+
free = free.union(*[e.atoms(AppliedUndef) for e in exprs])
|
30 |
+
return free or set().union(*[e.free_symbols for e in exprs])
|
31 |
+
|
32 |
+
|
33 |
+
def extract_solution(set_sol, n=10):
|
34 |
+
"""Extract numerical solutions from a set solution (computed by solveset,
|
35 |
+
linsolve, nonlinsolve). Often, it is not trivial do get something useful
|
36 |
+
out of them.
|
37 |
+
|
38 |
+
Parameters
|
39 |
+
==========
|
40 |
+
|
41 |
+
n : int, optional
|
42 |
+
In order to replace ImageSet with FiniteSet, an iterator is created
|
43 |
+
for each ImageSet contained in `set_sol`, starting from 0 up to `n`.
|
44 |
+
Default value: 10.
|
45 |
+
"""
|
46 |
+
images = set_sol.find(ImageSet)
|
47 |
+
for im in images:
|
48 |
+
it = iter(im)
|
49 |
+
s = FiniteSet(*[next(it) for n in range(0, n)])
|
50 |
+
set_sol = set_sol.subs(im, s)
|
51 |
+
return set_sol
|
52 |
+
|
53 |
+
|
54 |
+
def _plot_sympify(args):
|
55 |
+
"""This function recursively loop over the arguments passed to the plot
|
56 |
+
functions: the sympify function will be applied to all arguments except
|
57 |
+
those of type string/dict.
|
58 |
+
|
59 |
+
Generally, users can provide the following arguments to a plot function:
|
60 |
+
|
61 |
+
expr, range1 [tuple, opt], ..., label [str, opt], rendering_kw [dict, opt]
|
62 |
+
|
63 |
+
`expr, range1, ...` can be sympified, whereas `label, rendering_kw` can't.
|
64 |
+
In particular, whenever a special character like $, {, }, ... is used in
|
65 |
+
the `label`, sympify will raise an error.
|
66 |
+
"""
|
67 |
+
if isinstance(args, Expr):
|
68 |
+
return args
|
69 |
+
|
70 |
+
args = list(args)
|
71 |
+
for i, a in enumerate(args):
|
72 |
+
if isinstance(a, (list, tuple)):
|
73 |
+
args[i] = Tuple(*_plot_sympify(a), sympify=False)
|
74 |
+
elif not (isinstance(a, (str, dict)) or callable(a)
|
75 |
+
# NOTE: check if it is a vector from sympy.physics.vector module
|
76 |
+
# without importing the module (because it slows down SymPy's
|
77 |
+
# import process and triggers SymPy's optional-dependencies
|
78 |
+
# tests to fail).
|
79 |
+
or ((a.__class__.__name__ == "Vector") and not isinstance(a, Basic))
|
80 |
+
):
|
81 |
+
args[i] = sympify(a)
|
82 |
+
return args
|
83 |
+
|
84 |
+
|
85 |
+
def _create_ranges(exprs, ranges, npar, label="", params=None):
|
86 |
+
"""This function does two things:
|
87 |
+
|
88 |
+
1. Check if the number of free symbols is in agreement with the type of
|
89 |
+
plot chosen. For example, plot() requires 1 free symbol;
|
90 |
+
plot3d() requires 2 free symbols.
|
91 |
+
2. Sometime users create plots without providing ranges for the variables.
|
92 |
+
Here we create the necessary ranges.
|
93 |
+
|
94 |
+
Parameters
|
95 |
+
==========
|
96 |
+
|
97 |
+
exprs : iterable
|
98 |
+
The expressions from which to extract the free symbols
|
99 |
+
ranges : iterable
|
100 |
+
The limiting ranges provided by the user
|
101 |
+
npar : int
|
102 |
+
The number of free symbols required by the plot functions.
|
103 |
+
For example,
|
104 |
+
npar=1 for plot, npar=2 for plot3d, ...
|
105 |
+
params : dict
|
106 |
+
A dictionary mapping symbols to parameters for interactive plot.
|
107 |
+
"""
|
108 |
+
get_default_range = lambda symbol: Tuple(symbol, -10, 10)
|
109 |
+
|
110 |
+
free_symbols = _get_free_symbols(exprs)
|
111 |
+
if params is not None:
|
112 |
+
free_symbols = free_symbols.difference(params.keys())
|
113 |
+
|
114 |
+
if len(free_symbols) > npar:
|
115 |
+
raise ValueError(
|
116 |
+
"Too many free symbols.\n"
|
117 |
+
+ "Expected {} free symbols.\n".format(npar)
|
118 |
+
+ "Received {}: {}".format(len(free_symbols), free_symbols)
|
119 |
+
)
|
120 |
+
|
121 |
+
if len(ranges) > npar:
|
122 |
+
raise ValueError(
|
123 |
+
"Too many ranges. Received %s, expected %s" % (len(ranges), npar))
|
124 |
+
|
125 |
+
# free symbols in the ranges provided by the user
|
126 |
+
rfs = set().union([r[0] for r in ranges])
|
127 |
+
if len(rfs) != len(ranges):
|
128 |
+
raise ValueError("Multiple ranges with the same symbol")
|
129 |
+
|
130 |
+
if len(ranges) < npar:
|
131 |
+
symbols = free_symbols.difference(rfs)
|
132 |
+
if symbols != set():
|
133 |
+
# add a range for each missing free symbols
|
134 |
+
for s in symbols:
|
135 |
+
ranges.append(get_default_range(s))
|
136 |
+
# if there is still room, fill them with dummys
|
137 |
+
for i in range(npar - len(ranges)):
|
138 |
+
ranges.append(get_default_range(Dummy()))
|
139 |
+
|
140 |
+
if len(free_symbols) == npar:
|
141 |
+
# there could be times when this condition is not met, for example
|
142 |
+
# plotting the function f(x, y) = x (which is a plane); in this case,
|
143 |
+
# free_symbols = {x} whereas rfs = {x, y} (or x and Dummy)
|
144 |
+
rfs = set().union([r[0] for r in ranges])
|
145 |
+
if len(free_symbols.difference(rfs)) > 0:
|
146 |
+
raise ValueError(
|
147 |
+
"Incompatible free symbols of the expressions with "
|
148 |
+
"the ranges.\n"
|
149 |
+
+ "Free symbols in the expressions: {}\n".format(free_symbols)
|
150 |
+
+ "Free symbols in the ranges: {}".format(rfs)
|
151 |
+
)
|
152 |
+
return ranges
|
153 |
+
|
154 |
+
|
155 |
+
def _is_range(r):
|
156 |
+
"""A range is defined as (symbol, start, end). start and end should
|
157 |
+
be numbers.
|
158 |
+
"""
|
159 |
+
# TODO: prange check goes here
|
160 |
+
return (
|
161 |
+
isinstance(r, Tuple)
|
162 |
+
and (len(r) == 3)
|
163 |
+
and (not isinstance(r.args[1], str)) and r.args[1].is_number
|
164 |
+
and (not isinstance(r.args[2], str)) and r.args[2].is_number
|
165 |
+
)
|
166 |
+
|
167 |
+
|
168 |
+
def _unpack_args(*args):
|
169 |
+
"""Given a list/tuple of arguments previously processed by _plot_sympify()
|
170 |
+
and/or _check_arguments(), separates and returns its components:
|
171 |
+
expressions, ranges, label and rendering keywords.
|
172 |
+
|
173 |
+
Examples
|
174 |
+
========
|
175 |
+
|
176 |
+
>>> from sympy import cos, sin, symbols
|
177 |
+
>>> from sympy.plotting.utils import _plot_sympify, _unpack_args
|
178 |
+
>>> x, y = symbols('x, y')
|
179 |
+
>>> args = (sin(x), (x, -10, 10), "f1")
|
180 |
+
>>> args = _plot_sympify(args)
|
181 |
+
>>> _unpack_args(*args)
|
182 |
+
([sin(x)], [(x, -10, 10)], 'f1', None)
|
183 |
+
|
184 |
+
>>> args = (sin(x**2 + y**2), (x, -2, 2), (y, -3, 3), "f2")
|
185 |
+
>>> args = _plot_sympify(args)
|
186 |
+
>>> _unpack_args(*args)
|
187 |
+
([sin(x**2 + y**2)], [(x, -2, 2), (y, -3, 3)], 'f2', None)
|
188 |
+
|
189 |
+
>>> args = (sin(x + y), cos(x - y), x + y, (x, -2, 2), (y, -3, 3), "f3")
|
190 |
+
>>> args = _plot_sympify(args)
|
191 |
+
>>> _unpack_args(*args)
|
192 |
+
([sin(x + y), cos(x - y), x + y], [(x, -2, 2), (y, -3, 3)], 'f3', None)
|
193 |
+
"""
|
194 |
+
ranges = [t for t in args if _is_range(t)]
|
195 |
+
labels = [t for t in args if isinstance(t, str)]
|
196 |
+
label = None if not labels else labels[0]
|
197 |
+
rendering_kw = [t for t in args if isinstance(t, dict)]
|
198 |
+
rendering_kw = None if not rendering_kw else rendering_kw[0]
|
199 |
+
# NOTE: why None? because args might have been preprocessed by
|
200 |
+
# _check_arguments, so None might represent the rendering_kw
|
201 |
+
results = [not (_is_range(a) or isinstance(a, (str, dict)) or (a is None)) for a in args]
|
202 |
+
exprs = [a for a, b in zip(args, results) if b]
|
203 |
+
return exprs, ranges, label, rendering_kw
|
204 |
+
|
205 |
+
|
206 |
+
def _check_arguments(args, nexpr, npar, **kwargs):
|
207 |
+
"""Checks the arguments and converts into tuples of the
|
208 |
+
form (exprs, ranges, label, rendering_kw).
|
209 |
+
|
210 |
+
Parameters
|
211 |
+
==========
|
212 |
+
|
213 |
+
args
|
214 |
+
The arguments provided to the plot functions
|
215 |
+
nexpr
|
216 |
+
The number of sub-expression forming an expression to be plotted.
|
217 |
+
For example:
|
218 |
+
nexpr=1 for plot.
|
219 |
+
nexpr=2 for plot_parametric: a curve is represented by a tuple of two
|
220 |
+
elements.
|
221 |
+
nexpr=1 for plot3d.
|
222 |
+
nexpr=3 for plot3d_parametric_line: a curve is represented by a tuple
|
223 |
+
of three elements.
|
224 |
+
npar
|
225 |
+
The number of free symbols required by the plot functions. For example,
|
226 |
+
npar=1 for plot, npar=2 for plot3d, ...
|
227 |
+
**kwargs :
|
228 |
+
keyword arguments passed to the plotting function. It will be used to
|
229 |
+
verify if ``params`` has ben provided.
|
230 |
+
|
231 |
+
Examples
|
232 |
+
========
|
233 |
+
|
234 |
+
.. plot::
|
235 |
+
:context: reset
|
236 |
+
:format: doctest
|
237 |
+
:include-source: True
|
238 |
+
|
239 |
+
>>> from sympy import cos, sin, symbols
|
240 |
+
>>> from sympy.plotting.plot import _check_arguments
|
241 |
+
>>> x = symbols('x')
|
242 |
+
>>> _check_arguments([cos(x), sin(x)], 2, 1)
|
243 |
+
[(cos(x), sin(x), (x, -10, 10), None, None)]
|
244 |
+
|
245 |
+
>>> _check_arguments([cos(x), sin(x), "test"], 2, 1)
|
246 |
+
[(cos(x), sin(x), (x, -10, 10), 'test', None)]
|
247 |
+
|
248 |
+
>>> _check_arguments([cos(x), sin(x), "test", {"a": 0, "b": 1}], 2, 1)
|
249 |
+
[(cos(x), sin(x), (x, -10, 10), 'test', {'a': 0, 'b': 1})]
|
250 |
+
|
251 |
+
>>> _check_arguments([x, x**2], 1, 1)
|
252 |
+
[(x, (x, -10, 10), None, None), (x**2, (x, -10, 10), None, None)]
|
253 |
+
"""
|
254 |
+
if not args:
|
255 |
+
return []
|
256 |
+
output = []
|
257 |
+
params = kwargs.get("params", None)
|
258 |
+
|
259 |
+
if all(isinstance(a, (Expr, Relational, BooleanFunction)) for a in args[:nexpr]):
|
260 |
+
# In this case, with a single plot command, we are plotting either:
|
261 |
+
# 1. one expression
|
262 |
+
# 2. multiple expressions over the same range
|
263 |
+
|
264 |
+
exprs, ranges, label, rendering_kw = _unpack_args(*args)
|
265 |
+
free_symbols = set().union(*[e.free_symbols for e in exprs])
|
266 |
+
ranges = _create_ranges(exprs, ranges, npar, label, params)
|
267 |
+
|
268 |
+
if nexpr > 1:
|
269 |
+
# in case of plot_parametric or plot3d_parametric_line, there will
|
270 |
+
# be 2 or 3 expressions defining a curve. Group them together.
|
271 |
+
if len(exprs) == nexpr:
|
272 |
+
exprs = (tuple(exprs),)
|
273 |
+
for expr in exprs:
|
274 |
+
# need this if-else to deal with both plot/plot3d and
|
275 |
+
# plot_parametric/plot3d_parametric_line
|
276 |
+
is_expr = isinstance(expr, (Expr, Relational, BooleanFunction))
|
277 |
+
e = (expr,) if is_expr else expr
|
278 |
+
output.append((*e, *ranges, label, rendering_kw))
|
279 |
+
|
280 |
+
else:
|
281 |
+
# In this case, we are plotting multiple expressions, each one with its
|
282 |
+
# range. Each "expression" to be plotted has the following form:
|
283 |
+
# (expr, range, label) where label is optional
|
284 |
+
|
285 |
+
_, ranges, labels, rendering_kw = _unpack_args(*args)
|
286 |
+
labels = [labels] if labels else []
|
287 |
+
|
288 |
+
# number of expressions
|
289 |
+
n = (len(ranges) + len(labels) +
|
290 |
+
(len(rendering_kw) if rendering_kw is not None else 0))
|
291 |
+
new_args = args[:-n] if n > 0 else args
|
292 |
+
|
293 |
+
# at this point, new_args might just be [expr]. But I need it to be
|
294 |
+
# [[expr]] in order to be able to loop over
|
295 |
+
# [expr, range [opt], label [opt]]
|
296 |
+
if not isinstance(new_args[0], (list, tuple, Tuple)):
|
297 |
+
new_args = [new_args]
|
298 |
+
|
299 |
+
# Each arg has the form (expr1, expr2, ..., range1 [optional], ...,
|
300 |
+
# label [optional], rendering_kw [optional])
|
301 |
+
for arg in new_args:
|
302 |
+
# look for "local" range and label. If there is not, use "global".
|
303 |
+
l = [a for a in arg if isinstance(a, str)]
|
304 |
+
if not l:
|
305 |
+
l = labels
|
306 |
+
r = [a for a in arg if _is_range(a)]
|
307 |
+
if not r:
|
308 |
+
r = ranges.copy()
|
309 |
+
rend_kw = [a for a in arg if isinstance(a, dict)]
|
310 |
+
rend_kw = rendering_kw if len(rend_kw) == 0 else rend_kw[0]
|
311 |
+
|
312 |
+
# NOTE: arg = arg[:nexpr] may raise an exception if lambda
|
313 |
+
# functions are used. Execute the following instead:
|
314 |
+
arg = [arg[i] for i in range(nexpr)]
|
315 |
+
free_symbols = set()
|
316 |
+
if all(not callable(a) for a in arg):
|
317 |
+
free_symbols = free_symbols.union(*[a.free_symbols for a in arg])
|
318 |
+
if len(r) != npar:
|
319 |
+
r = _create_ranges(arg, r, npar, "", params)
|
320 |
+
|
321 |
+
label = None if not l else l[0]
|
322 |
+
output.append((*arg, *r, label, rend_kw))
|
323 |
+
return output
|
evalkit_internvl/lib/python3.10/site-packages/sympy/sandbox/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (369 Bytes). View file
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_wester.cpython-310.pyc
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f1f9b5f4ae26e18e8306a2e92d624a75677b0e01f26c9d971d9ac24ed803e397
|
3 |
+
size 113430
|
evalkit_tf437/lib/python3.10/site-packages/sklearn/decomposition/_factor_analysis.py
ADDED
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Factor Analysis.
|
2 |
+
|
3 |
+
A latent linear variable model.
|
4 |
+
|
5 |
+
FactorAnalysis is similar to probabilistic PCA implemented by PCA.score
|
6 |
+
While PCA assumes Gaussian noise with the same variance for each
|
7 |
+
feature, the FactorAnalysis model assumes different variances for
|
8 |
+
each of them.
|
9 |
+
|
10 |
+
This implementation is based on David Barber's Book,
|
11 |
+
Bayesian Reasoning and Machine Learning,
|
12 |
+
http://www.cs.ucl.ac.uk/staff/d.barber/brml,
|
13 |
+
Algorithm 21.1
|
14 |
+
"""
|
15 |
+
|
16 |
+
# Authors: The scikit-learn developers
|
17 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
18 |
+
|
19 |
+
import warnings
|
20 |
+
from math import log, sqrt
|
21 |
+
from numbers import Integral, Real
|
22 |
+
|
23 |
+
import numpy as np
|
24 |
+
from scipy import linalg
|
25 |
+
|
26 |
+
from ..base import (
|
27 |
+
BaseEstimator,
|
28 |
+
ClassNamePrefixFeaturesOutMixin,
|
29 |
+
TransformerMixin,
|
30 |
+
_fit_context,
|
31 |
+
)
|
32 |
+
from ..exceptions import ConvergenceWarning
|
33 |
+
from ..utils import check_random_state
|
34 |
+
from ..utils._param_validation import Interval, StrOptions
|
35 |
+
from ..utils.extmath import fast_logdet, randomized_svd, squared_norm
|
36 |
+
from ..utils.validation import check_is_fitted, validate_data
|
37 |
+
|
38 |
+
|
39 |
+
class FactorAnalysis(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator):
|
40 |
+
"""Factor Analysis (FA).
|
41 |
+
|
42 |
+
A simple linear generative model with Gaussian latent variables.
|
43 |
+
|
44 |
+
The observations are assumed to be caused by a linear transformation of
|
45 |
+
lower dimensional latent factors and added Gaussian noise.
|
46 |
+
Without loss of generality the factors are distributed according to a
|
47 |
+
Gaussian with zero mean and unit covariance. The noise is also zero mean
|
48 |
+
and has an arbitrary diagonal covariance matrix.
|
49 |
+
|
50 |
+
If we would restrict the model further, by assuming that the Gaussian
|
51 |
+
noise is even isotropic (all diagonal entries are the same) we would obtain
|
52 |
+
:class:`PCA`.
|
53 |
+
|
54 |
+
FactorAnalysis performs a maximum likelihood estimate of the so-called
|
55 |
+
`loading` matrix, the transformation of the latent variables to the
|
56 |
+
observed ones, using SVD based approach.
|
57 |
+
|
58 |
+
Read more in the :ref:`User Guide <FA>`.
|
59 |
+
|
60 |
+
.. versionadded:: 0.13
|
61 |
+
|
62 |
+
Parameters
|
63 |
+
----------
|
64 |
+
n_components : int, default=None
|
65 |
+
Dimensionality of latent space, the number of components
|
66 |
+
of ``X`` that are obtained after ``transform``.
|
67 |
+
If None, n_components is set to the number of features.
|
68 |
+
|
69 |
+
tol : float, default=1e-2
|
70 |
+
Stopping tolerance for log-likelihood increase.
|
71 |
+
|
72 |
+
copy : bool, default=True
|
73 |
+
Whether to make a copy of X. If ``False``, the input X gets overwritten
|
74 |
+
during fitting.
|
75 |
+
|
76 |
+
max_iter : int, default=1000
|
77 |
+
Maximum number of iterations.
|
78 |
+
|
79 |
+
noise_variance_init : array-like of shape (n_features,), default=None
|
80 |
+
The initial guess of the noise variance for each feature.
|
81 |
+
If None, it defaults to np.ones(n_features).
|
82 |
+
|
83 |
+
svd_method : {'lapack', 'randomized'}, default='randomized'
|
84 |
+
Which SVD method to use. If 'lapack' use standard SVD from
|
85 |
+
scipy.linalg, if 'randomized' use fast ``randomized_svd`` function.
|
86 |
+
Defaults to 'randomized'. For most applications 'randomized' will
|
87 |
+
be sufficiently precise while providing significant speed gains.
|
88 |
+
Accuracy can also be improved by setting higher values for
|
89 |
+
`iterated_power`. If this is not sufficient, for maximum precision
|
90 |
+
you should choose 'lapack'.
|
91 |
+
|
92 |
+
iterated_power : int, default=3
|
93 |
+
Number of iterations for the power method. 3 by default. Only used
|
94 |
+
if ``svd_method`` equals 'randomized'.
|
95 |
+
|
96 |
+
rotation : {'varimax', 'quartimax'}, default=None
|
97 |
+
If not None, apply the indicated rotation. Currently, varimax and
|
98 |
+
quartimax are implemented. See
|
99 |
+
`"The varimax criterion for analytic rotation in factor analysis"
|
100 |
+
<https://link.springer.com/article/10.1007%2FBF02289233>`_
|
101 |
+
H. F. Kaiser, 1958.
|
102 |
+
|
103 |
+
.. versionadded:: 0.24
|
104 |
+
|
105 |
+
random_state : int or RandomState instance, default=0
|
106 |
+
Only used when ``svd_method`` equals 'randomized'. Pass an int for
|
107 |
+
reproducible results across multiple function calls.
|
108 |
+
See :term:`Glossary <random_state>`.
|
109 |
+
|
110 |
+
Attributes
|
111 |
+
----------
|
112 |
+
components_ : ndarray of shape (n_components, n_features)
|
113 |
+
Components with maximum variance.
|
114 |
+
|
115 |
+
loglike_ : list of shape (n_iterations,)
|
116 |
+
The log likelihood at each iteration.
|
117 |
+
|
118 |
+
noise_variance_ : ndarray of shape (n_features,)
|
119 |
+
The estimated noise variance for each feature.
|
120 |
+
|
121 |
+
n_iter_ : int
|
122 |
+
Number of iterations run.
|
123 |
+
|
124 |
+
mean_ : ndarray of shape (n_features,)
|
125 |
+
Per-feature empirical mean, estimated from the training set.
|
126 |
+
|
127 |
+
n_features_in_ : int
|
128 |
+
Number of features seen during :term:`fit`.
|
129 |
+
|
130 |
+
.. versionadded:: 0.24
|
131 |
+
|
132 |
+
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
133 |
+
Names of features seen during :term:`fit`. Defined only when `X`
|
134 |
+
has feature names that are all strings.
|
135 |
+
|
136 |
+
.. versionadded:: 1.0
|
137 |
+
|
138 |
+
See Also
|
139 |
+
--------
|
140 |
+
PCA: Principal component analysis is also a latent linear variable model
|
141 |
+
which however assumes equal noise variance for each feature.
|
142 |
+
This extra assumption makes probabilistic PCA faster as it can be
|
143 |
+
computed in closed form.
|
144 |
+
FastICA: Independent component analysis, a latent variable model with
|
145 |
+
non-Gaussian latent variables.
|
146 |
+
|
147 |
+
References
|
148 |
+
----------
|
149 |
+
- David Barber, Bayesian Reasoning and Machine Learning,
|
150 |
+
Algorithm 21.1.
|
151 |
+
|
152 |
+
- Christopher M. Bishop: Pattern Recognition and Machine Learning,
|
153 |
+
Chapter 12.2.4.
|
154 |
+
|
155 |
+
Examples
|
156 |
+
--------
|
157 |
+
>>> from sklearn.datasets import load_digits
|
158 |
+
>>> from sklearn.decomposition import FactorAnalysis
|
159 |
+
>>> X, _ = load_digits(return_X_y=True)
|
160 |
+
>>> transformer = FactorAnalysis(n_components=7, random_state=0)
|
161 |
+
>>> X_transformed = transformer.fit_transform(X)
|
162 |
+
>>> X_transformed.shape
|
163 |
+
(1797, 7)
|
164 |
+
"""
|
165 |
+
|
166 |
+
_parameter_constraints: dict = {
|
167 |
+
"n_components": [Interval(Integral, 0, None, closed="left"), None],
|
168 |
+
"tol": [Interval(Real, 0.0, None, closed="left")],
|
169 |
+
"copy": ["boolean"],
|
170 |
+
"max_iter": [Interval(Integral, 1, None, closed="left")],
|
171 |
+
"noise_variance_init": ["array-like", None],
|
172 |
+
"svd_method": [StrOptions({"randomized", "lapack"})],
|
173 |
+
"iterated_power": [Interval(Integral, 0, None, closed="left")],
|
174 |
+
"rotation": [StrOptions({"varimax", "quartimax"}), None],
|
175 |
+
"random_state": ["random_state"],
|
176 |
+
}
|
177 |
+
|
178 |
+
def __init__(
|
179 |
+
self,
|
180 |
+
n_components=None,
|
181 |
+
*,
|
182 |
+
tol=1e-2,
|
183 |
+
copy=True,
|
184 |
+
max_iter=1000,
|
185 |
+
noise_variance_init=None,
|
186 |
+
svd_method="randomized",
|
187 |
+
iterated_power=3,
|
188 |
+
rotation=None,
|
189 |
+
random_state=0,
|
190 |
+
):
|
191 |
+
self.n_components = n_components
|
192 |
+
self.copy = copy
|
193 |
+
self.tol = tol
|
194 |
+
self.max_iter = max_iter
|
195 |
+
self.svd_method = svd_method
|
196 |
+
|
197 |
+
self.noise_variance_init = noise_variance_init
|
198 |
+
self.iterated_power = iterated_power
|
199 |
+
self.random_state = random_state
|
200 |
+
self.rotation = rotation
|
201 |
+
|
202 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
203 |
+
def fit(self, X, y=None):
|
204 |
+
"""Fit the FactorAnalysis model to X using SVD based approach.
|
205 |
+
|
206 |
+
Parameters
|
207 |
+
----------
|
208 |
+
X : array-like of shape (n_samples, n_features)
|
209 |
+
Training data.
|
210 |
+
|
211 |
+
y : Ignored
|
212 |
+
Ignored parameter.
|
213 |
+
|
214 |
+
Returns
|
215 |
+
-------
|
216 |
+
self : object
|
217 |
+
FactorAnalysis class instance.
|
218 |
+
"""
|
219 |
+
X = validate_data(
|
220 |
+
self, X, copy=self.copy, dtype=np.float64, force_writeable=True
|
221 |
+
)
|
222 |
+
|
223 |
+
n_samples, n_features = X.shape
|
224 |
+
n_components = self.n_components
|
225 |
+
if n_components is None:
|
226 |
+
n_components = n_features
|
227 |
+
|
228 |
+
self.mean_ = np.mean(X, axis=0)
|
229 |
+
X -= self.mean_
|
230 |
+
|
231 |
+
# some constant terms
|
232 |
+
nsqrt = sqrt(n_samples)
|
233 |
+
llconst = n_features * log(2.0 * np.pi) + n_components
|
234 |
+
var = np.var(X, axis=0)
|
235 |
+
|
236 |
+
if self.noise_variance_init is None:
|
237 |
+
psi = np.ones(n_features, dtype=X.dtype)
|
238 |
+
else:
|
239 |
+
if len(self.noise_variance_init) != n_features:
|
240 |
+
raise ValueError(
|
241 |
+
"noise_variance_init dimension does not "
|
242 |
+
"with number of features : %d != %d"
|
243 |
+
% (len(self.noise_variance_init), n_features)
|
244 |
+
)
|
245 |
+
psi = np.array(self.noise_variance_init)
|
246 |
+
|
247 |
+
loglike = []
|
248 |
+
old_ll = -np.inf
|
249 |
+
SMALL = 1e-12
|
250 |
+
|
251 |
+
# we'll modify svd outputs to return unexplained variance
|
252 |
+
# to allow for unified computation of loglikelihood
|
253 |
+
if self.svd_method == "lapack":
|
254 |
+
|
255 |
+
def my_svd(X):
|
256 |
+
_, s, Vt = linalg.svd(X, full_matrices=False, check_finite=False)
|
257 |
+
return (
|
258 |
+
s[:n_components],
|
259 |
+
Vt[:n_components],
|
260 |
+
squared_norm(s[n_components:]),
|
261 |
+
)
|
262 |
+
|
263 |
+
else: # svd_method == "randomized"
|
264 |
+
random_state = check_random_state(self.random_state)
|
265 |
+
|
266 |
+
def my_svd(X):
|
267 |
+
_, s, Vt = randomized_svd(
|
268 |
+
X,
|
269 |
+
n_components,
|
270 |
+
random_state=random_state,
|
271 |
+
n_iter=self.iterated_power,
|
272 |
+
)
|
273 |
+
return s, Vt, squared_norm(X) - squared_norm(s)
|
274 |
+
|
275 |
+
for i in range(self.max_iter):
|
276 |
+
# SMALL helps numerics
|
277 |
+
sqrt_psi = np.sqrt(psi) + SMALL
|
278 |
+
s, Vt, unexp_var = my_svd(X / (sqrt_psi * nsqrt))
|
279 |
+
s **= 2
|
280 |
+
# Use 'maximum' here to avoid sqrt problems.
|
281 |
+
W = np.sqrt(np.maximum(s - 1.0, 0.0))[:, np.newaxis] * Vt
|
282 |
+
del Vt
|
283 |
+
W *= sqrt_psi
|
284 |
+
|
285 |
+
# loglikelihood
|
286 |
+
ll = llconst + np.sum(np.log(s))
|
287 |
+
ll += unexp_var + np.sum(np.log(psi))
|
288 |
+
ll *= -n_samples / 2.0
|
289 |
+
loglike.append(ll)
|
290 |
+
if (ll - old_ll) < self.tol:
|
291 |
+
break
|
292 |
+
old_ll = ll
|
293 |
+
|
294 |
+
psi = np.maximum(var - np.sum(W**2, axis=0), SMALL)
|
295 |
+
else:
|
296 |
+
warnings.warn(
|
297 |
+
"FactorAnalysis did not converge."
|
298 |
+
+ " You might want"
|
299 |
+
+ " to increase the number of iterations.",
|
300 |
+
ConvergenceWarning,
|
301 |
+
)
|
302 |
+
|
303 |
+
self.components_ = W
|
304 |
+
if self.rotation is not None:
|
305 |
+
self.components_ = self._rotate(W)
|
306 |
+
self.noise_variance_ = psi
|
307 |
+
self.loglike_ = loglike
|
308 |
+
self.n_iter_ = i + 1
|
309 |
+
return self
|
310 |
+
|
311 |
+
def transform(self, X):
|
312 |
+
"""Apply dimensionality reduction to X using the model.
|
313 |
+
|
314 |
+
Compute the expected mean of the latent variables.
|
315 |
+
See Barber, 21.2.33 (or Bishop, 12.66).
|
316 |
+
|
317 |
+
Parameters
|
318 |
+
----------
|
319 |
+
X : array-like of shape (n_samples, n_features)
|
320 |
+
Training data.
|
321 |
+
|
322 |
+
Returns
|
323 |
+
-------
|
324 |
+
X_new : ndarray of shape (n_samples, n_components)
|
325 |
+
The latent variables of X.
|
326 |
+
"""
|
327 |
+
check_is_fitted(self)
|
328 |
+
|
329 |
+
X = validate_data(self, X, reset=False)
|
330 |
+
Ih = np.eye(len(self.components_))
|
331 |
+
|
332 |
+
X_transformed = X - self.mean_
|
333 |
+
|
334 |
+
Wpsi = self.components_ / self.noise_variance_
|
335 |
+
cov_z = linalg.inv(Ih + np.dot(Wpsi, self.components_.T))
|
336 |
+
tmp = np.dot(X_transformed, Wpsi.T)
|
337 |
+
X_transformed = np.dot(tmp, cov_z)
|
338 |
+
|
339 |
+
return X_transformed
|
340 |
+
|
341 |
+
def get_covariance(self):
|
342 |
+
"""Compute data covariance with the FactorAnalysis model.
|
343 |
+
|
344 |
+
``cov = components_.T * components_ + diag(noise_variance)``
|
345 |
+
|
346 |
+
Returns
|
347 |
+
-------
|
348 |
+
cov : ndarray of shape (n_features, n_features)
|
349 |
+
Estimated covariance of data.
|
350 |
+
"""
|
351 |
+
check_is_fitted(self)
|
352 |
+
|
353 |
+
cov = np.dot(self.components_.T, self.components_)
|
354 |
+
cov.flat[:: len(cov) + 1] += self.noise_variance_ # modify diag inplace
|
355 |
+
return cov
|
356 |
+
|
357 |
+
def get_precision(self):
|
358 |
+
"""Compute data precision matrix with the FactorAnalysis model.
|
359 |
+
|
360 |
+
Returns
|
361 |
+
-------
|
362 |
+
precision : ndarray of shape (n_features, n_features)
|
363 |
+
Estimated precision of data.
|
364 |
+
"""
|
365 |
+
check_is_fitted(self)
|
366 |
+
|
367 |
+
n_features = self.components_.shape[1]
|
368 |
+
|
369 |
+
# handle corner cases first
|
370 |
+
if self.n_components == 0:
|
371 |
+
return np.diag(1.0 / self.noise_variance_)
|
372 |
+
if self.n_components == n_features:
|
373 |
+
return linalg.inv(self.get_covariance())
|
374 |
+
|
375 |
+
# Get precision using matrix inversion lemma
|
376 |
+
components_ = self.components_
|
377 |
+
precision = np.dot(components_ / self.noise_variance_, components_.T)
|
378 |
+
precision.flat[:: len(precision) + 1] += 1.0
|
379 |
+
precision = np.dot(components_.T, np.dot(linalg.inv(precision), components_))
|
380 |
+
precision /= self.noise_variance_[:, np.newaxis]
|
381 |
+
precision /= -self.noise_variance_[np.newaxis, :]
|
382 |
+
precision.flat[:: len(precision) + 1] += 1.0 / self.noise_variance_
|
383 |
+
return precision
|
384 |
+
|
385 |
+
def score_samples(self, X):
|
386 |
+
"""Compute the log-likelihood of each sample.
|
387 |
+
|
388 |
+
Parameters
|
389 |
+
----------
|
390 |
+
X : ndarray of shape (n_samples, n_features)
|
391 |
+
The data.
|
392 |
+
|
393 |
+
Returns
|
394 |
+
-------
|
395 |
+
ll : ndarray of shape (n_samples,)
|
396 |
+
Log-likelihood of each sample under the current model.
|
397 |
+
"""
|
398 |
+
check_is_fitted(self)
|
399 |
+
X = validate_data(self, X, reset=False)
|
400 |
+
Xr = X - self.mean_
|
401 |
+
precision = self.get_precision()
|
402 |
+
n_features = X.shape[1]
|
403 |
+
log_like = -0.5 * (Xr * (np.dot(Xr, precision))).sum(axis=1)
|
404 |
+
log_like -= 0.5 * (n_features * log(2.0 * np.pi) - fast_logdet(precision))
|
405 |
+
return log_like
|
406 |
+
|
407 |
+
def score(self, X, y=None):
|
408 |
+
"""Compute the average log-likelihood of the samples.
|
409 |
+
|
410 |
+
Parameters
|
411 |
+
----------
|
412 |
+
X : ndarray of shape (n_samples, n_features)
|
413 |
+
The data.
|
414 |
+
|
415 |
+
y : Ignored
|
416 |
+
Ignored parameter.
|
417 |
+
|
418 |
+
Returns
|
419 |
+
-------
|
420 |
+
ll : float
|
421 |
+
Average log-likelihood of the samples under the current model.
|
422 |
+
"""
|
423 |
+
return np.mean(self.score_samples(X))
|
424 |
+
|
425 |
+
def _rotate(self, components, n_components=None, tol=1e-6):
|
426 |
+
"Rotate the factor analysis solution."
|
427 |
+
# note that tol is not exposed
|
428 |
+
return _ortho_rotation(components.T, method=self.rotation, tol=tol)[
|
429 |
+
: self.n_components
|
430 |
+
]
|
431 |
+
|
432 |
+
@property
|
433 |
+
def _n_features_out(self):
|
434 |
+
"""Number of transformed output features."""
|
435 |
+
return self.components_.shape[0]
|
436 |
+
|
437 |
+
|
438 |
+
def _ortho_rotation(components, method="varimax", tol=1e-6, max_iter=100):
|
439 |
+
"""Return rotated components."""
|
440 |
+
nrow, ncol = components.shape
|
441 |
+
rotation_matrix = np.eye(ncol)
|
442 |
+
var = 0
|
443 |
+
|
444 |
+
for _ in range(max_iter):
|
445 |
+
comp_rot = np.dot(components, rotation_matrix)
|
446 |
+
if method == "varimax":
|
447 |
+
tmp = comp_rot * np.transpose((comp_rot**2).sum(axis=0) / nrow)
|
448 |
+
elif method == "quartimax":
|
449 |
+
tmp = 0
|
450 |
+
u, s, v = np.linalg.svd(np.dot(components.T, comp_rot**3 - tmp))
|
451 |
+
rotation_matrix = np.dot(u, v)
|
452 |
+
var_new = np.sum(s)
|
453 |
+
if var != 0 and var_new < var * (1 + tol):
|
454 |
+
break
|
455 |
+
var = var_new
|
456 |
+
|
457 |
+
return np.dot(components, rotation_matrix).T
|
evalkit_tf437/lib/python3.10/site-packages/sklearn/decomposition/_incremental_pca.py
ADDED
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Incremental Principal Components Analysis."""
|
2 |
+
|
3 |
+
# Authors: The scikit-learn developers
|
4 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
5 |
+
|
6 |
+
from numbers import Integral
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
from scipy import linalg, sparse
|
10 |
+
|
11 |
+
from sklearn.utils import metadata_routing
|
12 |
+
|
13 |
+
from ..base import _fit_context
|
14 |
+
from ..utils import gen_batches
|
15 |
+
from ..utils._param_validation import Interval
|
16 |
+
from ..utils.extmath import _incremental_mean_and_var, svd_flip
|
17 |
+
from ..utils.validation import validate_data
|
18 |
+
from ._base import _BasePCA
|
19 |
+
|
20 |
+
|
21 |
+
class IncrementalPCA(_BasePCA):
|
22 |
+
"""Incremental principal components analysis (IPCA).
|
23 |
+
|
24 |
+
Linear dimensionality reduction using Singular Value Decomposition of
|
25 |
+
the data, keeping only the most significant singular vectors to
|
26 |
+
project the data to a lower dimensional space. The input data is centered
|
27 |
+
but not scaled for each feature before applying the SVD.
|
28 |
+
|
29 |
+
Depending on the size of the input data, this algorithm can be much more
|
30 |
+
memory efficient than a PCA, and allows sparse input.
|
31 |
+
|
32 |
+
This algorithm has constant memory complexity, on the order
|
33 |
+
of ``batch_size * n_features``, enabling use of np.memmap files without
|
34 |
+
loading the entire file into memory. For sparse matrices, the input
|
35 |
+
is converted to dense in batches (in order to be able to subtract the
|
36 |
+
mean) which avoids storing the entire dense matrix at any one time.
|
37 |
+
|
38 |
+
The computational overhead of each SVD is
|
39 |
+
``O(batch_size * n_features ** 2)``, but only 2 * batch_size samples
|
40 |
+
remain in memory at a time. There will be ``n_samples / batch_size`` SVD
|
41 |
+
computations to get the principal components, versus 1 large SVD of
|
42 |
+
complexity ``O(n_samples * n_features ** 2)`` for PCA.
|
43 |
+
|
44 |
+
For a usage example, see
|
45 |
+
:ref:`sphx_glr_auto_examples_decomposition_plot_incremental_pca.py`.
|
46 |
+
|
47 |
+
Read more in the :ref:`User Guide <IncrementalPCA>`.
|
48 |
+
|
49 |
+
.. versionadded:: 0.16
|
50 |
+
|
51 |
+
Parameters
|
52 |
+
----------
|
53 |
+
n_components : int, default=None
|
54 |
+
Number of components to keep. If ``n_components`` is ``None``,
|
55 |
+
then ``n_components`` is set to ``min(n_samples, n_features)``.
|
56 |
+
|
57 |
+
whiten : bool, default=False
|
58 |
+
When True (False by default) the ``components_`` vectors are divided
|
59 |
+
by ``n_samples`` times ``components_`` to ensure uncorrelated outputs
|
60 |
+
with unit component-wise variances.
|
61 |
+
|
62 |
+
Whitening will remove some information from the transformed signal
|
63 |
+
(the relative variance scales of the components) but can sometimes
|
64 |
+
improve the predictive accuracy of the downstream estimators by
|
65 |
+
making data respect some hard-wired assumptions.
|
66 |
+
|
67 |
+
copy : bool, default=True
|
68 |
+
If False, X will be overwritten. ``copy=False`` can be used to
|
69 |
+
save memory but is unsafe for general use.
|
70 |
+
|
71 |
+
batch_size : int, default=None
|
72 |
+
The number of samples to use for each batch. Only used when calling
|
73 |
+
``fit``. If ``batch_size`` is ``None``, then ``batch_size``
|
74 |
+
is inferred from the data and set to ``5 * n_features``, to provide a
|
75 |
+
balance between approximation accuracy and memory consumption.
|
76 |
+
|
77 |
+
Attributes
|
78 |
+
----------
|
79 |
+
components_ : ndarray of shape (n_components, n_features)
|
80 |
+
Principal axes in feature space, representing the directions of
|
81 |
+
maximum variance in the data. Equivalently, the right singular
|
82 |
+
vectors of the centered input data, parallel to its eigenvectors.
|
83 |
+
The components are sorted by decreasing ``explained_variance_``.
|
84 |
+
|
85 |
+
explained_variance_ : ndarray of shape (n_components,)
|
86 |
+
Variance explained by each of the selected components.
|
87 |
+
|
88 |
+
explained_variance_ratio_ : ndarray of shape (n_components,)
|
89 |
+
Percentage of variance explained by each of the selected components.
|
90 |
+
If all components are stored, the sum of explained variances is equal
|
91 |
+
to 1.0.
|
92 |
+
|
93 |
+
singular_values_ : ndarray of shape (n_components,)
|
94 |
+
The singular values corresponding to each of the selected components.
|
95 |
+
The singular values are equal to the 2-norms of the ``n_components``
|
96 |
+
variables in the lower-dimensional space.
|
97 |
+
|
98 |
+
mean_ : ndarray of shape (n_features,)
|
99 |
+
Per-feature empirical mean, aggregate over calls to ``partial_fit``.
|
100 |
+
|
101 |
+
var_ : ndarray of shape (n_features,)
|
102 |
+
Per-feature empirical variance, aggregate over calls to
|
103 |
+
``partial_fit``.
|
104 |
+
|
105 |
+
noise_variance_ : float
|
106 |
+
The estimated noise covariance following the Probabilistic PCA model
|
107 |
+
from Tipping and Bishop 1999. See "Pattern Recognition and
|
108 |
+
Machine Learning" by C. Bishop, 12.2.1 p. 574 or
|
109 |
+
http://www.miketipping.com/papers/met-mppca.pdf.
|
110 |
+
|
111 |
+
n_components_ : int
|
112 |
+
The estimated number of components. Relevant when
|
113 |
+
``n_components=None``.
|
114 |
+
|
115 |
+
n_samples_seen_ : int
|
116 |
+
The number of samples processed by the estimator. Will be reset on
|
117 |
+
new calls to fit, but increments across ``partial_fit`` calls.
|
118 |
+
|
119 |
+
batch_size_ : int
|
120 |
+
Inferred batch size from ``batch_size``.
|
121 |
+
|
122 |
+
n_features_in_ : int
|
123 |
+
Number of features seen during :term:`fit`.
|
124 |
+
|
125 |
+
.. versionadded:: 0.24
|
126 |
+
|
127 |
+
feature_names_in_ : ndarray of shape (`n_features_in_`,)
|
128 |
+
Names of features seen during :term:`fit`. Defined only when `X`
|
129 |
+
has feature names that are all strings.
|
130 |
+
|
131 |
+
.. versionadded:: 1.0
|
132 |
+
|
133 |
+
See Also
|
134 |
+
--------
|
135 |
+
PCA : Principal component analysis (PCA).
|
136 |
+
KernelPCA : Kernel Principal component analysis (KPCA).
|
137 |
+
SparsePCA : Sparse Principal Components Analysis (SparsePCA).
|
138 |
+
TruncatedSVD : Dimensionality reduction using truncated SVD.
|
139 |
+
|
140 |
+
Notes
|
141 |
+
-----
|
142 |
+
Implements the incremental PCA model from:
|
143 |
+
*D. Ross, J. Lim, R. Lin, M. Yang, Incremental Learning for Robust Visual
|
144 |
+
Tracking, International Journal of Computer Vision, Volume 77, Issue 1-3,
|
145 |
+
pp. 125-141, May 2008.*
|
146 |
+
See https://www.cs.toronto.edu/~dross/ivt/RossLimLinYang_ijcv.pdf
|
147 |
+
|
148 |
+
This model is an extension of the Sequential Karhunen-Loeve Transform from:
|
149 |
+
:doi:`A. Levy and M. Lindenbaum, Sequential Karhunen-Loeve Basis Extraction and
|
150 |
+
its Application to Images, IEEE Transactions on Image Processing, Volume 9,
|
151 |
+
Number 8, pp. 1371-1374, August 2000. <10.1109/83.855432>`
|
152 |
+
|
153 |
+
We have specifically abstained from an optimization used by authors of both
|
154 |
+
papers, a QR decomposition used in specific situations to reduce the
|
155 |
+
algorithmic complexity of the SVD. The source for this technique is
|
156 |
+
*Matrix Computations, Third Edition, G. Holub and C. Van Loan, Chapter 5,
|
157 |
+
section 5.4.4, pp 252-253.*. This technique has been omitted because it is
|
158 |
+
advantageous only when decomposing a matrix with ``n_samples`` (rows)
|
159 |
+
>= 5/3 * ``n_features`` (columns), and hurts the readability of the
|
160 |
+
implemented algorithm. This would be a good opportunity for future
|
161 |
+
optimization, if it is deemed necessary.
|
162 |
+
|
163 |
+
References
|
164 |
+
----------
|
165 |
+
D. Ross, J. Lim, R. Lin, M. Yang. Incremental Learning for Robust Visual
|
166 |
+
Tracking, International Journal of Computer Vision, Volume 77,
|
167 |
+
Issue 1-3, pp. 125-141, May 2008.
|
168 |
+
|
169 |
+
G. Golub and C. Van Loan. Matrix Computations, Third Edition, Chapter 5,
|
170 |
+
Section 5.4.4, pp. 252-253.
|
171 |
+
|
172 |
+
Examples
|
173 |
+
--------
|
174 |
+
>>> from sklearn.datasets import load_digits
|
175 |
+
>>> from sklearn.decomposition import IncrementalPCA
|
176 |
+
>>> from scipy import sparse
|
177 |
+
>>> X, _ = load_digits(return_X_y=True)
|
178 |
+
>>> transformer = IncrementalPCA(n_components=7, batch_size=200)
|
179 |
+
>>> # either partially fit on smaller batches of data
|
180 |
+
>>> transformer.partial_fit(X[:100, :])
|
181 |
+
IncrementalPCA(batch_size=200, n_components=7)
|
182 |
+
>>> # or let the fit function itself divide the data into batches
|
183 |
+
>>> X_sparse = sparse.csr_matrix(X)
|
184 |
+
>>> X_transformed = transformer.fit_transform(X_sparse)
|
185 |
+
>>> X_transformed.shape
|
186 |
+
(1797, 7)
|
187 |
+
"""
|
188 |
+
|
189 |
+
__metadata_request__partial_fit = {"check_input": metadata_routing.UNUSED}
|
190 |
+
|
191 |
+
_parameter_constraints: dict = {
|
192 |
+
"n_components": [Interval(Integral, 1, None, closed="left"), None],
|
193 |
+
"whiten": ["boolean"],
|
194 |
+
"copy": ["boolean"],
|
195 |
+
"batch_size": [Interval(Integral, 1, None, closed="left"), None],
|
196 |
+
}
|
197 |
+
|
198 |
+
def __init__(self, n_components=None, *, whiten=False, copy=True, batch_size=None):
|
199 |
+
self.n_components = n_components
|
200 |
+
self.whiten = whiten
|
201 |
+
self.copy = copy
|
202 |
+
self.batch_size = batch_size
|
203 |
+
|
204 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
205 |
+
def fit(self, X, y=None):
|
206 |
+
"""Fit the model with X, using minibatches of size batch_size.
|
207 |
+
|
208 |
+
Parameters
|
209 |
+
----------
|
210 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
211 |
+
Training data, where `n_samples` is the number of samples and
|
212 |
+
`n_features` is the number of features.
|
213 |
+
|
214 |
+
y : Ignored
|
215 |
+
Not used, present for API consistency by convention.
|
216 |
+
|
217 |
+
Returns
|
218 |
+
-------
|
219 |
+
self : object
|
220 |
+
Returns the instance itself.
|
221 |
+
"""
|
222 |
+
self.components_ = None
|
223 |
+
self.n_samples_seen_ = 0
|
224 |
+
self.mean_ = 0.0
|
225 |
+
self.var_ = 0.0
|
226 |
+
self.singular_values_ = None
|
227 |
+
self.explained_variance_ = None
|
228 |
+
self.explained_variance_ratio_ = None
|
229 |
+
self.noise_variance_ = None
|
230 |
+
|
231 |
+
X = validate_data(
|
232 |
+
self,
|
233 |
+
X,
|
234 |
+
accept_sparse=["csr", "csc", "lil"],
|
235 |
+
copy=self.copy,
|
236 |
+
dtype=[np.float64, np.float32],
|
237 |
+
force_writeable=True,
|
238 |
+
)
|
239 |
+
n_samples, n_features = X.shape
|
240 |
+
|
241 |
+
if self.batch_size is None:
|
242 |
+
self.batch_size_ = 5 * n_features
|
243 |
+
else:
|
244 |
+
self.batch_size_ = self.batch_size
|
245 |
+
|
246 |
+
for batch in gen_batches(
|
247 |
+
n_samples, self.batch_size_, min_batch_size=self.n_components or 0
|
248 |
+
):
|
249 |
+
X_batch = X[batch]
|
250 |
+
if sparse.issparse(X_batch):
|
251 |
+
X_batch = X_batch.toarray()
|
252 |
+
self.partial_fit(X_batch, check_input=False)
|
253 |
+
|
254 |
+
return self
|
255 |
+
|
256 |
+
@_fit_context(prefer_skip_nested_validation=True)
|
257 |
+
def partial_fit(self, X, y=None, check_input=True):
|
258 |
+
"""Incremental fit with X. All of X is processed as a single batch.
|
259 |
+
|
260 |
+
Parameters
|
261 |
+
----------
|
262 |
+
X : array-like of shape (n_samples, n_features)
|
263 |
+
Training data, where `n_samples` is the number of samples and
|
264 |
+
`n_features` is the number of features.
|
265 |
+
|
266 |
+
y : Ignored
|
267 |
+
Not used, present for API consistency by convention.
|
268 |
+
|
269 |
+
check_input : bool, default=True
|
270 |
+
Run check_array on X.
|
271 |
+
|
272 |
+
Returns
|
273 |
+
-------
|
274 |
+
self : object
|
275 |
+
Returns the instance itself.
|
276 |
+
"""
|
277 |
+
first_pass = not hasattr(self, "components_")
|
278 |
+
|
279 |
+
if check_input:
|
280 |
+
if sparse.issparse(X):
|
281 |
+
raise TypeError(
|
282 |
+
"IncrementalPCA.partial_fit does not support "
|
283 |
+
"sparse input. Either convert data to dense "
|
284 |
+
"or use IncrementalPCA.fit to do so in batches."
|
285 |
+
)
|
286 |
+
X = validate_data(
|
287 |
+
self,
|
288 |
+
X,
|
289 |
+
copy=self.copy,
|
290 |
+
dtype=[np.float64, np.float32],
|
291 |
+
force_writeable=True,
|
292 |
+
reset=first_pass,
|
293 |
+
)
|
294 |
+
n_samples, n_features = X.shape
|
295 |
+
if first_pass:
|
296 |
+
self.components_ = None
|
297 |
+
|
298 |
+
if self.n_components is None:
|
299 |
+
if self.components_ is None:
|
300 |
+
self.n_components_ = min(n_samples, n_features)
|
301 |
+
else:
|
302 |
+
self.n_components_ = self.components_.shape[0]
|
303 |
+
elif not self.n_components <= n_features:
|
304 |
+
raise ValueError(
|
305 |
+
"n_components=%r invalid for n_features=%d, need "
|
306 |
+
"more rows than columns for IncrementalPCA "
|
307 |
+
"processing" % (self.n_components, n_features)
|
308 |
+
)
|
309 |
+
elif self.n_components > n_samples and first_pass:
|
310 |
+
raise ValueError(
|
311 |
+
f"n_components={self.n_components} must be less or equal to "
|
312 |
+
f"the batch number of samples {n_samples} for the first "
|
313 |
+
"partial_fit call."
|
314 |
+
)
|
315 |
+
else:
|
316 |
+
self.n_components_ = self.n_components
|
317 |
+
|
318 |
+
if (self.components_ is not None) and (
|
319 |
+
self.components_.shape[0] != self.n_components_
|
320 |
+
):
|
321 |
+
raise ValueError(
|
322 |
+
"Number of input features has changed from %i "
|
323 |
+
"to %i between calls to partial_fit! Try "
|
324 |
+
"setting n_components to a fixed value."
|
325 |
+
% (self.components_.shape[0], self.n_components_)
|
326 |
+
)
|
327 |
+
|
328 |
+
# This is the first partial_fit
|
329 |
+
if not hasattr(self, "n_samples_seen_"):
|
330 |
+
self.n_samples_seen_ = 0
|
331 |
+
self.mean_ = 0.0
|
332 |
+
self.var_ = 0.0
|
333 |
+
|
334 |
+
# Update stats - they are 0 if this is the first step
|
335 |
+
col_mean, col_var, n_total_samples = _incremental_mean_and_var(
|
336 |
+
X,
|
337 |
+
last_mean=self.mean_,
|
338 |
+
last_variance=self.var_,
|
339 |
+
last_sample_count=np.repeat(self.n_samples_seen_, X.shape[1]),
|
340 |
+
)
|
341 |
+
n_total_samples = n_total_samples[0]
|
342 |
+
|
343 |
+
# Whitening
|
344 |
+
if self.n_samples_seen_ == 0:
|
345 |
+
# If it is the first step, simply whiten X
|
346 |
+
X -= col_mean
|
347 |
+
else:
|
348 |
+
col_batch_mean = np.mean(X, axis=0)
|
349 |
+
X -= col_batch_mean
|
350 |
+
# Build matrix of combined previous basis and new data
|
351 |
+
mean_correction = np.sqrt(
|
352 |
+
(self.n_samples_seen_ / n_total_samples) * n_samples
|
353 |
+
) * (self.mean_ - col_batch_mean)
|
354 |
+
X = np.vstack(
|
355 |
+
(
|
356 |
+
self.singular_values_.reshape((-1, 1)) * self.components_,
|
357 |
+
X,
|
358 |
+
mean_correction,
|
359 |
+
)
|
360 |
+
)
|
361 |
+
|
362 |
+
U, S, Vt = linalg.svd(X, full_matrices=False, check_finite=False)
|
363 |
+
U, Vt = svd_flip(U, Vt, u_based_decision=False)
|
364 |
+
explained_variance = S**2 / (n_total_samples - 1)
|
365 |
+
explained_variance_ratio = S**2 / np.sum(col_var * n_total_samples)
|
366 |
+
|
367 |
+
self.n_samples_seen_ = n_total_samples
|
368 |
+
self.components_ = Vt[: self.n_components_]
|
369 |
+
self.singular_values_ = S[: self.n_components_]
|
370 |
+
self.mean_ = col_mean
|
371 |
+
self.var_ = col_var
|
372 |
+
self.explained_variance_ = explained_variance[: self.n_components_]
|
373 |
+
self.explained_variance_ratio_ = explained_variance_ratio[: self.n_components_]
|
374 |
+
# we already checked `self.n_components <= n_samples` above
|
375 |
+
if self.n_components_ not in (n_samples, n_features):
|
376 |
+
self.noise_variance_ = explained_variance[self.n_components_ :].mean()
|
377 |
+
else:
|
378 |
+
self.noise_variance_ = 0.0
|
379 |
+
return self
|
380 |
+
|
381 |
+
def transform(self, X):
|
382 |
+
"""Apply dimensionality reduction to X.
|
383 |
+
|
384 |
+
X is projected on the first principal components previously extracted
|
385 |
+
from a training set, using minibatches of size batch_size if X is
|
386 |
+
sparse.
|
387 |
+
|
388 |
+
Parameters
|
389 |
+
----------
|
390 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
391 |
+
New data, where `n_samples` is the number of samples
|
392 |
+
and `n_features` is the number of features.
|
393 |
+
|
394 |
+
Returns
|
395 |
+
-------
|
396 |
+
X_new : ndarray of shape (n_samples, n_components)
|
397 |
+
Projection of X in the first principal components.
|
398 |
+
|
399 |
+
Examples
|
400 |
+
--------
|
401 |
+
|
402 |
+
>>> import numpy as np
|
403 |
+
>>> from sklearn.decomposition import IncrementalPCA
|
404 |
+
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2],
|
405 |
+
... [1, 1], [2, 1], [3, 2]])
|
406 |
+
>>> ipca = IncrementalPCA(n_components=2, batch_size=3)
|
407 |
+
>>> ipca.fit(X)
|
408 |
+
IncrementalPCA(batch_size=3, n_components=2)
|
409 |
+
>>> ipca.transform(X) # doctest: +SKIP
|
410 |
+
"""
|
411 |
+
if sparse.issparse(X):
|
412 |
+
n_samples = X.shape[0]
|
413 |
+
output = []
|
414 |
+
for batch in gen_batches(
|
415 |
+
n_samples, self.batch_size_, min_batch_size=self.n_components or 0
|
416 |
+
):
|
417 |
+
output.append(super().transform(X[batch].toarray()))
|
418 |
+
return np.vstack(output)
|
419 |
+
else:
|
420 |
+
return super().transform(X)
|
421 |
+
|
422 |
+
def __sklearn_tags__(self):
|
423 |
+
tags = super().__sklearn_tags__()
|
424 |
+
# Beware that fit accepts sparse data but partial_fit doesn't
|
425 |
+
tags.input_tags.sparse = True
|
426 |
+
return tags
|