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/integrals/__init__.py +43 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_integrate.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_trigintegrate.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/bench_integrate.py +21 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/bench_trigintegrate.py +13 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/deltafunctions.py +201 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/heurisch.py +771 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/integrals.py +1633 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/intpoly.py +1302 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/laplace.py +1761 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/manualintegrate.py +2171 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/meijerint.py +2190 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/meijerint_doc.py +37 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/prde.py +1332 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/quadrature.py +617 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/rationaltools.py +418 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/rde.py +800 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/risch.py +1858 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/singularityfunctions.py +63 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_deltafunctions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_failing_integrals.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_integrals.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_intpoly.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_laplace.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_lineintegrals.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_manual.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_meijerint.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_quadrature.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_risch.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_transforms.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_trigonometry.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_deltafunctions.py +79 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_failing_integrals.py +272 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_heurisch.py +367 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_integrals.py +2073 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_intpoly.py +627 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_laplace.py +550 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_lineintegrals.py +13 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_manual.py +688 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_meijerint.py +764 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_prde.py +322 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_quadrature.py +601 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_rationaltools.py +172 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_rde.py +202 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_risch.py +763 -0
- llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_singularityfunctions.py +22 -0
llmeval-env/lib/python3.10/site-packages/sympy/integrals/__init__.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Integration functions that integrate a SymPy expression.
|
2 |
+
|
3 |
+
Examples
|
4 |
+
========
|
5 |
+
|
6 |
+
>>> from sympy import integrate, sin
|
7 |
+
>>> from sympy.abc import x
|
8 |
+
>>> integrate(1/x,x)
|
9 |
+
log(x)
|
10 |
+
>>> integrate(sin(x),x)
|
11 |
+
-cos(x)
|
12 |
+
"""
|
13 |
+
from .integrals import integrate, Integral, line_integrate
|
14 |
+
from .transforms import (mellin_transform, inverse_mellin_transform,
|
15 |
+
MellinTransform, InverseMellinTransform,
|
16 |
+
laplace_transform, inverse_laplace_transform,
|
17 |
+
LaplaceTransform, InverseLaplaceTransform,
|
18 |
+
fourier_transform, inverse_fourier_transform,
|
19 |
+
FourierTransform, InverseFourierTransform,
|
20 |
+
sine_transform, inverse_sine_transform,
|
21 |
+
SineTransform, InverseSineTransform,
|
22 |
+
cosine_transform, inverse_cosine_transform,
|
23 |
+
CosineTransform, InverseCosineTransform,
|
24 |
+
hankel_transform, inverse_hankel_transform,
|
25 |
+
HankelTransform, InverseHankelTransform)
|
26 |
+
from .singularityfunctions import singularityintegrate
|
27 |
+
|
28 |
+
__all__ = [
|
29 |
+
'integrate', 'Integral', 'line_integrate',
|
30 |
+
|
31 |
+
'mellin_transform', 'inverse_mellin_transform', 'MellinTransform',
|
32 |
+
'InverseMellinTransform', 'laplace_transform',
|
33 |
+
'inverse_laplace_transform', 'LaplaceTransform',
|
34 |
+
'InverseLaplaceTransform', 'fourier_transform',
|
35 |
+
'inverse_fourier_transform', 'FourierTransform',
|
36 |
+
'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform',
|
37 |
+
'SineTransform', 'InverseSineTransform', 'cosine_transform',
|
38 |
+
'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform',
|
39 |
+
'hankel_transform', 'inverse_hankel_transform', 'HankelTransform',
|
40 |
+
'InverseHankelTransform',
|
41 |
+
|
42 |
+
'singularityintegrate',
|
43 |
+
]
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (199 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_integrate.cpython-310.pyc
ADDED
Binary file (924 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_trigintegrate.cpython-310.pyc
ADDED
Binary file (710 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/bench_integrate.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.symbol import Symbol
|
2 |
+
from sympy.functions.elementary.trigonometric import sin
|
3 |
+
from sympy.integrals.integrals import integrate
|
4 |
+
|
5 |
+
x = Symbol('x')
|
6 |
+
|
7 |
+
|
8 |
+
def bench_integrate_sin():
|
9 |
+
integrate(sin(x), x)
|
10 |
+
|
11 |
+
|
12 |
+
def bench_integrate_x1sin():
|
13 |
+
integrate(x**1*sin(x), x)
|
14 |
+
|
15 |
+
|
16 |
+
def bench_integrate_x2sin():
|
17 |
+
integrate(x**2*sin(x), x)
|
18 |
+
|
19 |
+
|
20 |
+
def bench_integrate_x3sin():
|
21 |
+
integrate(x**3*sin(x), x)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/benchmarks/bench_trigintegrate.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.symbol import Symbol
|
2 |
+
from sympy.functions.elementary.trigonometric import sin
|
3 |
+
from sympy.integrals.trigonometry import trigintegrate
|
4 |
+
|
5 |
+
x = Symbol('x')
|
6 |
+
|
7 |
+
|
8 |
+
def timeit_trigintegrate_sin3x():
|
9 |
+
trigintegrate(sin(x)**3, x)
|
10 |
+
|
11 |
+
|
12 |
+
def timeit_trigintegrate_x2():
|
13 |
+
trigintegrate(x**2, x) # -> None
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/deltafunctions.py
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.mul import Mul
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core.sorting import default_sort_key
|
4 |
+
from sympy.functions import DiracDelta, Heaviside
|
5 |
+
from .integrals import Integral, integrate
|
6 |
+
|
7 |
+
|
8 |
+
def change_mul(node, x):
|
9 |
+
"""change_mul(node, x)
|
10 |
+
|
11 |
+
Rearranges the operands of a product, bringing to front any simple
|
12 |
+
DiracDelta expression.
|
13 |
+
|
14 |
+
Explanation
|
15 |
+
===========
|
16 |
+
|
17 |
+
If no simple DiracDelta expression was found, then all the DiracDelta
|
18 |
+
expressions are simplified (using DiracDelta.expand(diracdelta=True, wrt=x)).
|
19 |
+
|
20 |
+
Return: (dirac, new node)
|
21 |
+
Where:
|
22 |
+
o dirac is either a simple DiracDelta expression or None (if no simple
|
23 |
+
expression was found);
|
24 |
+
o new node is either a simplified DiracDelta expressions or None (if it
|
25 |
+
could not be simplified).
|
26 |
+
|
27 |
+
Examples
|
28 |
+
========
|
29 |
+
|
30 |
+
>>> from sympy import DiracDelta, cos
|
31 |
+
>>> from sympy.integrals.deltafunctions import change_mul
|
32 |
+
>>> from sympy.abc import x, y
|
33 |
+
>>> change_mul(x*y*DiracDelta(x)*cos(x), x)
|
34 |
+
(DiracDelta(x), x*y*cos(x))
|
35 |
+
>>> change_mul(x*y*DiracDelta(x**2 - 1)*cos(x), x)
|
36 |
+
(None, x*y*cos(x)*DiracDelta(x - 1)/2 + x*y*cos(x)*DiracDelta(x + 1)/2)
|
37 |
+
>>> change_mul(x*y*DiracDelta(cos(x))*cos(x), x)
|
38 |
+
(None, None)
|
39 |
+
|
40 |
+
See Also
|
41 |
+
========
|
42 |
+
|
43 |
+
sympy.functions.special.delta_functions.DiracDelta
|
44 |
+
deltaintegrate
|
45 |
+
"""
|
46 |
+
|
47 |
+
new_args = []
|
48 |
+
dirac = None
|
49 |
+
|
50 |
+
#Sorting is needed so that we consistently collapse the same delta;
|
51 |
+
#However, we must preserve the ordering of non-commutative terms
|
52 |
+
c, nc = node.args_cnc()
|
53 |
+
sorted_args = sorted(c, key=default_sort_key)
|
54 |
+
sorted_args.extend(nc)
|
55 |
+
|
56 |
+
for arg in sorted_args:
|
57 |
+
if arg.is_Pow and isinstance(arg.base, DiracDelta):
|
58 |
+
new_args.append(arg.func(arg.base, arg.exp - 1))
|
59 |
+
arg = arg.base
|
60 |
+
if dirac is None and (isinstance(arg, DiracDelta) and arg.is_simple(x)):
|
61 |
+
dirac = arg
|
62 |
+
else:
|
63 |
+
new_args.append(arg)
|
64 |
+
if not dirac: # there was no simple dirac
|
65 |
+
new_args = []
|
66 |
+
for arg in sorted_args:
|
67 |
+
if isinstance(arg, DiracDelta):
|
68 |
+
new_args.append(arg.expand(diracdelta=True, wrt=x))
|
69 |
+
elif arg.is_Pow and isinstance(arg.base, DiracDelta):
|
70 |
+
new_args.append(arg.func(arg.base.expand(diracdelta=True, wrt=x), arg.exp))
|
71 |
+
else:
|
72 |
+
new_args.append(arg)
|
73 |
+
if new_args != sorted_args:
|
74 |
+
nnode = Mul(*new_args).expand()
|
75 |
+
else: # if the node didn't change there is nothing to do
|
76 |
+
nnode = None
|
77 |
+
return (None, nnode)
|
78 |
+
return (dirac, Mul(*new_args))
|
79 |
+
|
80 |
+
|
81 |
+
def deltaintegrate(f, x):
|
82 |
+
"""
|
83 |
+
deltaintegrate(f, x)
|
84 |
+
|
85 |
+
Explanation
|
86 |
+
===========
|
87 |
+
|
88 |
+
The idea for integration is the following:
|
89 |
+
|
90 |
+
- If we are dealing with a DiracDelta expression, i.e. DiracDelta(g(x)),
|
91 |
+
we try to simplify it.
|
92 |
+
|
93 |
+
If we could simplify it, then we integrate the resulting expression.
|
94 |
+
We already know we can integrate a simplified expression, because only
|
95 |
+
simple DiracDelta expressions are involved.
|
96 |
+
|
97 |
+
If we couldn't simplify it, there are two cases:
|
98 |
+
|
99 |
+
1) The expression is a simple expression: we return the integral,
|
100 |
+
taking care if we are dealing with a Derivative or with a proper
|
101 |
+
DiracDelta.
|
102 |
+
|
103 |
+
2) The expression is not simple (i.e. DiracDelta(cos(x))): we can do
|
104 |
+
nothing at all.
|
105 |
+
|
106 |
+
- If the node is a multiplication node having a DiracDelta term:
|
107 |
+
|
108 |
+
First we expand it.
|
109 |
+
|
110 |
+
If the expansion did work, then we try to integrate the expansion.
|
111 |
+
|
112 |
+
If not, we try to extract a simple DiracDelta term, then we have two
|
113 |
+
cases:
|
114 |
+
|
115 |
+
1) We have a simple DiracDelta term, so we return the integral.
|
116 |
+
|
117 |
+
2) We didn't have a simple term, but we do have an expression with
|
118 |
+
simplified DiracDelta terms, so we integrate this expression.
|
119 |
+
|
120 |
+
Examples
|
121 |
+
========
|
122 |
+
|
123 |
+
>>> from sympy.abc import x, y, z
|
124 |
+
>>> from sympy.integrals.deltafunctions import deltaintegrate
|
125 |
+
>>> from sympy import sin, cos, DiracDelta
|
126 |
+
>>> deltaintegrate(x*sin(x)*cos(x)*DiracDelta(x - 1), x)
|
127 |
+
sin(1)*cos(1)*Heaviside(x - 1)
|
128 |
+
>>> deltaintegrate(y**2*DiracDelta(x - z)*DiracDelta(y - z), y)
|
129 |
+
z**2*DiracDelta(x - z)*Heaviside(y - z)
|
130 |
+
|
131 |
+
See Also
|
132 |
+
========
|
133 |
+
|
134 |
+
sympy.functions.special.delta_functions.DiracDelta
|
135 |
+
sympy.integrals.integrals.Integral
|
136 |
+
"""
|
137 |
+
if not f.has(DiracDelta):
|
138 |
+
return None
|
139 |
+
|
140 |
+
# g(x) = DiracDelta(h(x))
|
141 |
+
if f.func == DiracDelta:
|
142 |
+
h = f.expand(diracdelta=True, wrt=x)
|
143 |
+
if h == f: # can't simplify the expression
|
144 |
+
#FIXME: the second term tells whether is DeltaDirac or Derivative
|
145 |
+
#For integrating derivatives of DiracDelta we need the chain rule
|
146 |
+
if f.is_simple(x):
|
147 |
+
if (len(f.args) <= 1 or f.args[1] == 0):
|
148 |
+
return Heaviside(f.args[0])
|
149 |
+
else:
|
150 |
+
return (DiracDelta(f.args[0], f.args[1] - 1) /
|
151 |
+
f.args[0].as_poly().LC())
|
152 |
+
else: # let's try to integrate the simplified expression
|
153 |
+
fh = integrate(h, x)
|
154 |
+
return fh
|
155 |
+
elif f.is_Mul or f.is_Pow: # g(x) = a*b*c*f(DiracDelta(h(x)))*d*e
|
156 |
+
g = f.expand()
|
157 |
+
if f != g: # the expansion worked
|
158 |
+
fh = integrate(g, x)
|
159 |
+
if fh is not None and not isinstance(fh, Integral):
|
160 |
+
return fh
|
161 |
+
else:
|
162 |
+
# no expansion performed, try to extract a simple DiracDelta term
|
163 |
+
deltaterm, rest_mult = change_mul(f, x)
|
164 |
+
|
165 |
+
if not deltaterm:
|
166 |
+
if rest_mult:
|
167 |
+
fh = integrate(rest_mult, x)
|
168 |
+
return fh
|
169 |
+
else:
|
170 |
+
from sympy.solvers import solve
|
171 |
+
deltaterm = deltaterm.expand(diracdelta=True, wrt=x)
|
172 |
+
if deltaterm.is_Mul: # Take out any extracted factors
|
173 |
+
deltaterm, rest_mult_2 = change_mul(deltaterm, x)
|
174 |
+
rest_mult = rest_mult*rest_mult_2
|
175 |
+
point = solve(deltaterm.args[0], x)[0]
|
176 |
+
|
177 |
+
# Return the largest hyperreal term left after
|
178 |
+
# repeated integration by parts. For example,
|
179 |
+
#
|
180 |
+
# integrate(y*DiracDelta(x, 1),x) == y*DiracDelta(x,0), not 0
|
181 |
+
#
|
182 |
+
# This is so Integral(y*DiracDelta(x).diff(x),x).doit()
|
183 |
+
# will return y*DiracDelta(x) instead of 0 or DiracDelta(x),
|
184 |
+
# both of which are correct everywhere the value is defined
|
185 |
+
# but give wrong answers for nested integration.
|
186 |
+
n = (0 if len(deltaterm.args)==1 else deltaterm.args[1])
|
187 |
+
m = 0
|
188 |
+
while n >= 0:
|
189 |
+
r = S.NegativeOne**n*rest_mult.diff(x, n).subs(x, point)
|
190 |
+
if r.is_zero:
|
191 |
+
n -= 1
|
192 |
+
m += 1
|
193 |
+
else:
|
194 |
+
if m == 0:
|
195 |
+
return r*Heaviside(x - point)
|
196 |
+
else:
|
197 |
+
return r*DiracDelta(x,m-1)
|
198 |
+
# In some very weak sense, x=0 is still a singularity,
|
199 |
+
# but we hope will not be of any practical consequence.
|
200 |
+
return S.Zero
|
201 |
+
return None
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/heurisch.py
ADDED
@@ -0,0 +1,771 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from itertools import permutations
|
4 |
+
from functools import reduce
|
5 |
+
|
6 |
+
from sympy.core.add import Add
|
7 |
+
from sympy.core.basic import Basic
|
8 |
+
from sympy.core.mul import Mul
|
9 |
+
from sympy.core.symbol import Wild, Dummy, Symbol
|
10 |
+
from sympy.core.basic import sympify
|
11 |
+
from sympy.core.numbers import Rational, pi, I
|
12 |
+
from sympy.core.relational import Eq, Ne
|
13 |
+
from sympy.core.singleton import S
|
14 |
+
from sympy.core.sorting import ordered
|
15 |
+
from sympy.core.traversal import iterfreeargs
|
16 |
+
|
17 |
+
from sympy.functions import exp, sin, cos, tan, cot, asin, atan
|
18 |
+
from sympy.functions import log, sinh, cosh, tanh, coth, asinh
|
19 |
+
from sympy.functions import sqrt, erf, erfi, li, Ei
|
20 |
+
from sympy.functions import besselj, bessely, besseli, besselk
|
21 |
+
from sympy.functions import hankel1, hankel2, jn, yn
|
22 |
+
from sympy.functions.elementary.complexes import Abs, re, im, sign, arg
|
23 |
+
from sympy.functions.elementary.exponential import LambertW
|
24 |
+
from sympy.functions.elementary.integers import floor, ceiling
|
25 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
26 |
+
from sympy.functions.special.delta_functions import Heaviside, DiracDelta
|
27 |
+
|
28 |
+
from sympy.simplify.radsimp import collect
|
29 |
+
|
30 |
+
from sympy.logic.boolalg import And, Or
|
31 |
+
from sympy.utilities.iterables import uniq
|
32 |
+
|
33 |
+
from sympy.polys import quo, gcd, lcm, factor_list, cancel, PolynomialError
|
34 |
+
from sympy.polys.monomials import itermonomials
|
35 |
+
from sympy.polys.polyroots import root_factors
|
36 |
+
|
37 |
+
from sympy.polys.rings import PolyRing
|
38 |
+
from sympy.polys.solvers import solve_lin_sys
|
39 |
+
from sympy.polys.constructor import construct_domain
|
40 |
+
|
41 |
+
from sympy.integrals.integrals import integrate
|
42 |
+
|
43 |
+
|
44 |
+
def components(f, x):
|
45 |
+
"""
|
46 |
+
Returns a set of all functional components of the given expression
|
47 |
+
which includes symbols, function applications and compositions and
|
48 |
+
non-integer powers. Fractional powers are collected with
|
49 |
+
minimal, positive exponents.
|
50 |
+
|
51 |
+
Examples
|
52 |
+
========
|
53 |
+
|
54 |
+
>>> from sympy import cos, sin
|
55 |
+
>>> from sympy.abc import x
|
56 |
+
>>> from sympy.integrals.heurisch import components
|
57 |
+
|
58 |
+
>>> components(sin(x)*cos(x)**2, x)
|
59 |
+
{x, sin(x), cos(x)}
|
60 |
+
|
61 |
+
See Also
|
62 |
+
========
|
63 |
+
|
64 |
+
heurisch
|
65 |
+
"""
|
66 |
+
result = set()
|
67 |
+
|
68 |
+
if f.has_free(x):
|
69 |
+
if f.is_symbol and f.is_commutative:
|
70 |
+
result.add(f)
|
71 |
+
elif f.is_Function or f.is_Derivative:
|
72 |
+
for g in f.args:
|
73 |
+
result |= components(g, x)
|
74 |
+
|
75 |
+
result.add(f)
|
76 |
+
elif f.is_Pow:
|
77 |
+
result |= components(f.base, x)
|
78 |
+
|
79 |
+
if not f.exp.is_Integer:
|
80 |
+
if f.exp.is_Rational:
|
81 |
+
result.add(f.base**Rational(1, f.exp.q))
|
82 |
+
else:
|
83 |
+
result |= components(f.exp, x) | {f}
|
84 |
+
else:
|
85 |
+
for g in f.args:
|
86 |
+
result |= components(g, x)
|
87 |
+
|
88 |
+
return result
|
89 |
+
|
90 |
+
# name -> [] of symbols
|
91 |
+
_symbols_cache: dict[str, list[Dummy]] = {}
|
92 |
+
|
93 |
+
|
94 |
+
# NB @cacheit is not convenient here
|
95 |
+
def _symbols(name, n):
|
96 |
+
"""get vector of symbols local to this module"""
|
97 |
+
try:
|
98 |
+
lsyms = _symbols_cache[name]
|
99 |
+
except KeyError:
|
100 |
+
lsyms = []
|
101 |
+
_symbols_cache[name] = lsyms
|
102 |
+
|
103 |
+
while len(lsyms) < n:
|
104 |
+
lsyms.append( Dummy('%s%i' % (name, len(lsyms))) )
|
105 |
+
|
106 |
+
return lsyms[:n]
|
107 |
+
|
108 |
+
|
109 |
+
def heurisch_wrapper(f, x, rewrite=False, hints=None, mappings=None, retries=3,
|
110 |
+
degree_offset=0, unnecessary_permutations=None,
|
111 |
+
_try_heurisch=None):
|
112 |
+
"""
|
113 |
+
A wrapper around the heurisch integration algorithm.
|
114 |
+
|
115 |
+
Explanation
|
116 |
+
===========
|
117 |
+
|
118 |
+
This method takes the result from heurisch and checks for poles in the
|
119 |
+
denominator. For each of these poles, the integral is reevaluated, and
|
120 |
+
the final integration result is given in terms of a Piecewise.
|
121 |
+
|
122 |
+
Examples
|
123 |
+
========
|
124 |
+
|
125 |
+
>>> from sympy import cos, symbols
|
126 |
+
>>> from sympy.integrals.heurisch import heurisch, heurisch_wrapper
|
127 |
+
>>> n, x = symbols('n x')
|
128 |
+
>>> heurisch(cos(n*x), x)
|
129 |
+
sin(n*x)/n
|
130 |
+
>>> heurisch_wrapper(cos(n*x), x)
|
131 |
+
Piecewise((sin(n*x)/n, Ne(n, 0)), (x, True))
|
132 |
+
|
133 |
+
See Also
|
134 |
+
========
|
135 |
+
|
136 |
+
heurisch
|
137 |
+
"""
|
138 |
+
from sympy.solvers.solvers import solve, denoms
|
139 |
+
f = sympify(f)
|
140 |
+
if not f.has_free(x):
|
141 |
+
return f*x
|
142 |
+
|
143 |
+
res = heurisch(f, x, rewrite, hints, mappings, retries, degree_offset,
|
144 |
+
unnecessary_permutations, _try_heurisch)
|
145 |
+
if not isinstance(res, Basic):
|
146 |
+
return res
|
147 |
+
|
148 |
+
# We consider each denominator in the expression, and try to find
|
149 |
+
# cases where one or more symbolic denominator might be zero. The
|
150 |
+
# conditions for these cases are stored in the list slns.
|
151 |
+
#
|
152 |
+
# Since denoms returns a set we use ordered. This is important because the
|
153 |
+
# ordering of slns determines the order of the resulting Piecewise so we
|
154 |
+
# need a deterministic order here to make the output deterministic.
|
155 |
+
slns = []
|
156 |
+
for d in ordered(denoms(res)):
|
157 |
+
try:
|
158 |
+
slns += solve([d], dict=True, exclude=(x,))
|
159 |
+
except NotImplementedError:
|
160 |
+
pass
|
161 |
+
if not slns:
|
162 |
+
return res
|
163 |
+
slns = list(uniq(slns))
|
164 |
+
# Remove the solutions corresponding to poles in the original expression.
|
165 |
+
slns0 = []
|
166 |
+
for d in denoms(f):
|
167 |
+
try:
|
168 |
+
slns0 += solve([d], dict=True, exclude=(x,))
|
169 |
+
except NotImplementedError:
|
170 |
+
pass
|
171 |
+
slns = [s for s in slns if s not in slns0]
|
172 |
+
if not slns:
|
173 |
+
return res
|
174 |
+
if len(slns) > 1:
|
175 |
+
eqs = []
|
176 |
+
for sub_dict in slns:
|
177 |
+
eqs.extend([Eq(key, value) for key, value in sub_dict.items()])
|
178 |
+
slns = solve(eqs, dict=True, exclude=(x,)) + slns
|
179 |
+
# For each case listed in the list slns, we reevaluate the integral.
|
180 |
+
pairs = []
|
181 |
+
for sub_dict in slns:
|
182 |
+
expr = heurisch(f.subs(sub_dict), x, rewrite, hints, mappings, retries,
|
183 |
+
degree_offset, unnecessary_permutations,
|
184 |
+
_try_heurisch)
|
185 |
+
cond = And(*[Eq(key, value) for key, value in sub_dict.items()])
|
186 |
+
generic = Or(*[Ne(key, value) for key, value in sub_dict.items()])
|
187 |
+
if expr is None:
|
188 |
+
expr = integrate(f.subs(sub_dict),x)
|
189 |
+
pairs.append((expr, cond))
|
190 |
+
# If there is one condition, put the generic case first. Otherwise,
|
191 |
+
# doing so may lead to longer Piecewise formulas
|
192 |
+
if len(pairs) == 1:
|
193 |
+
pairs = [(heurisch(f, x, rewrite, hints, mappings, retries,
|
194 |
+
degree_offset, unnecessary_permutations,
|
195 |
+
_try_heurisch),
|
196 |
+
generic),
|
197 |
+
(pairs[0][0], True)]
|
198 |
+
else:
|
199 |
+
pairs.append((heurisch(f, x, rewrite, hints, mappings, retries,
|
200 |
+
degree_offset, unnecessary_permutations,
|
201 |
+
_try_heurisch),
|
202 |
+
True))
|
203 |
+
return Piecewise(*pairs)
|
204 |
+
|
205 |
+
class BesselTable:
|
206 |
+
"""
|
207 |
+
Derivatives of Bessel functions of orders n and n-1
|
208 |
+
in terms of each other.
|
209 |
+
|
210 |
+
See the docstring of DiffCache.
|
211 |
+
"""
|
212 |
+
|
213 |
+
def __init__(self):
|
214 |
+
self.table = {}
|
215 |
+
self.n = Dummy('n')
|
216 |
+
self.z = Dummy('z')
|
217 |
+
self._create_table()
|
218 |
+
|
219 |
+
def _create_table(t):
|
220 |
+
table, n, z = t.table, t.n, t.z
|
221 |
+
for f in (besselj, bessely, hankel1, hankel2):
|
222 |
+
table[f] = (f(n-1, z) - n*f(n, z)/z,
|
223 |
+
(n-1)*f(n-1, z)/z - f(n, z))
|
224 |
+
|
225 |
+
f = besseli
|
226 |
+
table[f] = (f(n-1, z) - n*f(n, z)/z,
|
227 |
+
(n-1)*f(n-1, z)/z + f(n, z))
|
228 |
+
f = besselk
|
229 |
+
table[f] = (-f(n-1, z) - n*f(n, z)/z,
|
230 |
+
(n-1)*f(n-1, z)/z - f(n, z))
|
231 |
+
|
232 |
+
for f in (jn, yn):
|
233 |
+
table[f] = (f(n-1, z) - (n+1)*f(n, z)/z,
|
234 |
+
(n-1)*f(n-1, z)/z - f(n, z))
|
235 |
+
|
236 |
+
def diffs(t, f, n, z):
|
237 |
+
if f in t.table:
|
238 |
+
diff0, diff1 = t.table[f]
|
239 |
+
repl = [(t.n, n), (t.z, z)]
|
240 |
+
return (diff0.subs(repl), diff1.subs(repl))
|
241 |
+
|
242 |
+
def has(t, f):
|
243 |
+
return f in t.table
|
244 |
+
|
245 |
+
_bessel_table = None
|
246 |
+
|
247 |
+
class DiffCache:
|
248 |
+
"""
|
249 |
+
Store for derivatives of expressions.
|
250 |
+
|
251 |
+
Explanation
|
252 |
+
===========
|
253 |
+
|
254 |
+
The standard form of the derivative of a Bessel function of order n
|
255 |
+
contains two Bessel functions of orders n-1 and n+1, respectively.
|
256 |
+
Such forms cannot be used in parallel Risch algorithm, because
|
257 |
+
there is a linear recurrence relation between the three functions
|
258 |
+
while the algorithm expects that functions and derivatives are
|
259 |
+
represented in terms of algebraically independent transcendentals.
|
260 |
+
|
261 |
+
The solution is to take two of the functions, e.g., those of orders
|
262 |
+
n and n-1, and to express the derivatives in terms of the pair.
|
263 |
+
To guarantee that the proper form is used the two derivatives are
|
264 |
+
cached as soon as one is encountered.
|
265 |
+
|
266 |
+
Derivatives of other functions are also cached at no extra cost.
|
267 |
+
All derivatives are with respect to the same variable `x`.
|
268 |
+
"""
|
269 |
+
|
270 |
+
def __init__(self, x):
|
271 |
+
self.cache = {}
|
272 |
+
self.x = x
|
273 |
+
|
274 |
+
global _bessel_table
|
275 |
+
if not _bessel_table:
|
276 |
+
_bessel_table = BesselTable()
|
277 |
+
|
278 |
+
def get_diff(self, f):
|
279 |
+
cache = self.cache
|
280 |
+
|
281 |
+
if f in cache:
|
282 |
+
pass
|
283 |
+
elif (not hasattr(f, 'func') or
|
284 |
+
not _bessel_table.has(f.func)):
|
285 |
+
cache[f] = cancel(f.diff(self.x))
|
286 |
+
else:
|
287 |
+
n, z = f.args
|
288 |
+
d0, d1 = _bessel_table.diffs(f.func, n, z)
|
289 |
+
dz = self.get_diff(z)
|
290 |
+
cache[f] = d0*dz
|
291 |
+
cache[f.func(n-1, z)] = d1*dz
|
292 |
+
|
293 |
+
return cache[f]
|
294 |
+
|
295 |
+
def heurisch(f, x, rewrite=False, hints=None, mappings=None, retries=3,
|
296 |
+
degree_offset=0, unnecessary_permutations=None,
|
297 |
+
_try_heurisch=None):
|
298 |
+
"""
|
299 |
+
Compute indefinite integral using heuristic Risch algorithm.
|
300 |
+
|
301 |
+
Explanation
|
302 |
+
===========
|
303 |
+
|
304 |
+
This is a heuristic approach to indefinite integration in finite
|
305 |
+
terms using the extended heuristic (parallel) Risch algorithm, based
|
306 |
+
on Manuel Bronstein's "Poor Man's Integrator".
|
307 |
+
|
308 |
+
The algorithm supports various classes of functions including
|
309 |
+
transcendental elementary or special functions like Airy,
|
310 |
+
Bessel, Whittaker and Lambert.
|
311 |
+
|
312 |
+
Note that this algorithm is not a decision procedure. If it isn't
|
313 |
+
able to compute the antiderivative for a given function, then this is
|
314 |
+
not a proof that such a functions does not exist. One should use
|
315 |
+
recursive Risch algorithm in such case. It's an open question if
|
316 |
+
this algorithm can be made a full decision procedure.
|
317 |
+
|
318 |
+
This is an internal integrator procedure. You should use top level
|
319 |
+
'integrate' function in most cases, as this procedure needs some
|
320 |
+
preprocessing steps and otherwise may fail.
|
321 |
+
|
322 |
+
Specification
|
323 |
+
=============
|
324 |
+
|
325 |
+
heurisch(f, x, rewrite=False, hints=None)
|
326 |
+
|
327 |
+
where
|
328 |
+
f : expression
|
329 |
+
x : symbol
|
330 |
+
|
331 |
+
rewrite -> force rewrite 'f' in terms of 'tan' and 'tanh'
|
332 |
+
hints -> a list of functions that may appear in anti-derivate
|
333 |
+
|
334 |
+
- hints = None --> no suggestions at all
|
335 |
+
- hints = [ ] --> try to figure out
|
336 |
+
- hints = [f1, ..., fn] --> we know better
|
337 |
+
|
338 |
+
Examples
|
339 |
+
========
|
340 |
+
|
341 |
+
>>> from sympy import tan
|
342 |
+
>>> from sympy.integrals.heurisch import heurisch
|
343 |
+
>>> from sympy.abc import x, y
|
344 |
+
|
345 |
+
>>> heurisch(y*tan(x), x)
|
346 |
+
y*log(tan(x)**2 + 1)/2
|
347 |
+
|
348 |
+
See Manuel Bronstein's "Poor Man's Integrator":
|
349 |
+
|
350 |
+
References
|
351 |
+
==========
|
352 |
+
|
353 |
+
.. [1] https://www-sop.inria.fr/cafe/Manuel.Bronstein/pmint/index.html
|
354 |
+
|
355 |
+
For more information on the implemented algorithm refer to:
|
356 |
+
|
357 |
+
.. [2] K. Geddes, L. Stefanus, On the Risch-Norman Integration
|
358 |
+
Method and its Implementation in Maple, Proceedings of
|
359 |
+
ISSAC'89, ACM Press, 212-217.
|
360 |
+
|
361 |
+
.. [3] J. H. Davenport, On the Parallel Risch Algorithm (I),
|
362 |
+
Proceedings of EUROCAM'82, LNCS 144, Springer, 144-157.
|
363 |
+
|
364 |
+
.. [4] J. H. Davenport, On the Parallel Risch Algorithm (III):
|
365 |
+
Use of Tangents, SIGSAM Bulletin 16 (1982), 3-6.
|
366 |
+
|
367 |
+
.. [5] J. H. Davenport, B. M. Trager, On the Parallel Risch
|
368 |
+
Algorithm (II), ACM Transactions on Mathematical
|
369 |
+
Software 11 (1985), 356-362.
|
370 |
+
|
371 |
+
See Also
|
372 |
+
========
|
373 |
+
|
374 |
+
sympy.integrals.integrals.Integral.doit
|
375 |
+
sympy.integrals.integrals.Integral
|
376 |
+
sympy.integrals.heurisch.components
|
377 |
+
"""
|
378 |
+
f = sympify(f)
|
379 |
+
|
380 |
+
# There are some functions that Heurisch cannot currently handle,
|
381 |
+
# so do not even try.
|
382 |
+
# Set _try_heurisch=True to skip this check
|
383 |
+
if _try_heurisch is not True:
|
384 |
+
if f.has(Abs, re, im, sign, Heaviside, DiracDelta, floor, ceiling, arg):
|
385 |
+
return
|
386 |
+
|
387 |
+
if not f.has_free(x):
|
388 |
+
return f*x
|
389 |
+
|
390 |
+
if not f.is_Add:
|
391 |
+
indep, f = f.as_independent(x)
|
392 |
+
else:
|
393 |
+
indep = S.One
|
394 |
+
|
395 |
+
rewritables = {
|
396 |
+
(sin, cos, cot): tan,
|
397 |
+
(sinh, cosh, coth): tanh,
|
398 |
+
}
|
399 |
+
|
400 |
+
if rewrite:
|
401 |
+
for candidates, rule in rewritables.items():
|
402 |
+
f = f.rewrite(candidates, rule)
|
403 |
+
else:
|
404 |
+
for candidates in rewritables.keys():
|
405 |
+
if f.has(*candidates):
|
406 |
+
break
|
407 |
+
else:
|
408 |
+
rewrite = True
|
409 |
+
|
410 |
+
terms = components(f, x)
|
411 |
+
dcache = DiffCache(x)
|
412 |
+
|
413 |
+
if hints is not None:
|
414 |
+
if not hints:
|
415 |
+
a = Wild('a', exclude=[x])
|
416 |
+
b = Wild('b', exclude=[x])
|
417 |
+
c = Wild('c', exclude=[x])
|
418 |
+
|
419 |
+
for g in set(terms): # using copy of terms
|
420 |
+
if g.is_Function:
|
421 |
+
if isinstance(g, li):
|
422 |
+
M = g.args[0].match(a*x**b)
|
423 |
+
|
424 |
+
if M is not None:
|
425 |
+
terms.add( x*(li(M[a]*x**M[b]) - (M[a]*x**M[b])**(-1/M[b])*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) )
|
426 |
+
#terms.add( x*(li(M[a]*x**M[b]) - (x**M[b])**(-1/M[b])*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) )
|
427 |
+
#terms.add( x*(li(M[a]*x**M[b]) - x*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) )
|
428 |
+
#terms.add( li(M[a]*x**M[b]) - Ei((M[b]+1)*log(M[a]*x**M[b])/M[b]) )
|
429 |
+
|
430 |
+
elif isinstance(g, exp):
|
431 |
+
M = g.args[0].match(a*x**2)
|
432 |
+
|
433 |
+
if M is not None:
|
434 |
+
if M[a].is_positive:
|
435 |
+
terms.add(erfi(sqrt(M[a])*x))
|
436 |
+
else: # M[a].is_negative or unknown
|
437 |
+
terms.add(erf(sqrt(-M[a])*x))
|
438 |
+
|
439 |
+
M = g.args[0].match(a*x**2 + b*x + c)
|
440 |
+
|
441 |
+
if M is not None:
|
442 |
+
if M[a].is_positive:
|
443 |
+
terms.add(sqrt(pi/4*(-M[a]))*exp(M[c] - M[b]**2/(4*M[a]))*
|
444 |
+
erfi(sqrt(M[a])*x + M[b]/(2*sqrt(M[a]))))
|
445 |
+
elif M[a].is_negative:
|
446 |
+
terms.add(sqrt(pi/4*(-M[a]))*exp(M[c] - M[b]**2/(4*M[a]))*
|
447 |
+
erf(sqrt(-M[a])*x - M[b]/(2*sqrt(-M[a]))))
|
448 |
+
|
449 |
+
M = g.args[0].match(a*log(x)**2)
|
450 |
+
|
451 |
+
if M is not None:
|
452 |
+
if M[a].is_positive:
|
453 |
+
terms.add(erfi(sqrt(M[a])*log(x) + 1/(2*sqrt(M[a]))))
|
454 |
+
if M[a].is_negative:
|
455 |
+
terms.add(erf(sqrt(-M[a])*log(x) - 1/(2*sqrt(-M[a]))))
|
456 |
+
|
457 |
+
elif g.is_Pow:
|
458 |
+
if g.exp.is_Rational and g.exp.q == 2:
|
459 |
+
M = g.base.match(a*x**2 + b)
|
460 |
+
|
461 |
+
if M is not None and M[b].is_positive:
|
462 |
+
if M[a].is_positive:
|
463 |
+
terms.add(asinh(sqrt(M[a]/M[b])*x))
|
464 |
+
elif M[a].is_negative:
|
465 |
+
terms.add(asin(sqrt(-M[a]/M[b])*x))
|
466 |
+
|
467 |
+
M = g.base.match(a*x**2 - b)
|
468 |
+
|
469 |
+
if M is not None and M[b].is_positive:
|
470 |
+
if M[a].is_positive:
|
471 |
+
dF = 1/sqrt(M[a]*x**2 - M[b])
|
472 |
+
F = log(2*sqrt(M[a])*sqrt(M[a]*x**2 - M[b]) + 2*M[a]*x)/sqrt(M[a])
|
473 |
+
dcache.cache[F] = dF # hack: F.diff(x) doesn't automatically simplify to f
|
474 |
+
terms.add(F)
|
475 |
+
elif M[a].is_negative:
|
476 |
+
terms.add(-M[b]/2*sqrt(-M[a])*
|
477 |
+
atan(sqrt(-M[a])*x/sqrt(M[a]*x**2 - M[b])))
|
478 |
+
|
479 |
+
else:
|
480 |
+
terms |= set(hints)
|
481 |
+
|
482 |
+
for g in set(terms): # using copy of terms
|
483 |
+
terms |= components(dcache.get_diff(g), x)
|
484 |
+
|
485 |
+
# XXX: The commented line below makes heurisch more deterministic wrt
|
486 |
+
# PYTHONHASHSEED and the iteration order of sets. There are other places
|
487 |
+
# where sets are iterated over but this one is possibly the most important.
|
488 |
+
# Theoretically the order here should not matter but different orderings
|
489 |
+
# can expose potential bugs in the different code paths so potentially it
|
490 |
+
# is better to keep the non-determinism.
|
491 |
+
#
|
492 |
+
# terms = list(ordered(terms))
|
493 |
+
|
494 |
+
# TODO: caching is significant factor for why permutations work at all. Change this.
|
495 |
+
V = _symbols('x', len(terms))
|
496 |
+
|
497 |
+
|
498 |
+
# sort mapping expressions from largest to smallest (last is always x).
|
499 |
+
mapping = list(reversed(list(zip(*ordered( #
|
500 |
+
[(a[0].as_independent(x)[1], a) for a in zip(terms, V)])))[1])) #
|
501 |
+
rev_mapping = {v: k for k, v in mapping} #
|
502 |
+
if mappings is None: #
|
503 |
+
# optimizing the number of permutations of mapping #
|
504 |
+
assert mapping[-1][0] == x # if not, find it and correct this comment
|
505 |
+
unnecessary_permutations = [mapping.pop(-1)]
|
506 |
+
mappings = permutations(mapping)
|
507 |
+
else:
|
508 |
+
unnecessary_permutations = unnecessary_permutations or []
|
509 |
+
|
510 |
+
def _substitute(expr):
|
511 |
+
return expr.subs(mapping)
|
512 |
+
|
513 |
+
for mapping in mappings:
|
514 |
+
mapping = list(mapping)
|
515 |
+
mapping = mapping + unnecessary_permutations
|
516 |
+
diffs = [ _substitute(dcache.get_diff(g)) for g in terms ]
|
517 |
+
denoms = [ g.as_numer_denom()[1] for g in diffs ]
|
518 |
+
if all(h.is_polynomial(*V) for h in denoms) and _substitute(f).is_rational_function(*V):
|
519 |
+
denom = reduce(lambda p, q: lcm(p, q, *V), denoms)
|
520 |
+
break
|
521 |
+
else:
|
522 |
+
if not rewrite:
|
523 |
+
result = heurisch(f, x, rewrite=True, hints=hints,
|
524 |
+
unnecessary_permutations=unnecessary_permutations)
|
525 |
+
|
526 |
+
if result is not None:
|
527 |
+
return indep*result
|
528 |
+
return None
|
529 |
+
|
530 |
+
numers = [ cancel(denom*g) for g in diffs ]
|
531 |
+
def _derivation(h):
|
532 |
+
return Add(*[ d * h.diff(v) for d, v in zip(numers, V) ])
|
533 |
+
|
534 |
+
def _deflation(p):
|
535 |
+
for y in V:
|
536 |
+
if not p.has(y):
|
537 |
+
continue
|
538 |
+
|
539 |
+
if _derivation(p) is not S.Zero:
|
540 |
+
c, q = p.as_poly(y).primitive()
|
541 |
+
return _deflation(c)*gcd(q, q.diff(y)).as_expr()
|
542 |
+
|
543 |
+
return p
|
544 |
+
|
545 |
+
def _splitter(p):
|
546 |
+
for y in V:
|
547 |
+
if not p.has(y):
|
548 |
+
continue
|
549 |
+
|
550 |
+
if _derivation(y) is not S.Zero:
|
551 |
+
c, q = p.as_poly(y).primitive()
|
552 |
+
|
553 |
+
q = q.as_expr()
|
554 |
+
|
555 |
+
h = gcd(q, _derivation(q), y)
|
556 |
+
s = quo(h, gcd(q, q.diff(y), y), y)
|
557 |
+
|
558 |
+
c_split = _splitter(c)
|
559 |
+
|
560 |
+
if s.as_poly(y).degree() == 0:
|
561 |
+
return (c_split[0], q * c_split[1])
|
562 |
+
|
563 |
+
q_split = _splitter(cancel(q / s))
|
564 |
+
|
565 |
+
return (c_split[0]*q_split[0]*s, c_split[1]*q_split[1])
|
566 |
+
|
567 |
+
return (S.One, p)
|
568 |
+
|
569 |
+
special = {}
|
570 |
+
|
571 |
+
for term in terms:
|
572 |
+
if term.is_Function:
|
573 |
+
if isinstance(term, tan):
|
574 |
+
special[1 + _substitute(term)**2] = False
|
575 |
+
elif isinstance(term, tanh):
|
576 |
+
special[1 + _substitute(term)] = False
|
577 |
+
special[1 - _substitute(term)] = False
|
578 |
+
elif isinstance(term, LambertW):
|
579 |
+
special[_substitute(term)] = True
|
580 |
+
|
581 |
+
F = _substitute(f)
|
582 |
+
|
583 |
+
P, Q = F.as_numer_denom()
|
584 |
+
|
585 |
+
u_split = _splitter(denom)
|
586 |
+
v_split = _splitter(Q)
|
587 |
+
|
588 |
+
polys = set(list(v_split) + [ u_split[0] ] + list(special.keys()))
|
589 |
+
|
590 |
+
s = u_split[0] * Mul(*[ k for k, v in special.items() if v ])
|
591 |
+
polified = [ p.as_poly(*V) for p in [s, P, Q] ]
|
592 |
+
|
593 |
+
if None in polified:
|
594 |
+
return None
|
595 |
+
|
596 |
+
#--- definitions for _integrate
|
597 |
+
a, b, c = [ p.total_degree() for p in polified ]
|
598 |
+
|
599 |
+
poly_denom = (s * v_split[0] * _deflation(v_split[1])).as_expr()
|
600 |
+
|
601 |
+
def _exponent(g):
|
602 |
+
if g.is_Pow:
|
603 |
+
if g.exp.is_Rational and g.exp.q != 1:
|
604 |
+
if g.exp.p > 0:
|
605 |
+
return g.exp.p + g.exp.q - 1
|
606 |
+
else:
|
607 |
+
return abs(g.exp.p + g.exp.q)
|
608 |
+
else:
|
609 |
+
return 1
|
610 |
+
elif not g.is_Atom and g.args:
|
611 |
+
return max([ _exponent(h) for h in g.args ])
|
612 |
+
else:
|
613 |
+
return 1
|
614 |
+
|
615 |
+
A, B = _exponent(f), a + max(b, c)
|
616 |
+
|
617 |
+
if A > 1 and B > 1:
|
618 |
+
monoms = tuple(ordered(itermonomials(V, A + B - 1 + degree_offset)))
|
619 |
+
else:
|
620 |
+
monoms = tuple(ordered(itermonomials(V, A + B + degree_offset)))
|
621 |
+
|
622 |
+
poly_coeffs = _symbols('A', len(monoms))
|
623 |
+
|
624 |
+
poly_part = Add(*[ poly_coeffs[i]*monomial
|
625 |
+
for i, monomial in enumerate(monoms) ])
|
626 |
+
|
627 |
+
reducibles = set()
|
628 |
+
|
629 |
+
for poly in ordered(polys):
|
630 |
+
coeff, factors = factor_list(poly, *V)
|
631 |
+
reducibles.add(coeff)
|
632 |
+
for fact, mul in factors:
|
633 |
+
reducibles.add(fact)
|
634 |
+
|
635 |
+
def _integrate(field=None):
|
636 |
+
atans = set()
|
637 |
+
pairs = set()
|
638 |
+
|
639 |
+
if field == 'Q':
|
640 |
+
irreducibles = set(reducibles)
|
641 |
+
else:
|
642 |
+
setV = set(V)
|
643 |
+
irreducibles = set()
|
644 |
+
for poly in ordered(reducibles):
|
645 |
+
zV = setV & set(iterfreeargs(poly))
|
646 |
+
for z in ordered(zV):
|
647 |
+
s = set(root_factors(poly, z, filter=field))
|
648 |
+
irreducibles |= s
|
649 |
+
break
|
650 |
+
|
651 |
+
log_part, atan_part = [], []
|
652 |
+
|
653 |
+
for poly in ordered(irreducibles):
|
654 |
+
m = collect(poly, I, evaluate=False)
|
655 |
+
y = m.get(I, S.Zero)
|
656 |
+
if y:
|
657 |
+
x = m.get(S.One, S.Zero)
|
658 |
+
if x.has(I) or y.has(I):
|
659 |
+
continue # nontrivial x + I*y
|
660 |
+
pairs.add((x, y))
|
661 |
+
irreducibles.remove(poly)
|
662 |
+
|
663 |
+
while pairs:
|
664 |
+
x, y = pairs.pop()
|
665 |
+
if (x, -y) in pairs:
|
666 |
+
pairs.remove((x, -y))
|
667 |
+
# Choosing b with no minus sign
|
668 |
+
if y.could_extract_minus_sign():
|
669 |
+
y = -y
|
670 |
+
irreducibles.add(x*x + y*y)
|
671 |
+
atans.add(atan(x/y))
|
672 |
+
else:
|
673 |
+
irreducibles.add(x + I*y)
|
674 |
+
|
675 |
+
|
676 |
+
B = _symbols('B', len(irreducibles))
|
677 |
+
C = _symbols('C', len(atans))
|
678 |
+
|
679 |
+
# Note: the ordering matters here
|
680 |
+
for poly, b in reversed(list(zip(ordered(irreducibles), B))):
|
681 |
+
if poly.has(*V):
|
682 |
+
poly_coeffs.append(b)
|
683 |
+
log_part.append(b * log(poly))
|
684 |
+
|
685 |
+
for poly, c in reversed(list(zip(ordered(atans), C))):
|
686 |
+
if poly.has(*V):
|
687 |
+
poly_coeffs.append(c)
|
688 |
+
atan_part.append(c * poly)
|
689 |
+
|
690 |
+
# TODO: Currently it's better to use symbolic expressions here instead
|
691 |
+
# of rational functions, because it's simpler and FracElement doesn't
|
692 |
+
# give big speed improvement yet. This is because cancellation is slow
|
693 |
+
# due to slow polynomial GCD algorithms. If this gets improved then
|
694 |
+
# revise this code.
|
695 |
+
candidate = poly_part/poly_denom + Add(*log_part) + Add(*atan_part)
|
696 |
+
h = F - _derivation(candidate) / denom
|
697 |
+
raw_numer = h.as_numer_denom()[0]
|
698 |
+
|
699 |
+
# Rewrite raw_numer as a polynomial in K[coeffs][V] where K is a field
|
700 |
+
# that we have to determine. We can't use simply atoms() because log(3),
|
701 |
+
# sqrt(y) and similar expressions can appear, leading to non-trivial
|
702 |
+
# domains.
|
703 |
+
syms = set(poly_coeffs) | set(V)
|
704 |
+
non_syms = set()
|
705 |
+
|
706 |
+
def find_non_syms(expr):
|
707 |
+
if expr.is_Integer or expr.is_Rational:
|
708 |
+
pass # ignore trivial numbers
|
709 |
+
elif expr in syms:
|
710 |
+
pass # ignore variables
|
711 |
+
elif not expr.has_free(*syms):
|
712 |
+
non_syms.add(expr)
|
713 |
+
elif expr.is_Add or expr.is_Mul or expr.is_Pow:
|
714 |
+
list(map(find_non_syms, expr.args))
|
715 |
+
else:
|
716 |
+
# TODO: Non-polynomial expression. This should have been
|
717 |
+
# filtered out at an earlier stage.
|
718 |
+
raise PolynomialError
|
719 |
+
|
720 |
+
try:
|
721 |
+
find_non_syms(raw_numer)
|
722 |
+
except PolynomialError:
|
723 |
+
return None
|
724 |
+
else:
|
725 |
+
ground, _ = construct_domain(non_syms, field=True)
|
726 |
+
|
727 |
+
coeff_ring = PolyRing(poly_coeffs, ground)
|
728 |
+
ring = PolyRing(V, coeff_ring)
|
729 |
+
try:
|
730 |
+
numer = ring.from_expr(raw_numer)
|
731 |
+
except ValueError:
|
732 |
+
raise PolynomialError
|
733 |
+
solution = solve_lin_sys(numer.coeffs(), coeff_ring, _raw=False)
|
734 |
+
|
735 |
+
if solution is None:
|
736 |
+
return None
|
737 |
+
else:
|
738 |
+
return candidate.xreplace(solution).xreplace(
|
739 |
+
dict(zip(poly_coeffs, [S.Zero]*len(poly_coeffs))))
|
740 |
+
|
741 |
+
if all(isinstance(_, Symbol) for _ in V):
|
742 |
+
more_free = F.free_symbols - set(V)
|
743 |
+
else:
|
744 |
+
Fd = F.as_dummy()
|
745 |
+
more_free = Fd.xreplace(dict(zip(V, (Dummy() for _ in V)))
|
746 |
+
).free_symbols & Fd.free_symbols
|
747 |
+
if not more_free:
|
748 |
+
# all free generators are identified in V
|
749 |
+
solution = _integrate('Q')
|
750 |
+
|
751 |
+
if solution is None:
|
752 |
+
solution = _integrate()
|
753 |
+
else:
|
754 |
+
solution = _integrate()
|
755 |
+
|
756 |
+
if solution is not None:
|
757 |
+
antideriv = solution.subs(rev_mapping)
|
758 |
+
antideriv = cancel(antideriv).expand()
|
759 |
+
|
760 |
+
if antideriv.is_Add:
|
761 |
+
antideriv = antideriv.as_independent(x)[1]
|
762 |
+
|
763 |
+
return indep*antideriv
|
764 |
+
else:
|
765 |
+
if retries >= 0:
|
766 |
+
result = heurisch(f, x, mappings=mappings, rewrite=rewrite, hints=hints, retries=retries - 1, unnecessary_permutations=unnecessary_permutations)
|
767 |
+
|
768 |
+
if result is not None:
|
769 |
+
return indep*result
|
770 |
+
|
771 |
+
return None
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/integrals.py
ADDED
@@ -0,0 +1,1633 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple as tTuple
|
2 |
+
|
3 |
+
from sympy.concrete.expr_with_limits import AddWithLimits
|
4 |
+
from sympy.core.add import Add
|
5 |
+
from sympy.core.basic import Basic
|
6 |
+
from sympy.core.containers import Tuple
|
7 |
+
from sympy.core.expr import Expr
|
8 |
+
from sympy.core.exprtools import factor_terms
|
9 |
+
from sympy.core.function import diff
|
10 |
+
from sympy.core.logic import fuzzy_bool
|
11 |
+
from sympy.core.mul import Mul
|
12 |
+
from sympy.core.numbers import oo, pi
|
13 |
+
from sympy.core.relational import Ne
|
14 |
+
from sympy.core.singleton import S
|
15 |
+
from sympy.core.symbol import (Dummy, Symbol, Wild)
|
16 |
+
from sympy.core.sympify import sympify
|
17 |
+
from sympy.functions import Piecewise, sqrt, piecewise_fold, tan, cot, atan
|
18 |
+
from sympy.functions.elementary.exponential import log
|
19 |
+
from sympy.functions.elementary.integers import floor
|
20 |
+
from sympy.functions.elementary.complexes import Abs, sign
|
21 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
22 |
+
from .rationaltools import ratint
|
23 |
+
from sympy.matrices import MatrixBase
|
24 |
+
from sympy.polys import Poly, PolynomialError
|
25 |
+
from sympy.series.formal import FormalPowerSeries
|
26 |
+
from sympy.series.limits import limit
|
27 |
+
from sympy.series.order import Order
|
28 |
+
from sympy.tensor.functions import shape
|
29 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
30 |
+
from sympy.utilities.iterables import is_sequence
|
31 |
+
from sympy.utilities.misc import filldedent
|
32 |
+
|
33 |
+
|
34 |
+
class Integral(AddWithLimits):
|
35 |
+
"""Represents unevaluated integral."""
|
36 |
+
|
37 |
+
__slots__ = ()
|
38 |
+
|
39 |
+
args: tTuple[Expr, Tuple]
|
40 |
+
|
41 |
+
def __new__(cls, function, *symbols, **assumptions):
|
42 |
+
"""Create an unevaluated integral.
|
43 |
+
|
44 |
+
Explanation
|
45 |
+
===========
|
46 |
+
|
47 |
+
Arguments are an integrand followed by one or more limits.
|
48 |
+
|
49 |
+
If no limits are given and there is only one free symbol in the
|
50 |
+
expression, that symbol will be used, otherwise an error will be
|
51 |
+
raised.
|
52 |
+
|
53 |
+
>>> from sympy import Integral
|
54 |
+
>>> from sympy.abc import x, y
|
55 |
+
>>> Integral(x)
|
56 |
+
Integral(x, x)
|
57 |
+
>>> Integral(y)
|
58 |
+
Integral(y, y)
|
59 |
+
|
60 |
+
When limits are provided, they are interpreted as follows (using
|
61 |
+
``x`` as though it were the variable of integration):
|
62 |
+
|
63 |
+
(x,) or x - indefinite integral
|
64 |
+
(x, a) - "evaluate at" integral is an abstract antiderivative
|
65 |
+
(x, a, b) - definite integral
|
66 |
+
|
67 |
+
The ``as_dummy`` method can be used to see which symbols cannot be
|
68 |
+
targeted by subs: those with a prepended underscore cannot be
|
69 |
+
changed with ``subs``. (Also, the integration variables themselves --
|
70 |
+
the first element of a limit -- can never be changed by subs.)
|
71 |
+
|
72 |
+
>>> i = Integral(x, x)
|
73 |
+
>>> at = Integral(x, (x, x))
|
74 |
+
>>> i.as_dummy()
|
75 |
+
Integral(x, x)
|
76 |
+
>>> at.as_dummy()
|
77 |
+
Integral(_0, (_0, x))
|
78 |
+
|
79 |
+
"""
|
80 |
+
|
81 |
+
#This will help other classes define their own definitions
|
82 |
+
#of behaviour with Integral.
|
83 |
+
if hasattr(function, '_eval_Integral'):
|
84 |
+
return function._eval_Integral(*symbols, **assumptions)
|
85 |
+
|
86 |
+
if isinstance(function, Poly):
|
87 |
+
sympy_deprecation_warning(
|
88 |
+
"""
|
89 |
+
integrate(Poly) and Integral(Poly) are deprecated. Instead,
|
90 |
+
use the Poly.integrate() method, or convert the Poly to an
|
91 |
+
Expr first with the Poly.as_expr() method.
|
92 |
+
""",
|
93 |
+
deprecated_since_version="1.6",
|
94 |
+
active_deprecations_target="deprecated-integrate-poly")
|
95 |
+
|
96 |
+
obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
|
97 |
+
return obj
|
98 |
+
|
99 |
+
def __getnewargs__(self):
|
100 |
+
return (self.function,) + tuple([tuple(xab) for xab in self.limits])
|
101 |
+
|
102 |
+
@property
|
103 |
+
def free_symbols(self):
|
104 |
+
"""
|
105 |
+
This method returns the symbols that will exist when the
|
106 |
+
integral is evaluated. This is useful if one is trying to
|
107 |
+
determine whether an integral depends on a certain
|
108 |
+
symbol or not.
|
109 |
+
|
110 |
+
Examples
|
111 |
+
========
|
112 |
+
|
113 |
+
>>> from sympy import Integral
|
114 |
+
>>> from sympy.abc import x, y
|
115 |
+
>>> Integral(x, (x, y, 1)).free_symbols
|
116 |
+
{y}
|
117 |
+
|
118 |
+
See Also
|
119 |
+
========
|
120 |
+
|
121 |
+
sympy.concrete.expr_with_limits.ExprWithLimits.function
|
122 |
+
sympy.concrete.expr_with_limits.ExprWithLimits.limits
|
123 |
+
sympy.concrete.expr_with_limits.ExprWithLimits.variables
|
124 |
+
"""
|
125 |
+
return super().free_symbols
|
126 |
+
|
127 |
+
def _eval_is_zero(self):
|
128 |
+
# This is a very naive and quick test, not intended to do the integral to
|
129 |
+
# answer whether it is zero or not, e.g. Integral(sin(x), (x, 0, 2*pi))
|
130 |
+
# is zero but this routine should return None for that case. But, like
|
131 |
+
# Mul, there are trivial situations for which the integral will be
|
132 |
+
# zero so we check for those.
|
133 |
+
if self.function.is_zero:
|
134 |
+
return True
|
135 |
+
got_none = False
|
136 |
+
for l in self.limits:
|
137 |
+
if len(l) == 3:
|
138 |
+
z = (l[1] == l[2]) or (l[1] - l[2]).is_zero
|
139 |
+
if z:
|
140 |
+
return True
|
141 |
+
elif z is None:
|
142 |
+
got_none = True
|
143 |
+
free = self.function.free_symbols
|
144 |
+
for xab in self.limits:
|
145 |
+
if len(xab) == 1:
|
146 |
+
free.add(xab[0])
|
147 |
+
continue
|
148 |
+
if len(xab) == 2 and xab[0] not in free:
|
149 |
+
if xab[1].is_zero:
|
150 |
+
return True
|
151 |
+
elif xab[1].is_zero is None:
|
152 |
+
got_none = True
|
153 |
+
# take integration symbol out of free since it will be replaced
|
154 |
+
# with the free symbols in the limits
|
155 |
+
free.discard(xab[0])
|
156 |
+
# add in the new symbols
|
157 |
+
for i in xab[1:]:
|
158 |
+
free.update(i.free_symbols)
|
159 |
+
if self.function.is_zero is False and got_none is False:
|
160 |
+
return False
|
161 |
+
|
162 |
+
def transform(self, x, u):
|
163 |
+
r"""
|
164 |
+
Performs a change of variables from `x` to `u` using the relationship
|
165 |
+
given by `x` and `u` which will define the transformations `f` and `F`
|
166 |
+
(which are inverses of each other) as follows:
|
167 |
+
|
168 |
+
1) If `x` is a Symbol (which is a variable of integration) then `u`
|
169 |
+
will be interpreted as some function, f(u), with inverse F(u).
|
170 |
+
This, in effect, just makes the substitution of x with f(x).
|
171 |
+
|
172 |
+
2) If `u` is a Symbol then `x` will be interpreted as some function,
|
173 |
+
F(x), with inverse f(u). This is commonly referred to as
|
174 |
+
u-substitution.
|
175 |
+
|
176 |
+
Once f and F have been identified, the transformation is made as
|
177 |
+
follows:
|
178 |
+
|
179 |
+
.. math:: \int_a^b x \mathrm{d}x \rightarrow \int_{F(a)}^{F(b)} f(x)
|
180 |
+
\frac{\mathrm{d}}{\mathrm{d}x}
|
181 |
+
|
182 |
+
where `F(x)` is the inverse of `f(x)` and the limits and integrand have
|
183 |
+
been corrected so as to retain the same value after integration.
|
184 |
+
|
185 |
+
Notes
|
186 |
+
=====
|
187 |
+
|
188 |
+
The mappings, F(x) or f(u), must lead to a unique integral. Linear
|
189 |
+
or rational linear expression, ``2*x``, ``1/x`` and ``sqrt(x)``, will
|
190 |
+
always work; quadratic expressions like ``x**2 - 1`` are acceptable
|
191 |
+
as long as the resulting integrand does not depend on the sign of
|
192 |
+
the solutions (see examples).
|
193 |
+
|
194 |
+
The integral will be returned unchanged if ``x`` is not a variable of
|
195 |
+
integration.
|
196 |
+
|
197 |
+
``x`` must be (or contain) only one of of the integration variables. If
|
198 |
+
``u`` has more than one free symbol then it should be sent as a tuple
|
199 |
+
(``u``, ``uvar``) where ``uvar`` identifies which variable is replacing
|
200 |
+
the integration variable.
|
201 |
+
XXX can it contain another integration variable?
|
202 |
+
|
203 |
+
Examples
|
204 |
+
========
|
205 |
+
|
206 |
+
>>> from sympy.abc import a, x, u
|
207 |
+
>>> from sympy import Integral, cos, sqrt
|
208 |
+
|
209 |
+
>>> i = Integral(x*cos(x**2 - 1), (x, 0, 1))
|
210 |
+
|
211 |
+
transform can change the variable of integration
|
212 |
+
|
213 |
+
>>> i.transform(x, u)
|
214 |
+
Integral(u*cos(u**2 - 1), (u, 0, 1))
|
215 |
+
|
216 |
+
transform can perform u-substitution as long as a unique
|
217 |
+
integrand is obtained:
|
218 |
+
|
219 |
+
>>> i.transform(x**2 - 1, u)
|
220 |
+
Integral(cos(u)/2, (u, -1, 0))
|
221 |
+
|
222 |
+
This attempt fails because x = +/-sqrt(u + 1) and the
|
223 |
+
sign does not cancel out of the integrand:
|
224 |
+
|
225 |
+
>>> Integral(cos(x**2 - 1), (x, 0, 1)).transform(x**2 - 1, u)
|
226 |
+
Traceback (most recent call last):
|
227 |
+
...
|
228 |
+
ValueError:
|
229 |
+
The mapping between F(x) and f(u) did not give a unique integrand.
|
230 |
+
|
231 |
+
transform can do a substitution. Here, the previous
|
232 |
+
result is transformed back into the original expression
|
233 |
+
using "u-substitution":
|
234 |
+
|
235 |
+
>>> ui = _
|
236 |
+
>>> _.transform(sqrt(u + 1), x) == i
|
237 |
+
True
|
238 |
+
|
239 |
+
We can accomplish the same with a regular substitution:
|
240 |
+
|
241 |
+
>>> ui.transform(u, x**2 - 1) == i
|
242 |
+
True
|
243 |
+
|
244 |
+
If the `x` does not contain a symbol of integration then
|
245 |
+
the integral will be returned unchanged. Integral `i` does
|
246 |
+
not have an integration variable `a` so no change is made:
|
247 |
+
|
248 |
+
>>> i.transform(a, x) == i
|
249 |
+
True
|
250 |
+
|
251 |
+
When `u` has more than one free symbol the symbol that is
|
252 |
+
replacing `x` must be identified by passing `u` as a tuple:
|
253 |
+
|
254 |
+
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, u))
|
255 |
+
Integral(a + u, (u, -a, 1 - a))
|
256 |
+
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, a))
|
257 |
+
Integral(a + u, (a, -u, 1 - u))
|
258 |
+
|
259 |
+
See Also
|
260 |
+
========
|
261 |
+
|
262 |
+
sympy.concrete.expr_with_limits.ExprWithLimits.variables : Lists the integration variables
|
263 |
+
as_dummy : Replace integration variables with dummy ones
|
264 |
+
"""
|
265 |
+
d = Dummy('d')
|
266 |
+
|
267 |
+
xfree = x.free_symbols.intersection(self.variables)
|
268 |
+
if len(xfree) > 1:
|
269 |
+
raise ValueError(
|
270 |
+
'F(x) can only contain one of: %s' % self.variables)
|
271 |
+
xvar = xfree.pop() if xfree else d
|
272 |
+
|
273 |
+
if xvar not in self.variables:
|
274 |
+
return self
|
275 |
+
|
276 |
+
u = sympify(u)
|
277 |
+
if isinstance(u, Expr):
|
278 |
+
ufree = u.free_symbols
|
279 |
+
if len(ufree) == 0:
|
280 |
+
raise ValueError(filldedent('''
|
281 |
+
f(u) cannot be a constant'''))
|
282 |
+
if len(ufree) > 1:
|
283 |
+
raise ValueError(filldedent('''
|
284 |
+
When f(u) has more than one free symbol, the one replacing x
|
285 |
+
must be identified: pass f(u) as (f(u), u)'''))
|
286 |
+
uvar = ufree.pop()
|
287 |
+
else:
|
288 |
+
u, uvar = u
|
289 |
+
if uvar not in u.free_symbols:
|
290 |
+
raise ValueError(filldedent('''
|
291 |
+
Expecting a tuple (expr, symbol) where symbol identified
|
292 |
+
a free symbol in expr, but symbol is not in expr's free
|
293 |
+
symbols.'''))
|
294 |
+
if not isinstance(uvar, Symbol):
|
295 |
+
# This probably never evaluates to True
|
296 |
+
raise ValueError(filldedent('''
|
297 |
+
Expecting a tuple (expr, symbol) but didn't get
|
298 |
+
a symbol; got %s''' % uvar))
|
299 |
+
|
300 |
+
if x.is_Symbol and u.is_Symbol:
|
301 |
+
return self.xreplace({x: u})
|
302 |
+
|
303 |
+
if not x.is_Symbol and not u.is_Symbol:
|
304 |
+
raise ValueError('either x or u must be a symbol')
|
305 |
+
|
306 |
+
if uvar == xvar:
|
307 |
+
return self.transform(x, (u.subs(uvar, d), d)).xreplace({d: uvar})
|
308 |
+
|
309 |
+
if uvar in self.limits:
|
310 |
+
raise ValueError(filldedent('''
|
311 |
+
u must contain the same variable as in x
|
312 |
+
or a variable that is not already an integration variable'''))
|
313 |
+
|
314 |
+
from sympy.solvers.solvers import solve
|
315 |
+
if not x.is_Symbol:
|
316 |
+
F = [x.subs(xvar, d)]
|
317 |
+
soln = solve(u - x, xvar, check=False)
|
318 |
+
if not soln:
|
319 |
+
raise ValueError('no solution for solve(F(x) - f(u), x)')
|
320 |
+
f = [fi.subs(uvar, d) for fi in soln]
|
321 |
+
else:
|
322 |
+
f = [u.subs(uvar, d)]
|
323 |
+
from sympy.simplify.simplify import posify
|
324 |
+
pdiff, reps = posify(u - x)
|
325 |
+
puvar = uvar.subs([(v, k) for k, v in reps.items()])
|
326 |
+
soln = [s.subs(reps) for s in solve(pdiff, puvar)]
|
327 |
+
if not soln:
|
328 |
+
raise ValueError('no solution for solve(F(x) - f(u), u)')
|
329 |
+
F = [fi.subs(xvar, d) for fi in soln]
|
330 |
+
|
331 |
+
newfuncs = {(self.function.subs(xvar, fi)*fi.diff(d)
|
332 |
+
).subs(d, uvar) for fi in f}
|
333 |
+
if len(newfuncs) > 1:
|
334 |
+
raise ValueError(filldedent('''
|
335 |
+
The mapping between F(x) and f(u) did not give
|
336 |
+
a unique integrand.'''))
|
337 |
+
newfunc = newfuncs.pop()
|
338 |
+
|
339 |
+
def _calc_limit_1(F, a, b):
|
340 |
+
"""
|
341 |
+
replace d with a, using subs if possible, otherwise limit
|
342 |
+
where sign of b is considered
|
343 |
+
"""
|
344 |
+
wok = F.subs(d, a)
|
345 |
+
if wok is S.NaN or wok.is_finite is False and a.is_finite:
|
346 |
+
return limit(sign(b)*F, d, a)
|
347 |
+
return wok
|
348 |
+
|
349 |
+
def _calc_limit(a, b):
|
350 |
+
"""
|
351 |
+
replace d with a, using subs if possible, otherwise limit
|
352 |
+
where sign of b is considered
|
353 |
+
"""
|
354 |
+
avals = list({_calc_limit_1(Fi, a, b) for Fi in F})
|
355 |
+
if len(avals) > 1:
|
356 |
+
raise ValueError(filldedent('''
|
357 |
+
The mapping between F(x) and f(u) did not
|
358 |
+
give a unique limit.'''))
|
359 |
+
return avals[0]
|
360 |
+
|
361 |
+
newlimits = []
|
362 |
+
for xab in self.limits:
|
363 |
+
sym = xab[0]
|
364 |
+
if sym == xvar:
|
365 |
+
if len(xab) == 3:
|
366 |
+
a, b = xab[1:]
|
367 |
+
a, b = _calc_limit(a, b), _calc_limit(b, a)
|
368 |
+
if fuzzy_bool(a - b > 0):
|
369 |
+
a, b = b, a
|
370 |
+
newfunc = -newfunc
|
371 |
+
newlimits.append((uvar, a, b))
|
372 |
+
elif len(xab) == 2:
|
373 |
+
a = _calc_limit(xab[1], 1)
|
374 |
+
newlimits.append((uvar, a))
|
375 |
+
else:
|
376 |
+
newlimits.append(uvar)
|
377 |
+
else:
|
378 |
+
newlimits.append(xab)
|
379 |
+
|
380 |
+
return self.func(newfunc, *newlimits)
|
381 |
+
|
382 |
+
def doit(self, **hints):
|
383 |
+
"""
|
384 |
+
Perform the integration using any hints given.
|
385 |
+
|
386 |
+
Examples
|
387 |
+
========
|
388 |
+
|
389 |
+
>>> from sympy import Piecewise, S
|
390 |
+
>>> from sympy.abc import x, t
|
391 |
+
>>> p = x**2 + Piecewise((0, x/t < 0), (1, True))
|
392 |
+
>>> p.integrate((t, S(4)/5, 1), (x, -1, 1))
|
393 |
+
1/3
|
394 |
+
|
395 |
+
See Also
|
396 |
+
========
|
397 |
+
|
398 |
+
sympy.integrals.trigonometry.trigintegrate
|
399 |
+
sympy.integrals.heurisch.heurisch
|
400 |
+
sympy.integrals.rationaltools.ratint
|
401 |
+
as_sum : Approximate the integral using a sum
|
402 |
+
"""
|
403 |
+
if not hints.get('integrals', True):
|
404 |
+
return self
|
405 |
+
|
406 |
+
deep = hints.get('deep', True)
|
407 |
+
meijerg = hints.get('meijerg', None)
|
408 |
+
conds = hints.get('conds', 'piecewise')
|
409 |
+
risch = hints.get('risch', None)
|
410 |
+
heurisch = hints.get('heurisch', None)
|
411 |
+
manual = hints.get('manual', None)
|
412 |
+
if len(list(filter(None, (manual, meijerg, risch, heurisch)))) > 1:
|
413 |
+
raise ValueError("At most one of manual, meijerg, risch, heurisch can be True")
|
414 |
+
elif manual:
|
415 |
+
meijerg = risch = heurisch = False
|
416 |
+
elif meijerg:
|
417 |
+
manual = risch = heurisch = False
|
418 |
+
elif risch:
|
419 |
+
manual = meijerg = heurisch = False
|
420 |
+
elif heurisch:
|
421 |
+
manual = meijerg = risch = False
|
422 |
+
eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual, "heurisch": heurisch,
|
423 |
+
"conds": conds}
|
424 |
+
|
425 |
+
if conds not in ('separate', 'piecewise', 'none'):
|
426 |
+
raise ValueError('conds must be one of "separate", "piecewise", '
|
427 |
+
'"none", got: %s' % conds)
|
428 |
+
|
429 |
+
if risch and any(len(xab) > 1 for xab in self.limits):
|
430 |
+
raise ValueError('risch=True is only allowed for indefinite integrals.')
|
431 |
+
|
432 |
+
# check for the trivial zero
|
433 |
+
if self.is_zero:
|
434 |
+
return S.Zero
|
435 |
+
|
436 |
+
# hacks to handle integrals of
|
437 |
+
# nested summations
|
438 |
+
from sympy.concrete.summations import Sum
|
439 |
+
if isinstance(self.function, Sum):
|
440 |
+
if any(v in self.function.limits[0] for v in self.variables):
|
441 |
+
raise ValueError('Limit of the sum cannot be an integration variable.')
|
442 |
+
if any(l.is_infinite for l in self.function.limits[0][1:]):
|
443 |
+
return self
|
444 |
+
_i = self
|
445 |
+
_sum = self.function
|
446 |
+
return _sum.func(_i.func(_sum.function, *_i.limits).doit(), *_sum.limits).doit()
|
447 |
+
|
448 |
+
# now compute and check the function
|
449 |
+
function = self.function
|
450 |
+
if deep:
|
451 |
+
function = function.doit(**hints)
|
452 |
+
if function.is_zero:
|
453 |
+
return S.Zero
|
454 |
+
|
455 |
+
# hacks to handle special cases
|
456 |
+
if isinstance(function, MatrixBase):
|
457 |
+
return function.applyfunc(
|
458 |
+
lambda f: self.func(f, *self.limits).doit(**hints))
|
459 |
+
|
460 |
+
if isinstance(function, FormalPowerSeries):
|
461 |
+
if len(self.limits) > 1:
|
462 |
+
raise NotImplementedError
|
463 |
+
xab = self.limits[0]
|
464 |
+
if len(xab) > 1:
|
465 |
+
return function.integrate(xab, **eval_kwargs)
|
466 |
+
else:
|
467 |
+
return function.integrate(xab[0], **eval_kwargs)
|
468 |
+
|
469 |
+
# There is no trivial answer and special handling
|
470 |
+
# is done so continue
|
471 |
+
|
472 |
+
# first make sure any definite limits have integration
|
473 |
+
# variables with matching assumptions
|
474 |
+
reps = {}
|
475 |
+
for xab in self.limits:
|
476 |
+
if len(xab) != 3:
|
477 |
+
# it makes sense to just make
|
478 |
+
# all x real but in practice with the
|
479 |
+
# current state of integration...this
|
480 |
+
# doesn't work out well
|
481 |
+
# x = xab[0]
|
482 |
+
# if x not in reps and not x.is_real:
|
483 |
+
# reps[x] = Dummy(real=True)
|
484 |
+
continue
|
485 |
+
x, a, b = xab
|
486 |
+
l = (a, b)
|
487 |
+
if all(i.is_nonnegative for i in l) and not x.is_nonnegative:
|
488 |
+
d = Dummy(positive=True)
|
489 |
+
elif all(i.is_nonpositive for i in l) and not x.is_nonpositive:
|
490 |
+
d = Dummy(negative=True)
|
491 |
+
elif all(i.is_real for i in l) and not x.is_real:
|
492 |
+
d = Dummy(real=True)
|
493 |
+
else:
|
494 |
+
d = None
|
495 |
+
if d:
|
496 |
+
reps[x] = d
|
497 |
+
if reps:
|
498 |
+
undo = {v: k for k, v in reps.items()}
|
499 |
+
did = self.xreplace(reps).doit(**hints)
|
500 |
+
if isinstance(did, tuple): # when separate=True
|
501 |
+
did = tuple([i.xreplace(undo) for i in did])
|
502 |
+
else:
|
503 |
+
did = did.xreplace(undo)
|
504 |
+
return did
|
505 |
+
|
506 |
+
# continue with existing assumptions
|
507 |
+
undone_limits = []
|
508 |
+
# ulj = free symbols of any undone limits' upper and lower limits
|
509 |
+
ulj = set()
|
510 |
+
for xab in self.limits:
|
511 |
+
# compute uli, the free symbols in the
|
512 |
+
# Upper and Lower limits of limit I
|
513 |
+
if len(xab) == 1:
|
514 |
+
uli = set(xab[:1])
|
515 |
+
elif len(xab) == 2:
|
516 |
+
uli = xab[1].free_symbols
|
517 |
+
elif len(xab) == 3:
|
518 |
+
uli = xab[1].free_symbols.union(xab[2].free_symbols)
|
519 |
+
# this integral can be done as long as there is no blocking
|
520 |
+
# limit that has been undone. An undone limit is blocking if
|
521 |
+
# it contains an integration variable that is in this limit's
|
522 |
+
# upper or lower free symbols or vice versa
|
523 |
+
if xab[0] in ulj or any(v[0] in uli for v in undone_limits):
|
524 |
+
undone_limits.append(xab)
|
525 |
+
ulj.update(uli)
|
526 |
+
function = self.func(*([function] + [xab]))
|
527 |
+
factored_function = function.factor()
|
528 |
+
if not isinstance(factored_function, Integral):
|
529 |
+
function = factored_function
|
530 |
+
continue
|
531 |
+
|
532 |
+
if function.has(Abs, sign) and (
|
533 |
+
(len(xab) < 3 and all(x.is_extended_real for x in xab)) or
|
534 |
+
(len(xab) == 3 and all(x.is_extended_real and not x.is_infinite for
|
535 |
+
x in xab[1:]))):
|
536 |
+
# some improper integrals are better off with Abs
|
537 |
+
xr = Dummy("xr", real=True)
|
538 |
+
function = (function.xreplace({xab[0]: xr})
|
539 |
+
.rewrite(Piecewise).xreplace({xr: xab[0]}))
|
540 |
+
elif function.has(Min, Max):
|
541 |
+
function = function.rewrite(Piecewise)
|
542 |
+
if (function.has(Piecewise) and
|
543 |
+
not isinstance(function, Piecewise)):
|
544 |
+
function = piecewise_fold(function)
|
545 |
+
if isinstance(function, Piecewise):
|
546 |
+
if len(xab) == 1:
|
547 |
+
antideriv = function._eval_integral(xab[0],
|
548 |
+
**eval_kwargs)
|
549 |
+
else:
|
550 |
+
antideriv = self._eval_integral(
|
551 |
+
function, xab[0], **eval_kwargs)
|
552 |
+
else:
|
553 |
+
# There are a number of tradeoffs in using the
|
554 |
+
# Meijer G method. It can sometimes be a lot faster
|
555 |
+
# than other methods, and sometimes slower. And
|
556 |
+
# there are certain types of integrals for which it
|
557 |
+
# is more likely to work than others. These
|
558 |
+
# heuristics are incorporated in deciding what
|
559 |
+
# integration methods to try, in what order. See the
|
560 |
+
# integrate() docstring for details.
|
561 |
+
def try_meijerg(function, xab):
|
562 |
+
ret = None
|
563 |
+
if len(xab) == 3 and meijerg is not False:
|
564 |
+
x, a, b = xab
|
565 |
+
try:
|
566 |
+
res = meijerint_definite(function, x, a, b)
|
567 |
+
except NotImplementedError:
|
568 |
+
_debug('NotImplementedError '
|
569 |
+
'from meijerint_definite')
|
570 |
+
res = None
|
571 |
+
if res is not None:
|
572 |
+
f, cond = res
|
573 |
+
if conds == 'piecewise':
|
574 |
+
u = self.func(function, (x, a, b))
|
575 |
+
# if Piecewise modifies cond too
|
576 |
+
# much it may not be recognized by
|
577 |
+
# _condsimp pattern matching so just
|
578 |
+
# turn off all evaluation
|
579 |
+
return Piecewise((f, cond), (u, True),
|
580 |
+
evaluate=False)
|
581 |
+
elif conds == 'separate':
|
582 |
+
if len(self.limits) != 1:
|
583 |
+
raise ValueError(filldedent('''
|
584 |
+
conds=separate not supported in
|
585 |
+
multiple integrals'''))
|
586 |
+
ret = f, cond
|
587 |
+
else:
|
588 |
+
ret = f
|
589 |
+
return ret
|
590 |
+
|
591 |
+
meijerg1 = meijerg
|
592 |
+
if (meijerg is not False and
|
593 |
+
len(xab) == 3 and xab[1].is_extended_real and xab[2].is_extended_real
|
594 |
+
and not function.is_Poly and
|
595 |
+
(xab[1].has(oo, -oo) or xab[2].has(oo, -oo))):
|
596 |
+
ret = try_meijerg(function, xab)
|
597 |
+
if ret is not None:
|
598 |
+
function = ret
|
599 |
+
continue
|
600 |
+
meijerg1 = False
|
601 |
+
# If the special meijerg code did not succeed in
|
602 |
+
# finding a definite integral, then the code using
|
603 |
+
# meijerint_indefinite will not either (it might
|
604 |
+
# find an antiderivative, but the answer is likely
|
605 |
+
# to be nonsensical). Thus if we are requested to
|
606 |
+
# only use Meijer G-function methods, we give up at
|
607 |
+
# this stage. Otherwise we just disable G-function
|
608 |
+
# methods.
|
609 |
+
if meijerg1 is False and meijerg is True:
|
610 |
+
antideriv = None
|
611 |
+
else:
|
612 |
+
antideriv = self._eval_integral(
|
613 |
+
function, xab[0], **eval_kwargs)
|
614 |
+
if antideriv is None and meijerg is True:
|
615 |
+
ret = try_meijerg(function, xab)
|
616 |
+
if ret is not None:
|
617 |
+
function = ret
|
618 |
+
continue
|
619 |
+
|
620 |
+
final = hints.get('final', True)
|
621 |
+
# dotit may be iterated but floor terms making atan and acot
|
622 |
+
# continuous should only be added in the final round
|
623 |
+
if (final and not isinstance(antideriv, Integral) and
|
624 |
+
antideriv is not None):
|
625 |
+
for atan_term in antideriv.atoms(atan):
|
626 |
+
atan_arg = atan_term.args[0]
|
627 |
+
# Checking `atan_arg` to be linear combination of `tan` or `cot`
|
628 |
+
for tan_part in atan_arg.atoms(tan):
|
629 |
+
x1 = Dummy('x1')
|
630 |
+
tan_exp1 = atan_arg.subs(tan_part, x1)
|
631 |
+
# The coefficient of `tan` should be constant
|
632 |
+
coeff = tan_exp1.diff(x1)
|
633 |
+
if x1 not in coeff.free_symbols:
|
634 |
+
a = tan_part.args[0]
|
635 |
+
antideriv = antideriv.subs(atan_term, Add(atan_term,
|
636 |
+
sign(coeff)*pi*floor((a-pi/2)/pi)))
|
637 |
+
for cot_part in atan_arg.atoms(cot):
|
638 |
+
x1 = Dummy('x1')
|
639 |
+
cot_exp1 = atan_arg.subs(cot_part, x1)
|
640 |
+
# The coefficient of `cot` should be constant
|
641 |
+
coeff = cot_exp1.diff(x1)
|
642 |
+
if x1 not in coeff.free_symbols:
|
643 |
+
a = cot_part.args[0]
|
644 |
+
antideriv = antideriv.subs(atan_term, Add(atan_term,
|
645 |
+
sign(coeff)*pi*floor((a)/pi)))
|
646 |
+
|
647 |
+
if antideriv is None:
|
648 |
+
undone_limits.append(xab)
|
649 |
+
function = self.func(*([function] + [xab])).factor()
|
650 |
+
factored_function = function.factor()
|
651 |
+
if not isinstance(factored_function, Integral):
|
652 |
+
function = factored_function
|
653 |
+
continue
|
654 |
+
else:
|
655 |
+
if len(xab) == 1:
|
656 |
+
function = antideriv
|
657 |
+
else:
|
658 |
+
if len(xab) == 3:
|
659 |
+
x, a, b = xab
|
660 |
+
elif len(xab) == 2:
|
661 |
+
x, b = xab
|
662 |
+
a = None
|
663 |
+
else:
|
664 |
+
raise NotImplementedError
|
665 |
+
|
666 |
+
if deep:
|
667 |
+
if isinstance(a, Basic):
|
668 |
+
a = a.doit(**hints)
|
669 |
+
if isinstance(b, Basic):
|
670 |
+
b = b.doit(**hints)
|
671 |
+
|
672 |
+
if antideriv.is_Poly:
|
673 |
+
gens = list(antideriv.gens)
|
674 |
+
gens.remove(x)
|
675 |
+
|
676 |
+
antideriv = antideriv.as_expr()
|
677 |
+
|
678 |
+
function = antideriv._eval_interval(x, a, b)
|
679 |
+
function = Poly(function, *gens)
|
680 |
+
else:
|
681 |
+
def is_indef_int(g, x):
|
682 |
+
return (isinstance(g, Integral) and
|
683 |
+
any(i == (x,) for i in g.limits))
|
684 |
+
|
685 |
+
def eval_factored(f, x, a, b):
|
686 |
+
# _eval_interval for integrals with
|
687 |
+
# (constant) factors
|
688 |
+
# a single indefinite integral is assumed
|
689 |
+
args = []
|
690 |
+
for g in Mul.make_args(f):
|
691 |
+
if is_indef_int(g, x):
|
692 |
+
args.append(g._eval_interval(x, a, b))
|
693 |
+
else:
|
694 |
+
args.append(g)
|
695 |
+
return Mul(*args)
|
696 |
+
|
697 |
+
integrals, others, piecewises = [], [], []
|
698 |
+
for f in Add.make_args(antideriv):
|
699 |
+
if any(is_indef_int(g, x)
|
700 |
+
for g in Mul.make_args(f)):
|
701 |
+
integrals.append(f)
|
702 |
+
elif any(isinstance(g, Piecewise)
|
703 |
+
for g in Mul.make_args(f)):
|
704 |
+
piecewises.append(piecewise_fold(f))
|
705 |
+
else:
|
706 |
+
others.append(f)
|
707 |
+
uneval = Add(*[eval_factored(f, x, a, b)
|
708 |
+
for f in integrals])
|
709 |
+
try:
|
710 |
+
evalued = Add(*others)._eval_interval(x, a, b)
|
711 |
+
evalued_pw = piecewise_fold(Add(*piecewises))._eval_interval(x, a, b)
|
712 |
+
function = uneval + evalued + evalued_pw
|
713 |
+
except NotImplementedError:
|
714 |
+
# This can happen if _eval_interval depends in a
|
715 |
+
# complicated way on limits that cannot be computed
|
716 |
+
undone_limits.append(xab)
|
717 |
+
function = self.func(*([function] + [xab]))
|
718 |
+
factored_function = function.factor()
|
719 |
+
if not isinstance(factored_function, Integral):
|
720 |
+
function = factored_function
|
721 |
+
return function
|
722 |
+
|
723 |
+
def _eval_derivative(self, sym):
|
724 |
+
"""Evaluate the derivative of the current Integral object by
|
725 |
+
differentiating under the integral sign [1], using the Fundamental
|
726 |
+
Theorem of Calculus [2] when possible.
|
727 |
+
|
728 |
+
Explanation
|
729 |
+
===========
|
730 |
+
|
731 |
+
Whenever an Integral is encountered that is equivalent to zero or
|
732 |
+
has an integrand that is independent of the variable of integration
|
733 |
+
those integrals are performed. All others are returned as Integral
|
734 |
+
instances which can be resolved with doit() (provided they are integrable).
|
735 |
+
|
736 |
+
References
|
737 |
+
==========
|
738 |
+
|
739 |
+
.. [1] https://en.wikipedia.org/wiki/Differentiation_under_the_integral_sign
|
740 |
+
.. [2] https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus
|
741 |
+
|
742 |
+
Examples
|
743 |
+
========
|
744 |
+
|
745 |
+
>>> from sympy import Integral
|
746 |
+
>>> from sympy.abc import x, y
|
747 |
+
>>> i = Integral(x + y, y, (y, 1, x))
|
748 |
+
>>> i.diff(x)
|
749 |
+
Integral(x + y, (y, x)) + Integral(1, y, (y, 1, x))
|
750 |
+
>>> i.doit().diff(x) == i.diff(x).doit()
|
751 |
+
True
|
752 |
+
>>> i.diff(y)
|
753 |
+
0
|
754 |
+
|
755 |
+
The previous must be true since there is no y in the evaluated integral:
|
756 |
+
|
757 |
+
>>> i.free_symbols
|
758 |
+
{x}
|
759 |
+
>>> i.doit()
|
760 |
+
2*x**3/3 - x/2 - 1/6
|
761 |
+
|
762 |
+
"""
|
763 |
+
|
764 |
+
# differentiate under the integral sign; we do not
|
765 |
+
# check for regularity conditions (TODO), see issue 4215
|
766 |
+
|
767 |
+
# get limits and the function
|
768 |
+
f, limits = self.function, list(self.limits)
|
769 |
+
|
770 |
+
# the order matters if variables of integration appear in the limits
|
771 |
+
# so work our way in from the outside to the inside.
|
772 |
+
limit = limits.pop(-1)
|
773 |
+
if len(limit) == 3:
|
774 |
+
x, a, b = limit
|
775 |
+
elif len(limit) == 2:
|
776 |
+
x, b = limit
|
777 |
+
a = None
|
778 |
+
else:
|
779 |
+
a = b = None
|
780 |
+
x = limit[0]
|
781 |
+
|
782 |
+
if limits: # f is the argument to an integral
|
783 |
+
f = self.func(f, *tuple(limits))
|
784 |
+
|
785 |
+
# assemble the pieces
|
786 |
+
def _do(f, ab):
|
787 |
+
dab_dsym = diff(ab, sym)
|
788 |
+
if not dab_dsym:
|
789 |
+
return S.Zero
|
790 |
+
if isinstance(f, Integral):
|
791 |
+
limits = [(x, x) if (len(l) == 1 and l[0] == x) else l
|
792 |
+
for l in f.limits]
|
793 |
+
f = self.func(f.function, *limits)
|
794 |
+
return f.subs(x, ab)*dab_dsym
|
795 |
+
|
796 |
+
rv = S.Zero
|
797 |
+
if b is not None:
|
798 |
+
rv += _do(f, b)
|
799 |
+
if a is not None:
|
800 |
+
rv -= _do(f, a)
|
801 |
+
if len(limit) == 1 and sym == x:
|
802 |
+
# the dummy variable *is* also the real-world variable
|
803 |
+
arg = f
|
804 |
+
rv += arg
|
805 |
+
else:
|
806 |
+
# the dummy variable might match sym but it's
|
807 |
+
# only a dummy and the actual variable is determined
|
808 |
+
# by the limits, so mask off the variable of integration
|
809 |
+
# while differentiating
|
810 |
+
u = Dummy('u')
|
811 |
+
arg = f.subs(x, u).diff(sym).subs(u, x)
|
812 |
+
if arg:
|
813 |
+
rv += self.func(arg, (x, a, b))
|
814 |
+
return rv
|
815 |
+
|
816 |
+
def _eval_integral(self, f, x, meijerg=None, risch=None, manual=None,
|
817 |
+
heurisch=None, conds='piecewise',final=None):
|
818 |
+
"""
|
819 |
+
Calculate the anti-derivative to the function f(x).
|
820 |
+
|
821 |
+
Explanation
|
822 |
+
===========
|
823 |
+
|
824 |
+
The following algorithms are applied (roughly in this order):
|
825 |
+
|
826 |
+
1. Simple heuristics (based on pattern matching and integral table):
|
827 |
+
|
828 |
+
- most frequently used functions (e.g. polynomials, products of
|
829 |
+
trig functions)
|
830 |
+
|
831 |
+
2. Integration of rational functions:
|
832 |
+
|
833 |
+
- A complete algorithm for integrating rational functions is
|
834 |
+
implemented (the Lazard-Rioboo-Trager algorithm). The algorithm
|
835 |
+
also uses the partial fraction decomposition algorithm
|
836 |
+
implemented in apart() as a preprocessor to make this process
|
837 |
+
faster. Note that the integral of a rational function is always
|
838 |
+
elementary, but in general, it may include a RootSum.
|
839 |
+
|
840 |
+
3. Full Risch algorithm:
|
841 |
+
|
842 |
+
- The Risch algorithm is a complete decision
|
843 |
+
procedure for integrating elementary functions, which means that
|
844 |
+
given any elementary function, it will either compute an
|
845 |
+
elementary antiderivative, or else prove that none exists.
|
846 |
+
Currently, part of transcendental case is implemented, meaning
|
847 |
+
elementary integrals containing exponentials, logarithms, and
|
848 |
+
(soon!) trigonometric functions can be computed. The algebraic
|
849 |
+
case, e.g., functions containing roots, is much more difficult
|
850 |
+
and is not implemented yet.
|
851 |
+
|
852 |
+
- If the routine fails (because the integrand is not elementary, or
|
853 |
+
because a case is not implemented yet), it continues on to the
|
854 |
+
next algorithms below. If the routine proves that the integrals
|
855 |
+
is nonelementary, it still moves on to the algorithms below,
|
856 |
+
because we might be able to find a closed-form solution in terms
|
857 |
+
of special functions. If risch=True, however, it will stop here.
|
858 |
+
|
859 |
+
4. The Meijer G-Function algorithm:
|
860 |
+
|
861 |
+
- This algorithm works by first rewriting the integrand in terms of
|
862 |
+
very general Meijer G-Function (meijerg in SymPy), integrating
|
863 |
+
it, and then rewriting the result back, if possible. This
|
864 |
+
algorithm is particularly powerful for definite integrals (which
|
865 |
+
is actually part of a different method of Integral), since it can
|
866 |
+
compute closed-form solutions of definite integrals even when no
|
867 |
+
closed-form indefinite integral exists. But it also is capable
|
868 |
+
of computing many indefinite integrals as well.
|
869 |
+
|
870 |
+
- Another advantage of this method is that it can use some results
|
871 |
+
about the Meijer G-Function to give a result in terms of a
|
872 |
+
Piecewise expression, which allows to express conditionally
|
873 |
+
convergent integrals.
|
874 |
+
|
875 |
+
- Setting meijerg=True will cause integrate() to use only this
|
876 |
+
method.
|
877 |
+
|
878 |
+
5. The "manual integration" algorithm:
|
879 |
+
|
880 |
+
- This algorithm tries to mimic how a person would find an
|
881 |
+
antiderivative by hand, for example by looking for a
|
882 |
+
substitution or applying integration by parts. This algorithm
|
883 |
+
does not handle as many integrands but can return results in a
|
884 |
+
more familiar form.
|
885 |
+
|
886 |
+
- Sometimes this algorithm can evaluate parts of an integral; in
|
887 |
+
this case integrate() will try to evaluate the rest of the
|
888 |
+
integrand using the other methods here.
|
889 |
+
|
890 |
+
- Setting manual=True will cause integrate() to use only this
|
891 |
+
method.
|
892 |
+
|
893 |
+
6. The Heuristic Risch algorithm:
|
894 |
+
|
895 |
+
- This is a heuristic version of the Risch algorithm, meaning that
|
896 |
+
it is not deterministic. This is tried as a last resort because
|
897 |
+
it can be very slow. It is still used because not enough of the
|
898 |
+
full Risch algorithm is implemented, so that there are still some
|
899 |
+
integrals that can only be computed using this method. The goal
|
900 |
+
is to implement enough of the Risch and Meijer G-function methods
|
901 |
+
so that this can be deleted.
|
902 |
+
|
903 |
+
Setting heurisch=True will cause integrate() to use only this
|
904 |
+
method. Set heurisch=False to not use it.
|
905 |
+
|
906 |
+
"""
|
907 |
+
|
908 |
+
from sympy.integrals.risch import risch_integrate, NonElementaryIntegral
|
909 |
+
from sympy.integrals.manualintegrate import manualintegrate
|
910 |
+
|
911 |
+
if risch:
|
912 |
+
try:
|
913 |
+
return risch_integrate(f, x, conds=conds)
|
914 |
+
except NotImplementedError:
|
915 |
+
return None
|
916 |
+
|
917 |
+
if manual:
|
918 |
+
try:
|
919 |
+
result = manualintegrate(f, x)
|
920 |
+
if result is not None and result.func != Integral:
|
921 |
+
return result
|
922 |
+
except (ValueError, PolynomialError):
|
923 |
+
pass
|
924 |
+
|
925 |
+
eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual,
|
926 |
+
"heurisch": heurisch, "conds": conds}
|
927 |
+
|
928 |
+
# if it is a poly(x) then let the polynomial integrate itself (fast)
|
929 |
+
#
|
930 |
+
# It is important to make this check first, otherwise the other code
|
931 |
+
# will return a SymPy expression instead of a Polynomial.
|
932 |
+
#
|
933 |
+
# see Polynomial for details.
|
934 |
+
if isinstance(f, Poly) and not (manual or meijerg or risch):
|
935 |
+
# Note: this is deprecated, but the deprecation warning is already
|
936 |
+
# issued in the Integral constructor.
|
937 |
+
return f.integrate(x)
|
938 |
+
|
939 |
+
# Piecewise antiderivatives need to call special integrate.
|
940 |
+
if isinstance(f, Piecewise):
|
941 |
+
return f.piecewise_integrate(x, **eval_kwargs)
|
942 |
+
|
943 |
+
# let's cut it short if `f` does not depend on `x`; if
|
944 |
+
# x is only a dummy, that will be handled below
|
945 |
+
if not f.has(x):
|
946 |
+
return f*x
|
947 |
+
|
948 |
+
# try to convert to poly(x) and then integrate if successful (fast)
|
949 |
+
poly = f.as_poly(x)
|
950 |
+
if poly is not None and not (manual or meijerg or risch):
|
951 |
+
return poly.integrate().as_expr()
|
952 |
+
|
953 |
+
if risch is not False:
|
954 |
+
try:
|
955 |
+
result, i = risch_integrate(f, x, separate_integral=True,
|
956 |
+
conds=conds)
|
957 |
+
except NotImplementedError:
|
958 |
+
pass
|
959 |
+
else:
|
960 |
+
if i:
|
961 |
+
# There was a nonelementary integral. Try integrating it.
|
962 |
+
|
963 |
+
# if no part of the NonElementaryIntegral is integrated by
|
964 |
+
# the Risch algorithm, then use the original function to
|
965 |
+
# integrate, instead of re-written one
|
966 |
+
if result == 0:
|
967 |
+
return NonElementaryIntegral(f, x).doit(risch=False)
|
968 |
+
else:
|
969 |
+
return result + i.doit(risch=False)
|
970 |
+
else:
|
971 |
+
return result
|
972 |
+
|
973 |
+
# since Integral(f=g1+g2+...) == Integral(g1) + Integral(g2) + ...
|
974 |
+
# we are going to handle Add terms separately,
|
975 |
+
# if `f` is not Add -- we only have one term
|
976 |
+
|
977 |
+
# Note that in general, this is a bad idea, because Integral(g1) +
|
978 |
+
# Integral(g2) might not be computable, even if Integral(g1 + g2) is.
|
979 |
+
# For example, Integral(x**x + x**x*log(x)). But many heuristics only
|
980 |
+
# work term-wise. So we compute this step last, after trying
|
981 |
+
# risch_integrate. We also try risch_integrate again in this loop,
|
982 |
+
# because maybe the integral is a sum of an elementary part and a
|
983 |
+
# nonelementary part (like erf(x) + exp(x)). risch_integrate() is
|
984 |
+
# quite fast, so this is acceptable.
|
985 |
+
from sympy.simplify.fu import sincos_to_sum
|
986 |
+
parts = []
|
987 |
+
args = Add.make_args(f)
|
988 |
+
for g in args:
|
989 |
+
coeff, g = g.as_independent(x)
|
990 |
+
|
991 |
+
# g(x) = const
|
992 |
+
if g is S.One and not meijerg:
|
993 |
+
parts.append(coeff*x)
|
994 |
+
continue
|
995 |
+
|
996 |
+
# g(x) = expr + O(x**n)
|
997 |
+
order_term = g.getO()
|
998 |
+
|
999 |
+
if order_term is not None:
|
1000 |
+
h = self._eval_integral(g.removeO(), x, **eval_kwargs)
|
1001 |
+
|
1002 |
+
if h is not None:
|
1003 |
+
h_order_expr = self._eval_integral(order_term.expr, x, **eval_kwargs)
|
1004 |
+
|
1005 |
+
if h_order_expr is not None:
|
1006 |
+
h_order_term = order_term.func(
|
1007 |
+
h_order_expr, *order_term.variables)
|
1008 |
+
parts.append(coeff*(h + h_order_term))
|
1009 |
+
continue
|
1010 |
+
|
1011 |
+
# NOTE: if there is O(x**n) and we fail to integrate then
|
1012 |
+
# there is no point in trying other methods because they
|
1013 |
+
# will fail, too.
|
1014 |
+
return None
|
1015 |
+
|
1016 |
+
# c
|
1017 |
+
# g(x) = (a*x+b)
|
1018 |
+
if g.is_Pow and not g.exp.has(x) and not meijerg:
|
1019 |
+
a = Wild('a', exclude=[x])
|
1020 |
+
b = Wild('b', exclude=[x])
|
1021 |
+
|
1022 |
+
M = g.base.match(a*x + b)
|
1023 |
+
|
1024 |
+
if M is not None:
|
1025 |
+
if g.exp == -1:
|
1026 |
+
h = log(g.base)
|
1027 |
+
elif conds != 'piecewise':
|
1028 |
+
h = g.base**(g.exp + 1) / (g.exp + 1)
|
1029 |
+
else:
|
1030 |
+
h1 = log(g.base)
|
1031 |
+
h2 = g.base**(g.exp + 1) / (g.exp + 1)
|
1032 |
+
h = Piecewise((h2, Ne(g.exp, -1)), (h1, True))
|
1033 |
+
|
1034 |
+
parts.append(coeff * h / M[a])
|
1035 |
+
continue
|
1036 |
+
|
1037 |
+
# poly(x)
|
1038 |
+
# g(x) = -------
|
1039 |
+
# poly(x)
|
1040 |
+
if g.is_rational_function(x) and not (manual or meijerg or risch):
|
1041 |
+
parts.append(coeff * ratint(g, x))
|
1042 |
+
continue
|
1043 |
+
|
1044 |
+
if not (manual or meijerg or risch):
|
1045 |
+
# g(x) = Mul(trig)
|
1046 |
+
h = trigintegrate(g, x, conds=conds)
|
1047 |
+
if h is not None:
|
1048 |
+
parts.append(coeff * h)
|
1049 |
+
continue
|
1050 |
+
|
1051 |
+
# g(x) has at least a DiracDelta term
|
1052 |
+
h = deltaintegrate(g, x)
|
1053 |
+
if h is not None:
|
1054 |
+
parts.append(coeff * h)
|
1055 |
+
continue
|
1056 |
+
|
1057 |
+
from .singularityfunctions import singularityintegrate
|
1058 |
+
# g(x) has at least a Singularity Function term
|
1059 |
+
h = singularityintegrate(g, x)
|
1060 |
+
if h is not None:
|
1061 |
+
parts.append(coeff * h)
|
1062 |
+
continue
|
1063 |
+
|
1064 |
+
# Try risch again.
|
1065 |
+
if risch is not False:
|
1066 |
+
try:
|
1067 |
+
h, i = risch_integrate(g, x,
|
1068 |
+
separate_integral=True, conds=conds)
|
1069 |
+
except NotImplementedError:
|
1070 |
+
h = None
|
1071 |
+
else:
|
1072 |
+
if i:
|
1073 |
+
h = h + i.doit(risch=False)
|
1074 |
+
|
1075 |
+
parts.append(coeff*h)
|
1076 |
+
continue
|
1077 |
+
|
1078 |
+
# fall back to heurisch
|
1079 |
+
if heurisch is not False:
|
1080 |
+
from sympy.integrals.heurisch import (heurisch as heurisch_,
|
1081 |
+
heurisch_wrapper)
|
1082 |
+
try:
|
1083 |
+
if conds == 'piecewise':
|
1084 |
+
h = heurisch_wrapper(g, x, hints=[])
|
1085 |
+
else:
|
1086 |
+
h = heurisch_(g, x, hints=[])
|
1087 |
+
except PolynomialError:
|
1088 |
+
# XXX: this exception means there is a bug in the
|
1089 |
+
# implementation of heuristic Risch integration
|
1090 |
+
# algorithm.
|
1091 |
+
h = None
|
1092 |
+
else:
|
1093 |
+
h = None
|
1094 |
+
|
1095 |
+
if meijerg is not False and h is None:
|
1096 |
+
# rewrite using G functions
|
1097 |
+
try:
|
1098 |
+
h = meijerint_indefinite(g, x)
|
1099 |
+
except NotImplementedError:
|
1100 |
+
_debug('NotImplementedError from meijerint_definite')
|
1101 |
+
if h is not None:
|
1102 |
+
parts.append(coeff * h)
|
1103 |
+
continue
|
1104 |
+
|
1105 |
+
if h is None and manual is not False:
|
1106 |
+
try:
|
1107 |
+
result = manualintegrate(g, x)
|
1108 |
+
if result is not None and not isinstance(result, Integral):
|
1109 |
+
if result.has(Integral) and not manual:
|
1110 |
+
# Try to have other algorithms do the integrals
|
1111 |
+
# manualintegrate can't handle,
|
1112 |
+
# unless we were asked to use manual only.
|
1113 |
+
# Keep the rest of eval_kwargs in case another
|
1114 |
+
# method was set to False already
|
1115 |
+
new_eval_kwargs = eval_kwargs
|
1116 |
+
new_eval_kwargs["manual"] = False
|
1117 |
+
new_eval_kwargs["final"] = False
|
1118 |
+
result = result.func(*[
|
1119 |
+
arg.doit(**new_eval_kwargs) if
|
1120 |
+
arg.has(Integral) else arg
|
1121 |
+
for arg in result.args
|
1122 |
+
]).expand(multinomial=False,
|
1123 |
+
log=False,
|
1124 |
+
power_exp=False,
|
1125 |
+
power_base=False)
|
1126 |
+
if not result.has(Integral):
|
1127 |
+
parts.append(coeff * result)
|
1128 |
+
continue
|
1129 |
+
except (ValueError, PolynomialError):
|
1130 |
+
# can't handle some SymPy expressions
|
1131 |
+
pass
|
1132 |
+
|
1133 |
+
# if we failed maybe it was because we had
|
1134 |
+
# a product that could have been expanded,
|
1135 |
+
# so let's try an expansion of the whole
|
1136 |
+
# thing before giving up; we don't try this
|
1137 |
+
# at the outset because there are things
|
1138 |
+
# that cannot be solved unless they are
|
1139 |
+
# NOT expanded e.g., x**x*(1+log(x)). There
|
1140 |
+
# should probably be a checker somewhere in this
|
1141 |
+
# routine to look for such cases and try to do
|
1142 |
+
# collection on the expressions if they are already
|
1143 |
+
# in an expanded form
|
1144 |
+
if not h and len(args) == 1:
|
1145 |
+
f = sincos_to_sum(f).expand(mul=True, deep=False)
|
1146 |
+
if f.is_Add:
|
1147 |
+
# Note: risch will be identical on the expanded
|
1148 |
+
# expression, but maybe it will be able to pick out parts,
|
1149 |
+
# like x*(exp(x) + erf(x)).
|
1150 |
+
return self._eval_integral(f, x, **eval_kwargs)
|
1151 |
+
|
1152 |
+
if h is not None:
|
1153 |
+
parts.append(coeff * h)
|
1154 |
+
else:
|
1155 |
+
return None
|
1156 |
+
|
1157 |
+
return Add(*parts)
|
1158 |
+
|
1159 |
+
def _eval_lseries(self, x, logx=None, cdir=0):
|
1160 |
+
expr = self.as_dummy()
|
1161 |
+
symb = x
|
1162 |
+
for l in expr.limits:
|
1163 |
+
if x in l[1:]:
|
1164 |
+
symb = l[0]
|
1165 |
+
break
|
1166 |
+
for term in expr.function.lseries(symb, logx):
|
1167 |
+
yield integrate(term, *expr.limits)
|
1168 |
+
|
1169 |
+
def _eval_nseries(self, x, n, logx=None, cdir=0):
|
1170 |
+
expr = self.as_dummy()
|
1171 |
+
symb = x
|
1172 |
+
for l in expr.limits:
|
1173 |
+
if x in l[1:]:
|
1174 |
+
symb = l[0]
|
1175 |
+
break
|
1176 |
+
terms, order = expr.function.nseries(
|
1177 |
+
x=symb, n=n, logx=logx).as_coeff_add(Order)
|
1178 |
+
order = [o.subs(symb, x) for o in order]
|
1179 |
+
return integrate(terms, *expr.limits) + Add(*order)*x
|
1180 |
+
|
1181 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1182 |
+
series_gen = self.args[0].lseries(x)
|
1183 |
+
for leading_term in series_gen:
|
1184 |
+
if leading_term != 0:
|
1185 |
+
break
|
1186 |
+
return integrate(leading_term, *self.args[1:])
|
1187 |
+
|
1188 |
+
def _eval_simplify(self, **kwargs):
|
1189 |
+
expr = factor_terms(self)
|
1190 |
+
if isinstance(expr, Integral):
|
1191 |
+
from sympy.simplify.simplify import simplify
|
1192 |
+
return expr.func(*[simplify(i, **kwargs) for i in expr.args])
|
1193 |
+
return expr.simplify(**kwargs)
|
1194 |
+
|
1195 |
+
def as_sum(self, n=None, method="midpoint", evaluate=True):
|
1196 |
+
"""
|
1197 |
+
Approximates a definite integral by a sum.
|
1198 |
+
|
1199 |
+
Parameters
|
1200 |
+
==========
|
1201 |
+
|
1202 |
+
n :
|
1203 |
+
The number of subintervals to use, optional.
|
1204 |
+
method :
|
1205 |
+
One of: 'left', 'right', 'midpoint', 'trapezoid'.
|
1206 |
+
evaluate : bool
|
1207 |
+
If False, returns an unevaluated Sum expression. The default
|
1208 |
+
is True, evaluate the sum.
|
1209 |
+
|
1210 |
+
Notes
|
1211 |
+
=====
|
1212 |
+
|
1213 |
+
These methods of approximate integration are described in [1].
|
1214 |
+
|
1215 |
+
Examples
|
1216 |
+
========
|
1217 |
+
|
1218 |
+
>>> from sympy import Integral, sin, sqrt
|
1219 |
+
>>> from sympy.abc import x, n
|
1220 |
+
>>> e = Integral(sin(x), (x, 3, 7))
|
1221 |
+
>>> e
|
1222 |
+
Integral(sin(x), (x, 3, 7))
|
1223 |
+
|
1224 |
+
For demonstration purposes, this interval will only be split into 2
|
1225 |
+
regions, bounded by [3, 5] and [5, 7].
|
1226 |
+
|
1227 |
+
The left-hand rule uses function evaluations at the left of each
|
1228 |
+
interval:
|
1229 |
+
|
1230 |
+
>>> e.as_sum(2, 'left')
|
1231 |
+
2*sin(5) + 2*sin(3)
|
1232 |
+
|
1233 |
+
The midpoint rule uses evaluations at the center of each interval:
|
1234 |
+
|
1235 |
+
>>> e.as_sum(2, 'midpoint')
|
1236 |
+
2*sin(4) + 2*sin(6)
|
1237 |
+
|
1238 |
+
The right-hand rule uses function evaluations at the right of each
|
1239 |
+
interval:
|
1240 |
+
|
1241 |
+
>>> e.as_sum(2, 'right')
|
1242 |
+
2*sin(5) + 2*sin(7)
|
1243 |
+
|
1244 |
+
The trapezoid rule uses function evaluations on both sides of the
|
1245 |
+
intervals. This is equivalent to taking the average of the left and
|
1246 |
+
right hand rule results:
|
1247 |
+
|
1248 |
+
>>> e.as_sum(2, 'trapezoid')
|
1249 |
+
2*sin(5) + sin(3) + sin(7)
|
1250 |
+
>>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == _
|
1251 |
+
True
|
1252 |
+
|
1253 |
+
Here, the discontinuity at x = 0 can be avoided by using the
|
1254 |
+
midpoint or right-hand method:
|
1255 |
+
|
1256 |
+
>>> e = Integral(1/sqrt(x), (x, 0, 1))
|
1257 |
+
>>> e.as_sum(5).n(4)
|
1258 |
+
1.730
|
1259 |
+
>>> e.as_sum(10).n(4)
|
1260 |
+
1.809
|
1261 |
+
>>> e.doit().n(4) # the actual value is 2
|
1262 |
+
2.000
|
1263 |
+
|
1264 |
+
The left- or trapezoid method will encounter the discontinuity and
|
1265 |
+
return infinity:
|
1266 |
+
|
1267 |
+
>>> e.as_sum(5, 'left')
|
1268 |
+
zoo
|
1269 |
+
|
1270 |
+
The number of intervals can be symbolic. If omitted, a dummy symbol
|
1271 |
+
will be used for it.
|
1272 |
+
|
1273 |
+
>>> e = Integral(x**2, (x, 0, 2))
|
1274 |
+
>>> e.as_sum(n, 'right').expand()
|
1275 |
+
8/3 + 4/n + 4/(3*n**2)
|
1276 |
+
|
1277 |
+
This shows that the midpoint rule is more accurate, as its error
|
1278 |
+
term decays as the square of n:
|
1279 |
+
|
1280 |
+
>>> e.as_sum(method='midpoint').expand()
|
1281 |
+
8/3 - 2/(3*_n**2)
|
1282 |
+
|
1283 |
+
A symbolic sum is returned with evaluate=False:
|
1284 |
+
|
1285 |
+
>>> e.as_sum(n, 'midpoint', evaluate=False)
|
1286 |
+
2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n
|
1287 |
+
|
1288 |
+
See Also
|
1289 |
+
========
|
1290 |
+
|
1291 |
+
Integral.doit : Perform the integration using any hints
|
1292 |
+
|
1293 |
+
References
|
1294 |
+
==========
|
1295 |
+
|
1296 |
+
.. [1] https://en.wikipedia.org/wiki/Riemann_sum#Riemann_summation_methods
|
1297 |
+
"""
|
1298 |
+
|
1299 |
+
from sympy.concrete.summations import Sum
|
1300 |
+
limits = self.limits
|
1301 |
+
if len(limits) > 1:
|
1302 |
+
raise NotImplementedError(
|
1303 |
+
"Multidimensional midpoint rule not implemented yet")
|
1304 |
+
else:
|
1305 |
+
limit = limits[0]
|
1306 |
+
if (len(limit) != 3 or limit[1].is_finite is False or
|
1307 |
+
limit[2].is_finite is False):
|
1308 |
+
raise ValueError("Expecting a definite integral over "
|
1309 |
+
"a finite interval.")
|
1310 |
+
if n is None:
|
1311 |
+
n = Dummy('n', integer=True, positive=True)
|
1312 |
+
else:
|
1313 |
+
n = sympify(n)
|
1314 |
+
if (n.is_positive is False or n.is_integer is False or
|
1315 |
+
n.is_finite is False):
|
1316 |
+
raise ValueError("n must be a positive integer, got %s" % n)
|
1317 |
+
x, a, b = limit
|
1318 |
+
dx = (b - a)/n
|
1319 |
+
k = Dummy('k', integer=True, positive=True)
|
1320 |
+
f = self.function
|
1321 |
+
|
1322 |
+
if method == "left":
|
1323 |
+
result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n))
|
1324 |
+
elif method == "right":
|
1325 |
+
result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n))
|
1326 |
+
elif method == "midpoint":
|
1327 |
+
result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n))
|
1328 |
+
elif method == "trapezoid":
|
1329 |
+
result = dx*((f.subs(x, a) + f.subs(x, b))/2 +
|
1330 |
+
Sum(f.subs(x, a + k*dx), (k, 1, n - 1)))
|
1331 |
+
else:
|
1332 |
+
raise ValueError("Unknown method %s" % method)
|
1333 |
+
return result.doit() if evaluate else result
|
1334 |
+
|
1335 |
+
def principal_value(self, **kwargs):
|
1336 |
+
"""
|
1337 |
+
Compute the Cauchy Principal Value of the definite integral of a real function in the given interval
|
1338 |
+
on the real axis.
|
1339 |
+
|
1340 |
+
Explanation
|
1341 |
+
===========
|
1342 |
+
|
1343 |
+
In mathematics, the Cauchy principal value, is a method for assigning values to certain improper
|
1344 |
+
integrals which would otherwise be undefined.
|
1345 |
+
|
1346 |
+
Examples
|
1347 |
+
========
|
1348 |
+
|
1349 |
+
>>> from sympy import Integral, oo
|
1350 |
+
>>> from sympy.abc import x
|
1351 |
+
>>> Integral(x+1, (x, -oo, oo)).principal_value()
|
1352 |
+
oo
|
1353 |
+
>>> f = 1 / (x**3)
|
1354 |
+
>>> Integral(f, (x, -oo, oo)).principal_value()
|
1355 |
+
0
|
1356 |
+
>>> Integral(f, (x, -10, 10)).principal_value()
|
1357 |
+
0
|
1358 |
+
>>> Integral(f, (x, -10, oo)).principal_value() + Integral(f, (x, -oo, 10)).principal_value()
|
1359 |
+
0
|
1360 |
+
|
1361 |
+
References
|
1362 |
+
==========
|
1363 |
+
|
1364 |
+
.. [1] https://en.wikipedia.org/wiki/Cauchy_principal_value
|
1365 |
+
.. [2] https://mathworld.wolfram.com/CauchyPrincipalValue.html
|
1366 |
+
"""
|
1367 |
+
if len(self.limits) != 1 or len(list(self.limits[0])) != 3:
|
1368 |
+
raise ValueError("You need to insert a variable, lower_limit, and upper_limit correctly to calculate "
|
1369 |
+
"cauchy's principal value")
|
1370 |
+
x, a, b = self.limits[0]
|
1371 |
+
if not (a.is_comparable and b.is_comparable and a <= b):
|
1372 |
+
raise ValueError("The lower_limit must be smaller than or equal to the upper_limit to calculate "
|
1373 |
+
"cauchy's principal value. Also, a and b need to be comparable.")
|
1374 |
+
if a == b:
|
1375 |
+
return S.Zero
|
1376 |
+
|
1377 |
+
from sympy.calculus.singularities import singularities
|
1378 |
+
|
1379 |
+
r = Dummy('r')
|
1380 |
+
f = self.function
|
1381 |
+
singularities_list = [s for s in singularities(f, x) if s.is_comparable and a <= s <= b]
|
1382 |
+
for i in singularities_list:
|
1383 |
+
if i in (a, b):
|
1384 |
+
raise ValueError(
|
1385 |
+
'The principal value is not defined in the given interval due to singularity at %d.' % (i))
|
1386 |
+
F = integrate(f, x, **kwargs)
|
1387 |
+
if F.has(Integral):
|
1388 |
+
return self
|
1389 |
+
if a is -oo and b is oo:
|
1390 |
+
I = limit(F - F.subs(x, -x), x, oo)
|
1391 |
+
else:
|
1392 |
+
I = limit(F, x, b, '-') - limit(F, x, a, '+')
|
1393 |
+
for s in singularities_list:
|
1394 |
+
I += limit(((F.subs(x, s - r)) - F.subs(x, s + r)), r, 0, '+')
|
1395 |
+
return I
|
1396 |
+
|
1397 |
+
|
1398 |
+
|
1399 |
+
def integrate(*args, meijerg=None, conds='piecewise', risch=None, heurisch=None, manual=None, **kwargs):
|
1400 |
+
"""integrate(f, var, ...)
|
1401 |
+
|
1402 |
+
.. deprecated:: 1.6
|
1403 |
+
|
1404 |
+
Using ``integrate()`` with :class:`~.Poly` is deprecated. Use
|
1405 |
+
:meth:`.Poly.integrate` instead. See :ref:`deprecated-integrate-poly`.
|
1406 |
+
|
1407 |
+
Explanation
|
1408 |
+
===========
|
1409 |
+
|
1410 |
+
Compute definite or indefinite integral of one or more variables
|
1411 |
+
using Risch-Norman algorithm and table lookup. This procedure is
|
1412 |
+
able to handle elementary algebraic and transcendental functions
|
1413 |
+
and also a huge class of special functions, including Airy,
|
1414 |
+
Bessel, Whittaker and Lambert.
|
1415 |
+
|
1416 |
+
var can be:
|
1417 |
+
|
1418 |
+
- a symbol -- indefinite integration
|
1419 |
+
- a tuple (symbol, a) -- indefinite integration with result
|
1420 |
+
given with ``a`` replacing ``symbol``
|
1421 |
+
- a tuple (symbol, a, b) -- definite integration
|
1422 |
+
|
1423 |
+
Several variables can be specified, in which case the result is
|
1424 |
+
multiple integration. (If var is omitted and the integrand is
|
1425 |
+
univariate, the indefinite integral in that variable will be performed.)
|
1426 |
+
|
1427 |
+
Indefinite integrals are returned without terms that are independent
|
1428 |
+
of the integration variables. (see examples)
|
1429 |
+
|
1430 |
+
Definite improper integrals often entail delicate convergence
|
1431 |
+
conditions. Pass conds='piecewise', 'separate' or 'none' to have
|
1432 |
+
these returned, respectively, as a Piecewise function, as a separate
|
1433 |
+
result (i.e. result will be a tuple), or not at all (default is
|
1434 |
+
'piecewise').
|
1435 |
+
|
1436 |
+
**Strategy**
|
1437 |
+
|
1438 |
+
SymPy uses various approaches to definite integration. One method is to
|
1439 |
+
find an antiderivative for the integrand, and then use the fundamental
|
1440 |
+
theorem of calculus. Various functions are implemented to integrate
|
1441 |
+
polynomial, rational and trigonometric functions, and integrands
|
1442 |
+
containing DiracDelta terms.
|
1443 |
+
|
1444 |
+
SymPy also implements the part of the Risch algorithm, which is a decision
|
1445 |
+
procedure for integrating elementary functions, i.e., the algorithm can
|
1446 |
+
either find an elementary antiderivative, or prove that one does not
|
1447 |
+
exist. There is also a (very successful, albeit somewhat slow) general
|
1448 |
+
implementation of the heuristic Risch algorithm. This algorithm will
|
1449 |
+
eventually be phased out as more of the full Risch algorithm is
|
1450 |
+
implemented. See the docstring of Integral._eval_integral() for more
|
1451 |
+
details on computing the antiderivative using algebraic methods.
|
1452 |
+
|
1453 |
+
The option risch=True can be used to use only the (full) Risch algorithm.
|
1454 |
+
This is useful if you want to know if an elementary function has an
|
1455 |
+
elementary antiderivative. If the indefinite Integral returned by this
|
1456 |
+
function is an instance of NonElementaryIntegral, that means that the
|
1457 |
+
Risch algorithm has proven that integral to be non-elementary. Note that
|
1458 |
+
by default, additional methods (such as the Meijer G method outlined
|
1459 |
+
below) are tried on these integrals, as they may be expressible in terms
|
1460 |
+
of special functions, so if you only care about elementary answers, use
|
1461 |
+
risch=True. Also note that an unevaluated Integral returned by this
|
1462 |
+
function is not necessarily a NonElementaryIntegral, even with risch=True,
|
1463 |
+
as it may just be an indication that the particular part of the Risch
|
1464 |
+
algorithm needed to integrate that function is not yet implemented.
|
1465 |
+
|
1466 |
+
Another family of strategies comes from re-writing the integrand in
|
1467 |
+
terms of so-called Meijer G-functions. Indefinite integrals of a
|
1468 |
+
single G-function can always be computed, and the definite integral
|
1469 |
+
of a product of two G-functions can be computed from zero to
|
1470 |
+
infinity. Various strategies are implemented to rewrite integrands
|
1471 |
+
as G-functions, and use this information to compute integrals (see
|
1472 |
+
the ``meijerint`` module).
|
1473 |
+
|
1474 |
+
The option manual=True can be used to use only an algorithm that tries
|
1475 |
+
to mimic integration by hand. This algorithm does not handle as many
|
1476 |
+
integrands as the other algorithms implemented but may return results in
|
1477 |
+
a more familiar form. The ``manualintegrate`` module has functions that
|
1478 |
+
return the steps used (see the module docstring for more information).
|
1479 |
+
|
1480 |
+
In general, the algebraic methods work best for computing
|
1481 |
+
antiderivatives of (possibly complicated) combinations of elementary
|
1482 |
+
functions. The G-function methods work best for computing definite
|
1483 |
+
integrals from zero to infinity of moderately complicated
|
1484 |
+
combinations of special functions, or indefinite integrals of very
|
1485 |
+
simple combinations of special functions.
|
1486 |
+
|
1487 |
+
The strategy employed by the integration code is as follows:
|
1488 |
+
|
1489 |
+
- If computing a definite integral, and both limits are real,
|
1490 |
+
and at least one limit is +- oo, try the G-function method of
|
1491 |
+
definite integration first.
|
1492 |
+
|
1493 |
+
- Try to find an antiderivative, using all available methods, ordered
|
1494 |
+
by performance (that is try fastest method first, slowest last; in
|
1495 |
+
particular polynomial integration is tried first, Meijer
|
1496 |
+
G-functions second to last, and heuristic Risch last).
|
1497 |
+
|
1498 |
+
- If still not successful, try G-functions irrespective of the
|
1499 |
+
limits.
|
1500 |
+
|
1501 |
+
The option meijerg=True, False, None can be used to, respectively:
|
1502 |
+
always use G-function methods and no others, never use G-function
|
1503 |
+
methods, or use all available methods (in order as described above).
|
1504 |
+
It defaults to None.
|
1505 |
+
|
1506 |
+
Examples
|
1507 |
+
========
|
1508 |
+
|
1509 |
+
>>> from sympy import integrate, log, exp, oo
|
1510 |
+
>>> from sympy.abc import a, x, y
|
1511 |
+
|
1512 |
+
>>> integrate(x*y, x)
|
1513 |
+
x**2*y/2
|
1514 |
+
|
1515 |
+
>>> integrate(log(x), x)
|
1516 |
+
x*log(x) - x
|
1517 |
+
|
1518 |
+
>>> integrate(log(x), (x, 1, a))
|
1519 |
+
a*log(a) - a + 1
|
1520 |
+
|
1521 |
+
>>> integrate(x)
|
1522 |
+
x**2/2
|
1523 |
+
|
1524 |
+
Terms that are independent of x are dropped by indefinite integration:
|
1525 |
+
|
1526 |
+
>>> from sympy import sqrt
|
1527 |
+
>>> integrate(sqrt(1 + x), (x, 0, x))
|
1528 |
+
2*(x + 1)**(3/2)/3 - 2/3
|
1529 |
+
>>> integrate(sqrt(1 + x), x)
|
1530 |
+
2*(x + 1)**(3/2)/3
|
1531 |
+
|
1532 |
+
>>> integrate(x*y)
|
1533 |
+
Traceback (most recent call last):
|
1534 |
+
...
|
1535 |
+
ValueError: specify integration variables to integrate x*y
|
1536 |
+
|
1537 |
+
Note that ``integrate(x)`` syntax is meant only for convenience
|
1538 |
+
in interactive sessions and should be avoided in library code.
|
1539 |
+
|
1540 |
+
>>> integrate(x**a*exp(-x), (x, 0, oo)) # same as conds='piecewise'
|
1541 |
+
Piecewise((gamma(a + 1), re(a) > -1),
|
1542 |
+
(Integral(x**a*exp(-x), (x, 0, oo)), True))
|
1543 |
+
|
1544 |
+
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='none')
|
1545 |
+
gamma(a + 1)
|
1546 |
+
|
1547 |
+
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='separate')
|
1548 |
+
(gamma(a + 1), re(a) > -1)
|
1549 |
+
|
1550 |
+
See Also
|
1551 |
+
========
|
1552 |
+
|
1553 |
+
Integral, Integral.doit
|
1554 |
+
|
1555 |
+
"""
|
1556 |
+
doit_flags = {
|
1557 |
+
'deep': False,
|
1558 |
+
'meijerg': meijerg,
|
1559 |
+
'conds': conds,
|
1560 |
+
'risch': risch,
|
1561 |
+
'heurisch': heurisch,
|
1562 |
+
'manual': manual
|
1563 |
+
}
|
1564 |
+
integral = Integral(*args, **kwargs)
|
1565 |
+
|
1566 |
+
if isinstance(integral, Integral):
|
1567 |
+
return integral.doit(**doit_flags)
|
1568 |
+
else:
|
1569 |
+
new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a
|
1570 |
+
for a in integral.args]
|
1571 |
+
return integral.func(*new_args)
|
1572 |
+
|
1573 |
+
|
1574 |
+
def line_integrate(field, curve, vars):
|
1575 |
+
"""line_integrate(field, Curve, variables)
|
1576 |
+
|
1577 |
+
Compute the line integral.
|
1578 |
+
|
1579 |
+
Examples
|
1580 |
+
========
|
1581 |
+
|
1582 |
+
>>> from sympy import Curve, line_integrate, E, ln
|
1583 |
+
>>> from sympy.abc import x, y, t
|
1584 |
+
>>> C = Curve([E**t + 1, E**t - 1], (t, 0, ln(2)))
|
1585 |
+
>>> line_integrate(x + y, C, [x, y])
|
1586 |
+
3*sqrt(2)
|
1587 |
+
|
1588 |
+
See Also
|
1589 |
+
========
|
1590 |
+
|
1591 |
+
sympy.integrals.integrals.integrate, Integral
|
1592 |
+
"""
|
1593 |
+
from sympy.geometry import Curve
|
1594 |
+
F = sympify(field)
|
1595 |
+
if not F:
|
1596 |
+
raise ValueError(
|
1597 |
+
"Expecting function specifying field as first argument.")
|
1598 |
+
if not isinstance(curve, Curve):
|
1599 |
+
raise ValueError("Expecting Curve entity as second argument.")
|
1600 |
+
if not is_sequence(vars):
|
1601 |
+
raise ValueError("Expecting ordered iterable for variables.")
|
1602 |
+
if len(curve.functions) != len(vars):
|
1603 |
+
raise ValueError("Field variable size does not match curve dimension.")
|
1604 |
+
|
1605 |
+
if curve.parameter in vars:
|
1606 |
+
raise ValueError("Curve parameter clashes with field parameters.")
|
1607 |
+
|
1608 |
+
# Calculate derivatives for line parameter functions
|
1609 |
+
# F(r) -> F(r(t)) and finally F(r(t)*r'(t))
|
1610 |
+
Ft = F
|
1611 |
+
dldt = 0
|
1612 |
+
for i, var in enumerate(vars):
|
1613 |
+
_f = curve.functions[i]
|
1614 |
+
_dn = diff(_f, curve.parameter)
|
1615 |
+
# ...arc length
|
1616 |
+
dldt = dldt + (_dn * _dn)
|
1617 |
+
Ft = Ft.subs(var, _f)
|
1618 |
+
Ft = Ft * sqrt(dldt)
|
1619 |
+
|
1620 |
+
integral = Integral(Ft, curve.limits).doit(deep=False)
|
1621 |
+
return integral
|
1622 |
+
|
1623 |
+
|
1624 |
+
### Property function dispatching ###
|
1625 |
+
|
1626 |
+
@shape.register(Integral)
|
1627 |
+
def _(expr):
|
1628 |
+
return shape(expr.function)
|
1629 |
+
|
1630 |
+
# Delayed imports
|
1631 |
+
from .deltafunctions import deltaintegrate
|
1632 |
+
from .meijerint import meijerint_definite, meijerint_indefinite, _debug
|
1633 |
+
from .trigonometry import trigintegrate
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/intpoly.py
ADDED
@@ -0,0 +1,1302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Module to implement integration of uni/bivariate polynomials over
|
3 |
+
2D Polytopes and uni/bi/trivariate polynomials over 3D Polytopes.
|
4 |
+
|
5 |
+
Uses evaluation techniques as described in Chin et al. (2015) [1].
|
6 |
+
|
7 |
+
|
8 |
+
References
|
9 |
+
===========
|
10 |
+
|
11 |
+
.. [1] Chin, Eric B., Jean B. Lasserre, and N. Sukumar. "Numerical integration
|
12 |
+
of homogeneous functions on convex and nonconvex polygons and polyhedra."
|
13 |
+
Computational Mechanics 56.6 (2015): 967-981
|
14 |
+
|
15 |
+
PDF link : http://dilbert.engr.ucdavis.edu/~suku/quadrature/cls-integration.pdf
|
16 |
+
"""
|
17 |
+
|
18 |
+
from functools import cmp_to_key
|
19 |
+
|
20 |
+
from sympy.abc import x, y, z
|
21 |
+
from sympy.core import S, diff, Expr, Symbol
|
22 |
+
from sympy.core.sympify import _sympify
|
23 |
+
from sympy.geometry import Segment2D, Polygon, Point, Point2D
|
24 |
+
from sympy.polys.polytools import LC, gcd_list, degree_list, Poly
|
25 |
+
from sympy.simplify.simplify import nsimplify
|
26 |
+
|
27 |
+
|
28 |
+
def polytope_integrate(poly, expr=None, *, clockwise=False, max_degree=None):
|
29 |
+
"""Integrates polynomials over 2/3-Polytopes.
|
30 |
+
|
31 |
+
Explanation
|
32 |
+
===========
|
33 |
+
|
34 |
+
This function accepts the polytope in ``poly`` and the function in ``expr``
|
35 |
+
(uni/bi/trivariate polynomials are implemented) and returns
|
36 |
+
the exact integral of ``expr`` over ``poly``.
|
37 |
+
|
38 |
+
Parameters
|
39 |
+
==========
|
40 |
+
|
41 |
+
poly : The input Polygon.
|
42 |
+
|
43 |
+
expr : The input polynomial.
|
44 |
+
|
45 |
+
clockwise : Binary value to sort input points of 2-Polytope clockwise.(Optional)
|
46 |
+
|
47 |
+
max_degree : The maximum degree of any monomial of the input polynomial.(Optional)
|
48 |
+
|
49 |
+
Examples
|
50 |
+
========
|
51 |
+
|
52 |
+
>>> from sympy.abc import x, y
|
53 |
+
>>> from sympy import Point, Polygon
|
54 |
+
>>> from sympy.integrals.intpoly import polytope_integrate
|
55 |
+
>>> polygon = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
|
56 |
+
>>> polys = [1, x, y, x*y, x**2*y, x*y**2]
|
57 |
+
>>> expr = x*y
|
58 |
+
>>> polytope_integrate(polygon, expr)
|
59 |
+
1/4
|
60 |
+
>>> polytope_integrate(polygon, polys, max_degree=3)
|
61 |
+
{1: 1, x: 1/2, y: 1/2, x*y: 1/4, x*y**2: 1/6, x**2*y: 1/6}
|
62 |
+
"""
|
63 |
+
if clockwise:
|
64 |
+
if isinstance(poly, Polygon):
|
65 |
+
poly = Polygon(*point_sort(poly.vertices), evaluate=False)
|
66 |
+
else:
|
67 |
+
raise TypeError("clockwise=True works for only 2-Polytope"
|
68 |
+
"V-representation input")
|
69 |
+
|
70 |
+
if isinstance(poly, Polygon):
|
71 |
+
# For Vertex Representation(2D case)
|
72 |
+
hp_params = hyperplane_parameters(poly)
|
73 |
+
facets = poly.sides
|
74 |
+
elif len(poly[0]) == 2:
|
75 |
+
# For Hyperplane Representation(2D case)
|
76 |
+
plen = len(poly)
|
77 |
+
if len(poly[0][0]) == 2:
|
78 |
+
intersections = [intersection(poly[(i - 1) % plen], poly[i],
|
79 |
+
"plane2D")
|
80 |
+
for i in range(0, plen)]
|
81 |
+
hp_params = poly
|
82 |
+
lints = len(intersections)
|
83 |
+
facets = [Segment2D(intersections[i],
|
84 |
+
intersections[(i + 1) % lints])
|
85 |
+
for i in range(lints)]
|
86 |
+
else:
|
87 |
+
raise NotImplementedError("Integration for H-representation 3D"
|
88 |
+
"case not implemented yet.")
|
89 |
+
else:
|
90 |
+
# For Vertex Representation(3D case)
|
91 |
+
vertices = poly[0]
|
92 |
+
facets = poly[1:]
|
93 |
+
hp_params = hyperplane_parameters(facets, vertices)
|
94 |
+
|
95 |
+
if max_degree is None:
|
96 |
+
if expr is None:
|
97 |
+
raise TypeError('Input expression must be a valid SymPy expression')
|
98 |
+
return main_integrate3d(expr, facets, vertices, hp_params)
|
99 |
+
|
100 |
+
if max_degree is not None:
|
101 |
+
result = {}
|
102 |
+
if expr is not None:
|
103 |
+
f_expr = []
|
104 |
+
for e in expr:
|
105 |
+
_ = decompose(e)
|
106 |
+
if len(_) == 1 and not _.popitem()[0]:
|
107 |
+
f_expr.append(e)
|
108 |
+
elif Poly(e).total_degree() <= max_degree:
|
109 |
+
f_expr.append(e)
|
110 |
+
expr = f_expr
|
111 |
+
|
112 |
+
if not isinstance(expr, list) and expr is not None:
|
113 |
+
raise TypeError('Input polynomials must be list of expressions')
|
114 |
+
|
115 |
+
if len(hp_params[0][0]) == 3:
|
116 |
+
result_dict = main_integrate3d(0, facets, vertices, hp_params,
|
117 |
+
max_degree)
|
118 |
+
else:
|
119 |
+
result_dict = main_integrate(0, facets, hp_params, max_degree)
|
120 |
+
|
121 |
+
if expr is None:
|
122 |
+
return result_dict
|
123 |
+
|
124 |
+
for poly in expr:
|
125 |
+
poly = _sympify(poly)
|
126 |
+
if poly not in result:
|
127 |
+
if poly.is_zero:
|
128 |
+
result[S.Zero] = S.Zero
|
129 |
+
continue
|
130 |
+
integral_value = S.Zero
|
131 |
+
monoms = decompose(poly, separate=True)
|
132 |
+
for monom in monoms:
|
133 |
+
monom = nsimplify(monom)
|
134 |
+
coeff, m = strip(monom)
|
135 |
+
integral_value += result_dict[m] * coeff
|
136 |
+
result[poly] = integral_value
|
137 |
+
return result
|
138 |
+
|
139 |
+
if expr is None:
|
140 |
+
raise TypeError('Input expression must be a valid SymPy expression')
|
141 |
+
|
142 |
+
return main_integrate(expr, facets, hp_params)
|
143 |
+
|
144 |
+
|
145 |
+
def strip(monom):
|
146 |
+
if monom.is_zero:
|
147 |
+
return S.Zero, S.Zero
|
148 |
+
elif monom.is_number:
|
149 |
+
return monom, S.One
|
150 |
+
else:
|
151 |
+
coeff = LC(monom)
|
152 |
+
return coeff, monom / coeff
|
153 |
+
|
154 |
+
def _polynomial_integrate(polynomials, facets, hp_params):
|
155 |
+
dims = (x, y)
|
156 |
+
dim_length = len(dims)
|
157 |
+
integral_value = S.Zero
|
158 |
+
for deg in polynomials:
|
159 |
+
poly_contribute = S.Zero
|
160 |
+
facet_count = 0
|
161 |
+
for hp in hp_params:
|
162 |
+
value_over_boundary = integration_reduction(facets,
|
163 |
+
facet_count,
|
164 |
+
hp[0], hp[1],
|
165 |
+
polynomials[deg],
|
166 |
+
dims, deg)
|
167 |
+
poly_contribute += value_over_boundary * (hp[1] / norm(hp[0]))
|
168 |
+
facet_count += 1
|
169 |
+
poly_contribute /= (dim_length + deg)
|
170 |
+
integral_value += poly_contribute
|
171 |
+
|
172 |
+
return integral_value
|
173 |
+
|
174 |
+
|
175 |
+
def main_integrate3d(expr, facets, vertices, hp_params, max_degree=None):
|
176 |
+
"""Function to translate the problem of integrating uni/bi/tri-variate
|
177 |
+
polynomials over a 3-Polytope to integrating over its faces.
|
178 |
+
This is done using Generalized Stokes' Theorem and Euler's Theorem.
|
179 |
+
|
180 |
+
Parameters
|
181 |
+
==========
|
182 |
+
|
183 |
+
expr :
|
184 |
+
The input polynomial.
|
185 |
+
facets :
|
186 |
+
Faces of the 3-Polytope(expressed as indices of `vertices`).
|
187 |
+
vertices :
|
188 |
+
Vertices that constitute the Polytope.
|
189 |
+
hp_params :
|
190 |
+
Hyperplane Parameters of the facets.
|
191 |
+
max_degree : optional
|
192 |
+
Max degree of constituent monomial in given list of polynomial.
|
193 |
+
|
194 |
+
Examples
|
195 |
+
========
|
196 |
+
|
197 |
+
>>> from sympy.integrals.intpoly import main_integrate3d, \
|
198 |
+
hyperplane_parameters
|
199 |
+
>>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
|
200 |
+
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
|
201 |
+
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
|
202 |
+
[3, 1, 0, 2], [0, 4, 6, 2]]
|
203 |
+
>>> vertices = cube[0]
|
204 |
+
>>> faces = cube[1:]
|
205 |
+
>>> hp_params = hyperplane_parameters(faces, vertices)
|
206 |
+
>>> main_integrate3d(1, faces, vertices, hp_params)
|
207 |
+
-125
|
208 |
+
"""
|
209 |
+
result = {}
|
210 |
+
dims = (x, y, z)
|
211 |
+
dim_length = len(dims)
|
212 |
+
if max_degree:
|
213 |
+
grad_terms = gradient_terms(max_degree, 3)
|
214 |
+
flat_list = [term for z_terms in grad_terms
|
215 |
+
for x_term in z_terms
|
216 |
+
for term in x_term]
|
217 |
+
|
218 |
+
for term in flat_list:
|
219 |
+
result[term[0]] = 0
|
220 |
+
|
221 |
+
for facet_count, hp in enumerate(hp_params):
|
222 |
+
a, b = hp[0], hp[1]
|
223 |
+
x0 = vertices[facets[facet_count][0]]
|
224 |
+
|
225 |
+
for i, monom in enumerate(flat_list):
|
226 |
+
# Every monomial is a tuple :
|
227 |
+
# (term, x_degree, y_degree, z_degree, value over boundary)
|
228 |
+
expr, x_d, y_d, z_d, z_index, y_index, x_index, _ = monom
|
229 |
+
degree = x_d + y_d + z_d
|
230 |
+
if b.is_zero:
|
231 |
+
value_over_face = S.Zero
|
232 |
+
else:
|
233 |
+
value_over_face = \
|
234 |
+
integration_reduction_dynamic(facets, facet_count, a,
|
235 |
+
b, expr, degree, dims,
|
236 |
+
x_index, y_index,
|
237 |
+
z_index, x0, grad_terms,
|
238 |
+
i, vertices, hp)
|
239 |
+
monom[7] = value_over_face
|
240 |
+
result[expr] += value_over_face * \
|
241 |
+
(b / norm(a)) / (dim_length + x_d + y_d + z_d)
|
242 |
+
return result
|
243 |
+
else:
|
244 |
+
integral_value = S.Zero
|
245 |
+
polynomials = decompose(expr)
|
246 |
+
for deg in polynomials:
|
247 |
+
poly_contribute = S.Zero
|
248 |
+
facet_count = 0
|
249 |
+
for i, facet in enumerate(facets):
|
250 |
+
hp = hp_params[i]
|
251 |
+
if hp[1].is_zero:
|
252 |
+
continue
|
253 |
+
pi = polygon_integrate(facet, hp, i, facets, vertices, expr, deg)
|
254 |
+
poly_contribute += pi *\
|
255 |
+
(hp[1] / norm(tuple(hp[0])))
|
256 |
+
facet_count += 1
|
257 |
+
poly_contribute /= (dim_length + deg)
|
258 |
+
integral_value += poly_contribute
|
259 |
+
return integral_value
|
260 |
+
|
261 |
+
|
262 |
+
def main_integrate(expr, facets, hp_params, max_degree=None):
|
263 |
+
"""Function to translate the problem of integrating univariate/bivariate
|
264 |
+
polynomials over a 2-Polytope to integrating over its boundary facets.
|
265 |
+
This is done using Generalized Stokes's Theorem and Euler's Theorem.
|
266 |
+
|
267 |
+
Parameters
|
268 |
+
==========
|
269 |
+
|
270 |
+
expr :
|
271 |
+
The input polynomial.
|
272 |
+
facets :
|
273 |
+
Facets(Line Segments) of the 2-Polytope.
|
274 |
+
hp_params :
|
275 |
+
Hyperplane Parameters of the facets.
|
276 |
+
max_degree : optional
|
277 |
+
The maximum degree of any monomial of the input polynomial.
|
278 |
+
|
279 |
+
>>> from sympy.abc import x, y
|
280 |
+
>>> from sympy.integrals.intpoly import main_integrate,\
|
281 |
+
hyperplane_parameters
|
282 |
+
>>> from sympy import Point, Polygon
|
283 |
+
>>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
|
284 |
+
>>> facets = triangle.sides
|
285 |
+
>>> hp_params = hyperplane_parameters(triangle)
|
286 |
+
>>> main_integrate(x**2 + y**2, facets, hp_params)
|
287 |
+
325/6
|
288 |
+
"""
|
289 |
+
dims = (x, y)
|
290 |
+
dim_length = len(dims)
|
291 |
+
result = {}
|
292 |
+
|
293 |
+
if max_degree:
|
294 |
+
grad_terms = [[0, 0, 0, 0]] + gradient_terms(max_degree)
|
295 |
+
|
296 |
+
for facet_count, hp in enumerate(hp_params):
|
297 |
+
a, b = hp[0], hp[1]
|
298 |
+
x0 = facets[facet_count].points[0]
|
299 |
+
|
300 |
+
for i, monom in enumerate(grad_terms):
|
301 |
+
# Every monomial is a tuple :
|
302 |
+
# (term, x_degree, y_degree, value over boundary)
|
303 |
+
m, x_d, y_d, _ = monom
|
304 |
+
value = result.get(m, None)
|
305 |
+
degree = S.Zero
|
306 |
+
if b.is_zero:
|
307 |
+
value_over_boundary = S.Zero
|
308 |
+
else:
|
309 |
+
degree = x_d + y_d
|
310 |
+
value_over_boundary = \
|
311 |
+
integration_reduction_dynamic(facets, facet_count, a,
|
312 |
+
b, m, degree, dims, x_d,
|
313 |
+
y_d, max_degree, x0,
|
314 |
+
grad_terms, i)
|
315 |
+
monom[3] = value_over_boundary
|
316 |
+
if value is not None:
|
317 |
+
result[m] += value_over_boundary * \
|
318 |
+
(b / norm(a)) / (dim_length + degree)
|
319 |
+
else:
|
320 |
+
result[m] = value_over_boundary * \
|
321 |
+
(b / norm(a)) / (dim_length + degree)
|
322 |
+
return result
|
323 |
+
else:
|
324 |
+
if not isinstance(expr, list):
|
325 |
+
polynomials = decompose(expr)
|
326 |
+
return _polynomial_integrate(polynomials, facets, hp_params)
|
327 |
+
else:
|
328 |
+
return {e: _polynomial_integrate(decompose(e), facets, hp_params) for e in expr}
|
329 |
+
|
330 |
+
|
331 |
+
def polygon_integrate(facet, hp_param, index, facets, vertices, expr, degree):
|
332 |
+
"""Helper function to integrate the input uni/bi/trivariate polynomial
|
333 |
+
over a certain face of the 3-Polytope.
|
334 |
+
|
335 |
+
Parameters
|
336 |
+
==========
|
337 |
+
|
338 |
+
facet :
|
339 |
+
Particular face of the 3-Polytope over which ``expr`` is integrated.
|
340 |
+
index :
|
341 |
+
The index of ``facet`` in ``facets``.
|
342 |
+
facets :
|
343 |
+
Faces of the 3-Polytope(expressed as indices of `vertices`).
|
344 |
+
vertices :
|
345 |
+
Vertices that constitute the facet.
|
346 |
+
expr :
|
347 |
+
The input polynomial.
|
348 |
+
degree :
|
349 |
+
Degree of ``expr``.
|
350 |
+
|
351 |
+
Examples
|
352 |
+
========
|
353 |
+
|
354 |
+
>>> from sympy.integrals.intpoly import polygon_integrate
|
355 |
+
>>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
|
356 |
+
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
|
357 |
+
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
|
358 |
+
[3, 1, 0, 2], [0, 4, 6, 2]]
|
359 |
+
>>> facet = cube[1]
|
360 |
+
>>> facets = cube[1:]
|
361 |
+
>>> vertices = cube[0]
|
362 |
+
>>> polygon_integrate(facet, [(0, 1, 0), 5], 0, facets, vertices, 1, 0)
|
363 |
+
-25
|
364 |
+
"""
|
365 |
+
expr = S(expr)
|
366 |
+
if expr.is_zero:
|
367 |
+
return S.Zero
|
368 |
+
result = S.Zero
|
369 |
+
x0 = vertices[facet[0]]
|
370 |
+
facet_len = len(facet)
|
371 |
+
for i, fac in enumerate(facet):
|
372 |
+
side = (vertices[fac], vertices[facet[(i + 1) % facet_len]])
|
373 |
+
result += distance_to_side(x0, side, hp_param[0]) *\
|
374 |
+
lineseg_integrate(facet, i, side, expr, degree)
|
375 |
+
if not expr.is_number:
|
376 |
+
expr = diff(expr, x) * x0[0] + diff(expr, y) * x0[1] +\
|
377 |
+
diff(expr, z) * x0[2]
|
378 |
+
result += polygon_integrate(facet, hp_param, index, facets, vertices,
|
379 |
+
expr, degree - 1)
|
380 |
+
result /= (degree + 2)
|
381 |
+
return result
|
382 |
+
|
383 |
+
|
384 |
+
def distance_to_side(point, line_seg, A):
|
385 |
+
"""Helper function to compute the signed distance between given 3D point
|
386 |
+
and a line segment.
|
387 |
+
|
388 |
+
Parameters
|
389 |
+
==========
|
390 |
+
|
391 |
+
point : 3D Point
|
392 |
+
line_seg : Line Segment
|
393 |
+
|
394 |
+
Examples
|
395 |
+
========
|
396 |
+
|
397 |
+
>>> from sympy.integrals.intpoly import distance_to_side
|
398 |
+
>>> point = (0, 0, 0)
|
399 |
+
>>> distance_to_side(point, [(0, 0, 1), (0, 1, 0)], (1, 0, 0))
|
400 |
+
-sqrt(2)/2
|
401 |
+
"""
|
402 |
+
x1, x2 = line_seg
|
403 |
+
rev_normal = [-1 * S(i)/norm(A) for i in A]
|
404 |
+
vector = [x2[i] - x1[i] for i in range(0, 3)]
|
405 |
+
vector = [vector[i]/norm(vector) for i in range(0, 3)]
|
406 |
+
|
407 |
+
n_side = cross_product((0, 0, 0), rev_normal, vector)
|
408 |
+
vectorx0 = [line_seg[0][i] - point[i] for i in range(0, 3)]
|
409 |
+
dot_product = sum([vectorx0[i] * n_side[i] for i in range(0, 3)])
|
410 |
+
|
411 |
+
return dot_product
|
412 |
+
|
413 |
+
|
414 |
+
def lineseg_integrate(polygon, index, line_seg, expr, degree):
|
415 |
+
"""Helper function to compute the line integral of ``expr`` over ``line_seg``.
|
416 |
+
|
417 |
+
Parameters
|
418 |
+
===========
|
419 |
+
|
420 |
+
polygon :
|
421 |
+
Face of a 3-Polytope.
|
422 |
+
index :
|
423 |
+
Index of line_seg in polygon.
|
424 |
+
line_seg :
|
425 |
+
Line Segment.
|
426 |
+
|
427 |
+
Examples
|
428 |
+
========
|
429 |
+
|
430 |
+
>>> from sympy.integrals.intpoly import lineseg_integrate
|
431 |
+
>>> polygon = [(0, 5, 0), (5, 5, 0), (5, 5, 5), (0, 5, 5)]
|
432 |
+
>>> line_seg = [(0, 5, 0), (5, 5, 0)]
|
433 |
+
>>> lineseg_integrate(polygon, 0, line_seg, 1, 0)
|
434 |
+
5
|
435 |
+
"""
|
436 |
+
expr = _sympify(expr)
|
437 |
+
if expr.is_zero:
|
438 |
+
return S.Zero
|
439 |
+
result = S.Zero
|
440 |
+
x0 = line_seg[0]
|
441 |
+
distance = norm(tuple([line_seg[1][i] - line_seg[0][i] for i in
|
442 |
+
range(3)]))
|
443 |
+
if isinstance(expr, Expr):
|
444 |
+
expr_dict = {x: line_seg[1][0],
|
445 |
+
y: line_seg[1][1],
|
446 |
+
z: line_seg[1][2]}
|
447 |
+
result += distance * expr.subs(expr_dict)
|
448 |
+
else:
|
449 |
+
result += distance * expr
|
450 |
+
|
451 |
+
expr = diff(expr, x) * x0[0] + diff(expr, y) * x0[1] +\
|
452 |
+
diff(expr, z) * x0[2]
|
453 |
+
|
454 |
+
result += lineseg_integrate(polygon, index, line_seg, expr, degree - 1)
|
455 |
+
result /= (degree + 1)
|
456 |
+
return result
|
457 |
+
|
458 |
+
|
459 |
+
def integration_reduction(facets, index, a, b, expr, dims, degree):
|
460 |
+
"""Helper method for main_integrate. Returns the value of the input
|
461 |
+
expression evaluated over the polytope facet referenced by a given index.
|
462 |
+
|
463 |
+
Parameters
|
464 |
+
===========
|
465 |
+
|
466 |
+
facets :
|
467 |
+
List of facets of the polytope.
|
468 |
+
index :
|
469 |
+
Index referencing the facet to integrate the expression over.
|
470 |
+
a :
|
471 |
+
Hyperplane parameter denoting direction.
|
472 |
+
b :
|
473 |
+
Hyperplane parameter denoting distance.
|
474 |
+
expr :
|
475 |
+
The expression to integrate over the facet.
|
476 |
+
dims :
|
477 |
+
List of symbols denoting axes.
|
478 |
+
degree :
|
479 |
+
Degree of the homogeneous polynomial.
|
480 |
+
|
481 |
+
Examples
|
482 |
+
========
|
483 |
+
|
484 |
+
>>> from sympy.abc import x, y
|
485 |
+
>>> from sympy.integrals.intpoly import integration_reduction,\
|
486 |
+
hyperplane_parameters
|
487 |
+
>>> from sympy import Point, Polygon
|
488 |
+
>>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
|
489 |
+
>>> facets = triangle.sides
|
490 |
+
>>> a, b = hyperplane_parameters(triangle)[0]
|
491 |
+
>>> integration_reduction(facets, 0, a, b, 1, (x, y), 0)
|
492 |
+
5
|
493 |
+
"""
|
494 |
+
expr = _sympify(expr)
|
495 |
+
if expr.is_zero:
|
496 |
+
return expr
|
497 |
+
|
498 |
+
value = S.Zero
|
499 |
+
x0 = facets[index].points[0]
|
500 |
+
m = len(facets)
|
501 |
+
gens = (x, y)
|
502 |
+
|
503 |
+
inner_product = diff(expr, gens[0]) * x0[0] + diff(expr, gens[1]) * x0[1]
|
504 |
+
|
505 |
+
if inner_product != 0:
|
506 |
+
value += integration_reduction(facets, index, a, b,
|
507 |
+
inner_product, dims, degree - 1)
|
508 |
+
|
509 |
+
value += left_integral2D(m, index, facets, x0, expr, gens)
|
510 |
+
|
511 |
+
return value/(len(dims) + degree - 1)
|
512 |
+
|
513 |
+
|
514 |
+
def left_integral2D(m, index, facets, x0, expr, gens):
|
515 |
+
"""Computes the left integral of Eq 10 in Chin et al.
|
516 |
+
For the 2D case, the integral is just an evaluation of the polynomial
|
517 |
+
at the intersection of two facets which is multiplied by the distance
|
518 |
+
between the first point of facet and that intersection.
|
519 |
+
|
520 |
+
Parameters
|
521 |
+
==========
|
522 |
+
|
523 |
+
m :
|
524 |
+
No. of hyperplanes.
|
525 |
+
index :
|
526 |
+
Index of facet to find intersections with.
|
527 |
+
facets :
|
528 |
+
List of facets(Line Segments in 2D case).
|
529 |
+
x0 :
|
530 |
+
First point on facet referenced by index.
|
531 |
+
expr :
|
532 |
+
Input polynomial
|
533 |
+
gens :
|
534 |
+
Generators which generate the polynomial
|
535 |
+
|
536 |
+
Examples
|
537 |
+
========
|
538 |
+
|
539 |
+
>>> from sympy.abc import x, y
|
540 |
+
>>> from sympy.integrals.intpoly import left_integral2D
|
541 |
+
>>> from sympy import Point, Polygon
|
542 |
+
>>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
|
543 |
+
>>> facets = triangle.sides
|
544 |
+
>>> left_integral2D(3, 0, facets, facets[0].points[0], 1, (x, y))
|
545 |
+
5
|
546 |
+
"""
|
547 |
+
value = S.Zero
|
548 |
+
for j in range(m):
|
549 |
+
intersect = ()
|
550 |
+
if j in ((index - 1) % m, (index + 1) % m):
|
551 |
+
intersect = intersection(facets[index], facets[j], "segment2D")
|
552 |
+
if intersect:
|
553 |
+
distance_origin = norm(tuple(map(lambda x, y: x - y,
|
554 |
+
intersect, x0)))
|
555 |
+
if is_vertex(intersect):
|
556 |
+
if isinstance(expr, Expr):
|
557 |
+
if len(gens) == 3:
|
558 |
+
expr_dict = {gens[0]: intersect[0],
|
559 |
+
gens[1]: intersect[1],
|
560 |
+
gens[2]: intersect[2]}
|
561 |
+
else:
|
562 |
+
expr_dict = {gens[0]: intersect[0],
|
563 |
+
gens[1]: intersect[1]}
|
564 |
+
value += distance_origin * expr.subs(expr_dict)
|
565 |
+
else:
|
566 |
+
value += distance_origin * expr
|
567 |
+
return value
|
568 |
+
|
569 |
+
|
570 |
+
def integration_reduction_dynamic(facets, index, a, b, expr, degree, dims,
|
571 |
+
x_index, y_index, max_index, x0,
|
572 |
+
monomial_values, monom_index, vertices=None,
|
573 |
+
hp_param=None):
|
574 |
+
"""The same integration_reduction function which uses a dynamic
|
575 |
+
programming approach to compute terms by using the values of the integral
|
576 |
+
of previously computed terms.
|
577 |
+
|
578 |
+
Parameters
|
579 |
+
==========
|
580 |
+
|
581 |
+
facets :
|
582 |
+
Facets of the Polytope.
|
583 |
+
index :
|
584 |
+
Index of facet to find intersections with.(Used in left_integral()).
|
585 |
+
a, b :
|
586 |
+
Hyperplane parameters.
|
587 |
+
expr :
|
588 |
+
Input monomial.
|
589 |
+
degree :
|
590 |
+
Total degree of ``expr``.
|
591 |
+
dims :
|
592 |
+
Tuple denoting axes variables.
|
593 |
+
x_index :
|
594 |
+
Exponent of 'x' in ``expr``.
|
595 |
+
y_index :
|
596 |
+
Exponent of 'y' in ``expr``.
|
597 |
+
max_index :
|
598 |
+
Maximum exponent of any monomial in ``monomial_values``.
|
599 |
+
x0 :
|
600 |
+
First point on ``facets[index]``.
|
601 |
+
monomial_values :
|
602 |
+
List of monomial values constituting the polynomial.
|
603 |
+
monom_index :
|
604 |
+
Index of monomial whose integration is being found.
|
605 |
+
vertices : optional
|
606 |
+
Coordinates of vertices constituting the 3-Polytope.
|
607 |
+
hp_param : optional
|
608 |
+
Hyperplane Parameter of the face of the facets[index].
|
609 |
+
|
610 |
+
Examples
|
611 |
+
========
|
612 |
+
|
613 |
+
>>> from sympy.abc import x, y
|
614 |
+
>>> from sympy.integrals.intpoly import (integration_reduction_dynamic, \
|
615 |
+
hyperplane_parameters)
|
616 |
+
>>> from sympy import Point, Polygon
|
617 |
+
>>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
|
618 |
+
>>> facets = triangle.sides
|
619 |
+
>>> a, b = hyperplane_parameters(triangle)[0]
|
620 |
+
>>> x0 = facets[0].points[0]
|
621 |
+
>>> monomial_values = [[0, 0, 0, 0], [1, 0, 0, 5],\
|
622 |
+
[y, 0, 1, 15], [x, 1, 0, None]]
|
623 |
+
>>> integration_reduction_dynamic(facets, 0, a, b, x, 1, (x, y), 1, 0, 1,\
|
624 |
+
x0, monomial_values, 3)
|
625 |
+
25/2
|
626 |
+
"""
|
627 |
+
value = S.Zero
|
628 |
+
m = len(facets)
|
629 |
+
|
630 |
+
if expr == S.Zero:
|
631 |
+
return expr
|
632 |
+
|
633 |
+
if len(dims) == 2:
|
634 |
+
if not expr.is_number:
|
635 |
+
_, x_degree, y_degree, _ = monomial_values[monom_index]
|
636 |
+
x_index = monom_index - max_index + \
|
637 |
+
x_index - 2 if x_degree > 0 else 0
|
638 |
+
y_index = monom_index - 1 if y_degree > 0 else 0
|
639 |
+
x_value, y_value =\
|
640 |
+
monomial_values[x_index][3], monomial_values[y_index][3]
|
641 |
+
|
642 |
+
value += x_degree * x_value * x0[0] + y_degree * y_value * x0[1]
|
643 |
+
|
644 |
+
value += left_integral2D(m, index, facets, x0, expr, dims)
|
645 |
+
else:
|
646 |
+
# For 3D use case the max_index contains the z_degree of the term
|
647 |
+
z_index = max_index
|
648 |
+
if not expr.is_number:
|
649 |
+
x_degree, y_degree, z_degree = y_index,\
|
650 |
+
z_index - x_index - y_index, x_index
|
651 |
+
x_value = monomial_values[z_index - 1][y_index - 1][x_index][7]\
|
652 |
+
if x_degree > 0 else 0
|
653 |
+
y_value = monomial_values[z_index - 1][y_index][x_index][7]\
|
654 |
+
if y_degree > 0 else 0
|
655 |
+
z_value = monomial_values[z_index - 1][y_index][x_index - 1][7]\
|
656 |
+
if z_degree > 0 else 0
|
657 |
+
|
658 |
+
value += x_degree * x_value * x0[0] + y_degree * y_value * x0[1] \
|
659 |
+
+ z_degree * z_value * x0[2]
|
660 |
+
|
661 |
+
value += left_integral3D(facets, index, expr,
|
662 |
+
vertices, hp_param, degree)
|
663 |
+
return value / (len(dims) + degree - 1)
|
664 |
+
|
665 |
+
|
666 |
+
def left_integral3D(facets, index, expr, vertices, hp_param, degree):
|
667 |
+
"""Computes the left integral of Eq 10 in Chin et al.
|
668 |
+
|
669 |
+
Explanation
|
670 |
+
===========
|
671 |
+
|
672 |
+
For the 3D case, this is the sum of the integral values over constituting
|
673 |
+
line segments of the face (which is accessed by facets[index]) multiplied
|
674 |
+
by the distance between the first point of facet and that line segment.
|
675 |
+
|
676 |
+
Parameters
|
677 |
+
==========
|
678 |
+
|
679 |
+
facets :
|
680 |
+
List of faces of the 3-Polytope.
|
681 |
+
index :
|
682 |
+
Index of face over which integral is to be calculated.
|
683 |
+
expr :
|
684 |
+
Input polynomial.
|
685 |
+
vertices :
|
686 |
+
List of vertices that constitute the 3-Polytope.
|
687 |
+
hp_param :
|
688 |
+
The hyperplane parameters of the face.
|
689 |
+
degree :
|
690 |
+
Degree of the ``expr``.
|
691 |
+
|
692 |
+
Examples
|
693 |
+
========
|
694 |
+
|
695 |
+
>>> from sympy.integrals.intpoly import left_integral3D
|
696 |
+
>>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
|
697 |
+
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
|
698 |
+
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
|
699 |
+
[3, 1, 0, 2], [0, 4, 6, 2]]
|
700 |
+
>>> facets = cube[1:]
|
701 |
+
>>> vertices = cube[0]
|
702 |
+
>>> left_integral3D(facets, 3, 1, vertices, ([0, -1, 0], -5), 0)
|
703 |
+
-50
|
704 |
+
"""
|
705 |
+
value = S.Zero
|
706 |
+
facet = facets[index]
|
707 |
+
x0 = vertices[facet[0]]
|
708 |
+
facet_len = len(facet)
|
709 |
+
for i, fac in enumerate(facet):
|
710 |
+
side = (vertices[fac], vertices[facet[(i + 1) % facet_len]])
|
711 |
+
value += distance_to_side(x0, side, hp_param[0]) * \
|
712 |
+
lineseg_integrate(facet, i, side, expr, degree)
|
713 |
+
return value
|
714 |
+
|
715 |
+
|
716 |
+
def gradient_terms(binomial_power=0, no_of_gens=2):
|
717 |
+
"""Returns a list of all the possible monomials between
|
718 |
+
0 and y**binomial_power for 2D case and z**binomial_power
|
719 |
+
for 3D case.
|
720 |
+
|
721 |
+
Parameters
|
722 |
+
==========
|
723 |
+
|
724 |
+
binomial_power :
|
725 |
+
Power upto which terms are generated.
|
726 |
+
no_of_gens :
|
727 |
+
Denotes whether terms are being generated for 2D or 3D case.
|
728 |
+
|
729 |
+
Examples
|
730 |
+
========
|
731 |
+
|
732 |
+
>>> from sympy.integrals.intpoly import gradient_terms
|
733 |
+
>>> gradient_terms(2)
|
734 |
+
[[1, 0, 0, 0], [y, 0, 1, 0], [y**2, 0, 2, 0], [x, 1, 0, 0],
|
735 |
+
[x*y, 1, 1, 0], [x**2, 2, 0, 0]]
|
736 |
+
>>> gradient_terms(2, 3)
|
737 |
+
[[[[1, 0, 0, 0, 0, 0, 0, 0]]], [[[y, 0, 1, 0, 1, 0, 0, 0],
|
738 |
+
[z, 0, 0, 1, 1, 0, 1, 0]], [[x, 1, 0, 0, 1, 1, 0, 0]]],
|
739 |
+
[[[y**2, 0, 2, 0, 2, 0, 0, 0], [y*z, 0, 1, 1, 2, 0, 1, 0],
|
740 |
+
[z**2, 0, 0, 2, 2, 0, 2, 0]], [[x*y, 1, 1, 0, 2, 1, 0, 0],
|
741 |
+
[x*z, 1, 0, 1, 2, 1, 1, 0]], [[x**2, 2, 0, 0, 2, 2, 0, 0]]]]
|
742 |
+
"""
|
743 |
+
if no_of_gens == 2:
|
744 |
+
count = 0
|
745 |
+
terms = [None] * int((binomial_power ** 2 + 3 * binomial_power + 2) / 2)
|
746 |
+
for x_count in range(0, binomial_power + 1):
|
747 |
+
for y_count in range(0, binomial_power - x_count + 1):
|
748 |
+
terms[count] = [x**x_count*y**y_count,
|
749 |
+
x_count, y_count, 0]
|
750 |
+
count += 1
|
751 |
+
else:
|
752 |
+
terms = [[[[x ** x_count * y ** y_count *
|
753 |
+
z ** (z_count - y_count - x_count),
|
754 |
+
x_count, y_count, z_count - y_count - x_count,
|
755 |
+
z_count, x_count, z_count - y_count - x_count, 0]
|
756 |
+
for y_count in range(z_count - x_count, -1, -1)]
|
757 |
+
for x_count in range(0, z_count + 1)]
|
758 |
+
for z_count in range(0, binomial_power + 1)]
|
759 |
+
return terms
|
760 |
+
|
761 |
+
|
762 |
+
def hyperplane_parameters(poly, vertices=None):
|
763 |
+
"""A helper function to return the hyperplane parameters
|
764 |
+
of which the facets of the polytope are a part of.
|
765 |
+
|
766 |
+
Parameters
|
767 |
+
==========
|
768 |
+
|
769 |
+
poly :
|
770 |
+
The input 2/3-Polytope.
|
771 |
+
vertices :
|
772 |
+
Vertex indices of 3-Polytope.
|
773 |
+
|
774 |
+
Examples
|
775 |
+
========
|
776 |
+
|
777 |
+
>>> from sympy import Point, Polygon
|
778 |
+
>>> from sympy.integrals.intpoly import hyperplane_parameters
|
779 |
+
>>> hyperplane_parameters(Polygon(Point(0, 3), Point(5, 3), Point(1, 1)))
|
780 |
+
[((0, 1), 3), ((1, -2), -1), ((-2, -1), -3)]
|
781 |
+
>>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
|
782 |
+
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
|
783 |
+
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
|
784 |
+
[3, 1, 0, 2], [0, 4, 6, 2]]
|
785 |
+
>>> hyperplane_parameters(cube[1:], cube[0])
|
786 |
+
[([0, -1, 0], -5), ([0, 0, -1], -5), ([-1, 0, 0], -5),
|
787 |
+
([0, 1, 0], 0), ([1, 0, 0], 0), ([0, 0, 1], 0)]
|
788 |
+
"""
|
789 |
+
if isinstance(poly, Polygon):
|
790 |
+
vertices = list(poly.vertices) + [poly.vertices[0]] # Close the polygon
|
791 |
+
params = [None] * (len(vertices) - 1)
|
792 |
+
|
793 |
+
for i in range(len(vertices) - 1):
|
794 |
+
v1 = vertices[i]
|
795 |
+
v2 = vertices[i + 1]
|
796 |
+
|
797 |
+
a1 = v1[1] - v2[1]
|
798 |
+
a2 = v2[0] - v1[0]
|
799 |
+
b = v2[0] * v1[1] - v2[1] * v1[0]
|
800 |
+
|
801 |
+
factor = gcd_list([a1, a2, b])
|
802 |
+
|
803 |
+
b = S(b) / factor
|
804 |
+
a = (S(a1) / factor, S(a2) / factor)
|
805 |
+
params[i] = (a, b)
|
806 |
+
else:
|
807 |
+
params = [None] * len(poly)
|
808 |
+
for i, polygon in enumerate(poly):
|
809 |
+
v1, v2, v3 = [vertices[vertex] for vertex in polygon[:3]]
|
810 |
+
normal = cross_product(v1, v2, v3)
|
811 |
+
b = sum([normal[j] * v1[j] for j in range(0, 3)])
|
812 |
+
fac = gcd_list(normal)
|
813 |
+
if fac.is_zero:
|
814 |
+
fac = 1
|
815 |
+
normal = [j / fac for j in normal]
|
816 |
+
b = b / fac
|
817 |
+
params[i] = (normal, b)
|
818 |
+
return params
|
819 |
+
|
820 |
+
|
821 |
+
def cross_product(v1, v2, v3):
|
822 |
+
"""Returns the cross-product of vectors (v2 - v1) and (v3 - v1)
|
823 |
+
That is : (v2 - v1) X (v3 - v1)
|
824 |
+
"""
|
825 |
+
v2 = [v2[j] - v1[j] for j in range(0, 3)]
|
826 |
+
v3 = [v3[j] - v1[j] for j in range(0, 3)]
|
827 |
+
return [v3[2] * v2[1] - v3[1] * v2[2],
|
828 |
+
v3[0] * v2[2] - v3[2] * v2[0],
|
829 |
+
v3[1] * v2[0] - v3[0] * v2[1]]
|
830 |
+
|
831 |
+
|
832 |
+
def best_origin(a, b, lineseg, expr):
|
833 |
+
"""Helper method for polytope_integrate. Currently not used in the main
|
834 |
+
algorithm.
|
835 |
+
|
836 |
+
Explanation
|
837 |
+
===========
|
838 |
+
|
839 |
+
Returns a point on the lineseg whose vector inner product with the
|
840 |
+
divergence of `expr` yields an expression with the least maximum
|
841 |
+
total power.
|
842 |
+
|
843 |
+
Parameters
|
844 |
+
==========
|
845 |
+
|
846 |
+
a :
|
847 |
+
Hyperplane parameter denoting direction.
|
848 |
+
b :
|
849 |
+
Hyperplane parameter denoting distance.
|
850 |
+
lineseg :
|
851 |
+
Line segment on which to find the origin.
|
852 |
+
expr :
|
853 |
+
The expression which determines the best point.
|
854 |
+
|
855 |
+
Algorithm(currently works only for 2D use case)
|
856 |
+
===============================================
|
857 |
+
|
858 |
+
1 > Firstly, check for edge cases. Here that would refer to vertical
|
859 |
+
or horizontal lines.
|
860 |
+
|
861 |
+
2 > If input expression is a polynomial containing more than one generator
|
862 |
+
then find out the total power of each of the generators.
|
863 |
+
|
864 |
+
x**2 + 3 + x*y + x**4*y**5 ---> {x: 7, y: 6}
|
865 |
+
|
866 |
+
If expression is a constant value then pick the first boundary point
|
867 |
+
of the line segment.
|
868 |
+
|
869 |
+
3 > First check if a point exists on the line segment where the value of
|
870 |
+
the highest power generator becomes 0. If not check if the value of
|
871 |
+
the next highest becomes 0. If none becomes 0 within line segment
|
872 |
+
constraints then pick the first boundary point of the line segment.
|
873 |
+
Actually, any point lying on the segment can be picked as best origin
|
874 |
+
in the last case.
|
875 |
+
|
876 |
+
Examples
|
877 |
+
========
|
878 |
+
|
879 |
+
>>> from sympy.integrals.intpoly import best_origin
|
880 |
+
>>> from sympy.abc import x, y
|
881 |
+
>>> from sympy import Point, Segment2D
|
882 |
+
>>> l = Segment2D(Point(0, 3), Point(1, 1))
|
883 |
+
>>> expr = x**3*y**7
|
884 |
+
>>> best_origin((2, 1), 3, l, expr)
|
885 |
+
(0, 3.0)
|
886 |
+
"""
|
887 |
+
a1, b1 = lineseg.points[0]
|
888 |
+
|
889 |
+
def x_axis_cut(ls):
|
890 |
+
"""Returns the point where the input line segment
|
891 |
+
intersects the x-axis.
|
892 |
+
|
893 |
+
Parameters
|
894 |
+
==========
|
895 |
+
|
896 |
+
ls :
|
897 |
+
Line segment
|
898 |
+
"""
|
899 |
+
p, q = ls.points
|
900 |
+
if p.y.is_zero:
|
901 |
+
return tuple(p)
|
902 |
+
elif q.y.is_zero:
|
903 |
+
return tuple(q)
|
904 |
+
elif p.y/q.y < S.Zero:
|
905 |
+
return p.y * (p.x - q.x)/(q.y - p.y) + p.x, S.Zero
|
906 |
+
else:
|
907 |
+
return ()
|
908 |
+
|
909 |
+
def y_axis_cut(ls):
|
910 |
+
"""Returns the point where the input line segment
|
911 |
+
intersects the y-axis.
|
912 |
+
|
913 |
+
Parameters
|
914 |
+
==========
|
915 |
+
|
916 |
+
ls :
|
917 |
+
Line segment
|
918 |
+
"""
|
919 |
+
p, q = ls.points
|
920 |
+
if p.x.is_zero:
|
921 |
+
return tuple(p)
|
922 |
+
elif q.x.is_zero:
|
923 |
+
return tuple(q)
|
924 |
+
elif p.x/q.x < S.Zero:
|
925 |
+
return S.Zero, p.x * (p.y - q.y)/(q.x - p.x) + p.y
|
926 |
+
else:
|
927 |
+
return ()
|
928 |
+
|
929 |
+
gens = (x, y)
|
930 |
+
power_gens = {}
|
931 |
+
|
932 |
+
for i in gens:
|
933 |
+
power_gens[i] = S.Zero
|
934 |
+
|
935 |
+
if len(gens) > 1:
|
936 |
+
# Special case for vertical and horizontal lines
|
937 |
+
if len(gens) == 2:
|
938 |
+
if a[0] == 0:
|
939 |
+
if y_axis_cut(lineseg):
|
940 |
+
return S.Zero, b/a[1]
|
941 |
+
else:
|
942 |
+
return a1, b1
|
943 |
+
elif a[1] == 0:
|
944 |
+
if x_axis_cut(lineseg):
|
945 |
+
return b/a[0], S.Zero
|
946 |
+
else:
|
947 |
+
return a1, b1
|
948 |
+
|
949 |
+
if isinstance(expr, Expr): # Find the sum total of power of each
|
950 |
+
if expr.is_Add: # generator and store in a dictionary.
|
951 |
+
for monomial in expr.args:
|
952 |
+
if monomial.is_Pow:
|
953 |
+
if monomial.args[0] in gens:
|
954 |
+
power_gens[monomial.args[0]] += monomial.args[1]
|
955 |
+
else:
|
956 |
+
for univariate in monomial.args:
|
957 |
+
term_type = len(univariate.args)
|
958 |
+
if term_type == 0 and univariate in gens:
|
959 |
+
power_gens[univariate] += 1
|
960 |
+
elif term_type == 2 and univariate.args[0] in gens:
|
961 |
+
power_gens[univariate.args[0]] +=\
|
962 |
+
univariate.args[1]
|
963 |
+
elif expr.is_Mul:
|
964 |
+
for term in expr.args:
|
965 |
+
term_type = len(term.args)
|
966 |
+
if term_type == 0 and term in gens:
|
967 |
+
power_gens[term] += 1
|
968 |
+
elif term_type == 2 and term.args[0] in gens:
|
969 |
+
power_gens[term.args[0]] += term.args[1]
|
970 |
+
elif expr.is_Pow:
|
971 |
+
power_gens[expr.args[0]] = expr.args[1]
|
972 |
+
elif expr.is_Symbol:
|
973 |
+
power_gens[expr] += 1
|
974 |
+
else: # If `expr` is a constant take first vertex of the line segment.
|
975 |
+
return a1, b1
|
976 |
+
|
977 |
+
# TODO : This part is quite hacky. Should be made more robust with
|
978 |
+
# TODO : respect to symbol names and scalable w.r.t higher dimensions.
|
979 |
+
power_gens = sorted(power_gens.items(), key=lambda k: str(k[0]))
|
980 |
+
if power_gens[0][1] >= power_gens[1][1]:
|
981 |
+
if y_axis_cut(lineseg):
|
982 |
+
x0 = (S.Zero, b / a[1])
|
983 |
+
elif x_axis_cut(lineseg):
|
984 |
+
x0 = (b / a[0], S.Zero)
|
985 |
+
else:
|
986 |
+
x0 = (a1, b1)
|
987 |
+
else:
|
988 |
+
if x_axis_cut(lineseg):
|
989 |
+
x0 = (b/a[0], S.Zero)
|
990 |
+
elif y_axis_cut(lineseg):
|
991 |
+
x0 = (S.Zero, b/a[1])
|
992 |
+
else:
|
993 |
+
x0 = (a1, b1)
|
994 |
+
else:
|
995 |
+
x0 = (b/a[0])
|
996 |
+
return x0
|
997 |
+
|
998 |
+
|
999 |
+
def decompose(expr, separate=False):
|
1000 |
+
"""Decomposes an input polynomial into homogeneous ones of
|
1001 |
+
smaller or equal degree.
|
1002 |
+
|
1003 |
+
Explanation
|
1004 |
+
===========
|
1005 |
+
|
1006 |
+
Returns a dictionary with keys as the degree of the smaller
|
1007 |
+
constituting polynomials. Values are the constituting polynomials.
|
1008 |
+
|
1009 |
+
Parameters
|
1010 |
+
==========
|
1011 |
+
|
1012 |
+
expr : Expr
|
1013 |
+
Polynomial(SymPy expression).
|
1014 |
+
separate : bool
|
1015 |
+
If True then simply return a list of the constituent monomials
|
1016 |
+
If not then break up the polynomial into constituent homogeneous
|
1017 |
+
polynomials.
|
1018 |
+
|
1019 |
+
Examples
|
1020 |
+
========
|
1021 |
+
|
1022 |
+
>>> from sympy.abc import x, y
|
1023 |
+
>>> from sympy.integrals.intpoly import decompose
|
1024 |
+
>>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5)
|
1025 |
+
{1: x + y, 2: x**2 + x*y, 5: x**3*y**2 + y**5}
|
1026 |
+
>>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5, True)
|
1027 |
+
{x, x**2, y, y**5, x*y, x**3*y**2}
|
1028 |
+
"""
|
1029 |
+
poly_dict = {}
|
1030 |
+
|
1031 |
+
if isinstance(expr, Expr) and not expr.is_number:
|
1032 |
+
if expr.is_Symbol:
|
1033 |
+
poly_dict[1] = expr
|
1034 |
+
elif expr.is_Add:
|
1035 |
+
symbols = expr.atoms(Symbol)
|
1036 |
+
degrees = [(sum(degree_list(monom, *symbols)), monom)
|
1037 |
+
for monom in expr.args]
|
1038 |
+
if separate:
|
1039 |
+
return {monom[1] for monom in degrees}
|
1040 |
+
else:
|
1041 |
+
for monom in degrees:
|
1042 |
+
degree, term = monom
|
1043 |
+
if poly_dict.get(degree):
|
1044 |
+
poly_dict[degree] += term
|
1045 |
+
else:
|
1046 |
+
poly_dict[degree] = term
|
1047 |
+
elif expr.is_Pow:
|
1048 |
+
_, degree = expr.args
|
1049 |
+
poly_dict[degree] = expr
|
1050 |
+
else: # Now expr can only be of `Mul` type
|
1051 |
+
degree = 0
|
1052 |
+
for term in expr.args:
|
1053 |
+
term_type = len(term.args)
|
1054 |
+
if term_type == 0 and term.is_Symbol:
|
1055 |
+
degree += 1
|
1056 |
+
elif term_type == 2:
|
1057 |
+
degree += term.args[1]
|
1058 |
+
poly_dict[degree] = expr
|
1059 |
+
else:
|
1060 |
+
poly_dict[0] = expr
|
1061 |
+
|
1062 |
+
if separate:
|
1063 |
+
return set(poly_dict.values())
|
1064 |
+
return poly_dict
|
1065 |
+
|
1066 |
+
|
1067 |
+
def point_sort(poly, normal=None, clockwise=True):
|
1068 |
+
"""Returns the same polygon with points sorted in clockwise or
|
1069 |
+
anti-clockwise order.
|
1070 |
+
|
1071 |
+
Note that it's necessary for input points to be sorted in some order
|
1072 |
+
(clockwise or anti-clockwise) for the integration algorithm to work.
|
1073 |
+
As a convention algorithm has been implemented keeping clockwise
|
1074 |
+
orientation in mind.
|
1075 |
+
|
1076 |
+
Parameters
|
1077 |
+
==========
|
1078 |
+
|
1079 |
+
poly:
|
1080 |
+
2D or 3D Polygon.
|
1081 |
+
normal : optional
|
1082 |
+
The normal of the plane which the 3-Polytope is a part of.
|
1083 |
+
clockwise : bool, optional
|
1084 |
+
Returns points sorted in clockwise order if True and
|
1085 |
+
anti-clockwise if False.
|
1086 |
+
|
1087 |
+
Examples
|
1088 |
+
========
|
1089 |
+
|
1090 |
+
>>> from sympy.integrals.intpoly import point_sort
|
1091 |
+
>>> from sympy import Point
|
1092 |
+
>>> point_sort([Point(0, 0), Point(1, 0), Point(1, 1)])
|
1093 |
+
[Point2D(1, 1), Point2D(1, 0), Point2D(0, 0)]
|
1094 |
+
"""
|
1095 |
+
pts = poly.vertices if isinstance(poly, Polygon) else poly
|
1096 |
+
n = len(pts)
|
1097 |
+
if n < 2:
|
1098 |
+
return list(pts)
|
1099 |
+
|
1100 |
+
order = S.One if clockwise else S.NegativeOne
|
1101 |
+
dim = len(pts[0])
|
1102 |
+
if dim == 2:
|
1103 |
+
center = Point(sum((vertex.x for vertex in pts)) / n,
|
1104 |
+
sum((vertex.y for vertex in pts)) / n)
|
1105 |
+
else:
|
1106 |
+
center = Point(sum((vertex.x for vertex in pts)) / n,
|
1107 |
+
sum((vertex.y for vertex in pts)) / n,
|
1108 |
+
sum((vertex.z for vertex in pts)) / n)
|
1109 |
+
|
1110 |
+
def compare(a, b):
|
1111 |
+
if a.x - center.x >= S.Zero and b.x - center.x < S.Zero:
|
1112 |
+
return -order
|
1113 |
+
elif a.x - center.x < 0 and b.x - center.x >= 0:
|
1114 |
+
return order
|
1115 |
+
elif a.x - center.x == 0 and b.x - center.x == 0:
|
1116 |
+
if a.y - center.y >= 0 or b.y - center.y >= 0:
|
1117 |
+
return -order if a.y > b.y else order
|
1118 |
+
return -order if b.y > a.y else order
|
1119 |
+
|
1120 |
+
det = (a.x - center.x) * (b.y - center.y) -\
|
1121 |
+
(b.x - center.x) * (a.y - center.y)
|
1122 |
+
if det < 0:
|
1123 |
+
return -order
|
1124 |
+
elif det > 0:
|
1125 |
+
return order
|
1126 |
+
|
1127 |
+
first = (a.x - center.x) * (a.x - center.x) +\
|
1128 |
+
(a.y - center.y) * (a.y - center.y)
|
1129 |
+
second = (b.x - center.x) * (b.x - center.x) +\
|
1130 |
+
(b.y - center.y) * (b.y - center.y)
|
1131 |
+
return -order if first > second else order
|
1132 |
+
|
1133 |
+
def compare3d(a, b):
|
1134 |
+
det = cross_product(center, a, b)
|
1135 |
+
dot_product = sum([det[i] * normal[i] for i in range(0, 3)])
|
1136 |
+
if dot_product < 0:
|
1137 |
+
return -order
|
1138 |
+
elif dot_product > 0:
|
1139 |
+
return order
|
1140 |
+
|
1141 |
+
return sorted(pts, key=cmp_to_key(compare if dim==2 else compare3d))
|
1142 |
+
|
1143 |
+
|
1144 |
+
def norm(point):
|
1145 |
+
"""Returns the Euclidean norm of a point from origin.
|
1146 |
+
|
1147 |
+
Parameters
|
1148 |
+
==========
|
1149 |
+
|
1150 |
+
point:
|
1151 |
+
This denotes a point in the dimension_al spac_e.
|
1152 |
+
|
1153 |
+
Examples
|
1154 |
+
========
|
1155 |
+
|
1156 |
+
>>> from sympy.integrals.intpoly import norm
|
1157 |
+
>>> from sympy import Point
|
1158 |
+
>>> norm(Point(2, 7))
|
1159 |
+
sqrt(53)
|
1160 |
+
"""
|
1161 |
+
half = S.Half
|
1162 |
+
if isinstance(point, (list, tuple)):
|
1163 |
+
return sum([coord ** 2 for coord in point]) ** half
|
1164 |
+
elif isinstance(point, Point):
|
1165 |
+
if isinstance(point, Point2D):
|
1166 |
+
return (point.x ** 2 + point.y ** 2) ** half
|
1167 |
+
else:
|
1168 |
+
return (point.x ** 2 + point.y ** 2 + point.z) ** half
|
1169 |
+
elif isinstance(point, dict):
|
1170 |
+
return sum(i**2 for i in point.values()) ** half
|
1171 |
+
|
1172 |
+
|
1173 |
+
def intersection(geom_1, geom_2, intersection_type):
|
1174 |
+
"""Returns intersection between geometric objects.
|
1175 |
+
|
1176 |
+
Explanation
|
1177 |
+
===========
|
1178 |
+
|
1179 |
+
Note that this function is meant for use in integration_reduction and
|
1180 |
+
at that point in the calling function the lines denoted by the segments
|
1181 |
+
surely intersect within segment boundaries. Coincident lines are taken
|
1182 |
+
to be non-intersecting. Also, the hyperplane intersection for 2D case is
|
1183 |
+
also implemented.
|
1184 |
+
|
1185 |
+
Parameters
|
1186 |
+
==========
|
1187 |
+
|
1188 |
+
geom_1, geom_2:
|
1189 |
+
The input line segments.
|
1190 |
+
|
1191 |
+
Examples
|
1192 |
+
========
|
1193 |
+
|
1194 |
+
>>> from sympy.integrals.intpoly import intersection
|
1195 |
+
>>> from sympy import Point, Segment2D
|
1196 |
+
>>> l1 = Segment2D(Point(1, 1), Point(3, 5))
|
1197 |
+
>>> l2 = Segment2D(Point(2, 0), Point(2, 5))
|
1198 |
+
>>> intersection(l1, l2, "segment2D")
|
1199 |
+
(2, 3)
|
1200 |
+
>>> p1 = ((-1, 0), 0)
|
1201 |
+
>>> p2 = ((0, 1), 1)
|
1202 |
+
>>> intersection(p1, p2, "plane2D")
|
1203 |
+
(0, 1)
|
1204 |
+
"""
|
1205 |
+
if intersection_type[:-2] == "segment":
|
1206 |
+
if intersection_type == "segment2D":
|
1207 |
+
x1, y1 = geom_1.points[0]
|
1208 |
+
x2, y2 = geom_1.points[1]
|
1209 |
+
x3, y3 = geom_2.points[0]
|
1210 |
+
x4, y4 = geom_2.points[1]
|
1211 |
+
elif intersection_type == "segment3D":
|
1212 |
+
x1, y1, z1 = geom_1.points[0]
|
1213 |
+
x2, y2, z2 = geom_1.points[1]
|
1214 |
+
x3, y3, z3 = geom_2.points[0]
|
1215 |
+
x4, y4, z4 = geom_2.points[1]
|
1216 |
+
|
1217 |
+
denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
|
1218 |
+
if denom:
|
1219 |
+
t1 = x1 * y2 - y1 * x2
|
1220 |
+
t2 = x3 * y4 - x4 * y3
|
1221 |
+
return (S(t1 * (x3 - x4) - t2 * (x1 - x2)) / denom,
|
1222 |
+
S(t1 * (y3 - y4) - t2 * (y1 - y2)) / denom)
|
1223 |
+
if intersection_type[:-2] == "plane":
|
1224 |
+
if intersection_type == "plane2D": # Intersection of hyperplanes
|
1225 |
+
a1x, a1y = geom_1[0]
|
1226 |
+
a2x, a2y = geom_2[0]
|
1227 |
+
b1, b2 = geom_1[1], geom_2[1]
|
1228 |
+
|
1229 |
+
denom = a1x * a2y - a2x * a1y
|
1230 |
+
if denom:
|
1231 |
+
return (S(b1 * a2y - b2 * a1y) / denom,
|
1232 |
+
S(b2 * a1x - b1 * a2x) / denom)
|
1233 |
+
|
1234 |
+
|
1235 |
+
def is_vertex(ent):
|
1236 |
+
"""If the input entity is a vertex return True.
|
1237 |
+
|
1238 |
+
Parameter
|
1239 |
+
=========
|
1240 |
+
|
1241 |
+
ent :
|
1242 |
+
Denotes a geometric entity representing a point.
|
1243 |
+
|
1244 |
+
Examples
|
1245 |
+
========
|
1246 |
+
|
1247 |
+
>>> from sympy import Point
|
1248 |
+
>>> from sympy.integrals.intpoly import is_vertex
|
1249 |
+
>>> is_vertex((2, 3))
|
1250 |
+
True
|
1251 |
+
>>> is_vertex((2, 3, 6))
|
1252 |
+
True
|
1253 |
+
>>> is_vertex(Point(2, 3))
|
1254 |
+
True
|
1255 |
+
"""
|
1256 |
+
if isinstance(ent, tuple):
|
1257 |
+
if len(ent) in [2, 3]:
|
1258 |
+
return True
|
1259 |
+
elif isinstance(ent, Point):
|
1260 |
+
return True
|
1261 |
+
return False
|
1262 |
+
|
1263 |
+
|
1264 |
+
def plot_polytope(poly):
|
1265 |
+
"""Plots the 2D polytope using the functions written in plotting
|
1266 |
+
module which in turn uses matplotlib backend.
|
1267 |
+
|
1268 |
+
Parameter
|
1269 |
+
=========
|
1270 |
+
|
1271 |
+
poly:
|
1272 |
+
Denotes a 2-Polytope.
|
1273 |
+
"""
|
1274 |
+
from sympy.plotting.plot import Plot, List2DSeries
|
1275 |
+
|
1276 |
+
xl = [vertex.x for vertex in poly.vertices]
|
1277 |
+
yl = [vertex.y for vertex in poly.vertices]
|
1278 |
+
|
1279 |
+
xl.append(poly.vertices[0].x) # Closing the polygon
|
1280 |
+
yl.append(poly.vertices[0].y)
|
1281 |
+
|
1282 |
+
l2ds = List2DSeries(xl, yl)
|
1283 |
+
p = Plot(l2ds, axes='label_axes=True')
|
1284 |
+
p.show()
|
1285 |
+
|
1286 |
+
|
1287 |
+
def plot_polynomial(expr):
|
1288 |
+
"""Plots the polynomial using the functions written in
|
1289 |
+
plotting module which in turn uses matplotlib backend.
|
1290 |
+
|
1291 |
+
Parameter
|
1292 |
+
=========
|
1293 |
+
|
1294 |
+
expr:
|
1295 |
+
Denotes a polynomial(SymPy expression).
|
1296 |
+
"""
|
1297 |
+
from sympy.plotting.plot import plot3d, plot
|
1298 |
+
gens = expr.free_symbols
|
1299 |
+
if len(gens) == 2:
|
1300 |
+
plot3d(expr)
|
1301 |
+
else:
|
1302 |
+
plot(expr)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/laplace.py
ADDED
@@ -0,0 +1,1761 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Laplace Transforms"""
|
2 |
+
from sympy.core import S, pi, I
|
3 |
+
from sympy.core.add import Add
|
4 |
+
from sympy.core.cache import cacheit
|
5 |
+
from sympy.core.function import (
|
6 |
+
AppliedUndef, Derivative, expand, expand_complex, expand_mul, expand_trig,
|
7 |
+
Lambda, WildFunction, diff)
|
8 |
+
from sympy.core.mul import Mul, prod
|
9 |
+
from sympy.core.relational import _canonical, Ge, Gt, Lt, Unequality, Eq
|
10 |
+
from sympy.core.sorting import ordered
|
11 |
+
from sympy.core.symbol import Dummy, symbols, Wild
|
12 |
+
from sympy.functions.elementary.complexes import (
|
13 |
+
re, im, arg, Abs, polar_lift, periodic_argument)
|
14 |
+
from sympy.functions.elementary.exponential import exp, log
|
15 |
+
from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, asinh
|
16 |
+
from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
|
17 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
18 |
+
from sympy.functions.elementary.trigonometric import cos, sin, atan
|
19 |
+
from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
|
20 |
+
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
|
21 |
+
from sympy.functions.special.error_functions import erf, erfc, Ei
|
22 |
+
from sympy.functions.special.gamma_functions import digamma, gamma, lowergamma
|
23 |
+
from sympy.integrals import integrate, Integral
|
24 |
+
from sympy.integrals.transforms import (
|
25 |
+
_simplify, IntegralTransform, IntegralTransformError)
|
26 |
+
from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And
|
27 |
+
from sympy.matrices.matrices import MatrixBase
|
28 |
+
from sympy.polys.matrices.linsolve import _lin_eq2dict
|
29 |
+
from sympy.polys.polyerrors import PolynomialError
|
30 |
+
from sympy.polys.polyroots import roots
|
31 |
+
from sympy.polys.polytools import Poly
|
32 |
+
from sympy.polys.rationaltools import together
|
33 |
+
from sympy.polys.rootoftools import RootSum
|
34 |
+
from sympy.utilities.exceptions import (
|
35 |
+
sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings)
|
36 |
+
from sympy.utilities.misc import debug, debugf
|
37 |
+
|
38 |
+
|
39 |
+
def _simplifyconds(expr, s, a):
|
40 |
+
r"""
|
41 |
+
Naively simplify some conditions occurring in ``expr``,
|
42 |
+
given that `\operatorname{Re}(s) > a`.
|
43 |
+
|
44 |
+
Examples
|
45 |
+
========
|
46 |
+
|
47 |
+
>>> from sympy.integrals.laplace import _simplifyconds
|
48 |
+
>>> from sympy.abc import x
|
49 |
+
>>> from sympy import sympify as S
|
50 |
+
>>> _simplifyconds(abs(x**2) < 1, x, 1)
|
51 |
+
False
|
52 |
+
>>> _simplifyconds(abs(x**2) < 1, x, 2)
|
53 |
+
False
|
54 |
+
>>> _simplifyconds(abs(x**2) < 1, x, 0)
|
55 |
+
Abs(x**2) < 1
|
56 |
+
>>> _simplifyconds(abs(1/x**2) < 1, x, 1)
|
57 |
+
True
|
58 |
+
>>> _simplifyconds(S(1) < abs(x), x, 1)
|
59 |
+
True
|
60 |
+
>>> _simplifyconds(S(1) < abs(1/x), x, 1)
|
61 |
+
False
|
62 |
+
|
63 |
+
>>> from sympy import Ne
|
64 |
+
>>> _simplifyconds(Ne(1, x**3), x, 1)
|
65 |
+
True
|
66 |
+
>>> _simplifyconds(Ne(1, x**3), x, 2)
|
67 |
+
True
|
68 |
+
>>> _simplifyconds(Ne(1, x**3), x, 0)
|
69 |
+
Ne(1, x**3)
|
70 |
+
"""
|
71 |
+
|
72 |
+
def power(ex):
|
73 |
+
if ex == s:
|
74 |
+
return 1
|
75 |
+
if ex.is_Pow and ex.base == s:
|
76 |
+
return ex.exp
|
77 |
+
return None
|
78 |
+
|
79 |
+
def bigger(ex1, ex2):
|
80 |
+
""" Return True only if |ex1| > |ex2|, False only if |ex1| < |ex2|.
|
81 |
+
Else return None. """
|
82 |
+
if ex1.has(s) and ex2.has(s):
|
83 |
+
return None
|
84 |
+
if isinstance(ex1, Abs):
|
85 |
+
ex1 = ex1.args[0]
|
86 |
+
if isinstance(ex2, Abs):
|
87 |
+
ex2 = ex2.args[0]
|
88 |
+
if ex1.has(s):
|
89 |
+
return bigger(1/ex2, 1/ex1)
|
90 |
+
n = power(ex2)
|
91 |
+
if n is None:
|
92 |
+
return None
|
93 |
+
try:
|
94 |
+
if n > 0 and (Abs(ex1) <= Abs(a)**n) == S.true:
|
95 |
+
return False
|
96 |
+
if n < 0 and (Abs(ex1) >= Abs(a)**n) == S.true:
|
97 |
+
return True
|
98 |
+
except TypeError:
|
99 |
+
pass
|
100 |
+
|
101 |
+
def replie(x, y):
|
102 |
+
""" simplify x < y """
|
103 |
+
if (not (x.is_positive or isinstance(x, Abs))
|
104 |
+
or not (y.is_positive or isinstance(y, Abs))):
|
105 |
+
return (x < y)
|
106 |
+
r = bigger(x, y)
|
107 |
+
if r is not None:
|
108 |
+
return not r
|
109 |
+
return (x < y)
|
110 |
+
|
111 |
+
def replue(x, y):
|
112 |
+
b = bigger(x, y)
|
113 |
+
if b in (True, False):
|
114 |
+
return True
|
115 |
+
return Unequality(x, y)
|
116 |
+
|
117 |
+
def repl(ex, *args):
|
118 |
+
if ex in (True, False):
|
119 |
+
return bool(ex)
|
120 |
+
return ex.replace(*args)
|
121 |
+
from sympy.simplify.radsimp import collect_abs
|
122 |
+
expr = collect_abs(expr)
|
123 |
+
expr = repl(expr, Lt, replie)
|
124 |
+
expr = repl(expr, Gt, lambda x, y: replie(y, x))
|
125 |
+
expr = repl(expr, Unequality, replue)
|
126 |
+
return S(expr)
|
127 |
+
|
128 |
+
|
129 |
+
def expand_dirac_delta(expr):
|
130 |
+
"""
|
131 |
+
Expand an expression involving DiractDelta to get it as a linear
|
132 |
+
combination of DiracDelta functions.
|
133 |
+
"""
|
134 |
+
return _lin_eq2dict(expr, expr.atoms(DiracDelta))
|
135 |
+
|
136 |
+
|
137 |
+
def _laplace_transform_integration(f, t, s_, simplify=True):
|
138 |
+
""" The backend function for doing Laplace transforms by integration.
|
139 |
+
|
140 |
+
This backend assumes that the frontend has already split sums
|
141 |
+
such that `f` is to an addition anymore.
|
142 |
+
"""
|
143 |
+
s = Dummy('s')
|
144 |
+
debugf('[LT _l_t_i ] started with (%s, %s, %s)', (f, t, s))
|
145 |
+
debugf('[LT _l_t_i ] and simplify=%s', (simplify, ))
|
146 |
+
|
147 |
+
if f.has(DiracDelta):
|
148 |
+
return None
|
149 |
+
|
150 |
+
F = integrate(f*exp(-s*t), (t, S.Zero, S.Infinity))
|
151 |
+
debugf('[LT _l_t_i ] integrated: %s', (F, ))
|
152 |
+
|
153 |
+
if not F.has(Integral):
|
154 |
+
return _simplify(F.subs(s, s_), simplify), S.NegativeInfinity, S.true
|
155 |
+
|
156 |
+
if not F.is_Piecewise:
|
157 |
+
debug('[LT _l_t_i ] not piecewise.')
|
158 |
+
return None
|
159 |
+
|
160 |
+
F, cond = F.args[0]
|
161 |
+
if F.has(Integral):
|
162 |
+
debug('[LT _l_t_i ] integral in unexpected form.')
|
163 |
+
return None
|
164 |
+
|
165 |
+
def process_conds(conds):
|
166 |
+
""" Turn ``conds`` into a strip and auxiliary conditions. """
|
167 |
+
from sympy.solvers.inequalities import _solve_inequality
|
168 |
+
a = S.NegativeInfinity
|
169 |
+
aux = S.true
|
170 |
+
conds = conjuncts(to_cnf(conds))
|
171 |
+
p, q, w1, w2, w3, w4, w5 = symbols(
|
172 |
+
'p q w1 w2 w3 w4 w5', cls=Wild, exclude=[s])
|
173 |
+
patterns = (
|
174 |
+
p*Abs(arg((s + w3)*q)) < w2,
|
175 |
+
p*Abs(arg((s + w3)*q)) <= w2,
|
176 |
+
Abs(periodic_argument((s + w3)**p*q, w1)) < w2,
|
177 |
+
Abs(periodic_argument((s + w3)**p*q, w1)) <= w2,
|
178 |
+
Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) < w2,
|
179 |
+
Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) <= w2)
|
180 |
+
for c in conds:
|
181 |
+
a_ = S.Infinity
|
182 |
+
aux_ = []
|
183 |
+
for d in disjuncts(c):
|
184 |
+
if d.is_Relational and s in d.rhs.free_symbols:
|
185 |
+
d = d.reversed
|
186 |
+
if d.is_Relational and isinstance(d, (Ge, Gt)):
|
187 |
+
d = d.reversedsign
|
188 |
+
for pat in patterns:
|
189 |
+
m = d.match(pat)
|
190 |
+
if m:
|
191 |
+
break
|
192 |
+
if m and m[q].is_positive and m[w2]/m[p] == pi/2:
|
193 |
+
d = -re(s + m[w3]) < 0
|
194 |
+
m = d.match(p - cos(w1*Abs(arg(s*w5))*w2)*Abs(s**w3)**w4 < 0)
|
195 |
+
if not m:
|
196 |
+
m = d.match(
|
197 |
+
cos(p - Abs(periodic_argument(s**w1*w5, q))*w2) *
|
198 |
+
Abs(s**w3)**w4 < 0)
|
199 |
+
if not m:
|
200 |
+
m = d.match(
|
201 |
+
p - cos(
|
202 |
+
Abs(periodic_argument(polar_lift(s)**w1*w5, q))*w2
|
203 |
+
)*Abs(s**w3)**w4 < 0)
|
204 |
+
if m and all(m[wild].is_positive for wild in [
|
205 |
+
w1, w2, w3, w4, w5]):
|
206 |
+
d = re(s) > m[p]
|
207 |
+
d_ = d.replace(
|
208 |
+
re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t)
|
209 |
+
if (
|
210 |
+
not d.is_Relational or d.rel_op in ('==', '!=')
|
211 |
+
or d_.has(s) or not d_.has(t)):
|
212 |
+
aux_ += [d]
|
213 |
+
continue
|
214 |
+
soln = _solve_inequality(d_, t)
|
215 |
+
if not soln.is_Relational or soln.rel_op in ('==', '!='):
|
216 |
+
aux_ += [d]
|
217 |
+
continue
|
218 |
+
if soln.lts == t:
|
219 |
+
debug('[LT _l_t_i ] convergence not in half-plane.')
|
220 |
+
return None
|
221 |
+
else:
|
222 |
+
a_ = Min(soln.lts, a_)
|
223 |
+
if a_ is not S.Infinity:
|
224 |
+
a = Max(a_, a)
|
225 |
+
else:
|
226 |
+
aux = And(aux, Or(*aux_))
|
227 |
+
return a, aux.canonical if aux.is_Relational else aux
|
228 |
+
|
229 |
+
conds = [process_conds(c) for c in disjuncts(cond)]
|
230 |
+
conds2 = [x for x in conds if x[1] !=
|
231 |
+
S.false and x[0] is not S.NegativeInfinity]
|
232 |
+
if not conds2:
|
233 |
+
conds2 = [x for x in conds if x[1] != S.false]
|
234 |
+
conds = list(ordered(conds2))
|
235 |
+
|
236 |
+
def cnt(expr):
|
237 |
+
if expr in (True, False):
|
238 |
+
return 0
|
239 |
+
return expr.count_ops()
|
240 |
+
conds.sort(key=lambda x: (-x[0], cnt(x[1])))
|
241 |
+
|
242 |
+
if not conds:
|
243 |
+
debug('[LT _l_t_i ] no convergence found.')
|
244 |
+
return None
|
245 |
+
a, aux = conds[0] # XXX is [0] always the right one?
|
246 |
+
|
247 |
+
def sbs(expr):
|
248 |
+
return expr.subs(s, s_)
|
249 |
+
if simplify:
|
250 |
+
F = _simplifyconds(F, s, a)
|
251 |
+
aux = _simplifyconds(aux, s, a)
|
252 |
+
return _simplify(F.subs(s, s_), simplify), sbs(a), _canonical(sbs(aux))
|
253 |
+
|
254 |
+
|
255 |
+
def _laplace_deep_collect(f, t):
|
256 |
+
"""
|
257 |
+
This is an internal helper function that traverses through the epression
|
258 |
+
tree of `f(t)` and collects arguments. The purpose of it is that
|
259 |
+
anything like `f(w*t-1*t-c)` will be written as `f((w-1)*t-c)` such that
|
260 |
+
it can match `f(a*t+b)`.
|
261 |
+
"""
|
262 |
+
func = f.func
|
263 |
+
args = list(f.args)
|
264 |
+
if len(f.args) == 0:
|
265 |
+
return f
|
266 |
+
else:
|
267 |
+
args = [_laplace_deep_collect(arg, t) for arg in args]
|
268 |
+
if func.is_Add:
|
269 |
+
return func(*args).collect(t)
|
270 |
+
else:
|
271 |
+
return func(*args)
|
272 |
+
|
273 |
+
|
274 |
+
@cacheit
|
275 |
+
def _laplace_build_rules():
|
276 |
+
"""
|
277 |
+
This is an internal helper function that returns the table of Laplace
|
278 |
+
transform rules in terms of the time variable `t` and the frequency
|
279 |
+
variable `s`. It is used by ``_laplace_apply_rules``. Each entry is a
|
280 |
+
tuple containing:
|
281 |
+
|
282 |
+
(time domain pattern,
|
283 |
+
frequency-domain replacement,
|
284 |
+
condition for the rule to be applied,
|
285 |
+
convergence plane,
|
286 |
+
preparation function)
|
287 |
+
|
288 |
+
The preparation function is a function with one argument that is applied
|
289 |
+
to the expression before matching. For most rules it should be
|
290 |
+
``_laplace_deep_collect``.
|
291 |
+
"""
|
292 |
+
t = Dummy('t')
|
293 |
+
s = Dummy('s')
|
294 |
+
a = Wild('a', exclude=[t])
|
295 |
+
b = Wild('b', exclude=[t])
|
296 |
+
n = Wild('n', exclude=[t])
|
297 |
+
tau = Wild('tau', exclude=[t])
|
298 |
+
omega = Wild('omega', exclude=[t])
|
299 |
+
def dco(f): return _laplace_deep_collect(f, t)
|
300 |
+
debug('_laplace_build_rules is building rules')
|
301 |
+
|
302 |
+
laplace_transform_rules = [
|
303 |
+
(a, a/s,
|
304 |
+
S.true, S.Zero, dco), # 4.2.1
|
305 |
+
(DiracDelta(a*t-b), exp(-s*b/a)/Abs(a),
|
306 |
+
Or(And(a > 0, b >= 0), And(a < 0, b <= 0)),
|
307 |
+
S.NegativeInfinity, dco), # Not in Bateman54
|
308 |
+
(DiracDelta(a*t-b), S(0),
|
309 |
+
Or(And(a < 0, b >= 0), And(a > 0, b <= 0)),
|
310 |
+
S.NegativeInfinity, dco), # Not in Bateman54
|
311 |
+
(Heaviside(a*t-b), exp(-s*b/a)/s,
|
312 |
+
And(a > 0, b > 0), S.Zero, dco), # 4.4.1
|
313 |
+
(Heaviside(a*t-b), (1-exp(-s*b/a))/s,
|
314 |
+
And(a < 0, b < 0), S.Zero, dco), # 4.4.1
|
315 |
+
(Heaviside(a*t-b), 1/s,
|
316 |
+
And(a > 0, b <= 0), S.Zero, dco), # 4.4.1
|
317 |
+
(Heaviside(a*t-b), 0,
|
318 |
+
And(a < 0, b > 0), S.Zero, dco), # 4.4.1
|
319 |
+
(t, 1/s**2,
|
320 |
+
S.true, S.Zero, dco), # 4.2.3
|
321 |
+
(1/(a*t+b), -exp(-b/a*s)*Ei(-b/a*s)/a,
|
322 |
+
Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.6
|
323 |
+
(1/sqrt(a*t+b), sqrt(a*pi/s)*exp(b/a*s)*erfc(sqrt(b/a*s))/a,
|
324 |
+
Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.18
|
325 |
+
((a*t+b)**(-S(3)/2),
|
326 |
+
2*b**(-S(1)/2)-2*(pi*s/a)**(S(1)/2)*exp(b/a*s) * erfc(sqrt(b/a*s))/a,
|
327 |
+
Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.20
|
328 |
+
(sqrt(t)/(t+b), sqrt(pi/s)-pi*sqrt(b)*exp(b*s)*erfc(sqrt(b*s)),
|
329 |
+
Abs(arg(b)) < pi, S.Zero, dco), # 4.2.22
|
330 |
+
(1/(a*sqrt(t) + t**(3/2)), pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)),
|
331 |
+
S.true, S.Zero, dco), # Not in Bateman54
|
332 |
+
(t**n, gamma(n+1)/s**(n+1),
|
333 |
+
n > -1, S.Zero, dco), # 4.3.1
|
334 |
+
((a*t+b)**n, lowergamma(n+1, b/a*s)*exp(-b/a*s)/s**(n+1)/a,
|
335 |
+
And(n > -1, Abs(arg(b/a)) < pi), S.Zero, dco), # 4.3.4
|
336 |
+
(t**n/(t+a), a**n*gamma(n+1)*lowergamma(-n, a*s),
|
337 |
+
And(n > -1, Abs(arg(a)) < pi), S.Zero, dco), # 4.3.7
|
338 |
+
(exp(a*t-tau), exp(-tau)/(s-a),
|
339 |
+
S.true, re(a), dco), # 4.5.1
|
340 |
+
(t*exp(a*t-tau), exp(-tau)/(s-a)**2,
|
341 |
+
S.true, re(a), dco), # 4.5.2
|
342 |
+
(t**n*exp(a*t), gamma(n+1)/(s-a)**(n+1),
|
343 |
+
re(n) > -1, re(a), dco), # 4.5.3
|
344 |
+
(exp(-a*t**2), sqrt(pi/4/a)*exp(s**2/4/a)*erfc(s/sqrt(4*a)),
|
345 |
+
re(a) > 0, S.Zero, dco), # 4.5.21
|
346 |
+
(t*exp(-a*t**2),
|
347 |
+
1/(2*a)-2/sqrt(pi)/(4*a)**(S(3)/2)*s*erfc(s/sqrt(4*a)),
|
348 |
+
re(a) > 0, S.Zero, dco), # 4.5.22
|
349 |
+
(exp(-a/t), 2*sqrt(a/s)*besselk(1, 2*sqrt(a*s)),
|
350 |
+
re(a) >= 0, S.Zero, dco), # 4.5.25
|
351 |
+
(sqrt(t)*exp(-a/t),
|
352 |
+
S(1)/2*sqrt(pi/s**3)*(1+2*sqrt(a*s))*exp(-2*sqrt(a*s)),
|
353 |
+
re(a) >= 0, S.Zero, dco), # 4.5.26
|
354 |
+
(exp(-a/t)/sqrt(t), sqrt(pi/s)*exp(-2*sqrt(a*s)),
|
355 |
+
re(a) >= 0, S.Zero, dco), # 4.5.27
|
356 |
+
(exp(-a/t)/(t*sqrt(t)), sqrt(pi/a)*exp(-2*sqrt(a*s)),
|
357 |
+
re(a) > 0, S.Zero, dco), # 4.5.28
|
358 |
+
(t**n*exp(-a/t), 2*(a/s)**((n+1)/2)*besselk(n+1, 2*sqrt(a*s)),
|
359 |
+
re(a) > 0, S.Zero, dco), # 4.5.29
|
360 |
+
(exp(-2*sqrt(a*t)),
|
361 |
+
s**(-1)-sqrt(pi*a)*s**(-S(3)/2)*exp(a/s) * erfc(sqrt(a/s)),
|
362 |
+
Abs(arg(a)) < pi, S.Zero, dco), # 4.5.31
|
363 |
+
(exp(-2*sqrt(a*t))/sqrt(t), (pi/s)**(S(1)/2)*exp(a/s)*erfc(sqrt(a/s)),
|
364 |
+
Abs(arg(a)) < pi, S.Zero, dco), # 4.5.33
|
365 |
+
(log(a*t), -log(exp(S.EulerGamma)*s/a)/s,
|
366 |
+
a > 0, S.Zero, dco), # 4.6.1
|
367 |
+
(log(1+a*t), -exp(s/a)/s*Ei(-s/a),
|
368 |
+
Abs(arg(a)) < pi, S.Zero, dco), # 4.6.4
|
369 |
+
(log(a*t+b), (log(b)-exp(s/b/a)/s*a*Ei(-s/b))/s*a,
|
370 |
+
And(a > 0, Abs(arg(b)) < pi), S.Zero, dco), # 4.6.5
|
371 |
+
(log(t)/sqrt(t), -sqrt(pi/s)*log(4*s*exp(S.EulerGamma)),
|
372 |
+
S.true, S.Zero, dco), # 4.6.9
|
373 |
+
(t**n*log(t), gamma(n+1)*s**(-n-1)*(digamma(n+1)-log(s)),
|
374 |
+
re(n) > -1, S.Zero, dco), # 4.6.11
|
375 |
+
(log(a*t)**2, (log(exp(S.EulerGamma)*s/a)**2+pi**2/6)/s,
|
376 |
+
a > 0, S.Zero, dco), # 4.6.13
|
377 |
+
(sin(omega*t), omega/(s**2+omega**2),
|
378 |
+
S.true, Abs(im(omega)), dco), # 4,7,1
|
379 |
+
(Abs(sin(omega*t)), omega/(s**2+omega**2)*coth(pi*s/2/omega),
|
380 |
+
omega > 0, S.Zero, dco), # 4.7.2
|
381 |
+
(sin(omega*t)/t, atan(omega/s),
|
382 |
+
S.true, Abs(im(omega)), dco), # 4.7.16
|
383 |
+
(sin(omega*t)**2/t, log(1+4*omega**2/s**2)/4,
|
384 |
+
S.true, 2*Abs(im(omega)), dco), # 4.7.17
|
385 |
+
(sin(omega*t)**2/t**2,
|
386 |
+
omega*atan(2*omega/s)-s*log(1+4*omega**2/s**2)/4,
|
387 |
+
S.true, 2*Abs(im(omega)), dco), # 4.7.20
|
388 |
+
(sin(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(-a/s),
|
389 |
+
S.true, S.Zero, dco), # 4.7.32
|
390 |
+
(sin(2*sqrt(a*t))/t, pi*erf(sqrt(a/s)),
|
391 |
+
S.true, S.Zero, dco), # 4.7.34
|
392 |
+
(cos(omega*t), s/(s**2+omega**2),
|
393 |
+
S.true, Abs(im(omega)), dco), # 4.7.43
|
394 |
+
(cos(omega*t)**2, (s**2+2*omega**2)/(s**2+4*omega**2)/s,
|
395 |
+
S.true, 2*Abs(im(omega)), dco), # 4.7.45
|
396 |
+
(sqrt(t)*cos(2*sqrt(a*t)), sqrt(pi)/2*s**(-S(5)/2)*(s-2*a)*exp(-a/s),
|
397 |
+
S.true, S.Zero, dco), # 4.7.66
|
398 |
+
(cos(2*sqrt(a*t))/sqrt(t), sqrt(pi/s)*exp(-a/s),
|
399 |
+
S.true, S.Zero, dco), # 4.7.67
|
400 |
+
(sin(a*t)*sin(b*t), 2*a*b*s/(s**2+(a+b)**2)/(s**2+(a-b)**2),
|
401 |
+
S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.78
|
402 |
+
(cos(a*t)*sin(b*t), b*(s**2-a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2),
|
403 |
+
S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.79
|
404 |
+
(cos(a*t)*cos(b*t), s*(s**2+a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2),
|
405 |
+
S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.80
|
406 |
+
(sinh(a*t), a/(s**2-a**2),
|
407 |
+
S.true, Abs(re(a)), dco), # 4.9.1
|
408 |
+
(cosh(a*t), s/(s**2-a**2),
|
409 |
+
S.true, Abs(re(a)), dco), # 4.9.2
|
410 |
+
(sinh(a*t)**2, 2*a**2/(s**3-4*a**2*s),
|
411 |
+
S.true, 2*Abs(re(a)), dco), # 4.9.3
|
412 |
+
(cosh(a*t)**2, (s**2-2*a**2)/(s**3-4*a**2*s),
|
413 |
+
S.true, 2*Abs(re(a)), dco), # 4.9.4
|
414 |
+
(sinh(a*t)/t, log((s+a)/(s-a))/2,
|
415 |
+
S.true, Abs(re(a)), dco), # 4.9.12
|
416 |
+
(t**n*sinh(a*t), gamma(n+1)/2*((s-a)**(-n-1)-(s+a)**(-n-1)),
|
417 |
+
n > -2, Abs(a), dco), # 4.9.18
|
418 |
+
(t**n*cosh(a*t), gamma(n+1)/2*((s-a)**(-n-1)+(s+a)**(-n-1)),
|
419 |
+
n > -1, Abs(a), dco), # 4.9.19
|
420 |
+
(sinh(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(a/s),
|
421 |
+
S.true, S.Zero, dco), # 4.9.34
|
422 |
+
(cosh(2*sqrt(a*t)), 1/s+sqrt(pi*a)/s/sqrt(s)*exp(a/s)*erf(sqrt(a/s)),
|
423 |
+
S.true, S.Zero, dco), # 4.9.35
|
424 |
+
(
|
425 |
+
sqrt(t)*sinh(2*sqrt(a*t)),
|
426 |
+
pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a) *
|
427 |
+
exp(a/s)*erf(sqrt(a/s))-a**(S(1)/2)*s**(-2),
|
428 |
+
S.true, S.Zero, dco), # 4.9.36
|
429 |
+
(sqrt(t)*cosh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s),
|
430 |
+
S.true, S.Zero, dco), # 4.9.37
|
431 |
+
(sinh(2*sqrt(a*t))/sqrt(t),
|
432 |
+
pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s) * erf(sqrt(a/s)),
|
433 |
+
S.true, S.Zero, dco), # 4.9.38
|
434 |
+
(cosh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s),
|
435 |
+
S.true, S.Zero, dco), # 4.9.39
|
436 |
+
(sinh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)-1),
|
437 |
+
S.true, S.Zero, dco), # 4.9.40
|
438 |
+
(cosh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)+1),
|
439 |
+
S.true, S.Zero, dco), # 4.9.41
|
440 |
+
(erf(a*t), exp(s**2/(2*a)**2)*erfc(s/(2*a))/s,
|
441 |
+
4*Abs(arg(a)) < pi, S.Zero, dco), # 4.12.2
|
442 |
+
(erf(sqrt(a*t)), sqrt(a)/sqrt(s+a)/s,
|
443 |
+
S.true, Max(S.Zero, -re(a)), dco), # 4.12.4
|
444 |
+
(exp(a*t)*erf(sqrt(a*t)), sqrt(a)/sqrt(s)/(s-a),
|
445 |
+
S.true, Max(S.Zero, re(a)), dco), # 4.12.5
|
446 |
+
(erf(sqrt(a/t)/2), (1-exp(-sqrt(a*s)))/s,
|
447 |
+
re(a) > 0, S.Zero, dco), # 4.12.6
|
448 |
+
(erfc(sqrt(a*t)), (sqrt(s+a)-sqrt(a))/sqrt(s+a)/s,
|
449 |
+
S.true, -re(a), dco), # 4.12.9
|
450 |
+
(exp(a*t)*erfc(sqrt(a*t)), 1/(s+sqrt(a*s)),
|
451 |
+
S.true, S.Zero, dco), # 4.12.10
|
452 |
+
(erfc(sqrt(a/t)/2), exp(-sqrt(a*s))/s,
|
453 |
+
re(a) > 0, S.Zero, dco), # 4.2.11
|
454 |
+
(besselj(n, a*t), a**n/(sqrt(s**2+a**2)*(s+sqrt(s**2+a**2))**n),
|
455 |
+
re(n) > -1, Abs(im(a)), dco), # 4.14.1
|
456 |
+
(t**b*besselj(n, a*t),
|
457 |
+
2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2+a**2)**(-n-S.Half),
|
458 |
+
And(re(n) > -S.Half, Eq(b, n)), Abs(im(a)), dco), # 4.14.7
|
459 |
+
(t**b*besselj(n, a*t),
|
460 |
+
2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2+a**2)**(-n-S(3)/2),
|
461 |
+
And(re(n) > -1, Eq(b, n+1)), Abs(im(a)), dco), # 4.14.8
|
462 |
+
(besselj(0, 2*sqrt(a*t)), exp(-a/s)/s,
|
463 |
+
S.true, S.Zero, dco), # 4.14.25
|
464 |
+
(t**(b)*besselj(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(-a/s),
|
465 |
+
And(re(n) > -1, Eq(b, n*S.Half)), S.Zero, dco), # 4.14.30
|
466 |
+
(besselj(0, a*sqrt(t**2+b*t)),
|
467 |
+
exp(b*s-b*sqrt(s**2+a**2))/sqrt(s**2+a**2),
|
468 |
+
Abs(arg(b)) < pi, Abs(im(a)), dco), # 4.15.19
|
469 |
+
(besseli(n, a*t), a**n/(sqrt(s**2-a**2)*(s+sqrt(s**2-a**2))**n),
|
470 |
+
re(n) > -1, Abs(re(a)), dco), # 4.16.1
|
471 |
+
(t**b*besseli(n, a*t),
|
472 |
+
2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2-a**2)**(-n-S.Half),
|
473 |
+
And(re(n) > -S.Half, Eq(b, n)), Abs(re(a)), dco), # 4.16.6
|
474 |
+
(t**b*besseli(n, a*t),
|
475 |
+
2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2-a**2)**(-n-S(3)/2),
|
476 |
+
And(re(n) > -1, Eq(b, n+1)), Abs(re(a)), dco), # 4.16.7
|
477 |
+
(t**(b)*besseli(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(a/s),
|
478 |
+
And(re(n) > -1, Eq(b, n*S.Half)), S.Zero, dco), # 4.16.18
|
479 |
+
(bessely(0, a*t), -2/pi*asinh(s/a)/sqrt(s**2+a**2),
|
480 |
+
S.true, Abs(im(a)), dco), # 4.15.44
|
481 |
+
(besselk(0, a*t), log((s + sqrt(s**2-a**2))/a)/(sqrt(s**2-a**2)),
|
482 |
+
S.true, -re(a), dco) # 4.16.23
|
483 |
+
]
|
484 |
+
return laplace_transform_rules, t, s
|
485 |
+
|
486 |
+
|
487 |
+
def _laplace_rule_timescale(f, t, s):
|
488 |
+
"""
|
489 |
+
This function applies the time-scaling rule of the Laplace transform in
|
490 |
+
a straight-forward way. For example, if it gets ``(f(a*t), t, s)``, it will
|
491 |
+
compute ``LaplaceTransform(f(t)/a, t, s/a)`` if ``a>0``.
|
492 |
+
"""
|
493 |
+
|
494 |
+
a = Wild('a', exclude=[t])
|
495 |
+
g = WildFunction('g', nargs=1)
|
496 |
+
ma1 = f.match(g)
|
497 |
+
if ma1:
|
498 |
+
arg = ma1[g].args[0].collect(t)
|
499 |
+
ma2 = arg.match(a*t)
|
500 |
+
if ma2 and ma2[a].is_positive and ma2[a] != 1:
|
501 |
+
debug('_laplace_apply_prog rules match:')
|
502 |
+
debugf(' f: %s _ %s, %s )', (f, ma1, ma2))
|
503 |
+
debug(' rule: time scaling (4.1.4)')
|
504 |
+
r, pr, cr = _laplace_transform(1/ma2[a]*ma1[g].func(t),
|
505 |
+
t, s/ma2[a], simplify=False)
|
506 |
+
return (r, pr, cr)
|
507 |
+
return None
|
508 |
+
|
509 |
+
|
510 |
+
def _laplace_rule_heaviside(f, t, s):
|
511 |
+
"""
|
512 |
+
This function deals with time-shifted Heaviside step functions. If the time
|
513 |
+
shift is positive, it applies the time-shift rule of the Laplace transform.
|
514 |
+
For example, if it gets ``(Heaviside(t-a)*f(t), t, s)``, it will compute
|
515 |
+
``exp(-a*s)*LaplaceTransform(f(t+a), t, s)``.
|
516 |
+
|
517 |
+
If the time shift is negative, the Heaviside function is simply removed
|
518 |
+
as it means nothing to the Laplace transform.
|
519 |
+
|
520 |
+
The function does not remove a factor ``Heaviside(t)``; this is done by
|
521 |
+
the simple rules.
|
522 |
+
"""
|
523 |
+
|
524 |
+
a = Wild('a', exclude=[t])
|
525 |
+
y = Wild('y')
|
526 |
+
g = Wild('g')
|
527 |
+
ma1 = f.match(Heaviside(y)*g)
|
528 |
+
if ma1:
|
529 |
+
ma2 = ma1[y].match(t-a)
|
530 |
+
if ma2 and ma2[a].is_positive:
|
531 |
+
debug('_laplace_apply_prog_rules match:')
|
532 |
+
debugf(' f: %s ( %s, %s )', (f, ma1, ma2))
|
533 |
+
debug(' rule: time shift (4.1.4)')
|
534 |
+
r, pr, cr = _laplace_transform(ma1[g].subs(t, t+ma2[a]), t, s,
|
535 |
+
simplify=False)
|
536 |
+
return (exp(-ma2[a]*s)*r, pr, cr)
|
537 |
+
if ma2 and ma2[a].is_negative:
|
538 |
+
debug('_laplace_apply_prog_rules match:')
|
539 |
+
debugf(' f: %s ( %s, %s )', (f, ma1, ma2))
|
540 |
+
debug(' rule: Heaviside factor, negative time shift (4.1.4)')
|
541 |
+
r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False)
|
542 |
+
return (r, pr, cr)
|
543 |
+
return None
|
544 |
+
|
545 |
+
|
546 |
+
def _laplace_rule_exp(f, t, s):
|
547 |
+
"""
|
548 |
+
If this function finds a factor ``exp(a*t)``, it applies the
|
549 |
+
frequency-shift rule of the Laplace transform and adjusts the convergence
|
550 |
+
plane accordingly. For example, if it gets ``(exp(-a*t)*f(t), t, s)``, it
|
551 |
+
will compute ``LaplaceTransform(f(t), t, s+a)``.
|
552 |
+
"""
|
553 |
+
|
554 |
+
a = Wild('a', exclude=[t])
|
555 |
+
y = Wild('y')
|
556 |
+
z = Wild('z')
|
557 |
+
ma1 = f.match(exp(y)*z)
|
558 |
+
if ma1:
|
559 |
+
ma2 = ma1[y].collect(t).match(a*t)
|
560 |
+
if ma2:
|
561 |
+
debug('_laplace_apply_prog_rules match:')
|
562 |
+
debugf(' f: %s ( %s, %s )', (f, ma1, ma2))
|
563 |
+
debug(' rule: multiply with exp (4.1.5)')
|
564 |
+
r, pr, cr = _laplace_transform(ma1[z], t, s-ma2[a],
|
565 |
+
simplify=False)
|
566 |
+
return (r, pr+re(ma2[a]), cr)
|
567 |
+
return None
|
568 |
+
|
569 |
+
|
570 |
+
def _laplace_rule_delta(f, t, s):
|
571 |
+
"""
|
572 |
+
If this function finds a factor ``DiracDelta(b*t-a)``, it applies the
|
573 |
+
masking property of the delta distribution. For example, if it gets
|
574 |
+
``(DiracDelta(t-a)*f(t), t, s)``, it will return
|
575 |
+
``(f(a)*exp(-a*s), -a, True)``.
|
576 |
+
"""
|
577 |
+
# This rule is not in Bateman54
|
578 |
+
|
579 |
+
a = Wild('a', exclude=[t])
|
580 |
+
b = Wild('b', exclude=[t])
|
581 |
+
|
582 |
+
y = Wild('y')
|
583 |
+
z = Wild('z')
|
584 |
+
ma1 = f.match(DiracDelta(y)*z)
|
585 |
+
if ma1 and not ma1[z].has(DiracDelta):
|
586 |
+
ma2 = ma1[y].collect(t).match(b*t-a)
|
587 |
+
if ma2:
|
588 |
+
debug('_laplace_apply_prog_rules match:')
|
589 |
+
debugf(' f: %s ( %s, %s )', (f, ma1, ma2))
|
590 |
+
debug(' rule: multiply with DiracDelta')
|
591 |
+
loc = ma2[a]/ma2[b]
|
592 |
+
if re(loc) >= 0 and im(loc) == 0:
|
593 |
+
r = exp(-ma2[a]/ma2[b]*s)*ma1[z].subs(t, ma2[a]/ma2[b])/ma2[b]
|
594 |
+
return (r, S.NegativeInfinity, S.true)
|
595 |
+
else:
|
596 |
+
return (0, S.NegativeInfinity, S.true)
|
597 |
+
if ma1[y].is_polynomial(t):
|
598 |
+
ro = roots(ma1[y], t)
|
599 |
+
if roots is not {} and set(ro.values()) == {1}:
|
600 |
+
slope = diff(ma1[y], t)
|
601 |
+
r = Add(
|
602 |
+
*[exp(-x*s)*ma1[z].subs(t, s)/slope.subs(t, x)
|
603 |
+
for x in list(ro.keys()) if im(x) == 0 and re(x) >= 0])
|
604 |
+
return (r, S.NegativeInfinity, S.true)
|
605 |
+
return None
|
606 |
+
|
607 |
+
|
608 |
+
def _laplace_trig_split(fn):
|
609 |
+
"""
|
610 |
+
Helper function for `_laplace_rule_trig`. This function returns two terms
|
611 |
+
`f` and `g`. `f` contains all product terms with sin, cos, sinh, cosh in
|
612 |
+
them; `g` contains everything else.
|
613 |
+
"""
|
614 |
+
trigs = [S.One]
|
615 |
+
other = [S.One]
|
616 |
+
for term in Mul.make_args(fn):
|
617 |
+
if term.has(sin, cos, sinh, cosh, exp):
|
618 |
+
trigs.append(term)
|
619 |
+
else:
|
620 |
+
other.append(term)
|
621 |
+
f = Mul(*trigs)
|
622 |
+
g = Mul(*other)
|
623 |
+
return f, g
|
624 |
+
|
625 |
+
|
626 |
+
def _laplace_trig_expsum(f, t):
|
627 |
+
"""
|
628 |
+
Helper function for `_laplace_rule_trig`. This function expects the `f`
|
629 |
+
from `_laplace_trig_split`. It returns two lists `xm` and `xn`. `xm` is
|
630 |
+
a list of dictionaries with keys `k` and `a` representing a function
|
631 |
+
`k*exp(a*t)`. `xn` is a list of all terms that cannot be brought into
|
632 |
+
that form, which may happen, e.g., when a trigonometric function has
|
633 |
+
another function in its argument.
|
634 |
+
"""
|
635 |
+
m = Wild('m')
|
636 |
+
p = Wild('p', exclude=[t])
|
637 |
+
xm = []
|
638 |
+
xn = []
|
639 |
+
|
640 |
+
x1 = f.rewrite(exp).expand()
|
641 |
+
|
642 |
+
for term in Add.make_args(x1):
|
643 |
+
if not term.has(t):
|
644 |
+
xm.append({'k': term, 'a': 0, re: 0, im: 0})
|
645 |
+
continue
|
646 |
+
term = term.powsimp(combine='exp')
|
647 |
+
if (r := term.match(p*exp(m))) is not None:
|
648 |
+
if (mp := r[m].as_poly(t)) is not None:
|
649 |
+
mc = mp.all_coeffs()
|
650 |
+
if len(mc) == 2:
|
651 |
+
xm.append({
|
652 |
+
'k': r[p]*exp(mc[1]), 'a': mc[0],
|
653 |
+
re: re(mc[0]), im: im(mc[0])})
|
654 |
+
else:
|
655 |
+
xn.append(term)
|
656 |
+
else:
|
657 |
+
xn.append(term)
|
658 |
+
else:
|
659 |
+
xn.append(term)
|
660 |
+
return xm, xn
|
661 |
+
|
662 |
+
|
663 |
+
def _laplace_trig_ltex(xm, t, s):
|
664 |
+
"""
|
665 |
+
Helper function for `_laplace_rule_trig`. This function takes the list of
|
666 |
+
exponentials `xm` from `_laplace_trig_expsum` and simplifies complex
|
667 |
+
conjugate and real symmetric poles. It returns the result as a sum and
|
668 |
+
the convergence plane.
|
669 |
+
"""
|
670 |
+
results = []
|
671 |
+
planes = []
|
672 |
+
|
673 |
+
def _simpc(coeffs):
|
674 |
+
nc = coeffs.copy()
|
675 |
+
for k in range(len(nc)):
|
676 |
+
ri = nc[k].as_real_imag()
|
677 |
+
if ri[0].has(im):
|
678 |
+
nc[k] = nc[k].rewrite(cos)
|
679 |
+
else:
|
680 |
+
nc[k] = (ri[0] + I*ri[1]).rewrite(cos)
|
681 |
+
return nc
|
682 |
+
|
683 |
+
def _quadpole(t1, k1, k2, k3, s):
|
684 |
+
a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im]
|
685 |
+
nc = [
|
686 |
+
k0 + k1 + k2 + k3,
|
687 |
+
a*(k0 + k1 - k2 - k3) - 2*I*a_i*k1 + 2*I*a_i*k2,
|
688 |
+
(
|
689 |
+
a**2*(-k0 - k1 - k2 - k3) +
|
690 |
+
a*(4*I*a_i*k0 + 4*I*a_i*k3) +
|
691 |
+
4*a_i**2*k0 + 4*a_i**2*k3),
|
692 |
+
(
|
693 |
+
a**3*(-k0 - k1 + k2 + k3) +
|
694 |
+
a**2*(4*I*a_i*k0 + 2*I*a_i*k1 - 2*I*a_i*k2 - 4*I*a_i*k3) +
|
695 |
+
a*(4*a_i**2*k0 - 4*a_i**2*k3))
|
696 |
+
]
|
697 |
+
dc = [
|
698 |
+
S.One, S.Zero, 2*a_i**2 - 2*a_r**2,
|
699 |
+
S.Zero, a_i**4 + 2*a_i**2*a_r**2 + a_r**4]
|
700 |
+
n = Add(
|
701 |
+
*[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])])
|
702 |
+
d = Add(
|
703 |
+
*[x*s**y for x, y in zip(dc, range(len(dc))[::-1])])
|
704 |
+
debugf(' quadpole: (%s) / (%s)', (n, d))
|
705 |
+
return n/d
|
706 |
+
|
707 |
+
def _ccpole(t1, k1, s):
|
708 |
+
a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im]
|
709 |
+
nc = [k0 + k1, -a*k0 - a*k1 + 2*I*a_i*k0]
|
710 |
+
dc = [S.One, -2*a_r, a_i**2 + a_r**2]
|
711 |
+
n = Add(
|
712 |
+
*[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])])
|
713 |
+
d = Add(
|
714 |
+
*[x*s**y for x, y in zip(dc, range(len(dc))[::-1])])
|
715 |
+
debugf(' ccpole: (%s) / (%s)', (n, d))
|
716 |
+
return n/d
|
717 |
+
|
718 |
+
def _rspole(t1, k2, s):
|
719 |
+
a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im]
|
720 |
+
nc = [k0 + k2, a*k0 - a*k2 - 2*I*a_i*k0]
|
721 |
+
dc = [S.One, -2*I*a_i, -a_i**2 - a_r**2]
|
722 |
+
n = Add(
|
723 |
+
*[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])])
|
724 |
+
d = Add(
|
725 |
+
*[x*s**y for x, y in zip(dc, range(len(dc))[::-1])])
|
726 |
+
debugf(' rspole: (%s) / (%s)', (n, d))
|
727 |
+
return n/d
|
728 |
+
|
729 |
+
def _sypole(t1, k3, s):
|
730 |
+
a, k0 = t1['a'], t1['k']
|
731 |
+
nc = [k0 + k3, a*(k0 - k3)]
|
732 |
+
dc = [S.One, S.Zero, -a**2]
|
733 |
+
n = Add(
|
734 |
+
*[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])])
|
735 |
+
d = Add(
|
736 |
+
*[x*s**y for x, y in zip(dc, range(len(dc))[::-1])])
|
737 |
+
debugf(' sypole: (%s) / (%s)', (n, d))
|
738 |
+
return n/d
|
739 |
+
|
740 |
+
def _simplepole(t1, s):
|
741 |
+
a, k0 = t1['a'], t1['k']
|
742 |
+
n = k0
|
743 |
+
d = s - a
|
744 |
+
debugf(' simplepole: (%s) / (%s)', (n, d))
|
745 |
+
return n/d
|
746 |
+
|
747 |
+
while len(xm) > 0:
|
748 |
+
t1 = xm.pop()
|
749 |
+
i_imagsym = None
|
750 |
+
i_realsym = None
|
751 |
+
i_pointsym = None
|
752 |
+
# The following code checks all remaining poles. If t1 is a pole at
|
753 |
+
# a+b*I, then we check for a-b*I, -a+b*I, and -a-b*I, and
|
754 |
+
# assign the respective indices to i_imagsym, i_realsym, i_pointsym.
|
755 |
+
# -a-b*I / i_pointsym only applies if both a and b are != 0.
|
756 |
+
for i in range(len(xm)):
|
757 |
+
real_eq = t1[re] == xm[i][re]
|
758 |
+
realsym = t1[re] == -xm[i][re]
|
759 |
+
imag_eq = t1[im] == xm[i][im]
|
760 |
+
imagsym = t1[im] == -xm[i][im]
|
761 |
+
if realsym and imagsym and t1[re] != 0 and t1[im] != 0:
|
762 |
+
i_pointsym = i
|
763 |
+
elif realsym and imag_eq and t1[re] != 0:
|
764 |
+
i_realsym = i
|
765 |
+
elif real_eq and imagsym and t1[im] != 0:
|
766 |
+
i_imagsym = i
|
767 |
+
|
768 |
+
# The next part looks for four possible pole constellations:
|
769 |
+
# quad: a+b*I, a-b*I, -a+b*I, -a-b*I
|
770 |
+
# cc: a+b*I, a-b*I (a may be zero)
|
771 |
+
# quad: a+b*I, -a+b*I (b may be zero)
|
772 |
+
# point: a+b*I, -a-b*I (a!=0 and b!=0 is needed, but that has been
|
773 |
+
# asserted when finding i_pointsym above.)
|
774 |
+
# If none apply, then t1 is a simple pole.
|
775 |
+
if (
|
776 |
+
i_imagsym is not None and i_realsym is not None
|
777 |
+
and i_pointsym is not None):
|
778 |
+
results.append(
|
779 |
+
_quadpole(t1,
|
780 |
+
xm[i_imagsym]['k'], xm[i_realsym]['k'],
|
781 |
+
xm[i_pointsym]['k'], s))
|
782 |
+
planes.append(Abs(re(t1['a'])))
|
783 |
+
# The three additional poles have now been used; to pop them
|
784 |
+
# easily we have to do it from the back.
|
785 |
+
indices_to_pop = [i_imagsym, i_realsym, i_pointsym]
|
786 |
+
indices_to_pop.sort(reverse=True)
|
787 |
+
for i in indices_to_pop:
|
788 |
+
xm.pop(i)
|
789 |
+
elif i_imagsym is not None:
|
790 |
+
results.append(_ccpole(t1, xm[i_imagsym]['k'], s))
|
791 |
+
planes.append(t1[re])
|
792 |
+
xm.pop(i_imagsym)
|
793 |
+
elif i_realsym is not None:
|
794 |
+
results.append(_rspole(t1, xm[i_realsym]['k'], s))
|
795 |
+
planes.append(Abs(t1[re]))
|
796 |
+
xm.pop(i_realsym)
|
797 |
+
elif i_pointsym is not None:
|
798 |
+
results.append(_sypole(t1, xm[i_pointsym]['k'], s))
|
799 |
+
planes.append(Abs(t1[re]))
|
800 |
+
xm.pop(i_pointsym)
|
801 |
+
else:
|
802 |
+
results.append(_simplepole(t1, s))
|
803 |
+
planes.append(t1[re])
|
804 |
+
|
805 |
+
return Add(*results), Max(*planes)
|
806 |
+
|
807 |
+
|
808 |
+
def _laplace_rule_trig(fn, t_, s, doit=True, **hints):
|
809 |
+
"""
|
810 |
+
This rule covers trigonometric factors by splitting everything into a
|
811 |
+
sum of exponential functions and collecting complex conjugate poles and
|
812 |
+
real symmetric poles.
|
813 |
+
"""
|
814 |
+
t = Dummy('t', real=True)
|
815 |
+
|
816 |
+
if not fn.has(sin, cos, sinh, cosh):
|
817 |
+
return None
|
818 |
+
|
819 |
+
debugf('_laplace_rule_trig: (%s, %s, %s)', (fn, t_, s))
|
820 |
+
|
821 |
+
f, g = _laplace_trig_split(fn.subs(t_, t))
|
822 |
+
debugf(' f = %s\n g = %s', (f, g))
|
823 |
+
|
824 |
+
xm, xn = _laplace_trig_expsum(f, t)
|
825 |
+
debugf(' xm = %s\n xn = %s', (xm, xn))
|
826 |
+
|
827 |
+
if len(xn) > 0:
|
828 |
+
# not implemented yet
|
829 |
+
debug(' --> xn is not empty; giving up.')
|
830 |
+
return None
|
831 |
+
|
832 |
+
if not g.has(t):
|
833 |
+
r, p = _laplace_trig_ltex(xm, t, s)
|
834 |
+
return g*r, p, S.true
|
835 |
+
else:
|
836 |
+
# Just transform `g` and make frequency-shifted copies
|
837 |
+
planes = []
|
838 |
+
results = []
|
839 |
+
G, G_plane, G_cond = _laplace_transform(g, t, s)
|
840 |
+
for x1 in xm:
|
841 |
+
results.append(x1['k']*G.subs(s, s-x1['a']))
|
842 |
+
planes.append(G_plane+re(x1['a']))
|
843 |
+
return Add(*results).subs(t, t_), Max(*planes), G_cond
|
844 |
+
|
845 |
+
|
846 |
+
def _laplace_rule_diff(f, t, s, doit=True, **hints):
|
847 |
+
"""
|
848 |
+
This function looks for derivatives in the time domain and replaces it
|
849 |
+
by factors of `s` and initial conditions in the frequency domain. For
|
850 |
+
example, if it gets ``(diff(f(t), t), t, s)``, it will compute
|
851 |
+
``s*LaplaceTransform(f(t), t, s) - f(0)``.
|
852 |
+
"""
|
853 |
+
|
854 |
+
a = Wild('a', exclude=[t])
|
855 |
+
n = Wild('n', exclude=[t])
|
856 |
+
g = WildFunction('g')
|
857 |
+
ma1 = f.match(a*Derivative(g, (t, n)))
|
858 |
+
if ma1 and ma1[n].is_integer:
|
859 |
+
m = [z.has(t) for z in ma1[g].args]
|
860 |
+
if sum(m) == 1:
|
861 |
+
debug('_laplace_apply_rules match:')
|
862 |
+
debugf(' f, n: %s, %s', (f, ma1[n]))
|
863 |
+
debug(' rule: time derivative (4.1.8)')
|
864 |
+
d = []
|
865 |
+
for k in range(ma1[n]):
|
866 |
+
if k == 0:
|
867 |
+
y = ma1[g].subs(t, 0)
|
868 |
+
else:
|
869 |
+
y = Derivative(ma1[g], (t, k)).subs(t, 0)
|
870 |
+
d.append(s**(ma1[n]-k-1)*y)
|
871 |
+
r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False)
|
872 |
+
return (ma1[a]*(s**ma1[n]*r - Add(*d)), pr, cr)
|
873 |
+
return None
|
874 |
+
|
875 |
+
|
876 |
+
def _laplace_rule_sdiff(f, t, s, doit=True, **hints):
|
877 |
+
"""
|
878 |
+
This function looks for multiplications with polynoimials in `t` as they
|
879 |
+
correspond to differentiation in the frequency domain. For example, if it
|
880 |
+
gets ``(t*f(t), t, s)``, it will compute
|
881 |
+
``-Derivative(LaplaceTransform(f(t), t, s), s)``.
|
882 |
+
"""
|
883 |
+
|
884 |
+
if f.is_Mul:
|
885 |
+
pfac = [1]
|
886 |
+
ofac = [1]
|
887 |
+
for fac in Mul.make_args(f):
|
888 |
+
if fac.is_polynomial(t):
|
889 |
+
pfac.append(fac)
|
890 |
+
else:
|
891 |
+
ofac.append(fac)
|
892 |
+
if len(pfac) > 1:
|
893 |
+
pex = prod(pfac)
|
894 |
+
pc = Poly(pex, t).all_coeffs()
|
895 |
+
N = len(pc)
|
896 |
+
if N > 1:
|
897 |
+
debug('_laplace_apply_rules match:')
|
898 |
+
debugf(' f, n: %s, %s', (f, pfac))
|
899 |
+
debug(' rule: frequency derivative (4.1.6)')
|
900 |
+
oex = prod(ofac)
|
901 |
+
r_, p_, c_ = _laplace_transform(oex, t, s, simplify=False)
|
902 |
+
deri = [r_]
|
903 |
+
d1 = False
|
904 |
+
try:
|
905 |
+
d1 = -diff(deri[-1], s)
|
906 |
+
except ValueError:
|
907 |
+
d1 = False
|
908 |
+
if r_.has(LaplaceTransform):
|
909 |
+
for k in range(N-1):
|
910 |
+
deri.append((-1)**(k+1)*Derivative(r_, s, k+1))
|
911 |
+
else:
|
912 |
+
if d1:
|
913 |
+
deri.append(d1)
|
914 |
+
for k in range(N-2):
|
915 |
+
deri.append(-diff(deri[-1], s))
|
916 |
+
if d1:
|
917 |
+
r = Add(*[pc[N-n-1]*deri[n] for n in range(N)])
|
918 |
+
return (r, p_, c_)
|
919 |
+
return None
|
920 |
+
|
921 |
+
|
922 |
+
def _laplace_expand(f, t, s, doit=True, **hints):
|
923 |
+
"""
|
924 |
+
This function tries to expand its argument with successively stronger
|
925 |
+
methods: first it will expand on the top level, then it will expand any
|
926 |
+
multiplications in depth, then it will try all avilable expansion methods,
|
927 |
+
and finally it will try to expand trigonometric functions.
|
928 |
+
|
929 |
+
If it can expand, it will then compute the Laplace transform of the
|
930 |
+
expanded term.
|
931 |
+
"""
|
932 |
+
|
933 |
+
if f.is_Add:
|
934 |
+
return None
|
935 |
+
r = expand(f, deep=False)
|
936 |
+
if r.is_Add:
|
937 |
+
return _laplace_transform(r, t, s, simplify=False)
|
938 |
+
r = expand_mul(f)
|
939 |
+
if r.is_Add:
|
940 |
+
return _laplace_transform(r, t, s, simplify=False)
|
941 |
+
r = expand(f)
|
942 |
+
if r.is_Add:
|
943 |
+
return _laplace_transform(r, t, s, simplify=False)
|
944 |
+
if r != f:
|
945 |
+
return _laplace_transform(r, t, s, simplify=False)
|
946 |
+
r = expand(expand_trig(f))
|
947 |
+
if r.is_Add:
|
948 |
+
return _laplace_transform(r, t, s, simplify=False)
|
949 |
+
return None
|
950 |
+
|
951 |
+
|
952 |
+
def _laplace_apply_prog_rules(f, t, s):
|
953 |
+
"""
|
954 |
+
This function applies all program rules and returns the result if one
|
955 |
+
of them gives a result.
|
956 |
+
"""
|
957 |
+
|
958 |
+
prog_rules = [_laplace_rule_heaviside, _laplace_rule_delta,
|
959 |
+
_laplace_rule_timescale, _laplace_rule_exp,
|
960 |
+
_laplace_rule_trig,
|
961 |
+
_laplace_rule_diff, _laplace_rule_sdiff]
|
962 |
+
|
963 |
+
for p_rule in prog_rules:
|
964 |
+
if (L := p_rule(f, t, s)) is not None:
|
965 |
+
return L
|
966 |
+
return None
|
967 |
+
|
968 |
+
|
969 |
+
def _laplace_apply_simple_rules(f, t, s):
|
970 |
+
"""
|
971 |
+
This function applies all simple rules and returns the result if one
|
972 |
+
of them gives a result.
|
973 |
+
"""
|
974 |
+
simple_rules, t_, s_ = _laplace_build_rules()
|
975 |
+
prep_old = ''
|
976 |
+
prep_f = ''
|
977 |
+
for t_dom, s_dom, check, plane, prep in simple_rules:
|
978 |
+
if prep_old != prep:
|
979 |
+
prep_f = prep(f.subs({t: t_}))
|
980 |
+
prep_old = prep
|
981 |
+
ma = prep_f.match(t_dom)
|
982 |
+
if ma:
|
983 |
+
try:
|
984 |
+
c = check.xreplace(ma)
|
985 |
+
except TypeError:
|
986 |
+
# This may happen if the time function has imaginary
|
987 |
+
# numbers in it. Then we give up.
|
988 |
+
continue
|
989 |
+
if c == S.true:
|
990 |
+
debug('_laplace_apply_simple_rules match:')
|
991 |
+
debugf(' f: %s', (f,))
|
992 |
+
debugf(' rule: %s o---o %s', (t_dom, s_dom))
|
993 |
+
debugf(' match: %s', (ma, ))
|
994 |
+
return (s_dom.xreplace(ma).subs({s_: s}),
|
995 |
+
plane.xreplace(ma), S.true)
|
996 |
+
return None
|
997 |
+
|
998 |
+
|
999 |
+
def _laplace_transform(fn, t_, s_, simplify=True):
|
1000 |
+
"""
|
1001 |
+
Front-end function of the Laplace transform. It tries to apply all known
|
1002 |
+
rules recursively, and if everything else fails, it tries to integrate.
|
1003 |
+
"""
|
1004 |
+
debugf('[LT _l_t] (%s, %s, %s)', (fn, t_, s_))
|
1005 |
+
|
1006 |
+
terms = Add.make_args(fn)
|
1007 |
+
terms_s = []
|
1008 |
+
planes = []
|
1009 |
+
conditions = []
|
1010 |
+
for ff in terms:
|
1011 |
+
k, ft = ff.as_independent(t_, as_Add=False)
|
1012 |
+
if (r := _laplace_apply_simple_rules(ft, t_, s_)) is not None:
|
1013 |
+
pass
|
1014 |
+
elif (r := _laplace_apply_prog_rules(ft, t_, s_)) is not None:
|
1015 |
+
pass
|
1016 |
+
elif (r := _laplace_expand(ft, t_, s_)) is not None:
|
1017 |
+
pass
|
1018 |
+
elif any(undef.has(t_) for undef in ft.atoms(AppliedUndef)):
|
1019 |
+
# If there are undefined functions f(t) then integration is
|
1020 |
+
# unlikely to do anything useful so we skip it and given an
|
1021 |
+
# unevaluated LaplaceTransform.
|
1022 |
+
r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True)
|
1023 |
+
elif (r := _laplace_transform_integration(
|
1024 |
+
ft, t_, s_, simplify=simplify)) is not None:
|
1025 |
+
pass
|
1026 |
+
else:
|
1027 |
+
r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True)
|
1028 |
+
(ri_, pi_, ci_) = r
|
1029 |
+
terms_s.append(k*ri_)
|
1030 |
+
planes.append(pi_)
|
1031 |
+
conditions.append(ci_)
|
1032 |
+
|
1033 |
+
result = Add(*terms_s)
|
1034 |
+
if simplify:
|
1035 |
+
result = result.simplify(doit=False)
|
1036 |
+
plane = Max(*planes)
|
1037 |
+
condition = And(*conditions)
|
1038 |
+
|
1039 |
+
return result, plane, condition
|
1040 |
+
|
1041 |
+
|
1042 |
+
class LaplaceTransform(IntegralTransform):
|
1043 |
+
"""
|
1044 |
+
Class representing unevaluated Laplace transforms.
|
1045 |
+
|
1046 |
+
For usage of this class, see the :class:`IntegralTransform` docstring.
|
1047 |
+
|
1048 |
+
For how to compute Laplace transforms, see the :func:`laplace_transform`
|
1049 |
+
docstring.
|
1050 |
+
|
1051 |
+
If this is called with ``.doit()``, it returns the Laplace transform as an
|
1052 |
+
expression. If it is called with ``.doit(noconds=False)``, it returns a
|
1053 |
+
tuple containing the same expression, a convergence plane, and conditions.
|
1054 |
+
"""
|
1055 |
+
|
1056 |
+
_name = 'Laplace'
|
1057 |
+
|
1058 |
+
def _compute_transform(self, f, t, s, **hints):
|
1059 |
+
_simplify = hints.get('simplify', False)
|
1060 |
+
LT = _laplace_transform_integration(f, t, s, simplify=_simplify)
|
1061 |
+
return LT
|
1062 |
+
|
1063 |
+
def _as_integral(self, f, t, s):
|
1064 |
+
return Integral(f*exp(-s*t), (t, S.Zero, S.Infinity))
|
1065 |
+
|
1066 |
+
def _collapse_extra(self, extra):
|
1067 |
+
conds = []
|
1068 |
+
planes = []
|
1069 |
+
for plane, cond in extra:
|
1070 |
+
conds.append(cond)
|
1071 |
+
planes.append(plane)
|
1072 |
+
cond = And(*conds)
|
1073 |
+
plane = Max(*planes)
|
1074 |
+
if cond == S.false:
|
1075 |
+
raise IntegralTransformError(
|
1076 |
+
'Laplace', None, 'No combined convergence.')
|
1077 |
+
return plane, cond
|
1078 |
+
|
1079 |
+
def doit(self, **hints):
|
1080 |
+
"""
|
1081 |
+
Try to evaluate the transform in closed form.
|
1082 |
+
|
1083 |
+
Explanation
|
1084 |
+
===========
|
1085 |
+
|
1086 |
+
Standard hints are the following:
|
1087 |
+
- ``noconds``: if True, do not return convergence conditions. The
|
1088 |
+
default setting is `True`.
|
1089 |
+
- ``simplify``: if True, it simplifies the final result. The
|
1090 |
+
default setting is `False`.
|
1091 |
+
"""
|
1092 |
+
_noconds = hints.get('noconds', True)
|
1093 |
+
_simplify = hints.get('simplify', False)
|
1094 |
+
|
1095 |
+
debugf('[LT doit] (%s, %s, %s)', (self.function,
|
1096 |
+
self.function_variable,
|
1097 |
+
self.transform_variable))
|
1098 |
+
|
1099 |
+
t_ = self.function_variable
|
1100 |
+
s_ = self.transform_variable
|
1101 |
+
fn = self.function
|
1102 |
+
|
1103 |
+
r = _laplace_transform(fn, t_, s_, simplify=_simplify)
|
1104 |
+
|
1105 |
+
if _noconds:
|
1106 |
+
return r[0]
|
1107 |
+
else:
|
1108 |
+
return r
|
1109 |
+
|
1110 |
+
|
1111 |
+
def laplace_transform(f, t, s, legacy_matrix=True, **hints):
|
1112 |
+
r"""
|
1113 |
+
Compute the Laplace Transform `F(s)` of `f(t)`,
|
1114 |
+
|
1115 |
+
.. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t.
|
1116 |
+
|
1117 |
+
Explanation
|
1118 |
+
===========
|
1119 |
+
|
1120 |
+
For all sensible functions, this converges absolutely in a
|
1121 |
+
half-plane
|
1122 |
+
|
1123 |
+
.. math :: a < \operatorname{Re}(s)
|
1124 |
+
|
1125 |
+
This function returns ``(F, a, cond)`` where ``F`` is the Laplace
|
1126 |
+
transform of ``f``, `a` is the half-plane of convergence, and `cond` are
|
1127 |
+
auxiliary convergence conditions.
|
1128 |
+
|
1129 |
+
The implementation is rule-based, and if you are interested in which
|
1130 |
+
rules are applied, and whether integration is attempted, you can switch
|
1131 |
+
debug information on by setting ``sympy.SYMPY_DEBUG=True``. The numbers
|
1132 |
+
of the rules in the debug information (and the code) refer to Bateman's
|
1133 |
+
Tables of Integral Transforms [1].
|
1134 |
+
|
1135 |
+
The lower bound is `0-`, meaning that this bound should be approached
|
1136 |
+
from the lower side. This is only necessary if distributions are involved.
|
1137 |
+
At present, it is only done if `f(t)` contains ``DiracDelta``, in which
|
1138 |
+
case the Laplace transform is computed implicitly as
|
1139 |
+
|
1140 |
+
.. math ::
|
1141 |
+
F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st}
|
1142 |
+
f(t) \mathrm{d}t
|
1143 |
+
|
1144 |
+
by applying rules.
|
1145 |
+
|
1146 |
+
If the Laplace transform cannot be fully computed in closed form, this
|
1147 |
+
function returns expressions containing unevaluated
|
1148 |
+
:class:`LaplaceTransform` objects.
|
1149 |
+
|
1150 |
+
For a description of possible hints, refer to the docstring of
|
1151 |
+
:func:`sympy.integrals.transforms.IntegralTransform.doit`. If
|
1152 |
+
``noconds=True``, only `F` will be returned (i.e. not ``cond``, and also
|
1153 |
+
not the plane ``a``).
|
1154 |
+
|
1155 |
+
.. deprecated:: 1.9
|
1156 |
+
Legacy behavior for matrices where ``laplace_transform`` with
|
1157 |
+
``noconds=False`` (the default) returns a Matrix whose elements are
|
1158 |
+
tuples. The behavior of ``laplace_transform`` for matrices will change
|
1159 |
+
in a future release of SymPy to return a tuple of the transformed
|
1160 |
+
Matrix and the convergence conditions for the matrix as a whole. Use
|
1161 |
+
``legacy_matrix=False`` to enable the new behavior.
|
1162 |
+
|
1163 |
+
Examples
|
1164 |
+
========
|
1165 |
+
|
1166 |
+
>>> from sympy import DiracDelta, exp, laplace_transform
|
1167 |
+
>>> from sympy.abc import t, s, a
|
1168 |
+
>>> laplace_transform(t**4, t, s)
|
1169 |
+
(24/s**5, 0, True)
|
1170 |
+
>>> laplace_transform(t**a, t, s)
|
1171 |
+
(gamma(a + 1)/(s*s**a), 0, re(a) > -1)
|
1172 |
+
>>> laplace_transform(DiracDelta(t)-a*exp(-a*t), t, s, simplify=True)
|
1173 |
+
(s/(a + s), -re(a), True)
|
1174 |
+
|
1175 |
+
References
|
1176 |
+
==========
|
1177 |
+
|
1178 |
+
.. [1] Erdelyi, A. (ed.), Tables of Integral Transforms, Volume 1,
|
1179 |
+
Bateman Manuscript Prooject, McGraw-Hill (1954), available:
|
1180 |
+
https://resolver.caltech.edu/CaltechAUTHORS:20140123-101456353
|
1181 |
+
|
1182 |
+
See Also
|
1183 |
+
========
|
1184 |
+
|
1185 |
+
inverse_laplace_transform, mellin_transform, fourier_transform
|
1186 |
+
hankel_transform, inverse_hankel_transform
|
1187 |
+
|
1188 |
+
"""
|
1189 |
+
|
1190 |
+
_noconds = hints.get('noconds', False)
|
1191 |
+
_simplify = hints.get('simplify', False)
|
1192 |
+
|
1193 |
+
if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'):
|
1194 |
+
|
1195 |
+
conds = not hints.get('noconds', False)
|
1196 |
+
|
1197 |
+
if conds and legacy_matrix:
|
1198 |
+
adt = 'deprecated-laplace-transform-matrix'
|
1199 |
+
sympy_deprecation_warning(
|
1200 |
+
"""
|
1201 |
+
Calling laplace_transform() on a Matrix with noconds=False (the default) is
|
1202 |
+
deprecated. Either noconds=True or use legacy_matrix=False to get the new
|
1203 |
+
behavior.
|
1204 |
+
""",
|
1205 |
+
deprecated_since_version='1.9',
|
1206 |
+
active_deprecations_target=adt,
|
1207 |
+
)
|
1208 |
+
# Temporarily disable the deprecation warning for non-Expr objects
|
1209 |
+
# in Matrix
|
1210 |
+
with ignore_warnings(SymPyDeprecationWarning):
|
1211 |
+
return f.applyfunc(
|
1212 |
+
lambda fij: laplace_transform(fij, t, s, **hints))
|
1213 |
+
else:
|
1214 |
+
elements_trans = [laplace_transform(
|
1215 |
+
fij, t, s, **hints) for fij in f]
|
1216 |
+
if conds:
|
1217 |
+
elements, avals, conditions = zip(*elements_trans)
|
1218 |
+
f_laplace = type(f)(*f.shape, elements)
|
1219 |
+
return f_laplace, Max(*avals), And(*conditions)
|
1220 |
+
else:
|
1221 |
+
return type(f)(*f.shape, elements_trans)
|
1222 |
+
|
1223 |
+
LT = LaplaceTransform(f, t, s).doit(noconds=False, simplify=_simplify)
|
1224 |
+
|
1225 |
+
if not _noconds:
|
1226 |
+
return LT
|
1227 |
+
else:
|
1228 |
+
return LT[0]
|
1229 |
+
|
1230 |
+
|
1231 |
+
def _inverse_laplace_transform_integration(F, s, t_, plane, simplify=True):
|
1232 |
+
""" The backend function for inverse Laplace transforms. """
|
1233 |
+
from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp
|
1234 |
+
from sympy.integrals.transforms import inverse_mellin_transform
|
1235 |
+
|
1236 |
+
# There are two strategies we can try:
|
1237 |
+
# 1) Use inverse mellin transform, related by a simple change of variables.
|
1238 |
+
# 2) Use the inversion integral.
|
1239 |
+
|
1240 |
+
t = Dummy('t', real=True)
|
1241 |
+
|
1242 |
+
def pw_simp(*args):
|
1243 |
+
""" Simplify a piecewise expression from hyperexpand. """
|
1244 |
+
# XXX we break modularity here!
|
1245 |
+
if len(args) != 3:
|
1246 |
+
return Piecewise(*args)
|
1247 |
+
arg = args[2].args[0].argument
|
1248 |
+
coeff, exponent = _get_coeff_exp(arg, t)
|
1249 |
+
e1 = args[0].args[0]
|
1250 |
+
e2 = args[1].args[0]
|
1251 |
+
return (
|
1252 |
+
Heaviside(1/Abs(coeff) - t**exponent)*e1 +
|
1253 |
+
Heaviside(t**exponent - 1/Abs(coeff))*e2)
|
1254 |
+
|
1255 |
+
if F.is_rational_function(s):
|
1256 |
+
F = F.apart(s)
|
1257 |
+
|
1258 |
+
if F.is_Add:
|
1259 |
+
f = Add(
|
1260 |
+
*[_inverse_laplace_transform_integration(X, s, t, plane, simplify)
|
1261 |
+
for X in F.args])
|
1262 |
+
return _simplify(f.subs(t, t_), simplify), True
|
1263 |
+
|
1264 |
+
try:
|
1265 |
+
f, cond = inverse_mellin_transform(F, s, exp(-t), (None, S.Infinity),
|
1266 |
+
needeval=True, noconds=False)
|
1267 |
+
except IntegralTransformError:
|
1268 |
+
f = None
|
1269 |
+
if f is None:
|
1270 |
+
f = meijerint_inversion(F, s, t)
|
1271 |
+
if f is None:
|
1272 |
+
return None
|
1273 |
+
if f.is_Piecewise:
|
1274 |
+
f, cond = f.args[0]
|
1275 |
+
if f.has(Integral):
|
1276 |
+
return None
|
1277 |
+
else:
|
1278 |
+
cond = S.true
|
1279 |
+
f = f.replace(Piecewise, pw_simp)
|
1280 |
+
|
1281 |
+
if f.is_Piecewise:
|
1282 |
+
# many of the functions called below can't work with piecewise
|
1283 |
+
# (b/c it has a bool in args)
|
1284 |
+
return f.subs(t, t_), cond
|
1285 |
+
|
1286 |
+
u = Dummy('u')
|
1287 |
+
|
1288 |
+
def simp_heaviside(arg, H0=S.Half):
|
1289 |
+
a = arg.subs(exp(-t), u)
|
1290 |
+
if a.has(t):
|
1291 |
+
return Heaviside(arg, H0)
|
1292 |
+
from sympy.solvers.inequalities import _solve_inequality
|
1293 |
+
rel = _solve_inequality(a > 0, u)
|
1294 |
+
if rel.lts == u:
|
1295 |
+
k = log(rel.gts)
|
1296 |
+
return Heaviside(t + k, H0)
|
1297 |
+
else:
|
1298 |
+
k = log(rel.lts)
|
1299 |
+
return Heaviside(-(t + k), H0)
|
1300 |
+
|
1301 |
+
f = f.replace(Heaviside, simp_heaviside)
|
1302 |
+
|
1303 |
+
def simp_exp(arg):
|
1304 |
+
return expand_complex(exp(arg))
|
1305 |
+
|
1306 |
+
f = f.replace(exp, simp_exp)
|
1307 |
+
|
1308 |
+
# TODO it would be nice to fix cosh and sinh ... simplify messes these
|
1309 |
+
# exponentials up
|
1310 |
+
|
1311 |
+
return _simplify(f.subs(t, t_), simplify), cond
|
1312 |
+
|
1313 |
+
|
1314 |
+
def _complete_the_square_in_denom(f, s):
|
1315 |
+
from sympy.simplify.radsimp import fraction
|
1316 |
+
[n, d] = fraction(f)
|
1317 |
+
if d.is_polynomial(s):
|
1318 |
+
cf = d.as_poly(s).all_coeffs()
|
1319 |
+
if len(cf) == 3:
|
1320 |
+
a, b, c = cf
|
1321 |
+
d = a*((s+b/(2*a))**2+c/a-(b/(2*a))**2)
|
1322 |
+
return n/d
|
1323 |
+
|
1324 |
+
|
1325 |
+
@cacheit
|
1326 |
+
def _inverse_laplace_build_rules():
|
1327 |
+
"""
|
1328 |
+
This is an internal helper function that returns the table of inverse
|
1329 |
+
Laplace transform rules in terms of the time variable `t` and the
|
1330 |
+
frequency variable `s`. It is used by `_inverse_laplace_apply_rules`.
|
1331 |
+
"""
|
1332 |
+
s = Dummy('s')
|
1333 |
+
t = Dummy('t')
|
1334 |
+
a = Wild('a', exclude=[s])
|
1335 |
+
b = Wild('b', exclude=[s])
|
1336 |
+
c = Wild('c', exclude=[s])
|
1337 |
+
|
1338 |
+
debug('_inverse_laplace_build_rules is building rules')
|
1339 |
+
|
1340 |
+
def _frac(f, s):
|
1341 |
+
try:
|
1342 |
+
return f.factor(s)
|
1343 |
+
except PolynomialError:
|
1344 |
+
return f
|
1345 |
+
|
1346 |
+
def same(f): return f
|
1347 |
+
# This list is sorted according to the prep function needed.
|
1348 |
+
_ILT_rules = [
|
1349 |
+
(a/s, a, S.true, same, 1),
|
1350 |
+
(b*(s+a)**(-c), t**(c-1)*exp(-a*t)/gamma(c), c > 0, same, 1),
|
1351 |
+
(1/(s**2+a**2)**2, (sin(a*t) - a*t*cos(a*t))/(2*a**3),
|
1352 |
+
S.true, same, 1),
|
1353 |
+
# The next two rules must be there in that order. For the second
|
1354 |
+
# one, the condition would be a != 0 or, respectively, to take the
|
1355 |
+
# limit a -> 0 after the transform if a == 0. It is much simpler if
|
1356 |
+
# the case a == 0 has its own rule.
|
1357 |
+
(1/(s**b), t**(b - 1)/gamma(b), S.true, same, 1),
|
1358 |
+
(1/(s*(s+a)**b), lowergamma(b, a*t)/(a**b*gamma(b)),
|
1359 |
+
S.true, same, 1)
|
1360 |
+
]
|
1361 |
+
return _ILT_rules, s, t
|
1362 |
+
|
1363 |
+
|
1364 |
+
def _inverse_laplace_apply_simple_rules(f, s, t):
|
1365 |
+
"""
|
1366 |
+
Helper function for the class InverseLaplaceTransform.
|
1367 |
+
"""
|
1368 |
+
if f == 1:
|
1369 |
+
debug('_inverse_laplace_apply_simple_rules match:')
|
1370 |
+
debugf(' f: %s', (1,))
|
1371 |
+
debugf(' rule: 1 o---o DiracDelta(%s)', (t,))
|
1372 |
+
return DiracDelta(t), S.true
|
1373 |
+
|
1374 |
+
_ILT_rules, s_, t_ = _inverse_laplace_build_rules()
|
1375 |
+
_prep = ''
|
1376 |
+
fsubs = f.subs({s: s_})
|
1377 |
+
|
1378 |
+
for s_dom, t_dom, check, prep, fac in _ILT_rules:
|
1379 |
+
if _prep != (prep, fac):
|
1380 |
+
_F = prep(fsubs*fac)
|
1381 |
+
_prep = (prep, fac)
|
1382 |
+
ma = _F.match(s_dom)
|
1383 |
+
if ma:
|
1384 |
+
try:
|
1385 |
+
c = check.xreplace(ma)
|
1386 |
+
except TypeError:
|
1387 |
+
continue
|
1388 |
+
if c == S.true:
|
1389 |
+
debug('_inverse_laplace_apply_simple_rules match:')
|
1390 |
+
debugf(' f: %s', (f,))
|
1391 |
+
debugf(' rule: %s o---o %s', (s_dom, t_dom))
|
1392 |
+
debugf(' ma: %s', (ma,))
|
1393 |
+
return Heaviside(t)*t_dom.xreplace(ma).subs({t_: t}), S.true
|
1394 |
+
|
1395 |
+
return None
|
1396 |
+
|
1397 |
+
|
1398 |
+
def _inverse_laplace_time_shift(F, s, t, plane):
|
1399 |
+
"""
|
1400 |
+
Helper function for the class InverseLaplaceTransform.
|
1401 |
+
"""
|
1402 |
+
a = Wild('a', exclude=[s])
|
1403 |
+
g = Wild('g')
|
1404 |
+
|
1405 |
+
if not F.has(s):
|
1406 |
+
return F*DiracDelta(t), S.true
|
1407 |
+
ma1 = F.match(exp(a*s))
|
1408 |
+
if ma1:
|
1409 |
+
if ma1[a].is_negative:
|
1410 |
+
debug('_inverse_laplace_time_shift match:')
|
1411 |
+
debugf(' f: %s', (F,))
|
1412 |
+
debug(' rule: exp(-a*s) o---o DiracDelta(t-a)')
|
1413 |
+
debugf(' ma: %s', (ma1,))
|
1414 |
+
return DiracDelta(t+ma1[a]), S.true
|
1415 |
+
else:
|
1416 |
+
debug('_inverse_laplace_time_shift match: negative time shift')
|
1417 |
+
return InverseLaplaceTransform(F, s, t, plane), S.true
|
1418 |
+
|
1419 |
+
ma1 = F.match(exp(a*s)*g)
|
1420 |
+
if ma1:
|
1421 |
+
if ma1[a].is_negative:
|
1422 |
+
debug('_inverse_laplace_time_shift match:')
|
1423 |
+
debugf(' f: %s', (F,))
|
1424 |
+
debug(' rule: exp(-a*s)*F(s) o---o Heaviside(t-a)*f(t-a)')
|
1425 |
+
debugf(' ma: %s', (ma1,))
|
1426 |
+
return _inverse_laplace_transform(ma1[g], s, t+ma1[a], plane)
|
1427 |
+
else:
|
1428 |
+
debug('_inverse_laplace_time_shift match: negative time shift')
|
1429 |
+
return InverseLaplaceTransform(F, s, t, plane), S.true
|
1430 |
+
return None
|
1431 |
+
|
1432 |
+
|
1433 |
+
def _inverse_laplace_time_diff(F, s, t, plane):
|
1434 |
+
"""
|
1435 |
+
Helper function for the class InverseLaplaceTransform.
|
1436 |
+
"""
|
1437 |
+
n = Wild('n', exclude=[s])
|
1438 |
+
g = Wild('g')
|
1439 |
+
|
1440 |
+
ma1 = F.match(s**n*g)
|
1441 |
+
if ma1 and ma1[n].is_integer and ma1[n].is_positive:
|
1442 |
+
debug('_inverse_laplace_time_diff match:')
|
1443 |
+
debugf(' f: %s', (F,))
|
1444 |
+
debug(' rule: s**n*F(s) o---o diff(f(t), t, n)')
|
1445 |
+
debugf(' ma: %s', (ma1,))
|
1446 |
+
r, c = _inverse_laplace_transform(ma1[g], s, t, plane)
|
1447 |
+
r = r.replace(Heaviside(t), 1)
|
1448 |
+
if r.has(InverseLaplaceTransform):
|
1449 |
+
return diff(r, t, ma1[n]), c
|
1450 |
+
else:
|
1451 |
+
return Heaviside(t)*diff(r, t, ma1[n]), c
|
1452 |
+
return None
|
1453 |
+
|
1454 |
+
|
1455 |
+
def _inverse_laplace_apply_prog_rules(F, s, t, plane):
|
1456 |
+
"""
|
1457 |
+
Helper function for the class InverseLaplaceTransform.
|
1458 |
+
"""
|
1459 |
+
prog_rules = [_inverse_laplace_time_shift,
|
1460 |
+
_inverse_laplace_time_diff]
|
1461 |
+
|
1462 |
+
for p_rule in prog_rules:
|
1463 |
+
if (r := p_rule(F, s, t, plane)) is not None:
|
1464 |
+
return r
|
1465 |
+
return None
|
1466 |
+
|
1467 |
+
|
1468 |
+
def _inverse_laplace_expand(fn, s, t, plane):
|
1469 |
+
"""
|
1470 |
+
Helper function for the class InverseLaplaceTransform.
|
1471 |
+
"""
|
1472 |
+
if fn.is_Add:
|
1473 |
+
return None
|
1474 |
+
r = expand(fn, deep=False)
|
1475 |
+
if r.is_Add:
|
1476 |
+
return _inverse_laplace_transform(r, s, t, plane)
|
1477 |
+
r = expand_mul(fn)
|
1478 |
+
if r.is_Add:
|
1479 |
+
return _inverse_laplace_transform(r, s, t, plane)
|
1480 |
+
r = expand(fn)
|
1481 |
+
if r.is_Add:
|
1482 |
+
return _inverse_laplace_transform(r, s, t, plane)
|
1483 |
+
if fn.is_rational_function(s):
|
1484 |
+
r = fn.apart(s).doit()
|
1485 |
+
if r.is_Add:
|
1486 |
+
return _inverse_laplace_transform(r, s, t, plane)
|
1487 |
+
return None
|
1488 |
+
|
1489 |
+
|
1490 |
+
def _inverse_laplace_rational(fn, s, t, plane, simplify):
|
1491 |
+
"""
|
1492 |
+
Helper function for the class InverseLaplaceTransform.
|
1493 |
+
"""
|
1494 |
+
debugf('[ILT _i_l_r] (%s, %s, %s)', (fn, s, t))
|
1495 |
+
x_ = symbols('x_')
|
1496 |
+
f = fn.apart(s)
|
1497 |
+
terms = Add.make_args(f)
|
1498 |
+
terms_t = []
|
1499 |
+
conditions = [S.true]
|
1500 |
+
for term in terms:
|
1501 |
+
[n, d] = term.as_numer_denom()
|
1502 |
+
dc = d.as_poly(s).all_coeffs()
|
1503 |
+
dc_lead = dc[0]
|
1504 |
+
dc = [x/dc_lead for x in dc]
|
1505 |
+
nc = [x/dc_lead for x in n.as_poly(s).all_coeffs()]
|
1506 |
+
if len(dc) == 1:
|
1507 |
+
r = nc[0]*DiracDelta(t)
|
1508 |
+
terms_t.append(r)
|
1509 |
+
elif len(dc) == 2:
|
1510 |
+
r = nc[0]*exp(-dc[1]*t)
|
1511 |
+
terms_t.append(Heaviside(t)*r)
|
1512 |
+
elif len(dc) == 3:
|
1513 |
+
a = dc[1]/2
|
1514 |
+
b = (dc[2]-a**2).factor()
|
1515 |
+
if len(nc) == 1:
|
1516 |
+
nc = [S.Zero] + nc
|
1517 |
+
l, m = tuple(nc)
|
1518 |
+
if b == 0:
|
1519 |
+
r = (m*t+l*(1-a*t))*exp(-a*t)
|
1520 |
+
else:
|
1521 |
+
hyp = False
|
1522 |
+
if b.is_negative:
|
1523 |
+
b = -b
|
1524 |
+
hyp = True
|
1525 |
+
b2 = list(roots(x_**2-b, x_).keys())[0]
|
1526 |
+
bs = sqrt(b).simplify()
|
1527 |
+
if hyp:
|
1528 |
+
r = (
|
1529 |
+
l*exp(-a*t)*cosh(b2*t) + (m-a*l) /
|
1530 |
+
bs*exp(-a*t)*sinh(bs*t))
|
1531 |
+
else:
|
1532 |
+
r = l*exp(-a*t)*cos(b2*t) + (m-a*l)/bs*exp(-a*t)*sin(bs*t)
|
1533 |
+
terms_t.append(Heaviside(t)*r)
|
1534 |
+
else:
|
1535 |
+
ft, cond = _inverse_laplace_transform(
|
1536 |
+
fn, s, t, plane, simplify=True, dorational=False)
|
1537 |
+
terms_t.append(ft)
|
1538 |
+
conditions.append(cond)
|
1539 |
+
|
1540 |
+
result = Add(*terms_t)
|
1541 |
+
if simplify:
|
1542 |
+
result = result.simplify(doit=False)
|
1543 |
+
debugf('[ILT _i_l_r] returns %s', (result,))
|
1544 |
+
return result, And(*conditions)
|
1545 |
+
|
1546 |
+
|
1547 |
+
def _inverse_laplace_transform(
|
1548 |
+
fn, s_, t_, plane, simplify=True, dorational=True):
|
1549 |
+
"""
|
1550 |
+
Front-end function of the inverse Laplace transform. It tries to apply all
|
1551 |
+
known rules recursively. If everything else fails, it tries to integrate.
|
1552 |
+
"""
|
1553 |
+
terms = Add.make_args(fn)
|
1554 |
+
terms_t = []
|
1555 |
+
conditions = []
|
1556 |
+
|
1557 |
+
debugf('[ILT _i_l_t] (%s, %s, %s)', (fn, s_, t_))
|
1558 |
+
|
1559 |
+
for term in terms:
|
1560 |
+
k, f = term.as_independent(s_, as_Add=False)
|
1561 |
+
if (
|
1562 |
+
dorational and term.is_rational_function(s_) and
|
1563 |
+
(
|
1564 |
+
r := _inverse_laplace_rational(
|
1565 |
+
f, s_, t_, plane, simplify)) is not None):
|
1566 |
+
pass
|
1567 |
+
elif (r := _inverse_laplace_apply_simple_rules(f, s_, t_)) is not None:
|
1568 |
+
pass
|
1569 |
+
elif (r := _inverse_laplace_expand(f, s_, t_, plane)) is not None:
|
1570 |
+
pass
|
1571 |
+
elif (
|
1572 |
+
(r := _inverse_laplace_apply_prog_rules(f, s_, t_, plane))
|
1573 |
+
is not None):
|
1574 |
+
pass
|
1575 |
+
elif any(undef.has(s_) for undef in f.atoms(AppliedUndef)):
|
1576 |
+
# If there are undefined functions f(t) then integration is
|
1577 |
+
# unlikely to do anything useful so we skip it and given an
|
1578 |
+
# unevaluated LaplaceTransform.
|
1579 |
+
r = (InverseLaplaceTransform(f, s_, t_, plane), S.true)
|
1580 |
+
elif (
|
1581 |
+
r := _inverse_laplace_transform_integration(
|
1582 |
+
f, s_, t_, plane, simplify=simplify)) is not None:
|
1583 |
+
pass
|
1584 |
+
else:
|
1585 |
+
r = (InverseLaplaceTransform(f, s_, t_, plane), S.true)
|
1586 |
+
(ri_, ci_) = r
|
1587 |
+
terms_t.append(k*ri_)
|
1588 |
+
conditions.append(ci_)
|
1589 |
+
|
1590 |
+
result = Add(*terms_t)
|
1591 |
+
if simplify:
|
1592 |
+
result = result.simplify(doit=False)
|
1593 |
+
condition = And(*conditions)
|
1594 |
+
|
1595 |
+
return result, condition
|
1596 |
+
|
1597 |
+
|
1598 |
+
class InverseLaplaceTransform(IntegralTransform):
|
1599 |
+
"""
|
1600 |
+
Class representing unevaluated inverse Laplace transforms.
|
1601 |
+
|
1602 |
+
For usage of this class, see the :class:`IntegralTransform` docstring.
|
1603 |
+
|
1604 |
+
For how to compute inverse Laplace transforms, see the
|
1605 |
+
:func:`inverse_laplace_transform` docstring.
|
1606 |
+
"""
|
1607 |
+
|
1608 |
+
_name = 'Inverse Laplace'
|
1609 |
+
_none_sentinel = Dummy('None')
|
1610 |
+
_c = Dummy('c')
|
1611 |
+
|
1612 |
+
def __new__(cls, F, s, x, plane, **opts):
|
1613 |
+
if plane is None:
|
1614 |
+
plane = InverseLaplaceTransform._none_sentinel
|
1615 |
+
return IntegralTransform.__new__(cls, F, s, x, plane, **opts)
|
1616 |
+
|
1617 |
+
@property
|
1618 |
+
def fundamental_plane(self):
|
1619 |
+
plane = self.args[3]
|
1620 |
+
if plane is InverseLaplaceTransform._none_sentinel:
|
1621 |
+
plane = None
|
1622 |
+
return plane
|
1623 |
+
|
1624 |
+
def _compute_transform(self, F, s, t, **hints):
|
1625 |
+
return _inverse_laplace_transform_integration(
|
1626 |
+
F, s, t, self.fundamental_plane, **hints)
|
1627 |
+
|
1628 |
+
def _as_integral(self, F, s, t):
|
1629 |
+
c = self.__class__._c
|
1630 |
+
return (
|
1631 |
+
Integral(exp(s*t)*F, (s, c - S.ImaginaryUnit*S.Infinity,
|
1632 |
+
c + S.ImaginaryUnit*S.Infinity)) /
|
1633 |
+
(2*S.Pi*S.ImaginaryUnit))
|
1634 |
+
|
1635 |
+
def doit(self, **hints):
|
1636 |
+
"""
|
1637 |
+
Try to evaluate the transform in closed form.
|
1638 |
+
|
1639 |
+
Explanation
|
1640 |
+
===========
|
1641 |
+
|
1642 |
+
Standard hints are the following:
|
1643 |
+
- ``noconds``: if True, do not return convergence conditions. The
|
1644 |
+
default setting is `True`.
|
1645 |
+
- ``simplify``: if True, it simplifies the final result. The
|
1646 |
+
default setting is `False`.
|
1647 |
+
"""
|
1648 |
+
_noconds = hints.get('noconds', True)
|
1649 |
+
_simplify = hints.get('simplify', False)
|
1650 |
+
|
1651 |
+
debugf('[ILT doit] (%s, %s, %s)', (self.function,
|
1652 |
+
self.function_variable,
|
1653 |
+
self.transform_variable))
|
1654 |
+
|
1655 |
+
s_ = self.function_variable
|
1656 |
+
t_ = self.transform_variable
|
1657 |
+
fn = self.function
|
1658 |
+
plane = self.fundamental_plane
|
1659 |
+
|
1660 |
+
r = _inverse_laplace_transform(fn, s_, t_, plane, simplify=_simplify)
|
1661 |
+
|
1662 |
+
if _noconds:
|
1663 |
+
return r[0]
|
1664 |
+
else:
|
1665 |
+
return r
|
1666 |
+
|
1667 |
+
|
1668 |
+
def inverse_laplace_transform(F, s, t, plane=None, **hints):
|
1669 |
+
r"""
|
1670 |
+
Compute the inverse Laplace transform of `F(s)`, defined as
|
1671 |
+
|
1672 |
+
.. math ::
|
1673 |
+
f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{st}
|
1674 |
+
F(s) \mathrm{d}s,
|
1675 |
+
|
1676 |
+
for `c` so large that `F(s)` has no singularites in the
|
1677 |
+
half-plane `\operatorname{Re}(s) > c-\epsilon`.
|
1678 |
+
|
1679 |
+
Explanation
|
1680 |
+
===========
|
1681 |
+
|
1682 |
+
The plane can be specified by
|
1683 |
+
argument ``plane``, but will be inferred if passed as None.
|
1684 |
+
|
1685 |
+
Under certain regularity conditions, this recovers `f(t)` from its
|
1686 |
+
Laplace Transform `F(s)`, for non-negative `t`, and vice
|
1687 |
+
versa.
|
1688 |
+
|
1689 |
+
If the integral cannot be computed in closed form, this function returns
|
1690 |
+
an unevaluated :class:`InverseLaplaceTransform` object.
|
1691 |
+
|
1692 |
+
Note that this function will always assume `t` to be real,
|
1693 |
+
regardless of the SymPy assumption on `t`.
|
1694 |
+
|
1695 |
+
For a description of possible hints, refer to the docstring of
|
1696 |
+
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
|
1697 |
+
|
1698 |
+
Examples
|
1699 |
+
========
|
1700 |
+
|
1701 |
+
>>> from sympy import inverse_laplace_transform, exp, Symbol
|
1702 |
+
>>> from sympy.abc import s, t
|
1703 |
+
>>> a = Symbol('a', positive=True)
|
1704 |
+
>>> inverse_laplace_transform(exp(-a*s)/s, s, t)
|
1705 |
+
Heaviside(-a + t)
|
1706 |
+
|
1707 |
+
See Also
|
1708 |
+
========
|
1709 |
+
|
1710 |
+
laplace_transform
|
1711 |
+
hankel_transform, inverse_hankel_transform
|
1712 |
+
"""
|
1713 |
+
if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'):
|
1714 |
+
return F.applyfunc(
|
1715 |
+
lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints))
|
1716 |
+
return InverseLaplaceTransform(F, s, t, plane).doit(**hints)
|
1717 |
+
|
1718 |
+
|
1719 |
+
def _fast_inverse_laplace(e, s, t):
|
1720 |
+
"""Fast inverse Laplace transform of rational function including RootSum"""
|
1721 |
+
a, b, n = symbols('a, b, n', cls=Wild, exclude=[s])
|
1722 |
+
|
1723 |
+
def _ilt(e):
|
1724 |
+
if not e.has(s):
|
1725 |
+
return e
|
1726 |
+
elif e.is_Add:
|
1727 |
+
return _ilt_add(e)
|
1728 |
+
elif e.is_Mul:
|
1729 |
+
return _ilt_mul(e)
|
1730 |
+
elif e.is_Pow:
|
1731 |
+
return _ilt_pow(e)
|
1732 |
+
elif isinstance(e, RootSum):
|
1733 |
+
return _ilt_rootsum(e)
|
1734 |
+
else:
|
1735 |
+
raise NotImplementedError
|
1736 |
+
|
1737 |
+
def _ilt_add(e):
|
1738 |
+
return e.func(*map(_ilt, e.args))
|
1739 |
+
|
1740 |
+
def _ilt_mul(e):
|
1741 |
+
coeff, expr = e.as_independent(s)
|
1742 |
+
if expr.is_Mul:
|
1743 |
+
raise NotImplementedError
|
1744 |
+
return coeff * _ilt(expr)
|
1745 |
+
|
1746 |
+
def _ilt_pow(e):
|
1747 |
+
match = e.match((a*s + b)**n)
|
1748 |
+
if match is not None:
|
1749 |
+
nm, am, bm = match[n], match[a], match[b]
|
1750 |
+
if nm.is_Integer and nm < 0:
|
1751 |
+
return t**(-nm-1)*exp(-(bm/am)*t)/(am**-nm*gamma(-nm))
|
1752 |
+
if nm == 1:
|
1753 |
+
return exp(-(bm/am)*t) / am
|
1754 |
+
raise NotImplementedError
|
1755 |
+
|
1756 |
+
def _ilt_rootsum(e):
|
1757 |
+
expr = e.fun.expr
|
1758 |
+
[variable] = e.fun.variables
|
1759 |
+
return RootSum(e.poly, Lambda(variable, together(_ilt(expr))))
|
1760 |
+
|
1761 |
+
return _ilt(e)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/manualintegrate.py
ADDED
@@ -0,0 +1,2171 @@
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Integration method that emulates by-hand techniques.
|
2 |
+
|
3 |
+
This module also provides functionality to get the steps used to evaluate a
|
4 |
+
particular integral, in the ``integral_steps`` function. This will return
|
5 |
+
nested ``Rule`` s representing the integration rules used.
|
6 |
+
|
7 |
+
Each ``Rule`` class represents a (maybe parametrized) integration rule, e.g.
|
8 |
+
``SinRule`` for integrating ``sin(x)`` and ``ReciprocalSqrtQuadraticRule``
|
9 |
+
for integrating ``1/sqrt(a+b*x+c*x**2)``. The ``eval`` method returns the
|
10 |
+
integration result.
|
11 |
+
|
12 |
+
The ``manualintegrate`` function computes the integral by calling ``eval``
|
13 |
+
on the rule returned by ``integral_steps``.
|
14 |
+
|
15 |
+
The integrator can be extended with new heuristics and evaluation
|
16 |
+
techniques. To do so, extend the ``Rule`` class, implement ``eval`` method,
|
17 |
+
then write a function that accepts an ``IntegralInfo`` object and returns
|
18 |
+
either a ``Rule`` instance or ``None``. If the new technique requires a new
|
19 |
+
match, add the key and call to the antiderivative function to integral_steps.
|
20 |
+
To enable simple substitutions, add the match to find_substitutions.
|
21 |
+
|
22 |
+
"""
|
23 |
+
|
24 |
+
from __future__ import annotations
|
25 |
+
from typing import NamedTuple, Type, Callable, Sequence
|
26 |
+
from abc import ABC, abstractmethod
|
27 |
+
from dataclasses import dataclass
|
28 |
+
from collections import defaultdict
|
29 |
+
from collections.abc import Mapping
|
30 |
+
|
31 |
+
from sympy.core.add import Add
|
32 |
+
from sympy.core.cache import cacheit
|
33 |
+
from sympy.core.containers import Dict
|
34 |
+
from sympy.core.expr import Expr
|
35 |
+
from sympy.core.function import Derivative
|
36 |
+
from sympy.core.logic import fuzzy_not
|
37 |
+
from sympy.core.mul import Mul
|
38 |
+
from sympy.core.numbers import Integer, Number, E
|
39 |
+
from sympy.core.power import Pow
|
40 |
+
from sympy.core.relational import Eq, Ne, Boolean
|
41 |
+
from sympy.core.singleton import S
|
42 |
+
from sympy.core.symbol import Dummy, Symbol, Wild
|
43 |
+
from sympy.functions.elementary.complexes import Abs
|
44 |
+
from sympy.functions.elementary.exponential import exp, log
|
45 |
+
from sympy.functions.elementary.hyperbolic import (HyperbolicFunction, csch,
|
46 |
+
cosh, coth, sech, sinh, tanh, asinh)
|
47 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
48 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
49 |
+
from sympy.functions.elementary.trigonometric import (TrigonometricFunction,
|
50 |
+
cos, sin, tan, cot, csc, sec, acos, asin, atan, acot, acsc, asec)
|
51 |
+
from sympy.functions.special.delta_functions import Heaviside, DiracDelta
|
52 |
+
from sympy.functions.special.error_functions import (erf, erfi, fresnelc,
|
53 |
+
fresnels, Ci, Chi, Si, Shi, Ei, li)
|
54 |
+
from sympy.functions.special.gamma_functions import uppergamma
|
55 |
+
from sympy.functions.special.elliptic_integrals import elliptic_e, elliptic_f
|
56 |
+
from sympy.functions.special.polynomials import (chebyshevt, chebyshevu,
|
57 |
+
legendre, hermite, laguerre, assoc_laguerre, gegenbauer, jacobi,
|
58 |
+
OrthogonalPolynomial)
|
59 |
+
from sympy.functions.special.zeta_functions import polylog
|
60 |
+
from .integrals import Integral
|
61 |
+
from sympy.logic.boolalg import And
|
62 |
+
from sympy.ntheory.factor_ import primefactors
|
63 |
+
from sympy.polys.polytools import degree, lcm_list, gcd_list, Poly
|
64 |
+
from sympy.simplify.radsimp import fraction
|
65 |
+
from sympy.simplify.simplify import simplify
|
66 |
+
from sympy.solvers.solvers import solve
|
67 |
+
from sympy.strategies.core import switch, do_one, null_safe, condition
|
68 |
+
from sympy.utilities.iterables import iterable
|
69 |
+
from sympy.utilities.misc import debug
|
70 |
+
|
71 |
+
|
72 |
+
@dataclass
|
73 |
+
class Rule(ABC):
|
74 |
+
integrand: Expr
|
75 |
+
variable: Symbol
|
76 |
+
|
77 |
+
@abstractmethod
|
78 |
+
def eval(self) -> Expr:
|
79 |
+
pass
|
80 |
+
|
81 |
+
@abstractmethod
|
82 |
+
def contains_dont_know(self) -> bool:
|
83 |
+
pass
|
84 |
+
|
85 |
+
|
86 |
+
@dataclass
|
87 |
+
class AtomicRule(Rule, ABC):
|
88 |
+
"""A simple rule that does not depend on other rules"""
|
89 |
+
def contains_dont_know(self) -> bool:
|
90 |
+
return False
|
91 |
+
|
92 |
+
|
93 |
+
@dataclass
|
94 |
+
class ConstantRule(AtomicRule):
|
95 |
+
"""integrate(a, x) -> a*x"""
|
96 |
+
def eval(self) -> Expr:
|
97 |
+
return self.integrand * self.variable
|
98 |
+
|
99 |
+
|
100 |
+
@dataclass
|
101 |
+
class ConstantTimesRule(Rule):
|
102 |
+
"""integrate(a*f(x), x) -> a*integrate(f(x), x)"""
|
103 |
+
constant: Expr
|
104 |
+
other: Expr
|
105 |
+
substep: Rule
|
106 |
+
|
107 |
+
def eval(self) -> Expr:
|
108 |
+
return self.constant * self.substep.eval()
|
109 |
+
|
110 |
+
def contains_dont_know(self) -> bool:
|
111 |
+
return self.substep.contains_dont_know()
|
112 |
+
|
113 |
+
|
114 |
+
@dataclass
|
115 |
+
class PowerRule(AtomicRule):
|
116 |
+
"""integrate(x**a, x)"""
|
117 |
+
base: Expr
|
118 |
+
exp: Expr
|
119 |
+
|
120 |
+
def eval(self) -> Expr:
|
121 |
+
return Piecewise(
|
122 |
+
((self.base**(self.exp + 1))/(self.exp + 1), Ne(self.exp, -1)),
|
123 |
+
(log(self.base), True),
|
124 |
+
)
|
125 |
+
|
126 |
+
|
127 |
+
@dataclass
|
128 |
+
class NestedPowRule(AtomicRule):
|
129 |
+
"""integrate((x**a)**b, x)"""
|
130 |
+
base: Expr
|
131 |
+
exp: Expr
|
132 |
+
|
133 |
+
def eval(self) -> Expr:
|
134 |
+
m = self.base * self.integrand
|
135 |
+
return Piecewise((m / (self.exp + 1), Ne(self.exp, -1)),
|
136 |
+
(m * log(self.base), True))
|
137 |
+
|
138 |
+
|
139 |
+
@dataclass
|
140 |
+
class AddRule(Rule):
|
141 |
+
"""integrate(f(x) + g(x), x) -> integrate(f(x), x) + integrate(g(x), x)"""
|
142 |
+
substeps: list[Rule]
|
143 |
+
|
144 |
+
def eval(self) -> Expr:
|
145 |
+
return Add(*(substep.eval() for substep in self.substeps))
|
146 |
+
|
147 |
+
def contains_dont_know(self) -> bool:
|
148 |
+
return any(substep.contains_dont_know() for substep in self.substeps)
|
149 |
+
|
150 |
+
|
151 |
+
@dataclass
|
152 |
+
class URule(Rule):
|
153 |
+
"""integrate(f(g(x))*g'(x), x) -> integrate(f(u), u), u = g(x)"""
|
154 |
+
u_var: Symbol
|
155 |
+
u_func: Expr
|
156 |
+
substep: Rule
|
157 |
+
|
158 |
+
def eval(self) -> Expr:
|
159 |
+
result = self.substep.eval()
|
160 |
+
if self.u_func.is_Pow:
|
161 |
+
base, exp_ = self.u_func.as_base_exp()
|
162 |
+
if exp_ == -1:
|
163 |
+
# avoid needless -log(1/x) from substitution
|
164 |
+
result = result.subs(log(self.u_var), -log(base))
|
165 |
+
return result.subs(self.u_var, self.u_func)
|
166 |
+
|
167 |
+
def contains_dont_know(self) -> bool:
|
168 |
+
return self.substep.contains_dont_know()
|
169 |
+
|
170 |
+
|
171 |
+
@dataclass
|
172 |
+
class PartsRule(Rule):
|
173 |
+
"""integrate(u(x)*v'(x), x) -> u(x)*v(x) - integrate(u'(x)*v(x), x)"""
|
174 |
+
u: Symbol
|
175 |
+
dv: Expr
|
176 |
+
v_step: Rule
|
177 |
+
second_step: Rule | None # None when is a substep of CyclicPartsRule
|
178 |
+
|
179 |
+
def eval(self) -> Expr:
|
180 |
+
assert self.second_step is not None
|
181 |
+
v = self.v_step.eval()
|
182 |
+
return self.u * v - self.second_step.eval()
|
183 |
+
|
184 |
+
def contains_dont_know(self) -> bool:
|
185 |
+
return self.v_step.contains_dont_know() or (
|
186 |
+
self.second_step is not None and self.second_step.contains_dont_know())
|
187 |
+
|
188 |
+
|
189 |
+
@dataclass
|
190 |
+
class CyclicPartsRule(Rule):
|
191 |
+
"""Apply PartsRule multiple times to integrate exp(x)*sin(x)"""
|
192 |
+
parts_rules: list[PartsRule]
|
193 |
+
coefficient: Expr
|
194 |
+
|
195 |
+
def eval(self) -> Expr:
|
196 |
+
result = []
|
197 |
+
sign = 1
|
198 |
+
for rule in self.parts_rules:
|
199 |
+
result.append(sign * rule.u * rule.v_step.eval())
|
200 |
+
sign *= -1
|
201 |
+
return Add(*result) / (1 - self.coefficient)
|
202 |
+
|
203 |
+
def contains_dont_know(self) -> bool:
|
204 |
+
return any(substep.contains_dont_know() for substep in self.parts_rules)
|
205 |
+
|
206 |
+
|
207 |
+
@dataclass
|
208 |
+
class TrigRule(AtomicRule, ABC):
|
209 |
+
pass
|
210 |
+
|
211 |
+
|
212 |
+
@dataclass
|
213 |
+
class SinRule(TrigRule):
|
214 |
+
"""integrate(sin(x), x) -> -cos(x)"""
|
215 |
+
def eval(self) -> Expr:
|
216 |
+
return -cos(self.variable)
|
217 |
+
|
218 |
+
|
219 |
+
@dataclass
|
220 |
+
class CosRule(TrigRule):
|
221 |
+
"""integrate(cos(x), x) -> sin(x)"""
|
222 |
+
def eval(self) -> Expr:
|
223 |
+
return sin(self.variable)
|
224 |
+
|
225 |
+
|
226 |
+
@dataclass
|
227 |
+
class SecTanRule(TrigRule):
|
228 |
+
"""integrate(sec(x)*tan(x), x) -> sec(x)"""
|
229 |
+
def eval(self) -> Expr:
|
230 |
+
return sec(self.variable)
|
231 |
+
|
232 |
+
|
233 |
+
@dataclass
|
234 |
+
class CscCotRule(TrigRule):
|
235 |
+
"""integrate(csc(x)*cot(x), x) -> -csc(x)"""
|
236 |
+
def eval(self) -> Expr:
|
237 |
+
return -csc(self.variable)
|
238 |
+
|
239 |
+
|
240 |
+
@dataclass
|
241 |
+
class Sec2Rule(TrigRule):
|
242 |
+
"""integrate(sec(x)**2, x) -> tan(x)"""
|
243 |
+
def eval(self) -> Expr:
|
244 |
+
return tan(self.variable)
|
245 |
+
|
246 |
+
|
247 |
+
@dataclass
|
248 |
+
class Csc2Rule(TrigRule):
|
249 |
+
"""integrate(csc(x)**2, x) -> -cot(x)"""
|
250 |
+
def eval(self) -> Expr:
|
251 |
+
return -cot(self.variable)
|
252 |
+
|
253 |
+
|
254 |
+
@dataclass
|
255 |
+
class HyperbolicRule(AtomicRule, ABC):
|
256 |
+
pass
|
257 |
+
|
258 |
+
|
259 |
+
@dataclass
|
260 |
+
class SinhRule(HyperbolicRule):
|
261 |
+
"""integrate(sinh(x), x) -> cosh(x)"""
|
262 |
+
def eval(self) -> Expr:
|
263 |
+
return cosh(self.variable)
|
264 |
+
|
265 |
+
|
266 |
+
@dataclass
|
267 |
+
class CoshRule(HyperbolicRule):
|
268 |
+
"""integrate(cosh(x), x) -> sinh(x)"""
|
269 |
+
def eval(self):
|
270 |
+
return sinh(self.variable)
|
271 |
+
|
272 |
+
|
273 |
+
@dataclass
|
274 |
+
class ExpRule(AtomicRule):
|
275 |
+
"""integrate(a**x, x) -> a**x/ln(a)"""
|
276 |
+
base: Expr
|
277 |
+
exp: Expr
|
278 |
+
|
279 |
+
def eval(self) -> Expr:
|
280 |
+
return self.integrand / log(self.base)
|
281 |
+
|
282 |
+
|
283 |
+
@dataclass
|
284 |
+
class ReciprocalRule(AtomicRule):
|
285 |
+
"""integrate(1/x, x) -> ln(x)"""
|
286 |
+
base: Expr
|
287 |
+
|
288 |
+
def eval(self) -> Expr:
|
289 |
+
return log(self.base)
|
290 |
+
|
291 |
+
|
292 |
+
@dataclass
|
293 |
+
class ArcsinRule(AtomicRule):
|
294 |
+
"""integrate(1/sqrt(1-x**2), x) -> asin(x)"""
|
295 |
+
def eval(self) -> Expr:
|
296 |
+
return asin(self.variable)
|
297 |
+
|
298 |
+
|
299 |
+
@dataclass
|
300 |
+
class ArcsinhRule(AtomicRule):
|
301 |
+
"""integrate(1/sqrt(1+x**2), x) -> asin(x)"""
|
302 |
+
def eval(self) -> Expr:
|
303 |
+
return asinh(self.variable)
|
304 |
+
|
305 |
+
|
306 |
+
@dataclass
|
307 |
+
class ReciprocalSqrtQuadraticRule(AtomicRule):
|
308 |
+
"""integrate(1/sqrt(a+b*x+c*x**2), x) -> log(2*sqrt(c)*sqrt(a+b*x+c*x**2)+b+2*c*x)/sqrt(c)"""
|
309 |
+
a: Expr
|
310 |
+
b: Expr
|
311 |
+
c: Expr
|
312 |
+
|
313 |
+
def eval(self) -> Expr:
|
314 |
+
a, b, c, x = self.a, self.b, self.c, self.variable
|
315 |
+
return log(2*sqrt(c)*sqrt(a+b*x+c*x**2)+b+2*c*x)/sqrt(c)
|
316 |
+
|
317 |
+
|
318 |
+
@dataclass
|
319 |
+
class SqrtQuadraticDenomRule(AtomicRule):
|
320 |
+
"""integrate(poly(x)/sqrt(a+b*x+c*x**2), x)"""
|
321 |
+
a: Expr
|
322 |
+
b: Expr
|
323 |
+
c: Expr
|
324 |
+
coeffs: list[Expr]
|
325 |
+
|
326 |
+
def eval(self) -> Expr:
|
327 |
+
a, b, c, coeffs, x = self.a, self.b, self.c, self.coeffs.copy(), self.variable
|
328 |
+
# Integrate poly/sqrt(a+b*x+c*x**2) using recursion.
|
329 |
+
# coeffs are coefficients of the polynomial.
|
330 |
+
# Let I_n = x**n/sqrt(a+b*x+c*x**2), then
|
331 |
+
# I_n = A * x**(n-1)*sqrt(a+b*x+c*x**2) - B * I_{n-1} - C * I_{n-2}
|
332 |
+
# where A = 1/(n*c), B = (2*n-1)*b/(2*n*c), C = (n-1)*a/(n*c)
|
333 |
+
# See https://github.com/sympy/sympy/pull/23608 for proof.
|
334 |
+
result_coeffs = []
|
335 |
+
coeffs = coeffs.copy()
|
336 |
+
for i in range(len(coeffs)-2):
|
337 |
+
n = len(coeffs)-1-i
|
338 |
+
coeff = coeffs[i]/(c*n)
|
339 |
+
result_coeffs.append(coeff)
|
340 |
+
coeffs[i+1] -= (2*n-1)*b/2*coeff
|
341 |
+
coeffs[i+2] -= (n-1)*a*coeff
|
342 |
+
d, e = coeffs[-1], coeffs[-2]
|
343 |
+
s = sqrt(a+b*x+c*x**2)
|
344 |
+
constant = d-b*e/(2*c)
|
345 |
+
if constant == 0:
|
346 |
+
I0 = 0
|
347 |
+
else:
|
348 |
+
step = inverse_trig_rule(IntegralInfo(1/s, x), degenerate=False)
|
349 |
+
I0 = constant*step.eval()
|
350 |
+
return Add(*(result_coeffs[i]*x**(len(coeffs)-2-i)
|
351 |
+
for i in range(len(result_coeffs))), e/c)*s + I0
|
352 |
+
|
353 |
+
|
354 |
+
@dataclass
|
355 |
+
class SqrtQuadraticRule(AtomicRule):
|
356 |
+
"""integrate(sqrt(a+b*x+c*x**2), x)"""
|
357 |
+
a: Expr
|
358 |
+
b: Expr
|
359 |
+
c: Expr
|
360 |
+
|
361 |
+
def eval(self) -> Expr:
|
362 |
+
step = sqrt_quadratic_rule(IntegralInfo(self.integrand, self.variable), degenerate=False)
|
363 |
+
return step.eval()
|
364 |
+
|
365 |
+
|
366 |
+
@dataclass
|
367 |
+
class AlternativeRule(Rule):
|
368 |
+
"""Multiple ways to do integration."""
|
369 |
+
alternatives: list[Rule]
|
370 |
+
|
371 |
+
def eval(self) -> Expr:
|
372 |
+
return self.alternatives[0].eval()
|
373 |
+
|
374 |
+
def contains_dont_know(self) -> bool:
|
375 |
+
return any(substep.contains_dont_know() for substep in self.alternatives)
|
376 |
+
|
377 |
+
|
378 |
+
@dataclass
|
379 |
+
class DontKnowRule(Rule):
|
380 |
+
"""Leave the integral as is."""
|
381 |
+
def eval(self) -> Expr:
|
382 |
+
return Integral(self.integrand, self.variable)
|
383 |
+
|
384 |
+
def contains_dont_know(self) -> bool:
|
385 |
+
return True
|
386 |
+
|
387 |
+
|
388 |
+
@dataclass
|
389 |
+
class DerivativeRule(AtomicRule):
|
390 |
+
"""integrate(f'(x), x) -> f(x)"""
|
391 |
+
def eval(self) -> Expr:
|
392 |
+
assert isinstance(self.integrand, Derivative)
|
393 |
+
variable_count = list(self.integrand.variable_count)
|
394 |
+
for i, (var, count) in enumerate(variable_count):
|
395 |
+
if var == self.variable:
|
396 |
+
variable_count[i] = (var, count - 1)
|
397 |
+
break
|
398 |
+
return Derivative(self.integrand.expr, *variable_count)
|
399 |
+
|
400 |
+
|
401 |
+
@dataclass
|
402 |
+
class RewriteRule(Rule):
|
403 |
+
"""Rewrite integrand to another form that is easier to handle."""
|
404 |
+
rewritten: Expr
|
405 |
+
substep: Rule
|
406 |
+
|
407 |
+
def eval(self) -> Expr:
|
408 |
+
return self.substep.eval()
|
409 |
+
|
410 |
+
def contains_dont_know(self) -> bool:
|
411 |
+
return self.substep.contains_dont_know()
|
412 |
+
|
413 |
+
|
414 |
+
@dataclass
|
415 |
+
class CompleteSquareRule(RewriteRule):
|
416 |
+
"""Rewrite a+b*x+c*x**2 to a-b**2/(4*c) + c*(x+b/(2*c))**2"""
|
417 |
+
pass
|
418 |
+
|
419 |
+
|
420 |
+
@dataclass
|
421 |
+
class PiecewiseRule(Rule):
|
422 |
+
subfunctions: Sequence[tuple[Rule, bool | Boolean]]
|
423 |
+
|
424 |
+
def eval(self) -> Expr:
|
425 |
+
return Piecewise(*[(substep.eval(), cond)
|
426 |
+
for substep, cond in self.subfunctions])
|
427 |
+
|
428 |
+
def contains_dont_know(self) -> bool:
|
429 |
+
return any(substep.contains_dont_know() for substep, _ in self.subfunctions)
|
430 |
+
|
431 |
+
|
432 |
+
@dataclass
|
433 |
+
class HeavisideRule(Rule):
|
434 |
+
harg: Expr
|
435 |
+
ibnd: Expr
|
436 |
+
substep: Rule
|
437 |
+
|
438 |
+
def eval(self) -> Expr:
|
439 |
+
# If we are integrating over x and the integrand has the form
|
440 |
+
# Heaviside(m*x+b)*g(x) == Heaviside(harg)*g(symbol)
|
441 |
+
# then there needs to be continuity at -b/m == ibnd,
|
442 |
+
# so we subtract the appropriate term.
|
443 |
+
result = self.substep.eval()
|
444 |
+
return Heaviside(self.harg) * (result - result.subs(self.variable, self.ibnd))
|
445 |
+
|
446 |
+
def contains_dont_know(self) -> bool:
|
447 |
+
return self.substep.contains_dont_know()
|
448 |
+
|
449 |
+
|
450 |
+
@dataclass
|
451 |
+
class DiracDeltaRule(AtomicRule):
|
452 |
+
n: Expr
|
453 |
+
a: Expr
|
454 |
+
b: Expr
|
455 |
+
|
456 |
+
def eval(self) -> Expr:
|
457 |
+
n, a, b, x = self.n, self.a, self.b, self.variable
|
458 |
+
if n == 0:
|
459 |
+
return Heaviside(a+b*x)/b
|
460 |
+
return DiracDelta(a+b*x, n-1)/b
|
461 |
+
|
462 |
+
|
463 |
+
@dataclass
|
464 |
+
class TrigSubstitutionRule(Rule):
|
465 |
+
theta: Expr
|
466 |
+
func: Expr
|
467 |
+
rewritten: Expr
|
468 |
+
substep: Rule
|
469 |
+
restriction: bool | Boolean
|
470 |
+
|
471 |
+
def eval(self) -> Expr:
|
472 |
+
theta, func, x = self.theta, self.func, self.variable
|
473 |
+
func = func.subs(sec(theta), 1/cos(theta))
|
474 |
+
func = func.subs(csc(theta), 1/sin(theta))
|
475 |
+
func = func.subs(cot(theta), 1/tan(theta))
|
476 |
+
|
477 |
+
trig_function = list(func.find(TrigonometricFunction))
|
478 |
+
assert len(trig_function) == 1
|
479 |
+
trig_function = trig_function[0]
|
480 |
+
relation = solve(x - func, trig_function)
|
481 |
+
assert len(relation) == 1
|
482 |
+
numer, denom = fraction(relation[0])
|
483 |
+
|
484 |
+
if isinstance(trig_function, sin):
|
485 |
+
opposite = numer
|
486 |
+
hypotenuse = denom
|
487 |
+
adjacent = sqrt(denom**2 - numer**2)
|
488 |
+
inverse = asin(relation[0])
|
489 |
+
elif isinstance(trig_function, cos):
|
490 |
+
adjacent = numer
|
491 |
+
hypotenuse = denom
|
492 |
+
opposite = sqrt(denom**2 - numer**2)
|
493 |
+
inverse = acos(relation[0])
|
494 |
+
else: # tan
|
495 |
+
opposite = numer
|
496 |
+
adjacent = denom
|
497 |
+
hypotenuse = sqrt(denom**2 + numer**2)
|
498 |
+
inverse = atan(relation[0])
|
499 |
+
|
500 |
+
substitution = [
|
501 |
+
(sin(theta), opposite/hypotenuse),
|
502 |
+
(cos(theta), adjacent/hypotenuse),
|
503 |
+
(tan(theta), opposite/adjacent),
|
504 |
+
(theta, inverse)
|
505 |
+
]
|
506 |
+
return Piecewise(
|
507 |
+
(self.substep.eval().subs(substitution).trigsimp(), self.restriction)
|
508 |
+
)
|
509 |
+
|
510 |
+
def contains_dont_know(self) -> bool:
|
511 |
+
return self.substep.contains_dont_know()
|
512 |
+
|
513 |
+
|
514 |
+
@dataclass
|
515 |
+
class ArctanRule(AtomicRule):
|
516 |
+
"""integrate(a/(b*x**2+c), x) -> a/b / sqrt(c/b) * atan(x/sqrt(c/b))"""
|
517 |
+
a: Expr
|
518 |
+
b: Expr
|
519 |
+
c: Expr
|
520 |
+
|
521 |
+
def eval(self) -> Expr:
|
522 |
+
a, b, c, x = self.a, self.b, self.c, self.variable
|
523 |
+
return a/b / sqrt(c/b) * atan(x/sqrt(c/b))
|
524 |
+
|
525 |
+
|
526 |
+
@dataclass
|
527 |
+
class OrthogonalPolyRule(AtomicRule, ABC):
|
528 |
+
n: Expr
|
529 |
+
|
530 |
+
|
531 |
+
@dataclass
|
532 |
+
class JacobiRule(OrthogonalPolyRule):
|
533 |
+
a: Expr
|
534 |
+
b: Expr
|
535 |
+
|
536 |
+
def eval(self) -> Expr:
|
537 |
+
n, a, b, x = self.n, self.a, self.b, self.variable
|
538 |
+
return Piecewise(
|
539 |
+
(2*jacobi(n + 1, a - 1, b - 1, x)/(n + a + b), Ne(n + a + b, 0)),
|
540 |
+
(x, Eq(n, 0)),
|
541 |
+
((a + b + 2)*x**2/4 + (a - b)*x/2, Eq(n, 1)))
|
542 |
+
|
543 |
+
|
544 |
+
@dataclass
|
545 |
+
class GegenbauerRule(OrthogonalPolyRule):
|
546 |
+
a: Expr
|
547 |
+
|
548 |
+
def eval(self) -> Expr:
|
549 |
+
n, a, x = self.n, self.a, self.variable
|
550 |
+
return Piecewise(
|
551 |
+
(gegenbauer(n + 1, a - 1, x)/(2*(a - 1)), Ne(a, 1)),
|
552 |
+
(chebyshevt(n + 1, x)/(n + 1), Ne(n, -1)),
|
553 |
+
(S.Zero, True))
|
554 |
+
|
555 |
+
|
556 |
+
@dataclass
|
557 |
+
class ChebyshevTRule(OrthogonalPolyRule):
|
558 |
+
def eval(self) -> Expr:
|
559 |
+
n, x = self.n, self.variable
|
560 |
+
return Piecewise(
|
561 |
+
((chebyshevt(n + 1, x)/(n + 1) -
|
562 |
+
chebyshevt(n - 1, x)/(n - 1))/2, Ne(Abs(n), 1)),
|
563 |
+
(x**2/2, True))
|
564 |
+
|
565 |
+
|
566 |
+
@dataclass
|
567 |
+
class ChebyshevURule(OrthogonalPolyRule):
|
568 |
+
def eval(self) -> Expr:
|
569 |
+
n, x = self.n, self.variable
|
570 |
+
return Piecewise(
|
571 |
+
(chebyshevt(n + 1, x)/(n + 1), Ne(n, -1)),
|
572 |
+
(S.Zero, True))
|
573 |
+
|
574 |
+
|
575 |
+
@dataclass
|
576 |
+
class LegendreRule(OrthogonalPolyRule):
|
577 |
+
def eval(self) -> Expr:
|
578 |
+
n, x = self.n, self.variable
|
579 |
+
return(legendre(n + 1, x) - legendre(n - 1, x))/(2*n + 1)
|
580 |
+
|
581 |
+
|
582 |
+
@dataclass
|
583 |
+
class HermiteRule(OrthogonalPolyRule):
|
584 |
+
def eval(self) -> Expr:
|
585 |
+
n, x = self.n, self.variable
|
586 |
+
return hermite(n + 1, x)/(2*(n + 1))
|
587 |
+
|
588 |
+
|
589 |
+
@dataclass
|
590 |
+
class LaguerreRule(OrthogonalPolyRule):
|
591 |
+
def eval(self) -> Expr:
|
592 |
+
n, x = self.n, self.variable
|
593 |
+
return laguerre(n, x) - laguerre(n + 1, x)
|
594 |
+
|
595 |
+
|
596 |
+
@dataclass
|
597 |
+
class AssocLaguerreRule(OrthogonalPolyRule):
|
598 |
+
a: Expr
|
599 |
+
|
600 |
+
def eval(self) -> Expr:
|
601 |
+
return -assoc_laguerre(self.n + 1, self.a - 1, self.variable)
|
602 |
+
|
603 |
+
|
604 |
+
@dataclass
|
605 |
+
class IRule(AtomicRule, ABC):
|
606 |
+
a: Expr
|
607 |
+
b: Expr
|
608 |
+
|
609 |
+
|
610 |
+
@dataclass
|
611 |
+
class CiRule(IRule):
|
612 |
+
def eval(self) -> Expr:
|
613 |
+
a, b, x = self.a, self.b, self.variable
|
614 |
+
return cos(b)*Ci(a*x) - sin(b)*Si(a*x)
|
615 |
+
|
616 |
+
|
617 |
+
@dataclass
|
618 |
+
class ChiRule(IRule):
|
619 |
+
def eval(self) -> Expr:
|
620 |
+
a, b, x = self.a, self.b, self.variable
|
621 |
+
return cosh(b)*Chi(a*x) + sinh(b)*Shi(a*x)
|
622 |
+
|
623 |
+
|
624 |
+
@dataclass
|
625 |
+
class EiRule(IRule):
|
626 |
+
def eval(self) -> Expr:
|
627 |
+
a, b, x = self.a, self.b, self.variable
|
628 |
+
return exp(b)*Ei(a*x)
|
629 |
+
|
630 |
+
|
631 |
+
@dataclass
|
632 |
+
class SiRule(IRule):
|
633 |
+
def eval(self) -> Expr:
|
634 |
+
a, b, x = self.a, self.b, self.variable
|
635 |
+
return sin(b)*Ci(a*x) + cos(b)*Si(a*x)
|
636 |
+
|
637 |
+
|
638 |
+
@dataclass
|
639 |
+
class ShiRule(IRule):
|
640 |
+
def eval(self) -> Expr:
|
641 |
+
a, b, x = self.a, self.b, self.variable
|
642 |
+
return sinh(b)*Chi(a*x) + cosh(b)*Shi(a*x)
|
643 |
+
|
644 |
+
|
645 |
+
@dataclass
|
646 |
+
class LiRule(IRule):
|
647 |
+
def eval(self) -> Expr:
|
648 |
+
a, b, x = self.a, self.b, self.variable
|
649 |
+
return li(a*x + b)/a
|
650 |
+
|
651 |
+
|
652 |
+
@dataclass
|
653 |
+
class ErfRule(AtomicRule):
|
654 |
+
a: Expr
|
655 |
+
b: Expr
|
656 |
+
c: Expr
|
657 |
+
|
658 |
+
def eval(self) -> Expr:
|
659 |
+
a, b, c, x = self.a, self.b, self.c, self.variable
|
660 |
+
if a.is_extended_real:
|
661 |
+
return Piecewise(
|
662 |
+
(sqrt(S.Pi/(-a))/2 * exp(c - b**2/(4*a)) *
|
663 |
+
erf((-2*a*x - b)/(2*sqrt(-a))), a < 0),
|
664 |
+
(sqrt(S.Pi/a)/2 * exp(c - b**2/(4*a)) *
|
665 |
+
erfi((2*a*x + b)/(2*sqrt(a))), True))
|
666 |
+
return sqrt(S.Pi/a)/2 * exp(c - b**2/(4*a)) * \
|
667 |
+
erfi((2*a*x + b)/(2*sqrt(a)))
|
668 |
+
|
669 |
+
|
670 |
+
@dataclass
|
671 |
+
class FresnelCRule(AtomicRule):
|
672 |
+
a: Expr
|
673 |
+
b: Expr
|
674 |
+
c: Expr
|
675 |
+
|
676 |
+
def eval(self) -> Expr:
|
677 |
+
a, b, c, x = self.a, self.b, self.c, self.variable
|
678 |
+
return sqrt(S.Pi/(2*a)) * (
|
679 |
+
cos(b**2/(4*a) - c)*fresnelc((2*a*x + b)/sqrt(2*a*S.Pi)) +
|
680 |
+
sin(b**2/(4*a) - c)*fresnels((2*a*x + b)/sqrt(2*a*S.Pi)))
|
681 |
+
|
682 |
+
|
683 |
+
@dataclass
|
684 |
+
class FresnelSRule(AtomicRule):
|
685 |
+
a: Expr
|
686 |
+
b: Expr
|
687 |
+
c: Expr
|
688 |
+
|
689 |
+
def eval(self) -> Expr:
|
690 |
+
a, b, c, x = self.a, self.b, self.c, self.variable
|
691 |
+
return sqrt(S.Pi/(2*a)) * (
|
692 |
+
cos(b**2/(4*a) - c)*fresnels((2*a*x + b)/sqrt(2*a*S.Pi)) -
|
693 |
+
sin(b**2/(4*a) - c)*fresnelc((2*a*x + b)/sqrt(2*a*S.Pi)))
|
694 |
+
|
695 |
+
|
696 |
+
@dataclass
|
697 |
+
class PolylogRule(AtomicRule):
|
698 |
+
a: Expr
|
699 |
+
b: Expr
|
700 |
+
|
701 |
+
def eval(self) -> Expr:
|
702 |
+
return polylog(self.b + 1, self.a * self.variable)
|
703 |
+
|
704 |
+
|
705 |
+
@dataclass
|
706 |
+
class UpperGammaRule(AtomicRule):
|
707 |
+
a: Expr
|
708 |
+
e: Expr
|
709 |
+
|
710 |
+
def eval(self) -> Expr:
|
711 |
+
a, e, x = self.a, self.e, self.variable
|
712 |
+
return x**e * (-a*x)**(-e) * uppergamma(e + 1, -a*x)/a
|
713 |
+
|
714 |
+
|
715 |
+
@dataclass
|
716 |
+
class EllipticFRule(AtomicRule):
|
717 |
+
a: Expr
|
718 |
+
d: Expr
|
719 |
+
|
720 |
+
def eval(self) -> Expr:
|
721 |
+
return elliptic_f(self.variable, self.d/self.a)/sqrt(self.a)
|
722 |
+
|
723 |
+
|
724 |
+
@dataclass
|
725 |
+
class EllipticERule(AtomicRule):
|
726 |
+
a: Expr
|
727 |
+
d: Expr
|
728 |
+
|
729 |
+
def eval(self) -> Expr:
|
730 |
+
return elliptic_e(self.variable, self.d/self.a)*sqrt(self.a)
|
731 |
+
|
732 |
+
|
733 |
+
class IntegralInfo(NamedTuple):
|
734 |
+
integrand: Expr
|
735 |
+
symbol: Symbol
|
736 |
+
|
737 |
+
|
738 |
+
def manual_diff(f, symbol):
|
739 |
+
"""Derivative of f in form expected by find_substitutions
|
740 |
+
|
741 |
+
SymPy's derivatives for some trig functions (like cot) are not in a form
|
742 |
+
that works well with finding substitutions; this replaces the
|
743 |
+
derivatives for those particular forms with something that works better.
|
744 |
+
|
745 |
+
"""
|
746 |
+
if f.args:
|
747 |
+
arg = f.args[0]
|
748 |
+
if isinstance(f, tan):
|
749 |
+
return arg.diff(symbol) * sec(arg)**2
|
750 |
+
elif isinstance(f, cot):
|
751 |
+
return -arg.diff(symbol) * csc(arg)**2
|
752 |
+
elif isinstance(f, sec):
|
753 |
+
return arg.diff(symbol) * sec(arg) * tan(arg)
|
754 |
+
elif isinstance(f, csc):
|
755 |
+
return -arg.diff(symbol) * csc(arg) * cot(arg)
|
756 |
+
elif isinstance(f, Add):
|
757 |
+
return sum([manual_diff(arg, symbol) for arg in f.args])
|
758 |
+
elif isinstance(f, Mul):
|
759 |
+
if len(f.args) == 2 and isinstance(f.args[0], Number):
|
760 |
+
return f.args[0] * manual_diff(f.args[1], symbol)
|
761 |
+
return f.diff(symbol)
|
762 |
+
|
763 |
+
def manual_subs(expr, *args):
|
764 |
+
"""
|
765 |
+
A wrapper for `expr.subs(*args)` with additional logic for substitution
|
766 |
+
of invertible functions.
|
767 |
+
"""
|
768 |
+
if len(args) == 1:
|
769 |
+
sequence = args[0]
|
770 |
+
if isinstance(sequence, (Dict, Mapping)):
|
771 |
+
sequence = sequence.items()
|
772 |
+
elif not iterable(sequence):
|
773 |
+
raise ValueError("Expected an iterable of (old, new) pairs")
|
774 |
+
elif len(args) == 2:
|
775 |
+
sequence = [args]
|
776 |
+
else:
|
777 |
+
raise ValueError("subs accepts either 1 or 2 arguments")
|
778 |
+
|
779 |
+
new_subs = []
|
780 |
+
for old, new in sequence:
|
781 |
+
if isinstance(old, log):
|
782 |
+
# If log(x) = y, then exp(a*log(x)) = exp(a*y)
|
783 |
+
# that is, x**a = exp(a*y). Replace nontrivial powers of x
|
784 |
+
# before subs turns them into `exp(y)**a`, but
|
785 |
+
# do not replace x itself yet, to avoid `log(exp(y))`.
|
786 |
+
x0 = old.args[0]
|
787 |
+
expr = expr.replace(lambda x: x.is_Pow and x.base == x0,
|
788 |
+
lambda x: exp(x.exp*new))
|
789 |
+
new_subs.append((x0, exp(new)))
|
790 |
+
|
791 |
+
return expr.subs(list(sequence) + new_subs)
|
792 |
+
|
793 |
+
# Method based on that on SIN, described in "Symbolic Integration: The
|
794 |
+
# Stormy Decade"
|
795 |
+
|
796 |
+
inverse_trig_functions = (atan, asin, acos, acot, acsc, asec)
|
797 |
+
|
798 |
+
|
799 |
+
def find_substitutions(integrand, symbol, u_var):
|
800 |
+
results = []
|
801 |
+
|
802 |
+
def test_subterm(u, u_diff):
|
803 |
+
if u_diff == 0:
|
804 |
+
return False
|
805 |
+
substituted = integrand / u_diff
|
806 |
+
debug("substituted: {}, u: {}, u_var: {}".format(substituted, u, u_var))
|
807 |
+
substituted = manual_subs(substituted, u, u_var).cancel()
|
808 |
+
|
809 |
+
if substituted.has_free(symbol):
|
810 |
+
return False
|
811 |
+
# avoid increasing the degree of a rational function
|
812 |
+
if integrand.is_rational_function(symbol) and substituted.is_rational_function(u_var):
|
813 |
+
deg_before = max([degree(t, symbol) for t in integrand.as_numer_denom()])
|
814 |
+
deg_after = max([degree(t, u_var) for t in substituted.as_numer_denom()])
|
815 |
+
if deg_after > deg_before:
|
816 |
+
return False
|
817 |
+
return substituted.as_independent(u_var, as_Add=False)
|
818 |
+
|
819 |
+
def exp_subterms(term: Expr):
|
820 |
+
linear_coeffs = []
|
821 |
+
terms = []
|
822 |
+
n = Wild('n', properties=[lambda n: n.is_Integer])
|
823 |
+
for exp_ in term.find(exp):
|
824 |
+
arg = exp_.args[0]
|
825 |
+
if symbol not in arg.free_symbols:
|
826 |
+
continue
|
827 |
+
match = arg.match(n*symbol)
|
828 |
+
if match:
|
829 |
+
linear_coeffs.append(match[n])
|
830 |
+
else:
|
831 |
+
terms.append(exp_)
|
832 |
+
if linear_coeffs:
|
833 |
+
terms.append(exp(gcd_list(linear_coeffs)*symbol))
|
834 |
+
return terms
|
835 |
+
|
836 |
+
def possible_subterms(term):
|
837 |
+
if isinstance(term, (TrigonometricFunction, HyperbolicFunction,
|
838 |
+
*inverse_trig_functions,
|
839 |
+
exp, log, Heaviside)):
|
840 |
+
return [term.args[0]]
|
841 |
+
elif isinstance(term, (chebyshevt, chebyshevu,
|
842 |
+
legendre, hermite, laguerre)):
|
843 |
+
return [term.args[1]]
|
844 |
+
elif isinstance(term, (gegenbauer, assoc_laguerre)):
|
845 |
+
return [term.args[2]]
|
846 |
+
elif isinstance(term, jacobi):
|
847 |
+
return [term.args[3]]
|
848 |
+
elif isinstance(term, Mul):
|
849 |
+
r = []
|
850 |
+
for u in term.args:
|
851 |
+
r.append(u)
|
852 |
+
r.extend(possible_subterms(u))
|
853 |
+
return r
|
854 |
+
elif isinstance(term, Pow):
|
855 |
+
r = [arg for arg in term.args if arg.has(symbol)]
|
856 |
+
if term.exp.is_Integer:
|
857 |
+
r.extend([term.base**d for d in primefactors(term.exp)
|
858 |
+
if 1 < d < abs(term.args[1])])
|
859 |
+
if term.base.is_Add:
|
860 |
+
r.extend([t for t in possible_subterms(term.base)
|
861 |
+
if t.is_Pow])
|
862 |
+
return r
|
863 |
+
elif isinstance(term, Add):
|
864 |
+
r = []
|
865 |
+
for arg in term.args:
|
866 |
+
r.append(arg)
|
867 |
+
r.extend(possible_subterms(arg))
|
868 |
+
return r
|
869 |
+
return []
|
870 |
+
|
871 |
+
for u in list(dict.fromkeys(possible_subterms(integrand) + exp_subterms(integrand))):
|
872 |
+
if u == symbol:
|
873 |
+
continue
|
874 |
+
u_diff = manual_diff(u, symbol)
|
875 |
+
new_integrand = test_subterm(u, u_diff)
|
876 |
+
if new_integrand is not False:
|
877 |
+
constant, new_integrand = new_integrand
|
878 |
+
if new_integrand == integrand.subs(symbol, u_var):
|
879 |
+
continue
|
880 |
+
substitution = (u, constant, new_integrand)
|
881 |
+
if substitution not in results:
|
882 |
+
results.append(substitution)
|
883 |
+
|
884 |
+
return results
|
885 |
+
|
886 |
+
def rewriter(condition, rewrite):
|
887 |
+
"""Strategy that rewrites an integrand."""
|
888 |
+
def _rewriter(integral):
|
889 |
+
integrand, symbol = integral
|
890 |
+
debug("Integral: {} is rewritten with {} on symbol: {}".format(integrand, rewrite, symbol))
|
891 |
+
if condition(*integral):
|
892 |
+
rewritten = rewrite(*integral)
|
893 |
+
if rewritten != integrand:
|
894 |
+
substep = integral_steps(rewritten, symbol)
|
895 |
+
if not isinstance(substep, DontKnowRule) and substep:
|
896 |
+
return RewriteRule(integrand, symbol, rewritten, substep)
|
897 |
+
return _rewriter
|
898 |
+
|
899 |
+
def proxy_rewriter(condition, rewrite):
|
900 |
+
"""Strategy that rewrites an integrand based on some other criteria."""
|
901 |
+
def _proxy_rewriter(criteria):
|
902 |
+
criteria, integral = criteria
|
903 |
+
integrand, symbol = integral
|
904 |
+
debug("Integral: {} is rewritten with {} on symbol: {} and criteria: {}".format(integrand, rewrite, symbol, criteria))
|
905 |
+
args = criteria + list(integral)
|
906 |
+
if condition(*args):
|
907 |
+
rewritten = rewrite(*args)
|
908 |
+
if rewritten != integrand:
|
909 |
+
return RewriteRule(integrand, symbol, rewritten, integral_steps(rewritten, symbol))
|
910 |
+
return _proxy_rewriter
|
911 |
+
|
912 |
+
def multiplexer(conditions):
|
913 |
+
"""Apply the rule that matches the condition, else None"""
|
914 |
+
def multiplexer_rl(expr):
|
915 |
+
for key, rule in conditions.items():
|
916 |
+
if key(expr):
|
917 |
+
return rule(expr)
|
918 |
+
return multiplexer_rl
|
919 |
+
|
920 |
+
def alternatives(*rules):
|
921 |
+
"""Strategy that makes an AlternativeRule out of multiple possible results."""
|
922 |
+
def _alternatives(integral):
|
923 |
+
alts = []
|
924 |
+
count = 0
|
925 |
+
debug("List of Alternative Rules")
|
926 |
+
for rule in rules:
|
927 |
+
count = count + 1
|
928 |
+
debug("Rule {}: {}".format(count, rule))
|
929 |
+
|
930 |
+
result = rule(integral)
|
931 |
+
if (result and not isinstance(result, DontKnowRule) and
|
932 |
+
result != integral and result not in alts):
|
933 |
+
alts.append(result)
|
934 |
+
if len(alts) == 1:
|
935 |
+
return alts[0]
|
936 |
+
elif alts:
|
937 |
+
doable = [rule for rule in alts if not rule.contains_dont_know()]
|
938 |
+
if doable:
|
939 |
+
return AlternativeRule(*integral, doable)
|
940 |
+
else:
|
941 |
+
return AlternativeRule(*integral, alts)
|
942 |
+
return _alternatives
|
943 |
+
|
944 |
+
def constant_rule(integral):
|
945 |
+
return ConstantRule(*integral)
|
946 |
+
|
947 |
+
def power_rule(integral):
|
948 |
+
integrand, symbol = integral
|
949 |
+
base, expt = integrand.as_base_exp()
|
950 |
+
|
951 |
+
if symbol not in expt.free_symbols and isinstance(base, Symbol):
|
952 |
+
if simplify(expt + 1) == 0:
|
953 |
+
return ReciprocalRule(integrand, symbol, base)
|
954 |
+
return PowerRule(integrand, symbol, base, expt)
|
955 |
+
elif symbol not in base.free_symbols and isinstance(expt, Symbol):
|
956 |
+
rule = ExpRule(integrand, symbol, base, expt)
|
957 |
+
|
958 |
+
if fuzzy_not(log(base).is_zero):
|
959 |
+
return rule
|
960 |
+
elif log(base).is_zero:
|
961 |
+
return ConstantRule(1, symbol)
|
962 |
+
|
963 |
+
return PiecewiseRule(integrand, symbol, [
|
964 |
+
(rule, Ne(log(base), 0)),
|
965 |
+
(ConstantRule(1, symbol), True)
|
966 |
+
])
|
967 |
+
|
968 |
+
def exp_rule(integral):
|
969 |
+
integrand, symbol = integral
|
970 |
+
if isinstance(integrand.args[0], Symbol):
|
971 |
+
return ExpRule(integrand, symbol, E, integrand.args[0])
|
972 |
+
|
973 |
+
|
974 |
+
def orthogonal_poly_rule(integral):
|
975 |
+
orthogonal_poly_classes = {
|
976 |
+
jacobi: JacobiRule,
|
977 |
+
gegenbauer: GegenbauerRule,
|
978 |
+
chebyshevt: ChebyshevTRule,
|
979 |
+
chebyshevu: ChebyshevURule,
|
980 |
+
legendre: LegendreRule,
|
981 |
+
hermite: HermiteRule,
|
982 |
+
laguerre: LaguerreRule,
|
983 |
+
assoc_laguerre: AssocLaguerreRule
|
984 |
+
}
|
985 |
+
orthogonal_poly_var_index = {
|
986 |
+
jacobi: 3,
|
987 |
+
gegenbauer: 2,
|
988 |
+
assoc_laguerre: 2
|
989 |
+
}
|
990 |
+
integrand, symbol = integral
|
991 |
+
for klass in orthogonal_poly_classes:
|
992 |
+
if isinstance(integrand, klass):
|
993 |
+
var_index = orthogonal_poly_var_index.get(klass, 1)
|
994 |
+
if (integrand.args[var_index] is symbol and not
|
995 |
+
any(v.has(symbol) for v in integrand.args[:var_index])):
|
996 |
+
return orthogonal_poly_classes[klass](integrand, symbol, *integrand.args[:var_index])
|
997 |
+
|
998 |
+
|
999 |
+
_special_function_patterns: list[tuple[Type, Expr, Callable | None, tuple]] = []
|
1000 |
+
_wilds = []
|
1001 |
+
_symbol = Dummy('x')
|
1002 |
+
|
1003 |
+
|
1004 |
+
def special_function_rule(integral):
|
1005 |
+
integrand, symbol = integral
|
1006 |
+
if not _special_function_patterns:
|
1007 |
+
a = Wild('a', exclude=[_symbol], properties=[lambda x: not x.is_zero])
|
1008 |
+
b = Wild('b', exclude=[_symbol])
|
1009 |
+
c = Wild('c', exclude=[_symbol])
|
1010 |
+
d = Wild('d', exclude=[_symbol], properties=[lambda x: not x.is_zero])
|
1011 |
+
e = Wild('e', exclude=[_symbol], properties=[
|
1012 |
+
lambda x: not (x.is_nonnegative and x.is_integer)])
|
1013 |
+
_wilds.extend((a, b, c, d, e))
|
1014 |
+
# patterns consist of a SymPy class, a wildcard expr, an optional
|
1015 |
+
# condition coded as a lambda (when Wild properties are not enough),
|
1016 |
+
# followed by an applicable rule
|
1017 |
+
linear_pattern = a*_symbol + b
|
1018 |
+
quadratic_pattern = a*_symbol**2 + b*_symbol + c
|
1019 |
+
_special_function_patterns.extend((
|
1020 |
+
(Mul, exp(linear_pattern, evaluate=False)/_symbol, None, EiRule),
|
1021 |
+
(Mul, cos(linear_pattern, evaluate=False)/_symbol, None, CiRule),
|
1022 |
+
(Mul, cosh(linear_pattern, evaluate=False)/_symbol, None, ChiRule),
|
1023 |
+
(Mul, sin(linear_pattern, evaluate=False)/_symbol, None, SiRule),
|
1024 |
+
(Mul, sinh(linear_pattern, evaluate=False)/_symbol, None, ShiRule),
|
1025 |
+
(Pow, 1/log(linear_pattern, evaluate=False), None, LiRule),
|
1026 |
+
(exp, exp(quadratic_pattern, evaluate=False), None, ErfRule),
|
1027 |
+
(sin, sin(quadratic_pattern, evaluate=False), None, FresnelSRule),
|
1028 |
+
(cos, cos(quadratic_pattern, evaluate=False), None, FresnelCRule),
|
1029 |
+
(Mul, _symbol**e*exp(a*_symbol, evaluate=False), None, UpperGammaRule),
|
1030 |
+
(Mul, polylog(b, a*_symbol, evaluate=False)/_symbol, None, PolylogRule),
|
1031 |
+
(Pow, 1/sqrt(a - d*sin(_symbol, evaluate=False)**2),
|
1032 |
+
lambda a, d: a != d, EllipticFRule),
|
1033 |
+
(Pow, sqrt(a - d*sin(_symbol, evaluate=False)**2),
|
1034 |
+
lambda a, d: a != d, EllipticERule),
|
1035 |
+
))
|
1036 |
+
_integrand = integrand.subs(symbol, _symbol)
|
1037 |
+
for type_, pattern, constraint, rule in _special_function_patterns:
|
1038 |
+
if isinstance(_integrand, type_):
|
1039 |
+
match = _integrand.match(pattern)
|
1040 |
+
if match:
|
1041 |
+
wild_vals = tuple(match.get(w) for w in _wilds
|
1042 |
+
if match.get(w) is not None)
|
1043 |
+
if constraint is None or constraint(*wild_vals):
|
1044 |
+
return rule(integrand, symbol, *wild_vals)
|
1045 |
+
|
1046 |
+
|
1047 |
+
def _add_degenerate_step(generic_cond, generic_step: Rule, degenerate_step: Rule | None) -> Rule:
|
1048 |
+
if degenerate_step is None:
|
1049 |
+
return generic_step
|
1050 |
+
if isinstance(generic_step, PiecewiseRule):
|
1051 |
+
subfunctions = [(substep, (cond & generic_cond).simplify())
|
1052 |
+
for substep, cond in generic_step.subfunctions]
|
1053 |
+
else:
|
1054 |
+
subfunctions = [(generic_step, generic_cond)]
|
1055 |
+
if isinstance(degenerate_step, PiecewiseRule):
|
1056 |
+
subfunctions += degenerate_step.subfunctions
|
1057 |
+
else:
|
1058 |
+
subfunctions.append((degenerate_step, S.true))
|
1059 |
+
return PiecewiseRule(generic_step.integrand, generic_step.variable, subfunctions)
|
1060 |
+
|
1061 |
+
|
1062 |
+
def nested_pow_rule(integral: IntegralInfo):
|
1063 |
+
# nested (c*(a+b*x)**d)**e
|
1064 |
+
integrand, x = integral
|
1065 |
+
|
1066 |
+
a_ = Wild('a', exclude=[x])
|
1067 |
+
b_ = Wild('b', exclude=[x, 0])
|
1068 |
+
pattern = a_+b_*x
|
1069 |
+
generic_cond = S.true
|
1070 |
+
|
1071 |
+
class NoMatch(Exception):
|
1072 |
+
pass
|
1073 |
+
|
1074 |
+
def _get_base_exp(expr: Expr) -> tuple[Expr, Expr]:
|
1075 |
+
if not expr.has_free(x):
|
1076 |
+
return S.One, S.Zero
|
1077 |
+
if expr.is_Mul:
|
1078 |
+
_, terms = expr.as_coeff_mul()
|
1079 |
+
if not terms:
|
1080 |
+
return S.One, S.Zero
|
1081 |
+
results = [_get_base_exp(term) for term in terms]
|
1082 |
+
bases = {b for b, _ in results}
|
1083 |
+
bases.discard(S.One)
|
1084 |
+
if len(bases) == 1:
|
1085 |
+
return bases.pop(), Add(*(e for _, e in results))
|
1086 |
+
raise NoMatch
|
1087 |
+
if expr.is_Pow:
|
1088 |
+
b, e = expr.base, expr.exp # type: ignore
|
1089 |
+
if e.has_free(x):
|
1090 |
+
raise NoMatch
|
1091 |
+
base_, sub_exp = _get_base_exp(b)
|
1092 |
+
return base_, sub_exp * e
|
1093 |
+
match = expr.match(pattern)
|
1094 |
+
if match:
|
1095 |
+
a, b = match[a_], match[b_]
|
1096 |
+
base_ = x + a/b
|
1097 |
+
nonlocal generic_cond
|
1098 |
+
generic_cond = Ne(b, 0)
|
1099 |
+
return base_, S.One
|
1100 |
+
raise NoMatch
|
1101 |
+
|
1102 |
+
try:
|
1103 |
+
base, exp_ = _get_base_exp(integrand)
|
1104 |
+
except NoMatch:
|
1105 |
+
return
|
1106 |
+
if generic_cond is S.true:
|
1107 |
+
degenerate_step = None
|
1108 |
+
else:
|
1109 |
+
# equivalent with subs(b, 0) but no need to find b
|
1110 |
+
degenerate_step = ConstantRule(integrand.subs(x, 0), x)
|
1111 |
+
generic_step = NestedPowRule(integrand, x, base, exp_)
|
1112 |
+
return _add_degenerate_step(generic_cond, generic_step, degenerate_step)
|
1113 |
+
|
1114 |
+
|
1115 |
+
def inverse_trig_rule(integral: IntegralInfo, degenerate=True):
|
1116 |
+
"""
|
1117 |
+
Set degenerate=False on recursive call where coefficient of quadratic term
|
1118 |
+
is assumed non-zero.
|
1119 |
+
"""
|
1120 |
+
integrand, symbol = integral
|
1121 |
+
base, exp = integrand.as_base_exp()
|
1122 |
+
a = Wild('a', exclude=[symbol])
|
1123 |
+
b = Wild('b', exclude=[symbol])
|
1124 |
+
c = Wild('c', exclude=[symbol, 0])
|
1125 |
+
match = base.match(a + b*symbol + c*symbol**2)
|
1126 |
+
|
1127 |
+
if not match:
|
1128 |
+
return
|
1129 |
+
|
1130 |
+
def make_inverse_trig(RuleClass, a, sign_a, c, sign_c, h) -> Rule:
|
1131 |
+
u_var = Dummy("u")
|
1132 |
+
rewritten = 1/sqrt(sign_a*a + sign_c*c*(symbol-h)**2) # a>0, c>0
|
1133 |
+
quadratic_base = sqrt(c/a)*(symbol-h)
|
1134 |
+
constant = 1/sqrt(c)
|
1135 |
+
u_func = None
|
1136 |
+
if quadratic_base is not symbol:
|
1137 |
+
u_func = quadratic_base
|
1138 |
+
quadratic_base = u_var
|
1139 |
+
standard_form = 1/sqrt(sign_a + sign_c*quadratic_base**2)
|
1140 |
+
substep = RuleClass(standard_form, quadratic_base)
|
1141 |
+
if constant != 1:
|
1142 |
+
substep = ConstantTimesRule(constant*standard_form, symbol, constant, standard_form, substep)
|
1143 |
+
if u_func is not None:
|
1144 |
+
substep = URule(rewritten, symbol, u_var, u_func, substep)
|
1145 |
+
if h != 0:
|
1146 |
+
substep = CompleteSquareRule(integrand, symbol, rewritten, substep)
|
1147 |
+
return substep
|
1148 |
+
|
1149 |
+
a, b, c = [match.get(i, S.Zero) for i in (a, b, c)]
|
1150 |
+
generic_cond = Ne(c, 0)
|
1151 |
+
if not degenerate or generic_cond is S.true:
|
1152 |
+
degenerate_step = None
|
1153 |
+
elif b.is_zero:
|
1154 |
+
degenerate_step = ConstantRule(a ** exp, symbol)
|
1155 |
+
else:
|
1156 |
+
degenerate_step = sqrt_linear_rule(IntegralInfo((a + b * symbol) ** exp, symbol))
|
1157 |
+
|
1158 |
+
if simplify(2*exp + 1) == 0:
|
1159 |
+
h, k = -b/(2*c), a - b**2/(4*c) # rewrite base to k + c*(symbol-h)**2
|
1160 |
+
non_square_cond = Ne(k, 0)
|
1161 |
+
square_step = None
|
1162 |
+
if non_square_cond is not S.true:
|
1163 |
+
square_step = NestedPowRule(1/sqrt(c*(symbol-h)**2), symbol, symbol-h, S.NegativeOne)
|
1164 |
+
if non_square_cond is S.false:
|
1165 |
+
return square_step
|
1166 |
+
generic_step = ReciprocalSqrtQuadraticRule(integrand, symbol, a, b, c)
|
1167 |
+
step = _add_degenerate_step(non_square_cond, generic_step, square_step)
|
1168 |
+
if k.is_real and c.is_real:
|
1169 |
+
# list of ((rule, base_exp, a, sign_a, b, sign_b), condition)
|
1170 |
+
rules = []
|
1171 |
+
for args, cond in ( # don't apply ArccoshRule to x**2-1
|
1172 |
+
((ArcsinRule, k, 1, -c, -1, h), And(k > 0, c < 0)), # 1-x**2
|
1173 |
+
((ArcsinhRule, k, 1, c, 1, h), And(k > 0, c > 0)), # 1+x**2
|
1174 |
+
):
|
1175 |
+
if cond is S.true:
|
1176 |
+
return make_inverse_trig(*args)
|
1177 |
+
if cond is not S.false:
|
1178 |
+
rules.append((make_inverse_trig(*args), cond))
|
1179 |
+
if rules:
|
1180 |
+
if not k.is_positive: # conditions are not thorough, need fall back rule
|
1181 |
+
rules.append((generic_step, S.true))
|
1182 |
+
step = PiecewiseRule(integrand, symbol, rules)
|
1183 |
+
else:
|
1184 |
+
step = generic_step
|
1185 |
+
return _add_degenerate_step(generic_cond, step, degenerate_step)
|
1186 |
+
if exp == S.Half:
|
1187 |
+
step = SqrtQuadraticRule(integrand, symbol, a, b, c)
|
1188 |
+
return _add_degenerate_step(generic_cond, step, degenerate_step)
|
1189 |
+
|
1190 |
+
|
1191 |
+
def add_rule(integral):
|
1192 |
+
integrand, symbol = integral
|
1193 |
+
results = [integral_steps(g, symbol)
|
1194 |
+
for g in integrand.as_ordered_terms()]
|
1195 |
+
return None if None in results else AddRule(integrand, symbol, results)
|
1196 |
+
|
1197 |
+
|
1198 |
+
def mul_rule(integral: IntegralInfo):
|
1199 |
+
integrand, symbol = integral
|
1200 |
+
|
1201 |
+
# Constant times function case
|
1202 |
+
coeff, f = integrand.as_independent(symbol)
|
1203 |
+
if coeff != 1:
|
1204 |
+
next_step = integral_steps(f, symbol)
|
1205 |
+
if next_step is not None:
|
1206 |
+
return ConstantTimesRule(integrand, symbol, coeff, f, next_step)
|
1207 |
+
|
1208 |
+
|
1209 |
+
def _parts_rule(integrand, symbol) -> tuple[Expr, Expr, Expr, Expr, Rule] | None:
|
1210 |
+
# LIATE rule:
|
1211 |
+
# log, inverse trig, algebraic, trigonometric, exponential
|
1212 |
+
def pull_out_algebraic(integrand):
|
1213 |
+
integrand = integrand.cancel().together()
|
1214 |
+
# iterating over Piecewise args would not work here
|
1215 |
+
algebraic = ([] if isinstance(integrand, Piecewise) or not integrand.is_Mul
|
1216 |
+
else [arg for arg in integrand.args if arg.is_algebraic_expr(symbol)])
|
1217 |
+
if algebraic:
|
1218 |
+
u = Mul(*algebraic)
|
1219 |
+
dv = (integrand / u).cancel()
|
1220 |
+
return u, dv
|
1221 |
+
|
1222 |
+
def pull_out_u(*functions) -> Callable[[Expr], tuple[Expr, Expr] | None]:
|
1223 |
+
def pull_out_u_rl(integrand: Expr) -> tuple[Expr, Expr] | None:
|
1224 |
+
if any(integrand.has(f) for f in functions):
|
1225 |
+
args = [arg for arg in integrand.args
|
1226 |
+
if any(isinstance(arg, cls) for cls in functions)]
|
1227 |
+
if args:
|
1228 |
+
u = Mul(*args)
|
1229 |
+
dv = integrand / u
|
1230 |
+
return u, dv
|
1231 |
+
return None
|
1232 |
+
|
1233 |
+
return pull_out_u_rl
|
1234 |
+
|
1235 |
+
liate_rules = [pull_out_u(log), pull_out_u(*inverse_trig_functions),
|
1236 |
+
pull_out_algebraic, pull_out_u(sin, cos),
|
1237 |
+
pull_out_u(exp)]
|
1238 |
+
|
1239 |
+
|
1240 |
+
dummy = Dummy("temporary")
|
1241 |
+
# we can integrate log(x) and atan(x) by setting dv = 1
|
1242 |
+
if isinstance(integrand, (log, *inverse_trig_functions)):
|
1243 |
+
integrand = dummy * integrand
|
1244 |
+
|
1245 |
+
for index, rule in enumerate(liate_rules):
|
1246 |
+
result = rule(integrand)
|
1247 |
+
|
1248 |
+
if result:
|
1249 |
+
u, dv = result
|
1250 |
+
|
1251 |
+
# Don't pick u to be a constant if possible
|
1252 |
+
if symbol not in u.free_symbols and not u.has(dummy):
|
1253 |
+
return None
|
1254 |
+
|
1255 |
+
u = u.subs(dummy, 1)
|
1256 |
+
dv = dv.subs(dummy, 1)
|
1257 |
+
|
1258 |
+
# Don't pick a non-polynomial algebraic to be differentiated
|
1259 |
+
if rule == pull_out_algebraic and not u.is_polynomial(symbol):
|
1260 |
+
return None
|
1261 |
+
# Don't trade one logarithm for another
|
1262 |
+
if isinstance(u, log):
|
1263 |
+
rec_dv = 1/dv
|
1264 |
+
if (rec_dv.is_polynomial(symbol) and
|
1265 |
+
degree(rec_dv, symbol) == 1):
|
1266 |
+
return None
|
1267 |
+
|
1268 |
+
# Can integrate a polynomial times OrthogonalPolynomial
|
1269 |
+
if rule == pull_out_algebraic:
|
1270 |
+
if dv.is_Derivative or dv.has(TrigonometricFunction) or \
|
1271 |
+
isinstance(dv, OrthogonalPolynomial):
|
1272 |
+
v_step = integral_steps(dv, symbol)
|
1273 |
+
if v_step.contains_dont_know():
|
1274 |
+
return None
|
1275 |
+
else:
|
1276 |
+
du = u.diff(symbol)
|
1277 |
+
v = v_step.eval()
|
1278 |
+
return u, dv, v, du, v_step
|
1279 |
+
|
1280 |
+
# make sure dv is amenable to integration
|
1281 |
+
accept = False
|
1282 |
+
if index < 2: # log and inverse trig are usually worth trying
|
1283 |
+
accept = True
|
1284 |
+
elif (rule == pull_out_algebraic and dv.args and
|
1285 |
+
all(isinstance(a, (sin, cos, exp))
|
1286 |
+
for a in dv.args)):
|
1287 |
+
accept = True
|
1288 |
+
else:
|
1289 |
+
for lrule in liate_rules[index + 1:]:
|
1290 |
+
r = lrule(integrand)
|
1291 |
+
if r and r[0].subs(dummy, 1).equals(dv):
|
1292 |
+
accept = True
|
1293 |
+
break
|
1294 |
+
|
1295 |
+
if accept:
|
1296 |
+
du = u.diff(symbol)
|
1297 |
+
v_step = integral_steps(simplify(dv), symbol)
|
1298 |
+
if not v_step.contains_dont_know():
|
1299 |
+
v = v_step.eval()
|
1300 |
+
return u, dv, v, du, v_step
|
1301 |
+
return None
|
1302 |
+
|
1303 |
+
|
1304 |
+
def parts_rule(integral):
|
1305 |
+
integrand, symbol = integral
|
1306 |
+
constant, integrand = integrand.as_coeff_Mul()
|
1307 |
+
|
1308 |
+
result = _parts_rule(integrand, symbol)
|
1309 |
+
|
1310 |
+
steps = []
|
1311 |
+
if result:
|
1312 |
+
u, dv, v, du, v_step = result
|
1313 |
+
debug("u : {}, dv : {}, v : {}, du : {}, v_step: {}".format(u, dv, v, du, v_step))
|
1314 |
+
steps.append(result)
|
1315 |
+
|
1316 |
+
if isinstance(v, Integral):
|
1317 |
+
return
|
1318 |
+
|
1319 |
+
# Set a limit on the number of times u can be used
|
1320 |
+
if isinstance(u, (sin, cos, exp, sinh, cosh)):
|
1321 |
+
cachekey = u.xreplace({symbol: _cache_dummy})
|
1322 |
+
if _parts_u_cache[cachekey] > 2:
|
1323 |
+
return
|
1324 |
+
_parts_u_cache[cachekey] += 1
|
1325 |
+
|
1326 |
+
# Try cyclic integration by parts a few times
|
1327 |
+
for _ in range(4):
|
1328 |
+
debug("Cyclic integration {} with v: {}, du: {}, integrand: {}".format(_, v, du, integrand))
|
1329 |
+
coefficient = ((v * du) / integrand).cancel()
|
1330 |
+
if coefficient == 1:
|
1331 |
+
break
|
1332 |
+
if symbol not in coefficient.free_symbols:
|
1333 |
+
rule = CyclicPartsRule(integrand, symbol,
|
1334 |
+
[PartsRule(None, None, u, dv, v_step, None)
|
1335 |
+
for (u, dv, v, du, v_step) in steps],
|
1336 |
+
(-1) ** len(steps) * coefficient)
|
1337 |
+
if (constant != 1) and rule:
|
1338 |
+
rule = ConstantTimesRule(constant * integrand, symbol, constant, integrand, rule)
|
1339 |
+
return rule
|
1340 |
+
|
1341 |
+
# _parts_rule is sensitive to constants, factor it out
|
1342 |
+
next_constant, next_integrand = (v * du).as_coeff_Mul()
|
1343 |
+
result = _parts_rule(next_integrand, symbol)
|
1344 |
+
|
1345 |
+
if result:
|
1346 |
+
u, dv, v, du, v_step = result
|
1347 |
+
u *= next_constant
|
1348 |
+
du *= next_constant
|
1349 |
+
steps.append((u, dv, v, du, v_step))
|
1350 |
+
else:
|
1351 |
+
break
|
1352 |
+
|
1353 |
+
def make_second_step(steps, integrand):
|
1354 |
+
if steps:
|
1355 |
+
u, dv, v, du, v_step = steps[0]
|
1356 |
+
return PartsRule(integrand, symbol, u, dv, v_step, make_second_step(steps[1:], v * du))
|
1357 |
+
return integral_steps(integrand, symbol)
|
1358 |
+
|
1359 |
+
if steps:
|
1360 |
+
u, dv, v, du, v_step = steps[0]
|
1361 |
+
rule = PartsRule(integrand, symbol, u, dv, v_step, make_second_step(steps[1:], v * du))
|
1362 |
+
if (constant != 1) and rule:
|
1363 |
+
rule = ConstantTimesRule(constant * integrand, symbol, constant, integrand, rule)
|
1364 |
+
return rule
|
1365 |
+
|
1366 |
+
|
1367 |
+
def trig_rule(integral):
|
1368 |
+
integrand, symbol = integral
|
1369 |
+
if integrand == sin(symbol):
|
1370 |
+
return SinRule(integrand, symbol)
|
1371 |
+
if integrand == cos(symbol):
|
1372 |
+
return CosRule(integrand, symbol)
|
1373 |
+
if integrand == sec(symbol)**2:
|
1374 |
+
return Sec2Rule(integrand, symbol)
|
1375 |
+
if integrand == csc(symbol)**2:
|
1376 |
+
return Csc2Rule(integrand, symbol)
|
1377 |
+
|
1378 |
+
if isinstance(integrand, tan):
|
1379 |
+
rewritten = sin(*integrand.args) / cos(*integrand.args)
|
1380 |
+
elif isinstance(integrand, cot):
|
1381 |
+
rewritten = cos(*integrand.args) / sin(*integrand.args)
|
1382 |
+
elif isinstance(integrand, sec):
|
1383 |
+
arg = integrand.args[0]
|
1384 |
+
rewritten = ((sec(arg)**2 + tan(arg) * sec(arg)) /
|
1385 |
+
(sec(arg) + tan(arg)))
|
1386 |
+
elif isinstance(integrand, csc):
|
1387 |
+
arg = integrand.args[0]
|
1388 |
+
rewritten = ((csc(arg)**2 + cot(arg) * csc(arg)) /
|
1389 |
+
(csc(arg) + cot(arg)))
|
1390 |
+
else:
|
1391 |
+
return
|
1392 |
+
|
1393 |
+
return RewriteRule(integrand, symbol, rewritten, integral_steps(rewritten, symbol))
|
1394 |
+
|
1395 |
+
def trig_product_rule(integral: IntegralInfo):
|
1396 |
+
integrand, symbol = integral
|
1397 |
+
if integrand == sec(symbol) * tan(symbol):
|
1398 |
+
return SecTanRule(integrand, symbol)
|
1399 |
+
if integrand == csc(symbol) * cot(symbol):
|
1400 |
+
return CscCotRule(integrand, symbol)
|
1401 |
+
|
1402 |
+
|
1403 |
+
def quadratic_denom_rule(integral):
|
1404 |
+
integrand, symbol = integral
|
1405 |
+
a = Wild('a', exclude=[symbol])
|
1406 |
+
b = Wild('b', exclude=[symbol])
|
1407 |
+
c = Wild('c', exclude=[symbol])
|
1408 |
+
|
1409 |
+
match = integrand.match(a / (b * symbol ** 2 + c))
|
1410 |
+
|
1411 |
+
if match:
|
1412 |
+
a, b, c = match[a], match[b], match[c]
|
1413 |
+
general_rule = ArctanRule(integrand, symbol, a, b, c)
|
1414 |
+
if b.is_extended_real and c.is_extended_real:
|
1415 |
+
positive_cond = c/b > 0
|
1416 |
+
if positive_cond is S.true:
|
1417 |
+
return general_rule
|
1418 |
+
coeff = a/(2*sqrt(-c)*sqrt(b))
|
1419 |
+
constant = sqrt(-c/b)
|
1420 |
+
r1 = 1/(symbol-constant)
|
1421 |
+
r2 = 1/(symbol+constant)
|
1422 |
+
log_steps = [ReciprocalRule(r1, symbol, symbol-constant),
|
1423 |
+
ConstantTimesRule(-r2, symbol, -1, r2, ReciprocalRule(r2, symbol, symbol+constant))]
|
1424 |
+
rewritten = sub = r1 - r2
|
1425 |
+
negative_step = AddRule(sub, symbol, log_steps)
|
1426 |
+
if coeff != 1:
|
1427 |
+
rewritten = Mul(coeff, sub, evaluate=False)
|
1428 |
+
negative_step = ConstantTimesRule(rewritten, symbol, coeff, sub, negative_step)
|
1429 |
+
negative_step = RewriteRule(integrand, symbol, rewritten, negative_step)
|
1430 |
+
if positive_cond is S.false:
|
1431 |
+
return negative_step
|
1432 |
+
return PiecewiseRule(integrand, symbol, [(general_rule, positive_cond), (negative_step, S.true)])
|
1433 |
+
return general_rule
|
1434 |
+
|
1435 |
+
d = Wild('d', exclude=[symbol])
|
1436 |
+
match2 = integrand.match(a / (b * symbol ** 2 + c * symbol + d))
|
1437 |
+
if match2:
|
1438 |
+
b, c = match2[b], match2[c]
|
1439 |
+
if b.is_zero:
|
1440 |
+
return
|
1441 |
+
u = Dummy('u')
|
1442 |
+
u_func = symbol + c/(2*b)
|
1443 |
+
integrand2 = integrand.subs(symbol, u - c / (2*b))
|
1444 |
+
next_step = integral_steps(integrand2, u)
|
1445 |
+
if next_step:
|
1446 |
+
return URule(integrand2, symbol, u, u_func, next_step)
|
1447 |
+
else:
|
1448 |
+
return
|
1449 |
+
e = Wild('e', exclude=[symbol])
|
1450 |
+
match3 = integrand.match((a* symbol + b) / (c * symbol ** 2 + d * symbol + e))
|
1451 |
+
if match3:
|
1452 |
+
a, b, c, d, e = match3[a], match3[b], match3[c], match3[d], match3[e]
|
1453 |
+
if c.is_zero:
|
1454 |
+
return
|
1455 |
+
denominator = c * symbol**2 + d * symbol + e
|
1456 |
+
const = a/(2*c)
|
1457 |
+
numer1 = (2*c*symbol+d)
|
1458 |
+
numer2 = - const*d + b
|
1459 |
+
u = Dummy('u')
|
1460 |
+
step1 = URule(integrand, symbol,
|
1461 |
+
u, denominator, integral_steps(u**(-1), u))
|
1462 |
+
if const != 1:
|
1463 |
+
step1 = ConstantTimesRule(const*numer1/denominator, symbol,
|
1464 |
+
const, numer1/denominator, step1)
|
1465 |
+
if numer2.is_zero:
|
1466 |
+
return step1
|
1467 |
+
step2 = integral_steps(numer2/denominator, symbol)
|
1468 |
+
substeps = AddRule(integrand, symbol, [step1, step2])
|
1469 |
+
rewriten = const*numer1/denominator+numer2/denominator
|
1470 |
+
return RewriteRule(integrand, symbol, rewriten, substeps)
|
1471 |
+
|
1472 |
+
return
|
1473 |
+
|
1474 |
+
|
1475 |
+
def sqrt_linear_rule(integral: IntegralInfo):
|
1476 |
+
"""
|
1477 |
+
Substitute common (a+b*x)**(1/n)
|
1478 |
+
"""
|
1479 |
+
integrand, x = integral
|
1480 |
+
a = Wild('a', exclude=[x])
|
1481 |
+
b = Wild('b', exclude=[x, 0])
|
1482 |
+
a0 = b0 = 0
|
1483 |
+
bases, qs, bs = [], [], []
|
1484 |
+
for pow_ in integrand.find(Pow): # collect all (a+b*x)**(p/q)
|
1485 |
+
base, exp_ = pow_.base, pow_.exp
|
1486 |
+
if exp_.is_Integer or x not in base.free_symbols: # skip 1/x and sqrt(2)
|
1487 |
+
continue
|
1488 |
+
if not exp_.is_Rational: # exclude x**pi
|
1489 |
+
return
|
1490 |
+
match = base.match(a+b*x)
|
1491 |
+
if not match: # skip non-linear
|
1492 |
+
continue # for sqrt(x+sqrt(x)), although base is non-linear, we can still substitute sqrt(x)
|
1493 |
+
a1, b1 = match[a], match[b]
|
1494 |
+
if a0*b1 != a1*b0 or not (b0/b1).is_nonnegative: # cannot transform sqrt(x) to sqrt(x+1) or sqrt(-x)
|
1495 |
+
return
|
1496 |
+
if b0 == 0 or (b0/b1 > 1) is S.true: # choose the latter of sqrt(2*x) and sqrt(x) as representative
|
1497 |
+
a0, b0 = a1, b1
|
1498 |
+
bases.append(base)
|
1499 |
+
bs.append(b1)
|
1500 |
+
qs.append(exp_.q)
|
1501 |
+
if b0 == 0: # no such pattern found
|
1502 |
+
return
|
1503 |
+
q0: Integer = lcm_list(qs)
|
1504 |
+
u_x = (a0 + b0*x)**(1/q0)
|
1505 |
+
u = Dummy("u")
|
1506 |
+
substituted = integrand.subs({base**(S.One/q): (b/b0)**(S.One/q)*u**(q0/q)
|
1507 |
+
for base, b, q in zip(bases, bs, qs)}).subs(x, (u**q0-a0)/b0)
|
1508 |
+
substep = integral_steps(substituted*u**(q0-1)*q0/b0, u)
|
1509 |
+
if not substep.contains_dont_know():
|
1510 |
+
step: Rule = URule(integrand, x, u, u_x, substep)
|
1511 |
+
generic_cond = Ne(b0, 0)
|
1512 |
+
if generic_cond is not S.true: # possible degenerate case
|
1513 |
+
simplified = integrand.subs({b: 0 for b in bs})
|
1514 |
+
degenerate_step = integral_steps(simplified, x)
|
1515 |
+
step = PiecewiseRule(integrand, x, [(step, generic_cond), (degenerate_step, S.true)])
|
1516 |
+
return step
|
1517 |
+
|
1518 |
+
|
1519 |
+
def sqrt_quadratic_rule(integral: IntegralInfo, degenerate=True):
|
1520 |
+
integrand, x = integral
|
1521 |
+
a = Wild('a', exclude=[x])
|
1522 |
+
b = Wild('b', exclude=[x])
|
1523 |
+
c = Wild('c', exclude=[x, 0])
|
1524 |
+
f = Wild('f')
|
1525 |
+
n = Wild('n', properties=[lambda n: n.is_Integer and n.is_odd])
|
1526 |
+
match = integrand.match(f*sqrt(a+b*x+c*x**2)**n)
|
1527 |
+
if not match:
|
1528 |
+
return
|
1529 |
+
a, b, c, f, n = match[a], match[b], match[c], match[f], match[n]
|
1530 |
+
f_poly = f.as_poly(x)
|
1531 |
+
if f_poly is None:
|
1532 |
+
return
|
1533 |
+
|
1534 |
+
generic_cond = Ne(c, 0)
|
1535 |
+
if not degenerate or generic_cond is S.true:
|
1536 |
+
degenerate_step = None
|
1537 |
+
elif b.is_zero:
|
1538 |
+
degenerate_step = integral_steps(f*sqrt(a)**n, x)
|
1539 |
+
else:
|
1540 |
+
degenerate_step = sqrt_linear_rule(IntegralInfo(f*sqrt(a+b*x)**n, x))
|
1541 |
+
|
1542 |
+
def sqrt_quadratic_denom_rule(numer_poly: Poly, integrand: Expr):
|
1543 |
+
denom = sqrt(a+b*x+c*x**2)
|
1544 |
+
deg = numer_poly.degree()
|
1545 |
+
if deg <= 1:
|
1546 |
+
# integrand == (d+e*x)/sqrt(a+b*x+c*x**2)
|
1547 |
+
e, d = numer_poly.all_coeffs() if deg == 1 else (S.Zero, numer_poly.as_expr())
|
1548 |
+
# rewrite numerator to A*(2*c*x+b) + B
|
1549 |
+
A = e/(2*c)
|
1550 |
+
B = d-A*b
|
1551 |
+
pre_substitute = (2*c*x+b)/denom
|
1552 |
+
constant_step: Rule | None = None
|
1553 |
+
linear_step: Rule | None = None
|
1554 |
+
if A != 0:
|
1555 |
+
u = Dummy("u")
|
1556 |
+
pow_rule = PowerRule(1/sqrt(u), u, u, -S.Half)
|
1557 |
+
linear_step = URule(pre_substitute, x, u, a+b*x+c*x**2, pow_rule)
|
1558 |
+
if A != 1:
|
1559 |
+
linear_step = ConstantTimesRule(A*pre_substitute, x, A, pre_substitute, linear_step)
|
1560 |
+
if B != 0:
|
1561 |
+
constant_step = inverse_trig_rule(IntegralInfo(1/denom, x), degenerate=False)
|
1562 |
+
if B != 1:
|
1563 |
+
constant_step = ConstantTimesRule(B/denom, x, B, 1/denom, constant_step) # type: ignore
|
1564 |
+
if linear_step and constant_step:
|
1565 |
+
add = Add(A*pre_substitute, B/denom, evaluate=False)
|
1566 |
+
step: Rule | None = RewriteRule(integrand, x, add, AddRule(add, x, [linear_step, constant_step]))
|
1567 |
+
else:
|
1568 |
+
step = linear_step or constant_step
|
1569 |
+
else:
|
1570 |
+
coeffs = numer_poly.all_coeffs()
|
1571 |
+
step = SqrtQuadraticDenomRule(integrand, x, a, b, c, coeffs)
|
1572 |
+
return step
|
1573 |
+
|
1574 |
+
if n > 0: # rewrite poly * sqrt(s)**(2*k-1) to poly*s**k / sqrt(s)
|
1575 |
+
numer_poly = f_poly * (a+b*x+c*x**2)**((n+1)/2)
|
1576 |
+
rewritten = numer_poly.as_expr()/sqrt(a+b*x+c*x**2)
|
1577 |
+
substep = sqrt_quadratic_denom_rule(numer_poly, rewritten)
|
1578 |
+
generic_step = RewriteRule(integrand, x, rewritten, substep)
|
1579 |
+
elif n == -1:
|
1580 |
+
generic_step = sqrt_quadratic_denom_rule(f_poly, integrand)
|
1581 |
+
else:
|
1582 |
+
return # todo: handle n < -1 case
|
1583 |
+
return _add_degenerate_step(generic_cond, generic_step, degenerate_step)
|
1584 |
+
|
1585 |
+
|
1586 |
+
def hyperbolic_rule(integral: tuple[Expr, Symbol]):
|
1587 |
+
integrand, symbol = integral
|
1588 |
+
if isinstance(integrand, HyperbolicFunction) and integrand.args[0] == symbol:
|
1589 |
+
if integrand.func == sinh:
|
1590 |
+
return SinhRule(integrand, symbol)
|
1591 |
+
if integrand.func == cosh:
|
1592 |
+
return CoshRule(integrand, symbol)
|
1593 |
+
u = Dummy('u')
|
1594 |
+
if integrand.func == tanh:
|
1595 |
+
rewritten = sinh(symbol)/cosh(symbol)
|
1596 |
+
return RewriteRule(integrand, symbol, rewritten,
|
1597 |
+
URule(rewritten, symbol, u, cosh(symbol), ReciprocalRule(1/u, u, u)))
|
1598 |
+
if integrand.func == coth:
|
1599 |
+
rewritten = cosh(symbol)/sinh(symbol)
|
1600 |
+
return RewriteRule(integrand, symbol, rewritten,
|
1601 |
+
URule(rewritten, symbol, u, sinh(symbol), ReciprocalRule(1/u, u, u)))
|
1602 |
+
else:
|
1603 |
+
rewritten = integrand.rewrite(tanh)
|
1604 |
+
if integrand.func == sech:
|
1605 |
+
return RewriteRule(integrand, symbol, rewritten,
|
1606 |
+
URule(rewritten, symbol, u, tanh(symbol/2),
|
1607 |
+
ArctanRule(2/(u**2 + 1), u, S(2), S.One, S.One)))
|
1608 |
+
if integrand.func == csch:
|
1609 |
+
return RewriteRule(integrand, symbol, rewritten,
|
1610 |
+
URule(rewritten, symbol, u, tanh(symbol/2),
|
1611 |
+
ReciprocalRule(1/u, u, u)))
|
1612 |
+
|
1613 |
+
@cacheit
|
1614 |
+
def make_wilds(symbol):
|
1615 |
+
a = Wild('a', exclude=[symbol])
|
1616 |
+
b = Wild('b', exclude=[symbol])
|
1617 |
+
m = Wild('m', exclude=[symbol], properties=[lambda n: isinstance(n, Integer)])
|
1618 |
+
n = Wild('n', exclude=[symbol], properties=[lambda n: isinstance(n, Integer)])
|
1619 |
+
|
1620 |
+
return a, b, m, n
|
1621 |
+
|
1622 |
+
@cacheit
|
1623 |
+
def sincos_pattern(symbol):
|
1624 |
+
a, b, m, n = make_wilds(symbol)
|
1625 |
+
pattern = sin(a*symbol)**m * cos(b*symbol)**n
|
1626 |
+
|
1627 |
+
return pattern, a, b, m, n
|
1628 |
+
|
1629 |
+
@cacheit
|
1630 |
+
def tansec_pattern(symbol):
|
1631 |
+
a, b, m, n = make_wilds(symbol)
|
1632 |
+
pattern = tan(a*symbol)**m * sec(b*symbol)**n
|
1633 |
+
|
1634 |
+
return pattern, a, b, m, n
|
1635 |
+
|
1636 |
+
@cacheit
|
1637 |
+
def cotcsc_pattern(symbol):
|
1638 |
+
a, b, m, n = make_wilds(symbol)
|
1639 |
+
pattern = cot(a*symbol)**m * csc(b*symbol)**n
|
1640 |
+
|
1641 |
+
return pattern, a, b, m, n
|
1642 |
+
|
1643 |
+
@cacheit
|
1644 |
+
def heaviside_pattern(symbol):
|
1645 |
+
m = Wild('m', exclude=[symbol])
|
1646 |
+
b = Wild('b', exclude=[symbol])
|
1647 |
+
g = Wild('g')
|
1648 |
+
pattern = Heaviside(m*symbol + b) * g
|
1649 |
+
|
1650 |
+
return pattern, m, b, g
|
1651 |
+
|
1652 |
+
def uncurry(func):
|
1653 |
+
def uncurry_rl(args):
|
1654 |
+
return func(*args)
|
1655 |
+
return uncurry_rl
|
1656 |
+
|
1657 |
+
def trig_rewriter(rewrite):
|
1658 |
+
def trig_rewriter_rl(args):
|
1659 |
+
a, b, m, n, integrand, symbol = args
|
1660 |
+
rewritten = rewrite(a, b, m, n, integrand, symbol)
|
1661 |
+
if rewritten != integrand:
|
1662 |
+
return RewriteRule(integrand, symbol, rewritten, integral_steps(rewritten, symbol))
|
1663 |
+
return trig_rewriter_rl
|
1664 |
+
|
1665 |
+
sincos_botheven_condition = uncurry(
|
1666 |
+
lambda a, b, m, n, i, s: m.is_even and n.is_even and
|
1667 |
+
m.is_nonnegative and n.is_nonnegative)
|
1668 |
+
|
1669 |
+
sincos_botheven = trig_rewriter(
|
1670 |
+
lambda a, b, m, n, i, symbol: ( (((1 - cos(2*a*symbol)) / 2) ** (m / 2)) *
|
1671 |
+
(((1 + cos(2*b*symbol)) / 2) ** (n / 2)) ))
|
1672 |
+
|
1673 |
+
sincos_sinodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd and m >= 3)
|
1674 |
+
|
1675 |
+
sincos_sinodd = trig_rewriter(
|
1676 |
+
lambda a, b, m, n, i, symbol: ( (1 - cos(a*symbol)**2)**((m - 1) / 2) *
|
1677 |
+
sin(a*symbol) *
|
1678 |
+
cos(b*symbol) ** n))
|
1679 |
+
|
1680 |
+
sincos_cosodd_condition = uncurry(lambda a, b, m, n, i, s: n.is_odd and n >= 3)
|
1681 |
+
|
1682 |
+
sincos_cosodd = trig_rewriter(
|
1683 |
+
lambda a, b, m, n, i, symbol: ( (1 - sin(b*symbol)**2)**((n - 1) / 2) *
|
1684 |
+
cos(b*symbol) *
|
1685 |
+
sin(a*symbol) ** m))
|
1686 |
+
|
1687 |
+
tansec_seceven_condition = uncurry(lambda a, b, m, n, i, s: n.is_even and n >= 4)
|
1688 |
+
tansec_seceven = trig_rewriter(
|
1689 |
+
lambda a, b, m, n, i, symbol: ( (1 + tan(b*symbol)**2) ** (n/2 - 1) *
|
1690 |
+
sec(b*symbol)**2 *
|
1691 |
+
tan(a*symbol) ** m ))
|
1692 |
+
|
1693 |
+
tansec_tanodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd)
|
1694 |
+
tansec_tanodd = trig_rewriter(
|
1695 |
+
lambda a, b, m, n, i, symbol: ( (sec(a*symbol)**2 - 1) ** ((m - 1) / 2) *
|
1696 |
+
tan(a*symbol) *
|
1697 |
+
sec(b*symbol) ** n ))
|
1698 |
+
|
1699 |
+
tan_tansquared_condition = uncurry(lambda a, b, m, n, i, s: m == 2 and n == 0)
|
1700 |
+
tan_tansquared = trig_rewriter(
|
1701 |
+
lambda a, b, m, n, i, symbol: ( sec(a*symbol)**2 - 1))
|
1702 |
+
|
1703 |
+
cotcsc_csceven_condition = uncurry(lambda a, b, m, n, i, s: n.is_even and n >= 4)
|
1704 |
+
cotcsc_csceven = trig_rewriter(
|
1705 |
+
lambda a, b, m, n, i, symbol: ( (1 + cot(b*symbol)**2) ** (n/2 - 1) *
|
1706 |
+
csc(b*symbol)**2 *
|
1707 |
+
cot(a*symbol) ** m ))
|
1708 |
+
|
1709 |
+
cotcsc_cotodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd)
|
1710 |
+
cotcsc_cotodd = trig_rewriter(
|
1711 |
+
lambda a, b, m, n, i, symbol: ( (csc(a*symbol)**2 - 1) ** ((m - 1) / 2) *
|
1712 |
+
cot(a*symbol) *
|
1713 |
+
csc(b*symbol) ** n ))
|
1714 |
+
|
1715 |
+
def trig_sincos_rule(integral):
|
1716 |
+
integrand, symbol = integral
|
1717 |
+
|
1718 |
+
if any(integrand.has(f) for f in (sin, cos)):
|
1719 |
+
pattern, a, b, m, n = sincos_pattern(symbol)
|
1720 |
+
match = integrand.match(pattern)
|
1721 |
+
if not match:
|
1722 |
+
return
|
1723 |
+
|
1724 |
+
return multiplexer({
|
1725 |
+
sincos_botheven_condition: sincos_botheven,
|
1726 |
+
sincos_sinodd_condition: sincos_sinodd,
|
1727 |
+
sincos_cosodd_condition: sincos_cosodd
|
1728 |
+
})(tuple(
|
1729 |
+
[match.get(i, S.Zero) for i in (a, b, m, n)] +
|
1730 |
+
[integrand, symbol]))
|
1731 |
+
|
1732 |
+
def trig_tansec_rule(integral):
|
1733 |
+
integrand, symbol = integral
|
1734 |
+
|
1735 |
+
integrand = integrand.subs({
|
1736 |
+
1 / cos(symbol): sec(symbol)
|
1737 |
+
})
|
1738 |
+
|
1739 |
+
if any(integrand.has(f) for f in (tan, sec)):
|
1740 |
+
pattern, a, b, m, n = tansec_pattern(symbol)
|
1741 |
+
match = integrand.match(pattern)
|
1742 |
+
if not match:
|
1743 |
+
return
|
1744 |
+
|
1745 |
+
return multiplexer({
|
1746 |
+
tansec_tanodd_condition: tansec_tanodd,
|
1747 |
+
tansec_seceven_condition: tansec_seceven,
|
1748 |
+
tan_tansquared_condition: tan_tansquared
|
1749 |
+
})(tuple(
|
1750 |
+
[match.get(i, S.Zero) for i in (a, b, m, n)] +
|
1751 |
+
[integrand, symbol]))
|
1752 |
+
|
1753 |
+
def trig_cotcsc_rule(integral):
|
1754 |
+
integrand, symbol = integral
|
1755 |
+
integrand = integrand.subs({
|
1756 |
+
1 / sin(symbol): csc(symbol),
|
1757 |
+
1 / tan(symbol): cot(symbol),
|
1758 |
+
cos(symbol) / tan(symbol): cot(symbol)
|
1759 |
+
})
|
1760 |
+
|
1761 |
+
if any(integrand.has(f) for f in (cot, csc)):
|
1762 |
+
pattern, a, b, m, n = cotcsc_pattern(symbol)
|
1763 |
+
match = integrand.match(pattern)
|
1764 |
+
if not match:
|
1765 |
+
return
|
1766 |
+
|
1767 |
+
return multiplexer({
|
1768 |
+
cotcsc_cotodd_condition: cotcsc_cotodd,
|
1769 |
+
cotcsc_csceven_condition: cotcsc_csceven
|
1770 |
+
})(tuple(
|
1771 |
+
[match.get(i, S.Zero) for i in (a, b, m, n)] +
|
1772 |
+
[integrand, symbol]))
|
1773 |
+
|
1774 |
+
def trig_sindouble_rule(integral):
|
1775 |
+
integrand, symbol = integral
|
1776 |
+
a = Wild('a', exclude=[sin(2*symbol)])
|
1777 |
+
match = integrand.match(sin(2*symbol)*a)
|
1778 |
+
if match:
|
1779 |
+
sin_double = 2*sin(symbol)*cos(symbol)/sin(2*symbol)
|
1780 |
+
return integral_steps(integrand * sin_double, symbol)
|
1781 |
+
|
1782 |
+
def trig_powers_products_rule(integral):
|
1783 |
+
return do_one(null_safe(trig_sincos_rule),
|
1784 |
+
null_safe(trig_tansec_rule),
|
1785 |
+
null_safe(trig_cotcsc_rule),
|
1786 |
+
null_safe(trig_sindouble_rule))(integral)
|
1787 |
+
|
1788 |
+
def trig_substitution_rule(integral):
|
1789 |
+
integrand, symbol = integral
|
1790 |
+
A = Wild('a', exclude=[0, symbol])
|
1791 |
+
B = Wild('b', exclude=[0, symbol])
|
1792 |
+
theta = Dummy("theta")
|
1793 |
+
target_pattern = A + B*symbol**2
|
1794 |
+
|
1795 |
+
matches = integrand.find(target_pattern)
|
1796 |
+
for expr in matches:
|
1797 |
+
match = expr.match(target_pattern)
|
1798 |
+
a = match.get(A, S.Zero)
|
1799 |
+
b = match.get(B, S.Zero)
|
1800 |
+
|
1801 |
+
a_positive = ((a.is_number and a > 0) or a.is_positive)
|
1802 |
+
b_positive = ((b.is_number and b > 0) or b.is_positive)
|
1803 |
+
a_negative = ((a.is_number and a < 0) or a.is_negative)
|
1804 |
+
b_negative = ((b.is_number and b < 0) or b.is_negative)
|
1805 |
+
x_func = None
|
1806 |
+
if a_positive and b_positive:
|
1807 |
+
# a**2 + b*x**2. Assume sec(theta) > 0, -pi/2 < theta < pi/2
|
1808 |
+
x_func = (sqrt(a)/sqrt(b)) * tan(theta)
|
1809 |
+
# Do not restrict the domain: tan(theta) takes on any real
|
1810 |
+
# value on the interval -pi/2 < theta < pi/2 so x takes on
|
1811 |
+
# any value
|
1812 |
+
restriction = True
|
1813 |
+
elif a_positive and b_negative:
|
1814 |
+
# a**2 - b*x**2. Assume cos(theta) > 0, -pi/2 < theta < pi/2
|
1815 |
+
constant = sqrt(a)/sqrt(-b)
|
1816 |
+
x_func = constant * sin(theta)
|
1817 |
+
restriction = And(symbol > -constant, symbol < constant)
|
1818 |
+
elif a_negative and b_positive:
|
1819 |
+
# b*x**2 - a**2. Assume sin(theta) > 0, 0 < theta < pi
|
1820 |
+
constant = sqrt(-a)/sqrt(b)
|
1821 |
+
x_func = constant * sec(theta)
|
1822 |
+
restriction = And(symbol > -constant, symbol < constant)
|
1823 |
+
if x_func:
|
1824 |
+
# Manually simplify sqrt(trig(theta)**2) to trig(theta)
|
1825 |
+
# Valid due to assumed domain restriction
|
1826 |
+
substitutions = {}
|
1827 |
+
for f in [sin, cos, tan,
|
1828 |
+
sec, csc, cot]:
|
1829 |
+
substitutions[sqrt(f(theta)**2)] = f(theta)
|
1830 |
+
substitutions[sqrt(f(theta)**(-2))] = 1/f(theta)
|
1831 |
+
|
1832 |
+
replaced = integrand.subs(symbol, x_func).trigsimp()
|
1833 |
+
replaced = manual_subs(replaced, substitutions)
|
1834 |
+
if not replaced.has(symbol):
|
1835 |
+
replaced *= manual_diff(x_func, theta)
|
1836 |
+
replaced = replaced.trigsimp()
|
1837 |
+
secants = replaced.find(1/cos(theta))
|
1838 |
+
if secants:
|
1839 |
+
replaced = replaced.xreplace({
|
1840 |
+
1/cos(theta): sec(theta)
|
1841 |
+
})
|
1842 |
+
|
1843 |
+
substep = integral_steps(replaced, theta)
|
1844 |
+
if not substep.contains_dont_know():
|
1845 |
+
return TrigSubstitutionRule(integrand, symbol,
|
1846 |
+
theta, x_func, replaced, substep, restriction)
|
1847 |
+
|
1848 |
+
def heaviside_rule(integral):
|
1849 |
+
integrand, symbol = integral
|
1850 |
+
pattern, m, b, g = heaviside_pattern(symbol)
|
1851 |
+
match = integrand.match(pattern)
|
1852 |
+
if match and 0 != match[g]:
|
1853 |
+
# f = Heaviside(m*x + b)*g
|
1854 |
+
substep = integral_steps(match[g], symbol)
|
1855 |
+
m, b = match[m], match[b]
|
1856 |
+
return HeavisideRule(integrand, symbol, m*symbol + b, -b/m, substep)
|
1857 |
+
|
1858 |
+
|
1859 |
+
def dirac_delta_rule(integral: IntegralInfo):
|
1860 |
+
integrand, x = integral
|
1861 |
+
if len(integrand.args) == 1:
|
1862 |
+
n = S.Zero
|
1863 |
+
else:
|
1864 |
+
n = integrand.args[1]
|
1865 |
+
if not n.is_Integer or n < 0:
|
1866 |
+
return
|
1867 |
+
a, b = Wild('a', exclude=[x]), Wild('b', exclude=[x, 0])
|
1868 |
+
match = integrand.args[0].match(a+b*x)
|
1869 |
+
if not match:
|
1870 |
+
return
|
1871 |
+
a, b = match[a], match[b]
|
1872 |
+
generic_cond = Ne(b, 0)
|
1873 |
+
if generic_cond is S.true:
|
1874 |
+
degenerate_step = None
|
1875 |
+
else:
|
1876 |
+
degenerate_step = ConstantRule(DiracDelta(a, n), x)
|
1877 |
+
generic_step = DiracDeltaRule(integrand, x, n, a, b)
|
1878 |
+
return _add_degenerate_step(generic_cond, generic_step, degenerate_step)
|
1879 |
+
|
1880 |
+
|
1881 |
+
def substitution_rule(integral):
|
1882 |
+
integrand, symbol = integral
|
1883 |
+
|
1884 |
+
u_var = Dummy("u")
|
1885 |
+
substitutions = find_substitutions(integrand, symbol, u_var)
|
1886 |
+
count = 0
|
1887 |
+
if substitutions:
|
1888 |
+
debug("List of Substitution Rules")
|
1889 |
+
ways = []
|
1890 |
+
for u_func, c, substituted in substitutions:
|
1891 |
+
subrule = integral_steps(substituted, u_var)
|
1892 |
+
count = count + 1
|
1893 |
+
debug("Rule {}: {}".format(count, subrule))
|
1894 |
+
|
1895 |
+
if subrule.contains_dont_know():
|
1896 |
+
continue
|
1897 |
+
|
1898 |
+
if simplify(c - 1) != 0:
|
1899 |
+
_, denom = c.as_numer_denom()
|
1900 |
+
if subrule:
|
1901 |
+
subrule = ConstantTimesRule(c * substituted, u_var, c, substituted, subrule)
|
1902 |
+
|
1903 |
+
if denom.free_symbols:
|
1904 |
+
piecewise = []
|
1905 |
+
could_be_zero = []
|
1906 |
+
|
1907 |
+
if isinstance(denom, Mul):
|
1908 |
+
could_be_zero = denom.args
|
1909 |
+
else:
|
1910 |
+
could_be_zero.append(denom)
|
1911 |
+
|
1912 |
+
for expr in could_be_zero:
|
1913 |
+
if not fuzzy_not(expr.is_zero):
|
1914 |
+
substep = integral_steps(manual_subs(integrand, expr, 0), symbol)
|
1915 |
+
|
1916 |
+
if substep:
|
1917 |
+
piecewise.append((
|
1918 |
+
substep,
|
1919 |
+
Eq(expr, 0)
|
1920 |
+
))
|
1921 |
+
piecewise.append((subrule, True))
|
1922 |
+
subrule = PiecewiseRule(substituted, symbol, piecewise)
|
1923 |
+
|
1924 |
+
ways.append(URule(integrand, symbol, u_var, u_func, subrule))
|
1925 |
+
|
1926 |
+
if len(ways) > 1:
|
1927 |
+
return AlternativeRule(integrand, symbol, ways)
|
1928 |
+
elif ways:
|
1929 |
+
return ways[0]
|
1930 |
+
|
1931 |
+
|
1932 |
+
partial_fractions_rule = rewriter(
|
1933 |
+
lambda integrand, symbol: integrand.is_rational_function(),
|
1934 |
+
lambda integrand, symbol: integrand.apart(symbol))
|
1935 |
+
|
1936 |
+
cancel_rule = rewriter(
|
1937 |
+
# lambda integrand, symbol: integrand.is_algebraic_expr(),
|
1938 |
+
# lambda integrand, symbol: isinstance(integrand, Mul),
|
1939 |
+
lambda integrand, symbol: True,
|
1940 |
+
lambda integrand, symbol: integrand.cancel())
|
1941 |
+
|
1942 |
+
distribute_expand_rule = rewriter(
|
1943 |
+
lambda integrand, symbol: (
|
1944 |
+
all(arg.is_Pow or arg.is_polynomial(symbol) for arg in integrand.args)
|
1945 |
+
or isinstance(integrand, Pow)
|
1946 |
+
or isinstance(integrand, Mul)),
|
1947 |
+
lambda integrand, symbol: integrand.expand())
|
1948 |
+
|
1949 |
+
trig_expand_rule = rewriter(
|
1950 |
+
# If there are trig functions with different arguments, expand them
|
1951 |
+
lambda integrand, symbol: (
|
1952 |
+
len({a.args[0] for a in integrand.atoms(TrigonometricFunction)}) > 1),
|
1953 |
+
lambda integrand, symbol: integrand.expand(trig=True))
|
1954 |
+
|
1955 |
+
def derivative_rule(integral):
|
1956 |
+
integrand = integral[0]
|
1957 |
+
diff_variables = integrand.variables
|
1958 |
+
undifferentiated_function = integrand.expr
|
1959 |
+
integrand_variables = undifferentiated_function.free_symbols
|
1960 |
+
|
1961 |
+
if integral.symbol in integrand_variables:
|
1962 |
+
if integral.symbol in diff_variables:
|
1963 |
+
return DerivativeRule(*integral)
|
1964 |
+
else:
|
1965 |
+
return DontKnowRule(integrand, integral.symbol)
|
1966 |
+
else:
|
1967 |
+
return ConstantRule(*integral)
|
1968 |
+
|
1969 |
+
def rewrites_rule(integral):
|
1970 |
+
integrand, symbol = integral
|
1971 |
+
|
1972 |
+
if integrand.match(1/cos(symbol)):
|
1973 |
+
rewritten = integrand.subs(1/cos(symbol), sec(symbol))
|
1974 |
+
return RewriteRule(integrand, symbol, rewritten, integral_steps(rewritten, symbol))
|
1975 |
+
|
1976 |
+
def fallback_rule(integral):
|
1977 |
+
return DontKnowRule(*integral)
|
1978 |
+
|
1979 |
+
# Cache is used to break cyclic integrals.
|
1980 |
+
# Need to use the same dummy variable in cached expressions for them to match.
|
1981 |
+
# Also record "u" of integration by parts, to avoid infinite repetition.
|
1982 |
+
_integral_cache: dict[Expr, Expr | None] = {}
|
1983 |
+
_parts_u_cache: dict[Expr, int] = defaultdict(int)
|
1984 |
+
_cache_dummy = Dummy("z")
|
1985 |
+
|
1986 |
+
def integral_steps(integrand, symbol, **options):
|
1987 |
+
"""Returns the steps needed to compute an integral.
|
1988 |
+
|
1989 |
+
Explanation
|
1990 |
+
===========
|
1991 |
+
|
1992 |
+
This function attempts to mirror what a student would do by hand as
|
1993 |
+
closely as possible.
|
1994 |
+
|
1995 |
+
SymPy Gamma uses this to provide a step-by-step explanation of an
|
1996 |
+
integral. The code it uses to format the results of this function can be
|
1997 |
+
found at
|
1998 |
+
https://github.com/sympy/sympy_gamma/blob/master/app/logic/intsteps.py.
|
1999 |
+
|
2000 |
+
Examples
|
2001 |
+
========
|
2002 |
+
|
2003 |
+
>>> from sympy import exp, sin
|
2004 |
+
>>> from sympy.integrals.manualintegrate import integral_steps
|
2005 |
+
>>> from sympy.abc import x
|
2006 |
+
>>> print(repr(integral_steps(exp(x) / (1 + exp(2 * x)), x))) \
|
2007 |
+
# doctest: +NORMALIZE_WHITESPACE
|
2008 |
+
URule(integrand=exp(x)/(exp(2*x) + 1), variable=x, u_var=_u, u_func=exp(x),
|
2009 |
+
substep=ArctanRule(integrand=1/(_u**2 + 1), variable=_u, a=1, b=1, c=1))
|
2010 |
+
>>> print(repr(integral_steps(sin(x), x))) \
|
2011 |
+
# doctest: +NORMALIZE_WHITESPACE
|
2012 |
+
SinRule(integrand=sin(x), variable=x)
|
2013 |
+
>>> print(repr(integral_steps((x**2 + 3)**2, x))) \
|
2014 |
+
# doctest: +NORMALIZE_WHITESPACE
|
2015 |
+
RewriteRule(integrand=(x**2 + 3)**2, variable=x, rewritten=x**4 + 6*x**2 + 9,
|
2016 |
+
substep=AddRule(integrand=x**4 + 6*x**2 + 9, variable=x,
|
2017 |
+
substeps=[PowerRule(integrand=x**4, variable=x, base=x, exp=4),
|
2018 |
+
ConstantTimesRule(integrand=6*x**2, variable=x, constant=6, other=x**2,
|
2019 |
+
substep=PowerRule(integrand=x**2, variable=x, base=x, exp=2)),
|
2020 |
+
ConstantRule(integrand=9, variable=x)]))
|
2021 |
+
|
2022 |
+
Returns
|
2023 |
+
=======
|
2024 |
+
|
2025 |
+
rule : Rule
|
2026 |
+
The first step; most rules have substeps that must also be
|
2027 |
+
considered. These substeps can be evaluated using ``manualintegrate``
|
2028 |
+
to obtain a result.
|
2029 |
+
|
2030 |
+
"""
|
2031 |
+
cachekey = integrand.xreplace({symbol: _cache_dummy})
|
2032 |
+
if cachekey in _integral_cache:
|
2033 |
+
if _integral_cache[cachekey] is None:
|
2034 |
+
# Stop this attempt, because it leads around in a loop
|
2035 |
+
return DontKnowRule(integrand, symbol)
|
2036 |
+
else:
|
2037 |
+
# TODO: This is for future development, as currently
|
2038 |
+
# _integral_cache gets no values other than None
|
2039 |
+
return (_integral_cache[cachekey].xreplace(_cache_dummy, symbol),
|
2040 |
+
symbol)
|
2041 |
+
else:
|
2042 |
+
_integral_cache[cachekey] = None
|
2043 |
+
|
2044 |
+
integral = IntegralInfo(integrand, symbol)
|
2045 |
+
|
2046 |
+
def key(integral):
|
2047 |
+
integrand = integral.integrand
|
2048 |
+
|
2049 |
+
if symbol not in integrand.free_symbols:
|
2050 |
+
return Number
|
2051 |
+
for cls in (Symbol, TrigonometricFunction, OrthogonalPolynomial):
|
2052 |
+
if isinstance(integrand, cls):
|
2053 |
+
return cls
|
2054 |
+
return type(integrand)
|
2055 |
+
|
2056 |
+
def integral_is_subclass(*klasses):
|
2057 |
+
def _integral_is_subclass(integral):
|
2058 |
+
k = key(integral)
|
2059 |
+
return k and issubclass(k, klasses)
|
2060 |
+
return _integral_is_subclass
|
2061 |
+
|
2062 |
+
result = do_one(
|
2063 |
+
null_safe(special_function_rule),
|
2064 |
+
null_safe(switch(key, {
|
2065 |
+
Pow: do_one(null_safe(power_rule), null_safe(inverse_trig_rule),
|
2066 |
+
null_safe(sqrt_linear_rule),
|
2067 |
+
null_safe(quadratic_denom_rule)),
|
2068 |
+
Symbol: power_rule,
|
2069 |
+
exp: exp_rule,
|
2070 |
+
Add: add_rule,
|
2071 |
+
Mul: do_one(null_safe(mul_rule), null_safe(trig_product_rule),
|
2072 |
+
null_safe(heaviside_rule), null_safe(quadratic_denom_rule),
|
2073 |
+
null_safe(sqrt_linear_rule),
|
2074 |
+
null_safe(sqrt_quadratic_rule)),
|
2075 |
+
Derivative: derivative_rule,
|
2076 |
+
TrigonometricFunction: trig_rule,
|
2077 |
+
Heaviside: heaviside_rule,
|
2078 |
+
DiracDelta: dirac_delta_rule,
|
2079 |
+
OrthogonalPolynomial: orthogonal_poly_rule,
|
2080 |
+
Number: constant_rule
|
2081 |
+
})),
|
2082 |
+
do_one(
|
2083 |
+
null_safe(trig_rule),
|
2084 |
+
null_safe(hyperbolic_rule),
|
2085 |
+
null_safe(alternatives(
|
2086 |
+
rewrites_rule,
|
2087 |
+
substitution_rule,
|
2088 |
+
condition(
|
2089 |
+
integral_is_subclass(Mul, Pow),
|
2090 |
+
partial_fractions_rule),
|
2091 |
+
condition(
|
2092 |
+
integral_is_subclass(Mul, Pow),
|
2093 |
+
cancel_rule),
|
2094 |
+
condition(
|
2095 |
+
integral_is_subclass(Mul, log,
|
2096 |
+
*inverse_trig_functions),
|
2097 |
+
parts_rule),
|
2098 |
+
condition(
|
2099 |
+
integral_is_subclass(Mul, Pow),
|
2100 |
+
distribute_expand_rule),
|
2101 |
+
trig_powers_products_rule,
|
2102 |
+
trig_expand_rule
|
2103 |
+
)),
|
2104 |
+
null_safe(condition(integral_is_subclass(Mul, Pow), nested_pow_rule)),
|
2105 |
+
null_safe(trig_substitution_rule)
|
2106 |
+
),
|
2107 |
+
fallback_rule)(integral)
|
2108 |
+
del _integral_cache[cachekey]
|
2109 |
+
return result
|
2110 |
+
|
2111 |
+
|
2112 |
+
def manualintegrate(f, var):
|
2113 |
+
"""manualintegrate(f, var)
|
2114 |
+
|
2115 |
+
Explanation
|
2116 |
+
===========
|
2117 |
+
|
2118 |
+
Compute indefinite integral of a single variable using an algorithm that
|
2119 |
+
resembles what a student would do by hand.
|
2120 |
+
|
2121 |
+
Unlike :func:`~.integrate`, var can only be a single symbol.
|
2122 |
+
|
2123 |
+
Examples
|
2124 |
+
========
|
2125 |
+
|
2126 |
+
>>> from sympy import sin, cos, tan, exp, log, integrate
|
2127 |
+
>>> from sympy.integrals.manualintegrate import manualintegrate
|
2128 |
+
>>> from sympy.abc import x
|
2129 |
+
>>> manualintegrate(1 / x, x)
|
2130 |
+
log(x)
|
2131 |
+
>>> integrate(1/x)
|
2132 |
+
log(x)
|
2133 |
+
>>> manualintegrate(log(x), x)
|
2134 |
+
x*log(x) - x
|
2135 |
+
>>> integrate(log(x))
|
2136 |
+
x*log(x) - x
|
2137 |
+
>>> manualintegrate(exp(x) / (1 + exp(2 * x)), x)
|
2138 |
+
atan(exp(x))
|
2139 |
+
>>> integrate(exp(x) / (1 + exp(2 * x)))
|
2140 |
+
RootSum(4*_z**2 + 1, Lambda(_i, _i*log(2*_i + exp(x))))
|
2141 |
+
>>> manualintegrate(cos(x)**4 * sin(x), x)
|
2142 |
+
-cos(x)**5/5
|
2143 |
+
>>> integrate(cos(x)**4 * sin(x), x)
|
2144 |
+
-cos(x)**5/5
|
2145 |
+
>>> manualintegrate(cos(x)**4 * sin(x)**3, x)
|
2146 |
+
cos(x)**7/7 - cos(x)**5/5
|
2147 |
+
>>> integrate(cos(x)**4 * sin(x)**3, x)
|
2148 |
+
cos(x)**7/7 - cos(x)**5/5
|
2149 |
+
>>> manualintegrate(tan(x), x)
|
2150 |
+
-log(cos(x))
|
2151 |
+
>>> integrate(tan(x), x)
|
2152 |
+
-log(cos(x))
|
2153 |
+
|
2154 |
+
See Also
|
2155 |
+
========
|
2156 |
+
|
2157 |
+
sympy.integrals.integrals.integrate
|
2158 |
+
sympy.integrals.integrals.Integral.doit
|
2159 |
+
sympy.integrals.integrals.Integral
|
2160 |
+
"""
|
2161 |
+
result = integral_steps(f, var).eval()
|
2162 |
+
# Clear the cache of u-parts
|
2163 |
+
_parts_u_cache.clear()
|
2164 |
+
# If we got Piecewise with two parts, put generic first
|
2165 |
+
if isinstance(result, Piecewise) and len(result.args) == 2:
|
2166 |
+
cond = result.args[0][1]
|
2167 |
+
if isinstance(cond, Eq) and result.args[1][1] == True:
|
2168 |
+
result = result.func(
|
2169 |
+
(result.args[1][0], Ne(*cond.args)),
|
2170 |
+
(result.args[0][0], True))
|
2171 |
+
return result
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/meijerint.py
ADDED
@@ -0,0 +1,2190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Integrate functions by rewriting them as Meijer G-functions.
|
3 |
+
|
4 |
+
There are three user-visible functions that can be used by other parts of the
|
5 |
+
sympy library to solve various integration problems:
|
6 |
+
|
7 |
+
- meijerint_indefinite
|
8 |
+
- meijerint_definite
|
9 |
+
- meijerint_inversion
|
10 |
+
|
11 |
+
They can be used to compute, respectively, indefinite integrals, definite
|
12 |
+
integrals over intervals of the real line, and inverse laplace-type integrals
|
13 |
+
(from c-I*oo to c+I*oo). See the respective docstrings for details.
|
14 |
+
|
15 |
+
The main references for this are:
|
16 |
+
|
17 |
+
[L] Luke, Y. L. (1969), The Special Functions and Their Approximations,
|
18 |
+
Volume 1
|
19 |
+
|
20 |
+
[R] Kelly B. Roach. Meijer G Function Representations.
|
21 |
+
In: Proceedings of the 1997 International Symposium on Symbolic and
|
22 |
+
Algebraic Computation, pages 205-211, New York, 1997. ACM.
|
23 |
+
|
24 |
+
[P] A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990).
|
25 |
+
Integrals and Series: More Special Functions, Vol. 3,.
|
26 |
+
Gordon and Breach Science Publisher
|
27 |
+
"""
|
28 |
+
|
29 |
+
from __future__ import annotations
|
30 |
+
import itertools
|
31 |
+
|
32 |
+
from sympy import SYMPY_DEBUG
|
33 |
+
from sympy.core import S, Expr
|
34 |
+
from sympy.core.add import Add
|
35 |
+
from sympy.core.basic import Basic
|
36 |
+
from sympy.core.cache import cacheit
|
37 |
+
from sympy.core.containers import Tuple
|
38 |
+
from sympy.core.exprtools import factor_terms
|
39 |
+
from sympy.core.function import (expand, expand_mul, expand_power_base,
|
40 |
+
expand_trig, Function)
|
41 |
+
from sympy.core.mul import Mul
|
42 |
+
from sympy.core.numbers import ilcm, Rational, pi
|
43 |
+
from sympy.core.relational import Eq, Ne, _canonical_coeff
|
44 |
+
from sympy.core.sorting import default_sort_key, ordered
|
45 |
+
from sympy.core.symbol import Dummy, symbols, Wild, Symbol
|
46 |
+
from sympy.core.sympify import sympify
|
47 |
+
from sympy.functions.combinatorial.factorials import factorial
|
48 |
+
from sympy.functions.elementary.complexes import (re, im, arg, Abs, sign,
|
49 |
+
unpolarify, polarify, polar_lift, principal_branch, unbranched_argument,
|
50 |
+
periodic_argument)
|
51 |
+
from sympy.functions.elementary.exponential import exp, exp_polar, log
|
52 |
+
from sympy.functions.elementary.integers import ceiling
|
53 |
+
from sympy.functions.elementary.hyperbolic import (cosh, sinh,
|
54 |
+
_rewrite_hyperbolics_as_exp, HyperbolicFunction)
|
55 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
56 |
+
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
|
57 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, sinc,
|
58 |
+
TrigonometricFunction)
|
59 |
+
from sympy.functions.special.bessel import besselj, bessely, besseli, besselk
|
60 |
+
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
|
61 |
+
from sympy.functions.special.elliptic_integrals import elliptic_k, elliptic_e
|
62 |
+
from sympy.functions.special.error_functions import (erf, erfc, erfi, Ei,
|
63 |
+
expint, Si, Ci, Shi, Chi, fresnels, fresnelc)
|
64 |
+
from sympy.functions.special.gamma_functions import gamma
|
65 |
+
from sympy.functions.special.hyper import hyper, meijerg
|
66 |
+
from sympy.functions.special.singularity_functions import SingularityFunction
|
67 |
+
from .integrals import Integral
|
68 |
+
from sympy.logic.boolalg import And, Or, BooleanAtom, Not, BooleanFunction
|
69 |
+
from sympy.polys import cancel, factor
|
70 |
+
from sympy.utilities.iterables import multiset_partitions
|
71 |
+
from sympy.utilities.misc import debug as _debug
|
72 |
+
from sympy.utilities.misc import debugf as _debugf
|
73 |
+
|
74 |
+
# keep this at top for easy reference
|
75 |
+
z = Dummy('z')
|
76 |
+
|
77 |
+
|
78 |
+
def _has(res, *f):
|
79 |
+
# return True if res has f; in the case of Piecewise
|
80 |
+
# only return True if *all* pieces have f
|
81 |
+
res = piecewise_fold(res)
|
82 |
+
if getattr(res, 'is_Piecewise', False):
|
83 |
+
return all(_has(i, *f) for i in res.args)
|
84 |
+
return res.has(*f)
|
85 |
+
|
86 |
+
|
87 |
+
def _create_lookup_table(table):
|
88 |
+
""" Add formulae for the function -> meijerg lookup table. """
|
89 |
+
def wild(n):
|
90 |
+
return Wild(n, exclude=[z])
|
91 |
+
p, q, a, b, c = list(map(wild, 'pqabc'))
|
92 |
+
n = Wild('n', properties=[lambda x: x.is_Integer and x > 0])
|
93 |
+
t = p*z**q
|
94 |
+
|
95 |
+
def add(formula, an, ap, bm, bq, arg=t, fac=S.One, cond=True, hint=True):
|
96 |
+
table.setdefault(_mytype(formula, z), []).append((formula,
|
97 |
+
[(fac, meijerg(an, ap, bm, bq, arg))], cond, hint))
|
98 |
+
|
99 |
+
def addi(formula, inst, cond, hint=True):
|
100 |
+
table.setdefault(
|
101 |
+
_mytype(formula, z), []).append((formula, inst, cond, hint))
|
102 |
+
|
103 |
+
def constant(a):
|
104 |
+
return [(a, meijerg([1], [], [], [0], z)),
|
105 |
+
(a, meijerg([], [1], [0], [], z))]
|
106 |
+
table[()] = [(a, constant(a), True, True)]
|
107 |
+
|
108 |
+
# [P], Section 8.
|
109 |
+
class IsNonPositiveInteger(Function):
|
110 |
+
|
111 |
+
@classmethod
|
112 |
+
def eval(cls, arg):
|
113 |
+
arg = unpolarify(arg)
|
114 |
+
if arg.is_Integer is True:
|
115 |
+
return arg <= 0
|
116 |
+
|
117 |
+
# Section 8.4.2
|
118 |
+
# TODO this needs more polar_lift (c/f entry for exp)
|
119 |
+
add(Heaviside(t - b)*(t - b)**(a - 1), [a], [], [], [0], t/b,
|
120 |
+
gamma(a)*b**(a - 1), And(b > 0))
|
121 |
+
add(Heaviside(b - t)*(b - t)**(a - 1), [], [a], [0], [], t/b,
|
122 |
+
gamma(a)*b**(a - 1), And(b > 0))
|
123 |
+
add(Heaviside(z - (b/p)**(1/q))*(t - b)**(a - 1), [a], [], [], [0], t/b,
|
124 |
+
gamma(a)*b**(a - 1), And(b > 0))
|
125 |
+
add(Heaviside((b/p)**(1/q) - z)*(b - t)**(a - 1), [], [a], [0], [], t/b,
|
126 |
+
gamma(a)*b**(a - 1), And(b > 0))
|
127 |
+
add((b + t)**(-a), [1 - a], [], [0], [], t/b, b**(-a)/gamma(a),
|
128 |
+
hint=Not(IsNonPositiveInteger(a)))
|
129 |
+
add(Abs(b - t)**(-a), [1 - a], [(1 - a)/2], [0], [(1 - a)/2], t/b,
|
130 |
+
2*sin(pi*a/2)*gamma(1 - a)*Abs(b)**(-a), re(a) < 1)
|
131 |
+
add((t**a - b**a)/(t - b), [0, a], [], [0, a], [], t/b,
|
132 |
+
b**(a - 1)*sin(a*pi)/pi)
|
133 |
+
|
134 |
+
# 12
|
135 |
+
def A1(r, sign, nu):
|
136 |
+
return pi**Rational(-1, 2)*(-sign*nu/2)**(1 - 2*r)
|
137 |
+
|
138 |
+
def tmpadd(r, sgn):
|
139 |
+
# XXX the a**2 is bad for matching
|
140 |
+
add((sqrt(a**2 + t) + sgn*a)**b/(a**2 + t)**r,
|
141 |
+
[(1 + b)/2, 1 - 2*r + b/2], [],
|
142 |
+
[(b - sgn*b)/2], [(b + sgn*b)/2], t/a**2,
|
143 |
+
a**(b - 2*r)*A1(r, sgn, b))
|
144 |
+
tmpadd(0, 1)
|
145 |
+
tmpadd(0, -1)
|
146 |
+
tmpadd(S.Half, 1)
|
147 |
+
tmpadd(S.Half, -1)
|
148 |
+
|
149 |
+
# 13
|
150 |
+
def tmpadd(r, sgn):
|
151 |
+
add((sqrt(a + p*z**q) + sgn*sqrt(p)*z**(q/2))**b/(a + p*z**q)**r,
|
152 |
+
[1 - r + sgn*b/2], [1 - r - sgn*b/2], [0, S.Half], [],
|
153 |
+
p*z**q/a, a**(b/2 - r)*A1(r, sgn, b))
|
154 |
+
tmpadd(0, 1)
|
155 |
+
tmpadd(0, -1)
|
156 |
+
tmpadd(S.Half, 1)
|
157 |
+
tmpadd(S.Half, -1)
|
158 |
+
# (those after look obscure)
|
159 |
+
|
160 |
+
# Section 8.4.3
|
161 |
+
add(exp(polar_lift(-1)*t), [], [], [0], [])
|
162 |
+
|
163 |
+
# TODO can do sin^n, sinh^n by expansion ... where?
|
164 |
+
# 8.4.4 (hyperbolic functions)
|
165 |
+
add(sinh(t), [], [1], [S.Half], [1, 0], t**2/4, pi**Rational(3, 2))
|
166 |
+
add(cosh(t), [], [S.Half], [0], [S.Half, S.Half], t**2/4, pi**Rational(3, 2))
|
167 |
+
|
168 |
+
# Section 8.4.5
|
169 |
+
# TODO can do t + a. but can also do by expansion... (XXX not really)
|
170 |
+
add(sin(t), [], [], [S.Half], [0], t**2/4, sqrt(pi))
|
171 |
+
add(cos(t), [], [], [0], [S.Half], t**2/4, sqrt(pi))
|
172 |
+
|
173 |
+
# Section 8.4.6 (sinc function)
|
174 |
+
add(sinc(t), [], [], [0], [Rational(-1, 2)], t**2/4, sqrt(pi)/2)
|
175 |
+
|
176 |
+
# Section 8.5.5
|
177 |
+
def make_log1(subs):
|
178 |
+
N = subs[n]
|
179 |
+
return [(S.NegativeOne**N*factorial(N),
|
180 |
+
meijerg([], [1]*(N + 1), [0]*(N + 1), [], t))]
|
181 |
+
|
182 |
+
def make_log2(subs):
|
183 |
+
N = subs[n]
|
184 |
+
return [(factorial(N),
|
185 |
+
meijerg([1]*(N + 1), [], [], [0]*(N + 1), t))]
|
186 |
+
# TODO these only hold for positive p, and can be made more general
|
187 |
+
# but who uses log(x)*Heaviside(a-x) anyway ...
|
188 |
+
# TODO also it would be nice to derive them recursively ...
|
189 |
+
addi(log(t)**n*Heaviside(1 - t), make_log1, True)
|
190 |
+
addi(log(t)**n*Heaviside(t - 1), make_log2, True)
|
191 |
+
|
192 |
+
def make_log3(subs):
|
193 |
+
return make_log1(subs) + make_log2(subs)
|
194 |
+
addi(log(t)**n, make_log3, True)
|
195 |
+
addi(log(t + a),
|
196 |
+
constant(log(a)) + [(S.One, meijerg([1, 1], [], [1], [0], t/a))],
|
197 |
+
True)
|
198 |
+
addi(log(Abs(t - a)), constant(log(Abs(a))) +
|
199 |
+
[(pi, meijerg([1, 1], [S.Half], [1], [0, S.Half], t/a))],
|
200 |
+
True)
|
201 |
+
# TODO log(x)/(x+a) and log(x)/(x-1) can also be done. should they
|
202 |
+
# be derivable?
|
203 |
+
# TODO further formulae in this section seem obscure
|
204 |
+
|
205 |
+
# Sections 8.4.9-10
|
206 |
+
# TODO
|
207 |
+
|
208 |
+
# Section 8.4.11
|
209 |
+
addi(Ei(t),
|
210 |
+
constant(-S.ImaginaryUnit*pi) + [(S.NegativeOne, meijerg([], [1], [0, 0], [],
|
211 |
+
t*polar_lift(-1)))],
|
212 |
+
True)
|
213 |
+
|
214 |
+
# Section 8.4.12
|
215 |
+
add(Si(t), [1], [], [S.Half], [0, 0], t**2/4, sqrt(pi)/2)
|
216 |
+
add(Ci(t), [], [1], [0, 0], [S.Half], t**2/4, -sqrt(pi)/2)
|
217 |
+
|
218 |
+
# Section 8.4.13
|
219 |
+
add(Shi(t), [S.Half], [], [0], [Rational(-1, 2), Rational(-1, 2)], polar_lift(-1)*t**2/4,
|
220 |
+
t*sqrt(pi)/4)
|
221 |
+
add(Chi(t), [], [S.Half, 1], [0, 0], [S.Half, S.Half], t**2/4, -
|
222 |
+
pi**S('3/2')/2)
|
223 |
+
|
224 |
+
# generalized exponential integral
|
225 |
+
add(expint(a, t), [], [a], [a - 1, 0], [], t)
|
226 |
+
|
227 |
+
# Section 8.4.14
|
228 |
+
add(erf(t), [1], [], [S.Half], [0], t**2, 1/sqrt(pi))
|
229 |
+
# TODO exp(-x)*erf(I*x) does not work
|
230 |
+
add(erfc(t), [], [1], [0, S.Half], [], t**2, 1/sqrt(pi))
|
231 |
+
# This formula for erfi(z) yields a wrong(?) minus sign
|
232 |
+
#add(erfi(t), [1], [], [S.Half], [0], -t**2, I/sqrt(pi))
|
233 |
+
add(erfi(t), [S.Half], [], [0], [Rational(-1, 2)], -t**2, t/sqrt(pi))
|
234 |
+
|
235 |
+
# Fresnel Integrals
|
236 |
+
add(fresnels(t), [1], [], [Rational(3, 4)], [0, Rational(1, 4)], pi**2*t**4/16, S.Half)
|
237 |
+
add(fresnelc(t), [1], [], [Rational(1, 4)], [0, Rational(3, 4)], pi**2*t**4/16, S.Half)
|
238 |
+
|
239 |
+
##### bessel-type functions #####
|
240 |
+
# Section 8.4.19
|
241 |
+
add(besselj(a, t), [], [], [a/2], [-a/2], t**2/4)
|
242 |
+
|
243 |
+
# all of the following are derivable
|
244 |
+
#add(sin(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [(1+a)/2],
|
245 |
+
# [-a/2, a/2, (1-a)/2], t**2, 1/sqrt(2))
|
246 |
+
#add(cos(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [a/2],
|
247 |
+
# [-a/2, (1+a)/2, (1-a)/2], t**2, 1/sqrt(2))
|
248 |
+
#add(besselj(a, t)**2, [S.Half], [], [a], [-a, 0], t**2, 1/sqrt(pi))
|
249 |
+
#add(besselj(a, t)*besselj(b, t), [0, S.Half], [], [(a + b)/2],
|
250 |
+
# [-(a+b)/2, (a - b)/2, (b - a)/2], t**2, 1/sqrt(pi))
|
251 |
+
|
252 |
+
# Section 8.4.20
|
253 |
+
add(bessely(a, t), [], [-(a + 1)/2], [a/2, -a/2], [-(a + 1)/2], t**2/4)
|
254 |
+
|
255 |
+
# TODO all of the following should be derivable
|
256 |
+
#add(sin(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(1 - a - 1)/2],
|
257 |
+
# [(1 + a)/2, (1 - a)/2], [(1 - a - 1)/2, (1 - 1 - a)/2, (1 - 1 + a)/2],
|
258 |
+
# t**2, 1/sqrt(2))
|
259 |
+
#add(cos(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(0 - a - 1)/2],
|
260 |
+
# [(0 + a)/2, (0 - a)/2], [(0 - a - 1)/2, (1 - 0 - a)/2, (1 - 0 + a)/2],
|
261 |
+
# t**2, 1/sqrt(2))
|
262 |
+
#add(besselj(a, t)*bessely(b, t), [0, S.Half], [(a - b - 1)/2],
|
263 |
+
# [(a + b)/2, (a - b)/2], [(a - b - 1)/2, -(a + b)/2, (b - a)/2],
|
264 |
+
# t**2, 1/sqrt(pi))
|
265 |
+
#addi(bessely(a, t)**2,
|
266 |
+
# [(2/sqrt(pi), meijerg([], [S.Half, S.Half - a], [0, a, -a],
|
267 |
+
# [S.Half - a], t**2)),
|
268 |
+
# (1/sqrt(pi), meijerg([S.Half], [], [a], [-a, 0], t**2))],
|
269 |
+
# True)
|
270 |
+
#addi(bessely(a, t)*bessely(b, t),
|
271 |
+
# [(2/sqrt(pi), meijerg([], [0, S.Half, (1 - a - b)/2],
|
272 |
+
# [(a + b)/2, (a - b)/2, (b - a)/2, -(a + b)/2],
|
273 |
+
# [(1 - a - b)/2], t**2)),
|
274 |
+
# (1/sqrt(pi), meijerg([0, S.Half], [], [(a + b)/2],
|
275 |
+
# [-(a + b)/2, (a - b)/2, (b - a)/2], t**2))],
|
276 |
+
# True)
|
277 |
+
|
278 |
+
# Section 8.4.21 ?
|
279 |
+
# Section 8.4.22
|
280 |
+
add(besseli(a, t), [], [(1 + a)/2], [a/2], [-a/2, (1 + a)/2], t**2/4, pi)
|
281 |
+
# TODO many more formulas. should all be derivable
|
282 |
+
|
283 |
+
# Section 8.4.23
|
284 |
+
add(besselk(a, t), [], [], [a/2, -a/2], [], t**2/4, S.Half)
|
285 |
+
# TODO many more formulas. should all be derivable
|
286 |
+
|
287 |
+
# Complete elliptic integrals K(z) and E(z)
|
288 |
+
add(elliptic_k(t), [S.Half, S.Half], [], [0], [0], -t, S.Half)
|
289 |
+
add(elliptic_e(t), [S.Half, 3*S.Half], [], [0], [0], -t, Rational(-1, 2)/2)
|
290 |
+
|
291 |
+
|
292 |
+
####################################################################
|
293 |
+
# First some helper functions.
|
294 |
+
####################################################################
|
295 |
+
|
296 |
+
from sympy.utilities.timeutils import timethis
|
297 |
+
timeit = timethis('meijerg')
|
298 |
+
|
299 |
+
|
300 |
+
def _mytype(f: Basic, x: Symbol) -> tuple[type[Basic], ...]:
|
301 |
+
""" Create a hashable entity describing the type of f. """
|
302 |
+
def key(x: type[Basic]) -> tuple[int, int, str]:
|
303 |
+
return x.class_key()
|
304 |
+
|
305 |
+
if x not in f.free_symbols:
|
306 |
+
return ()
|
307 |
+
elif f.is_Function:
|
308 |
+
return type(f),
|
309 |
+
return tuple(sorted((t for a in f.args for t in _mytype(a, x)), key=key))
|
310 |
+
|
311 |
+
|
312 |
+
class _CoeffExpValueError(ValueError):
|
313 |
+
"""
|
314 |
+
Exception raised by _get_coeff_exp, for internal use only.
|
315 |
+
"""
|
316 |
+
pass
|
317 |
+
|
318 |
+
|
319 |
+
def _get_coeff_exp(expr, x):
|
320 |
+
"""
|
321 |
+
When expr is known to be of the form c*x**b, with c and/or b possibly 1,
|
322 |
+
return c, b.
|
323 |
+
|
324 |
+
Examples
|
325 |
+
========
|
326 |
+
|
327 |
+
>>> from sympy.abc import x, a, b
|
328 |
+
>>> from sympy.integrals.meijerint import _get_coeff_exp
|
329 |
+
>>> _get_coeff_exp(a*x**b, x)
|
330 |
+
(a, b)
|
331 |
+
>>> _get_coeff_exp(x, x)
|
332 |
+
(1, 1)
|
333 |
+
>>> _get_coeff_exp(2*x, x)
|
334 |
+
(2, 1)
|
335 |
+
>>> _get_coeff_exp(x**3, x)
|
336 |
+
(1, 3)
|
337 |
+
"""
|
338 |
+
from sympy.simplify import powsimp
|
339 |
+
(c, m) = expand_power_base(powsimp(expr)).as_coeff_mul(x)
|
340 |
+
if not m:
|
341 |
+
return c, S.Zero
|
342 |
+
[m] = m
|
343 |
+
if m.is_Pow:
|
344 |
+
if m.base != x:
|
345 |
+
raise _CoeffExpValueError('expr not of form a*x**b')
|
346 |
+
return c, m.exp
|
347 |
+
elif m == x:
|
348 |
+
return c, S.One
|
349 |
+
else:
|
350 |
+
raise _CoeffExpValueError('expr not of form a*x**b: %s' % expr)
|
351 |
+
|
352 |
+
|
353 |
+
def _exponents(expr, x):
|
354 |
+
"""
|
355 |
+
Find the exponents of ``x`` (not including zero) in ``expr``.
|
356 |
+
|
357 |
+
Examples
|
358 |
+
========
|
359 |
+
|
360 |
+
>>> from sympy.integrals.meijerint import _exponents
|
361 |
+
>>> from sympy.abc import x, y
|
362 |
+
>>> from sympy import sin
|
363 |
+
>>> _exponents(x, x)
|
364 |
+
{1}
|
365 |
+
>>> _exponents(x**2, x)
|
366 |
+
{2}
|
367 |
+
>>> _exponents(x**2 + x, x)
|
368 |
+
{1, 2}
|
369 |
+
>>> _exponents(x**3*sin(x + x**y) + 1/x, x)
|
370 |
+
{-1, 1, 3, y}
|
371 |
+
"""
|
372 |
+
def _exponents_(expr, x, res):
|
373 |
+
if expr == x:
|
374 |
+
res.update([1])
|
375 |
+
return
|
376 |
+
if expr.is_Pow and expr.base == x:
|
377 |
+
res.update([expr.exp])
|
378 |
+
return
|
379 |
+
for argument in expr.args:
|
380 |
+
_exponents_(argument, x, res)
|
381 |
+
res = set()
|
382 |
+
_exponents_(expr, x, res)
|
383 |
+
return res
|
384 |
+
|
385 |
+
|
386 |
+
def _functions(expr, x):
|
387 |
+
""" Find the types of functions in expr, to estimate the complexity. """
|
388 |
+
return {e.func for e in expr.atoms(Function) if x in e.free_symbols}
|
389 |
+
|
390 |
+
|
391 |
+
def _find_splitting_points(expr, x):
|
392 |
+
"""
|
393 |
+
Find numbers a such that a linear substitution x -> x + a would
|
394 |
+
(hopefully) simplify expr.
|
395 |
+
|
396 |
+
Examples
|
397 |
+
========
|
398 |
+
|
399 |
+
>>> from sympy.integrals.meijerint import _find_splitting_points as fsp
|
400 |
+
>>> from sympy import sin
|
401 |
+
>>> from sympy.abc import x
|
402 |
+
>>> fsp(x, x)
|
403 |
+
{0}
|
404 |
+
>>> fsp((x-1)**3, x)
|
405 |
+
{1}
|
406 |
+
>>> fsp(sin(x+3)*x, x)
|
407 |
+
{-3, 0}
|
408 |
+
"""
|
409 |
+
p, q = [Wild(n, exclude=[x]) for n in 'pq']
|
410 |
+
|
411 |
+
def compute_innermost(expr, res):
|
412 |
+
if not isinstance(expr, Expr):
|
413 |
+
return
|
414 |
+
m = expr.match(p*x + q)
|
415 |
+
if m and m[p] != 0:
|
416 |
+
res.add(-m[q]/m[p])
|
417 |
+
return
|
418 |
+
if expr.is_Atom:
|
419 |
+
return
|
420 |
+
for argument in expr.args:
|
421 |
+
compute_innermost(argument, res)
|
422 |
+
innermost = set()
|
423 |
+
compute_innermost(expr, innermost)
|
424 |
+
return innermost
|
425 |
+
|
426 |
+
|
427 |
+
def _split_mul(f, x):
|
428 |
+
"""
|
429 |
+
Split expression ``f`` into fac, po, g, where fac is a constant factor,
|
430 |
+
po = x**s for some s independent of s, and g is "the rest".
|
431 |
+
|
432 |
+
Examples
|
433 |
+
========
|
434 |
+
|
435 |
+
>>> from sympy.integrals.meijerint import _split_mul
|
436 |
+
>>> from sympy import sin
|
437 |
+
>>> from sympy.abc import s, x
|
438 |
+
>>> _split_mul((3*x)**s*sin(x**2)*x, x)
|
439 |
+
(3**s, x*x**s, sin(x**2))
|
440 |
+
"""
|
441 |
+
fac = S.One
|
442 |
+
po = S.One
|
443 |
+
g = S.One
|
444 |
+
f = expand_power_base(f)
|
445 |
+
|
446 |
+
args = Mul.make_args(f)
|
447 |
+
for a in args:
|
448 |
+
if a == x:
|
449 |
+
po *= x
|
450 |
+
elif x not in a.free_symbols:
|
451 |
+
fac *= a
|
452 |
+
else:
|
453 |
+
if a.is_Pow and x not in a.exp.free_symbols:
|
454 |
+
c, t = a.base.as_coeff_mul(x)
|
455 |
+
if t != (x,):
|
456 |
+
c, t = expand_mul(a.base).as_coeff_mul(x)
|
457 |
+
if t == (x,):
|
458 |
+
po *= x**a.exp
|
459 |
+
fac *= unpolarify(polarify(c**a.exp, subs=False))
|
460 |
+
continue
|
461 |
+
g *= a
|
462 |
+
|
463 |
+
return fac, po, g
|
464 |
+
|
465 |
+
|
466 |
+
def _mul_args(f):
|
467 |
+
"""
|
468 |
+
Return a list ``L`` such that ``Mul(*L) == f``.
|
469 |
+
|
470 |
+
If ``f`` is not a ``Mul`` or ``Pow``, ``L=[f]``.
|
471 |
+
If ``f=g**n`` for an integer ``n``, ``L=[g]*n``.
|
472 |
+
If ``f`` is a ``Mul``, ``L`` comes from applying ``_mul_args`` to all factors of ``f``.
|
473 |
+
"""
|
474 |
+
args = Mul.make_args(f)
|
475 |
+
gs = []
|
476 |
+
for g in args:
|
477 |
+
if g.is_Pow and g.exp.is_Integer:
|
478 |
+
n = g.exp
|
479 |
+
base = g.base
|
480 |
+
if n < 0:
|
481 |
+
n = -n
|
482 |
+
base = 1/base
|
483 |
+
gs += [base]*n
|
484 |
+
else:
|
485 |
+
gs.append(g)
|
486 |
+
return gs
|
487 |
+
|
488 |
+
|
489 |
+
def _mul_as_two_parts(f):
|
490 |
+
"""
|
491 |
+
Find all the ways to split ``f`` into a product of two terms.
|
492 |
+
Return None on failure.
|
493 |
+
|
494 |
+
Explanation
|
495 |
+
===========
|
496 |
+
|
497 |
+
Although the order is canonical from multiset_partitions, this is
|
498 |
+
not necessarily the best order to process the terms. For example,
|
499 |
+
if the case of len(gs) == 2 is removed and multiset is allowed to
|
500 |
+
sort the terms, some tests fail.
|
501 |
+
|
502 |
+
Examples
|
503 |
+
========
|
504 |
+
|
505 |
+
>>> from sympy.integrals.meijerint import _mul_as_two_parts
|
506 |
+
>>> from sympy import sin, exp, ordered
|
507 |
+
>>> from sympy.abc import x
|
508 |
+
>>> list(ordered(_mul_as_two_parts(x*sin(x)*exp(x))))
|
509 |
+
[(x, exp(x)*sin(x)), (x*exp(x), sin(x)), (x*sin(x), exp(x))]
|
510 |
+
"""
|
511 |
+
|
512 |
+
gs = _mul_args(f)
|
513 |
+
if len(gs) < 2:
|
514 |
+
return None
|
515 |
+
if len(gs) == 2:
|
516 |
+
return [tuple(gs)]
|
517 |
+
return [(Mul(*x), Mul(*y)) for (x, y) in multiset_partitions(gs, 2)]
|
518 |
+
|
519 |
+
|
520 |
+
def _inflate_g(g, n):
|
521 |
+
""" Return C, h such that h is a G function of argument z**n and
|
522 |
+
g = C*h. """
|
523 |
+
# TODO should this be a method of meijerg?
|
524 |
+
# See: [L, page 150, equation (5)]
|
525 |
+
def inflate(params, n):
|
526 |
+
""" (a1, .., ak) -> (a1/n, (a1+1)/n, ..., (ak + n-1)/n) """
|
527 |
+
return [(a + i)/n for a, i in itertools.product(params, range(n))]
|
528 |
+
v = S(len(g.ap) - len(g.bq))
|
529 |
+
C = n**(1 + g.nu + v/2)
|
530 |
+
C /= (2*pi)**((n - 1)*g.delta)
|
531 |
+
return C, meijerg(inflate(g.an, n), inflate(g.aother, n),
|
532 |
+
inflate(g.bm, n), inflate(g.bother, n),
|
533 |
+
g.argument**n * n**(n*v))
|
534 |
+
|
535 |
+
|
536 |
+
def _flip_g(g):
|
537 |
+
""" Turn the G function into one of inverse argument
|
538 |
+
(i.e. G(1/x) -> G'(x)) """
|
539 |
+
# See [L], section 5.2
|
540 |
+
def tr(l):
|
541 |
+
return [1 - a for a in l]
|
542 |
+
return meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), 1/g.argument)
|
543 |
+
|
544 |
+
|
545 |
+
def _inflate_fox_h(g, a):
|
546 |
+
r"""
|
547 |
+
Let d denote the integrand in the definition of the G function ``g``.
|
548 |
+
Consider the function H which is defined in the same way, but with
|
549 |
+
integrand d/Gamma(a*s) (contour conventions as usual).
|
550 |
+
|
551 |
+
If ``a`` is rational, the function H can be written as C*G, for a constant C
|
552 |
+
and a G-function G.
|
553 |
+
|
554 |
+
This function returns C, G.
|
555 |
+
"""
|
556 |
+
if a < 0:
|
557 |
+
return _inflate_fox_h(_flip_g(g), -a)
|
558 |
+
p = S(a.p)
|
559 |
+
q = S(a.q)
|
560 |
+
# We use the substitution s->qs, i.e. inflate g by q. We are left with an
|
561 |
+
# extra factor of Gamma(p*s), for which we use Gauss' multiplication
|
562 |
+
# theorem.
|
563 |
+
D, g = _inflate_g(g, q)
|
564 |
+
z = g.argument
|
565 |
+
D /= (2*pi)**((1 - p)/2)*p**Rational(-1, 2)
|
566 |
+
z /= p**p
|
567 |
+
bs = [(n + 1)/p for n in range(p)]
|
568 |
+
return D, meijerg(g.an, g.aother, g.bm, list(g.bother) + bs, z)
|
569 |
+
|
570 |
+
_dummies: dict[tuple[str, str], Dummy] = {}
|
571 |
+
|
572 |
+
|
573 |
+
def _dummy(name, token, expr, **kwargs):
|
574 |
+
"""
|
575 |
+
Return a dummy. This will return the same dummy if the same token+name is
|
576 |
+
requested more than once, and it is not already in expr.
|
577 |
+
This is for being cache-friendly.
|
578 |
+
"""
|
579 |
+
d = _dummy_(name, token, **kwargs)
|
580 |
+
if d in expr.free_symbols:
|
581 |
+
return Dummy(name, **kwargs)
|
582 |
+
return d
|
583 |
+
|
584 |
+
|
585 |
+
def _dummy_(name, token, **kwargs):
|
586 |
+
"""
|
587 |
+
Return a dummy associated to name and token. Same effect as declaring
|
588 |
+
it globally.
|
589 |
+
"""
|
590 |
+
global _dummies
|
591 |
+
if not (name, token) in _dummies:
|
592 |
+
_dummies[(name, token)] = Dummy(name, **kwargs)
|
593 |
+
return _dummies[(name, token)]
|
594 |
+
|
595 |
+
|
596 |
+
def _is_analytic(f, x):
|
597 |
+
""" Check if f(x), when expressed using G functions on the positive reals,
|
598 |
+
will in fact agree with the G functions almost everywhere """
|
599 |
+
return not any(x in expr.free_symbols for expr in f.atoms(Heaviside, Abs))
|
600 |
+
|
601 |
+
|
602 |
+
def _condsimp(cond, first=True):
|
603 |
+
"""
|
604 |
+
Do naive simplifications on ``cond``.
|
605 |
+
|
606 |
+
Explanation
|
607 |
+
===========
|
608 |
+
|
609 |
+
Note that this routine is completely ad-hoc, simplification rules being
|
610 |
+
added as need arises rather than following any logical pattern.
|
611 |
+
|
612 |
+
Examples
|
613 |
+
========
|
614 |
+
|
615 |
+
>>> from sympy.integrals.meijerint import _condsimp as simp
|
616 |
+
>>> from sympy import Or, Eq
|
617 |
+
>>> from sympy.abc import x, y
|
618 |
+
>>> simp(Or(x < y, Eq(x, y)))
|
619 |
+
x <= y
|
620 |
+
"""
|
621 |
+
if first:
|
622 |
+
cond = cond.replace(lambda _: _.is_Relational, _canonical_coeff)
|
623 |
+
first = False
|
624 |
+
if not isinstance(cond, BooleanFunction):
|
625 |
+
return cond
|
626 |
+
p, q, r = symbols('p q r', cls=Wild)
|
627 |
+
# transforms tests use 0, 4, 5 and 11-14
|
628 |
+
# meijer tests use 0, 2, 11, 14
|
629 |
+
# joint_rv uses 6, 7
|
630 |
+
rules = [
|
631 |
+
(Or(p < q, Eq(p, q)), p <= q), # 0
|
632 |
+
# The next two obviously are instances of a general pattern, but it is
|
633 |
+
# easier to spell out the few cases we care about.
|
634 |
+
(And(Abs(arg(p)) <= pi, Abs(arg(p) - 2*pi) <= pi),
|
635 |
+
Eq(arg(p) - pi, 0)), # 1
|
636 |
+
(And(Abs(2*arg(p) + pi) <= pi, Abs(2*arg(p) - pi) <= pi),
|
637 |
+
Eq(arg(p), 0)), # 2
|
638 |
+
(And(Abs(2*arg(p) + pi) < pi, Abs(2*arg(p) - pi) <= pi),
|
639 |
+
S.false), # 3
|
640 |
+
(And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) <= pi/2),
|
641 |
+
Eq(arg(p), 0)), # 4
|
642 |
+
(And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) < pi/2),
|
643 |
+
S.false), # 5
|
644 |
+
(And(Abs(arg(p**2/2 + 1)) < pi, Ne(Abs(arg(p**2/2 + 1)), pi)),
|
645 |
+
S.true), # 6
|
646 |
+
(Or(Abs(arg(p**2/2 + 1)) < pi, Ne(1/(p**2/2 + 1), 0)),
|
647 |
+
S.true), # 7
|
648 |
+
(And(Abs(unbranched_argument(p)) <= pi,
|
649 |
+
Abs(unbranched_argument(exp_polar(-2*pi*S.ImaginaryUnit)*p)) <= pi),
|
650 |
+
Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi)*p), 0)), # 8
|
651 |
+
(And(Abs(unbranched_argument(p)) <= pi/2,
|
652 |
+
Abs(unbranched_argument(exp_polar(-pi*S.ImaginaryUnit)*p)) <= pi/2),
|
653 |
+
Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi/2)*p), 0)), # 9
|
654 |
+
(Or(p <= q, And(p < q, r)), p <= q), # 10
|
655 |
+
(Ne(p**2, 1) & (p**2 > 1), p**2 > 1), # 11
|
656 |
+
(Ne(1/p, 1) & (cos(Abs(arg(p)))*Abs(p) > 1), Abs(p) > 1), # 12
|
657 |
+
(Ne(p, 2) & (cos(Abs(arg(p)))*Abs(p) > 2), Abs(p) > 2), # 13
|
658 |
+
((Abs(arg(p)) < pi/2) & (cos(Abs(arg(p)))*sqrt(Abs(p**2)) > 1), p**2 > 1), # 14
|
659 |
+
]
|
660 |
+
cond = cond.func(*[_condsimp(_, first) for _ in cond.args])
|
661 |
+
change = True
|
662 |
+
while change:
|
663 |
+
change = False
|
664 |
+
for irule, (fro, to) in enumerate(rules):
|
665 |
+
if fro.func != cond.func:
|
666 |
+
continue
|
667 |
+
for n, arg1 in enumerate(cond.args):
|
668 |
+
if r in fro.args[0].free_symbols:
|
669 |
+
m = arg1.match(fro.args[1])
|
670 |
+
num = 1
|
671 |
+
else:
|
672 |
+
num = 0
|
673 |
+
m = arg1.match(fro.args[0])
|
674 |
+
if not m:
|
675 |
+
continue
|
676 |
+
otherargs = [x.subs(m) for x in fro.args[:num] + fro.args[num + 1:]]
|
677 |
+
otherlist = [n]
|
678 |
+
for arg2 in otherargs:
|
679 |
+
for k, arg3 in enumerate(cond.args):
|
680 |
+
if k in otherlist:
|
681 |
+
continue
|
682 |
+
if arg2 == arg3:
|
683 |
+
otherlist += [k]
|
684 |
+
break
|
685 |
+
if isinstance(arg3, And) and arg2.args[1] == r and \
|
686 |
+
isinstance(arg2, And) and arg2.args[0] in arg3.args:
|
687 |
+
otherlist += [k]
|
688 |
+
break
|
689 |
+
if isinstance(arg3, And) and arg2.args[0] == r and \
|
690 |
+
isinstance(arg2, And) and arg2.args[1] in arg3.args:
|
691 |
+
otherlist += [k]
|
692 |
+
break
|
693 |
+
if len(otherlist) != len(otherargs) + 1:
|
694 |
+
continue
|
695 |
+
newargs = [arg_ for (k, arg_) in enumerate(cond.args)
|
696 |
+
if k not in otherlist] + [to.subs(m)]
|
697 |
+
if SYMPY_DEBUG:
|
698 |
+
if irule not in (0, 2, 4, 5, 6, 7, 11, 12, 13, 14):
|
699 |
+
print('used new rule:', irule)
|
700 |
+
cond = cond.func(*newargs)
|
701 |
+
change = True
|
702 |
+
break
|
703 |
+
|
704 |
+
# final tweak
|
705 |
+
def rel_touchup(rel):
|
706 |
+
if rel.rel_op != '==' or rel.rhs != 0:
|
707 |
+
return rel
|
708 |
+
|
709 |
+
# handle Eq(*, 0)
|
710 |
+
LHS = rel.lhs
|
711 |
+
m = LHS.match(arg(p)**q)
|
712 |
+
if not m:
|
713 |
+
m = LHS.match(unbranched_argument(polar_lift(p)**q))
|
714 |
+
if not m:
|
715 |
+
if isinstance(LHS, periodic_argument) and not LHS.args[0].is_polar \
|
716 |
+
and LHS.args[1] is S.Infinity:
|
717 |
+
return (LHS.args[0] > 0)
|
718 |
+
return rel
|
719 |
+
return (m[p] > 0)
|
720 |
+
cond = cond.replace(lambda _: _.is_Relational, rel_touchup)
|
721 |
+
if SYMPY_DEBUG:
|
722 |
+
print('_condsimp: ', cond)
|
723 |
+
return cond
|
724 |
+
|
725 |
+
def _eval_cond(cond):
|
726 |
+
""" Re-evaluate the conditions. """
|
727 |
+
if isinstance(cond, bool):
|
728 |
+
return cond
|
729 |
+
return _condsimp(cond.doit())
|
730 |
+
|
731 |
+
####################################################################
|
732 |
+
# Now the "backbone" functions to do actual integration.
|
733 |
+
####################################################################
|
734 |
+
|
735 |
+
|
736 |
+
def _my_principal_branch(expr, period, full_pb=False):
|
737 |
+
""" Bring expr nearer to its principal branch by removing superfluous
|
738 |
+
factors.
|
739 |
+
This function does *not* guarantee to yield the principal branch,
|
740 |
+
to avoid introducing opaque principal_branch() objects,
|
741 |
+
unless full_pb=True. """
|
742 |
+
res = principal_branch(expr, period)
|
743 |
+
if not full_pb:
|
744 |
+
res = res.replace(principal_branch, lambda x, y: x)
|
745 |
+
return res
|
746 |
+
|
747 |
+
|
748 |
+
def _rewrite_saxena_1(fac, po, g, x):
|
749 |
+
"""
|
750 |
+
Rewrite the integral fac*po*g dx, from zero to infinity, as
|
751 |
+
integral fac*G, where G has argument a*x. Note po=x**s.
|
752 |
+
Return fac, G.
|
753 |
+
"""
|
754 |
+
_, s = _get_coeff_exp(po, x)
|
755 |
+
a, b = _get_coeff_exp(g.argument, x)
|
756 |
+
period = g.get_period()
|
757 |
+
a = _my_principal_branch(a, period)
|
758 |
+
|
759 |
+
# We substitute t = x**b.
|
760 |
+
C = fac/(Abs(b)*a**((s + 1)/b - 1))
|
761 |
+
# Absorb a factor of (at)**((1 + s)/b - 1).
|
762 |
+
|
763 |
+
def tr(l):
|
764 |
+
return [a + (1 + s)/b - 1 for a in l]
|
765 |
+
return C, meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother),
|
766 |
+
a*x)
|
767 |
+
|
768 |
+
|
769 |
+
def _check_antecedents_1(g, x, helper=False):
|
770 |
+
r"""
|
771 |
+
Return a condition under which the mellin transform of g exists.
|
772 |
+
Any power of x has already been absorbed into the G function,
|
773 |
+
so this is just $\int_0^\infty g\, dx$.
|
774 |
+
|
775 |
+
See [L, section 5.6.1]. (Note that s=1.)
|
776 |
+
|
777 |
+
If ``helper`` is True, only check if the MT exists at infinity, i.e. if
|
778 |
+
$\int_1^\infty g\, dx$ exists.
|
779 |
+
"""
|
780 |
+
# NOTE if you update these conditions, please update the documentation as well
|
781 |
+
delta = g.delta
|
782 |
+
eta, _ = _get_coeff_exp(g.argument, x)
|
783 |
+
m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)])
|
784 |
+
|
785 |
+
if p > q:
|
786 |
+
def tr(l):
|
787 |
+
return [1 - x for x in l]
|
788 |
+
return _check_antecedents_1(meijerg(tr(g.bm), tr(g.bother),
|
789 |
+
tr(g.an), tr(g.aother), x/eta),
|
790 |
+
x)
|
791 |
+
|
792 |
+
tmp = [-re(b) < 1 for b in g.bm] + [1 < 1 - re(a) for a in g.an]
|
793 |
+
cond_3 = And(*tmp)
|
794 |
+
|
795 |
+
tmp += [-re(b) < 1 for b in g.bother]
|
796 |
+
tmp += [1 < 1 - re(a) for a in g.aother]
|
797 |
+
cond_3_star = And(*tmp)
|
798 |
+
|
799 |
+
cond_4 = (-re(g.nu) + (q + 1 - p)/2 > q - p)
|
800 |
+
|
801 |
+
def debug(*msg):
|
802 |
+
_debug(*msg)
|
803 |
+
|
804 |
+
def debugf(string, arg):
|
805 |
+
_debugf(string, arg)
|
806 |
+
|
807 |
+
debug('Checking antecedents for 1 function:')
|
808 |
+
debugf(' delta=%s, eta=%s, m=%s, n=%s, p=%s, q=%s',
|
809 |
+
(delta, eta, m, n, p, q))
|
810 |
+
debugf(' ap = %s, %s', (list(g.an), list(g.aother)))
|
811 |
+
debugf(' bq = %s, %s', (list(g.bm), list(g.bother)))
|
812 |
+
debugf(' cond_3=%s, cond_3*=%s, cond_4=%s', (cond_3, cond_3_star, cond_4))
|
813 |
+
|
814 |
+
conds = []
|
815 |
+
|
816 |
+
# case 1
|
817 |
+
case1 = []
|
818 |
+
tmp1 = [1 <= n, p < q, 1 <= m]
|
819 |
+
tmp2 = [1 <= p, 1 <= m, Eq(q, p + 1), Not(And(Eq(n, 0), Eq(m, p + 1)))]
|
820 |
+
tmp3 = [1 <= p, Eq(q, p)]
|
821 |
+
for k in range(ceiling(delta/2) + 1):
|
822 |
+
tmp3 += [Ne(Abs(unbranched_argument(eta)), (delta - 2*k)*pi)]
|
823 |
+
tmp = [delta > 0, Abs(unbranched_argument(eta)) < delta*pi]
|
824 |
+
extra = [Ne(eta, 0), cond_3]
|
825 |
+
if helper:
|
826 |
+
extra = []
|
827 |
+
for t in [tmp1, tmp2, tmp3]:
|
828 |
+
case1 += [And(*(t + tmp + extra))]
|
829 |
+
conds += case1
|
830 |
+
debug(' case 1:', case1)
|
831 |
+
|
832 |
+
# case 2
|
833 |
+
extra = [cond_3]
|
834 |
+
if helper:
|
835 |
+
extra = []
|
836 |
+
case2 = [And(Eq(n, 0), p + 1 <= m, m <= q,
|
837 |
+
Abs(unbranched_argument(eta)) < delta*pi, *extra)]
|
838 |
+
conds += case2
|
839 |
+
debug(' case 2:', case2)
|
840 |
+
|
841 |
+
# case 3
|
842 |
+
extra = [cond_3, cond_4]
|
843 |
+
if helper:
|
844 |
+
extra = []
|
845 |
+
case3 = [And(p < q, 1 <= m, delta > 0, Eq(Abs(unbranched_argument(eta)), delta*pi),
|
846 |
+
*extra)]
|
847 |
+
case3 += [And(p <= q - 2, Eq(delta, 0), Eq(Abs(unbranched_argument(eta)), 0), *extra)]
|
848 |
+
conds += case3
|
849 |
+
debug(' case 3:', case3)
|
850 |
+
|
851 |
+
# TODO altered cases 4-7
|
852 |
+
|
853 |
+
# extra case from wofram functions site:
|
854 |
+
# (reproduced verbatim from Prudnikov, section 2.24.2)
|
855 |
+
# https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/01/
|
856 |
+
case_extra = []
|
857 |
+
case_extra += [Eq(p, q), Eq(delta, 0), Eq(unbranched_argument(eta), 0), Ne(eta, 0)]
|
858 |
+
if not helper:
|
859 |
+
case_extra += [cond_3]
|
860 |
+
s = []
|
861 |
+
for a, b in zip(g.ap, g.bq):
|
862 |
+
s += [b - a]
|
863 |
+
case_extra += [re(Add(*s)) < 0]
|
864 |
+
case_extra = And(*case_extra)
|
865 |
+
conds += [case_extra]
|
866 |
+
debug(' extra case:', [case_extra])
|
867 |
+
|
868 |
+
case_extra_2 = [And(delta > 0, Abs(unbranched_argument(eta)) < delta*pi)]
|
869 |
+
if not helper:
|
870 |
+
case_extra_2 += [cond_3]
|
871 |
+
case_extra_2 = And(*case_extra_2)
|
872 |
+
conds += [case_extra_2]
|
873 |
+
debug(' second extra case:', [case_extra_2])
|
874 |
+
|
875 |
+
# TODO This leaves only one case from the three listed by Prudnikov.
|
876 |
+
# Investigate if these indeed cover everything; if so, remove the rest.
|
877 |
+
|
878 |
+
return Or(*conds)
|
879 |
+
|
880 |
+
|
881 |
+
def _int0oo_1(g, x):
|
882 |
+
r"""
|
883 |
+
Evaluate $\int_0^\infty g\, dx$ using G functions,
|
884 |
+
assuming the necessary conditions are fulfilled.
|
885 |
+
|
886 |
+
Examples
|
887 |
+
========
|
888 |
+
|
889 |
+
>>> from sympy.abc import a, b, c, d, x, y
|
890 |
+
>>> from sympy import meijerg
|
891 |
+
>>> from sympy.integrals.meijerint import _int0oo_1
|
892 |
+
>>> _int0oo_1(meijerg([a], [b], [c], [d], x*y), x)
|
893 |
+
gamma(-a)*gamma(c + 1)/(y*gamma(-d)*gamma(b + 1))
|
894 |
+
"""
|
895 |
+
from sympy.simplify import gammasimp
|
896 |
+
# See [L, section 5.6.1]. Note that s=1.
|
897 |
+
eta, _ = _get_coeff_exp(g.argument, x)
|
898 |
+
res = 1/eta
|
899 |
+
# XXX TODO we should reduce order first
|
900 |
+
for b in g.bm:
|
901 |
+
res *= gamma(b + 1)
|
902 |
+
for a in g.an:
|
903 |
+
res *= gamma(1 - a - 1)
|
904 |
+
for b in g.bother:
|
905 |
+
res /= gamma(1 - b - 1)
|
906 |
+
for a in g.aother:
|
907 |
+
res /= gamma(a + 1)
|
908 |
+
return gammasimp(unpolarify(res))
|
909 |
+
|
910 |
+
|
911 |
+
def _rewrite_saxena(fac, po, g1, g2, x, full_pb=False):
|
912 |
+
"""
|
913 |
+
Rewrite the integral ``fac*po*g1*g2`` from 0 to oo in terms of G
|
914 |
+
functions with argument ``c*x``.
|
915 |
+
|
916 |
+
Explanation
|
917 |
+
===========
|
918 |
+
|
919 |
+
Return C, f1, f2 such that integral C f1 f2 from 0 to infinity equals
|
920 |
+
integral fac ``po``, ``g1``, ``g2`` from 0 to infinity.
|
921 |
+
|
922 |
+
Examples
|
923 |
+
========
|
924 |
+
|
925 |
+
>>> from sympy.integrals.meijerint import _rewrite_saxena
|
926 |
+
>>> from sympy.abc import s, t, m
|
927 |
+
>>> from sympy import meijerg
|
928 |
+
>>> g1 = meijerg([], [], [0], [], s*t)
|
929 |
+
>>> g2 = meijerg([], [], [m/2], [-m/2], t**2/4)
|
930 |
+
>>> r = _rewrite_saxena(1, t**0, g1, g2, t)
|
931 |
+
>>> r[0]
|
932 |
+
s/(4*sqrt(pi))
|
933 |
+
>>> r[1]
|
934 |
+
meijerg(((), ()), ((-1/2, 0), ()), s**2*t/4)
|
935 |
+
>>> r[2]
|
936 |
+
meijerg(((), ()), ((m/2,), (-m/2,)), t/4)
|
937 |
+
"""
|
938 |
+
def pb(g):
|
939 |
+
a, b = _get_coeff_exp(g.argument, x)
|
940 |
+
per = g.get_period()
|
941 |
+
return meijerg(g.an, g.aother, g.bm, g.bother,
|
942 |
+
_my_principal_branch(a, per, full_pb)*x**b)
|
943 |
+
|
944 |
+
_, s = _get_coeff_exp(po, x)
|
945 |
+
_, b1 = _get_coeff_exp(g1.argument, x)
|
946 |
+
_, b2 = _get_coeff_exp(g2.argument, x)
|
947 |
+
if (b1 < 0) == True:
|
948 |
+
b1 = -b1
|
949 |
+
g1 = _flip_g(g1)
|
950 |
+
if (b2 < 0) == True:
|
951 |
+
b2 = -b2
|
952 |
+
g2 = _flip_g(g2)
|
953 |
+
if not b1.is_Rational or not b2.is_Rational:
|
954 |
+
return
|
955 |
+
m1, n1 = b1.p, b1.q
|
956 |
+
m2, n2 = b2.p, b2.q
|
957 |
+
tau = ilcm(m1*n2, m2*n1)
|
958 |
+
r1 = tau//(m1*n2)
|
959 |
+
r2 = tau//(m2*n1)
|
960 |
+
|
961 |
+
C1, g1 = _inflate_g(g1, r1)
|
962 |
+
C2, g2 = _inflate_g(g2, r2)
|
963 |
+
g1 = pb(g1)
|
964 |
+
g2 = pb(g2)
|
965 |
+
|
966 |
+
fac *= C1*C2
|
967 |
+
a1, b = _get_coeff_exp(g1.argument, x)
|
968 |
+
a2, _ = _get_coeff_exp(g2.argument, x)
|
969 |
+
|
970 |
+
# arbitrarily tack on the x**s part to g1
|
971 |
+
# TODO should we try both?
|
972 |
+
exp = (s + 1)/b - 1
|
973 |
+
fac = fac/(Abs(b) * a1**exp)
|
974 |
+
|
975 |
+
def tr(l):
|
976 |
+
return [a + exp for a in l]
|
977 |
+
g1 = meijerg(tr(g1.an), tr(g1.aother), tr(g1.bm), tr(g1.bother), a1*x)
|
978 |
+
g2 = meijerg(g2.an, g2.aother, g2.bm, g2.bother, a2*x)
|
979 |
+
|
980 |
+
from sympy.simplify import powdenest
|
981 |
+
return powdenest(fac, polar=True), g1, g2
|
982 |
+
|
983 |
+
|
984 |
+
def _check_antecedents(g1, g2, x):
|
985 |
+
""" Return a condition under which the integral theorem applies. """
|
986 |
+
# Yes, this is madness.
|
987 |
+
# XXX TODO this is a testing *nightmare*
|
988 |
+
# NOTE if you update these conditions, please update the documentation as well
|
989 |
+
|
990 |
+
# The following conditions are found in
|
991 |
+
# [P], Section 2.24.1
|
992 |
+
#
|
993 |
+
# They are also reproduced (verbatim!) at
|
994 |
+
# https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/
|
995 |
+
#
|
996 |
+
# Note: k=l=r=alpha=1
|
997 |
+
sigma, _ = _get_coeff_exp(g1.argument, x)
|
998 |
+
omega, _ = _get_coeff_exp(g2.argument, x)
|
999 |
+
s, t, u, v = S([len(g1.bm), len(g1.an), len(g1.ap), len(g1.bq)])
|
1000 |
+
m, n, p, q = S([len(g2.bm), len(g2.an), len(g2.ap), len(g2.bq)])
|
1001 |
+
bstar = s + t - (u + v)/2
|
1002 |
+
cstar = m + n - (p + q)/2
|
1003 |
+
rho = g1.nu + (u - v)/2 + 1
|
1004 |
+
mu = g2.nu + (p - q)/2 + 1
|
1005 |
+
phi = q - p - (v - u)
|
1006 |
+
eta = 1 - (v - u) - mu - rho
|
1007 |
+
psi = (pi*(q - m - n) + Abs(unbranched_argument(omega)))/(q - p)
|
1008 |
+
theta = (pi*(v - s - t) + Abs(unbranched_argument(sigma)))/(v - u)
|
1009 |
+
|
1010 |
+
_debug('Checking antecedents:')
|
1011 |
+
_debugf(' sigma=%s, s=%s, t=%s, u=%s, v=%s, b*=%s, rho=%s',
|
1012 |
+
(sigma, s, t, u, v, bstar, rho))
|
1013 |
+
_debugf(' omega=%s, m=%s, n=%s, p=%s, q=%s, c*=%s, mu=%s,',
|
1014 |
+
(omega, m, n, p, q, cstar, mu))
|
1015 |
+
_debugf(' phi=%s, eta=%s, psi=%s, theta=%s', (phi, eta, psi, theta))
|
1016 |
+
|
1017 |
+
def _c1():
|
1018 |
+
for g in [g1, g2]:
|
1019 |
+
for i, j in itertools.product(g.an, g.bm):
|
1020 |
+
diff = i - j
|
1021 |
+
if diff.is_integer and diff.is_positive:
|
1022 |
+
return False
|
1023 |
+
return True
|
1024 |
+
c1 = _c1()
|
1025 |
+
c2 = And(*[re(1 + i + j) > 0 for i in g1.bm for j in g2.bm])
|
1026 |
+
c3 = And(*[re(1 + i + j) < 1 + 1 for i in g1.an for j in g2.an])
|
1027 |
+
c4 = And(*[(p - q)*re(1 + i - 1) - re(mu) > Rational(-3, 2) for i in g1.an])
|
1028 |
+
c5 = And(*[(p - q)*re(1 + i) - re(mu) > Rational(-3, 2) for i in g1.bm])
|
1029 |
+
c6 = And(*[(u - v)*re(1 + i - 1) - re(rho) > Rational(-3, 2) for i in g2.an])
|
1030 |
+
c7 = And(*[(u - v)*re(1 + i) - re(rho) > Rational(-3, 2) for i in g2.bm])
|
1031 |
+
c8 = (Abs(phi) + 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu -
|
1032 |
+
1)*(v - u)) > 0)
|
1033 |
+
c9 = (Abs(phi) - 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu -
|
1034 |
+
1)*(v - u)) > 0)
|
1035 |
+
c10 = (Abs(unbranched_argument(sigma)) < bstar*pi)
|
1036 |
+
c11 = Eq(Abs(unbranched_argument(sigma)), bstar*pi)
|
1037 |
+
c12 = (Abs(unbranched_argument(omega)) < cstar*pi)
|
1038 |
+
c13 = Eq(Abs(unbranched_argument(omega)), cstar*pi)
|
1039 |
+
|
1040 |
+
# The following condition is *not* implemented as stated on the wolfram
|
1041 |
+
# function site. In the book of Prudnikov there is an additional part
|
1042 |
+
# (the And involving re()). However, I only have this book in russian, and
|
1043 |
+
# I don't read any russian. The following condition is what other people
|
1044 |
+
# have told me it means.
|
1045 |
+
# Worryingly, it is different from the condition implemented in REDUCE.
|
1046 |
+
# The REDUCE implementation:
|
1047 |
+
# https://reduce-algebra.svn.sourceforge.net/svnroot/reduce-algebra/trunk/packages/defint/definta.red
|
1048 |
+
# (search for tst14)
|
1049 |
+
# The Wolfram alpha version:
|
1050 |
+
# https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/03/0014/
|
1051 |
+
z0 = exp(-(bstar + cstar)*pi*S.ImaginaryUnit)
|
1052 |
+
zos = unpolarify(z0*omega/sigma)
|
1053 |
+
zso = unpolarify(z0*sigma/omega)
|
1054 |
+
if zos == 1/zso:
|
1055 |
+
c14 = And(Eq(phi, 0), bstar + cstar <= 1,
|
1056 |
+
Or(Ne(zos, 1), re(mu + rho + v - u) < 1,
|
1057 |
+
re(mu + rho + q - p) < 1))
|
1058 |
+
else:
|
1059 |
+
def _cond(z):
|
1060 |
+
'''Returns True if abs(arg(1-z)) < pi, avoiding arg(0).
|
1061 |
+
|
1062 |
+
Explanation
|
1063 |
+
===========
|
1064 |
+
|
1065 |
+
If ``z`` is 1 then arg is NaN. This raises a
|
1066 |
+
TypeError on `NaN < pi`. Previously this gave `False` so
|
1067 |
+
this behavior has been hardcoded here but someone should
|
1068 |
+
check if this NaN is more serious! This NaN is triggered by
|
1069 |
+
test_meijerint() in test_meijerint.py:
|
1070 |
+
`meijerint_definite(exp(x), x, 0, I)`
|
1071 |
+
'''
|
1072 |
+
return z != 1 and Abs(arg(1 - z)) < pi
|
1073 |
+
|
1074 |
+
c14 = And(Eq(phi, 0), bstar - 1 + cstar <= 0,
|
1075 |
+
Or(And(Ne(zos, 1), _cond(zos)),
|
1076 |
+
And(re(mu + rho + v - u) < 1, Eq(zos, 1))))
|
1077 |
+
|
1078 |
+
c14_alt = And(Eq(phi, 0), cstar - 1 + bstar <= 0,
|
1079 |
+
Or(And(Ne(zso, 1), _cond(zso)),
|
1080 |
+
And(re(mu + rho + q - p) < 1, Eq(zso, 1))))
|
1081 |
+
|
1082 |
+
# Since r=k=l=1, in our case there is c14_alt which is the same as calling
|
1083 |
+
# us with (g1, g2) = (g2, g1). The conditions below enumerate all cases
|
1084 |
+
# (i.e. we don't have to try arguments reversed by hand), and indeed try
|
1085 |
+
# all symmetric cases. (i.e. whenever there is a condition involving c14,
|
1086 |
+
# there is also a dual condition which is exactly what we would get when g1,
|
1087 |
+
# g2 were interchanged, *but c14 was unaltered*).
|
1088 |
+
# Hence the following seems correct:
|
1089 |
+
c14 = Or(c14, c14_alt)
|
1090 |
+
|
1091 |
+
'''
|
1092 |
+
When `c15` is NaN (e.g. from `psi` being NaN as happens during
|
1093 |
+
'test_issue_4992' and/or `theta` is NaN as in 'test_issue_6253',
|
1094 |
+
both in `test_integrals.py`) the comparison to 0 formerly gave False
|
1095 |
+
whereas now an error is raised. To keep the old behavior, the value
|
1096 |
+
of NaN is replaced with False but perhaps a closer look at this condition
|
1097 |
+
should be made: XXX how should conditions leading to c15=NaN be handled?
|
1098 |
+
'''
|
1099 |
+
try:
|
1100 |
+
lambda_c = (q - p)*Abs(omega)**(1/(q - p))*cos(psi) \
|
1101 |
+
+ (v - u)*Abs(sigma)**(1/(v - u))*cos(theta)
|
1102 |
+
# the TypeError might be raised here, e.g. if lambda_c is NaN
|
1103 |
+
if _eval_cond(lambda_c > 0) != False:
|
1104 |
+
c15 = (lambda_c > 0)
|
1105 |
+
else:
|
1106 |
+
def lambda_s0(c1, c2):
|
1107 |
+
return c1*(q - p)*Abs(omega)**(1/(q - p))*sin(psi) \
|
1108 |
+
+ c2*(v - u)*Abs(sigma)**(1/(v - u))*sin(theta)
|
1109 |
+
lambda_s = Piecewise(
|
1110 |
+
((lambda_s0(+1, +1)*lambda_s0(-1, -1)),
|
1111 |
+
And(Eq(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))),
|
1112 |
+
(lambda_s0(sign(unbranched_argument(omega)), +1)*lambda_s0(sign(unbranched_argument(omega)), -1),
|
1113 |
+
And(Eq(unbranched_argument(sigma), 0), Ne(unbranched_argument(omega), 0))),
|
1114 |
+
(lambda_s0(+1, sign(unbranched_argument(sigma)))*lambda_s0(-1, sign(unbranched_argument(sigma))),
|
1115 |
+
And(Ne(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))),
|
1116 |
+
(lambda_s0(sign(unbranched_argument(omega)), sign(unbranched_argument(sigma))), True))
|
1117 |
+
tmp = [lambda_c > 0,
|
1118 |
+
And(Eq(lambda_c, 0), Ne(lambda_s, 0), re(eta) > -1),
|
1119 |
+
And(Eq(lambda_c, 0), Eq(lambda_s, 0), re(eta) > 0)]
|
1120 |
+
c15 = Or(*tmp)
|
1121 |
+
except TypeError:
|
1122 |
+
c15 = False
|
1123 |
+
for cond, i in [(c1, 1), (c2, 2), (c3, 3), (c4, 4), (c5, 5), (c6, 6),
|
1124 |
+
(c7, 7), (c8, 8), (c9, 9), (c10, 10), (c11, 11),
|
1125 |
+
(c12, 12), (c13, 13), (c14, 14), (c15, 15)]:
|
1126 |
+
_debugf(' c%s: %s', (i, cond))
|
1127 |
+
|
1128 |
+
# We will return Or(*conds)
|
1129 |
+
conds = []
|
1130 |
+
|
1131 |
+
def pr(count):
|
1132 |
+
_debugf(' case %s: %s', (count, conds[-1]))
|
1133 |
+
conds += [And(m*n*s*t != 0, bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10,
|
1134 |
+
c12)] # 1
|
1135 |
+
pr(1)
|
1136 |
+
conds += [And(Eq(u, v), Eq(bstar, 0), cstar.is_positive is True, sigma.is_positive is True, re(rho) < 1,
|
1137 |
+
c1, c2, c3, c12)] # 2
|
1138 |
+
pr(2)
|
1139 |
+
conds += [And(Eq(p, q), Eq(cstar, 0), bstar.is_positive is True, omega.is_positive is True, re(mu) < 1,
|
1140 |
+
c1, c2, c3, c10)] # 3
|
1141 |
+
pr(3)
|
1142 |
+
conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0),
|
1143 |
+
sigma.is_positive is True, omega.is_positive is True, re(mu) < 1, re(rho) < 1,
|
1144 |
+
Ne(sigma, omega), c1, c2, c3)] # 4
|
1145 |
+
pr(4)
|
1146 |
+
conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0),
|
1147 |
+
sigma.is_positive is True, omega.is_positive is True, re(mu + rho) < 1,
|
1148 |
+
Ne(omega, sigma), c1, c2, c3)] # 5
|
1149 |
+
pr(5)
|
1150 |
+
conds += [And(p > q, s.is_positive is True, bstar.is_positive is True, cstar >= 0,
|
1151 |
+
c1, c2, c3, c5, c10, c13)] # 6
|
1152 |
+
pr(6)
|
1153 |
+
conds += [And(p < q, t.is_positive is True, bstar.is_positive is True, cstar >= 0,
|
1154 |
+
c1, c2, c3, c4, c10, c13)] # 7
|
1155 |
+
pr(7)
|
1156 |
+
conds += [And(u > v, m.is_positive is True, cstar.is_positive is True, bstar >= 0,
|
1157 |
+
c1, c2, c3, c7, c11, c12)] # 8
|
1158 |
+
pr(8)
|
1159 |
+
conds += [And(u < v, n.is_positive is True, cstar.is_positive is True, bstar >= 0,
|
1160 |
+
c1, c2, c3, c6, c11, c12)] # 9
|
1161 |
+
pr(9)
|
1162 |
+
conds += [And(p > q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True,
|
1163 |
+
re(rho) < 1, c1, c2, c3, c5, c13)] # 10
|
1164 |
+
pr(10)
|
1165 |
+
conds += [And(p < q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True,
|
1166 |
+
re(rho) < 1, c1, c2, c3, c4, c13)] # 11
|
1167 |
+
pr(11)
|
1168 |
+
conds += [And(Eq(p, q), u > v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True,
|
1169 |
+
re(mu) < 1, c1, c2, c3, c7, c11)] # 12
|
1170 |
+
pr(12)
|
1171 |
+
conds += [And(Eq(p, q), u < v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True,
|
1172 |
+
re(mu) < 1, c1, c2, c3, c6, c11)] # 13
|
1173 |
+
pr(13)
|
1174 |
+
conds += [And(p < q, u > v, bstar >= 0, cstar >= 0,
|
1175 |
+
c1, c2, c3, c4, c7, c11, c13)] # 14
|
1176 |
+
pr(14)
|
1177 |
+
conds += [And(p > q, u < v, bstar >= 0, cstar >= 0,
|
1178 |
+
c1, c2, c3, c5, c6, c11, c13)] # 15
|
1179 |
+
pr(15)
|
1180 |
+
conds += [And(p > q, u > v, bstar >= 0, cstar >= 0,
|
1181 |
+
c1, c2, c3, c5, c7, c8, c11, c13, c14)] # 16
|
1182 |
+
pr(16)
|
1183 |
+
conds += [And(p < q, u < v, bstar >= 0, cstar >= 0,
|
1184 |
+
c1, c2, c3, c4, c6, c9, c11, c13, c14)] # 17
|
1185 |
+
pr(17)
|
1186 |
+
conds += [And(Eq(t, 0), s.is_positive is True, bstar.is_positive is True, phi.is_positive is True, c1, c2, c10)] # 18
|
1187 |
+
pr(18)
|
1188 |
+
conds += [And(Eq(s, 0), t.is_positive is True, bstar.is_positive is True, phi.is_negative is True, c1, c3, c10)] # 19
|
1189 |
+
pr(19)
|
1190 |
+
conds += [And(Eq(n, 0), m.is_positive is True, cstar.is_positive is True, phi.is_negative is True, c1, c2, c12)] # 20
|
1191 |
+
pr(20)
|
1192 |
+
conds += [And(Eq(m, 0), n.is_positive is True, cstar.is_positive is True, phi.is_positive is True, c1, c3, c12)] # 21
|
1193 |
+
pr(21)
|
1194 |
+
conds += [And(Eq(s*t, 0), bstar.is_positive is True, cstar.is_positive is True,
|
1195 |
+
c1, c2, c3, c10, c12)] # 22
|
1196 |
+
pr(22)
|
1197 |
+
conds += [And(Eq(m*n, 0), bstar.is_positive is True, cstar.is_positive is True,
|
1198 |
+
c1, c2, c3, c10, c12)] # 23
|
1199 |
+
pr(23)
|
1200 |
+
|
1201 |
+
# The following case is from [Luke1969]. As far as I can tell, it is *not*
|
1202 |
+
# covered by Prudnikov's.
|
1203 |
+
# Let G1 and G2 be the two G-functions. Suppose the integral exists from
|
1204 |
+
# 0 to a > 0 (this is easy the easy part), that G1 is exponential decay at
|
1205 |
+
# infinity, and that the mellin transform of G2 exists.
|
1206 |
+
# Then the integral exists.
|
1207 |
+
mt1_exists = _check_antecedents_1(g1, x, helper=True)
|
1208 |
+
mt2_exists = _check_antecedents_1(g2, x, helper=True)
|
1209 |
+
conds += [And(mt2_exists, Eq(t, 0), u < s, bstar.is_positive is True, c10, c1, c2, c3)]
|
1210 |
+
pr('E1')
|
1211 |
+
conds += [And(mt2_exists, Eq(s, 0), v < t, bstar.is_positive is True, c10, c1, c2, c3)]
|
1212 |
+
pr('E2')
|
1213 |
+
conds += [And(mt1_exists, Eq(n, 0), p < m, cstar.is_positive is True, c12, c1, c2, c3)]
|
1214 |
+
pr('E3')
|
1215 |
+
conds += [And(mt1_exists, Eq(m, 0), q < n, cstar.is_positive is True, c12, c1, c2, c3)]
|
1216 |
+
pr('E4')
|
1217 |
+
|
1218 |
+
# Let's short-circuit if this worked ...
|
1219 |
+
# the rest is corner-cases and terrible to read.
|
1220 |
+
r = Or(*conds)
|
1221 |
+
if _eval_cond(r) != False:
|
1222 |
+
return r
|
1223 |
+
|
1224 |
+
conds += [And(m + n > p, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True, cstar.is_negative is True,
|
1225 |
+
Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi,
|
1226 |
+
c1, c2, c10, c14, c15)] # 24
|
1227 |
+
pr(24)
|
1228 |
+
conds += [And(m + n > q, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar.is_negative is True,
|
1229 |
+
Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi,
|
1230 |
+
c1, c3, c10, c14, c15)] # 25
|
1231 |
+
pr(25)
|
1232 |
+
conds += [And(Eq(p, q - 1), Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True,
|
1233 |
+
cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)),
|
1234 |
+
c1, c2, c10, c14, c15)] # 26
|
1235 |
+
pr(26)
|
1236 |
+
conds += [And(Eq(p, q + 1), Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True,
|
1237 |
+
cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)),
|
1238 |
+
c1, c3, c10, c14, c15)] # 27
|
1239 |
+
pr(27)
|
1240 |
+
conds += [And(p < q - 1, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True,
|
1241 |
+
cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)),
|
1242 |
+
Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi,
|
1243 |
+
c1, c2, c10, c14, c15)] # 28
|
1244 |
+
pr(28)
|
1245 |
+
conds += [And(
|
1246 |
+
p > q + 1, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar >= 0,
|
1247 |
+
cstar*pi < Abs(unbranched_argument(omega)),
|
1248 |
+
Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi,
|
1249 |
+
c1, c3, c10, c14, c15)] # 29
|
1250 |
+
pr(29)
|
1251 |
+
conds += [And(Eq(n, 0), Eq(phi, 0), s + t > 0, m.is_positive is True, cstar.is_positive is True, bstar.is_negative is True,
|
1252 |
+
Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi,
|
1253 |
+
c1, c2, c12, c14, c15)] # 30
|
1254 |
+
pr(30)
|
1255 |
+
conds += [And(Eq(m, 0), Eq(phi, 0), s + t > v, n.is_positive is True, cstar.is_positive is True, bstar.is_negative is True,
|
1256 |
+
Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi,
|
1257 |
+
c1, c3, c12, c14, c15)] # 31
|
1258 |
+
pr(31)
|
1259 |
+
conds += [And(Eq(n, 0), Eq(phi, 0), Eq(u, v - 1), m.is_positive is True, cstar.is_positive is True,
|
1260 |
+
bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)),
|
1261 |
+
Abs(unbranched_argument(sigma)) < (bstar + 1)*pi,
|
1262 |
+
c1, c2, c12, c14, c15)] # 32
|
1263 |
+
pr(32)
|
1264 |
+
conds += [And(Eq(m, 0), Eq(phi, 0), Eq(u, v + 1), n.is_positive is True, cstar.is_positive is True,
|
1265 |
+
bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)),
|
1266 |
+
Abs(unbranched_argument(sigma)) < (bstar + 1)*pi,
|
1267 |
+
c1, c3, c12, c14, c15)] # 33
|
1268 |
+
pr(33)
|
1269 |
+
conds += [And(
|
1270 |
+
Eq(n, 0), Eq(phi, 0), u < v - 1, m.is_positive is True, cstar.is_positive is True, bstar >= 0,
|
1271 |
+
bstar*pi < Abs(unbranched_argument(sigma)),
|
1272 |
+
Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi,
|
1273 |
+
c1, c2, c12, c14, c15)] # 34
|
1274 |
+
pr(34)
|
1275 |
+
conds += [And(
|
1276 |
+
Eq(m, 0), Eq(phi, 0), u > v + 1, n.is_positive is True, cstar.is_positive is True, bstar >= 0,
|
1277 |
+
bstar*pi < Abs(unbranched_argument(sigma)),
|
1278 |
+
Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi,
|
1279 |
+
c1, c3, c12, c14, c15)] # 35
|
1280 |
+
pr(35)
|
1281 |
+
|
1282 |
+
return Or(*conds)
|
1283 |
+
|
1284 |
+
# NOTE An alternative, but as far as I can tell weaker, set of conditions
|
1285 |
+
# can be found in [L, section 5.6.2].
|
1286 |
+
|
1287 |
+
|
1288 |
+
def _int0oo(g1, g2, x):
|
1289 |
+
"""
|
1290 |
+
Express integral from zero to infinity g1*g2 using a G function,
|
1291 |
+
assuming the necessary conditions are fulfilled.
|
1292 |
+
|
1293 |
+
Examples
|
1294 |
+
========
|
1295 |
+
|
1296 |
+
>>> from sympy.integrals.meijerint import _int0oo
|
1297 |
+
>>> from sympy.abc import s, t, m
|
1298 |
+
>>> from sympy import meijerg, S
|
1299 |
+
>>> g1 = meijerg([], [], [-S(1)/2, 0], [], s**2*t/4)
|
1300 |
+
>>> g2 = meijerg([], [], [m/2], [-m/2], t/4)
|
1301 |
+
>>> _int0oo(g1, g2, t)
|
1302 |
+
4*meijerg(((1/2, 0), ()), ((m/2,), (-m/2,)), s**(-2))/s**2
|
1303 |
+
"""
|
1304 |
+
# See: [L, section 5.6.2, equation (1)]
|
1305 |
+
eta, _ = _get_coeff_exp(g1.argument, x)
|
1306 |
+
omega, _ = _get_coeff_exp(g2.argument, x)
|
1307 |
+
|
1308 |
+
def neg(l):
|
1309 |
+
return [-x for x in l]
|
1310 |
+
a1 = neg(g1.bm) + list(g2.an)
|
1311 |
+
a2 = list(g2.aother) + neg(g1.bother)
|
1312 |
+
b1 = neg(g1.an) + list(g2.bm)
|
1313 |
+
b2 = list(g2.bother) + neg(g1.aother)
|
1314 |
+
return meijerg(a1, a2, b1, b2, omega/eta)/eta
|
1315 |
+
|
1316 |
+
|
1317 |
+
def _rewrite_inversion(fac, po, g, x):
|
1318 |
+
""" Absorb ``po`` == x**s into g. """
|
1319 |
+
_, s = _get_coeff_exp(po, x)
|
1320 |
+
a, b = _get_coeff_exp(g.argument, x)
|
1321 |
+
|
1322 |
+
def tr(l):
|
1323 |
+
return [t + s/b for t in l]
|
1324 |
+
from sympy.simplify import powdenest
|
1325 |
+
return (powdenest(fac/a**(s/b), polar=True),
|
1326 |
+
meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother), g.argument))
|
1327 |
+
|
1328 |
+
|
1329 |
+
def _check_antecedents_inversion(g, x):
|
1330 |
+
""" Check antecedents for the laplace inversion integral. """
|
1331 |
+
_debug('Checking antecedents for inversion:')
|
1332 |
+
z = g.argument
|
1333 |
+
_, e = _get_coeff_exp(z, x)
|
1334 |
+
if e < 0:
|
1335 |
+
_debug(' Flipping G.')
|
1336 |
+
# We want to assume that argument gets large as |x| -> oo
|
1337 |
+
return _check_antecedents_inversion(_flip_g(g), x)
|
1338 |
+
|
1339 |
+
def statement_half(a, b, c, z, plus):
|
1340 |
+
coeff, exponent = _get_coeff_exp(z, x)
|
1341 |
+
a *= exponent
|
1342 |
+
b *= coeff**c
|
1343 |
+
c *= exponent
|
1344 |
+
conds = []
|
1345 |
+
wp = b*exp(S.ImaginaryUnit*re(c)*pi/2)
|
1346 |
+
wm = b*exp(-S.ImaginaryUnit*re(c)*pi/2)
|
1347 |
+
if plus:
|
1348 |
+
w = wp
|
1349 |
+
else:
|
1350 |
+
w = wm
|
1351 |
+
conds += [And(Or(Eq(b, 0), re(c) <= 0), re(a) <= -1)]
|
1352 |
+
conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) < 0)]
|
1353 |
+
conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) <= 0,
|
1354 |
+
re(a) <= -1)]
|
1355 |
+
return Or(*conds)
|
1356 |
+
|
1357 |
+
def statement(a, b, c, z):
|
1358 |
+
""" Provide a convergence statement for z**a * exp(b*z**c),
|
1359 |
+
c/f sphinx docs. """
|
1360 |
+
return And(statement_half(a, b, c, z, True),
|
1361 |
+
statement_half(a, b, c, z, False))
|
1362 |
+
|
1363 |
+
# Notations from [L], section 5.7-10
|
1364 |
+
m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)])
|
1365 |
+
tau = m + n - p
|
1366 |
+
nu = q - m - n
|
1367 |
+
rho = (tau - nu)/2
|
1368 |
+
sigma = q - p
|
1369 |
+
if sigma == 1:
|
1370 |
+
epsilon = S.Half
|
1371 |
+
elif sigma > 1:
|
1372 |
+
epsilon = 1
|
1373 |
+
else:
|
1374 |
+
epsilon = S.NaN
|
1375 |
+
theta = ((1 - sigma)/2 + Add(*g.bq) - Add(*g.ap))/sigma
|
1376 |
+
delta = g.delta
|
1377 |
+
_debugf(' m=%s, n=%s, p=%s, q=%s, tau=%s, nu=%s, rho=%s, sigma=%s',
|
1378 |
+
(m, n, p, q, tau, nu, rho, sigma))
|
1379 |
+
_debugf(' epsilon=%s, theta=%s, delta=%s', (epsilon, theta, delta))
|
1380 |
+
|
1381 |
+
# First check if the computation is valid.
|
1382 |
+
if not (g.delta >= e/2 or (p >= 1 and p >= q)):
|
1383 |
+
_debug(' Computation not valid for these parameters.')
|
1384 |
+
return False
|
1385 |
+
|
1386 |
+
# Now check if the inversion integral exists.
|
1387 |
+
|
1388 |
+
# Test "condition A"
|
1389 |
+
for a, b in itertools.product(g.an, g.bm):
|
1390 |
+
if (a - b).is_integer and a > b:
|
1391 |
+
_debug(' Not a valid G function.')
|
1392 |
+
return False
|
1393 |
+
|
1394 |
+
# There are two cases. If p >= q, we can directly use a slater expansion
|
1395 |
+
# like [L], 5.2 (11). Note in particular that the asymptotics of such an
|
1396 |
+
# expansion even hold when some of the parameters differ by integers, i.e.
|
1397 |
+
# the formula itself would not be valid! (b/c G functions are cts. in their
|
1398 |
+
# parameters)
|
1399 |
+
# When p < q, we need to use the theorems of [L], 5.10.
|
1400 |
+
|
1401 |
+
if p >= q:
|
1402 |
+
_debug(' Using asymptotic Slater expansion.')
|
1403 |
+
return And(*[statement(a - 1, 0, 0, z) for a in g.an])
|
1404 |
+
|
1405 |
+
def E(z):
|
1406 |
+
return And(*[statement(a - 1, 0, 0, z) for a in g.an])
|
1407 |
+
|
1408 |
+
def H(z):
|
1409 |
+
return statement(theta, -sigma, 1/sigma, z)
|
1410 |
+
|
1411 |
+
def Hp(z):
|
1412 |
+
return statement_half(theta, -sigma, 1/sigma, z, True)
|
1413 |
+
|
1414 |
+
def Hm(z):
|
1415 |
+
return statement_half(theta, -sigma, 1/sigma, z, False)
|
1416 |
+
|
1417 |
+
# [L], section 5.10
|
1418 |
+
conds = []
|
1419 |
+
# Theorem 1 -- p < q from test above
|
1420 |
+
conds += [And(1 <= n, 1 <= m, rho*pi - delta >= pi/2, delta > 0,
|
1421 |
+
E(z*exp(S.ImaginaryUnit*pi*(nu + 1))))]
|
1422 |
+
# Theorem 2, statements (2) and (3)
|
1423 |
+
conds += [And(p + 1 <= m, m + 1 <= q, delta > 0, delta < pi/2, n == 0,
|
1424 |
+
(m - p + 1)*pi - delta >= pi/2,
|
1425 |
+
Hp(z*exp(S.ImaginaryUnit*pi*(q - m))),
|
1426 |
+
Hm(z*exp(-S.ImaginaryUnit*pi*(q - m))))]
|
1427 |
+
# Theorem 2, statement (5) -- p < q from test above
|
1428 |
+
conds += [And(m == q, n == 0, delta > 0,
|
1429 |
+
(sigma + epsilon)*pi - delta >= pi/2, H(z))]
|
1430 |
+
# Theorem 3, statements (6) and (7)
|
1431 |
+
conds += [And(Or(And(p <= q - 2, 1 <= tau, tau <= sigma/2),
|
1432 |
+
And(p + 1 <= m + n, m + n <= (p + q)/2)),
|
1433 |
+
delta > 0, delta < pi/2, (tau + 1)*pi - delta >= pi/2,
|
1434 |
+
Hp(z*exp(S.ImaginaryUnit*pi*nu)),
|
1435 |
+
Hm(z*exp(-S.ImaginaryUnit*pi*nu)))]
|
1436 |
+
# Theorem 4, statements (10) and (11) -- p < q from test above
|
1437 |
+
conds += [And(1 <= m, rho > 0, delta > 0, delta + rho*pi < pi/2,
|
1438 |
+
(tau + epsilon)*pi - delta >= pi/2,
|
1439 |
+
Hp(z*exp(S.ImaginaryUnit*pi*nu)),
|
1440 |
+
Hm(z*exp(-S.ImaginaryUnit*pi*nu)))]
|
1441 |
+
# Trivial case
|
1442 |
+
conds += [m == 0]
|
1443 |
+
|
1444 |
+
# TODO
|
1445 |
+
# Theorem 5 is quite general
|
1446 |
+
# Theorem 6 contains special cases for q=p+1
|
1447 |
+
|
1448 |
+
return Or(*conds)
|
1449 |
+
|
1450 |
+
|
1451 |
+
def _int_inversion(g, x, t):
|
1452 |
+
"""
|
1453 |
+
Compute the laplace inversion integral, assuming the formula applies.
|
1454 |
+
"""
|
1455 |
+
b, a = _get_coeff_exp(g.argument, x)
|
1456 |
+
C, g = _inflate_fox_h(meijerg(g.an, g.aother, g.bm, g.bother, b/t**a), -a)
|
1457 |
+
return C/t*g
|
1458 |
+
|
1459 |
+
|
1460 |
+
####################################################################
|
1461 |
+
# Finally, the real meat.
|
1462 |
+
####################################################################
|
1463 |
+
|
1464 |
+
_lookup_table = None
|
1465 |
+
|
1466 |
+
|
1467 |
+
@cacheit
|
1468 |
+
@timeit
|
1469 |
+
def _rewrite_single(f, x, recursive=True):
|
1470 |
+
"""
|
1471 |
+
Try to rewrite f as a sum of single G functions of the form
|
1472 |
+
C*x**s*G(a*x**b), where b is a rational number and C is independent of x.
|
1473 |
+
We guarantee that result.argument.as_coeff_mul(x) returns (a, (x**b,))
|
1474 |
+
or (a, ()).
|
1475 |
+
Returns a list of tuples (C, s, G) and a condition cond.
|
1476 |
+
Returns None on failure.
|
1477 |
+
"""
|
1478 |
+
from .transforms import (mellin_transform, inverse_mellin_transform,
|
1479 |
+
IntegralTransformError, MellinTransformStripError)
|
1480 |
+
|
1481 |
+
global _lookup_table
|
1482 |
+
if not _lookup_table:
|
1483 |
+
_lookup_table = {}
|
1484 |
+
_create_lookup_table(_lookup_table)
|
1485 |
+
|
1486 |
+
if isinstance(f, meijerg):
|
1487 |
+
coeff, m = factor(f.argument, x).as_coeff_mul(x)
|
1488 |
+
if len(m) > 1:
|
1489 |
+
return None
|
1490 |
+
m = m[0]
|
1491 |
+
if m.is_Pow:
|
1492 |
+
if m.base != x or not m.exp.is_Rational:
|
1493 |
+
return None
|
1494 |
+
elif m != x:
|
1495 |
+
return None
|
1496 |
+
return [(1, 0, meijerg(f.an, f.aother, f.bm, f.bother, coeff*m))], True
|
1497 |
+
|
1498 |
+
f_ = f
|
1499 |
+
f = f.subs(x, z)
|
1500 |
+
t = _mytype(f, z)
|
1501 |
+
if t in _lookup_table:
|
1502 |
+
l = _lookup_table[t]
|
1503 |
+
for formula, terms, cond, hint in l:
|
1504 |
+
subs = f.match(formula, old=True)
|
1505 |
+
if subs:
|
1506 |
+
subs_ = {}
|
1507 |
+
for fro, to in subs.items():
|
1508 |
+
subs_[fro] = unpolarify(polarify(to, lift=True),
|
1509 |
+
exponents_only=True)
|
1510 |
+
subs = subs_
|
1511 |
+
if not isinstance(hint, bool):
|
1512 |
+
hint = hint.subs(subs)
|
1513 |
+
if hint == False:
|
1514 |
+
continue
|
1515 |
+
if not isinstance(cond, (bool, BooleanAtom)):
|
1516 |
+
cond = unpolarify(cond.subs(subs))
|
1517 |
+
if _eval_cond(cond) == False:
|
1518 |
+
continue
|
1519 |
+
if not isinstance(terms, list):
|
1520 |
+
terms = terms(subs)
|
1521 |
+
res = []
|
1522 |
+
for fac, g in terms:
|
1523 |
+
r1 = _get_coeff_exp(unpolarify(fac.subs(subs).subs(z, x),
|
1524 |
+
exponents_only=True), x)
|
1525 |
+
try:
|
1526 |
+
g = g.subs(subs).subs(z, x)
|
1527 |
+
except ValueError:
|
1528 |
+
continue
|
1529 |
+
# NOTE these substitutions can in principle introduce oo,
|
1530 |
+
# zoo and other absurdities. It shouldn't matter,
|
1531 |
+
# but better be safe.
|
1532 |
+
if Tuple(*(r1 + (g,))).has(S.Infinity, S.ComplexInfinity, S.NegativeInfinity):
|
1533 |
+
continue
|
1534 |
+
g = meijerg(g.an, g.aother, g.bm, g.bother,
|
1535 |
+
unpolarify(g.argument, exponents_only=True))
|
1536 |
+
res.append(r1 + (g,))
|
1537 |
+
if res:
|
1538 |
+
return res, cond
|
1539 |
+
|
1540 |
+
# try recursive mellin transform
|
1541 |
+
if not recursive:
|
1542 |
+
return None
|
1543 |
+
_debug('Trying recursive Mellin transform method.')
|
1544 |
+
|
1545 |
+
def my_imt(F, s, x, strip):
|
1546 |
+
""" Calling simplify() all the time is slow and not helpful, since
|
1547 |
+
most of the time it only factors things in a way that has to be
|
1548 |
+
un-done anyway. But sometimes it can remove apparent poles. """
|
1549 |
+
# XXX should this be in inverse_mellin_transform?
|
1550 |
+
try:
|
1551 |
+
return inverse_mellin_transform(F, s, x, strip,
|
1552 |
+
as_meijerg=True, needeval=True)
|
1553 |
+
except MellinTransformStripError:
|
1554 |
+
from sympy.simplify import simplify
|
1555 |
+
return inverse_mellin_transform(
|
1556 |
+
simplify(cancel(expand(F))), s, x, strip,
|
1557 |
+
as_meijerg=True, needeval=True)
|
1558 |
+
f = f_
|
1559 |
+
s = _dummy('s', 'rewrite-single', f)
|
1560 |
+
# to avoid infinite recursion, we have to force the two g functions case
|
1561 |
+
|
1562 |
+
def my_integrator(f, x):
|
1563 |
+
r = _meijerint_definite_4(f, x, only_double=True)
|
1564 |
+
if r is not None:
|
1565 |
+
from sympy.simplify import hyperexpand
|
1566 |
+
res, cond = r
|
1567 |
+
res = _my_unpolarify(hyperexpand(res, rewrite='nonrepsmall'))
|
1568 |
+
return Piecewise((res, cond),
|
1569 |
+
(Integral(f, (x, S.Zero, S.Infinity)), True))
|
1570 |
+
return Integral(f, (x, S.Zero, S.Infinity))
|
1571 |
+
try:
|
1572 |
+
F, strip, _ = mellin_transform(f, x, s, integrator=my_integrator,
|
1573 |
+
simplify=False, needeval=True)
|
1574 |
+
g = my_imt(F, s, x, strip)
|
1575 |
+
except IntegralTransformError:
|
1576 |
+
g = None
|
1577 |
+
if g is None:
|
1578 |
+
# We try to find an expression by analytic continuation.
|
1579 |
+
# (also if the dummy is already in the expression, there is no point in
|
1580 |
+
# putting in another one)
|
1581 |
+
a = _dummy_('a', 'rewrite-single')
|
1582 |
+
if a not in f.free_symbols and _is_analytic(f, x):
|
1583 |
+
try:
|
1584 |
+
F, strip, _ = mellin_transform(f.subs(x, a*x), x, s,
|
1585 |
+
integrator=my_integrator,
|
1586 |
+
needeval=True, simplify=False)
|
1587 |
+
g = my_imt(F, s, x, strip).subs(a, 1)
|
1588 |
+
except IntegralTransformError:
|
1589 |
+
g = None
|
1590 |
+
if g is None or g.has(S.Infinity, S.NaN, S.ComplexInfinity):
|
1591 |
+
_debug('Recursive Mellin transform failed.')
|
1592 |
+
return None
|
1593 |
+
args = Add.make_args(g)
|
1594 |
+
res = []
|
1595 |
+
for f in args:
|
1596 |
+
c, m = f.as_coeff_mul(x)
|
1597 |
+
if len(m) > 1:
|
1598 |
+
raise NotImplementedError('Unexpected form...')
|
1599 |
+
g = m[0]
|
1600 |
+
a, b = _get_coeff_exp(g.argument, x)
|
1601 |
+
res += [(c, 0, meijerg(g.an, g.aother, g.bm, g.bother,
|
1602 |
+
unpolarify(polarify(
|
1603 |
+
a, lift=True), exponents_only=True)
|
1604 |
+
*x**b))]
|
1605 |
+
_debug('Recursive Mellin transform worked:', g)
|
1606 |
+
return res, True
|
1607 |
+
|
1608 |
+
|
1609 |
+
def _rewrite1(f, x, recursive=True):
|
1610 |
+
"""
|
1611 |
+
Try to rewrite ``f`` using a (sum of) single G functions with argument a*x**b.
|
1612 |
+
Return fac, po, g such that f = fac*po*g, fac is independent of ``x``.
|
1613 |
+
and po = x**s.
|
1614 |
+
Here g is a result from _rewrite_single.
|
1615 |
+
Return None on failure.
|
1616 |
+
"""
|
1617 |
+
fac, po, g = _split_mul(f, x)
|
1618 |
+
g = _rewrite_single(g, x, recursive)
|
1619 |
+
if g:
|
1620 |
+
return fac, po, g[0], g[1]
|
1621 |
+
|
1622 |
+
|
1623 |
+
def _rewrite2(f, x):
|
1624 |
+
"""
|
1625 |
+
Try to rewrite ``f`` as a product of two G functions of arguments a*x**b.
|
1626 |
+
Return fac, po, g1, g2 such that f = fac*po*g1*g2, where fac is
|
1627 |
+
independent of x and po is x**s.
|
1628 |
+
Here g1 and g2 are results of _rewrite_single.
|
1629 |
+
Returns None on failure.
|
1630 |
+
"""
|
1631 |
+
fac, po, g = _split_mul(f, x)
|
1632 |
+
if any(_rewrite_single(expr, x, False) is None for expr in _mul_args(g)):
|
1633 |
+
return None
|
1634 |
+
l = _mul_as_two_parts(g)
|
1635 |
+
if not l:
|
1636 |
+
return None
|
1637 |
+
l = list(ordered(l, [
|
1638 |
+
lambda p: max(len(_exponents(p[0], x)), len(_exponents(p[1], x))),
|
1639 |
+
lambda p: max(len(_functions(p[0], x)), len(_functions(p[1], x))),
|
1640 |
+
lambda p: max(len(_find_splitting_points(p[0], x)),
|
1641 |
+
len(_find_splitting_points(p[1], x)))]))
|
1642 |
+
|
1643 |
+
for recursive, (fac1, fac2) in itertools.product((False, True), l):
|
1644 |
+
g1 = _rewrite_single(fac1, x, recursive)
|
1645 |
+
g2 = _rewrite_single(fac2, x, recursive)
|
1646 |
+
if g1 and g2:
|
1647 |
+
cond = And(g1[1], g2[1])
|
1648 |
+
if cond != False:
|
1649 |
+
return fac, po, g1[0], g2[0], cond
|
1650 |
+
|
1651 |
+
|
1652 |
+
def meijerint_indefinite(f, x):
|
1653 |
+
"""
|
1654 |
+
Compute an indefinite integral of ``f`` by rewriting it as a G function.
|
1655 |
+
|
1656 |
+
Examples
|
1657 |
+
========
|
1658 |
+
|
1659 |
+
>>> from sympy.integrals.meijerint import meijerint_indefinite
|
1660 |
+
>>> from sympy import sin
|
1661 |
+
>>> from sympy.abc import x
|
1662 |
+
>>> meijerint_indefinite(sin(x), x)
|
1663 |
+
-cos(x)
|
1664 |
+
"""
|
1665 |
+
f = sympify(f)
|
1666 |
+
results = []
|
1667 |
+
for a in sorted(_find_splitting_points(f, x) | {S.Zero}, key=default_sort_key):
|
1668 |
+
res = _meijerint_indefinite_1(f.subs(x, x + a), x)
|
1669 |
+
if not res:
|
1670 |
+
continue
|
1671 |
+
res = res.subs(x, x - a)
|
1672 |
+
if _has(res, hyper, meijerg):
|
1673 |
+
results.append(res)
|
1674 |
+
else:
|
1675 |
+
return res
|
1676 |
+
if f.has(HyperbolicFunction):
|
1677 |
+
_debug('Try rewriting hyperbolics in terms of exp.')
|
1678 |
+
rv = meijerint_indefinite(
|
1679 |
+
_rewrite_hyperbolics_as_exp(f), x)
|
1680 |
+
if rv:
|
1681 |
+
if not isinstance(rv, list):
|
1682 |
+
from sympy.simplify.radsimp import collect
|
1683 |
+
return collect(factor_terms(rv), rv.atoms(exp))
|
1684 |
+
results.extend(rv)
|
1685 |
+
if results:
|
1686 |
+
return next(ordered(results))
|
1687 |
+
|
1688 |
+
|
1689 |
+
def _meijerint_indefinite_1(f, x):
|
1690 |
+
""" Helper that does not attempt any substitution. """
|
1691 |
+
_debug('Trying to compute the indefinite integral of', f, 'wrt', x)
|
1692 |
+
from sympy.simplify import hyperexpand, powdenest
|
1693 |
+
|
1694 |
+
gs = _rewrite1(f, x)
|
1695 |
+
if gs is None:
|
1696 |
+
# Note: the code that calls us will do expand() and try again
|
1697 |
+
return None
|
1698 |
+
|
1699 |
+
fac, po, gl, cond = gs
|
1700 |
+
_debug(' could rewrite:', gs)
|
1701 |
+
res = S.Zero
|
1702 |
+
for C, s, g in gl:
|
1703 |
+
a, b = _get_coeff_exp(g.argument, x)
|
1704 |
+
_, c = _get_coeff_exp(po, x)
|
1705 |
+
c += s
|
1706 |
+
|
1707 |
+
# we do a substitution t=a*x**b, get integrand fac*t**rho*g
|
1708 |
+
fac_ = fac * C / (b*a**((1 + c)/b))
|
1709 |
+
rho = (c + 1)/b - 1
|
1710 |
+
|
1711 |
+
# we now use t**rho*G(params, t) = G(params + rho, t)
|
1712 |
+
# [L, page 150, equation (4)]
|
1713 |
+
# and integral G(params, t) dt = G(1, params+1, 0, t)
|
1714 |
+
# (or a similar expression with 1 and 0 exchanged ... pick the one
|
1715 |
+
# which yields a well-defined function)
|
1716 |
+
# [R, section 5]
|
1717 |
+
# (Note that this dummy will immediately go away again, so we
|
1718 |
+
# can safely pass S.One for ``expr``.)
|
1719 |
+
t = _dummy('t', 'meijerint-indefinite', S.One)
|
1720 |
+
|
1721 |
+
def tr(p):
|
1722 |
+
return [a + rho + 1 for a in p]
|
1723 |
+
if any(b.is_integer and (b <= 0) == True for b in tr(g.bm)):
|
1724 |
+
r = -meijerg(
|
1725 |
+
tr(g.an), tr(g.aother) + [1], tr(g.bm) + [0], tr(g.bother), t)
|
1726 |
+
else:
|
1727 |
+
r = meijerg(
|
1728 |
+
tr(g.an) + [1], tr(g.aother), tr(g.bm), tr(g.bother) + [0], t)
|
1729 |
+
# The antiderivative is most often expected to be defined
|
1730 |
+
# in the neighborhood of x = 0.
|
1731 |
+
if b.is_extended_nonnegative and not f.subs(x, 0).has(S.NaN, S.ComplexInfinity):
|
1732 |
+
place = 0 # Assume we can expand at zero
|
1733 |
+
else:
|
1734 |
+
place = None
|
1735 |
+
r = hyperexpand(r.subs(t, a*x**b), place=place)
|
1736 |
+
|
1737 |
+
# now substitute back
|
1738 |
+
# Note: we really do want the powers of x to combine.
|
1739 |
+
res += powdenest(fac_*r, polar=True)
|
1740 |
+
|
1741 |
+
def _clean(res):
|
1742 |
+
"""This multiplies out superfluous powers of x we created, and chops off
|
1743 |
+
constants:
|
1744 |
+
|
1745 |
+
>> _clean(x*(exp(x)/x - 1/x) + 3)
|
1746 |
+
exp(x)
|
1747 |
+
|
1748 |
+
cancel is used before mul_expand since it is possible for an
|
1749 |
+
expression to have an additive constant that does not become isolated
|
1750 |
+
with simple expansion. Such a situation was identified in issue 6369:
|
1751 |
+
|
1752 |
+
Examples
|
1753 |
+
========
|
1754 |
+
|
1755 |
+
>>> from sympy import sqrt, cancel
|
1756 |
+
>>> from sympy.abc import x
|
1757 |
+
>>> a = sqrt(2*x + 1)
|
1758 |
+
>>> bad = (3*x*a**5 + 2*x - a**5 + 1)/a**2
|
1759 |
+
>>> bad.expand().as_independent(x)[0]
|
1760 |
+
0
|
1761 |
+
>>> cancel(bad).expand().as_independent(x)[0]
|
1762 |
+
1
|
1763 |
+
"""
|
1764 |
+
res = expand_mul(cancel(res), deep=False)
|
1765 |
+
return Add._from_args(res.as_coeff_add(x)[1])
|
1766 |
+
|
1767 |
+
res = piecewise_fold(res, evaluate=None)
|
1768 |
+
if res.is_Piecewise:
|
1769 |
+
newargs = []
|
1770 |
+
for e, c in res.args:
|
1771 |
+
e = _my_unpolarify(_clean(e))
|
1772 |
+
newargs += [(e, c)]
|
1773 |
+
res = Piecewise(*newargs, evaluate=False)
|
1774 |
+
else:
|
1775 |
+
res = _my_unpolarify(_clean(res))
|
1776 |
+
return Piecewise((res, _my_unpolarify(cond)), (Integral(f, x), True))
|
1777 |
+
|
1778 |
+
|
1779 |
+
@timeit
|
1780 |
+
def meijerint_definite(f, x, a, b):
|
1781 |
+
"""
|
1782 |
+
Integrate ``f`` over the interval [``a``, ``b``], by rewriting it as a product
|
1783 |
+
of two G functions, or as a single G function.
|
1784 |
+
|
1785 |
+
Return res, cond, where cond are convergence conditions.
|
1786 |
+
|
1787 |
+
Examples
|
1788 |
+
========
|
1789 |
+
|
1790 |
+
>>> from sympy.integrals.meijerint import meijerint_definite
|
1791 |
+
>>> from sympy import exp, oo
|
1792 |
+
>>> from sympy.abc import x
|
1793 |
+
>>> meijerint_definite(exp(-x**2), x, -oo, oo)
|
1794 |
+
(sqrt(pi), True)
|
1795 |
+
|
1796 |
+
This function is implemented as a succession of functions
|
1797 |
+
meijerint_definite, _meijerint_definite_2, _meijerint_definite_3,
|
1798 |
+
_meijerint_definite_4. Each function in the list calls the next one
|
1799 |
+
(presumably) several times. This means that calling meijerint_definite
|
1800 |
+
can be very costly.
|
1801 |
+
"""
|
1802 |
+
# This consists of three steps:
|
1803 |
+
# 1) Change the integration limits to 0, oo
|
1804 |
+
# 2) Rewrite in terms of G functions
|
1805 |
+
# 3) Evaluate the integral
|
1806 |
+
#
|
1807 |
+
# There are usually several ways of doing this, and we want to try all.
|
1808 |
+
# This function does (1), calls _meijerint_definite_2 for step (2).
|
1809 |
+
_debugf('Integrating %s wrt %s from %s to %s.', (f, x, a, b))
|
1810 |
+
f = sympify(f)
|
1811 |
+
if f.has(DiracDelta):
|
1812 |
+
_debug('Integrand has DiracDelta terms - giving up.')
|
1813 |
+
return None
|
1814 |
+
|
1815 |
+
if f.has(SingularityFunction):
|
1816 |
+
_debug('Integrand has Singularity Function terms - giving up.')
|
1817 |
+
return None
|
1818 |
+
|
1819 |
+
f_, x_, a_, b_ = f, x, a, b
|
1820 |
+
|
1821 |
+
# Let's use a dummy in case any of the boundaries has x.
|
1822 |
+
d = Dummy('x')
|
1823 |
+
f = f.subs(x, d)
|
1824 |
+
x = d
|
1825 |
+
|
1826 |
+
if a == b:
|
1827 |
+
return (S.Zero, True)
|
1828 |
+
|
1829 |
+
results = []
|
1830 |
+
if a is S.NegativeInfinity and b is not S.Infinity:
|
1831 |
+
return meijerint_definite(f.subs(x, -x), x, -b, -a)
|
1832 |
+
|
1833 |
+
elif a is S.NegativeInfinity:
|
1834 |
+
# Integrating -oo to oo. We need to find a place to split the integral.
|
1835 |
+
_debug(' Integrating -oo to +oo.')
|
1836 |
+
innermost = _find_splitting_points(f, x)
|
1837 |
+
_debug(' Sensible splitting points:', innermost)
|
1838 |
+
for c in sorted(innermost, key=default_sort_key, reverse=True) + [S.Zero]:
|
1839 |
+
_debug(' Trying to split at', c)
|
1840 |
+
if not c.is_extended_real:
|
1841 |
+
_debug(' Non-real splitting point.')
|
1842 |
+
continue
|
1843 |
+
res1 = _meijerint_definite_2(f.subs(x, x + c), x)
|
1844 |
+
if res1 is None:
|
1845 |
+
_debug(' But could not compute first integral.')
|
1846 |
+
continue
|
1847 |
+
res2 = _meijerint_definite_2(f.subs(x, c - x), x)
|
1848 |
+
if res2 is None:
|
1849 |
+
_debug(' But could not compute second integral.')
|
1850 |
+
continue
|
1851 |
+
res1, cond1 = res1
|
1852 |
+
res2, cond2 = res2
|
1853 |
+
cond = _condsimp(And(cond1, cond2))
|
1854 |
+
if cond == False:
|
1855 |
+
_debug(' But combined condition is always false.')
|
1856 |
+
continue
|
1857 |
+
res = res1 + res2
|
1858 |
+
return res, cond
|
1859 |
+
|
1860 |
+
elif a is S.Infinity:
|
1861 |
+
res = meijerint_definite(f, x, b, S.Infinity)
|
1862 |
+
return -res[0], res[1]
|
1863 |
+
|
1864 |
+
elif (a, b) == (S.Zero, S.Infinity):
|
1865 |
+
# This is a common case - try it directly first.
|
1866 |
+
res = _meijerint_definite_2(f, x)
|
1867 |
+
if res:
|
1868 |
+
if _has(res[0], meijerg):
|
1869 |
+
results.append(res)
|
1870 |
+
else:
|
1871 |
+
return res
|
1872 |
+
|
1873 |
+
else:
|
1874 |
+
if b is S.Infinity:
|
1875 |
+
for split in _find_splitting_points(f, x):
|
1876 |
+
if (a - split >= 0) == True:
|
1877 |
+
_debugf('Trying x -> x + %s', split)
|
1878 |
+
res = _meijerint_definite_2(f.subs(x, x + split)
|
1879 |
+
*Heaviside(x + split - a), x)
|
1880 |
+
if res:
|
1881 |
+
if _has(res[0], meijerg):
|
1882 |
+
results.append(res)
|
1883 |
+
else:
|
1884 |
+
return res
|
1885 |
+
|
1886 |
+
f = f.subs(x, x + a)
|
1887 |
+
b = b - a
|
1888 |
+
a = 0
|
1889 |
+
if b is not S.Infinity:
|
1890 |
+
phi = exp(S.ImaginaryUnit*arg(b))
|
1891 |
+
b = Abs(b)
|
1892 |
+
f = f.subs(x, phi*x)
|
1893 |
+
f *= Heaviside(b - x)*phi
|
1894 |
+
b = S.Infinity
|
1895 |
+
|
1896 |
+
_debug('Changed limits to', a, b)
|
1897 |
+
_debug('Changed function to', f)
|
1898 |
+
res = _meijerint_definite_2(f, x)
|
1899 |
+
if res:
|
1900 |
+
if _has(res[0], meijerg):
|
1901 |
+
results.append(res)
|
1902 |
+
else:
|
1903 |
+
return res
|
1904 |
+
if f_.has(HyperbolicFunction):
|
1905 |
+
_debug('Try rewriting hyperbolics in terms of exp.')
|
1906 |
+
rv = meijerint_definite(
|
1907 |
+
_rewrite_hyperbolics_as_exp(f_), x_, a_, b_)
|
1908 |
+
if rv:
|
1909 |
+
if not isinstance(rv, list):
|
1910 |
+
from sympy.simplify.radsimp import collect
|
1911 |
+
rv = (collect(factor_terms(rv[0]), rv[0].atoms(exp)),) + rv[1:]
|
1912 |
+
return rv
|
1913 |
+
results.extend(rv)
|
1914 |
+
if results:
|
1915 |
+
return next(ordered(results))
|
1916 |
+
|
1917 |
+
|
1918 |
+
def _guess_expansion(f, x):
|
1919 |
+
""" Try to guess sensible rewritings for integrand f(x). """
|
1920 |
+
res = [(f, 'original integrand')]
|
1921 |
+
|
1922 |
+
orig = res[-1][0]
|
1923 |
+
saw = {orig}
|
1924 |
+
expanded = expand_mul(orig)
|
1925 |
+
if expanded not in saw:
|
1926 |
+
res += [(expanded, 'expand_mul')]
|
1927 |
+
saw.add(expanded)
|
1928 |
+
|
1929 |
+
expanded = expand(orig)
|
1930 |
+
if expanded not in saw:
|
1931 |
+
res += [(expanded, 'expand')]
|
1932 |
+
saw.add(expanded)
|
1933 |
+
|
1934 |
+
if orig.has(TrigonometricFunction, HyperbolicFunction):
|
1935 |
+
expanded = expand_mul(expand_trig(orig))
|
1936 |
+
if expanded not in saw:
|
1937 |
+
res += [(expanded, 'expand_trig, expand_mul')]
|
1938 |
+
saw.add(expanded)
|
1939 |
+
|
1940 |
+
if orig.has(cos, sin):
|
1941 |
+
from sympy.simplify.fu import sincos_to_sum
|
1942 |
+
reduced = sincos_to_sum(orig)
|
1943 |
+
if reduced not in saw:
|
1944 |
+
res += [(reduced, 'trig power reduction')]
|
1945 |
+
saw.add(reduced)
|
1946 |
+
|
1947 |
+
return res
|
1948 |
+
|
1949 |
+
|
1950 |
+
def _meijerint_definite_2(f, x):
|
1951 |
+
"""
|
1952 |
+
Try to integrate f dx from zero to infinity.
|
1953 |
+
|
1954 |
+
The body of this function computes various 'simplifications'
|
1955 |
+
f1, f2, ... of f (e.g. by calling expand_mul(), trigexpand()
|
1956 |
+
- see _guess_expansion) and calls _meijerint_definite_3 with each of
|
1957 |
+
these in succession.
|
1958 |
+
If _meijerint_definite_3 succeeds with any of the simplified functions,
|
1959 |
+
returns this result.
|
1960 |
+
"""
|
1961 |
+
# This function does preparation for (2), calls
|
1962 |
+
# _meijerint_definite_3 for (2) and (3) combined.
|
1963 |
+
|
1964 |
+
# use a positive dummy - we integrate from 0 to oo
|
1965 |
+
# XXX if a nonnegative symbol is used there will be test failures
|
1966 |
+
dummy = _dummy('x', 'meijerint-definite2', f, positive=True)
|
1967 |
+
f = f.subs(x, dummy)
|
1968 |
+
x = dummy
|
1969 |
+
|
1970 |
+
if f == 0:
|
1971 |
+
return S.Zero, True
|
1972 |
+
|
1973 |
+
for g, explanation in _guess_expansion(f, x):
|
1974 |
+
_debug('Trying', explanation)
|
1975 |
+
res = _meijerint_definite_3(g, x)
|
1976 |
+
if res:
|
1977 |
+
return res
|
1978 |
+
|
1979 |
+
|
1980 |
+
def _meijerint_definite_3(f, x):
|
1981 |
+
"""
|
1982 |
+
Try to integrate f dx from zero to infinity.
|
1983 |
+
|
1984 |
+
This function calls _meijerint_definite_4 to try to compute the
|
1985 |
+
integral. If this fails, it tries using linearity.
|
1986 |
+
"""
|
1987 |
+
res = _meijerint_definite_4(f, x)
|
1988 |
+
if res and res[1] != False:
|
1989 |
+
return res
|
1990 |
+
if f.is_Add:
|
1991 |
+
_debug('Expanding and evaluating all terms.')
|
1992 |
+
ress = [_meijerint_definite_4(g, x) for g in f.args]
|
1993 |
+
if all(r is not None for r in ress):
|
1994 |
+
conds = []
|
1995 |
+
res = S.Zero
|
1996 |
+
for r, c in ress:
|
1997 |
+
res += r
|
1998 |
+
conds += [c]
|
1999 |
+
c = And(*conds)
|
2000 |
+
if c != False:
|
2001 |
+
return res, c
|
2002 |
+
|
2003 |
+
|
2004 |
+
def _my_unpolarify(f):
|
2005 |
+
return _eval_cond(unpolarify(f))
|
2006 |
+
|
2007 |
+
|
2008 |
+
@timeit
|
2009 |
+
def _meijerint_definite_4(f, x, only_double=False):
|
2010 |
+
"""
|
2011 |
+
Try to integrate f dx from zero to infinity.
|
2012 |
+
|
2013 |
+
Explanation
|
2014 |
+
===========
|
2015 |
+
|
2016 |
+
This function tries to apply the integration theorems found in literature,
|
2017 |
+
i.e. it tries to rewrite f as either one or a product of two G-functions.
|
2018 |
+
|
2019 |
+
The parameter ``only_double`` is used internally in the recursive algorithm
|
2020 |
+
to disable trying to rewrite f as a single G-function.
|
2021 |
+
"""
|
2022 |
+
from sympy.simplify import hyperexpand
|
2023 |
+
# This function does (2) and (3)
|
2024 |
+
_debug('Integrating', f)
|
2025 |
+
# Try single G function.
|
2026 |
+
if not only_double:
|
2027 |
+
gs = _rewrite1(f, x, recursive=False)
|
2028 |
+
if gs is not None:
|
2029 |
+
fac, po, g, cond = gs
|
2030 |
+
_debug('Could rewrite as single G function:', fac, po, g)
|
2031 |
+
res = S.Zero
|
2032 |
+
for C, s, f in g:
|
2033 |
+
if C == 0:
|
2034 |
+
continue
|
2035 |
+
C, f = _rewrite_saxena_1(fac*C, po*x**s, f, x)
|
2036 |
+
res += C*_int0oo_1(f, x)
|
2037 |
+
cond = And(cond, _check_antecedents_1(f, x))
|
2038 |
+
if cond == False:
|
2039 |
+
break
|
2040 |
+
cond = _my_unpolarify(cond)
|
2041 |
+
if cond == False:
|
2042 |
+
_debug('But cond is always False.')
|
2043 |
+
else:
|
2044 |
+
_debug('Result before branch substitutions is:', res)
|
2045 |
+
return _my_unpolarify(hyperexpand(res)), cond
|
2046 |
+
|
2047 |
+
# Try two G functions.
|
2048 |
+
gs = _rewrite2(f, x)
|
2049 |
+
if gs is not None:
|
2050 |
+
for full_pb in [False, True]:
|
2051 |
+
fac, po, g1, g2, cond = gs
|
2052 |
+
_debug('Could rewrite as two G functions:', fac, po, g1, g2)
|
2053 |
+
res = S.Zero
|
2054 |
+
for C1, s1, f1 in g1:
|
2055 |
+
for C2, s2, f2 in g2:
|
2056 |
+
r = _rewrite_saxena(fac*C1*C2, po*x**(s1 + s2),
|
2057 |
+
f1, f2, x, full_pb)
|
2058 |
+
if r is None:
|
2059 |
+
_debug('Non-rational exponents.')
|
2060 |
+
return
|
2061 |
+
C, f1_, f2_ = r
|
2062 |
+
_debug('Saxena subst for yielded:', C, f1_, f2_)
|
2063 |
+
cond = And(cond, _check_antecedents(f1_, f2_, x))
|
2064 |
+
if cond == False:
|
2065 |
+
break
|
2066 |
+
res += C*_int0oo(f1_, f2_, x)
|
2067 |
+
else:
|
2068 |
+
continue
|
2069 |
+
break
|
2070 |
+
cond = _my_unpolarify(cond)
|
2071 |
+
if cond == False:
|
2072 |
+
_debugf('But cond is always False (full_pb=%s).', full_pb)
|
2073 |
+
else:
|
2074 |
+
_debugf('Result before branch substitutions is: %s', (res, ))
|
2075 |
+
if only_double:
|
2076 |
+
return res, cond
|
2077 |
+
return _my_unpolarify(hyperexpand(res)), cond
|
2078 |
+
|
2079 |
+
|
2080 |
+
def meijerint_inversion(f, x, t):
|
2081 |
+
r"""
|
2082 |
+
Compute the inverse laplace transform
|
2083 |
+
$\int_{c+i\infty}^{c-i\infty} f(x) e^{tx}\, dx$,
|
2084 |
+
for real c larger than the real part of all singularities of ``f``.
|
2085 |
+
|
2086 |
+
Note that ``t`` is always assumed real and positive.
|
2087 |
+
|
2088 |
+
Return None if the integral does not exist or could not be evaluated.
|
2089 |
+
|
2090 |
+
Examples
|
2091 |
+
========
|
2092 |
+
|
2093 |
+
>>> from sympy.abc import x, t
|
2094 |
+
>>> from sympy.integrals.meijerint import meijerint_inversion
|
2095 |
+
>>> meijerint_inversion(1/x, x, t)
|
2096 |
+
Heaviside(t)
|
2097 |
+
"""
|
2098 |
+
f_ = f
|
2099 |
+
t_ = t
|
2100 |
+
t = Dummy('t', polar=True) # We don't want sqrt(t**2) = abs(t) etc
|
2101 |
+
f = f.subs(t_, t)
|
2102 |
+
_debug('Laplace-inverting', f)
|
2103 |
+
if not _is_analytic(f, x):
|
2104 |
+
_debug('But expression is not analytic.')
|
2105 |
+
return None
|
2106 |
+
# Exponentials correspond to shifts; we filter them out and then
|
2107 |
+
# shift the result later. If we are given an Add this will not
|
2108 |
+
# work, but the calling code will take care of that.
|
2109 |
+
shift = S.Zero
|
2110 |
+
|
2111 |
+
if f.is_Mul:
|
2112 |
+
args = list(f.args)
|
2113 |
+
elif isinstance(f, exp):
|
2114 |
+
args = [f]
|
2115 |
+
else:
|
2116 |
+
args = None
|
2117 |
+
|
2118 |
+
if args:
|
2119 |
+
newargs = []
|
2120 |
+
exponentials = []
|
2121 |
+
while args:
|
2122 |
+
arg = args.pop()
|
2123 |
+
if isinstance(arg, exp):
|
2124 |
+
arg2 = expand(arg)
|
2125 |
+
if arg2.is_Mul:
|
2126 |
+
args += arg2.args
|
2127 |
+
continue
|
2128 |
+
try:
|
2129 |
+
a, b = _get_coeff_exp(arg.args[0], x)
|
2130 |
+
except _CoeffExpValueError:
|
2131 |
+
b = 0
|
2132 |
+
if b == 1:
|
2133 |
+
exponentials.append(a)
|
2134 |
+
else:
|
2135 |
+
newargs.append(arg)
|
2136 |
+
elif arg.is_Pow:
|
2137 |
+
arg2 = expand(arg)
|
2138 |
+
if arg2.is_Mul:
|
2139 |
+
args += arg2.args
|
2140 |
+
continue
|
2141 |
+
if x not in arg.base.free_symbols:
|
2142 |
+
try:
|
2143 |
+
a, b = _get_coeff_exp(arg.exp, x)
|
2144 |
+
except _CoeffExpValueError:
|
2145 |
+
b = 0
|
2146 |
+
if b == 1:
|
2147 |
+
exponentials.append(a*log(arg.base))
|
2148 |
+
newargs.append(arg)
|
2149 |
+
else:
|
2150 |
+
newargs.append(arg)
|
2151 |
+
shift = Add(*exponentials)
|
2152 |
+
f = Mul(*newargs)
|
2153 |
+
|
2154 |
+
if x not in f.free_symbols:
|
2155 |
+
_debug('Expression consists of constant and exp shift:', f, shift)
|
2156 |
+
cond = Eq(im(shift), 0)
|
2157 |
+
if cond == False:
|
2158 |
+
_debug('but shift is nonreal, cannot be a Laplace transform')
|
2159 |
+
return None
|
2160 |
+
res = f*DiracDelta(t + shift)
|
2161 |
+
_debug('Result is a delta function, possibly conditional:', res, cond)
|
2162 |
+
# cond is True or Eq
|
2163 |
+
return Piecewise((res.subs(t, t_), cond))
|
2164 |
+
|
2165 |
+
gs = _rewrite1(f, x)
|
2166 |
+
if gs is not None:
|
2167 |
+
fac, po, g, cond = gs
|
2168 |
+
_debug('Could rewrite as single G function:', fac, po, g)
|
2169 |
+
res = S.Zero
|
2170 |
+
for C, s, f in g:
|
2171 |
+
C, f = _rewrite_inversion(fac*C, po*x**s, f, x)
|
2172 |
+
res += C*_int_inversion(f, x, t)
|
2173 |
+
cond = And(cond, _check_antecedents_inversion(f, x))
|
2174 |
+
if cond == False:
|
2175 |
+
break
|
2176 |
+
cond = _my_unpolarify(cond)
|
2177 |
+
if cond == False:
|
2178 |
+
_debug('But cond is always False.')
|
2179 |
+
else:
|
2180 |
+
_debug('Result before branch substitution:', res)
|
2181 |
+
from sympy.simplify import hyperexpand
|
2182 |
+
res = _my_unpolarify(hyperexpand(res))
|
2183 |
+
if not res.has(Heaviside):
|
2184 |
+
res *= Heaviside(t)
|
2185 |
+
res = res.subs(t, t + shift)
|
2186 |
+
if not isinstance(cond, bool):
|
2187 |
+
cond = cond.subs(t, t + shift)
|
2188 |
+
from .transforms import InverseLaplaceTransform
|
2189 |
+
return Piecewise((res.subs(t, t_), cond),
|
2190 |
+
(InverseLaplaceTransform(f_.subs(t, t_), x, t_, None), True))
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/meijerint_doc.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" This module cooks up a docstring when imported. Its only purpose is to
|
2 |
+
be displayed in the sphinx documentation. """
|
3 |
+
|
4 |
+
from __future__ import annotations
|
5 |
+
from typing import Any
|
6 |
+
|
7 |
+
from sympy.integrals.meijerint import _create_lookup_table
|
8 |
+
from sympy.core.add import Add
|
9 |
+
from sympy.core.basic import Basic
|
10 |
+
from sympy.core.relational import Eq
|
11 |
+
from sympy.core.symbol import Symbol
|
12 |
+
from sympy.printing.latex import latex
|
13 |
+
|
14 |
+
t: dict[tuple[type[Basic], ...], list[Any]] = {}
|
15 |
+
_create_lookup_table(t)
|
16 |
+
|
17 |
+
|
18 |
+
doc = ""
|
19 |
+
for about, category in t.items():
|
20 |
+
if about == ():
|
21 |
+
doc += 'Elementary functions:\n\n'
|
22 |
+
else:
|
23 |
+
doc += 'Functions involving ' + ', '.join('`%s`' % latex(
|
24 |
+
list(category[0][0].atoms(func))[0]) for func in about) + ':\n\n'
|
25 |
+
for formula, gs, cond, hint in category:
|
26 |
+
if not isinstance(gs, list):
|
27 |
+
g = Symbol('\\text{generated}')
|
28 |
+
else:
|
29 |
+
g = Add(*[fac*f for (fac, f) in gs])
|
30 |
+
obj = Eq(formula, g)
|
31 |
+
if cond is True:
|
32 |
+
cond = ""
|
33 |
+
else:
|
34 |
+
cond = ',\\text{ if } %s' % latex(cond)
|
35 |
+
doc += ".. math::\n %s%s\n\n" % (latex(obj), cond)
|
36 |
+
|
37 |
+
__doc__ = doc
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/prde.py
ADDED
@@ -0,0 +1,1332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Algorithms for solving Parametric Risch Differential Equations.
|
3 |
+
|
4 |
+
The methods used for solving Parametric Risch Differential Equations parallel
|
5 |
+
those for solving Risch Differential Equations. See the outline in the
|
6 |
+
docstring of rde.py for more information.
|
7 |
+
|
8 |
+
The Parametric Risch Differential Equation problem is, given f, g1, ..., gm in
|
9 |
+
K(t), to determine if there exist y in K(t) and c1, ..., cm in Const(K) such
|
10 |
+
that Dy + f*y == Sum(ci*gi, (i, 1, m)), and to find such y and ci if they exist.
|
11 |
+
|
12 |
+
For the algorithms here G is a list of tuples of factions of the terms on the
|
13 |
+
right hand side of the equation (i.e., gi in k(t)), and Q is a list of terms on
|
14 |
+
the right hand side of the equation (i.e., qi in k[t]). See the docstring of
|
15 |
+
each function for more information.
|
16 |
+
"""
|
17 |
+
import itertools
|
18 |
+
from functools import reduce
|
19 |
+
|
20 |
+
from sympy.core import Dummy, ilcm, Add, Mul, Pow, S
|
21 |
+
from sympy.integrals.rde import (order_at, order_at_oo, weak_normalizer,
|
22 |
+
bound_degree)
|
23 |
+
from sympy.integrals.risch import (gcdex_diophantine, frac_in, derivation,
|
24 |
+
residue_reduce, splitfactor, residue_reduce_derivation, DecrementLevel,
|
25 |
+
recognize_log_derivative)
|
26 |
+
from sympy.polys import Poly, lcm, cancel, sqf_list
|
27 |
+
from sympy.polys.polymatrix import PolyMatrix as Matrix
|
28 |
+
from sympy.solvers import solve
|
29 |
+
|
30 |
+
zeros = Matrix.zeros
|
31 |
+
eye = Matrix.eye
|
32 |
+
|
33 |
+
|
34 |
+
def prde_normal_denom(fa, fd, G, DE):
|
35 |
+
"""
|
36 |
+
Parametric Risch Differential Equation - Normal part of the denominator.
|
37 |
+
|
38 |
+
Explanation
|
39 |
+
===========
|
40 |
+
|
41 |
+
Given a derivation D on k[t] and f, g1, ..., gm in k(t) with f weakly
|
42 |
+
normalized with respect to t, return the tuple (a, b, G, h) such that
|
43 |
+
a, h in k[t], b in k<t>, G = [g1, ..., gm] in k(t)^m, and for any solution
|
44 |
+
c1, ..., cm in Const(k) and y in k(t) of Dy + f*y == Sum(ci*gi, (i, 1, m)),
|
45 |
+
q == y*h in k<t> satisfies a*Dq + b*q == Sum(ci*Gi, (i, 1, m)).
|
46 |
+
"""
|
47 |
+
dn, ds = splitfactor(fd, DE)
|
48 |
+
Gas, Gds = list(zip(*G))
|
49 |
+
gd = reduce(lambda i, j: i.lcm(j), Gds, Poly(1, DE.t))
|
50 |
+
en, es = splitfactor(gd, DE)
|
51 |
+
|
52 |
+
p = dn.gcd(en)
|
53 |
+
h = en.gcd(en.diff(DE.t)).quo(p.gcd(p.diff(DE.t)))
|
54 |
+
|
55 |
+
a = dn*h
|
56 |
+
c = a*h
|
57 |
+
|
58 |
+
ba = a*fa - dn*derivation(h, DE)*fd
|
59 |
+
ba, bd = ba.cancel(fd, include=True)
|
60 |
+
|
61 |
+
G = [(c*A).cancel(D, include=True) for A, D in G]
|
62 |
+
|
63 |
+
return (a, (ba, bd), G, h)
|
64 |
+
|
65 |
+
def real_imag(ba, bd, gen):
|
66 |
+
"""
|
67 |
+
Helper function, to get the real and imaginary part of a rational function
|
68 |
+
evaluated at sqrt(-1) without actually evaluating it at sqrt(-1).
|
69 |
+
|
70 |
+
Explanation
|
71 |
+
===========
|
72 |
+
|
73 |
+
Separates the even and odd power terms by checking the degree of terms wrt
|
74 |
+
mod 4. Returns a tuple (ba[0], ba[1], bd) where ba[0] is real part
|
75 |
+
of the numerator ba[1] is the imaginary part and bd is the denominator
|
76 |
+
of the rational function.
|
77 |
+
"""
|
78 |
+
bd = bd.as_poly(gen).as_dict()
|
79 |
+
ba = ba.as_poly(gen).as_dict()
|
80 |
+
denom_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in bd.items()]
|
81 |
+
denom_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in bd.items()]
|
82 |
+
bd_real = sum(r for r in denom_real)
|
83 |
+
bd_imag = sum(r for r in denom_imag)
|
84 |
+
num_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in ba.items()]
|
85 |
+
num_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in ba.items()]
|
86 |
+
ba_real = sum(r for r in num_real)
|
87 |
+
ba_imag = sum(r for r in num_imag)
|
88 |
+
ba = ((ba_real*bd_real + ba_imag*bd_imag).as_poly(gen), (ba_imag*bd_real - ba_real*bd_imag).as_poly(gen))
|
89 |
+
bd = (bd_real*bd_real + bd_imag*bd_imag).as_poly(gen)
|
90 |
+
return (ba[0], ba[1], bd)
|
91 |
+
|
92 |
+
|
93 |
+
def prde_special_denom(a, ba, bd, G, DE, case='auto'):
|
94 |
+
"""
|
95 |
+
Parametric Risch Differential Equation - Special part of the denominator.
|
96 |
+
|
97 |
+
Explanation
|
98 |
+
===========
|
99 |
+
|
100 |
+
Case is one of {'exp', 'tan', 'primitive'} for the hyperexponential,
|
101 |
+
hypertangent, and primitive cases, respectively. For the hyperexponential
|
102 |
+
(resp. hypertangent) case, given a derivation D on k[t] and a in k[t],
|
103 |
+
b in k<t>, and g1, ..., gm in k(t) with Dt/t in k (resp. Dt/(t**2 + 1) in
|
104 |
+
k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp.
|
105 |
+
gcd(a, t**2 + 1) == 1), return the tuple (A, B, GG, h) such that A, B, h in
|
106 |
+
k[t], GG = [gg1, ..., ggm] in k(t)^m, and for any solution c1, ..., cm in
|
107 |
+
Const(k) and q in k<t> of a*Dq + b*q == Sum(ci*gi, (i, 1, m)), r == q*h in
|
108 |
+
k[t] satisfies A*Dr + B*r == Sum(ci*ggi, (i, 1, m)).
|
109 |
+
|
110 |
+
For case == 'primitive', k<t> == k[t], so it returns (a, b, G, 1) in this
|
111 |
+
case.
|
112 |
+
"""
|
113 |
+
# TODO: Merge this with the very similar special_denom() in rde.py
|
114 |
+
if case == 'auto':
|
115 |
+
case = DE.case
|
116 |
+
|
117 |
+
if case == 'exp':
|
118 |
+
p = Poly(DE.t, DE.t)
|
119 |
+
elif case == 'tan':
|
120 |
+
p = Poly(DE.t**2 + 1, DE.t)
|
121 |
+
elif case in ('primitive', 'base'):
|
122 |
+
B = ba.quo(bd)
|
123 |
+
return (a, B, G, Poly(1, DE.t))
|
124 |
+
else:
|
125 |
+
raise ValueError("case must be one of {'exp', 'tan', 'primitive', "
|
126 |
+
"'base'}, not %s." % case)
|
127 |
+
|
128 |
+
nb = order_at(ba, p, DE.t) - order_at(bd, p, DE.t)
|
129 |
+
nc = min([order_at(Ga, p, DE.t) - order_at(Gd, p, DE.t) for Ga, Gd in G])
|
130 |
+
n = min(0, nc - min(0, nb))
|
131 |
+
if not nb:
|
132 |
+
# Possible cancellation.
|
133 |
+
if case == 'exp':
|
134 |
+
dcoeff = DE.d.quo(Poly(DE.t, DE.t))
|
135 |
+
with DecrementLevel(DE): # We are guaranteed to not have problems,
|
136 |
+
# because case != 'base'.
|
137 |
+
alphaa, alphad = frac_in(-ba.eval(0)/bd.eval(0)/a.eval(0), DE.t)
|
138 |
+
etaa, etad = frac_in(dcoeff, DE.t)
|
139 |
+
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
|
140 |
+
if A is not None:
|
141 |
+
Q, m, z = A
|
142 |
+
if Q == 1:
|
143 |
+
n = min(n, m)
|
144 |
+
|
145 |
+
elif case == 'tan':
|
146 |
+
dcoeff = DE.d.quo(Poly(DE.t**2 + 1, DE.t))
|
147 |
+
with DecrementLevel(DE): # We are guaranteed to not have problems,
|
148 |
+
# because case != 'base'.
|
149 |
+
betaa, alphaa, alphad = real_imag(ba, bd*a, DE.t)
|
150 |
+
betad = alphad
|
151 |
+
etaa, etad = frac_in(dcoeff, DE.t)
|
152 |
+
if recognize_log_derivative(Poly(2, DE.t)*betaa, betad, DE):
|
153 |
+
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
|
154 |
+
B = parametric_log_deriv(betaa, betad, etaa, etad, DE)
|
155 |
+
if A is not None and B is not None:
|
156 |
+
Q, s, z = A
|
157 |
+
# TODO: Add test
|
158 |
+
if Q == 1:
|
159 |
+
n = min(n, s/2)
|
160 |
+
|
161 |
+
N = max(0, -nb)
|
162 |
+
pN = p**N
|
163 |
+
pn = p**-n # This is 1/h
|
164 |
+
|
165 |
+
A = a*pN
|
166 |
+
B = ba*pN.quo(bd) + Poly(n, DE.t)*a*derivation(p, DE).quo(p)*pN
|
167 |
+
G = [(Ga*pN*pn).cancel(Gd, include=True) for Ga, Gd in G]
|
168 |
+
h = pn
|
169 |
+
|
170 |
+
# (a*p**N, (b + n*a*Dp/p)*p**N, g1*p**(N - n), ..., gm*p**(N - n), p**-n)
|
171 |
+
return (A, B, G, h)
|
172 |
+
|
173 |
+
|
174 |
+
def prde_linear_constraints(a, b, G, DE):
|
175 |
+
"""
|
176 |
+
Parametric Risch Differential Equation - Generate linear constraints on the constants.
|
177 |
+
|
178 |
+
Explanation
|
179 |
+
===========
|
180 |
+
|
181 |
+
Given a derivation D on k[t], a, b, in k[t] with gcd(a, b) == 1, and
|
182 |
+
G = [g1, ..., gm] in k(t)^m, return Q = [q1, ..., qm] in k[t]^m and a
|
183 |
+
matrix M with entries in k(t) such that for any solution c1, ..., cm in
|
184 |
+
Const(k) and p in k[t] of a*Dp + b*p == Sum(ci*gi, (i, 1, m)),
|
185 |
+
(c1, ..., cm) is a solution of Mx == 0, and p and the ci satisfy
|
186 |
+
a*Dp + b*p == Sum(ci*qi, (i, 1, m)).
|
187 |
+
|
188 |
+
Because M has entries in k(t), and because Matrix does not play well with
|
189 |
+
Poly, M will be a Matrix of Basic expressions.
|
190 |
+
"""
|
191 |
+
m = len(G)
|
192 |
+
|
193 |
+
Gns, Gds = list(zip(*G))
|
194 |
+
d = reduce(lambda i, j: i.lcm(j), Gds)
|
195 |
+
d = Poly(d, field=True)
|
196 |
+
Q = [(ga*(d).quo(gd)).div(d) for ga, gd in G]
|
197 |
+
|
198 |
+
if not all(ri.is_zero for _, ri in Q):
|
199 |
+
N = max(ri.degree(DE.t) for _, ri in Q)
|
200 |
+
M = Matrix(N + 1, m, lambda i, j: Q[j][1].nth(i), DE.t)
|
201 |
+
else:
|
202 |
+
M = Matrix(0, m, [], DE.t) # No constraints, return the empty matrix.
|
203 |
+
|
204 |
+
qs, _ = list(zip(*Q))
|
205 |
+
return (qs, M)
|
206 |
+
|
207 |
+
def poly_linear_constraints(p, d):
|
208 |
+
"""
|
209 |
+
Given p = [p1, ..., pm] in k[t]^m and d in k[t], return
|
210 |
+
q = [q1, ..., qm] in k[t]^m and a matrix M with entries in k such
|
211 |
+
that Sum(ci*pi, (i, 1, m)), for c1, ..., cm in k, is divisible
|
212 |
+
by d if and only if (c1, ..., cm) is a solution of Mx = 0, in
|
213 |
+
which case the quotient is Sum(ci*qi, (i, 1, m)).
|
214 |
+
"""
|
215 |
+
m = len(p)
|
216 |
+
q, r = zip(*[pi.div(d) for pi in p])
|
217 |
+
|
218 |
+
if not all(ri.is_zero for ri in r):
|
219 |
+
n = max(ri.degree() for ri in r)
|
220 |
+
M = Matrix(n + 1, m, lambda i, j: r[j].nth(i), d.gens)
|
221 |
+
else:
|
222 |
+
M = Matrix(0, m, [], d.gens) # No constraints.
|
223 |
+
|
224 |
+
return q, M
|
225 |
+
|
226 |
+
def constant_system(A, u, DE):
|
227 |
+
"""
|
228 |
+
Generate a system for the constant solutions.
|
229 |
+
|
230 |
+
Explanation
|
231 |
+
===========
|
232 |
+
|
233 |
+
Given a differential field (K, D) with constant field C = Const(K), a Matrix
|
234 |
+
A, and a vector (Matrix) u with coefficients in K, returns the tuple
|
235 |
+
(B, v, s), where B is a Matrix with coefficients in C and v is a vector
|
236 |
+
(Matrix) such that either v has coefficients in C, in which case s is True
|
237 |
+
and the solutions in C of Ax == u are exactly all the solutions of Bx == v,
|
238 |
+
or v has a non-constant coefficient, in which case s is False Ax == u has no
|
239 |
+
constant solution.
|
240 |
+
|
241 |
+
This algorithm is used both in solving parametric problems and in
|
242 |
+
determining if an element a of K is a derivative of an element of K or the
|
243 |
+
logarithmic derivative of a K-radical using the structure theorem approach.
|
244 |
+
|
245 |
+
Because Poly does not play well with Matrix yet, this algorithm assumes that
|
246 |
+
all matrix entries are Basic expressions.
|
247 |
+
"""
|
248 |
+
if not A:
|
249 |
+
return A, u
|
250 |
+
Au = A.row_join(u)
|
251 |
+
Au, _ = Au.rref()
|
252 |
+
# Warning: This will NOT return correct results if cancel() cannot reduce
|
253 |
+
# an identically zero expression to 0. The danger is that we might
|
254 |
+
# incorrectly prove that an integral is nonelementary (such as
|
255 |
+
# risch_integrate(exp((sin(x)**2 + cos(x)**2 - 1)*x**2), x).
|
256 |
+
# But this is a limitation in computer algebra in general, and implicit
|
257 |
+
# in the correctness of the Risch Algorithm is the computability of the
|
258 |
+
# constant field (actually, this same correctness problem exists in any
|
259 |
+
# algorithm that uses rref()).
|
260 |
+
#
|
261 |
+
# We therefore limit ourselves to constant fields that are computable
|
262 |
+
# via the cancel() function, in order to prevent a speed bottleneck from
|
263 |
+
# calling some more complex simplification function (rational function
|
264 |
+
# coefficients will fall into this class). Furthermore, (I believe) this
|
265 |
+
# problem will only crop up if the integral explicitly contains an
|
266 |
+
# expression in the constant field that is identically zero, but cannot
|
267 |
+
# be reduced to such by cancel(). Therefore, a careful user can avoid this
|
268 |
+
# problem entirely by being careful with the sorts of expressions that
|
269 |
+
# appear in his integrand in the variables other than the integration
|
270 |
+
# variable (the structure theorems should be able to completely decide these
|
271 |
+
# problems in the integration variable).
|
272 |
+
|
273 |
+
A, u = Au[:, :-1], Au[:, -1]
|
274 |
+
|
275 |
+
D = lambda x: derivation(x, DE, basic=True)
|
276 |
+
|
277 |
+
for j, i in itertools.product(range(A.cols), range(A.rows)):
|
278 |
+
if A[i, j].expr.has(*DE.T):
|
279 |
+
# This assumes that const(F(t0, ..., tn) == const(K) == F
|
280 |
+
Ri = A[i, :]
|
281 |
+
# Rm+1; m = A.rows
|
282 |
+
DAij = D(A[i, j])
|
283 |
+
Rm1 = Ri.applyfunc(lambda x: D(x) / DAij)
|
284 |
+
um1 = D(u[i]) / DAij
|
285 |
+
|
286 |
+
Aj = A[:, j]
|
287 |
+
A = A - Aj * Rm1
|
288 |
+
u = u - Aj * um1
|
289 |
+
|
290 |
+
A = A.col_join(Rm1)
|
291 |
+
u = u.col_join(Matrix([um1], u.gens))
|
292 |
+
|
293 |
+
return (A, u)
|
294 |
+
|
295 |
+
|
296 |
+
def prde_spde(a, b, Q, n, DE):
|
297 |
+
"""
|
298 |
+
Special Polynomial Differential Equation algorithm: Parametric Version.
|
299 |
+
|
300 |
+
Explanation
|
301 |
+
===========
|
302 |
+
|
303 |
+
Given a derivation D on k[t], an integer n, and a, b, q1, ..., qm in k[t]
|
304 |
+
with deg(a) > 0 and gcd(a, b) == 1, return (A, B, Q, R, n1), with
|
305 |
+
Qq = [q1, ..., qm] and R = [r1, ..., rm], such that for any solution
|
306 |
+
c1, ..., cm in Const(k) and q in k[t] of degree at most n of
|
307 |
+
a*Dq + b*q == Sum(ci*gi, (i, 1, m)), p = (q - Sum(ci*ri, (i, 1, m)))/a has
|
308 |
+
degree at most n1 and satisfies A*Dp + B*p == Sum(ci*qi, (i, 1, m))
|
309 |
+
"""
|
310 |
+
R, Z = list(zip(*[gcdex_diophantine(b, a, qi) for qi in Q]))
|
311 |
+
|
312 |
+
A = a
|
313 |
+
B = b + derivation(a, DE)
|
314 |
+
Qq = [zi - derivation(ri, DE) for ri, zi in zip(R, Z)]
|
315 |
+
R = list(R)
|
316 |
+
n1 = n - a.degree(DE.t)
|
317 |
+
|
318 |
+
return (A, B, Qq, R, n1)
|
319 |
+
|
320 |
+
|
321 |
+
def prde_no_cancel_b_large(b, Q, n, DE):
|
322 |
+
"""
|
323 |
+
Parametric Poly Risch Differential Equation - No cancellation: deg(b) large enough.
|
324 |
+
|
325 |
+
Explanation
|
326 |
+
===========
|
327 |
+
|
328 |
+
Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with
|
329 |
+
b != 0 and either D == d/dt or deg(b) > max(0, deg(D) - 1), returns
|
330 |
+
h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that
|
331 |
+
if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and
|
332 |
+
Dq + b*q == Sum(ci*qi, (i, 1, m)), then q = Sum(dj*hj, (j, 1, r)), where
|
333 |
+
d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0.
|
334 |
+
"""
|
335 |
+
db = b.degree(DE.t)
|
336 |
+
m = len(Q)
|
337 |
+
H = [Poly(0, DE.t)]*m
|
338 |
+
|
339 |
+
for N, i in itertools.product(range(n, -1, -1), range(m)): # [n, ..., 0]
|
340 |
+
si = Q[i].nth(N + db)/b.LC()
|
341 |
+
sitn = Poly(si*DE.t**N, DE.t)
|
342 |
+
H[i] = H[i] + sitn
|
343 |
+
Q[i] = Q[i] - derivation(sitn, DE) - b*sitn
|
344 |
+
|
345 |
+
if all(qi.is_zero for qi in Q):
|
346 |
+
dc = -1
|
347 |
+
else:
|
348 |
+
dc = max([qi.degree(DE.t) for qi in Q])
|
349 |
+
M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t)
|
350 |
+
A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE)
|
351 |
+
c = eye(m, DE.t)
|
352 |
+
A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c))
|
353 |
+
|
354 |
+
return (H, A)
|
355 |
+
|
356 |
+
|
357 |
+
def prde_no_cancel_b_small(b, Q, n, DE):
|
358 |
+
"""
|
359 |
+
Parametric Poly Risch Differential Equation - No cancellation: deg(b) small enough.
|
360 |
+
|
361 |
+
Explanation
|
362 |
+
===========
|
363 |
+
|
364 |
+
Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with
|
365 |
+
deg(b) < deg(D) - 1 and either D == d/dt or deg(D) >= 2, returns
|
366 |
+
h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that
|
367 |
+
if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and
|
368 |
+
Dq + b*q == Sum(ci*qi, (i, 1, m)) then q = Sum(dj*hj, (j, 1, r)) where
|
369 |
+
d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0.
|
370 |
+
"""
|
371 |
+
m = len(Q)
|
372 |
+
H = [Poly(0, DE.t)]*m
|
373 |
+
|
374 |
+
for N, i in itertools.product(range(n, 0, -1), range(m)): # [n, ..., 1]
|
375 |
+
si = Q[i].nth(N + DE.d.degree(DE.t) - 1)/(N*DE.d.LC())
|
376 |
+
sitn = Poly(si*DE.t**N, DE.t)
|
377 |
+
H[i] = H[i] + sitn
|
378 |
+
Q[i] = Q[i] - derivation(sitn, DE) - b*sitn
|
379 |
+
|
380 |
+
if b.degree(DE.t) > 0:
|
381 |
+
for i in range(m):
|
382 |
+
si = Poly(Q[i].nth(b.degree(DE.t))/b.LC(), DE.t)
|
383 |
+
H[i] = H[i] + si
|
384 |
+
Q[i] = Q[i] - derivation(si, DE) - b*si
|
385 |
+
if all(qi.is_zero for qi in Q):
|
386 |
+
dc = -1
|
387 |
+
else:
|
388 |
+
dc = max([qi.degree(DE.t) for qi in Q])
|
389 |
+
M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t)
|
390 |
+
A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE)
|
391 |
+
c = eye(m, DE.t)
|
392 |
+
A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c))
|
393 |
+
return (H, A)
|
394 |
+
|
395 |
+
# else: b is in k, deg(qi) < deg(Dt)
|
396 |
+
|
397 |
+
t = DE.t
|
398 |
+
if DE.case != 'base':
|
399 |
+
with DecrementLevel(DE):
|
400 |
+
t0 = DE.t # k = k0(t0)
|
401 |
+
ba, bd = frac_in(b, t0, field=True)
|
402 |
+
Q0 = [frac_in(qi.TC(), t0, field=True) for qi in Q]
|
403 |
+
f, B = param_rischDE(ba, bd, Q0, DE)
|
404 |
+
|
405 |
+
# f = [f1, ..., fr] in k^r and B is a matrix with
|
406 |
+
# m + r columns and entries in Const(k) = Const(k0)
|
407 |
+
# such that Dy0 + b*y0 = Sum(ci*qi, (i, 1, m)) has
|
408 |
+
# a solution y0 in k with c1, ..., cm in Const(k)
|
409 |
+
# if and only y0 = Sum(dj*fj, (j, 1, r)) where
|
410 |
+
# d1, ..., dr ar in Const(k) and
|
411 |
+
# B*Matrix([c1, ..., cm, d1, ..., dr]) == 0.
|
412 |
+
|
413 |
+
# Transform fractions (fa, fd) in f into constant
|
414 |
+
# polynomials fa/fd in k[t].
|
415 |
+
# (Is there a better way?)
|
416 |
+
f = [Poly(fa.as_expr()/fd.as_expr(), t, field=True)
|
417 |
+
for fa, fd in f]
|
418 |
+
B = Matrix.from_Matrix(B.to_Matrix(), t)
|
419 |
+
else:
|
420 |
+
# Base case. Dy == 0 for all y in k and b == 0.
|
421 |
+
# Dy + b*y = Sum(ci*qi) is solvable if and only if
|
422 |
+
# Sum(ci*qi) == 0 in which case the solutions are
|
423 |
+
# y = d1*f1 for f1 = 1 and any d1 in Const(k) = k.
|
424 |
+
|
425 |
+
f = [Poly(1, t, field=True)] # r = 1
|
426 |
+
B = Matrix([[qi.TC() for qi in Q] + [S.Zero]], DE.t)
|
427 |
+
# The condition for solvability is
|
428 |
+
# B*Matrix([c1, ..., cm, d1]) == 0
|
429 |
+
# There are no constraints on d1.
|
430 |
+
|
431 |
+
# Coefficients of t^j (j > 0) in Sum(ci*qi) must be zero.
|
432 |
+
d = max([qi.degree(DE.t) for qi in Q])
|
433 |
+
if d > 0:
|
434 |
+
M = Matrix(d, m, lambda i, j: Q[j].nth(i + 1), DE.t)
|
435 |
+
A, _ = constant_system(M, zeros(d, 1, DE.t), DE)
|
436 |
+
else:
|
437 |
+
# No constraints on the hj.
|
438 |
+
A = Matrix(0, m, [], DE.t)
|
439 |
+
|
440 |
+
# Solutions of the original equation are
|
441 |
+
# y = Sum(dj*fj, (j, 1, r) + Sum(ei*hi, (i, 1, m)),
|
442 |
+
# where ei == ci (i = 1, ..., m), when
|
443 |
+
# A*Matrix([c1, ..., cm]) == 0 and
|
444 |
+
# B*Matrix([c1, ..., cm, d1, ..., dr]) == 0
|
445 |
+
|
446 |
+
# Build combined constraint matrix with m + r + m columns.
|
447 |
+
|
448 |
+
r = len(f)
|
449 |
+
I = eye(m, DE.t)
|
450 |
+
A = A.row_join(zeros(A.rows, r + m, DE.t))
|
451 |
+
B = B.row_join(zeros(B.rows, m, DE.t))
|
452 |
+
C = I.row_join(zeros(m, r, DE.t)).row_join(-I)
|
453 |
+
|
454 |
+
return f + H, A.col_join(B).col_join(C)
|
455 |
+
|
456 |
+
|
457 |
+
def prde_cancel_liouvillian(b, Q, n, DE):
|
458 |
+
"""
|
459 |
+
Pg, 237.
|
460 |
+
"""
|
461 |
+
H = []
|
462 |
+
|
463 |
+
# Why use DecrementLevel? Below line answers that:
|
464 |
+
# Assuming that we can solve such problems over 'k' (not k[t])
|
465 |
+
if DE.case == 'primitive':
|
466 |
+
with DecrementLevel(DE):
|
467 |
+
ba, bd = frac_in(b, DE.t, field=True)
|
468 |
+
|
469 |
+
for i in range(n, -1, -1):
|
470 |
+
if DE.case == 'exp': # this re-checking can be avoided
|
471 |
+
with DecrementLevel(DE):
|
472 |
+
ba, bd = frac_in(b + (i*(derivation(DE.t, DE)/DE.t)).as_poly(b.gens),
|
473 |
+
DE.t, field=True)
|
474 |
+
with DecrementLevel(DE):
|
475 |
+
Qy = [frac_in(q.nth(i), DE.t, field=True) for q in Q]
|
476 |
+
fi, Ai = param_rischDE(ba, bd, Qy, DE)
|
477 |
+
fi = [Poly(fa.as_expr()/fd.as_expr(), DE.t, field=True)
|
478 |
+
for fa, fd in fi]
|
479 |
+
Ai = Ai.set_gens(DE.t)
|
480 |
+
|
481 |
+
ri = len(fi)
|
482 |
+
|
483 |
+
if i == n:
|
484 |
+
M = Ai
|
485 |
+
else:
|
486 |
+
M = Ai.col_join(M.row_join(zeros(M.rows, ri, DE.t)))
|
487 |
+
|
488 |
+
Fi, hi = [None]*ri, [None]*ri
|
489 |
+
|
490 |
+
# from eq. on top of p.238 (unnumbered)
|
491 |
+
for j in range(ri):
|
492 |
+
hji = fi[j] * (DE.t**i).as_poly(fi[j].gens)
|
493 |
+
hi[j] = hji
|
494 |
+
# building up Sum(djn*(D(fjn*t^n) - b*fjnt^n))
|
495 |
+
Fi[j] = -(derivation(hji, DE) - b*hji)
|
496 |
+
|
497 |
+
H += hi
|
498 |
+
# in the next loop instead of Q it has
|
499 |
+
# to be Q + Fi taking its place
|
500 |
+
Q = Q + Fi
|
501 |
+
|
502 |
+
return (H, M)
|
503 |
+
|
504 |
+
|
505 |
+
def param_poly_rischDE(a, b, q, n, DE):
|
506 |
+
"""Polynomial solutions of a parametric Risch differential equation.
|
507 |
+
|
508 |
+
Explanation
|
509 |
+
===========
|
510 |
+
|
511 |
+
Given a derivation D in k[t], a, b in k[t] relatively prime, and q
|
512 |
+
= [q1, ..., qm] in k[t]^m, return h = [h1, ..., hr] in k[t]^r and
|
513 |
+
a matrix A with m + r columns and entries in Const(k) such that
|
514 |
+
a*Dp + b*p = Sum(ci*qi, (i, 1, m)) has a solution p of degree <= n
|
515 |
+
in k[t] with c1, ..., cm in Const(k) if and only if p = Sum(dj*hj,
|
516 |
+
(j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm,
|
517 |
+
d1, ..., dr) is a solution of Ax == 0.
|
518 |
+
"""
|
519 |
+
m = len(q)
|
520 |
+
if n < 0:
|
521 |
+
# Only the trivial zero solution is possible.
|
522 |
+
# Find relations between the qi.
|
523 |
+
if all(qi.is_zero for qi in q):
|
524 |
+
return [], zeros(1, m, DE.t) # No constraints.
|
525 |
+
|
526 |
+
N = max([qi.degree(DE.t) for qi in q])
|
527 |
+
M = Matrix(N + 1, m, lambda i, j: q[j].nth(i), DE.t)
|
528 |
+
A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
|
529 |
+
|
530 |
+
return [], A
|
531 |
+
|
532 |
+
if a.is_ground:
|
533 |
+
# Normalization: a = 1.
|
534 |
+
a = a.LC()
|
535 |
+
b, q = b.quo_ground(a), [qi.quo_ground(a) for qi in q]
|
536 |
+
|
537 |
+
if not b.is_zero and (DE.case == 'base' or
|
538 |
+
b.degree() > max(0, DE.d.degree() - 1)):
|
539 |
+
return prde_no_cancel_b_large(b, q, n, DE)
|
540 |
+
|
541 |
+
elif ((b.is_zero or b.degree() < DE.d.degree() - 1)
|
542 |
+
and (DE.case == 'base' or DE.d.degree() >= 2)):
|
543 |
+
return prde_no_cancel_b_small(b, q, n, DE)
|
544 |
+
|
545 |
+
elif (DE.d.degree() >= 2 and
|
546 |
+
b.degree() == DE.d.degree() - 1 and
|
547 |
+
n > -b.as_poly().LC()/DE.d.as_poly().LC()):
|
548 |
+
raise NotImplementedError("prde_no_cancel_b_equal() is "
|
549 |
+
"not yet implemented.")
|
550 |
+
|
551 |
+
else:
|
552 |
+
# Liouvillian cases
|
553 |
+
if DE.case in ('primitive', 'exp'):
|
554 |
+
return prde_cancel_liouvillian(b, q, n, DE)
|
555 |
+
else:
|
556 |
+
raise NotImplementedError("non-linear and hypertangent "
|
557 |
+
"cases have not yet been implemented")
|
558 |
+
|
559 |
+
# else: deg(a) > 0
|
560 |
+
|
561 |
+
# Iterate SPDE as long as possible cumulating coefficient
|
562 |
+
# and terms for the recovery of original solutions.
|
563 |
+
alpha, beta = a.one, [a.zero]*m
|
564 |
+
while n >= 0: # and a, b relatively prime
|
565 |
+
a, b, q, r, n = prde_spde(a, b, q, n, DE)
|
566 |
+
beta = [betai + alpha*ri for betai, ri in zip(beta, r)]
|
567 |
+
alpha *= a
|
568 |
+
# Solutions p of a*Dp + b*p = Sum(ci*qi) correspond to
|
569 |
+
# solutions alpha*p + Sum(ci*betai) of the initial equation.
|
570 |
+
d = a.gcd(b)
|
571 |
+
if not d.is_ground:
|
572 |
+
break
|
573 |
+
|
574 |
+
# a*Dp + b*p = Sum(ci*qi) may have a polynomial solution
|
575 |
+
# only if the sum is divisible by d.
|
576 |
+
|
577 |
+
qq, M = poly_linear_constraints(q, d)
|
578 |
+
# qq = [qq1, ..., qqm] where qqi = qi.quo(d).
|
579 |
+
# M is a matrix with m columns an entries in k.
|
580 |
+
# Sum(fi*qi, (i, 1, m)), where f1, ..., fm are elements of k, is
|
581 |
+
# divisible by d if and only if M*Matrix([f1, ..., fm]) == 0,
|
582 |
+
# in which case the quotient is Sum(fi*qqi).
|
583 |
+
|
584 |
+
A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
|
585 |
+
# A is a matrix with m columns and entries in Const(k).
|
586 |
+
# Sum(ci*qqi) is Sum(ci*qi).quo(d), and the remainder is zero
|
587 |
+
# for c1, ..., cm in Const(k) if and only if
|
588 |
+
# A*Matrix([c1, ...,cm]) == 0.
|
589 |
+
|
590 |
+
V = A.nullspace()
|
591 |
+
# V = [v1, ..., vu] where each vj is a column matrix with
|
592 |
+
# entries aj1, ..., ajm in Const(k).
|
593 |
+
# Sum(aji*qi) is divisible by d with exact quotient Sum(aji*qqi).
|
594 |
+
# Sum(ci*qi) is divisible by d if and only if ci = Sum(dj*aji)
|
595 |
+
# (i = 1, ..., m) for some d1, ..., du in Const(k).
|
596 |
+
# In that case, solutions of
|
597 |
+
# a*Dp + b*p = Sum(ci*qi) = Sum(dj*Sum(aji*qi))
|
598 |
+
# are the same as those of
|
599 |
+
# (a/d)*Dp + (b/d)*p = Sum(dj*rj)
|
600 |
+
# where rj = Sum(aji*qqi).
|
601 |
+
|
602 |
+
if not V: # No non-trivial solution.
|
603 |
+
return [], eye(m, DE.t) # Could return A, but this has
|
604 |
+
# the minimum number of rows.
|
605 |
+
|
606 |
+
Mqq = Matrix([qq]) # A single row.
|
607 |
+
r = [(Mqq*vj)[0] for vj in V] # [r1, ..., ru]
|
608 |
+
|
609 |
+
# Solutions of (a/d)*Dp + (b/d)*p = Sum(dj*rj) correspond to
|
610 |
+
# solutions alpha*p + Sum(Sum(dj*aji)*betai) of the initial
|
611 |
+
# equation. These are equal to alpha*p + Sum(dj*fj) where
|
612 |
+
# fj = Sum(aji*betai).
|
613 |
+
Mbeta = Matrix([beta])
|
614 |
+
f = [(Mbeta*vj)[0] for vj in V] # [f1, ..., fu]
|
615 |
+
|
616 |
+
#
|
617 |
+
# Solve the reduced equation recursively.
|
618 |
+
#
|
619 |
+
g, B = param_poly_rischDE(a.quo(d), b.quo(d), r, n, DE)
|
620 |
+
|
621 |
+
# g = [g1, ..., gv] in k[t]^v and and B is a matrix with u + v
|
622 |
+
# columns and entries in Const(k) such that
|
623 |
+
# (a/d)*Dp + (b/d)*p = Sum(dj*rj) has a solution p of degree <= n
|
624 |
+
# in k[t] if and only if p = Sum(ek*gk) where e1, ..., ev are in
|
625 |
+
# Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0.
|
626 |
+
# The solutions of the original equation are then
|
627 |
+
# Sum(dj*fj, (j, 1, u)) + alpha*Sum(ek*gk, (k, 1, v)).
|
628 |
+
|
629 |
+
# Collect solution components.
|
630 |
+
h = f + [alpha*gk for gk in g]
|
631 |
+
|
632 |
+
# Build combined relation matrix.
|
633 |
+
A = -eye(m, DE.t)
|
634 |
+
for vj in V:
|
635 |
+
A = A.row_join(vj)
|
636 |
+
A = A.row_join(zeros(m, len(g), DE.t))
|
637 |
+
A = A.col_join(zeros(B.rows, m, DE.t).row_join(B))
|
638 |
+
|
639 |
+
return h, A
|
640 |
+
|
641 |
+
|
642 |
+
def param_rischDE(fa, fd, G, DE):
|
643 |
+
"""
|
644 |
+
Solve a Parametric Risch Differential Equation: Dy + f*y == Sum(ci*Gi, (i, 1, m)).
|
645 |
+
|
646 |
+
Explanation
|
647 |
+
===========
|
648 |
+
|
649 |
+
Given a derivation D in k(t), f in k(t), and G
|
650 |
+
= [G1, ..., Gm] in k(t)^m, return h = [h1, ..., hr] in k(t)^r and
|
651 |
+
a matrix A with m + r columns and entries in Const(k) such that
|
652 |
+
Dy + f*y = Sum(ci*Gi, (i, 1, m)) has a solution y
|
653 |
+
in k(t) with c1, ..., cm in Const(k) if and only if y = Sum(dj*hj,
|
654 |
+
(j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm,
|
655 |
+
d1, ..., dr) is a solution of Ax == 0.
|
656 |
+
|
657 |
+
Elements of k(t) are tuples (a, d) with a and d in k[t].
|
658 |
+
"""
|
659 |
+
m = len(G)
|
660 |
+
q, (fa, fd) = weak_normalizer(fa, fd, DE)
|
661 |
+
# Solutions of the weakly normalized equation Dz + f*z = q*Sum(ci*Gi)
|
662 |
+
# correspond to solutions y = z/q of the original equation.
|
663 |
+
gamma = q
|
664 |
+
G = [(q*ga).cancel(gd, include=True) for ga, gd in G]
|
665 |
+
|
666 |
+
a, (ba, bd), G, hn = prde_normal_denom(fa, fd, G, DE)
|
667 |
+
# Solutions q in k<t> of a*Dq + b*q = Sum(ci*Gi) correspond
|
668 |
+
# to solutions z = q/hn of the weakly normalized equation.
|
669 |
+
gamma *= hn
|
670 |
+
|
671 |
+
A, B, G, hs = prde_special_denom(a, ba, bd, G, DE)
|
672 |
+
# Solutions p in k[t] of A*Dp + B*p = Sum(ci*Gi) correspond
|
673 |
+
# to solutions q = p/hs of the previous equation.
|
674 |
+
gamma *= hs
|
675 |
+
|
676 |
+
g = A.gcd(B)
|
677 |
+
a, b, g = A.quo(g), B.quo(g), [gia.cancel(gid*g, include=True) for
|
678 |
+
gia, gid in G]
|
679 |
+
|
680 |
+
# a*Dp + b*p = Sum(ci*gi) may have a polynomial solution
|
681 |
+
# only if the sum is in k[t].
|
682 |
+
|
683 |
+
q, M = prde_linear_constraints(a, b, g, DE)
|
684 |
+
|
685 |
+
# q = [q1, ..., qm] where qi in k[t] is the polynomial component
|
686 |
+
# of the partial fraction expansion of gi.
|
687 |
+
# M is a matrix with m columns and entries in k.
|
688 |
+
# Sum(fi*gi, (i, 1, m)), where f1, ..., fm are elements of k,
|
689 |
+
# is a polynomial if and only if M*Matrix([f1, ..., fm]) == 0,
|
690 |
+
# in which case the sum is equal to Sum(fi*qi).
|
691 |
+
|
692 |
+
M, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE)
|
693 |
+
# M is a matrix with m columns and entries in Const(k).
|
694 |
+
# Sum(ci*gi) is in k[t] for c1, ..., cm in Const(k)
|
695 |
+
# if and only if M*Matrix([c1, ..., cm]) == 0,
|
696 |
+
# in which case the sum is Sum(ci*qi).
|
697 |
+
|
698 |
+
## Reduce number of constants at this point
|
699 |
+
|
700 |
+
V = M.nullspace()
|
701 |
+
# V = [v1, ..., vu] where each vj is a column matrix with
|
702 |
+
# entries aj1, ..., ajm in Const(k).
|
703 |
+
# Sum(aji*gi) is in k[t] and equal to Sum(aji*qi) (j = 1, ..., u).
|
704 |
+
# Sum(ci*gi) is in k[t] if and only is ci = Sum(dj*aji)
|
705 |
+
# (i = 1, ..., m) for some d1, ..., du in Const(k).
|
706 |
+
# In that case,
|
707 |
+
# Sum(ci*gi) = Sum(ci*qi) = Sum(dj*Sum(aji*qi)) = Sum(dj*rj)
|
708 |
+
# where rj = Sum(aji*qi) (j = 1, ..., u) in k[t].
|
709 |
+
|
710 |
+
if not V: # No non-trivial solution
|
711 |
+
return [], eye(m, DE.t)
|
712 |
+
|
713 |
+
Mq = Matrix([q]) # A single row.
|
714 |
+
r = [(Mq*vj)[0] for vj in V] # [r1, ..., ru]
|
715 |
+
|
716 |
+
# Solutions of a*Dp + b*p = Sum(dj*rj) correspond to solutions
|
717 |
+
# y = p/gamma of the initial equation with ci = Sum(dj*aji).
|
718 |
+
|
719 |
+
try:
|
720 |
+
# We try n=5. At least for prde_spde, it will always
|
721 |
+
# terminate no matter what n is.
|
722 |
+
n = bound_degree(a, b, r, DE, parametric=True)
|
723 |
+
except NotImplementedError:
|
724 |
+
# A temporary bound is set. Eventually, it will be removed.
|
725 |
+
# the currently added test case takes large time
|
726 |
+
# even with n=5, and much longer with large n's.
|
727 |
+
n = 5
|
728 |
+
|
729 |
+
h, B = param_poly_rischDE(a, b, r, n, DE)
|
730 |
+
|
731 |
+
# h = [h1, ..., hv] in k[t]^v and and B is a matrix with u + v
|
732 |
+
# columns and entries in Const(k) such that
|
733 |
+
# a*Dp + b*p = Sum(dj*rj) has a solution p of degree <= n
|
734 |
+
# in k[t] if and only if p = Sum(ek*hk) where e1, ..., ev are in
|
735 |
+
# Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0.
|
736 |
+
# The solutions of the original equation for ci = Sum(dj*aji)
|
737 |
+
# (i = 1, ..., m) are then y = Sum(ek*hk, (k, 1, v))/gamma.
|
738 |
+
|
739 |
+
## Build combined relation matrix with m + u + v columns.
|
740 |
+
|
741 |
+
A = -eye(m, DE.t)
|
742 |
+
for vj in V:
|
743 |
+
A = A.row_join(vj)
|
744 |
+
A = A.row_join(zeros(m, len(h), DE.t))
|
745 |
+
A = A.col_join(zeros(B.rows, m, DE.t).row_join(B))
|
746 |
+
|
747 |
+
## Eliminate d1, ..., du.
|
748 |
+
|
749 |
+
W = A.nullspace()
|
750 |
+
|
751 |
+
# W = [w1, ..., wt] where each wl is a column matrix with
|
752 |
+
# entries blk (k = 1, ..., m + u + v) in Const(k).
|
753 |
+
# The vectors (bl1, ..., blm) generate the space of those
|
754 |
+
# constant families (c1, ..., cm) for which a solution of
|
755 |
+
# the equation Dy + f*y == Sum(ci*Gi) exists. They generate
|
756 |
+
# the space and form a basis except possibly when Dy + f*y == 0
|
757 |
+
# is solvable in k(t}. The corresponding solutions are
|
758 |
+
# y = Sum(blk'*hk, (k, 1, v))/gamma, where k' = k + m + u.
|
759 |
+
|
760 |
+
v = len(h)
|
761 |
+
shape = (len(W), m+v)
|
762 |
+
elements = [wl[:m] + wl[-v:] for wl in W] # excise dj's.
|
763 |
+
items = [e for row in elements for e in row]
|
764 |
+
|
765 |
+
# Need to set the shape in case W is empty
|
766 |
+
M = Matrix(*shape, items, DE.t)
|
767 |
+
N = M.nullspace()
|
768 |
+
|
769 |
+
# N = [n1, ..., ns] where the ni in Const(k)^(m + v) are column
|
770 |
+
# vectors generating the space of linear relations between
|
771 |
+
# c1, ..., cm, e1, ..., ev.
|
772 |
+
|
773 |
+
C = Matrix([ni[:] for ni in N], DE.t) # rows n1, ..., ns.
|
774 |
+
|
775 |
+
return [hk.cancel(gamma, include=True) for hk in h], C
|
776 |
+
|
777 |
+
|
778 |
+
def limited_integrate_reduce(fa, fd, G, DE):
|
779 |
+
"""
|
780 |
+
Simpler version of step 1 & 2 for the limited integration problem.
|
781 |
+
|
782 |
+
Explanation
|
783 |
+
===========
|
784 |
+
|
785 |
+
Given a derivation D on k(t) and f, g1, ..., gn in k(t), return
|
786 |
+
(a, b, h, N, g, V) such that a, b, h in k[t], N is a non-negative integer,
|
787 |
+
g in k(t), V == [v1, ..., vm] in k(t)^m, and for any solution v in k(t),
|
788 |
+
c1, ..., cm in C of f == Dv + Sum(ci*wi, (i, 1, m)), p = v*h is in k<t>, and
|
789 |
+
p and the ci satisfy a*Dp + b*p == g + Sum(ci*vi, (i, 1, m)). Furthermore,
|
790 |
+
if S1irr == Sirr, then p is in k[t], and if t is nonlinear or Liouvillian
|
791 |
+
over k, then deg(p) <= N.
|
792 |
+
|
793 |
+
So that the special part is always computed, this function calls the more
|
794 |
+
general prde_special_denom() automatically if it cannot determine that
|
795 |
+
S1irr == Sirr. Furthermore, it will automatically call bound_degree() when
|
796 |
+
t is linear and non-Liouvillian, which for the transcendental case, implies
|
797 |
+
that Dt == a*t + b with for some a, b in k*.
|
798 |
+
"""
|
799 |
+
dn, ds = splitfactor(fd, DE)
|
800 |
+
E = [splitfactor(gd, DE) for _, gd in G]
|
801 |
+
En, Es = list(zip(*E))
|
802 |
+
c = reduce(lambda i, j: i.lcm(j), (dn,) + En) # lcm(dn, en1, ..., enm)
|
803 |
+
hn = c.gcd(c.diff(DE.t))
|
804 |
+
a = hn
|
805 |
+
b = -derivation(hn, DE)
|
806 |
+
N = 0
|
807 |
+
|
808 |
+
# These are the cases where we know that S1irr = Sirr, but there could be
|
809 |
+
# others, and this algorithm will need to be extended to handle them.
|
810 |
+
if DE.case in ('base', 'primitive', 'exp', 'tan'):
|
811 |
+
hs = reduce(lambda i, j: i.lcm(j), (ds,) + Es) # lcm(ds, es1, ..., esm)
|
812 |
+
a = hn*hs
|
813 |
+
b -= (hn*derivation(hs, DE)).quo(hs)
|
814 |
+
mu = min(order_at_oo(fa, fd, DE.t), min([order_at_oo(ga, gd, DE.t) for
|
815 |
+
ga, gd in G]))
|
816 |
+
# So far, all the above are also nonlinear or Liouvillian, but if this
|
817 |
+
# changes, then this will need to be updated to call bound_degree()
|
818 |
+
# as per the docstring of this function (DE.case == 'other_linear').
|
819 |
+
N = hn.degree(DE.t) + hs.degree(DE.t) + max(0, 1 - DE.d.degree(DE.t) - mu)
|
820 |
+
else:
|
821 |
+
# TODO: implement this
|
822 |
+
raise NotImplementedError
|
823 |
+
|
824 |
+
V = [(-a*hn*ga).cancel(gd, include=True) for ga, gd in G]
|
825 |
+
return (a, b, a, N, (a*hn*fa).cancel(fd, include=True), V)
|
826 |
+
|
827 |
+
|
828 |
+
def limited_integrate(fa, fd, G, DE):
|
829 |
+
"""
|
830 |
+
Solves the limited integration problem: f = Dv + Sum(ci*wi, (i, 1, n))
|
831 |
+
"""
|
832 |
+
fa, fd = fa*Poly(1/fd.LC(), DE.t), fd.monic()
|
833 |
+
# interpreting limited integration problem as a
|
834 |
+
# parametric Risch DE problem
|
835 |
+
Fa = Poly(0, DE.t)
|
836 |
+
Fd = Poly(1, DE.t)
|
837 |
+
G = [(fa, fd)] + G
|
838 |
+
h, A = param_rischDE(Fa, Fd, G, DE)
|
839 |
+
V = A.nullspace()
|
840 |
+
V = [v for v in V if v[0] != 0]
|
841 |
+
if not V:
|
842 |
+
return None
|
843 |
+
else:
|
844 |
+
# we can take any vector from V, we take V[0]
|
845 |
+
c0 = V[0][0]
|
846 |
+
# v = [-1, c1, ..., cm, d1, ..., dr]
|
847 |
+
v = V[0]/(-c0)
|
848 |
+
r = len(h)
|
849 |
+
m = len(v) - r - 1
|
850 |
+
C = list(v[1: m + 1])
|
851 |
+
y = -sum([v[m + 1 + i]*h[i][0].as_expr()/h[i][1].as_expr() \
|
852 |
+
for i in range(r)])
|
853 |
+
y_num, y_den = y.as_numer_denom()
|
854 |
+
Ya, Yd = Poly(y_num, DE.t), Poly(y_den, DE.t)
|
855 |
+
Y = Ya*Poly(1/Yd.LC(), DE.t), Yd.monic()
|
856 |
+
return Y, C
|
857 |
+
|
858 |
+
|
859 |
+
def parametric_log_deriv_heu(fa, fd, wa, wd, DE, c1=None):
|
860 |
+
"""
|
861 |
+
Parametric logarithmic derivative heuristic.
|
862 |
+
|
863 |
+
Explanation
|
864 |
+
===========
|
865 |
+
|
866 |
+
Given a derivation D on k[t], f in k(t), and a hyperexponential monomial
|
867 |
+
theta over k(t), raises either NotImplementedError, in which case the
|
868 |
+
heuristic failed, or returns None, in which case it has proven that no
|
869 |
+
solution exists, or returns a solution (n, m, v) of the equation
|
870 |
+
n*f == Dv/v + m*Dtheta/theta, with v in k(t)* and n, m in ZZ with n != 0.
|
871 |
+
|
872 |
+
If this heuristic fails, the structure theorem approach will need to be
|
873 |
+
used.
|
874 |
+
|
875 |
+
The argument w == Dtheta/theta
|
876 |
+
"""
|
877 |
+
# TODO: finish writing this and write tests
|
878 |
+
c1 = c1 or Dummy('c1')
|
879 |
+
|
880 |
+
p, a = fa.div(fd)
|
881 |
+
q, b = wa.div(wd)
|
882 |
+
|
883 |
+
B = max(0, derivation(DE.t, DE).degree(DE.t) - 1)
|
884 |
+
C = max(p.degree(DE.t), q.degree(DE.t))
|
885 |
+
|
886 |
+
if q.degree(DE.t) > B:
|
887 |
+
eqs = [p.nth(i) - c1*q.nth(i) for i in range(B + 1, C + 1)]
|
888 |
+
s = solve(eqs, c1)
|
889 |
+
if not s or not s[c1].is_Rational:
|
890 |
+
# deg(q) > B, no solution for c.
|
891 |
+
return None
|
892 |
+
|
893 |
+
M, N = s[c1].as_numer_denom()
|
894 |
+
M_poly = M.as_poly(q.gens)
|
895 |
+
N_poly = N.as_poly(q.gens)
|
896 |
+
|
897 |
+
nfmwa = N_poly*fa*wd - M_poly*wa*fd
|
898 |
+
nfmwd = fd*wd
|
899 |
+
Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE, 'auto')
|
900 |
+
if Qv is None:
|
901 |
+
# (N*f - M*w) is not the logarithmic derivative of a k(t)-radical.
|
902 |
+
return None
|
903 |
+
|
904 |
+
Q, v = Qv
|
905 |
+
|
906 |
+
if Q.is_zero or v.is_zero:
|
907 |
+
return None
|
908 |
+
|
909 |
+
return (Q*N, Q*M, v)
|
910 |
+
|
911 |
+
if p.degree(DE.t) > B:
|
912 |
+
return None
|
913 |
+
|
914 |
+
c = lcm(fd.as_poly(DE.t).LC(), wd.as_poly(DE.t).LC())
|
915 |
+
l = fd.monic().lcm(wd.monic())*Poly(c, DE.t)
|
916 |
+
ln, ls = splitfactor(l, DE)
|
917 |
+
z = ls*ln.gcd(ln.diff(DE.t))
|
918 |
+
|
919 |
+
if not z.has(DE.t):
|
920 |
+
# TODO: We treat this as 'no solution', until the structure
|
921 |
+
# theorem version of parametric_log_deriv is implemented.
|
922 |
+
return None
|
923 |
+
|
924 |
+
u1, r1 = (fa*l.quo(fd)).div(z) # (l*f).div(z)
|
925 |
+
u2, r2 = (wa*l.quo(wd)).div(z) # (l*w).div(z)
|
926 |
+
|
927 |
+
eqs = [r1.nth(i) - c1*r2.nth(i) for i in range(z.degree(DE.t))]
|
928 |
+
s = solve(eqs, c1)
|
929 |
+
if not s or not s[c1].is_Rational:
|
930 |
+
# deg(q) <= B, no solution for c.
|
931 |
+
return None
|
932 |
+
|
933 |
+
M, N = s[c1].as_numer_denom()
|
934 |
+
|
935 |
+
nfmwa = N.as_poly(DE.t)*fa*wd - M.as_poly(DE.t)*wa*fd
|
936 |
+
nfmwd = fd*wd
|
937 |
+
Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE)
|
938 |
+
if Qv is None:
|
939 |
+
# (N*f - M*w) is not the logarithmic derivative of a k(t)-radical.
|
940 |
+
return None
|
941 |
+
|
942 |
+
Q, v = Qv
|
943 |
+
|
944 |
+
if Q.is_zero or v.is_zero:
|
945 |
+
return None
|
946 |
+
|
947 |
+
return (Q*N, Q*M, v)
|
948 |
+
|
949 |
+
|
950 |
+
def parametric_log_deriv(fa, fd, wa, wd, DE):
|
951 |
+
# TODO: Write the full algorithm using the structure theorems.
|
952 |
+
# try:
|
953 |
+
A = parametric_log_deriv_heu(fa, fd, wa, wd, DE)
|
954 |
+
# except NotImplementedError:
|
955 |
+
# Heuristic failed, we have to use the full method.
|
956 |
+
# TODO: This could be implemented more efficiently.
|
957 |
+
# It isn't too worrisome, because the heuristic handles most difficult
|
958 |
+
# cases.
|
959 |
+
return A
|
960 |
+
|
961 |
+
|
962 |
+
def is_deriv_k(fa, fd, DE):
|
963 |
+
r"""
|
964 |
+
Checks if Df/f is the derivative of an element of k(t).
|
965 |
+
|
966 |
+
Explanation
|
967 |
+
===========
|
968 |
+
|
969 |
+
a in k(t) is the derivative of an element of k(t) if there exists b in k(t)
|
970 |
+
such that a = Db. Either returns (ans, u), such that Df/f == Du, or None,
|
971 |
+
which means that Df/f is not the derivative of an element of k(t). ans is
|
972 |
+
a list of tuples such that Add(*[i*j for i, j in ans]) == u. This is useful
|
973 |
+
for seeing exactly which elements of k(t) produce u.
|
974 |
+
|
975 |
+
This function uses the structure theorem approach, which says that for any
|
976 |
+
f in K, Df/f is the derivative of a element of K if and only if there are ri
|
977 |
+
in QQ such that::
|
978 |
+
|
979 |
+
--- --- Dt
|
980 |
+
\ r * Dt + \ r * i Df
|
981 |
+
/ i i / i --- = --.
|
982 |
+
--- --- t f
|
983 |
+
i in L i in E i
|
984 |
+
K/C(x) K/C(x)
|
985 |
+
|
986 |
+
|
987 |
+
Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is
|
988 |
+
transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i
|
989 |
+
in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic
|
990 |
+
monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i
|
991 |
+
is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some
|
992 |
+
a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of
|
993 |
+
hyperexponential monomials of K over C(x)). If K is an elementary extension
|
994 |
+
over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the
|
995 |
+
transcendence degree of K over C(x). Furthermore, because Const_D(K) ==
|
996 |
+
Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and
|
997 |
+
deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x)
|
998 |
+
and L_K/C(x) are disjoint.
|
999 |
+
|
1000 |
+
The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed
|
1001 |
+
recursively using this same function. Therefore, it is required to pass
|
1002 |
+
them as indices to D (or T). E_args are the arguments of the
|
1003 |
+
hyperexponentials indexed by E_K (i.e., if i is in E_K, then T[i] ==
|
1004 |
+
exp(E_args[i])). This is needed to compute the final answer u such that
|
1005 |
+
Df/f == Du.
|
1006 |
+
|
1007 |
+
log(f) will be the same as u up to a additive constant. This is because
|
1008 |
+
they will both behave the same as monomials. For example, both log(x) and
|
1009 |
+
log(2*x) == log(x) + log(2) satisfy Dt == 1/x, because log(2) is constant.
|
1010 |
+
Therefore, the term const is returned. const is such that
|
1011 |
+
log(const) + f == u. This is calculated by dividing the arguments of one
|
1012 |
+
logarithm from the other. Therefore, it is necessary to pass the arguments
|
1013 |
+
of the logarithmic terms in L_args.
|
1014 |
+
|
1015 |
+
To handle the case where we are given Df/f, not f, use is_deriv_k_in_field().
|
1016 |
+
|
1017 |
+
See also
|
1018 |
+
========
|
1019 |
+
is_log_deriv_k_t_radical_in_field, is_log_deriv_k_t_radical
|
1020 |
+
|
1021 |
+
"""
|
1022 |
+
# Compute Df/f
|
1023 |
+
dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)), fd*fa
|
1024 |
+
dfa, dfd = dfa.cancel(dfd, include=True)
|
1025 |
+
|
1026 |
+
# Our assumption here is that each monomial is recursively transcendental
|
1027 |
+
if len(DE.exts) != len(DE.D):
|
1028 |
+
if [i for i in DE.cases if i == 'tan'] or \
|
1029 |
+
({i for i in DE.cases if i == 'primitive'} -
|
1030 |
+
set(DE.indices('log'))):
|
1031 |
+
raise NotImplementedError("Real version of the structure "
|
1032 |
+
"theorems with hypertangent support is not yet implemented.")
|
1033 |
+
|
1034 |
+
# TODO: What should really be done in this case?
|
1035 |
+
raise NotImplementedError("Nonelementary extensions not supported "
|
1036 |
+
"in the structure theorems.")
|
1037 |
+
|
1038 |
+
E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')]
|
1039 |
+
L_part = [DE.D[i].as_expr() for i in DE.indices('log')]
|
1040 |
+
|
1041 |
+
# The expression dfa/dfd might not be polynomial in any of its symbols so we
|
1042 |
+
# use a Dummy as the generator for PolyMatrix.
|
1043 |
+
dum = Dummy()
|
1044 |
+
lhs = Matrix([E_part + L_part], dum)
|
1045 |
+
rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum)
|
1046 |
+
|
1047 |
+
A, u = constant_system(lhs, rhs, DE)
|
1048 |
+
|
1049 |
+
u = u.to_Matrix() # Poly to Expr
|
1050 |
+
|
1051 |
+
if not A or not all(derivation(i, DE, basic=True).is_zero for i in u):
|
1052 |
+
# If the elements of u are not all constant
|
1053 |
+
# Note: See comment in constant_system
|
1054 |
+
|
1055 |
+
# Also note: derivation(basic=True) calls cancel()
|
1056 |
+
return None
|
1057 |
+
else:
|
1058 |
+
if not all(i.is_Rational for i in u):
|
1059 |
+
raise NotImplementedError("Cannot work with non-rational "
|
1060 |
+
"coefficients in this case.")
|
1061 |
+
else:
|
1062 |
+
terms = ([DE.extargs[i] for i in DE.indices('exp')] +
|
1063 |
+
[DE.T[i] for i in DE.indices('log')])
|
1064 |
+
ans = list(zip(terms, u))
|
1065 |
+
result = Add(*[Mul(i, j) for i, j in ans])
|
1066 |
+
argterms = ([DE.T[i] for i in DE.indices('exp')] +
|
1067 |
+
[DE.extargs[i] for i in DE.indices('log')])
|
1068 |
+
l = []
|
1069 |
+
ld = []
|
1070 |
+
for i, j in zip(argterms, u):
|
1071 |
+
# We need to get around things like sqrt(x**2) != x
|
1072 |
+
# and also sqrt(x**2 + 2*x + 1) != x + 1
|
1073 |
+
# Issue 10798: i need not be a polynomial
|
1074 |
+
i, d = i.as_numer_denom()
|
1075 |
+
icoeff, iterms = sqf_list(i)
|
1076 |
+
l.append(Mul(*([Pow(icoeff, j)] + [Pow(b, e*j) for b, e in iterms])))
|
1077 |
+
dcoeff, dterms = sqf_list(d)
|
1078 |
+
ld.append(Mul(*([Pow(dcoeff, j)] + [Pow(b, e*j) for b, e in dterms])))
|
1079 |
+
const = cancel(fa.as_expr()/fd.as_expr()/Mul(*l)*Mul(*ld))
|
1080 |
+
|
1081 |
+
return (ans, result, const)
|
1082 |
+
|
1083 |
+
|
1084 |
+
def is_log_deriv_k_t_radical(fa, fd, DE, Df=True):
|
1085 |
+
r"""
|
1086 |
+
Checks if Df is the logarithmic derivative of a k(t)-radical.
|
1087 |
+
|
1088 |
+
Explanation
|
1089 |
+
===========
|
1090 |
+
|
1091 |
+
b in k(t) can be written as the logarithmic derivative of a k(t) radical if
|
1092 |
+
there exist n in ZZ and u in k(t) with n, u != 0 such that n*b == Du/u.
|
1093 |
+
Either returns (ans, u, n, const) or None, which means that Df cannot be
|
1094 |
+
written as the logarithmic derivative of a k(t)-radical. ans is a list of
|
1095 |
+
tuples such that Mul(*[i**j for i, j in ans]) == u. This is useful for
|
1096 |
+
seeing exactly what elements of k(t) produce u.
|
1097 |
+
|
1098 |
+
This function uses the structure theorem approach, which says that for any
|
1099 |
+
f in K, Df is the logarithmic derivative of a K-radical if and only if there
|
1100 |
+
are ri in QQ such that::
|
1101 |
+
|
1102 |
+
--- --- Dt
|
1103 |
+
\ r * Dt + \ r * i
|
1104 |
+
/ i i / i --- = Df.
|
1105 |
+
--- --- t
|
1106 |
+
i in L i in E i
|
1107 |
+
K/C(x) K/C(x)
|
1108 |
+
|
1109 |
+
|
1110 |
+
Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is
|
1111 |
+
transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i
|
1112 |
+
in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic
|
1113 |
+
monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i
|
1114 |
+
is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some
|
1115 |
+
a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of
|
1116 |
+
hyperexponential monomials of K over C(x)). If K is an elementary extension
|
1117 |
+
over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the
|
1118 |
+
transcendence degree of K over C(x). Furthermore, because Const_D(K) ==
|
1119 |
+
Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and
|
1120 |
+
deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x)
|
1121 |
+
and L_K/C(x) are disjoint.
|
1122 |
+
|
1123 |
+
The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed
|
1124 |
+
recursively using this same function. Therefore, it is required to pass
|
1125 |
+
them as indices to D (or T). L_args are the arguments of the logarithms
|
1126 |
+
indexed by L_K (i.e., if i is in L_K, then T[i] == log(L_args[i])). This is
|
1127 |
+
needed to compute the final answer u such that n*f == Du/u.
|
1128 |
+
|
1129 |
+
exp(f) will be the same as u up to a multiplicative constant. This is
|
1130 |
+
because they will both behave the same as monomials. For example, both
|
1131 |
+
exp(x) and exp(x + 1) == E*exp(x) satisfy Dt == t. Therefore, the term const
|
1132 |
+
is returned. const is such that exp(const)*f == u. This is calculated by
|
1133 |
+
subtracting the arguments of one exponential from the other. Therefore, it
|
1134 |
+
is necessary to pass the arguments of the exponential terms in E_args.
|
1135 |
+
|
1136 |
+
To handle the case where we are given Df, not f, use
|
1137 |
+
is_log_deriv_k_t_radical_in_field().
|
1138 |
+
|
1139 |
+
See also
|
1140 |
+
========
|
1141 |
+
|
1142 |
+
is_log_deriv_k_t_radical_in_field, is_deriv_k
|
1143 |
+
|
1144 |
+
"""
|
1145 |
+
if Df:
|
1146 |
+
dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)).cancel(fd**2,
|
1147 |
+
include=True)
|
1148 |
+
else:
|
1149 |
+
dfa, dfd = fa, fd
|
1150 |
+
|
1151 |
+
# Our assumption here is that each monomial is recursively transcendental
|
1152 |
+
if len(DE.exts) != len(DE.D):
|
1153 |
+
if [i for i in DE.cases if i == 'tan'] or \
|
1154 |
+
({i for i in DE.cases if i == 'primitive'} -
|
1155 |
+
set(DE.indices('log'))):
|
1156 |
+
raise NotImplementedError("Real version of the structure "
|
1157 |
+
"theorems with hypertangent support is not yet implemented.")
|
1158 |
+
|
1159 |
+
# TODO: What should really be done in this case?
|
1160 |
+
raise NotImplementedError("Nonelementary extensions not supported "
|
1161 |
+
"in the structure theorems.")
|
1162 |
+
|
1163 |
+
E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')]
|
1164 |
+
L_part = [DE.D[i].as_expr() for i in DE.indices('log')]
|
1165 |
+
|
1166 |
+
# The expression dfa/dfd might not be polynomial in any of its symbols so we
|
1167 |
+
# use a Dummy as the generator for PolyMatrix.
|
1168 |
+
dum = Dummy()
|
1169 |
+
lhs = Matrix([E_part + L_part], dum)
|
1170 |
+
rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum)
|
1171 |
+
|
1172 |
+
A, u = constant_system(lhs, rhs, DE)
|
1173 |
+
|
1174 |
+
u = u.to_Matrix() # Poly to Expr
|
1175 |
+
|
1176 |
+
if not A or not all(derivation(i, DE, basic=True).is_zero for i in u):
|
1177 |
+
# If the elements of u are not all constant
|
1178 |
+
# Note: See comment in constant_system
|
1179 |
+
|
1180 |
+
# Also note: derivation(basic=True) calls cancel()
|
1181 |
+
return None
|
1182 |
+
else:
|
1183 |
+
if not all(i.is_Rational for i in u):
|
1184 |
+
# TODO: But maybe we can tell if they're not rational, like
|
1185 |
+
# log(2)/log(3). Also, there should be an option to continue
|
1186 |
+
# anyway, even if the result might potentially be wrong.
|
1187 |
+
raise NotImplementedError("Cannot work with non-rational "
|
1188 |
+
"coefficients in this case.")
|
1189 |
+
else:
|
1190 |
+
n = reduce(ilcm, [i.as_numer_denom()[1] for i in u])
|
1191 |
+
u *= n
|
1192 |
+
terms = ([DE.T[i] for i in DE.indices('exp')] +
|
1193 |
+
[DE.extargs[i] for i in DE.indices('log')])
|
1194 |
+
ans = list(zip(terms, u))
|
1195 |
+
result = Mul(*[Pow(i, j) for i, j in ans])
|
1196 |
+
|
1197 |
+
# exp(f) will be the same as result up to a multiplicative
|
1198 |
+
# constant. We now find the log of that constant.
|
1199 |
+
argterms = ([DE.extargs[i] for i in DE.indices('exp')] +
|
1200 |
+
[DE.T[i] for i in DE.indices('log')])
|
1201 |
+
const = cancel(fa.as_expr()/fd.as_expr() -
|
1202 |
+
Add(*[Mul(i, j/n) for i, j in zip(argterms, u)]))
|
1203 |
+
|
1204 |
+
return (ans, result, n, const)
|
1205 |
+
|
1206 |
+
|
1207 |
+
def is_log_deriv_k_t_radical_in_field(fa, fd, DE, case='auto', z=None):
|
1208 |
+
"""
|
1209 |
+
Checks if f can be written as the logarithmic derivative of a k(t)-radical.
|
1210 |
+
|
1211 |
+
Explanation
|
1212 |
+
===========
|
1213 |
+
|
1214 |
+
It differs from is_log_deriv_k_t_radical(fa, fd, DE, Df=False)
|
1215 |
+
for any given fa, fd, DE in that it finds the solution in the
|
1216 |
+
given field not in some (possibly unspecified extension) and
|
1217 |
+
"in_field" with the function name is used to indicate that.
|
1218 |
+
|
1219 |
+
f in k(t) can be written as the logarithmic derivative of a k(t) radical if
|
1220 |
+
there exist n in ZZ and u in k(t) with n, u != 0 such that n*f == Du/u.
|
1221 |
+
Either returns (n, u) or None, which means that f cannot be written as the
|
1222 |
+
logarithmic derivative of a k(t)-radical.
|
1223 |
+
|
1224 |
+
case is one of {'primitive', 'exp', 'tan', 'auto'} for the primitive,
|
1225 |
+
hyperexponential, and hypertangent cases, respectively. If case is 'auto',
|
1226 |
+
it will attempt to determine the type of the derivation automatically.
|
1227 |
+
|
1228 |
+
See also
|
1229 |
+
========
|
1230 |
+
is_log_deriv_k_t_radical, is_deriv_k
|
1231 |
+
|
1232 |
+
"""
|
1233 |
+
fa, fd = fa.cancel(fd, include=True)
|
1234 |
+
|
1235 |
+
# f must be simple
|
1236 |
+
n, s = splitfactor(fd, DE)
|
1237 |
+
if not s.is_one:
|
1238 |
+
pass
|
1239 |
+
|
1240 |
+
z = z or Dummy('z')
|
1241 |
+
H, b = residue_reduce(fa, fd, DE, z=z)
|
1242 |
+
if not b:
|
1243 |
+
# I will have to verify, but I believe that the answer should be
|
1244 |
+
# None in this case. This should never happen for the
|
1245 |
+
# functions given when solving the parametric logarithmic
|
1246 |
+
# derivative problem when integration elementary functions (see
|
1247 |
+
# Bronstein's book, page 255), so most likely this indicates a bug.
|
1248 |
+
return None
|
1249 |
+
|
1250 |
+
roots = [(i, i.real_roots()) for i, _ in H]
|
1251 |
+
if not all(len(j) == i.degree() and all(k.is_Rational for k in j) for
|
1252 |
+
i, j in roots):
|
1253 |
+
# If f is the logarithmic derivative of a k(t)-radical, then all the
|
1254 |
+
# roots of the resultant must be rational numbers.
|
1255 |
+
return None
|
1256 |
+
|
1257 |
+
# [(a, i), ...], where i*log(a) is a term in the log-part of the integral
|
1258 |
+
# of f
|
1259 |
+
respolys, residues = list(zip(*roots)) or [[], []]
|
1260 |
+
# Note: this might be empty, but everything below should work find in that
|
1261 |
+
# case (it should be the same as if it were [[1, 1]])
|
1262 |
+
residueterms = [(H[j][1].subs(z, i), i) for j in range(len(H)) for
|
1263 |
+
i in residues[j]]
|
1264 |
+
|
1265 |
+
# TODO: finish writing this and write tests
|
1266 |
+
|
1267 |
+
p = cancel(fa.as_expr()/fd.as_expr() - residue_reduce_derivation(H, DE, z))
|
1268 |
+
|
1269 |
+
p = p.as_poly(DE.t)
|
1270 |
+
if p is None:
|
1271 |
+
# f - Dg will be in k[t] if f is the logarithmic derivative of a k(t)-radical
|
1272 |
+
return None
|
1273 |
+
|
1274 |
+
if p.degree(DE.t) >= max(1, DE.d.degree(DE.t)):
|
1275 |
+
return None
|
1276 |
+
|
1277 |
+
if case == 'auto':
|
1278 |
+
case = DE.case
|
1279 |
+
|
1280 |
+
if case == 'exp':
|
1281 |
+
wa, wd = derivation(DE.t, DE).cancel(Poly(DE.t, DE.t), include=True)
|
1282 |
+
with DecrementLevel(DE):
|
1283 |
+
pa, pd = frac_in(p, DE.t, cancel=True)
|
1284 |
+
wa, wd = frac_in((wa, wd), DE.t)
|
1285 |
+
A = parametric_log_deriv(pa, pd, wa, wd, DE)
|
1286 |
+
if A is None:
|
1287 |
+
return None
|
1288 |
+
n, e, u = A
|
1289 |
+
u *= DE.t**e
|
1290 |
+
|
1291 |
+
elif case == 'primitive':
|
1292 |
+
with DecrementLevel(DE):
|
1293 |
+
pa, pd = frac_in(p, DE.t)
|
1294 |
+
A = is_log_deriv_k_t_radical_in_field(pa, pd, DE, case='auto')
|
1295 |
+
if A is None:
|
1296 |
+
return None
|
1297 |
+
n, u = A
|
1298 |
+
|
1299 |
+
elif case == 'base':
|
1300 |
+
# TODO: we can use more efficient residue reduction from ratint()
|
1301 |
+
if not fd.is_sqf or fa.degree() >= fd.degree():
|
1302 |
+
# f is the logarithmic derivative in the base case if and only if
|
1303 |
+
# f = fa/fd, fd is square-free, deg(fa) < deg(fd), and
|
1304 |
+
# gcd(fa, fd) == 1. The last condition is handled by cancel() above.
|
1305 |
+
return None
|
1306 |
+
# Note: if residueterms = [], returns (1, 1)
|
1307 |
+
# f had better be 0 in that case.
|
1308 |
+
n = reduce(ilcm, [i.as_numer_denom()[1] for _, i in residueterms], S.One)
|
1309 |
+
u = Mul(*[Pow(i, j*n) for i, j in residueterms])
|
1310 |
+
return (n, u)
|
1311 |
+
|
1312 |
+
elif case == 'tan':
|
1313 |
+
raise NotImplementedError("The hypertangent case is "
|
1314 |
+
"not yet implemented for is_log_deriv_k_t_radical_in_field()")
|
1315 |
+
|
1316 |
+
elif case in ('other_linear', 'other_nonlinear'):
|
1317 |
+
# XXX: If these are supported by the structure theorems, change to NotImplementedError.
|
1318 |
+
raise ValueError("The %s case is not supported in this function." % case)
|
1319 |
+
|
1320 |
+
else:
|
1321 |
+
raise ValueError("case must be one of {'primitive', 'exp', 'tan', "
|
1322 |
+
"'base', 'auto'}, not %s" % case)
|
1323 |
+
|
1324 |
+
common_denom = reduce(ilcm, [i.as_numer_denom()[1] for i in [j for _, j in
|
1325 |
+
residueterms]] + [n], S.One)
|
1326 |
+
residueterms = [(i, j*common_denom) for i, j in residueterms]
|
1327 |
+
m = common_denom//n
|
1328 |
+
if common_denom != n*m: # Verify exact division
|
1329 |
+
raise ValueError("Inexact division")
|
1330 |
+
u = cancel(u**m*Mul(*[Pow(i, j) for i, j in residueterms]))
|
1331 |
+
|
1332 |
+
return (common_denom, u)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/quadrature.py
ADDED
@@ -0,0 +1,617 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import S, Dummy, pi
|
2 |
+
from sympy.functions.combinatorial.factorials import factorial
|
3 |
+
from sympy.functions.elementary.trigonometric import sin, cos
|
4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
5 |
+
from sympy.functions.special.gamma_functions import gamma
|
6 |
+
from sympy.polys.orthopolys import (legendre_poly, laguerre_poly,
|
7 |
+
hermite_poly, jacobi_poly)
|
8 |
+
from sympy.polys.rootoftools import RootOf
|
9 |
+
|
10 |
+
|
11 |
+
def gauss_legendre(n, n_digits):
|
12 |
+
r"""
|
13 |
+
Computes the Gauss-Legendre quadrature [1]_ points and weights.
|
14 |
+
|
15 |
+
Explanation
|
16 |
+
===========
|
17 |
+
|
18 |
+
The Gauss-Legendre quadrature approximates the integral:
|
19 |
+
|
20 |
+
.. math::
|
21 |
+
\int_{-1}^1 f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i)
|
22 |
+
|
23 |
+
The nodes `x_i` of an order `n` quadrature rule are the roots of `P_n`
|
24 |
+
and the weights `w_i` are given by:
|
25 |
+
|
26 |
+
.. math::
|
27 |
+
w_i = \frac{2}{\left(1-x_i^2\right) \left(P'_n(x_i)\right)^2}
|
28 |
+
|
29 |
+
Parameters
|
30 |
+
==========
|
31 |
+
|
32 |
+
n :
|
33 |
+
The order of quadrature.
|
34 |
+
n_digits :
|
35 |
+
Number of significant digits of the points and weights to return.
|
36 |
+
|
37 |
+
Returns
|
38 |
+
=======
|
39 |
+
|
40 |
+
(x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
|
41 |
+
The points `x_i` and weights `w_i` are returned as ``(x, w)``
|
42 |
+
tuple of lists.
|
43 |
+
|
44 |
+
Examples
|
45 |
+
========
|
46 |
+
|
47 |
+
>>> from sympy.integrals.quadrature import gauss_legendre
|
48 |
+
>>> x, w = gauss_legendre(3, 5)
|
49 |
+
>>> x
|
50 |
+
[-0.7746, 0, 0.7746]
|
51 |
+
>>> w
|
52 |
+
[0.55556, 0.88889, 0.55556]
|
53 |
+
>>> x, w = gauss_legendre(4, 5)
|
54 |
+
>>> x
|
55 |
+
[-0.86114, -0.33998, 0.33998, 0.86114]
|
56 |
+
>>> w
|
57 |
+
[0.34785, 0.65215, 0.65215, 0.34785]
|
58 |
+
|
59 |
+
See Also
|
60 |
+
========
|
61 |
+
|
62 |
+
gauss_laguerre, gauss_gen_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
|
63 |
+
|
64 |
+
References
|
65 |
+
==========
|
66 |
+
|
67 |
+
.. [1] https://en.wikipedia.org/wiki/Gaussian_quadrature
|
68 |
+
.. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/legendre_rule/legendre_rule.html
|
69 |
+
"""
|
70 |
+
x = Dummy("x")
|
71 |
+
p = legendre_poly(n, x, polys=True)
|
72 |
+
pd = p.diff(x)
|
73 |
+
xi = []
|
74 |
+
w = []
|
75 |
+
for r in p.real_roots():
|
76 |
+
if isinstance(r, RootOf):
|
77 |
+
r = r.eval_rational(S.One/10**(n_digits+2))
|
78 |
+
xi.append(r.n(n_digits))
|
79 |
+
w.append((2/((1-r**2) * pd.subs(x, r)**2)).n(n_digits))
|
80 |
+
return xi, w
|
81 |
+
|
82 |
+
|
83 |
+
def gauss_laguerre(n, n_digits):
|
84 |
+
r"""
|
85 |
+
Computes the Gauss-Laguerre quadrature [1]_ points and weights.
|
86 |
+
|
87 |
+
Explanation
|
88 |
+
===========
|
89 |
+
|
90 |
+
The Gauss-Laguerre quadrature approximates the integral:
|
91 |
+
|
92 |
+
.. math::
|
93 |
+
\int_0^{\infty} e^{-x} f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i)
|
94 |
+
|
95 |
+
|
96 |
+
The nodes `x_i` of an order `n` quadrature rule are the roots of `L_n`
|
97 |
+
and the weights `w_i` are given by:
|
98 |
+
|
99 |
+
.. math::
|
100 |
+
w_i = \frac{x_i}{(n+1)^2 \left(L_{n+1}(x_i)\right)^2}
|
101 |
+
|
102 |
+
Parameters
|
103 |
+
==========
|
104 |
+
|
105 |
+
n :
|
106 |
+
The order of quadrature.
|
107 |
+
n_digits :
|
108 |
+
Number of significant digits of the points and weights to return.
|
109 |
+
|
110 |
+
Returns
|
111 |
+
=======
|
112 |
+
|
113 |
+
(x, w) : The ``x`` and ``w`` are lists of points and weights as Floats.
|
114 |
+
The points `x_i` and weights `w_i` are returned as ``(x, w)``
|
115 |
+
tuple of lists.
|
116 |
+
|
117 |
+
Examples
|
118 |
+
========
|
119 |
+
|
120 |
+
>>> from sympy.integrals.quadrature import gauss_laguerre
|
121 |
+
>>> x, w = gauss_laguerre(3, 5)
|
122 |
+
>>> x
|
123 |
+
[0.41577, 2.2943, 6.2899]
|
124 |
+
>>> w
|
125 |
+
[0.71109, 0.27852, 0.010389]
|
126 |
+
>>> x, w = gauss_laguerre(6, 5)
|
127 |
+
>>> x
|
128 |
+
[0.22285, 1.1889, 2.9927, 5.7751, 9.8375, 15.983]
|
129 |
+
>>> w
|
130 |
+
[0.45896, 0.417, 0.11337, 0.010399, 0.00026102, 8.9855e-7]
|
131 |
+
|
132 |
+
See Also
|
133 |
+
========
|
134 |
+
|
135 |
+
gauss_legendre, gauss_gen_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
|
136 |
+
|
137 |
+
References
|
138 |
+
==========
|
139 |
+
|
140 |
+
.. [1] https://en.wikipedia.org/wiki/Gauss%E2%80%93Laguerre_quadrature
|
141 |
+
.. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/laguerre_rule/laguerre_rule.html
|
142 |
+
"""
|
143 |
+
x = Dummy("x")
|
144 |
+
p = laguerre_poly(n, x, polys=True)
|
145 |
+
p1 = laguerre_poly(n+1, x, polys=True)
|
146 |
+
xi = []
|
147 |
+
w = []
|
148 |
+
for r in p.real_roots():
|
149 |
+
if isinstance(r, RootOf):
|
150 |
+
r = r.eval_rational(S.One/10**(n_digits+2))
|
151 |
+
xi.append(r.n(n_digits))
|
152 |
+
w.append((r/((n+1)**2 * p1.subs(x, r)**2)).n(n_digits))
|
153 |
+
return xi, w
|
154 |
+
|
155 |
+
|
156 |
+
def gauss_hermite(n, n_digits):
|
157 |
+
r"""
|
158 |
+
Computes the Gauss-Hermite quadrature [1]_ points and weights.
|
159 |
+
|
160 |
+
Explanation
|
161 |
+
===========
|
162 |
+
|
163 |
+
The Gauss-Hermite quadrature approximates the integral:
|
164 |
+
|
165 |
+
.. math::
|
166 |
+
\int_{-\infty}^{\infty} e^{-x^2} f(x)\,dx \approx
|
167 |
+
\sum_{i=1}^n w_i f(x_i)
|
168 |
+
|
169 |
+
The nodes `x_i` of an order `n` quadrature rule are the roots of `H_n`
|
170 |
+
and the weights `w_i` are given by:
|
171 |
+
|
172 |
+
.. math::
|
173 |
+
w_i = \frac{2^{n-1} n! \sqrt{\pi}}{n^2 \left(H_{n-1}(x_i)\right)^2}
|
174 |
+
|
175 |
+
Parameters
|
176 |
+
==========
|
177 |
+
|
178 |
+
n :
|
179 |
+
The order of quadrature.
|
180 |
+
n_digits :
|
181 |
+
Number of significant digits of the points and weights to return.
|
182 |
+
|
183 |
+
Returns
|
184 |
+
=======
|
185 |
+
|
186 |
+
(x, w) : The ``x`` and ``w`` are lists of points and weights as Floats.
|
187 |
+
The points `x_i` and weights `w_i` are returned as ``(x, w)``
|
188 |
+
tuple of lists.
|
189 |
+
|
190 |
+
Examples
|
191 |
+
========
|
192 |
+
|
193 |
+
>>> from sympy.integrals.quadrature import gauss_hermite
|
194 |
+
>>> x, w = gauss_hermite(3, 5)
|
195 |
+
>>> x
|
196 |
+
[-1.2247, 0, 1.2247]
|
197 |
+
>>> w
|
198 |
+
[0.29541, 1.1816, 0.29541]
|
199 |
+
|
200 |
+
>>> x, w = gauss_hermite(6, 5)
|
201 |
+
>>> x
|
202 |
+
[-2.3506, -1.3358, -0.43608, 0.43608, 1.3358, 2.3506]
|
203 |
+
>>> w
|
204 |
+
[0.00453, 0.15707, 0.72463, 0.72463, 0.15707, 0.00453]
|
205 |
+
|
206 |
+
See Also
|
207 |
+
========
|
208 |
+
|
209 |
+
gauss_legendre, gauss_laguerre, gauss_gen_laguerre, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
|
210 |
+
|
211 |
+
References
|
212 |
+
==========
|
213 |
+
|
214 |
+
.. [1] https://en.wikipedia.org/wiki/Gauss-Hermite_Quadrature
|
215 |
+
.. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/hermite_rule/hermite_rule.html
|
216 |
+
.. [3] https://people.sc.fsu.edu/~jburkardt/cpp_src/gen_hermite_rule/gen_hermite_rule.html
|
217 |
+
"""
|
218 |
+
x = Dummy("x")
|
219 |
+
p = hermite_poly(n, x, polys=True)
|
220 |
+
p1 = hermite_poly(n-1, x, polys=True)
|
221 |
+
xi = []
|
222 |
+
w = []
|
223 |
+
for r in p.real_roots():
|
224 |
+
if isinstance(r, RootOf):
|
225 |
+
r = r.eval_rational(S.One/10**(n_digits+2))
|
226 |
+
xi.append(r.n(n_digits))
|
227 |
+
w.append(((2**(n-1) * factorial(n) * sqrt(pi)) /
|
228 |
+
(n**2 * p1.subs(x, r)**2)).n(n_digits))
|
229 |
+
return xi, w
|
230 |
+
|
231 |
+
|
232 |
+
def gauss_gen_laguerre(n, alpha, n_digits):
|
233 |
+
r"""
|
234 |
+
Computes the generalized Gauss-Laguerre quadrature [1]_ points and weights.
|
235 |
+
|
236 |
+
Explanation
|
237 |
+
===========
|
238 |
+
|
239 |
+
The generalized Gauss-Laguerre quadrature approximates the integral:
|
240 |
+
|
241 |
+
.. math::
|
242 |
+
\int_{0}^\infty x^{\alpha} e^{-x} f(x)\,dx \approx
|
243 |
+
\sum_{i=1}^n w_i f(x_i)
|
244 |
+
|
245 |
+
The nodes `x_i` of an order `n` quadrature rule are the roots of
|
246 |
+
`L^{\alpha}_n` and the weights `w_i` are given by:
|
247 |
+
|
248 |
+
.. math::
|
249 |
+
w_i = \frac{\Gamma(\alpha+n)}
|
250 |
+
{n \Gamma(n) L^{\alpha}_{n-1}(x_i) L^{\alpha+1}_{n-1}(x_i)}
|
251 |
+
|
252 |
+
Parameters
|
253 |
+
==========
|
254 |
+
|
255 |
+
n :
|
256 |
+
The order of quadrature.
|
257 |
+
|
258 |
+
alpha :
|
259 |
+
The exponent of the singularity, `\alpha > -1`.
|
260 |
+
|
261 |
+
n_digits :
|
262 |
+
Number of significant digits of the points and weights to return.
|
263 |
+
|
264 |
+
Returns
|
265 |
+
=======
|
266 |
+
|
267 |
+
(x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
|
268 |
+
The points `x_i` and weights `w_i` are returned as ``(x, w)``
|
269 |
+
tuple of lists.
|
270 |
+
|
271 |
+
Examples
|
272 |
+
========
|
273 |
+
|
274 |
+
>>> from sympy import S
|
275 |
+
>>> from sympy.integrals.quadrature import gauss_gen_laguerre
|
276 |
+
>>> x, w = gauss_gen_laguerre(3, -S.Half, 5)
|
277 |
+
>>> x
|
278 |
+
[0.19016, 1.7845, 5.5253]
|
279 |
+
>>> w
|
280 |
+
[1.4493, 0.31413, 0.00906]
|
281 |
+
|
282 |
+
>>> x, w = gauss_gen_laguerre(4, 3*S.Half, 5)
|
283 |
+
>>> x
|
284 |
+
[0.97851, 2.9904, 6.3193, 11.712]
|
285 |
+
>>> w
|
286 |
+
[0.53087, 0.67721, 0.11895, 0.0023152]
|
287 |
+
|
288 |
+
See Also
|
289 |
+
========
|
290 |
+
|
291 |
+
gauss_legendre, gauss_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
|
292 |
+
|
293 |
+
References
|
294 |
+
==========
|
295 |
+
|
296 |
+
.. [1] https://en.wikipedia.org/wiki/Gauss%E2%80%93Laguerre_quadrature
|
297 |
+
.. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/gen_laguerre_rule/gen_laguerre_rule.html
|
298 |
+
"""
|
299 |
+
x = Dummy("x")
|
300 |
+
p = laguerre_poly(n, x, alpha=alpha, polys=True)
|
301 |
+
p1 = laguerre_poly(n-1, x, alpha=alpha, polys=True)
|
302 |
+
p2 = laguerre_poly(n-1, x, alpha=alpha+1, polys=True)
|
303 |
+
xi = []
|
304 |
+
w = []
|
305 |
+
for r in p.real_roots():
|
306 |
+
if isinstance(r, RootOf):
|
307 |
+
r = r.eval_rational(S.One/10**(n_digits+2))
|
308 |
+
xi.append(r.n(n_digits))
|
309 |
+
w.append((gamma(alpha+n) /
|
310 |
+
(n*gamma(n)*p1.subs(x, r)*p2.subs(x, r))).n(n_digits))
|
311 |
+
return xi, w
|
312 |
+
|
313 |
+
|
314 |
+
def gauss_chebyshev_t(n, n_digits):
|
315 |
+
r"""
|
316 |
+
Computes the Gauss-Chebyshev quadrature [1]_ points and weights of
|
317 |
+
the first kind.
|
318 |
+
|
319 |
+
Explanation
|
320 |
+
===========
|
321 |
+
|
322 |
+
The Gauss-Chebyshev quadrature of the first kind approximates the integral:
|
323 |
+
|
324 |
+
.. math::
|
325 |
+
\int_{-1}^{1} \frac{1}{\sqrt{1-x^2}} f(x)\,dx \approx
|
326 |
+
\sum_{i=1}^n w_i f(x_i)
|
327 |
+
|
328 |
+
The nodes `x_i` of an order `n` quadrature rule are the roots of `T_n`
|
329 |
+
and the weights `w_i` are given by:
|
330 |
+
|
331 |
+
.. math::
|
332 |
+
w_i = \frac{\pi}{n}
|
333 |
+
|
334 |
+
Parameters
|
335 |
+
==========
|
336 |
+
|
337 |
+
n :
|
338 |
+
The order of quadrature.
|
339 |
+
|
340 |
+
n_digits :
|
341 |
+
Number of significant digits of the points and weights to return.
|
342 |
+
|
343 |
+
Returns
|
344 |
+
=======
|
345 |
+
|
346 |
+
(x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
|
347 |
+
The points `x_i` and weights `w_i` are returned as ``(x, w)``
|
348 |
+
tuple of lists.
|
349 |
+
|
350 |
+
Examples
|
351 |
+
========
|
352 |
+
|
353 |
+
>>> from sympy.integrals.quadrature import gauss_chebyshev_t
|
354 |
+
>>> x, w = gauss_chebyshev_t(3, 5)
|
355 |
+
>>> x
|
356 |
+
[0.86602, 0, -0.86602]
|
357 |
+
>>> w
|
358 |
+
[1.0472, 1.0472, 1.0472]
|
359 |
+
|
360 |
+
>>> x, w = gauss_chebyshev_t(6, 5)
|
361 |
+
>>> x
|
362 |
+
[0.96593, 0.70711, 0.25882, -0.25882, -0.70711, -0.96593]
|
363 |
+
>>> w
|
364 |
+
[0.5236, 0.5236, 0.5236, 0.5236, 0.5236, 0.5236]
|
365 |
+
|
366 |
+
See Also
|
367 |
+
========
|
368 |
+
|
369 |
+
gauss_legendre, gauss_laguerre, gauss_hermite, gauss_gen_laguerre, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
|
370 |
+
|
371 |
+
References
|
372 |
+
==========
|
373 |
+
|
374 |
+
.. [1] https://en.wikipedia.org/wiki/Chebyshev%E2%80%93Gauss_quadrature
|
375 |
+
.. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/chebyshev1_rule/chebyshev1_rule.html
|
376 |
+
"""
|
377 |
+
xi = []
|
378 |
+
w = []
|
379 |
+
for i in range(1, n+1):
|
380 |
+
xi.append((cos((2*i-S.One)/(2*n)*S.Pi)).n(n_digits))
|
381 |
+
w.append((S.Pi/n).n(n_digits))
|
382 |
+
return xi, w
|
383 |
+
|
384 |
+
|
385 |
+
def gauss_chebyshev_u(n, n_digits):
|
386 |
+
r"""
|
387 |
+
Computes the Gauss-Chebyshev quadrature [1]_ points and weights of
|
388 |
+
the second kind.
|
389 |
+
|
390 |
+
Explanation
|
391 |
+
===========
|
392 |
+
|
393 |
+
The Gauss-Chebyshev quadrature of the second kind approximates the
|
394 |
+
integral:
|
395 |
+
|
396 |
+
.. math::
|
397 |
+
\int_{-1}^{1} \sqrt{1-x^2} f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i)
|
398 |
+
|
399 |
+
The nodes `x_i` of an order `n` quadrature rule are the roots of `U_n`
|
400 |
+
and the weights `w_i` are given by:
|
401 |
+
|
402 |
+
.. math::
|
403 |
+
w_i = \frac{\pi}{n+1} \sin^2 \left(\frac{i}{n+1}\pi\right)
|
404 |
+
|
405 |
+
Parameters
|
406 |
+
==========
|
407 |
+
|
408 |
+
n : the order of quadrature
|
409 |
+
|
410 |
+
n_digits : number of significant digits of the points and weights to return
|
411 |
+
|
412 |
+
Returns
|
413 |
+
=======
|
414 |
+
|
415 |
+
(x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
|
416 |
+
The points `x_i` and weights `w_i` are returned as ``(x, w)``
|
417 |
+
tuple of lists.
|
418 |
+
|
419 |
+
Examples
|
420 |
+
========
|
421 |
+
|
422 |
+
>>> from sympy.integrals.quadrature import gauss_chebyshev_u
|
423 |
+
>>> x, w = gauss_chebyshev_u(3, 5)
|
424 |
+
>>> x
|
425 |
+
[0.70711, 0, -0.70711]
|
426 |
+
>>> w
|
427 |
+
[0.3927, 0.7854, 0.3927]
|
428 |
+
|
429 |
+
>>> x, w = gauss_chebyshev_u(6, 5)
|
430 |
+
>>> x
|
431 |
+
[0.90097, 0.62349, 0.22252, -0.22252, -0.62349, -0.90097]
|
432 |
+
>>> w
|
433 |
+
[0.084489, 0.27433, 0.42658, 0.42658, 0.27433, 0.084489]
|
434 |
+
|
435 |
+
See Also
|
436 |
+
========
|
437 |
+
|
438 |
+
gauss_legendre, gauss_laguerre, gauss_hermite, gauss_gen_laguerre, gauss_chebyshev_t, gauss_jacobi, gauss_lobatto
|
439 |
+
|
440 |
+
References
|
441 |
+
==========
|
442 |
+
|
443 |
+
.. [1] https://en.wikipedia.org/wiki/Chebyshev%E2%80%93Gauss_quadrature
|
444 |
+
.. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/chebyshev2_rule/chebyshev2_rule.html
|
445 |
+
"""
|
446 |
+
xi = []
|
447 |
+
w = []
|
448 |
+
for i in range(1, n+1):
|
449 |
+
xi.append((cos(i/(n+S.One)*S.Pi)).n(n_digits))
|
450 |
+
w.append((S.Pi/(n+S.One)*sin(i*S.Pi/(n+S.One))**2).n(n_digits))
|
451 |
+
return xi, w
|
452 |
+
|
453 |
+
|
454 |
+
def gauss_jacobi(n, alpha, beta, n_digits):
|
455 |
+
r"""
|
456 |
+
Computes the Gauss-Jacobi quadrature [1]_ points and weights.
|
457 |
+
|
458 |
+
Explanation
|
459 |
+
===========
|
460 |
+
|
461 |
+
The Gauss-Jacobi quadrature of the first kind approximates the integral:
|
462 |
+
|
463 |
+
.. math::
|
464 |
+
\int_{-1}^1 (1-x)^\alpha (1+x)^\beta f(x)\,dx \approx
|
465 |
+
\sum_{i=1}^n w_i f(x_i)
|
466 |
+
|
467 |
+
The nodes `x_i` of an order `n` quadrature rule are the roots of
|
468 |
+
`P^{(\alpha,\beta)}_n` and the weights `w_i` are given by:
|
469 |
+
|
470 |
+
.. math::
|
471 |
+
w_i = -\frac{2n+\alpha+\beta+2}{n+\alpha+\beta+1}
|
472 |
+
\frac{\Gamma(n+\alpha+1)\Gamma(n+\beta+1)}
|
473 |
+
{\Gamma(n+\alpha+\beta+1)(n+1)!}
|
474 |
+
\frac{2^{\alpha+\beta}}{P'_n(x_i)
|
475 |
+
P^{(\alpha,\beta)}_{n+1}(x_i)}
|
476 |
+
|
477 |
+
Parameters
|
478 |
+
==========
|
479 |
+
|
480 |
+
n : the order of quadrature
|
481 |
+
|
482 |
+
alpha : the first parameter of the Jacobi Polynomial, `\alpha > -1`
|
483 |
+
|
484 |
+
beta : the second parameter of the Jacobi Polynomial, `\beta > -1`
|
485 |
+
|
486 |
+
n_digits : number of significant digits of the points and weights to return
|
487 |
+
|
488 |
+
Returns
|
489 |
+
=======
|
490 |
+
|
491 |
+
(x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
|
492 |
+
The points `x_i` and weights `w_i` are returned as ``(x, w)``
|
493 |
+
tuple of lists.
|
494 |
+
|
495 |
+
Examples
|
496 |
+
========
|
497 |
+
|
498 |
+
>>> from sympy import S
|
499 |
+
>>> from sympy.integrals.quadrature import gauss_jacobi
|
500 |
+
>>> x, w = gauss_jacobi(3, S.Half, -S.Half, 5)
|
501 |
+
>>> x
|
502 |
+
[-0.90097, -0.22252, 0.62349]
|
503 |
+
>>> w
|
504 |
+
[1.7063, 1.0973, 0.33795]
|
505 |
+
|
506 |
+
>>> x, w = gauss_jacobi(6, 1, 1, 5)
|
507 |
+
>>> x
|
508 |
+
[-0.87174, -0.5917, -0.2093, 0.2093, 0.5917, 0.87174]
|
509 |
+
>>> w
|
510 |
+
[0.050584, 0.22169, 0.39439, 0.39439, 0.22169, 0.050584]
|
511 |
+
|
512 |
+
See Also
|
513 |
+
========
|
514 |
+
|
515 |
+
gauss_legendre, gauss_laguerre, gauss_hermite, gauss_gen_laguerre,
|
516 |
+
gauss_chebyshev_t, gauss_chebyshev_u, gauss_lobatto
|
517 |
+
|
518 |
+
References
|
519 |
+
==========
|
520 |
+
|
521 |
+
.. [1] https://en.wikipedia.org/wiki/Gauss%E2%80%93Jacobi_quadrature
|
522 |
+
.. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/jacobi_rule/jacobi_rule.html
|
523 |
+
.. [3] https://people.sc.fsu.edu/~jburkardt/cpp_src/gegenbauer_rule/gegenbauer_rule.html
|
524 |
+
"""
|
525 |
+
x = Dummy("x")
|
526 |
+
p = jacobi_poly(n, alpha, beta, x, polys=True)
|
527 |
+
pd = p.diff(x)
|
528 |
+
pn = jacobi_poly(n+1, alpha, beta, x, polys=True)
|
529 |
+
xi = []
|
530 |
+
w = []
|
531 |
+
for r in p.real_roots():
|
532 |
+
if isinstance(r, RootOf):
|
533 |
+
r = r.eval_rational(S.One/10**(n_digits+2))
|
534 |
+
xi.append(r.n(n_digits))
|
535 |
+
w.append((
|
536 |
+
- (2*n+alpha+beta+2) / (n+alpha+beta+S.One) *
|
537 |
+
(gamma(n+alpha+1)*gamma(n+beta+1)) /
|
538 |
+
(gamma(n+alpha+beta+S.One)*gamma(n+2)) *
|
539 |
+
2**(alpha+beta) / (pd.subs(x, r) * pn.subs(x, r))).n(n_digits))
|
540 |
+
return xi, w
|
541 |
+
|
542 |
+
|
543 |
+
def gauss_lobatto(n, n_digits):
|
544 |
+
r"""
|
545 |
+
Computes the Gauss-Lobatto quadrature [1]_ points and weights.
|
546 |
+
|
547 |
+
Explanation
|
548 |
+
===========
|
549 |
+
|
550 |
+
The Gauss-Lobatto quadrature approximates the integral:
|
551 |
+
|
552 |
+
.. math::
|
553 |
+
\int_{-1}^1 f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i)
|
554 |
+
|
555 |
+
The nodes `x_i` of an order `n` quadrature rule are the roots of `P'_(n-1)`
|
556 |
+
and the weights `w_i` are given by:
|
557 |
+
|
558 |
+
.. math::
|
559 |
+
&w_i = \frac{2}{n(n-1) \left[P_{n-1}(x_i)\right]^2},\quad x\neq\pm 1\\
|
560 |
+
&w_i = \frac{2}{n(n-1)},\quad x=\pm 1
|
561 |
+
|
562 |
+
Parameters
|
563 |
+
==========
|
564 |
+
|
565 |
+
n : the order of quadrature
|
566 |
+
|
567 |
+
n_digits : number of significant digits of the points and weights to return
|
568 |
+
|
569 |
+
Returns
|
570 |
+
=======
|
571 |
+
|
572 |
+
(x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
|
573 |
+
The points `x_i` and weights `w_i` are returned as ``(x, w)``
|
574 |
+
tuple of lists.
|
575 |
+
|
576 |
+
Examples
|
577 |
+
========
|
578 |
+
|
579 |
+
>>> from sympy.integrals.quadrature import gauss_lobatto
|
580 |
+
>>> x, w = gauss_lobatto(3, 5)
|
581 |
+
>>> x
|
582 |
+
[-1, 0, 1]
|
583 |
+
>>> w
|
584 |
+
[0.33333, 1.3333, 0.33333]
|
585 |
+
>>> x, w = gauss_lobatto(4, 5)
|
586 |
+
>>> x
|
587 |
+
[-1, -0.44721, 0.44721, 1]
|
588 |
+
>>> w
|
589 |
+
[0.16667, 0.83333, 0.83333, 0.16667]
|
590 |
+
|
591 |
+
See Also
|
592 |
+
========
|
593 |
+
|
594 |
+
gauss_legendre,gauss_laguerre, gauss_gen_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi
|
595 |
+
|
596 |
+
References
|
597 |
+
==========
|
598 |
+
|
599 |
+
.. [1] https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss.E2.80.93Lobatto_rules
|
600 |
+
.. [2] https://web.archive.org/web/20200118141346/http://people.math.sfu.ca/~cbm/aands/page_888.htm
|
601 |
+
"""
|
602 |
+
x = Dummy("x")
|
603 |
+
p = legendre_poly(n-1, x, polys=True)
|
604 |
+
pd = p.diff(x)
|
605 |
+
xi = []
|
606 |
+
w = []
|
607 |
+
for r in pd.real_roots():
|
608 |
+
if isinstance(r, RootOf):
|
609 |
+
r = r.eval_rational(S.One/10**(n_digits+2))
|
610 |
+
xi.append(r.n(n_digits))
|
611 |
+
w.append((2/(n*(n-1) * p.subs(x, r)**2)).n(n_digits))
|
612 |
+
|
613 |
+
xi.insert(0, -1)
|
614 |
+
xi.append(1)
|
615 |
+
w.insert(0, (S(2)/(n*(n-1))).n(n_digits))
|
616 |
+
w.append((S(2)/(n*(n-1))).n(n_digits))
|
617 |
+
return xi, w
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/rationaltools.py
ADDED
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""This module implements tools for integrating rational functions. """
|
2 |
+
|
3 |
+
from sympy.core.function import Lambda
|
4 |
+
from sympy.core.numbers import I
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.core.symbol import (Dummy, Symbol, symbols)
|
7 |
+
from sympy.functions.elementary.exponential import log
|
8 |
+
from sympy.functions.elementary.trigonometric import atan
|
9 |
+
from sympy.polys.polyroots import roots
|
10 |
+
from sympy.polys.polytools import cancel
|
11 |
+
from sympy.polys.rootoftools import RootSum
|
12 |
+
from sympy.polys import Poly, resultant, ZZ
|
13 |
+
|
14 |
+
|
15 |
+
def ratint(f, x, **flags):
|
16 |
+
"""
|
17 |
+
Performs indefinite integration of rational functions.
|
18 |
+
|
19 |
+
Explanation
|
20 |
+
===========
|
21 |
+
|
22 |
+
Given a field :math:`K` and a rational function :math:`f = p/q`,
|
23 |
+
where :math:`p` and :math:`q` are polynomials in :math:`K[x]`,
|
24 |
+
returns a function :math:`g` such that :math:`f = g'`.
|
25 |
+
|
26 |
+
Examples
|
27 |
+
========
|
28 |
+
|
29 |
+
>>> from sympy.integrals.rationaltools import ratint
|
30 |
+
>>> from sympy.abc import x
|
31 |
+
|
32 |
+
>>> ratint(36/(x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2), x)
|
33 |
+
(12*x + 6)/(x**2 - 1) + 4*log(x - 2) - 4*log(x + 1)
|
34 |
+
|
35 |
+
References
|
36 |
+
==========
|
37 |
+
|
38 |
+
.. [1] M. Bronstein, Symbolic Integration I: Transcendental
|
39 |
+
Functions, Second Edition, Springer-Verlag, 2005, pp. 35-70
|
40 |
+
|
41 |
+
See Also
|
42 |
+
========
|
43 |
+
|
44 |
+
sympy.integrals.integrals.Integral.doit
|
45 |
+
sympy.integrals.rationaltools.ratint_logpart
|
46 |
+
sympy.integrals.rationaltools.ratint_ratpart
|
47 |
+
|
48 |
+
"""
|
49 |
+
if isinstance(f, tuple):
|
50 |
+
p, q = f
|
51 |
+
else:
|
52 |
+
p, q = f.as_numer_denom()
|
53 |
+
|
54 |
+
p, q = Poly(p, x, composite=False, field=True), Poly(q, x, composite=False, field=True)
|
55 |
+
|
56 |
+
coeff, p, q = p.cancel(q)
|
57 |
+
poly, p = p.div(q)
|
58 |
+
|
59 |
+
result = poly.integrate(x).as_expr()
|
60 |
+
|
61 |
+
if p.is_zero:
|
62 |
+
return coeff*result
|
63 |
+
|
64 |
+
g, h = ratint_ratpart(p, q, x)
|
65 |
+
|
66 |
+
P, Q = h.as_numer_denom()
|
67 |
+
|
68 |
+
P = Poly(P, x)
|
69 |
+
Q = Poly(Q, x)
|
70 |
+
|
71 |
+
q, r = P.div(Q)
|
72 |
+
|
73 |
+
result += g + q.integrate(x).as_expr()
|
74 |
+
|
75 |
+
if not r.is_zero:
|
76 |
+
symbol = flags.get('symbol', 't')
|
77 |
+
|
78 |
+
if not isinstance(symbol, Symbol):
|
79 |
+
t = Dummy(symbol)
|
80 |
+
else:
|
81 |
+
t = symbol.as_dummy()
|
82 |
+
|
83 |
+
L = ratint_logpart(r, Q, x, t)
|
84 |
+
|
85 |
+
real = flags.get('real')
|
86 |
+
|
87 |
+
if real is None:
|
88 |
+
if isinstance(f, tuple):
|
89 |
+
p, q = f
|
90 |
+
atoms = p.atoms() | q.atoms()
|
91 |
+
else:
|
92 |
+
atoms = f.atoms()
|
93 |
+
|
94 |
+
for elt in atoms - {x}:
|
95 |
+
if not elt.is_extended_real:
|
96 |
+
real = False
|
97 |
+
break
|
98 |
+
else:
|
99 |
+
real = True
|
100 |
+
|
101 |
+
eps = S.Zero
|
102 |
+
|
103 |
+
if not real:
|
104 |
+
for h, q in L:
|
105 |
+
_, h = h.primitive()
|
106 |
+
eps += RootSum(
|
107 |
+
q, Lambda(t, t*log(h.as_expr())), quadratic=True)
|
108 |
+
else:
|
109 |
+
for h, q in L:
|
110 |
+
_, h = h.primitive()
|
111 |
+
R = log_to_real(h, q, x, t)
|
112 |
+
|
113 |
+
if R is not None:
|
114 |
+
eps += R
|
115 |
+
else:
|
116 |
+
eps += RootSum(
|
117 |
+
q, Lambda(t, t*log(h.as_expr())), quadratic=True)
|
118 |
+
|
119 |
+
result += eps
|
120 |
+
|
121 |
+
return coeff*result
|
122 |
+
|
123 |
+
|
124 |
+
def ratint_ratpart(f, g, x):
|
125 |
+
"""
|
126 |
+
Horowitz-Ostrogradsky algorithm.
|
127 |
+
|
128 |
+
Explanation
|
129 |
+
===========
|
130 |
+
|
131 |
+
Given a field K and polynomials f and g in K[x], such that f and g
|
132 |
+
are coprime and deg(f) < deg(g), returns fractions A and B in K(x),
|
133 |
+
such that f/g = A' + B and B has square-free denominator.
|
134 |
+
|
135 |
+
Examples
|
136 |
+
========
|
137 |
+
|
138 |
+
>>> from sympy.integrals.rationaltools import ratint_ratpart
|
139 |
+
>>> from sympy.abc import x, y
|
140 |
+
>>> from sympy import Poly
|
141 |
+
>>> ratint_ratpart(Poly(1, x, domain='ZZ'),
|
142 |
+
... Poly(x + 1, x, domain='ZZ'), x)
|
143 |
+
(0, 1/(x + 1))
|
144 |
+
>>> ratint_ratpart(Poly(1, x, domain='EX'),
|
145 |
+
... Poly(x**2 + y**2, x, domain='EX'), x)
|
146 |
+
(0, 1/(x**2 + y**2))
|
147 |
+
>>> ratint_ratpart(Poly(36, x, domain='ZZ'),
|
148 |
+
... Poly(x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2, x, domain='ZZ'), x)
|
149 |
+
((12*x + 6)/(x**2 - 1), 12/(x**2 - x - 2))
|
150 |
+
|
151 |
+
See Also
|
152 |
+
========
|
153 |
+
|
154 |
+
ratint, ratint_logpart
|
155 |
+
"""
|
156 |
+
from sympy.solvers.solvers import solve
|
157 |
+
|
158 |
+
f = Poly(f, x)
|
159 |
+
g = Poly(g, x)
|
160 |
+
|
161 |
+
u, v, _ = g.cofactors(g.diff())
|
162 |
+
|
163 |
+
n = u.degree()
|
164 |
+
m = v.degree()
|
165 |
+
|
166 |
+
A_coeffs = [ Dummy('a' + str(n - i)) for i in range(0, n) ]
|
167 |
+
B_coeffs = [ Dummy('b' + str(m - i)) for i in range(0, m) ]
|
168 |
+
|
169 |
+
C_coeffs = A_coeffs + B_coeffs
|
170 |
+
|
171 |
+
A = Poly(A_coeffs, x, domain=ZZ[C_coeffs])
|
172 |
+
B = Poly(B_coeffs, x, domain=ZZ[C_coeffs])
|
173 |
+
|
174 |
+
H = f - A.diff()*v + A*(u.diff()*v).quo(u) - B*u
|
175 |
+
|
176 |
+
result = solve(H.coeffs(), C_coeffs)
|
177 |
+
|
178 |
+
A = A.as_expr().subs(result)
|
179 |
+
B = B.as_expr().subs(result)
|
180 |
+
|
181 |
+
rat_part = cancel(A/u.as_expr(), x)
|
182 |
+
log_part = cancel(B/v.as_expr(), x)
|
183 |
+
|
184 |
+
return rat_part, log_part
|
185 |
+
|
186 |
+
|
187 |
+
def ratint_logpart(f, g, x, t=None):
|
188 |
+
r"""
|
189 |
+
Lazard-Rioboo-Trager algorithm.
|
190 |
+
|
191 |
+
Explanation
|
192 |
+
===========
|
193 |
+
|
194 |
+
Given a field K and polynomials f and g in K[x], such that f and g
|
195 |
+
are coprime, deg(f) < deg(g) and g is square-free, returns a list
|
196 |
+
of tuples (s_i, q_i) of polynomials, for i = 1..n, such that s_i
|
197 |
+
in K[t, x] and q_i in K[t], and::
|
198 |
+
|
199 |
+
___ ___
|
200 |
+
d f d \ ` \ `
|
201 |
+
-- - = -- ) ) a log(s_i(a, x))
|
202 |
+
dx g dx /__, /__,
|
203 |
+
i=1..n a | q_i(a) = 0
|
204 |
+
|
205 |
+
Examples
|
206 |
+
========
|
207 |
+
|
208 |
+
>>> from sympy.integrals.rationaltools import ratint_logpart
|
209 |
+
>>> from sympy.abc import x
|
210 |
+
>>> from sympy import Poly
|
211 |
+
>>> ratint_logpart(Poly(1, x, domain='ZZ'),
|
212 |
+
... Poly(x**2 + x + 1, x, domain='ZZ'), x)
|
213 |
+
[(Poly(x + 3*_t/2 + 1/2, x, domain='QQ[_t]'),
|
214 |
+
...Poly(3*_t**2 + 1, _t, domain='ZZ'))]
|
215 |
+
>>> ratint_logpart(Poly(12, x, domain='ZZ'),
|
216 |
+
... Poly(x**2 - x - 2, x, domain='ZZ'), x)
|
217 |
+
[(Poly(x - 3*_t/8 - 1/2, x, domain='QQ[_t]'),
|
218 |
+
...Poly(-_t**2 + 16, _t, domain='ZZ'))]
|
219 |
+
|
220 |
+
See Also
|
221 |
+
========
|
222 |
+
|
223 |
+
ratint, ratint_ratpart
|
224 |
+
"""
|
225 |
+
f, g = Poly(f, x), Poly(g, x)
|
226 |
+
|
227 |
+
t = t or Dummy('t')
|
228 |
+
a, b = g, f - g.diff()*Poly(t, x)
|
229 |
+
|
230 |
+
res, R = resultant(a, b, includePRS=True)
|
231 |
+
res = Poly(res, t, composite=False)
|
232 |
+
|
233 |
+
assert res, "BUG: resultant(%s, %s) cannot be zero" % (a, b)
|
234 |
+
|
235 |
+
R_map, H = {}, []
|
236 |
+
|
237 |
+
for r in R:
|
238 |
+
R_map[r.degree()] = r
|
239 |
+
|
240 |
+
def _include_sign(c, sqf):
|
241 |
+
if c.is_extended_real and (c < 0) == True:
|
242 |
+
h, k = sqf[0]
|
243 |
+
c_poly = c.as_poly(h.gens)
|
244 |
+
sqf[0] = h*c_poly, k
|
245 |
+
|
246 |
+
C, res_sqf = res.sqf_list()
|
247 |
+
_include_sign(C, res_sqf)
|
248 |
+
|
249 |
+
for q, i in res_sqf:
|
250 |
+
_, q = q.primitive()
|
251 |
+
|
252 |
+
if g.degree() == i:
|
253 |
+
H.append((g, q))
|
254 |
+
else:
|
255 |
+
h = R_map[i]
|
256 |
+
h_lc = Poly(h.LC(), t, field=True)
|
257 |
+
|
258 |
+
c, h_lc_sqf = h_lc.sqf_list(all=True)
|
259 |
+
_include_sign(c, h_lc_sqf)
|
260 |
+
|
261 |
+
for a, j in h_lc_sqf:
|
262 |
+
h = h.quo(Poly(a.gcd(q)**j, x))
|
263 |
+
|
264 |
+
inv, coeffs = h_lc.invert(q), [S.One]
|
265 |
+
|
266 |
+
for coeff in h.coeffs()[1:]:
|
267 |
+
coeff = coeff.as_poly(inv.gens)
|
268 |
+
T = (inv*coeff).rem(q)
|
269 |
+
coeffs.append(T.as_expr())
|
270 |
+
|
271 |
+
h = Poly(dict(list(zip(h.monoms(), coeffs))), x)
|
272 |
+
|
273 |
+
H.append((h, q))
|
274 |
+
|
275 |
+
return H
|
276 |
+
|
277 |
+
|
278 |
+
def log_to_atan(f, g):
|
279 |
+
"""
|
280 |
+
Convert complex logarithms to real arctangents.
|
281 |
+
|
282 |
+
Explanation
|
283 |
+
===========
|
284 |
+
|
285 |
+
Given a real field K and polynomials f and g in K[x], with g != 0,
|
286 |
+
returns a sum h of arctangents of polynomials in K[x], such that:
|
287 |
+
|
288 |
+
dh d f + I g
|
289 |
+
-- = -- I log( ------- )
|
290 |
+
dx dx f - I g
|
291 |
+
|
292 |
+
Examples
|
293 |
+
========
|
294 |
+
|
295 |
+
>>> from sympy.integrals.rationaltools import log_to_atan
|
296 |
+
>>> from sympy.abc import x
|
297 |
+
>>> from sympy import Poly, sqrt, S
|
298 |
+
>>> log_to_atan(Poly(x, x, domain='ZZ'), Poly(1, x, domain='ZZ'))
|
299 |
+
2*atan(x)
|
300 |
+
>>> log_to_atan(Poly(x + S(1)/2, x, domain='QQ'),
|
301 |
+
... Poly(sqrt(3)/2, x, domain='EX'))
|
302 |
+
2*atan(2*sqrt(3)*x/3 + sqrt(3)/3)
|
303 |
+
|
304 |
+
See Also
|
305 |
+
========
|
306 |
+
|
307 |
+
log_to_real
|
308 |
+
"""
|
309 |
+
if f.degree() < g.degree():
|
310 |
+
f, g = -g, f
|
311 |
+
|
312 |
+
f = f.to_field()
|
313 |
+
g = g.to_field()
|
314 |
+
|
315 |
+
p, q = f.div(g)
|
316 |
+
|
317 |
+
if q.is_zero:
|
318 |
+
return 2*atan(p.as_expr())
|
319 |
+
else:
|
320 |
+
s, t, h = g.gcdex(-f)
|
321 |
+
u = (f*s + g*t).quo(h)
|
322 |
+
A = 2*atan(u.as_expr())
|
323 |
+
|
324 |
+
return A + log_to_atan(s, t)
|
325 |
+
|
326 |
+
|
327 |
+
def log_to_real(h, q, x, t):
|
328 |
+
r"""
|
329 |
+
Convert complex logarithms to real functions.
|
330 |
+
|
331 |
+
Explanation
|
332 |
+
===========
|
333 |
+
|
334 |
+
Given real field K and polynomials h in K[t,x] and q in K[t],
|
335 |
+
returns real function f such that:
|
336 |
+
___
|
337 |
+
df d \ `
|
338 |
+
-- = -- ) a log(h(a, x))
|
339 |
+
dx dx /__,
|
340 |
+
a | q(a) = 0
|
341 |
+
|
342 |
+
Examples
|
343 |
+
========
|
344 |
+
|
345 |
+
>>> from sympy.integrals.rationaltools import log_to_real
|
346 |
+
>>> from sympy.abc import x, y
|
347 |
+
>>> from sympy import Poly, S
|
348 |
+
>>> log_to_real(Poly(x + 3*y/2 + S(1)/2, x, domain='QQ[y]'),
|
349 |
+
... Poly(3*y**2 + 1, y, domain='ZZ'), x, y)
|
350 |
+
2*sqrt(3)*atan(2*sqrt(3)*x/3 + sqrt(3)/3)/3
|
351 |
+
>>> log_to_real(Poly(x**2 - 1, x, domain='ZZ'),
|
352 |
+
... Poly(-2*y + 1, y, domain='ZZ'), x, y)
|
353 |
+
log(x**2 - 1)/2
|
354 |
+
|
355 |
+
See Also
|
356 |
+
========
|
357 |
+
|
358 |
+
log_to_atan
|
359 |
+
"""
|
360 |
+
from sympy.simplify.radsimp import collect
|
361 |
+
u, v = symbols('u,v', cls=Dummy)
|
362 |
+
|
363 |
+
H = h.as_expr().subs({t: u + I*v}).expand()
|
364 |
+
Q = q.as_expr().subs({t: u + I*v}).expand()
|
365 |
+
|
366 |
+
H_map = collect(H, I, evaluate=False)
|
367 |
+
Q_map = collect(Q, I, evaluate=False)
|
368 |
+
|
369 |
+
a, b = H_map.get(S.One, S.Zero), H_map.get(I, S.Zero)
|
370 |
+
c, d = Q_map.get(S.One, S.Zero), Q_map.get(I, S.Zero)
|
371 |
+
|
372 |
+
R = Poly(resultant(c, d, v), u)
|
373 |
+
|
374 |
+
R_u = roots(R, filter='R')
|
375 |
+
|
376 |
+
if len(R_u) != R.count_roots():
|
377 |
+
return None
|
378 |
+
|
379 |
+
result = S.Zero
|
380 |
+
|
381 |
+
for r_u in R_u.keys():
|
382 |
+
C = Poly(c.subs({u: r_u}), v)
|
383 |
+
R_v = roots(C, filter='R')
|
384 |
+
|
385 |
+
if len(R_v) != C.count_roots():
|
386 |
+
return None
|
387 |
+
|
388 |
+
R_v_paired = [] # take one from each pair of conjugate roots
|
389 |
+
for r_v in R_v:
|
390 |
+
if r_v not in R_v_paired and -r_v not in R_v_paired:
|
391 |
+
if r_v.is_negative or r_v.could_extract_minus_sign():
|
392 |
+
R_v_paired.append(-r_v)
|
393 |
+
elif not r_v.is_zero:
|
394 |
+
R_v_paired.append(r_v)
|
395 |
+
|
396 |
+
for r_v in R_v_paired:
|
397 |
+
|
398 |
+
D = d.subs({u: r_u, v: r_v})
|
399 |
+
|
400 |
+
if D.evalf(chop=True) != 0:
|
401 |
+
continue
|
402 |
+
|
403 |
+
A = Poly(a.subs({u: r_u, v: r_v}), x)
|
404 |
+
B = Poly(b.subs({u: r_u, v: r_v}), x)
|
405 |
+
|
406 |
+
AB = (A**2 + B**2).as_expr()
|
407 |
+
|
408 |
+
result += r_u*log(AB) + r_v*log_to_atan(A, B)
|
409 |
+
|
410 |
+
R_q = roots(q, filter='R')
|
411 |
+
|
412 |
+
if len(R_q) != q.count_roots():
|
413 |
+
return None
|
414 |
+
|
415 |
+
for r in R_q.keys():
|
416 |
+
result += r*log(h.as_expr().subs(t, r))
|
417 |
+
|
418 |
+
return result
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/rde.py
ADDED
@@ -0,0 +1,800 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Algorithms for solving the Risch differential equation.
|
3 |
+
|
4 |
+
Given a differential field K of characteristic 0 that is a simple
|
5 |
+
monomial extension of a base field k and f, g in K, the Risch
|
6 |
+
Differential Equation problem is to decide if there exist y in K such
|
7 |
+
that Dy + f*y == g and to find one if there are some. If t is a
|
8 |
+
monomial over k and the coefficients of f and g are in k(t), then y is
|
9 |
+
in k(t), and the outline of the algorithm here is given as:
|
10 |
+
|
11 |
+
1. Compute the normal part n of the denominator of y. The problem is
|
12 |
+
then reduced to finding y' in k<t>, where y == y'/n.
|
13 |
+
2. Compute the special part s of the denominator of y. The problem is
|
14 |
+
then reduced to finding y'' in k[t], where y == y''/(n*s)
|
15 |
+
3. Bound the degree of y''.
|
16 |
+
4. Reduce the equation Dy + f*y == g to a similar equation with f, g in
|
17 |
+
k[t].
|
18 |
+
5. Find the solutions in k[t] of bounded degree of the reduced equation.
|
19 |
+
|
20 |
+
See Chapter 6 of "Symbolic Integration I: Transcendental Functions" by
|
21 |
+
Manuel Bronstein. See also the docstring of risch.py.
|
22 |
+
"""
|
23 |
+
|
24 |
+
from operator import mul
|
25 |
+
from functools import reduce
|
26 |
+
|
27 |
+
from sympy.core import oo
|
28 |
+
from sympy.core.symbol import Dummy
|
29 |
+
|
30 |
+
from sympy.polys import Poly, gcd, ZZ, cancel
|
31 |
+
|
32 |
+
from sympy.functions.elementary.complexes import (im, re)
|
33 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
34 |
+
|
35 |
+
from sympy.integrals.risch import (gcdex_diophantine, frac_in, derivation,
|
36 |
+
splitfactor, NonElementaryIntegralException, DecrementLevel, recognize_log_derivative)
|
37 |
+
|
38 |
+
# TODO: Add messages to NonElementaryIntegralException errors
|
39 |
+
|
40 |
+
|
41 |
+
def order_at(a, p, t):
|
42 |
+
"""
|
43 |
+
Computes the order of a at p, with respect to t.
|
44 |
+
|
45 |
+
Explanation
|
46 |
+
===========
|
47 |
+
|
48 |
+
For a, p in k[t], the order of a at p is defined as nu_p(a) = max({n
|
49 |
+
in Z+ such that p**n|a}), where a != 0. If a == 0, nu_p(a) = +oo.
|
50 |
+
|
51 |
+
To compute the order at a rational function, a/b, use the fact that
|
52 |
+
nu_p(a/b) == nu_p(a) - nu_p(b).
|
53 |
+
"""
|
54 |
+
if a.is_zero:
|
55 |
+
return oo
|
56 |
+
if p == Poly(t, t):
|
57 |
+
return a.as_poly(t).ET()[0][0]
|
58 |
+
|
59 |
+
# Uses binary search for calculating the power. power_list collects the tuples
|
60 |
+
# (p^k,k) where each k is some power of 2. After deciding the largest k
|
61 |
+
# such that k is power of 2 and p^k|a the loop iteratively calculates
|
62 |
+
# the actual power.
|
63 |
+
power_list = []
|
64 |
+
p1 = p
|
65 |
+
r = a.rem(p1)
|
66 |
+
tracks_power = 1
|
67 |
+
while r.is_zero:
|
68 |
+
power_list.append((p1,tracks_power))
|
69 |
+
p1 = p1*p1
|
70 |
+
tracks_power *= 2
|
71 |
+
r = a.rem(p1)
|
72 |
+
n = 0
|
73 |
+
product = Poly(1, t)
|
74 |
+
while len(power_list) != 0:
|
75 |
+
final = power_list.pop()
|
76 |
+
productf = product*final[0]
|
77 |
+
r = a.rem(productf)
|
78 |
+
if r.is_zero:
|
79 |
+
n += final[1]
|
80 |
+
product = productf
|
81 |
+
return n
|
82 |
+
|
83 |
+
|
84 |
+
def order_at_oo(a, d, t):
|
85 |
+
"""
|
86 |
+
Computes the order of a/d at oo (infinity), with respect to t.
|
87 |
+
|
88 |
+
For f in k(t), the order or f at oo is defined as deg(d) - deg(a), where
|
89 |
+
f == a/d.
|
90 |
+
"""
|
91 |
+
if a.is_zero:
|
92 |
+
return oo
|
93 |
+
return d.degree(t) - a.degree(t)
|
94 |
+
|
95 |
+
|
96 |
+
def weak_normalizer(a, d, DE, z=None):
|
97 |
+
"""
|
98 |
+
Weak normalization.
|
99 |
+
|
100 |
+
Explanation
|
101 |
+
===========
|
102 |
+
|
103 |
+
Given a derivation D on k[t] and f == a/d in k(t), return q in k[t]
|
104 |
+
such that f - Dq/q is weakly normalized with respect to t.
|
105 |
+
|
106 |
+
f in k(t) is said to be "weakly normalized" with respect to t if
|
107 |
+
residue_p(f) is not a positive integer for any normal irreducible p
|
108 |
+
in k[t] such that f is in R_p (Definition 6.1.1). If f has an
|
109 |
+
elementary integral, this is equivalent to no logarithm of
|
110 |
+
integral(f) whose argument depends on t has a positive integer
|
111 |
+
coefficient, where the arguments of the logarithms not in k(t) are
|
112 |
+
in k[t].
|
113 |
+
|
114 |
+
Returns (q, f - Dq/q)
|
115 |
+
"""
|
116 |
+
z = z or Dummy('z')
|
117 |
+
dn, ds = splitfactor(d, DE)
|
118 |
+
|
119 |
+
# Compute d1, where dn == d1*d2**2*...*dn**n is a square-free
|
120 |
+
# factorization of d.
|
121 |
+
g = gcd(dn, dn.diff(DE.t))
|
122 |
+
d_sqf_part = dn.quo(g)
|
123 |
+
d1 = d_sqf_part.quo(gcd(d_sqf_part, g))
|
124 |
+
|
125 |
+
a1, b = gcdex_diophantine(d.quo(d1).as_poly(DE.t), d1.as_poly(DE.t),
|
126 |
+
a.as_poly(DE.t))
|
127 |
+
r = (a - Poly(z, DE.t)*derivation(d1, DE)).as_poly(DE.t).resultant(
|
128 |
+
d1.as_poly(DE.t))
|
129 |
+
r = Poly(r, z)
|
130 |
+
|
131 |
+
if not r.expr.has(z):
|
132 |
+
return (Poly(1, DE.t), (a, d))
|
133 |
+
|
134 |
+
N = [i for i in r.real_roots() if i in ZZ and i > 0]
|
135 |
+
|
136 |
+
q = reduce(mul, [gcd(a - Poly(n, DE.t)*derivation(d1, DE), d1) for n in N],
|
137 |
+
Poly(1, DE.t))
|
138 |
+
|
139 |
+
dq = derivation(q, DE)
|
140 |
+
sn = q*a - d*dq
|
141 |
+
sd = q*d
|
142 |
+
sn, sd = sn.cancel(sd, include=True)
|
143 |
+
|
144 |
+
return (q, (sn, sd))
|
145 |
+
|
146 |
+
|
147 |
+
def normal_denom(fa, fd, ga, gd, DE):
|
148 |
+
"""
|
149 |
+
Normal part of the denominator.
|
150 |
+
|
151 |
+
Explanation
|
152 |
+
===========
|
153 |
+
|
154 |
+
Given a derivation D on k[t] and f, g in k(t) with f weakly
|
155 |
+
normalized with respect to t, either raise NonElementaryIntegralException,
|
156 |
+
in which case the equation Dy + f*y == g has no solution in k(t), or the
|
157 |
+
quadruplet (a, b, c, h) such that a, h in k[t], b, c in k<t>, and for any
|
158 |
+
solution y in k(t) of Dy + f*y == g, q = y*h in k<t> satisfies
|
159 |
+
a*Dq + b*q == c.
|
160 |
+
|
161 |
+
This constitutes step 1 in the outline given in the rde.py docstring.
|
162 |
+
"""
|
163 |
+
dn, ds = splitfactor(fd, DE)
|
164 |
+
en, es = splitfactor(gd, DE)
|
165 |
+
|
166 |
+
p = dn.gcd(en)
|
167 |
+
h = en.gcd(en.diff(DE.t)).quo(p.gcd(p.diff(DE.t)))
|
168 |
+
|
169 |
+
a = dn*h
|
170 |
+
c = a*h
|
171 |
+
if c.div(en)[1]:
|
172 |
+
# en does not divide dn*h**2
|
173 |
+
raise NonElementaryIntegralException
|
174 |
+
ca = c*ga
|
175 |
+
ca, cd = ca.cancel(gd, include=True)
|
176 |
+
|
177 |
+
ba = a*fa - dn*derivation(h, DE)*fd
|
178 |
+
ba, bd = ba.cancel(fd, include=True)
|
179 |
+
|
180 |
+
# (dn*h, dn*h*f - dn*Dh, dn*h**2*g, h)
|
181 |
+
return (a, (ba, bd), (ca, cd), h)
|
182 |
+
|
183 |
+
|
184 |
+
def special_denom(a, ba, bd, ca, cd, DE, case='auto'):
|
185 |
+
"""
|
186 |
+
Special part of the denominator.
|
187 |
+
|
188 |
+
Explanation
|
189 |
+
===========
|
190 |
+
|
191 |
+
case is one of {'exp', 'tan', 'primitive'} for the hyperexponential,
|
192 |
+
hypertangent, and primitive cases, respectively. For the
|
193 |
+
hyperexponential (resp. hypertangent) case, given a derivation D on
|
194 |
+
k[t] and a in k[t], b, c, in k<t> with Dt/t in k (resp. Dt/(t**2 + 1) in
|
195 |
+
k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp.
|
196 |
+
gcd(a, t**2 + 1) == 1), return the quadruplet (A, B, C, 1/h) such that
|
197 |
+
A, B, C, h in k[t] and for any solution q in k<t> of a*Dq + b*q == c,
|
198 |
+
r = qh in k[t] satisfies A*Dr + B*r == C.
|
199 |
+
|
200 |
+
For ``case == 'primitive'``, k<t> == k[t], so it returns (a, b, c, 1) in
|
201 |
+
this case.
|
202 |
+
|
203 |
+
This constitutes step 2 of the outline given in the rde.py docstring.
|
204 |
+
"""
|
205 |
+
# TODO: finish writing this and write tests
|
206 |
+
|
207 |
+
if case == 'auto':
|
208 |
+
case = DE.case
|
209 |
+
|
210 |
+
if case == 'exp':
|
211 |
+
p = Poly(DE.t, DE.t)
|
212 |
+
elif case == 'tan':
|
213 |
+
p = Poly(DE.t**2 + 1, DE.t)
|
214 |
+
elif case in ('primitive', 'base'):
|
215 |
+
B = ba.to_field().quo(bd)
|
216 |
+
C = ca.to_field().quo(cd)
|
217 |
+
return (a, B, C, Poly(1, DE.t))
|
218 |
+
else:
|
219 |
+
raise ValueError("case must be one of {'exp', 'tan', 'primitive', "
|
220 |
+
"'base'}, not %s." % case)
|
221 |
+
|
222 |
+
nb = order_at(ba, p, DE.t) - order_at(bd, p, DE.t)
|
223 |
+
nc = order_at(ca, p, DE.t) - order_at(cd, p, DE.t)
|
224 |
+
|
225 |
+
n = min(0, nc - min(0, nb))
|
226 |
+
if not nb:
|
227 |
+
# Possible cancellation.
|
228 |
+
from .prde import parametric_log_deriv
|
229 |
+
if case == 'exp':
|
230 |
+
dcoeff = DE.d.quo(Poly(DE.t, DE.t))
|
231 |
+
with DecrementLevel(DE): # We are guaranteed to not have problems,
|
232 |
+
# because case != 'base'.
|
233 |
+
alphaa, alphad = frac_in(-ba.eval(0)/bd.eval(0)/a.eval(0), DE.t)
|
234 |
+
etaa, etad = frac_in(dcoeff, DE.t)
|
235 |
+
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
|
236 |
+
if A is not None:
|
237 |
+
Q, m, z = A
|
238 |
+
if Q == 1:
|
239 |
+
n = min(n, m)
|
240 |
+
|
241 |
+
elif case == 'tan':
|
242 |
+
dcoeff = DE.d.quo(Poly(DE.t**2+1, DE.t))
|
243 |
+
with DecrementLevel(DE): # We are guaranteed to not have problems,
|
244 |
+
# because case != 'base'.
|
245 |
+
alphaa, alphad = frac_in(im(-ba.eval(sqrt(-1))/bd.eval(sqrt(-1))/a.eval(sqrt(-1))), DE.t)
|
246 |
+
betaa, betad = frac_in(re(-ba.eval(sqrt(-1))/bd.eval(sqrt(-1))/a.eval(sqrt(-1))), DE.t)
|
247 |
+
etaa, etad = frac_in(dcoeff, DE.t)
|
248 |
+
|
249 |
+
if recognize_log_derivative(Poly(2, DE.t)*betaa, betad, DE):
|
250 |
+
A = parametric_log_deriv(alphaa*Poly(sqrt(-1), DE.t)*betad+alphad*betaa, alphad*betad, etaa, etad, DE)
|
251 |
+
if A is not None:
|
252 |
+
Q, m, z = A
|
253 |
+
if Q == 1:
|
254 |
+
n = min(n, m)
|
255 |
+
N = max(0, -nb, n - nc)
|
256 |
+
pN = p**N
|
257 |
+
pn = p**-n
|
258 |
+
|
259 |
+
A = a*pN
|
260 |
+
B = ba*pN.quo(bd) + Poly(n, DE.t)*a*derivation(p, DE).quo(p)*pN
|
261 |
+
C = (ca*pN*pn).quo(cd)
|
262 |
+
h = pn
|
263 |
+
|
264 |
+
# (a*p**N, (b + n*a*Dp/p)*p**N, c*p**(N - n), p**-n)
|
265 |
+
return (A, B, C, h)
|
266 |
+
|
267 |
+
|
268 |
+
def bound_degree(a, b, cQ, DE, case='auto', parametric=False):
|
269 |
+
"""
|
270 |
+
Bound on polynomial solutions.
|
271 |
+
|
272 |
+
Explanation
|
273 |
+
===========
|
274 |
+
|
275 |
+
Given a derivation D on k[t] and ``a``, ``b``, ``c`` in k[t] with ``a != 0``, return
|
276 |
+
n in ZZ such that deg(q) <= n for any solution q in k[t] of
|
277 |
+
a*Dq + b*q == c, when parametric=False, or deg(q) <= n for any solution
|
278 |
+
c1, ..., cm in Const(k) and q in k[t] of a*Dq + b*q == Sum(ci*gi, (i, 1, m))
|
279 |
+
when parametric=True.
|
280 |
+
|
281 |
+
For ``parametric=False``, ``cQ`` is ``c``, a ``Poly``; for ``parametric=True``, ``cQ`` is Q ==
|
282 |
+
[q1, ..., qm], a list of Polys.
|
283 |
+
|
284 |
+
This constitutes step 3 of the outline given in the rde.py docstring.
|
285 |
+
"""
|
286 |
+
# TODO: finish writing this and write tests
|
287 |
+
|
288 |
+
if case == 'auto':
|
289 |
+
case = DE.case
|
290 |
+
|
291 |
+
da = a.degree(DE.t)
|
292 |
+
db = b.degree(DE.t)
|
293 |
+
|
294 |
+
# The parametric and regular cases are identical, except for this part
|
295 |
+
if parametric:
|
296 |
+
dc = max([i.degree(DE.t) for i in cQ])
|
297 |
+
else:
|
298 |
+
dc = cQ.degree(DE.t)
|
299 |
+
|
300 |
+
alpha = cancel(-b.as_poly(DE.t).LC().as_expr()/
|
301 |
+
a.as_poly(DE.t).LC().as_expr())
|
302 |
+
|
303 |
+
if case == 'base':
|
304 |
+
n = max(0, dc - max(db, da - 1))
|
305 |
+
if db == da - 1 and alpha.is_Integer:
|
306 |
+
n = max(0, alpha, dc - db)
|
307 |
+
|
308 |
+
elif case == 'primitive':
|
309 |
+
if db > da:
|
310 |
+
n = max(0, dc - db)
|
311 |
+
else:
|
312 |
+
n = max(0, dc - da + 1)
|
313 |
+
|
314 |
+
etaa, etad = frac_in(DE.d, DE.T[DE.level - 1])
|
315 |
+
|
316 |
+
t1 = DE.t
|
317 |
+
with DecrementLevel(DE):
|
318 |
+
alphaa, alphad = frac_in(alpha, DE.t)
|
319 |
+
if db == da - 1:
|
320 |
+
from .prde import limited_integrate
|
321 |
+
# if alpha == m*Dt + Dz for z in k and m in ZZ:
|
322 |
+
try:
|
323 |
+
(za, zd), m = limited_integrate(alphaa, alphad, [(etaa, etad)],
|
324 |
+
DE)
|
325 |
+
except NonElementaryIntegralException:
|
326 |
+
pass
|
327 |
+
else:
|
328 |
+
if len(m) != 1:
|
329 |
+
raise ValueError("Length of m should be 1")
|
330 |
+
n = max(n, m[0])
|
331 |
+
|
332 |
+
elif db == da:
|
333 |
+
# if alpha == Dz/z for z in k*:
|
334 |
+
# beta = -lc(a*Dz + b*z)/(z*lc(a))
|
335 |
+
# if beta == m*Dt + Dw for w in k and m in ZZ:
|
336 |
+
# n = max(n, m)
|
337 |
+
from .prde import is_log_deriv_k_t_radical_in_field
|
338 |
+
A = is_log_deriv_k_t_radical_in_field(alphaa, alphad, DE)
|
339 |
+
if A is not None:
|
340 |
+
aa, z = A
|
341 |
+
if aa == 1:
|
342 |
+
beta = -(a*derivation(z, DE).as_poly(t1) +
|
343 |
+
b*z.as_poly(t1)).LC()/(z.as_expr()*a.LC())
|
344 |
+
betaa, betad = frac_in(beta, DE.t)
|
345 |
+
from .prde import limited_integrate
|
346 |
+
try:
|
347 |
+
(za, zd), m = limited_integrate(betaa, betad,
|
348 |
+
[(etaa, etad)], DE)
|
349 |
+
except NonElementaryIntegralException:
|
350 |
+
pass
|
351 |
+
else:
|
352 |
+
if len(m) != 1:
|
353 |
+
raise ValueError("Length of m should be 1")
|
354 |
+
n = max(n, m[0].as_expr())
|
355 |
+
|
356 |
+
elif case == 'exp':
|
357 |
+
from .prde import parametric_log_deriv
|
358 |
+
|
359 |
+
n = max(0, dc - max(db, da))
|
360 |
+
if da == db:
|
361 |
+
etaa, etad = frac_in(DE.d.quo(Poly(DE.t, DE.t)), DE.T[DE.level - 1])
|
362 |
+
with DecrementLevel(DE):
|
363 |
+
alphaa, alphad = frac_in(alpha, DE.t)
|
364 |
+
A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE)
|
365 |
+
if A is not None:
|
366 |
+
# if alpha == m*Dt/t + Dz/z for z in k* and m in ZZ:
|
367 |
+
# n = max(n, m)
|
368 |
+
a, m, z = A
|
369 |
+
if a == 1:
|
370 |
+
n = max(n, m)
|
371 |
+
|
372 |
+
elif case in ('tan', 'other_nonlinear'):
|
373 |
+
delta = DE.d.degree(DE.t)
|
374 |
+
lam = DE.d.LC()
|
375 |
+
alpha = cancel(alpha/lam)
|
376 |
+
n = max(0, dc - max(da + delta - 1, db))
|
377 |
+
if db == da + delta - 1 and alpha.is_Integer:
|
378 |
+
n = max(0, alpha, dc - db)
|
379 |
+
|
380 |
+
else:
|
381 |
+
raise ValueError("case must be one of {'exp', 'tan', 'primitive', "
|
382 |
+
"'other_nonlinear', 'base'}, not %s." % case)
|
383 |
+
|
384 |
+
return n
|
385 |
+
|
386 |
+
|
387 |
+
def spde(a, b, c, n, DE):
|
388 |
+
"""
|
389 |
+
Rothstein's Special Polynomial Differential Equation algorithm.
|
390 |
+
|
391 |
+
Explanation
|
392 |
+
===========
|
393 |
+
|
394 |
+
Given a derivation D on k[t], an integer n and ``a``,``b``,``c`` in k[t] with
|
395 |
+
``a != 0``, either raise NonElementaryIntegralException, in which case the
|
396 |
+
equation a*Dq + b*q == c has no solution of degree at most ``n`` in
|
397 |
+
k[t], or return the tuple (B, C, m, alpha, beta) such that B, C,
|
398 |
+
alpha, beta in k[t], m in ZZ, and any solution q in k[t] of degree
|
399 |
+
at most n of a*Dq + b*q == c must be of the form
|
400 |
+
q == alpha*h + beta, where h in k[t], deg(h) <= m, and Dh + B*h == C.
|
401 |
+
|
402 |
+
This constitutes step 4 of the outline given in the rde.py docstring.
|
403 |
+
"""
|
404 |
+
zero = Poly(0, DE.t)
|
405 |
+
|
406 |
+
alpha = Poly(1, DE.t)
|
407 |
+
beta = Poly(0, DE.t)
|
408 |
+
|
409 |
+
while True:
|
410 |
+
if c.is_zero:
|
411 |
+
return (zero, zero, 0, zero, beta) # -1 is more to the point
|
412 |
+
if (n < 0) is True:
|
413 |
+
raise NonElementaryIntegralException
|
414 |
+
|
415 |
+
g = a.gcd(b)
|
416 |
+
if not c.rem(g).is_zero: # g does not divide c
|
417 |
+
raise NonElementaryIntegralException
|
418 |
+
|
419 |
+
a, b, c = a.quo(g), b.quo(g), c.quo(g)
|
420 |
+
|
421 |
+
if a.degree(DE.t) == 0:
|
422 |
+
b = b.to_field().quo(a)
|
423 |
+
c = c.to_field().quo(a)
|
424 |
+
return (b, c, n, alpha, beta)
|
425 |
+
|
426 |
+
r, z = gcdex_diophantine(b, a, c)
|
427 |
+
b += derivation(a, DE)
|
428 |
+
c = z - derivation(r, DE)
|
429 |
+
n -= a.degree(DE.t)
|
430 |
+
|
431 |
+
beta += alpha * r
|
432 |
+
alpha *= a
|
433 |
+
|
434 |
+
def no_cancel_b_large(b, c, n, DE):
|
435 |
+
"""
|
436 |
+
Poly Risch Differential Equation - No cancellation: deg(b) large enough.
|
437 |
+
|
438 |
+
Explanation
|
439 |
+
===========
|
440 |
+
|
441 |
+
Given a derivation D on k[t], ``n`` either an integer or +oo, and ``b``,``c``
|
442 |
+
in k[t] with ``b != 0`` and either D == d/dt or
|
443 |
+
deg(b) > max(0, deg(D) - 1), either raise NonElementaryIntegralException, in
|
444 |
+
which case the equation ``Dq + b*q == c`` has no solution of degree at
|
445 |
+
most n in k[t], or a solution q in k[t] of this equation with
|
446 |
+
``deg(q) < n``.
|
447 |
+
"""
|
448 |
+
q = Poly(0, DE.t)
|
449 |
+
|
450 |
+
while not c.is_zero:
|
451 |
+
m = c.degree(DE.t) - b.degree(DE.t)
|
452 |
+
if not 0 <= m <= n: # n < 0 or m < 0 or m > n
|
453 |
+
raise NonElementaryIntegralException
|
454 |
+
|
455 |
+
p = Poly(c.as_poly(DE.t).LC()/b.as_poly(DE.t).LC()*DE.t**m, DE.t,
|
456 |
+
expand=False)
|
457 |
+
q = q + p
|
458 |
+
n = m - 1
|
459 |
+
c = c - derivation(p, DE) - b*p
|
460 |
+
|
461 |
+
return q
|
462 |
+
|
463 |
+
|
464 |
+
def no_cancel_b_small(b, c, n, DE):
|
465 |
+
"""
|
466 |
+
Poly Risch Differential Equation - No cancellation: deg(b) small enough.
|
467 |
+
|
468 |
+
Explanation
|
469 |
+
===========
|
470 |
+
|
471 |
+
Given a derivation D on k[t], ``n`` either an integer or +oo, and ``b``,``c``
|
472 |
+
in k[t] with deg(b) < deg(D) - 1 and either D == d/dt or
|
473 |
+
deg(D) >= 2, either raise NonElementaryIntegralException, in which case the
|
474 |
+
equation Dq + b*q == c has no solution of degree at most n in k[t],
|
475 |
+
or a solution q in k[t] of this equation with deg(q) <= n, or the
|
476 |
+
tuple (h, b0, c0) such that h in k[t], b0, c0, in k, and for any
|
477 |
+
solution q in k[t] of degree at most n of Dq + bq == c, y == q - h
|
478 |
+
is a solution in k of Dy + b0*y == c0.
|
479 |
+
"""
|
480 |
+
q = Poly(0, DE.t)
|
481 |
+
|
482 |
+
while not c.is_zero:
|
483 |
+
if n == 0:
|
484 |
+
m = 0
|
485 |
+
else:
|
486 |
+
m = c.degree(DE.t) - DE.d.degree(DE.t) + 1
|
487 |
+
|
488 |
+
if not 0 <= m <= n: # n < 0 or m < 0 or m > n
|
489 |
+
raise NonElementaryIntegralException
|
490 |
+
|
491 |
+
if m > 0:
|
492 |
+
p = Poly(c.as_poly(DE.t).LC()/(m*DE.d.as_poly(DE.t).LC())*DE.t**m,
|
493 |
+
DE.t, expand=False)
|
494 |
+
else:
|
495 |
+
if b.degree(DE.t) != c.degree(DE.t):
|
496 |
+
raise NonElementaryIntegralException
|
497 |
+
if b.degree(DE.t) == 0:
|
498 |
+
return (q, b.as_poly(DE.T[DE.level - 1]),
|
499 |
+
c.as_poly(DE.T[DE.level - 1]))
|
500 |
+
p = Poly(c.as_poly(DE.t).LC()/b.as_poly(DE.t).LC(), DE.t,
|
501 |
+
expand=False)
|
502 |
+
|
503 |
+
q = q + p
|
504 |
+
n = m - 1
|
505 |
+
c = c - derivation(p, DE) - b*p
|
506 |
+
|
507 |
+
return q
|
508 |
+
|
509 |
+
|
510 |
+
# TODO: better name for this function
|
511 |
+
def no_cancel_equal(b, c, n, DE):
|
512 |
+
"""
|
513 |
+
Poly Risch Differential Equation - No cancellation: deg(b) == deg(D) - 1
|
514 |
+
|
515 |
+
Explanation
|
516 |
+
===========
|
517 |
+
|
518 |
+
Given a derivation D on k[t] with deg(D) >= 2, n either an integer
|
519 |
+
or +oo, and b, c in k[t] with deg(b) == deg(D) - 1, either raise
|
520 |
+
NonElementaryIntegralException, in which case the equation Dq + b*q == c has
|
521 |
+
no solution of degree at most n in k[t], or a solution q in k[t] of
|
522 |
+
this equation with deg(q) <= n, or the tuple (h, m, C) such that h
|
523 |
+
in k[t], m in ZZ, and C in k[t], and for any solution q in k[t] of
|
524 |
+
degree at most n of Dq + b*q == c, y == q - h is a solution in k[t]
|
525 |
+
of degree at most m of Dy + b*y == C.
|
526 |
+
"""
|
527 |
+
q = Poly(0, DE.t)
|
528 |
+
lc = cancel(-b.as_poly(DE.t).LC()/DE.d.as_poly(DE.t).LC())
|
529 |
+
if lc.is_Integer and lc.is_positive:
|
530 |
+
M = lc
|
531 |
+
else:
|
532 |
+
M = -1
|
533 |
+
|
534 |
+
while not c.is_zero:
|
535 |
+
m = max(M, c.degree(DE.t) - DE.d.degree(DE.t) + 1)
|
536 |
+
|
537 |
+
if not 0 <= m <= n: # n < 0 or m < 0 or m > n
|
538 |
+
raise NonElementaryIntegralException
|
539 |
+
|
540 |
+
u = cancel(m*DE.d.as_poly(DE.t).LC() + b.as_poly(DE.t).LC())
|
541 |
+
if u.is_zero:
|
542 |
+
return (q, m, c)
|
543 |
+
if m > 0:
|
544 |
+
p = Poly(c.as_poly(DE.t).LC()/u*DE.t**m, DE.t, expand=False)
|
545 |
+
else:
|
546 |
+
if c.degree(DE.t) != DE.d.degree(DE.t) - 1:
|
547 |
+
raise NonElementaryIntegralException
|
548 |
+
else:
|
549 |
+
p = c.as_poly(DE.t).LC()/b.as_poly(DE.t).LC()
|
550 |
+
|
551 |
+
q = q + p
|
552 |
+
n = m - 1
|
553 |
+
c = c - derivation(p, DE) - b*p
|
554 |
+
|
555 |
+
return q
|
556 |
+
|
557 |
+
|
558 |
+
def cancel_primitive(b, c, n, DE):
|
559 |
+
"""
|
560 |
+
Poly Risch Differential Equation - Cancellation: Primitive case.
|
561 |
+
|
562 |
+
Explanation
|
563 |
+
===========
|
564 |
+
|
565 |
+
Given a derivation D on k[t], n either an integer or +oo, ``b`` in k, and
|
566 |
+
``c`` in k[t] with Dt in k and ``b != 0``, either raise
|
567 |
+
NonElementaryIntegralException, in which case the equation Dq + b*q == c
|
568 |
+
has no solution of degree at most n in k[t], or a solution q in k[t] of
|
569 |
+
this equation with deg(q) <= n.
|
570 |
+
"""
|
571 |
+
# Delayed imports
|
572 |
+
from .prde import is_log_deriv_k_t_radical_in_field
|
573 |
+
with DecrementLevel(DE):
|
574 |
+
ba, bd = frac_in(b, DE.t)
|
575 |
+
A = is_log_deriv_k_t_radical_in_field(ba, bd, DE)
|
576 |
+
if A is not None:
|
577 |
+
n, z = A
|
578 |
+
if n == 1: # b == Dz/z
|
579 |
+
raise NotImplementedError("is_deriv_in_field() is required to "
|
580 |
+
" solve this problem.")
|
581 |
+
# if z*c == Dp for p in k[t] and deg(p) <= n:
|
582 |
+
# return p/z
|
583 |
+
# else:
|
584 |
+
# raise NonElementaryIntegralException
|
585 |
+
|
586 |
+
if c.is_zero:
|
587 |
+
return c # return 0
|
588 |
+
|
589 |
+
if n < c.degree(DE.t):
|
590 |
+
raise NonElementaryIntegralException
|
591 |
+
|
592 |
+
q = Poly(0, DE.t)
|
593 |
+
while not c.is_zero:
|
594 |
+
m = c.degree(DE.t)
|
595 |
+
if n < m:
|
596 |
+
raise NonElementaryIntegralException
|
597 |
+
with DecrementLevel(DE):
|
598 |
+
a2a, a2d = frac_in(c.LC(), DE.t)
|
599 |
+
sa, sd = rischDE(ba, bd, a2a, a2d, DE)
|
600 |
+
stm = Poly(sa.as_expr()/sd.as_expr()*DE.t**m, DE.t, expand=False)
|
601 |
+
q += stm
|
602 |
+
n = m - 1
|
603 |
+
c -= b*stm + derivation(stm, DE)
|
604 |
+
|
605 |
+
return q
|
606 |
+
|
607 |
+
|
608 |
+
def cancel_exp(b, c, n, DE):
|
609 |
+
"""
|
610 |
+
Poly Risch Differential Equation - Cancellation: Hyperexponential case.
|
611 |
+
|
612 |
+
Explanation
|
613 |
+
===========
|
614 |
+
|
615 |
+
Given a derivation D on k[t], n either an integer or +oo, ``b`` in k, and
|
616 |
+
``c`` in k[t] with Dt/t in k and ``b != 0``, either raise
|
617 |
+
NonElementaryIntegralException, in which case the equation Dq + b*q == c
|
618 |
+
has no solution of degree at most n in k[t], or a solution q in k[t] of
|
619 |
+
this equation with deg(q) <= n.
|
620 |
+
"""
|
621 |
+
from .prde import parametric_log_deriv
|
622 |
+
eta = DE.d.quo(Poly(DE.t, DE.t)).as_expr()
|
623 |
+
|
624 |
+
with DecrementLevel(DE):
|
625 |
+
etaa, etad = frac_in(eta, DE.t)
|
626 |
+
ba, bd = frac_in(b, DE.t)
|
627 |
+
A = parametric_log_deriv(ba, bd, etaa, etad, DE)
|
628 |
+
if A is not None:
|
629 |
+
a, m, z = A
|
630 |
+
if a == 1:
|
631 |
+
raise NotImplementedError("is_deriv_in_field() is required to "
|
632 |
+
"solve this problem.")
|
633 |
+
# if c*z*t**m == Dp for p in k<t> and q = p/(z*t**m) in k[t] and
|
634 |
+
# deg(q) <= n:
|
635 |
+
# return q
|
636 |
+
# else:
|
637 |
+
# raise NonElementaryIntegralException
|
638 |
+
|
639 |
+
if c.is_zero:
|
640 |
+
return c # return 0
|
641 |
+
|
642 |
+
if n < c.degree(DE.t):
|
643 |
+
raise NonElementaryIntegralException
|
644 |
+
|
645 |
+
q = Poly(0, DE.t)
|
646 |
+
while not c.is_zero:
|
647 |
+
m = c.degree(DE.t)
|
648 |
+
if n < m:
|
649 |
+
raise NonElementaryIntegralException
|
650 |
+
# a1 = b + m*Dt/t
|
651 |
+
a1 = b.as_expr()
|
652 |
+
with DecrementLevel(DE):
|
653 |
+
# TODO: Write a dummy function that does this idiom
|
654 |
+
a1a, a1d = frac_in(a1, DE.t)
|
655 |
+
a1a = a1a*etad + etaa*a1d*Poly(m, DE.t)
|
656 |
+
a1d = a1d*etad
|
657 |
+
|
658 |
+
a2a, a2d = frac_in(c.LC(), DE.t)
|
659 |
+
|
660 |
+
sa, sd = rischDE(a1a, a1d, a2a, a2d, DE)
|
661 |
+
stm = Poly(sa.as_expr()/sd.as_expr()*DE.t**m, DE.t, expand=False)
|
662 |
+
q += stm
|
663 |
+
n = m - 1
|
664 |
+
c -= b*stm + derivation(stm, DE) # deg(c) becomes smaller
|
665 |
+
return q
|
666 |
+
|
667 |
+
|
668 |
+
def solve_poly_rde(b, cQ, n, DE, parametric=False):
|
669 |
+
"""
|
670 |
+
Solve a Polynomial Risch Differential Equation with degree bound ``n``.
|
671 |
+
|
672 |
+
This constitutes step 4 of the outline given in the rde.py docstring.
|
673 |
+
|
674 |
+
For parametric=False, cQ is c, a Poly; for parametric=True, cQ is Q ==
|
675 |
+
[q1, ..., qm], a list of Polys.
|
676 |
+
"""
|
677 |
+
# No cancellation
|
678 |
+
if not b.is_zero and (DE.case == 'base' or
|
679 |
+
b.degree(DE.t) > max(0, DE.d.degree(DE.t) - 1)):
|
680 |
+
|
681 |
+
if parametric:
|
682 |
+
# Delayed imports
|
683 |
+
from .prde import prde_no_cancel_b_large
|
684 |
+
return prde_no_cancel_b_large(b, cQ, n, DE)
|
685 |
+
return no_cancel_b_large(b, cQ, n, DE)
|
686 |
+
|
687 |
+
elif (b.is_zero or b.degree(DE.t) < DE.d.degree(DE.t) - 1) and \
|
688 |
+
(DE.case == 'base' or DE.d.degree(DE.t) >= 2):
|
689 |
+
|
690 |
+
if parametric:
|
691 |
+
from .prde import prde_no_cancel_b_small
|
692 |
+
return prde_no_cancel_b_small(b, cQ, n, DE)
|
693 |
+
|
694 |
+
R = no_cancel_b_small(b, cQ, n, DE)
|
695 |
+
|
696 |
+
if isinstance(R, Poly):
|
697 |
+
return R
|
698 |
+
else:
|
699 |
+
# XXX: Might k be a field? (pg. 209)
|
700 |
+
h, b0, c0 = R
|
701 |
+
with DecrementLevel(DE):
|
702 |
+
b0, c0 = b0.as_poly(DE.t), c0.as_poly(DE.t)
|
703 |
+
if b0 is None: # See above comment
|
704 |
+
raise ValueError("b0 should be a non-Null value")
|
705 |
+
if c0 is None:
|
706 |
+
raise ValueError("c0 should be a non-Null value")
|
707 |
+
y = solve_poly_rde(b0, c0, n, DE).as_poly(DE.t)
|
708 |
+
return h + y
|
709 |
+
|
710 |
+
elif DE.d.degree(DE.t) >= 2 and b.degree(DE.t) == DE.d.degree(DE.t) - 1 and \
|
711 |
+
n > -b.as_poly(DE.t).LC()/DE.d.as_poly(DE.t).LC():
|
712 |
+
|
713 |
+
# TODO: Is this check necessary, and if so, what should it do if it fails?
|
714 |
+
# b comes from the first element returned from spde()
|
715 |
+
if not b.as_poly(DE.t).LC().is_number:
|
716 |
+
raise TypeError("Result should be a number")
|
717 |
+
|
718 |
+
if parametric:
|
719 |
+
raise NotImplementedError("prde_no_cancel_b_equal() is not yet "
|
720 |
+
"implemented.")
|
721 |
+
|
722 |
+
R = no_cancel_equal(b, cQ, n, DE)
|
723 |
+
|
724 |
+
if isinstance(R, Poly):
|
725 |
+
return R
|
726 |
+
else:
|
727 |
+
h, m, C = R
|
728 |
+
# XXX: Or should it be rischDE()?
|
729 |
+
y = solve_poly_rde(b, C, m, DE)
|
730 |
+
return h + y
|
731 |
+
|
732 |
+
else:
|
733 |
+
# Cancellation
|
734 |
+
if b.is_zero:
|
735 |
+
raise NotImplementedError("Remaining cases for Poly (P)RDE are "
|
736 |
+
"not yet implemented (is_deriv_in_field() required).")
|
737 |
+
else:
|
738 |
+
if DE.case == 'exp':
|
739 |
+
if parametric:
|
740 |
+
raise NotImplementedError("Parametric RDE cancellation "
|
741 |
+
"hyperexponential case is not yet implemented.")
|
742 |
+
return cancel_exp(b, cQ, n, DE)
|
743 |
+
|
744 |
+
elif DE.case == 'primitive':
|
745 |
+
if parametric:
|
746 |
+
raise NotImplementedError("Parametric RDE cancellation "
|
747 |
+
"primitive case is not yet implemented.")
|
748 |
+
return cancel_primitive(b, cQ, n, DE)
|
749 |
+
|
750 |
+
else:
|
751 |
+
raise NotImplementedError("Other Poly (P)RDE cancellation "
|
752 |
+
"cases are not yet implemented (%s)." % DE.case)
|
753 |
+
|
754 |
+
if parametric:
|
755 |
+
raise NotImplementedError("Remaining cases for Poly PRDE not yet "
|
756 |
+
"implemented.")
|
757 |
+
raise NotImplementedError("Remaining cases for Poly RDE not yet "
|
758 |
+
"implemented.")
|
759 |
+
|
760 |
+
|
761 |
+
def rischDE(fa, fd, ga, gd, DE):
|
762 |
+
"""
|
763 |
+
Solve a Risch Differential Equation: Dy + f*y == g.
|
764 |
+
|
765 |
+
Explanation
|
766 |
+
===========
|
767 |
+
|
768 |
+
See the outline in the docstring of rde.py for more information
|
769 |
+
about the procedure used. Either raise NonElementaryIntegralException, in
|
770 |
+
which case there is no solution y in the given differential field,
|
771 |
+
or return y in k(t) satisfying Dy + f*y == g, or raise
|
772 |
+
NotImplementedError, in which case, the algorithms necessary to
|
773 |
+
solve the given Risch Differential Equation have not yet been
|
774 |
+
implemented.
|
775 |
+
"""
|
776 |
+
_, (fa, fd) = weak_normalizer(fa, fd, DE)
|
777 |
+
a, (ba, bd), (ca, cd), hn = normal_denom(fa, fd, ga, gd, DE)
|
778 |
+
A, B, C, hs = special_denom(a, ba, bd, ca, cd, DE)
|
779 |
+
try:
|
780 |
+
# Until this is fully implemented, use oo. Note that this will almost
|
781 |
+
# certainly cause non-termination in spde() (unless A == 1), and
|
782 |
+
# *might* lead to non-termination in the next step for a nonelementary
|
783 |
+
# integral (I don't know for certain yet). Fortunately, spde() is
|
784 |
+
# currently written recursively, so this will just give
|
785 |
+
# RuntimeError: maximum recursion depth exceeded.
|
786 |
+
n = bound_degree(A, B, C, DE)
|
787 |
+
except NotImplementedError:
|
788 |
+
# Useful for debugging:
|
789 |
+
# import warnings
|
790 |
+
# warnings.warn("rischDE: Proceeding with n = oo; may cause "
|
791 |
+
# "non-termination.")
|
792 |
+
n = oo
|
793 |
+
|
794 |
+
B, C, m, alpha, beta = spde(A, B, C, n, DE)
|
795 |
+
if C.is_zero:
|
796 |
+
y = C
|
797 |
+
else:
|
798 |
+
y = solve_poly_rde(B, C, m, DE)
|
799 |
+
|
800 |
+
return (alpha*y + beta, hn*hs)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/risch.py
ADDED
@@ -0,0 +1,1858 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
The Risch Algorithm for transcendental function integration.
|
3 |
+
|
4 |
+
The core algorithms for the Risch algorithm are here. The subproblem
|
5 |
+
algorithms are in the rde.py and prde.py files for the Risch
|
6 |
+
Differential Equation solver and the parametric problems solvers,
|
7 |
+
respectively. All important information concerning the differential extension
|
8 |
+
for an integrand is stored in a DifferentialExtension object, which in the code
|
9 |
+
is usually called DE. Throughout the code and Inside the DifferentialExtension
|
10 |
+
object, the conventions/attribute names are that the base domain is QQ and each
|
11 |
+
differential extension is x, t0, t1, ..., tn-1 = DE.t. DE.x is the variable of
|
12 |
+
integration (Dx == 1), DE.D is a list of the derivatives of
|
13 |
+
x, t1, t2, ..., tn-1 = t, DE.T is the list [x, t1, t2, ..., tn-1], DE.t is the
|
14 |
+
outer-most variable of the differential extension at the given level (the level
|
15 |
+
can be adjusted using DE.increment_level() and DE.decrement_level()),
|
16 |
+
k is the field C(x, t0, ..., tn-2), where C is the constant field. The
|
17 |
+
numerator of a fraction is denoted by a and the denominator by
|
18 |
+
d. If the fraction is named f, fa == numer(f) and fd == denom(f).
|
19 |
+
Fractions are returned as tuples (fa, fd). DE.d and DE.t are used to
|
20 |
+
represent the topmost derivation and extension variable, respectively.
|
21 |
+
The docstring of a function signifies whether an argument is in k[t], in
|
22 |
+
which case it will just return a Poly in t, or in k(t), in which case it
|
23 |
+
will return the fraction (fa, fd). Other variable names probably come
|
24 |
+
from the names used in Bronstein's book.
|
25 |
+
"""
|
26 |
+
from types import GeneratorType
|
27 |
+
from functools import reduce
|
28 |
+
|
29 |
+
from sympy.core.function import Lambda
|
30 |
+
from sympy.core.mul import Mul
|
31 |
+
from sympy.core.numbers import ilcm, I, oo
|
32 |
+
from sympy.core.power import Pow
|
33 |
+
from sympy.core.relational import Ne
|
34 |
+
from sympy.core.singleton import S
|
35 |
+
from sympy.core.sorting import ordered, default_sort_key
|
36 |
+
from sympy.core.symbol import Dummy, Symbol
|
37 |
+
from sympy.functions.elementary.exponential import log, exp
|
38 |
+
from sympy.functions.elementary.hyperbolic import (cosh, coth, sinh,
|
39 |
+
tanh)
|
40 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
41 |
+
from sympy.functions.elementary.trigonometric import (atan, sin, cos,
|
42 |
+
tan, acot, cot, asin, acos)
|
43 |
+
from .integrals import integrate, Integral
|
44 |
+
from .heurisch import _symbols
|
45 |
+
from sympy.polys.polyerrors import DomainError, PolynomialError
|
46 |
+
from sympy.polys.polytools import (real_roots, cancel, Poly, gcd,
|
47 |
+
reduced)
|
48 |
+
from sympy.polys.rootoftools import RootSum
|
49 |
+
from sympy.utilities.iterables import numbered_symbols
|
50 |
+
|
51 |
+
|
52 |
+
def integer_powers(exprs):
|
53 |
+
"""
|
54 |
+
Rewrites a list of expressions as integer multiples of each other.
|
55 |
+
|
56 |
+
Explanation
|
57 |
+
===========
|
58 |
+
|
59 |
+
For example, if you have [x, x/2, x**2 + 1, 2*x/3], then you can rewrite
|
60 |
+
this as [(x/6) * 6, (x/6) * 3, (x**2 + 1) * 1, (x/6) * 4]. This is useful
|
61 |
+
in the Risch integration algorithm, where we must write exp(x) + exp(x/2)
|
62 |
+
as (exp(x/2))**2 + exp(x/2), but not as exp(x) + sqrt(exp(x)) (this is
|
63 |
+
because only the transcendental case is implemented and we therefore cannot
|
64 |
+
integrate algebraic extensions). The integer multiples returned by this
|
65 |
+
function for each term are the smallest possible (their content equals 1).
|
66 |
+
|
67 |
+
Returns a list of tuples where the first element is the base term and the
|
68 |
+
second element is a list of `(item, factor)` terms, where `factor` is the
|
69 |
+
integer multiplicative factor that must multiply the base term to obtain
|
70 |
+
the original item.
|
71 |
+
|
72 |
+
The easiest way to understand this is to look at an example:
|
73 |
+
|
74 |
+
>>> from sympy.abc import x
|
75 |
+
>>> from sympy.integrals.risch import integer_powers
|
76 |
+
>>> integer_powers([x, x/2, x**2 + 1, 2*x/3])
|
77 |
+
[(x/6, [(x, 6), (x/2, 3), (2*x/3, 4)]), (x**2 + 1, [(x**2 + 1, 1)])]
|
78 |
+
|
79 |
+
We can see how this relates to the example at the beginning of the
|
80 |
+
docstring. It chose x/6 as the first base term. Then, x can be written as
|
81 |
+
(x/2) * 2, so we get (0, 2), and so on. Now only element (x**2 + 1)
|
82 |
+
remains, and there are no other terms that can be written as a rational
|
83 |
+
multiple of that, so we get that it can be written as (x**2 + 1) * 1.
|
84 |
+
|
85 |
+
"""
|
86 |
+
# Here is the strategy:
|
87 |
+
|
88 |
+
# First, go through each term and determine if it can be rewritten as a
|
89 |
+
# rational multiple of any of the terms gathered so far.
|
90 |
+
# cancel(a/b).is_Rational is sufficient for this. If it is a multiple, we
|
91 |
+
# add its multiple to the dictionary.
|
92 |
+
|
93 |
+
terms = {}
|
94 |
+
for term in exprs:
|
95 |
+
for trm, trm_list in terms.items():
|
96 |
+
a = cancel(term/trm)
|
97 |
+
if a.is_Rational:
|
98 |
+
trm_list.append((term, a))
|
99 |
+
break
|
100 |
+
else:
|
101 |
+
terms[term] = [(term, S.One)]
|
102 |
+
|
103 |
+
# After we have done this, we have all the like terms together, so we just
|
104 |
+
# need to find a common denominator so that we can get the base term and
|
105 |
+
# integer multiples such that each term can be written as an integer
|
106 |
+
# multiple of the base term, and the content of the integers is 1.
|
107 |
+
|
108 |
+
newterms = {}
|
109 |
+
for term, term_list in terms.items():
|
110 |
+
common_denom = reduce(ilcm, [i.as_numer_denom()[1] for _, i in
|
111 |
+
term_list])
|
112 |
+
newterm = term/common_denom
|
113 |
+
newmults = [(i, j*common_denom) for i, j in term_list]
|
114 |
+
newterms[newterm] = newmults
|
115 |
+
|
116 |
+
return sorted(iter(newterms.items()), key=lambda item: item[0].sort_key())
|
117 |
+
|
118 |
+
|
119 |
+
class DifferentialExtension:
|
120 |
+
"""
|
121 |
+
A container for all the information relating to a differential extension.
|
122 |
+
|
123 |
+
Explanation
|
124 |
+
===========
|
125 |
+
|
126 |
+
The attributes of this object are (see also the docstring of __init__):
|
127 |
+
|
128 |
+
- f: The original (Expr) integrand.
|
129 |
+
- x: The variable of integration.
|
130 |
+
- T: List of variables in the extension.
|
131 |
+
- D: List of derivations in the extension; corresponds to the elements of T.
|
132 |
+
- fa: Poly of the numerator of the integrand.
|
133 |
+
- fd: Poly of the denominator of the integrand.
|
134 |
+
- Tfuncs: Lambda() representations of each element of T (except for x).
|
135 |
+
For back-substitution after integration.
|
136 |
+
- backsubs: A (possibly empty) list of further substitutions to be made on
|
137 |
+
the final integral to make it look more like the integrand.
|
138 |
+
- exts:
|
139 |
+
- extargs:
|
140 |
+
- cases: List of string representations of the cases of T.
|
141 |
+
- t: The top level extension variable, as defined by the current level
|
142 |
+
(see level below).
|
143 |
+
- d: The top level extension derivation, as defined by the current
|
144 |
+
derivation (see level below).
|
145 |
+
- case: The string representation of the case of self.d.
|
146 |
+
(Note that self.T and self.D will always contain the complete extension,
|
147 |
+
regardless of the level. Therefore, you should ALWAYS use DE.t and DE.d
|
148 |
+
instead of DE.T[-1] and DE.D[-1]. If you want to have a list of the
|
149 |
+
derivations or variables only up to the current level, use
|
150 |
+
DE.D[:len(DE.D) + DE.level + 1] and DE.T[:len(DE.T) + DE.level + 1]. Note
|
151 |
+
that, in particular, the derivation() function does this.)
|
152 |
+
|
153 |
+
The following are also attributes, but will probably not be useful other
|
154 |
+
than in internal use:
|
155 |
+
- newf: Expr form of fa/fd.
|
156 |
+
- level: The number (between -1 and -len(self.T)) such that
|
157 |
+
self.T[self.level] == self.t and self.D[self.level] == self.d.
|
158 |
+
Use the methods self.increment_level() and self.decrement_level() to change
|
159 |
+
the current level.
|
160 |
+
"""
|
161 |
+
# __slots__ is defined mainly so we can iterate over all the attributes
|
162 |
+
# of the class easily (the memory use doesn't matter too much, since we
|
163 |
+
# only create one DifferentialExtension per integration). Also, it's nice
|
164 |
+
# to have a safeguard when debugging.
|
165 |
+
__slots__ = ('f', 'x', 'T', 'D', 'fa', 'fd', 'Tfuncs', 'backsubs',
|
166 |
+
'exts', 'extargs', 'cases', 'case', 't', 'd', 'newf', 'level',
|
167 |
+
'ts', 'dummy')
|
168 |
+
|
169 |
+
def __init__(self, f=None, x=None, handle_first='log', dummy=False, extension=None, rewrite_complex=None):
|
170 |
+
"""
|
171 |
+
Tries to build a transcendental extension tower from ``f`` with respect to ``x``.
|
172 |
+
|
173 |
+
Explanation
|
174 |
+
===========
|
175 |
+
|
176 |
+
If it is successful, creates a DifferentialExtension object with, among
|
177 |
+
others, the attributes fa, fd, D, T, Tfuncs, and backsubs such that
|
178 |
+
fa and fd are Polys in T[-1] with rational coefficients in T[:-1],
|
179 |
+
fa/fd == f, and D[i] is a Poly in T[i] with rational coefficients in
|
180 |
+
T[:i] representing the derivative of T[i] for each i from 1 to len(T).
|
181 |
+
Tfuncs is a list of Lambda objects for back replacing the functions
|
182 |
+
after integrating. Lambda() is only used (instead of lambda) to make
|
183 |
+
them easier to test and debug. Note that Tfuncs corresponds to the
|
184 |
+
elements of T, except for T[0] == x, but they should be back-substituted
|
185 |
+
in reverse order. backsubs is a (possibly empty) back-substitution list
|
186 |
+
that should be applied on the completed integral to make it look more
|
187 |
+
like the original integrand.
|
188 |
+
|
189 |
+
If it is unsuccessful, it raises NotImplementedError.
|
190 |
+
|
191 |
+
You can also create an object by manually setting the attributes as a
|
192 |
+
dictionary to the extension keyword argument. You must include at least
|
193 |
+
D. Warning, any attribute that is not given will be set to None. The
|
194 |
+
attributes T, t, d, cases, case, x, and level are set automatically and
|
195 |
+
do not need to be given. The functions in the Risch Algorithm will NOT
|
196 |
+
check to see if an attribute is None before using it. This also does not
|
197 |
+
check to see if the extension is valid (non-algebraic) or even if it is
|
198 |
+
self-consistent. Therefore, this should only be used for
|
199 |
+
testing/debugging purposes.
|
200 |
+
"""
|
201 |
+
# XXX: If you need to debug this function, set the break point here
|
202 |
+
|
203 |
+
if extension:
|
204 |
+
if 'D' not in extension:
|
205 |
+
raise ValueError("At least the key D must be included with "
|
206 |
+
"the extension flag to DifferentialExtension.")
|
207 |
+
for attr in extension:
|
208 |
+
setattr(self, attr, extension[attr])
|
209 |
+
|
210 |
+
self._auto_attrs()
|
211 |
+
|
212 |
+
return
|
213 |
+
elif f is None or x is None:
|
214 |
+
raise ValueError("Either both f and x or a manual extension must "
|
215 |
+
"be given.")
|
216 |
+
|
217 |
+
if handle_first not in ('log', 'exp'):
|
218 |
+
raise ValueError("handle_first must be 'log' or 'exp', not %s." %
|
219 |
+
str(handle_first))
|
220 |
+
|
221 |
+
# f will be the original function, self.f might change if we reset
|
222 |
+
# (e.g., we pull out a constant from an exponential)
|
223 |
+
self.f = f
|
224 |
+
self.x = x
|
225 |
+
# setting the default value 'dummy'
|
226 |
+
self.dummy = dummy
|
227 |
+
self.reset()
|
228 |
+
exp_new_extension, log_new_extension = True, True
|
229 |
+
|
230 |
+
# case of 'automatic' choosing
|
231 |
+
if rewrite_complex is None:
|
232 |
+
rewrite_complex = I in self.f.atoms()
|
233 |
+
|
234 |
+
if rewrite_complex:
|
235 |
+
rewritables = {
|
236 |
+
(sin, cos, cot, tan, sinh, cosh, coth, tanh): exp,
|
237 |
+
(asin, acos, acot, atan): log,
|
238 |
+
}
|
239 |
+
# rewrite the trigonometric components
|
240 |
+
for candidates, rule in rewritables.items():
|
241 |
+
self.newf = self.newf.rewrite(candidates, rule)
|
242 |
+
self.newf = cancel(self.newf)
|
243 |
+
else:
|
244 |
+
if any(i.has(x) for i in self.f.atoms(sin, cos, tan, atan, asin, acos)):
|
245 |
+
raise NotImplementedError("Trigonometric extensions are not "
|
246 |
+
"supported (yet!)")
|
247 |
+
|
248 |
+
exps = set()
|
249 |
+
pows = set()
|
250 |
+
numpows = set()
|
251 |
+
sympows = set()
|
252 |
+
logs = set()
|
253 |
+
symlogs = set()
|
254 |
+
|
255 |
+
while True:
|
256 |
+
if self.newf.is_rational_function(*self.T):
|
257 |
+
break
|
258 |
+
|
259 |
+
if not exp_new_extension and not log_new_extension:
|
260 |
+
# We couldn't find a new extension on the last pass, so I guess
|
261 |
+
# we can't do it.
|
262 |
+
raise NotImplementedError("Couldn't find an elementary "
|
263 |
+
"transcendental extension for %s. Try using a " % str(f) +
|
264 |
+
"manual extension with the extension flag.")
|
265 |
+
|
266 |
+
exps, pows, numpows, sympows, log_new_extension = \
|
267 |
+
self._rewrite_exps_pows(exps, pows, numpows, sympows, log_new_extension)
|
268 |
+
|
269 |
+
logs, symlogs = self._rewrite_logs(logs, symlogs)
|
270 |
+
|
271 |
+
if handle_first == 'exp' or not log_new_extension:
|
272 |
+
exp_new_extension = self._exp_part(exps)
|
273 |
+
if exp_new_extension is None:
|
274 |
+
# reset and restart
|
275 |
+
self.f = self.newf
|
276 |
+
self.reset()
|
277 |
+
exp_new_extension = True
|
278 |
+
continue
|
279 |
+
|
280 |
+
if handle_first == 'log' or not exp_new_extension:
|
281 |
+
log_new_extension = self._log_part(logs)
|
282 |
+
|
283 |
+
self.fa, self.fd = frac_in(self.newf, self.t)
|
284 |
+
self._auto_attrs()
|
285 |
+
|
286 |
+
return
|
287 |
+
|
288 |
+
def __getattr__(self, attr):
|
289 |
+
# Avoid AttributeErrors when debugging
|
290 |
+
if attr not in self.__slots__:
|
291 |
+
raise AttributeError("%s has no attribute %s" % (repr(self), repr(attr)))
|
292 |
+
return None
|
293 |
+
|
294 |
+
def _rewrite_exps_pows(self, exps, pows, numpows,
|
295 |
+
sympows, log_new_extension):
|
296 |
+
"""
|
297 |
+
Rewrite exps/pows for better processing.
|
298 |
+
"""
|
299 |
+
from .prde import is_deriv_k
|
300 |
+
|
301 |
+
# Pre-preparsing.
|
302 |
+
#################
|
303 |
+
# Get all exp arguments, so we can avoid ahead of time doing
|
304 |
+
# something like t1 = exp(x), t2 = exp(x/2) == sqrt(t1).
|
305 |
+
|
306 |
+
# Things like sqrt(exp(x)) do not automatically simplify to
|
307 |
+
# exp(x/2), so they will be viewed as algebraic. The easiest way
|
308 |
+
# to handle this is to convert all instances of exp(a)**Rational
|
309 |
+
# to exp(Rational*a) before doing anything else. Note that the
|
310 |
+
# _exp_part code can generate terms of this form, so we do need to
|
311 |
+
# do this at each pass (or else modify it to not do that).
|
312 |
+
|
313 |
+
ratpows = [i for i in self.newf.atoms(Pow)
|
314 |
+
if (isinstance(i.base, exp) and i.exp.is_Rational)]
|
315 |
+
|
316 |
+
ratpows_repl = [
|
317 |
+
(i, i.base.base**(i.exp*i.base.exp)) for i in ratpows]
|
318 |
+
self.backsubs += [(j, i) for i, j in ratpows_repl]
|
319 |
+
self.newf = self.newf.xreplace(dict(ratpows_repl))
|
320 |
+
|
321 |
+
# To make the process deterministic, the args are sorted
|
322 |
+
# so that functions with smaller op-counts are processed first.
|
323 |
+
# Ties are broken with the default_sort_key.
|
324 |
+
|
325 |
+
# XXX Although the method is deterministic no additional work
|
326 |
+
# has been done to guarantee that the simplest solution is
|
327 |
+
# returned and that it would be affected be using different
|
328 |
+
# variables. Though it is possible that this is the case
|
329 |
+
# one should know that it has not been done intentionally, so
|
330 |
+
# further improvements may be possible.
|
331 |
+
|
332 |
+
# TODO: This probably doesn't need to be completely recomputed at
|
333 |
+
# each pass.
|
334 |
+
exps = update_sets(exps, self.newf.atoms(exp),
|
335 |
+
lambda i: i.exp.is_rational_function(*self.T) and
|
336 |
+
i.exp.has(*self.T))
|
337 |
+
pows = update_sets(pows, self.newf.atoms(Pow),
|
338 |
+
lambda i: i.exp.is_rational_function(*self.T) and
|
339 |
+
i.exp.has(*self.T))
|
340 |
+
numpows = update_sets(numpows, set(pows),
|
341 |
+
lambda i: not i.base.has(*self.T))
|
342 |
+
sympows = update_sets(sympows, set(pows) - set(numpows),
|
343 |
+
lambda i: i.base.is_rational_function(*self.T) and
|
344 |
+
not i.exp.is_Integer)
|
345 |
+
|
346 |
+
# The easiest way to deal with non-base E powers is to convert them
|
347 |
+
# into base E, integrate, and then convert back.
|
348 |
+
for i in ordered(pows):
|
349 |
+
old = i
|
350 |
+
new = exp(i.exp*log(i.base))
|
351 |
+
# If exp is ever changed to automatically reduce exp(x*log(2))
|
352 |
+
# to 2**x, then this will break. The solution is to not change
|
353 |
+
# exp to do that :)
|
354 |
+
if i in sympows:
|
355 |
+
if i.exp.is_Rational:
|
356 |
+
raise NotImplementedError("Algebraic extensions are "
|
357 |
+
"not supported (%s)." % str(i))
|
358 |
+
# We can add a**b only if log(a) in the extension, because
|
359 |
+
# a**b == exp(b*log(a)).
|
360 |
+
basea, based = frac_in(i.base, self.t)
|
361 |
+
A = is_deriv_k(basea, based, self)
|
362 |
+
if A is None:
|
363 |
+
# Nonelementary monomial (so far)
|
364 |
+
|
365 |
+
# TODO: Would there ever be any benefit from just
|
366 |
+
# adding log(base) as a new monomial?
|
367 |
+
# ANSWER: Yes, otherwise we can't integrate x**x (or
|
368 |
+
# rather prove that it has no elementary integral)
|
369 |
+
# without first manually rewriting it as exp(x*log(x))
|
370 |
+
self.newf = self.newf.xreplace({old: new})
|
371 |
+
self.backsubs += [(new, old)]
|
372 |
+
log_new_extension = self._log_part([log(i.base)])
|
373 |
+
exps = update_sets(exps, self.newf.atoms(exp), lambda i:
|
374 |
+
i.exp.is_rational_function(*self.T) and i.exp.has(*self.T))
|
375 |
+
continue
|
376 |
+
ans, u, const = A
|
377 |
+
newterm = exp(i.exp*(log(const) + u))
|
378 |
+
# Under the current implementation, exp kills terms
|
379 |
+
# only if they are of the form a*log(x), where a is a
|
380 |
+
# Number. This case should have already been killed by the
|
381 |
+
# above tests. Again, if this changes to kill more than
|
382 |
+
# that, this will break, which maybe is a sign that you
|
383 |
+
# shouldn't be changing that. Actually, if anything, this
|
384 |
+
# auto-simplification should be removed. See
|
385 |
+
# https://groups.google.com/group/sympy/browse_thread/thread/a61d48235f16867f
|
386 |
+
|
387 |
+
self.newf = self.newf.xreplace({i: newterm})
|
388 |
+
|
389 |
+
elif i not in numpows:
|
390 |
+
continue
|
391 |
+
else:
|
392 |
+
# i in numpows
|
393 |
+
newterm = new
|
394 |
+
# TODO: Just put it in self.Tfuncs
|
395 |
+
self.backsubs.append((new, old))
|
396 |
+
self.newf = self.newf.xreplace({old: newterm})
|
397 |
+
exps.append(newterm)
|
398 |
+
|
399 |
+
return exps, pows, numpows, sympows, log_new_extension
|
400 |
+
|
401 |
+
def _rewrite_logs(self, logs, symlogs):
|
402 |
+
"""
|
403 |
+
Rewrite logs for better processing.
|
404 |
+
"""
|
405 |
+
atoms = self.newf.atoms(log)
|
406 |
+
logs = update_sets(logs, atoms,
|
407 |
+
lambda i: i.args[0].is_rational_function(*self.T) and
|
408 |
+
i.args[0].has(*self.T))
|
409 |
+
symlogs = update_sets(symlogs, atoms,
|
410 |
+
lambda i: i.has(*self.T) and i.args[0].is_Pow and
|
411 |
+
i.args[0].base.is_rational_function(*self.T) and
|
412 |
+
not i.args[0].exp.is_Integer)
|
413 |
+
|
414 |
+
# We can handle things like log(x**y) by converting it to y*log(x)
|
415 |
+
# This will fix not only symbolic exponents of the argument, but any
|
416 |
+
# non-Integer exponent, like log(sqrt(x)). The exponent can also
|
417 |
+
# depend on x, like log(x**x).
|
418 |
+
for i in ordered(symlogs):
|
419 |
+
# Unlike in the exponential case above, we do not ever
|
420 |
+
# potentially add new monomials (above we had to add log(a)).
|
421 |
+
# Therefore, there is no need to run any is_deriv functions
|
422 |
+
# here. Just convert log(a**b) to b*log(a) and let
|
423 |
+
# log_new_extension() handle it from there.
|
424 |
+
lbase = log(i.args[0].base)
|
425 |
+
logs.append(lbase)
|
426 |
+
new = i.args[0].exp*lbase
|
427 |
+
self.newf = self.newf.xreplace({i: new})
|
428 |
+
self.backsubs.append((new, i))
|
429 |
+
|
430 |
+
# remove any duplicates
|
431 |
+
logs = sorted(set(logs), key=default_sort_key)
|
432 |
+
|
433 |
+
return logs, symlogs
|
434 |
+
|
435 |
+
def _auto_attrs(self):
|
436 |
+
"""
|
437 |
+
Set attributes that are generated automatically.
|
438 |
+
"""
|
439 |
+
if not self.T:
|
440 |
+
# i.e., when using the extension flag and T isn't given
|
441 |
+
self.T = [i.gen for i in self.D]
|
442 |
+
if not self.x:
|
443 |
+
self.x = self.T[0]
|
444 |
+
self.cases = [get_case(d, t) for d, t in zip(self.D, self.T)]
|
445 |
+
self.level = -1
|
446 |
+
self.t = self.T[self.level]
|
447 |
+
self.d = self.D[self.level]
|
448 |
+
self.case = self.cases[self.level]
|
449 |
+
|
450 |
+
def _exp_part(self, exps):
|
451 |
+
"""
|
452 |
+
Try to build an exponential extension.
|
453 |
+
|
454 |
+
Returns
|
455 |
+
=======
|
456 |
+
|
457 |
+
Returns True if there was a new extension, False if there was no new
|
458 |
+
extension but it was able to rewrite the given exponentials in terms
|
459 |
+
of the existing extension, and None if the entire extension building
|
460 |
+
process should be restarted. If the process fails because there is no
|
461 |
+
way around an algebraic extension (e.g., exp(log(x)/2)), it will raise
|
462 |
+
NotImplementedError.
|
463 |
+
"""
|
464 |
+
from .prde import is_log_deriv_k_t_radical
|
465 |
+
new_extension = False
|
466 |
+
restart = False
|
467 |
+
expargs = [i.exp for i in exps]
|
468 |
+
ip = integer_powers(expargs)
|
469 |
+
for arg, others in ip:
|
470 |
+
# Minimize potential problems with algebraic substitution
|
471 |
+
others.sort(key=lambda i: i[1])
|
472 |
+
|
473 |
+
arga, argd = frac_in(arg, self.t)
|
474 |
+
A = is_log_deriv_k_t_radical(arga, argd, self)
|
475 |
+
|
476 |
+
if A is not None:
|
477 |
+
ans, u, n, const = A
|
478 |
+
# if n is 1 or -1, it's algebraic, but we can handle it
|
479 |
+
if n == -1:
|
480 |
+
# This probably will never happen, because
|
481 |
+
# Rational.as_numer_denom() returns the negative term in
|
482 |
+
# the numerator. But in case that changes, reduce it to
|
483 |
+
# n == 1.
|
484 |
+
n = 1
|
485 |
+
u **= -1
|
486 |
+
const *= -1
|
487 |
+
ans = [(i, -j) for i, j in ans]
|
488 |
+
|
489 |
+
if n == 1:
|
490 |
+
# Example: exp(x + x**2) over QQ(x, exp(x), exp(x**2))
|
491 |
+
self.newf = self.newf.xreplace({exp(arg): exp(const)*Mul(*[
|
492 |
+
u**power for u, power in ans])})
|
493 |
+
self.newf = self.newf.xreplace({exp(p*exparg):
|
494 |
+
exp(const*p) * Mul(*[u**power for u, power in ans])
|
495 |
+
for exparg, p in others})
|
496 |
+
# TODO: Add something to backsubs to put exp(const*p)
|
497 |
+
# back together.
|
498 |
+
|
499 |
+
continue
|
500 |
+
|
501 |
+
else:
|
502 |
+
# Bad news: we have an algebraic radical. But maybe we
|
503 |
+
# could still avoid it by choosing a different extension.
|
504 |
+
# For example, integer_powers() won't handle exp(x/2 + 1)
|
505 |
+
# over QQ(x, exp(x)), but if we pull out the exp(1), it
|
506 |
+
# will. Or maybe we have exp(x + x**2/2), over
|
507 |
+
# QQ(x, exp(x), exp(x**2)), which is exp(x)*sqrt(exp(x**2)),
|
508 |
+
# but if we use QQ(x, exp(x), exp(x**2/2)), then they will
|
509 |
+
# all work.
|
510 |
+
#
|
511 |
+
# So here is what we do: If there is a non-zero const, pull
|
512 |
+
# it out and retry. Also, if len(ans) > 1, then rewrite
|
513 |
+
# exp(arg) as the product of exponentials from ans, and
|
514 |
+
# retry that. If const == 0 and len(ans) == 1, then we
|
515 |
+
# assume that it would have been handled by either
|
516 |
+
# integer_powers() or n == 1 above if it could be handled,
|
517 |
+
# so we give up at that point. For example, you can never
|
518 |
+
# handle exp(log(x)/2) because it equals sqrt(x).
|
519 |
+
|
520 |
+
if const or len(ans) > 1:
|
521 |
+
rad = Mul(*[term**(power/n) for term, power in ans])
|
522 |
+
self.newf = self.newf.xreplace({exp(p*exparg):
|
523 |
+
exp(const*p)*rad for exparg, p in others})
|
524 |
+
self.newf = self.newf.xreplace(dict(list(zip(reversed(self.T),
|
525 |
+
reversed([f(self.x) for f in self.Tfuncs])))))
|
526 |
+
restart = True
|
527 |
+
break
|
528 |
+
else:
|
529 |
+
# TODO: give algebraic dependence in error string
|
530 |
+
raise NotImplementedError("Cannot integrate over "
|
531 |
+
"algebraic extensions.")
|
532 |
+
|
533 |
+
else:
|
534 |
+
arga, argd = frac_in(arg, self.t)
|
535 |
+
darga = (argd*derivation(Poly(arga, self.t), self) -
|
536 |
+
arga*derivation(Poly(argd, self.t), self))
|
537 |
+
dargd = argd**2
|
538 |
+
darga, dargd = darga.cancel(dargd, include=True)
|
539 |
+
darg = darga.as_expr()/dargd.as_expr()
|
540 |
+
self.t = next(self.ts)
|
541 |
+
self.T.append(self.t)
|
542 |
+
self.extargs.append(arg)
|
543 |
+
self.exts.append('exp')
|
544 |
+
self.D.append(darg.as_poly(self.t, expand=False)*Poly(self.t,
|
545 |
+
self.t, expand=False))
|
546 |
+
if self.dummy:
|
547 |
+
i = Dummy("i")
|
548 |
+
else:
|
549 |
+
i = Symbol('i')
|
550 |
+
self.Tfuncs += [Lambda(i, exp(arg.subs(self.x, i)))]
|
551 |
+
self.newf = self.newf.xreplace(
|
552 |
+
{exp(exparg): self.t**p for exparg, p in others})
|
553 |
+
new_extension = True
|
554 |
+
|
555 |
+
if restart:
|
556 |
+
return None
|
557 |
+
return new_extension
|
558 |
+
|
559 |
+
def _log_part(self, logs):
|
560 |
+
"""
|
561 |
+
Try to build a logarithmic extension.
|
562 |
+
|
563 |
+
Returns
|
564 |
+
=======
|
565 |
+
|
566 |
+
Returns True if there was a new extension and False if there was no new
|
567 |
+
extension but it was able to rewrite the given logarithms in terms
|
568 |
+
of the existing extension. Unlike with exponential extensions, there
|
569 |
+
is no way that a logarithm is not transcendental over and cannot be
|
570 |
+
rewritten in terms of an already existing extension in a non-algebraic
|
571 |
+
way, so this function does not ever return None or raise
|
572 |
+
NotImplementedError.
|
573 |
+
"""
|
574 |
+
from .prde import is_deriv_k
|
575 |
+
new_extension = False
|
576 |
+
logargs = [i.args[0] for i in logs]
|
577 |
+
for arg in ordered(logargs):
|
578 |
+
# The log case is easier, because whenever a logarithm is algebraic
|
579 |
+
# over the base field, it is of the form a1*t1 + ... an*tn + c,
|
580 |
+
# which is a polynomial, so we can just replace it with that.
|
581 |
+
# In other words, we don't have to worry about radicals.
|
582 |
+
arga, argd = frac_in(arg, self.t)
|
583 |
+
A = is_deriv_k(arga, argd, self)
|
584 |
+
if A is not None:
|
585 |
+
ans, u, const = A
|
586 |
+
newterm = log(const) + u
|
587 |
+
self.newf = self.newf.xreplace({log(arg): newterm})
|
588 |
+
continue
|
589 |
+
|
590 |
+
else:
|
591 |
+
arga, argd = frac_in(arg, self.t)
|
592 |
+
darga = (argd*derivation(Poly(arga, self.t), self) -
|
593 |
+
arga*derivation(Poly(argd, self.t), self))
|
594 |
+
dargd = argd**2
|
595 |
+
darg = darga.as_expr()/dargd.as_expr()
|
596 |
+
self.t = next(self.ts)
|
597 |
+
self.T.append(self.t)
|
598 |
+
self.extargs.append(arg)
|
599 |
+
self.exts.append('log')
|
600 |
+
self.D.append(cancel(darg.as_expr()/arg).as_poly(self.t,
|
601 |
+
expand=False))
|
602 |
+
if self.dummy:
|
603 |
+
i = Dummy("i")
|
604 |
+
else:
|
605 |
+
i = Symbol('i')
|
606 |
+
self.Tfuncs += [Lambda(i, log(arg.subs(self.x, i)))]
|
607 |
+
self.newf = self.newf.xreplace({log(arg): self.t})
|
608 |
+
new_extension = True
|
609 |
+
|
610 |
+
return new_extension
|
611 |
+
|
612 |
+
@property
|
613 |
+
def _important_attrs(self):
|
614 |
+
"""
|
615 |
+
Returns some of the more important attributes of self.
|
616 |
+
|
617 |
+
Explanation
|
618 |
+
===========
|
619 |
+
|
620 |
+
Used for testing and debugging purposes.
|
621 |
+
|
622 |
+
The attributes are (fa, fd, D, T, Tfuncs, backsubs,
|
623 |
+
exts, extargs).
|
624 |
+
"""
|
625 |
+
return (self.fa, self.fd, self.D, self.T, self.Tfuncs,
|
626 |
+
self.backsubs, self.exts, self.extargs)
|
627 |
+
|
628 |
+
# NOTE: this printing doesn't follow the Python's standard
|
629 |
+
# eval(repr(DE)) == DE, where DE is the DifferentialExtension object,
|
630 |
+
# also this printing is supposed to contain all the important
|
631 |
+
# attributes of a DifferentialExtension object
|
632 |
+
def __repr__(self):
|
633 |
+
# no need to have GeneratorType object printed in it
|
634 |
+
r = [(attr, getattr(self, attr)) for attr in self.__slots__
|
635 |
+
if not isinstance(getattr(self, attr), GeneratorType)]
|
636 |
+
return self.__class__.__name__ + '(dict(%r))' % (r)
|
637 |
+
|
638 |
+
# fancy printing of DifferentialExtension object
|
639 |
+
def __str__(self):
|
640 |
+
return (self.__class__.__name__ + '({fa=%s, fd=%s, D=%s})' %
|
641 |
+
(self.fa, self.fd, self.D))
|
642 |
+
|
643 |
+
# should only be used for debugging purposes, internally
|
644 |
+
# f1 = f2 = log(x) at different places in code execution
|
645 |
+
# may return D1 != D2 as True, since 'level' or other attribute
|
646 |
+
# may differ
|
647 |
+
def __eq__(self, other):
|
648 |
+
for attr in self.__class__.__slots__:
|
649 |
+
d1, d2 = getattr(self, attr), getattr(other, attr)
|
650 |
+
if not (isinstance(d1, GeneratorType) or d1 == d2):
|
651 |
+
return False
|
652 |
+
return True
|
653 |
+
|
654 |
+
def reset(self):
|
655 |
+
"""
|
656 |
+
Reset self to an initial state. Used by __init__.
|
657 |
+
"""
|
658 |
+
self.t = self.x
|
659 |
+
self.T = [self.x]
|
660 |
+
self.D = [Poly(1, self.x)]
|
661 |
+
self.level = -1
|
662 |
+
self.exts = [None]
|
663 |
+
self.extargs = [None]
|
664 |
+
if self.dummy:
|
665 |
+
self.ts = numbered_symbols('t', cls=Dummy)
|
666 |
+
else:
|
667 |
+
# For testing
|
668 |
+
self.ts = numbered_symbols('t')
|
669 |
+
# For various things that we change to make things work that we need to
|
670 |
+
# change back when we are done.
|
671 |
+
self.backsubs = []
|
672 |
+
self.Tfuncs = []
|
673 |
+
self.newf = self.f
|
674 |
+
|
675 |
+
def indices(self, extension):
|
676 |
+
"""
|
677 |
+
Parameters
|
678 |
+
==========
|
679 |
+
|
680 |
+
extension : str
|
681 |
+
Represents a valid extension type.
|
682 |
+
|
683 |
+
Returns
|
684 |
+
=======
|
685 |
+
|
686 |
+
list: A list of indices of 'exts' where extension of
|
687 |
+
type 'extension' is present.
|
688 |
+
|
689 |
+
Examples
|
690 |
+
========
|
691 |
+
|
692 |
+
>>> from sympy.integrals.risch import DifferentialExtension
|
693 |
+
>>> from sympy import log, exp
|
694 |
+
>>> from sympy.abc import x
|
695 |
+
>>> DE = DifferentialExtension(log(x) + exp(x), x, handle_first='exp')
|
696 |
+
>>> DE.indices('log')
|
697 |
+
[2]
|
698 |
+
>>> DE.indices('exp')
|
699 |
+
[1]
|
700 |
+
|
701 |
+
"""
|
702 |
+
return [i for i, ext in enumerate(self.exts) if ext == extension]
|
703 |
+
|
704 |
+
def increment_level(self):
|
705 |
+
"""
|
706 |
+
Increment the level of self.
|
707 |
+
|
708 |
+
Explanation
|
709 |
+
===========
|
710 |
+
|
711 |
+
This makes the working differential extension larger. self.level is
|
712 |
+
given relative to the end of the list (-1, -2, etc.), so we do not need
|
713 |
+
do worry about it when building the extension.
|
714 |
+
"""
|
715 |
+
if self.level >= -1:
|
716 |
+
raise ValueError("The level of the differential extension cannot "
|
717 |
+
"be incremented any further.")
|
718 |
+
|
719 |
+
self.level += 1
|
720 |
+
self.t = self.T[self.level]
|
721 |
+
self.d = self.D[self.level]
|
722 |
+
self.case = self.cases[self.level]
|
723 |
+
return None
|
724 |
+
|
725 |
+
def decrement_level(self):
|
726 |
+
"""
|
727 |
+
Decrease the level of self.
|
728 |
+
|
729 |
+
Explanation
|
730 |
+
===========
|
731 |
+
|
732 |
+
This makes the working differential extension smaller. self.level is
|
733 |
+
given relative to the end of the list (-1, -2, etc.), so we do not need
|
734 |
+
do worry about it when building the extension.
|
735 |
+
"""
|
736 |
+
if self.level <= -len(self.T):
|
737 |
+
raise ValueError("The level of the differential extension cannot "
|
738 |
+
"be decremented any further.")
|
739 |
+
|
740 |
+
self.level -= 1
|
741 |
+
self.t = self.T[self.level]
|
742 |
+
self.d = self.D[self.level]
|
743 |
+
self.case = self.cases[self.level]
|
744 |
+
return None
|
745 |
+
|
746 |
+
|
747 |
+
def update_sets(seq, atoms, func):
|
748 |
+
s = set(seq)
|
749 |
+
s = atoms.intersection(s)
|
750 |
+
new = atoms - s
|
751 |
+
s.update(list(filter(func, new)))
|
752 |
+
return list(s)
|
753 |
+
|
754 |
+
|
755 |
+
class DecrementLevel:
|
756 |
+
"""
|
757 |
+
A context manager for decrementing the level of a DifferentialExtension.
|
758 |
+
"""
|
759 |
+
__slots__ = ('DE',)
|
760 |
+
|
761 |
+
def __init__(self, DE):
|
762 |
+
self.DE = DE
|
763 |
+
return
|
764 |
+
|
765 |
+
def __enter__(self):
|
766 |
+
self.DE.decrement_level()
|
767 |
+
|
768 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
769 |
+
self.DE.increment_level()
|
770 |
+
|
771 |
+
|
772 |
+
class NonElementaryIntegralException(Exception):
|
773 |
+
"""
|
774 |
+
Exception used by subroutines within the Risch algorithm to indicate to one
|
775 |
+
another that the function being integrated does not have an elementary
|
776 |
+
integral in the given differential field.
|
777 |
+
"""
|
778 |
+
# TODO: Rewrite algorithms below to use this (?)
|
779 |
+
|
780 |
+
# TODO: Pass through information about why the integral was nonelementary,
|
781 |
+
# and store that in the resulting NonElementaryIntegral somehow.
|
782 |
+
pass
|
783 |
+
|
784 |
+
|
785 |
+
def gcdex_diophantine(a, b, c):
|
786 |
+
"""
|
787 |
+
Extended Euclidean Algorithm, Diophantine version.
|
788 |
+
|
789 |
+
Explanation
|
790 |
+
===========
|
791 |
+
|
792 |
+
Given ``a``, ``b`` in K[x] and ``c`` in (a, b), the ideal generated by ``a`` and
|
793 |
+
``b``, return (s, t) such that s*a + t*b == c and either s == 0 or s.degree()
|
794 |
+
< b.degree().
|
795 |
+
"""
|
796 |
+
# Extended Euclidean Algorithm (Diophantine Version) pg. 13
|
797 |
+
# TODO: This should go in densetools.py.
|
798 |
+
# XXX: Bettter name?
|
799 |
+
|
800 |
+
s, g = a.half_gcdex(b)
|
801 |
+
s *= c.exquo(g) # Inexact division means c is not in (a, b)
|
802 |
+
if s and s.degree() >= b.degree():
|
803 |
+
_, s = s.div(b)
|
804 |
+
t = (c - s*a).exquo(b)
|
805 |
+
return (s, t)
|
806 |
+
|
807 |
+
|
808 |
+
def frac_in(f, t, *, cancel=False, **kwargs):
|
809 |
+
"""
|
810 |
+
Returns the tuple (fa, fd), where fa and fd are Polys in t.
|
811 |
+
|
812 |
+
Explanation
|
813 |
+
===========
|
814 |
+
|
815 |
+
This is a common idiom in the Risch Algorithm functions, so we abstract
|
816 |
+
it out here. ``f`` should be a basic expression, a Poly, or a tuple (fa, fd),
|
817 |
+
where fa and fd are either basic expressions or Polys, and f == fa/fd.
|
818 |
+
**kwargs are applied to Poly.
|
819 |
+
"""
|
820 |
+
if isinstance(f, tuple):
|
821 |
+
fa, fd = f
|
822 |
+
f = fa.as_expr()/fd.as_expr()
|
823 |
+
fa, fd = f.as_expr().as_numer_denom()
|
824 |
+
fa, fd = fa.as_poly(t, **kwargs), fd.as_poly(t, **kwargs)
|
825 |
+
if cancel:
|
826 |
+
fa, fd = fa.cancel(fd, include=True)
|
827 |
+
if fa is None or fd is None:
|
828 |
+
raise ValueError("Could not turn %s into a fraction in %s." % (f, t))
|
829 |
+
return (fa, fd)
|
830 |
+
|
831 |
+
|
832 |
+
def as_poly_1t(p, t, z):
|
833 |
+
"""
|
834 |
+
(Hackish) way to convert an element ``p`` of K[t, 1/t] to K[t, z].
|
835 |
+
|
836 |
+
In other words, ``z == 1/t`` will be a dummy variable that Poly can handle
|
837 |
+
better.
|
838 |
+
|
839 |
+
See issue 5131.
|
840 |
+
|
841 |
+
Examples
|
842 |
+
========
|
843 |
+
|
844 |
+
>>> from sympy import random_poly
|
845 |
+
>>> from sympy.integrals.risch import as_poly_1t
|
846 |
+
>>> from sympy.abc import x, z
|
847 |
+
|
848 |
+
>>> p1 = random_poly(x, 10, -10, 10)
|
849 |
+
>>> p2 = random_poly(x, 10, -10, 10)
|
850 |
+
>>> p = p1 + p2.subs(x, 1/x)
|
851 |
+
>>> as_poly_1t(p, x, z).as_expr().subs(z, 1/x) == p
|
852 |
+
True
|
853 |
+
"""
|
854 |
+
# TODO: Use this on the final result. That way, we can avoid answers like
|
855 |
+
# (...)*exp(-x).
|
856 |
+
pa, pd = frac_in(p, t, cancel=True)
|
857 |
+
if not pd.is_monomial:
|
858 |
+
# XXX: Is there a better Poly exception that we could raise here?
|
859 |
+
# Either way, if you see this (from the Risch Algorithm) it indicates
|
860 |
+
# a bug.
|
861 |
+
raise PolynomialError("%s is not an element of K[%s, 1/%s]." % (p, t, t))
|
862 |
+
d = pd.degree(t)
|
863 |
+
one_t_part = pa.slice(0, d + 1)
|
864 |
+
r = pd.degree() - pa.degree()
|
865 |
+
t_part = pa - one_t_part
|
866 |
+
try:
|
867 |
+
t_part = t_part.to_field().exquo(pd)
|
868 |
+
except DomainError as e:
|
869 |
+
# issue 4950
|
870 |
+
raise NotImplementedError(e)
|
871 |
+
# Compute the negative degree parts.
|
872 |
+
one_t_part = Poly.from_list(reversed(one_t_part.rep.rep), *one_t_part.gens,
|
873 |
+
domain=one_t_part.domain)
|
874 |
+
if 0 < r < oo:
|
875 |
+
one_t_part *= Poly(t**r, t)
|
876 |
+
|
877 |
+
one_t_part = one_t_part.replace(t, z) # z will be 1/t
|
878 |
+
if pd.nth(d):
|
879 |
+
one_t_part *= Poly(1/pd.nth(d), z, expand=False)
|
880 |
+
ans = t_part.as_poly(t, z, expand=False) + one_t_part.as_poly(t, z,
|
881 |
+
expand=False)
|
882 |
+
|
883 |
+
return ans
|
884 |
+
|
885 |
+
|
886 |
+
def derivation(p, DE, coefficientD=False, basic=False):
|
887 |
+
"""
|
888 |
+
Computes Dp.
|
889 |
+
|
890 |
+
Explanation
|
891 |
+
===========
|
892 |
+
|
893 |
+
Given the derivation D with D = d/dx and p is a polynomial in t over
|
894 |
+
K(x), return Dp.
|
895 |
+
|
896 |
+
If coefficientD is True, it computes the derivation kD
|
897 |
+
(kappaD), which is defined as kD(sum(ai*Xi**i, (i, 0, n))) ==
|
898 |
+
sum(Dai*Xi**i, (i, 1, n)) (Definition 3.2.2, page 80). X in this case is
|
899 |
+
T[-1], so coefficientD computes the derivative just with respect to T[:-1],
|
900 |
+
with T[-1] treated as a constant.
|
901 |
+
|
902 |
+
If ``basic=True``, the returns a Basic expression. Elements of D can still be
|
903 |
+
instances of Poly.
|
904 |
+
"""
|
905 |
+
if basic:
|
906 |
+
r = 0
|
907 |
+
else:
|
908 |
+
r = Poly(0, DE.t)
|
909 |
+
|
910 |
+
t = DE.t
|
911 |
+
if coefficientD:
|
912 |
+
if DE.level <= -len(DE.T):
|
913 |
+
# 'base' case, the answer is 0.
|
914 |
+
return r
|
915 |
+
DE.decrement_level()
|
916 |
+
|
917 |
+
D = DE.D[:len(DE.D) + DE.level + 1]
|
918 |
+
T = DE.T[:len(DE.T) + DE.level + 1]
|
919 |
+
|
920 |
+
for d, v in zip(D, T):
|
921 |
+
pv = p.as_poly(v)
|
922 |
+
if pv is None or basic:
|
923 |
+
pv = p.as_expr()
|
924 |
+
|
925 |
+
if basic:
|
926 |
+
r += d.as_expr()*pv.diff(v)
|
927 |
+
else:
|
928 |
+
r += (d.as_expr()*pv.diff(v).as_expr()).as_poly(t)
|
929 |
+
|
930 |
+
if basic:
|
931 |
+
r = cancel(r)
|
932 |
+
if coefficientD:
|
933 |
+
DE.increment_level()
|
934 |
+
|
935 |
+
return r
|
936 |
+
|
937 |
+
|
938 |
+
def get_case(d, t):
|
939 |
+
"""
|
940 |
+
Returns the type of the derivation d.
|
941 |
+
|
942 |
+
Returns one of {'exp', 'tan', 'base', 'primitive', 'other_linear',
|
943 |
+
'other_nonlinear'}.
|
944 |
+
"""
|
945 |
+
if not d.expr.has(t):
|
946 |
+
if d.is_one:
|
947 |
+
return 'base'
|
948 |
+
return 'primitive'
|
949 |
+
if d.rem(Poly(t, t)).is_zero:
|
950 |
+
return 'exp'
|
951 |
+
if d.rem(Poly(1 + t**2, t)).is_zero:
|
952 |
+
return 'tan'
|
953 |
+
if d.degree(t) > 1:
|
954 |
+
return 'other_nonlinear'
|
955 |
+
return 'other_linear'
|
956 |
+
|
957 |
+
|
958 |
+
def splitfactor(p, DE, coefficientD=False, z=None):
|
959 |
+
"""
|
960 |
+
Splitting factorization.
|
961 |
+
|
962 |
+
Explanation
|
963 |
+
===========
|
964 |
+
|
965 |
+
Given a derivation D on k[t] and ``p`` in k[t], return (p_n, p_s) in
|
966 |
+
k[t] x k[t] such that p = p_n*p_s, p_s is special, and each square
|
967 |
+
factor of p_n is normal.
|
968 |
+
|
969 |
+
Page. 100
|
970 |
+
"""
|
971 |
+
kinv = [1/x for x in DE.T[:DE.level]]
|
972 |
+
if z:
|
973 |
+
kinv.append(z)
|
974 |
+
|
975 |
+
One = Poly(1, DE.t, domain=p.get_domain())
|
976 |
+
Dp = derivation(p, DE, coefficientD=coefficientD)
|
977 |
+
# XXX: Is this right?
|
978 |
+
if p.is_zero:
|
979 |
+
return (p, One)
|
980 |
+
|
981 |
+
if not p.expr.has(DE.t):
|
982 |
+
s = p.as_poly(*kinv).gcd(Dp.as_poly(*kinv)).as_poly(DE.t)
|
983 |
+
n = p.exquo(s)
|
984 |
+
return (n, s)
|
985 |
+
|
986 |
+
if not Dp.is_zero:
|
987 |
+
h = p.gcd(Dp).to_field()
|
988 |
+
g = p.gcd(p.diff(DE.t)).to_field()
|
989 |
+
s = h.exquo(g)
|
990 |
+
|
991 |
+
if s.degree(DE.t) == 0:
|
992 |
+
return (p, One)
|
993 |
+
|
994 |
+
q_split = splitfactor(p.exquo(s), DE, coefficientD=coefficientD)
|
995 |
+
|
996 |
+
return (q_split[0], q_split[1]*s)
|
997 |
+
else:
|
998 |
+
return (p, One)
|
999 |
+
|
1000 |
+
|
1001 |
+
def splitfactor_sqf(p, DE, coefficientD=False, z=None, basic=False):
|
1002 |
+
"""
|
1003 |
+
Splitting Square-free Factorization.
|
1004 |
+
|
1005 |
+
Explanation
|
1006 |
+
===========
|
1007 |
+
|
1008 |
+
Given a derivation D on k[t] and ``p`` in k[t], returns (N1, ..., Nm)
|
1009 |
+
and (S1, ..., Sm) in k[t]^m such that p =
|
1010 |
+
(N1*N2**2*...*Nm**m)*(S1*S2**2*...*Sm**m) is a splitting
|
1011 |
+
factorization of ``p`` and the Ni and Si are square-free and coprime.
|
1012 |
+
"""
|
1013 |
+
# TODO: This algorithm appears to be faster in every case
|
1014 |
+
# TODO: Verify this and splitfactor() for multiple extensions
|
1015 |
+
kkinv = [1/x for x in DE.T[:DE.level]] + DE.T[:DE.level]
|
1016 |
+
if z:
|
1017 |
+
kkinv = [z]
|
1018 |
+
|
1019 |
+
S = []
|
1020 |
+
N = []
|
1021 |
+
p_sqf = p.sqf_list_include()
|
1022 |
+
if p.is_zero:
|
1023 |
+
return (((p, 1),), ())
|
1024 |
+
|
1025 |
+
for pi, i in p_sqf:
|
1026 |
+
Si = pi.as_poly(*kkinv).gcd(derivation(pi, DE,
|
1027 |
+
coefficientD=coefficientD,basic=basic).as_poly(*kkinv)).as_poly(DE.t)
|
1028 |
+
pi = Poly(pi, DE.t)
|
1029 |
+
Si = Poly(Si, DE.t)
|
1030 |
+
Ni = pi.exquo(Si)
|
1031 |
+
if not Si.is_one:
|
1032 |
+
S.append((Si, i))
|
1033 |
+
if not Ni.is_one:
|
1034 |
+
N.append((Ni, i))
|
1035 |
+
|
1036 |
+
return (tuple(N), tuple(S))
|
1037 |
+
|
1038 |
+
|
1039 |
+
def canonical_representation(a, d, DE):
|
1040 |
+
"""
|
1041 |
+
Canonical Representation.
|
1042 |
+
|
1043 |
+
Explanation
|
1044 |
+
===========
|
1045 |
+
|
1046 |
+
Given a derivation D on k[t] and f = a/d in k(t), return (f_p, f_s,
|
1047 |
+
f_n) in k[t] x k(t) x k(t) such that f = f_p + f_s + f_n is the
|
1048 |
+
canonical representation of f (f_p is a polynomial, f_s is reduced
|
1049 |
+
(has a special denominator), and f_n is simple (has a normal
|
1050 |
+
denominator).
|
1051 |
+
"""
|
1052 |
+
# Make d monic
|
1053 |
+
l = Poly(1/d.LC(), DE.t)
|
1054 |
+
a, d = a.mul(l), d.mul(l)
|
1055 |
+
|
1056 |
+
q, r = a.div(d)
|
1057 |
+
dn, ds = splitfactor(d, DE)
|
1058 |
+
|
1059 |
+
b, c = gcdex_diophantine(dn.as_poly(DE.t), ds.as_poly(DE.t), r.as_poly(DE.t))
|
1060 |
+
b, c = b.as_poly(DE.t), c.as_poly(DE.t)
|
1061 |
+
|
1062 |
+
return (q, (b, ds), (c, dn))
|
1063 |
+
|
1064 |
+
|
1065 |
+
def hermite_reduce(a, d, DE):
|
1066 |
+
"""
|
1067 |
+
Hermite Reduction - Mack's Linear Version.
|
1068 |
+
|
1069 |
+
Given a derivation D on k(t) and f = a/d in k(t), returns g, h, r in
|
1070 |
+
k(t) such that f = Dg + h + r, h is simple, and r is reduced.
|
1071 |
+
|
1072 |
+
"""
|
1073 |
+
# Make d monic
|
1074 |
+
l = Poly(1/d.LC(), DE.t)
|
1075 |
+
a, d = a.mul(l), d.mul(l)
|
1076 |
+
|
1077 |
+
fp, fs, fn = canonical_representation(a, d, DE)
|
1078 |
+
a, d = fn
|
1079 |
+
l = Poly(1/d.LC(), DE.t)
|
1080 |
+
a, d = a.mul(l), d.mul(l)
|
1081 |
+
|
1082 |
+
ga = Poly(0, DE.t)
|
1083 |
+
gd = Poly(1, DE.t)
|
1084 |
+
|
1085 |
+
dd = derivation(d, DE)
|
1086 |
+
dm = gcd(d.to_field(), dd.to_field()).as_poly(DE.t)
|
1087 |
+
ds, _ = d.div(dm)
|
1088 |
+
|
1089 |
+
while dm.degree(DE.t) > 0:
|
1090 |
+
|
1091 |
+
ddm = derivation(dm, DE)
|
1092 |
+
dm2 = gcd(dm.to_field(), ddm.to_field())
|
1093 |
+
dms, _ = dm.div(dm2)
|
1094 |
+
ds_ddm = ds.mul(ddm)
|
1095 |
+
ds_ddm_dm, _ = ds_ddm.div(dm)
|
1096 |
+
|
1097 |
+
b, c = gcdex_diophantine(-ds_ddm_dm.as_poly(DE.t),
|
1098 |
+
dms.as_poly(DE.t), a.as_poly(DE.t))
|
1099 |
+
b, c = b.as_poly(DE.t), c.as_poly(DE.t)
|
1100 |
+
|
1101 |
+
db = derivation(b, DE).as_poly(DE.t)
|
1102 |
+
ds_dms, _ = ds.div(dms)
|
1103 |
+
a = c.as_poly(DE.t) - db.mul(ds_dms).as_poly(DE.t)
|
1104 |
+
|
1105 |
+
ga = ga*dm + b*gd
|
1106 |
+
gd = gd*dm
|
1107 |
+
ga, gd = ga.cancel(gd, include=True)
|
1108 |
+
dm = dm2
|
1109 |
+
|
1110 |
+
q, r = a.div(ds)
|
1111 |
+
ga, gd = ga.cancel(gd, include=True)
|
1112 |
+
|
1113 |
+
r, d = r.cancel(ds, include=True)
|
1114 |
+
rra = q*fs[1] + fp*fs[1] + fs[0]
|
1115 |
+
rrd = fs[1]
|
1116 |
+
rra, rrd = rra.cancel(rrd, include=True)
|
1117 |
+
|
1118 |
+
return ((ga, gd), (r, d), (rra, rrd))
|
1119 |
+
|
1120 |
+
|
1121 |
+
def polynomial_reduce(p, DE):
|
1122 |
+
"""
|
1123 |
+
Polynomial Reduction.
|
1124 |
+
|
1125 |
+
Explanation
|
1126 |
+
===========
|
1127 |
+
|
1128 |
+
Given a derivation D on k(t) and p in k[t] where t is a nonlinear
|
1129 |
+
monomial over k, return q, r in k[t] such that p = Dq + r, and
|
1130 |
+
deg(r) < deg_t(Dt).
|
1131 |
+
"""
|
1132 |
+
q = Poly(0, DE.t)
|
1133 |
+
while p.degree(DE.t) >= DE.d.degree(DE.t):
|
1134 |
+
m = p.degree(DE.t) - DE.d.degree(DE.t) + 1
|
1135 |
+
q0 = Poly(DE.t**m, DE.t).mul(Poly(p.as_poly(DE.t).LC()/
|
1136 |
+
(m*DE.d.LC()), DE.t))
|
1137 |
+
q += q0
|
1138 |
+
p = p - derivation(q0, DE)
|
1139 |
+
|
1140 |
+
return (q, p)
|
1141 |
+
|
1142 |
+
|
1143 |
+
def laurent_series(a, d, F, n, DE):
|
1144 |
+
"""
|
1145 |
+
Contribution of ``F`` to the full partial fraction decomposition of A/D.
|
1146 |
+
|
1147 |
+
Explanation
|
1148 |
+
===========
|
1149 |
+
|
1150 |
+
Given a field K of characteristic 0 and ``A``,``D``,``F`` in K[x] with D monic,
|
1151 |
+
nonzero, coprime with A, and ``F`` the factor of multiplicity n in the square-
|
1152 |
+
free factorization of D, return the principal parts of the Laurent series of
|
1153 |
+
A/D at all the zeros of ``F``.
|
1154 |
+
"""
|
1155 |
+
if F.degree()==0:
|
1156 |
+
return 0
|
1157 |
+
Z = _symbols('z', n)
|
1158 |
+
z = Symbol('z')
|
1159 |
+
Z.insert(0, z)
|
1160 |
+
delta_a = Poly(0, DE.t)
|
1161 |
+
delta_d = Poly(1, DE.t)
|
1162 |
+
|
1163 |
+
E = d.quo(F**n)
|
1164 |
+
ha, hd = (a, E*Poly(z**n, DE.t))
|
1165 |
+
dF = derivation(F,DE)
|
1166 |
+
B, _ = gcdex_diophantine(E, F, Poly(1,DE.t))
|
1167 |
+
C, _ = gcdex_diophantine(dF, F, Poly(1,DE.t))
|
1168 |
+
|
1169 |
+
# initialization
|
1170 |
+
F_store = F
|
1171 |
+
V, DE_D_list, H_list= [], [], []
|
1172 |
+
|
1173 |
+
for j in range(0, n):
|
1174 |
+
# jth derivative of z would be substituted with dfnth/(j+1) where dfnth =(d^n)f/(dx)^n
|
1175 |
+
F_store = derivation(F_store, DE)
|
1176 |
+
v = (F_store.as_expr())/(j + 1)
|
1177 |
+
V.append(v)
|
1178 |
+
DE_D_list.append(Poly(Z[j + 1],Z[j]))
|
1179 |
+
|
1180 |
+
DE_new = DifferentialExtension(extension = {'D': DE_D_list}) #a differential indeterminate
|
1181 |
+
for j in range(0, n):
|
1182 |
+
zEha = Poly(z**(n + j), DE.t)*E**(j + 1)*ha
|
1183 |
+
zEhd = hd
|
1184 |
+
Pa, Pd = cancel((zEha, zEhd))[1], cancel((zEha, zEhd))[2]
|
1185 |
+
Q = Pa.quo(Pd)
|
1186 |
+
for i in range(0, j + 1):
|
1187 |
+
Q = Q.subs(Z[i], V[i])
|
1188 |
+
Dha = (hd*derivation(ha, DE, basic=True).as_poly(DE.t)
|
1189 |
+
+ ha*derivation(hd, DE, basic=True).as_poly(DE.t)
|
1190 |
+
+ hd*derivation(ha, DE_new, basic=True).as_poly(DE.t)
|
1191 |
+
+ ha*derivation(hd, DE_new, basic=True).as_poly(DE.t))
|
1192 |
+
Dhd = Poly(j + 1, DE.t)*hd**2
|
1193 |
+
ha, hd = Dha, Dhd
|
1194 |
+
|
1195 |
+
Ff, _ = F.div(gcd(F, Q))
|
1196 |
+
F_stara, F_stard = frac_in(Ff, DE.t)
|
1197 |
+
if F_stara.degree(DE.t) - F_stard.degree(DE.t) > 0:
|
1198 |
+
QBC = Poly(Q, DE.t)*B**(1 + j)*C**(n + j)
|
1199 |
+
H = QBC
|
1200 |
+
H_list.append(H)
|
1201 |
+
H = (QBC*F_stard).rem(F_stara)
|
1202 |
+
alphas = real_roots(F_stara)
|
1203 |
+
for alpha in list(alphas):
|
1204 |
+
delta_a = delta_a*Poly((DE.t - alpha)**(n - j), DE.t) + Poly(H.eval(alpha), DE.t)
|
1205 |
+
delta_d = delta_d*Poly((DE.t - alpha)**(n - j), DE.t)
|
1206 |
+
return (delta_a, delta_d, H_list)
|
1207 |
+
|
1208 |
+
|
1209 |
+
def recognize_derivative(a, d, DE, z=None):
|
1210 |
+
"""
|
1211 |
+
Compute the squarefree factorization of the denominator of f
|
1212 |
+
and for each Di the polynomial H in K[x] (see Theorem 2.7.1), using the
|
1213 |
+
LaurentSeries algorithm. Write Di = GiEi where Gj = gcd(Hn, Di) and
|
1214 |
+
gcd(Ei,Hn) = 1. Since the residues of f at the roots of Gj are all 0, and
|
1215 |
+
the residue of f at a root alpha of Ei is Hi(a) != 0, f is the derivative of a
|
1216 |
+
rational function if and only if Ei = 1 for each i, which is equivalent to
|
1217 |
+
Di | H[-1] for each i.
|
1218 |
+
"""
|
1219 |
+
flag =True
|
1220 |
+
a, d = a.cancel(d, include=True)
|
1221 |
+
_, r = a.div(d)
|
1222 |
+
Np, Sp = splitfactor_sqf(d, DE, coefficientD=True, z=z)
|
1223 |
+
|
1224 |
+
j = 1
|
1225 |
+
for s, _ in Sp:
|
1226 |
+
delta_a, delta_d, H = laurent_series(r, d, s, j, DE)
|
1227 |
+
g = gcd(d, H[-1]).as_poly()
|
1228 |
+
if g is not d:
|
1229 |
+
flag = False
|
1230 |
+
break
|
1231 |
+
j = j + 1
|
1232 |
+
return flag
|
1233 |
+
|
1234 |
+
|
1235 |
+
def recognize_log_derivative(a, d, DE, z=None):
|
1236 |
+
"""
|
1237 |
+
There exists a v in K(x)* such that f = dv/v
|
1238 |
+
where f a rational function if and only if f can be written as f = A/D
|
1239 |
+
where D is squarefree,deg(A) < deg(D), gcd(A, D) = 1,
|
1240 |
+
and all the roots of the Rothstein-Trager resultant are integers. In that case,
|
1241 |
+
any of the Rothstein-Trager, Lazard-Rioboo-Trager or Czichowski algorithm
|
1242 |
+
produces u in K(x) such that du/dx = uf.
|
1243 |
+
"""
|
1244 |
+
|
1245 |
+
z = z or Dummy('z')
|
1246 |
+
a, d = a.cancel(d, include=True)
|
1247 |
+
_, a = a.div(d)
|
1248 |
+
|
1249 |
+
pz = Poly(z, DE.t)
|
1250 |
+
Dd = derivation(d, DE)
|
1251 |
+
q = a - pz*Dd
|
1252 |
+
r, _ = d.resultant(q, includePRS=True)
|
1253 |
+
r = Poly(r, z)
|
1254 |
+
Np, Sp = splitfactor_sqf(r, DE, coefficientD=True, z=z)
|
1255 |
+
|
1256 |
+
for s, _ in Sp:
|
1257 |
+
# TODO also consider the complex roots which should
|
1258 |
+
# turn the flag false
|
1259 |
+
a = real_roots(s.as_poly(z))
|
1260 |
+
|
1261 |
+
if not all(j.is_Integer for j in a):
|
1262 |
+
return False
|
1263 |
+
return True
|
1264 |
+
|
1265 |
+
def residue_reduce(a, d, DE, z=None, invert=True):
|
1266 |
+
"""
|
1267 |
+
Lazard-Rioboo-Rothstein-Trager resultant reduction.
|
1268 |
+
|
1269 |
+
Explanation
|
1270 |
+
===========
|
1271 |
+
|
1272 |
+
Given a derivation ``D`` on k(t) and f in k(t) simple, return g
|
1273 |
+
elementary over k(t) and a Boolean b in {True, False} such that f -
|
1274 |
+
Dg in k[t] if b == True or f + h and f + h - Dg do not have an
|
1275 |
+
elementary integral over k(t) for any h in k<t> (reduced) if b ==
|
1276 |
+
False.
|
1277 |
+
|
1278 |
+
Returns (G, b), where G is a tuple of tuples of the form (s_i, S_i),
|
1279 |
+
such that g = Add(*[RootSum(s_i, lambda z: z*log(S_i(z, t))) for
|
1280 |
+
S_i, s_i in G]). f - Dg is the remaining integral, which is elementary
|
1281 |
+
only if b == True, and hence the integral of f is elementary only if
|
1282 |
+
b == True.
|
1283 |
+
|
1284 |
+
f - Dg is not calculated in this function because that would require
|
1285 |
+
explicitly calculating the RootSum. Use residue_reduce_derivation().
|
1286 |
+
"""
|
1287 |
+
# TODO: Use log_to_atan() from rationaltools.py
|
1288 |
+
# If r = residue_reduce(...), then the logarithmic part is given by:
|
1289 |
+
# sum([RootSum(a[0].as_poly(z), lambda i: i*log(a[1].as_expr()).subs(z,
|
1290 |
+
# i)).subs(t, log(x)) for a in r[0]])
|
1291 |
+
|
1292 |
+
z = z or Dummy('z')
|
1293 |
+
a, d = a.cancel(d, include=True)
|
1294 |
+
a, d = a.to_field().mul_ground(1/d.LC()), d.to_field().mul_ground(1/d.LC())
|
1295 |
+
kkinv = [1/x for x in DE.T[:DE.level]] + DE.T[:DE.level]
|
1296 |
+
|
1297 |
+
if a.is_zero:
|
1298 |
+
return ([], True)
|
1299 |
+
_, a = a.div(d)
|
1300 |
+
|
1301 |
+
pz = Poly(z, DE.t)
|
1302 |
+
|
1303 |
+
Dd = derivation(d, DE)
|
1304 |
+
q = a - pz*Dd
|
1305 |
+
|
1306 |
+
if Dd.degree(DE.t) <= d.degree(DE.t):
|
1307 |
+
r, R = d.resultant(q, includePRS=True)
|
1308 |
+
else:
|
1309 |
+
r, R = q.resultant(d, includePRS=True)
|
1310 |
+
|
1311 |
+
R_map, H = {}, []
|
1312 |
+
for i in R:
|
1313 |
+
R_map[i.degree()] = i
|
1314 |
+
|
1315 |
+
r = Poly(r, z)
|
1316 |
+
Np, Sp = splitfactor_sqf(r, DE, coefficientD=True, z=z)
|
1317 |
+
|
1318 |
+
for s, i in Sp:
|
1319 |
+
if i == d.degree(DE.t):
|
1320 |
+
s = Poly(s, z).monic()
|
1321 |
+
H.append((s, d))
|
1322 |
+
else:
|
1323 |
+
h = R_map.get(i)
|
1324 |
+
if h is None:
|
1325 |
+
continue
|
1326 |
+
h_lc = Poly(h.as_poly(DE.t).LC(), DE.t, field=True)
|
1327 |
+
|
1328 |
+
h_lc_sqf = h_lc.sqf_list_include(all=True)
|
1329 |
+
|
1330 |
+
for a, j in h_lc_sqf:
|
1331 |
+
h = Poly(h, DE.t, field=True).exquo(Poly(gcd(a, s**j, *kkinv),
|
1332 |
+
DE.t))
|
1333 |
+
|
1334 |
+
s = Poly(s, z).monic()
|
1335 |
+
|
1336 |
+
if invert:
|
1337 |
+
h_lc = Poly(h.as_poly(DE.t).LC(), DE.t, field=True, expand=False)
|
1338 |
+
inv, coeffs = h_lc.as_poly(z, field=True).invert(s), [S.One]
|
1339 |
+
|
1340 |
+
for coeff in h.coeffs()[1:]:
|
1341 |
+
L = reduced(inv*coeff.as_poly(inv.gens), [s])[1]
|
1342 |
+
coeffs.append(L.as_expr())
|
1343 |
+
|
1344 |
+
h = Poly(dict(list(zip(h.monoms(), coeffs))), DE.t)
|
1345 |
+
|
1346 |
+
H.append((s, h))
|
1347 |
+
|
1348 |
+
b = not any(cancel(i.as_expr()).has(DE.t, z) for i, _ in Np)
|
1349 |
+
|
1350 |
+
return (H, b)
|
1351 |
+
|
1352 |
+
|
1353 |
+
def residue_reduce_to_basic(H, DE, z):
|
1354 |
+
"""
|
1355 |
+
Converts the tuple returned by residue_reduce() into a Basic expression.
|
1356 |
+
"""
|
1357 |
+
# TODO: check what Lambda does with RootOf
|
1358 |
+
i = Dummy('i')
|
1359 |
+
s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs])))
|
1360 |
+
|
1361 |
+
return sum(RootSum(a[0].as_poly(z), Lambda(i, i*log(a[1].as_expr()).subs(
|
1362 |
+
{z: i}).subs(s))) for a in H)
|
1363 |
+
|
1364 |
+
|
1365 |
+
def residue_reduce_derivation(H, DE, z):
|
1366 |
+
"""
|
1367 |
+
Computes the derivation of an expression returned by residue_reduce().
|
1368 |
+
|
1369 |
+
In general, this is a rational function in t, so this returns an
|
1370 |
+
as_expr() result.
|
1371 |
+
"""
|
1372 |
+
# TODO: verify that this is correct for multiple extensions
|
1373 |
+
i = Dummy('i')
|
1374 |
+
return S(sum(RootSum(a[0].as_poly(z), Lambda(i, i*derivation(a[1],
|
1375 |
+
DE).as_expr().subs(z, i)/a[1].as_expr().subs(z, i))) for a in H))
|
1376 |
+
|
1377 |
+
|
1378 |
+
def integrate_primitive_polynomial(p, DE):
|
1379 |
+
"""
|
1380 |
+
Integration of primitive polynomials.
|
1381 |
+
|
1382 |
+
Explanation
|
1383 |
+
===========
|
1384 |
+
|
1385 |
+
Given a primitive monomial t over k, and ``p`` in k[t], return q in k[t],
|
1386 |
+
r in k, and a bool b in {True, False} such that r = p - Dq is in k if b is
|
1387 |
+
True, or r = p - Dq does not have an elementary integral over k(t) if b is
|
1388 |
+
False.
|
1389 |
+
"""
|
1390 |
+
Zero = Poly(0, DE.t)
|
1391 |
+
q = Poly(0, DE.t)
|
1392 |
+
|
1393 |
+
if not p.expr.has(DE.t):
|
1394 |
+
return (Zero, p, True)
|
1395 |
+
|
1396 |
+
from .prde import limited_integrate
|
1397 |
+
while True:
|
1398 |
+
if not p.expr.has(DE.t):
|
1399 |
+
return (q, p, True)
|
1400 |
+
|
1401 |
+
Dta, Dtb = frac_in(DE.d, DE.T[DE.level - 1])
|
1402 |
+
|
1403 |
+
with DecrementLevel(DE): # We had better be integrating the lowest extension (x)
|
1404 |
+
# with ratint().
|
1405 |
+
a = p.LC()
|
1406 |
+
aa, ad = frac_in(a, DE.t)
|
1407 |
+
|
1408 |
+
try:
|
1409 |
+
rv = limited_integrate(aa, ad, [(Dta, Dtb)], DE)
|
1410 |
+
if rv is None:
|
1411 |
+
raise NonElementaryIntegralException
|
1412 |
+
(ba, bd), c = rv
|
1413 |
+
except NonElementaryIntegralException:
|
1414 |
+
return (q, p, False)
|
1415 |
+
|
1416 |
+
m = p.degree(DE.t)
|
1417 |
+
q0 = c[0].as_poly(DE.t)*Poly(DE.t**(m + 1)/(m + 1), DE.t) + \
|
1418 |
+
(ba.as_expr()/bd.as_expr()).as_poly(DE.t)*Poly(DE.t**m, DE.t)
|
1419 |
+
|
1420 |
+
p = p - derivation(q0, DE)
|
1421 |
+
q = q + q0
|
1422 |
+
|
1423 |
+
|
1424 |
+
def integrate_primitive(a, d, DE, z=None):
|
1425 |
+
"""
|
1426 |
+
Integration of primitive functions.
|
1427 |
+
|
1428 |
+
Explanation
|
1429 |
+
===========
|
1430 |
+
|
1431 |
+
Given a primitive monomial t over k and f in k(t), return g elementary over
|
1432 |
+
k(t), i in k(t), and b in {True, False} such that i = f - Dg is in k if b
|
1433 |
+
is True or i = f - Dg does not have an elementary integral over k(t) if b
|
1434 |
+
is False.
|
1435 |
+
|
1436 |
+
This function returns a Basic expression for the first argument. If b is
|
1437 |
+
True, the second argument is Basic expression in k to recursively integrate.
|
1438 |
+
If b is False, the second argument is an unevaluated Integral, which has
|
1439 |
+
been proven to be nonelementary.
|
1440 |
+
"""
|
1441 |
+
# XXX: a and d must be canceled, or this might return incorrect results
|
1442 |
+
z = z or Dummy("z")
|
1443 |
+
s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs])))
|
1444 |
+
|
1445 |
+
g1, h, r = hermite_reduce(a, d, DE)
|
1446 |
+
g2, b = residue_reduce(h[0], h[1], DE, z=z)
|
1447 |
+
if not b:
|
1448 |
+
i = cancel(a.as_expr()/d.as_expr() - (g1[1]*derivation(g1[0], DE) -
|
1449 |
+
g1[0]*derivation(g1[1], DE)).as_expr()/(g1[1]**2).as_expr() -
|
1450 |
+
residue_reduce_derivation(g2, DE, z))
|
1451 |
+
i = NonElementaryIntegral(cancel(i).subs(s), DE.x)
|
1452 |
+
return ((g1[0].as_expr()/g1[1].as_expr()).subs(s) +
|
1453 |
+
residue_reduce_to_basic(g2, DE, z), i, b)
|
1454 |
+
|
1455 |
+
# h - Dg2 + r
|
1456 |
+
p = cancel(h[0].as_expr()/h[1].as_expr() - residue_reduce_derivation(g2,
|
1457 |
+
DE, z) + r[0].as_expr()/r[1].as_expr())
|
1458 |
+
p = p.as_poly(DE.t)
|
1459 |
+
|
1460 |
+
q, i, b = integrate_primitive_polynomial(p, DE)
|
1461 |
+
|
1462 |
+
ret = ((g1[0].as_expr()/g1[1].as_expr() + q.as_expr()).subs(s) +
|
1463 |
+
residue_reduce_to_basic(g2, DE, z))
|
1464 |
+
if not b:
|
1465 |
+
# TODO: This does not do the right thing when b is False
|
1466 |
+
i = NonElementaryIntegral(cancel(i.as_expr()).subs(s), DE.x)
|
1467 |
+
else:
|
1468 |
+
i = cancel(i.as_expr())
|
1469 |
+
|
1470 |
+
return (ret, i, b)
|
1471 |
+
|
1472 |
+
|
1473 |
+
def integrate_hyperexponential_polynomial(p, DE, z):
|
1474 |
+
"""
|
1475 |
+
Integration of hyperexponential polynomials.
|
1476 |
+
|
1477 |
+
Explanation
|
1478 |
+
===========
|
1479 |
+
|
1480 |
+
Given a hyperexponential monomial t over k and ``p`` in k[t, 1/t], return q in
|
1481 |
+
k[t, 1/t] and a bool b in {True, False} such that p - Dq in k if b is True,
|
1482 |
+
or p - Dq does not have an elementary integral over k(t) if b is False.
|
1483 |
+
"""
|
1484 |
+
t1 = DE.t
|
1485 |
+
dtt = DE.d.exquo(Poly(DE.t, DE.t))
|
1486 |
+
qa = Poly(0, DE.t)
|
1487 |
+
qd = Poly(1, DE.t)
|
1488 |
+
b = True
|
1489 |
+
|
1490 |
+
if p.is_zero:
|
1491 |
+
return(qa, qd, b)
|
1492 |
+
|
1493 |
+
from sympy.integrals.rde import rischDE
|
1494 |
+
|
1495 |
+
with DecrementLevel(DE):
|
1496 |
+
for i in range(-p.degree(z), p.degree(t1) + 1):
|
1497 |
+
if not i:
|
1498 |
+
continue
|
1499 |
+
elif i < 0:
|
1500 |
+
# If you get AttributeError: 'NoneType' object has no attribute 'nth'
|
1501 |
+
# then this should really not have expand=False
|
1502 |
+
# But it shouldn't happen because p is already a Poly in t and z
|
1503 |
+
a = p.as_poly(z, expand=False).nth(-i)
|
1504 |
+
else:
|
1505 |
+
# If you get AttributeError: 'NoneType' object has no attribute 'nth'
|
1506 |
+
# then this should really not have expand=False
|
1507 |
+
a = p.as_poly(t1, expand=False).nth(i)
|
1508 |
+
|
1509 |
+
aa, ad = frac_in(a, DE.t, field=True)
|
1510 |
+
aa, ad = aa.cancel(ad, include=True)
|
1511 |
+
iDt = Poly(i, t1)*dtt
|
1512 |
+
iDta, iDtd = frac_in(iDt, DE.t, field=True)
|
1513 |
+
try:
|
1514 |
+
va, vd = rischDE(iDta, iDtd, Poly(aa, DE.t), Poly(ad, DE.t), DE)
|
1515 |
+
va, vd = frac_in((va, vd), t1, cancel=True)
|
1516 |
+
except NonElementaryIntegralException:
|
1517 |
+
b = False
|
1518 |
+
else:
|
1519 |
+
qa = qa*vd + va*Poly(t1**i)*qd
|
1520 |
+
qd *= vd
|
1521 |
+
|
1522 |
+
return (qa, qd, b)
|
1523 |
+
|
1524 |
+
|
1525 |
+
def integrate_hyperexponential(a, d, DE, z=None, conds='piecewise'):
|
1526 |
+
"""
|
1527 |
+
Integration of hyperexponential functions.
|
1528 |
+
|
1529 |
+
Explanation
|
1530 |
+
===========
|
1531 |
+
|
1532 |
+
Given a hyperexponential monomial t over k and f in k(t), return g
|
1533 |
+
elementary over k(t), i in k(t), and a bool b in {True, False} such that
|
1534 |
+
i = f - Dg is in k if b is True or i = f - Dg does not have an elementary
|
1535 |
+
integral over k(t) if b is False.
|
1536 |
+
|
1537 |
+
This function returns a Basic expression for the first argument. If b is
|
1538 |
+
True, the second argument is Basic expression in k to recursively integrate.
|
1539 |
+
If b is False, the second argument is an unevaluated Integral, which has
|
1540 |
+
been proven to be nonelementary.
|
1541 |
+
"""
|
1542 |
+
# XXX: a and d must be canceled, or this might return incorrect results
|
1543 |
+
z = z or Dummy("z")
|
1544 |
+
s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs])))
|
1545 |
+
|
1546 |
+
g1, h, r = hermite_reduce(a, d, DE)
|
1547 |
+
g2, b = residue_reduce(h[0], h[1], DE, z=z)
|
1548 |
+
if not b:
|
1549 |
+
i = cancel(a.as_expr()/d.as_expr() - (g1[1]*derivation(g1[0], DE) -
|
1550 |
+
g1[0]*derivation(g1[1], DE)).as_expr()/(g1[1]**2).as_expr() -
|
1551 |
+
residue_reduce_derivation(g2, DE, z))
|
1552 |
+
i = NonElementaryIntegral(cancel(i.subs(s)), DE.x)
|
1553 |
+
return ((g1[0].as_expr()/g1[1].as_expr()).subs(s) +
|
1554 |
+
residue_reduce_to_basic(g2, DE, z), i, b)
|
1555 |
+
|
1556 |
+
# p should be a polynomial in t and 1/t, because Sirr == k[t, 1/t]
|
1557 |
+
# h - Dg2 + r
|
1558 |
+
p = cancel(h[0].as_expr()/h[1].as_expr() - residue_reduce_derivation(g2,
|
1559 |
+
DE, z) + r[0].as_expr()/r[1].as_expr())
|
1560 |
+
pp = as_poly_1t(p, DE.t, z)
|
1561 |
+
|
1562 |
+
qa, qd, b = integrate_hyperexponential_polynomial(pp, DE, z)
|
1563 |
+
|
1564 |
+
i = pp.nth(0, 0)
|
1565 |
+
|
1566 |
+
ret = ((g1[0].as_expr()/g1[1].as_expr()).subs(s) \
|
1567 |
+
+ residue_reduce_to_basic(g2, DE, z))
|
1568 |
+
|
1569 |
+
qas = qa.as_expr().subs(s)
|
1570 |
+
qds = qd.as_expr().subs(s)
|
1571 |
+
if conds == 'piecewise' and DE.x not in qds.free_symbols:
|
1572 |
+
# We have to be careful if the exponent is S.Zero!
|
1573 |
+
|
1574 |
+
# XXX: Does qd = 0 always necessarily correspond to the exponential
|
1575 |
+
# equaling 1?
|
1576 |
+
ret += Piecewise(
|
1577 |
+
(qas/qds, Ne(qds, 0)),
|
1578 |
+
(integrate((p - i).subs(DE.t, 1).subs(s), DE.x), True)
|
1579 |
+
)
|
1580 |
+
else:
|
1581 |
+
ret += qas/qds
|
1582 |
+
|
1583 |
+
if not b:
|
1584 |
+
i = p - (qd*derivation(qa, DE) - qa*derivation(qd, DE)).as_expr()/\
|
1585 |
+
(qd**2).as_expr()
|
1586 |
+
i = NonElementaryIntegral(cancel(i).subs(s), DE.x)
|
1587 |
+
return (ret, i, b)
|
1588 |
+
|
1589 |
+
|
1590 |
+
def integrate_hypertangent_polynomial(p, DE):
|
1591 |
+
"""
|
1592 |
+
Integration of hypertangent polynomials.
|
1593 |
+
|
1594 |
+
Explanation
|
1595 |
+
===========
|
1596 |
+
|
1597 |
+
Given a differential field k such that sqrt(-1) is not in k, a
|
1598 |
+
hypertangent monomial t over k, and p in k[t], return q in k[t] and
|
1599 |
+
c in k such that p - Dq - c*D(t**2 + 1)/(t**1 + 1) is in k and p -
|
1600 |
+
Dq does not have an elementary integral over k(t) if Dc != 0.
|
1601 |
+
"""
|
1602 |
+
# XXX: Make sure that sqrt(-1) is not in k.
|
1603 |
+
q, r = polynomial_reduce(p, DE)
|
1604 |
+
a = DE.d.exquo(Poly(DE.t**2 + 1, DE.t))
|
1605 |
+
c = Poly(r.nth(1)/(2*a.as_expr()), DE.t)
|
1606 |
+
return (q, c)
|
1607 |
+
|
1608 |
+
|
1609 |
+
def integrate_nonlinear_no_specials(a, d, DE, z=None):
|
1610 |
+
"""
|
1611 |
+
Integration of nonlinear monomials with no specials.
|
1612 |
+
|
1613 |
+
Explanation
|
1614 |
+
===========
|
1615 |
+
|
1616 |
+
Given a nonlinear monomial t over k such that Sirr ({p in k[t] | p is
|
1617 |
+
special, monic, and irreducible}) is empty, and f in k(t), returns g
|
1618 |
+
elementary over k(t) and a Boolean b in {True, False} such that f - Dg is
|
1619 |
+
in k if b == True, or f - Dg does not have an elementary integral over k(t)
|
1620 |
+
if b == False.
|
1621 |
+
|
1622 |
+
This function is applicable to all nonlinear extensions, but in the case
|
1623 |
+
where it returns b == False, it will only have proven that the integral of
|
1624 |
+
f - Dg is nonelementary if Sirr is empty.
|
1625 |
+
|
1626 |
+
This function returns a Basic expression.
|
1627 |
+
"""
|
1628 |
+
# TODO: Integral from k?
|
1629 |
+
# TODO: split out nonelementary integral
|
1630 |
+
# XXX: a and d must be canceled, or this might not return correct results
|
1631 |
+
z = z or Dummy("z")
|
1632 |
+
s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs])))
|
1633 |
+
|
1634 |
+
g1, h, r = hermite_reduce(a, d, DE)
|
1635 |
+
g2, b = residue_reduce(h[0], h[1], DE, z=z)
|
1636 |
+
if not b:
|
1637 |
+
return ((g1[0].as_expr()/g1[1].as_expr()).subs(s) +
|
1638 |
+
residue_reduce_to_basic(g2, DE, z), b)
|
1639 |
+
|
1640 |
+
# Because f has no specials, this should be a polynomial in t, or else
|
1641 |
+
# there is a bug.
|
1642 |
+
p = cancel(h[0].as_expr()/h[1].as_expr() - residue_reduce_derivation(g2,
|
1643 |
+
DE, z).as_expr() + r[0].as_expr()/r[1].as_expr()).as_poly(DE.t)
|
1644 |
+
q1, q2 = polynomial_reduce(p, DE)
|
1645 |
+
|
1646 |
+
if q2.expr.has(DE.t):
|
1647 |
+
b = False
|
1648 |
+
else:
|
1649 |
+
b = True
|
1650 |
+
|
1651 |
+
ret = (cancel(g1[0].as_expr()/g1[1].as_expr() + q1.as_expr()).subs(s) +
|
1652 |
+
residue_reduce_to_basic(g2, DE, z))
|
1653 |
+
return (ret, b)
|
1654 |
+
|
1655 |
+
|
1656 |
+
class NonElementaryIntegral(Integral):
|
1657 |
+
"""
|
1658 |
+
Represents a nonelementary Integral.
|
1659 |
+
|
1660 |
+
Explanation
|
1661 |
+
===========
|
1662 |
+
|
1663 |
+
If the result of integrate() is an instance of this class, it is
|
1664 |
+
guaranteed to be nonelementary. Note that integrate() by default will try
|
1665 |
+
to find any closed-form solution, even in terms of special functions which
|
1666 |
+
may themselves not be elementary. To make integrate() only give
|
1667 |
+
elementary solutions, or, in the cases where it can prove the integral to
|
1668 |
+
be nonelementary, instances of this class, use integrate(risch=True).
|
1669 |
+
In this case, integrate() may raise NotImplementedError if it cannot make
|
1670 |
+
such a determination.
|
1671 |
+
|
1672 |
+
integrate() uses the deterministic Risch algorithm to integrate elementary
|
1673 |
+
functions or prove that they have no elementary integral. In some cases,
|
1674 |
+
this algorithm can split an integral into an elementary and nonelementary
|
1675 |
+
part, so that the result of integrate will be the sum of an elementary
|
1676 |
+
expression and a NonElementaryIntegral.
|
1677 |
+
|
1678 |
+
Examples
|
1679 |
+
========
|
1680 |
+
|
1681 |
+
>>> from sympy import integrate, exp, log, Integral
|
1682 |
+
>>> from sympy.abc import x
|
1683 |
+
|
1684 |
+
>>> a = integrate(exp(-x**2), x, risch=True)
|
1685 |
+
>>> print(a)
|
1686 |
+
Integral(exp(-x**2), x)
|
1687 |
+
>>> type(a)
|
1688 |
+
<class 'sympy.integrals.risch.NonElementaryIntegral'>
|
1689 |
+
|
1690 |
+
>>> expr = (2*log(x)**2 - log(x) - x**2)/(log(x)**3 - x**2*log(x))
|
1691 |
+
>>> b = integrate(expr, x, risch=True)
|
1692 |
+
>>> print(b)
|
1693 |
+
-log(-x + log(x))/2 + log(x + log(x))/2 + Integral(1/log(x), x)
|
1694 |
+
>>> type(b.atoms(Integral).pop())
|
1695 |
+
<class 'sympy.integrals.risch.NonElementaryIntegral'>
|
1696 |
+
|
1697 |
+
"""
|
1698 |
+
# TODO: This is useful in and of itself, because isinstance(result,
|
1699 |
+
# NonElementaryIntegral) will tell if the integral has been proven to be
|
1700 |
+
# elementary. But should we do more? Perhaps a no-op .doit() if
|
1701 |
+
# elementary=True? Or maybe some information on why the integral is
|
1702 |
+
# nonelementary.
|
1703 |
+
pass
|
1704 |
+
|
1705 |
+
|
1706 |
+
def risch_integrate(f, x, extension=None, handle_first='log',
|
1707 |
+
separate_integral=False, rewrite_complex=None,
|
1708 |
+
conds='piecewise'):
|
1709 |
+
r"""
|
1710 |
+
The Risch Integration Algorithm.
|
1711 |
+
|
1712 |
+
Explanation
|
1713 |
+
===========
|
1714 |
+
|
1715 |
+
Only transcendental functions are supported. Currently, only exponentials
|
1716 |
+
and logarithms are supported, but support for trigonometric functions is
|
1717 |
+
forthcoming.
|
1718 |
+
|
1719 |
+
If this function returns an unevaluated Integral in the result, it means
|
1720 |
+
that it has proven that integral to be nonelementary. Any errors will
|
1721 |
+
result in raising NotImplementedError. The unevaluated Integral will be
|
1722 |
+
an instance of NonElementaryIntegral, a subclass of Integral.
|
1723 |
+
|
1724 |
+
handle_first may be either 'exp' or 'log'. This changes the order in
|
1725 |
+
which the extension is built, and may result in a different (but
|
1726 |
+
equivalent) solution (for an example of this, see issue 5109). It is also
|
1727 |
+
possible that the integral may be computed with one but not the other,
|
1728 |
+
because not all cases have been implemented yet. It defaults to 'log' so
|
1729 |
+
that the outer extension is exponential when possible, because more of the
|
1730 |
+
exponential case has been implemented.
|
1731 |
+
|
1732 |
+
If ``separate_integral`` is ``True``, the result is returned as a tuple (ans, i),
|
1733 |
+
where the integral is ans + i, ans is elementary, and i is either a
|
1734 |
+
NonElementaryIntegral or 0. This useful if you want to try further
|
1735 |
+
integrating the NonElementaryIntegral part using other algorithms to
|
1736 |
+
possibly get a solution in terms of special functions. It is False by
|
1737 |
+
default.
|
1738 |
+
|
1739 |
+
Examples
|
1740 |
+
========
|
1741 |
+
|
1742 |
+
>>> from sympy.integrals.risch import risch_integrate
|
1743 |
+
>>> from sympy import exp, log, pprint
|
1744 |
+
>>> from sympy.abc import x
|
1745 |
+
|
1746 |
+
First, we try integrating exp(-x**2). Except for a constant factor of
|
1747 |
+
2/sqrt(pi), this is the famous error function.
|
1748 |
+
|
1749 |
+
>>> pprint(risch_integrate(exp(-x**2), x))
|
1750 |
+
/
|
1751 |
+
|
|
1752 |
+
| 2
|
1753 |
+
| -x
|
1754 |
+
| e dx
|
1755 |
+
|
|
1756 |
+
/
|
1757 |
+
|
1758 |
+
The unevaluated Integral in the result means that risch_integrate() has
|
1759 |
+
proven that exp(-x**2) does not have an elementary anti-derivative.
|
1760 |
+
|
1761 |
+
In many cases, risch_integrate() can split out the elementary
|
1762 |
+
anti-derivative part from the nonelementary anti-derivative part.
|
1763 |
+
For example,
|
1764 |
+
|
1765 |
+
>>> pprint(risch_integrate((2*log(x)**2 - log(x) - x**2)/(log(x)**3 -
|
1766 |
+
... x**2*log(x)), x))
|
1767 |
+
/
|
1768 |
+
|
|
1769 |
+
log(-x + log(x)) log(x + log(x)) | 1
|
1770 |
+
- ---------------- + --------------- + | ------ dx
|
1771 |
+
2 2 | log(x)
|
1772 |
+
|
|
1773 |
+
/
|
1774 |
+
|
1775 |
+
This means that it has proven that the integral of 1/log(x) is
|
1776 |
+
nonelementary. This function is also known as the logarithmic integral,
|
1777 |
+
and is often denoted as Li(x).
|
1778 |
+
|
1779 |
+
risch_integrate() currently only accepts purely transcendental functions
|
1780 |
+
with exponentials and logarithms, though note that this can include
|
1781 |
+
nested exponentials and logarithms, as well as exponentials with bases
|
1782 |
+
other than E.
|
1783 |
+
|
1784 |
+
>>> pprint(risch_integrate(exp(x)*exp(exp(x)), x))
|
1785 |
+
/ x\
|
1786 |
+
\e /
|
1787 |
+
e
|
1788 |
+
>>> pprint(risch_integrate(exp(exp(x)), x))
|
1789 |
+
/
|
1790 |
+
|
|
1791 |
+
| / x\
|
1792 |
+
| \e /
|
1793 |
+
| e dx
|
1794 |
+
|
|
1795 |
+
/
|
1796 |
+
|
1797 |
+
>>> pprint(risch_integrate(x*x**x*log(x) + x**x + x*x**x, x))
|
1798 |
+
x
|
1799 |
+
x*x
|
1800 |
+
>>> pprint(risch_integrate(x**x, x))
|
1801 |
+
/
|
1802 |
+
|
|
1803 |
+
| x
|
1804 |
+
| x dx
|
1805 |
+
|
|
1806 |
+
/
|
1807 |
+
|
1808 |
+
>>> pprint(risch_integrate(-1/(x*log(x)*log(log(x))**2), x))
|
1809 |
+
1
|
1810 |
+
-----------
|
1811 |
+
log(log(x))
|
1812 |
+
|
1813 |
+
"""
|
1814 |
+
f = S(f)
|
1815 |
+
|
1816 |
+
DE = extension or DifferentialExtension(f, x, handle_first=handle_first,
|
1817 |
+
dummy=True, rewrite_complex=rewrite_complex)
|
1818 |
+
fa, fd = DE.fa, DE.fd
|
1819 |
+
|
1820 |
+
result = S.Zero
|
1821 |
+
for case in reversed(DE.cases):
|
1822 |
+
if not fa.expr.has(DE.t) and not fd.expr.has(DE.t) and not case == 'base':
|
1823 |
+
DE.decrement_level()
|
1824 |
+
fa, fd = frac_in((fa, fd), DE.t)
|
1825 |
+
continue
|
1826 |
+
|
1827 |
+
fa, fd = fa.cancel(fd, include=True)
|
1828 |
+
if case == 'exp':
|
1829 |
+
ans, i, b = integrate_hyperexponential(fa, fd, DE, conds=conds)
|
1830 |
+
elif case == 'primitive':
|
1831 |
+
ans, i, b = integrate_primitive(fa, fd, DE)
|
1832 |
+
elif case == 'base':
|
1833 |
+
# XXX: We can't call ratint() directly here because it doesn't
|
1834 |
+
# handle polynomials correctly.
|
1835 |
+
ans = integrate(fa.as_expr()/fd.as_expr(), DE.x, risch=False)
|
1836 |
+
b = False
|
1837 |
+
i = S.Zero
|
1838 |
+
else:
|
1839 |
+
raise NotImplementedError("Only exponential and logarithmic "
|
1840 |
+
"extensions are currently supported.")
|
1841 |
+
|
1842 |
+
result += ans
|
1843 |
+
if b:
|
1844 |
+
DE.decrement_level()
|
1845 |
+
fa, fd = frac_in(i, DE.t)
|
1846 |
+
else:
|
1847 |
+
result = result.subs(DE.backsubs)
|
1848 |
+
if not i.is_zero:
|
1849 |
+
i = NonElementaryIntegral(i.function.subs(DE.backsubs),i.limits)
|
1850 |
+
if not separate_integral:
|
1851 |
+
result += i
|
1852 |
+
return result
|
1853 |
+
else:
|
1854 |
+
|
1855 |
+
if isinstance(i, NonElementaryIntegral):
|
1856 |
+
return (result, i)
|
1857 |
+
else:
|
1858 |
+
return (result, 0)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/singularityfunctions.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.functions import SingularityFunction, DiracDelta
|
2 |
+
from sympy.integrals import integrate
|
3 |
+
|
4 |
+
|
5 |
+
def singularityintegrate(f, x):
|
6 |
+
"""
|
7 |
+
This function handles the indefinite integrations of Singularity functions.
|
8 |
+
The ``integrate`` function calls this function internally whenever an
|
9 |
+
instance of SingularityFunction is passed as argument.
|
10 |
+
|
11 |
+
Explanation
|
12 |
+
===========
|
13 |
+
|
14 |
+
The idea for integration is the following:
|
15 |
+
|
16 |
+
- If we are dealing with a SingularityFunction expression,
|
17 |
+
i.e. ``SingularityFunction(x, a, n)``, we just return
|
18 |
+
``SingularityFunction(x, a, n + 1)/(n + 1)`` if ``n >= 0`` and
|
19 |
+
``SingularityFunction(x, a, n + 1)`` if ``n < 0``.
|
20 |
+
|
21 |
+
- If the node is a multiplication or power node having a
|
22 |
+
SingularityFunction term we rewrite the whole expression in terms of
|
23 |
+
Heaviside and DiracDelta and then integrate the output. Lastly, we
|
24 |
+
rewrite the output of integration back in terms of SingularityFunction.
|
25 |
+
|
26 |
+
- If none of the above case arises, we return None.
|
27 |
+
|
28 |
+
Examples
|
29 |
+
========
|
30 |
+
|
31 |
+
>>> from sympy.integrals.singularityfunctions import singularityintegrate
|
32 |
+
>>> from sympy import SingularityFunction, symbols, Function
|
33 |
+
>>> x, a, n, y = symbols('x a n y')
|
34 |
+
>>> f = Function('f')
|
35 |
+
>>> singularityintegrate(SingularityFunction(x, a, 3), x)
|
36 |
+
SingularityFunction(x, a, 4)/4
|
37 |
+
>>> singularityintegrate(5*SingularityFunction(x, 5, -2), x)
|
38 |
+
5*SingularityFunction(x, 5, -1)
|
39 |
+
>>> singularityintegrate(6*SingularityFunction(x, 5, -1), x)
|
40 |
+
6*SingularityFunction(x, 5, 0)
|
41 |
+
>>> singularityintegrate(x*SingularityFunction(x, 0, -1), x)
|
42 |
+
0
|
43 |
+
>>> singularityintegrate(SingularityFunction(x, 1, -1) * f(x), x)
|
44 |
+
f(1)*SingularityFunction(x, 1, 0)
|
45 |
+
|
46 |
+
"""
|
47 |
+
|
48 |
+
if not f.has(SingularityFunction):
|
49 |
+
return None
|
50 |
+
|
51 |
+
if isinstance(f, SingularityFunction):
|
52 |
+
x, a, n = f.args
|
53 |
+
if n.is_positive or n.is_zero:
|
54 |
+
return SingularityFunction(x, a, n + 1)/(n + 1)
|
55 |
+
elif n in (-1, -2):
|
56 |
+
return SingularityFunction(x, a, n + 1)
|
57 |
+
|
58 |
+
if f.is_Mul or f.is_Pow:
|
59 |
+
|
60 |
+
expr = f.rewrite(DiracDelta)
|
61 |
+
expr = integrate(expr, x)
|
62 |
+
return expr.rewrite(SingularityFunction)
|
63 |
+
return None
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (194 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_deltafunctions.cpython-310.pyc
ADDED
Binary file (3.15 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_failing_integrals.cpython-310.pyc
ADDED
Binary file (9.91 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_integrals.cpython-310.pyc
ADDED
Binary file (87.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_intpoly.cpython-310.pyc
ADDED
Binary file (25 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_laplace.cpython-310.pyc
ADDED
Binary file (23.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_lineintegrals.cpython-310.pyc
ADDED
Binary file (839 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_manual.cpython-310.pyc
ADDED
Binary file (33.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_meijerint.cpython-310.pyc
ADDED
Binary file (27.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_quadrature.cpython-310.pyc
ADDED
Binary file (22.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_risch.cpython-310.pyc
ADDED
Binary file (35.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_transforms.cpython-310.pyc
ADDED
Binary file (23.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_trigonometry.cpython-310.pyc
ADDED
Binary file (3.67 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_deltafunctions.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.function import Function
|
2 |
+
from sympy.core.numbers import (Rational, pi)
|
3 |
+
from sympy.core.singleton import S
|
4 |
+
from sympy.core.symbol import symbols
|
5 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
6 |
+
from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
|
7 |
+
from sympy.integrals.deltafunctions import change_mul, deltaintegrate
|
8 |
+
|
9 |
+
f = Function("f")
|
10 |
+
x_1, x_2, x, y, z = symbols("x_1 x_2 x y z")
|
11 |
+
|
12 |
+
|
13 |
+
def test_change_mul():
|
14 |
+
assert change_mul(x, x) == (None, None)
|
15 |
+
assert change_mul(x*y, x) == (None, None)
|
16 |
+
assert change_mul(x*y*DiracDelta(x), x) == (DiracDelta(x), x*y)
|
17 |
+
assert change_mul(x*y*DiracDelta(x)*DiracDelta(y), x) == \
|
18 |
+
(DiracDelta(x), x*y*DiracDelta(y))
|
19 |
+
assert change_mul(DiracDelta(x)**2, x) == \
|
20 |
+
(DiracDelta(x), DiracDelta(x))
|
21 |
+
assert change_mul(y*DiracDelta(x)**2, x) == \
|
22 |
+
(DiracDelta(x), y*DiracDelta(x))
|
23 |
+
|
24 |
+
|
25 |
+
def test_deltaintegrate():
|
26 |
+
assert deltaintegrate(x, x) is None
|
27 |
+
assert deltaintegrate(x + DiracDelta(x), x) is None
|
28 |
+
assert deltaintegrate(DiracDelta(x, 0), x) == Heaviside(x)
|
29 |
+
for n in range(10):
|
30 |
+
assert deltaintegrate(DiracDelta(x, n + 1), x) == DiracDelta(x, n)
|
31 |
+
assert deltaintegrate(DiracDelta(x), x) == Heaviside(x)
|
32 |
+
assert deltaintegrate(DiracDelta(-x), x) == Heaviside(x)
|
33 |
+
assert deltaintegrate(DiracDelta(x - y), x) == Heaviside(x - y)
|
34 |
+
assert deltaintegrate(DiracDelta(y - x), x) == Heaviside(x - y)
|
35 |
+
|
36 |
+
assert deltaintegrate(x*DiracDelta(x), x) == 0
|
37 |
+
assert deltaintegrate((x - y)*DiracDelta(x - y), x) == 0
|
38 |
+
|
39 |
+
assert deltaintegrate(DiracDelta(x)**2, x) == DiracDelta(0)*Heaviside(x)
|
40 |
+
assert deltaintegrate(y*DiracDelta(x)**2, x) == \
|
41 |
+
y*DiracDelta(0)*Heaviside(x)
|
42 |
+
assert deltaintegrate(DiracDelta(x, 1), x) == DiracDelta(x, 0)
|
43 |
+
assert deltaintegrate(y*DiracDelta(x, 1), x) == y*DiracDelta(x, 0)
|
44 |
+
assert deltaintegrate(DiracDelta(x, 1)**2, x) == -DiracDelta(0, 2)*Heaviside(x)
|
45 |
+
assert deltaintegrate(y*DiracDelta(x, 1)**2, x) == -y*DiracDelta(0, 2)*Heaviside(x)
|
46 |
+
|
47 |
+
|
48 |
+
assert deltaintegrate(DiracDelta(x) * f(x), x) == f(0) * Heaviside(x)
|
49 |
+
assert deltaintegrate(DiracDelta(-x) * f(x), x) == f(0) * Heaviside(x)
|
50 |
+
assert deltaintegrate(DiracDelta(x - 1) * f(x), x) == f(1) * Heaviside(x - 1)
|
51 |
+
assert deltaintegrate(DiracDelta(1 - x) * f(x), x) == f(1) * Heaviside(x - 1)
|
52 |
+
assert deltaintegrate(DiracDelta(x**2 + x - 2), x) == \
|
53 |
+
Heaviside(x - 1)/3 + Heaviside(x + 2)/3
|
54 |
+
|
55 |
+
p = cos(x)*(DiracDelta(x) + DiracDelta(x**2 - 1))*sin(x)*(x - pi)
|
56 |
+
assert deltaintegrate(p, x) - (-pi*(cos(1)*Heaviside(-1 + x)*sin(1)/2 - \
|
57 |
+
cos(1)*Heaviside(1 + x)*sin(1)/2) + \
|
58 |
+
cos(1)*Heaviside(1 + x)*sin(1)/2 + \
|
59 |
+
cos(1)*Heaviside(-1 + x)*sin(1)/2) == 0
|
60 |
+
|
61 |
+
p = x_2*DiracDelta(x - x_2)*DiracDelta(x_2 - x_1)
|
62 |
+
assert deltaintegrate(p, x_2) == x*DiracDelta(x - x_1)*Heaviside(x_2 - x)
|
63 |
+
|
64 |
+
p = x*y**2*z*DiracDelta(y - x)*DiracDelta(y - z)*DiracDelta(x - z)
|
65 |
+
assert deltaintegrate(p, y) == x**3*z*DiracDelta(x - z)**2*Heaviside(y - x)
|
66 |
+
assert deltaintegrate((x + 1)*DiracDelta(2*x), x) == S.Half * Heaviside(x)
|
67 |
+
assert deltaintegrate((x + 1)*DiracDelta(x*Rational(2, 3) + Rational(4, 9)), x) == \
|
68 |
+
S.Half * Heaviside(x + Rational(2, 3))
|
69 |
+
|
70 |
+
a, b, c = symbols('a b c', commutative=False)
|
71 |
+
assert deltaintegrate(DiracDelta(x - y)*f(x - b)*f(x - a), x) == \
|
72 |
+
f(y - b)*f(y - a)*Heaviside(x - y)
|
73 |
+
|
74 |
+
p = f(x - a)*DiracDelta(x - y)*f(x - c)*f(x - b)
|
75 |
+
assert deltaintegrate(p, x) == f(y - a)*f(y - c)*f(y - b)*Heaviside(x - y)
|
76 |
+
|
77 |
+
p = DiracDelta(x - z)*f(x - b)*f(x - a)*DiracDelta(x - y)
|
78 |
+
assert deltaintegrate(p, x) == DiracDelta(y - z)*f(y - b)*f(y - a) * \
|
79 |
+
Heaviside(x - y)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_failing_integrals.py
ADDED
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# A collection of failing integrals from the issues.
|
2 |
+
|
3 |
+
from sympy.core.numbers import (I, Rational, oo, pi)
|
4 |
+
from sympy.core.singleton import S
|
5 |
+
from sympy.core.symbol import symbols
|
6 |
+
from sympy.functions.elementary.complexes import sign
|
7 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
8 |
+
from sympy.functions.elementary.hyperbolic import (sech, sinh)
|
9 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
10 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
11 |
+
from sympy.functions.elementary.trigonometric import (acos, atan, cos, sin, tan)
|
12 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
13 |
+
from sympy.functions.special.gamma_functions import gamma
|
14 |
+
from sympy.integrals.integrals import (Integral, integrate)
|
15 |
+
|
16 |
+
|
17 |
+
from sympy.testing.pytest import XFAIL, SKIP, slow, skip, ON_CI
|
18 |
+
|
19 |
+
from sympy.abc import x, k, c, y, b, h, a, m, z, n, t
|
20 |
+
|
21 |
+
|
22 |
+
@SKIP("Too slow for @slow")
|
23 |
+
@XFAIL
|
24 |
+
def test_issue_3880():
|
25 |
+
# integrate_hyperexponential(Poly(t*2*(1 - t0**2)*t0*(x**3 + x**2), t), Poly((1 + t0**2)**2*2*(x**2 + x + 1), t), [Poly(1, x), Poly(1 + t0**2, t0), Poly(t, t)], [x, t0, t], [exp, tan])
|
26 |
+
assert not integrate(exp(x)*cos(2*x)*sin(2*x) * (x**3 + x**2)/(2*(x**2 + x + 1)), x).has(Integral)
|
27 |
+
|
28 |
+
|
29 |
+
@XFAIL
|
30 |
+
def test_issue_4212():
|
31 |
+
assert not integrate(sign(x), x).has(Integral)
|
32 |
+
|
33 |
+
|
34 |
+
@XFAIL
|
35 |
+
def test_issue_4511():
|
36 |
+
# This works, but gives a complicated answer. The correct answer is x - cos(x).
|
37 |
+
# If current answer is simplified, 1 - cos(x) + x is obtained.
|
38 |
+
# The last one is what Maple gives. It is also quite slow.
|
39 |
+
assert integrate(cos(x)**2 / (1 - sin(x))) in [x - cos(x), 1 - cos(x) + x,
|
40 |
+
-2/(tan((S.Half)*x)**2 + 1) + x]
|
41 |
+
|
42 |
+
|
43 |
+
@XFAIL
|
44 |
+
def test_integrate_DiracDelta_fails():
|
45 |
+
# issue 6427
|
46 |
+
assert integrate(integrate(integrate(
|
47 |
+
DiracDelta(x - y - z), (z, 0, oo)), (y, 0, 1)), (x, 0, 1)) == S.Half
|
48 |
+
|
49 |
+
|
50 |
+
@XFAIL
|
51 |
+
@slow
|
52 |
+
def test_issue_4525():
|
53 |
+
# Warning: takes a long time
|
54 |
+
assert not integrate((x**m * (1 - x)**n * (a + b*x + c*x**2))/(1 + x**2), (x, 0, 1)).has(Integral)
|
55 |
+
|
56 |
+
|
57 |
+
@XFAIL
|
58 |
+
@slow
|
59 |
+
def test_issue_4540():
|
60 |
+
if ON_CI:
|
61 |
+
skip("Too slow for CI.")
|
62 |
+
# Note, this integral is probably nonelementary
|
63 |
+
assert not integrate(
|
64 |
+
(sin(1/x) - x*exp(x)) /
|
65 |
+
((-sin(1/x) + x*exp(x))*x + x*sin(1/x)), x).has(Integral)
|
66 |
+
|
67 |
+
|
68 |
+
@XFAIL
|
69 |
+
@slow
|
70 |
+
def test_issue_4891():
|
71 |
+
# Requires the hypergeometric function.
|
72 |
+
assert not integrate(cos(x)**y, x).has(Integral)
|
73 |
+
|
74 |
+
|
75 |
+
@XFAIL
|
76 |
+
@slow
|
77 |
+
def test_issue_1796a():
|
78 |
+
assert not integrate(exp(2*b*x)*exp(-a*x**2), x).has(Integral)
|
79 |
+
|
80 |
+
|
81 |
+
@XFAIL
|
82 |
+
def test_issue_4895b():
|
83 |
+
assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, -oo, 0)).has(Integral)
|
84 |
+
|
85 |
+
|
86 |
+
@XFAIL
|
87 |
+
def test_issue_4895c():
|
88 |
+
assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, -oo, oo)).has(Integral)
|
89 |
+
|
90 |
+
|
91 |
+
@XFAIL
|
92 |
+
def test_issue_4895d():
|
93 |
+
assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, 0, oo)).has(Integral)
|
94 |
+
|
95 |
+
|
96 |
+
@XFAIL
|
97 |
+
@slow
|
98 |
+
def test_issue_4941():
|
99 |
+
if ON_CI:
|
100 |
+
skip("Too slow for CI.")
|
101 |
+
assert not integrate(sqrt(1 + sinh(x/20)**2), (x, -25, 25)).has(Integral)
|
102 |
+
|
103 |
+
|
104 |
+
@XFAIL
|
105 |
+
def test_issue_4992():
|
106 |
+
# Nonelementary integral. Requires hypergeometric/Meijer-G handling.
|
107 |
+
assert not integrate(log(x) * x**(k - 1) * exp(-x) / gamma(k), (x, 0, oo)).has(Integral)
|
108 |
+
|
109 |
+
|
110 |
+
@XFAIL
|
111 |
+
def test_issue_16396a():
|
112 |
+
i = integrate(1/(1+sqrt(tan(x))), (x, pi/3, pi/6))
|
113 |
+
assert not i.has(Integral)
|
114 |
+
|
115 |
+
|
116 |
+
@XFAIL
|
117 |
+
def test_issue_16396b():
|
118 |
+
i = integrate(x*sin(x)/(1+cos(x)**2), (x, 0, pi))
|
119 |
+
assert not i.has(Integral)
|
120 |
+
|
121 |
+
|
122 |
+
@XFAIL
|
123 |
+
def test_issue_16046():
|
124 |
+
assert integrate(exp(exp(I*x)), [x, 0, 2*pi]) == 2*pi
|
125 |
+
|
126 |
+
|
127 |
+
@XFAIL
|
128 |
+
def test_issue_15925a():
|
129 |
+
assert not integrate(sqrt((1+sin(x))**2+(cos(x))**2), (x, -pi/2, pi/2)).has(Integral)
|
130 |
+
|
131 |
+
|
132 |
+
@XFAIL
|
133 |
+
@slow
|
134 |
+
def test_issue_15925b():
|
135 |
+
if ON_CI:
|
136 |
+
skip("Too slow for CI.")
|
137 |
+
assert not integrate(sqrt((-12*cos(x)**2*sin(x))**2+(12*cos(x)*sin(x)**2)**2),
|
138 |
+
(x, 0, pi/6)).has(Integral)
|
139 |
+
|
140 |
+
|
141 |
+
@XFAIL
|
142 |
+
def test_issue_15925b_manual():
|
143 |
+
assert not integrate(sqrt((-12*cos(x)**2*sin(x))**2+(12*cos(x)*sin(x)**2)**2),
|
144 |
+
(x, 0, pi/6), manual=True).has(Integral)
|
145 |
+
|
146 |
+
|
147 |
+
@XFAIL
|
148 |
+
@slow
|
149 |
+
def test_issue_15227():
|
150 |
+
if ON_CI:
|
151 |
+
skip("Too slow for CI.")
|
152 |
+
i = integrate(log(1-x)*log((1+x)**2)/x, (x, 0, 1))
|
153 |
+
assert not i.has(Integral)
|
154 |
+
# assert i == -5*zeta(3)/4
|
155 |
+
|
156 |
+
|
157 |
+
@XFAIL
|
158 |
+
@slow
|
159 |
+
def test_issue_14716():
|
160 |
+
i = integrate(log(x + 5)*cos(pi*x),(x, S.Half, 1))
|
161 |
+
assert not i.has(Integral)
|
162 |
+
# Mathematica can not solve it either, but
|
163 |
+
# integrate(log(x + 5)*cos(pi*x),(x, S.Half, 1)).transform(x, y - 5).doit()
|
164 |
+
# works
|
165 |
+
# assert i == -log(Rational(11, 2))/pi - Si(pi*Rational(11, 2))/pi + Si(6*pi)/pi
|
166 |
+
|
167 |
+
|
168 |
+
@XFAIL
|
169 |
+
def test_issue_14709a():
|
170 |
+
i = integrate(x*acos(1 - 2*x/h), (x, 0, h))
|
171 |
+
assert not i.has(Integral)
|
172 |
+
# assert i == 5*h**2*pi/16
|
173 |
+
|
174 |
+
|
175 |
+
@slow
|
176 |
+
@XFAIL
|
177 |
+
def test_issue_14398():
|
178 |
+
assert not integrate(exp(x**2)*cos(x), x).has(Integral)
|
179 |
+
|
180 |
+
|
181 |
+
@XFAIL
|
182 |
+
def test_issue_14074():
|
183 |
+
i = integrate(log(sin(x)), (x, 0, pi/2))
|
184 |
+
assert not i.has(Integral)
|
185 |
+
# assert i == -pi*log(2)/2
|
186 |
+
|
187 |
+
|
188 |
+
@XFAIL
|
189 |
+
@slow
|
190 |
+
def test_issue_14078b():
|
191 |
+
i = integrate((atan(4*x)-atan(2*x))/x, (x, 0, oo))
|
192 |
+
assert not i.has(Integral)
|
193 |
+
# assert i == pi*log(2)/2
|
194 |
+
|
195 |
+
|
196 |
+
@XFAIL
|
197 |
+
def test_issue_13792():
|
198 |
+
i = integrate(log(1/x) / (1 - x), (x, 0, 1))
|
199 |
+
assert not i.has(Integral)
|
200 |
+
# assert i in [polylog(2, -exp_polar(I*pi)), pi**2/6]
|
201 |
+
|
202 |
+
|
203 |
+
@XFAIL
|
204 |
+
def test_issue_11845a():
|
205 |
+
assert not integrate(exp(y - x**3), (x, 0, 1)).has(Integral)
|
206 |
+
|
207 |
+
|
208 |
+
@XFAIL
|
209 |
+
def test_issue_11845b():
|
210 |
+
assert not integrate(exp(-y - x**3), (x, 0, 1)).has(Integral)
|
211 |
+
|
212 |
+
|
213 |
+
@XFAIL
|
214 |
+
def test_issue_11813():
|
215 |
+
assert not integrate((a - x)**Rational(-1, 2)*x, (x, 0, a)).has(Integral)
|
216 |
+
|
217 |
+
|
218 |
+
@XFAIL
|
219 |
+
def test_issue_11254c():
|
220 |
+
assert not integrate(sech(x)**2, (x, 0, 1)).has(Integral)
|
221 |
+
|
222 |
+
|
223 |
+
@XFAIL
|
224 |
+
def test_issue_10584():
|
225 |
+
assert not integrate(sqrt(x**2 + 1/x**2), x).has(Integral)
|
226 |
+
|
227 |
+
|
228 |
+
@XFAIL
|
229 |
+
def test_issue_9101():
|
230 |
+
assert not integrate(log(x + sqrt(x**2 + y**2 + z**2)), z).has(Integral)
|
231 |
+
|
232 |
+
|
233 |
+
@XFAIL
|
234 |
+
def test_issue_7147():
|
235 |
+
assert not integrate(x/sqrt(a*x**2 + b*x + c)**3, x).has(Integral)
|
236 |
+
|
237 |
+
|
238 |
+
@XFAIL
|
239 |
+
def test_issue_7109():
|
240 |
+
assert not integrate(sqrt(a**2/(a**2 - x**2)), x).has(Integral)
|
241 |
+
|
242 |
+
|
243 |
+
@XFAIL
|
244 |
+
def test_integrate_Piecewise_rational_over_reals():
|
245 |
+
f = Piecewise(
|
246 |
+
(0, t - 478.515625*pi < 0),
|
247 |
+
(13.2075145209219*pi/(0.000871222*t + 0.995)**2, t - 478.515625*pi >= 0))
|
248 |
+
|
249 |
+
assert abs((integrate(f, (t, 0, oo)) - 15235.9375*pi).evalf()) <= 1e-7
|
250 |
+
|
251 |
+
|
252 |
+
@XFAIL
|
253 |
+
def test_issue_4311_slow():
|
254 |
+
# Not slow when bypassing heurish
|
255 |
+
assert not integrate(x*abs(9-x**2), x).has(Integral)
|
256 |
+
|
257 |
+
@XFAIL
|
258 |
+
def test_issue_20370():
|
259 |
+
a = symbols('a', positive=True)
|
260 |
+
assert integrate((1 + a * cos(x))**-1, (x, 0, 2 * pi)) == (2 * pi / sqrt(1 - a**2))
|
261 |
+
|
262 |
+
|
263 |
+
@XFAIL
|
264 |
+
def test_polylog():
|
265 |
+
# log(1/x)*log(x+1)-polylog(2, -x)
|
266 |
+
assert not integrate(log(1/x)/(x + 1), x).has(Integral)
|
267 |
+
|
268 |
+
|
269 |
+
@XFAIL
|
270 |
+
def test_polylog_manual():
|
271 |
+
# Make sure _parts_rule does not go into an infinite loop here
|
272 |
+
assert not integrate(log(1/x)/(x + 1), x, manual=True).has(Integral)
|
llmeval-env/lib/python3.10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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.summations import Sum
|
2 |
+
from sympy.core.add import Add
|
3 |
+
from sympy.core.function import (Derivative, Function, diff)
|
4 |
+
from sympy.core.numbers import (I, Rational, pi)
|
5 |
+
from sympy.core.relational import Ne
|
6 |
+
from sympy.core.symbol import (Symbol, symbols)
|
7 |
+
from sympy.functions.elementary.exponential import (LambertW, exp, log)
|
8 |
+
from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, tanh)
|
9 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
10 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
11 |
+
from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan)
|
12 |
+
from sympy.functions.special.bessel import (besselj, besselk, bessely, jn)
|
13 |
+
from sympy.functions.special.error_functions import erf
|
14 |
+
from sympy.integrals.integrals import Integral
|
15 |
+
from sympy.simplify.ratsimp import ratsimp
|
16 |
+
from sympy.simplify.simplify import simplify
|
17 |
+
from sympy.integrals.heurisch import components, heurisch, heurisch_wrapper
|
18 |
+
from sympy.testing.pytest import XFAIL, skip, slow, ON_CI
|
19 |
+
from sympy.integrals.integrals import integrate
|
20 |
+
x, y, z, nu = symbols('x,y,z,nu')
|
21 |
+
f = Function('f')
|
22 |
+
|
23 |
+
|
24 |
+
def test_components():
|
25 |
+
assert components(x*y, x) == {x}
|
26 |
+
assert components(1/(x + y), x) == {x}
|
27 |
+
assert components(sin(x), x) == {sin(x), x}
|
28 |
+
assert components(sin(x)*sqrt(log(x)), x) == \
|
29 |
+
{log(x), sin(x), sqrt(log(x)), x}
|
30 |
+
assert components(x*sin(exp(x)*y), x) == \
|
31 |
+
{sin(y*exp(x)), x, exp(x)}
|
32 |
+
assert components(x**Rational(17, 54)/sqrt(sin(x)), x) == \
|
33 |
+
{sin(x), x**Rational(1, 54), sqrt(sin(x)), x}
|
34 |
+
|
35 |
+
assert components(f(x), x) == \
|
36 |
+
{x, f(x)}
|
37 |
+
assert components(Derivative(f(x), x), x) == \
|
38 |
+
{x, f(x), Derivative(f(x), x)}
|
39 |
+
assert components(f(x)*diff(f(x), x), x) == \
|
40 |
+
{x, f(x), Derivative(f(x), x), Derivative(f(x), x)}
|
41 |
+
|
42 |
+
|
43 |
+
def test_issue_10680():
|
44 |
+
assert isinstance(integrate(x**log(x**log(x**log(x))),x), Integral)
|
45 |
+
|
46 |
+
|
47 |
+
def test_issue_21166():
|
48 |
+
assert integrate(sin(x/sqrt(abs(x))), (x, -1, 1)) == 0
|
49 |
+
|
50 |
+
|
51 |
+
def test_heurisch_polynomials():
|
52 |
+
assert heurisch(1, x) == x
|
53 |
+
assert heurisch(x, x) == x**2/2
|
54 |
+
assert heurisch(x**17, x) == x**18/18
|
55 |
+
# For coverage
|
56 |
+
assert heurisch_wrapper(y, x) == y*x
|
57 |
+
|
58 |
+
|
59 |
+
def test_heurisch_fractions():
|
60 |
+
assert heurisch(1/x, x) == log(x)
|
61 |
+
assert heurisch(1/(2 + x), x) == log(x + 2)
|
62 |
+
assert heurisch(1/(x + sin(y)), x) == log(x + sin(y))
|
63 |
+
|
64 |
+
# Up to a constant, where C = pi*I*Rational(5, 12), Mathematica gives identical
|
65 |
+
# result in the first case. The difference is because SymPy changes
|
66 |
+
# signs of expressions without any care.
|
67 |
+
# XXX ^ ^ ^ is this still correct?
|
68 |
+
assert heurisch(5*x**5/(
|
69 |
+
2*x**6 - 5), x) in [5*log(2*x**6 - 5) / 12, 5*log(-2*x**6 + 5) / 12]
|
70 |
+
assert heurisch(5*x**5/(2*x**6 + 5), x) == 5*log(2*x**6 + 5) / 12
|
71 |
+
|
72 |
+
assert heurisch(1/x**2, x) == -1/x
|
73 |
+
assert heurisch(-1/x**5, x) == 1/(4*x**4)
|
74 |
+
|
75 |
+
|
76 |
+
def test_heurisch_log():
|
77 |
+
assert heurisch(log(x), x) == x*log(x) - x
|
78 |
+
assert heurisch(log(3*x), x) == -x + x*log(3) + x*log(x)
|
79 |
+
assert heurisch(log(x**2), x) in [x*log(x**2) - 2*x, 2*x*log(x) - 2*x]
|
80 |
+
|
81 |
+
|
82 |
+
def test_heurisch_exp():
|
83 |
+
assert heurisch(exp(x), x) == exp(x)
|
84 |
+
assert heurisch(exp(-x), x) == -exp(-x)
|
85 |
+
assert heurisch(exp(17*x), x) == exp(17*x) / 17
|
86 |
+
assert heurisch(x*exp(x), x) == x*exp(x) - exp(x)
|
87 |
+
assert heurisch(x*exp(x**2), x) == exp(x**2) / 2
|
88 |
+
|
89 |
+
assert heurisch(exp(-x**2), x) is None
|
90 |
+
|
91 |
+
assert heurisch(2**x, x) == 2**x/log(2)
|
92 |
+
assert heurisch(x*2**x, x) == x*2**x/log(2) - 2**x*log(2)**(-2)
|
93 |
+
|
94 |
+
assert heurisch(Integral(x**z*y, (y, 1, 2), (z, 2, 3)).function, x) == (x*x**z*y)/(z+1)
|
95 |
+
assert heurisch(Sum(x**z, (z, 1, 2)).function, z) == x**z/log(x)
|
96 |
+
|
97 |
+
# https://github.com/sympy/sympy/issues/23707
|
98 |
+
anti = -exp(z)/(sqrt(x - y)*exp(z*sqrt(x - y)) - exp(z*sqrt(x - y)))
|
99 |
+
assert heurisch(exp(z)*exp(-z*sqrt(x - y)), z) == anti
|
100 |
+
|
101 |
+
|
102 |
+
def test_heurisch_trigonometric():
|
103 |
+
assert heurisch(sin(x), x) == -cos(x)
|
104 |
+
assert heurisch(pi*sin(x) + 1, x) == x - pi*cos(x)
|
105 |
+
|
106 |
+
assert heurisch(cos(x), x) == sin(x)
|
107 |
+
assert heurisch(tan(x), x) in [
|
108 |
+
log(1 + tan(x)**2)/2,
|
109 |
+
log(tan(x) + I) + I*x,
|
110 |
+
log(tan(x) - I) - I*x,
|
111 |
+
]
|
112 |
+
|
113 |
+
assert heurisch(sin(x)*sin(y), x) == -cos(x)*sin(y)
|
114 |
+
assert heurisch(sin(x)*sin(y), y) == -cos(y)*sin(x)
|
115 |
+
|
116 |
+
# gives sin(x) in answer when run via setup.py and cos(x) when run via py.test
|
117 |
+
assert heurisch(sin(x)*cos(x), x) in [sin(x)**2 / 2, -cos(x)**2 / 2]
|
118 |
+
assert heurisch(cos(x)/sin(x), x) == log(sin(x))
|
119 |
+
|
120 |
+
assert heurisch(x*sin(7*x), x) == sin(7*x) / 49 - x*cos(7*x) / 7
|
121 |
+
assert heurisch(1/pi/4 * x**2*cos(x), x) == 1/pi/4*(x**2*sin(x) -
|
122 |
+
2*sin(x) + 2*x*cos(x))
|
123 |
+
|
124 |
+
assert heurisch(acos(x/4) * asin(x/4), x) == 2*x - (sqrt(16 - x**2))*asin(x/4) \
|
125 |
+
+ (sqrt(16 - x**2))*acos(x/4) + x*asin(x/4)*acos(x/4)
|
126 |
+
|
127 |
+
assert heurisch(sin(x)/(cos(x)**2+1), x) == -atan(cos(x)) #fixes issue 13723
|
128 |
+
assert heurisch(1/(cos(x)+2), x) == 2*sqrt(3)*atan(sqrt(3)*tan(x/2)/3)/3
|
129 |
+
assert heurisch(2*sin(x)*cos(x)/(sin(x)**4 + 1), x) == atan(sqrt(2)*sin(x)
|
130 |
+
- 1) - atan(sqrt(2)*sin(x) + 1)
|
131 |
+
|
132 |
+
assert heurisch(1/cosh(x), x) == 2*atan(tanh(x/2))
|
133 |
+
|
134 |
+
|
135 |
+
def test_heurisch_hyperbolic():
|
136 |
+
assert heurisch(sinh(x), x) == cosh(x)
|
137 |
+
assert heurisch(cosh(x), x) == sinh(x)
|
138 |
+
|
139 |
+
assert heurisch(x*sinh(x), x) == x*cosh(x) - sinh(x)
|
140 |
+
assert heurisch(x*cosh(x), x) == x*sinh(x) - cosh(x)
|
141 |
+
|
142 |
+
assert heurisch(
|
143 |
+
x*asinh(x/2), x) == x**2*asinh(x/2)/2 + asinh(x/2) - x*sqrt(4 + x**2)/4
|
144 |
+
|
145 |
+
|
146 |
+
def test_heurisch_mixed():
|
147 |
+
assert heurisch(sin(x)*exp(x), x) == exp(x)*sin(x)/2 - exp(x)*cos(x)/2
|
148 |
+
assert heurisch(sin(x/sqrt(-x)), x) == 2*x*cos(x/sqrt(-x))/sqrt(-x) - 2*sin(x/sqrt(-x))
|
149 |
+
|
150 |
+
|
151 |
+
def test_heurisch_radicals():
|
152 |
+
assert heurisch(1/sqrt(x), x) == 2*sqrt(x)
|
153 |
+
assert heurisch(1/sqrt(x)**3, x) == -2/sqrt(x)
|
154 |
+
assert heurisch(sqrt(x)**3, x) == 2*sqrt(x)**5/5
|
155 |
+
|
156 |
+
assert heurisch(sin(x)*sqrt(cos(x)), x) == -2*sqrt(cos(x))**3/3
|
157 |
+
y = Symbol('y')
|
158 |
+
assert heurisch(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \
|
159 |
+
2*sqrt(x)*cos(y*sqrt(x))/y
|
160 |
+
assert heurisch_wrapper(sin(y*sqrt(x)), x) == Piecewise(
|
161 |
+
(-2*sqrt(x)*cos(sqrt(x)*y)/y + 2*sin(sqrt(x)*y)/y**2, Ne(y, 0)),
|
162 |
+
(0, True))
|
163 |
+
y = Symbol('y', positive=True)
|
164 |
+
assert heurisch_wrapper(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \
|
165 |
+
2*sqrt(x)*cos(y*sqrt(x))/y
|
166 |
+
|
167 |
+
|
168 |
+
def test_heurisch_special():
|
169 |
+
assert heurisch(erf(x), x) == x*erf(x) + exp(-x**2)/sqrt(pi)
|
170 |
+
assert heurisch(exp(-x**2)*erf(x), x) == sqrt(pi)*erf(x)**2 / 4
|
171 |
+
|
172 |
+
|
173 |
+
def test_heurisch_symbolic_coeffs():
|
174 |
+
assert heurisch(1/(x + y), x) == log(x + y)
|
175 |
+
assert heurisch(1/(x + sqrt(2)), x) == log(x + sqrt(2))
|
176 |
+
assert simplify(diff(heurisch(log(x + y + z), y), y)) == log(x + y + z)
|
177 |
+
|
178 |
+
|
179 |
+
def test_heurisch_symbolic_coeffs_1130():
|
180 |
+
y = Symbol('y')
|
181 |
+
assert heurisch_wrapper(1/(x**2 + y), x) == Piecewise(
|
182 |
+
(log(x - sqrt(-y))/(2*sqrt(-y)) - log(x + sqrt(-y))/(2*sqrt(-y)),
|
183 |
+
Ne(y, 0)), (-1/x, True))
|
184 |
+
y = Symbol('y', positive=True)
|
185 |
+
assert heurisch_wrapper(1/(x**2 + y), x) == (atan(x/sqrt(y))/sqrt(y))
|
186 |
+
|
187 |
+
|
188 |
+
def test_heurisch_hacking():
|
189 |
+
assert heurisch(sqrt(1 + 7*x**2), x, hints=[]) == \
|
190 |
+
x*sqrt(1 + 7*x**2)/2 + sqrt(7)*asinh(sqrt(7)*x)/14
|
191 |
+
assert heurisch(sqrt(1 - 7*x**2), x, hints=[]) == \
|
192 |
+
x*sqrt(1 - 7*x**2)/2 + sqrt(7)*asin(sqrt(7)*x)/14
|
193 |
+
|
194 |
+
assert heurisch(1/sqrt(1 + 7*x**2), x, hints=[]) == \
|
195 |
+
sqrt(7)*asinh(sqrt(7)*x)/7
|
196 |
+
assert heurisch(1/sqrt(1 - 7*x**2), x, hints=[]) == \
|
197 |
+
sqrt(7)*asin(sqrt(7)*x)/7
|
198 |
+
|
199 |
+
assert heurisch(exp(-7*x**2), x, hints=[]) == \
|
200 |
+
sqrt(7*pi)*erf(sqrt(7)*x)/14
|
201 |
+
|
202 |
+
assert heurisch(1/sqrt(9 - 4*x**2), x, hints=[]) == \
|
203 |
+
asin(x*Rational(2, 3))/2
|
204 |
+
|
205 |
+
assert heurisch(1/sqrt(9 + 4*x**2), x, hints=[]) == \
|
206 |
+
asinh(x*Rational(2, 3))/2
|
207 |
+
|
208 |
+
assert heurisch(1/sqrt(3*x**2-4), x, hints=[]) == \
|
209 |
+
sqrt(3)*log(3*x + sqrt(3)*sqrt(3*x**2 - 4))/3
|
210 |
+
|
211 |
+
|
212 |
+
def test_heurisch_function():
|
213 |
+
assert heurisch(f(x), x) is None
|
214 |
+
|
215 |
+
@XFAIL
|
216 |
+
def test_heurisch_function_derivative():
|
217 |
+
# TODO: it looks like this used to work just by coincindence and
|
218 |
+
# thanks to sloppy implementation. Investigate why this used to
|
219 |
+
# work at all and if support for this can be restored.
|
220 |
+
|
221 |
+
df = diff(f(x), x)
|
222 |
+
|
223 |
+
assert heurisch(f(x)*df, x) == f(x)**2/2
|
224 |
+
assert heurisch(f(x)**2*df, x) == f(x)**3/3
|
225 |
+
assert heurisch(df/f(x), x) == log(f(x))
|
226 |
+
|
227 |
+
|
228 |
+
def test_heurisch_wrapper():
|
229 |
+
f = 1/(y + x)
|
230 |
+
assert heurisch_wrapper(f, x) == log(x + y)
|
231 |
+
f = 1/(y - x)
|
232 |
+
assert heurisch_wrapper(f, x) == -log(x - y)
|
233 |
+
f = 1/((y - x)*(y + x))
|
234 |
+
assert heurisch_wrapper(f, x) == Piecewise(
|
235 |
+
(-log(x - y)/(2*y) + log(x + y)/(2*y), Ne(y, 0)), (1/x, True))
|
236 |
+
# issue 6926
|
237 |
+
f = sqrt(x**2/((y - x)*(y + x)))
|
238 |
+
assert heurisch_wrapper(f, x) == x*sqrt(-x**2/(x**2 - y**2)) \
|
239 |
+
- y**2*sqrt(-x**2/(x**2 - y**2))/x
|
240 |
+
|
241 |
+
|
242 |
+
def test_issue_3609():
|
243 |
+
assert heurisch(1/(x * (1 + log(x)**2)), x) == atan(log(x))
|
244 |
+
|
245 |
+
### These are examples from the Poor Man's Integrator
|
246 |
+
### http://www-sop.inria.fr/cafe/Manuel.Bronstein/pmint/examples/
|
247 |
+
|
248 |
+
|
249 |
+
def test_pmint_rat():
|
250 |
+
# TODO: heurisch() is off by a constant: -3/4. Possibly different permutation
|
251 |
+
# would give the optimal result?
|
252 |
+
|
253 |
+
def drop_const(expr, x):
|
254 |
+
if expr.is_Add:
|
255 |
+
return Add(*[ arg for arg in expr.args if arg.has(x) ])
|
256 |
+
else:
|
257 |
+
return expr
|
258 |
+
|
259 |
+
f = (x**7 - 24*x**4 - 4*x**2 + 8*x - 8)/(x**8 + 6*x**6 + 12*x**4 + 8*x**2)
|
260 |
+
g = (4 + 8*x**2 + 6*x + 3*x**3)/(x**5 + 4*x**3 + 4*x) + log(x)
|
261 |
+
|
262 |
+
assert drop_const(ratsimp(heurisch(f, x)), x) == g
|
263 |
+
|
264 |
+
|
265 |
+
def test_pmint_trig():
|
266 |
+
f = (x - tan(x)) / tan(x)**2 + tan(x)
|
267 |
+
g = -x**2/2 - x/tan(x) + log(tan(x)**2 + 1)/2
|
268 |
+
|
269 |
+
assert heurisch(f, x) == g
|
270 |
+
|
271 |
+
@slow # 8 seconds on 3.4 GHz
|
272 |
+
def test_pmint_logexp():
|
273 |
+
if ON_CI:
|
274 |
+
# See https://github.com/sympy/sympy/pull/12795
|
275 |
+
skip("Too slow for CI.")
|
276 |
+
|
277 |
+
f = (1 + x + x*exp(x))*(x + log(x) + exp(x) - 1)/(x + log(x) + exp(x))**2/x
|
278 |
+
g = log(x + exp(x) + log(x)) + 1/(x + exp(x) + log(x))
|
279 |
+
|
280 |
+
assert ratsimp(heurisch(f, x)) == g
|
281 |
+
|
282 |
+
|
283 |
+
def test_pmint_erf():
|
284 |
+
f = exp(-x**2)*erf(x)/(erf(x)**3 - erf(x)**2 - erf(x) + 1)
|
285 |
+
g = sqrt(pi)*log(erf(x) - 1)/8 - sqrt(pi)*log(erf(x) + 1)/8 - sqrt(pi)/(4*erf(x) - 4)
|
286 |
+
|
287 |
+
assert ratsimp(heurisch(f, x)) == g
|
288 |
+
|
289 |
+
|
290 |
+
def test_pmint_LambertW():
|
291 |
+
f = LambertW(x)
|
292 |
+
g = x*LambertW(x) - x + x/LambertW(x)
|
293 |
+
|
294 |
+
assert heurisch(f, x) == g
|
295 |
+
|
296 |
+
|
297 |
+
def test_pmint_besselj():
|
298 |
+
f = besselj(nu + 1, x)/besselj(nu, x)
|
299 |
+
g = nu*log(x) - log(besselj(nu, x))
|
300 |
+
|
301 |
+
assert heurisch(f, x) == g
|
302 |
+
|
303 |
+
f = (nu*besselj(nu, x) - x*besselj(nu + 1, x))/x
|
304 |
+
g = besselj(nu, x)
|
305 |
+
|
306 |
+
assert heurisch(f, x) == g
|
307 |
+
|
308 |
+
f = jn(nu + 1, x)/jn(nu, x)
|
309 |
+
g = nu*log(x) - log(jn(nu, x))
|
310 |
+
|
311 |
+
assert heurisch(f, x) == g
|
312 |
+
|
313 |
+
@slow
|
314 |
+
def test_pmint_bessel_products():
|
315 |
+
# Note: Derivatives of Bessel functions have many forms.
|
316 |
+
# Recurrence relations are needed for comparisons.
|
317 |
+
if ON_CI:
|
318 |
+
skip("Too slow for CI.")
|
319 |
+
|
320 |
+
f = x*besselj(nu, x)*bessely(nu, 2*x)
|
321 |
+
g = -2*x*besselj(nu, x)*bessely(nu - 1, 2*x)/3 + x*besselj(nu - 1, x)*bessely(nu, 2*x)/3
|
322 |
+
|
323 |
+
assert heurisch(f, x) == g
|
324 |
+
|
325 |
+
f = x*besselj(nu, x)*besselk(nu, 2*x)
|
326 |
+
g = -2*x*besselj(nu, x)*besselk(nu - 1, 2*x)/5 - x*besselj(nu - 1, x)*besselk(nu, 2*x)/5
|
327 |
+
|
328 |
+
assert heurisch(f, x) == g
|
329 |
+
|
330 |
+
@slow # 110 seconds on 3.4 GHz
|
331 |
+
def test_pmint_WrightOmega():
|
332 |
+
if ON_CI:
|
333 |
+
skip("Too slow for CI.")
|
334 |
+
def omega(x):
|
335 |
+
return LambertW(exp(x))
|
336 |
+
|
337 |
+
f = (1 + omega(x) * (2 + cos(omega(x)) * (x + omega(x))))/(1 + omega(x))/(x + omega(x))
|
338 |
+
g = log(x + LambertW(exp(x))) + sin(LambertW(exp(x)))
|
339 |
+
|
340 |
+
assert heurisch(f, x) == g
|
341 |
+
|
342 |
+
|
343 |
+
def test_RR():
|
344 |
+
# Make sure the algorithm does the right thing if the ring is RR. See
|
345 |
+
# issue 8685.
|
346 |
+
assert heurisch(sqrt(1 + 0.25*x**2), x, hints=[]) == \
|
347 |
+
0.5*x*sqrt(0.25*x**2 + 1) + 1.0*asinh(0.5*x)
|
348 |
+
|
349 |
+
# TODO: convert the rest of PMINT tests:
|
350 |
+
# Airy functions
|
351 |
+
# f = (x - AiryAi(x)*AiryAi(1, x)) / (x**2 - AiryAi(x)**2)
|
352 |
+
# g = Rational(1,2)*ln(x + AiryAi(x)) + Rational(1,2)*ln(x - AiryAi(x))
|
353 |
+
# f = x**2 * AiryAi(x)
|
354 |
+
# g = -AiryAi(x) + AiryAi(1, x)*x
|
355 |
+
# Whittaker functions
|
356 |
+
# f = WhittakerW(mu + 1, nu, x) / (WhittakerW(mu, nu, x) * x)
|
357 |
+
# g = x/2 - mu*ln(x) - ln(WhittakerW(mu, nu, x))
|
358 |
+
|
359 |
+
|
360 |
+
def test_issue_22527():
|
361 |
+
t, R = symbols(r't R')
|
362 |
+
z = Function('z')(t)
|
363 |
+
def f(x):
|
364 |
+
return x/sqrt(R**2 - x**2)
|
365 |
+
Uz = integrate(f(z), z)
|
366 |
+
Ut = integrate(f(t), t)
|
367 |
+
assert Ut == Uz.subs(z, t)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_integrals.py
ADDED
@@ -0,0 +1,2073 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from sympy.concrete.summations import (Sum, summation)
|
3 |
+
from sympy.core.add import Add
|
4 |
+
from sympy.core.containers import Tuple
|
5 |
+
from sympy.core.expr import Expr
|
6 |
+
from sympy.core.function import (Derivative, Function, Lambda, diff)
|
7 |
+
from sympy.core import EulerGamma
|
8 |
+
from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
|
9 |
+
from sympy.core.relational import (Eq, Ne)
|
10 |
+
from sympy.core.singleton import S
|
11 |
+
from sympy.core.symbol import (Symbol, symbols)
|
12 |
+
from sympy.core.sympify import sympify
|
13 |
+
from sympy.functions.elementary.complexes import (Abs, im, polar_lift, re, sign)
|
14 |
+
from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
|
15 |
+
from sympy.functions.elementary.hyperbolic import (acosh, asinh, cosh, coth, csch, sinh, tanh, sech)
|
16 |
+
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
|
17 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
18 |
+
from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, sinc, tan, sec)
|
19 |
+
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
|
20 |
+
from sympy.functions.special.error_functions import (Ci, Ei, Si, erf, erfc, erfi, fresnelc, li)
|
21 |
+
from sympy.functions.special.gamma_functions import (gamma, polygamma)
|
22 |
+
from sympy.functions.special.hyper import (hyper, meijerg)
|
23 |
+
from sympy.functions.special.singularity_functions import SingularityFunction
|
24 |
+
from sympy.functions.special.zeta_functions import lerchphi
|
25 |
+
from sympy.integrals.integrals import integrate
|
26 |
+
from sympy.logic.boolalg import And
|
27 |
+
from sympy.matrices.dense import Matrix
|
28 |
+
from sympy.polys.polytools import (Poly, factor)
|
29 |
+
from sympy.printing.str import sstr
|
30 |
+
from sympy.series.order import O
|
31 |
+
from sympy.sets.sets import Interval
|
32 |
+
from sympy.simplify.gammasimp import gammasimp
|
33 |
+
from sympy.simplify.simplify import simplify
|
34 |
+
from sympy.simplify.trigsimp import trigsimp
|
35 |
+
from sympy.tensor.indexed import (Idx, IndexedBase)
|
36 |
+
from sympy.core.expr import unchanged
|
37 |
+
from sympy.functions.elementary.integers import floor
|
38 |
+
from sympy.integrals.integrals import Integral
|
39 |
+
from sympy.integrals.risch import NonElementaryIntegral
|
40 |
+
from sympy.physics import units
|
41 |
+
from sympy.testing.pytest import (raises, slow, skip, ON_CI,
|
42 |
+
warns_deprecated_sympy, warns)
|
43 |
+
from sympy.utilities.exceptions import SymPyDeprecationWarning
|
44 |
+
from sympy.core.random import verify_numerically
|
45 |
+
|
46 |
+
|
47 |
+
x, y, z, a, b, c, d, e, s, t, x_1, x_2 = symbols('x y z a b c d e s t x_1 x_2')
|
48 |
+
n = Symbol('n', integer=True)
|
49 |
+
f = Function('f')
|
50 |
+
|
51 |
+
|
52 |
+
def NS(e, n=15, **options):
|
53 |
+
return sstr(sympify(e).evalf(n, **options), full_prec=True)
|
54 |
+
|
55 |
+
|
56 |
+
def test_poly_deprecated():
|
57 |
+
p = Poly(2*x, x)
|
58 |
+
assert p.integrate(x) == Poly(x**2, x, domain='QQ')
|
59 |
+
# The stacklevel is based on Integral(Poly)
|
60 |
+
with warns(SymPyDeprecationWarning, test_stacklevel=False):
|
61 |
+
integrate(p, x)
|
62 |
+
with warns(SymPyDeprecationWarning, test_stacklevel=False):
|
63 |
+
Integral(p, (x,))
|
64 |
+
|
65 |
+
|
66 |
+
@slow
|
67 |
+
def test_principal_value():
|
68 |
+
g = 1 / x
|
69 |
+
assert Integral(g, (x, -oo, oo)).principal_value() == 0
|
70 |
+
assert Integral(g, (y, -oo, oo)).principal_value() == oo * sign(1 / x)
|
71 |
+
raises(ValueError, lambda: Integral(g, (x)).principal_value())
|
72 |
+
raises(ValueError, lambda: Integral(g).principal_value())
|
73 |
+
|
74 |
+
l = 1 / ((x ** 3) - 1)
|
75 |
+
assert Integral(l, (x, -oo, oo)).principal_value().together() == -sqrt(3)*pi/3
|
76 |
+
raises(ValueError, lambda: Integral(l, (x, -oo, 1)).principal_value())
|
77 |
+
|
78 |
+
d = 1 / (x ** 2 - 1)
|
79 |
+
assert Integral(d, (x, -oo, oo)).principal_value() == 0
|
80 |
+
assert Integral(d, (x, -2, 2)).principal_value() == -log(3)
|
81 |
+
|
82 |
+
v = x / (x ** 2 - 1)
|
83 |
+
assert Integral(v, (x, -oo, oo)).principal_value() == 0
|
84 |
+
assert Integral(v, (x, -2, 2)).principal_value() == 0
|
85 |
+
|
86 |
+
s = x ** 2 / (x ** 2 - 1)
|
87 |
+
assert Integral(s, (x, -oo, oo)).principal_value() is oo
|
88 |
+
assert Integral(s, (x, -2, 2)).principal_value() == -log(3) + 4
|
89 |
+
|
90 |
+
f = 1 / ((x ** 2 - 1) * (1 + x ** 2))
|
91 |
+
assert Integral(f, (x, -oo, oo)).principal_value() == -pi / 2
|
92 |
+
assert Integral(f, (x, -2, 2)).principal_value() == -atan(2) - log(3) / 2
|
93 |
+
|
94 |
+
|
95 |
+
def diff_test(i):
|
96 |
+
"""Return the set of symbols, s, which were used in testing that
|
97 |
+
i.diff(s) agrees with i.doit().diff(s). If there is an error then
|
98 |
+
the assertion will fail, causing the test to fail."""
|
99 |
+
syms = i.free_symbols
|
100 |
+
for s in syms:
|
101 |
+
assert (i.diff(s).doit() - i.doit().diff(s)).expand() == 0
|
102 |
+
return syms
|
103 |
+
|
104 |
+
|
105 |
+
def test_improper_integral():
|
106 |
+
assert integrate(log(x), (x, 0, 1)) == -1
|
107 |
+
assert integrate(x**(-2), (x, 1, oo)) == 1
|
108 |
+
assert integrate(1/(1 + exp(x)), (x, 0, oo)) == log(2)
|
109 |
+
|
110 |
+
|
111 |
+
def test_constructor():
|
112 |
+
# this is shared by Sum, so testing Integral's constructor
|
113 |
+
# is equivalent to testing Sum's
|
114 |
+
s1 = Integral(n, n)
|
115 |
+
assert s1.limits == (Tuple(n),)
|
116 |
+
s2 = Integral(n, (n,))
|
117 |
+
assert s2.limits == (Tuple(n),)
|
118 |
+
s3 = Integral(Sum(x, (x, 1, y)))
|
119 |
+
assert s3.limits == (Tuple(y),)
|
120 |
+
s4 = Integral(n, Tuple(n,))
|
121 |
+
assert s4.limits == (Tuple(n),)
|
122 |
+
|
123 |
+
s5 = Integral(n, (n, Interval(1, 2)))
|
124 |
+
assert s5.limits == (Tuple(n, 1, 2),)
|
125 |
+
|
126 |
+
# Testing constructor with inequalities:
|
127 |
+
s6 = Integral(n, n > 10)
|
128 |
+
assert s6.limits == (Tuple(n, 10, oo),)
|
129 |
+
s7 = Integral(n, (n > 2) & (n < 5))
|
130 |
+
assert s7.limits == (Tuple(n, 2, 5),)
|
131 |
+
|
132 |
+
|
133 |
+
def test_basics():
|
134 |
+
|
135 |
+
assert Integral(0, x) != 0
|
136 |
+
assert Integral(x, (x, 1, 1)) != 0
|
137 |
+
assert Integral(oo, x) != oo
|
138 |
+
assert Integral(S.NaN, x) is S.NaN
|
139 |
+
|
140 |
+
assert diff(Integral(y, y), x) == 0
|
141 |
+
assert diff(Integral(x, (x, 0, 1)), x) == 0
|
142 |
+
assert diff(Integral(x, x), x) == x
|
143 |
+
assert diff(Integral(t, (t, 0, x)), x) == x
|
144 |
+
|
145 |
+
e = (t + 1)**2
|
146 |
+
assert diff(integrate(e, (t, 0, x)), x) == \
|
147 |
+
diff(Integral(e, (t, 0, x)), x).doit().expand() == \
|
148 |
+
((1 + x)**2).expand()
|
149 |
+
assert diff(integrate(e, (t, 0, x)), t) == \
|
150 |
+
diff(Integral(e, (t, 0, x)), t) == 0
|
151 |
+
assert diff(integrate(e, (t, 0, x)), a) == \
|
152 |
+
diff(Integral(e, (t, 0, x)), a) == 0
|
153 |
+
assert diff(integrate(e, t), a) == diff(Integral(e, t), a) == 0
|
154 |
+
|
155 |
+
assert integrate(e, (t, a, x)).diff(x) == \
|
156 |
+
Integral(e, (t, a, x)).diff(x).doit().expand()
|
157 |
+
assert Integral(e, (t, a, x)).diff(x).doit() == ((1 + x)**2)
|
158 |
+
assert integrate(e, (t, x, a)).diff(x).doit() == (-(1 + x)**2).expand()
|
159 |
+
|
160 |
+
assert integrate(t**2, (t, x, 2*x)).diff(x) == 7*x**2
|
161 |
+
|
162 |
+
assert Integral(x, x).atoms() == {x}
|
163 |
+
assert Integral(f(x), (x, 0, 1)).atoms() == {S.Zero, S.One, x}
|
164 |
+
|
165 |
+
assert diff_test(Integral(x, (x, 3*y))) == {y}
|
166 |
+
assert diff_test(Integral(x, (a, 3*y))) == {x, y}
|
167 |
+
|
168 |
+
assert integrate(x, (x, oo, oo)) == 0 #issue 8171
|
169 |
+
assert integrate(x, (x, -oo, -oo)) == 0
|
170 |
+
|
171 |
+
# sum integral of terms
|
172 |
+
assert integrate(y + x + exp(x), x) == x*y + x**2/2 + exp(x)
|
173 |
+
|
174 |
+
assert Integral(x).is_commutative
|
175 |
+
n = Symbol('n', commutative=False)
|
176 |
+
assert Integral(n + x, x).is_commutative is False
|
177 |
+
|
178 |
+
|
179 |
+
def test_diff_wrt():
|
180 |
+
class Test(Expr):
|
181 |
+
_diff_wrt = True
|
182 |
+
is_commutative = True
|
183 |
+
|
184 |
+
t = Test()
|
185 |
+
assert integrate(t + 1, t) == t**2/2 + t
|
186 |
+
assert integrate(t + 1, (t, 0, 1)) == Rational(3, 2)
|
187 |
+
|
188 |
+
raises(ValueError, lambda: integrate(x + 1, x + 1))
|
189 |
+
raises(ValueError, lambda: integrate(x + 1, (x + 1, 0, 1)))
|
190 |
+
|
191 |
+
|
192 |
+
def test_basics_multiple():
|
193 |
+
assert diff_test(Integral(x, (x, 3*x, 5*y), (y, x, 2*x))) == {x}
|
194 |
+
assert diff_test(Integral(x, (x, 5*y), (y, x, 2*x))) == {x}
|
195 |
+
assert diff_test(Integral(x, (x, 5*y), (y, y, 2*x))) == {x, y}
|
196 |
+
assert diff_test(Integral(y, y, x)) == {x, y}
|
197 |
+
assert diff_test(Integral(y*x, x, y)) == {x, y}
|
198 |
+
assert diff_test(Integral(x + y, y, (y, 1, x))) == {x}
|
199 |
+
assert diff_test(Integral(x + y, (x, x, y), (y, y, x))) == {x, y}
|
200 |
+
|
201 |
+
|
202 |
+
def test_conjugate_transpose():
|
203 |
+
A, B = symbols("A B", commutative=False)
|
204 |
+
|
205 |
+
x = Symbol("x", complex=True)
|
206 |
+
p = Integral(A*B, (x,))
|
207 |
+
assert p.adjoint().doit() == p.doit().adjoint()
|
208 |
+
assert p.conjugate().doit() == p.doit().conjugate()
|
209 |
+
assert p.transpose().doit() == p.doit().transpose()
|
210 |
+
|
211 |
+
x = Symbol("x", real=True)
|
212 |
+
p = Integral(A*B, (x,))
|
213 |
+
assert p.adjoint().doit() == p.doit().adjoint()
|
214 |
+
assert p.conjugate().doit() == p.doit().conjugate()
|
215 |
+
assert p.transpose().doit() == p.doit().transpose()
|
216 |
+
|
217 |
+
|
218 |
+
def test_integration():
|
219 |
+
assert integrate(0, (t, 0, x)) == 0
|
220 |
+
assert integrate(3, (t, 0, x)) == 3*x
|
221 |
+
assert integrate(t, (t, 0, x)) == x**2/2
|
222 |
+
assert integrate(3*t, (t, 0, x)) == 3*x**2/2
|
223 |
+
assert integrate(3*t**2, (t, 0, x)) == x**3
|
224 |
+
assert integrate(1/t, (t, 1, x)) == log(x)
|
225 |
+
assert integrate(-1/t**2, (t, 1, x)) == 1/x - 1
|
226 |
+
assert integrate(t**2 + 5*t - 8, (t, 0, x)) == x**3/3 + 5*x**2/2 - 8*x
|
227 |
+
assert integrate(x**2, x) == x**3/3
|
228 |
+
assert integrate((3*t*x)**5, x) == (3*t)**5 * x**6 / 6
|
229 |
+
|
230 |
+
b = Symbol("b")
|
231 |
+
c = Symbol("c")
|
232 |
+
assert integrate(a*t, (t, 0, x)) == a*x**2/2
|
233 |
+
assert integrate(a*t**4, (t, 0, x)) == a*x**5/5
|
234 |
+
assert integrate(a*t**2 + b*t + c, (t, 0, x)) == a*x**3/3 + b*x**2/2 + c*x
|
235 |
+
|
236 |
+
|
237 |
+
def test_multiple_integration():
|
238 |
+
assert integrate((x**2)*(y**2), (x, 0, 1), (y, -1, 2)) == Rational(1)
|
239 |
+
assert integrate((y**2)*(x**2), x, y) == Rational(1, 9)*(x**3)*(y**3)
|
240 |
+
assert integrate(1/(x + 3)/(1 + x)**3, x) == \
|
241 |
+
log(3 + x)*Rational(-1, 8) + log(1 + x)*Rational(1, 8) + x/(4 + 8*x + 4*x**2)
|
242 |
+
assert integrate(sin(x*y)*y, (x, 0, 1), (y, 0, 1)) == -sin(1) + 1
|
243 |
+
|
244 |
+
|
245 |
+
def test_issue_3532():
|
246 |
+
assert integrate(exp(-x), (x, 0, oo)) == 1
|
247 |
+
|
248 |
+
|
249 |
+
def test_issue_3560():
|
250 |
+
assert integrate(sqrt(x)**3, x) == 2*sqrt(x)**5/5
|
251 |
+
assert integrate(sqrt(x), x) == 2*sqrt(x)**3/3
|
252 |
+
assert integrate(1/sqrt(x)**3, x) == -2/sqrt(x)
|
253 |
+
|
254 |
+
|
255 |
+
def test_issue_18038():
|
256 |
+
raises(AttributeError, lambda: integrate((x, x)))
|
257 |
+
|
258 |
+
|
259 |
+
def test_integrate_poly():
|
260 |
+
p = Poly(x + x**2*y + y**3, x, y)
|
261 |
+
|
262 |
+
# The stacklevel is based on Integral(Poly)
|
263 |
+
with warns_deprecated_sympy():
|
264 |
+
qx = Integral(p, x)
|
265 |
+
with warns(SymPyDeprecationWarning, test_stacklevel=False):
|
266 |
+
qx = integrate(p, x)
|
267 |
+
with warns(SymPyDeprecationWarning, test_stacklevel=False):
|
268 |
+
qy = integrate(p, y)
|
269 |
+
|
270 |
+
assert isinstance(qx, Poly) is True
|
271 |
+
assert isinstance(qy, Poly) is True
|
272 |
+
|
273 |
+
assert qx.gens == (x, y)
|
274 |
+
assert qy.gens == (x, y)
|
275 |
+
|
276 |
+
assert qx.as_expr() == x**2/2 + x**3*y/3 + x*y**3
|
277 |
+
assert qy.as_expr() == x*y + x**2*y**2/2 + y**4/4
|
278 |
+
|
279 |
+
|
280 |
+
def test_integrate_poly_definite():
|
281 |
+
p = Poly(x + x**2*y + y**3, x, y)
|
282 |
+
|
283 |
+
with warns_deprecated_sympy():
|
284 |
+
Qx = Integral(p, (x, 0, 1))
|
285 |
+
with warns(SymPyDeprecationWarning, test_stacklevel=False):
|
286 |
+
Qx = integrate(p, (x, 0, 1))
|
287 |
+
with warns(SymPyDeprecationWarning, test_stacklevel=False):
|
288 |
+
Qy = integrate(p, (y, 0, pi))
|
289 |
+
|
290 |
+
assert isinstance(Qx, Poly) is True
|
291 |
+
assert isinstance(Qy, Poly) is True
|
292 |
+
|
293 |
+
assert Qx.gens == (y,)
|
294 |
+
assert Qy.gens == (x,)
|
295 |
+
|
296 |
+
assert Qx.as_expr() == S.Half + y/3 + y**3
|
297 |
+
assert Qy.as_expr() == pi**4/4 + pi*x + pi**2*x**2/2
|
298 |
+
|
299 |
+
|
300 |
+
def test_integrate_omit_var():
|
301 |
+
y = Symbol('y')
|
302 |
+
|
303 |
+
assert integrate(x) == x**2/2
|
304 |
+
|
305 |
+
raises(ValueError, lambda: integrate(2))
|
306 |
+
raises(ValueError, lambda: integrate(x*y))
|
307 |
+
|
308 |
+
|
309 |
+
def test_integrate_poly_accurately():
|
310 |
+
y = Symbol('y')
|
311 |
+
assert integrate(x*sin(y), x) == x**2*sin(y)/2
|
312 |
+
|
313 |
+
# when passed to risch_norman, this will be a CPU hog, so this really
|
314 |
+
# checks, that integrated function is recognized as polynomial
|
315 |
+
assert integrate(x**1000*sin(y), x) == x**1001*sin(y)/1001
|
316 |
+
|
317 |
+
|
318 |
+
def test_issue_3635():
|
319 |
+
y = Symbol('y')
|
320 |
+
assert integrate(x**2, y) == x**2*y
|
321 |
+
assert integrate(x**2, (y, -1, 1)) == 2*x**2
|
322 |
+
|
323 |
+
# works in SymPy and py.test but hangs in `setup.py test`
|
324 |
+
|
325 |
+
|
326 |
+
def test_integrate_linearterm_pow():
|
327 |
+
# check integrate((a*x+b)^c, x) -- issue 3499
|
328 |
+
y = Symbol('y', positive=True)
|
329 |
+
# TODO: Remove conds='none' below, let the assumption take care of it.
|
330 |
+
assert integrate(x**y, x, conds='none') == x**(y + 1)/(y + 1)
|
331 |
+
assert integrate((exp(y)*x + 1/y)**(1 + sin(y)), x, conds='none') == \
|
332 |
+
exp(-y)*(exp(y)*x + 1/y)**(2 + sin(y)) / (2 + sin(y))
|
333 |
+
|
334 |
+
|
335 |
+
def test_issue_3618():
|
336 |
+
assert integrate(pi*sqrt(x), x) == 2*pi*sqrt(x)**3/3
|
337 |
+
assert integrate(pi*sqrt(x) + E*sqrt(x)**3, x) == \
|
338 |
+
2*pi*sqrt(x)**3/3 + 2*E *sqrt(x)**5/5
|
339 |
+
|
340 |
+
|
341 |
+
def test_issue_3623():
|
342 |
+
assert integrate(cos((n + 1)*x), x) == Piecewise(
|
343 |
+
(sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True))
|
344 |
+
assert integrate(cos((n - 1)*x), x) == Piecewise(
|
345 |
+
(sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True))
|
346 |
+
assert integrate(cos((n + 1)*x) + cos((n - 1)*x), x) == \
|
347 |
+
Piecewise((sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True)) + \
|
348 |
+
Piecewise((sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True))
|
349 |
+
|
350 |
+
|
351 |
+
def test_issue_3664():
|
352 |
+
n = Symbol('n', integer=True, nonzero=True)
|
353 |
+
assert integrate(-1./2 * x * sin(n * pi * x/2), [x, -2, 0]) == \
|
354 |
+
2.0*cos(pi*n)/(pi*n)
|
355 |
+
assert integrate(x * sin(n * pi * x/2) * Rational(-1, 2), [x, -2, 0]) == \
|
356 |
+
2*cos(pi*n)/(pi*n)
|
357 |
+
|
358 |
+
|
359 |
+
def test_issue_3679():
|
360 |
+
# definite integration of rational functions gives wrong answers
|
361 |
+
assert NS(Integral(1/(x**2 - 8*x + 17), (x, 2, 4))) == '1.10714871779409'
|
362 |
+
|
363 |
+
|
364 |
+
def test_issue_3686(): # remove this when fresnel integrals are implemented
|
365 |
+
from sympy.core.function import expand_func
|
366 |
+
from sympy.functions.special.error_functions import fresnels
|
367 |
+
assert expand_func(integrate(sin(x**2), x)) == \
|
368 |
+
sqrt(2)*sqrt(pi)*fresnels(sqrt(2)*x/sqrt(pi))/2
|
369 |
+
|
370 |
+
|
371 |
+
def test_integrate_units():
|
372 |
+
m = units.m
|
373 |
+
s = units.s
|
374 |
+
assert integrate(x * m/s, (x, 1*s, 5*s)) == 12*m*s
|
375 |
+
|
376 |
+
|
377 |
+
def test_transcendental_functions():
|
378 |
+
assert integrate(LambertW(2*x), x) == \
|
379 |
+
-x + x*LambertW(2*x) + x/LambertW(2*x)
|
380 |
+
|
381 |
+
|
382 |
+
def test_log_polylog():
|
383 |
+
assert integrate(log(1 - x)/x, (x, 0, 1)) == -pi**2/6
|
384 |
+
assert integrate(log(x)*(1 - x)**(-1), (x, 0, 1)) == -pi**2/6
|
385 |
+
|
386 |
+
|
387 |
+
def test_issue_3740():
|
388 |
+
f = 4*log(x) - 2*log(x)**2
|
389 |
+
fid = diff(integrate(f, x), x)
|
390 |
+
assert abs(f.subs(x, 42).evalf() - fid.subs(x, 42).evalf()) < 1e-10
|
391 |
+
|
392 |
+
|
393 |
+
def test_issue_3788():
|
394 |
+
assert integrate(1/(1 + x**2), x) == atan(x)
|
395 |
+
|
396 |
+
|
397 |
+
def test_issue_3952():
|
398 |
+
f = sin(x)
|
399 |
+
assert integrate(f, x) == -cos(x)
|
400 |
+
raises(ValueError, lambda: integrate(f, 2*x))
|
401 |
+
|
402 |
+
|
403 |
+
def test_issue_4516():
|
404 |
+
assert integrate(2**x - 2*x, x) == 2**x/log(2) - x**2
|
405 |
+
|
406 |
+
|
407 |
+
def test_issue_7450():
|
408 |
+
ans = integrate(exp(-(1 + I)*x), (x, 0, oo))
|
409 |
+
assert re(ans) == S.Half and im(ans) == Rational(-1, 2)
|
410 |
+
|
411 |
+
|
412 |
+
def test_issue_8623():
|
413 |
+
assert integrate((1 + cos(2*x)) / (3 - 2*cos(2*x)), (x, 0, pi)) == -pi/2 + sqrt(5)*pi/2
|
414 |
+
assert integrate((1 + cos(2*x))/(3 - 2*cos(2*x))) == -x/2 + sqrt(5)*(atan(sqrt(5)*tan(x)) + \
|
415 |
+
pi*floor((x - pi/2)/pi))/2
|
416 |
+
|
417 |
+
|
418 |
+
def test_issue_9569():
|
419 |
+
assert integrate(1 / (2 - cos(x)), (x, 0, pi)) == pi/sqrt(3)
|
420 |
+
assert integrate(1/(2 - cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)) + pi*floor((x/2 - pi/2)/pi))/3
|
421 |
+
|
422 |
+
|
423 |
+
def test_issue_13733():
|
424 |
+
s = Symbol('s', positive=True)
|
425 |
+
pz = exp(-(z - y)**2/(2*s*s))/sqrt(2*pi*s*s)
|
426 |
+
pzgx = integrate(pz, (z, x, oo))
|
427 |
+
assert integrate(pzgx, (x, 0, oo)) == sqrt(2)*s*exp(-y**2/(2*s**2))/(2*sqrt(pi)) + \
|
428 |
+
y*erf(sqrt(2)*y/(2*s))/2 + y/2
|
429 |
+
|
430 |
+
|
431 |
+
def test_issue_13749():
|
432 |
+
assert integrate(1 / (2 + cos(x)), (x, 0, pi)) == pi/sqrt(3)
|
433 |
+
assert integrate(1/(2 + cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)/3) + pi*floor((x/2 - pi/2)/pi))/3
|
434 |
+
|
435 |
+
|
436 |
+
def test_issue_18133():
|
437 |
+
assert integrate(exp(x)/(1 + x)**2, x) == NonElementaryIntegral(exp(x)/(x + 1)**2, x)
|
438 |
+
|
439 |
+
|
440 |
+
def test_issue_21741():
|
441 |
+
a = Float('3999999.9999999995', precision=53)
|
442 |
+
b = Float('2.5000000000000004e-7', precision=53)
|
443 |
+
r = Piecewise((b*I*exp(-a*I*pi*t*y)*exp(-a*I*pi*x*z)/(pi*x),
|
444 |
+
Ne(1.0*pi*x*exp(a*I*pi*t*y), 0)),
|
445 |
+
(z*exp(-a*I*pi*t*y), True))
|
446 |
+
fun = E**((-2*I*pi*(z*x+t*y))/(500*10**(-9)))
|
447 |
+
assert integrate(fun, z) == r
|
448 |
+
|
449 |
+
|
450 |
+
def test_matrices():
|
451 |
+
M = Matrix(2, 2, lambda i, j: (i + j + 1)*sin((i + j + 1)*x))
|
452 |
+
|
453 |
+
assert integrate(M, x) == Matrix([
|
454 |
+
[-cos(x), -cos(2*x)],
|
455 |
+
[-cos(2*x), -cos(3*x)],
|
456 |
+
])
|
457 |
+
|
458 |
+
|
459 |
+
def test_integrate_functions():
|
460 |
+
# issue 4111
|
461 |
+
assert integrate(f(x), x) == Integral(f(x), x)
|
462 |
+
assert integrate(f(x), (x, 0, 1)) == Integral(f(x), (x, 0, 1))
|
463 |
+
assert integrate(f(x)*diff(f(x), x), x) == f(x)**2/2
|
464 |
+
assert integrate(diff(f(x), x) / f(x), x) == log(f(x))
|
465 |
+
|
466 |
+
|
467 |
+
def test_integrate_derivatives():
|
468 |
+
assert integrate(Derivative(f(x), x), x) == f(x)
|
469 |
+
assert integrate(Derivative(f(y), y), x) == x*Derivative(f(y), y)
|
470 |
+
assert integrate(Derivative(f(x), x)**2, x) == \
|
471 |
+
Integral(Derivative(f(x), x)**2, x)
|
472 |
+
|
473 |
+
|
474 |
+
def test_transform():
|
475 |
+
a = Integral(x**2 + 1, (x, -1, 2))
|
476 |
+
fx = x
|
477 |
+
fy = 3*y + 1
|
478 |
+
assert a.doit() == a.transform(fx, fy).doit()
|
479 |
+
assert a.transform(fx, fy).transform(fy, fx) == a
|
480 |
+
fx = 3*x + 1
|
481 |
+
fy = y
|
482 |
+
assert a.transform(fx, fy).transform(fy, fx) == a
|
483 |
+
a = Integral(sin(1/x), (x, 0, 1))
|
484 |
+
assert a.transform(x, 1/y) == Integral(sin(y)/y**2, (y, 1, oo))
|
485 |
+
assert a.transform(x, 1/y).transform(y, 1/x) == a
|
486 |
+
a = Integral(exp(-x**2), (x, -oo, oo))
|
487 |
+
assert a.transform(x, 2*y) == Integral(2*exp(-4*y**2), (y, -oo, oo))
|
488 |
+
# < 3 arg limit handled properly
|
489 |
+
assert Integral(x, x).transform(x, a*y).doit() == \
|
490 |
+
Integral(y*a**2, y).doit()
|
491 |
+
_3 = S(3)
|
492 |
+
assert Integral(x, (x, 0, -_3)).transform(x, 1/y).doit() == \
|
493 |
+
Integral(-1/x**3, (x, -oo, -1/_3)).doit()
|
494 |
+
assert Integral(x, (x, 0, _3)).transform(x, 1/y) == \
|
495 |
+
Integral(y**(-3), (y, 1/_3, oo))
|
496 |
+
# issue 8400
|
497 |
+
i = Integral(x + y, (x, 1, 2), (y, 1, 2))
|
498 |
+
assert i.transform(x, (x + 2*y, x)).doit() == \
|
499 |
+
i.transform(x, (x + 2*z, x)).doit() == 3
|
500 |
+
|
501 |
+
i = Integral(x, (x, a, b))
|
502 |
+
assert i.transform(x, 2*s) == Integral(4*s, (s, a/2, b/2))
|
503 |
+
raises(ValueError, lambda: i.transform(x, 1))
|
504 |
+
raises(ValueError, lambda: i.transform(x, s*t))
|
505 |
+
raises(ValueError, lambda: i.transform(x, -s))
|
506 |
+
raises(ValueError, lambda: i.transform(x, (s, t)))
|
507 |
+
raises(ValueError, lambda: i.transform(2*x, 2*s))
|
508 |
+
|
509 |
+
i = Integral(x**2, (x, 1, 2))
|
510 |
+
raises(ValueError, lambda: i.transform(x**2, s))
|
511 |
+
|
512 |
+
am = Symbol('a', negative=True)
|
513 |
+
bp = Symbol('b', positive=True)
|
514 |
+
i = Integral(x, (x, bp, am))
|
515 |
+
i.transform(x, 2*s)
|
516 |
+
assert i.transform(x, 2*s) == Integral(-4*s, (s, am/2, bp/2))
|
517 |
+
|
518 |
+
i = Integral(x, (x, a))
|
519 |
+
assert i.transform(x, 2*s) == Integral(4*s, (s, a/2))
|
520 |
+
|
521 |
+
|
522 |
+
def test_issue_4052():
|
523 |
+
f = S.Half*asin(x) + x*sqrt(1 - x**2)/2
|
524 |
+
|
525 |
+
assert integrate(cos(asin(x)), x) == f
|
526 |
+
assert integrate(sin(acos(x)), x) == f
|
527 |
+
|
528 |
+
|
529 |
+
@slow
|
530 |
+
def test_evalf_integrals():
|
531 |
+
assert NS(Integral(x, (x, 2, 5)), 15) == '10.5000000000000'
|
532 |
+
gauss = Integral(exp(-x**2), (x, -oo, oo))
|
533 |
+
assert NS(gauss, 15) == '1.77245385090552'
|
534 |
+
assert NS(gauss**2 - pi + E*Rational(
|
535 |
+
1, 10**20), 15) in ('2.71828182845904e-20', '2.71828182845905e-20')
|
536 |
+
# A monster of an integral from http://mathworld.wolfram.com/DefiniteIntegral.html
|
537 |
+
t = Symbol('t')
|
538 |
+
a = 8*sqrt(3)/(1 + 3*t**2)
|
539 |
+
b = 16*sqrt(2)*(3*t + 1)*sqrt(4*t**2 + t + 1)**3
|
540 |
+
c = (3*t**2 + 1)*(11*t**2 + 2*t + 3)**2
|
541 |
+
d = sqrt(2)*(249*t**2 + 54*t + 65)/(11*t**2 + 2*t + 3)**2
|
542 |
+
f = a - b/c - d
|
543 |
+
assert NS(Integral(f, (t, 0, 1)), 50) == \
|
544 |
+
NS((3*sqrt(2) - 49*pi + 162*atan(sqrt(2)))/12, 50)
|
545 |
+
# http://mathworld.wolfram.com/VardisIntegral.html
|
546 |
+
assert NS(Integral(log(log(1/x))/(1 + x + x**2), (x, 0, 1)), 15) == \
|
547 |
+
NS('pi/sqrt(3) * log(2*pi**(5/6) / gamma(1/6))', 15)
|
548 |
+
# http://mathworld.wolfram.com/AhmedsIntegral.html
|
549 |
+
assert NS(Integral(atan(sqrt(x**2 + 2))/(sqrt(x**2 + 2)*(x**2 + 1)), (x,
|
550 |
+
0, 1)), 15) == NS(5*pi**2/96, 15)
|
551 |
+
# http://mathworld.wolfram.com/AbelsIntegral.html
|
552 |
+
assert NS(Integral(x/((exp(pi*x) - exp(
|
553 |
+
-pi*x))*(x**2 + 1)), (x, 0, oo)), 15) == NS('log(2)/2-1/4', 15)
|
554 |
+
# Complex part trimming
|
555 |
+
# http://mathworld.wolfram.com/VardisIntegral.html
|
556 |
+
assert NS(Integral(log(log(sin(x)/cos(x))), (x, pi/4, pi/2)), 15, chop=True) == \
|
557 |
+
NS('pi/4*log(4*pi**3/gamma(1/4)**4)', 15)
|
558 |
+
#
|
559 |
+
# Endpoints causing trouble (rounding error in integration points -> complex log)
|
560 |
+
assert NS(
|
561 |
+
2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 17, chop=True) == NS(2, 17)
|
562 |
+
assert NS(
|
563 |
+
2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 20, chop=True) == NS(2, 20)
|
564 |
+
assert NS(
|
565 |
+
2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 22, chop=True) == NS(2, 22)
|
566 |
+
# Needs zero handling
|
567 |
+
assert NS(pi - 4*Integral(
|
568 |
+
'sqrt(1-x**2)', (x, 0, 1)), 15, maxn=30, chop=True) in ('0.0', '0')
|
569 |
+
# Oscillatory quadrature
|
570 |
+
a = Integral(sin(x)/x**2, (x, 1, oo)).evalf(maxn=15)
|
571 |
+
assert 0.49 < a < 0.51
|
572 |
+
assert NS(
|
573 |
+
Integral(sin(x)/x**2, (x, 1, oo)), quad='osc') == '0.504067061906928'
|
574 |
+
assert NS(Integral(
|
575 |
+
cos(pi*x + 1)/x, (x, -oo, -1)), quad='osc') == '0.276374705640365'
|
576 |
+
# indefinite integrals aren't evaluated
|
577 |
+
assert NS(Integral(x, x)) == 'Integral(x, x)'
|
578 |
+
assert NS(Integral(x, (x, y))) == 'Integral(x, (x, y))'
|
579 |
+
|
580 |
+
|
581 |
+
def test_evalf_issue_939():
|
582 |
+
# https://github.com/sympy/sympy/issues/4038
|
583 |
+
|
584 |
+
# The output form of an integral may differ by a step function between
|
585 |
+
# revisions, making this test a bit useless. This can't be said about
|
586 |
+
# other two tests. For now, all values of this evaluation are used here,
|
587 |
+
# but in future this should be reconsidered.
|
588 |
+
assert NS(integrate(1/(x**5 + 1), x).subs(x, 4), chop=True) in \
|
589 |
+
['-0.000976138910649103', '0.965906660135753', '1.93278945918216']
|
590 |
+
|
591 |
+
assert NS(Integral(1/(x**5 + 1), (x, 2, 4))) == '0.0144361088886740'
|
592 |
+
assert NS(
|
593 |
+
integrate(1/(x**5 + 1), (x, 2, 4)), chop=True) == '0.0144361088886740'
|
594 |
+
|
595 |
+
|
596 |
+
def test_double_previously_failing_integrals():
|
597 |
+
# Double integrals not implemented <- Sure it is!
|
598 |
+
res = integrate(sqrt(x) + x*y, (x, 1, 2), (y, -1, 1))
|
599 |
+
# Old numerical test
|
600 |
+
assert NS(res, 15) == '2.43790283299492'
|
601 |
+
# Symbolic test
|
602 |
+
assert res == Rational(-4, 3) + 8*sqrt(2)/3
|
603 |
+
# double integral + zero detection
|
604 |
+
assert integrate(sin(x + x*y), (x, -1, 1), (y, -1, 1)) is S.Zero
|
605 |
+
|
606 |
+
|
607 |
+
def test_integrate_SingularityFunction():
|
608 |
+
in_1 = SingularityFunction(x, a, 3) + SingularityFunction(x, 5, -1)
|
609 |
+
out_1 = SingularityFunction(x, a, 4)/4 + SingularityFunction(x, 5, 0)
|
610 |
+
assert integrate(in_1, x) == out_1
|
611 |
+
|
612 |
+
in_2 = 10*SingularityFunction(x, 4, 0) - 5*SingularityFunction(x, -6, -2)
|
613 |
+
out_2 = 10*SingularityFunction(x, 4, 1) - 5*SingularityFunction(x, -6, -1)
|
614 |
+
assert integrate(in_2, x) == out_2
|
615 |
+
|
616 |
+
in_3 = 2*x**2*y -10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -2)
|
617 |
+
out_3_1 = 2*x**3*y/3 - 2*x*SingularityFunction(y, 10, -2) - 5*SingularityFunction(x, -4, 8)/4
|
618 |
+
out_3_2 = x**2*y**2 - 10*y*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -1)
|
619 |
+
assert integrate(in_3, x) == out_3_1
|
620 |
+
assert integrate(in_3, y) == out_3_2
|
621 |
+
|
622 |
+
assert unchanged(Integral, in_3, (x,))
|
623 |
+
assert Integral(in_3, x) == Integral(in_3, (x,))
|
624 |
+
assert Integral(in_3, x).doit() == out_3_1
|
625 |
+
|
626 |
+
in_4 = 10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(x, 10, -2)
|
627 |
+
out_4 = 5*SingularityFunction(x, -4, 8)/4 - 2*SingularityFunction(x, 10, -1)
|
628 |
+
assert integrate(in_4, (x, -oo, x)) == out_4
|
629 |
+
|
630 |
+
assert integrate(SingularityFunction(x, 5, -1), x) == SingularityFunction(x, 5, 0)
|
631 |
+
assert integrate(SingularityFunction(x, 0, -1), (x, -oo, oo)) == 1
|
632 |
+
assert integrate(5*SingularityFunction(x, 5, -1), (x, -oo, oo)) == 5
|
633 |
+
assert integrate(SingularityFunction(x, 5, -1) * f(x), (x, -oo, oo)) == f(5)
|
634 |
+
|
635 |
+
|
636 |
+
def test_integrate_DiracDelta():
|
637 |
+
# This is here to check that deltaintegrate is being called, but also
|
638 |
+
# to test definite integrals. More tests are in test_deltafunctions.py
|
639 |
+
assert integrate(DiracDelta(x) * f(x), (x, -oo, oo)) == f(0)
|
640 |
+
assert integrate(DiracDelta(x)**2, (x, -oo, oo)) == DiracDelta(0)
|
641 |
+
# issue 4522
|
642 |
+
assert integrate(integrate((4 - 4*x + x*y - 4*y) * \
|
643 |
+
DiracDelta(x)*DiracDelta(y - 1), (x, 0, 1)), (y, 0, 1)) == 0
|
644 |
+
# issue 5729
|
645 |
+
p = exp(-(x**2 + y**2))/pi
|
646 |
+
assert integrate(p*DiracDelta(x - 10*y), (x, -oo, oo), (y, -oo, oo)) == \
|
647 |
+
integrate(p*DiracDelta(x - 10*y), (y, -oo, oo), (x, -oo, oo)) == \
|
648 |
+
integrate(p*DiracDelta(10*x - y), (x, -oo, oo), (y, -oo, oo)) == \
|
649 |
+
integrate(p*DiracDelta(10*x - y), (y, -oo, oo), (x, -oo, oo)) == \
|
650 |
+
1/sqrt(101*pi)
|
651 |
+
|
652 |
+
|
653 |
+
def test_integrate_returns_piecewise():
|
654 |
+
assert integrate(x**y, x) == Piecewise(
|
655 |
+
(x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True))
|
656 |
+
assert integrate(x**y, y) == Piecewise(
|
657 |
+
(x**y/log(x), Ne(log(x), 0)), (y, True))
|
658 |
+
assert integrate(exp(n*x), x) == Piecewise(
|
659 |
+
(exp(n*x)/n, Ne(n, 0)), (x, True))
|
660 |
+
assert integrate(x*exp(n*x), x) == Piecewise(
|
661 |
+
((n*x - 1)*exp(n*x)/n**2, Ne(n**2, 0)), (x**2/2, True))
|
662 |
+
assert integrate(x**(n*y), x) == Piecewise(
|
663 |
+
(x**(n*y + 1)/(n*y + 1), Ne(n*y, -1)), (log(x), True))
|
664 |
+
assert integrate(x**(n*y), y) == Piecewise(
|
665 |
+
(x**(n*y)/(n*log(x)), Ne(n*log(x), 0)), (y, True))
|
666 |
+
assert integrate(cos(n*x), x) == Piecewise(
|
667 |
+
(sin(n*x)/n, Ne(n, 0)), (x, True))
|
668 |
+
assert integrate(cos(n*x)**2, x) == Piecewise(
|
669 |
+
((n*x/2 + sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (x, True))
|
670 |
+
assert integrate(x*cos(n*x), x) == Piecewise(
|
671 |
+
(x*sin(n*x)/n + cos(n*x)/n**2, Ne(n, 0)), (x**2/2, True))
|
672 |
+
assert integrate(sin(n*x), x) == Piecewise(
|
673 |
+
(-cos(n*x)/n, Ne(n, 0)), (0, True))
|
674 |
+
assert integrate(sin(n*x)**2, x) == Piecewise(
|
675 |
+
((n*x/2 - sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (0, True))
|
676 |
+
assert integrate(x*sin(n*x), x) == Piecewise(
|
677 |
+
(-x*cos(n*x)/n + sin(n*x)/n**2, Ne(n, 0)), (0, True))
|
678 |
+
assert integrate(exp(x*y), (x, 0, z)) == Piecewise(
|
679 |
+
(exp(y*z)/y - 1/y, (y > -oo) & (y < oo) & Ne(y, 0)), (z, True))
|
680 |
+
# https://github.com/sympy/sympy/issues/23707
|
681 |
+
assert integrate(exp(t)*exp(-t*sqrt(x - y)), t) == Piecewise(
|
682 |
+
(-exp(t)/(sqrt(x - y)*exp(t*sqrt(x - y)) - exp(t*sqrt(x - y))),
|
683 |
+
Ne(x, y + 1)), (t, True))
|
684 |
+
|
685 |
+
|
686 |
+
def test_integrate_max_min():
|
687 |
+
x = symbols('x', real=True)
|
688 |
+
assert integrate(Min(x, 2), (x, 0, 3)) == 4
|
689 |
+
assert integrate(Max(x**2, x**3), (x, 0, 2)) == Rational(49, 12)
|
690 |
+
assert integrate(Min(exp(x), exp(-x))**2, x) == Piecewise( \
|
691 |
+
(exp(2*x)/2, x <= 0), (1 - exp(-2*x)/2, True))
|
692 |
+
# issue 7907
|
693 |
+
c = symbols('c', extended_real=True)
|
694 |
+
int1 = integrate(Max(c, x)*exp(-x**2), (x, -oo, oo))
|
695 |
+
int2 = integrate(c*exp(-x**2), (x, -oo, c))
|
696 |
+
int3 = integrate(x*exp(-x**2), (x, c, oo))
|
697 |
+
assert int1 == int2 + int3 == sqrt(pi)*c*erf(c)/2 + \
|
698 |
+
sqrt(pi)*c/2 + exp(-c**2)/2
|
699 |
+
|
700 |
+
|
701 |
+
def test_integrate_Abs_sign():
|
702 |
+
assert integrate(Abs(x), (x, -2, 1)) == Rational(5, 2)
|
703 |
+
assert integrate(Abs(x), (x, 0, 1)) == S.Half
|
704 |
+
assert integrate(Abs(x + 1), (x, 0, 1)) == Rational(3, 2)
|
705 |
+
assert integrate(Abs(x**2 - 1), (x, -2, 2)) == 4
|
706 |
+
assert integrate(Abs(x**2 - 3*x), (x, -15, 15)) == 2259
|
707 |
+
assert integrate(sign(x), (x, -1, 2)) == 1
|
708 |
+
assert integrate(sign(x)*sin(x), (x, -pi, pi)) == 4
|
709 |
+
assert integrate(sign(x - 2) * x**2, (x, 0, 3)) == Rational(11, 3)
|
710 |
+
|
711 |
+
t, s = symbols('t s', real=True)
|
712 |
+
assert integrate(Abs(t), t) == Piecewise(
|
713 |
+
(-t**2/2, t <= 0), (t**2/2, True))
|
714 |
+
assert integrate(Abs(2*t - 6), t) == Piecewise(
|
715 |
+
(-t**2 + 6*t, t <= 3), (t**2 - 6*t + 18, True))
|
716 |
+
assert (integrate(abs(t - s**2), (t, 0, 2)) ==
|
717 |
+
2*s**2*Min(2, s**2) - 2*s**2 - Min(2, s**2)**2 + 2)
|
718 |
+
assert integrate(exp(-Abs(t)), t) == Piecewise(
|
719 |
+
(exp(t), t <= 0), (2 - exp(-t), True))
|
720 |
+
assert integrate(sign(2*t - 6), t) == Piecewise(
|
721 |
+
(-t, t < 3), (t - 6, True))
|
722 |
+
assert integrate(2*t*sign(t**2 - 1), t) == Piecewise(
|
723 |
+
(t**2, t < -1), (-t**2 + 2, t < 1), (t**2, True))
|
724 |
+
assert integrate(sign(t), (t, s + 1)) == Piecewise(
|
725 |
+
(s + 1, s + 1 > 0), (-s - 1, s + 1 < 0), (0, True))
|
726 |
+
|
727 |
+
|
728 |
+
def test_subs1():
|
729 |
+
e = Integral(exp(x - y), x)
|
730 |
+
assert e.subs(y, 3) == Integral(exp(x - 3), x)
|
731 |
+
e = Integral(exp(x - y), (x, 0, 1))
|
732 |
+
assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1))
|
733 |
+
f = Lambda(x, exp(-x**2))
|
734 |
+
conv = Integral(f(x - y)*f(y), (y, -oo, oo))
|
735 |
+
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo))
|
736 |
+
|
737 |
+
|
738 |
+
def test_subs2():
|
739 |
+
e = Integral(exp(x - y), x, t)
|
740 |
+
assert e.subs(y, 3) == Integral(exp(x - 3), x, t)
|
741 |
+
e = Integral(exp(x - y), (x, 0, 1), (t, 0, 1))
|
742 |
+
assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1), (t, 0, 1))
|
743 |
+
f = Lambda(x, exp(-x**2))
|
744 |
+
conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, 0, 1))
|
745 |
+
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1))
|
746 |
+
|
747 |
+
|
748 |
+
def test_subs3():
|
749 |
+
e = Integral(exp(x - y), (x, 0, y), (t, y, 1))
|
750 |
+
assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 3), (t, 3, 1))
|
751 |
+
f = Lambda(x, exp(-x**2))
|
752 |
+
conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, x, 1))
|
753 |
+
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1))
|
754 |
+
|
755 |
+
|
756 |
+
def test_subs4():
|
757 |
+
e = Integral(exp(x), (x, 0, y), (t, y, 1))
|
758 |
+
assert e.subs(y, 3) == Integral(exp(x), (x, 0, 3), (t, 3, 1))
|
759 |
+
f = Lambda(x, exp(-x**2))
|
760 |
+
conv = Integral(f(y)*f(y), (y, -oo, oo), (t, x, 1))
|
761 |
+
assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1))
|
762 |
+
|
763 |
+
|
764 |
+
def test_subs5():
|
765 |
+
e = Integral(exp(-x**2), (x, -oo, oo))
|
766 |
+
assert e.subs(x, 5) == e
|
767 |
+
e = Integral(exp(-x**2 + y), x)
|
768 |
+
assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x)
|
769 |
+
e = Integral(exp(-x**2 + y), (x, x))
|
770 |
+
assert e.subs(x, 5) == Integral(exp(y - x**2), (x, 5))
|
771 |
+
assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x)
|
772 |
+
e = Integral(exp(-x**2 + y), (y, -oo, oo), (x, -oo, oo))
|
773 |
+
assert e.subs(x, 5) == e
|
774 |
+
assert e.subs(y, 5) == e
|
775 |
+
# Test evaluation of antiderivatives
|
776 |
+
e = Integral(exp(-x**2), (x, x))
|
777 |
+
assert e.subs(x, 5) == Integral(exp(-x**2), (x, 5))
|
778 |
+
e = Integral(exp(x), x)
|
779 |
+
assert (e.subs(x,1) - e.subs(x,0) - Integral(exp(x), (x, 0, 1))
|
780 |
+
).doit().is_zero
|
781 |
+
|
782 |
+
|
783 |
+
def test_subs6():
|
784 |
+
a, b = symbols('a b')
|
785 |
+
e = Integral(x*y, (x, f(x), f(y)))
|
786 |
+
assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y)))
|
787 |
+
assert e.subs(y, 1) == Integral(x, (x, f(x), f(1)))
|
788 |
+
e = Integral(x*y, (x, f(x), f(y)), (y, f(x), f(y)))
|
789 |
+
assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y)), (y, f(1), f(y)))
|
790 |
+
assert e.subs(y, 1) == Integral(x*y, (x, f(x), f(y)), (y, f(x), f(1)))
|
791 |
+
e = Integral(x*y, (x, f(x), f(a)), (y, f(x), f(a)))
|
792 |
+
assert e.subs(a, 1) == Integral(x*y, (x, f(x), f(1)), (y, f(x), f(1)))
|
793 |
+
|
794 |
+
|
795 |
+
def test_subs7():
|
796 |
+
e = Integral(x, (x, 1, y), (y, 1, 2))
|
797 |
+
assert e.subs({x: 1, y: 2}) == e
|
798 |
+
e = Integral(sin(x) + sin(y), (x, sin(x), sin(y)),
|
799 |
+
(y, 1, 2))
|
800 |
+
assert e.subs(sin(y), 1) == e
|
801 |
+
assert e.subs(sin(x), 1) == Integral(sin(x) + sin(y), (x, 1, sin(y)),
|
802 |
+
(y, 1, 2))
|
803 |
+
|
804 |
+
def test_expand():
|
805 |
+
e = Integral(f(x)+f(x**2), (x, 1, y))
|
806 |
+
assert e.expand() == Integral(f(x), (x, 1, y)) + Integral(f(x**2), (x, 1, y))
|
807 |
+
e = Integral(f(x)+f(x**2), (x, 1, oo))
|
808 |
+
assert e.expand() == e
|
809 |
+
assert e.expand(force=True) == Integral(f(x), (x, 1, oo)) + \
|
810 |
+
Integral(f(x**2), (x, 1, oo))
|
811 |
+
|
812 |
+
|
813 |
+
def test_integration_variable():
|
814 |
+
raises(ValueError, lambda: Integral(exp(-x**2), 3))
|
815 |
+
raises(ValueError, lambda: Integral(exp(-x**2), (3, -oo, oo)))
|
816 |
+
|
817 |
+
|
818 |
+
def test_expand_integral():
|
819 |
+
assert Integral(cos(x**2)*(sin(x**2) + 1), (x, 0, 1)).expand() == \
|
820 |
+
Integral(cos(x**2)*sin(x**2), (x, 0, 1)) + \
|
821 |
+
Integral(cos(x**2), (x, 0, 1))
|
822 |
+
assert Integral(cos(x**2)*(sin(x**2) + 1), x).expand() == \
|
823 |
+
Integral(cos(x**2)*sin(x**2), x) + \
|
824 |
+
Integral(cos(x**2), x)
|
825 |
+
|
826 |
+
|
827 |
+
def test_as_sum_midpoint1():
|
828 |
+
e = Integral(sqrt(x**3 + 1), (x, 2, 10))
|
829 |
+
assert e.as_sum(1, method="midpoint") == 8*sqrt(217)
|
830 |
+
assert e.as_sum(2, method="midpoint") == 4*sqrt(65) + 12*sqrt(57)
|
831 |
+
assert e.as_sum(3, method="midpoint") == 8*sqrt(217)/3 + \
|
832 |
+
8*sqrt(3081)/27 + 8*sqrt(52809)/27
|
833 |
+
assert e.as_sum(4, method="midpoint") == 2*sqrt(730) + \
|
834 |
+
4*sqrt(7) + 4*sqrt(86) + 6*sqrt(14)
|
835 |
+
assert abs(e.as_sum(4, method="midpoint").n() - e.n()) < 0.5
|
836 |
+
|
837 |
+
e = Integral(sqrt(x**3 + y**3), (x, 2, 10), (y, 0, 10))
|
838 |
+
raises(NotImplementedError, lambda: e.as_sum(4))
|
839 |
+
|
840 |
+
|
841 |
+
def test_as_sum_midpoint2():
|
842 |
+
e = Integral((x + y)**2, (x, 0, 1))
|
843 |
+
n = Symbol('n', positive=True, integer=True)
|
844 |
+
assert e.as_sum(1, method="midpoint").expand() == Rational(1, 4) + y + y**2
|
845 |
+
assert e.as_sum(2, method="midpoint").expand() == Rational(5, 16) + y + y**2
|
846 |
+
assert e.as_sum(3, method="midpoint").expand() == Rational(35, 108) + y + y**2
|
847 |
+
assert e.as_sum(4, method="midpoint").expand() == Rational(21, 64) + y + y**2
|
848 |
+
assert e.as_sum(n, method="midpoint").expand() == \
|
849 |
+
y**2 + y + Rational(1, 3) - 1/(12*n**2)
|
850 |
+
|
851 |
+
|
852 |
+
def test_as_sum_left():
|
853 |
+
e = Integral((x + y)**2, (x, 0, 1))
|
854 |
+
assert e.as_sum(1, method="left").expand() == y**2
|
855 |
+
assert e.as_sum(2, method="left").expand() == Rational(1, 8) + y/2 + y**2
|
856 |
+
assert e.as_sum(3, method="left").expand() == Rational(5, 27) + y*Rational(2, 3) + y**2
|
857 |
+
assert e.as_sum(4, method="left").expand() == Rational(7, 32) + y*Rational(3, 4) + y**2
|
858 |
+
assert e.as_sum(n, method="left").expand() == \
|
859 |
+
y**2 + y + Rational(1, 3) - y/n - 1/(2*n) + 1/(6*n**2)
|
860 |
+
assert e.as_sum(10, method="left", evaluate=False).has(Sum)
|
861 |
+
|
862 |
+
|
863 |
+
def test_as_sum_right():
|
864 |
+
e = Integral((x + y)**2, (x, 0, 1))
|
865 |
+
assert e.as_sum(1, method="right").expand() == 1 + 2*y + y**2
|
866 |
+
assert e.as_sum(2, method="right").expand() == Rational(5, 8) + y*Rational(3, 2) + y**2
|
867 |
+
assert e.as_sum(3, method="right").expand() == Rational(14, 27) + y*Rational(4, 3) + y**2
|
868 |
+
assert e.as_sum(4, method="right").expand() == Rational(15, 32) + y*Rational(5, 4) + y**2
|
869 |
+
assert e.as_sum(n, method="right").expand() == \
|
870 |
+
y**2 + y + Rational(1, 3) + y/n + 1/(2*n) + 1/(6*n**2)
|
871 |
+
|
872 |
+
|
873 |
+
def test_as_sum_trapezoid():
|
874 |
+
e = Integral((x + y)**2, (x, 0, 1))
|
875 |
+
assert e.as_sum(1, method="trapezoid").expand() == y**2 + y + S.Half
|
876 |
+
assert e.as_sum(2, method="trapezoid").expand() == y**2 + y + Rational(3, 8)
|
877 |
+
assert e.as_sum(3, method="trapezoid").expand() == y**2 + y + Rational(19, 54)
|
878 |
+
assert e.as_sum(4, method="trapezoid").expand() == y**2 + y + Rational(11, 32)
|
879 |
+
assert e.as_sum(n, method="trapezoid").expand() == \
|
880 |
+
y**2 + y + Rational(1, 3) + 1/(6*n**2)
|
881 |
+
assert Integral(sign(x), (x, 0, 1)).as_sum(1, 'trapezoid') == S.Half
|
882 |
+
|
883 |
+
|
884 |
+
def test_as_sum_raises():
|
885 |
+
e = Integral((x + y)**2, (x, 0, 1))
|
886 |
+
raises(ValueError, lambda: e.as_sum(-1))
|
887 |
+
raises(ValueError, lambda: e.as_sum(0))
|
888 |
+
raises(ValueError, lambda: Integral(x).as_sum(3))
|
889 |
+
raises(ValueError, lambda: e.as_sum(oo))
|
890 |
+
raises(ValueError, lambda: e.as_sum(3, method='xxxx2'))
|
891 |
+
|
892 |
+
|
893 |
+
def test_nested_doit():
|
894 |
+
e = Integral(Integral(x, x), x)
|
895 |
+
f = Integral(x, x, x)
|
896 |
+
assert e.doit() == f.doit()
|
897 |
+
|
898 |
+
|
899 |
+
def test_issue_4665():
|
900 |
+
# Allow only upper or lower limit evaluation
|
901 |
+
e = Integral(x**2, (x, None, 1))
|
902 |
+
f = Integral(x**2, (x, 1, None))
|
903 |
+
assert e.doit() == Rational(1, 3)
|
904 |
+
assert f.doit() == Rational(-1, 3)
|
905 |
+
assert Integral(x*y, (x, None, y)).subs(y, t) == Integral(x*t, (x, None, t))
|
906 |
+
assert Integral(x*y, (x, y, None)).subs(y, t) == Integral(x*t, (x, t, None))
|
907 |
+
assert integrate(x**2, (x, None, 1)) == Rational(1, 3)
|
908 |
+
assert integrate(x**2, (x, 1, None)) == Rational(-1, 3)
|
909 |
+
assert integrate("x**2", ("x", "1", None)) == Rational(-1, 3)
|
910 |
+
|
911 |
+
|
912 |
+
def test_integral_reconstruct():
|
913 |
+
e = Integral(x**2, (x, -1, 1))
|
914 |
+
assert e == Integral(*e.args)
|
915 |
+
|
916 |
+
|
917 |
+
def test_doit_integrals():
|
918 |
+
e = Integral(Integral(2*x), (x, 0, 1))
|
919 |
+
assert e.doit() == Rational(1, 3)
|
920 |
+
assert e.doit(deep=False) == Rational(1, 3)
|
921 |
+
f = Function('f')
|
922 |
+
# doesn't matter if the integral can't be performed
|
923 |
+
assert Integral(f(x), (x, 1, 1)).doit() == 0
|
924 |
+
# doesn't matter if the limits can't be evaluated
|
925 |
+
assert Integral(0, (x, 1, Integral(f(x), x))).doit() == 0
|
926 |
+
assert Integral(x, (a, 0)).doit() == 0
|
927 |
+
limits = ((a, 1, exp(x)), (x, 0))
|
928 |
+
assert Integral(a, *limits).doit() == Rational(1, 4)
|
929 |
+
assert Integral(a, *list(reversed(limits))).doit() == 0
|
930 |
+
|
931 |
+
|
932 |
+
def test_issue_4884():
|
933 |
+
assert integrate(sqrt(x)*(1 + x)) == \
|
934 |
+
Piecewise(
|
935 |
+
(2*sqrt(x)*(x + 1)**2/5 - 2*sqrt(x)*(x + 1)/15 - 4*sqrt(x)/15,
|
936 |
+
Abs(x + 1) > 1),
|
937 |
+
(2*I*sqrt(-x)*(x + 1)**2/5 - 2*I*sqrt(-x)*(x + 1)/15 -
|
938 |
+
4*I*sqrt(-x)/15, True))
|
939 |
+
assert integrate(x**x*(1 + log(x))) == x**x
|
940 |
+
|
941 |
+
def test_issue_18153():
|
942 |
+
assert integrate(x**n*log(x),x) == \
|
943 |
+
Piecewise(
|
944 |
+
(n*x*x**n*log(x)/(n**2 + 2*n + 1) +
|
945 |
+
x*x**n*log(x)/(n**2 + 2*n + 1) - x*x**n/(n**2 + 2*n + 1)
|
946 |
+
, Ne(n, -1)), (log(x)**2/2, True)
|
947 |
+
)
|
948 |
+
|
949 |
+
|
950 |
+
def test_is_number():
|
951 |
+
from sympy.abc import x, y, z
|
952 |
+
assert Integral(x).is_number is False
|
953 |
+
assert Integral(1, x).is_number is False
|
954 |
+
assert Integral(1, (x, 1)).is_number is True
|
955 |
+
assert Integral(1, (x, 1, 2)).is_number is True
|
956 |
+
assert Integral(1, (x, 1, y)).is_number is False
|
957 |
+
assert Integral(1, (x, y)).is_number is False
|
958 |
+
assert Integral(x, y).is_number is False
|
959 |
+
assert Integral(x, (y, 1, x)).is_number is False
|
960 |
+
assert Integral(x, (y, 1, 2)).is_number is False
|
961 |
+
assert Integral(x, (x, 1, 2)).is_number is True
|
962 |
+
# `foo.is_number` should always be equivalent to `not foo.free_symbols`
|
963 |
+
# in each of these cases, there are pseudo-free symbols
|
964 |
+
i = Integral(x, (y, 1, 1))
|
965 |
+
assert i.is_number is False and i.n() == 0
|
966 |
+
i = Integral(x, (y, z, z))
|
967 |
+
assert i.is_number is False and i.n() == 0
|
968 |
+
i = Integral(1, (y, z, z + 2))
|
969 |
+
assert i.is_number is False and i.n() == 2.0
|
970 |
+
|
971 |
+
assert Integral(x*y, (x, 1, 2), (y, 1, 3)).is_number is True
|
972 |
+
assert Integral(x*y, (x, 1, 2), (y, 1, z)).is_number is False
|
973 |
+
assert Integral(x, (x, 1)).is_number is True
|
974 |
+
assert Integral(x, (x, 1, Integral(y, (y, 1, 2)))).is_number is True
|
975 |
+
assert Integral(Sum(z, (z, 1, 2)), (x, 1, 2)).is_number is True
|
976 |
+
# it is possible to get a false negative if the integrand is
|
977 |
+
# actually an unsimplified zero, but this is true of is_number in general.
|
978 |
+
assert Integral(sin(x)**2 + cos(x)**2 - 1, x).is_number is False
|
979 |
+
assert Integral(f(x), (x, 0, 1)).is_number is True
|
980 |
+
|
981 |
+
|
982 |
+
def test_free_symbols():
|
983 |
+
from sympy.abc import x, y, z
|
984 |
+
assert Integral(0, x).free_symbols == {x}
|
985 |
+
assert Integral(x).free_symbols == {x}
|
986 |
+
assert Integral(x, (x, None, y)).free_symbols == {y}
|
987 |
+
assert Integral(x, (x, y, None)).free_symbols == {y}
|
988 |
+
assert Integral(x, (x, 1, y)).free_symbols == {y}
|
989 |
+
assert Integral(x, (x, y, 1)).free_symbols == {y}
|
990 |
+
assert Integral(x, (x, x, y)).free_symbols == {x, y}
|
991 |
+
assert Integral(x, x, y).free_symbols == {x, y}
|
992 |
+
assert Integral(x, (x, 1, 2)).free_symbols == set()
|
993 |
+
assert Integral(x, (y, 1, 2)).free_symbols == {x}
|
994 |
+
# pseudo-free in this case
|
995 |
+
assert Integral(x, (y, z, z)).free_symbols == {x, z}
|
996 |
+
assert Integral(x, (y, 1, 2), (y, None, None)
|
997 |
+
).free_symbols == {x, y}
|
998 |
+
assert Integral(x, (y, 1, 2), (x, 1, y)
|
999 |
+
).free_symbols == {y}
|
1000 |
+
assert Integral(2, (y, 1, 2), (y, 1, x), (x, 1, 2)
|
1001 |
+
).free_symbols == set()
|
1002 |
+
assert Integral(2, (y, x, 2), (y, 1, x), (x, 1, 2)
|
1003 |
+
).free_symbols == set()
|
1004 |
+
assert Integral(2, (x, 1, 2), (y, x, 2), (y, 1, 2)
|
1005 |
+
).free_symbols == {x}
|
1006 |
+
assert Integral(f(x), (f(x), 1, y)).free_symbols == {y}
|
1007 |
+
assert Integral(f(x), (f(x), 1, x)).free_symbols == {x}
|
1008 |
+
|
1009 |
+
|
1010 |
+
def test_is_zero():
|
1011 |
+
from sympy.abc import x, m
|
1012 |
+
assert Integral(0, (x, 1, x)).is_zero
|
1013 |
+
assert Integral(1, (x, 1, 1)).is_zero
|
1014 |
+
assert Integral(1, (x, 1, 2), (y, 2)).is_zero is False
|
1015 |
+
assert Integral(x, (m, 0)).is_zero
|
1016 |
+
assert Integral(x + m, (m, 0)).is_zero is None
|
1017 |
+
i = Integral(m, (m, 1, exp(x)), (x, 0))
|
1018 |
+
assert i.is_zero is None
|
1019 |
+
assert Integral(m, (x, 0), (m, 1, exp(x))).is_zero is True
|
1020 |
+
|
1021 |
+
assert Integral(x, (x, oo, oo)).is_zero # issue 8171
|
1022 |
+
assert Integral(x, (x, -oo, -oo)).is_zero
|
1023 |
+
|
1024 |
+
# this is zero but is beyond the scope of what is_zero
|
1025 |
+
# should be doing
|
1026 |
+
assert Integral(sin(x), (x, 0, 2*pi)).is_zero is None
|
1027 |
+
|
1028 |
+
|
1029 |
+
def test_series():
|
1030 |
+
from sympy.abc import x
|
1031 |
+
i = Integral(cos(x), (x, x))
|
1032 |
+
e = i.lseries(x)
|
1033 |
+
assert i.nseries(x, n=8).removeO() == Add(*[next(e) for j in range(4)])
|
1034 |
+
|
1035 |
+
|
1036 |
+
def test_trig_nonelementary_integrals():
|
1037 |
+
x = Symbol('x')
|
1038 |
+
assert integrate((1 + sin(x))/x, x) == log(x) + Si(x)
|
1039 |
+
# next one comes out as log(x) + log(x**2)/2 + Ci(x)
|
1040 |
+
# so not hardcoding this log ugliness
|
1041 |
+
assert integrate((cos(x) + 2)/x, x).has(Ci)
|
1042 |
+
|
1043 |
+
|
1044 |
+
def test_issue_4403():
|
1045 |
+
x = Symbol('x')
|
1046 |
+
y = Symbol('y')
|
1047 |
+
z = Symbol('z', positive=True)
|
1048 |
+
assert integrate(sqrt(x**2 + z**2), x) == \
|
1049 |
+
z**2*asinh(x/z)/2 + x*sqrt(x**2 + z**2)/2
|
1050 |
+
assert integrate(sqrt(x**2 - z**2), x) == \
|
1051 |
+
x*sqrt(x**2 - z**2)/2 - z**2*log(x + sqrt(x**2 - z**2))/2
|
1052 |
+
|
1053 |
+
x = Symbol('x', real=True)
|
1054 |
+
y = Symbol('y', positive=True)
|
1055 |
+
assert integrate(1/(x**2 + y**2)**S('3/2'), x) == \
|
1056 |
+
x/(y**2*sqrt(x**2 + y**2))
|
1057 |
+
# If y is real and nonzero, we get x*Abs(y)/(y**3*sqrt(x**2 + y**2)),
|
1058 |
+
# which results from sqrt(1 + x**2/y**2) = sqrt(x**2 + y**2)/|y|.
|
1059 |
+
|
1060 |
+
|
1061 |
+
def test_issue_4403_2():
|
1062 |
+
assert integrate(sqrt(-x**2 - 4), x) == \
|
1063 |
+
-2*atan(x/sqrt(-4 - x**2)) + x*sqrt(-4 - x**2)/2
|
1064 |
+
|
1065 |
+
|
1066 |
+
def test_issue_4100():
|
1067 |
+
R = Symbol('R', positive=True)
|
1068 |
+
assert integrate(sqrt(R**2 - x**2), (x, 0, R)) == pi*R**2/4
|
1069 |
+
|
1070 |
+
|
1071 |
+
def test_issue_5167():
|
1072 |
+
from sympy.abc import w, x, y, z
|
1073 |
+
f = Function('f')
|
1074 |
+
assert Integral(Integral(f(x), x), x) == Integral(f(x), x, x)
|
1075 |
+
assert Integral(f(x)).args == (f(x), Tuple(x))
|
1076 |
+
assert Integral(Integral(f(x))).args == (f(x), Tuple(x), Tuple(x))
|
1077 |
+
assert Integral(Integral(f(x)), y).args == (f(x), Tuple(x), Tuple(y))
|
1078 |
+
assert Integral(Integral(f(x), z), y).args == (f(x), Tuple(z), Tuple(y))
|
1079 |
+
assert Integral(Integral(Integral(f(x), x), y), z).args == \
|
1080 |
+
(f(x), Tuple(x), Tuple(y), Tuple(z))
|
1081 |
+
assert integrate(Integral(f(x), x), x) == Integral(f(x), x, x)
|
1082 |
+
assert integrate(Integral(f(x), y), x) == y*Integral(f(x), x)
|
1083 |
+
assert integrate(Integral(f(x), x), y) in [Integral(y*f(x), x), y*Integral(f(x), x)]
|
1084 |
+
assert integrate(Integral(2, x), x) == x**2
|
1085 |
+
assert integrate(Integral(2, x), y) == 2*x*y
|
1086 |
+
# don't re-order given limits
|
1087 |
+
assert Integral(1, x, y).args != Integral(1, y, x).args
|
1088 |
+
# do as many as possible
|
1089 |
+
assert Integral(f(x), y, x, y, x).doit() == y**2*Integral(f(x), x, x)/2
|
1090 |
+
assert Integral(f(x), (x, 1, 2), (w, 1, x), (z, 1, y)).doit() == \
|
1091 |
+
y*(x - 1)*Integral(f(x), (x, 1, 2)) - (x - 1)*Integral(f(x), (x, 1, 2))
|
1092 |
+
|
1093 |
+
|
1094 |
+
def test_issue_4890():
|
1095 |
+
z = Symbol('z', positive=True)
|
1096 |
+
assert integrate(exp(-log(x)**2), x) == \
|
1097 |
+
sqrt(pi)*exp(Rational(1, 4))*erf(log(x) - S.Half)/2
|
1098 |
+
assert integrate(exp(log(x)**2), x) == \
|
1099 |
+
sqrt(pi)*exp(Rational(-1, 4))*erfi(log(x)+S.Half)/2
|
1100 |
+
assert integrate(exp(-z*log(x)**2), x) == \
|
1101 |
+
sqrt(pi)*exp(1/(4*z))*erf(sqrt(z)*log(x) - 1/(2*sqrt(z)))/(2*sqrt(z))
|
1102 |
+
|
1103 |
+
|
1104 |
+
def test_issue_4551():
|
1105 |
+
assert not integrate(1/(x*sqrt(1 - x**2)), x).has(Integral)
|
1106 |
+
|
1107 |
+
|
1108 |
+
def test_issue_4376():
|
1109 |
+
n = Symbol('n', integer=True, positive=True)
|
1110 |
+
assert simplify(integrate(n*(x**(1/n) - 1), (x, 0, S.Half)) -
|
1111 |
+
(n**2 - 2**(1/n)*n**2 - n*2**(1/n))/(2**(1 + 1/n) + n*2**(1 + 1/n))) == 0
|
1112 |
+
|
1113 |
+
|
1114 |
+
def test_issue_4517():
|
1115 |
+
assert integrate((sqrt(x) - x**3)/x**Rational(1, 3), x) == \
|
1116 |
+
6*x**Rational(7, 6)/7 - 3*x**Rational(11, 3)/11
|
1117 |
+
|
1118 |
+
|
1119 |
+
def test_issue_4527():
|
1120 |
+
k, m = symbols('k m', integer=True)
|
1121 |
+
assert integrate(sin(k*x)*sin(m*x), (x, 0, pi)).simplify() == \
|
1122 |
+
Piecewise((0, Eq(k, 0) | Eq(m, 0)),
|
1123 |
+
(-pi/2, Eq(k, -m) | (Eq(k, 0) & Eq(m, 0))),
|
1124 |
+
(pi/2, Eq(k, m) | (Eq(k, 0) & Eq(m, 0))),
|
1125 |
+
(0, True))
|
1126 |
+
# Should be possible to further simplify to:
|
1127 |
+
# Piecewise(
|
1128 |
+
# (0, Eq(k, 0) | Eq(m, 0)),
|
1129 |
+
# (-pi/2, Eq(k, -m)),
|
1130 |
+
# (pi/2, Eq(k, m)),
|
1131 |
+
# (0, True))
|
1132 |
+
assert integrate(sin(k*x)*sin(m*x), (x,)) == Piecewise(
|
1133 |
+
(0, And(Eq(k, 0), Eq(m, 0))),
|
1134 |
+
(-x*sin(m*x)**2/2 - x*cos(m*x)**2/2 + sin(m*x)*cos(m*x)/(2*m), Eq(k, -m)),
|
1135 |
+
(x*sin(m*x)**2/2 + x*cos(m*x)**2/2 - sin(m*x)*cos(m*x)/(2*m), Eq(k, m)),
|
1136 |
+
(m*sin(k*x)*cos(m*x)/(k**2 - m**2) -
|
1137 |
+
k*sin(m*x)*cos(k*x)/(k**2 - m**2), True))
|
1138 |
+
|
1139 |
+
|
1140 |
+
def test_issue_4199():
|
1141 |
+
ypos = Symbol('y', positive=True)
|
1142 |
+
# TODO: Remove conds='none' below, let the assumption take care of it.
|
1143 |
+
assert integrate(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo), conds='none') == \
|
1144 |
+
Integral(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo))
|
1145 |
+
|
1146 |
+
|
1147 |
+
def test_issue_3940():
|
1148 |
+
a, b, c, d = symbols('a:d', positive=True)
|
1149 |
+
assert integrate(exp(-x**2 + I*c*x), x) == \
|
1150 |
+
-sqrt(pi)*exp(-c**2/4)*erf(I*c/2 - x)/2
|
1151 |
+
assert integrate(exp(a*x**2 + b*x + c), x) == \
|
1152 |
+
sqrt(pi)*exp(c)*exp(-b**2/(4*a))*erfi(sqrt(a)*x + b/(2*sqrt(a)))/(2*sqrt(a))
|
1153 |
+
|
1154 |
+
from sympy.core.function import expand_mul
|
1155 |
+
from sympy.abc import k
|
1156 |
+
assert expand_mul(integrate(exp(-x**2)*exp(I*k*x), (x, -oo, oo))) == \
|
1157 |
+
sqrt(pi)*exp(-k**2/4)
|
1158 |
+
a, d = symbols('a d', positive=True)
|
1159 |
+
assert expand_mul(integrate(exp(-a*x**2 + 2*d*x), (x, -oo, oo))) == \
|
1160 |
+
sqrt(pi)*exp(d**2/a)/sqrt(a)
|
1161 |
+
|
1162 |
+
|
1163 |
+
def test_issue_5413():
|
1164 |
+
# Note that this is not the same as testing ratint() because integrate()
|
1165 |
+
# pulls out the coefficient.
|
1166 |
+
assert integrate(-a/(a**2 + x**2), x) == I*log(-I*a + x)/2 - I*log(I*a + x)/2
|
1167 |
+
|
1168 |
+
|
1169 |
+
def test_issue_4892a():
|
1170 |
+
A, z = symbols('A z')
|
1171 |
+
c = Symbol('c', nonzero=True)
|
1172 |
+
P1 = -A*exp(-z)
|
1173 |
+
P2 = -A/(c*t)*(sin(x)**2 + cos(y)**2)
|
1174 |
+
|
1175 |
+
h1 = -sin(x)**2 - cos(y)**2
|
1176 |
+
h2 = -sin(x)**2 + sin(y)**2 - 1
|
1177 |
+
|
1178 |
+
# there is still some non-deterministic behavior in integrate
|
1179 |
+
# or trigsimp which permits one of the following
|
1180 |
+
assert integrate(c*(P2 - P1), t) in [
|
1181 |
+
c*(-A*(-h1)*log(c*t)/c + A*t*exp(-z)),
|
1182 |
+
c*(-A*(-h2)*log(c*t)/c + A*t*exp(-z)),
|
1183 |
+
c*( A* h1 *log(c*t)/c + A*t*exp(-z)),
|
1184 |
+
c*( A* h2 *log(c*t)/c + A*t*exp(-z)),
|
1185 |
+
(A*c*t - A*(-h1)*log(t)*exp(z))*exp(-z),
|
1186 |
+
(A*c*t - A*(-h2)*log(t)*exp(z))*exp(-z),
|
1187 |
+
]
|
1188 |
+
|
1189 |
+
|
1190 |
+
def test_issue_4892b():
|
1191 |
+
# Issues relating to issue 4596 are making the actual result of this hard
|
1192 |
+
# to test. The answer should be something like
|
1193 |
+
#
|
1194 |
+
# (-sin(y) + sqrt(-72 + 48*cos(y) - 8*cos(y)**2)/2)*log(x + sqrt(-72 +
|
1195 |
+
# 48*cos(y) - 8*cos(y)**2)/(2*(3 - cos(y)))) + (-sin(y) - sqrt(-72 +
|
1196 |
+
# 48*cos(y) - 8*cos(y)**2)/2)*log(x - sqrt(-72 + 48*cos(y) -
|
1197 |
+
# 8*cos(y)**2)/(2*(3 - cos(y)))) + x**2*sin(y)/2 + 2*x*cos(y)
|
1198 |
+
|
1199 |
+
expr = (sin(y)*x**3 + 2*cos(y)*x**2 + 12)/(x**2 + 2)
|
1200 |
+
assert trigsimp(factor(integrate(expr, x).diff(x) - expr)) == 0
|
1201 |
+
|
1202 |
+
|
1203 |
+
def test_issue_5178():
|
1204 |
+
assert integrate(sin(x)*f(y, z), (x, 0, pi), (y, 0, pi), (z, 0, pi)) == \
|
1205 |
+
2*Integral(f(y, z), (y, 0, pi), (z, 0, pi))
|
1206 |
+
|
1207 |
+
|
1208 |
+
def test_integrate_series():
|
1209 |
+
f = sin(x).series(x, 0, 10)
|
1210 |
+
g = x**2/2 - x**4/24 + x**6/720 - x**8/40320 + x**10/3628800 + O(x**11)
|
1211 |
+
|
1212 |
+
assert integrate(f, x) == g
|
1213 |
+
assert diff(integrate(f, x), x) == f
|
1214 |
+
|
1215 |
+
assert integrate(O(x**5), x) == O(x**6)
|
1216 |
+
|
1217 |
+
|
1218 |
+
def test_atom_bug():
|
1219 |
+
from sympy.integrals.heurisch import heurisch
|
1220 |
+
assert heurisch(meijerg([], [], [1], [], x), x) is None
|
1221 |
+
|
1222 |
+
|
1223 |
+
def test_limit_bug():
|
1224 |
+
z = Symbol('z', zero=False)
|
1225 |
+
assert integrate(sin(x*y*z), (x, 0, pi), (y, 0, pi)).together() == \
|
1226 |
+
(log(z) - Ci(pi**2*z) + EulerGamma + 2*log(pi))/z
|
1227 |
+
|
1228 |
+
|
1229 |
+
def test_issue_4703():
|
1230 |
+
g = Function('g')
|
1231 |
+
assert integrate(exp(x)*g(x), x).has(Integral)
|
1232 |
+
|
1233 |
+
|
1234 |
+
def test_issue_1888():
|
1235 |
+
f = Function('f')
|
1236 |
+
assert integrate(f(x).diff(x)**2, x).has(Integral)
|
1237 |
+
|
1238 |
+
# The following tests work using meijerint.
|
1239 |
+
|
1240 |
+
|
1241 |
+
def test_issue_3558():
|
1242 |
+
assert integrate(cos(x*y), (x, -pi/2, pi/2), (y, 0, pi)) == 2*Si(pi**2/2)
|
1243 |
+
|
1244 |
+
|
1245 |
+
def test_issue_4422():
|
1246 |
+
assert integrate(1/sqrt(16 + 4*x**2), x) == asinh(x/2) / 2
|
1247 |
+
|
1248 |
+
|
1249 |
+
def test_issue_4493():
|
1250 |
+
assert simplify(integrate(x*sqrt(1 + 2*x), x)) == \
|
1251 |
+
sqrt(2*x + 1)*(6*x**2 + x - 1)/15
|
1252 |
+
|
1253 |
+
|
1254 |
+
def test_issue_4737():
|
1255 |
+
assert integrate(sin(x)/x, (x, -oo, oo)) == pi
|
1256 |
+
assert integrate(sin(x)/x, (x, 0, oo)) == pi/2
|
1257 |
+
assert integrate(sin(x)/x, x) == Si(x)
|
1258 |
+
|
1259 |
+
|
1260 |
+
def test_issue_4992():
|
1261 |
+
# Note: psi in _check_antecedents becomes NaN.
|
1262 |
+
from sympy.core.function import expand_func
|
1263 |
+
a = Symbol('a', positive=True)
|
1264 |
+
assert simplify(expand_func(integrate(exp(-x)*log(x)*x**a, (x, 0, oo)))) == \
|
1265 |
+
(a*polygamma(0, a) + 1)*gamma(a)
|
1266 |
+
|
1267 |
+
|
1268 |
+
def test_issue_4487():
|
1269 |
+
from sympy.functions.special.gamma_functions import lowergamma
|
1270 |
+
assert simplify(integrate(exp(-x)*x**y, x)) == lowergamma(y + 1, x)
|
1271 |
+
|
1272 |
+
|
1273 |
+
def test_issue_4215():
|
1274 |
+
x = Symbol("x")
|
1275 |
+
assert integrate(1/(x**2), (x, -1, 1)) is oo
|
1276 |
+
|
1277 |
+
|
1278 |
+
def test_issue_4400():
|
1279 |
+
n = Symbol('n', integer=True, positive=True)
|
1280 |
+
assert integrate((x**n)*log(x), x) == \
|
1281 |
+
n*x*x**n*log(x)/(n**2 + 2*n + 1) + x*x**n*log(x)/(n**2 + 2*n + 1) - \
|
1282 |
+
x*x**n/(n**2 + 2*n + 1)
|
1283 |
+
|
1284 |
+
|
1285 |
+
def test_issue_6253():
|
1286 |
+
# Note: this used to raise NotImplementedError
|
1287 |
+
# Note: psi in _check_antecedents becomes NaN.
|
1288 |
+
assert integrate((sqrt(1 - x) + sqrt(1 + x))**2/x, x, meijerg=True) == \
|
1289 |
+
Integral((sqrt(-x + 1) + sqrt(x + 1))**2/x, x)
|
1290 |
+
|
1291 |
+
|
1292 |
+
def test_issue_4153():
|
1293 |
+
assert integrate(1/(1 + x + y + z), (x, 0, 1), (y, 0, 1), (z, 0, 1)) in [
|
1294 |
+
-12*log(3) - 3*log(6)/2 + 3*log(8)/2 + 5*log(2) + 7*log(4),
|
1295 |
+
6*log(2) + 8*log(4) - 27*log(3)/2, 22*log(2) - 27*log(3)/2,
|
1296 |
+
-12*log(3) - 3*log(6)/2 + 47*log(2)/2]
|
1297 |
+
|
1298 |
+
|
1299 |
+
def test_issue_4326():
|
1300 |
+
R, b, h = symbols('R b h')
|
1301 |
+
# It doesn't matter if we can do the integral. Just make sure the result
|
1302 |
+
# doesn't contain nan. This is really a test against _eval_interval.
|
1303 |
+
e = integrate(((h*(x - R + b))/b)*sqrt(R**2 - x**2), (x, R - b, R))
|
1304 |
+
assert not e.has(nan)
|
1305 |
+
# See that it evaluates
|
1306 |
+
assert not e.has(Integral)
|
1307 |
+
|
1308 |
+
|
1309 |
+
def test_powers():
|
1310 |
+
assert integrate(2**x + 3**x, x) == 2**x/log(2) + 3**x/log(3)
|
1311 |
+
|
1312 |
+
|
1313 |
+
def test_manual_option():
|
1314 |
+
raises(ValueError, lambda: integrate(1/x, x, manual=True, meijerg=True))
|
1315 |
+
# an example of a function that manual integration cannot handle
|
1316 |
+
assert integrate(log(1+x)/x, (x, 0, 1), manual=True).has(Integral)
|
1317 |
+
|
1318 |
+
|
1319 |
+
def test_meijerg_option():
|
1320 |
+
raises(ValueError, lambda: integrate(1/x, x, meijerg=True, risch=True))
|
1321 |
+
# an example of a function that meijerg integration cannot handle
|
1322 |
+
assert integrate(tan(x), x, meijerg=True) == Integral(tan(x), x)
|
1323 |
+
|
1324 |
+
|
1325 |
+
def test_risch_option():
|
1326 |
+
# risch=True only allowed on indefinite integrals
|
1327 |
+
raises(ValueError, lambda: integrate(1/log(x), (x, 0, oo), risch=True))
|
1328 |
+
assert integrate(exp(-x**2), x, risch=True) == NonElementaryIntegral(exp(-x**2), x)
|
1329 |
+
assert integrate(log(1/x)*y, x, y, risch=True) == y**2*(x*log(1/x)/2 + x/2)
|
1330 |
+
assert integrate(erf(x), x, risch=True) == Integral(erf(x), x)
|
1331 |
+
# TODO: How to test risch=False?
|
1332 |
+
|
1333 |
+
|
1334 |
+
@slow
|
1335 |
+
def test_heurisch_option():
|
1336 |
+
raises(ValueError, lambda: integrate(1/x, x, risch=True, heurisch=True))
|
1337 |
+
# an integral that heurisch can handle
|
1338 |
+
assert integrate(exp(x**2), x, heurisch=True) == sqrt(pi)*erfi(x)/2
|
1339 |
+
# an integral that heurisch currently cannot handle
|
1340 |
+
assert integrate(exp(x)/x, x, heurisch=True) == Integral(exp(x)/x, x)
|
1341 |
+
# an integral where heurisch currently hangs, issue 15471
|
1342 |
+
assert integrate(log(x)*cos(log(x))/x**Rational(3, 4), x, heurisch=False) == (
|
1343 |
+
-128*x**Rational(1, 4)*sin(log(x))/289 + 240*x**Rational(1, 4)*cos(log(x))/289 +
|
1344 |
+
(16*x**Rational(1, 4)*sin(log(x))/17 + 4*x**Rational(1, 4)*cos(log(x))/17)*log(x))
|
1345 |
+
|
1346 |
+
|
1347 |
+
def test_issue_6828():
|
1348 |
+
f = 1/(1.08*x**2 - 4.3)
|
1349 |
+
g = integrate(f, x).diff(x)
|
1350 |
+
assert verify_numerically(f, g, tol=1e-12)
|
1351 |
+
|
1352 |
+
|
1353 |
+
def test_issue_4803():
|
1354 |
+
x_max = Symbol("x_max")
|
1355 |
+
assert integrate(y/pi*exp(-(x_max - x)/cos(a)), x) == \
|
1356 |
+
y*exp((x - x_max)/cos(a))*cos(a)/pi
|
1357 |
+
|
1358 |
+
|
1359 |
+
def test_issue_4234():
|
1360 |
+
assert integrate(1/sqrt(1 + tan(x)**2)) == tan(x)/sqrt(1 + tan(x)**2)
|
1361 |
+
|
1362 |
+
|
1363 |
+
def test_issue_4492():
|
1364 |
+
assert simplify(integrate(x**2 * sqrt(5 - x**2), x)).factor(
|
1365 |
+
deep=True) == Piecewise(
|
1366 |
+
(I*(2*x**5 - 15*x**3 + 25*x - 25*sqrt(x**2 - 5)*acosh(sqrt(5)*x/5)) /
|
1367 |
+
(8*sqrt(x**2 - 5)), (x > sqrt(5)) | (x < -sqrt(5))),
|
1368 |
+
((2*x**5 - 15*x**3 + 25*x - 25*sqrt(5 - x**2)*asin(sqrt(5)*x/5)) /
|
1369 |
+
(-8*sqrt(-x**2 + 5)), True))
|
1370 |
+
|
1371 |
+
|
1372 |
+
def test_issue_2708():
|
1373 |
+
# This test needs to use an integration function that can
|
1374 |
+
# not be evaluated in closed form. Update as needed.
|
1375 |
+
f = 1/(a + z + log(z))
|
1376 |
+
integral_f = NonElementaryIntegral(f, (z, 2, 3))
|
1377 |
+
assert Integral(f, (z, 2, 3)).doit() == integral_f
|
1378 |
+
assert integrate(f + exp(z), (z, 2, 3)) == integral_f - exp(2) + exp(3)
|
1379 |
+
assert integrate(2*f + exp(z), (z, 2, 3)) == \
|
1380 |
+
2*integral_f - exp(2) + exp(3)
|
1381 |
+
assert integrate(exp(1.2*n*s*z*(-t + z)/t), (z, 0, x)) == \
|
1382 |
+
NonElementaryIntegral(exp(-1.2*n*s*z)*exp(1.2*n*s*z**2/t),
|
1383 |
+
(z, 0, x))
|
1384 |
+
|
1385 |
+
|
1386 |
+
def test_issue_2884():
|
1387 |
+
f = (4.000002016020*x + 4.000002016020*y + 4.000006024032)*exp(10.0*x)
|
1388 |
+
e = integrate(f, (x, 0.1, 0.2))
|
1389 |
+
assert str(e) == '1.86831064982608*y + 2.16387491480008'
|
1390 |
+
|
1391 |
+
|
1392 |
+
def test_issue_8368i():
|
1393 |
+
from sympy.functions.elementary.complexes import arg, Abs
|
1394 |
+
assert integrate(exp(-s*x)*cosh(x), (x, 0, oo)) == \
|
1395 |
+
Piecewise(
|
1396 |
+
( pi*Piecewise(
|
1397 |
+
( -s/(pi*(-s**2 + 1)),
|
1398 |
+
Abs(s**2) < 1),
|
1399 |
+
( 1/(pi*s*(1 - 1/s**2)),
|
1400 |
+
Abs(s**(-2)) < 1),
|
1401 |
+
( meijerg(
|
1402 |
+
((S.Half,), (0, 0)),
|
1403 |
+
((0, S.Half), (0,)),
|
1404 |
+
polar_lift(s)**2),
|
1405 |
+
True)
|
1406 |
+
),
|
1407 |
+
s**2 > 1
|
1408 |
+
),
|
1409 |
+
(
|
1410 |
+
Integral(exp(-s*x)*cosh(x), (x, 0, oo)),
|
1411 |
+
True))
|
1412 |
+
assert integrate(exp(-s*x)*sinh(x), (x, 0, oo)) == \
|
1413 |
+
Piecewise(
|
1414 |
+
( -1/(s + 1)/2 - 1/(-s + 1)/2,
|
1415 |
+
And(
|
1416 |
+
Abs(s) > 1,
|
1417 |
+
Abs(arg(s)) < pi/2,
|
1418 |
+
Abs(arg(s)) <= pi/2
|
1419 |
+
)),
|
1420 |
+
( Integral(exp(-s*x)*sinh(x), (x, 0, oo)),
|
1421 |
+
True))
|
1422 |
+
|
1423 |
+
|
1424 |
+
def test_issue_8901():
|
1425 |
+
assert integrate(sinh(1.0*x)) == 1.0*cosh(1.0*x)
|
1426 |
+
assert integrate(tanh(1.0*x)) == 1.0*x - 1.0*log(tanh(1.0*x) + 1)
|
1427 |
+
assert integrate(tanh(x)) == x - log(tanh(x) + 1)
|
1428 |
+
|
1429 |
+
|
1430 |
+
@slow
|
1431 |
+
def test_issue_8945():
|
1432 |
+
assert integrate(sin(x)**3/x, (x, 0, 1)) == -Si(3)/4 + 3*Si(1)/4
|
1433 |
+
assert integrate(sin(x)**3/x, (x, 0, oo)) == pi/4
|
1434 |
+
assert integrate(cos(x)**2/x**2, x) == -Si(2*x) - cos(2*x)/(2*x) - 1/(2*x)
|
1435 |
+
|
1436 |
+
|
1437 |
+
@slow
|
1438 |
+
def test_issue_7130():
|
1439 |
+
if ON_CI:
|
1440 |
+
skip("Too slow for CI.")
|
1441 |
+
i, L, a, b = symbols('i L a b')
|
1442 |
+
integrand = (cos(pi*i*x/L)**2 / (a + b*x)).rewrite(exp)
|
1443 |
+
assert x not in integrate(integrand, (x, 0, L)).free_symbols
|
1444 |
+
|
1445 |
+
|
1446 |
+
def test_issue_10567():
|
1447 |
+
a, b, c, t = symbols('a b c t')
|
1448 |
+
vt = Matrix([a*t, b, c])
|
1449 |
+
assert integrate(vt, t) == Integral(vt, t).doit()
|
1450 |
+
assert integrate(vt, t) == Matrix([[a*t**2/2], [b*t], [c*t]])
|
1451 |
+
|
1452 |
+
|
1453 |
+
def test_issue_11742():
|
1454 |
+
assert integrate(sqrt(-x**2 + 8*x + 48), (x, 4, 12)) == 16*pi
|
1455 |
+
|
1456 |
+
|
1457 |
+
def test_issue_11856():
|
1458 |
+
t = symbols('t')
|
1459 |
+
assert integrate(sinc(pi*t), t) == Si(pi*t)/pi
|
1460 |
+
|
1461 |
+
|
1462 |
+
@slow
|
1463 |
+
def test_issue_11876():
|
1464 |
+
assert integrate(sqrt(log(1/x)), (x, 0, 1)) == sqrt(pi)/2
|
1465 |
+
|
1466 |
+
|
1467 |
+
def test_issue_4950():
|
1468 |
+
assert integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) ==\
|
1469 |
+
-2.4*exp(8*x) - 12.0*exp(5*x)
|
1470 |
+
|
1471 |
+
|
1472 |
+
def test_issue_4968():
|
1473 |
+
assert integrate(sin(log(x**2))) == x*sin(log(x**2))/5 - 2*x*cos(log(x**2))/5
|
1474 |
+
|
1475 |
+
|
1476 |
+
def test_singularities():
|
1477 |
+
assert integrate(1/x**2, (x, -oo, oo)) is oo
|
1478 |
+
assert integrate(1/x**2, (x, -1, 1)) is oo
|
1479 |
+
assert integrate(1/(x - 1)**2, (x, -2, 2)) is oo
|
1480 |
+
|
1481 |
+
assert integrate(1/x**2, (x, 1, -1)) is -oo
|
1482 |
+
assert integrate(1/(x - 1)**2, (x, 2, -2)) is -oo
|
1483 |
+
|
1484 |
+
|
1485 |
+
def test_issue_12645():
|
1486 |
+
x, y = symbols('x y', real=True)
|
1487 |
+
assert (integrate(sin(x*x*x + y*y),
|
1488 |
+
(x, -sqrt(pi - y*y), sqrt(pi - y*y)),
|
1489 |
+
(y, -sqrt(pi), sqrt(pi)))
|
1490 |
+
== Integral(sin(x**3 + y**2),
|
1491 |
+
(x, -sqrt(-y**2 + pi), sqrt(-y**2 + pi)),
|
1492 |
+
(y, -sqrt(pi), sqrt(pi))))
|
1493 |
+
|
1494 |
+
|
1495 |
+
def test_issue_12677():
|
1496 |
+
assert integrate(sin(x) / (cos(x)**3), (x, 0, pi/6)) == Rational(1, 6)
|
1497 |
+
|
1498 |
+
|
1499 |
+
def test_issue_14078():
|
1500 |
+
assert integrate((cos(3*x)-cos(x))/x, (x, 0, oo)) == -log(3)
|
1501 |
+
|
1502 |
+
|
1503 |
+
def test_issue_14064():
|
1504 |
+
assert integrate(1/cosh(x), (x, 0, oo)) == pi/2
|
1505 |
+
|
1506 |
+
|
1507 |
+
def test_issue_14027():
|
1508 |
+
assert integrate(1/(1 + exp(x - S.Half)/(1 + exp(x))), x) == \
|
1509 |
+
x - exp(S.Half)*log(exp(x) + exp(S.Half)/(1 + exp(S.Half)))/(exp(S.Half) + E)
|
1510 |
+
|
1511 |
+
|
1512 |
+
def test_issue_8170():
|
1513 |
+
assert integrate(tan(x), (x, 0, pi/2)) is S.Infinity
|
1514 |
+
|
1515 |
+
|
1516 |
+
def test_issue_8440_14040():
|
1517 |
+
assert integrate(1/x, (x, -1, 1)) is S.NaN
|
1518 |
+
assert integrate(1/(x + 1), (x, -2, 3)) is S.NaN
|
1519 |
+
|
1520 |
+
|
1521 |
+
def test_issue_14096():
|
1522 |
+
assert integrate(1/(x + y)**2, (x, 0, 1)) == -1/(y + 1) + 1/y
|
1523 |
+
assert integrate(1/(1 + x + y + z)**2, (x, 0, 1), (y, 0, 1), (z, 0, 1)) == \
|
1524 |
+
-4*log(4) - 6*log(2) + 9*log(3)
|
1525 |
+
|
1526 |
+
|
1527 |
+
def test_issue_14144():
|
1528 |
+
assert Abs(integrate(1/sqrt(1 - x**3), (x, 0, 1)).n() - 1.402182) < 1e-6
|
1529 |
+
assert Abs(integrate(sqrt(1 - x**3), (x, 0, 1)).n() - 0.841309) < 1e-6
|
1530 |
+
|
1531 |
+
|
1532 |
+
def test_issue_14375():
|
1533 |
+
# This raised a TypeError. The antiderivative has exp_polar, which
|
1534 |
+
# may be possible to unpolarify, so the exact output is not asserted here.
|
1535 |
+
assert integrate(exp(I*x)*log(x), x).has(Ei)
|
1536 |
+
|
1537 |
+
|
1538 |
+
def test_issue_14437():
|
1539 |
+
f = Function('f')(x, y, z)
|
1540 |
+
assert integrate(f, (x, 0, 1), (y, 0, 2), (z, 0, 3)) == \
|
1541 |
+
Integral(f, (x, 0, 1), (y, 0, 2), (z, 0, 3))
|
1542 |
+
|
1543 |
+
|
1544 |
+
def test_issue_14470():
|
1545 |
+
assert integrate(1/sqrt(exp(x) + 1), x) == log(sqrt(exp(x) + 1) - 1) - log(sqrt(exp(x) + 1) + 1)
|
1546 |
+
|
1547 |
+
|
1548 |
+
def test_issue_14877():
|
1549 |
+
f = exp(1 - exp(x**2)*x + 2*x**2)*(2*x**3 + x)/(1 - exp(x**2)*x)**2
|
1550 |
+
assert integrate(f, x) == \
|
1551 |
+
-exp(2*x**2 - x*exp(x**2) + 1)/(x*exp(3*x**2) - exp(2*x**2))
|
1552 |
+
|
1553 |
+
|
1554 |
+
def test_issue_14782():
|
1555 |
+
f = sqrt(-x**2 + 1)*(-x**2 + x)
|
1556 |
+
assert integrate(f, [x, -1, 1]) == - pi / 8
|
1557 |
+
|
1558 |
+
|
1559 |
+
@slow
|
1560 |
+
def test_issue_14782_slow():
|
1561 |
+
f = sqrt(-x**2 + 1)*(-x**2 + x)
|
1562 |
+
assert integrate(f, [x, 0, 1]) == S.One / 3 - pi / 16
|
1563 |
+
|
1564 |
+
|
1565 |
+
def test_issue_12081():
|
1566 |
+
f = x**(Rational(-3, 2))*exp(-x)
|
1567 |
+
assert integrate(f, [x, 0, oo]) is oo
|
1568 |
+
|
1569 |
+
|
1570 |
+
def test_issue_15285():
|
1571 |
+
y = 1/x - 1
|
1572 |
+
f = 4*y*exp(-2*y)/x**2
|
1573 |
+
assert integrate(f, [x, 0, 1]) == 1
|
1574 |
+
|
1575 |
+
|
1576 |
+
def test_issue_15432():
|
1577 |
+
assert integrate(x**n * exp(-x) * log(x), (x, 0, oo)).gammasimp() == Piecewise(
|
1578 |
+
(gamma(n + 1)*polygamma(0, n) + gamma(n + 1)/n, re(n) + 1 > 0),
|
1579 |
+
(Integral(x**n*exp(-x)*log(x), (x, 0, oo)), True))
|
1580 |
+
|
1581 |
+
|
1582 |
+
def test_issue_15124():
|
1583 |
+
omega = IndexedBase('omega')
|
1584 |
+
m, p = symbols('m p', cls=Idx)
|
1585 |
+
assert integrate(exp(x*I*(omega[m] + omega[p])), x, conds='none') == \
|
1586 |
+
-I*exp(I*x*omega[m])*exp(I*x*omega[p])/(omega[m] + omega[p])
|
1587 |
+
|
1588 |
+
|
1589 |
+
def test_issue_15218():
|
1590 |
+
with warns_deprecated_sympy():
|
1591 |
+
Integral(Eq(x, y))
|
1592 |
+
with warns_deprecated_sympy():
|
1593 |
+
assert Integral(Eq(x, y), x) == Eq(Integral(x, x), Integral(y, x))
|
1594 |
+
with warns_deprecated_sympy():
|
1595 |
+
assert Integral(Eq(x, y), x).doit() == Eq(x**2/2, x*y)
|
1596 |
+
with warns(SymPyDeprecationWarning, test_stacklevel=False):
|
1597 |
+
# The warning is made in the ExprWithLimits superclass. The stacklevel
|
1598 |
+
# is correct for integrate(Eq) but not Eq.integrate
|
1599 |
+
assert Eq(x, y).integrate(x) == Eq(x**2/2, x*y)
|
1600 |
+
|
1601 |
+
# These are not deprecated because they are definite integrals
|
1602 |
+
assert integrate(Eq(x, y), (x, 0, 1)) == Eq(S.Half, y)
|
1603 |
+
assert Eq(x, y).integrate((x, 0, 1)) == Eq(S.Half, y)
|
1604 |
+
|
1605 |
+
|
1606 |
+
def test_issue_15292():
|
1607 |
+
res = integrate(exp(-x**2*cos(2*t)) * cos(x**2*sin(2*t)), (x, 0, oo))
|
1608 |
+
assert isinstance(res, Piecewise)
|
1609 |
+
assert gammasimp((res - sqrt(pi)/2 * cos(t)).subs(t, pi/6)) == 0
|
1610 |
+
|
1611 |
+
|
1612 |
+
def test_issue_4514():
|
1613 |
+
assert integrate(sin(2*x)/sin(x), x) == 2*sin(x)
|
1614 |
+
|
1615 |
+
|
1616 |
+
def test_issue_15457():
|
1617 |
+
x, a, b = symbols('x a b', real=True)
|
1618 |
+
definite = integrate(exp(Abs(x-2)), (x, a, b))
|
1619 |
+
indefinite = integrate(exp(Abs(x-2)), x)
|
1620 |
+
assert definite.subs({a: 1, b: 3}) == -2 + 2*E
|
1621 |
+
assert indefinite.subs(x, 3) - indefinite.subs(x, 1) == -2 + 2*E
|
1622 |
+
assert definite.subs({a: -3, b: -1}) == -exp(3) + exp(5)
|
1623 |
+
assert indefinite.subs(x, -1) - indefinite.subs(x, -3) == -exp(3) + exp(5)
|
1624 |
+
|
1625 |
+
|
1626 |
+
def test_issue_15431():
|
1627 |
+
assert integrate(x*exp(x)*log(x), x) == \
|
1628 |
+
(x*exp(x) - exp(x))*log(x) - exp(x) + Ei(x)
|
1629 |
+
|
1630 |
+
|
1631 |
+
def test_issue_15640_log_substitutions():
|
1632 |
+
f = x/log(x)
|
1633 |
+
F = Ei(2*log(x))
|
1634 |
+
assert integrate(f, x) == F and F.diff(x) == f
|
1635 |
+
f = x**3/log(x)**2
|
1636 |
+
F = -x**4/log(x) + 4*Ei(4*log(x))
|
1637 |
+
assert integrate(f, x) == F and F.diff(x) == f
|
1638 |
+
f = sqrt(log(x))/x**2
|
1639 |
+
F = -sqrt(pi)*erfc(sqrt(log(x)))/2 - sqrt(log(x))/x
|
1640 |
+
assert integrate(f, x) == F and F.diff(x) == f
|
1641 |
+
|
1642 |
+
|
1643 |
+
def test_issue_15509():
|
1644 |
+
from sympy.vector import CoordSys3D
|
1645 |
+
N = CoordSys3D('N')
|
1646 |
+
x = N.x
|
1647 |
+
assert integrate(cos(a*x + b), (x, x_1, x_2), heurisch=True) == Piecewise(
|
1648 |
+
(-sin(a*x_1 + b)/a + sin(a*x_2 + b)/a, (a > -oo) & (a < oo) & Ne(a, 0)), \
|
1649 |
+
(-x_1*cos(b) + x_2*cos(b), True))
|
1650 |
+
|
1651 |
+
|
1652 |
+
def test_issue_4311_fast():
|
1653 |
+
x = symbols('x', real=True)
|
1654 |
+
assert integrate(x*abs(9-x**2), x) == Piecewise(
|
1655 |
+
(x**4/4 - 9*x**2/2, x <= -3),
|
1656 |
+
(-x**4/4 + 9*x**2/2 - Rational(81, 2), x <= 3),
|
1657 |
+
(x**4/4 - 9*x**2/2, True))
|
1658 |
+
|
1659 |
+
|
1660 |
+
def test_integrate_with_complex_constants():
|
1661 |
+
K = Symbol('K', positive=True)
|
1662 |
+
x = Symbol('x', real=True)
|
1663 |
+
m = Symbol('m', real=True)
|
1664 |
+
t = Symbol('t', real=True)
|
1665 |
+
assert integrate(exp(-I*K*x**2+m*x), x) == sqrt(I)*sqrt(pi)*exp(-I*m**2
|
1666 |
+
/(4*K))*erfi((-2*I*K*x + m)/(2*sqrt(K)*sqrt(-I)))/(2*sqrt(K))
|
1667 |
+
assert integrate(1/(1 + I*x**2), x) == (-I*(sqrt(-I)*log(x - I*sqrt(-I))/2
|
1668 |
+
- sqrt(-I)*log(x + I*sqrt(-I))/2))
|
1669 |
+
assert integrate(exp(-I*x**2), x) == sqrt(pi)*erf(sqrt(I)*x)/(2*sqrt(I))
|
1670 |
+
|
1671 |
+
assert integrate((1/(exp(I*t)-2)), t) == -t/2 - I*log(exp(I*t) - 2)/2
|
1672 |
+
assert integrate((1/(exp(I*t)-2)), (t, 0, 2*pi)) == -pi
|
1673 |
+
|
1674 |
+
|
1675 |
+
def test_issue_14241():
|
1676 |
+
x = Symbol('x')
|
1677 |
+
n = Symbol('n', positive=True, integer=True)
|
1678 |
+
assert integrate(n * x ** (n - 1) / (x + 1), x) == \
|
1679 |
+
n**2*x**n*lerchphi(x*exp_polar(I*pi), 1, n)*gamma(n)/gamma(n + 1)
|
1680 |
+
|
1681 |
+
|
1682 |
+
def test_issue_13112():
|
1683 |
+
assert integrate(sin(t)**2 / (5 - 4*cos(t)), [t, 0, 2*pi]) == pi / 4
|
1684 |
+
|
1685 |
+
|
1686 |
+
def test_issue_14709b():
|
1687 |
+
h = Symbol('h', positive=True)
|
1688 |
+
i = integrate(x*acos(1 - 2*x/h), (x, 0, h))
|
1689 |
+
assert i == 5*h**2*pi/16
|
1690 |
+
|
1691 |
+
|
1692 |
+
def test_issue_8614():
|
1693 |
+
x = Symbol('x')
|
1694 |
+
t = Symbol('t')
|
1695 |
+
assert integrate(exp(t)/t, (t, -oo, x)) == Ei(x)
|
1696 |
+
assert integrate((exp(-x) - exp(-2*x))/x, (x, 0, oo)) == log(2)
|
1697 |
+
|
1698 |
+
|
1699 |
+
@slow
|
1700 |
+
def test_issue_15494():
|
1701 |
+
s = symbols('s', positive=True)
|
1702 |
+
|
1703 |
+
integrand = (exp(s/2) - 2*exp(1.6*s) + exp(s))*exp(s)
|
1704 |
+
solution = integrate(integrand, s)
|
1705 |
+
assert solution != S.NaN
|
1706 |
+
# Not sure how to test this properly as it is a symbolic expression with floats
|
1707 |
+
# assert str(solution) == '0.666666666666667*exp(1.5*s) + 0.5*exp(2.0*s) - 0.769230769230769*exp(2.6*s)'
|
1708 |
+
# Maybe
|
1709 |
+
assert abs(solution.subs(s, 1) - (-3.67440080236188)) <= 1e-8
|
1710 |
+
|
1711 |
+
integrand = (exp(s/2) - 2*exp(S(8)/5*s) + exp(s))*exp(s)
|
1712 |
+
assert integrate(integrand, s) == -10*exp(13*s/5)/13 + 2*exp(3*s/2)/3 + exp(2*s)/2
|
1713 |
+
|
1714 |
+
|
1715 |
+
def test_li_integral():
|
1716 |
+
y = Symbol('y')
|
1717 |
+
assert Integral(li(y*x**2), x).doit() == Piecewise((x*li(x**2*y) - \
|
1718 |
+
x*Ei(3*log(x**2*y)/2)/sqrt(x**2*y),
|
1719 |
+
Ne(y, 0)), (0, True))
|
1720 |
+
|
1721 |
+
|
1722 |
+
def test_issue_17473():
|
1723 |
+
x = Symbol('x')
|
1724 |
+
n = Symbol('n')
|
1725 |
+
h = S.Half
|
1726 |
+
ans = x**(n + 1)*gamma(h + h/n)*hyper((h + h/n,),
|
1727 |
+
(3*h, 3*h + h/n), -x**(2*n)/4)/(2*n*gamma(3*h + h/n))
|
1728 |
+
got = integrate(sin(x**n), x)
|
1729 |
+
assert got == ans
|
1730 |
+
_x = Symbol('x', zero=False)
|
1731 |
+
reps = {x: _x}
|
1732 |
+
assert integrate(sin(_x**n), _x) == ans.xreplace(reps).expand()
|
1733 |
+
|
1734 |
+
|
1735 |
+
def test_issue_17671():
|
1736 |
+
assert integrate(log(log(x)) / x**2, [x, 1, oo]) == -EulerGamma
|
1737 |
+
assert integrate(log(log(x)) / x**3, [x, 1, oo]) == -log(2)/2 - EulerGamma/2
|
1738 |
+
assert integrate(log(log(x)) / x**10, [x, 1, oo]) == -log(9)/9 - EulerGamma/9
|
1739 |
+
|
1740 |
+
|
1741 |
+
def test_issue_2975():
|
1742 |
+
w = Symbol('w')
|
1743 |
+
C = Symbol('C')
|
1744 |
+
y = Symbol('y')
|
1745 |
+
assert integrate(1/(y**2+C)**(S(3)/2), (y, -w/2, w/2)) == w/(C**(S(3)/2)*sqrt(1 + w**2/(4*C)))
|
1746 |
+
|
1747 |
+
|
1748 |
+
def test_issue_7827():
|
1749 |
+
x, n, M = symbols('x n M')
|
1750 |
+
N = Symbol('N', integer=True)
|
1751 |
+
assert integrate(summation(x*n, (n, 1, N)), x) == x**2*(N**2/4 + N/4)
|
1752 |
+
assert integrate(summation(x*sin(n), (n,1,N)), x) == \
|
1753 |
+
Sum(x**2*sin(n)/2, (n, 1, N))
|
1754 |
+
assert integrate(summation(sin(n*x), (n,1,N)), x) == \
|
1755 |
+
Sum(Piecewise((-cos(n*x)/n, Ne(n, 0)), (0, True)), (n, 1, N))
|
1756 |
+
assert integrate(integrate(summation(sin(n*x), (n,1,N)), x), x) == \
|
1757 |
+
Piecewise((Sum(Piecewise((-sin(n*x)/n**2, Ne(n, 0)), (-x/n, True)),
|
1758 |
+
(n, 1, N)), (n > -oo) & (n < oo) & Ne(n, 0)), (0, True))
|
1759 |
+
assert integrate(Sum(x, (n, 1, M)), x) == M*x**2/2
|
1760 |
+
raises(ValueError, lambda: integrate(Sum(x, (x, y, n)), y))
|
1761 |
+
raises(ValueError, lambda: integrate(Sum(x, (x, 1, n)), n))
|
1762 |
+
raises(ValueError, lambda: integrate(Sum(x, (x, 1, y)), x))
|
1763 |
+
|
1764 |
+
|
1765 |
+
def test_issue_4231():
|
1766 |
+
f = (1 + 2*x + sqrt(x + log(x))*(1 + 3*x) + x**2)/(x*(x + sqrt(x + log(x)))*sqrt(x + log(x)))
|
1767 |
+
assert integrate(f, x) == 2*sqrt(x + log(x)) + 2*log(x + sqrt(x + log(x)))
|
1768 |
+
|
1769 |
+
|
1770 |
+
def test_issue_17841():
|
1771 |
+
f = diff(1/(x**2+x+I), x)
|
1772 |
+
assert integrate(f, x) == 1/(x**2 + x + I)
|
1773 |
+
|
1774 |
+
|
1775 |
+
def test_issue_21034():
|
1776 |
+
x = Symbol('x', real=True, nonzero=True)
|
1777 |
+
f1 = x*(-x**4/asin(5)**4 - x*sinh(x + log(asin(5))) + 5)
|
1778 |
+
f2 = (x + cosh(cos(4)))/(x*(x + 1/(12*x)))
|
1779 |
+
|
1780 |
+
assert integrate(f1, x) == \
|
1781 |
+
-x**6/(6*asin(5)**4) - x**2*cosh(x + log(asin(5))) + 5*x**2/2 + 2*x*sinh(x + log(asin(5))) - 2*cosh(x + log(asin(5)))
|
1782 |
+
|
1783 |
+
assert integrate(f2, x) == \
|
1784 |
+
log(x**2 + S(1)/12)/2 + 2*sqrt(3)*cosh(cos(4))*atan(2*sqrt(3)*x)
|
1785 |
+
|
1786 |
+
|
1787 |
+
def test_issue_4187():
|
1788 |
+
assert integrate(log(x)*exp(-x), x) == Ei(-x) - exp(-x)*log(x)
|
1789 |
+
assert integrate(log(x)*exp(-x), (x, 0, oo)) == -EulerGamma
|
1790 |
+
|
1791 |
+
|
1792 |
+
def test_issue_5547():
|
1793 |
+
L = Symbol('L')
|
1794 |
+
z = Symbol('z')
|
1795 |
+
r0 = Symbol('r0')
|
1796 |
+
R0 = Symbol('R0')
|
1797 |
+
|
1798 |
+
assert integrate(r0**2*cos(z)**2, (z, -L/2, L/2)) == -r0**2*(-L/4 -
|
1799 |
+
sin(L/2)*cos(L/2)/2) + r0**2*(L/4 + sin(L/2)*cos(L/2)/2)
|
1800 |
+
|
1801 |
+
assert integrate(r0**2*cos(R0*z)**2, (z, -L/2, L/2)) == Piecewise(
|
1802 |
+
(-r0**2*(-L*R0/4 - sin(L*R0/2)*cos(L*R0/2)/2)/R0 +
|
1803 |
+
r0**2*(L*R0/4 + sin(L*R0/2)*cos(L*R0/2)/2)/R0, (R0 > -oo) & (R0 < oo) & Ne(R0, 0)),
|
1804 |
+
(L*r0**2, True))
|
1805 |
+
|
1806 |
+
w = 2*pi*z/L
|
1807 |
+
|
1808 |
+
sol = sqrt(2)*sqrt(L)*r0**2*fresnelc(sqrt(2)*sqrt(L))*gamma(S.One/4)/(16*gamma(S(5)/4)) + L*r0**2/2
|
1809 |
+
|
1810 |
+
assert integrate(r0**2*cos(w*z)**2, (z, -L/2, L/2)) == sol
|
1811 |
+
|
1812 |
+
|
1813 |
+
def test_issue_15810():
|
1814 |
+
assert integrate(1/(2**(2*x/3) + 1), (x, 0, oo)) == Rational(3, 2)
|
1815 |
+
|
1816 |
+
|
1817 |
+
def test_issue_21024():
|
1818 |
+
x = Symbol('x', real=True, nonzero=True)
|
1819 |
+
f = log(x)*log(4*x) + log(3*x + exp(2))
|
1820 |
+
F = x*log(x)**2 + x*(1 - 2*log(2)) + (-2*x + 2*x*log(2))*log(x) + \
|
1821 |
+
(x + exp(2)/6)*log(3*x + exp(2)) + exp(2)*log(3*x + exp(2))/6
|
1822 |
+
assert F == integrate(f, x)
|
1823 |
+
|
1824 |
+
f = (x + exp(3))/x**2
|
1825 |
+
F = log(x) - exp(3)/x
|
1826 |
+
assert F == integrate(f, x)
|
1827 |
+
|
1828 |
+
f = (x**2 + exp(5))/x
|
1829 |
+
F = x**2/2 + exp(5)*log(x)
|
1830 |
+
assert F == integrate(f, x)
|
1831 |
+
|
1832 |
+
f = x/(2*x + tanh(1))
|
1833 |
+
F = x/2 - log(2*x + tanh(1))*tanh(1)/4
|
1834 |
+
assert F == integrate(f, x)
|
1835 |
+
|
1836 |
+
f = x - sinh(4)/x
|
1837 |
+
F = x**2/2 - log(x)*sinh(4)
|
1838 |
+
assert F == integrate(f, x)
|
1839 |
+
|
1840 |
+
f = log(x + exp(5)/x)
|
1841 |
+
F = x*log(x + exp(5)/x) - x + 2*exp(Rational(5, 2))*atan(x*exp(Rational(-5, 2)))
|
1842 |
+
assert F == integrate(f, x)
|
1843 |
+
|
1844 |
+
f = x**5/(x + E)
|
1845 |
+
F = x**5/5 - E*x**4/4 + x**3*exp(2)/3 - x**2*exp(3)/2 + x*exp(4) - exp(5)*log(x + E)
|
1846 |
+
assert F == integrate(f, x)
|
1847 |
+
|
1848 |
+
f = 4*x/(x + sinh(5))
|
1849 |
+
F = 4*x - 4*log(x + sinh(5))*sinh(5)
|
1850 |
+
assert F == integrate(f, x)
|
1851 |
+
|
1852 |
+
f = x**2/(2*x + sinh(2))
|
1853 |
+
F = x**2/4 - x*sinh(2)/4 + log(2*x + sinh(2))*sinh(2)**2/8
|
1854 |
+
assert F == integrate(f, x)
|
1855 |
+
|
1856 |
+
f = -x**2/(x + E)
|
1857 |
+
F = -x**2/2 + E*x - exp(2)*log(x + E)
|
1858 |
+
assert F == integrate(f, x)
|
1859 |
+
|
1860 |
+
f = (2*x + 3)*exp(5)/x
|
1861 |
+
F = 2*x*exp(5) + 3*exp(5)*log(x)
|
1862 |
+
assert F == integrate(f, x)
|
1863 |
+
|
1864 |
+
f = x + 2 + cosh(3)/x
|
1865 |
+
F = x**2/2 + 2*x + log(x)*cosh(3)
|
1866 |
+
assert F == integrate(f, x)
|
1867 |
+
|
1868 |
+
f = x - tanh(1)/x**3
|
1869 |
+
F = x**2/2 + tanh(1)/(2*x**2)
|
1870 |
+
assert F == integrate(f, x)
|
1871 |
+
|
1872 |
+
f = (3*x - exp(6))/x
|
1873 |
+
F = 3*x - exp(6)*log(x)
|
1874 |
+
assert F == integrate(f, x)
|
1875 |
+
|
1876 |
+
f = x**4/(x + exp(5))**2 + x
|
1877 |
+
F = x**3/3 + x**2*(Rational(1, 2) - exp(5)) + 3*x*exp(10) - 4*exp(15)*log(x + exp(5)) - exp(20)/(x + exp(5))
|
1878 |
+
assert F == integrate(f, x)
|
1879 |
+
|
1880 |
+
f = x*(x + exp(10)/x**2) + x
|
1881 |
+
F = x**3/3 + x**2/2 + exp(10)*log(x)
|
1882 |
+
assert F == integrate(f, x)
|
1883 |
+
|
1884 |
+
f = x + x/(5*x + sinh(3))
|
1885 |
+
F = x**2/2 + x/5 - log(5*x + sinh(3))*sinh(3)/25
|
1886 |
+
assert F == integrate(f, x)
|
1887 |
+
|
1888 |
+
f = (x + exp(3))/(2*x**2 + 2*x)
|
1889 |
+
F = exp(3)*log(x)/2 - exp(3)*log(x + 1)/2 + log(x + 1)/2
|
1890 |
+
assert F == integrate(f, x).expand()
|
1891 |
+
|
1892 |
+
f = log(x + 4*sinh(4))
|
1893 |
+
F = x*log(x + 4*sinh(4)) - x + 4*log(x + 4*sinh(4))*sinh(4)
|
1894 |
+
assert F == integrate(f, x)
|
1895 |
+
|
1896 |
+
f = -x + 20*(exp(-5) - atan(4)/x)**3*sin(4)/x
|
1897 |
+
F = (-x**2*exp(15)/2 + 20*log(x)*sin(4) - (-180*x**2*exp(5)*sin(4)*atan(4) + 90*x*exp(10)*sin(4)*atan(4)**2 - \
|
1898 |
+
20*exp(15)*sin(4)*atan(4)**3)/(3*x**3))*exp(-15)
|
1899 |
+
assert F == integrate(f, x)
|
1900 |
+
|
1901 |
+
f = 2*x**2*exp(-4) + 6/x
|
1902 |
+
F_true = (2*x**3/3 + 6*exp(4)*log(x))*exp(-4)
|
1903 |
+
assert F_true == integrate(f, x)
|
1904 |
+
|
1905 |
+
|
1906 |
+
def test_issue_21721():
|
1907 |
+
a = Symbol('a')
|
1908 |
+
assert integrate(1/(pi*(1+(x-a)**2)),(x,-oo,oo)).expand() == \
|
1909 |
+
-Heaviside(im(a) - 1, 0) + Heaviside(im(a) + 1, 0)
|
1910 |
+
|
1911 |
+
|
1912 |
+
def test_issue_21831():
|
1913 |
+
theta = symbols('theta')
|
1914 |
+
assert integrate(cos(3*theta)/(5-4*cos(theta)), (theta, 0, 2*pi)) == pi/12
|
1915 |
+
integrand = cos(2*theta)/(5 - 4*cos(theta))
|
1916 |
+
assert integrate(integrand, (theta, 0, 2*pi)) == pi/6
|
1917 |
+
|
1918 |
+
|
1919 |
+
@slow
|
1920 |
+
def test_issue_22033_integral():
|
1921 |
+
assert integrate((x**2 - Rational(1, 4))**2 * sqrt(1 - x**2), (x, -1, 1)) == pi/32
|
1922 |
+
|
1923 |
+
|
1924 |
+
@slow
|
1925 |
+
def test_issue_21671():
|
1926 |
+
assert integrate(1,(z,x**2+y**2,2-x**2-y**2),(y,-sqrt(1-x**2),sqrt(1-x**2)),(x,-1,1)) == pi
|
1927 |
+
assert integrate(-4*(1 - x**2)**(S(3)/2)/3 + 2*sqrt(1 - x**2)*(2 - 2*x**2), (x, -1, 1)) == pi
|
1928 |
+
|
1929 |
+
|
1930 |
+
def test_issue_18527():
|
1931 |
+
# The manual integrator can not currently solve this. Assert that it does
|
1932 |
+
# not give an incorrect result involving Abs when x has real assumptions.
|
1933 |
+
xr = symbols('xr', real=True)
|
1934 |
+
expr = (cos(x)/(4+(sin(x))**2))
|
1935 |
+
res_real = integrate(expr.subs(x, xr), xr, manual=True).subs(xr, x)
|
1936 |
+
assert integrate(expr, x, manual=True) == res_real == Integral(expr, x)
|
1937 |
+
|
1938 |
+
|
1939 |
+
def test_issue_23718():
|
1940 |
+
f = 1/(b*cos(x) + a*sin(x))
|
1941 |
+
Fpos = (-log(-a/b + tan(x/2) - sqrt(a**2 + b**2)/b)/sqrt(a**2 + b**2)
|
1942 |
+
+log(-a/b + tan(x/2) + sqrt(a**2 + b**2)/b)/sqrt(a**2 + b**2))
|
1943 |
+
F = Piecewise(
|
1944 |
+
# XXX: The zoo case here is for a=b=0 so it should just be zoo or maybe
|
1945 |
+
# it doesn't really need to be included at all given that the original
|
1946 |
+
# integrand is really undefined in that case anyway.
|
1947 |
+
(zoo*(-log(tan(x/2) - 1) + log(tan(x/2) + 1)), Eq(a, 0) & Eq(b, 0)),
|
1948 |
+
(log(tan(x/2))/a, Eq(b, 0)),
|
1949 |
+
(-I/(-I*b*sin(x) + b*cos(x)), Eq(a, -I*b)),
|
1950 |
+
(I/(I*b*sin(x) + b*cos(x)), Eq(a, I*b)),
|
1951 |
+
(Fpos, True),
|
1952 |
+
)
|
1953 |
+
assert integrate(f, x) == F
|
1954 |
+
|
1955 |
+
ap, bp = symbols('a, b', positive=True)
|
1956 |
+
rep = {a: ap, b: bp}
|
1957 |
+
assert integrate(f.subs(rep), x) == Fpos.subs(rep)
|
1958 |
+
|
1959 |
+
|
1960 |
+
def test_issue_23566():
|
1961 |
+
i = integrate(1/sqrt(x**2-1), (x, -2, -1))
|
1962 |
+
assert i == -log(2 - sqrt(3))
|
1963 |
+
assert math.isclose(i.n(), 1.31695789692482)
|
1964 |
+
|
1965 |
+
|
1966 |
+
def test_pr_23583():
|
1967 |
+
# This result from meijerg is wrong. Check whether new result is correct when this test fail.
|
1968 |
+
assert integrate(1/sqrt((x - I)**2-1)) == Piecewise((acosh(x - I), Abs((x - I)**2) > 1), (-I*asin(x - I), True))
|
1969 |
+
|
1970 |
+
|
1971 |
+
def test_issue_7264():
|
1972 |
+
assert integrate(exp(x)*sqrt(1 + exp(2*x))) == sqrt(exp(2*x) + 1)*exp(x)/2 + asinh(exp(x))/2
|
1973 |
+
|
1974 |
+
|
1975 |
+
def test_issue_11254a():
|
1976 |
+
assert integrate(sech(x), (x, 0, 1)) == 2*atan(tanh(S.Half))
|
1977 |
+
|
1978 |
+
|
1979 |
+
def test_issue_11254b():
|
1980 |
+
assert integrate(csch(x), x) == log(tanh(x/2))
|
1981 |
+
assert integrate(csch(x), (x, 0, 1)) == oo
|
1982 |
+
|
1983 |
+
|
1984 |
+
def test_issue_11254d():
|
1985 |
+
assert integrate((sech(x)**2).rewrite(sinh), x) == 2*tanh(x/2)/(tanh(x/2)**2 + 1)
|
1986 |
+
|
1987 |
+
|
1988 |
+
def test_issue_22863():
|
1989 |
+
i = integrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2), (x, 0, 1))
|
1990 |
+
assert i == -101*sqrt(2)/8 - 135*log(3 - 2*sqrt(2))/16
|
1991 |
+
assert math.isclose(i.n(), -2.98126694400554)
|
1992 |
+
|
1993 |
+
|
1994 |
+
def test_issue_9723():
|
1995 |
+
assert integrate(sqrt(x + sqrt(x))) == \
|
1996 |
+
2*sqrt(sqrt(x) + x)*(sqrt(x)/12 + x/3 - S(1)/8) + log(2*sqrt(x) + 2*sqrt(sqrt(x) + x) + 1)/8
|
1997 |
+
assert integrate(sqrt(2*x+3+sqrt(4*x+5))**3) == \
|
1998 |
+
sqrt(2*x + sqrt(4*x + 5) + 3) * \
|
1999 |
+
(9*x/10 + 11*(4*x + 5)**(S(3)/2)/40 + sqrt(4*x + 5)/40 + (4*x + 5)**2/10 + S(11)/10)/2
|
2000 |
+
|
2001 |
+
|
2002 |
+
def test_issue_23704():
|
2003 |
+
# XXX: This is testing that an exception is not raised in risch Ideally
|
2004 |
+
# manualintegrate (manual=True) would be able to compute this but
|
2005 |
+
# manualintegrate is very slow for this example so we don't test that here.
|
2006 |
+
assert (integrate(log(x)/x**2/(c*x**2+b*x+a),x, risch=True)
|
2007 |
+
== NonElementaryIntegral(log(x)/(a*x**2 + b*x**3 + c*x**4), x))
|
2008 |
+
|
2009 |
+
|
2010 |
+
def test_exp_substitution():
|
2011 |
+
assert integrate(1/sqrt(1-exp(2*x))) == log(sqrt(1 - exp(2*x)) - 1)/2 - log(sqrt(1 - exp(2*x)) + 1)/2
|
2012 |
+
|
2013 |
+
|
2014 |
+
def test_hyperbolic():
|
2015 |
+
assert integrate(coth(x)) == x - log(tanh(x) + 1) + log(tanh(x))
|
2016 |
+
assert integrate(sech(x)) == 2*atan(tanh(x/2))
|
2017 |
+
assert integrate(csch(x)) == log(tanh(x/2))
|
2018 |
+
|
2019 |
+
|
2020 |
+
def test_nested_pow():
|
2021 |
+
assert integrate(sqrt(x**2)) == x*sqrt(x**2)/2
|
2022 |
+
assert integrate(sqrt(x**(S(5)/3))) == 6*x*sqrt(x**(S(5)/3))/11
|
2023 |
+
assert integrate(1/sqrt(x**2)) == x*log(x)/sqrt(x**2)
|
2024 |
+
assert integrate(x*sqrt(x**(-4))) == x**2*sqrt(x**-4)*log(x)
|
2025 |
+
|
2026 |
+
|
2027 |
+
def test_sqrt_quadratic():
|
2028 |
+
assert integrate(1/sqrt(3*x**2+4*x+5)) == sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/3
|
2029 |
+
assert integrate(1/sqrt(-3*x**2+4*x+5)) == sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/3
|
2030 |
+
assert integrate(1/sqrt(3*x**2+4*x-5)) == sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/3
|
2031 |
+
assert integrate(1/sqrt(4*x**2-4*x+1)) == (x - S.Half)*log(x - S.Half)/(2*sqrt((x - S.Half)**2))
|
2032 |
+
assert integrate(1/sqrt(a+b*x+c*x**2), x) == \
|
2033 |
+
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0) & Ne(a - b**2/(4*c), 0)),
|
2034 |
+
((b/(2*c) + x)*log(b/(2*c) + x)/sqrt(c*(b/(2*c) + x)**2), Ne(c, 0)),
|
2035 |
+
(2*sqrt(a + b*x)/b, Ne(b, 0)), (x/sqrt(a), True))
|
2036 |
+
|
2037 |
+
assert integrate((7*x+6)/sqrt(3*x**2+4*x+5)) == \
|
2038 |
+
7*sqrt(3*x**2 + 4*x + 5)/3 + 4*sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/9
|
2039 |
+
assert integrate((7*x+6)/sqrt(-3*x**2+4*x+5)) == \
|
2040 |
+
-7*sqrt(-3*x**2 + 4*x + 5)/3 + 32*sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/9
|
2041 |
+
assert integrate((7*x+6)/sqrt(3*x**2+4*x-5)) == \
|
2042 |
+
7*sqrt(3*x**2 + 4*x - 5)/3 + 4*sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/9
|
2043 |
+
assert integrate((d+e*x)/sqrt(a+b*x+c*x**2), x) == \
|
2044 |
+
Piecewise(((-b*e/(2*c) + d) *
|
2045 |
+
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(a - b**2/(4*c), 0)),
|
2046 |
+
((b/(2*c) + x)*log(b/(2*c) + x)/sqrt(c*(b/(2*c) + x)**2), True)) +
|
2047 |
+
e*sqrt(a + b*x + c*x**2)/c, Ne(c, 0)),
|
2048 |
+
((2*d*sqrt(a + b*x) + 2*e*(-a*sqrt(a + b*x) + (a + b*x)**(S(3)/2)/3)/b)/b, Ne(b, 0)),
|
2049 |
+
((d*x + e*x**2/2)/sqrt(a), True))
|
2050 |
+
|
2051 |
+
assert integrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2)) == \
|
2052 |
+
sqrt(x**2 - 3*x + 2)*(x**2 + 13*x/4 + S(101)/8) + 135*log(2*x + 2*sqrt(x**2 - 3*x + 2) - 3)/16
|
2053 |
+
|
2054 |
+
assert integrate(sqrt(53225*x**2-66732*x+23013)) == \
|
2055 |
+
(x/2 - S(16683)/53225)*sqrt(53225*x**2 - 66732*x + 23013) + \
|
2056 |
+
111576969*sqrt(2129)*asinh(53225*x/10563 - S(11122)/3521)/1133160250
|
2057 |
+
assert integrate(sqrt(a+b*x+c*x**2), x) == \
|
2058 |
+
Piecewise(((a/2 - b**2/(8*c)) *
|
2059 |
+
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(a - b**2/(4*c), 0)),
|
2060 |
+
((b/(2*c) + x)*log(b/(2*c) + x)/sqrt(c*(b/(2*c) + x)**2), True)) +
|
2061 |
+
(b/(4*c) + x/2)*sqrt(a + b*x + c*x**2), Ne(c, 0)),
|
2062 |
+
(2*(a + b*x)**(S(3)/2)/(3*b), Ne(b, 0)),
|
2063 |
+
(sqrt(a)*x, True))
|
2064 |
+
|
2065 |
+
assert integrate(x*sqrt(x**2+2*x+4)) == \
|
2066 |
+
(x**2/3 + x/6 + S(5)/6)*sqrt(x**2 + 2*x + 4) - 3*asinh(sqrt(3)*(x + 1)/3)/2
|
2067 |
+
|
2068 |
+
|
2069 |
+
def test_mul_pow_derivative():
|
2070 |
+
assert integrate(x*sec(x)*tan(x)) == x*sec(x) - log(tan(x) + sec(x))
|
2071 |
+
assert integrate(x*sec(x)**2, x) == x*tan(x) + log(cos(x))
|
2072 |
+
assert integrate(x**3*Derivative(f(x), (x, 4))) == \
|
2073 |
+
x**3*Derivative(f(x), (x, 3)) - 3*x**2*Derivative(f(x), (x, 2)) + 6*x*Derivative(f(x), x) - 6*f(x)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_intpoly.py
ADDED
@@ -0,0 +1,627 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.functions.elementary.complexes import Abs
|
2 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
3 |
+
|
4 |
+
from sympy.core import S, Rational
|
5 |
+
|
6 |
+
from sympy.integrals.intpoly import (decompose, best_origin, distance_to_side,
|
7 |
+
polytope_integrate, point_sort,
|
8 |
+
hyperplane_parameters, main_integrate3d,
|
9 |
+
main_integrate, polygon_integrate,
|
10 |
+
lineseg_integrate, integration_reduction,
|
11 |
+
integration_reduction_dynamic, is_vertex)
|
12 |
+
|
13 |
+
from sympy.geometry.line import Segment2D
|
14 |
+
from sympy.geometry.polygon import Polygon
|
15 |
+
from sympy.geometry.point import Point, Point2D
|
16 |
+
from sympy.abc import x, y, z
|
17 |
+
|
18 |
+
from sympy.testing.pytest import slow
|
19 |
+
|
20 |
+
|
21 |
+
def test_decompose():
|
22 |
+
assert decompose(x) == {1: x}
|
23 |
+
assert decompose(x**2) == {2: x**2}
|
24 |
+
assert decompose(x*y) == {2: x*y}
|
25 |
+
assert decompose(x + y) == {1: x + y}
|
26 |
+
assert decompose(x**2 + y) == {1: y, 2: x**2}
|
27 |
+
assert decompose(8*x**2 + 4*y + 7) == {0: 7, 1: 4*y, 2: 8*x**2}
|
28 |
+
assert decompose(x**2 + 3*y*x) == {2: x**2 + 3*x*y}
|
29 |
+
assert decompose(9*x**2 + y + 4*x + x**3 + y**2*x + 3) ==\
|
30 |
+
{0: 3, 1: 4*x + y, 2: 9*x**2, 3: x**3 + x*y**2}
|
31 |
+
|
32 |
+
assert decompose(x, True) == {x}
|
33 |
+
assert decompose(x ** 2, True) == {x**2}
|
34 |
+
assert decompose(x * y, True) == {x * y}
|
35 |
+
assert decompose(x + y, True) == {x, y}
|
36 |
+
assert decompose(x ** 2 + y, True) == {y, x ** 2}
|
37 |
+
assert decompose(8 * x ** 2 + 4 * y + 7, True) == {7, 4*y, 8*x**2}
|
38 |
+
assert decompose(x ** 2 + 3 * y * x, True) == {x ** 2, 3 * x * y}
|
39 |
+
assert decompose(9 * x ** 2 + y + 4 * x + x ** 3 + y ** 2 * x + 3, True) == \
|
40 |
+
{3, y, 4*x, 9*x**2, x*y**2, x**3}
|
41 |
+
|
42 |
+
|
43 |
+
def test_best_origin():
|
44 |
+
expr1 = y ** 2 * x ** 5 + y ** 5 * x ** 7 + 7 * x + x ** 12 + y ** 7 * x
|
45 |
+
|
46 |
+
l1 = Segment2D(Point(0, 3), Point(1, 1))
|
47 |
+
l2 = Segment2D(Point(S(3) / 2, 0), Point(S(3) / 2, 3))
|
48 |
+
l3 = Segment2D(Point(0, S(3) / 2), Point(3, S(3) / 2))
|
49 |
+
l4 = Segment2D(Point(0, 2), Point(2, 0))
|
50 |
+
l5 = Segment2D(Point(0, 2), Point(1, 1))
|
51 |
+
l6 = Segment2D(Point(2, 0), Point(1, 1))
|
52 |
+
|
53 |
+
assert best_origin((2, 1), 3, l1, expr1) == (0, 3)
|
54 |
+
# XXX: Should these return exact Rational output? Maybe best_origin should
|
55 |
+
# sympify its arguments...
|
56 |
+
assert best_origin((2, 0), 3, l2, x ** 7) == (1.5, 0)
|
57 |
+
assert best_origin((0, 2), 3, l3, x ** 7) == (0, 1.5)
|
58 |
+
assert best_origin((1, 1), 2, l4, x ** 7 * y ** 3) == (0, 2)
|
59 |
+
assert best_origin((1, 1), 2, l4, x ** 3 * y ** 7) == (2, 0)
|
60 |
+
assert best_origin((1, 1), 2, l5, x ** 2 * y ** 9) == (0, 2)
|
61 |
+
assert best_origin((1, 1), 2, l6, x ** 9 * y ** 2) == (2, 0)
|
62 |
+
|
63 |
+
|
64 |
+
@slow
|
65 |
+
def test_polytope_integrate():
|
66 |
+
# Convex 2-Polytopes
|
67 |
+
# Vertex representation
|
68 |
+
assert polytope_integrate(Polygon(Point(0, 0), Point(0, 2),
|
69 |
+
Point(4, 0)), 1) == 4
|
70 |
+
assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1),
|
71 |
+
Point(1, 1), Point(1, 0)), x * y) ==\
|
72 |
+
Rational(1, 4)
|
73 |
+
assert polytope_integrate(Polygon(Point(0, 3), Point(5, 3), Point(1, 1)),
|
74 |
+
6*x**2 - 40*y) == Rational(-935, 3)
|
75 |
+
|
76 |
+
assert polytope_integrate(Polygon(Point(0, 0), Point(0, sqrt(3)),
|
77 |
+
Point(sqrt(3), sqrt(3)),
|
78 |
+
Point(sqrt(3), 0)), 1) == 3
|
79 |
+
|
80 |
+
hexagon = Polygon(Point(0, 0), Point(-sqrt(3) / 2, S.Half),
|
81 |
+
Point(-sqrt(3) / 2, S(3) / 2), Point(0, 2),
|
82 |
+
Point(sqrt(3) / 2, S(3) / 2), Point(sqrt(3) / 2, S.Half))
|
83 |
+
|
84 |
+
assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2
|
85 |
+
|
86 |
+
# Hyperplane representation
|
87 |
+
assert polytope_integrate([((-1, 0), 0), ((1, 2), 4),
|
88 |
+
((0, -1), 0)], 1) == 4
|
89 |
+
assert polytope_integrate([((-1, 0), 0), ((0, 1), 1),
|
90 |
+
((1, 0), 1), ((0, -1), 0)], x * y) == Rational(1, 4)
|
91 |
+
assert polytope_integrate([((0, 1), 3), ((1, -2), -1),
|
92 |
+
((-2, -1), -3)], 6*x**2 - 40*y) == Rational(-935, 3)
|
93 |
+
assert polytope_integrate([((-1, 0), 0), ((0, sqrt(3)), 3),
|
94 |
+
((sqrt(3), 0), 3), ((0, -1), 0)], 1) == 3
|
95 |
+
|
96 |
+
hexagon = [((Rational(-1, 2), -sqrt(3) / 2), 0),
|
97 |
+
((-1, 0), sqrt(3) / 2),
|
98 |
+
((Rational(-1, 2), sqrt(3) / 2), sqrt(3)),
|
99 |
+
((S.Half, sqrt(3) / 2), sqrt(3)),
|
100 |
+
((1, 0), sqrt(3) / 2),
|
101 |
+
((S.Half, -sqrt(3) / 2), 0)]
|
102 |
+
assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2
|
103 |
+
|
104 |
+
# Non-convex polytopes
|
105 |
+
# Vertex representation
|
106 |
+
assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1),
|
107 |
+
Point(1, 1), Point(0, 0),
|
108 |
+
Point(1, -1)), 1) == 3
|
109 |
+
assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1),
|
110 |
+
Point(0, 0), Point(1, 1),
|
111 |
+
Point(1, -1), Point(0, 0)), 1) == 2
|
112 |
+
# Hyperplane representation
|
113 |
+
assert polytope_integrate([((-1, 0), 1), ((0, 1), 1), ((1, -1), 0),
|
114 |
+
((1, 1), 0), ((0, -1), 1)], 1) == 3
|
115 |
+
assert polytope_integrate([((-1, 0), 1), ((1, 1), 0), ((-1, 1), 0),
|
116 |
+
((1, 0), 1), ((-1, -1), 0),
|
117 |
+
((1, -1), 0)], 1) == 2
|
118 |
+
|
119 |
+
# Tests for 2D polytopes mentioned in Chin et al(Page 10):
|
120 |
+
# http://dilbert.engr.ucdavis.edu/~suku/quadrature/cls-integration.pdf
|
121 |
+
fig1 = Polygon(Point(1.220, -0.827), Point(-1.490, -4.503),
|
122 |
+
Point(-3.766, -1.622), Point(-4.240, -0.091),
|
123 |
+
Point(-3.160, 4), Point(-0.981, 4.447),
|
124 |
+
Point(0.132, 4.027))
|
125 |
+
assert polytope_integrate(fig1, x**2 + x*y + y**2) ==\
|
126 |
+
S(2031627344735367)/(8*10**12)
|
127 |
+
|
128 |
+
fig2 = Polygon(Point(4.561, 2.317), Point(1.491, -1.315),
|
129 |
+
Point(-3.310, -3.164), Point(-4.845, -3.110),
|
130 |
+
Point(-4.569, 1.867))
|
131 |
+
assert polytope_integrate(fig2, x**2 + x*y + y**2) ==\
|
132 |
+
S(517091313866043)/(16*10**11)
|
133 |
+
|
134 |
+
fig3 = Polygon(Point(-2.740, -1.888), Point(-3.292, 4.233),
|
135 |
+
Point(-2.723, -0.697), Point(-0.643, -3.151))
|
136 |
+
assert polytope_integrate(fig3, x**2 + x*y + y**2) ==\
|
137 |
+
S(147449361647041)/(8*10**12)
|
138 |
+
|
139 |
+
fig4 = Polygon(Point(0.211, -4.622), Point(-2.684, 3.851),
|
140 |
+
Point(0.468, 4.879), Point(4.630, -1.325),
|
141 |
+
Point(-0.411, -1.044))
|
142 |
+
assert polytope_integrate(fig4, x**2 + x*y + y**2) ==\
|
143 |
+
S(180742845225803)/(10**12)
|
144 |
+
|
145 |
+
# Tests for many polynomials with maximum degree given(2D case).
|
146 |
+
tri = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
|
147 |
+
polys = []
|
148 |
+
expr1 = x**9*y + x**7*y**3 + 2*x**2*y**8
|
149 |
+
expr2 = x**6*y**4 + x**5*y**5 + 2*y**10
|
150 |
+
expr3 = x**10 + x**9*y + x**8*y**2 + x**5*y**5
|
151 |
+
polys.extend((expr1, expr2, expr3))
|
152 |
+
result_dict = polytope_integrate(tri, polys, max_degree=10)
|
153 |
+
assert result_dict[expr1] == Rational(615780107, 594)
|
154 |
+
assert result_dict[expr2] == Rational(13062161, 27)
|
155 |
+
assert result_dict[expr3] == Rational(1946257153, 924)
|
156 |
+
|
157 |
+
tri = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
|
158 |
+
expr1 = x**7*y**1 + 2*x**2*y**6
|
159 |
+
expr2 = x**6*y**4 + x**5*y**5 + 2*y**10
|
160 |
+
expr3 = x**10 + x**9*y + x**8*y**2 + x**5*y**5
|
161 |
+
polys.extend((expr1, expr2, expr3))
|
162 |
+
assert polytope_integrate(tri, polys, max_degree=9) == \
|
163 |
+
{x**7*y + 2*x**2*y**6: Rational(489262, 9)}
|
164 |
+
|
165 |
+
# Tests when all integral of all monomials up to a max_degree is to be
|
166 |
+
# calculated.
|
167 |
+
assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1),
|
168 |
+
Point(1, 1), Point(1, 0)),
|
169 |
+
max_degree=4) == {0: 0, 1: 1, x: S.Half,
|
170 |
+
x ** 2 * y ** 2: S.One / 9,
|
171 |
+
x ** 4: S.One / 5,
|
172 |
+
y ** 4: S.One / 5,
|
173 |
+
y: S.Half,
|
174 |
+
x * y ** 2: S.One / 6,
|
175 |
+
y ** 2: S.One / 3,
|
176 |
+
x ** 3: S.One / 4,
|
177 |
+
x ** 2 * y: S.One / 6,
|
178 |
+
x ** 3 * y: S.One / 8,
|
179 |
+
x * y: S.One / 4,
|
180 |
+
y ** 3: S.One / 4,
|
181 |
+
x ** 2: S.One / 3,
|
182 |
+
x * y ** 3: S.One / 8}
|
183 |
+
|
184 |
+
# Tests for 3D polytopes
|
185 |
+
cube1 = [[(0, 0, 0), (0, 6, 6), (6, 6, 6), (3, 6, 0),
|
186 |
+
(0, 6, 0), (6, 0, 6), (3, 0, 0), (0, 0, 6)],
|
187 |
+
[1, 2, 3, 4], [3, 2, 5, 6], [1, 7, 5, 2], [0, 6, 5, 7],
|
188 |
+
[1, 4, 0, 7], [0, 4, 3, 6]]
|
189 |
+
assert polytope_integrate(cube1, 1) == S(162)
|
190 |
+
|
191 |
+
# 3D Test cases in Chin et al(2015)
|
192 |
+
cube2 = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),
|
193 |
+
(5, 0, 5), (5, 5, 0), (5, 5, 5)],
|
194 |
+
[3, 7, 6, 2], [1, 5, 7, 3], [5, 4, 6, 7], [0, 4, 5, 1],
|
195 |
+
[2, 0, 1, 3], [2, 6, 4, 0]]
|
196 |
+
|
197 |
+
cube3 = [[(0, 0, 0), (5, 0, 0), (5, 4, 0), (3, 2, 0), (3, 5, 0),
|
198 |
+
(0, 5, 0), (0, 0, 5), (5, 0, 5), (5, 4, 5), (3, 2, 5),
|
199 |
+
(3, 5, 5), (0, 5, 5)],
|
200 |
+
[6, 11, 5, 0], [1, 7, 6, 0], [5, 4, 3, 2, 1, 0], [11, 10, 4, 5],
|
201 |
+
[10, 9, 3, 4], [9, 8, 2, 3], [8, 7, 1, 2], [7, 8, 9, 10, 11, 6]]
|
202 |
+
|
203 |
+
cube4 = [[(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1),
|
204 |
+
(S.One / 4, S.One / 4, S.One / 4)],
|
205 |
+
[0, 2, 1], [1, 3, 0], [4, 2, 3], [4, 3, 1],
|
206 |
+
[0, 1, 2], [2, 4, 1], [0, 3, 2]]
|
207 |
+
|
208 |
+
assert polytope_integrate(cube2, x ** 2 + y ** 2 + x * y + z ** 2) ==\
|
209 |
+
Rational(15625, 4)
|
210 |
+
assert polytope_integrate(cube3, x ** 2 + y ** 2 + x * y + z ** 2) ==\
|
211 |
+
S(33835) / 12
|
212 |
+
assert polytope_integrate(cube4, x ** 2 + y ** 2 + x * y + z ** 2) ==\
|
213 |
+
S(37) / 960
|
214 |
+
|
215 |
+
# Test cases from Mathematica's PolyhedronData library
|
216 |
+
octahedron = [[(S.NegativeOne / sqrt(2), 0, 0), (0, S.One / sqrt(2), 0),
|
217 |
+
(0, 0, S.NegativeOne / sqrt(2)), (0, 0, S.One / sqrt(2)),
|
218 |
+
(0, S.NegativeOne / sqrt(2), 0), (S.One / sqrt(2), 0, 0)],
|
219 |
+
[3, 4, 5], [3, 5, 1], [3, 1, 0], [3, 0, 4], [4, 0, 2],
|
220 |
+
[4, 2, 5], [2, 0, 1], [5, 2, 1]]
|
221 |
+
|
222 |
+
assert polytope_integrate(octahedron, 1) == sqrt(2) / 3
|
223 |
+
|
224 |
+
great_stellated_dodecahedron =\
|
225 |
+
[[(-0.32491969623290634095, 0, 0.42532540417601993887),
|
226 |
+
(0.32491969623290634095, 0, -0.42532540417601993887),
|
227 |
+
(-0.52573111211913359231, 0, 0.10040570794311363956),
|
228 |
+
(0.52573111211913359231, 0, -0.10040570794311363956),
|
229 |
+
(-0.10040570794311363956, -0.3090169943749474241, 0.42532540417601993887),
|
230 |
+
(-0.10040570794311363956, 0.30901699437494742410, 0.42532540417601993887),
|
231 |
+
(0.10040570794311363956, -0.3090169943749474241, -0.42532540417601993887),
|
232 |
+
(0.10040570794311363956, 0.30901699437494742410, -0.42532540417601993887),
|
233 |
+
(-0.16245984811645317047, -0.5, 0.10040570794311363956),
|
234 |
+
(-0.16245984811645317047, 0.5, 0.10040570794311363956),
|
235 |
+
(0.16245984811645317047, -0.5, -0.10040570794311363956),
|
236 |
+
(0.16245984811645317047, 0.5, -0.10040570794311363956),
|
237 |
+
(-0.42532540417601993887, -0.3090169943749474241, -0.10040570794311363956),
|
238 |
+
(-0.42532540417601993887, 0.30901699437494742410, -0.10040570794311363956),
|
239 |
+
(-0.26286555605956679615, 0.1909830056250525759, -0.42532540417601993887),
|
240 |
+
(-0.26286555605956679615, -0.1909830056250525759, -0.42532540417601993887),
|
241 |
+
(0.26286555605956679615, 0.1909830056250525759, 0.42532540417601993887),
|
242 |
+
(0.26286555605956679615, -0.1909830056250525759, 0.42532540417601993887),
|
243 |
+
(0.42532540417601993887, -0.3090169943749474241, 0.10040570794311363956),
|
244 |
+
(0.42532540417601993887, 0.30901699437494742410, 0.10040570794311363956)],
|
245 |
+
[12, 3, 0, 6, 16], [17, 7, 0, 3, 13],
|
246 |
+
[9, 6, 0, 7, 8], [18, 2, 1, 4, 14],
|
247 |
+
[15, 5, 1, 2, 19], [11, 4, 1, 5, 10],
|
248 |
+
[8, 19, 2, 18, 9], [10, 13, 3, 12, 11],
|
249 |
+
[16, 14, 4, 11, 12], [13, 10, 5, 15, 17],
|
250 |
+
[14, 16, 6, 9, 18], [19, 8, 7, 17, 15]]
|
251 |
+
# Actual volume is : 0.163118960624632
|
252 |
+
assert Abs(polytope_integrate(great_stellated_dodecahedron, 1) -\
|
253 |
+
0.163118960624632) < 1e-12
|
254 |
+
|
255 |
+
expr = x **2 + y ** 2 + z ** 2
|
256 |
+
octahedron_five_compound = [[(0, -0.7071067811865475244, 0),
|
257 |
+
(0, 0.70710678118654752440, 0),
|
258 |
+
(0.1148764602736805918,
|
259 |
+
-0.35355339059327376220, -0.60150095500754567366),
|
260 |
+
(0.1148764602736805918, 0.35355339059327376220,
|
261 |
+
-0.60150095500754567366),
|
262 |
+
(0.18587401723009224507,
|
263 |
+
-0.57206140281768429760, 0.37174803446018449013),
|
264 |
+
(0.18587401723009224507, 0.57206140281768429760,
|
265 |
+
0.37174803446018449013),
|
266 |
+
(0.30075047750377283683, -0.21850801222441053540,
|
267 |
+
0.60150095500754567366),
|
268 |
+
(0.30075047750377283683, 0.21850801222441053540,
|
269 |
+
0.60150095500754567366),
|
270 |
+
(0.48662449473386508189, -0.35355339059327376220,
|
271 |
+
-0.37174803446018449013),
|
272 |
+
(0.48662449473386508189, 0.35355339059327376220,
|
273 |
+
-0.37174803446018449013),
|
274 |
+
(-0.60150095500754567366, 0, -0.37174803446018449013),
|
275 |
+
(-0.30075047750377283683, -0.21850801222441053540,
|
276 |
+
-0.60150095500754567366),
|
277 |
+
(-0.30075047750377283683, 0.21850801222441053540,
|
278 |
+
-0.60150095500754567366),
|
279 |
+
(0.60150095500754567366, 0, 0.37174803446018449013),
|
280 |
+
(0.4156269377774534286, -0.57206140281768429760, 0),
|
281 |
+
(0.4156269377774534286, 0.57206140281768429760, 0),
|
282 |
+
(0.37174803446018449013, 0, -0.60150095500754567366),
|
283 |
+
(-0.4156269377774534286, -0.57206140281768429760, 0),
|
284 |
+
(-0.4156269377774534286, 0.57206140281768429760, 0),
|
285 |
+
(-0.67249851196395732696, -0.21850801222441053540, 0),
|
286 |
+
(-0.67249851196395732696, 0.21850801222441053540, 0),
|
287 |
+
(0.67249851196395732696, -0.21850801222441053540, 0),
|
288 |
+
(0.67249851196395732696, 0.21850801222441053540, 0),
|
289 |
+
(-0.37174803446018449013, 0, 0.60150095500754567366),
|
290 |
+
(-0.48662449473386508189, -0.35355339059327376220,
|
291 |
+
0.37174803446018449013),
|
292 |
+
(-0.48662449473386508189, 0.35355339059327376220,
|
293 |
+
0.37174803446018449013),
|
294 |
+
(-0.18587401723009224507, -0.57206140281768429760,
|
295 |
+
-0.37174803446018449013),
|
296 |
+
(-0.18587401723009224507, 0.57206140281768429760,
|
297 |
+
-0.37174803446018449013),
|
298 |
+
(-0.11487646027368059176, -0.35355339059327376220,
|
299 |
+
0.60150095500754567366),
|
300 |
+
(-0.11487646027368059176, 0.35355339059327376220,
|
301 |
+
0.60150095500754567366)],
|
302 |
+
[0, 10, 16], [23, 10, 0], [16, 13, 0],
|
303 |
+
[0, 13, 23], [16, 10, 1], [1, 10, 23],
|
304 |
+
[1, 13, 16], [23, 13, 1], [2, 4, 19],
|
305 |
+
[22, 4, 2], [2, 19, 27], [27, 22, 2],
|
306 |
+
[20, 5, 3], [3, 5, 21], [26, 20, 3],
|
307 |
+
[3, 21, 26], [29, 19, 4], [4, 22, 29],
|
308 |
+
[5, 20, 28], [28, 21, 5], [6, 8, 15],
|
309 |
+
[17, 8, 6], [6, 15, 25], [25, 17, 6],
|
310 |
+
[14, 9, 7], [7, 9, 18], [24, 14, 7],
|
311 |
+
[7, 18, 24], [8, 12, 15], [17, 12, 8],
|
312 |
+
[14, 11, 9], [9, 11, 18], [11, 14, 24],
|
313 |
+
[24, 18, 11], [25, 15, 12], [12, 17, 25],
|
314 |
+
[29, 27, 19], [20, 26, 28], [28, 26, 21],
|
315 |
+
[22, 27, 29]]
|
316 |
+
assert Abs(polytope_integrate(octahedron_five_compound, expr)) - 0.353553\
|
317 |
+
< 1e-6
|
318 |
+
|
319 |
+
cube_five_compound = [[(-0.1624598481164531631, -0.5, -0.6881909602355867691),
|
320 |
+
(-0.1624598481164531631, 0.5, -0.6881909602355867691),
|
321 |
+
(0.1624598481164531631, -0.5, 0.68819096023558676910),
|
322 |
+
(0.1624598481164531631, 0.5, 0.68819096023558676910),
|
323 |
+
(-0.52573111211913359231, 0, -0.6881909602355867691),
|
324 |
+
(0.52573111211913359231, 0, 0.68819096023558676910),
|
325 |
+
(-0.26286555605956679615, -0.8090169943749474241,
|
326 |
+
-0.1624598481164531631),
|
327 |
+
(-0.26286555605956679615, 0.8090169943749474241,
|
328 |
+
-0.1624598481164531631),
|
329 |
+
(0.26286555605956680301, -0.8090169943749474241,
|
330 |
+
0.1624598481164531631),
|
331 |
+
(0.26286555605956680301, 0.8090169943749474241,
|
332 |
+
0.1624598481164531631),
|
333 |
+
(-0.42532540417601993887, -0.3090169943749474241,
|
334 |
+
0.68819096023558676910),
|
335 |
+
(-0.42532540417601993887, 0.30901699437494742410,
|
336 |
+
0.68819096023558676910),
|
337 |
+
(0.42532540417601996609, -0.3090169943749474241,
|
338 |
+
-0.6881909602355867691),
|
339 |
+
(0.42532540417601996609, 0.30901699437494742410,
|
340 |
+
-0.6881909602355867691),
|
341 |
+
(-0.6881909602355867691, -0.5, 0.1624598481164531631),
|
342 |
+
(-0.6881909602355867691, 0.5, 0.1624598481164531631),
|
343 |
+
(0.68819096023558676910, -0.5, -0.1624598481164531631),
|
344 |
+
(0.68819096023558676910, 0.5, -0.1624598481164531631),
|
345 |
+
(-0.85065080835203998877, 0, -0.1624598481164531631),
|
346 |
+
(0.85065080835203993218, 0, 0.1624598481164531631)],
|
347 |
+
[18, 10, 3, 7], [13, 19, 8, 0], [18, 0, 8, 10],
|
348 |
+
[3, 19, 13, 7], [18, 7, 13, 0], [8, 19, 3, 10],
|
349 |
+
[6, 2, 11, 18], [1, 9, 19, 12], [11, 9, 1, 18],
|
350 |
+
[6, 12, 19, 2], [1, 12, 6, 18], [11, 2, 19, 9],
|
351 |
+
[4, 14, 11, 7], [17, 5, 8, 12], [4, 12, 8, 14],
|
352 |
+
[11, 5, 17, 7], [4, 7, 17, 12], [8, 5, 11, 14],
|
353 |
+
[6, 10, 15, 4], [13, 9, 5, 16], [15, 9, 13, 4],
|
354 |
+
[6, 16, 5, 10], [13, 16, 6, 4], [15, 10, 5, 9],
|
355 |
+
[14, 15, 1, 0], [16, 17, 3, 2], [14, 2, 3, 15],
|
356 |
+
[1, 17, 16, 0], [14, 0, 16, 2], [3, 17, 1, 15]]
|
357 |
+
assert Abs(polytope_integrate(cube_five_compound, expr) - 1.25) < 1e-12
|
358 |
+
|
359 |
+
echidnahedron = [[(0, 0, -2.4898982848827801995),
|
360 |
+
(0, 0, 2.4898982848827802734),
|
361 |
+
(0, -4.2360679774997896964, -2.4898982848827801995),
|
362 |
+
(0, -4.2360679774997896964, 2.4898982848827802734),
|
363 |
+
(0, 4.2360679774997896964, -2.4898982848827801995),
|
364 |
+
(0, 4.2360679774997896964, 2.4898982848827802734),
|
365 |
+
(-4.0287400534704067567, -1.3090169943749474241, -2.4898982848827801995),
|
366 |
+
(-4.0287400534704067567, -1.3090169943749474241, 2.4898982848827802734),
|
367 |
+
(-4.0287400534704067567, 1.3090169943749474241, -2.4898982848827801995),
|
368 |
+
(-4.0287400534704067567, 1.3090169943749474241, 2.4898982848827802734),
|
369 |
+
(4.0287400534704069747, -1.3090169943749474241, -2.4898982848827801995),
|
370 |
+
(4.0287400534704069747, -1.3090169943749474241, 2.4898982848827802734),
|
371 |
+
(4.0287400534704069747, 1.3090169943749474241, -2.4898982848827801995),
|
372 |
+
(4.0287400534704069747, 1.3090169943749474241, 2.4898982848827802734),
|
373 |
+
(-2.4898982848827801995, -3.4270509831248422723, -2.4898982848827801995),
|
374 |
+
(-2.4898982848827801995, -3.4270509831248422723, 2.4898982848827802734),
|
375 |
+
(-2.4898982848827801995, 3.4270509831248422723, -2.4898982848827801995),
|
376 |
+
(-2.4898982848827801995, 3.4270509831248422723, 2.4898982848827802734),
|
377 |
+
(2.4898982848827802734, -3.4270509831248422723, -2.4898982848827801995),
|
378 |
+
(2.4898982848827802734, -3.4270509831248422723, 2.4898982848827802734),
|
379 |
+
(2.4898982848827802734, 3.4270509831248422723, -2.4898982848827801995),
|
380 |
+
(2.4898982848827802734, 3.4270509831248422723, 2.4898982848827802734),
|
381 |
+
(-4.7169310137059934362, -0.8090169943749474241, -1.1135163644116066184),
|
382 |
+
(-4.7169310137059934362, 0.8090169943749474241, -1.1135163644116066184),
|
383 |
+
(4.7169310137059937438, -0.8090169943749474241, 1.11351636441160673519),
|
384 |
+
(4.7169310137059937438, 0.8090169943749474241, 1.11351636441160673519),
|
385 |
+
(-4.2916056095299737777, -2.1180339887498948482, 1.11351636441160673519),
|
386 |
+
(-4.2916056095299737777, 2.1180339887498948482, 1.11351636441160673519),
|
387 |
+
(4.2916056095299737777, -2.1180339887498948482, -1.1135163644116066184),
|
388 |
+
(4.2916056095299737777, 2.1180339887498948482, -1.1135163644116066184),
|
389 |
+
(-3.6034146492943870399, 0, -3.3405490932348205213),
|
390 |
+
(3.6034146492943870399, 0, 3.3405490932348202056),
|
391 |
+
(-3.3405490932348205213, -3.4270509831248422723, 1.11351636441160673519),
|
392 |
+
(-3.3405490932348205213, 3.4270509831248422723, 1.11351636441160673519),
|
393 |
+
(3.3405490932348202056, -3.4270509831248422723, -1.1135163644116066184),
|
394 |
+
(3.3405490932348202056, 3.4270509831248422723, -1.1135163644116066184),
|
395 |
+
(-2.9152236890588002395, -2.1180339887498948482, 3.3405490932348202056),
|
396 |
+
(-2.9152236890588002395, 2.1180339887498948482, 3.3405490932348202056),
|
397 |
+
(2.9152236890588002395, -2.1180339887498948482, -3.3405490932348205213),
|
398 |
+
(2.9152236890588002395, 2.1180339887498948482, -3.3405490932348205213),
|
399 |
+
(-2.2270327288232132368, 0, -1.1135163644116066184),
|
400 |
+
(-2.2270327288232132368, -4.2360679774997896964, -1.1135163644116066184),
|
401 |
+
(-2.2270327288232132368, 4.2360679774997896964, -1.1135163644116066184),
|
402 |
+
(2.2270327288232134704, 0, 1.11351636441160673519),
|
403 |
+
(2.2270327288232134704, -4.2360679774997896964, 1.11351636441160673519),
|
404 |
+
(2.2270327288232134704, 4.2360679774997896964, 1.11351636441160673519),
|
405 |
+
(-1.8017073246471935200, -1.3090169943749474241, 1.11351636441160673519),
|
406 |
+
(-1.8017073246471935200, 1.3090169943749474241, 1.11351636441160673519),
|
407 |
+
(1.8017073246471935043, -1.3090169943749474241, -1.1135163644116066184),
|
408 |
+
(1.8017073246471935043, 1.3090169943749474241, -1.1135163644116066184),
|
409 |
+
(-1.3763819204711735382, 0, -4.7169310137059934362),
|
410 |
+
(-1.3763819204711735382, 0, 0.26286555605956679615),
|
411 |
+
(1.37638192047117353821, 0, 4.7169310137059937438),
|
412 |
+
(1.37638192047117353821, 0, -0.26286555605956679615),
|
413 |
+
(-1.1135163644116066184, -3.4270509831248422723, -3.3405490932348205213),
|
414 |
+
(-1.1135163644116066184, -0.8090169943749474241, 4.7169310137059937438),
|
415 |
+
(-1.1135163644116066184, -0.8090169943749474241, -0.26286555605956679615),
|
416 |
+
(-1.1135163644116066184, 0.8090169943749474241, 4.7169310137059937438),
|
417 |
+
(-1.1135163644116066184, 0.8090169943749474241, -0.26286555605956679615),
|
418 |
+
(-1.1135163644116066184, 3.4270509831248422723, -3.3405490932348205213),
|
419 |
+
(1.11351636441160673519, -3.4270509831248422723, 3.3405490932348202056),
|
420 |
+
(1.11351636441160673519, -0.8090169943749474241, -4.7169310137059934362),
|
421 |
+
(1.11351636441160673519, -0.8090169943749474241, 0.26286555605956679615),
|
422 |
+
(1.11351636441160673519, 0.8090169943749474241, -4.7169310137059934362),
|
423 |
+
(1.11351636441160673519, 0.8090169943749474241, 0.26286555605956679615),
|
424 |
+
(1.11351636441160673519, 3.4270509831248422723, 3.3405490932348202056),
|
425 |
+
(-0.85065080835203998877, 0, 1.11351636441160673519),
|
426 |
+
(0.85065080835203993218, 0, -1.1135163644116066184),
|
427 |
+
(-0.6881909602355867691, -0.5, -1.1135163644116066184),
|
428 |
+
(-0.6881909602355867691, 0.5, -1.1135163644116066184),
|
429 |
+
(-0.6881909602355867691, -4.7360679774997896964, -1.1135163644116066184),
|
430 |
+
(-0.6881909602355867691, -2.1180339887498948482, -1.1135163644116066184),
|
431 |
+
(-0.6881909602355867691, 2.1180339887498948482, -1.1135163644116066184),
|
432 |
+
(-0.6881909602355867691, 4.7360679774997896964, -1.1135163644116066184),
|
433 |
+
(0.68819096023558676910, -0.5, 1.11351636441160673519),
|
434 |
+
(0.68819096023558676910, 0.5, 1.11351636441160673519),
|
435 |
+
(0.68819096023558676910, -4.7360679774997896964, 1.11351636441160673519),
|
436 |
+
(0.68819096023558676910, -2.1180339887498948482, 1.11351636441160673519),
|
437 |
+
(0.68819096023558676910, 2.1180339887498948482, 1.11351636441160673519),
|
438 |
+
(0.68819096023558676910, 4.7360679774997896964, 1.11351636441160673519),
|
439 |
+
(-0.42532540417601993887, -1.3090169943749474241, -4.7169310137059934362),
|
440 |
+
(-0.42532540417601993887, -1.3090169943749474241, 0.26286555605956679615),
|
441 |
+
(-0.42532540417601993887, 1.3090169943749474241, -4.7169310137059934362),
|
442 |
+
(-0.42532540417601993887, 1.3090169943749474241, 0.26286555605956679615),
|
443 |
+
(-0.26286555605956679615, -0.8090169943749474241, 1.11351636441160673519),
|
444 |
+
(-0.26286555605956679615, 0.8090169943749474241, 1.11351636441160673519),
|
445 |
+
(0.26286555605956679615, -0.8090169943749474241, -1.1135163644116066184),
|
446 |
+
(0.26286555605956679615, 0.8090169943749474241, -1.1135163644116066184),
|
447 |
+
(0.42532540417601996609, -1.3090169943749474241, 4.7169310137059937438),
|
448 |
+
(0.42532540417601996609, -1.3090169943749474241, -0.26286555605956679615),
|
449 |
+
(0.42532540417601996609, 1.3090169943749474241, 4.7169310137059937438),
|
450 |
+
(0.42532540417601996609, 1.3090169943749474241, -0.26286555605956679615)],
|
451 |
+
[9, 66, 47], [44, 62, 77], [20, 91, 49], [33, 47, 83],
|
452 |
+
[3, 77, 84], [12, 49, 53], [36, 84, 66], [28, 53, 62],
|
453 |
+
[73, 83, 91], [15, 84, 46], [25, 64, 43], [16, 58, 72],
|
454 |
+
[26, 46, 51], [11, 43, 74], [4, 72, 91], [60, 74, 84],
|
455 |
+
[35, 91, 64], [23, 51, 58], [19, 74, 77], [79, 83, 78],
|
456 |
+
[6, 56, 40], [76, 77, 81], [21, 78, 75], [8, 40, 58],
|
457 |
+
[31, 75, 74], [42, 58, 83], [41, 81, 56], [13, 75, 43],
|
458 |
+
[27, 51, 47], [2, 89, 71], [24, 43, 62], [17, 47, 85],
|
459 |
+
[14, 71, 56], [65, 85, 75], [22, 56, 51], [34, 62, 89],
|
460 |
+
[5, 85, 78], [32, 81, 46], [10, 53, 48], [45, 78, 64],
|
461 |
+
[7, 46, 66], [18, 48, 89], [37, 66, 85], [70, 89, 81],
|
462 |
+
[29, 64, 53], [88, 74, 1], [38, 67, 48], [42, 83, 72],
|
463 |
+
[57, 1, 85], [34, 48, 62], [59, 72, 87], [19, 62, 74],
|
464 |
+
[63, 87, 67], [17, 85, 83], [52, 75, 1], [39, 87, 49],
|
465 |
+
[22, 51, 40], [55, 1, 66], [29, 49, 64], [30, 40, 69],
|
466 |
+
[13, 64, 75], [82, 69, 87], [7, 66, 51], [90, 85, 1],
|
467 |
+
[59, 69, 72], [70, 81, 71], [88, 1, 84], [73, 72, 83],
|
468 |
+
[54, 71, 68], [5, 83, 85], [50, 68, 69], [3, 84, 81],
|
469 |
+
[57, 66, 1], [30, 68, 40], [28, 62, 48], [52, 1, 74],
|
470 |
+
[23, 40, 51], [38, 48, 86], [9, 51, 66], [80, 86, 68],
|
471 |
+
[11, 74, 62], [55, 84, 1], [54, 86, 71], [35, 64, 49],
|
472 |
+
[90, 1, 75], [41, 71, 81], [39, 49, 67], [15, 81, 84],
|
473 |
+
[61, 67, 86], [21, 75, 64], [24, 53, 43], [50, 69, 0],
|
474 |
+
[37, 85, 47], [31, 43, 75], [61, 0, 67], [27, 47, 58],
|
475 |
+
[10, 67, 53], [8, 58, 69], [90, 75, 85], [45, 91, 78],
|
476 |
+
[80, 68, 0], [36, 66, 46], [65, 78, 85], [63, 0, 87],
|
477 |
+
[32, 46, 56], [20, 87, 91], [14, 56, 68], [57, 85, 66],
|
478 |
+
[33, 58, 47], [61, 86, 0], [60, 84, 77], [37, 47, 66],
|
479 |
+
[82, 0, 69], [44, 77, 89], [16, 69, 58], [18, 89, 86],
|
480 |
+
[55, 66, 84], [26, 56, 46], [63, 67, 0], [31, 74, 43],
|
481 |
+
[36, 46, 84], [50, 0, 68], [25, 43, 53], [6, 68, 56],
|
482 |
+
[12, 53, 67], [88, 84, 74], [76, 89, 77], [82, 87, 0],
|
483 |
+
[65, 75, 78], [60, 77, 74], [80, 0, 86], [79, 78, 91],
|
484 |
+
[2, 86, 89], [4, 91, 87], [52, 74, 75], [21, 64, 78],
|
485 |
+
[18, 86, 48], [23, 58, 40], [5, 78, 83], [28, 48, 53],
|
486 |
+
[6, 40, 68], [25, 53, 64], [54, 68, 86], [33, 83, 58],
|
487 |
+
[17, 83, 47], [12, 67, 49], [41, 56, 71], [9, 47, 51],
|
488 |
+
[35, 49, 91], [2, 71, 86], [79, 91, 83], [38, 86, 67],
|
489 |
+
[26, 51, 56], [7, 51, 46], [4, 87, 72], [34, 89, 48],
|
490 |
+
[15, 46, 81], [42, 72, 58], [10, 48, 67], [27, 58, 51],
|
491 |
+
[39, 67, 87], [76, 81, 89], [3, 81, 77], [8, 69, 40],
|
492 |
+
[29, 53, 49], [19, 77, 62], [22, 40, 56], [20, 49, 87],
|
493 |
+
[32, 56, 81], [59, 87, 69], [24, 62, 53], [11, 62, 43],
|
494 |
+
[14, 68, 71], [73, 91, 72], [13, 43, 64], [70, 71, 89],
|
495 |
+
[16, 72, 69], [44, 89, 62], [30, 69, 68], [45, 64, 91]]
|
496 |
+
# Actual volume is : 51.405764746872634
|
497 |
+
assert Abs(polytope_integrate(echidnahedron, 1) - 51.4057647468726) < 1e-12
|
498 |
+
assert Abs(polytope_integrate(echidnahedron, expr) - 253.569603474519) <\
|
499 |
+
1e-12
|
500 |
+
|
501 |
+
# Tests for many polynomials with maximum degree given(2D case).
|
502 |
+
assert polytope_integrate(cube2, [x**2, y*z], max_degree=2) == \
|
503 |
+
{y * z: 3125 / S(4), x ** 2: 3125 / S(3)}
|
504 |
+
|
505 |
+
assert polytope_integrate(cube2, max_degree=2) == \
|
506 |
+
{1: 125, x: 625 / S(2), x * z: 3125 / S(4), y: 625 / S(2),
|
507 |
+
y * z: 3125 / S(4), z ** 2: 3125 / S(3), y ** 2: 3125 / S(3),
|
508 |
+
z: 625 / S(2), x * y: 3125 / S(4), x ** 2: 3125 / S(3)}
|
509 |
+
|
510 |
+
def test_point_sort():
|
511 |
+
assert point_sort([Point(0, 0), Point(1, 0), Point(1, 1)]) == \
|
512 |
+
[Point2D(1, 1), Point2D(1, 0), Point2D(0, 0)]
|
513 |
+
|
514 |
+
fig6 = Polygon((0, 0), (1, 0), (1, 1))
|
515 |
+
assert polytope_integrate(fig6, x*y) == Rational(-1, 8)
|
516 |
+
assert polytope_integrate(fig6, x*y, clockwise = True) == Rational(1, 8)
|
517 |
+
|
518 |
+
|
519 |
+
def test_polytopes_intersecting_sides():
|
520 |
+
fig5 = Polygon(Point(-4.165, -0.832), Point(-3.668, 1.568),
|
521 |
+
Point(-3.266, 1.279), Point(-1.090, -2.080),
|
522 |
+
Point(3.313, -0.683), Point(3.033, -4.845),
|
523 |
+
Point(-4.395, 4.840), Point(-1.007, -3.328))
|
524 |
+
assert polytope_integrate(fig5, x**2 + x*y + y**2) ==\
|
525 |
+
S(1633405224899363)/(24*10**12)
|
526 |
+
|
527 |
+
fig6 = Polygon(Point(-3.018, -4.473), Point(-0.103, 2.378),
|
528 |
+
Point(-1.605, -2.308), Point(4.516, -0.771),
|
529 |
+
Point(4.203, 0.478))
|
530 |
+
assert polytope_integrate(fig6, x**2 + x*y + y**2) ==\
|
531 |
+
S(88161333955921)/(3*10**12)
|
532 |
+
|
533 |
+
|
534 |
+
def test_max_degree():
|
535 |
+
polygon = Polygon((0, 0), (0, 1), (1, 1), (1, 0))
|
536 |
+
polys = [1, x, y, x*y, x**2*y, x*y**2]
|
537 |
+
assert polytope_integrate(polygon, polys, max_degree=3) == \
|
538 |
+
{1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y: Rational(1, 6), x*y**2: Rational(1, 6)}
|
539 |
+
assert polytope_integrate(polygon, polys, max_degree=2) == \
|
540 |
+
{1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4)}
|
541 |
+
assert polytope_integrate(polygon, polys, max_degree=1) == \
|
542 |
+
{1: 1, x: S.Half, y: S.Half}
|
543 |
+
|
544 |
+
|
545 |
+
def test_main_integrate3d():
|
546 |
+
cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
|
547 |
+
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
|
548 |
+
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
|
549 |
+
[3, 1, 0, 2], [0, 4, 6, 2]]
|
550 |
+
vertices = cube[0]
|
551 |
+
faces = cube[1:]
|
552 |
+
hp_params = hyperplane_parameters(faces, vertices)
|
553 |
+
assert main_integrate3d(1, faces, vertices, hp_params) == -125
|
554 |
+
assert main_integrate3d(1, faces, vertices, hp_params, max_degree=1) == \
|
555 |
+
{1: -125, y: Rational(-625, 2), z: Rational(-625, 2), x: Rational(-625, 2)}
|
556 |
+
|
557 |
+
|
558 |
+
def test_main_integrate():
|
559 |
+
triangle = Polygon((0, 3), (5, 3), (1, 1))
|
560 |
+
facets = triangle.sides
|
561 |
+
hp_params = hyperplane_parameters(triangle)
|
562 |
+
assert main_integrate(x**2 + y**2, facets, hp_params) == Rational(325, 6)
|
563 |
+
assert main_integrate(x**2 + y**2, facets, hp_params, max_degree=1) == \
|
564 |
+
{0: 0, 1: 5, y: Rational(35, 3), x: 10}
|
565 |
+
|
566 |
+
|
567 |
+
def test_polygon_integrate():
|
568 |
+
cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
|
569 |
+
(5, 0, 5), (5, 5, 0), (5, 5, 5)],\
|
570 |
+
[2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
|
571 |
+
[3, 1, 0, 2], [0, 4, 6, 2]]
|
572 |
+
facet = cube[1]
|
573 |
+
facets = cube[1:]
|
574 |
+
vertices = cube[0]
|
575 |
+
assert polygon_integrate(facet, [(0, 1, 0), 5], 0, facets, vertices, 1, 0) == -25
|
576 |
+
|
577 |
+
|
578 |
+
def test_distance_to_side():
|
579 |
+
point = (0, 0, 0)
|
580 |
+
assert distance_to_side(point, [(0, 0, 1), (0, 1, 0)], (1, 0, 0)) == -sqrt(2)/2
|
581 |
+
|
582 |
+
|
583 |
+
def test_lineseg_integrate():
|
584 |
+
polygon = [(0, 5, 0), (5, 5, 0), (5, 5, 5), (0, 5, 5)]
|
585 |
+
line_seg = [(0, 5, 0), (5, 5, 0)]
|
586 |
+
assert lineseg_integrate(polygon, 0, line_seg, 1, 0) == 5
|
587 |
+
assert lineseg_integrate(polygon, 0, line_seg, 0, 0) == 0
|
588 |
+
|
589 |
+
|
590 |
+
def test_integration_reduction():
|
591 |
+
triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
|
592 |
+
facets = triangle.sides
|
593 |
+
a, b = hyperplane_parameters(triangle)[0]
|
594 |
+
assert integration_reduction(facets, 0, a, b, 1, (x, y), 0) == 5
|
595 |
+
assert integration_reduction(facets, 0, a, b, 0, (x, y), 0) == 0
|
596 |
+
|
597 |
+
|
598 |
+
def test_integration_reduction_dynamic():
|
599 |
+
triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
|
600 |
+
facets = triangle.sides
|
601 |
+
a, b = hyperplane_parameters(triangle)[0]
|
602 |
+
x0 = facets[0].points[0]
|
603 |
+
monomial_values = [[0, 0, 0, 0], [1, 0, 0, 5],\
|
604 |
+
[y, 0, 1, 15], [x, 1, 0, None]]
|
605 |
+
|
606 |
+
assert integration_reduction_dynamic(facets, 0, a, b, x, 1, (x, y), 1,\
|
607 |
+
0, 1, x0, monomial_values, 3) == Rational(25, 2)
|
608 |
+
assert integration_reduction_dynamic(facets, 0, a, b, 0, 1, (x, y), 1,\
|
609 |
+
0, 1, x0, monomial_values, 3) == 0
|
610 |
+
|
611 |
+
|
612 |
+
def test_is_vertex():
|
613 |
+
assert is_vertex(2) is False
|
614 |
+
assert is_vertex((2, 3)) is True
|
615 |
+
assert is_vertex(Point(2, 3)) is True
|
616 |
+
assert is_vertex((2, 3, 4)) is True
|
617 |
+
assert is_vertex((2, 3, 4, 5)) is False
|
618 |
+
|
619 |
+
|
620 |
+
def test_issue_19234():
|
621 |
+
polygon = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
|
622 |
+
polys = [ 1, x, y, x*y, x**2*y, x*y**2]
|
623 |
+
assert polytope_integrate(polygon, polys) == \
|
624 |
+
{1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y: Rational(1, 6), x*y**2: Rational(1, 6)}
|
625 |
+
polys = [ 1, x, y, x*y, 3 + x**2*y, x + x*y**2]
|
626 |
+
assert polytope_integrate(polygon, polys) == \
|
627 |
+
{1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y + 3: Rational(19, 6), x*y**2 + x: Rational(2, 3)}
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_laplace.py
ADDED
@@ -0,0 +1,550 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.integrals.laplace import (
|
2 |
+
laplace_transform, inverse_laplace_transform,
|
3 |
+
LaplaceTransform, InverseLaplaceTransform)
|
4 |
+
from sympy.core.function import Function, expand_mul
|
5 |
+
from sympy.core import EulerGamma, Subs, Derivative, diff
|
6 |
+
from sympy.core.exprtools import factor_terms
|
7 |
+
from sympy.core.numbers import I, oo, pi
|
8 |
+
from sympy.core.singleton import S
|
9 |
+
from sympy.core.symbol import Symbol, symbols
|
10 |
+
from sympy.simplify.simplify import simplify
|
11 |
+
from sympy.functions.elementary.complexes import Abs, re
|
12 |
+
from sympy.functions.elementary.exponential import exp, log, exp_polar
|
13 |
+
from sympy.functions.elementary.hyperbolic import cosh, sinh, coth, asinh
|
14 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
15 |
+
from sympy.functions.elementary.trigonometric import atan, cos, sin
|
16 |
+
from sympy.functions.special.gamma_functions import lowergamma, gamma
|
17 |
+
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
|
18 |
+
from sympy.functions.special.zeta_functions import lerchphi
|
19 |
+
from sympy.functions.special.error_functions import (
|
20 |
+
fresnelc, fresnels, erf, erfc, Ei, Ci, expint, E1)
|
21 |
+
from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
|
22 |
+
from sympy.testing.pytest import slow, warns_deprecated_sympy
|
23 |
+
from sympy.matrices import Matrix, eye
|
24 |
+
from sympy.abc import s
|
25 |
+
|
26 |
+
|
27 |
+
@slow
|
28 |
+
def test_laplace_transform():
|
29 |
+
LT = laplace_transform
|
30 |
+
a, b, c, = symbols('a, b, c', positive=True)
|
31 |
+
t, w, x = symbols('t, w, x')
|
32 |
+
f = Function('f')
|
33 |
+
g = Function('g')
|
34 |
+
|
35 |
+
# Test whether `noconds=True` in `doit`:
|
36 |
+
assert (2*LaplaceTransform(exp(t), t, s) - 1).doit() == -1 + 2/(s - 1)
|
37 |
+
assert (LT(a*t+t**2+t**(S(5)/2), t, s) ==
|
38 |
+
(a/s**2 + 2/s**3 + 15*sqrt(pi)/(8*s**(S(7)/2)), 0, True))
|
39 |
+
assert LT(b/(t+a), t, s) == (-b*exp(-a*s)*Ei(-a*s), 0, True)
|
40 |
+
assert (LT(1/sqrt(t+a), t, s) ==
|
41 |
+
(sqrt(pi)*sqrt(1/s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True))
|
42 |
+
assert (LT(sqrt(t)/(t+a), t, s) ==
|
43 |
+
(-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
|
44 |
+
0, True))
|
45 |
+
assert (LT((t+a)**(-S(3)/2), t, s) ==
|
46 |
+
(-2*sqrt(pi)*sqrt(s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + 2/sqrt(a),
|
47 |
+
0, True))
|
48 |
+
assert (LT(t**(S(1)/2)*(t+a)**(-1), t, s) ==
|
49 |
+
(-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
|
50 |
+
0, True))
|
51 |
+
assert (LT(1/(a*sqrt(t) + t**(3/2)), t, s) ==
|
52 |
+
(pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True))
|
53 |
+
assert (LT((t+a)**b, t, s) ==
|
54 |
+
(s**(-b - 1)*exp(-a*s)*lowergamma(b + 1, a*s), 0, True))
|
55 |
+
assert LT(t**5/(t+a), t, s) == (120*a**5*lowergamma(-5, a*s), 0, True)
|
56 |
+
assert LT(exp(t), t, s) == (1/(s - 1), 1, True)
|
57 |
+
assert LT(exp(2*t), t, s) == (1/(s - 2), 2, True)
|
58 |
+
assert LT(exp(a*t), t, s) == (1/(s - a), a, True)
|
59 |
+
assert LT(exp(a*(t-b)), t, s) == (exp(-a*b)/(-a + s), a, True)
|
60 |
+
assert LT(t*exp(-a*(t)), t, s) == ((a + s)**(-2), -a, True)
|
61 |
+
assert LT(t*exp(-a*(t-b)), t, s) == (exp(a*b)/(a + s)**2, -a, True)
|
62 |
+
assert LT(b*t*exp(-a*t), t, s) == (b/(a + s)**2, -a, True)
|
63 |
+
assert (LT(t**(S(7)/4)*exp(-8*t)/gamma(S(11)/4), t, s) ==
|
64 |
+
((s + 8)**(-S(11)/4), -8, True))
|
65 |
+
assert (LT(t**(S(3)/2)*exp(-8*t), t, s) ==
|
66 |
+
(3*sqrt(pi)/(4*(s + 8)**(S(5)/2)), -8, True))
|
67 |
+
assert LT(t**a*exp(-a*t), t, s) == ((a+s)**(-a-1)*gamma(a+1), -a, True)
|
68 |
+
assert (LT(b*exp(-a*t**2), t, s) ==
|
69 |
+
(sqrt(pi)*b*exp(s**2/(4*a))*erfc(s/(2*sqrt(a)))/(2*sqrt(a)),
|
70 |
+
0, True))
|
71 |
+
assert (LT(exp(-2*t**2), t, s) ==
|
72 |
+
(sqrt(2)*sqrt(pi)*exp(s**2/8)*erfc(sqrt(2)*s/4)/4, 0, True))
|
73 |
+
assert (LT(b*exp(2*t**2), t, s) ==
|
74 |
+
(b*LaplaceTransform(exp(2*t**2), t, s), -oo, True))
|
75 |
+
assert (LT(t*exp(-a*t**2), t, s) ==
|
76 |
+
(1/(2*a) - s*erfc(s/(2*sqrt(a)))/(4*sqrt(pi)*a**(S(3)/2)),
|
77 |
+
0, True))
|
78 |
+
assert (LT(exp(-a/t), t, s) ==
|
79 |
+
(2*sqrt(a)*sqrt(1/s)*besselk(1, 2*sqrt(a)*sqrt(s)), 0, True))
|
80 |
+
assert LT(sqrt(t)*exp(-a/t), t, s, simplify=True) == (
|
81 |
+
sqrt(pi)*(sqrt(a)*sqrt(s) + 1/S(2))*sqrt(s**(-3)) *
|
82 |
+
exp(-2*sqrt(a)*sqrt(s)), 0, True)
|
83 |
+
assert (LT(exp(-a/t)/sqrt(t), t, s) ==
|
84 |
+
(sqrt(pi)*sqrt(1/s)*exp(-2*sqrt(a)*sqrt(s)), 0, True))
|
85 |
+
assert (LT(exp(-a/t)/(t*sqrt(t)), t, s) ==
|
86 |
+
(sqrt(pi)*sqrt(1/a)*exp(-2*sqrt(a)*sqrt(s)), 0, True))
|
87 |
+
assert (
|
88 |
+
LT(exp(-2*sqrt(a*t)), t, s) ==
|
89 |
+
(1/s - sqrt(pi)*sqrt(a) * exp(a/s)*erfc(sqrt(a)*sqrt(1/s)) /
|
90 |
+
s**(S(3)/2), 0, True))
|
91 |
+
assert LT(exp(-2*sqrt(a*t))/sqrt(t), t, s) == (
|
92 |
+
exp(a/s)*erfc(sqrt(a) * sqrt(1/s))*(sqrt(pi)*sqrt(1/s)), 0, True)
|
93 |
+
assert (LT(t**4*exp(-2/t), t, s) ==
|
94 |
+
(8*sqrt(2)*(1/s)**(S(5)/2)*besselk(5, 2*sqrt(2)*sqrt(s)),
|
95 |
+
0, True))
|
96 |
+
assert LT(sinh(a*t), t, s) == (a/(-a**2 + s**2), a, True)
|
97 |
+
assert (LT(b*sinh(a*t)**2, t, s) ==
|
98 |
+
(2*a**2*b/(-4*a**2*s + s**3), 2*a, True))
|
99 |
+
assert (LT(b*sinh(a*t)**2, t, s, simplify=True) ==
|
100 |
+
(2*a**2*b/(s*(-4*a**2 + s**2)), 2*a, True))
|
101 |
+
# The following line confirms that issue #21202 is solved
|
102 |
+
assert LT(cosh(2*t), t, s) == (s/(-4 + s**2), 2, True)
|
103 |
+
assert LT(cosh(a*t), t, s) == (s/(-a**2 + s**2), a, True)
|
104 |
+
assert (LT(cosh(a*t)**2, t, s, simplify=True) ==
|
105 |
+
((2*a**2 - s**2)/(s*(4*a**2 - s**2)), 2*a, True))
|
106 |
+
assert (LT(sinh(x+3), x, s, simplify=True) ==
|
107 |
+
((s*sinh(3) + cosh(3))/(s**2 - 1), 1, True))
|
108 |
+
L, _, _ = LT(42*sin(w*t+x)**2, t, s)
|
109 |
+
assert (
|
110 |
+
L -
|
111 |
+
21*(s**2 + s*(-s*cos(2*x) + 2*w*sin(2*x)) +
|
112 |
+
4*w**2)/(s*(s**2 + 4*w**2))).simplify() == 0
|
113 |
+
# The following line replaces the old test test_issue_7173()
|
114 |
+
assert LT(sinh(a*t)*cosh(a*t), t, s, simplify=True) == (a/(-4*a**2 + s**2),
|
115 |
+
2*a, True)
|
116 |
+
assert LT(sinh(a*t)/t, t, s) == (log((a + s)/(-a + s))/2, a, True)
|
117 |
+
assert (LT(t**(-S(3)/2)*sinh(a*t), t, s) ==
|
118 |
+
(-sqrt(pi)*(sqrt(-a + s) - sqrt(a + s)), a, True))
|
119 |
+
assert (LT(sinh(2*sqrt(a*t)), t, s) ==
|
120 |
+
(sqrt(pi)*sqrt(a)*exp(a/s)/s**(S(3)/2), 0, True))
|
121 |
+
assert (LT(sqrt(t)*sinh(2*sqrt(a*t)), t, s, simplify=True) ==
|
122 |
+
((-sqrt(a)*s**(S(5)/2) + sqrt(pi)*s**2*(2*a + s)*exp(a/s) *
|
123 |
+
erf(sqrt(a)*sqrt(1/s))/2)/s**(S(9)/2), 0, True))
|
124 |
+
assert (LT(sinh(2*sqrt(a*t))/sqrt(t), t, s) ==
|
125 |
+
(sqrt(pi)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/sqrt(s), 0, True))
|
126 |
+
assert (LT(sinh(sqrt(a*t))**2/sqrt(t), t, s) ==
|
127 |
+
(sqrt(pi)*(exp(a/s) - 1)/(2*sqrt(s)), 0, True))
|
128 |
+
assert (LT(t**(S(3)/7)*cosh(a*t), t, s) ==
|
129 |
+
(((a + s)**(-S(10)/7) + (-a+s)**(-S(10)/7))*gamma(S(10)/7)/2,
|
130 |
+
a, True))
|
131 |
+
assert (LT(cosh(2*sqrt(a*t)), t, s) ==
|
132 |
+
(sqrt(pi)*sqrt(a)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/s**(S(3)/2) +
|
133 |
+
1/s, 0, True))
|
134 |
+
assert (LT(sqrt(t)*cosh(2*sqrt(a*t)), t, s) ==
|
135 |
+
(sqrt(pi)*(a + s/2)*exp(a/s)/s**(S(5)/2), 0, True))
|
136 |
+
assert (LT(cosh(2*sqrt(a*t))/sqrt(t), t, s) ==
|
137 |
+
(sqrt(pi)*exp(a/s)/sqrt(s), 0, True))
|
138 |
+
assert (LT(cosh(sqrt(a*t))**2/sqrt(t), t, s) ==
|
139 |
+
(sqrt(pi)*(exp(a/s) + 1)/(2*sqrt(s)), 0, True))
|
140 |
+
assert LT(log(t), t, s, simplify=True) == (
|
141 |
+
(-log(s) - EulerGamma)/s, 0, True)
|
142 |
+
assert (LT(-log(t/a), t, s, simplify=True) ==
|
143 |
+
((log(a) + log(s) + EulerGamma)/s, 0, True))
|
144 |
+
assert LT(log(1+a*t), t, s) == (-exp(s/a)*Ei(-s/a)/s, 0, True)
|
145 |
+
assert (LT(log(t+a), t, s, simplify=True) ==
|
146 |
+
((s*log(a) - exp(s/a)*Ei(-s/a))/s**2, 0, True))
|
147 |
+
assert (LT(log(t)/sqrt(t), t, s, simplify=True) ==
|
148 |
+
(sqrt(pi)*(-log(s) - log(4) - EulerGamma)/sqrt(s), 0, True))
|
149 |
+
assert (LT(t**(S(5)/2)*log(t), t, s, simplify=True) ==
|
150 |
+
(sqrt(pi)*(-15*log(s) - log(1073741824) - 15*EulerGamma + 46) /
|
151 |
+
(8*s**(S(7)/2)), 0, True))
|
152 |
+
assert (LT(t**3*log(t), t, s, noconds=True, simplify=True) -
|
153 |
+
6*(-log(s) - S.EulerGamma + S(11)/6)/s**4).simplify() == S.Zero
|
154 |
+
assert (LT(log(t)**2, t, s, simplify=True) ==
|
155 |
+
(((log(s) + EulerGamma)**2 + pi**2/6)/s, 0, True))
|
156 |
+
assert (LT(exp(-a*t)*log(t), t, s, simplify=True) ==
|
157 |
+
((-log(a + s) - EulerGamma)/(a + s), -a, True))
|
158 |
+
assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True)
|
159 |
+
assert (LT(Abs(sin(a*t)), t, s) ==
|
160 |
+
(a*coth(pi*s/(2*a))/(a**2 + s**2), 0, True))
|
161 |
+
assert LT(sin(a*t)/t, t, s) == (atan(a/s), 0, True)
|
162 |
+
assert LT(sin(a*t)**2/t, t, s) == (log(4*a**2/s**2 + 1)/4, 0, True)
|
163 |
+
assert (LT(sin(a*t)**2/t**2, t, s) ==
|
164 |
+
(a*atan(2*a/s) - s*log(4*a**2/s**2 + 1)/4, 0, True))
|
165 |
+
assert (LT(sin(2*sqrt(a*t)), t, s) ==
|
166 |
+
(sqrt(pi)*sqrt(a)*exp(-a/s)/s**(S(3)/2), 0, True))
|
167 |
+
assert LT(sin(2*sqrt(a*t))/t, t, s) == (pi*erf(sqrt(a)*sqrt(1/s)), 0, True)
|
168 |
+
assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True)
|
169 |
+
assert (LT(cos(a*t)**2, t, s) ==
|
170 |
+
((2*a**2 + s**2)/(s*(4*a**2 + s**2)), 0, True))
|
171 |
+
assert (LT(sqrt(t)*cos(2*sqrt(a*t)), t, s, simplify=True) ==
|
172 |
+
(sqrt(pi)*(-a + s/2)*exp(-a/s)/s**(S(5)/2), 0, True))
|
173 |
+
assert (LT(cos(2*sqrt(a*t))/sqrt(t), t, s) ==
|
174 |
+
(sqrt(pi)*sqrt(1/s)*exp(-a/s), 0, True))
|
175 |
+
assert (LT(sin(a*t)*sin(b*t), t, s) ==
|
176 |
+
(2*a*b*s/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True))
|
177 |
+
assert (LT(cos(a*t)*sin(b*t), t, s) ==
|
178 |
+
(b*(-a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
|
179 |
+
0, True))
|
180 |
+
assert (LT(cos(a*t)*cos(b*t), t, s) ==
|
181 |
+
(s*(a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
|
182 |
+
0, True))
|
183 |
+
assert (LT(-a*t*cos(a*t) + sin(a*t), t, s, simplify=True) ==
|
184 |
+
(2*a**3/(a**4 + 2*a**2*s**2 + s**4), 0, True))
|
185 |
+
assert LT(c*exp(-b*t)*sin(a*t), t, s) == (a *
|
186 |
+
c/(a**2 + (b + s)**2), -b, True)
|
187 |
+
assert LT(c*exp(-b*t)*cos(a*t), t, s) == (c*(b + s)/(a**2 + (b + s)**2),
|
188 |
+
-b, True)
|
189 |
+
L, plane, cond = LT(cos(x + 3), x, s, simplify=True)
|
190 |
+
assert plane == 0
|
191 |
+
assert L - (s*cos(3) - sin(3))/(s**2 + 1) == 0
|
192 |
+
# Error functions (laplace7.pdf)
|
193 |
+
assert LT(erf(a*t), t, s) == (exp(s**2/(4*a**2))*erfc(s/(2*a))/s, 0, True)
|
194 |
+
assert LT(erf(sqrt(a*t)), t, s) == (sqrt(a)/(s*sqrt(a + s)), 0, True)
|
195 |
+
assert (LT(exp(a*t)*erf(sqrt(a*t)), t, s, simplify=True) ==
|
196 |
+
(-sqrt(a)/(sqrt(s)*(a - s)), a, True))
|
197 |
+
assert (LT(erf(sqrt(a/t)/2), t, s, simplify=True) ==
|
198 |
+
(1/s - exp(-sqrt(a)*sqrt(s))/s, 0, True))
|
199 |
+
assert (LT(erfc(sqrt(a*t)), t, s, simplify=True) ==
|
200 |
+
(-sqrt(a)/(s*sqrt(a + s)) + 1/s, -a, True))
|
201 |
+
assert (LT(exp(a*t)*erfc(sqrt(a*t)), t, s) ==
|
202 |
+
(1/(sqrt(a)*sqrt(s) + s), 0, True))
|
203 |
+
assert LT(erfc(sqrt(a/t)/2), t, s) == (exp(-sqrt(a)*sqrt(s))/s, 0, True)
|
204 |
+
# Bessel functions (laplace8.pdf)
|
205 |
+
assert LT(besselj(0, a*t), t, s) == (1/sqrt(a**2 + s**2), 0, True)
|
206 |
+
assert (LT(besselj(1, a*t), t, s, simplify=True) ==
|
207 |
+
(a/(a**2 + s**2 + s*sqrt(a**2 + s**2)), 0, True))
|
208 |
+
assert (LT(besselj(2, a*t), t, s, simplify=True) ==
|
209 |
+
(a**2/(sqrt(a**2 + s**2)*(s + sqrt(a**2 + s**2))**2), 0, True))
|
210 |
+
assert (LT(t*besselj(0, a*t), t, s) ==
|
211 |
+
(s/(a**2 + s**2)**(S(3)/2), 0, True))
|
212 |
+
assert (LT(t*besselj(1, a*t), t, s) ==
|
213 |
+
(a/(a**2 + s**2)**(S(3)/2), 0, True))
|
214 |
+
assert (LT(t**2*besselj(2, a*t), t, s) ==
|
215 |
+
(3*a**2/(a**2 + s**2)**(S(5)/2), 0, True))
|
216 |
+
assert LT(besselj(0, 2*sqrt(a*t)), t, s) == (exp(-a/s)/s, 0, True)
|
217 |
+
assert (LT(t**(S(3)/2)*besselj(3, 2*sqrt(a*t)), t, s) ==
|
218 |
+
(a**(S(3)/2)*exp(-a/s)/s**4, 0, True))
|
219 |
+
assert (LT(besselj(0, a*sqrt(t**2+b*t)), t, s, simplify=True) ==
|
220 |
+
(exp(b*(s - sqrt(a**2 + s**2)))/sqrt(a**2 + s**2), 0, True))
|
221 |
+
assert LT(besseli(0, a*t), t, s) == (1/sqrt(-a**2 + s**2), a, True)
|
222 |
+
assert (LT(besseli(1, a*t), t, s, simplify=True) ==
|
223 |
+
(a/(-a**2 + s**2 + s*sqrt(-a**2 + s**2)), a, True))
|
224 |
+
assert (LT(besseli(2, a*t), t, s, simplify=True) ==
|
225 |
+
(a**2/(sqrt(-a**2 + s**2)*(s + sqrt(-a**2 + s**2))**2), a, True))
|
226 |
+
assert LT(t*besseli(0, a*t), t, s) == (s/(-a**2 + s**2)**(S(3)/2), a, True)
|
227 |
+
assert LT(t*besseli(1, a*t), t, s) == (a/(-a**2 + s**2)**(S(3)/2), a, True)
|
228 |
+
assert (LT(t**2*besseli(2, a*t), t, s) ==
|
229 |
+
(3*a**2/(-a**2 + s**2)**(S(5)/2), a, True))
|
230 |
+
assert (LT(t**(S(3)/2)*besseli(3, 2*sqrt(a*t)), t, s) ==
|
231 |
+
(a**(S(3)/2)*exp(a/s)/s**4, 0, True))
|
232 |
+
assert (LT(bessely(0, a*t), t, s) ==
|
233 |
+
(-2*asinh(s/a)/(pi*sqrt(a**2 + s**2)), 0, True))
|
234 |
+
assert (LT(besselk(0, a*t), t, s) ==
|
235 |
+
(log((s + sqrt(-a**2 + s**2))/a)/sqrt(-a**2 + s**2), -a, True))
|
236 |
+
assert (LT(sin(a*t)**4, t, s, simplify=True) ==
|
237 |
+
(24*a**4/(s*(64*a**4 + 20*a**2*s**2 + s**4)), 0, True))
|
238 |
+
# Test general rules and unevaluated forms
|
239 |
+
# These all also test whether issue #7219 is solved.
|
240 |
+
assert LT(Heaviside(t-1)*cos(t-1), t, s) == (s*exp(-s)/(s**2 + 1), 0, True)
|
241 |
+
assert LT(a*f(t), t, w) == (a*LaplaceTransform(f(t), t, w), -oo, True)
|
242 |
+
assert (LT(a*Heaviside(t+1)*f(t+1), t, s) ==
|
243 |
+
(a*LaplaceTransform(f(t + 1), t, s), -oo, True))
|
244 |
+
assert (LT(a*Heaviside(t-1)*f(t-1), t, s) ==
|
245 |
+
(a*LaplaceTransform(f(t), t, s)*exp(-s), -oo, True))
|
246 |
+
assert (LT(b*f(t/a), t, s) ==
|
247 |
+
(a*b*LaplaceTransform(f(t), t, a*s), -oo, True))
|
248 |
+
assert LT(exp(-f(x)*t), t, s) == (1/(s + f(x)), -re(f(x)), True)
|
249 |
+
assert (LT(exp(-a*t)*f(t), t, s) ==
|
250 |
+
(LaplaceTransform(f(t), t, a + s), -oo, True))
|
251 |
+
assert (LT(exp(-a*t)*erfc(sqrt(b/t)/2), t, s) ==
|
252 |
+
(exp(-sqrt(b)*sqrt(a + s))/(a + s), -a, True))
|
253 |
+
assert (LT(sinh(a*t)*f(t), t, s) ==
|
254 |
+
(LaplaceTransform(f(t), t, -a + s)/2 -
|
255 |
+
LaplaceTransform(f(t), t, a + s)/2, -oo, True))
|
256 |
+
assert (LT(sinh(a*t)*t, t, s, simplify=True) ==
|
257 |
+
(2*a*s/(a**4 - 2*a**2*s**2 + s**4), a, True))
|
258 |
+
assert (LT(cosh(a*t)*f(t), t, s) ==
|
259 |
+
(LaplaceTransform(f(t), t, -a + s)/2 +
|
260 |
+
LaplaceTransform(f(t), t, a + s)/2, -oo, True))
|
261 |
+
assert (LT(cosh(a*t)*t, t, s, simplify=True) ==
|
262 |
+
(1/(2*(a + s)**2) + 1/(2*(a - s)**2), a, True))
|
263 |
+
assert (LT(sin(a*t)*f(t), t, s, simplify=True) ==
|
264 |
+
(I*(-LaplaceTransform(f(t), t, -I*a + s) +
|
265 |
+
LaplaceTransform(f(t), t, I*a + s))/2, -oo, True))
|
266 |
+
assert (LT(sin(f(t)), t, s) ==
|
267 |
+
(LaplaceTransform(sin(f(t)), t, s), -oo, True))
|
268 |
+
assert (LT(sin(a*t)*t, t, s, simplify=True) ==
|
269 |
+
(2*a*s/(a**4 + 2*a**2*s**2 + s**4), 0, True))
|
270 |
+
assert (LT(cos(a*t)*f(t), t, s) ==
|
271 |
+
(LaplaceTransform(f(t), t, -I*a + s)/2 +
|
272 |
+
LaplaceTransform(f(t), t, I*a + s)/2, -oo, True))
|
273 |
+
assert (LT(cos(a*t)*t, t, s, simplify=True) ==
|
274 |
+
((-a**2 + s**2)/(a**4 + 2*a**2*s**2 + s**4), 0, True))
|
275 |
+
L, plane, _ = LT(sin(a*t+b)**2*f(t), t, s)
|
276 |
+
assert plane == -oo
|
277 |
+
assert (
|
278 |
+
-L + (
|
279 |
+
LaplaceTransform(f(t), t, s)/2 -
|
280 |
+
LaplaceTransform(f(t), t, -2*I*a + s)*exp(2*I*b)/4 -
|
281 |
+
LaplaceTransform(f(t), t, 2*I*a + s)*exp(-2*I*b)/4)) == 0
|
282 |
+
L, plane, _ = LT(sin(a*t)**3*cosh(b*t), t, s)
|
283 |
+
assert plane == b
|
284 |
+
assert (
|
285 |
+
-L - 3*a/(8*(9*a**2 + b**2 + 2*b*s + s**2)) -
|
286 |
+
3*a/(8*(9*a**2 + b**2 - 2*b*s + s**2)) +
|
287 |
+
3*a/(8*(a**2 + b**2 + 2*b*s + s**2)) +
|
288 |
+
3*a/(8*(a**2 + b**2 - 2*b*s + s**2))).simplify() == 0
|
289 |
+
assert (LT(t**2*exp(-t**2), t, s) ==
|
290 |
+
(sqrt(pi)*s**2*exp(s**2/4)*erfc(s/2)/8 - s/4 +
|
291 |
+
sqrt(pi)*exp(s**2/4)*erfc(s/2)/4, 0, True))
|
292 |
+
assert (LT((a*t**2 + b*t + c)*f(t), t, s) ==
|
293 |
+
(a*Derivative(LaplaceTransform(f(t), t, s), (s, 2)) -
|
294 |
+
b*Derivative(LaplaceTransform(f(t), t, s), s) +
|
295 |
+
c*LaplaceTransform(f(t), t, s), -oo, True))
|
296 |
+
# The following two lines test whether issues #5813 and #7176 are solved.
|
297 |
+
assert (LT(diff(f(t), (t, 1)), t, s, noconds=True) ==
|
298 |
+
s*LaplaceTransform(f(t), t, s) - f(0))
|
299 |
+
assert (LT(diff(f(t), (t, 3)), t, s, noconds=True) ==
|
300 |
+
s**3*LaplaceTransform(f(t), t, s) - s**2*f(0) -
|
301 |
+
s*Subs(Derivative(f(t), t), t, 0) -
|
302 |
+
Subs(Derivative(f(t), (t, 2)), t, 0))
|
303 |
+
# Issue #7219
|
304 |
+
assert (LT(diff(f(x, t, w), t, 2), t, s) ==
|
305 |
+
(s**2*LaplaceTransform(f(x, t, w), t, s) - s*f(x, 0, w) -
|
306 |
+
Subs(Derivative(f(x, t, w), t), t, 0), -oo, True))
|
307 |
+
# Issue #23307
|
308 |
+
assert (LT(10*diff(f(t), (t, 1)), t, s, noconds=True) ==
|
309 |
+
10*s*LaplaceTransform(f(t), t, s) - 10*f(0))
|
310 |
+
assert (LT(a*f(b*t)+g(c*t), t, s, noconds=True) ==
|
311 |
+
a*LaplaceTransform(f(t), t, s/b)/b +
|
312 |
+
LaplaceTransform(g(t), t, s/c)/c)
|
313 |
+
assert inverse_laplace_transform(
|
314 |
+
f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0)
|
315 |
+
assert (LT(f(t)*g(t), t, s, noconds=True) ==
|
316 |
+
LaplaceTransform(f(t)*g(t), t, s))
|
317 |
+
# Issue #24294
|
318 |
+
assert (LT(b*f(a*t), t, s, noconds=True) ==
|
319 |
+
b*LaplaceTransform(f(t), t, s/a)/a)
|
320 |
+
assert LT(3*exp(t)*Heaviside(t), t, s) == (3/(s - 1), 1, True)
|
321 |
+
assert (LT(2*sin(t)*Heaviside(t), t, s, simplify=True) ==
|
322 |
+
(2/(s**2 + 1), 0, True))
|
323 |
+
# additional basic tests from wikipedia
|
324 |
+
assert (LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) ==
|
325 |
+
((c + s)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True))
|
326 |
+
assert (
|
327 |
+
LT((exp(2*t)-1)*exp(-b-t)*Heaviside(t)/2, t, s, noconds=True,
|
328 |
+
simplify=True) ==
|
329 |
+
exp(-b)/(s**2 - 1))
|
330 |
+
# DiracDelta function: standard cases
|
331 |
+
assert LT(DiracDelta(t), t, s) == (1, -oo, True)
|
332 |
+
assert LT(DiracDelta(a*t), t, s) == (1/a, -oo, True)
|
333 |
+
assert LT(DiracDelta(t/42), t, s) == (42, -oo, True)
|
334 |
+
assert LT(DiracDelta(t+42), t, s) == (0, -oo, True)
|
335 |
+
assert (LT(DiracDelta(t)+DiracDelta(t-42), t, s) ==
|
336 |
+
(1 + exp(-42*s), -oo, True))
|
337 |
+
assert (LT(DiracDelta(t)-a*exp(-a*t), t, s, simplify=True) ==
|
338 |
+
(s/(a + s), -a, True))
|
339 |
+
assert (
|
340 |
+
LT(exp(-t)*(DiracDelta(t)+DiracDelta(t-42)), t, s, simplify=True) ==
|
341 |
+
(exp(-42*s - 42) + 1, -oo, True))
|
342 |
+
assert LT(f(t)*DiracDelta(t-42), t, s) == (f(42)*exp(-42*s), -oo, True)
|
343 |
+
assert LT(f(t)*DiracDelta(b*t-a), t, s) == (f(a/b)*exp(-a*s/b)/b,
|
344 |
+
-oo, True)
|
345 |
+
assert LT(f(t)*DiracDelta(b*t+a), t, s) == (0, -oo, True)
|
346 |
+
# Collection of cases that cannot be fully evaluated and/or would catch
|
347 |
+
# some common implementation errors
|
348 |
+
assert (LT(DiracDelta(t**2), t, s, noconds=True) ==
|
349 |
+
LaplaceTransform(DiracDelta(t**2), t, s))
|
350 |
+
assert LT(DiracDelta(t**2 - 1), t, s) == (exp(-s)/2, -oo, True)
|
351 |
+
assert LT(DiracDelta(t*(1 - t)), t, s) == (1 - exp(-s), -oo, True)
|
352 |
+
assert (LT((DiracDelta(t) + 1)*(DiracDelta(t - 1) + 1), t, s) ==
|
353 |
+
(LaplaceTransform(DiracDelta(t)*DiracDelta(t - 1), t, s) +
|
354 |
+
1 + exp(-s) + 1/s, 0, True))
|
355 |
+
assert LT(DiracDelta(2*t-2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True)
|
356 |
+
assert LT(DiracDelta(-2*t+2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True)
|
357 |
+
# Heaviside tests
|
358 |
+
assert LT(Heaviside(t), t, s) == (1/s, 0, True)
|
359 |
+
assert LT(Heaviside(t - a), t, s) == (exp(-a*s)/s, 0, True)
|
360 |
+
assert LT(Heaviside(t-1), t, s) == (exp(-s)/s, 0, True)
|
361 |
+
assert LT(Heaviside(2*t-4), t, s) == (exp(-2*s)/s, 0, True)
|
362 |
+
assert LT(Heaviside(2*t+4), t, s) == (1/s, 0, True)
|
363 |
+
assert (LT(Heaviside(-2*t+4), t, s, simplify=True) ==
|
364 |
+
(1/s - exp(-2*s)/s, 0, True))
|
365 |
+
assert (LT(g(t)*Heaviside(t - w), t, s) ==
|
366 |
+
(LaplaceTransform(g(t)*Heaviside(t - w), t, s), -oo, True))
|
367 |
+
# Fresnel functions
|
368 |
+
assert (laplace_transform(fresnels(t), t, s, simplify=True) ==
|
369 |
+
((-sin(s**2/(2*pi))*fresnels(s/pi) +
|
370 |
+
sqrt(2)*sin(s**2/(2*pi) + pi/4)/2 -
|
371 |
+
cos(s**2/(2*pi))*fresnelc(s/pi))/s, 0, True))
|
372 |
+
assert (laplace_transform(fresnelc(t), t, s, simplify=True) ==
|
373 |
+
((sin(s**2/(2*pi))*fresnelc(s/pi) -
|
374 |
+
cos(s**2/(2*pi))*fresnels(s/pi) +
|
375 |
+
sqrt(2)*cos(s**2/(2*pi) + pi/4)/2)/s, 0, True))
|
376 |
+
# Matrix tests
|
377 |
+
Mt = Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]])
|
378 |
+
Ms = Matrix([[1/(s - 1), (s + 1)**(-2)],
|
379 |
+
[(s + 1)**(-2), 1/(s - 1)]])
|
380 |
+
# The default behaviour for Laplace transform of a Matrix returns a Matrix
|
381 |
+
# of Tuples and is deprecated:
|
382 |
+
with warns_deprecated_sympy():
|
383 |
+
Ms_conds = Matrix(
|
384 |
+
[[(1/(s - 1), 1, True), ((s + 1)**(-2), -1, True)],
|
385 |
+
[((s + 1)**(-2), -1, True), (1/(s - 1), 1, True)]])
|
386 |
+
with warns_deprecated_sympy():
|
387 |
+
assert LT(Mt, t, s) == Ms_conds
|
388 |
+
# The new behavior is to return a tuple of a Matrix and the convergence
|
389 |
+
# conditions for the matrix as a whole:
|
390 |
+
assert LT(Mt, t, s, legacy_matrix=False) == (Ms, 1, True)
|
391 |
+
# With noconds=True the transformed matrix is returned without conditions
|
392 |
+
# either way:
|
393 |
+
assert LT(Mt, t, s, noconds=True) == Ms
|
394 |
+
assert LT(Mt, t, s, legacy_matrix=False, noconds=True) == Ms
|
395 |
+
|
396 |
+
|
397 |
+
@slow
|
398 |
+
def test_inverse_laplace_transform():
|
399 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
400 |
+
ILT = inverse_laplace_transform
|
401 |
+
a, b, c, d = symbols('a b c d', positive=True)
|
402 |
+
n, r = symbols('n, r', real=True)
|
403 |
+
t, z = symbols('t z')
|
404 |
+
f = Function('f')
|
405 |
+
|
406 |
+
def simp_hyp(expr):
|
407 |
+
return factor_terms(expand_mul(expr)).rewrite(sin)
|
408 |
+
|
409 |
+
assert ILT(1, s, t) == DiracDelta(t)
|
410 |
+
assert ILT(1/s, s, t) == Heaviside(t)
|
411 |
+
assert ILT(a/(a + s), s, t) == a*exp(-a*t)*Heaviside(t)
|
412 |
+
assert ILT(s/(a + s), s, t) == -a*exp(-a*t)*Heaviside(t) + DiracDelta(t)
|
413 |
+
assert (ILT(s/(a + s)**3, s, t, simplify=True) ==
|
414 |
+
t*(-a*t + 4)*exp(-a*t)*Heaviside(t)/2)
|
415 |
+
assert (ILT(1/(s*(a + s)**3), s, t, simplify=True) ==
|
416 |
+
(-a**2*t**2 - 4*a*t + 4*exp(a*t) - 4) *
|
417 |
+
exp(-a*t)*Heaviside(t)/(2*a**3))
|
418 |
+
assert ILT(1/(s*(a + s)**n), s, t) == (
|
419 |
+
Heaviside(t)*lowergamma(n, a*t)/(a**n*gamma(n)))
|
420 |
+
assert ILT((s-a)**(-b), s, t) == t**(b - 1)*exp(a*t)*Heaviside(t)/gamma(b)
|
421 |
+
assert ILT((a + s)**(-2), s, t) == t*exp(-a*t)*Heaviside(t)
|
422 |
+
assert ILT((a + s)**(-5), s, t) == t**4*exp(-a*t)*Heaviside(t)/24
|
423 |
+
assert ILT(a/(a**2 + s**2), s, t) == sin(a*t)*Heaviside(t)
|
424 |
+
assert ILT(s/(s**2 + a**2), s, t) == cos(a*t)*Heaviside(t)
|
425 |
+
assert ILT(b/(b**2 + (a + s)**2), s, t) == exp(-a*t)*sin(b*t)*Heaviside(t)
|
426 |
+
assert (ILT(b*s/(b**2 + (a + s)**2), s, t) ==
|
427 |
+
b*(-a*exp(-a*t)*sin(b*t)/b + exp(-a*t)*cos(b*t))*Heaviside(t))
|
428 |
+
assert ILT(exp(-a*s)/s, s, t) == Heaviside(-a + t)
|
429 |
+
assert ILT(exp(-a*s)/(b + s), s, t) == exp(b*(a - t))*Heaviside(-a + t)
|
430 |
+
assert (ILT((b + s)/(a**2 + (b + s)**2), s, t) ==
|
431 |
+
exp(-b*t)*cos(a*t)*Heaviside(t))
|
432 |
+
assert (ILT(exp(-a*s)/s**b, s, t) ==
|
433 |
+
(-a + t)**(b - 1)*Heaviside(-a + t)/gamma(b))
|
434 |
+
assert (ILT(exp(-a*s)/sqrt(s**2 + 1), s, t) ==
|
435 |
+
Heaviside(-a + t)*besselj(0, a - t))
|
436 |
+
assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
|
437 |
+
assert (ILT(1/(s**2*(s**2 + 1)), s, t) ==
|
438 |
+
t*Heaviside(t) - sin(t)*Heaviside(t))
|
439 |
+
assert ILT(s**2/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t)
|
440 |
+
assert ILT(1 - 1/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t)
|
441 |
+
assert ILT(1/s**2, s, t) == t*Heaviside(t)
|
442 |
+
assert ILT(1/s**5, s, t) == t**4*Heaviside(t)/24
|
443 |
+
assert ILT(1/s**n, s, t) == t**(n - 1)*Heaviside(t)/gamma(n)
|
444 |
+
# Issue #24424
|
445 |
+
assert (ILT((s + 8)/((s + 2)*(s**2 + 2*s + 10)), s, t, simplify=True) ==
|
446 |
+
((8*sin(3*t) - 9*cos(3*t))*exp(t) + 9)*exp(-2*t)*Heaviside(t)/15)
|
447 |
+
assert simp_hyp(ILT(a/(s**2 - a**2), s, t)) == sinh(a*t)*Heaviside(t)
|
448 |
+
assert simp_hyp(ILT(s/(s**2 - a**2), s, t)) == cosh(a*t)*Heaviside(t)
|
449 |
+
# TODO sinh/cosh shifted come out a mess. also delayed trig is a mess
|
450 |
+
# TODO should this simplify further?
|
451 |
+
assert (ILT(exp(-a*s)/s**b, s, t) ==
|
452 |
+
(t - a)**(b - 1)*Heaviside(t - a)/gamma(b))
|
453 |
+
assert (ILT(exp(-a*s)/sqrt(1 + s**2), s, t) ==
|
454 |
+
Heaviside(t - a)*besselj(0, a - t)) # note: besselj(0, x) is even
|
455 |
+
# XXX ILT turns these branch factor into trig functions ...
|
456 |
+
assert (
|
457 |
+
simplify(ILT(a**b*(s + sqrt(s**2 - a**2))**(-b)/sqrt(s**2 - a**2),
|
458 |
+
s, t).rewrite(exp)) ==
|
459 |
+
Heaviside(t)*besseli(b, a*t))
|
460 |
+
assert (
|
461 |
+
ILT(a**b*(s + sqrt(s**2 + a**2))**(-b)/sqrt(s**2 + a**2),
|
462 |
+
s, t, simplify=True).rewrite(exp) ==
|
463 |
+
Heaviside(t)*besselj(b, a*t))
|
464 |
+
assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
|
465 |
+
# TODO can we make erf(t) work?
|
466 |
+
assert (ILT(1/(s**2*(s**2 + 1)), s, t, simplify=True) ==
|
467 |
+
(t - sin(t))*Heaviside(t))
|
468 |
+
assert (ILT((s * eye(2) - Matrix([[1, 0], [0, 2]])).inv(), s, t) ==
|
469 |
+
Matrix([[exp(t)*Heaviside(t), 0], [0, exp(2*t)*Heaviside(t)]]))
|
470 |
+
# New tests for rules
|
471 |
+
assert (ILT(b/(s**2-a**2), s, t, simplify=True) ==
|
472 |
+
b*sinh(a*t)*Heaviside(t)/a)
|
473 |
+
assert (ILT(b/(s**2-a**2), s, t) ==
|
474 |
+
b*(exp(a*t)*Heaviside(t)/(2*a) - exp(-a*t)*Heaviside(t)/(2*a)))
|
475 |
+
assert (ILT(b*s/(s**2-a**2), s, t, simplify=True) ==
|
476 |
+
b*cosh(a*t)*Heaviside(t))
|
477 |
+
assert (ILT(b/(s*(s+a)), s, t) ==
|
478 |
+
b*(Heaviside(t)/a - exp(-a*t)*Heaviside(t)/a))
|
479 |
+
assert (ILT(b*s/(s+a)**2, s, t) ==
|
480 |
+
b*(-a*t*exp(-a*t)*Heaviside(t) + exp(-a*t)*Heaviside(t)))
|
481 |
+
assert (ILT(c/((s+a)*(s+b)), s, t, simplify=True) ==
|
482 |
+
c*(exp(a*t) - exp(b*t))*exp(-t*(a + b))*Heaviside(t)/(a - b))
|
483 |
+
assert (ILT(c*s/((s+a)*(s+b)), s, t, simplify=True) ==
|
484 |
+
c*(a*exp(b*t) - b*exp(a*t))*exp(-t*(a + b))*Heaviside(t)/(a - b))
|
485 |
+
assert (ILT(c*s/(d**2*(s+a)**2+b**2), s, t, simplify=True) ==
|
486 |
+
c*(-a*d*sin(b*t/d) + b*cos(b*t/d))*exp(-a*t)*Heaviside(t)/(b*d**2))
|
487 |
+
# Test time_diff rule
|
488 |
+
assert (ILT(s**42*f(s), s, t) ==
|
489 |
+
Derivative(InverseLaplaceTransform(f(s), s, t, None), (t, 42)))
|
490 |
+
assert (ILT((b*s**2 + d)/(a**2 + s**2)**2, s, t, simplify=True) ==
|
491 |
+
(a**3*b*t*cos(a*t) + 5*a**2*b*sin(a*t) - a*d*t*cos(a*t) +
|
492 |
+
d*sin(a*t))*Heaviside(t)/(2*a**3))
|
493 |
+
assert ILT(cos(s), s, t) == InverseLaplaceTransform(cos(s), s, t, None)
|
494 |
+
# Rules for testing different DiracDelta cases
|
495 |
+
assert ILT(2, s, t) == 2*DiracDelta(t)
|
496 |
+
assert (ILT(2*exp(3*s) - 5*exp(-7*s), s, t) ==
|
497 |
+
2*InverseLaplaceTransform(exp(3*s), s, t, None) -
|
498 |
+
5*DiracDelta(t - 7))
|
499 |
+
a = cos(sin(7)/2)
|
500 |
+
assert ILT(a*exp(-3*s), s, t) == a*DiracDelta(t - 3)
|
501 |
+
assert ILT(exp(2*s), s, t) == InverseLaplaceTransform(exp(2*s), s, t, None)
|
502 |
+
r = Symbol('r', real=True)
|
503 |
+
assert ILT(exp(r*s), s, t) == InverseLaplaceTransform(exp(r*s), s, t, None)
|
504 |
+
# Rules for testing whether Heaviside(t) is treated properly in diff rule
|
505 |
+
assert ILT(s**2/(a**2 + s**2), s, t) == (
|
506 |
+
-a*sin(a*t)*Heaviside(t) + DiracDelta(t))
|
507 |
+
assert ILT(s**2*(f(s) + 1/(a**2 + s**2)), s, t) == (
|
508 |
+
-a*sin(a*t)*Heaviside(t) + DiracDelta(t) +
|
509 |
+
Derivative(InverseLaplaceTransform(f(s), s, t, None), (t, 2)))
|
510 |
+
# Rules from the previous test_inverse_laplace_transform_delta_cond():
|
511 |
+
assert (ILT(exp(r*s), s, t, noconds=False) ==
|
512 |
+
(InverseLaplaceTransform(exp(r*s), s, t, None), True))
|
513 |
+
# inversion does not exist: verify it doesn't evaluate to DiracDelta
|
514 |
+
for z in (Symbol('z', extended_real=False),
|
515 |
+
Symbol('z', imaginary=True, zero=False)):
|
516 |
+
f = ILT(exp(z*s), s, t, noconds=False)
|
517 |
+
f = f[0] if isinstance(f, tuple) else f
|
518 |
+
assert f.func != DiracDelta
|
519 |
+
# old test for Issue 8514, is not important anymore since this function
|
520 |
+
# is not solved by integration anymore
|
521 |
+
assert (ILT(1/(a*s**2+b*s+c), s, t) ==
|
522 |
+
2*exp(-b*t/(2*a))*sin(t*sqrt(4*a*c - b**2)/(2*a)) *
|
523 |
+
Heaviside(t)/sqrt(4*a*c - b**2))
|
524 |
+
|
525 |
+
|
526 |
+
@slow
|
527 |
+
def test_expint():
|
528 |
+
x = Symbol('x')
|
529 |
+
a = Symbol('a')
|
530 |
+
u = Symbol('u', polar=True)
|
531 |
+
|
532 |
+
# TODO LT of Si, Shi, Chi is a mess ...
|
533 |
+
assert laplace_transform(Ci(x), x, s) == (-log(1 + s**2)/2/s, 0, True)
|
534 |
+
assert (laplace_transform(expint(a, x), x, s, simplify=True) ==
|
535 |
+
(lerchphi(s*exp_polar(I*pi), 1, a), 0, re(a) > S.Zero))
|
536 |
+
assert (laplace_transform(expint(1, x), x, s, simplify=True) ==
|
537 |
+
(log(s + 1)/s, 0, True))
|
538 |
+
assert (laplace_transform(expint(2, x), x, s, simplify=True) ==
|
539 |
+
((s - log(s + 1))/s**2, 0, True))
|
540 |
+
assert (inverse_laplace_transform(-log(1 + s**2)/2/s, s, u).expand() ==
|
541 |
+
Heaviside(u)*Ci(u))
|
542 |
+
assert (
|
543 |
+
inverse_laplace_transform(log(s + 1)/s, s, x,
|
544 |
+
simplify=True).rewrite(expint) ==
|
545 |
+
Heaviside(x)*E1(x))
|
546 |
+
assert (
|
547 |
+
inverse_laplace_transform(
|
548 |
+
(s - log(s + 1))/s**2, s, x,
|
549 |
+
simplify=True).rewrite(expint).expand() ==
|
550 |
+
(expint(2, x)*Heaviside(x)).rewrite(Ei).rewrite(expint).expand())
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_lineintegrals.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import E
|
2 |
+
from sympy.core.symbol import symbols
|
3 |
+
from sympy.functions.elementary.exponential import log
|
4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
5 |
+
from sympy.geometry.curve import Curve
|
6 |
+
from sympy.integrals.integrals import line_integrate
|
7 |
+
|
8 |
+
s, t, x, y, z = symbols('s,t,x,y,z')
|
9 |
+
|
10 |
+
|
11 |
+
def test_lineintegral():
|
12 |
+
c = Curve([E**t + 1, E**t - 1], (t, 0, log(2)))
|
13 |
+
assert line_integrate(x + y, c, [x, y]) == 3*sqrt(2)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_manual.py
ADDED
@@ -0,0 +1,688 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.expr import Expr
|
2 |
+
from sympy.core.mul import Mul
|
3 |
+
from sympy.core.function import (Derivative, Function, diff, expand)
|
4 |
+
from sympy.core.numbers import (I, Rational, pi)
|
5 |
+
from sympy.core.relational import Ne
|
6 |
+
from sympy.core.singleton import S
|
7 |
+
from sympy.core.symbol import (Dummy, Symbol, symbols)
|
8 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
9 |
+
from sympy.functions.elementary.hyperbolic import (asinh, csch, cosh, coth, sech, sinh, tanh)
|
10 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
11 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
12 |
+
from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, cos, cot, csc, sec, sin, tan)
|
13 |
+
from sympy.functions.special.delta_functions import Heaviside, DiracDelta
|
14 |
+
from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f)
|
15 |
+
from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, erf, erfi, fresnelc, fresnels, li)
|
16 |
+
from sympy.functions.special.gamma_functions import uppergamma
|
17 |
+
from sympy.functions.special.polynomials import (assoc_laguerre, chebyshevt, chebyshevu, gegenbauer, hermite, jacobi, laguerre, legendre)
|
18 |
+
from sympy.functions.special.zeta_functions import polylog
|
19 |
+
from sympy.integrals.integrals import (Integral, integrate)
|
20 |
+
from sympy.logic.boolalg import And
|
21 |
+
from sympy.integrals.manualintegrate import (manualintegrate, find_substitutions,
|
22 |
+
_parts_rule, integral_steps, manual_subs)
|
23 |
+
from sympy.testing.pytest import raises, slow
|
24 |
+
|
25 |
+
x, y, z, u, n, a, b, c, d, e = symbols('x y z u n a b c d e')
|
26 |
+
f = Function('f')
|
27 |
+
|
28 |
+
|
29 |
+
def assert_is_integral_of(f: Expr, F: Expr):
|
30 |
+
assert manualintegrate(f, x) == F
|
31 |
+
assert F.diff(x).equals(f)
|
32 |
+
|
33 |
+
|
34 |
+
def test_find_substitutions():
|
35 |
+
assert find_substitutions((cot(x)**2 + 1)**2*csc(x)**2*cot(x)**2, x, u) == \
|
36 |
+
[(cot(x), 1, -u**6 - 2*u**4 - u**2)]
|
37 |
+
assert find_substitutions((sec(x)**2 + tan(x) * sec(x)) / (sec(x) + tan(x)),
|
38 |
+
x, u) == [(sec(x) + tan(x), 1, 1/u)]
|
39 |
+
assert (-x**2, Rational(-1, 2), exp(u)) in find_substitutions(x * exp(-x**2), x, u)
|
40 |
+
assert not find_substitutions(Derivative(f(x), x)**2, x, u)
|
41 |
+
|
42 |
+
|
43 |
+
def test_manualintegrate_polynomials():
|
44 |
+
assert manualintegrate(y, x) == x*y
|
45 |
+
assert manualintegrate(exp(2), x) == x * exp(2)
|
46 |
+
assert manualintegrate(x**2, x) == x**3 / 3
|
47 |
+
assert manualintegrate(3 * x**2 + 4 * x**3, x) == x**3 + x**4
|
48 |
+
|
49 |
+
assert manualintegrate((x + 2)**3, x) == (x + 2)**4 / 4
|
50 |
+
assert manualintegrate((3*x + 4)**2, x) == (3*x + 4)**3 / 9
|
51 |
+
|
52 |
+
assert manualintegrate((u + 2)**3, u) == (u + 2)**4 / 4
|
53 |
+
assert manualintegrate((3*u + 4)**2, u) == (3*u + 4)**3 / 9
|
54 |
+
|
55 |
+
|
56 |
+
def test_manualintegrate_exponentials():
|
57 |
+
assert manualintegrate(exp(2*x), x) == exp(2*x) / 2
|
58 |
+
assert manualintegrate(2**x, x) == (2 ** x) / log(2)
|
59 |
+
assert_is_integral_of(1/sqrt(1-exp(2*x)),
|
60 |
+
log(sqrt(1 - exp(2*x)) - 1)/2 - log(sqrt(1 - exp(2*x)) + 1)/2)
|
61 |
+
|
62 |
+
assert manualintegrate(1 / x, x) == log(x)
|
63 |
+
assert manualintegrate(1 / (2*x + 3), x) == log(2*x + 3) / 2
|
64 |
+
assert manualintegrate(log(x)**2 / x, x) == log(x)**3 / 3
|
65 |
+
|
66 |
+
assert_is_integral_of(x**x*(log(x)+1), x**x)
|
67 |
+
|
68 |
+
|
69 |
+
def test_manualintegrate_parts():
|
70 |
+
assert manualintegrate(exp(x) * sin(x), x) == \
|
71 |
+
(exp(x) * sin(x)) / 2 - (exp(x) * cos(x)) / 2
|
72 |
+
assert manualintegrate(2*x*cos(x), x) == 2*x*sin(x) + 2*cos(x)
|
73 |
+
assert manualintegrate(x * log(x), x) == x**2*log(x)/2 - x**2/4
|
74 |
+
assert manualintegrate(log(x), x) == x * log(x) - x
|
75 |
+
assert manualintegrate((3*x**2 + 5) * exp(x), x) == \
|
76 |
+
3*x**2*exp(x) - 6*x*exp(x) + 11*exp(x)
|
77 |
+
assert manualintegrate(atan(x), x) == x*atan(x) - log(x**2 + 1)/2
|
78 |
+
|
79 |
+
# Make sure _parts_rule doesn't pick u = constant but can pick dv =
|
80 |
+
# constant if necessary, e.g. for integrate(atan(x))
|
81 |
+
assert _parts_rule(cos(x), x) == None
|
82 |
+
assert _parts_rule(exp(x), x) == None
|
83 |
+
assert _parts_rule(x**2, x) == None
|
84 |
+
result = _parts_rule(atan(x), x)
|
85 |
+
assert result[0] == atan(x) and result[1] == 1
|
86 |
+
|
87 |
+
|
88 |
+
def test_manualintegrate_trigonometry():
|
89 |
+
assert manualintegrate(sin(x), x) == -cos(x)
|
90 |
+
assert manualintegrate(tan(x), x) == -log(cos(x))
|
91 |
+
|
92 |
+
assert manualintegrate(sec(x), x) == log(sec(x) + tan(x))
|
93 |
+
assert manualintegrate(csc(x), x) == -log(csc(x) + cot(x))
|
94 |
+
|
95 |
+
assert manualintegrate(sin(x) * cos(x), x) in [sin(x) ** 2 / 2, -cos(x)**2 / 2]
|
96 |
+
assert manualintegrate(-sec(x) * tan(x), x) == -sec(x)
|
97 |
+
assert manualintegrate(csc(x) * cot(x), x) == -csc(x)
|
98 |
+
assert manualintegrate(sec(x)**2, x) == tan(x)
|
99 |
+
assert manualintegrate(csc(x)**2, x) == -cot(x)
|
100 |
+
|
101 |
+
assert manualintegrate(x * sec(x**2), x) == log(tan(x**2) + sec(x**2))/2
|
102 |
+
assert manualintegrate(cos(x)*csc(sin(x)), x) == -log(cot(sin(x)) + csc(sin(x)))
|
103 |
+
assert manualintegrate(cos(3*x)*sec(x), x) == -x + sin(2*x)
|
104 |
+
assert manualintegrate(sin(3*x)*sec(x), x) == \
|
105 |
+
-3*log(cos(x)) + 2*log(cos(x)**2) - 2*cos(x)**2
|
106 |
+
|
107 |
+
assert_is_integral_of(sinh(2*x), cosh(2*x)/2)
|
108 |
+
assert_is_integral_of(x*cosh(x**2), sinh(x**2)/2)
|
109 |
+
assert_is_integral_of(tanh(x), log(cosh(x)))
|
110 |
+
assert_is_integral_of(coth(x), log(sinh(x)))
|
111 |
+
f, F = sech(x), 2*atan(tanh(x/2))
|
112 |
+
assert manualintegrate(f, x) == F
|
113 |
+
assert (F.diff(x) - f).rewrite(exp).simplify() == 0 # todo: equals returns None
|
114 |
+
f, F = csch(x), log(tanh(x/2))
|
115 |
+
assert manualintegrate(f, x) == F
|
116 |
+
assert (F.diff(x) - f).rewrite(exp).simplify() == 0
|
117 |
+
|
118 |
+
|
119 |
+
@slow
|
120 |
+
def test_manualintegrate_trigpowers():
|
121 |
+
assert manualintegrate(sin(x)**2 * cos(x), x) == sin(x)**3 / 3
|
122 |
+
assert manualintegrate(sin(x)**2 * cos(x) **2, x) == \
|
123 |
+
x / 8 - sin(4*x) / 32
|
124 |
+
assert manualintegrate(sin(x) * cos(x)**3, x) == -cos(x)**4 / 4
|
125 |
+
assert manualintegrate(sin(x)**3 * cos(x)**2, x) == \
|
126 |
+
cos(x)**5 / 5 - cos(x)**3 / 3
|
127 |
+
|
128 |
+
assert manualintegrate(tan(x)**3 * sec(x), x) == sec(x)**3/3 - sec(x)
|
129 |
+
assert manualintegrate(tan(x) * sec(x) **2, x) == sec(x)**2/2
|
130 |
+
|
131 |
+
assert manualintegrate(cot(x)**5 * csc(x), x) == \
|
132 |
+
-csc(x)**5/5 + 2*csc(x)**3/3 - csc(x)
|
133 |
+
assert manualintegrate(cot(x)**2 * csc(x)**6, x) == \
|
134 |
+
-cot(x)**7/7 - 2*cot(x)**5/5 - cot(x)**3/3
|
135 |
+
|
136 |
+
|
137 |
+
@slow
|
138 |
+
def test_manualintegrate_inversetrig():
|
139 |
+
# atan
|
140 |
+
assert manualintegrate(exp(x) / (1 + exp(2*x)), x) == atan(exp(x))
|
141 |
+
assert manualintegrate(1 / (4 + 9 * x**2), x) == atan(3 * x/2) / 6
|
142 |
+
assert manualintegrate(1 / (16 + 16 * x**2), x) == atan(x) / 16
|
143 |
+
assert manualintegrate(1 / (4 + x**2), x) == atan(x / 2) / 2
|
144 |
+
assert manualintegrate(1 / (1 + 4 * x**2), x) == atan(2*x) / 2
|
145 |
+
ra = Symbol('a', real=True)
|
146 |
+
rb = Symbol('b', real=True)
|
147 |
+
assert manualintegrate(1/(ra + rb*x**2), x) == \
|
148 |
+
Piecewise((atan(x/sqrt(ra/rb))/(rb*sqrt(ra/rb)), ra/rb > 0),
|
149 |
+
((log(x - sqrt(-ra/rb)) - log(x + sqrt(-ra/rb)))/(2*sqrt(rb)*sqrt(-ra)), True))
|
150 |
+
assert manualintegrate(1/(4 + rb*x**2), x) == \
|
151 |
+
Piecewise((atan(x/(2*sqrt(1/rb)))/(2*rb*sqrt(1/rb)), 1/rb > 0),
|
152 |
+
(-I*(log(x - 2*sqrt(-1/rb)) - log(x + 2*sqrt(-1/rb)))/(4*sqrt(rb)), True))
|
153 |
+
assert manualintegrate(1/(ra + 4*x**2), x) == \
|
154 |
+
Piecewise((atan(2*x/sqrt(ra))/(2*sqrt(ra)), ra > 0),
|
155 |
+
((log(x - sqrt(-ra)/2) - log(x + sqrt(-ra)/2))/(4*sqrt(-ra)), True))
|
156 |
+
assert manualintegrate(1/(4 + 4*x**2), x) == atan(x) / 4
|
157 |
+
|
158 |
+
assert manualintegrate(1/(a + b*x**2), x) == atan(x/sqrt(a/b))/(b*sqrt(a/b))
|
159 |
+
|
160 |
+
# asin
|
161 |
+
assert manualintegrate(1/sqrt(1-x**2), x) == asin(x)
|
162 |
+
assert manualintegrate(1/sqrt(4-4*x**2), x) == asin(x)/2
|
163 |
+
assert manualintegrate(3/sqrt(1-9*x**2), x) == asin(3*x)
|
164 |
+
assert manualintegrate(1/sqrt(4-9*x**2), x) == asin(x*Rational(3, 2))/3
|
165 |
+
|
166 |
+
# asinh
|
167 |
+
assert manualintegrate(1/sqrt(x**2 + 1), x) == \
|
168 |
+
asinh(x)
|
169 |
+
assert manualintegrate(1/sqrt(x**2 + 4), x) == \
|
170 |
+
asinh(x/2)
|
171 |
+
assert manualintegrate(1/sqrt(4*x**2 + 4), x) == \
|
172 |
+
asinh(x)/2
|
173 |
+
assert manualintegrate(1/sqrt(4*x**2 + 1), x) == \
|
174 |
+
asinh(2*x)/2
|
175 |
+
assert manualintegrate(1/sqrt(ra*x**2 + 1), x) == \
|
176 |
+
Piecewise((asin(x*sqrt(-ra))/sqrt(-ra), ra < 0), (asinh(sqrt(ra)*x)/sqrt(ra), ra > 0), (x, True))
|
177 |
+
assert manualintegrate(1/sqrt(ra + x**2), x) == \
|
178 |
+
Piecewise((asinh(x*sqrt(1/ra)), ra > 0), (log(2*x + 2*sqrt(ra + x**2)), True))
|
179 |
+
|
180 |
+
# log
|
181 |
+
assert manualintegrate(1/sqrt(x**2 - 1), x) == log(2*x + 2*sqrt(x**2 - 1))
|
182 |
+
assert manualintegrate(1/sqrt(x**2 - 4), x) == log(2*x + 2*sqrt(x**2 - 4))
|
183 |
+
assert manualintegrate(1/sqrt(4*x**2 - 4), x) == log(8*x + 4*sqrt(4*x**2 - 4))/2
|
184 |
+
assert manualintegrate(1/sqrt(9*x**2 - 1), x) == log(18*x + 6*sqrt(9*x**2 - 1))/3
|
185 |
+
assert manualintegrate(1/sqrt(ra*x**2 - 4), x) == \
|
186 |
+
Piecewise((log(2*sqrt(ra)*sqrt(ra*x**2 - 4) + 2*ra*x)/sqrt(ra), Ne(ra, 0)), (-I*x/2, True))
|
187 |
+
assert manualintegrate(1/sqrt(-ra + 4*x**2), x) == \
|
188 |
+
Piecewise((asinh(2*x*sqrt(-1/ra))/2, ra < 0), (log(8*x + 4*sqrt(-ra + 4*x**2))/2, True))
|
189 |
+
|
190 |
+
# From https://www.wikiwand.com/en/List_of_integrals_of_inverse_trigonometric_functions
|
191 |
+
# asin
|
192 |
+
assert manualintegrate(asin(x), x) == x*asin(x) + sqrt(1 - x**2)
|
193 |
+
assert manualintegrate(asin(a*x), x) == Piecewise(((a*x*asin(a*x) + sqrt(-a**2*x**2 + 1))/a, Ne(a, 0)), (0, True))
|
194 |
+
assert manualintegrate(x*asin(a*x), x) == \
|
195 |
+
-a*Piecewise((-x*sqrt(-a**2*x**2 + 1)/(2*a**2) +
|
196 |
+
log(-2*a**2*x + 2*sqrt(-a**2)*sqrt(-a**2*x**2 + 1))/(2*a**2*sqrt(-a**2)), Ne(a**2, 0)),
|
197 |
+
(x**3/3, True))/2 + x**2*asin(a*x)/2
|
198 |
+
# acos
|
199 |
+
assert manualintegrate(acos(x), x) == x*acos(x) - sqrt(1 - x**2)
|
200 |
+
assert manualintegrate(acos(a*x), x) == Piecewise(((a*x*acos(a*x) - sqrt(-a**2*x**2 + 1))/a, Ne(a, 0)), (pi*x/2, True))
|
201 |
+
assert manualintegrate(x*acos(a*x), x) == \
|
202 |
+
a*Piecewise((-x*sqrt(-a**2*x**2 + 1)/(2*a**2) +
|
203 |
+
log(-2*a**2*x + 2*sqrt(-a**2)*sqrt(-a**2*x**2 + 1))/(2*a**2*sqrt(-a**2)), Ne(a**2, 0)),
|
204 |
+
(x**3/3, True))/2 + x**2*acos(a*x)/2
|
205 |
+
# atan
|
206 |
+
assert manualintegrate(atan(x), x) == x*atan(x) - log(x**2 + 1)/2
|
207 |
+
assert manualintegrate(atan(a*x), x) == Piecewise(((a*x*atan(a*x) - log(a**2*x**2 + 1)/2)/a, Ne(a, 0)), (0, True))
|
208 |
+
assert manualintegrate(x*atan(a*x), x) == -a*(x/a**2 - atan(x/sqrt(a**(-2)))/(a**4*sqrt(a**(-2))))/2 + x**2*atan(a*x)/2
|
209 |
+
# acsc
|
210 |
+
assert manualintegrate(acsc(x), x) == x*acsc(x) + Integral(1/(x*sqrt(1 - 1/x**2)), x)
|
211 |
+
assert manualintegrate(acsc(a*x), x) == x*acsc(a*x) + Integral(1/(x*sqrt(1 - 1/(a**2*x**2))), x)/a
|
212 |
+
assert manualintegrate(x*acsc(a*x), x) == x**2*acsc(a*x)/2 + Integral(1/sqrt(1 - 1/(a**2*x**2)), x)/(2*a)
|
213 |
+
# asec
|
214 |
+
assert manualintegrate(asec(x), x) == x*asec(x) - Integral(1/(x*sqrt(1 - 1/x**2)), x)
|
215 |
+
assert manualintegrate(asec(a*x), x) == x*asec(a*x) - Integral(1/(x*sqrt(1 - 1/(a**2*x**2))), x)/a
|
216 |
+
assert manualintegrate(x*asec(a*x), x) == x**2*asec(a*x)/2 - Integral(1/sqrt(1 - 1/(a**2*x**2)), x)/(2*a)
|
217 |
+
# acot
|
218 |
+
assert manualintegrate(acot(x), x) == x*acot(x) + log(x**2 + 1)/2
|
219 |
+
assert manualintegrate(acot(a*x), x) == Piecewise(((a*x*acot(a*x) + log(a**2*x**2 + 1)/2)/a, Ne(a, 0)), (pi*x/2, True))
|
220 |
+
assert manualintegrate(x*acot(a*x), x) == a*(x/a**2 - atan(x/sqrt(a**(-2)))/(a**4*sqrt(a**(-2))))/2 + x**2*acot(a*x)/2
|
221 |
+
|
222 |
+
# piecewise
|
223 |
+
assert manualintegrate(1/sqrt(ra-rb*x**2), x) == \
|
224 |
+
Piecewise((asin(x*sqrt(rb/ra))/sqrt(rb), And(-rb < 0, ra > 0)),
|
225 |
+
(asinh(x*sqrt(-rb/ra))/sqrt(-rb), And(-rb > 0, ra > 0)),
|
226 |
+
(log(-2*rb*x + 2*sqrt(-rb)*sqrt(ra - rb*x**2))/sqrt(-rb), Ne(rb, 0)),
|
227 |
+
(x/sqrt(ra), True))
|
228 |
+
assert manualintegrate(1/sqrt(ra + rb*x**2), x) == \
|
229 |
+
Piecewise((asin(x*sqrt(-rb/ra))/sqrt(-rb), And(ra > 0, rb < 0)),
|
230 |
+
(asinh(x*sqrt(rb/ra))/sqrt(rb), And(ra > 0, rb > 0)),
|
231 |
+
(log(2*sqrt(rb)*sqrt(ra + rb*x**2) + 2*rb*x)/sqrt(rb), Ne(rb, 0)),
|
232 |
+
(x/sqrt(ra), True))
|
233 |
+
|
234 |
+
|
235 |
+
def test_manualintegrate_trig_substitution():
|
236 |
+
assert manualintegrate(sqrt(16*x**2 - 9)/x, x) == \
|
237 |
+
Piecewise((sqrt(16*x**2 - 9) - 3*acos(3/(4*x)),
|
238 |
+
And(x < Rational(3, 4), x > Rational(-3, 4))))
|
239 |
+
assert manualintegrate(1/(x**4 * sqrt(25-x**2)), x) == \
|
240 |
+
Piecewise((-sqrt(-x**2/25 + 1)/(125*x) -
|
241 |
+
(-x**2/25 + 1)**(3*S.Half)/(15*x**3), And(x < 5, x > -5)))
|
242 |
+
assert manualintegrate(x**7/(49*x**2 + 1)**(3 * S.Half), x) == \
|
243 |
+
((49*x**2 + 1)**(5*S.Half)/28824005 -
|
244 |
+
(49*x**2 + 1)**(3*S.Half)/5764801 +
|
245 |
+
3*sqrt(49*x**2 + 1)/5764801 + 1/(5764801*sqrt(49*x**2 + 1)))
|
246 |
+
|
247 |
+
def test_manualintegrate_trivial_substitution():
|
248 |
+
assert manualintegrate((exp(x) - exp(-x))/x, x) == -Ei(-x) + Ei(x)
|
249 |
+
f = Function('f')
|
250 |
+
assert manualintegrate((f(x) - f(-x))/x, x) == \
|
251 |
+
-Integral(f(-x)/x, x) + Integral(f(x)/x, x)
|
252 |
+
|
253 |
+
|
254 |
+
def test_manualintegrate_rational():
|
255 |
+
assert manualintegrate(1/(4 - x**2), x) == -log(x - 2)/4 + log(x + 2)/4
|
256 |
+
assert manualintegrate(1/(-1 + x**2), x) == log(x - 1)/2 - log(x + 1)/2
|
257 |
+
|
258 |
+
|
259 |
+
def test_manualintegrate_special():
|
260 |
+
f, F = 4*exp(-x**2/3), 2*sqrt(3)*sqrt(pi)*erf(sqrt(3)*x/3)
|
261 |
+
assert_is_integral_of(f, F)
|
262 |
+
f, F = 3*exp(4*x**2), 3*sqrt(pi)*erfi(2*x)/4
|
263 |
+
assert_is_integral_of(f, F)
|
264 |
+
f, F = x**Rational(1, 3)*exp(-x/8), -16*uppergamma(Rational(4, 3), x/8)
|
265 |
+
assert_is_integral_of(f, F)
|
266 |
+
f, F = exp(2*x)/x, Ei(2*x)
|
267 |
+
assert_is_integral_of(f, F)
|
268 |
+
f, F = exp(1 + 2*x - x**2), sqrt(pi)*exp(2)*erf(x - 1)/2
|
269 |
+
assert_is_integral_of(f, F)
|
270 |
+
f = sin(x**2 + 4*x + 1)
|
271 |
+
F = (sqrt(2)*sqrt(pi)*(-sin(3)*fresnelc(sqrt(2)*(2*x + 4)/(2*sqrt(pi))) +
|
272 |
+
cos(3)*fresnels(sqrt(2)*(2*x + 4)/(2*sqrt(pi))))/2)
|
273 |
+
assert_is_integral_of(f, F)
|
274 |
+
f, F = cos(4*x**2), sqrt(2)*sqrt(pi)*fresnelc(2*sqrt(2)*x/sqrt(pi))/4
|
275 |
+
assert_is_integral_of(f, F)
|
276 |
+
f, F = sin(3*x + 2)/x, sin(2)*Ci(3*x) + cos(2)*Si(3*x)
|
277 |
+
assert_is_integral_of(f, F)
|
278 |
+
f, F = sinh(3*x - 2)/x, -sinh(2)*Chi(3*x) + cosh(2)*Shi(3*x)
|
279 |
+
assert_is_integral_of(f, F)
|
280 |
+
f, F = 5*cos(2*x - 3)/x, 5*cos(3)*Ci(2*x) + 5*sin(3)*Si(2*x)
|
281 |
+
assert_is_integral_of(f, F)
|
282 |
+
f, F = cosh(x/2)/x, Chi(x/2)
|
283 |
+
assert_is_integral_of(f, F)
|
284 |
+
f, F = cos(x**2)/x, Ci(x**2)/2
|
285 |
+
assert_is_integral_of(f, F)
|
286 |
+
f, F = 1/log(2*x + 1), li(2*x + 1)/2
|
287 |
+
assert_is_integral_of(f, F)
|
288 |
+
f, F = polylog(2, 5*x)/x, polylog(3, 5*x)
|
289 |
+
assert_is_integral_of(f, F)
|
290 |
+
f, F = 5/sqrt(3 - 2*sin(x)**2), 5*sqrt(3)*elliptic_f(x, Rational(2, 3))/3
|
291 |
+
assert_is_integral_of(f, F)
|
292 |
+
f, F = sqrt(4 + 9*sin(x)**2), 2*elliptic_e(x, Rational(-9, 4))
|
293 |
+
assert_is_integral_of(f, F)
|
294 |
+
|
295 |
+
|
296 |
+
def test_manualintegrate_derivative():
|
297 |
+
assert manualintegrate(pi * Derivative(x**2 + 2*x + 3), x) == \
|
298 |
+
pi * (x**2 + 2*x + 3)
|
299 |
+
assert manualintegrate(Derivative(x**2 + 2*x + 3, y), x) == \
|
300 |
+
Integral(Derivative(x**2 + 2*x + 3, y))
|
301 |
+
assert manualintegrate(Derivative(sin(x), x, x, x, y), x) == \
|
302 |
+
Derivative(sin(x), x, x, y)
|
303 |
+
|
304 |
+
|
305 |
+
def test_manualintegrate_Heaviside():
|
306 |
+
assert_is_integral_of(DiracDelta(3*x+2), Heaviside(3*x+2)/3)
|
307 |
+
assert_is_integral_of(DiracDelta(3*x, 0), Heaviside(3*x)/3)
|
308 |
+
assert manualintegrate(DiracDelta(a+b*x, 1), x) == \
|
309 |
+
Piecewise((DiracDelta(a + b*x)/b, Ne(b, 0)), (x*DiracDelta(a, 1), True))
|
310 |
+
assert_is_integral_of(DiracDelta(x/3-1, 2), 3*DiracDelta(x/3-1, 1))
|
311 |
+
assert manualintegrate(Heaviside(x), x) == x*Heaviside(x)
|
312 |
+
assert manualintegrate(x*Heaviside(2), x) == x**2/2
|
313 |
+
assert manualintegrate(x*Heaviside(-2), x) == 0
|
314 |
+
assert manualintegrate(x*Heaviside( x), x) == x**2*Heaviside( x)/2
|
315 |
+
assert manualintegrate(x*Heaviside(-x), x) == x**2*Heaviside(-x)/2
|
316 |
+
assert manualintegrate(Heaviside(2*x + 4), x) == (x+2)*Heaviside(2*x + 4)
|
317 |
+
assert manualintegrate(x*Heaviside(x), x) == x**2*Heaviside(x)/2
|
318 |
+
assert manualintegrate(Heaviside(x + 1)*Heaviside(1 - x)*x**2, x) == \
|
319 |
+
((x**3/3 + Rational(1, 3))*Heaviside(x + 1) - Rational(2, 3))*Heaviside(-x + 1)
|
320 |
+
|
321 |
+
y = Symbol('y')
|
322 |
+
assert manualintegrate(sin(7 + x)*Heaviside(3*x - 7), x) == \
|
323 |
+
(- cos(x + 7) + cos(Rational(28, 3)))*Heaviside(3*x - S(7))
|
324 |
+
|
325 |
+
assert manualintegrate(sin(y + x)*Heaviside(3*x - y), x) == \
|
326 |
+
(cos(y*Rational(4, 3)) - cos(x + y))*Heaviside(3*x - y)
|
327 |
+
|
328 |
+
|
329 |
+
def test_manualintegrate_orthogonal_poly():
|
330 |
+
n = symbols('n')
|
331 |
+
a, b = 7, Rational(5, 3)
|
332 |
+
polys = [jacobi(n, a, b, x), gegenbauer(n, a, x), chebyshevt(n, x),
|
333 |
+
chebyshevu(n, x), legendre(n, x), hermite(n, x), laguerre(n, x),
|
334 |
+
assoc_laguerre(n, a, x)]
|
335 |
+
for p in polys:
|
336 |
+
integral = manualintegrate(p, x)
|
337 |
+
for deg in [-2, -1, 0, 1, 3, 5, 8]:
|
338 |
+
# some accept negative "degree", some do not
|
339 |
+
try:
|
340 |
+
p_subbed = p.subs(n, deg)
|
341 |
+
except ValueError:
|
342 |
+
continue
|
343 |
+
assert (integral.subs(n, deg).diff(x) - p_subbed).expand() == 0
|
344 |
+
|
345 |
+
# can also integrate simple expressions with these polynomials
|
346 |
+
q = x*p.subs(x, 2*x + 1)
|
347 |
+
integral = manualintegrate(q, x)
|
348 |
+
for deg in [2, 4, 7]:
|
349 |
+
assert (integral.subs(n, deg).diff(x) - q.subs(n, deg)).expand() == 0
|
350 |
+
|
351 |
+
# cannot integrate with respect to any other parameter
|
352 |
+
t = symbols('t')
|
353 |
+
for i in range(len(p.args) - 1):
|
354 |
+
new_args = list(p.args)
|
355 |
+
new_args[i] = t
|
356 |
+
assert isinstance(manualintegrate(p.func(*new_args), t), Integral)
|
357 |
+
|
358 |
+
|
359 |
+
@slow
|
360 |
+
def test_issue_6799():
|
361 |
+
r, x, phi = map(Symbol, 'r x phi'.split())
|
362 |
+
n = Symbol('n', integer=True, positive=True)
|
363 |
+
|
364 |
+
integrand = (cos(n*(x-phi))*cos(n*x))
|
365 |
+
limits = (x, -pi, pi)
|
366 |
+
assert manualintegrate(integrand, x) == \
|
367 |
+
((n*x/2 + sin(2*n*x)/4)*cos(n*phi) - sin(n*phi)*cos(n*x)**2/2)/n
|
368 |
+
assert r * integrate(integrand, limits).trigsimp() / pi == r * cos(n * phi)
|
369 |
+
assert not integrate(integrand, limits).has(Dummy)
|
370 |
+
|
371 |
+
|
372 |
+
def test_issue_12251():
|
373 |
+
assert manualintegrate(x**y, x) == Piecewise(
|
374 |
+
(x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True))
|
375 |
+
|
376 |
+
|
377 |
+
def test_issue_3796():
|
378 |
+
assert manualintegrate(diff(exp(x + x**2)), x) == exp(x + x**2)
|
379 |
+
assert integrate(x * exp(x**4), x, risch=False) == -I*sqrt(pi)*erf(I*x**2)/4
|
380 |
+
|
381 |
+
|
382 |
+
def test_manual_true():
|
383 |
+
assert integrate(exp(x) * sin(x), x, manual=True) == \
|
384 |
+
(exp(x) * sin(x)) / 2 - (exp(x) * cos(x)) / 2
|
385 |
+
assert integrate(sin(x) * cos(x), x, manual=True) in \
|
386 |
+
[sin(x) ** 2 / 2, -cos(x)**2 / 2]
|
387 |
+
|
388 |
+
|
389 |
+
def test_issue_6746():
|
390 |
+
y = Symbol('y')
|
391 |
+
n = Symbol('n')
|
392 |
+
assert manualintegrate(y**x, x) == Piecewise(
|
393 |
+
(y**x/log(y), Ne(log(y), 0)), (x, True))
|
394 |
+
assert manualintegrate(y**(n*x), x) == Piecewise(
|
395 |
+
(Piecewise(
|
396 |
+
(y**(n*x)/log(y), Ne(log(y), 0)),
|
397 |
+
(n*x, True)
|
398 |
+
)/n, Ne(n, 0)),
|
399 |
+
(x, True))
|
400 |
+
assert manualintegrate(exp(n*x), x) == Piecewise(
|
401 |
+
(exp(n*x)/n, Ne(n, 0)), (x, True))
|
402 |
+
|
403 |
+
y = Symbol('y', positive=True)
|
404 |
+
assert manualintegrate((y + 1)**x, x) == (y + 1)**x/log(y + 1)
|
405 |
+
y = Symbol('y', zero=True)
|
406 |
+
assert manualintegrate((y + 1)**x, x) == x
|
407 |
+
y = Symbol('y')
|
408 |
+
n = Symbol('n', nonzero=True)
|
409 |
+
assert manualintegrate(y**(n*x), x) == Piecewise(
|
410 |
+
(y**(n*x)/log(y), Ne(log(y), 0)), (n*x, True))/n
|
411 |
+
y = Symbol('y', positive=True)
|
412 |
+
assert manualintegrate((y + 1)**(n*x), x) == \
|
413 |
+
(y + 1)**(n*x)/(n*log(y + 1))
|
414 |
+
a = Symbol('a', negative=True)
|
415 |
+
b = Symbol('b')
|
416 |
+
assert manualintegrate(1/(a + b*x**2), x) == atan(x/sqrt(a/b))/(b*sqrt(a/b))
|
417 |
+
b = Symbol('b', negative=True)
|
418 |
+
assert manualintegrate(1/(a + b*x**2), x) == \
|
419 |
+
atan(x/(sqrt(-a)*sqrt(-1/b)))/(b*sqrt(-a)*sqrt(-1/b))
|
420 |
+
assert manualintegrate(1/((x**a + y**b + 4)*sqrt(a*x**2 + 1)), x) == \
|
421 |
+
y**(-b)*Integral(x**(-a)/(y**(-b)*sqrt(a*x**2 + 1) +
|
422 |
+
x**(-a)*sqrt(a*x**2 + 1) + 4*x**(-a)*y**(-b)*sqrt(a*x**2 + 1)), x)
|
423 |
+
assert manualintegrate(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x) == \
|
424 |
+
Integral(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x)
|
425 |
+
assert manualintegrate(1/(x - a**x + x*b**2), x) == \
|
426 |
+
Integral(1/(-a**x + b**2*x + x), x)
|
427 |
+
|
428 |
+
|
429 |
+
@slow
|
430 |
+
def test_issue_2850():
|
431 |
+
assert manualintegrate(asin(x)*log(x), x) == -x*asin(x) - sqrt(-x**2 + 1) \
|
432 |
+
+ (x*asin(x) + sqrt(-x**2 + 1))*log(x) - Integral(sqrt(-x**2 + 1)/x, x)
|
433 |
+
assert manualintegrate(acos(x)*log(x), x) == -x*acos(x) + sqrt(-x**2 + 1) + \
|
434 |
+
(x*acos(x) - sqrt(-x**2 + 1))*log(x) + Integral(sqrt(-x**2 + 1)/x, x)
|
435 |
+
assert manualintegrate(atan(x)*log(x), x) == -x*atan(x) + (x*atan(x) - \
|
436 |
+
log(x**2 + 1)/2)*log(x) + log(x**2 + 1)/2 + Integral(log(x**2 + 1)/x, x)/2
|
437 |
+
|
438 |
+
|
439 |
+
def test_issue_9462():
|
440 |
+
assert manualintegrate(sin(2*x)*exp(x), x) == exp(x)*sin(2*x)/5 - 2*exp(x)*cos(2*x)/5
|
441 |
+
assert not integral_steps(sin(2*x)*exp(x), x).contains_dont_know()
|
442 |
+
assert manualintegrate((x - 3) / (x**2 - 2*x + 2)**2, x) == \
|
443 |
+
Integral(x/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x) \
|
444 |
+
- 3*Integral(1/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x)
|
445 |
+
|
446 |
+
|
447 |
+
def test_cyclic_parts():
|
448 |
+
f = cos(x)*exp(x/4)
|
449 |
+
F = 16*exp(x/4)*sin(x)/17 + 4*exp(x/4)*cos(x)/17
|
450 |
+
assert manualintegrate(f, x) == F and F.diff(x) == f
|
451 |
+
f = x*cos(x)*exp(x/4)
|
452 |
+
F = (x*(16*exp(x/4)*sin(x)/17 + 4*exp(x/4)*cos(x)/17) -
|
453 |
+
128*exp(x/4)*sin(x)/289 + 240*exp(x/4)*cos(x)/289)
|
454 |
+
assert manualintegrate(f, x) == F and F.diff(x) == f
|
455 |
+
|
456 |
+
|
457 |
+
@slow
|
458 |
+
def test_issue_10847_slow():
|
459 |
+
assert manualintegrate((4*x**4 + 4*x**3 + 16*x**2 + 12*x + 8)
|
460 |
+
/ (x**6 + 2*x**5 + 3*x**4 + 4*x**3 + 3*x**2 + 2*x + 1), x) == \
|
461 |
+
2*x/(x**2 + 1) + 3*atan(x) - 1/(x**2 + 1) - 3/(x + 1)
|
462 |
+
|
463 |
+
|
464 |
+
@slow
|
465 |
+
def test_issue_10847():
|
466 |
+
|
467 |
+
assert manualintegrate(x**2 / (x**2 - c), x) == c*atan(x/sqrt(-c))/sqrt(-c) + x
|
468 |
+
|
469 |
+
rc = Symbol('c', real=True)
|
470 |
+
assert manualintegrate(x**2 / (x**2 - rc), x) == \
|
471 |
+
rc*Piecewise((atan(x/sqrt(-rc))/sqrt(-rc), rc < 0),
|
472 |
+
((log(-sqrt(rc) + x) - log(sqrt(rc) + x))/(2*sqrt(rc)), True)) + x
|
473 |
+
|
474 |
+
assert manualintegrate(sqrt(x - y) * log(z / x), x) == \
|
475 |
+
4*y**Rational(3, 2)*atan(sqrt(x - y)/sqrt(y))/3 - 4*y*sqrt(x - y)/3 +\
|
476 |
+
2*(x - y)**Rational(3, 2)*log(z/x)/3 + 4*(x - y)**Rational(3, 2)/9
|
477 |
+
ry = Symbol('y', real=True)
|
478 |
+
rz = Symbol('z', real=True)
|
479 |
+
assert manualintegrate(sqrt(x - ry) * log(rz / x), x) == \
|
480 |
+
4*ry**2*Piecewise((atan(sqrt(x - ry)/sqrt(ry))/sqrt(ry), ry > 0),
|
481 |
+
((log(-sqrt(-ry) + sqrt(x - ry)) - log(sqrt(-ry) + sqrt(x - ry)))/(2*sqrt(-ry)), True))/3 \
|
482 |
+
- 4*ry*sqrt(x - ry)/3 + 2*(x - ry)**Rational(3, 2)*log(rz/x)/3 \
|
483 |
+
+ 4*(x - ry)**Rational(3, 2)/9
|
484 |
+
|
485 |
+
assert manualintegrate(sqrt(x) * log(x), x) == 2*x**Rational(3, 2)*log(x)/3 - 4*x**Rational(3, 2)/9
|
486 |
+
assert manualintegrate(sqrt(a*x + b) / x, x) == \
|
487 |
+
Piecewise((2*b*atan(sqrt(a*x + b)/sqrt(-b))/sqrt(-b) + 2*sqrt(a*x + b), Ne(a, 0)), (sqrt(b)*log(x), True))
|
488 |
+
ra = Symbol('a', real=True)
|
489 |
+
rb = Symbol('b', real=True)
|
490 |
+
assert manualintegrate(sqrt(ra*x + rb) / x, x) == \
|
491 |
+
Piecewise(
|
492 |
+
(-2*rb*Piecewise(
|
493 |
+
(-atan(sqrt(ra*x + rb)/sqrt(-rb))/sqrt(-rb), rb < 0),
|
494 |
+
(-I*(log(-sqrt(rb) + sqrt(ra*x + rb)) - log(sqrt(rb) + sqrt(ra*x + rb)))/(2*sqrt(-rb)), True)) +
|
495 |
+
2*sqrt(ra*x + rb), Ne(ra, 0)),
|
496 |
+
(sqrt(rb)*log(x), True))
|
497 |
+
|
498 |
+
assert expand(manualintegrate(sqrt(ra*x + rb) / (x + rc), x)) == \
|
499 |
+
Piecewise((-2*ra*rc*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), ra*rc - rb > 0),
|
500 |
+
(log(-sqrt(-ra*rc + rb) + sqrt(ra*x + rb))/(2*sqrt(-ra*rc + rb)) -
|
501 |
+
log(sqrt(-ra*rc + rb) + sqrt(ra*x + rb))/(2*sqrt(-ra*rc + rb)), True)) +
|
502 |
+
2*rb*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), ra*rc - rb > 0),
|
503 |
+
(log(-sqrt(-ra*rc + rb) + sqrt(ra*x + rb))/(2*sqrt(-ra*rc + rb)) -
|
504 |
+
log(sqrt(-ra*rc + rb) + sqrt(ra*x + rb))/(2*sqrt(-ra*rc + rb)), True)) +
|
505 |
+
2*sqrt(ra*x + rb), Ne(ra, 0)), (sqrt(rb)*log(rc + x), True))
|
506 |
+
|
507 |
+
assert manualintegrate(sqrt(2*x + 3) / (x + 1), x) == 2*sqrt(2*x + 3) - log(sqrt(2*x + 3) + 1) + log(sqrt(2*x + 3) - 1)
|
508 |
+
assert manualintegrate(sqrt(2*x + 3) / 2 * x, x) == (2*x + 3)**Rational(5, 2)/20 - (2*x + 3)**Rational(3, 2)/4
|
509 |
+
assert manualintegrate(x**Rational(3,2) * log(x), x) == 2*x**Rational(5,2)*log(x)/5 - 4*x**Rational(5,2)/25
|
510 |
+
assert manualintegrate(x**(-3) * log(x), x) == -log(x)/(2*x**2) - 1/(4*x**2)
|
511 |
+
assert manualintegrate(log(y)/(y**2*(1 - 1/y)), y) == \
|
512 |
+
log(y)*log(-1 + 1/y) - Integral(log(-1 + 1/y)/y, y)
|
513 |
+
|
514 |
+
|
515 |
+
def test_issue_12899():
|
516 |
+
assert manualintegrate(f(x,y).diff(x),y) == Integral(Derivative(f(x,y),x),y)
|
517 |
+
assert manualintegrate(f(x,y).diff(y).diff(x),y) == Derivative(f(x,y),x)
|
518 |
+
|
519 |
+
|
520 |
+
def test_constant_independent_of_symbol():
|
521 |
+
assert manualintegrate(Integral(y, (x, 1, 2)), x) == \
|
522 |
+
x*Integral(y, (x, 1, 2))
|
523 |
+
|
524 |
+
|
525 |
+
def test_issue_12641():
|
526 |
+
assert manualintegrate(sin(2*x), x) == -cos(2*x)/2
|
527 |
+
assert manualintegrate(cos(x)*sin(2*x), x) == -2*cos(x)**3/3
|
528 |
+
assert manualintegrate((sin(2*x)*cos(x))/(1 + cos(x)), x) == \
|
529 |
+
-2*log(cos(x) + 1) - cos(x)**2 + 2*cos(x)
|
530 |
+
|
531 |
+
|
532 |
+
@slow
|
533 |
+
def test_issue_13297():
|
534 |
+
assert manualintegrate(sin(x) * cos(x)**5, x) == -cos(x)**6 / 6
|
535 |
+
|
536 |
+
|
537 |
+
def test_issue_14470():
|
538 |
+
assert_is_integral_of(1/(x*sqrt(x + 1)), log(sqrt(x + 1) - 1) - log(sqrt(x + 1) + 1))
|
539 |
+
|
540 |
+
|
541 |
+
@slow
|
542 |
+
def test_issue_9858():
|
543 |
+
assert manualintegrate(exp(x)*cos(exp(x)), x) == sin(exp(x))
|
544 |
+
assert manualintegrate(exp(2*x)*cos(exp(x)), x) == \
|
545 |
+
exp(x)*sin(exp(x)) + cos(exp(x))
|
546 |
+
res = manualintegrate(exp(10*x)*sin(exp(x)), x)
|
547 |
+
assert not res.has(Integral)
|
548 |
+
assert res.diff(x) == exp(10*x)*sin(exp(x))
|
549 |
+
# an example with many similar integrations by parts
|
550 |
+
assert manualintegrate(sum([x*exp(k*x) for k in range(1, 8)]), x) == (
|
551 |
+
x*exp(7*x)/7 + x*exp(6*x)/6 + x*exp(5*x)/5 + x*exp(4*x)/4 +
|
552 |
+
x*exp(3*x)/3 + x*exp(2*x)/2 + x*exp(x) - exp(7*x)/49 -exp(6*x)/36 -
|
553 |
+
exp(5*x)/25 - exp(4*x)/16 - exp(3*x)/9 - exp(2*x)/4 - exp(x))
|
554 |
+
|
555 |
+
|
556 |
+
def test_issue_8520():
|
557 |
+
assert manualintegrate(x/(x**4 + 1), x) == atan(x**2)/2
|
558 |
+
assert manualintegrate(x**2/(x**6 + 25), x) == atan(x**3/5)/15
|
559 |
+
f = x/(9*x**4 + 4)**2
|
560 |
+
assert manualintegrate(f, x).diff(x).factor() == f
|
561 |
+
|
562 |
+
|
563 |
+
def test_manual_subs():
|
564 |
+
x, y = symbols('x y')
|
565 |
+
expr = log(x) + exp(x)
|
566 |
+
# if log(x) is y, then exp(y) is x
|
567 |
+
assert manual_subs(expr, log(x), y) == y + exp(exp(y))
|
568 |
+
# if exp(x) is y, then log(y) need not be x
|
569 |
+
assert manual_subs(expr, exp(x), y) == log(x) + y
|
570 |
+
|
571 |
+
raises(ValueError, lambda: manual_subs(expr, x))
|
572 |
+
raises(ValueError, lambda: manual_subs(expr, exp(x), x, y))
|
573 |
+
|
574 |
+
|
575 |
+
@slow
|
576 |
+
def test_issue_15471():
|
577 |
+
f = log(x)*cos(log(x))/x**Rational(3, 4)
|
578 |
+
F = -128*x**Rational(1, 4)*sin(log(x))/289 + 240*x**Rational(1, 4)*cos(log(x))/289 + (16*x**Rational(1, 4)*sin(log(x))/17 + 4*x**Rational(1, 4)*cos(log(x))/17)*log(x)
|
579 |
+
assert_is_integral_of(f, F)
|
580 |
+
|
581 |
+
|
582 |
+
def test_quadratic_denom():
|
583 |
+
f = (5*x + 2)/(3*x**2 - 2*x + 8)
|
584 |
+
assert manualintegrate(f, x) == 5*log(3*x**2 - 2*x + 8)/6 + 11*sqrt(23)*atan(3*sqrt(23)*(x - Rational(1, 3))/23)/69
|
585 |
+
g = 3/(2*x**2 + 3*x + 1)
|
586 |
+
assert manualintegrate(g, x) == 3*log(4*x + 2) - 3*log(4*x + 4)
|
587 |
+
|
588 |
+
def test_issue_22757():
|
589 |
+
assert manualintegrate(sin(x), y) == y * sin(x)
|
590 |
+
|
591 |
+
|
592 |
+
def test_issue_23348():
|
593 |
+
steps = integral_steps(tan(x), x)
|
594 |
+
constant_times_step = steps.substep.substep
|
595 |
+
assert constant_times_step.integrand == constant_times_step.constant * constant_times_step.other
|
596 |
+
|
597 |
+
|
598 |
+
def test_issue_23566():
|
599 |
+
i = Integral(1/sqrt(x**2 - 1), (x, -2, -1)).doit(manual=True)
|
600 |
+
assert i == -log(4 - 2*sqrt(3)) + log(2)
|
601 |
+
assert str(i.n()) == '1.31695789692482'
|
602 |
+
|
603 |
+
|
604 |
+
def test_nested_pow():
|
605 |
+
assert_is_integral_of(sqrt(x**2), x*sqrt(x**2)/2)
|
606 |
+
assert_is_integral_of(sqrt(x**(S(5)/3)), 6*x*sqrt(x**(S(5)/3))/11)
|
607 |
+
assert_is_integral_of(1/sqrt(x**2), x*log(x)/sqrt(x**2))
|
608 |
+
assert_is_integral_of(x*sqrt(x**(-4)), x**2*sqrt(x**-4)*log(x))
|
609 |
+
f = (c*(a+b*x)**d)**e
|
610 |
+
F1 = (c*(a + b*x)**d)**e*(a/b + x)/(d*e + 1)
|
611 |
+
F2 = (c*(a + b*x)**d)**e*(a/b + x)*log(a/b + x)
|
612 |
+
assert manualintegrate(f, x) == \
|
613 |
+
Piecewise((Piecewise((F1, Ne(d*e, -1)), (F2, True)), Ne(b, 0)), (x*(a**d*c)**e, True))
|
614 |
+
assert F1.diff(x).equals(f)
|
615 |
+
assert F2.diff(x).subs(d*e, -1).equals(f)
|
616 |
+
|
617 |
+
|
618 |
+
def test_manualintegrate_sqrt_linear():
|
619 |
+
assert_is_integral_of((5*x**3+4)/sqrt(2+3*x),
|
620 |
+
10*(3*x + 2)**(S(7)/2)/567 - 4*(3*x + 2)**(S(5)/2)/27 +
|
621 |
+
40*(3*x + 2)**(S(3)/2)/81 + 136*sqrt(3*x + 2)/81)
|
622 |
+
assert manualintegrate(x/sqrt(a+b*x)**3, x) == \
|
623 |
+
Piecewise((Mul(2, b**-2, a/sqrt(a + b*x) + sqrt(a + b*x)), Ne(b, 0)), (x**2/(2*a**(S(3)/2)), True))
|
624 |
+
assert_is_integral_of((sqrt(3*x+3)+1)/((2*x+2)**(1/S(3))+1),
|
625 |
+
3*sqrt(6)*(2*x + 2)**(S(7)/6)/14 - 3*sqrt(6)*(2*x + 2)**(S(5)/6)/10 -
|
626 |
+
3*sqrt(6)*(2*x + 2)**(S.One/6)/2 + 3*(2*x + 2)**(S(2)/3)/4 - 3*(2*x + 2)**(S.One/3)/2 +
|
627 |
+
sqrt(6)*sqrt(2*x + 2)/2 + 3*log((2*x + 2)**(S.One/3) + 1)/2 +
|
628 |
+
3*sqrt(6)*atan((2*x + 2)**(S.One/6))/2)
|
629 |
+
assert_is_integral_of(sqrt(x+sqrt(x)),
|
630 |
+
2*sqrt(sqrt(x) + x)*(sqrt(x)/12 + x/3 - S(1)/8) + log(2*sqrt(x) + 2*sqrt(sqrt(x) + x) + 1)/8)
|
631 |
+
assert_is_integral_of(sqrt(2*x+3+sqrt(4*x+5))**3,
|
632 |
+
sqrt(2*x + sqrt(4*x + 5) + 3) *
|
633 |
+
(9*x/10 + 11*(4*x + 5)**(S(3)/2)/40 + sqrt(4*x + 5)/40 + (4*x + 5)**2/10 + S(11)/10)/2)
|
634 |
+
|
635 |
+
|
636 |
+
def test_manualintegrate_sqrt_quadratic():
|
637 |
+
assert_is_integral_of(1/sqrt((x - I)**2-1), log(2*x + 2*sqrt(x**2 - 2*I*x - 2) - 2*I))
|
638 |
+
assert_is_integral_of(1/sqrt(3*x**2+4*x+5), sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/3)
|
639 |
+
assert_is_integral_of(1/sqrt(-3*x**2+4*x+5), sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/3)
|
640 |
+
assert_is_integral_of(1/sqrt(3*x**2+4*x-5), sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/3)
|
641 |
+
assert_is_integral_of(1/sqrt(4*x**2-4*x+1), (x - S.Half)*log(x - S.Half)/(2*sqrt((x - S.Half)**2)))
|
642 |
+
assert manualintegrate(1/sqrt(a+b*x+c*x**2), x) == \
|
643 |
+
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0) & Ne(a - b**2/(4*c), 0)),
|
644 |
+
((b/(2*c) + x)*log(b/(2*c) + x)/sqrt(c*(b/(2*c) + x)**2), Ne(c, 0)),
|
645 |
+
(2*sqrt(a + b*x)/b, Ne(b, 0)), (x/sqrt(a), True))
|
646 |
+
|
647 |
+
assert_is_integral_of((7*x+6)/sqrt(3*x**2+4*x+5),
|
648 |
+
7*sqrt(3*x**2 + 4*x + 5)/3 + 4*sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/9)
|
649 |
+
assert_is_integral_of((7*x+6)/sqrt(-3*x**2+4*x+5),
|
650 |
+
-7*sqrt(-3*x**2 + 4*x + 5)/3 + 32*sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/9)
|
651 |
+
assert_is_integral_of((7*x+6)/sqrt(3*x**2+4*x-5),
|
652 |
+
7*sqrt(3*x**2 + 4*x - 5)/3 + 4*sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/9)
|
653 |
+
assert manualintegrate((d+e*x)/sqrt(a+b*x+c*x**2), x) == \
|
654 |
+
Piecewise(((-b*e/(2*c) + d) *
|
655 |
+
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(a - b**2/(4*c), 0)),
|
656 |
+
((b/(2*c) + x)*log(b/(2*c) + x)/sqrt(c*(b/(2*c) + x)**2), True)) +
|
657 |
+
e*sqrt(a + b*x + c*x**2)/c, Ne(c, 0)),
|
658 |
+
((2*d*sqrt(a + b*x) + 2*e*(-a*sqrt(a + b*x) + (a + b*x)**(S(3)/2)/3)/b)/b, Ne(b, 0)),
|
659 |
+
((d*x + e*x**2/2)/sqrt(a), True))
|
660 |
+
|
661 |
+
assert manualintegrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2), x) == \
|
662 |
+
sqrt(x**2 - 3*x + 2)*(x**2 + 13*x/4 + S(101)/8) + 135*log(2*x + 2*sqrt(x**2 - 3*x + 2) - 3)/16
|
663 |
+
|
664 |
+
assert_is_integral_of(sqrt(53225*x**2-66732*x+23013),
|
665 |
+
(x/2 - S(16683)/53225)*sqrt(53225*x**2 - 66732*x + 23013) +
|
666 |
+
111576969*sqrt(2129)*asinh(53225*x/10563 - S(11122)/3521)/1133160250)
|
667 |
+
assert manualintegrate(sqrt(a+c*x**2), x) == \
|
668 |
+
Piecewise((a*Piecewise((log(2*sqrt(c)*sqrt(a + c*x**2) + 2*c*x)/sqrt(c), Ne(a, 0)),
|
669 |
+
(x*log(x)/sqrt(c*x**2), True))/2 + x*sqrt(a + c*x**2)/2, Ne(c, 0)),
|
670 |
+
(sqrt(a)*x, True))
|
671 |
+
assert manualintegrate(sqrt(a+b*x+c*x**2), x) == \
|
672 |
+
Piecewise(((a/2 - b**2/(8*c)) *
|
673 |
+
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(a - b**2/(4*c), 0)),
|
674 |
+
((b/(2*c) + x)*log(b/(2*c) + x)/sqrt(c*(b/(2*c) + x)**2), True)) +
|
675 |
+
(b/(4*c) + x/2)*sqrt(a + b*x + c*x**2), Ne(c, 0)),
|
676 |
+
(2*(a + b*x)**(S(3)/2)/(3*b), Ne(b, 0)),
|
677 |
+
(sqrt(a)*x, True))
|
678 |
+
|
679 |
+
assert_is_integral_of(x*sqrt(x**2+2*x+4),
|
680 |
+
(x**2/3 + x/6 + S(5)/6)*sqrt(x**2 + 2*x + 4) - 3*asinh(sqrt(3)*(x + 1)/3)/2)
|
681 |
+
|
682 |
+
|
683 |
+
def test_mul_pow_derivative():
|
684 |
+
assert_is_integral_of(x*sec(x)*tan(x), x*sec(x) - log(tan(x) + sec(x)))
|
685 |
+
assert_is_integral_of(x*sec(x)**2, x*tan(x) + log(cos(x)))
|
686 |
+
assert_is_integral_of(x**3*Derivative(f(x), (x, 4)),
|
687 |
+
x**3*Derivative(f(x), (x, 3)) - 3*x**2*Derivative(f(x), (x, 2)) +
|
688 |
+
6*x*Derivative(f(x), x) - 6*f(x))
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_meijerint.py
ADDED
@@ -0,0 +1,764 @@
|
|
|
|
|
|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
2 |
+
from sympy.core.numbers import (I, Rational, oo, pi)
|
3 |
+
from sympy.core.singleton import S
|
4 |
+
from sympy.core.sorting import default_sort_key
|
5 |
+
from sympy.functions.elementary.complexes import Abs, arg, re, unpolarify
|
6 |
+
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
|
7 |
+
from sympy.functions.elementary.hyperbolic import cosh, acosh
|
8 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
9 |
+
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
|
10 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, sinc, asin)
|
11 |
+
from sympy.functions.special.error_functions import (erf, erfc)
|
12 |
+
from sympy.functions.special.gamma_functions import (gamma, polygamma)
|
13 |
+
from sympy.functions.special.hyper import (hyper, meijerg)
|
14 |
+
from sympy.integrals.integrals import (Integral, integrate)
|
15 |
+
from sympy.simplify.hyperexpand import hyperexpand
|
16 |
+
from sympy.simplify.simplify import simplify
|
17 |
+
from sympy.integrals.meijerint import (_rewrite_single, _rewrite1,
|
18 |
+
meijerint_indefinite, _inflate_g, _create_lookup_table,
|
19 |
+
meijerint_definite, meijerint_inversion)
|
20 |
+
from sympy.testing.pytest import slow
|
21 |
+
from sympy.core.random import (verify_numerically,
|
22 |
+
random_complex_number as randcplx)
|
23 |
+
from sympy.abc import x, y, a, b, c, d, s, t, z
|
24 |
+
|
25 |
+
|
26 |
+
def test_rewrite_single():
|
27 |
+
def t(expr, c, m):
|
28 |
+
e = _rewrite_single(meijerg([a], [b], [c], [d], expr), x)
|
29 |
+
assert e is not None
|
30 |
+
assert isinstance(e[0][0][2], meijerg)
|
31 |
+
assert e[0][0][2].argument.as_coeff_mul(x) == (c, (m,))
|
32 |
+
|
33 |
+
def tn(expr):
|
34 |
+
assert _rewrite_single(meijerg([a], [b], [c], [d], expr), x) is None
|
35 |
+
|
36 |
+
t(x, 1, x)
|
37 |
+
t(x**2, 1, x**2)
|
38 |
+
t(x**2 + y*x**2, y + 1, x**2)
|
39 |
+
tn(x**2 + x)
|
40 |
+
tn(x**y)
|
41 |
+
|
42 |
+
def u(expr, x):
|
43 |
+
from sympy.core.add import Add
|
44 |
+
r = _rewrite_single(expr, x)
|
45 |
+
e = Add(*[res[0]*res[2] for res in r[0]]).replace(
|
46 |
+
exp_polar, exp) # XXX Hack?
|
47 |
+
assert verify_numerically(e, expr, x)
|
48 |
+
|
49 |
+
u(exp(-x)*sin(x), x)
|
50 |
+
|
51 |
+
# The following has stopped working because hyperexpand changed slightly.
|
52 |
+
# It is probably not worth fixing
|
53 |
+
#u(exp(-x)*sin(x)*cos(x), x)
|
54 |
+
|
55 |
+
# This one cannot be done numerically, since it comes out as a g-function
|
56 |
+
# of argument 4*pi
|
57 |
+
# NOTE This also tests a bug in inverse mellin transform (which used to
|
58 |
+
# turn exp(4*pi*I*t) into a factor of exp(4*pi*I)**t instead of
|
59 |
+
# exp_polar).
|
60 |
+
#u(exp(x)*sin(x), x)
|
61 |
+
assert _rewrite_single(exp(x)*sin(x), x) == \
|
62 |
+
([(-sqrt(2)/(2*sqrt(pi)), 0,
|
63 |
+
meijerg(((Rational(-1, 2), 0, Rational(1, 4), S.Half, Rational(3, 4)), (1,)),
|
64 |
+
((), (Rational(-1, 2), 0)), 64*exp_polar(-4*I*pi)/x**4))], True)
|
65 |
+
|
66 |
+
|
67 |
+
def test_rewrite1():
|
68 |
+
assert _rewrite1(x**3*meijerg([a], [b], [c], [d], x**2 + y*x**2)*5, x) == \
|
69 |
+
(5, x**3, [(1, 0, meijerg([a], [b], [c], [d], x**2*(y + 1)))], True)
|
70 |
+
|
71 |
+
|
72 |
+
def test_meijerint_indefinite_numerically():
|
73 |
+
def t(fac, arg):
|
74 |
+
g = meijerg([a], [b], [c], [d], arg)*fac
|
75 |
+
subs = {a: randcplx()/10, b: randcplx()/10 + I,
|
76 |
+
c: randcplx(), d: randcplx()}
|
77 |
+
integral = meijerint_indefinite(g, x)
|
78 |
+
assert integral is not None
|
79 |
+
assert verify_numerically(g.subs(subs), integral.diff(x).subs(subs), x)
|
80 |
+
t(1, x)
|
81 |
+
t(2, x)
|
82 |
+
t(1, 2*x)
|
83 |
+
t(1, x**2)
|
84 |
+
t(5, x**S('3/2'))
|
85 |
+
t(x**3, x)
|
86 |
+
t(3*x**S('3/2'), 4*x**S('7/3'))
|
87 |
+
|
88 |
+
|
89 |
+
def test_meijerint_definite():
|
90 |
+
v, b = meijerint_definite(x, x, 0, 0)
|
91 |
+
assert v.is_zero and b is True
|
92 |
+
v, b = meijerint_definite(x, x, oo, oo)
|
93 |
+
assert v.is_zero and b is True
|
94 |
+
|
95 |
+
|
96 |
+
def test_inflate():
|
97 |
+
subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(),
|
98 |
+
d: randcplx(), y: randcplx()/10}
|
99 |
+
|
100 |
+
def t(a, b, arg, n):
|
101 |
+
from sympy.core.mul import Mul
|
102 |
+
m1 = meijerg(a, b, arg)
|
103 |
+
m2 = Mul(*_inflate_g(m1, n))
|
104 |
+
# NOTE: (the random number)**9 must still be on the principal sheet.
|
105 |
+
# Thus make b&d small to create random numbers of small imaginary part.
|
106 |
+
return verify_numerically(m1.subs(subs), m2.subs(subs), x, b=0.1, d=-0.1)
|
107 |
+
assert t([[a], [b]], [[c], [d]], x, 3)
|
108 |
+
assert t([[a, y], [b]], [[c], [d]], x, 3)
|
109 |
+
assert t([[a], [b]], [[c, y], [d]], 2*x**3, 3)
|
110 |
+
|
111 |
+
|
112 |
+
def test_recursive():
|
113 |
+
from sympy.core.symbol import symbols
|
114 |
+
a, b, c = symbols('a b c', positive=True)
|
115 |
+
r = exp(-(x - a)**2)*exp(-(x - b)**2)
|
116 |
+
e = integrate(r, (x, 0, oo), meijerg=True)
|
117 |
+
assert simplify(e.expand()) == (
|
118 |
+
sqrt(2)*sqrt(pi)*(
|
119 |
+
(erf(sqrt(2)*(a + b)/2) + 1)*exp(-a**2/2 + a*b - b**2/2))/4)
|
120 |
+
e = integrate(exp(-(x - a)**2)*exp(-(x - b)**2)*exp(c*x), (x, 0, oo), meijerg=True)
|
121 |
+
assert simplify(e) == (
|
122 |
+
sqrt(2)*sqrt(pi)*(erf(sqrt(2)*(2*a + 2*b + c)/4) + 1)*exp(-a**2 - b**2
|
123 |
+
+ (2*a + 2*b + c)**2/8)/4)
|
124 |
+
assert simplify(integrate(exp(-(x - a - b - c)**2), (x, 0, oo), meijerg=True)) == \
|
125 |
+
sqrt(pi)/2*(1 + erf(a + b + c))
|
126 |
+
assert simplify(integrate(exp(-(x + a + b + c)**2), (x, 0, oo), meijerg=True)) == \
|
127 |
+
sqrt(pi)/2*(1 - erf(a + b + c))
|
128 |
+
|
129 |
+
|
130 |
+
@slow
|
131 |
+
def test_meijerint():
|
132 |
+
from sympy.core.function import expand
|
133 |
+
from sympy.core.symbol import symbols
|
134 |
+
s, t, mu = symbols('s t mu', real=True)
|
135 |
+
assert integrate(meijerg([], [], [0], [], s*t)
|
136 |
+
*meijerg([], [], [mu/2], [-mu/2], t**2/4),
|
137 |
+
(t, 0, oo)).is_Piecewise
|
138 |
+
s = symbols('s', positive=True)
|
139 |
+
assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \
|
140 |
+
gamma(s + 1)
|
141 |
+
assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo),
|
142 |
+
meijerg=True) == gamma(s + 1)
|
143 |
+
assert isinstance(integrate(x**s*meijerg([[], []], [[0], []], x),
|
144 |
+
(x, 0, oo), meijerg=False),
|
145 |
+
Integral)
|
146 |
+
|
147 |
+
assert meijerint_indefinite(exp(x), x) == exp(x)
|
148 |
+
|
149 |
+
# TODO what simplifications should be done automatically?
|
150 |
+
# This tests "extra case" for antecedents_1.
|
151 |
+
a, b = symbols('a b', positive=True)
|
152 |
+
assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \
|
153 |
+
b**(a + 1)/(a + 1)
|
154 |
+
|
155 |
+
# This tests various conditions and expansions:
|
156 |
+
assert meijerint_definite((x + 1)**3*exp(-x), x, 0, oo) == (16, True)
|
157 |
+
|
158 |
+
# Again, how about simplifications?
|
159 |
+
sigma, mu = symbols('sigma mu', positive=True)
|
160 |
+
i, c = meijerint_definite(exp(-((x - mu)/(2*sigma))**2), x, 0, oo)
|
161 |
+
assert simplify(i) == sqrt(pi)*sigma*(2 - erfc(mu/(2*sigma)))
|
162 |
+
assert c == True
|
163 |
+
|
164 |
+
i, _ = meijerint_definite(exp(-mu*x)*exp(sigma*x), x, 0, oo)
|
165 |
+
# TODO it would be nice to test the condition
|
166 |
+
assert simplify(i) == 1/(mu - sigma)
|
167 |
+
|
168 |
+
# Test substitutions to change limits
|
169 |
+
assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True)
|
170 |
+
# Note: causes a NaN in _check_antecedents
|
171 |
+
assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1
|
172 |
+
assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \
|
173 |
+
1 - exp(-exp(I*arg(x))*abs(x))
|
174 |
+
|
175 |
+
# Test -oo to oo
|
176 |
+
assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True)
|
177 |
+
assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True)
|
178 |
+
assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \
|
179 |
+
(sqrt(pi)/2, True)
|
180 |
+
assert meijerint_definite(exp(-abs(2*x - 3)), x, -oo, oo) == (1, True)
|
181 |
+
assert meijerint_definite(exp(-((x - mu)/sigma)**2/2)/sqrt(2*pi*sigma**2),
|
182 |
+
x, -oo, oo) == (1, True)
|
183 |
+
assert meijerint_definite(sinc(x)**2, x, -oo, oo) == (pi, True)
|
184 |
+
|
185 |
+
# Test one of the extra conditions for 2 g-functinos
|
186 |
+
assert meijerint_definite(exp(-x)*sin(x), x, 0, oo) == (S.Half, True)
|
187 |
+
|
188 |
+
# Test a bug
|
189 |
+
def res(n):
|
190 |
+
return (1/(1 + x**2)).diff(x, n).subs(x, 1)*(-1)**n
|
191 |
+
for n in range(6):
|
192 |
+
assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \
|
193 |
+
res(n)
|
194 |
+
|
195 |
+
# This used to test trigexpand... now it is done by linear substitution
|
196 |
+
assert simplify(integrate(exp(-x)*sin(x + a), (x, 0, oo), meijerg=True)
|
197 |
+
) == sqrt(2)*sin(a + pi/4)/2
|
198 |
+
|
199 |
+
# Test the condition 14 from prudnikov.
|
200 |
+
# (This is besselj*besselj in disguise, to stop the product from being
|
201 |
+
# recognised in the tables.)
|
202 |
+
a, b, s = symbols('a b s')
|
203 |
+
assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4)
|
204 |
+
*meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo
|
205 |
+
) == (
|
206 |
+
(4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
|
207 |
+
/(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
|
208 |
+
*gamma(a/2 + b/2 - s + 1)),
|
209 |
+
(re(s) < 1) & (re(s) < S(1)/2) & (re(a)/2 + re(b)/2 + re(s) > 0)))
|
210 |
+
|
211 |
+
# test a bug
|
212 |
+
assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \
|
213 |
+
Integral(sin(x**a)*sin(x**b), (x, 0, oo))
|
214 |
+
|
215 |
+
# test better hyperexpand
|
216 |
+
assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \
|
217 |
+
(sqrt(pi)*polygamma(0, S.Half)/4).expand()
|
218 |
+
|
219 |
+
# Test hyperexpand bug.
|
220 |
+
from sympy.functions.special.gamma_functions import lowergamma
|
221 |
+
n = symbols('n', integer=True)
|
222 |
+
assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \
|
223 |
+
lowergamma(n + 1, x)
|
224 |
+
|
225 |
+
# Test a bug with argument 1/x
|
226 |
+
alpha = symbols('alpha', positive=True)
|
227 |
+
assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \
|
228 |
+
(sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S.Half,
|
229 |
+
alpha/2 + 1)), ((0, 0, S.Half), (Rational(-1, 2),)), alpha**2/16)/4, True)
|
230 |
+
|
231 |
+
# test a bug related to 3016
|
232 |
+
a, s = symbols('a s', positive=True)
|
233 |
+
assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \
|
234 |
+
a**(-s/2 - S.Half)*((-1)**s + 1)*gamma(s/2 + S.Half)/2
|
235 |
+
|
236 |
+
|
237 |
+
def test_bessel():
|
238 |
+
from sympy.functions.special.bessel import (besseli, besselj)
|
239 |
+
assert simplify(integrate(besselj(a, z)*besselj(b, z)/z, (z, 0, oo),
|
240 |
+
meijerg=True, conds='none')) == \
|
241 |
+
2*sin(pi*(a/2 - b/2))/(pi*(a - b)*(a + b))
|
242 |
+
assert simplify(integrate(besselj(a, z)*besselj(a, z)/z, (z, 0, oo),
|
243 |
+
meijerg=True, conds='none')) == 1/(2*a)
|
244 |
+
|
245 |
+
# TODO more orthogonality integrals
|
246 |
+
|
247 |
+
assert simplify(integrate(sin(z*x)*(x**2 - 1)**(-(y + S.Half)),
|
248 |
+
(x, 1, oo), meijerg=True, conds='none')
|
249 |
+
*2/((z/2)**y*sqrt(pi)*gamma(S.Half - y))) == \
|
250 |
+
besselj(y, z)
|
251 |
+
|
252 |
+
# Werner Rosenheinrich
|
253 |
+
# SOME INDEFINITE INTEGRALS OF BESSEL FUNCTIONS
|
254 |
+
|
255 |
+
assert integrate(x*besselj(0, x), x, meijerg=True) == x*besselj(1, x)
|
256 |
+
assert integrate(x*besseli(0, x), x, meijerg=True) == x*besseli(1, x)
|
257 |
+
# TODO can do higher powers, but come out as high order ... should they be
|
258 |
+
# reduced to order 0, 1?
|
259 |
+
assert integrate(besselj(1, x), x, meijerg=True) == -besselj(0, x)
|
260 |
+
assert integrate(besselj(1, x)**2/x, x, meijerg=True) == \
|
261 |
+
-(besselj(0, x)**2 + besselj(1, x)**2)/2
|
262 |
+
# TODO more besseli when tables are extended or recursive mellin works
|
263 |
+
assert integrate(besselj(0, x)**2/x**2, x, meijerg=True) == \
|
264 |
+
-2*x*besselj(0, x)**2 - 2*x*besselj(1, x)**2 \
|
265 |
+
+ 2*besselj(0, x)*besselj(1, x) - besselj(0, x)**2/x
|
266 |
+
assert integrate(besselj(0, x)*besselj(1, x), x, meijerg=True) == \
|
267 |
+
-besselj(0, x)**2/2
|
268 |
+
assert integrate(x**2*besselj(0, x)*besselj(1, x), x, meijerg=True) == \
|
269 |
+
x**2*besselj(1, x)**2/2
|
270 |
+
assert integrate(besselj(0, x)*besselj(1, x)/x, x, meijerg=True) == \
|
271 |
+
(x*besselj(0, x)**2 + x*besselj(1, x)**2 -
|
272 |
+
besselj(0, x)*besselj(1, x))
|
273 |
+
# TODO how does besselj(0, a*x)*besselj(0, b*x) work?
|
274 |
+
# TODO how does besselj(0, x)**2*besselj(1, x)**2 work?
|
275 |
+
# TODO sin(x)*besselj(0, x) etc come out a mess
|
276 |
+
# TODO can x*log(x)*besselj(0, x) be done?
|
277 |
+
# TODO how does besselj(1, x)*besselj(0, x+a) work?
|
278 |
+
# TODO more indefinite integrals when struve functions etc are implemented
|
279 |
+
|
280 |
+
# test a substitution
|
281 |
+
assert integrate(besselj(1, x**2)*x, x, meijerg=True) == \
|
282 |
+
-besselj(0, x**2)/2
|
283 |
+
|
284 |
+
|
285 |
+
def test_inversion():
|
286 |
+
from sympy.functions.special.bessel import besselj
|
287 |
+
from sympy.functions.special.delta_functions import Heaviside
|
288 |
+
|
289 |
+
def inv(f):
|
290 |
+
return piecewise_fold(meijerint_inversion(f, s, t))
|
291 |
+
assert inv(1/(s**2 + 1)) == sin(t)*Heaviside(t)
|
292 |
+
assert inv(s/(s**2 + 1)) == cos(t)*Heaviside(t)
|
293 |
+
assert inv(exp(-s)/s) == Heaviside(t - 1)
|
294 |
+
assert inv(1/sqrt(1 + s**2)) == besselj(0, t)*Heaviside(t)
|
295 |
+
|
296 |
+
# Test some antcedents checking.
|
297 |
+
assert meijerint_inversion(sqrt(s)/sqrt(1 + s**2), s, t) is None
|
298 |
+
assert inv(exp(s**2)) is None
|
299 |
+
assert meijerint_inversion(exp(-s**2), s, t) is None
|
300 |
+
|
301 |
+
|
302 |
+
def test_inversion_conditional_output():
|
303 |
+
from sympy.core.symbol import Symbol
|
304 |
+
from sympy.integrals.transforms import InverseLaplaceTransform
|
305 |
+
|
306 |
+
a = Symbol('a', positive=True)
|
307 |
+
F = sqrt(pi/a)*exp(-2*sqrt(a)*sqrt(s))
|
308 |
+
f = meijerint_inversion(F, s, t)
|
309 |
+
assert not f.is_Piecewise
|
310 |
+
|
311 |
+
b = Symbol('b', real=True)
|
312 |
+
F = F.subs(a, b)
|
313 |
+
f2 = meijerint_inversion(F, s, t)
|
314 |
+
assert f2.is_Piecewise
|
315 |
+
# first piece is same as f
|
316 |
+
assert f2.args[0][0] == f.subs(a, b)
|
317 |
+
# last piece is an unevaluated transform
|
318 |
+
assert f2.args[-1][1]
|
319 |
+
ILT = InverseLaplaceTransform(F, s, t, None)
|
320 |
+
assert f2.args[-1][0] == ILT or f2.args[-1][0] == ILT.as_integral
|
321 |
+
|
322 |
+
|
323 |
+
def test_inversion_exp_real_nonreal_shift():
|
324 |
+
from sympy.core.symbol import Symbol
|
325 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
326 |
+
r = Symbol('r', real=True)
|
327 |
+
c = Symbol('c', extended_real=False)
|
328 |
+
a = 1 + 2*I
|
329 |
+
z = Symbol('z')
|
330 |
+
assert not meijerint_inversion(exp(r*s), s, t).is_Piecewise
|
331 |
+
assert meijerint_inversion(exp(a*s), s, t) is None
|
332 |
+
assert meijerint_inversion(exp(c*s), s, t) is None
|
333 |
+
f = meijerint_inversion(exp(z*s), s, t)
|
334 |
+
assert f.is_Piecewise
|
335 |
+
assert isinstance(f.args[0][0], DiracDelta)
|
336 |
+
|
337 |
+
|
338 |
+
@slow
|
339 |
+
def test_lookup_table():
|
340 |
+
from sympy.core.random import uniform, randrange
|
341 |
+
from sympy.core.add import Add
|
342 |
+
from sympy.integrals.meijerint import z as z_dummy
|
343 |
+
table = {}
|
344 |
+
_create_lookup_table(table)
|
345 |
+
for _, l in table.items():
|
346 |
+
for formula, terms, cond, hint in sorted(l, key=default_sort_key):
|
347 |
+
subs = {}
|
348 |
+
for ai in list(formula.free_symbols) + [z_dummy]:
|
349 |
+
if hasattr(ai, 'properties') and ai.properties:
|
350 |
+
# these Wilds match positive integers
|
351 |
+
subs[ai] = randrange(1, 10)
|
352 |
+
else:
|
353 |
+
subs[ai] = uniform(1.5, 2.0)
|
354 |
+
if not isinstance(terms, list):
|
355 |
+
terms = terms(subs)
|
356 |
+
|
357 |
+
# First test that hyperexpand can do this.
|
358 |
+
expanded = [hyperexpand(g) for (_, g) in terms]
|
359 |
+
assert all(x.is_Piecewise or not x.has(meijerg) for x in expanded)
|
360 |
+
|
361 |
+
# Now test that the meijer g-function is indeed as advertised.
|
362 |
+
expanded = Add(*[f*x for (f, x) in terms])
|
363 |
+
a, b = formula.n(subs=subs), expanded.n(subs=subs)
|
364 |
+
r = min(abs(a), abs(b))
|
365 |
+
if r < 1:
|
366 |
+
assert abs(a - b).n() <= 1e-10
|
367 |
+
else:
|
368 |
+
assert (abs(a - b)/r).n() <= 1e-10
|
369 |
+
|
370 |
+
|
371 |
+
def test_branch_bug():
|
372 |
+
from sympy.functions.special.gamma_functions import lowergamma
|
373 |
+
from sympy.simplify.powsimp import powdenest
|
374 |
+
# TODO gammasimp cannot prove that the factor is unity
|
375 |
+
assert powdenest(integrate(erf(x**3), x, meijerg=True).diff(x),
|
376 |
+
polar=True) == 2*erf(x**3)*gamma(Rational(2, 3))/3/gamma(Rational(5, 3))
|
377 |
+
assert integrate(erf(x**3), x, meijerg=True) == \
|
378 |
+
2*x*erf(x**3)*gamma(Rational(2, 3))/(3*gamma(Rational(5, 3))) \
|
379 |
+
- 2*gamma(Rational(2, 3))*lowergamma(Rational(2, 3), x**6)/(3*sqrt(pi)*gamma(Rational(5, 3)))
|
380 |
+
|
381 |
+
|
382 |
+
def test_linear_subs():
|
383 |
+
from sympy.functions.special.bessel import besselj
|
384 |
+
assert integrate(sin(x - 1), x, meijerg=True) == -cos(1 - x)
|
385 |
+
assert integrate(besselj(1, x - 1), x, meijerg=True) == -besselj(0, 1 - x)
|
386 |
+
|
387 |
+
|
388 |
+
@slow
|
389 |
+
def test_probability():
|
390 |
+
# various integrals from probability theory
|
391 |
+
from sympy.core.function import expand_mul
|
392 |
+
from sympy.core.symbol import (Symbol, symbols)
|
393 |
+
from sympy.simplify.gammasimp import gammasimp
|
394 |
+
from sympy.simplify.powsimp import powsimp
|
395 |
+
mu1, mu2 = symbols('mu1 mu2', nonzero=True)
|
396 |
+
sigma1, sigma2 = symbols('sigma1 sigma2', positive=True)
|
397 |
+
rate = Symbol('lambda', positive=True)
|
398 |
+
|
399 |
+
def normal(x, mu, sigma):
|
400 |
+
return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2)
|
401 |
+
|
402 |
+
def exponential(x, rate):
|
403 |
+
return rate*exp(-rate*x)
|
404 |
+
|
405 |
+
assert integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == 1
|
406 |
+
assert integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == \
|
407 |
+
mu1
|
408 |
+
assert integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \
|
409 |
+
== mu1**2 + sigma1**2
|
410 |
+
assert integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \
|
411 |
+
== mu1**3 + 3*mu1*sigma1**2
|
412 |
+
assert integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
|
413 |
+
(x, -oo, oo), (y, -oo, oo), meijerg=True) == 1
|
414 |
+
assert integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
|
415 |
+
(x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1
|
416 |
+
assert integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
|
417 |
+
(x, -oo, oo), (y, -oo, oo), meijerg=True) == mu2
|
418 |
+
assert integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
|
419 |
+
(x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1*mu2
|
420 |
+
assert integrate((x + y + 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
|
421 |
+
(x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 + mu1 + mu2
|
422 |
+
assert integrate((x + y - 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
|
423 |
+
(x, -oo, oo), (y, -oo, oo), meijerg=True) == \
|
424 |
+
-1 + mu1 + mu2
|
425 |
+
|
426 |
+
i = integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
|
427 |
+
(x, -oo, oo), (y, -oo, oo), meijerg=True)
|
428 |
+
assert not i.has(Abs)
|
429 |
+
assert simplify(i) == mu1**2 + sigma1**2
|
430 |
+
assert integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
|
431 |
+
(x, -oo, oo), (y, -oo, oo), meijerg=True) == \
|
432 |
+
sigma2**2 + mu2**2
|
433 |
+
|
434 |
+
assert integrate(exponential(x, rate), (x, 0, oo), meijerg=True) == 1
|
435 |
+
assert integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True) == \
|
436 |
+
1/rate
|
437 |
+
assert integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True) == \
|
438 |
+
2/rate**2
|
439 |
+
|
440 |
+
def E(expr):
|
441 |
+
res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
|
442 |
+
(x, 0, oo), (y, -oo, oo), meijerg=True)
|
443 |
+
res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
|
444 |
+
(y, -oo, oo), (x, 0, oo), meijerg=True)
|
445 |
+
assert expand_mul(res1) == expand_mul(res2)
|
446 |
+
return res1
|
447 |
+
|
448 |
+
assert E(1) == 1
|
449 |
+
assert E(x*y) == mu1/rate
|
450 |
+
assert E(x*y**2) == mu1**2/rate + sigma1**2/rate
|
451 |
+
ans = sigma1**2 + 1/rate**2
|
452 |
+
assert simplify(E((x + y + 1)**2) - E(x + y + 1)**2) == ans
|
453 |
+
assert simplify(E((x + y - 1)**2) - E(x + y - 1)**2) == ans
|
454 |
+
assert simplify(E((x + y)**2) - E(x + y)**2) == ans
|
455 |
+
|
456 |
+
# Beta' distribution
|
457 |
+
alpha, beta = symbols('alpha beta', positive=True)
|
458 |
+
betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
|
459 |
+
/gamma(alpha)/gamma(beta)
|
460 |
+
assert integrate(betadist, (x, 0, oo), meijerg=True) == 1
|
461 |
+
i = integrate(x*betadist, (x, 0, oo), meijerg=True, conds='separate')
|
462 |
+
assert (gammasimp(i[0]), i[1]) == (alpha/(beta - 1), 1 < beta)
|
463 |
+
j = integrate(x**2*betadist, (x, 0, oo), meijerg=True, conds='separate')
|
464 |
+
assert j[1] == (beta > 2)
|
465 |
+
assert gammasimp(j[0] - i[0]**2) == (alpha + beta - 1)*alpha \
|
466 |
+
/(beta - 2)/(beta - 1)**2
|
467 |
+
|
468 |
+
# Beta distribution
|
469 |
+
# NOTE: this is evaluated using antiderivatives. It also tests that
|
470 |
+
# meijerint_indefinite returns the simplest possible answer.
|
471 |
+
a, b = symbols('a b', positive=True)
|
472 |
+
betadist = x**(a - 1)*(-x + 1)**(b - 1)*gamma(a + b)/(gamma(a)*gamma(b))
|
473 |
+
assert simplify(integrate(betadist, (x, 0, 1), meijerg=True)) == 1
|
474 |
+
assert simplify(integrate(x*betadist, (x, 0, 1), meijerg=True)) == \
|
475 |
+
a/(a + b)
|
476 |
+
assert simplify(integrate(x**2*betadist, (x, 0, 1), meijerg=True)) == \
|
477 |
+
a*(a + 1)/(a + b)/(a + b + 1)
|
478 |
+
assert simplify(integrate(x**y*betadist, (x, 0, 1), meijerg=True)) == \
|
479 |
+
gamma(a + b)*gamma(a + y)/gamma(a)/gamma(a + b + y)
|
480 |
+
|
481 |
+
# Chi distribution
|
482 |
+
k = Symbol('k', integer=True, positive=True)
|
483 |
+
chi = 2**(1 - k/2)*x**(k - 1)*exp(-x**2/2)/gamma(k/2)
|
484 |
+
assert powsimp(integrate(chi, (x, 0, oo), meijerg=True)) == 1
|
485 |
+
assert simplify(integrate(x*chi, (x, 0, oo), meijerg=True)) == \
|
486 |
+
sqrt(2)*gamma((k + 1)/2)/gamma(k/2)
|
487 |
+
assert simplify(integrate(x**2*chi, (x, 0, oo), meijerg=True)) == k
|
488 |
+
|
489 |
+
# Chi^2 distribution
|
490 |
+
chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2)
|
491 |
+
assert powsimp(integrate(chisquared, (x, 0, oo), meijerg=True)) == 1
|
492 |
+
assert simplify(integrate(x*chisquared, (x, 0, oo), meijerg=True)) == k
|
493 |
+
assert simplify(integrate(x**2*chisquared, (x, 0, oo), meijerg=True)) == \
|
494 |
+
k*(k + 2)
|
495 |
+
assert gammasimp(integrate(((x - k)/sqrt(2*k))**3*chisquared, (x, 0, oo),
|
496 |
+
meijerg=True)) == 2*sqrt(2)/sqrt(k)
|
497 |
+
|
498 |
+
# Dagum distribution
|
499 |
+
a, b, p = symbols('a b p', positive=True)
|
500 |
+
# XXX (x/b)**a does not work
|
501 |
+
dagum = a*p/x*(x/b)**(a*p)/(1 + x**a/b**a)**(p + 1)
|
502 |
+
assert simplify(integrate(dagum, (x, 0, oo), meijerg=True)) == 1
|
503 |
+
# XXX conditions are a mess
|
504 |
+
arg = x*dagum
|
505 |
+
assert simplify(integrate(arg, (x, 0, oo), meijerg=True, conds='none')
|
506 |
+
) == a*b*gamma(1 - 1/a)*gamma(p + 1 + 1/a)/(
|
507 |
+
(a*p + 1)*gamma(p))
|
508 |
+
assert simplify(integrate(x*arg, (x, 0, oo), meijerg=True, conds='none')
|
509 |
+
) == a*b**2*gamma(1 - 2/a)*gamma(p + 1 + 2/a)/(
|
510 |
+
(a*p + 2)*gamma(p))
|
511 |
+
|
512 |
+
# F-distribution
|
513 |
+
d1, d2 = symbols('d1 d2', positive=True)
|
514 |
+
f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
|
515 |
+
/gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
|
516 |
+
assert simplify(integrate(f, (x, 0, oo), meijerg=True)) == 1
|
517 |
+
# TODO conditions are a mess
|
518 |
+
assert simplify(integrate(x*f, (x, 0, oo), meijerg=True, conds='none')
|
519 |
+
) == d2/(d2 - 2)
|
520 |
+
assert simplify(integrate(x**2*f, (x, 0, oo), meijerg=True, conds='none')
|
521 |
+
) == d2**2*(d1 + 2)/d1/(d2 - 4)/(d2 - 2)
|
522 |
+
|
523 |
+
# TODO gamma, rayleigh
|
524 |
+
|
525 |
+
# inverse gaussian
|
526 |
+
lamda, mu = symbols('lamda mu', positive=True)
|
527 |
+
dist = sqrt(lamda/2/pi)*x**(Rational(-3, 2))*exp(-lamda*(x - mu)**2/x/2/mu**2)
|
528 |
+
mysimp = lambda expr: simplify(expr.rewrite(exp))
|
529 |
+
assert mysimp(integrate(dist, (x, 0, oo))) == 1
|
530 |
+
assert mysimp(integrate(x*dist, (x, 0, oo))) == mu
|
531 |
+
assert mysimp(integrate((x - mu)**2*dist, (x, 0, oo))) == mu**3/lamda
|
532 |
+
assert mysimp(integrate((x - mu)**3*dist, (x, 0, oo))) == 3*mu**5/lamda**2
|
533 |
+
|
534 |
+
# Levi
|
535 |
+
c = Symbol('c', positive=True)
|
536 |
+
assert integrate(sqrt(c/2/pi)*exp(-c/2/(x - mu))/(x - mu)**S('3/2'),
|
537 |
+
(x, mu, oo)) == 1
|
538 |
+
# higher moments oo
|
539 |
+
|
540 |
+
# log-logistic
|
541 |
+
alpha, beta = symbols('alpha beta', positive=True)
|
542 |
+
distn = (beta/alpha)*x**(beta - 1)/alpha**(beta - 1)/ \
|
543 |
+
(1 + x**beta/alpha**beta)**2
|
544 |
+
# FIXME: If alpha, beta are not declared as finite the line below hangs
|
545 |
+
# after the changes in:
|
546 |
+
# https://github.com/sympy/sympy/pull/16603
|
547 |
+
assert simplify(integrate(distn, (x, 0, oo))) == 1
|
548 |
+
# NOTE the conditions are a mess, but correctly state beta > 1
|
549 |
+
assert simplify(integrate(x*distn, (x, 0, oo), conds='none')) == \
|
550 |
+
pi*alpha/beta/sin(pi/beta)
|
551 |
+
# (similar comment for conditions applies)
|
552 |
+
assert simplify(integrate(x**y*distn, (x, 0, oo), conds='none')) == \
|
553 |
+
pi*alpha**y*y/beta/sin(pi*y/beta)
|
554 |
+
|
555 |
+
# weibull
|
556 |
+
k = Symbol('k', positive=True)
|
557 |
+
n = Symbol('n', positive=True)
|
558 |
+
distn = k/lamda*(x/lamda)**(k - 1)*exp(-(x/lamda)**k)
|
559 |
+
assert simplify(integrate(distn, (x, 0, oo))) == 1
|
560 |
+
assert simplify(integrate(x**n*distn, (x, 0, oo))) == \
|
561 |
+
lamda**n*gamma(1 + n/k)
|
562 |
+
|
563 |
+
# rice distribution
|
564 |
+
from sympy.functions.special.bessel import besseli
|
565 |
+
nu, sigma = symbols('nu sigma', positive=True)
|
566 |
+
rice = x/sigma**2*exp(-(x**2 + nu**2)/2/sigma**2)*besseli(0, x*nu/sigma**2)
|
567 |
+
assert integrate(rice, (x, 0, oo), meijerg=True) == 1
|
568 |
+
# can someone verify higher moments?
|
569 |
+
|
570 |
+
# Laplace distribution
|
571 |
+
mu = Symbol('mu', real=True)
|
572 |
+
b = Symbol('b', positive=True)
|
573 |
+
laplace = exp(-abs(x - mu)/b)/2/b
|
574 |
+
assert integrate(laplace, (x, -oo, oo), meijerg=True) == 1
|
575 |
+
assert integrate(x*laplace, (x, -oo, oo), meijerg=True) == mu
|
576 |
+
assert integrate(x**2*laplace, (x, -oo, oo), meijerg=True) == \
|
577 |
+
2*b**2 + mu**2
|
578 |
+
|
579 |
+
# TODO are there other distributions supported on (-oo, oo) that we can do?
|
580 |
+
|
581 |
+
# misc tests
|
582 |
+
k = Symbol('k', positive=True)
|
583 |
+
assert gammasimp(expand_mul(integrate(log(x)*x**(k - 1)*exp(-x)/gamma(k),
|
584 |
+
(x, 0, oo)))) == polygamma(0, k)
|
585 |
+
|
586 |
+
|
587 |
+
@slow
|
588 |
+
def test_expint():
|
589 |
+
""" Test various exponential integrals. """
|
590 |
+
from sympy.core.symbol import Symbol
|
591 |
+
from sympy.functions.elementary.hyperbolic import sinh
|
592 |
+
from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, expint)
|
593 |
+
assert simplify(unpolarify(integrate(exp(-z*x)/x**y, (x, 1, oo),
|
594 |
+
meijerg=True, conds='none'
|
595 |
+
).rewrite(expint).expand(func=True))) == expint(y, z)
|
596 |
+
|
597 |
+
assert integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True,
|
598 |
+
conds='none').rewrite(expint).expand() == \
|
599 |
+
expint(1, z)
|
600 |
+
assert integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True,
|
601 |
+
conds='none').rewrite(expint).expand() == \
|
602 |
+
expint(2, z).rewrite(Ei).rewrite(expint)
|
603 |
+
assert integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,
|
604 |
+
conds='none').rewrite(expint).expand() == \
|
605 |
+
expint(3, z).rewrite(Ei).rewrite(expint).expand()
|
606 |
+
|
607 |
+
t = Symbol('t', positive=True)
|
608 |
+
assert integrate(-cos(x)/x, (x, t, oo), meijerg=True).expand() == Ci(t)
|
609 |
+
assert integrate(-sin(x)/x, (x, t, oo), meijerg=True).expand() == \
|
610 |
+
Si(t) - pi/2
|
611 |
+
assert integrate(sin(x)/x, (x, 0, z), meijerg=True) == Si(z)
|
612 |
+
assert integrate(sinh(x)/x, (x, 0, z), meijerg=True) == Shi(z)
|
613 |
+
assert integrate(exp(-x)/x, x, meijerg=True).expand().rewrite(expint) == \
|
614 |
+
I*pi - expint(1, x)
|
615 |
+
assert integrate(exp(-x)/x**2, x, meijerg=True).rewrite(expint).expand() \
|
616 |
+
== expint(1, x) - exp(-x)/x - I*pi
|
617 |
+
|
618 |
+
u = Symbol('u', polar=True)
|
619 |
+
assert integrate(cos(u)/u, u, meijerg=True).expand().as_independent(u)[1] \
|
620 |
+
== Ci(u)
|
621 |
+
assert integrate(cosh(u)/u, u, meijerg=True).expand().as_independent(u)[1] \
|
622 |
+
== Chi(u)
|
623 |
+
|
624 |
+
assert integrate(expint(1, x), x, meijerg=True
|
625 |
+
).rewrite(expint).expand() == x*expint(1, x) - exp(-x)
|
626 |
+
assert integrate(expint(2, x), x, meijerg=True
|
627 |
+
).rewrite(expint).expand() == \
|
628 |
+
-x**2*expint(1, x)/2 + x*exp(-x)/2 - exp(-x)/2
|
629 |
+
assert simplify(unpolarify(integrate(expint(y, x), x,
|
630 |
+
meijerg=True).rewrite(expint).expand(func=True))) == \
|
631 |
+
-expint(y + 1, x)
|
632 |
+
|
633 |
+
assert integrate(Si(x), x, meijerg=True) == x*Si(x) + cos(x)
|
634 |
+
assert integrate(Ci(u), u, meijerg=True).expand() == u*Ci(u) - sin(u)
|
635 |
+
assert integrate(Shi(x), x, meijerg=True) == x*Shi(x) - cosh(x)
|
636 |
+
assert integrate(Chi(u), u, meijerg=True).expand() == u*Chi(u) - sinh(u)
|
637 |
+
|
638 |
+
assert integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True) == pi/4
|
639 |
+
assert integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True) == log(2)/2
|
640 |
+
|
641 |
+
|
642 |
+
def test_messy():
|
643 |
+
from sympy.functions.elementary.hyperbolic import (acosh, acoth)
|
644 |
+
from sympy.functions.elementary.trigonometric import (asin, atan)
|
645 |
+
from sympy.functions.special.bessel import besselj
|
646 |
+
from sympy.functions.special.error_functions import (Chi, E1, Shi, Si)
|
647 |
+
from sympy.integrals.transforms import (fourier_transform, laplace_transform)
|
648 |
+
assert (laplace_transform(Si(x), x, s, simplify=True) ==
|
649 |
+
((-atan(s) + pi/2)/s, 0, True))
|
650 |
+
|
651 |
+
assert laplace_transform(Shi(x), x, s, simplify=True) == (
|
652 |
+
acoth(s)/s, -oo, s**2 > 1)
|
653 |
+
|
654 |
+
# where should the logs be simplified?
|
655 |
+
assert laplace_transform(Chi(x), x, s, simplify=True) == (
|
656 |
+
(log(s**(-2)) - log(1 - 1/s**2))/(2*s), -oo, s**2 > 1)
|
657 |
+
|
658 |
+
# TODO maybe simplify the inequalities? when the simplification
|
659 |
+
# allows for generators instead of symbols this will work
|
660 |
+
assert laplace_transform(besselj(a, x), x, s)[1:] == \
|
661 |
+
(0, (re(a) > -2) & (re(a) > -1))
|
662 |
+
|
663 |
+
# NOTE s < 0 can be done, but argument reduction is not good enough yet
|
664 |
+
ans = fourier_transform(besselj(1, x)/x, x, s, noconds=False)
|
665 |
+
assert (ans[0].factor(deep=True).expand(), ans[1]) == \
|
666 |
+
(Piecewise((0, (s > 1/(2*pi)) | (s < -1/(2*pi))),
|
667 |
+
(2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0)
|
668 |
+
# TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons)
|
669 |
+
# - folding could be better
|
670 |
+
|
671 |
+
assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \
|
672 |
+
log(1 + sqrt(2))
|
673 |
+
assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \
|
674 |
+
log(S.Half + sqrt(2)/2)
|
675 |
+
|
676 |
+
assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \
|
677 |
+
Piecewise((-acosh(1/x), abs(x**(-2)) > 1), (I*asin(1/x), True))
|
678 |
+
|
679 |
+
|
680 |
+
def test_issue_6122():
|
681 |
+
assert integrate(exp(-I*x**2), (x, -oo, oo), meijerg=True) == \
|
682 |
+
-I*sqrt(pi)*exp(I*pi/4)
|
683 |
+
|
684 |
+
|
685 |
+
def test_issue_6252():
|
686 |
+
expr = 1/x/(a + b*x)**Rational(1, 3)
|
687 |
+
anti = integrate(expr, x, meijerg=True)
|
688 |
+
assert not anti.has(hyper)
|
689 |
+
# XXX the expression is a mess, but actually upon differentiation and
|
690 |
+
# putting in numerical values seems to work...
|
691 |
+
|
692 |
+
|
693 |
+
def test_issue_6348():
|
694 |
+
assert integrate(exp(I*x)/(1 + x**2), (x, -oo, oo)).simplify().rewrite(exp) \
|
695 |
+
== pi*exp(-1)
|
696 |
+
|
697 |
+
|
698 |
+
def test_fresnel():
|
699 |
+
from sympy.functions.special.error_functions import (fresnelc, fresnels)
|
700 |
+
|
701 |
+
assert expand_func(integrate(sin(pi*x**2/2), x)) == fresnels(x)
|
702 |
+
assert expand_func(integrate(cos(pi*x**2/2), x)) == fresnelc(x)
|
703 |
+
|
704 |
+
|
705 |
+
def test_issue_6860():
|
706 |
+
assert meijerint_indefinite(x**x**x, x) is None
|
707 |
+
|
708 |
+
|
709 |
+
def test_issue_7337():
|
710 |
+
f = meijerint_indefinite(x*sqrt(2*x + 3), x).together()
|
711 |
+
assert f == sqrt(2*x + 3)*(2*x**2 + x - 3)/5
|
712 |
+
assert f._eval_interval(x, S.NegativeOne, S.One) == Rational(2, 5)
|
713 |
+
|
714 |
+
|
715 |
+
def test_issue_8368():
|
716 |
+
assert meijerint_indefinite(cosh(x)*exp(-x*t), x) == (
|
717 |
+
(-t - 1)*exp(x) + (-t + 1)*exp(-x))*exp(-t*x)/2/(t**2 - 1)
|
718 |
+
|
719 |
+
|
720 |
+
def test_issue_10211():
|
721 |
+
from sympy.abc import h, w
|
722 |
+
assert integrate((1/sqrt((y-x)**2 + h**2)**3), (x,0,w), (y,0,w)) == \
|
723 |
+
2*sqrt(1 + w**2/h**2)/h - 2/h
|
724 |
+
|
725 |
+
|
726 |
+
def test_issue_11806():
|
727 |
+
from sympy.core.symbol import symbols
|
728 |
+
y, L = symbols('y L', positive=True)
|
729 |
+
assert integrate(1/sqrt(x**2 + y**2)**3, (x, -L, L)) == \
|
730 |
+
2*L/(y**2*sqrt(L**2 + y**2))
|
731 |
+
|
732 |
+
def test_issue_10681():
|
733 |
+
from sympy.polys.domains.realfield import RR
|
734 |
+
from sympy.abc import R, r
|
735 |
+
f = integrate(r**2*(R**2-r**2)**0.5, r, meijerg=True)
|
736 |
+
g = (1.0/3)*R**1.0*r**3*hyper((-0.5, Rational(3, 2)), (Rational(5, 2),),
|
737 |
+
r**2*exp_polar(2*I*pi)/R**2)
|
738 |
+
assert RR.almosteq((f/g).n(), 1.0, 1e-12)
|
739 |
+
|
740 |
+
def test_issue_13536():
|
741 |
+
from sympy.core.symbol import Symbol
|
742 |
+
a = Symbol('a', positive=True)
|
743 |
+
assert integrate(1/x**2, (x, oo, a)) == -1/a
|
744 |
+
|
745 |
+
|
746 |
+
def test_issue_6462():
|
747 |
+
from sympy.core.symbol import Symbol
|
748 |
+
x = Symbol('x')
|
749 |
+
n = Symbol('n')
|
750 |
+
# Not the actual issue, still wrong answer for n = 1, but that there is no
|
751 |
+
# exception
|
752 |
+
assert integrate(cos(x**n)/x**n, x, meijerg=True).subs(n, 2).equals(
|
753 |
+
integrate(cos(x**2)/x**2, x, meijerg=True))
|
754 |
+
|
755 |
+
|
756 |
+
def test_indefinite_1_bug():
|
757 |
+
assert integrate((b + t)**(-a), t, meijerg=True
|
758 |
+
) == -b**(1 - a)*(1 + t/b)**(1 - a)/(a - 1)
|
759 |
+
|
760 |
+
|
761 |
+
def test_pr_23583():
|
762 |
+
# This result is wrong. Check whether new result is correct when this test fail.
|
763 |
+
assert integrate(1/sqrt((x - I)**2-1), meijerg=True) == \
|
764 |
+
Piecewise((acosh(x - I), Abs((x - I)**2) > 1), (-I*asin(x - I), True))
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_prde.py
ADDED
@@ -0,0 +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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Most of these tests come from the examples in Bronstein's book."""
|
2 |
+
from sympy.integrals.risch import DifferentialExtension, derivation
|
3 |
+
from sympy.integrals.prde import (prde_normal_denom, prde_special_denom,
|
4 |
+
prde_linear_constraints, constant_system, prde_spde, prde_no_cancel_b_large,
|
5 |
+
prde_no_cancel_b_small, limited_integrate_reduce, limited_integrate,
|
6 |
+
is_deriv_k, is_log_deriv_k_t_radical, parametric_log_deriv_heu,
|
7 |
+
is_log_deriv_k_t_radical_in_field, param_poly_rischDE, param_rischDE,
|
8 |
+
prde_cancel_liouvillian)
|
9 |
+
|
10 |
+
from sympy.polys.polymatrix import PolyMatrix as Matrix
|
11 |
+
|
12 |
+
from sympy.core.numbers import Rational
|
13 |
+
from sympy.core.singleton import S
|
14 |
+
from sympy.core.symbol import symbols
|
15 |
+
from sympy.polys.domains.rationalfield import QQ
|
16 |
+
from sympy.polys.polytools import Poly
|
17 |
+
from sympy.abc import x, t, n
|
18 |
+
|
19 |
+
t0, t1, t2, t3, k = symbols('t:4 k')
|
20 |
+
|
21 |
+
|
22 |
+
def test_prde_normal_denom():
|
23 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
|
24 |
+
fa = Poly(1, t)
|
25 |
+
fd = Poly(x, t)
|
26 |
+
G = [(Poly(t, t), Poly(1 + t**2, t)), (Poly(1, t), Poly(x + x*t**2, t))]
|
27 |
+
assert prde_normal_denom(fa, fd, G, DE) == \
|
28 |
+
(Poly(x, t, domain='ZZ(x)'), (Poly(1, t, domain='ZZ(x)'), Poly(1, t,
|
29 |
+
domain='ZZ(x)')), [(Poly(x*t, t, domain='ZZ(x)'),
|
30 |
+
Poly(t**2 + 1, t, domain='ZZ(x)')), (Poly(1, t, domain='ZZ(x)'),
|
31 |
+
Poly(t**2 + 1, t, domain='ZZ(x)'))], Poly(1, t, domain='ZZ(x)'))
|
32 |
+
G = [(Poly(t, t), Poly(t**2 + 2*t + 1, t)), (Poly(x*t, t),
|
33 |
+
Poly(t**2 + 2*t + 1, t)), (Poly(x*t**2, t), Poly(t**2 + 2*t + 1, t))]
|
34 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
35 |
+
assert prde_normal_denom(Poly(x, t), Poly(1, t), G, DE) == \
|
36 |
+
(Poly(t + 1, t), (Poly((-1 + x)*t + x, t), Poly(1, t, domain='ZZ[x]')), [(Poly(t, t),
|
37 |
+
Poly(1, t)), (Poly(x*t, t), Poly(1, t, domain='ZZ[x]')), (Poly(x*t**2, t),
|
38 |
+
Poly(1, t, domain='ZZ[x]'))], Poly(t + 1, t))
|
39 |
+
|
40 |
+
|
41 |
+
def test_prde_special_denom():
|
42 |
+
a = Poly(t + 1, t)
|
43 |
+
ba = Poly(t**2, t)
|
44 |
+
bd = Poly(1, t)
|
45 |
+
G = [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))]
|
46 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
47 |
+
assert prde_special_denom(a, ba, bd, G, DE) == \
|
48 |
+
(Poly(t + 1, t), Poly(t**2, t), [(Poly(t, t), Poly(1, t)),
|
49 |
+
(Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))], Poly(1, t))
|
50 |
+
G = [(Poly(t, t), Poly(1, t)), (Poly(1, t), Poly(t, t))]
|
51 |
+
assert prde_special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), G, DE) == \
|
52 |
+
(Poly(1, t), Poly(t**2 - 1, t), [(Poly(t**2, t), Poly(1, t)),
|
53 |
+
(Poly(1, t), Poly(1, t))], Poly(t, t))
|
54 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-2*x*t0, t0)]})
|
55 |
+
DE.decrement_level()
|
56 |
+
G = [(Poly(t, t), Poly(t**2, t)), (Poly(2*t, t), Poly(t, t))]
|
57 |
+
assert prde_special_denom(Poly(5*x*t + 1, t), Poly(t**2 + 2*x**3*t, t), Poly(t**3 + 2, t), G, DE) == \
|
58 |
+
(Poly(5*x*t + 1, t), Poly(0, t, domain='ZZ[x]'), [(Poly(t, t), Poly(t**2, t)),
|
59 |
+
(Poly(2*t, t), Poly(t, t))], Poly(1, x))
|
60 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly((t**2 + 1)*2*x, t)]})
|
61 |
+
G = [(Poly(t + x, t), Poly(t*x, t)), (Poly(2*t, t), Poly(x**2, x))]
|
62 |
+
assert prde_special_denom(Poly(5*x*t + 1, t), Poly(t**2 + 2*x**3*t, t), Poly(t**3, t), G, DE) == \
|
63 |
+
(Poly(5*x*t + 1, t), Poly(0, t, domain='ZZ[x]'), [(Poly(t + x, t), Poly(x*t, t)),
|
64 |
+
(Poly(2*t, t, x), Poly(x**2, t, x))], Poly(1, t))
|
65 |
+
assert prde_special_denom(Poly(t + 1, t), Poly(t**2, t), Poly(t**3, t), G, DE) == \
|
66 |
+
(Poly(t + 1, t), Poly(0, t, domain='ZZ[x]'), [(Poly(t + x, t), Poly(x*t, t)), (Poly(2*t, t, x),
|
67 |
+
Poly(x**2, t, x))], Poly(1, t))
|
68 |
+
|
69 |
+
|
70 |
+
def test_prde_linear_constraints():
|
71 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
72 |
+
G = [(Poly(2*x**3 + 3*x + 1, x), Poly(x**2 - 1, x)), (Poly(1, x), Poly(x - 1, x)),
|
73 |
+
(Poly(1, x), Poly(x + 1, x))]
|
74 |
+
assert prde_linear_constraints(Poly(1, x), Poly(0, x), G, DE) == \
|
75 |
+
((Poly(2*x, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(0, x, domain='QQ')),
|
76 |
+
Matrix([[1, 1, -1], [5, 1, 1]], x))
|
77 |
+
G = [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))]
|
78 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
79 |
+
assert prde_linear_constraints(Poly(t + 1, t), Poly(t**2, t), G, DE) == \
|
80 |
+
((Poly(t, t, domain='QQ'), Poly(t**2, t, domain='QQ'), Poly(t**3, t, domain='QQ')),
|
81 |
+
Matrix(0, 3, [], t))
|
82 |
+
G = [(Poly(2*x, t), Poly(t, t)), (Poly(-x, t), Poly(t, t))]
|
83 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
84 |
+
assert prde_linear_constraints(Poly(1, t), Poly(0, t), G, DE) == \
|
85 |
+
((Poly(0, t, domain='QQ[x]'), Poly(0, t, domain='QQ[x]')), Matrix([[2*x, -x]], t))
|
86 |
+
|
87 |
+
|
88 |
+
def test_constant_system():
|
89 |
+
A = Matrix([[-(x + 3)/(x - 1), (x + 1)/(x - 1), 1],
|
90 |
+
[-x - 3, x + 1, x - 1],
|
91 |
+
[2*(x + 3)/(x - 1), 0, 0]], t)
|
92 |
+
u = Matrix([[(x + 1)/(x - 1)], [x + 1], [0]], t)
|
93 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
94 |
+
R = QQ.frac_field(x)[t]
|
95 |
+
assert constant_system(A, u, DE) == \
|
96 |
+
(Matrix([[1, 0, 0],
|
97 |
+
[0, 1, 0],
|
98 |
+
[0, 0, 0],
|
99 |
+
[0, 0, 1]], ring=R), Matrix([0, 1, 0, 0], ring=R))
|
100 |
+
|
101 |
+
|
102 |
+
def test_prde_spde():
|
103 |
+
D = [Poly(x, t), Poly(-x*t, t)]
|
104 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
105 |
+
# TODO: when bound_degree() can handle this, test degree bound from that too
|
106 |
+
assert prde_spde(Poly(t, t), Poly(-1/x, t), D, n, DE) == \
|
107 |
+
(Poly(t, t), Poly(0, t, domain='ZZ(x)'),
|
108 |
+
[Poly(2*x, t, domain='ZZ(x)'), Poly(-x, t, domain='ZZ(x)')],
|
109 |
+
[Poly(-x**2, t, domain='ZZ(x)'), Poly(0, t, domain='ZZ(x)')], n - 1)
|
110 |
+
|
111 |
+
|
112 |
+
def test_prde_no_cancel():
|
113 |
+
# b large
|
114 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
115 |
+
assert prde_no_cancel_b_large(Poly(1, x), [Poly(x**2, x), Poly(1, x)], 2, DE) == \
|
116 |
+
([Poly(x**2 - 2*x + 2, x), Poly(1, x)], Matrix([[1, 0, -1, 0],
|
117 |
+
[0, 1, 0, -1]], x))
|
118 |
+
assert prde_no_cancel_b_large(Poly(1, x), [Poly(x**3, x), Poly(1, x)], 3, DE) == \
|
119 |
+
([Poly(x**3 - 3*x**2 + 6*x - 6, x), Poly(1, x)], Matrix([[1, 0, -1, 0],
|
120 |
+
[0, 1, 0, -1]], x))
|
121 |
+
assert prde_no_cancel_b_large(Poly(x, x), [Poly(x**2, x), Poly(1, x)], 1, DE) == \
|
122 |
+
([Poly(x, x, domain='ZZ'), Poly(0, x, domain='ZZ')], Matrix([[1, -1, 0, 0],
|
123 |
+
[1, 0, -1, 0],
|
124 |
+
[0, 1, 0, -1]], x))
|
125 |
+
# b small
|
126 |
+
# XXX: Is there a better example of a monomial with D.degree() > 2?
|
127 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**3 + 1, t)]})
|
128 |
+
|
129 |
+
# My original q was t**4 + t + 1, but this solution implies q == t**4
|
130 |
+
# (c1 = 4), with some of the ci for the original q equal to 0.
|
131 |
+
G = [Poly(t**6, t), Poly(x*t**5, t), Poly(t**3, t), Poly(x*t**2, t), Poly(1 + x, t)]
|
132 |
+
R = QQ.frac_field(x)[t]
|
133 |
+
assert prde_no_cancel_b_small(Poly(x*t, t), G, 4, DE) == \
|
134 |
+
([Poly(t**4/4 - x/12*t**3 + x**2/24*t**2 + (Rational(-11, 12) - x**3/24)*t + x/24, t),
|
135 |
+
Poly(x/3*t**3 - x**2/6*t**2 + (Rational(-1, 3) + x**3/6)*t - x/6, t), Poly(t, t),
|
136 |
+
Poly(0, t), Poly(0, t)], Matrix([[1, 0, -1, 0, 0, 0, 0, 0, 0, 0],
|
137 |
+
[0, 1, Rational(-1, 4), 0, 0, 0, 0, 0, 0, 0],
|
138 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
139 |
+
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
|
140 |
+
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
|
141 |
+
[1, 0, 0, 0, 0, -1, 0, 0, 0, 0],
|
142 |
+
[0, 1, 0, 0, 0, 0, -1, 0, 0, 0],
|
143 |
+
[0, 0, 1, 0, 0, 0, 0, -1, 0, 0],
|
144 |
+
[0, 0, 0, 1, 0, 0, 0, 0, -1, 0],
|
145 |
+
[0, 0, 0, 0, 1, 0, 0, 0, 0, -1]], ring=R))
|
146 |
+
|
147 |
+
# TODO: Add test for deg(b) <= 0 with b small
|
148 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
|
149 |
+
b = Poly(-1/x**2, t, field=True) # deg(b) == 0
|
150 |
+
q = [Poly(x**i*t**j, t, field=True) for i in range(2) for j in range(3)]
|
151 |
+
h, A = prde_no_cancel_b_small(b, q, 3, DE)
|
152 |
+
V = A.nullspace()
|
153 |
+
R = QQ.frac_field(x)[t]
|
154 |
+
assert len(V) == 1
|
155 |
+
assert V[0] == Matrix([Rational(-1, 2), 0, 0, 1, 0, 0]*3, ring=R)
|
156 |
+
assert (Matrix([h])*V[0][6:, :])[0] == Poly(x**2/2, t, domain='QQ(x)')
|
157 |
+
assert (Matrix([q])*V[0][:6, :])[0] == Poly(x - S.Half, t, domain='QQ(x)')
|
158 |
+
|
159 |
+
|
160 |
+
def test_prde_cancel_liouvillian():
|
161 |
+
### 1. case == 'primitive'
|
162 |
+
# used when integrating f = log(x) - log(x - 1)
|
163 |
+
# Not taken from 'the' book
|
164 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
165 |
+
p0 = Poly(0, t, field=True)
|
166 |
+
p1 = Poly((x - 1)*t, t, domain='ZZ(x)')
|
167 |
+
p2 = Poly(x - 1, t, domain='ZZ(x)')
|
168 |
+
p3 = Poly(-x**2 + x, t, domain='ZZ(x)')
|
169 |
+
h, A = prde_cancel_liouvillian(Poly(-1/(x - 1), t), [Poly(-x + 1, t), Poly(1, t)], 1, DE)
|
170 |
+
V = A.nullspace()
|
171 |
+
assert h == [p0, p0, p1, p0, p0, p0, p0, p0, p0, p0, p2, p3, p0, p0, p0, p0]
|
172 |
+
assert A.rank() == 16
|
173 |
+
assert (Matrix([h])*V[0][:16, :]) == Matrix([[Poly(0, t, domain='QQ(x)')]])
|
174 |
+
|
175 |
+
### 2. case == 'exp'
|
176 |
+
# used when integrating log(x/exp(x) + 1)
|
177 |
+
# Not taken from book
|
178 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t, t)]})
|
179 |
+
assert prde_cancel_liouvillian(Poly(0, t, domain='QQ[x]'), [Poly(1, t, domain='QQ(x)')], 0, DE) == \
|
180 |
+
([Poly(1, t, domain='QQ'), Poly(x, t, domain='ZZ(x)')], Matrix([[-1, 0, 1]], DE.t))
|
181 |
+
|
182 |
+
|
183 |
+
def test_param_poly_rischDE():
|
184 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
185 |
+
a = Poly(x**2 - x, x, field=True)
|
186 |
+
b = Poly(1, x, field=True)
|
187 |
+
q = [Poly(x, x, field=True), Poly(x**2, x, field=True)]
|
188 |
+
h, A = param_poly_rischDE(a, b, q, 3, DE)
|
189 |
+
|
190 |
+
assert A.nullspace() == [Matrix([0, 1, 1, 1], DE.t)] # c1, c2, d1, d2
|
191 |
+
# Solution of a*Dp + b*p = c1*q1 + c2*q2 = q2 = x**2
|
192 |
+
# is d1*h1 + d2*h2 = h1 + h2 = x.
|
193 |
+
assert h[0] + h[1] == Poly(x, x, domain='QQ')
|
194 |
+
# a*Dp + b*p = q1 = x has no solution.
|
195 |
+
|
196 |
+
a = Poly(x**2 - x, x, field=True)
|
197 |
+
b = Poly(x**2 - 5*x + 3, x, field=True)
|
198 |
+
q = [Poly(1, x, field=True), Poly(x, x, field=True),
|
199 |
+
Poly(x**2, x, field=True)]
|
200 |
+
h, A = param_poly_rischDE(a, b, q, 3, DE)
|
201 |
+
|
202 |
+
assert A.nullspace() == [Matrix([3, -5, 1, -5, 1, 1], DE.t)]
|
203 |
+
p = -Poly(5, DE.t)*h[0] + h[1] + h[2] # Poly(1, x)
|
204 |
+
assert a*derivation(p, DE) + b*p == Poly(x**2 - 5*x + 3, x, domain='QQ')
|
205 |
+
|
206 |
+
|
207 |
+
def test_param_rischDE():
|
208 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
209 |
+
p1, px = Poly(1, x, field=True), Poly(x, x, field=True)
|
210 |
+
G = [(p1, px), (p1, p1), (px, p1)] # [1/x, 1, x]
|
211 |
+
h, A = param_rischDE(-p1, Poly(x**2, x, field=True), G, DE)
|
212 |
+
assert len(h) == 3
|
213 |
+
p = [hi[0].as_expr()/hi[1].as_expr() for hi in h]
|
214 |
+
V = A.nullspace()
|
215 |
+
assert len(V) == 2
|
216 |
+
assert V[0] == Matrix([-1, 1, 0, -1, 1, 0], DE.t)
|
217 |
+
y = -p[0] + p[1] + 0*p[2] # x
|
218 |
+
assert y.diff(x) - y/x**2 == 1 - 1/x # Dy + f*y == -G0 + G1 + 0*G2
|
219 |
+
|
220 |
+
# the below test computation takes place while computing the integral
|
221 |
+
# of 'f = log(log(x + exp(x)))'
|
222 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
223 |
+
G = [(Poly(t + x, t, domain='ZZ(x)'), Poly(1, t, domain='QQ')), (Poly(0, t, domain='QQ'), Poly(1, t, domain='QQ'))]
|
224 |
+
h, A = param_rischDE(Poly(-t - 1, t, field=True), Poly(t + x, t, field=True), G, DE)
|
225 |
+
assert len(h) == 5
|
226 |
+
p = [hi[0].as_expr()/hi[1].as_expr() for hi in h]
|
227 |
+
V = A.nullspace()
|
228 |
+
assert len(V) == 3
|
229 |
+
assert V[0] == Matrix([0, 0, 0, 0, 1, 0, 0], DE.t)
|
230 |
+
y = 0*p[0] + 0*p[1] + 1*p[2] + 0*p[3] + 0*p[4]
|
231 |
+
assert y.diff(t) - y/(t + x) == 0 # Dy + f*y = 0*G0 + 0*G1
|
232 |
+
|
233 |
+
|
234 |
+
def test_limited_integrate_reduce():
|
235 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
236 |
+
assert limited_integrate_reduce(Poly(x, t), Poly(t**2, t), [(Poly(x, t),
|
237 |
+
Poly(t, t))], DE) == \
|
238 |
+
(Poly(t, t), Poly(-1/x, t), Poly(t, t), 1, (Poly(x, t), Poly(1, t, domain='ZZ[x]')),
|
239 |
+
[(Poly(-x*t, t), Poly(1, t, domain='ZZ[x]'))])
|
240 |
+
|
241 |
+
|
242 |
+
def test_limited_integrate():
|
243 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
244 |
+
G = [(Poly(x, x), Poly(x + 1, x))]
|
245 |
+
assert limited_integrate(Poly(-(1 + x + 5*x**2 - 3*x**3), x),
|
246 |
+
Poly(1 - x - x**2 + x**3, x), G, DE) == \
|
247 |
+
((Poly(x**2 - x + 2, x), Poly(x - 1, x, domain='QQ')), [2])
|
248 |
+
G = [(Poly(1, x), Poly(x, x))]
|
249 |
+
assert limited_integrate(Poly(5*x**2, x), Poly(3, x), G, DE) == \
|
250 |
+
((Poly(5*x**3/9, x), Poly(1, x, domain='QQ')), [0])
|
251 |
+
|
252 |
+
|
253 |
+
def test_is_log_deriv_k_t_radical():
|
254 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)], 'exts': [None],
|
255 |
+
'extargs': [None]})
|
256 |
+
assert is_log_deriv_k_t_radical(Poly(2*x, x), Poly(1, x), DE) is None
|
257 |
+
|
258 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2*t1, t1), Poly(1/x, t2)],
|
259 |
+
'exts': [None, 'exp', 'log'], 'extargs': [None, 2*x, x]})
|
260 |
+
assert is_log_deriv_k_t_radical(Poly(x + t2/2, t2), Poly(1, t2), DE) == \
|
261 |
+
([(t1, 1), (x, 1)], t1*x, 2, 0)
|
262 |
+
# TODO: Add more tests
|
263 |
+
|
264 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(1/x, t)],
|
265 |
+
'exts': [None, 'exp', 'log'], 'extargs': [None, x, x]})
|
266 |
+
assert is_log_deriv_k_t_radical(Poly(x + t/2 + 3, t), Poly(1, t), DE) == \
|
267 |
+
([(t0, 2), (x, 1)], x*t0**2, 2, 3)
|
268 |
+
|
269 |
+
|
270 |
+
def test_is_deriv_k():
|
271 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x + 1), t2)],
|
272 |
+
'exts': [None, 'log', 'log'], 'extargs': [None, x, x + 1]})
|
273 |
+
assert is_deriv_k(Poly(2*x**2 + 2*x, t2), Poly(1, t2), DE) == \
|
274 |
+
([(t1, 1), (t2, 1)], t1 + t2, 2)
|
275 |
+
|
276 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(t2, t2)],
|
277 |
+
'exts': [None, 'log', 'exp'], 'extargs': [None, x, x]})
|
278 |
+
assert is_deriv_k(Poly(x**2*t2**3, t2), Poly(1, t2), DE) == \
|
279 |
+
([(x, 3), (t1, 2)], 2*t1 + 3*x, 1)
|
280 |
+
# TODO: Add more tests, including ones with exponentials
|
281 |
+
|
282 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2/x, t1)],
|
283 |
+
'exts': [None, 'log'], 'extargs': [None, x**2]})
|
284 |
+
assert is_deriv_k(Poly(x, t1), Poly(1, t1), DE) == \
|
285 |
+
([(t1, S.Half)], t1/2, 1)
|
286 |
+
|
287 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2/(1 + x), t0)],
|
288 |
+
'exts': [None, 'log'], 'extargs': [None, x**2 + 2*x + 1]})
|
289 |
+
assert is_deriv_k(Poly(1 + x, t0), Poly(1, t0), DE) == \
|
290 |
+
([(t0, S.Half)], t0/2, 1)
|
291 |
+
|
292 |
+
# Issue 10798
|
293 |
+
# DE = DifferentialExtension(log(1/x), x)
|
294 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-1/x, t)],
|
295 |
+
'exts': [None, 'log'], 'extargs': [None, 1/x]})
|
296 |
+
assert is_deriv_k(Poly(1, t), Poly(x, t), DE) == ([(t, 1)], t, 1)
|
297 |
+
|
298 |
+
|
299 |
+
def test_is_log_deriv_k_t_radical_in_field():
|
300 |
+
# NOTE: any potential constant factor in the second element of the result
|
301 |
+
# doesn't matter, because it cancels in Da/a.
|
302 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
303 |
+
assert is_log_deriv_k_t_radical_in_field(Poly(5*t + 1, t), Poly(2*t*x, t), DE) == \
|
304 |
+
(2, t*x**5)
|
305 |
+
assert is_log_deriv_k_t_radical_in_field(Poly(2 + 3*t, t), Poly(5*x*t, t), DE) == \
|
306 |
+
(5, x**3*t**2)
|
307 |
+
|
308 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t/x**2, t)]})
|
309 |
+
assert is_log_deriv_k_t_radical_in_field(Poly(-(1 + 2*t), t),
|
310 |
+
Poly(2*x**2 + 2*x**2*t, t), DE) == \
|
311 |
+
(2, t + t**2)
|
312 |
+
assert is_log_deriv_k_t_radical_in_field(Poly(-1, t), Poly(x**2, t), DE) == \
|
313 |
+
(1, t)
|
314 |
+
assert is_log_deriv_k_t_radical_in_field(Poly(1, t), Poly(2*x**2, t), DE) == \
|
315 |
+
(2, 1/t)
|
316 |
+
|
317 |
+
|
318 |
+
def test_parametric_log_deriv():
|
319 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
320 |
+
assert parametric_log_deriv_heu(Poly(5*t**2 + t - 6, t), Poly(2*x*t**2, t),
|
321 |
+
Poly(-1, t), Poly(x*t**2, t), DE) == \
|
322 |
+
(2, 6, t*x**5)
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_quadrature.py
ADDED
@@ -0,0 +1,601 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import S, Rational
|
2 |
+
from sympy.integrals.quadrature import (gauss_legendre, gauss_laguerre,
|
3 |
+
gauss_hermite, gauss_gen_laguerre,
|
4 |
+
gauss_chebyshev_t, gauss_chebyshev_u,
|
5 |
+
gauss_jacobi, gauss_lobatto)
|
6 |
+
|
7 |
+
|
8 |
+
def test_legendre():
|
9 |
+
x, w = gauss_legendre(1, 17)
|
10 |
+
assert [str(r) for r in x] == ['0']
|
11 |
+
assert [str(r) for r in w] == ['2.0000000000000000']
|
12 |
+
|
13 |
+
x, w = gauss_legendre(2, 17)
|
14 |
+
assert [str(r) for r in x] == [
|
15 |
+
'-0.57735026918962576',
|
16 |
+
'0.57735026918962576']
|
17 |
+
assert [str(r) for r in w] == [
|
18 |
+
'1.0000000000000000',
|
19 |
+
'1.0000000000000000']
|
20 |
+
|
21 |
+
x, w = gauss_legendre(3, 17)
|
22 |
+
assert [str(r) for r in x] == [
|
23 |
+
'-0.77459666924148338',
|
24 |
+
'0',
|
25 |
+
'0.77459666924148338']
|
26 |
+
assert [str(r) for r in w] == [
|
27 |
+
'0.55555555555555556',
|
28 |
+
'0.88888888888888889',
|
29 |
+
'0.55555555555555556']
|
30 |
+
|
31 |
+
x, w = gauss_legendre(4, 17)
|
32 |
+
assert [str(r) for r in x] == [
|
33 |
+
'-0.86113631159405258',
|
34 |
+
'-0.33998104358485626',
|
35 |
+
'0.33998104358485626',
|
36 |
+
'0.86113631159405258']
|
37 |
+
assert [str(r) for r in w] == [
|
38 |
+
'0.34785484513745386',
|
39 |
+
'0.65214515486254614',
|
40 |
+
'0.65214515486254614',
|
41 |
+
'0.34785484513745386']
|
42 |
+
|
43 |
+
|
44 |
+
def test_legendre_precise():
|
45 |
+
x, w = gauss_legendre(3, 40)
|
46 |
+
assert [str(r) for r in x] == [
|
47 |
+
'-0.7745966692414833770358530799564799221666',
|
48 |
+
'0',
|
49 |
+
'0.7745966692414833770358530799564799221666']
|
50 |
+
assert [str(r) for r in w] == [
|
51 |
+
'0.5555555555555555555555555555555555555556',
|
52 |
+
'0.8888888888888888888888888888888888888889',
|
53 |
+
'0.5555555555555555555555555555555555555556']
|
54 |
+
|
55 |
+
|
56 |
+
def test_laguerre():
|
57 |
+
x, w = gauss_laguerre(1, 17)
|
58 |
+
assert [str(r) for r in x] == ['1.0000000000000000']
|
59 |
+
assert [str(r) for r in w] == ['1.0000000000000000']
|
60 |
+
|
61 |
+
x, w = gauss_laguerre(2, 17)
|
62 |
+
assert [str(r) for r in x] == [
|
63 |
+
'0.58578643762690495',
|
64 |
+
'3.4142135623730950']
|
65 |
+
assert [str(r) for r in w] == [
|
66 |
+
'0.85355339059327376',
|
67 |
+
'0.14644660940672624']
|
68 |
+
|
69 |
+
x, w = gauss_laguerre(3, 17)
|
70 |
+
assert [str(r) for r in x] == [
|
71 |
+
'0.41577455678347908',
|
72 |
+
'2.2942803602790417',
|
73 |
+
'6.2899450829374792',
|
74 |
+
]
|
75 |
+
assert [str(r) for r in w] == [
|
76 |
+
'0.71109300992917302',
|
77 |
+
'0.27851773356924085',
|
78 |
+
'0.010389256501586136',
|
79 |
+
]
|
80 |
+
|
81 |
+
x, w = gauss_laguerre(4, 17)
|
82 |
+
assert [str(r) for r in x] == [
|
83 |
+
'0.32254768961939231',
|
84 |
+
'1.7457611011583466',
|
85 |
+
'4.5366202969211280',
|
86 |
+
'9.3950709123011331']
|
87 |
+
assert [str(r) for r in w] == [
|
88 |
+
'0.60315410434163360',
|
89 |
+
'0.35741869243779969',
|
90 |
+
'0.038887908515005384',
|
91 |
+
'0.00053929470556132745']
|
92 |
+
|
93 |
+
x, w = gauss_laguerre(5, 17)
|
94 |
+
assert [str(r) for r in x] == [
|
95 |
+
'0.26356031971814091',
|
96 |
+
'1.4134030591065168',
|
97 |
+
'3.5964257710407221',
|
98 |
+
'7.0858100058588376',
|
99 |
+
'12.640800844275783']
|
100 |
+
assert [str(r) for r in w] == [
|
101 |
+
'0.52175561058280865',
|
102 |
+
'0.39866681108317593',
|
103 |
+
'0.075942449681707595',
|
104 |
+
'0.0036117586799220485',
|
105 |
+
'2.3369972385776228e-5']
|
106 |
+
|
107 |
+
|
108 |
+
def test_laguerre_precise():
|
109 |
+
x, w = gauss_laguerre(3, 40)
|
110 |
+
assert [str(r) for r in x] == [
|
111 |
+
'0.4157745567834790833115338731282744735466',
|
112 |
+
'2.294280360279041719822050361359593868960',
|
113 |
+
'6.289945082937479196866415765512131657493']
|
114 |
+
assert [str(r) for r in w] == [
|
115 |
+
'0.7110930099291730154495901911425944313094',
|
116 |
+
'0.2785177335692408488014448884567264810349',
|
117 |
+
'0.01038925650158613574896492040067908765572']
|
118 |
+
|
119 |
+
|
120 |
+
def test_hermite():
|
121 |
+
x, w = gauss_hermite(1, 17)
|
122 |
+
assert [str(r) for r in x] == ['0']
|
123 |
+
assert [str(r) for r in w] == ['1.7724538509055160']
|
124 |
+
|
125 |
+
x, w = gauss_hermite(2, 17)
|
126 |
+
assert [str(r) for r in x] == [
|
127 |
+
'-0.70710678118654752',
|
128 |
+
'0.70710678118654752']
|
129 |
+
assert [str(r) for r in w] == [
|
130 |
+
'0.88622692545275801',
|
131 |
+
'0.88622692545275801']
|
132 |
+
|
133 |
+
x, w = gauss_hermite(3, 17)
|
134 |
+
assert [str(r) for r in x] == [
|
135 |
+
'-1.2247448713915890',
|
136 |
+
'0',
|
137 |
+
'1.2247448713915890']
|
138 |
+
assert [str(r) for r in w] == [
|
139 |
+
'0.29540897515091934',
|
140 |
+
'1.1816359006036774',
|
141 |
+
'0.29540897515091934']
|
142 |
+
|
143 |
+
x, w = gauss_hermite(4, 17)
|
144 |
+
assert [str(r) for r in x] == [
|
145 |
+
'-1.6506801238857846',
|
146 |
+
'-0.52464762327529032',
|
147 |
+
'0.52464762327529032',
|
148 |
+
'1.6506801238857846']
|
149 |
+
assert [str(r) for r in w] == [
|
150 |
+
'0.081312835447245177',
|
151 |
+
'0.80491409000551284',
|
152 |
+
'0.80491409000551284',
|
153 |
+
'0.081312835447245177']
|
154 |
+
|
155 |
+
x, w = gauss_hermite(5, 17)
|
156 |
+
assert [str(r) for r in x] == [
|
157 |
+
'-2.0201828704560856',
|
158 |
+
'-0.95857246461381851',
|
159 |
+
'0',
|
160 |
+
'0.95857246461381851',
|
161 |
+
'2.0201828704560856']
|
162 |
+
assert [str(r) for r in w] == [
|
163 |
+
'0.019953242059045913',
|
164 |
+
'0.39361932315224116',
|
165 |
+
'0.94530872048294188',
|
166 |
+
'0.39361932315224116',
|
167 |
+
'0.019953242059045913']
|
168 |
+
|
169 |
+
|
170 |
+
def test_hermite_precise():
|
171 |
+
x, w = gauss_hermite(3, 40)
|
172 |
+
assert [str(r) for r in x] == [
|
173 |
+
'-1.224744871391589049098642037352945695983',
|
174 |
+
'0',
|
175 |
+
'1.224744871391589049098642037352945695983']
|
176 |
+
assert [str(r) for r in w] == [
|
177 |
+
'0.2954089751509193378830279138901908637996',
|
178 |
+
'1.181635900603677351532111655560763455198',
|
179 |
+
'0.2954089751509193378830279138901908637996']
|
180 |
+
|
181 |
+
|
182 |
+
def test_gen_laguerre():
|
183 |
+
x, w = gauss_gen_laguerre(1, Rational(-1, 2), 17)
|
184 |
+
assert [str(r) for r in x] == ['0.50000000000000000']
|
185 |
+
assert [str(r) for r in w] == ['1.7724538509055160']
|
186 |
+
|
187 |
+
x, w = gauss_gen_laguerre(2, Rational(-1, 2), 17)
|
188 |
+
assert [str(r) for r in x] == [
|
189 |
+
'0.27525512860841095',
|
190 |
+
'2.7247448713915890']
|
191 |
+
assert [str(r) for r in w] == [
|
192 |
+
'1.6098281800110257',
|
193 |
+
'0.16262567089449035']
|
194 |
+
|
195 |
+
x, w = gauss_gen_laguerre(3, Rational(-1, 2), 17)
|
196 |
+
assert [str(r) for r in x] == [
|
197 |
+
'0.19016350919348813',
|
198 |
+
'1.7844927485432516',
|
199 |
+
'5.5253437422632603']
|
200 |
+
assert [str(r) for r in w] == [
|
201 |
+
'1.4492591904487850',
|
202 |
+
'0.31413464064571329',
|
203 |
+
'0.0090600198110176913']
|
204 |
+
|
205 |
+
x, w = gauss_gen_laguerre(4, Rational(-1, 2), 17)
|
206 |
+
assert [str(r) for r in x] == [
|
207 |
+
'0.14530352150331709',
|
208 |
+
'1.3390972881263614',
|
209 |
+
'3.9269635013582872',
|
210 |
+
'8.5886356890120343']
|
211 |
+
assert [str(r) for r in w] == [
|
212 |
+
'1.3222940251164826',
|
213 |
+
'0.41560465162978376',
|
214 |
+
'0.034155966014826951',
|
215 |
+
'0.00039920814442273524']
|
216 |
+
|
217 |
+
x, w = gauss_gen_laguerre(5, Rational(-1, 2), 17)
|
218 |
+
assert [str(r) for r in x] == [
|
219 |
+
'0.11758132021177814',
|
220 |
+
'1.0745620124369040',
|
221 |
+
'3.0859374437175500',
|
222 |
+
'6.4147297336620305',
|
223 |
+
'11.807189489971737']
|
224 |
+
assert [str(r) for r in w] == [
|
225 |
+
'1.2217252674706516',
|
226 |
+
'0.48027722216462937',
|
227 |
+
'0.067748788910962126',
|
228 |
+
'0.0026872914935624654',
|
229 |
+
'1.5280865710465241e-5']
|
230 |
+
|
231 |
+
x, w = gauss_gen_laguerre(1, 2, 17)
|
232 |
+
assert [str(r) for r in x] == ['3.0000000000000000']
|
233 |
+
assert [str(r) for r in w] == ['2.0000000000000000']
|
234 |
+
|
235 |
+
x, w = gauss_gen_laguerre(2, 2, 17)
|
236 |
+
assert [str(r) for r in x] == [
|
237 |
+
'2.0000000000000000',
|
238 |
+
'6.0000000000000000']
|
239 |
+
assert [str(r) for r in w] == [
|
240 |
+
'1.5000000000000000',
|
241 |
+
'0.50000000000000000']
|
242 |
+
|
243 |
+
x, w = gauss_gen_laguerre(3, 2, 17)
|
244 |
+
assert [str(r) for r in x] == [
|
245 |
+
'1.5173870806774125',
|
246 |
+
'4.3115831337195203',
|
247 |
+
'9.1710297856030672']
|
248 |
+
assert [str(r) for r in w] == [
|
249 |
+
'1.0374949614904253',
|
250 |
+
'0.90575000470306537',
|
251 |
+
'0.056755033806509347']
|
252 |
+
|
253 |
+
x, w = gauss_gen_laguerre(4, 2, 17)
|
254 |
+
assert [str(r) for r in x] == [
|
255 |
+
'1.2267632635003021',
|
256 |
+
'3.4125073586969460',
|
257 |
+
'6.9026926058516134',
|
258 |
+
'12.458036771951139']
|
259 |
+
assert [str(r) for r in w] == [
|
260 |
+
'0.72552499769865438',
|
261 |
+
'1.0634242919791946',
|
262 |
+
'0.20669613102835355',
|
263 |
+
'0.0043545792937974889']
|
264 |
+
|
265 |
+
x, w = gauss_gen_laguerre(5, 2, 17)
|
266 |
+
assert [str(r) for r in x] == [
|
267 |
+
'1.0311091440933816',
|
268 |
+
'2.8372128239538217',
|
269 |
+
'5.6202942725987079',
|
270 |
+
'9.6829098376640271',
|
271 |
+
'15.828473921690062']
|
272 |
+
assert [str(r) for r in w] == [
|
273 |
+
'0.52091739683509184',
|
274 |
+
'1.0667059331592211',
|
275 |
+
'0.38354972366693113',
|
276 |
+
'0.028564233532974658',
|
277 |
+
'0.00026271280578124935']
|
278 |
+
|
279 |
+
|
280 |
+
def test_gen_laguerre_precise():
|
281 |
+
x, w = gauss_gen_laguerre(3, Rational(-1, 2), 40)
|
282 |
+
assert [str(r) for r in x] == [
|
283 |
+
'0.1901635091934881328718554276203028970878',
|
284 |
+
'1.784492748543251591186722461957367638500',
|
285 |
+
'5.525343742263260275941422110422329464413']
|
286 |
+
assert [str(r) for r in w] == [
|
287 |
+
'1.449259190448785048183829411195134343108',
|
288 |
+
'0.3141346406457132878326231270167565378246',
|
289 |
+
'0.009060019811017691281714945129254301865020']
|
290 |
+
|
291 |
+
x, w = gauss_gen_laguerre(3, 2, 40)
|
292 |
+
assert [str(r) for r in x] == [
|
293 |
+
'1.517387080677412495020323111016672547482',
|
294 |
+
'4.311583133719520302881184669723530562299',
|
295 |
+
'9.171029785603067202098492219259796890218']
|
296 |
+
assert [str(r) for r in w] == [
|
297 |
+
'1.037494961490425285817554606541269153041',
|
298 |
+
'0.9057500047030653669269785048806009945254',
|
299 |
+
'0.05675503380650934725546688857812985243312']
|
300 |
+
|
301 |
+
|
302 |
+
def test_chebyshev_t():
|
303 |
+
x, w = gauss_chebyshev_t(1, 17)
|
304 |
+
assert [str(r) for r in x] == ['0']
|
305 |
+
assert [str(r) for r in w] == ['3.1415926535897932']
|
306 |
+
|
307 |
+
x, w = gauss_chebyshev_t(2, 17)
|
308 |
+
assert [str(r) for r in x] == [
|
309 |
+
'0.70710678118654752',
|
310 |
+
'-0.70710678118654752']
|
311 |
+
assert [str(r) for r in w] == [
|
312 |
+
'1.5707963267948966',
|
313 |
+
'1.5707963267948966']
|
314 |
+
|
315 |
+
x, w = gauss_chebyshev_t(3, 17)
|
316 |
+
assert [str(r) for r in x] == [
|
317 |
+
'0.86602540378443865',
|
318 |
+
'0',
|
319 |
+
'-0.86602540378443865']
|
320 |
+
assert [str(r) for r in w] == [
|
321 |
+
'1.0471975511965977',
|
322 |
+
'1.0471975511965977',
|
323 |
+
'1.0471975511965977']
|
324 |
+
|
325 |
+
x, w = gauss_chebyshev_t(4, 17)
|
326 |
+
assert [str(r) for r in x] == [
|
327 |
+
'0.92387953251128676',
|
328 |
+
'0.38268343236508977',
|
329 |
+
'-0.38268343236508977',
|
330 |
+
'-0.92387953251128676']
|
331 |
+
assert [str(r) for r in w] == [
|
332 |
+
'0.78539816339744831',
|
333 |
+
'0.78539816339744831',
|
334 |
+
'0.78539816339744831',
|
335 |
+
'0.78539816339744831']
|
336 |
+
|
337 |
+
x, w = gauss_chebyshev_t(5, 17)
|
338 |
+
assert [str(r) for r in x] == [
|
339 |
+
'0.95105651629515357',
|
340 |
+
'0.58778525229247313',
|
341 |
+
'0',
|
342 |
+
'-0.58778525229247313',
|
343 |
+
'-0.95105651629515357']
|
344 |
+
assert [str(r) for r in w] == [
|
345 |
+
'0.62831853071795865',
|
346 |
+
'0.62831853071795865',
|
347 |
+
'0.62831853071795865',
|
348 |
+
'0.62831853071795865',
|
349 |
+
'0.62831853071795865']
|
350 |
+
|
351 |
+
|
352 |
+
def test_chebyshev_t_precise():
|
353 |
+
x, w = gauss_chebyshev_t(3, 40)
|
354 |
+
assert [str(r) for r in x] == [
|
355 |
+
'0.8660254037844386467637231707529361834714',
|
356 |
+
'0',
|
357 |
+
'-0.8660254037844386467637231707529361834714']
|
358 |
+
assert [str(r) for r in w] == [
|
359 |
+
'1.047197551196597746154214461093167628066',
|
360 |
+
'1.047197551196597746154214461093167628066',
|
361 |
+
'1.047197551196597746154214461093167628066']
|
362 |
+
|
363 |
+
|
364 |
+
def test_chebyshev_u():
|
365 |
+
x, w = gauss_chebyshev_u(1, 17)
|
366 |
+
assert [str(r) for r in x] == ['0']
|
367 |
+
assert [str(r) for r in w] == ['1.5707963267948966']
|
368 |
+
|
369 |
+
x, w = gauss_chebyshev_u(2, 17)
|
370 |
+
assert [str(r) for r in x] == [
|
371 |
+
'0.50000000000000000',
|
372 |
+
'-0.50000000000000000']
|
373 |
+
assert [str(r) for r in w] == [
|
374 |
+
'0.78539816339744831',
|
375 |
+
'0.78539816339744831']
|
376 |
+
|
377 |
+
x, w = gauss_chebyshev_u(3, 17)
|
378 |
+
assert [str(r) for r in x] == [
|
379 |
+
'0.70710678118654752',
|
380 |
+
'0',
|
381 |
+
'-0.70710678118654752']
|
382 |
+
assert [str(r) for r in w] == [
|
383 |
+
'0.39269908169872415',
|
384 |
+
'0.78539816339744831',
|
385 |
+
'0.39269908169872415']
|
386 |
+
|
387 |
+
x, w = gauss_chebyshev_u(4, 17)
|
388 |
+
assert [str(r) for r in x] == [
|
389 |
+
'0.80901699437494742',
|
390 |
+
'0.30901699437494742',
|
391 |
+
'-0.30901699437494742',
|
392 |
+
'-0.80901699437494742']
|
393 |
+
assert [str(r) for r in w] == [
|
394 |
+
'0.21707871342270599',
|
395 |
+
'0.56831944997474231',
|
396 |
+
'0.56831944997474231',
|
397 |
+
'0.21707871342270599']
|
398 |
+
|
399 |
+
x, w = gauss_chebyshev_u(5, 17)
|
400 |
+
assert [str(r) for r in x] == [
|
401 |
+
'0.86602540378443865',
|
402 |
+
'0.50000000000000000',
|
403 |
+
'0',
|
404 |
+
'-0.50000000000000000',
|
405 |
+
'-0.86602540378443865']
|
406 |
+
assert [str(r) for r in w] == [
|
407 |
+
'0.13089969389957472',
|
408 |
+
'0.39269908169872415',
|
409 |
+
'0.52359877559829887',
|
410 |
+
'0.39269908169872415',
|
411 |
+
'0.13089969389957472']
|
412 |
+
|
413 |
+
|
414 |
+
def test_chebyshev_u_precise():
|
415 |
+
x, w = gauss_chebyshev_u(3, 40)
|
416 |
+
assert [str(r) for r in x] == [
|
417 |
+
'0.7071067811865475244008443621048490392848',
|
418 |
+
'0',
|
419 |
+
'-0.7071067811865475244008443621048490392848']
|
420 |
+
assert [str(r) for r in w] == [
|
421 |
+
'0.3926990816987241548078304229099378605246',
|
422 |
+
'0.7853981633974483096156608458198757210493',
|
423 |
+
'0.3926990816987241548078304229099378605246']
|
424 |
+
|
425 |
+
|
426 |
+
def test_jacobi():
|
427 |
+
x, w = gauss_jacobi(1, Rational(-1, 2), S.Half, 17)
|
428 |
+
assert [str(r) for r in x] == ['0.50000000000000000']
|
429 |
+
assert [str(r) for r in w] == ['3.1415926535897932']
|
430 |
+
|
431 |
+
x, w = gauss_jacobi(2, Rational(-1, 2), S.Half, 17)
|
432 |
+
assert [str(r) for r in x] == [
|
433 |
+
'-0.30901699437494742',
|
434 |
+
'0.80901699437494742']
|
435 |
+
assert [str(r) for r in w] == [
|
436 |
+
'0.86831485369082398',
|
437 |
+
'2.2732777998989693']
|
438 |
+
|
439 |
+
x, w = gauss_jacobi(3, Rational(-1, 2), S.Half, 17)
|
440 |
+
assert [str(r) for r in x] == [
|
441 |
+
'-0.62348980185873353',
|
442 |
+
'0.22252093395631440',
|
443 |
+
'0.90096886790241913']
|
444 |
+
assert [str(r) for r in w] == [
|
445 |
+
'0.33795476356635433',
|
446 |
+
'1.0973322242791115',
|
447 |
+
'1.7063056657443274']
|
448 |
+
|
449 |
+
x, w = gauss_jacobi(4, Rational(-1, 2), S.Half, 17)
|
450 |
+
assert [str(r) for r in x] == [
|
451 |
+
'-0.76604444311897804',
|
452 |
+
'-0.17364817766693035',
|
453 |
+
'0.50000000000000000',
|
454 |
+
'0.93969262078590838']
|
455 |
+
assert [str(r) for r in w] == [
|
456 |
+
'0.16333179083642836',
|
457 |
+
'0.57690240318269103',
|
458 |
+
'1.0471975511965977',
|
459 |
+
'1.3541609083740761']
|
460 |
+
|
461 |
+
x, w = gauss_jacobi(5, Rational(-1, 2), S.Half, 17)
|
462 |
+
assert [str(r) for r in x] == [
|
463 |
+
'-0.84125353283118117',
|
464 |
+
'-0.41541501300188643',
|
465 |
+
'0.14231483827328514',
|
466 |
+
'0.65486073394528506',
|
467 |
+
'0.95949297361449739']
|
468 |
+
assert [str(r) for r in w] == [
|
469 |
+
'0.090675770007435372',
|
470 |
+
'0.33391416373675607',
|
471 |
+
'0.65248870981926643',
|
472 |
+
'0.94525424081394926',
|
473 |
+
'1.1192597692123861']
|
474 |
+
|
475 |
+
x, w = gauss_jacobi(1, 2, 3, 17)
|
476 |
+
assert [str(r) for r in x] == ['0.14285714285714286']
|
477 |
+
assert [str(r) for r in w] == ['1.0666666666666667']
|
478 |
+
|
479 |
+
x, w = gauss_jacobi(2, 2, 3, 17)
|
480 |
+
assert [str(r) for r in x] == [
|
481 |
+
'-0.24025307335204215',
|
482 |
+
'0.46247529557426437']
|
483 |
+
assert [str(r) for r in w] == [
|
484 |
+
'0.48514624517838660',
|
485 |
+
'0.58152042148828007']
|
486 |
+
|
487 |
+
x, w = gauss_jacobi(3, 2, 3, 17)
|
488 |
+
assert [str(r) for r in x] == [
|
489 |
+
'-0.46115870378089762',
|
490 |
+
'0.10438533038323902',
|
491 |
+
'0.62950064612493132']
|
492 |
+
assert [str(r) for r in w] == [
|
493 |
+
'0.17937613502213266',
|
494 |
+
'0.61595640991147154',
|
495 |
+
'0.27133412173306246']
|
496 |
+
|
497 |
+
x, w = gauss_jacobi(4, 2, 3, 17)
|
498 |
+
assert [str(r) for r in x] == [
|
499 |
+
'-0.59903470850824782',
|
500 |
+
'-0.14761105199952565',
|
501 |
+
'0.32554377081188859',
|
502 |
+
'0.72879429738819258']
|
503 |
+
assert [str(r) for r in w] == [
|
504 |
+
'0.067809641836772187',
|
505 |
+
'0.38956404952032481',
|
506 |
+
'0.47995970868024150',
|
507 |
+
'0.12933326662932816']
|
508 |
+
|
509 |
+
x, w = gauss_jacobi(5, 2, 3, 17)
|
510 |
+
assert [str(r) for r in x] == [
|
511 |
+
'-0.69045775012676106',
|
512 |
+
'-0.32651993134900065',
|
513 |
+
'0.082337849552034905',
|
514 |
+
'0.47517887061283164',
|
515 |
+
'0.79279429464422850']
|
516 |
+
assert [str(r) for r in w] == [
|
517 |
+
'0.027410178066337099',
|
518 |
+
'0.21291786060364828',
|
519 |
+
'0.43908437944395081',
|
520 |
+
'0.32220656547221822',
|
521 |
+
'0.065047683080512268']
|
522 |
+
|
523 |
+
|
524 |
+
def test_jacobi_precise():
|
525 |
+
x, w = gauss_jacobi(3, Rational(-1, 2), S.Half, 40)
|
526 |
+
assert [str(r) for r in x] == [
|
527 |
+
'-0.6234898018587335305250048840042398106323',
|
528 |
+
'0.2225209339563144042889025644967947594664',
|
529 |
+
'0.9009688679024191262361023195074450511659']
|
530 |
+
assert [str(r) for r in w] == [
|
531 |
+
'0.3379547635663543330553835737094171534907',
|
532 |
+
'1.097332224279111467485302294320899710461',
|
533 |
+
'1.706305665744327437921957515249186020246']
|
534 |
+
|
535 |
+
x, w = gauss_jacobi(3, 2, 3, 40)
|
536 |
+
assert [str(r) for r in x] == [
|
537 |
+
'-0.4611587037808976179121958105554375981274',
|
538 |
+
'0.1043853303832390210914918407615869143233',
|
539 |
+
'0.6295006461249313240934312425211234110769']
|
540 |
+
assert [str(r) for r in w] == [
|
541 |
+
'0.1793761350221326596137764371503859752628',
|
542 |
+
'0.6159564099114715430909548532229749439714',
|
543 |
+
'0.2713341217330624639619353762933057474325']
|
544 |
+
|
545 |
+
|
546 |
+
def test_lobatto():
|
547 |
+
x, w = gauss_lobatto(2, 17)
|
548 |
+
assert [str(r) for r in x] == [
|
549 |
+
'-1',
|
550 |
+
'1']
|
551 |
+
assert [str(r) for r in w] == [
|
552 |
+
'1.0000000000000000',
|
553 |
+
'1.0000000000000000']
|
554 |
+
|
555 |
+
x, w = gauss_lobatto(3, 17)
|
556 |
+
assert [str(r) for r in x] == [
|
557 |
+
'-1',
|
558 |
+
'0',
|
559 |
+
'1']
|
560 |
+
assert [str(r) for r in w] == [
|
561 |
+
'0.33333333333333333',
|
562 |
+
'1.3333333333333333',
|
563 |
+
'0.33333333333333333']
|
564 |
+
|
565 |
+
x, w = gauss_lobatto(4, 17)
|
566 |
+
assert [str(r) for r in x] == [
|
567 |
+
'-1',
|
568 |
+
'-0.44721359549995794',
|
569 |
+
'0.44721359549995794',
|
570 |
+
'1']
|
571 |
+
assert [str(r) for r in w] == [
|
572 |
+
'0.16666666666666667',
|
573 |
+
'0.83333333333333333',
|
574 |
+
'0.83333333333333333',
|
575 |
+
'0.16666666666666667']
|
576 |
+
|
577 |
+
x, w = gauss_lobatto(5, 17)
|
578 |
+
assert [str(r) for r in x] == [
|
579 |
+
'-1',
|
580 |
+
'-0.65465367070797714',
|
581 |
+
'0',
|
582 |
+
'0.65465367070797714',
|
583 |
+
'1']
|
584 |
+
assert [str(r) for r in w] == [
|
585 |
+
'0.10000000000000000',
|
586 |
+
'0.54444444444444444',
|
587 |
+
'0.71111111111111111',
|
588 |
+
'0.54444444444444444',
|
589 |
+
'0.10000000000000000']
|
590 |
+
|
591 |
+
|
592 |
+
def test_lobatto_precise():
|
593 |
+
x, w = gauss_lobatto(3, 40)
|
594 |
+
assert [str(r) for r in x] == [
|
595 |
+
'-1',
|
596 |
+
'0',
|
597 |
+
'1']
|
598 |
+
assert [str(r) for r in w] == [
|
599 |
+
'0.3333333333333333333333333333333333333333',
|
600 |
+
'1.333333333333333333333333333333333333333',
|
601 |
+
'0.3333333333333333333333333333333333333333']
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_rationaltools.py
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import (I, Rational)
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core.symbol import (Dummy, symbols)
|
4 |
+
from sympy.functions.elementary.exponential import log
|
5 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
6 |
+
from sympy.functions.elementary.trigonometric import atan
|
7 |
+
from sympy.integrals.integrals import integrate
|
8 |
+
from sympy.polys.polytools import Poly
|
9 |
+
from sympy.simplify.simplify import simplify
|
10 |
+
|
11 |
+
from sympy.integrals.rationaltools import ratint, ratint_logpart, log_to_atan
|
12 |
+
|
13 |
+
from sympy.abc import a, b, x, t
|
14 |
+
|
15 |
+
half = S.Half
|
16 |
+
|
17 |
+
|
18 |
+
def test_ratint():
|
19 |
+
assert ratint(S.Zero, x) == 0
|
20 |
+
assert ratint(S(7), x) == 7*x
|
21 |
+
|
22 |
+
assert ratint(x, x) == x**2/2
|
23 |
+
assert ratint(2*x, x) == x**2
|
24 |
+
assert ratint(-2*x, x) == -x**2
|
25 |
+
|
26 |
+
assert ratint(8*x**7 + 2*x + 1, x) == x**8 + x**2 + x
|
27 |
+
|
28 |
+
f = S.One
|
29 |
+
g = x + 1
|
30 |
+
|
31 |
+
assert ratint(f / g, x) == log(x + 1)
|
32 |
+
assert ratint((f, g), x) == log(x + 1)
|
33 |
+
|
34 |
+
f = x**3 - x
|
35 |
+
g = x - 1
|
36 |
+
|
37 |
+
assert ratint(f/g, x) == x**3/3 + x**2/2
|
38 |
+
|
39 |
+
f = x
|
40 |
+
g = (x - a)*(x + a)
|
41 |
+
|
42 |
+
assert ratint(f/g, x) == log(x**2 - a**2)/2
|
43 |
+
|
44 |
+
f = S.One
|
45 |
+
g = x**2 + 1
|
46 |
+
|
47 |
+
assert ratint(f/g, x, real=None) == atan(x)
|
48 |
+
assert ratint(f/g, x, real=True) == atan(x)
|
49 |
+
|
50 |
+
assert ratint(f/g, x, real=False) == I*log(x + I)/2 - I*log(x - I)/2
|
51 |
+
|
52 |
+
f = S(36)
|
53 |
+
g = x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2
|
54 |
+
|
55 |
+
assert ratint(f/g, x) == \
|
56 |
+
-4*log(x + 1) + 4*log(x - 2) + (12*x + 6)/(x**2 - 1)
|
57 |
+
|
58 |
+
f = x**4 - 3*x**2 + 6
|
59 |
+
g = x**6 - 5*x**4 + 5*x**2 + 4
|
60 |
+
|
61 |
+
assert ratint(f/g, x) == \
|
62 |
+
atan(x) + atan(x**3) + atan(x/2 - Rational(3, 2)*x**3 + S.Half*x**5)
|
63 |
+
|
64 |
+
f = x**7 - 24*x**4 - 4*x**2 + 8*x - 8
|
65 |
+
g = x**8 + 6*x**6 + 12*x**4 + 8*x**2
|
66 |
+
|
67 |
+
assert ratint(f/g, x) == \
|
68 |
+
(4 + 6*x + 8*x**2 + 3*x**3)/(4*x + 4*x**3 + x**5) + log(x)
|
69 |
+
|
70 |
+
assert ratint((x**3*f)/(x*g), x) == \
|
71 |
+
-(12 - 16*x + 6*x**2 - 14*x**3)/(4 + 4*x**2 + x**4) - \
|
72 |
+
5*sqrt(2)*atan(x*sqrt(2)/2) + S.Half*x**2 - 3*log(2 + x**2)
|
73 |
+
|
74 |
+
f = x**5 - x**4 + 4*x**3 + x**2 - x + 5
|
75 |
+
g = x**4 - 2*x**3 + 5*x**2 - 4*x + 4
|
76 |
+
|
77 |
+
assert ratint(f/g, x) == \
|
78 |
+
x + S.Half*x**2 + S.Half*log(2 - x + x**2) + (9 - 4*x)/(7*x**2 - 7*x + 14) + \
|
79 |
+
13*sqrt(7)*atan(Rational(-1, 7)*sqrt(7) + 2*x*sqrt(7)/7)/49
|
80 |
+
|
81 |
+
assert ratint(1/(x**2 + x + 1), x) == \
|
82 |
+
2*sqrt(3)*atan(sqrt(3)/3 + 2*x*sqrt(3)/3)/3
|
83 |
+
|
84 |
+
assert ratint(1/(x**3 + 1), x) == \
|
85 |
+
-log(1 - x + x**2)/6 + log(1 + x)/3 + sqrt(3)*atan(-sqrt(3)
|
86 |
+
/3 + 2*x*sqrt(3)/3)/3
|
87 |
+
|
88 |
+
assert ratint(1/(x**2 + x + 1), x, real=False) == \
|
89 |
+
-I*3**half*log(half + x - half*I*3**half)/3 + \
|
90 |
+
I*3**half*log(half + x + half*I*3**half)/3
|
91 |
+
|
92 |
+
assert ratint(1/(x**3 + 1), x, real=False) == log(1 + x)/3 + \
|
93 |
+
(Rational(-1, 6) + I*3**half/6)*log(-half + x + I*3**half/2) + \
|
94 |
+
(Rational(-1, 6) - I*3**half/6)*log(-half + x - I*3**half/2)
|
95 |
+
|
96 |
+
# issue 4991
|
97 |
+
assert ratint(1/(x*(a + b*x)**3), x) == \
|
98 |
+
(3*a + 2*b*x)/(2*a**4 + 4*a**3*b*x + 2*a**2*b**2*x**2) + (
|
99 |
+
log(x) - log(a/b + x))/a**3
|
100 |
+
|
101 |
+
assert ratint(x/(1 - x**2), x) == -log(x**2 - 1)/2
|
102 |
+
assert ratint(-x/(1 - x**2), x) == log(x**2 - 1)/2
|
103 |
+
|
104 |
+
assert ratint((x/4 - 4/(1 - x)).diff(x), x) == x/4 + 4/(x - 1)
|
105 |
+
|
106 |
+
ans = atan(x)
|
107 |
+
assert ratint(1/(x**2 + 1), x, symbol=x) == ans
|
108 |
+
assert ratint(1/(x**2 + 1), x, symbol='x') == ans
|
109 |
+
assert ratint(1/(x**2 + 1), x, symbol=a) == ans
|
110 |
+
# this asserts that as_dummy must return a unique symbol
|
111 |
+
# even if the symbol is already a Dummy
|
112 |
+
d = Dummy()
|
113 |
+
assert ratint(1/(d**2 + 1), d, symbol=d) == atan(d)
|
114 |
+
|
115 |
+
|
116 |
+
def test_ratint_logpart():
|
117 |
+
assert ratint_logpart(x, x**2 - 9, x, t) == \
|
118 |
+
[(Poly(x**2 - 9, x), Poly(-2*t + 1, t))]
|
119 |
+
assert ratint_logpart(x**2, x**3 - 5, x, t) == \
|
120 |
+
[(Poly(x**3 - 5, x), Poly(-3*t + 1, t))]
|
121 |
+
|
122 |
+
|
123 |
+
def test_issue_5414():
|
124 |
+
assert ratint(1/(x**2 + 16), x) == atan(x/4)/4
|
125 |
+
|
126 |
+
|
127 |
+
def test_issue_5249():
|
128 |
+
assert ratint(
|
129 |
+
1/(x**2 + a**2), x) == (-I*log(-I*a + x)/2 + I*log(I*a + x)/2)/a
|
130 |
+
|
131 |
+
|
132 |
+
def test_issue_5817():
|
133 |
+
a, b, c = symbols('a,b,c', positive=True)
|
134 |
+
|
135 |
+
assert simplify(ratint(a/(b*c*x**2 + a**2 + b*a), x)) == \
|
136 |
+
sqrt(a)*atan(sqrt(
|
137 |
+
b)*sqrt(c)*x/(sqrt(a)*sqrt(a + b)))/(sqrt(b)*sqrt(c)*sqrt(a + b))
|
138 |
+
|
139 |
+
|
140 |
+
def test_issue_5981():
|
141 |
+
u = symbols('u')
|
142 |
+
assert integrate(1/(u**2 + 1)) == atan(u)
|
143 |
+
|
144 |
+
def test_issue_10488():
|
145 |
+
a,b,c,x = symbols('a b c x', positive=True)
|
146 |
+
assert integrate(x/(a*x+b),x) == x/a - b*log(a*x + b)/a**2
|
147 |
+
|
148 |
+
|
149 |
+
def test_issues_8246_12050_13501_14080():
|
150 |
+
a = symbols('a', nonzero=True)
|
151 |
+
assert integrate(a/(x**2 + a**2), x) == atan(x/a)
|
152 |
+
assert integrate(1/(x**2 + a**2), x) == atan(x/a)/a
|
153 |
+
assert integrate(1/(1 + a**2*x**2), x) == atan(a*x)/a
|
154 |
+
|
155 |
+
|
156 |
+
def test_issue_6308():
|
157 |
+
k, a0 = symbols('k a0', real=True)
|
158 |
+
assert integrate((x**2 + 1 - k**2)/(x**2 + 1 + a0**2), x) == \
|
159 |
+
x - (a0**2 + k**2)*atan(x/sqrt(a0**2 + 1))/sqrt(a0**2 + 1)
|
160 |
+
|
161 |
+
|
162 |
+
def test_issue_5907():
|
163 |
+
a = symbols('a', nonzero=True)
|
164 |
+
assert integrate(1/(x**2 + a**2)**2, x) == \
|
165 |
+
x/(2*a**4 + 2*a**2*x**2) + atan(x/a)/(2*a**3)
|
166 |
+
|
167 |
+
|
168 |
+
def test_log_to_atan():
|
169 |
+
f, g = (Poly(x + S.Half, x, domain='QQ'), Poly(sqrt(3)/2, x, domain='EX'))
|
170 |
+
fg_ans = 2*atan(2*sqrt(3)*x/3 + sqrt(3)/3)
|
171 |
+
assert log_to_atan(f, g) == fg_ans
|
172 |
+
assert log_to_atan(g, f) == -fg_ans
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_rde.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Most of these tests come from the examples in Bronstein's book."""
|
2 |
+
from sympy.core.numbers import (I, Rational, oo)
|
3 |
+
from sympy.core.symbol import symbols
|
4 |
+
from sympy.polys.polytools import Poly
|
5 |
+
from sympy.integrals.risch import (DifferentialExtension,
|
6 |
+
NonElementaryIntegralException)
|
7 |
+
from sympy.integrals.rde import (order_at, order_at_oo, weak_normalizer,
|
8 |
+
normal_denom, special_denom, bound_degree, spde, solve_poly_rde,
|
9 |
+
no_cancel_equal, cancel_primitive, cancel_exp, rischDE)
|
10 |
+
|
11 |
+
from sympy.testing.pytest import raises
|
12 |
+
from sympy.abc import x, t, z, n
|
13 |
+
|
14 |
+
t0, t1, t2, k = symbols('t:3 k')
|
15 |
+
|
16 |
+
|
17 |
+
def test_order_at():
|
18 |
+
a = Poly(t**4, t)
|
19 |
+
b = Poly((t**2 + 1)**3*t, t)
|
20 |
+
c = Poly((t**2 + 1)**6*t, t)
|
21 |
+
d = Poly((t**2 + 1)**10*t**10, t)
|
22 |
+
e = Poly((t**2 + 1)**100*t**37, t)
|
23 |
+
p1 = Poly(t, t)
|
24 |
+
p2 = Poly(1 + t**2, t)
|
25 |
+
assert order_at(a, p1, t) == 4
|
26 |
+
assert order_at(b, p1, t) == 1
|
27 |
+
assert order_at(c, p1, t) == 1
|
28 |
+
assert order_at(d, p1, t) == 10
|
29 |
+
assert order_at(e, p1, t) == 37
|
30 |
+
assert order_at(a, p2, t) == 0
|
31 |
+
assert order_at(b, p2, t) == 3
|
32 |
+
assert order_at(c, p2, t) == 6
|
33 |
+
assert order_at(d, p1, t) == 10
|
34 |
+
assert order_at(e, p2, t) == 100
|
35 |
+
assert order_at(Poly(0, t), Poly(t, t), t) is oo
|
36 |
+
assert order_at_oo(Poly(t**2 - 1, t), Poly(t + 1), t) == \
|
37 |
+
order_at_oo(Poly(t - 1, t), Poly(1, t), t) == -1
|
38 |
+
assert order_at_oo(Poly(0, t), Poly(1, t), t) is oo
|
39 |
+
|
40 |
+
def test_weak_normalizer():
|
41 |
+
a = Poly((1 + x)*t**5 + 4*t**4 + (-1 - 3*x)*t**3 - 4*t**2 + (-2 + 2*x)*t, t)
|
42 |
+
d = Poly(t**4 - 3*t**2 + 2, t)
|
43 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
44 |
+
r = weak_normalizer(a, d, DE, z)
|
45 |
+
assert r == (Poly(t**5 - t**4 - 4*t**3 + 4*t**2 + 4*t - 4, t, domain='ZZ[x]'),
|
46 |
+
(Poly((1 + x)*t**2 + x*t, t, domain='ZZ[x]'),
|
47 |
+
Poly(t + 1, t, domain='ZZ[x]')))
|
48 |
+
assert weak_normalizer(r[1][0], r[1][1], DE) == (Poly(1, t), r[1])
|
49 |
+
r = weak_normalizer(Poly(1 + t**2), Poly(t**2 - 1, t), DE, z)
|
50 |
+
assert r == (Poly(t**4 - 2*t**2 + 1, t), (Poly(-3*t**2 + 1, t), Poly(t**2 - 1, t)))
|
51 |
+
assert weak_normalizer(r[1][0], r[1][1], DE, z) == (Poly(1, t), r[1])
|
52 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2)]})
|
53 |
+
r = weak_normalizer(Poly(1 + t**2), Poly(t, t), DE, z)
|
54 |
+
assert r == (Poly(t, t), (Poly(0, t), Poly(1, t)))
|
55 |
+
assert weak_normalizer(r[1][0], r[1][1], DE, z) == (Poly(1, t), r[1])
|
56 |
+
|
57 |
+
|
58 |
+
def test_normal_denom():
|
59 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
60 |
+
raises(NonElementaryIntegralException, lambda: normal_denom(Poly(1, x), Poly(1, x),
|
61 |
+
Poly(1, x), Poly(x, x), DE))
|
62 |
+
fa, fd = Poly(t**2 + 1, t), Poly(1, t)
|
63 |
+
ga, gd = Poly(1, t), Poly(t**2, t)
|
64 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
65 |
+
assert normal_denom(fa, fd, ga, gd, DE) == \
|
66 |
+
(Poly(t, t), (Poly(t**3 - t**2 + t - 1, t), Poly(1, t)), (Poly(1, t),
|
67 |
+
Poly(1, t)), Poly(t, t))
|
68 |
+
|
69 |
+
|
70 |
+
def test_special_denom():
|
71 |
+
# TODO: add more tests here
|
72 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
73 |
+
assert special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t),
|
74 |
+
Poly(t, t), DE) == \
|
75 |
+
(Poly(1, t), Poly(t**2 - 1, t), Poly(t**2 - 1, t), Poly(t, t))
|
76 |
+
# assert special_denom(Poly(1, t), Poly(2*x, t), Poly((1 + 2*x)*t, t), DE) == 1
|
77 |
+
|
78 |
+
# issue 3940
|
79 |
+
# Note, this isn't a very good test, because the denominator is just 1,
|
80 |
+
# but at least it tests the exp cancellation case
|
81 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-2*x*t0, t0),
|
82 |
+
Poly(I*k*t1, t1)]})
|
83 |
+
DE.decrement_level()
|
84 |
+
assert special_denom(Poly(1, t0), Poly(I*k, t0), Poly(1, t0), Poly(t0, t0),
|
85 |
+
Poly(1, t0), DE) == \
|
86 |
+
(Poly(1, t0, domain='ZZ'), Poly(I*k, t0, domain='ZZ_I[k,x]'),
|
87 |
+
Poly(t0, t0, domain='ZZ'), Poly(1, t0, domain='ZZ'))
|
88 |
+
|
89 |
+
|
90 |
+
assert special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t),
|
91 |
+
Poly(t, t), DE, case='tan') == \
|
92 |
+
(Poly(1, t, t0, domain='ZZ'), Poly(t**2, t0, t, domain='ZZ[x]'),
|
93 |
+
Poly(t, t, t0, domain='ZZ'), Poly(1, t0, domain='ZZ'))
|
94 |
+
|
95 |
+
raises(ValueError, lambda: special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t),
|
96 |
+
Poly(t, t), DE, case='unrecognized_case'))
|
97 |
+
|
98 |
+
|
99 |
+
def test_bound_degree_fail():
|
100 |
+
# Primitive
|
101 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x),
|
102 |
+
Poly(t0/x**2, t0), Poly(1/x, t)]})
|
103 |
+
assert bound_degree(Poly(t**2, t), Poly(-(1/x**2*t**2 + 1/x), t),
|
104 |
+
Poly((2*x - 1)*t**4 + (t0 + x)/x*t**3 - (t0 + 4*x**2)/2*x*t**2 + x*t,
|
105 |
+
t), DE) == 3
|
106 |
+
|
107 |
+
|
108 |
+
def test_bound_degree():
|
109 |
+
# Base
|
110 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
111 |
+
assert bound_degree(Poly(1, x), Poly(-2*x, x), Poly(1, x), DE) == 0
|
112 |
+
|
113 |
+
# Primitive (see above test_bound_degree_fail)
|
114 |
+
# TODO: Add test for when the degree bound becomes larger after limited_integrate
|
115 |
+
# TODO: Add test for db == da - 1 case
|
116 |
+
|
117 |
+
# Exp
|
118 |
+
# TODO: Add tests
|
119 |
+
# TODO: Add test for when the degree becomes larger after parametric_log_deriv()
|
120 |
+
|
121 |
+
# Nonlinear
|
122 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
123 |
+
assert bound_degree(Poly(t, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), DE) == 0
|
124 |
+
|
125 |
+
|
126 |
+
def test_spde():
|
127 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
128 |
+
raises(NonElementaryIntegralException, lambda: spde(Poly(t, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), 0, DE))
|
129 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
130 |
+
assert spde(Poly(t**2 + x*t*2 + x**2, t), Poly(t**2/x**2 + (2/x - 1)*t, t),
|
131 |
+
Poly(t**2/x**2 + (2/x - 1)*t, t), 0, DE) == \
|
132 |
+
(Poly(0, t), Poly(0, t), 0, Poly(0, t), Poly(1, t, domain='ZZ(x)'))
|
133 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0/x**2, t0), Poly(1/x, t)]})
|
134 |
+
assert spde(Poly(t**2, t), Poly(-t**2/x**2 - 1/x, t),
|
135 |
+
Poly((2*x - 1)*t**4 + (t0 + x)/x*t**3 - (t0 + 4*x**2)/(2*x)*t**2 + x*t, t), 3, DE) == \
|
136 |
+
(Poly(0, t), Poly(0, t), 0, Poly(0, t),
|
137 |
+
Poly(t0*t**2/2 + x**2*t**2 - x**2*t, t, domain='ZZ(x,t0)'))
|
138 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
139 |
+
assert spde(Poly(x**2 + x + 1, x), Poly(-2*x - 1, x), Poly(x**5/2 +
|
140 |
+
3*x**4/4 + x**3 - x**2 + 1, x), 4, DE) == \
|
141 |
+
(Poly(0, x, domain='QQ'), Poly(x/2 - Rational(1, 4), x), 2, Poly(x**2 + x + 1, x), Poly(x*Rational(5, 4), x))
|
142 |
+
assert spde(Poly(x**2 + x + 1, x), Poly(-2*x - 1, x), Poly(x**5/2 +
|
143 |
+
3*x**4/4 + x**3 - x**2 + 1, x), n, DE) == \
|
144 |
+
(Poly(0, x, domain='QQ'), Poly(x/2 - Rational(1, 4), x), -2 + n, Poly(x**2 + x + 1, x), Poly(x*Rational(5, 4), x))
|
145 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1, t)]})
|
146 |
+
raises(NonElementaryIntegralException, lambda: spde(Poly((t - 1)*(t**2 + 1)**2, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), 0, DE))
|
147 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
148 |
+
assert spde(Poly(x**2 - x, x), Poly(1, x), Poly(9*x**4 - 10*x**3 + 2*x**2, x), 4, DE) == \
|
149 |
+
(Poly(0, x, domain='ZZ'), Poly(0, x), 0, Poly(0, x), Poly(3*x**3 - 2*x**2, x, domain='QQ'))
|
150 |
+
assert spde(Poly(x**2 - x, x), Poly(x**2 - 5*x + 3, x), Poly(x**7 - x**6 - 2*x**4 + 3*x**3 - x**2, x), 5, DE) == \
|
151 |
+
(Poly(1, x, domain='QQ'), Poly(x + 1, x, domain='QQ'), 1, Poly(x**4 - x**3, x), Poly(x**3 - x**2, x, domain='QQ'))
|
152 |
+
|
153 |
+
def test_solve_poly_rde_no_cancel():
|
154 |
+
# deg(b) large
|
155 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
|
156 |
+
assert solve_poly_rde(Poly(t**2 + 1, t), Poly(t**3 + (x + 1)*t**2 + t + x + 2, t),
|
157 |
+
oo, DE) == Poly(t + x, t)
|
158 |
+
# deg(b) small
|
159 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
160 |
+
assert solve_poly_rde(Poly(0, x), Poly(x/2 - Rational(1, 4), x), oo, DE) == \
|
161 |
+
Poly(x**2/4 - x/4, x)
|
162 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
163 |
+
assert solve_poly_rde(Poly(2, t), Poly(t**2 + 2*t + 3, t), 1, DE) == \
|
164 |
+
Poly(t + 1, t, x)
|
165 |
+
# deg(b) == deg(D) - 1
|
166 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
167 |
+
assert no_cancel_equal(Poly(1 - t, t),
|
168 |
+
Poly(t**3 + t**2 - 2*x*t - 2*x, t), oo, DE) == \
|
169 |
+
(Poly(t**2, t), 1, Poly((-2 - 2*x)*t - 2*x, t))
|
170 |
+
|
171 |
+
|
172 |
+
def test_solve_poly_rde_cancel():
|
173 |
+
# exp
|
174 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
175 |
+
assert cancel_exp(Poly(2*x, t), Poly(2*x, t), 0, DE) == \
|
176 |
+
Poly(1, t)
|
177 |
+
assert cancel_exp(Poly(2*x, t), Poly((1 + 2*x)*t, t), 1, DE) == \
|
178 |
+
Poly(t, t)
|
179 |
+
# TODO: Add more exp tests, including tests that require is_deriv_in_field()
|
180 |
+
|
181 |
+
# primitive
|
182 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
183 |
+
|
184 |
+
# If the DecrementLevel context manager is working correctly, this shouldn't
|
185 |
+
# cause any problems with the further tests.
|
186 |
+
raises(NonElementaryIntegralException, lambda: cancel_primitive(Poly(1, t), Poly(t, t), oo, DE))
|
187 |
+
|
188 |
+
assert cancel_primitive(Poly(1, t), Poly(t + 1/x, t), 2, DE) == \
|
189 |
+
Poly(t, t)
|
190 |
+
assert cancel_primitive(Poly(4*x, t), Poly(4*x*t**2 + 2*t/x, t), 3, DE) == \
|
191 |
+
Poly(t**2, t)
|
192 |
+
|
193 |
+
# TODO: Add more primitive tests, including tests that require is_deriv_in_field()
|
194 |
+
|
195 |
+
|
196 |
+
def test_rischDE():
|
197 |
+
# TODO: Add more tests for rischDE, including ones from the text
|
198 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
199 |
+
DE.decrement_level()
|
200 |
+
assert rischDE(Poly(-2*x, x), Poly(1, x), Poly(1 - 2*x - 2*x**2, x),
|
201 |
+
Poly(1, x), DE) == \
|
202 |
+
(Poly(x + 1, x), Poly(1, x))
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_risch.py
ADDED
@@ -0,0 +1,763 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Most of these tests come from the examples in Bronstein's book."""
|
2 |
+
from sympy.core.function import (Function, Lambda, diff, expand_log)
|
3 |
+
from sympy.core.numbers import (I, Rational, pi)
|
4 |
+
from sympy.core.relational import Ne
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.core.symbol import (Symbol, symbols)
|
7 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
8 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
9 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
10 |
+
from sympy.functions.elementary.trigonometric import (atan, sin, tan)
|
11 |
+
from sympy.polys.polytools import (Poly, cancel, factor)
|
12 |
+
from sympy.integrals.risch import (gcdex_diophantine, frac_in, as_poly_1t,
|
13 |
+
derivation, splitfactor, splitfactor_sqf, canonical_representation,
|
14 |
+
hermite_reduce, polynomial_reduce, residue_reduce, residue_reduce_to_basic,
|
15 |
+
integrate_primitive, integrate_hyperexponential_polynomial,
|
16 |
+
integrate_hyperexponential, integrate_hypertangent_polynomial,
|
17 |
+
integrate_nonlinear_no_specials, integer_powers, DifferentialExtension,
|
18 |
+
risch_integrate, DecrementLevel, NonElementaryIntegral, recognize_log_derivative,
|
19 |
+
recognize_derivative, laurent_series)
|
20 |
+
from sympy.testing.pytest import raises
|
21 |
+
|
22 |
+
from sympy.abc import x, t, nu, z, a, y
|
23 |
+
t0, t1, t2 = symbols('t:3')
|
24 |
+
i = Symbol('i')
|
25 |
+
|
26 |
+
def test_gcdex_diophantine():
|
27 |
+
assert gcdex_diophantine(Poly(x**4 - 2*x**3 - 6*x**2 + 12*x + 15),
|
28 |
+
Poly(x**3 + x**2 - 4*x - 4), Poly(x**2 - 1)) == \
|
29 |
+
(Poly((-x**2 + 4*x - 3)/5), Poly((x**3 - 7*x**2 + 16*x - 10)/5))
|
30 |
+
assert gcdex_diophantine(Poly(x**3 + 6*x + 7), Poly(x**2 + 3*x + 2), Poly(x + 1)) == \
|
31 |
+
(Poly(1/13, x, domain='QQ'), Poly(-1/13*x + 3/13, x, domain='QQ'))
|
32 |
+
|
33 |
+
|
34 |
+
def test_frac_in():
|
35 |
+
assert frac_in(Poly((x + 1)/x*t, t), x) == \
|
36 |
+
(Poly(t*x + t, x), Poly(x, x))
|
37 |
+
assert frac_in((x + 1)/x*t, x) == \
|
38 |
+
(Poly(t*x + t, x), Poly(x, x))
|
39 |
+
assert frac_in((Poly((x + 1)/x*t, t), Poly(t + 1, t)), x) == \
|
40 |
+
(Poly(t*x + t, x), Poly((1 + t)*x, x))
|
41 |
+
raises(ValueError, lambda: frac_in((x + 1)/log(x)*t, x))
|
42 |
+
assert frac_in(Poly((2 + 2*x + x*(1 + x))/(1 + x)**2, t), x, cancel=True) == \
|
43 |
+
(Poly(x + 2, x), Poly(x + 1, x))
|
44 |
+
|
45 |
+
|
46 |
+
def test_as_poly_1t():
|
47 |
+
assert as_poly_1t(2/t + t, t, z) in [
|
48 |
+
Poly(t + 2*z, t, z), Poly(t + 2*z, z, t)]
|
49 |
+
assert as_poly_1t(2/t + 3/t**2, t, z) in [
|
50 |
+
Poly(2*z + 3*z**2, t, z), Poly(2*z + 3*z**2, z, t)]
|
51 |
+
assert as_poly_1t(2/((exp(2) + 1)*t), t, z) in [
|
52 |
+
Poly(2/(exp(2) + 1)*z, t, z), Poly(2/(exp(2) + 1)*z, z, t)]
|
53 |
+
assert as_poly_1t(2/((exp(2) + 1)*t) + t, t, z) in [
|
54 |
+
Poly(t + 2/(exp(2) + 1)*z, t, z), Poly(t + 2/(exp(2) + 1)*z, z, t)]
|
55 |
+
assert as_poly_1t(S.Zero, t, z) == Poly(0, t, z)
|
56 |
+
|
57 |
+
|
58 |
+
def test_derivation():
|
59 |
+
p = Poly(4*x**4*t**5 + (-4*x**3 - 4*x**4)*t**4 + (-3*x**2 + 2*x**3)*t**3 +
|
60 |
+
(2*x + 7*x**2 + 2*x**3)*t**2 + (1 - 4*x - 4*x**2)*t - 1 + 2*x, t)
|
61 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - 3/(2*x)*t + 1/(2*x), t)]})
|
62 |
+
assert derivation(p, DE) == Poly(-20*x**4*t**6 + (2*x**3 + 16*x**4)*t**5 +
|
63 |
+
(21*x**2 + 12*x**3)*t**4 + (x*Rational(7, 2) - 25*x**2 - 12*x**3)*t**3 +
|
64 |
+
(-5 - x*Rational(15, 2) + 7*x**2)*t**2 - (3 - 8*x - 10*x**2 - 4*x**3)/(2*x)*t +
|
65 |
+
(1 - 4*x**2)/(2*x), t)
|
66 |
+
assert derivation(Poly(1, t), DE) == Poly(0, t)
|
67 |
+
assert derivation(Poly(t, t), DE) == DE.d
|
68 |
+
assert derivation(Poly(t**2 + 1/x*t + (1 - 2*x)/(4*x**2), t), DE) == \
|
69 |
+
Poly(-2*t**3 - 4/x*t**2 - (5 - 2*x)/(2*x**2)*t - (1 - 2*x)/(2*x**3), t, domain='ZZ(x)')
|
70 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(t, t)]})
|
71 |
+
assert derivation(Poly(x*t*t1, t), DE) == Poly(t*t1 + x*t*t1 + t, t)
|
72 |
+
assert derivation(Poly(x*t*t1, t), DE, coefficientD=True) == \
|
73 |
+
Poly((1 + t1)*t, t)
|
74 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
75 |
+
assert derivation(Poly(x, x), DE) == Poly(1, x)
|
76 |
+
# Test basic option
|
77 |
+
assert derivation((x + 1)/(x - 1), DE, basic=True) == -2/(1 - 2*x + x**2)
|
78 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
79 |
+
assert derivation((t + 1)/(t - 1), DE, basic=True) == -2*t/(1 - 2*t + t**2)
|
80 |
+
assert derivation(t + 1, DE, basic=True) == t
|
81 |
+
|
82 |
+
|
83 |
+
def test_splitfactor():
|
84 |
+
p = Poly(4*x**4*t**5 + (-4*x**3 - 4*x**4)*t**4 + (-3*x**2 + 2*x**3)*t**3 +
|
85 |
+
(2*x + 7*x**2 + 2*x**3)*t**2 + (1 - 4*x - 4*x**2)*t - 1 + 2*x, t, field=True)
|
86 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - 3/(2*x)*t + 1/(2*x), t)]})
|
87 |
+
assert splitfactor(p, DE) == (Poly(4*x**4*t**3 + (-8*x**3 - 4*x**4)*t**2 +
|
88 |
+
(4*x**2 + 8*x**3)*t - 4*x**2, t, domain='ZZ(x)'),
|
89 |
+
Poly(t**2 + 1/x*t + (1 - 2*x)/(4*x**2), t, domain='ZZ(x)'))
|
90 |
+
assert splitfactor(Poly(x, t), DE) == (Poly(x, t), Poly(1, t))
|
91 |
+
r = Poly(-4*x**4*z**2 + 4*x**6*z**2 - z*x**3 - 4*x**5*z**3 + 4*x**3*z**3 + x**4 + z*x**5 - x**6, t)
|
92 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
93 |
+
assert splitfactor(r, DE, coefficientD=True) == \
|
94 |
+
(Poly(x*z - x**2 - z*x**3 + x**4, t), Poly(-x**2 + 4*x**2*z**2, t))
|
95 |
+
assert splitfactor_sqf(r, DE, coefficientD=True) == \
|
96 |
+
(((Poly(x*z - x**2 - z*x**3 + x**4, t), 1),), ((Poly(-x**2 + 4*x**2*z**2, t), 1),))
|
97 |
+
assert splitfactor(Poly(0, t), DE) == (Poly(0, t), Poly(1, t))
|
98 |
+
assert splitfactor_sqf(Poly(0, t), DE) == (((Poly(0, t), 1),), ())
|
99 |
+
|
100 |
+
|
101 |
+
def test_canonical_representation():
|
102 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
|
103 |
+
assert canonical_representation(Poly(x - t, t), Poly(t**2, t), DE) == \
|
104 |
+
(Poly(0, t, domain='ZZ[x]'), (Poly(0, t, domain='QQ[x]'),
|
105 |
+
Poly(1, t, domain='ZZ')), (Poly(-t + x, t, domain='QQ[x]'),
|
106 |
+
Poly(t**2, t)))
|
107 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
108 |
+
assert canonical_representation(Poly(t**5 + t**3 + x**2*t + 1, t),
|
109 |
+
Poly((t**2 + 1)**3, t), DE) == \
|
110 |
+
(Poly(0, t, domain='ZZ[x]'), (Poly(t**5 + t**3 + x**2*t + 1, t, domain='QQ[x]'),
|
111 |
+
Poly(t**6 + 3*t**4 + 3*t**2 + 1, t, domain='QQ')),
|
112 |
+
(Poly(0, t, domain='QQ[x]'), Poly(1, t, domain='QQ')))
|
113 |
+
|
114 |
+
|
115 |
+
def test_hermite_reduce():
|
116 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
117 |
+
|
118 |
+
assert hermite_reduce(Poly(x - t, t), Poly(t**2, t), DE) == \
|
119 |
+
((Poly(-x, t, domain='QQ[x]'), Poly(t, t, domain='QQ[x]')),
|
120 |
+
(Poly(0, t, domain='QQ[x]'), Poly(1, t, domain='QQ[x]')),
|
121 |
+
(Poly(-x, t, domain='QQ[x]'), Poly(1, t, domain='QQ[x]')))
|
122 |
+
|
123 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - t/x - (1 - nu**2/x**2), t)]})
|
124 |
+
|
125 |
+
assert hermite_reduce(
|
126 |
+
Poly(x**2*t**5 + x*t**4 - nu**2*t**3 - x*(x**2 + 1)*t**2 - (x**2 - nu**2)*t - x**5/4, t),
|
127 |
+
Poly(x**2*t**4 + x**2*(x**2 + 2)*t**2 + x**2 + x**4 + x**6/4, t), DE) == \
|
128 |
+
((Poly(-x**2 - 4, t, domain='ZZ(x,nu)'), Poly(4*t**2 + 2*x**2 + 4, t, domain='ZZ(x,nu)')),
|
129 |
+
(Poly((-2*nu**2 - x**4)*t - (2*x**3 + 2*x), t, domain='ZZ(x,nu)'),
|
130 |
+
Poly(2*x**2*t**2 + x**4 + 2*x**2, t, domain='ZZ(x,nu)')),
|
131 |
+
(Poly(x*t + 1, t, domain='ZZ(x,nu)'), Poly(x, t, domain='ZZ(x,nu)')))
|
132 |
+
|
133 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
134 |
+
|
135 |
+
a = Poly((-2 + 3*x)*t**3 + (-1 + x)*t**2 + (-4*x + 2*x**2)*t + x**2, t)
|
136 |
+
d = Poly(x*t**6 - 4*x**2*t**5 + 6*x**3*t**4 - 4*x**4*t**3 + x**5*t**2, t)
|
137 |
+
|
138 |
+
assert hermite_reduce(a, d, DE) == \
|
139 |
+
((Poly(3*t**2 + t + 3*x, t, domain='ZZ(x)'),
|
140 |
+
Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t, domain='ZZ(x)')),
|
141 |
+
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
|
142 |
+
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')))
|
143 |
+
|
144 |
+
assert hermite_reduce(
|
145 |
+
Poly(-t**2 + 2*t + 2, t, domain='ZZ(x)'),
|
146 |
+
Poly(-x*t**2 + 2*x*t - x, t, domain='ZZ(x)'), DE) == \
|
147 |
+
((Poly(3, t, domain='ZZ(x)'), Poly(t - 1, t, domain='ZZ(x)')),
|
148 |
+
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
|
149 |
+
(Poly(1, t, domain='ZZ(x)'), Poly(x, t, domain='ZZ(x)')))
|
150 |
+
|
151 |
+
assert hermite_reduce(
|
152 |
+
Poly(-x**2*t**6 + (-1 - 2*x**3 + x**4)*t**3 + (-3 - 3*x**4)*t**2 -
|
153 |
+
2*x*t - x - 3*x**2, t, domain='ZZ(x)'),
|
154 |
+
Poly(x**4*t**6 - 2*x**2*t**3 + 1, t, domain='ZZ(x)'), DE) == \
|
155 |
+
((Poly(x**3*t + x**4 + 1, t, domain='ZZ(x)'), Poly(x**3*t**3 - x, t, domain='ZZ(x)')),
|
156 |
+
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
|
157 |
+
(Poly(-1, t, domain='ZZ(x)'), Poly(x**2, t, domain='ZZ(x)')))
|
158 |
+
|
159 |
+
assert hermite_reduce(
|
160 |
+
Poly((-2 + 3*x)*t**3 + (-1 + x)*t**2 + (-4*x + 2*x**2)*t + x**2, t),
|
161 |
+
Poly(x*t**6 - 4*x**2*t**5 + 6*x**3*t**4 - 4*x**4*t**3 + x**5*t**2, t), DE) == \
|
162 |
+
((Poly(3*t**2 + t + 3*x, t, domain='ZZ(x)'),
|
163 |
+
Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t, domain='ZZ(x)')),
|
164 |
+
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
|
165 |
+
(Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')))
|
166 |
+
|
167 |
+
|
168 |
+
def test_polynomial_reduce():
|
169 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
|
170 |
+
assert polynomial_reduce(Poly(1 + x*t + t**2, t), DE) == \
|
171 |
+
(Poly(t, t), Poly(x*t, t))
|
172 |
+
assert polynomial_reduce(Poly(0, t), DE) == \
|
173 |
+
(Poly(0, t), Poly(0, t))
|
174 |
+
|
175 |
+
|
176 |
+
def test_laurent_series():
|
177 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1, t)]})
|
178 |
+
a = Poly(36, t)
|
179 |
+
d = Poly((t - 2)*(t**2 - 1)**2, t)
|
180 |
+
F = Poly(t**2 - 1, t)
|
181 |
+
n = 2
|
182 |
+
assert laurent_series(a, d, F, n, DE) == \
|
183 |
+
(Poly(-3*t**3 + 3*t**2 - 6*t - 8, t), Poly(t**5 + t**4 - 2*t**3 - 2*t**2 + t + 1, t),
|
184 |
+
[Poly(-3*t**3 - 6*t**2, t, domain='QQ'), Poly(2*t**6 + 6*t**5 - 8*t**3, t, domain='QQ')])
|
185 |
+
|
186 |
+
|
187 |
+
def test_recognize_derivative():
|
188 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, t)]})
|
189 |
+
a = Poly(36, t)
|
190 |
+
d = Poly((t - 2)*(t**2 - 1)**2, t)
|
191 |
+
assert recognize_derivative(a, d, DE) == False
|
192 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
193 |
+
a = Poly(2, t)
|
194 |
+
d = Poly(t**2 - 1, t)
|
195 |
+
assert recognize_derivative(a, d, DE) == False
|
196 |
+
assert recognize_derivative(Poly(x*t, t), Poly(1, t), DE) == True
|
197 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
198 |
+
assert recognize_derivative(Poly(t, t), Poly(1, t), DE) == True
|
199 |
+
|
200 |
+
|
201 |
+
def test_recognize_log_derivative():
|
202 |
+
|
203 |
+
a = Poly(2*x**2 + 4*x*t - 2*t - x**2*t, t)
|
204 |
+
d = Poly((2*x + t)*(t + x**2), t)
|
205 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
206 |
+
assert recognize_log_derivative(a, d, DE, z) == True
|
207 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
|
208 |
+
assert recognize_log_derivative(Poly(t + 1, t), Poly(t + x, t), DE) == True
|
209 |
+
assert recognize_log_derivative(Poly(2, t), Poly(t**2 - 1, t), DE) == True
|
210 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
|
211 |
+
assert recognize_log_derivative(Poly(1, x), Poly(x**2 - 2, x), DE) == False
|
212 |
+
assert recognize_log_derivative(Poly(1, x), Poly(x**2 + x, x), DE) == True
|
213 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
214 |
+
assert recognize_log_derivative(Poly(1, t), Poly(t**2 - 2, t), DE) == False
|
215 |
+
assert recognize_log_derivative(Poly(1, t), Poly(t**2 + t, t), DE) == False
|
216 |
+
|
217 |
+
|
218 |
+
def test_residue_reduce():
|
219 |
+
a = Poly(2*t**2 - t - x**2, t)
|
220 |
+
d = Poly(t**3 - x**2*t, t)
|
221 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)], 'Tfuncs': [log]})
|
222 |
+
assert residue_reduce(a, d, DE, z, invert=False) == \
|
223 |
+
([(Poly(z**2 - Rational(1, 4), z, domain='ZZ(x)'),
|
224 |
+
Poly((1 + 3*x*z - 6*z**2 - 2*x**2 + 4*x**2*z**2)*t - x*z + x**2 +
|
225 |
+
2*x**2*z**2 - 2*z*x**3, t, domain='ZZ(z, x)'))], False)
|
226 |
+
assert residue_reduce(a, d, DE, z, invert=True) == \
|
227 |
+
([(Poly(z**2 - Rational(1, 4), z, domain='ZZ(x)'), Poly(t + 2*x*z, t))], False)
|
228 |
+
assert residue_reduce(Poly(-2/x, t), Poly(t**2 - 1, t,), DE, z, invert=False) == \
|
229 |
+
([(Poly(z**2 - 1, z, domain='QQ'), Poly(-2*z*t/x - 2/x, t, domain='ZZ(z,x)'))], True)
|
230 |
+
ans = residue_reduce(Poly(-2/x, t), Poly(t**2 - 1, t), DE, z, invert=True)
|
231 |
+
assert ans == ([(Poly(z**2 - 1, z, domain='QQ'), Poly(t + z, t))], True)
|
232 |
+
assert residue_reduce_to_basic(ans[0], DE, z) == -log(-1 + log(x)) + log(1 + log(x))
|
233 |
+
|
234 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - t/x - (1 - nu**2/x**2), t)]})
|
235 |
+
# TODO: Skip or make faster
|
236 |
+
assert residue_reduce(Poly((-2*nu**2 - x**4)/(2*x**2)*t - (1 + x**2)/x, t),
|
237 |
+
Poly(t**2 + 1 + x**2/2, t), DE, z) == \
|
238 |
+
([(Poly(z + S.Half, z, domain='QQ'), Poly(t**2 + 1 + x**2/2, t,
|
239 |
+
domain='ZZ(x,nu)'))], True)
|
240 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
|
241 |
+
assert residue_reduce(Poly(-2*x*t + 1 - x**2, t),
|
242 |
+
Poly(t**2 + 2*x*t + 1 + x**2, t), DE, z) == \
|
243 |
+
([(Poly(z**2 + Rational(1, 4), z), Poly(t + x + 2*z, t))], True)
|
244 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
245 |
+
assert residue_reduce(Poly(t, t), Poly(t + sqrt(2), t), DE, z) == \
|
246 |
+
([(Poly(z - 1, z, domain='QQ'), Poly(t + sqrt(2), t))], True)
|
247 |
+
|
248 |
+
|
249 |
+
def test_integrate_hyperexponential():
|
250 |
+
# TODO: Add tests for integrate_hyperexponential() from the book
|
251 |
+
a = Poly((1 + 2*t1 + t1**2 + 2*t1**3)*t**2 + (1 + t1**2)*t + 1 + t1**2, t)
|
252 |
+
d = Poly(1, t)
|
253 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t1**2, t1),
|
254 |
+
Poly(t*(1 + t1**2), t)], 'Tfuncs': [tan, Lambda(i, exp(tan(i)))]})
|
255 |
+
assert integrate_hyperexponential(a, d, DE) == \
|
256 |
+
(exp(2*tan(x))*tan(x) + exp(tan(x)), 1 + t1**2, True)
|
257 |
+
a = Poly((t1**3 + (x + 1)*t1**2 + t1 + x + 2)*t, t)
|
258 |
+
assert integrate_hyperexponential(a, d, DE) == \
|
259 |
+
((x + tan(x))*exp(tan(x)), 0, True)
|
260 |
+
|
261 |
+
a = Poly(t, t)
|
262 |
+
d = Poly(1, t)
|
263 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2*x*t, t)],
|
264 |
+
'Tfuncs': [Lambda(i, exp(x**2))]})
|
265 |
+
|
266 |
+
assert integrate_hyperexponential(a, d, DE) == \
|
267 |
+
(0, NonElementaryIntegral(exp(x**2), x), False)
|
268 |
+
|
269 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)], 'Tfuncs': [exp]})
|
270 |
+
assert integrate_hyperexponential(a, d, DE) == (exp(x), 0, True)
|
271 |
+
|
272 |
+
a = Poly(25*t**6 - 10*t**5 + 7*t**4 - 8*t**3 + 13*t**2 + 2*t - 1, t)
|
273 |
+
d = Poly(25*t**6 + 35*t**4 + 11*t**2 + 1, t)
|
274 |
+
assert integrate_hyperexponential(a, d, DE) == \
|
275 |
+
(-(11 - 10*exp(x))/(5 + 25*exp(2*x)) + log(1 + exp(2*x)), -1, True)
|
276 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(t0*t, t)],
|
277 |
+
'Tfuncs': [exp, Lambda(i, exp(exp(i)))]})
|
278 |
+
assert integrate_hyperexponential(Poly(2*t0*t**2, t), Poly(1, t), DE) == (exp(2*exp(x)), 0, True)
|
279 |
+
|
280 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(-t0*t, t)],
|
281 |
+
'Tfuncs': [exp, Lambda(i, exp(-exp(i)))]})
|
282 |
+
assert integrate_hyperexponential(Poly(-27*exp(9) - 162*t0*exp(9) +
|
283 |
+
27*x*t0*exp(9), t), Poly((36*exp(18) + x**2*exp(18) - 12*x*exp(18))*t, t), DE) == \
|
284 |
+
(27*exp(exp(x))/(-6*exp(9) + x*exp(9)), 0, True)
|
285 |
+
|
286 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)], 'Tfuncs': [exp]})
|
287 |
+
assert integrate_hyperexponential(Poly(x**2/2*t, t), Poly(1, t), DE) == \
|
288 |
+
((2 - 2*x + x**2)*exp(x)/2, 0, True)
|
289 |
+
assert integrate_hyperexponential(Poly(1 + t, t), Poly(t, t), DE) == \
|
290 |
+
(-exp(-x), 1, True) # x - exp(-x)
|
291 |
+
assert integrate_hyperexponential(Poly(x, t), Poly(t + 1, t), DE) == \
|
292 |
+
(0, NonElementaryIntegral(x/(1 + exp(x)), x), False)
|
293 |
+
|
294 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0), Poly(2*x*t1, t1)],
|
295 |
+
'Tfuncs': [log, Lambda(i, exp(i**2))]})
|
296 |
+
|
297 |
+
elem, nonelem, b = integrate_hyperexponential(Poly((8*x**7 - 12*x**5 + 6*x**3 - x)*t1**4 +
|
298 |
+
(8*t0*x**7 - 8*t0*x**6 - 4*t0*x**5 + 2*t0*x**3 + 2*t0*x**2 - t0*x +
|
299 |
+
24*x**8 - 36*x**6 - 4*x**5 + 22*x**4 + 4*x**3 - 7*x**2 - x + 1)*t1**3
|
300 |
+
+ (8*t0*x**8 - 4*t0*x**6 - 16*t0*x**5 - 2*t0*x**4 + 12*t0*x**3 +
|
301 |
+
t0*x**2 - 2*t0*x + 24*x**9 - 36*x**7 - 8*x**6 + 22*x**5 + 12*x**4 -
|
302 |
+
7*x**3 - 6*x**2 + x + 1)*t1**2 + (8*t0*x**8 - 8*t0*x**6 - 16*t0*x**5 +
|
303 |
+
6*t0*x**4 + 10*t0*x**3 - 2*t0*x**2 - t0*x + 8*x**10 - 12*x**8 - 4*x**7
|
304 |
+
+ 2*x**6 + 12*x**5 + 3*x**4 - 9*x**3 - x**2 + 2*x)*t1 + 8*t0*x**7 -
|
305 |
+
12*t0*x**6 - 4*t0*x**5 + 8*t0*x**4 - t0*x**2 - 4*x**7 + 4*x**6 +
|
306 |
+
4*x**5 - 4*x**4 - x**3 + x**2, t1), Poly((8*x**7 - 12*x**5 + 6*x**3 -
|
307 |
+
x)*t1**4 + (24*x**8 + 8*x**7 - 36*x**6 - 12*x**5 + 18*x**4 + 6*x**3 -
|
308 |
+
3*x**2 - x)*t1**3 + (24*x**9 + 24*x**8 - 36*x**7 - 36*x**6 + 18*x**5 +
|
309 |
+
18*x**4 - 3*x**3 - 3*x**2)*t1**2 + (8*x**10 + 24*x**9 - 12*x**8 -
|
310 |
+
36*x**7 + 6*x**6 + 18*x**5 - x**4 - 3*x**3)*t1 + 8*x**10 - 12*x**8 +
|
311 |
+
6*x**6 - x**4, t1), DE)
|
312 |
+
|
313 |
+
assert factor(elem) == -((x - 1)*log(x)/((x + exp(x**2))*(2*x**2 - 1)))
|
314 |
+
assert (nonelem, b) == (NonElementaryIntegral(exp(x**2)/(exp(x**2) + 1), x), False)
|
315 |
+
|
316 |
+
def test_integrate_hyperexponential_polynomial():
|
317 |
+
# Without proper cancellation within integrate_hyperexponential_polynomial(),
|
318 |
+
# this will take a long time to complete, and will return a complicated
|
319 |
+
# expression
|
320 |
+
p = Poly((-28*x**11*t0 - 6*x**8*t0 + 6*x**9*t0 - 15*x**8*t0**2 +
|
321 |
+
15*x**7*t0**2 + 84*x**10*t0**2 - 140*x**9*t0**3 - 20*x**6*t0**3 +
|
322 |
+
20*x**7*t0**3 - 15*x**6*t0**4 + 15*x**5*t0**4 + 140*x**8*t0**4 -
|
323 |
+
84*x**7*t0**5 - 6*x**4*t0**5 + 6*x**5*t0**5 + x**3*t0**6 - x**4*t0**6 +
|
324 |
+
28*x**6*t0**6 - 4*x**5*t0**7 + x**9 - x**10 + 4*x**12)/(-8*x**11*t0 +
|
325 |
+
28*x**10*t0**2 - 56*x**9*t0**3 + 70*x**8*t0**4 - 56*x**7*t0**5 +
|
326 |
+
28*x**6*t0**6 - 8*x**5*t0**7 + x**4*t0**8 + x**12)*t1**2 +
|
327 |
+
(-28*x**11*t0 - 12*x**8*t0 + 12*x**9*t0 - 30*x**8*t0**2 +
|
328 |
+
30*x**7*t0**2 + 84*x**10*t0**2 - 140*x**9*t0**3 - 40*x**6*t0**3 +
|
329 |
+
40*x**7*t0**3 - 30*x**6*t0**4 + 30*x**5*t0**4 + 140*x**8*t0**4 -
|
330 |
+
84*x**7*t0**5 - 12*x**4*t0**5 + 12*x**5*t0**5 - 2*x**4*t0**6 +
|
331 |
+
2*x**3*t0**6 + 28*x**6*t0**6 - 4*x**5*t0**7 + 2*x**9 - 2*x**10 +
|
332 |
+
4*x**12)/(-8*x**11*t0 + 28*x**10*t0**2 - 56*x**9*t0**3 +
|
333 |
+
70*x**8*t0**4 - 56*x**7*t0**5 + 28*x**6*t0**6 - 8*x**5*t0**7 +
|
334 |
+
x**4*t0**8 + x**12)*t1 + (-2*x**2*t0 + 2*x**3*t0 + x*t0**2 -
|
335 |
+
x**2*t0**2 + x**3 - x**4)/(-4*x**5*t0 + 6*x**4*t0**2 - 4*x**3*t0**3 +
|
336 |
+
x**2*t0**4 + x**6), t1, z, expand=False)
|
337 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0), Poly(2*x*t1, t1)]})
|
338 |
+
assert integrate_hyperexponential_polynomial(p, DE, z) == (
|
339 |
+
Poly((x - t0)*t1**2 + (-2*t0 + 2*x)*t1, t1), Poly(-2*x*t0 + x**2 +
|
340 |
+
t0**2, t1), True)
|
341 |
+
|
342 |
+
DE = DifferentialExtension(extension={'D':[Poly(1, x), Poly(t0, t0)]})
|
343 |
+
assert integrate_hyperexponential_polynomial(Poly(0, t0), DE, z) == (
|
344 |
+
Poly(0, t0), Poly(1, t0), True)
|
345 |
+
|
346 |
+
|
347 |
+
def test_integrate_hyperexponential_returns_piecewise():
|
348 |
+
a, b = symbols('a b')
|
349 |
+
DE = DifferentialExtension(a**x, x)
|
350 |
+
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
|
351 |
+
(exp(x*log(a))/log(a), Ne(log(a), 0)), (x, True)), 0, True)
|
352 |
+
DE = DifferentialExtension(a**(b*x), x)
|
353 |
+
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
|
354 |
+
(exp(b*x*log(a))/(b*log(a)), Ne(b*log(a), 0)), (x, True)), 0, True)
|
355 |
+
DE = DifferentialExtension(exp(a*x), x)
|
356 |
+
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
|
357 |
+
(exp(a*x)/a, Ne(a, 0)), (x, True)), 0, True)
|
358 |
+
DE = DifferentialExtension(x*exp(a*x), x)
|
359 |
+
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
|
360 |
+
((a*x - 1)*exp(a*x)/a**2, Ne(a**2, 0)), (x**2/2, True)), 0, True)
|
361 |
+
DE = DifferentialExtension(x**2*exp(a*x), x)
|
362 |
+
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
|
363 |
+
((x**2*a**2 - 2*a*x + 2)*exp(a*x)/a**3, Ne(a**3, 0)),
|
364 |
+
(x**3/3, True)), 0, True)
|
365 |
+
DE = DifferentialExtension(x**y + z, y)
|
366 |
+
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
|
367 |
+
(exp(log(x)*y)/log(x), Ne(log(x), 0)), (y, True)), z, True)
|
368 |
+
DE = DifferentialExtension(x**y + z + x**(2*y), y)
|
369 |
+
assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
|
370 |
+
((exp(2*log(x)*y)*log(x) +
|
371 |
+
2*exp(log(x)*y)*log(x))/(2*log(x)**2), Ne(2*log(x)**2, 0)),
|
372 |
+
(2*y, True),
|
373 |
+
), z, True)
|
374 |
+
# TODO: Add a test where two different parts of the extension use a
|
375 |
+
# Piecewise, like y**x + z**x.
|
376 |
+
|
377 |
+
|
378 |
+
def test_issue_13947():
|
379 |
+
a, t, s = symbols('a t s')
|
380 |
+
assert risch_integrate(2**(-pi)/(2**t + 1), t) == \
|
381 |
+
2**(-pi)*t - 2**(-pi)*log(2**t + 1)/log(2)
|
382 |
+
assert risch_integrate(a**(t - s)/(a**t + 1), t) == \
|
383 |
+
exp(-s*log(a))*log(a**t + 1)/log(a)
|
384 |
+
|
385 |
+
|
386 |
+
def test_integrate_primitive():
|
387 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)],
|
388 |
+
'Tfuncs': [log]})
|
389 |
+
assert integrate_primitive(Poly(t, t), Poly(1, t), DE) == (x*log(x), -1, True)
|
390 |
+
assert integrate_primitive(Poly(x, t), Poly(t, t), DE) == (0, NonElementaryIntegral(x/log(x), x), False)
|
391 |
+
|
392 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x + 1), t2)],
|
393 |
+
'Tfuncs': [log, Lambda(i, log(i + 1))]})
|
394 |
+
assert integrate_primitive(Poly(t1, t2), Poly(t2, t2), DE) == \
|
395 |
+
(0, NonElementaryIntegral(log(x)/log(1 + x), x), False)
|
396 |
+
|
397 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x*t1), t2)],
|
398 |
+
'Tfuncs': [log, Lambda(i, log(log(i)))]})
|
399 |
+
assert integrate_primitive(Poly(t2, t2), Poly(t1, t2), DE) == \
|
400 |
+
(0, NonElementaryIntegral(log(log(x))/log(x), x), False)
|
401 |
+
|
402 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0)],
|
403 |
+
'Tfuncs': [log]})
|
404 |
+
assert integrate_primitive(Poly(x**2*t0**3 + (3*x**2 + x)*t0**2 + (3*x**2
|
405 |
+
+ 2*x)*t0 + x**2 + x, t0), Poly(x**2*t0**4 + 4*x**2*t0**3 + 6*x**2*t0**2 +
|
406 |
+
4*x**2*t0 + x**2, t0), DE) == \
|
407 |
+
(-1/(log(x) + 1), NonElementaryIntegral(1/(log(x) + 1), x), False)
|
408 |
+
|
409 |
+
def test_integrate_hypertangent_polynomial():
|
410 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
|
411 |
+
assert integrate_hypertangent_polynomial(Poly(t**2 + x*t + 1, t), DE) == \
|
412 |
+
(Poly(t, t), Poly(x/2, t))
|
413 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(a*(t**2 + 1), t)]})
|
414 |
+
assert integrate_hypertangent_polynomial(Poly(t**5, t), DE) == \
|
415 |
+
(Poly(1/(4*a)*t**4 - 1/(2*a)*t**2, t), Poly(1/(2*a), t))
|
416 |
+
|
417 |
+
|
418 |
+
def test_integrate_nonlinear_no_specials():
|
419 |
+
a, d, = Poly(x**2*t**5 + x*t**4 - nu**2*t**3 - x*(x**2 + 1)*t**2 - (x**2 -
|
420 |
+
nu**2)*t - x**5/4, t), Poly(x**2*t**4 + x**2*(x**2 + 2)*t**2 + x**2 + x**4 + x**6/4, t)
|
421 |
+
# f(x) == phi_nu(x), the logarithmic derivative of J_v, the Bessel function,
|
422 |
+
# which has no specials (see Chapter 5, note 4 of Bronstein's book).
|
423 |
+
f = Function('phi_nu')
|
424 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x),
|
425 |
+
Poly(-t**2 - t/x - (1 - nu**2/x**2), t)], 'Tfuncs': [f]})
|
426 |
+
assert integrate_nonlinear_no_specials(a, d, DE) == \
|
427 |
+
(-log(1 + f(x)**2 + x**2/2)/2 + (- 4 - x**2)/(4 + 2*x**2 + 4*f(x)**2), True)
|
428 |
+
assert integrate_nonlinear_no_specials(Poly(t, t), Poly(1, t), DE) == \
|
429 |
+
(0, False)
|
430 |
+
|
431 |
+
|
432 |
+
def test_integer_powers():
|
433 |
+
assert integer_powers([x, x/2, x**2 + 1, x*Rational(2, 3)]) == [
|
434 |
+
(x/6, [(x, 6), (x/2, 3), (x*Rational(2, 3), 4)]),
|
435 |
+
(1 + x**2, [(1 + x**2, 1)])]
|
436 |
+
|
437 |
+
|
438 |
+
def test_DifferentialExtension_exp():
|
439 |
+
assert DifferentialExtension(exp(x) + exp(x**2), x)._important_attrs == \
|
440 |
+
(Poly(t1 + t0, t1), Poly(1, t1), [Poly(1, x,), Poly(t0, t0),
|
441 |
+
Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
|
442 |
+
Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
|
443 |
+
assert DifferentialExtension(exp(x) + exp(2*x), x)._important_attrs == \
|
444 |
+
(Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0, t0)], [x, t0],
|
445 |
+
[Lambda(i, exp(i))], [], [None, 'exp'], [None, x])
|
446 |
+
assert DifferentialExtension(exp(x) + exp(x/2), x)._important_attrs == \
|
447 |
+
(Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)],
|
448 |
+
[x, t0], [Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2])
|
449 |
+
assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2), x)._important_attrs == \
|
450 |
+
(Poly((1 + t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0),
|
451 |
+
Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
|
452 |
+
Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
|
453 |
+
assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2 + 1), x)._important_attrs == \
|
454 |
+
(Poly((1 + S.Exp1*t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x),
|
455 |
+
Poly(t0, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
|
456 |
+
Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
|
457 |
+
assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2), x)._important_attrs == \
|
458 |
+
(Poly((t0 + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x),
|
459 |
+
Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1],
|
460 |
+
[Lambda(i, exp(i/2)), Lambda(i, exp(i**2))],
|
461 |
+
[(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'], [None, x/2, x**2])
|
462 |
+
assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2 + 3), x)._important_attrs == \
|
463 |
+
(Poly((t0*exp(3) + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x),
|
464 |
+
Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i/2)),
|
465 |
+
Lambda(i, exp(i**2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'],
|
466 |
+
[None, x/2, x**2])
|
467 |
+
assert DifferentialExtension(sqrt(exp(x)), x)._important_attrs == \
|
468 |
+
(Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0],
|
469 |
+
[Lambda(i, exp(i/2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp'], [None, x/2])
|
470 |
+
|
471 |
+
assert DifferentialExtension(exp(x/2), x)._important_attrs == \
|
472 |
+
(Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0],
|
473 |
+
[Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2])
|
474 |
+
|
475 |
+
|
476 |
+
def test_DifferentialExtension_log():
|
477 |
+
assert DifferentialExtension(log(x)*log(x + 1)*log(2*x**2 + 2*x), x)._important_attrs == \
|
478 |
+
(Poly(t0*t1**2 + (t0*log(2) + t0**2)*t1, t1), Poly(1, t1),
|
479 |
+
[Poly(1, x), Poly(1/x, t0),
|
480 |
+
Poly(1/(x + 1), t1, expand=False)], [x, t0, t1],
|
481 |
+
[Lambda(i, log(i)), Lambda(i, log(i + 1))], [], [None, 'log', 'log'],
|
482 |
+
[None, x, x + 1])
|
483 |
+
assert DifferentialExtension(x**x*log(x), x)._important_attrs == \
|
484 |
+
(Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0),
|
485 |
+
Poly((1 + t0)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)),
|
486 |
+
Lambda(i, exp(t0*i))], [(exp(x*log(x)), x**x)], [None, 'log', 'exp'],
|
487 |
+
[None, x, t0*x])
|
488 |
+
|
489 |
+
|
490 |
+
def test_DifferentialExtension_symlog():
|
491 |
+
# See comment on test_risch_integrate below
|
492 |
+
assert DifferentialExtension(log(x**x), x)._important_attrs == \
|
493 |
+
(Poly(t0*x, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0), Poly((t0 +
|
494 |
+
1)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i*t0))],
|
495 |
+
[(exp(x*log(x)), x**x)], [None, 'log', 'exp'], [None, x, t0*x])
|
496 |
+
assert DifferentialExtension(log(x**y), x)._important_attrs == \
|
497 |
+
(Poly(y*t0, t0), Poly(1, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
|
498 |
+
[Lambda(i, log(i))], [(y*log(x), log(x**y))], [None, 'log'],
|
499 |
+
[None, x])
|
500 |
+
assert DifferentialExtension(log(sqrt(x)), x)._important_attrs == \
|
501 |
+
(Poly(t0, t0), Poly(2, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
|
502 |
+
[Lambda(i, log(i))], [(log(x)/2, log(sqrt(x)))], [None, 'log'],
|
503 |
+
[None, x])
|
504 |
+
|
505 |
+
|
506 |
+
def test_DifferentialExtension_handle_first():
|
507 |
+
assert DifferentialExtension(exp(x)*log(x), x, handle_first='log')._important_attrs == \
|
508 |
+
(Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0),
|
509 |
+
Poly(t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i))],
|
510 |
+
[], [None, 'log', 'exp'], [None, x, x])
|
511 |
+
assert DifferentialExtension(exp(x)*log(x), x, handle_first='exp')._important_attrs == \
|
512 |
+
(Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0),
|
513 |
+
Poly(1/x, t1)], [x, t0, t1], [Lambda(i, exp(i)), Lambda(i, log(i))],
|
514 |
+
[], [None, 'exp', 'log'], [None, x, x])
|
515 |
+
|
516 |
+
# This one must have the log first, regardless of what we set it to
|
517 |
+
# (because the log is inside of the exponential: x**x == exp(x*log(x)))
|
518 |
+
assert DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x,
|
519 |
+
handle_first='exp')._important_attrs == \
|
520 |
+
DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x,
|
521 |
+
handle_first='log')._important_attrs == \
|
522 |
+
(Poly((-1 + x - x*t0**2)*t1, t1), Poly(x, t1),
|
523 |
+
[Poly(1, x), Poly(1/x, t0), Poly((1 + t0)*t1, t1)], [x, t0, t1],
|
524 |
+
[Lambda(i, log(i)), Lambda(i, exp(t0*i))], [(exp(x*log(x)), x**x)],
|
525 |
+
[None, 'log', 'exp'], [None, x, t0*x])
|
526 |
+
|
527 |
+
|
528 |
+
def test_DifferentialExtension_all_attrs():
|
529 |
+
# Test 'unimportant' attributes
|
530 |
+
DE = DifferentialExtension(exp(x)*log(x), x, handle_first='exp')
|
531 |
+
assert DE.f == exp(x)*log(x)
|
532 |
+
assert DE.newf == t0*t1
|
533 |
+
assert DE.x == x
|
534 |
+
assert DE.cases == ['base', 'exp', 'primitive']
|
535 |
+
assert DE.case == 'primitive'
|
536 |
+
|
537 |
+
assert DE.level == -1
|
538 |
+
assert DE.t == t1 == DE.T[DE.level]
|
539 |
+
assert DE.d == Poly(1/x, t1) == DE.D[DE.level]
|
540 |
+
raises(ValueError, lambda: DE.increment_level())
|
541 |
+
DE.decrement_level()
|
542 |
+
assert DE.level == -2
|
543 |
+
assert DE.t == t0 == DE.T[DE.level]
|
544 |
+
assert DE.d == Poly(t0, t0) == DE.D[DE.level]
|
545 |
+
assert DE.case == 'exp'
|
546 |
+
DE.decrement_level()
|
547 |
+
assert DE.level == -3
|
548 |
+
assert DE.t == x == DE.T[DE.level] == DE.x
|
549 |
+
assert DE.d == Poly(1, x) == DE.D[DE.level]
|
550 |
+
assert DE.case == 'base'
|
551 |
+
raises(ValueError, lambda: DE.decrement_level())
|
552 |
+
DE.increment_level()
|
553 |
+
DE.increment_level()
|
554 |
+
assert DE.level == -1
|
555 |
+
assert DE.t == t1 == DE.T[DE.level]
|
556 |
+
assert DE.d == Poly(1/x, t1) == DE.D[DE.level]
|
557 |
+
assert DE.case == 'primitive'
|
558 |
+
|
559 |
+
# Test methods
|
560 |
+
assert DE.indices('log') == [2]
|
561 |
+
assert DE.indices('exp') == [1]
|
562 |
+
|
563 |
+
|
564 |
+
def test_DifferentialExtension_extension_flag():
|
565 |
+
raises(ValueError, lambda: DifferentialExtension(extension={'T': [x, t]}))
|
566 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
|
567 |
+
assert DE._important_attrs == (None, None, [Poly(1, x), Poly(t, t)], [x, t],
|
568 |
+
None, None, None, None)
|
569 |
+
assert DE.d == Poly(t, t)
|
570 |
+
assert DE.t == t
|
571 |
+
assert DE.level == -1
|
572 |
+
assert DE.cases == ['base', 'exp']
|
573 |
+
assert DE.x == x
|
574 |
+
assert DE.case == 'exp'
|
575 |
+
|
576 |
+
DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)],
|
577 |
+
'exts': [None, 'exp'], 'extargs': [None, x]})
|
578 |
+
assert DE._important_attrs == (None, None, [Poly(1, x), Poly(t, t)], [x, t],
|
579 |
+
None, None, [None, 'exp'], [None, x])
|
580 |
+
raises(ValueError, lambda: DifferentialExtension())
|
581 |
+
|
582 |
+
|
583 |
+
def test_DifferentialExtension_misc():
|
584 |
+
# Odd ends
|
585 |
+
assert DifferentialExtension(sin(y)*exp(x), x)._important_attrs == \
|
586 |
+
(Poly(sin(y)*t0, t0, domain='ZZ[sin(y)]'), Poly(1, t0, domain='ZZ'),
|
587 |
+
[Poly(1, x, domain='ZZ'), Poly(t0, t0, domain='ZZ')], [x, t0],
|
588 |
+
[Lambda(i, exp(i))], [], [None, 'exp'], [None, x])
|
589 |
+
raises(NotImplementedError, lambda: DifferentialExtension(sin(x), x))
|
590 |
+
assert DifferentialExtension(10**x, x)._important_attrs == \
|
591 |
+
(Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(log(10)*t0, t0)], [x, t0],
|
592 |
+
[Lambda(i, exp(i*log(10)))], [(exp(x*log(10)), 10**x)], [None, 'exp'],
|
593 |
+
[None, x*log(10)])
|
594 |
+
assert DifferentialExtension(log(x) + log(x**2), x)._important_attrs in [
|
595 |
+
(Poly(3*t0, t0), Poly(2, t0), [Poly(1, x), Poly(2/x, t0)], [x, t0],
|
596 |
+
[Lambda(i, log(i**2))], [], [None, ], [], [1], [x**2]),
|
597 |
+
(Poly(3*t0, t0), Poly(1, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
|
598 |
+
[Lambda(i, log(i))], [], [None, 'log'], [None, x])]
|
599 |
+
assert DifferentialExtension(S.Zero, x)._important_attrs == \
|
600 |
+
(Poly(0, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None])
|
601 |
+
assert DifferentialExtension(tan(atan(x).rewrite(log)), x)._important_attrs == \
|
602 |
+
(Poly(x, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None])
|
603 |
+
|
604 |
+
|
605 |
+
def test_DifferentialExtension_Rothstein():
|
606 |
+
# Rothstein's integral
|
607 |
+
f = (2581284541*exp(x) + 1757211400)/(39916800*exp(3*x) +
|
608 |
+
119750400*exp(x)**2 + 119750400*exp(x) + 39916800)*exp(1/(exp(x) + 1) - 10*x)
|
609 |
+
assert DifferentialExtension(f, x)._important_attrs == \
|
610 |
+
(Poly((1757211400 + 2581284541*t0)*t1, t1), Poly(39916800 +
|
611 |
+
119750400*t0 + 119750400*t0**2 + 39916800*t0**3, t1),
|
612 |
+
[Poly(1, x), Poly(t0, t0), Poly(-(10 + 21*t0 + 10*t0**2)/(1 + 2*t0 +
|
613 |
+
t0**2)*t1, t1, domain='ZZ(t0)')], [x, t0, t1],
|
614 |
+
[Lambda(i, exp(i)), Lambda(i, exp(1/(t0 + 1) - 10*i))], [],
|
615 |
+
[None, 'exp', 'exp'], [None, x, 1/(t0 + 1) - 10*x])
|
616 |
+
|
617 |
+
|
618 |
+
class _TestingException(Exception):
|
619 |
+
"""Dummy Exception class for testing."""
|
620 |
+
pass
|
621 |
+
|
622 |
+
|
623 |
+
def test_DecrementLevel():
|
624 |
+
DE = DifferentialExtension(x*log(exp(x) + 1), x)
|
625 |
+
assert DE.level == -1
|
626 |
+
assert DE.t == t1
|
627 |
+
assert DE.d == Poly(t0/(t0 + 1), t1)
|
628 |
+
assert DE.case == 'primitive'
|
629 |
+
|
630 |
+
with DecrementLevel(DE):
|
631 |
+
assert DE.level == -2
|
632 |
+
assert DE.t == t0
|
633 |
+
assert DE.d == Poly(t0, t0)
|
634 |
+
assert DE.case == 'exp'
|
635 |
+
|
636 |
+
with DecrementLevel(DE):
|
637 |
+
assert DE.level == -3
|
638 |
+
assert DE.t == x
|
639 |
+
assert DE.d == Poly(1, x)
|
640 |
+
assert DE.case == 'base'
|
641 |
+
|
642 |
+
assert DE.level == -2
|
643 |
+
assert DE.t == t0
|
644 |
+
assert DE.d == Poly(t0, t0)
|
645 |
+
assert DE.case == 'exp'
|
646 |
+
|
647 |
+
assert DE.level == -1
|
648 |
+
assert DE.t == t1
|
649 |
+
assert DE.d == Poly(t0/(t0 + 1), t1)
|
650 |
+
assert DE.case == 'primitive'
|
651 |
+
|
652 |
+
# Test that __exit__ is called after an exception correctly
|
653 |
+
try:
|
654 |
+
with DecrementLevel(DE):
|
655 |
+
raise _TestingException
|
656 |
+
except _TestingException:
|
657 |
+
pass
|
658 |
+
else:
|
659 |
+
raise AssertionError("Did not raise.")
|
660 |
+
|
661 |
+
assert DE.level == -1
|
662 |
+
assert DE.t == t1
|
663 |
+
assert DE.d == Poly(t0/(t0 + 1), t1)
|
664 |
+
assert DE.case == 'primitive'
|
665 |
+
|
666 |
+
|
667 |
+
def test_risch_integrate():
|
668 |
+
assert risch_integrate(t0*exp(x), x) == t0*exp(x)
|
669 |
+
assert risch_integrate(sin(x), x, rewrite_complex=True) == -exp(I*x)/2 - exp(-I*x)/2
|
670 |
+
|
671 |
+
# From my GSoC writeup
|
672 |
+
assert risch_integrate((1 + 2*x**2 + x**4 + 2*x**3*exp(2*x**2))/
|
673 |
+
(x**4*exp(x**2) + 2*x**2*exp(x**2) + exp(x**2)), x) == \
|
674 |
+
NonElementaryIntegral(exp(-x**2), x) + exp(x**2)/(1 + x**2)
|
675 |
+
|
676 |
+
|
677 |
+
assert risch_integrate(0, x) == 0
|
678 |
+
|
679 |
+
# also tests prde_cancel()
|
680 |
+
e1 = log(x/exp(x) + 1)
|
681 |
+
ans1 = risch_integrate(e1, x)
|
682 |
+
assert ans1 == (x*log(x*exp(-x) + 1) + NonElementaryIntegral((x**2 - x)/(x + exp(x)), x))
|
683 |
+
assert cancel(diff(ans1, x) - e1) == 0
|
684 |
+
|
685 |
+
# also tests issue #10798
|
686 |
+
e2 = (log(-1/y)/2 - log(1/y)/2)/y - (log(1 - 1/y)/2 - log(1 + 1/y)/2)/y
|
687 |
+
ans2 = risch_integrate(e2, y)
|
688 |
+
assert ans2 == log(1/y)*log(1 - 1/y)/2 - log(1/y)*log(1 + 1/y)/2 + \
|
689 |
+
NonElementaryIntegral((I*pi*y**2 - 2*y*log(1/y) - I*pi)/(2*y**3 - 2*y), y)
|
690 |
+
assert expand_log(cancel(diff(ans2, y) - e2), force=True) == 0
|
691 |
+
|
692 |
+
# These are tested here in addition to in test_DifferentialExtension above
|
693 |
+
# (symlogs) to test that backsubs works correctly. The integrals should be
|
694 |
+
# written in terms of the original logarithms in the integrands.
|
695 |
+
|
696 |
+
# XXX: Unfortunately, making backsubs work on this one is a little
|
697 |
+
# trickier, because x**x is converted to exp(x*log(x)), and so log(x**x)
|
698 |
+
# is converted to x*log(x). (x**2*log(x)).subs(x*log(x), log(x**x)) is
|
699 |
+
# smart enough, the issue is that these splits happen at different places
|
700 |
+
# in the algorithm. Maybe a heuristic is in order
|
701 |
+
assert risch_integrate(log(x**x), x) == x**2*log(x)/2 - x**2/4
|
702 |
+
|
703 |
+
assert risch_integrate(log(x**y), x) == x*log(x**y) - x*y
|
704 |
+
assert risch_integrate(log(sqrt(x)), x) == x*log(sqrt(x)) - x/2
|
705 |
+
|
706 |
+
|
707 |
+
def test_risch_integrate_float():
|
708 |
+
assert risch_integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) == -2.4*exp(8*x) - 12.0*exp(5*x)
|
709 |
+
|
710 |
+
|
711 |
+
def test_NonElementaryIntegral():
|
712 |
+
assert isinstance(risch_integrate(exp(x**2), x), NonElementaryIntegral)
|
713 |
+
assert isinstance(risch_integrate(x**x*log(x), x), NonElementaryIntegral)
|
714 |
+
# Make sure methods of Integral still give back a NonElementaryIntegral
|
715 |
+
assert isinstance(NonElementaryIntegral(x**x*t0, x).subs(t0, log(x)), NonElementaryIntegral)
|
716 |
+
|
717 |
+
|
718 |
+
def test_xtothex():
|
719 |
+
a = risch_integrate(x**x, x)
|
720 |
+
assert a == NonElementaryIntegral(x**x, x)
|
721 |
+
assert isinstance(a, NonElementaryIntegral)
|
722 |
+
|
723 |
+
|
724 |
+
def test_DifferentialExtension_equality():
|
725 |
+
DE1 = DE2 = DifferentialExtension(log(x), x)
|
726 |
+
assert DE1 == DE2
|
727 |
+
|
728 |
+
|
729 |
+
def test_DifferentialExtension_printing():
|
730 |
+
DE = DifferentialExtension(exp(2*x**2) + log(exp(x**2) + 1), x)
|
731 |
+
assert repr(DE) == ("DifferentialExtension(dict([('f', exp(2*x**2) + log(exp(x**2) + 1)), "
|
732 |
+
"('x', x), ('T', [x, t0, t1]), ('D', [Poly(1, x, domain='ZZ'), Poly(2*x*t0, t0, domain='ZZ[x]'), "
|
733 |
+
"Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')]), ('fa', Poly(t1 + t0**2, t1, domain='ZZ[t0]')), "
|
734 |
+
"('fd', Poly(1, t1, domain='ZZ')), ('Tfuncs', [Lambda(i, exp(i**2)), Lambda(i, log(t0 + 1))]), "
|
735 |
+
"('backsubs', []), ('exts', [None, 'exp', 'log']), ('extargs', [None, x**2, t0 + 1]), "
|
736 |
+
"('cases', ['base', 'exp', 'primitive']), ('case', 'primitive'), ('t', t1), "
|
737 |
+
"('d', Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')), ('newf', t0**2 + t1), ('level', -1), "
|
738 |
+
"('dummy', False)]))")
|
739 |
+
|
740 |
+
assert str(DE) == ("DifferentialExtension({fa=Poly(t1 + t0**2, t1, domain='ZZ[t0]'), "
|
741 |
+
"fd=Poly(1, t1, domain='ZZ'), D=[Poly(1, x, domain='ZZ'), Poly(2*x*t0, t0, domain='ZZ[x]'), "
|
742 |
+
"Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')]})")
|
743 |
+
|
744 |
+
|
745 |
+
def test_issue_23948():
|
746 |
+
f = (
|
747 |
+
( (-2*x**5 + 28*x**4 - 144*x**3 + 324*x**2 - 270*x)*log(x)**2
|
748 |
+
+(-4*x**6 + 56*x**5 - 288*x**4 + 648*x**3 - 540*x**2)*log(x)
|
749 |
+
+(2*x**5 - 28*x**4 + 144*x**3 - 324*x**2 + 270*x)*exp(x)
|
750 |
+
+(2*x**5 - 28*x**4 + 144*x**3 - 324*x**2 + 270*x)*log(5)
|
751 |
+
-2*x**7 + 26*x**6 - 116*x**5 + 180*x**4 + 54*x**3 - 270*x**2
|
752 |
+
)*log(-log(x)**2 - 2*x*log(x) + exp(x) + log(5) - x**2 - x)**2
|
753 |
+
+( (4*x**5 - 44*x**4 + 168*x**3 - 216*x**2 - 108*x + 324)*log(x)
|
754 |
+
+(-2*x**5 + 24*x**4 - 108*x**3 + 216*x**2 - 162*x)*exp(x)
|
755 |
+
+4*x**6 - 42*x**5 + 144*x**4 - 108*x**3 - 324*x**2 + 486*x
|
756 |
+
)*log(-log(x)**2 - 2*x*log(x) + exp(x) + log(5) - x**2 - x)
|
757 |
+
)/(x*exp(x)**2*log(x)**2 + 2*x**2*exp(x)**2*log(x) - x*exp(x)**3
|
758 |
+
+(-x*log(5) + x**3 + x**2)*exp(x)**2)
|
759 |
+
|
760 |
+
F = ((x**4 - 12*x**3 + 54*x**2 - 108*x + 81)*exp(-2*x)
|
761 |
+
*log(-x**2 - 2*x*log(x) - x + exp(x) - log(x)**2 + log(5))**2)
|
762 |
+
|
763 |
+
assert risch_integrate(f, x) == F
|
llmeval-env/lib/python3.10/site-packages/sympy/integrals/tests/test_singularityfunctions.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.integrals.singularityfunctions import singularityintegrate
|
2 |
+
from sympy.core.function import Function
|
3 |
+
from sympy.core.symbol import symbols
|
4 |
+
from sympy.functions.special.singularity_functions import SingularityFunction
|
5 |
+
|
6 |
+
x, a, n, y = symbols('x a n y')
|
7 |
+
f = Function('f')
|
8 |
+
|
9 |
+
|
10 |
+
def test_singularityintegrate():
|
11 |
+
assert singularityintegrate(x, x) is None
|
12 |
+
assert singularityintegrate(x + SingularityFunction(x, 9, 1), x) is None
|
13 |
+
|
14 |
+
assert 4*singularityintegrate(SingularityFunction(x, a, 3), x) == 4*SingularityFunction(x, a, 4)/4
|
15 |
+
assert singularityintegrate(5*SingularityFunction(x, 5, -2), x) == 5*SingularityFunction(x, 5, -1)
|
16 |
+
assert singularityintegrate(6*SingularityFunction(x, 5, -1), x) == 6*SingularityFunction(x, 5, 0)
|
17 |
+
assert singularityintegrate(x*SingularityFunction(x, 0, -1), x) == 0
|
18 |
+
assert singularityintegrate((x - 5)*SingularityFunction(x, 5, -1), x) == 0
|
19 |
+
assert singularityintegrate(SingularityFunction(x, 0, -1) * f(x), x) == f(0) * SingularityFunction(x, 0, 0)
|
20 |
+
assert singularityintegrate(SingularityFunction(x, 1, -1) * f(x), x) == f(1) * SingularityFunction(x, 1, 0)
|
21 |
+
assert singularityintegrate(y*SingularityFunction(x, 0, -1)**2, x) == \
|
22 |
+
y*SingularityFunction(0, 0, -1)*SingularityFunction(x, 0, 0)
|