Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/12.attention.query_key_value.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/12.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/20.input_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/7.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/7.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__init__.py +43 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/deltafunctions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/heurisch.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/integrals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/intpoly.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/laplace.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/manualintegrate.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/meijerint.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/meijerint_doc.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/prde.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/quadrature.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/rationaltools.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/rde.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/risch.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/singularityfunctions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/transforms.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/trigonometry.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/__init__.py +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_integrate.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_trigintegrate.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/bench_integrate.py +21 -0
- venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/bench_trigintegrate.py +13 -0
- venv/lib/python3.10/site-packages/sympy/integrals/deltafunctions.py +201 -0
- venv/lib/python3.10/site-packages/sympy/integrals/heurisch.py +771 -0
- venv/lib/python3.10/site-packages/sympy/integrals/integrals.py +1633 -0
- venv/lib/python3.10/site-packages/sympy/integrals/intpoly.py +1302 -0
- venv/lib/python3.10/site-packages/sympy/integrals/laplace.py +1761 -0
- venv/lib/python3.10/site-packages/sympy/integrals/manualintegrate.py +2171 -0
- venv/lib/python3.10/site-packages/sympy/integrals/meijerint.py +2190 -0
- venv/lib/python3.10/site-packages/sympy/integrals/meijerint_doc.py +37 -0
- venv/lib/python3.10/site-packages/sympy/integrals/prde.py +1332 -0
- venv/lib/python3.10/site-packages/sympy/integrals/quadrature.py +617 -0
- venv/lib/python3.10/site-packages/sympy/integrals/rationaltools.py +418 -0
- venv/lib/python3.10/site-packages/sympy/integrals/rde.py +800 -0
- venv/lib/python3.10/site-packages/sympy/integrals/risch.py +1858 -0
- venv/lib/python3.10/site-packages/sympy/integrals/singularityfunctions.py +63 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_heurisch.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_integrals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_intpoly.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_laplace.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_risch.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_transforms.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/12.attention.query_key_value.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cf051809286ce8412e7b87c25178856d79690f0bfde093da40edeb5f4c8d923a
|
3 |
+
size 50332828
|
ckpts/universal/global_step80/zero/12.attention.query_key_value.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2b8c1db01d740e8063be98123074316da3456ce68769e5e2e25f4ccd0c4106d7
|
3 |
+
size 50332843
|
ckpts/universal/global_step80/zero/20.input_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dbd97bf88dbd0614264d28caf0bd54aed3e436a9582e7d5f612c9823ae28d95f
|
3 |
+
size 9293
|
ckpts/universal/global_step80/zero/7.mlp.dense_h_to_4h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1a26400a520c393ffe0f00c3ae2143b0f3e242f6d041b289ca4655b910fbac3e
|
3 |
+
size 33555612
|
ckpts/universal/global_step80/zero/7.mlp.dense_h_to_4h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:81409076621a6c42b62587c454731cfd343ff97cfbe4802ee9b3a04f9d0d53f9
|
3 |
+
size 33555533
|
venv/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 |
+
]
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.5 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/deltafunctions.cpython-310.pyc
ADDED
Binary file (5.03 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/heurisch.cpython-310.pyc
ADDED
Binary file (21.1 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/integrals.cpython-310.pyc
ADDED
Binary file (47.5 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/intpoly.cpython-310.pyc
ADDED
Binary file (37.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/laplace.cpython-310.pyc
ADDED
Binary file (56.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/manualintegrate.cpython-310.pyc
ADDED
Binary file (71 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/meijerint.cpython-310.pyc
ADDED
Binary file (63.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/meijerint_doc.cpython-310.pyc
ADDED
Binary file (1.54 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/prde.cpython-310.pyc
ADDED
Binary file (43.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/quadrature.cpython-310.pyc
ADDED
Binary file (17.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/rationaltools.cpython-310.pyc
ADDED
Binary file (10.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/rde.cpython-310.pyc
ADDED
Binary file (20.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/risch.cpython-310.pyc
ADDED
Binary file (55.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/singularityfunctions.cpython-310.pyc
ADDED
Binary file (2.33 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/transforms.cpython-310.pyc
ADDED
Binary file (47.5 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/__pycache__/trigonometry.cpython-310.pyc
ADDED
Binary file (4.27 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (194 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_integrate.cpython-310.pyc
ADDED
Binary file (919 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/benchmarks/__pycache__/bench_trigintegrate.cpython-310.pyc
ADDED
Binary file (705 Bytes). View file
|
|
venv/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)
|
venv/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
|
venv/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
|
venv/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
|
venv/lib/python3.10/site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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
|
venv/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)
|
venv/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)
|
venv/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
|
venv/lib/python3.10/site-packages/sympy/integrals/meij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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))
|
venv/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 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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)
|
venv/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
|
venv/lib/python3.10/site-packages/sympy/integrals/rationaltools.py
ADDED
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
venv/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)
|
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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)
|
venv/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
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_heurisch.cpython-310.pyc
ADDED
Binary file (13.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_integrals.cpython-310.pyc
ADDED
Binary file (87.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_intpoly.cpython-310.pyc
ADDED
Binary file (25 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_laplace.cpython-310.pyc
ADDED
Binary file (23.4 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_risch.cpython-310.pyc
ADDED
Binary file (35.4 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_transforms.cpython-310.pyc
ADDED
Binary file (23.4 kB). View file
|
|