Upload folder using huggingface_hub (part 18)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +23 -0
- .venv/lib/python3.12/site-packages/sympy/geometry/util.py +731 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/__init__.py +18 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-312.pyc +3 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/numerical.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/holonomic.py +2765 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/holonomicerrors.py +49 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/numerical.py +98 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/recurrence.py +342 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/tests/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/tests/test_holonomic.py +851 -0
- .venv/lib/python3.12/site-packages/sympy/holonomic/tests/test_recurrence.py +41 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__init__.py +45 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/deltafunctions.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/heurisch.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/integrals.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/intpoly.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/laplace.cpython-312.pyc +3 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/manualintegrate.cpython-312.pyc +3 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/meijerint.cpython-312.pyc +3 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/meijerint_doc.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/prde.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/quadrature.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/rationaltools.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/rde.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/risch.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/singularityfunctions.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/transforms.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/trigonometry.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/__pycache__/bench_integrate.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/__pycache__/bench_trigintegrate.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/bench_integrate.py +21 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/bench_trigintegrate.py +13 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/deltafunctions.py +201 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/heurisch.py +781 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/integrals.py +1640 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/intpoly.py +1302 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/laplace.py +2377 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/manualintegrate.py +2174 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/meijerint.py +2191 -0
- .venv/lib/python3.12/site-packages/sympy/integrals/meijerint_doc.py +38 -0
.gitattributes
CHANGED
|
@@ -432,3 +432,26 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 432 |
.venv/lib/python3.12/site-packages/sympy/functions/special/__pycache__/error_functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 433 |
.venv/lib/python3.12/site-packages/sympy/functions/special/tests/__pycache__/test_error_functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 434 |
.venv/lib/python3.12/site-packages/sympy/geometry/__pycache__/polygon.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
.venv/lib/python3.12/site-packages/sympy/functions/special/__pycache__/error_functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 433 |
.venv/lib/python3.12/site-packages/sympy/functions/special/tests/__pycache__/test_error_functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 434 |
.venv/lib/python3.12/site-packages/sympy/geometry/__pycache__/polygon.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 435 |
+
.venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 436 |
+
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/laplace.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 437 |
+
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/manualintegrate.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 438 |
+
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/meijerint.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 439 |
+
.venv/lib/python3.12/site-packages/sympy/integrals/tests/__pycache__/test_integrals.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 440 |
+
.venv/lib/python3.12/site-packages/sympy/logic/__pycache__/boolalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 441 |
+
.venv/lib/python3.12/site-packages/sympy/logic/tests/__pycache__/test_boolalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 442 |
+
.venv/lib/python3.12/site-packages/sympy/matrices/__pycache__/common.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 443 |
+
.venv/lib/python3.12/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 444 |
+
.venv/lib/python3.12/site-packages/sympy/matrices/tests/__pycache__/test_matrices.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 445 |
+
.venv/lib/python3.12/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 446 |
+
.venv/lib/python3.12/site-packages/sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 447 |
+
.venv/lib/python3.12/site-packages/sympy/parsing/autolev/_antlr/__pycache__/autolevparser.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 448 |
+
.venv/lib/python3.12/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexparser.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 449 |
+
.venv/lib/python3.12/site-packages/sympy/parsing/tests/__pycache__/test_c_parser.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 450 |
+
.venv/lib/python3.12/site-packages/sympy/physics/__pycache__/secondquant.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 451 |
+
.venv/lib/python3.12/site-packages/sympy/physics/biomechanics/tests/__pycache__/test_curve.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 452 |
+
.venv/lib/python3.12/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 453 |
+
.venv/lib/python3.12/site-packages/sympy/physics/control/__pycache__/lti.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 454 |
+
.venv/lib/python3.12/site-packages/sympy/physics/control/tests/__pycache__/test_lti.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 455 |
+
.venv/lib/python3.12/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 456 |
+
.venv/lib/python3.12/site-packages/sympy/physics/quantum/__pycache__/spin.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 457 |
+
.venv/lib/python3.12/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/sympy/geometry/util.py
ADDED
|
@@ -0,0 +1,731 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utility functions for geometrical entities.
|
| 2 |
+
|
| 3 |
+
Contains
|
| 4 |
+
========
|
| 5 |
+
intersection
|
| 6 |
+
convex_hull
|
| 7 |
+
closest_points
|
| 8 |
+
farthest_points
|
| 9 |
+
are_coplanar
|
| 10 |
+
are_similar
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from collections import deque
|
| 15 |
+
from math import sqrt as _sqrt
|
| 16 |
+
|
| 17 |
+
from sympy import nsimplify
|
| 18 |
+
from .entity import GeometryEntity
|
| 19 |
+
from .exceptions import GeometryError
|
| 20 |
+
from .point import Point, Point2D, Point3D
|
| 21 |
+
from sympy.core.containers import OrderedSet
|
| 22 |
+
from sympy.core.exprtools import factor_terms
|
| 23 |
+
from sympy.core.function import Function, expand_mul
|
| 24 |
+
from sympy.core.numbers import Float
|
| 25 |
+
from sympy.core.sorting import ordered
|
| 26 |
+
from sympy.core.symbol import Symbol
|
| 27 |
+
from sympy.core.singleton import S
|
| 28 |
+
from sympy.polys.polytools import cancel
|
| 29 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 30 |
+
from sympy.utilities.iterables import is_sequence
|
| 31 |
+
|
| 32 |
+
from mpmath.libmp.libmpf import prec_to_dps
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def find(x, equation):
|
| 36 |
+
"""
|
| 37 |
+
Checks whether a Symbol matching ``x`` is present in ``equation``
|
| 38 |
+
or not. If present, the matching symbol is returned, else a
|
| 39 |
+
ValueError is raised. If ``x`` is a string the matching symbol
|
| 40 |
+
will have the same name; if ``x`` is a Symbol then it will be
|
| 41 |
+
returned if found.
|
| 42 |
+
|
| 43 |
+
Examples
|
| 44 |
+
========
|
| 45 |
+
|
| 46 |
+
>>> from sympy.geometry.util import find
|
| 47 |
+
>>> from sympy import Dummy
|
| 48 |
+
>>> from sympy.abc import x
|
| 49 |
+
>>> find('x', x)
|
| 50 |
+
x
|
| 51 |
+
>>> find('x', Dummy('x'))
|
| 52 |
+
_x
|
| 53 |
+
|
| 54 |
+
The dummy symbol is returned since it has a matching name:
|
| 55 |
+
|
| 56 |
+
>>> _.name == 'x'
|
| 57 |
+
True
|
| 58 |
+
>>> find(x, Dummy('x'))
|
| 59 |
+
Traceback (most recent call last):
|
| 60 |
+
...
|
| 61 |
+
ValueError: could not find x
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
free = equation.free_symbols
|
| 65 |
+
xs = [i for i in free if (i.name if isinstance(x, str) else i) == x]
|
| 66 |
+
if not xs:
|
| 67 |
+
raise ValueError('could not find %s' % x)
|
| 68 |
+
if len(xs) != 1:
|
| 69 |
+
raise ValueError('ambiguous %s' % x)
|
| 70 |
+
return xs[0]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _ordered_points(p):
|
| 74 |
+
"""Return the tuple of points sorted numerically according to args"""
|
| 75 |
+
return tuple(sorted(p, key=lambda x: x.args))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def are_coplanar(*e):
|
| 79 |
+
""" Returns True if the given entities are coplanar otherwise False
|
| 80 |
+
|
| 81 |
+
Parameters
|
| 82 |
+
==========
|
| 83 |
+
|
| 84 |
+
e: entities to be checked for being coplanar
|
| 85 |
+
|
| 86 |
+
Returns
|
| 87 |
+
=======
|
| 88 |
+
|
| 89 |
+
Boolean
|
| 90 |
+
|
| 91 |
+
Examples
|
| 92 |
+
========
|
| 93 |
+
|
| 94 |
+
>>> from sympy import Point3D, Line3D
|
| 95 |
+
>>> from sympy.geometry.util import are_coplanar
|
| 96 |
+
>>> a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
|
| 97 |
+
>>> b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
|
| 98 |
+
>>> c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
|
| 99 |
+
>>> are_coplanar(a, b, c)
|
| 100 |
+
False
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
from .line import LinearEntity3D
|
| 104 |
+
from .plane import Plane
|
| 105 |
+
# XXX update tests for coverage
|
| 106 |
+
|
| 107 |
+
e = set(e)
|
| 108 |
+
# first work with a Plane if present
|
| 109 |
+
for i in list(e):
|
| 110 |
+
if isinstance(i, Plane):
|
| 111 |
+
e.remove(i)
|
| 112 |
+
return all(p.is_coplanar(i) for p in e)
|
| 113 |
+
|
| 114 |
+
if all(isinstance(i, Point3D) for i in e):
|
| 115 |
+
if len(e) < 3:
|
| 116 |
+
return False
|
| 117 |
+
|
| 118 |
+
# remove pts that are collinear with 2 pts
|
| 119 |
+
a, b = e.pop(), e.pop()
|
| 120 |
+
for i in list(e):
|
| 121 |
+
if Point3D.are_collinear(a, b, i):
|
| 122 |
+
e.remove(i)
|
| 123 |
+
|
| 124 |
+
if not e:
|
| 125 |
+
return False
|
| 126 |
+
else:
|
| 127 |
+
# define a plane
|
| 128 |
+
p = Plane(a, b, e.pop())
|
| 129 |
+
for i in e:
|
| 130 |
+
if i not in p:
|
| 131 |
+
return False
|
| 132 |
+
return True
|
| 133 |
+
else:
|
| 134 |
+
pt3d = []
|
| 135 |
+
for i in e:
|
| 136 |
+
if isinstance(i, Point3D):
|
| 137 |
+
pt3d.append(i)
|
| 138 |
+
elif isinstance(i, LinearEntity3D):
|
| 139 |
+
pt3d.extend(i.args)
|
| 140 |
+
elif isinstance(i, GeometryEntity): # XXX we should have a GeometryEntity3D class so we can tell the difference between 2D and 3D -- here we just want to deal with 2D objects; if new 3D objects are encountered that we didn't handle above, an error should be raised
|
| 141 |
+
# all 2D objects have some Point that defines them; so convert those points to 3D pts by making z=0
|
| 142 |
+
for p in i.args:
|
| 143 |
+
if isinstance(p, Point):
|
| 144 |
+
pt3d.append(Point3D(*(p.args + (0,))))
|
| 145 |
+
return are_coplanar(*pt3d)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def are_similar(e1, e2):
|
| 149 |
+
"""Are two geometrical entities similar.
|
| 150 |
+
|
| 151 |
+
Can one geometrical entity be uniformly scaled to the other?
|
| 152 |
+
|
| 153 |
+
Parameters
|
| 154 |
+
==========
|
| 155 |
+
|
| 156 |
+
e1 : GeometryEntity
|
| 157 |
+
e2 : GeometryEntity
|
| 158 |
+
|
| 159 |
+
Returns
|
| 160 |
+
=======
|
| 161 |
+
|
| 162 |
+
are_similar : boolean
|
| 163 |
+
|
| 164 |
+
Raises
|
| 165 |
+
======
|
| 166 |
+
|
| 167 |
+
GeometryError
|
| 168 |
+
When `e1` and `e2` cannot be compared.
|
| 169 |
+
|
| 170 |
+
Notes
|
| 171 |
+
=====
|
| 172 |
+
|
| 173 |
+
If the two objects are equal then they are similar.
|
| 174 |
+
|
| 175 |
+
See Also
|
| 176 |
+
========
|
| 177 |
+
|
| 178 |
+
sympy.geometry.entity.GeometryEntity.is_similar
|
| 179 |
+
|
| 180 |
+
Examples
|
| 181 |
+
========
|
| 182 |
+
|
| 183 |
+
>>> from sympy import Point, Circle, Triangle, are_similar
|
| 184 |
+
>>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3)
|
| 185 |
+
>>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
|
| 186 |
+
>>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2))
|
| 187 |
+
>>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1))
|
| 188 |
+
>>> are_similar(t1, t2)
|
| 189 |
+
True
|
| 190 |
+
>>> are_similar(t1, t3)
|
| 191 |
+
False
|
| 192 |
+
|
| 193 |
+
"""
|
| 194 |
+
if e1 == e2:
|
| 195 |
+
return True
|
| 196 |
+
is_similar1 = getattr(e1, 'is_similar', None)
|
| 197 |
+
if is_similar1:
|
| 198 |
+
return is_similar1(e2)
|
| 199 |
+
is_similar2 = getattr(e2, 'is_similar', None)
|
| 200 |
+
if is_similar2:
|
| 201 |
+
return is_similar2(e1)
|
| 202 |
+
n1 = e1.__class__.__name__
|
| 203 |
+
n2 = e2.__class__.__name__
|
| 204 |
+
raise GeometryError(
|
| 205 |
+
"Cannot test similarity between %s and %s" % (n1, n2))
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def centroid(*args):
|
| 209 |
+
"""Find the centroid (center of mass) of the collection containing only Points,
|
| 210 |
+
Segments or Polygons. The centroid is the weighted average of the individual centroid
|
| 211 |
+
where the weights are the lengths (of segments) or areas (of polygons).
|
| 212 |
+
Overlapping regions will add to the weight of that region.
|
| 213 |
+
|
| 214 |
+
If there are no objects (or a mixture of objects) then None is returned.
|
| 215 |
+
|
| 216 |
+
See Also
|
| 217 |
+
========
|
| 218 |
+
|
| 219 |
+
sympy.geometry.point.Point, sympy.geometry.line.Segment,
|
| 220 |
+
sympy.geometry.polygon.Polygon
|
| 221 |
+
|
| 222 |
+
Examples
|
| 223 |
+
========
|
| 224 |
+
|
| 225 |
+
>>> from sympy import Point, Segment, Polygon
|
| 226 |
+
>>> from sympy.geometry.util import centroid
|
| 227 |
+
>>> p = Polygon((0, 0), (10, 0), (10, 10))
|
| 228 |
+
>>> q = p.translate(0, 20)
|
| 229 |
+
>>> p.centroid, q.centroid
|
| 230 |
+
(Point2D(20/3, 10/3), Point2D(20/3, 70/3))
|
| 231 |
+
>>> centroid(p, q)
|
| 232 |
+
Point2D(20/3, 40/3)
|
| 233 |
+
>>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))
|
| 234 |
+
>>> centroid(p, q)
|
| 235 |
+
Point2D(1, 2 - sqrt(2))
|
| 236 |
+
>>> centroid(Point(0, 0), Point(2, 0))
|
| 237 |
+
Point2D(1, 0)
|
| 238 |
+
|
| 239 |
+
Stacking 3 polygons on top of each other effectively triples the
|
| 240 |
+
weight of that polygon:
|
| 241 |
+
|
| 242 |
+
>>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))
|
| 243 |
+
>>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))
|
| 244 |
+
>>> centroid(p, q)
|
| 245 |
+
Point2D(3/2, 1/2)
|
| 246 |
+
>>> centroid(p, p, p, q) # centroid x-coord shifts left
|
| 247 |
+
Point2D(11/10, 1/2)
|
| 248 |
+
|
| 249 |
+
Stacking the squares vertically above and below p has the same
|
| 250 |
+
effect:
|
| 251 |
+
|
| 252 |
+
>>> centroid(p, p.translate(0, 1), p.translate(0, -1), q)
|
| 253 |
+
Point2D(11/10, 1/2)
|
| 254 |
+
|
| 255 |
+
"""
|
| 256 |
+
from .line import Segment
|
| 257 |
+
from .polygon import Polygon
|
| 258 |
+
if args:
|
| 259 |
+
if all(isinstance(g, Point) for g in args):
|
| 260 |
+
c = Point(0, 0)
|
| 261 |
+
for g in args:
|
| 262 |
+
c += g
|
| 263 |
+
den = len(args)
|
| 264 |
+
elif all(isinstance(g, Segment) for g in args):
|
| 265 |
+
c = Point(0, 0)
|
| 266 |
+
L = 0
|
| 267 |
+
for g in args:
|
| 268 |
+
l = g.length
|
| 269 |
+
c += g.midpoint*l
|
| 270 |
+
L += l
|
| 271 |
+
den = L
|
| 272 |
+
elif all(isinstance(g, Polygon) for g in args):
|
| 273 |
+
c = Point(0, 0)
|
| 274 |
+
A = 0
|
| 275 |
+
for g in args:
|
| 276 |
+
a = g.area
|
| 277 |
+
c += g.centroid*a
|
| 278 |
+
A += a
|
| 279 |
+
den = A
|
| 280 |
+
c /= den
|
| 281 |
+
return c.func(*[i.simplify() for i in c.args])
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def closest_points(*args):
|
| 285 |
+
"""Return the subset of points from a set of points that were
|
| 286 |
+
the closest to each other in the 2D plane.
|
| 287 |
+
|
| 288 |
+
Parameters
|
| 289 |
+
==========
|
| 290 |
+
|
| 291 |
+
args
|
| 292 |
+
A collection of Points on 2D plane.
|
| 293 |
+
|
| 294 |
+
Notes
|
| 295 |
+
=====
|
| 296 |
+
|
| 297 |
+
This can only be performed on a set of points whose coordinates can
|
| 298 |
+
be ordered on the number line. If there are no ties then a single
|
| 299 |
+
pair of Points will be in the set.
|
| 300 |
+
|
| 301 |
+
Examples
|
| 302 |
+
========
|
| 303 |
+
|
| 304 |
+
>>> from sympy import closest_points, Triangle
|
| 305 |
+
>>> Triangle(sss=(3, 4, 5)).args
|
| 306 |
+
(Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
|
| 307 |
+
>>> closest_points(*_)
|
| 308 |
+
{(Point2D(0, 0), Point2D(3, 0))}
|
| 309 |
+
|
| 310 |
+
References
|
| 311 |
+
==========
|
| 312 |
+
|
| 313 |
+
.. [1] https://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html
|
| 314 |
+
|
| 315 |
+
.. [2] Sweep line algorithm
|
| 316 |
+
https://en.wikipedia.org/wiki/Sweep_line_algorithm
|
| 317 |
+
|
| 318 |
+
"""
|
| 319 |
+
p = [Point2D(i) for i in set(args)]
|
| 320 |
+
if len(p) < 2:
|
| 321 |
+
raise ValueError('At least 2 distinct points must be given.')
|
| 322 |
+
|
| 323 |
+
try:
|
| 324 |
+
p.sort(key=lambda x: x.args)
|
| 325 |
+
except TypeError:
|
| 326 |
+
raise ValueError("The points could not be sorted.")
|
| 327 |
+
|
| 328 |
+
if not all(i.is_Rational for j in p for i in j.args):
|
| 329 |
+
def hypot(x, y):
|
| 330 |
+
arg = x*x + y*y
|
| 331 |
+
if arg.is_Rational:
|
| 332 |
+
return _sqrt(arg)
|
| 333 |
+
return sqrt(arg)
|
| 334 |
+
else:
|
| 335 |
+
from math import hypot
|
| 336 |
+
|
| 337 |
+
rv = [(0, 1)]
|
| 338 |
+
best_dist = hypot(p[1].x - p[0].x, p[1].y - p[0].y)
|
| 339 |
+
left = 0
|
| 340 |
+
box = deque([0, 1])
|
| 341 |
+
for i in range(2, len(p)):
|
| 342 |
+
while left < i and p[i][0] - p[left][0] > best_dist:
|
| 343 |
+
box.popleft()
|
| 344 |
+
left += 1
|
| 345 |
+
|
| 346 |
+
for j in box:
|
| 347 |
+
d = hypot(p[i].x - p[j].x, p[i].y - p[j].y)
|
| 348 |
+
if d < best_dist:
|
| 349 |
+
rv = [(j, i)]
|
| 350 |
+
elif d == best_dist:
|
| 351 |
+
rv.append((j, i))
|
| 352 |
+
else:
|
| 353 |
+
continue
|
| 354 |
+
best_dist = d
|
| 355 |
+
box.append(i)
|
| 356 |
+
|
| 357 |
+
return {tuple([p[i] for i in pair]) for pair in rv}
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def convex_hull(*args, polygon=True):
|
| 361 |
+
"""The convex hull surrounding the Points contained in the list of entities.
|
| 362 |
+
|
| 363 |
+
Parameters
|
| 364 |
+
==========
|
| 365 |
+
|
| 366 |
+
args : a collection of Points, Segments and/or Polygons
|
| 367 |
+
|
| 368 |
+
Optional parameters
|
| 369 |
+
===================
|
| 370 |
+
|
| 371 |
+
polygon : Boolean. If True, returns a Polygon, if false a tuple, see below.
|
| 372 |
+
Default is True.
|
| 373 |
+
|
| 374 |
+
Returns
|
| 375 |
+
=======
|
| 376 |
+
|
| 377 |
+
convex_hull : Polygon if ``polygon`` is True else as a tuple `(U, L)` where
|
| 378 |
+
``L`` and ``U`` are the lower and upper hulls, respectively.
|
| 379 |
+
|
| 380 |
+
Notes
|
| 381 |
+
=====
|
| 382 |
+
|
| 383 |
+
This can only be performed on a set of points whose coordinates can
|
| 384 |
+
be ordered on the number line.
|
| 385 |
+
|
| 386 |
+
See Also
|
| 387 |
+
========
|
| 388 |
+
|
| 389 |
+
sympy.geometry.point.Point, sympy.geometry.polygon.Polygon
|
| 390 |
+
|
| 391 |
+
Examples
|
| 392 |
+
========
|
| 393 |
+
|
| 394 |
+
>>> from sympy import convex_hull
|
| 395 |
+
>>> points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
|
| 396 |
+
>>> convex_hull(*points)
|
| 397 |
+
Polygon(Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4))
|
| 398 |
+
>>> convex_hull(*points, **dict(polygon=False))
|
| 399 |
+
([Point2D(-5, 2), Point2D(15, 4)],
|
| 400 |
+
[Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)])
|
| 401 |
+
|
| 402 |
+
References
|
| 403 |
+
==========
|
| 404 |
+
|
| 405 |
+
.. [1] https://en.wikipedia.org/wiki/Graham_scan
|
| 406 |
+
|
| 407 |
+
.. [2] Andrew's Monotone Chain Algorithm
|
| 408 |
+
(A.M. Andrew,
|
| 409 |
+
"Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979)
|
| 410 |
+
https://web.archive.org/web/20210511015444/http://geomalgorithms.com/a10-_hull-1.html
|
| 411 |
+
|
| 412 |
+
"""
|
| 413 |
+
from .line import Segment
|
| 414 |
+
from .polygon import Polygon
|
| 415 |
+
p = OrderedSet()
|
| 416 |
+
for e in args:
|
| 417 |
+
if not isinstance(e, GeometryEntity):
|
| 418 |
+
try:
|
| 419 |
+
e = Point(e)
|
| 420 |
+
except NotImplementedError:
|
| 421 |
+
raise ValueError('%s is not a GeometryEntity and cannot be made into Point' % str(e))
|
| 422 |
+
if isinstance(e, Point):
|
| 423 |
+
p.add(e)
|
| 424 |
+
elif isinstance(e, Segment):
|
| 425 |
+
p.update(e.points)
|
| 426 |
+
elif isinstance(e, Polygon):
|
| 427 |
+
p.update(e.vertices)
|
| 428 |
+
else:
|
| 429 |
+
raise NotImplementedError(
|
| 430 |
+
'Convex hull for %s not implemented.' % type(e))
|
| 431 |
+
|
| 432 |
+
# make sure all our points are of the same dimension
|
| 433 |
+
if any(len(x) != 2 for x in p):
|
| 434 |
+
raise ValueError('Can only compute the convex hull in two dimensions')
|
| 435 |
+
|
| 436 |
+
p = list(p)
|
| 437 |
+
if len(p) == 1:
|
| 438 |
+
return p[0] if polygon else (p[0], None)
|
| 439 |
+
elif len(p) == 2:
|
| 440 |
+
s = Segment(p[0], p[1])
|
| 441 |
+
return s if polygon else (s, None)
|
| 442 |
+
|
| 443 |
+
def _orientation(p, q, r):
|
| 444 |
+
'''Return positive if p-q-r are clockwise, neg if ccw, zero if
|
| 445 |
+
collinear.'''
|
| 446 |
+
return (q.y - p.y)*(r.x - p.x) - (q.x - p.x)*(r.y - p.y)
|
| 447 |
+
|
| 448 |
+
# scan to find upper and lower convex hulls of a set of 2d points.
|
| 449 |
+
U = []
|
| 450 |
+
L = []
|
| 451 |
+
try:
|
| 452 |
+
p.sort(key=lambda x: x.args)
|
| 453 |
+
except TypeError:
|
| 454 |
+
raise ValueError("The points could not be sorted.")
|
| 455 |
+
for p_i in p:
|
| 456 |
+
while len(U) > 1 and _orientation(U[-2], U[-1], p_i) <= 0:
|
| 457 |
+
U.pop()
|
| 458 |
+
while len(L) > 1 and _orientation(L[-2], L[-1], p_i) >= 0:
|
| 459 |
+
L.pop()
|
| 460 |
+
U.append(p_i)
|
| 461 |
+
L.append(p_i)
|
| 462 |
+
U.reverse()
|
| 463 |
+
convexHull = tuple(L + U[1:-1])
|
| 464 |
+
|
| 465 |
+
if len(convexHull) == 2:
|
| 466 |
+
s = Segment(convexHull[0], convexHull[1])
|
| 467 |
+
return s if polygon else (s, None)
|
| 468 |
+
if polygon:
|
| 469 |
+
return Polygon(*convexHull)
|
| 470 |
+
else:
|
| 471 |
+
U.reverse()
|
| 472 |
+
return (U, L)
|
| 473 |
+
|
| 474 |
+
def farthest_points(*args):
|
| 475 |
+
"""Return the subset of points from a set of points that were
|
| 476 |
+
the furthest apart from each other in the 2D plane.
|
| 477 |
+
|
| 478 |
+
Parameters
|
| 479 |
+
==========
|
| 480 |
+
|
| 481 |
+
args
|
| 482 |
+
A collection of Points on 2D plane.
|
| 483 |
+
|
| 484 |
+
Notes
|
| 485 |
+
=====
|
| 486 |
+
|
| 487 |
+
This can only be performed on a set of points whose coordinates can
|
| 488 |
+
be ordered on the number line. If there are no ties then a single
|
| 489 |
+
pair of Points will be in the set.
|
| 490 |
+
|
| 491 |
+
Examples
|
| 492 |
+
========
|
| 493 |
+
|
| 494 |
+
>>> from sympy.geometry import farthest_points, Triangle
|
| 495 |
+
>>> Triangle(sss=(3, 4, 5)).args
|
| 496 |
+
(Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
|
| 497 |
+
>>> farthest_points(*_)
|
| 498 |
+
{(Point2D(0, 0), Point2D(3, 4))}
|
| 499 |
+
|
| 500 |
+
References
|
| 501 |
+
==========
|
| 502 |
+
|
| 503 |
+
.. [1] https://code.activestate.com/recipes/117225-convex-hull-and-diameter-of-2d-point-sets/
|
| 504 |
+
|
| 505 |
+
.. [2] Rotating Callipers Technique
|
| 506 |
+
https://en.wikipedia.org/wiki/Rotating_calipers
|
| 507 |
+
|
| 508 |
+
"""
|
| 509 |
+
|
| 510 |
+
def rotatingCalipers(Points):
|
| 511 |
+
U, L = convex_hull(*Points, **{"polygon": False})
|
| 512 |
+
|
| 513 |
+
if L is None:
|
| 514 |
+
if isinstance(U, Point):
|
| 515 |
+
raise ValueError('At least two distinct points must be given.')
|
| 516 |
+
yield U.args
|
| 517 |
+
else:
|
| 518 |
+
i = 0
|
| 519 |
+
j = len(L) - 1
|
| 520 |
+
while i < len(U) - 1 or j > 0:
|
| 521 |
+
yield U[i], L[j]
|
| 522 |
+
# if all the way through one side of hull, advance the other side
|
| 523 |
+
if i == len(U) - 1:
|
| 524 |
+
j -= 1
|
| 525 |
+
elif j == 0:
|
| 526 |
+
i += 1
|
| 527 |
+
# still points left on both lists, compare slopes of next hull edges
|
| 528 |
+
# being careful to avoid divide-by-zero in slope calculation
|
| 529 |
+
elif (U[i+1].y - U[i].y) * (L[j].x - L[j-1].x) > \
|
| 530 |
+
(L[j].y - L[j-1].y) * (U[i+1].x - U[i].x):
|
| 531 |
+
i += 1
|
| 532 |
+
else:
|
| 533 |
+
j -= 1
|
| 534 |
+
|
| 535 |
+
p = [Point2D(i) for i in set(args)]
|
| 536 |
+
|
| 537 |
+
if not all(i.is_Rational for j in p for i in j.args):
|
| 538 |
+
def hypot(x, y):
|
| 539 |
+
arg = x*x + y*y
|
| 540 |
+
if arg.is_Rational:
|
| 541 |
+
return _sqrt(arg)
|
| 542 |
+
return sqrt(arg)
|
| 543 |
+
else:
|
| 544 |
+
from math import hypot
|
| 545 |
+
|
| 546 |
+
rv = []
|
| 547 |
+
diam = 0
|
| 548 |
+
for pair in rotatingCalipers(args):
|
| 549 |
+
h, q = _ordered_points(pair)
|
| 550 |
+
d = hypot(h.x - q.x, h.y - q.y)
|
| 551 |
+
if d > diam:
|
| 552 |
+
rv = [(h, q)]
|
| 553 |
+
elif d == diam:
|
| 554 |
+
rv.append((h, q))
|
| 555 |
+
else:
|
| 556 |
+
continue
|
| 557 |
+
diam = d
|
| 558 |
+
|
| 559 |
+
return set(rv)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def idiff(eq, y, x, n=1):
|
| 563 |
+
"""Return ``dy/dx`` assuming that ``eq == 0``.
|
| 564 |
+
|
| 565 |
+
Parameters
|
| 566 |
+
==========
|
| 567 |
+
|
| 568 |
+
y : the dependent variable or a list of dependent variables (with y first)
|
| 569 |
+
x : the variable that the derivative is being taken with respect to
|
| 570 |
+
n : the order of the derivative (default is 1)
|
| 571 |
+
|
| 572 |
+
Examples
|
| 573 |
+
========
|
| 574 |
+
|
| 575 |
+
>>> from sympy.abc import x, y, a
|
| 576 |
+
>>> from sympy.geometry.util import idiff
|
| 577 |
+
|
| 578 |
+
>>> circ = x**2 + y**2 - 4
|
| 579 |
+
>>> idiff(circ, y, x)
|
| 580 |
+
-x/y
|
| 581 |
+
>>> idiff(circ, y, x, 2).simplify()
|
| 582 |
+
(-x**2 - y**2)/y**3
|
| 583 |
+
|
| 584 |
+
Here, ``a`` is assumed to be independent of ``x``:
|
| 585 |
+
|
| 586 |
+
>>> idiff(x + a + y, y, x)
|
| 587 |
+
-1
|
| 588 |
+
|
| 589 |
+
Now the x-dependence of ``a`` is made explicit by listing ``a`` after
|
| 590 |
+
``y`` in a list.
|
| 591 |
+
|
| 592 |
+
>>> idiff(x + a + y, [y, a], x)
|
| 593 |
+
-Derivative(a, x) - 1
|
| 594 |
+
|
| 595 |
+
See Also
|
| 596 |
+
========
|
| 597 |
+
|
| 598 |
+
sympy.core.function.Derivative: represents unevaluated derivatives
|
| 599 |
+
sympy.core.function.diff: explicitly differentiates wrt symbols
|
| 600 |
+
|
| 601 |
+
"""
|
| 602 |
+
if is_sequence(y):
|
| 603 |
+
dep = set(y)
|
| 604 |
+
y = y[0]
|
| 605 |
+
elif isinstance(y, Symbol):
|
| 606 |
+
dep = {y}
|
| 607 |
+
elif isinstance(y, Function):
|
| 608 |
+
pass
|
| 609 |
+
else:
|
| 610 |
+
raise ValueError("expecting x-dependent symbol(s) or function(s) but got: %s" % y)
|
| 611 |
+
|
| 612 |
+
f = {s: Function(s.name)(x) for s in eq.free_symbols
|
| 613 |
+
if s != x and s in dep}
|
| 614 |
+
|
| 615 |
+
if isinstance(y, Symbol):
|
| 616 |
+
dydx = Function(y.name)(x).diff(x)
|
| 617 |
+
else:
|
| 618 |
+
dydx = y.diff(x)
|
| 619 |
+
|
| 620 |
+
eq = eq.subs(f)
|
| 621 |
+
derivs = {}
|
| 622 |
+
for i in range(n):
|
| 623 |
+
# equation will be linear in dydx, a*dydx + b, so dydx = -b/a
|
| 624 |
+
deq = eq.diff(x)
|
| 625 |
+
b = deq.xreplace({dydx: S.Zero})
|
| 626 |
+
a = (deq - b).xreplace({dydx: S.One})
|
| 627 |
+
yp = factor_terms(expand_mul(cancel((-b/a).subs(derivs)), deep=False))
|
| 628 |
+
if i == n - 1:
|
| 629 |
+
return yp.subs([(v, k) for k, v in f.items()])
|
| 630 |
+
derivs[dydx] = yp
|
| 631 |
+
eq = dydx - yp
|
| 632 |
+
dydx = dydx.diff(x)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def intersection(*entities, pairwise=False, **kwargs):
|
| 636 |
+
"""The intersection of a collection of GeometryEntity instances.
|
| 637 |
+
|
| 638 |
+
Parameters
|
| 639 |
+
==========
|
| 640 |
+
entities : sequence of GeometryEntity
|
| 641 |
+
pairwise (keyword argument) : Can be either True or False
|
| 642 |
+
|
| 643 |
+
Returns
|
| 644 |
+
=======
|
| 645 |
+
intersection : list of GeometryEntity
|
| 646 |
+
|
| 647 |
+
Raises
|
| 648 |
+
======
|
| 649 |
+
NotImplementedError
|
| 650 |
+
When unable to calculate intersection.
|
| 651 |
+
|
| 652 |
+
Notes
|
| 653 |
+
=====
|
| 654 |
+
The intersection of any geometrical entity with itself should return
|
| 655 |
+
a list with one item: the entity in question.
|
| 656 |
+
An intersection requires two or more entities. If only a single
|
| 657 |
+
entity is given then the function will return an empty list.
|
| 658 |
+
It is possible for `intersection` to miss intersections that one
|
| 659 |
+
knows exists because the required quantities were not fully
|
| 660 |
+
simplified internally.
|
| 661 |
+
Reals should be converted to Rationals, e.g. Rational(str(real_num))
|
| 662 |
+
or else failures due to floating point issues may result.
|
| 663 |
+
|
| 664 |
+
Case 1: When the keyword argument 'pairwise' is False (default value):
|
| 665 |
+
In this case, the function returns a list of intersections common to
|
| 666 |
+
all entities.
|
| 667 |
+
|
| 668 |
+
Case 2: When the keyword argument 'pairwise' is True:
|
| 669 |
+
In this case, the functions returns a list intersections that occur
|
| 670 |
+
between any pair of entities.
|
| 671 |
+
|
| 672 |
+
See Also
|
| 673 |
+
========
|
| 674 |
+
|
| 675 |
+
sympy.geometry.entity.GeometryEntity.intersection
|
| 676 |
+
|
| 677 |
+
Examples
|
| 678 |
+
========
|
| 679 |
+
|
| 680 |
+
>>> from sympy import Ray, Circle, intersection
|
| 681 |
+
>>> c = Circle((0, 1), 1)
|
| 682 |
+
>>> intersection(c, c.center)
|
| 683 |
+
[]
|
| 684 |
+
>>> right = Ray((0, 0), (1, 0))
|
| 685 |
+
>>> up = Ray((0, 0), (0, 1))
|
| 686 |
+
>>> intersection(c, right, up)
|
| 687 |
+
[Point2D(0, 0)]
|
| 688 |
+
>>> intersection(c, right, up, pairwise=True)
|
| 689 |
+
[Point2D(0, 0), Point2D(0, 2)]
|
| 690 |
+
>>> left = Ray((1, 0), (0, 0))
|
| 691 |
+
>>> intersection(right, left)
|
| 692 |
+
[Segment2D(Point2D(0, 0), Point2D(1, 0))]
|
| 693 |
+
|
| 694 |
+
"""
|
| 695 |
+
if len(entities) <= 1:
|
| 696 |
+
return []
|
| 697 |
+
|
| 698 |
+
entities = list(entities)
|
| 699 |
+
prec = None
|
| 700 |
+
for i, e in enumerate(entities):
|
| 701 |
+
if not isinstance(e, GeometryEntity):
|
| 702 |
+
# entities may be an immutable tuple
|
| 703 |
+
e = Point(e)
|
| 704 |
+
# convert to exact Rationals
|
| 705 |
+
d = {}
|
| 706 |
+
for f in e.atoms(Float):
|
| 707 |
+
prec = f._prec if prec is None else min(f._prec, prec)
|
| 708 |
+
d.setdefault(f, nsimplify(f, rational=True))
|
| 709 |
+
entities[i] = e.xreplace(d)
|
| 710 |
+
|
| 711 |
+
if not pairwise:
|
| 712 |
+
# find the intersection common to all objects
|
| 713 |
+
res = entities[0].intersection(entities[1])
|
| 714 |
+
for entity in entities[2:]:
|
| 715 |
+
newres = []
|
| 716 |
+
for x in res:
|
| 717 |
+
newres.extend(x.intersection(entity))
|
| 718 |
+
res = newres
|
| 719 |
+
else:
|
| 720 |
+
# find all pairwise intersections
|
| 721 |
+
ans = []
|
| 722 |
+
for j in range(len(entities)):
|
| 723 |
+
for k in range(j + 1, len(entities)):
|
| 724 |
+
ans.extend(intersection(entities[j], entities[k]))
|
| 725 |
+
res = list(ordered(set(ans)))
|
| 726 |
+
|
| 727 |
+
# convert back to Floats
|
| 728 |
+
if prec is not None:
|
| 729 |
+
p = prec_to_dps(prec)
|
| 730 |
+
res = [i.n(p) for i in res]
|
| 731 |
+
return res
|
.venv/lib/python3.12/site-packages/sympy/holonomic/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
The :py:mod:`~sympy.holonomic` module is intended to deal with holonomic functions along
|
| 3 |
+
with various operations on them like addition, multiplication, composition,
|
| 4 |
+
integration and differentiation. The module also implements various kinds of
|
| 5 |
+
conversions such as converting holonomic functions to a different form and the
|
| 6 |
+
other way around.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from .holonomic import (DifferentialOperator, HolonomicFunction, DifferentialOperators,
|
| 10 |
+
from_hyper, from_meijerg, expr_to_holonomic)
|
| 11 |
+
from .recurrence import RecurrenceOperators, RecurrenceOperator, HolonomicSequence
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
'DifferentialOperator', 'HolonomicFunction', 'DifferentialOperators',
|
| 15 |
+
'from_hyper', 'from_meijerg', 'expr_to_holonomic',
|
| 16 |
+
|
| 17 |
+
'RecurrenceOperators', 'RecurrenceOperator', 'HolonomicSequence',
|
| 18 |
+
]
|
.venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (935 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/holonomic.cpython-312.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dc7697e3ce518ef192ef1d4d216c6cf36efc18cd55aee5ab71a53fd4b03925fa
|
| 3 |
+
size 121362
|
.venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/holonomicerrors.cpython-312.pyc
ADDED
|
Binary file (2.93 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/numerical.cpython-312.pyc
ADDED
|
Binary file (5.8 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/holonomic/__pycache__/recurrence.cpython-312.pyc
ADDED
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module implements Holonomic Functions and
|
| 3 |
+
various operations on them.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from sympy.core import Add, Mul, Pow
|
| 7 |
+
from sympy.core.numbers import (NaN, Infinity, NegativeInfinity, Float, I, pi,
|
| 8 |
+
equal_valued, int_valued)
|
| 9 |
+
from sympy.core.singleton import S
|
| 10 |
+
from sympy.core.sorting import ordered
|
| 11 |
+
from sympy.core.symbol import Dummy, Symbol
|
| 12 |
+
from sympy.core.sympify import sympify
|
| 13 |
+
from sympy.functions.combinatorial.factorials import binomial, factorial, rf
|
| 14 |
+
from sympy.functions.elementary.exponential import exp_polar, exp, log
|
| 15 |
+
from sympy.functions.elementary.hyperbolic import (cosh, sinh)
|
| 16 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 17 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, sinc)
|
| 18 |
+
from sympy.functions.special.error_functions import (Ci, Shi, Si, erf, erfc, erfi)
|
| 19 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 20 |
+
from sympy.functions.special.hyper import hyper, meijerg
|
| 21 |
+
from sympy.integrals import meijerint
|
| 22 |
+
from sympy.matrices import Matrix
|
| 23 |
+
from sympy.polys.rings import PolyElement
|
| 24 |
+
from sympy.polys.fields import FracElement
|
| 25 |
+
from sympy.polys.domains import QQ, RR
|
| 26 |
+
from sympy.polys.polyclasses import DMF
|
| 27 |
+
from sympy.polys.polyroots import roots
|
| 28 |
+
from sympy.polys.polytools import Poly
|
| 29 |
+
from sympy.polys.matrices import DomainMatrix
|
| 30 |
+
from sympy.printing import sstr
|
| 31 |
+
from sympy.series.limits import limit
|
| 32 |
+
from sympy.series.order import Order
|
| 33 |
+
from sympy.simplify.hyperexpand import hyperexpand
|
| 34 |
+
from sympy.simplify.simplify import nsimplify
|
| 35 |
+
from sympy.solvers.solvers import solve
|
| 36 |
+
|
| 37 |
+
from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators
|
| 38 |
+
from .holonomicerrors import (NotPowerSeriesError, NotHyperSeriesError,
|
| 39 |
+
SingularityError, NotHolonomicError)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _find_nonzero_solution(r, homosys):
|
| 43 |
+
ones = lambda shape: DomainMatrix.ones(shape, r.domain)
|
| 44 |
+
particular, nullspace = r._solve(homosys)
|
| 45 |
+
nullity = nullspace.shape[0]
|
| 46 |
+
nullpart = ones((1, nullity)) * nullspace
|
| 47 |
+
sol = (particular + nullpart).transpose()
|
| 48 |
+
return sol
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def DifferentialOperators(base, generator):
|
| 53 |
+
r"""
|
| 54 |
+
This function is used to create annihilators using ``Dx``.
|
| 55 |
+
|
| 56 |
+
Explanation
|
| 57 |
+
===========
|
| 58 |
+
|
| 59 |
+
Returns an Algebra of Differential Operators also called Weyl Algebra
|
| 60 |
+
and the operator for differentiation i.e. the ``Dx`` operator.
|
| 61 |
+
|
| 62 |
+
Parameters
|
| 63 |
+
==========
|
| 64 |
+
|
| 65 |
+
base:
|
| 66 |
+
Base polynomial ring for the algebra.
|
| 67 |
+
The base polynomial ring is the ring of polynomials in :math:`x` that
|
| 68 |
+
will appear as coefficients in the operators.
|
| 69 |
+
generator:
|
| 70 |
+
Generator of the algebra which can
|
| 71 |
+
be either a noncommutative ``Symbol`` or a string. e.g. "Dx" or "D".
|
| 72 |
+
|
| 73 |
+
Examples
|
| 74 |
+
========
|
| 75 |
+
|
| 76 |
+
>>> from sympy import ZZ
|
| 77 |
+
>>> from sympy.abc import x
|
| 78 |
+
>>> from sympy.holonomic.holonomic import DifferentialOperators
|
| 79 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 80 |
+
>>> R
|
| 81 |
+
Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x]
|
| 82 |
+
>>> Dx*x
|
| 83 |
+
(1) + (x)*Dx
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
ring = DifferentialOperatorAlgebra(base, generator)
|
| 87 |
+
return (ring, ring.derivative_operator)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class DifferentialOperatorAlgebra:
|
| 91 |
+
r"""
|
| 92 |
+
An Ore Algebra is a set of noncommutative polynomials in the
|
| 93 |
+
intermediate ``Dx`` and coefficients in a base polynomial ring :math:`A`.
|
| 94 |
+
It follows the commutation rule:
|
| 95 |
+
|
| 96 |
+
.. math ::
|
| 97 |
+
Dxa = \sigma(a)Dx + \delta(a)
|
| 98 |
+
|
| 99 |
+
for :math:`a \subset A`.
|
| 100 |
+
|
| 101 |
+
Where :math:`\sigma: A \Rightarrow A` is an endomorphism and :math:`\delta: A \rightarrow A`
|
| 102 |
+
is a skew-derivation i.e. :math:`\delta(ab) = \delta(a) b + \sigma(a) \delta(b)`.
|
| 103 |
+
|
| 104 |
+
If one takes the sigma as identity map and delta as the standard derivation
|
| 105 |
+
then it becomes the algebra of Differential Operators also called
|
| 106 |
+
a Weyl Algebra i.e. an algebra whose elements are Differential Operators.
|
| 107 |
+
|
| 108 |
+
This class represents a Weyl Algebra and serves as the parent ring for
|
| 109 |
+
Differential Operators.
|
| 110 |
+
|
| 111 |
+
Examples
|
| 112 |
+
========
|
| 113 |
+
|
| 114 |
+
>>> from sympy import ZZ
|
| 115 |
+
>>> from sympy import symbols
|
| 116 |
+
>>> from sympy.holonomic.holonomic import DifferentialOperators
|
| 117 |
+
>>> x = symbols('x')
|
| 118 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 119 |
+
>>> R
|
| 120 |
+
Univariate Differential Operator Algebra in intermediate Dx over the base ring
|
| 121 |
+
ZZ[x]
|
| 122 |
+
|
| 123 |
+
See Also
|
| 124 |
+
========
|
| 125 |
+
|
| 126 |
+
DifferentialOperator
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
def __init__(self, base, generator):
|
| 130 |
+
# the base polynomial ring for the algebra
|
| 131 |
+
self.base = base
|
| 132 |
+
# the operator representing differentiation i.e. `Dx`
|
| 133 |
+
self.derivative_operator = DifferentialOperator(
|
| 134 |
+
[base.zero, base.one], self)
|
| 135 |
+
|
| 136 |
+
if generator is None:
|
| 137 |
+
self.gen_symbol = Symbol('Dx', commutative=False)
|
| 138 |
+
else:
|
| 139 |
+
if isinstance(generator, str):
|
| 140 |
+
self.gen_symbol = Symbol(generator, commutative=False)
|
| 141 |
+
elif isinstance(generator, Symbol):
|
| 142 |
+
self.gen_symbol = generator
|
| 143 |
+
|
| 144 |
+
def __str__(self):
|
| 145 |
+
string = 'Univariate Differential Operator Algebra in intermediate '\
|
| 146 |
+
+ sstr(self.gen_symbol) + ' over the base ring ' + \
|
| 147 |
+
(self.base).__str__()
|
| 148 |
+
|
| 149 |
+
return string
|
| 150 |
+
|
| 151 |
+
__repr__ = __str__
|
| 152 |
+
|
| 153 |
+
def __eq__(self, other):
|
| 154 |
+
return self.base == other.base and \
|
| 155 |
+
self.gen_symbol == other.gen_symbol
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class DifferentialOperator:
|
| 159 |
+
"""
|
| 160 |
+
Differential Operators are elements of Weyl Algebra. The Operators
|
| 161 |
+
are defined by a list of polynomials in the base ring and the
|
| 162 |
+
parent ring of the Operator i.e. the algebra it belongs to.
|
| 163 |
+
|
| 164 |
+
Explanation
|
| 165 |
+
===========
|
| 166 |
+
|
| 167 |
+
Takes a list of polynomials for each power of ``Dx`` and the
|
| 168 |
+
parent ring which must be an instance of DifferentialOperatorAlgebra.
|
| 169 |
+
|
| 170 |
+
A Differential Operator can be created easily using
|
| 171 |
+
the operator ``Dx``. See examples below.
|
| 172 |
+
|
| 173 |
+
Examples
|
| 174 |
+
========
|
| 175 |
+
|
| 176 |
+
>>> from sympy.holonomic.holonomic import DifferentialOperator, DifferentialOperators
|
| 177 |
+
>>> from sympy import ZZ
|
| 178 |
+
>>> from sympy import symbols
|
| 179 |
+
>>> x = symbols('x')
|
| 180 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
|
| 181 |
+
|
| 182 |
+
>>> DifferentialOperator([0, 1, x**2], R)
|
| 183 |
+
(1)*Dx + (x**2)*Dx**2
|
| 184 |
+
|
| 185 |
+
>>> (x*Dx*x + 1 - Dx**2)**2
|
| 186 |
+
(2*x**2 + 2*x + 1) + (4*x**3 + 2*x**2 - 4)*Dx + (x**4 - 6*x - 2)*Dx**2 + (-2*x**2)*Dx**3 + (1)*Dx**4
|
| 187 |
+
|
| 188 |
+
See Also
|
| 189 |
+
========
|
| 190 |
+
|
| 191 |
+
DifferentialOperatorAlgebra
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
_op_priority = 20
|
| 195 |
+
|
| 196 |
+
def __init__(self, list_of_poly, parent):
|
| 197 |
+
"""
|
| 198 |
+
Parameters
|
| 199 |
+
==========
|
| 200 |
+
|
| 201 |
+
list_of_poly:
|
| 202 |
+
List of polynomials belonging to the base ring of the algebra.
|
| 203 |
+
parent:
|
| 204 |
+
Parent algebra of the operator.
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
# the parent ring for this operator
|
| 208 |
+
# must be an DifferentialOperatorAlgebra object
|
| 209 |
+
self.parent = parent
|
| 210 |
+
base = self.parent.base
|
| 211 |
+
self.x = base.gens[0] if isinstance(base.gens[0], Symbol) else base.gens[0][0]
|
| 212 |
+
# sequence of polynomials in x for each power of Dx
|
| 213 |
+
# the list should not have trailing zeroes
|
| 214 |
+
# represents the operator
|
| 215 |
+
# convert the expressions into ring elements using from_sympy
|
| 216 |
+
for i, j in enumerate(list_of_poly):
|
| 217 |
+
if not isinstance(j, base.dtype):
|
| 218 |
+
list_of_poly[i] = base.from_sympy(sympify(j))
|
| 219 |
+
else:
|
| 220 |
+
list_of_poly[i] = base.from_sympy(base.to_sympy(j))
|
| 221 |
+
|
| 222 |
+
self.listofpoly = list_of_poly
|
| 223 |
+
# highest power of `Dx`
|
| 224 |
+
self.order = len(self.listofpoly) - 1
|
| 225 |
+
|
| 226 |
+
def __mul__(self, other):
|
| 227 |
+
"""
|
| 228 |
+
Multiplies two DifferentialOperator and returns another
|
| 229 |
+
DifferentialOperator instance using the commutation rule
|
| 230 |
+
Dx*a = a*Dx + a'
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
listofself = self.listofpoly
|
| 234 |
+
if isinstance(other, DifferentialOperator):
|
| 235 |
+
listofother = other.listofpoly
|
| 236 |
+
elif isinstance(other, self.parent.base.dtype):
|
| 237 |
+
listofother = [other]
|
| 238 |
+
else:
|
| 239 |
+
listofother = [self.parent.base.from_sympy(sympify(other))]
|
| 240 |
+
|
| 241 |
+
# multiplies a polynomial `b` with a list of polynomials
|
| 242 |
+
def _mul_dmp_diffop(b, listofother):
|
| 243 |
+
if isinstance(listofother, list):
|
| 244 |
+
return [i * b for i in listofother]
|
| 245 |
+
return [b * listofother]
|
| 246 |
+
|
| 247 |
+
sol = _mul_dmp_diffop(listofself[0], listofother)
|
| 248 |
+
|
| 249 |
+
# compute Dx^i * b
|
| 250 |
+
def _mul_Dxi_b(b):
|
| 251 |
+
sol1 = [self.parent.base.zero]
|
| 252 |
+
sol2 = []
|
| 253 |
+
|
| 254 |
+
if isinstance(b, list):
|
| 255 |
+
for i in b:
|
| 256 |
+
sol1.append(i)
|
| 257 |
+
sol2.append(i.diff())
|
| 258 |
+
else:
|
| 259 |
+
sol1.append(self.parent.base.from_sympy(b))
|
| 260 |
+
sol2.append(self.parent.base.from_sympy(b).diff())
|
| 261 |
+
|
| 262 |
+
return _add_lists(sol1, sol2)
|
| 263 |
+
|
| 264 |
+
for i in range(1, len(listofself)):
|
| 265 |
+
# find Dx^i * b in ith iteration
|
| 266 |
+
listofother = _mul_Dxi_b(listofother)
|
| 267 |
+
# solution = solution + listofself[i] * (Dx^i * b)
|
| 268 |
+
sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother))
|
| 269 |
+
|
| 270 |
+
return DifferentialOperator(sol, self.parent)
|
| 271 |
+
|
| 272 |
+
def __rmul__(self, other):
|
| 273 |
+
if not isinstance(other, DifferentialOperator):
|
| 274 |
+
|
| 275 |
+
if not isinstance(other, self.parent.base.dtype):
|
| 276 |
+
other = (self.parent.base).from_sympy(sympify(other))
|
| 277 |
+
|
| 278 |
+
sol = [other * j for j in self.listofpoly]
|
| 279 |
+
return DifferentialOperator(sol, self.parent)
|
| 280 |
+
|
| 281 |
+
def __add__(self, other):
|
| 282 |
+
if isinstance(other, DifferentialOperator):
|
| 283 |
+
|
| 284 |
+
sol = _add_lists(self.listofpoly, other.listofpoly)
|
| 285 |
+
return DifferentialOperator(sol, self.parent)
|
| 286 |
+
|
| 287 |
+
list_self = self.listofpoly
|
| 288 |
+
if not isinstance(other, self.parent.base.dtype):
|
| 289 |
+
list_other = [((self.parent).base).from_sympy(sympify(other))]
|
| 290 |
+
else:
|
| 291 |
+
list_other = [other]
|
| 292 |
+
sol = [list_self[0] + list_other[0]] + list_self[1:]
|
| 293 |
+
return DifferentialOperator(sol, self.parent)
|
| 294 |
+
|
| 295 |
+
__radd__ = __add__
|
| 296 |
+
|
| 297 |
+
def __sub__(self, other):
|
| 298 |
+
return self + (-1) * other
|
| 299 |
+
|
| 300 |
+
def __rsub__(self, other):
|
| 301 |
+
return (-1) * self + other
|
| 302 |
+
|
| 303 |
+
def __neg__(self):
|
| 304 |
+
return -1 * self
|
| 305 |
+
|
| 306 |
+
def __truediv__(self, other):
|
| 307 |
+
return self * (S.One / other)
|
| 308 |
+
|
| 309 |
+
def __pow__(self, n):
|
| 310 |
+
if n == 1:
|
| 311 |
+
return self
|
| 312 |
+
result = DifferentialOperator([self.parent.base.one], self.parent)
|
| 313 |
+
if n == 0:
|
| 314 |
+
return result
|
| 315 |
+
# if self is `Dx`
|
| 316 |
+
if self.listofpoly == self.parent.derivative_operator.listofpoly:
|
| 317 |
+
sol = [self.parent.base.zero]*n + [self.parent.base.one]
|
| 318 |
+
return DifferentialOperator(sol, self.parent)
|
| 319 |
+
x = self
|
| 320 |
+
while True:
|
| 321 |
+
if n % 2:
|
| 322 |
+
result *= x
|
| 323 |
+
n >>= 1
|
| 324 |
+
if not n:
|
| 325 |
+
break
|
| 326 |
+
x *= x
|
| 327 |
+
return result
|
| 328 |
+
|
| 329 |
+
def __str__(self):
|
| 330 |
+
listofpoly = self.listofpoly
|
| 331 |
+
print_str = ''
|
| 332 |
+
|
| 333 |
+
for i, j in enumerate(listofpoly):
|
| 334 |
+
if j == self.parent.base.zero:
|
| 335 |
+
continue
|
| 336 |
+
|
| 337 |
+
j = self.parent.base.to_sympy(j)
|
| 338 |
+
|
| 339 |
+
if i == 0:
|
| 340 |
+
print_str += '(' + sstr(j) + ')'
|
| 341 |
+
continue
|
| 342 |
+
|
| 343 |
+
if print_str:
|
| 344 |
+
print_str += ' + '
|
| 345 |
+
|
| 346 |
+
if i == 1:
|
| 347 |
+
print_str += '(' + sstr(j) + ')*%s' %(self.parent.gen_symbol)
|
| 348 |
+
continue
|
| 349 |
+
|
| 350 |
+
print_str += '(' + sstr(j) + ')' + '*%s**' %(self.parent.gen_symbol) + sstr(i)
|
| 351 |
+
|
| 352 |
+
return print_str
|
| 353 |
+
|
| 354 |
+
__repr__ = __str__
|
| 355 |
+
|
| 356 |
+
def __eq__(self, other):
|
| 357 |
+
if isinstance(other, DifferentialOperator):
|
| 358 |
+
return self.listofpoly == other.listofpoly and \
|
| 359 |
+
self.parent == other.parent
|
| 360 |
+
return self.listofpoly[0] == other and \
|
| 361 |
+
all(i is self.parent.base.zero for i in self.listofpoly[1:])
|
| 362 |
+
|
| 363 |
+
def is_singular(self, x0):
|
| 364 |
+
"""
|
| 365 |
+
Checks if the differential equation is singular at x0.
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
base = self.parent.base
|
| 369 |
+
return x0 in roots(base.to_sympy(self.listofpoly[-1]), self.x)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
class HolonomicFunction:
|
| 373 |
+
r"""
|
| 374 |
+
A Holonomic Function is a solution to a linear homogeneous ordinary
|
| 375 |
+
differential equation with polynomial coefficients. This differential
|
| 376 |
+
equation can also be represented by an annihilator i.e. a Differential
|
| 377 |
+
Operator ``L`` such that :math:`L.f = 0`. For uniqueness of these functions,
|
| 378 |
+
initial conditions can also be provided along with the annihilator.
|
| 379 |
+
|
| 380 |
+
Explanation
|
| 381 |
+
===========
|
| 382 |
+
|
| 383 |
+
Holonomic functions have closure properties and thus forms a ring.
|
| 384 |
+
Given two Holonomic Functions f and g, their sum, product,
|
| 385 |
+
integral and derivative is also a Holonomic Function.
|
| 386 |
+
|
| 387 |
+
For ordinary points initial condition should be a vector of values of
|
| 388 |
+
the derivatives i.e. :math:`[y(x_0), y'(x_0), y''(x_0) ... ]`.
|
| 389 |
+
|
| 390 |
+
For regular singular points initial conditions can also be provided in this
|
| 391 |
+
format:
|
| 392 |
+
:math:`{s0: [C_0, C_1, ...], s1: [C^1_0, C^1_1, ...], ...}`
|
| 393 |
+
where s0, s1, ... are the roots of indicial equation and vectors
|
| 394 |
+
:math:`[C_0, C_1, ...], [C^0_0, C^0_1, ...], ...` are the corresponding initial
|
| 395 |
+
terms of the associated power series. See Examples below.
|
| 396 |
+
|
| 397 |
+
Examples
|
| 398 |
+
========
|
| 399 |
+
|
| 400 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
| 401 |
+
>>> from sympy import QQ
|
| 402 |
+
>>> from sympy import symbols, S
|
| 403 |
+
>>> x = symbols('x')
|
| 404 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
| 405 |
+
|
| 406 |
+
>>> p = HolonomicFunction(Dx - 1, x, 0, [1]) # e^x
|
| 407 |
+
>>> q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) # sin(x)
|
| 408 |
+
|
| 409 |
+
>>> p + q # annihilator of e^x + sin(x)
|
| 410 |
+
HolonomicFunction((-1) + (1)*Dx + (-1)*Dx**2 + (1)*Dx**3, x, 0, [1, 2, 1])
|
| 411 |
+
|
| 412 |
+
>>> p * q # annihilator of e^x * sin(x)
|
| 413 |
+
HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x, 0, [0, 1])
|
| 414 |
+
|
| 415 |
+
An example of initial conditions for regular singular points,
|
| 416 |
+
the indicial equation has only one root `1/2`.
|
| 417 |
+
|
| 418 |
+
>>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]})
|
| 419 |
+
HolonomicFunction((-1/2) + (x)*Dx, x, 0, {1/2: [1]})
|
| 420 |
+
|
| 421 |
+
>>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_expr()
|
| 422 |
+
sqrt(x)
|
| 423 |
+
|
| 424 |
+
To plot a Holonomic Function, one can use `.evalf()` for numerical
|
| 425 |
+
computation. Here's an example on `sin(x)**2/x` using numpy and matplotlib.
|
| 426 |
+
|
| 427 |
+
>>> import sympy.holonomic # doctest: +SKIP
|
| 428 |
+
>>> from sympy import var, sin # doctest: +SKIP
|
| 429 |
+
>>> import matplotlib.pyplot as plt # doctest: +SKIP
|
| 430 |
+
>>> import numpy as np # doctest: +SKIP
|
| 431 |
+
>>> var("x") # doctest: +SKIP
|
| 432 |
+
>>> r = np.linspace(1, 5, 100) # doctest: +SKIP
|
| 433 |
+
>>> y = sympy.holonomic.expr_to_holonomic(sin(x)**2/x, x0=1).evalf(r) # doctest: +SKIP
|
| 434 |
+
>>> plt.plot(r, y, label="holonomic function") # doctest: +SKIP
|
| 435 |
+
>>> plt.show() # doctest: +SKIP
|
| 436 |
+
|
| 437 |
+
"""
|
| 438 |
+
|
| 439 |
+
_op_priority = 20
|
| 440 |
+
|
| 441 |
+
def __init__(self, annihilator, x, x0=0, y0=None):
|
| 442 |
+
"""
|
| 443 |
+
|
| 444 |
+
Parameters
|
| 445 |
+
==========
|
| 446 |
+
|
| 447 |
+
annihilator:
|
| 448 |
+
Annihilator of the Holonomic Function, represented by a
|
| 449 |
+
`DifferentialOperator` object.
|
| 450 |
+
x:
|
| 451 |
+
Variable of the function.
|
| 452 |
+
x0:
|
| 453 |
+
The point at which initial conditions are stored.
|
| 454 |
+
Generally an integer.
|
| 455 |
+
y0:
|
| 456 |
+
The initial condition. The proper format for the initial condition
|
| 457 |
+
is described in class docstring. To make the function unique,
|
| 458 |
+
length of the vector `y0` should be equal to or greater than the
|
| 459 |
+
order of differential equation.
|
| 460 |
+
"""
|
| 461 |
+
|
| 462 |
+
# initial condition
|
| 463 |
+
self.y0 = y0
|
| 464 |
+
# the point for initial conditions, default is zero.
|
| 465 |
+
self.x0 = x0
|
| 466 |
+
# differential operator L such that L.f = 0
|
| 467 |
+
self.annihilator = annihilator
|
| 468 |
+
self.x = x
|
| 469 |
+
|
| 470 |
+
def __str__(self):
|
| 471 |
+
if self._have_init_cond():
|
| 472 |
+
str_sol = 'HolonomicFunction(%s, %s, %s, %s)' % (str(self.annihilator),\
|
| 473 |
+
sstr(self.x), sstr(self.x0), sstr(self.y0))
|
| 474 |
+
else:
|
| 475 |
+
str_sol = 'HolonomicFunction(%s, %s)' % (str(self.annihilator),\
|
| 476 |
+
sstr(self.x))
|
| 477 |
+
|
| 478 |
+
return str_sol
|
| 479 |
+
|
| 480 |
+
__repr__ = __str__
|
| 481 |
+
|
| 482 |
+
def unify(self, other):
|
| 483 |
+
"""
|
| 484 |
+
Unifies the base polynomial ring of a given two Holonomic
|
| 485 |
+
Functions.
|
| 486 |
+
"""
|
| 487 |
+
|
| 488 |
+
R1 = self.annihilator.parent.base
|
| 489 |
+
R2 = other.annihilator.parent.base
|
| 490 |
+
|
| 491 |
+
dom1 = R1.dom
|
| 492 |
+
dom2 = R2.dom
|
| 493 |
+
|
| 494 |
+
if R1 == R2:
|
| 495 |
+
return (self, other)
|
| 496 |
+
|
| 497 |
+
R = (dom1.unify(dom2)).old_poly_ring(self.x)
|
| 498 |
+
|
| 499 |
+
newparent, _ = DifferentialOperators(R, str(self.annihilator.parent.gen_symbol))
|
| 500 |
+
|
| 501 |
+
sol1 = [R1.to_sympy(i) for i in self.annihilator.listofpoly]
|
| 502 |
+
sol2 = [R2.to_sympy(i) for i in other.annihilator.listofpoly]
|
| 503 |
+
|
| 504 |
+
sol1 = DifferentialOperator(sol1, newparent)
|
| 505 |
+
sol2 = DifferentialOperator(sol2, newparent)
|
| 506 |
+
|
| 507 |
+
sol1 = HolonomicFunction(sol1, self.x, self.x0, self.y0)
|
| 508 |
+
sol2 = HolonomicFunction(sol2, other.x, other.x0, other.y0)
|
| 509 |
+
|
| 510 |
+
return (sol1, sol2)
|
| 511 |
+
|
| 512 |
+
def is_singularics(self):
|
| 513 |
+
"""
|
| 514 |
+
Returns True if the function have singular initial condition
|
| 515 |
+
in the dictionary format.
|
| 516 |
+
|
| 517 |
+
Returns False if the function have ordinary initial condition
|
| 518 |
+
in the list format.
|
| 519 |
+
|
| 520 |
+
Returns None for all other cases.
|
| 521 |
+
"""
|
| 522 |
+
|
| 523 |
+
if isinstance(self.y0, dict):
|
| 524 |
+
return True
|
| 525 |
+
elif isinstance(self.y0, list):
|
| 526 |
+
return False
|
| 527 |
+
|
| 528 |
+
def _have_init_cond(self):
|
| 529 |
+
"""
|
| 530 |
+
Checks if the function have initial condition.
|
| 531 |
+
"""
|
| 532 |
+
return bool(self.y0)
|
| 533 |
+
|
| 534 |
+
def _singularics_to_ord(self):
|
| 535 |
+
"""
|
| 536 |
+
Converts a singular initial condition to ordinary if possible.
|
| 537 |
+
"""
|
| 538 |
+
a = list(self.y0)[0]
|
| 539 |
+
b = self.y0[a]
|
| 540 |
+
|
| 541 |
+
if len(self.y0) == 1 and a == int(a) and a > 0:
|
| 542 |
+
a = int(a)
|
| 543 |
+
y0 = [S.Zero] * a
|
| 544 |
+
y0 += [j * factorial(a + i) for i, j in enumerate(b)]
|
| 545 |
+
|
| 546 |
+
return HolonomicFunction(self.annihilator, self.x, self.x0, y0)
|
| 547 |
+
|
| 548 |
+
def __add__(self, other):
|
| 549 |
+
# if the ground domains are different
|
| 550 |
+
if self.annihilator.parent.base != other.annihilator.parent.base:
|
| 551 |
+
a, b = self.unify(other)
|
| 552 |
+
return a + b
|
| 553 |
+
|
| 554 |
+
deg1 = self.annihilator.order
|
| 555 |
+
deg2 = other.annihilator.order
|
| 556 |
+
dim = max(deg1, deg2)
|
| 557 |
+
R = self.annihilator.parent.base
|
| 558 |
+
K = R.get_field()
|
| 559 |
+
|
| 560 |
+
rowsself = [self.annihilator]
|
| 561 |
+
rowsother = [other.annihilator]
|
| 562 |
+
gen = self.annihilator.parent.derivative_operator
|
| 563 |
+
|
| 564 |
+
# constructing annihilators up to order dim
|
| 565 |
+
for i in range(dim - deg1):
|
| 566 |
+
diff1 = (gen * rowsself[-1])
|
| 567 |
+
rowsself.append(diff1)
|
| 568 |
+
|
| 569 |
+
for i in range(dim - deg2):
|
| 570 |
+
diff2 = (gen * rowsother[-1])
|
| 571 |
+
rowsother.append(diff2)
|
| 572 |
+
|
| 573 |
+
row = rowsself + rowsother
|
| 574 |
+
|
| 575 |
+
# constructing the matrix of the ansatz
|
| 576 |
+
r = []
|
| 577 |
+
|
| 578 |
+
for expr in row:
|
| 579 |
+
p = []
|
| 580 |
+
for i in range(dim + 1):
|
| 581 |
+
if i >= len(expr.listofpoly):
|
| 582 |
+
p.append(K.zero)
|
| 583 |
+
else:
|
| 584 |
+
p.append(K.new(expr.listofpoly[i].to_list()))
|
| 585 |
+
r.append(p)
|
| 586 |
+
|
| 587 |
+
# solving the linear system using gauss jordan solver
|
| 588 |
+
r = DomainMatrix(r, (len(row), dim+1), K).transpose()
|
| 589 |
+
homosys = DomainMatrix.zeros((dim+1, 1), K)
|
| 590 |
+
sol = _find_nonzero_solution(r, homosys)
|
| 591 |
+
|
| 592 |
+
# if a solution is not obtained then increasing the order by 1 in each
|
| 593 |
+
# iteration
|
| 594 |
+
while sol.is_zero_matrix:
|
| 595 |
+
dim += 1
|
| 596 |
+
|
| 597 |
+
diff1 = (gen * rowsself[-1])
|
| 598 |
+
rowsself.append(diff1)
|
| 599 |
+
|
| 600 |
+
diff2 = (gen * rowsother[-1])
|
| 601 |
+
rowsother.append(diff2)
|
| 602 |
+
|
| 603 |
+
row = rowsself + rowsother
|
| 604 |
+
r = []
|
| 605 |
+
|
| 606 |
+
for expr in row:
|
| 607 |
+
p = []
|
| 608 |
+
for i in range(dim + 1):
|
| 609 |
+
if i >= len(expr.listofpoly):
|
| 610 |
+
p.append(K.zero)
|
| 611 |
+
else:
|
| 612 |
+
p.append(K.new(expr.listofpoly[i].to_list()))
|
| 613 |
+
r.append(p)
|
| 614 |
+
|
| 615 |
+
# solving the linear system using gauss jordan solver
|
| 616 |
+
r = DomainMatrix(r, (len(row), dim+1), K).transpose()
|
| 617 |
+
homosys = DomainMatrix.zeros((dim+1, 1), K)
|
| 618 |
+
sol = _find_nonzero_solution(r, homosys)
|
| 619 |
+
|
| 620 |
+
# taking only the coefficients needed to multiply with `self`
|
| 621 |
+
# can be also be done the other way by taking R.H.S and multiplying with
|
| 622 |
+
# `other`
|
| 623 |
+
sol = sol.flat()[:dim + 1 - deg1]
|
| 624 |
+
sol1 = _normalize(sol, self.annihilator.parent)
|
| 625 |
+
# annihilator of the solution
|
| 626 |
+
sol = sol1 * (self.annihilator)
|
| 627 |
+
sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False)
|
| 628 |
+
|
| 629 |
+
if not (self._have_init_cond() and other._have_init_cond()):
|
| 630 |
+
return HolonomicFunction(sol, self.x)
|
| 631 |
+
|
| 632 |
+
# both the functions have ordinary initial conditions
|
| 633 |
+
if self.is_singularics() == False and other.is_singularics() == False:
|
| 634 |
+
|
| 635 |
+
# directly add the corresponding value
|
| 636 |
+
if self.x0 == other.x0:
|
| 637 |
+
# try to extended the initial conditions
|
| 638 |
+
# using the annihilator
|
| 639 |
+
y1 = _extend_y0(self, sol.order)
|
| 640 |
+
y2 = _extend_y0(other, sol.order)
|
| 641 |
+
y0 = [a + b for a, b in zip(y1, y2)]
|
| 642 |
+
return HolonomicFunction(sol, self.x, self.x0, y0)
|
| 643 |
+
|
| 644 |
+
# change the initial conditions to a same point
|
| 645 |
+
selfat0 = self.annihilator.is_singular(0)
|
| 646 |
+
otherat0 = other.annihilator.is_singular(0)
|
| 647 |
+
if self.x0 == 0 and not selfat0 and not otherat0:
|
| 648 |
+
return self + other.change_ics(0)
|
| 649 |
+
if other.x0 == 0 and not selfat0 and not otherat0:
|
| 650 |
+
return self.change_ics(0) + other
|
| 651 |
+
|
| 652 |
+
selfatx0 = self.annihilator.is_singular(self.x0)
|
| 653 |
+
otheratx0 = other.annihilator.is_singular(self.x0)
|
| 654 |
+
if not selfatx0 and not otheratx0:
|
| 655 |
+
return self + other.change_ics(self.x0)
|
| 656 |
+
return self.change_ics(other.x0) + other
|
| 657 |
+
|
| 658 |
+
if self.x0 != other.x0:
|
| 659 |
+
return HolonomicFunction(sol, self.x)
|
| 660 |
+
|
| 661 |
+
# if the functions have singular_ics
|
| 662 |
+
y1 = None
|
| 663 |
+
y2 = None
|
| 664 |
+
|
| 665 |
+
if self.is_singularics() == False and other.is_singularics() == True:
|
| 666 |
+
# convert the ordinary initial condition to singular.
|
| 667 |
+
_y0 = [j / factorial(i) for i, j in enumerate(self.y0)]
|
| 668 |
+
y1 = {S.Zero: _y0}
|
| 669 |
+
y2 = other.y0
|
| 670 |
+
elif self.is_singularics() == True and other.is_singularics() == False:
|
| 671 |
+
_y0 = [j / factorial(i) for i, j in enumerate(other.y0)]
|
| 672 |
+
y1 = self.y0
|
| 673 |
+
y2 = {S.Zero: _y0}
|
| 674 |
+
elif self.is_singularics() == True and other.is_singularics() == True:
|
| 675 |
+
y1 = self.y0
|
| 676 |
+
y2 = other.y0
|
| 677 |
+
|
| 678 |
+
# computing singular initial condition for the result
|
| 679 |
+
# taking union of the series terms of both functions
|
| 680 |
+
y0 = {}
|
| 681 |
+
for i in y1:
|
| 682 |
+
# add corresponding initial terms if the power
|
| 683 |
+
# on `x` is same
|
| 684 |
+
if i in y2:
|
| 685 |
+
y0[i] = [a + b for a, b in zip(y1[i], y2[i])]
|
| 686 |
+
else:
|
| 687 |
+
y0[i] = y1[i]
|
| 688 |
+
for i in y2:
|
| 689 |
+
if i not in y1:
|
| 690 |
+
y0[i] = y2[i]
|
| 691 |
+
return HolonomicFunction(sol, self.x, self.x0, y0)
|
| 692 |
+
|
| 693 |
+
def integrate(self, limits, initcond=False):
|
| 694 |
+
"""
|
| 695 |
+
Integrates the given holonomic function.
|
| 696 |
+
|
| 697 |
+
Examples
|
| 698 |
+
========
|
| 699 |
+
|
| 700 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
| 701 |
+
>>> from sympy import QQ
|
| 702 |
+
>>> from sympy import symbols
|
| 703 |
+
>>> x = symbols('x')
|
| 704 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
| 705 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).integrate((x, 0, x)) # e^x - 1
|
| 706 |
+
HolonomicFunction((-1)*Dx + (1)*Dx**2, x, 0, [0, 1])
|
| 707 |
+
>>> HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).integrate((x, 0, x))
|
| 708 |
+
HolonomicFunction((1)*Dx + (1)*Dx**3, x, 0, [0, 1, 0])
|
| 709 |
+
"""
|
| 710 |
+
|
| 711 |
+
# to get the annihilator, just multiply by Dx from right
|
| 712 |
+
D = self.annihilator.parent.derivative_operator
|
| 713 |
+
|
| 714 |
+
# if the function have initial conditions of the series format
|
| 715 |
+
if self.is_singularics() == True:
|
| 716 |
+
|
| 717 |
+
r = self._singularics_to_ord()
|
| 718 |
+
if r:
|
| 719 |
+
return r.integrate(limits, initcond=initcond)
|
| 720 |
+
|
| 721 |
+
# computing singular initial condition for the function
|
| 722 |
+
# produced after integration.
|
| 723 |
+
y0 = {}
|
| 724 |
+
for i in self.y0:
|
| 725 |
+
c = self.y0[i]
|
| 726 |
+
c2 = []
|
| 727 |
+
for j, cj in enumerate(c):
|
| 728 |
+
if cj == 0:
|
| 729 |
+
c2.append(S.Zero)
|
| 730 |
+
|
| 731 |
+
# if power on `x` is -1, the integration becomes log(x)
|
| 732 |
+
# TODO: Implement this case
|
| 733 |
+
elif i + j + 1 == 0:
|
| 734 |
+
raise NotImplementedError("logarithmic terms in the series are not supported")
|
| 735 |
+
else:
|
| 736 |
+
c2.append(cj / S(i + j + 1))
|
| 737 |
+
y0[i + 1] = c2
|
| 738 |
+
|
| 739 |
+
if hasattr(limits, "__iter__"):
|
| 740 |
+
raise NotImplementedError("Definite integration for singular initial conditions")
|
| 741 |
+
|
| 742 |
+
return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0)
|
| 743 |
+
|
| 744 |
+
# if no initial conditions are available for the function
|
| 745 |
+
if not self._have_init_cond():
|
| 746 |
+
if initcond:
|
| 747 |
+
return HolonomicFunction(self.annihilator * D, self.x, self.x0, [S.Zero])
|
| 748 |
+
return HolonomicFunction(self.annihilator * D, self.x)
|
| 749 |
+
|
| 750 |
+
# definite integral
|
| 751 |
+
# initial conditions for the answer will be stored at point `a`,
|
| 752 |
+
# where `a` is the lower limit of the integrand
|
| 753 |
+
if hasattr(limits, "__iter__"):
|
| 754 |
+
|
| 755 |
+
if len(limits) == 3 and limits[0] == self.x:
|
| 756 |
+
x0 = self.x0
|
| 757 |
+
a = limits[1]
|
| 758 |
+
b = limits[2]
|
| 759 |
+
definite = True
|
| 760 |
+
|
| 761 |
+
else:
|
| 762 |
+
definite = False
|
| 763 |
+
|
| 764 |
+
y0 = [S.Zero]
|
| 765 |
+
y0 += self.y0
|
| 766 |
+
|
| 767 |
+
indefinite_integral = HolonomicFunction(self.annihilator * D, self.x, self.x0, y0)
|
| 768 |
+
|
| 769 |
+
if not definite:
|
| 770 |
+
return indefinite_integral
|
| 771 |
+
|
| 772 |
+
# use evalf to get the values at `a`
|
| 773 |
+
if x0 != a:
|
| 774 |
+
try:
|
| 775 |
+
indefinite_expr = indefinite_integral.to_expr()
|
| 776 |
+
except (NotHyperSeriesError, NotPowerSeriesError):
|
| 777 |
+
indefinite_expr = None
|
| 778 |
+
|
| 779 |
+
if indefinite_expr:
|
| 780 |
+
lower = indefinite_expr.subs(self.x, a)
|
| 781 |
+
if isinstance(lower, NaN):
|
| 782 |
+
lower = indefinite_expr.limit(self.x, a)
|
| 783 |
+
else:
|
| 784 |
+
lower = indefinite_integral.evalf(a)
|
| 785 |
+
|
| 786 |
+
if b == self.x:
|
| 787 |
+
y0[0] = y0[0] - lower
|
| 788 |
+
return HolonomicFunction(self.annihilator * D, self.x, x0, y0)
|
| 789 |
+
|
| 790 |
+
elif S(b).is_Number:
|
| 791 |
+
if indefinite_expr:
|
| 792 |
+
upper = indefinite_expr.subs(self.x, b)
|
| 793 |
+
if isinstance(upper, NaN):
|
| 794 |
+
upper = indefinite_expr.limit(self.x, b)
|
| 795 |
+
else:
|
| 796 |
+
upper = indefinite_integral.evalf(b)
|
| 797 |
+
|
| 798 |
+
return upper - lower
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
# if the upper limit is `x`, the answer will be a function
|
| 802 |
+
if b == self.x:
|
| 803 |
+
return HolonomicFunction(self.annihilator * D, self.x, a, y0)
|
| 804 |
+
|
| 805 |
+
# if the upper limits is a Number, a numerical value will be returned
|
| 806 |
+
elif S(b).is_Number:
|
| 807 |
+
try:
|
| 808 |
+
s = HolonomicFunction(self.annihilator * D, self.x, a,\
|
| 809 |
+
y0).to_expr()
|
| 810 |
+
indefinite = s.subs(self.x, b)
|
| 811 |
+
if not isinstance(indefinite, NaN):
|
| 812 |
+
return indefinite
|
| 813 |
+
else:
|
| 814 |
+
return s.limit(self.x, b)
|
| 815 |
+
except (NotHyperSeriesError, NotPowerSeriesError):
|
| 816 |
+
return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b)
|
| 817 |
+
|
| 818 |
+
return HolonomicFunction(self.annihilator * D, self.x)
|
| 819 |
+
|
| 820 |
+
def diff(self, *args, **kwargs):
|
| 821 |
+
r"""
|
| 822 |
+
Differentiation of the given Holonomic function.
|
| 823 |
+
|
| 824 |
+
Examples
|
| 825 |
+
========
|
| 826 |
+
|
| 827 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
| 828 |
+
>>> from sympy import ZZ
|
| 829 |
+
>>> from sympy import symbols
|
| 830 |
+
>>> x = symbols('x')
|
| 831 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
|
| 832 |
+
>>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_expr()
|
| 833 |
+
cos(x)
|
| 834 |
+
>>> HolonomicFunction(Dx - 2, x, 0, [1]).diff().to_expr()
|
| 835 |
+
2*exp(2*x)
|
| 836 |
+
|
| 837 |
+
See Also
|
| 838 |
+
========
|
| 839 |
+
|
| 840 |
+
integrate
|
| 841 |
+
"""
|
| 842 |
+
kwargs.setdefault('evaluate', True)
|
| 843 |
+
if args:
|
| 844 |
+
if args[0] != self.x:
|
| 845 |
+
return S.Zero
|
| 846 |
+
elif len(args) == 2:
|
| 847 |
+
sol = self
|
| 848 |
+
for i in range(args[1]):
|
| 849 |
+
sol = sol.diff(args[0])
|
| 850 |
+
return sol
|
| 851 |
+
|
| 852 |
+
ann = self.annihilator
|
| 853 |
+
|
| 854 |
+
# if the function is constant.
|
| 855 |
+
if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1:
|
| 856 |
+
return S.Zero
|
| 857 |
+
|
| 858 |
+
# if the coefficient of y in the differential equation is zero.
|
| 859 |
+
# a shifting is done to compute the answer in this case.
|
| 860 |
+
elif ann.listofpoly[0] == ann.parent.base.zero:
|
| 861 |
+
|
| 862 |
+
sol = DifferentialOperator(ann.listofpoly[1:], ann.parent)
|
| 863 |
+
|
| 864 |
+
if self._have_init_cond():
|
| 865 |
+
# if ordinary initial condition
|
| 866 |
+
if self.is_singularics() == False:
|
| 867 |
+
return HolonomicFunction(sol, self.x, self.x0, self.y0[1:])
|
| 868 |
+
# TODO: support for singular initial condition
|
| 869 |
+
return HolonomicFunction(sol, self.x)
|
| 870 |
+
else:
|
| 871 |
+
return HolonomicFunction(sol, self.x)
|
| 872 |
+
|
| 873 |
+
# the general algorithm
|
| 874 |
+
R = ann.parent.base
|
| 875 |
+
K = R.get_field()
|
| 876 |
+
|
| 877 |
+
seq_dmf = [K.new(i.to_list()) for i in ann.listofpoly]
|
| 878 |
+
|
| 879 |
+
# -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0
|
| 880 |
+
rhs = [i / seq_dmf[0] for i in seq_dmf[1:]]
|
| 881 |
+
rhs.insert(0, K.zero)
|
| 882 |
+
|
| 883 |
+
# differentiate both lhs and rhs
|
| 884 |
+
sol = _derivate_diff_eq(rhs, K)
|
| 885 |
+
|
| 886 |
+
# add the term y' in lhs to rhs
|
| 887 |
+
sol = _add_lists(sol, [K.zero, K.one])
|
| 888 |
+
|
| 889 |
+
sol = _normalize(sol[1:], self.annihilator.parent, negative=False)
|
| 890 |
+
|
| 891 |
+
if not self._have_init_cond() or self.is_singularics() == True:
|
| 892 |
+
return HolonomicFunction(sol, self.x)
|
| 893 |
+
|
| 894 |
+
y0 = _extend_y0(self, sol.order + 1)[1:]
|
| 895 |
+
return HolonomicFunction(sol, self.x, self.x0, y0)
|
| 896 |
+
|
| 897 |
+
def __eq__(self, other):
|
| 898 |
+
if self.annihilator != other.annihilator or self.x != other.x:
|
| 899 |
+
return False
|
| 900 |
+
if self._have_init_cond() and other._have_init_cond():
|
| 901 |
+
return self.x0 == other.x0 and self.y0 == other.y0
|
| 902 |
+
return True
|
| 903 |
+
|
| 904 |
+
def __mul__(self, other):
|
| 905 |
+
ann_self = self.annihilator
|
| 906 |
+
|
| 907 |
+
if not isinstance(other, HolonomicFunction):
|
| 908 |
+
other = sympify(other)
|
| 909 |
+
|
| 910 |
+
if other.has(self.x):
|
| 911 |
+
raise NotImplementedError(" Can't multiply a HolonomicFunction and expressions/functions.")
|
| 912 |
+
|
| 913 |
+
if not self._have_init_cond():
|
| 914 |
+
return self
|
| 915 |
+
y0 = _extend_y0(self, ann_self.order)
|
| 916 |
+
y1 = [(Poly.new(j, self.x) * other).rep for j in y0]
|
| 917 |
+
return HolonomicFunction(ann_self, self.x, self.x0, y1)
|
| 918 |
+
|
| 919 |
+
if self.annihilator.parent.base != other.annihilator.parent.base:
|
| 920 |
+
a, b = self.unify(other)
|
| 921 |
+
return a * b
|
| 922 |
+
|
| 923 |
+
ann_other = other.annihilator
|
| 924 |
+
|
| 925 |
+
a = ann_self.order
|
| 926 |
+
b = ann_other.order
|
| 927 |
+
|
| 928 |
+
R = ann_self.parent.base
|
| 929 |
+
K = R.get_field()
|
| 930 |
+
|
| 931 |
+
list_self = [K.new(j.to_list()) for j in ann_self.listofpoly]
|
| 932 |
+
list_other = [K.new(j.to_list()) for j in ann_other.listofpoly]
|
| 933 |
+
|
| 934 |
+
# will be used to reduce the degree
|
| 935 |
+
self_red = [-list_self[i] / list_self[a] for i in range(a)]
|
| 936 |
+
|
| 937 |
+
other_red = [-list_other[i] / list_other[b] for i in range(b)]
|
| 938 |
+
|
| 939 |
+
# coeff_mull[i][j] is the coefficient of Dx^i(f).Dx^j(g)
|
| 940 |
+
coeff_mul = [[K.zero for i in range(b + 1)] for j in range(a + 1)]
|
| 941 |
+
coeff_mul[0][0] = K.one
|
| 942 |
+
|
| 943 |
+
# making the ansatz
|
| 944 |
+
lin_sys_elements = [[coeff_mul[i][j] for i in range(a) for j in range(b)]]
|
| 945 |
+
lin_sys = DomainMatrix(lin_sys_elements, (1, a*b), K).transpose()
|
| 946 |
+
|
| 947 |
+
homo_sys = DomainMatrix.zeros((a*b, 1), K)
|
| 948 |
+
|
| 949 |
+
sol = _find_nonzero_solution(lin_sys, homo_sys)
|
| 950 |
+
|
| 951 |
+
# until a non trivial solution is found
|
| 952 |
+
while sol.is_zero_matrix:
|
| 953 |
+
|
| 954 |
+
# updating the coefficients Dx^i(f).Dx^j(g) for next degree
|
| 955 |
+
for i in range(a - 1, -1, -1):
|
| 956 |
+
for j in range(b - 1, -1, -1):
|
| 957 |
+
coeff_mul[i][j + 1] += coeff_mul[i][j]
|
| 958 |
+
coeff_mul[i + 1][j] += coeff_mul[i][j]
|
| 959 |
+
if isinstance(coeff_mul[i][j], K.dtype):
|
| 960 |
+
coeff_mul[i][j] = DMFdiff(coeff_mul[i][j], K)
|
| 961 |
+
else:
|
| 962 |
+
coeff_mul[i][j] = coeff_mul[i][j].diff(self.x)
|
| 963 |
+
|
| 964 |
+
# reduce the terms to lower power using annihilators of f, g
|
| 965 |
+
for i in range(a + 1):
|
| 966 |
+
if coeff_mul[i][b].is_zero:
|
| 967 |
+
continue
|
| 968 |
+
for j in range(b):
|
| 969 |
+
coeff_mul[i][j] += other_red[j] * coeff_mul[i][b]
|
| 970 |
+
coeff_mul[i][b] = K.zero
|
| 971 |
+
|
| 972 |
+
# not d2 + 1, as that is already covered in previous loop
|
| 973 |
+
for j in range(b):
|
| 974 |
+
if coeff_mul[a][j] == 0:
|
| 975 |
+
continue
|
| 976 |
+
for i in range(a):
|
| 977 |
+
coeff_mul[i][j] += self_red[i] * coeff_mul[a][j]
|
| 978 |
+
coeff_mul[a][j] = K.zero
|
| 979 |
+
|
| 980 |
+
lin_sys_elements.append([coeff_mul[i][j] for i in range(a) for j in range(b)])
|
| 981 |
+
lin_sys = DomainMatrix(lin_sys_elements, (len(lin_sys_elements), a*b), K).transpose()
|
| 982 |
+
|
| 983 |
+
sol = _find_nonzero_solution(lin_sys, homo_sys)
|
| 984 |
+
|
| 985 |
+
sol_ann = _normalize(sol.flat(), self.annihilator.parent, negative=False)
|
| 986 |
+
|
| 987 |
+
if not (self._have_init_cond() and other._have_init_cond()):
|
| 988 |
+
return HolonomicFunction(sol_ann, self.x)
|
| 989 |
+
|
| 990 |
+
if self.is_singularics() == False and other.is_singularics() == False:
|
| 991 |
+
|
| 992 |
+
# if both the conditions are at same point
|
| 993 |
+
if self.x0 == other.x0:
|
| 994 |
+
|
| 995 |
+
# try to find more initial conditions
|
| 996 |
+
y0_self = _extend_y0(self, sol_ann.order)
|
| 997 |
+
y0_other = _extend_y0(other, sol_ann.order)
|
| 998 |
+
# h(x0) = f(x0) * g(x0)
|
| 999 |
+
y0 = [y0_self[0] * y0_other[0]]
|
| 1000 |
+
|
| 1001 |
+
# coefficient of Dx^j(f)*Dx^i(g) in Dx^i(fg)
|
| 1002 |
+
for i in range(1, min(len(y0_self), len(y0_other))):
|
| 1003 |
+
coeff = [[0 for i in range(i + 1)] for j in range(i + 1)]
|
| 1004 |
+
for j in range(i + 1):
|
| 1005 |
+
for k in range(i + 1):
|
| 1006 |
+
if j + k == i:
|
| 1007 |
+
coeff[j][k] = binomial(i, j)
|
| 1008 |
+
|
| 1009 |
+
sol = 0
|
| 1010 |
+
for j in range(i + 1):
|
| 1011 |
+
for k in range(i + 1):
|
| 1012 |
+
sol += coeff[j][k]* y0_self[j] * y0_other[k]
|
| 1013 |
+
|
| 1014 |
+
y0.append(sol)
|
| 1015 |
+
|
| 1016 |
+
return HolonomicFunction(sol_ann, self.x, self.x0, y0)
|
| 1017 |
+
|
| 1018 |
+
# if the points are different, consider one
|
| 1019 |
+
selfat0 = self.annihilator.is_singular(0)
|
| 1020 |
+
otherat0 = other.annihilator.is_singular(0)
|
| 1021 |
+
|
| 1022 |
+
if self.x0 == 0 and not selfat0 and not otherat0:
|
| 1023 |
+
return self * other.change_ics(0)
|
| 1024 |
+
if other.x0 == 0 and not selfat0 and not otherat0:
|
| 1025 |
+
return self.change_ics(0) * other
|
| 1026 |
+
|
| 1027 |
+
selfatx0 = self.annihilator.is_singular(self.x0)
|
| 1028 |
+
otheratx0 = other.annihilator.is_singular(self.x0)
|
| 1029 |
+
if not selfatx0 and not otheratx0:
|
| 1030 |
+
return self * other.change_ics(self.x0)
|
| 1031 |
+
return self.change_ics(other.x0) * other
|
| 1032 |
+
|
| 1033 |
+
if self.x0 != other.x0:
|
| 1034 |
+
return HolonomicFunction(sol_ann, self.x)
|
| 1035 |
+
|
| 1036 |
+
# if the functions have singular_ics
|
| 1037 |
+
y1 = None
|
| 1038 |
+
y2 = None
|
| 1039 |
+
|
| 1040 |
+
if self.is_singularics() == False and other.is_singularics() == True:
|
| 1041 |
+
_y0 = [j / factorial(i) for i, j in enumerate(self.y0)]
|
| 1042 |
+
y1 = {S.Zero: _y0}
|
| 1043 |
+
y2 = other.y0
|
| 1044 |
+
elif self.is_singularics() == True and other.is_singularics() == False:
|
| 1045 |
+
_y0 = [j / factorial(i) for i, j in enumerate(other.y0)]
|
| 1046 |
+
y1 = self.y0
|
| 1047 |
+
y2 = {S.Zero: _y0}
|
| 1048 |
+
elif self.is_singularics() == True and other.is_singularics() == True:
|
| 1049 |
+
y1 = self.y0
|
| 1050 |
+
y2 = other.y0
|
| 1051 |
+
|
| 1052 |
+
y0 = {}
|
| 1053 |
+
# multiply every possible pair of the series terms
|
| 1054 |
+
for i in y1:
|
| 1055 |
+
for j in y2:
|
| 1056 |
+
k = min(len(y1[i]), len(y2[j]))
|
| 1057 |
+
c = [sum((y1[i][b] * y2[j][a - b] for b in range(a + 1)),
|
| 1058 |
+
start=S.Zero) for a in range(k)]
|
| 1059 |
+
if not i + j in y0:
|
| 1060 |
+
y0[i + j] = c
|
| 1061 |
+
else:
|
| 1062 |
+
y0[i + j] = [a + b for a, b in zip(c, y0[i + j])]
|
| 1063 |
+
return HolonomicFunction(sol_ann, self.x, self.x0, y0)
|
| 1064 |
+
|
| 1065 |
+
__rmul__ = __mul__
|
| 1066 |
+
|
| 1067 |
+
def __sub__(self, other):
|
| 1068 |
+
return self + other * -1
|
| 1069 |
+
|
| 1070 |
+
def __rsub__(self, other):
|
| 1071 |
+
return self * -1 + other
|
| 1072 |
+
|
| 1073 |
+
def __neg__(self):
|
| 1074 |
+
return -1 * self
|
| 1075 |
+
|
| 1076 |
+
def __truediv__(self, other):
|
| 1077 |
+
return self * (S.One / other)
|
| 1078 |
+
|
| 1079 |
+
def __pow__(self, n):
|
| 1080 |
+
if self.annihilator.order <= 1:
|
| 1081 |
+
ann = self.annihilator
|
| 1082 |
+
parent = ann.parent
|
| 1083 |
+
|
| 1084 |
+
if self.y0 is None:
|
| 1085 |
+
y0 = None
|
| 1086 |
+
else:
|
| 1087 |
+
y0 = [list(self.y0)[0] ** n]
|
| 1088 |
+
|
| 1089 |
+
p0 = ann.listofpoly[0]
|
| 1090 |
+
p1 = ann.listofpoly[1]
|
| 1091 |
+
|
| 1092 |
+
p0 = (Poly.new(p0, self.x) * n).rep
|
| 1093 |
+
|
| 1094 |
+
sol = [parent.base.to_sympy(i) for i in [p0, p1]]
|
| 1095 |
+
dd = DifferentialOperator(sol, parent)
|
| 1096 |
+
return HolonomicFunction(dd, self.x, self.x0, y0)
|
| 1097 |
+
if n < 0:
|
| 1098 |
+
raise NotHolonomicError("Negative Power on a Holonomic Function")
|
| 1099 |
+
Dx = self.annihilator.parent.derivative_operator
|
| 1100 |
+
result = HolonomicFunction(Dx, self.x, S.Zero, [S.One])
|
| 1101 |
+
if n == 0:
|
| 1102 |
+
return result
|
| 1103 |
+
x = self
|
| 1104 |
+
while True:
|
| 1105 |
+
if n % 2:
|
| 1106 |
+
result *= x
|
| 1107 |
+
n >>= 1
|
| 1108 |
+
if not n:
|
| 1109 |
+
break
|
| 1110 |
+
x *= x
|
| 1111 |
+
return result
|
| 1112 |
+
|
| 1113 |
+
def degree(self):
|
| 1114 |
+
"""
|
| 1115 |
+
Returns the highest power of `x` in the annihilator.
|
| 1116 |
+
"""
|
| 1117 |
+
return max(i.degree() for i in self.annihilator.listofpoly)
|
| 1118 |
+
|
| 1119 |
+
def composition(self, expr, *args, **kwargs):
|
| 1120 |
+
"""
|
| 1121 |
+
Returns function after composition of a holonomic
|
| 1122 |
+
function with an algebraic function. The method cannot compute
|
| 1123 |
+
initial conditions for the result by itself, so they can be also be
|
| 1124 |
+
provided.
|
| 1125 |
+
|
| 1126 |
+
Examples
|
| 1127 |
+
========
|
| 1128 |
+
|
| 1129 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
| 1130 |
+
>>> from sympy import QQ
|
| 1131 |
+
>>> from sympy import symbols
|
| 1132 |
+
>>> x = symbols('x')
|
| 1133 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
| 1134 |
+
>>> HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2)
|
| 1135 |
+
HolonomicFunction((-2*x) + (1)*Dx, x, 0, [1])
|
| 1136 |
+
>>> HolonomicFunction(Dx**2 + 1, x).composition(x**2 - 1, 1, [1, 0])
|
| 1137 |
+
HolonomicFunction((4*x**3) + (-1)*Dx + (x)*Dx**2, x, 1, [1, 0])
|
| 1138 |
+
|
| 1139 |
+
See Also
|
| 1140 |
+
========
|
| 1141 |
+
|
| 1142 |
+
from_hyper
|
| 1143 |
+
"""
|
| 1144 |
+
|
| 1145 |
+
R = self.annihilator.parent
|
| 1146 |
+
a = self.annihilator.order
|
| 1147 |
+
diff = expr.diff(self.x)
|
| 1148 |
+
listofpoly = self.annihilator.listofpoly
|
| 1149 |
+
|
| 1150 |
+
for i, j in enumerate(listofpoly):
|
| 1151 |
+
if isinstance(j, self.annihilator.parent.base.dtype):
|
| 1152 |
+
listofpoly[i] = self.annihilator.parent.base.to_sympy(j)
|
| 1153 |
+
|
| 1154 |
+
r = listofpoly[a].subs({self.x:expr})
|
| 1155 |
+
subs = [-listofpoly[i].subs({self.x:expr}) / r for i in range (a)]
|
| 1156 |
+
coeffs = [S.Zero for i in range(a)] # coeffs[i] == coeff of (D^i f)(a) in D^k (f(a))
|
| 1157 |
+
coeffs[0] = S.One
|
| 1158 |
+
system = [coeffs]
|
| 1159 |
+
homogeneous = Matrix([[S.Zero for i in range(a)]]).transpose()
|
| 1160 |
+
while True:
|
| 1161 |
+
coeffs_next = [p.diff(self.x) for p in coeffs]
|
| 1162 |
+
for i in range(a - 1):
|
| 1163 |
+
coeffs_next[i + 1] += (coeffs[i] * diff)
|
| 1164 |
+
for i in range(a):
|
| 1165 |
+
coeffs_next[i] += (coeffs[-1] * subs[i] * diff)
|
| 1166 |
+
coeffs = coeffs_next
|
| 1167 |
+
# check for linear relations
|
| 1168 |
+
system.append(coeffs)
|
| 1169 |
+
sol, taus = (Matrix(system).transpose()
|
| 1170 |
+
).gauss_jordan_solve(homogeneous)
|
| 1171 |
+
if sol.is_zero_matrix is not True:
|
| 1172 |
+
break
|
| 1173 |
+
|
| 1174 |
+
tau = list(taus)[0]
|
| 1175 |
+
sol = sol.subs(tau, 1)
|
| 1176 |
+
sol = _normalize(sol[0:], R, negative=False)
|
| 1177 |
+
|
| 1178 |
+
# if initial conditions are given for the resulting function
|
| 1179 |
+
if args:
|
| 1180 |
+
return HolonomicFunction(sol, self.x, args[0], args[1])
|
| 1181 |
+
return HolonomicFunction(sol, self.x)
|
| 1182 |
+
|
| 1183 |
+
def to_sequence(self, lb=True):
|
| 1184 |
+
r"""
|
| 1185 |
+
Finds recurrence relation for the coefficients in the series expansion
|
| 1186 |
+
of the function about :math:`x_0`, where :math:`x_0` is the point at
|
| 1187 |
+
which the initial condition is stored.
|
| 1188 |
+
|
| 1189 |
+
Explanation
|
| 1190 |
+
===========
|
| 1191 |
+
|
| 1192 |
+
If the point :math:`x_0` is ordinary, solution of the form :math:`[(R, n_0)]`
|
| 1193 |
+
is returned. Where :math:`R` is the recurrence relation and :math:`n_0` is the
|
| 1194 |
+
smallest ``n`` for which the recurrence holds true.
|
| 1195 |
+
|
| 1196 |
+
If the point :math:`x_0` is regular singular, a list of solutions in
|
| 1197 |
+
the format :math:`(R, p, n_0)` is returned, i.e. `[(R, p, n_0), ... ]`.
|
| 1198 |
+
Each tuple in this vector represents a recurrence relation :math:`R`
|
| 1199 |
+
associated with a root of the indicial equation ``p``. Conditions of
|
| 1200 |
+
a different format can also be provided in this case, see the
|
| 1201 |
+
docstring of HolonomicFunction class.
|
| 1202 |
+
|
| 1203 |
+
If it's not possible to numerically compute a initial condition,
|
| 1204 |
+
it is returned as a symbol :math:`C_j`, denoting the coefficient of
|
| 1205 |
+
:math:`(x - x_0)^j` in the power series about :math:`x_0`.
|
| 1206 |
+
|
| 1207 |
+
Examples
|
| 1208 |
+
========
|
| 1209 |
+
|
| 1210 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
| 1211 |
+
>>> from sympy import QQ
|
| 1212 |
+
>>> from sympy import symbols, S
|
| 1213 |
+
>>> x = symbols('x')
|
| 1214 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
| 1215 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence()
|
| 1216 |
+
[(HolonomicSequence((-1) + (n + 1)Sn, n), u(0) = 1, 0)]
|
| 1217 |
+
>>> HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_sequence()
|
| 1218 |
+
[(HolonomicSequence((n**2) + (n**2 + n)Sn, n), u(0) = 0, u(1) = 1, u(2) = -1/2, 2)]
|
| 1219 |
+
>>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_sequence()
|
| 1220 |
+
[(HolonomicSequence((n), n), u(0) = 1, 1/2, 1)]
|
| 1221 |
+
|
| 1222 |
+
See Also
|
| 1223 |
+
========
|
| 1224 |
+
|
| 1225 |
+
HolonomicFunction.series
|
| 1226 |
+
|
| 1227 |
+
References
|
| 1228 |
+
==========
|
| 1229 |
+
|
| 1230 |
+
.. [1] https://hal.inria.fr/inria-00070025/document
|
| 1231 |
+
.. [2] https://www3.risc.jku.at/publications/download/risc_2244/DIPLFORM.pdf
|
| 1232 |
+
|
| 1233 |
+
"""
|
| 1234 |
+
|
| 1235 |
+
if self.x0 != 0:
|
| 1236 |
+
return self.shift_x(self.x0).to_sequence()
|
| 1237 |
+
|
| 1238 |
+
# check whether a power series exists if the point is singular
|
| 1239 |
+
if self.annihilator.is_singular(self.x0):
|
| 1240 |
+
return self._frobenius(lb=lb)
|
| 1241 |
+
|
| 1242 |
+
dict1 = {}
|
| 1243 |
+
n = Symbol('n', integer=True)
|
| 1244 |
+
dom = self.annihilator.parent.base.dom
|
| 1245 |
+
R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn')
|
| 1246 |
+
|
| 1247 |
+
# substituting each term of the form `x^k Dx^j` in the
|
| 1248 |
+
# annihilator, according to the formula below:
|
| 1249 |
+
# x^k Dx^j = Sum(rf(n + 1 - k, j) * a(n + j - k) * x^n, (n, k, oo))
|
| 1250 |
+
# for explanation see [2].
|
| 1251 |
+
for i, j in enumerate(self.annihilator.listofpoly):
|
| 1252 |
+
|
| 1253 |
+
listofdmp = j.all_coeffs()
|
| 1254 |
+
degree = len(listofdmp) - 1
|
| 1255 |
+
|
| 1256 |
+
for k in range(degree + 1):
|
| 1257 |
+
coeff = listofdmp[degree - k]
|
| 1258 |
+
|
| 1259 |
+
if coeff == 0:
|
| 1260 |
+
continue
|
| 1261 |
+
|
| 1262 |
+
if (i - k, k) in dict1:
|
| 1263 |
+
dict1[(i - k, k)] += (dom.to_sympy(coeff) * rf(n - k + 1, i))
|
| 1264 |
+
else:
|
| 1265 |
+
dict1[(i - k, k)] = (dom.to_sympy(coeff) * rf(n - k + 1, i))
|
| 1266 |
+
|
| 1267 |
+
|
| 1268 |
+
sol = []
|
| 1269 |
+
keylist = [i[0] for i in dict1]
|
| 1270 |
+
lower = min(keylist)
|
| 1271 |
+
upper = max(keylist)
|
| 1272 |
+
degree = self.degree()
|
| 1273 |
+
|
| 1274 |
+
# the recurrence relation holds for all values of
|
| 1275 |
+
# n greater than smallest_n, i.e. n >= smallest_n
|
| 1276 |
+
smallest_n = lower + degree
|
| 1277 |
+
dummys = {}
|
| 1278 |
+
eqs = []
|
| 1279 |
+
unknowns = []
|
| 1280 |
+
|
| 1281 |
+
# an appropriate shift of the recurrence
|
| 1282 |
+
for j in range(lower, upper + 1):
|
| 1283 |
+
if j in keylist:
|
| 1284 |
+
temp = sum((v.subs(n, n - lower)
|
| 1285 |
+
for k, v in dict1.items() if k[0] == j),
|
| 1286 |
+
start=S.Zero)
|
| 1287 |
+
sol.append(temp)
|
| 1288 |
+
else:
|
| 1289 |
+
sol.append(S.Zero)
|
| 1290 |
+
|
| 1291 |
+
# the recurrence relation
|
| 1292 |
+
sol = RecurrenceOperator(sol, R)
|
| 1293 |
+
|
| 1294 |
+
# computing the initial conditions for recurrence
|
| 1295 |
+
order = sol.order
|
| 1296 |
+
all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z')
|
| 1297 |
+
all_roots = all_roots.keys()
|
| 1298 |
+
|
| 1299 |
+
if all_roots:
|
| 1300 |
+
max_root = max(all_roots) + 1
|
| 1301 |
+
smallest_n = max(max_root, smallest_n)
|
| 1302 |
+
order += smallest_n
|
| 1303 |
+
|
| 1304 |
+
y0 = _extend_y0(self, order)
|
| 1305 |
+
# u(n) = y^n(0)/factorial(n)
|
| 1306 |
+
u0 = [j / factorial(i) for i, j in enumerate(y0)]
|
| 1307 |
+
|
| 1308 |
+
# if sufficient conditions can't be computed then
|
| 1309 |
+
# try to use the series method i.e.
|
| 1310 |
+
# equate the coefficients of x^k in the equation formed by
|
| 1311 |
+
# substituting the series in differential equation, to zero.
|
| 1312 |
+
if len(u0) < order:
|
| 1313 |
+
|
| 1314 |
+
for i in range(degree):
|
| 1315 |
+
eq = S.Zero
|
| 1316 |
+
|
| 1317 |
+
for j in dict1:
|
| 1318 |
+
|
| 1319 |
+
if i + j[0] < 0:
|
| 1320 |
+
dummys[i + j[0]] = S.Zero
|
| 1321 |
+
|
| 1322 |
+
elif i + j[0] < len(u0):
|
| 1323 |
+
dummys[i + j[0]] = u0[i + j[0]]
|
| 1324 |
+
|
| 1325 |
+
elif not i + j[0] in dummys:
|
| 1326 |
+
dummys[i + j[0]] = Symbol('C_%s' %(i + j[0]))
|
| 1327 |
+
unknowns.append(dummys[i + j[0]])
|
| 1328 |
+
|
| 1329 |
+
if j[1] <= i:
|
| 1330 |
+
eq += dict1[j].subs(n, i) * dummys[i + j[0]]
|
| 1331 |
+
|
| 1332 |
+
eqs.append(eq)
|
| 1333 |
+
|
| 1334 |
+
# solve the system of equations formed
|
| 1335 |
+
soleqs = solve(eqs, *unknowns)
|
| 1336 |
+
|
| 1337 |
+
if isinstance(soleqs, dict):
|
| 1338 |
+
|
| 1339 |
+
for i in range(len(u0), order):
|
| 1340 |
+
|
| 1341 |
+
if i not in dummys:
|
| 1342 |
+
dummys[i] = Symbol('C_%s' %i)
|
| 1343 |
+
|
| 1344 |
+
if dummys[i] in soleqs:
|
| 1345 |
+
u0.append(soleqs[dummys[i]])
|
| 1346 |
+
|
| 1347 |
+
else:
|
| 1348 |
+
u0.append(dummys[i])
|
| 1349 |
+
|
| 1350 |
+
if lb:
|
| 1351 |
+
return [(HolonomicSequence(sol, u0), smallest_n)]
|
| 1352 |
+
return [HolonomicSequence(sol, u0)]
|
| 1353 |
+
|
| 1354 |
+
for i in range(len(u0), order):
|
| 1355 |
+
|
| 1356 |
+
if i not in dummys:
|
| 1357 |
+
dummys[i] = Symbol('C_%s' %i)
|
| 1358 |
+
|
| 1359 |
+
s = False
|
| 1360 |
+
for j in soleqs:
|
| 1361 |
+
if dummys[i] in j:
|
| 1362 |
+
u0.append(j[dummys[i]])
|
| 1363 |
+
s = True
|
| 1364 |
+
if not s:
|
| 1365 |
+
u0.append(dummys[i])
|
| 1366 |
+
|
| 1367 |
+
if lb:
|
| 1368 |
+
return [(HolonomicSequence(sol, u0), smallest_n)]
|
| 1369 |
+
|
| 1370 |
+
return [HolonomicSequence(sol, u0)]
|
| 1371 |
+
|
| 1372 |
+
def _frobenius(self, lb=True):
|
| 1373 |
+
# compute the roots of indicial equation
|
| 1374 |
+
indicialroots = self._indicial()
|
| 1375 |
+
|
| 1376 |
+
reals = []
|
| 1377 |
+
compl = []
|
| 1378 |
+
for i in ordered(indicialroots.keys()):
|
| 1379 |
+
if i.is_real:
|
| 1380 |
+
reals.extend([i] * indicialroots[i])
|
| 1381 |
+
else:
|
| 1382 |
+
a, b = i.as_real_imag()
|
| 1383 |
+
compl.extend([(i, a, b)] * indicialroots[i])
|
| 1384 |
+
|
| 1385 |
+
# sort the roots for a fixed ordering of solution
|
| 1386 |
+
compl.sort(key=lambda x : x[1])
|
| 1387 |
+
compl.sort(key=lambda x : x[2])
|
| 1388 |
+
reals.sort()
|
| 1389 |
+
|
| 1390 |
+
# grouping the roots, roots differ by an integer are put in the same group.
|
| 1391 |
+
grp = []
|
| 1392 |
+
|
| 1393 |
+
for i in reals:
|
| 1394 |
+
if len(grp) == 0:
|
| 1395 |
+
grp.append([i])
|
| 1396 |
+
continue
|
| 1397 |
+
for j in grp:
|
| 1398 |
+
if int_valued(j[0] - i):
|
| 1399 |
+
j.append(i)
|
| 1400 |
+
break
|
| 1401 |
+
else:
|
| 1402 |
+
grp.append([i])
|
| 1403 |
+
|
| 1404 |
+
# True if none of the roots differ by an integer i.e.
|
| 1405 |
+
# each element in group have only one member
|
| 1406 |
+
independent = all(len(i) == 1 for i in grp)
|
| 1407 |
+
|
| 1408 |
+
allpos = all(i >= 0 for i in reals)
|
| 1409 |
+
allint = all(int_valued(i) for i in reals)
|
| 1410 |
+
|
| 1411 |
+
# if initial conditions are provided
|
| 1412 |
+
# then use them.
|
| 1413 |
+
if self.is_singularics() == True:
|
| 1414 |
+
rootstoconsider = []
|
| 1415 |
+
for i in ordered(self.y0.keys()):
|
| 1416 |
+
for j in ordered(indicialroots.keys()):
|
| 1417 |
+
if equal_valued(j, i):
|
| 1418 |
+
rootstoconsider.append(i)
|
| 1419 |
+
|
| 1420 |
+
elif allpos and allint:
|
| 1421 |
+
rootstoconsider = [min(reals)]
|
| 1422 |
+
|
| 1423 |
+
elif independent:
|
| 1424 |
+
rootstoconsider = [i[0] for i in grp] + [j[0] for j in compl]
|
| 1425 |
+
|
| 1426 |
+
elif not allint:
|
| 1427 |
+
rootstoconsider = [i for i in reals if not int(i) == i]
|
| 1428 |
+
|
| 1429 |
+
elif not allpos:
|
| 1430 |
+
|
| 1431 |
+
if not self._have_init_cond() or S(self.y0[0]).is_finite == False:
|
| 1432 |
+
rootstoconsider = [min(reals)]
|
| 1433 |
+
|
| 1434 |
+
else:
|
| 1435 |
+
posroots = [i for i in reals if i >= 0]
|
| 1436 |
+
rootstoconsider = [min(posroots)]
|
| 1437 |
+
|
| 1438 |
+
n = Symbol('n', integer=True)
|
| 1439 |
+
dom = self.annihilator.parent.base.dom
|
| 1440 |
+
R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn')
|
| 1441 |
+
|
| 1442 |
+
finalsol = []
|
| 1443 |
+
char = ord('C')
|
| 1444 |
+
|
| 1445 |
+
for p in rootstoconsider:
|
| 1446 |
+
dict1 = {}
|
| 1447 |
+
|
| 1448 |
+
for i, j in enumerate(self.annihilator.listofpoly):
|
| 1449 |
+
|
| 1450 |
+
listofdmp = j.all_coeffs()
|
| 1451 |
+
degree = len(listofdmp) - 1
|
| 1452 |
+
|
| 1453 |
+
for k in range(degree + 1):
|
| 1454 |
+
coeff = listofdmp[degree - k]
|
| 1455 |
+
|
| 1456 |
+
if coeff == 0:
|
| 1457 |
+
continue
|
| 1458 |
+
|
| 1459 |
+
if (i - k, k - i) in dict1:
|
| 1460 |
+
dict1[(i - k, k - i)] += (dom.to_sympy(coeff) * rf(n - k + 1 + p, i))
|
| 1461 |
+
else:
|
| 1462 |
+
dict1[(i - k, k - i)] = (dom.to_sympy(coeff) * rf(n - k + 1 + p, i))
|
| 1463 |
+
|
| 1464 |
+
sol = []
|
| 1465 |
+
keylist = [i[0] for i in dict1]
|
| 1466 |
+
lower = min(keylist)
|
| 1467 |
+
upper = max(keylist)
|
| 1468 |
+
degree = max(i[1] for i in dict1)
|
| 1469 |
+
degree2 = min(i[1] for i in dict1)
|
| 1470 |
+
|
| 1471 |
+
smallest_n = lower + degree
|
| 1472 |
+
dummys = {}
|
| 1473 |
+
eqs = []
|
| 1474 |
+
unknowns = []
|
| 1475 |
+
|
| 1476 |
+
for j in range(lower, upper + 1):
|
| 1477 |
+
if j in keylist:
|
| 1478 |
+
temp = sum((v.subs(n, n - lower)
|
| 1479 |
+
for k, v in dict1.items() if k[0] == j),
|
| 1480 |
+
start=S.Zero)
|
| 1481 |
+
sol.append(temp)
|
| 1482 |
+
else:
|
| 1483 |
+
sol.append(S.Zero)
|
| 1484 |
+
|
| 1485 |
+
# the recurrence relation
|
| 1486 |
+
sol = RecurrenceOperator(sol, R)
|
| 1487 |
+
|
| 1488 |
+
# computing the initial conditions for recurrence
|
| 1489 |
+
order = sol.order
|
| 1490 |
+
all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z')
|
| 1491 |
+
all_roots = all_roots.keys()
|
| 1492 |
+
|
| 1493 |
+
if all_roots:
|
| 1494 |
+
max_root = max(all_roots) + 1
|
| 1495 |
+
smallest_n = max(max_root, smallest_n)
|
| 1496 |
+
order += smallest_n
|
| 1497 |
+
|
| 1498 |
+
u0 = []
|
| 1499 |
+
|
| 1500 |
+
if self.is_singularics() == True:
|
| 1501 |
+
u0 = self.y0[p]
|
| 1502 |
+
|
| 1503 |
+
elif self.is_singularics() == False and p >= 0 and int(p) == p and len(rootstoconsider) == 1:
|
| 1504 |
+
y0 = _extend_y0(self, order + int(p))
|
| 1505 |
+
# u(n) = y^n(0)/factorial(n)
|
| 1506 |
+
if len(y0) > int(p):
|
| 1507 |
+
u0 = [y0[i] / factorial(i) for i in range(int(p), len(y0))]
|
| 1508 |
+
|
| 1509 |
+
if len(u0) < order:
|
| 1510 |
+
|
| 1511 |
+
for i in range(degree2, degree):
|
| 1512 |
+
eq = S.Zero
|
| 1513 |
+
|
| 1514 |
+
for j in dict1:
|
| 1515 |
+
if i + j[0] < 0:
|
| 1516 |
+
dummys[i + j[0]] = S.Zero
|
| 1517 |
+
|
| 1518 |
+
elif i + j[0] < len(u0):
|
| 1519 |
+
dummys[i + j[0]] = u0[i + j[0]]
|
| 1520 |
+
|
| 1521 |
+
elif not i + j[0] in dummys:
|
| 1522 |
+
letter = chr(char) + '_%s' %(i + j[0])
|
| 1523 |
+
dummys[i + j[0]] = Symbol(letter)
|
| 1524 |
+
unknowns.append(dummys[i + j[0]])
|
| 1525 |
+
|
| 1526 |
+
if j[1] <= i:
|
| 1527 |
+
eq += dict1[j].subs(n, i) * dummys[i + j[0]]
|
| 1528 |
+
|
| 1529 |
+
eqs.append(eq)
|
| 1530 |
+
|
| 1531 |
+
# solve the system of equations formed
|
| 1532 |
+
soleqs = solve(eqs, *unknowns)
|
| 1533 |
+
|
| 1534 |
+
if isinstance(soleqs, dict):
|
| 1535 |
+
|
| 1536 |
+
for i in range(len(u0), order):
|
| 1537 |
+
|
| 1538 |
+
if i not in dummys:
|
| 1539 |
+
letter = chr(char) + '_%s' %i
|
| 1540 |
+
dummys[i] = Symbol(letter)
|
| 1541 |
+
|
| 1542 |
+
if dummys[i] in soleqs:
|
| 1543 |
+
u0.append(soleqs[dummys[i]])
|
| 1544 |
+
|
| 1545 |
+
else:
|
| 1546 |
+
u0.append(dummys[i])
|
| 1547 |
+
|
| 1548 |
+
if lb:
|
| 1549 |
+
finalsol.append((HolonomicSequence(sol, u0), p, smallest_n))
|
| 1550 |
+
continue
|
| 1551 |
+
else:
|
| 1552 |
+
finalsol.append((HolonomicSequence(sol, u0), p))
|
| 1553 |
+
continue
|
| 1554 |
+
|
| 1555 |
+
for i in range(len(u0), order):
|
| 1556 |
+
|
| 1557 |
+
if i not in dummys:
|
| 1558 |
+
letter = chr(char) + '_%s' %i
|
| 1559 |
+
dummys[i] = Symbol(letter)
|
| 1560 |
+
|
| 1561 |
+
s = False
|
| 1562 |
+
for j in soleqs:
|
| 1563 |
+
if dummys[i] in j:
|
| 1564 |
+
u0.append(j[dummys[i]])
|
| 1565 |
+
s = True
|
| 1566 |
+
if not s:
|
| 1567 |
+
u0.append(dummys[i])
|
| 1568 |
+
if lb:
|
| 1569 |
+
finalsol.append((HolonomicSequence(sol, u0), p, smallest_n))
|
| 1570 |
+
|
| 1571 |
+
else:
|
| 1572 |
+
finalsol.append((HolonomicSequence(sol, u0), p))
|
| 1573 |
+
char += 1
|
| 1574 |
+
return finalsol
|
| 1575 |
+
|
| 1576 |
+
def series(self, n=6, coefficient=False, order=True, _recur=None):
|
| 1577 |
+
r"""
|
| 1578 |
+
Finds the power series expansion of given holonomic function about :math:`x_0`.
|
| 1579 |
+
|
| 1580 |
+
Explanation
|
| 1581 |
+
===========
|
| 1582 |
+
|
| 1583 |
+
A list of series might be returned if :math:`x_0` is a regular point with
|
| 1584 |
+
multiple roots of the indicial equation.
|
| 1585 |
+
|
| 1586 |
+
Examples
|
| 1587 |
+
========
|
| 1588 |
+
|
| 1589 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
| 1590 |
+
>>> from sympy import QQ
|
| 1591 |
+
>>> from sympy import symbols
|
| 1592 |
+
>>> x = symbols('x')
|
| 1593 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
| 1594 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).series() # e^x
|
| 1595 |
+
1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)
|
| 1596 |
+
>>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).series(n=8) # sin(x)
|
| 1597 |
+
x - x**3/6 + x**5/120 - x**7/5040 + O(x**8)
|
| 1598 |
+
|
| 1599 |
+
See Also
|
| 1600 |
+
========
|
| 1601 |
+
|
| 1602 |
+
HolonomicFunction.to_sequence
|
| 1603 |
+
"""
|
| 1604 |
+
|
| 1605 |
+
if _recur is None:
|
| 1606 |
+
recurrence = self.to_sequence()
|
| 1607 |
+
else:
|
| 1608 |
+
recurrence = _recur
|
| 1609 |
+
|
| 1610 |
+
if isinstance(recurrence, tuple) and len(recurrence) == 2:
|
| 1611 |
+
recurrence = recurrence[0]
|
| 1612 |
+
constantpower = 0
|
| 1613 |
+
elif isinstance(recurrence, tuple) and len(recurrence) == 3:
|
| 1614 |
+
constantpower = recurrence[1]
|
| 1615 |
+
recurrence = recurrence[0]
|
| 1616 |
+
|
| 1617 |
+
elif len(recurrence) == 1 and len(recurrence[0]) == 2:
|
| 1618 |
+
recurrence = recurrence[0][0]
|
| 1619 |
+
constantpower = 0
|
| 1620 |
+
elif len(recurrence) == 1 and len(recurrence[0]) == 3:
|
| 1621 |
+
constantpower = recurrence[0][1]
|
| 1622 |
+
recurrence = recurrence[0][0]
|
| 1623 |
+
else:
|
| 1624 |
+
return [self.series(_recur=i) for i in recurrence]
|
| 1625 |
+
|
| 1626 |
+
n = n - int(constantpower)
|
| 1627 |
+
l = len(recurrence.u0) - 1
|
| 1628 |
+
k = recurrence.recurrence.order
|
| 1629 |
+
x = self.x
|
| 1630 |
+
x0 = self.x0
|
| 1631 |
+
seq_dmp = recurrence.recurrence.listofpoly
|
| 1632 |
+
R = recurrence.recurrence.parent.base
|
| 1633 |
+
K = R.get_field()
|
| 1634 |
+
seq = [K.new(j.to_list()) for j in seq_dmp]
|
| 1635 |
+
sub = [-seq[i] / seq[k] for i in range(k)]
|
| 1636 |
+
sol = list(recurrence.u0)
|
| 1637 |
+
|
| 1638 |
+
if l + 1 < n:
|
| 1639 |
+
# use the initial conditions to find the next term
|
| 1640 |
+
for i in range(l + 1 - k, n - k):
|
| 1641 |
+
coeff = sum((DMFsubs(sub[j], i) * sol[i + j]
|
| 1642 |
+
for j in range(k) if i + j >= 0), start=S.Zero)
|
| 1643 |
+
sol.append(coeff)
|
| 1644 |
+
|
| 1645 |
+
if coefficient:
|
| 1646 |
+
return sol
|
| 1647 |
+
|
| 1648 |
+
ser = sum((x**(i + constantpower) * j for i, j in enumerate(sol)),
|
| 1649 |
+
start=S.Zero)
|
| 1650 |
+
if order:
|
| 1651 |
+
ser += Order(x**(n + int(constantpower)), x)
|
| 1652 |
+
if x0 != 0:
|
| 1653 |
+
return ser.subs(x, x - x0)
|
| 1654 |
+
return ser
|
| 1655 |
+
|
| 1656 |
+
def _indicial(self):
|
| 1657 |
+
"""
|
| 1658 |
+
Computes roots of the Indicial equation.
|
| 1659 |
+
"""
|
| 1660 |
+
|
| 1661 |
+
if self.x0 != 0:
|
| 1662 |
+
return self.shift_x(self.x0)._indicial()
|
| 1663 |
+
|
| 1664 |
+
list_coeff = self.annihilator.listofpoly
|
| 1665 |
+
R = self.annihilator.parent.base
|
| 1666 |
+
x = self.x
|
| 1667 |
+
s = R.zero
|
| 1668 |
+
y = R.one
|
| 1669 |
+
|
| 1670 |
+
def _pole_degree(poly):
|
| 1671 |
+
root_all = roots(R.to_sympy(poly), x, filter='Z')
|
| 1672 |
+
if 0 in root_all.keys():
|
| 1673 |
+
return root_all[0]
|
| 1674 |
+
else:
|
| 1675 |
+
return 0
|
| 1676 |
+
|
| 1677 |
+
degree = max(j.degree() for j in list_coeff)
|
| 1678 |
+
inf = 10 * (max(1, degree) + max(1, self.annihilator.order))
|
| 1679 |
+
|
| 1680 |
+
deg = lambda q: inf if q.is_zero else _pole_degree(q)
|
| 1681 |
+
b = min(deg(q) - j for j, q in enumerate(list_coeff))
|
| 1682 |
+
|
| 1683 |
+
for i, j in enumerate(list_coeff):
|
| 1684 |
+
listofdmp = j.all_coeffs()
|
| 1685 |
+
degree = len(listofdmp) - 1
|
| 1686 |
+
if 0 <= i + b <= degree:
|
| 1687 |
+
s = s + listofdmp[degree - i - b] * y
|
| 1688 |
+
y *= R.from_sympy(x - i)
|
| 1689 |
+
|
| 1690 |
+
return roots(R.to_sympy(s), x)
|
| 1691 |
+
|
| 1692 |
+
def evalf(self, points, method='RK4', h=0.05, derivatives=False):
|
| 1693 |
+
r"""
|
| 1694 |
+
Finds numerical value of a holonomic function using numerical methods.
|
| 1695 |
+
(RK4 by default). A set of points (real or complex) must be provided
|
| 1696 |
+
which will be the path for the numerical integration.
|
| 1697 |
+
|
| 1698 |
+
Explanation
|
| 1699 |
+
===========
|
| 1700 |
+
|
| 1701 |
+
The path should be given as a list :math:`[x_1, x_2, \dots x_n]`. The numerical
|
| 1702 |
+
values will be computed at each point in this order
|
| 1703 |
+
:math:`x_1 \rightarrow x_2 \rightarrow x_3 \dots \rightarrow x_n`.
|
| 1704 |
+
|
| 1705 |
+
Returns values of the function at :math:`x_1, x_2, \dots x_n` in a list.
|
| 1706 |
+
|
| 1707 |
+
Examples
|
| 1708 |
+
========
|
| 1709 |
+
|
| 1710 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
| 1711 |
+
>>> from sympy import QQ
|
| 1712 |
+
>>> from sympy import symbols
|
| 1713 |
+
>>> x = symbols('x')
|
| 1714 |
+
>>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx')
|
| 1715 |
+
|
| 1716 |
+
A straight line on the real axis from (0 to 1)
|
| 1717 |
+
|
| 1718 |
+
>>> r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
|
| 1719 |
+
|
| 1720 |
+
Runge-Kutta 4th order on e^x from 0.1 to 1.
|
| 1721 |
+
Exact solution at 1 is 2.71828182845905
|
| 1722 |
+
|
| 1723 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r)
|
| 1724 |
+
[1.10517083333333, 1.22140257085069, 1.34985849706254, 1.49182424008069,
|
| 1725 |
+
1.64872063859684, 1.82211796209193, 2.01375162659678, 2.22553956329232,
|
| 1726 |
+
2.45960141378007, 2.71827974413517]
|
| 1727 |
+
|
| 1728 |
+
Euler's method for the same
|
| 1729 |
+
|
| 1730 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r, method='Euler')
|
| 1731 |
+
[1.1, 1.21, 1.331, 1.4641, 1.61051, 1.771561, 1.9487171, 2.14358881,
|
| 1732 |
+
2.357947691, 2.5937424601]
|
| 1733 |
+
|
| 1734 |
+
One can also observe that the value obtained using Runge-Kutta 4th order
|
| 1735 |
+
is much more accurate than Euler's method.
|
| 1736 |
+
"""
|
| 1737 |
+
|
| 1738 |
+
from sympy.holonomic.numerical import _evalf
|
| 1739 |
+
lp = False
|
| 1740 |
+
|
| 1741 |
+
# if a point `b` is given instead of a mesh
|
| 1742 |
+
if not hasattr(points, "__iter__"):
|
| 1743 |
+
lp = True
|
| 1744 |
+
b = S(points)
|
| 1745 |
+
if self.x0 == b:
|
| 1746 |
+
return _evalf(self, [b], method=method, derivatives=derivatives)[-1]
|
| 1747 |
+
|
| 1748 |
+
if not b.is_Number:
|
| 1749 |
+
raise NotImplementedError
|
| 1750 |
+
|
| 1751 |
+
a = self.x0
|
| 1752 |
+
if a > b:
|
| 1753 |
+
h = -h
|
| 1754 |
+
n = int((b - a) / h)
|
| 1755 |
+
points = [a + h]
|
| 1756 |
+
for i in range(n - 1):
|
| 1757 |
+
points.append(points[-1] + h)
|
| 1758 |
+
|
| 1759 |
+
for i in roots(self.annihilator.parent.base.to_sympy(self.annihilator.listofpoly[-1]), self.x):
|
| 1760 |
+
if i == self.x0 or i in points:
|
| 1761 |
+
raise SingularityError(self, i)
|
| 1762 |
+
|
| 1763 |
+
if lp:
|
| 1764 |
+
return _evalf(self, points, method=method, derivatives=derivatives)[-1]
|
| 1765 |
+
return _evalf(self, points, method=method, derivatives=derivatives)
|
| 1766 |
+
|
| 1767 |
+
def change_x(self, z):
|
| 1768 |
+
"""
|
| 1769 |
+
Changes only the variable of Holonomic Function, for internal
|
| 1770 |
+
purposes. For composition use HolonomicFunction.composition()
|
| 1771 |
+
"""
|
| 1772 |
+
|
| 1773 |
+
dom = self.annihilator.parent.base.dom
|
| 1774 |
+
R = dom.old_poly_ring(z)
|
| 1775 |
+
parent, _ = DifferentialOperators(R, 'Dx')
|
| 1776 |
+
sol = [R(j.to_list()) for j in self.annihilator.listofpoly]
|
| 1777 |
+
sol = DifferentialOperator(sol, parent)
|
| 1778 |
+
return HolonomicFunction(sol, z, self.x0, self.y0)
|
| 1779 |
+
|
| 1780 |
+
def shift_x(self, a):
|
| 1781 |
+
"""
|
| 1782 |
+
Substitute `x + a` for `x`.
|
| 1783 |
+
"""
|
| 1784 |
+
|
| 1785 |
+
x = self.x
|
| 1786 |
+
listaftershift = self.annihilator.listofpoly
|
| 1787 |
+
base = self.annihilator.parent.base
|
| 1788 |
+
|
| 1789 |
+
sol = [base.from_sympy(base.to_sympy(i).subs(x, x + a)) for i in listaftershift]
|
| 1790 |
+
sol = DifferentialOperator(sol, self.annihilator.parent)
|
| 1791 |
+
x0 = self.x0 - a
|
| 1792 |
+
if not self._have_init_cond():
|
| 1793 |
+
return HolonomicFunction(sol, x)
|
| 1794 |
+
return HolonomicFunction(sol, x, x0, self.y0)
|
| 1795 |
+
|
| 1796 |
+
def to_hyper(self, as_list=False, _recur=None):
|
| 1797 |
+
r"""
|
| 1798 |
+
Returns a hypergeometric function (or linear combination of them)
|
| 1799 |
+
representing the given holonomic function.
|
| 1800 |
+
|
| 1801 |
+
Explanation
|
| 1802 |
+
===========
|
| 1803 |
+
|
| 1804 |
+
Returns an answer of the form:
|
| 1805 |
+
`a_1 \cdot x^{b_1} \cdot{hyper()} + a_2 \cdot x^{b_2} \cdot{hyper()} \dots`
|
| 1806 |
+
|
| 1807 |
+
This is very useful as one can now use ``hyperexpand`` to find the
|
| 1808 |
+
symbolic expressions/functions.
|
| 1809 |
+
|
| 1810 |
+
Examples
|
| 1811 |
+
========
|
| 1812 |
+
|
| 1813 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
| 1814 |
+
>>> from sympy import ZZ
|
| 1815 |
+
>>> from sympy import symbols
|
| 1816 |
+
>>> x = symbols('x')
|
| 1817 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
|
| 1818 |
+
>>> # sin(x)
|
| 1819 |
+
>>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_hyper()
|
| 1820 |
+
x*hyper((), (3/2,), -x**2/4)
|
| 1821 |
+
>>> # exp(x)
|
| 1822 |
+
>>> HolonomicFunction(Dx - 1, x, 0, [1]).to_hyper()
|
| 1823 |
+
hyper((), (), x)
|
| 1824 |
+
|
| 1825 |
+
See Also
|
| 1826 |
+
========
|
| 1827 |
+
|
| 1828 |
+
from_hyper, from_meijerg
|
| 1829 |
+
"""
|
| 1830 |
+
|
| 1831 |
+
if _recur is None:
|
| 1832 |
+
recurrence = self.to_sequence()
|
| 1833 |
+
else:
|
| 1834 |
+
recurrence = _recur
|
| 1835 |
+
|
| 1836 |
+
if isinstance(recurrence, tuple) and len(recurrence) == 2:
|
| 1837 |
+
smallest_n = recurrence[1]
|
| 1838 |
+
recurrence = recurrence[0]
|
| 1839 |
+
constantpower = 0
|
| 1840 |
+
elif isinstance(recurrence, tuple) and len(recurrence) == 3:
|
| 1841 |
+
smallest_n = recurrence[2]
|
| 1842 |
+
constantpower = recurrence[1]
|
| 1843 |
+
recurrence = recurrence[0]
|
| 1844 |
+
elif len(recurrence) == 1 and len(recurrence[0]) == 2:
|
| 1845 |
+
smallest_n = recurrence[0][1]
|
| 1846 |
+
recurrence = recurrence[0][0]
|
| 1847 |
+
constantpower = 0
|
| 1848 |
+
elif len(recurrence) == 1 and len(recurrence[0]) == 3:
|
| 1849 |
+
smallest_n = recurrence[0][2]
|
| 1850 |
+
constantpower = recurrence[0][1]
|
| 1851 |
+
recurrence = recurrence[0][0]
|
| 1852 |
+
else:
|
| 1853 |
+
sol = self.to_hyper(as_list=as_list, _recur=recurrence[0])
|
| 1854 |
+
for i in recurrence[1:]:
|
| 1855 |
+
sol += self.to_hyper(as_list=as_list, _recur=i)
|
| 1856 |
+
return sol
|
| 1857 |
+
|
| 1858 |
+
u0 = recurrence.u0
|
| 1859 |
+
r = recurrence.recurrence
|
| 1860 |
+
x = self.x
|
| 1861 |
+
x0 = self.x0
|
| 1862 |
+
|
| 1863 |
+
# order of the recurrence relation
|
| 1864 |
+
m = r.order
|
| 1865 |
+
|
| 1866 |
+
# when no recurrence exists, and the power series have finite terms
|
| 1867 |
+
if m == 0:
|
| 1868 |
+
nonzeroterms = roots(r.parent.base.to_sympy(r.listofpoly[0]), recurrence.n, filter='R')
|
| 1869 |
+
|
| 1870 |
+
sol = S.Zero
|
| 1871 |
+
for j, i in enumerate(nonzeroterms):
|
| 1872 |
+
|
| 1873 |
+
if i < 0 or not int_valued(i):
|
| 1874 |
+
continue
|
| 1875 |
+
|
| 1876 |
+
i = int(i)
|
| 1877 |
+
if i < len(u0):
|
| 1878 |
+
if isinstance(u0[i], (PolyElement, FracElement)):
|
| 1879 |
+
u0[i] = u0[i].as_expr()
|
| 1880 |
+
sol += u0[i] * x**i
|
| 1881 |
+
|
| 1882 |
+
else:
|
| 1883 |
+
sol += Symbol('C_%s' %j) * x**i
|
| 1884 |
+
|
| 1885 |
+
if isinstance(sol, (PolyElement, FracElement)):
|
| 1886 |
+
sol = sol.as_expr() * x**constantpower
|
| 1887 |
+
else:
|
| 1888 |
+
sol = sol * x**constantpower
|
| 1889 |
+
if as_list:
|
| 1890 |
+
if x0 != 0:
|
| 1891 |
+
return [(sol.subs(x, x - x0), )]
|
| 1892 |
+
return [(sol, )]
|
| 1893 |
+
if x0 != 0:
|
| 1894 |
+
return sol.subs(x, x - x0)
|
| 1895 |
+
return sol
|
| 1896 |
+
|
| 1897 |
+
if smallest_n + m > len(u0):
|
| 1898 |
+
raise NotImplementedError("Can't compute sufficient Initial Conditions")
|
| 1899 |
+
|
| 1900 |
+
# check if the recurrence represents a hypergeometric series
|
| 1901 |
+
if any(i != r.parent.base.zero for i in r.listofpoly[1:-1]):
|
| 1902 |
+
raise NotHyperSeriesError(self, self.x0)
|
| 1903 |
+
|
| 1904 |
+
a = r.listofpoly[0]
|
| 1905 |
+
b = r.listofpoly[-1]
|
| 1906 |
+
|
| 1907 |
+
# the constant multiple of argument of hypergeometric function
|
| 1908 |
+
if isinstance(a.LC(), (PolyElement, FracElement)):
|
| 1909 |
+
c = - (S(a.LC().as_expr()) * m**(a.degree())) / (S(b.LC().as_expr()) * m**(b.degree()))
|
| 1910 |
+
else:
|
| 1911 |
+
c = - (S(a.LC()) * m**(a.degree())) / (S(b.LC()) * m**(b.degree()))
|
| 1912 |
+
|
| 1913 |
+
sol = 0
|
| 1914 |
+
|
| 1915 |
+
arg1 = roots(r.parent.base.to_sympy(a), recurrence.n)
|
| 1916 |
+
arg2 = roots(r.parent.base.to_sympy(b), recurrence.n)
|
| 1917 |
+
|
| 1918 |
+
# iterate through the initial conditions to find
|
| 1919 |
+
# the hypergeometric representation of the given
|
| 1920 |
+
# function.
|
| 1921 |
+
# The answer will be a linear combination
|
| 1922 |
+
# of different hypergeometric series which satisfies
|
| 1923 |
+
# the recurrence.
|
| 1924 |
+
if as_list:
|
| 1925 |
+
listofsol = []
|
| 1926 |
+
for i in range(smallest_n + m):
|
| 1927 |
+
|
| 1928 |
+
# if the recurrence relation doesn't hold for `n = i`,
|
| 1929 |
+
# then a Hypergeometric representation doesn't exist.
|
| 1930 |
+
# add the algebraic term a * x**i to the solution,
|
| 1931 |
+
# where a is u0[i]
|
| 1932 |
+
if i < smallest_n:
|
| 1933 |
+
if as_list:
|
| 1934 |
+
listofsol.append(((S(u0[i]) * x**(i+constantpower)).subs(x, x-x0), ))
|
| 1935 |
+
else:
|
| 1936 |
+
sol += S(u0[i]) * x**i
|
| 1937 |
+
continue
|
| 1938 |
+
|
| 1939 |
+
# if the coefficient u0[i] is zero, then the
|
| 1940 |
+
# independent hypergeomtric series starting with
|
| 1941 |
+
# x**i is not a part of the answer.
|
| 1942 |
+
if S(u0[i]) == 0:
|
| 1943 |
+
continue
|
| 1944 |
+
|
| 1945 |
+
ap = []
|
| 1946 |
+
bq = []
|
| 1947 |
+
|
| 1948 |
+
# substitute m * n + i for n
|
| 1949 |
+
for k in ordered(arg1.keys()):
|
| 1950 |
+
ap.extend([nsimplify((i - k) / m)] * arg1[k])
|
| 1951 |
+
|
| 1952 |
+
for k in ordered(arg2.keys()):
|
| 1953 |
+
bq.extend([nsimplify((i - k) / m)] * arg2[k])
|
| 1954 |
+
|
| 1955 |
+
# convention of (k + 1) in the denominator
|
| 1956 |
+
if 1 in bq:
|
| 1957 |
+
bq.remove(1)
|
| 1958 |
+
else:
|
| 1959 |
+
ap.append(1)
|
| 1960 |
+
if as_list:
|
| 1961 |
+
listofsol.append(((S(u0[i])*x**(i+constantpower)).subs(x, x-x0), (hyper(ap, bq, c*x**m)).subs(x, x-x0)))
|
| 1962 |
+
else:
|
| 1963 |
+
sol += S(u0[i]) * hyper(ap, bq, c * x**m) * x**i
|
| 1964 |
+
if as_list:
|
| 1965 |
+
return listofsol
|
| 1966 |
+
sol = sol * x**constantpower
|
| 1967 |
+
if x0 != 0:
|
| 1968 |
+
return sol.subs(x, x - x0)
|
| 1969 |
+
|
| 1970 |
+
return sol
|
| 1971 |
+
|
| 1972 |
+
def to_expr(self):
|
| 1973 |
+
"""
|
| 1974 |
+
Converts a Holonomic Function back to elementary functions.
|
| 1975 |
+
|
| 1976 |
+
Examples
|
| 1977 |
+
========
|
| 1978 |
+
|
| 1979 |
+
>>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators
|
| 1980 |
+
>>> from sympy import ZZ
|
| 1981 |
+
>>> from sympy import symbols, S
|
| 1982 |
+
>>> x = symbols('x')
|
| 1983 |
+
>>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx')
|
| 1984 |
+
>>> HolonomicFunction(x**2*Dx**2 + x*Dx + (x**2 - 1), x, 0, [0, S(1)/2]).to_expr()
|
| 1985 |
+
besselj(1, x)
|
| 1986 |
+
>>> HolonomicFunction((1 + x)*Dx**3 + Dx**2, x, 0, [1, 1, 1]).to_expr()
|
| 1987 |
+
x*log(x + 1) + log(x + 1) + 1
|
| 1988 |
+
|
| 1989 |
+
"""
|
| 1990 |
+
|
| 1991 |
+
return hyperexpand(self.to_hyper()).simplify()
|
| 1992 |
+
|
| 1993 |
+
def change_ics(self, b, lenics=None):
|
| 1994 |
+
"""
|
| 1995 |
+
Changes the point `x0` to ``b`` for initial conditions.
|
| 1996 |
+
|
| 1997 |
+
Examples
|
| 1998 |
+
========
|
| 1999 |
+
|
| 2000 |
+
>>> from sympy.holonomic import expr_to_holonomic
|
| 2001 |
+
>>> from sympy import symbols, sin, exp
|
| 2002 |
+
>>> x = symbols('x')
|
| 2003 |
+
|
| 2004 |
+
>>> expr_to_holonomic(sin(x)).change_ics(1)
|
| 2005 |
+
HolonomicFunction((1) + (1)*Dx**2, x, 1, [sin(1), cos(1)])
|
| 2006 |
+
|
| 2007 |
+
>>> expr_to_holonomic(exp(x)).change_ics(2)
|
| 2008 |
+
HolonomicFunction((-1) + (1)*Dx, x, 2, [exp(2)])
|
| 2009 |
+
"""
|
| 2010 |
+
|
| 2011 |
+
symbolic = True
|
| 2012 |
+
|
| 2013 |
+
if lenics is None and len(self.y0) > self.annihilator.order:
|
| 2014 |
+
lenics = len(self.y0)
|
| 2015 |
+
dom = self.annihilator.parent.base.domain
|
| 2016 |
+
|
| 2017 |
+
try:
|
| 2018 |
+
sol = expr_to_holonomic(self.to_expr(), x=self.x, x0=b, lenics=lenics, domain=dom)
|
| 2019 |
+
except (NotPowerSeriesError, NotHyperSeriesError):
|
| 2020 |
+
symbolic = False
|
| 2021 |
+
|
| 2022 |
+
if symbolic and sol.x0 == b:
|
| 2023 |
+
return sol
|
| 2024 |
+
|
| 2025 |
+
y0 = self.evalf(b, derivatives=True)
|
| 2026 |
+
return HolonomicFunction(self.annihilator, self.x, b, y0)
|
| 2027 |
+
|
| 2028 |
+
def to_meijerg(self):
|
| 2029 |
+
"""
|
| 2030 |
+
Returns a linear combination of Meijer G-functions.
|
| 2031 |
+
|
| 2032 |
+
Examples
|
| 2033 |
+
========
|
| 2034 |
+
|
| 2035 |
+
>>> from sympy.holonomic import expr_to_holonomic
|
| 2036 |
+
>>> from sympy import sin, cos, hyperexpand, log, symbols
|
| 2037 |
+
>>> x = symbols('x')
|
| 2038 |
+
>>> hyperexpand(expr_to_holonomic(cos(x) + sin(x)).to_meijerg())
|
| 2039 |
+
sin(x) + cos(x)
|
| 2040 |
+
>>> hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify()
|
| 2041 |
+
log(x)
|
| 2042 |
+
|
| 2043 |
+
See Also
|
| 2044 |
+
========
|
| 2045 |
+
|
| 2046 |
+
to_hyper
|
| 2047 |
+
"""
|
| 2048 |
+
|
| 2049 |
+
# convert to hypergeometric first
|
| 2050 |
+
rep = self.to_hyper(as_list=True)
|
| 2051 |
+
sol = S.Zero
|
| 2052 |
+
|
| 2053 |
+
for i in rep:
|
| 2054 |
+
if len(i) == 1:
|
| 2055 |
+
sol += i[0]
|
| 2056 |
+
|
| 2057 |
+
elif len(i) == 2:
|
| 2058 |
+
sol += i[0] * _hyper_to_meijerg(i[1])
|
| 2059 |
+
|
| 2060 |
+
return sol
|
| 2061 |
+
|
| 2062 |
+
|
| 2063 |
+
def from_hyper(func, x0=0, evalf=False):
|
| 2064 |
+
r"""
|
| 2065 |
+
Converts a hypergeometric function to holonomic.
|
| 2066 |
+
``func`` is the Hypergeometric Function and ``x0`` is the point at
|
| 2067 |
+
which initial conditions are required.
|
| 2068 |
+
|
| 2069 |
+
Examples
|
| 2070 |
+
========
|
| 2071 |
+
|
| 2072 |
+
>>> from sympy.holonomic.holonomic import from_hyper
|
| 2073 |
+
>>> from sympy import symbols, hyper, S
|
| 2074 |
+
>>> x = symbols('x')
|
| 2075 |
+
>>> from_hyper(hyper([], [S(3)/2], x**2/4))
|
| 2076 |
+
HolonomicFunction((-x) + (2)*Dx + (x)*Dx**2, x, 1, [sinh(1), -sinh(1) + cosh(1)])
|
| 2077 |
+
"""
|
| 2078 |
+
|
| 2079 |
+
a = func.ap
|
| 2080 |
+
b = func.bq
|
| 2081 |
+
z = func.args[2]
|
| 2082 |
+
x = z.atoms(Symbol).pop()
|
| 2083 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 2084 |
+
|
| 2085 |
+
# generalized hypergeometric differential equation
|
| 2086 |
+
xDx = x*Dx
|
| 2087 |
+
r1 = 1
|
| 2088 |
+
for ai in a: # XXX gives sympify error if Mul is used with list of all factors
|
| 2089 |
+
r1 *= xDx + ai
|
| 2090 |
+
xDx_1 = xDx - 1
|
| 2091 |
+
# r2 = Mul(*([Dx] + [xDx_1 + bi for bi in b])) # XXX gives sympify error
|
| 2092 |
+
r2 = Dx
|
| 2093 |
+
for bi in b:
|
| 2094 |
+
r2 *= xDx_1 + bi
|
| 2095 |
+
sol = r1 - r2
|
| 2096 |
+
|
| 2097 |
+
simp = hyperexpand(func)
|
| 2098 |
+
|
| 2099 |
+
if simp in (Infinity, NegativeInfinity):
|
| 2100 |
+
return HolonomicFunction(sol, x).composition(z)
|
| 2101 |
+
|
| 2102 |
+
# if the function is known symbolically
|
| 2103 |
+
if not isinstance(simp, hyper):
|
| 2104 |
+
y0 = _find_conditions(simp, x, x0, sol.order, use_limit=False)
|
| 2105 |
+
while not y0:
|
| 2106 |
+
# if values don't exist at 0, then try to find initial
|
| 2107 |
+
# conditions at 1. If it doesn't exist at 1 too then
|
| 2108 |
+
# try 2 and so on.
|
| 2109 |
+
x0 += 1
|
| 2110 |
+
y0 = _find_conditions(simp, x, x0, sol.order, use_limit=False)
|
| 2111 |
+
|
| 2112 |
+
return HolonomicFunction(sol, x).composition(z, x0, y0)
|
| 2113 |
+
|
| 2114 |
+
if isinstance(simp, hyper):
|
| 2115 |
+
x0 = 1
|
| 2116 |
+
# use evalf if the function can't be simplified
|
| 2117 |
+
y0 = _find_conditions(simp, x, x0, sol.order, evalf, use_limit=False)
|
| 2118 |
+
while not y0:
|
| 2119 |
+
x0 += 1
|
| 2120 |
+
y0 = _find_conditions(simp, x, x0, sol.order, evalf, use_limit=False)
|
| 2121 |
+
return HolonomicFunction(sol, x).composition(z, x0, y0)
|
| 2122 |
+
|
| 2123 |
+
return HolonomicFunction(sol, x).composition(z)
|
| 2124 |
+
|
| 2125 |
+
|
| 2126 |
+
def from_meijerg(func, x0=0, evalf=False, initcond=True, domain=QQ):
|
| 2127 |
+
"""
|
| 2128 |
+
Converts a Meijer G-function to Holonomic.
|
| 2129 |
+
``func`` is the G-Function and ``x0`` is the point at
|
| 2130 |
+
which initial conditions are required.
|
| 2131 |
+
|
| 2132 |
+
Examples
|
| 2133 |
+
========
|
| 2134 |
+
|
| 2135 |
+
>>> from sympy.holonomic.holonomic import from_meijerg
|
| 2136 |
+
>>> from sympy import symbols, meijerg, S
|
| 2137 |
+
>>> x = symbols('x')
|
| 2138 |
+
>>> from_meijerg(meijerg(([], []), ([S(1)/2], [0]), x**2/4))
|
| 2139 |
+
HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1/sqrt(pi)])
|
| 2140 |
+
"""
|
| 2141 |
+
|
| 2142 |
+
a = func.ap
|
| 2143 |
+
b = func.bq
|
| 2144 |
+
n = len(func.an)
|
| 2145 |
+
m = len(func.bm)
|
| 2146 |
+
p = len(a)
|
| 2147 |
+
z = func.args[2]
|
| 2148 |
+
x = z.atoms(Symbol).pop()
|
| 2149 |
+
R, Dx = DifferentialOperators(domain.old_poly_ring(x), 'Dx')
|
| 2150 |
+
|
| 2151 |
+
# compute the differential equation satisfied by the
|
| 2152 |
+
# Meijer G-function.
|
| 2153 |
+
xDx = x*Dx
|
| 2154 |
+
xDx1 = xDx + 1
|
| 2155 |
+
r1 = x*(-1)**(m + n - p)
|
| 2156 |
+
for ai in a: # XXX gives sympify error if args given in list
|
| 2157 |
+
r1 *= xDx1 - ai
|
| 2158 |
+
# r2 = Mul(*[xDx - bi for bi in b]) # gives sympify error
|
| 2159 |
+
r2 = 1
|
| 2160 |
+
for bi in b:
|
| 2161 |
+
r2 *= xDx - bi
|
| 2162 |
+
sol = r1 - r2
|
| 2163 |
+
|
| 2164 |
+
if not initcond:
|
| 2165 |
+
return HolonomicFunction(sol, x).composition(z)
|
| 2166 |
+
|
| 2167 |
+
simp = hyperexpand(func)
|
| 2168 |
+
|
| 2169 |
+
if simp in (Infinity, NegativeInfinity):
|
| 2170 |
+
return HolonomicFunction(sol, x).composition(z)
|
| 2171 |
+
|
| 2172 |
+
# computing initial conditions
|
| 2173 |
+
if not isinstance(simp, meijerg):
|
| 2174 |
+
y0 = _find_conditions(simp, x, x0, sol.order, use_limit=False)
|
| 2175 |
+
while not y0:
|
| 2176 |
+
x0 += 1
|
| 2177 |
+
y0 = _find_conditions(simp, x, x0, sol.order, use_limit=False)
|
| 2178 |
+
|
| 2179 |
+
return HolonomicFunction(sol, x).composition(z, x0, y0)
|
| 2180 |
+
|
| 2181 |
+
if isinstance(simp, meijerg):
|
| 2182 |
+
x0 = 1
|
| 2183 |
+
y0 = _find_conditions(simp, x, x0, sol.order, evalf, use_limit=False)
|
| 2184 |
+
while not y0:
|
| 2185 |
+
x0 += 1
|
| 2186 |
+
y0 = _find_conditions(simp, x, x0, sol.order, evalf, use_limit=False)
|
| 2187 |
+
|
| 2188 |
+
return HolonomicFunction(sol, x).composition(z, x0, y0)
|
| 2189 |
+
|
| 2190 |
+
return HolonomicFunction(sol, x).composition(z)
|
| 2191 |
+
|
| 2192 |
+
|
| 2193 |
+
x_1 = Dummy('x_1')
|
| 2194 |
+
_lookup_table = None
|
| 2195 |
+
domain_for_table = None
|
| 2196 |
+
from sympy.integrals.meijerint import _mytype
|
| 2197 |
+
|
| 2198 |
+
|
| 2199 |
+
def expr_to_holonomic(func, x=None, x0=0, y0=None, lenics=None, domain=None, initcond=True):
|
| 2200 |
+
"""
|
| 2201 |
+
Converts a function or an expression to a holonomic function.
|
| 2202 |
+
|
| 2203 |
+
Parameters
|
| 2204 |
+
==========
|
| 2205 |
+
|
| 2206 |
+
func:
|
| 2207 |
+
The expression to be converted.
|
| 2208 |
+
x:
|
| 2209 |
+
variable for the function.
|
| 2210 |
+
x0:
|
| 2211 |
+
point at which initial condition must be computed.
|
| 2212 |
+
y0:
|
| 2213 |
+
One can optionally provide initial condition if the method
|
| 2214 |
+
is not able to do it automatically.
|
| 2215 |
+
lenics:
|
| 2216 |
+
Number of terms in the initial condition. By default it is
|
| 2217 |
+
equal to the order of the annihilator.
|
| 2218 |
+
domain:
|
| 2219 |
+
Ground domain for the polynomials in ``x`` appearing as coefficients
|
| 2220 |
+
in the annihilator.
|
| 2221 |
+
initcond:
|
| 2222 |
+
Set it false if you do not want the initial conditions to be computed.
|
| 2223 |
+
|
| 2224 |
+
Examples
|
| 2225 |
+
========
|
| 2226 |
+
|
| 2227 |
+
>>> from sympy.holonomic.holonomic import expr_to_holonomic
|
| 2228 |
+
>>> from sympy import sin, exp, symbols
|
| 2229 |
+
>>> x = symbols('x')
|
| 2230 |
+
>>> expr_to_holonomic(sin(x))
|
| 2231 |
+
HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1])
|
| 2232 |
+
>>> expr_to_holonomic(exp(x))
|
| 2233 |
+
HolonomicFunction((-1) + (1)*Dx, x, 0, [1])
|
| 2234 |
+
|
| 2235 |
+
See Also
|
| 2236 |
+
========
|
| 2237 |
+
|
| 2238 |
+
sympy.integrals.meijerint._rewrite1, _convert_poly_rat_alg, _create_table
|
| 2239 |
+
"""
|
| 2240 |
+
func = sympify(func)
|
| 2241 |
+
syms = func.free_symbols
|
| 2242 |
+
|
| 2243 |
+
if not x:
|
| 2244 |
+
if len(syms) == 1:
|
| 2245 |
+
x= syms.pop()
|
| 2246 |
+
else:
|
| 2247 |
+
raise ValueError("Specify the variable for the function")
|
| 2248 |
+
elif x in syms:
|
| 2249 |
+
syms.remove(x)
|
| 2250 |
+
|
| 2251 |
+
extra_syms = list(syms)
|
| 2252 |
+
|
| 2253 |
+
if domain is None:
|
| 2254 |
+
if func.has(Float):
|
| 2255 |
+
domain = RR
|
| 2256 |
+
else:
|
| 2257 |
+
domain = QQ
|
| 2258 |
+
if len(extra_syms) != 0:
|
| 2259 |
+
domain = domain[extra_syms].get_field()
|
| 2260 |
+
|
| 2261 |
+
# try to convert if the function is polynomial or rational
|
| 2262 |
+
solpoly = _convert_poly_rat_alg(func, x, x0=x0, y0=y0, lenics=lenics, domain=domain, initcond=initcond)
|
| 2263 |
+
if solpoly:
|
| 2264 |
+
return solpoly
|
| 2265 |
+
|
| 2266 |
+
# create the lookup table
|
| 2267 |
+
global _lookup_table, domain_for_table
|
| 2268 |
+
if not _lookup_table:
|
| 2269 |
+
domain_for_table = domain
|
| 2270 |
+
_lookup_table = {}
|
| 2271 |
+
_create_table(_lookup_table, domain=domain)
|
| 2272 |
+
elif domain != domain_for_table:
|
| 2273 |
+
domain_for_table = domain
|
| 2274 |
+
_lookup_table = {}
|
| 2275 |
+
_create_table(_lookup_table, domain=domain)
|
| 2276 |
+
|
| 2277 |
+
# use the table directly to convert to Holonomic
|
| 2278 |
+
if func.is_Function:
|
| 2279 |
+
f = func.subs(x, x_1)
|
| 2280 |
+
t = _mytype(f, x_1)
|
| 2281 |
+
if t in _lookup_table:
|
| 2282 |
+
l = _lookup_table[t]
|
| 2283 |
+
sol = l[0][1].change_x(x)
|
| 2284 |
+
else:
|
| 2285 |
+
sol = _convert_meijerint(func, x, initcond=False, domain=domain)
|
| 2286 |
+
if not sol:
|
| 2287 |
+
raise NotImplementedError
|
| 2288 |
+
if y0:
|
| 2289 |
+
sol.y0 = y0
|
| 2290 |
+
if y0 or not initcond:
|
| 2291 |
+
sol.x0 = x0
|
| 2292 |
+
return sol
|
| 2293 |
+
if not lenics:
|
| 2294 |
+
lenics = sol.annihilator.order
|
| 2295 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
| 2296 |
+
while not _y0:
|
| 2297 |
+
x0 += 1
|
| 2298 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
| 2299 |
+
return HolonomicFunction(sol.annihilator, x, x0, _y0)
|
| 2300 |
+
|
| 2301 |
+
if y0 or not initcond:
|
| 2302 |
+
sol = sol.composition(func.args[0])
|
| 2303 |
+
if y0:
|
| 2304 |
+
sol.y0 = y0
|
| 2305 |
+
sol.x0 = x0
|
| 2306 |
+
return sol
|
| 2307 |
+
if not lenics:
|
| 2308 |
+
lenics = sol.annihilator.order
|
| 2309 |
+
|
| 2310 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
| 2311 |
+
while not _y0:
|
| 2312 |
+
x0 += 1
|
| 2313 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
| 2314 |
+
return sol.composition(func.args[0], x0, _y0)
|
| 2315 |
+
|
| 2316 |
+
# iterate through the expression recursively
|
| 2317 |
+
args = func.args
|
| 2318 |
+
f = func.func
|
| 2319 |
+
sol = expr_to_holonomic(args[0], x=x, initcond=False, domain=domain)
|
| 2320 |
+
|
| 2321 |
+
if f is Add:
|
| 2322 |
+
for i in range(1, len(args)):
|
| 2323 |
+
sol += expr_to_holonomic(args[i], x=x, initcond=False, domain=domain)
|
| 2324 |
+
|
| 2325 |
+
elif f is Mul:
|
| 2326 |
+
for i in range(1, len(args)):
|
| 2327 |
+
sol *= expr_to_holonomic(args[i], x=x, initcond=False, domain=domain)
|
| 2328 |
+
|
| 2329 |
+
elif f is Pow:
|
| 2330 |
+
sol = sol**args[1]
|
| 2331 |
+
sol.x0 = x0
|
| 2332 |
+
if not sol:
|
| 2333 |
+
raise NotImplementedError
|
| 2334 |
+
if y0:
|
| 2335 |
+
sol.y0 = y0
|
| 2336 |
+
if y0 or not initcond:
|
| 2337 |
+
return sol
|
| 2338 |
+
if sol.y0:
|
| 2339 |
+
return sol
|
| 2340 |
+
if not lenics:
|
| 2341 |
+
lenics = sol.annihilator.order
|
| 2342 |
+
if sol.annihilator.is_singular(x0):
|
| 2343 |
+
r = sol._indicial()
|
| 2344 |
+
l = list(r)
|
| 2345 |
+
if len(r) == 1 and r[l[0]] == S.One:
|
| 2346 |
+
r = l[0]
|
| 2347 |
+
g = func / (x - x0)**r
|
| 2348 |
+
singular_ics = _find_conditions(g, x, x0, lenics)
|
| 2349 |
+
singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)]
|
| 2350 |
+
y0 = {r:singular_ics}
|
| 2351 |
+
return HolonomicFunction(sol.annihilator, x, x0, y0)
|
| 2352 |
+
|
| 2353 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
| 2354 |
+
while not _y0:
|
| 2355 |
+
x0 += 1
|
| 2356 |
+
_y0 = _find_conditions(func, x, x0, lenics)
|
| 2357 |
+
|
| 2358 |
+
return HolonomicFunction(sol.annihilator, x, x0, _y0)
|
| 2359 |
+
|
| 2360 |
+
|
| 2361 |
+
## Some helper functions ##
|
| 2362 |
+
|
| 2363 |
+
def _normalize(list_of, parent, negative=True):
|
| 2364 |
+
"""
|
| 2365 |
+
Normalize a given annihilator
|
| 2366 |
+
"""
|
| 2367 |
+
|
| 2368 |
+
num = []
|
| 2369 |
+
denom = []
|
| 2370 |
+
base = parent.base
|
| 2371 |
+
K = base.get_field()
|
| 2372 |
+
lcm_denom = base.from_sympy(S.One)
|
| 2373 |
+
list_of_coeff = []
|
| 2374 |
+
|
| 2375 |
+
# convert polynomials to the elements of associated
|
| 2376 |
+
# fraction field
|
| 2377 |
+
for i, j in enumerate(list_of):
|
| 2378 |
+
if isinstance(j, base.dtype):
|
| 2379 |
+
list_of_coeff.append(K.new(j.to_list()))
|
| 2380 |
+
elif not isinstance(j, K.dtype):
|
| 2381 |
+
list_of_coeff.append(K.from_sympy(sympify(j)))
|
| 2382 |
+
else:
|
| 2383 |
+
list_of_coeff.append(j)
|
| 2384 |
+
|
| 2385 |
+
# corresponding numerators of the sequence of polynomials
|
| 2386 |
+
num.append(list_of_coeff[i].numer())
|
| 2387 |
+
|
| 2388 |
+
# corresponding denominators
|
| 2389 |
+
denom.append(list_of_coeff[i].denom())
|
| 2390 |
+
|
| 2391 |
+
# lcm of denominators in the coefficients
|
| 2392 |
+
for i in denom:
|
| 2393 |
+
lcm_denom = i.lcm(lcm_denom)
|
| 2394 |
+
|
| 2395 |
+
if negative:
|
| 2396 |
+
lcm_denom = -lcm_denom
|
| 2397 |
+
|
| 2398 |
+
lcm_denom = K.new(lcm_denom.to_list())
|
| 2399 |
+
|
| 2400 |
+
# multiply the coefficients with lcm
|
| 2401 |
+
for i, j in enumerate(list_of_coeff):
|
| 2402 |
+
list_of_coeff[i] = j * lcm_denom
|
| 2403 |
+
|
| 2404 |
+
gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).to_list())
|
| 2405 |
+
|
| 2406 |
+
# gcd of numerators in the coefficients
|
| 2407 |
+
for i in num:
|
| 2408 |
+
gcd_numer = i.gcd(gcd_numer)
|
| 2409 |
+
|
| 2410 |
+
gcd_numer = K.new(gcd_numer.to_list())
|
| 2411 |
+
|
| 2412 |
+
# divide all the coefficients by the gcd
|
| 2413 |
+
for i, j in enumerate(list_of_coeff):
|
| 2414 |
+
frac_ans = j / gcd_numer
|
| 2415 |
+
list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).to_list())
|
| 2416 |
+
|
| 2417 |
+
return DifferentialOperator(list_of_coeff, parent)
|
| 2418 |
+
|
| 2419 |
+
|
| 2420 |
+
def _derivate_diff_eq(listofpoly, K):
|
| 2421 |
+
"""
|
| 2422 |
+
Let a differential equation a0(x)y(x) + a1(x)y'(x) + ... = 0
|
| 2423 |
+
where a0, a1,... are polynomials or rational functions. The function
|
| 2424 |
+
returns b0, b1, b2... such that the differential equation
|
| 2425 |
+
b0(x)y(x) + b1(x)y'(x) +... = 0 is formed after differentiating the
|
| 2426 |
+
former equation.
|
| 2427 |
+
"""
|
| 2428 |
+
|
| 2429 |
+
sol = []
|
| 2430 |
+
a = len(listofpoly) - 1
|
| 2431 |
+
sol.append(DMFdiff(listofpoly[0], K))
|
| 2432 |
+
|
| 2433 |
+
for i, j in enumerate(listofpoly[1:]):
|
| 2434 |
+
sol.append(DMFdiff(j, K) + listofpoly[i])
|
| 2435 |
+
|
| 2436 |
+
sol.append(listofpoly[a])
|
| 2437 |
+
return sol
|
| 2438 |
+
|
| 2439 |
+
|
| 2440 |
+
def _hyper_to_meijerg(func):
|
| 2441 |
+
"""
|
| 2442 |
+
Converts a `hyper` to meijerg.
|
| 2443 |
+
"""
|
| 2444 |
+
ap = func.ap
|
| 2445 |
+
bq = func.bq
|
| 2446 |
+
|
| 2447 |
+
if any(i <= 0 and int(i) == i for i in ap):
|
| 2448 |
+
return hyperexpand(func)
|
| 2449 |
+
|
| 2450 |
+
z = func.args[2]
|
| 2451 |
+
|
| 2452 |
+
# parameters of the `meijerg` function.
|
| 2453 |
+
an = (1 - i for i in ap)
|
| 2454 |
+
anp = ()
|
| 2455 |
+
bm = (S.Zero, )
|
| 2456 |
+
bmq = (1 - i for i in bq)
|
| 2457 |
+
|
| 2458 |
+
k = S.One
|
| 2459 |
+
|
| 2460 |
+
for i in bq:
|
| 2461 |
+
k = k * gamma(i)
|
| 2462 |
+
|
| 2463 |
+
for i in ap:
|
| 2464 |
+
k = k / gamma(i)
|
| 2465 |
+
|
| 2466 |
+
return k * meijerg(an, anp, bm, bmq, -z)
|
| 2467 |
+
|
| 2468 |
+
|
| 2469 |
+
def _add_lists(list1, list2):
|
| 2470 |
+
"""Takes polynomial sequences of two annihilators a and b and returns
|
| 2471 |
+
the list of polynomials of sum of a and b.
|
| 2472 |
+
"""
|
| 2473 |
+
if len(list1) <= len(list2):
|
| 2474 |
+
sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):]
|
| 2475 |
+
else:
|
| 2476 |
+
sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):]
|
| 2477 |
+
return sol
|
| 2478 |
+
|
| 2479 |
+
|
| 2480 |
+
def _extend_y0(Holonomic, n):
|
| 2481 |
+
"""
|
| 2482 |
+
Tries to find more initial conditions by substituting the initial
|
| 2483 |
+
value point in the differential equation.
|
| 2484 |
+
"""
|
| 2485 |
+
|
| 2486 |
+
if Holonomic.annihilator.is_singular(Holonomic.x0) or Holonomic.is_singularics() == True:
|
| 2487 |
+
return Holonomic.y0
|
| 2488 |
+
|
| 2489 |
+
annihilator = Holonomic.annihilator
|
| 2490 |
+
a = annihilator.order
|
| 2491 |
+
|
| 2492 |
+
listofpoly = []
|
| 2493 |
+
|
| 2494 |
+
y0 = Holonomic.y0
|
| 2495 |
+
R = annihilator.parent.base
|
| 2496 |
+
K = R.get_field()
|
| 2497 |
+
|
| 2498 |
+
for j in annihilator.listofpoly:
|
| 2499 |
+
if isinstance(j, annihilator.parent.base.dtype):
|
| 2500 |
+
listofpoly.append(K.new(j.to_list()))
|
| 2501 |
+
|
| 2502 |
+
if len(y0) < a or n <= len(y0):
|
| 2503 |
+
return y0
|
| 2504 |
+
list_red = [-listofpoly[i] / listofpoly[a]
|
| 2505 |
+
for i in range(a)]
|
| 2506 |
+
y1 = y0[:min(len(y0), a)]
|
| 2507 |
+
for _ in range(n - a):
|
| 2508 |
+
sol = 0
|
| 2509 |
+
for a, b in zip(y1, list_red):
|
| 2510 |
+
r = DMFsubs(b, Holonomic.x0)
|
| 2511 |
+
if not getattr(r, 'is_finite', True):
|
| 2512 |
+
return y0
|
| 2513 |
+
if isinstance(r, (PolyElement, FracElement)):
|
| 2514 |
+
r = r.as_expr()
|
| 2515 |
+
sol += a * r
|
| 2516 |
+
y1.append(sol)
|
| 2517 |
+
list_red = _derivate_diff_eq(list_red, K)
|
| 2518 |
+
return y0 + y1[len(y0):]
|
| 2519 |
+
|
| 2520 |
+
|
| 2521 |
+
def DMFdiff(frac, K):
|
| 2522 |
+
# differentiate a DMF object represented as p/q
|
| 2523 |
+
if not isinstance(frac, DMF):
|
| 2524 |
+
return frac.diff()
|
| 2525 |
+
|
| 2526 |
+
p = K.numer(frac)
|
| 2527 |
+
q = K.denom(frac)
|
| 2528 |
+
sol_num = - p * q.diff() + q * p.diff()
|
| 2529 |
+
sol_denom = q**2
|
| 2530 |
+
return K((sol_num.to_list(), sol_denom.to_list()))
|
| 2531 |
+
|
| 2532 |
+
|
| 2533 |
+
def DMFsubs(frac, x0, mpm=False):
|
| 2534 |
+
# substitute the point x0 in DMF object of the form p/q
|
| 2535 |
+
if not isinstance(frac, DMF):
|
| 2536 |
+
return frac
|
| 2537 |
+
|
| 2538 |
+
p = frac.num
|
| 2539 |
+
q = frac.den
|
| 2540 |
+
sol_p = S.Zero
|
| 2541 |
+
sol_q = S.Zero
|
| 2542 |
+
|
| 2543 |
+
if mpm:
|
| 2544 |
+
from mpmath import mp
|
| 2545 |
+
|
| 2546 |
+
for i, j in enumerate(reversed(p)):
|
| 2547 |
+
if mpm:
|
| 2548 |
+
j = sympify(j)._to_mpmath(mp.prec)
|
| 2549 |
+
sol_p += j * x0**i
|
| 2550 |
+
|
| 2551 |
+
for i, j in enumerate(reversed(q)):
|
| 2552 |
+
if mpm:
|
| 2553 |
+
j = sympify(j)._to_mpmath(mp.prec)
|
| 2554 |
+
sol_q += j * x0**i
|
| 2555 |
+
|
| 2556 |
+
if isinstance(sol_p, (PolyElement, FracElement)):
|
| 2557 |
+
sol_p = sol_p.as_expr()
|
| 2558 |
+
if isinstance(sol_q, (PolyElement, FracElement)):
|
| 2559 |
+
sol_q = sol_q.as_expr()
|
| 2560 |
+
|
| 2561 |
+
return sol_p / sol_q
|
| 2562 |
+
|
| 2563 |
+
|
| 2564 |
+
def _convert_poly_rat_alg(func, x, x0=0, y0=None, lenics=None, domain=QQ, initcond=True):
|
| 2565 |
+
"""
|
| 2566 |
+
Converts polynomials, rationals and algebraic functions to holonomic.
|
| 2567 |
+
"""
|
| 2568 |
+
|
| 2569 |
+
ispoly = func.is_polynomial()
|
| 2570 |
+
if not ispoly:
|
| 2571 |
+
israt = func.is_rational_function()
|
| 2572 |
+
else:
|
| 2573 |
+
israt = True
|
| 2574 |
+
|
| 2575 |
+
if not (ispoly or israt):
|
| 2576 |
+
basepoly, ratexp = func.as_base_exp()
|
| 2577 |
+
if basepoly.is_polynomial() and ratexp.is_Number:
|
| 2578 |
+
if isinstance(ratexp, Float):
|
| 2579 |
+
ratexp = nsimplify(ratexp)
|
| 2580 |
+
m, n = ratexp.p, ratexp.q
|
| 2581 |
+
is_alg = True
|
| 2582 |
+
else:
|
| 2583 |
+
is_alg = False
|
| 2584 |
+
else:
|
| 2585 |
+
is_alg = True
|
| 2586 |
+
|
| 2587 |
+
if not (ispoly or israt or is_alg):
|
| 2588 |
+
return None
|
| 2589 |
+
|
| 2590 |
+
R = domain.old_poly_ring(x)
|
| 2591 |
+
_, Dx = DifferentialOperators(R, 'Dx')
|
| 2592 |
+
|
| 2593 |
+
# if the function is constant
|
| 2594 |
+
if not func.has(x):
|
| 2595 |
+
return HolonomicFunction(Dx, x, 0, [func])
|
| 2596 |
+
|
| 2597 |
+
if ispoly:
|
| 2598 |
+
# differential equation satisfied by polynomial
|
| 2599 |
+
sol = func * Dx - func.diff(x)
|
| 2600 |
+
sol = _normalize(sol.listofpoly, sol.parent, negative=False)
|
| 2601 |
+
is_singular = sol.is_singular(x0)
|
| 2602 |
+
|
| 2603 |
+
# try to compute the conditions for singular points
|
| 2604 |
+
if y0 is None and x0 == 0 and is_singular:
|
| 2605 |
+
rep = R.from_sympy(func).to_list()
|
| 2606 |
+
for i, j in enumerate(reversed(rep)):
|
| 2607 |
+
if j == 0:
|
| 2608 |
+
continue
|
| 2609 |
+
coeff = list(reversed(rep))[i:]
|
| 2610 |
+
indicial = i
|
| 2611 |
+
break
|
| 2612 |
+
for i, j in enumerate(coeff):
|
| 2613 |
+
if isinstance(j, (PolyElement, FracElement)):
|
| 2614 |
+
coeff[i] = j.as_expr()
|
| 2615 |
+
y0 = {indicial: S(coeff)}
|
| 2616 |
+
|
| 2617 |
+
elif israt:
|
| 2618 |
+
p, q = func.as_numer_denom()
|
| 2619 |
+
# differential equation satisfied by rational
|
| 2620 |
+
sol = p * q * Dx + p * q.diff(x) - q * p.diff(x)
|
| 2621 |
+
sol = _normalize(sol.listofpoly, sol.parent, negative=False)
|
| 2622 |
+
|
| 2623 |
+
elif is_alg:
|
| 2624 |
+
sol = n * (x / m) * Dx - 1
|
| 2625 |
+
sol = HolonomicFunction(sol, x).composition(basepoly).annihilator
|
| 2626 |
+
is_singular = sol.is_singular(x0)
|
| 2627 |
+
|
| 2628 |
+
# try to compute the conditions for singular points
|
| 2629 |
+
if y0 is None and x0 == 0 and is_singular and \
|
| 2630 |
+
(lenics is None or lenics <= 1):
|
| 2631 |
+
rep = R.from_sympy(basepoly).to_list()
|
| 2632 |
+
for i, j in enumerate(reversed(rep)):
|
| 2633 |
+
if j == 0:
|
| 2634 |
+
continue
|
| 2635 |
+
if isinstance(j, (PolyElement, FracElement)):
|
| 2636 |
+
j = j.as_expr()
|
| 2637 |
+
|
| 2638 |
+
coeff = S(j)**ratexp
|
| 2639 |
+
indicial = S(i) * ratexp
|
| 2640 |
+
break
|
| 2641 |
+
if isinstance(coeff, (PolyElement, FracElement)):
|
| 2642 |
+
coeff = coeff.as_expr()
|
| 2643 |
+
y0 = {indicial: S([coeff])}
|
| 2644 |
+
|
| 2645 |
+
if y0 or not initcond:
|
| 2646 |
+
return HolonomicFunction(sol, x, x0, y0)
|
| 2647 |
+
|
| 2648 |
+
if not lenics:
|
| 2649 |
+
lenics = sol.order
|
| 2650 |
+
|
| 2651 |
+
if sol.is_singular(x0):
|
| 2652 |
+
r = HolonomicFunction(sol, x, x0)._indicial()
|
| 2653 |
+
l = list(r)
|
| 2654 |
+
if len(r) == 1 and r[l[0]] == S.One:
|
| 2655 |
+
r = l[0]
|
| 2656 |
+
g = func / (x - x0)**r
|
| 2657 |
+
singular_ics = _find_conditions(g, x, x0, lenics)
|
| 2658 |
+
singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)]
|
| 2659 |
+
y0 = {r:singular_ics}
|
| 2660 |
+
return HolonomicFunction(sol, x, x0, y0)
|
| 2661 |
+
|
| 2662 |
+
y0 = _find_conditions(func, x, x0, lenics)
|
| 2663 |
+
while not y0:
|
| 2664 |
+
x0 += 1
|
| 2665 |
+
y0 = _find_conditions(func, x, x0, lenics)
|
| 2666 |
+
|
| 2667 |
+
return HolonomicFunction(sol, x, x0, y0)
|
| 2668 |
+
|
| 2669 |
+
|
| 2670 |
+
def _convert_meijerint(func, x, initcond=True, domain=QQ):
|
| 2671 |
+
args = meijerint._rewrite1(func, x)
|
| 2672 |
+
|
| 2673 |
+
if args:
|
| 2674 |
+
fac, po, g, _ = args
|
| 2675 |
+
else:
|
| 2676 |
+
return None
|
| 2677 |
+
|
| 2678 |
+
# lists for sum of meijerg functions
|
| 2679 |
+
fac_list = [fac * i[0] for i in g]
|
| 2680 |
+
t = po.as_base_exp()
|
| 2681 |
+
s = t[1] if t[0] == x else S.Zero
|
| 2682 |
+
po_list = [s + i[1] for i in g]
|
| 2683 |
+
G_list = [i[2] for i in g]
|
| 2684 |
+
|
| 2685 |
+
# finds meijerg representation of x**s * meijerg(a1 ... ap, b1 ... bq, z)
|
| 2686 |
+
def _shift(func, s):
|
| 2687 |
+
z = func.args[-1]
|
| 2688 |
+
if z.has(I):
|
| 2689 |
+
z = z.subs(exp_polar, exp)
|
| 2690 |
+
|
| 2691 |
+
d = z.collect(x, evaluate=False)
|
| 2692 |
+
b = list(d)[0]
|
| 2693 |
+
a = d[b]
|
| 2694 |
+
|
| 2695 |
+
t = b.as_base_exp()
|
| 2696 |
+
b = t[1] if t[0] == x else S.Zero
|
| 2697 |
+
r = s / b
|
| 2698 |
+
an = (i + r for i in func.args[0][0])
|
| 2699 |
+
ap = (i + r for i in func.args[0][1])
|
| 2700 |
+
bm = (i + r for i in func.args[1][0])
|
| 2701 |
+
bq = (i + r for i in func.args[1][1])
|
| 2702 |
+
|
| 2703 |
+
return a**-r, meijerg((an, ap), (bm, bq), z)
|
| 2704 |
+
|
| 2705 |
+
coeff, m = _shift(G_list[0], po_list[0])
|
| 2706 |
+
sol = fac_list[0] * coeff * from_meijerg(m, initcond=initcond, domain=domain)
|
| 2707 |
+
|
| 2708 |
+
# add all the meijerg functions after converting to holonomic
|
| 2709 |
+
for i in range(1, len(G_list)):
|
| 2710 |
+
coeff, m = _shift(G_list[i], po_list[i])
|
| 2711 |
+
sol += fac_list[i] * coeff * from_meijerg(m, initcond=initcond, domain=domain)
|
| 2712 |
+
|
| 2713 |
+
return sol
|
| 2714 |
+
|
| 2715 |
+
|
| 2716 |
+
def _create_table(table, domain=QQ):
|
| 2717 |
+
"""
|
| 2718 |
+
Creates the look-up table. For a similar implementation
|
| 2719 |
+
see meijerint._create_lookup_table.
|
| 2720 |
+
"""
|
| 2721 |
+
|
| 2722 |
+
def add(formula, annihilator, arg, x0=0, y0=()):
|
| 2723 |
+
"""
|
| 2724 |
+
Adds a formula in the dictionary
|
| 2725 |
+
"""
|
| 2726 |
+
table.setdefault(_mytype(formula, x_1), []).append((formula,
|
| 2727 |
+
HolonomicFunction(annihilator, arg, x0, y0)))
|
| 2728 |
+
|
| 2729 |
+
R = domain.old_poly_ring(x_1)
|
| 2730 |
+
_, Dx = DifferentialOperators(R, 'Dx')
|
| 2731 |
+
|
| 2732 |
+
# add some basic functions
|
| 2733 |
+
add(sin(x_1), Dx**2 + 1, x_1, 0, [0, 1])
|
| 2734 |
+
add(cos(x_1), Dx**2 + 1, x_1, 0, [1, 0])
|
| 2735 |
+
add(exp(x_1), Dx - 1, x_1, 0, 1)
|
| 2736 |
+
add(log(x_1), Dx + x_1*Dx**2, x_1, 1, [0, 1])
|
| 2737 |
+
|
| 2738 |
+
add(erf(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)])
|
| 2739 |
+
add(erfc(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [1, -2/sqrt(pi)])
|
| 2740 |
+
add(erfi(x_1), -2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)])
|
| 2741 |
+
|
| 2742 |
+
add(sinh(x_1), Dx**2 - 1, x_1, 0, [0, 1])
|
| 2743 |
+
add(cosh(x_1), Dx**2 - 1, x_1, 0, [1, 0])
|
| 2744 |
+
|
| 2745 |
+
add(sinc(x_1), x_1 + 2*Dx + x_1*Dx**2, x_1)
|
| 2746 |
+
|
| 2747 |
+
add(Si(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
|
| 2748 |
+
add(Ci(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
|
| 2749 |
+
|
| 2750 |
+
add(Shi(x_1), -x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1)
|
| 2751 |
+
|
| 2752 |
+
|
| 2753 |
+
def _find_conditions(func, x, x0, order, evalf=False, use_limit=True):
|
| 2754 |
+
y0 = []
|
| 2755 |
+
for _ in range(order):
|
| 2756 |
+
val = func.subs(x, x0)
|
| 2757 |
+
if evalf:
|
| 2758 |
+
val = val.evalf()
|
| 2759 |
+
if use_limit and isinstance(val, NaN):
|
| 2760 |
+
val = limit(func, x, x0)
|
| 2761 |
+
if val.is_finite is False or isinstance(val, NaN):
|
| 2762 |
+
return None
|
| 2763 |
+
y0.append(val)
|
| 2764 |
+
func = func.diff(x)
|
| 2765 |
+
return y0
|
.venv/lib/python3.12/site-packages/sympy/holonomic/holonomicerrors.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Common Exceptions for `holonomic` module. """
|
| 2 |
+
|
| 3 |
+
class BaseHolonomicError(Exception):
|
| 4 |
+
|
| 5 |
+
def new(self, *args):
|
| 6 |
+
raise NotImplementedError("abstract base class")
|
| 7 |
+
|
| 8 |
+
class NotPowerSeriesError(BaseHolonomicError):
|
| 9 |
+
|
| 10 |
+
def __init__(self, holonomic, x0):
|
| 11 |
+
self.holonomic = holonomic
|
| 12 |
+
self.x0 = x0
|
| 13 |
+
|
| 14 |
+
def __str__(self):
|
| 15 |
+
s = 'A Power Series does not exists for '
|
| 16 |
+
s += str(self.holonomic)
|
| 17 |
+
s += ' about %s.' %self.x0
|
| 18 |
+
return s
|
| 19 |
+
|
| 20 |
+
class NotHolonomicError(BaseHolonomicError):
|
| 21 |
+
|
| 22 |
+
def __init__(self, m):
|
| 23 |
+
self.m = m
|
| 24 |
+
|
| 25 |
+
def __str__(self):
|
| 26 |
+
return self.m
|
| 27 |
+
|
| 28 |
+
class SingularityError(BaseHolonomicError):
|
| 29 |
+
|
| 30 |
+
def __init__(self, holonomic, x0):
|
| 31 |
+
self.holonomic = holonomic
|
| 32 |
+
self.x0 = x0
|
| 33 |
+
|
| 34 |
+
def __str__(self):
|
| 35 |
+
s = str(self.holonomic)
|
| 36 |
+
s += ' has a singularity at %s.' %self.x0
|
| 37 |
+
return s
|
| 38 |
+
|
| 39 |
+
class NotHyperSeriesError(BaseHolonomicError):
|
| 40 |
+
|
| 41 |
+
def __init__(self, holonomic, x0):
|
| 42 |
+
self.holonomic = holonomic
|
| 43 |
+
self.x0 = x0
|
| 44 |
+
|
| 45 |
+
def __str__(self):
|
| 46 |
+
s = 'Power series expansion of '
|
| 47 |
+
s += str(self.holonomic)
|
| 48 |
+
s += ' about %s is not hypergeometric' %self.x0
|
| 49 |
+
return s
|
.venv/lib/python3.12/site-packages/sympy/holonomic/numerical.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Numerical Methods for Holonomic Functions"""
|
| 2 |
+
|
| 3 |
+
from sympy.core.sympify import sympify
|
| 4 |
+
from sympy.holonomic.holonomic import DMFsubs
|
| 5 |
+
|
| 6 |
+
from mpmath import mp
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _evalf(func, points, derivatives=False, method='RK4'):
|
| 10 |
+
"""
|
| 11 |
+
Numerical methods for numerical integration along a given set of
|
| 12 |
+
points in the complex plane.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
ann = func.annihilator
|
| 16 |
+
a = ann.order
|
| 17 |
+
R = ann.parent.base
|
| 18 |
+
K = R.get_field()
|
| 19 |
+
|
| 20 |
+
if method == 'Euler':
|
| 21 |
+
meth = _euler
|
| 22 |
+
else:
|
| 23 |
+
meth = _rk4
|
| 24 |
+
|
| 25 |
+
dmf = [K.new(j.to_list()) for j in ann.listofpoly]
|
| 26 |
+
red = [-dmf[i] / dmf[a] for i in range(a)]
|
| 27 |
+
|
| 28 |
+
y0 = func.y0
|
| 29 |
+
if len(y0) < a:
|
| 30 |
+
raise TypeError("Not Enough Initial Conditions")
|
| 31 |
+
x0 = func.x0
|
| 32 |
+
sol = [meth(red, x0, points[0], y0, a)]
|
| 33 |
+
|
| 34 |
+
for i, j in enumerate(points[1:]):
|
| 35 |
+
sol.append(meth(red, points[i], j, sol[-1], a))
|
| 36 |
+
|
| 37 |
+
if not derivatives:
|
| 38 |
+
return [sympify(i[0]) for i in sol]
|
| 39 |
+
else:
|
| 40 |
+
return sympify(sol)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _euler(red, x0, x1, y0, a):
|
| 44 |
+
"""
|
| 45 |
+
Euler's method for numerical integration.
|
| 46 |
+
From x0 to x1 with initial values given at x0 as vector y0.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
A = sympify(x0)._to_mpmath(mp.prec)
|
| 50 |
+
B = sympify(x1)._to_mpmath(mp.prec)
|
| 51 |
+
y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
|
| 52 |
+
h = B - A
|
| 53 |
+
f_0 = y_0[1:]
|
| 54 |
+
f_0_n = 0
|
| 55 |
+
|
| 56 |
+
for i in range(a):
|
| 57 |
+
f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
|
| 58 |
+
f_0.append(f_0_n)
|
| 59 |
+
|
| 60 |
+
return [y_0[i] + h * f_0[i] for i in range(a)]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _rk4(red, x0, x1, y0, a):
|
| 64 |
+
"""
|
| 65 |
+
Runge-Kutta 4th order numerical method.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
A = sympify(x0)._to_mpmath(mp.prec)
|
| 69 |
+
B = sympify(x1)._to_mpmath(mp.prec)
|
| 70 |
+
y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
|
| 71 |
+
h = B - A
|
| 72 |
+
|
| 73 |
+
f_0_n = 0
|
| 74 |
+
f_1_n = 0
|
| 75 |
+
f_2_n = 0
|
| 76 |
+
f_3_n = 0
|
| 77 |
+
|
| 78 |
+
f_0 = y_0[1:]
|
| 79 |
+
for i in range(a):
|
| 80 |
+
f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
|
| 81 |
+
f_0.append(f_0_n)
|
| 82 |
+
|
| 83 |
+
f_1 = [y_0[i] + f_0[i]*h/2 for i in range(1, a)]
|
| 84 |
+
for i in range(a):
|
| 85 |
+
f_1_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2)
|
| 86 |
+
f_1.append(f_1_n)
|
| 87 |
+
|
| 88 |
+
f_2 = [y_0[i] + f_1[i]*h/2 for i in range(1, a)]
|
| 89 |
+
for i in range(a):
|
| 90 |
+
f_2_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2)
|
| 91 |
+
f_2.append(f_2_n)
|
| 92 |
+
|
| 93 |
+
f_3 = [y_0[i] + f_2[i]*h for i in range(1, a)]
|
| 94 |
+
for i in range(a):
|
| 95 |
+
f_3_n += sympify(DMFsubs(red[i], A + h, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_2[i]*h)
|
| 96 |
+
f_3.append(f_3_n)
|
| 97 |
+
|
| 98 |
+
return [y_0[i] + h*(f_0[i]+2*f_1[i]+2*f_2[i]+f_3[i])/6 for i in range(a)]
|
.venv/lib/python3.12/site-packages/sympy/holonomic/recurrence.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Recurrence Operators"""
|
| 2 |
+
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 5 |
+
from sympy.printing import sstr
|
| 6 |
+
from sympy.core.sympify import sympify
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def RecurrenceOperators(base, generator):
|
| 10 |
+
"""
|
| 11 |
+
Returns an Algebra of Recurrence Operators and the operator for
|
| 12 |
+
shifting i.e. the `Sn` operator.
|
| 13 |
+
The first argument needs to be the base polynomial ring for the algebra
|
| 14 |
+
and the second argument must be a generator which can be either a
|
| 15 |
+
noncommutative Symbol or a string.
|
| 16 |
+
|
| 17 |
+
Examples
|
| 18 |
+
========
|
| 19 |
+
|
| 20 |
+
>>> from sympy import ZZ
|
| 21 |
+
>>> from sympy import symbols
|
| 22 |
+
>>> from sympy.holonomic.recurrence import RecurrenceOperators
|
| 23 |
+
>>> n = symbols('n', integer=True)
|
| 24 |
+
>>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
ring = RecurrenceOperatorAlgebra(base, generator)
|
| 28 |
+
return (ring, ring.shift_operator)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class RecurrenceOperatorAlgebra:
|
| 32 |
+
"""
|
| 33 |
+
A Recurrence Operator Algebra is a set of noncommutative polynomials
|
| 34 |
+
in intermediate `Sn` and coefficients in a base ring A. It follows the
|
| 35 |
+
commutation rule:
|
| 36 |
+
Sn * a(n) = a(n + 1) * Sn
|
| 37 |
+
|
| 38 |
+
This class represents a Recurrence Operator Algebra and serves as the parent ring
|
| 39 |
+
for Recurrence Operators.
|
| 40 |
+
|
| 41 |
+
Examples
|
| 42 |
+
========
|
| 43 |
+
|
| 44 |
+
>>> from sympy import ZZ
|
| 45 |
+
>>> from sympy import symbols
|
| 46 |
+
>>> from sympy.holonomic.recurrence import RecurrenceOperators
|
| 47 |
+
>>> n = symbols('n', integer=True)
|
| 48 |
+
>>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
|
| 49 |
+
>>> R
|
| 50 |
+
Univariate Recurrence Operator Algebra in intermediate Sn over the base ring
|
| 51 |
+
ZZ[n]
|
| 52 |
+
|
| 53 |
+
See Also
|
| 54 |
+
========
|
| 55 |
+
|
| 56 |
+
RecurrenceOperator
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(self, base, generator):
|
| 60 |
+
# the base ring for the algebra
|
| 61 |
+
self.base = base
|
| 62 |
+
# the operator representing shift i.e. `Sn`
|
| 63 |
+
self.shift_operator = RecurrenceOperator(
|
| 64 |
+
[base.zero, base.one], self)
|
| 65 |
+
|
| 66 |
+
if generator is None:
|
| 67 |
+
self.gen_symbol = symbols('Sn', commutative=False)
|
| 68 |
+
else:
|
| 69 |
+
if isinstance(generator, str):
|
| 70 |
+
self.gen_symbol = symbols(generator, commutative=False)
|
| 71 |
+
elif isinstance(generator, Symbol):
|
| 72 |
+
self.gen_symbol = generator
|
| 73 |
+
|
| 74 |
+
def __str__(self):
|
| 75 |
+
string = 'Univariate Recurrence Operator Algebra in intermediate '\
|
| 76 |
+
+ sstr(self.gen_symbol) + ' over the base ring ' + \
|
| 77 |
+
(self.base).__str__()
|
| 78 |
+
|
| 79 |
+
return string
|
| 80 |
+
|
| 81 |
+
__repr__ = __str__
|
| 82 |
+
|
| 83 |
+
def __eq__(self, other):
|
| 84 |
+
if self.base == other.base and self.gen_symbol == other.gen_symbol:
|
| 85 |
+
return True
|
| 86 |
+
else:
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _add_lists(list1, list2):
|
| 91 |
+
if len(list1) <= len(list2):
|
| 92 |
+
sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):]
|
| 93 |
+
else:
|
| 94 |
+
sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):]
|
| 95 |
+
return sol
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class RecurrenceOperator:
|
| 99 |
+
"""
|
| 100 |
+
The Recurrence Operators are defined by a list of polynomials
|
| 101 |
+
in the base ring and the parent ring of the Operator.
|
| 102 |
+
|
| 103 |
+
Explanation
|
| 104 |
+
===========
|
| 105 |
+
|
| 106 |
+
Takes a list of polynomials for each power of Sn and the
|
| 107 |
+
parent ring which must be an instance of RecurrenceOperatorAlgebra.
|
| 108 |
+
|
| 109 |
+
A Recurrence Operator can be created easily using
|
| 110 |
+
the operator `Sn`. See examples below.
|
| 111 |
+
|
| 112 |
+
Examples
|
| 113 |
+
========
|
| 114 |
+
|
| 115 |
+
>>> from sympy.holonomic.recurrence import RecurrenceOperator, RecurrenceOperators
|
| 116 |
+
>>> from sympy import ZZ
|
| 117 |
+
>>> from sympy import symbols
|
| 118 |
+
>>> n = symbols('n', integer=True)
|
| 119 |
+
>>> R, Sn = RecurrenceOperators(ZZ.old_poly_ring(n),'Sn')
|
| 120 |
+
|
| 121 |
+
>>> RecurrenceOperator([0, 1, n**2], R)
|
| 122 |
+
(1)Sn + (n**2)Sn**2
|
| 123 |
+
|
| 124 |
+
>>> Sn*n
|
| 125 |
+
(n + 1)Sn
|
| 126 |
+
|
| 127 |
+
>>> n*Sn*n + 1 - Sn**2*n
|
| 128 |
+
(1) + (n**2 + n)Sn + (-n - 2)Sn**2
|
| 129 |
+
|
| 130 |
+
See Also
|
| 131 |
+
========
|
| 132 |
+
|
| 133 |
+
DifferentialOperatorAlgebra
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
_op_priority = 20
|
| 137 |
+
|
| 138 |
+
def __init__(self, list_of_poly, parent):
|
| 139 |
+
# the parent ring for this operator
|
| 140 |
+
# must be an RecurrenceOperatorAlgebra object
|
| 141 |
+
self.parent = parent
|
| 142 |
+
# sequence of polynomials in n for each power of Sn
|
| 143 |
+
# represents the operator
|
| 144 |
+
# convert the expressions into ring elements using from_sympy
|
| 145 |
+
if isinstance(list_of_poly, list):
|
| 146 |
+
for i, j in enumerate(list_of_poly):
|
| 147 |
+
if isinstance(j, int):
|
| 148 |
+
list_of_poly[i] = self.parent.base.from_sympy(S(j))
|
| 149 |
+
elif not isinstance(j, self.parent.base.dtype):
|
| 150 |
+
list_of_poly[i] = self.parent.base.from_sympy(j)
|
| 151 |
+
|
| 152 |
+
self.listofpoly = list_of_poly
|
| 153 |
+
self.order = len(self.listofpoly) - 1
|
| 154 |
+
|
| 155 |
+
def __mul__(self, other):
|
| 156 |
+
"""
|
| 157 |
+
Multiplies two Operators and returns another
|
| 158 |
+
RecurrenceOperator instance using the commutation rule
|
| 159 |
+
Sn * a(n) = a(n + 1) * Sn
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
listofself = self.listofpoly
|
| 163 |
+
base = self.parent.base
|
| 164 |
+
|
| 165 |
+
if not isinstance(other, RecurrenceOperator):
|
| 166 |
+
if not isinstance(other, self.parent.base.dtype):
|
| 167 |
+
listofother = [self.parent.base.from_sympy(sympify(other))]
|
| 168 |
+
|
| 169 |
+
else:
|
| 170 |
+
listofother = [other]
|
| 171 |
+
else:
|
| 172 |
+
listofother = other.listofpoly
|
| 173 |
+
# multiply a polynomial `b` with a list of polynomials
|
| 174 |
+
|
| 175 |
+
def _mul_dmp_diffop(b, listofother):
|
| 176 |
+
if isinstance(listofother, list):
|
| 177 |
+
return [i * b for i in listofother]
|
| 178 |
+
return [b * listofother]
|
| 179 |
+
|
| 180 |
+
sol = _mul_dmp_diffop(listofself[0], listofother)
|
| 181 |
+
|
| 182 |
+
# compute Sn^i * b
|
| 183 |
+
def _mul_Sni_b(b):
|
| 184 |
+
sol = [base.zero]
|
| 185 |
+
|
| 186 |
+
if isinstance(b, list):
|
| 187 |
+
for i in b:
|
| 188 |
+
j = base.to_sympy(i).subs(base.gens[0], base.gens[0] + S.One)
|
| 189 |
+
sol.append(base.from_sympy(j))
|
| 190 |
+
|
| 191 |
+
else:
|
| 192 |
+
j = b.subs(base.gens[0], base.gens[0] + S.One)
|
| 193 |
+
sol.append(base.from_sympy(j))
|
| 194 |
+
|
| 195 |
+
return sol
|
| 196 |
+
|
| 197 |
+
for i in range(1, len(listofself)):
|
| 198 |
+
# find Sn^i * b in ith iteration
|
| 199 |
+
listofother = _mul_Sni_b(listofother)
|
| 200 |
+
# solution = solution + listofself[i] * (Sn^i * b)
|
| 201 |
+
sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother))
|
| 202 |
+
|
| 203 |
+
return RecurrenceOperator(sol, self.parent)
|
| 204 |
+
|
| 205 |
+
def __rmul__(self, other):
|
| 206 |
+
if not isinstance(other, RecurrenceOperator):
|
| 207 |
+
|
| 208 |
+
if isinstance(other, int):
|
| 209 |
+
other = S(other)
|
| 210 |
+
|
| 211 |
+
if not isinstance(other, self.parent.base.dtype):
|
| 212 |
+
other = (self.parent.base).from_sympy(other)
|
| 213 |
+
|
| 214 |
+
sol = [other * j for j in self.listofpoly]
|
| 215 |
+
return RecurrenceOperator(sol, self.parent)
|
| 216 |
+
|
| 217 |
+
def __add__(self, other):
|
| 218 |
+
if isinstance(other, RecurrenceOperator):
|
| 219 |
+
|
| 220 |
+
sol = _add_lists(self.listofpoly, other.listofpoly)
|
| 221 |
+
return RecurrenceOperator(sol, self.parent)
|
| 222 |
+
|
| 223 |
+
else:
|
| 224 |
+
|
| 225 |
+
if isinstance(other, int):
|
| 226 |
+
other = S(other)
|
| 227 |
+
list_self = self.listofpoly
|
| 228 |
+
if not isinstance(other, self.parent.base.dtype):
|
| 229 |
+
list_other = [((self.parent).base).from_sympy(other)]
|
| 230 |
+
else:
|
| 231 |
+
list_other = [other]
|
| 232 |
+
sol = [list_self[0] + list_other[0]] + list_self[1:]
|
| 233 |
+
|
| 234 |
+
return RecurrenceOperator(sol, self.parent)
|
| 235 |
+
|
| 236 |
+
__radd__ = __add__
|
| 237 |
+
|
| 238 |
+
def __sub__(self, other):
|
| 239 |
+
return self + (-1) * other
|
| 240 |
+
|
| 241 |
+
def __rsub__(self, other):
|
| 242 |
+
return (-1) * self + other
|
| 243 |
+
|
| 244 |
+
def __pow__(self, n):
|
| 245 |
+
if n == 1:
|
| 246 |
+
return self
|
| 247 |
+
result = RecurrenceOperator([self.parent.base.one], self.parent)
|
| 248 |
+
if n == 0:
|
| 249 |
+
return result
|
| 250 |
+
# if self is `Sn`
|
| 251 |
+
if self.listofpoly == self.parent.shift_operator.listofpoly:
|
| 252 |
+
sol = [self.parent.base.zero] * n + [self.parent.base.one]
|
| 253 |
+
return RecurrenceOperator(sol, self.parent)
|
| 254 |
+
x = self
|
| 255 |
+
while True:
|
| 256 |
+
if n % 2:
|
| 257 |
+
result *= x
|
| 258 |
+
n >>= 1
|
| 259 |
+
if not n:
|
| 260 |
+
break
|
| 261 |
+
x *= x
|
| 262 |
+
return result
|
| 263 |
+
|
| 264 |
+
def __str__(self):
|
| 265 |
+
listofpoly = self.listofpoly
|
| 266 |
+
print_str = ''
|
| 267 |
+
|
| 268 |
+
for i, j in enumerate(listofpoly):
|
| 269 |
+
if j == self.parent.base.zero:
|
| 270 |
+
continue
|
| 271 |
+
|
| 272 |
+
j = self.parent.base.to_sympy(j)
|
| 273 |
+
|
| 274 |
+
if i == 0:
|
| 275 |
+
print_str += '(' + sstr(j) + ')'
|
| 276 |
+
continue
|
| 277 |
+
|
| 278 |
+
if print_str:
|
| 279 |
+
print_str += ' + '
|
| 280 |
+
|
| 281 |
+
if i == 1:
|
| 282 |
+
print_str += '(' + sstr(j) + ')Sn'
|
| 283 |
+
continue
|
| 284 |
+
|
| 285 |
+
print_str += '(' + sstr(j) + ')' + 'Sn**' + sstr(i)
|
| 286 |
+
|
| 287 |
+
return print_str
|
| 288 |
+
|
| 289 |
+
__repr__ = __str__
|
| 290 |
+
|
| 291 |
+
def __eq__(self, other):
|
| 292 |
+
if isinstance(other, RecurrenceOperator):
|
| 293 |
+
if self.listofpoly == other.listofpoly and self.parent == other.parent:
|
| 294 |
+
return True
|
| 295 |
+
else:
|
| 296 |
+
return False
|
| 297 |
+
return self.listofpoly[0] == other and \
|
| 298 |
+
all(i is self.parent.base.zero for i in self.listofpoly[1:])
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class HolonomicSequence:
|
| 302 |
+
"""
|
| 303 |
+
A Holonomic Sequence is a type of sequence satisfying a linear homogeneous
|
| 304 |
+
recurrence relation with Polynomial coefficients. Alternatively, A sequence
|
| 305 |
+
is Holonomic if and only if its generating function is a Holonomic Function.
|
| 306 |
+
"""
|
| 307 |
+
|
| 308 |
+
def __init__(self, recurrence, u0=[]):
|
| 309 |
+
self.recurrence = recurrence
|
| 310 |
+
if not isinstance(u0, list):
|
| 311 |
+
self.u0 = [u0]
|
| 312 |
+
else:
|
| 313 |
+
self.u0 = u0
|
| 314 |
+
|
| 315 |
+
if len(self.u0) == 0:
|
| 316 |
+
self._have_init_cond = False
|
| 317 |
+
else:
|
| 318 |
+
self._have_init_cond = True
|
| 319 |
+
self.n = recurrence.parent.base.gens[0]
|
| 320 |
+
|
| 321 |
+
def __repr__(self):
|
| 322 |
+
str_sol = 'HolonomicSequence(%s, %s)' % ((self.recurrence).__repr__(), sstr(self.n))
|
| 323 |
+
if not self._have_init_cond:
|
| 324 |
+
return str_sol
|
| 325 |
+
else:
|
| 326 |
+
cond_str = ''
|
| 327 |
+
seq_str = 0
|
| 328 |
+
for i in self.u0:
|
| 329 |
+
cond_str += ', u(%s) = %s' % (sstr(seq_str), sstr(i))
|
| 330 |
+
seq_str += 1
|
| 331 |
+
|
| 332 |
+
sol = str_sol + cond_str
|
| 333 |
+
return sol
|
| 334 |
+
|
| 335 |
+
__str__ = __repr__
|
| 336 |
+
|
| 337 |
+
def __eq__(self, other):
|
| 338 |
+
if self.recurrence != other.recurrence or self.n != other.n:
|
| 339 |
+
return False
|
| 340 |
+
if self._have_init_cond and other._have_init_cond:
|
| 341 |
+
return self.u0 == other.u0
|
| 342 |
+
return True
|
.venv/lib/python3.12/site-packages/sympy/holonomic/tests/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/sympy/holonomic/tests/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (196 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/holonomic/tests/__pycache__/test_holonomic.cpython-312.pyc
ADDED
|
Binary file (74.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/holonomic/tests/__pycache__/test_recurrence.cpython-312.pyc
ADDED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.holonomic import (DifferentialOperator, HolonomicFunction,
|
| 2 |
+
DifferentialOperators, from_hyper,
|
| 3 |
+
from_meijerg, expr_to_holonomic)
|
| 4 |
+
from sympy.holonomic.recurrence import RecurrenceOperators, HolonomicSequence
|
| 5 |
+
from sympy.core import EulerGamma
|
| 6 |
+
from sympy.core.numbers import (I, Rational, pi)
|
| 7 |
+
from sympy.core.singleton import S
|
| 8 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 9 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 10 |
+
from sympy.functions.elementary.hyperbolic import (asinh, cosh)
|
| 11 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 12 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 13 |
+
from sympy.functions.special.bessel import besselj
|
| 14 |
+
from sympy.functions.special.beta_functions import beta
|
| 15 |
+
from sympy.functions.special.error_functions import (Ci, Si, erf, erfc)
|
| 16 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 17 |
+
from sympy.functions.special.hyper import (hyper, meijerg)
|
| 18 |
+
from sympy.printing.str import sstr
|
| 19 |
+
from sympy.series.order import O
|
| 20 |
+
from sympy.simplify.hyperexpand import hyperexpand
|
| 21 |
+
from sympy.polys.domains.integerring import ZZ
|
| 22 |
+
from sympy.polys.domains.rationalfield import QQ
|
| 23 |
+
from sympy.polys.domains.realfield import RR
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_DifferentialOperator():
|
| 27 |
+
x = symbols('x')
|
| 28 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 29 |
+
assert Dx == R.derivative_operator
|
| 30 |
+
assert Dx == DifferentialOperator([R.base.zero, R.base.one], R)
|
| 31 |
+
assert x * Dx + x**2 * Dx**2 == DifferentialOperator([0, x, x**2], R)
|
| 32 |
+
assert (x**2 + 1) + Dx + x * \
|
| 33 |
+
Dx**5 == DifferentialOperator([x**2 + 1, 1, 0, 0, 0, x], R)
|
| 34 |
+
assert (x * Dx + x**2 + 1 - Dx * (x**3 + x))**3 == (-48 * x**6) + \
|
| 35 |
+
(-57 * x**7) * Dx + (-15 * x**8) * Dx**2 + (-x**9) * Dx**3
|
| 36 |
+
p = (x * Dx**2 + (x**2 + 3) * Dx**5) * (Dx + x**2)
|
| 37 |
+
q = (2 * x) + (4 * x**2) * Dx + (x**3) * Dx**2 + \
|
| 38 |
+
(20 * x**2 + x + 60) * Dx**3 + (10 * x**3 + 30 * x) * Dx**4 + \
|
| 39 |
+
(x**4 + 3 * x**2) * Dx**5 + (x**2 + 3) * Dx**6
|
| 40 |
+
assert p == q
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_HolonomicFunction_addition():
|
| 44 |
+
x = symbols('x')
|
| 45 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 46 |
+
p = HolonomicFunction(Dx**2 * x, x)
|
| 47 |
+
q = HolonomicFunction((2) * Dx + (x) * Dx**2, x)
|
| 48 |
+
assert p == q
|
| 49 |
+
p = HolonomicFunction(x * Dx + 1, x)
|
| 50 |
+
q = HolonomicFunction(Dx + 1, x)
|
| 51 |
+
r = HolonomicFunction((x - 2) + (x**2 - 2) * Dx + (x**2 - x) * Dx**2, x)
|
| 52 |
+
assert p + q == r
|
| 53 |
+
p = HolonomicFunction(x * Dx + Dx**2 * (x**2 + 2), x)
|
| 54 |
+
q = HolonomicFunction(Dx - 3, x)
|
| 55 |
+
r = HolonomicFunction((-54 * x**2 - 126 * x - 150) + (-135 * x**3 - 252 * x**2 - 270 * x + 140) * Dx +\
|
| 56 |
+
(-27 * x**4 - 24 * x**2 + 14 * x - 150) * Dx**2 + \
|
| 57 |
+
(9 * x**4 + 15 * x**3 + 38 * x**2 + 30 * x +40) * Dx**3, x)
|
| 58 |
+
assert p + q == r
|
| 59 |
+
p = HolonomicFunction(Dx**5 - 1, x)
|
| 60 |
+
q = HolonomicFunction(x**3 + Dx, x)
|
| 61 |
+
r = HolonomicFunction((-x**18 + 45*x**14 - 525*x**10 + 1575*x**6 - x**3 - 630*x**2) + \
|
| 62 |
+
(-x**15 + 30*x**11 - 195*x**7 + 210*x**3 - 1)*Dx + (x**18 - 45*x**14 + 525*x**10 - \
|
| 63 |
+
1575*x**6 + x**3 + 630*x**2)*Dx**5 + (x**15 - 30*x**11 + 195*x**7 - 210*x**3 + \
|
| 64 |
+
1)*Dx**6, x)
|
| 65 |
+
assert p+q == r
|
| 66 |
+
|
| 67 |
+
p = x**2 + 3*x + 8
|
| 68 |
+
q = x**3 - 7*x + 5
|
| 69 |
+
p = p*Dx - p.diff()
|
| 70 |
+
q = q*Dx - q.diff()
|
| 71 |
+
r = HolonomicFunction(p, x) + HolonomicFunction(q, x)
|
| 72 |
+
s = HolonomicFunction((6*x**2 + 18*x + 14) + (-4*x**3 - 18*x**2 - 62*x + 10)*Dx +\
|
| 73 |
+
(x**4 + 6*x**3 + 31*x**2 - 10*x - 71)*Dx**2, x)
|
| 74 |
+
assert r == s
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_HolonomicFunction_multiplication():
|
| 78 |
+
x = symbols('x')
|
| 79 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 80 |
+
p = HolonomicFunction(Dx+x+x*Dx**2, x)
|
| 81 |
+
q = HolonomicFunction(x*Dx+Dx*x+Dx**2, x)
|
| 82 |
+
r = HolonomicFunction((8*x**6 + 4*x**4 + 6*x**2 + 3) + (24*x**5 - 4*x**3 + 24*x)*Dx + \
|
| 83 |
+
(8*x**6 + 20*x**4 + 12*x**2 + 2)*Dx**2 + (8*x**5 + 4*x**3 + 4*x)*Dx**3 + \
|
| 84 |
+
(2*x**4 + x**2)*Dx**4, x)
|
| 85 |
+
assert p*q == r
|
| 86 |
+
p = HolonomicFunction(Dx**2+1, x)
|
| 87 |
+
q = HolonomicFunction(Dx-1, x)
|
| 88 |
+
r = HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x)
|
| 89 |
+
assert p*q == r
|
| 90 |
+
p = HolonomicFunction(Dx**2+1+x+Dx, x)
|
| 91 |
+
q = HolonomicFunction((Dx*x-1)**2, x)
|
| 92 |
+
r = HolonomicFunction((4*x**7 + 11*x**6 + 16*x**5 + 4*x**4 - 6*x**3 - 7*x**2 - 8*x - 2) + \
|
| 93 |
+
(8*x**6 + 26*x**5 + 24*x**4 - 3*x**3 - 11*x**2 - 6*x - 2)*Dx + \
|
| 94 |
+
(8*x**6 + 18*x**5 + 15*x**4 - 3*x**3 - 6*x**2 - 6*x - 2)*Dx**2 + (8*x**5 + \
|
| 95 |
+
10*x**4 + 6*x**3 - 2*x**2 - 4*x)*Dx**3 + (4*x**5 + 3*x**4 - x**2)*Dx**4, x)
|
| 96 |
+
assert p*q == r
|
| 97 |
+
p = HolonomicFunction(x*Dx**2-1, x)
|
| 98 |
+
q = HolonomicFunction(Dx*x-x, x)
|
| 99 |
+
r = HolonomicFunction((x - 3) + (-2*x + 2)*Dx + (x)*Dx**2, x)
|
| 100 |
+
assert p*q == r
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_HolonomicFunction_power():
|
| 104 |
+
x = symbols('x')
|
| 105 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 106 |
+
p = HolonomicFunction(Dx+x+x*Dx**2, x)
|
| 107 |
+
a = HolonomicFunction(Dx, x)
|
| 108 |
+
for n in range(10):
|
| 109 |
+
assert a == p**n
|
| 110 |
+
a *= p
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_addition_initial_condition():
|
| 114 |
+
x = symbols('x')
|
| 115 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 116 |
+
p = HolonomicFunction(Dx-1, x, 0, [3])
|
| 117 |
+
q = HolonomicFunction(Dx**2+1, x, 0, [1, 0])
|
| 118 |
+
r = HolonomicFunction(-1 + Dx - Dx**2 + Dx**3, x, 0, [4, 3, 2])
|
| 119 |
+
assert p + q == r
|
| 120 |
+
p = HolonomicFunction(Dx - x + Dx**2, x, 0, [1, 2])
|
| 121 |
+
q = HolonomicFunction(Dx**2 + x, x, 0, [1, 0])
|
| 122 |
+
r = HolonomicFunction((-x**4 - x**3/4 - x**2 + Rational(1, 4)) + (x**3 + x**2/4 + x*Rational(3, 4) + 1)*Dx + \
|
| 123 |
+
(x*Rational(-3, 2) + Rational(7, 4))*Dx**2 + (x**2 - x*Rational(7, 4) + Rational(1, 4))*Dx**3 + (x**2 + x/4 + S.Half)*Dx**4, x, 0, [2, 2, -2, 2])
|
| 124 |
+
assert p + q == r
|
| 125 |
+
p = HolonomicFunction(Dx**2 + 4*x*Dx + x**2, x, 0, [3, 4])
|
| 126 |
+
q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1])
|
| 127 |
+
r = HolonomicFunction((x**6 + 2*x**4 - 5*x**2 - 6) + (4*x**5 + 36*x**3 - 32*x)*Dx + \
|
| 128 |
+
(x**6 + 3*x**4 + 5*x**2 - 9)*Dx**2 + (4*x**5 + 36*x**3 - 32*x)*Dx**3 + (x**4 + \
|
| 129 |
+
10*x**2 - 3)*Dx**4, x, 0, [4, 5, -1, -17])
|
| 130 |
+
assert p + q == r
|
| 131 |
+
q = HolonomicFunction(Dx**3 + x, x, 2, [3, 0, 1])
|
| 132 |
+
p = HolonomicFunction(Dx - 1, x, 2, [1])
|
| 133 |
+
r = HolonomicFunction((-x**2 - x + 1) + (x**2 + x)*Dx + (-x - 2)*Dx**3 + \
|
| 134 |
+
(x + 1)*Dx**4, x, 2, [4, 1, 2, -5 ])
|
| 135 |
+
assert p + q == r
|
| 136 |
+
p = expr_to_holonomic(sin(x))
|
| 137 |
+
q = expr_to_holonomic(1/x, x0=1)
|
| 138 |
+
r = HolonomicFunction((x**2 + 6) + (x**3 + 2*x)*Dx + (x**2 + 6)*Dx**2 + (x**3 + 2*x)*Dx**3, \
|
| 139 |
+
x, 1, [sin(1) + 1, -1 + cos(1), -sin(1) + 2])
|
| 140 |
+
assert p + q == r
|
| 141 |
+
C_1 = symbols('C_1')
|
| 142 |
+
p = expr_to_holonomic(sqrt(x))
|
| 143 |
+
q = expr_to_holonomic(sqrt(x**2-x))
|
| 144 |
+
r = (p + q).to_expr().subs(C_1, -I/2).expand()
|
| 145 |
+
assert r == I*sqrt(x)*sqrt(-x + 1) + sqrt(x)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def test_multiplication_initial_condition():
|
| 149 |
+
x = symbols('x')
|
| 150 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 151 |
+
p = HolonomicFunction(Dx**2 + x*Dx - 1, x, 0, [3, 1])
|
| 152 |
+
q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1])
|
| 153 |
+
r = HolonomicFunction((x**4 + 14*x**2 + 60) + 4*x*Dx + (x**4 + 9*x**2 + 20)*Dx**2 + \
|
| 154 |
+
(2*x**3 + 18*x)*Dx**3 + (x**2 + 10)*Dx**4, x, 0, [3, 4, 2, 3])
|
| 155 |
+
assert p * q == r
|
| 156 |
+
p = HolonomicFunction(Dx**2 + x, x, 0, [1, 0])
|
| 157 |
+
q = HolonomicFunction(Dx**3 - x**2, x, 0, [3, 3, 3])
|
| 158 |
+
r = HolonomicFunction((x**8 - 37*x**7/27 - 10*x**6/27 - 164*x**5/9 - 184*x**4/9 + \
|
| 159 |
+
160*x**3/27 + 404*x**2/9 + 8*x + Rational(40, 3)) + (6*x**7 - 128*x**6/9 - 98*x**5/9 - 28*x**4/9 + \
|
| 160 |
+
8*x**3/9 + 28*x**2 + x*Rational(40, 9) - 40)*Dx + (3*x**6 - 82*x**5/9 + 76*x**4/9 + 4*x**3/3 + \
|
| 161 |
+
220*x**2/9 - x*Rational(80, 3))*Dx**2 + (-2*x**6 + 128*x**5/27 - 2*x**4/3 -80*x**2/9 + Rational(200, 9))*Dx**3 + \
|
| 162 |
+
(3*x**5 - 64*x**4/9 - 28*x**3/9 + 6*x**2 - x*Rational(20, 9) - Rational(20, 3))*Dx**4 + (-4*x**3 + 64*x**2/9 + \
|
| 163 |
+
x*Rational(8, 3))*Dx**5 + (x**4 - 64*x**3/27 - 4*x**2/3 + Rational(20, 9))*Dx**6, x, 0, [3, 3, 3, -3, -12, -24])
|
| 164 |
+
assert p * q == r
|
| 165 |
+
p = HolonomicFunction(Dx - 1, x, 0, [2])
|
| 166 |
+
q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])
|
| 167 |
+
r = HolonomicFunction(2 -2*Dx + Dx**2, x, 0, [0, 2])
|
| 168 |
+
assert p * q == r
|
| 169 |
+
q = HolonomicFunction(x*Dx**2 + 1 + 2*Dx, x, 0,[0, 1])
|
| 170 |
+
r = HolonomicFunction((x - 1) + (-2*x + 2)*Dx + x*Dx**2, x, 0, [0, 2])
|
| 171 |
+
assert p * q == r
|
| 172 |
+
p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 3])
|
| 173 |
+
q = HolonomicFunction(Dx**3 + 1, x, 0, [1, 2, 1])
|
| 174 |
+
r = HolonomicFunction(6*Dx + 3*Dx**2 + 2*Dx**3 - 3*Dx**4 + Dx**6, x, 0, [1, 5, 14, 17, 17, 2])
|
| 175 |
+
assert p * q == r
|
| 176 |
+
p = expr_to_holonomic(sin(x))
|
| 177 |
+
q = expr_to_holonomic(1/x, x0=1)
|
| 178 |
+
r = HolonomicFunction(x + 2*Dx + x*Dx**2, x, 1, [sin(1), -sin(1) + cos(1)])
|
| 179 |
+
assert p * q == r
|
| 180 |
+
p = expr_to_holonomic(sqrt(x))
|
| 181 |
+
q = expr_to_holonomic(sqrt(x**2-x))
|
| 182 |
+
r = (p * q).to_expr()
|
| 183 |
+
assert r == I*x*sqrt(-x + 1)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def test_HolonomicFunction_composition():
|
| 187 |
+
x = symbols('x')
|
| 188 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 189 |
+
p = HolonomicFunction(Dx-1, x).composition(x**2+x)
|
| 190 |
+
r = HolonomicFunction((-2*x - 1) + Dx, x)
|
| 191 |
+
assert p == r
|
| 192 |
+
p = HolonomicFunction(Dx**2+1, x).composition(x**5+x**2+1)
|
| 193 |
+
r = HolonomicFunction((125*x**12 + 150*x**9 + 60*x**6 + 8*x**3) + (-20*x**3 - 2)*Dx + \
|
| 194 |
+
(5*x**4 + 2*x)*Dx**2, x)
|
| 195 |
+
assert p == r
|
| 196 |
+
p = HolonomicFunction(Dx**2*x+x, x).composition(2*x**3+x**2+1)
|
| 197 |
+
r = HolonomicFunction((216*x**9 + 324*x**8 + 180*x**7 + 152*x**6 + 112*x**5 + \
|
| 198 |
+
36*x**4 + 4*x**3) + (24*x**4 + 16*x**3 + 3*x**2 - 6*x - 1)*Dx + (6*x**5 + 5*x**4 + \
|
| 199 |
+
x**3 + 3*x**2 + x)*Dx**2, x)
|
| 200 |
+
assert p == r
|
| 201 |
+
p = HolonomicFunction(Dx**2+1, x).composition(1-x**2)
|
| 202 |
+
r = HolonomicFunction((4*x**3) - Dx + x*Dx**2, x)
|
| 203 |
+
assert p == r
|
| 204 |
+
p = HolonomicFunction(Dx**2+1, x).composition(x - 2/(x**2 + 1))
|
| 205 |
+
r = HolonomicFunction((x**12 + 6*x**10 + 12*x**9 + 15*x**8 + 48*x**7 + 68*x**6 + \
|
| 206 |
+
72*x**5 + 111*x**4 + 112*x**3 + 54*x**2 + 12*x + 1) + (12*x**8 + 32*x**6 + \
|
| 207 |
+
24*x**4 - 4)*Dx + (x**12 + 6*x**10 + 4*x**9 + 15*x**8 + 16*x**7 + 20*x**6 + 24*x**5+ \
|
| 208 |
+
15*x**4 + 16*x**3 + 6*x**2 + 4*x + 1)*Dx**2, x)
|
| 209 |
+
assert p == r
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def test_from_hyper():
|
| 213 |
+
x = symbols('x')
|
| 214 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 215 |
+
p = hyper([1, 1], [Rational(3, 2)], x**2/4)
|
| 216 |
+
q = HolonomicFunction((4*x) + (5*x**2 - 8)*Dx + (x**3 - 4*x)*Dx**2, x, 1, [2*sqrt(3)*pi/9, -4*sqrt(3)*pi/27 + Rational(4, 3)])
|
| 217 |
+
r = from_hyper(p)
|
| 218 |
+
assert r == q
|
| 219 |
+
p = from_hyper(hyper([1], [Rational(3, 2)], x**2/4))
|
| 220 |
+
q = HolonomicFunction(-x + (-x**2/2 + 2)*Dx + x*Dx**2, x)
|
| 221 |
+
# x0 = 1
|
| 222 |
+
y0 = '[sqrt(pi)*exp(1/4)*erf(1/2), -sqrt(pi)*exp(1/4)*erf(1/2)/2 + 1]'
|
| 223 |
+
assert sstr(p.y0) == y0
|
| 224 |
+
assert q.annihilator == p.annihilator
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def test_from_meijerg():
|
| 228 |
+
x = symbols('x')
|
| 229 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 230 |
+
p = from_meijerg(meijerg(([], [Rational(3, 2)]), ([S.Half], [S.Half, 1]), x))
|
| 231 |
+
q = HolonomicFunction(x/2 - Rational(1, 4) + (-x**2 + x/4)*Dx + x**2*Dx**2 + x**3*Dx**3, x, 1, \
|
| 232 |
+
[1/sqrt(pi), 1/(2*sqrt(pi)), -1/(4*sqrt(pi))])
|
| 233 |
+
assert p == q
|
| 234 |
+
p = from_meijerg(meijerg(([], []), ([0], []), x))
|
| 235 |
+
q = HolonomicFunction(1 + Dx, x, 0, [1])
|
| 236 |
+
assert p == q
|
| 237 |
+
p = from_meijerg(meijerg(([1], []), ([S.Half], [0]), x))
|
| 238 |
+
q = HolonomicFunction((x + S.Half)*Dx + x*Dx**2, x, 1, [sqrt(pi)*erf(1), exp(-1)])
|
| 239 |
+
assert p == q
|
| 240 |
+
p = from_meijerg(meijerg(([0], [1]), ([0], []), 2*x**2))
|
| 241 |
+
q = HolonomicFunction((3*x**2 - 1)*Dx + x**3*Dx**2, x, 1, [-exp(Rational(-1, 2)) + 1, -exp(Rational(-1, 2))])
|
| 242 |
+
assert p == q
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def test_to_Sequence():
|
| 246 |
+
x = symbols('x')
|
| 247 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 248 |
+
n = symbols('n', integer=True)
|
| 249 |
+
_, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn')
|
| 250 |
+
p = HolonomicFunction(x**2*Dx**4 + x + Dx, x).to_sequence()
|
| 251 |
+
q = [(HolonomicSequence(1 + (n + 2)*Sn**2 + (n**4 + 6*n**3 + 11*n**2 + 6*n)*Sn**3), 0, 1)]
|
| 252 |
+
assert p == q
|
| 253 |
+
p = HolonomicFunction(x**2*Dx**4 + x**3 + Dx**2, x).to_sequence()
|
| 254 |
+
q = [(HolonomicSequence(1 + (n**4 + 14*n**3 + 72*n**2 + 163*n + 140)*Sn**5), 0, 0)]
|
| 255 |
+
assert p == q
|
| 256 |
+
p = HolonomicFunction(x**3*Dx**4 + 1 + Dx**2, x).to_sequence()
|
| 257 |
+
q = [(HolonomicSequence(1 + (n**4 - 2*n**3 - n**2 + 2*n)*Sn + (n**2 + 3*n + 2)*Sn**2), 0, 0)]
|
| 258 |
+
assert p == q
|
| 259 |
+
p = HolonomicFunction(3*x**3*Dx**4 + 2*x*Dx + x*Dx**3, x).to_sequence()
|
| 260 |
+
q = [(HolonomicSequence(2*n + (3*n**4 - 6*n**3 - 3*n**2 + 6*n)*Sn + (n**3 + 3*n**2 + 2*n)*Sn**2), 0, 1)]
|
| 261 |
+
assert p == q
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def test_to_Sequence_Initial_Coniditons():
|
| 265 |
+
x = symbols('x')
|
| 266 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 267 |
+
n = symbols('n', integer=True)
|
| 268 |
+
_, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
|
| 269 |
+
p = HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence()
|
| 270 |
+
q = [(HolonomicSequence(-1 + (n + 1)*Sn, 1), 0)]
|
| 271 |
+
assert p == q
|
| 272 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_sequence()
|
| 273 |
+
q = [(HolonomicSequence(1 + (n**2 + 3*n + 2)*Sn**2, [0, 1]), 0)]
|
| 274 |
+
assert p == q
|
| 275 |
+
p = HolonomicFunction(Dx**2 + 1 + x**3*Dx, x, 0, [2, 3]).to_sequence()
|
| 276 |
+
q = [(HolonomicSequence(n + Sn**2 + (n**2 + 7*n + 12)*Sn**4, [2, 3, -1, Rational(-1, 2), Rational(1, 12)]), 1)]
|
| 277 |
+
assert p == q
|
| 278 |
+
p = HolonomicFunction(x**3*Dx**5 + 1 + Dx, x).to_sequence()
|
| 279 |
+
q = [(HolonomicSequence(1 + (n + 1)*Sn + (n**5 - 5*n**3 + 4*n)*Sn**2), 0, 3)]
|
| 280 |
+
assert p == q
|
| 281 |
+
C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3')
|
| 282 |
+
p = expr_to_holonomic(log(1+x**2))
|
| 283 |
+
q = [(HolonomicSequence(n**2 + (n**2 + 2*n)*Sn**2, [0, 0, C_2]), 0, 1)]
|
| 284 |
+
assert p.to_sequence() == q
|
| 285 |
+
p = p.diff()
|
| 286 |
+
q = [(HolonomicSequence((n + 2) + (n + 2)*Sn**2, [C_0, 0]), 1, 0)]
|
| 287 |
+
assert p.to_sequence() == q
|
| 288 |
+
p = expr_to_holonomic(erf(x) + x).to_sequence()
|
| 289 |
+
q = [(HolonomicSequence((2*n**2 - 2*n) + (n**3 + 2*n**2 - n - 2)*Sn**2, [0, 1 + 2/sqrt(pi), 0, C_3]), 0, 2)]
|
| 290 |
+
assert p == q
|
| 291 |
+
|
| 292 |
+
def test_series():
|
| 293 |
+
x = symbols('x')
|
| 294 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 295 |
+
p = HolonomicFunction(Dx**2 + 2*x*Dx, x, 0, [0, 1]).series(n=10)
|
| 296 |
+
q = x - x**3/3 + x**5/10 - x**7/42 + x**9/216 + O(x**10)
|
| 297 |
+
assert p == q
|
| 298 |
+
p = HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2)
|
| 299 |
+
q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]) # cos(x)
|
| 300 |
+
r = (p * q).series(n=10) # expansion of cos(x) * exp(x**2)
|
| 301 |
+
s = 1 + x**2/2 + x**4/24 - 31*x**6/720 - 179*x**8/8064 + O(x**10)
|
| 302 |
+
assert r == s
|
| 303 |
+
t = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]) # log(1 + x)
|
| 304 |
+
r = (p * t + q).series(n=10)
|
| 305 |
+
s = 1 + x - x**2 + 4*x**3/3 - 17*x**4/24 + 31*x**5/30 - 481*x**6/720 +\
|
| 306 |
+
71*x**7/105 - 20159*x**8/40320 + 379*x**9/840 + O(x**10)
|
| 307 |
+
assert r == s
|
| 308 |
+
p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \
|
| 309 |
+
(4-6*x**3+2*x**4)*Dx**2, x, 0, [0, 1]).series(n=7)
|
| 310 |
+
q = x + x**3/6 - 3*x**4/16 + x**5/20 - 23*x**6/960 + O(x**7)
|
| 311 |
+
assert p == q
|
| 312 |
+
p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \
|
| 313 |
+
(4-6*x**3+2*x**4)*Dx**2, x, 0, [1, 0]).series(n=7)
|
| 314 |
+
q = 1 - 3*x**2/4 - x**3/4 - 5*x**4/32 - 3*x**5/40 - 17*x**6/384 + O(x**7)
|
| 315 |
+
assert p == q
|
| 316 |
+
p = expr_to_holonomic(erf(x) + x).series(n=10)
|
| 317 |
+
C_3 = symbols('C_3')
|
| 318 |
+
q = (erf(x) + x).series(n=10)
|
| 319 |
+
assert p.subs(C_3, -2/(3*sqrt(pi))) == q
|
| 320 |
+
assert expr_to_holonomic(sqrt(x**3 + x)).series(n=10) == sqrt(x**3 + x).series(n=10)
|
| 321 |
+
assert expr_to_holonomic((2*x - 3*x**2)**Rational(1, 3)).series() == ((2*x - 3*x**2)**Rational(1, 3)).series()
|
| 322 |
+
assert expr_to_holonomic(sqrt(x**2-x)).series() == (sqrt(x**2-x)).series()
|
| 323 |
+
assert expr_to_holonomic(cos(x)**2/x**2, y0={-2: [1, 0, -1]}).series(n=10) == (cos(x)**2/x**2).series(n=10)
|
| 324 |
+
assert expr_to_holonomic(cos(x)**2/x**2, x0=1).series(n=10).together() == (cos(x)**2/x**2).series(n=10, x0=1).together()
|
| 325 |
+
assert expr_to_holonomic(cos(x-1)**2/(x-1)**2, x0=1, y0={-2: [1, 0, -1]}).series(n=10) \
|
| 326 |
+
== (cos(x-1)**2/(x-1)**2).series(x0=1, n=10)
|
| 327 |
+
|
| 328 |
+
def test_evalf_euler():
|
| 329 |
+
x = symbols('x')
|
| 330 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 331 |
+
|
| 332 |
+
# log(1+x)
|
| 333 |
+
p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1])
|
| 334 |
+
|
| 335 |
+
# path taken is a straight line from 0 to 1, on the real axis
|
| 336 |
+
r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
|
| 337 |
+
s = '0.699525841805253' # approx. equal to log(2) i.e. 0.693147180559945
|
| 338 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
| 339 |
+
|
| 340 |
+
# path taken is a triangle 0-->1+i-->2
|
| 341 |
+
r = [0.1 + 0.1*I]
|
| 342 |
+
for i in range(9):
|
| 343 |
+
r.append(r[-1]+0.1+0.1*I)
|
| 344 |
+
for i in range(10):
|
| 345 |
+
r.append(r[-1]+0.1-0.1*I)
|
| 346 |
+
|
| 347 |
+
# close to the exact solution 1.09861228866811
|
| 348 |
+
# imaginary part also close to zero
|
| 349 |
+
s = '1.07530466271334 - 0.0251200594793912*I'
|
| 350 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
| 351 |
+
|
| 352 |
+
# sin(x)
|
| 353 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])
|
| 354 |
+
s = '0.905546532085401 - 6.93889390390723e-18*I'
|
| 355 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
| 356 |
+
|
| 357 |
+
# computing sin(pi/2) using this method
|
| 358 |
+
# using a linear path from 0 to pi/2
|
| 359 |
+
r = [0.1]
|
| 360 |
+
for i in range(14):
|
| 361 |
+
r.append(r[-1] + 0.1)
|
| 362 |
+
r.append(pi/2)
|
| 363 |
+
s = '1.08016557252834' # close to 1.0 (exact solution)
|
| 364 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
| 365 |
+
|
| 366 |
+
# trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2)
|
| 367 |
+
# computing the same value sin(pi/2) using different path
|
| 368 |
+
r = [0.1*I]
|
| 369 |
+
for i in range(9):
|
| 370 |
+
r.append(r[-1]+0.1*I)
|
| 371 |
+
for i in range(15):
|
| 372 |
+
r.append(r[-1]+0.1)
|
| 373 |
+
r.append(pi/2+I)
|
| 374 |
+
for i in range(10):
|
| 375 |
+
r.append(r[-1]-0.1*I)
|
| 376 |
+
|
| 377 |
+
# close to 1.0
|
| 378 |
+
s = '0.976882381836257 - 1.65557671738537e-16*I'
|
| 379 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
| 380 |
+
|
| 381 |
+
# cos(x)
|
| 382 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0])
|
| 383 |
+
# compute cos(pi) along 0-->pi
|
| 384 |
+
r = [0.05]
|
| 385 |
+
for i in range(61):
|
| 386 |
+
r.append(r[-1]+0.05)
|
| 387 |
+
r.append(pi)
|
| 388 |
+
# close to -1 (exact answer)
|
| 389 |
+
s = '-1.08140824719196'
|
| 390 |
+
assert sstr(p.evalf(r, method='Euler')[-1]) == s
|
| 391 |
+
|
| 392 |
+
# a rectangular path (0 -> i -> 2+i -> 2)
|
| 393 |
+
r = [0.1*I]
|
| 394 |
+
for i in range(9):
|
| 395 |
+
r.append(r[-1]+0.1*I)
|
| 396 |
+
for i in range(20):
|
| 397 |
+
r.append(r[-1]+0.1)
|
| 398 |
+
for i in range(10):
|
| 399 |
+
r.append(r[-1]-0.1*I)
|
| 400 |
+
|
| 401 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r, method='Euler')
|
| 402 |
+
s = '0.501421652861245 - 3.88578058618805e-16*I'
|
| 403 |
+
assert sstr(p[-1]) == s
|
| 404 |
+
|
| 405 |
+
def test_evalf_rk4():
|
| 406 |
+
x = symbols('x')
|
| 407 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 408 |
+
|
| 409 |
+
# log(1+x)
|
| 410 |
+
p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1])
|
| 411 |
+
|
| 412 |
+
# path taken is a straight line from 0 to 1, on the real axis
|
| 413 |
+
r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
|
| 414 |
+
s = '0.693146363174626' # approx. equal to log(2) i.e. 0.693147180559945
|
| 415 |
+
assert sstr(p.evalf(r)[-1]) == s
|
| 416 |
+
|
| 417 |
+
# path taken is a triangle 0-->1+i-->2
|
| 418 |
+
r = [0.1 + 0.1*I]
|
| 419 |
+
for i in range(9):
|
| 420 |
+
r.append(r[-1]+0.1+0.1*I)
|
| 421 |
+
for i in range(10):
|
| 422 |
+
r.append(r[-1]+0.1-0.1*I)
|
| 423 |
+
|
| 424 |
+
# close to the exact solution 1.09861228866811
|
| 425 |
+
# imaginary part also close to zero
|
| 426 |
+
s = '1.098616 + 1.36083e-7*I'
|
| 427 |
+
assert sstr(p.evalf(r)[-1].n(7)) == s
|
| 428 |
+
|
| 429 |
+
# sin(x)
|
| 430 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1])
|
| 431 |
+
s = '0.90929463522785 + 1.52655665885959e-16*I'
|
| 432 |
+
assert sstr(p.evalf(r)[-1]) == s
|
| 433 |
+
|
| 434 |
+
# computing sin(pi/2) using this method
|
| 435 |
+
# using a linear path from 0 to pi/2
|
| 436 |
+
r = [0.1]
|
| 437 |
+
for i in range(14):
|
| 438 |
+
r.append(r[-1] + 0.1)
|
| 439 |
+
r.append(pi/2)
|
| 440 |
+
s = '0.999999895088917' # close to 1.0 (exact solution)
|
| 441 |
+
assert sstr(p.evalf(r)[-1]) == s
|
| 442 |
+
|
| 443 |
+
# trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2)
|
| 444 |
+
# computing the same value sin(pi/2) using different path
|
| 445 |
+
r = [0.1*I]
|
| 446 |
+
for i in range(9):
|
| 447 |
+
r.append(r[-1]+0.1*I)
|
| 448 |
+
for i in range(15):
|
| 449 |
+
r.append(r[-1]+0.1)
|
| 450 |
+
r.append(pi/2+I)
|
| 451 |
+
for i in range(10):
|
| 452 |
+
r.append(r[-1]-0.1*I)
|
| 453 |
+
|
| 454 |
+
# close to 1.0
|
| 455 |
+
s = '1.00000003415141 + 6.11940487991086e-16*I'
|
| 456 |
+
assert sstr(p.evalf(r)[-1]) == s
|
| 457 |
+
|
| 458 |
+
# cos(x)
|
| 459 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0])
|
| 460 |
+
# compute cos(pi) along 0-->pi
|
| 461 |
+
r = [0.05]
|
| 462 |
+
for i in range(61):
|
| 463 |
+
r.append(r[-1]+0.05)
|
| 464 |
+
r.append(pi)
|
| 465 |
+
# close to -1 (exact answer)
|
| 466 |
+
s = '-0.999999993238714'
|
| 467 |
+
assert sstr(p.evalf(r)[-1]) == s
|
| 468 |
+
|
| 469 |
+
# a rectangular path (0 -> i -> 2+i -> 2)
|
| 470 |
+
r = [0.1*I]
|
| 471 |
+
for i in range(9):
|
| 472 |
+
r.append(r[-1]+0.1*I)
|
| 473 |
+
for i in range(20):
|
| 474 |
+
r.append(r[-1]+0.1)
|
| 475 |
+
for i in range(10):
|
| 476 |
+
r.append(r[-1]-0.1*I)
|
| 477 |
+
|
| 478 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r)
|
| 479 |
+
s = '0.493152791638442 - 1.41553435639707e-15*I'
|
| 480 |
+
assert sstr(p[-1]) == s
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def test_expr_to_holonomic():
|
| 484 |
+
x = symbols('x')
|
| 485 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 486 |
+
p = expr_to_holonomic((sin(x)/x)**2)
|
| 487 |
+
q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 0, \
|
| 488 |
+
[1, 0, Rational(-2, 3)])
|
| 489 |
+
assert p == q
|
| 490 |
+
p = expr_to_holonomic(1/(1+x**2)**2)
|
| 491 |
+
q = HolonomicFunction(4*x + (x**2 + 1)*Dx, x, 0, [1])
|
| 492 |
+
assert p == q
|
| 493 |
+
p = expr_to_holonomic(exp(x)*sin(x)+x*log(1+x))
|
| 494 |
+
q = HolonomicFunction((2*x**3 + 10*x**2 + 20*x + 18) + (-2*x**4 - 10*x**3 - 20*x**2 \
|
| 495 |
+
- 18*x)*Dx + (2*x**5 + 6*x**4 + 7*x**3 + 8*x**2 + 10*x - 4)*Dx**2 + \
|
| 496 |
+
(-2*x**5 - 5*x**4 - 2*x**3 + 2*x**2 - x + 4)*Dx**3 + (x**5 + 2*x**4 - x**3 - \
|
| 497 |
+
7*x**2/2 + x + Rational(5, 2))*Dx**4, x, 0, [0, 1, 4, -1])
|
| 498 |
+
assert p == q
|
| 499 |
+
p = expr_to_holonomic(x*exp(x)+cos(x)+1)
|
| 500 |
+
q = HolonomicFunction((-x - 3)*Dx + (x + 2)*Dx**2 + (-x - 3)*Dx**3 + (x + 2)*Dx**4, x, \
|
| 501 |
+
0, [2, 1, 1, 3])
|
| 502 |
+
assert p == q
|
| 503 |
+
assert (x*exp(x)+cos(x)+1).series(n=10) == p.series(n=10)
|
| 504 |
+
p = expr_to_holonomic(log(1 + x)**2 + 1)
|
| 505 |
+
q = HolonomicFunction(Dx + (3*x + 3)*Dx**2 + (x**2 + 2*x + 1)*Dx**3, x, 0, [1, 0, 2])
|
| 506 |
+
assert p == q
|
| 507 |
+
p = expr_to_holonomic(erf(x)**2 + x)
|
| 508 |
+
q = HolonomicFunction((8*x**4 - 2*x**2 + 2)*Dx**2 + (6*x**3 - x/2)*Dx**3 + \
|
| 509 |
+
(x**2+ Rational(1, 4))*Dx**4, x, 0, [0, 1, 8/pi, 0])
|
| 510 |
+
assert p == q
|
| 511 |
+
p = expr_to_holonomic(cosh(x)*x)
|
| 512 |
+
q = HolonomicFunction((-x**2 + 2) -2*x*Dx + x**2*Dx**2, x, 0, [0, 1])
|
| 513 |
+
assert p == q
|
| 514 |
+
p = expr_to_holonomic(besselj(2, x))
|
| 515 |
+
q = HolonomicFunction((x**2 - 4) + x*Dx + x**2*Dx**2, x, 0, [0, 0])
|
| 516 |
+
assert p == q
|
| 517 |
+
p = expr_to_holonomic(besselj(0, x) + exp(x))
|
| 518 |
+
q = HolonomicFunction((-x**2 - x/2 + S.Half) + (x**2 - x/2 - Rational(3, 2))*Dx + (-x**2 + x/2 + 1)*Dx**2 +\
|
| 519 |
+
(x**2 + x/2)*Dx**3, x, 0, [2, 1, S.Half])
|
| 520 |
+
assert p == q
|
| 521 |
+
p = expr_to_holonomic(sin(x)**2/x)
|
| 522 |
+
q = HolonomicFunction(4 + 4*x*Dx + 3*Dx**2 + x*Dx**3, x, 0, [0, 1, 0])
|
| 523 |
+
assert p == q
|
| 524 |
+
p = expr_to_holonomic(sin(x)**2/x, x0=2)
|
| 525 |
+
q = HolonomicFunction((4) + (4*x)*Dx + (3)*Dx**2 + (x)*Dx**3, x, 2, [sin(2)**2/2,
|
| 526 |
+
sin(2)*cos(2) - sin(2)**2/4, -3*sin(2)**2/4 + cos(2)**2 - sin(2)*cos(2)])
|
| 527 |
+
assert p == q
|
| 528 |
+
p = expr_to_holonomic(log(x)/2 - Ci(2*x)/2 + Ci(2)/2)
|
| 529 |
+
q = HolonomicFunction(4*Dx + 4*x*Dx**2 + 3*Dx**3 + x*Dx**4, x, 0, \
|
| 530 |
+
[-log(2)/2 - EulerGamma/2 + Ci(2)/2, 0, 1, 0])
|
| 531 |
+
assert p == q
|
| 532 |
+
p = p.to_expr()
|
| 533 |
+
q = log(x)/2 - Ci(2*x)/2 + Ci(2)/2
|
| 534 |
+
assert p == q
|
| 535 |
+
p = expr_to_holonomic(x**S.Half, x0=1)
|
| 536 |
+
q = HolonomicFunction(x*Dx - S.Half, x, 1, [1])
|
| 537 |
+
assert p == q
|
| 538 |
+
p = expr_to_holonomic(sqrt(1 + x**2))
|
| 539 |
+
q = HolonomicFunction((-x) + (x**2 + 1)*Dx, x, 0, [1])
|
| 540 |
+
assert p == q
|
| 541 |
+
assert (expr_to_holonomic(sqrt(x) + sqrt(2*x)).to_expr()-\
|
| 542 |
+
(sqrt(x) + sqrt(2*x))).simplify() == 0
|
| 543 |
+
assert expr_to_holonomic(3*x+2*sqrt(x)).to_expr() == 3*x+2*sqrt(x)
|
| 544 |
+
p = expr_to_holonomic((x**4+x**3+5*x**2+3*x+2)/x**2, lenics=3)
|
| 545 |
+
q = HolonomicFunction((-2*x**4 - x**3 + 3*x + 4) + (x**5 + x**4 + 5*x**3 + 3*x**2 + \
|
| 546 |
+
2*x)*Dx, x, 0, {-2: [2, 3, 5]})
|
| 547 |
+
assert p == q
|
| 548 |
+
p = expr_to_holonomic(1/(x-1)**2, lenics=3, x0=1)
|
| 549 |
+
q = HolonomicFunction((2) + (x - 1)*Dx, x, 1, {-2: [1, 0, 0]})
|
| 550 |
+
assert p == q
|
| 551 |
+
a = symbols("a")
|
| 552 |
+
p = expr_to_holonomic(sqrt(a*x), x=x)
|
| 553 |
+
assert p.to_expr() == sqrt(a)*sqrt(x)
|
| 554 |
+
|
| 555 |
+
def test_to_hyper():
|
| 556 |
+
x = symbols('x')
|
| 557 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 558 |
+
p = HolonomicFunction(Dx - 2, x, 0, [3]).to_hyper()
|
| 559 |
+
q = 3 * hyper([], [], 2*x)
|
| 560 |
+
assert p == q
|
| 561 |
+
p = hyperexpand(HolonomicFunction((1 + x) * Dx - 3, x, 0, [2]).to_hyper()).expand()
|
| 562 |
+
q = 2*x**3 + 6*x**2 + 6*x + 2
|
| 563 |
+
assert p == q
|
| 564 |
+
p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_hyper()
|
| 565 |
+
q = -x**2*hyper((2, 2, 1), (3, 2), -x)/2 + x
|
| 566 |
+
assert p == q
|
| 567 |
+
p = HolonomicFunction(2*x*Dx + Dx**2, x, 0, [0, 2/sqrt(pi)]).to_hyper()
|
| 568 |
+
q = 2*x*hyper((S.Half,), (Rational(3, 2),), -x**2)/sqrt(pi)
|
| 569 |
+
assert p == q
|
| 570 |
+
p = hyperexpand(HolonomicFunction(2*x*Dx + Dx**2, x, 0, [1, -2/sqrt(pi)]).to_hyper())
|
| 571 |
+
q = erfc(x)
|
| 572 |
+
assert p.rewrite(erfc) == q
|
| 573 |
+
p = hyperexpand(HolonomicFunction((x**2 - 1) + x*Dx + x**2*Dx**2,
|
| 574 |
+
x, 0, [0, S.Half]).to_hyper())
|
| 575 |
+
q = besselj(1, x)
|
| 576 |
+
assert p == q
|
| 577 |
+
p = hyperexpand(HolonomicFunction(x*Dx**2 + Dx + x, x, 0, [1, 0]).to_hyper())
|
| 578 |
+
q = besselj(0, x)
|
| 579 |
+
assert p == q
|
| 580 |
+
|
| 581 |
+
def test_to_expr():
|
| 582 |
+
x = symbols('x')
|
| 583 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 584 |
+
p = HolonomicFunction(Dx - 1, x, 0, [1]).to_expr()
|
| 585 |
+
q = exp(x)
|
| 586 |
+
assert p == q
|
| 587 |
+
p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).to_expr()
|
| 588 |
+
q = cos(x)
|
| 589 |
+
assert p == q
|
| 590 |
+
p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0]).to_expr()
|
| 591 |
+
q = cosh(x)
|
| 592 |
+
assert p == q
|
| 593 |
+
p = HolonomicFunction(2 + (4*x - 1)*Dx + \
|
| 594 |
+
(x**2 - x)*Dx**2, x, 0, [1, 2]).to_expr().expand()
|
| 595 |
+
q = 1/(x**2 - 2*x + 1)
|
| 596 |
+
assert p == q
|
| 597 |
+
p = expr_to_holonomic(sin(x)**2/x).integrate((x, 0, x)).to_expr()
|
| 598 |
+
q = (sin(x)**2/x).integrate((x, 0, x))
|
| 599 |
+
assert p == q
|
| 600 |
+
C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3')
|
| 601 |
+
p = expr_to_holonomic(log(1+x**2)).to_expr()
|
| 602 |
+
q = C_2*log(x**2 + 1)
|
| 603 |
+
assert p == q
|
| 604 |
+
p = expr_to_holonomic(log(1+x**2)).diff().to_expr()
|
| 605 |
+
q = C_0*x/(x**2 + 1)
|
| 606 |
+
assert p == q
|
| 607 |
+
p = expr_to_holonomic(erf(x) + x).to_expr()
|
| 608 |
+
q = 3*C_3*x - 3*sqrt(pi)*C_3*erf(x)/2 + x + 2*x/sqrt(pi)
|
| 609 |
+
assert p == q
|
| 610 |
+
p = expr_to_holonomic(sqrt(x), x0=1).to_expr()
|
| 611 |
+
assert p == sqrt(x)
|
| 612 |
+
assert expr_to_holonomic(sqrt(x)).to_expr() == sqrt(x)
|
| 613 |
+
p = expr_to_holonomic(sqrt(1 + x**2)).to_expr()
|
| 614 |
+
assert p == sqrt(1+x**2)
|
| 615 |
+
p = expr_to_holonomic((2*x**2 + 1)**Rational(2, 3)).to_expr()
|
| 616 |
+
assert p == (2*x**2 + 1)**Rational(2, 3)
|
| 617 |
+
p = expr_to_holonomic(sqrt(-x**2+2*x)).to_expr()
|
| 618 |
+
assert p == sqrt(x)*sqrt(-x + 2)
|
| 619 |
+
p = expr_to_holonomic((-2*x**3+7*x)**Rational(2, 3)).to_expr()
|
| 620 |
+
q = x**Rational(2, 3)*(-2*x**2 + 7)**Rational(2, 3)
|
| 621 |
+
assert p == q
|
| 622 |
+
p = from_hyper(hyper((-2, -3), (S.Half, ), x))
|
| 623 |
+
s = hyperexpand(hyper((-2, -3), (S.Half, ), x))
|
| 624 |
+
D_0 = Symbol('D_0')
|
| 625 |
+
C_0 = Symbol('C_0')
|
| 626 |
+
assert (p.to_expr().subs({C_0:1, D_0:0}) - s).simplify() == 0
|
| 627 |
+
p.y0 = {0: [1], S.Half: [0]}
|
| 628 |
+
assert p.to_expr() == s
|
| 629 |
+
assert expr_to_holonomic(x**5).to_expr() == x**5
|
| 630 |
+
assert expr_to_holonomic(2*x**3-3*x**2).to_expr().expand() == \
|
| 631 |
+
2*x**3-3*x**2
|
| 632 |
+
a = symbols("a")
|
| 633 |
+
p = (expr_to_holonomic(1.4*x)*expr_to_holonomic(a*x, x)).to_expr()
|
| 634 |
+
q = 1.4*a*x**2
|
| 635 |
+
assert p == q
|
| 636 |
+
p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(a*x, x)).to_expr()
|
| 637 |
+
q = x*(a + 1.4)
|
| 638 |
+
assert p == q
|
| 639 |
+
p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(x)).to_expr()
|
| 640 |
+
assert p == 2.4*x
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def test_integrate():
|
| 644 |
+
x = symbols('x')
|
| 645 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 646 |
+
p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 2, 3))
|
| 647 |
+
q = '0.166270406994788'
|
| 648 |
+
assert sstr(p) == q
|
| 649 |
+
p = expr_to_holonomic(sin(x)).integrate((x, 0, x)).to_expr()
|
| 650 |
+
q = 1 - cos(x)
|
| 651 |
+
assert p == q
|
| 652 |
+
p = expr_to_holonomic(sin(x)).integrate((x, 0, 3))
|
| 653 |
+
q = 1 - cos(3)
|
| 654 |
+
assert p == q
|
| 655 |
+
p = expr_to_holonomic(sin(x)/x, x0=1).integrate((x, 1, 2))
|
| 656 |
+
q = '0.659329913368450'
|
| 657 |
+
assert sstr(p) == q
|
| 658 |
+
p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 1, 0))
|
| 659 |
+
q = '-0.423690480850035'
|
| 660 |
+
assert sstr(p) == q
|
| 661 |
+
p = expr_to_holonomic(sin(x)/x)
|
| 662 |
+
assert p.integrate(x).to_expr() == Si(x)
|
| 663 |
+
assert p.integrate((x, 0, 2)) == Si(2)
|
| 664 |
+
p = expr_to_holonomic(sin(x)**2/x)
|
| 665 |
+
q = p.to_expr()
|
| 666 |
+
assert p.integrate(x).to_expr() == q.integrate((x, 0, x))
|
| 667 |
+
assert p.integrate((x, 0, 1)) == q.integrate((x, 0, 1))
|
| 668 |
+
assert expr_to_holonomic(1/x, x0=1).integrate(x).to_expr() == log(x)
|
| 669 |
+
p = expr_to_holonomic((x + 1)**3*exp(-x), x0=-1).integrate(x).to_expr()
|
| 670 |
+
q = (-x**3 - 6*x**2 - 15*x + 6*exp(x + 1) - 16)*exp(-x)
|
| 671 |
+
assert p == q
|
| 672 |
+
p = expr_to_holonomic(cos(x)**2/x**2, y0={-2: [1, 0, -1]}).integrate(x).to_expr()
|
| 673 |
+
q = -Si(2*x) - cos(x)**2/x
|
| 674 |
+
assert p == q
|
| 675 |
+
p = expr_to_holonomic(sqrt(x**2+x)).integrate(x).to_expr()
|
| 676 |
+
q = (x**Rational(3, 2)*(2*x**2 + 3*x + 1) - x*sqrt(x + 1)*asinh(sqrt(x)))/(4*x*sqrt(x + 1))
|
| 677 |
+
assert p == q
|
| 678 |
+
p = expr_to_holonomic(sqrt(x**2+1)).integrate(x).to_expr()
|
| 679 |
+
q = (sqrt(x**2+1)).integrate(x)
|
| 680 |
+
assert (p-q).simplify() == 0
|
| 681 |
+
p = expr_to_holonomic(1/x**2, y0={-2:[1, 0, 0]})
|
| 682 |
+
r = expr_to_holonomic(1/x**2, lenics=3)
|
| 683 |
+
assert p == r
|
| 684 |
+
q = expr_to_holonomic(cos(x)**2)
|
| 685 |
+
assert (r*q).integrate(x).to_expr() == -Si(2*x) - cos(x)**2/x
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def test_diff():
|
| 689 |
+
x, y = symbols('x, y')
|
| 690 |
+
R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx')
|
| 691 |
+
p = HolonomicFunction(x*Dx**2 + 1, x, 0, [0, 1])
|
| 692 |
+
assert p.diff().to_expr() == p.to_expr().diff().simplify()
|
| 693 |
+
p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0])
|
| 694 |
+
assert p.diff(x, 2).to_expr() == p.to_expr()
|
| 695 |
+
p = expr_to_holonomic(Si(x))
|
| 696 |
+
assert p.diff().to_expr() == sin(x)/x
|
| 697 |
+
assert p.diff(y) == 0
|
| 698 |
+
C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3')
|
| 699 |
+
q = Si(x)
|
| 700 |
+
assert p.diff(x).to_expr() == q.diff()
|
| 701 |
+
assert p.diff(x, 2).to_expr().subs(C_0, Rational(-1, 3)).cancel() == q.diff(x, 2).cancel()
|
| 702 |
+
assert p.diff(x, 3).series().subs({C_3: Rational(-1, 3), C_0: 0}) == q.diff(x, 3).series()
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
def test_extended_domain_in_expr_to_holonomic():
|
| 706 |
+
x = symbols('x')
|
| 707 |
+
p = expr_to_holonomic(1.2*cos(3.1*x))
|
| 708 |
+
assert p.to_expr() == 1.2*cos(3.1*x)
|
| 709 |
+
assert sstr(p.integrate(x).to_expr()) == '0.387096774193548*sin(3.1*x)'
|
| 710 |
+
_, Dx = DifferentialOperators(RR.old_poly_ring(x), 'Dx')
|
| 711 |
+
p = expr_to_holonomic(1.1329138213*x)
|
| 712 |
+
q = HolonomicFunction((-1.1329138213) + (1.1329138213*x)*Dx, x, 0, {1: [1.1329138213]})
|
| 713 |
+
assert p == q
|
| 714 |
+
assert p.to_expr() == 1.1329138213*x
|
| 715 |
+
assert sstr(p.integrate((x, 1, 2))) == sstr((1.1329138213*x).integrate((x, 1, 2)))
|
| 716 |
+
y, z = symbols('y, z')
|
| 717 |
+
p = expr_to_holonomic(sin(x*y*z), x=x)
|
| 718 |
+
assert p.to_expr() == sin(x*y*z)
|
| 719 |
+
assert p.integrate(x).to_expr() == (-cos(x*y*z) + 1)/(y*z)
|
| 720 |
+
p = expr_to_holonomic(sin(x*y + z), x=x).integrate(x).to_expr()
|
| 721 |
+
q = (cos(z) - cos(x*y + z))/y
|
| 722 |
+
assert p == q
|
| 723 |
+
a = symbols('a')
|
| 724 |
+
p = expr_to_holonomic(a*x, x)
|
| 725 |
+
assert p.to_expr() == a*x
|
| 726 |
+
assert p.integrate(x).to_expr() == a*x**2/2
|
| 727 |
+
D_2, C_1 = symbols("D_2, C_1")
|
| 728 |
+
p = expr_to_holonomic(x) + expr_to_holonomic(1.2*cos(x))
|
| 729 |
+
p = p.to_expr().subs(D_2, 0)
|
| 730 |
+
assert p - x - 1.2*cos(1.0*x) == 0
|
| 731 |
+
p = expr_to_holonomic(x) * expr_to_holonomic(1.2*cos(x))
|
| 732 |
+
p = p.to_expr().subs(C_1, 0)
|
| 733 |
+
assert p - 1.2*x*cos(1.0*x) == 0
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def test_to_meijerg():
|
| 737 |
+
x = symbols('x')
|
| 738 |
+
assert hyperexpand(expr_to_holonomic(sin(x)).to_meijerg()) == sin(x)
|
| 739 |
+
assert hyperexpand(expr_to_holonomic(cos(x)).to_meijerg()) == cos(x)
|
| 740 |
+
assert hyperexpand(expr_to_holonomic(exp(x)).to_meijerg()) == exp(x)
|
| 741 |
+
assert hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify() == log(x)
|
| 742 |
+
assert expr_to_holonomic(4*x**2/3 + 7).to_meijerg() == 4*x**2/3 + 7
|
| 743 |
+
assert hyperexpand(expr_to_holonomic(besselj(2, x), lenics=3).to_meijerg()) == besselj(2, x)
|
| 744 |
+
p = hyper((Rational(-1, 2), -3), (), x)
|
| 745 |
+
assert from_hyper(p).to_meijerg() == hyperexpand(p)
|
| 746 |
+
p = hyper((S.One, S(3)), (S(2), ), x)
|
| 747 |
+
assert (hyperexpand(from_hyper(p).to_meijerg()) - hyperexpand(p)).expand() == 0
|
| 748 |
+
p = from_hyper(hyper((-2, -3), (S.Half, ), x))
|
| 749 |
+
s = hyperexpand(hyper((-2, -3), (S.Half, ), x))
|
| 750 |
+
C_0 = Symbol('C_0')
|
| 751 |
+
C_1 = Symbol('C_1')
|
| 752 |
+
D_0 = Symbol('D_0')
|
| 753 |
+
assert (hyperexpand(p.to_meijerg()).subs({C_0:1, D_0:0}) - s).simplify() == 0
|
| 754 |
+
p.y0 = {0: [1], S.Half: [0]}
|
| 755 |
+
assert (hyperexpand(p.to_meijerg()) - s).simplify() == 0
|
| 756 |
+
p = expr_to_holonomic(besselj(S.Half, x), initcond=False)
|
| 757 |
+
assert (p.to_expr() - (D_0*sin(x) + C_0*cos(x) + C_1*sin(x))/sqrt(x)).simplify() == 0
|
| 758 |
+
p = expr_to_holonomic(besselj(S.Half, x), y0={Rational(-1, 2): [sqrt(2)/sqrt(pi), sqrt(2)/sqrt(pi)]})
|
| 759 |
+
assert (p.to_expr() - besselj(S.Half, x) - besselj(Rational(-1, 2), x)).simplify() == 0
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def test_gaussian():
|
| 763 |
+
mu, x = symbols("mu x")
|
| 764 |
+
sd = symbols("sd", positive=True)
|
| 765 |
+
Q = QQ[mu, sd].get_field()
|
| 766 |
+
e = sqrt(2)*exp(-(-mu + x)**2/(2*sd**2))/(2*sqrt(pi)*sd)
|
| 767 |
+
h1 = expr_to_holonomic(e, x, domain=Q)
|
| 768 |
+
|
| 769 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
| 770 |
+
h2 = HolonomicFunction((-mu/sd**2 + x/sd**2) + (1)*Dx, x)
|
| 771 |
+
|
| 772 |
+
assert h1 == h2
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def test_beta():
|
| 776 |
+
a, b, x = symbols("a b x", positive=True)
|
| 777 |
+
e = x**(a - 1)*(-x + 1)**(b - 1)/beta(a, b)
|
| 778 |
+
Q = QQ[a, b].get_field()
|
| 779 |
+
h1 = expr_to_holonomic(e, x, domain=Q)
|
| 780 |
+
|
| 781 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
| 782 |
+
h2 = HolonomicFunction((a + x*(-a - b + 2) - 1) + (x**2 - x)*Dx, x)
|
| 783 |
+
|
| 784 |
+
assert h1 == h2
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
def test_gamma():
|
| 788 |
+
a, b, x = symbols("a b x", positive=True)
|
| 789 |
+
e = b**(-a)*x**(a - 1)*exp(-x/b)/gamma(a)
|
| 790 |
+
Q = QQ[a, b].get_field()
|
| 791 |
+
h1 = expr_to_holonomic(e, x, domain=Q)
|
| 792 |
+
|
| 793 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
| 794 |
+
h2 = HolonomicFunction((-a + 1 + x/b) + (x)*Dx, x)
|
| 795 |
+
|
| 796 |
+
assert h1 == h2
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
def test_symbolic_power():
|
| 800 |
+
x, n = symbols("x n")
|
| 801 |
+
Q = QQ[n].get_field()
|
| 802 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
| 803 |
+
h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -n
|
| 804 |
+
h2 = HolonomicFunction((n) + (x)*Dx, x)
|
| 805 |
+
|
| 806 |
+
assert h1 == h2
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def test_negative_power():
|
| 810 |
+
x = symbols("x")
|
| 811 |
+
_, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 812 |
+
h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -2
|
| 813 |
+
h2 = HolonomicFunction((2) + (x)*Dx, x)
|
| 814 |
+
|
| 815 |
+
assert h1 == h2
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def test_expr_in_power():
|
| 819 |
+
x, n = symbols("x n")
|
| 820 |
+
Q = QQ[n].get_field()
|
| 821 |
+
_, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
|
| 822 |
+
h1 = HolonomicFunction((-1) + (x)*Dx, x) ** (n - 3)
|
| 823 |
+
h2 = HolonomicFunction((-n + 3) + (x)*Dx, x)
|
| 824 |
+
|
| 825 |
+
assert h1 == h2
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
def test_DifferentialOperatorEqPoly():
|
| 829 |
+
x = symbols('x', integer=True)
|
| 830 |
+
R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 831 |
+
do = DifferentialOperator([x**2, R.base.zero, R.base.zero], R)
|
| 832 |
+
do2 = DifferentialOperator([x**2, 1, x], R)
|
| 833 |
+
assert not do == do2
|
| 834 |
+
|
| 835 |
+
# polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799
|
| 836 |
+
# should work once that is solved
|
| 837 |
+
# p = do.listofpoly[0]
|
| 838 |
+
# assert do == p
|
| 839 |
+
|
| 840 |
+
p2 = do2.listofpoly[0]
|
| 841 |
+
assert not do2 == p2
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
def test_DifferentialOperatorPow():
|
| 845 |
+
x = symbols('x', integer=True)
|
| 846 |
+
R, _ = DifferentialOperators(QQ.old_poly_ring(x), 'Dx')
|
| 847 |
+
do = DifferentialOperator([x**2, R.base.zero, R.base.zero], R)
|
| 848 |
+
a = DifferentialOperator([R.base.one], R)
|
| 849 |
+
for n in range(10):
|
| 850 |
+
assert a == do**n
|
| 851 |
+
a *= do
|
.venv/lib/python3.12/site-packages/sympy/holonomic/tests/test_recurrence.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.holonomic.recurrence import RecurrenceOperators, RecurrenceOperator
|
| 2 |
+
from sympy.core.symbol import symbols
|
| 3 |
+
from sympy.polys.domains.rationalfield import QQ
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_RecurrenceOperator():
|
| 7 |
+
n = symbols('n', integer=True)
|
| 8 |
+
R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
|
| 9 |
+
assert Sn*n == (n + 1)*Sn
|
| 10 |
+
assert Sn*n**2 == (n**2+1+2*n)*Sn
|
| 11 |
+
assert Sn**2*n**2 == (n**2 + 4*n + 4)*Sn**2
|
| 12 |
+
p = (Sn**3*n**2 + Sn*n)**2
|
| 13 |
+
q = (n**2 + 3*n + 2)*Sn**2 + (2*n**3 + 19*n**2 + 57*n + 52)*Sn**4 + (n**4 + 18*n**3 + \
|
| 14 |
+
117*n**2 + 324*n + 324)*Sn**6
|
| 15 |
+
assert p == q
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_RecurrenceOperatorEqPoly():
|
| 19 |
+
n = symbols('n', integer=True)
|
| 20 |
+
R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
|
| 21 |
+
rr = RecurrenceOperator([n**2, 0, 0], R)
|
| 22 |
+
rr2 = RecurrenceOperator([n**2, 1, n], R)
|
| 23 |
+
assert not rr == rr2
|
| 24 |
+
|
| 25 |
+
# polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799
|
| 26 |
+
# should work once that is solved
|
| 27 |
+
# d = rr.listofpoly[0]
|
| 28 |
+
# assert rr == d
|
| 29 |
+
|
| 30 |
+
d2 = rr2.listofpoly[0]
|
| 31 |
+
assert not rr2 == d2
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_RecurrenceOperatorPow():
|
| 35 |
+
n = symbols('n', integer=True)
|
| 36 |
+
R, _ = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn')
|
| 37 |
+
rr = RecurrenceOperator([n**2, 0, 0], R)
|
| 38 |
+
a = RecurrenceOperator([R.base.one], R)
|
| 39 |
+
for m in range(10):
|
| 40 |
+
assert a == rr**m
|
| 41 |
+
a *= rr
|
.venv/lib/python3.12/site-packages/sympy/integrals/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
laplace_correspondence, laplace_initial_conds,
|
| 18 |
+
LaplaceTransform, InverseLaplaceTransform,
|
| 19 |
+
fourier_transform, inverse_fourier_transform,
|
| 20 |
+
FourierTransform, InverseFourierTransform,
|
| 21 |
+
sine_transform, inverse_sine_transform,
|
| 22 |
+
SineTransform, InverseSineTransform,
|
| 23 |
+
cosine_transform, inverse_cosine_transform,
|
| 24 |
+
CosineTransform, InverseCosineTransform,
|
| 25 |
+
hankel_transform, inverse_hankel_transform,
|
| 26 |
+
HankelTransform, InverseHankelTransform)
|
| 27 |
+
from .singularityfunctions import singularityintegrate
|
| 28 |
+
|
| 29 |
+
__all__ = [
|
| 30 |
+
'integrate', 'Integral', 'line_integrate',
|
| 31 |
+
|
| 32 |
+
'mellin_transform', 'inverse_mellin_transform', 'MellinTransform',
|
| 33 |
+
'InverseMellinTransform', 'laplace_transform',
|
| 34 |
+
'inverse_laplace_transform', 'LaplaceTransform',
|
| 35 |
+
'laplace_correspondence', 'laplace_initial_conds',
|
| 36 |
+
'InverseLaplaceTransform', 'fourier_transform',
|
| 37 |
+
'inverse_fourier_transform', 'FourierTransform',
|
| 38 |
+
'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform',
|
| 39 |
+
'SineTransform', 'InverseSineTransform', 'cosine_transform',
|
| 40 |
+
'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform',
|
| 41 |
+
'hankel_transform', 'inverse_hankel_transform', 'HankelTransform',
|
| 42 |
+
'InverseHankelTransform',
|
| 43 |
+
|
| 44 |
+
'singularityintegrate',
|
| 45 |
+
]
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.64 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/deltafunctions.cpython-312.pyc
ADDED
|
Binary file (7.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/heurisch.cpython-312.pyc
ADDED
|
Binary file (35.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/integrals.cpython-312.pyc
ADDED
|
Binary file (66 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/intpoly.cpython-312.pyc
ADDED
|
Binary file (52.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/laplace.cpython-312.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2494ac24fb5bf03e53564bb0b90f136949c2863bc87e732b1cae4f9bc50ef33e
|
| 3 |
+
size 124863
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/manualintegrate.cpython-312.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:503f971f4c45ae2080e82adbd09c166459250849540c02bc519c9c5bb1ffe93a
|
| 3 |
+
size 117491
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/meijerint.cpython-312.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b6abcea71af32513766dffb63251c1ffa605eccb083bbb7eb41a3c7eca700f8
|
| 3 |
+
size 113464
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/meijerint_doc.cpython-312.pyc
ADDED
|
Binary file (2.06 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/prde.cpython-312.pyc
ADDED
|
Binary file (67.9 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/quadrature.cpython-312.pyc
ADDED
|
Binary file (21.9 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/rationaltools.cpython-312.pyc
ADDED
|
Binary file (16.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/rde.cpython-312.pyc
ADDED
|
Binary file (36.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/risch.cpython-312.pyc
ADDED
|
Binary file (87.8 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/singularityfunctions.cpython-312.pyc
ADDED
|
Binary file (2.76 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/transforms.cpython-312.pyc
ADDED
|
Binary file (64.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/__pycache__/trigonometry.cpython-312.pyc
ADDED
|
Binary file (7.87 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (201 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/__pycache__/bench_integrate.cpython-312.pyc
ADDED
|
Binary file (1.23 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/sympy/integrals/benchmarks/__pycache__/bench_trigintegrate.cpython-312.pyc
ADDED
|
Binary file (836 Bytes). View file
|
|
|
.venv/lib/python3.12/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.12/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.12/site-packages/sympy/integrals/deltafunctions.py
ADDED
|
@@ -0,0 +1,201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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.12/site-packages/sympy/integrals/heurisch.py
ADDED
|
@@ -0,0 +1,781 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from functools import reduce
|
| 5 |
+
from itertools import permutations
|
| 6 |
+
|
| 7 |
+
from sympy.core.add import Add
|
| 8 |
+
from sympy.core.basic import Basic
|
| 9 |
+
from sympy.core.mul import Mul
|
| 10 |
+
from sympy.core.symbol import Wild, Dummy, Symbol
|
| 11 |
+
from sympy.core.basic import sympify
|
| 12 |
+
from sympy.core.numbers import Rational, pi, I
|
| 13 |
+
from sympy.core.relational import Eq, Ne
|
| 14 |
+
from sympy.core.singleton import S
|
| 15 |
+
from sympy.core.sorting import ordered
|
| 16 |
+
from sympy.core.traversal import iterfreeargs
|
| 17 |
+
|
| 18 |
+
from sympy.functions import exp, sin, cos, tan, cot, asin, atan
|
| 19 |
+
from sympy.functions import log, sinh, cosh, tanh, coth, asinh
|
| 20 |
+
from sympy.functions import sqrt, erf, erfi, li, Ei
|
| 21 |
+
from sympy.functions import besselj, bessely, besseli, besselk
|
| 22 |
+
from sympy.functions import hankel1, hankel2, jn, yn
|
| 23 |
+
from sympy.functions.elementary.complexes import Abs, re, im, sign, arg
|
| 24 |
+
from sympy.functions.elementary.exponential import LambertW
|
| 25 |
+
from sympy.functions.elementary.integers import floor, ceiling
|
| 26 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 27 |
+
from sympy.functions.special.delta_functions import Heaviside, DiracDelta
|
| 28 |
+
|
| 29 |
+
from sympy.simplify.radsimp import collect
|
| 30 |
+
|
| 31 |
+
from sympy.logic.boolalg import And, Or
|
| 32 |
+
from sympy.utilities.iterables import uniq
|
| 33 |
+
|
| 34 |
+
from sympy.polys import quo, gcd, lcm, factor_list, cancel, PolynomialError
|
| 35 |
+
from sympy.polys.monomials import itermonomials
|
| 36 |
+
from sympy.polys.polyroots import root_factors
|
| 37 |
+
|
| 38 |
+
from sympy.polys.rings import PolyRing
|
| 39 |
+
from sympy.polys.solvers import solve_lin_sys
|
| 40 |
+
from sympy.polys.constructor import construct_domain
|
| 41 |
+
|
| 42 |
+
from sympy.integrals.integrals import integrate
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def components(f, x):
|
| 46 |
+
"""
|
| 47 |
+
Returns a set of all functional components of the given expression
|
| 48 |
+
which includes symbols, function applications and compositions and
|
| 49 |
+
non-integer powers. Fractional powers are collected with
|
| 50 |
+
minimal, positive exponents.
|
| 51 |
+
|
| 52 |
+
Examples
|
| 53 |
+
========
|
| 54 |
+
|
| 55 |
+
>>> from sympy import cos, sin
|
| 56 |
+
>>> from sympy.abc import x
|
| 57 |
+
>>> from sympy.integrals.heurisch import components
|
| 58 |
+
|
| 59 |
+
>>> components(sin(x)*cos(x)**2, x)
|
| 60 |
+
{x, sin(x), cos(x)}
|
| 61 |
+
|
| 62 |
+
See Also
|
| 63 |
+
========
|
| 64 |
+
|
| 65 |
+
heurisch
|
| 66 |
+
"""
|
| 67 |
+
result = set()
|
| 68 |
+
|
| 69 |
+
if f.has_free(x):
|
| 70 |
+
if f.is_symbol and f.is_commutative:
|
| 71 |
+
result.add(f)
|
| 72 |
+
elif f.is_Function or f.is_Derivative:
|
| 73 |
+
for g in f.args:
|
| 74 |
+
result |= components(g, x)
|
| 75 |
+
|
| 76 |
+
result.add(f)
|
| 77 |
+
elif f.is_Pow:
|
| 78 |
+
result |= components(f.base, x)
|
| 79 |
+
|
| 80 |
+
if not f.exp.is_Integer:
|
| 81 |
+
if f.exp.is_Rational:
|
| 82 |
+
result.add(f.base**Rational(1, f.exp.q))
|
| 83 |
+
else:
|
| 84 |
+
result |= components(f.exp, x) | {f}
|
| 85 |
+
else:
|
| 86 |
+
for g in f.args:
|
| 87 |
+
result |= components(g, x)
|
| 88 |
+
|
| 89 |
+
return result
|
| 90 |
+
|
| 91 |
+
# name -> [] of symbols
|
| 92 |
+
_symbols_cache: dict[str, list[Dummy]] = {}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# NB @cacheit is not convenient here
|
| 96 |
+
def _symbols(name, n):
|
| 97 |
+
"""get vector of symbols local to this module"""
|
| 98 |
+
try:
|
| 99 |
+
lsyms = _symbols_cache[name]
|
| 100 |
+
except KeyError:
|
| 101 |
+
lsyms = []
|
| 102 |
+
_symbols_cache[name] = lsyms
|
| 103 |
+
|
| 104 |
+
while len(lsyms) < n:
|
| 105 |
+
lsyms.append( Dummy('%s%i' % (name, len(lsyms))) )
|
| 106 |
+
|
| 107 |
+
return lsyms[:n]
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def heurisch_wrapper(f, x, rewrite=False, hints=None, mappings=None, retries=3,
|
| 111 |
+
degree_offset=0, unnecessary_permutations=None,
|
| 112 |
+
_try_heurisch=None):
|
| 113 |
+
"""
|
| 114 |
+
A wrapper around the heurisch integration algorithm.
|
| 115 |
+
|
| 116 |
+
Explanation
|
| 117 |
+
===========
|
| 118 |
+
|
| 119 |
+
This method takes the result from heurisch and checks for poles in the
|
| 120 |
+
denominator. For each of these poles, the integral is reevaluated, and
|
| 121 |
+
the final integration result is given in terms of a Piecewise.
|
| 122 |
+
|
| 123 |
+
Examples
|
| 124 |
+
========
|
| 125 |
+
|
| 126 |
+
>>> from sympy import cos, symbols
|
| 127 |
+
>>> from sympy.integrals.heurisch import heurisch, heurisch_wrapper
|
| 128 |
+
>>> n, x = symbols('n x')
|
| 129 |
+
>>> heurisch(cos(n*x), x)
|
| 130 |
+
sin(n*x)/n
|
| 131 |
+
>>> heurisch_wrapper(cos(n*x), x)
|
| 132 |
+
Piecewise((sin(n*x)/n, Ne(n, 0)), (x, True))
|
| 133 |
+
|
| 134 |
+
See Also
|
| 135 |
+
========
|
| 136 |
+
|
| 137 |
+
heurisch
|
| 138 |
+
"""
|
| 139 |
+
from sympy.solvers.solvers import solve, denoms
|
| 140 |
+
f = sympify(f)
|
| 141 |
+
if not f.has_free(x):
|
| 142 |
+
return f*x
|
| 143 |
+
|
| 144 |
+
res = heurisch(f, x, rewrite, hints, mappings, retries, degree_offset,
|
| 145 |
+
unnecessary_permutations, _try_heurisch)
|
| 146 |
+
if not isinstance(res, Basic):
|
| 147 |
+
return res
|
| 148 |
+
|
| 149 |
+
# We consider each denominator in the expression, and try to find
|
| 150 |
+
# cases where one or more symbolic denominator might be zero. The
|
| 151 |
+
# conditions for these cases are stored in the list slns.
|
| 152 |
+
#
|
| 153 |
+
# Since denoms returns a set we use ordered. This is important because the
|
| 154 |
+
# ordering of slns determines the order of the resulting Piecewise so we
|
| 155 |
+
# need a deterministic order here to make the output deterministic.
|
| 156 |
+
slns = []
|
| 157 |
+
for d in ordered(denoms(res)):
|
| 158 |
+
try:
|
| 159 |
+
slns += solve([d], dict=True, exclude=(x,))
|
| 160 |
+
except NotImplementedError:
|
| 161 |
+
pass
|
| 162 |
+
if not slns:
|
| 163 |
+
return res
|
| 164 |
+
slns = list(uniq(slns))
|
| 165 |
+
# Remove the solutions corresponding to poles in the original expression.
|
| 166 |
+
slns0 = []
|
| 167 |
+
for d in denoms(f):
|
| 168 |
+
try:
|
| 169 |
+
slns0 += solve([d], dict=True, exclude=(x,))
|
| 170 |
+
except NotImplementedError:
|
| 171 |
+
pass
|
| 172 |
+
slns = [s for s in slns if s not in slns0]
|
| 173 |
+
if not slns:
|
| 174 |
+
return res
|
| 175 |
+
if len(slns) > 1:
|
| 176 |
+
eqs = []
|
| 177 |
+
for sub_dict in slns:
|
| 178 |
+
eqs.extend([Eq(key, value) for key, value in sub_dict.items()])
|
| 179 |
+
slns = solve(eqs, dict=True, exclude=(x,)) + slns
|
| 180 |
+
# For each case listed in the list slns, we reevaluate the integral.
|
| 181 |
+
pairs = []
|
| 182 |
+
for sub_dict in slns:
|
| 183 |
+
expr = heurisch(f.subs(sub_dict), x, rewrite, hints, mappings, retries,
|
| 184 |
+
degree_offset, unnecessary_permutations,
|
| 185 |
+
_try_heurisch)
|
| 186 |
+
cond = And(*[Eq(key, value) for key, value in sub_dict.items()])
|
| 187 |
+
generic = Or(*[Ne(key, value) for key, value in sub_dict.items()])
|
| 188 |
+
if expr is None:
|
| 189 |
+
expr = integrate(f.subs(sub_dict),x)
|
| 190 |
+
pairs.append((expr, cond))
|
| 191 |
+
# If there is one condition, put the generic case first. Otherwise,
|
| 192 |
+
# doing so may lead to longer Piecewise formulas
|
| 193 |
+
if len(pairs) == 1:
|
| 194 |
+
pairs = [(heurisch(f, x, rewrite, hints, mappings, retries,
|
| 195 |
+
degree_offset, unnecessary_permutations,
|
| 196 |
+
_try_heurisch),
|
| 197 |
+
generic),
|
| 198 |
+
(pairs[0][0], True)]
|
| 199 |
+
else:
|
| 200 |
+
pairs.append((heurisch(f, x, rewrite, hints, mappings, retries,
|
| 201 |
+
degree_offset, unnecessary_permutations,
|
| 202 |
+
_try_heurisch),
|
| 203 |
+
True))
|
| 204 |
+
return Piecewise(*pairs)
|
| 205 |
+
|
| 206 |
+
class BesselTable:
|
| 207 |
+
"""
|
| 208 |
+
Derivatives of Bessel functions of orders n and n-1
|
| 209 |
+
in terms of each other.
|
| 210 |
+
|
| 211 |
+
See the docstring of DiffCache.
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
def __init__(self):
|
| 215 |
+
self.table = {}
|
| 216 |
+
self.n = Dummy('n')
|
| 217 |
+
self.z = Dummy('z')
|
| 218 |
+
self._create_table()
|
| 219 |
+
|
| 220 |
+
def _create_table(t):
|
| 221 |
+
table, n, z = t.table, t.n, t.z
|
| 222 |
+
for f in (besselj, bessely, hankel1, hankel2):
|
| 223 |
+
table[f] = (f(n-1, z) - n*f(n, z)/z,
|
| 224 |
+
(n-1)*f(n-1, z)/z - f(n, z))
|
| 225 |
+
|
| 226 |
+
f = besseli
|
| 227 |
+
table[f] = (f(n-1, z) - n*f(n, z)/z,
|
| 228 |
+
(n-1)*f(n-1, z)/z + f(n, z))
|
| 229 |
+
f = besselk
|
| 230 |
+
table[f] = (-f(n-1, z) - n*f(n, z)/z,
|
| 231 |
+
(n-1)*f(n-1, z)/z - f(n, z))
|
| 232 |
+
|
| 233 |
+
for f in (jn, yn):
|
| 234 |
+
table[f] = (f(n-1, z) - (n+1)*f(n, z)/z,
|
| 235 |
+
(n-1)*f(n-1, z)/z - f(n, z))
|
| 236 |
+
|
| 237 |
+
def diffs(t, f, n, z):
|
| 238 |
+
if f in t.table:
|
| 239 |
+
diff0, diff1 = t.table[f]
|
| 240 |
+
repl = [(t.n, n), (t.z, z)]
|
| 241 |
+
return (diff0.subs(repl), diff1.subs(repl))
|
| 242 |
+
|
| 243 |
+
def has(t, f):
|
| 244 |
+
return f in t.table
|
| 245 |
+
|
| 246 |
+
_bessel_table = None
|
| 247 |
+
|
| 248 |
+
class DiffCache:
|
| 249 |
+
"""
|
| 250 |
+
Store for derivatives of expressions.
|
| 251 |
+
|
| 252 |
+
Explanation
|
| 253 |
+
===========
|
| 254 |
+
|
| 255 |
+
The standard form of the derivative of a Bessel function of order n
|
| 256 |
+
contains two Bessel functions of orders n-1 and n+1, respectively.
|
| 257 |
+
Such forms cannot be used in parallel Risch algorithm, because
|
| 258 |
+
there is a linear recurrence relation between the three functions
|
| 259 |
+
while the algorithm expects that functions and derivatives are
|
| 260 |
+
represented in terms of algebraically independent transcendentals.
|
| 261 |
+
|
| 262 |
+
The solution is to take two of the functions, e.g., those of orders
|
| 263 |
+
n and n-1, and to express the derivatives in terms of the pair.
|
| 264 |
+
To guarantee that the proper form is used the two derivatives are
|
| 265 |
+
cached as soon as one is encountered.
|
| 266 |
+
|
| 267 |
+
Derivatives of other functions are also cached at no extra cost.
|
| 268 |
+
All derivatives are with respect to the same variable `x`.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
def __init__(self, x):
|
| 272 |
+
self.cache = {}
|
| 273 |
+
self.x = x
|
| 274 |
+
|
| 275 |
+
global _bessel_table
|
| 276 |
+
if not _bessel_table:
|
| 277 |
+
_bessel_table = BesselTable()
|
| 278 |
+
|
| 279 |
+
def get_diff(self, f):
|
| 280 |
+
cache = self.cache
|
| 281 |
+
|
| 282 |
+
if f in cache:
|
| 283 |
+
pass
|
| 284 |
+
elif (not hasattr(f, 'func') or
|
| 285 |
+
not _bessel_table.has(f.func)):
|
| 286 |
+
cache[f] = cancel(f.diff(self.x))
|
| 287 |
+
else:
|
| 288 |
+
n, z = f.args
|
| 289 |
+
d0, d1 = _bessel_table.diffs(f.func, n, z)
|
| 290 |
+
dz = self.get_diff(z)
|
| 291 |
+
cache[f] = d0*dz
|
| 292 |
+
cache[f.func(n-1, z)] = d1*dz
|
| 293 |
+
|
| 294 |
+
return cache[f]
|
| 295 |
+
|
| 296 |
+
def heurisch(f, x, rewrite=False, hints=None, mappings=None, retries=3,
|
| 297 |
+
degree_offset=0, unnecessary_permutations=None,
|
| 298 |
+
_try_heurisch=None):
|
| 299 |
+
"""
|
| 300 |
+
Compute indefinite integral using heuristic Risch algorithm.
|
| 301 |
+
|
| 302 |
+
Explanation
|
| 303 |
+
===========
|
| 304 |
+
|
| 305 |
+
This is a heuristic approach to indefinite integration in finite
|
| 306 |
+
terms using the extended heuristic (parallel) Risch algorithm, based
|
| 307 |
+
on Manuel Bronstein's "Poor Man's Integrator".
|
| 308 |
+
|
| 309 |
+
The algorithm supports various classes of functions including
|
| 310 |
+
transcendental elementary or special functions like Airy,
|
| 311 |
+
Bessel, Whittaker and Lambert.
|
| 312 |
+
|
| 313 |
+
Note that this algorithm is not a decision procedure. If it isn't
|
| 314 |
+
able to compute the antiderivative for a given function, then this is
|
| 315 |
+
not a proof that such a functions does not exist. One should use
|
| 316 |
+
recursive Risch algorithm in such case. It's an open question if
|
| 317 |
+
this algorithm can be made a full decision procedure.
|
| 318 |
+
|
| 319 |
+
This is an internal integrator procedure. You should use top level
|
| 320 |
+
'integrate' function in most cases, as this procedure needs some
|
| 321 |
+
preprocessing steps and otherwise may fail.
|
| 322 |
+
|
| 323 |
+
Specification
|
| 324 |
+
=============
|
| 325 |
+
|
| 326 |
+
heurisch(f, x, rewrite=False, hints=None)
|
| 327 |
+
|
| 328 |
+
where
|
| 329 |
+
f : expression
|
| 330 |
+
x : symbol
|
| 331 |
+
|
| 332 |
+
rewrite -> force rewrite 'f' in terms of 'tan' and 'tanh'
|
| 333 |
+
hints -> a list of functions that may appear in anti-derivate
|
| 334 |
+
|
| 335 |
+
- hints = None --> no suggestions at all
|
| 336 |
+
- hints = [ ] --> try to figure out
|
| 337 |
+
- hints = [f1, ..., fn] --> we know better
|
| 338 |
+
|
| 339 |
+
Examples
|
| 340 |
+
========
|
| 341 |
+
|
| 342 |
+
>>> from sympy import tan
|
| 343 |
+
>>> from sympy.integrals.heurisch import heurisch
|
| 344 |
+
>>> from sympy.abc import x, y
|
| 345 |
+
|
| 346 |
+
>>> heurisch(y*tan(x), x)
|
| 347 |
+
y*log(tan(x)**2 + 1)/2
|
| 348 |
+
|
| 349 |
+
See Manuel Bronstein's "Poor Man's Integrator":
|
| 350 |
+
|
| 351 |
+
References
|
| 352 |
+
==========
|
| 353 |
+
|
| 354 |
+
.. [1] https://www-sop.inria.fr/cafe/Manuel.Bronstein/pmint/index.html
|
| 355 |
+
|
| 356 |
+
For more information on the implemented algorithm refer to:
|
| 357 |
+
|
| 358 |
+
.. [2] K. Geddes, L. Stefanus, On the Risch-Norman Integration
|
| 359 |
+
Method and its Implementation in Maple, Proceedings of
|
| 360 |
+
ISSAC'89, ACM Press, 212-217.
|
| 361 |
+
|
| 362 |
+
.. [3] J. H. Davenport, On the Parallel Risch Algorithm (I),
|
| 363 |
+
Proceedings of EUROCAM'82, LNCS 144, Springer, 144-157.
|
| 364 |
+
|
| 365 |
+
.. [4] J. H. Davenport, On the Parallel Risch Algorithm (III):
|
| 366 |
+
Use of Tangents, SIGSAM Bulletin 16 (1982), 3-6.
|
| 367 |
+
|
| 368 |
+
.. [5] J. H. Davenport, B. M. Trager, On the Parallel Risch
|
| 369 |
+
Algorithm (II), ACM Transactions on Mathematical
|
| 370 |
+
Software 11 (1985), 356-362.
|
| 371 |
+
|
| 372 |
+
See Also
|
| 373 |
+
========
|
| 374 |
+
|
| 375 |
+
sympy.integrals.integrals.Integral.doit
|
| 376 |
+
sympy.integrals.integrals.Integral
|
| 377 |
+
sympy.integrals.heurisch.components
|
| 378 |
+
"""
|
| 379 |
+
f = sympify(f)
|
| 380 |
+
|
| 381 |
+
# There are some functions that Heurisch cannot currently handle,
|
| 382 |
+
# so do not even try.
|
| 383 |
+
# Set _try_heurisch=True to skip this check
|
| 384 |
+
if _try_heurisch is not True:
|
| 385 |
+
if f.has(Abs, re, im, sign, Heaviside, DiracDelta, floor, ceiling, arg):
|
| 386 |
+
return
|
| 387 |
+
|
| 388 |
+
if not f.has_free(x):
|
| 389 |
+
return f*x
|
| 390 |
+
|
| 391 |
+
if not f.is_Add:
|
| 392 |
+
indep, f = f.as_independent(x)
|
| 393 |
+
else:
|
| 394 |
+
indep = S.One
|
| 395 |
+
|
| 396 |
+
rewritables = {
|
| 397 |
+
(sin, cos, cot): tan,
|
| 398 |
+
(sinh, cosh, coth): tanh,
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
if rewrite:
|
| 402 |
+
for candidates, rule in rewritables.items():
|
| 403 |
+
f = f.rewrite(candidates, rule)
|
| 404 |
+
else:
|
| 405 |
+
for candidates in rewritables.keys():
|
| 406 |
+
if f.has(*candidates):
|
| 407 |
+
break
|
| 408 |
+
else:
|
| 409 |
+
rewrite = True
|
| 410 |
+
|
| 411 |
+
terms = components(f, x)
|
| 412 |
+
dcache = DiffCache(x)
|
| 413 |
+
|
| 414 |
+
if hints is not None:
|
| 415 |
+
if not hints:
|
| 416 |
+
a = Wild('a', exclude=[x])
|
| 417 |
+
b = Wild('b', exclude=[x])
|
| 418 |
+
c = Wild('c', exclude=[x])
|
| 419 |
+
|
| 420 |
+
for g in set(terms): # using copy of terms
|
| 421 |
+
if g.is_Function:
|
| 422 |
+
if isinstance(g, li):
|
| 423 |
+
M = g.args[0].match(a*x**b)
|
| 424 |
+
|
| 425 |
+
if M is not None:
|
| 426 |
+
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])) )
|
| 427 |
+
#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])) )
|
| 428 |
+
#terms.add( x*(li(M[a]*x**M[b]) - x*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) )
|
| 429 |
+
#terms.add( li(M[a]*x**M[b]) - Ei((M[b]+1)*log(M[a]*x**M[b])/M[b]) )
|
| 430 |
+
|
| 431 |
+
elif isinstance(g, exp):
|
| 432 |
+
M = g.args[0].match(a*x**2)
|
| 433 |
+
|
| 434 |
+
if M is not None:
|
| 435 |
+
if M[a].is_positive:
|
| 436 |
+
terms.add(erfi(sqrt(M[a])*x))
|
| 437 |
+
else: # M[a].is_negative or unknown
|
| 438 |
+
terms.add(erf(sqrt(-M[a])*x))
|
| 439 |
+
|
| 440 |
+
M = g.args[0].match(a*x**2 + b*x + c)
|
| 441 |
+
|
| 442 |
+
if M is not None:
|
| 443 |
+
if M[a].is_positive:
|
| 444 |
+
terms.add(sqrt(pi/4*(-M[a]))*exp(M[c] - M[b]**2/(4*M[a]))*
|
| 445 |
+
erfi(sqrt(M[a])*x + M[b]/(2*sqrt(M[a]))))
|
| 446 |
+
elif M[a].is_negative:
|
| 447 |
+
terms.add(sqrt(pi/4*(-M[a]))*exp(M[c] - M[b]**2/(4*M[a]))*
|
| 448 |
+
erf(sqrt(-M[a])*x - M[b]/(2*sqrt(-M[a]))))
|
| 449 |
+
|
| 450 |
+
M = g.args[0].match(a*log(x)**2)
|
| 451 |
+
|
| 452 |
+
if M is not None:
|
| 453 |
+
if M[a].is_positive:
|
| 454 |
+
terms.add(erfi(sqrt(M[a])*log(x) + 1/(2*sqrt(M[a]))))
|
| 455 |
+
if M[a].is_negative:
|
| 456 |
+
terms.add(erf(sqrt(-M[a])*log(x) - 1/(2*sqrt(-M[a]))))
|
| 457 |
+
|
| 458 |
+
elif g.is_Pow:
|
| 459 |
+
if g.exp.is_Rational and g.exp.q == 2:
|
| 460 |
+
M = g.base.match(a*x**2 + b)
|
| 461 |
+
|
| 462 |
+
if M is not None and M[b].is_positive:
|
| 463 |
+
if M[a].is_positive:
|
| 464 |
+
terms.add(asinh(sqrt(M[a]/M[b])*x))
|
| 465 |
+
elif M[a].is_negative:
|
| 466 |
+
terms.add(asin(sqrt(-M[a]/M[b])*x))
|
| 467 |
+
|
| 468 |
+
M = g.base.match(a*x**2 - b)
|
| 469 |
+
|
| 470 |
+
if M is not None and M[b].is_positive:
|
| 471 |
+
if M[a].is_positive:
|
| 472 |
+
dF = 1/sqrt(M[a]*x**2 - M[b])
|
| 473 |
+
F = log(2*sqrt(M[a])*sqrt(M[a]*x**2 - M[b]) + 2*M[a]*x)/sqrt(M[a])
|
| 474 |
+
dcache.cache[F] = dF # hack: F.diff(x) doesn't automatically simplify to f
|
| 475 |
+
terms.add(F)
|
| 476 |
+
elif M[a].is_negative:
|
| 477 |
+
terms.add(-M[b]/2*sqrt(-M[a])*
|
| 478 |
+
atan(sqrt(-M[a])*x/sqrt(M[a]*x**2 - M[b])))
|
| 479 |
+
|
| 480 |
+
else:
|
| 481 |
+
terms |= set(hints)
|
| 482 |
+
|
| 483 |
+
for g in set(terms): # using copy of terms
|
| 484 |
+
terms |= components(dcache.get_diff(g), x)
|
| 485 |
+
|
| 486 |
+
# XXX: The commented line below makes heurisch more deterministic wrt
|
| 487 |
+
# PYTHONHASHSEED and the iteration order of sets. There are other places
|
| 488 |
+
# where sets are iterated over but this one is possibly the most important.
|
| 489 |
+
# Theoretically the order here should not matter but different orderings
|
| 490 |
+
# can expose potential bugs in the different code paths so potentially it
|
| 491 |
+
# is better to keep the non-determinism.
|
| 492 |
+
#
|
| 493 |
+
# terms = list(ordered(terms))
|
| 494 |
+
|
| 495 |
+
# TODO: caching is significant factor for why permutations work at all. Change this.
|
| 496 |
+
V = _symbols('x', len(terms))
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
# sort mapping expressions from largest to smallest (last is always x).
|
| 500 |
+
mapping = list(reversed(list(zip(*ordered( #
|
| 501 |
+
[(a[0].as_independent(x)[1], a) for a in zip(terms, V)])))[1])) #
|
| 502 |
+
rev_mapping = {v: k for k, v in mapping} #
|
| 503 |
+
if mappings is None: #
|
| 504 |
+
# optimizing the number of permutations of mapping #
|
| 505 |
+
assert mapping[-1][0] == x # if not, find it and correct this comment
|
| 506 |
+
unnecessary_permutations = [mapping.pop(-1)]
|
| 507 |
+
# permute types of objects
|
| 508 |
+
types = defaultdict(list)
|
| 509 |
+
for i in mapping:
|
| 510 |
+
e, _ = i
|
| 511 |
+
types[type(e)].append(i)
|
| 512 |
+
mapping = [types[i] for i in types]
|
| 513 |
+
def _iter_mappings():
|
| 514 |
+
for i in permutations(mapping):
|
| 515 |
+
# make the expression of a given type be ordered
|
| 516 |
+
yield [j for i in i for j in ordered(i)]
|
| 517 |
+
mappings = _iter_mappings()
|
| 518 |
+
else:
|
| 519 |
+
unnecessary_permutations = unnecessary_permutations or []
|
| 520 |
+
|
| 521 |
+
def _substitute(expr):
|
| 522 |
+
return expr.subs(mapping)
|
| 523 |
+
|
| 524 |
+
for mapping in mappings:
|
| 525 |
+
mapping = list(mapping)
|
| 526 |
+
mapping = mapping + unnecessary_permutations
|
| 527 |
+
diffs = [ _substitute(dcache.get_diff(g)) for g in terms ]
|
| 528 |
+
denoms = [ g.as_numer_denom()[1] for g in diffs ]
|
| 529 |
+
if all(h.is_polynomial(*V) for h in denoms) and _substitute(f).is_rational_function(*V):
|
| 530 |
+
denom = reduce(lambda p, q: lcm(p, q, *V), denoms)
|
| 531 |
+
break
|
| 532 |
+
else:
|
| 533 |
+
if not rewrite:
|
| 534 |
+
result = heurisch(f, x, rewrite=True, hints=hints,
|
| 535 |
+
unnecessary_permutations=unnecessary_permutations)
|
| 536 |
+
|
| 537 |
+
if result is not None:
|
| 538 |
+
return indep*result
|
| 539 |
+
return None
|
| 540 |
+
|
| 541 |
+
numers = [ cancel(denom*g) for g in diffs ]
|
| 542 |
+
def _derivation(h):
|
| 543 |
+
return Add(*[ d * h.diff(v) for d, v in zip(numers, V) ])
|
| 544 |
+
|
| 545 |
+
def _deflation(p):
|
| 546 |
+
for y in V:
|
| 547 |
+
if not p.has(y):
|
| 548 |
+
continue
|
| 549 |
+
|
| 550 |
+
if _derivation(p) is not S.Zero:
|
| 551 |
+
c, q = p.as_poly(y).primitive()
|
| 552 |
+
return _deflation(c)*gcd(q, q.diff(y)).as_expr()
|
| 553 |
+
|
| 554 |
+
return p
|
| 555 |
+
|
| 556 |
+
def _splitter(p):
|
| 557 |
+
for y in V:
|
| 558 |
+
if not p.has(y):
|
| 559 |
+
continue
|
| 560 |
+
|
| 561 |
+
if _derivation(y) is not S.Zero:
|
| 562 |
+
c, q = p.as_poly(y).primitive()
|
| 563 |
+
|
| 564 |
+
q = q.as_expr()
|
| 565 |
+
|
| 566 |
+
h = gcd(q, _derivation(q), y)
|
| 567 |
+
s = quo(h, gcd(q, q.diff(y), y), y)
|
| 568 |
+
|
| 569 |
+
c_split = _splitter(c)
|
| 570 |
+
|
| 571 |
+
if s.as_poly(y).degree() == 0:
|
| 572 |
+
return (c_split[0], q * c_split[1])
|
| 573 |
+
|
| 574 |
+
q_split = _splitter(cancel(q / s))
|
| 575 |
+
|
| 576 |
+
return (c_split[0]*q_split[0]*s, c_split[1]*q_split[1])
|
| 577 |
+
|
| 578 |
+
return (S.One, p)
|
| 579 |
+
|
| 580 |
+
special = {}
|
| 581 |
+
|
| 582 |
+
for term in terms:
|
| 583 |
+
if term.is_Function:
|
| 584 |
+
if isinstance(term, tan):
|
| 585 |
+
special[1 + _substitute(term)**2] = False
|
| 586 |
+
elif isinstance(term, tanh):
|
| 587 |
+
special[1 + _substitute(term)] = False
|
| 588 |
+
special[1 - _substitute(term)] = False
|
| 589 |
+
elif isinstance(term, LambertW):
|
| 590 |
+
special[_substitute(term)] = True
|
| 591 |
+
|
| 592 |
+
F = _substitute(f)
|
| 593 |
+
|
| 594 |
+
P, Q = F.as_numer_denom()
|
| 595 |
+
|
| 596 |
+
u_split = _splitter(denom)
|
| 597 |
+
v_split = _splitter(Q)
|
| 598 |
+
|
| 599 |
+
polys = set(list(v_split) + [ u_split[0] ] + list(special.keys()))
|
| 600 |
+
|
| 601 |
+
s = u_split[0] * Mul(*[ k for k, v in special.items() if v ])
|
| 602 |
+
polified = [ p.as_poly(*V) for p in [s, P, Q] ]
|
| 603 |
+
|
| 604 |
+
if None in polified:
|
| 605 |
+
return None
|
| 606 |
+
|
| 607 |
+
#--- definitions for _integrate
|
| 608 |
+
a, b, c = [ p.total_degree() for p in polified ]
|
| 609 |
+
|
| 610 |
+
poly_denom = (s * v_split[0] * _deflation(v_split[1])).as_expr()
|
| 611 |
+
|
| 612 |
+
def _exponent(g):
|
| 613 |
+
if g.is_Pow:
|
| 614 |
+
if g.exp.is_Rational and g.exp.q != 1:
|
| 615 |
+
if g.exp.p > 0:
|
| 616 |
+
return g.exp.p + g.exp.q - 1
|
| 617 |
+
else:
|
| 618 |
+
return abs(g.exp.p + g.exp.q)
|
| 619 |
+
else:
|
| 620 |
+
return 1
|
| 621 |
+
elif not g.is_Atom and g.args:
|
| 622 |
+
return max(_exponent(h) for h in g.args)
|
| 623 |
+
else:
|
| 624 |
+
return 1
|
| 625 |
+
|
| 626 |
+
A, B = _exponent(f), a + max(b, c)
|
| 627 |
+
|
| 628 |
+
if A > 1 and B > 1:
|
| 629 |
+
monoms = tuple(ordered(itermonomials(V, A + B - 1 + degree_offset)))
|
| 630 |
+
else:
|
| 631 |
+
monoms = tuple(ordered(itermonomials(V, A + B + degree_offset)))
|
| 632 |
+
|
| 633 |
+
poly_coeffs = _symbols('A', len(monoms))
|
| 634 |
+
|
| 635 |
+
poly_part = Add(*[ poly_coeffs[i]*monomial
|
| 636 |
+
for i, monomial in enumerate(monoms) ])
|
| 637 |
+
|
| 638 |
+
reducibles = set()
|
| 639 |
+
|
| 640 |
+
for poly in ordered(polys):
|
| 641 |
+
coeff, factors = factor_list(poly, *V)
|
| 642 |
+
reducibles.add(coeff)
|
| 643 |
+
reducibles.update(fact for fact, mul in factors)
|
| 644 |
+
|
| 645 |
+
def _integrate(field=None):
|
| 646 |
+
atans = set()
|
| 647 |
+
pairs = set()
|
| 648 |
+
|
| 649 |
+
if field == 'Q':
|
| 650 |
+
irreducibles = set(reducibles)
|
| 651 |
+
else:
|
| 652 |
+
setV = set(V)
|
| 653 |
+
irreducibles = set()
|
| 654 |
+
for poly in ordered(reducibles):
|
| 655 |
+
zV = setV & set(iterfreeargs(poly))
|
| 656 |
+
for z in ordered(zV):
|
| 657 |
+
s = set(root_factors(poly, z, filter=field))
|
| 658 |
+
irreducibles |= s
|
| 659 |
+
break
|
| 660 |
+
|
| 661 |
+
log_part, atan_part = [], []
|
| 662 |
+
|
| 663 |
+
for poly in ordered(irreducibles):
|
| 664 |
+
m = collect(poly, I, evaluate=False)
|
| 665 |
+
y = m.get(I, S.Zero)
|
| 666 |
+
if y:
|
| 667 |
+
x = m.get(S.One, S.Zero)
|
| 668 |
+
if x.has(I) or y.has(I):
|
| 669 |
+
continue # nontrivial x + I*y
|
| 670 |
+
pairs.add((x, y))
|
| 671 |
+
irreducibles.remove(poly)
|
| 672 |
+
|
| 673 |
+
while pairs:
|
| 674 |
+
x, y = pairs.pop()
|
| 675 |
+
if (x, -y) in pairs:
|
| 676 |
+
pairs.remove((x, -y))
|
| 677 |
+
# Choosing b with no minus sign
|
| 678 |
+
if y.could_extract_minus_sign():
|
| 679 |
+
y = -y
|
| 680 |
+
irreducibles.add(x*x + y*y)
|
| 681 |
+
atans.add(atan(x/y))
|
| 682 |
+
else:
|
| 683 |
+
irreducibles.add(x + I*y)
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
B = _symbols('B', len(irreducibles))
|
| 687 |
+
C = _symbols('C', len(atans))
|
| 688 |
+
|
| 689 |
+
# Note: the ordering matters here
|
| 690 |
+
for poly, b in reversed(list(zip(ordered(irreducibles), B))):
|
| 691 |
+
if poly.has(*V):
|
| 692 |
+
poly_coeffs.append(b)
|
| 693 |
+
log_part.append(b * log(poly))
|
| 694 |
+
|
| 695 |
+
for poly, c in reversed(list(zip(ordered(atans), C))):
|
| 696 |
+
if poly.has(*V):
|
| 697 |
+
poly_coeffs.append(c)
|
| 698 |
+
atan_part.append(c * poly)
|
| 699 |
+
|
| 700 |
+
# TODO: Currently it's better to use symbolic expressions here instead
|
| 701 |
+
# of rational functions, because it's simpler and FracElement doesn't
|
| 702 |
+
# give big speed improvement yet. This is because cancellation is slow
|
| 703 |
+
# due to slow polynomial GCD algorithms. If this gets improved then
|
| 704 |
+
# revise this code.
|
| 705 |
+
candidate = poly_part/poly_denom + Add(*log_part) + Add(*atan_part)
|
| 706 |
+
h = F - _derivation(candidate) / denom
|
| 707 |
+
raw_numer = h.as_numer_denom()[0]
|
| 708 |
+
|
| 709 |
+
# Rewrite raw_numer as a polynomial in K[coeffs][V] where K is a field
|
| 710 |
+
# that we have to determine. We can't use simply atoms() because log(3),
|
| 711 |
+
# sqrt(y) and similar expressions can appear, leading to non-trivial
|
| 712 |
+
# domains.
|
| 713 |
+
syms = set(poly_coeffs) | set(V)
|
| 714 |
+
non_syms = set()
|
| 715 |
+
|
| 716 |
+
def find_non_syms(expr):
|
| 717 |
+
if expr.is_Integer or expr.is_Rational:
|
| 718 |
+
pass # ignore trivial numbers
|
| 719 |
+
elif expr in syms:
|
| 720 |
+
pass # ignore variables
|
| 721 |
+
elif not expr.has_free(*syms):
|
| 722 |
+
non_syms.add(expr)
|
| 723 |
+
elif expr.is_Add or expr.is_Mul or expr.is_Pow:
|
| 724 |
+
list(map(find_non_syms, expr.args))
|
| 725 |
+
else:
|
| 726 |
+
# TODO: Non-polynomial expression. This should have been
|
| 727 |
+
# filtered out at an earlier stage.
|
| 728 |
+
raise PolynomialError
|
| 729 |
+
|
| 730 |
+
try:
|
| 731 |
+
find_non_syms(raw_numer)
|
| 732 |
+
except PolynomialError:
|
| 733 |
+
return None
|
| 734 |
+
else:
|
| 735 |
+
ground, _ = construct_domain(non_syms, field=True)
|
| 736 |
+
|
| 737 |
+
coeff_ring = PolyRing(poly_coeffs, ground)
|
| 738 |
+
ring = PolyRing(V, coeff_ring)
|
| 739 |
+
try:
|
| 740 |
+
numer = ring.from_expr(raw_numer)
|
| 741 |
+
except ValueError:
|
| 742 |
+
raise PolynomialError
|
| 743 |
+
solution = solve_lin_sys(numer.coeffs(), coeff_ring, _raw=False)
|
| 744 |
+
|
| 745 |
+
if solution is None:
|
| 746 |
+
return None
|
| 747 |
+
else:
|
| 748 |
+
return candidate.xreplace(solution).xreplace(
|
| 749 |
+
dict(zip(poly_coeffs, [S.Zero]*len(poly_coeffs))))
|
| 750 |
+
|
| 751 |
+
if all(isinstance(_, Symbol) for _ in V):
|
| 752 |
+
more_free = F.free_symbols - set(V)
|
| 753 |
+
else:
|
| 754 |
+
Fd = F.as_dummy()
|
| 755 |
+
more_free = Fd.xreplace(dict(zip(V, (Dummy() for _ in V)))
|
| 756 |
+
).free_symbols & Fd.free_symbols
|
| 757 |
+
if not more_free:
|
| 758 |
+
# all free generators are identified in V
|
| 759 |
+
solution = _integrate('Q')
|
| 760 |
+
|
| 761 |
+
if solution is None:
|
| 762 |
+
solution = _integrate()
|
| 763 |
+
else:
|
| 764 |
+
solution = _integrate()
|
| 765 |
+
|
| 766 |
+
if solution is not None:
|
| 767 |
+
antideriv = solution.subs(rev_mapping)
|
| 768 |
+
antideriv = cancel(antideriv).expand()
|
| 769 |
+
|
| 770 |
+
if antideriv.is_Add:
|
| 771 |
+
antideriv = antideriv.as_independent(x)[1]
|
| 772 |
+
|
| 773 |
+
return indep*antideriv
|
| 774 |
+
else:
|
| 775 |
+
if retries >= 0:
|
| 776 |
+
result = heurisch(f, x, mappings=mappings, rewrite=rewrite, hints=hints, retries=retries - 1, unnecessary_permutations=unnecessary_permutations)
|
| 777 |
+
|
| 778 |
+
if result is not None:
|
| 779 |
+
return indep*result
|
| 780 |
+
|
| 781 |
+
return None
|
.venv/lib/python3.12/site-packages/sympy/integrals/integrals.py
ADDED
|
@@ -0,0 +1,1640 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 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 sympy.functions.special.singularity_functions import Heaviside
|
| 23 |
+
from .rationaltools import ratint
|
| 24 |
+
from sympy.matrices import MatrixBase
|
| 25 |
+
from sympy.polys import Poly, PolynomialError
|
| 26 |
+
from sympy.series.formal import FormalPowerSeries
|
| 27 |
+
from sympy.series.limits import limit
|
| 28 |
+
from sympy.series.order import Order
|
| 29 |
+
from sympy.tensor.functions import shape
|
| 30 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
| 31 |
+
from sympy.utilities.iterables import is_sequence
|
| 32 |
+
from sympy.utilities.misc import filldedent
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Integral(AddWithLimits):
|
| 36 |
+
"""Represents unevaluated integral."""
|
| 37 |
+
|
| 38 |
+
__slots__ = ()
|
| 39 |
+
|
| 40 |
+
args: tuple[Expr, Tuple] # type: ignore
|
| 41 |
+
|
| 42 |
+
def __new__(cls, function, *symbols, **assumptions) -> Integral:
|
| 43 |
+
"""Create an unevaluated integral.
|
| 44 |
+
|
| 45 |
+
Explanation
|
| 46 |
+
===========
|
| 47 |
+
|
| 48 |
+
Arguments are an integrand followed by one or more limits.
|
| 49 |
+
|
| 50 |
+
If no limits are given and there is only one free symbol in the
|
| 51 |
+
expression, that symbol will be used, otherwise an error will be
|
| 52 |
+
raised.
|
| 53 |
+
|
| 54 |
+
>>> from sympy import Integral
|
| 55 |
+
>>> from sympy.abc import x, y
|
| 56 |
+
>>> Integral(x)
|
| 57 |
+
Integral(x, x)
|
| 58 |
+
>>> Integral(y)
|
| 59 |
+
Integral(y, y)
|
| 60 |
+
|
| 61 |
+
When limits are provided, they are interpreted as follows (using
|
| 62 |
+
``x`` as though it were the variable of integration):
|
| 63 |
+
|
| 64 |
+
(x,) or x - indefinite integral
|
| 65 |
+
(x, a) - "evaluate at" integral is an abstract antiderivative
|
| 66 |
+
(x, a, b) - definite integral
|
| 67 |
+
|
| 68 |
+
The ``as_dummy`` method can be used to see which symbols cannot be
|
| 69 |
+
targeted by subs: those with a prepended underscore cannot be
|
| 70 |
+
changed with ``subs``. (Also, the integration variables themselves --
|
| 71 |
+
the first element of a limit -- can never be changed by subs.)
|
| 72 |
+
|
| 73 |
+
>>> i = Integral(x, x)
|
| 74 |
+
>>> at = Integral(x, (x, x))
|
| 75 |
+
>>> i.as_dummy()
|
| 76 |
+
Integral(x, x)
|
| 77 |
+
>>> at.as_dummy()
|
| 78 |
+
Integral(_0, (_0, x))
|
| 79 |
+
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
#This will help other classes define their own definitions
|
| 83 |
+
#of behaviour with Integral.
|
| 84 |
+
if hasattr(function, '_eval_Integral'):
|
| 85 |
+
return function._eval_Integral(*symbols, **assumptions)
|
| 86 |
+
|
| 87 |
+
if isinstance(function, Poly):
|
| 88 |
+
sympy_deprecation_warning(
|
| 89 |
+
"""
|
| 90 |
+
integrate(Poly) and Integral(Poly) are deprecated. Instead,
|
| 91 |
+
use the Poly.integrate() method, or convert the Poly to an
|
| 92 |
+
Expr first with the Poly.as_expr() method.
|
| 93 |
+
""",
|
| 94 |
+
deprecated_since_version="1.6",
|
| 95 |
+
active_deprecations_target="deprecated-integrate-poly")
|
| 96 |
+
|
| 97 |
+
obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
|
| 98 |
+
return obj
|
| 99 |
+
|
| 100 |
+
def __getnewargs__(self):
|
| 101 |
+
return (self.function,) + tuple([tuple(xab) for xab in self.limits])
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def free_symbols(self):
|
| 105 |
+
"""
|
| 106 |
+
This method returns the symbols that will exist when the
|
| 107 |
+
integral is evaluated. This is useful if one is trying to
|
| 108 |
+
determine whether an integral depends on a certain
|
| 109 |
+
symbol or not.
|
| 110 |
+
|
| 111 |
+
Examples
|
| 112 |
+
========
|
| 113 |
+
|
| 114 |
+
>>> from sympy import Integral
|
| 115 |
+
>>> from sympy.abc import x, y
|
| 116 |
+
>>> Integral(x, (x, y, 1)).free_symbols
|
| 117 |
+
{y}
|
| 118 |
+
|
| 119 |
+
See Also
|
| 120 |
+
========
|
| 121 |
+
|
| 122 |
+
sympy.concrete.expr_with_limits.ExprWithLimits.function
|
| 123 |
+
sympy.concrete.expr_with_limits.ExprWithLimits.limits
|
| 124 |
+
sympy.concrete.expr_with_limits.ExprWithLimits.variables
|
| 125 |
+
"""
|
| 126 |
+
return super().free_symbols
|
| 127 |
+
|
| 128 |
+
def _eval_is_zero(self):
|
| 129 |
+
# This is a very naive and quick test, not intended to do the integral to
|
| 130 |
+
# answer whether it is zero or not, e.g. Integral(sin(x), (x, 0, 2*pi))
|
| 131 |
+
# is zero but this routine should return None for that case. But, like
|
| 132 |
+
# Mul, there are trivial situations for which the integral will be
|
| 133 |
+
# zero so we check for those.
|
| 134 |
+
if self.function.is_zero:
|
| 135 |
+
return True
|
| 136 |
+
got_none = False
|
| 137 |
+
for l in self.limits:
|
| 138 |
+
if len(l) == 3:
|
| 139 |
+
z = (l[1] == l[2]) or (l[1] - l[2]).is_zero
|
| 140 |
+
if z:
|
| 141 |
+
return True
|
| 142 |
+
elif z is None:
|
| 143 |
+
got_none = True
|
| 144 |
+
free = self.function.free_symbols
|
| 145 |
+
for xab in self.limits:
|
| 146 |
+
if len(xab) == 1:
|
| 147 |
+
free.add(xab[0])
|
| 148 |
+
continue
|
| 149 |
+
if len(xab) == 2 and xab[0] not in free:
|
| 150 |
+
if xab[1].is_zero:
|
| 151 |
+
return True
|
| 152 |
+
elif xab[1].is_zero is None:
|
| 153 |
+
got_none = True
|
| 154 |
+
# take integration symbol out of free since it will be replaced
|
| 155 |
+
# with the free symbols in the limits
|
| 156 |
+
free.discard(xab[0])
|
| 157 |
+
# add in the new symbols
|
| 158 |
+
for i in xab[1:]:
|
| 159 |
+
free.update(i.free_symbols)
|
| 160 |
+
if self.function.is_zero is False and got_none is False:
|
| 161 |
+
return False
|
| 162 |
+
|
| 163 |
+
def transform(self, x, u):
|
| 164 |
+
r"""
|
| 165 |
+
Performs a change of variables from `x` to `u` using the relationship
|
| 166 |
+
given by `x` and `u` which will define the transformations `f` and `F`
|
| 167 |
+
(which are inverses of each other) as follows:
|
| 168 |
+
|
| 169 |
+
1) If `x` is a Symbol (which is a variable of integration) then `u`
|
| 170 |
+
will be interpreted as some function, f(u), with inverse F(u).
|
| 171 |
+
This, in effect, just makes the substitution of x with f(x).
|
| 172 |
+
|
| 173 |
+
2) If `u` is a Symbol then `x` will be interpreted as some function,
|
| 174 |
+
F(x), with inverse f(u). This is commonly referred to as
|
| 175 |
+
u-substitution.
|
| 176 |
+
|
| 177 |
+
Once f and F have been identified, the transformation is made as
|
| 178 |
+
follows:
|
| 179 |
+
|
| 180 |
+
.. math:: \int_a^b x \mathrm{d}x \rightarrow \int_{F(a)}^{F(b)} f(x)
|
| 181 |
+
\frac{\mathrm{d}}{\mathrm{d}x}
|
| 182 |
+
|
| 183 |
+
where `F(x)` is the inverse of `f(x)` and the limits and integrand have
|
| 184 |
+
been corrected so as to retain the same value after integration.
|
| 185 |
+
|
| 186 |
+
Notes
|
| 187 |
+
=====
|
| 188 |
+
|
| 189 |
+
The mappings, F(x) or f(u), must lead to a unique integral. Linear
|
| 190 |
+
or rational linear expression, ``2*x``, ``1/x`` and ``sqrt(x)``, will
|
| 191 |
+
always work; quadratic expressions like ``x**2 - 1`` are acceptable
|
| 192 |
+
as long as the resulting integrand does not depend on the sign of
|
| 193 |
+
the solutions (see examples).
|
| 194 |
+
|
| 195 |
+
The integral will be returned unchanged if ``x`` is not a variable of
|
| 196 |
+
integration.
|
| 197 |
+
|
| 198 |
+
``x`` must be (or contain) only one of of the integration variables. If
|
| 199 |
+
``u`` has more than one free symbol then it should be sent as a tuple
|
| 200 |
+
(``u``, ``uvar``) where ``uvar`` identifies which variable is replacing
|
| 201 |
+
the integration variable.
|
| 202 |
+
XXX can it contain another integration variable?
|
| 203 |
+
|
| 204 |
+
Examples
|
| 205 |
+
========
|
| 206 |
+
|
| 207 |
+
>>> from sympy.abc import a, x, u
|
| 208 |
+
>>> from sympy import Integral, cos, sqrt
|
| 209 |
+
|
| 210 |
+
>>> i = Integral(x*cos(x**2 - 1), (x, 0, 1))
|
| 211 |
+
|
| 212 |
+
transform can change the variable of integration
|
| 213 |
+
|
| 214 |
+
>>> i.transform(x, u)
|
| 215 |
+
Integral(u*cos(u**2 - 1), (u, 0, 1))
|
| 216 |
+
|
| 217 |
+
transform can perform u-substitution as long as a unique
|
| 218 |
+
integrand is obtained:
|
| 219 |
+
|
| 220 |
+
>>> ui = i.transform(x**2 - 1, u)
|
| 221 |
+
>>> ui
|
| 222 |
+
Integral(cos(u)/2, (u, -1, 0))
|
| 223 |
+
|
| 224 |
+
This attempt fails because x = +/-sqrt(u + 1) and the
|
| 225 |
+
sign does not cancel out of the integrand:
|
| 226 |
+
|
| 227 |
+
>>> Integral(cos(x**2 - 1), (x, 0, 1)).transform(x**2 - 1, u)
|
| 228 |
+
Traceback (most recent call last):
|
| 229 |
+
...
|
| 230 |
+
ValueError:
|
| 231 |
+
The mapping between F(x) and f(u) did not give a unique integrand.
|
| 232 |
+
|
| 233 |
+
transform can do a substitution. Here, the previous
|
| 234 |
+
result is transformed back into the original expression
|
| 235 |
+
using "u-substitution":
|
| 236 |
+
|
| 237 |
+
>>> ui.transform(sqrt(u + 1), x) == i
|
| 238 |
+
True
|
| 239 |
+
|
| 240 |
+
We can accomplish the same with a regular substitution:
|
| 241 |
+
|
| 242 |
+
>>> ui.transform(u, x**2 - 1) == i
|
| 243 |
+
True
|
| 244 |
+
|
| 245 |
+
If the `x` does not contain a symbol of integration then
|
| 246 |
+
the integral will be returned unchanged. Integral `i` does
|
| 247 |
+
not have an integration variable `a` so no change is made:
|
| 248 |
+
|
| 249 |
+
>>> i.transform(a, x) == i
|
| 250 |
+
True
|
| 251 |
+
|
| 252 |
+
When `u` has more than one free symbol the symbol that is
|
| 253 |
+
replacing `x` must be identified by passing `u` as a tuple:
|
| 254 |
+
|
| 255 |
+
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, u))
|
| 256 |
+
Integral(a + u, (u, -a, 1 - a))
|
| 257 |
+
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, a))
|
| 258 |
+
Integral(a + u, (a, -u, 1 - u))
|
| 259 |
+
|
| 260 |
+
See Also
|
| 261 |
+
========
|
| 262 |
+
|
| 263 |
+
sympy.concrete.expr_with_limits.ExprWithLimits.variables : Lists the integration variables
|
| 264 |
+
as_dummy : Replace integration variables with dummy ones
|
| 265 |
+
"""
|
| 266 |
+
d = Dummy('d')
|
| 267 |
+
|
| 268 |
+
xfree = x.free_symbols.intersection(self.variables)
|
| 269 |
+
if len(xfree) > 1:
|
| 270 |
+
raise ValueError(
|
| 271 |
+
'F(x) can only contain one of: %s' % self.variables)
|
| 272 |
+
xvar = xfree.pop() if xfree else d
|
| 273 |
+
|
| 274 |
+
if xvar not in self.variables:
|
| 275 |
+
return self
|
| 276 |
+
|
| 277 |
+
u = sympify(u)
|
| 278 |
+
if isinstance(u, Expr):
|
| 279 |
+
ufree = u.free_symbols
|
| 280 |
+
if len(ufree) == 0:
|
| 281 |
+
raise ValueError(filldedent('''
|
| 282 |
+
f(u) cannot be a constant'''))
|
| 283 |
+
if len(ufree) > 1:
|
| 284 |
+
raise ValueError(filldedent('''
|
| 285 |
+
When f(u) has more than one free symbol, the one replacing x
|
| 286 |
+
must be identified: pass f(u) as (f(u), u)'''))
|
| 287 |
+
uvar = ufree.pop()
|
| 288 |
+
else:
|
| 289 |
+
u, uvar = u
|
| 290 |
+
if uvar not in u.free_symbols:
|
| 291 |
+
raise ValueError(filldedent('''
|
| 292 |
+
Expecting a tuple (expr, symbol) where symbol identified
|
| 293 |
+
a free symbol in expr, but symbol is not in expr's free
|
| 294 |
+
symbols.'''))
|
| 295 |
+
if not isinstance(uvar, Symbol):
|
| 296 |
+
# This probably never evaluates to True
|
| 297 |
+
raise ValueError(filldedent('''
|
| 298 |
+
Expecting a tuple (expr, symbol) but didn't get
|
| 299 |
+
a symbol; got %s''' % uvar))
|
| 300 |
+
|
| 301 |
+
if x.is_Symbol and u.is_Symbol:
|
| 302 |
+
return self.xreplace({x: u})
|
| 303 |
+
|
| 304 |
+
if not x.is_Symbol and not u.is_Symbol:
|
| 305 |
+
raise ValueError('either x or u must be a symbol')
|
| 306 |
+
|
| 307 |
+
if uvar == xvar:
|
| 308 |
+
return self.transform(x, (u.subs(uvar, d), d)).xreplace({d: uvar})
|
| 309 |
+
|
| 310 |
+
if uvar in self.limits:
|
| 311 |
+
raise ValueError(filldedent('''
|
| 312 |
+
u must contain the same variable as in x
|
| 313 |
+
or a variable that is not already an integration variable'''))
|
| 314 |
+
|
| 315 |
+
from sympy.solvers.solvers import solve
|
| 316 |
+
if not x.is_Symbol:
|
| 317 |
+
F = [x.subs(xvar, d)]
|
| 318 |
+
soln = solve(u - x, xvar, check=False)
|
| 319 |
+
if not soln:
|
| 320 |
+
raise ValueError('no solution for solve(F(x) - f(u), x)')
|
| 321 |
+
f = [fi.subs(uvar, d) for fi in soln]
|
| 322 |
+
else:
|
| 323 |
+
f = [u.subs(uvar, d)]
|
| 324 |
+
from sympy.simplify.simplify import posify
|
| 325 |
+
pdiff, reps = posify(u - x)
|
| 326 |
+
puvar = uvar.subs([(v, k) for k, v in reps.items()])
|
| 327 |
+
soln = [s.subs(reps) for s in solve(pdiff, puvar)]
|
| 328 |
+
if not soln:
|
| 329 |
+
raise ValueError('no solution for solve(F(x) - f(u), u)')
|
| 330 |
+
F = [fi.subs(xvar, d) for fi in soln]
|
| 331 |
+
|
| 332 |
+
newfuncs = {(self.function.subs(xvar, fi)*fi.diff(d)
|
| 333 |
+
).subs(d, uvar) for fi in f}
|
| 334 |
+
if len(newfuncs) > 1:
|
| 335 |
+
raise ValueError(filldedent('''
|
| 336 |
+
The mapping between F(x) and f(u) did not give
|
| 337 |
+
a unique integrand.'''))
|
| 338 |
+
newfunc = newfuncs.pop()
|
| 339 |
+
|
| 340 |
+
def _calc_limit_1(F, a, b):
|
| 341 |
+
"""
|
| 342 |
+
replace d with a, using subs if possible, otherwise limit
|
| 343 |
+
where sign of b is considered
|
| 344 |
+
"""
|
| 345 |
+
wok = F.subs(d, a)
|
| 346 |
+
if wok is S.NaN or wok.is_finite is False and a.is_finite:
|
| 347 |
+
return limit(sign(b)*F, d, a)
|
| 348 |
+
return wok
|
| 349 |
+
|
| 350 |
+
def _calc_limit(a, b):
|
| 351 |
+
"""
|
| 352 |
+
replace d with a, using subs if possible, otherwise limit
|
| 353 |
+
where sign of b is considered
|
| 354 |
+
"""
|
| 355 |
+
avals = list({_calc_limit_1(Fi, a, b) for Fi in F})
|
| 356 |
+
if len(avals) > 1:
|
| 357 |
+
raise ValueError(filldedent('''
|
| 358 |
+
The mapping between F(x) and f(u) did not
|
| 359 |
+
give a unique limit.'''))
|
| 360 |
+
return avals[0]
|
| 361 |
+
|
| 362 |
+
newlimits = []
|
| 363 |
+
for xab in self.limits:
|
| 364 |
+
sym = xab[0]
|
| 365 |
+
if sym == xvar:
|
| 366 |
+
if len(xab) == 3:
|
| 367 |
+
a, b = xab[1:]
|
| 368 |
+
a, b = _calc_limit(a, b), _calc_limit(b, a)
|
| 369 |
+
if fuzzy_bool(a - b > 0):
|
| 370 |
+
a, b = b, a
|
| 371 |
+
newfunc = -newfunc
|
| 372 |
+
newlimits.append((uvar, a, b))
|
| 373 |
+
elif len(xab) == 2:
|
| 374 |
+
a = _calc_limit(xab[1], 1)
|
| 375 |
+
newlimits.append((uvar, a))
|
| 376 |
+
else:
|
| 377 |
+
newlimits.append(uvar)
|
| 378 |
+
else:
|
| 379 |
+
newlimits.append(xab)
|
| 380 |
+
|
| 381 |
+
return self.func(newfunc, *newlimits)
|
| 382 |
+
|
| 383 |
+
def doit(self, **hints):
|
| 384 |
+
"""
|
| 385 |
+
Perform the integration using any hints given.
|
| 386 |
+
|
| 387 |
+
Examples
|
| 388 |
+
========
|
| 389 |
+
|
| 390 |
+
>>> from sympy import Piecewise, S
|
| 391 |
+
>>> from sympy.abc import x, t
|
| 392 |
+
>>> p = x**2 + Piecewise((0, x/t < 0), (1, True))
|
| 393 |
+
>>> p.integrate((t, S(4)/5, 1), (x, -1, 1))
|
| 394 |
+
1/3
|
| 395 |
+
|
| 396 |
+
See Also
|
| 397 |
+
========
|
| 398 |
+
|
| 399 |
+
sympy.integrals.trigonometry.trigintegrate
|
| 400 |
+
sympy.integrals.heurisch.heurisch
|
| 401 |
+
sympy.integrals.rationaltools.ratint
|
| 402 |
+
as_sum : Approximate the integral using a sum
|
| 403 |
+
"""
|
| 404 |
+
if not hints.get('integrals', True):
|
| 405 |
+
return self
|
| 406 |
+
|
| 407 |
+
deep = hints.get('deep', True)
|
| 408 |
+
meijerg = hints.get('meijerg', None)
|
| 409 |
+
conds = hints.get('conds', 'piecewise')
|
| 410 |
+
risch = hints.get('risch', None)
|
| 411 |
+
heurisch = hints.get('heurisch', None)
|
| 412 |
+
manual = hints.get('manual', None)
|
| 413 |
+
if len(list(filter(None, (manual, meijerg, risch, heurisch)))) > 1:
|
| 414 |
+
raise ValueError("At most one of manual, meijerg, risch, heurisch can be True")
|
| 415 |
+
elif manual:
|
| 416 |
+
meijerg = risch = heurisch = False
|
| 417 |
+
elif meijerg:
|
| 418 |
+
manual = risch = heurisch = False
|
| 419 |
+
elif risch:
|
| 420 |
+
manual = meijerg = heurisch = False
|
| 421 |
+
elif heurisch:
|
| 422 |
+
manual = meijerg = risch = False
|
| 423 |
+
eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual, "heurisch": heurisch,
|
| 424 |
+
"conds": conds}
|
| 425 |
+
|
| 426 |
+
if conds not in ('separate', 'piecewise', 'none'):
|
| 427 |
+
raise ValueError('conds must be one of "separate", "piecewise", '
|
| 428 |
+
'"none", got: %s' % conds)
|
| 429 |
+
|
| 430 |
+
if risch and any(len(xab) > 1 for xab in self.limits):
|
| 431 |
+
raise ValueError('risch=True is only allowed for indefinite integrals.')
|
| 432 |
+
|
| 433 |
+
# check for the trivial zero
|
| 434 |
+
if self.is_zero:
|
| 435 |
+
return S.Zero
|
| 436 |
+
|
| 437 |
+
# hacks to handle integrals of
|
| 438 |
+
# nested summations
|
| 439 |
+
from sympy.concrete.summations import Sum
|
| 440 |
+
if isinstance(self.function, Sum):
|
| 441 |
+
if any(v in self.function.limits[0] for v in self.variables):
|
| 442 |
+
raise ValueError('Limit of the sum cannot be an integration variable.')
|
| 443 |
+
if any(l.is_infinite for l in self.function.limits[0][1:]):
|
| 444 |
+
return self
|
| 445 |
+
_i = self
|
| 446 |
+
_sum = self.function
|
| 447 |
+
return _sum.func(_i.func(_sum.function, *_i.limits).doit(), *_sum.limits).doit()
|
| 448 |
+
|
| 449 |
+
# now compute and check the function
|
| 450 |
+
function = self.function
|
| 451 |
+
|
| 452 |
+
# hack to use a consistent Heaviside(x, 1/2)
|
| 453 |
+
function = function.replace(
|
| 454 |
+
lambda x: isinstance(x, Heaviside) and x.args[1]*2 != 1,
|
| 455 |
+
lambda x: Heaviside(x.args[0]))
|
| 456 |
+
|
| 457 |
+
if deep:
|
| 458 |
+
function = function.doit(**hints)
|
| 459 |
+
if function.is_zero:
|
| 460 |
+
return S.Zero
|
| 461 |
+
|
| 462 |
+
# hacks to handle special cases
|
| 463 |
+
if isinstance(function, MatrixBase):
|
| 464 |
+
return function.applyfunc(
|
| 465 |
+
lambda f: self.func(f, *self.limits).doit(**hints))
|
| 466 |
+
|
| 467 |
+
if isinstance(function, FormalPowerSeries):
|
| 468 |
+
if len(self.limits) > 1:
|
| 469 |
+
raise NotImplementedError
|
| 470 |
+
xab = self.limits[0]
|
| 471 |
+
if len(xab) > 1:
|
| 472 |
+
return function.integrate(xab, **eval_kwargs)
|
| 473 |
+
else:
|
| 474 |
+
return function.integrate(xab[0], **eval_kwargs)
|
| 475 |
+
|
| 476 |
+
# There is no trivial answer and special handling
|
| 477 |
+
# is done so continue
|
| 478 |
+
|
| 479 |
+
# first make sure any definite limits have integration
|
| 480 |
+
# variables with matching assumptions
|
| 481 |
+
reps = {}
|
| 482 |
+
for xab in self.limits:
|
| 483 |
+
if len(xab) != 3:
|
| 484 |
+
# it makes sense to just make
|
| 485 |
+
# all x real but in practice with the
|
| 486 |
+
# current state of integration...this
|
| 487 |
+
# doesn't work out well
|
| 488 |
+
# x = xab[0]
|
| 489 |
+
# if x not in reps and not x.is_real:
|
| 490 |
+
# reps[x] = Dummy(real=True)
|
| 491 |
+
continue
|
| 492 |
+
x, a, b = xab
|
| 493 |
+
l = (a, b)
|
| 494 |
+
if all(i.is_nonnegative for i in l) and not x.is_nonnegative:
|
| 495 |
+
d = Dummy(positive=True)
|
| 496 |
+
elif all(i.is_nonpositive for i in l) and not x.is_nonpositive:
|
| 497 |
+
d = Dummy(negative=True)
|
| 498 |
+
elif all(i.is_real for i in l) and not x.is_real:
|
| 499 |
+
d = Dummy(real=True)
|
| 500 |
+
else:
|
| 501 |
+
d = None
|
| 502 |
+
if d:
|
| 503 |
+
reps[x] = d
|
| 504 |
+
if reps:
|
| 505 |
+
undo = {v: k for k, v in reps.items()}
|
| 506 |
+
did = self.xreplace(reps).doit(**hints)
|
| 507 |
+
if isinstance(did, tuple): # when separate=True
|
| 508 |
+
did = tuple([i.xreplace(undo) for i in did])
|
| 509 |
+
else:
|
| 510 |
+
did = did.xreplace(undo)
|
| 511 |
+
return did
|
| 512 |
+
|
| 513 |
+
# continue with existing assumptions
|
| 514 |
+
undone_limits = []
|
| 515 |
+
# ulj = free symbols of any undone limits' upper and lower limits
|
| 516 |
+
ulj = set()
|
| 517 |
+
for xab in self.limits:
|
| 518 |
+
# compute uli, the free symbols in the
|
| 519 |
+
# Upper and Lower limits of limit I
|
| 520 |
+
if len(xab) == 1:
|
| 521 |
+
uli = set(xab[:1])
|
| 522 |
+
elif len(xab) == 2:
|
| 523 |
+
uli = xab[1].free_symbols
|
| 524 |
+
elif len(xab) == 3:
|
| 525 |
+
uli = xab[1].free_symbols.union(xab[2].free_symbols)
|
| 526 |
+
# this integral can be done as long as there is no blocking
|
| 527 |
+
# limit that has been undone. An undone limit is blocking if
|
| 528 |
+
# it contains an integration variable that is in this limit's
|
| 529 |
+
# upper or lower free symbols or vice versa
|
| 530 |
+
if xab[0] in ulj or any(v[0] in uli for v in undone_limits):
|
| 531 |
+
undone_limits.append(xab)
|
| 532 |
+
ulj.update(uli)
|
| 533 |
+
function = self.func(*([function] + [xab]))
|
| 534 |
+
factored_function = function.factor()
|
| 535 |
+
if not isinstance(factored_function, Integral):
|
| 536 |
+
function = factored_function
|
| 537 |
+
continue
|
| 538 |
+
|
| 539 |
+
if function.has(Abs, sign) and (
|
| 540 |
+
(len(xab) < 3 and all(x.is_extended_real for x in xab)) or
|
| 541 |
+
(len(xab) == 3 and all(x.is_extended_real and not x.is_infinite for
|
| 542 |
+
x in xab[1:]))):
|
| 543 |
+
# some improper integrals are better off with Abs
|
| 544 |
+
xr = Dummy("xr", real=True)
|
| 545 |
+
function = (function.xreplace({xab[0]: xr})
|
| 546 |
+
.rewrite(Piecewise).xreplace({xr: xab[0]}))
|
| 547 |
+
elif function.has(Min, Max):
|
| 548 |
+
function = function.rewrite(Piecewise)
|
| 549 |
+
if (function.has(Piecewise) and
|
| 550 |
+
not isinstance(function, Piecewise)):
|
| 551 |
+
function = piecewise_fold(function)
|
| 552 |
+
if isinstance(function, Piecewise):
|
| 553 |
+
if len(xab) == 1:
|
| 554 |
+
antideriv = function._eval_integral(xab[0],
|
| 555 |
+
**eval_kwargs)
|
| 556 |
+
else:
|
| 557 |
+
antideriv = self._eval_integral(
|
| 558 |
+
function, xab[0], **eval_kwargs)
|
| 559 |
+
else:
|
| 560 |
+
# There are a number of tradeoffs in using the
|
| 561 |
+
# Meijer G method. It can sometimes be a lot faster
|
| 562 |
+
# than other methods, and sometimes slower. And
|
| 563 |
+
# there are certain types of integrals for which it
|
| 564 |
+
# is more likely to work than others. These
|
| 565 |
+
# heuristics are incorporated in deciding what
|
| 566 |
+
# integration methods to try, in what order. See the
|
| 567 |
+
# integrate() docstring for details.
|
| 568 |
+
def try_meijerg(function, xab):
|
| 569 |
+
ret = None
|
| 570 |
+
if len(xab) == 3 and meijerg is not False:
|
| 571 |
+
x, a, b = xab
|
| 572 |
+
try:
|
| 573 |
+
res = meijerint_definite(function, x, a, b)
|
| 574 |
+
except NotImplementedError:
|
| 575 |
+
_debug('NotImplementedError '
|
| 576 |
+
'from meijerint_definite')
|
| 577 |
+
res = None
|
| 578 |
+
if res is not None:
|
| 579 |
+
f, cond = res
|
| 580 |
+
if conds == 'piecewise':
|
| 581 |
+
u = self.func(function, (x, a, b))
|
| 582 |
+
# if Piecewise modifies cond too
|
| 583 |
+
# much it may not be recognized by
|
| 584 |
+
# _condsimp pattern matching so just
|
| 585 |
+
# turn off all evaluation
|
| 586 |
+
return Piecewise((f, cond), (u, True),
|
| 587 |
+
evaluate=False)
|
| 588 |
+
elif conds == 'separate':
|
| 589 |
+
if len(self.limits) != 1:
|
| 590 |
+
raise ValueError(filldedent('''
|
| 591 |
+
conds=separate not supported in
|
| 592 |
+
multiple integrals'''))
|
| 593 |
+
ret = f, cond
|
| 594 |
+
else:
|
| 595 |
+
ret = f
|
| 596 |
+
return ret
|
| 597 |
+
|
| 598 |
+
meijerg1 = meijerg
|
| 599 |
+
if (meijerg is not False and
|
| 600 |
+
len(xab) == 3 and xab[1].is_extended_real and xab[2].is_extended_real
|
| 601 |
+
and not function.is_Poly and
|
| 602 |
+
(xab[1].has(oo, -oo) or xab[2].has(oo, -oo))):
|
| 603 |
+
ret = try_meijerg(function, xab)
|
| 604 |
+
if ret is not None:
|
| 605 |
+
function = ret
|
| 606 |
+
continue
|
| 607 |
+
meijerg1 = False
|
| 608 |
+
# If the special meijerg code did not succeed in
|
| 609 |
+
# finding a definite integral, then the code using
|
| 610 |
+
# meijerint_indefinite will not either (it might
|
| 611 |
+
# find an antiderivative, but the answer is likely
|
| 612 |
+
# to be nonsensical). Thus if we are requested to
|
| 613 |
+
# only use Meijer G-function methods, we give up at
|
| 614 |
+
# this stage. Otherwise we just disable G-function
|
| 615 |
+
# methods.
|
| 616 |
+
if meijerg1 is False and meijerg is True:
|
| 617 |
+
antideriv = None
|
| 618 |
+
else:
|
| 619 |
+
antideriv = self._eval_integral(
|
| 620 |
+
function, xab[0], **eval_kwargs)
|
| 621 |
+
if antideriv is None and meijerg is True:
|
| 622 |
+
ret = try_meijerg(function, xab)
|
| 623 |
+
if ret is not None:
|
| 624 |
+
function = ret
|
| 625 |
+
continue
|
| 626 |
+
|
| 627 |
+
final = hints.get('final', True)
|
| 628 |
+
# dotit may be iterated but floor terms making atan and acot
|
| 629 |
+
# continuous should only be added in the final round
|
| 630 |
+
if (final and not isinstance(antideriv, Integral) and
|
| 631 |
+
antideriv is not None):
|
| 632 |
+
for atan_term in antideriv.atoms(atan):
|
| 633 |
+
atan_arg = atan_term.args[0]
|
| 634 |
+
# Checking `atan_arg` to be linear combination of `tan` or `cot`
|
| 635 |
+
for tan_part in atan_arg.atoms(tan):
|
| 636 |
+
x1 = Dummy('x1')
|
| 637 |
+
tan_exp1 = atan_arg.subs(tan_part, x1)
|
| 638 |
+
# The coefficient of `tan` should be constant
|
| 639 |
+
coeff = tan_exp1.diff(x1)
|
| 640 |
+
if x1 not in coeff.free_symbols:
|
| 641 |
+
a = tan_part.args[0]
|
| 642 |
+
antideriv = antideriv.subs(atan_term, Add(atan_term,
|
| 643 |
+
sign(coeff)*pi*floor((a-pi/2)/pi)))
|
| 644 |
+
for cot_part in atan_arg.atoms(cot):
|
| 645 |
+
x1 = Dummy('x1')
|
| 646 |
+
cot_exp1 = atan_arg.subs(cot_part, x1)
|
| 647 |
+
# The coefficient of `cot` should be constant
|
| 648 |
+
coeff = cot_exp1.diff(x1)
|
| 649 |
+
if x1 not in coeff.free_symbols:
|
| 650 |
+
a = cot_part.args[0]
|
| 651 |
+
antideriv = antideriv.subs(atan_term, Add(atan_term,
|
| 652 |
+
sign(coeff)*pi*floor((a)/pi)))
|
| 653 |
+
|
| 654 |
+
if antideriv is None:
|
| 655 |
+
undone_limits.append(xab)
|
| 656 |
+
function = self.func(*([function] + [xab])).factor()
|
| 657 |
+
factored_function = function.factor()
|
| 658 |
+
if not isinstance(factored_function, Integral):
|
| 659 |
+
function = factored_function
|
| 660 |
+
continue
|
| 661 |
+
else:
|
| 662 |
+
if len(xab) == 1:
|
| 663 |
+
function = antideriv
|
| 664 |
+
else:
|
| 665 |
+
if len(xab) == 3:
|
| 666 |
+
x, a, b = xab
|
| 667 |
+
elif len(xab) == 2:
|
| 668 |
+
x, b = xab
|
| 669 |
+
a = None
|
| 670 |
+
else:
|
| 671 |
+
raise NotImplementedError
|
| 672 |
+
|
| 673 |
+
if deep:
|
| 674 |
+
if isinstance(a, Basic):
|
| 675 |
+
a = a.doit(**hints)
|
| 676 |
+
if isinstance(b, Basic):
|
| 677 |
+
b = b.doit(**hints)
|
| 678 |
+
|
| 679 |
+
if antideriv.is_Poly:
|
| 680 |
+
gens = list(antideriv.gens)
|
| 681 |
+
gens.remove(x)
|
| 682 |
+
|
| 683 |
+
antideriv = antideriv.as_expr()
|
| 684 |
+
|
| 685 |
+
function = antideriv._eval_interval(x, a, b)
|
| 686 |
+
function = Poly(function, *gens)
|
| 687 |
+
else:
|
| 688 |
+
def is_indef_int(g, x):
|
| 689 |
+
return (isinstance(g, Integral) and
|
| 690 |
+
any(i == (x,) for i in g.limits))
|
| 691 |
+
|
| 692 |
+
def eval_factored(f, x, a, b):
|
| 693 |
+
# _eval_interval for integrals with
|
| 694 |
+
# (constant) factors
|
| 695 |
+
# a single indefinite integral is assumed
|
| 696 |
+
args = []
|
| 697 |
+
for g in Mul.make_args(f):
|
| 698 |
+
if is_indef_int(g, x):
|
| 699 |
+
args.append(g._eval_interval(x, a, b))
|
| 700 |
+
else:
|
| 701 |
+
args.append(g)
|
| 702 |
+
return Mul(*args)
|
| 703 |
+
|
| 704 |
+
integrals, others, piecewises = [], [], []
|
| 705 |
+
for f in Add.make_args(antideriv):
|
| 706 |
+
if any(is_indef_int(g, x)
|
| 707 |
+
for g in Mul.make_args(f)):
|
| 708 |
+
integrals.append(f)
|
| 709 |
+
elif any(isinstance(g, Piecewise)
|
| 710 |
+
for g in Mul.make_args(f)):
|
| 711 |
+
piecewises.append(piecewise_fold(f))
|
| 712 |
+
else:
|
| 713 |
+
others.append(f)
|
| 714 |
+
uneval = Add(*[eval_factored(f, x, a, b)
|
| 715 |
+
for f in integrals])
|
| 716 |
+
try:
|
| 717 |
+
evalued = Add(*others)._eval_interval(x, a, b)
|
| 718 |
+
evalued_pw = piecewise_fold(Add(*piecewises))._eval_interval(x, a, b)
|
| 719 |
+
function = uneval + evalued + evalued_pw
|
| 720 |
+
except NotImplementedError:
|
| 721 |
+
# This can happen if _eval_interval depends in a
|
| 722 |
+
# complicated way on limits that cannot be computed
|
| 723 |
+
undone_limits.append(xab)
|
| 724 |
+
function = self.func(*([function] + [xab]))
|
| 725 |
+
factored_function = function.factor()
|
| 726 |
+
if not isinstance(factored_function, Integral):
|
| 727 |
+
function = factored_function
|
| 728 |
+
return function
|
| 729 |
+
|
| 730 |
+
def _eval_derivative(self, sym):
|
| 731 |
+
"""Evaluate the derivative of the current Integral object by
|
| 732 |
+
differentiating under the integral sign [1], using the Fundamental
|
| 733 |
+
Theorem of Calculus [2] when possible.
|
| 734 |
+
|
| 735 |
+
Explanation
|
| 736 |
+
===========
|
| 737 |
+
|
| 738 |
+
Whenever an Integral is encountered that is equivalent to zero or
|
| 739 |
+
has an integrand that is independent of the variable of integration
|
| 740 |
+
those integrals are performed. All others are returned as Integral
|
| 741 |
+
instances which can be resolved with doit() (provided they are integrable).
|
| 742 |
+
|
| 743 |
+
References
|
| 744 |
+
==========
|
| 745 |
+
|
| 746 |
+
.. [1] https://en.wikipedia.org/wiki/Differentiation_under_the_integral_sign
|
| 747 |
+
.. [2] https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus
|
| 748 |
+
|
| 749 |
+
Examples
|
| 750 |
+
========
|
| 751 |
+
|
| 752 |
+
>>> from sympy import Integral
|
| 753 |
+
>>> from sympy.abc import x, y
|
| 754 |
+
>>> i = Integral(x + y, y, (y, 1, x))
|
| 755 |
+
>>> i.diff(x)
|
| 756 |
+
Integral(x + y, (y, x)) + Integral(1, y, (y, 1, x))
|
| 757 |
+
>>> i.doit().diff(x) == i.diff(x).doit()
|
| 758 |
+
True
|
| 759 |
+
>>> i.diff(y)
|
| 760 |
+
0
|
| 761 |
+
|
| 762 |
+
The previous must be true since there is no y in the evaluated integral:
|
| 763 |
+
|
| 764 |
+
>>> i.free_symbols
|
| 765 |
+
{x}
|
| 766 |
+
>>> i.doit()
|
| 767 |
+
2*x**3/3 - x/2 - 1/6
|
| 768 |
+
|
| 769 |
+
"""
|
| 770 |
+
|
| 771 |
+
# differentiate under the integral sign; we do not
|
| 772 |
+
# check for regularity conditions (TODO), see issue 4215
|
| 773 |
+
|
| 774 |
+
# get limits and the function
|
| 775 |
+
f, limits = self.function, list(self.limits)
|
| 776 |
+
|
| 777 |
+
# the order matters if variables of integration appear in the limits
|
| 778 |
+
# so work our way in from the outside to the inside.
|
| 779 |
+
limit = limits.pop(-1)
|
| 780 |
+
if len(limit) == 3:
|
| 781 |
+
x, a, b = limit
|
| 782 |
+
elif len(limit) == 2:
|
| 783 |
+
x, b = limit
|
| 784 |
+
a = None
|
| 785 |
+
else:
|
| 786 |
+
a = b = None
|
| 787 |
+
x = limit[0]
|
| 788 |
+
|
| 789 |
+
if limits: # f is the argument to an integral
|
| 790 |
+
f = self.func(f, *tuple(limits))
|
| 791 |
+
|
| 792 |
+
# assemble the pieces
|
| 793 |
+
def _do(f, ab):
|
| 794 |
+
dab_dsym = diff(ab, sym)
|
| 795 |
+
if not dab_dsym:
|
| 796 |
+
return S.Zero
|
| 797 |
+
if isinstance(f, Integral):
|
| 798 |
+
limits = [(x, x) if (len(l) == 1 and l[0] == x) else l
|
| 799 |
+
for l in f.limits]
|
| 800 |
+
f = self.func(f.function, *limits)
|
| 801 |
+
return f.subs(x, ab)*dab_dsym
|
| 802 |
+
|
| 803 |
+
rv = S.Zero
|
| 804 |
+
if b is not None:
|
| 805 |
+
rv += _do(f, b)
|
| 806 |
+
if a is not None:
|
| 807 |
+
rv -= _do(f, a)
|
| 808 |
+
if len(limit) == 1 and sym == x:
|
| 809 |
+
# the dummy variable *is* also the real-world variable
|
| 810 |
+
arg = f
|
| 811 |
+
rv += arg
|
| 812 |
+
else:
|
| 813 |
+
# the dummy variable might match sym but it's
|
| 814 |
+
# only a dummy and the actual variable is determined
|
| 815 |
+
# by the limits, so mask off the variable of integration
|
| 816 |
+
# while differentiating
|
| 817 |
+
u = Dummy('u')
|
| 818 |
+
arg = f.subs(x, u).diff(sym).subs(u, x)
|
| 819 |
+
if arg:
|
| 820 |
+
rv += self.func(arg, (x, a, b))
|
| 821 |
+
return rv
|
| 822 |
+
|
| 823 |
+
def _eval_integral(self, f, x, meijerg=None, risch=None, manual=None,
|
| 824 |
+
heurisch=None, conds='piecewise',final=None):
|
| 825 |
+
"""
|
| 826 |
+
Calculate the anti-derivative to the function f(x).
|
| 827 |
+
|
| 828 |
+
Explanation
|
| 829 |
+
===========
|
| 830 |
+
|
| 831 |
+
The following algorithms are applied (roughly in this order):
|
| 832 |
+
|
| 833 |
+
1. Simple heuristics (based on pattern matching and integral table):
|
| 834 |
+
|
| 835 |
+
- most frequently used functions (e.g. polynomials, products of
|
| 836 |
+
trig functions)
|
| 837 |
+
|
| 838 |
+
2. Integration of rational functions:
|
| 839 |
+
|
| 840 |
+
- A complete algorithm for integrating rational functions is
|
| 841 |
+
implemented (the Lazard-Rioboo-Trager algorithm). The algorithm
|
| 842 |
+
also uses the partial fraction decomposition algorithm
|
| 843 |
+
implemented in apart() as a preprocessor to make this process
|
| 844 |
+
faster. Note that the integral of a rational function is always
|
| 845 |
+
elementary, but in general, it may include a RootSum.
|
| 846 |
+
|
| 847 |
+
3. Full Risch algorithm:
|
| 848 |
+
|
| 849 |
+
- The Risch algorithm is a complete decision
|
| 850 |
+
procedure for integrating elementary functions, which means that
|
| 851 |
+
given any elementary function, it will either compute an
|
| 852 |
+
elementary antiderivative, or else prove that none exists.
|
| 853 |
+
Currently, part of transcendental case is implemented, meaning
|
| 854 |
+
elementary integrals containing exponentials, logarithms, and
|
| 855 |
+
(soon!) trigonometric functions can be computed. The algebraic
|
| 856 |
+
case, e.g., functions containing roots, is much more difficult
|
| 857 |
+
and is not implemented yet.
|
| 858 |
+
|
| 859 |
+
- If the routine fails (because the integrand is not elementary, or
|
| 860 |
+
because a case is not implemented yet), it continues on to the
|
| 861 |
+
next algorithms below. If the routine proves that the integrals
|
| 862 |
+
is nonelementary, it still moves on to the algorithms below,
|
| 863 |
+
because we might be able to find a closed-form solution in terms
|
| 864 |
+
of special functions. If risch=True, however, it will stop here.
|
| 865 |
+
|
| 866 |
+
4. The Meijer G-Function algorithm:
|
| 867 |
+
|
| 868 |
+
- This algorithm works by first rewriting the integrand in terms of
|
| 869 |
+
very general Meijer G-Function (meijerg in SymPy), integrating
|
| 870 |
+
it, and then rewriting the result back, if possible. This
|
| 871 |
+
algorithm is particularly powerful for definite integrals (which
|
| 872 |
+
is actually part of a different method of Integral), since it can
|
| 873 |
+
compute closed-form solutions of definite integrals even when no
|
| 874 |
+
closed-form indefinite integral exists. But it also is capable
|
| 875 |
+
of computing many indefinite integrals as well.
|
| 876 |
+
|
| 877 |
+
- Another advantage of this method is that it can use some results
|
| 878 |
+
about the Meijer G-Function to give a result in terms of a
|
| 879 |
+
Piecewise expression, which allows to express conditionally
|
| 880 |
+
convergent integrals.
|
| 881 |
+
|
| 882 |
+
- Setting meijerg=True will cause integrate() to use only this
|
| 883 |
+
method.
|
| 884 |
+
|
| 885 |
+
5. The "manual integration" algorithm:
|
| 886 |
+
|
| 887 |
+
- This algorithm tries to mimic how a person would find an
|
| 888 |
+
antiderivative by hand, for example by looking for a
|
| 889 |
+
substitution or applying integration by parts. This algorithm
|
| 890 |
+
does not handle as many integrands but can return results in a
|
| 891 |
+
more familiar form.
|
| 892 |
+
|
| 893 |
+
- Sometimes this algorithm can evaluate parts of an integral; in
|
| 894 |
+
this case integrate() will try to evaluate the rest of the
|
| 895 |
+
integrand using the other methods here.
|
| 896 |
+
|
| 897 |
+
- Setting manual=True will cause integrate() to use only this
|
| 898 |
+
method.
|
| 899 |
+
|
| 900 |
+
6. The Heuristic Risch algorithm:
|
| 901 |
+
|
| 902 |
+
- This is a heuristic version of the Risch algorithm, meaning that
|
| 903 |
+
it is not deterministic. This is tried as a last resort because
|
| 904 |
+
it can be very slow. It is still used because not enough of the
|
| 905 |
+
full Risch algorithm is implemented, so that there are still some
|
| 906 |
+
integrals that can only be computed using this method. The goal
|
| 907 |
+
is to implement enough of the Risch and Meijer G-function methods
|
| 908 |
+
so that this can be deleted.
|
| 909 |
+
|
| 910 |
+
Setting heurisch=True will cause integrate() to use only this
|
| 911 |
+
method. Set heurisch=False to not use it.
|
| 912 |
+
|
| 913 |
+
"""
|
| 914 |
+
|
| 915 |
+
from sympy.integrals.risch import risch_integrate, NonElementaryIntegral
|
| 916 |
+
from sympy.integrals.manualintegrate import manualintegrate
|
| 917 |
+
|
| 918 |
+
if risch:
|
| 919 |
+
try:
|
| 920 |
+
return risch_integrate(f, x, conds=conds)
|
| 921 |
+
except NotImplementedError:
|
| 922 |
+
return None
|
| 923 |
+
|
| 924 |
+
if manual:
|
| 925 |
+
try:
|
| 926 |
+
result = manualintegrate(f, x)
|
| 927 |
+
if result is not None and result.func != Integral:
|
| 928 |
+
return result
|
| 929 |
+
except (ValueError, PolynomialError):
|
| 930 |
+
pass
|
| 931 |
+
|
| 932 |
+
eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual,
|
| 933 |
+
"heurisch": heurisch, "conds": conds}
|
| 934 |
+
|
| 935 |
+
# if it is a poly(x) then let the polynomial integrate itself (fast)
|
| 936 |
+
#
|
| 937 |
+
# It is important to make this check first, otherwise the other code
|
| 938 |
+
# will return a SymPy expression instead of a Polynomial.
|
| 939 |
+
#
|
| 940 |
+
# see Polynomial for details.
|
| 941 |
+
if isinstance(f, Poly) and not (manual or meijerg or risch):
|
| 942 |
+
# Note: this is deprecated, but the deprecation warning is already
|
| 943 |
+
# issued in the Integral constructor.
|
| 944 |
+
return f.integrate(x)
|
| 945 |
+
|
| 946 |
+
# Piecewise antiderivatives need to call special integrate.
|
| 947 |
+
if isinstance(f, Piecewise):
|
| 948 |
+
return f.piecewise_integrate(x, **eval_kwargs)
|
| 949 |
+
|
| 950 |
+
# let's cut it short if `f` does not depend on `x`; if
|
| 951 |
+
# x is only a dummy, that will be handled below
|
| 952 |
+
if not f.has(x):
|
| 953 |
+
return f*x
|
| 954 |
+
|
| 955 |
+
# try to convert to poly(x) and then integrate if successful (fast)
|
| 956 |
+
poly = f.as_poly(x)
|
| 957 |
+
if poly is not None and not (manual or meijerg or risch):
|
| 958 |
+
return poly.integrate().as_expr()
|
| 959 |
+
|
| 960 |
+
if risch is not False:
|
| 961 |
+
try:
|
| 962 |
+
result, i = risch_integrate(f, x, separate_integral=True,
|
| 963 |
+
conds=conds)
|
| 964 |
+
except NotImplementedError:
|
| 965 |
+
pass
|
| 966 |
+
else:
|
| 967 |
+
if i:
|
| 968 |
+
# There was a nonelementary integral. Try integrating it.
|
| 969 |
+
|
| 970 |
+
# if no part of the NonElementaryIntegral is integrated by
|
| 971 |
+
# the Risch algorithm, then use the original function to
|
| 972 |
+
# integrate, instead of re-written one
|
| 973 |
+
if result == 0:
|
| 974 |
+
return NonElementaryIntegral(f, x).doit(risch=False)
|
| 975 |
+
else:
|
| 976 |
+
return result + i.doit(risch=False)
|
| 977 |
+
else:
|
| 978 |
+
return result
|
| 979 |
+
|
| 980 |
+
# since Integral(f=g1+g2+...) == Integral(g1) + Integral(g2) + ...
|
| 981 |
+
# we are going to handle Add terms separately,
|
| 982 |
+
# if `f` is not Add -- we only have one term
|
| 983 |
+
|
| 984 |
+
# Note that in general, this is a bad idea, because Integral(g1) +
|
| 985 |
+
# Integral(g2) might not be computable, even if Integral(g1 + g2) is.
|
| 986 |
+
# For example, Integral(x**x + x**x*log(x)). But many heuristics only
|
| 987 |
+
# work term-wise. So we compute this step last, after trying
|
| 988 |
+
# risch_integrate. We also try risch_integrate again in this loop,
|
| 989 |
+
# because maybe the integral is a sum of an elementary part and a
|
| 990 |
+
# nonelementary part (like erf(x) + exp(x)). risch_integrate() is
|
| 991 |
+
# quite fast, so this is acceptable.
|
| 992 |
+
from sympy.simplify.fu import sincos_to_sum
|
| 993 |
+
parts = []
|
| 994 |
+
args = Add.make_args(f)
|
| 995 |
+
for g in args:
|
| 996 |
+
coeff, g = g.as_independent(x)
|
| 997 |
+
|
| 998 |
+
# g(x) = const
|
| 999 |
+
if g is S.One and not meijerg:
|
| 1000 |
+
parts.append(coeff*x)
|
| 1001 |
+
continue
|
| 1002 |
+
|
| 1003 |
+
# g(x) = expr + O(x**n)
|
| 1004 |
+
order_term = g.getO()
|
| 1005 |
+
|
| 1006 |
+
if order_term is not None:
|
| 1007 |
+
h = self._eval_integral(g.removeO(), x, **eval_kwargs)
|
| 1008 |
+
|
| 1009 |
+
if h is not None:
|
| 1010 |
+
h_order_expr = self._eval_integral(order_term.expr, x, **eval_kwargs)
|
| 1011 |
+
|
| 1012 |
+
if h_order_expr is not None:
|
| 1013 |
+
h_order_term = order_term.func(
|
| 1014 |
+
h_order_expr, *order_term.variables)
|
| 1015 |
+
parts.append(coeff*(h + h_order_term))
|
| 1016 |
+
continue
|
| 1017 |
+
|
| 1018 |
+
# NOTE: if there is O(x**n) and we fail to integrate then
|
| 1019 |
+
# there is no point in trying other methods because they
|
| 1020 |
+
# will fail, too.
|
| 1021 |
+
return None
|
| 1022 |
+
|
| 1023 |
+
# c
|
| 1024 |
+
# g(x) = (a*x+b)
|
| 1025 |
+
if g.is_Pow and not g.exp.has(x) and not meijerg:
|
| 1026 |
+
a = Wild('a', exclude=[x])
|
| 1027 |
+
b = Wild('b', exclude=[x])
|
| 1028 |
+
|
| 1029 |
+
M = g.base.match(a*x + b)
|
| 1030 |
+
|
| 1031 |
+
if M is not None:
|
| 1032 |
+
if g.exp == -1:
|
| 1033 |
+
h = log(g.base)
|
| 1034 |
+
elif conds != 'piecewise':
|
| 1035 |
+
h = g.base**(g.exp + 1) / (g.exp + 1)
|
| 1036 |
+
else:
|
| 1037 |
+
h1 = log(g.base)
|
| 1038 |
+
h2 = g.base**(g.exp + 1) / (g.exp + 1)
|
| 1039 |
+
h = Piecewise((h2, Ne(g.exp, -1)), (h1, True))
|
| 1040 |
+
|
| 1041 |
+
parts.append(coeff * h / M[a])
|
| 1042 |
+
continue
|
| 1043 |
+
|
| 1044 |
+
# poly(x)
|
| 1045 |
+
# g(x) = -------
|
| 1046 |
+
# poly(x)
|
| 1047 |
+
if g.is_rational_function(x) and not (manual or meijerg or risch):
|
| 1048 |
+
parts.append(coeff * ratint(g, x))
|
| 1049 |
+
continue
|
| 1050 |
+
|
| 1051 |
+
if not (manual or meijerg or risch):
|
| 1052 |
+
# g(x) = Mul(trig)
|
| 1053 |
+
h = trigintegrate(g, x, conds=conds)
|
| 1054 |
+
if h is not None:
|
| 1055 |
+
parts.append(coeff * h)
|
| 1056 |
+
continue
|
| 1057 |
+
|
| 1058 |
+
# g(x) has at least a DiracDelta term
|
| 1059 |
+
h = deltaintegrate(g, x)
|
| 1060 |
+
if h is not None:
|
| 1061 |
+
parts.append(coeff * h)
|
| 1062 |
+
continue
|
| 1063 |
+
|
| 1064 |
+
from .singularityfunctions import singularityintegrate
|
| 1065 |
+
# g(x) has at least a Singularity Function term
|
| 1066 |
+
h = singularityintegrate(g, x)
|
| 1067 |
+
if h is not None:
|
| 1068 |
+
parts.append(coeff * h)
|
| 1069 |
+
continue
|
| 1070 |
+
|
| 1071 |
+
# Try risch again.
|
| 1072 |
+
if risch is not False:
|
| 1073 |
+
try:
|
| 1074 |
+
h, i = risch_integrate(g, x,
|
| 1075 |
+
separate_integral=True, conds=conds)
|
| 1076 |
+
except NotImplementedError:
|
| 1077 |
+
h = None
|
| 1078 |
+
else:
|
| 1079 |
+
if i:
|
| 1080 |
+
h = h + i.doit(risch=False)
|
| 1081 |
+
|
| 1082 |
+
parts.append(coeff*h)
|
| 1083 |
+
continue
|
| 1084 |
+
|
| 1085 |
+
# fall back to heurisch
|
| 1086 |
+
if heurisch is not False:
|
| 1087 |
+
from sympy.integrals.heurisch import (heurisch as heurisch_,
|
| 1088 |
+
heurisch_wrapper)
|
| 1089 |
+
try:
|
| 1090 |
+
if conds == 'piecewise':
|
| 1091 |
+
h = heurisch_wrapper(g, x, hints=[])
|
| 1092 |
+
else:
|
| 1093 |
+
h = heurisch_(g, x, hints=[])
|
| 1094 |
+
except PolynomialError:
|
| 1095 |
+
# XXX: this exception means there is a bug in the
|
| 1096 |
+
# implementation of heuristic Risch integration
|
| 1097 |
+
# algorithm.
|
| 1098 |
+
h = None
|
| 1099 |
+
else:
|
| 1100 |
+
h = None
|
| 1101 |
+
|
| 1102 |
+
if meijerg is not False and h is None:
|
| 1103 |
+
# rewrite using G functions
|
| 1104 |
+
try:
|
| 1105 |
+
h = meijerint_indefinite(g, x)
|
| 1106 |
+
except NotImplementedError:
|
| 1107 |
+
_debug('NotImplementedError from meijerint_definite')
|
| 1108 |
+
if h is not None:
|
| 1109 |
+
parts.append(coeff * h)
|
| 1110 |
+
continue
|
| 1111 |
+
|
| 1112 |
+
if h is None and manual is not False:
|
| 1113 |
+
try:
|
| 1114 |
+
result = manualintegrate(g, x)
|
| 1115 |
+
if result is not None and not isinstance(result, Integral):
|
| 1116 |
+
if result.has(Integral) and not manual:
|
| 1117 |
+
# Try to have other algorithms do the integrals
|
| 1118 |
+
# manualintegrate can't handle,
|
| 1119 |
+
# unless we were asked to use manual only.
|
| 1120 |
+
# Keep the rest of eval_kwargs in case another
|
| 1121 |
+
# method was set to False already
|
| 1122 |
+
new_eval_kwargs = eval_kwargs
|
| 1123 |
+
new_eval_kwargs["manual"] = False
|
| 1124 |
+
new_eval_kwargs["final"] = False
|
| 1125 |
+
result = result.func(*[
|
| 1126 |
+
arg.doit(**new_eval_kwargs) if
|
| 1127 |
+
arg.has(Integral) else arg
|
| 1128 |
+
for arg in result.args
|
| 1129 |
+
]).expand(multinomial=False,
|
| 1130 |
+
log=False,
|
| 1131 |
+
power_exp=False,
|
| 1132 |
+
power_base=False)
|
| 1133 |
+
if not result.has(Integral):
|
| 1134 |
+
parts.append(coeff * result)
|
| 1135 |
+
continue
|
| 1136 |
+
except (ValueError, PolynomialError):
|
| 1137 |
+
# can't handle some SymPy expressions
|
| 1138 |
+
pass
|
| 1139 |
+
|
| 1140 |
+
# if we failed maybe it was because we had
|
| 1141 |
+
# a product that could have been expanded,
|
| 1142 |
+
# so let's try an expansion of the whole
|
| 1143 |
+
# thing before giving up; we don't try this
|
| 1144 |
+
# at the outset because there are things
|
| 1145 |
+
# that cannot be solved unless they are
|
| 1146 |
+
# NOT expanded e.g., x**x*(1+log(x)). There
|
| 1147 |
+
# should probably be a checker somewhere in this
|
| 1148 |
+
# routine to look for such cases and try to do
|
| 1149 |
+
# collection on the expressions if they are already
|
| 1150 |
+
# in an expanded form
|
| 1151 |
+
if not h and len(args) == 1:
|
| 1152 |
+
f = sincos_to_sum(f).expand(mul=True, deep=False)
|
| 1153 |
+
if f.is_Add:
|
| 1154 |
+
# Note: risch will be identical on the expanded
|
| 1155 |
+
# expression, but maybe it will be able to pick out parts,
|
| 1156 |
+
# like x*(exp(x) + erf(x)).
|
| 1157 |
+
return self._eval_integral(f, x, **eval_kwargs)
|
| 1158 |
+
|
| 1159 |
+
if h is not None:
|
| 1160 |
+
parts.append(coeff * h)
|
| 1161 |
+
else:
|
| 1162 |
+
return None
|
| 1163 |
+
|
| 1164 |
+
return Add(*parts)
|
| 1165 |
+
|
| 1166 |
+
def _eval_lseries(self, x, logx=None, cdir=0):
|
| 1167 |
+
expr = self.as_dummy()
|
| 1168 |
+
symb = x
|
| 1169 |
+
for l in expr.limits:
|
| 1170 |
+
if x in l[1:]:
|
| 1171 |
+
symb = l[0]
|
| 1172 |
+
break
|
| 1173 |
+
for term in expr.function.lseries(symb, logx):
|
| 1174 |
+
yield integrate(term, *expr.limits)
|
| 1175 |
+
|
| 1176 |
+
def _eval_nseries(self, x, n, logx=None, cdir=0):
|
| 1177 |
+
symb = x
|
| 1178 |
+
for l in self.limits:
|
| 1179 |
+
if x in l[1:]:
|
| 1180 |
+
symb = l[0]
|
| 1181 |
+
break
|
| 1182 |
+
terms, order = self.function.nseries(
|
| 1183 |
+
x=symb, n=n, logx=logx).as_coeff_add(Order)
|
| 1184 |
+
order = [o.subs(symb, x) for o in order]
|
| 1185 |
+
return integrate(terms, *self.limits) + Add(*order)*x
|
| 1186 |
+
|
| 1187 |
+
def _eval_as_leading_term(self, x, logx, cdir):
|
| 1188 |
+
series_gen = self.args[0].lseries(x)
|
| 1189 |
+
for leading_term in series_gen:
|
| 1190 |
+
if leading_term != 0:
|
| 1191 |
+
break
|
| 1192 |
+
return integrate(leading_term, *self.args[1:])
|
| 1193 |
+
|
| 1194 |
+
def _eval_simplify(self, **kwargs):
|
| 1195 |
+
expr = factor_terms(self)
|
| 1196 |
+
if isinstance(expr, Integral):
|
| 1197 |
+
from sympy.simplify.simplify import simplify
|
| 1198 |
+
return expr.func(*[simplify(i, **kwargs) for i in expr.args])
|
| 1199 |
+
return expr.simplify(**kwargs)
|
| 1200 |
+
|
| 1201 |
+
def as_sum(self, n=None, method="midpoint", evaluate=True):
|
| 1202 |
+
"""
|
| 1203 |
+
Approximates a definite integral by a sum.
|
| 1204 |
+
|
| 1205 |
+
Parameters
|
| 1206 |
+
==========
|
| 1207 |
+
|
| 1208 |
+
n :
|
| 1209 |
+
The number of subintervals to use, optional.
|
| 1210 |
+
method :
|
| 1211 |
+
One of: 'left', 'right', 'midpoint', 'trapezoid'.
|
| 1212 |
+
evaluate : bool
|
| 1213 |
+
If False, returns an unevaluated Sum expression. The default
|
| 1214 |
+
is True, evaluate the sum.
|
| 1215 |
+
|
| 1216 |
+
Notes
|
| 1217 |
+
=====
|
| 1218 |
+
|
| 1219 |
+
These methods of approximate integration are described in [1].
|
| 1220 |
+
|
| 1221 |
+
Examples
|
| 1222 |
+
========
|
| 1223 |
+
|
| 1224 |
+
>>> from sympy import Integral, sin, sqrt
|
| 1225 |
+
>>> from sympy.abc import x, n
|
| 1226 |
+
>>> e = Integral(sin(x), (x, 3, 7))
|
| 1227 |
+
>>> e
|
| 1228 |
+
Integral(sin(x), (x, 3, 7))
|
| 1229 |
+
|
| 1230 |
+
For demonstration purposes, this interval will only be split into 2
|
| 1231 |
+
regions, bounded by [3, 5] and [5, 7].
|
| 1232 |
+
|
| 1233 |
+
The left-hand rule uses function evaluations at the left of each
|
| 1234 |
+
interval:
|
| 1235 |
+
|
| 1236 |
+
>>> e.as_sum(2, 'left')
|
| 1237 |
+
2*sin(5) + 2*sin(3)
|
| 1238 |
+
|
| 1239 |
+
The midpoint rule uses evaluations at the center of each interval:
|
| 1240 |
+
|
| 1241 |
+
>>> e.as_sum(2, 'midpoint')
|
| 1242 |
+
2*sin(4) + 2*sin(6)
|
| 1243 |
+
|
| 1244 |
+
The right-hand rule uses function evaluations at the right of each
|
| 1245 |
+
interval:
|
| 1246 |
+
|
| 1247 |
+
>>> e.as_sum(2, 'right')
|
| 1248 |
+
2*sin(5) + 2*sin(7)
|
| 1249 |
+
|
| 1250 |
+
The trapezoid rule uses function evaluations on both sides of the
|
| 1251 |
+
intervals. This is equivalent to taking the average of the left and
|
| 1252 |
+
right hand rule results:
|
| 1253 |
+
|
| 1254 |
+
>>> s = e.as_sum(2, 'trapezoid')
|
| 1255 |
+
>>> s
|
| 1256 |
+
2*sin(5) + sin(3) + sin(7)
|
| 1257 |
+
>>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == s
|
| 1258 |
+
True
|
| 1259 |
+
|
| 1260 |
+
Here, the discontinuity at x = 0 can be avoided by using the
|
| 1261 |
+
midpoint or right-hand method:
|
| 1262 |
+
|
| 1263 |
+
>>> e = Integral(1/sqrt(x), (x, 0, 1))
|
| 1264 |
+
>>> e.as_sum(5).n(4)
|
| 1265 |
+
1.730
|
| 1266 |
+
>>> e.as_sum(10).n(4)
|
| 1267 |
+
1.809
|
| 1268 |
+
>>> e.doit().n(4) # the actual value is 2
|
| 1269 |
+
2.000
|
| 1270 |
+
|
| 1271 |
+
The left- or trapezoid method will encounter the discontinuity and
|
| 1272 |
+
return infinity:
|
| 1273 |
+
|
| 1274 |
+
>>> e.as_sum(5, 'left')
|
| 1275 |
+
zoo
|
| 1276 |
+
|
| 1277 |
+
The number of intervals can be symbolic. If omitted, a dummy symbol
|
| 1278 |
+
will be used for it.
|
| 1279 |
+
|
| 1280 |
+
>>> e = Integral(x**2, (x, 0, 2))
|
| 1281 |
+
>>> e.as_sum(n, 'right').expand()
|
| 1282 |
+
8/3 + 4/n + 4/(3*n**2)
|
| 1283 |
+
|
| 1284 |
+
This shows that the midpoint rule is more accurate, as its error
|
| 1285 |
+
term decays as the square of n:
|
| 1286 |
+
|
| 1287 |
+
>>> e.as_sum(method='midpoint').expand()
|
| 1288 |
+
8/3 - 2/(3*_n**2)
|
| 1289 |
+
|
| 1290 |
+
A symbolic sum is returned with evaluate=False:
|
| 1291 |
+
|
| 1292 |
+
>>> e.as_sum(n, 'midpoint', evaluate=False)
|
| 1293 |
+
2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n
|
| 1294 |
+
|
| 1295 |
+
See Also
|
| 1296 |
+
========
|
| 1297 |
+
|
| 1298 |
+
Integral.doit : Perform the integration using any hints
|
| 1299 |
+
|
| 1300 |
+
References
|
| 1301 |
+
==========
|
| 1302 |
+
|
| 1303 |
+
.. [1] https://en.wikipedia.org/wiki/Riemann_sum#Riemann_summation_methods
|
| 1304 |
+
"""
|
| 1305 |
+
|
| 1306 |
+
from sympy.concrete.summations import Sum
|
| 1307 |
+
limits = self.limits
|
| 1308 |
+
if len(limits) > 1:
|
| 1309 |
+
raise NotImplementedError(
|
| 1310 |
+
"Multidimensional midpoint rule not implemented yet")
|
| 1311 |
+
else:
|
| 1312 |
+
limit = limits[0]
|
| 1313 |
+
if (len(limit) != 3 or limit[1].is_finite is False or
|
| 1314 |
+
limit[2].is_finite is False):
|
| 1315 |
+
raise ValueError("Expecting a definite integral over "
|
| 1316 |
+
"a finite interval.")
|
| 1317 |
+
if n is None:
|
| 1318 |
+
n = Dummy('n', integer=True, positive=True)
|
| 1319 |
+
else:
|
| 1320 |
+
n = sympify(n)
|
| 1321 |
+
if (n.is_positive is False or n.is_integer is False or
|
| 1322 |
+
n.is_finite is False):
|
| 1323 |
+
raise ValueError("n must be a positive integer, got %s" % n)
|
| 1324 |
+
x, a, b = limit
|
| 1325 |
+
dx = (b - a)/n
|
| 1326 |
+
k = Dummy('k', integer=True, positive=True)
|
| 1327 |
+
f = self.function
|
| 1328 |
+
|
| 1329 |
+
if method == "left":
|
| 1330 |
+
result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n))
|
| 1331 |
+
elif method == "right":
|
| 1332 |
+
result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n))
|
| 1333 |
+
elif method == "midpoint":
|
| 1334 |
+
result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n))
|
| 1335 |
+
elif method == "trapezoid":
|
| 1336 |
+
result = dx*((f.subs(x, a) + f.subs(x, b))/2 +
|
| 1337 |
+
Sum(f.subs(x, a + k*dx), (k, 1, n - 1)))
|
| 1338 |
+
else:
|
| 1339 |
+
raise ValueError("Unknown method %s" % method)
|
| 1340 |
+
return result.doit() if evaluate else result
|
| 1341 |
+
|
| 1342 |
+
def principal_value(self, **kwargs):
|
| 1343 |
+
"""
|
| 1344 |
+
Compute the Cauchy Principal Value of the definite integral of a real function in the given interval
|
| 1345 |
+
on the real axis.
|
| 1346 |
+
|
| 1347 |
+
Explanation
|
| 1348 |
+
===========
|
| 1349 |
+
|
| 1350 |
+
In mathematics, the Cauchy principal value, is a method for assigning values to certain improper
|
| 1351 |
+
integrals which would otherwise be undefined.
|
| 1352 |
+
|
| 1353 |
+
Examples
|
| 1354 |
+
========
|
| 1355 |
+
|
| 1356 |
+
>>> from sympy import Integral, oo
|
| 1357 |
+
>>> from sympy.abc import x
|
| 1358 |
+
>>> Integral(x+1, (x, -oo, oo)).principal_value()
|
| 1359 |
+
oo
|
| 1360 |
+
>>> f = 1 / (x**3)
|
| 1361 |
+
>>> Integral(f, (x, -oo, oo)).principal_value()
|
| 1362 |
+
0
|
| 1363 |
+
>>> Integral(f, (x, -10, 10)).principal_value()
|
| 1364 |
+
0
|
| 1365 |
+
>>> Integral(f, (x, -10, oo)).principal_value() + Integral(f, (x, -oo, 10)).principal_value()
|
| 1366 |
+
0
|
| 1367 |
+
|
| 1368 |
+
References
|
| 1369 |
+
==========
|
| 1370 |
+
|
| 1371 |
+
.. [1] https://en.wikipedia.org/wiki/Cauchy_principal_value
|
| 1372 |
+
.. [2] https://mathworld.wolfram.com/CauchyPrincipalValue.html
|
| 1373 |
+
"""
|
| 1374 |
+
if len(self.limits) != 1 or len(list(self.limits[0])) != 3:
|
| 1375 |
+
raise ValueError("You need to insert a variable, lower_limit, and upper_limit correctly to calculate "
|
| 1376 |
+
"cauchy's principal value")
|
| 1377 |
+
x, a, b = self.limits[0]
|
| 1378 |
+
if not (a.is_comparable and b.is_comparable and a <= b):
|
| 1379 |
+
raise ValueError("The lower_limit must be smaller than or equal to the upper_limit to calculate "
|
| 1380 |
+
"cauchy's principal value. Also, a and b need to be comparable.")
|
| 1381 |
+
if a == b:
|
| 1382 |
+
return S.Zero
|
| 1383 |
+
|
| 1384 |
+
from sympy.calculus.singularities import singularities
|
| 1385 |
+
|
| 1386 |
+
r = Dummy('r')
|
| 1387 |
+
f = self.function
|
| 1388 |
+
singularities_list = [s for s in singularities(f, x) if s.is_comparable and a <= s <= b]
|
| 1389 |
+
for i in singularities_list:
|
| 1390 |
+
if i in (a, b):
|
| 1391 |
+
raise ValueError(
|
| 1392 |
+
'The principal value is not defined in the given interval due to singularity at %d.' % (i))
|
| 1393 |
+
F = integrate(f, x, **kwargs)
|
| 1394 |
+
if F.has(Integral):
|
| 1395 |
+
return self
|
| 1396 |
+
if a is -oo and b is oo:
|
| 1397 |
+
I = limit(F - F.subs(x, -x), x, oo)
|
| 1398 |
+
else:
|
| 1399 |
+
I = limit(F, x, b, '-') - limit(F, x, a, '+')
|
| 1400 |
+
for s in singularities_list:
|
| 1401 |
+
I += limit(((F.subs(x, s - r)) - F.subs(x, s + r)), r, 0, '+')
|
| 1402 |
+
return I
|
| 1403 |
+
|
| 1404 |
+
|
| 1405 |
+
|
| 1406 |
+
def integrate(*args, meijerg=None, conds='piecewise', risch=None, heurisch=None, manual=None, **kwargs):
|
| 1407 |
+
"""integrate(f, var, ...)
|
| 1408 |
+
|
| 1409 |
+
.. deprecated:: 1.6
|
| 1410 |
+
|
| 1411 |
+
Using ``integrate()`` with :class:`~.Poly` is deprecated. Use
|
| 1412 |
+
:meth:`.Poly.integrate` instead. See :ref:`deprecated-integrate-poly`.
|
| 1413 |
+
|
| 1414 |
+
Explanation
|
| 1415 |
+
===========
|
| 1416 |
+
|
| 1417 |
+
Compute definite or indefinite integral of one or more variables
|
| 1418 |
+
using Risch-Norman algorithm and table lookup. This procedure is
|
| 1419 |
+
able to handle elementary algebraic and transcendental functions
|
| 1420 |
+
and also a huge class of special functions, including Airy,
|
| 1421 |
+
Bessel, Whittaker and Lambert.
|
| 1422 |
+
|
| 1423 |
+
var can be:
|
| 1424 |
+
|
| 1425 |
+
- a symbol -- indefinite integration
|
| 1426 |
+
- a tuple (symbol, a) -- indefinite integration with result
|
| 1427 |
+
given with ``a`` replacing ``symbol``
|
| 1428 |
+
- a tuple (symbol, a, b) -- definite integration
|
| 1429 |
+
|
| 1430 |
+
Several variables can be specified, in which case the result is
|
| 1431 |
+
multiple integration. (If var is omitted and the integrand is
|
| 1432 |
+
univariate, the indefinite integral in that variable will be performed.)
|
| 1433 |
+
|
| 1434 |
+
Indefinite integrals are returned without terms that are independent
|
| 1435 |
+
of the integration variables. (see examples)
|
| 1436 |
+
|
| 1437 |
+
Definite improper integrals often entail delicate convergence
|
| 1438 |
+
conditions. Pass conds='piecewise', 'separate' or 'none' to have
|
| 1439 |
+
these returned, respectively, as a Piecewise function, as a separate
|
| 1440 |
+
result (i.e. result will be a tuple), or not at all (default is
|
| 1441 |
+
'piecewise').
|
| 1442 |
+
|
| 1443 |
+
**Strategy**
|
| 1444 |
+
|
| 1445 |
+
SymPy uses various approaches to definite integration. One method is to
|
| 1446 |
+
find an antiderivative for the integrand, and then use the fundamental
|
| 1447 |
+
theorem of calculus. Various functions are implemented to integrate
|
| 1448 |
+
polynomial, rational and trigonometric functions, and integrands
|
| 1449 |
+
containing DiracDelta terms.
|
| 1450 |
+
|
| 1451 |
+
SymPy also implements the part of the Risch algorithm, which is a decision
|
| 1452 |
+
procedure for integrating elementary functions, i.e., the algorithm can
|
| 1453 |
+
either find an elementary antiderivative, or prove that one does not
|
| 1454 |
+
exist. There is also a (very successful, albeit somewhat slow) general
|
| 1455 |
+
implementation of the heuristic Risch algorithm. This algorithm will
|
| 1456 |
+
eventually be phased out as more of the full Risch algorithm is
|
| 1457 |
+
implemented. See the docstring of Integral._eval_integral() for more
|
| 1458 |
+
details on computing the antiderivative using algebraic methods.
|
| 1459 |
+
|
| 1460 |
+
The option risch=True can be used to use only the (full) Risch algorithm.
|
| 1461 |
+
This is useful if you want to know if an elementary function has an
|
| 1462 |
+
elementary antiderivative. If the indefinite Integral returned by this
|
| 1463 |
+
function is an instance of NonElementaryIntegral, that means that the
|
| 1464 |
+
Risch algorithm has proven that integral to be non-elementary. Note that
|
| 1465 |
+
by default, additional methods (such as the Meijer G method outlined
|
| 1466 |
+
below) are tried on these integrals, as they may be expressible in terms
|
| 1467 |
+
of special functions, so if you only care about elementary answers, use
|
| 1468 |
+
risch=True. Also note that an unevaluated Integral returned by this
|
| 1469 |
+
function is not necessarily a NonElementaryIntegral, even with risch=True,
|
| 1470 |
+
as it may just be an indication that the particular part of the Risch
|
| 1471 |
+
algorithm needed to integrate that function is not yet implemented.
|
| 1472 |
+
|
| 1473 |
+
Another family of strategies comes from re-writing the integrand in
|
| 1474 |
+
terms of so-called Meijer G-functions. Indefinite integrals of a
|
| 1475 |
+
single G-function can always be computed, and the definite integral
|
| 1476 |
+
of a product of two G-functions can be computed from zero to
|
| 1477 |
+
infinity. Various strategies are implemented to rewrite integrands
|
| 1478 |
+
as G-functions, and use this information to compute integrals (see
|
| 1479 |
+
the ``meijerint`` module).
|
| 1480 |
+
|
| 1481 |
+
The option manual=True can be used to use only an algorithm that tries
|
| 1482 |
+
to mimic integration by hand. This algorithm does not handle as many
|
| 1483 |
+
integrands as the other algorithms implemented but may return results in
|
| 1484 |
+
a more familiar form. The ``manualintegrate`` module has functions that
|
| 1485 |
+
return the steps used (see the module docstring for more information).
|
| 1486 |
+
|
| 1487 |
+
In general, the algebraic methods work best for computing
|
| 1488 |
+
antiderivatives of (possibly complicated) combinations of elementary
|
| 1489 |
+
functions. The G-function methods work best for computing definite
|
| 1490 |
+
integrals from zero to infinity of moderately complicated
|
| 1491 |
+
combinations of special functions, or indefinite integrals of very
|
| 1492 |
+
simple combinations of special functions.
|
| 1493 |
+
|
| 1494 |
+
The strategy employed by the integration code is as follows:
|
| 1495 |
+
|
| 1496 |
+
- If computing a definite integral, and both limits are real,
|
| 1497 |
+
and at least one limit is +- oo, try the G-function method of
|
| 1498 |
+
definite integration first.
|
| 1499 |
+
|
| 1500 |
+
- Try to find an antiderivative, using all available methods, ordered
|
| 1501 |
+
by performance (that is try fastest method first, slowest last; in
|
| 1502 |
+
particular polynomial integration is tried first, Meijer
|
| 1503 |
+
G-functions second to last, and heuristic Risch last).
|
| 1504 |
+
|
| 1505 |
+
- If still not successful, try G-functions irrespective of the
|
| 1506 |
+
limits.
|
| 1507 |
+
|
| 1508 |
+
The option meijerg=True, False, None can be used to, respectively:
|
| 1509 |
+
always use G-function methods and no others, never use G-function
|
| 1510 |
+
methods, or use all available methods (in order as described above).
|
| 1511 |
+
It defaults to None.
|
| 1512 |
+
|
| 1513 |
+
Examples
|
| 1514 |
+
========
|
| 1515 |
+
|
| 1516 |
+
>>> from sympy import integrate, log, exp, oo
|
| 1517 |
+
>>> from sympy.abc import a, x, y
|
| 1518 |
+
|
| 1519 |
+
>>> integrate(x*y, x)
|
| 1520 |
+
x**2*y/2
|
| 1521 |
+
|
| 1522 |
+
>>> integrate(log(x), x)
|
| 1523 |
+
x*log(x) - x
|
| 1524 |
+
|
| 1525 |
+
>>> integrate(log(x), (x, 1, a))
|
| 1526 |
+
a*log(a) - a + 1
|
| 1527 |
+
|
| 1528 |
+
>>> integrate(x)
|
| 1529 |
+
x**2/2
|
| 1530 |
+
|
| 1531 |
+
Terms that are independent of x are dropped by indefinite integration:
|
| 1532 |
+
|
| 1533 |
+
>>> from sympy import sqrt
|
| 1534 |
+
>>> integrate(sqrt(1 + x), (x, 0, x))
|
| 1535 |
+
2*(x + 1)**(3/2)/3 - 2/3
|
| 1536 |
+
>>> integrate(sqrt(1 + x), x)
|
| 1537 |
+
2*(x + 1)**(3/2)/3
|
| 1538 |
+
|
| 1539 |
+
>>> integrate(x*y)
|
| 1540 |
+
Traceback (most recent call last):
|
| 1541 |
+
...
|
| 1542 |
+
ValueError: specify integration variables to integrate x*y
|
| 1543 |
+
|
| 1544 |
+
Note that ``integrate(x)`` syntax is meant only for convenience
|
| 1545 |
+
in interactive sessions and should be avoided in library code.
|
| 1546 |
+
|
| 1547 |
+
>>> integrate(x**a*exp(-x), (x, 0, oo)) # same as conds='piecewise'
|
| 1548 |
+
Piecewise((gamma(a + 1), re(a) > -1),
|
| 1549 |
+
(Integral(x**a*exp(-x), (x, 0, oo)), True))
|
| 1550 |
+
|
| 1551 |
+
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='none')
|
| 1552 |
+
gamma(a + 1)
|
| 1553 |
+
|
| 1554 |
+
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='separate')
|
| 1555 |
+
(gamma(a + 1), re(a) > -1)
|
| 1556 |
+
|
| 1557 |
+
See Also
|
| 1558 |
+
========
|
| 1559 |
+
|
| 1560 |
+
Integral, Integral.doit
|
| 1561 |
+
|
| 1562 |
+
"""
|
| 1563 |
+
doit_flags = {
|
| 1564 |
+
'deep': False,
|
| 1565 |
+
'meijerg': meijerg,
|
| 1566 |
+
'conds': conds,
|
| 1567 |
+
'risch': risch,
|
| 1568 |
+
'heurisch': heurisch,
|
| 1569 |
+
'manual': manual
|
| 1570 |
+
}
|
| 1571 |
+
|
| 1572 |
+
integral = Integral(*args, **kwargs)
|
| 1573 |
+
|
| 1574 |
+
if isinstance(integral, Integral):
|
| 1575 |
+
return integral.doit(**doit_flags)
|
| 1576 |
+
else:
|
| 1577 |
+
new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a
|
| 1578 |
+
for a in integral.args]
|
| 1579 |
+
return integral.func(*new_args)
|
| 1580 |
+
|
| 1581 |
+
def line_integrate(field, curve, vars):
|
| 1582 |
+
"""line_integrate(field, Curve, variables)
|
| 1583 |
+
|
| 1584 |
+
Compute the line integral.
|
| 1585 |
+
|
| 1586 |
+
Examples
|
| 1587 |
+
========
|
| 1588 |
+
|
| 1589 |
+
>>> from sympy import Curve, line_integrate, E, ln
|
| 1590 |
+
>>> from sympy.abc import x, y, t
|
| 1591 |
+
>>> C = Curve([E**t + 1, E**t - 1], (t, 0, ln(2)))
|
| 1592 |
+
>>> line_integrate(x + y, C, [x, y])
|
| 1593 |
+
3*sqrt(2)
|
| 1594 |
+
|
| 1595 |
+
See Also
|
| 1596 |
+
========
|
| 1597 |
+
|
| 1598 |
+
sympy.integrals.integrals.integrate, Integral
|
| 1599 |
+
"""
|
| 1600 |
+
from sympy.geometry import Curve
|
| 1601 |
+
F = sympify(field)
|
| 1602 |
+
if not F:
|
| 1603 |
+
raise ValueError(
|
| 1604 |
+
"Expecting function specifying field as first argument.")
|
| 1605 |
+
if not isinstance(curve, Curve):
|
| 1606 |
+
raise ValueError("Expecting Curve entity as second argument.")
|
| 1607 |
+
if not is_sequence(vars):
|
| 1608 |
+
raise ValueError("Expecting ordered iterable for variables.")
|
| 1609 |
+
if len(curve.functions) != len(vars):
|
| 1610 |
+
raise ValueError("Field variable size does not match curve dimension.")
|
| 1611 |
+
|
| 1612 |
+
if curve.parameter in vars:
|
| 1613 |
+
raise ValueError("Curve parameter clashes with field parameters.")
|
| 1614 |
+
|
| 1615 |
+
# Calculate derivatives for line parameter functions
|
| 1616 |
+
# F(r) -> F(r(t)) and finally F(r(t)*r'(t))
|
| 1617 |
+
Ft = F
|
| 1618 |
+
dldt = 0
|
| 1619 |
+
for i, var in enumerate(vars):
|
| 1620 |
+
_f = curve.functions[i]
|
| 1621 |
+
_dn = diff(_f, curve.parameter)
|
| 1622 |
+
# ...arc length
|
| 1623 |
+
dldt = dldt + (_dn * _dn)
|
| 1624 |
+
Ft = Ft.subs(var, _f)
|
| 1625 |
+
Ft = Ft * sqrt(dldt)
|
| 1626 |
+
|
| 1627 |
+
integral = Integral(Ft, curve.limits).doit(deep=False)
|
| 1628 |
+
return integral
|
| 1629 |
+
|
| 1630 |
+
|
| 1631 |
+
### Property function dispatching ###
|
| 1632 |
+
|
| 1633 |
+
@shape.register(Integral)
|
| 1634 |
+
def _(expr):
|
| 1635 |
+
return shape(expr.function)
|
| 1636 |
+
|
| 1637 |
+
# Delayed imports
|
| 1638 |
+
from .deltafunctions import deltaintegrate
|
| 1639 |
+
from .meijerint import meijerint_definite, meijerint_indefinite, _debug
|
| 1640 |
+
from .trigonometry import trigintegrate
|
.venv/lib/python3.12/site-packages/sympy/integrals/intpoly.py
ADDED
|
@@ -0,0 +1,1302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 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.12/site-packages/sympy/integrals/laplace.py
ADDED
|
@@ -0,0 +1,2377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Laplace Transforms"""
|
| 2 |
+
import sys
|
| 3 |
+
import sympy
|
| 4 |
+
from sympy.core import S, pi, I
|
| 5 |
+
from sympy.core.add import Add
|
| 6 |
+
from sympy.core.cache import cacheit
|
| 7 |
+
from sympy.core.expr import Expr
|
| 8 |
+
from sympy.core.function import (
|
| 9 |
+
AppliedUndef, Derivative, expand, expand_complex, expand_mul, expand_trig,
|
| 10 |
+
Lambda, WildFunction, diff, Subs)
|
| 11 |
+
from sympy.core.mul import Mul, prod
|
| 12 |
+
from sympy.core.relational import (
|
| 13 |
+
_canonical, Ge, Gt, Lt, Unequality, Eq, Ne, Relational)
|
| 14 |
+
from sympy.core.sorting import ordered
|
| 15 |
+
from sympy.core.symbol import Dummy, symbols, Wild
|
| 16 |
+
from sympy.functions.elementary.complexes import (
|
| 17 |
+
re, im, arg, Abs, polar_lift, periodic_argument)
|
| 18 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 19 |
+
from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, asinh
|
| 20 |
+
from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
|
| 21 |
+
from sympy.functions.elementary.piecewise import (
|
| 22 |
+
Piecewise, piecewise_exclusive)
|
| 23 |
+
from sympy.functions.elementary.trigonometric import cos, sin, atan, sinc
|
| 24 |
+
from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
|
| 25 |
+
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
|
| 26 |
+
from sympy.functions.special.error_functions import erf, erfc, Ei
|
| 27 |
+
from sympy.functions.special.gamma_functions import (
|
| 28 |
+
digamma, gamma, lowergamma, uppergamma)
|
| 29 |
+
from sympy.functions.special.singularity_functions import SingularityFunction
|
| 30 |
+
from sympy.integrals import integrate, Integral
|
| 31 |
+
from sympy.integrals.transforms import (
|
| 32 |
+
_simplify, IntegralTransform, IntegralTransformError)
|
| 33 |
+
from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And
|
| 34 |
+
from sympy.matrices.matrixbase import MatrixBase
|
| 35 |
+
from sympy.polys.matrices.linsolve import _lin_eq2dict
|
| 36 |
+
from sympy.polys.polyerrors import PolynomialError
|
| 37 |
+
from sympy.polys.polyroots import roots
|
| 38 |
+
from sympy.polys.polytools import Poly
|
| 39 |
+
from sympy.polys.rationaltools import together
|
| 40 |
+
from sympy.polys.rootoftools import RootSum
|
| 41 |
+
from sympy.utilities.exceptions import (
|
| 42 |
+
sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings)
|
| 43 |
+
from sympy.utilities.misc import debugf
|
| 44 |
+
|
| 45 |
+
_LT_level = 0
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def DEBUG_WRAP(func):
|
| 49 |
+
def wrap(*args, **kwargs):
|
| 50 |
+
from sympy import SYMPY_DEBUG
|
| 51 |
+
global _LT_level
|
| 52 |
+
|
| 53 |
+
if not SYMPY_DEBUG:
|
| 54 |
+
return func(*args, **kwargs)
|
| 55 |
+
|
| 56 |
+
if _LT_level == 0:
|
| 57 |
+
print('\n' + '-'*78, file=sys.stderr)
|
| 58 |
+
print('-LT- %s%s%s' % (' '*_LT_level, func.__name__, args),
|
| 59 |
+
file=sys.stderr)
|
| 60 |
+
_LT_level += 1
|
| 61 |
+
if (
|
| 62 |
+
func.__name__ == '_laplace_transform_integration' or
|
| 63 |
+
func.__name__ == '_inverse_laplace_transform_integration'):
|
| 64 |
+
sympy.SYMPY_DEBUG = False
|
| 65 |
+
print('**** %sIntegrating ...' % (' '*_LT_level), file=sys.stderr)
|
| 66 |
+
result = func(*args, **kwargs)
|
| 67 |
+
sympy.SYMPY_DEBUG = True
|
| 68 |
+
else:
|
| 69 |
+
result = func(*args, **kwargs)
|
| 70 |
+
_LT_level -= 1
|
| 71 |
+
print('-LT- %s---> %s' % (' '*_LT_level, result), file=sys.stderr)
|
| 72 |
+
if _LT_level == 0:
|
| 73 |
+
print('-'*78 + '\n', file=sys.stderr)
|
| 74 |
+
return result
|
| 75 |
+
return wrap
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _debug(text):
|
| 79 |
+
from sympy import SYMPY_DEBUG
|
| 80 |
+
|
| 81 |
+
if SYMPY_DEBUG:
|
| 82 |
+
print('-LT- %s%s' % (' '*_LT_level, text), file=sys.stderr)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _simplifyconds(expr, s, a):
|
| 86 |
+
r"""
|
| 87 |
+
Naively simplify some conditions occurring in ``expr``,
|
| 88 |
+
given that `\operatorname{Re}(s) > a`.
|
| 89 |
+
|
| 90 |
+
Examples
|
| 91 |
+
========
|
| 92 |
+
|
| 93 |
+
>>> from sympy.integrals.laplace import _simplifyconds
|
| 94 |
+
>>> from sympy.abc import x
|
| 95 |
+
>>> from sympy import sympify as S
|
| 96 |
+
>>> _simplifyconds(abs(x**2) < 1, x, 1)
|
| 97 |
+
False
|
| 98 |
+
>>> _simplifyconds(abs(x**2) < 1, x, 2)
|
| 99 |
+
False
|
| 100 |
+
>>> _simplifyconds(abs(x**2) < 1, x, 0)
|
| 101 |
+
Abs(x**2) < 1
|
| 102 |
+
>>> _simplifyconds(abs(1/x**2) < 1, x, 1)
|
| 103 |
+
True
|
| 104 |
+
>>> _simplifyconds(S(1) < abs(x), x, 1)
|
| 105 |
+
True
|
| 106 |
+
>>> _simplifyconds(S(1) < abs(1/x), x, 1)
|
| 107 |
+
False
|
| 108 |
+
|
| 109 |
+
>>> from sympy import Ne
|
| 110 |
+
>>> _simplifyconds(Ne(1, x**3), x, 1)
|
| 111 |
+
True
|
| 112 |
+
>>> _simplifyconds(Ne(1, x**3), x, 2)
|
| 113 |
+
True
|
| 114 |
+
>>> _simplifyconds(Ne(1, x**3), x, 0)
|
| 115 |
+
Ne(1, x**3)
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
def power(ex):
|
| 119 |
+
if ex == s:
|
| 120 |
+
return 1
|
| 121 |
+
if ex.is_Pow and ex.base == s:
|
| 122 |
+
return ex.exp
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
def bigger(ex1, ex2):
|
| 126 |
+
""" Return True only if |ex1| > |ex2|, False only if |ex1| < |ex2|.
|
| 127 |
+
Else return None. """
|
| 128 |
+
if ex1.has(s) and ex2.has(s):
|
| 129 |
+
return None
|
| 130 |
+
if isinstance(ex1, Abs):
|
| 131 |
+
ex1 = ex1.args[0]
|
| 132 |
+
if isinstance(ex2, Abs):
|
| 133 |
+
ex2 = ex2.args[0]
|
| 134 |
+
if ex1.has(s):
|
| 135 |
+
return bigger(1/ex2, 1/ex1)
|
| 136 |
+
n = power(ex2)
|
| 137 |
+
if n is None:
|
| 138 |
+
return None
|
| 139 |
+
try:
|
| 140 |
+
if n > 0 and (Abs(ex1) <= Abs(a)**n) == S.true:
|
| 141 |
+
return False
|
| 142 |
+
if n < 0 and (Abs(ex1) >= Abs(a)**n) == S.true:
|
| 143 |
+
return True
|
| 144 |
+
except TypeError:
|
| 145 |
+
return None
|
| 146 |
+
|
| 147 |
+
def replie(x, y):
|
| 148 |
+
""" simplify x < y """
|
| 149 |
+
if (not (x.is_positive or isinstance(x, Abs))
|
| 150 |
+
or not (y.is_positive or isinstance(y, Abs))):
|
| 151 |
+
return (x < y)
|
| 152 |
+
r = bigger(x, y)
|
| 153 |
+
if r is not None:
|
| 154 |
+
return not r
|
| 155 |
+
return (x < y)
|
| 156 |
+
|
| 157 |
+
def replue(x, y):
|
| 158 |
+
b = bigger(x, y)
|
| 159 |
+
if b in (True, False):
|
| 160 |
+
return True
|
| 161 |
+
return Unequality(x, y)
|
| 162 |
+
|
| 163 |
+
def repl(ex, *args):
|
| 164 |
+
if ex in (True, False):
|
| 165 |
+
return bool(ex)
|
| 166 |
+
return ex.replace(*args)
|
| 167 |
+
|
| 168 |
+
from sympy.simplify.radsimp import collect_abs
|
| 169 |
+
expr = collect_abs(expr)
|
| 170 |
+
expr = repl(expr, Lt, replie)
|
| 171 |
+
expr = repl(expr, Gt, lambda x, y: replie(y, x))
|
| 172 |
+
expr = repl(expr, Unequality, replue)
|
| 173 |
+
return S(expr)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@DEBUG_WRAP
|
| 177 |
+
def expand_dirac_delta(expr):
|
| 178 |
+
"""
|
| 179 |
+
Expand an expression involving DiractDelta to get it as a linear
|
| 180 |
+
combination of DiracDelta functions.
|
| 181 |
+
"""
|
| 182 |
+
return _lin_eq2dict(expr, expr.atoms(DiracDelta))
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@DEBUG_WRAP
|
| 186 |
+
def _laplace_transform_integration(f, t, s_, *, simplify):
|
| 187 |
+
""" The backend function for doing Laplace transforms by integration.
|
| 188 |
+
|
| 189 |
+
This backend assumes that the frontend has already split sums
|
| 190 |
+
such that `f` is to an addition anymore.
|
| 191 |
+
"""
|
| 192 |
+
s = Dummy('s')
|
| 193 |
+
|
| 194 |
+
if f.has(DiracDelta):
|
| 195 |
+
return None
|
| 196 |
+
|
| 197 |
+
F = integrate(f*exp(-s*t), (t, S.Zero, S.Infinity))
|
| 198 |
+
|
| 199 |
+
if not F.has(Integral):
|
| 200 |
+
return _simplify(F.subs(s, s_), simplify), S.NegativeInfinity, S.true
|
| 201 |
+
|
| 202 |
+
if not F.is_Piecewise:
|
| 203 |
+
return None
|
| 204 |
+
|
| 205 |
+
F, cond = F.args[0]
|
| 206 |
+
if F.has(Integral):
|
| 207 |
+
return None
|
| 208 |
+
|
| 209 |
+
def process_conds(conds):
|
| 210 |
+
""" Turn ``conds`` into a strip and auxiliary conditions. """
|
| 211 |
+
from sympy.solvers.inequalities import _solve_inequality
|
| 212 |
+
a = S.NegativeInfinity
|
| 213 |
+
aux = S.true
|
| 214 |
+
conds = conjuncts(to_cnf(conds))
|
| 215 |
+
p, q, w1, w2, w3, w4, w5 = symbols(
|
| 216 |
+
'p q w1 w2 w3 w4 w5', cls=Wild, exclude=[s])
|
| 217 |
+
patterns = (
|
| 218 |
+
p*Abs(arg((s + w3)*q)) < w2,
|
| 219 |
+
p*Abs(arg((s + w3)*q)) <= w2,
|
| 220 |
+
Abs(periodic_argument((s + w3)**p*q, w1)) < w2,
|
| 221 |
+
Abs(periodic_argument((s + w3)**p*q, w1)) <= w2,
|
| 222 |
+
Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) < w2,
|
| 223 |
+
Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) <= w2)
|
| 224 |
+
for c in conds:
|
| 225 |
+
a_ = S.Infinity
|
| 226 |
+
aux_ = []
|
| 227 |
+
for d in disjuncts(c):
|
| 228 |
+
if d.is_Relational and s in d.rhs.free_symbols:
|
| 229 |
+
d = d.reversed
|
| 230 |
+
if d.is_Relational and isinstance(d, (Ge, Gt)):
|
| 231 |
+
d = d.reversedsign
|
| 232 |
+
for pat in patterns:
|
| 233 |
+
m = d.match(pat)
|
| 234 |
+
if m:
|
| 235 |
+
break
|
| 236 |
+
if m and m[q].is_positive and m[w2]/m[p] == pi/2:
|
| 237 |
+
d = -re(s + m[w3]) < 0
|
| 238 |
+
m = d.match(p - cos(w1*Abs(arg(s*w5))*w2)*Abs(s**w3)**w4 < 0)
|
| 239 |
+
if not m:
|
| 240 |
+
m = d.match(
|
| 241 |
+
cos(p - Abs(periodic_argument(s**w1*w5, q))*w2) *
|
| 242 |
+
Abs(s**w3)**w4 < 0)
|
| 243 |
+
if not m:
|
| 244 |
+
m = d.match(
|
| 245 |
+
p - cos(
|
| 246 |
+
Abs(periodic_argument(polar_lift(s)**w1*w5, q))*w2
|
| 247 |
+
)*Abs(s**w3)**w4 < 0)
|
| 248 |
+
if m and all(m[wild].is_positive for wild in [
|
| 249 |
+
w1, w2, w3, w4, w5]):
|
| 250 |
+
d = re(s) > m[p]
|
| 251 |
+
d_ = d.replace(
|
| 252 |
+
re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t)
|
| 253 |
+
if (
|
| 254 |
+
not d.is_Relational or d.rel_op in ('==', '!=')
|
| 255 |
+
or d_.has(s) or not d_.has(t)):
|
| 256 |
+
aux_ += [d]
|
| 257 |
+
continue
|
| 258 |
+
soln = _solve_inequality(d_, t)
|
| 259 |
+
if not soln.is_Relational or soln.rel_op in ('==', '!='):
|
| 260 |
+
aux_ += [d]
|
| 261 |
+
continue
|
| 262 |
+
if soln.lts == t:
|
| 263 |
+
return None
|
| 264 |
+
else:
|
| 265 |
+
a_ = Min(soln.lts, a_)
|
| 266 |
+
if a_ is not S.Infinity:
|
| 267 |
+
a = Max(a_, a)
|
| 268 |
+
else:
|
| 269 |
+
aux = And(aux, Or(*aux_))
|
| 270 |
+
return a, aux.canonical if aux.is_Relational else aux
|
| 271 |
+
|
| 272 |
+
conds = [process_conds(c) for c in disjuncts(cond)]
|
| 273 |
+
conds2 = [x for x in conds if x[1] !=
|
| 274 |
+
S.false and x[0] is not S.NegativeInfinity]
|
| 275 |
+
if not conds2:
|
| 276 |
+
conds2 = [x for x in conds if x[1] != S.false]
|
| 277 |
+
conds = list(ordered(conds2))
|
| 278 |
+
|
| 279 |
+
def cnt(expr):
|
| 280 |
+
if expr in (True, False):
|
| 281 |
+
return 0
|
| 282 |
+
return expr.count_ops()
|
| 283 |
+
conds.sort(key=lambda x: (-x[0], cnt(x[1])))
|
| 284 |
+
|
| 285 |
+
if not conds:
|
| 286 |
+
return None
|
| 287 |
+
a, aux = conds[0] # XXX is [0] always the right one?
|
| 288 |
+
|
| 289 |
+
def sbs(expr):
|
| 290 |
+
return expr.subs(s, s_)
|
| 291 |
+
if simplify:
|
| 292 |
+
F = _simplifyconds(F, s, a)
|
| 293 |
+
aux = _simplifyconds(aux, s, a)
|
| 294 |
+
return _simplify(F.subs(s, s_), simplify), sbs(a), _canonical(sbs(aux))
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@DEBUG_WRAP
|
| 298 |
+
def _laplace_deep_collect(f, t):
|
| 299 |
+
"""
|
| 300 |
+
This is an internal helper function that traverses through the expression
|
| 301 |
+
tree of `f(t)` and collects arguments. The purpose of it is that
|
| 302 |
+
anything like `f(w*t-1*t-c)` will be written as `f((w-1)*t-c)` such that
|
| 303 |
+
it can match `f(a*t+b)`.
|
| 304 |
+
"""
|
| 305 |
+
if not isinstance(f, Expr):
|
| 306 |
+
return f
|
| 307 |
+
if (p := f.as_poly(t)) is not None:
|
| 308 |
+
return p.as_expr()
|
| 309 |
+
func = f.func
|
| 310 |
+
args = [_laplace_deep_collect(arg, t) for arg in f.args]
|
| 311 |
+
return func(*args)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
@cacheit
|
| 315 |
+
def _laplace_build_rules():
|
| 316 |
+
"""
|
| 317 |
+
This is an internal helper function that returns the table of Laplace
|
| 318 |
+
transform rules in terms of the time variable `t` and the frequency
|
| 319 |
+
variable `s`. It is used by ``_laplace_apply_rules``. Each entry is a
|
| 320 |
+
tuple containing:
|
| 321 |
+
|
| 322 |
+
(time domain pattern,
|
| 323 |
+
frequency-domain replacement,
|
| 324 |
+
condition for the rule to be applied,
|
| 325 |
+
convergence plane,
|
| 326 |
+
preparation function)
|
| 327 |
+
|
| 328 |
+
The preparation function is a function with one argument that is applied
|
| 329 |
+
to the expression before matching. For most rules it should be
|
| 330 |
+
``_laplace_deep_collect``.
|
| 331 |
+
"""
|
| 332 |
+
t = Dummy('t')
|
| 333 |
+
s = Dummy('s')
|
| 334 |
+
a = Wild('a', exclude=[t])
|
| 335 |
+
b = Wild('b', exclude=[t])
|
| 336 |
+
n = Wild('n', exclude=[t])
|
| 337 |
+
tau = Wild('tau', exclude=[t])
|
| 338 |
+
omega = Wild('omega', exclude=[t])
|
| 339 |
+
def dco(f): return _laplace_deep_collect(f, t)
|
| 340 |
+
_debug('_laplace_build_rules is building rules')
|
| 341 |
+
|
| 342 |
+
laplace_transform_rules = [
|
| 343 |
+
(a, a/s,
|
| 344 |
+
S.true, S.Zero, dco), # 4.2.1
|
| 345 |
+
(DiracDelta(a*t-b), exp(-s*b/a)/Abs(a),
|
| 346 |
+
Or(And(a > 0, b >= 0), And(a < 0, b <= 0)),
|
| 347 |
+
S.NegativeInfinity, dco), # Not in Bateman54
|
| 348 |
+
(DiracDelta(a*t-b), S(0),
|
| 349 |
+
Or(And(a < 0, b >= 0), And(a > 0, b <= 0)),
|
| 350 |
+
S.NegativeInfinity, dco), # Not in Bateman54
|
| 351 |
+
(Heaviside(a*t-b), exp(-s*b/a)/s,
|
| 352 |
+
And(a > 0, b > 0), S.Zero, dco), # 4.4.1
|
| 353 |
+
(Heaviside(a*t-b), (1-exp(-s*b/a))/s,
|
| 354 |
+
And(a < 0, b < 0), S.Zero, dco), # 4.4.1
|
| 355 |
+
(Heaviside(a*t-b), 1/s,
|
| 356 |
+
And(a > 0, b <= 0), S.Zero, dco), # 4.4.1
|
| 357 |
+
(Heaviside(a*t-b), 0,
|
| 358 |
+
And(a < 0, b > 0), S.Zero, dco), # 4.4.1
|
| 359 |
+
(t, 1/s**2,
|
| 360 |
+
S.true, S.Zero, dco), # 4.2.3
|
| 361 |
+
(1/(a*t+b), -exp(-b/a*s)*Ei(-b/a*s)/a,
|
| 362 |
+
Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.6
|
| 363 |
+
(1/sqrt(a*t+b), sqrt(a*pi/s)*exp(b/a*s)*erfc(sqrt(b/a*s))/a,
|
| 364 |
+
Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.18
|
| 365 |
+
((a*t+b)**(-S(3)/2),
|
| 366 |
+
2*b**(-S(1)/2)-2*(pi*s/a)**(S(1)/2)*exp(b/a*s) * erfc(sqrt(b/a*s))/a,
|
| 367 |
+
Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.20
|
| 368 |
+
(sqrt(t)/(t+b), sqrt(pi/s)-pi*sqrt(b)*exp(b*s)*erfc(sqrt(b*s)),
|
| 369 |
+
Abs(arg(b)) < pi, S.Zero, dco), # 4.2.22
|
| 370 |
+
(1/(a*sqrt(t) + t**(3/2)), pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)),
|
| 371 |
+
S.true, S.Zero, dco), # Not in Bateman54
|
| 372 |
+
(t**n, gamma(n+1)/s**(n+1),
|
| 373 |
+
n > -1, S.Zero, dco), # 4.3.1
|
| 374 |
+
((a*t+b)**n, uppergamma(n+1, b/a*s)*exp(-b/a*s)/s**(n+1)/a,
|
| 375 |
+
And(n > -1, Abs(arg(b/a)) < pi), S.Zero, dco), # 4.3.4
|
| 376 |
+
(t**n/(t+a), a**n*gamma(n+1)*uppergamma(-n, a*s),
|
| 377 |
+
And(n > -1, Abs(arg(a)) < pi), S.Zero, dco), # 4.3.7
|
| 378 |
+
(exp(a*t-tau), exp(-tau)/(s-a),
|
| 379 |
+
S.true, re(a), dco), # 4.5.1
|
| 380 |
+
(t*exp(a*t-tau), exp(-tau)/(s-a)**2,
|
| 381 |
+
S.true, re(a), dco), # 4.5.2
|
| 382 |
+
(t**n*exp(a*t), gamma(n+1)/(s-a)**(n+1),
|
| 383 |
+
re(n) > -1, re(a), dco), # 4.5.3
|
| 384 |
+
(exp(-a*t**2), sqrt(pi/4/a)*exp(s**2/4/a)*erfc(s/sqrt(4*a)),
|
| 385 |
+
re(a) > 0, S.Zero, dco), # 4.5.21
|
| 386 |
+
(t*exp(-a*t**2),
|
| 387 |
+
1/(2*a)-2/sqrt(pi)/(4*a)**(S(3)/2)*s*erfc(s/sqrt(4*a)),
|
| 388 |
+
re(a) > 0, S.Zero, dco), # 4.5.22
|
| 389 |
+
(exp(-a/t), 2*sqrt(a/s)*besselk(1, 2*sqrt(a*s)),
|
| 390 |
+
re(a) >= 0, S.Zero, dco), # 4.5.25
|
| 391 |
+
(sqrt(t)*exp(-a/t),
|
| 392 |
+
S(1)/2*sqrt(pi/s**3)*(1+2*sqrt(a*s))*exp(-2*sqrt(a*s)),
|
| 393 |
+
re(a) >= 0, S.Zero, dco), # 4.5.26
|
| 394 |
+
(exp(-a/t)/sqrt(t), sqrt(pi/s)*exp(-2*sqrt(a*s)),
|
| 395 |
+
re(a) >= 0, S.Zero, dco), # 4.5.27
|
| 396 |
+
(exp(-a/t)/(t*sqrt(t)), sqrt(pi/a)*exp(-2*sqrt(a*s)),
|
| 397 |
+
re(a) > 0, S.Zero, dco), # 4.5.28
|
| 398 |
+
(t**n*exp(-a/t), 2*(a/s)**((n+1)/2)*besselk(n+1, 2*sqrt(a*s)),
|
| 399 |
+
re(a) > 0, S.Zero, dco), # 4.5.29
|
| 400 |
+
# TODO: rules with sqrt(a*t) and sqrt(a/t) have stopped working after
|
| 401 |
+
# changes to as_base_exp
|
| 402 |
+
# (exp(-2*sqrt(a*t)),
|
| 403 |
+
# s**(-1)-sqrt(pi*a)*s**(-S(3)/2)*exp(a/s) * erfc(sqrt(a/s)),
|
| 404 |
+
# Abs(arg(a)) < pi, S.Zero, dco), # 4.5.31
|
| 405 |
+
# (exp(-2*sqrt(a*t))/sqrt(t), (pi/s)**(S(1)/2)*exp(a/s)*erfc(sqrt(a/s)),
|
| 406 |
+
# Abs(arg(a)) < pi, S.Zero, dco), # 4.5.33
|
| 407 |
+
(exp(-a*exp(-t)), a**(-s)*lowergamma(s, a),
|
| 408 |
+
S.true, S.Zero, dco), # 4.5.36
|
| 409 |
+
(exp(-a*exp(t)), a**s*uppergamma(-s, a),
|
| 410 |
+
re(a) > 0, S.Zero, dco), # 4.5.37
|
| 411 |
+
(log(a*t), -log(exp(S.EulerGamma)*s/a)/s,
|
| 412 |
+
a > 0, S.Zero, dco), # 4.6.1
|
| 413 |
+
(log(1+a*t), -exp(s/a)/s*Ei(-s/a),
|
| 414 |
+
Abs(arg(a)) < pi, S.Zero, dco), # 4.6.4
|
| 415 |
+
(log(a*t+b), (log(b)-exp(s/b/a)/s*a*Ei(-s/b))/s*a,
|
| 416 |
+
And(a > 0, Abs(arg(b)) < pi), S.Zero, dco), # 4.6.5
|
| 417 |
+
(log(t)/sqrt(t), -sqrt(pi/s)*log(4*s*exp(S.EulerGamma)),
|
| 418 |
+
S.true, S.Zero, dco), # 4.6.9
|
| 419 |
+
(t**n*log(t), gamma(n+1)*s**(-n-1)*(digamma(n+1)-log(s)),
|
| 420 |
+
re(n) > -1, S.Zero, dco), # 4.6.11
|
| 421 |
+
(log(a*t)**2, (log(exp(S.EulerGamma)*s/a)**2+pi**2/6)/s,
|
| 422 |
+
a > 0, S.Zero, dco), # 4.6.13
|
| 423 |
+
(sin(omega*t), omega/(s**2+omega**2),
|
| 424 |
+
S.true, Abs(im(omega)), dco), # 4,7,1
|
| 425 |
+
(Abs(sin(omega*t)), omega/(s**2+omega**2)*coth(pi*s/2/omega),
|
| 426 |
+
omega > 0, S.Zero, dco), # 4.7.2
|
| 427 |
+
(sin(omega*t)/t, atan(omega/s),
|
| 428 |
+
S.true, Abs(im(omega)), dco), # 4.7.16
|
| 429 |
+
(sin(omega*t)**2/t, log(1+4*omega**2/s**2)/4,
|
| 430 |
+
S.true, 2*Abs(im(omega)), dco), # 4.7.17
|
| 431 |
+
(sin(omega*t)**2/t**2,
|
| 432 |
+
omega*atan(2*omega/s)-s*log(1+4*omega**2/s**2)/4,
|
| 433 |
+
S.true, 2*Abs(im(omega)), dco), # 4.7.20
|
| 434 |
+
# (sin(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(-a/s),
|
| 435 |
+
# S.true, S.Zero, dco), # 4.7.32
|
| 436 |
+
# (sin(2*sqrt(a*t))/t, pi*erf(sqrt(a/s)),
|
| 437 |
+
# S.true, S.Zero, dco), # 4.7.34
|
| 438 |
+
(cos(omega*t), s/(s**2+omega**2),
|
| 439 |
+
S.true, Abs(im(omega)), dco), # 4.7.43
|
| 440 |
+
(cos(omega*t)**2, (s**2+2*omega**2)/(s**2+4*omega**2)/s,
|
| 441 |
+
S.true, 2*Abs(im(omega)), dco), # 4.7.45
|
| 442 |
+
# (sqrt(t)*cos(2*sqrt(a*t)), sqrt(pi)/2*s**(-S(5)/2)*(s-2*a)*exp(-a/s),
|
| 443 |
+
# S.true, S.Zero, dco), # 4.7.66
|
| 444 |
+
# (cos(2*sqrt(a*t))/sqrt(t), sqrt(pi/s)*exp(-a/s),
|
| 445 |
+
# S.true, S.Zero, dco), # 4.7.67
|
| 446 |
+
(sin(a*t)*sin(b*t), 2*a*b*s/(s**2+(a+b)**2)/(s**2+(a-b)**2),
|
| 447 |
+
S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.78
|
| 448 |
+
(cos(a*t)*sin(b*t), b*(s**2-a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2),
|
| 449 |
+
S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.79
|
| 450 |
+
(cos(a*t)*cos(b*t), s*(s**2+a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2),
|
| 451 |
+
S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.80
|
| 452 |
+
(sinh(a*t), a/(s**2-a**2),
|
| 453 |
+
S.true, Abs(re(a)), dco), # 4.9.1
|
| 454 |
+
(cosh(a*t), s/(s**2-a**2),
|
| 455 |
+
S.true, Abs(re(a)), dco), # 4.9.2
|
| 456 |
+
(sinh(a*t)**2, 2*a**2/(s**3-4*a**2*s),
|
| 457 |
+
S.true, 2*Abs(re(a)), dco), # 4.9.3
|
| 458 |
+
(cosh(a*t)**2, (s**2-2*a**2)/(s**3-4*a**2*s),
|
| 459 |
+
S.true, 2*Abs(re(a)), dco), # 4.9.4
|
| 460 |
+
(sinh(a*t)/t, log((s+a)/(s-a))/2,
|
| 461 |
+
S.true, Abs(re(a)), dco), # 4.9.12
|
| 462 |
+
(t**n*sinh(a*t), gamma(n+1)/2*((s-a)**(-n-1)-(s+a)**(-n-1)),
|
| 463 |
+
n > -2, Abs(a), dco), # 4.9.18
|
| 464 |
+
(t**n*cosh(a*t), gamma(n+1)/2*((s-a)**(-n-1)+(s+a)**(-n-1)),
|
| 465 |
+
n > -1, Abs(a), dco), # 4.9.19
|
| 466 |
+
# TODO
|
| 467 |
+
# (sinh(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(a/s),
|
| 468 |
+
# S.true, S.Zero, dco), # 4.9.34
|
| 469 |
+
# (cosh(2*sqrt(a*t)), 1/s+sqrt(pi*a)/s/sqrt(s)*exp(a/s)*erf(sqrt(a/s)),
|
| 470 |
+
# S.true, S.Zero, dco), # 4.9.35
|
| 471 |
+
# (
|
| 472 |
+
# sqrt(t)*sinh(2*sqrt(a*t)),
|
| 473 |
+
# pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a) *
|
| 474 |
+
# exp(a/s)*erf(sqrt(a/s))-a**(S(1)/2)*s**(-2),
|
| 475 |
+
# S.true, S.Zero, dco), # 4.9.36
|
| 476 |
+
# (sqrt(t)*cosh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s),
|
| 477 |
+
# S.true, S.Zero, dco), # 4.9.37
|
| 478 |
+
# (sinh(2*sqrt(a*t))/sqrt(t),
|
| 479 |
+
# pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s) * erf(sqrt(a/s)),
|
| 480 |
+
# S.true, S.Zero, dco), # 4.9.38
|
| 481 |
+
# (cosh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s),
|
| 482 |
+
# S.true, S.Zero, dco), # 4.9.39
|
| 483 |
+
# (sinh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)-1),
|
| 484 |
+
# S.true, S.Zero, dco), # 4.9.40
|
| 485 |
+
# (cosh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)+1),
|
| 486 |
+
# S.true, S.Zero, dco), # 4.9.41
|
| 487 |
+
(erf(a*t), exp(s**2/(2*a)**2)*erfc(s/(2*a))/s,
|
| 488 |
+
4*Abs(arg(a)) < pi, S.Zero, dco), # 4.12.2
|
| 489 |
+
# (erf(sqrt(a*t)), sqrt(a)/sqrt(s+a)/s,
|
| 490 |
+
# S.true, Max(S.Zero, -re(a)), dco), # 4.12.4
|
| 491 |
+
# (exp(a*t)*erf(sqrt(a*t)), sqrt(a)/sqrt(s)/(s-a),
|
| 492 |
+
# S.true, Max(S.Zero, re(a)), dco), # 4.12.5
|
| 493 |
+
# (erf(sqrt(a/t)/2), (1-exp(-sqrt(a*s)))/s,
|
| 494 |
+
# re(a) > 0, S.Zero, dco), # 4.12.6
|
| 495 |
+
# (erfc(sqrt(a*t)), (sqrt(s+a)-sqrt(a))/sqrt(s+a)/s,
|
| 496 |
+
# S.true, -re(a), dco), # 4.12.9
|
| 497 |
+
# (exp(a*t)*erfc(sqrt(a*t)), 1/(s+sqrt(a*s)),
|
| 498 |
+
# S.true, S.Zero, dco), # 4.12.10
|
| 499 |
+
# (erfc(sqrt(a/t)/2), exp(-sqrt(a*s))/s,
|
| 500 |
+
# re(a) > 0, S.Zero, dco), # 4.2.11
|
| 501 |
+
(besselj(n, a*t), a**n/(sqrt(s**2+a**2)*(s+sqrt(s**2+a**2))**n),
|
| 502 |
+
re(n) > -1, Abs(im(a)), dco), # 4.14.1
|
| 503 |
+
(t**b*besselj(n, a*t),
|
| 504 |
+
2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2+a**2)**(-n-S.Half),
|
| 505 |
+
And(re(n) > -S.Half, Eq(b, n)), Abs(im(a)), dco), # 4.14.7
|
| 506 |
+
(t**b*besselj(n, a*t),
|
| 507 |
+
2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2+a**2)**(-n-S(3)/2),
|
| 508 |
+
And(re(n) > -1, Eq(b, n+1)), Abs(im(a)), dco), # 4.14.8
|
| 509 |
+
# (besselj(0, 2*sqrt(a*t)), exp(-a/s)/s,
|
| 510 |
+
# S.true, S.Zero, dco), # 4.14.25
|
| 511 |
+
# (t**(b)*besselj(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(-a/s),
|
| 512 |
+
# And(re(n) > -1, Eq(b, n*S.Half)), S.Zero, dco), # 4.14.30
|
| 513 |
+
(besselj(0, a*sqrt(t**2+b*t)),
|
| 514 |
+
exp(b*s-b*sqrt(s**2+a**2))/sqrt(s**2+a**2),
|
| 515 |
+
Abs(arg(b)) < pi, Abs(im(a)), dco), # 4.15.19
|
| 516 |
+
(besseli(n, a*t), a**n/(sqrt(s**2-a**2)*(s+sqrt(s**2-a**2))**n),
|
| 517 |
+
re(n) > -1, Abs(re(a)), dco), # 4.16.1
|
| 518 |
+
(t**b*besseli(n, a*t),
|
| 519 |
+
2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2-a**2)**(-n-S.Half),
|
| 520 |
+
And(re(n) > -S.Half, Eq(b, n)), Abs(re(a)), dco), # 4.16.6
|
| 521 |
+
(t**b*besseli(n, a*t),
|
| 522 |
+
2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2-a**2)**(-n-S(3)/2),
|
| 523 |
+
And(re(n) > -1, Eq(b, n+1)), Abs(re(a)), dco), # 4.16.7
|
| 524 |
+
# (t**(b)*besseli(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(a/s),
|
| 525 |
+
# And(re(n) > -1, Eq(b, n*S.Half)), S.Zero, dco), # 4.16.18
|
| 526 |
+
(bessely(0, a*t), -2/pi*asinh(s/a)/sqrt(s**2+a**2),
|
| 527 |
+
S.true, Abs(im(a)), dco), # 4.15.44
|
| 528 |
+
(besselk(0, a*t), log((s + sqrt(s**2-a**2))/a)/(sqrt(s**2-a**2)),
|
| 529 |
+
S.true, -re(a), dco) # 4.16.23
|
| 530 |
+
]
|
| 531 |
+
return laplace_transform_rules, t, s
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
@DEBUG_WRAP
|
| 535 |
+
def _laplace_rule_timescale(f, t, s):
|
| 536 |
+
"""
|
| 537 |
+
This function applies the time-scaling rule of the Laplace transform in
|
| 538 |
+
a straight-forward way. For example, if it gets ``(f(a*t), t, s)``, it will
|
| 539 |
+
compute ``LaplaceTransform(f(t)/a, t, s/a)`` if ``a>0``.
|
| 540 |
+
"""
|
| 541 |
+
|
| 542 |
+
a = Wild('a', exclude=[t])
|
| 543 |
+
g = WildFunction('g', nargs=1)
|
| 544 |
+
ma1 = f.match(g)
|
| 545 |
+
if ma1:
|
| 546 |
+
arg = ma1[g].args[0].collect(t)
|
| 547 |
+
ma2 = arg.match(a*t)
|
| 548 |
+
if ma2 and ma2[a].is_positive and ma2[a] != 1:
|
| 549 |
+
_debug(' rule: time scaling (4.1.4)')
|
| 550 |
+
r, pr, cr = _laplace_transform(
|
| 551 |
+
1/ma2[a]*ma1[g].func(t), t, s/ma2[a], simplify=False)
|
| 552 |
+
return (r, pr, cr)
|
| 553 |
+
return None
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
@DEBUG_WRAP
|
| 557 |
+
def _laplace_rule_heaviside(f, t, s):
|
| 558 |
+
"""
|
| 559 |
+
This function deals with time-shifted Heaviside step functions. If the time
|
| 560 |
+
shift is positive, it applies the time-shift rule of the Laplace transform.
|
| 561 |
+
For example, if it gets ``(Heaviside(t-a)*f(t), t, s)``, it will compute
|
| 562 |
+
``exp(-a*s)*LaplaceTransform(f(t+a), t, s)``.
|
| 563 |
+
|
| 564 |
+
If the time shift is negative, the Heaviside function is simply removed
|
| 565 |
+
as it means nothing to the Laplace transform.
|
| 566 |
+
|
| 567 |
+
The function does not remove a factor ``Heaviside(t)``; this is done by
|
| 568 |
+
the simple rules.
|
| 569 |
+
"""
|
| 570 |
+
|
| 571 |
+
a = Wild('a', exclude=[t])
|
| 572 |
+
y = Wild('y')
|
| 573 |
+
g = Wild('g')
|
| 574 |
+
if ma1 := f.match(Heaviside(y) * g):
|
| 575 |
+
if ma2 := ma1[y].match(t - a):
|
| 576 |
+
if ma2[a].is_positive:
|
| 577 |
+
_debug(' rule: time shift (4.1.4)')
|
| 578 |
+
r, pr, cr = _laplace_transform(
|
| 579 |
+
ma1[g].subs(t, t + ma2[a]), t, s, simplify=False)
|
| 580 |
+
return (exp(-ma2[a] * s) * r, pr, cr)
|
| 581 |
+
if ma2[a].is_negative:
|
| 582 |
+
_debug(
|
| 583 |
+
' rule: Heaviside factor; negative time shift (4.1.4)')
|
| 584 |
+
r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False)
|
| 585 |
+
return (r, pr, cr)
|
| 586 |
+
if ma2 := ma1[y].match(a - t):
|
| 587 |
+
if ma2[a].is_positive:
|
| 588 |
+
_debug(' rule: Heaviside window open')
|
| 589 |
+
r, pr, cr = _laplace_transform(
|
| 590 |
+
(1 - Heaviside(t - ma2[a])) * ma1[g], t, s, simplify=False)
|
| 591 |
+
return (r, pr, cr)
|
| 592 |
+
if ma2[a].is_negative:
|
| 593 |
+
_debug(' rule: Heaviside window closed')
|
| 594 |
+
return (0, 0, S.true)
|
| 595 |
+
return None
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
@DEBUG_WRAP
|
| 599 |
+
def _laplace_rule_exp(f, t, s):
|
| 600 |
+
"""
|
| 601 |
+
If this function finds a factor ``exp(a*t)``, it applies the
|
| 602 |
+
frequency-shift rule of the Laplace transform and adjusts the convergence
|
| 603 |
+
plane accordingly. For example, if it gets ``(exp(-a*t)*f(t), t, s)``, it
|
| 604 |
+
will compute ``LaplaceTransform(f(t), t, s+a)``.
|
| 605 |
+
"""
|
| 606 |
+
|
| 607 |
+
a = Wild('a', exclude=[t])
|
| 608 |
+
y = Wild('y')
|
| 609 |
+
z = Wild('z')
|
| 610 |
+
ma1 = f.match(exp(y)*z)
|
| 611 |
+
if ma1:
|
| 612 |
+
ma2 = ma1[y].collect(t).match(a*t)
|
| 613 |
+
if ma2:
|
| 614 |
+
_debug(' rule: multiply with exp (4.1.5)')
|
| 615 |
+
r, pr, cr = _laplace_transform(ma1[z], t, s-ma2[a],
|
| 616 |
+
simplify=False)
|
| 617 |
+
return (r, pr+re(ma2[a]), cr)
|
| 618 |
+
return None
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
@DEBUG_WRAP
|
| 622 |
+
def _laplace_rule_delta(f, t, s):
|
| 623 |
+
"""
|
| 624 |
+
If this function finds a factor ``DiracDelta(b*t-a)``, it applies the
|
| 625 |
+
masking property of the delta distribution. For example, if it gets
|
| 626 |
+
``(DiracDelta(t-a)*f(t), t, s)``, it will return
|
| 627 |
+
``(f(a)*exp(-a*s), -a, True)``.
|
| 628 |
+
"""
|
| 629 |
+
# This rule is not in Bateman54
|
| 630 |
+
|
| 631 |
+
a = Wild('a', exclude=[t])
|
| 632 |
+
b = Wild('b', exclude=[t])
|
| 633 |
+
|
| 634 |
+
y = Wild('y')
|
| 635 |
+
z = Wild('z')
|
| 636 |
+
ma1 = f.match(DiracDelta(y)*z)
|
| 637 |
+
if ma1 and not ma1[z].has(DiracDelta):
|
| 638 |
+
ma2 = ma1[y].collect(t).match(b*t-a)
|
| 639 |
+
if ma2:
|
| 640 |
+
_debug(' rule: multiply with DiracDelta')
|
| 641 |
+
loc = ma2[a]/ma2[b]
|
| 642 |
+
if re(loc) >= 0 and im(loc) == 0:
|
| 643 |
+
fn = exp(-ma2[a]/ma2[b]*s)*ma1[z]
|
| 644 |
+
if fn.has(sin, cos):
|
| 645 |
+
# Then it may be possible that a sinc() is present in the
|
| 646 |
+
# term; let's try this:
|
| 647 |
+
fn = fn.rewrite(sinc).ratsimp()
|
| 648 |
+
n, d = [x.subs(t, ma2[a]/ma2[b]) for x in fn.as_numer_denom()]
|
| 649 |
+
if d != 0:
|
| 650 |
+
return (n/d/ma2[b], S.NegativeInfinity, S.true)
|
| 651 |
+
else:
|
| 652 |
+
return None
|
| 653 |
+
else:
|
| 654 |
+
return (0, S.NegativeInfinity, S.true)
|
| 655 |
+
if ma1[y].is_polynomial(t):
|
| 656 |
+
ro = roots(ma1[y], t)
|
| 657 |
+
if ro != {} and set(ro.values()) == {1}:
|
| 658 |
+
slope = diff(ma1[y], t)
|
| 659 |
+
r = Add(
|
| 660 |
+
*[exp(-x*s)*ma1[z].subs(t, s)/slope.subs(t, x)
|
| 661 |
+
for x in list(ro.keys()) if im(x) == 0 and re(x) >= 0])
|
| 662 |
+
return (r, S.NegativeInfinity, S.true)
|
| 663 |
+
return None
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
@DEBUG_WRAP
|
| 667 |
+
def _laplace_trig_split(fn):
|
| 668 |
+
"""
|
| 669 |
+
Helper function for `_laplace_rule_trig`. This function returns two terms
|
| 670 |
+
`f` and `g`. `f` contains all product terms with sin, cos, sinh, cosh in
|
| 671 |
+
them; `g` contains everything else.
|
| 672 |
+
"""
|
| 673 |
+
trigs = [S.One]
|
| 674 |
+
other = [S.One]
|
| 675 |
+
for term in Mul.make_args(fn):
|
| 676 |
+
if term.has(sin, cos, sinh, cosh, exp):
|
| 677 |
+
trigs.append(term)
|
| 678 |
+
else:
|
| 679 |
+
other.append(term)
|
| 680 |
+
f = Mul(*trigs)
|
| 681 |
+
g = Mul(*other)
|
| 682 |
+
return f, g
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
@DEBUG_WRAP
|
| 686 |
+
def _laplace_trig_expsum(f, t):
|
| 687 |
+
"""
|
| 688 |
+
Helper function for `_laplace_rule_trig`. This function expects the `f`
|
| 689 |
+
from `_laplace_trig_split`. It returns two lists `xm` and `xn`. `xm` is
|
| 690 |
+
a list of dictionaries with keys `k` and `a` representing a function
|
| 691 |
+
`k*exp(a*t)`. `xn` is a list of all terms that cannot be brought into
|
| 692 |
+
that form, which may happen, e.g., when a trigonometric function has
|
| 693 |
+
another function in its argument.
|
| 694 |
+
"""
|
| 695 |
+
c1 = Wild('c1', exclude=[t])
|
| 696 |
+
c0 = Wild('c0', exclude=[t])
|
| 697 |
+
p = Wild('p', exclude=[t])
|
| 698 |
+
xm = []
|
| 699 |
+
xn = []
|
| 700 |
+
|
| 701 |
+
x1 = f.rewrite(exp).expand()
|
| 702 |
+
|
| 703 |
+
for term in Add.make_args(x1):
|
| 704 |
+
if not term.has(t):
|
| 705 |
+
xm.append({'k': term, 'a': 0, re: 0, im: 0})
|
| 706 |
+
continue
|
| 707 |
+
term = _laplace_deep_collect(term.powsimp(combine='exp'), t)
|
| 708 |
+
|
| 709 |
+
if (r := term.match(p*exp(c1*t+c0))) is not None:
|
| 710 |
+
xm.append({
|
| 711 |
+
'k': r[p]*exp(r[c0]), 'a': r[c1],
|
| 712 |
+
re: re(r[c1]), im: im(r[c1])})
|
| 713 |
+
else:
|
| 714 |
+
xn.append(term)
|
| 715 |
+
return xm, xn
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
@DEBUG_WRAP
|
| 719 |
+
def _laplace_trig_ltex(xm, t, s):
|
| 720 |
+
"""
|
| 721 |
+
Helper function for `_laplace_rule_trig`. This function takes the list of
|
| 722 |
+
exponentials `xm` from `_laplace_trig_expsum` and simplifies complex
|
| 723 |
+
conjugate and real symmetric poles. It returns the result as a sum and
|
| 724 |
+
the convergence plane.
|
| 725 |
+
"""
|
| 726 |
+
results = []
|
| 727 |
+
planes = []
|
| 728 |
+
|
| 729 |
+
def _simpc(coeffs):
|
| 730 |
+
nc = coeffs.copy()
|
| 731 |
+
for k in range(len(nc)):
|
| 732 |
+
ri = nc[k].as_real_imag()
|
| 733 |
+
if ri[0].has(im):
|
| 734 |
+
nc[k] = nc[k].rewrite(cos)
|
| 735 |
+
else:
|
| 736 |
+
nc[k] = (ri[0] + I*ri[1]).rewrite(cos)
|
| 737 |
+
return nc
|
| 738 |
+
|
| 739 |
+
def _quadpole(t1, k1, k2, k3, s):
|
| 740 |
+
a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im]
|
| 741 |
+
nc = [
|
| 742 |
+
k0 + k1 + k2 + k3,
|
| 743 |
+
a*(k0 + k1 - k2 - k3) - 2*I*a_i*k1 + 2*I*a_i*k2,
|
| 744 |
+
(
|
| 745 |
+
a**2*(-k0 - k1 - k2 - k3) +
|
| 746 |
+
a*(4*I*a_i*k0 + 4*I*a_i*k3) +
|
| 747 |
+
4*a_i**2*k0 + 4*a_i**2*k3),
|
| 748 |
+
(
|
| 749 |
+
a**3*(-k0 - k1 + k2 + k3) +
|
| 750 |
+
a**2*(4*I*a_i*k0 + 2*I*a_i*k1 - 2*I*a_i*k2 - 4*I*a_i*k3) +
|
| 751 |
+
a*(4*a_i**2*k0 - 4*a_i**2*k3))
|
| 752 |
+
]
|
| 753 |
+
dc = [
|
| 754 |
+
S.One, S.Zero, 2*a_i**2 - 2*a_r**2,
|
| 755 |
+
S.Zero, a_i**4 + 2*a_i**2*a_r**2 + a_r**4]
|
| 756 |
+
n = Add(
|
| 757 |
+
*[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])])
|
| 758 |
+
d = Add(
|
| 759 |
+
*[x*s**y for x, y in zip(dc, range(len(dc))[::-1])])
|
| 760 |
+
return n/d
|
| 761 |
+
|
| 762 |
+
def _ccpole(t1, k1, s):
|
| 763 |
+
a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im]
|
| 764 |
+
nc = [k0 + k1, -a*k0 - a*k1 + 2*I*a_i*k0]
|
| 765 |
+
dc = [S.One, -2*a_r, a_i**2 + a_r**2]
|
| 766 |
+
n = Add(
|
| 767 |
+
*[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])])
|
| 768 |
+
d = Add(
|
| 769 |
+
*[x*s**y for x, y in zip(dc, range(len(dc))[::-1])])
|
| 770 |
+
return n/d
|
| 771 |
+
|
| 772 |
+
def _rspole(t1, k2, s):
|
| 773 |
+
a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im]
|
| 774 |
+
nc = [k0 + k2, a*k0 - a*k2 - 2*I*a_i*k0]
|
| 775 |
+
dc = [S.One, -2*I*a_i, -a_i**2 - a_r**2]
|
| 776 |
+
n = Add(
|
| 777 |
+
*[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])])
|
| 778 |
+
d = Add(
|
| 779 |
+
*[x*s**y for x, y in zip(dc, range(len(dc))[::-1])])
|
| 780 |
+
return n/d
|
| 781 |
+
|
| 782 |
+
def _sypole(t1, k3, s):
|
| 783 |
+
a, k0 = t1['a'], t1['k']
|
| 784 |
+
nc = [k0 + k3, a*(k0 - k3)]
|
| 785 |
+
dc = [S.One, S.Zero, -a**2]
|
| 786 |
+
n = Add(
|
| 787 |
+
*[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])])
|
| 788 |
+
d = Add(
|
| 789 |
+
*[x*s**y for x, y in zip(dc, range(len(dc))[::-1])])
|
| 790 |
+
return n/d
|
| 791 |
+
|
| 792 |
+
def _simplepole(t1, s):
|
| 793 |
+
a, k0 = t1['a'], t1['k']
|
| 794 |
+
n = k0
|
| 795 |
+
d = s - a
|
| 796 |
+
return n/d
|
| 797 |
+
|
| 798 |
+
while len(xm) > 0:
|
| 799 |
+
t1 = xm.pop()
|
| 800 |
+
i_imagsym = None
|
| 801 |
+
i_realsym = None
|
| 802 |
+
i_pointsym = None
|
| 803 |
+
# The following code checks all remaining poles. If t1 is a pole at
|
| 804 |
+
# a+b*I, then we check for a-b*I, -a+b*I, and -a-b*I, and
|
| 805 |
+
# assign the respective indices to i_imagsym, i_realsym, i_pointsym.
|
| 806 |
+
# -a-b*I / i_pointsym only applies if both a and b are != 0.
|
| 807 |
+
for i in range(len(xm)):
|
| 808 |
+
real_eq = t1[re] == xm[i][re]
|
| 809 |
+
realsym = t1[re] == -xm[i][re]
|
| 810 |
+
imag_eq = t1[im] == xm[i][im]
|
| 811 |
+
imagsym = t1[im] == -xm[i][im]
|
| 812 |
+
if realsym and imagsym and t1[re] != 0 and t1[im] != 0:
|
| 813 |
+
i_pointsym = i
|
| 814 |
+
elif realsym and imag_eq and t1[re] != 0:
|
| 815 |
+
i_realsym = i
|
| 816 |
+
elif real_eq and imagsym and t1[im] != 0:
|
| 817 |
+
i_imagsym = i
|
| 818 |
+
|
| 819 |
+
# The next part looks for four possible pole constellations:
|
| 820 |
+
# quad: a+b*I, a-b*I, -a+b*I, -a-b*I
|
| 821 |
+
# cc: a+b*I, a-b*I (a may be zero)
|
| 822 |
+
# quad: a+b*I, -a+b*I (b may be zero)
|
| 823 |
+
# point: a+b*I, -a-b*I (a!=0 and b!=0 is needed, but that has been
|
| 824 |
+
# asserted when finding i_pointsym above.)
|
| 825 |
+
# If none apply, then t1 is a simple pole.
|
| 826 |
+
if (
|
| 827 |
+
i_imagsym is not None and i_realsym is not None
|
| 828 |
+
and i_pointsym is not None):
|
| 829 |
+
results.append(
|
| 830 |
+
_quadpole(t1,
|
| 831 |
+
xm[i_imagsym]['k'], xm[i_realsym]['k'],
|
| 832 |
+
xm[i_pointsym]['k'], s))
|
| 833 |
+
planes.append(Abs(re(t1['a'])))
|
| 834 |
+
# The three additional poles have now been used; to pop them
|
| 835 |
+
# easily we have to do it from the back.
|
| 836 |
+
indices_to_pop = [i_imagsym, i_realsym, i_pointsym]
|
| 837 |
+
indices_to_pop.sort(reverse=True)
|
| 838 |
+
for i in indices_to_pop:
|
| 839 |
+
xm.pop(i)
|
| 840 |
+
elif i_imagsym is not None:
|
| 841 |
+
results.append(_ccpole(t1, xm[i_imagsym]['k'], s))
|
| 842 |
+
planes.append(t1[re])
|
| 843 |
+
xm.pop(i_imagsym)
|
| 844 |
+
elif i_realsym is not None:
|
| 845 |
+
results.append(_rspole(t1, xm[i_realsym]['k'], s))
|
| 846 |
+
planes.append(Abs(t1[re]))
|
| 847 |
+
xm.pop(i_realsym)
|
| 848 |
+
elif i_pointsym is not None:
|
| 849 |
+
results.append(_sypole(t1, xm[i_pointsym]['k'], s))
|
| 850 |
+
planes.append(Abs(t1[re]))
|
| 851 |
+
xm.pop(i_pointsym)
|
| 852 |
+
else:
|
| 853 |
+
results.append(_simplepole(t1, s))
|
| 854 |
+
planes.append(t1[re])
|
| 855 |
+
|
| 856 |
+
return Add(*results), Max(*planes)
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
@DEBUG_WRAP
|
| 860 |
+
def _laplace_rule_trig(fn, t_, s):
|
| 861 |
+
"""
|
| 862 |
+
This rule covers trigonometric factors by splitting everything into a
|
| 863 |
+
sum of exponential functions and collecting complex conjugate poles and
|
| 864 |
+
real symmetric poles.
|
| 865 |
+
"""
|
| 866 |
+
t = Dummy('t', real=True)
|
| 867 |
+
|
| 868 |
+
if not fn.has(sin, cos, sinh, cosh):
|
| 869 |
+
return None
|
| 870 |
+
|
| 871 |
+
f, g = _laplace_trig_split(fn.subs(t_, t))
|
| 872 |
+
xm, xn = _laplace_trig_expsum(f, t)
|
| 873 |
+
|
| 874 |
+
if len(xn) > 0:
|
| 875 |
+
# TODO not implemented yet, but also not important
|
| 876 |
+
return None
|
| 877 |
+
|
| 878 |
+
if not g.has(t):
|
| 879 |
+
r, p = _laplace_trig_ltex(xm, t, s)
|
| 880 |
+
return g*r, p, S.true
|
| 881 |
+
else:
|
| 882 |
+
# Just transform `g` and make frequency-shifted copies
|
| 883 |
+
planes = []
|
| 884 |
+
results = []
|
| 885 |
+
G, G_plane, G_cond = _laplace_transform(g, t, s, simplify=False)
|
| 886 |
+
for x1 in xm:
|
| 887 |
+
results.append(x1['k']*G.subs(s, s-x1['a']))
|
| 888 |
+
planes.append(G_plane+re(x1['a']))
|
| 889 |
+
return Add(*results).subs(t, t_), Max(*planes), G_cond
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
@DEBUG_WRAP
|
| 893 |
+
def _laplace_rule_diff(f, t, s):
|
| 894 |
+
"""
|
| 895 |
+
This function looks for derivatives in the time domain and replaces it
|
| 896 |
+
by factors of `s` and initial conditions in the frequency domain. For
|
| 897 |
+
example, if it gets ``(diff(f(t), t), t, s)``, it will compute
|
| 898 |
+
``s*LaplaceTransform(f(t), t, s) - f(0)``.
|
| 899 |
+
"""
|
| 900 |
+
|
| 901 |
+
a = Wild('a', exclude=[t])
|
| 902 |
+
n = Wild('n', exclude=[t])
|
| 903 |
+
g = WildFunction('g')
|
| 904 |
+
ma1 = f.match(a*Derivative(g, (t, n)))
|
| 905 |
+
if ma1 and ma1[n].is_integer:
|
| 906 |
+
m = [z.has(t) for z in ma1[g].args]
|
| 907 |
+
if sum(m) == 1:
|
| 908 |
+
_debug(' rule: time derivative (4.1.8)')
|
| 909 |
+
d = []
|
| 910 |
+
for k in range(ma1[n]):
|
| 911 |
+
if k == 0:
|
| 912 |
+
y = ma1[g].subs(t, 0)
|
| 913 |
+
else:
|
| 914 |
+
y = Derivative(ma1[g], (t, k)).subs(t, 0)
|
| 915 |
+
d.append(s**(ma1[n]-k-1)*y)
|
| 916 |
+
r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False)
|
| 917 |
+
return (ma1[a]*(s**ma1[n]*r - Add(*d)), pr, cr)
|
| 918 |
+
return None
|
| 919 |
+
|
| 920 |
+
|
| 921 |
+
@DEBUG_WRAP
|
| 922 |
+
def _laplace_rule_sdiff(f, t, s):
|
| 923 |
+
"""
|
| 924 |
+
This function looks for multiplications with polynoimials in `t` as they
|
| 925 |
+
correspond to differentiation in the frequency domain. For example, if it
|
| 926 |
+
gets ``(t*f(t), t, s)``, it will compute
|
| 927 |
+
``-Derivative(LaplaceTransform(f(t), t, s), s)``.
|
| 928 |
+
"""
|
| 929 |
+
|
| 930 |
+
if f.is_Mul:
|
| 931 |
+
pfac = [1]
|
| 932 |
+
ofac = [1]
|
| 933 |
+
for fac in Mul.make_args(f):
|
| 934 |
+
if fac.is_polynomial(t):
|
| 935 |
+
pfac.append(fac)
|
| 936 |
+
else:
|
| 937 |
+
ofac.append(fac)
|
| 938 |
+
if len(pfac) > 1:
|
| 939 |
+
pex = prod(pfac)
|
| 940 |
+
pc = Poly(pex, t).all_coeffs()
|
| 941 |
+
N = len(pc)
|
| 942 |
+
if N > 1:
|
| 943 |
+
oex = prod(ofac)
|
| 944 |
+
r_, p_, c_ = _laplace_transform(oex, t, s, simplify=False)
|
| 945 |
+
deri = [r_]
|
| 946 |
+
d1 = False
|
| 947 |
+
try:
|
| 948 |
+
d1 = -diff(deri[-1], s)
|
| 949 |
+
except ValueError:
|
| 950 |
+
d1 = False
|
| 951 |
+
if r_.has(LaplaceTransform):
|
| 952 |
+
for k in range(N-1):
|
| 953 |
+
deri.append((-1)**(k+1)*Derivative(r_, s, k+1))
|
| 954 |
+
elif d1:
|
| 955 |
+
deri.append(d1)
|
| 956 |
+
for k in range(N-2):
|
| 957 |
+
deri.append(-diff(deri[-1], s))
|
| 958 |
+
if d1:
|
| 959 |
+
r = Add(*[pc[N-n-1]*deri[n] for n in range(N)])
|
| 960 |
+
return (r, p_, c_)
|
| 961 |
+
# We still have to cover the possibility that there is a symbolic positive
|
| 962 |
+
# integer exponent.
|
| 963 |
+
n = Wild('n', exclude=[t])
|
| 964 |
+
g = Wild('g')
|
| 965 |
+
if ma1 := f.match(t**n*g):
|
| 966 |
+
if ma1[n].is_integer and ma1[n].is_positive:
|
| 967 |
+
r_, p_, c_ = _laplace_transform(ma1[g], t, s, simplify=False)
|
| 968 |
+
return (-1)**ma1[n]*diff(r_, (s, ma1[n])), p_, c_
|
| 969 |
+
return None
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
@DEBUG_WRAP
|
| 973 |
+
def _laplace_expand(f, t, s):
|
| 974 |
+
"""
|
| 975 |
+
This function tries to expand its argument with successively stronger
|
| 976 |
+
methods: first it will expand on the top level, then it will expand any
|
| 977 |
+
multiplications in depth, then it will try all available expansion methods,
|
| 978 |
+
and finally it will try to expand trigonometric functions.
|
| 979 |
+
|
| 980 |
+
If it can expand, it will then compute the Laplace transform of the
|
| 981 |
+
expanded term.
|
| 982 |
+
"""
|
| 983 |
+
|
| 984 |
+
r = expand(f, deep=False)
|
| 985 |
+
if r.is_Add:
|
| 986 |
+
return _laplace_transform(r, t, s, simplify=False)
|
| 987 |
+
r = expand_mul(f)
|
| 988 |
+
if r.is_Add:
|
| 989 |
+
return _laplace_transform(r, t, s, simplify=False)
|
| 990 |
+
r = expand(f)
|
| 991 |
+
if r.is_Add:
|
| 992 |
+
return _laplace_transform(r, t, s, simplify=False)
|
| 993 |
+
if r != f:
|
| 994 |
+
return _laplace_transform(r, t, s, simplify=False)
|
| 995 |
+
r = expand(expand_trig(f))
|
| 996 |
+
if r.is_Add:
|
| 997 |
+
return _laplace_transform(r, t, s, simplify=False)
|
| 998 |
+
return None
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
@DEBUG_WRAP
|
| 1002 |
+
def _laplace_apply_prog_rules(f, t, s):
|
| 1003 |
+
"""
|
| 1004 |
+
This function applies all program rules and returns the result if one
|
| 1005 |
+
of them gives a result.
|
| 1006 |
+
"""
|
| 1007 |
+
|
| 1008 |
+
prog_rules = [_laplace_rule_heaviside, _laplace_rule_delta,
|
| 1009 |
+
_laplace_rule_timescale, _laplace_rule_exp,
|
| 1010 |
+
_laplace_rule_trig,
|
| 1011 |
+
_laplace_rule_diff, _laplace_rule_sdiff]
|
| 1012 |
+
|
| 1013 |
+
for p_rule in prog_rules:
|
| 1014 |
+
if (L := p_rule(f, t, s)) is not None:
|
| 1015 |
+
return L
|
| 1016 |
+
return None
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
@DEBUG_WRAP
|
| 1020 |
+
def _laplace_apply_simple_rules(f, t, s):
|
| 1021 |
+
"""
|
| 1022 |
+
This function applies all simple rules and returns the result if one
|
| 1023 |
+
of them gives a result.
|
| 1024 |
+
"""
|
| 1025 |
+
simple_rules, t_, s_ = _laplace_build_rules()
|
| 1026 |
+
prep_old = ''
|
| 1027 |
+
prep_f = ''
|
| 1028 |
+
for t_dom, s_dom, check, plane, prep in simple_rules:
|
| 1029 |
+
if prep_old != prep:
|
| 1030 |
+
prep_f = prep(f.subs({t: t_}))
|
| 1031 |
+
prep_old = prep
|
| 1032 |
+
ma = prep_f.match(t_dom)
|
| 1033 |
+
if ma:
|
| 1034 |
+
try:
|
| 1035 |
+
c = check.xreplace(ma)
|
| 1036 |
+
except TypeError:
|
| 1037 |
+
# This may happen if the time function has imaginary
|
| 1038 |
+
# numbers in it. Then we give up.
|
| 1039 |
+
continue
|
| 1040 |
+
if c == S.true:
|
| 1041 |
+
return (s_dom.xreplace(ma).subs({s_: s}),
|
| 1042 |
+
plane.xreplace(ma), S.true)
|
| 1043 |
+
return None
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
@DEBUG_WRAP
|
| 1047 |
+
def _piecewise_to_heaviside(f, t):
|
| 1048 |
+
"""
|
| 1049 |
+
This function converts a Piecewise expression to an expression written
|
| 1050 |
+
with Heaviside. It is not exact, but valid in the context of the Laplace
|
| 1051 |
+
transform.
|
| 1052 |
+
"""
|
| 1053 |
+
if not t.is_real:
|
| 1054 |
+
r = Dummy('r', real=True)
|
| 1055 |
+
return _piecewise_to_heaviside(f.xreplace({t: r}), r).xreplace({r: t})
|
| 1056 |
+
x = piecewise_exclusive(f)
|
| 1057 |
+
r = []
|
| 1058 |
+
for fn, cond in x.args:
|
| 1059 |
+
# Here we do not need to do many checks because piecewise_exclusive
|
| 1060 |
+
# has a clearly predictable output. However, if any of the conditions
|
| 1061 |
+
# is not relative to t, this function just returns the input argument.
|
| 1062 |
+
if isinstance(cond, Relational) and t in cond.args:
|
| 1063 |
+
if isinstance(cond, (Eq, Ne)):
|
| 1064 |
+
# We do not cover this case; these would be single-point
|
| 1065 |
+
# exceptions that do not play a role in Laplace practice,
|
| 1066 |
+
# except if they contain Dirac impulses, and then we can
|
| 1067 |
+
# expect users to not try to use Piecewise for writing it.
|
| 1068 |
+
return f
|
| 1069 |
+
else:
|
| 1070 |
+
r.append(Heaviside(cond.gts - cond.lts)*fn)
|
| 1071 |
+
elif isinstance(cond, Or) and len(cond.args) == 2:
|
| 1072 |
+
# Or(t<2, t>4), Or(t>4, t<=2), ... in any order with any <= >=
|
| 1073 |
+
for c2 in cond.args:
|
| 1074 |
+
if c2.lhs == t:
|
| 1075 |
+
r.append(Heaviside(c2.gts - c2.lts)*fn)
|
| 1076 |
+
else:
|
| 1077 |
+
return f
|
| 1078 |
+
elif isinstance(cond, And) and len(cond.args) == 2:
|
| 1079 |
+
# And(t>2, t<4), And(t>4, t<=2), ... in any order with any <= >=
|
| 1080 |
+
c0, c1 = cond.args
|
| 1081 |
+
if c0.lhs == t and c1.lhs == t:
|
| 1082 |
+
if '>' in c0.rel_op:
|
| 1083 |
+
c0, c1 = c1, c0
|
| 1084 |
+
r.append(
|
| 1085 |
+
(Heaviside(c1.gts - c1.lts) -
|
| 1086 |
+
Heaviside(c0.lts - c0.gts))*fn)
|
| 1087 |
+
else:
|
| 1088 |
+
return f
|
| 1089 |
+
else:
|
| 1090 |
+
return f
|
| 1091 |
+
return Add(*r)
|
| 1092 |
+
|
| 1093 |
+
|
| 1094 |
+
def laplace_correspondence(f, fdict, /):
|
| 1095 |
+
"""
|
| 1096 |
+
This helper function takes a function `f` that is the result of a
|
| 1097 |
+
``laplace_transform`` or an ``inverse_laplace_transform``. It replaces all
|
| 1098 |
+
unevaluated ``LaplaceTransform(y(t), t, s)`` by `Y(s)` for any `s` and
|
| 1099 |
+
all ``InverseLaplaceTransform(Y(s), s, t)`` by `y(t)` for any `t` if
|
| 1100 |
+
``fdict`` contains a correspondence ``{y: Y}``.
|
| 1101 |
+
|
| 1102 |
+
Parameters
|
| 1103 |
+
==========
|
| 1104 |
+
|
| 1105 |
+
f : sympy expression
|
| 1106 |
+
Expression containing unevaluated ``LaplaceTransform`` or
|
| 1107 |
+
``LaplaceTransform`` objects.
|
| 1108 |
+
fdict : dictionary
|
| 1109 |
+
Dictionary containing one or more function correspondences,
|
| 1110 |
+
e.g., ``{x: X, y: Y}`` meaning that ``X`` and ``Y`` are the
|
| 1111 |
+
Laplace transforms of ``x`` and ``y``, respectively.
|
| 1112 |
+
|
| 1113 |
+
Examples
|
| 1114 |
+
========
|
| 1115 |
+
|
| 1116 |
+
>>> from sympy import laplace_transform, diff, Function
|
| 1117 |
+
>>> from sympy import laplace_correspondence, inverse_laplace_transform
|
| 1118 |
+
>>> from sympy.abc import t, s
|
| 1119 |
+
>>> y = Function("y")
|
| 1120 |
+
>>> Y = Function("Y")
|
| 1121 |
+
>>> z = Function("z")
|
| 1122 |
+
>>> Z = Function("Z")
|
| 1123 |
+
>>> f = laplace_transform(diff(y(t), t, 1) + z(t), t, s, noconds=True)
|
| 1124 |
+
>>> laplace_correspondence(f, {y: Y, z: Z})
|
| 1125 |
+
s*Y(s) + Z(s) - y(0)
|
| 1126 |
+
>>> f = inverse_laplace_transform(Y(s), s, t)
|
| 1127 |
+
>>> laplace_correspondence(f, {y: Y})
|
| 1128 |
+
y(t)
|
| 1129 |
+
"""
|
| 1130 |
+
p = Wild('p')
|
| 1131 |
+
s = Wild('s')
|
| 1132 |
+
t = Wild('t')
|
| 1133 |
+
a = Wild('a')
|
| 1134 |
+
if (
|
| 1135 |
+
not isinstance(f, Expr)
|
| 1136 |
+
or (not f.has(LaplaceTransform)
|
| 1137 |
+
and not f.has(InverseLaplaceTransform))):
|
| 1138 |
+
return f
|
| 1139 |
+
for y, Y in fdict.items():
|
| 1140 |
+
if (
|
| 1141 |
+
(m := f.match(LaplaceTransform(y(a), t, s))) is not None
|
| 1142 |
+
and m[a] == m[t]):
|
| 1143 |
+
return Y(m[s])
|
| 1144 |
+
if (
|
| 1145 |
+
(m := f.match(InverseLaplaceTransform(Y(a), s, t, p)))
|
| 1146 |
+
is not None
|
| 1147 |
+
and m[a] == m[s]):
|
| 1148 |
+
return y(m[t])
|
| 1149 |
+
func = f.func
|
| 1150 |
+
args = [laplace_correspondence(arg, fdict) for arg in f.args]
|
| 1151 |
+
return func(*args)
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
def laplace_initial_conds(f, t, fdict, /):
|
| 1155 |
+
"""
|
| 1156 |
+
This helper function takes a function `f` that is the result of a
|
| 1157 |
+
``laplace_transform``. It takes an fdict of the form ``{y: [1, 4, 2]}``,
|
| 1158 |
+
where the values in the list are the initial value, the initial slope, the
|
| 1159 |
+
initial second derivative, etc., of the function `y(t)`, and replaces all
|
| 1160 |
+
unevaluated initial conditions.
|
| 1161 |
+
|
| 1162 |
+
Parameters
|
| 1163 |
+
==========
|
| 1164 |
+
|
| 1165 |
+
f : sympy expression
|
| 1166 |
+
Expression containing initial conditions of unevaluated functions.
|
| 1167 |
+
t : sympy expression
|
| 1168 |
+
Variable for which the initial conditions are to be applied.
|
| 1169 |
+
fdict : dictionary
|
| 1170 |
+
Dictionary containing a list of initial conditions for every
|
| 1171 |
+
function, e.g., ``{y: [0, 1, 2], x: [3, 4, 5]}``. The order
|
| 1172 |
+
of derivatives is ascending, so `0`, `1`, `2` are `y(0)`, `y'(0)`,
|
| 1173 |
+
and `y''(0)`, respectively.
|
| 1174 |
+
|
| 1175 |
+
Examples
|
| 1176 |
+
========
|
| 1177 |
+
|
| 1178 |
+
>>> from sympy import laplace_transform, diff, Function
|
| 1179 |
+
>>> from sympy import laplace_correspondence, laplace_initial_conds
|
| 1180 |
+
>>> from sympy.abc import t, s
|
| 1181 |
+
>>> y = Function("y")
|
| 1182 |
+
>>> Y = Function("Y")
|
| 1183 |
+
>>> f = laplace_transform(diff(y(t), t, 3), t, s, noconds=True)
|
| 1184 |
+
>>> g = laplace_correspondence(f, {y: Y})
|
| 1185 |
+
>>> laplace_initial_conds(g, t, {y: [2, 4, 8, 16, 32]})
|
| 1186 |
+
s**3*Y(s) - 2*s**2 - 4*s - 8
|
| 1187 |
+
"""
|
| 1188 |
+
for y, ic in fdict.items():
|
| 1189 |
+
for k in range(len(ic)):
|
| 1190 |
+
if k == 0:
|
| 1191 |
+
f = f.replace(y(0), ic[0])
|
| 1192 |
+
elif k == 1:
|
| 1193 |
+
f = f.replace(Subs(Derivative(y(t), t), t, 0), ic[1])
|
| 1194 |
+
else:
|
| 1195 |
+
f = f.replace(Subs(Derivative(y(t), (t, k)), t, 0), ic[k])
|
| 1196 |
+
return f
|
| 1197 |
+
|
| 1198 |
+
|
| 1199 |
+
@DEBUG_WRAP
|
| 1200 |
+
def _laplace_transform(fn, t_, s_, *, simplify):
|
| 1201 |
+
"""
|
| 1202 |
+
Front-end function of the Laplace transform. It tries to apply all known
|
| 1203 |
+
rules recursively, and if everything else fails, it tries to integrate.
|
| 1204 |
+
"""
|
| 1205 |
+
|
| 1206 |
+
terms_t = Add.make_args(fn)
|
| 1207 |
+
terms_s = []
|
| 1208 |
+
terms = []
|
| 1209 |
+
planes = []
|
| 1210 |
+
conditions = []
|
| 1211 |
+
|
| 1212 |
+
for ff in terms_t:
|
| 1213 |
+
k, ft = ff.as_independent(t_, as_Add=False)
|
| 1214 |
+
if ft.has(SingularityFunction):
|
| 1215 |
+
_terms = Add.make_args(ft.rewrite(Heaviside))
|
| 1216 |
+
for _term in _terms:
|
| 1217 |
+
k1, f1 = _term.as_independent(t_, as_Add=False)
|
| 1218 |
+
terms.append((k*k1, f1))
|
| 1219 |
+
elif ft.func == Piecewise and not ft.has(DiracDelta(t_)):
|
| 1220 |
+
_terms = Add.make_args(_piecewise_to_heaviside(ft, t_))
|
| 1221 |
+
for _term in _terms:
|
| 1222 |
+
k1, f1 = _term.as_independent(t_, as_Add=False)
|
| 1223 |
+
terms.append((k*k1, f1))
|
| 1224 |
+
else:
|
| 1225 |
+
terms.append((k, ft))
|
| 1226 |
+
|
| 1227 |
+
for k, ft in terms:
|
| 1228 |
+
if ft.has(SingularityFunction):
|
| 1229 |
+
r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True)
|
| 1230 |
+
else:
|
| 1231 |
+
if ft.has(Heaviside(t_)) and not ft.has(DiracDelta(t_)):
|
| 1232 |
+
# For t>=0, Heaviside(t)=1 can be used, except if there is also
|
| 1233 |
+
# a DiracDelta(t) present, in which case removing Heaviside(t)
|
| 1234 |
+
# is unnecessary because _laplace_rule_delta can deal with it.
|
| 1235 |
+
ft = ft.subs(Heaviside(t_), 1)
|
| 1236 |
+
if (
|
| 1237 |
+
(r := _laplace_apply_simple_rules(ft, t_, s_))
|
| 1238 |
+
is not None or
|
| 1239 |
+
(r := _laplace_apply_prog_rules(ft, t_, s_))
|
| 1240 |
+
is not None or
|
| 1241 |
+
(r := _laplace_expand(ft, t_, s_)) is not None):
|
| 1242 |
+
pass
|
| 1243 |
+
elif any(undef.has(t_) for undef in ft.atoms(AppliedUndef)):
|
| 1244 |
+
# If there are undefined functions f(t) then integration is
|
| 1245 |
+
# unlikely to do anything useful so we skip it and given an
|
| 1246 |
+
# unevaluated LaplaceTransform.
|
| 1247 |
+
r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True)
|
| 1248 |
+
elif (r := _laplace_transform_integration(
|
| 1249 |
+
ft, t_, s_, simplify=simplify)) is not None:
|
| 1250 |
+
pass
|
| 1251 |
+
else:
|
| 1252 |
+
r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True)
|
| 1253 |
+
(ri_, pi_, ci_) = r
|
| 1254 |
+
terms_s.append(k*ri_)
|
| 1255 |
+
planes.append(pi_)
|
| 1256 |
+
conditions.append(ci_)
|
| 1257 |
+
|
| 1258 |
+
result = Add(*terms_s)
|
| 1259 |
+
if simplify:
|
| 1260 |
+
result = result.simplify(doit=False)
|
| 1261 |
+
plane = Max(*planes)
|
| 1262 |
+
condition = And(*conditions)
|
| 1263 |
+
|
| 1264 |
+
return result, plane, condition
|
| 1265 |
+
|
| 1266 |
+
|
| 1267 |
+
class LaplaceTransform(IntegralTransform):
|
| 1268 |
+
"""
|
| 1269 |
+
Class representing unevaluated Laplace transforms.
|
| 1270 |
+
|
| 1271 |
+
For usage of this class, see the :class:`IntegralTransform` docstring.
|
| 1272 |
+
|
| 1273 |
+
For how to compute Laplace transforms, see the :func:`laplace_transform`
|
| 1274 |
+
docstring.
|
| 1275 |
+
|
| 1276 |
+
If this is called with ``.doit()``, it returns the Laplace transform as an
|
| 1277 |
+
expression. If it is called with ``.doit(noconds=False)``, it returns a
|
| 1278 |
+
tuple containing the same expression, a convergence plane, and conditions.
|
| 1279 |
+
"""
|
| 1280 |
+
|
| 1281 |
+
_name = 'Laplace'
|
| 1282 |
+
|
| 1283 |
+
def _compute_transform(self, f, t, s, **hints):
|
| 1284 |
+
_simplify = hints.get('simplify', False)
|
| 1285 |
+
LT = _laplace_transform_integration(f, t, s, simplify=_simplify)
|
| 1286 |
+
return LT
|
| 1287 |
+
|
| 1288 |
+
def _as_integral(self, f, t, s):
|
| 1289 |
+
return Integral(f*exp(-s*t), (t, S.Zero, S.Infinity))
|
| 1290 |
+
|
| 1291 |
+
def doit(self, **hints):
|
| 1292 |
+
"""
|
| 1293 |
+
Try to evaluate the transform in closed form.
|
| 1294 |
+
|
| 1295 |
+
Explanation
|
| 1296 |
+
===========
|
| 1297 |
+
|
| 1298 |
+
Standard hints are the following:
|
| 1299 |
+
- ``noconds``: if True, do not return convergence conditions. The
|
| 1300 |
+
default setting is `True`.
|
| 1301 |
+
- ``simplify``: if True, it simplifies the final result. The
|
| 1302 |
+
default setting is `False`.
|
| 1303 |
+
"""
|
| 1304 |
+
_noconds = hints.get('noconds', True)
|
| 1305 |
+
_simplify = hints.get('simplify', False)
|
| 1306 |
+
|
| 1307 |
+
debugf('[LT doit] (%s, %s, %s)', (self.function,
|
| 1308 |
+
self.function_variable,
|
| 1309 |
+
self.transform_variable))
|
| 1310 |
+
|
| 1311 |
+
t_ = self.function_variable
|
| 1312 |
+
s_ = self.transform_variable
|
| 1313 |
+
fn = self.function
|
| 1314 |
+
|
| 1315 |
+
r = _laplace_transform(fn, t_, s_, simplify=_simplify)
|
| 1316 |
+
|
| 1317 |
+
if _noconds:
|
| 1318 |
+
return r[0]
|
| 1319 |
+
else:
|
| 1320 |
+
return r
|
| 1321 |
+
|
| 1322 |
+
|
| 1323 |
+
def laplace_transform(f, t, s, legacy_matrix=True, **hints):
|
| 1324 |
+
r"""
|
| 1325 |
+
Compute the Laplace Transform `F(s)` of `f(t)`,
|
| 1326 |
+
|
| 1327 |
+
.. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t.
|
| 1328 |
+
|
| 1329 |
+
Explanation
|
| 1330 |
+
===========
|
| 1331 |
+
|
| 1332 |
+
For all sensible functions, this converges absolutely in a
|
| 1333 |
+
half-plane
|
| 1334 |
+
|
| 1335 |
+
.. math :: a < \operatorname{Re}(s)
|
| 1336 |
+
|
| 1337 |
+
This function returns ``(F, a, cond)`` where ``F`` is the Laplace
|
| 1338 |
+
transform of ``f``, `a` is the half-plane of convergence, and `cond` are
|
| 1339 |
+
auxiliary convergence conditions.
|
| 1340 |
+
|
| 1341 |
+
The implementation is rule-based, and if you are interested in which
|
| 1342 |
+
rules are applied, and whether integration is attempted, you can switch
|
| 1343 |
+
debug information on by setting ``sympy.SYMPY_DEBUG=True``. The numbers
|
| 1344 |
+
of the rules in the debug information (and the code) refer to Bateman's
|
| 1345 |
+
Tables of Integral Transforms [1].
|
| 1346 |
+
|
| 1347 |
+
The lower bound is `0-`, meaning that this bound should be approached
|
| 1348 |
+
from the lower side. This is only necessary if distributions are involved.
|
| 1349 |
+
At present, it is only done if `f(t)` contains ``DiracDelta``, in which
|
| 1350 |
+
case the Laplace transform is computed implicitly as
|
| 1351 |
+
|
| 1352 |
+
.. math ::
|
| 1353 |
+
F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st}
|
| 1354 |
+
f(t) \mathrm{d}t
|
| 1355 |
+
|
| 1356 |
+
by applying rules.
|
| 1357 |
+
|
| 1358 |
+
If the Laplace transform cannot be fully computed in closed form, this
|
| 1359 |
+
function returns expressions containing unevaluated
|
| 1360 |
+
:class:`LaplaceTransform` objects.
|
| 1361 |
+
|
| 1362 |
+
For a description of possible hints, refer to the docstring of
|
| 1363 |
+
:func:`sympy.integrals.transforms.IntegralTransform.doit`. If
|
| 1364 |
+
``noconds=True``, only `F` will be returned (i.e. not ``cond``, and also
|
| 1365 |
+
not the plane ``a``).
|
| 1366 |
+
|
| 1367 |
+
.. deprecated:: 1.9
|
| 1368 |
+
Legacy behavior for matrices where ``laplace_transform`` with
|
| 1369 |
+
``noconds=False`` (the default) returns a Matrix whose elements are
|
| 1370 |
+
tuples. The behavior of ``laplace_transform`` for matrices will change
|
| 1371 |
+
in a future release of SymPy to return a tuple of the transformed
|
| 1372 |
+
Matrix and the convergence conditions for the matrix as a whole. Use
|
| 1373 |
+
``legacy_matrix=False`` to enable the new behavior.
|
| 1374 |
+
|
| 1375 |
+
Examples
|
| 1376 |
+
========
|
| 1377 |
+
|
| 1378 |
+
>>> from sympy import DiracDelta, exp, laplace_transform
|
| 1379 |
+
>>> from sympy.abc import t, s, a
|
| 1380 |
+
>>> laplace_transform(t**4, t, s)
|
| 1381 |
+
(24/s**5, 0, True)
|
| 1382 |
+
>>> laplace_transform(t**a, t, s)
|
| 1383 |
+
(gamma(a + 1)/(s*s**a), 0, re(a) > -1)
|
| 1384 |
+
>>> laplace_transform(DiracDelta(t)-a*exp(-a*t), t, s, simplify=True)
|
| 1385 |
+
(s/(a + s), -re(a), True)
|
| 1386 |
+
|
| 1387 |
+
There are also helper functions that make it easy to solve differential
|
| 1388 |
+
equations by Laplace transform. For example, to solve
|
| 1389 |
+
|
| 1390 |
+
.. math :: m x''(t) + d x'(t) + k x(t) = 0
|
| 1391 |
+
|
| 1392 |
+
with initial value `0` and initial derivative `v`:
|
| 1393 |
+
|
| 1394 |
+
>>> from sympy import Function, laplace_correspondence, diff, solve
|
| 1395 |
+
>>> from sympy import laplace_initial_conds, inverse_laplace_transform
|
| 1396 |
+
>>> from sympy.abc import d, k, m, v
|
| 1397 |
+
>>> x = Function('x')
|
| 1398 |
+
>>> X = Function('X')
|
| 1399 |
+
>>> f = m*diff(x(t), t, 2) + d*diff(x(t), t) + k*x(t)
|
| 1400 |
+
>>> F = laplace_transform(f, t, s, noconds=True)
|
| 1401 |
+
>>> F = laplace_correspondence(F, {x: X})
|
| 1402 |
+
>>> F = laplace_initial_conds(F, t, {x: [0, v]})
|
| 1403 |
+
>>> F
|
| 1404 |
+
d*s*X(s) + k*X(s) + m*(s**2*X(s) - v)
|
| 1405 |
+
>>> Xs = solve(F, X(s))[0]
|
| 1406 |
+
>>> Xs
|
| 1407 |
+
m*v/(d*s + k + m*s**2)
|
| 1408 |
+
>>> inverse_laplace_transform(Xs, s, t)
|
| 1409 |
+
2*v*exp(-d*t/(2*m))*sin(t*sqrt((-d**2 + 4*k*m)/m**2)/2)*Heaviside(t)/sqrt((-d**2 + 4*k*m)/m**2)
|
| 1410 |
+
|
| 1411 |
+
References
|
| 1412 |
+
==========
|
| 1413 |
+
|
| 1414 |
+
.. [1] Erdelyi, A. (ed.), Tables of Integral Transforms, Volume 1,
|
| 1415 |
+
Bateman Manuscript Prooject, McGraw-Hill (1954), available:
|
| 1416 |
+
https://resolver.caltech.edu/CaltechAUTHORS:20140123-101456353
|
| 1417 |
+
|
| 1418 |
+
See Also
|
| 1419 |
+
========
|
| 1420 |
+
|
| 1421 |
+
inverse_laplace_transform, mellin_transform, fourier_transform
|
| 1422 |
+
hankel_transform, inverse_hankel_transform
|
| 1423 |
+
|
| 1424 |
+
"""
|
| 1425 |
+
|
| 1426 |
+
_noconds = hints.get('noconds', False)
|
| 1427 |
+
_simplify = hints.get('simplify', False)
|
| 1428 |
+
|
| 1429 |
+
if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'):
|
| 1430 |
+
|
| 1431 |
+
conds = not hints.get('noconds', False)
|
| 1432 |
+
|
| 1433 |
+
if conds and legacy_matrix:
|
| 1434 |
+
adt = 'deprecated-laplace-transform-matrix'
|
| 1435 |
+
sympy_deprecation_warning(
|
| 1436 |
+
"""
|
| 1437 |
+
Calling laplace_transform() on a Matrix with noconds=False (the default) is
|
| 1438 |
+
deprecated. Either noconds=True or use legacy_matrix=False to get the new
|
| 1439 |
+
behavior.
|
| 1440 |
+
""",
|
| 1441 |
+
deprecated_since_version='1.9',
|
| 1442 |
+
active_deprecations_target=adt,
|
| 1443 |
+
)
|
| 1444 |
+
# Temporarily disable the deprecation warning for non-Expr objects
|
| 1445 |
+
# in Matrix
|
| 1446 |
+
with ignore_warnings(SymPyDeprecationWarning):
|
| 1447 |
+
return f.applyfunc(
|
| 1448 |
+
lambda fij: laplace_transform(fij, t, s, **hints))
|
| 1449 |
+
else:
|
| 1450 |
+
elements_trans = [laplace_transform(
|
| 1451 |
+
fij, t, s, **hints) for fij in f]
|
| 1452 |
+
if conds:
|
| 1453 |
+
elements, avals, conditions = zip(*elements_trans)
|
| 1454 |
+
f_laplace = type(f)(*f.shape, elements)
|
| 1455 |
+
return f_laplace, Max(*avals), And(*conditions)
|
| 1456 |
+
else:
|
| 1457 |
+
return type(f)(*f.shape, elements_trans)
|
| 1458 |
+
|
| 1459 |
+
LT, p, c = LaplaceTransform(f, t, s).doit(noconds=False,
|
| 1460 |
+
simplify=_simplify)
|
| 1461 |
+
|
| 1462 |
+
if not _noconds:
|
| 1463 |
+
return LT, p, c
|
| 1464 |
+
else:
|
| 1465 |
+
return LT
|
| 1466 |
+
|
| 1467 |
+
|
| 1468 |
+
@DEBUG_WRAP
|
| 1469 |
+
def _inverse_laplace_transform_integration(F, s, t_, plane, *, simplify):
|
| 1470 |
+
""" The backend function for inverse Laplace transforms. """
|
| 1471 |
+
from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp
|
| 1472 |
+
from sympy.integrals.transforms import inverse_mellin_transform
|
| 1473 |
+
|
| 1474 |
+
# There are two strategies we can try:
|
| 1475 |
+
# 1) Use inverse mellin transform, related by a simple change of variables.
|
| 1476 |
+
# 2) Use the inversion integral.
|
| 1477 |
+
|
| 1478 |
+
t = Dummy('t', real=True)
|
| 1479 |
+
|
| 1480 |
+
def pw_simp(*args):
|
| 1481 |
+
""" Simplify a piecewise expression from hyperexpand. """
|
| 1482 |
+
if len(args) != 3:
|
| 1483 |
+
return Piecewise(*args)
|
| 1484 |
+
arg = args[2].args[0].argument
|
| 1485 |
+
coeff, exponent = _get_coeff_exp(arg, t)
|
| 1486 |
+
e1 = args[0].args[0]
|
| 1487 |
+
e2 = args[1].args[0]
|
| 1488 |
+
return (
|
| 1489 |
+
Heaviside(1/Abs(coeff) - t**exponent)*e1 +
|
| 1490 |
+
Heaviside(t**exponent - 1/Abs(coeff))*e2)
|
| 1491 |
+
|
| 1492 |
+
if F.is_rational_function(s):
|
| 1493 |
+
F = F.apart(s)
|
| 1494 |
+
|
| 1495 |
+
if F.is_Add:
|
| 1496 |
+
f = Add(
|
| 1497 |
+
*[_inverse_laplace_transform_integration(X, s, t, plane, simplify)
|
| 1498 |
+
for X in F.args])
|
| 1499 |
+
return _simplify(f.subs(t, t_), simplify), True
|
| 1500 |
+
|
| 1501 |
+
try:
|
| 1502 |
+
f, cond = inverse_mellin_transform(F, s, exp(-t), (None, S.Infinity),
|
| 1503 |
+
needeval=True, noconds=False)
|
| 1504 |
+
except IntegralTransformError:
|
| 1505 |
+
f = None
|
| 1506 |
+
|
| 1507 |
+
if f is None:
|
| 1508 |
+
f = meijerint_inversion(F, s, t)
|
| 1509 |
+
if f is None:
|
| 1510 |
+
return None
|
| 1511 |
+
if f.is_Piecewise:
|
| 1512 |
+
f, cond = f.args[0]
|
| 1513 |
+
if f.has(Integral):
|
| 1514 |
+
return None
|
| 1515 |
+
else:
|
| 1516 |
+
cond = S.true
|
| 1517 |
+
f = f.replace(Piecewise, pw_simp)
|
| 1518 |
+
|
| 1519 |
+
if f.is_Piecewise:
|
| 1520 |
+
# many of the functions called below can't work with piecewise
|
| 1521 |
+
# (b/c it has a bool in args)
|
| 1522 |
+
return f.subs(t, t_), cond
|
| 1523 |
+
|
| 1524 |
+
u = Dummy('u')
|
| 1525 |
+
|
| 1526 |
+
def simp_heaviside(arg, H0=S.Half):
|
| 1527 |
+
a = arg.subs(exp(-t), u)
|
| 1528 |
+
if a.has(t):
|
| 1529 |
+
return Heaviside(arg, H0)
|
| 1530 |
+
from sympy.solvers.inequalities import _solve_inequality
|
| 1531 |
+
rel = _solve_inequality(a > 0, u)
|
| 1532 |
+
if rel.lts == u:
|
| 1533 |
+
k = log(rel.gts)
|
| 1534 |
+
return Heaviside(t + k, H0)
|
| 1535 |
+
else:
|
| 1536 |
+
k = log(rel.lts)
|
| 1537 |
+
return Heaviside(-(t + k), H0)
|
| 1538 |
+
|
| 1539 |
+
f = f.replace(Heaviside, simp_heaviside)
|
| 1540 |
+
|
| 1541 |
+
def simp_exp(arg):
|
| 1542 |
+
return expand_complex(exp(arg))
|
| 1543 |
+
|
| 1544 |
+
f = f.replace(exp, simp_exp)
|
| 1545 |
+
|
| 1546 |
+
return _simplify(f.subs(t, t_), simplify), cond
|
| 1547 |
+
|
| 1548 |
+
|
| 1549 |
+
@DEBUG_WRAP
|
| 1550 |
+
def _complete_the_square_in_denom(f, s):
|
| 1551 |
+
from sympy.simplify.radsimp import fraction
|
| 1552 |
+
[n, d] = fraction(f)
|
| 1553 |
+
if d.is_polynomial(s):
|
| 1554 |
+
cf = d.as_poly(s).all_coeffs()
|
| 1555 |
+
if len(cf) == 3:
|
| 1556 |
+
a, b, c = cf
|
| 1557 |
+
d = a*((s+b/(2*a))**2+c/a-(b/(2*a))**2)
|
| 1558 |
+
return n/d
|
| 1559 |
+
|
| 1560 |
+
|
| 1561 |
+
@cacheit
|
| 1562 |
+
def _inverse_laplace_build_rules():
|
| 1563 |
+
"""
|
| 1564 |
+
This is an internal helper function that returns the table of inverse
|
| 1565 |
+
Laplace transform rules in terms of the time variable `t` and the
|
| 1566 |
+
frequency variable `s`. It is used by `_inverse_laplace_apply_rules`.
|
| 1567 |
+
"""
|
| 1568 |
+
s = Dummy('s')
|
| 1569 |
+
t = Dummy('t')
|
| 1570 |
+
a = Wild('a', exclude=[s])
|
| 1571 |
+
b = Wild('b', exclude=[s])
|
| 1572 |
+
c = Wild('c', exclude=[s])
|
| 1573 |
+
|
| 1574 |
+
_debug('_inverse_laplace_build_rules is building rules')
|
| 1575 |
+
|
| 1576 |
+
def _frac(f, s):
|
| 1577 |
+
try:
|
| 1578 |
+
return f.factor(s)
|
| 1579 |
+
except PolynomialError:
|
| 1580 |
+
return f
|
| 1581 |
+
|
| 1582 |
+
def same(f): return f
|
| 1583 |
+
# This list is sorted according to the prep function needed.
|
| 1584 |
+
_ILT_rules = [
|
| 1585 |
+
(a/s, a, S.true, same, 1),
|
| 1586 |
+
(
|
| 1587 |
+
b*(s+a)**(-c), t**(c-1)*exp(-a*t)/gamma(c),
|
| 1588 |
+
S.true, same, 1),
|
| 1589 |
+
(1/(s**2+a**2)**2, (sin(a*t) - a*t*cos(a*t))/(2*a**3),
|
| 1590 |
+
S.true, same, 1),
|
| 1591 |
+
# The next two rules must be there in that order. For the second
|
| 1592 |
+
# one, the condition would be a != 0 or, respectively, to take the
|
| 1593 |
+
# limit a -> 0 after the transform if a == 0. It is much simpler if
|
| 1594 |
+
# the case a == 0 has its own rule.
|
| 1595 |
+
(1/(s**b), t**(b - 1)/gamma(b), S.true, same, 1),
|
| 1596 |
+
(1/(s*(s+a)**b), lowergamma(b, a*t)/(a**b*gamma(b)),
|
| 1597 |
+
S.true, same, 1)
|
| 1598 |
+
]
|
| 1599 |
+
return _ILT_rules, s, t
|
| 1600 |
+
|
| 1601 |
+
|
| 1602 |
+
@DEBUG_WRAP
|
| 1603 |
+
def _inverse_laplace_apply_simple_rules(f, s, t):
|
| 1604 |
+
"""
|
| 1605 |
+
Helper function for the class InverseLaplaceTransform.
|
| 1606 |
+
"""
|
| 1607 |
+
if f == 1:
|
| 1608 |
+
_debug(' rule: 1 o---o DiracDelta()')
|
| 1609 |
+
return DiracDelta(t), S.true
|
| 1610 |
+
|
| 1611 |
+
_ILT_rules, s_, t_ = _inverse_laplace_build_rules()
|
| 1612 |
+
_prep = ''
|
| 1613 |
+
fsubs = f.subs({s: s_})
|
| 1614 |
+
|
| 1615 |
+
for s_dom, t_dom, check, prep, fac in _ILT_rules:
|
| 1616 |
+
if _prep != (prep, fac):
|
| 1617 |
+
_F = prep(fsubs*fac)
|
| 1618 |
+
_prep = (prep, fac)
|
| 1619 |
+
ma = _F.match(s_dom)
|
| 1620 |
+
if ma:
|
| 1621 |
+
c = check
|
| 1622 |
+
if c is not S.true:
|
| 1623 |
+
args = [x.xreplace(ma) for x in c[0]]
|
| 1624 |
+
c = c[1](*args)
|
| 1625 |
+
if c == S.true:
|
| 1626 |
+
return Heaviside(t)*t_dom.xreplace(ma).subs({t_: t}), S.true
|
| 1627 |
+
|
| 1628 |
+
return None
|
| 1629 |
+
|
| 1630 |
+
|
| 1631 |
+
@DEBUG_WRAP
|
| 1632 |
+
def _inverse_laplace_diff(f, s, t, plane):
|
| 1633 |
+
"""
|
| 1634 |
+
Helper function for the class InverseLaplaceTransform.
|
| 1635 |
+
"""
|
| 1636 |
+
a = Wild('a', exclude=[s])
|
| 1637 |
+
n = Wild('n', exclude=[s])
|
| 1638 |
+
g = Wild('g')
|
| 1639 |
+
ma = f.match(a*Derivative(g, (s, n)))
|
| 1640 |
+
if ma and ma[n].is_integer:
|
| 1641 |
+
_debug(' rule: t**n*f(t) o---o (-1)**n*diff(F(s), s, n)')
|
| 1642 |
+
r, c = _inverse_laplace_transform(
|
| 1643 |
+
ma[g], s, t, plane, simplify=False, dorational=False)
|
| 1644 |
+
return (-t)**ma[n]*r, c
|
| 1645 |
+
return None
|
| 1646 |
+
|
| 1647 |
+
|
| 1648 |
+
@DEBUG_WRAP
|
| 1649 |
+
def _inverse_laplace_time_shift(F, s, t, plane):
|
| 1650 |
+
"""
|
| 1651 |
+
Helper function for the class InverseLaplaceTransform.
|
| 1652 |
+
"""
|
| 1653 |
+
a = Wild('a', exclude=[s])
|
| 1654 |
+
g = Wild('g')
|
| 1655 |
+
|
| 1656 |
+
if not F.has(s):
|
| 1657 |
+
return F*DiracDelta(t), S.true
|
| 1658 |
+
if not F.has(exp):
|
| 1659 |
+
return None
|
| 1660 |
+
|
| 1661 |
+
ma1 = F.match(exp(a*s))
|
| 1662 |
+
if ma1:
|
| 1663 |
+
if ma1[a].is_negative:
|
| 1664 |
+
_debug(' rule: exp(-a*s) o---o DiracDelta(t-a)')
|
| 1665 |
+
return DiracDelta(t+ma1[a]), S.true
|
| 1666 |
+
else:
|
| 1667 |
+
return InverseLaplaceTransform(F, s, t, plane), S.true
|
| 1668 |
+
|
| 1669 |
+
ma1 = F.match(exp(a*s)*g)
|
| 1670 |
+
if ma1:
|
| 1671 |
+
if ma1[a].is_negative:
|
| 1672 |
+
_debug(' rule: exp(-a*s)*F(s) o---o Heaviside(t-a)*f(t-a)')
|
| 1673 |
+
return _inverse_laplace_transform(
|
| 1674 |
+
ma1[g], s, t+ma1[a], plane, simplify=False, dorational=True)
|
| 1675 |
+
else:
|
| 1676 |
+
return InverseLaplaceTransform(F, s, t, plane), S.true
|
| 1677 |
+
return None
|
| 1678 |
+
|
| 1679 |
+
|
| 1680 |
+
@DEBUG_WRAP
|
| 1681 |
+
def _inverse_laplace_freq_shift(F, s, t, plane):
|
| 1682 |
+
"""
|
| 1683 |
+
Helper function for the class InverseLaplaceTransform.
|
| 1684 |
+
"""
|
| 1685 |
+
if not F.has(s):
|
| 1686 |
+
return F*DiracDelta(t), S.true
|
| 1687 |
+
if len(args := F.args) == 1:
|
| 1688 |
+
a = Wild('a', exclude=[s])
|
| 1689 |
+
if (ma := args[0].match(s-a)) and re(ma[a]).is_positive:
|
| 1690 |
+
_debug(' rule: F(s-a) o---o exp(-a*t)*f(t)')
|
| 1691 |
+
return (
|
| 1692 |
+
exp(-ma[a]*t) *
|
| 1693 |
+
InverseLaplaceTransform(F.func(s), s, t, plane), S.true)
|
| 1694 |
+
return None
|
| 1695 |
+
|
| 1696 |
+
|
| 1697 |
+
@DEBUG_WRAP
|
| 1698 |
+
def _inverse_laplace_time_diff(F, s, t, plane):
|
| 1699 |
+
"""
|
| 1700 |
+
Helper function for the class InverseLaplaceTransform.
|
| 1701 |
+
"""
|
| 1702 |
+
n = Wild('n', exclude=[s])
|
| 1703 |
+
g = Wild('g')
|
| 1704 |
+
|
| 1705 |
+
ma1 = F.match(s**n*g)
|
| 1706 |
+
if ma1 and ma1[n].is_integer and ma1[n].is_positive:
|
| 1707 |
+
_debug(' rule: s**n*F(s) o---o diff(f(t), t, n)')
|
| 1708 |
+
r, c = _inverse_laplace_transform(
|
| 1709 |
+
ma1[g], s, t, plane, simplify=False, dorational=True)
|
| 1710 |
+
r = r.replace(Heaviside(t), 1)
|
| 1711 |
+
if r.has(InverseLaplaceTransform):
|
| 1712 |
+
return diff(r, t, ma1[n]), c
|
| 1713 |
+
else:
|
| 1714 |
+
return Heaviside(t)*diff(r, t, ma1[n]), c
|
| 1715 |
+
return None
|
| 1716 |
+
|
| 1717 |
+
|
| 1718 |
+
@DEBUG_WRAP
|
| 1719 |
+
def _inverse_laplace_irrational(fn, s, t, plane):
|
| 1720 |
+
"""
|
| 1721 |
+
Helper function for the class InverseLaplaceTransform.
|
| 1722 |
+
"""
|
| 1723 |
+
|
| 1724 |
+
a = Wild('a', exclude=[s])
|
| 1725 |
+
b = Wild('b', exclude=[s])
|
| 1726 |
+
m = Wild('m', exclude=[s])
|
| 1727 |
+
n = Wild('n', exclude=[s])
|
| 1728 |
+
|
| 1729 |
+
result = None
|
| 1730 |
+
condition = S.true
|
| 1731 |
+
|
| 1732 |
+
fa = fn.as_ordered_factors()
|
| 1733 |
+
|
| 1734 |
+
ma = [x.match((a*s**m+b)**n) for x in fa]
|
| 1735 |
+
|
| 1736 |
+
if None in ma:
|
| 1737 |
+
return None
|
| 1738 |
+
|
| 1739 |
+
constants = S.One
|
| 1740 |
+
zeros = []
|
| 1741 |
+
poles = []
|
| 1742 |
+
rest = []
|
| 1743 |
+
|
| 1744 |
+
for term in ma:
|
| 1745 |
+
if term[a] == 0:
|
| 1746 |
+
constants = constants*term
|
| 1747 |
+
elif term[n].is_positive:
|
| 1748 |
+
zeros.append(term)
|
| 1749 |
+
elif term[n].is_negative:
|
| 1750 |
+
poles.append(term)
|
| 1751 |
+
else:
|
| 1752 |
+
rest.append(term)
|
| 1753 |
+
|
| 1754 |
+
# The code below assumes that the poles are sorted in a specific way:
|
| 1755 |
+
poles = sorted(poles, key=lambda x: (x[n], x[b] != 0, x[b]))
|
| 1756 |
+
zeros = sorted(zeros, key=lambda x: (x[n], x[b] != 0, x[b]))
|
| 1757 |
+
|
| 1758 |
+
if len(rest) != 0:
|
| 1759 |
+
return None
|
| 1760 |
+
|
| 1761 |
+
if len(poles) == 1 and len(zeros) == 0:
|
| 1762 |
+
if poles[0][n] == -1 and poles[0][m] == S.Half:
|
| 1763 |
+
# 1/(a0*sqrt(s)+b0) == 1/a0 * 1/(sqrt(s)+b0/a0)
|
| 1764 |
+
a_ = poles[0][b]/poles[0][a]
|
| 1765 |
+
k_ = 1/poles[0][a]*constants
|
| 1766 |
+
if a_.is_positive:
|
| 1767 |
+
result = (
|
| 1768 |
+
k_/sqrt(pi)/sqrt(t) -
|
| 1769 |
+
k_*a_*exp(a_**2*t)*erfc(a_*sqrt(t)))
|
| 1770 |
+
_debug(' rule 5.3.4')
|
| 1771 |
+
elif poles[0][n] == -2 and poles[0][m] == S.Half:
|
| 1772 |
+
# 1/(a0*sqrt(s)+b0)**2 == 1/a0**2 * 1/(sqrt(s)+b0/a0)**2
|
| 1773 |
+
a_sq = poles[0][b]/poles[0][a]
|
| 1774 |
+
a_ = a_sq**2
|
| 1775 |
+
k_ = 1/poles[0][a]**2*constants
|
| 1776 |
+
if a_sq.is_positive:
|
| 1777 |
+
result = (
|
| 1778 |
+
k_*(1 - 2/sqrt(pi)*sqrt(a_)*sqrt(t) +
|
| 1779 |
+
(1-2*a_*t)*exp(a_*t)*(erf(sqrt(a_)*sqrt(t))-1)))
|
| 1780 |
+
_debug(' rule 5.3.10')
|
| 1781 |
+
elif poles[0][n] == -3 and poles[0][m] == S.Half:
|
| 1782 |
+
# 1/(a0*sqrt(s)+b0)**3 == 1/a0**3 * 1/(sqrt(s)+b0/a0)**3
|
| 1783 |
+
a_ = poles[0][b]/poles[0][a]
|
| 1784 |
+
k_ = 1/poles[0][a]**3*constants
|
| 1785 |
+
if a_.is_positive:
|
| 1786 |
+
result = (
|
| 1787 |
+
k_*(2/sqrt(pi)*(a_**2*t+1)*sqrt(t) -
|
| 1788 |
+
a_*t*exp(a_**2*t)*(2*a_**2*t+3)*erfc(a_*sqrt(t))))
|
| 1789 |
+
_debug(' rule 5.3.13')
|
| 1790 |
+
elif poles[0][n] == -4 and poles[0][m] == S.Half:
|
| 1791 |
+
# 1/(a0*sqrt(s)+b0)**4 == 1/a0**4 * 1/(sqrt(s)+b0/a0)**4
|
| 1792 |
+
a_ = poles[0][b]/poles[0][a]
|
| 1793 |
+
k_ = 1/poles[0][a]**4*constants/3
|
| 1794 |
+
if a_.is_positive:
|
| 1795 |
+
result = (
|
| 1796 |
+
k_*(t*(4*a_**4*t**2+12*a_**2*t+3)*exp(a_**2*t) *
|
| 1797 |
+
erfc(a_*sqrt(t)) -
|
| 1798 |
+
2/sqrt(pi)*a_**3*t**(S(5)/2)*(2*a_**2*t+5)))
|
| 1799 |
+
_debug(' rule 5.3.16')
|
| 1800 |
+
elif poles[0][n] == -S.Half and poles[0][m] == 2:
|
| 1801 |
+
# 1/sqrt(a0*s**2+b0) == 1/sqrt(a0) * 1/sqrt(s**2+b0/a0)
|
| 1802 |
+
a_ = sqrt(poles[0][b]/poles[0][a])
|
| 1803 |
+
k_ = 1/sqrt(poles[0][a])*constants
|
| 1804 |
+
result = (k_*(besselj(0, a_*t)))
|
| 1805 |
+
_debug(' rule 5.3.35/44')
|
| 1806 |
+
|
| 1807 |
+
elif len(poles) == 1 and len(zeros) == 1:
|
| 1808 |
+
if (
|
| 1809 |
+
poles[0][n] == -3 and poles[0][m] == S.Half and
|
| 1810 |
+
zeros[0][n] == S.Half and zeros[0][b] == 0):
|
| 1811 |
+
# sqrt(az*s)/(ap*sqrt(s+bp)**3)
|
| 1812 |
+
# == sqrt(az)/ap * sqrt(s)/(sqrt(s+bp)**3)
|
| 1813 |
+
a_ = poles[0][b]
|
| 1814 |
+
k_ = sqrt(zeros[0][a])/poles[0][a]*constants
|
| 1815 |
+
result = (
|
| 1816 |
+
k_*(2*a_**4*t**2+5*a_**2*t+1)*exp(a_**2*t) *
|
| 1817 |
+
erfc(a_*sqrt(t)) - 2/sqrt(pi)*a_*(a_**2*t+2)*sqrt(t))
|
| 1818 |
+
_debug(' rule 5.3.14')
|
| 1819 |
+
if (
|
| 1820 |
+
poles[0][n] == -1 and poles[0][m] == 1 and
|
| 1821 |
+
zeros[0][n] == S.Half and zeros[0][m] == 1):
|
| 1822 |
+
# sqrt(az*s+bz)/(ap*s+bp)
|
| 1823 |
+
# == sqrt(az)/ap * (sqrt(s+bz/az)/(s+bp/ap))
|
| 1824 |
+
a_ = zeros[0][b]/zeros[0][a]
|
| 1825 |
+
b_ = poles[0][b]/poles[0][a]
|
| 1826 |
+
k_ = sqrt(zeros[0][a])/poles[0][a]*constants
|
| 1827 |
+
result = (
|
| 1828 |
+
k_*(exp(-a_*t)/sqrt(t)/sqrt(pi)+sqrt(a_-b_) *
|
| 1829 |
+
exp(-b_*t)*erf(sqrt(a_-b_)*sqrt(t))))
|
| 1830 |
+
_debug(' rule 5.3.22')
|
| 1831 |
+
|
| 1832 |
+
elif len(poles) == 2 and len(zeros) == 0:
|
| 1833 |
+
if (
|
| 1834 |
+
poles[0][n] == -1 and poles[0][m] == 1 and
|
| 1835 |
+
poles[1][n] == -S.Half and poles[1][m] == 1 and
|
| 1836 |
+
poles[1][b] == 0):
|
| 1837 |
+
# 1/((a0*s+b0)*sqrt(a1*s))
|
| 1838 |
+
# == 1/(a0*sqrt(a1)) * 1/((s+b0/a0)*sqrt(s))
|
| 1839 |
+
a_ = -poles[0][b]/poles[0][a]
|
| 1840 |
+
k_ = 1/sqrt(poles[1][a])/poles[0][a]*constants
|
| 1841 |
+
if a_.is_positive:
|
| 1842 |
+
result = (k_/sqrt(a_)*exp(a_*t)*erf(sqrt(a_)*sqrt(t)))
|
| 1843 |
+
_debug(' rule 5.3.1')
|
| 1844 |
+
elif (
|
| 1845 |
+
poles[0][n] == -1 and poles[0][m] == 1 and poles[0][b] == 0 and
|
| 1846 |
+
poles[1][n] == -1 and poles[1][m] == S.Half):
|
| 1847 |
+
# 1/(a0*s*(a1*sqrt(s)+b1))
|
| 1848 |
+
# == 1/(a0*a1) * 1/(s*(sqrt(s)+b1/a1))
|
| 1849 |
+
a_ = poles[1][b]/poles[1][a]
|
| 1850 |
+
k_ = 1/poles[0][a]/poles[1][a]/a_*constants
|
| 1851 |
+
if a_.is_positive:
|
| 1852 |
+
result = k_*(1-exp(a_**2*t)*erfc(a_*sqrt(t)))
|
| 1853 |
+
_debug(' rule 5.3.5')
|
| 1854 |
+
elif (
|
| 1855 |
+
poles[0][n] == -1 and poles[0][m] == S.Half and
|
| 1856 |
+
poles[1][n] == -S.Half and poles[1][m] == 1 and
|
| 1857 |
+
poles[1][b] == 0):
|
| 1858 |
+
# 1/((a0*sqrt(s)+b0)*(sqrt(a1*s))
|
| 1859 |
+
# == 1/(a0*sqrt(a1)) * 1/((sqrt(s)+b0/a0)"sqrt(s))
|
| 1860 |
+
a_ = poles[0][b]/poles[0][a]
|
| 1861 |
+
k_ = 1/(poles[0][a]*sqrt(poles[1][a]))*constants
|
| 1862 |
+
if a_.is_positive:
|
| 1863 |
+
result = k_*exp(a_**2*t)*erfc(a_*sqrt(t))
|
| 1864 |
+
_debug(' rule 5.3.7')
|
| 1865 |
+
elif (
|
| 1866 |
+
poles[0][n] == -S(3)/2 and poles[0][m] == 1 and
|
| 1867 |
+
poles[0][b] == 0 and poles[1][n] == -1 and
|
| 1868 |
+
poles[1][m] == S.Half):
|
| 1869 |
+
# 1/((a0**(3/2)*s**(3/2))*(a1*sqrt(s)+b1))
|
| 1870 |
+
# == 1/(a0**(3/2)*a1) 1/((s**(3/2))*(sqrt(s)+b1/a1))
|
| 1871 |
+
# Note that Bateman54 5.3 (8) is incorrect; there (sqrt(p)+a)
|
| 1872 |
+
# should be (sqrt(p)+a)**(-1).
|
| 1873 |
+
a_ = poles[1][b]/poles[1][a]
|
| 1874 |
+
k_ = 1/(poles[0][a]**(S(3)/2)*poles[1][a])/a_**2*constants
|
| 1875 |
+
if a_.is_positive:
|
| 1876 |
+
result = (
|
| 1877 |
+
k_*(2/sqrt(pi)*a_*sqrt(t)+exp(a_**2*t)*erfc(a_*sqrt(t))-1))
|
| 1878 |
+
_debug(' rule 5.3.8')
|
| 1879 |
+
elif (
|
| 1880 |
+
poles[0][n] == -2 and poles[0][m] == S.Half and
|
| 1881 |
+
poles[1][n] == -1 and poles[1][m] == 1 and
|
| 1882 |
+
poles[1][b] == 0):
|
| 1883 |
+
# 1/((a0*sqrt(s)+b0)**2*a1*s)
|
| 1884 |
+
# == 1/a0**2/a1 * 1/(sqrt(s)+b0/a0)**2/s
|
| 1885 |
+
a_sq = poles[0][b]/poles[0][a]
|
| 1886 |
+
a_ = a_sq**2
|
| 1887 |
+
k_ = 1/poles[0][a]**2/poles[1][a]*constants
|
| 1888 |
+
if a_sq.is_positive:
|
| 1889 |
+
result = (
|
| 1890 |
+
k_*(1/a_ + (2*t-1/a_)*exp(a_*t)*erfc(sqrt(a_)*sqrt(t)) -
|
| 1891 |
+
2/sqrt(pi)/sqrt(a_)*sqrt(t)))
|
| 1892 |
+
_debug(' rule 5.3.11')
|
| 1893 |
+
elif (
|
| 1894 |
+
poles[0][n] == -2 and poles[0][m] == S.Half and
|
| 1895 |
+
poles[1][n] == -S.Half and poles[1][m] == 1 and
|
| 1896 |
+
poles[1][b] == 0):
|
| 1897 |
+
# 1/((a0*sqrt(s)+b0)**2*sqrt(a1*s))
|
| 1898 |
+
# == 1/a0**2/sqrt(a1) * 1/(sqrt(s)+b0/a0)**2/sqrt(s)
|
| 1899 |
+
a_ = poles[0][b]/poles[0][a]
|
| 1900 |
+
k_ = 1/poles[0][a]**2/sqrt(poles[1][a])*constants
|
| 1901 |
+
if a_.is_positive:
|
| 1902 |
+
result = (
|
| 1903 |
+
k_*(2/sqrt(pi)*sqrt(t) -
|
| 1904 |
+
2*a_*t*exp(a_**2*t)*erfc(a_*sqrt(t))))
|
| 1905 |
+
_debug(' rule 5.3.12')
|
| 1906 |
+
elif (
|
| 1907 |
+
poles[0][n] == -3 and poles[0][m] == S.Half and
|
| 1908 |
+
poles[1][n] == -S.Half and poles[1][m] == 1 and
|
| 1909 |
+
poles[1][b] == 0):
|
| 1910 |
+
# 1 / (sqrt(a1*s)*(a0*sqrt(s+b0)**3))
|
| 1911 |
+
# == 1/(sqrt(a1)*a0) * 1/(sqrt(s)*(sqrt(s+b0)**3))
|
| 1912 |
+
a_ = poles[0][b]
|
| 1913 |
+
k_ = constants/sqrt(poles[1][a])/poles[0][a]
|
| 1914 |
+
result = k_*(
|
| 1915 |
+
(2*a_**2*t+1)*t*exp(a_**2*t)*erfc(a_*sqrt(t)) -
|
| 1916 |
+
2/sqrt(pi)*a_*t**(S(3)/2))
|
| 1917 |
+
_debug(' rule 5.3.15')
|
| 1918 |
+
elif (
|
| 1919 |
+
poles[0][n] == -1 and poles[0][m] == 1 and
|
| 1920 |
+
poles[1][n] == -S.Half and poles[1][m] == 1):
|
| 1921 |
+
# 1 / ( (a0*s+b0)* sqrt(a1*s+b1) )
|
| 1922 |
+
# == 1/(sqrt(a1)*a0) * 1 / ( (s+b0/a0)* sqrt(s+b1/a1) )
|
| 1923 |
+
a_ = poles[0][b]/poles[0][a]
|
| 1924 |
+
b_ = poles[1][b]/poles[1][a]
|
| 1925 |
+
k_ = constants/sqrt(poles[1][a])/poles[0][a]
|
| 1926 |
+
result = k_*(
|
| 1927 |
+
1/sqrt(b_-a_)*exp(-a_*t)*erf(sqrt(b_-a_)*sqrt(t)))
|
| 1928 |
+
_debug(' rule 5.3.23')
|
| 1929 |
+
|
| 1930 |
+
elif len(poles) == 2 and len(zeros) == 1:
|
| 1931 |
+
if (
|
| 1932 |
+
poles[0][n] == -1 and poles[0][m] == 1 and
|
| 1933 |
+
poles[1][n] == -1 and poles[1][m] == S.Half and
|
| 1934 |
+
zeros[0][n] == S.Half and zeros[0][m] == 1 and
|
| 1935 |
+
zeros[0][b] == 0):
|
| 1936 |
+
# sqrt(za0*s)/((a0*s+b0)*(a1*sqrt(s)+b1))
|
| 1937 |
+
# == sqrt(za0)/(a0*a1) * s/((s+b0/a0)*(sqrt(s)+b1/a1))
|
| 1938 |
+
a_sq = poles[1][b]/poles[1][a]
|
| 1939 |
+
a_ = a_sq**2
|
| 1940 |
+
b_ = -poles[0][b]/poles[0][a]
|
| 1941 |
+
k_ = sqrt(zeros[0][a])/poles[0][a]/poles[1][a]/(a_-b_)*constants
|
| 1942 |
+
if a_sq.is_positive and b_.is_positive:
|
| 1943 |
+
result = k_*(
|
| 1944 |
+
a_*exp(a_*t)*erfc(sqrt(a_)*sqrt(t)) +
|
| 1945 |
+
sqrt(a_)*sqrt(b_)*exp(b_*t)*erfc(sqrt(b_)*sqrt(t)) -
|
| 1946 |
+
b_*exp(b_*t))
|
| 1947 |
+
_debug(' rule 5.3.6')
|
| 1948 |
+
elif (
|
| 1949 |
+
poles[0][n] == -1 and poles[0][m] == 1 and
|
| 1950 |
+
poles[0][b] == 0 and poles[1][n] == -1 and
|
| 1951 |
+
poles[1][m] == S.Half and zeros[0][n] == 1 and
|
| 1952 |
+
zeros[0][m] == S.Half):
|
| 1953 |
+
# (az*sqrt(s)+bz)/(a0*s*(a1*sqrt(s)+b1))
|
| 1954 |
+
# == az/a0/a1 * (sqrt(z)+bz/az)/(s*(sqrt(s)+b1/a1))
|
| 1955 |
+
a_num = zeros[0][b]/zeros[0][a]
|
| 1956 |
+
a_ = poles[1][b]/poles[1][a]
|
| 1957 |
+
if a_+a_num == 0:
|
| 1958 |
+
k_ = zeros[0][a]/poles[0][a]/poles[1][a]*constants
|
| 1959 |
+
result = k_*(
|
| 1960 |
+
2*exp(a_**2*t)*erfc(a_*sqrt(t))-1)
|
| 1961 |
+
_debug(' rule 5.3.17')
|
| 1962 |
+
elif (
|
| 1963 |
+
poles[1][n] == -1 and poles[1][m] == 1 and
|
| 1964 |
+
poles[1][b] == 0 and poles[0][n] == -2 and
|
| 1965 |
+
poles[0][m] == S.Half and zeros[0][n] == 2 and
|
| 1966 |
+
zeros[0][m] == S.Half):
|
| 1967 |
+
# (az*sqrt(s)+bz)**2/(a1*s*(a0*sqrt(s)+b0)**2)
|
| 1968 |
+
# == az**2/a1/a0**2 * (sqrt(z)+bz/az)**2/(s*(sqrt(s)+b0/a0)**2)
|
| 1969 |
+
a_num = zeros[0][b]/zeros[0][a]
|
| 1970 |
+
a_ = poles[0][b]/poles[0][a]
|
| 1971 |
+
if a_+a_num == 0:
|
| 1972 |
+
k_ = zeros[0][a]**2/poles[1][a]/poles[0][a]**2*constants
|
| 1973 |
+
result = k_*(
|
| 1974 |
+
1 + 8*a_**2*t*exp(a_**2*t)*erfc(a_*sqrt(t)) -
|
| 1975 |
+
8/sqrt(pi)*a_*sqrt(t))
|
| 1976 |
+
_debug(' rule 5.3.18')
|
| 1977 |
+
elif (
|
| 1978 |
+
poles[1][n] == -1 and poles[1][m] == 1 and
|
| 1979 |
+
poles[1][b] == 0 and poles[0][n] == -3 and
|
| 1980 |
+
poles[0][m] == S.Half and zeros[0][n] == 3 and
|
| 1981 |
+
zeros[0][m] == S.Half):
|
| 1982 |
+
# (az*sqrt(s)+bz)**3/(a1*s*(a0*sqrt(s)+b0)**3)
|
| 1983 |
+
# == az**3/a1/a0**3 * (sqrt(z)+bz/az)**3/(s*(sqrt(s)+b0/a0)**3)
|
| 1984 |
+
a_num = zeros[0][b]/zeros[0][a]
|
| 1985 |
+
a_ = poles[0][b]/poles[0][a]
|
| 1986 |
+
if a_+a_num == 0:
|
| 1987 |
+
k_ = zeros[0][a]**3/poles[1][a]/poles[0][a]**3*constants
|
| 1988 |
+
result = k_*(
|
| 1989 |
+
2*(8*a_**4*t**2+8*a_**2*t+1)*exp(a_**2*t) *
|
| 1990 |
+
erfc(a_*sqrt(t))-8/sqrt(pi)*a_*sqrt(t)*(2*a_**2*t+1)-1)
|
| 1991 |
+
_debug(' rule 5.3.19')
|
| 1992 |
+
|
| 1993 |
+
elif len(poles) == 3 and len(zeros) == 0:
|
| 1994 |
+
if (
|
| 1995 |
+
poles[0][n] == -1 and poles[0][b] == 0 and poles[0][m] == 1 and
|
| 1996 |
+
poles[1][n] == -1 and poles[1][m] == 1 and
|
| 1997 |
+
poles[2][n] == -S.Half and poles[2][m] == 1):
|
| 1998 |
+
# 1/((a0*s)*(a1*s+b1)*sqrt(a2*s))
|
| 1999 |
+
# == 1/(a0*a1*sqrt(a2)) * 1/((s)*(s+b1/a1)*sqrt(s))
|
| 2000 |
+
a_ = -poles[1][b]/poles[1][a]
|
| 2001 |
+
k_ = 1/poles[0][a]/poles[1][a]/sqrt(poles[2][a])*constants
|
| 2002 |
+
if a_.is_positive:
|
| 2003 |
+
result = k_ * (
|
| 2004 |
+
a_**(-S(3)/2) * exp(a_*t) * erf(sqrt(a_)*sqrt(t)) -
|
| 2005 |
+
2/a_/sqrt(pi)*sqrt(t))
|
| 2006 |
+
_debug(' rule 5.3.2')
|
| 2007 |
+
elif (
|
| 2008 |
+
poles[0][n] == -1 and poles[0][m] == 1 and
|
| 2009 |
+
poles[1][n] == -1 and poles[1][m] == S.Half and
|
| 2010 |
+
poles[2][n] == -S.Half and poles[2][m] == 1 and
|
| 2011 |
+
poles[2][b] == 0):
|
| 2012 |
+
# 1/((a0*s+b0)*(a1*sqrt(s)+b1)*(sqrt(a2)*sqrt(s)))
|
| 2013 |
+
# == 1/(a0*a1*sqrt(a2)) * 1/((s+b0/a0)*(sqrt(s)+b1/a1)*sqrt(s))
|
| 2014 |
+
a_sq = poles[1][b]/poles[1][a]
|
| 2015 |
+
a_ = a_sq**2
|
| 2016 |
+
b_ = -poles[0][b]/poles[0][a]
|
| 2017 |
+
k_ = (
|
| 2018 |
+
1/poles[0][a]/poles[1][a]/sqrt(poles[2][a]) /
|
| 2019 |
+
(sqrt(b_)*(a_-b_)))
|
| 2020 |
+
if a_sq.is_positive and b_.is_positive:
|
| 2021 |
+
result = k_ * (
|
| 2022 |
+
sqrt(b_)*exp(a_*t)*erfc(sqrt(a_)*sqrt(t)) +
|
| 2023 |
+
sqrt(a_)*exp(b_*t)*erf(sqrt(b_)*sqrt(t)) -
|
| 2024 |
+
sqrt(b_)*exp(b_*t))
|
| 2025 |
+
_debug(' rule 5.3.9')
|
| 2026 |
+
|
| 2027 |
+
if result is None:
|
| 2028 |
+
return None
|
| 2029 |
+
else:
|
| 2030 |
+
return Heaviside(t)*result, condition
|
| 2031 |
+
|
| 2032 |
+
|
| 2033 |
+
@DEBUG_WRAP
|
| 2034 |
+
def _inverse_laplace_early_prog_rules(F, s, t, plane):
|
| 2035 |
+
"""
|
| 2036 |
+
Helper function for the class InverseLaplaceTransform.
|
| 2037 |
+
"""
|
| 2038 |
+
prog_rules = [_inverse_laplace_irrational]
|
| 2039 |
+
|
| 2040 |
+
for p_rule in prog_rules:
|
| 2041 |
+
if (r := p_rule(F, s, t, plane)) is not None:
|
| 2042 |
+
return r
|
| 2043 |
+
return None
|
| 2044 |
+
|
| 2045 |
+
|
| 2046 |
+
@DEBUG_WRAP
|
| 2047 |
+
def _inverse_laplace_apply_prog_rules(F, s, t, plane):
|
| 2048 |
+
"""
|
| 2049 |
+
Helper function for the class InverseLaplaceTransform.
|
| 2050 |
+
"""
|
| 2051 |
+
prog_rules = [_inverse_laplace_time_shift, _inverse_laplace_freq_shift,
|
| 2052 |
+
_inverse_laplace_time_diff, _inverse_laplace_diff,
|
| 2053 |
+
_inverse_laplace_irrational]
|
| 2054 |
+
|
| 2055 |
+
for p_rule in prog_rules:
|
| 2056 |
+
if (r := p_rule(F, s, t, plane)) is not None:
|
| 2057 |
+
return r
|
| 2058 |
+
return None
|
| 2059 |
+
|
| 2060 |
+
|
| 2061 |
+
@DEBUG_WRAP
|
| 2062 |
+
def _inverse_laplace_expand(fn, s, t, plane):
|
| 2063 |
+
"""
|
| 2064 |
+
Helper function for the class InverseLaplaceTransform.
|
| 2065 |
+
"""
|
| 2066 |
+
if fn.is_Add:
|
| 2067 |
+
return None
|
| 2068 |
+
r = expand(fn, deep=False)
|
| 2069 |
+
if r.is_Add:
|
| 2070 |
+
return _inverse_laplace_transform(
|
| 2071 |
+
r, s, t, plane, simplify=False, dorational=True)
|
| 2072 |
+
r = expand_mul(fn)
|
| 2073 |
+
if r.is_Add:
|
| 2074 |
+
return _inverse_laplace_transform(
|
| 2075 |
+
r, s, t, plane, simplify=False, dorational=True)
|
| 2076 |
+
r = expand(fn)
|
| 2077 |
+
if r.is_Add:
|
| 2078 |
+
return _inverse_laplace_transform(
|
| 2079 |
+
r, s, t, plane, simplify=False, dorational=True)
|
| 2080 |
+
if fn.is_rational_function(s):
|
| 2081 |
+
r = fn.apart(s).doit()
|
| 2082 |
+
if r.is_Add:
|
| 2083 |
+
return _inverse_laplace_transform(
|
| 2084 |
+
r, s, t, plane, simplify=False, dorational=True)
|
| 2085 |
+
return None
|
| 2086 |
+
|
| 2087 |
+
|
| 2088 |
+
@DEBUG_WRAP
|
| 2089 |
+
def _inverse_laplace_rational(fn, s, t, plane, *, simplify):
|
| 2090 |
+
"""
|
| 2091 |
+
Helper function for the class InverseLaplaceTransform.
|
| 2092 |
+
"""
|
| 2093 |
+
x_ = symbols('x_')
|
| 2094 |
+
f = fn.apart(s)
|
| 2095 |
+
terms = Add.make_args(f)
|
| 2096 |
+
terms_t = []
|
| 2097 |
+
conditions = [S.true]
|
| 2098 |
+
for term in terms:
|
| 2099 |
+
[n, d] = term.as_numer_denom()
|
| 2100 |
+
dc = d.as_poly(s).all_coeffs()
|
| 2101 |
+
dc_lead = dc[0]
|
| 2102 |
+
dc = [x/dc_lead for x in dc]
|
| 2103 |
+
nc = [x/dc_lead for x in n.as_poly(s).all_coeffs()]
|
| 2104 |
+
if len(dc) == 1:
|
| 2105 |
+
N = len(nc)-1
|
| 2106 |
+
for c in enumerate(nc):
|
| 2107 |
+
r = c[1]*DiracDelta(t, N-c[0])
|
| 2108 |
+
terms_t.append(r)
|
| 2109 |
+
elif len(dc) == 2:
|
| 2110 |
+
r = nc[0]*exp(-dc[1]*t)
|
| 2111 |
+
terms_t.append(Heaviside(t)*r)
|
| 2112 |
+
elif len(dc) == 3:
|
| 2113 |
+
a = dc[1]/2
|
| 2114 |
+
b = (dc[2]-a**2).factor()
|
| 2115 |
+
if len(nc) == 1:
|
| 2116 |
+
nc = [S.Zero] + nc
|
| 2117 |
+
l, m = tuple(nc)
|
| 2118 |
+
if b == 0:
|
| 2119 |
+
r = (m*t+l*(1-a*t))*exp(-a*t)
|
| 2120 |
+
else:
|
| 2121 |
+
hyp = False
|
| 2122 |
+
if b.is_negative:
|
| 2123 |
+
b = -b
|
| 2124 |
+
hyp = True
|
| 2125 |
+
b2 = list(roots(x_**2-b, x_).keys())[0]
|
| 2126 |
+
bs = sqrt(b).simplify()
|
| 2127 |
+
if hyp:
|
| 2128 |
+
r = (
|
| 2129 |
+
l*exp(-a*t)*cosh(b2*t) + (m-a*l) /
|
| 2130 |
+
bs*exp(-a*t)*sinh(bs*t))
|
| 2131 |
+
else:
|
| 2132 |
+
r = l*exp(-a*t)*cos(b2*t) + (m-a*l)/bs*exp(-a*t)*sin(bs*t)
|
| 2133 |
+
terms_t.append(Heaviside(t)*r)
|
| 2134 |
+
else:
|
| 2135 |
+
ft, cond = _inverse_laplace_transform(
|
| 2136 |
+
term, s, t, plane, simplify=simplify, dorational=False)
|
| 2137 |
+
terms_t.append(ft)
|
| 2138 |
+
conditions.append(cond)
|
| 2139 |
+
|
| 2140 |
+
result = Add(*terms_t)
|
| 2141 |
+
if simplify:
|
| 2142 |
+
result = result.simplify(doit=False)
|
| 2143 |
+
return result, And(*conditions)
|
| 2144 |
+
|
| 2145 |
+
|
| 2146 |
+
@DEBUG_WRAP
|
| 2147 |
+
def _inverse_laplace_transform(fn, s_, t_, plane, *, simplify, dorational):
|
| 2148 |
+
"""
|
| 2149 |
+
Front-end function of the inverse Laplace transform. It tries to apply all
|
| 2150 |
+
known rules recursively. If everything else fails, it tries to integrate.
|
| 2151 |
+
"""
|
| 2152 |
+
terms = Add.make_args(fn)
|
| 2153 |
+
terms_t = []
|
| 2154 |
+
conditions = []
|
| 2155 |
+
|
| 2156 |
+
for term in terms:
|
| 2157 |
+
if term.has(exp):
|
| 2158 |
+
# Simplify expressions with exp() such that time-shifted
|
| 2159 |
+
# expressions have negative exponents in the numerator instead of
|
| 2160 |
+
# positive exponents in the numerator and denominator; this is a
|
| 2161 |
+
# (necessary) trick. It will, for example, convert
|
| 2162 |
+
# (s**2*exp(2*s) + 4*exp(s) - 4)*exp(-2*s)/(s*(s**2 + 1)) into
|
| 2163 |
+
# (s**2 + 4*exp(-s) - 4*exp(-2*s))/(s*(s**2 + 1))
|
| 2164 |
+
term = term.subs(s_, -s_).together().subs(s_, -s_)
|
| 2165 |
+
k, f = term.as_independent(s_, as_Add=False)
|
| 2166 |
+
if (
|
| 2167 |
+
dorational and term.is_rational_function(s_) and
|
| 2168 |
+
(r := _inverse_laplace_rational(
|
| 2169 |
+
f, s_, t_, plane, simplify=simplify))
|
| 2170 |
+
is not None or
|
| 2171 |
+
(r := _inverse_laplace_apply_simple_rules(f, s_, t_))
|
| 2172 |
+
is not None or
|
| 2173 |
+
(r := _inverse_laplace_early_prog_rules(f, s_, t_, plane))
|
| 2174 |
+
is not None or
|
| 2175 |
+
(r := _inverse_laplace_expand(f, s_, t_, plane))
|
| 2176 |
+
is not None or
|
| 2177 |
+
(r := _inverse_laplace_apply_prog_rules(f, s_, t_, plane))
|
| 2178 |
+
is not None):
|
| 2179 |
+
pass
|
| 2180 |
+
elif any(undef.has(s_) for undef in f.atoms(AppliedUndef)):
|
| 2181 |
+
# If there are undefined functions f(t) then integration is
|
| 2182 |
+
# unlikely to do anything useful so we skip it and given an
|
| 2183 |
+
# unevaluated LaplaceTransform.
|
| 2184 |
+
r = (InverseLaplaceTransform(f, s_, t_, plane), S.true)
|
| 2185 |
+
elif (
|
| 2186 |
+
r := _inverse_laplace_transform_integration(
|
| 2187 |
+
f, s_, t_, plane, simplify=simplify)) is not None:
|
| 2188 |
+
pass
|
| 2189 |
+
else:
|
| 2190 |
+
r = (InverseLaplaceTransform(f, s_, t_, plane), S.true)
|
| 2191 |
+
(ri_, ci_) = r
|
| 2192 |
+
terms_t.append(k*ri_)
|
| 2193 |
+
conditions.append(ci_)
|
| 2194 |
+
|
| 2195 |
+
result = Add(*terms_t)
|
| 2196 |
+
if simplify:
|
| 2197 |
+
result = result.simplify(doit=False)
|
| 2198 |
+
condition = And(*conditions)
|
| 2199 |
+
|
| 2200 |
+
return result, condition
|
| 2201 |
+
|
| 2202 |
+
|
| 2203 |
+
class InverseLaplaceTransform(IntegralTransform):
|
| 2204 |
+
"""
|
| 2205 |
+
Class representing unevaluated inverse Laplace transforms.
|
| 2206 |
+
|
| 2207 |
+
For usage of this class, see the :class:`IntegralTransform` docstring.
|
| 2208 |
+
|
| 2209 |
+
For how to compute inverse Laplace transforms, see the
|
| 2210 |
+
:func:`inverse_laplace_transform` docstring.
|
| 2211 |
+
"""
|
| 2212 |
+
|
| 2213 |
+
_name = 'Inverse Laplace'
|
| 2214 |
+
_none_sentinel = Dummy('None')
|
| 2215 |
+
_c = Dummy('c')
|
| 2216 |
+
|
| 2217 |
+
def __new__(cls, F, s, x, plane, **opts):
|
| 2218 |
+
if plane is None:
|
| 2219 |
+
plane = InverseLaplaceTransform._none_sentinel
|
| 2220 |
+
return IntegralTransform.__new__(cls, F, s, x, plane, **opts)
|
| 2221 |
+
|
| 2222 |
+
@property
|
| 2223 |
+
def fundamental_plane(self):
|
| 2224 |
+
plane = self.args[3]
|
| 2225 |
+
if plane is InverseLaplaceTransform._none_sentinel:
|
| 2226 |
+
plane = None
|
| 2227 |
+
return plane
|
| 2228 |
+
|
| 2229 |
+
def _compute_transform(self, F, s, t, **hints):
|
| 2230 |
+
return _inverse_laplace_transform_integration(
|
| 2231 |
+
F, s, t, self.fundamental_plane, **hints)
|
| 2232 |
+
|
| 2233 |
+
def _as_integral(self, F, s, t):
|
| 2234 |
+
c = self.__class__._c
|
| 2235 |
+
return (
|
| 2236 |
+
Integral(exp(s*t)*F, (s, c - S.ImaginaryUnit*S.Infinity,
|
| 2237 |
+
c + S.ImaginaryUnit*S.Infinity)) /
|
| 2238 |
+
(2*S.Pi*S.ImaginaryUnit))
|
| 2239 |
+
|
| 2240 |
+
def doit(self, **hints):
|
| 2241 |
+
"""
|
| 2242 |
+
Try to evaluate the transform in closed form.
|
| 2243 |
+
|
| 2244 |
+
Explanation
|
| 2245 |
+
===========
|
| 2246 |
+
|
| 2247 |
+
Standard hints are the following:
|
| 2248 |
+
- ``noconds``: if True, do not return convergence conditions. The
|
| 2249 |
+
default setting is `True`.
|
| 2250 |
+
- ``simplify``: if True, it simplifies the final result. The
|
| 2251 |
+
default setting is `False`.
|
| 2252 |
+
"""
|
| 2253 |
+
_noconds = hints.get('noconds', True)
|
| 2254 |
+
_simplify = hints.get('simplify', False)
|
| 2255 |
+
|
| 2256 |
+
debugf('[ILT doit] (%s, %s, %s)', (self.function,
|
| 2257 |
+
self.function_variable,
|
| 2258 |
+
self.transform_variable))
|
| 2259 |
+
|
| 2260 |
+
s_ = self.function_variable
|
| 2261 |
+
t_ = self.transform_variable
|
| 2262 |
+
fn = self.function
|
| 2263 |
+
plane = self.fundamental_plane
|
| 2264 |
+
|
| 2265 |
+
r = _inverse_laplace_transform(
|
| 2266 |
+
fn, s_, t_, plane, simplify=_simplify, dorational=True)
|
| 2267 |
+
|
| 2268 |
+
if _noconds:
|
| 2269 |
+
return r[0]
|
| 2270 |
+
else:
|
| 2271 |
+
return r
|
| 2272 |
+
|
| 2273 |
+
|
| 2274 |
+
def inverse_laplace_transform(F, s, t, plane=None, **hints):
|
| 2275 |
+
r"""
|
| 2276 |
+
Compute the inverse Laplace transform of `F(s)`, defined as
|
| 2277 |
+
|
| 2278 |
+
.. math ::
|
| 2279 |
+
f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{st}
|
| 2280 |
+
F(s) \mathrm{d}s,
|
| 2281 |
+
|
| 2282 |
+
for `c` so large that `F(s)` has no singularites in the
|
| 2283 |
+
half-plane `\operatorname{Re}(s) > c-\epsilon`.
|
| 2284 |
+
|
| 2285 |
+
Explanation
|
| 2286 |
+
===========
|
| 2287 |
+
|
| 2288 |
+
The plane can be specified by
|
| 2289 |
+
argument ``plane``, but will be inferred if passed as None.
|
| 2290 |
+
|
| 2291 |
+
Under certain regularity conditions, this recovers `f(t)` from its
|
| 2292 |
+
Laplace Transform `F(s)`, for non-negative `t`, and vice
|
| 2293 |
+
versa.
|
| 2294 |
+
|
| 2295 |
+
If the integral cannot be computed in closed form, this function returns
|
| 2296 |
+
an unevaluated :class:`InverseLaplaceTransform` object.
|
| 2297 |
+
|
| 2298 |
+
Note that this function will always assume `t` to be real,
|
| 2299 |
+
regardless of the SymPy assumption on `t`.
|
| 2300 |
+
|
| 2301 |
+
For a description of possible hints, refer to the docstring of
|
| 2302 |
+
:func:`sympy.integrals.transforms.IntegralTransform.doit`.
|
| 2303 |
+
|
| 2304 |
+
Examples
|
| 2305 |
+
========
|
| 2306 |
+
|
| 2307 |
+
>>> from sympy import inverse_laplace_transform, exp, Symbol
|
| 2308 |
+
>>> from sympy.abc import s, t
|
| 2309 |
+
>>> a = Symbol('a', positive=True)
|
| 2310 |
+
>>> inverse_laplace_transform(exp(-a*s)/s, s, t)
|
| 2311 |
+
Heaviside(-a + t)
|
| 2312 |
+
|
| 2313 |
+
See Also
|
| 2314 |
+
========
|
| 2315 |
+
|
| 2316 |
+
laplace_transform
|
| 2317 |
+
hankel_transform, inverse_hankel_transform
|
| 2318 |
+
"""
|
| 2319 |
+
_noconds = hints.get('noconds', True)
|
| 2320 |
+
_simplify = hints.get('simplify', False)
|
| 2321 |
+
|
| 2322 |
+
if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'):
|
| 2323 |
+
return F.applyfunc(
|
| 2324 |
+
lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints))
|
| 2325 |
+
|
| 2326 |
+
r, c = InverseLaplaceTransform(F, s, t, plane).doit(
|
| 2327 |
+
noconds=False, simplify=_simplify)
|
| 2328 |
+
|
| 2329 |
+
if _noconds:
|
| 2330 |
+
return r
|
| 2331 |
+
else:
|
| 2332 |
+
return r, c
|
| 2333 |
+
|
| 2334 |
+
|
| 2335 |
+
def _fast_inverse_laplace(e, s, t):
|
| 2336 |
+
"""Fast inverse Laplace transform of rational function including RootSum"""
|
| 2337 |
+
a, b, n = symbols('a, b, n', cls=Wild, exclude=[s])
|
| 2338 |
+
|
| 2339 |
+
def _ilt(e):
|
| 2340 |
+
if not e.has(s):
|
| 2341 |
+
return e
|
| 2342 |
+
elif e.is_Add:
|
| 2343 |
+
return _ilt_add(e)
|
| 2344 |
+
elif e.is_Mul:
|
| 2345 |
+
return _ilt_mul(e)
|
| 2346 |
+
elif e.is_Pow:
|
| 2347 |
+
return _ilt_pow(e)
|
| 2348 |
+
elif isinstance(e, RootSum):
|
| 2349 |
+
return _ilt_rootsum(e)
|
| 2350 |
+
else:
|
| 2351 |
+
raise NotImplementedError
|
| 2352 |
+
|
| 2353 |
+
def _ilt_add(e):
|
| 2354 |
+
return e.func(*map(_ilt, e.args))
|
| 2355 |
+
|
| 2356 |
+
def _ilt_mul(e):
|
| 2357 |
+
coeff, expr = e.as_independent(s)
|
| 2358 |
+
if expr.is_Mul:
|
| 2359 |
+
raise NotImplementedError
|
| 2360 |
+
return coeff * _ilt(expr)
|
| 2361 |
+
|
| 2362 |
+
def _ilt_pow(e):
|
| 2363 |
+
match = e.match((a*s + b)**n)
|
| 2364 |
+
if match is not None:
|
| 2365 |
+
nm, am, bm = match[n], match[a], match[b]
|
| 2366 |
+
if nm.is_Integer and nm < 0:
|
| 2367 |
+
return t**(-nm-1)*exp(-(bm/am)*t)/(am**-nm*gamma(-nm))
|
| 2368 |
+
if nm == 1:
|
| 2369 |
+
return exp(-(bm/am)*t) / am
|
| 2370 |
+
raise NotImplementedError
|
| 2371 |
+
|
| 2372 |
+
def _ilt_rootsum(e):
|
| 2373 |
+
expr = e.fun.expr
|
| 2374 |
+
[variable] = e.fun.variables
|
| 2375 |
+
return RootSum(e.poly, Lambda(variable, together(_ilt(expr))))
|
| 2376 |
+
|
| 2377 |
+
return _ilt(e)
|
.venv/lib/python3.12/site-packages/sympy/integrals/manualintegrate.py
ADDED
|
@@ -0,0 +1,2174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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) # type: ignore
|
| 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)/sqrt(-a)/2 * exp(c - b**2/(4*a)) *
|
| 663 |
+
erf((-2*a*x - b)/(2*sqrt(-a))), a < 0),
|
| 664 |
+
(sqrt(S.Pi)/sqrt(a)/2 * exp(c - b**2/(4*a)) *
|
| 665 |
+
erfi((2*a*x + b)/(2*sqrt(a))), True))
|
| 666 |
+
return sqrt(S.Pi)/sqrt(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)/sqrt(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)/sqrt(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) # type: ignore
|
| 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 |
+
|
| 1434 |
+
power = PowerRule(integrand, symbol, symbol, -2)
|
| 1435 |
+
if b != 1:
|
| 1436 |
+
power = ConstantTimesRule(integrand, symbol, 1/b, symbol**-2, power)
|
| 1437 |
+
|
| 1438 |
+
return PiecewiseRule(integrand, symbol, [(general_rule, Ne(c, 0)), (power, True)])
|
| 1439 |
+
|
| 1440 |
+
d = Wild('d', exclude=[symbol])
|
| 1441 |
+
match2 = integrand.match(a / (b * symbol ** 2 + c * symbol + d))
|
| 1442 |
+
if match2:
|
| 1443 |
+
b, c = match2[b], match2[c]
|
| 1444 |
+
if b.is_zero:
|
| 1445 |
+
return
|
| 1446 |
+
u = Dummy('u')
|
| 1447 |
+
u_func = symbol + c/(2*b)
|
| 1448 |
+
integrand2 = integrand.subs(symbol, u - c / (2*b))
|
| 1449 |
+
next_step = integral_steps(integrand2, u)
|
| 1450 |
+
if next_step:
|
| 1451 |
+
return URule(integrand2, symbol, u, u_func, next_step)
|
| 1452 |
+
else:
|
| 1453 |
+
return
|
| 1454 |
+
e = Wild('e', exclude=[symbol])
|
| 1455 |
+
match3 = integrand.match((a* symbol + b) / (c * symbol ** 2 + d * symbol + e))
|
| 1456 |
+
if match3:
|
| 1457 |
+
a, b, c, d, e = match3[a], match3[b], match3[c], match3[d], match3[e]
|
| 1458 |
+
if c.is_zero:
|
| 1459 |
+
return
|
| 1460 |
+
denominator = c * symbol**2 + d * symbol + e
|
| 1461 |
+
const = a/(2*c)
|
| 1462 |
+
numer1 = (2*c*symbol+d)
|
| 1463 |
+
numer2 = - const*d + b
|
| 1464 |
+
u = Dummy('u')
|
| 1465 |
+
step1 = URule(integrand, symbol,
|
| 1466 |
+
u, denominator, integral_steps(u**(-1), u))
|
| 1467 |
+
if const != 1:
|
| 1468 |
+
step1 = ConstantTimesRule(const*numer1/denominator, symbol,
|
| 1469 |
+
const, numer1/denominator, step1)
|
| 1470 |
+
if numer2.is_zero:
|
| 1471 |
+
return step1
|
| 1472 |
+
step2 = integral_steps(numer2/denominator, symbol)
|
| 1473 |
+
substeps = AddRule(integrand, symbol, [step1, step2])
|
| 1474 |
+
rewriten = const*numer1/denominator+numer2/denominator
|
| 1475 |
+
return RewriteRule(integrand, symbol, rewriten, substeps)
|
| 1476 |
+
|
| 1477 |
+
return
|
| 1478 |
+
|
| 1479 |
+
|
| 1480 |
+
def sqrt_linear_rule(integral: IntegralInfo):
|
| 1481 |
+
"""
|
| 1482 |
+
Substitute common (a+b*x)**(1/n)
|
| 1483 |
+
"""
|
| 1484 |
+
integrand, x = integral
|
| 1485 |
+
a = Wild('a', exclude=[x])
|
| 1486 |
+
b = Wild('b', exclude=[x, 0])
|
| 1487 |
+
a0 = b0 = 0
|
| 1488 |
+
bases, qs, bs = [], [], []
|
| 1489 |
+
for pow_ in integrand.find(Pow): # collect all (a+b*x)**(p/q)
|
| 1490 |
+
base, exp_ = pow_.base, pow_.exp
|
| 1491 |
+
if exp_.is_Integer or x not in base.free_symbols: # skip 1/x and sqrt(2)
|
| 1492 |
+
continue
|
| 1493 |
+
if not exp_.is_Rational: # exclude x**pi
|
| 1494 |
+
return
|
| 1495 |
+
match = base.match(a+b*x)
|
| 1496 |
+
if not match: # skip non-linear
|
| 1497 |
+
continue # for sqrt(x+sqrt(x)), although base is non-linear, we can still substitute sqrt(x)
|
| 1498 |
+
a1, b1 = match[a], match[b]
|
| 1499 |
+
if a0*b1 != a1*b0 or not (b0/b1).is_nonnegative: # cannot transform sqrt(x) to sqrt(x+1) or sqrt(-x)
|
| 1500 |
+
return
|
| 1501 |
+
if b0 == 0 or (b0/b1 > 1) is S.true: # choose the latter of sqrt(2*x) and sqrt(x) as representative
|
| 1502 |
+
a0, b0 = a1, b1
|
| 1503 |
+
bases.append(base)
|
| 1504 |
+
bs.append(b1)
|
| 1505 |
+
qs.append(exp_.q)
|
| 1506 |
+
if b0 == 0: # no such pattern found
|
| 1507 |
+
return
|
| 1508 |
+
q0: Integer = lcm_list(qs)
|
| 1509 |
+
u_x = (a0 + b0*x)**(1/q0)
|
| 1510 |
+
u = Dummy("u")
|
| 1511 |
+
substituted = integrand.subs({base**(S.One/q): (b/b0)**(S.One/q)*u**(q0/q)
|
| 1512 |
+
for base, b, q in zip(bases, bs, qs)}).subs(x, (u**q0-a0)/b0)
|
| 1513 |
+
substep = integral_steps(substituted*u**(q0-1)*q0/b0, u)
|
| 1514 |
+
if not substep.contains_dont_know():
|
| 1515 |
+
step: Rule = URule(integrand, x, u, u_x, substep)
|
| 1516 |
+
generic_cond = Ne(b0, 0)
|
| 1517 |
+
if generic_cond is not S.true: # possible degenerate case
|
| 1518 |
+
simplified = integrand.subs(dict.fromkeys(bs, 0))
|
| 1519 |
+
degenerate_step = integral_steps(simplified, x)
|
| 1520 |
+
step = PiecewiseRule(integrand, x, [(step, generic_cond), (degenerate_step, S.true)])
|
| 1521 |
+
return step
|
| 1522 |
+
|
| 1523 |
+
|
| 1524 |
+
def sqrt_quadratic_rule(integral: IntegralInfo, degenerate=True):
|
| 1525 |
+
integrand, x = integral
|
| 1526 |
+
a = Wild('a', exclude=[x])
|
| 1527 |
+
b = Wild('b', exclude=[x])
|
| 1528 |
+
c = Wild('c', exclude=[x, 0])
|
| 1529 |
+
f = Wild('f')
|
| 1530 |
+
n = Wild('n', properties=[lambda n: n.is_Integer and n.is_odd])
|
| 1531 |
+
match = integrand.match(f*sqrt(a+b*x+c*x**2)**n)
|
| 1532 |
+
if not match:
|
| 1533 |
+
return
|
| 1534 |
+
a, b, c, f, n = match[a], match[b], match[c], match[f], match[n]
|
| 1535 |
+
f_poly = f.as_poly(x)
|
| 1536 |
+
if f_poly is None:
|
| 1537 |
+
return
|
| 1538 |
+
|
| 1539 |
+
generic_cond = Ne(c, 0)
|
| 1540 |
+
if not degenerate or generic_cond is S.true:
|
| 1541 |
+
degenerate_step = None
|
| 1542 |
+
elif b.is_zero:
|
| 1543 |
+
degenerate_step = integral_steps(f*sqrt(a)**n, x)
|
| 1544 |
+
else:
|
| 1545 |
+
degenerate_step = sqrt_linear_rule(IntegralInfo(f*sqrt(a+b*x)**n, x))
|
| 1546 |
+
|
| 1547 |
+
def sqrt_quadratic_denom_rule(numer_poly: Poly, integrand: Expr):
|
| 1548 |
+
denom = sqrt(a+b*x+c*x**2)
|
| 1549 |
+
deg = numer_poly.degree()
|
| 1550 |
+
if deg <= 1:
|
| 1551 |
+
# integrand == (d+e*x)/sqrt(a+b*x+c*x**2)
|
| 1552 |
+
e, d = numer_poly.all_coeffs() if deg == 1 else (S.Zero, numer_poly.as_expr())
|
| 1553 |
+
# rewrite numerator to A*(2*c*x+b) + B
|
| 1554 |
+
A = e/(2*c)
|
| 1555 |
+
B = d-A*b
|
| 1556 |
+
pre_substitute = (2*c*x+b)/denom
|
| 1557 |
+
constant_step: Rule | None = None
|
| 1558 |
+
linear_step: Rule | None = None
|
| 1559 |
+
if A != 0:
|
| 1560 |
+
u = Dummy("u")
|
| 1561 |
+
pow_rule = PowerRule(1/sqrt(u), u, u, -S.Half)
|
| 1562 |
+
linear_step = URule(pre_substitute, x, u, a+b*x+c*x**2, pow_rule)
|
| 1563 |
+
if A != 1:
|
| 1564 |
+
linear_step = ConstantTimesRule(A*pre_substitute, x, A, pre_substitute, linear_step)
|
| 1565 |
+
if B != 0:
|
| 1566 |
+
constant_step = inverse_trig_rule(IntegralInfo(1/denom, x), degenerate=False)
|
| 1567 |
+
if B != 1:
|
| 1568 |
+
constant_step = ConstantTimesRule(B/denom, x, B, 1/denom, constant_step) # type: ignore
|
| 1569 |
+
if linear_step and constant_step:
|
| 1570 |
+
add = Add(A*pre_substitute, B/denom, evaluate=False)
|
| 1571 |
+
step: Rule | None = RewriteRule(integrand, x, add, AddRule(add, x, [linear_step, constant_step]))
|
| 1572 |
+
else:
|
| 1573 |
+
step = linear_step or constant_step
|
| 1574 |
+
else:
|
| 1575 |
+
coeffs = numer_poly.all_coeffs()
|
| 1576 |
+
step = SqrtQuadraticDenomRule(integrand, x, a, b, c, coeffs)
|
| 1577 |
+
return step
|
| 1578 |
+
|
| 1579 |
+
if n > 0: # rewrite poly * sqrt(s)**(2*k-1) to poly*s**k / sqrt(s)
|
| 1580 |
+
numer_poly = f_poly * (a+b*x+c*x**2)**((n+1)/2)
|
| 1581 |
+
rewritten = numer_poly.as_expr()/sqrt(a+b*x+c*x**2)
|
| 1582 |
+
substep = sqrt_quadratic_denom_rule(numer_poly, rewritten)
|
| 1583 |
+
generic_step = RewriteRule(integrand, x, rewritten, substep)
|
| 1584 |
+
elif n == -1:
|
| 1585 |
+
generic_step = sqrt_quadratic_denom_rule(f_poly, integrand)
|
| 1586 |
+
else:
|
| 1587 |
+
return # todo: handle n < -1 case
|
| 1588 |
+
return _add_degenerate_step(generic_cond, generic_step, degenerate_step)
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
def hyperbolic_rule(integral: tuple[Expr, Symbol]):
|
| 1592 |
+
integrand, symbol = integral
|
| 1593 |
+
if isinstance(integrand, HyperbolicFunction) and integrand.args[0] == symbol:
|
| 1594 |
+
if integrand.func == sinh:
|
| 1595 |
+
return SinhRule(integrand, symbol)
|
| 1596 |
+
if integrand.func == cosh:
|
| 1597 |
+
return CoshRule(integrand, symbol)
|
| 1598 |
+
u = Dummy('u')
|
| 1599 |
+
if integrand.func == tanh:
|
| 1600 |
+
rewritten = sinh(symbol)/cosh(symbol)
|
| 1601 |
+
return RewriteRule(integrand, symbol, rewritten,
|
| 1602 |
+
URule(rewritten, symbol, u, cosh(symbol), ReciprocalRule(1/u, u, u)))
|
| 1603 |
+
if integrand.func == coth:
|
| 1604 |
+
rewritten = cosh(symbol)/sinh(symbol)
|
| 1605 |
+
return RewriteRule(integrand, symbol, rewritten,
|
| 1606 |
+
URule(rewritten, symbol, u, sinh(symbol), ReciprocalRule(1/u, u, u)))
|
| 1607 |
+
else:
|
| 1608 |
+
rewritten = integrand.rewrite(tanh)
|
| 1609 |
+
if integrand.func == sech:
|
| 1610 |
+
return RewriteRule(integrand, symbol, rewritten,
|
| 1611 |
+
URule(rewritten, symbol, u, tanh(symbol/2),
|
| 1612 |
+
ArctanRule(2/(u**2 + 1), u, S(2), S.One, S.One)))
|
| 1613 |
+
if integrand.func == csch:
|
| 1614 |
+
return RewriteRule(integrand, symbol, rewritten,
|
| 1615 |
+
URule(rewritten, symbol, u, tanh(symbol/2),
|
| 1616 |
+
ReciprocalRule(1/u, u, u)))
|
| 1617 |
+
|
| 1618 |
+
@cacheit
|
| 1619 |
+
def make_wilds(symbol):
|
| 1620 |
+
a = Wild('a', exclude=[symbol])
|
| 1621 |
+
b = Wild('b', exclude=[symbol])
|
| 1622 |
+
m = Wild('m', exclude=[symbol], properties=[lambda n: isinstance(n, Integer)])
|
| 1623 |
+
n = Wild('n', exclude=[symbol], properties=[lambda n: isinstance(n, Integer)])
|
| 1624 |
+
|
| 1625 |
+
return a, b, m, n
|
| 1626 |
+
|
| 1627 |
+
@cacheit
|
| 1628 |
+
def sincos_pattern(symbol):
|
| 1629 |
+
a, b, m, n = make_wilds(symbol)
|
| 1630 |
+
pattern = sin(a*symbol)**m * cos(b*symbol)**n
|
| 1631 |
+
|
| 1632 |
+
return pattern, a, b, m, n
|
| 1633 |
+
|
| 1634 |
+
@cacheit
|
| 1635 |
+
def tansec_pattern(symbol):
|
| 1636 |
+
a, b, m, n = make_wilds(symbol)
|
| 1637 |
+
pattern = tan(a*symbol)**m * sec(b*symbol)**n
|
| 1638 |
+
|
| 1639 |
+
return pattern, a, b, m, n
|
| 1640 |
+
|
| 1641 |
+
@cacheit
|
| 1642 |
+
def cotcsc_pattern(symbol):
|
| 1643 |
+
a, b, m, n = make_wilds(symbol)
|
| 1644 |
+
pattern = cot(a*symbol)**m * csc(b*symbol)**n
|
| 1645 |
+
|
| 1646 |
+
return pattern, a, b, m, n
|
| 1647 |
+
|
| 1648 |
+
@cacheit
|
| 1649 |
+
def heaviside_pattern(symbol):
|
| 1650 |
+
m = Wild('m', exclude=[symbol])
|
| 1651 |
+
b = Wild('b', exclude=[symbol])
|
| 1652 |
+
g = Wild('g')
|
| 1653 |
+
pattern = Heaviside(m*symbol + b) * g
|
| 1654 |
+
|
| 1655 |
+
return pattern, m, b, g
|
| 1656 |
+
|
| 1657 |
+
def uncurry(func):
|
| 1658 |
+
def uncurry_rl(args):
|
| 1659 |
+
return func(*args)
|
| 1660 |
+
return uncurry_rl
|
| 1661 |
+
|
| 1662 |
+
def trig_rewriter(rewrite):
|
| 1663 |
+
def trig_rewriter_rl(args):
|
| 1664 |
+
a, b, m, n, integrand, symbol = args
|
| 1665 |
+
rewritten = rewrite(a, b, m, n, integrand, symbol)
|
| 1666 |
+
if rewritten != integrand:
|
| 1667 |
+
return RewriteRule(integrand, symbol, rewritten, integral_steps(rewritten, symbol))
|
| 1668 |
+
return trig_rewriter_rl
|
| 1669 |
+
|
| 1670 |
+
sincos_botheven_condition = uncurry(
|
| 1671 |
+
lambda a, b, m, n, i, s: m.is_even and n.is_even and
|
| 1672 |
+
m.is_nonnegative and n.is_nonnegative)
|
| 1673 |
+
|
| 1674 |
+
sincos_botheven = trig_rewriter(
|
| 1675 |
+
lambda a, b, m, n, i, symbol: ( (((1 - cos(2*a*symbol)) / 2) ** (m / 2)) *
|
| 1676 |
+
(((1 + cos(2*b*symbol)) / 2) ** (n / 2)) ))
|
| 1677 |
+
|
| 1678 |
+
sincos_sinodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd and m >= 3)
|
| 1679 |
+
|
| 1680 |
+
sincos_sinodd = trig_rewriter(
|
| 1681 |
+
lambda a, b, m, n, i, symbol: ( (1 - cos(a*symbol)**2)**((m - 1) / 2) *
|
| 1682 |
+
sin(a*symbol) *
|
| 1683 |
+
cos(b*symbol) ** n))
|
| 1684 |
+
|
| 1685 |
+
sincos_cosodd_condition = uncurry(lambda a, b, m, n, i, s: n.is_odd and n >= 3)
|
| 1686 |
+
|
| 1687 |
+
sincos_cosodd = trig_rewriter(
|
| 1688 |
+
lambda a, b, m, n, i, symbol: ( (1 - sin(b*symbol)**2)**((n - 1) / 2) *
|
| 1689 |
+
cos(b*symbol) *
|
| 1690 |
+
sin(a*symbol) ** m))
|
| 1691 |
+
|
| 1692 |
+
tansec_seceven_condition = uncurry(lambda a, b, m, n, i, s: n.is_even and n >= 4)
|
| 1693 |
+
tansec_seceven = trig_rewriter(
|
| 1694 |
+
lambda a, b, m, n, i, symbol: ( (1 + tan(b*symbol)**2) ** (n/2 - 1) *
|
| 1695 |
+
sec(b*symbol)**2 *
|
| 1696 |
+
tan(a*symbol) ** m ))
|
| 1697 |
+
|
| 1698 |
+
tansec_tanodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd)
|
| 1699 |
+
tansec_tanodd = trig_rewriter(
|
| 1700 |
+
lambda a, b, m, n, i, symbol: ( (sec(a*symbol)**2 - 1) ** ((m - 1) / 2) *
|
| 1701 |
+
tan(a*symbol) *
|
| 1702 |
+
sec(b*symbol) ** n ))
|
| 1703 |
+
|
| 1704 |
+
tan_tansquared_condition = uncurry(lambda a, b, m, n, i, s: m == 2 and n == 0)
|
| 1705 |
+
tan_tansquared = trig_rewriter(
|
| 1706 |
+
lambda a, b, m, n, i, symbol: ( sec(a*symbol)**2 - 1))
|
| 1707 |
+
|
| 1708 |
+
cotcsc_csceven_condition = uncurry(lambda a, b, m, n, i, s: n.is_even and n >= 4)
|
| 1709 |
+
cotcsc_csceven = trig_rewriter(
|
| 1710 |
+
lambda a, b, m, n, i, symbol: ( (1 + cot(b*symbol)**2) ** (n/2 - 1) *
|
| 1711 |
+
csc(b*symbol)**2 *
|
| 1712 |
+
cot(a*symbol) ** m ))
|
| 1713 |
+
|
| 1714 |
+
cotcsc_cotodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd)
|
| 1715 |
+
cotcsc_cotodd = trig_rewriter(
|
| 1716 |
+
lambda a, b, m, n, i, symbol: ( (csc(a*symbol)**2 - 1) ** ((m - 1) / 2) *
|
| 1717 |
+
cot(a*symbol) *
|
| 1718 |
+
csc(b*symbol) ** n ))
|
| 1719 |
+
|
| 1720 |
+
def trig_sincos_rule(integral):
|
| 1721 |
+
integrand, symbol = integral
|
| 1722 |
+
|
| 1723 |
+
if any(integrand.has(f) for f in (sin, cos)):
|
| 1724 |
+
pattern, a, b, m, n = sincos_pattern(symbol)
|
| 1725 |
+
match = integrand.match(pattern)
|
| 1726 |
+
if not match:
|
| 1727 |
+
return
|
| 1728 |
+
|
| 1729 |
+
return multiplexer({
|
| 1730 |
+
sincos_botheven_condition: sincos_botheven,
|
| 1731 |
+
sincos_sinodd_condition: sincos_sinodd,
|
| 1732 |
+
sincos_cosodd_condition: sincos_cosodd
|
| 1733 |
+
})(tuple(
|
| 1734 |
+
[match.get(i, S.Zero) for i in (a, b, m, n)] +
|
| 1735 |
+
[integrand, symbol]))
|
| 1736 |
+
|
| 1737 |
+
def trig_tansec_rule(integral):
|
| 1738 |
+
integrand, symbol = integral
|
| 1739 |
+
|
| 1740 |
+
integrand = integrand.subs({
|
| 1741 |
+
1 / cos(symbol): sec(symbol)
|
| 1742 |
+
})
|
| 1743 |
+
|
| 1744 |
+
if any(integrand.has(f) for f in (tan, sec)):
|
| 1745 |
+
pattern, a, b, m, n = tansec_pattern(symbol)
|
| 1746 |
+
match = integrand.match(pattern)
|
| 1747 |
+
if not match:
|
| 1748 |
+
return
|
| 1749 |
+
|
| 1750 |
+
return multiplexer({
|
| 1751 |
+
tansec_tanodd_condition: tansec_tanodd,
|
| 1752 |
+
tansec_seceven_condition: tansec_seceven,
|
| 1753 |
+
tan_tansquared_condition: tan_tansquared
|
| 1754 |
+
})(tuple(
|
| 1755 |
+
[match.get(i, S.Zero) for i in (a, b, m, n)] +
|
| 1756 |
+
[integrand, symbol]))
|
| 1757 |
+
|
| 1758 |
+
def trig_cotcsc_rule(integral):
|
| 1759 |
+
integrand, symbol = integral
|
| 1760 |
+
integrand = integrand.subs({
|
| 1761 |
+
1 / sin(symbol): csc(symbol),
|
| 1762 |
+
1 / tan(symbol): cot(symbol),
|
| 1763 |
+
cos(symbol) / tan(symbol): cot(symbol)
|
| 1764 |
+
})
|
| 1765 |
+
|
| 1766 |
+
if any(integrand.has(f) for f in (cot, csc)):
|
| 1767 |
+
pattern, a, b, m, n = cotcsc_pattern(symbol)
|
| 1768 |
+
match = integrand.match(pattern)
|
| 1769 |
+
if not match:
|
| 1770 |
+
return
|
| 1771 |
+
|
| 1772 |
+
return multiplexer({
|
| 1773 |
+
cotcsc_cotodd_condition: cotcsc_cotodd,
|
| 1774 |
+
cotcsc_csceven_condition: cotcsc_csceven
|
| 1775 |
+
})(tuple(
|
| 1776 |
+
[match.get(i, S.Zero) for i in (a, b, m, n)] +
|
| 1777 |
+
[integrand, symbol]))
|
| 1778 |
+
|
| 1779 |
+
def trig_sindouble_rule(integral):
|
| 1780 |
+
integrand, symbol = integral
|
| 1781 |
+
a = Wild('a', exclude=[sin(2*symbol)])
|
| 1782 |
+
match = integrand.match(sin(2*symbol)*a)
|
| 1783 |
+
if match:
|
| 1784 |
+
sin_double = 2*sin(symbol)*cos(symbol)/sin(2*symbol)
|
| 1785 |
+
return integral_steps(integrand * sin_double, symbol)
|
| 1786 |
+
|
| 1787 |
+
def trig_powers_products_rule(integral):
|
| 1788 |
+
return do_one(null_safe(trig_sincos_rule),
|
| 1789 |
+
null_safe(trig_tansec_rule),
|
| 1790 |
+
null_safe(trig_cotcsc_rule),
|
| 1791 |
+
null_safe(trig_sindouble_rule))(integral)
|
| 1792 |
+
|
| 1793 |
+
def trig_substitution_rule(integral):
|
| 1794 |
+
integrand, symbol = integral
|
| 1795 |
+
A = Wild('a', exclude=[0, symbol])
|
| 1796 |
+
B = Wild('b', exclude=[0, symbol])
|
| 1797 |
+
theta = Dummy("theta")
|
| 1798 |
+
target_pattern = A + B*symbol**2
|
| 1799 |
+
|
| 1800 |
+
matches = integrand.find(target_pattern)
|
| 1801 |
+
for expr in matches:
|
| 1802 |
+
match = expr.match(target_pattern)
|
| 1803 |
+
a = match.get(A, S.Zero)
|
| 1804 |
+
b = match.get(B, S.Zero)
|
| 1805 |
+
|
| 1806 |
+
a_positive = ((a.is_number and a > 0) or a.is_positive)
|
| 1807 |
+
b_positive = ((b.is_number and b > 0) or b.is_positive)
|
| 1808 |
+
a_negative = ((a.is_number and a < 0) or a.is_negative)
|
| 1809 |
+
b_negative = ((b.is_number and b < 0) or b.is_negative)
|
| 1810 |
+
x_func = None
|
| 1811 |
+
if a_positive and b_positive:
|
| 1812 |
+
# a**2 + b*x**2. Assume sec(theta) > 0, -pi/2 < theta < pi/2
|
| 1813 |
+
x_func = (sqrt(a)/sqrt(b)) * tan(theta)
|
| 1814 |
+
# Do not restrict the domain: tan(theta) takes on any real
|
| 1815 |
+
# value on the interval -pi/2 < theta < pi/2 so x takes on
|
| 1816 |
+
# any value
|
| 1817 |
+
restriction = True
|
| 1818 |
+
elif a_positive and b_negative:
|
| 1819 |
+
# a**2 - b*x**2. Assume cos(theta) > 0, -pi/2 < theta < pi/2
|
| 1820 |
+
constant = sqrt(a)/sqrt(-b)
|
| 1821 |
+
x_func = constant * sin(theta)
|
| 1822 |
+
restriction = And(symbol > -constant, symbol < constant)
|
| 1823 |
+
elif a_negative and b_positive:
|
| 1824 |
+
# b*x**2 - a**2. Assume sin(theta) > 0, 0 < theta < pi
|
| 1825 |
+
constant = sqrt(-a)/sqrt(b)
|
| 1826 |
+
x_func = constant * sec(theta)
|
| 1827 |
+
restriction = And(symbol > -constant, symbol < constant)
|
| 1828 |
+
if x_func:
|
| 1829 |
+
# Manually simplify sqrt(trig(theta)**2) to trig(theta)
|
| 1830 |
+
# Valid due to assumed domain restriction
|
| 1831 |
+
substitutions = {}
|
| 1832 |
+
for f in [sin, cos, tan,
|
| 1833 |
+
sec, csc, cot]:
|
| 1834 |
+
substitutions[sqrt(f(theta)**2)] = f(theta)
|
| 1835 |
+
substitutions[sqrt(f(theta)**(-2))] = 1/f(theta)
|
| 1836 |
+
|
| 1837 |
+
replaced = integrand.subs(symbol, x_func).trigsimp()
|
| 1838 |
+
replaced = manual_subs(replaced, substitutions)
|
| 1839 |
+
if not replaced.has(symbol):
|
| 1840 |
+
replaced *= manual_diff(x_func, theta)
|
| 1841 |
+
replaced = replaced.trigsimp()
|
| 1842 |
+
secants = replaced.find(1/cos(theta))
|
| 1843 |
+
if secants:
|
| 1844 |
+
replaced = replaced.xreplace({
|
| 1845 |
+
1/cos(theta): sec(theta)
|
| 1846 |
+
})
|
| 1847 |
+
|
| 1848 |
+
substep = integral_steps(replaced, theta)
|
| 1849 |
+
if not substep.contains_dont_know():
|
| 1850 |
+
return TrigSubstitutionRule(integrand, symbol,
|
| 1851 |
+
theta, x_func, replaced, substep, restriction)
|
| 1852 |
+
|
| 1853 |
+
def heaviside_rule(integral):
|
| 1854 |
+
integrand, symbol = integral
|
| 1855 |
+
pattern, m, b, g = heaviside_pattern(symbol)
|
| 1856 |
+
match = integrand.match(pattern)
|
| 1857 |
+
if match and 0 != match[g]:
|
| 1858 |
+
# f = Heaviside(m*x + b)*g
|
| 1859 |
+
substep = integral_steps(match[g], symbol)
|
| 1860 |
+
m, b = match[m], match[b]
|
| 1861 |
+
return HeavisideRule(integrand, symbol, m*symbol + b, -b/m, substep)
|
| 1862 |
+
|
| 1863 |
+
|
| 1864 |
+
def dirac_delta_rule(integral: IntegralInfo):
|
| 1865 |
+
integrand, x = integral
|
| 1866 |
+
if len(integrand.args) == 1:
|
| 1867 |
+
n = S.Zero
|
| 1868 |
+
else:
|
| 1869 |
+
n = integrand.args[1] # type: ignore
|
| 1870 |
+
if not n.is_Integer or n < 0:
|
| 1871 |
+
return
|
| 1872 |
+
a, b = Wild('a', exclude=[x]), Wild('b', exclude=[x, 0])
|
| 1873 |
+
match = integrand.args[0].match(a+b*x)
|
| 1874 |
+
if not match:
|
| 1875 |
+
return
|
| 1876 |
+
a, b = match[a], match[b]
|
| 1877 |
+
generic_cond = Ne(b, 0)
|
| 1878 |
+
if generic_cond is S.true:
|
| 1879 |
+
degenerate_step = None
|
| 1880 |
+
else:
|
| 1881 |
+
degenerate_step = ConstantRule(DiracDelta(a, n), x)
|
| 1882 |
+
generic_step = DiracDeltaRule(integrand, x, n, a, b)
|
| 1883 |
+
return _add_degenerate_step(generic_cond, generic_step, degenerate_step)
|
| 1884 |
+
|
| 1885 |
+
|
| 1886 |
+
def substitution_rule(integral):
|
| 1887 |
+
integrand, symbol = integral
|
| 1888 |
+
|
| 1889 |
+
u_var = Dummy("u")
|
| 1890 |
+
substitutions = find_substitutions(integrand, symbol, u_var)
|
| 1891 |
+
count = 0
|
| 1892 |
+
if substitutions:
|
| 1893 |
+
debug("List of Substitution Rules")
|
| 1894 |
+
ways = []
|
| 1895 |
+
for u_func, c, substituted in substitutions:
|
| 1896 |
+
subrule = integral_steps(substituted, u_var)
|
| 1897 |
+
count = count + 1
|
| 1898 |
+
debug("Rule {}: {}".format(count, subrule))
|
| 1899 |
+
|
| 1900 |
+
if subrule.contains_dont_know():
|
| 1901 |
+
continue
|
| 1902 |
+
|
| 1903 |
+
if simplify(c - 1) != 0:
|
| 1904 |
+
_, denom = c.as_numer_denom()
|
| 1905 |
+
if subrule:
|
| 1906 |
+
subrule = ConstantTimesRule(c * substituted, u_var, c, substituted, subrule)
|
| 1907 |
+
|
| 1908 |
+
if denom.free_symbols:
|
| 1909 |
+
piecewise = []
|
| 1910 |
+
could_be_zero = []
|
| 1911 |
+
|
| 1912 |
+
if isinstance(denom, Mul):
|
| 1913 |
+
could_be_zero = denom.args
|
| 1914 |
+
else:
|
| 1915 |
+
could_be_zero.append(denom)
|
| 1916 |
+
|
| 1917 |
+
for expr in could_be_zero:
|
| 1918 |
+
if not fuzzy_not(expr.is_zero):
|
| 1919 |
+
substep = integral_steps(manual_subs(integrand, expr, 0), symbol)
|
| 1920 |
+
|
| 1921 |
+
if substep:
|
| 1922 |
+
piecewise.append((
|
| 1923 |
+
substep,
|
| 1924 |
+
Eq(expr, 0)
|
| 1925 |
+
))
|
| 1926 |
+
piecewise.append((subrule, True))
|
| 1927 |
+
subrule = PiecewiseRule(substituted, symbol, piecewise)
|
| 1928 |
+
|
| 1929 |
+
ways.append(URule(integrand, symbol, u_var, u_func, subrule))
|
| 1930 |
+
|
| 1931 |
+
if len(ways) > 1:
|
| 1932 |
+
return AlternativeRule(integrand, symbol, ways)
|
| 1933 |
+
elif ways:
|
| 1934 |
+
return ways[0]
|
| 1935 |
+
|
| 1936 |
+
|
| 1937 |
+
partial_fractions_rule = rewriter(
|
| 1938 |
+
lambda integrand, symbol: integrand.is_rational_function(),
|
| 1939 |
+
lambda integrand, symbol: integrand.apart(symbol))
|
| 1940 |
+
|
| 1941 |
+
cancel_rule = rewriter(
|
| 1942 |
+
# lambda integrand, symbol: integrand.is_algebraic_expr(),
|
| 1943 |
+
# lambda integrand, symbol: isinstance(integrand, Mul),
|
| 1944 |
+
lambda integrand, symbol: True,
|
| 1945 |
+
lambda integrand, symbol: integrand.cancel())
|
| 1946 |
+
|
| 1947 |
+
distribute_expand_rule = rewriter(
|
| 1948 |
+
lambda integrand, symbol: (
|
| 1949 |
+
isinstance(integrand, (Pow, Mul)) or all(arg.is_Pow or arg.is_polynomial(symbol) for arg in integrand.args)),
|
| 1950 |
+
lambda integrand, symbol: integrand.expand())
|
| 1951 |
+
|
| 1952 |
+
trig_expand_rule = rewriter(
|
| 1953 |
+
# If there are trig functions with different arguments, expand them
|
| 1954 |
+
lambda integrand, symbol: (
|
| 1955 |
+
len({a.args[0] for a in integrand.atoms(TrigonometricFunction)}) > 1),
|
| 1956 |
+
lambda integrand, symbol: integrand.expand(trig=True))
|
| 1957 |
+
|
| 1958 |
+
def derivative_rule(integral):
|
| 1959 |
+
integrand = integral[0]
|
| 1960 |
+
diff_variables = integrand.variables
|
| 1961 |
+
undifferentiated_function = integrand.expr
|
| 1962 |
+
integrand_variables = undifferentiated_function.free_symbols
|
| 1963 |
+
|
| 1964 |
+
if integral.symbol in integrand_variables:
|
| 1965 |
+
if integral.symbol in diff_variables:
|
| 1966 |
+
return DerivativeRule(*integral)
|
| 1967 |
+
else:
|
| 1968 |
+
return DontKnowRule(integrand, integral.symbol)
|
| 1969 |
+
else:
|
| 1970 |
+
return ConstantRule(*integral)
|
| 1971 |
+
|
| 1972 |
+
def rewrites_rule(integral):
|
| 1973 |
+
integrand, symbol = integral
|
| 1974 |
+
|
| 1975 |
+
if integrand.match(1/cos(symbol)):
|
| 1976 |
+
rewritten = integrand.subs(1/cos(symbol), sec(symbol))
|
| 1977 |
+
return RewriteRule(integrand, symbol, rewritten, integral_steps(rewritten, symbol))
|
| 1978 |
+
|
| 1979 |
+
def fallback_rule(integral):
|
| 1980 |
+
return DontKnowRule(*integral)
|
| 1981 |
+
|
| 1982 |
+
# Cache is used to break cyclic integrals.
|
| 1983 |
+
# Need to use the same dummy variable in cached expressions for them to match.
|
| 1984 |
+
# Also record "u" of integration by parts, to avoid infinite repetition.
|
| 1985 |
+
_integral_cache: dict[Expr, Expr | None] = {}
|
| 1986 |
+
_parts_u_cache: dict[Expr, int] = defaultdict(int)
|
| 1987 |
+
_cache_dummy = Dummy("z")
|
| 1988 |
+
|
| 1989 |
+
def integral_steps(integrand, symbol, **options):
|
| 1990 |
+
"""Returns the steps needed to compute an integral.
|
| 1991 |
+
|
| 1992 |
+
Explanation
|
| 1993 |
+
===========
|
| 1994 |
+
|
| 1995 |
+
This function attempts to mirror what a student would do by hand as
|
| 1996 |
+
closely as possible.
|
| 1997 |
+
|
| 1998 |
+
SymPy Gamma uses this to provide a step-by-step explanation of an
|
| 1999 |
+
integral. The code it uses to format the results of this function can be
|
| 2000 |
+
found at
|
| 2001 |
+
https://github.com/sympy/sympy_gamma/blob/master/app/logic/intsteps.py.
|
| 2002 |
+
|
| 2003 |
+
Examples
|
| 2004 |
+
========
|
| 2005 |
+
|
| 2006 |
+
>>> from sympy import exp, sin
|
| 2007 |
+
>>> from sympy.integrals.manualintegrate import integral_steps
|
| 2008 |
+
>>> from sympy.abc import x
|
| 2009 |
+
>>> print(repr(integral_steps(exp(x) / (1 + exp(2 * x)), x))) \
|
| 2010 |
+
# doctest: +NORMALIZE_WHITESPACE
|
| 2011 |
+
URule(integrand=exp(x)/(exp(2*x) + 1), variable=x, u_var=_u, u_func=exp(x),
|
| 2012 |
+
substep=ArctanRule(integrand=1/(_u**2 + 1), variable=_u, a=1, b=1, c=1))
|
| 2013 |
+
>>> print(repr(integral_steps(sin(x), x))) \
|
| 2014 |
+
# doctest: +NORMALIZE_WHITESPACE
|
| 2015 |
+
SinRule(integrand=sin(x), variable=x)
|
| 2016 |
+
>>> print(repr(integral_steps((x**2 + 3)**2, x))) \
|
| 2017 |
+
# doctest: +NORMALIZE_WHITESPACE
|
| 2018 |
+
RewriteRule(integrand=(x**2 + 3)**2, variable=x, rewritten=x**4 + 6*x**2 + 9,
|
| 2019 |
+
substep=AddRule(integrand=x**4 + 6*x**2 + 9, variable=x,
|
| 2020 |
+
substeps=[PowerRule(integrand=x**4, variable=x, base=x, exp=4),
|
| 2021 |
+
ConstantTimesRule(integrand=6*x**2, variable=x, constant=6, other=x**2,
|
| 2022 |
+
substep=PowerRule(integrand=x**2, variable=x, base=x, exp=2)),
|
| 2023 |
+
ConstantRule(integrand=9, variable=x)]))
|
| 2024 |
+
|
| 2025 |
+
Returns
|
| 2026 |
+
=======
|
| 2027 |
+
|
| 2028 |
+
rule : Rule
|
| 2029 |
+
The first step; most rules have substeps that must also be
|
| 2030 |
+
considered. These substeps can be evaluated using ``manualintegrate``
|
| 2031 |
+
to obtain a result.
|
| 2032 |
+
|
| 2033 |
+
"""
|
| 2034 |
+
cachekey = integrand.xreplace({symbol: _cache_dummy})
|
| 2035 |
+
if cachekey in _integral_cache:
|
| 2036 |
+
if _integral_cache[cachekey] is None:
|
| 2037 |
+
# Stop this attempt, because it leads around in a loop
|
| 2038 |
+
return DontKnowRule(integrand, symbol)
|
| 2039 |
+
else:
|
| 2040 |
+
# TODO: This is for future development, as currently
|
| 2041 |
+
# _integral_cache gets no values other than None
|
| 2042 |
+
return (_integral_cache[cachekey].xreplace(_cache_dummy, symbol),
|
| 2043 |
+
symbol)
|
| 2044 |
+
else:
|
| 2045 |
+
_integral_cache[cachekey] = None
|
| 2046 |
+
|
| 2047 |
+
integral = IntegralInfo(integrand, symbol)
|
| 2048 |
+
|
| 2049 |
+
def key(integral):
|
| 2050 |
+
integrand = integral.integrand
|
| 2051 |
+
|
| 2052 |
+
if symbol not in integrand.free_symbols:
|
| 2053 |
+
return Number
|
| 2054 |
+
for cls in (Symbol, TrigonometricFunction, OrthogonalPolynomial):
|
| 2055 |
+
if isinstance(integrand, cls):
|
| 2056 |
+
return cls
|
| 2057 |
+
return type(integrand)
|
| 2058 |
+
|
| 2059 |
+
def integral_is_subclass(*klasses):
|
| 2060 |
+
def _integral_is_subclass(integral):
|
| 2061 |
+
k = key(integral)
|
| 2062 |
+
return k and issubclass(k, klasses)
|
| 2063 |
+
return _integral_is_subclass
|
| 2064 |
+
|
| 2065 |
+
result = do_one(
|
| 2066 |
+
null_safe(special_function_rule),
|
| 2067 |
+
null_safe(switch(key, {
|
| 2068 |
+
Pow: do_one(null_safe(power_rule), null_safe(inverse_trig_rule),
|
| 2069 |
+
null_safe(sqrt_linear_rule),
|
| 2070 |
+
null_safe(quadratic_denom_rule)),
|
| 2071 |
+
Symbol: power_rule,
|
| 2072 |
+
exp: exp_rule,
|
| 2073 |
+
Add: add_rule,
|
| 2074 |
+
Mul: do_one(null_safe(mul_rule), null_safe(trig_product_rule),
|
| 2075 |
+
null_safe(heaviside_rule), null_safe(quadratic_denom_rule),
|
| 2076 |
+
null_safe(sqrt_linear_rule),
|
| 2077 |
+
null_safe(sqrt_quadratic_rule)),
|
| 2078 |
+
Derivative: derivative_rule,
|
| 2079 |
+
TrigonometricFunction: trig_rule,
|
| 2080 |
+
Heaviside: heaviside_rule,
|
| 2081 |
+
DiracDelta: dirac_delta_rule,
|
| 2082 |
+
OrthogonalPolynomial: orthogonal_poly_rule,
|
| 2083 |
+
Number: constant_rule
|
| 2084 |
+
})),
|
| 2085 |
+
do_one(
|
| 2086 |
+
null_safe(trig_rule),
|
| 2087 |
+
null_safe(hyperbolic_rule),
|
| 2088 |
+
null_safe(alternatives(
|
| 2089 |
+
rewrites_rule,
|
| 2090 |
+
substitution_rule,
|
| 2091 |
+
condition(
|
| 2092 |
+
integral_is_subclass(Mul, Pow),
|
| 2093 |
+
partial_fractions_rule),
|
| 2094 |
+
condition(
|
| 2095 |
+
integral_is_subclass(Mul, Pow),
|
| 2096 |
+
cancel_rule),
|
| 2097 |
+
condition(
|
| 2098 |
+
integral_is_subclass(Mul, log,
|
| 2099 |
+
*inverse_trig_functions),
|
| 2100 |
+
parts_rule),
|
| 2101 |
+
condition(
|
| 2102 |
+
integral_is_subclass(Mul, Pow),
|
| 2103 |
+
distribute_expand_rule),
|
| 2104 |
+
trig_powers_products_rule,
|
| 2105 |
+
trig_expand_rule
|
| 2106 |
+
)),
|
| 2107 |
+
null_safe(condition(integral_is_subclass(Mul, Pow), nested_pow_rule)),
|
| 2108 |
+
null_safe(trig_substitution_rule)
|
| 2109 |
+
),
|
| 2110 |
+
fallback_rule)(integral)
|
| 2111 |
+
del _integral_cache[cachekey]
|
| 2112 |
+
return result
|
| 2113 |
+
|
| 2114 |
+
|
| 2115 |
+
def manualintegrate(f, var):
|
| 2116 |
+
"""manualintegrate(f, var)
|
| 2117 |
+
|
| 2118 |
+
Explanation
|
| 2119 |
+
===========
|
| 2120 |
+
|
| 2121 |
+
Compute indefinite integral of a single variable using an algorithm that
|
| 2122 |
+
resembles what a student would do by hand.
|
| 2123 |
+
|
| 2124 |
+
Unlike :func:`~.integrate`, var can only be a single symbol.
|
| 2125 |
+
|
| 2126 |
+
Examples
|
| 2127 |
+
========
|
| 2128 |
+
|
| 2129 |
+
>>> from sympy import sin, cos, tan, exp, log, integrate
|
| 2130 |
+
>>> from sympy.integrals.manualintegrate import manualintegrate
|
| 2131 |
+
>>> from sympy.abc import x
|
| 2132 |
+
>>> manualintegrate(1 / x, x)
|
| 2133 |
+
log(x)
|
| 2134 |
+
>>> integrate(1/x)
|
| 2135 |
+
log(x)
|
| 2136 |
+
>>> manualintegrate(log(x), x)
|
| 2137 |
+
x*log(x) - x
|
| 2138 |
+
>>> integrate(log(x))
|
| 2139 |
+
x*log(x) - x
|
| 2140 |
+
>>> manualintegrate(exp(x) / (1 + exp(2 * x)), x)
|
| 2141 |
+
atan(exp(x))
|
| 2142 |
+
>>> integrate(exp(x) / (1 + exp(2 * x)))
|
| 2143 |
+
RootSum(4*_z**2 + 1, Lambda(_i, _i*log(2*_i + exp(x))))
|
| 2144 |
+
>>> manualintegrate(cos(x)**4 * sin(x), x)
|
| 2145 |
+
-cos(x)**5/5
|
| 2146 |
+
>>> integrate(cos(x)**4 * sin(x), x)
|
| 2147 |
+
-cos(x)**5/5
|
| 2148 |
+
>>> manualintegrate(cos(x)**4 * sin(x)**3, x)
|
| 2149 |
+
cos(x)**7/7 - cos(x)**5/5
|
| 2150 |
+
>>> integrate(cos(x)**4 * sin(x)**3, x)
|
| 2151 |
+
cos(x)**7/7 - cos(x)**5/5
|
| 2152 |
+
>>> manualintegrate(tan(x), x)
|
| 2153 |
+
-log(cos(x))
|
| 2154 |
+
>>> integrate(tan(x), x)
|
| 2155 |
+
-log(cos(x))
|
| 2156 |
+
|
| 2157 |
+
See Also
|
| 2158 |
+
========
|
| 2159 |
+
|
| 2160 |
+
sympy.integrals.integrals.integrate
|
| 2161 |
+
sympy.integrals.integrals.Integral.doit
|
| 2162 |
+
sympy.integrals.integrals.Integral
|
| 2163 |
+
"""
|
| 2164 |
+
result = integral_steps(f, var).eval()
|
| 2165 |
+
# Clear the cache of u-parts
|
| 2166 |
+
_parts_u_cache.clear()
|
| 2167 |
+
# If we got Piecewise with two parts, put generic first
|
| 2168 |
+
if isinstance(result, Piecewise) and len(result.args) == 2:
|
| 2169 |
+
cond = result.args[0][1]
|
| 2170 |
+
if isinstance(cond, Eq) and result.args[1][1] == True:
|
| 2171 |
+
result = result.func(
|
| 2172 |
+
(result.args[1][0], Ne(*cond.args)),
|
| 2173 |
+
(result.args[0][0], True))
|
| 2174 |
+
return result
|
.venv/lib/python3.12/site-packages/sympy/integrals/meijerint.py
ADDED
|
@@ -0,0 +1,2191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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.intfunc import ilcm
|
| 43 |
+
from sympy.core.numbers import Rational, pi
|
| 44 |
+
from sympy.core.relational import Eq, Ne, _canonical_coeff
|
| 45 |
+
from sympy.core.sorting import default_sort_key, ordered
|
| 46 |
+
from sympy.core.symbol import Dummy, symbols, Wild, Symbol
|
| 47 |
+
from sympy.core.sympify import sympify
|
| 48 |
+
from sympy.functions.combinatorial.factorials import factorial
|
| 49 |
+
from sympy.functions.elementary.complexes import (re, im, arg, Abs, sign,
|
| 50 |
+
unpolarify, polarify, polar_lift, principal_branch, unbranched_argument,
|
| 51 |
+
periodic_argument)
|
| 52 |
+
from sympy.functions.elementary.exponential import exp, exp_polar, log
|
| 53 |
+
from sympy.functions.elementary.integers import ceiling
|
| 54 |
+
from sympy.functions.elementary.hyperbolic import (cosh, sinh,
|
| 55 |
+
_rewrite_hyperbolics_as_exp, HyperbolicFunction)
|
| 56 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 57 |
+
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
|
| 58 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, sinc,
|
| 59 |
+
TrigonometricFunction)
|
| 60 |
+
from sympy.functions.special.bessel import besselj, bessely, besseli, besselk
|
| 61 |
+
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
|
| 62 |
+
from sympy.functions.special.elliptic_integrals import elliptic_k, elliptic_e
|
| 63 |
+
from sympy.functions.special.error_functions import (erf, erfc, erfi, Ei,
|
| 64 |
+
expint, Si, Ci, Shi, Chi, fresnels, fresnelc)
|
| 65 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 66 |
+
from sympy.functions.special.hyper import hyper, meijerg
|
| 67 |
+
from sympy.functions.special.singularity_functions import SingularityFunction
|
| 68 |
+
from .integrals import Integral
|
| 69 |
+
from sympy.logic.boolalg import And, Or, BooleanAtom, Not, BooleanFunction
|
| 70 |
+
from sympy.polys import cancel, factor
|
| 71 |
+
from sympy.utilities.iterables import multiset_partitions
|
| 72 |
+
from sympy.utilities.misc import debug as _debug
|
| 73 |
+
from sympy.utilities.misc import debugf as _debugf
|
| 74 |
+
|
| 75 |
+
# keep this at top for easy reference
|
| 76 |
+
z = Dummy('z')
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _has(res, *f):
|
| 80 |
+
# return True if res has f; in the case of Piecewise
|
| 81 |
+
# only return True if *all* pieces have f
|
| 82 |
+
res = piecewise_fold(res)
|
| 83 |
+
if getattr(res, 'is_Piecewise', False):
|
| 84 |
+
return all(_has(i, *f) for i in res.args)
|
| 85 |
+
return res.has(*f)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _create_lookup_table(table):
|
| 89 |
+
""" Add formulae for the function -> meijerg lookup table. """
|
| 90 |
+
def wild(n):
|
| 91 |
+
return Wild(n, exclude=[z])
|
| 92 |
+
p, q, a, b, c = list(map(wild, 'pqabc'))
|
| 93 |
+
n = Wild('n', properties=[lambda x: x.is_Integer and x > 0])
|
| 94 |
+
t = p*z**q
|
| 95 |
+
|
| 96 |
+
def add(formula, an, ap, bm, bq, arg=t, fac=S.One, cond=True, hint=True):
|
| 97 |
+
table.setdefault(_mytype(formula, z), []).append((formula,
|
| 98 |
+
[(fac, meijerg(an, ap, bm, bq, arg))], cond, hint))
|
| 99 |
+
|
| 100 |
+
def addi(formula, inst, cond, hint=True):
|
| 101 |
+
table.setdefault(
|
| 102 |
+
_mytype(formula, z), []).append((formula, inst, cond, hint))
|
| 103 |
+
|
| 104 |
+
def constant(a):
|
| 105 |
+
return [(a, meijerg([1], [], [], [0], z)),
|
| 106 |
+
(a, meijerg([], [1], [0], [], z))]
|
| 107 |
+
table[()] = [(a, constant(a), True, True)]
|
| 108 |
+
|
| 109 |
+
# [P], Section 8.
|
| 110 |
+
class IsNonPositiveInteger(Function):
|
| 111 |
+
|
| 112 |
+
@classmethod
|
| 113 |
+
def eval(cls, arg):
|
| 114 |
+
arg = unpolarify(arg)
|
| 115 |
+
if arg.is_Integer is True:
|
| 116 |
+
return arg <= 0
|
| 117 |
+
|
| 118 |
+
# Section 8.4.2
|
| 119 |
+
# TODO this needs more polar_lift (c/f entry for exp)
|
| 120 |
+
add(Heaviside(t - b)*(t - b)**(a - 1), [a], [], [], [0], t/b,
|
| 121 |
+
gamma(a)*b**(a - 1), And(b > 0))
|
| 122 |
+
add(Heaviside(b - t)*(b - t)**(a - 1), [], [a], [0], [], t/b,
|
| 123 |
+
gamma(a)*b**(a - 1), And(b > 0))
|
| 124 |
+
add(Heaviside(z - (b/p)**(1/q))*(t - b)**(a - 1), [a], [], [], [0], t/b,
|
| 125 |
+
gamma(a)*b**(a - 1), And(b > 0))
|
| 126 |
+
add(Heaviside((b/p)**(1/q) - z)*(b - t)**(a - 1), [], [a], [0], [], t/b,
|
| 127 |
+
gamma(a)*b**(a - 1), And(b > 0))
|
| 128 |
+
add((b + t)**(-a), [1 - a], [], [0], [], t/b, b**(-a)/gamma(a),
|
| 129 |
+
hint=Not(IsNonPositiveInteger(a)))
|
| 130 |
+
add(Abs(b - t)**(-a), [1 - a], [(1 - a)/2], [0], [(1 - a)/2], t/b,
|
| 131 |
+
2*sin(pi*a/2)*gamma(1 - a)*Abs(b)**(-a), re(a) < 1)
|
| 132 |
+
add((t**a - b**a)/(t - b), [0, a], [], [0, a], [], t/b,
|
| 133 |
+
b**(a - 1)*sin(a*pi)/pi)
|
| 134 |
+
|
| 135 |
+
# 12
|
| 136 |
+
def A1(r, sign, nu):
|
| 137 |
+
return pi**Rational(-1, 2)*(-sign*nu/2)**(1 - 2*r)
|
| 138 |
+
|
| 139 |
+
def tmpadd(r, sgn):
|
| 140 |
+
# XXX the a**2 is bad for matching
|
| 141 |
+
add((sqrt(a**2 + t) + sgn*a)**b/(a**2 + t)**r,
|
| 142 |
+
[(1 + b)/2, 1 - 2*r + b/2], [],
|
| 143 |
+
[(b - sgn*b)/2], [(b + sgn*b)/2], t/a**2,
|
| 144 |
+
a**(b - 2*r)*A1(r, sgn, b))
|
| 145 |
+
tmpadd(0, 1)
|
| 146 |
+
tmpadd(0, -1)
|
| 147 |
+
tmpadd(S.Half, 1)
|
| 148 |
+
tmpadd(S.Half, -1)
|
| 149 |
+
|
| 150 |
+
# 13
|
| 151 |
+
def tmpadd(r, sgn):
|
| 152 |
+
add((sqrt(a + p*z**q) + sgn*sqrt(p)*z**(q/2))**b/(a + p*z**q)**r,
|
| 153 |
+
[1 - r + sgn*b/2], [1 - r - sgn*b/2], [0, S.Half], [],
|
| 154 |
+
p*z**q/a, a**(b/2 - r)*A1(r, sgn, b))
|
| 155 |
+
tmpadd(0, 1)
|
| 156 |
+
tmpadd(0, -1)
|
| 157 |
+
tmpadd(S.Half, 1)
|
| 158 |
+
tmpadd(S.Half, -1)
|
| 159 |
+
# (those after look obscure)
|
| 160 |
+
|
| 161 |
+
# Section 8.4.3
|
| 162 |
+
add(exp(polar_lift(-1)*t), [], [], [0], [])
|
| 163 |
+
|
| 164 |
+
# TODO can do sin^n, sinh^n by expansion ... where?
|
| 165 |
+
# 8.4.4 (hyperbolic functions)
|
| 166 |
+
add(sinh(t), [], [1], [S.Half], [1, 0], t**2/4, pi**Rational(3, 2))
|
| 167 |
+
add(cosh(t), [], [S.Half], [0], [S.Half, S.Half], t**2/4, pi**Rational(3, 2))
|
| 168 |
+
|
| 169 |
+
# Section 8.4.5
|
| 170 |
+
# TODO can do t + a. but can also do by expansion... (XXX not really)
|
| 171 |
+
add(sin(t), [], [], [S.Half], [0], t**2/4, sqrt(pi))
|
| 172 |
+
add(cos(t), [], [], [0], [S.Half], t**2/4, sqrt(pi))
|
| 173 |
+
|
| 174 |
+
# Section 8.4.6 (sinc function)
|
| 175 |
+
add(sinc(t), [], [], [0], [Rational(-1, 2)], t**2/4, sqrt(pi)/2)
|
| 176 |
+
|
| 177 |
+
# Section 8.5.5
|
| 178 |
+
def make_log1(subs):
|
| 179 |
+
N = subs[n]
|
| 180 |
+
return [(S.NegativeOne**N*factorial(N),
|
| 181 |
+
meijerg([], [1]*(N + 1), [0]*(N + 1), [], t))]
|
| 182 |
+
|
| 183 |
+
def make_log2(subs):
|
| 184 |
+
N = subs[n]
|
| 185 |
+
return [(factorial(N),
|
| 186 |
+
meijerg([1]*(N + 1), [], [], [0]*(N + 1), t))]
|
| 187 |
+
# TODO these only hold for positive p, and can be made more general
|
| 188 |
+
# but who uses log(x)*Heaviside(a-x) anyway ...
|
| 189 |
+
# TODO also it would be nice to derive them recursively ...
|
| 190 |
+
addi(log(t)**n*Heaviside(1 - t), make_log1, True)
|
| 191 |
+
addi(log(t)**n*Heaviside(t - 1), make_log2, True)
|
| 192 |
+
|
| 193 |
+
def make_log3(subs):
|
| 194 |
+
return make_log1(subs) + make_log2(subs)
|
| 195 |
+
addi(log(t)**n, make_log3, True)
|
| 196 |
+
addi(log(t + a),
|
| 197 |
+
constant(log(a)) + [(S.One, meijerg([1, 1], [], [1], [0], t/a))],
|
| 198 |
+
True)
|
| 199 |
+
addi(log(Abs(t - a)), constant(log(Abs(a))) +
|
| 200 |
+
[(pi, meijerg([1, 1], [S.Half], [1], [0, S.Half], t/a))],
|
| 201 |
+
True)
|
| 202 |
+
# TODO log(x)/(x+a) and log(x)/(x-1) can also be done. should they
|
| 203 |
+
# be derivable?
|
| 204 |
+
# TODO further formulae in this section seem obscure
|
| 205 |
+
|
| 206 |
+
# Sections 8.4.9-10
|
| 207 |
+
# TODO
|
| 208 |
+
|
| 209 |
+
# Section 8.4.11
|
| 210 |
+
addi(Ei(t),
|
| 211 |
+
constant(-S.ImaginaryUnit*pi) + [(S.NegativeOne, meijerg([], [1], [0, 0], [],
|
| 212 |
+
t*polar_lift(-1)))],
|
| 213 |
+
True)
|
| 214 |
+
|
| 215 |
+
# Section 8.4.12
|
| 216 |
+
add(Si(t), [1], [], [S.Half], [0, 0], t**2/4, sqrt(pi)/2)
|
| 217 |
+
add(Ci(t), [], [1], [0, 0], [S.Half], t**2/4, -sqrt(pi)/2)
|
| 218 |
+
|
| 219 |
+
# Section 8.4.13
|
| 220 |
+
add(Shi(t), [S.Half], [], [0], [Rational(-1, 2), Rational(-1, 2)], polar_lift(-1)*t**2/4,
|
| 221 |
+
t*sqrt(pi)/4)
|
| 222 |
+
add(Chi(t), [], [S.Half, 1], [0, 0], [S.Half, S.Half], t**2/4, -
|
| 223 |
+
pi**S('3/2')/2)
|
| 224 |
+
|
| 225 |
+
# generalized exponential integral
|
| 226 |
+
add(expint(a, t), [], [a], [a - 1, 0], [], t)
|
| 227 |
+
|
| 228 |
+
# Section 8.4.14
|
| 229 |
+
add(erf(t), [1], [], [S.Half], [0], t**2, 1/sqrt(pi))
|
| 230 |
+
# TODO exp(-x)*erf(I*x) does not work
|
| 231 |
+
add(erfc(t), [], [1], [0, S.Half], [], t**2, 1/sqrt(pi))
|
| 232 |
+
# This formula for erfi(z) yields a wrong(?) minus sign
|
| 233 |
+
#add(erfi(t), [1], [], [S.Half], [0], -t**2, I/sqrt(pi))
|
| 234 |
+
add(erfi(t), [S.Half], [], [0], [Rational(-1, 2)], -t**2, t/sqrt(pi))
|
| 235 |
+
|
| 236 |
+
# Fresnel Integrals
|
| 237 |
+
add(fresnels(t), [1], [], [Rational(3, 4)], [0, Rational(1, 4)], pi**2*t**4/16, S.Half)
|
| 238 |
+
add(fresnelc(t), [1], [], [Rational(1, 4)], [0, Rational(3, 4)], pi**2*t**4/16, S.Half)
|
| 239 |
+
|
| 240 |
+
##### bessel-type functions #####
|
| 241 |
+
# Section 8.4.19
|
| 242 |
+
add(besselj(a, t), [], [], [a/2], [-a/2], t**2/4)
|
| 243 |
+
|
| 244 |
+
# all of the following are derivable
|
| 245 |
+
#add(sin(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [(1+a)/2],
|
| 246 |
+
# [-a/2, a/2, (1-a)/2], t**2, 1/sqrt(2))
|
| 247 |
+
#add(cos(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [a/2],
|
| 248 |
+
# [-a/2, (1+a)/2, (1-a)/2], t**2, 1/sqrt(2))
|
| 249 |
+
#add(besselj(a, t)**2, [S.Half], [], [a], [-a, 0], t**2, 1/sqrt(pi))
|
| 250 |
+
#add(besselj(a, t)*besselj(b, t), [0, S.Half], [], [(a + b)/2],
|
| 251 |
+
# [-(a+b)/2, (a - b)/2, (b - a)/2], t**2, 1/sqrt(pi))
|
| 252 |
+
|
| 253 |
+
# Section 8.4.20
|
| 254 |
+
add(bessely(a, t), [], [-(a + 1)/2], [a/2, -a/2], [-(a + 1)/2], t**2/4)
|
| 255 |
+
|
| 256 |
+
# TODO all of the following should be derivable
|
| 257 |
+
#add(sin(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(1 - a - 1)/2],
|
| 258 |
+
# [(1 + a)/2, (1 - a)/2], [(1 - a - 1)/2, (1 - 1 - a)/2, (1 - 1 + a)/2],
|
| 259 |
+
# t**2, 1/sqrt(2))
|
| 260 |
+
#add(cos(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(0 - a - 1)/2],
|
| 261 |
+
# [(0 + a)/2, (0 - a)/2], [(0 - a - 1)/2, (1 - 0 - a)/2, (1 - 0 + a)/2],
|
| 262 |
+
# t**2, 1/sqrt(2))
|
| 263 |
+
#add(besselj(a, t)*bessely(b, t), [0, S.Half], [(a - b - 1)/2],
|
| 264 |
+
# [(a + b)/2, (a - b)/2], [(a - b - 1)/2, -(a + b)/2, (b - a)/2],
|
| 265 |
+
# t**2, 1/sqrt(pi))
|
| 266 |
+
#addi(bessely(a, t)**2,
|
| 267 |
+
# [(2/sqrt(pi), meijerg([], [S.Half, S.Half - a], [0, a, -a],
|
| 268 |
+
# [S.Half - a], t**2)),
|
| 269 |
+
# (1/sqrt(pi), meijerg([S.Half], [], [a], [-a, 0], t**2))],
|
| 270 |
+
# True)
|
| 271 |
+
#addi(bessely(a, t)*bessely(b, t),
|
| 272 |
+
# [(2/sqrt(pi), meijerg([], [0, S.Half, (1 - a - b)/2],
|
| 273 |
+
# [(a + b)/2, (a - b)/2, (b - a)/2, -(a + b)/2],
|
| 274 |
+
# [(1 - a - b)/2], t**2)),
|
| 275 |
+
# (1/sqrt(pi), meijerg([0, S.Half], [], [(a + b)/2],
|
| 276 |
+
# [-(a + b)/2, (a - b)/2, (b - a)/2], t**2))],
|
| 277 |
+
# True)
|
| 278 |
+
|
| 279 |
+
# Section 8.4.21 ?
|
| 280 |
+
# Section 8.4.22
|
| 281 |
+
add(besseli(a, t), [], [(1 + a)/2], [a/2], [-a/2, (1 + a)/2], t**2/4, pi)
|
| 282 |
+
# TODO many more formulas. should all be derivable
|
| 283 |
+
|
| 284 |
+
# Section 8.4.23
|
| 285 |
+
add(besselk(a, t), [], [], [a/2, -a/2], [], t**2/4, S.Half)
|
| 286 |
+
# TODO many more formulas. should all be derivable
|
| 287 |
+
|
| 288 |
+
# Complete elliptic integrals K(z) and E(z)
|
| 289 |
+
add(elliptic_k(t), [S.Half, S.Half], [], [0], [0], -t, S.Half)
|
| 290 |
+
add(elliptic_e(t), [S.Half, 3*S.Half], [], [0], [0], -t, Rational(-1, 2)/2)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
####################################################################
|
| 294 |
+
# First some helper functions.
|
| 295 |
+
####################################################################
|
| 296 |
+
|
| 297 |
+
from sympy.utilities.timeutils import timethis
|
| 298 |
+
timeit = timethis('meijerg')
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def _mytype(f: Basic, x: Symbol) -> tuple[type[Basic], ...]:
|
| 302 |
+
""" Create a hashable entity describing the type of f. """
|
| 303 |
+
def key(x: type[Basic]) -> tuple[int, int, str]:
|
| 304 |
+
return x.class_key()
|
| 305 |
+
|
| 306 |
+
if x not in f.free_symbols:
|
| 307 |
+
return ()
|
| 308 |
+
elif f.is_Function:
|
| 309 |
+
return type(f),
|
| 310 |
+
return tuple(sorted((t for a in f.args for t in _mytype(a, x)), key=key))
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class _CoeffExpValueError(ValueError):
|
| 314 |
+
"""
|
| 315 |
+
Exception raised by _get_coeff_exp, for internal use only.
|
| 316 |
+
"""
|
| 317 |
+
pass
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _get_coeff_exp(expr, x):
|
| 321 |
+
"""
|
| 322 |
+
When expr is known to be of the form c*x**b, with c and/or b possibly 1,
|
| 323 |
+
return c, b.
|
| 324 |
+
|
| 325 |
+
Examples
|
| 326 |
+
========
|
| 327 |
+
|
| 328 |
+
>>> from sympy.abc import x, a, b
|
| 329 |
+
>>> from sympy.integrals.meijerint import _get_coeff_exp
|
| 330 |
+
>>> _get_coeff_exp(a*x**b, x)
|
| 331 |
+
(a, b)
|
| 332 |
+
>>> _get_coeff_exp(x, x)
|
| 333 |
+
(1, 1)
|
| 334 |
+
>>> _get_coeff_exp(2*x, x)
|
| 335 |
+
(2, 1)
|
| 336 |
+
>>> _get_coeff_exp(x**3, x)
|
| 337 |
+
(1, 3)
|
| 338 |
+
"""
|
| 339 |
+
from sympy.simplify import powsimp
|
| 340 |
+
(c, m) = expand_power_base(powsimp(expr)).as_coeff_mul(x)
|
| 341 |
+
if not m:
|
| 342 |
+
return c, S.Zero
|
| 343 |
+
[m] = m
|
| 344 |
+
if m.is_Pow:
|
| 345 |
+
if m.base != x:
|
| 346 |
+
raise _CoeffExpValueError('expr not of form a*x**b')
|
| 347 |
+
return c, m.exp
|
| 348 |
+
elif m == x:
|
| 349 |
+
return c, S.One
|
| 350 |
+
else:
|
| 351 |
+
raise _CoeffExpValueError('expr not of form a*x**b: %s' % expr)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _exponents(expr, x):
|
| 355 |
+
"""
|
| 356 |
+
Find the exponents of ``x`` (not including zero) in ``expr``.
|
| 357 |
+
|
| 358 |
+
Examples
|
| 359 |
+
========
|
| 360 |
+
|
| 361 |
+
>>> from sympy.integrals.meijerint import _exponents
|
| 362 |
+
>>> from sympy.abc import x, y
|
| 363 |
+
>>> from sympy import sin
|
| 364 |
+
>>> _exponents(x, x)
|
| 365 |
+
{1}
|
| 366 |
+
>>> _exponents(x**2, x)
|
| 367 |
+
{2}
|
| 368 |
+
>>> _exponents(x**2 + x, x)
|
| 369 |
+
{1, 2}
|
| 370 |
+
>>> _exponents(x**3*sin(x + x**y) + 1/x, x)
|
| 371 |
+
{-1, 1, 3, y}
|
| 372 |
+
"""
|
| 373 |
+
def _exponents_(expr, x, res):
|
| 374 |
+
if expr == x:
|
| 375 |
+
res.update([1])
|
| 376 |
+
return
|
| 377 |
+
if expr.is_Pow and expr.base == x:
|
| 378 |
+
res.update([expr.exp])
|
| 379 |
+
return
|
| 380 |
+
for argument in expr.args:
|
| 381 |
+
_exponents_(argument, x, res)
|
| 382 |
+
res = set()
|
| 383 |
+
_exponents_(expr, x, res)
|
| 384 |
+
return res
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def _functions(expr, x):
|
| 388 |
+
""" Find the types of functions in expr, to estimate the complexity. """
|
| 389 |
+
return {e.func for e in expr.atoms(Function) if x in e.free_symbols}
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def _find_splitting_points(expr, x):
|
| 393 |
+
"""
|
| 394 |
+
Find numbers a such that a linear substitution x -> x + a would
|
| 395 |
+
(hopefully) simplify expr.
|
| 396 |
+
|
| 397 |
+
Examples
|
| 398 |
+
========
|
| 399 |
+
|
| 400 |
+
>>> from sympy.integrals.meijerint import _find_splitting_points as fsp
|
| 401 |
+
>>> from sympy import sin
|
| 402 |
+
>>> from sympy.abc import x
|
| 403 |
+
>>> fsp(x, x)
|
| 404 |
+
{0}
|
| 405 |
+
>>> fsp((x-1)**3, x)
|
| 406 |
+
{1}
|
| 407 |
+
>>> fsp(sin(x+3)*x, x)
|
| 408 |
+
{-3, 0}
|
| 409 |
+
"""
|
| 410 |
+
p, q = [Wild(n, exclude=[x]) for n in 'pq']
|
| 411 |
+
|
| 412 |
+
def compute_innermost(expr, res):
|
| 413 |
+
if not isinstance(expr, Expr):
|
| 414 |
+
return
|
| 415 |
+
m = expr.match(p*x + q)
|
| 416 |
+
if m and m[p] != 0:
|
| 417 |
+
res.add(-m[q]/m[p])
|
| 418 |
+
return
|
| 419 |
+
if expr.is_Atom:
|
| 420 |
+
return
|
| 421 |
+
for argument in expr.args:
|
| 422 |
+
compute_innermost(argument, res)
|
| 423 |
+
innermost = set()
|
| 424 |
+
compute_innermost(expr, innermost)
|
| 425 |
+
return innermost
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def _split_mul(f, x):
|
| 429 |
+
"""
|
| 430 |
+
Split expression ``f`` into fac, po, g, where fac is a constant factor,
|
| 431 |
+
po = x**s for some s independent of s, and g is "the rest".
|
| 432 |
+
|
| 433 |
+
Examples
|
| 434 |
+
========
|
| 435 |
+
|
| 436 |
+
>>> from sympy.integrals.meijerint import _split_mul
|
| 437 |
+
>>> from sympy import sin
|
| 438 |
+
>>> from sympy.abc import s, x
|
| 439 |
+
>>> _split_mul((3*x)**s*sin(x**2)*x, x)
|
| 440 |
+
(3**s, x*x**s, sin(x**2))
|
| 441 |
+
"""
|
| 442 |
+
fac = S.One
|
| 443 |
+
po = S.One
|
| 444 |
+
g = S.One
|
| 445 |
+
f = expand_power_base(f)
|
| 446 |
+
|
| 447 |
+
args = Mul.make_args(f)
|
| 448 |
+
for a in args:
|
| 449 |
+
if a == x:
|
| 450 |
+
po *= x
|
| 451 |
+
elif x not in a.free_symbols:
|
| 452 |
+
fac *= a
|
| 453 |
+
else:
|
| 454 |
+
if a.is_Pow and x not in a.exp.free_symbols:
|
| 455 |
+
c, t = a.base.as_coeff_mul(x)
|
| 456 |
+
if t != (x,):
|
| 457 |
+
c, t = expand_mul(a.base).as_coeff_mul(x)
|
| 458 |
+
if t == (x,):
|
| 459 |
+
po *= x**a.exp
|
| 460 |
+
fac *= unpolarify(polarify(c**a.exp, subs=False))
|
| 461 |
+
continue
|
| 462 |
+
g *= a
|
| 463 |
+
|
| 464 |
+
return fac, po, g
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def _mul_args(f):
|
| 468 |
+
"""
|
| 469 |
+
Return a list ``L`` such that ``Mul(*L) == f``.
|
| 470 |
+
|
| 471 |
+
If ``f`` is not a ``Mul`` or ``Pow``, ``L=[f]``.
|
| 472 |
+
If ``f=g**n`` for an integer ``n``, ``L=[g]*n``.
|
| 473 |
+
If ``f`` is a ``Mul``, ``L`` comes from applying ``_mul_args`` to all factors of ``f``.
|
| 474 |
+
"""
|
| 475 |
+
args = Mul.make_args(f)
|
| 476 |
+
gs = []
|
| 477 |
+
for g in args:
|
| 478 |
+
if g.is_Pow and g.exp.is_Integer:
|
| 479 |
+
n = g.exp
|
| 480 |
+
base = g.base
|
| 481 |
+
if n < 0:
|
| 482 |
+
n = -n
|
| 483 |
+
base = 1/base
|
| 484 |
+
gs += [base]*n
|
| 485 |
+
else:
|
| 486 |
+
gs.append(g)
|
| 487 |
+
return gs
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def _mul_as_two_parts(f):
|
| 491 |
+
"""
|
| 492 |
+
Find all the ways to split ``f`` into a product of two terms.
|
| 493 |
+
Return None on failure.
|
| 494 |
+
|
| 495 |
+
Explanation
|
| 496 |
+
===========
|
| 497 |
+
|
| 498 |
+
Although the order is canonical from multiset_partitions, this is
|
| 499 |
+
not necessarily the best order to process the terms. For example,
|
| 500 |
+
if the case of len(gs) == 2 is removed and multiset is allowed to
|
| 501 |
+
sort the terms, some tests fail.
|
| 502 |
+
|
| 503 |
+
Examples
|
| 504 |
+
========
|
| 505 |
+
|
| 506 |
+
>>> from sympy.integrals.meijerint import _mul_as_two_parts
|
| 507 |
+
>>> from sympy import sin, exp, ordered
|
| 508 |
+
>>> from sympy.abc import x
|
| 509 |
+
>>> list(ordered(_mul_as_two_parts(x*sin(x)*exp(x))))
|
| 510 |
+
[(x, exp(x)*sin(x)), (x*exp(x), sin(x)), (x*sin(x), exp(x))]
|
| 511 |
+
"""
|
| 512 |
+
|
| 513 |
+
gs = _mul_args(f)
|
| 514 |
+
if len(gs) < 2:
|
| 515 |
+
return None
|
| 516 |
+
if len(gs) == 2:
|
| 517 |
+
return [tuple(gs)]
|
| 518 |
+
return [(Mul(*x), Mul(*y)) for (x, y) in multiset_partitions(gs, 2)]
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def _inflate_g(g, n):
|
| 522 |
+
""" Return C, h such that h is a G function of argument z**n and
|
| 523 |
+
g = C*h. """
|
| 524 |
+
# TODO should this be a method of meijerg?
|
| 525 |
+
# See: [L, page 150, equation (5)]
|
| 526 |
+
def inflate(params, n):
|
| 527 |
+
""" (a1, .., ak) -> (a1/n, (a1+1)/n, ..., (ak + n-1)/n) """
|
| 528 |
+
return [(a + i)/n for a, i in itertools.product(params, range(n))]
|
| 529 |
+
v = S(len(g.ap) - len(g.bq))
|
| 530 |
+
C = n**(1 + g.nu + v/2)
|
| 531 |
+
C /= (2*pi)**((n - 1)*g.delta)
|
| 532 |
+
return C, meijerg(inflate(g.an, n), inflate(g.aother, n),
|
| 533 |
+
inflate(g.bm, n), inflate(g.bother, n),
|
| 534 |
+
g.argument**n * n**(n*v))
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _flip_g(g):
|
| 538 |
+
""" Turn the G function into one of inverse argument
|
| 539 |
+
(i.e. G(1/x) -> G'(x)) """
|
| 540 |
+
# See [L], section 5.2
|
| 541 |
+
def tr(l):
|
| 542 |
+
return [1 - a for a in l]
|
| 543 |
+
return meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), 1/g.argument)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def _inflate_fox_h(g, a):
|
| 547 |
+
r"""
|
| 548 |
+
Let d denote the integrand in the definition of the G function ``g``.
|
| 549 |
+
Consider the function H which is defined in the same way, but with
|
| 550 |
+
integrand d/Gamma(a*s) (contour conventions as usual).
|
| 551 |
+
|
| 552 |
+
If ``a`` is rational, the function H can be written as C*G, for a constant C
|
| 553 |
+
and a G-function G.
|
| 554 |
+
|
| 555 |
+
This function returns C, G.
|
| 556 |
+
"""
|
| 557 |
+
if a < 0:
|
| 558 |
+
return _inflate_fox_h(_flip_g(g), -a)
|
| 559 |
+
p = S(a.p)
|
| 560 |
+
q = S(a.q)
|
| 561 |
+
# We use the substitution s->qs, i.e. inflate g by q. We are left with an
|
| 562 |
+
# extra factor of Gamma(p*s), for which we use Gauss' multiplication
|
| 563 |
+
# theorem.
|
| 564 |
+
D, g = _inflate_g(g, q)
|
| 565 |
+
z = g.argument
|
| 566 |
+
D /= (2*pi)**((1 - p)/2)*p**Rational(-1, 2)
|
| 567 |
+
z /= p**p
|
| 568 |
+
bs = [(n + 1)/p for n in range(p)]
|
| 569 |
+
return D, meijerg(g.an, g.aother, g.bm, list(g.bother) + bs, z)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
_dummies: dict[tuple[str, str], Dummy] = {}
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def _dummy(name, token, expr, **kwargs):
|
| 576 |
+
"""
|
| 577 |
+
Return a dummy. This will return the same dummy if the same token+name is
|
| 578 |
+
requested more than once, and it is not already in expr.
|
| 579 |
+
This is for being cache-friendly.
|
| 580 |
+
"""
|
| 581 |
+
d = _dummy_(name, token, **kwargs)
|
| 582 |
+
if d in expr.free_symbols:
|
| 583 |
+
return Dummy(name, **kwargs)
|
| 584 |
+
return d
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def _dummy_(name, token, **kwargs):
|
| 588 |
+
"""
|
| 589 |
+
Return a dummy associated to name and token. Same effect as declaring
|
| 590 |
+
it globally.
|
| 591 |
+
"""
|
| 592 |
+
if not (name, token) in _dummies:
|
| 593 |
+
_dummies[(name, token)] = Dummy(name, **kwargs)
|
| 594 |
+
return _dummies[(name, token)]
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def _is_analytic(f, x):
|
| 598 |
+
""" Check if f(x), when expressed using G functions on the positive reals,
|
| 599 |
+
will in fact agree with the G functions almost everywhere """
|
| 600 |
+
return not any(x in expr.free_symbols for expr in f.atoms(Heaviside, Abs))
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def _condsimp(cond, first=True):
|
| 604 |
+
"""
|
| 605 |
+
Do naive simplifications on ``cond``.
|
| 606 |
+
|
| 607 |
+
Explanation
|
| 608 |
+
===========
|
| 609 |
+
|
| 610 |
+
Note that this routine is completely ad-hoc, simplification rules being
|
| 611 |
+
added as need arises rather than following any logical pattern.
|
| 612 |
+
|
| 613 |
+
Examples
|
| 614 |
+
========
|
| 615 |
+
|
| 616 |
+
>>> from sympy.integrals.meijerint import _condsimp as simp
|
| 617 |
+
>>> from sympy import Or, Eq
|
| 618 |
+
>>> from sympy.abc import x, y
|
| 619 |
+
>>> simp(Or(x < y, Eq(x, y)))
|
| 620 |
+
x <= y
|
| 621 |
+
"""
|
| 622 |
+
if first:
|
| 623 |
+
cond = cond.replace(lambda _: _.is_Relational, _canonical_coeff)
|
| 624 |
+
first = False
|
| 625 |
+
if not isinstance(cond, BooleanFunction):
|
| 626 |
+
return cond
|
| 627 |
+
p, q, r = symbols('p q r', cls=Wild)
|
| 628 |
+
# transforms tests use 0, 4, 5 and 11-14
|
| 629 |
+
# meijer tests use 0, 2, 11, 14
|
| 630 |
+
# joint_rv uses 6, 7
|
| 631 |
+
rules = [
|
| 632 |
+
(Or(p < q, Eq(p, q)), p <= q), # 0
|
| 633 |
+
# The next two obviously are instances of a general pattern, but it is
|
| 634 |
+
# easier to spell out the few cases we care about.
|
| 635 |
+
(And(Abs(arg(p)) <= pi, Abs(arg(p) - 2*pi) <= pi),
|
| 636 |
+
Eq(arg(p) - pi, 0)), # 1
|
| 637 |
+
(And(Abs(2*arg(p) + pi) <= pi, Abs(2*arg(p) - pi) <= pi),
|
| 638 |
+
Eq(arg(p), 0)), # 2
|
| 639 |
+
(And(Abs(2*arg(p) + pi) < pi, Abs(2*arg(p) - pi) <= pi),
|
| 640 |
+
S.false), # 3
|
| 641 |
+
(And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) <= pi/2),
|
| 642 |
+
Eq(arg(p), 0)), # 4
|
| 643 |
+
(And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) < pi/2),
|
| 644 |
+
S.false), # 5
|
| 645 |
+
(And(Abs(arg(p**2/2 + 1)) < pi, Ne(Abs(arg(p**2/2 + 1)), pi)),
|
| 646 |
+
S.true), # 6
|
| 647 |
+
(Or(Abs(arg(p**2/2 + 1)) < pi, Ne(1/(p**2/2 + 1), 0)),
|
| 648 |
+
S.true), # 7
|
| 649 |
+
(And(Abs(unbranched_argument(p)) <= pi,
|
| 650 |
+
Abs(unbranched_argument(exp_polar(-2*pi*S.ImaginaryUnit)*p)) <= pi),
|
| 651 |
+
Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi)*p), 0)), # 8
|
| 652 |
+
(And(Abs(unbranched_argument(p)) <= pi/2,
|
| 653 |
+
Abs(unbranched_argument(exp_polar(-pi*S.ImaginaryUnit)*p)) <= pi/2),
|
| 654 |
+
Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi/2)*p), 0)), # 9
|
| 655 |
+
(Or(p <= q, And(p < q, r)), p <= q), # 10
|
| 656 |
+
(Ne(p**2, 1) & (p**2 > 1), p**2 > 1), # 11
|
| 657 |
+
(Ne(1/p, 1) & (cos(Abs(arg(p)))*Abs(p) > 1), Abs(p) > 1), # 12
|
| 658 |
+
(Ne(p, 2) & (cos(Abs(arg(p)))*Abs(p) > 2), Abs(p) > 2), # 13
|
| 659 |
+
((Abs(arg(p)) < pi/2) & (cos(Abs(arg(p)))*sqrt(Abs(p**2)) > 1), p**2 > 1), # 14
|
| 660 |
+
]
|
| 661 |
+
cond = cond.func(*[_condsimp(_, first) for _ in cond.args])
|
| 662 |
+
change = True
|
| 663 |
+
while change:
|
| 664 |
+
change = False
|
| 665 |
+
for irule, (fro, to) in enumerate(rules):
|
| 666 |
+
if fro.func != cond.func:
|
| 667 |
+
continue
|
| 668 |
+
for n, arg1 in enumerate(cond.args):
|
| 669 |
+
if r in fro.args[0].free_symbols:
|
| 670 |
+
m = arg1.match(fro.args[1])
|
| 671 |
+
num = 1
|
| 672 |
+
else:
|
| 673 |
+
num = 0
|
| 674 |
+
m = arg1.match(fro.args[0])
|
| 675 |
+
if not m:
|
| 676 |
+
continue
|
| 677 |
+
otherargs = [x.subs(m) for x in fro.args[:num] + fro.args[num + 1:]]
|
| 678 |
+
otherlist = [n]
|
| 679 |
+
for arg2 in otherargs:
|
| 680 |
+
for k, arg3 in enumerate(cond.args):
|
| 681 |
+
if k in otherlist:
|
| 682 |
+
continue
|
| 683 |
+
if arg2 == arg3:
|
| 684 |
+
otherlist += [k]
|
| 685 |
+
break
|
| 686 |
+
if isinstance(arg3, And) and arg2.args[1] == r and \
|
| 687 |
+
isinstance(arg2, And) and arg2.args[0] in arg3.args:
|
| 688 |
+
otherlist += [k]
|
| 689 |
+
break
|
| 690 |
+
if isinstance(arg3, And) and arg2.args[0] == r and \
|
| 691 |
+
isinstance(arg2, And) and arg2.args[1] in arg3.args:
|
| 692 |
+
otherlist += [k]
|
| 693 |
+
break
|
| 694 |
+
if len(otherlist) != len(otherargs) + 1:
|
| 695 |
+
continue
|
| 696 |
+
newargs = [arg_ for (k, arg_) in enumerate(cond.args)
|
| 697 |
+
if k not in otherlist] + [to.subs(m)]
|
| 698 |
+
if SYMPY_DEBUG:
|
| 699 |
+
if irule not in (0, 2, 4, 5, 6, 7, 11, 12, 13, 14):
|
| 700 |
+
print('used new rule:', irule)
|
| 701 |
+
cond = cond.func(*newargs)
|
| 702 |
+
change = True
|
| 703 |
+
break
|
| 704 |
+
|
| 705 |
+
# final tweak
|
| 706 |
+
def rel_touchup(rel):
|
| 707 |
+
if rel.rel_op != '==' or rel.rhs != 0:
|
| 708 |
+
return rel
|
| 709 |
+
|
| 710 |
+
# handle Eq(*, 0)
|
| 711 |
+
LHS = rel.lhs
|
| 712 |
+
m = LHS.match(arg(p)**q)
|
| 713 |
+
if not m:
|
| 714 |
+
m = LHS.match(unbranched_argument(polar_lift(p)**q))
|
| 715 |
+
if not m:
|
| 716 |
+
if isinstance(LHS, periodic_argument) and not LHS.args[0].is_polar \
|
| 717 |
+
and LHS.args[1] is S.Infinity:
|
| 718 |
+
return (LHS.args[0] > 0)
|
| 719 |
+
return rel
|
| 720 |
+
return (m[p] > 0)
|
| 721 |
+
cond = cond.replace(lambda _: _.is_Relational, rel_touchup)
|
| 722 |
+
if SYMPY_DEBUG:
|
| 723 |
+
print('_condsimp: ', cond)
|
| 724 |
+
return cond
|
| 725 |
+
|
| 726 |
+
def _eval_cond(cond):
|
| 727 |
+
""" Re-evaluate the conditions. """
|
| 728 |
+
if isinstance(cond, bool):
|
| 729 |
+
return cond
|
| 730 |
+
return _condsimp(cond.doit())
|
| 731 |
+
|
| 732 |
+
####################################################################
|
| 733 |
+
# Now the "backbone" functions to do actual integration.
|
| 734 |
+
####################################################################
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def _my_principal_branch(expr, period, full_pb=False):
|
| 738 |
+
""" Bring expr nearer to its principal branch by removing superfluous
|
| 739 |
+
factors.
|
| 740 |
+
This function does *not* guarantee to yield the principal branch,
|
| 741 |
+
to avoid introducing opaque principal_branch() objects,
|
| 742 |
+
unless full_pb=True. """
|
| 743 |
+
res = principal_branch(expr, period)
|
| 744 |
+
if not full_pb:
|
| 745 |
+
res = res.replace(principal_branch, lambda x, y: x)
|
| 746 |
+
return res
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def _rewrite_saxena_1(fac, po, g, x):
|
| 750 |
+
"""
|
| 751 |
+
Rewrite the integral fac*po*g dx, from zero to infinity, as
|
| 752 |
+
integral fac*G, where G has argument a*x. Note po=x**s.
|
| 753 |
+
Return fac, G.
|
| 754 |
+
"""
|
| 755 |
+
_, s = _get_coeff_exp(po, x)
|
| 756 |
+
a, b = _get_coeff_exp(g.argument, x)
|
| 757 |
+
period = g.get_period()
|
| 758 |
+
a = _my_principal_branch(a, period)
|
| 759 |
+
|
| 760 |
+
# We substitute t = x**b.
|
| 761 |
+
C = fac/(Abs(b)*a**((s + 1)/b - 1))
|
| 762 |
+
# Absorb a factor of (at)**((1 + s)/b - 1).
|
| 763 |
+
|
| 764 |
+
def tr(l):
|
| 765 |
+
return [a + (1 + s)/b - 1 for a in l]
|
| 766 |
+
return C, meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother),
|
| 767 |
+
a*x)
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def _check_antecedents_1(g, x, helper=False):
|
| 771 |
+
r"""
|
| 772 |
+
Return a condition under which the mellin transform of g exists.
|
| 773 |
+
Any power of x has already been absorbed into the G function,
|
| 774 |
+
so this is just $\int_0^\infty g\, dx$.
|
| 775 |
+
|
| 776 |
+
See [L, section 5.6.1]. (Note that s=1.)
|
| 777 |
+
|
| 778 |
+
If ``helper`` is True, only check if the MT exists at infinity, i.e. if
|
| 779 |
+
$\int_1^\infty g\, dx$ exists.
|
| 780 |
+
"""
|
| 781 |
+
# NOTE if you update these conditions, please update the documentation as well
|
| 782 |
+
delta = g.delta
|
| 783 |
+
eta, _ = _get_coeff_exp(g.argument, x)
|
| 784 |
+
m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)])
|
| 785 |
+
|
| 786 |
+
if p > q:
|
| 787 |
+
def tr(l):
|
| 788 |
+
return [1 - x for x in l]
|
| 789 |
+
return _check_antecedents_1(meijerg(tr(g.bm), tr(g.bother),
|
| 790 |
+
tr(g.an), tr(g.aother), x/eta),
|
| 791 |
+
x)
|
| 792 |
+
|
| 793 |
+
tmp = [-re(b) < 1 for b in g.bm] + [1 < 1 - re(a) for a in g.an]
|
| 794 |
+
cond_3 = And(*tmp)
|
| 795 |
+
|
| 796 |
+
tmp += [-re(b) < 1 for b in g.bother]
|
| 797 |
+
tmp += [1 < 1 - re(a) for a in g.aother]
|
| 798 |
+
cond_3_star = And(*tmp)
|
| 799 |
+
|
| 800 |
+
cond_4 = (-re(g.nu) + (q + 1 - p)/2 > q - p)
|
| 801 |
+
|
| 802 |
+
def debug(*msg):
|
| 803 |
+
_debug(*msg)
|
| 804 |
+
|
| 805 |
+
def debugf(string, arg):
|
| 806 |
+
_debugf(string, arg)
|
| 807 |
+
|
| 808 |
+
debug('Checking antecedents for 1 function:')
|
| 809 |
+
debugf(' delta=%s, eta=%s, m=%s, n=%s, p=%s, q=%s',
|
| 810 |
+
(delta, eta, m, n, p, q))
|
| 811 |
+
debugf(' ap = %s, %s', (list(g.an), list(g.aother)))
|
| 812 |
+
debugf(' bq = %s, %s', (list(g.bm), list(g.bother)))
|
| 813 |
+
debugf(' cond_3=%s, cond_3*=%s, cond_4=%s', (cond_3, cond_3_star, cond_4))
|
| 814 |
+
|
| 815 |
+
conds = []
|
| 816 |
+
|
| 817 |
+
# case 1
|
| 818 |
+
case1 = []
|
| 819 |
+
tmp1 = [1 <= n, p < q, 1 <= m]
|
| 820 |
+
tmp2 = [1 <= p, 1 <= m, Eq(q, p + 1), Not(And(Eq(n, 0), Eq(m, p + 1)))]
|
| 821 |
+
tmp3 = [1 <= p, Eq(q, p)]
|
| 822 |
+
for k in range(ceiling(delta/2) + 1):
|
| 823 |
+
tmp3 += [Ne(Abs(unbranched_argument(eta)), (delta - 2*k)*pi)]
|
| 824 |
+
tmp = [delta > 0, Abs(unbranched_argument(eta)) < delta*pi]
|
| 825 |
+
extra = [Ne(eta, 0), cond_3]
|
| 826 |
+
if helper:
|
| 827 |
+
extra = []
|
| 828 |
+
for t in [tmp1, tmp2, tmp3]:
|
| 829 |
+
case1 += [And(*(t + tmp + extra))]
|
| 830 |
+
conds += case1
|
| 831 |
+
debug(' case 1:', case1)
|
| 832 |
+
|
| 833 |
+
# case 2
|
| 834 |
+
extra = [cond_3]
|
| 835 |
+
if helper:
|
| 836 |
+
extra = []
|
| 837 |
+
case2 = [And(Eq(n, 0), p + 1 <= m, m <= q,
|
| 838 |
+
Abs(unbranched_argument(eta)) < delta*pi, *extra)]
|
| 839 |
+
conds += case2
|
| 840 |
+
debug(' case 2:', case2)
|
| 841 |
+
|
| 842 |
+
# case 3
|
| 843 |
+
extra = [cond_3, cond_4]
|
| 844 |
+
if helper:
|
| 845 |
+
extra = []
|
| 846 |
+
case3 = [And(p < q, 1 <= m, delta > 0, Eq(Abs(unbranched_argument(eta)), delta*pi),
|
| 847 |
+
*extra)]
|
| 848 |
+
case3 += [And(p <= q - 2, Eq(delta, 0), Eq(Abs(unbranched_argument(eta)), 0), *extra)]
|
| 849 |
+
conds += case3
|
| 850 |
+
debug(' case 3:', case3)
|
| 851 |
+
|
| 852 |
+
# TODO altered cases 4-7
|
| 853 |
+
|
| 854 |
+
# extra case from wofram functions site:
|
| 855 |
+
# (reproduced verbatim from Prudnikov, section 2.24.2)
|
| 856 |
+
# https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/01/
|
| 857 |
+
case_extra = []
|
| 858 |
+
case_extra += [Eq(p, q), Eq(delta, 0), Eq(unbranched_argument(eta), 0), Ne(eta, 0)]
|
| 859 |
+
if not helper:
|
| 860 |
+
case_extra += [cond_3]
|
| 861 |
+
s = []
|
| 862 |
+
for a, b in zip(g.ap, g.bq):
|
| 863 |
+
s += [b - a]
|
| 864 |
+
case_extra += [re(Add(*s)) < 0]
|
| 865 |
+
case_extra = And(*case_extra)
|
| 866 |
+
conds += [case_extra]
|
| 867 |
+
debug(' extra case:', [case_extra])
|
| 868 |
+
|
| 869 |
+
case_extra_2 = [And(delta > 0, Abs(unbranched_argument(eta)) < delta*pi)]
|
| 870 |
+
if not helper:
|
| 871 |
+
case_extra_2 += [cond_3]
|
| 872 |
+
case_extra_2 = And(*case_extra_2)
|
| 873 |
+
conds += [case_extra_2]
|
| 874 |
+
debug(' second extra case:', [case_extra_2])
|
| 875 |
+
|
| 876 |
+
# TODO This leaves only one case from the three listed by Prudnikov.
|
| 877 |
+
# Investigate if these indeed cover everything; if so, remove the rest.
|
| 878 |
+
|
| 879 |
+
return Or(*conds)
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
def _int0oo_1(g, x):
|
| 883 |
+
r"""
|
| 884 |
+
Evaluate $\int_0^\infty g\, dx$ using G functions,
|
| 885 |
+
assuming the necessary conditions are fulfilled.
|
| 886 |
+
|
| 887 |
+
Examples
|
| 888 |
+
========
|
| 889 |
+
|
| 890 |
+
>>> from sympy.abc import a, b, c, d, x, y
|
| 891 |
+
>>> from sympy import meijerg
|
| 892 |
+
>>> from sympy.integrals.meijerint import _int0oo_1
|
| 893 |
+
>>> _int0oo_1(meijerg([a], [b], [c], [d], x*y), x)
|
| 894 |
+
gamma(-a)*gamma(c + 1)/(y*gamma(-d)*gamma(b + 1))
|
| 895 |
+
"""
|
| 896 |
+
from sympy.simplify import gammasimp
|
| 897 |
+
# See [L, section 5.6.1]. Note that s=1.
|
| 898 |
+
eta, _ = _get_coeff_exp(g.argument, x)
|
| 899 |
+
res = 1/eta
|
| 900 |
+
# XXX TODO we should reduce order first
|
| 901 |
+
for b in g.bm:
|
| 902 |
+
res *= gamma(b + 1)
|
| 903 |
+
for a in g.an:
|
| 904 |
+
res *= gamma(1 - a - 1)
|
| 905 |
+
for b in g.bother:
|
| 906 |
+
res /= gamma(1 - b - 1)
|
| 907 |
+
for a in g.aother:
|
| 908 |
+
res /= gamma(a + 1)
|
| 909 |
+
return gammasimp(unpolarify(res))
|
| 910 |
+
|
| 911 |
+
|
| 912 |
+
def _rewrite_saxena(fac, po, g1, g2, x, full_pb=False):
|
| 913 |
+
"""
|
| 914 |
+
Rewrite the integral ``fac*po*g1*g2`` from 0 to oo in terms of G
|
| 915 |
+
functions with argument ``c*x``.
|
| 916 |
+
|
| 917 |
+
Explanation
|
| 918 |
+
===========
|
| 919 |
+
|
| 920 |
+
Return C, f1, f2 such that integral C f1 f2 from 0 to infinity equals
|
| 921 |
+
integral fac ``po``, ``g1``, ``g2`` from 0 to infinity.
|
| 922 |
+
|
| 923 |
+
Examples
|
| 924 |
+
========
|
| 925 |
+
|
| 926 |
+
>>> from sympy.integrals.meijerint import _rewrite_saxena
|
| 927 |
+
>>> from sympy.abc import s, t, m
|
| 928 |
+
>>> from sympy import meijerg
|
| 929 |
+
>>> g1 = meijerg([], [], [0], [], s*t)
|
| 930 |
+
>>> g2 = meijerg([], [], [m/2], [-m/2], t**2/4)
|
| 931 |
+
>>> r = _rewrite_saxena(1, t**0, g1, g2, t)
|
| 932 |
+
>>> r[0]
|
| 933 |
+
s/(4*sqrt(pi))
|
| 934 |
+
>>> r[1]
|
| 935 |
+
meijerg(((), ()), ((-1/2, 0), ()), s**2*t/4)
|
| 936 |
+
>>> r[2]
|
| 937 |
+
meijerg(((), ()), ((m/2,), (-m/2,)), t/4)
|
| 938 |
+
"""
|
| 939 |
+
def pb(g):
|
| 940 |
+
a, b = _get_coeff_exp(g.argument, x)
|
| 941 |
+
per = g.get_period()
|
| 942 |
+
return meijerg(g.an, g.aother, g.bm, g.bother,
|
| 943 |
+
_my_principal_branch(a, per, full_pb)*x**b)
|
| 944 |
+
|
| 945 |
+
_, s = _get_coeff_exp(po, x)
|
| 946 |
+
_, b1 = _get_coeff_exp(g1.argument, x)
|
| 947 |
+
_, b2 = _get_coeff_exp(g2.argument, x)
|
| 948 |
+
if (b1 < 0) == True:
|
| 949 |
+
b1 = -b1
|
| 950 |
+
g1 = _flip_g(g1)
|
| 951 |
+
if (b2 < 0) == True:
|
| 952 |
+
b2 = -b2
|
| 953 |
+
g2 = _flip_g(g2)
|
| 954 |
+
if not b1.is_Rational or not b2.is_Rational:
|
| 955 |
+
return
|
| 956 |
+
m1, n1 = b1.p, b1.q
|
| 957 |
+
m2, n2 = b2.p, b2.q
|
| 958 |
+
tau = ilcm(m1*n2, m2*n1)
|
| 959 |
+
r1 = tau//(m1*n2)
|
| 960 |
+
r2 = tau//(m2*n1)
|
| 961 |
+
|
| 962 |
+
C1, g1 = _inflate_g(g1, r1)
|
| 963 |
+
C2, g2 = _inflate_g(g2, r2)
|
| 964 |
+
g1 = pb(g1)
|
| 965 |
+
g2 = pb(g2)
|
| 966 |
+
|
| 967 |
+
fac *= C1*C2
|
| 968 |
+
a1, b = _get_coeff_exp(g1.argument, x)
|
| 969 |
+
a2, _ = _get_coeff_exp(g2.argument, x)
|
| 970 |
+
|
| 971 |
+
# arbitrarily tack on the x**s part to g1
|
| 972 |
+
# TODO should we try both?
|
| 973 |
+
exp = (s + 1)/b - 1
|
| 974 |
+
fac = fac/(Abs(b) * a1**exp)
|
| 975 |
+
|
| 976 |
+
def tr(l):
|
| 977 |
+
return [a + exp for a in l]
|
| 978 |
+
g1 = meijerg(tr(g1.an), tr(g1.aother), tr(g1.bm), tr(g1.bother), a1*x)
|
| 979 |
+
g2 = meijerg(g2.an, g2.aother, g2.bm, g2.bother, a2*x)
|
| 980 |
+
|
| 981 |
+
from sympy.simplify import powdenest
|
| 982 |
+
return powdenest(fac, polar=True), g1, g2
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
def _check_antecedents(g1, g2, x):
|
| 986 |
+
""" Return a condition under which the integral theorem applies. """
|
| 987 |
+
# Yes, this is madness.
|
| 988 |
+
# XXX TODO this is a testing *nightmare*
|
| 989 |
+
# NOTE if you update these conditions, please update the documentation as well
|
| 990 |
+
|
| 991 |
+
# The following conditions are found in
|
| 992 |
+
# [P], Section 2.24.1
|
| 993 |
+
#
|
| 994 |
+
# They are also reproduced (verbatim!) at
|
| 995 |
+
# https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/
|
| 996 |
+
#
|
| 997 |
+
# Note: k=l=r=alpha=1
|
| 998 |
+
sigma, _ = _get_coeff_exp(g1.argument, x)
|
| 999 |
+
omega, _ = _get_coeff_exp(g2.argument, x)
|
| 1000 |
+
s, t, u, v = S([len(g1.bm), len(g1.an), len(g1.ap), len(g1.bq)])
|
| 1001 |
+
m, n, p, q = S([len(g2.bm), len(g2.an), len(g2.ap), len(g2.bq)])
|
| 1002 |
+
bstar = s + t - (u + v)/2
|
| 1003 |
+
cstar = m + n - (p + q)/2
|
| 1004 |
+
rho = g1.nu + (u - v)/2 + 1
|
| 1005 |
+
mu = g2.nu + (p - q)/2 + 1
|
| 1006 |
+
phi = q - p - (v - u)
|
| 1007 |
+
eta = 1 - (v - u) - mu - rho
|
| 1008 |
+
psi = (pi*(q - m - n) + Abs(unbranched_argument(omega)))/(q - p)
|
| 1009 |
+
theta = (pi*(v - s - t) + Abs(unbranched_argument(sigma)))/(v - u)
|
| 1010 |
+
|
| 1011 |
+
_debug('Checking antecedents:')
|
| 1012 |
+
_debugf(' sigma=%s, s=%s, t=%s, u=%s, v=%s, b*=%s, rho=%s',
|
| 1013 |
+
(sigma, s, t, u, v, bstar, rho))
|
| 1014 |
+
_debugf(' omega=%s, m=%s, n=%s, p=%s, q=%s, c*=%s, mu=%s,',
|
| 1015 |
+
(omega, m, n, p, q, cstar, mu))
|
| 1016 |
+
_debugf(' phi=%s, eta=%s, psi=%s, theta=%s', (phi, eta, psi, theta))
|
| 1017 |
+
|
| 1018 |
+
def _c1():
|
| 1019 |
+
for g in [g1, g2]:
|
| 1020 |
+
for i, j in itertools.product(g.an, g.bm):
|
| 1021 |
+
diff = i - j
|
| 1022 |
+
if diff.is_integer and diff.is_positive:
|
| 1023 |
+
return False
|
| 1024 |
+
return True
|
| 1025 |
+
c1 = _c1()
|
| 1026 |
+
c2 = And(*[re(1 + i + j) > 0 for i in g1.bm for j in g2.bm])
|
| 1027 |
+
c3 = And(*[re(1 + i + j) < 1 + 1 for i in g1.an for j in g2.an])
|
| 1028 |
+
c4 = And(*[(p - q)*re(1 + i - 1) - re(mu) > Rational(-3, 2) for i in g1.an])
|
| 1029 |
+
c5 = And(*[(p - q)*re(1 + i) - re(mu) > Rational(-3, 2) for i in g1.bm])
|
| 1030 |
+
c6 = And(*[(u - v)*re(1 + i - 1) - re(rho) > Rational(-3, 2) for i in g2.an])
|
| 1031 |
+
c7 = And(*[(u - v)*re(1 + i) - re(rho) > Rational(-3, 2) for i in g2.bm])
|
| 1032 |
+
c8 = (Abs(phi) + 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu -
|
| 1033 |
+
1)*(v - u)) > 0)
|
| 1034 |
+
c9 = (Abs(phi) - 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu -
|
| 1035 |
+
1)*(v - u)) > 0)
|
| 1036 |
+
c10 = (Abs(unbranched_argument(sigma)) < bstar*pi)
|
| 1037 |
+
c11 = Eq(Abs(unbranched_argument(sigma)), bstar*pi)
|
| 1038 |
+
c12 = (Abs(unbranched_argument(omega)) < cstar*pi)
|
| 1039 |
+
c13 = Eq(Abs(unbranched_argument(omega)), cstar*pi)
|
| 1040 |
+
|
| 1041 |
+
# The following condition is *not* implemented as stated on the wolfram
|
| 1042 |
+
# function site. In the book of Prudnikov there is an additional part
|
| 1043 |
+
# (the And involving re()). However, I only have this book in russian, and
|
| 1044 |
+
# I don't read any russian. The following condition is what other people
|
| 1045 |
+
# have told me it means.
|
| 1046 |
+
# Worryingly, it is different from the condition implemented in REDUCE.
|
| 1047 |
+
# The REDUCE implementation:
|
| 1048 |
+
# https://reduce-algebra.svn.sourceforge.net/svnroot/reduce-algebra/trunk/packages/defint/definta.red
|
| 1049 |
+
# (search for tst14)
|
| 1050 |
+
# The Wolfram alpha version:
|
| 1051 |
+
# https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/03/0014/
|
| 1052 |
+
z0 = exp(-(bstar + cstar)*pi*S.ImaginaryUnit)
|
| 1053 |
+
zos = unpolarify(z0*omega/sigma)
|
| 1054 |
+
zso = unpolarify(z0*sigma/omega)
|
| 1055 |
+
if zos == 1/zso:
|
| 1056 |
+
c14 = And(Eq(phi, 0), bstar + cstar <= 1,
|
| 1057 |
+
Or(Ne(zos, 1), re(mu + rho + v - u) < 1,
|
| 1058 |
+
re(mu + rho + q - p) < 1))
|
| 1059 |
+
else:
|
| 1060 |
+
def _cond(z):
|
| 1061 |
+
'''Returns True if abs(arg(1-z)) < pi, avoiding arg(0).
|
| 1062 |
+
|
| 1063 |
+
Explanation
|
| 1064 |
+
===========
|
| 1065 |
+
|
| 1066 |
+
If ``z`` is 1 then arg is NaN. This raises a
|
| 1067 |
+
TypeError on `NaN < pi`. Previously this gave `False` so
|
| 1068 |
+
this behavior has been hardcoded here but someone should
|
| 1069 |
+
check if this NaN is more serious! This NaN is triggered by
|
| 1070 |
+
test_meijerint() in test_meijerint.py:
|
| 1071 |
+
`meijerint_definite(exp(x), x, 0, I)`
|
| 1072 |
+
'''
|
| 1073 |
+
return z != 1 and Abs(arg(1 - z)) < pi
|
| 1074 |
+
|
| 1075 |
+
c14 = And(Eq(phi, 0), bstar - 1 + cstar <= 0,
|
| 1076 |
+
Or(And(Ne(zos, 1), _cond(zos)),
|
| 1077 |
+
And(re(mu + rho + v - u) < 1, Eq(zos, 1))))
|
| 1078 |
+
|
| 1079 |
+
c14_alt = And(Eq(phi, 0), cstar - 1 + bstar <= 0,
|
| 1080 |
+
Or(And(Ne(zso, 1), _cond(zso)),
|
| 1081 |
+
And(re(mu + rho + q - p) < 1, Eq(zso, 1))))
|
| 1082 |
+
|
| 1083 |
+
# Since r=k=l=1, in our case there is c14_alt which is the same as calling
|
| 1084 |
+
# us with (g1, g2) = (g2, g1). The conditions below enumerate all cases
|
| 1085 |
+
# (i.e. we don't have to try arguments reversed by hand), and indeed try
|
| 1086 |
+
# all symmetric cases. (i.e. whenever there is a condition involving c14,
|
| 1087 |
+
# there is also a dual condition which is exactly what we would get when g1,
|
| 1088 |
+
# g2 were interchanged, *but c14 was unaltered*).
|
| 1089 |
+
# Hence the following seems correct:
|
| 1090 |
+
c14 = Or(c14, c14_alt)
|
| 1091 |
+
|
| 1092 |
+
'''
|
| 1093 |
+
When `c15` is NaN (e.g. from `psi` being NaN as happens during
|
| 1094 |
+
'test_issue_4992' and/or `theta` is NaN as in 'test_issue_6253',
|
| 1095 |
+
both in `test_integrals.py`) the comparison to 0 formerly gave False
|
| 1096 |
+
whereas now an error is raised. To keep the old behavior, the value
|
| 1097 |
+
of NaN is replaced with False but perhaps a closer look at this condition
|
| 1098 |
+
should be made: XXX how should conditions leading to c15=NaN be handled?
|
| 1099 |
+
'''
|
| 1100 |
+
try:
|
| 1101 |
+
lambda_c = (q - p)*Abs(omega)**(1/(q - p))*cos(psi) \
|
| 1102 |
+
+ (v - u)*Abs(sigma)**(1/(v - u))*cos(theta)
|
| 1103 |
+
# the TypeError might be raised here, e.g. if lambda_c is NaN
|
| 1104 |
+
if _eval_cond(lambda_c > 0) != False:
|
| 1105 |
+
c15 = (lambda_c > 0)
|
| 1106 |
+
else:
|
| 1107 |
+
def lambda_s0(c1, c2):
|
| 1108 |
+
return c1*(q - p)*Abs(omega)**(1/(q - p))*sin(psi) \
|
| 1109 |
+
+ c2*(v - u)*Abs(sigma)**(1/(v - u))*sin(theta)
|
| 1110 |
+
lambda_s = Piecewise(
|
| 1111 |
+
((lambda_s0(+1, +1)*lambda_s0(-1, -1)),
|
| 1112 |
+
And(Eq(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))),
|
| 1113 |
+
(lambda_s0(sign(unbranched_argument(omega)), +1)*lambda_s0(sign(unbranched_argument(omega)), -1),
|
| 1114 |
+
And(Eq(unbranched_argument(sigma), 0), Ne(unbranched_argument(omega), 0))),
|
| 1115 |
+
(lambda_s0(+1, sign(unbranched_argument(sigma)))*lambda_s0(-1, sign(unbranched_argument(sigma))),
|
| 1116 |
+
And(Ne(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))),
|
| 1117 |
+
(lambda_s0(sign(unbranched_argument(omega)), sign(unbranched_argument(sigma))), True))
|
| 1118 |
+
tmp = [lambda_c > 0,
|
| 1119 |
+
And(Eq(lambda_c, 0), Ne(lambda_s, 0), re(eta) > -1),
|
| 1120 |
+
And(Eq(lambda_c, 0), Eq(lambda_s, 0), re(eta) > 0)]
|
| 1121 |
+
c15 = Or(*tmp)
|
| 1122 |
+
except TypeError:
|
| 1123 |
+
c15 = False
|
| 1124 |
+
for cond, i in [(c1, 1), (c2, 2), (c3, 3), (c4, 4), (c5, 5), (c6, 6),
|
| 1125 |
+
(c7, 7), (c8, 8), (c9, 9), (c10, 10), (c11, 11),
|
| 1126 |
+
(c12, 12), (c13, 13), (c14, 14), (c15, 15)]:
|
| 1127 |
+
_debugf(' c%s: %s', (i, cond))
|
| 1128 |
+
|
| 1129 |
+
# We will return Or(*conds)
|
| 1130 |
+
conds = []
|
| 1131 |
+
|
| 1132 |
+
def pr(count):
|
| 1133 |
+
_debugf(' case %s: %s', (count, conds[-1]))
|
| 1134 |
+
conds += [And(m*n*s*t != 0, bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10,
|
| 1135 |
+
c12)] # 1
|
| 1136 |
+
pr(1)
|
| 1137 |
+
conds += [And(Eq(u, v), Eq(bstar, 0), cstar.is_positive is True, sigma.is_positive is True, re(rho) < 1,
|
| 1138 |
+
c1, c2, c3, c12)] # 2
|
| 1139 |
+
pr(2)
|
| 1140 |
+
conds += [And(Eq(p, q), Eq(cstar, 0), bstar.is_positive is True, omega.is_positive is True, re(mu) < 1,
|
| 1141 |
+
c1, c2, c3, c10)] # 3
|
| 1142 |
+
pr(3)
|
| 1143 |
+
conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0),
|
| 1144 |
+
sigma.is_positive is True, omega.is_positive is True, re(mu) < 1, re(rho) < 1,
|
| 1145 |
+
Ne(sigma, omega), c1, c2, c3)] # 4
|
| 1146 |
+
pr(4)
|
| 1147 |
+
conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0),
|
| 1148 |
+
sigma.is_positive is True, omega.is_positive is True, re(mu + rho) < 1,
|
| 1149 |
+
Ne(omega, sigma), c1, c2, c3)] # 5
|
| 1150 |
+
pr(5)
|
| 1151 |
+
conds += [And(p > q, s.is_positive is True, bstar.is_positive is True, cstar >= 0,
|
| 1152 |
+
c1, c2, c3, c5, c10, c13)] # 6
|
| 1153 |
+
pr(6)
|
| 1154 |
+
conds += [And(p < q, t.is_positive is True, bstar.is_positive is True, cstar >= 0,
|
| 1155 |
+
c1, c2, c3, c4, c10, c13)] # 7
|
| 1156 |
+
pr(7)
|
| 1157 |
+
conds += [And(u > v, m.is_positive is True, cstar.is_positive is True, bstar >= 0,
|
| 1158 |
+
c1, c2, c3, c7, c11, c12)] # 8
|
| 1159 |
+
pr(8)
|
| 1160 |
+
conds += [And(u < v, n.is_positive is True, cstar.is_positive is True, bstar >= 0,
|
| 1161 |
+
c1, c2, c3, c6, c11, c12)] # 9
|
| 1162 |
+
pr(9)
|
| 1163 |
+
conds += [And(p > q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True,
|
| 1164 |
+
re(rho) < 1, c1, c2, c3, c5, c13)] # 10
|
| 1165 |
+
pr(10)
|
| 1166 |
+
conds += [And(p < q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True,
|
| 1167 |
+
re(rho) < 1, c1, c2, c3, c4, c13)] # 11
|
| 1168 |
+
pr(11)
|
| 1169 |
+
conds += [And(Eq(p, q), u > v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True,
|
| 1170 |
+
re(mu) < 1, c1, c2, c3, c7, c11)] # 12
|
| 1171 |
+
pr(12)
|
| 1172 |
+
conds += [And(Eq(p, q), u < v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True,
|
| 1173 |
+
re(mu) < 1, c1, c2, c3, c6, c11)] # 13
|
| 1174 |
+
pr(13)
|
| 1175 |
+
conds += [And(p < q, u > v, bstar >= 0, cstar >= 0,
|
| 1176 |
+
c1, c2, c3, c4, c7, c11, c13)] # 14
|
| 1177 |
+
pr(14)
|
| 1178 |
+
conds += [And(p > q, u < v, bstar >= 0, cstar >= 0,
|
| 1179 |
+
c1, c2, c3, c5, c6, c11, c13)] # 15
|
| 1180 |
+
pr(15)
|
| 1181 |
+
conds += [And(p > q, u > v, bstar >= 0, cstar >= 0,
|
| 1182 |
+
c1, c2, c3, c5, c7, c8, c11, c13, c14)] # 16
|
| 1183 |
+
pr(16)
|
| 1184 |
+
conds += [And(p < q, u < v, bstar >= 0, cstar >= 0,
|
| 1185 |
+
c1, c2, c3, c4, c6, c9, c11, c13, c14)] # 17
|
| 1186 |
+
pr(17)
|
| 1187 |
+
conds += [And(Eq(t, 0), s.is_positive is True, bstar.is_positive is True, phi.is_positive is True, c1, c2, c10)] # 18
|
| 1188 |
+
pr(18)
|
| 1189 |
+
conds += [And(Eq(s, 0), t.is_positive is True, bstar.is_positive is True, phi.is_negative is True, c1, c3, c10)] # 19
|
| 1190 |
+
pr(19)
|
| 1191 |
+
conds += [And(Eq(n, 0), m.is_positive is True, cstar.is_positive is True, phi.is_negative is True, c1, c2, c12)] # 20
|
| 1192 |
+
pr(20)
|
| 1193 |
+
conds += [And(Eq(m, 0), n.is_positive is True, cstar.is_positive is True, phi.is_positive is True, c1, c3, c12)] # 21
|
| 1194 |
+
pr(21)
|
| 1195 |
+
conds += [And(Eq(s*t, 0), bstar.is_positive is True, cstar.is_positive is True,
|
| 1196 |
+
c1, c2, c3, c10, c12)] # 22
|
| 1197 |
+
pr(22)
|
| 1198 |
+
conds += [And(Eq(m*n, 0), bstar.is_positive is True, cstar.is_positive is True,
|
| 1199 |
+
c1, c2, c3, c10, c12)] # 23
|
| 1200 |
+
pr(23)
|
| 1201 |
+
|
| 1202 |
+
# The following case is from [Luke1969]. As far as I can tell, it is *not*
|
| 1203 |
+
# covered by Prudnikov's.
|
| 1204 |
+
# Let G1 and G2 be the two G-functions. Suppose the integral exists from
|
| 1205 |
+
# 0 to a > 0 (this is easy the easy part), that G1 is exponential decay at
|
| 1206 |
+
# infinity, and that the mellin transform of G2 exists.
|
| 1207 |
+
# Then the integral exists.
|
| 1208 |
+
mt1_exists = _check_antecedents_1(g1, x, helper=True)
|
| 1209 |
+
mt2_exists = _check_antecedents_1(g2, x, helper=True)
|
| 1210 |
+
conds += [And(mt2_exists, Eq(t, 0), u < s, bstar.is_positive is True, c10, c1, c2, c3)]
|
| 1211 |
+
pr('E1')
|
| 1212 |
+
conds += [And(mt2_exists, Eq(s, 0), v < t, bstar.is_positive is True, c10, c1, c2, c3)]
|
| 1213 |
+
pr('E2')
|
| 1214 |
+
conds += [And(mt1_exists, Eq(n, 0), p < m, cstar.is_positive is True, c12, c1, c2, c3)]
|
| 1215 |
+
pr('E3')
|
| 1216 |
+
conds += [And(mt1_exists, Eq(m, 0), q < n, cstar.is_positive is True, c12, c1, c2, c3)]
|
| 1217 |
+
pr('E4')
|
| 1218 |
+
|
| 1219 |
+
# Let's short-circuit if this worked ...
|
| 1220 |
+
# the rest is corner-cases and terrible to read.
|
| 1221 |
+
r = Or(*conds)
|
| 1222 |
+
if _eval_cond(r) != False:
|
| 1223 |
+
return r
|
| 1224 |
+
|
| 1225 |
+
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,
|
| 1226 |
+
Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi,
|
| 1227 |
+
c1, c2, c10, c14, c15)] # 24
|
| 1228 |
+
pr(24)
|
| 1229 |
+
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,
|
| 1230 |
+
Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi,
|
| 1231 |
+
c1, c3, c10, c14, c15)] # 25
|
| 1232 |
+
pr(25)
|
| 1233 |
+
conds += [And(Eq(p, q - 1), Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True,
|
| 1234 |
+
cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)),
|
| 1235 |
+
c1, c2, c10, c14, c15)] # 26
|
| 1236 |
+
pr(26)
|
| 1237 |
+
conds += [And(Eq(p, q + 1), Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True,
|
| 1238 |
+
cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)),
|
| 1239 |
+
c1, c3, c10, c14, c15)] # 27
|
| 1240 |
+
pr(27)
|
| 1241 |
+
conds += [And(p < q - 1, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True,
|
| 1242 |
+
cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)),
|
| 1243 |
+
Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi,
|
| 1244 |
+
c1, c2, c10, c14, c15)] # 28
|
| 1245 |
+
pr(28)
|
| 1246 |
+
conds += [And(
|
| 1247 |
+
p > q + 1, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar >= 0,
|
| 1248 |
+
cstar*pi < Abs(unbranched_argument(omega)),
|
| 1249 |
+
Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi,
|
| 1250 |
+
c1, c3, c10, c14, c15)] # 29
|
| 1251 |
+
pr(29)
|
| 1252 |
+
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,
|
| 1253 |
+
Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi,
|
| 1254 |
+
c1, c2, c12, c14, c15)] # 30
|
| 1255 |
+
pr(30)
|
| 1256 |
+
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,
|
| 1257 |
+
Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi,
|
| 1258 |
+
c1, c3, c12, c14, c15)] # 31
|
| 1259 |
+
pr(31)
|
| 1260 |
+
conds += [And(Eq(n, 0), Eq(phi, 0), Eq(u, v - 1), m.is_positive is True, cstar.is_positive is True,
|
| 1261 |
+
bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)),
|
| 1262 |
+
Abs(unbranched_argument(sigma)) < (bstar + 1)*pi,
|
| 1263 |
+
c1, c2, c12, c14, c15)] # 32
|
| 1264 |
+
pr(32)
|
| 1265 |
+
conds += [And(Eq(m, 0), Eq(phi, 0), Eq(u, v + 1), n.is_positive is True, cstar.is_positive is True,
|
| 1266 |
+
bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)),
|
| 1267 |
+
Abs(unbranched_argument(sigma)) < (bstar + 1)*pi,
|
| 1268 |
+
c1, c3, c12, c14, c15)] # 33
|
| 1269 |
+
pr(33)
|
| 1270 |
+
conds += [And(
|
| 1271 |
+
Eq(n, 0), Eq(phi, 0), u < v - 1, m.is_positive is True, cstar.is_positive is True, bstar >= 0,
|
| 1272 |
+
bstar*pi < Abs(unbranched_argument(sigma)),
|
| 1273 |
+
Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi,
|
| 1274 |
+
c1, c2, c12, c14, c15)] # 34
|
| 1275 |
+
pr(34)
|
| 1276 |
+
conds += [And(
|
| 1277 |
+
Eq(m, 0), Eq(phi, 0), u > v + 1, n.is_positive is True, cstar.is_positive is True, bstar >= 0,
|
| 1278 |
+
bstar*pi < Abs(unbranched_argument(sigma)),
|
| 1279 |
+
Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi,
|
| 1280 |
+
c1, c3, c12, c14, c15)] # 35
|
| 1281 |
+
pr(35)
|
| 1282 |
+
|
| 1283 |
+
return Or(*conds)
|
| 1284 |
+
|
| 1285 |
+
# NOTE An alternative, but as far as I can tell weaker, set of conditions
|
| 1286 |
+
# can be found in [L, section 5.6.2].
|
| 1287 |
+
|
| 1288 |
+
|
| 1289 |
+
def _int0oo(g1, g2, x):
|
| 1290 |
+
"""
|
| 1291 |
+
Express integral from zero to infinity g1*g2 using a G function,
|
| 1292 |
+
assuming the necessary conditions are fulfilled.
|
| 1293 |
+
|
| 1294 |
+
Examples
|
| 1295 |
+
========
|
| 1296 |
+
|
| 1297 |
+
>>> from sympy.integrals.meijerint import _int0oo
|
| 1298 |
+
>>> from sympy.abc import s, t, m
|
| 1299 |
+
>>> from sympy import meijerg, S
|
| 1300 |
+
>>> g1 = meijerg([], [], [-S(1)/2, 0], [], s**2*t/4)
|
| 1301 |
+
>>> g2 = meijerg([], [], [m/2], [-m/2], t/4)
|
| 1302 |
+
>>> _int0oo(g1, g2, t)
|
| 1303 |
+
4*meijerg(((0, 1/2), ()), ((m/2,), (-m/2,)), s**(-2))/s**2
|
| 1304 |
+
"""
|
| 1305 |
+
# See: [L, section 5.6.2, equation (1)]
|
| 1306 |
+
eta, _ = _get_coeff_exp(g1.argument, x)
|
| 1307 |
+
omega, _ = _get_coeff_exp(g2.argument, x)
|
| 1308 |
+
|
| 1309 |
+
def neg(l):
|
| 1310 |
+
return [-x for x in l]
|
| 1311 |
+
a1 = neg(g1.bm) + list(g2.an)
|
| 1312 |
+
a2 = list(g2.aother) + neg(g1.bother)
|
| 1313 |
+
b1 = neg(g1.an) + list(g2.bm)
|
| 1314 |
+
b2 = list(g2.bother) + neg(g1.aother)
|
| 1315 |
+
return meijerg(a1, a2, b1, b2, omega/eta)/eta
|
| 1316 |
+
|
| 1317 |
+
|
| 1318 |
+
def _rewrite_inversion(fac, po, g, x):
|
| 1319 |
+
""" Absorb ``po`` == x**s into g. """
|
| 1320 |
+
_, s = _get_coeff_exp(po, x)
|
| 1321 |
+
a, b = _get_coeff_exp(g.argument, x)
|
| 1322 |
+
|
| 1323 |
+
def tr(l):
|
| 1324 |
+
return [t + s/b for t in l]
|
| 1325 |
+
from sympy.simplify import powdenest
|
| 1326 |
+
return (powdenest(fac/a**(s/b), polar=True),
|
| 1327 |
+
meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother), g.argument))
|
| 1328 |
+
|
| 1329 |
+
|
| 1330 |
+
def _check_antecedents_inversion(g, x):
|
| 1331 |
+
""" Check antecedents for the laplace inversion integral. """
|
| 1332 |
+
_debug('Checking antecedents for inversion:')
|
| 1333 |
+
z = g.argument
|
| 1334 |
+
_, e = _get_coeff_exp(z, x)
|
| 1335 |
+
if e < 0:
|
| 1336 |
+
_debug(' Flipping G.')
|
| 1337 |
+
# We want to assume that argument gets large as |x| -> oo
|
| 1338 |
+
return _check_antecedents_inversion(_flip_g(g), x)
|
| 1339 |
+
|
| 1340 |
+
def statement_half(a, b, c, z, plus):
|
| 1341 |
+
coeff, exponent = _get_coeff_exp(z, x)
|
| 1342 |
+
a *= exponent
|
| 1343 |
+
b *= coeff**c
|
| 1344 |
+
c *= exponent
|
| 1345 |
+
conds = []
|
| 1346 |
+
wp = b*exp(S.ImaginaryUnit*re(c)*pi/2)
|
| 1347 |
+
wm = b*exp(-S.ImaginaryUnit*re(c)*pi/2)
|
| 1348 |
+
if plus:
|
| 1349 |
+
w = wp
|
| 1350 |
+
else:
|
| 1351 |
+
w = wm
|
| 1352 |
+
conds += [And(Or(Eq(b, 0), re(c) <= 0), re(a) <= -1)]
|
| 1353 |
+
conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) < 0)]
|
| 1354 |
+
conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) <= 0,
|
| 1355 |
+
re(a) <= -1)]
|
| 1356 |
+
return Or(*conds)
|
| 1357 |
+
|
| 1358 |
+
def statement(a, b, c, z):
|
| 1359 |
+
""" Provide a convergence statement for z**a * exp(b*z**c),
|
| 1360 |
+
c/f sphinx docs. """
|
| 1361 |
+
return And(statement_half(a, b, c, z, True),
|
| 1362 |
+
statement_half(a, b, c, z, False))
|
| 1363 |
+
|
| 1364 |
+
# Notations from [L], section 5.7-10
|
| 1365 |
+
m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)])
|
| 1366 |
+
tau = m + n - p
|
| 1367 |
+
nu = q - m - n
|
| 1368 |
+
rho = (tau - nu)/2
|
| 1369 |
+
sigma = q - p
|
| 1370 |
+
if sigma == 1:
|
| 1371 |
+
epsilon = S.Half
|
| 1372 |
+
elif sigma > 1:
|
| 1373 |
+
epsilon = 1
|
| 1374 |
+
else:
|
| 1375 |
+
epsilon = S.NaN
|
| 1376 |
+
theta = ((1 - sigma)/2 + Add(*g.bq) - Add(*g.ap))/sigma
|
| 1377 |
+
delta = g.delta
|
| 1378 |
+
_debugf(' m=%s, n=%s, p=%s, q=%s, tau=%s, nu=%s, rho=%s, sigma=%s',
|
| 1379 |
+
(m, n, p, q, tau, nu, rho, sigma))
|
| 1380 |
+
_debugf(' epsilon=%s, theta=%s, delta=%s', (epsilon, theta, delta))
|
| 1381 |
+
|
| 1382 |
+
# First check if the computation is valid.
|
| 1383 |
+
if not (g.delta >= e/2 or (p >= 1 and p >= q)):
|
| 1384 |
+
_debug(' Computation not valid for these parameters.')
|
| 1385 |
+
return False
|
| 1386 |
+
|
| 1387 |
+
# Now check if the inversion integral exists.
|
| 1388 |
+
|
| 1389 |
+
# Test "condition A"
|
| 1390 |
+
for a, b in itertools.product(g.an, g.bm):
|
| 1391 |
+
if (a - b).is_integer and a > b:
|
| 1392 |
+
_debug(' Not a valid G function.')
|
| 1393 |
+
return False
|
| 1394 |
+
|
| 1395 |
+
# There are two cases. If p >= q, we can directly use a slater expansion
|
| 1396 |
+
# like [L], 5.2 (11). Note in particular that the asymptotics of such an
|
| 1397 |
+
# expansion even hold when some of the parameters differ by integers, i.e.
|
| 1398 |
+
# the formula itself would not be valid! (b/c G functions are cts. in their
|
| 1399 |
+
# parameters)
|
| 1400 |
+
# When p < q, we need to use the theorems of [L], 5.10.
|
| 1401 |
+
|
| 1402 |
+
if p >= q:
|
| 1403 |
+
_debug(' Using asymptotic Slater expansion.')
|
| 1404 |
+
return And(*[statement(a - 1, 0, 0, z) for a in g.an])
|
| 1405 |
+
|
| 1406 |
+
def E(z):
|
| 1407 |
+
return And(*[statement(a - 1, 0, 0, z) for a in g.an])
|
| 1408 |
+
|
| 1409 |
+
def H(z):
|
| 1410 |
+
return statement(theta, -sigma, 1/sigma, z)
|
| 1411 |
+
|
| 1412 |
+
def Hp(z):
|
| 1413 |
+
return statement_half(theta, -sigma, 1/sigma, z, True)
|
| 1414 |
+
|
| 1415 |
+
def Hm(z):
|
| 1416 |
+
return statement_half(theta, -sigma, 1/sigma, z, False)
|
| 1417 |
+
|
| 1418 |
+
# [L], section 5.10
|
| 1419 |
+
conds = []
|
| 1420 |
+
# Theorem 1 -- p < q from test above
|
| 1421 |
+
conds += [And(1 <= n, 1 <= m, rho*pi - delta >= pi/2, delta > 0,
|
| 1422 |
+
E(z*exp(S.ImaginaryUnit*pi*(nu + 1))))]
|
| 1423 |
+
# Theorem 2, statements (2) and (3)
|
| 1424 |
+
conds += [And(p + 1 <= m, m + 1 <= q, delta > 0, delta < pi/2, n == 0,
|
| 1425 |
+
(m - p + 1)*pi - delta >= pi/2,
|
| 1426 |
+
Hp(z*exp(S.ImaginaryUnit*pi*(q - m))),
|
| 1427 |
+
Hm(z*exp(-S.ImaginaryUnit*pi*(q - m))))]
|
| 1428 |
+
# Theorem 2, statement (5) -- p < q from test above
|
| 1429 |
+
conds += [And(m == q, n == 0, delta > 0,
|
| 1430 |
+
(sigma + epsilon)*pi - delta >= pi/2, H(z))]
|
| 1431 |
+
# Theorem 3, statements (6) and (7)
|
| 1432 |
+
conds += [And(Or(And(p <= q - 2, 1 <= tau, tau <= sigma/2),
|
| 1433 |
+
And(p + 1 <= m + n, m + n <= (p + q)/2)),
|
| 1434 |
+
delta > 0, delta < pi/2, (tau + 1)*pi - delta >= pi/2,
|
| 1435 |
+
Hp(z*exp(S.ImaginaryUnit*pi*nu)),
|
| 1436 |
+
Hm(z*exp(-S.ImaginaryUnit*pi*nu)))]
|
| 1437 |
+
# Theorem 4, statements (10) and (11) -- p < q from test above
|
| 1438 |
+
conds += [And(1 <= m, rho > 0, delta > 0, delta + rho*pi < pi/2,
|
| 1439 |
+
(tau + epsilon)*pi - delta >= pi/2,
|
| 1440 |
+
Hp(z*exp(S.ImaginaryUnit*pi*nu)),
|
| 1441 |
+
Hm(z*exp(-S.ImaginaryUnit*pi*nu)))]
|
| 1442 |
+
# Trivial case
|
| 1443 |
+
conds += [m == 0]
|
| 1444 |
+
|
| 1445 |
+
# TODO
|
| 1446 |
+
# Theorem 5 is quite general
|
| 1447 |
+
# Theorem 6 contains special cases for q=p+1
|
| 1448 |
+
|
| 1449 |
+
return Or(*conds)
|
| 1450 |
+
|
| 1451 |
+
|
| 1452 |
+
def _int_inversion(g, x, t):
|
| 1453 |
+
"""
|
| 1454 |
+
Compute the laplace inversion integral, assuming the formula applies.
|
| 1455 |
+
"""
|
| 1456 |
+
b, a = _get_coeff_exp(g.argument, x)
|
| 1457 |
+
C, g = _inflate_fox_h(meijerg(g.an, g.aother, g.bm, g.bother, b/t**a), -a)
|
| 1458 |
+
return C/t*g
|
| 1459 |
+
|
| 1460 |
+
|
| 1461 |
+
####################################################################
|
| 1462 |
+
# Finally, the real meat.
|
| 1463 |
+
####################################################################
|
| 1464 |
+
|
| 1465 |
+
_lookup_table = None
|
| 1466 |
+
|
| 1467 |
+
|
| 1468 |
+
@cacheit
|
| 1469 |
+
@timeit
|
| 1470 |
+
def _rewrite_single(f, x, recursive=True):
|
| 1471 |
+
"""
|
| 1472 |
+
Try to rewrite f as a sum of single G functions of the form
|
| 1473 |
+
C*x**s*G(a*x**b), where b is a rational number and C is independent of x.
|
| 1474 |
+
We guarantee that result.argument.as_coeff_mul(x) returns (a, (x**b,))
|
| 1475 |
+
or (a, ()).
|
| 1476 |
+
Returns a list of tuples (C, s, G) and a condition cond.
|
| 1477 |
+
Returns None on failure.
|
| 1478 |
+
"""
|
| 1479 |
+
from .transforms import (mellin_transform, inverse_mellin_transform,
|
| 1480 |
+
IntegralTransformError, MellinTransformStripError)
|
| 1481 |
+
|
| 1482 |
+
global _lookup_table
|
| 1483 |
+
if not _lookup_table:
|
| 1484 |
+
_lookup_table = {}
|
| 1485 |
+
_create_lookup_table(_lookup_table)
|
| 1486 |
+
|
| 1487 |
+
if isinstance(f, meijerg):
|
| 1488 |
+
coeff, m = factor(f.argument, x).as_coeff_mul(x)
|
| 1489 |
+
if len(m) > 1:
|
| 1490 |
+
return None
|
| 1491 |
+
m = m[0]
|
| 1492 |
+
if m.is_Pow:
|
| 1493 |
+
if m.base != x or not m.exp.is_Rational:
|
| 1494 |
+
return None
|
| 1495 |
+
elif m != x:
|
| 1496 |
+
return None
|
| 1497 |
+
return [(1, 0, meijerg(f.an, f.aother, f.bm, f.bother, coeff*m))], True
|
| 1498 |
+
|
| 1499 |
+
f_ = f
|
| 1500 |
+
f = f.subs(x, z)
|
| 1501 |
+
t = _mytype(f, z)
|
| 1502 |
+
if t in _lookup_table:
|
| 1503 |
+
l = _lookup_table[t]
|
| 1504 |
+
for formula, terms, cond, hint in l:
|
| 1505 |
+
subs = f.match(formula, old=True)
|
| 1506 |
+
if subs:
|
| 1507 |
+
subs_ = {}
|
| 1508 |
+
for fro, to in subs.items():
|
| 1509 |
+
subs_[fro] = unpolarify(polarify(to, lift=True),
|
| 1510 |
+
exponents_only=True)
|
| 1511 |
+
subs = subs_
|
| 1512 |
+
if not isinstance(hint, bool):
|
| 1513 |
+
hint = hint.subs(subs)
|
| 1514 |
+
if hint == False:
|
| 1515 |
+
continue
|
| 1516 |
+
if not isinstance(cond, (bool, BooleanAtom)):
|
| 1517 |
+
cond = unpolarify(cond.subs(subs))
|
| 1518 |
+
if _eval_cond(cond) == False:
|
| 1519 |
+
continue
|
| 1520 |
+
if not isinstance(terms, list):
|
| 1521 |
+
terms = terms(subs)
|
| 1522 |
+
res = []
|
| 1523 |
+
for fac, g in terms:
|
| 1524 |
+
r1 = _get_coeff_exp(unpolarify(fac.subs(subs).subs(z, x),
|
| 1525 |
+
exponents_only=True), x)
|
| 1526 |
+
try:
|
| 1527 |
+
g = g.subs(subs).subs(z, x)
|
| 1528 |
+
except ValueError:
|
| 1529 |
+
continue
|
| 1530 |
+
# NOTE these substitutions can in principle introduce oo,
|
| 1531 |
+
# zoo and other absurdities. It shouldn't matter,
|
| 1532 |
+
# but better be safe.
|
| 1533 |
+
if Tuple(*(r1 + (g,))).has(S.Infinity, S.ComplexInfinity, S.NegativeInfinity):
|
| 1534 |
+
continue
|
| 1535 |
+
g = meijerg(g.an, g.aother, g.bm, g.bother,
|
| 1536 |
+
unpolarify(g.argument, exponents_only=True))
|
| 1537 |
+
res.append(r1 + (g,))
|
| 1538 |
+
if res:
|
| 1539 |
+
return res, cond
|
| 1540 |
+
|
| 1541 |
+
# try recursive mellin transform
|
| 1542 |
+
if not recursive:
|
| 1543 |
+
return None
|
| 1544 |
+
_debug('Trying recursive Mellin transform method.')
|
| 1545 |
+
|
| 1546 |
+
def my_imt(F, s, x, strip):
|
| 1547 |
+
""" Calling simplify() all the time is slow and not helpful, since
|
| 1548 |
+
most of the time it only factors things in a way that has to be
|
| 1549 |
+
un-done anyway. But sometimes it can remove apparent poles. """
|
| 1550 |
+
# XXX should this be in inverse_mellin_transform?
|
| 1551 |
+
try:
|
| 1552 |
+
return inverse_mellin_transform(F, s, x, strip,
|
| 1553 |
+
as_meijerg=True, needeval=True)
|
| 1554 |
+
except MellinTransformStripError:
|
| 1555 |
+
from sympy.simplify import simplify
|
| 1556 |
+
return inverse_mellin_transform(
|
| 1557 |
+
simplify(cancel(expand(F))), s, x, strip,
|
| 1558 |
+
as_meijerg=True, needeval=True)
|
| 1559 |
+
f = f_
|
| 1560 |
+
s = _dummy('s', 'rewrite-single', f)
|
| 1561 |
+
# to avoid infinite recursion, we have to force the two g functions case
|
| 1562 |
+
|
| 1563 |
+
def my_integrator(f, x):
|
| 1564 |
+
r = _meijerint_definite_4(f, x, only_double=True)
|
| 1565 |
+
if r is not None:
|
| 1566 |
+
from sympy.simplify import hyperexpand
|
| 1567 |
+
res, cond = r
|
| 1568 |
+
res = _my_unpolarify(hyperexpand(res, rewrite='nonrepsmall'))
|
| 1569 |
+
return Piecewise((res, cond),
|
| 1570 |
+
(Integral(f, (x, S.Zero, S.Infinity)), True))
|
| 1571 |
+
return Integral(f, (x, S.Zero, S.Infinity))
|
| 1572 |
+
try:
|
| 1573 |
+
F, strip, _ = mellin_transform(f, x, s, integrator=my_integrator,
|
| 1574 |
+
simplify=False, needeval=True)
|
| 1575 |
+
g = my_imt(F, s, x, strip)
|
| 1576 |
+
except IntegralTransformError:
|
| 1577 |
+
g = None
|
| 1578 |
+
if g is None:
|
| 1579 |
+
# We try to find an expression by analytic continuation.
|
| 1580 |
+
# (also if the dummy is already in the expression, there is no point in
|
| 1581 |
+
# putting in another one)
|
| 1582 |
+
a = _dummy_('a', 'rewrite-single')
|
| 1583 |
+
if a not in f.free_symbols and _is_analytic(f, x):
|
| 1584 |
+
try:
|
| 1585 |
+
F, strip, _ = mellin_transform(f.subs(x, a*x), x, s,
|
| 1586 |
+
integrator=my_integrator,
|
| 1587 |
+
needeval=True, simplify=False)
|
| 1588 |
+
g = my_imt(F, s, x, strip).subs(a, 1)
|
| 1589 |
+
except IntegralTransformError:
|
| 1590 |
+
g = None
|
| 1591 |
+
if g is None or g.has(S.Infinity, S.NaN, S.ComplexInfinity):
|
| 1592 |
+
_debug('Recursive Mellin transform failed.')
|
| 1593 |
+
return None
|
| 1594 |
+
args = Add.make_args(g)
|
| 1595 |
+
res = []
|
| 1596 |
+
for f in args:
|
| 1597 |
+
c, m = f.as_coeff_mul(x)
|
| 1598 |
+
if len(m) > 1:
|
| 1599 |
+
raise NotImplementedError('Unexpected form...')
|
| 1600 |
+
g = m[0]
|
| 1601 |
+
a, b = _get_coeff_exp(g.argument, x)
|
| 1602 |
+
res += [(c, 0, meijerg(g.an, g.aother, g.bm, g.bother,
|
| 1603 |
+
unpolarify(polarify(
|
| 1604 |
+
a, lift=True), exponents_only=True)
|
| 1605 |
+
*x**b))]
|
| 1606 |
+
_debug('Recursive Mellin transform worked:', g)
|
| 1607 |
+
return res, True
|
| 1608 |
+
|
| 1609 |
+
|
| 1610 |
+
def _rewrite1(f, x, recursive=True):
|
| 1611 |
+
"""
|
| 1612 |
+
Try to rewrite ``f`` using a (sum of) single G functions with argument a*x**b.
|
| 1613 |
+
Return fac, po, g such that f = fac*po*g, fac is independent of ``x``.
|
| 1614 |
+
and po = x**s.
|
| 1615 |
+
Here g is a result from _rewrite_single.
|
| 1616 |
+
Return None on failure.
|
| 1617 |
+
"""
|
| 1618 |
+
fac, po, g = _split_mul(f, x)
|
| 1619 |
+
g = _rewrite_single(g, x, recursive)
|
| 1620 |
+
if g:
|
| 1621 |
+
return fac, po, g[0], g[1]
|
| 1622 |
+
|
| 1623 |
+
|
| 1624 |
+
def _rewrite2(f, x):
|
| 1625 |
+
"""
|
| 1626 |
+
Try to rewrite ``f`` as a product of two G functions of arguments a*x**b.
|
| 1627 |
+
Return fac, po, g1, g2 such that f = fac*po*g1*g2, where fac is
|
| 1628 |
+
independent of x and po is x**s.
|
| 1629 |
+
Here g1 and g2 are results of _rewrite_single.
|
| 1630 |
+
Returns None on failure.
|
| 1631 |
+
"""
|
| 1632 |
+
fac, po, g = _split_mul(f, x)
|
| 1633 |
+
if any(_rewrite_single(expr, x, False) is None for expr in _mul_args(g)):
|
| 1634 |
+
return None
|
| 1635 |
+
l = _mul_as_two_parts(g)
|
| 1636 |
+
if not l:
|
| 1637 |
+
return None
|
| 1638 |
+
l = list(ordered(l, [
|
| 1639 |
+
lambda p: max(len(_exponents(p[0], x)), len(_exponents(p[1], x))),
|
| 1640 |
+
lambda p: max(len(_functions(p[0], x)), len(_functions(p[1], x))),
|
| 1641 |
+
lambda p: max(len(_find_splitting_points(p[0], x)),
|
| 1642 |
+
len(_find_splitting_points(p[1], x)))]))
|
| 1643 |
+
|
| 1644 |
+
for recursive, (fac1, fac2) in itertools.product((False, True), l):
|
| 1645 |
+
g1 = _rewrite_single(fac1, x, recursive)
|
| 1646 |
+
g2 = _rewrite_single(fac2, x, recursive)
|
| 1647 |
+
if g1 and g2:
|
| 1648 |
+
cond = And(g1[1], g2[1])
|
| 1649 |
+
if cond != False:
|
| 1650 |
+
return fac, po, g1[0], g2[0], cond
|
| 1651 |
+
|
| 1652 |
+
|
| 1653 |
+
def meijerint_indefinite(f, x):
|
| 1654 |
+
"""
|
| 1655 |
+
Compute an indefinite integral of ``f`` by rewriting it as a G function.
|
| 1656 |
+
|
| 1657 |
+
Examples
|
| 1658 |
+
========
|
| 1659 |
+
|
| 1660 |
+
>>> from sympy.integrals.meijerint import meijerint_indefinite
|
| 1661 |
+
>>> from sympy import sin
|
| 1662 |
+
>>> from sympy.abc import x
|
| 1663 |
+
>>> meijerint_indefinite(sin(x), x)
|
| 1664 |
+
-cos(x)
|
| 1665 |
+
"""
|
| 1666 |
+
f = sympify(f)
|
| 1667 |
+
results = []
|
| 1668 |
+
for a in sorted(_find_splitting_points(f, x) | {S.Zero}, key=default_sort_key):
|
| 1669 |
+
res = _meijerint_indefinite_1(f.subs(x, x + a), x)
|
| 1670 |
+
if not res:
|
| 1671 |
+
continue
|
| 1672 |
+
res = res.subs(x, x - a)
|
| 1673 |
+
if _has(res, hyper, meijerg):
|
| 1674 |
+
results.append(res)
|
| 1675 |
+
else:
|
| 1676 |
+
return res
|
| 1677 |
+
if f.has(HyperbolicFunction):
|
| 1678 |
+
_debug('Try rewriting hyperbolics in terms of exp.')
|
| 1679 |
+
rv = meijerint_indefinite(
|
| 1680 |
+
_rewrite_hyperbolics_as_exp(f), x)
|
| 1681 |
+
if rv:
|
| 1682 |
+
if not isinstance(rv, list):
|
| 1683 |
+
from sympy.simplify.radsimp import collect
|
| 1684 |
+
return collect(factor_terms(rv), rv.atoms(exp))
|
| 1685 |
+
results.extend(rv)
|
| 1686 |
+
if results:
|
| 1687 |
+
return next(ordered(results))
|
| 1688 |
+
|
| 1689 |
+
|
| 1690 |
+
def _meijerint_indefinite_1(f, x):
|
| 1691 |
+
""" Helper that does not attempt any substitution. """
|
| 1692 |
+
_debug('Trying to compute the indefinite integral of', f, 'wrt', x)
|
| 1693 |
+
from sympy.simplify import hyperexpand, powdenest
|
| 1694 |
+
|
| 1695 |
+
gs = _rewrite1(f, x)
|
| 1696 |
+
if gs is None:
|
| 1697 |
+
# Note: the code that calls us will do expand() and try again
|
| 1698 |
+
return None
|
| 1699 |
+
|
| 1700 |
+
fac, po, gl, cond = gs
|
| 1701 |
+
_debug(' could rewrite:', gs)
|
| 1702 |
+
res = S.Zero
|
| 1703 |
+
for C, s, g in gl:
|
| 1704 |
+
a, b = _get_coeff_exp(g.argument, x)
|
| 1705 |
+
_, c = _get_coeff_exp(po, x)
|
| 1706 |
+
c += s
|
| 1707 |
+
|
| 1708 |
+
# we do a substitution t=a*x**b, get integrand fac*t**rho*g
|
| 1709 |
+
fac_ = fac * C * x**(1 + c) / b
|
| 1710 |
+
rho = (c + 1)/b
|
| 1711 |
+
|
| 1712 |
+
# we now use t**rho*G(params, t) = G(params + rho, t)
|
| 1713 |
+
# [L, page 150, equation (4)]
|
| 1714 |
+
# and integral G(params, t) dt = G(1, params+1, 0, t)
|
| 1715 |
+
# (or a similar expression with 1 and 0 exchanged ... pick the one
|
| 1716 |
+
# which yields a well-defined function)
|
| 1717 |
+
# [R, section 5]
|
| 1718 |
+
# (Note that this dummy will immediately go away again, so we
|
| 1719 |
+
# can safely pass S.One for ``expr``.)
|
| 1720 |
+
t = _dummy('t', 'meijerint-indefinite', S.One)
|
| 1721 |
+
|
| 1722 |
+
def tr(p):
|
| 1723 |
+
return [a + rho for a in p]
|
| 1724 |
+
if any(b.is_integer and (b <= 0) == True for b in tr(g.bm)):
|
| 1725 |
+
r = -meijerg(
|
| 1726 |
+
list(g.an), list(g.aother) + [1-rho], list(g.bm) + [-rho], list(g.bother), t)
|
| 1727 |
+
else:
|
| 1728 |
+
r = meijerg(
|
| 1729 |
+
list(g.an) + [1-rho], list(g.aother), list(g.bm), list(g.bother) + [-rho], t)
|
| 1730 |
+
# The antiderivative is most often expected to be defined
|
| 1731 |
+
# in the neighborhood of x = 0.
|
| 1732 |
+
if b.is_extended_nonnegative and not f.subs(x, 0).has(S.NaN, S.ComplexInfinity):
|
| 1733 |
+
place = 0 # Assume we can expand at zero
|
| 1734 |
+
else:
|
| 1735 |
+
place = None
|
| 1736 |
+
r = hyperexpand(r.subs(t, a*x**b), place=place)
|
| 1737 |
+
|
| 1738 |
+
# now substitute back
|
| 1739 |
+
# Note: we really do want the powers of x to combine.
|
| 1740 |
+
res += powdenest(fac_*r, polar=True)
|
| 1741 |
+
|
| 1742 |
+
def _clean(res):
|
| 1743 |
+
"""This multiplies out superfluous powers of x we created, and chops off
|
| 1744 |
+
constants:
|
| 1745 |
+
|
| 1746 |
+
>> _clean(x*(exp(x)/x - 1/x) + 3)
|
| 1747 |
+
exp(x)
|
| 1748 |
+
|
| 1749 |
+
cancel is used before mul_expand since it is possible for an
|
| 1750 |
+
expression to have an additive constant that does not become isolated
|
| 1751 |
+
with simple expansion. Such a situation was identified in issue 6369:
|
| 1752 |
+
|
| 1753 |
+
Examples
|
| 1754 |
+
========
|
| 1755 |
+
|
| 1756 |
+
>>> from sympy import sqrt, cancel
|
| 1757 |
+
>>> from sympy.abc import x
|
| 1758 |
+
>>> a = sqrt(2*x + 1)
|
| 1759 |
+
>>> bad = (3*x*a**5 + 2*x - a**5 + 1)/a**2
|
| 1760 |
+
>>> bad.expand().as_independent(x)[0]
|
| 1761 |
+
0
|
| 1762 |
+
>>> cancel(bad).expand().as_independent(x)[0]
|
| 1763 |
+
1
|
| 1764 |
+
"""
|
| 1765 |
+
res = expand_mul(cancel(res), deep=False)
|
| 1766 |
+
return Add._from_args(res.as_coeff_add(x)[1])
|
| 1767 |
+
|
| 1768 |
+
res = piecewise_fold(res, evaluate=None)
|
| 1769 |
+
if res.is_Piecewise:
|
| 1770 |
+
newargs = []
|
| 1771 |
+
for e, c in res.args:
|
| 1772 |
+
e = _my_unpolarify(_clean(e))
|
| 1773 |
+
newargs += [(e, c)]
|
| 1774 |
+
res = Piecewise(*newargs, evaluate=False)
|
| 1775 |
+
else:
|
| 1776 |
+
res = _my_unpolarify(_clean(res))
|
| 1777 |
+
return Piecewise((res, _my_unpolarify(cond)), (Integral(f, x), True))
|
| 1778 |
+
|
| 1779 |
+
|
| 1780 |
+
@timeit
|
| 1781 |
+
def meijerint_definite(f, x, a, b):
|
| 1782 |
+
"""
|
| 1783 |
+
Integrate ``f`` over the interval [``a``, ``b``], by rewriting it as a product
|
| 1784 |
+
of two G functions, or as a single G function.
|
| 1785 |
+
|
| 1786 |
+
Return res, cond, where cond are convergence conditions.
|
| 1787 |
+
|
| 1788 |
+
Examples
|
| 1789 |
+
========
|
| 1790 |
+
|
| 1791 |
+
>>> from sympy.integrals.meijerint import meijerint_definite
|
| 1792 |
+
>>> from sympy import exp, oo
|
| 1793 |
+
>>> from sympy.abc import x
|
| 1794 |
+
>>> meijerint_definite(exp(-x**2), x, -oo, oo)
|
| 1795 |
+
(sqrt(pi), True)
|
| 1796 |
+
|
| 1797 |
+
This function is implemented as a succession of functions
|
| 1798 |
+
meijerint_definite, _meijerint_definite_2, _meijerint_definite_3,
|
| 1799 |
+
_meijerint_definite_4. Each function in the list calls the next one
|
| 1800 |
+
(presumably) several times. This means that calling meijerint_definite
|
| 1801 |
+
can be very costly.
|
| 1802 |
+
"""
|
| 1803 |
+
# This consists of three steps:
|
| 1804 |
+
# 1) Change the integration limits to 0, oo
|
| 1805 |
+
# 2) Rewrite in terms of G functions
|
| 1806 |
+
# 3) Evaluate the integral
|
| 1807 |
+
#
|
| 1808 |
+
# There are usually several ways of doing this, and we want to try all.
|
| 1809 |
+
# This function does (1), calls _meijerint_definite_2 for step (2).
|
| 1810 |
+
_debugf('Integrating %s wrt %s from %s to %s.', (f, x, a, b))
|
| 1811 |
+
f = sympify(f)
|
| 1812 |
+
if f.has(DiracDelta):
|
| 1813 |
+
_debug('Integrand has DiracDelta terms - giving up.')
|
| 1814 |
+
return None
|
| 1815 |
+
|
| 1816 |
+
if f.has(SingularityFunction):
|
| 1817 |
+
_debug('Integrand has Singularity Function terms - giving up.')
|
| 1818 |
+
return None
|
| 1819 |
+
|
| 1820 |
+
f_, x_, a_, b_ = f, x, a, b
|
| 1821 |
+
|
| 1822 |
+
# Let's use a dummy in case any of the boundaries has x.
|
| 1823 |
+
d = Dummy('x')
|
| 1824 |
+
f = f.subs(x, d)
|
| 1825 |
+
x = d
|
| 1826 |
+
|
| 1827 |
+
if a == b:
|
| 1828 |
+
return (S.Zero, True)
|
| 1829 |
+
|
| 1830 |
+
results = []
|
| 1831 |
+
if a is S.NegativeInfinity and b is not S.Infinity:
|
| 1832 |
+
return meijerint_definite(f.subs(x, -x), x, -b, -a)
|
| 1833 |
+
|
| 1834 |
+
elif a is S.NegativeInfinity:
|
| 1835 |
+
# Integrating -oo to oo. We need to find a place to split the integral.
|
| 1836 |
+
_debug(' Integrating -oo to +oo.')
|
| 1837 |
+
innermost = _find_splitting_points(f, x)
|
| 1838 |
+
_debug(' Sensible splitting points:', innermost)
|
| 1839 |
+
for c in sorted(innermost, key=default_sort_key, reverse=True) + [S.Zero]:
|
| 1840 |
+
_debug(' Trying to split at', c)
|
| 1841 |
+
if not c.is_extended_real:
|
| 1842 |
+
_debug(' Non-real splitting point.')
|
| 1843 |
+
continue
|
| 1844 |
+
res1 = _meijerint_definite_2(f.subs(x, x + c), x)
|
| 1845 |
+
if res1 is None:
|
| 1846 |
+
_debug(' But could not compute first integral.')
|
| 1847 |
+
continue
|
| 1848 |
+
res2 = _meijerint_definite_2(f.subs(x, c - x), x)
|
| 1849 |
+
if res2 is None:
|
| 1850 |
+
_debug(' But could not compute second integral.')
|
| 1851 |
+
continue
|
| 1852 |
+
res1, cond1 = res1
|
| 1853 |
+
res2, cond2 = res2
|
| 1854 |
+
cond = _condsimp(And(cond1, cond2))
|
| 1855 |
+
if cond == False:
|
| 1856 |
+
_debug(' But combined condition is always false.')
|
| 1857 |
+
continue
|
| 1858 |
+
res = res1 + res2
|
| 1859 |
+
return res, cond
|
| 1860 |
+
|
| 1861 |
+
elif a is S.Infinity:
|
| 1862 |
+
res = meijerint_definite(f, x, b, S.Infinity)
|
| 1863 |
+
return -res[0], res[1]
|
| 1864 |
+
|
| 1865 |
+
elif (a, b) == (S.Zero, S.Infinity):
|
| 1866 |
+
# This is a common case - try it directly first.
|
| 1867 |
+
res = _meijerint_definite_2(f, x)
|
| 1868 |
+
if res:
|
| 1869 |
+
if _has(res[0], meijerg):
|
| 1870 |
+
results.append(res)
|
| 1871 |
+
else:
|
| 1872 |
+
return res
|
| 1873 |
+
|
| 1874 |
+
else:
|
| 1875 |
+
if b is S.Infinity:
|
| 1876 |
+
for split in _find_splitting_points(f, x):
|
| 1877 |
+
if (a - split >= 0) == True:
|
| 1878 |
+
_debugf('Trying x -> x + %s', split)
|
| 1879 |
+
res = _meijerint_definite_2(f.subs(x, x + split)
|
| 1880 |
+
*Heaviside(x + split - a), x)
|
| 1881 |
+
if res:
|
| 1882 |
+
if _has(res[0], meijerg):
|
| 1883 |
+
results.append(res)
|
| 1884 |
+
else:
|
| 1885 |
+
return res
|
| 1886 |
+
|
| 1887 |
+
f = f.subs(x, x + a)
|
| 1888 |
+
b = b - a
|
| 1889 |
+
a = 0
|
| 1890 |
+
if b is not S.Infinity:
|
| 1891 |
+
phi = exp(S.ImaginaryUnit*arg(b))
|
| 1892 |
+
b = Abs(b)
|
| 1893 |
+
f = f.subs(x, phi*x)
|
| 1894 |
+
f *= Heaviside(b - x)*phi
|
| 1895 |
+
b = S.Infinity
|
| 1896 |
+
|
| 1897 |
+
_debug('Changed limits to', a, b)
|
| 1898 |
+
_debug('Changed function to', f)
|
| 1899 |
+
res = _meijerint_definite_2(f, x)
|
| 1900 |
+
if res:
|
| 1901 |
+
if _has(res[0], meijerg):
|
| 1902 |
+
results.append(res)
|
| 1903 |
+
else:
|
| 1904 |
+
return res
|
| 1905 |
+
if f_.has(HyperbolicFunction):
|
| 1906 |
+
_debug('Try rewriting hyperbolics in terms of exp.')
|
| 1907 |
+
rv = meijerint_definite(
|
| 1908 |
+
_rewrite_hyperbolics_as_exp(f_), x_, a_, b_)
|
| 1909 |
+
if rv:
|
| 1910 |
+
if not isinstance(rv, list):
|
| 1911 |
+
from sympy.simplify.radsimp import collect
|
| 1912 |
+
rv = (collect(factor_terms(rv[0]), rv[0].atoms(exp)),) + rv[1:]
|
| 1913 |
+
return rv
|
| 1914 |
+
results.extend(rv)
|
| 1915 |
+
if results:
|
| 1916 |
+
return next(ordered(results))
|
| 1917 |
+
|
| 1918 |
+
|
| 1919 |
+
def _guess_expansion(f, x):
|
| 1920 |
+
""" Try to guess sensible rewritings for integrand f(x). """
|
| 1921 |
+
res = [(f, 'original integrand')]
|
| 1922 |
+
|
| 1923 |
+
orig = res[-1][0]
|
| 1924 |
+
saw = {orig}
|
| 1925 |
+
expanded = expand_mul(orig)
|
| 1926 |
+
if expanded not in saw:
|
| 1927 |
+
res += [(expanded, 'expand_mul')]
|
| 1928 |
+
saw.add(expanded)
|
| 1929 |
+
|
| 1930 |
+
expanded = expand(orig)
|
| 1931 |
+
if expanded not in saw:
|
| 1932 |
+
res += [(expanded, 'expand')]
|
| 1933 |
+
saw.add(expanded)
|
| 1934 |
+
|
| 1935 |
+
if orig.has(TrigonometricFunction, HyperbolicFunction):
|
| 1936 |
+
expanded = expand_mul(expand_trig(orig))
|
| 1937 |
+
if expanded not in saw:
|
| 1938 |
+
res += [(expanded, 'expand_trig, expand_mul')]
|
| 1939 |
+
saw.add(expanded)
|
| 1940 |
+
|
| 1941 |
+
if orig.has(cos, sin):
|
| 1942 |
+
from sympy.simplify.fu import sincos_to_sum
|
| 1943 |
+
reduced = sincos_to_sum(orig)
|
| 1944 |
+
if reduced not in saw:
|
| 1945 |
+
res += [(reduced, 'trig power reduction')]
|
| 1946 |
+
saw.add(reduced)
|
| 1947 |
+
|
| 1948 |
+
return res
|
| 1949 |
+
|
| 1950 |
+
|
| 1951 |
+
def _meijerint_definite_2(f, x):
|
| 1952 |
+
"""
|
| 1953 |
+
Try to integrate f dx from zero to infinity.
|
| 1954 |
+
|
| 1955 |
+
The body of this function computes various 'simplifications'
|
| 1956 |
+
f1, f2, ... of f (e.g. by calling expand_mul(), trigexpand()
|
| 1957 |
+
- see _guess_expansion) and calls _meijerint_definite_3 with each of
|
| 1958 |
+
these in succession.
|
| 1959 |
+
If _meijerint_definite_3 succeeds with any of the simplified functions,
|
| 1960 |
+
returns this result.
|
| 1961 |
+
"""
|
| 1962 |
+
# This function does preparation for (2), calls
|
| 1963 |
+
# _meijerint_definite_3 for (2) and (3) combined.
|
| 1964 |
+
|
| 1965 |
+
# use a positive dummy - we integrate from 0 to oo
|
| 1966 |
+
# XXX if a nonnegative symbol is used there will be test failures
|
| 1967 |
+
dummy = _dummy('x', 'meijerint-definite2', f, positive=True)
|
| 1968 |
+
f = f.subs(x, dummy)
|
| 1969 |
+
x = dummy
|
| 1970 |
+
|
| 1971 |
+
if f == 0:
|
| 1972 |
+
return S.Zero, True
|
| 1973 |
+
|
| 1974 |
+
for g, explanation in _guess_expansion(f, x):
|
| 1975 |
+
_debug('Trying', explanation)
|
| 1976 |
+
res = _meijerint_definite_3(g, x)
|
| 1977 |
+
if res:
|
| 1978 |
+
return res
|
| 1979 |
+
|
| 1980 |
+
|
| 1981 |
+
def _meijerint_definite_3(f, x):
|
| 1982 |
+
"""
|
| 1983 |
+
Try to integrate f dx from zero to infinity.
|
| 1984 |
+
|
| 1985 |
+
This function calls _meijerint_definite_4 to try to compute the
|
| 1986 |
+
integral. If this fails, it tries using linearity.
|
| 1987 |
+
"""
|
| 1988 |
+
res = _meijerint_definite_4(f, x)
|
| 1989 |
+
if res and res[1] != False:
|
| 1990 |
+
return res
|
| 1991 |
+
if f.is_Add:
|
| 1992 |
+
_debug('Expanding and evaluating all terms.')
|
| 1993 |
+
ress = [_meijerint_definite_4(g, x) for g in f.args]
|
| 1994 |
+
if all(r is not None for r in ress):
|
| 1995 |
+
conds = []
|
| 1996 |
+
res = S.Zero
|
| 1997 |
+
for r, c in ress:
|
| 1998 |
+
res += r
|
| 1999 |
+
conds += [c]
|
| 2000 |
+
c = And(*conds)
|
| 2001 |
+
if c != False:
|
| 2002 |
+
return res, c
|
| 2003 |
+
|
| 2004 |
+
|
| 2005 |
+
def _my_unpolarify(f):
|
| 2006 |
+
return _eval_cond(unpolarify(f))
|
| 2007 |
+
|
| 2008 |
+
|
| 2009 |
+
@timeit
|
| 2010 |
+
def _meijerint_definite_4(f, x, only_double=False):
|
| 2011 |
+
"""
|
| 2012 |
+
Try to integrate f dx from zero to infinity.
|
| 2013 |
+
|
| 2014 |
+
Explanation
|
| 2015 |
+
===========
|
| 2016 |
+
|
| 2017 |
+
This function tries to apply the integration theorems found in literature,
|
| 2018 |
+
i.e. it tries to rewrite f as either one or a product of two G-functions.
|
| 2019 |
+
|
| 2020 |
+
The parameter ``only_double`` is used internally in the recursive algorithm
|
| 2021 |
+
to disable trying to rewrite f as a single G-function.
|
| 2022 |
+
"""
|
| 2023 |
+
from sympy.simplify import hyperexpand
|
| 2024 |
+
# This function does (2) and (3)
|
| 2025 |
+
_debug('Integrating', f)
|
| 2026 |
+
# Try single G function.
|
| 2027 |
+
if not only_double:
|
| 2028 |
+
gs = _rewrite1(f, x, recursive=False)
|
| 2029 |
+
if gs is not None:
|
| 2030 |
+
fac, po, g, cond = gs
|
| 2031 |
+
_debug('Could rewrite as single G function:', fac, po, g)
|
| 2032 |
+
res = S.Zero
|
| 2033 |
+
for C, s, f in g:
|
| 2034 |
+
if C == 0:
|
| 2035 |
+
continue
|
| 2036 |
+
C, f = _rewrite_saxena_1(fac*C, po*x**s, f, x)
|
| 2037 |
+
res += C*_int0oo_1(f, x)
|
| 2038 |
+
cond = And(cond, _check_antecedents_1(f, x))
|
| 2039 |
+
if cond == False:
|
| 2040 |
+
break
|
| 2041 |
+
cond = _my_unpolarify(cond)
|
| 2042 |
+
if cond == False:
|
| 2043 |
+
_debug('But cond is always False.')
|
| 2044 |
+
else:
|
| 2045 |
+
_debug('Result before branch substitutions is:', res)
|
| 2046 |
+
return _my_unpolarify(hyperexpand(res)), cond
|
| 2047 |
+
|
| 2048 |
+
# Try two G functions.
|
| 2049 |
+
gs = _rewrite2(f, x)
|
| 2050 |
+
if gs is not None:
|
| 2051 |
+
for full_pb in [False, True]:
|
| 2052 |
+
fac, po, g1, g2, cond = gs
|
| 2053 |
+
_debug('Could rewrite as two G functions:', fac, po, g1, g2)
|
| 2054 |
+
res = S.Zero
|
| 2055 |
+
for C1, s1, f1 in g1:
|
| 2056 |
+
for C2, s2, f2 in g2:
|
| 2057 |
+
r = _rewrite_saxena(fac*C1*C2, po*x**(s1 + s2),
|
| 2058 |
+
f1, f2, x, full_pb)
|
| 2059 |
+
if r is None:
|
| 2060 |
+
_debug('Non-rational exponents.')
|
| 2061 |
+
return
|
| 2062 |
+
C, f1_, f2_ = r
|
| 2063 |
+
_debug('Saxena subst for yielded:', C, f1_, f2_)
|
| 2064 |
+
cond = And(cond, _check_antecedents(f1_, f2_, x))
|
| 2065 |
+
if cond == False:
|
| 2066 |
+
break
|
| 2067 |
+
res += C*_int0oo(f1_, f2_, x)
|
| 2068 |
+
else:
|
| 2069 |
+
continue
|
| 2070 |
+
break
|
| 2071 |
+
cond = _my_unpolarify(cond)
|
| 2072 |
+
if cond == False:
|
| 2073 |
+
_debugf('But cond is always False (full_pb=%s).', full_pb)
|
| 2074 |
+
else:
|
| 2075 |
+
_debugf('Result before branch substitutions is: %s', (res, ))
|
| 2076 |
+
if only_double:
|
| 2077 |
+
return res, cond
|
| 2078 |
+
return _my_unpolarify(hyperexpand(res)), cond
|
| 2079 |
+
|
| 2080 |
+
|
| 2081 |
+
def meijerint_inversion(f, x, t):
|
| 2082 |
+
r"""
|
| 2083 |
+
Compute the inverse laplace transform
|
| 2084 |
+
$\int_{c+i\infty}^{c-i\infty} f(x) e^{tx}\, dx$,
|
| 2085 |
+
for real c larger than the real part of all singularities of ``f``.
|
| 2086 |
+
|
| 2087 |
+
Note that ``t`` is always assumed real and positive.
|
| 2088 |
+
|
| 2089 |
+
Return None if the integral does not exist or could not be evaluated.
|
| 2090 |
+
|
| 2091 |
+
Examples
|
| 2092 |
+
========
|
| 2093 |
+
|
| 2094 |
+
>>> from sympy.abc import x, t
|
| 2095 |
+
>>> from sympy.integrals.meijerint import meijerint_inversion
|
| 2096 |
+
>>> meijerint_inversion(1/x, x, t)
|
| 2097 |
+
Heaviside(t)
|
| 2098 |
+
"""
|
| 2099 |
+
f_ = f
|
| 2100 |
+
t_ = t
|
| 2101 |
+
t = Dummy('t', polar=True) # We don't want sqrt(t**2) = abs(t) etc
|
| 2102 |
+
f = f.subs(t_, t)
|
| 2103 |
+
_debug('Laplace-inverting', f)
|
| 2104 |
+
if not _is_analytic(f, x):
|
| 2105 |
+
_debug('But expression is not analytic.')
|
| 2106 |
+
return None
|
| 2107 |
+
# Exponentials correspond to shifts; we filter them out and then
|
| 2108 |
+
# shift the result later. If we are given an Add this will not
|
| 2109 |
+
# work, but the calling code will take care of that.
|
| 2110 |
+
shift = S.Zero
|
| 2111 |
+
|
| 2112 |
+
if f.is_Mul:
|
| 2113 |
+
args = list(f.args)
|
| 2114 |
+
elif isinstance(f, exp):
|
| 2115 |
+
args = [f]
|
| 2116 |
+
else:
|
| 2117 |
+
args = None
|
| 2118 |
+
|
| 2119 |
+
if args:
|
| 2120 |
+
newargs = []
|
| 2121 |
+
exponentials = []
|
| 2122 |
+
while args:
|
| 2123 |
+
arg = args.pop()
|
| 2124 |
+
if isinstance(arg, exp):
|
| 2125 |
+
arg2 = expand(arg)
|
| 2126 |
+
if arg2.is_Mul:
|
| 2127 |
+
args += arg2.args
|
| 2128 |
+
continue
|
| 2129 |
+
try:
|
| 2130 |
+
a, b = _get_coeff_exp(arg.args[0], x)
|
| 2131 |
+
except _CoeffExpValueError:
|
| 2132 |
+
b = 0
|
| 2133 |
+
if b == 1:
|
| 2134 |
+
exponentials.append(a)
|
| 2135 |
+
else:
|
| 2136 |
+
newargs.append(arg)
|
| 2137 |
+
elif arg.is_Pow:
|
| 2138 |
+
arg2 = expand(arg)
|
| 2139 |
+
if arg2.is_Mul:
|
| 2140 |
+
args += arg2.args
|
| 2141 |
+
continue
|
| 2142 |
+
if x not in arg.base.free_symbols:
|
| 2143 |
+
try:
|
| 2144 |
+
a, b = _get_coeff_exp(arg.exp, x)
|
| 2145 |
+
except _CoeffExpValueError:
|
| 2146 |
+
b = 0
|
| 2147 |
+
if b == 1:
|
| 2148 |
+
exponentials.append(a*log(arg.base))
|
| 2149 |
+
newargs.append(arg)
|
| 2150 |
+
else:
|
| 2151 |
+
newargs.append(arg)
|
| 2152 |
+
shift = Add(*exponentials)
|
| 2153 |
+
f = Mul(*newargs)
|
| 2154 |
+
|
| 2155 |
+
if x not in f.free_symbols:
|
| 2156 |
+
_debug('Expression consists of constant and exp shift:', f, shift)
|
| 2157 |
+
cond = Eq(im(shift), 0)
|
| 2158 |
+
if cond == False:
|
| 2159 |
+
_debug('but shift is nonreal, cannot be a Laplace transform')
|
| 2160 |
+
return None
|
| 2161 |
+
res = f*DiracDelta(t + shift)
|
| 2162 |
+
_debug('Result is a delta function, possibly conditional:', res, cond)
|
| 2163 |
+
# cond is True or Eq
|
| 2164 |
+
return Piecewise((res.subs(t, t_), cond))
|
| 2165 |
+
|
| 2166 |
+
gs = _rewrite1(f, x)
|
| 2167 |
+
if gs is not None:
|
| 2168 |
+
fac, po, g, cond = gs
|
| 2169 |
+
_debug('Could rewrite as single G function:', fac, po, g)
|
| 2170 |
+
res = S.Zero
|
| 2171 |
+
for C, s, f in g:
|
| 2172 |
+
C, f = _rewrite_inversion(fac*C, po*x**s, f, x)
|
| 2173 |
+
res += C*_int_inversion(f, x, t)
|
| 2174 |
+
cond = And(cond, _check_antecedents_inversion(f, x))
|
| 2175 |
+
if cond == False:
|
| 2176 |
+
break
|
| 2177 |
+
cond = _my_unpolarify(cond)
|
| 2178 |
+
if cond == False:
|
| 2179 |
+
_debug('But cond is always False.')
|
| 2180 |
+
else:
|
| 2181 |
+
_debug('Result before branch substitution:', res)
|
| 2182 |
+
from sympy.simplify import hyperexpand
|
| 2183 |
+
res = _my_unpolarify(hyperexpand(res))
|
| 2184 |
+
if not res.has(Heaviside):
|
| 2185 |
+
res *= Heaviside(t)
|
| 2186 |
+
res = res.subs(t, t + shift)
|
| 2187 |
+
if not isinstance(cond, bool):
|
| 2188 |
+
cond = cond.subs(t, t + shift)
|
| 2189 |
+
from .transforms import InverseLaplaceTransform
|
| 2190 |
+
return Piecewise((res.subs(t, t_), cond),
|
| 2191 |
+
(InverseLaplaceTransform(f_.subs(t, t_), x, t_, None), True))
|
.venv/lib/python3.12/site-packages/sympy/integrals/meijerint_doc.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.expr import Expr
|
| 11 |
+
from sympy.core.relational import Eq
|
| 12 |
+
from sympy.core.symbol import Symbol
|
| 13 |
+
from sympy.printing.latex import latex
|
| 14 |
+
|
| 15 |
+
t: dict[tuple[type[Basic], ...], list[Any]] = {}
|
| 16 |
+
_create_lookup_table(t)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
doc = ""
|
| 20 |
+
for about, category in t.items():
|
| 21 |
+
if about == ():
|
| 22 |
+
doc += 'Elementary functions:\n\n'
|
| 23 |
+
else:
|
| 24 |
+
doc += 'Functions involving ' + ', '.join('`%s`' % latex(
|
| 25 |
+
list(category[0][0].atoms(func))[0]) for func in about) + ':\n\n'
|
| 26 |
+
for formula, gs, cond, hint in category:
|
| 27 |
+
if not isinstance(gs, list):
|
| 28 |
+
g: Expr = Symbol('\\text{generated}')
|
| 29 |
+
else:
|
| 30 |
+
g = Add(*[fac*f for (fac, f) in gs])
|
| 31 |
+
obj = Eq(formula, g)
|
| 32 |
+
if cond is True:
|
| 33 |
+
cond = ""
|
| 34 |
+
else:
|
| 35 |
+
cond = ',\\text{ if } %s' % latex(cond)
|
| 36 |
+
doc += ".. math::\n %s%s\n\n" % (latex(obj), cond)
|
| 37 |
+
|
| 38 |
+
__doc__ = doc
|