Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/__init__.py +25 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py +805 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/euler.py +108 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/finite_diff.py +476 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/singularities.py +398 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py +336 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py +74 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py +103 -0
- llmeval-env/lib/python3.10/site-packages/sympy/calculus/util.py +841 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__init__.py +18 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/holonomic.py +2899 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/holonomicerrors.py +49 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/numerical.py +109 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/recurrence.py +365 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/test_holonomic.py +830 -0
- llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/test_recurrence.py +29 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/decompositions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/dense.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/immutable.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/inverse.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/normalforms.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/repmatrix.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/solvers.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/utilities.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_commonmatrix.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_decompositions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_determinant.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_eigen.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_graph.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_immutable.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_interactions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrices.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/sympy/calculus/__init__.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Calculus-related methods."""
|
2 |
+
|
3 |
+
from .euler import euler_equations
|
4 |
+
from .singularities import (singularities, is_increasing,
|
5 |
+
is_strictly_increasing, is_decreasing,
|
6 |
+
is_strictly_decreasing, is_monotonic)
|
7 |
+
from .finite_diff import finite_diff_weights, apply_finite_diff, differentiate_finite
|
8 |
+
from .util import (periodicity, not_empty_in, is_convex,
|
9 |
+
stationary_points, minimum, maximum)
|
10 |
+
from .accumulationbounds import AccumBounds
|
11 |
+
|
12 |
+
__all__ = [
|
13 |
+
'euler_equations',
|
14 |
+
|
15 |
+
'singularities', 'is_increasing',
|
16 |
+
'is_strictly_increasing', 'is_decreasing',
|
17 |
+
'is_strictly_decreasing', 'is_monotonic',
|
18 |
+
|
19 |
+
'finite_diff_weights', 'apply_finite_diff', 'differentiate_finite',
|
20 |
+
|
21 |
+
'periodicity', 'not_empty_in', 'is_convex', 'stationary_points',
|
22 |
+
'minimum', 'maximum',
|
23 |
+
|
24 |
+
'AccumBounds'
|
25 |
+
]
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (868 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc
ADDED
Binary file (20.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc
ADDED
Binary file (3.82 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc
ADDED
Binary file (17.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc
ADDED
Binary file (11.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc
ADDED
Binary file (21.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py
ADDED
@@ -0,0 +1,805 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import Add, Mul, Pow, S
|
2 |
+
from sympy.core.basic import Basic
|
3 |
+
from sympy.core.expr import Expr
|
4 |
+
from sympy.core.numbers import _sympifyit, oo, zoo
|
5 |
+
from sympy.core.relational import is_le, is_lt, is_ge, is_gt
|
6 |
+
from sympy.core.sympify import _sympify
|
7 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
8 |
+
from sympy.logic.boolalg import And
|
9 |
+
from sympy.multipledispatch import dispatch
|
10 |
+
from sympy.series.order import Order
|
11 |
+
from sympy.sets.sets import FiniteSet
|
12 |
+
|
13 |
+
|
14 |
+
class AccumulationBounds(Expr):
|
15 |
+
r"""An accumulation bounds.
|
16 |
+
|
17 |
+
# Note AccumulationBounds has an alias: AccumBounds
|
18 |
+
|
19 |
+
AccumulationBounds represent an interval `[a, b]`, which is always closed
|
20 |
+
at the ends. Here `a` and `b` can be any value from extended real numbers.
|
21 |
+
|
22 |
+
The intended meaning of AccummulationBounds is to give an approximate
|
23 |
+
location of the accumulation points of a real function at a limit point.
|
24 |
+
|
25 |
+
Let `a` and `b` be reals such that `a \le b`.
|
26 |
+
|
27 |
+
`\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}`
|
28 |
+
|
29 |
+
`\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}`
|
30 |
+
|
31 |
+
`\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}`
|
32 |
+
|
33 |
+
`\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}`
|
34 |
+
|
35 |
+
``oo`` and ``-oo`` are added to the second and third definition respectively,
|
36 |
+
since if either ``-oo`` or ``oo`` is an argument, then the other one should
|
37 |
+
be included (though not as an end point). This is forced, since we have,
|
38 |
+
for example, ``1/AccumBounds(0, 1) = AccumBounds(1, oo)``, and the limit at
|
39 |
+
`0` is not one-sided. As `x` tends to `0-`, then `1/x \rightarrow -\infty`, so `-\infty`
|
40 |
+
should be interpreted as belonging to ``AccumBounds(1, oo)`` though it need
|
41 |
+
not appear explicitly.
|
42 |
+
|
43 |
+
In many cases it suffices to know that the limit set is bounded.
|
44 |
+
However, in some other cases more exact information could be useful.
|
45 |
+
For example, all accumulation values of `\cos(x) + 1` are non-negative.
|
46 |
+
(``AccumBounds(-1, 1) + 1 = AccumBounds(0, 2)``)
|
47 |
+
|
48 |
+
A AccumulationBounds object is defined to be real AccumulationBounds,
|
49 |
+
if its end points are finite reals.
|
50 |
+
|
51 |
+
Let `X`, `Y` be real AccumulationBounds, then their sum, difference,
|
52 |
+
product are defined to be the following sets:
|
53 |
+
|
54 |
+
`X + Y = \{ x+y \mid x \in X \cap y \in Y\}`
|
55 |
+
|
56 |
+
`X - Y = \{ x-y \mid x \in X \cap y \in Y\}`
|
57 |
+
|
58 |
+
`X \times Y = \{ x \times y \mid x \in X \cap y \in Y\}`
|
59 |
+
|
60 |
+
When an AccumBounds is raised to a negative power, if 0 is contained
|
61 |
+
between the bounds then an infinite range is returned, otherwise if an
|
62 |
+
endpoint is 0 then a semi-infinite range with consistent sign will be returned.
|
63 |
+
|
64 |
+
AccumBounds in expressions behave a lot like Intervals but the
|
65 |
+
semantics are not necessarily the same. Division (or exponentiation
|
66 |
+
to a negative integer power) could be handled with *intervals* by
|
67 |
+
returning a union of the results obtained after splitting the
|
68 |
+
bounds between negatives and positives, but that is not done with
|
69 |
+
AccumBounds. In addition, bounds are assumed to be independent of
|
70 |
+
each other; if the same bound is used in more than one place in an
|
71 |
+
expression, the result may not be the supremum or infimum of the
|
72 |
+
expression (see below). Finally, when a boundary is ``1``,
|
73 |
+
exponentiation to the power of ``oo`` yields ``oo``, neither
|
74 |
+
``1`` nor ``nan``.
|
75 |
+
|
76 |
+
Examples
|
77 |
+
========
|
78 |
+
|
79 |
+
>>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo
|
80 |
+
>>> from sympy.abc import x
|
81 |
+
|
82 |
+
>>> AccumBounds(0, 1) + AccumBounds(1, 2)
|
83 |
+
AccumBounds(1, 3)
|
84 |
+
|
85 |
+
>>> AccumBounds(0, 1) - AccumBounds(0, 2)
|
86 |
+
AccumBounds(-2, 1)
|
87 |
+
|
88 |
+
>>> AccumBounds(-2, 3)*AccumBounds(-1, 1)
|
89 |
+
AccumBounds(-3, 3)
|
90 |
+
|
91 |
+
>>> AccumBounds(1, 2)*AccumBounds(3, 5)
|
92 |
+
AccumBounds(3, 10)
|
93 |
+
|
94 |
+
The exponentiation of AccumulationBounds is defined
|
95 |
+
as follows:
|
96 |
+
|
97 |
+
If 0 does not belong to `X` or `n > 0` then
|
98 |
+
|
99 |
+
`X^n = \{ x^n \mid x \in X\}`
|
100 |
+
|
101 |
+
>>> AccumBounds(1, 4)**(S(1)/2)
|
102 |
+
AccumBounds(1, 2)
|
103 |
+
|
104 |
+
otherwise, an infinite or semi-infinite result is obtained:
|
105 |
+
|
106 |
+
>>> 1/AccumBounds(-1, 1)
|
107 |
+
AccumBounds(-oo, oo)
|
108 |
+
>>> 1/AccumBounds(0, 2)
|
109 |
+
AccumBounds(1/2, oo)
|
110 |
+
>>> 1/AccumBounds(-oo, 0)
|
111 |
+
AccumBounds(-oo, 0)
|
112 |
+
|
113 |
+
A boundary of 1 will always generate all nonnegatives:
|
114 |
+
|
115 |
+
>>> AccumBounds(1, 2)**oo
|
116 |
+
AccumBounds(0, oo)
|
117 |
+
>>> AccumBounds(0, 1)**oo
|
118 |
+
AccumBounds(0, oo)
|
119 |
+
|
120 |
+
If the exponent is itself an AccumulationBounds or is not an
|
121 |
+
integer then unevaluated results will be returned unless the base
|
122 |
+
values are positive:
|
123 |
+
|
124 |
+
>>> AccumBounds(2, 3)**AccumBounds(-1, 2)
|
125 |
+
AccumBounds(1/3, 9)
|
126 |
+
>>> AccumBounds(-2, 3)**AccumBounds(-1, 2)
|
127 |
+
AccumBounds(-2, 3)**AccumBounds(-1, 2)
|
128 |
+
|
129 |
+
>>> AccumBounds(-2, -1)**(S(1)/2)
|
130 |
+
sqrt(AccumBounds(-2, -1))
|
131 |
+
|
132 |
+
Note: `\left\langle a, b\right\rangle^2` is not same as `\left\langle a, b\right\rangle \times \left\langle a, b\right\rangle`
|
133 |
+
|
134 |
+
>>> AccumBounds(-1, 1)**2
|
135 |
+
AccumBounds(0, 1)
|
136 |
+
|
137 |
+
>>> AccumBounds(1, 3) < 4
|
138 |
+
True
|
139 |
+
|
140 |
+
>>> AccumBounds(1, 3) < -1
|
141 |
+
False
|
142 |
+
|
143 |
+
Some elementary functions can also take AccumulationBounds as input.
|
144 |
+
A function `f` evaluated for some real AccumulationBounds `\left\langle a, b \right\rangle`
|
145 |
+
is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}`
|
146 |
+
|
147 |
+
>>> sin(AccumBounds(pi/6, pi/3))
|
148 |
+
AccumBounds(1/2, sqrt(3)/2)
|
149 |
+
|
150 |
+
>>> exp(AccumBounds(0, 1))
|
151 |
+
AccumBounds(1, E)
|
152 |
+
|
153 |
+
>>> log(AccumBounds(1, E))
|
154 |
+
AccumBounds(0, 1)
|
155 |
+
|
156 |
+
Some symbol in an expression can be substituted for a AccumulationBounds
|
157 |
+
object. But it does not necessarily evaluate the AccumulationBounds for
|
158 |
+
that expression.
|
159 |
+
|
160 |
+
The same expression can be evaluated to different values depending upon
|
161 |
+
the form it is used for substitution since each instance of an
|
162 |
+
AccumulationBounds is considered independent. For example:
|
163 |
+
|
164 |
+
>>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1))
|
165 |
+
AccumBounds(-1, 4)
|
166 |
+
|
167 |
+
>>> ((x + 1)**2).subs(x, AccumBounds(-1, 1))
|
168 |
+
AccumBounds(0, 4)
|
169 |
+
|
170 |
+
References
|
171 |
+
==========
|
172 |
+
|
173 |
+
.. [1] https://en.wikipedia.org/wiki/Interval_arithmetic
|
174 |
+
|
175 |
+
.. [2] https://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf
|
176 |
+
|
177 |
+
Notes
|
178 |
+
=====
|
179 |
+
|
180 |
+
Do not use ``AccumulationBounds`` for floating point interval arithmetic
|
181 |
+
calculations, use ``mpmath.iv`` instead.
|
182 |
+
"""
|
183 |
+
|
184 |
+
is_extended_real = True
|
185 |
+
is_number = False
|
186 |
+
|
187 |
+
def __new__(cls, min, max):
|
188 |
+
|
189 |
+
min = _sympify(min)
|
190 |
+
max = _sympify(max)
|
191 |
+
|
192 |
+
# Only allow real intervals (use symbols with 'is_extended_real=True').
|
193 |
+
if not min.is_extended_real or not max.is_extended_real:
|
194 |
+
raise ValueError("Only real AccumulationBounds are supported")
|
195 |
+
|
196 |
+
if max == min:
|
197 |
+
return max
|
198 |
+
|
199 |
+
# Make sure that the created AccumBounds object will be valid.
|
200 |
+
if max.is_number and min.is_number:
|
201 |
+
bad = max.is_comparable and min.is_comparable and max < min
|
202 |
+
else:
|
203 |
+
bad = (max - min).is_extended_negative
|
204 |
+
if bad:
|
205 |
+
raise ValueError(
|
206 |
+
"Lower limit should be smaller than upper limit")
|
207 |
+
|
208 |
+
return Basic.__new__(cls, min, max)
|
209 |
+
|
210 |
+
# setting the operation priority
|
211 |
+
_op_priority = 11.0
|
212 |
+
|
213 |
+
def _eval_is_real(self):
|
214 |
+
if self.min.is_real and self.max.is_real:
|
215 |
+
return True
|
216 |
+
|
217 |
+
@property
|
218 |
+
def min(self):
|
219 |
+
"""
|
220 |
+
Returns the minimum possible value attained by AccumulationBounds
|
221 |
+
object.
|
222 |
+
|
223 |
+
Examples
|
224 |
+
========
|
225 |
+
|
226 |
+
>>> from sympy import AccumBounds
|
227 |
+
>>> AccumBounds(1, 3).min
|
228 |
+
1
|
229 |
+
|
230 |
+
"""
|
231 |
+
return self.args[0]
|
232 |
+
|
233 |
+
@property
|
234 |
+
def max(self):
|
235 |
+
"""
|
236 |
+
Returns the maximum possible value attained by AccumulationBounds
|
237 |
+
object.
|
238 |
+
|
239 |
+
Examples
|
240 |
+
========
|
241 |
+
|
242 |
+
>>> from sympy import AccumBounds
|
243 |
+
>>> AccumBounds(1, 3).max
|
244 |
+
3
|
245 |
+
|
246 |
+
"""
|
247 |
+
return self.args[1]
|
248 |
+
|
249 |
+
@property
|
250 |
+
def delta(self):
|
251 |
+
"""
|
252 |
+
Returns the difference of maximum possible value attained by
|
253 |
+
AccumulationBounds object and minimum possible value attained
|
254 |
+
by AccumulationBounds object.
|
255 |
+
|
256 |
+
Examples
|
257 |
+
========
|
258 |
+
|
259 |
+
>>> from sympy import AccumBounds
|
260 |
+
>>> AccumBounds(1, 3).delta
|
261 |
+
2
|
262 |
+
|
263 |
+
"""
|
264 |
+
return self.max - self.min
|
265 |
+
|
266 |
+
@property
|
267 |
+
def mid(self):
|
268 |
+
"""
|
269 |
+
Returns the mean of maximum possible value attained by
|
270 |
+
AccumulationBounds object and minimum possible value
|
271 |
+
attained by AccumulationBounds object.
|
272 |
+
|
273 |
+
Examples
|
274 |
+
========
|
275 |
+
|
276 |
+
>>> from sympy import AccumBounds
|
277 |
+
>>> AccumBounds(1, 3).mid
|
278 |
+
2
|
279 |
+
|
280 |
+
"""
|
281 |
+
return (self.min + self.max) / 2
|
282 |
+
|
283 |
+
@_sympifyit('other', NotImplemented)
|
284 |
+
def _eval_power(self, other):
|
285 |
+
return self.__pow__(other)
|
286 |
+
|
287 |
+
@_sympifyit('other', NotImplemented)
|
288 |
+
def __add__(self, other):
|
289 |
+
if isinstance(other, Expr):
|
290 |
+
if isinstance(other, AccumBounds):
|
291 |
+
return AccumBounds(
|
292 |
+
Add(self.min, other.min),
|
293 |
+
Add(self.max, other.max))
|
294 |
+
if other is S.Infinity and self.min is S.NegativeInfinity or \
|
295 |
+
other is S.NegativeInfinity and self.max is S.Infinity:
|
296 |
+
return AccumBounds(-oo, oo)
|
297 |
+
elif other.is_extended_real:
|
298 |
+
if self.min is S.NegativeInfinity and self.max is S.Infinity:
|
299 |
+
return AccumBounds(-oo, oo)
|
300 |
+
elif self.min is S.NegativeInfinity:
|
301 |
+
return AccumBounds(-oo, self.max + other)
|
302 |
+
elif self.max is S.Infinity:
|
303 |
+
return AccumBounds(self.min + other, oo)
|
304 |
+
else:
|
305 |
+
return AccumBounds(Add(self.min, other), Add(self.max, other))
|
306 |
+
return Add(self, other, evaluate=False)
|
307 |
+
return NotImplemented
|
308 |
+
|
309 |
+
__radd__ = __add__
|
310 |
+
|
311 |
+
def __neg__(self):
|
312 |
+
return AccumBounds(-self.max, -self.min)
|
313 |
+
|
314 |
+
@_sympifyit('other', NotImplemented)
|
315 |
+
def __sub__(self, other):
|
316 |
+
if isinstance(other, Expr):
|
317 |
+
if isinstance(other, AccumBounds):
|
318 |
+
return AccumBounds(
|
319 |
+
Add(self.min, -other.max),
|
320 |
+
Add(self.max, -other.min))
|
321 |
+
if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \
|
322 |
+
other is S.Infinity and self.max is S.Infinity:
|
323 |
+
return AccumBounds(-oo, oo)
|
324 |
+
elif other.is_extended_real:
|
325 |
+
if self.min is S.NegativeInfinity and self.max is S.Infinity:
|
326 |
+
return AccumBounds(-oo, oo)
|
327 |
+
elif self.min is S.NegativeInfinity:
|
328 |
+
return AccumBounds(-oo, self.max - other)
|
329 |
+
elif self.max is S.Infinity:
|
330 |
+
return AccumBounds(self.min - other, oo)
|
331 |
+
else:
|
332 |
+
return AccumBounds(
|
333 |
+
Add(self.min, -other),
|
334 |
+
Add(self.max, -other))
|
335 |
+
return Add(self, -other, evaluate=False)
|
336 |
+
return NotImplemented
|
337 |
+
|
338 |
+
@_sympifyit('other', NotImplemented)
|
339 |
+
def __rsub__(self, other):
|
340 |
+
return self.__neg__() + other
|
341 |
+
|
342 |
+
@_sympifyit('other', NotImplemented)
|
343 |
+
def __mul__(self, other):
|
344 |
+
if self.args == (-oo, oo):
|
345 |
+
return self
|
346 |
+
if isinstance(other, Expr):
|
347 |
+
if isinstance(other, AccumBounds):
|
348 |
+
if other.args == (-oo, oo):
|
349 |
+
return other
|
350 |
+
v = set()
|
351 |
+
for a in self.args:
|
352 |
+
vi = other*a
|
353 |
+
for i in vi.args or (vi,):
|
354 |
+
v.add(i)
|
355 |
+
return AccumBounds(Min(*v), Max(*v))
|
356 |
+
if other is S.Infinity:
|
357 |
+
if self.min.is_zero:
|
358 |
+
return AccumBounds(0, oo)
|
359 |
+
if self.max.is_zero:
|
360 |
+
return AccumBounds(-oo, 0)
|
361 |
+
if other is S.NegativeInfinity:
|
362 |
+
if self.min.is_zero:
|
363 |
+
return AccumBounds(-oo, 0)
|
364 |
+
if self.max.is_zero:
|
365 |
+
return AccumBounds(0, oo)
|
366 |
+
if other.is_extended_real:
|
367 |
+
if other.is_zero:
|
368 |
+
if self.max is S.Infinity:
|
369 |
+
return AccumBounds(0, oo)
|
370 |
+
if self.min is S.NegativeInfinity:
|
371 |
+
return AccumBounds(-oo, 0)
|
372 |
+
return S.Zero
|
373 |
+
if other.is_extended_positive:
|
374 |
+
return AccumBounds(
|
375 |
+
Mul(self.min, other),
|
376 |
+
Mul(self.max, other))
|
377 |
+
elif other.is_extended_negative:
|
378 |
+
return AccumBounds(
|
379 |
+
Mul(self.max, other),
|
380 |
+
Mul(self.min, other))
|
381 |
+
if isinstance(other, Order):
|
382 |
+
return other
|
383 |
+
return Mul(self, other, evaluate=False)
|
384 |
+
return NotImplemented
|
385 |
+
|
386 |
+
__rmul__ = __mul__
|
387 |
+
|
388 |
+
@_sympifyit('other', NotImplemented)
|
389 |
+
def __truediv__(self, other):
|
390 |
+
if isinstance(other, Expr):
|
391 |
+
if isinstance(other, AccumBounds):
|
392 |
+
if other.min.is_positive or other.max.is_negative:
|
393 |
+
return self * AccumBounds(1/other.max, 1/other.min)
|
394 |
+
|
395 |
+
if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and
|
396 |
+
other.min.is_extended_nonpositive and other.max.is_extended_nonnegative):
|
397 |
+
if self.min.is_zero and other.min.is_zero:
|
398 |
+
return AccumBounds(0, oo)
|
399 |
+
if self.max.is_zero and other.min.is_zero:
|
400 |
+
return AccumBounds(-oo, 0)
|
401 |
+
return AccumBounds(-oo, oo)
|
402 |
+
|
403 |
+
if self.max.is_extended_negative:
|
404 |
+
if other.min.is_extended_negative:
|
405 |
+
if other.max.is_zero:
|
406 |
+
return AccumBounds(self.max / other.min, oo)
|
407 |
+
if other.max.is_extended_positive:
|
408 |
+
# if we were dealing with intervals we would return
|
409 |
+
# Union(Interval(-oo, self.max/other.max),
|
410 |
+
# Interval(self.max/other.min, oo))
|
411 |
+
return AccumBounds(-oo, oo)
|
412 |
+
|
413 |
+
if other.min.is_zero and other.max.is_extended_positive:
|
414 |
+
return AccumBounds(-oo, self.max / other.max)
|
415 |
+
|
416 |
+
if self.min.is_extended_positive:
|
417 |
+
if other.min.is_extended_negative:
|
418 |
+
if other.max.is_zero:
|
419 |
+
return AccumBounds(-oo, self.min / other.min)
|
420 |
+
if other.max.is_extended_positive:
|
421 |
+
# if we were dealing with intervals we would return
|
422 |
+
# Union(Interval(-oo, self.min/other.min),
|
423 |
+
# Interval(self.min/other.max, oo))
|
424 |
+
return AccumBounds(-oo, oo)
|
425 |
+
|
426 |
+
if other.min.is_zero and other.max.is_extended_positive:
|
427 |
+
return AccumBounds(self.min / other.max, oo)
|
428 |
+
|
429 |
+
elif other.is_extended_real:
|
430 |
+
if other in (S.Infinity, S.NegativeInfinity):
|
431 |
+
if self == AccumBounds(-oo, oo):
|
432 |
+
return AccumBounds(-oo, oo)
|
433 |
+
if self.max is S.Infinity:
|
434 |
+
return AccumBounds(Min(0, other), Max(0, other))
|
435 |
+
if self.min is S.NegativeInfinity:
|
436 |
+
return AccumBounds(Min(0, -other), Max(0, -other))
|
437 |
+
if other.is_extended_positive:
|
438 |
+
return AccumBounds(self.min / other, self.max / other)
|
439 |
+
elif other.is_extended_negative:
|
440 |
+
return AccumBounds(self.max / other, self.min / other)
|
441 |
+
if (1 / other) is S.ComplexInfinity:
|
442 |
+
return Mul(self, 1 / other, evaluate=False)
|
443 |
+
else:
|
444 |
+
return Mul(self, 1 / other)
|
445 |
+
|
446 |
+
return NotImplemented
|
447 |
+
|
448 |
+
@_sympifyit('other', NotImplemented)
|
449 |
+
def __rtruediv__(self, other):
|
450 |
+
if isinstance(other, Expr):
|
451 |
+
if other.is_extended_real:
|
452 |
+
if other.is_zero:
|
453 |
+
return S.Zero
|
454 |
+
if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative):
|
455 |
+
if self.min.is_zero:
|
456 |
+
if other.is_extended_positive:
|
457 |
+
return AccumBounds(Mul(other, 1 / self.max), oo)
|
458 |
+
if other.is_extended_negative:
|
459 |
+
return AccumBounds(-oo, Mul(other, 1 / self.max))
|
460 |
+
if self.max.is_zero:
|
461 |
+
if other.is_extended_positive:
|
462 |
+
return AccumBounds(-oo, Mul(other, 1 / self.min))
|
463 |
+
if other.is_extended_negative:
|
464 |
+
return AccumBounds(Mul(other, 1 / self.min), oo)
|
465 |
+
return AccumBounds(-oo, oo)
|
466 |
+
else:
|
467 |
+
return AccumBounds(Min(other / self.min, other / self.max),
|
468 |
+
Max(other / self.min, other / self.max))
|
469 |
+
return Mul(other, 1 / self, evaluate=False)
|
470 |
+
else:
|
471 |
+
return NotImplemented
|
472 |
+
|
473 |
+
@_sympifyit('other', NotImplemented)
|
474 |
+
def __pow__(self, other):
|
475 |
+
if isinstance(other, Expr):
|
476 |
+
if other is S.Infinity:
|
477 |
+
if self.min.is_extended_nonnegative:
|
478 |
+
if self.max < 1:
|
479 |
+
return S.Zero
|
480 |
+
if self.min > 1:
|
481 |
+
return S.Infinity
|
482 |
+
return AccumBounds(0, oo)
|
483 |
+
elif self.max.is_extended_negative:
|
484 |
+
if self.min > -1:
|
485 |
+
return S.Zero
|
486 |
+
if self.max < -1:
|
487 |
+
return zoo
|
488 |
+
return S.NaN
|
489 |
+
else:
|
490 |
+
if self.min > -1:
|
491 |
+
if self.max < 1:
|
492 |
+
return S.Zero
|
493 |
+
return AccumBounds(0, oo)
|
494 |
+
return AccumBounds(-oo, oo)
|
495 |
+
|
496 |
+
if other is S.NegativeInfinity:
|
497 |
+
return (1/self)**oo
|
498 |
+
|
499 |
+
# generically true
|
500 |
+
if (self.max - self.min).is_nonnegative:
|
501 |
+
# well defined
|
502 |
+
if self.min.is_nonnegative:
|
503 |
+
# no 0 to worry about
|
504 |
+
if other.is_nonnegative:
|
505 |
+
# no infinity to worry about
|
506 |
+
return self.func(self.min**other, self.max**other)
|
507 |
+
|
508 |
+
if other.is_zero:
|
509 |
+
return S.One # x**0 = 1
|
510 |
+
|
511 |
+
if other.is_Integer or other.is_integer:
|
512 |
+
if self.min.is_extended_positive:
|
513 |
+
return AccumBounds(
|
514 |
+
Min(self.min**other, self.max**other),
|
515 |
+
Max(self.min**other, self.max**other))
|
516 |
+
elif self.max.is_extended_negative:
|
517 |
+
return AccumBounds(
|
518 |
+
Min(self.max**other, self.min**other),
|
519 |
+
Max(self.max**other, self.min**other))
|
520 |
+
|
521 |
+
if other % 2 == 0:
|
522 |
+
if other.is_extended_negative:
|
523 |
+
if self.min.is_zero:
|
524 |
+
return AccumBounds(self.max**other, oo)
|
525 |
+
if self.max.is_zero:
|
526 |
+
return AccumBounds(self.min**other, oo)
|
527 |
+
return (1/self)**(-other)
|
528 |
+
return AccumBounds(
|
529 |
+
S.Zero, Max(self.min**other, self.max**other))
|
530 |
+
elif other % 2 == 1:
|
531 |
+
if other.is_extended_negative:
|
532 |
+
if self.min.is_zero:
|
533 |
+
return AccumBounds(self.max**other, oo)
|
534 |
+
if self.max.is_zero:
|
535 |
+
return AccumBounds(-oo, self.min**other)
|
536 |
+
return (1/self)**(-other)
|
537 |
+
return AccumBounds(self.min**other, self.max**other)
|
538 |
+
|
539 |
+
# non-integer exponent
|
540 |
+
# 0**neg or neg**frac yields complex
|
541 |
+
if (other.is_number or other.is_rational) and (
|
542 |
+
self.min.is_extended_nonnegative or (
|
543 |
+
other.is_extended_nonnegative and
|
544 |
+
self.min.is_extended_nonnegative)):
|
545 |
+
num, den = other.as_numer_denom()
|
546 |
+
if num is S.One:
|
547 |
+
return AccumBounds(*[i**(1/den) for i in self.args])
|
548 |
+
|
549 |
+
elif den is not S.One: # e.g. if other is not Float
|
550 |
+
return (self**num)**(1/den) # ok for non-negative base
|
551 |
+
|
552 |
+
if isinstance(other, AccumBounds):
|
553 |
+
if (self.min.is_extended_positive or
|
554 |
+
self.min.is_extended_nonnegative and
|
555 |
+
other.min.is_extended_nonnegative):
|
556 |
+
p = [self**i for i in other.args]
|
557 |
+
if not any(i.is_Pow for i in p):
|
558 |
+
a = [j for i in p for j in i.args or (i,)]
|
559 |
+
try:
|
560 |
+
return self.func(min(a), max(a))
|
561 |
+
except TypeError: # can't sort
|
562 |
+
pass
|
563 |
+
|
564 |
+
return Pow(self, other, evaluate=False)
|
565 |
+
|
566 |
+
return NotImplemented
|
567 |
+
|
568 |
+
@_sympifyit('other', NotImplemented)
|
569 |
+
def __rpow__(self, other):
|
570 |
+
if other.is_real and other.is_extended_nonnegative and (
|
571 |
+
self.max - self.min).is_extended_positive:
|
572 |
+
if other is S.One:
|
573 |
+
return S.One
|
574 |
+
if other.is_extended_positive:
|
575 |
+
a, b = [other**i for i in self.args]
|
576 |
+
if min(a, b) != a:
|
577 |
+
a, b = b, a
|
578 |
+
return self.func(a, b)
|
579 |
+
if other.is_zero:
|
580 |
+
if self.min.is_zero:
|
581 |
+
return self.func(0, 1)
|
582 |
+
if self.min.is_extended_positive:
|
583 |
+
return S.Zero
|
584 |
+
|
585 |
+
return Pow(other, self, evaluate=False)
|
586 |
+
|
587 |
+
def __abs__(self):
|
588 |
+
if self.max.is_extended_negative:
|
589 |
+
return self.__neg__()
|
590 |
+
elif self.min.is_extended_negative:
|
591 |
+
return AccumBounds(S.Zero, Max(abs(self.min), self.max))
|
592 |
+
else:
|
593 |
+
return self
|
594 |
+
|
595 |
+
|
596 |
+
def __contains__(self, other):
|
597 |
+
"""
|
598 |
+
Returns ``True`` if other is contained in self, where other
|
599 |
+
belongs to extended real numbers, ``False`` if not contained,
|
600 |
+
otherwise TypeError is raised.
|
601 |
+
|
602 |
+
Examples
|
603 |
+
========
|
604 |
+
|
605 |
+
>>> from sympy import AccumBounds, oo
|
606 |
+
>>> 1 in AccumBounds(-1, 3)
|
607 |
+
True
|
608 |
+
|
609 |
+
-oo and oo go together as limits (in AccumulationBounds).
|
610 |
+
|
611 |
+
>>> -oo in AccumBounds(1, oo)
|
612 |
+
True
|
613 |
+
|
614 |
+
>>> oo in AccumBounds(-oo, 0)
|
615 |
+
True
|
616 |
+
|
617 |
+
"""
|
618 |
+
other = _sympify(other)
|
619 |
+
|
620 |
+
if other in (S.Infinity, S.NegativeInfinity):
|
621 |
+
if self.min is S.NegativeInfinity or self.max is S.Infinity:
|
622 |
+
return True
|
623 |
+
return False
|
624 |
+
|
625 |
+
rv = And(self.min <= other, self.max >= other)
|
626 |
+
if rv not in (True, False):
|
627 |
+
raise TypeError("input failed to evaluate")
|
628 |
+
return rv
|
629 |
+
|
630 |
+
def intersection(self, other):
|
631 |
+
"""
|
632 |
+
Returns the intersection of 'self' and 'other'.
|
633 |
+
Here other can be an instance of :py:class:`~.FiniteSet` or AccumulationBounds.
|
634 |
+
|
635 |
+
Parameters
|
636 |
+
==========
|
637 |
+
|
638 |
+
other : AccumulationBounds
|
639 |
+
Another AccumulationBounds object with which the intersection
|
640 |
+
has to be computed.
|
641 |
+
|
642 |
+
Returns
|
643 |
+
=======
|
644 |
+
|
645 |
+
AccumulationBounds
|
646 |
+
Intersection of ``self`` and ``other``.
|
647 |
+
|
648 |
+
Examples
|
649 |
+
========
|
650 |
+
|
651 |
+
>>> from sympy import AccumBounds, FiniteSet
|
652 |
+
>>> AccumBounds(1, 3).intersection(AccumBounds(2, 4))
|
653 |
+
AccumBounds(2, 3)
|
654 |
+
|
655 |
+
>>> AccumBounds(1, 3).intersection(AccumBounds(4, 6))
|
656 |
+
EmptySet
|
657 |
+
|
658 |
+
>>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5))
|
659 |
+
{1, 2}
|
660 |
+
|
661 |
+
"""
|
662 |
+
if not isinstance(other, (AccumBounds, FiniteSet)):
|
663 |
+
raise TypeError(
|
664 |
+
"Input must be AccumulationBounds or FiniteSet object")
|
665 |
+
|
666 |
+
if isinstance(other, FiniteSet):
|
667 |
+
fin_set = S.EmptySet
|
668 |
+
for i in other:
|
669 |
+
if i in self:
|
670 |
+
fin_set = fin_set + FiniteSet(i)
|
671 |
+
return fin_set
|
672 |
+
|
673 |
+
if self.max < other.min or self.min > other.max:
|
674 |
+
return S.EmptySet
|
675 |
+
|
676 |
+
if self.min <= other.min:
|
677 |
+
if self.max <= other.max:
|
678 |
+
return AccumBounds(other.min, self.max)
|
679 |
+
if self.max > other.max:
|
680 |
+
return other
|
681 |
+
|
682 |
+
if other.min <= self.min:
|
683 |
+
if other.max < self.max:
|
684 |
+
return AccumBounds(self.min, other.max)
|
685 |
+
if other.max > self.max:
|
686 |
+
return self
|
687 |
+
|
688 |
+
def union(self, other):
|
689 |
+
# TODO : Devise a better method for Union of AccumBounds
|
690 |
+
# this method is not actually correct and
|
691 |
+
# can be made better
|
692 |
+
if not isinstance(other, AccumBounds):
|
693 |
+
raise TypeError(
|
694 |
+
"Input must be AccumulationBounds or FiniteSet object")
|
695 |
+
|
696 |
+
if self.min <= other.min and self.max >= other.min:
|
697 |
+
return AccumBounds(self.min, Max(self.max, other.max))
|
698 |
+
|
699 |
+
if other.min <= self.min and other.max >= self.min:
|
700 |
+
return AccumBounds(other.min, Max(self.max, other.max))
|
701 |
+
|
702 |
+
|
703 |
+
@dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811
|
704 |
+
def _eval_is_le(lhs, rhs): # noqa:F811
|
705 |
+
if is_le(lhs.max, rhs.min):
|
706 |
+
return True
|
707 |
+
if is_gt(lhs.min, rhs.max):
|
708 |
+
return False
|
709 |
+
|
710 |
+
|
711 |
+
@dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811
|
712 |
+
def _eval_is_le(lhs, rhs): # noqa: F811
|
713 |
+
|
714 |
+
"""
|
715 |
+
Returns ``True `` if range of values attained by ``lhs`` AccumulationBounds
|
716 |
+
object is greater than the range of values attained by ``rhs``,
|
717 |
+
where ``rhs`` may be any value of type AccumulationBounds object or
|
718 |
+
extended real number value, ``False`` if ``rhs`` satisfies
|
719 |
+
the same property, else an unevaluated :py:class:`~.Relational`.
|
720 |
+
|
721 |
+
Examples
|
722 |
+
========
|
723 |
+
|
724 |
+
>>> from sympy import AccumBounds, oo
|
725 |
+
>>> AccumBounds(1, 3) > AccumBounds(4, oo)
|
726 |
+
False
|
727 |
+
>>> AccumBounds(1, 4) > AccumBounds(3, 4)
|
728 |
+
AccumBounds(1, 4) > AccumBounds(3, 4)
|
729 |
+
>>> AccumBounds(1, oo) > -1
|
730 |
+
True
|
731 |
+
|
732 |
+
"""
|
733 |
+
if not rhs.is_extended_real:
|
734 |
+
raise TypeError(
|
735 |
+
"Invalid comparison of %s %s" %
|
736 |
+
(type(rhs), rhs))
|
737 |
+
elif rhs.is_comparable:
|
738 |
+
if is_le(lhs.max, rhs):
|
739 |
+
return True
|
740 |
+
if is_gt(lhs.min, rhs):
|
741 |
+
return False
|
742 |
+
|
743 |
+
|
744 |
+
@dispatch(AccumulationBounds, AccumulationBounds)
|
745 |
+
def _eval_is_ge(lhs, rhs): # noqa:F811
|
746 |
+
if is_ge(lhs.min, rhs.max):
|
747 |
+
return True
|
748 |
+
if is_lt(lhs.max, rhs.min):
|
749 |
+
return False
|
750 |
+
|
751 |
+
|
752 |
+
@dispatch(AccumulationBounds, Expr) # type:ignore
|
753 |
+
def _eval_is_ge(lhs, rhs): # noqa: F811
|
754 |
+
"""
|
755 |
+
Returns ``True`` if range of values attained by ``lhs`` AccumulationBounds
|
756 |
+
object is less that the range of values attained by ``rhs``, where
|
757 |
+
other may be any value of type AccumulationBounds object or extended
|
758 |
+
real number value, ``False`` if ``rhs`` satisfies the same
|
759 |
+
property, else an unevaluated :py:class:`~.Relational`.
|
760 |
+
|
761 |
+
Examples
|
762 |
+
========
|
763 |
+
|
764 |
+
>>> from sympy import AccumBounds, oo
|
765 |
+
>>> AccumBounds(1, 3) >= AccumBounds(4, oo)
|
766 |
+
False
|
767 |
+
>>> AccumBounds(1, 4) >= AccumBounds(3, 4)
|
768 |
+
AccumBounds(1, 4) >= AccumBounds(3, 4)
|
769 |
+
>>> AccumBounds(1, oo) >= 1
|
770 |
+
True
|
771 |
+
"""
|
772 |
+
|
773 |
+
if not rhs.is_extended_real:
|
774 |
+
raise TypeError(
|
775 |
+
"Invalid comparison of %s %s" %
|
776 |
+
(type(rhs), rhs))
|
777 |
+
elif rhs.is_comparable:
|
778 |
+
if is_ge(lhs.min, rhs):
|
779 |
+
return True
|
780 |
+
if is_lt(lhs.max, rhs):
|
781 |
+
return False
|
782 |
+
|
783 |
+
|
784 |
+
@dispatch(Expr, AccumulationBounds) # type:ignore
|
785 |
+
def _eval_is_ge(lhs, rhs): # noqa:F811
|
786 |
+
if not lhs.is_extended_real:
|
787 |
+
raise TypeError(
|
788 |
+
"Invalid comparison of %s %s" %
|
789 |
+
(type(lhs), lhs))
|
790 |
+
elif lhs.is_comparable:
|
791 |
+
if is_le(rhs.max, lhs):
|
792 |
+
return True
|
793 |
+
if is_gt(rhs.min, lhs):
|
794 |
+
return False
|
795 |
+
|
796 |
+
|
797 |
+
@dispatch(AccumulationBounds, AccumulationBounds) # type:ignore
|
798 |
+
def _eval_is_ge(lhs, rhs): # noqa:F811
|
799 |
+
if is_ge(lhs.min, rhs.max):
|
800 |
+
return True
|
801 |
+
if is_lt(lhs.max, rhs.min):
|
802 |
+
return False
|
803 |
+
|
804 |
+
# setting an alias for AccumulationBounds
|
805 |
+
AccumBounds = AccumulationBounds
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/euler.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module implements a method to find
|
3 |
+
Euler-Lagrange Equations for given Lagrangian.
|
4 |
+
"""
|
5 |
+
from itertools import combinations_with_replacement
|
6 |
+
from sympy.core.function import (Derivative, Function, diff)
|
7 |
+
from sympy.core.relational import Eq
|
8 |
+
from sympy.core.singleton import S
|
9 |
+
from sympy.core.symbol import Symbol
|
10 |
+
from sympy.core.sympify import sympify
|
11 |
+
from sympy.utilities.iterables import iterable
|
12 |
+
|
13 |
+
|
14 |
+
def euler_equations(L, funcs=(), vars=()):
|
15 |
+
r"""
|
16 |
+
Find the Euler-Lagrange equations [1]_ for a given Lagrangian.
|
17 |
+
|
18 |
+
Parameters
|
19 |
+
==========
|
20 |
+
|
21 |
+
L : Expr
|
22 |
+
The Lagrangian that should be a function of the functions listed
|
23 |
+
in the second argument and their derivatives.
|
24 |
+
|
25 |
+
For example, in the case of two functions $f(x,y)$, $g(x,y)$ and
|
26 |
+
two independent variables $x$, $y$ the Lagrangian has the form:
|
27 |
+
|
28 |
+
.. math:: L\left(f(x,y),g(x,y),\frac{\partial f(x,y)}{\partial x},
|
29 |
+
\frac{\partial f(x,y)}{\partial y},
|
30 |
+
\frac{\partial g(x,y)}{\partial x},
|
31 |
+
\frac{\partial g(x,y)}{\partial y},x,y\right)
|
32 |
+
|
33 |
+
In many cases it is not necessary to provide anything, except the
|
34 |
+
Lagrangian, it will be auto-detected (and an error raised if this
|
35 |
+
cannot be done).
|
36 |
+
|
37 |
+
funcs : Function or an iterable of Functions
|
38 |
+
The functions that the Lagrangian depends on. The Euler equations
|
39 |
+
are differential equations for each of these functions.
|
40 |
+
|
41 |
+
vars : Symbol or an iterable of Symbols
|
42 |
+
The Symbols that are the independent variables of the functions.
|
43 |
+
|
44 |
+
Returns
|
45 |
+
=======
|
46 |
+
|
47 |
+
eqns : list of Eq
|
48 |
+
The list of differential equations, one for each function.
|
49 |
+
|
50 |
+
Examples
|
51 |
+
========
|
52 |
+
|
53 |
+
>>> from sympy import euler_equations, Symbol, Function
|
54 |
+
>>> x = Function('x')
|
55 |
+
>>> t = Symbol('t')
|
56 |
+
>>> L = (x(t).diff(t))**2/2 - x(t)**2/2
|
57 |
+
>>> euler_equations(L, x(t), t)
|
58 |
+
[Eq(-x(t) - Derivative(x(t), (t, 2)), 0)]
|
59 |
+
>>> u = Function('u')
|
60 |
+
>>> x = Symbol('x')
|
61 |
+
>>> L = (u(t, x).diff(t))**2/2 - (u(t, x).diff(x))**2/2
|
62 |
+
>>> euler_equations(L, u(t, x), [t, x])
|
63 |
+
[Eq(-Derivative(u(t, x), (t, 2)) + Derivative(u(t, x), (x, 2)), 0)]
|
64 |
+
|
65 |
+
References
|
66 |
+
==========
|
67 |
+
|
68 |
+
.. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation
|
69 |
+
|
70 |
+
"""
|
71 |
+
|
72 |
+
funcs = tuple(funcs) if iterable(funcs) else (funcs,)
|
73 |
+
|
74 |
+
if not funcs:
|
75 |
+
funcs = tuple(L.atoms(Function))
|
76 |
+
else:
|
77 |
+
for f in funcs:
|
78 |
+
if not isinstance(f, Function):
|
79 |
+
raise TypeError('Function expected, got: %s' % f)
|
80 |
+
|
81 |
+
vars = tuple(vars) if iterable(vars) else (vars,)
|
82 |
+
|
83 |
+
if not vars:
|
84 |
+
vars = funcs[0].args
|
85 |
+
else:
|
86 |
+
vars = tuple(sympify(var) for var in vars)
|
87 |
+
|
88 |
+
if not all(isinstance(v, Symbol) for v in vars):
|
89 |
+
raise TypeError('Variables are not symbols, got %s' % vars)
|
90 |
+
|
91 |
+
for f in funcs:
|
92 |
+
if not vars == f.args:
|
93 |
+
raise ValueError("Variables %s do not match args: %s" % (vars, f))
|
94 |
+
|
95 |
+
order = max([len(d.variables) for d in L.atoms(Derivative)
|
96 |
+
if d.expr in funcs] + [0])
|
97 |
+
|
98 |
+
eqns = []
|
99 |
+
for f in funcs:
|
100 |
+
eq = diff(L, f)
|
101 |
+
for i in range(1, order + 1):
|
102 |
+
for p in combinations_with_replacement(vars, i):
|
103 |
+
eq = eq + S.NegativeOne**i*diff(L, diff(f, *p), *p)
|
104 |
+
new_eq = Eq(eq, 0)
|
105 |
+
if isinstance(new_eq, Eq):
|
106 |
+
eqns.append(new_eq)
|
107 |
+
|
108 |
+
return eqns
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/finite_diff.py
ADDED
@@ -0,0 +1,476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Finite difference weights
|
3 |
+
=========================
|
4 |
+
|
5 |
+
This module implements an algorithm for efficient generation of finite
|
6 |
+
difference weights for ordinary differentials of functions for
|
7 |
+
derivatives from 0 (interpolation) up to arbitrary order.
|
8 |
+
|
9 |
+
The core algorithm is provided in the finite difference weight generating
|
10 |
+
function (``finite_diff_weights``), and two convenience functions are provided
|
11 |
+
for:
|
12 |
+
|
13 |
+
- estimating a derivative (or interpolate) directly from a series of points
|
14 |
+
is also provided (``apply_finite_diff``).
|
15 |
+
- differentiating by using finite difference approximations
|
16 |
+
(``differentiate_finite``).
|
17 |
+
|
18 |
+
"""
|
19 |
+
|
20 |
+
from sympy.core.function import Derivative
|
21 |
+
from sympy.core.singleton import S
|
22 |
+
from sympy.core.function import Subs
|
23 |
+
from sympy.core.traversal import preorder_traversal
|
24 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
25 |
+
from sympy.utilities.iterables import iterable
|
26 |
+
|
27 |
+
|
28 |
+
|
29 |
+
def finite_diff_weights(order, x_list, x0=S.One):
|
30 |
+
"""
|
31 |
+
Calculates the finite difference weights for an arbitrarily spaced
|
32 |
+
one-dimensional grid (``x_list``) for derivatives at ``x0`` of order
|
33 |
+
0, 1, ..., up to ``order`` using a recursive formula. Order of accuracy
|
34 |
+
is at least ``len(x_list) - order``, if ``x_list`` is defined correctly.
|
35 |
+
|
36 |
+
Parameters
|
37 |
+
==========
|
38 |
+
|
39 |
+
order: int
|
40 |
+
Up to what derivative order weights should be calculated.
|
41 |
+
0 corresponds to interpolation.
|
42 |
+
x_list: sequence
|
43 |
+
Sequence of (unique) values for the independent variable.
|
44 |
+
It is useful (but not necessary) to order ``x_list`` from
|
45 |
+
nearest to furthest from ``x0``; see examples below.
|
46 |
+
x0: Number or Symbol
|
47 |
+
Root or value of the independent variable for which the finite
|
48 |
+
difference weights should be generated. Default is ``S.One``.
|
49 |
+
|
50 |
+
Returns
|
51 |
+
=======
|
52 |
+
|
53 |
+
list
|
54 |
+
A list of sublists, each corresponding to coefficients for
|
55 |
+
increasing derivative order, and each containing lists of
|
56 |
+
coefficients for increasing subsets of x_list.
|
57 |
+
|
58 |
+
Examples
|
59 |
+
========
|
60 |
+
|
61 |
+
>>> from sympy import finite_diff_weights, S
|
62 |
+
>>> res = finite_diff_weights(1, [-S(1)/2, S(1)/2, S(3)/2, S(5)/2], 0)
|
63 |
+
>>> res
|
64 |
+
[[[1, 0, 0, 0],
|
65 |
+
[1/2, 1/2, 0, 0],
|
66 |
+
[3/8, 3/4, -1/8, 0],
|
67 |
+
[5/16, 15/16, -5/16, 1/16]],
|
68 |
+
[[0, 0, 0, 0],
|
69 |
+
[-1, 1, 0, 0],
|
70 |
+
[-1, 1, 0, 0],
|
71 |
+
[-23/24, 7/8, 1/8, -1/24]]]
|
72 |
+
>>> res[0][-1] # FD weights for 0th derivative, using full x_list
|
73 |
+
[5/16, 15/16, -5/16, 1/16]
|
74 |
+
>>> res[1][-1] # FD weights for 1st derivative
|
75 |
+
[-23/24, 7/8, 1/8, -1/24]
|
76 |
+
>>> res[1][-2] # FD weights for 1st derivative, using x_list[:-1]
|
77 |
+
[-1, 1, 0, 0]
|
78 |
+
>>> res[1][-1][0] # FD weight for 1st deriv. for x_list[0]
|
79 |
+
-23/24
|
80 |
+
>>> res[1][-1][1] # FD weight for 1st deriv. for x_list[1], etc.
|
81 |
+
7/8
|
82 |
+
|
83 |
+
Each sublist contains the most accurate formula at the end.
|
84 |
+
Note, that in the above example ``res[1][1]`` is the same as ``res[1][2]``.
|
85 |
+
Since res[1][2] has an order of accuracy of
|
86 |
+
``len(x_list[:3]) - order = 3 - 1 = 2``, the same is true for ``res[1][1]``!
|
87 |
+
|
88 |
+
>>> res = finite_diff_weights(1, [S(0), S(1), -S(1), S(2), -S(2)], 0)[1]
|
89 |
+
>>> res
|
90 |
+
[[0, 0, 0, 0, 0],
|
91 |
+
[-1, 1, 0, 0, 0],
|
92 |
+
[0, 1/2, -1/2, 0, 0],
|
93 |
+
[-1/2, 1, -1/3, -1/6, 0],
|
94 |
+
[0, 2/3, -2/3, -1/12, 1/12]]
|
95 |
+
>>> res[0] # no approximation possible, using x_list[0] only
|
96 |
+
[0, 0, 0, 0, 0]
|
97 |
+
>>> res[1] # classic forward step approximation
|
98 |
+
[-1, 1, 0, 0, 0]
|
99 |
+
>>> res[2] # classic centered approximation
|
100 |
+
[0, 1/2, -1/2, 0, 0]
|
101 |
+
>>> res[3:] # higher order approximations
|
102 |
+
[[-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]]
|
103 |
+
|
104 |
+
Let us compare this to a differently defined ``x_list``. Pay attention to
|
105 |
+
``foo[i][k]`` corresponding to the gridpoint defined by ``x_list[k]``.
|
106 |
+
|
107 |
+
>>> foo = finite_diff_weights(1, [-S(2), -S(1), S(0), S(1), S(2)], 0)[1]
|
108 |
+
>>> foo
|
109 |
+
[[0, 0, 0, 0, 0],
|
110 |
+
[-1, 1, 0, 0, 0],
|
111 |
+
[1/2, -2, 3/2, 0, 0],
|
112 |
+
[1/6, -1, 1/2, 1/3, 0],
|
113 |
+
[1/12, -2/3, 0, 2/3, -1/12]]
|
114 |
+
>>> foo[1] # not the same and of lower accuracy as res[1]!
|
115 |
+
[-1, 1, 0, 0, 0]
|
116 |
+
>>> foo[2] # classic double backward step approximation
|
117 |
+
[1/2, -2, 3/2, 0, 0]
|
118 |
+
>>> foo[4] # the same as res[4]
|
119 |
+
[1/12, -2/3, 0, 2/3, -1/12]
|
120 |
+
|
121 |
+
Note that, unless you plan on using approximations based on subsets of
|
122 |
+
``x_list``, the order of gridpoints does not matter.
|
123 |
+
|
124 |
+
The capability to generate weights at arbitrary points can be
|
125 |
+
used e.g. to minimize Runge's phenomenon by using Chebyshev nodes:
|
126 |
+
|
127 |
+
>>> from sympy import cos, symbols, pi, simplify
|
128 |
+
>>> N, (h, x) = 4, symbols('h x')
|
129 |
+
>>> x_list = [x+h*cos(i*pi/(N)) for i in range(N,-1,-1)] # chebyshev nodes
|
130 |
+
>>> print(x_list)
|
131 |
+
[-h + x, -sqrt(2)*h/2 + x, x, sqrt(2)*h/2 + x, h + x]
|
132 |
+
>>> mycoeffs = finite_diff_weights(1, x_list, 0)[1][4]
|
133 |
+
>>> [simplify(c) for c in mycoeffs] #doctest: +NORMALIZE_WHITESPACE
|
134 |
+
[(h**3/2 + h**2*x - 3*h*x**2 - 4*x**3)/h**4,
|
135 |
+
(-sqrt(2)*h**3 - 4*h**2*x + 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
|
136 |
+
(6*h**2*x - 8*x**3)/h**4,
|
137 |
+
(sqrt(2)*h**3 - 4*h**2*x - 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
|
138 |
+
(-h**3/2 + h**2*x + 3*h*x**2 - 4*x**3)/h**4]
|
139 |
+
|
140 |
+
Notes
|
141 |
+
=====
|
142 |
+
|
143 |
+
If weights for a finite difference approximation of 3rd order
|
144 |
+
derivative is wanted, weights for 0th, 1st and 2nd order are
|
145 |
+
calculated "for free", so are formulae using subsets of ``x_list``.
|
146 |
+
This is something one can take advantage of to save computational cost.
|
147 |
+
Be aware that one should define ``x_list`` from nearest to furthest from
|
148 |
+
``x0``. If not, subsets of ``x_list`` will yield poorer approximations,
|
149 |
+
which might not grand an order of accuracy of ``len(x_list) - order``.
|
150 |
+
|
151 |
+
See also
|
152 |
+
========
|
153 |
+
|
154 |
+
sympy.calculus.finite_diff.apply_finite_diff
|
155 |
+
|
156 |
+
References
|
157 |
+
==========
|
158 |
+
|
159 |
+
.. [1] Generation of Finite Difference Formulas on Arbitrarily Spaced
|
160 |
+
Grids, Bengt Fornberg; Mathematics of computation; 51; 184;
|
161 |
+
(1988); 699-706; doi:10.1090/S0025-5718-1988-0935077-0
|
162 |
+
|
163 |
+
"""
|
164 |
+
# The notation below closely corresponds to the one used in the paper.
|
165 |
+
order = S(order)
|
166 |
+
if not order.is_number:
|
167 |
+
raise ValueError("Cannot handle symbolic order.")
|
168 |
+
if order < 0:
|
169 |
+
raise ValueError("Negative derivative order illegal.")
|
170 |
+
if int(order) != order:
|
171 |
+
raise ValueError("Non-integer order illegal")
|
172 |
+
M = order
|
173 |
+
N = len(x_list) - 1
|
174 |
+
delta = [[[0 for nu in range(N+1)] for n in range(N+1)] for
|
175 |
+
m in range(M+1)]
|
176 |
+
delta[0][0][0] = S.One
|
177 |
+
c1 = S.One
|
178 |
+
for n in range(1, N+1):
|
179 |
+
c2 = S.One
|
180 |
+
for nu in range(n):
|
181 |
+
c3 = x_list[n] - x_list[nu]
|
182 |
+
c2 = c2 * c3
|
183 |
+
if n <= M:
|
184 |
+
delta[n][n-1][nu] = 0
|
185 |
+
for m in range(min(n, M)+1):
|
186 |
+
delta[m][n][nu] = (x_list[n]-x0)*delta[m][n-1][nu] -\
|
187 |
+
m*delta[m-1][n-1][nu]
|
188 |
+
delta[m][n][nu] /= c3
|
189 |
+
for m in range(min(n, M)+1):
|
190 |
+
delta[m][n][n] = c1/c2*(m*delta[m-1][n-1][n-1] -
|
191 |
+
(x_list[n-1]-x0)*delta[m][n-1][n-1])
|
192 |
+
c1 = c2
|
193 |
+
return delta
|
194 |
+
|
195 |
+
|
196 |
+
def apply_finite_diff(order, x_list, y_list, x0=S.Zero):
|
197 |
+
"""
|
198 |
+
Calculates the finite difference approximation of
|
199 |
+
the derivative of requested order at ``x0`` from points
|
200 |
+
provided in ``x_list`` and ``y_list``.
|
201 |
+
|
202 |
+
Parameters
|
203 |
+
==========
|
204 |
+
|
205 |
+
order: int
|
206 |
+
order of derivative to approximate. 0 corresponds to interpolation.
|
207 |
+
x_list: sequence
|
208 |
+
Sequence of (unique) values for the independent variable.
|
209 |
+
y_list: sequence
|
210 |
+
The function value at corresponding values for the independent
|
211 |
+
variable in x_list.
|
212 |
+
x0: Number or Symbol
|
213 |
+
At what value of the independent variable the derivative should be
|
214 |
+
evaluated. Defaults to 0.
|
215 |
+
|
216 |
+
Returns
|
217 |
+
=======
|
218 |
+
|
219 |
+
sympy.core.add.Add or sympy.core.numbers.Number
|
220 |
+
The finite difference expression approximating the requested
|
221 |
+
derivative order at ``x0``.
|
222 |
+
|
223 |
+
Examples
|
224 |
+
========
|
225 |
+
|
226 |
+
>>> from sympy import apply_finite_diff
|
227 |
+
>>> cube = lambda arg: (1.0*arg)**3
|
228 |
+
>>> xlist = range(-3,3+1)
|
229 |
+
>>> apply_finite_diff(2, xlist, map(cube, xlist), 2) - 12 # doctest: +SKIP
|
230 |
+
-3.55271367880050e-15
|
231 |
+
|
232 |
+
we see that the example above only contain rounding errors.
|
233 |
+
apply_finite_diff can also be used on more abstract objects:
|
234 |
+
|
235 |
+
>>> from sympy import IndexedBase, Idx
|
236 |
+
>>> x, y = map(IndexedBase, 'xy')
|
237 |
+
>>> i = Idx('i')
|
238 |
+
>>> x_list, y_list = zip(*[(x[i+j], y[i+j]) for j in range(-1,2)])
|
239 |
+
>>> apply_finite_diff(1, x_list, y_list, x[i])
|
240 |
+
((x[i + 1] - x[i])/(-x[i - 1] + x[i]) - 1)*y[i]/(x[i + 1] - x[i]) -
|
241 |
+
(x[i + 1] - x[i])*y[i - 1]/((x[i + 1] - x[i - 1])*(-x[i - 1] + x[i])) +
|
242 |
+
(-x[i - 1] + x[i])*y[i + 1]/((x[i + 1] - x[i - 1])*(x[i + 1] - x[i]))
|
243 |
+
|
244 |
+
Notes
|
245 |
+
=====
|
246 |
+
|
247 |
+
Order = 0 corresponds to interpolation.
|
248 |
+
Only supply so many points you think makes sense
|
249 |
+
to around x0 when extracting the derivative (the function
|
250 |
+
need to be well behaved within that region). Also beware
|
251 |
+
of Runge's phenomenon.
|
252 |
+
|
253 |
+
See also
|
254 |
+
========
|
255 |
+
|
256 |
+
sympy.calculus.finite_diff.finite_diff_weights
|
257 |
+
|
258 |
+
References
|
259 |
+
==========
|
260 |
+
|
261 |
+
Fortran 90 implementation with Python interface for numerics: finitediff_
|
262 |
+
|
263 |
+
.. _finitediff: https://github.com/bjodah/finitediff
|
264 |
+
|
265 |
+
"""
|
266 |
+
|
267 |
+
# In the original paper the following holds for the notation:
|
268 |
+
# M = order
|
269 |
+
# N = len(x_list) - 1
|
270 |
+
|
271 |
+
N = len(x_list) - 1
|
272 |
+
if len(x_list) != len(y_list):
|
273 |
+
raise ValueError("x_list and y_list not equal in length.")
|
274 |
+
|
275 |
+
delta = finite_diff_weights(order, x_list, x0)
|
276 |
+
|
277 |
+
derivative = 0
|
278 |
+
for nu in range(len(x_list)):
|
279 |
+
derivative += delta[order][N][nu]*y_list[nu]
|
280 |
+
return derivative
|
281 |
+
|
282 |
+
|
283 |
+
def _as_finite_diff(derivative, points=1, x0=None, wrt=None):
|
284 |
+
"""
|
285 |
+
Returns an approximation of a derivative of a function in
|
286 |
+
the form of a finite difference formula. The expression is a
|
287 |
+
weighted sum of the function at a number of discrete values of
|
288 |
+
(one of) the independent variable(s).
|
289 |
+
|
290 |
+
Parameters
|
291 |
+
==========
|
292 |
+
|
293 |
+
derivative: a Derivative instance
|
294 |
+
|
295 |
+
points: sequence or coefficient, optional
|
296 |
+
If sequence: discrete values (length >= order+1) of the
|
297 |
+
independent variable used for generating the finite
|
298 |
+
difference weights.
|
299 |
+
If it is a coefficient, it will be used as the step-size
|
300 |
+
for generating an equidistant sequence of length order+1
|
301 |
+
centered around ``x0``. default: 1 (step-size 1)
|
302 |
+
|
303 |
+
x0: number or Symbol, optional
|
304 |
+
the value of the independent variable (``wrt``) at which the
|
305 |
+
derivative is to be approximated. Default: same as ``wrt``.
|
306 |
+
|
307 |
+
wrt: Symbol, optional
|
308 |
+
"with respect to" the variable for which the (partial)
|
309 |
+
derivative is to be approximated for. If not provided it
|
310 |
+
is required that the Derivative is ordinary. Default: ``None``.
|
311 |
+
|
312 |
+
Examples
|
313 |
+
========
|
314 |
+
|
315 |
+
>>> from sympy import symbols, Function, exp, sqrt, Symbol
|
316 |
+
>>> from sympy.calculus.finite_diff import _as_finite_diff
|
317 |
+
>>> x, h = symbols('x h')
|
318 |
+
>>> f = Function('f')
|
319 |
+
>>> _as_finite_diff(f(x).diff(x))
|
320 |
+
-f(x - 1/2) + f(x + 1/2)
|
321 |
+
|
322 |
+
The default step size and number of points are 1 and ``order + 1``
|
323 |
+
respectively. We can change the step size by passing a symbol
|
324 |
+
as a parameter:
|
325 |
+
|
326 |
+
>>> _as_finite_diff(f(x).diff(x), h)
|
327 |
+
-f(-h/2 + x)/h + f(h/2 + x)/h
|
328 |
+
|
329 |
+
We can also specify the discretized values to be used in a sequence:
|
330 |
+
|
331 |
+
>>> _as_finite_diff(f(x).diff(x), [x, x+h, x+2*h])
|
332 |
+
-3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)
|
333 |
+
|
334 |
+
The algorithm is not restricted to use equidistant spacing, nor
|
335 |
+
do we need to make the approximation around ``x0``, but we can get
|
336 |
+
an expression estimating the derivative at an offset:
|
337 |
+
|
338 |
+
>>> e, sq2 = exp(1), sqrt(2)
|
339 |
+
>>> xl = [x-h, x+h, x+e*h]
|
340 |
+
>>> _as_finite_diff(f(x).diff(x, 1), xl, x+h*sq2)
|
341 |
+
2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/((-h + E*h)*(h + E*h)) +
|
342 |
+
(-(-sqrt(2)*h + h)/(2*h) - (-sqrt(2)*h + E*h)/(2*h))*f(-h + x)/(h + E*h) +
|
343 |
+
(-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h + E*h)/(2*h))*f(h + x)/(-h + E*h)
|
344 |
+
|
345 |
+
Partial derivatives are also supported:
|
346 |
+
|
347 |
+
>>> y = Symbol('y')
|
348 |
+
>>> d2fdxdy=f(x,y).diff(x,y)
|
349 |
+
>>> _as_finite_diff(d2fdxdy, wrt=x)
|
350 |
+
-Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)
|
351 |
+
|
352 |
+
See also
|
353 |
+
========
|
354 |
+
|
355 |
+
sympy.calculus.finite_diff.apply_finite_diff
|
356 |
+
sympy.calculus.finite_diff.finite_diff_weights
|
357 |
+
|
358 |
+
"""
|
359 |
+
if derivative.is_Derivative:
|
360 |
+
pass
|
361 |
+
elif derivative.is_Atom:
|
362 |
+
return derivative
|
363 |
+
else:
|
364 |
+
return derivative.fromiter(
|
365 |
+
[_as_finite_diff(ar, points, x0, wrt) for ar
|
366 |
+
in derivative.args], **derivative.assumptions0)
|
367 |
+
|
368 |
+
if wrt is None:
|
369 |
+
old = None
|
370 |
+
for v in derivative.variables:
|
371 |
+
if old is v:
|
372 |
+
continue
|
373 |
+
derivative = _as_finite_diff(derivative, points, x0, v)
|
374 |
+
old = v
|
375 |
+
return derivative
|
376 |
+
|
377 |
+
order = derivative.variables.count(wrt)
|
378 |
+
|
379 |
+
if x0 is None:
|
380 |
+
x0 = wrt
|
381 |
+
|
382 |
+
if not iterable(points):
|
383 |
+
if getattr(points, 'is_Function', False) and wrt in points.args:
|
384 |
+
points = points.subs(wrt, x0)
|
385 |
+
# points is simply the step-size, let's make it a
|
386 |
+
# equidistant sequence centered around x0
|
387 |
+
if order % 2 == 0:
|
388 |
+
# even order => odd number of points, grid point included
|
389 |
+
points = [x0 + points*i for i
|
390 |
+
in range(-order//2, order//2 + 1)]
|
391 |
+
else:
|
392 |
+
# odd order => even number of points, half-way wrt grid point
|
393 |
+
points = [x0 + points*S(i)/2 for i
|
394 |
+
in range(-order, order + 1, 2)]
|
395 |
+
others = [wrt, 0]
|
396 |
+
for v in set(derivative.variables):
|
397 |
+
if v == wrt:
|
398 |
+
continue
|
399 |
+
others += [v, derivative.variables.count(v)]
|
400 |
+
if len(points) < order+1:
|
401 |
+
raise ValueError("Too few points for order %d" % order)
|
402 |
+
return apply_finite_diff(order, points, [
|
403 |
+
Derivative(derivative.expr.subs({wrt: x}), *others) for
|
404 |
+
x in points], x0)
|
405 |
+
|
406 |
+
|
407 |
+
def differentiate_finite(expr, *symbols,
|
408 |
+
points=1, x0=None, wrt=None, evaluate=False):
|
409 |
+
r""" Differentiate expr and replace Derivatives with finite differences.
|
410 |
+
|
411 |
+
Parameters
|
412 |
+
==========
|
413 |
+
|
414 |
+
expr : expression
|
415 |
+
\*symbols : differentiate with respect to symbols
|
416 |
+
points: sequence, coefficient or undefined function, optional
|
417 |
+
see ``Derivative.as_finite_difference``
|
418 |
+
x0: number or Symbol, optional
|
419 |
+
see ``Derivative.as_finite_difference``
|
420 |
+
wrt: Symbol, optional
|
421 |
+
see ``Derivative.as_finite_difference``
|
422 |
+
|
423 |
+
Examples
|
424 |
+
========
|
425 |
+
|
426 |
+
>>> from sympy import sin, Function, differentiate_finite
|
427 |
+
>>> from sympy.abc import x, y, h
|
428 |
+
>>> f, g = Function('f'), Function('g')
|
429 |
+
>>> differentiate_finite(f(x)*g(x), x, points=[x-h, x+h])
|
430 |
+
-f(-h + x)*g(-h + x)/(2*h) + f(h + x)*g(h + x)/(2*h)
|
431 |
+
|
432 |
+
``differentiate_finite`` works on any expression, including the expressions
|
433 |
+
with embedded derivatives:
|
434 |
+
|
435 |
+
>>> differentiate_finite(f(x) + sin(x), x, 2)
|
436 |
+
-2*f(x) + f(x - 1) + f(x + 1) - 2*sin(x) + sin(x - 1) + sin(x + 1)
|
437 |
+
>>> differentiate_finite(f(x, y), x, y)
|
438 |
+
f(x - 1/2, y - 1/2) - f(x - 1/2, y + 1/2) - f(x + 1/2, y - 1/2) + f(x + 1/2, y + 1/2)
|
439 |
+
>>> differentiate_finite(f(x)*g(x).diff(x), x)
|
440 |
+
(-g(x) + g(x + 1))*f(x + 1/2) - (g(x) - g(x - 1))*f(x - 1/2)
|
441 |
+
|
442 |
+
To make finite difference with non-constant discretization step use
|
443 |
+
undefined functions:
|
444 |
+
|
445 |
+
>>> dx = Function('dx')
|
446 |
+
>>> differentiate_finite(f(x)*g(x).diff(x), points=dx(x))
|
447 |
+
-(-g(x - dx(x)/2 - dx(x - dx(x)/2)/2)/dx(x - dx(x)/2) +
|
448 |
+
g(x - dx(x)/2 + dx(x - dx(x)/2)/2)/dx(x - dx(x)/2))*f(x - dx(x)/2)/dx(x) +
|
449 |
+
(-g(x + dx(x)/2 - dx(x + dx(x)/2)/2)/dx(x + dx(x)/2) +
|
450 |
+
g(x + dx(x)/2 + dx(x + dx(x)/2)/2)/dx(x + dx(x)/2))*f(x + dx(x)/2)/dx(x)
|
451 |
+
|
452 |
+
"""
|
453 |
+
if any(term.is_Derivative for term in list(preorder_traversal(expr))):
|
454 |
+
evaluate = False
|
455 |
+
|
456 |
+
Dexpr = expr.diff(*symbols, evaluate=evaluate)
|
457 |
+
if evaluate:
|
458 |
+
sympy_deprecation_warning("""
|
459 |
+
The evaluate flag to differentiate_finite() is deprecated.
|
460 |
+
|
461 |
+
evaluate=True expands the intermediate derivatives before computing
|
462 |
+
differences, but this usually not what you want, as it does not
|
463 |
+
satisfy the product rule.
|
464 |
+
""",
|
465 |
+
deprecated_since_version="1.5",
|
466 |
+
active_deprecations_target="deprecated-differentiate_finite-evaluate",
|
467 |
+
)
|
468 |
+
return Dexpr.replace(
|
469 |
+
lambda arg: arg.is_Derivative,
|
470 |
+
lambda arg: arg.as_finite_difference(points=points, x0=x0, wrt=wrt))
|
471 |
+
else:
|
472 |
+
DFexpr = Dexpr.as_finite_difference(points=points, x0=x0, wrt=wrt)
|
473 |
+
return DFexpr.replace(
|
474 |
+
lambda arg: isinstance(arg, Subs),
|
475 |
+
lambda arg: arg.expr.as_finite_difference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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Singularities
|
3 |
+
=============
|
4 |
+
|
5 |
+
This module implements algorithms for finding singularities for a function
|
6 |
+
and identifying types of functions.
|
7 |
+
|
8 |
+
The differential calculus methods in this module include methods to identify
|
9 |
+
the following function types in the given ``Interval``:
|
10 |
+
- Increasing
|
11 |
+
- Strictly Increasing
|
12 |
+
- Decreasing
|
13 |
+
- Strictly Decreasing
|
14 |
+
- Monotonic
|
15 |
+
|
16 |
+
"""
|
17 |
+
|
18 |
+
from sympy.core.power import Pow
|
19 |
+
from sympy.core.singleton import S
|
20 |
+
from sympy.core.symbol import Symbol
|
21 |
+
from sympy.core.sympify import sympify
|
22 |
+
from sympy.functions.elementary.exponential import log
|
23 |
+
from sympy.functions.elementary.trigonometric import sec, csc, cot, tan, cos
|
24 |
+
from sympy.utilities.misc import filldedent
|
25 |
+
|
26 |
+
|
27 |
+
def singularities(expression, symbol, domain=None):
|
28 |
+
"""
|
29 |
+
Find singularities of a given function.
|
30 |
+
|
31 |
+
Parameters
|
32 |
+
==========
|
33 |
+
|
34 |
+
expression : Expr
|
35 |
+
The target function in which singularities need to be found.
|
36 |
+
symbol : Symbol
|
37 |
+
The symbol over the values of which the singularity in
|
38 |
+
expression in being searched for.
|
39 |
+
|
40 |
+
Returns
|
41 |
+
=======
|
42 |
+
|
43 |
+
Set
|
44 |
+
A set of values for ``symbol`` for which ``expression`` has a
|
45 |
+
singularity. An ``EmptySet`` is returned if ``expression`` has no
|
46 |
+
singularities for any given value of ``Symbol``.
|
47 |
+
|
48 |
+
Raises
|
49 |
+
======
|
50 |
+
|
51 |
+
NotImplementedError
|
52 |
+
Methods for determining the singularities of this function have
|
53 |
+
not been developed.
|
54 |
+
|
55 |
+
Notes
|
56 |
+
=====
|
57 |
+
|
58 |
+
This function does not find non-isolated singularities
|
59 |
+
nor does it find branch points of the expression.
|
60 |
+
|
61 |
+
Currently supported functions are:
|
62 |
+
- univariate continuous (real or complex) functions
|
63 |
+
|
64 |
+
References
|
65 |
+
==========
|
66 |
+
|
67 |
+
.. [1] https://en.wikipedia.org/wiki/Mathematical_singularity
|
68 |
+
|
69 |
+
Examples
|
70 |
+
========
|
71 |
+
|
72 |
+
>>> from sympy import singularities, Symbol, log
|
73 |
+
>>> x = Symbol('x', real=True)
|
74 |
+
>>> y = Symbol('y', real=False)
|
75 |
+
>>> singularities(x**2 + x + 1, x)
|
76 |
+
EmptySet
|
77 |
+
>>> singularities(1/(x + 1), x)
|
78 |
+
{-1}
|
79 |
+
>>> singularities(1/(y**2 + 1), y)
|
80 |
+
{-I, I}
|
81 |
+
>>> singularities(1/(y**3 + 1), y)
|
82 |
+
{-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2}
|
83 |
+
>>> singularities(log(x), x)
|
84 |
+
{0}
|
85 |
+
|
86 |
+
"""
|
87 |
+
from sympy.solvers.solveset import solveset
|
88 |
+
|
89 |
+
if domain is None:
|
90 |
+
domain = S.Reals if symbol.is_real else S.Complexes
|
91 |
+
try:
|
92 |
+
sings = S.EmptySet
|
93 |
+
for i in expression.rewrite([sec, csc, cot, tan], cos).atoms(Pow):
|
94 |
+
if i.exp.is_infinite:
|
95 |
+
raise NotImplementedError
|
96 |
+
if i.exp.is_negative:
|
97 |
+
sings += solveset(i.base, symbol, domain)
|
98 |
+
for i in expression.atoms(log):
|
99 |
+
sings += solveset(i.args[0], symbol, domain)
|
100 |
+
return sings
|
101 |
+
except NotImplementedError:
|
102 |
+
raise NotImplementedError(filldedent('''
|
103 |
+
Methods for determining the singularities
|
104 |
+
of this function have not been developed.'''))
|
105 |
+
|
106 |
+
|
107 |
+
###########################################################################
|
108 |
+
# DIFFERENTIAL CALCULUS METHODS #
|
109 |
+
###########################################################################
|
110 |
+
|
111 |
+
|
112 |
+
def monotonicity_helper(expression, predicate, interval=S.Reals, symbol=None):
|
113 |
+
"""
|
114 |
+
Helper function for functions checking function monotonicity.
|
115 |
+
|
116 |
+
Parameters
|
117 |
+
==========
|
118 |
+
|
119 |
+
expression : Expr
|
120 |
+
The target function which is being checked
|
121 |
+
predicate : function
|
122 |
+
The property being tested for. The function takes in an integer
|
123 |
+
and returns a boolean. The integer input is the derivative and
|
124 |
+
the boolean result should be true if the property is being held,
|
125 |
+
and false otherwise.
|
126 |
+
interval : Set, optional
|
127 |
+
The range of values in which we are testing, defaults to all reals.
|
128 |
+
symbol : Symbol, optional
|
129 |
+
The symbol present in expression which gets varied over the given range.
|
130 |
+
|
131 |
+
It returns a boolean indicating whether the interval in which
|
132 |
+
the function's derivative satisfies given predicate is a superset
|
133 |
+
of the given interval.
|
134 |
+
|
135 |
+
Returns
|
136 |
+
=======
|
137 |
+
|
138 |
+
Boolean
|
139 |
+
True if ``predicate`` is true for all the derivatives when ``symbol``
|
140 |
+
is varied in ``range``, False otherwise.
|
141 |
+
|
142 |
+
"""
|
143 |
+
from sympy.solvers.solveset import solveset
|
144 |
+
|
145 |
+
expression = sympify(expression)
|
146 |
+
free = expression.free_symbols
|
147 |
+
|
148 |
+
if symbol is None:
|
149 |
+
if len(free) > 1:
|
150 |
+
raise NotImplementedError(
|
151 |
+
'The function has not yet been implemented'
|
152 |
+
' for all multivariate expressions.'
|
153 |
+
)
|
154 |
+
|
155 |
+
variable = symbol or (free.pop() if free else Symbol('x'))
|
156 |
+
derivative = expression.diff(variable)
|
157 |
+
predicate_interval = solveset(predicate(derivative), variable, S.Reals)
|
158 |
+
return interval.is_subset(predicate_interval)
|
159 |
+
|
160 |
+
|
161 |
+
def is_increasing(expression, interval=S.Reals, symbol=None):
|
162 |
+
"""
|
163 |
+
Return whether the function is increasing in the given interval.
|
164 |
+
|
165 |
+
Parameters
|
166 |
+
==========
|
167 |
+
|
168 |
+
expression : Expr
|
169 |
+
The target function which is being checked.
|
170 |
+
interval : Set, optional
|
171 |
+
The range of values in which we are testing (defaults to set of
|
172 |
+
all real numbers).
|
173 |
+
symbol : Symbol, optional
|
174 |
+
The symbol present in expression which gets varied over the given range.
|
175 |
+
|
176 |
+
Returns
|
177 |
+
=======
|
178 |
+
|
179 |
+
Boolean
|
180 |
+
True if ``expression`` is increasing (either strictly increasing or
|
181 |
+
constant) in the given ``interval``, False otherwise.
|
182 |
+
|
183 |
+
Examples
|
184 |
+
========
|
185 |
+
|
186 |
+
>>> from sympy import is_increasing
|
187 |
+
>>> from sympy.abc import x, y
|
188 |
+
>>> from sympy import S, Interval, oo
|
189 |
+
>>> is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
|
190 |
+
True
|
191 |
+
>>> is_increasing(-x**2, Interval(-oo, 0))
|
192 |
+
True
|
193 |
+
>>> is_increasing(-x**2, Interval(0, oo))
|
194 |
+
False
|
195 |
+
>>> is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
|
196 |
+
False
|
197 |
+
>>> is_increasing(x**2 + y, Interval(1, 2), x)
|
198 |
+
True
|
199 |
+
|
200 |
+
"""
|
201 |
+
return monotonicity_helper(expression, lambda x: x >= 0, interval, symbol)
|
202 |
+
|
203 |
+
|
204 |
+
def is_strictly_increasing(expression, interval=S.Reals, symbol=None):
|
205 |
+
"""
|
206 |
+
Return whether the function is strictly increasing in the given interval.
|
207 |
+
|
208 |
+
Parameters
|
209 |
+
==========
|
210 |
+
|
211 |
+
expression : Expr
|
212 |
+
The target function which is being checked.
|
213 |
+
interval : Set, optional
|
214 |
+
The range of values in which we are testing (defaults to set of
|
215 |
+
all real numbers).
|
216 |
+
symbol : Symbol, optional
|
217 |
+
The symbol present in expression which gets varied over the given range.
|
218 |
+
|
219 |
+
Returns
|
220 |
+
=======
|
221 |
+
|
222 |
+
Boolean
|
223 |
+
True if ``expression`` is strictly increasing in the given ``interval``,
|
224 |
+
False otherwise.
|
225 |
+
|
226 |
+
Examples
|
227 |
+
========
|
228 |
+
|
229 |
+
>>> from sympy import is_strictly_increasing
|
230 |
+
>>> from sympy.abc import x, y
|
231 |
+
>>> from sympy import Interval, oo
|
232 |
+
>>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
|
233 |
+
True
|
234 |
+
>>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
|
235 |
+
True
|
236 |
+
>>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
|
237 |
+
False
|
238 |
+
>>> is_strictly_increasing(-x**2, Interval(0, oo))
|
239 |
+
False
|
240 |
+
>>> is_strictly_increasing(-x**2 + y, Interval(-oo, 0), x)
|
241 |
+
False
|
242 |
+
|
243 |
+
"""
|
244 |
+
return monotonicity_helper(expression, lambda x: x > 0, interval, symbol)
|
245 |
+
|
246 |
+
|
247 |
+
def is_decreasing(expression, interval=S.Reals, symbol=None):
|
248 |
+
"""
|
249 |
+
Return whether the function is decreasing in the given interval.
|
250 |
+
|
251 |
+
Parameters
|
252 |
+
==========
|
253 |
+
|
254 |
+
expression : Expr
|
255 |
+
The target function which is being checked.
|
256 |
+
interval : Set, optional
|
257 |
+
The range of values in which we are testing (defaults to set of
|
258 |
+
all real numbers).
|
259 |
+
symbol : Symbol, optional
|
260 |
+
The symbol present in expression which gets varied over the given range.
|
261 |
+
|
262 |
+
Returns
|
263 |
+
=======
|
264 |
+
|
265 |
+
Boolean
|
266 |
+
True if ``expression`` is decreasing (either strictly decreasing or
|
267 |
+
constant) in the given ``interval``, False otherwise.
|
268 |
+
|
269 |
+
Examples
|
270 |
+
========
|
271 |
+
|
272 |
+
>>> from sympy import is_decreasing
|
273 |
+
>>> from sympy.abc import x, y
|
274 |
+
>>> from sympy import S, Interval, oo
|
275 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.open(S(3)/2, 3))
|
276 |
+
True
|
277 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
278 |
+
True
|
279 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
280 |
+
True
|
281 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
|
282 |
+
False
|
283 |
+
>>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5))
|
284 |
+
False
|
285 |
+
>>> is_decreasing(-x**2, Interval(-oo, 0))
|
286 |
+
False
|
287 |
+
>>> is_decreasing(-x**2 + y, Interval(-oo, 0), x)
|
288 |
+
False
|
289 |
+
|
290 |
+
"""
|
291 |
+
return monotonicity_helper(expression, lambda x: x <= 0, interval, symbol)
|
292 |
+
|
293 |
+
|
294 |
+
def is_strictly_decreasing(expression, interval=S.Reals, symbol=None):
|
295 |
+
"""
|
296 |
+
Return whether the function is strictly decreasing in the given interval.
|
297 |
+
|
298 |
+
Parameters
|
299 |
+
==========
|
300 |
+
|
301 |
+
expression : Expr
|
302 |
+
The target function which is being checked.
|
303 |
+
interval : Set, optional
|
304 |
+
The range of values in which we are testing (defaults to set of
|
305 |
+
all real numbers).
|
306 |
+
symbol : Symbol, optional
|
307 |
+
The symbol present in expression which gets varied over the given range.
|
308 |
+
|
309 |
+
Returns
|
310 |
+
=======
|
311 |
+
|
312 |
+
Boolean
|
313 |
+
True if ``expression`` is strictly decreasing in the given ``interval``,
|
314 |
+
False otherwise.
|
315 |
+
|
316 |
+
Examples
|
317 |
+
========
|
318 |
+
|
319 |
+
>>> from sympy import is_strictly_decreasing
|
320 |
+
>>> from sympy.abc import x, y
|
321 |
+
>>> from sympy import S, Interval, oo
|
322 |
+
>>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
323 |
+
True
|
324 |
+
>>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
|
325 |
+
False
|
326 |
+
>>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5))
|
327 |
+
False
|
328 |
+
>>> is_strictly_decreasing(-x**2, Interval(-oo, 0))
|
329 |
+
False
|
330 |
+
>>> is_strictly_decreasing(-x**2 + y, Interval(-oo, 0), x)
|
331 |
+
False
|
332 |
+
|
333 |
+
"""
|
334 |
+
return monotonicity_helper(expression, lambda x: x < 0, interval, symbol)
|
335 |
+
|
336 |
+
|
337 |
+
def is_monotonic(expression, interval=S.Reals, symbol=None):
|
338 |
+
"""
|
339 |
+
Return whether the function is monotonic in the given interval.
|
340 |
+
|
341 |
+
Parameters
|
342 |
+
==========
|
343 |
+
|
344 |
+
expression : Expr
|
345 |
+
The target function which is being checked.
|
346 |
+
interval : Set, optional
|
347 |
+
The range of values in which we are testing (defaults to set of
|
348 |
+
all real numbers).
|
349 |
+
symbol : Symbol, optional
|
350 |
+
The symbol present in expression which gets varied over the given range.
|
351 |
+
|
352 |
+
Returns
|
353 |
+
=======
|
354 |
+
|
355 |
+
Boolean
|
356 |
+
True if ``expression`` is monotonic in the given ``interval``,
|
357 |
+
False otherwise.
|
358 |
+
|
359 |
+
Raises
|
360 |
+
======
|
361 |
+
|
362 |
+
NotImplementedError
|
363 |
+
Monotonicity check has not been implemented for the queried function.
|
364 |
+
|
365 |
+
Examples
|
366 |
+
========
|
367 |
+
|
368 |
+
>>> from sympy import is_monotonic
|
369 |
+
>>> from sympy.abc import x, y
|
370 |
+
>>> from sympy import S, Interval, oo
|
371 |
+
>>> is_monotonic(1/(x**2 - 3*x), Interval.open(S(3)/2, 3))
|
372 |
+
True
|
373 |
+
>>> is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
374 |
+
True
|
375 |
+
>>> is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
376 |
+
True
|
377 |
+
>>> is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
|
378 |
+
True
|
379 |
+
>>> is_monotonic(-x**2, S.Reals)
|
380 |
+
False
|
381 |
+
>>> is_monotonic(x**2 + y + 1, Interval(1, 2), x)
|
382 |
+
True
|
383 |
+
|
384 |
+
"""
|
385 |
+
from sympy.solvers.solveset import solveset
|
386 |
+
|
387 |
+
expression = sympify(expression)
|
388 |
+
|
389 |
+
free = expression.free_symbols
|
390 |
+
if symbol is None and len(free) > 1:
|
391 |
+
raise NotImplementedError(
|
392 |
+
'is_monotonic has not yet been implemented'
|
393 |
+
' for all multivariate expressions.'
|
394 |
+
)
|
395 |
+
|
396 |
+
variable = symbol or (free.pop() if free else Symbol('x'))
|
397 |
+
turning_points = solveset(expression.diff(variable), variable, interval)
|
398 |
+
return interval.intersection(turning_points) is S.EmptySet
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py
ADDED
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import (E, Rational, oo, pi, zoo)
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core.symbol import Symbol
|
4 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
5 |
+
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
|
6 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
|
7 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
8 |
+
from sympy.core import Add, Mul, Pow
|
9 |
+
from sympy.core.expr import unchanged
|
10 |
+
from sympy.testing.pytest import raises, XFAIL
|
11 |
+
from sympy.abc import x
|
12 |
+
|
13 |
+
a = Symbol('a', real=True)
|
14 |
+
B = AccumBounds
|
15 |
+
|
16 |
+
|
17 |
+
def test_AccumBounds():
|
18 |
+
assert B(1, 2).args == (1, 2)
|
19 |
+
assert B(1, 2).delta is S.One
|
20 |
+
assert B(1, 2).mid == Rational(3, 2)
|
21 |
+
assert B(1, 3).is_real == True
|
22 |
+
|
23 |
+
assert B(1, 1) is S.One
|
24 |
+
|
25 |
+
assert B(1, 2) + 1 == B(2, 3)
|
26 |
+
assert 1 + B(1, 2) == B(2, 3)
|
27 |
+
assert B(1, 2) + B(2, 3) == B(3, 5)
|
28 |
+
|
29 |
+
assert -B(1, 2) == B(-2, -1)
|
30 |
+
|
31 |
+
assert B(1, 2) - 1 == B(0, 1)
|
32 |
+
assert 1 - B(1, 2) == B(-1, 0)
|
33 |
+
assert B(2, 3) - B(1, 2) == B(0, 2)
|
34 |
+
|
35 |
+
assert x + B(1, 2) == Add(B(1, 2), x)
|
36 |
+
assert a + B(1, 2) == B(1 + a, 2 + a)
|
37 |
+
assert B(1, 2) - x == Add(B(1, 2), -x)
|
38 |
+
|
39 |
+
assert B(-oo, 1) + oo == B(-oo, oo)
|
40 |
+
assert B(1, oo) + oo is oo
|
41 |
+
assert B(1, oo) - oo == B(-oo, oo)
|
42 |
+
assert (-oo - B(-1, oo)) is -oo
|
43 |
+
assert B(-oo, 1) - oo is -oo
|
44 |
+
|
45 |
+
assert B(1, oo) - oo == B(-oo, oo)
|
46 |
+
assert B(-oo, 1) - (-oo) == B(-oo, oo)
|
47 |
+
assert (oo - B(1, oo)) == B(-oo, oo)
|
48 |
+
assert (-oo - B(1, oo)) is -oo
|
49 |
+
|
50 |
+
assert B(1, 2)/2 == B(S.Half, 1)
|
51 |
+
assert 2/B(2, 3) == B(Rational(2, 3), 1)
|
52 |
+
assert 1/B(-1, 1) == B(-oo, oo)
|
53 |
+
|
54 |
+
assert abs(B(1, 2)) == B(1, 2)
|
55 |
+
assert abs(B(-2, -1)) == B(1, 2)
|
56 |
+
assert abs(B(-2, 1)) == B(0, 2)
|
57 |
+
assert abs(B(-1, 2)) == B(0, 2)
|
58 |
+
c = Symbol('c')
|
59 |
+
raises(ValueError, lambda: B(0, c))
|
60 |
+
raises(ValueError, lambda: B(1, -1))
|
61 |
+
r = Symbol('r', real=True)
|
62 |
+
raises(ValueError, lambda: B(r, r - 1))
|
63 |
+
|
64 |
+
|
65 |
+
def test_AccumBounds_mul():
|
66 |
+
assert B(1, 2)*2 == B(2, 4)
|
67 |
+
assert 2*B(1, 2) == B(2, 4)
|
68 |
+
assert B(1, 2)*B(2, 3) == B(2, 6)
|
69 |
+
assert B(0, 2)*B(2, oo) == B(0, oo)
|
70 |
+
l, r = B(-oo, oo), B(-a, a)
|
71 |
+
assert l*r == B(-oo, oo)
|
72 |
+
assert r*l == B(-oo, oo)
|
73 |
+
l, r = B(1, oo), B(-3, -2)
|
74 |
+
assert l*r == B(-oo, -2)
|
75 |
+
assert r*l == B(-oo, -2)
|
76 |
+
assert B(1, 2)*0 == 0
|
77 |
+
assert B(1, oo)*0 == B(0, oo)
|
78 |
+
assert B(-oo, 1)*0 == B(-oo, 0)
|
79 |
+
assert B(-oo, oo)*0 == B(-oo, oo)
|
80 |
+
|
81 |
+
assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False)
|
82 |
+
|
83 |
+
assert B(0, 2)*oo == B(0, oo)
|
84 |
+
assert B(-2, 0)*oo == B(-oo, 0)
|
85 |
+
assert B(0, 2)*(-oo) == B(-oo, 0)
|
86 |
+
assert B(-2, 0)*(-oo) == B(0, oo)
|
87 |
+
assert B(-1, 1)*oo == B(-oo, oo)
|
88 |
+
assert B(-1, 1)*(-oo) == B(-oo, oo)
|
89 |
+
assert B(-oo, oo)*oo == B(-oo, oo)
|
90 |
+
|
91 |
+
|
92 |
+
def test_AccumBounds_div():
|
93 |
+
assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1)
|
94 |
+
assert B(-2, 4)/B(-3, 4) == B(-oo, oo)
|
95 |
+
assert B(-3, -2)/B(-4, 0) == B(S.Half, oo)
|
96 |
+
|
97 |
+
# these two tests can have a better answer
|
98 |
+
# after Union of B is improved
|
99 |
+
assert B(-3, -2)/B(-2, 1) == B(-oo, oo)
|
100 |
+
assert B(2, 3)/B(-2, 2) == B(-oo, oo)
|
101 |
+
|
102 |
+
assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2))
|
103 |
+
assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3))
|
104 |
+
assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo)
|
105 |
+
|
106 |
+
assert B(0, 1)/B(0, 1) == B(0, oo)
|
107 |
+
assert B(-1, 0)/B(0, 1) == B(-oo, 0)
|
108 |
+
assert B(-1, 2)/B(-2, 2) == B(-oo, oo)
|
109 |
+
|
110 |
+
assert 1/B(-1, 2) == B(-oo, oo)
|
111 |
+
assert 1/B(0, 2) == B(S.Half, oo)
|
112 |
+
assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2))
|
113 |
+
assert 1/B(-oo, 0) == B(-oo, 0)
|
114 |
+
assert 1/B(-1, 0) == B(-oo, -1)
|
115 |
+
assert (-2)/B(-oo, 0) == B(0, oo)
|
116 |
+
assert 1/B(-oo, -1) == B(-1, 0)
|
117 |
+
|
118 |
+
assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False)
|
119 |
+
|
120 |
+
assert B(1, 2)/0 == B(1, 2)*zoo
|
121 |
+
assert B(1, oo)/oo == B(0, oo)
|
122 |
+
assert B(1, oo)/(-oo) == B(-oo, 0)
|
123 |
+
assert B(-oo, -1)/oo == B(-oo, 0)
|
124 |
+
assert B(-oo, -1)/(-oo) == B(0, oo)
|
125 |
+
assert B(-oo, oo)/oo == B(-oo, oo)
|
126 |
+
assert B(-oo, oo)/(-oo) == B(-oo, oo)
|
127 |
+
assert B(-1, oo)/oo == B(0, oo)
|
128 |
+
assert B(-1, oo)/(-oo) == B(-oo, 0)
|
129 |
+
assert B(-oo, 1)/oo == B(-oo, 0)
|
130 |
+
assert B(-oo, 1)/(-oo) == B(0, oo)
|
131 |
+
|
132 |
+
|
133 |
+
def test_issue_18795():
|
134 |
+
r = Symbol('r', real=True)
|
135 |
+
a = B(-1,1)
|
136 |
+
c = B(7, oo)
|
137 |
+
b = B(-oo, oo)
|
138 |
+
assert c - tan(r) == B(7-tan(r), oo)
|
139 |
+
assert b + tan(r) == B(-oo, oo)
|
140 |
+
assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1)
|
141 |
+
assert (b + a)/a == B(-oo, oo)
|
142 |
+
|
143 |
+
|
144 |
+
def test_AccumBounds_func():
|
145 |
+
assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4)
|
146 |
+
assert exp(B(0, 1)) == B(1, E)
|
147 |
+
assert exp(B(-oo, oo)) == B(0, oo)
|
148 |
+
assert log(B(3, 6)) == B(log(3), log(6))
|
149 |
+
|
150 |
+
|
151 |
+
@XFAIL
|
152 |
+
def test_AccumBounds_powf():
|
153 |
+
nn = Symbol('nn', nonnegative=True)
|
154 |
+
assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2)
|
155 |
+
i = Symbol('i', integer=True, negative=True)
|
156 |
+
assert B(1, 2)**i == B(2**i, 1)
|
157 |
+
|
158 |
+
|
159 |
+
def test_AccumBounds_pow():
|
160 |
+
assert B(0, 2)**2 == B(0, 4)
|
161 |
+
assert B(-1, 1)**2 == B(0, 1)
|
162 |
+
assert B(1, 2)**2 == B(1, 4)
|
163 |
+
assert B(-1, 2)**3 == B(-1, 8)
|
164 |
+
assert B(-1, 1)**0 == 1
|
165 |
+
|
166 |
+
assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2))
|
167 |
+
assert B(0, 2)**S.Half == B(0, sqrt(2))
|
168 |
+
|
169 |
+
neg = Symbol('neg', negative=True)
|
170 |
+
assert unchanged(Pow, B(neg, 1), S.Half)
|
171 |
+
nn = Symbol('nn', nonnegative=True)
|
172 |
+
assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1))
|
173 |
+
assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn)
|
174 |
+
assert unchanged(Pow, B(nn, nn + 1), x)
|
175 |
+
i = Symbol('i', integer=True)
|
176 |
+
assert B(1, 2)**i == B(Min(1, 2**i), Max(1, 2**i))
|
177 |
+
i = Symbol('i', integer=True, nonnegative=True)
|
178 |
+
assert B(1, 2)**i == B(1, 2**i)
|
179 |
+
assert B(0, 1)**i == B(0**i, 1)
|
180 |
+
|
181 |
+
assert B(1, 5)**(-2) == B(Rational(1, 25), 1)
|
182 |
+
assert B(-1, 3)**(-2) == B(0, oo)
|
183 |
+
assert B(0, 2)**(-3) == B(Rational(1, 8), oo)
|
184 |
+
assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8))
|
185 |
+
assert B(0, 2)**(-2) == B(Rational(1, 4), oo)
|
186 |
+
assert B(-1, 2)**(-3) == B(-oo, oo)
|
187 |
+
assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27))
|
188 |
+
assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4))
|
189 |
+
assert B(0, oo)**S.Half == B(0, oo)
|
190 |
+
assert B(-oo, 0)**(-2) == B(0, oo)
|
191 |
+
assert B(-2, 0)**(-2) == B(Rational(1, 4), oo)
|
192 |
+
|
193 |
+
assert B(Rational(1, 3), S.Half)**oo is S.Zero
|
194 |
+
assert B(0, S.Half)**oo is S.Zero
|
195 |
+
assert B(S.Half, 1)**oo == B(0, oo)
|
196 |
+
assert B(0, 1)**oo == B(0, oo)
|
197 |
+
assert B(2, 3)**oo is oo
|
198 |
+
assert B(1, 2)**oo == B(0, oo)
|
199 |
+
assert B(S.Half, 3)**oo == B(0, oo)
|
200 |
+
assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero
|
201 |
+
assert B(-1, Rational(-1, 2))**oo is S.NaN
|
202 |
+
assert B(-3, -2)**oo is zoo
|
203 |
+
assert B(-2, -1)**oo is S.NaN
|
204 |
+
assert B(-2, Rational(-1, 2))**oo is S.NaN
|
205 |
+
assert B(Rational(-1, 2), S.Half)**oo is S.Zero
|
206 |
+
assert B(Rational(-1, 2), 1)**oo == B(0, oo)
|
207 |
+
assert B(Rational(-2, 3), 2)**oo == B(0, oo)
|
208 |
+
assert B(-1, 1)**oo == B(-oo, oo)
|
209 |
+
assert B(-1, S.Half)**oo == B(-oo, oo)
|
210 |
+
assert B(-1, 2)**oo == B(-oo, oo)
|
211 |
+
assert B(-2, S.Half)**oo == B(-oo, oo)
|
212 |
+
|
213 |
+
assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False)
|
214 |
+
|
215 |
+
assert B(2, 3)**(-oo) is S.Zero
|
216 |
+
assert B(0, 2)**(-oo) == B(0, oo)
|
217 |
+
assert B(-1, 2)**(-oo) == B(-oo, oo)
|
218 |
+
|
219 |
+
assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \
|
220 |
+
Pow(B(-oo, oo), B(0, 1))
|
221 |
+
|
222 |
+
|
223 |
+
def test_AccumBounds_exponent():
|
224 |
+
# base is 0
|
225 |
+
z = 0**B(a, a + S.Half)
|
226 |
+
assert z.subs(a, 0) == B(0, 1)
|
227 |
+
assert z.subs(a, 1) == 0
|
228 |
+
p = z.subs(a, -1)
|
229 |
+
assert p.is_Pow and p.args == (0, B(-1, -S.Half))
|
230 |
+
# base > 0
|
231 |
+
# when base is 1 the type of bounds does not matter
|
232 |
+
assert 1**B(a, a + 1) == 1
|
233 |
+
# otherwise we need to know if 0 is in the bounds
|
234 |
+
assert S.Half**B(-2, 2) == B(S(1)/4, 4)
|
235 |
+
assert 2**B(-2, 2) == B(S(1)/4, 4)
|
236 |
+
|
237 |
+
# +eps may introduce +oo
|
238 |
+
# if there is a negative integer exponent
|
239 |
+
assert B(0, 1)**B(S(1)/2, 1) == B(0, 1)
|
240 |
+
assert B(0, 1)**B(0, 1) == B(0, 1)
|
241 |
+
|
242 |
+
# positive bases have positive bounds
|
243 |
+
assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4)
|
244 |
+
assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9)
|
245 |
+
|
246 |
+
# bounds generating imaginary parts unevaluated
|
247 |
+
assert unchanged(Pow, B(-1, 1), B(1, 2))
|
248 |
+
assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2)
|
249 |
+
assert B(0, 1)**B(1, oo) == B(0, oo)
|
250 |
+
assert B(0, 2)**B(1, oo) == B(0, oo)
|
251 |
+
assert B(0, oo)**B(1, oo) == B(0, oo)
|
252 |
+
assert B(S(1)/2, 1)**B(1, oo) == B(0, oo)
|
253 |
+
assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo)
|
254 |
+
assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo)
|
255 |
+
assert B(S(1)/2, 2)**B(1, oo) == B(0, oo)
|
256 |
+
assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo)
|
257 |
+
assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo)
|
258 |
+
assert B(S(1)/2, oo)**B(1, oo) == B(0, oo)
|
259 |
+
assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo)
|
260 |
+
assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo)
|
261 |
+
assert B(1, 2)**B(1, oo) == B(0, oo)
|
262 |
+
assert B(1, 2)**B(-oo, -1) == B(0, oo)
|
263 |
+
assert B(1, 2)**B(-oo, oo) == B(0, oo)
|
264 |
+
assert B(1, oo)**B(1, oo) == B(0, oo)
|
265 |
+
assert B(1, oo)**B(-oo, -1) == B(0, oo)
|
266 |
+
assert B(1, oo)**B(-oo, oo) == B(0, oo)
|
267 |
+
assert B(2, oo)**B(1, oo) == B(2, oo)
|
268 |
+
assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2)
|
269 |
+
assert B(2, oo)**B(-oo, oo) == B(0, oo)
|
270 |
+
|
271 |
+
|
272 |
+
def test_comparison_AccumBounds():
|
273 |
+
assert (B(1, 3) < 4) == S.true
|
274 |
+
assert (B(1, 3) < -1) == S.false
|
275 |
+
assert (B(1, 3) < 2).rel_op == '<'
|
276 |
+
assert (B(1, 3) <= 2).rel_op == '<='
|
277 |
+
|
278 |
+
assert (B(1, 3) > 4) == S.false
|
279 |
+
assert (B(1, 3) > -1) == S.true
|
280 |
+
assert (B(1, 3) > 2).rel_op == '>'
|
281 |
+
assert (B(1, 3) >= 2).rel_op == '>='
|
282 |
+
|
283 |
+
assert (B(1, 3) < B(4, 6)) == S.true
|
284 |
+
assert (B(1, 3) < B(2, 4)).rel_op == '<'
|
285 |
+
assert (B(1, 3) < B(-2, 0)) == S.false
|
286 |
+
|
287 |
+
assert (B(1, 3) <= B(4, 6)) == S.true
|
288 |
+
assert (B(1, 3) <= B(-2, 0)) == S.false
|
289 |
+
|
290 |
+
assert (B(1, 3) > B(4, 6)) == S.false
|
291 |
+
assert (B(1, 3) > B(-2, 0)) == S.true
|
292 |
+
|
293 |
+
assert (B(1, 3) >= B(4, 6)) == S.false
|
294 |
+
assert (B(1, 3) >= B(-2, 0)) == S.true
|
295 |
+
|
296 |
+
# issue 13499
|
297 |
+
assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0)
|
298 |
+
|
299 |
+
c = Symbol('c')
|
300 |
+
raises(TypeError, lambda: (B(0, 1) < c))
|
301 |
+
raises(TypeError, lambda: (B(0, 1) <= c))
|
302 |
+
raises(TypeError, lambda: (B(0, 1) > c))
|
303 |
+
raises(TypeError, lambda: (B(0, 1) >= c))
|
304 |
+
|
305 |
+
|
306 |
+
def test_contains_AccumBounds():
|
307 |
+
assert (1 in B(1, 2)) == S.true
|
308 |
+
raises(TypeError, lambda: a in B(1, 2))
|
309 |
+
assert 0 in B(-1, 0)
|
310 |
+
raises(TypeError, lambda:
|
311 |
+
(cos(1)**2 + sin(1)**2 - 1) in B(-1, 0))
|
312 |
+
assert (-oo in B(1, oo)) == S.true
|
313 |
+
assert (oo in B(-oo, 0)) == S.true
|
314 |
+
|
315 |
+
# issue 13159
|
316 |
+
assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0
|
317 |
+
import itertools
|
318 |
+
for perm in itertools.permutations([0, B(-1, 1), x]):
|
319 |
+
assert Mul(*perm) == 0
|
320 |
+
|
321 |
+
|
322 |
+
def test_intersection_AccumBounds():
|
323 |
+
assert B(0, 3).intersection(B(1, 2)) == B(1, 2)
|
324 |
+
assert B(0, 3).intersection(B(1, 4)) == B(1, 3)
|
325 |
+
assert B(0, 3).intersection(B(-1, 2)) == B(0, 2)
|
326 |
+
assert B(0, 3).intersection(B(-1, 4)) == B(0, 3)
|
327 |
+
assert B(0, 1).intersection(B(2, 3)) == S.EmptySet
|
328 |
+
raises(TypeError, lambda: B(0, 3).intersection(1))
|
329 |
+
|
330 |
+
|
331 |
+
def test_union_AccumBounds():
|
332 |
+
assert B(0, 3).union(B(1, 2)) == B(0, 3)
|
333 |
+
assert B(0, 3).union(B(1, 4)) == B(0, 4)
|
334 |
+
assert B(0, 3).union(B(-1, 2)) == B(-1, 3)
|
335 |
+
assert B(0, 3).union(B(-1, 4)) == B(-1, 4)
|
336 |
+
raises(TypeError, lambda: B(0, 3).union(1))
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.function import (Derivative as D, Function)
|
2 |
+
from sympy.core.relational import Eq
|
3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
4 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
5 |
+
from sympy.testing.pytest import raises
|
6 |
+
from sympy.calculus.euler import euler_equations as euler
|
7 |
+
|
8 |
+
|
9 |
+
def test_euler_interface():
|
10 |
+
x = Function('x')
|
11 |
+
y = Symbol('y')
|
12 |
+
t = Symbol('t')
|
13 |
+
raises(TypeError, lambda: euler())
|
14 |
+
raises(TypeError, lambda: euler(D(x(t), t)*y(t), [x(t), y]))
|
15 |
+
raises(ValueError, lambda: euler(D(x(t), t)*x(y), [x(t), x(y)]))
|
16 |
+
raises(TypeError, lambda: euler(D(x(t), t)**2, x(0)))
|
17 |
+
raises(TypeError, lambda: euler(D(x(t), t)*y(t), [t]))
|
18 |
+
assert euler(D(x(t), t)**2/2, {x(t)}) == [Eq(-D(x(t), t, t), 0)]
|
19 |
+
assert euler(D(x(t), t)**2/2, x(t), {t}) == [Eq(-D(x(t), t, t), 0)]
|
20 |
+
|
21 |
+
|
22 |
+
def test_euler_pendulum():
|
23 |
+
x = Function('x')
|
24 |
+
t = Symbol('t')
|
25 |
+
L = D(x(t), t)**2/2 + cos(x(t))
|
26 |
+
assert euler(L, x(t), t) == [Eq(-sin(x(t)) - D(x(t), t, t), 0)]
|
27 |
+
|
28 |
+
|
29 |
+
def test_euler_henonheiles():
|
30 |
+
x = Function('x')
|
31 |
+
y = Function('y')
|
32 |
+
t = Symbol('t')
|
33 |
+
L = sum(D(z(t), t)**2/2 - z(t)**2/2 for z in [x, y])
|
34 |
+
L += -x(t)**2*y(t) + y(t)**3/3
|
35 |
+
assert euler(L, [x(t), y(t)], t) == [Eq(-2*x(t)*y(t) - x(t) -
|
36 |
+
D(x(t), t, t), 0),
|
37 |
+
Eq(-x(t)**2 + y(t)**2 -
|
38 |
+
y(t) - D(y(t), t, t), 0)]
|
39 |
+
|
40 |
+
|
41 |
+
def test_euler_sineg():
|
42 |
+
psi = Function('psi')
|
43 |
+
t = Symbol('t')
|
44 |
+
x = Symbol('x')
|
45 |
+
L = D(psi(t, x), t)**2/2 - D(psi(t, x), x)**2/2 + cos(psi(t, x))
|
46 |
+
assert euler(L, psi(t, x), [t, x]) == [Eq(-sin(psi(t, x)) -
|
47 |
+
D(psi(t, x), t, t) +
|
48 |
+
D(psi(t, x), x, x), 0)]
|
49 |
+
|
50 |
+
|
51 |
+
def test_euler_high_order():
|
52 |
+
# an example from hep-th/0309038
|
53 |
+
m = Symbol('m')
|
54 |
+
k = Symbol('k')
|
55 |
+
x = Function('x')
|
56 |
+
y = Function('y')
|
57 |
+
t = Symbol('t')
|
58 |
+
L = (m*D(x(t), t)**2/2 + m*D(y(t), t)**2/2 -
|
59 |
+
k*D(x(t), t)*D(y(t), t, t) + k*D(y(t), t)*D(x(t), t, t))
|
60 |
+
assert euler(L, [x(t), y(t)]) == [Eq(2*k*D(y(t), t, t, t) -
|
61 |
+
m*D(x(t), t, t), 0),
|
62 |
+
Eq(-2*k*D(x(t), t, t, t) -
|
63 |
+
m*D(y(t), t, t), 0)]
|
64 |
+
|
65 |
+
w = Symbol('w')
|
66 |
+
L = D(x(t, w), t, w)**2/2
|
67 |
+
assert euler(L) == [Eq(D(x(t, w), t, t, w, w), 0)]
|
68 |
+
|
69 |
+
def test_issue_18653():
|
70 |
+
x, y, z = symbols("x y z")
|
71 |
+
f, g, h = symbols("f g h", cls=Function, args=(x, y))
|
72 |
+
f, g, h = f(), g(), h()
|
73 |
+
expr2 = f.diff(x)*h.diff(z)
|
74 |
+
assert euler(expr2, (f,), (x, y)) == []
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import (I, Rational, oo)
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core.symbol import Symbol
|
4 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
5 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
6 |
+
from sympy.calculus.singularities import (
|
7 |
+
singularities,
|
8 |
+
is_increasing,
|
9 |
+
is_strictly_increasing,
|
10 |
+
is_decreasing,
|
11 |
+
is_strictly_decreasing,
|
12 |
+
is_monotonic
|
13 |
+
)
|
14 |
+
from sympy.sets import Interval, FiniteSet
|
15 |
+
from sympy.testing.pytest import raises
|
16 |
+
from sympy.abc import x, y
|
17 |
+
|
18 |
+
|
19 |
+
def test_singularities():
|
20 |
+
x = Symbol('x')
|
21 |
+
assert singularities(x**2, x) == S.EmptySet
|
22 |
+
assert singularities(x/(x**2 + 3*x + 2), x) == FiniteSet(-2, -1)
|
23 |
+
assert singularities(1/(x**2 + 1), x) == FiniteSet(I, -I)
|
24 |
+
assert singularities(x/(x**3 + 1), x) == \
|
25 |
+
FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2)
|
26 |
+
assert singularities(1/(y**2 + 2*I*y + 1), y) == \
|
27 |
+
FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I)
|
28 |
+
|
29 |
+
x = Symbol('x', real=True)
|
30 |
+
assert singularities(1/(x**2 + 1), x) == S.EmptySet
|
31 |
+
assert singularities(exp(1/x), x, S.Reals) == FiniteSet(0)
|
32 |
+
assert singularities(exp(1/x), x, Interval(1, 2)) == S.EmptySet
|
33 |
+
assert singularities(log((x - 2)**2), x, Interval(1, 3)) == FiniteSet(2)
|
34 |
+
raises(NotImplementedError, lambda: singularities(x**-oo, x))
|
35 |
+
|
36 |
+
|
37 |
+
def test_is_increasing():
|
38 |
+
"""Test whether is_increasing returns correct value."""
|
39 |
+
a = Symbol('a', negative=True)
|
40 |
+
|
41 |
+
assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
|
42 |
+
assert is_increasing(-x**2, Interval(-oo, 0))
|
43 |
+
assert not is_increasing(-x**2, Interval(0, oo))
|
44 |
+
assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
|
45 |
+
assert is_increasing(x**2 + y, Interval(1, oo), x)
|
46 |
+
assert is_increasing(-x**2*a, Interval(1, oo), x)
|
47 |
+
assert is_increasing(1)
|
48 |
+
|
49 |
+
assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False
|
50 |
+
|
51 |
+
|
52 |
+
def test_is_strictly_increasing():
|
53 |
+
"""Test whether is_strictly_increasing returns correct value."""
|
54 |
+
assert is_strictly_increasing(
|
55 |
+
4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
|
56 |
+
assert is_strictly_increasing(
|
57 |
+
4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
|
58 |
+
assert not is_strictly_increasing(
|
59 |
+
4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
|
60 |
+
assert not is_strictly_increasing(-x**2, Interval(0, oo))
|
61 |
+
assert not is_strictly_decreasing(1)
|
62 |
+
|
63 |
+
assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False
|
64 |
+
|
65 |
+
|
66 |
+
def test_is_decreasing():
|
67 |
+
"""Test whether is_decreasing returns correct value."""
|
68 |
+
b = Symbol('b', positive=True)
|
69 |
+
|
70 |
+
assert is_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
|
71 |
+
assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
72 |
+
assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
73 |
+
assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
|
74 |
+
assert not is_decreasing(-x**2, Interval(-oo, 0))
|
75 |
+
assert not is_decreasing(-x**2*b, Interval(-oo, 0), x)
|
76 |
+
|
77 |
+
|
78 |
+
def test_is_strictly_decreasing():
|
79 |
+
"""Test whether is_strictly_decreasing returns correct value."""
|
80 |
+
assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
81 |
+
assert not is_strictly_decreasing(
|
82 |
+
1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
|
83 |
+
assert not is_strictly_decreasing(-x**2, Interval(-oo, 0))
|
84 |
+
assert not is_strictly_decreasing(1)
|
85 |
+
assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
|
86 |
+
assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
87 |
+
|
88 |
+
|
89 |
+
def test_is_monotonic():
|
90 |
+
"""Test whether is_monotonic returns correct value."""
|
91 |
+
assert is_monotonic(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
|
92 |
+
assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
93 |
+
assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
94 |
+
assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
|
95 |
+
assert not is_monotonic(-x**2, S.Reals)
|
96 |
+
assert is_monotonic(x**2 + y + 1, Interval(1, 2), x)
|
97 |
+
raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1))
|
98 |
+
|
99 |
+
|
100 |
+
def test_issue_23401():
|
101 |
+
x = Symbol('x')
|
102 |
+
expr = (x + 1)/(-1.0e-3*x**2 + 0.1*x + 0.1)
|
103 |
+
assert is_increasing(expr, Interval(1,2), x)
|
llmeval-env/lib/python3.10/site-packages/sympy/calculus/util.py
ADDED
@@ -0,0 +1,841 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401
|
2 |
+
from .singularities import singularities
|
3 |
+
from sympy.core import Pow, S
|
4 |
+
from sympy.core.function import diff, expand_mul
|
5 |
+
from sympy.core.kind import NumberKind
|
6 |
+
from sympy.core.mod import Mod
|
7 |
+
from sympy.core.numbers import equal_valued
|
8 |
+
from sympy.core.relational import Relational
|
9 |
+
from sympy.core.symbol import Symbol, Dummy
|
10 |
+
from sympy.core.sympify import _sympify
|
11 |
+
from sympy.functions.elementary.complexes import Abs, im, re
|
12 |
+
from sympy.functions.elementary.exponential import exp, log
|
13 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
14 |
+
from sympy.functions.elementary.trigonometric import (
|
15 |
+
TrigonometricFunction, sin, cos, csc, sec)
|
16 |
+
from sympy.polys.polytools import degree, lcm_list
|
17 |
+
from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union,
|
18 |
+
Complement)
|
19 |
+
from sympy.sets.fancysets import ImageSet
|
20 |
+
from sympy.utilities import filldedent
|
21 |
+
from sympy.utilities.iterables import iterable
|
22 |
+
|
23 |
+
|
24 |
+
def continuous_domain(f, symbol, domain):
|
25 |
+
"""
|
26 |
+
Returns the intervals in the given domain for which the function
|
27 |
+
is continuous.
|
28 |
+
This method is limited by the ability to determine the various
|
29 |
+
singularities and discontinuities of the given function.
|
30 |
+
|
31 |
+
Parameters
|
32 |
+
==========
|
33 |
+
|
34 |
+
f : :py:class:`~.Expr`
|
35 |
+
The concerned function.
|
36 |
+
symbol : :py:class:`~.Symbol`
|
37 |
+
The variable for which the intervals are to be determined.
|
38 |
+
domain : :py:class:`~.Interval`
|
39 |
+
The domain over which the continuity of the symbol has to be checked.
|
40 |
+
|
41 |
+
Examples
|
42 |
+
========
|
43 |
+
|
44 |
+
>>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt
|
45 |
+
>>> from sympy.calculus.util import continuous_domain
|
46 |
+
>>> x = Symbol('x')
|
47 |
+
>>> continuous_domain(1/x, x, S.Reals)
|
48 |
+
Union(Interval.open(-oo, 0), Interval.open(0, oo))
|
49 |
+
>>> continuous_domain(tan(x), x, Interval(0, pi))
|
50 |
+
Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi))
|
51 |
+
>>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5))
|
52 |
+
Interval(2, 5)
|
53 |
+
>>> continuous_domain(log(2*x - 1), x, S.Reals)
|
54 |
+
Interval.open(1/2, oo)
|
55 |
+
|
56 |
+
Returns
|
57 |
+
=======
|
58 |
+
|
59 |
+
:py:class:`~.Interval`
|
60 |
+
Union of all intervals where the function is continuous.
|
61 |
+
|
62 |
+
Raises
|
63 |
+
======
|
64 |
+
|
65 |
+
NotImplementedError
|
66 |
+
If the method to determine continuity of such a function
|
67 |
+
has not yet been developed.
|
68 |
+
|
69 |
+
"""
|
70 |
+
from sympy.solvers.inequalities import solve_univariate_inequality
|
71 |
+
|
72 |
+
if domain.is_subset(S.Reals):
|
73 |
+
constrained_interval = domain
|
74 |
+
for atom in f.atoms(Pow):
|
75 |
+
den = atom.exp.as_numer_denom()[1]
|
76 |
+
if den.is_even and den.is_nonzero:
|
77 |
+
constraint = solve_univariate_inequality(atom.base >= 0,
|
78 |
+
symbol).as_set()
|
79 |
+
constrained_interval = Intersection(constraint,
|
80 |
+
constrained_interval)
|
81 |
+
|
82 |
+
for atom in f.atoms(log):
|
83 |
+
constraint = solve_univariate_inequality(atom.args[0] > 0,
|
84 |
+
symbol).as_set()
|
85 |
+
constrained_interval = Intersection(constraint,
|
86 |
+
constrained_interval)
|
87 |
+
|
88 |
+
|
89 |
+
return constrained_interval - singularities(f, symbol, domain)
|
90 |
+
|
91 |
+
|
92 |
+
def function_range(f, symbol, domain):
|
93 |
+
"""
|
94 |
+
Finds the range of a function in a given domain.
|
95 |
+
This method is limited by the ability to determine the singularities and
|
96 |
+
determine limits.
|
97 |
+
|
98 |
+
Parameters
|
99 |
+
==========
|
100 |
+
|
101 |
+
f : :py:class:`~.Expr`
|
102 |
+
The concerned function.
|
103 |
+
symbol : :py:class:`~.Symbol`
|
104 |
+
The variable for which the range of function is to be determined.
|
105 |
+
domain : :py:class:`~.Interval`
|
106 |
+
The domain under which the range of the function has to be found.
|
107 |
+
|
108 |
+
Examples
|
109 |
+
========
|
110 |
+
|
111 |
+
>>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan
|
112 |
+
>>> from sympy.calculus.util import function_range
|
113 |
+
>>> x = Symbol('x')
|
114 |
+
>>> function_range(sin(x), x, Interval(0, 2*pi))
|
115 |
+
Interval(-1, 1)
|
116 |
+
>>> function_range(tan(x), x, Interval(-pi/2, pi/2))
|
117 |
+
Interval(-oo, oo)
|
118 |
+
>>> function_range(1/x, x, S.Reals)
|
119 |
+
Union(Interval.open(-oo, 0), Interval.open(0, oo))
|
120 |
+
>>> function_range(exp(x), x, S.Reals)
|
121 |
+
Interval.open(0, oo)
|
122 |
+
>>> function_range(log(x), x, S.Reals)
|
123 |
+
Interval(-oo, oo)
|
124 |
+
>>> function_range(sqrt(x), x, Interval(-5, 9))
|
125 |
+
Interval(0, 3)
|
126 |
+
|
127 |
+
Returns
|
128 |
+
=======
|
129 |
+
|
130 |
+
:py:class:`~.Interval`
|
131 |
+
Union of all ranges for all intervals under domain where function is
|
132 |
+
continuous.
|
133 |
+
|
134 |
+
Raises
|
135 |
+
======
|
136 |
+
|
137 |
+
NotImplementedError
|
138 |
+
If any of the intervals, in the given domain, for which function
|
139 |
+
is continuous are not finite or real,
|
140 |
+
OR if the critical points of the function on the domain cannot be found.
|
141 |
+
"""
|
142 |
+
|
143 |
+
if domain is S.EmptySet:
|
144 |
+
return S.EmptySet
|
145 |
+
|
146 |
+
period = periodicity(f, symbol)
|
147 |
+
if period == S.Zero:
|
148 |
+
# the expression is constant wrt symbol
|
149 |
+
return FiniteSet(f.expand())
|
150 |
+
|
151 |
+
from sympy.series.limits import limit
|
152 |
+
from sympy.solvers.solveset import solveset
|
153 |
+
|
154 |
+
if period is not None:
|
155 |
+
if isinstance(domain, Interval):
|
156 |
+
if (domain.inf - domain.sup).is_infinite:
|
157 |
+
domain = Interval(0, period)
|
158 |
+
elif isinstance(domain, Union):
|
159 |
+
for sub_dom in domain.args:
|
160 |
+
if isinstance(sub_dom, Interval) and \
|
161 |
+
((sub_dom.inf - sub_dom.sup).is_infinite):
|
162 |
+
domain = Interval(0, period)
|
163 |
+
|
164 |
+
intervals = continuous_domain(f, symbol, domain)
|
165 |
+
range_int = S.EmptySet
|
166 |
+
if isinstance(intervals,(Interval, FiniteSet)):
|
167 |
+
interval_iter = (intervals,)
|
168 |
+
|
169 |
+
elif isinstance(intervals, Union):
|
170 |
+
interval_iter = intervals.args
|
171 |
+
|
172 |
+
else:
|
173 |
+
raise NotImplementedError(filldedent('''
|
174 |
+
Unable to find range for the given domain.
|
175 |
+
'''))
|
176 |
+
|
177 |
+
for interval in interval_iter:
|
178 |
+
if isinstance(interval, FiniteSet):
|
179 |
+
for singleton in interval:
|
180 |
+
if singleton in domain:
|
181 |
+
range_int += FiniteSet(f.subs(symbol, singleton))
|
182 |
+
elif isinstance(interval, Interval):
|
183 |
+
vals = S.EmptySet
|
184 |
+
critical_points = S.EmptySet
|
185 |
+
critical_values = S.EmptySet
|
186 |
+
bounds = ((interval.left_open, interval.inf, '+'),
|
187 |
+
(interval.right_open, interval.sup, '-'))
|
188 |
+
|
189 |
+
for is_open, limit_point, direction in bounds:
|
190 |
+
if is_open:
|
191 |
+
critical_values += FiniteSet(limit(f, symbol, limit_point, direction))
|
192 |
+
vals += critical_values
|
193 |
+
|
194 |
+
else:
|
195 |
+
vals += FiniteSet(f.subs(symbol, limit_point))
|
196 |
+
|
197 |
+
solution = solveset(f.diff(symbol), symbol, interval)
|
198 |
+
|
199 |
+
if not iterable(solution):
|
200 |
+
raise NotImplementedError(
|
201 |
+
'Unable to find critical points for {}'.format(f))
|
202 |
+
if isinstance(solution, ImageSet):
|
203 |
+
raise NotImplementedError(
|
204 |
+
'Infinite number of critical points for {}'.format(f))
|
205 |
+
|
206 |
+
critical_points += solution
|
207 |
+
|
208 |
+
for critical_point in critical_points:
|
209 |
+
vals += FiniteSet(f.subs(symbol, critical_point))
|
210 |
+
|
211 |
+
left_open, right_open = False, False
|
212 |
+
|
213 |
+
if critical_values is not S.EmptySet:
|
214 |
+
if critical_values.inf == vals.inf:
|
215 |
+
left_open = True
|
216 |
+
|
217 |
+
if critical_values.sup == vals.sup:
|
218 |
+
right_open = True
|
219 |
+
|
220 |
+
range_int += Interval(vals.inf, vals.sup, left_open, right_open)
|
221 |
+
else:
|
222 |
+
raise NotImplementedError(filldedent('''
|
223 |
+
Unable to find range for the given domain.
|
224 |
+
'''))
|
225 |
+
|
226 |
+
return range_int
|
227 |
+
|
228 |
+
|
229 |
+
def not_empty_in(finset_intersection, *syms):
|
230 |
+
"""
|
231 |
+
Finds the domain of the functions in ``finset_intersection`` in which the
|
232 |
+
``finite_set`` is not-empty.
|
233 |
+
|
234 |
+
Parameters
|
235 |
+
==========
|
236 |
+
|
237 |
+
finset_intersection : Intersection of FiniteSet
|
238 |
+
The unevaluated intersection of FiniteSet containing
|
239 |
+
real-valued functions with Union of Sets
|
240 |
+
syms : Tuple of symbols
|
241 |
+
Symbol for which domain is to be found
|
242 |
+
|
243 |
+
Raises
|
244 |
+
======
|
245 |
+
|
246 |
+
NotImplementedError
|
247 |
+
The algorithms to find the non-emptiness of the given FiniteSet are
|
248 |
+
not yet implemented.
|
249 |
+
ValueError
|
250 |
+
The input is not valid.
|
251 |
+
RuntimeError
|
252 |
+
It is a bug, please report it to the github issue tracker
|
253 |
+
(https://github.com/sympy/sympy/issues).
|
254 |
+
|
255 |
+
Examples
|
256 |
+
========
|
257 |
+
|
258 |
+
>>> from sympy import FiniteSet, Interval, not_empty_in, oo
|
259 |
+
>>> from sympy.abc import x
|
260 |
+
>>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x)
|
261 |
+
Interval(0, 2)
|
262 |
+
>>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x)
|
263 |
+
Union(Interval(1, 2), Interval(-sqrt(2), -1))
|
264 |
+
>>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x)
|
265 |
+
Union(Interval.Lopen(-2, -1), Interval(2, oo))
|
266 |
+
"""
|
267 |
+
|
268 |
+
# TODO: handle piecewise defined functions
|
269 |
+
# TODO: handle transcendental functions
|
270 |
+
# TODO: handle multivariate functions
|
271 |
+
if len(syms) == 0:
|
272 |
+
raise ValueError("One or more symbols must be given in syms.")
|
273 |
+
|
274 |
+
if finset_intersection is S.EmptySet:
|
275 |
+
return S.EmptySet
|
276 |
+
|
277 |
+
if isinstance(finset_intersection, Union):
|
278 |
+
elm_in_sets = finset_intersection.args[0]
|
279 |
+
return Union(not_empty_in(finset_intersection.args[1], *syms),
|
280 |
+
elm_in_sets)
|
281 |
+
|
282 |
+
if isinstance(finset_intersection, FiniteSet):
|
283 |
+
finite_set = finset_intersection
|
284 |
+
_sets = S.Reals
|
285 |
+
else:
|
286 |
+
finite_set = finset_intersection.args[1]
|
287 |
+
_sets = finset_intersection.args[0]
|
288 |
+
|
289 |
+
if not isinstance(finite_set, FiniteSet):
|
290 |
+
raise ValueError('A FiniteSet must be given, not %s: %s' %
|
291 |
+
(type(finite_set), finite_set))
|
292 |
+
|
293 |
+
if len(syms) == 1:
|
294 |
+
symb = syms[0]
|
295 |
+
else:
|
296 |
+
raise NotImplementedError('more than one variables %s not handled' %
|
297 |
+
(syms,))
|
298 |
+
|
299 |
+
def elm_domain(expr, intrvl):
|
300 |
+
""" Finds the domain of an expression in any given interval """
|
301 |
+
from sympy.solvers.solveset import solveset
|
302 |
+
|
303 |
+
_start = intrvl.start
|
304 |
+
_end = intrvl.end
|
305 |
+
_singularities = solveset(expr.as_numer_denom()[1], symb,
|
306 |
+
domain=S.Reals)
|
307 |
+
|
308 |
+
if intrvl.right_open:
|
309 |
+
if _end is S.Infinity:
|
310 |
+
_domain1 = S.Reals
|
311 |
+
else:
|
312 |
+
_domain1 = solveset(expr < _end, symb, domain=S.Reals)
|
313 |
+
else:
|
314 |
+
_domain1 = solveset(expr <= _end, symb, domain=S.Reals)
|
315 |
+
|
316 |
+
if intrvl.left_open:
|
317 |
+
if _start is S.NegativeInfinity:
|
318 |
+
_domain2 = S.Reals
|
319 |
+
else:
|
320 |
+
_domain2 = solveset(expr > _start, symb, domain=S.Reals)
|
321 |
+
else:
|
322 |
+
_domain2 = solveset(expr >= _start, symb, domain=S.Reals)
|
323 |
+
|
324 |
+
# domain in the interval
|
325 |
+
expr_with_sing = Intersection(_domain1, _domain2)
|
326 |
+
expr_domain = Complement(expr_with_sing, _singularities)
|
327 |
+
return expr_domain
|
328 |
+
|
329 |
+
if isinstance(_sets, Interval):
|
330 |
+
return Union(*[elm_domain(element, _sets) for element in finite_set])
|
331 |
+
|
332 |
+
if isinstance(_sets, Union):
|
333 |
+
_domain = S.EmptySet
|
334 |
+
for intrvl in _sets.args:
|
335 |
+
_domain_element = Union(*[elm_domain(element, intrvl)
|
336 |
+
for element in finite_set])
|
337 |
+
_domain = Union(_domain, _domain_element)
|
338 |
+
return _domain
|
339 |
+
|
340 |
+
|
341 |
+
def periodicity(f, symbol, check=False):
|
342 |
+
"""
|
343 |
+
Tests the given function for periodicity in the given symbol.
|
344 |
+
|
345 |
+
Parameters
|
346 |
+
==========
|
347 |
+
|
348 |
+
f : :py:class:`~.Expr`
|
349 |
+
The concerned function.
|
350 |
+
symbol : :py:class:`~.Symbol`
|
351 |
+
The variable for which the period is to be determined.
|
352 |
+
check : bool, optional
|
353 |
+
The flag to verify whether the value being returned is a period or not.
|
354 |
+
|
355 |
+
Returns
|
356 |
+
=======
|
357 |
+
|
358 |
+
period
|
359 |
+
The period of the function is returned.
|
360 |
+
``None`` is returned when the function is aperiodic or has a complex period.
|
361 |
+
The value of $0$ is returned as the period of a constant function.
|
362 |
+
|
363 |
+
Raises
|
364 |
+
======
|
365 |
+
|
366 |
+
NotImplementedError
|
367 |
+
The value of the period computed cannot be verified.
|
368 |
+
|
369 |
+
|
370 |
+
Notes
|
371 |
+
=====
|
372 |
+
|
373 |
+
Currently, we do not support functions with a complex period.
|
374 |
+
The period of functions having complex periodic values such
|
375 |
+
as ``exp``, ``sinh`` is evaluated to ``None``.
|
376 |
+
|
377 |
+
The value returned might not be the "fundamental" period of the given
|
378 |
+
function i.e. it may not be the smallest periodic value of the function.
|
379 |
+
|
380 |
+
The verification of the period through the ``check`` flag is not reliable
|
381 |
+
due to internal simplification of the given expression. Hence, it is set
|
382 |
+
to ``False`` by default.
|
383 |
+
|
384 |
+
Examples
|
385 |
+
========
|
386 |
+
>>> from sympy import periodicity, Symbol, sin, cos, tan, exp
|
387 |
+
>>> x = Symbol('x')
|
388 |
+
>>> f = sin(x) + sin(2*x) + sin(3*x)
|
389 |
+
>>> periodicity(f, x)
|
390 |
+
2*pi
|
391 |
+
>>> periodicity(sin(x)*cos(x), x)
|
392 |
+
pi
|
393 |
+
>>> periodicity(exp(tan(2*x) - 1), x)
|
394 |
+
pi/2
|
395 |
+
>>> periodicity(sin(4*x)**cos(2*x), x)
|
396 |
+
pi
|
397 |
+
>>> periodicity(exp(x), x)
|
398 |
+
"""
|
399 |
+
if symbol.kind is not NumberKind:
|
400 |
+
raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind)
|
401 |
+
temp = Dummy('x', real=True)
|
402 |
+
f = f.subs(symbol, temp)
|
403 |
+
symbol = temp
|
404 |
+
|
405 |
+
def _check(orig_f, period):
|
406 |
+
'''Return the checked period or raise an error.'''
|
407 |
+
new_f = orig_f.subs(symbol, symbol + period)
|
408 |
+
if new_f.equals(orig_f):
|
409 |
+
return period
|
410 |
+
else:
|
411 |
+
raise NotImplementedError(filldedent('''
|
412 |
+
The period of the given function cannot be verified.
|
413 |
+
When `%s` was replaced with `%s + %s` in `%s`, the result
|
414 |
+
was `%s` which was not recognized as being the same as
|
415 |
+
the original function.
|
416 |
+
So either the period was wrong or the two forms were
|
417 |
+
not recognized as being equal.
|
418 |
+
Set check=False to obtain the value.''' %
|
419 |
+
(symbol, symbol, period, orig_f, new_f)))
|
420 |
+
|
421 |
+
orig_f = f
|
422 |
+
period = None
|
423 |
+
|
424 |
+
if isinstance(f, Relational):
|
425 |
+
f = f.lhs - f.rhs
|
426 |
+
|
427 |
+
f = f.simplify()
|
428 |
+
|
429 |
+
if symbol not in f.free_symbols:
|
430 |
+
return S.Zero
|
431 |
+
|
432 |
+
if isinstance(f, TrigonometricFunction):
|
433 |
+
try:
|
434 |
+
period = f.period(symbol)
|
435 |
+
except NotImplementedError:
|
436 |
+
pass
|
437 |
+
|
438 |
+
if isinstance(f, Abs):
|
439 |
+
arg = f.args[0]
|
440 |
+
if isinstance(arg, (sec, csc, cos)):
|
441 |
+
# all but tan and cot might have a
|
442 |
+
# a period that is half as large
|
443 |
+
# so recast as sin
|
444 |
+
arg = sin(arg.args[0])
|
445 |
+
period = periodicity(arg, symbol)
|
446 |
+
if period is not None and isinstance(arg, sin):
|
447 |
+
# the argument of Abs was a trigonometric other than
|
448 |
+
# cot or tan; test to see if the half-period
|
449 |
+
# is valid. Abs(arg) has behaviour equivalent to
|
450 |
+
# orig_f, so use that for test:
|
451 |
+
orig_f = Abs(arg)
|
452 |
+
try:
|
453 |
+
return _check(orig_f, period/2)
|
454 |
+
except NotImplementedError as err:
|
455 |
+
if check:
|
456 |
+
raise NotImplementedError(err)
|
457 |
+
# else let new orig_f and period be
|
458 |
+
# checked below
|
459 |
+
|
460 |
+
if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1):
|
461 |
+
f = Pow(S.Exp1, expand_mul(f.exp))
|
462 |
+
if im(f) != 0:
|
463 |
+
period_real = periodicity(re(f), symbol)
|
464 |
+
period_imag = periodicity(im(f), symbol)
|
465 |
+
if period_real is not None and period_imag is not None:
|
466 |
+
period = lcim([period_real, period_imag])
|
467 |
+
|
468 |
+
if f.is_Pow and f.base != S.Exp1:
|
469 |
+
base, expo = f.args
|
470 |
+
base_has_sym = base.has(symbol)
|
471 |
+
expo_has_sym = expo.has(symbol)
|
472 |
+
|
473 |
+
if base_has_sym and not expo_has_sym:
|
474 |
+
period = periodicity(base, symbol)
|
475 |
+
|
476 |
+
elif expo_has_sym and not base_has_sym:
|
477 |
+
period = periodicity(expo, symbol)
|
478 |
+
|
479 |
+
else:
|
480 |
+
period = _periodicity(f.args, symbol)
|
481 |
+
|
482 |
+
elif f.is_Mul:
|
483 |
+
coeff, g = f.as_independent(symbol, as_Add=False)
|
484 |
+
if isinstance(g, TrigonometricFunction) or not equal_valued(coeff, 1):
|
485 |
+
period = periodicity(g, symbol)
|
486 |
+
else:
|
487 |
+
period = _periodicity(g.args, symbol)
|
488 |
+
|
489 |
+
elif f.is_Add:
|
490 |
+
k, g = f.as_independent(symbol)
|
491 |
+
if k is not S.Zero:
|
492 |
+
return periodicity(g, symbol)
|
493 |
+
|
494 |
+
period = _periodicity(g.args, symbol)
|
495 |
+
|
496 |
+
elif isinstance(f, Mod):
|
497 |
+
a, n = f.args
|
498 |
+
|
499 |
+
if a == symbol:
|
500 |
+
period = n
|
501 |
+
elif isinstance(a, TrigonometricFunction):
|
502 |
+
period = periodicity(a, symbol)
|
503 |
+
#check if 'f' is linear in 'symbol'
|
504 |
+
elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and
|
505 |
+
symbol not in n.free_symbols):
|
506 |
+
period = Abs(n / a.diff(symbol))
|
507 |
+
|
508 |
+
elif isinstance(f, Piecewise):
|
509 |
+
pass # not handling Piecewise yet as the return type is not favorable
|
510 |
+
|
511 |
+
elif period is None:
|
512 |
+
from sympy.solvers.decompogen import compogen, decompogen
|
513 |
+
g_s = decompogen(f, symbol)
|
514 |
+
num_of_gs = len(g_s)
|
515 |
+
if num_of_gs > 1:
|
516 |
+
for index, g in enumerate(reversed(g_s)):
|
517 |
+
start_index = num_of_gs - 1 - index
|
518 |
+
g = compogen(g_s[start_index:], symbol)
|
519 |
+
if g not in (orig_f, f): # Fix for issue 12620
|
520 |
+
period = periodicity(g, symbol)
|
521 |
+
if period is not None:
|
522 |
+
break
|
523 |
+
|
524 |
+
if period is not None:
|
525 |
+
if check:
|
526 |
+
return _check(orig_f, period)
|
527 |
+
return period
|
528 |
+
|
529 |
+
return None
|
530 |
+
|
531 |
+
|
532 |
+
def _periodicity(args, symbol):
|
533 |
+
"""
|
534 |
+
Helper for `periodicity` to find the period of a list of simpler
|
535 |
+
functions.
|
536 |
+
It uses the `lcim` method to find the least common period of
|
537 |
+
all the functions.
|
538 |
+
|
539 |
+
Parameters
|
540 |
+
==========
|
541 |
+
|
542 |
+
args : Tuple of :py:class:`~.Symbol`
|
543 |
+
All the symbols present in a function.
|
544 |
+
|
545 |
+
symbol : :py:class:`~.Symbol`
|
546 |
+
The symbol over which the function is to be evaluated.
|
547 |
+
|
548 |
+
Returns
|
549 |
+
=======
|
550 |
+
|
551 |
+
period
|
552 |
+
The least common period of the function for all the symbols
|
553 |
+
of the function.
|
554 |
+
``None`` if for at least one of the symbols the function is aperiodic.
|
555 |
+
|
556 |
+
"""
|
557 |
+
periods = []
|
558 |
+
for f in args:
|
559 |
+
period = periodicity(f, symbol)
|
560 |
+
if period is None:
|
561 |
+
return None
|
562 |
+
|
563 |
+
if period is not S.Zero:
|
564 |
+
periods.append(period)
|
565 |
+
|
566 |
+
if len(periods) > 1:
|
567 |
+
return lcim(periods)
|
568 |
+
|
569 |
+
if periods:
|
570 |
+
return periods[0]
|
571 |
+
|
572 |
+
|
573 |
+
def lcim(numbers):
|
574 |
+
"""Returns the least common integral multiple of a list of numbers.
|
575 |
+
|
576 |
+
The numbers can be rational or irrational or a mixture of both.
|
577 |
+
`None` is returned for incommensurable numbers.
|
578 |
+
|
579 |
+
Parameters
|
580 |
+
==========
|
581 |
+
|
582 |
+
numbers : list
|
583 |
+
Numbers (rational and/or irrational) for which lcim is to be found.
|
584 |
+
|
585 |
+
Returns
|
586 |
+
=======
|
587 |
+
|
588 |
+
number
|
589 |
+
lcim if it exists, otherwise ``None`` for incommensurable numbers.
|
590 |
+
|
591 |
+
Examples
|
592 |
+
========
|
593 |
+
|
594 |
+
>>> from sympy.calculus.util import lcim
|
595 |
+
>>> from sympy import S, pi
|
596 |
+
>>> lcim([S(1)/2, S(3)/4, S(5)/6])
|
597 |
+
15/2
|
598 |
+
>>> lcim([2*pi, 3*pi, pi, pi/2])
|
599 |
+
6*pi
|
600 |
+
>>> lcim([S(1), 2*pi])
|
601 |
+
"""
|
602 |
+
result = None
|
603 |
+
if all(num.is_irrational for num in numbers):
|
604 |
+
factorized_nums = [num.factor() for num in numbers]
|
605 |
+
factors_num = [num.as_coeff_Mul() for num in factorized_nums]
|
606 |
+
term = factors_num[0][1]
|
607 |
+
if all(factor == term for coeff, factor in factors_num):
|
608 |
+
common_term = term
|
609 |
+
coeffs = [coeff for coeff, factor in factors_num]
|
610 |
+
result = lcm_list(coeffs) * common_term
|
611 |
+
|
612 |
+
elif all(num.is_rational for num in numbers):
|
613 |
+
result = lcm_list(numbers)
|
614 |
+
|
615 |
+
else:
|
616 |
+
pass
|
617 |
+
|
618 |
+
return result
|
619 |
+
|
620 |
+
def is_convex(f, *syms, domain=S.Reals):
|
621 |
+
r"""Determines the convexity of the function passed in the argument.
|
622 |
+
|
623 |
+
Parameters
|
624 |
+
==========
|
625 |
+
|
626 |
+
f : :py:class:`~.Expr`
|
627 |
+
The concerned function.
|
628 |
+
syms : Tuple of :py:class:`~.Symbol`
|
629 |
+
The variables with respect to which the convexity is to be determined.
|
630 |
+
domain : :py:class:`~.Interval`, optional
|
631 |
+
The domain over which the convexity of the function has to be checked.
|
632 |
+
If unspecified, S.Reals will be the default domain.
|
633 |
+
|
634 |
+
Returns
|
635 |
+
=======
|
636 |
+
|
637 |
+
bool
|
638 |
+
The method returns ``True`` if the function is convex otherwise it
|
639 |
+
returns ``False``.
|
640 |
+
|
641 |
+
Raises
|
642 |
+
======
|
643 |
+
|
644 |
+
NotImplementedError
|
645 |
+
The check for the convexity of multivariate functions is not implemented yet.
|
646 |
+
|
647 |
+
Notes
|
648 |
+
=====
|
649 |
+
|
650 |
+
To determine concavity of a function pass `-f` as the concerned function.
|
651 |
+
To determine logarithmic convexity of a function pass `\log(f)` as
|
652 |
+
concerned function.
|
653 |
+
To determine logarithmic concavity of a function pass `-\log(f)` as
|
654 |
+
concerned function.
|
655 |
+
|
656 |
+
Currently, convexity check of multivariate functions is not handled.
|
657 |
+
|
658 |
+
Examples
|
659 |
+
========
|
660 |
+
|
661 |
+
>>> from sympy import is_convex, symbols, exp, oo, Interval
|
662 |
+
>>> x = symbols('x')
|
663 |
+
>>> is_convex(exp(x), x)
|
664 |
+
True
|
665 |
+
>>> is_convex(x**3, x, domain = Interval(-1, oo))
|
666 |
+
False
|
667 |
+
>>> is_convex(1/x**2, x, domain=Interval.open(0, oo))
|
668 |
+
True
|
669 |
+
|
670 |
+
References
|
671 |
+
==========
|
672 |
+
|
673 |
+
.. [1] https://en.wikipedia.org/wiki/Convex_function
|
674 |
+
.. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf
|
675 |
+
.. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function
|
676 |
+
.. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function
|
677 |
+
.. [5] https://en.wikipedia.org/wiki/Concave_function
|
678 |
+
|
679 |
+
"""
|
680 |
+
|
681 |
+
if len(syms) > 1:
|
682 |
+
raise NotImplementedError(
|
683 |
+
"The check for the convexity of multivariate functions is not implemented yet.")
|
684 |
+
|
685 |
+
from sympy.solvers.inequalities import solve_univariate_inequality
|
686 |
+
|
687 |
+
f = _sympify(f)
|
688 |
+
var = syms[0]
|
689 |
+
if any(s in domain for s in singularities(f, var)):
|
690 |
+
return False
|
691 |
+
|
692 |
+
condition = f.diff(var, 2) < 0
|
693 |
+
if solve_univariate_inequality(condition, var, False, domain):
|
694 |
+
return False
|
695 |
+
return True
|
696 |
+
|
697 |
+
|
698 |
+
def stationary_points(f, symbol, domain=S.Reals):
|
699 |
+
"""
|
700 |
+
Returns the stationary points of a function (where derivative of the
|
701 |
+
function is 0) in the given domain.
|
702 |
+
|
703 |
+
Parameters
|
704 |
+
==========
|
705 |
+
|
706 |
+
f : :py:class:`~.Expr`
|
707 |
+
The concerned function.
|
708 |
+
symbol : :py:class:`~.Symbol`
|
709 |
+
The variable for which the stationary points are to be determined.
|
710 |
+
domain : :py:class:`~.Interval`
|
711 |
+
The domain over which the stationary points have to be checked.
|
712 |
+
If unspecified, ``S.Reals`` will be the default domain.
|
713 |
+
|
714 |
+
Returns
|
715 |
+
=======
|
716 |
+
|
717 |
+
Set
|
718 |
+
A set of stationary points for the function. If there are no
|
719 |
+
stationary point, an :py:class:`~.EmptySet` is returned.
|
720 |
+
|
721 |
+
Examples
|
722 |
+
========
|
723 |
+
|
724 |
+
>>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points
|
725 |
+
>>> x = Symbol('x')
|
726 |
+
|
727 |
+
>>> stationary_points(1/x, x, S.Reals)
|
728 |
+
EmptySet
|
729 |
+
|
730 |
+
>>> pprint(stationary_points(sin(x), x), use_unicode=False)
|
731 |
+
pi 3*pi
|
732 |
+
{2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers}
|
733 |
+
2 2
|
734 |
+
|
735 |
+
>>> stationary_points(sin(x),x, Interval(0, 4*pi))
|
736 |
+
{pi/2, 3*pi/2, 5*pi/2, 7*pi/2}
|
737 |
+
|
738 |
+
"""
|
739 |
+
from sympy.solvers.solveset import solveset
|
740 |
+
|
741 |
+
if domain is S.EmptySet:
|
742 |
+
return S.EmptySet
|
743 |
+
|
744 |
+
domain = continuous_domain(f, symbol, domain)
|
745 |
+
set = solveset(diff(f, symbol), symbol, domain)
|
746 |
+
|
747 |
+
return set
|
748 |
+
|
749 |
+
|
750 |
+
def maximum(f, symbol, domain=S.Reals):
|
751 |
+
"""
|
752 |
+
Returns the maximum value of a function in the given domain.
|
753 |
+
|
754 |
+
Parameters
|
755 |
+
==========
|
756 |
+
|
757 |
+
f : :py:class:`~.Expr`
|
758 |
+
The concerned function.
|
759 |
+
symbol : :py:class:`~.Symbol`
|
760 |
+
The variable for maximum value needs to be determined.
|
761 |
+
domain : :py:class:`~.Interval`
|
762 |
+
The domain over which the maximum have to be checked.
|
763 |
+
If unspecified, then the global maximum is returned.
|
764 |
+
|
765 |
+
Returns
|
766 |
+
=======
|
767 |
+
|
768 |
+
number
|
769 |
+
Maximum value of the function in given domain.
|
770 |
+
|
771 |
+
Examples
|
772 |
+
========
|
773 |
+
|
774 |
+
>>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum
|
775 |
+
>>> x = Symbol('x')
|
776 |
+
|
777 |
+
>>> f = -x**2 + 2*x + 5
|
778 |
+
>>> maximum(f, x, S.Reals)
|
779 |
+
6
|
780 |
+
|
781 |
+
>>> maximum(sin(x), x, Interval(-pi, pi/4))
|
782 |
+
sqrt(2)/2
|
783 |
+
|
784 |
+
>>> maximum(sin(x)*cos(x), x)
|
785 |
+
1/2
|
786 |
+
|
787 |
+
"""
|
788 |
+
if isinstance(symbol, Symbol):
|
789 |
+
if domain is S.EmptySet:
|
790 |
+
raise ValueError("Maximum value not defined for empty domain.")
|
791 |
+
|
792 |
+
return function_range(f, symbol, domain).sup
|
793 |
+
else:
|
794 |
+
raise ValueError("%s is not a valid symbol." % symbol)
|
795 |
+
|
796 |
+
|
797 |
+
def minimum(f, symbol, domain=S.Reals):
|
798 |
+
"""
|
799 |
+
Returns the minimum value of a function in the given domain.
|
800 |
+
|
801 |
+
Parameters
|
802 |
+
==========
|
803 |
+
|
804 |
+
f : :py:class:`~.Expr`
|
805 |
+
The concerned function.
|
806 |
+
symbol : :py:class:`~.Symbol`
|
807 |
+
The variable for minimum value needs to be determined.
|
808 |
+
domain : :py:class:`~.Interval`
|
809 |
+
The domain over which the minimum have to be checked.
|
810 |
+
If unspecified, then the global minimum is returned.
|
811 |
+
|
812 |
+
Returns
|
813 |
+
=======
|
814 |
+
|
815 |
+
number
|
816 |
+
Minimum value of the function in the given domain.
|
817 |
+
|
818 |
+
Examples
|
819 |
+
========
|
820 |
+
|
821 |
+
>>> from sympy import Interval, Symbol, S, sin, cos, minimum
|
822 |
+
>>> x = Symbol('x')
|
823 |
+
|
824 |
+
>>> f = x**2 + 2*x + 5
|
825 |
+
>>> minimum(f, x, S.Reals)
|
826 |
+
4
|
827 |
+
|
828 |
+
>>> minimum(sin(x), x, Interval(2, 3))
|
829 |
+
sin(3)
|
830 |
+
|
831 |
+
>>> minimum(sin(x)*cos(x), x)
|
832 |
+
-1/2
|
833 |
+
|
834 |
+
"""
|
835 |
+
if isinstance(symbol, Symbol):
|
836 |
+
if domain is S.EmptySet:
|
837 |
+
raise ValueError("Minimum value not defined for empty domain.")
|
838 |
+
|
839 |
+
return function_range(f, symbol, domain).inf
|
840 |
+
else:
|
841 |
+
raise ValueError("%s is not a valid symbol." % symbol)
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__init__.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
r"""
|
2 |
+
The :py:mod:`~sympy.holonomic` module is intended to deal with holonomic functions along
|
3 |
+
with various operations on them like addition, multiplication, composition,
|
4 |
+
integration and differentiation. The module also implements various kinds of
|
5 |
+
conversions such as converting holonomic functions to a different form and the
|
6 |
+
other way around.
|
7 |
+
"""
|
8 |
+
|
9 |
+
from .holonomic import (DifferentialOperator, HolonomicFunction, DifferentialOperators,
|
10 |
+
from_hyper, from_meijerg, expr_to_holonomic)
|
11 |
+
from .recurrence import RecurrenceOperators, RecurrenceOperator, HolonomicSequence
|
12 |
+
|
13 |
+
__all__ = [
|
14 |
+
'DifferentialOperator', 'HolonomicFunction', 'DifferentialOperators',
|
15 |
+
'from_hyper', 'from_meijerg', 'expr_to_holonomic',
|
16 |
+
|
17 |
+
'RecurrenceOperators', 'RecurrenceOperator', 'HolonomicSequence',
|
18 |
+
]
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (911 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-310.pyc
ADDED
Binary file (69 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-310.pyc
ADDED
Binary file (2.26 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/numerical.cpython-310.pyc
ADDED
Binary file (3.42 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-310.pyc
ADDED
Binary file (9.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/holonomic.py
ADDED
@@ -0,0 +1,2899 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module implements Holonomic Functions and
|
3 |
+
various operations on them.
|
4 |
+
"""
|
5 |
+
|
6 |
+
from sympy.core import Add, Mul, Pow
|
7 |
+
from sympy.core.numbers import (NaN, Infinity, NegativeInfinity, Float, I, pi,
|
8 |
+
equal_valued)
|
9 |
+
from sympy.core.singleton import S
|
10 |
+
from sympy.core.sorting import ordered
|
11 |
+
from sympy.core.symbol import Dummy, Symbol
|
12 |
+
from sympy.core.sympify import sympify
|
13 |
+
from sympy.functions.combinatorial.factorials import binomial, factorial, rf
|
14 |
+
from sympy.functions.elementary.exponential import exp_polar, exp, log
|
15 |
+
from sympy.functions.elementary.hyperbolic import (cosh, sinh)
|
16 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
17 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, sinc)
|
18 |
+
from sympy.functions.special.error_functions import (Ci, Shi, Si, erf, erfc, erfi)
|
19 |
+
from sympy.functions.special.gamma_functions import gamma
|
20 |
+
from sympy.functions.special.hyper import hyper, meijerg
|
21 |
+
from sympy.integrals import meijerint
|
22 |
+
from sympy.matrices import Matrix
|
23 |
+
from sympy.polys.rings import PolyElement
|
24 |
+
from sympy.polys.fields import FracElement
|
25 |
+
from sympy.polys.domains import QQ, RR
|
26 |
+
from sympy.polys.polyclasses import DMF
|
27 |
+
from sympy.polys.polyroots import roots
|
28 |
+
from sympy.polys.polytools import Poly
|
29 |
+
from sympy.polys.matrices import DomainMatrix
|
30 |
+
from sympy.printing import sstr
|
31 |
+
from sympy.series.limits import limit
|
32 |
+
from sympy.series.order import Order
|
33 |
+
from sympy.simplify.hyperexpand import hyperexpand
|
34 |
+
from sympy.simplify.simplify import nsimplify
|
35 |
+
from sympy.solvers.solvers import solve
|
36 |
+
|
37 |
+
from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators
|
38 |
+
from .holonomicerrors import (NotPowerSeriesError, NotHyperSeriesError,
|
39 |
+
SingularityError, NotHolonomicError)
|
40 |
+
|
41 |
+
|
42 |
+
def _find_nonzero_solution(r, homosys):
|
43 |
+
ones = lambda shape: DomainMatrix.ones(shape, r.domain)
|
44 |
+
particular, nullspace = r._solve(homosys)
|
45 |
+
nullity = nullspace.shape[0]
|
46 |
+
nullpart = ones((1, nullity)) * nullspace
|
47 |
+
sol = (particular + nullpart).transpose()
|
48 |
+
return sol
|
49 |
+
|
50 |
+
|
51 |
+
|
52 |
+
def DifferentialOperators(base, generator):
|
53 |
+
r"""
|
54 |
+
This function is used to create annihilators using ``Dx``.
|
55 |
+
|
56 |
+
Explanation
|
57 |
+
===========
|
58 |
+
|
59 |
+
Returns an Algebra of Differential Operators also called Weyl Algebra
|
60 |
+
and the operator for differentiation i.e. the ``Dx`` operator.
|
61 |
+
|
62 |
+
Parameters
|
63 |
+
==========
|
64 |
+
|
65 |
+
base:
|
66 |
+
Base polynomial ring for the algebra.
|
67 |
+
The base polynomial ring is the ring of polynomials in :math:`x` that
|
68 |
+
will appear as coefficients in the operators.
|
69 |
+
generator:
|
70 |
+
Generator of the algebra which can
|
71 |
+
be either a noncommutative ``Symbol`` or a string. e.g. "Dx" or "D".
|
72 |
+
|
73 |
+
Examples
|
74 |
+
========
|
75 |
+
|
76 |
+
>>> from sympy import ZZ
|
77 |
+
>>> from sympy.abc import x
|
78 |
+
>>> from sympy.holonomic.holonomic import DifferentialOperators
|
79 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
80 |
+
>>> R
|
81 |
+
Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x]
|
82 |
+
>>> Dx*x
|
83 |
+
(1) + (x)*Dx
|
84 |
+
"""
|
85 |
+
|
86 |
+
ring = DifferentialOperatorAlgebra(base, generator)
|
87 |
+
return (ring, ring.derivative_operator)
|
88 |
+
|
89 |
+
|
90 |
+
class DifferentialOperatorAlgebra:
|
91 |
+
r"""
|
92 |
+
An Ore Algebra is a set of noncommutative polynomials in the
|
93 |
+
intermediate ``Dx`` and coefficients in a base polynomial ring :math:`A`.
|
94 |
+
It follows the commutation rule:
|
95 |
+
|
96 |
+
.. math ::
|
97 |
+
Dxa = \sigma(a)Dx + \delta(a)
|
98 |
+
|
99 |
+
for :math:`a \subset A`.
|
100 |
+
|
101 |
+
Where :math:`\sigma: A \Rightarrow A` is an endomorphism and :math:`\delta: A \rightarrow A`
|
102 |
+
is a skew-derivation i.e. :math:`\delta(ab) = \delta(a) b + \sigma(a) \delta(b)`.
|
103 |
+
|
104 |
+
If one takes the sigma as identity map and delta as the standard derivation
|
105 |
+
then it becomes the algebra of Differential Operators also called
|
106 |
+
a Weyl Algebra i.e. an algebra whose elements are Differential Operators.
|
107 |
+
|
108 |
+
This class represents a Weyl Algebra and serves as the parent ring for
|
109 |
+
Differential Operators.
|
110 |
+
|
111 |
+
Examples
|
112 |
+
========
|
113 |
+
|
114 |
+
>>> from sympy import ZZ
|
115 |
+
>>> from sympy import symbols
|
116 |
+
>>> from sympy.holonomic.holonomic import DifferentialOperators
|
117 |
+
>>> x = symbols('x')
|
118 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
119 |
+
>>> R
|
120 |
+
Univariate Differential Operator Algebra in intermediate Dx over the base ring
|
121 |
+
ZZ[x]
|
122 |
+
|
123 |
+
See Also
|
124 |
+
========
|
125 |
+
|
126 |
+
DifferentialOperator
|
127 |
+
"""
|
128 |
+
|
129 |
+
def __init__(self, base, generator):
|
130 |
+
# the base polynomial ring for the algebra
|
131 |
+
self.base = base
|
132 |
+
# the operator representing differentiation i.e. `Dx`
|
133 |
+
self.derivative_operator = DifferentialOperator(
|
134 |
+
[base.zero, base.one], self)
|
135 |
+
|
136 |
+
if generator is None:
|
137 |
+
self.gen_symbol = Symbol('Dx', commutative=False)
|
138 |
+
else:
|
139 |
+
if isinstance(generator, str):
|
140 |
+
self.gen_symbol = Symbol(generator, commutative=False)
|
141 |
+
elif isinstance(generator, Symbol):
|
142 |
+
self.gen_symbol = generator
|
143 |
+
|
144 |
+
def __str__(self):
|
145 |
+
string = 'Univariate Differential Operator Algebra in intermediate '\
|
146 |
+
+ sstr(self.gen_symbol) + ' over the base ring ' + \
|
147 |
+
(self.base).__str__()
|
148 |
+
|
149 |
+
return string
|
150 |
+
|
151 |
+
__repr__ = __str__
|
152 |
+
|
153 |
+
def __eq__(self, other):
|
154 |
+
if self.base == other.base and self.gen_symbol == other.gen_symbol:
|
155 |
+
return True
|
156 |
+
else:
|
157 |
+
return False
|
158 |
+
|
159 |
+
|
160 |
+
class DifferentialOperator:
|
161 |
+
"""
|
162 |
+
Differential Operators are elements of Weyl Algebra. The Operators
|
163 |
+
are defined by a list of polynomials in the base ring and the
|
164 |
+
parent ring of the Operator i.e. the algebra it belongs to.
|
165 |
+
|
166 |
+
Explanation
|
167 |
+
===========
|
168 |
+
|
169 |
+
Takes a list of polynomials for each power of ``Dx`` and the
|
170 |
+
parent ring which must be an instance of DifferentialOperatorAlgebra.
|
171 |
+
|
172 |
+
A Differential Operator can be created easily using
|
173 |
+
the operator ``Dx``. See examples below.
|
174 |
+
|
175 |
+
Examples
|
176 |
+
========
|
177 |
+
|
178 |
+
>>> from sympy.holonomic.holonomic import DifferentialOperator, DifferentialOperators
|
179 |
+
>>> from sympy import ZZ
|
180 |
+
>>> from sympy import symbols
|
181 |
+
>>> x = symbols('x')
|
182 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
|
183 |
+
|
184 |
+
>>> DifferentialOperator([0, 1, x**2], R)
|
185 |
+
(1)*Dx + (x**2)*Dx**2
|
186 |
+
|
187 |
+
>>> (x*Dx*x + 1 - Dx**2)**2
|
188 |
+
(2*x**2 + 2*x + 1) + (4*x**3 + 2*x**2 - 4)*Dx + (x**4 - 6*x - 2)*Dx**2 + (-2*x**2)*Dx**3 + (1)*Dx**4
|
189 |
+
|
190 |
+
See Also
|
191 |
+
========
|
192 |
+
|
193 |
+
DifferentialOperatorAlgebra
|
194 |
+
"""
|
195 |
+
|
196 |
+
_op_priority = 20
|
197 |
+
|
198 |
+
def __init__(self, list_of_poly, parent):
|
199 |
+
"""
|
200 |
+
Parameters
|
201 |
+
==========
|
202 |
+
|
203 |
+
list_of_poly:
|
204 |
+
List of polynomials belonging to the base ring of the algebra.
|
205 |
+
parent:
|
206 |
+
Parent algebra of the operator.
|
207 |
+
"""
|
208 |
+
|
209 |
+
# the parent ring for this operator
|
210 |
+
# must be an DifferentialOperatorAlgebra object
|
211 |
+
self.parent = parent
|
212 |
+
base = self.parent.base
|
213 |
+
self.x = base.gens[0] if isinstance(base.gens[0], Symbol) else base.gens[0][0]
|
214 |
+
# sequence of polynomials in x for each power of Dx
|
215 |
+
# the list should not have trailing zeroes
|
216 |
+
# represents the operator
|
217 |
+
# convert the expressions into ring elements using from_sympy
|
218 |
+
for i, j in enumerate(list_of_poly):
|
219 |
+
if not isinstance(j, base.dtype):
|
220 |
+
list_of_poly[i] = base.from_sympy(sympify(j))
|
221 |
+
else:
|
222 |
+
list_of_poly[i] = base.from_sympy(base.to_sympy(j))
|
223 |
+
|
224 |
+
self.listofpoly = list_of_poly
|
225 |
+
# highest power of `Dx`
|
226 |
+
self.order = len(self.listofpoly) - 1
|
227 |
+
|
228 |
+
def __mul__(self, other):
|
229 |
+
"""
|
230 |
+
Multiplies two DifferentialOperator and returns another
|
231 |
+
DifferentialOperator instance using the commutation rule
|
232 |
+
Dx*a = a*Dx + a'
|
233 |
+
"""
|
234 |
+
|
235 |
+
listofself = self.listofpoly
|
236 |
+
|
237 |
+
if not isinstance(other, DifferentialOperator):
|
238 |
+
if not isinstance(other, self.parent.base.dtype):
|
239 |
+
listofother = [self.parent.base.from_sympy(sympify(other))]
|
240 |
+
|
241 |
+
else:
|
242 |
+
listofother = [other]
|
243 |
+
else:
|
244 |
+
listofother = other.listofpoly
|
245 |
+
|
246 |
+
# multiplies a polynomial `b` with a list of polynomials
|
247 |
+
def _mul_dmp_diffop(b, listofother):
|
248 |
+
if isinstance(listofother, list):
|
249 |
+
sol = []
|
250 |
+
for i in listofother:
|
251 |
+
sol.append(i * b)
|
252 |
+
return sol
|
253 |
+
else:
|
254 |
+
return [b * listofother]
|
255 |
+
|
256 |
+
sol = _mul_dmp_diffop(listofself[0], listofother)
|
257 |
+
|
258 |
+
# compute Dx^i * b
|
259 |
+
def _mul_Dxi_b(b):
|
260 |
+
sol1 = [self.parent.base.zero]
|
261 |
+
sol2 = []
|
262 |
+
|
263 |
+
if isinstance(b, list):
|
264 |
+
for i in b:
|
265 |
+
sol1.append(i)
|
266 |
+
sol2.append(i.diff())
|
267 |
+
else:
|
268 |
+
sol1.append(self.parent.base.from_sympy(b))
|
269 |
+
sol2.append(self.parent.base.from_sympy(b).diff())
|
270 |
+
|
271 |
+
return _add_lists(sol1, sol2)
|
272 |
+
|
273 |
+
for i in range(1, len(listofself)):
|
274 |
+
# find Dx^i * b in ith iteration
|
275 |
+
listofother = _mul_Dxi_b(listofother)
|
276 |
+
# solution = solution + listofself[i] * (Dx^i * b)
|
277 |
+
sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother))
|
278 |
+
|
279 |
+
return DifferentialOperator(sol, self.parent)
|
280 |
+
|
281 |
+
def __rmul__(self, other):
|
282 |
+
if not isinstance(other, DifferentialOperator):
|
283 |
+
|
284 |
+
if not isinstance(other, self.parent.base.dtype):
|
285 |
+
other = (self.parent.base).from_sympy(sympify(other))
|
286 |
+
|
287 |
+
sol = []
|
288 |
+
for j in self.listofpoly:
|
289 |
+
sol.append(other * j)
|
290 |
+
|
291 |
+
return DifferentialOperator(sol, self.parent)
|
292 |
+
|
293 |
+
def __add__(self, other):
|
294 |
+
if isinstance(other, DifferentialOperator):
|
295 |
+
|
296 |
+
sol = _add_lists(self.listofpoly, other.listofpoly)
|
297 |
+
return DifferentialOperator(sol, self.parent)
|
298 |
+
|
299 |
+
else:
|
300 |
+
list_self = self.listofpoly
|
301 |
+
if not isinstance(other, self.parent.base.dtype):
|
302 |
+
list_other = [((self.parent).base).from_sympy(sympify(other))]
|
303 |
+
else:
|
304 |
+
list_other = [other]
|
305 |
+
sol = []
|
306 |
+
sol.append(list_self[0] + list_other[0])
|
307 |
+
sol += list_self[1:]
|
308 |
+
|
309 |
+
return DifferentialOperator(sol, self.parent)
|
310 |
+
|
311 |
+
__radd__ = __add__
|
312 |
+
|
313 |
+
def __sub__(self, other):
|
314 |
+
return self + (-1) * other
|
315 |
+
|
316 |
+
def __rsub__(self, other):
|
317 |
+
return (-1) * self + other
|
318 |
+
|
319 |
+
def __neg__(self):
|
320 |
+
return -1 * self
|
321 |
+
|
322 |
+
def __truediv__(self, other):
|
323 |
+
return self * (S.One / other)
|
324 |
+
|
325 |
+
def __pow__(self, n):
|
326 |
+
if n == 1:
|
327 |
+
return self
|
328 |
+
if n == 0:
|
329 |
+
return DifferentialOperator([self.parent.base.one], self.parent)
|
330 |
+
|
331 |
+
# if self is `Dx`
|
332 |
+
if self.listofpoly == self.parent.derivative_operator.listofpoly:
|
333 |
+
sol = [self.parent.base.zero]*n
|
334 |
+
sol.append(self.parent.base.one)
|
335 |
+
return DifferentialOperator(sol, self.parent)
|
336 |
+
|
337 |
+
# the general case
|
338 |
+
else:
|
339 |
+
if n % 2 == 1:
|
340 |
+
powreduce = self**(n - 1)
|
341 |
+
return powreduce * self
|
342 |
+
elif n % 2 == 0:
|
343 |
+
powreduce = self**(n / 2)
|
344 |
+
return powreduce * powreduce
|
345 |
+
|
346 |
+
def __str__(self):
|
347 |
+
listofpoly = self.listofpoly
|
348 |
+
print_str = ''
|
349 |
+
|
350 |
+
for i, j in enumerate(listofpoly):
|
351 |
+
if j == self.parent.base.zero:
|
352 |
+
continue
|
353 |
+
|
354 |
+
if i == 0:
|
355 |
+
print_str += '(' + sstr(j) + ')'
|
356 |
+
continue
|
357 |
+
|
358 |
+
if print_str:
|
359 |
+
print_str += ' + '
|
360 |
+
|
361 |
+
if i == 1:
|
362 |
+
print_str += '(' + sstr(j) + ')*%s' %(self.parent.gen_symbol)
|
363 |
+
continue
|
364 |
+
|
365 |
+
print_str += '(' + sstr(j) + ')' + '*%s**' %(self.parent.gen_symbol) + sstr(i)
|
366 |
+
|
367 |
+
return print_str
|
368 |
+
|
369 |
+
__repr__ = __str__
|
370 |
+
|
371 |
+
def __eq__(self, other):
|
372 |
+
if isinstance(other, DifferentialOperator):
|
373 |
+
if self.listofpoly == other.listofpoly and self.parent == other.parent:
|
374 |
+
return True
|
375 |
+
else:
|
376 |
+
return False
|
377 |
+
else:
|
378 |
+
if self.listofpoly[0] == other:
|
379 |
+
for i in self.listofpoly[1:]:
|
380 |
+
if i is not self.parent.base.zero:
|
381 |
+
return False
|
382 |
+
return True
|
383 |
+
else:
|
384 |
+
return False
|
385 |
+
|
386 |
+
def is_singular(self, x0):
|
387 |
+
"""
|
388 |
+
Checks if the differential equation is singular at x0.
|
389 |
+
"""
|
390 |
+
|
391 |
+
base = self.parent.base
|
392 |
+
return x0 in roots(base.to_sympy(self.listofpoly[-1]), self.x)
|
393 |
+
|
394 |
+
|
395 |
+
class HolonomicFunction:
|
396 |
+
r"""
|
397 |
+
A Holonomic Function is a solution to a linear homogeneous ordinary
|
398 |
+
differential equation with polynomial coefficients. This differential
|
399 |
+
equation can also be represented by an annihilator i.e. a Differential
|
400 |
+
Operator ``L`` such that :math:`L.f = 0`. For uniqueness of these functions,
|
401 |
+
initial conditions can also be provided along with the annihilator.
|
402 |
+
|
403 |
+
Explanation
|
404 |
+
===========
|
405 |
+
|
406 |
+
Holonomic functions have closure properties and thus forms a ring.
|
407 |
+
Given two Holonomic Functions f and g, their sum, product,
|
408 |
+
integral and derivative is also a Holonomic Function.
|
409 |
+
|
410 |
+
For ordinary points initial condition should be a vector of values of
|
411 |
+
the derivatives i.e. :math:`[y(x_0), y'(x_0), y''(x_0) ... ]`.
|
412 |
+
|
413 |
+
For regular singular points initial conditions can also be provided in this
|
414 |
+
format:
|
415 |
+
:math:`{s0: [C_0, C_1, ...], s1: [C^1_0, C^1_1, ...], ...}`
|
416 |
+
where s0, s1, ... are the roots of indicial equation and vectors
|
417 |
+
:math:`[C_0, C_1, ...], [C^0_0, C^0_1, ...], ...` are the corresponding initial
|
418 |
+
terms of the associated power series. See Examples below.
|
419 |
+
|
420 |
+
Examples
|
421 |
+
========
|
422 |
+
|
423 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
424 |
+
>>> from sympy import QQ
|
425 |
+
>>> from sympy import symbols, S
|
426 |
+
>>> x = symbols('x')
|
427 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
428 |
+
|
429 |
+
>>> p = HolonomicFunction(Dx - 1, x, 0, [1]) # e^x
|
430 |
+
>>> q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) # sin(x)
|
431 |
+
|
432 |
+
>>> p + q # annihilator of e^x + sin(x)
|
433 |
+
HolonomicFunction((-1) + (1)*Dx + (-1)*Dx**2 + (1)*Dx**3, x, 0, [1, 2, 1])
|
434 |
+
|
435 |
+
>>> p * q # annihilator of e^x * sin(x)
|
436 |
+
HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x, 0, [0, 1])
|
437 |
+
|
438 |
+
An example of initial conditions for regular singular points,
|
439 |
+
the indicial equation has only one root `1/2`.
|
440 |
+
|
441 |
+
>>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]})
|
442 |
+
HolonomicFunction((-1/2) + (x)*Dx, x, 0, {1/2: [1]})
|
443 |
+
|
444 |
+
>>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_expr()
|
445 |
+
sqrt(x)
|
446 |
+
|
447 |
+
To plot a Holonomic Function, one can use `.evalf()` for numerical
|
448 |
+
computation. Here's an example on `sin(x)**2/x` using numpy and matplotlib.
|
449 |
+
|
450 |
+
>>> import sympy.holonomic # doctest: +SKIP
|
451 |
+
>>> from sympy import var, sin # doctest: +SKIP
|
452 |
+
>>> import matplotlib.pyplot as plt # doctest: +SKIP
|
453 |
+
>>> import numpy as np # doctest: +SKIP
|
454 |
+
>>> var("x") # doctest: +SKIP
|
455 |
+
>>> r = np.linspace(1, 5, 100) # doctest: +SKIP
|
456 |
+
>>> y = sympy.holonomic.expr_to_holonomic(sin(x)**2/x, x0=1).evalf(r) # doctest: +SKIP
|
457 |
+
>>> plt.plot(r, y, label="holonomic function") # doctest: +SKIP
|
458 |
+
>>> plt.show() # doctest: +SKIP
|
459 |
+
|
460 |
+
"""
|
461 |
+
|
462 |
+
_op_priority = 20
|
463 |
+
|
464 |
+
def __init__(self, annihilator, x, x0=0, y0=None):
|
465 |
+
"""
|
466 |
+
|
467 |
+
Parameters
|
468 |
+
==========
|
469 |
+
|
470 |
+
annihilator:
|
471 |
+
Annihilator of the Holonomic Function, represented by a
|
472 |
+
`DifferentialOperator` object.
|
473 |
+
x:
|
474 |
+
Variable of the function.
|
475 |
+
x0:
|
476 |
+
The point at which initial conditions are stored.
|
477 |
+
Generally an integer.
|
478 |
+
y0:
|
479 |
+
The initial condition. The proper format for the initial condition
|
480 |
+
is described in class docstring. To make the function unique,
|
481 |
+
length of the vector `y0` should be equal to or greater than the
|
482 |
+
order of differential equation.
|
483 |
+
"""
|
484 |
+
|
485 |
+
# initial condition
|
486 |
+
self.y0 = y0
|
487 |
+
# the point for initial conditions, default is zero.
|
488 |
+
self.x0 = x0
|
489 |
+
# differential operator L such that L.f = 0
|
490 |
+
self.annihilator = annihilator
|
491 |
+
self.x = x
|
492 |
+
|
493 |
+
def __str__(self):
|
494 |
+
if self._have_init_cond():
|
495 |
+
str_sol = 'HolonomicFunction(%s, %s, %s, %s)' % (str(self.annihilator),\
|
496 |
+
sstr(self.x), sstr(self.x0), sstr(self.y0))
|
497 |
+
else:
|
498 |
+
str_sol = 'HolonomicFunction(%s, %s)' % (str(self.annihilator),\
|
499 |
+
sstr(self.x))
|
500 |
+
|
501 |
+
return str_sol
|
502 |
+
|
503 |
+
__repr__ = __str__
|
504 |
+
|
505 |
+
def unify(self, other):
|
506 |
+
"""
|
507 |
+
Unifies the base polynomial ring of a given two Holonomic
|
508 |
+
Functions.
|
509 |
+
"""
|
510 |
+
|
511 |
+
R1 = self.annihilator.parent.base
|
512 |
+
R2 = other.annihilator.parent.base
|
513 |
+
|
514 |
+
dom1 = R1.dom
|
515 |
+
dom2 = R2.dom
|
516 |
+
|
517 |
+
if R1 == R2:
|
518 |
+
return (self, other)
|
519 |
+
|
520 |
+
R = (dom1.unify(dom2)).old_poly_ring(self.x)
|
521 |
+
|
522 |
+
newparent, _ = DifferentialOperators(R, str(self.annihilator.parent.gen_symbol))
|
523 |
+
|
524 |
+
sol1 = [R1.to_sympy(i) for i in self.annihilator.listofpoly]
|
525 |
+
sol2 = [R2.to_sympy(i) for i in other.annihilator.listofpoly]
|
526 |
+
|
527 |
+
sol1 = DifferentialOperator(sol1, newparent)
|
528 |
+
sol2 = DifferentialOperator(sol2, newparent)
|
529 |
+
|
530 |
+
sol1 = HolonomicFunction(sol1, self.x, self.x0, self.y0)
|
531 |
+
sol2 = HolonomicFunction(sol2, other.x, other.x0, other.y0)
|
532 |
+
|
533 |
+
return (sol1, sol2)
|
534 |
+
|
535 |
+
def is_singularics(self):
|
536 |
+
"""
|
537 |
+
Returns True if the function have singular initial condition
|
538 |
+
in the dictionary format.
|
539 |
+
|
540 |
+
Returns False if the function have ordinary initial condition
|
541 |
+
in the list format.
|
542 |
+
|
543 |
+
Returns None for all other cases.
|
544 |
+
"""
|
545 |
+
|
546 |
+
if isinstance(self.y0, dict):
|
547 |
+
return True
|
548 |
+
elif isinstance(self.y0, list):
|
549 |
+
return False
|
550 |
+
|
551 |
+
def _have_init_cond(self):
|
552 |
+
"""
|
553 |
+
Checks if the function have initial condition.
|
554 |
+
"""
|
555 |
+
return bool(self.y0)
|
556 |
+
|
557 |
+
def _singularics_to_ord(self):
|
558 |
+
"""
|
559 |
+
Converts a singular initial condition to ordinary if possible.
|
560 |
+
"""
|
561 |
+
a = list(self.y0)[0]
|
562 |
+
b = self.y0[a]
|
563 |
+
|
564 |
+
if len(self.y0) == 1 and a == int(a) and a > 0:
|
565 |
+
y0 = []
|
566 |
+
a = int(a)
|
567 |
+
for i in range(a):
|
568 |
+
y0.append(S.Zero)
|
569 |
+
y0 += [j * factorial(a + i) for i, j in enumerate(b)]
|
570 |
+
|
571 |
+
return HolonomicFunction(self.annihilator, self.x, self.x0, y0)
|
572 |
+
|
573 |
+
def __add__(self, other):
|
574 |
+
# if the ground domains are different
|
575 |
+
if self.annihilator.parent.base != other.annihilator.parent.base:
|
576 |
+
a, b = self.unify(other)
|
577 |
+
return a + b
|
578 |
+
|
579 |
+
deg1 = self.annihilator.order
|
580 |
+
deg2 = other.annihilator.order
|
581 |
+
dim = max(deg1, deg2)
|
582 |
+
R = self.annihilator.parent.base
|
583 |
+
K = R.get_field()
|
584 |
+
|
585 |
+
rowsself = [self.annihilator]
|
586 |
+
rowsother = [other.annihilator]
|
587 |
+
gen = self.annihilator.parent.derivative_operator
|
588 |
+
|
589 |
+
# constructing annihilators up to order dim
|
590 |
+
for i in range(dim - deg1):
|
591 |
+
diff1 = (gen * rowsself[-1])
|
592 |
+
rowsself.append(diff1)
|
593 |
+
|
594 |
+
for i in range(dim - deg2):
|
595 |
+
diff2 = (gen * rowsother[-1])
|
596 |
+
rowsother.append(diff2)
|
597 |
+
|
598 |
+
row = rowsself + rowsother
|
599 |
+
|
600 |
+
# constructing the matrix of the ansatz
|
601 |
+
r = []
|
602 |
+
|
603 |
+
for expr in row:
|
604 |
+
p = []
|
605 |
+
for i in range(dim + 1):
|
606 |
+
if i >= len(expr.listofpoly):
|
607 |
+
p.append(K.zero)
|
608 |
+
else:
|
609 |
+
p.append(K.new(expr.listofpoly[i].rep))
|
610 |
+
r.append(p)
|
611 |
+
|
612 |
+
# solving the linear system using gauss jordan solver
|
613 |
+
r = DomainMatrix(r, (len(row), dim+1), K).transpose()
|
614 |
+
homosys = DomainMatrix.zeros((dim+1, 1), K)
|
615 |
+
sol = _find_nonzero_solution(r, homosys)
|
616 |
+
|
617 |
+
# if a solution is not obtained then increasing the order by 1 in each
|
618 |
+
# iteration
|
619 |
+
while sol.is_zero_matrix:
|
620 |
+
dim += 1
|
621 |
+
|
622 |
+
diff1 = (gen * rowsself[-1])
|
623 |
+
rowsself.append(diff1)
|
624 |
+
|
625 |
+
diff2 = (gen * rowsother[-1])
|
626 |
+
rowsother.append(diff2)
|
627 |
+
|
628 |
+
row = rowsself + rowsother
|
629 |
+
r = []
|
630 |
+
|
631 |
+
for expr in row:
|
632 |
+
p = []
|
633 |
+
for i in range(dim + 1):
|
634 |
+
if i >= len(expr.listofpoly):
|
635 |
+
p.append(K.zero)
|
636 |
+
else:
|
637 |
+
p.append(K.new(expr.listofpoly[i].rep))
|
638 |
+
r.append(p)
|
639 |
+
|
640 |
+
# solving the linear system using gauss jordan solver
|
641 |
+
r = DomainMatrix(r, (len(row), dim+1), K).transpose()
|
642 |
+
homosys = DomainMatrix.zeros((dim+1, 1), K)
|
643 |
+
sol = _find_nonzero_solution(r, homosys)
|
644 |
+
|
645 |
+
# taking only the coefficients needed to multiply with `self`
|
646 |
+
# can be also be done the other way by taking R.H.S and multiplying with
|
647 |
+
# `other`
|
648 |
+
sol = sol.flat()[:dim + 1 - deg1]
|
649 |
+
sol1 = _normalize(sol, self.annihilator.parent)
|
650 |
+
# annihilator of the solution
|
651 |
+
sol = sol1 * (self.annihilator)
|
652 |
+
sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False)
|
653 |
+
|
654 |
+
if not (self._have_init_cond() and other._have_init_cond()):
|
655 |
+
return HolonomicFunction(sol, self.x)
|
656 |
+
|
657 |
+
# both the functions have ordinary initial conditions
|
658 |
+
if self.is_singularics() == False and other.is_singularics() == False:
|
659 |
+
|
660 |
+
# directly add the corresponding value
|
661 |
+
if self.x0 == other.x0:
|
662 |
+
# try to extended the initial conditions
|
663 |
+
# using the annihilator
|
664 |
+
y1 = _extend_y0(self, sol.order)
|
665 |
+
y2 = _extend_y0(other, sol.order)
|
666 |
+
y0 = [a + b for a, b in zip(y1, y2)]
|
667 |
+
return HolonomicFunction(sol, self.x, self.x0, y0)
|
668 |
+
|
669 |
+
else:
|
670 |
+
# change the initial conditions to a same point
|
671 |
+
selfat0 = self.annihilator.is_singular(0)
|
672 |
+
otherat0 = other.annihilator.is_singular(0)
|
673 |
+
|
674 |
+
if self.x0 == 0 and not selfat0 and not otherat0:
|
675 |
+
return self + other.change_ics(0)
|
676 |
+
|
677 |
+
elif other.x0 == 0 and not selfat0 and not otherat0:
|
678 |
+
return self.change_ics(0) + other
|
679 |
+
|
680 |
+
else:
|
681 |
+
selfatx0 = self.annihilator.is_singular(self.x0)
|
682 |
+
otheratx0 = other.annihilator.is_singular(self.x0)
|
683 |
+
|
684 |
+
if not selfatx0 and not otheratx0:
|
685 |
+
return self + other.change_ics(self.x0)
|
686 |
+
|
687 |
+
else:
|
688 |
+
return self.change_ics(other.x0) + other
|
689 |
+
|
690 |
+
if self.x0 != other.x0:
|
691 |
+
return HolonomicFunction(sol, self.x)
|
692 |
+
|
693 |
+
# if the functions have singular_ics
|
694 |
+
y1 = None
|
695 |
+
y2 = None
|
696 |
+
|
697 |
+
if self.is_singularics() == False and other.is_singularics() == True:
|
698 |
+
# convert the ordinary initial condition to singular.
|
699 |
+
_y0 = [j / factorial(i) for i, j in enumerate(self.y0)]
|
700 |
+
y1 = {S.Zero: _y0}
|
701 |
+
y2 = other.y0
|
702 |
+
elif self.is_singularics() == True and other.is_singularics() == False:
|
703 |
+
_y0 = [j / factorial(i) for i, j in enumerate(other.y0)]
|
704 |
+
y1 = self.y0
|
705 |
+
y2 = {S.Zero: _y0}
|
706 |
+
elif self.is_singularics() == True and other.is_singularics() == True:
|
707 |
+
y1 = self.y0
|
708 |
+
y2 = other.y0
|
709 |
+
|
710 |
+
# computing singular initial condition for the result
|
711 |
+
# taking union of the series terms of both functions
|
712 |
+
y0 = {}
|
713 |
+
for i in y1:
|
714 |
+
# add corresponding initial terms if the power
|
715 |
+
# on `x` is same
|
716 |
+
if i in y2:
|
717 |
+
y0[i] = [a + b for a, b in zip(y1[i], y2[i])]
|
718 |
+
else:
|
719 |
+
y0[i] = y1[i]
|
720 |
+
for i in y2:
|
721 |
+
if i not in y1:
|
722 |
+
y0[i] = y2[i]
|
723 |
+
return HolonomicFunction(sol, self.x, self.x0, y0)
|
724 |
+
|
725 |
+
def integrate(self, limits, initcond=False):
|
726 |
+
"""
|
727 |
+
Integrates the given holonomic function.
|
728 |
+
|
729 |
+
Examples
|
730 |
+
========
|
731 |
+
|
732 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
733 |
+
>>> from sympy import QQ
|
734 |
+
>>> from sympy import symbols
|
735 |
+
>>> x = symbols('x')
|
736 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
737 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).integrate((x, 0, x)) # e^x - 1
|
738 |
+
HolonomicFunction((-1)*Dx + (1)*Dx**2, x, 0, [0, 1])
|
739 |
+
>>> HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).integrate((x, 0, x))
|
740 |
+
HolonomicFunction((1)*Dx + (1)*Dx**3, x, 0, [0, 1, 0])
|
741 |
+
"""
|
742 |
+
|
743 |
+
# to get the annihilator, just multiply by Dx from right
|
744 |
+
D = self.annihilator.parent.derivative_operator
|
745 |
+
|
746 |
+
# if the function have initial conditions of the series format
|
747 |
+
if self.is_singularics() == True:
|
748 |
+
|
749 |
+
r = self._singularics_to_ord()
|
750 |
+
if r:
|
751 |
+
return r.integrate(limits, initcond=initcond)
|
752 |
+
|
753 |
+
# computing singular initial condition for the function
|
754 |
+
# produced after integration.
|
755 |
+
y0 = {}
|
756 |
+
for i in self.y0:
|
757 |
+
c = self.y0[i]
|
758 |
+
c2 = []
|
759 |
+
for j, cj in enumerate(c):
|
760 |
+
if cj == 0:
|
761 |
+
c2.append(S.Zero)
|
762 |
+
|
763 |
+
# if power on `x` is -1, the integration becomes log(x)
|
764 |
+
# TODO: Implement this case
|
765 |
+
elif i + j + 1 == 0:
|
766 |
+
raise NotImplementedError("logarithmic terms in the series are not supported")
|
767 |
+
else:
|
768 |
+
c2.append(cj / S(i + j + 1))
|
769 |
+
y0[i + 1] = c2
|
770 |
+
|
771 |
+
if hasattr(limits, "__iter__"):
|
772 |
+
raise NotImplementedError("Definite integration for singular initial conditions")
|
773 |
+
|
774 |
+
return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0)
|
775 |
+
|
776 |
+
# if no initial conditions are available for the function
|
777 |
+
if not self._have_init_cond():
|
778 |
+
if initcond:
|
779 |
+
return HolonomicFunction(self.annihilator * D, self.x, self.x0, [S.Zero])
|
780 |
+
return HolonomicFunction(self.annihilator * D, self.x)
|
781 |
+
|
782 |
+
# definite integral
|
783 |
+
# initial conditions for the answer will be stored at point `a`,
|
784 |
+
# where `a` is the lower limit of the integrand
|
785 |
+
if hasattr(limits, "__iter__"):
|
786 |
+
|
787 |
+
if len(limits) == 3 and limits[0] == self.x:
|
788 |
+
x0 = self.x0
|
789 |
+
a = limits[1]
|
790 |
+
b = limits[2]
|
791 |
+
definite = True
|
792 |
+
|
793 |
+
else:
|
794 |
+
definite = False
|
795 |
+
|
796 |
+
y0 = [S.Zero]
|
797 |
+
y0 += self.y0
|
798 |
+
|
799 |
+
indefinite_integral = HolonomicFunction(self.annihilator * D, self.x, self.x0, y0)
|
800 |
+
|
801 |
+
if not definite:
|
802 |
+
return indefinite_integral
|
803 |
+
|
804 |
+
# use evalf to get the values at `a`
|
805 |
+
if x0 != a:
|
806 |
+
try:
|
807 |
+
indefinite_expr = indefinite_integral.to_expr()
|
808 |
+
except (NotHyperSeriesError, NotPowerSeriesError):
|
809 |
+
indefinite_expr = None
|
810 |
+
|
811 |
+
if indefinite_expr:
|
812 |
+
lower = indefinite_expr.subs(self.x, a)
|
813 |
+
if isinstance(lower, NaN):
|
814 |
+
lower = indefinite_expr.limit(self.x, a)
|
815 |
+
else:
|
816 |
+
lower = indefinite_integral.evalf(a)
|
817 |
+
|
818 |
+
if b == self.x:
|
819 |
+
y0[0] = y0[0] - lower
|
820 |
+
return HolonomicFunction(self.annihilator * D, self.x, x0, y0)
|
821 |
+
|
822 |
+
elif S(b).is_Number:
|
823 |
+
if indefinite_expr:
|
824 |
+
upper = indefinite_expr.subs(self.x, b)
|
825 |
+
if isinstance(upper, NaN):
|
826 |
+
upper = indefinite_expr.limit(self.x, b)
|
827 |
+
else:
|
828 |
+
upper = indefinite_integral.evalf(b)
|
829 |
+
|
830 |
+
return upper - lower
|
831 |
+
|
832 |
+
|
833 |
+
# if the upper limit is `x`, the answer will be a function
|
834 |
+
if b == self.x:
|
835 |
+
return HolonomicFunction(self.annihilator * D, self.x, a, y0)
|
836 |
+
|
837 |
+
# if the upper limits is a Number, a numerical value will be returned
|
838 |
+
elif S(b).is_Number:
|
839 |
+
try:
|
840 |
+
s = HolonomicFunction(self.annihilator * D, self.x, a,\
|
841 |
+
y0).to_expr()
|
842 |
+
indefinite = s.subs(self.x, b)
|
843 |
+
if not isinstance(indefinite, NaN):
|
844 |
+
return indefinite
|
845 |
+
else:
|
846 |
+
return s.limit(self.x, b)
|
847 |
+
except (NotHyperSeriesError, NotPowerSeriesError):
|
848 |
+
return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b)
|
849 |
+
|
850 |
+
return HolonomicFunction(self.annihilator * D, self.x)
|
851 |
+
|
852 |
+
def diff(self, *args, **kwargs):
|
853 |
+
r"""
|
854 |
+
Differentiation of the given Holonomic function.
|
855 |
+
|
856 |
+
Examples
|
857 |
+
========
|
858 |
+
|
859 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
860 |
+
>>> from sympy import ZZ
|
861 |
+
>>> from sympy import symbols
|
862 |
+
>>> x = symbols('x')
|
863 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
|
864 |
+
>>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_expr()
|
865 |
+
cos(x)
|
866 |
+
>>> HolonomicFunction(Dx - 2, x, 0, [1]).diff().to_expr()
|
867 |
+
2*exp(2*x)
|
868 |
+
|
869 |
+
See Also
|
870 |
+
========
|
871 |
+
|
872 |
+
integrate
|
873 |
+
"""
|
874 |
+
kwargs.setdefault('evaluate', True)
|
875 |
+
if args:
|
876 |
+
if args[0] != self.x:
|
877 |
+
return S.Zero
|
878 |
+
elif len(args) == 2:
|
879 |
+
sol = self
|
880 |
+
for i in range(args[1]):
|
881 |
+
sol = sol.diff(args[0])
|
882 |
+
return sol
|
883 |
+
|
884 |
+
ann = self.annihilator
|
885 |
+
|
886 |
+
# if the function is constant.
|
887 |
+
if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1:
|
888 |
+
return S.Zero
|
889 |
+
|
890 |
+
# if the coefficient of y in the differential equation is zero.
|
891 |
+
# a shifting is done to compute the answer in this case.
|
892 |
+
elif ann.listofpoly[0] == ann.parent.base.zero:
|
893 |
+
|
894 |
+
sol = DifferentialOperator(ann.listofpoly[1:], ann.parent)
|
895 |
+
|
896 |
+
if self._have_init_cond():
|
897 |
+
# if ordinary initial condition
|
898 |
+
if self.is_singularics() == False:
|
899 |
+
return HolonomicFunction(sol, self.x, self.x0, self.y0[1:])
|
900 |
+
# TODO: support for singular initial condition
|
901 |
+
return HolonomicFunction(sol, self.x)
|
902 |
+
else:
|
903 |
+
return HolonomicFunction(sol, self.x)
|
904 |
+
|
905 |
+
# the general algorithm
|
906 |
+
R = ann.parent.base
|
907 |
+
K = R.get_field()
|
908 |
+
|
909 |
+
seq_dmf = [K.new(i.rep) for i in ann.listofpoly]
|
910 |
+
|
911 |
+
# -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0
|
912 |
+
rhs = [i / seq_dmf[0] for i in seq_dmf[1:]]
|
913 |
+
rhs.insert(0, K.zero)
|
914 |
+
|
915 |
+
# differentiate both lhs and rhs
|
916 |
+
sol = _derivate_diff_eq(rhs)
|
917 |
+
|
918 |
+
# add the term y' in lhs to rhs
|
919 |
+
sol = _add_lists(sol, [K.zero, K.one])
|
920 |
+
|
921 |
+
sol = _normalize(sol[1:], self.annihilator.parent, negative=False)
|
922 |
+
|
923 |
+
if not self._have_init_cond() or self.is_singularics() == True:
|
924 |
+
return HolonomicFunction(sol, self.x)
|
925 |
+
|
926 |
+
y0 = _extend_y0(self, sol.order + 1)[1:]
|
927 |
+
return HolonomicFunction(sol, self.x, self.x0, y0)
|
928 |
+
|
929 |
+
def __eq__(self, other):
|
930 |
+
if self.annihilator == other.annihilator:
|
931 |
+
if self.x == other.x:
|
932 |
+
if self._have_init_cond() and other._have_init_cond():
|
933 |
+
if self.x0 == other.x0 and self.y0 == other.y0:
|
934 |
+
return True
|
935 |
+
else:
|
936 |
+
return False
|
937 |
+
else:
|
938 |
+
return True
|
939 |
+
else:
|
940 |
+
return False
|
941 |
+
else:
|
942 |
+
return False
|
943 |
+
|
944 |
+
def __mul__(self, other):
|
945 |
+
ann_self = self.annihilator
|
946 |
+
|
947 |
+
if not isinstance(other, HolonomicFunction):
|
948 |
+
other = sympify(other)
|
949 |
+
|
950 |
+
if other.has(self.x):
|
951 |
+
raise NotImplementedError(" Can't multiply a HolonomicFunction and expressions/functions.")
|
952 |
+
|
953 |
+
if not self._have_init_cond():
|
954 |
+
return self
|
955 |
+
else:
|
956 |
+
y0 = _extend_y0(self, ann_self.order)
|
957 |
+
y1 = []
|
958 |
+
|
959 |
+
for j in y0:
|
960 |
+
y1.append((Poly.new(j, self.x) * other).rep)
|
961 |
+
|
962 |
+
return HolonomicFunction(ann_self, self.x, self.x0, y1)
|
963 |
+
|
964 |
+
if self.annihilator.parent.base != other.annihilator.parent.base:
|
965 |
+
a, b = self.unify(other)
|
966 |
+
return a * b
|
967 |
+
|
968 |
+
ann_other = other.annihilator
|
969 |
+
|
970 |
+
list_self = []
|
971 |
+
list_other = []
|
972 |
+
|
973 |
+
a = ann_self.order
|
974 |
+
b = ann_other.order
|
975 |
+
|
976 |
+
R = ann_self.parent.base
|
977 |
+
K = R.get_field()
|
978 |
+
|
979 |
+
for j in ann_self.listofpoly:
|
980 |
+
list_self.append(K.new(j.rep))
|
981 |
+
|
982 |
+
for j in ann_other.listofpoly:
|
983 |
+
list_other.append(K.new(j.rep))
|
984 |
+
|
985 |
+
# will be used to reduce the degree
|
986 |
+
self_red = [-list_self[i] / list_self[a] for i in range(a)]
|
987 |
+
|
988 |
+
other_red = [-list_other[i] / list_other[b] for i in range(b)]
|
989 |
+
|
990 |
+
# coeff_mull[i][j] is the coefficient of Dx^i(f).Dx^j(g)
|
991 |
+
coeff_mul = [[K.zero for i in range(b + 1)] for j in range(a + 1)]
|
992 |
+
coeff_mul[0][0] = K.one
|
993 |
+
|
994 |
+
# making the ansatz
|
995 |
+
lin_sys_elements = [[coeff_mul[i][j] for i in range(a) for j in range(b)]]
|
996 |
+
lin_sys = DomainMatrix(lin_sys_elements, (1, a*b), K).transpose()
|
997 |
+
|
998 |
+
homo_sys = DomainMatrix.zeros((a*b, 1), K)
|
999 |
+
|
1000 |
+
sol = _find_nonzero_solution(lin_sys, homo_sys)
|
1001 |
+
|
1002 |
+
# until a non trivial solution is found
|
1003 |
+
while sol.is_zero_matrix:
|
1004 |
+
|
1005 |
+
# updating the coefficients Dx^i(f).Dx^j(g) for next degree
|
1006 |
+
for i in range(a - 1, -1, -1):
|
1007 |
+
for j in range(b - 1, -1, -1):
|
1008 |
+
coeff_mul[i][j + 1] += coeff_mul[i][j]
|
1009 |
+
coeff_mul[i + 1][j] += coeff_mul[i][j]
|
1010 |
+
if isinstance(coeff_mul[i][j], K.dtype):
|
1011 |
+
coeff_mul[i][j] = DMFdiff(coeff_mul[i][j])
|
1012 |
+
else:
|
1013 |
+
coeff_mul[i][j] = coeff_mul[i][j].diff(self.x)
|
1014 |
+
|
1015 |
+
# reduce the terms to lower power using annihilators of f, g
|
1016 |
+
for i in range(a + 1):
|
1017 |
+
if not coeff_mul[i][b].is_zero:
|
1018 |
+
for j in range(b):
|
1019 |
+
coeff_mul[i][j] += other_red[j] * \
|
1020 |
+
coeff_mul[i][b]
|
1021 |
+
coeff_mul[i][b] = K.zero
|
1022 |
+
|
1023 |
+
# not d2 + 1, as that is already covered in previous loop
|
1024 |
+
for j in range(b):
|
1025 |
+
if not coeff_mul[a][j] == 0:
|
1026 |
+
for i in range(a):
|
1027 |
+
coeff_mul[i][j] += self_red[i] * \
|
1028 |
+
coeff_mul[a][j]
|
1029 |
+
coeff_mul[a][j] = K.zero
|
1030 |
+
|
1031 |
+
lin_sys_elements.append([coeff_mul[i][j] for i in range(a) for j in range(b)])
|
1032 |
+
lin_sys = DomainMatrix(lin_sys_elements, (len(lin_sys_elements), a*b), K).transpose()
|
1033 |
+
|
1034 |
+
sol = _find_nonzero_solution(lin_sys, homo_sys)
|
1035 |
+
|
1036 |
+
sol_ann = _normalize(sol.flat(), self.annihilator.parent, negative=False)
|
1037 |
+
|
1038 |
+
if not (self._have_init_cond() and other._have_init_cond()):
|
1039 |
+
return HolonomicFunction(sol_ann, self.x)
|
1040 |
+
|
1041 |
+
if self.is_singularics() == False and other.is_singularics() == False:
|
1042 |
+
|
1043 |
+
# if both the conditions are at same point
|
1044 |
+
if self.x0 == other.x0:
|
1045 |
+
|
1046 |
+
# try to find more initial conditions
|
1047 |
+
y0_self = _extend_y0(self, sol_ann.order)
|
1048 |
+
y0_other = _extend_y0(other, sol_ann.order)
|
1049 |
+
# h(x0) = f(x0) * g(x0)
|
1050 |
+
y0 = [y0_self[0] * y0_other[0]]
|
1051 |
+
|
1052 |
+
# coefficient of Dx^j(f)*Dx^i(g) in Dx^i(fg)
|
1053 |
+
for i in range(1, min(len(y0_self), len(y0_other))):
|
1054 |
+
coeff = [[0 for i in range(i + 1)] for j in range(i + 1)]
|
1055 |
+
for j in range(i + 1):
|
1056 |
+
for k in range(i + 1):
|
1057 |
+
if j + k == i:
|
1058 |
+
coeff[j][k] = binomial(i, j)
|
1059 |
+
|
1060 |
+
sol = 0
|
1061 |
+
for j in range(i + 1):
|
1062 |
+
for k in range(i + 1):
|
1063 |
+
sol += coeff[j][k]* y0_self[j] * y0_other[k]
|
1064 |
+
|
1065 |
+
y0.append(sol)
|
1066 |
+
|
1067 |
+
return HolonomicFunction(sol_ann, self.x, self.x0, y0)
|
1068 |
+
|
1069 |
+
# if the points are different, consider one
|
1070 |
+
else:
|
1071 |
+
|
1072 |
+
selfat0 = self.annihilator.is_singular(0)
|
1073 |
+
otherat0 = other.annihilator.is_singular(0)
|
1074 |
+
|
1075 |
+
if self.x0 == 0 and not selfat0 and not otherat0:
|
1076 |
+
return self * other.change_ics(0)
|
1077 |
+
|
1078 |
+
elif other.x0 == 0 and not selfat0 and not otherat0:
|
1079 |
+
return self.change_ics(0) * other
|
1080 |
+
|
1081 |
+
else:
|
1082 |
+
selfatx0 = self.annihilator.is_singular(self.x0)
|
1083 |
+
otheratx0 = other.annihilator.is_singular(self.x0)
|
1084 |
+
|
1085 |
+
if not selfatx0 and not otheratx0:
|
1086 |
+
return self * other.change_ics(self.x0)
|
1087 |
+
|
1088 |
+
else:
|
1089 |
+
return self.change_ics(other.x0) * other
|
1090 |
+
|
1091 |
+
if self.x0 != other.x0:
|
1092 |
+
return HolonomicFunction(sol_ann, self.x)
|
1093 |
+
|
1094 |
+
# if the functions have singular_ics
|
1095 |
+
y1 = None
|
1096 |
+
y2 = None
|
1097 |
+
|
1098 |
+
if self.is_singularics() == False and other.is_singularics() == True:
|
1099 |
+
_y0 = [j / factorial(i) for i, j in enumerate(self.y0)]
|
1100 |
+
y1 = {S.Zero: _y0}
|
1101 |
+
y2 = other.y0
|
1102 |
+
elif self.is_singularics() == True and other.is_singularics() == False:
|
1103 |
+
_y0 = [j / factorial(i) for i, j in enumerate(other.y0)]
|
1104 |
+
y1 = self.y0
|
1105 |
+
y2 = {S.Zero: _y0}
|
1106 |
+
elif self.is_singularics() == True and other.is_singularics() == True:
|
1107 |
+
y1 = self.y0
|
1108 |
+
y2 = other.y0
|
1109 |
+
|
1110 |
+
y0 = {}
|
1111 |
+
# multiply every possible pair of the series terms
|
1112 |
+
for i in y1:
|
1113 |
+
for j in y2:
|
1114 |
+
k = min(len(y1[i]), len(y2[j]))
|
1115 |
+
c = []
|
1116 |
+
for a in range(k):
|
1117 |
+
s = S.Zero
|
1118 |
+
for b in range(a + 1):
|
1119 |
+
s += y1[i][b] * y2[j][a - b]
|
1120 |
+
c.append(s)
|
1121 |
+
if not i + j in y0:
|
1122 |
+
y0[i + j] = c
|
1123 |
+
else:
|
1124 |
+
y0[i + j] = [a + b for a, b in zip(c, y0[i + j])]
|
1125 |
+
return HolonomicFunction(sol_ann, self.x, self.x0, y0)
|
1126 |
+
|
1127 |
+
__rmul__ = __mul__
|
1128 |
+
|
1129 |
+
def __sub__(self, other):
|
1130 |
+
return self + other * -1
|
1131 |
+
|
1132 |
+
def __rsub__(self, other):
|
1133 |
+
return self * -1 + other
|
1134 |
+
|
1135 |
+
def __neg__(self):
|
1136 |
+
return -1 * self
|
1137 |
+
|
1138 |
+
def __truediv__(self, other):
|
1139 |
+
return self * (S.One / other)
|
1140 |
+
|
1141 |
+
def __pow__(self, n):
|
1142 |
+
if self.annihilator.order <= 1:
|
1143 |
+
ann = self.annihilator
|
1144 |
+
parent = ann.parent
|
1145 |
+
|
1146 |
+
if self.y0 is None:
|
1147 |
+
y0 = None
|
1148 |
+
else:
|
1149 |
+
y0 = [list(self.y0)[0] ** n]
|
1150 |
+
|
1151 |
+
p0 = ann.listofpoly[0]
|
1152 |
+
p1 = ann.listofpoly[1]
|
1153 |
+
|
1154 |
+
p0 = (Poly.new(p0, self.x) * n).rep
|
1155 |
+
|
1156 |
+
sol = [parent.base.to_sympy(i) for i in [p0, p1]]
|
1157 |
+
dd = DifferentialOperator(sol, parent)
|
1158 |
+
return HolonomicFunction(dd, self.x, self.x0, y0)
|
1159 |
+
if n < 0:
|
1160 |
+
raise NotHolonomicError("Negative Power on a Holonomic Function")
|
1161 |
+
if n == 0:
|
1162 |
+
Dx = self.annihilator.parent.derivative_operator
|
1163 |
+
return HolonomicFunction(Dx, self.x, S.Zero, [S.One])
|
1164 |
+
if n == 1:
|
1165 |
+
return self
|
1166 |
+
else:
|
1167 |
+
if n % 2 == 1:
|
1168 |
+
powreduce = self**(n - 1)
|
1169 |
+
return powreduce * self
|
1170 |
+
elif n % 2 == 0:
|
1171 |
+
powreduce = self**(n / 2)
|
1172 |
+
return powreduce * powreduce
|
1173 |
+
|
1174 |
+
def degree(self):
|
1175 |
+
"""
|
1176 |
+
Returns the highest power of `x` in the annihilator.
|
1177 |
+
"""
|
1178 |
+
sol = [i.degree() for i in self.annihilator.listofpoly]
|
1179 |
+
return max(sol)
|
1180 |
+
|
1181 |
+
def composition(self, expr, *args, **kwargs):
|
1182 |
+
"""
|
1183 |
+
Returns function after composition of a holonomic
|
1184 |
+
function with an algebraic function. The method cannot compute
|
1185 |
+
initial conditions for the result by itself, so they can be also be
|
1186 |
+
provided.
|
1187 |
+
|
1188 |
+
Examples
|
1189 |
+
========
|
1190 |
+
|
1191 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
1192 |
+
>>> from sympy import QQ
|
1193 |
+
>>> from sympy import symbols
|
1194 |
+
>>> x = symbols('x')
|
1195 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
1196 |
+
>>> HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2)
|
1197 |
+
HolonomicFunction((-2*x) + (1)*Dx, x, 0, [1])
|
1198 |
+
>>> HolonomicFunction(Dx**2 + 1, x).composition(x**2 - 1, 1, [1, 0])
|
1199 |
+
HolonomicFunction((4*x**3) + (-1)*Dx + (x)*Dx**2, x, 1, [1, 0])
|
1200 |
+
|
1201 |
+
See Also
|
1202 |
+
========
|
1203 |
+
|
1204 |
+
from_hyper
|
1205 |
+
"""
|
1206 |
+
|
1207 |
+
R = self.annihilator.parent
|
1208 |
+
a = self.annihilator.order
|
1209 |
+
diff = expr.diff(self.x)
|
1210 |
+
listofpoly = self.annihilator.listofpoly
|
1211 |
+
|
1212 |
+
for i, j in enumerate(listofpoly):
|
1213 |
+
if isinstance(j, self.annihilator.parent.base.dtype):
|
1214 |
+
listofpoly[i] = self.annihilator.parent.base.to_sympy(j)
|
1215 |
+
|
1216 |
+
r = listofpoly[a].subs({self.x:expr})
|
1217 |
+
subs = [-listofpoly[i].subs({self.x:expr}) / r for i in range (a)]
|
1218 |
+
coeffs = [S.Zero for i in range(a)] # coeffs[i] == coeff of (D^i f)(a) in D^k (f(a))
|
1219 |
+
coeffs[0] = S.One
|
1220 |
+
system = [coeffs]
|
1221 |
+
homogeneous = Matrix([[S.Zero for i in range(a)]]).transpose()
|
1222 |
+
while True:
|
1223 |
+
coeffs_next = [p.diff(self.x) for p in coeffs]
|
1224 |
+
for i in range(a - 1):
|
1225 |
+
coeffs_next[i + 1] += (coeffs[i] * diff)
|
1226 |
+
for i in range(a):
|
1227 |
+
coeffs_next[i] += (coeffs[-1] * subs[i] * diff)
|
1228 |
+
coeffs = coeffs_next
|
1229 |
+
# check for linear relations
|
1230 |
+
system.append(coeffs)
|
1231 |
+
sol, taus = (Matrix(system).transpose()
|
1232 |
+
).gauss_jordan_solve(homogeneous)
|
1233 |
+
if sol.is_zero_matrix is not True:
|
1234 |
+
break
|
1235 |
+
|
1236 |
+
tau = list(taus)[0]
|
1237 |
+
sol = sol.subs(tau, 1)
|
1238 |
+
sol = _normalize(sol[0:], R, negative=False)
|
1239 |
+
|
1240 |
+
# if initial conditions are given for the resulting function
|
1241 |
+
if args:
|
1242 |
+
return HolonomicFunction(sol, self.x, args[0], args[1])
|
1243 |
+
return HolonomicFunction(sol, self.x)
|
1244 |
+
|
1245 |
+
def to_sequence(self, lb=True):
|
1246 |
+
r"""
|
1247 |
+
Finds recurrence relation for the coefficients in the series expansion
|
1248 |
+
of the function about :math:`x_0`, where :math:`x_0` is the point at
|
1249 |
+
which the initial condition is stored.
|
1250 |
+
|
1251 |
+
Explanation
|
1252 |
+
===========
|
1253 |
+
|
1254 |
+
If the point :math:`x_0` is ordinary, solution of the form :math:`[(R, n_0)]`
|
1255 |
+
is returned. Where :math:`R` is the recurrence relation and :math:`n_0` is the
|
1256 |
+
smallest ``n`` for which the recurrence holds true.
|
1257 |
+
|
1258 |
+
If the point :math:`x_0` is regular singular, a list of solutions in
|
1259 |
+
the format :math:`(R, p, n_0)` is returned, i.e. `[(R, p, n_0), ... ]`.
|
1260 |
+
Each tuple in this vector represents a recurrence relation :math:`R`
|
1261 |
+
associated with a root of the indicial equation ``p``. Conditions of
|
1262 |
+
a different format can also be provided in this case, see the
|
1263 |
+
docstring of HolonomicFunction class.
|
1264 |
+
|
1265 |
+
If it's not possible to numerically compute a initial condition,
|
1266 |
+
it is returned as a symbol :math:`C_j`, denoting the coefficient of
|
1267 |
+
:math:`(x - x_0)^j` in the power series about :math:`x_0`.
|
1268 |
+
|
1269 |
+
Examples
|
1270 |
+
========
|
1271 |
+
|
1272 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
1273 |
+
>>> from sympy import QQ
|
1274 |
+
>>> from sympy import symbols, S
|
1275 |
+
>>> x = symbols('x')
|
1276 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
1277 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence()
|
1278 |
+
[(HolonomicSequence((-1) + (n + 1)Sn, n), u(0) = 1, 0)]
|
1279 |
+
>>> HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_sequence()
|
1280 |
+
[(HolonomicSequence((n**2) + (n**2 + n)Sn, n), u(0) = 0, u(1) = 1, u(2) = -1/2, 2)]
|
1281 |
+
>>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_sequence()
|
1282 |
+
[(HolonomicSequence((n), n), u(0) = 1, 1/2, 1)]
|
1283 |
+
|
1284 |
+
See Also
|
1285 |
+
========
|
1286 |
+
|
1287 |
+
HolonomicFunction.series
|
1288 |
+
|
1289 |
+
References
|
1290 |
+
==========
|
1291 |
+
|
1292 |
+
.. [1] https://hal.inria.fr/inria-00070025/document
|
1293 |
+
.. [2] https://www3.risc.jku.at/publications/download/risc_2244/DIPLFORM.pdf
|
1294 |
+
|
1295 |
+
"""
|
1296 |
+
|
1297 |
+
if self.x0 != 0:
|
1298 |
+
return self.shift_x(self.x0).to_sequence()
|
1299 |
+
|
1300 |
+
# check whether a power series exists if the point is singular
|
1301 |
+
if self.annihilator.is_singular(self.x0):
|
1302 |
+
return self._frobenius(lb=lb)
|
1303 |
+
|
1304 |
+
dict1 = {}
|
1305 |
+
n = Symbol('n', integer=True)
|
1306 |
+
dom = self.annihilator.parent.base.dom
|
1307 |
+
R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn')
|
1308 |
+
|
1309 |
+
# substituting each term of the form `x^k Dx^j` in the
|
1310 |
+
# annihilator, according to the formula below:
|
1311 |
+
# x^k Dx^j = Sum(rf(n + 1 - k, j) * a(n + j - k) * x^n, (n, k, oo))
|
1312 |
+
# for explanation see [2].
|
1313 |
+
for i, j in enumerate(self.annihilator.listofpoly):
|
1314 |
+
|
1315 |
+
listofdmp = j.all_coeffs()
|
1316 |
+
degree = len(listofdmp) - 1
|
1317 |
+
|
1318 |
+
for k in range(degree + 1):
|
1319 |
+
coeff = listofdmp[degree - k]
|
1320 |
+
|
1321 |
+
if coeff == 0:
|
1322 |
+
continue
|
1323 |
+
|
1324 |
+
if (i - k, k) in dict1:
|
1325 |
+
dict1[(i - k, k)] += (dom.to_sympy(coeff) * rf(n - k + 1, i))
|
1326 |
+
else:
|
1327 |
+
dict1[(i - k, k)] = (dom.to_sympy(coeff) * rf(n - k + 1, i))
|
1328 |
+
|
1329 |
+
|
1330 |
+
sol = []
|
1331 |
+
keylist = [i[0] for i in dict1]
|
1332 |
+
lower = min(keylist)
|
1333 |
+
upper = max(keylist)
|
1334 |
+
degree = self.degree()
|
1335 |
+
|
1336 |
+
# the recurrence relation holds for all values of
|
1337 |
+
# n greater than smallest_n, i.e. n >= smallest_n
|
1338 |
+
smallest_n = lower + degree
|
1339 |
+
dummys = {}
|
1340 |
+
eqs = []
|
1341 |
+
unknowns = []
|
1342 |
+
|
1343 |
+
# an appropriate shift of the recurrence
|
1344 |
+
for j in range(lower, upper + 1):
|
1345 |
+
if j in keylist:
|
1346 |
+
temp = S.Zero
|
1347 |
+
for k in dict1.keys():
|
1348 |
+
if k[0] == j:
|
1349 |
+
temp += dict1[k].subs(n, n - lower)
|
1350 |
+
sol.append(temp)
|
1351 |
+
else:
|
1352 |
+
sol.append(S.Zero)
|
1353 |
+
|
1354 |
+
# the recurrence relation
|
1355 |
+
sol = RecurrenceOperator(sol, R)
|
1356 |
+
|
1357 |
+
# computing the initial conditions for recurrence
|
1358 |
+
order = sol.order
|
1359 |
+
all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z')
|
1360 |
+
all_roots = all_roots.keys()
|
1361 |
+
|
1362 |
+
if all_roots:
|
1363 |
+
max_root = max(all_roots) + 1
|
1364 |
+
smallest_n = max(max_root, smallest_n)
|
1365 |
+
order += smallest_n
|
1366 |
+
|
1367 |
+
y0 = _extend_y0(self, order)
|
1368 |
+
u0 = []
|
1369 |
+
|
1370 |
+
# u(n) = y^n(0)/factorial(n)
|
1371 |
+
for i, j in enumerate(y0):
|
1372 |
+
u0.append(j / factorial(i))
|
1373 |
+
|
1374 |
+
# if sufficient conditions can't be computed then
|
1375 |
+
# try to use the series method i.e.
|
1376 |
+
# equate the coefficients of x^k in the equation formed by
|
1377 |
+
# substituting the series in differential equation, to zero.
|
1378 |
+
if len(u0) < order:
|
1379 |
+
|
1380 |
+
for i in range(degree):
|
1381 |
+
eq = S.Zero
|
1382 |
+
|
1383 |
+
for j in dict1:
|
1384 |
+
|
1385 |
+
if i + j[0] < 0:
|
1386 |
+
dummys[i + j[0]] = S.Zero
|
1387 |
+
|
1388 |
+
elif i + j[0] < len(u0):
|
1389 |
+
dummys[i + j[0]] = u0[i + j[0]]
|
1390 |
+
|
1391 |
+
elif not i + j[0] in dummys:
|
1392 |
+
dummys[i + j[0]] = Symbol('C_%s' %(i + j[0]))
|
1393 |
+
unknowns.append(dummys[i + j[0]])
|
1394 |
+
|
1395 |
+
if j[1] <= i:
|
1396 |
+
eq += dict1[j].subs(n, i) * dummys[i + j[0]]
|
1397 |
+
|
1398 |
+
eqs.append(eq)
|
1399 |
+
|
1400 |
+
# solve the system of equations formed
|
1401 |
+
soleqs = solve(eqs, *unknowns)
|
1402 |
+
|
1403 |
+
if isinstance(soleqs, dict):
|
1404 |
+
|
1405 |
+
for i in range(len(u0), order):
|
1406 |
+
|
1407 |
+
if i not in dummys:
|
1408 |
+
dummys[i] = Symbol('C_%s' %i)
|
1409 |
+
|
1410 |
+
if dummys[i] in soleqs:
|
1411 |
+
u0.append(soleqs[dummys[i]])
|
1412 |
+
|
1413 |
+
else:
|
1414 |
+
u0.append(dummys[i])
|
1415 |
+
|
1416 |
+
if lb:
|
1417 |
+
return [(HolonomicSequence(sol, u0), smallest_n)]
|
1418 |
+
return [HolonomicSequence(sol, u0)]
|
1419 |
+
|
1420 |
+
for i in range(len(u0), order):
|
1421 |
+
|
1422 |
+
if i not in dummys:
|
1423 |
+
dummys[i] = Symbol('C_%s' %i)
|
1424 |
+
|
1425 |
+
s = False
|
1426 |
+
for j in soleqs:
|
1427 |
+
if dummys[i] in j:
|
1428 |
+
u0.append(j[dummys[i]])
|
1429 |
+
s = True
|
1430 |
+
if not s:
|
1431 |
+
u0.append(dummys[i])
|
1432 |
+
|
1433 |
+
if lb:
|
1434 |
+
return [(HolonomicSequence(sol, u0), smallest_n)]
|
1435 |
+
|
1436 |
+
return [HolonomicSequence(sol, u0)]
|
1437 |
+
|
1438 |
+
def _frobenius(self, lb=True):
|
1439 |
+
# compute the roots of indicial equation
|
1440 |
+
indicialroots = self._indicial()
|
1441 |
+
|
1442 |
+
reals = []
|
1443 |
+
compl = []
|
1444 |
+
for i in ordered(indicialroots.keys()):
|
1445 |
+
if i.is_real:
|
1446 |
+
reals.extend([i] * indicialroots[i])
|
1447 |
+
else:
|
1448 |
+
a, b = i.as_real_imag()
|
1449 |
+
compl.extend([(i, a, b)] * indicialroots[i])
|
1450 |
+
|
1451 |
+
# sort the roots for a fixed ordering of solution
|
1452 |
+
compl.sort(key=lambda x : x[1])
|
1453 |
+
compl.sort(key=lambda x : x[2])
|
1454 |
+
reals.sort()
|
1455 |
+
|
1456 |
+
# grouping the roots, roots differ by an integer are put in the same group.
|
1457 |
+
grp = []
|
1458 |
+
|
1459 |
+
for i in reals:
|
1460 |
+
intdiff = False
|
1461 |
+
if len(grp) == 0:
|
1462 |
+
grp.append([i])
|
1463 |
+
continue
|
1464 |
+
for j in grp:
|
1465 |
+
if int(j[0] - i) == j[0] - i:
|
1466 |
+
j.append(i)
|
1467 |
+
intdiff = True
|
1468 |
+
break
|
1469 |
+
if not intdiff:
|
1470 |
+
grp.append([i])
|
1471 |
+
|
1472 |
+
# True if none of the roots differ by an integer i.e.
|
1473 |
+
# each element in group have only one member
|
1474 |
+
independent = True if all(len(i) == 1 for i in grp) else False
|
1475 |
+
|
1476 |
+
allpos = all(i >= 0 for i in reals)
|
1477 |
+
allint = all(int(i) == i for i in reals)
|
1478 |
+
|
1479 |
+
# if initial conditions are provided
|
1480 |
+
# then use them.
|
1481 |
+
if self.is_singularics() == True:
|
1482 |
+
rootstoconsider = []
|
1483 |
+
for i in ordered(self.y0.keys()):
|
1484 |
+
for j in ordered(indicialroots.keys()):
|
1485 |
+
if equal_valued(j, i):
|
1486 |
+
rootstoconsider.append(i)
|
1487 |
+
|
1488 |
+
elif allpos and allint:
|
1489 |
+
rootstoconsider = [min(reals)]
|
1490 |
+
|
1491 |
+
elif independent:
|
1492 |
+
rootstoconsider = [i[0] for i in grp] + [j[0] for j in compl]
|
1493 |
+
|
1494 |
+
elif not allint:
|
1495 |
+
rootstoconsider = []
|
1496 |
+
for i in reals:
|
1497 |
+
if not int(i) == i:
|
1498 |
+
rootstoconsider.append(i)
|
1499 |
+
|
1500 |
+
elif not allpos:
|
1501 |
+
|
1502 |
+
if not self._have_init_cond() or S(self.y0[0]).is_finite == False:
|
1503 |
+
rootstoconsider = [min(reals)]
|
1504 |
+
|
1505 |
+
else:
|
1506 |
+
posroots = []
|
1507 |
+
for i in reals:
|
1508 |
+
if i >= 0:
|
1509 |
+
posroots.append(i)
|
1510 |
+
rootstoconsider = [min(posroots)]
|
1511 |
+
|
1512 |
+
n = Symbol('n', integer=True)
|
1513 |
+
dom = self.annihilator.parent.base.dom
|
1514 |
+
R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn')
|
1515 |
+
|
1516 |
+
finalsol = []
|
1517 |
+
char = ord('C')
|
1518 |
+
|
1519 |
+
for p in rootstoconsider:
|
1520 |
+
dict1 = {}
|
1521 |
+
|
1522 |
+
for i, j in enumerate(self.annihilator.listofpoly):
|
1523 |
+
|
1524 |
+
listofdmp = j.all_coeffs()
|
1525 |
+
degree = len(listofdmp) - 1
|
1526 |
+
|
1527 |
+
for k in range(degree + 1):
|
1528 |
+
coeff = listofdmp[degree - k]
|
1529 |
+
|
1530 |
+
if coeff == 0:
|
1531 |
+
continue
|
1532 |
+
|
1533 |
+
if (i - k, k - i) in dict1:
|
1534 |
+
dict1[(i - k, k - i)] += (dom.to_sympy(coeff) * rf(n - k + 1 + p, i))
|
1535 |
+
else:
|
1536 |
+
dict1[(i - k, k - i)] = (dom.to_sympy(coeff) * rf(n - k + 1 + p, i))
|
1537 |
+
|
1538 |
+
sol = []
|
1539 |
+
keylist = [i[0] for i in dict1]
|
1540 |
+
lower = min(keylist)
|
1541 |
+
upper = max(keylist)
|
1542 |
+
degree = max([i[1] for i in dict1])
|
1543 |
+
degree2 = min([i[1] for i in dict1])
|
1544 |
+
|
1545 |
+
smallest_n = lower + degree
|
1546 |
+
dummys = {}
|
1547 |
+
eqs = []
|
1548 |
+
unknowns = []
|
1549 |
+
|
1550 |
+
for j in range(lower, upper + 1):
|
1551 |
+
if j in keylist:
|
1552 |
+
temp = S.Zero
|
1553 |
+
for k in dict1.keys():
|
1554 |
+
if k[0] == j:
|
1555 |
+
temp += dict1[k].subs(n, n - lower)
|
1556 |
+
sol.append(temp)
|
1557 |
+
else:
|
1558 |
+
sol.append(S.Zero)
|
1559 |
+
|
1560 |
+
# the recurrence relation
|
1561 |
+
sol = RecurrenceOperator(sol, R)
|
1562 |
+
|
1563 |
+
# computing the initial conditions for recurrence
|
1564 |
+
order = sol.order
|
1565 |
+
all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z')
|
1566 |
+
all_roots = all_roots.keys()
|
1567 |
+
|
1568 |
+
if all_roots:
|
1569 |
+
max_root = max(all_roots) + 1
|
1570 |
+
smallest_n = max(max_root, smallest_n)
|
1571 |
+
order += smallest_n
|
1572 |
+
|
1573 |
+
u0 = []
|
1574 |
+
|
1575 |
+
if self.is_singularics() == True:
|
1576 |
+
u0 = self.y0[p]
|
1577 |
+
|
1578 |
+
elif self.is_singularics() == False and p >= 0 and int(p) == p and len(rootstoconsider) == 1:
|
1579 |
+
y0 = _extend_y0(self, order + int(p))
|
1580 |
+
# u(n) = y^n(0)/factorial(n)
|
1581 |
+
if len(y0) > int(p):
|
1582 |
+
for i in range(int(p), len(y0)):
|
1583 |
+
u0.append(y0[i] / factorial(i))
|
1584 |
+
|
1585 |
+
if len(u0) < order:
|
1586 |
+
|
1587 |
+
for i in range(degree2, degree):
|
1588 |
+
eq = S.Zero
|
1589 |
+
|
1590 |
+
for j in dict1:
|
1591 |
+
if i + j[0] < 0:
|
1592 |
+
dummys[i + j[0]] = S.Zero
|
1593 |
+
|
1594 |
+
elif i + j[0] < len(u0):
|
1595 |
+
dummys[i + j[0]] = u0[i + j[0]]
|
1596 |
+
|
1597 |
+
elif not i + j[0] in dummys:
|
1598 |
+
letter = chr(char) + '_%s' %(i + j[0])
|
1599 |
+
dummys[i + j[0]] = Symbol(letter)
|
1600 |
+
unknowns.append(dummys[i + j[0]])
|
1601 |
+
|
1602 |
+
if j[1] <= i:
|
1603 |
+
eq += dict1[j].subs(n, i) * dummys[i + j[0]]
|
1604 |
+
|
1605 |
+
eqs.append(eq)
|
1606 |
+
|
1607 |
+
# solve the system of equations formed
|
1608 |
+
soleqs = solve(eqs, *unknowns)
|
1609 |
+
|
1610 |
+
if isinstance(soleqs, dict):
|
1611 |
+
|
1612 |
+
for i in range(len(u0), order):
|
1613 |
+
|
1614 |
+
if i not in dummys:
|
1615 |
+
letter = chr(char) + '_%s' %i
|
1616 |
+
dummys[i] = Symbol(letter)
|
1617 |
+
|
1618 |
+
if dummys[i] in soleqs:
|
1619 |
+
u0.append(soleqs[dummys[i]])
|
1620 |
+
|
1621 |
+
else:
|
1622 |
+
u0.append(dummys[i])
|
1623 |
+
|
1624 |
+
if lb:
|
1625 |
+
finalsol.append((HolonomicSequence(sol, u0), p, smallest_n))
|
1626 |
+
continue
|
1627 |
+
else:
|
1628 |
+
finalsol.append((HolonomicSequence(sol, u0), p))
|
1629 |
+
continue
|
1630 |
+
|
1631 |
+
for i in range(len(u0), order):
|
1632 |
+
|
1633 |
+
if i not in dummys:
|
1634 |
+
letter = chr(char) + '_%s' %i
|
1635 |
+
dummys[i] = Symbol(letter)
|
1636 |
+
|
1637 |
+
s = False
|
1638 |
+
for j in soleqs:
|
1639 |
+
if dummys[i] in j:
|
1640 |
+
u0.append(j[dummys[i]])
|
1641 |
+
s = True
|
1642 |
+
if not s:
|
1643 |
+
u0.append(dummys[i])
|
1644 |
+
if lb:
|
1645 |
+
finalsol.append((HolonomicSequence(sol, u0), p, smallest_n))
|
1646 |
+
|
1647 |
+
else:
|
1648 |
+
finalsol.append((HolonomicSequence(sol, u0), p))
|
1649 |
+
char += 1
|
1650 |
+
return finalsol
|
1651 |
+
|
1652 |
+
def series(self, n=6, coefficient=False, order=True, _recur=None):
|
1653 |
+
r"""
|
1654 |
+
Finds the power series expansion of given holonomic function about :math:`x_0`.
|
1655 |
+
|
1656 |
+
Explanation
|
1657 |
+
===========
|
1658 |
+
|
1659 |
+
A list of series might be returned if :math:`x_0` is a regular point with
|
1660 |
+
multiple roots of the indicial equation.
|
1661 |
+
|
1662 |
+
Examples
|
1663 |
+
========
|
1664 |
+
|
1665 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
1666 |
+
>>> from sympy import QQ
|
1667 |
+
>>> from sympy import symbols
|
1668 |
+
>>> x = symbols('x')
|
1669 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
1670 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).series() # e^x
|
1671 |
+
1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)
|
1672 |
+
>>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).series(n=8) # sin(x)
|
1673 |
+
x - x**3/6 + x**5/120 - x**7/5040 + O(x**8)
|
1674 |
+
|
1675 |
+
See Also
|
1676 |
+
========
|
1677 |
+
|
1678 |
+
HolonomicFunction.to_sequence
|
1679 |
+
"""
|
1680 |
+
|
1681 |
+
if _recur is None:
|
1682 |
+
recurrence = self.to_sequence()
|
1683 |
+
else:
|
1684 |
+
recurrence = _recur
|
1685 |
+
|
1686 |
+
if isinstance(recurrence, tuple) and len(recurrence) == 2:
|
1687 |
+
recurrence = recurrence[0]
|
1688 |
+
constantpower = 0
|
1689 |
+
elif isinstance(recurrence, tuple) and len(recurrence) == 3:
|
1690 |
+
constantpower = recurrence[1]
|
1691 |
+
recurrence = recurrence[0]
|
1692 |
+
|
1693 |
+
elif len(recurrence) == 1 and len(recurrence[0]) == 2:
|
1694 |
+
recurrence = recurrence[0][0]
|
1695 |
+
constantpower = 0
|
1696 |
+
elif len(recurrence) == 1 and len(recurrence[0]) == 3:
|
1697 |
+
constantpower = recurrence[0][1]
|
1698 |
+
recurrence = recurrence[0][0]
|
1699 |
+
else:
|
1700 |
+
sol = []
|
1701 |
+
for i in recurrence:
|
1702 |
+
sol.append(self.series(_recur=i))
|
1703 |
+
return sol
|
1704 |
+
|
1705 |
+
n = n - int(constantpower)
|
1706 |
+
l = len(recurrence.u0) - 1
|
1707 |
+
k = recurrence.recurrence.order
|
1708 |
+
x = self.x
|
1709 |
+
x0 = self.x0
|
1710 |
+
seq_dmp = recurrence.recurrence.listofpoly
|
1711 |
+
R = recurrence.recurrence.parent.base
|
1712 |
+
K = R.get_field()
|
1713 |
+
seq = []
|
1714 |
+
|
1715 |
+
for i, j in enumerate(seq_dmp):
|
1716 |
+
seq.append(K.new(j.rep))
|
1717 |
+
|
1718 |
+
sub = [-seq[i] / seq[k] for i in range(k)]
|
1719 |
+
sol = list(recurrence.u0)
|
1720 |
+
|
1721 |
+
if l + 1 >= n:
|
1722 |
+
pass
|
1723 |
+
else:
|
1724 |
+
# use the initial conditions to find the next term
|
1725 |
+
for i in range(l + 1 - k, n - k):
|
1726 |
+
coeff = S.Zero
|
1727 |
+
for j in range(k):
|
1728 |
+
if i + j >= 0:
|
1729 |
+
coeff += DMFsubs(sub[j], i) * sol[i + j]
|
1730 |
+
sol.append(coeff)
|
1731 |
+
|
1732 |
+
if coefficient:
|
1733 |
+
return sol
|
1734 |
+
|
1735 |
+
ser = S.Zero
|
1736 |
+
for i, j in enumerate(sol):
|
1737 |
+
ser += x**(i + constantpower) * j
|
1738 |
+
if order:
|
1739 |
+
ser += Order(x**(n + int(constantpower)), x)
|
1740 |
+
if x0 != 0:
|
1741 |
+
return ser.subs(x, x - x0)
|
1742 |
+
return ser
|
1743 |
+
|
1744 |
+
def _indicial(self):
|
1745 |
+
"""
|
1746 |
+
Computes roots of the Indicial equation.
|
1747 |
+
"""
|
1748 |
+
|
1749 |
+
if self.x0 != 0:
|
1750 |
+
return self.shift_x(self.x0)._indicial()
|
1751 |
+
|
1752 |
+
list_coeff = self.annihilator.listofpoly
|
1753 |
+
R = self.annihilator.parent.base
|
1754 |
+
x = self.x
|
1755 |
+
s = R.zero
|
1756 |
+
y = R.one
|
1757 |
+
|
1758 |
+
def _pole_degree(poly):
|
1759 |
+
root_all = roots(R.to_sympy(poly), x, filter='Z')
|
1760 |
+
if 0 in root_all.keys():
|
1761 |
+
return root_all[0]
|
1762 |
+
else:
|
1763 |
+
return 0
|
1764 |
+
|
1765 |
+
degree = [j.degree() for j in list_coeff]
|
1766 |
+
degree = max(degree)
|
1767 |
+
inf = 10 * (max(1, degree) + max(1, self.annihilator.order))
|
1768 |
+
|
1769 |
+
deg = lambda q: inf if q.is_zero else _pole_degree(q)
|
1770 |
+
b = deg(list_coeff[0])
|
1771 |
+
|
1772 |
+
for j in range(1, len(list_coeff)):
|
1773 |
+
b = min(b, deg(list_coeff[j]) - j)
|
1774 |
+
|
1775 |
+
for i, j in enumerate(list_coeff):
|
1776 |
+
listofdmp = j.all_coeffs()
|
1777 |
+
degree = len(listofdmp) - 1
|
1778 |
+
if - i - b <= 0 and degree - i - b >= 0:
|
1779 |
+
s = s + listofdmp[degree - i - b] * y
|
1780 |
+
y *= x - i
|
1781 |
+
|
1782 |
+
return roots(R.to_sympy(s), x)
|
1783 |
+
|
1784 |
+
def evalf(self, points, method='RK4', h=0.05, derivatives=False):
|
1785 |
+
r"""
|
1786 |
+
Finds numerical value of a holonomic function using numerical methods.
|
1787 |
+
(RK4 by default). A set of points (real or complex) must be provided
|
1788 |
+
which will be the path for the numerical integration.
|
1789 |
+
|
1790 |
+
Explanation
|
1791 |
+
===========
|
1792 |
+
|
1793 |
+
The path should be given as a list :math:`[x_1, x_2, \dots x_n]`. The numerical
|
1794 |
+
values will be computed at each point in this order
|
1795 |
+
:math:`x_1 \rightarrow x_2 \rightarrow x_3 \dots \rightarrow x_n`.
|
1796 |
+
|
1797 |
+
Returns values of the function at :math:`x_1, x_2, \dots x_n` in a list.
|
1798 |
+
|
1799 |
+
Examples
|
1800 |
+
========
|
1801 |
+
|
1802 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
1803 |
+
>>> from sympy import QQ
|
1804 |
+
>>> from sympy import symbols
|
1805 |
+
>>> x = symbols('x')
|
1806 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
1807 |
+
|
1808 |
+
A straight line on the real axis from (0 to 1)
|
1809 |
+
|
1810 |
+
>>> r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
|
1811 |
+
|
1812 |
+
Runge-Kutta 4th order on e^x from 0.1 to 1.
|
1813 |
+
Exact solution at 1 is 2.71828182845905
|
1814 |
+
|
1815 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r)
|
1816 |
+
[1.10517083333333, 1.22140257085069, 1.34985849706254, 1.49182424008069,
|
1817 |
+
1.64872063859684, 1.82211796209193, 2.01375162659678, 2.22553956329232,
|
1818 |
+
2.45960141378007, 2.71827974413517]
|
1819 |
+
|
1820 |
+
Euler's method for the same
|
1821 |
+
|
1822 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r, method='Euler')
|
1823 |
+
[1.1, 1.21, 1.331, 1.4641, 1.61051, 1.771561, 1.9487171, 2.14358881,
|
1824 |
+
2.357947691, 2.5937424601]
|
1825 |
+
|
1826 |
+
One can also observe that the value obtained using Runge-Kutta 4th order
|
1827 |
+
is much more accurate than Euler's method.
|
1828 |
+
"""
|
1829 |
+
|
1830 |
+
from sympy.holonomic.numerical import _evalf
|
1831 |
+
lp = False
|
1832 |
+
|
1833 |
+
# if a point `b` is given instead of a mesh
|
1834 |
+
if not hasattr(points, "__iter__"):
|
1835 |
+
lp = True
|
1836 |
+
b = S(points)
|
1837 |
+
if self.x0 == b:
|
1838 |
+
return _evalf(self, [b], method=method, derivatives=derivatives)[-1]
|
1839 |
+
|
1840 |
+
if not b.is_Number:
|
1841 |
+
raise NotImplementedError
|
1842 |
+
|
1843 |
+
a = self.x0
|
1844 |
+
if a > b:
|
1845 |
+
h = -h
|
1846 |
+
n = int((b - a) / h)
|
1847 |
+
points = [a + h]
|
1848 |
+
for i in range(n - 1):
|
1849 |
+
points.append(points[-1] + h)
|
1850 |
+
|
1851 |
+
for i in roots(self.annihilator.parent.base.to_sympy(self.annihilator.listofpoly[-1]), self.x):
|
1852 |
+
if i == self.x0 or i in points:
|
1853 |
+
raise SingularityError(self, i)
|
1854 |
+
|
1855 |
+
if lp:
|
1856 |
+
return _evalf(self, points, method=method, derivatives=derivatives)[-1]
|
1857 |
+
return _evalf(self, points, method=method, derivatives=derivatives)
|
1858 |
+
|
1859 |
+
def change_x(self, z):
|
1860 |
+
"""
|
1861 |
+
Changes only the variable of Holonomic Function, for internal
|
1862 |
+
purposes. For composition use HolonomicFunction.composition()
|
1863 |
+
"""
|
1864 |
+
|
1865 |
+
dom = self.annihilator.parent.base.dom
|
1866 |
+
R = dom.old_poly_ring(z)
|
1867 |
+
parent, _ = DifferentialOperators(R, 'Dx')
|
1868 |
+
sol = []
|
1869 |
+
for j in self.annihilator.listofpoly:
|
1870 |
+
sol.append(R(j.rep))
|
1871 |
+
sol = DifferentialOperator(sol, parent)
|
1872 |
+
return HolonomicFunction(sol, z, self.x0, self.y0)
|
1873 |
+
|
1874 |
+
def shift_x(self, a):
|
1875 |
+
"""
|
1876 |
+
Substitute `x + a` for `x`.
|
1877 |
+
"""
|
1878 |
+
|
1879 |
+
x = self.x
|
1880 |
+
listaftershift = self.annihilator.listofpoly
|
1881 |
+
base = self.annihilator.parent.base
|
1882 |
+
|
1883 |
+
sol = [base.from_sympy(base.to_sympy(i).subs(x, x + a)) for i in listaftershift]
|
1884 |
+
sol = DifferentialOperator(sol, self.annihilator.parent)
|
1885 |
+
x0 = self.x0 - a
|
1886 |
+
if not self._have_init_cond():
|
1887 |
+
return HolonomicFunction(sol, x)
|
1888 |
+
return HolonomicFunction(sol, x, x0, self.y0)
|
1889 |
+
|
1890 |
+
def to_hyper(self, as_list=False, _recur=None):
|
1891 |
+
r"""
|
1892 |
+
Returns a hypergeometric function (or linear combination of them)
|
1893 |
+
representing the given holonomic function.
|
1894 |
+
|
1895 |
+
Explanation
|
1896 |
+
===========
|
1897 |
+
|
1898 |
+
Returns an answer of the form:
|
1899 |
+
`a_1 \cdot x^{b_1} \cdot{hyper()} + a_2 \cdot x^{b_2} \cdot{hyper()} \dots`
|
1900 |
+
|
1901 |
+
This is very useful as one can now use ``hyperexpand`` to find the
|
1902 |
+
symbolic expressions/functions.
|
1903 |
+
|
1904 |
+
Examples
|
1905 |
+
========
|
1906 |
+
|
1907 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
1908 |
+
>>> from sympy import ZZ
|
1909 |
+
>>> from sympy import symbols
|
1910 |
+
>>> x = symbols('x')
|
1911 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
|
1912 |
+
>>> # sin(x)
|
1913 |
+
>>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_hyper()
|
1914 |
+
x*hyper((), (3/2,), -x**2/4)
|
1915 |
+
>>> # exp(x)
|
1916 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).to_hyper()
|
1917 |
+
hyper((), (), x)
|
1918 |
+
|
1919 |
+
See Also
|
1920 |
+
========
|
1921 |
+
|
1922 |
+
from_hyper, from_meijerg
|
1923 |
+
"""
|
1924 |
+
|
1925 |
+
if _recur is None:
|
1926 |
+
recurrence = self.to_sequence()
|
1927 |
+
else:
|
1928 |
+
recurrence = _recur
|
1929 |
+
|
1930 |
+
if isinstance(recurrence, tuple) and len(recurrence) == 2:
|
1931 |
+
smallest_n = recurrence[1]
|
1932 |
+
recurrence = recurrence[0]
|
1933 |
+
constantpower = 0
|
1934 |
+
elif isinstance(recurrence, tuple) and len(recurrence) == 3:
|
1935 |
+
smallest_n = recurrence[2]
|
1936 |
+
constantpower = recurrence[1]
|
1937 |
+
recurrence = recurrence[0]
|
1938 |
+
elif len(recurrence) == 1 and len(recurrence[0]) == 2:
|
1939 |
+
smallest_n = recurrence[0][1]
|
1940 |
+
recurrence = recurrence[0][0]
|
1941 |
+
constantpower = 0
|
1942 |
+
elif len(recurrence) == 1 and len(recurrence[0]) == 3:
|
1943 |
+
smallest_n = recurrence[0][2]
|
1944 |
+
constantpower = recurrence[0][1]
|
1945 |
+
recurrence = recurrence[0][0]
|
1946 |
+
else:
|
1947 |
+
sol = self.to_hyper(as_list=as_list, _recur=recurrence[0])
|
1948 |
+
for i in recurrence[1:]:
|
1949 |
+
sol += self.to_hyper(as_list=as_list, _recur=i)
|
1950 |
+
return sol
|
1951 |
+
|
1952 |
+
u0 = recurrence.u0
|
1953 |
+
r = recurrence.recurrence
|
1954 |
+
x = self.x
|
1955 |
+
x0 = self.x0
|
1956 |
+
|
1957 |
+
# order of the recurrence relation
|
1958 |
+
m = r.order
|
1959 |
+
|
1960 |
+
# when no recurrence exists, and the power series have finite terms
|
1961 |
+
if m == 0:
|
1962 |
+
nonzeroterms = roots(r.parent.base.to_sympy(r.listofpoly[0]), recurrence.n, filter='R')
|
1963 |
+
|
1964 |
+
sol = S.Zero
|
1965 |
+
for j, i in enumerate(nonzeroterms):
|
1966 |
+
|
1967 |
+
if i < 0 or int(i) != i:
|
1968 |
+
continue
|
1969 |
+
|
1970 |
+
i = int(i)
|
1971 |
+
if i < len(u0):
|
1972 |
+
if isinstance(u0[i], (PolyElement, FracElement)):
|
1973 |
+
u0[i] = u0[i].as_expr()
|
1974 |
+
sol += u0[i] * x**i
|
1975 |
+
|
1976 |
+
else:
|
1977 |
+
sol += Symbol('C_%s' %j) * x**i
|
1978 |
+
|
1979 |
+
if isinstance(sol, (PolyElement, FracElement)):
|
1980 |
+
sol = sol.as_expr() * x**constantpower
|
1981 |
+
else:
|
1982 |
+
sol = sol * x**constantpower
|
1983 |
+
if as_list:
|
1984 |
+
if x0 != 0:
|
1985 |
+
return [(sol.subs(x, x - x0), )]
|
1986 |
+
return [(sol, )]
|
1987 |
+
if x0 != 0:
|
1988 |
+
return sol.subs(x, x - x0)
|
1989 |
+
return sol
|
1990 |
+
|
1991 |
+
if smallest_n + m > len(u0):
|
1992 |
+
raise NotImplementedError("Can't compute sufficient Initial Conditions")
|
1993 |
+
|
1994 |
+
# check if the recurrence represents a hypergeometric series
|
1995 |
+
is_hyper = True
|
1996 |
+
|
1997 |
+
for i in range(1, len(r.listofpoly)-1):
|
1998 |
+
if r.listofpoly[i] != r.parent.base.zero:
|
1999 |
+
is_hyper = False
|
2000 |
+
break
|
2001 |
+
|
2002 |
+
if not is_hyper:
|
2003 |
+
raise NotHyperSeriesError(self, self.x0)
|
2004 |
+
|
2005 |
+
a = r.listofpoly[0]
|
2006 |
+
b = r.listofpoly[-1]
|
2007 |
+
|
2008 |
+
# the constant multiple of argument of hypergeometric function
|
2009 |
+
if isinstance(a.rep[0], (PolyElement, FracElement)):
|
2010 |
+
c = - (S(a.rep[0].as_expr()) * m**(a.degree())) / (S(b.rep[0].as_expr()) * m**(b.degree()))
|
2011 |
+
else:
|
2012 |
+
c = - (S(a.rep[0]) * m**(a.degree())) / (S(b.rep[0]) * m**(b.degree()))
|
2013 |
+
|
2014 |
+
sol = 0
|
2015 |
+
|
2016 |
+
arg1 = roots(r.parent.base.to_sympy(a), recurrence.n)
|
2017 |
+
arg2 = roots(r.parent.base.to_sympy(b), recurrence.n)
|
2018 |
+
|
2019 |
+
# iterate through the initial conditions to find
|
2020 |
+
# the hypergeometric representation of the given
|
2021 |
+
# function.
|
2022 |
+
# The answer will be a linear combination
|
2023 |
+
# of different hypergeometric series which satisfies
|
2024 |
+
# the recurrence.
|
2025 |
+
if as_list:
|
2026 |
+
listofsol = []
|
2027 |
+
for i in range(smallest_n + m):
|
2028 |
+
|
2029 |
+
# if the recurrence relation doesn't hold for `n = i`,
|
2030 |
+
# then a Hypergeometric representation doesn't exist.
|
2031 |
+
# add the algebraic term a * x**i to the solution,
|
2032 |
+
# where a is u0[i]
|
2033 |
+
if i < smallest_n:
|
2034 |
+
if as_list:
|
2035 |
+
listofsol.append(((S(u0[i]) * x**(i+constantpower)).subs(x, x-x0), ))
|
2036 |
+
else:
|
2037 |
+
sol += S(u0[i]) * x**i
|
2038 |
+
continue
|
2039 |
+
|
2040 |
+
# if the coefficient u0[i] is zero, then the
|
2041 |
+
# independent hypergeomtric series starting with
|
2042 |
+
# x**i is not a part of the answer.
|
2043 |
+
if S(u0[i]) == 0:
|
2044 |
+
continue
|
2045 |
+
|
2046 |
+
ap = []
|
2047 |
+
bq = []
|
2048 |
+
|
2049 |
+
# substitute m * n + i for n
|
2050 |
+
for k in ordered(arg1.keys()):
|
2051 |
+
ap.extend([nsimplify((i - k) / m)] * arg1[k])
|
2052 |
+
|
2053 |
+
for k in ordered(arg2.keys()):
|
2054 |
+
bq.extend([nsimplify((i - k) / m)] * arg2[k])
|
2055 |
+
|
2056 |
+
# convention of (k + 1) in the denominator
|
2057 |
+
if 1 in bq:
|
2058 |
+
bq.remove(1)
|
2059 |
+
else:
|
2060 |
+
ap.append(1)
|
2061 |
+
if as_list:
|
2062 |
+
listofsol.append(((S(u0[i])*x**(i+constantpower)).subs(x, x-x0), (hyper(ap, bq, c*x**m)).subs(x, x-x0)))
|
2063 |
+
else:
|
2064 |
+
sol += S(u0[i]) * hyper(ap, bq, c * x**m) * x**i
|
2065 |
+
if as_list:
|
2066 |
+
return listofsol
|
2067 |
+
sol = sol * x**constantpower
|
2068 |
+
if x0 != 0:
|
2069 |
+
return sol.subs(x, x - x0)
|
2070 |
+
|
2071 |
+
return sol
|
2072 |
+
|
2073 |
+
def to_expr(self):
|
2074 |
+
"""
|
2075 |
+
Converts a Holonomic Function back to elementary functions.
|
2076 |
+
|
2077 |
+
Examples
|
2078 |
+
========
|
2079 |
+
|
2080 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
2081 |
+
>>> from sympy import ZZ
|
2082 |
+
>>> from sympy import symbols, S
|
2083 |
+
>>> x = symbols('x')
|
2084 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
|
2085 |
+
>>> HolonomicFunction(x**2*Dx**2 + x*Dx + (x**2 - 1), x, 0, [0, S(1)/2]).to_expr()
|
2086 |
+
besselj(1, x)
|
2087 |
+
>>> HolonomicFunction((1 + x)*Dx**3 + Dx**2, x, 0, [1, 1, 1]).to_expr()
|
2088 |
+
x*log(x + 1) + log(x + 1) + 1
|
2089 |
+
|
2090 |
+
"""
|
2091 |
+
|
2092 |
+
return hyperexpand(self.to_hyper()).simplify()
|
2093 |
+
|
2094 |
+
def change_ics(self, b, lenics=None):
|
2095 |
+
"""
|
2096 |
+
Changes the point `x0` to ``b`` for initial conditions.
|
2097 |
+
|
2098 |
+
Examples
|
2099 |
+
========
|
2100 |
+
|
2101 |
+
>>> from sympy.holonomic import expr_to_holonomic
|
2102 |
+
>>> from sympy import symbols, sin, exp
|
2103 |
+
>>> x = symbols('x')
|
2104 |
+
|
2105 |
+
>>> expr_to_holonomic(sin(x)).change_ics(1)
|
2106 |
+
HolonomicFunction((1) + (1)*Dx**2, x, 1, [sin(1), cos(1)])
|
2107 |
+
|
2108 |
+
>>> expr_to_holonomic(exp(x)).change_ics(2)
|
2109 |
+
HolonomicFunction((-1) + (1)*Dx, x, 2, [exp(2)])
|
2110 |
+
"""
|
2111 |
+
|
2112 |
+
symbolic = True
|
2113 |
+
|
2114 |
+
if lenics is None and len(self.y0) > self.annihilator.order:
|
2115 |
+
lenics = len(self.y0)
|
2116 |
+
dom = self.annihilator.parent.base.domain
|
2117 |
+
|
2118 |
+
try:
|
2119 |
+
sol = expr_to_holonomic(self.to_expr(), x=self.x, x0=b, lenics=lenics, domain=dom)
|
2120 |
+
except (NotPowerSeriesError, NotHyperSeriesError):
|
2121 |
+
symbolic = False
|
2122 |
+
|
2123 |
+
if symbolic and sol.x0 == b:
|
2124 |
+
return sol
|
2125 |
+
|
2126 |
+
y0 = self.evalf(b, derivatives=True)
|
2127 |
+
return HolonomicFunction(self.annihilator, self.x, b, y0)
|
2128 |
+
|
2129 |
+
def to_meijerg(self):
|
2130 |
+
"""
|
2131 |
+
Returns a linear combination of Meijer G-functions.
|
2132 |
+
|
2133 |
+
Examples
|
2134 |
+
========
|
2135 |
+
|
2136 |
+
>>> from sympy.holonomic import expr_to_holonomic
|
2137 |
+
>>> from sympy import sin, cos, hyperexpand, log, symbols
|
2138 |
+
>>> x = symbols('x')
|
2139 |
+
>>> hyperexpand(expr_to_holonomic(cos(x) + sin(x)).to_meijerg())
|
2140 |
+
sin(x) + cos(x)
|
2141 |
+
>>> hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify()
|
2142 |
+
log(x)
|
2143 |
+
|
2144 |
+
See Also
|
2145 |
+
========
|
2146 |
+
|
2147 |
+
to_hyper
|
2148 |
+
"""
|
2149 |
+
|
2150 |
+
# convert to hypergeometric first
|
2151 |
+
rep = self.to_hyper(as_list=True)
|
2152 |
+
sol = S.Zero
|
2153 |
+
|
2154 |
+
for i in rep:
|
2155 |
+
if len(i) == 1:
|
2156 |
+
sol += i[0]
|
2157 |
+
|
2158 |
+
elif len(i) == 2:
|
2159 |
+
sol += i[0] * _hyper_to_meijerg(i[1])
|
2160 |
+
|
2161 |
+
return sol
|
2162 |
+
|
2163 |
+
|
2164 |
+
def from_hyper(func, x0=0, evalf=False):
|
2165 |
+
r"""
|
2166 |
+
Converts a hypergeometric function to holonomic.
|
2167 |
+
``func`` is the Hypergeometric Function and ``x0`` is the point at
|
2168 |
+
which initial conditions are required.
|
2169 |
+
|
2170 |
+
Examples
|
2171 |
+
========
|
2172 |
+
|
2173 |
+
>>> from sympy.holonomic.holonomic import from_hyper
|
2174 |
+
>>> from sympy import symbols, hyper, S
|
2175 |
+
>>> x = symbols('x')
|
2176 |
+
>>> from_hyper(hyper([], [S(3)/2], x**2/4))
|
2177 |
+
HolonomicFunction((-x) + (2)*Dx + (x)*Dx**2, x, 1, [sinh(1), -sinh(1) + cosh(1)])
|
2178 |
+
"""
|
2179 |
+
|
2180 |
+
a = func.ap
|
2181 |
+
b = func.bq
|
2182 |
+
z = func.args[2]
|
2183 |
+
x = z.atoms(Symbol).pop()
|
2184 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
2185 |
+
|
2186 |
+
# generalized hypergeometric differential equation
|
2187 |
+
xDx = x*Dx
|
2188 |
+
r1 = 1
|
2189 |
+
for ai in a: # XXX gives sympify error if Mul is used with list of all factors
|
2190 |
+
r1 *= xDx + ai
|
2191 |
+
xDx_1 = xDx - 1
|
2192 |
+
# r2 = Mul(*([Dx] + [xDx_1 + bi for bi in b])) # XXX gives sympify error
|
2193 |
+
r2 = Dx
|
2194 |
+
for bi in b:
|
2195 |
+
r2 *= xDx_1 + bi
|
2196 |
+
sol = r1 - r2
|
2197 |
+
|
2198 |
+
simp = hyperexpand(func)
|
2199 |
+
|
2200 |
+
if simp in (Infinity, NegativeInfinity):
|
2201 |
+
return HolonomicFunction(sol, x).composition(z)
|
2202 |
+
|
2203 |
+
def _find_conditions(simp, x, x0, order, evalf=False):
|
2204 |
+
y0 = []
|
2205 |
+
for i in range(order):
|
2206 |
+
if evalf:
|
2207 |
+
val = simp.subs(x, x0).evalf()
|
2208 |
+
else:
|
2209 |
+
val = simp.subs(x, x0)
|
2210 |
+
# return None if it is Infinite or NaN
|
2211 |
+
if val.is_finite is False or isinstance(val, NaN):
|
2212 |
+
return None
|
2213 |
+
y0.append(val)
|
2214 |
+
simp = simp.diff(x)
|
2215 |
+
return y0
|
2216 |
+
|
2217 |
+
# if the function is known symbolically
|
2218 |
+
if not isinstance(simp, hyper):
|
2219 |
+
y0 = _find_conditions(simp, x, x0, sol.order)
|
2220 |
+
while not y0:
|
2221 |
+
# if values don't exist at 0, then try to find initial
|
2222 |
+
# conditions at 1. If it doesn't exist at 1 too then
|
2223 |
+
# try 2 and so on.
|
2224 |
+
x0 += 1
|
2225 |
+
y0 = _find_conditions(simp, x, x0, sol.order)
|
2226 |
+
|
2227 |
+
return HolonomicFunction(sol, x).composition(z, x0, y0)
|
2228 |
+
|
2229 |
+
if isinstance(simp, hyper):
|
2230 |
+
x0 = 1
|
2231 |
+
# use evalf if the function can't be simplified
|
2232 |
+
y0 = _find_conditions(simp, x, x0, sol.order, evalf)
|
2233 |
+
while not y0:
|
2234 |
+
x0 += 1
|
2235 |
+
y0 = _find_conditions(simp, x, x0, sol.order, evalf)
|
2236 |
+
return HolonomicFunction(sol, x).composition(z, x0, y0)
|
2237 |
+
|
2238 |
+
return HolonomicFunction(sol, x).composition(z)
|
2239 |
+
|
2240 |
+
|
2241 |
+
def from_meijerg(func, x0=0, evalf=False, initcond=True, domain=QQ):
|
2242 |
+
"""
|
2243 |
+
Converts a Meijer G-function to Holonomic.
|
2244 |
+
``func`` is the G-Function and ``x0`` is the point at
|
2245 |
+
which initial conditions are required.
|
2246 |
+
|
2247 |
+
Examples
|
2248 |
+
========
|
2249 |
+
|
2250 |
+
>>> from sympy.holonomic.holonomic import from_meijerg
|
2251 |
+
>>> from sympy import symbols, meijerg, S
|
2252 |
+
>>> x = symbols('x')
|
2253 |
+
>>> from_meijerg(meijerg(([], []), ([S(1)/2], [0]), x**2/4))
|
2254 |
+
HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1/sqrt(pi)])
|
2255 |
+
"""
|
2256 |
+
|
2257 |
+
a = func.ap
|
2258 |
+
b = func.bq
|
2259 |
+
n = len(func.an)
|
2260 |
+
m = len(func.bm)
|
2261 |
+
p = len(a)
|
2262 |
+
z = func.args[2]
|
2263 |
+
x = z.atoms(Symbol).pop()
|
2264 |
+
R, Dx = DifferentialOperators(domain.old_poly_ring(x), 'Dx')
|
2265 |
+
|
2266 |
+
# compute the differential equation satisfied by the
|
2267 |
+
# Meijer G-function.
|
2268 |
+
xDx = x*Dx
|
2269 |
+
xDx1 = xDx + 1
|
2270 |
+
r1 = x*(-1)**(m + n - p)
|
2271 |
+
for ai in a: # XXX gives sympify error if args given in list
|
2272 |
+
r1 *= xDx1 - ai
|
2273 |
+
# r2 = Mul(*[xDx - bi for bi in b]) # gives sympify error
|
2274 |
+
r2 = 1
|
2275 |
+
for bi in b:
|
2276 |
+
r2 *= xDx - bi
|
2277 |
+
sol = r1 - r2
|
2278 |
+
|
2279 |
+
if not initcond:
|
2280 |
+
return HolonomicFunction(sol, x).composition(z)
|
2281 |
+
|
2282 |
+
simp = hyperexpand(func)
|
2283 |
+
|
2284 |
+
if simp in (Infinity, NegativeInfinity):
|
2285 |
+
return HolonomicFunction(sol, x).composition(z)
|
2286 |
+
|
2287 |
+
def _find_conditions(simp, x, x0, order, evalf=False):
|
2288 |
+
y0 = []
|
2289 |
+
for i in range(order):
|
2290 |
+
if evalf:
|
2291 |
+
val = simp.subs(x, x0).evalf()
|
2292 |
+
else:
|
2293 |
+
val = simp.subs(x, x0)
|
2294 |
+
if val.is_finite is False or isinstance(val, NaN):
|
2295 |
+
return None
|
2296 |
+
y0.append(val)
|
2297 |
+
simp = simp.diff(x)
|
2298 |
+
return y0
|
2299 |
+
|
2300 |
+
# computing initial conditions
|
2301 |
+
if not isinstance(simp, meijerg):
|
2302 |
+
y0 = _find_conditions(simp, x, x0, sol.order)
|
2303 |
+
while not y0:
|
2304 |
+
x0 += 1
|
2305 |
+
y0 = _find_conditions(simp, x, x0, sol.order)
|
2306 |
+
|
2307 |
+
return HolonomicFunction(sol, x).composition(z, x0, y0)
|
2308 |
+
|
2309 |
+
if isinstance(simp, meijerg):
|
2310 |
+
x0 = 1
|
2311 |
+
y0 = _find_conditions(simp, x, x0, sol.order, evalf)
|
2312 |
+
while not y0:
|
2313 |
+
x0 += 1
|
2314 |
+
y0 = _find_conditions(simp, x, x0, sol.order, evalf)
|
2315 |
+
|
2316 |
+
return HolonomicFunction(sol, x).composition(z, x0, y0)
|
2317 |
+
|
2318 |
+
return HolonomicFunction(sol, x).composition(z)
|
2319 |
+
|
2320 |
+
|
2321 |
+
x_1 = Dummy('x_1')
|
2322 |
+
_lookup_table = None
|
2323 |
+
domain_for_table = None
|
2324 |
+
from sympy.integrals.meijerint import _mytype
|
2325 |
+
|
2326 |
+
|
2327 |
+
def expr_to_holonomic(func, x=None, x0=0, y0=None, lenics=None, domain=None, initcond=True):
|
2328 |
+
"""
|
2329 |
+
Converts a function or an expression to a holonomic function.
|
2330 |
+
|
2331 |
+
Parameters
|
2332 |
+
==========
|
2333 |
+
|
2334 |
+
func:
|
2335 |
+
The expression to be converted.
|
2336 |
+
x:
|
2337 |
+
variable for the function.
|
2338 |
+
x0:
|
2339 |
+
point at which initial condition must be computed.
|
2340 |
+
y0:
|
2341 |
+
One can optionally provide initial condition if the method
|
2342 |
+
is not able to do it automatically.
|
2343 |
+
lenics:
|
2344 |
+
Number of terms in the initial condition. By default it is
|
2345 |
+
equal to the order of the annihilator.
|
2346 |
+
domain:
|
2347 |
+
Ground domain for the polynomials in ``x`` appearing as coefficients
|
2348 |
+
in the annihilator.
|
2349 |
+
initcond:
|
2350 |
+
Set it false if you do not want the initial conditions to be computed.
|
2351 |
+
|
2352 |
+
Examples
|
2353 |
+
========
|
2354 |
+
|
2355 |
+
>>> from sympy.holonomic.holonomic import expr_to_holonomic
|
2356 |
+
>>> from sympy import sin, exp, symbols
|
2357 |
+
>>> x = symbols('x')
|
2358 |
+
>>> expr_to_holonomic(sin(x))
|
2359 |
+
HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1])
|
2360 |
+
>>> expr_to_holonomic(exp(x))
|
2361 |
+
HolonomicFunction((-1) + (1)*Dx, x, 0, [1])
|
2362 |
+
|
2363 |
+
See Also
|
2364 |
+
========
|
2365 |
+
|
2366 |
+
sympy.integrals.meijerint._rewrite1, _convert_poly_rat_alg, _create_table
|
2367 |
+
"""
|
2368 |
+
func = sympify(func)
|
2369 |
+
syms = func.free_symbols
|
2370 |
+
|
2371 |
+
if not x:
|
2372 |
+
if len(syms) == 1:
|
2373 |
+
x= syms.pop()
|
2374 |
+
else:
|
2375 |
+
raise ValueError("Specify the variable for the function")
|
2376 |
+
elif x in syms:
|
2377 |
+
syms.remove(x)
|
2378 |
+
|
2379 |
+
extra_syms = list(syms)
|
2380 |
+
|
2381 |
+
if domain is None:
|
2382 |
+
if func.has(Float):
|
2383 |
+
domain = RR
|
2384 |
+
else:
|
2385 |
+
domain = QQ
|
2386 |
+
if len(extra_syms) != 0:
|
2387 |
+
domain = domain[extra_syms].get_field()
|
2388 |
+
|
2389 |
+
# try to convert if the function is polynomial or rational
|
2390 |
+
solpoly = _convert_poly_rat_alg(func, x, x0=x0, y0=y0, lenics=lenics, domain=domain, initcond=initcond)
|
2391 |
+
if solpoly:
|
2392 |
+
return solpoly
|
2393 |
+
|
2394 |
+
# create the lookup table
|
2395 |
+
global _lookup_table, domain_for_table
|
2396 |
+
if not _lookup_table:
|
2397 |
+
domain_for_table = domain
|
2398 |
+
_lookup_table = {}
|
2399 |
+
_create_table(_lookup_table, domain=domain)
|
2400 |
+
elif domain != domain_for_table:
|
2401 |
+
domain_for_table = domain
|
2402 |
+
_lookup_table = {}
|
2403 |
+
_create_table(_lookup_table, domain=domain)
|
2404 |
+
|
2405 |
+
# use the table directly to convert to Holonomic
|
2406 |
+
if func.is_Function:
|
2407 |
+
f = func.subs(x, x_1)
|
2408 |
+
t = _mytype(f, x_1)
|
2409 |
+
if t in _lookup_table:
|
2410 |
+
l = _lookup_table[t]
|
2411 |
+
sol = l[0][1].change_x(x)
|
2412 |
+
else:
|
2413 |
+
sol = _convert_meijerint(func, x, initcond=False, domain=domain)
|
2414 |
+
if not sol:
|
2415 |
+
raise NotImplementedError
|
2416 |
+
if y0:
|
2417 |
+
sol.y0 = y0
|
2418 |
+
if y0 or not initcond:
|
2419 |
+
sol.x0 = x0
|
2420 |
+
return sol
|
2421 |
+
if not lenics:
|
2422 |
+
lenics = sol.annihilator.order
|
2423 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
2424 |
+
while not _y0:
|
2425 |
+
x0 += 1
|
2426 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
2427 |
+
return HolonomicFunction(sol.annihilator, x, x0, _y0)
|
2428 |
+
|
2429 |
+
if y0 or not initcond:
|
2430 |
+
sol = sol.composition(func.args[0])
|
2431 |
+
if y0:
|
2432 |
+
sol.y0 = y0
|
2433 |
+
sol.x0 = x0
|
2434 |
+
return sol
|
2435 |
+
if not lenics:
|
2436 |
+
lenics = sol.annihilator.order
|
2437 |
+
|
2438 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
2439 |
+
while not _y0:
|
2440 |
+
x0 += 1
|
2441 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
2442 |
+
return sol.composition(func.args[0], x0, _y0)
|
2443 |
+
|
2444 |
+
# iterate through the expression recursively
|
2445 |
+
args = func.args
|
2446 |
+
f = func.func
|
2447 |
+
sol = expr_to_holonomic(args[0], x=x, initcond=False, domain=domain)
|
2448 |
+
|
2449 |
+
if f is Add:
|
2450 |
+
for i in range(1, len(args)):
|
2451 |
+
sol += expr_to_holonomic(args[i], x=x, initcond=False, domain=domain)
|
2452 |
+
|
2453 |
+
elif f is Mul:
|
2454 |
+
for i in range(1, len(args)):
|
2455 |
+
sol *= expr_to_holonomic(args[i], x=x, initcond=False, domain=domain)
|
2456 |
+
|
2457 |
+
elif f is Pow:
|
2458 |
+
sol = sol**args[1]
|
2459 |
+
sol.x0 = x0
|
2460 |
+
if not sol:
|
2461 |
+
raise NotImplementedError
|
2462 |
+
if y0:
|
2463 |
+
sol.y0 = y0
|
2464 |
+
if y0 or not initcond:
|
2465 |
+
return sol
|
2466 |
+
if sol.y0:
|
2467 |
+
return sol
|
2468 |
+
if not lenics:
|
2469 |
+
lenics = sol.annihilator.order
|
2470 |
+
if sol.annihilator.is_singular(x0):
|
2471 |
+
r = sol._indicial()
|
2472 |
+
l = list(r)
|
2473 |
+
if len(r) == 1 and r[l[0]] == S.One:
|
2474 |
+
r = l[0]
|
2475 |
+
g = func / (x - x0)**r
|
2476 |
+
singular_ics = _find_conditions(g, x, x0, lenics)
|
2477 |
+
singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)]
|
2478 |
+
y0 = {r:singular_ics}
|
2479 |
+
return HolonomicFunction(sol.annihilator, x, x0, y0)
|
2480 |
+
|
2481 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
2482 |
+
while not _y0:
|
2483 |
+
x0 += 1
|
2484 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
2485 |
+
|
2486 |
+
return HolonomicFunction(sol.annihilator, x, x0, _y0)
|
2487 |
+
|
2488 |
+
|
2489 |
+
## Some helper functions ##
|
2490 |
+
|
2491 |
+
def _normalize(list_of, parent, negative=True):
|
2492 |
+
"""
|
2493 |
+
Normalize a given annihilator
|
2494 |
+
"""
|
2495 |
+
|
2496 |
+
num = []
|
2497 |
+
denom = []
|
2498 |
+
base = parent.base
|
2499 |
+
K = base.get_field()
|
2500 |
+
lcm_denom = base.from_sympy(S.One)
|
2501 |
+
list_of_coeff = []
|
2502 |
+
|
2503 |
+
# convert polynomials to the elements of associated
|
2504 |
+
# fraction field
|
2505 |
+
for i, j in enumerate(list_of):
|
2506 |
+
if isinstance(j, base.dtype):
|
2507 |
+
list_of_coeff.append(K.new(j.rep))
|
2508 |
+
elif not isinstance(j, K.dtype):
|
2509 |
+
list_of_coeff.append(K.from_sympy(sympify(j)))
|
2510 |
+
else:
|
2511 |
+
list_of_coeff.append(j)
|
2512 |
+
|
2513 |
+
# corresponding numerators of the sequence of polynomials
|
2514 |
+
num.append(list_of_coeff[i].numer())
|
2515 |
+
|
2516 |
+
# corresponding denominators
|
2517 |
+
denom.append(list_of_coeff[i].denom())
|
2518 |
+
|
2519 |
+
# lcm of denominators in the coefficients
|
2520 |
+
for i in denom:
|
2521 |
+
lcm_denom = i.lcm(lcm_denom)
|
2522 |
+
|
2523 |
+
if negative:
|
2524 |
+
lcm_denom = -lcm_denom
|
2525 |
+
|
2526 |
+
lcm_denom = K.new(lcm_denom.rep)
|
2527 |
+
|
2528 |
+
# multiply the coefficients with lcm
|
2529 |
+
for i, j in enumerate(list_of_coeff):
|
2530 |
+
list_of_coeff[i] = j * lcm_denom
|
2531 |
+
|
2532 |
+
gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).rep)
|
2533 |
+
|
2534 |
+
# gcd of numerators in the coefficients
|
2535 |
+
for i in num:
|
2536 |
+
gcd_numer = i.gcd(gcd_numer)
|
2537 |
+
|
2538 |
+
gcd_numer = K.new(gcd_numer.rep)
|
2539 |
+
|
2540 |
+
# divide all the coefficients by the gcd
|
2541 |
+
for i, j in enumerate(list_of_coeff):
|
2542 |
+
frac_ans = j / gcd_numer
|
2543 |
+
list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).rep)
|
2544 |
+
|
2545 |
+
return DifferentialOperator(list_of_coeff, parent)
|
2546 |
+
|
2547 |
+
|
2548 |
+
def _derivate_diff_eq(listofpoly):
|
2549 |
+
"""
|
2550 |
+
Let a differential equation a0(x)y(x) + a1(x)y'(x) + ... = 0
|
2551 |
+
where a0, a1,... are polynomials or rational functions. The function
|
2552 |
+
returns b0, b1, b2... such that the differential equation
|
2553 |
+
b0(x)y(x) + b1(x)y'(x) +... = 0 is formed after differentiating the
|
2554 |
+
former equation.
|
2555 |
+
"""
|
2556 |
+
|
2557 |
+
sol = []
|
2558 |
+
a = len(listofpoly) - 1
|
2559 |
+
sol.append(DMFdiff(listofpoly[0]))
|
2560 |
+
|
2561 |
+
for i, j in enumerate(listofpoly[1:]):
|
2562 |
+
sol.append(DMFdiff(j) + listofpoly[i])
|
2563 |
+
|
2564 |
+
sol.append(listofpoly[a])
|
2565 |
+
return sol
|
2566 |
+
|
2567 |
+
|
2568 |
+
def _hyper_to_meijerg(func):
|
2569 |
+
"""
|
2570 |
+
Converts a `hyper` to meijerg.
|
2571 |
+
"""
|
2572 |
+
ap = func.ap
|
2573 |
+
bq = func.bq
|
2574 |
+
|
2575 |
+
ispoly = any(i <= 0 and int(i) == i for i in ap)
|
2576 |
+
if ispoly:
|
2577 |
+
return hyperexpand(func)
|
2578 |
+
|
2579 |
+
z = func.args[2]
|
2580 |
+
|
2581 |
+
# parameters of the `meijerg` function.
|
2582 |
+
an = (1 - i for i in ap)
|
2583 |
+
anp = ()
|
2584 |
+
bm = (S.Zero, )
|
2585 |
+
bmq = (1 - i for i in bq)
|
2586 |
+
|
2587 |
+
k = S.One
|
2588 |
+
|
2589 |
+
for i in bq:
|
2590 |
+
k = k * gamma(i)
|
2591 |
+
|
2592 |
+
for i in ap:
|
2593 |
+
k = k / gamma(i)
|
2594 |
+
|
2595 |
+
return k * meijerg(an, anp, bm, bmq, -z)
|
2596 |
+
|
2597 |
+
|
2598 |
+
def _add_lists(list1, list2):
|
2599 |
+
"""Takes polynomial sequences of two annihilators a and b and returns
|
2600 |
+
the list of polynomials of sum of a and b.
|
2601 |
+
"""
|
2602 |
+
if len(list1) <= len(list2):
|
2603 |
+
sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):]
|
2604 |
+
else:
|
2605 |
+
sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):]
|
2606 |
+
return sol
|
2607 |
+
|
2608 |
+
|
2609 |
+
def _extend_y0(Holonomic, n):
|
2610 |
+
"""
|
2611 |
+
Tries to find more initial conditions by substituting the initial
|
2612 |
+
value point in the differential equation.
|
2613 |
+
"""
|
2614 |
+
|
2615 |
+
if Holonomic.annihilator.is_singular(Holonomic.x0) or Holonomic.is_singularics() == True:
|
2616 |
+
return Holonomic.y0
|
2617 |
+
|
2618 |
+
annihilator = Holonomic.annihilator
|
2619 |
+
a = annihilator.order
|
2620 |
+
|
2621 |
+
listofpoly = []
|
2622 |
+
|
2623 |
+
y0 = Holonomic.y0
|
2624 |
+
R = annihilator.parent.base
|
2625 |
+
K = R.get_field()
|
2626 |
+
|
2627 |
+
for i, j in enumerate(annihilator.listofpoly):
|
2628 |
+
if isinstance(j, annihilator.parent.base.dtype):
|
2629 |
+
listofpoly.append(K.new(j.rep))
|
2630 |
+
|
2631 |
+
if len(y0) < a or n <= len(y0):
|
2632 |
+
return y0
|
2633 |
+
else:
|
2634 |
+
list_red = [-listofpoly[i] / listofpoly[a]
|
2635 |
+
for i in range(a)]
|
2636 |
+
if len(y0) > a:
|
2637 |
+
y1 = [y0[i] for i in range(a)]
|
2638 |
+
else:
|
2639 |
+
y1 = list(y0)
|
2640 |
+
for i in range(n - a):
|
2641 |
+
sol = 0
|
2642 |
+
for a, b in zip(y1, list_red):
|
2643 |
+
r = DMFsubs(b, Holonomic.x0)
|
2644 |
+
if not getattr(r, 'is_finite', True):
|
2645 |
+
return y0
|
2646 |
+
if isinstance(r, (PolyElement, FracElement)):
|
2647 |
+
r = r.as_expr()
|
2648 |
+
sol += a * r
|
2649 |
+
y1.append(sol)
|
2650 |
+
list_red = _derivate_diff_eq(list_red)
|
2651 |
+
|
2652 |
+
return y0 + y1[len(y0):]
|
2653 |
+
|
2654 |
+
|
2655 |
+
def DMFdiff(frac):
|
2656 |
+
# differentiate a DMF object represented as p/q
|
2657 |
+
if not isinstance(frac, DMF):
|
2658 |
+
return frac.diff()
|
2659 |
+
|
2660 |
+
K = frac.ring
|
2661 |
+
p = K.numer(frac)
|
2662 |
+
q = K.denom(frac)
|
2663 |
+
sol_num = - p * q.diff() + q * p.diff()
|
2664 |
+
sol_denom = q**2
|
2665 |
+
return K((sol_num.rep, sol_denom.rep))
|
2666 |
+
|
2667 |
+
|
2668 |
+
def DMFsubs(frac, x0, mpm=False):
|
2669 |
+
# substitute the point x0 in DMF object of the form p/q
|
2670 |
+
if not isinstance(frac, DMF):
|
2671 |
+
return frac
|
2672 |
+
|
2673 |
+
p = frac.num
|
2674 |
+
q = frac.den
|
2675 |
+
sol_p = S.Zero
|
2676 |
+
sol_q = S.Zero
|
2677 |
+
|
2678 |
+
if mpm:
|
2679 |
+
from mpmath import mp
|
2680 |
+
|
2681 |
+
for i, j in enumerate(reversed(p)):
|
2682 |
+
if mpm:
|
2683 |
+
j = sympify(j)._to_mpmath(mp.prec)
|
2684 |
+
sol_p += j * x0**i
|
2685 |
+
|
2686 |
+
for i, j in enumerate(reversed(q)):
|
2687 |
+
if mpm:
|
2688 |
+
j = sympify(j)._to_mpmath(mp.prec)
|
2689 |
+
sol_q += j * x0**i
|
2690 |
+
|
2691 |
+
if isinstance(sol_p, (PolyElement, FracElement)):
|
2692 |
+
sol_p = sol_p.as_expr()
|
2693 |
+
if isinstance(sol_q, (PolyElement, FracElement)):
|
2694 |
+
sol_q = sol_q.as_expr()
|
2695 |
+
|
2696 |
+
return sol_p / sol_q
|
2697 |
+
|
2698 |
+
|
2699 |
+
def _convert_poly_rat_alg(func, x, x0=0, y0=None, lenics=None, domain=QQ, initcond=True):
|
2700 |
+
"""
|
2701 |
+
Converts polynomials, rationals and algebraic functions to holonomic.
|
2702 |
+
"""
|
2703 |
+
|
2704 |
+
ispoly = func.is_polynomial()
|
2705 |
+
if not ispoly:
|
2706 |
+
israt = func.is_rational_function()
|
2707 |
+
else:
|
2708 |
+
israt = True
|
2709 |
+
|
2710 |
+
if not (ispoly or israt):
|
2711 |
+
basepoly, ratexp = func.as_base_exp()
|
2712 |
+
if basepoly.is_polynomial() and ratexp.is_Number:
|
2713 |
+
if isinstance(ratexp, Float):
|
2714 |
+
ratexp = nsimplify(ratexp)
|
2715 |
+
m, n = ratexp.p, ratexp.q
|
2716 |
+
is_alg = True
|
2717 |
+
else:
|
2718 |
+
is_alg = False
|
2719 |
+
else:
|
2720 |
+
is_alg = True
|
2721 |
+
|
2722 |
+
if not (ispoly or israt or is_alg):
|
2723 |
+
return None
|
2724 |
+
|
2725 |
+
R = domain.old_poly_ring(x)
|
2726 |
+
_, Dx = DifferentialOperators(R, 'Dx')
|
2727 |
+
|
2728 |
+
# if the function is constant
|
2729 |
+
if not func.has(x):
|
2730 |
+
return HolonomicFunction(Dx, x, 0, [func])
|
2731 |
+
|
2732 |
+
if ispoly:
|
2733 |
+
# differential equation satisfied by polynomial
|
2734 |
+
sol = func * Dx - func.diff(x)
|
2735 |
+
sol = _normalize(sol.listofpoly, sol.parent, negative=False)
|
2736 |
+
is_singular = sol.is_singular(x0)
|
2737 |
+
|
2738 |
+
# try to compute the conditions for singular points
|
2739 |
+
if y0 is None and x0 == 0 and is_singular:
|
2740 |
+
rep = R.from_sympy(func).rep
|
2741 |
+
for i, j in enumerate(reversed(rep)):
|
2742 |
+
if j == 0:
|
2743 |
+
continue
|
2744 |
+
else:
|
2745 |
+
coeff = list(reversed(rep))[i:]
|
2746 |
+
indicial = i
|
2747 |
+
break
|
2748 |
+
for i, j in enumerate(coeff):
|
2749 |
+
if isinstance(j, (PolyElement, FracElement)):
|
2750 |
+
coeff[i] = j.as_expr()
|
2751 |
+
y0 = {indicial: S(coeff)}
|
2752 |
+
|
2753 |
+
elif israt:
|
2754 |
+
p, q = func.as_numer_denom()
|
2755 |
+
# differential equation satisfied by rational
|
2756 |
+
sol = p * q * Dx + p * q.diff(x) - q * p.diff(x)
|
2757 |
+
sol = _normalize(sol.listofpoly, sol.parent, negative=False)
|
2758 |
+
|
2759 |
+
elif is_alg:
|
2760 |
+
sol = n * (x / m) * Dx - 1
|
2761 |
+
sol = HolonomicFunction(sol, x).composition(basepoly).annihilator
|
2762 |
+
is_singular = sol.is_singular(x0)
|
2763 |
+
|
2764 |
+
# try to compute the conditions for singular points
|
2765 |
+
if y0 is None and x0 == 0 and is_singular and \
|
2766 |
+
(lenics is None or lenics <= 1):
|
2767 |
+
rep = R.from_sympy(basepoly).rep
|
2768 |
+
for i, j in enumerate(reversed(rep)):
|
2769 |
+
if j == 0:
|
2770 |
+
continue
|
2771 |
+
if isinstance(j, (PolyElement, FracElement)):
|
2772 |
+
j = j.as_expr()
|
2773 |
+
|
2774 |
+
coeff = S(j)**ratexp
|
2775 |
+
indicial = S(i) * ratexp
|
2776 |
+
break
|
2777 |
+
if isinstance(coeff, (PolyElement, FracElement)):
|
2778 |
+
coeff = coeff.as_expr()
|
2779 |
+
y0 = {indicial: S([coeff])}
|
2780 |
+
|
2781 |
+
if y0 or not initcond:
|
2782 |
+
return HolonomicFunction(sol, x, x0, y0)
|
2783 |
+
|
2784 |
+
if not lenics:
|
2785 |
+
lenics = sol.order
|
2786 |
+
|
2787 |
+
if sol.is_singular(x0):
|
2788 |
+
r = HolonomicFunction(sol, x, x0)._indicial()
|
2789 |
+
l = list(r)
|
2790 |
+
if len(r) == 1 and r[l[0]] == S.One:
|
2791 |
+
r = l[0]
|
2792 |
+
g = func / (x - x0)**r
|
2793 |
+
singular_ics = _find_conditions(g, x, x0, lenics)
|
2794 |
+
singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)]
|
2795 |
+
y0 = {r:singular_ics}
|
2796 |
+
return HolonomicFunction(sol, x, x0, y0)
|
2797 |
+
|
2798 |
+
y0 = _find_conditions(func, x, x0, lenics)
|
2799 |
+
while not y0:
|
2800 |
+
x0 += 1
|
2801 |
+
y0 = _find_conditions(func, x, x0, lenics)
|
2802 |
+
|
2803 |
+
return HolonomicFunction(sol, x, x0, y0)
|
2804 |
+
|
2805 |
+
|
2806 |
+
def _convert_meijerint(func, x, initcond=True, domain=QQ):
|
2807 |
+
args = meijerint._rewrite1(func, x)
|
2808 |
+
|
2809 |
+
if args:
|
2810 |
+
fac, po, g, _ = args
|
2811 |
+
else:
|
2812 |
+
return None
|
2813 |
+
|
2814 |
+
# lists for sum of meijerg functions
|
2815 |
+
fac_list = [fac * i[0] for i in g]
|
2816 |
+
t = po.as_base_exp()
|
2817 |
+
s = t[1] if t[0] == x else S.Zero
|
2818 |
+
po_list = [s + i[1] for i in g]
|
2819 |
+
G_list = [i[2] for i in g]
|
2820 |
+
|
2821 |
+
# finds meijerg representation of x**s * meijerg(a1 ... ap, b1 ... bq, z)
|
2822 |
+
def _shift(func, s):
|
2823 |
+
z = func.args[-1]
|
2824 |
+
if z.has(I):
|
2825 |
+
z = z.subs(exp_polar, exp)
|
2826 |
+
|
2827 |
+
d = z.collect(x, evaluate=False)
|
2828 |
+
b = list(d)[0]
|
2829 |
+
a = d[b]
|
2830 |
+
|
2831 |
+
t = b.as_base_exp()
|
2832 |
+
b = t[1] if t[0] == x else S.Zero
|
2833 |
+
r = s / b
|
2834 |
+
an = (i + r for i in func.args[0][0])
|
2835 |
+
ap = (i + r for i in func.args[0][1])
|
2836 |
+
bm = (i + r for i in func.args[1][0])
|
2837 |
+
bq = (i + r for i in func.args[1][1])
|
2838 |
+
|
2839 |
+
return a**-r, meijerg((an, ap), (bm, bq), z)
|
2840 |
+
|
2841 |
+
coeff, m = _shift(G_list[0], po_list[0])
|
2842 |
+
sol = fac_list[0] * coeff * from_meijerg(m, initcond=initcond, domain=domain)
|
2843 |
+
|
2844 |
+
# add all the meijerg functions after converting to holonomic
|
2845 |
+
for i in range(1, len(G_list)):
|
2846 |
+
coeff, m = _shift(G_list[i], po_list[i])
|
2847 |
+
sol += fac_list[i] * coeff * from_meijerg(m, initcond=initcond, domain=domain)
|
2848 |
+
|
2849 |
+
return sol
|
2850 |
+
|
2851 |
+
|
2852 |
+
def _create_table(table, domain=QQ):
|
2853 |
+
"""
|
2854 |
+
Creates the look-up table. For a similar implementation
|
2855 |
+
see meijerint._create_lookup_table.
|
2856 |
+
"""
|
2857 |
+
|
2858 |
+
def add(formula, annihilator, arg, x0=0, y0=()):
|
2859 |
+
"""
|
2860 |
+
Adds a formula in the dictionary
|
2861 |
+
"""
|
2862 |
+
table.setdefault(_mytype(formula, x_1), []).append((formula,
|
2863 |
+
HolonomicFunction(annihilator, arg, x0, y0)))
|
2864 |
+
|
2865 |
+
R = domain.old_poly_ring(x_1)
|
2866 |
+
_, Dx = DifferentialOperators(R, 'Dx')
|
2867 |
+
|
2868 |
+
# add some basic functions
|
2869 |
+
add(sin(x_1), Dx**2 + 1, x_1, 0, [0, 1])
|
2870 |
+
add(cos(x_1), Dx**2 + 1, x_1, 0, [1, 0])
|
2871 |
+
add(exp(x_1), Dx - 1, x_1, 0, 1)
|
2872 |
+
add(log(x_1), Dx + x_1*Dx**2, x_1, 1, [0, 1])
|
2873 |
+
|
2874 |
+
add(erf(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)])
|
2875 |
+
add(erfc(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [1, -2/sqrt(pi)])
|
2876 |
+
add(erfi(x_1), -2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)])
|
2877 |
+
|
2878 |
+
add(sinh(x_1), Dx**2 - 1, x_1, 0, [0, 1])
|
2879 |
+
add(cosh(x_1), Dx**2 - 1, x_1, 0, [1, 0])
|
2880 |
+
|
2881 |
+
add(sinc(x_1), x_1 + 2*Dx + x_1*Dx**2, x_1)
|
2882 |
+
|
2883 |
+
add(Si(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
|
2884 |
+
add(Ci(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
|
2885 |
+
|
2886 |
+
add(Shi(x_1), -x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
|
2887 |
+
|
2888 |
+
|
2889 |
+
def _find_conditions(func, x, x0, order):
|
2890 |
+
y0 = []
|
2891 |
+
for i in range(order):
|
2892 |
+
val = func.subs(x, x0)
|
2893 |
+
if isinstance(val, NaN):
|
2894 |
+
val = limit(func, x, x0)
|
2895 |
+
if val.is_finite is False or isinstance(val, NaN):
|
2896 |
+
return None
|
2897 |
+
y0.append(val)
|
2898 |
+
func = func.diff(x)
|
2899 |
+
return y0
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/holonomicerrors.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Common Exceptions for `holonomic` module. """
|
2 |
+
|
3 |
+
class BaseHolonomicError(Exception):
|
4 |
+
|
5 |
+
def new(self, *args):
|
6 |
+
raise NotImplementedError("abstract base class")
|
7 |
+
|
8 |
+
class NotPowerSeriesError(BaseHolonomicError):
|
9 |
+
|
10 |
+
def __init__(self, holonomic, x0):
|
11 |
+
self.holonomic = holonomic
|
12 |
+
self.x0 = x0
|
13 |
+
|
14 |
+
def __str__(self):
|
15 |
+
s = 'A Power Series does not exists for '
|
16 |
+
s += str(self.holonomic)
|
17 |
+
s += ' about %s.' %self.x0
|
18 |
+
return s
|
19 |
+
|
20 |
+
class NotHolonomicError(BaseHolonomicError):
|
21 |
+
|
22 |
+
def __init__(self, m):
|
23 |
+
self.m = m
|
24 |
+
|
25 |
+
def __str__(self):
|
26 |
+
return self.m
|
27 |
+
|
28 |
+
class SingularityError(BaseHolonomicError):
|
29 |
+
|
30 |
+
def __init__(self, holonomic, x0):
|
31 |
+
self.holonomic = holonomic
|
32 |
+
self.x0 = x0
|
33 |
+
|
34 |
+
def __str__(self):
|
35 |
+
s = str(self.holonomic)
|
36 |
+
s += ' has a singularity at %s.' %self.x0
|
37 |
+
return s
|
38 |
+
|
39 |
+
class NotHyperSeriesError(BaseHolonomicError):
|
40 |
+
|
41 |
+
def __init__(self, holonomic, x0):
|
42 |
+
self.holonomic = holonomic
|
43 |
+
self.x0 = x0
|
44 |
+
|
45 |
+
def __str__(self):
|
46 |
+
s = 'Power series expansion of '
|
47 |
+
s += str(self.holonomic)
|
48 |
+
s += ' about %s is not hypergeometric' %self.x0
|
49 |
+
return s
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/numerical.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Numerical Methods for Holonomic Functions"""
|
2 |
+
|
3 |
+
from sympy.core.sympify import sympify
|
4 |
+
from sympy.holonomic.holonomic import DMFsubs
|
5 |
+
|
6 |
+
from mpmath import mp
|
7 |
+
|
8 |
+
|
9 |
+
def _evalf(func, points, derivatives=False, method='RK4'):
|
10 |
+
"""
|
11 |
+
Numerical methods for numerical integration along a given set of
|
12 |
+
points in the complex plane.
|
13 |
+
"""
|
14 |
+
|
15 |
+
ann = func.annihilator
|
16 |
+
a = ann.order
|
17 |
+
R = ann.parent.base
|
18 |
+
K = R.get_field()
|
19 |
+
|
20 |
+
if method == 'Euler':
|
21 |
+
meth = _euler
|
22 |
+
else:
|
23 |
+
meth = _rk4
|
24 |
+
|
25 |
+
dmf = []
|
26 |
+
for j in ann.listofpoly:
|
27 |
+
dmf.append(K.new(j.rep))
|
28 |
+
|
29 |
+
red = [-dmf[i] / dmf[a] for i in range(a)]
|
30 |
+
|
31 |
+
y0 = func.y0
|
32 |
+
if len(y0) < a:
|
33 |
+
raise TypeError("Not Enough Initial Conditions")
|
34 |
+
x0 = func.x0
|
35 |
+
sol = [meth(red, x0, points[0], y0, a)]
|
36 |
+
|
37 |
+
for i, j in enumerate(points[1:]):
|
38 |
+
sol.append(meth(red, points[i], j, sol[-1], a))
|
39 |
+
|
40 |
+
if not derivatives:
|
41 |
+
return [sympify(i[0]) for i in sol]
|
42 |
+
else:
|
43 |
+
return sympify(sol)
|
44 |
+
|
45 |
+
|
46 |
+
def _euler(red, x0, x1, y0, a):
|
47 |
+
"""
|
48 |
+
Euler's method for numerical integration.
|
49 |
+
From x0 to x1 with initial values given at x0 as vector y0.
|
50 |
+
"""
|
51 |
+
|
52 |
+
A = sympify(x0)._to_mpmath(mp.prec)
|
53 |
+
B = sympify(x1)._to_mpmath(mp.prec)
|
54 |
+
y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
|
55 |
+
h = B - A
|
56 |
+
f_0 = y_0[1:]
|
57 |
+
f_0_n = 0
|
58 |
+
|
59 |
+
for i in range(a):
|
60 |
+
f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
|
61 |
+
f_0.append(f_0_n)
|
62 |
+
|
63 |
+
sol = []
|
64 |
+
for i in range(a):
|
65 |
+
sol.append(y_0[i] + h * f_0[i])
|
66 |
+
|
67 |
+
return sol
|
68 |
+
|
69 |
+
|
70 |
+
def _rk4(red, x0, x1, y0, a):
|
71 |
+
"""
|
72 |
+
Runge-Kutta 4th order numerical method.
|
73 |
+
"""
|
74 |
+
|
75 |
+
A = sympify(x0)._to_mpmath(mp.prec)
|
76 |
+
B = sympify(x1)._to_mpmath(mp.prec)
|
77 |
+
y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
|
78 |
+
h = B - A
|
79 |
+
|
80 |
+
f_0_n = 0
|
81 |
+
f_1_n = 0
|
82 |
+
f_2_n = 0
|
83 |
+
f_3_n = 0
|
84 |
+
|
85 |
+
f_0 = y_0[1:]
|
86 |
+
for i in range(a):
|
87 |
+
f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
|
88 |
+
f_0.append(f_0_n)
|
89 |
+
|
90 |
+
f_1 = [y_0[i] + f_0[i]*h/2 for i in range(1, a)]
|
91 |
+
for i in range(a):
|
92 |
+
f_1_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2)
|
93 |
+
f_1.append(f_1_n)
|
94 |
+
|
95 |
+
f_2 = [y_0[i] + f_1[i]*h/2 for i in range(1, a)]
|
96 |
+
for i in range(a):
|
97 |
+
f_2_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2)
|
98 |
+
f_2.append(f_2_n)
|
99 |
+
|
100 |
+
f_3 = [y_0[i] + f_2[i]*h for i in range(1, a)]
|
101 |
+
for i in range(a):
|
102 |
+
f_3_n += sympify(DMFsubs(red[i], A + h, mpm=True))._to_mpmath(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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Recurrence Operators"""
|
2 |
+
|
3 |
+
from sympy.core.singleton import S
|
4 |
+
from sympy.core.symbol import (Symbol, symbols)
|
5 |
+
from sympy.printing import sstr
|
6 |
+
from sympy.core.sympify import sympify
|
7 |
+
|
8 |
+
|
9 |
+
def RecurrenceOperators(base, generator):
|
10 |
+
"""
|
11 |
+
Returns an Algebra of Recurrence Operators and the operator for
|
12 |
+
shifting i.e. the `Sn` operator.
|
13 |
+
The first argument needs to be the base polynomial ring for the algebra
|
14 |
+
and the second argument must be a generator which can be either a
|
15 |
+
noncommutative Symbol or a string.
|
16 |
+
|
17 |
+
Examples
|
18 |
+
========
|
19 |
+
|
20 |
+
>>> from sympy import ZZ
|
21 |
+
>>> from sympy import symbols
|
22 |
+
>>> from sympy.holonomic.recurrence import RecurrenceOperators
|
23 |
+
>>> n = symbols('n', integer=True)
|
24 |
+
>>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
|
25 |
+
"""
|
26 |
+
|
27 |
+
ring = RecurrenceOperatorAlgebra(base, generator)
|
28 |
+
return (ring, ring.shift_operator)
|
29 |
+
|
30 |
+
|
31 |
+
class RecurrenceOperatorAlgebra:
|
32 |
+
"""
|
33 |
+
A Recurrence Operator Algebra is a set of noncommutative polynomials
|
34 |
+
in intermediate `Sn` and coefficients in a base ring A. It follows the
|
35 |
+
commutation rule:
|
36 |
+
Sn * a(n) = a(n + 1) * Sn
|
37 |
+
|
38 |
+
This class represents a Recurrence Operator Algebra and serves as the parent ring
|
39 |
+
for Recurrence Operators.
|
40 |
+
|
41 |
+
Examples
|
42 |
+
========
|
43 |
+
|
44 |
+
>>> from sympy import ZZ
|
45 |
+
>>> from sympy import symbols
|
46 |
+
>>> from sympy.holonomic.recurrence import RecurrenceOperators
|
47 |
+
>>> n = symbols('n', integer=True)
|
48 |
+
>>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
|
49 |
+
>>> R
|
50 |
+
Univariate Recurrence Operator Algebra in intermediate Sn over the base ring
|
51 |
+
ZZ[n]
|
52 |
+
|
53 |
+
See Also
|
54 |
+
========
|
55 |
+
|
56 |
+
RecurrenceOperator
|
57 |
+
"""
|
58 |
+
|
59 |
+
def __init__(self, base, generator):
|
60 |
+
# the base ring for the algebra
|
61 |
+
self.base = base
|
62 |
+
# the operator representing shift i.e. `Sn`
|
63 |
+
self.shift_operator = RecurrenceOperator(
|
64 |
+
[base.zero, base.one], self)
|
65 |
+
|
66 |
+
if generator is None:
|
67 |
+
self.gen_symbol = symbols('Sn', commutative=False)
|
68 |
+
else:
|
69 |
+
if isinstance(generator, str):
|
70 |
+
self.gen_symbol = symbols(generator, commutative=False)
|
71 |
+
elif isinstance(generator, Symbol):
|
72 |
+
self.gen_symbol = generator
|
73 |
+
|
74 |
+
def __str__(self):
|
75 |
+
string = 'Univariate Recurrence Operator Algebra in intermediate '\
|
76 |
+
+ sstr(self.gen_symbol) + ' over the base ring ' + \
|
77 |
+
(self.base).__str__()
|
78 |
+
|
79 |
+
return string
|
80 |
+
|
81 |
+
__repr__ = __str__
|
82 |
+
|
83 |
+
def __eq__(self, other):
|
84 |
+
if self.base == other.base and self.gen_symbol == other.gen_symbol:
|
85 |
+
return True
|
86 |
+
else:
|
87 |
+
return False
|
88 |
+
|
89 |
+
|
90 |
+
def _add_lists(list1, list2):
|
91 |
+
if len(list1) <= len(list2):
|
92 |
+
sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):]
|
93 |
+
else:
|
94 |
+
sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):]
|
95 |
+
return sol
|
96 |
+
|
97 |
+
|
98 |
+
class RecurrenceOperator:
|
99 |
+
"""
|
100 |
+
The Recurrence Operators are defined by a list of polynomials
|
101 |
+
in the base ring and the parent ring of the Operator.
|
102 |
+
|
103 |
+
Explanation
|
104 |
+
===========
|
105 |
+
|
106 |
+
Takes a list of polynomials for each power of Sn and the
|
107 |
+
parent ring which must be an instance of RecurrenceOperatorAlgebra.
|
108 |
+
|
109 |
+
A Recurrence Operator can be created easily using
|
110 |
+
the operator `Sn`. See examples below.
|
111 |
+
|
112 |
+
Examples
|
113 |
+
========
|
114 |
+
|
115 |
+
>>> from sympy.holonomic.recurrence import RecurrenceOperator, RecurrenceOperators
|
116 |
+
>>> from sympy import ZZ
|
117 |
+
>>> from sympy import symbols
|
118 |
+
>>> n = symbols('n', integer=True)
|
119 |
+
>>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n),'Sn')
|
120 |
+
|
121 |
+
>>> RecurrenceOperator([0, 1, n**2], R)
|
122 |
+
(1)Sn + (n**2)Sn**2
|
123 |
+
|
124 |
+
>>> Sn*n
|
125 |
+
(n + 1)Sn
|
126 |
+
|
127 |
+
>>> n*Sn*n + 1 - Sn**2*n
|
128 |
+
(1) + (n**2 + n)Sn + (-n - 2)Sn**2
|
129 |
+
|
130 |
+
See Also
|
131 |
+
========
|
132 |
+
|
133 |
+
DifferentialOperatorAlgebra
|
134 |
+
"""
|
135 |
+
|
136 |
+
_op_priority = 20
|
137 |
+
|
138 |
+
def __init__(self, list_of_poly, parent):
|
139 |
+
# the parent ring for this operator
|
140 |
+
# must be an RecurrenceOperatorAlgebra object
|
141 |
+
self.parent = parent
|
142 |
+
# sequence of polynomials in n for each power of Sn
|
143 |
+
# represents the operator
|
144 |
+
# convert the expressions into ring elements using from_sympy
|
145 |
+
if isinstance(list_of_poly, list):
|
146 |
+
for i, j in enumerate(list_of_poly):
|
147 |
+
if isinstance(j, int):
|
148 |
+
list_of_poly[i] = self.parent.base.from_sympy(S(j))
|
149 |
+
elif not isinstance(j, self.parent.base.dtype):
|
150 |
+
list_of_poly[i] = self.parent.base.from_sympy(j)
|
151 |
+
|
152 |
+
self.listofpoly = list_of_poly
|
153 |
+
self.order = len(self.listofpoly) - 1
|
154 |
+
|
155 |
+
def __mul__(self, other):
|
156 |
+
"""
|
157 |
+
Multiplies two Operators and returns another
|
158 |
+
RecurrenceOperator instance using the commutation rule
|
159 |
+
Sn * a(n) = a(n + 1) * Sn
|
160 |
+
"""
|
161 |
+
|
162 |
+
listofself = self.listofpoly
|
163 |
+
base = self.parent.base
|
164 |
+
|
165 |
+
if not isinstance(other, RecurrenceOperator):
|
166 |
+
if not isinstance(other, self.parent.base.dtype):
|
167 |
+
listofother = [self.parent.base.from_sympy(sympify(other))]
|
168 |
+
|
169 |
+
else:
|
170 |
+
listofother = [other]
|
171 |
+
else:
|
172 |
+
listofother = other.listofpoly
|
173 |
+
# multiply a polynomial `b` with a list of polynomials
|
174 |
+
|
175 |
+
def _mul_dmp_diffop(b, listofother):
|
176 |
+
if isinstance(listofother, list):
|
177 |
+
sol = []
|
178 |
+
for i in listofother:
|
179 |
+
sol.append(i * b)
|
180 |
+
return sol
|
181 |
+
else:
|
182 |
+
return [b * listofother]
|
183 |
+
|
184 |
+
sol = _mul_dmp_diffop(listofself[0], listofother)
|
185 |
+
|
186 |
+
# compute Sn^i * b
|
187 |
+
def _mul_Sni_b(b):
|
188 |
+
sol = [base.zero]
|
189 |
+
|
190 |
+
if isinstance(b, list):
|
191 |
+
for i in b:
|
192 |
+
j = base.to_sympy(i).subs(base.gens[0], base.gens[0] + S.One)
|
193 |
+
sol.append(base.from_sympy(j))
|
194 |
+
|
195 |
+
else:
|
196 |
+
j = b.subs(base.gens[0], base.gens[0] + S.One)
|
197 |
+
sol.append(base.from_sympy(j))
|
198 |
+
|
199 |
+
return sol
|
200 |
+
|
201 |
+
for i in range(1, len(listofself)):
|
202 |
+
# find Sn^i * b in ith iteration
|
203 |
+
listofother = _mul_Sni_b(listofother)
|
204 |
+
# solution = solution + listofself[i] * (Sn^i * b)
|
205 |
+
sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother))
|
206 |
+
|
207 |
+
return RecurrenceOperator(sol, self.parent)
|
208 |
+
|
209 |
+
def __rmul__(self, other):
|
210 |
+
if not isinstance(other, RecurrenceOperator):
|
211 |
+
|
212 |
+
if isinstance(other, int):
|
213 |
+
other = S(other)
|
214 |
+
|
215 |
+
if not isinstance(other, self.parent.base.dtype):
|
216 |
+
other = (self.parent.base).from_sympy(other)
|
217 |
+
|
218 |
+
sol = []
|
219 |
+
for j in self.listofpoly:
|
220 |
+
sol.append(other * j)
|
221 |
+
|
222 |
+
return RecurrenceOperator(sol, self.parent)
|
223 |
+
|
224 |
+
def __add__(self, other):
|
225 |
+
if isinstance(other, RecurrenceOperator):
|
226 |
+
|
227 |
+
sol = _add_lists(self.listofpoly, other.listofpoly)
|
228 |
+
return RecurrenceOperator(sol, self.parent)
|
229 |
+
|
230 |
+
else:
|
231 |
+
|
232 |
+
if isinstance(other, int):
|
233 |
+
other = S(other)
|
234 |
+
list_self = self.listofpoly
|
235 |
+
if not isinstance(other, self.parent.base.dtype):
|
236 |
+
list_other = [((self.parent).base).from_sympy(other)]
|
237 |
+
else:
|
238 |
+
list_other = [other]
|
239 |
+
sol = []
|
240 |
+
sol.append(list_self[0] + list_other[0])
|
241 |
+
sol += list_self[1:]
|
242 |
+
|
243 |
+
return RecurrenceOperator(sol, self.parent)
|
244 |
+
|
245 |
+
__radd__ = __add__
|
246 |
+
|
247 |
+
def __sub__(self, other):
|
248 |
+
return self + (-1) * other
|
249 |
+
|
250 |
+
def __rsub__(self, other):
|
251 |
+
return (-1) * self + other
|
252 |
+
|
253 |
+
def __pow__(self, n):
|
254 |
+
if n == 1:
|
255 |
+
return self
|
256 |
+
if n == 0:
|
257 |
+
return RecurrenceOperator([self.parent.base.one], self.parent)
|
258 |
+
# if self is `Sn`
|
259 |
+
if self.listofpoly == self.parent.shift_operator.listofpoly:
|
260 |
+
sol = []
|
261 |
+
for i in range(0, n):
|
262 |
+
sol.append(self.parent.base.zero)
|
263 |
+
sol.append(self.parent.base.one)
|
264 |
+
|
265 |
+
return RecurrenceOperator(sol, self.parent)
|
266 |
+
|
267 |
+
else:
|
268 |
+
if n % 2 == 1:
|
269 |
+
powreduce = self**(n - 1)
|
270 |
+
return powreduce * self
|
271 |
+
elif n % 2 == 0:
|
272 |
+
powreduce = self**(n / 2)
|
273 |
+
return powreduce * powreduce
|
274 |
+
|
275 |
+
def __str__(self):
|
276 |
+
listofpoly = self.listofpoly
|
277 |
+
print_str = ''
|
278 |
+
|
279 |
+
for i, j in enumerate(listofpoly):
|
280 |
+
if j == self.parent.base.zero:
|
281 |
+
continue
|
282 |
+
|
283 |
+
if i == 0:
|
284 |
+
print_str += '(' + sstr(j) + ')'
|
285 |
+
continue
|
286 |
+
|
287 |
+
if print_str:
|
288 |
+
print_str += ' + '
|
289 |
+
|
290 |
+
if i == 1:
|
291 |
+
print_str += '(' + sstr(j) + ')Sn'
|
292 |
+
continue
|
293 |
+
|
294 |
+
print_str += '(' + sstr(j) + ')' + 'Sn**' + sstr(i)
|
295 |
+
|
296 |
+
return print_str
|
297 |
+
|
298 |
+
__repr__ = __str__
|
299 |
+
|
300 |
+
def __eq__(self, other):
|
301 |
+
if isinstance(other, RecurrenceOperator):
|
302 |
+
if self.listofpoly == other.listofpoly and self.parent == other.parent:
|
303 |
+
return True
|
304 |
+
else:
|
305 |
+
return False
|
306 |
+
else:
|
307 |
+
if self.listofpoly[0] == other:
|
308 |
+
for i in self.listofpoly[1:]:
|
309 |
+
if i is not self.parent.base.zero:
|
310 |
+
return False
|
311 |
+
return True
|
312 |
+
else:
|
313 |
+
return False
|
314 |
+
|
315 |
+
|
316 |
+
class HolonomicSequence:
|
317 |
+
"""
|
318 |
+
A Holonomic Sequence is a type of sequence satisfying a linear homogeneous
|
319 |
+
recurrence relation with Polynomial coefficients. Alternatively, A sequence
|
320 |
+
is Holonomic if and only if its generating function is a Holonomic Function.
|
321 |
+
"""
|
322 |
+
|
323 |
+
def __init__(self, recurrence, u0=[]):
|
324 |
+
self.recurrence = recurrence
|
325 |
+
if not isinstance(u0, list):
|
326 |
+
self.u0 = [u0]
|
327 |
+
else:
|
328 |
+
self.u0 = u0
|
329 |
+
|
330 |
+
if len(self.u0) == 0:
|
331 |
+
self._have_init_cond = False
|
332 |
+
else:
|
333 |
+
self._have_init_cond = True
|
334 |
+
self.n = recurrence.parent.base.gens[0]
|
335 |
+
|
336 |
+
def __repr__(self):
|
337 |
+
str_sol = 'HolonomicSequence(%s, %s)' % ((self.recurrence).__repr__(), sstr(self.n))
|
338 |
+
if not self._have_init_cond:
|
339 |
+
return str_sol
|
340 |
+
else:
|
341 |
+
cond_str = ''
|
342 |
+
seq_str = 0
|
343 |
+
for i in self.u0:
|
344 |
+
cond_str += ', u(%s) = %s' % (sstr(seq_str), sstr(i))
|
345 |
+
seq_str += 1
|
346 |
+
|
347 |
+
sol = str_sol + cond_str
|
348 |
+
return sol
|
349 |
+
|
350 |
+
__str__ = __repr__
|
351 |
+
|
352 |
+
def __eq__(self, other):
|
353 |
+
if self.recurrence == other.recurrence:
|
354 |
+
if self.n == other.n:
|
355 |
+
if self._have_init_cond and other._have_init_cond:
|
356 |
+
if self.u0 == other.u0:
|
357 |
+
return True
|
358 |
+
else:
|
359 |
+
return False
|
360 |
+
else:
|
361 |
+
return True
|
362 |
+
else:
|
363 |
+
return False
|
364 |
+
else:
|
365 |
+
return False
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (194 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-310.pyc
ADDED
Binary file (31.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-310.pyc
ADDED
Binary file (1.31 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/test_holonomic.py
ADDED
@@ -0,0 +1,830 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.holonomic import (DifferentialOperator, HolonomicFunction,
|
2 |
+
DifferentialOperators, from_hyper,
|
3 |
+
from_meijerg, expr_to_holonomic)
|
4 |
+
from sympy.holonomic.recurrence import RecurrenceOperators, HolonomicSequence
|
5 |
+
from sympy.core import EulerGamma
|
6 |
+
from sympy.core.numbers import (I, Rational, pi)
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.core.symbol import (Symbol, symbols)
|
9 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
10 |
+
from sympy.functions.elementary.hyperbolic import (asinh, cosh)
|
11 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
12 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
13 |
+
from sympy.functions.special.bessel import besselj
|
14 |
+
from sympy.functions.special.beta_functions import beta
|
15 |
+
from sympy.functions.special.error_functions import (Ci, Si, erf, erfc)
|
16 |
+
from sympy.functions.special.gamma_functions import gamma
|
17 |
+
from sympy.functions.special.hyper import (hyper, meijerg)
|
18 |
+
from sympy.printing.str import sstr
|
19 |
+
from sympy.series.order import O
|
20 |
+
from sympy.simplify.hyperexpand import hyperexpand
|
21 |
+
from sympy.polys.domains.integerring import ZZ
|
22 |
+
from sympy.polys.domains.rationalfield import QQ
|
23 |
+
from sympy.polys.domains.realfield import RR
|
24 |
+
|
25 |
+
|
26 |
+
def test_DifferentialOperator():
|
27 |
+
x = symbols('x')
|
28 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
29 |
+
assert Dx == R.derivative_operator
|
30 |
+
assert Dx == DifferentialOperator([R.base.zero, R.base.one], R)
|
31 |
+
assert x * Dx + x**2 * Dx**2 == DifferentialOperator([0, x, x**2], R)
|
32 |
+
assert (x**2 + 1) + Dx + x * \
|
33 |
+
Dx**5 == DifferentialOperator([x**2 + 1, 1, 0, 0, 0, x], R)
|
34 |
+
assert (x * Dx + x**2 + 1 - Dx * (x**3 + x))**3 == (-48 * x**6) + \
|
35 |
+
(-57 * x**7) * Dx + (-15 * x**8) * Dx**2 + (-x**9) * Dx**3
|
36 |
+
p = (x * Dx**2 + (x**2 + 3) * Dx**5) * (Dx + x**2)
|
37 |
+
q = (2 * x) + (4 * x**2) * Dx + (x**3) * Dx**2 + \
|
38 |
+
(20 * x**2 + x + 60) * Dx**3 + (10 * x**3 + 30 * x) * Dx**4 + \
|
39 |
+
(x**4 + 3 * x**2) * Dx**5 + (x**2 + 3) * Dx**6
|
40 |
+
assert p == q
|
41 |
+
|
42 |
+
|
43 |
+
def test_HolonomicFunction_addition():
|
44 |
+
x = symbols('x')
|
45 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
46 |
+
p = HolonomicFunction(Dx**2 * x, x)
|
47 |
+
q = HolonomicFunction((2) * Dx + (x) * Dx**2, x)
|
48 |
+
assert p == q
|
49 |
+
p = HolonomicFunction(x * Dx + 1, x)
|
50 |
+
q = HolonomicFunction(Dx + 1, x)
|
51 |
+
r = HolonomicFunction((x - 2) + (x**2 - 2) * Dx + (x**2 - x) * Dx**2, x)
|
52 |
+
assert p + q == r
|
53 |
+
p = HolonomicFunction(x * Dx + Dx**2 * (x**2 + 2), x)
|
54 |
+
q = HolonomicFunction(Dx - 3, x)
|
55 |
+
r = HolonomicFunction((-54 * x**2 - 126 * x - 150) + (-135 * x**3 - 252 * x**2 - 270 * x + 140) * Dx +\
|
56 |
+
(-27 * x**4 - 24 * x**2 + 14 * x - 150) * Dx**2 + \
|
57 |
+
(9 * x**4 + 15 * x**3 + 38 * x**2 + 30 * x +40) * Dx**3, x)
|
58 |
+
assert p + q == r
|
59 |
+
p = HolonomicFunction(Dx**5 - 1, x)
|
60 |
+
q = HolonomicFunction(x**3 + Dx, x)
|
61 |
+
r = HolonomicFunction((-x**18 + 45*x**14 - 525*x**10 + 1575*x**6 - x**3 - 630*x**2) + \
|
62 |
+
(-x**15 + 30*x**11 - 195*x**7 + 210*x**3 - 1)*Dx + (x**18 - 45*x**14 + 525*x**10 - \
|
63 |
+
1575*x**6 + x**3 + 630*x**2)*Dx**5 + (x**15 - 30*x**11 + 195*x**7 - 210*x**3 + \
|
64 |
+
1)*Dx**6, x)
|
65 |
+
assert p+q == r
|
66 |
+
|
67 |
+
p = x**2 + 3*x + 8
|
68 |
+
q = x**3 - 7*x + 5
|
69 |
+
p = p*Dx - p.diff()
|
70 |
+
q = q*Dx - q.diff()
|
71 |
+
r = HolonomicFunction(p, x) + HolonomicFunction(q, x)
|
72 |
+
s = HolonomicFunction((6*x**2 + 18*x + 14) + (-4*x**3 - 18*x**2 - 62*x + 10)*Dx +\
|
73 |
+
(x**4 + 6*x**3 + 31*x**2 - 10*x - 71)*Dx**2, x)
|
74 |
+
assert r == s
|
75 |
+
|
76 |
+
|
77 |
+
def test_HolonomicFunction_multiplication():
|
78 |
+
x = symbols('x')
|
79 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
80 |
+
p = HolonomicFunction(Dx+x+x*Dx**2, x)
|
81 |
+
q = HolonomicFunction(x*Dx+Dx*x+Dx**2, x)
|
82 |
+
r = HolonomicFunction((8*x**6 + 4*x**4 + 6*x**2 + 3) + (24*x**5 - 4*x**3 + 24*x)*Dx + \
|
83 |
+
(8*x**6 + 20*x**4 + 12*x**2 + 2)*Dx**2 + (8*x**5 + 4*x**3 + 4*x)*Dx**3 + \
|
84 |
+
(2*x**4 + x**2)*Dx**4, x)
|
85 |
+
assert p*q == r
|
86 |
+
p = HolonomicFunction(Dx**2+1, x)
|
87 |
+
q = HolonomicFunction(Dx-1, x)
|
88 |
+
r = HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x)
|
89 |
+
assert p*q == r
|
90 |
+
p = HolonomicFunction(Dx**2+1+x+Dx, x)
|
91 |
+
q = HolonomicFunction((Dx*x-1)**2, x)
|
92 |
+
r = HolonomicFunction((4*x**7 + 11*x**6 + 16*x**5 + 4*x**4 - 6*x**3 - 7*x**2 - 8*x - 2) + \
|
93 |
+
(8*x**6 + 26*x**5 + 24*x**4 - 3*x**3 - 11*x**2 - 6*x - 2)*Dx + \
|
94 |
+
(8*x**6 + 18*x**5 + 15*x**4 - 3*x**3 - 6*x**2 - 6*x - 2)*Dx**2 + (8*x**5 + \
|
95 |
+
10*x**4 + 6*x**3 - 2*x**2 - 4*x)*Dx**3 + (4*x**5 + 3*x**4 - x**2)*Dx**4, x)
|
96 |
+
assert p*q == r
|
97 |
+
p = HolonomicFunction(x*Dx**2-1, x)
|
98 |
+
q = HolonomicFunction(Dx*x-x, x)
|
99 |
+
r = HolonomicFunction((x - 3) + (-2*x + 2)*Dx + (x)*Dx**2, x)
|
100 |
+
assert p*q == r
|
101 |
+
|
102 |
+
|
103 |
+
def test_addition_initial_condition():
|
104 |
+
x = symbols('x')
|
105 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
106 |
+
p = HolonomicFunction(Dx-1, x, 0, [3])
|
107 |
+
q = HolonomicFunction(Dx**2+1, x, 0, [1, 0])
|
108 |
+
r = HolonomicFunction(-1 + Dx - Dx**2 + Dx**3, x, 0, [4, 3, 2])
|
109 |
+
assert p + q == r
|
110 |
+
p = HolonomicFunction(Dx - x + Dx**2, x, 0, [1, 2])
|
111 |
+
q = HolonomicFunction(Dx**2 + x, x, 0, [1, 0])
|
112 |
+
r = HolonomicFunction((-x**4 - x**3/4 - x**2 + Rational(1, 4)) + (x**3 + x**2/4 + x*Rational(3, 4) + 1)*Dx + \
|
113 |
+
(x*Rational(-3, 2) + Rational(7, 4))*Dx**2 + (x**2 - x*Rational(7, 4) + Rational(1, 4))*Dx**3 + (x**2 + x/4 + S.Half)*Dx**4, x, 0, [2, 2, -2, 2])
|
114 |
+
assert p + q == r
|
115 |
+
p = HolonomicFunction(Dx**2 + 4*x*Dx + x**2, x, 0, [3, 4])
|
116 |
+
q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1])
|
117 |
+
r = HolonomicFunction((x**6 + 2*x**4 - 5*x**2 - 6) + (4*x**5 + 36*x**3 - 32*x)*Dx + \
|
118 |
+
(x**6 + 3*x**4 + 5*x**2 - 9)*Dx**2 + (4*x**5 + 36*x**3 - 32*x)*Dx**3 + (x**4 + \
|
119 |
+
10*x**2 - 3)*Dx**4, x, 0, [4, 5, -1, -17])
|
120 |
+
assert p + q == r
|
121 |
+
q = HolonomicFunction(Dx**3 + x, x, 2, [3, 0, 1])
|
122 |
+
p = HolonomicFunction(Dx - 1, x, 2, [1])
|
123 |
+
r = HolonomicFunction((-x**2 - x + 1) + (x**2 + x)*Dx + (-x - 2)*Dx**3 + \
|
124 |
+
(x + 1)*Dx**4, x, 2, [4, 1, 2, -5 ])
|
125 |
+
assert p + q == r
|
126 |
+
p = expr_to_holonomic(sin(x))
|
127 |
+
q = expr_to_holonomic(1/x, x0=1)
|
128 |
+
r = HolonomicFunction((x**2 + 6) + (x**3 + 2*x)*Dx + (x**2 + 6)*Dx**2 + (x**3 + 2*x)*Dx**3, \
|
129 |
+
x, 1, [sin(1) + 1, -1 + cos(1), -sin(1) + 2])
|
130 |
+
assert p + q == r
|
131 |
+
C_1 = symbols('C_1')
|
132 |
+
p = expr_to_holonomic(sqrt(x))
|
133 |
+
q = expr_to_holonomic(sqrt(x**2-x))
|
134 |
+
r = (p + q).to_expr().subs(C_1, -I/2).expand()
|
135 |
+
assert r == I*sqrt(x)*sqrt(-x + 1) + sqrt(x)
|
136 |
+
|
137 |
+
|
138 |
+
def test_multiplication_initial_condition():
|
139 |
+
x = symbols('x')
|
140 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
141 |
+
p = HolonomicFunction(Dx**2 + x*Dx - 1, x, 0, [3, 1])
|
142 |
+
q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1])
|
143 |
+
r = HolonomicFunction((x**4 + 14*x**2 + 60) + 4*x*Dx + (x**4 + 9*x**2 + 20)*Dx**2 + \
|
144 |
+
(2*x**3 + 18*x)*Dx**3 + (x**2 + 10)*Dx**4, x, 0, [3, 4, 2, 3])
|
145 |
+
assert p * q == r
|
146 |
+
p = HolonomicFunction(Dx**2 + x, x, 0, [1, 0])
|
147 |
+
q = HolonomicFunction(Dx**3 - x**2, x, 0, [3, 3, 3])
|
148 |
+
r = HolonomicFunction((x**8 - 37*x**7/27 - 10*x**6/27 - 164*x**5/9 - 184*x**4/9 + \
|
149 |
+
160*x**3/27 + 404*x**2/9 + 8*x + Rational(40, 3)) + (6*x**7 - 128*x**6/9 - 98*x**5/9 - 28*x**4/9 + \
|
150 |
+
8*x**3/9 + 28*x**2 + x*Rational(40, 9) - 40)*Dx + (3*x**6 - 82*x**5/9 + 76*x**4/9 + 4*x**3/3 + \
|
151 |
+
220*x**2/9 - x*Rational(80, 3))*Dx**2 + (-2*x**6 + 128*x**5/27 - 2*x**4/3 -80*x**2/9 + Rational(200, 9))*Dx**3 + \
|
152 |
+
(3*x**5 - 64*x**4/9 - 28*x**3/9 + 6*x**2 - x*Rational(20, 9) - Rational(20, 3))*Dx**4 + (-4*x**3 + 64*x**2/9 + \
|
153 |
+
x*Rational(8, 3))*Dx**5 + (x**4 - 64*x**3/27 - 4*x**2/3 + Rational(20, 9))*Dx**6, x, 0, [3, 3, 3, -3, -12, -24])
|
154 |
+
assert p * q == r
|
155 |
+
p = HolonomicFunction(Dx - 1, x, 0, [2])
|
156 |
+
q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])
|
157 |
+
r = HolonomicFunction(2 -2*Dx + Dx**2, x, 0, [0, 2])
|
158 |
+
assert p * q == r
|
159 |
+
q = HolonomicFunction(x*Dx**2 + 1 + 2*Dx, x, 0,[0, 1])
|
160 |
+
r = HolonomicFunction((x - 1) + (-2*x + 2)*Dx + x*Dx**2, x, 0, [0, 2])
|
161 |
+
assert p * q == r
|
162 |
+
p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 3])
|
163 |
+
q = HolonomicFunction(Dx**3 + 1, x, 0, [1, 2, 1])
|
164 |
+
r = HolonomicFunction(6*Dx + 3*Dx**2 + 2*Dx**3 - 3*Dx**4 + Dx**6, x, 0, [1, 5, 14, 17, 17, 2])
|
165 |
+
assert p * q == r
|
166 |
+
p = expr_to_holonomic(sin(x))
|
167 |
+
q = expr_to_holonomic(1/x, x0=1)
|
168 |
+
r = HolonomicFunction(x + 2*Dx + x*Dx**2, x, 1, [sin(1), -sin(1) + cos(1)])
|
169 |
+
assert p * q == r
|
170 |
+
p = expr_to_holonomic(sqrt(x))
|
171 |
+
q = expr_to_holonomic(sqrt(x**2-x))
|
172 |
+
r = (p * q).to_expr()
|
173 |
+
assert r == I*x*sqrt(-x + 1)
|
174 |
+
|
175 |
+
|
176 |
+
def test_HolonomicFunction_composition():
|
177 |
+
x = symbols('x')
|
178 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
179 |
+
p = HolonomicFunction(Dx-1, x).composition(x**2+x)
|
180 |
+
r = HolonomicFunction((-2*x - 1) + Dx, x)
|
181 |
+
assert p == r
|
182 |
+
p = HolonomicFunction(Dx**2+1, x).composition(x**5+x**2+1)
|
183 |
+
r = HolonomicFunction((125*x**12 + 150*x**9 + 60*x**6 + 8*x**3) + (-20*x**3 - 2)*Dx + \
|
184 |
+
(5*x**4 + 2*x)*Dx**2, x)
|
185 |
+
assert p == r
|
186 |
+
p = HolonomicFunction(Dx**2*x+x, x).composition(2*x**3+x**2+1)
|
187 |
+
r = HolonomicFunction((216*x**9 + 324*x**8 + 180*x**7 + 152*x**6 + 112*x**5 + \
|
188 |
+
36*x**4 + 4*x**3) + (24*x**4 + 16*x**3 + 3*x**2 - 6*x - 1)*Dx + (6*x**5 + 5*x**4 + \
|
189 |
+
x**3 + 3*x**2 + x)*Dx**2, x)
|
190 |
+
assert p == r
|
191 |
+
p = HolonomicFunction(Dx**2+1, x).composition(1-x**2)
|
192 |
+
r = HolonomicFunction((4*x**3) - Dx + x*Dx**2, x)
|
193 |
+
assert p == r
|
194 |
+
p = HolonomicFunction(Dx**2+1, x).composition(x - 2/(x**2 + 1))
|
195 |
+
r = HolonomicFunction((x**12 + 6*x**10 + 12*x**9 + 15*x**8 + 48*x**7 + 68*x**6 + \
|
196 |
+
72*x**5 + 111*x**4 + 112*x**3 + 54*x**2 + 12*x + 1) + (12*x**8 + 32*x**6 + \
|
197 |
+
24*x**4 - 4)*Dx + (x**12 + 6*x**10 + 4*x**9 + 15*x**8 + 16*x**7 + 20*x**6 + 24*x**5+ \
|
198 |
+
15*x**4 + 16*x**3 + 6*x**2 + 4*x + 1)*Dx**2, x)
|
199 |
+
assert p == r
|
200 |
+
|
201 |
+
|
202 |
+
def test_from_hyper():
|
203 |
+
x = symbols('x')
|
204 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
205 |
+
p = hyper([1, 1], [Rational(3, 2)], x**2/4)
|
206 |
+
q = HolonomicFunction((4*x) + (5*x**2 - 8)*Dx + (x**3 - 4*x)*Dx**2, x, 1, [2*sqrt(3)*pi/9, -4*sqrt(3)*pi/27 + Rational(4, 3)])
|
207 |
+
r = from_hyper(p)
|
208 |
+
assert r == q
|
209 |
+
p = from_hyper(hyper([1], [Rational(3, 2)], x**2/4))
|
210 |
+
q = HolonomicFunction(-x + (-x**2/2 + 2)*Dx + x*Dx**2, x)
|
211 |
+
# x0 = 1
|
212 |
+
y0 = '[sqrt(pi)*exp(1/4)*erf(1/2), -sqrt(pi)*exp(1/4)*erf(1/2)/2 + 1]'
|
213 |
+
assert sstr(p.y0) == y0
|
214 |
+
assert q.annihilator == p.annihilator
|
215 |
+
|
216 |
+
|
217 |
+
def test_from_meijerg():
|
218 |
+
x = symbols('x')
|
219 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
220 |
+
p = from_meijerg(meijerg(([], [Rational(3, 2)]), ([S.Half], [S.Half, 1]), x))
|
221 |
+
q = HolonomicFunction(x/2 - Rational(1, 4) + (-x**2 + x/4)*Dx + x**2*Dx**2 + x**3*Dx**3, x, 1, \
|
222 |
+
[1/sqrt(pi), 1/(2*sqrt(pi)), -1/(4*sqrt(pi))])
|
223 |
+
assert p == q
|
224 |
+
p = from_meijerg(meijerg(([], []), ([0], []), x))
|
225 |
+
q = HolonomicFunction(1 + Dx, x, 0, [1])
|
226 |
+
assert p == q
|
227 |
+
p = from_meijerg(meijerg(([1], []), ([S.Half], [0]), x))
|
228 |
+
q = HolonomicFunction((x + S.Half)*Dx + x*Dx**2, x, 1, [sqrt(pi)*erf(1), exp(-1)])
|
229 |
+
assert p == q
|
230 |
+
p = from_meijerg(meijerg(([0], [1]), ([0], []), 2*x**2))
|
231 |
+
q = HolonomicFunction((3*x**2 - 1)*Dx + x**3*Dx**2, x, 1, [-exp(Rational(-1, 2)) + 1, -exp(Rational(-1, 2))])
|
232 |
+
assert p == q
|
233 |
+
|
234 |
+
|
235 |
+
def test_to_Sequence():
|
236 |
+
x = symbols('x')
|
237 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
238 |
+
n = symbols('n', integer=True)
|
239 |
+
_, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
|
240 |
+
p = HolonomicFunction(x**2*Dx**4 + x + Dx, x).to_sequence()
|
241 |
+
q = [(HolonomicSequence(1 + (n + 2)*Sn**2 + (n**4 + 6*n**3 + 11*n**2 + 6*n)*Sn**3), 0, 1)]
|
242 |
+
assert p == q
|
243 |
+
p = HolonomicFunction(x**2*Dx**4 + x**3 + Dx**2, x).to_sequence()
|
244 |
+
q = [(HolonomicSequence(1 + (n**4 + 14*n**3 + 72*n**2 + 163*n + 140)*Sn**5), 0, 0)]
|
245 |
+
assert p == q
|
246 |
+
p = HolonomicFunction(x**3*Dx**4 + 1 + Dx**2, x).to_sequence()
|
247 |
+
q = [(HolonomicSequence(1 + (n**4 - 2*n**3 - n**2 + 2*n)*Sn + (n**2 + 3*n + 2)*Sn**2), 0, 0)]
|
248 |
+
assert p == q
|
249 |
+
p = HolonomicFunction(3*x**3*Dx**4 + 2*x*Dx + x*Dx**3, x).to_sequence()
|
250 |
+
q = [(HolonomicSequence(2*n + (3*n**4 - 6*n**3 - 3*n**2 + 6*n)*Sn + (n**3 + 3*n**2 + 2*n)*Sn**2), 0, 1)]
|
251 |
+
assert p == q
|
252 |
+
|
253 |
+
|
254 |
+
def test_to_Sequence_Initial_Coniditons():
|
255 |
+
x = symbols('x')
|
256 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
257 |
+
n = symbols('n', integer=True)
|
258 |
+
_, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
|
259 |
+
p = HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence()
|
260 |
+
q = [(HolonomicSequence(-1 + (n + 1)*Sn, 1), 0)]
|
261 |
+
assert p == q
|
262 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_sequence()
|
263 |
+
q = [(HolonomicSequence(1 + (n**2 + 3*n + 2)*Sn**2, [0, 1]), 0)]
|
264 |
+
assert p == q
|
265 |
+
p = HolonomicFunction(Dx**2 + 1 + x**3*Dx, x, 0, [2, 3]).to_sequence()
|
266 |
+
q = [(HolonomicSequence(n + Sn**2 + (n**2 + 7*n + 12)*Sn**4, [2, 3, -1, Rational(-1, 2), Rational(1, 12)]), 1)]
|
267 |
+
assert p == q
|
268 |
+
p = HolonomicFunction(x**3*Dx**5 + 1 + Dx, x).to_sequence()
|
269 |
+
q = [(HolonomicSequence(1 + (n + 1)*Sn + (n**5 - 5*n**3 + 4*n)*Sn**2), 0, 3)]
|
270 |
+
assert p == q
|
271 |
+
C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3')
|
272 |
+
p = expr_to_holonomic(log(1+x**2))
|
273 |
+
q = [(HolonomicSequence(n**2 + (n**2 + 2*n)*Sn**2, [0, 0, C_2]), 0, 1)]
|
274 |
+
assert p.to_sequence() == q
|
275 |
+
p = p.diff()
|
276 |
+
q = [(HolonomicSequence((n + 2) + (n + 2)*Sn**2, [C_0, 0]), 1, 0)]
|
277 |
+
assert p.to_sequence() == q
|
278 |
+
p = expr_to_holonomic(erf(x) + x).to_sequence()
|
279 |
+
q = [(HolonomicSequence((2*n**2 - 2*n) + (n**3 + 2*n**2 - n - 2)*Sn**2, [0, 1 + 2/sqrt(pi), 0, C_3]), 0, 2)]
|
280 |
+
assert p == q
|
281 |
+
|
282 |
+
def test_series():
|
283 |
+
x = symbols('x')
|
284 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
285 |
+
p = HolonomicFunction(Dx**2 + 2*x*Dx, x, 0, [0, 1]).series(n=10)
|
286 |
+
q = x - x**3/3 + x**5/10 - x**7/42 + x**9/216 + O(x**10)
|
287 |
+
assert p == q
|
288 |
+
p = HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2)
|
289 |
+
q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]) # cos(x)
|
290 |
+
r = (p * q).series(n=10) # expansion of cos(x) * exp(x**2)
|
291 |
+
s = 1 + x**2/2 + x**4/24 - 31*x**6/720 - 179*x**8/8064 + O(x**10)
|
292 |
+
assert r == s
|
293 |
+
t = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]) # log(1 + x)
|
294 |
+
r = (p * t + q).series(n=10)
|
295 |
+
s = 1 + x - x**2 + 4*x**3/3 - 17*x**4/24 + 31*x**5/30 - 481*x**6/720 +\
|
296 |
+
71*x**7/105 - 20159*x**8/40320 + 379*x**9/840 + O(x**10)
|
297 |
+
assert r == s
|
298 |
+
p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \
|
299 |
+
(4-6*x**3+2*x**4)*Dx**2, x, 0, [0, 1]).series(n=7)
|
300 |
+
q = x + x**3/6 - 3*x**4/16 + x**5/20 - 23*x**6/960 + O(x**7)
|
301 |
+
assert p == q
|
302 |
+
p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \
|
303 |
+
(4-6*x**3+2*x**4)*Dx**2, x, 0, [1, 0]).series(n=7)
|
304 |
+
q = 1 - 3*x**2/4 - x**3/4 - 5*x**4/32 - 3*x**5/40 - 17*x**6/384 + O(x**7)
|
305 |
+
assert p == q
|
306 |
+
p = expr_to_holonomic(erf(x) + x).series(n=10)
|
307 |
+
C_3 = symbols('C_3')
|
308 |
+
q = (erf(x) + x).series(n=10)
|
309 |
+
assert p.subs(C_3, -2/(3*sqrt(pi))) == q
|
310 |
+
assert expr_to_holonomic(sqrt(x**3 + x)).series(n=10) == sqrt(x**3 + x).series(n=10)
|
311 |
+
assert expr_to_holonomic((2*x - 3*x**2)**Rational(1, 3)).series() == ((2*x - 3*x**2)**Rational(1, 3)).series()
|
312 |
+
assert expr_to_holonomic(sqrt(x**2-x)).series() == (sqrt(x**2-x)).series()
|
313 |
+
assert expr_to_holonomic(cos(x)**2/x**2, y0={-2: [1, 0, -1]}).series(n=10) == (cos(x)**2/x**2).series(n=10)
|
314 |
+
assert expr_to_holonomic(cos(x)**2/x**2, x0=1).series(n=10).together() == (cos(x)**2/x**2).series(n=10, x0=1).together()
|
315 |
+
assert expr_to_holonomic(cos(x-1)**2/(x-1)**2, x0=1, y0={-2: [1, 0, -1]}).series(n=10) \
|
316 |
+
== (cos(x-1)**2/(x-1)**2).series(x0=1, n=10)
|
317 |
+
|
318 |
+
def test_evalf_euler():
|
319 |
+
x = symbols('x')
|
320 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
321 |
+
|
322 |
+
# log(1+x)
|
323 |
+
p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1])
|
324 |
+
|
325 |
+
# path taken is a straight line from 0 to 1, on the real axis
|
326 |
+
r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
|
327 |
+
s = '0.699525841805253' # approx. equal to log(2) i.e. 0.693147180559945
|
328 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
329 |
+
|
330 |
+
# path taken is a triangle 0-->1+i-->2
|
331 |
+
r = [0.1 + 0.1*I]
|
332 |
+
for i in range(9):
|
333 |
+
r.append(r[-1]+0.1+0.1*I)
|
334 |
+
for i in range(10):
|
335 |
+
r.append(r[-1]+0.1-0.1*I)
|
336 |
+
|
337 |
+
# close to the exact solution 1.09861228866811
|
338 |
+
# imaginary part also close to zero
|
339 |
+
s = '1.07530466271334 - 0.0251200594793912*I'
|
340 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
341 |
+
|
342 |
+
# sin(x)
|
343 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])
|
344 |
+
s = '0.905546532085401 - 6.93889390390723e-18*I'
|
345 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
346 |
+
|
347 |
+
# computing sin(pi/2) using this method
|
348 |
+
# using a linear path from 0 to pi/2
|
349 |
+
r = [0.1]
|
350 |
+
for i in range(14):
|
351 |
+
r.append(r[-1] + 0.1)
|
352 |
+
r.append(pi/2)
|
353 |
+
s = '1.08016557252834' # close to 1.0 (exact solution)
|
354 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
355 |
+
|
356 |
+
# trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2)
|
357 |
+
# computing the same value sin(pi/2) using different path
|
358 |
+
r = [0.1*I]
|
359 |
+
for i in range(9):
|
360 |
+
r.append(r[-1]+0.1*I)
|
361 |
+
for i in range(15):
|
362 |
+
r.append(r[-1]+0.1)
|
363 |
+
r.append(pi/2+I)
|
364 |
+
for i in range(10):
|
365 |
+
r.append(r[-1]-0.1*I)
|
366 |
+
|
367 |
+
# close to 1.0
|
368 |
+
s = '0.976882381836257 - 1.65557671738537e-16*I'
|
369 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
370 |
+
|
371 |
+
# cos(x)
|
372 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0])
|
373 |
+
# compute cos(pi) along 0-->pi
|
374 |
+
r = [0.05]
|
375 |
+
for i in range(61):
|
376 |
+
r.append(r[-1]+0.05)
|
377 |
+
r.append(pi)
|
378 |
+
# close to -1 (exact answer)
|
379 |
+
s = '-1.08140824719196'
|
380 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
381 |
+
|
382 |
+
# a rectangular path (0 -> i -> 2+i -> 2)
|
383 |
+
r = [0.1*I]
|
384 |
+
for i in range(9):
|
385 |
+
r.append(r[-1]+0.1*I)
|
386 |
+
for i in range(20):
|
387 |
+
r.append(r[-1]+0.1)
|
388 |
+
for i in range(10):
|
389 |
+
r.append(r[-1]-0.1*I)
|
390 |
+
|
391 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r, method='Euler')
|
392 |
+
s = '0.501421652861245 - 3.88578058618805e-16*I'
|
393 |
+
assert sstr(p[-1]) == s
|
394 |
+
|
395 |
+
def test_evalf_rk4():
|
396 |
+
x = symbols('x')
|
397 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
398 |
+
|
399 |
+
# log(1+x)
|
400 |
+
p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1])
|
401 |
+
|
402 |
+
# path taken is a straight line from 0 to 1, on the real axis
|
403 |
+
r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
|
404 |
+
s = '0.693146363174626' # approx. equal to log(2) i.e. 0.693147180559945
|
405 |
+
assert sstr(p.evalf(r)[-1]) == s
|
406 |
+
|
407 |
+
# path taken is a triangle 0-->1+i-->2
|
408 |
+
r = [0.1 + 0.1*I]
|
409 |
+
for i in range(9):
|
410 |
+
r.append(r[-1]+0.1+0.1*I)
|
411 |
+
for i in range(10):
|
412 |
+
r.append(r[-1]+0.1-0.1*I)
|
413 |
+
|
414 |
+
# close to the exact solution 1.09861228866811
|
415 |
+
# imaginary part also close to zero
|
416 |
+
s = '1.098616 + 1.36083e-7*I'
|
417 |
+
assert sstr(p.evalf(r)[-1].n(7)) == s
|
418 |
+
|
419 |
+
# sin(x)
|
420 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])
|
421 |
+
s = '0.90929463522785 + 1.52655665885959e-16*I'
|
422 |
+
assert sstr(p.evalf(r)[-1]) == s
|
423 |
+
|
424 |
+
# computing sin(pi/2) using this method
|
425 |
+
# using a linear path from 0 to pi/2
|
426 |
+
r = [0.1]
|
427 |
+
for i in range(14):
|
428 |
+
r.append(r[-1] + 0.1)
|
429 |
+
r.append(pi/2)
|
430 |
+
s = '0.999999895088917' # close to 1.0 (exact solution)
|
431 |
+
assert sstr(p.evalf(r)[-1]) == s
|
432 |
+
|
433 |
+
# trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2)
|
434 |
+
# computing the same value sin(pi/2) using different path
|
435 |
+
r = [0.1*I]
|
436 |
+
for i in range(9):
|
437 |
+
r.append(r[-1]+0.1*I)
|
438 |
+
for i in range(15):
|
439 |
+
r.append(r[-1]+0.1)
|
440 |
+
r.append(pi/2+I)
|
441 |
+
for i in range(10):
|
442 |
+
r.append(r[-1]-0.1*I)
|
443 |
+
|
444 |
+
# close to 1.0
|
445 |
+
s = '1.00000003415141 + 6.11940487991086e-16*I'
|
446 |
+
assert sstr(p.evalf(r)[-1]) == s
|
447 |
+
|
448 |
+
# cos(x)
|
449 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0])
|
450 |
+
# compute cos(pi) along 0-->pi
|
451 |
+
r = [0.05]
|
452 |
+
for i in range(61):
|
453 |
+
r.append(r[-1]+0.05)
|
454 |
+
r.append(pi)
|
455 |
+
# close to -1 (exact answer)
|
456 |
+
s = '-0.999999993238714'
|
457 |
+
assert sstr(p.evalf(r)[-1]) == s
|
458 |
+
|
459 |
+
# a rectangular path (0 -> i -> 2+i -> 2)
|
460 |
+
r = [0.1*I]
|
461 |
+
for i in range(9):
|
462 |
+
r.append(r[-1]+0.1*I)
|
463 |
+
for i in range(20):
|
464 |
+
r.append(r[-1]+0.1)
|
465 |
+
for i in range(10):
|
466 |
+
r.append(r[-1]-0.1*I)
|
467 |
+
|
468 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r)
|
469 |
+
s = '0.493152791638442 - 1.41553435639707e-15*I'
|
470 |
+
assert sstr(p[-1]) == s
|
471 |
+
|
472 |
+
|
473 |
+
def test_expr_to_holonomic():
|
474 |
+
x = symbols('x')
|
475 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
476 |
+
p = expr_to_holonomic((sin(x)/x)**2)
|
477 |
+
q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 0, \
|
478 |
+
[1, 0, Rational(-2, 3)])
|
479 |
+
assert p == q
|
480 |
+
p = expr_to_holonomic(1/(1+x**2)**2)
|
481 |
+
q = HolonomicFunction(4*x + (x**2 + 1)*Dx, x, 0, [1])
|
482 |
+
assert p == q
|
483 |
+
p = expr_to_holonomic(exp(x)*sin(x)+x*log(1+x))
|
484 |
+
q = HolonomicFunction((2*x**3 + 10*x**2 + 20*x + 18) + (-2*x**4 - 10*x**3 - 20*x**2 \
|
485 |
+
- 18*x)*Dx + (2*x**5 + 6*x**4 + 7*x**3 + 8*x**2 + 10*x - 4)*Dx**2 + \
|
486 |
+
(-2*x**5 - 5*x**4 - 2*x**3 + 2*x**2 - x + 4)*Dx**3 + (x**5 + 2*x**4 - x**3 - \
|
487 |
+
7*x**2/2 + x + Rational(5, 2))*Dx**4, x, 0, [0, 1, 4, -1])
|
488 |
+
assert p == q
|
489 |
+
p = expr_to_holonomic(x*exp(x)+cos(x)+1)
|
490 |
+
q = HolonomicFunction((-x - 3)*Dx + (x + 2)*Dx**2 + (-x - 3)*Dx**3 + (x + 2)*Dx**4, x, \
|
491 |
+
0, [2, 1, 1, 3])
|
492 |
+
assert p == q
|
493 |
+
assert (x*exp(x)+cos(x)+1).series(n=10) == p.series(n=10)
|
494 |
+
p = expr_to_holonomic(log(1 + x)**2 + 1)
|
495 |
+
q = HolonomicFunction(Dx + (3*x + 3)*Dx**2 + (x**2 + 2*x + 1)*Dx**3, x, 0, [1, 0, 2])
|
496 |
+
assert p == q
|
497 |
+
p = expr_to_holonomic(erf(x)**2 + x)
|
498 |
+
q = HolonomicFunction((8*x**4 - 2*x**2 + 2)*Dx**2 + (6*x**3 - x/2)*Dx**3 + \
|
499 |
+
(x**2+ Rational(1, 4))*Dx**4, x, 0, [0, 1, 8/pi, 0])
|
500 |
+
assert p == q
|
501 |
+
p = expr_to_holonomic(cosh(x)*x)
|
502 |
+
q = HolonomicFunction((-x**2 + 2) -2*x*Dx + x**2*Dx**2, x, 0, [0, 1])
|
503 |
+
assert p == q
|
504 |
+
p = expr_to_holonomic(besselj(2, x))
|
505 |
+
q = HolonomicFunction((x**2 - 4) + x*Dx + x**2*Dx**2, x, 0, [0, 0])
|
506 |
+
assert p == q
|
507 |
+
p = expr_to_holonomic(besselj(0, x) + exp(x))
|
508 |
+
q = HolonomicFunction((-x**2 - x/2 + S.Half) + (x**2 - x/2 - Rational(3, 2))*Dx + (-x**2 + x/2 + 1)*Dx**2 +\
|
509 |
+
(x**2 + x/2)*Dx**3, x, 0, [2, 1, S.Half])
|
510 |
+
assert p == q
|
511 |
+
p = expr_to_holonomic(sin(x)**2/x)
|
512 |
+
q = HolonomicFunction(4 + 4*x*Dx + 3*Dx**2 + x*Dx**3, x, 0, [0, 1, 0])
|
513 |
+
assert p == q
|
514 |
+
p = expr_to_holonomic(sin(x)**2/x, x0=2)
|
515 |
+
q = HolonomicFunction((4) + (4*x)*Dx + (3)*Dx**2 + (x)*Dx**3, x, 2, [sin(2)**2/2,
|
516 |
+
sin(2)*cos(2) - sin(2)**2/4, -3*sin(2)**2/4 + cos(2)**2 - sin(2)*cos(2)])
|
517 |
+
assert p == q
|
518 |
+
p = expr_to_holonomic(log(x)/2 - Ci(2*x)/2 + Ci(2)/2)
|
519 |
+
q = HolonomicFunction(4*Dx + 4*x*Dx**2 + 3*Dx**3 + x*Dx**4, x, 0, \
|
520 |
+
[-log(2)/2 - EulerGamma/2 + Ci(2)/2, 0, 1, 0])
|
521 |
+
assert p == q
|
522 |
+
p = p.to_expr()
|
523 |
+
q = log(x)/2 - Ci(2*x)/2 + Ci(2)/2
|
524 |
+
assert p == q
|
525 |
+
p = expr_to_holonomic(x**S.Half, x0=1)
|
526 |
+
q = HolonomicFunction(x*Dx - S.Half, x, 1, [1])
|
527 |
+
assert p == q
|
528 |
+
p = expr_to_holonomic(sqrt(1 + x**2))
|
529 |
+
q = HolonomicFunction((-x) + (x**2 + 1)*Dx, x, 0, [1])
|
530 |
+
assert p == q
|
531 |
+
assert (expr_to_holonomic(sqrt(x) + sqrt(2*x)).to_expr()-\
|
532 |
+
(sqrt(x) + sqrt(2*x))).simplify() == 0
|
533 |
+
assert expr_to_holonomic(3*x+2*sqrt(x)).to_expr() == 3*x+2*sqrt(x)
|
534 |
+
p = expr_to_holonomic((x**4+x**3+5*x**2+3*x+2)/x**2, lenics=3)
|
535 |
+
q = HolonomicFunction((-2*x**4 - x**3 + 3*x + 4) + (x**5 + x**4 + 5*x**3 + 3*x**2 + \
|
536 |
+
2*x)*Dx, x, 0, {-2: [2, 3, 5]})
|
537 |
+
assert p == q
|
538 |
+
p = expr_to_holonomic(1/(x-1)**2, lenics=3, x0=1)
|
539 |
+
q = HolonomicFunction((2) + (x - 1)*Dx, x, 1, {-2: [1, 0, 0]})
|
540 |
+
assert p == q
|
541 |
+
a = symbols("a")
|
542 |
+
p = expr_to_holonomic(sqrt(a*x), x=x)
|
543 |
+
assert p.to_expr() == sqrt(a)*sqrt(x)
|
544 |
+
|
545 |
+
def test_to_hyper():
|
546 |
+
x = symbols('x')
|
547 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
548 |
+
p = HolonomicFunction(Dx - 2, x, 0, [3]).to_hyper()
|
549 |
+
q = 3 * hyper([], [], 2*x)
|
550 |
+
assert p == q
|
551 |
+
p = hyperexpand(HolonomicFunction((1 + x) * Dx - 3, x, 0, [2]).to_hyper()).expand()
|
552 |
+
q = 2*x**3 + 6*x**2 + 6*x + 2
|
553 |
+
assert p == q
|
554 |
+
p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_hyper()
|
555 |
+
q = -x**2*hyper((2, 2, 1), (3, 2), -x)/2 + x
|
556 |
+
assert p == q
|
557 |
+
p = HolonomicFunction(2*x*Dx + Dx**2, x, 0, [0, 2/sqrt(pi)]).to_hyper()
|
558 |
+
q = 2*x*hyper((S.Half,), (Rational(3, 2),), -x**2)/sqrt(pi)
|
559 |
+
assert p == q
|
560 |
+
p = hyperexpand(HolonomicFunction(2*x*Dx + Dx**2, x, 0, [1, -2/sqrt(pi)]).to_hyper())
|
561 |
+
q = erfc(x)
|
562 |
+
assert p.rewrite(erfc) == q
|
563 |
+
p = hyperexpand(HolonomicFunction((x**2 - 1) + x*Dx + x**2*Dx**2,
|
564 |
+
x, 0, [0, S.Half]).to_hyper())
|
565 |
+
q = besselj(1, x)
|
566 |
+
assert p == q
|
567 |
+
p = hyperexpand(HolonomicFunction(x*Dx**2 + Dx + x, x, 0, [1, 0]).to_hyper())
|
568 |
+
q = besselj(0, x)
|
569 |
+
assert p == q
|
570 |
+
|
571 |
+
def test_to_expr():
|
572 |
+
x = symbols('x')
|
573 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
574 |
+
p = HolonomicFunction(Dx - 1, x, 0, [1]).to_expr()
|
575 |
+
q = exp(x)
|
576 |
+
assert p == q
|
577 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).to_expr()
|
578 |
+
q = cos(x)
|
579 |
+
assert p == q
|
580 |
+
p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0]).to_expr()
|
581 |
+
q = cosh(x)
|
582 |
+
assert p == q
|
583 |
+
p = HolonomicFunction(2 + (4*x - 1)*Dx + \
|
584 |
+
(x**2 - x)*Dx**2, x, 0, [1, 2]).to_expr().expand()
|
585 |
+
q = 1/(x**2 - 2*x + 1)
|
586 |
+
assert p == q
|
587 |
+
p = expr_to_holonomic(sin(x)**2/x).integrate((x, 0, x)).to_expr()
|
588 |
+
q = (sin(x)**2/x).integrate((x, 0, x))
|
589 |
+
assert p == q
|
590 |
+
C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3')
|
591 |
+
p = expr_to_holonomic(log(1+x**2)).to_expr()
|
592 |
+
q = C_2*log(x**2 + 1)
|
593 |
+
assert p == q
|
594 |
+
p = expr_to_holonomic(log(1+x**2)).diff().to_expr()
|
595 |
+
q = C_0*x/(x**2 + 1)
|
596 |
+
assert p == q
|
597 |
+
p = expr_to_holonomic(erf(x) + x).to_expr()
|
598 |
+
q = 3*C_3*x - 3*sqrt(pi)*C_3*erf(x)/2 + x + 2*x/sqrt(pi)
|
599 |
+
assert p == q
|
600 |
+
p = expr_to_holonomic(sqrt(x), x0=1).to_expr()
|
601 |
+
assert p == sqrt(x)
|
602 |
+
assert expr_to_holonomic(sqrt(x)).to_expr() == sqrt(x)
|
603 |
+
p = expr_to_holonomic(sqrt(1 + x**2)).to_expr()
|
604 |
+
assert p == sqrt(1+x**2)
|
605 |
+
p = expr_to_holonomic((2*x**2 + 1)**Rational(2, 3)).to_expr()
|
606 |
+
assert p == (2*x**2 + 1)**Rational(2, 3)
|
607 |
+
p = expr_to_holonomic(sqrt(-x**2+2*x)).to_expr()
|
608 |
+
assert p == sqrt(x)*sqrt(-x + 2)
|
609 |
+
p = expr_to_holonomic((-2*x**3+7*x)**Rational(2, 3)).to_expr()
|
610 |
+
q = x**Rational(2, 3)*(-2*x**2 + 7)**Rational(2, 3)
|
611 |
+
assert p == q
|
612 |
+
p = from_hyper(hyper((-2, -3), (S.Half, ), x))
|
613 |
+
s = hyperexpand(hyper((-2, -3), (S.Half, ), x))
|
614 |
+
D_0 = Symbol('D_0')
|
615 |
+
C_0 = Symbol('C_0')
|
616 |
+
assert (p.to_expr().subs({C_0:1, D_0:0}) - s).simplify() == 0
|
617 |
+
p.y0 = {0: [1], S.Half: [0]}
|
618 |
+
assert p.to_expr() == s
|
619 |
+
assert expr_to_holonomic(x**5).to_expr() == x**5
|
620 |
+
assert expr_to_holonomic(2*x**3-3*x**2).to_expr().expand() == \
|
621 |
+
2*x**3-3*x**2
|
622 |
+
a = symbols("a")
|
623 |
+
p = (expr_to_holonomic(1.4*x)*expr_to_holonomic(a*x, x)).to_expr()
|
624 |
+
q = 1.4*a*x**2
|
625 |
+
assert p == q
|
626 |
+
p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(a*x, x)).to_expr()
|
627 |
+
q = x*(a + 1.4)
|
628 |
+
assert p == q
|
629 |
+
p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(x)).to_expr()
|
630 |
+
assert p == 2.4*x
|
631 |
+
|
632 |
+
|
633 |
+
def test_integrate():
|
634 |
+
x = symbols('x')
|
635 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
636 |
+
p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 2, 3))
|
637 |
+
q = '0.166270406994788'
|
638 |
+
assert sstr(p) == q
|
639 |
+
p = expr_to_holonomic(sin(x)).integrate((x, 0, x)).to_expr()
|
640 |
+
q = 1 - cos(x)
|
641 |
+
assert p == q
|
642 |
+
p = expr_to_holonomic(sin(x)).integrate((x, 0, 3))
|
643 |
+
q = 1 - cos(3)
|
644 |
+
assert p == q
|
645 |
+
p = expr_to_holonomic(sin(x)/x, x0=1).integrate((x, 1, 2))
|
646 |
+
q = '0.659329913368450'
|
647 |
+
assert sstr(p) == q
|
648 |
+
p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 1, 0))
|
649 |
+
q = '-0.423690480850035'
|
650 |
+
assert sstr(p) == q
|
651 |
+
p = expr_to_holonomic(sin(x)/x)
|
652 |
+
assert p.integrate(x).to_expr() == Si(x)
|
653 |
+
assert p.integrate((x, 0, 2)) == Si(2)
|
654 |
+
p = expr_to_holonomic(sin(x)**2/x)
|
655 |
+
q = p.to_expr()
|
656 |
+
assert p.integrate(x).to_expr() == q.integrate((x, 0, x))
|
657 |
+
assert p.integrate((x, 0, 1)) == q.integrate((x, 0, 1))
|
658 |
+
assert expr_to_holonomic(1/x, x0=1).integrate(x).to_expr() == log(x)
|
659 |
+
p = expr_to_holonomic((x + 1)**3*exp(-x), x0=-1).integrate(x).to_expr()
|
660 |
+
q = (-x**3 - 6*x**2 - 15*x + 6*exp(x + 1) - 16)*exp(-x)
|
661 |
+
assert p == q
|
662 |
+
p = expr_to_holonomic(cos(x)**2/x**2, y0={-2: [1, 0, -1]}).integrate(x).to_expr()
|
663 |
+
q = -Si(2*x) - cos(x)**2/x
|
664 |
+
assert p == q
|
665 |
+
p = expr_to_holonomic(sqrt(x**2+x)).integrate(x).to_expr()
|
666 |
+
q = (x**Rational(3, 2)*(2*x**2 + 3*x + 1) - x*sqrt(x + 1)*asinh(sqrt(x)))/(4*x*sqrt(x + 1))
|
667 |
+
assert p == q
|
668 |
+
p = expr_to_holonomic(sqrt(x**2+1)).integrate(x).to_expr()
|
669 |
+
q = (sqrt(x**2+1)).integrate(x)
|
670 |
+
assert (p-q).simplify() == 0
|
671 |
+
p = expr_to_holonomic(1/x**2, y0={-2:[1, 0, 0]})
|
672 |
+
r = expr_to_holonomic(1/x**2, lenics=3)
|
673 |
+
assert p == r
|
674 |
+
q = expr_to_holonomic(cos(x)**2)
|
675 |
+
assert (r*q).integrate(x).to_expr() == -Si(2*x) - cos(x)**2/x
|
676 |
+
|
677 |
+
|
678 |
+
def test_diff():
|
679 |
+
x, y = symbols('x, y')
|
680 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
681 |
+
p = HolonomicFunction(x*Dx**2 + 1, x, 0, [0, 1])
|
682 |
+
assert p.diff().to_expr() == p.to_expr().diff().simplify()
|
683 |
+
p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0])
|
684 |
+
assert p.diff(x, 2).to_expr() == p.to_expr()
|
685 |
+
p = expr_to_holonomic(Si(x))
|
686 |
+
assert p.diff().to_expr() == sin(x)/x
|
687 |
+
assert p.diff(y) == 0
|
688 |
+
C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3')
|
689 |
+
q = Si(x)
|
690 |
+
assert p.diff(x).to_expr() == q.diff()
|
691 |
+
assert p.diff(x, 2).to_expr().subs(C_0, Rational(-1, 3)).cancel() == q.diff(x, 2).cancel()
|
692 |
+
assert p.diff(x, 3).series().subs({C_3: Rational(-1, 3), C_0: 0}) == q.diff(x, 3).series()
|
693 |
+
|
694 |
+
|
695 |
+
def test_extended_domain_in_expr_to_holonomic():
|
696 |
+
x = symbols('x')
|
697 |
+
p = expr_to_holonomic(1.2*cos(3.1*x))
|
698 |
+
assert p.to_expr() == 1.2*cos(3.1*x)
|
699 |
+
assert sstr(p.integrate(x).to_expr()) == '0.387096774193548*sin(3.1*x)'
|
700 |
+
_, Dx = DifferentialOperators(RR.old_poly_ring(x), 'Dx')
|
701 |
+
p = expr_to_holonomic(1.1329138213*x)
|
702 |
+
q = HolonomicFunction((-1.1329138213) + (1.1329138213*x)*Dx, x, 0, {1: [1.1329138213]})
|
703 |
+
assert p == q
|
704 |
+
assert p.to_expr() == 1.1329138213*x
|
705 |
+
assert sstr(p.integrate((x, 1, 2))) == sstr((1.1329138213*x).integrate((x, 1, 2)))
|
706 |
+
y, z = symbols('y, z')
|
707 |
+
p = expr_to_holonomic(sin(x*y*z), x=x)
|
708 |
+
assert p.to_expr() == sin(x*y*z)
|
709 |
+
assert p.integrate(x).to_expr() == (-cos(x*y*z) + 1)/(y*z)
|
710 |
+
p = expr_to_holonomic(sin(x*y + z), x=x).integrate(x).to_expr()
|
711 |
+
q = (cos(z) - cos(x*y + z))/y
|
712 |
+
assert p == q
|
713 |
+
a = symbols('a')
|
714 |
+
p = expr_to_holonomic(a*x, x)
|
715 |
+
assert p.to_expr() == a*x
|
716 |
+
assert p.integrate(x).to_expr() == a*x**2/2
|
717 |
+
D_2, C_1 = symbols("D_2, C_1")
|
718 |
+
p = expr_to_holonomic(x) + expr_to_holonomic(1.2*cos(x))
|
719 |
+
p = p.to_expr().subs(D_2, 0)
|
720 |
+
assert p - x - 1.2*cos(1.0*x) == 0
|
721 |
+
p = expr_to_holonomic(x) * expr_to_holonomic(1.2*cos(x))
|
722 |
+
p = p.to_expr().subs(C_1, 0)
|
723 |
+
assert p - 1.2*x*cos(1.0*x) == 0
|
724 |
+
|
725 |
+
|
726 |
+
def test_to_meijerg():
|
727 |
+
x = symbols('x')
|
728 |
+
assert hyperexpand(expr_to_holonomic(sin(x)).to_meijerg()) == sin(x)
|
729 |
+
assert hyperexpand(expr_to_holonomic(cos(x)).to_meijerg()) == cos(x)
|
730 |
+
assert hyperexpand(expr_to_holonomic(exp(x)).to_meijerg()) == exp(x)
|
731 |
+
assert hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify() == log(x)
|
732 |
+
assert expr_to_holonomic(4*x**2/3 + 7).to_meijerg() == 4*x**2/3 + 7
|
733 |
+
assert hyperexpand(expr_to_holonomic(besselj(2, x), lenics=3).to_meijerg()) == besselj(2, x)
|
734 |
+
p = hyper((Rational(-1, 2), -3), (), x)
|
735 |
+
assert from_hyper(p).to_meijerg() == hyperexpand(p)
|
736 |
+
p = hyper((S.One, S(3)), (S(2), ), x)
|
737 |
+
assert (hyperexpand(from_hyper(p).to_meijerg()) - hyperexpand(p)).expand() == 0
|
738 |
+
p = from_hyper(hyper((-2, -3), (S.Half, ), x))
|
739 |
+
s = hyperexpand(hyper((-2, -3), (S.Half, ), x))
|
740 |
+
C_0 = Symbol('C_0')
|
741 |
+
C_1 = Symbol('C_1')
|
742 |
+
D_0 = Symbol('D_0')
|
743 |
+
assert (hyperexpand(p.to_meijerg()).subs({C_0:1, D_0:0}) - s).simplify() == 0
|
744 |
+
p.y0 = {0: [1], S.Half: [0]}
|
745 |
+
assert (hyperexpand(p.to_meijerg()) - s).simplify() == 0
|
746 |
+
p = expr_to_holonomic(besselj(S.Half, x), initcond=False)
|
747 |
+
assert (p.to_expr() - (D_0*sin(x) + C_0*cos(x) + C_1*sin(x))/sqrt(x)).simplify() == 0
|
748 |
+
p = expr_to_holonomic(besselj(S.Half, x), y0={Rational(-1, 2): [sqrt(2)/sqrt(pi), sqrt(2)/sqrt(pi)]})
|
749 |
+
assert (p.to_expr() - besselj(S.Half, x) - besselj(Rational(-1, 2), x)).simplify() == 0
|
750 |
+
|
751 |
+
|
752 |
+
def test_gaussian():
|
753 |
+
mu, x = symbols("mu x")
|
754 |
+
sd = symbols("sd", positive=True)
|
755 |
+
Q = QQ[mu, sd].get_field()
|
756 |
+
e = sqrt(2)*exp(-(-mu + x)**2/(2*sd**2))/(2*sqrt(pi)*sd)
|
757 |
+
h1 = expr_to_holonomic(e, x, domain=Q)
|
758 |
+
|
759 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
760 |
+
h2 = HolonomicFunction((-mu/sd**2 + x/sd**2) + (1)*Dx, x)
|
761 |
+
|
762 |
+
assert h1 == h2
|
763 |
+
|
764 |
+
|
765 |
+
def test_beta():
|
766 |
+
a, b, x = symbols("a b x", positive=True)
|
767 |
+
e = x**(a - 1)*(-x + 1)**(b - 1)/beta(a, b)
|
768 |
+
Q = QQ[a, b].get_field()
|
769 |
+
h1 = expr_to_holonomic(e, x, domain=Q)
|
770 |
+
|
771 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
772 |
+
h2 = HolonomicFunction((a + x*(-a - b + 2) - 1) + (x**2 - x)*Dx, x)
|
773 |
+
|
774 |
+
assert h1 == h2
|
775 |
+
|
776 |
+
|
777 |
+
def test_gamma():
|
778 |
+
a, b, x = symbols("a b x", positive=True)
|
779 |
+
e = b**(-a)*x**(a - 1)*exp(-x/b)/gamma(a)
|
780 |
+
Q = QQ[a, b].get_field()
|
781 |
+
h1 = expr_to_holonomic(e, x, domain=Q)
|
782 |
+
|
783 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
784 |
+
h2 = HolonomicFunction((-a + 1 + x/b) + (x)*Dx, x)
|
785 |
+
|
786 |
+
assert h1 == h2
|
787 |
+
|
788 |
+
|
789 |
+
def test_symbolic_power():
|
790 |
+
x, n = symbols("x n")
|
791 |
+
Q = QQ[n].get_field()
|
792 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
793 |
+
h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -n
|
794 |
+
h2 = HolonomicFunction((n) + (x)*Dx, x)
|
795 |
+
|
796 |
+
assert h1 == h2
|
797 |
+
|
798 |
+
|
799 |
+
def test_negative_power():
|
800 |
+
x = symbols("x")
|
801 |
+
_, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
802 |
+
h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -2
|
803 |
+
h2 = HolonomicFunction((2) + (x)*Dx, x)
|
804 |
+
|
805 |
+
assert h1 == h2
|
806 |
+
|
807 |
+
|
808 |
+
def test_expr_in_power():
|
809 |
+
x, n = symbols("x n")
|
810 |
+
Q = QQ[n].get_field()
|
811 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
812 |
+
h1 = HolonomicFunction((-1) + (x)*Dx, x) ** (n - 3)
|
813 |
+
h2 = HolonomicFunction((-n + 3) + (x)*Dx, x)
|
814 |
+
|
815 |
+
assert h1 == h2
|
816 |
+
|
817 |
+
def test_DifferentialOperatorEqPoly():
|
818 |
+
x = symbols('x', integer=True)
|
819 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
820 |
+
do = DifferentialOperator([x**2, R.base.zero, R.base.zero], R)
|
821 |
+
do2 = DifferentialOperator([x**2, 1, x], R)
|
822 |
+
assert not do == do2
|
823 |
+
|
824 |
+
# polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799
|
825 |
+
# should work once that is solved
|
826 |
+
# p = do.listofpoly[0]
|
827 |
+
# assert do == p
|
828 |
+
|
829 |
+
p2 = do2.listofpoly[0]
|
830 |
+
assert not do2 == p2
|
llmeval-env/lib/python3.10/site-packages/sympy/holonomic/tests/test_recurrence.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.holonomic.recurrence import RecurrenceOperators, RecurrenceOperator
|
2 |
+
from sympy.core.symbol import symbols
|
3 |
+
from sympy.polys.domains.rationalfield import QQ
|
4 |
+
|
5 |
+
def test_RecurrenceOperator():
|
6 |
+
n = symbols('n', integer=True)
|
7 |
+
R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
|
8 |
+
assert Sn*n == (n + 1)*Sn
|
9 |
+
assert Sn*n**2 == (n**2+1+2*n)*Sn
|
10 |
+
assert Sn**2*n**2 == (n**2 + 4*n + 4)*Sn**2
|
11 |
+
p = (Sn**3*n**2 + Sn*n)**2
|
12 |
+
q = (n**2 + 3*n + 2)*Sn**2 + (2*n**3 + 19*n**2 + 57*n + 52)*Sn**4 + (n**4 + 18*n**3 + \
|
13 |
+
117*n**2 + 324*n + 324)*Sn**6
|
14 |
+
assert p == q
|
15 |
+
|
16 |
+
def test_RecurrenceOperatorEqPoly():
|
17 |
+
n = symbols('n', integer=True)
|
18 |
+
R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
|
19 |
+
rr = RecurrenceOperator([n**2, 0, 0], R)
|
20 |
+
rr2 = RecurrenceOperator([n**2, 1, n], R)
|
21 |
+
assert not rr == rr2
|
22 |
+
|
23 |
+
# polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799
|
24 |
+
# should work once that is solved
|
25 |
+
# d = rr.listofpoly[0]
|
26 |
+
# assert rr == d
|
27 |
+
|
28 |
+
d2 = rr2.listofpoly[0]
|
29 |
+
assert not rr2 == d2
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (2.49 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/decompositions.cpython-310.pyc
ADDED
Binary file (41.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/dense.cpython-310.pyc
ADDED
Binary file (31.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/immutable.cpython-310.pyc
ADDED
Binary file (6.24 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/inverse.cpython-310.pyc
ADDED
Binary file (11.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/normalforms.cpython-310.pyc
ADDED
Binary file (4.39 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/repmatrix.cpython-310.pyc
ADDED
Binary file (22 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/solvers.cpython-310.pyc
ADDED
Binary file (21.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/__pycache__/utilities.cpython-310.pyc
ADDED
Binary file (2.73 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (193 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_commonmatrix.cpython-310.pyc
ADDED
Binary file (43.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_decompositions.cpython-310.pyc
ADDED
Binary file (13.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_determinant.cpython-310.pyc
ADDED
Binary file (12.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_eigen.cpython-310.pyc
ADDED
Binary file (19.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_graph.cpython-310.pyc
ADDED
Binary file (2.93 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_immutable.cpython-310.pyc
ADDED
Binary file (5.13 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_interactions.cpython-310.pyc
ADDED
Binary file (2.88 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrices.cpython-310.pyc
ADDED
Binary file (129 kB). View file
|
|