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 +1 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/__init__.py +22 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/experimental_lambdify.py +641 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/plot.py +1234 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/plot_implicit.py +233 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/plotgrid.py +188 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/pygletplot/__init__.py +138 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/pygletplot/color_scheme.py +336 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/pygletplot/managed_window.py +106 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_object.py +17 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_surface.py +102 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/series.py +2591 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/textplot.py +168 -0
- vllm/lib/python3.10/site-packages/sympy/plotting/utils.py +323 -0
- vllm/lib/python3.10/site-packages/sympy/polys/benchmarks/__pycache__/bench_solvers.cpython-310.pyc +3 -0
- vllm/lib/python3.10/site-packages/sympy/sandbox/__init__.py +8 -0
- vllm/lib/python3.10/site-packages/sympy/sandbox/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/sandbox/__pycache__/indexed_integrals.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/sandbox/indexed_integrals.py +72 -0
- vllm/lib/python3.10/site-packages/sympy/sandbox/tests/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/test_indexed_integrals.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/sandbox/tests/test_indexed_integrals.py +25 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/recurr.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/simplex.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/benchmarks/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/bench_solvers.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py +12 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/__init__.py +16 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/hypergeometric.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/riccati.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/subscheck.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/systems.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/lie_group.py +1097 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/nonhomogeneous.py +499 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/single.py +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/subscheck.py +392 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_lie_group.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -1680,3 +1680,4 @@ vllm/lib/python3.10/site-packages/sympy/polys/tests/__pycache__/test_polytools.c
|
|
| 1680 |
vllm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyquinticconst.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1681 |
vllm/lib/python3.10/site-packages/sympy/polys/__pycache__/polytools.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1682 |
vllm/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainmatrix.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 1680 |
vllm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyquinticconst.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1681 |
vllm/lib/python3.10/site-packages/sympy/polys/__pycache__/polytools.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1682 |
vllm/lib/python3.10/site-packages/sympy/polys/matrices/__pycache__/domainmatrix.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1683 |
+
vllm/lib/python3.10/site-packages/sympy/polys/benchmarks/__pycache__/bench_solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
vllm/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 |
+
]
|
vllm/lib/python3.10/site-packages/sympy/plotting/experimental_lambdify.py
ADDED
|
@@ -0,0 +1,641 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
vllm/lib/python3.10/site-packages/sympy/plotting/plot.py
ADDED
|
@@ -0,0 +1,1234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
vllm/lib/python3.10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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
vllm/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)
|
vllm/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)
|
vllm/lib/python3.10/site-packages/sympy/plotting/pygletplot/color_scheme.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)])
|
vllm/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()
|
vllm/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
|
vllm/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
|
vllm/lib/python3.10/site-packages/sympy/plotting/series.py
ADDED
|
@@ -0,0 +1,2591 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
vllm/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)
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|
| 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
|
vllm/lib/python3.10/site-packages/sympy/polys/benchmarks/__pycache__/bench_solvers.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ed17115d5df362673b472a7ec8d119f11c8feccb3945bdca7f746a135fc35b5c
|
| 3 |
+
size 334846
|
vllm/lib/python3.10/site-packages/sympy/sandbox/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sandbox module of SymPy.
|
| 3 |
+
|
| 4 |
+
This module contains experimental code, use at your own risk!
|
| 5 |
+
|
| 6 |
+
There is no warranty that this code will still be located here in future
|
| 7 |
+
versions of SymPy.
|
| 8 |
+
"""
|
vllm/lib/python3.10/site-packages/sympy/sandbox/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (357 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/sandbox/__pycache__/indexed_integrals.cpython-310.pyc
ADDED
|
Binary file (2.55 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/sandbox/indexed_integrals.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.tensor import Indexed
|
| 2 |
+
from sympy.core.containers import Tuple
|
| 3 |
+
from sympy.core.symbol import Dummy
|
| 4 |
+
from sympy.core.sympify import sympify
|
| 5 |
+
from sympy.integrals.integrals import Integral
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class IndexedIntegral(Integral):
|
| 9 |
+
"""
|
| 10 |
+
Experimental class to test integration by indexed variables.
|
| 11 |
+
|
| 12 |
+
Usage is analogue to ``Integral``, it simply adds awareness of
|
| 13 |
+
integration over indices.
|
| 14 |
+
|
| 15 |
+
Contraction of non-identical index symbols referring to the same
|
| 16 |
+
``IndexedBase`` is not yet supported.
|
| 17 |
+
|
| 18 |
+
Examples
|
| 19 |
+
========
|
| 20 |
+
|
| 21 |
+
>>> from sympy.sandbox.indexed_integrals import IndexedIntegral
|
| 22 |
+
>>> from sympy import IndexedBase, symbols
|
| 23 |
+
>>> A = IndexedBase('A')
|
| 24 |
+
>>> i, j = symbols('i j', integer=True)
|
| 25 |
+
>>> ii = IndexedIntegral(A[i], A[i])
|
| 26 |
+
>>> ii
|
| 27 |
+
Integral(_A[i], _A[i])
|
| 28 |
+
>>> ii.doit()
|
| 29 |
+
A[i]**2/2
|
| 30 |
+
|
| 31 |
+
If the indices are different, indexed objects are considered to be
|
| 32 |
+
different variables:
|
| 33 |
+
|
| 34 |
+
>>> i2 = IndexedIntegral(A[j], A[i])
|
| 35 |
+
>>> i2
|
| 36 |
+
Integral(A[j], _A[i])
|
| 37 |
+
>>> i2.doit()
|
| 38 |
+
A[i]*A[j]
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __new__(cls, function, *limits, **assumptions):
|
| 42 |
+
repl, limits = IndexedIntegral._indexed_process_limits(limits)
|
| 43 |
+
function = sympify(function)
|
| 44 |
+
function = function.xreplace(repl)
|
| 45 |
+
obj = Integral.__new__(cls, function, *limits, **assumptions)
|
| 46 |
+
obj._indexed_repl = repl
|
| 47 |
+
obj._indexed_reverse_repl = {val: key for key, val in repl.items()}
|
| 48 |
+
return obj
|
| 49 |
+
|
| 50 |
+
def doit(self):
|
| 51 |
+
res = super().doit()
|
| 52 |
+
return res.xreplace(self._indexed_reverse_repl)
|
| 53 |
+
|
| 54 |
+
@staticmethod
|
| 55 |
+
def _indexed_process_limits(limits):
|
| 56 |
+
repl = {}
|
| 57 |
+
newlimits = []
|
| 58 |
+
for i in limits:
|
| 59 |
+
if isinstance(i, (tuple, list, Tuple)):
|
| 60 |
+
v = i[0]
|
| 61 |
+
vrest = i[1:]
|
| 62 |
+
else:
|
| 63 |
+
v = i
|
| 64 |
+
vrest = ()
|
| 65 |
+
if isinstance(v, Indexed):
|
| 66 |
+
if v not in repl:
|
| 67 |
+
r = Dummy(str(v))
|
| 68 |
+
repl[v] = r
|
| 69 |
+
newlimits.append((r,)+vrest)
|
| 70 |
+
else:
|
| 71 |
+
newlimits.append(i)
|
| 72 |
+
return repl, newlimits
|
vllm/lib/python3.10/site-packages/sympy/sandbox/tests/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (169 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/sandbox/tests/__pycache__/test_indexed_integrals.cpython-310.pyc
ADDED
|
Binary file (1.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/sandbox/tests/test_indexed_integrals.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.sandbox.indexed_integrals import IndexedIntegral
|
| 2 |
+
from sympy.core.symbol import symbols
|
| 3 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 4 |
+
from sympy.tensor.indexed import (Idx, IndexedBase)
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_indexed_integrals():
|
| 8 |
+
A = IndexedBase('A')
|
| 9 |
+
i, j = symbols('i j', integer=True)
|
| 10 |
+
a1, a2 = symbols('a1:3', cls=Idx)
|
| 11 |
+
assert isinstance(a1, Idx)
|
| 12 |
+
|
| 13 |
+
assert IndexedIntegral(1, A[i]).doit() == A[i]
|
| 14 |
+
assert IndexedIntegral(A[i], A[i]).doit() == A[i] ** 2 / 2
|
| 15 |
+
assert IndexedIntegral(A[j], A[i]).doit() == A[i] * A[j]
|
| 16 |
+
assert IndexedIntegral(A[i] * A[j], A[i]).doit() == A[i] ** 2 * A[j] / 2
|
| 17 |
+
assert IndexedIntegral(sin(A[i]), A[i]).doit() == -cos(A[i])
|
| 18 |
+
assert IndexedIntegral(sin(A[j]), A[i]).doit() == sin(A[j]) * A[i]
|
| 19 |
+
|
| 20 |
+
assert IndexedIntegral(1, A[a1]).doit() == A[a1]
|
| 21 |
+
assert IndexedIntegral(A[a1], A[a1]).doit() == A[a1] ** 2 / 2
|
| 22 |
+
assert IndexedIntegral(A[a2], A[a1]).doit() == A[a1] * A[a2]
|
| 23 |
+
assert IndexedIntegral(A[a1] * A[a2], A[a1]).doit() == A[a1] ** 2 * A[a2] / 2
|
| 24 |
+
assert IndexedIntegral(sin(A[a1]), A[a1]).doit() == -cos(A[a1])
|
| 25 |
+
assert IndexedIntegral(sin(A[a2]), A[a1]).doit() == sin(A[a2]) * A[a1]
|
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc
ADDED
|
Binary file (3.48 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc
ADDED
|
Binary file (8.04 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc
ADDED
|
Binary file (23.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc
ADDED
|
Binary file (29.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/recurr.cpython-310.pyc
ADDED
|
Binary file (22.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/simplex.cpython-310.pyc
ADDED
|
Binary file (32.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/benchmarks/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (174 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/bench_solvers.cpython-310.pyc
ADDED
|
Binary file (714 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.symbol import Symbol
|
| 2 |
+
from sympy.matrices.dense import (eye, zeros)
|
| 3 |
+
from sympy.solvers.solvers import solve_linear_system
|
| 4 |
+
|
| 5 |
+
N = 8
|
| 6 |
+
M = zeros(N, N + 1)
|
| 7 |
+
M[:, :N] = eye(N)
|
| 8 |
+
S = [Symbol('A%i' % i) for i in range(N)]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def timeit_linsolve_trivial():
|
| 12 |
+
solve_linear_system(M, *S)
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .ode import (allhints, checkinfsol, classify_ode,
|
| 2 |
+
constantsimp, dsolve, homogeneous_order)
|
| 3 |
+
|
| 4 |
+
from .lie_group import infinitesimals
|
| 5 |
+
|
| 6 |
+
from .subscheck import checkodesol
|
| 7 |
+
|
| 8 |
+
from .systems import (canonical_odes, linear_ode_to_matrix,
|
| 9 |
+
linodesolve)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
'allhints', 'checkinfsol', 'checkodesol', 'classify_ode', 'constantsimp',
|
| 14 |
+
'dsolve', 'homogeneous_order', 'infinitesimals', 'canonical_odes', 'linear_ode_to_matrix',
|
| 15 |
+
'linodesolve'
|
| 16 |
+
]
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (584 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/hypergeometric.cpython-310.pyc
ADDED
|
Binary file (7.06 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc
ADDED
|
Binary file (30.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc
ADDED
|
Binary file (14.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/riccati.cpython-310.pyc
ADDED
|
Binary file (24.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/subscheck.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/systems.cpython-310.pyc
ADDED
|
Binary file (66.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/lie_group.py
ADDED
|
@@ -0,0 +1,1097 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
This module contains the implementation of the internal helper functions for the lie_group hint for
|
| 3 |
+
dsolve. These helper functions apply different heuristics on the given equation
|
| 4 |
+
and return the solution. These functions are used by :py:meth:`sympy.solvers.ode.single.LieGroup`
|
| 5 |
+
|
| 6 |
+
References
|
| 7 |
+
=========
|
| 8 |
+
|
| 9 |
+
- `abaco1_simple`, `function_sum` and `chi` are referenced from E.S Cheb-Terrab, L.G.S Duarte
|
| 10 |
+
and L.A,C.P da Mota, Computer Algebra Solving of First Order ODEs Using
|
| 11 |
+
Symmetry Methods, pp. 7 - pp. 8
|
| 12 |
+
|
| 13 |
+
- `abaco1_product`, `abaco2_similar`, `abaco2_unique_unknown`, `linear` and `abaco2_unique_general`
|
| 14 |
+
are referenced from E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
|
| 15 |
+
ODE Patterns, pp. 7 - pp. 12
|
| 16 |
+
|
| 17 |
+
- `bivariate` from Lie Groups and Differential Equations pp. 327 - pp. 329
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
from itertools import islice
|
| 21 |
+
|
| 22 |
+
from sympy.core import Add, S, Mul, Pow
|
| 23 |
+
from sympy.core.exprtools import factor_terms
|
| 24 |
+
from sympy.core.function import Function, AppliedUndef, expand
|
| 25 |
+
from sympy.core.relational import Equality, Eq
|
| 26 |
+
from sympy.core.symbol import Symbol, Wild, Dummy, symbols
|
| 27 |
+
from sympy.functions import exp, log
|
| 28 |
+
from sympy.integrals.integrals import integrate
|
| 29 |
+
from sympy.polys import Poly
|
| 30 |
+
from sympy.polys.polytools import cancel, div
|
| 31 |
+
from sympy.simplify import (collect, powsimp, # type: ignore
|
| 32 |
+
separatevars, simplify)
|
| 33 |
+
from sympy.solvers import solve
|
| 34 |
+
from sympy.solvers.pde import pdsolve
|
| 35 |
+
|
| 36 |
+
from sympy.utilities import numbered_symbols
|
| 37 |
+
from sympy.solvers.deutils import _preprocess, ode_order
|
| 38 |
+
from .ode import checkinfsol
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
lie_heuristics = (
|
| 42 |
+
"abaco1_simple",
|
| 43 |
+
"abaco1_product",
|
| 44 |
+
"abaco2_similar",
|
| 45 |
+
"abaco2_unique_unknown",
|
| 46 |
+
"abaco2_unique_general",
|
| 47 |
+
"linear",
|
| 48 |
+
"function_sum",
|
| 49 |
+
"bivariate",
|
| 50 |
+
"chi"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _ode_lie_group_try_heuristic(eq, heuristic, func, match, inf):
|
| 55 |
+
|
| 56 |
+
xi = Function("xi")
|
| 57 |
+
eta = Function("eta")
|
| 58 |
+
f = func.func
|
| 59 |
+
x = func.args[0]
|
| 60 |
+
y = match['y']
|
| 61 |
+
h = match['h']
|
| 62 |
+
tempsol = []
|
| 63 |
+
if not inf:
|
| 64 |
+
try:
|
| 65 |
+
inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match)
|
| 66 |
+
except ValueError:
|
| 67 |
+
return None
|
| 68 |
+
for infsim in inf:
|
| 69 |
+
xiinf = (infsim[xi(x, func)]).subs(func, y)
|
| 70 |
+
etainf = (infsim[eta(x, func)]).subs(func, y)
|
| 71 |
+
# This condition creates recursion while using pdsolve.
|
| 72 |
+
# Since the first step while solving a PDE of form
|
| 73 |
+
# a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0
|
| 74 |
+
# is to solve the ODE dy/dx = b/a
|
| 75 |
+
if simplify(etainf/xiinf) == h:
|
| 76 |
+
continue
|
| 77 |
+
rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf
|
| 78 |
+
r = pdsolve(rpde, func=f(x, y)).rhs
|
| 79 |
+
s = pdsolve(rpde - 1, func=f(x, y)).rhs
|
| 80 |
+
newcoord = [_lie_group_remove(coord) for coord in [r, s]]
|
| 81 |
+
r = Dummy("r")
|
| 82 |
+
s = Dummy("s")
|
| 83 |
+
C1 = Symbol("C1")
|
| 84 |
+
rcoord = newcoord[0]
|
| 85 |
+
scoord = newcoord[-1]
|
| 86 |
+
try:
|
| 87 |
+
sol = solve([r - rcoord, s - scoord], x, y, dict=True)
|
| 88 |
+
if sol == []:
|
| 89 |
+
continue
|
| 90 |
+
except NotImplementedError:
|
| 91 |
+
continue
|
| 92 |
+
else:
|
| 93 |
+
sol = sol[0]
|
| 94 |
+
xsub = sol[x]
|
| 95 |
+
ysub = sol[y]
|
| 96 |
+
num = simplify(scoord.diff(x) + scoord.diff(y)*h)
|
| 97 |
+
denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h)
|
| 98 |
+
if num and denom:
|
| 99 |
+
diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)]))
|
| 100 |
+
sep = separatevars(diffeq, symbols=[r, s], dict=True)
|
| 101 |
+
if sep:
|
| 102 |
+
# Trying to separate, r and s coordinates
|
| 103 |
+
deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r)
|
| 104 |
+
# Substituting and reverting back to original coordinates
|
| 105 |
+
deq = deq.subs([(r, rcoord), (s, scoord)])
|
| 106 |
+
try:
|
| 107 |
+
sdeq = solve(deq, y)
|
| 108 |
+
except NotImplementedError:
|
| 109 |
+
tempsol.append(deq)
|
| 110 |
+
else:
|
| 111 |
+
return [Eq(f(x), sol) for sol in sdeq]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
elif denom: # (ds/dr) is zero which means s is constant
|
| 115 |
+
return [Eq(f(x), solve(scoord - C1, y)[0])]
|
| 116 |
+
|
| 117 |
+
elif num: # (dr/ds) is zero which means r is constant
|
| 118 |
+
return [Eq(f(x), solve(rcoord - C1, y)[0])]
|
| 119 |
+
|
| 120 |
+
# If nothing works, return solution as it is, without solving for y
|
| 121 |
+
if tempsol:
|
| 122 |
+
return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol]
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _ode_lie_group( s, func, order, match):
|
| 127 |
+
|
| 128 |
+
heuristics = lie_heuristics
|
| 129 |
+
inf = {}
|
| 130 |
+
f = func.func
|
| 131 |
+
x = func.args[0]
|
| 132 |
+
df = func.diff(x)
|
| 133 |
+
xi = Function("xi")
|
| 134 |
+
eta = Function("eta")
|
| 135 |
+
xis = match['xi']
|
| 136 |
+
etas = match['eta']
|
| 137 |
+
y = match.pop('y', None)
|
| 138 |
+
if y:
|
| 139 |
+
h = -simplify(match[match['d']]/match[match['e']])
|
| 140 |
+
y = y
|
| 141 |
+
else:
|
| 142 |
+
y = Dummy("y")
|
| 143 |
+
h = s.subs(func, y)
|
| 144 |
+
|
| 145 |
+
if xis is not None and etas is not None:
|
| 146 |
+
inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}]
|
| 147 |
+
|
| 148 |
+
if checkinfsol(Eq(df, s), inf, func=f(x), order=1)[0][0]:
|
| 149 |
+
heuristics = ["user_defined"] + list(heuristics)
|
| 150 |
+
|
| 151 |
+
match = {'h': h, 'y': y}
|
| 152 |
+
|
| 153 |
+
# This is done so that if any heuristic raises a ValueError
|
| 154 |
+
# another heuristic can be used.
|
| 155 |
+
sol = None
|
| 156 |
+
for heuristic in heuristics:
|
| 157 |
+
sol = _ode_lie_group_try_heuristic(Eq(df, s), heuristic, func, match, inf)
|
| 158 |
+
if sol:
|
| 159 |
+
return sol
|
| 160 |
+
return sol
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def infinitesimals(eq, func=None, order=None, hint='default', match=None):
|
| 164 |
+
r"""
|
| 165 |
+
The infinitesimal functions of an ordinary differential equation, `\xi(x,y)`
|
| 166 |
+
and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations
|
| 167 |
+
for which the differential equation is invariant. So, the ODE `y'=f(x,y)`
|
| 168 |
+
would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`,
|
| 169 |
+
`y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`.
|
| 170 |
+
A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group
|
| 171 |
+
becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`.
|
| 172 |
+
They are tangents to the coordinate curves of the new system.
|
| 173 |
+
|
| 174 |
+
Consider the transformation `(x, y) \to (X, Y)` such that the
|
| 175 |
+
differential equation remains invariant. `\xi` and `\eta` are the tangents to
|
| 176 |
+
the transformed coordinates `X` and `Y`, at `\varepsilon=0`.
|
| 177 |
+
|
| 178 |
+
.. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon
|
| 179 |
+
}\right)|_{\varepsilon=0} = \xi,
|
| 180 |
+
\left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon
|
| 181 |
+
}\right)|_{\varepsilon=0} = \eta,
|
| 182 |
+
|
| 183 |
+
The infinitesimals can be found by solving the following PDE:
|
| 184 |
+
|
| 185 |
+
>>> from sympy import Function, Eq, pprint
|
| 186 |
+
>>> from sympy.abc import x, y
|
| 187 |
+
>>> xi, eta, h = map(Function, ['xi', 'eta', 'h'])
|
| 188 |
+
>>> h = h(x, y) # dy/dx = h
|
| 189 |
+
>>> eta = eta(x, y)
|
| 190 |
+
>>> xi = xi(x, y)
|
| 191 |
+
>>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h
|
| 192 |
+
... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0)
|
| 193 |
+
>>> pprint(genform)
|
| 194 |
+
/d d \ d 2 d d d
|
| 195 |
+
|--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(xi(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0
|
| 196 |
+
\dy dx / dy dy dx dx
|
| 197 |
+
|
| 198 |
+
Solving the above mentioned PDE is not trivial, and can be solved only by
|
| 199 |
+
making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an
|
| 200 |
+
infinitesimal is found, the attempt to find more heuristics stops. This is done to
|
| 201 |
+
optimise the speed of solving the differential equation. If a list of all the
|
| 202 |
+
infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives
|
| 203 |
+
the complete list of infinitesimals. If the infinitesimals for a particular
|
| 204 |
+
heuristic needs to be found, it can be passed as a flag to ``hint``.
|
| 205 |
+
|
| 206 |
+
Examples
|
| 207 |
+
========
|
| 208 |
+
|
| 209 |
+
>>> from sympy import Function
|
| 210 |
+
>>> from sympy.solvers.ode.lie_group import infinitesimals
|
| 211 |
+
>>> from sympy.abc import x
|
| 212 |
+
>>> f = Function('f')
|
| 213 |
+
>>> eq = f(x).diff(x) - x**2*f(x)
|
| 214 |
+
>>> infinitesimals(eq)
|
| 215 |
+
[{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}]
|
| 216 |
+
|
| 217 |
+
References
|
| 218 |
+
==========
|
| 219 |
+
|
| 220 |
+
- Solving differential equations by Symmetry Groups,
|
| 221 |
+
John Starrett, pp. 1 - pp. 14
|
| 222 |
+
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
if isinstance(eq, Equality):
|
| 226 |
+
eq = eq.lhs - eq.rhs
|
| 227 |
+
if not func:
|
| 228 |
+
eq, func = _preprocess(eq)
|
| 229 |
+
variables = func.args
|
| 230 |
+
if len(variables) != 1:
|
| 231 |
+
raise ValueError("ODE's have only one independent variable")
|
| 232 |
+
else:
|
| 233 |
+
x = variables[0]
|
| 234 |
+
if not order:
|
| 235 |
+
order = ode_order(eq, func)
|
| 236 |
+
if order != 1:
|
| 237 |
+
raise NotImplementedError("Infinitesimals for only "
|
| 238 |
+
"first order ODE's have been implemented")
|
| 239 |
+
else:
|
| 240 |
+
df = func.diff(x)
|
| 241 |
+
# Matching differential equation of the form a*df + b
|
| 242 |
+
a = Wild('a', exclude = [df])
|
| 243 |
+
b = Wild('b', exclude = [df])
|
| 244 |
+
if match: # Used by lie_group hint
|
| 245 |
+
h = match['h']
|
| 246 |
+
y = match['y']
|
| 247 |
+
else:
|
| 248 |
+
match = collect(expand(eq), df).match(a*df + b)
|
| 249 |
+
if match:
|
| 250 |
+
h = -simplify(match[b]/match[a])
|
| 251 |
+
else:
|
| 252 |
+
try:
|
| 253 |
+
sol = solve(eq, df)
|
| 254 |
+
except NotImplementedError:
|
| 255 |
+
raise NotImplementedError("Infinitesimals for the "
|
| 256 |
+
"first order ODE could not be found")
|
| 257 |
+
else:
|
| 258 |
+
h = sol[0] # Find infinitesimals for one solution
|
| 259 |
+
y = Dummy("y")
|
| 260 |
+
h = h.subs(func, y)
|
| 261 |
+
|
| 262 |
+
u = Dummy("u")
|
| 263 |
+
hx = h.diff(x)
|
| 264 |
+
hy = h.diff(y)
|
| 265 |
+
hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE
|
| 266 |
+
match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv}
|
| 267 |
+
if hint == 'all':
|
| 268 |
+
xieta = []
|
| 269 |
+
for heuristic in lie_heuristics:
|
| 270 |
+
function = globals()['lie_heuristic_' + heuristic]
|
| 271 |
+
inflist = function(match, comp=True)
|
| 272 |
+
if inflist:
|
| 273 |
+
xieta.extend([inf for inf in inflist if inf not in xieta])
|
| 274 |
+
if xieta:
|
| 275 |
+
return xieta
|
| 276 |
+
else:
|
| 277 |
+
raise NotImplementedError("Infinitesimals could not be found for "
|
| 278 |
+
"the given ODE")
|
| 279 |
+
|
| 280 |
+
elif hint == 'default':
|
| 281 |
+
for heuristic in lie_heuristics:
|
| 282 |
+
function = globals()['lie_heuristic_' + heuristic]
|
| 283 |
+
xieta = function(match, comp=False)
|
| 284 |
+
if xieta:
|
| 285 |
+
return xieta
|
| 286 |
+
|
| 287 |
+
raise NotImplementedError("Infinitesimals could not be found for"
|
| 288 |
+
" the given ODE")
|
| 289 |
+
|
| 290 |
+
elif hint not in lie_heuristics:
|
| 291 |
+
raise ValueError("Heuristic not recognized: " + hint)
|
| 292 |
+
|
| 293 |
+
else:
|
| 294 |
+
function = globals()['lie_heuristic_' + hint]
|
| 295 |
+
xieta = function(match, comp=True)
|
| 296 |
+
if xieta:
|
| 297 |
+
return xieta
|
| 298 |
+
else:
|
| 299 |
+
raise ValueError("Infinitesimals could not be found using the"
|
| 300 |
+
" given heuristic")
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def lie_heuristic_abaco1_simple(match, comp=False):
|
| 304 |
+
r"""
|
| 305 |
+
The first heuristic uses the following four sets of
|
| 306 |
+
assumptions on `\xi` and `\eta`
|
| 307 |
+
|
| 308 |
+
.. math:: \xi = 0, \eta = f(x)
|
| 309 |
+
|
| 310 |
+
.. math:: \xi = 0, \eta = f(y)
|
| 311 |
+
|
| 312 |
+
.. math:: \xi = f(x), \eta = 0
|
| 313 |
+
|
| 314 |
+
.. math:: \xi = f(y), \eta = 0
|
| 315 |
+
|
| 316 |
+
The success of this heuristic is determined by algebraic factorisation.
|
| 317 |
+
For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE
|
| 318 |
+
|
| 319 |
+
.. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y}
|
| 320 |
+
- \frac{\partial \xi}{\partial x})*h
|
| 321 |
+
- \frac{\partial \xi}{\partial y}*h^{2}
|
| 322 |
+
- \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0
|
| 323 |
+
|
| 324 |
+
reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0`
|
| 325 |
+
If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually
|
| 326 |
+
be integrated easily. A similar idea is applied to the other 3 assumptions as well.
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
References
|
| 330 |
+
==========
|
| 331 |
+
|
| 332 |
+
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
|
| 333 |
+
Solving of First Order ODEs Using Symmetry Methods, pp. 8
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
xieta = []
|
| 339 |
+
y = match['y']
|
| 340 |
+
h = match['h']
|
| 341 |
+
func = match['func']
|
| 342 |
+
x = func.args[0]
|
| 343 |
+
hx = match['hx']
|
| 344 |
+
hy = match['hy']
|
| 345 |
+
xi = Function('xi')(x, func)
|
| 346 |
+
eta = Function('eta')(x, func)
|
| 347 |
+
|
| 348 |
+
hysym = hy.free_symbols
|
| 349 |
+
if y not in hysym:
|
| 350 |
+
try:
|
| 351 |
+
fx = exp(integrate(hy, x))
|
| 352 |
+
except NotImplementedError:
|
| 353 |
+
pass
|
| 354 |
+
else:
|
| 355 |
+
inf = {xi: S.Zero, eta: fx}
|
| 356 |
+
if not comp:
|
| 357 |
+
return [inf]
|
| 358 |
+
if comp and inf not in xieta:
|
| 359 |
+
xieta.append(inf)
|
| 360 |
+
|
| 361 |
+
factor = hy/h
|
| 362 |
+
facsym = factor.free_symbols
|
| 363 |
+
if x not in facsym:
|
| 364 |
+
try:
|
| 365 |
+
fy = exp(integrate(factor, y))
|
| 366 |
+
except NotImplementedError:
|
| 367 |
+
pass
|
| 368 |
+
else:
|
| 369 |
+
inf = {xi: S.Zero, eta: fy.subs(y, func)}
|
| 370 |
+
if not comp:
|
| 371 |
+
return [inf]
|
| 372 |
+
if comp and inf not in xieta:
|
| 373 |
+
xieta.append(inf)
|
| 374 |
+
|
| 375 |
+
factor = -hx/h
|
| 376 |
+
facsym = factor.free_symbols
|
| 377 |
+
if y not in facsym:
|
| 378 |
+
try:
|
| 379 |
+
fx = exp(integrate(factor, x))
|
| 380 |
+
except NotImplementedError:
|
| 381 |
+
pass
|
| 382 |
+
else:
|
| 383 |
+
inf = {xi: fx, eta: S.Zero}
|
| 384 |
+
if not comp:
|
| 385 |
+
return [inf]
|
| 386 |
+
if comp and inf not in xieta:
|
| 387 |
+
xieta.append(inf)
|
| 388 |
+
|
| 389 |
+
factor = -hx/(h**2)
|
| 390 |
+
facsym = factor.free_symbols
|
| 391 |
+
if x not in facsym:
|
| 392 |
+
try:
|
| 393 |
+
fy = exp(integrate(factor, y))
|
| 394 |
+
except NotImplementedError:
|
| 395 |
+
pass
|
| 396 |
+
else:
|
| 397 |
+
inf = {xi: fy.subs(y, func), eta: S.Zero}
|
| 398 |
+
if not comp:
|
| 399 |
+
return [inf]
|
| 400 |
+
if comp and inf not in xieta:
|
| 401 |
+
xieta.append(inf)
|
| 402 |
+
|
| 403 |
+
if xieta:
|
| 404 |
+
return xieta
|
| 405 |
+
|
| 406 |
+
def lie_heuristic_abaco1_product(match, comp=False):
|
| 407 |
+
r"""
|
| 408 |
+
The second heuristic uses the following two assumptions on `\xi` and `\eta`
|
| 409 |
+
|
| 410 |
+
.. math:: \eta = 0, \xi = f(x)*g(y)
|
| 411 |
+
|
| 412 |
+
.. math:: \eta = f(x)*g(y), \xi = 0
|
| 413 |
+
|
| 414 |
+
The first assumption of this heuristic holds good if
|
| 415 |
+
`\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is
|
| 416 |
+
separable in `x` and `y`, then the separated factors containing `x`
|
| 417 |
+
is `f(x)`, and `g(y)` is obtained by
|
| 418 |
+
|
| 419 |
+
.. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy}
|
| 420 |
+
|
| 421 |
+
provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function
|
| 422 |
+
of `y` only.
|
| 423 |
+
|
| 424 |
+
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
|
| 425 |
+
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
|
| 426 |
+
satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again
|
| 427 |
+
interchanged, to get `\eta` as `f(x)*g(y)`
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
References
|
| 431 |
+
==========
|
| 432 |
+
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
|
| 433 |
+
ODE Patterns, pp. 7 - pp. 8
|
| 434 |
+
|
| 435 |
+
"""
|
| 436 |
+
|
| 437 |
+
xieta = []
|
| 438 |
+
y = match['y']
|
| 439 |
+
h = match['h']
|
| 440 |
+
hinv = match['hinv']
|
| 441 |
+
func = match['func']
|
| 442 |
+
x = func.args[0]
|
| 443 |
+
xi = Function('xi')(x, func)
|
| 444 |
+
eta = Function('eta')(x, func)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y])
|
| 448 |
+
if inf and inf['coeff']:
|
| 449 |
+
fx = inf[x]
|
| 450 |
+
gy = simplify(fx*((1/(fx*h)).diff(x)))
|
| 451 |
+
gysyms = gy.free_symbols
|
| 452 |
+
if x not in gysyms:
|
| 453 |
+
gy = exp(integrate(gy, y))
|
| 454 |
+
inf = {eta: S.Zero, xi: (fx*gy).subs(y, func)}
|
| 455 |
+
if not comp:
|
| 456 |
+
return [inf]
|
| 457 |
+
if comp and inf not in xieta:
|
| 458 |
+
xieta.append(inf)
|
| 459 |
+
|
| 460 |
+
u1 = Dummy("u1")
|
| 461 |
+
inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y])
|
| 462 |
+
if inf and inf['coeff']:
|
| 463 |
+
fx = inf[x]
|
| 464 |
+
gy = simplify(fx*((1/(fx*hinv)).diff(x)))
|
| 465 |
+
gysyms = gy.free_symbols
|
| 466 |
+
if x not in gysyms:
|
| 467 |
+
gy = exp(integrate(gy, y))
|
| 468 |
+
etaval = fx*gy
|
| 469 |
+
etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y)
|
| 470 |
+
inf = {eta: etaval.subs(y, func), xi: S.Zero}
|
| 471 |
+
if not comp:
|
| 472 |
+
return [inf]
|
| 473 |
+
if comp and inf not in xieta:
|
| 474 |
+
xieta.append(inf)
|
| 475 |
+
|
| 476 |
+
if xieta:
|
| 477 |
+
return xieta
|
| 478 |
+
|
| 479 |
+
def lie_heuristic_bivariate(match, comp=False):
|
| 480 |
+
r"""
|
| 481 |
+
The third heuristic assumes the infinitesimals `\xi` and `\eta`
|
| 482 |
+
to be bi-variate polynomials in `x` and `y`. The assumption made here
|
| 483 |
+
for the logic below is that `h` is a rational function in `x` and `y`
|
| 484 |
+
though that may not be necessary for the infinitesimals to be
|
| 485 |
+
bivariate polynomials. The coefficients of the infinitesimals
|
| 486 |
+
are found out by substituting them in the PDE and grouping similar terms
|
| 487 |
+
that are polynomials and since they form a linear system, solve and check
|
| 488 |
+
for non trivial solutions. The degree of the assumed bivariates
|
| 489 |
+
are increased till a certain maximum value.
|
| 490 |
+
|
| 491 |
+
References
|
| 492 |
+
==========
|
| 493 |
+
- Lie Groups and Differential Equations
|
| 494 |
+
pp. 327 - pp. 329
|
| 495 |
+
|
| 496 |
+
"""
|
| 497 |
+
|
| 498 |
+
h = match['h']
|
| 499 |
+
hx = match['hx']
|
| 500 |
+
hy = match['hy']
|
| 501 |
+
func = match['func']
|
| 502 |
+
x = func.args[0]
|
| 503 |
+
y = match['y']
|
| 504 |
+
xi = Function('xi')(x, func)
|
| 505 |
+
eta = Function('eta')(x, func)
|
| 506 |
+
|
| 507 |
+
if h.is_rational_function():
|
| 508 |
+
# The maximum degree that the infinitesimals can take is
|
| 509 |
+
# calculated by this technique.
|
| 510 |
+
etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid")
|
| 511 |
+
ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy
|
| 512 |
+
num, denom = cancel(ipde).as_numer_denom()
|
| 513 |
+
deg = Poly(num, x, y).total_degree()
|
| 514 |
+
deta = Function('deta')(x, y)
|
| 515 |
+
dxi = Function('dxi')(x, y)
|
| 516 |
+
ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2
|
| 517 |
+
- dxi*hx - deta*hy)
|
| 518 |
+
xieq = Symbol("xi0")
|
| 519 |
+
etaeq = Symbol("eta0")
|
| 520 |
+
|
| 521 |
+
for i in range(deg + 1):
|
| 522 |
+
if i:
|
| 523 |
+
xieq += Add(*[
|
| 524 |
+
Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
|
| 525 |
+
for power in range(i + 1)])
|
| 526 |
+
etaeq += Add(*[
|
| 527 |
+
Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
|
| 528 |
+
for power in range(i + 1)])
|
| 529 |
+
pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom()
|
| 530 |
+
pden = expand(pden)
|
| 531 |
+
|
| 532 |
+
# If the individual terms are monomials, the coefficients
|
| 533 |
+
# are grouped
|
| 534 |
+
if pden.is_polynomial(x, y) and pden.is_Add:
|
| 535 |
+
polyy = Poly(pden, x, y).as_dict()
|
| 536 |
+
if polyy:
|
| 537 |
+
symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y}
|
| 538 |
+
soldict = solve(polyy.values(), *symset)
|
| 539 |
+
if isinstance(soldict, list):
|
| 540 |
+
soldict = soldict[0]
|
| 541 |
+
if any(soldict.values()):
|
| 542 |
+
xired = xieq.subs(soldict)
|
| 543 |
+
etared = etaeq.subs(soldict)
|
| 544 |
+
# Scaling is done by substituting one for the parameters
|
| 545 |
+
# This can be any number except zero.
|
| 546 |
+
dict_ = dict.fromkeys(symset, 1)
|
| 547 |
+
inf = {eta: etared.subs(dict_).subs(y, func),
|
| 548 |
+
xi: xired.subs(dict_).subs(y, func)}
|
| 549 |
+
return [inf]
|
| 550 |
+
|
| 551 |
+
def lie_heuristic_chi(match, comp=False):
|
| 552 |
+
r"""
|
| 553 |
+
The aim of the fourth heuristic is to find the function `\chi(x, y)`
|
| 554 |
+
that satisfies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx}
|
| 555 |
+
- \frac{\partial h}{\partial y}\chi = 0`.
|
| 556 |
+
|
| 557 |
+
This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intuition,
|
| 558 |
+
`h` should be a rational function in `x` and `y`. The method used here is
|
| 559 |
+
to substitute a general binomial for `\chi` up to a certain maximum degree
|
| 560 |
+
is reached. The coefficients of the polynomials, are calculated by by collecting
|
| 561 |
+
terms of the same order in `x` and `y`.
|
| 562 |
+
|
| 563 |
+
After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to
|
| 564 |
+
determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h`
|
| 565 |
+
which would give `-\xi` as the quotient and `\eta` as the remainder.
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
References
|
| 569 |
+
==========
|
| 570 |
+
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
|
| 571 |
+
Solving of First Order ODEs Using Symmetry Methods, pp. 8
|
| 572 |
+
|
| 573 |
+
"""
|
| 574 |
+
|
| 575 |
+
h = match['h']
|
| 576 |
+
hy = match['hy']
|
| 577 |
+
func = match['func']
|
| 578 |
+
x = func.args[0]
|
| 579 |
+
y = match['y']
|
| 580 |
+
xi = Function('xi')(x, func)
|
| 581 |
+
eta = Function('eta')(x, func)
|
| 582 |
+
|
| 583 |
+
if h.is_rational_function():
|
| 584 |
+
schi, schix, schiy = symbols("schi, schix, schiy")
|
| 585 |
+
cpde = schix + h*schiy - hy*schi
|
| 586 |
+
num, denom = cancel(cpde).as_numer_denom()
|
| 587 |
+
deg = Poly(num, x, y).total_degree()
|
| 588 |
+
|
| 589 |
+
chi = Function('chi')(x, y)
|
| 590 |
+
chix = chi.diff(x)
|
| 591 |
+
chiy = chi.diff(y)
|
| 592 |
+
cpde = chix + h*chiy - hy*chi
|
| 593 |
+
chieq = Symbol("chi")
|
| 594 |
+
for i in range(1, deg + 1):
|
| 595 |
+
chieq += Add(*[
|
| 596 |
+
Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
|
| 597 |
+
for power in range(i + 1)])
|
| 598 |
+
cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom()
|
| 599 |
+
cnum = expand(cnum)
|
| 600 |
+
if cnum.is_polynomial(x, y) and cnum.is_Add:
|
| 601 |
+
cpoly = Poly(cnum, x, y).as_dict()
|
| 602 |
+
if cpoly:
|
| 603 |
+
solsyms = chieq.free_symbols - {x, y}
|
| 604 |
+
soldict = solve(cpoly.values(), *solsyms)
|
| 605 |
+
if isinstance(soldict, list):
|
| 606 |
+
soldict = soldict[0]
|
| 607 |
+
if any(soldict.values()):
|
| 608 |
+
chieq = chieq.subs(soldict)
|
| 609 |
+
dict_ = dict.fromkeys(solsyms, 1)
|
| 610 |
+
chieq = chieq.subs(dict_)
|
| 611 |
+
# After finding chi, the main aim is to find out
|
| 612 |
+
# eta, xi by the equation eta = xi*h + chi
|
| 613 |
+
# One method to set xi, would be rearranging it to
|
| 614 |
+
# (eta/h) - xi = (chi/h). This would mean dividing
|
| 615 |
+
# chi by h would give -xi as the quotient and eta
|
| 616 |
+
# as the remainder. Thanks to Sean Vig for suggesting
|
| 617 |
+
# this method.
|
| 618 |
+
xic, etac = div(chieq, h)
|
| 619 |
+
inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)}
|
| 620 |
+
return [inf]
|
| 621 |
+
|
| 622 |
+
def lie_heuristic_function_sum(match, comp=False):
|
| 623 |
+
r"""
|
| 624 |
+
This heuristic uses the following two assumptions on `\xi` and `\eta`
|
| 625 |
+
|
| 626 |
+
.. math:: \eta = 0, \xi = f(x) + g(y)
|
| 627 |
+
|
| 628 |
+
.. math:: \eta = f(x) + g(y), \xi = 0
|
| 629 |
+
|
| 630 |
+
The first assumption of this heuristic holds good if
|
| 631 |
+
|
| 632 |
+
.. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{
|
| 633 |
+
\partial x^{2}}(h^{-1}))^{-1}]
|
| 634 |
+
|
| 635 |
+
is separable in `x` and `y`,
|
| 636 |
+
|
| 637 |
+
1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`.
|
| 638 |
+
From this `g(y)` can be determined.
|
| 639 |
+
2. The separated factors containing `x` is `f''(x)`.
|
| 640 |
+
3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals
|
| 641 |
+
`\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined.
|
| 642 |
+
|
| 643 |
+
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
|
| 644 |
+
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first
|
| 645 |
+
assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates
|
| 646 |
+
are again interchanged, to get `\eta` as `f(x) + g(y)`.
|
| 647 |
+
|
| 648 |
+
For both assumptions, the constant factors are separated among `g(y)`
|
| 649 |
+
and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that
|
| 650 |
+
obtained from 2]. If not possible, then this heuristic fails.
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
References
|
| 654 |
+
==========
|
| 655 |
+
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
|
| 656 |
+
ODE Patterns, pp. 7 - pp. 8
|
| 657 |
+
|
| 658 |
+
"""
|
| 659 |
+
|
| 660 |
+
xieta = []
|
| 661 |
+
h = match['h']
|
| 662 |
+
func = match['func']
|
| 663 |
+
hinv = match['hinv']
|
| 664 |
+
x = func.args[0]
|
| 665 |
+
y = match['y']
|
| 666 |
+
xi = Function('xi')(x, func)
|
| 667 |
+
eta = Function('eta')(x, func)
|
| 668 |
+
|
| 669 |
+
for odefac in [h, hinv]:
|
| 670 |
+
factor = odefac*((1/odefac).diff(x, 2))
|
| 671 |
+
sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y])
|
| 672 |
+
if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y):
|
| 673 |
+
k = Dummy("k")
|
| 674 |
+
try:
|
| 675 |
+
gy = k*integrate(sep[y], y)
|
| 676 |
+
except NotImplementedError:
|
| 677 |
+
pass
|
| 678 |
+
else:
|
| 679 |
+
fdd = 1/(k*sep[x]*sep['coeff'])
|
| 680 |
+
fx = simplify(fdd/factor - gy)
|
| 681 |
+
check = simplify(fx.diff(x, 2) - fdd)
|
| 682 |
+
if fx:
|
| 683 |
+
if not check:
|
| 684 |
+
fx = fx.subs(k, 1)
|
| 685 |
+
gy = (gy/k)
|
| 686 |
+
else:
|
| 687 |
+
sol = solve(check, k)
|
| 688 |
+
if sol:
|
| 689 |
+
sol = sol[0]
|
| 690 |
+
fx = fx.subs(k, sol)
|
| 691 |
+
gy = (gy/k)*sol
|
| 692 |
+
else:
|
| 693 |
+
continue
|
| 694 |
+
if odefac == hinv: # Inverse ODE
|
| 695 |
+
fx = fx.subs(x, y)
|
| 696 |
+
gy = gy.subs(y, x)
|
| 697 |
+
etaval = factor_terms(fx + gy)
|
| 698 |
+
if etaval.is_Mul:
|
| 699 |
+
etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)])
|
| 700 |
+
if odefac == hinv: # Inverse ODE
|
| 701 |
+
inf = {eta: etaval.subs(y, func), xi : S.Zero}
|
| 702 |
+
else:
|
| 703 |
+
inf = {xi: etaval.subs(y, func), eta : S.Zero}
|
| 704 |
+
if not comp:
|
| 705 |
+
return [inf]
|
| 706 |
+
else:
|
| 707 |
+
xieta.append(inf)
|
| 708 |
+
|
| 709 |
+
if xieta:
|
| 710 |
+
return xieta
|
| 711 |
+
|
| 712 |
+
def lie_heuristic_abaco2_similar(match, comp=False):
|
| 713 |
+
r"""
|
| 714 |
+
This heuristic uses the following two assumptions on `\xi` and `\eta`
|
| 715 |
+
|
| 716 |
+
.. math:: \eta = g(x), \xi = f(x)
|
| 717 |
+
|
| 718 |
+
.. math:: \eta = f(y), \xi = g(y)
|
| 719 |
+
|
| 720 |
+
For the first assumption,
|
| 721 |
+
|
| 722 |
+
1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{
|
| 723 |
+
\partial yy}}` is calculated. Let us say this value is A
|
| 724 |
+
|
| 725 |
+
2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{
|
| 726 |
+
\frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)`
|
| 727 |
+
and `A(x)*f(x)` gives `g(x)`
|
| 728 |
+
|
| 729 |
+
3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{
|
| 730 |
+
\partial Y}} = \gamma` is calculated. If
|
| 731 |
+
|
| 732 |
+
a] `\gamma` is a function of `x` alone
|
| 733 |
+
|
| 734 |
+
b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{
|
| 735 |
+
\partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone.
|
| 736 |
+
then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)`
|
| 737 |
+
|
| 738 |
+
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
|
| 739 |
+
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
|
| 740 |
+
satisfies. After obtaining `f(x)` and `g(x)`, the coordinates are again
|
| 741 |
+
interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)`
|
| 742 |
+
|
| 743 |
+
References
|
| 744 |
+
==========
|
| 745 |
+
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
|
| 746 |
+
ODE Patterns, pp. 10 - pp. 12
|
| 747 |
+
|
| 748 |
+
"""
|
| 749 |
+
|
| 750 |
+
h = match['h']
|
| 751 |
+
hx = match['hx']
|
| 752 |
+
hy = match['hy']
|
| 753 |
+
func = match['func']
|
| 754 |
+
hinv = match['hinv']
|
| 755 |
+
x = func.args[0]
|
| 756 |
+
y = match['y']
|
| 757 |
+
xi = Function('xi')(x, func)
|
| 758 |
+
eta = Function('eta')(x, func)
|
| 759 |
+
|
| 760 |
+
factor = cancel(h.diff(y)/h.diff(y, 2))
|
| 761 |
+
factorx = factor.diff(x)
|
| 762 |
+
factory = factor.diff(y)
|
| 763 |
+
if not factor.has(x) and not factor.has(y):
|
| 764 |
+
A = Wild('A', exclude=[y])
|
| 765 |
+
B = Wild('B', exclude=[y])
|
| 766 |
+
C = Wild('C', exclude=[x, y])
|
| 767 |
+
match = h.match(A + B*exp(y/C))
|
| 768 |
+
try:
|
| 769 |
+
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
|
| 770 |
+
except NotImplementedError:
|
| 771 |
+
pass
|
| 772 |
+
else:
|
| 773 |
+
gx = match[A]*tau
|
| 774 |
+
return [{xi: tau, eta: gx}]
|
| 775 |
+
|
| 776 |
+
else:
|
| 777 |
+
gamma = cancel(factorx/factory)
|
| 778 |
+
if not gamma.has(y):
|
| 779 |
+
tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma))
|
| 780 |
+
if not tauint.has(y):
|
| 781 |
+
try:
|
| 782 |
+
tau = exp(integrate(tauint, x))
|
| 783 |
+
except NotImplementedError:
|
| 784 |
+
pass
|
| 785 |
+
else:
|
| 786 |
+
gx = -tau*gamma
|
| 787 |
+
return [{xi: tau, eta: gx}]
|
| 788 |
+
|
| 789 |
+
factor = cancel(hinv.diff(y)/hinv.diff(y, 2))
|
| 790 |
+
factorx = factor.diff(x)
|
| 791 |
+
factory = factor.diff(y)
|
| 792 |
+
if not factor.has(x) and not factor.has(y):
|
| 793 |
+
A = Wild('A', exclude=[y])
|
| 794 |
+
B = Wild('B', exclude=[y])
|
| 795 |
+
C = Wild('C', exclude=[x, y])
|
| 796 |
+
match = h.match(A + B*exp(y/C))
|
| 797 |
+
try:
|
| 798 |
+
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
|
| 799 |
+
except NotImplementedError:
|
| 800 |
+
pass
|
| 801 |
+
else:
|
| 802 |
+
gx = match[A]*tau
|
| 803 |
+
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
|
| 804 |
+
|
| 805 |
+
else:
|
| 806 |
+
gamma = cancel(factorx/factory)
|
| 807 |
+
if not gamma.has(y):
|
| 808 |
+
tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/(
|
| 809 |
+
hinv + gamma))
|
| 810 |
+
if not tauint.has(y):
|
| 811 |
+
try:
|
| 812 |
+
tau = exp(integrate(tauint, x))
|
| 813 |
+
except NotImplementedError:
|
| 814 |
+
pass
|
| 815 |
+
else:
|
| 816 |
+
gx = -tau*gamma
|
| 817 |
+
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
def lie_heuristic_abaco2_unique_unknown(match, comp=False):
|
| 821 |
+
r"""
|
| 822 |
+
This heuristic assumes the presence of unknown functions or known functions
|
| 823 |
+
with non-integer powers.
|
| 824 |
+
|
| 825 |
+
1. A list of all functions and non-integer powers containing x and y
|
| 826 |
+
2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{
|
| 827 |
+
\frac{\partial f}{\partial x}} = R`
|
| 828 |
+
|
| 829 |
+
If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then
|
| 830 |
+
|
| 831 |
+
a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return
|
| 832 |
+
`\xi` and `\eta`
|
| 833 |
+
b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE.
|
| 834 |
+
If yes, then return `\xi` and `\eta`
|
| 835 |
+
|
| 836 |
+
If not, then check if
|
| 837 |
+
|
| 838 |
+
a] :math:`\xi = -R,\eta = 1`
|
| 839 |
+
|
| 840 |
+
b] :math:`\xi = 1, \eta = -\frac{1}{R}`
|
| 841 |
+
|
| 842 |
+
are solutions.
|
| 843 |
+
|
| 844 |
+
References
|
| 845 |
+
==========
|
| 846 |
+
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
|
| 847 |
+
ODE Patterns, pp. 10 - pp. 12
|
| 848 |
+
|
| 849 |
+
"""
|
| 850 |
+
|
| 851 |
+
h = match['h']
|
| 852 |
+
hx = match['hx']
|
| 853 |
+
hy = match['hy']
|
| 854 |
+
func = match['func']
|
| 855 |
+
x = func.args[0]
|
| 856 |
+
y = match['y']
|
| 857 |
+
xi = Function('xi')(x, func)
|
| 858 |
+
eta = Function('eta')(x, func)
|
| 859 |
+
|
| 860 |
+
funclist = []
|
| 861 |
+
for atom in h.atoms(Pow):
|
| 862 |
+
base, exp = atom.as_base_exp()
|
| 863 |
+
if base.has(x) and base.has(y):
|
| 864 |
+
if not exp.is_Integer:
|
| 865 |
+
funclist.append(atom)
|
| 866 |
+
|
| 867 |
+
for function in h.atoms(AppliedUndef):
|
| 868 |
+
syms = function.free_symbols
|
| 869 |
+
if x in syms and y in syms:
|
| 870 |
+
funclist.append(function)
|
| 871 |
+
|
| 872 |
+
for f in funclist:
|
| 873 |
+
frac = cancel(f.diff(y)/f.diff(x))
|
| 874 |
+
sep = separatevars(frac, dict=True, symbols=[x, y])
|
| 875 |
+
if sep and sep['coeff']:
|
| 876 |
+
xitry1 = sep[x]
|
| 877 |
+
etatry1 = -1/(sep[y]*sep['coeff'])
|
| 878 |
+
pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy
|
| 879 |
+
if not simplify(pde1):
|
| 880 |
+
return [{xi: xitry1, eta: etatry1.subs(y, func)}]
|
| 881 |
+
xitry2 = 1/etatry1
|
| 882 |
+
etatry2 = 1/xitry1
|
| 883 |
+
pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy
|
| 884 |
+
if not simplify(expand(pde2)):
|
| 885 |
+
return [{xi: xitry2.subs(y, func), eta: etatry2}]
|
| 886 |
+
|
| 887 |
+
else:
|
| 888 |
+
etatry = -1/frac
|
| 889 |
+
pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy
|
| 890 |
+
if not simplify(pde):
|
| 891 |
+
return [{xi: S.One, eta: etatry.subs(y, func)}]
|
| 892 |
+
xitry = -frac
|
| 893 |
+
pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy
|
| 894 |
+
if not simplify(expand(pde)):
|
| 895 |
+
return [{xi: xitry.subs(y, func), eta: S.One}]
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def lie_heuristic_abaco2_unique_general(match, comp=False):
|
| 899 |
+
r"""
|
| 900 |
+
This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)`
|
| 901 |
+
without making any assumptions on `h`.
|
| 902 |
+
|
| 903 |
+
The complete sequence of steps is given in the paper mentioned below.
|
| 904 |
+
|
| 905 |
+
References
|
| 906 |
+
==========
|
| 907 |
+
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
|
| 908 |
+
ODE Patterns, pp. 10 - pp. 12
|
| 909 |
+
|
| 910 |
+
"""
|
| 911 |
+
hx = match['hx']
|
| 912 |
+
hy = match['hy']
|
| 913 |
+
func = match['func']
|
| 914 |
+
x = func.args[0]
|
| 915 |
+
y = match['y']
|
| 916 |
+
xi = Function('xi')(x, func)
|
| 917 |
+
eta = Function('eta')(x, func)
|
| 918 |
+
|
| 919 |
+
A = hx.diff(y)
|
| 920 |
+
B = hy.diff(y) + hy**2
|
| 921 |
+
C = hx.diff(x) - hx**2
|
| 922 |
+
|
| 923 |
+
if not (A and B and C):
|
| 924 |
+
return
|
| 925 |
+
|
| 926 |
+
Ax = A.diff(x)
|
| 927 |
+
Ay = A.diff(y)
|
| 928 |
+
Axy = Ax.diff(y)
|
| 929 |
+
Axx = Ax.diff(x)
|
| 930 |
+
Ayy = Ay.diff(y)
|
| 931 |
+
D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay
|
| 932 |
+
if not D:
|
| 933 |
+
E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A)
|
| 934 |
+
if E1:
|
| 935 |
+
E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
|
| 936 |
+
if not E2:
|
| 937 |
+
E3 = simplify(
|
| 938 |
+
E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4)
|
| 939 |
+
if not E3:
|
| 940 |
+
etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1))
|
| 941 |
+
if x not in etaval:
|
| 942 |
+
try:
|
| 943 |
+
etaval = exp(integrate(etaval, y))
|
| 944 |
+
except NotImplementedError:
|
| 945 |
+
pass
|
| 946 |
+
else:
|
| 947 |
+
xival = -4*A**3*etaval/E1
|
| 948 |
+
if y not in xival:
|
| 949 |
+
return [{xi: xival, eta: etaval.subs(y, func)}]
|
| 950 |
+
|
| 951 |
+
else:
|
| 952 |
+
E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
|
| 953 |
+
if E1:
|
| 954 |
+
E2 = simplify(
|
| 955 |
+
4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2))
|
| 956 |
+
if not E2:
|
| 957 |
+
E3 = simplify(
|
| 958 |
+
-(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D +
|
| 959 |
+
(A*hx - 3*Ax)*E1)*E1)
|
| 960 |
+
if not E3:
|
| 961 |
+
etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D))
|
| 962 |
+
if x not in etaval:
|
| 963 |
+
try:
|
| 964 |
+
etaval = exp(integrate(etaval, y))
|
| 965 |
+
except NotImplementedError:
|
| 966 |
+
pass
|
| 967 |
+
else:
|
| 968 |
+
xival = -E1*etaval/D
|
| 969 |
+
if y not in xival:
|
| 970 |
+
return [{xi: xival, eta: etaval.subs(y, func)}]
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
def lie_heuristic_linear(match, comp=False):
|
| 974 |
+
r"""
|
| 975 |
+
This heuristic assumes
|
| 976 |
+
|
| 977 |
+
1. `\xi = ax + by + c` and
|
| 978 |
+
2. `\eta = fx + gy + h`
|
| 979 |
+
|
| 980 |
+
After substituting the following assumptions in the determining PDE, it
|
| 981 |
+
reduces to
|
| 982 |
+
|
| 983 |
+
.. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x}
|
| 984 |
+
- (fx + gy + c)\frac{\partial h}{\partial y}
|
| 985 |
+
|
| 986 |
+
Solving the reduced PDE obtained, using the method of characteristics, becomes
|
| 987 |
+
impractical. The method followed is grouping similar terms and solving the system
|
| 988 |
+
of linear equations obtained. The difference between the bivariate heuristic is that
|
| 989 |
+
`h` need not be a rational function in this case.
|
| 990 |
+
|
| 991 |
+
References
|
| 992 |
+
==========
|
| 993 |
+
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
|
| 994 |
+
ODE Patterns, pp. 10 - pp. 12
|
| 995 |
+
|
| 996 |
+
"""
|
| 997 |
+
h = match['h']
|
| 998 |
+
hx = match['hx']
|
| 999 |
+
hy = match['hy']
|
| 1000 |
+
func = match['func']
|
| 1001 |
+
x = func.args[0]
|
| 1002 |
+
y = match['y']
|
| 1003 |
+
xi = Function('xi')(x, func)
|
| 1004 |
+
eta = Function('eta')(x, func)
|
| 1005 |
+
|
| 1006 |
+
coeffdict = {}
|
| 1007 |
+
symbols = numbered_symbols("c", cls=Dummy)
|
| 1008 |
+
symlist = [next(symbols) for _ in islice(symbols, 6)]
|
| 1009 |
+
C0, C1, C2, C3, C4, C5 = symlist
|
| 1010 |
+
pde = C3 + (C4 - C0)*h - (C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2
|
| 1011 |
+
pde, denom = pde.as_numer_denom()
|
| 1012 |
+
pde = powsimp(expand(pde))
|
| 1013 |
+
if pde.is_Add:
|
| 1014 |
+
terms = pde.args
|
| 1015 |
+
for term in terms:
|
| 1016 |
+
if term.is_Mul:
|
| 1017 |
+
rem = Mul(*[m for m in term.args if not m.has(x, y)])
|
| 1018 |
+
xypart = term/rem
|
| 1019 |
+
if xypart not in coeffdict:
|
| 1020 |
+
coeffdict[xypart] = rem
|
| 1021 |
+
else:
|
| 1022 |
+
coeffdict[xypart] += rem
|
| 1023 |
+
else:
|
| 1024 |
+
if term not in coeffdict:
|
| 1025 |
+
coeffdict[term] = S.One
|
| 1026 |
+
else:
|
| 1027 |
+
coeffdict[term] += S.One
|
| 1028 |
+
|
| 1029 |
+
sollist = coeffdict.values()
|
| 1030 |
+
soldict = solve(sollist, symlist)
|
| 1031 |
+
if soldict:
|
| 1032 |
+
if isinstance(soldict, list):
|
| 1033 |
+
soldict = soldict[0]
|
| 1034 |
+
subval = soldict.values()
|
| 1035 |
+
if any(t for t in subval):
|
| 1036 |
+
onedict = dict(zip(symlist, [1]*6))
|
| 1037 |
+
xival = C0*x + C1*func + C2
|
| 1038 |
+
etaval = C3*x + C4*func + C5
|
| 1039 |
+
xival = xival.subs(soldict)
|
| 1040 |
+
etaval = etaval.subs(soldict)
|
| 1041 |
+
xival = xival.subs(onedict)
|
| 1042 |
+
etaval = etaval.subs(onedict)
|
| 1043 |
+
return [{xi: xival, eta: etaval}]
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
def _lie_group_remove(coords):
|
| 1047 |
+
r"""
|
| 1048 |
+
This function is strictly meant for internal use by the Lie group ODE solving
|
| 1049 |
+
method. It replaces arbitrary functions returned by pdsolve as follows:
|
| 1050 |
+
|
| 1051 |
+
1] If coords is an arbitrary function, then its argument is returned.
|
| 1052 |
+
2] An arbitrary function in an Add object is replaced by zero.
|
| 1053 |
+
3] An arbitrary function in a Mul object is replaced by one.
|
| 1054 |
+
4] If there is no arbitrary function coords is returned unchanged.
|
| 1055 |
+
|
| 1056 |
+
Examples
|
| 1057 |
+
========
|
| 1058 |
+
|
| 1059 |
+
>>> from sympy.solvers.ode.lie_group import _lie_group_remove
|
| 1060 |
+
>>> from sympy import Function
|
| 1061 |
+
>>> from sympy.abc import x, y
|
| 1062 |
+
>>> F = Function("F")
|
| 1063 |
+
>>> eq = x**2*y
|
| 1064 |
+
>>> _lie_group_remove(eq)
|
| 1065 |
+
x**2*y
|
| 1066 |
+
>>> eq = F(x**2*y)
|
| 1067 |
+
>>> _lie_group_remove(eq)
|
| 1068 |
+
x**2*y
|
| 1069 |
+
>>> eq = x*y**2 + F(x**3)
|
| 1070 |
+
>>> _lie_group_remove(eq)
|
| 1071 |
+
x*y**2
|
| 1072 |
+
>>> eq = (F(x**3) + y)*x**4
|
| 1073 |
+
>>> _lie_group_remove(eq)
|
| 1074 |
+
x**4*y
|
| 1075 |
+
|
| 1076 |
+
"""
|
| 1077 |
+
if isinstance(coords, AppliedUndef):
|
| 1078 |
+
return coords.args[0]
|
| 1079 |
+
elif coords.is_Add:
|
| 1080 |
+
subfunc = coords.atoms(AppliedUndef)
|
| 1081 |
+
if subfunc:
|
| 1082 |
+
for func in subfunc:
|
| 1083 |
+
coords = coords.subs(func, 0)
|
| 1084 |
+
return coords
|
| 1085 |
+
elif coords.is_Pow:
|
| 1086 |
+
base, expr = coords.as_base_exp()
|
| 1087 |
+
base = _lie_group_remove(base)
|
| 1088 |
+
expr = _lie_group_remove(expr)
|
| 1089 |
+
return base**expr
|
| 1090 |
+
elif coords.is_Mul:
|
| 1091 |
+
mulargs = []
|
| 1092 |
+
coordargs = coords.args
|
| 1093 |
+
for arg in coordargs:
|
| 1094 |
+
if not isinstance(coords, AppliedUndef):
|
| 1095 |
+
mulargs.append(_lie_group_remove(arg))
|
| 1096 |
+
return Mul(*mulargs)
|
| 1097 |
+
return coords
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/nonhomogeneous.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
This File contains helper functions for nth_linear_constant_coeff_undetermined_coefficients,
|
| 3 |
+
nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients,
|
| 4 |
+
nth_linear_constant_coeff_variation_of_parameters,
|
| 5 |
+
and nth_linear_euler_eq_nonhomogeneous_variation_of_parameters.
|
| 6 |
+
|
| 7 |
+
All the functions in this file are used by more than one solvers so, instead of creating
|
| 8 |
+
instances in other classes for using them it is better to keep it here as separate helpers.
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
from sympy.core import Add, S
|
| 13 |
+
from sympy.core.function import diff, expand, _mexpand, expand_mul
|
| 14 |
+
from sympy.core.relational import Eq
|
| 15 |
+
from sympy.core.sorting import default_sort_key
|
| 16 |
+
from sympy.core.symbol import Dummy, Wild
|
| 17 |
+
from sympy.functions import exp, cos, cosh, im, log, re, sin, sinh, \
|
| 18 |
+
atan2, conjugate
|
| 19 |
+
from sympy.integrals import Integral
|
| 20 |
+
from sympy.polys import (Poly, RootOf, rootof, roots)
|
| 21 |
+
from sympy.simplify import collect, simplify, separatevars, powsimp, trigsimp # type: ignore
|
| 22 |
+
from sympy.utilities import numbered_symbols
|
| 23 |
+
from sympy.solvers.solvers import solve
|
| 24 |
+
from sympy.matrices import wronskian
|
| 25 |
+
from .subscheck import sub_func_doit
|
| 26 |
+
from sympy.solvers.ode.ode import get_numbered_constants
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _test_term(coeff, func, order):
|
| 30 |
+
r"""
|
| 31 |
+
Linear Euler ODEs have the form K*x**order*diff(y(x), x, order) = F(x),
|
| 32 |
+
where K is independent of x and y(x), order>= 0.
|
| 33 |
+
So we need to check that for each term, coeff == K*x**order from
|
| 34 |
+
some K. We have a few cases, since coeff may have several
|
| 35 |
+
different types.
|
| 36 |
+
"""
|
| 37 |
+
x = func.args[0]
|
| 38 |
+
f = func.func
|
| 39 |
+
if order < 0:
|
| 40 |
+
raise ValueError("order should be greater than 0")
|
| 41 |
+
if coeff == 0:
|
| 42 |
+
return True
|
| 43 |
+
if order == 0:
|
| 44 |
+
if x in coeff.free_symbols:
|
| 45 |
+
return False
|
| 46 |
+
return True
|
| 47 |
+
if coeff.is_Mul:
|
| 48 |
+
if coeff.has(f(x)):
|
| 49 |
+
return False
|
| 50 |
+
return x**order in coeff.args
|
| 51 |
+
elif coeff.is_Pow:
|
| 52 |
+
return coeff.as_base_exp() == (x, order)
|
| 53 |
+
elif order == 1:
|
| 54 |
+
return x == coeff
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _get_euler_characteristic_eq_sols(eq, func, match_obj):
|
| 59 |
+
r"""
|
| 60 |
+
Returns the solution of homogeneous part of the linear euler ODE and
|
| 61 |
+
the list of roots of characteristic equation.
|
| 62 |
+
|
| 63 |
+
The parameter ``match_obj`` is a dict of order:coeff terms, where order is the order
|
| 64 |
+
of the derivative on each term, and coeff is the coefficient of that derivative.
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
x = func.args[0]
|
| 68 |
+
f = func.func
|
| 69 |
+
|
| 70 |
+
# First, set up characteristic equation.
|
| 71 |
+
chareq, symbol = S.Zero, Dummy('x')
|
| 72 |
+
|
| 73 |
+
for i in match_obj:
|
| 74 |
+
if i >= 0:
|
| 75 |
+
chareq += (match_obj[i]*diff(x**symbol, x, i)*x**-symbol).expand()
|
| 76 |
+
|
| 77 |
+
chareq = Poly(chareq, symbol)
|
| 78 |
+
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
|
| 79 |
+
collectterms = []
|
| 80 |
+
|
| 81 |
+
# A generator of constants
|
| 82 |
+
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
|
| 83 |
+
constants.reverse()
|
| 84 |
+
|
| 85 |
+
# Create a dict root: multiplicity or charroots
|
| 86 |
+
charroots = defaultdict(int)
|
| 87 |
+
for root in chareqroots:
|
| 88 |
+
charroots[root] += 1
|
| 89 |
+
gsol = S.Zero
|
| 90 |
+
ln = log
|
| 91 |
+
for root, multiplicity in charroots.items():
|
| 92 |
+
for i in range(multiplicity):
|
| 93 |
+
if isinstance(root, RootOf):
|
| 94 |
+
gsol += (x**root) * constants.pop()
|
| 95 |
+
if multiplicity != 1:
|
| 96 |
+
raise ValueError("Value should be 1")
|
| 97 |
+
collectterms = [(0, root, 0)] + collectterms
|
| 98 |
+
elif root.is_real:
|
| 99 |
+
gsol += ln(x)**i*(x**root) * constants.pop()
|
| 100 |
+
collectterms = [(i, root, 0)] + collectterms
|
| 101 |
+
else:
|
| 102 |
+
reroot = re(root)
|
| 103 |
+
imroot = im(root)
|
| 104 |
+
gsol += ln(x)**i * (x**reroot) * (
|
| 105 |
+
constants.pop() * sin(abs(imroot)*ln(x))
|
| 106 |
+
+ constants.pop() * cos(imroot*ln(x)))
|
| 107 |
+
collectterms = [(i, reroot, imroot)] + collectterms
|
| 108 |
+
|
| 109 |
+
gsol = Eq(f(x), gsol)
|
| 110 |
+
|
| 111 |
+
gensols = []
|
| 112 |
+
# Keep track of when to use sin or cos for nonzero imroot
|
| 113 |
+
for i, reroot, imroot in collectterms:
|
| 114 |
+
if imroot == 0:
|
| 115 |
+
gensols.append(ln(x)**i*x**reroot)
|
| 116 |
+
else:
|
| 117 |
+
sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x))
|
| 118 |
+
if sin_form in gensols:
|
| 119 |
+
cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x))
|
| 120 |
+
gensols.append(cos_form)
|
| 121 |
+
else:
|
| 122 |
+
gensols.append(sin_form)
|
| 123 |
+
return gsol, gensols
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _solve_variation_of_parameters(eq, func, roots, homogen_sol, order, match_obj, simplify_flag=True):
|
| 127 |
+
r"""
|
| 128 |
+
Helper function for the method of variation of parameters and nonhomogeneous euler eq.
|
| 129 |
+
|
| 130 |
+
See the
|
| 131 |
+
:py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffVariationOfParameters`
|
| 132 |
+
docstring for more information on this method.
|
| 133 |
+
|
| 134 |
+
The parameter are ``match_obj`` should be a dictionary that has the following
|
| 135 |
+
keys:
|
| 136 |
+
|
| 137 |
+
``list``
|
| 138 |
+
A list of solutions to the homogeneous equation.
|
| 139 |
+
|
| 140 |
+
``sol``
|
| 141 |
+
The general solution.
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
f = func.func
|
| 145 |
+
x = func.args[0]
|
| 146 |
+
r = match_obj
|
| 147 |
+
psol = 0
|
| 148 |
+
wr = wronskian(roots, x)
|
| 149 |
+
|
| 150 |
+
if simplify_flag:
|
| 151 |
+
wr = simplify(wr) # We need much better simplification for
|
| 152 |
+
# some ODEs. See issue 4662, for example.
|
| 153 |
+
# To reduce commonly occurring sin(x)**2 + cos(x)**2 to 1
|
| 154 |
+
wr = trigsimp(wr, deep=True, recursive=True)
|
| 155 |
+
if not wr:
|
| 156 |
+
# The wronskian will be 0 iff the solutions are not linearly
|
| 157 |
+
# independent.
|
| 158 |
+
raise NotImplementedError("Cannot find " + str(order) +
|
| 159 |
+
" solutions to the homogeneous equation necessary to apply " +
|
| 160 |
+
"variation of parameters to " + str(eq) + " (Wronskian == 0)")
|
| 161 |
+
if len(roots) != order:
|
| 162 |
+
raise NotImplementedError("Cannot find " + str(order) +
|
| 163 |
+
" solutions to the homogeneous equation necessary to apply " +
|
| 164 |
+
"variation of parameters to " +
|
| 165 |
+
str(eq) + " (number of terms != order)")
|
| 166 |
+
negoneterm = S.NegativeOne**(order)
|
| 167 |
+
for i in roots:
|
| 168 |
+
psol += negoneterm*Integral(wronskian([sol for sol in roots if sol != i], x)*r[-1]/wr, x)*i/r[order]
|
| 169 |
+
negoneterm *= -1
|
| 170 |
+
|
| 171 |
+
if simplify_flag:
|
| 172 |
+
psol = simplify(psol)
|
| 173 |
+
psol = trigsimp(psol, deep=True)
|
| 174 |
+
return Eq(f(x), homogen_sol.rhs + psol)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _get_const_characteristic_eq_sols(r, func, order):
|
| 178 |
+
r"""
|
| 179 |
+
Returns the roots of characteristic equation of constant coefficient
|
| 180 |
+
linear ODE and list of collectterms which is later on used by simplification
|
| 181 |
+
to use collect on solution.
|
| 182 |
+
|
| 183 |
+
The parameter `r` is a dict of order:coeff terms, where order is the order of the
|
| 184 |
+
derivative on each term, and coeff is the coefficient of that derivative.
|
| 185 |
+
|
| 186 |
+
"""
|
| 187 |
+
x = func.args[0]
|
| 188 |
+
# First, set up characteristic equation.
|
| 189 |
+
chareq, symbol = S.Zero, Dummy('x')
|
| 190 |
+
|
| 191 |
+
for i in r.keys():
|
| 192 |
+
if isinstance(i, str) or i < 0:
|
| 193 |
+
pass
|
| 194 |
+
else:
|
| 195 |
+
chareq += r[i]*symbol**i
|
| 196 |
+
|
| 197 |
+
chareq = Poly(chareq, symbol)
|
| 198 |
+
# Can't just call roots because it doesn't return rootof for unsolveable
|
| 199 |
+
# polynomials.
|
| 200 |
+
chareqroots = roots(chareq, multiple=True)
|
| 201 |
+
if len(chareqroots) != order:
|
| 202 |
+
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
|
| 203 |
+
|
| 204 |
+
chareq_is_complex = not all(i.is_real for i in chareq.all_coeffs())
|
| 205 |
+
|
| 206 |
+
# Create a dict root: multiplicity or charroots
|
| 207 |
+
charroots = defaultdict(int)
|
| 208 |
+
for root in chareqroots:
|
| 209 |
+
charroots[root] += 1
|
| 210 |
+
# We need to keep track of terms so we can run collect() at the end.
|
| 211 |
+
# This is necessary for constantsimp to work properly.
|
| 212 |
+
collectterms = []
|
| 213 |
+
gensols = []
|
| 214 |
+
conjugate_roots = [] # used to prevent double-use of conjugate roots
|
| 215 |
+
# Loop over roots in theorder provided by roots/rootof...
|
| 216 |
+
for root in chareqroots:
|
| 217 |
+
# but don't repoeat multiple roots.
|
| 218 |
+
if root not in charroots:
|
| 219 |
+
continue
|
| 220 |
+
multiplicity = charroots.pop(root)
|
| 221 |
+
for i in range(multiplicity):
|
| 222 |
+
if chareq_is_complex:
|
| 223 |
+
gensols.append(x**i*exp(root*x))
|
| 224 |
+
collectterms = [(i, root, 0)] + collectterms
|
| 225 |
+
continue
|
| 226 |
+
reroot = re(root)
|
| 227 |
+
imroot = im(root)
|
| 228 |
+
if imroot.has(atan2) and reroot.has(atan2):
|
| 229 |
+
# Remove this condition when re and im stop returning
|
| 230 |
+
# circular atan2 usages.
|
| 231 |
+
gensols.append(x**i*exp(root*x))
|
| 232 |
+
collectterms = [(i, root, 0)] + collectterms
|
| 233 |
+
else:
|
| 234 |
+
if root in conjugate_roots:
|
| 235 |
+
collectterms = [(i, reroot, imroot)] + collectterms
|
| 236 |
+
continue
|
| 237 |
+
if imroot == 0:
|
| 238 |
+
gensols.append(x**i*exp(reroot*x))
|
| 239 |
+
collectterms = [(i, reroot, 0)] + collectterms
|
| 240 |
+
continue
|
| 241 |
+
conjugate_roots.append(conjugate(root))
|
| 242 |
+
gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x))
|
| 243 |
+
gensols.append(x**i*exp(reroot*x) * cos( imroot * x))
|
| 244 |
+
|
| 245 |
+
# This ordering is important
|
| 246 |
+
collectterms = [(i, reroot, imroot)] + collectterms
|
| 247 |
+
return gensols, collectterms
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# Ideally these kind of simplification functions shouldn't be part of solvers.
|
| 251 |
+
# odesimp should be improved to handle these kind of specific simplifications.
|
| 252 |
+
def _get_simplified_sol(sol, func, collectterms):
|
| 253 |
+
r"""
|
| 254 |
+
Helper function which collects the solution on
|
| 255 |
+
collectterms. Ideally this should be handled by odesimp.It is used
|
| 256 |
+
only when the simplify is set to True in dsolve.
|
| 257 |
+
|
| 258 |
+
The parameter ``collectterms`` is a list of tuple (i, reroot, imroot) where `i` is
|
| 259 |
+
the multiplicity of the root, reroot is real part and imroot being the imaginary part.
|
| 260 |
+
|
| 261 |
+
"""
|
| 262 |
+
f = func.func
|
| 263 |
+
x = func.args[0]
|
| 264 |
+
collectterms.sort(key=default_sort_key)
|
| 265 |
+
collectterms.reverse()
|
| 266 |
+
assert len(sol) == 1 and sol[0].lhs == f(x)
|
| 267 |
+
sol = sol[0].rhs
|
| 268 |
+
sol = expand_mul(sol)
|
| 269 |
+
for i, reroot, imroot in collectterms:
|
| 270 |
+
sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x))
|
| 271 |
+
sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x))
|
| 272 |
+
for i, reroot, imroot in collectterms:
|
| 273 |
+
sol = collect(sol, x**i*exp(reroot*x))
|
| 274 |
+
sol = powsimp(sol)
|
| 275 |
+
return Eq(f(x), sol)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero):
|
| 279 |
+
r"""
|
| 280 |
+
Returns a trial function match if undetermined coefficients can be applied
|
| 281 |
+
to ``expr``, and ``None`` otherwise.
|
| 282 |
+
|
| 283 |
+
A trial expression can be found for an expression for use with the method
|
| 284 |
+
of undetermined coefficients if the expression is an
|
| 285 |
+
additive/multiplicative combination of constants, polynomials in `x` (the
|
| 286 |
+
independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and
|
| 287 |
+
`e^{a x}` terms (in other words, it has a finite number of linearly
|
| 288 |
+
independent derivatives).
|
| 289 |
+
|
| 290 |
+
Note that you may still need to multiply each term returned here by
|
| 291 |
+
sufficient `x` to make it linearly independent with the solutions to the
|
| 292 |
+
homogeneous equation.
|
| 293 |
+
|
| 294 |
+
This is intended for internal use by ``undetermined_coefficients`` hints.
|
| 295 |
+
|
| 296 |
+
SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of
|
| 297 |
+
only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So,
|
| 298 |
+
for example, you will need to manually convert `\sin^2(x)` into `[1 +
|
| 299 |
+
\cos(2 x)]/2` to properly apply the method of undetermined coefficients on
|
| 300 |
+
it.
|
| 301 |
+
|
| 302 |
+
Examples
|
| 303 |
+
========
|
| 304 |
+
|
| 305 |
+
>>> from sympy import log, exp
|
| 306 |
+
>>> from sympy.solvers.ode.nonhomogeneous import _undetermined_coefficients_match
|
| 307 |
+
>>> from sympy.abc import x
|
| 308 |
+
>>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x)
|
| 309 |
+
{'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}}
|
| 310 |
+
>>> _undetermined_coefficients_match(log(x), x)
|
| 311 |
+
{'test': False}
|
| 312 |
+
|
| 313 |
+
"""
|
| 314 |
+
a = Wild('a', exclude=[x])
|
| 315 |
+
b = Wild('b', exclude=[x])
|
| 316 |
+
expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
|
| 317 |
+
retdict = {}
|
| 318 |
+
|
| 319 |
+
def _test_term(expr, x):
|
| 320 |
+
r"""
|
| 321 |
+
Test if ``expr`` fits the proper form for undetermined coefficients.
|
| 322 |
+
"""
|
| 323 |
+
if not expr.has(x):
|
| 324 |
+
return True
|
| 325 |
+
elif expr.is_Add:
|
| 326 |
+
return all(_test_term(i, x) for i in expr.args)
|
| 327 |
+
elif expr.is_Mul:
|
| 328 |
+
if expr.has(sin, cos):
|
| 329 |
+
foundtrig = False
|
| 330 |
+
# Make sure that there is only one trig function in the args.
|
| 331 |
+
# See the docstring.
|
| 332 |
+
for i in expr.args:
|
| 333 |
+
if i.has(sin, cos):
|
| 334 |
+
if foundtrig:
|
| 335 |
+
return False
|
| 336 |
+
else:
|
| 337 |
+
foundtrig = True
|
| 338 |
+
return all(_test_term(i, x) for i in expr.args)
|
| 339 |
+
elif expr.is_Function:
|
| 340 |
+
if expr.func in (sin, cos, exp, sinh, cosh):
|
| 341 |
+
if expr.args[0].match(a*x + b):
|
| 342 |
+
return True
|
| 343 |
+
else:
|
| 344 |
+
return False
|
| 345 |
+
else:
|
| 346 |
+
return False
|
| 347 |
+
elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \
|
| 348 |
+
expr.exp >= 0:
|
| 349 |
+
return True
|
| 350 |
+
elif expr.is_Pow and expr.base.is_number:
|
| 351 |
+
if expr.exp.match(a*x + b):
|
| 352 |
+
return True
|
| 353 |
+
else:
|
| 354 |
+
return False
|
| 355 |
+
elif expr.is_Symbol or expr.is_number:
|
| 356 |
+
return True
|
| 357 |
+
else:
|
| 358 |
+
return False
|
| 359 |
+
|
| 360 |
+
def _get_trial_set(expr, x, exprs=set()):
|
| 361 |
+
r"""
|
| 362 |
+
Returns a set of trial terms for undetermined coefficients.
|
| 363 |
+
|
| 364 |
+
The idea behind undetermined coefficients is that the terms expression
|
| 365 |
+
repeat themselves after a finite number of derivatives, except for the
|
| 366 |
+
coefficients (they are linearly dependent). So if we collect these,
|
| 367 |
+
we should have the terms of our trial function.
|
| 368 |
+
"""
|
| 369 |
+
def _remove_coefficient(expr, x):
|
| 370 |
+
r"""
|
| 371 |
+
Returns the expression without a coefficient.
|
| 372 |
+
|
| 373 |
+
Similar to expr.as_independent(x)[1], except it only works
|
| 374 |
+
multiplicatively.
|
| 375 |
+
"""
|
| 376 |
+
term = S.One
|
| 377 |
+
if expr.is_Mul:
|
| 378 |
+
for i in expr.args:
|
| 379 |
+
if i.has(x):
|
| 380 |
+
term *= i
|
| 381 |
+
elif expr.has(x):
|
| 382 |
+
term = expr
|
| 383 |
+
return term
|
| 384 |
+
|
| 385 |
+
expr = expand_mul(expr)
|
| 386 |
+
if expr.is_Add:
|
| 387 |
+
for term in expr.args:
|
| 388 |
+
if _remove_coefficient(term, x) in exprs:
|
| 389 |
+
pass
|
| 390 |
+
else:
|
| 391 |
+
exprs.add(_remove_coefficient(term, x))
|
| 392 |
+
exprs = exprs.union(_get_trial_set(term, x, exprs))
|
| 393 |
+
else:
|
| 394 |
+
term = _remove_coefficient(expr, x)
|
| 395 |
+
tmpset = exprs.union({term})
|
| 396 |
+
oldset = set()
|
| 397 |
+
while tmpset != oldset:
|
| 398 |
+
# If you get stuck in this loop, then _test_term is probably
|
| 399 |
+
# broken
|
| 400 |
+
oldset = tmpset.copy()
|
| 401 |
+
expr = expr.diff(x)
|
| 402 |
+
term = _remove_coefficient(expr, x)
|
| 403 |
+
if term.is_Add:
|
| 404 |
+
tmpset = tmpset.union(_get_trial_set(term, x, tmpset))
|
| 405 |
+
else:
|
| 406 |
+
tmpset.add(term)
|
| 407 |
+
exprs = tmpset
|
| 408 |
+
return exprs
|
| 409 |
+
|
| 410 |
+
def is_homogeneous_solution(term):
|
| 411 |
+
r""" This function checks whether the given trialset contains any root
|
| 412 |
+
of homogeneous equation"""
|
| 413 |
+
return expand(sub_func_doit(eq_homogeneous, func, term)).is_zero
|
| 414 |
+
|
| 415 |
+
retdict['test'] = _test_term(expr, x)
|
| 416 |
+
if retdict['test']:
|
| 417 |
+
# Try to generate a list of trial solutions that will have the
|
| 418 |
+
# undetermined coefficients. Note that if any of these are not linearly
|
| 419 |
+
# independent with any of the solutions to the homogeneous equation,
|
| 420 |
+
# then they will need to be multiplied by sufficient x to make them so.
|
| 421 |
+
# This function DOES NOT do that (it doesn't even look at the
|
| 422 |
+
# homogeneous equation).
|
| 423 |
+
temp_set = set()
|
| 424 |
+
for i in Add.make_args(expr):
|
| 425 |
+
act = _get_trial_set(i, x)
|
| 426 |
+
if eq_homogeneous is not S.Zero:
|
| 427 |
+
while any(is_homogeneous_solution(ts) for ts in act):
|
| 428 |
+
act = {x*ts for ts in act}
|
| 429 |
+
temp_set = temp_set.union(act)
|
| 430 |
+
|
| 431 |
+
retdict['trialset'] = temp_set
|
| 432 |
+
return retdict
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def _solve_undetermined_coefficients(eq, func, order, match, trialset):
|
| 436 |
+
r"""
|
| 437 |
+
Helper function for the method of undetermined coefficients.
|
| 438 |
+
|
| 439 |
+
See the
|
| 440 |
+
:py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffUndeterminedCoefficients`
|
| 441 |
+
docstring for more information on this method.
|
| 442 |
+
|
| 443 |
+
The parameter ``trialset`` is the set of trial functions as returned by
|
| 444 |
+
``_undetermined_coefficients_match()['trialset']``.
|
| 445 |
+
|
| 446 |
+
The parameter ``match`` should be a dictionary that has the following
|
| 447 |
+
keys:
|
| 448 |
+
|
| 449 |
+
``list``
|
| 450 |
+
A list of solutions to the homogeneous equation.
|
| 451 |
+
|
| 452 |
+
``sol``
|
| 453 |
+
The general solution.
|
| 454 |
+
|
| 455 |
+
"""
|
| 456 |
+
r = match
|
| 457 |
+
coeffs = numbered_symbols('a', cls=Dummy)
|
| 458 |
+
coefflist = []
|
| 459 |
+
gensols = r['list']
|
| 460 |
+
gsol = r['sol']
|
| 461 |
+
f = func.func
|
| 462 |
+
x = func.args[0]
|
| 463 |
+
|
| 464 |
+
if len(gensols) != order:
|
| 465 |
+
raise NotImplementedError("Cannot find " + str(order) +
|
| 466 |
+
" solutions to the homogeneous equation necessary to apply" +
|
| 467 |
+
" undetermined coefficients to " + str(eq) +
|
| 468 |
+
" (number of terms != order)")
|
| 469 |
+
|
| 470 |
+
trialfunc = 0
|
| 471 |
+
for i in trialset:
|
| 472 |
+
c = next(coeffs)
|
| 473 |
+
coefflist.append(c)
|
| 474 |
+
trialfunc += c*i
|
| 475 |
+
|
| 476 |
+
eqs = sub_func_doit(eq, f(x), trialfunc)
|
| 477 |
+
|
| 478 |
+
coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1))))
|
| 479 |
+
|
| 480 |
+
eqs = _mexpand(eqs)
|
| 481 |
+
|
| 482 |
+
for i in Add.make_args(eqs):
|
| 483 |
+
s = separatevars(i, dict=True, symbols=[x])
|
| 484 |
+
if coeffsdict.get(s[x]):
|
| 485 |
+
coeffsdict[s[x]] += s['coeff']
|
| 486 |
+
else:
|
| 487 |
+
coeffsdict[s[x]] = s['coeff']
|
| 488 |
+
|
| 489 |
+
coeffvals = solve(list(coeffsdict.values()), coefflist)
|
| 490 |
+
|
| 491 |
+
if not coeffvals:
|
| 492 |
+
raise NotImplementedError(
|
| 493 |
+
"Could not solve `%s` using the "
|
| 494 |
+
"method of undetermined coefficients "
|
| 495 |
+
"(unable to solve for coefficients)." % eq)
|
| 496 |
+
|
| 497 |
+
psol = trialfunc.subs(coeffvals)
|
| 498 |
+
|
| 499 |
+
return Eq(f(x), gsol.rhs + psol)
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/single.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/subscheck.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import S, Pow
|
| 2 |
+
from sympy.core.function import (Derivative, AppliedUndef, diff)
|
| 3 |
+
from sympy.core.relational import Equality, Eq
|
| 4 |
+
from sympy.core.symbol import Dummy
|
| 5 |
+
from sympy.core.sympify import sympify
|
| 6 |
+
|
| 7 |
+
from sympy.logic.boolalg import BooleanAtom
|
| 8 |
+
from sympy.functions import exp
|
| 9 |
+
from sympy.series import Order
|
| 10 |
+
from sympy.simplify.simplify import simplify, posify, besselsimp
|
| 11 |
+
from sympy.simplify.trigsimp import trigsimp
|
| 12 |
+
from sympy.simplify.sqrtdenest import sqrtdenest
|
| 13 |
+
from sympy.solvers import solve
|
| 14 |
+
from sympy.solvers.deutils import _preprocess, ode_order
|
| 15 |
+
from sympy.utilities.iterables import iterable, is_sequence
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def sub_func_doit(eq, func, new):
|
| 19 |
+
r"""
|
| 20 |
+
When replacing the func with something else, we usually want the
|
| 21 |
+
derivative evaluated, so this function helps in making that happen.
|
| 22 |
+
|
| 23 |
+
Examples
|
| 24 |
+
========
|
| 25 |
+
|
| 26 |
+
>>> from sympy import Derivative, symbols, Function
|
| 27 |
+
>>> from sympy.solvers.ode.subscheck import sub_func_doit
|
| 28 |
+
>>> x, z = symbols('x, z')
|
| 29 |
+
>>> y = Function('y')
|
| 30 |
+
|
| 31 |
+
>>> sub_func_doit(3*Derivative(y(x), x) - 1, y(x), x)
|
| 32 |
+
2
|
| 33 |
+
|
| 34 |
+
>>> sub_func_doit(x*Derivative(y(x), x) - y(x)**2 + y(x), y(x),
|
| 35 |
+
... 1/(x*(z + 1/x)))
|
| 36 |
+
x*(-1/(x**2*(z + 1/x)) + 1/(x**3*(z + 1/x)**2)) + 1/(x*(z + 1/x))
|
| 37 |
+
...- 1/(x**2*(z + 1/x)**2)
|
| 38 |
+
"""
|
| 39 |
+
reps= {func: new}
|
| 40 |
+
for d in eq.atoms(Derivative):
|
| 41 |
+
if d.expr == func:
|
| 42 |
+
reps[d] = new.diff(*d.variable_count)
|
| 43 |
+
else:
|
| 44 |
+
reps[d] = d.xreplace({func: new}).doit(deep=False)
|
| 45 |
+
return eq.xreplace(reps)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def checkodesol(ode, sol, func=None, order='auto', solve_for_func=True):
|
| 49 |
+
r"""
|
| 50 |
+
Substitutes ``sol`` into ``ode`` and checks that the result is ``0``.
|
| 51 |
+
|
| 52 |
+
This works when ``func`` is one function, like `f(x)` or a list of
|
| 53 |
+
functions like `[f(x), g(x)]` when `ode` is a system of ODEs. ``sol`` can
|
| 54 |
+
be a single solution or a list of solutions. Each solution may be an
|
| 55 |
+
:py:class:`~sympy.core.relational.Equality` that the solution satisfies,
|
| 56 |
+
e.g. ``Eq(f(x), C1), Eq(f(x) + C1, 0)``; or simply an
|
| 57 |
+
:py:class:`~sympy.core.expr.Expr`, e.g. ``f(x) - C1``. In most cases it
|
| 58 |
+
will not be necessary to explicitly identify the function, but if the
|
| 59 |
+
function cannot be inferred from the original equation it can be supplied
|
| 60 |
+
through the ``func`` argument.
|
| 61 |
+
|
| 62 |
+
If a sequence of solutions is passed, the same sort of container will be
|
| 63 |
+
used to return the result for each solution.
|
| 64 |
+
|
| 65 |
+
It tries the following methods, in order, until it finds zero equivalence:
|
| 66 |
+
|
| 67 |
+
1. Substitute the solution for `f` in the original equation. This only
|
| 68 |
+
works if ``ode`` is solved for `f`. It will attempt to solve it first
|
| 69 |
+
unless ``solve_for_func == False``.
|
| 70 |
+
2. Take `n` derivatives of the solution, where `n` is the order of
|
| 71 |
+
``ode``, and check to see if that is equal to the solution. This only
|
| 72 |
+
works on exact ODEs.
|
| 73 |
+
3. Take the 1st, 2nd, ..., `n`\th derivatives of the solution, each time
|
| 74 |
+
solving for the derivative of `f` of that order (this will always be
|
| 75 |
+
possible because `f` is a linear operator). Then back substitute each
|
| 76 |
+
derivative into ``ode`` in reverse order.
|
| 77 |
+
|
| 78 |
+
This function returns a tuple. The first item in the tuple is ``True`` if
|
| 79 |
+
the substitution results in ``0``, and ``False`` otherwise. The second
|
| 80 |
+
item in the tuple is what the substitution results in. It should always
|
| 81 |
+
be ``0`` if the first item is ``True``. Sometimes this function will
|
| 82 |
+
return ``False`` even when an expression is identically equal to ``0``.
|
| 83 |
+
This happens when :py:meth:`~sympy.simplify.simplify.simplify` does not
|
| 84 |
+
reduce the expression to ``0``. If an expression returned by this
|
| 85 |
+
function vanishes identically, then ``sol`` really is a solution to
|
| 86 |
+
the ``ode``.
|
| 87 |
+
|
| 88 |
+
If this function seems to hang, it is probably because of a hard
|
| 89 |
+
simplification.
|
| 90 |
+
|
| 91 |
+
To use this function to test, test the first item of the tuple.
|
| 92 |
+
|
| 93 |
+
Examples
|
| 94 |
+
========
|
| 95 |
+
|
| 96 |
+
>>> from sympy import (Eq, Function, checkodesol, symbols,
|
| 97 |
+
... Derivative, exp)
|
| 98 |
+
>>> x, C1, C2 = symbols('x,C1,C2')
|
| 99 |
+
>>> f, g = symbols('f g', cls=Function)
|
| 100 |
+
>>> checkodesol(f(x).diff(x), Eq(f(x), C1))
|
| 101 |
+
(True, 0)
|
| 102 |
+
>>> assert checkodesol(f(x).diff(x), C1)[0]
|
| 103 |
+
>>> assert not checkodesol(f(x).diff(x), x)[0]
|
| 104 |
+
>>> checkodesol(f(x).diff(x, 2), x**2)
|
| 105 |
+
(False, 2)
|
| 106 |
+
|
| 107 |
+
>>> eqs = [Eq(Derivative(f(x), x), f(x)), Eq(Derivative(g(x), x), g(x))]
|
| 108 |
+
>>> sol = [Eq(f(x), C1*exp(x)), Eq(g(x), C2*exp(x))]
|
| 109 |
+
>>> checkodesol(eqs, sol)
|
| 110 |
+
(True, [0, 0])
|
| 111 |
+
|
| 112 |
+
"""
|
| 113 |
+
if iterable(ode):
|
| 114 |
+
return checksysodesol(ode, sol, func=func)
|
| 115 |
+
|
| 116 |
+
if not isinstance(ode, Equality):
|
| 117 |
+
ode = Eq(ode, 0)
|
| 118 |
+
if func is None:
|
| 119 |
+
try:
|
| 120 |
+
_, func = _preprocess(ode.lhs)
|
| 121 |
+
except ValueError:
|
| 122 |
+
funcs = [s.atoms(AppliedUndef) for s in (
|
| 123 |
+
sol if is_sequence(sol, set) else [sol])]
|
| 124 |
+
funcs = set().union(*funcs)
|
| 125 |
+
if len(funcs) != 1:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
'must pass func arg to checkodesol for this case.')
|
| 128 |
+
func = funcs.pop()
|
| 129 |
+
if not isinstance(func, AppliedUndef) or len(func.args) != 1:
|
| 130 |
+
raise ValueError(
|
| 131 |
+
"func must be a function of one variable, not %s" % func)
|
| 132 |
+
if is_sequence(sol, set):
|
| 133 |
+
return type(sol)([checkodesol(ode, i, order=order, solve_for_func=solve_for_func) for i in sol])
|
| 134 |
+
|
| 135 |
+
if not isinstance(sol, Equality):
|
| 136 |
+
sol = Eq(func, sol)
|
| 137 |
+
elif sol.rhs == func:
|
| 138 |
+
sol = sol.reversed
|
| 139 |
+
|
| 140 |
+
if order == 'auto':
|
| 141 |
+
order = ode_order(ode, func)
|
| 142 |
+
solved = sol.lhs == func and not sol.rhs.has(func)
|
| 143 |
+
if solve_for_func and not solved:
|
| 144 |
+
rhs = solve(sol, func)
|
| 145 |
+
if rhs:
|
| 146 |
+
eqs = [Eq(func, t) for t in rhs]
|
| 147 |
+
if len(rhs) == 1:
|
| 148 |
+
eqs = eqs[0]
|
| 149 |
+
return checkodesol(ode, eqs, order=order,
|
| 150 |
+
solve_for_func=False)
|
| 151 |
+
|
| 152 |
+
x = func.args[0]
|
| 153 |
+
|
| 154 |
+
# Handle series solutions here
|
| 155 |
+
if sol.has(Order):
|
| 156 |
+
assert sol.lhs == func
|
| 157 |
+
Oterm = sol.rhs.getO()
|
| 158 |
+
solrhs = sol.rhs.removeO()
|
| 159 |
+
|
| 160 |
+
Oexpr = Oterm.expr
|
| 161 |
+
assert isinstance(Oexpr, Pow)
|
| 162 |
+
sorder = Oexpr.exp
|
| 163 |
+
assert Oterm == Order(x**sorder)
|
| 164 |
+
|
| 165 |
+
odesubs = (ode.lhs-ode.rhs).subs(func, solrhs).doit().expand()
|
| 166 |
+
|
| 167 |
+
neworder = Order(x**(sorder - order))
|
| 168 |
+
odesubs = odesubs + neworder
|
| 169 |
+
assert odesubs.getO() == neworder
|
| 170 |
+
residual = odesubs.removeO()
|
| 171 |
+
|
| 172 |
+
return (residual == 0, residual)
|
| 173 |
+
|
| 174 |
+
s = True
|
| 175 |
+
testnum = 0
|
| 176 |
+
while s:
|
| 177 |
+
if testnum == 0:
|
| 178 |
+
# First pass, try substituting a solved solution directly into the
|
| 179 |
+
# ODE. This has the highest chance of succeeding.
|
| 180 |
+
ode_diff = ode.lhs - ode.rhs
|
| 181 |
+
|
| 182 |
+
if sol.lhs == func:
|
| 183 |
+
s = sub_func_doit(ode_diff, func, sol.rhs)
|
| 184 |
+
s = besselsimp(s)
|
| 185 |
+
else:
|
| 186 |
+
testnum += 1
|
| 187 |
+
continue
|
| 188 |
+
ss = simplify(s.rewrite(exp))
|
| 189 |
+
if ss:
|
| 190 |
+
# with the new numer_denom in power.py, if we do a simple
|
| 191 |
+
# expansion then testnum == 0 verifies all solutions.
|
| 192 |
+
s = ss.expand(force=True)
|
| 193 |
+
else:
|
| 194 |
+
s = 0
|
| 195 |
+
testnum += 1
|
| 196 |
+
elif testnum == 1:
|
| 197 |
+
# Second pass. If we cannot substitute f, try seeing if the nth
|
| 198 |
+
# derivative is equal, this will only work for odes that are exact,
|
| 199 |
+
# by definition.
|
| 200 |
+
s = simplify(
|
| 201 |
+
trigsimp(diff(sol.lhs, x, order) - diff(sol.rhs, x, order)) -
|
| 202 |
+
trigsimp(ode.lhs) + trigsimp(ode.rhs))
|
| 203 |
+
# s2 = simplify(
|
| 204 |
+
# diff(sol.lhs, x, order) - diff(sol.rhs, x, order) - \
|
| 205 |
+
# ode.lhs + ode.rhs)
|
| 206 |
+
testnum += 1
|
| 207 |
+
elif testnum == 2:
|
| 208 |
+
# Third pass. Try solving for df/dx and substituting that into the
|
| 209 |
+
# ODE. Thanks to Chris Smith for suggesting this method. Many of
|
| 210 |
+
# the comments below are his, too.
|
| 211 |
+
# The method:
|
| 212 |
+
# - Take each of 1..n derivatives of the solution.
|
| 213 |
+
# - Solve each nth derivative for d^(n)f/dx^(n)
|
| 214 |
+
# (the differential of that order)
|
| 215 |
+
# - Back substitute into the ODE in decreasing order
|
| 216 |
+
# (i.e., n, n-1, ...)
|
| 217 |
+
# - Check the result for zero equivalence
|
| 218 |
+
if sol.lhs == func and not sol.rhs.has(func):
|
| 219 |
+
diffsols = {0: sol.rhs}
|
| 220 |
+
elif sol.rhs == func and not sol.lhs.has(func):
|
| 221 |
+
diffsols = {0: sol.lhs}
|
| 222 |
+
else:
|
| 223 |
+
diffsols = {}
|
| 224 |
+
sol = sol.lhs - sol.rhs
|
| 225 |
+
for i in range(1, order + 1):
|
| 226 |
+
# Differentiation is a linear operator, so there should always
|
| 227 |
+
# be 1 solution. Nonetheless, we test just to make sure.
|
| 228 |
+
# We only need to solve once. After that, we automatically
|
| 229 |
+
# have the solution to the differential in the order we want.
|
| 230 |
+
if i == 1:
|
| 231 |
+
ds = sol.diff(x)
|
| 232 |
+
try:
|
| 233 |
+
sdf = solve(ds, func.diff(x, i))
|
| 234 |
+
if not sdf:
|
| 235 |
+
raise NotImplementedError
|
| 236 |
+
except NotImplementedError:
|
| 237 |
+
testnum += 1
|
| 238 |
+
break
|
| 239 |
+
else:
|
| 240 |
+
diffsols[i] = sdf[0]
|
| 241 |
+
else:
|
| 242 |
+
# This is what the solution says df/dx should be.
|
| 243 |
+
diffsols[i] = diffsols[i - 1].diff(x)
|
| 244 |
+
|
| 245 |
+
# Make sure the above didn't fail.
|
| 246 |
+
if testnum > 2:
|
| 247 |
+
continue
|
| 248 |
+
else:
|
| 249 |
+
# Substitute it into ODE to check for self consistency.
|
| 250 |
+
lhs, rhs = ode.lhs, ode.rhs
|
| 251 |
+
for i in range(order, -1, -1):
|
| 252 |
+
if i == 0 and 0 not in diffsols:
|
| 253 |
+
# We can only substitute f(x) if the solution was
|
| 254 |
+
# solved for f(x).
|
| 255 |
+
break
|
| 256 |
+
lhs = sub_func_doit(lhs, func.diff(x, i), diffsols[i])
|
| 257 |
+
rhs = sub_func_doit(rhs, func.diff(x, i), diffsols[i])
|
| 258 |
+
ode_or_bool = Eq(lhs, rhs)
|
| 259 |
+
ode_or_bool = simplify(ode_or_bool)
|
| 260 |
+
|
| 261 |
+
if isinstance(ode_or_bool, (bool, BooleanAtom)):
|
| 262 |
+
if ode_or_bool:
|
| 263 |
+
lhs = rhs = S.Zero
|
| 264 |
+
else:
|
| 265 |
+
lhs = ode_or_bool.lhs
|
| 266 |
+
rhs = ode_or_bool.rhs
|
| 267 |
+
# No sense in overworking simplify -- just prove that the
|
| 268 |
+
# numerator goes to zero
|
| 269 |
+
num = trigsimp((lhs - rhs).as_numer_denom()[0])
|
| 270 |
+
# since solutions are obtained using force=True we test
|
| 271 |
+
# using the same level of assumptions
|
| 272 |
+
## replace function with dummy so assumptions will work
|
| 273 |
+
_func = Dummy('func')
|
| 274 |
+
num = num.subs(func, _func)
|
| 275 |
+
## posify the expression
|
| 276 |
+
num, reps = posify(num)
|
| 277 |
+
s = simplify(num).xreplace(reps).xreplace({_func: func})
|
| 278 |
+
testnum += 1
|
| 279 |
+
else:
|
| 280 |
+
break
|
| 281 |
+
|
| 282 |
+
if not s:
|
| 283 |
+
return (True, s)
|
| 284 |
+
elif s is True: # The code above never was able to change s
|
| 285 |
+
raise NotImplementedError("Unable to test if " + str(sol) +
|
| 286 |
+
" is a solution to " + str(ode) + ".")
|
| 287 |
+
else:
|
| 288 |
+
return (False, s)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def checksysodesol(eqs, sols, func=None):
|
| 292 |
+
r"""
|
| 293 |
+
Substitutes corresponding ``sols`` for each functions into each ``eqs`` and
|
| 294 |
+
checks that the result of substitutions for each equation is ``0``. The
|
| 295 |
+
equations and solutions passed can be any iterable.
|
| 296 |
+
|
| 297 |
+
This only works when each ``sols`` have one function only, like `x(t)` or `y(t)`.
|
| 298 |
+
For each function, ``sols`` can have a single solution or a list of solutions.
|
| 299 |
+
In most cases it will not be necessary to explicitly identify the function,
|
| 300 |
+
but if the function cannot be inferred from the original equation it
|
| 301 |
+
can be supplied through the ``func`` argument.
|
| 302 |
+
|
| 303 |
+
When a sequence of equations is passed, the same sequence is used to return
|
| 304 |
+
the result for each equation with each function substituted with corresponding
|
| 305 |
+
solutions.
|
| 306 |
+
|
| 307 |
+
It tries the following method to find zero equivalence for each equation:
|
| 308 |
+
|
| 309 |
+
Substitute the solutions for functions, like `x(t)` and `y(t)` into the
|
| 310 |
+
original equations containing those functions.
|
| 311 |
+
This function returns a tuple. The first item in the tuple is ``True`` if
|
| 312 |
+
the substitution results for each equation is ``0``, and ``False`` otherwise.
|
| 313 |
+
The second item in the tuple is what the substitution results in. Each element
|
| 314 |
+
of the ``list`` should always be ``0`` corresponding to each equation if the
|
| 315 |
+
first item is ``True``. Note that sometimes this function may return ``False``,
|
| 316 |
+
but with an expression that is identically equal to ``0``, instead of returning
|
| 317 |
+
``True``. This is because :py:meth:`~sympy.simplify.simplify.simplify` cannot
|
| 318 |
+
reduce the expression to ``0``. If an expression returned by each function
|
| 319 |
+
vanishes identically, then ``sols`` really is a solution to ``eqs``.
|
| 320 |
+
|
| 321 |
+
If this function seems to hang, it is probably because of a difficult simplification.
|
| 322 |
+
|
| 323 |
+
Examples
|
| 324 |
+
========
|
| 325 |
+
|
| 326 |
+
>>> from sympy import Eq, diff, symbols, sin, cos, exp, sqrt, S, Function
|
| 327 |
+
>>> from sympy.solvers.ode.subscheck import checksysodesol
|
| 328 |
+
>>> C1, C2 = symbols('C1:3')
|
| 329 |
+
>>> t = symbols('t')
|
| 330 |
+
>>> x, y = symbols('x, y', cls=Function)
|
| 331 |
+
>>> eq = (Eq(diff(x(t),t), x(t) + y(t) + 17), Eq(diff(y(t),t), -2*x(t) + y(t) + 12))
|
| 332 |
+
>>> sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - S(5)/3),
|
| 333 |
+
... Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - S(46)/3)]
|
| 334 |
+
>>> checksysodesol(eq, sol)
|
| 335 |
+
(True, [0, 0])
|
| 336 |
+
>>> eq = (Eq(diff(x(t),t),x(t)*y(t)**4), Eq(diff(y(t),t),y(t)**3))
|
| 337 |
+
>>> sol = [Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), -sqrt(2)*sqrt(-1/(C2 + t))/2),
|
| 338 |
+
... Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), sqrt(2)*sqrt(-1/(C2 + t))/2)]
|
| 339 |
+
>>> checksysodesol(eq, sol)
|
| 340 |
+
(True, [0, 0])
|
| 341 |
+
|
| 342 |
+
"""
|
| 343 |
+
def _sympify(eq):
|
| 344 |
+
return list(map(sympify, eq if iterable(eq) else [eq]))
|
| 345 |
+
eqs = _sympify(eqs)
|
| 346 |
+
for i in range(len(eqs)):
|
| 347 |
+
if isinstance(eqs[i], Equality):
|
| 348 |
+
eqs[i] = eqs[i].lhs - eqs[i].rhs
|
| 349 |
+
if func is None:
|
| 350 |
+
funcs = []
|
| 351 |
+
for eq in eqs:
|
| 352 |
+
derivs = eq.atoms(Derivative)
|
| 353 |
+
func = set().union(*[d.atoms(AppliedUndef) for d in derivs])
|
| 354 |
+
funcs.extend(func)
|
| 355 |
+
funcs = list(set(funcs))
|
| 356 |
+
if not all(isinstance(func, AppliedUndef) and len(func.args) == 1 for func in funcs)\
|
| 357 |
+
and len({func.args for func in funcs})!=1:
|
| 358 |
+
raise ValueError("func must be a function of one variable, not %s" % func)
|
| 359 |
+
for sol in sols:
|
| 360 |
+
if len(sol.atoms(AppliedUndef)) != 1:
|
| 361 |
+
raise ValueError("solutions should have one function only")
|
| 362 |
+
if len(funcs) != len({sol.lhs for sol in sols}):
|
| 363 |
+
raise ValueError("number of solutions provided does not match the number of equations")
|
| 364 |
+
dictsol = {}
|
| 365 |
+
for sol in sols:
|
| 366 |
+
func = list(sol.atoms(AppliedUndef))[0]
|
| 367 |
+
if sol.rhs == func:
|
| 368 |
+
sol = sol.reversed
|
| 369 |
+
solved = sol.lhs == func and not sol.rhs.has(func)
|
| 370 |
+
if not solved:
|
| 371 |
+
rhs = solve(sol, func)
|
| 372 |
+
if not rhs:
|
| 373 |
+
raise NotImplementedError
|
| 374 |
+
else:
|
| 375 |
+
rhs = sol.rhs
|
| 376 |
+
dictsol[func] = rhs
|
| 377 |
+
checkeq = []
|
| 378 |
+
for eq in eqs:
|
| 379 |
+
for func in funcs:
|
| 380 |
+
eq = sub_func_doit(eq, func, dictsol[func])
|
| 381 |
+
ss = simplify(eq)
|
| 382 |
+
if ss != 0:
|
| 383 |
+
eq = ss.expand(force=True)
|
| 384 |
+
if eq != 0:
|
| 385 |
+
eq = sqrtdenest(eq).simplify()
|
| 386 |
+
else:
|
| 387 |
+
eq = 0
|
| 388 |
+
checkeq.append(eq)
|
| 389 |
+
if len(set(checkeq)) == 1 and list(set(checkeq))[0] == 0:
|
| 390 |
+
return (True, checkeq)
|
| 391 |
+
else:
|
| 392 |
+
return (False, checkeq)
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (173 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_lie_group.cpython-310.pyc
ADDED
|
Binary file (5.93 kB). View file
|
|
|