ZTWHHH commited on
Commit
75bc553
·
verified ·
1 Parent(s): 28ffaf7

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. vllm/lib/python3.10/site-packages/sympy/core/__pycache__/intfunc.cpython-310.pyc +0 -0
  2. vllm/lib/python3.10/site-packages/sympy/core/__pycache__/operations.cpython-310.pyc +0 -0
  3. vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  4. vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_arit.cpython-310.pyc +0 -0
  5. vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_exprtools.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_logic.cpython-310.pyc +0 -0
  7. vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_multidimensional.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_relational.cpython-310.pyc +0 -0
  9. vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_singleton.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_sympify.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/sympy/geometry/__init__.py +45 -0
  12. vllm/lib/python3.10/site-packages/sympy/geometry/exceptions.py +5 -0
  13. vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_ellipse.py +613 -0
  14. vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_entity.py +120 -0
  15. vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_geometrysets.py +38 -0
  16. vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_point.py +481 -0
  17. vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py +676 -0
  18. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc +0 -0
  19. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc +0 -0
  20. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc +0 -0
  21. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc +0 -0
  26. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand_doc.cpython-310.pyc +0 -0
  27. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc +0 -0
  28. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc +0 -0
  29. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc +0 -0
  31. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/traversaltools.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc +0 -0
  34. vllm/lib/python3.10/site-packages/sympy/simplify/hyperexpand.py +2494 -0
  35. vllm/lib/python3.10/site-packages/sympy/simplify/ratsimp.py +222 -0
  36. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py +0 -0
  37. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_combsimp.cpython-310.pyc +0 -0
  39. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_cse.cpython-310.pyc +0 -0
  40. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_epathtools.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_fu.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_function.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_gammasimp.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_hyperexpand.cpython-310.pyc +0 -0
  45. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_powsimp.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_radsimp.cpython-310.pyc +0 -0
  47. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_ratsimp.cpython-310.pyc +0 -0
  48. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_rewrite.cpython-310.pyc +0 -0
  49. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_simplify.cpython-310.pyc +0 -0
  50. vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_sqrtdenest.cpython-310.pyc +0 -0
vllm/lib/python3.10/site-packages/sympy/core/__pycache__/intfunc.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/core/__pycache__/operations.cpython-310.pyc ADDED
Binary file (20.3 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (166 Bytes). View file
 
vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_arit.cpython-310.pyc ADDED
Binary file (64.9 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_exprtools.cpython-310.pyc ADDED
Binary file (16.8 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_logic.cpython-310.pyc ADDED
Binary file (8.06 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_multidimensional.cpython-310.pyc ADDED
Binary file (1.24 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_relational.cpython-310.pyc ADDED
Binary file (45.5 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_singleton.cpython-310.pyc ADDED
Binary file (2.02 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_sympify.cpython-310.pyc ADDED
Binary file (32 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/geometry/__init__.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A geometry module for the SymPy library. This module contains all of the
3
+ entities and functions needed to construct basic geometrical data and to
4
+ perform simple informational queries.
5
+
6
+ Usage:
7
+ ======
8
+
9
+ Examples
10
+ ========
11
+
12
+ """
13
+ from sympy.geometry.point import Point, Point2D, Point3D
14
+ from sympy.geometry.line import Line, Ray, Segment, Line2D, Segment2D, Ray2D, \
15
+ Line3D, Segment3D, Ray3D
16
+ from sympy.geometry.plane import Plane
17
+ from sympy.geometry.ellipse import Ellipse, Circle
18
+ from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg
19
+ from sympy.geometry.util import are_similar, centroid, convex_hull, idiff, \
20
+ intersection, closest_points, farthest_points
21
+ from sympy.geometry.exceptions import GeometryError
22
+ from sympy.geometry.curve import Curve
23
+ from sympy.geometry.parabola import Parabola
24
+
25
+ __all__ = [
26
+ 'Point', 'Point2D', 'Point3D',
27
+
28
+ 'Line', 'Ray', 'Segment', 'Line2D', 'Segment2D', 'Ray2D', 'Line3D',
29
+ 'Segment3D', 'Ray3D',
30
+
31
+ 'Plane',
32
+
33
+ 'Ellipse', 'Circle',
34
+
35
+ 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg',
36
+
37
+ 'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection',
38
+ 'closest_points', 'farthest_points',
39
+
40
+ 'GeometryError',
41
+
42
+ 'Curve',
43
+
44
+ 'Parabola',
45
+ ]
vllm/lib/python3.10/site-packages/sympy/geometry/exceptions.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Geometry Errors."""
2
+
3
+ class GeometryError(ValueError):
4
+ """An exception raised by classes in the geometry module."""
5
+ pass
vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_ellipse.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import expand
2
+ from sympy.core.numbers import (Rational, oo, pi)
3
+ from sympy.core.relational import Eq
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import (Symbol, symbols)
6
+ from sympy.functions.elementary.complexes import Abs
7
+ from sympy.functions.elementary.miscellaneous import sqrt
8
+ from sympy.functions.elementary.trigonometric import sec
9
+ from sympy.geometry.line import Segment2D
10
+ from sympy.geometry.point import Point2D
11
+ from sympy.geometry import (Circle, Ellipse, GeometryError, Line, Point,
12
+ Polygon, Ray, RegularPolygon, Segment,
13
+ Triangle, intersection)
14
+ from sympy.testing.pytest import raises, slow
15
+ from sympy.integrals.integrals import integrate
16
+ from sympy.functions.special.elliptic_integrals import elliptic_e
17
+ from sympy.functions.elementary.miscellaneous import Max
18
+
19
+
20
+ def test_ellipse_equation_using_slope():
21
+ from sympy.abc import x, y
22
+
23
+ e1 = Ellipse(Point(1, 0), 3, 2)
24
+ assert str(e1.equation(_slope=1)) == str((-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1)
25
+
26
+ e2 = Ellipse(Point(0, 0), 4, 1)
27
+ assert str(e2.equation(_slope=1)) == str((-x + y)**2/2 + (x + y)**2/32 - 1)
28
+
29
+ e3 = Ellipse(Point(1, 5), 6, 2)
30
+ assert str(e3.equation(_slope=2)) == str((-2*x + y - 3)**2/20 + (x + 2*y - 11)**2/180 - 1)
31
+
32
+
33
+ def test_object_from_equation():
34
+ from sympy.abc import x, y, a, b, c, d, e
35
+ assert Circle(x**2 + y**2 + 3*x + 4*y - 8) == Circle(Point2D(S(-3) / 2, -2), sqrt(57) / 2)
36
+ assert Circle(x**2 + y**2 + 6*x + 8*y + 25) == Circle(Point2D(-3, -4), 0)
37
+ assert Circle(a**2 + b**2 + 6*a + 8*b + 25, x='a', y='b') == Circle(Point2D(-3, -4), 0)
38
+ assert Circle(x**2 + y**2 - 25) == Circle(Point2D(0, 0), 5)
39
+ assert Circle(x**2 + y**2) == Circle(Point2D(0, 0), 0)
40
+ assert Circle(a**2 + b**2, x='a', y='b') == Circle(Point2D(0, 0), 0)
41
+ assert Circle(x**2 + y**2 + 6*x + 8) == Circle(Point2D(-3, 0), 1)
42
+ assert Circle(x**2 + y**2 + 6*y + 8) == Circle(Point2D(0, -3), 1)
43
+ assert Circle((x - 1)**2 + y**2 - 9) == Circle(Point2D(1, 0), 3)
44
+ assert Circle(6*(x**2) + 6*(y**2) + 6*x + 8*y - 25) == Circle(Point2D(Rational(-1, 2), Rational(-2, 3)), 5*sqrt(7)/6)
45
+ assert Circle(Eq(a**2 + b**2, 25), x='a', y=b) == Circle(Point2D(0, 0), 5)
46
+ raises(GeometryError, lambda: Circle(x**2 + y**2 + 3*x + 4*y + 26))
47
+ raises(GeometryError, lambda: Circle(x**2 + y**2 + 25))
48
+ raises(GeometryError, lambda: Circle(a**2 + b**2 + 25, x='a', y='b'))
49
+ raises(GeometryError, lambda: Circle(x**2 + 6*y + 8))
50
+ raises(GeometryError, lambda: Circle(6*(x ** 2) + 4*(y**2) + 6*x + 8*y + 25))
51
+ raises(ValueError, lambda: Circle(a**2 + b**2 + 3*a + 4*b - 8))
52
+ # .equation() adds 'real=True' assumption; '==' would fail if assumptions differed
53
+ x, y = symbols('x y', real=True)
54
+ eq = a*x**2 + a*y**2 + c*x + d*y + e
55
+ assert expand(Circle(eq).equation()*a) == eq
56
+
57
+
58
+ @slow
59
+ def test_ellipse_geom():
60
+ x = Symbol('x', real=True)
61
+ y = Symbol('y', real=True)
62
+ t = Symbol('t', real=True)
63
+ y1 = Symbol('y1', real=True)
64
+ half = S.Half
65
+ p1 = Point(0, 0)
66
+ p2 = Point(1, 1)
67
+ p4 = Point(0, 1)
68
+
69
+ e1 = Ellipse(p1, 1, 1)
70
+ e2 = Ellipse(p2, half, 1)
71
+ e3 = Ellipse(p1, y1, y1)
72
+ c1 = Circle(p1, 1)
73
+ c2 = Circle(p2, 1)
74
+ c3 = Circle(Point(sqrt(2), sqrt(2)), 1)
75
+ l1 = Line(p1, p2)
76
+
77
+ # Test creation with three points
78
+ cen, rad = Point(3*half, 2), 5*half
79
+ assert Circle(Point(0, 0), Point(3, 0), Point(0, 4)) == Circle(cen, rad)
80
+ assert Circle(Point(0, 0), Point(1, 1), Point(2, 2)) == Segment2D(Point2D(0, 0), Point2D(2, 2))
81
+
82
+ raises(ValueError, lambda: Ellipse(None, None, None, 1))
83
+ raises(ValueError, lambda: Ellipse())
84
+ raises(GeometryError, lambda: Circle(Point(0, 0)))
85
+ raises(GeometryError, lambda: Circle(Symbol('x')*Symbol('y')))
86
+
87
+ # Basic Stuff
88
+ assert Ellipse(None, 1, 1).center == Point(0, 0)
89
+ assert e1 == c1
90
+ assert e1 != e2
91
+ assert e1 != l1
92
+ assert p4 in e1
93
+ assert e1 in e1
94
+ assert e2 in e2
95
+ assert 1 not in e2
96
+ assert p2 not in e2
97
+ assert e1.area == pi
98
+ assert e2.area == pi/2
99
+ assert e3.area == pi*y1*abs(y1)
100
+ assert c1.area == e1.area
101
+ assert c1.circumference == e1.circumference
102
+ assert e3.circumference == 2*pi*y1
103
+ assert e1.plot_interval() == e2.plot_interval() == [t, -pi, pi]
104
+ assert e1.plot_interval(x) == e2.plot_interval(x) == [x, -pi, pi]
105
+
106
+ assert c1.minor == 1
107
+ assert c1.major == 1
108
+ assert c1.hradius == 1
109
+ assert c1.vradius == 1
110
+
111
+ assert Ellipse((1, 1), 0, 0) == Point(1, 1)
112
+ assert Ellipse((1, 1), 1, 0) == Segment(Point(0, 1), Point(2, 1))
113
+ assert Ellipse((1, 1), 0, 1) == Segment(Point(1, 0), Point(1, 2))
114
+
115
+ # Private Functions
116
+ assert hash(c1) == hash(Circle(Point(1, 0), Point(0, 1), Point(0, -1)))
117
+ assert c1 in e1
118
+ assert (Line(p1, p2) in e1) is False
119
+ assert e1.__cmp__(e1) == 0
120
+ assert e1.__cmp__(Point(0, 0)) > 0
121
+
122
+ # Encloses
123
+ assert e1.encloses(Segment(Point(-0.5, -0.5), Point(0.5, 0.5))) is True
124
+ assert e1.encloses(Line(p1, p2)) is False
125
+ assert e1.encloses(Ray(p1, p2)) is False
126
+ assert e1.encloses(e1) is False
127
+ assert e1.encloses(
128
+ Polygon(Point(-0.5, -0.5), Point(-0.5, 0.5), Point(0.5, 0.5))) is True
129
+ assert e1.encloses(RegularPolygon(p1, 0.5, 3)) is True
130
+ assert e1.encloses(RegularPolygon(p1, 5, 3)) is False
131
+ assert e1.encloses(RegularPolygon(p2, 5, 3)) is False
132
+
133
+ assert e2.arbitrary_point() in e2
134
+ raises(ValueError, lambda: Ellipse(Point(x, y), 1, 1).arbitrary_point(parameter='x'))
135
+
136
+ # Foci
137
+ f1, f2 = Point(sqrt(12), 0), Point(-sqrt(12), 0)
138
+ ef = Ellipse(Point(0, 0), 4, 2)
139
+ assert ef.foci in [(f1, f2), (f2, f1)]
140
+
141
+ # Tangents
142
+ v = sqrt(2) / 2
143
+ p1_1 = Point(v, v)
144
+ p1_2 = p2 + Point(half, 0)
145
+ p1_3 = p2 + Point(0, 1)
146
+ assert e1.tangent_lines(p4) == c1.tangent_lines(p4)
147
+ assert e2.tangent_lines(p1_2) == [Line(Point(Rational(3, 2), 1), Point(Rational(3, 2), S.Half))]
148
+ assert e2.tangent_lines(p1_3) == [Line(Point(1, 2), Point(Rational(5, 4), 2))]
149
+ assert c1.tangent_lines(p1_1) != [Line(p1_1, Point(0, sqrt(2)))]
150
+ assert c1.tangent_lines(p1) == []
151
+ assert e2.is_tangent(Line(p1_2, p2 + Point(half, 1)))
152
+ assert e2.is_tangent(Line(p1_3, p2 + Point(half, 1)))
153
+ assert c1.is_tangent(Line(p1_1, Point(0, sqrt(2))))
154
+ assert e1.is_tangent(Line(Point(0, 0), Point(1, 1))) is False
155
+ assert c1.is_tangent(e1) is True
156
+ assert c1.is_tangent(Ellipse(Point(2, 0), 1, 1)) is True
157
+ assert c1.is_tangent(
158
+ Polygon(Point(1, 1), Point(1, -1), Point(2, 0))) is False
159
+ assert c1.is_tangent(
160
+ Polygon(Point(1, 1), Point(1, 0), Point(2, 0))) is False
161
+ assert Circle(Point(5, 5), 3).is_tangent(Circle(Point(0, 5), 1)) is False
162
+
163
+ assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(0, 0)) == \
164
+ [Line(Point(0, 0), Point(Rational(77, 25), Rational(132, 25))),
165
+ Line(Point(0, 0), Point(Rational(33, 5), Rational(22, 5)))]
166
+ assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(3, 4)) == \
167
+ [Line(Point(3, 4), Point(4, 4)), Line(Point(3, 4), Point(3, 5))]
168
+ assert Circle(Point(5, 5), 2).tangent_lines(Point(3, 3)) == \
169
+ [Line(Point(3, 3), Point(4, 3)), Line(Point(3, 3), Point(3, 4))]
170
+ assert Circle(Point(5, 5), 2).tangent_lines(Point(5 - 2*sqrt(2), 5)) == \
171
+ [Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 - sqrt(2))),
172
+ Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 + sqrt(2))), ]
173
+ assert Circle(Point(5, 5), 5).tangent_lines(Point(4, 0)) == \
174
+ [Line(Point(4, 0), Point(Rational(40, 13), Rational(5, 13))),
175
+ Line(Point(4, 0), Point(5, 0))]
176
+ assert Circle(Point(5, 5), 5).tangent_lines(Point(0, 6)) == \
177
+ [Line(Point(0, 6), Point(0, 7)),
178
+ Line(Point(0, 6), Point(Rational(5, 13), Rational(90, 13)))]
179
+
180
+ # for numerical calculations, we shouldn't demand exact equality,
181
+ # so only test up to the desired precision
182
+ def lines_close(l1, l2, prec):
183
+ """ tests whether l1 and 12 are within 10**(-prec)
184
+ of each other """
185
+ return abs(l1.p1 - l2.p1) < 10**(-prec) and abs(l1.p2 - l2.p2) < 10**(-prec)
186
+ def line_list_close(ll1, ll2, prec):
187
+ return all(lines_close(l1, l2, prec) for l1, l2 in zip(ll1, ll2))
188
+
189
+ e = Ellipse(Point(0, 0), 2, 1)
190
+ assert e.normal_lines(Point(0, 0)) == \
191
+ [Line(Point(0, 0), Point(0, 1)), Line(Point(0, 0), Point(1, 0))]
192
+ assert e.normal_lines(Point(1, 0)) == \
193
+ [Line(Point(0, 0), Point(1, 0))]
194
+ assert e.normal_lines((0, 1)) == \
195
+ [Line(Point(0, 0), Point(0, 1))]
196
+ assert line_list_close(e.normal_lines(Point(1, 1), 2), [
197
+ Line(Point(Rational(-51, 26), Rational(-1, 5)), Point(Rational(-25, 26), Rational(17, 83))),
198
+ Line(Point(Rational(28, 29), Rational(-7, 8)), Point(Rational(57, 29), Rational(-9, 2)))], 2)
199
+ # test the failure of Poly.intervals and checks a point on the boundary
200
+ p = Point(sqrt(3), S.Half)
201
+ assert p in e
202
+ assert line_list_close(e.normal_lines(p, 2), [
203
+ Line(Point(Rational(-341, 171), Rational(-1, 13)), Point(Rational(-170, 171), Rational(5, 64))),
204
+ Line(Point(Rational(26, 15), Rational(-1, 2)), Point(Rational(41, 15), Rational(-43, 26)))], 2)
205
+ # be sure to use the slope that isn't undefined on boundary
206
+ e = Ellipse((0, 0), 2, 2*sqrt(3)/3)
207
+ assert line_list_close(e.normal_lines((1, 1), 2), [
208
+ Line(Point(Rational(-64, 33), Rational(-20, 71)), Point(Rational(-31, 33), Rational(2, 13))),
209
+ Line(Point(1, -1), Point(2, -4))], 2)
210
+ # general ellipse fails except under certain conditions
211
+ e = Ellipse((0, 0), x, 1)
212
+ assert e.normal_lines((x + 1, 0)) == [Line(Point(0, 0), Point(1, 0))]
213
+ raises(NotImplementedError, lambda: e.normal_lines((x + 1, 1)))
214
+ # Properties
215
+ major = 3
216
+ minor = 1
217
+ e4 = Ellipse(p2, minor, major)
218
+ assert e4.focus_distance == sqrt(major**2 - minor**2)
219
+ ecc = e4.focus_distance / major
220
+ assert e4.eccentricity == ecc
221
+ assert e4.periapsis == major*(1 - ecc)
222
+ assert e4.apoapsis == major*(1 + ecc)
223
+ assert e4.semilatus_rectum == major*(1 - ecc ** 2)
224
+ # independent of orientation
225
+ e4 = Ellipse(p2, major, minor)
226
+ assert e4.focus_distance == sqrt(major**2 - minor**2)
227
+ ecc = e4.focus_distance / major
228
+ assert e4.eccentricity == ecc
229
+ assert e4.periapsis == major*(1 - ecc)
230
+ assert e4.apoapsis == major*(1 + ecc)
231
+
232
+ # Intersection
233
+ l1 = Line(Point(1, -5), Point(1, 5))
234
+ l2 = Line(Point(-5, -1), Point(5, -1))
235
+ l3 = Line(Point(-1, -1), Point(1, 1))
236
+ l4 = Line(Point(-10, 0), Point(0, 10))
237
+ pts_c1_l3 = [Point(sqrt(2)/2, sqrt(2)/2), Point(-sqrt(2)/2, -sqrt(2)/2)]
238
+
239
+ assert intersection(e2, l4) == []
240
+ assert intersection(c1, Point(1, 0)) == [Point(1, 0)]
241
+ assert intersection(c1, l1) == [Point(1, 0)]
242
+ assert intersection(c1, l2) == [Point(0, -1)]
243
+ assert intersection(c1, l3) in [pts_c1_l3, [pts_c1_l3[1], pts_c1_l3[0]]]
244
+ assert intersection(c1, c2) == [Point(0, 1), Point(1, 0)]
245
+ assert intersection(c1, c3) == [Point(sqrt(2)/2, sqrt(2)/2)]
246
+ assert e1.intersection(l1) == [Point(1, 0)]
247
+ assert e2.intersection(l4) == []
248
+ assert e1.intersection(Circle(Point(0, 2), 1)) == [Point(0, 1)]
249
+ assert e1.intersection(Circle(Point(5, 0), 1)) == []
250
+ assert e1.intersection(Ellipse(Point(2, 0), 1, 1)) == [Point(1, 0)]
251
+ assert e1.intersection(Ellipse(Point(5, 0), 1, 1)) == []
252
+ assert e1.intersection(Point(2, 0)) == []
253
+ assert e1.intersection(e1) == e1
254
+ assert intersection(Ellipse(Point(0, 0), 2, 1), Ellipse(Point(3, 0), 1, 2)) == [Point(2, 0)]
255
+ assert intersection(Circle(Point(0, 0), 2), Circle(Point(3, 0), 1)) == [Point(2, 0)]
256
+ assert intersection(Circle(Point(0, 0), 2), Circle(Point(7, 0), 1)) == []
257
+ assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 1, 0.2)
258
+ ) == [Point(5.0, 0, evaluate=False)]
259
+ assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 0.999, 0.2)) == []
260
+ assert Circle((0, 0), S.Half).intersection(
261
+ Triangle((-1, 0), (1, 0), (0, 1))) == [
262
+ Point(Rational(-1, 2), 0), Point(S.Half, 0)]
263
+ raises(TypeError, lambda: intersection(e2, Line((0, 0, 0), (0, 0, 1))))
264
+ raises(TypeError, lambda: intersection(e2, Rational(12)))
265
+ raises(TypeError, lambda: Ellipse.intersection(e2, 1))
266
+ # some special case intersections
267
+ csmall = Circle(p1, 3)
268
+ cbig = Circle(p1, 5)
269
+ cout = Circle(Point(5, 5), 1)
270
+ # one circle inside of another
271
+ assert csmall.intersection(cbig) == []
272
+ # separate circles
273
+ assert csmall.intersection(cout) == []
274
+ # coincident circles
275
+ assert csmall.intersection(csmall) == csmall
276
+
277
+ v = sqrt(2)
278
+ t1 = Triangle(Point(0, v), Point(0, -v), Point(v, 0))
279
+ points = intersection(t1, c1)
280
+ assert len(points) == 4
281
+ assert Point(0, 1) in points
282
+ assert Point(0, -1) in points
283
+ assert Point(v/2, v/2) in points
284
+ assert Point(v/2, -v/2) in points
285
+
286
+ circ = Circle(Point(0, 0), 5)
287
+ elip = Ellipse(Point(0, 0), 5, 20)
288
+ assert intersection(circ, elip) in \
289
+ [[Point(5, 0), Point(-5, 0)], [Point(-5, 0), Point(5, 0)]]
290
+ assert elip.tangent_lines(Point(0, 0)) == []
291
+ elip = Ellipse(Point(0, 0), 3, 2)
292
+ assert elip.tangent_lines(Point(3, 0)) == \
293
+ [Line(Point(3, 0), Point(3, -12))]
294
+
295
+ e1 = Ellipse(Point(0, 0), 5, 10)
296
+ e2 = Ellipse(Point(2, 1), 4, 8)
297
+ a = Rational(53, 17)
298
+ c = 2*sqrt(3991)/17
299
+ ans = [Point(a - c/8, a/2 + c), Point(a + c/8, a/2 - c)]
300
+ assert e1.intersection(e2) == ans
301
+ e2 = Ellipse(Point(x, y), 4, 8)
302
+ c = sqrt(3991)
303
+ ans = [Point(-c/68 + a, c*Rational(2, 17) + a/2), Point(c/68 + a, c*Rational(-2, 17) + a/2)]
304
+ assert [p.subs({x: 2, y:1}) for p in e1.intersection(e2)] == ans
305
+
306
+ # Combinations of above
307
+ assert e3.is_tangent(e3.tangent_lines(p1 + Point(y1, 0))[0])
308
+
309
+ e = Ellipse((1, 2), 3, 2)
310
+ assert e.tangent_lines(Point(10, 0)) == \
311
+ [Line(Point(10, 0), Point(1, 0)),
312
+ Line(Point(10, 0), Point(Rational(14, 5), Rational(18, 5)))]
313
+
314
+ # encloses_point
315
+ e = Ellipse((0, 0), 1, 2)
316
+ assert e.encloses_point(e.center)
317
+ assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10)))
318
+ assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0))
319
+ assert e.encloses_point(e.center + Point(e.hradius, 0)) is False
320
+ assert e.encloses_point(
321
+ e.center + Point(e.hradius + Rational(1, 10), 0)) is False
322
+ e = Ellipse((0, 0), 2, 1)
323
+ assert e.encloses_point(e.center)
324
+ assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10)))
325
+ assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0))
326
+ assert e.encloses_point(e.center + Point(e.hradius, 0)) is False
327
+ assert e.encloses_point(
328
+ e.center + Point(e.hradius + Rational(1, 10), 0)) is False
329
+ assert c1.encloses_point(Point(1, 0)) is False
330
+ assert c1.encloses_point(Point(0.3, 0.4)) is True
331
+
332
+ assert e.scale(2, 3) == Ellipse((0, 0), 4, 3)
333
+ assert e.scale(3, 6) == Ellipse((0, 0), 6, 6)
334
+ assert e.rotate(pi) == e
335
+ assert e.rotate(pi, (1, 2)) == Ellipse(Point(2, 4), 2, 1)
336
+ raises(NotImplementedError, lambda: e.rotate(pi/3))
337
+
338
+ # Circle rotation tests (Issue #11743)
339
+ # Link - https://github.com/sympy/sympy/issues/11743
340
+ cir = Circle(Point(1, 0), 1)
341
+ assert cir.rotate(pi/2) == Circle(Point(0, 1), 1)
342
+ assert cir.rotate(pi/3) == Circle(Point(S.Half, sqrt(3)/2), 1)
343
+ assert cir.rotate(pi/3, Point(1, 0)) == Circle(Point(1, 0), 1)
344
+ assert cir.rotate(pi/3, Point(0, 1)) == Circle(Point(S.Half + sqrt(3)/2, S.Half + sqrt(3)/2), 1)
345
+
346
+
347
+ def test_construction():
348
+ e1 = Ellipse(hradius=2, vradius=1, eccentricity=None)
349
+ assert e1.eccentricity == sqrt(3)/2
350
+
351
+ e2 = Ellipse(hradius=2, vradius=None, eccentricity=sqrt(3)/2)
352
+ assert e2.vradius == 1
353
+
354
+ e3 = Ellipse(hradius=None, vradius=1, eccentricity=sqrt(3)/2)
355
+ assert e3.hradius == 2
356
+
357
+ # filter(None, iterator) filters out anything falsey, including 0
358
+ # eccentricity would be filtered out in this case and the constructor would throw an error
359
+ e4 = Ellipse(Point(0, 0), hradius=1, eccentricity=0)
360
+ assert e4.vradius == 1
361
+
362
+ #tests for eccentricity > 1
363
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = S(3)/2))
364
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=sec(5)))
365
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=S.Pi-S(2)))
366
+
367
+ #tests for eccentricity = 1
368
+ #if vradius is not defined
369
+ assert Ellipse(None, 1, None, 1).length == 2
370
+ #if hradius is not defined
371
+ raises(GeometryError, lambda: Ellipse(None, None, 1, eccentricity = 1))
372
+
373
+ #tests for eccentricity < 0
374
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -3))
375
+ raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -0.5))
376
+
377
+ def test_ellipse_random_point():
378
+ y1 = Symbol('y1', real=True)
379
+ e3 = Ellipse(Point(0, 0), y1, y1)
380
+ rx, ry = Symbol('rx'), Symbol('ry')
381
+ for ind in range(0, 5):
382
+ r = e3.random_point()
383
+ # substitution should give zero*y1**2
384
+ assert e3.equation(rx, ry).subs(zip((rx, ry), r.args)).equals(0)
385
+ # test for the case with seed
386
+ r = e3.random_point(seed=1)
387
+ assert e3.equation(rx, ry).subs(zip((rx, ry), r.args)).equals(0)
388
+
389
+
390
+ def test_repr():
391
+ assert repr(Circle((0, 1), 2)) == 'Circle(Point2D(0, 1), 2)'
392
+
393
+
394
+ def test_transform():
395
+ c = Circle((1, 1), 2)
396
+ assert c.scale(-1) == Circle((-1, 1), 2)
397
+ assert c.scale(y=-1) == Circle((1, -1), 2)
398
+ assert c.scale(2) == Ellipse((2, 1), 4, 2)
399
+
400
+ assert Ellipse((0, 0), 2, 3).scale(2, 3, (4, 5)) == \
401
+ Ellipse(Point(-4, -10), 4, 9)
402
+ assert Circle((0, 0), 2).scale(2, 3, (4, 5)) == \
403
+ Ellipse(Point(-4, -10), 4, 6)
404
+ assert Ellipse((0, 0), 2, 3).scale(3, 3, (4, 5)) == \
405
+ Ellipse(Point(-8, -10), 6, 9)
406
+ assert Circle((0, 0), 2).scale(3, 3, (4, 5)) == \
407
+ Circle(Point(-8, -10), 6)
408
+ assert Circle(Point(-8, -10), 6).scale(Rational(1, 3), Rational(1, 3), (4, 5)) == \
409
+ Circle((0, 0), 2)
410
+ assert Circle((0, 0), 2).translate(4, 5) == \
411
+ Circle((4, 5), 2)
412
+ assert Circle((0, 0), 2).scale(3, 3) == \
413
+ Circle((0, 0), 6)
414
+
415
+
416
+ def test_bounds():
417
+ e1 = Ellipse(Point(0, 0), 3, 5)
418
+ e2 = Ellipse(Point(2, -2), 7, 7)
419
+ c1 = Circle(Point(2, -2), 7)
420
+ c2 = Circle(Point(-2, 0), Point(0, 2), Point(2, 0))
421
+ assert e1.bounds == (-3, -5, 3, 5)
422
+ assert e2.bounds == (-5, -9, 9, 5)
423
+ assert c1.bounds == (-5, -9, 9, 5)
424
+ assert c2.bounds == (-2, -2, 2, 2)
425
+
426
+
427
+ def test_reflect():
428
+ b = Symbol('b')
429
+ m = Symbol('m')
430
+ l = Line((0, b), slope=m)
431
+ t1 = Triangle((0, 0), (1, 0), (2, 3))
432
+ assert t1.area == -t1.reflect(l).area
433
+ e = Ellipse((1, 0), 1, 2)
434
+ assert e.area == -e.reflect(Line((1, 0), slope=0)).area
435
+ assert e.area == -e.reflect(Line((1, 0), slope=oo)).area
436
+ raises(NotImplementedError, lambda: e.reflect(Line((1, 0), slope=m)))
437
+ assert Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) == Circle(Point2D(1, 0), -1)
438
+
439
+
440
+ def test_is_tangent():
441
+ e1 = Ellipse(Point(0, 0), 3, 5)
442
+ c1 = Circle(Point(2, -2), 7)
443
+ assert e1.is_tangent(Point(0, 0)) is False
444
+ assert e1.is_tangent(Point(3, 0)) is False
445
+ assert e1.is_tangent(e1) is True
446
+ assert e1.is_tangent(Ellipse((0, 0), 1, 2)) is False
447
+ assert e1.is_tangent(Ellipse((0, 0), 3, 2)) is True
448
+ assert c1.is_tangent(Ellipse((2, -2), 7, 1)) is True
449
+ assert c1.is_tangent(Circle((11, -2), 2)) is True
450
+ assert c1.is_tangent(Circle((7, -2), 2)) is True
451
+ assert c1.is_tangent(Ray((-5, -2), (-15, -20))) is False
452
+ assert c1.is_tangent(Ray((-3, -2), (-15, -20))) is False
453
+ assert c1.is_tangent(Ray((-3, -22), (15, 20))) is False
454
+ assert c1.is_tangent(Ray((9, 20), (9, -20))) is True
455
+ assert c1.is_tangent(Ray((2, 5), (9, 5))) is True
456
+ assert c1.is_tangent(Segment((2, 5), (9, 5))) is True
457
+ assert e1.is_tangent(Segment((2, 2), (-7, 7))) is False
458
+ assert e1.is_tangent(Segment((0, 0), (1, 2))) is False
459
+ assert c1.is_tangent(Segment((0, 0), (-5, -2))) is False
460
+ assert e1.is_tangent(Segment((3, 0), (12, 12))) is False
461
+ assert e1.is_tangent(Segment((12, 12), (3, 0))) is False
462
+ assert e1.is_tangent(Segment((-3, 0), (3, 0))) is False
463
+ assert e1.is_tangent(Segment((-3, 5), (3, 5))) is True
464
+ assert e1.is_tangent(Line((10, 0), (10, 10))) is False
465
+ assert e1.is_tangent(Line((0, 0), (1, 1))) is False
466
+ assert e1.is_tangent(Line((-3, 0), (-2.99, -0.001))) is False
467
+ assert e1.is_tangent(Line((-3, 0), (-3, 1))) is True
468
+ assert e1.is_tangent(Polygon((0, 0), (5, 5), (5, -5))) is False
469
+ assert e1.is_tangent(Polygon((-100, -50), (-40, -334), (-70, -52))) is False
470
+ assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 1))) is False
471
+ assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 5))) is False
472
+ assert e1.is_tangent(Polygon((-3, 0), (0, -5), (3, 0), (0, 5))) is False
473
+ assert e1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is True
474
+ assert c1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is False
475
+ assert e1.is_tangent(Polygon((0, 0), (3, 0), (7, 7), (0, 5))) is False
476
+ assert e1.is_tangent(Polygon((3, 12), (3, -12), (6, 5))) is False
477
+ assert e1.is_tangent(Polygon((3, 12), (3, -12), (0, -5), (0, 5))) is False
478
+ assert e1.is_tangent(Polygon((3, 0), (5, 7), (6, -5))) is False
479
+ assert c1.is_tangent(Segment((0, 0), (-5, -2))) is False
480
+ assert e1.is_tangent(Segment((-3, 0), (3, 0))) is False
481
+ assert e1.is_tangent(Segment((-3, 5), (3, 5))) is True
482
+ assert e1.is_tangent(Polygon((0, 0), (5, 5), (5, -5))) is False
483
+ assert e1.is_tangent(Polygon((-100, -50), (-40, -334), (-70, -52))) is False
484
+ assert e1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is True
485
+ assert c1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is False
486
+ assert e1.is_tangent(Polygon((3, 12), (3, -12), (0, -5), (0, 5))) is False
487
+ assert e1.is_tangent(Polygon((3, 0), (5, 7), (6, -5))) is False
488
+ raises(TypeError, lambda: e1.is_tangent(Point(0, 0, 0)))
489
+ raises(TypeError, lambda: e1.is_tangent(Rational(5)))
490
+
491
+
492
+ def test_parameter_value():
493
+ t = Symbol('t')
494
+ e = Ellipse(Point(0, 0), 3, 5)
495
+ assert e.parameter_value((3, 0), t) == {t: 0}
496
+ raises(ValueError, lambda: e.parameter_value((4, 0), t))
497
+
498
+
499
+ @slow
500
+ def test_second_moment_of_area():
501
+ x, y = symbols('x, y')
502
+ e = Ellipse(Point(0, 0), 5, 4)
503
+ I_yy = 2*4*integrate(sqrt(25 - x**2)*x**2, (x, -5, 5))/5
504
+ I_xx = 2*5*integrate(sqrt(16 - y**2)*y**2, (y, -4, 4))/4
505
+ Y = 3*sqrt(1 - x**2/5**2)
506
+ I_xy = integrate(integrate(y, (y, -Y, Y))*x, (x, -5, 5))
507
+ assert I_yy == e.second_moment_of_area()[1]
508
+ assert I_xx == e.second_moment_of_area()[0]
509
+ assert I_xy == e.second_moment_of_area()[2]
510
+ #checking for other point
511
+ t1 = e.second_moment_of_area(Point(6,5))
512
+ t2 = (580*pi, 845*pi, 600*pi)
513
+ assert t1==t2
514
+
515
+
516
+ def test_section_modulus_and_polar_second_moment_of_area():
517
+ d = Symbol('d', positive=True)
518
+ c = Circle((3, 7), 8)
519
+ assert c.polar_second_moment_of_area() == 2048*pi
520
+ assert c.section_modulus() == (128*pi, 128*pi)
521
+ c = Circle((2, 9), d/2)
522
+ assert c.polar_second_moment_of_area() == pi*d**3*Abs(d)/64 + pi*d*Abs(d)**3/64
523
+ assert c.section_modulus() == (pi*d**3/S(32), pi*d**3/S(32))
524
+
525
+ a, b = symbols('a, b', positive=True)
526
+ e = Ellipse((4, 6), a, b)
527
+ assert e.section_modulus() == (pi*a*b**2/S(4), pi*a**2*b/S(4))
528
+ assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4)
529
+ e = e.rotate(pi/2) # no change in polar and section modulus
530
+ assert e.section_modulus() == (pi*a**2*b/S(4), pi*a*b**2/S(4))
531
+ assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4)
532
+
533
+ e = Ellipse((a, b), 2, 6)
534
+ assert e.section_modulus() == (18*pi, 6*pi)
535
+ assert e.polar_second_moment_of_area() == 120*pi
536
+
537
+ e = Ellipse(Point(0, 0), 2, 2)
538
+ assert e.section_modulus() == (2*pi, 2*pi)
539
+ assert e.section_modulus(Point(2, 2)) == (2*pi, 2*pi)
540
+ assert e.section_modulus((2, 2)) == (2*pi, 2*pi)
541
+
542
+
543
+ def test_circumference():
544
+ M = Symbol('M')
545
+ m = Symbol('m')
546
+ assert Ellipse(Point(0, 0), M, m).circumference == 4 * M * elliptic_e((M ** 2 - m ** 2) / M**2)
547
+
548
+ assert Ellipse(Point(0, 0), 5, 4).circumference == 20 * elliptic_e(S(9) / 25)
549
+
550
+ # circle
551
+ assert Ellipse(None, 1, None, 0).circumference == 2*pi
552
+
553
+ # test numerically
554
+ assert abs(Ellipse(None, hradius=5, vradius=3).circumference.evalf(16) - 25.52699886339813) < 1e-10
555
+
556
+
557
+ def test_issue_15259():
558
+ assert Circle((1, 2), 0) == Point(1, 2)
559
+
560
+
561
+ def test_issue_15797_equals():
562
+ Ri = 0.024127189424130748
563
+ Ci = (0.0864931002830291, 0.0819863295239654)
564
+ A = Point(0, 0.0578591400998346)
565
+ c = Circle(Ci, Ri) # evaluated
566
+ assert c.is_tangent(c.tangent_lines(A)[0]) == True
567
+ assert c.center.x.is_Rational
568
+ assert c.center.y.is_Rational
569
+ assert c.radius.is_Rational
570
+ u = Circle(Ci, Ri, evaluate=False) # unevaluated
571
+ assert u.center.x.is_Float
572
+ assert u.center.y.is_Float
573
+ assert u.radius.is_Float
574
+
575
+
576
+ def test_auxiliary_circle():
577
+ x, y, a, b = symbols('x y a b')
578
+ e = Ellipse((x, y), a, b)
579
+ # the general result
580
+ assert e.auxiliary_circle() == Circle((x, y), Max(a, b))
581
+ # a special case where Ellipse is a Circle
582
+ assert Circle((3, 4), 8).auxiliary_circle() == Circle((3, 4), 8)
583
+
584
+
585
+ def test_director_circle():
586
+ x, y, a, b = symbols('x y a b')
587
+ e = Ellipse((x, y), a, b)
588
+ # the general result
589
+ assert e.director_circle() == Circle((x, y), sqrt(a**2 + b**2))
590
+ # a special case where Ellipse is a Circle
591
+ assert Circle((3, 4), 8).director_circle() == Circle((3, 4), 8*sqrt(2))
592
+
593
+
594
+ def test_evolute():
595
+ #ellipse centered at h,k
596
+ x, y, h, k = symbols('x y h k',real = True)
597
+ a, b = symbols('a b')
598
+ e = Ellipse(Point(h, k), a, b)
599
+ t1 = (e.hradius*(x - e.center.x))**Rational(2, 3)
600
+ t2 = (e.vradius*(y - e.center.y))**Rational(2, 3)
601
+ E = t1 + t2 - (e.hradius**2 - e.vradius**2)**Rational(2, 3)
602
+ assert e.evolute() == E
603
+ #Numerical Example
604
+ e = Ellipse(Point(1, 1), 6, 3)
605
+ t1 = (6*(x - 1))**Rational(2, 3)
606
+ t2 = (3*(y - 1))**Rational(2, 3)
607
+ E = t1 + t2 - (27)**Rational(2, 3)
608
+ assert e.evolute() == E
609
+
610
+
611
+ def test_svg():
612
+ e1 = Ellipse(Point(1, 0), 3, 2)
613
+ assert e1._svg(2, "#FFAAFF") == '<ellipse fill="#FFAAFF" stroke="#555555" stroke-width="4.0" opacity="0.6" cx="1.00000000000000" cy="0" rx="3.00000000000000" ry="2.00000000000000"/>'
vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_entity.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (Rational, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.geometry import (Circle, Ellipse, Point, Line, Parabola,
5
+ Polygon, Ray, RegularPolygon, Segment, Triangle, Plane, Curve)
6
+ from sympy.geometry.entity import scale, GeometryEntity
7
+ from sympy.testing.pytest import raises
8
+
9
+
10
+ def test_entity():
11
+ x = Symbol('x', real=True)
12
+ y = Symbol('y', real=True)
13
+
14
+ assert GeometryEntity(x, y) in GeometryEntity(x, y)
15
+ raises(NotImplementedError, lambda: Point(0, 0) in GeometryEntity(x, y))
16
+
17
+ assert GeometryEntity(x, y) == GeometryEntity(x, y)
18
+ assert GeometryEntity(x, y).equals(GeometryEntity(x, y))
19
+
20
+ c = Circle((0, 0), 5)
21
+ assert GeometryEntity.encloses(c, Point(0, 0))
22
+ assert GeometryEntity.encloses(c, Segment((0, 0), (1, 1)))
23
+ assert GeometryEntity.encloses(c, Line((0, 0), (1, 1))) is False
24
+ assert GeometryEntity.encloses(c, Circle((0, 0), 4))
25
+ assert GeometryEntity.encloses(c, Polygon(Point(0, 0), Point(1, 0), Point(0, 1)))
26
+ assert GeometryEntity.encloses(c, RegularPolygon(Point(8, 8), 1, 3)) is False
27
+
28
+
29
+ def test_svg():
30
+ a = Symbol('a')
31
+ b = Symbol('b')
32
+ d = Symbol('d')
33
+
34
+ entity = Circle(Point(a, b), d)
35
+ assert entity._repr_svg_() is None
36
+
37
+ entity = Circle(Point(0, 0), S.Infinity)
38
+ assert entity._repr_svg_() is None
39
+
40
+
41
+ def test_subs():
42
+ x = Symbol('x', real=True)
43
+ y = Symbol('y', real=True)
44
+ p = Point(x, 2)
45
+ q = Point(1, 1)
46
+ r = Point(3, 4)
47
+ for o in [p,
48
+ Segment(p, q),
49
+ Ray(p, q),
50
+ Line(p, q),
51
+ Triangle(p, q, r),
52
+ RegularPolygon(p, 3, 6),
53
+ Polygon(p, q, r, Point(5, 4)),
54
+ Circle(p, 3),
55
+ Ellipse(p, 3, 4)]:
56
+ assert 'y' in str(o.subs(x, y))
57
+ assert p.subs({x: 1}) == Point(1, 2)
58
+ assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4)
59
+ assert Point(1, 2).subs((1, 2), Point(3, 4)) == Point(3, 4)
60
+ assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4)
61
+ assert Point(1, 2).subs({(1, 2)}) == Point(2, 2)
62
+ raises(ValueError, lambda: Point(1, 2).subs(1))
63
+ raises(ValueError, lambda: Point(1, 1).subs((Point(1, 1), Point(1,
64
+ 2)), 1, 2))
65
+
66
+
67
+ def test_transform():
68
+ assert scale(1, 2, (3, 4)).tolist() == \
69
+ [[1, 0, 0], [0, 2, 0], [0, -4, 1]]
70
+
71
+
72
+ def test_reflect_entity_overrides():
73
+ x = Symbol('x', real=True)
74
+ y = Symbol('y', real=True)
75
+ b = Symbol('b')
76
+ m = Symbol('m')
77
+ l = Line((0, b), slope=m)
78
+ p = Point(x, y)
79
+ r = p.reflect(l)
80
+ c = Circle((x, y), 3)
81
+ cr = c.reflect(l)
82
+ assert cr == Circle(r, -3)
83
+ assert c.area == -cr.area
84
+
85
+ pent = RegularPolygon((1, 2), 1, 5)
86
+ slope = S.ComplexInfinity
87
+ while slope is S.ComplexInfinity:
88
+ slope = Rational(*(x._random()/2).as_real_imag())
89
+ l = Line(pent.vertices[1], slope=slope)
90
+ rpent = pent.reflect(l)
91
+ assert rpent.center == pent.center.reflect(l)
92
+ rvert = [i.reflect(l) for i in pent.vertices]
93
+ for v in rpent.vertices:
94
+ for i in range(len(rvert)):
95
+ ri = rvert[i]
96
+ if ri.equals(v):
97
+ rvert.remove(ri)
98
+ break
99
+ assert not rvert
100
+ assert pent.area.equals(-rpent.area)
101
+
102
+
103
+ def test_geometry_EvalfMixin():
104
+ x = pi
105
+ t = Symbol('t')
106
+ for g in [
107
+ Point(x, x),
108
+ Plane(Point(0, x, 0), (0, 0, x)),
109
+ Curve((x*t, x), (t, 0, x)),
110
+ Ellipse((x, x), x, -x),
111
+ Circle((x, x), x),
112
+ Line((0, x), (x, 0)),
113
+ Segment((0, x), (x, 0)),
114
+ Ray((0, x), (x, 0)),
115
+ Parabola((0, x), Line((-x, 0), (x, 0))),
116
+ Polygon((0, 0), (0, x), (x, 0), (x, x)),
117
+ RegularPolygon((0, x), x, 4, x),
118
+ Triangle((0, 0), (x, 0), (x, x)),
119
+ ]:
120
+ assert str(g).replace('pi', '3.1') == str(g.n(2))
vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_geometrysets.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Rational
2
+ from sympy.core.singleton import S
3
+ from sympy.geometry import Circle, Line, Point, Polygon, Segment
4
+ from sympy.sets import FiniteSet, Union, Intersection, EmptySet
5
+
6
+
7
+ def test_booleans():
8
+ """ test basic unions and intersections """
9
+ half = S.Half
10
+
11
+ p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
12
+ p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)])
13
+ l1 = Line(Point(0,0), Point(1,1))
14
+ l2 = Line(Point(half, half), Point(5,5))
15
+ l3 = Line(p2, p3)
16
+ l4 = Line(p3, p4)
17
+ poly1 = Polygon(p1, p2, p3, p4)
18
+ poly2 = Polygon(p5, p6, p7)
19
+ poly3 = Polygon(p1, p2, p5)
20
+ assert Union(l1, l2).equals(l1)
21
+ assert Intersection(l1, l2).equals(l1)
22
+ assert Intersection(l1, l4) == FiniteSet(Point(1,1))
23
+ assert Intersection(Union(l1, l4), l3) == FiniteSet(Point(Rational(-1, 3), Rational(-1, 3)), Point(5, 1))
24
+ assert Intersection(l1, FiniteSet(Point(7,-7))) == EmptySet
25
+ assert Intersection(Circle(Point(0,0), 3), Line(p1,p2)) == FiniteSet(Point(-3,0), Point(3,0))
26
+ assert Intersection(l1, FiniteSet(p1)) == FiniteSet(p1)
27
+ assert Union(l1, FiniteSet(p1)) == l1
28
+
29
+ fs = FiniteSet(Point(Rational(1, 3), 1), Point(Rational(2, 3), 0), Point(Rational(9, 5), Rational(1, 5)), Point(Rational(7, 3), 1))
30
+ # test the intersection of polygons
31
+ assert Intersection(poly1, poly2) == fs
32
+ # make sure if we union polygons with subsets, the subsets go away
33
+ assert Union(poly1, poly2, fs) == Union(poly1, poly2)
34
+ # make sure that if we union with a FiniteSet that isn't a subset,
35
+ # that the points in the intersection stop being listed
36
+ assert Union(poly1, FiniteSet(Point(0,0), Point(3,5))) == Union(poly1, FiniteSet(Point(3,5)))
37
+ # intersect two polygons that share an edge
38
+ assert Intersection(poly1, poly3) == Union(FiniteSet(Point(Rational(3, 2), 1), Point(2, 1)), Segment(Point(0, 0), Point(1, 0)))
vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_point.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.core.numbers import (I, Rational, pi)
3
+ from sympy.core.parameters import evaluate
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.core.sympify import sympify
7
+ from sympy.functions.elementary.miscellaneous import sqrt
8
+ from sympy.geometry import Line, Point, Point2D, Point3D, Line3D, Plane
9
+ from sympy.geometry.entity import rotate, scale, translate, GeometryEntity
10
+ from sympy.matrices import Matrix
11
+ from sympy.utilities.iterables import subsets, permutations, cartes
12
+ from sympy.utilities.misc import Undecidable
13
+ from sympy.testing.pytest import raises, warns
14
+
15
+
16
+ def test_point():
17
+ x = Symbol('x', real=True)
18
+ y = Symbol('y', real=True)
19
+ x1 = Symbol('x1', real=True)
20
+ x2 = Symbol('x2', real=True)
21
+ y1 = Symbol('y1', real=True)
22
+ y2 = Symbol('y2', real=True)
23
+ half = S.Half
24
+ p1 = Point(x1, x2)
25
+ p2 = Point(y1, y2)
26
+ p3 = Point(0, 0)
27
+ p4 = Point(1, 1)
28
+ p5 = Point(0, 1)
29
+ line = Line(Point(1, 0), slope=1)
30
+
31
+ assert p1 in p1
32
+ assert p1 not in p2
33
+ assert p2.y == y2
34
+ assert (p3 + p4) == p4
35
+ assert (p2 - p1) == Point(y1 - x1, y2 - x2)
36
+ assert -p2 == Point(-y1, -y2)
37
+ raises(TypeError, lambda: Point(1))
38
+ raises(ValueError, lambda: Point([1]))
39
+ raises(ValueError, lambda: Point(3, I))
40
+ raises(ValueError, lambda: Point(2*I, I))
41
+ raises(ValueError, lambda: Point(3 + I, I))
42
+
43
+ assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
44
+ assert Point.midpoint(p3, p4) == Point(half, half)
45
+ assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2)
46
+ assert Point.midpoint(p2, p2) == p2
47
+ assert p2.midpoint(p2) == p2
48
+ assert p1.origin == Point(0, 0)
49
+
50
+ assert Point.distance(p3, p4) == sqrt(2)
51
+ assert Point.distance(p1, p1) == 0
52
+ assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2)
53
+ raises(TypeError, lambda: Point.distance(p1, 0))
54
+ raises(TypeError, lambda: Point.distance(p1, GeometryEntity()))
55
+
56
+ # distance should be symmetric
57
+ assert p1.distance(line) == line.distance(p1)
58
+ assert p4.distance(line) == line.distance(p4)
59
+
60
+ assert Point.taxicab_distance(p4, p3) == 2
61
+
62
+ assert Point.canberra_distance(p4, p5) == 1
63
+ raises(ValueError, lambda: Point.canberra_distance(p3, p3))
64
+
65
+ p1_1 = Point(x1, x1)
66
+ p1_2 = Point(y2, y2)
67
+ p1_3 = Point(x1 + 1, x1)
68
+ assert Point.is_collinear(p3)
69
+
70
+ with warns(UserWarning, test_stacklevel=False):
71
+ assert Point.is_collinear(p3, Point(p3, dim=4))
72
+ assert p3.is_collinear()
73
+ assert Point.is_collinear(p3, p4)
74
+ assert Point.is_collinear(p3, p4, p1_1, p1_2)
75
+ assert Point.is_collinear(p3, p4, p1_1, p1_3) is False
76
+ assert Point.is_collinear(p3, p3, p4, p5) is False
77
+
78
+ raises(TypeError, lambda: Point.is_collinear(line))
79
+ raises(TypeError, lambda: p1_1.is_collinear(line))
80
+
81
+ assert p3.intersection(Point(0, 0)) == [p3]
82
+ assert p3.intersection(p4) == []
83
+ assert p3.intersection(line) == []
84
+ with warns(UserWarning, test_stacklevel=False):
85
+ assert Point.intersection(Point(0, 0, 0), Point(0, 0)) == [Point(0, 0, 0)]
86
+
87
+ x_pos = Symbol('x', positive=True)
88
+ p2_1 = Point(x_pos, 0)
89
+ p2_2 = Point(0, x_pos)
90
+ p2_3 = Point(-x_pos, 0)
91
+ p2_4 = Point(0, -x_pos)
92
+ p2_5 = Point(x_pos, 5)
93
+ assert Point.is_concyclic(p2_1)
94
+ assert Point.is_concyclic(p2_1, p2_2)
95
+ assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
96
+ for pts in permutations((p2_1, p2_2, p2_3, p2_5)):
97
+ assert Point.is_concyclic(*pts) is False
98
+ assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False
99
+ assert Point(0, 0).is_concyclic((1, 1), (2, 2), (2, 1)) is False
100
+ assert Point.is_concyclic(Point(0, 0, 0, 0), Point(1, 0, 0, 0), Point(1, 1, 0, 0), Point(1, 1, 1, 0)) is False
101
+
102
+ assert p1.is_scalar_multiple(p1)
103
+ assert p1.is_scalar_multiple(2*p1)
104
+ assert not p1.is_scalar_multiple(p2)
105
+ assert Point.is_scalar_multiple(Point(1, 1), (-1, -1))
106
+ assert Point.is_scalar_multiple(Point(0, 0), (0, -1))
107
+ # test when is_scalar_multiple can't be determined
108
+ raises(Undecidable, lambda: Point.is_scalar_multiple(Point(sympify("x1%y1"), sympify("x2%y2")), Point(0, 1)))
109
+
110
+ assert Point(0, 1).orthogonal_direction == Point(1, 0)
111
+ assert Point(1, 0).orthogonal_direction == Point(0, 1)
112
+
113
+ assert p1.is_zero is None
114
+ assert p3.is_zero
115
+ assert p4.is_zero is False
116
+ assert p1.is_nonzero is None
117
+ assert p3.is_nonzero is False
118
+ assert p4.is_nonzero
119
+
120
+ assert p4.scale(2, 3) == Point(2, 3)
121
+ assert p3.scale(2, 3) == p3
122
+
123
+ assert p4.rotate(pi, Point(0.5, 0.5)) == p3
124
+ assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2)
125
+ assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2)
126
+
127
+ assert p4 * 5 == Point(5, 5)
128
+ assert p4 / 5 == Point(0.2, 0.2)
129
+ assert 5 * p4 == Point(5, 5)
130
+
131
+ raises(ValueError, lambda: Point(0, 0) + 10)
132
+
133
+ # Point differences should be simplified
134
+ assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1)
135
+
136
+ a, b = S.Half, Rational(1, 3)
137
+ assert Point(a, b).evalf(2) == \
138
+ Point(a.n(2), b.n(2), evaluate=False)
139
+ raises(ValueError, lambda: Point(1, 2) + 1)
140
+
141
+ # test project
142
+ assert Point.project((0, 1), (1, 0)) == Point(0, 0)
143
+ assert Point.project((1, 1), (1, 0)) == Point(1, 0)
144
+ raises(ValueError, lambda: Point.project(p1, Point(0, 0)))
145
+
146
+ # test transformations
147
+ p = Point(1, 0)
148
+ assert p.rotate(pi/2) == Point(0, 1)
149
+ assert p.rotate(pi/2, p) == p
150
+ p = Point(1, 1)
151
+ assert p.scale(2, 3) == Point(2, 3)
152
+ assert p.translate(1, 2) == Point(2, 3)
153
+ assert p.translate(1) == Point(2, 1)
154
+ assert p.translate(y=1) == Point(1, 2)
155
+ assert p.translate(*p.args) == Point(2, 2)
156
+
157
+ # Check invalid input for transform
158
+ raises(ValueError, lambda: p3.transform(p3))
159
+ raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
160
+
161
+ # test __contains__
162
+ assert 0 in Point(0, 0, 0, 0)
163
+ assert 1 not in Point(0, 0, 0, 0)
164
+
165
+ # test affine_rank
166
+ assert Point.affine_rank() == -1
167
+
168
+
169
+ def test_point3D():
170
+ x = Symbol('x', real=True)
171
+ y = Symbol('y', real=True)
172
+ x1 = Symbol('x1', real=True)
173
+ x2 = Symbol('x2', real=True)
174
+ x3 = Symbol('x3', real=True)
175
+ y1 = Symbol('y1', real=True)
176
+ y2 = Symbol('y2', real=True)
177
+ y3 = Symbol('y3', real=True)
178
+ half = S.Half
179
+ p1 = Point3D(x1, x2, x3)
180
+ p2 = Point3D(y1, y2, y3)
181
+ p3 = Point3D(0, 0, 0)
182
+ p4 = Point3D(1, 1, 1)
183
+ p5 = Point3D(0, 1, 2)
184
+
185
+ assert p1 in p1
186
+ assert p1 not in p2
187
+ assert p2.y == y2
188
+ assert (p3 + p4) == p4
189
+ assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3)
190
+ assert -p2 == Point3D(-y1, -y2, -y3)
191
+
192
+ assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
193
+ assert Point3D.midpoint(p3, p4) == Point3D(half, half, half)
194
+ assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2,
195
+ half + half*x3)
196
+ assert Point3D.midpoint(p2, p2) == p2
197
+ assert p2.midpoint(p2) == p2
198
+
199
+ assert Point3D.distance(p3, p4) == sqrt(3)
200
+ assert Point3D.distance(p1, p1) == 0
201
+ assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2)
202
+
203
+ p1_1 = Point3D(x1, x1, x1)
204
+ p1_2 = Point3D(y2, y2, y2)
205
+ p1_3 = Point3D(x1 + 1, x1, x1)
206
+ Point3D.are_collinear(p3)
207
+ assert Point3D.are_collinear(p3, p4)
208
+ assert Point3D.are_collinear(p3, p4, p1_1, p1_2)
209
+ assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False
210
+ assert Point3D.are_collinear(p3, p3, p4, p5) is False
211
+
212
+ assert p3.intersection(Point3D(0, 0, 0)) == [p3]
213
+ assert p3.intersection(p4) == []
214
+
215
+
216
+ assert p4 * 5 == Point3D(5, 5, 5)
217
+ assert p4 / 5 == Point3D(0.2, 0.2, 0.2)
218
+ assert 5 * p4 == Point3D(5, 5, 5)
219
+
220
+ raises(ValueError, lambda: Point3D(0, 0, 0) + 10)
221
+
222
+ # Test coordinate properties
223
+ assert p1.coordinates == (x1, x2, x3)
224
+ assert p2.coordinates == (y1, y2, y3)
225
+ assert p3.coordinates == (0, 0, 0)
226
+ assert p4.coordinates == (1, 1, 1)
227
+ assert p5.coordinates == (0, 1, 2)
228
+ assert p5.x == 0
229
+ assert p5.y == 1
230
+ assert p5.z == 2
231
+
232
+ # Point differences should be simplified
233
+ assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \
234
+ Point3D(0, -1, 1)
235
+
236
+ a, b, c = S.Half, Rational(1, 3), Rational(1, 4)
237
+ assert Point3D(a, b, c).evalf(2) == \
238
+ Point(a.n(2), b.n(2), c.n(2), evaluate=False)
239
+ raises(ValueError, lambda: Point3D(1, 2, 3) + 1)
240
+
241
+ # test transformations
242
+ p = Point3D(1, 1, 1)
243
+ assert p.scale(2, 3) == Point3D(2, 3, 1)
244
+ assert p.translate(1, 2) == Point3D(2, 3, 1)
245
+ assert p.translate(1) == Point3D(2, 1, 1)
246
+ assert p.translate(z=1) == Point3D(1, 1, 2)
247
+ assert p.translate(*p.args) == Point3D(2, 2, 2)
248
+
249
+ # Test __new__
250
+ assert Point3D(0.1, 0.2, evaluate=False, on_morph='ignore').args[0].is_Float
251
+
252
+ # Test length property returns correctly
253
+ assert p.length == 0
254
+ assert p1_1.length == 0
255
+ assert p1_2.length == 0
256
+
257
+ # Test are_colinear type error
258
+ raises(TypeError, lambda: Point3D.are_collinear(p, x))
259
+
260
+ # Test are_coplanar
261
+ assert Point.are_coplanar()
262
+ assert Point.are_coplanar((1, 2, 0), (1, 2, 0), (1, 3, 0))
263
+ assert Point.are_coplanar((1, 2, 0), (1, 2, 3))
264
+ with warns(UserWarning, test_stacklevel=False):
265
+ raises(ValueError, lambda: Point2D.are_coplanar((1, 2), (1, 2, 3)))
266
+ assert Point3D.are_coplanar((1, 2, 0), (1, 2, 3))
267
+ assert Point.are_coplanar((0, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 1)) is False
268
+ planar2 = Point3D(1, -1, 1)
269
+ planar3 = Point3D(-1, 1, 1)
270
+ assert Point3D.are_coplanar(p, planar2, planar3) == True
271
+ assert Point3D.are_coplanar(p, planar2, planar3, p3) == False
272
+ assert Point.are_coplanar(p, planar2)
273
+ planar2 = Point3D(1, 1, 2)
274
+ planar3 = Point3D(1, 1, 3)
275
+ assert Point3D.are_coplanar(p, planar2, planar3) # line, not plane
276
+ plane = Plane((1, 2, 1), (2, 1, 0), (3, 1, 2))
277
+ assert Point.are_coplanar(*[plane.projection(((-1)**i, i)) for i in range(4)])
278
+
279
+ # all 2D points are coplanar
280
+ assert Point.are_coplanar(Point(x, y), Point(x, x + y), Point(y, x + 2)) is True
281
+
282
+ # Test Intersection
283
+ assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)]
284
+
285
+ # Test Scale
286
+ assert planar2.scale(1, 1, 1) == planar2
287
+ assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1)
288
+ assert planar2.scale(1, 1, 1, p3) == planar2
289
+
290
+ # Test Transform
291
+ identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
292
+ assert p.transform(identity) == p
293
+ trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]])
294
+ assert p.transform(trans) == Point3D(2, 2, 2)
295
+ raises(ValueError, lambda: p.transform(p))
296
+ raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
297
+
298
+ # Test Equals
299
+ assert p.equals(x1) == False
300
+
301
+ # Test __sub__
302
+ p_4d = Point(0, 0, 0, 1)
303
+ with warns(UserWarning, test_stacklevel=False):
304
+ assert p - p_4d == Point(1, 1, 1, -1)
305
+ p_4d3d = Point(0, 0, 1, 0)
306
+ with warns(UserWarning, test_stacklevel=False):
307
+ assert p - p_4d3d == Point(1, 1, 0, 0)
308
+
309
+
310
+ def test_Point2D():
311
+
312
+ # Test Distance
313
+ p1 = Point2D(1, 5)
314
+ p2 = Point2D(4, 2.5)
315
+ p3 = (6, 3)
316
+ assert p1.distance(p2) == sqrt(61)/2
317
+ assert p2.distance(p3) == sqrt(17)/2
318
+
319
+ # Test coordinates
320
+ assert p1.x == 1
321
+ assert p1.y == 5
322
+ assert p2.x == 4
323
+ assert p2.y == S(5)/2
324
+ assert p1.coordinates == (1, 5)
325
+ assert p2.coordinates == (4, S(5)/2)
326
+
327
+ # test bounds
328
+ assert p1.bounds == (1, 5, 1, 5)
329
+
330
+ def test_issue_9214():
331
+ p1 = Point3D(4, -2, 6)
332
+ p2 = Point3D(1, 2, 3)
333
+ p3 = Point3D(7, 2, 3)
334
+
335
+ assert Point3D.are_collinear(p1, p2, p3) is False
336
+
337
+
338
+ def test_issue_11617():
339
+ p1 = Point3D(1,0,2)
340
+ p2 = Point2D(2,0)
341
+
342
+ with warns(UserWarning, test_stacklevel=False):
343
+ assert p1.distance(p2) == sqrt(5)
344
+
345
+
346
+ def test_transform():
347
+ p = Point(1, 1)
348
+ assert p.transform(rotate(pi/2)) == Point(-1, 1)
349
+ assert p.transform(scale(3, 2)) == Point(3, 2)
350
+ assert p.transform(translate(1, 2)) == Point(2, 3)
351
+ assert Point(1, 1).scale(2, 3, (4, 5)) == \
352
+ Point(-2, -7)
353
+ assert Point(1, 1).translate(4, 5) == \
354
+ Point(5, 6)
355
+
356
+
357
+ def test_concyclic_doctest_bug():
358
+ p1, p2 = Point(-1, 0), Point(1, 0)
359
+ p3, p4 = Point(0, 1), Point(-1, 2)
360
+ assert Point.is_concyclic(p1, p2, p3)
361
+ assert not Point.is_concyclic(p1, p2, p3, p4)
362
+
363
+
364
+ def test_arguments():
365
+ """Functions accepting `Point` objects in `geometry`
366
+ should also accept tuples and lists and
367
+ automatically convert them to points."""
368
+
369
+ singles2d = ((1,2), [1,2], Point(1,2))
370
+ singles2d2 = ((1,3), [1,3], Point(1,3))
371
+ doubles2d = cartes(singles2d, singles2d2)
372
+ p2d = Point2D(1,2)
373
+ singles3d = ((1,2,3), [1,2,3], Point(1,2,3))
374
+ doubles3d = subsets(singles3d, 2)
375
+ p3d = Point3D(1,2,3)
376
+ singles4d = ((1,2,3,4), [1,2,3,4], Point(1,2,3,4))
377
+ doubles4d = subsets(singles4d, 2)
378
+ p4d = Point(1,2,3,4)
379
+
380
+ # test 2D
381
+ test_single = ['distance', 'is_scalar_multiple', 'taxicab_distance', 'midpoint', 'intersection', 'dot', 'equals', '__add__', '__sub__']
382
+ test_double = ['is_concyclic', 'is_collinear']
383
+ for p in singles2d:
384
+ Point2D(p)
385
+ for func in test_single:
386
+ for p in singles2d:
387
+ getattr(p2d, func)(p)
388
+ for func in test_double:
389
+ for p in doubles2d:
390
+ getattr(p2d, func)(*p)
391
+
392
+ # test 3D
393
+ test_double = ['is_collinear']
394
+ for p in singles3d:
395
+ Point3D(p)
396
+ for func in test_single:
397
+ for p in singles3d:
398
+ getattr(p3d, func)(p)
399
+ for func in test_double:
400
+ for p in doubles3d:
401
+ getattr(p3d, func)(*p)
402
+
403
+ # test 4D
404
+ test_double = ['is_collinear']
405
+ for p in singles4d:
406
+ Point(p)
407
+ for func in test_single:
408
+ for p in singles4d:
409
+ getattr(p4d, func)(p)
410
+ for func in test_double:
411
+ for p in doubles4d:
412
+ getattr(p4d, func)(*p)
413
+
414
+ # test evaluate=False for ops
415
+ x = Symbol('x')
416
+ a = Point(0, 1)
417
+ assert a + (0.1, x) == Point(0.1, 1 + x, evaluate=False)
418
+ a = Point(0, 1)
419
+ assert a/10.0 == Point(0, 0.1, evaluate=False)
420
+ a = Point(0, 1)
421
+ assert a*10.0 == Point(0.0, 10.0, evaluate=False)
422
+
423
+ # test evaluate=False when changing dimensions
424
+ u = Point(.1, .2, evaluate=False)
425
+ u4 = Point(u, dim=4, on_morph='ignore')
426
+ assert u4.args == (.1, .2, 0, 0)
427
+ assert all(i.is_Float for i in u4.args[:2])
428
+ # and even when *not* changing dimensions
429
+ assert all(i.is_Float for i in Point(u).args)
430
+
431
+ # never raise error if creating an origin
432
+ assert Point(dim=3, on_morph='error')
433
+
434
+ # raise error with unmatched dimension
435
+ raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='error'))
436
+ # test unknown on_morph
437
+ raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='unknown'))
438
+ # test invalid expressions
439
+ raises(TypeError, lambda: Point(Basic(), Basic()))
440
+
441
+ def test_unit():
442
+ assert Point(1, 1).unit == Point(sqrt(2)/2, sqrt(2)/2)
443
+
444
+
445
+ def test_dot():
446
+ raises(TypeError, lambda: Point(1, 2).dot(Line((0, 0), (1, 1))))
447
+
448
+
449
+ def test__normalize_dimension():
450
+ assert Point._normalize_dimension(Point(1, 2), Point(3, 4)) == [
451
+ Point(1, 2), Point(3, 4)]
452
+ assert Point._normalize_dimension(
453
+ Point(1, 2), Point(3, 4, 0), on_morph='ignore') == [
454
+ Point(1, 2, 0), Point(3, 4, 0)]
455
+
456
+
457
+ def test_issue_22684():
458
+ # Used to give an error
459
+ with evaluate(False):
460
+ Point(1, 2)
461
+
462
+
463
+ def test_direction_cosine():
464
+ p1 = Point3D(0, 0, 0)
465
+ p2 = Point3D(1, 1, 1)
466
+
467
+ assert p1.direction_cosine(Point3D(1, 0, 0)) == [1, 0, 0]
468
+ assert p1.direction_cosine(Point3D(0, 1, 0)) == [0, 1, 0]
469
+ assert p1.direction_cosine(Point3D(0, 0, pi)) == [0, 0, 1]
470
+
471
+ assert p1.direction_cosine(Point3D(5, 0, 0)) == [1, 0, 0]
472
+ assert p1.direction_cosine(Point3D(0, sqrt(3), 0)) == [0, 1, 0]
473
+ assert p1.direction_cosine(Point3D(0, 0, 5)) == [0, 0, 1]
474
+
475
+ assert p1.direction_cosine(Point3D(2.4, 2.4, 0)) == [sqrt(2)/2, sqrt(2)/2, 0]
476
+ assert p1.direction_cosine(Point3D(1, 1, 1)) == [sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3]
477
+ assert p1.direction_cosine(Point3D(-12, 0 -15)) == [-4*sqrt(41)/41, -5*sqrt(41)/41, 0]
478
+
479
+ assert p2.direction_cosine(Point3D(0, 0, 0)) == [-sqrt(3) / 3, -sqrt(3) / 3, -sqrt(3) / 3]
480
+ assert p2.direction_cosine(Point3D(1, 1, 12)) == [0, 0, 1]
481
+ assert p2.direction_cosine(Point3D(12, 1, 12)) == [sqrt(2) / 2, 0, sqrt(2) / 2]
vllm/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (Float, Rational, oo, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+ from sympy.functions.elementary.complexes import Abs
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import (acos, cos, sin)
7
+ from sympy.functions.elementary.trigonometric import tan
8
+ from sympy.geometry import (Circle, Ellipse, GeometryError, Point, Point2D,
9
+ Polygon, Ray, RegularPolygon, Segment, Triangle,
10
+ are_similar, convex_hull, intersection, Line, Ray2D)
11
+ from sympy.testing.pytest import raises, slow, warns
12
+ from sympy.core.random import verify_numerically
13
+ from sympy.geometry.polygon import rad, deg
14
+ from sympy.integrals.integrals import integrate
15
+ from sympy.utilities.iterables import rotate_left
16
+
17
+
18
+ def feq(a, b):
19
+ """Test if two floating point values are 'equal'."""
20
+ t_float = Float("1.0E-10")
21
+ return -t_float < a - b < t_float
22
+
23
+ @slow
24
+ def test_polygon():
25
+ x = Symbol('x', real=True)
26
+ y = Symbol('y', real=True)
27
+ q = Symbol('q', real=True)
28
+ u = Symbol('u', real=True)
29
+ v = Symbol('v', real=True)
30
+ w = Symbol('w', real=True)
31
+ x1 = Symbol('x1', real=True)
32
+ half = S.Half
33
+ a, b, c = Point(0, 0), Point(2, 0), Point(3, 3)
34
+ t = Triangle(a, b, c)
35
+ assert Polygon(Point(0, 0)) == Point(0, 0)
36
+ assert Polygon(a, Point(1, 0), b, c) == t
37
+ assert Polygon(Point(1, 0), b, c, a) == t
38
+ assert Polygon(b, c, a, Point(1, 0)) == t
39
+ # 2 "remove folded" tests
40
+ assert Polygon(a, Point(3, 0), b, c) == t
41
+ assert Polygon(a, b, Point(3, -1), b, c) == t
42
+ # remove multiple collinear points
43
+ assert Polygon(Point(-4, 15), Point(-11, 15), Point(-15, 15),
44
+ Point(-15, 33/5), Point(-15, -87/10), Point(-15, -15),
45
+ Point(-42/5, -15), Point(-2, -15), Point(7, -15), Point(15, -15),
46
+ Point(15, -3), Point(15, 10), Point(15, 15)) == \
47
+ Polygon(Point(-15, -15), Point(15, -15), Point(15, 15), Point(-15, 15))
48
+
49
+ p1 = Polygon(
50
+ Point(0, 0), Point(3, -1),
51
+ Point(6, 0), Point(4, 5),
52
+ Point(2, 3), Point(0, 3))
53
+ p2 = Polygon(
54
+ Point(6, 0), Point(3, -1),
55
+ Point(0, 0), Point(0, 3),
56
+ Point(2, 3), Point(4, 5))
57
+ p3 = Polygon(
58
+ Point(0, 0), Point(3, 0),
59
+ Point(5, 2), Point(4, 4))
60
+ p4 = Polygon(
61
+ Point(0, 0), Point(4, 4),
62
+ Point(5, 2), Point(3, 0))
63
+ p5 = Polygon(
64
+ Point(0, 0), Point(4, 4),
65
+ Point(0, 4))
66
+ p6 = Polygon(
67
+ Point(-11, 1), Point(-9, 6.6),
68
+ Point(-4, -3), Point(-8.4, -8.7))
69
+ p7 = Polygon(
70
+ Point(x, y), Point(q, u),
71
+ Point(v, w))
72
+ p8 = Polygon(
73
+ Point(x, y), Point(v, w),
74
+ Point(q, u))
75
+ p9 = Polygon(
76
+ Point(0, 0), Point(4, 4),
77
+ Point(3, 0), Point(5, 2))
78
+ p10 = Polygon(
79
+ Point(0, 2), Point(2, 2),
80
+ Point(0, 0), Point(2, 0))
81
+ p11 = Polygon(Point(0, 0), 1, n=3)
82
+ p12 = Polygon(Point(0, 0), 1, 0, n=3)
83
+ p13 = Polygon(
84
+ Point(0, 0),Point(8, 8),
85
+ Point(23, 20),Point(0, 20))
86
+ p14 = Polygon(*rotate_left(p13.args, 1))
87
+
88
+
89
+ r = Ray(Point(-9, 6.6), Point(-9, 5.5))
90
+ #
91
+ # General polygon
92
+ #
93
+ assert p1 == p2
94
+ assert len(p1.args) == 6
95
+ assert len(p1.sides) == 6
96
+ assert p1.perimeter == 5 + 2*sqrt(10) + sqrt(29) + sqrt(8)
97
+ assert p1.area == 22
98
+ assert not p1.is_convex()
99
+ assert Polygon((-1, 1), (2, -1), (2, 1), (-1, -1), (3, 0)
100
+ ).is_convex() is False
101
+ # ensure convex for both CW and CCW point specification
102
+ assert p3.is_convex()
103
+ assert p4.is_convex()
104
+ dict5 = p5.angles
105
+ assert dict5[Point(0, 0)] == pi / 4
106
+ assert dict5[Point(0, 4)] == pi / 2
107
+ assert p5.encloses_point(Point(x, y)) is None
108
+ assert p5.encloses_point(Point(1, 3))
109
+ assert p5.encloses_point(Point(0, 0)) is False
110
+ assert p5.encloses_point(Point(4, 0)) is False
111
+ assert p1.encloses(Circle(Point(2.5, 2.5), 5)) is False
112
+ assert p1.encloses(Ellipse(Point(2.5, 2), 5, 6)) is False
113
+ assert p5.plot_interval('x') == [x, 0, 1]
114
+ assert p5.distance(
115
+ Polygon(Point(10, 10), Point(14, 14), Point(10, 14))) == 6 * sqrt(2)
116
+ assert p5.distance(
117
+ Polygon(Point(1, 8), Point(5, 8), Point(8, 12), Point(1, 12))) == 4
118
+ with warns(UserWarning, \
119
+ match="Polygons may intersect producing erroneous output"):
120
+ Polygon(Point(0, 0), Point(1, 0), Point(1, 1)).distance(
121
+ Polygon(Point(0, 0), Point(0, 1), Point(1, 1)))
122
+ assert hash(p5) == hash(Polygon(Point(0, 0), Point(4, 4), Point(0, 4)))
123
+ assert hash(p1) == hash(p2)
124
+ assert hash(p7) == hash(p8)
125
+ assert hash(p3) != hash(p9)
126
+ assert p5 == Polygon(Point(4, 4), Point(0, 4), Point(0, 0))
127
+ assert Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) in p5
128
+ assert p5 != Point(0, 4)
129
+ assert Point(0, 1) in p5
130
+ assert p5.arbitrary_point('t').subs(Symbol('t', real=True), 0) == \
131
+ Point(0, 0)
132
+ raises(ValueError, lambda: Polygon(
133
+ Point(x, 0), Point(0, y), Point(x, y)).arbitrary_point('x'))
134
+ assert p6.intersection(r) == [Point(-9, Rational(-84, 13)), Point(-9, Rational(33, 5))]
135
+ assert p10.area == 0
136
+ assert p11 == RegularPolygon(Point(0, 0), 1, 3, 0)
137
+ assert p11 == p12
138
+ assert p11.vertices[0] == Point(1, 0)
139
+ assert p11.args[0] == Point(0, 0)
140
+ p11.spin(pi/2)
141
+ assert p11.vertices[0] == Point(0, 1)
142
+ #
143
+ # Regular polygon
144
+ #
145
+ p1 = RegularPolygon(Point(0, 0), 10, 5)
146
+ p2 = RegularPolygon(Point(0, 0), 5, 5)
147
+ raises(GeometryError, lambda: RegularPolygon(Point(0, 0), Point(0,
148
+ 1), Point(1, 1)))
149
+ raises(GeometryError, lambda: RegularPolygon(Point(0, 0), 1, 2))
150
+ raises(ValueError, lambda: RegularPolygon(Point(0, 0), 1, 2.5))
151
+
152
+ assert p1 != p2
153
+ assert p1.interior_angle == pi*Rational(3, 5)
154
+ assert p1.exterior_angle == pi*Rational(2, 5)
155
+ assert p2.apothem == 5*cos(pi/5)
156
+ assert p2.circumcenter == p1.circumcenter == Point(0, 0)
157
+ assert p1.circumradius == p1.radius == 10
158
+ assert p2.circumcircle == Circle(Point(0, 0), 5)
159
+ assert p2.incircle == Circle(Point(0, 0), p2.apothem)
160
+ assert p2.inradius == p2.apothem == (5 * (1 + sqrt(5)) / 4)
161
+ p2.spin(pi / 10)
162
+ dict1 = p2.angles
163
+ assert dict1[Point(0, 5)] == 3 * pi / 5
164
+ assert p1.is_convex()
165
+ assert p1.rotation == 0
166
+ assert p1.encloses_point(Point(0, 0))
167
+ assert p1.encloses_point(Point(11, 0)) is False
168
+ assert p2.encloses_point(Point(0, 4.9))
169
+ p1.spin(pi/3)
170
+ assert p1.rotation == pi/3
171
+ assert p1.vertices[0] == Point(5, 5*sqrt(3))
172
+ for var in p1.args:
173
+ if isinstance(var, Point):
174
+ assert var == Point(0, 0)
175
+ else:
176
+ assert var in (5, 10, pi / 3)
177
+ assert p1 != Point(0, 0)
178
+ assert p1 != p5
179
+
180
+ # while spin works in place (notice that rotation is 2pi/3 below)
181
+ # rotate returns a new object
182
+ p1_old = p1
183
+ assert p1.rotate(pi/3) == RegularPolygon(Point(0, 0), 10, 5, pi*Rational(2, 3))
184
+ assert p1 == p1_old
185
+
186
+ assert p1.area == (-250*sqrt(5) + 1250)/(4*tan(pi/5))
187
+ assert p1.length == 20*sqrt(-sqrt(5)/8 + Rational(5, 8))
188
+ assert p1.scale(2, 2) == \
189
+ RegularPolygon(p1.center, p1.radius*2, p1._n, p1.rotation)
190
+ assert RegularPolygon((0, 0), 1, 4).scale(2, 3) == \
191
+ Polygon(Point(2, 0), Point(0, 3), Point(-2, 0), Point(0, -3))
192
+
193
+ assert repr(p1) == str(p1)
194
+
195
+ #
196
+ # Angles
197
+ #
198
+ angles = p4.angles
199
+ assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483"))
200
+ assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544"))
201
+ assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388"))
202
+ assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449"))
203
+
204
+ angles = p3.angles
205
+ assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483"))
206
+ assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544"))
207
+ assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388"))
208
+ assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449"))
209
+
210
+ # https://github.com/sympy/sympy/issues/24885
211
+ interior_angles_sum = sum(p13.angles.values())
212
+ assert feq(interior_angles_sum, (len(p13.angles) - 2)*pi )
213
+ interior_angles_sum = sum(p14.angles.values())
214
+ assert feq(interior_angles_sum, (len(p14.angles) - 2)*pi )
215
+
216
+ #
217
+ # Triangle
218
+ #
219
+ p1 = Point(0, 0)
220
+ p2 = Point(5, 0)
221
+ p3 = Point(0, 5)
222
+ t1 = Triangle(p1, p2, p3)
223
+ t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4))))
224
+ t3 = Triangle(p1, Point(x1, 0), Point(0, x1))
225
+ s1 = t1.sides
226
+ assert Triangle(p1, p2, p1) == Polygon(p1, p2, p1) == Segment(p1, p2)
227
+ raises(GeometryError, lambda: Triangle(Point(0, 0)))
228
+
229
+ # Basic stuff
230
+ assert Triangle(p1, p1, p1) == p1
231
+ assert Triangle(p2, p2*2, p2*3) == Segment(p2, p2*3)
232
+ assert t1.area == Rational(25, 2)
233
+ assert t1.is_right()
234
+ assert t2.is_right() is False
235
+ assert t3.is_right()
236
+ assert p1 in t1
237
+ assert t1.sides[0] in t1
238
+ assert Segment((0, 0), (1, 0)) in t1
239
+ assert Point(5, 5) not in t2
240
+ assert t1.is_convex()
241
+ assert feq(t1.angles[p1].evalf(), pi.evalf()/2)
242
+
243
+ assert t1.is_equilateral() is False
244
+ assert t2.is_equilateral()
245
+ assert t3.is_equilateral() is False
246
+ assert are_similar(t1, t2) is False
247
+ assert are_similar(t1, t3)
248
+ assert are_similar(t2, t3) is False
249
+ assert t1.is_similar(Point(0, 0)) is False
250
+ assert t1.is_similar(t2) is False
251
+
252
+ # Bisectors
253
+ bisectors = t1.bisectors()
254
+ assert bisectors[p1] == Segment(
255
+ p1, Point(Rational(5, 2), Rational(5, 2)))
256
+ assert t2.bisectors()[p2] == Segment(
257
+ Point(5, 0), Point(Rational(5, 4), 5*sqrt(3)/4))
258
+ p4 = Point(0, x1)
259
+ assert t3.bisectors()[p4] == Segment(p4, Point(x1*(sqrt(2) - 1), 0))
260
+ ic = (250 - 125*sqrt(2))/50
261
+ assert t1.incenter == Point(ic, ic)
262
+
263
+ # Inradius
264
+ assert t1.inradius == t1.incircle.radius == 5 - 5*sqrt(2)/2
265
+ assert t2.inradius == t2.incircle.radius == 5*sqrt(3)/6
266
+ assert t3.inradius == t3.incircle.radius == x1**2/((2 + sqrt(2))*Abs(x1))
267
+
268
+ # Exradius
269
+ assert t1.exradii[t1.sides[2]] == 5*sqrt(2)/2
270
+
271
+ # Excenters
272
+ assert t1.excenters[t1.sides[2]] == Point2D(25*sqrt(2), -5*sqrt(2)/2)
273
+
274
+ # Circumcircle
275
+ assert t1.circumcircle.center == Point(2.5, 2.5)
276
+
277
+ # Medians + Centroid
278
+ m = t1.medians
279
+ assert t1.centroid == Point(Rational(5, 3), Rational(5, 3))
280
+ assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
281
+ assert t3.medians[p1] == Segment(p1, Point(x1/2, x1/2))
282
+ assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid]
283
+ assert t1.medial == Triangle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5))
284
+
285
+ # Nine-point circle
286
+ assert t1.nine_point_circle == Circle(Point(2.5, 0),
287
+ Point(0, 2.5), Point(2.5, 2.5))
288
+ assert t1.nine_point_circle == Circle(Point(0, 0),
289
+ Point(0, 2.5), Point(2.5, 2.5))
290
+
291
+ # Perpendicular
292
+ altitudes = t1.altitudes
293
+ assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
294
+ assert altitudes[p2].equals(s1[0])
295
+ assert altitudes[p3] == s1[2]
296
+ assert t1.orthocenter == p1
297
+ t = S('''Triangle(
298
+ Point(100080156402737/5000000000000, 79782624633431/500000000000),
299
+ Point(39223884078253/2000000000000, 156345163124289/1000000000000),
300
+ Point(31241359188437/1250000000000, 338338270939941/1000000000000000))''')
301
+ assert t.orthocenter == S('''Point(-780660869050599840216997'''
302
+ '''79471538701955848721853/80368430960602242240789074233100000000000000,'''
303
+ '''20151573611150265741278060334545897615974257/16073686192120448448157'''
304
+ '''8148466200000000000)''')
305
+
306
+ # Ensure
307
+ assert len(intersection(*bisectors.values())) == 1
308
+ assert len(intersection(*altitudes.values())) == 1
309
+ assert len(intersection(*m.values())) == 1
310
+
311
+ # Distance
312
+ p1 = Polygon(
313
+ Point(0, 0), Point(1, 0),
314
+ Point(1, 1), Point(0, 1))
315
+ p2 = Polygon(
316
+ Point(0, Rational(5)/4), Point(1, Rational(5)/4),
317
+ Point(1, Rational(9)/4), Point(0, Rational(9)/4))
318
+ p3 = Polygon(
319
+ Point(1, 2), Point(2, 2),
320
+ Point(2, 1))
321
+ p4 = Polygon(
322
+ Point(1, 1), Point(Rational(6)/5, 1),
323
+ Point(1, Rational(6)/5))
324
+ pt1 = Point(half, half)
325
+ pt2 = Point(1, 1)
326
+
327
+ '''Polygon to Point'''
328
+ assert p1.distance(pt1) == half
329
+ assert p1.distance(pt2) == 0
330
+ assert p2.distance(pt1) == Rational(3)/4
331
+ assert p3.distance(pt2) == sqrt(2)/2
332
+
333
+ '''Polygon to Polygon'''
334
+ # p1.distance(p2) emits a warning
335
+ with warns(UserWarning, \
336
+ match="Polygons may intersect producing erroneous output"):
337
+ assert p1.distance(p2) == half/2
338
+
339
+ assert p1.distance(p3) == sqrt(2)/2
340
+
341
+ # p3.distance(p4) emits a warning
342
+ with warns(UserWarning, \
343
+ match="Polygons may intersect producing erroneous output"):
344
+ assert p3.distance(p4) == (sqrt(2)/2 - sqrt(Rational(2)/25)/2)
345
+
346
+
347
+ def test_convex_hull():
348
+ p = [Point(-5, -1), Point(-2, 1), Point(-2, -1), Point(-1, -3), \
349
+ Point(0, 0), Point(1, 1), Point(2, 2), Point(2, -1), Point(3, 1), \
350
+ Point(4, -1), Point(6, 2)]
351
+ ch = Polygon(p[0], p[3], p[9], p[10], p[6], p[1])
352
+ #test handling of duplicate points
353
+ p.append(p[3])
354
+
355
+ #more than 3 collinear points
356
+ another_p = [Point(-45, -85), Point(-45, 85), Point(-45, 26), \
357
+ Point(-45, -24)]
358
+ ch2 = Segment(another_p[0], another_p[1])
359
+
360
+ assert convex_hull(*another_p) == ch2
361
+ assert convex_hull(*p) == ch
362
+ assert convex_hull(p[0]) == p[0]
363
+ assert convex_hull(p[0], p[1]) == Segment(p[0], p[1])
364
+
365
+ # no unique points
366
+ assert convex_hull(*[p[-1]]*3) == p[-1]
367
+
368
+ # collection of items
369
+ assert convex_hull(*[Point(0, 0), \
370
+ Segment(Point(1, 0), Point(1, 1)), \
371
+ RegularPolygon(Point(2, 0), 2, 4)]) == \
372
+ Polygon(Point(0, 0), Point(2, -2), Point(4, 0), Point(2, 2))
373
+
374
+
375
+ def test_encloses():
376
+ # square with a dimpled left side
377
+ s = Polygon(Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1), \
378
+ Point(S.Half, S.Half))
379
+ # the following is True if the polygon isn't treated as closing on itself
380
+ assert s.encloses(Point(0, S.Half)) is False
381
+ assert s.encloses(Point(S.Half, S.Half)) is False # it's a vertex
382
+ assert s.encloses(Point(Rational(3, 4), S.Half)) is True
383
+
384
+
385
+ def test_triangle_kwargs():
386
+ assert Triangle(sss=(3, 4, 5)) == \
387
+ Triangle(Point(0, 0), Point(3, 0), Point(3, 4))
388
+ assert Triangle(asa=(30, 2, 30)) == \
389
+ Triangle(Point(0, 0), Point(2, 0), Point(1, sqrt(3)/3))
390
+ assert Triangle(sas=(1, 45, 2)) == \
391
+ Triangle(Point(0, 0), Point(2, 0), Point(sqrt(2)/2, sqrt(2)/2))
392
+ assert Triangle(sss=(1, 2, 5)) is None
393
+ assert deg(rad(180)) == 180
394
+
395
+
396
+ def test_transform():
397
+ pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)]
398
+ pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)]
399
+ assert Triangle(*pts).scale(2, 3, (4, 5)) == Triangle(*pts_out)
400
+ assert RegularPolygon((0, 0), 1, 4).scale(2, 3, (4, 5)) == \
401
+ Polygon(Point(-2, -10), Point(-4, -7), Point(-6, -10), Point(-4, -13))
402
+ # Checks for symmetric scaling
403
+ assert RegularPolygon((0, 0), 1, 4).scale(2, 2) == \
404
+ RegularPolygon(Point2D(0, 0), 2, 4, 0)
405
+
406
+ def test_reflect():
407
+ x = Symbol('x', real=True)
408
+ y = Symbol('y', real=True)
409
+ b = Symbol('b')
410
+ m = Symbol('m')
411
+ l = Line((0, b), slope=m)
412
+ p = Point(x, y)
413
+ r = p.reflect(l)
414
+ dp = l.perpendicular_segment(p).length
415
+ dr = l.perpendicular_segment(r).length
416
+
417
+ assert verify_numerically(dp, dr)
418
+
419
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=oo)) \
420
+ == Triangle(Point(5, 0), Point(4, 0), Point(4, 2))
421
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=oo)) \
422
+ == Triangle(Point(-1, 0), Point(-2, 0), Point(-2, 2))
423
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=0)) \
424
+ == Triangle(Point(1, 6), Point(2, 6), Point(2, 4))
425
+ assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=0)) \
426
+ == Triangle(Point(1, 0), Point(2, 0), Point(2, -2))
427
+
428
+ def test_bisectors():
429
+ p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
430
+ p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3))
431
+ q = Polygon(Point(1, 0), Point(2, 0), Point(3, 3), Point(-1, 5))
432
+ poly = Polygon(Point(3, 4), Point(0, 0), Point(8, 7), Point(-1, 1), Point(19, -19))
433
+ t = Triangle(p1, p2, p3)
434
+ assert t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1))
435
+ assert p.bisectors()[Point2D(0, 3)] == Ray2D(Point2D(0, 3), \
436
+ Point2D(sin(acos(2*sqrt(5)/5)/2), 3 - cos(acos(2*sqrt(5)/5)/2)))
437
+ assert q.bisectors()[Point2D(-1, 5)] == \
438
+ Ray2D(Point2D(-1, 5), Point2D(-1 + sqrt(29)*(5*sin(acos(9*sqrt(145)/145)/2) + \
439
+ 2*cos(acos(9*sqrt(145)/145)/2))/29, sqrt(29)*(-5*cos(acos(9*sqrt(145)/145)/2) + \
440
+ 2*sin(acos(9*sqrt(145)/145)/2))/29 + 5))
441
+ assert poly.bisectors()[Point2D(-1, 1)] == Ray2D(Point2D(-1, 1), \
442
+ Point2D(-1 + sin(acos(sqrt(26)/26)/2 + pi/4), 1 - sin(-acos(sqrt(26)/26)/2 + pi/4)))
443
+
444
+ def test_incenter():
445
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).incenter \
446
+ == Point(1 - sqrt(2)/2, 1 - sqrt(2)/2)
447
+
448
+ def test_inradius():
449
+ assert Triangle(Point(0, 0), Point(4, 0), Point(0, 3)).inradius == 1
450
+
451
+ def test_incircle():
452
+ assert Triangle(Point(0, 0), Point(2, 0), Point(0, 2)).incircle \
453
+ == Circle(Point(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2))
454
+
455
+ def test_exradii():
456
+ t = Triangle(Point(0, 0), Point(6, 0), Point(0, 2))
457
+ assert t.exradii[t.sides[2]] == (-2 + sqrt(10))
458
+
459
+ def test_medians():
460
+ t = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
461
+ assert t.medians[Point(0, 0)] == Segment(Point(0, 0), Point(S.Half, S.Half))
462
+
463
+ def test_medial():
464
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).medial \
465
+ == Triangle(Point(S.Half, 0), Point(S.Half, S.Half), Point(0, S.Half))
466
+
467
+ def test_nine_point_circle():
468
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).nine_point_circle \
469
+ == Circle(Point2D(Rational(1, 4), Rational(1, 4)), sqrt(2)/4)
470
+
471
+ def test_eulerline():
472
+ assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).eulerline \
473
+ == Line(Point2D(0, 0), Point2D(S.Half, S.Half))
474
+ assert Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))).eulerline \
475
+ == Point2D(5, 5*sqrt(3)/3)
476
+ assert Triangle(Point(4, -6), Point(4, -1), Point(-3, 3)).eulerline \
477
+ == Line(Point2D(Rational(64, 7), 3), Point2D(Rational(-29, 14), Rational(-7, 2)))
478
+
479
+ def test_intersection():
480
+ poly1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
481
+ poly2 = Polygon(Point(0, 1), Point(-5, 0),
482
+ Point(0, -4), Point(0, Rational(1, 5)),
483
+ Point(S.Half, -0.1), Point(1, 0), Point(0, 1))
484
+
485
+ assert poly1.intersection(poly2) == [Point2D(Rational(1, 3), 0),
486
+ Segment(Point(0, Rational(1, 5)), Point(0, 0)),
487
+ Segment(Point(1, 0), Point(0, 1))]
488
+ assert poly2.intersection(poly1) == [Point(Rational(1, 3), 0),
489
+ Segment(Point(0, 0), Point(0, Rational(1, 5))),
490
+ Segment(Point(1, 0), Point(0, 1))]
491
+ assert poly1.intersection(Point(0, 0)) == [Point(0, 0)]
492
+ assert poly1.intersection(Point(-12, -43)) == []
493
+ assert poly2.intersection(Line((-12, 0), (12, 0))) == [Point(-5, 0),
494
+ Point(0, 0), Point(Rational(1, 3), 0), Point(1, 0)]
495
+ assert poly2.intersection(Line((-12, 12), (12, 12))) == []
496
+ assert poly2.intersection(Ray((-3, 4), (1, 0))) == [Segment(Point(1, 0),
497
+ Point(0, 1))]
498
+ assert poly2.intersection(Circle((0, -1), 1)) == [Point(0, -2),
499
+ Point(0, 0)]
500
+ assert poly1.intersection(poly1) == [Segment(Point(0, 0), Point(1, 0)),
501
+ Segment(Point(0, 1), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))]
502
+ assert poly2.intersection(poly2) == [Segment(Point(-5, 0), Point(0, -4)),
503
+ Segment(Point(0, -4), Point(0, Rational(1, 5))),
504
+ Segment(Point(0, Rational(1, 5)), Point(S.Half, Rational(-1, 10))),
505
+ Segment(Point(0, 1), Point(-5, 0)),
506
+ Segment(Point(S.Half, Rational(-1, 10)), Point(1, 0)),
507
+ Segment(Point(1, 0), Point(0, 1))]
508
+ assert poly2.intersection(Triangle(Point(0, 1), Point(1, 0), Point(-1, 1))) \
509
+ == [Point(Rational(-5, 7), Rational(6, 7)), Segment(Point2D(0, 1), Point(1, 0))]
510
+ assert poly1.intersection(RegularPolygon((-12, -15), 3, 3)) == []
511
+
512
+
513
+ def test_parameter_value():
514
+ t = Symbol('t')
515
+ sq = Polygon((0, 0), (0, 1), (1, 1), (1, 0))
516
+ assert sq.parameter_value((0.5, 1), t) == {t: Rational(3, 8)}
517
+ q = Polygon((0, 0), (2, 1), (2, 4), (4, 0))
518
+ assert q.parameter_value((4, 0), t) == {t: -6 + 3*sqrt(5)} # ~= 0.708
519
+
520
+ raises(ValueError, lambda: sq.parameter_value((5, 6), t))
521
+ raises(ValueError, lambda: sq.parameter_value(Circle(Point(0, 0), 1), t))
522
+
523
+
524
+ def test_issue_12966():
525
+ poly = Polygon(Point(0, 0), Point(0, 10), Point(5, 10), Point(5, 5),
526
+ Point(10, 5), Point(10, 0))
527
+ t = Symbol('t')
528
+ pt = poly.arbitrary_point(t)
529
+ DELTA = 5/poly.perimeter
530
+ assert [pt.subs(t, DELTA*i) for i in range(int(1/DELTA))] == [
531
+ Point(0, 0), Point(0, 5), Point(0, 10), Point(5, 10),
532
+ Point(5, 5), Point(10, 5), Point(10, 0), Point(5, 0)]
533
+
534
+
535
+ def test_second_moment_of_area():
536
+ x, y = symbols('x, y')
537
+ # triangle
538
+ p1, p2, p3 = [(0, 0), (4, 0), (0, 2)]
539
+ p = (0, 0)
540
+ # equation of hypotenuse
541
+ eq_y = (1-x/4)*2
542
+ I_yy = integrate((x**2) * (integrate(1, (y, 0, eq_y))), (x, 0, 4))
543
+ I_xx = integrate(1 * (integrate(y**2, (y, 0, eq_y))), (x, 0, 4))
544
+ I_xy = integrate(x * (integrate(y, (y, 0, eq_y))), (x, 0, 4))
545
+
546
+ triangle = Polygon(p1, p2, p3)
547
+
548
+ assert (I_xx - triangle.second_moment_of_area(p)[0]) == 0
549
+ assert (I_yy - triangle.second_moment_of_area(p)[1]) == 0
550
+ assert (I_xy - triangle.second_moment_of_area(p)[2]) == 0
551
+
552
+ # rectangle
553
+ p1, p2, p3, p4=[(0, 0), (4, 0), (4, 2), (0, 2)]
554
+ I_yy = integrate((x**2) * integrate(1, (y, 0, 2)), (x, 0, 4))
555
+ I_xx = integrate(1 * integrate(y**2, (y, 0, 2)), (x, 0, 4))
556
+ I_xy = integrate(x * integrate(y, (y, 0, 2)), (x, 0, 4))
557
+
558
+ rectangle = Polygon(p1, p2, p3, p4)
559
+
560
+ assert (I_xx - rectangle.second_moment_of_area(p)[0]) == 0
561
+ assert (I_yy - rectangle.second_moment_of_area(p)[1]) == 0
562
+ assert (I_xy - rectangle.second_moment_of_area(p)[2]) == 0
563
+
564
+
565
+ r = RegularPolygon(Point(0, 0), 5, 3)
566
+ assert r.second_moment_of_area() == (1875*sqrt(3)/S(32), 1875*sqrt(3)/S(32), 0)
567
+
568
+
569
+ def test_first_moment():
570
+ a, b = symbols('a, b', positive=True)
571
+ # rectangle
572
+ p1 = Polygon((0, 0), (a, 0), (a, b), (0, b))
573
+ assert p1.first_moment_of_area() == (a*b**2/8, a**2*b/8)
574
+ assert p1.first_moment_of_area((a/3, b/4)) == (-3*a*b**2/32, -a**2*b/9)
575
+
576
+ p1 = Polygon((0, 0), (40, 0), (40, 30), (0, 30))
577
+ assert p1.first_moment_of_area() == (4500, 6000)
578
+
579
+ # triangle
580
+ p2 = Polygon((0, 0), (a, 0), (a/2, b))
581
+ assert p2.first_moment_of_area() == (4*a*b**2/81, a**2*b/24)
582
+ assert p2.first_moment_of_area((a/8, b/6)) == (-25*a*b**2/648, -5*a**2*b/768)
583
+
584
+ p2 = Polygon((0, 0), (12, 0), (12, 30))
585
+ assert p2.first_moment_of_area() == (S(1600)/3, -S(640)/3)
586
+
587
+
588
+ def test_section_modulus_and_polar_second_moment_of_area():
589
+ a, b = symbols('a, b', positive=True)
590
+ x, y = symbols('x, y')
591
+ rectangle = Polygon((0, b), (0, 0), (a, 0), (a, b))
592
+ assert rectangle.section_modulus(Point(x, y)) == (a*b**3/12/(-b/2 + y), a**3*b/12/(-a/2 + x))
593
+ assert rectangle.polar_second_moment_of_area() == a**3*b/12 + a*b**3/12
594
+
595
+ convex = RegularPolygon((0, 0), 1, 6)
596
+ assert convex.section_modulus() == (Rational(5, 8), sqrt(3)*Rational(5, 16))
597
+ assert convex.polar_second_moment_of_area() == 5*sqrt(3)/S(8)
598
+
599
+ concave = Polygon((0, 0), (1, 8), (3, 4), (4, 6), (7, 1))
600
+ assert concave.section_modulus() == (Rational(-6371, 429), Rational(-9778, 519))
601
+ assert concave.polar_second_moment_of_area() == Rational(-38669, 252)
602
+
603
+
604
+ def test_cut_section():
605
+ # concave polygon
606
+ p = Polygon((-1, -1), (1, Rational(5, 2)), (2, 1), (3, Rational(5, 2)), (4, 2), (5, 3), (-1, 3))
607
+ l = Line((0, 0), (Rational(9, 2), 3))
608
+ p1 = p.cut_section(l)[0]
609
+ p2 = p.cut_section(l)[1]
610
+ assert p1 == Polygon(
611
+ Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(1, Rational(5, 2)), Point2D(Rational(24, 13), Rational(16, 13)),
612
+ Point2D(Rational(12, 5), Rational(8, 5)), Point2D(3, Rational(5, 2)), Point2D(Rational(24, 7), Rational(16, 7)),
613
+ Point2D(Rational(9, 2), 3), Point2D(-1, 3), Point2D(-1, Rational(-2, 3)))
614
+ assert p2 == Polygon(Point2D(-1, -1), Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(Rational(24, 13), Rational(16, 13)),
615
+ Point2D(2, 1), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(4, 2), Point2D(5, 3),
616
+ Point2D(Rational(9, 2), 3), Point2D(-1, Rational(-2, 3)))
617
+
618
+ # convex polygon
619
+ p = RegularPolygon(Point2D(0, 0), 6, 6)
620
+ s = p.cut_section(Line((0, 0), slope=1))
621
+ assert s[0] == Polygon(Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(3, 3*sqrt(3)),
622
+ Point2D(-3, 3*sqrt(3)), Point2D(-6, 0), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)))
623
+ assert s[1] == Polygon(Point2D(6, 0), Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9),
624
+ Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)), Point2D(-3, -3*sqrt(3)), Point2D(3, -3*sqrt(3)))
625
+
626
+ # case where line does not intersects but coincides with the edge of polygon
627
+ a, b = 20, 10
628
+ t1, t2, t3, t4 = [(0, b), (0, 0), (a, 0), (a, b)]
629
+ p = Polygon(t1, t2, t3, t4)
630
+ p1, p2 = p.cut_section(Line((0, b), slope=0))
631
+ assert p1 == None
632
+ assert p2 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10))
633
+
634
+ p3, p4 = p.cut_section(Line((0, 0), slope=0))
635
+ assert p3 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10))
636
+ assert p4 == None
637
+
638
+ # case where the line does not intersect with a polygon at all
639
+ raises(ValueError, lambda: p.cut_section(Line((0, a), slope=0)))
640
+
641
+ def test_type_of_triangle():
642
+ # Isoceles triangle
643
+ p1 = Polygon(Point(0, 0), Point(5, 0), Point(2, 4))
644
+ assert p1.is_isosceles() == True
645
+ assert p1.is_scalene() == False
646
+ assert p1.is_equilateral() == False
647
+
648
+ # Scalene triangle
649
+ p2 = Polygon (Point(0, 0), Point(0, 2), Point(4, 0))
650
+ assert p2.is_isosceles() == False
651
+ assert p2.is_scalene() == True
652
+ assert p2.is_equilateral() == False
653
+
654
+ # Equilateral triagle
655
+ p3 = Polygon(Point(0, 0), Point(6, 0), Point(3, sqrt(27)))
656
+ assert p3.is_isosceles() == True
657
+ assert p3.is_scalene() == False
658
+ assert p3.is_equilateral() == True
659
+
660
+ def test_do_poly_distance():
661
+ # Non-intersecting polygons
662
+ square1 = Polygon (Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
663
+ triangle1 = Polygon(Point(1, 2), Point(2, 2), Point(2, 1))
664
+ assert square1._do_poly_distance(triangle1) == sqrt(2)/2
665
+
666
+ # Polygons which sides intersect
667
+ square2 = Polygon(Point(1, 0), Point(2, 0), Point(2, 1), Point(1, 1))
668
+ with warns(UserWarning, \
669
+ match="Polygons may intersect producing erroneous output", test_stacklevel=False):
670
+ assert square1._do_poly_distance(square2) == 0
671
+
672
+ # Polygons which bodies intersect
673
+ triangle2 = Polygon(Point(0, -1), Point(2, -1), Point(S.Half, S.Half))
674
+ with warns(UserWarning, \
675
+ match="Polygons may intersect producing erroneous output", test_stacklevel=False):
676
+ assert triangle2._do_poly_distance(square1) == 0
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.34 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc ADDED
Binary file (3.67 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc ADDED
Binary file (26 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc ADDED
Binary file (1.61 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc ADDED
Binary file (8.48 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc ADDED
Binary file (52.1 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc ADDED
Binary file (73.4 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand_doc.cpython-310.pyc ADDED
Binary file (722 Bytes). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc ADDED
Binary file (17.8 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc ADDED
Binary file (34.6 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc ADDED
Binary file (7.63 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc ADDED
Binary file (57.4 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc ADDED
Binary file (19.5 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/traversaltools.cpython-310.pyc ADDED
Binary file (587 Bytes). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc ADDED
Binary file (33.9 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/hyperexpand.py ADDED
@@ -0,0 +1,2494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Expand Hypergeometric (and Meijer G) functions into named
3
+ special functions.
4
+
5
+ The algorithm for doing this uses a collection of lookup tables of
6
+ hypergeometric functions, and various of their properties, to expand
7
+ many hypergeometric functions in terms of special functions.
8
+
9
+ It is based on the following paper:
10
+ Kelly B. Roach. Meijer G Function Representations.
11
+ In: Proceedings of the 1997 International Symposium on Symbolic and
12
+ Algebraic Computation, pages 205-211, New York, 1997. ACM.
13
+
14
+ It is described in great(er) detail in the Sphinx documentation.
15
+ """
16
+ # SUMMARY OF EXTENSIONS FOR MEIJER G FUNCTIONS
17
+ #
18
+ # o z**rho G(ap, bq; z) = G(ap + rho, bq + rho; z)
19
+ #
20
+ # o denote z*d/dz by D
21
+ #
22
+ # o It is helpful to keep in mind that ap and bq play essentially symmetric
23
+ # roles: G(1/z) has slightly altered parameters, with ap and bq interchanged.
24
+ #
25
+ # o There are four shift operators:
26
+ # A_J = b_J - D, J = 1, ..., n
27
+ # B_J = 1 - a_j + D, J = 1, ..., m
28
+ # C_J = -b_J + D, J = m+1, ..., q
29
+ # D_J = a_J - 1 - D, J = n+1, ..., p
30
+ #
31
+ # A_J, C_J increment b_J
32
+ # B_J, D_J decrement a_J
33
+ #
34
+ # o The corresponding four inverse-shift operators are defined if there
35
+ # is no cancellation. Thus e.g. an index a_J (upper or lower) can be
36
+ # incremented if a_J != b_i for i = 1, ..., q.
37
+ #
38
+ # o Order reduction: if b_j - a_i is a non-negative integer, where
39
+ # j <= m and i > n, the corresponding quotient of gamma functions reduces
40
+ # to a polynomial. Hence the G function can be expressed using a G-function
41
+ # of lower order.
42
+ # Similarly if j > m and i <= n.
43
+ #
44
+ # Secondly, there are paired index theorems [Adamchik, The evaluation of
45
+ # integrals of Bessel functions via G-function identities]. Suppose there
46
+ # are three parameters a, b, c, where a is an a_i, i <= n, b is a b_j,
47
+ # j <= m and c is a denominator parameter (i.e. a_i, i > n or b_j, j > m).
48
+ # Suppose further all three differ by integers.
49
+ # Then the order can be reduced.
50
+ # TODO work this out in detail.
51
+ #
52
+ # o An index quadruple is called suitable if its order cannot be reduced.
53
+ # If there exists a sequence of shift operators transforming one index
54
+ # quadruple into another, we say one is reachable from the other.
55
+ #
56
+ # o Deciding if one index quadruple is reachable from another is tricky. For
57
+ # this reason, we use hand-built routines to match and instantiate formulas.
58
+ #
59
+ from collections import defaultdict
60
+ from itertools import product
61
+ from functools import reduce
62
+ from math import prod
63
+
64
+ from sympy import SYMPY_DEBUG
65
+ from sympy.core import (S, Dummy, symbols, sympify, Tuple, expand, I, pi, Mul,
66
+ EulerGamma, oo, zoo, expand_func, Add, nan, Expr, Rational)
67
+ from sympy.core.mod import Mod
68
+ from sympy.core.sorting import default_sort_key
69
+ from sympy.functions import (exp, sqrt, root, log, lowergamma, cos,
70
+ besseli, gamma, uppergamma, expint, erf, sin, besselj, Ei, Ci, Si, Shi,
71
+ sinh, cosh, Chi, fresnels, fresnelc, polar_lift, exp_polar, floor, ceiling,
72
+ rf, factorial, lerchphi, Piecewise, re, elliptic_k, elliptic_e)
73
+ from sympy.functions.elementary.complexes import polarify, unpolarify
74
+ from sympy.functions.special.hyper import (hyper, HyperRep_atanh,
75
+ HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1,
76
+ HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2,
77
+ HyperRep_cosasin, HyperRep_sinasin, meijerg)
78
+ from sympy.matrices import Matrix, eye, zeros
79
+ from sympy.polys import apart, poly, Poly
80
+ from sympy.series import residue
81
+ from sympy.simplify.powsimp import powdenest
82
+ from sympy.utilities.iterables import sift
83
+
84
+ # function to define "buckets"
85
+ def _mod1(x):
86
+ # TODO see if this can work as Mod(x, 1); this will require
87
+ # different handling of the "buckets" since these need to
88
+ # be sorted and that fails when there is a mixture of
89
+ # integers and expressions with parameters. With the current
90
+ # Mod behavior, Mod(k, 1) == Mod(1, 1) == 0 if k is an integer.
91
+ # Although the sorting can be done with Basic.compare, this may
92
+ # still require different handling of the sorted buckets.
93
+ if x.is_Number:
94
+ return Mod(x, 1)
95
+ c, x = x.as_coeff_Add()
96
+ return Mod(c, 1) + x
97
+
98
+
99
+ # leave add formulae at the top for easy reference
100
+ def add_formulae(formulae):
101
+ """ Create our knowledge base. """
102
+ a, b, c, z = symbols('a b c, z', cls=Dummy)
103
+
104
+ def add(ap, bq, res):
105
+ func = Hyper_Function(ap, bq)
106
+ formulae.append(Formula(func, z, res, (a, b, c)))
107
+
108
+ def addb(ap, bq, B, C, M):
109
+ func = Hyper_Function(ap, bq)
110
+ formulae.append(Formula(func, z, None, (a, b, c), B, C, M))
111
+
112
+ # Luke, Y. L. (1969), The Special Functions and Their Approximations,
113
+ # Volume 1, section 6.2
114
+
115
+ # 0F0
116
+ add((), (), exp(z))
117
+
118
+ # 1F0
119
+ add((a, ), (), HyperRep_power1(-a, z))
120
+
121
+ # 2F1
122
+ addb((a, a - S.Half), (2*a, ),
123
+ Matrix([HyperRep_power2(a, z),
124
+ HyperRep_power2(a + S.Half, z)/2]),
125
+ Matrix([[1, 0]]),
126
+ Matrix([[(a - S.Half)*z/(1 - z), (S.Half - a)*z/(1 - z)],
127
+ [a/(1 - z), a*(z - 2)/(1 - z)]]))
128
+ addb((1, 1), (2, ),
129
+ Matrix([HyperRep_log1(z), 1]), Matrix([[-1/z, 0]]),
130
+ Matrix([[0, z/(z - 1)], [0, 0]]))
131
+ addb((S.Half, 1), (S('3/2'), ),
132
+ Matrix([HyperRep_atanh(z), 1]),
133
+ Matrix([[1, 0]]),
134
+ Matrix([[Rational(-1, 2), 1/(1 - z)/2], [0, 0]]))
135
+ addb((S.Half, S.Half), (S('3/2'), ),
136
+ Matrix([HyperRep_asin1(z), HyperRep_power1(Rational(-1, 2), z)]),
137
+ Matrix([[1, 0]]),
138
+ Matrix([[Rational(-1, 2), S.Half], [0, z/(1 - z)/2]]))
139
+ addb((a, S.Half + a), (S.Half, ),
140
+ Matrix([HyperRep_sqrts1(-a, z), -HyperRep_sqrts2(-a - S.Half, z)]),
141
+ Matrix([[1, 0]]),
142
+ Matrix([[0, -a],
143
+ [z*(-2*a - 1)/2/(1 - z), S.Half - z*(-2*a - 1)/(1 - z)]]))
144
+
145
+ # A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990).
146
+ # Integrals and Series: More Special Functions, Vol. 3,.
147
+ # Gordon and Breach Science Publisher
148
+ addb([a, -a], [S.Half],
149
+ Matrix([HyperRep_cosasin(a, z), HyperRep_sinasin(a, z)]),
150
+ Matrix([[1, 0]]),
151
+ Matrix([[0, -a], [a*z/(1 - z), 1/(1 - z)/2]]))
152
+ addb([1, 1], [3*S.Half],
153
+ Matrix([HyperRep_asin2(z), 1]), Matrix([[1, 0]]),
154
+ Matrix([[(z - S.Half)/(1 - z), 1/(1 - z)/2], [0, 0]]))
155
+
156
+ # Complete elliptic integrals K(z) and E(z), both a 2F1 function
157
+ addb([S.Half, S.Half], [S.One],
158
+ Matrix([elliptic_k(z), elliptic_e(z)]),
159
+ Matrix([[2/pi, 0]]),
160
+ Matrix([[Rational(-1, 2), -1/(2*z-2)],
161
+ [Rational(-1, 2), S.Half]]))
162
+ addb([Rational(-1, 2), S.Half], [S.One],
163
+ Matrix([elliptic_k(z), elliptic_e(z)]),
164
+ Matrix([[0, 2/pi]]),
165
+ Matrix([[Rational(-1, 2), -1/(2*z-2)],
166
+ [Rational(-1, 2), S.Half]]))
167
+
168
+ # 3F2
169
+ addb([Rational(-1, 2), 1, 1], [S.Half, 2],
170
+ Matrix([z*HyperRep_atanh(z), HyperRep_log1(z), 1]),
171
+ Matrix([[Rational(-2, 3), -S.One/(3*z), Rational(2, 3)]]),
172
+ Matrix([[S.Half, 0, z/(1 - z)/2],
173
+ [0, 0, z/(z - 1)],
174
+ [0, 0, 0]]))
175
+ # actually the formula for 3/2 is much nicer ...
176
+ addb([Rational(-1, 2), 1, 1], [2, 2],
177
+ Matrix([HyperRep_power1(S.Half, z), HyperRep_log2(z), 1]),
178
+ Matrix([[Rational(4, 9) - 16/(9*z), 4/(3*z), 16/(9*z)]]),
179
+ Matrix([[z/2/(z - 1), 0, 0], [1/(2*(z - 1)), 0, S.Half], [0, 0, 0]]))
180
+
181
+ # 1F1
182
+ addb([1], [b], Matrix([z**(1 - b) * exp(z) * lowergamma(b - 1, z), 1]),
183
+ Matrix([[b - 1, 0]]), Matrix([[1 - b + z, 1], [0, 0]]))
184
+ addb([a], [2*a],
185
+ Matrix([z**(S.Half - a)*exp(z/2)*besseli(a - S.Half, z/2)
186
+ * gamma(a + S.Half)/4**(S.Half - a),
187
+ z**(S.Half - a)*exp(z/2)*besseli(a + S.Half, z/2)
188
+ * gamma(a + S.Half)/4**(S.Half - a)]),
189
+ Matrix([[1, 0]]),
190
+ Matrix([[z/2, z/2], [z/2, (z/2 - 2*a)]]))
191
+ mz = polar_lift(-1)*z
192
+ addb([a], [a + 1],
193
+ Matrix([mz**(-a)*a*lowergamma(a, mz), a*exp(z)]),
194
+ Matrix([[1, 0]]),
195
+ Matrix([[-a, 1], [0, z]]))
196
+ # This one is redundant.
197
+ add([Rational(-1, 2)], [S.Half], exp(z) - sqrt(pi*z)*(-I)*erf(I*sqrt(z)))
198
+
199
+ # Added to get nice results for Laplace transform of Fresnel functions
200
+ # https://functions.wolfram.com/07.22.03.6437.01
201
+ # Basic rule
202
+ #add([1], [Rational(3, 4), Rational(5, 4)],
203
+ # sqrt(pi) * (cos(2*sqrt(polar_lift(-1)*z))*fresnelc(2*root(polar_lift(-1)*z,4)/sqrt(pi)) +
204
+ # sin(2*sqrt(polar_lift(-1)*z))*fresnels(2*root(polar_lift(-1)*z,4)/sqrt(pi)))
205
+ # / (2*root(polar_lift(-1)*z,4)))
206
+ # Manually tuned rule
207
+ addb([1], [Rational(3, 4), Rational(5, 4)],
208
+ Matrix([ sqrt(pi)*(I*sinh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
209
+ + cosh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
210
+ * exp(-I*pi/4)/(2*root(z, 4)),
211
+ sqrt(pi)*root(z, 4)*(sinh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
212
+ + I*cosh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
213
+ *exp(-I*pi/4)/2,
214
+ 1 ]),
215
+ Matrix([[1, 0, 0]]),
216
+ Matrix([[Rational(-1, 4), 1, Rational(1, 4)],
217
+ [ z, Rational(1, 4), 0],
218
+ [ 0, 0, 0]]))
219
+
220
+ # 2F2
221
+ addb([S.Half, a], [Rational(3, 2), a + 1],
222
+ Matrix([a/(2*a - 1)*(-I)*sqrt(pi/z)*erf(I*sqrt(z)),
223
+ a/(2*a - 1)*(polar_lift(-1)*z)**(-a)*
224
+ lowergamma(a, polar_lift(-1)*z),
225
+ a/(2*a - 1)*exp(z)]),
226
+ Matrix([[1, -1, 0]]),
227
+ Matrix([[Rational(-1, 2), 0, 1], [0, -a, 1], [0, 0, z]]))
228
+ # We make a "basis" of four functions instead of three, and give EulerGamma
229
+ # an extra slot (it could just be a coefficient to 1). The advantage is
230
+ # that this way Polys will not see multivariate polynomials (it treats
231
+ # EulerGamma as an indeterminate), which is *way* faster.
232
+ addb([1, 1], [2, 2],
233
+ Matrix([Ei(z) - log(z), exp(z), 1, EulerGamma]),
234
+ Matrix([[1/z, 0, 0, -1/z]]),
235
+ Matrix([[0, 1, -1, 0], [0, z, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]))
236
+
237
+ # 0F1
238
+ add((), (S.Half, ), cosh(2*sqrt(z)))
239
+ addb([], [b],
240
+ Matrix([gamma(b)*z**((1 - b)/2)*besseli(b - 1, 2*sqrt(z)),
241
+ gamma(b)*z**(1 - b/2)*besseli(b, 2*sqrt(z))]),
242
+ Matrix([[1, 0]]), Matrix([[0, 1], [z, (1 - b)]]))
243
+
244
+ # 0F3
245
+ x = 4*z**Rational(1, 4)
246
+
247
+ def fp(a, z):
248
+ return besseli(a, x) + besselj(a, x)
249
+
250
+ def fm(a, z):
251
+ return besseli(a, x) - besselj(a, x)
252
+
253
+ # TODO branching
254
+ addb([], [S.Half, a, a + S.Half],
255
+ Matrix([fp(2*a - 1, z), fm(2*a, z)*z**Rational(1, 4),
256
+ fm(2*a - 1, z)*sqrt(z), fp(2*a, z)*z**Rational(3, 4)])
257
+ * 2**(-2*a)*gamma(2*a)*z**((1 - 2*a)/4),
258
+ Matrix([[1, 0, 0, 0]]),
259
+ Matrix([[0, 1, 0, 0],
260
+ [0, S.Half - a, 1, 0],
261
+ [0, 0, S.Half, 1],
262
+ [z, 0, 0, 1 - a]]))
263
+ x = 2*(4*z)**Rational(1, 4)*exp_polar(I*pi/4)
264
+ addb([], [a, a + S.Half, 2*a],
265
+ (2*sqrt(polar_lift(-1)*z))**(1 - 2*a)*gamma(2*a)**2 *
266
+ Matrix([besselj(2*a - 1, x)*besseli(2*a - 1, x),
267
+ x*(besseli(2*a, x)*besselj(2*a - 1, x)
268
+ - besseli(2*a - 1, x)*besselj(2*a, x)),
269
+ x**2*besseli(2*a, x)*besselj(2*a, x),
270
+ x**3*(besseli(2*a, x)*besselj(2*a - 1, x)
271
+ + besseli(2*a - 1, x)*besselj(2*a, x))]),
272
+ Matrix([[1, 0, 0, 0]]),
273
+ Matrix([[0, Rational(1, 4), 0, 0],
274
+ [0, (1 - 2*a)/2, Rational(-1, 2), 0],
275
+ [0, 0, 1 - 2*a, Rational(1, 4)],
276
+ [-32*z, 0, 0, 1 - a]]))
277
+
278
+ # 1F2
279
+ addb([a], [a - S.Half, 2*a],
280
+ Matrix([z**(S.Half - a)*besseli(a - S.Half, sqrt(z))**2,
281
+ z**(1 - a)*besseli(a - S.Half, sqrt(z))
282
+ *besseli(a - Rational(3, 2), sqrt(z)),
283
+ z**(Rational(3, 2) - a)*besseli(a - Rational(3, 2), sqrt(z))**2]),
284
+ Matrix([[-gamma(a + S.Half)**2/4**(S.Half - a),
285
+ 2*gamma(a - S.Half)*gamma(a + S.Half)/4**(1 - a),
286
+ 0]]),
287
+ Matrix([[1 - 2*a, 1, 0], [z/2, S.Half - a, S.Half], [0, z, 0]]))
288
+ addb([S.Half], [b, 2 - b],
289
+ pi*(1 - b)/sin(pi*b)*
290
+ Matrix([besseli(1 - b, sqrt(z))*besseli(b - 1, sqrt(z)),
291
+ sqrt(z)*(besseli(-b, sqrt(z))*besseli(b - 1, sqrt(z))
292
+ + besseli(1 - b, sqrt(z))*besseli(b, sqrt(z))),
293
+ besseli(-b, sqrt(z))*besseli(b, sqrt(z))]),
294
+ Matrix([[1, 0, 0]]),
295
+ Matrix([[b - 1, S.Half, 0],
296
+ [z, 0, z],
297
+ [0, S.Half, -b]]))
298
+ addb([S.Half], [Rational(3, 2), Rational(3, 2)],
299
+ Matrix([Shi(2*sqrt(z))/2/sqrt(z), sinh(2*sqrt(z))/2/sqrt(z),
300
+ cosh(2*sqrt(z))]),
301
+ Matrix([[1, 0, 0]]),
302
+ Matrix([[Rational(-1, 2), S.Half, 0], [0, Rational(-1, 2), S.Half], [0, 2*z, 0]]))
303
+
304
+ # FresnelS
305
+ # Basic rule
306
+ #add([Rational(3, 4)], [Rational(3, 2),Rational(7, 4)], 6*fresnels( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( pi * (exp(pi*I/4)*root(z,4)*2/sqrt(pi))**3 ) )
307
+ # Manually tuned rule
308
+ addb([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)],
309
+ Matrix(
310
+ [ fresnels(
311
+ exp(
312
+ pi*I/4)*root(
313
+ z, 4)*2/sqrt(
314
+ pi) ) / (
315
+ pi * (exp(pi*I/4)*root(z, 4)*2/sqrt(pi))**3 ),
316
+ sinh(2*sqrt(z))/sqrt(z),
317
+ cosh(2*sqrt(z)) ]),
318
+ Matrix([[6, 0, 0]]),
319
+ Matrix([[Rational(-3, 4), Rational(1, 16), 0],
320
+ [ 0, Rational(-1, 2), 1],
321
+ [ 0, z, 0]]))
322
+
323
+ # FresnelC
324
+ # Basic rule
325
+ #add([Rational(1, 4)], [S.Half,Rational(5, 4)], fresnelc( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) )
326
+ # Manually tuned rule
327
+ addb([Rational(1, 4)], [S.Half, Rational(5, 4)],
328
+ Matrix(
329
+ [ sqrt(
330
+ pi)*exp(
331
+ -I*pi/4)*fresnelc(
332
+ 2*root(z, 4)*exp(I*pi/4)/sqrt(pi))/(2*root(z, 4)),
333
+ cosh(2*sqrt(z)),
334
+ sinh(2*sqrt(z))*sqrt(z) ]),
335
+ Matrix([[1, 0, 0]]),
336
+ Matrix([[Rational(-1, 4), Rational(1, 4), 0 ],
337
+ [ 0, 0, 1 ],
338
+ [ 0, z, S.Half]]))
339
+
340
+ # 2F3
341
+ # XXX with this five-parameter formula is pretty slow with the current
342
+ # Formula.find_instantiations (creates 2!*3!*3**(2+3) ~ 3000
343
+ # instantiations ... But it's not too bad.
344
+ addb([a, a + S.Half], [2*a, b, 2*a - b + 1],
345
+ gamma(b)*gamma(2*a - b + 1) * (sqrt(z)/2)**(1 - 2*a) *
346
+ Matrix([besseli(b - 1, sqrt(z))*besseli(2*a - b, sqrt(z)),
347
+ sqrt(z)*besseli(b, sqrt(z))*besseli(2*a - b, sqrt(z)),
348
+ sqrt(z)*besseli(b - 1, sqrt(z))*besseli(2*a - b + 1, sqrt(z)),
349
+ besseli(b, sqrt(z))*besseli(2*a - b + 1, sqrt(z))]),
350
+ Matrix([[1, 0, 0, 0]]),
351
+ Matrix([[0, S.Half, S.Half, 0],
352
+ [z/2, 1 - b, 0, z/2],
353
+ [z/2, 0, b - 2*a, z/2],
354
+ [0, S.Half, S.Half, -2*a]]))
355
+ # (C/f above comment about eulergamma in the basis).
356
+ addb([1, 1], [2, 2, Rational(3, 2)],
357
+ Matrix([Chi(2*sqrt(z)) - log(2*sqrt(z)),
358
+ cosh(2*sqrt(z)), sqrt(z)*sinh(2*sqrt(z)), 1, EulerGamma]),
359
+ Matrix([[1/z, 0, 0, 0, -1/z]]),
360
+ Matrix([[0, S.Half, 0, Rational(-1, 2), 0],
361
+ [0, 0, 1, 0, 0],
362
+ [0, z, S.Half, 0, 0],
363
+ [0, 0, 0, 0, 0],
364
+ [0, 0, 0, 0, 0]]))
365
+
366
+ # 3F3
367
+ # This is rule: https://functions.wolfram.com/07.31.03.0134.01
368
+ # Initial reason to add it was a nice solution for
369
+ # integrate(erf(a*z)/z**2, z) and same for erfc and erfi.
370
+ # Basic rule
371
+ # add([1, 1, a], [2, 2, a+1], (a/(z*(a-1)**2)) *
372
+ # (1 - (-z)**(1-a) * (gamma(a) - uppergamma(a,-z))
373
+ # - (a-1) * (EulerGamma + uppergamma(0,-z) + log(-z))
374
+ # - exp(z)))
375
+ # Manually tuned rule
376
+ addb([1, 1, a], [2, 2, a+1],
377
+ Matrix([a*(log(-z) + expint(1, -z) + EulerGamma)/(z*(a**2 - 2*a + 1)),
378
+ a*(-z)**(-a)*(gamma(a) - uppergamma(a, -z))/(a - 1)**2,
379
+ a*exp(z)/(a**2 - 2*a + 1),
380
+ a/(z*(a**2 - 2*a + 1))]),
381
+ Matrix([[1-a, 1, -1/z, 1]]),
382
+ Matrix([[-1,0,-1/z,1],
383
+ [0,-a,1,0],
384
+ [0,0,z,0],
385
+ [0,0,0,-1]]))
386
+
387
+
388
+ def add_meijerg_formulae(formulae):
389
+ a, b, c, z = list(map(Dummy, 'abcz'))
390
+ rho = Dummy('rho')
391
+
392
+ def add(an, ap, bm, bq, B, C, M, matcher):
393
+ formulae.append(MeijerFormula(an, ap, bm, bq, z, [a, b, c, rho],
394
+ B, C, M, matcher))
395
+
396
+ def detect_uppergamma(func):
397
+ x = func.an[0]
398
+ y, z = func.bm
399
+ swapped = False
400
+ if not _mod1((x - y).simplify()):
401
+ swapped = True
402
+ (y, z) = (z, y)
403
+ if _mod1((x - z).simplify()) or x - z > 0:
404
+ return None
405
+ l = [y, x]
406
+ if swapped:
407
+ l = [x, y]
408
+ return {rho: y, a: x - y}, G_Function([x], [], l, [])
409
+
410
+ add([a + rho], [], [rho, a + rho], [],
411
+ Matrix([gamma(1 - a)*z**rho*exp(z)*uppergamma(a, z),
412
+ gamma(1 - a)*z**(a + rho)]),
413
+ Matrix([[1, 0]]),
414
+ Matrix([[rho + z, -1], [0, a + rho]]),
415
+ detect_uppergamma)
416
+
417
+ def detect_3113(func):
418
+ """https://functions.wolfram.com/07.34.03.0984.01"""
419
+ x = func.an[0]
420
+ u, v, w = func.bm
421
+ if _mod1((u - v).simplify()) == 0:
422
+ if _mod1((v - w).simplify()) == 0:
423
+ return
424
+ sig = (S.Half, S.Half, S.Zero)
425
+ x1, x2, y = u, v, w
426
+ else:
427
+ if _mod1((x - u).simplify()) == 0:
428
+ sig = (S.Half, S.Zero, S.Half)
429
+ x1, y, x2 = u, v, w
430
+ else:
431
+ sig = (S.Zero, S.Half, S.Half)
432
+ y, x1, x2 = u, v, w
433
+
434
+ if (_mod1((x - x1).simplify()) != 0 or
435
+ _mod1((x - x2).simplify()) != 0 or
436
+ _mod1((x - y).simplify()) != S.Half or
437
+ x - x1 > 0 or x - x2 > 0):
438
+ return
439
+
440
+ return {a: x}, G_Function([x], [], [x - S.Half + t for t in sig], [])
441
+
442
+ s = sin(2*sqrt(z))
443
+ c_ = cos(2*sqrt(z))
444
+ S_ = Si(2*sqrt(z)) - pi/2
445
+ C = Ci(2*sqrt(z))
446
+ add([a], [], [a, a, a - S.Half], [],
447
+ Matrix([sqrt(pi)*z**(a - S.Half)*(c_*S_ - s*C),
448
+ sqrt(pi)*z**a*(s*S_ + c_*C),
449
+ sqrt(pi)*z**a]),
450
+ Matrix([[-2, 0, 0]]),
451
+ Matrix([[a - S.Half, -1, 0], [z, a, S.Half], [0, 0, a]]),
452
+ detect_3113)
453
+
454
+
455
+ def make_simp(z):
456
+ """ Create a function that simplifies rational functions in ``z``. """
457
+
458
+ def simp(expr):
459
+ """ Efficiently simplify the rational function ``expr``. """
460
+ numer, denom = expr.as_numer_denom()
461
+ numer = numer.expand()
462
+ # denom = denom.expand() # is this needed?
463
+ c, numer, denom = poly(numer, z).cancel(poly(denom, z))
464
+ return c * numer.as_expr() / denom.as_expr()
465
+
466
+ return simp
467
+
468
+
469
+ def debug(*args):
470
+ if SYMPY_DEBUG:
471
+ for a in args:
472
+ print(a, end="")
473
+ print()
474
+
475
+
476
+ class Hyper_Function(Expr):
477
+ """ A generalized hypergeometric function. """
478
+
479
+ def __new__(cls, ap, bq):
480
+ obj = super().__new__(cls)
481
+ obj.ap = Tuple(*list(map(expand, ap)))
482
+ obj.bq = Tuple(*list(map(expand, bq)))
483
+ return obj
484
+
485
+ @property
486
+ def args(self):
487
+ return (self.ap, self.bq)
488
+
489
+ @property
490
+ def sizes(self):
491
+ return (len(self.ap), len(self.bq))
492
+
493
+ @property
494
+ def gamma(self):
495
+ """
496
+ Number of upper parameters that are negative integers
497
+
498
+ This is a transformation invariant.
499
+ """
500
+ return sum(bool(x.is_integer and x.is_negative) for x in self.ap)
501
+
502
+ def _hashable_content(self):
503
+ return super()._hashable_content() + (self.ap,
504
+ self.bq)
505
+
506
+ def __call__(self, arg):
507
+ return hyper(self.ap, self.bq, arg)
508
+
509
+ def build_invariants(self):
510
+ """
511
+ Compute the invariant vector.
512
+
513
+ Explanation
514
+ ===========
515
+
516
+ The invariant vector is:
517
+ (gamma, ((s1, n1), ..., (sk, nk)), ((t1, m1), ..., (tr, mr)))
518
+ where gamma is the number of integer a < 0,
519
+ s1 < ... < sk
520
+ nl is the number of parameters a_i congruent to sl mod 1
521
+ t1 < ... < tr
522
+ ml is the number of parameters b_i congruent to tl mod 1
523
+
524
+ If the index pair contains parameters, then this is not truly an
525
+ invariant, since the parameters cannot be sorted uniquely mod1.
526
+
527
+ Examples
528
+ ========
529
+
530
+ >>> from sympy.simplify.hyperexpand import Hyper_Function
531
+ >>> from sympy import S
532
+ >>> ap = (S.Half, S.One/3, S(-1)/2, -2)
533
+ >>> bq = (1, 2)
534
+
535
+ Here gamma = 1,
536
+ k = 3, s1 = 0, s2 = 1/3, s3 = 1/2
537
+ n1 = 1, n2 = 1, n2 = 2
538
+ r = 1, t1 = 0
539
+ m1 = 2:
540
+
541
+ >>> Hyper_Function(ap, bq).build_invariants()
542
+ (1, ((0, 1), (1/3, 1), (1/2, 2)), ((0, 2),))
543
+ """
544
+ abuckets, bbuckets = sift(self.ap, _mod1), sift(self.bq, _mod1)
545
+
546
+ def tr(bucket):
547
+ bucket = list(bucket.items())
548
+ if not any(isinstance(x[0], Mod) for x in bucket):
549
+ bucket.sort(key=lambda x: default_sort_key(x[0]))
550
+ bucket = tuple([(mod, len(values)) for mod, values in bucket if
551
+ values])
552
+ return bucket
553
+
554
+ return (self.gamma, tr(abuckets), tr(bbuckets))
555
+
556
+ def difficulty(self, func):
557
+ """ Estimate how many steps it takes to reach ``func`` from self.
558
+ Return -1 if impossible. """
559
+ if self.gamma != func.gamma:
560
+ return -1
561
+ oabuckets, obbuckets, abuckets, bbuckets = [sift(params, _mod1) for
562
+ params in (self.ap, self.bq, func.ap, func.bq)]
563
+
564
+ diff = 0
565
+ for bucket, obucket in [(abuckets, oabuckets), (bbuckets, obbuckets)]:
566
+ for mod in set(list(bucket.keys()) + list(obucket.keys())):
567
+ if (mod not in bucket) or (mod not in obucket) \
568
+ or len(bucket[mod]) != len(obucket[mod]):
569
+ return -1
570
+ l1 = list(bucket[mod])
571
+ l2 = list(obucket[mod])
572
+ l1.sort()
573
+ l2.sort()
574
+ for i, j in zip(l1, l2):
575
+ diff += abs(i - j)
576
+
577
+ return diff
578
+
579
+ def _is_suitable_origin(self):
580
+ """
581
+ Decide if ``self`` is a suitable origin.
582
+
583
+ Explanation
584
+ ===========
585
+
586
+ A function is a suitable origin iff:
587
+ * none of the ai equals bj + n, with n a non-negative integer
588
+ * none of the ai is zero
589
+ * none of the bj is a non-positive integer
590
+
591
+ Note that this gives meaningful results only when none of the indices
592
+ are symbolic.
593
+
594
+ """
595
+ for a in self.ap:
596
+ for b in self.bq:
597
+ if (a - b).is_integer and (a - b).is_negative is False:
598
+ return False
599
+ for a in self.ap:
600
+ if a == 0:
601
+ return False
602
+ for b in self.bq:
603
+ if b.is_integer and b.is_nonpositive:
604
+ return False
605
+ return True
606
+
607
+
608
+ class G_Function(Expr):
609
+ """ A Meijer G-function. """
610
+
611
+ def __new__(cls, an, ap, bm, bq):
612
+ obj = super().__new__(cls)
613
+ obj.an = Tuple(*list(map(expand, an)))
614
+ obj.ap = Tuple(*list(map(expand, ap)))
615
+ obj.bm = Tuple(*list(map(expand, bm)))
616
+ obj.bq = Tuple(*list(map(expand, bq)))
617
+ return obj
618
+
619
+ @property
620
+ def args(self):
621
+ return (self.an, self.ap, self.bm, self.bq)
622
+
623
+ def _hashable_content(self):
624
+ return super()._hashable_content() + self.args
625
+
626
+ def __call__(self, z):
627
+ return meijerg(self.an, self.ap, self.bm, self.bq, z)
628
+
629
+ def compute_buckets(self):
630
+ """
631
+ Compute buckets for the fours sets of parameters.
632
+
633
+ Explanation
634
+ ===========
635
+
636
+ We guarantee that any two equal Mod objects returned are actually the
637
+ same, and that the buckets are sorted by real part (an and bq
638
+ descendending, bm and ap ascending).
639
+
640
+ Examples
641
+ ========
642
+
643
+ >>> from sympy.simplify.hyperexpand import G_Function
644
+ >>> from sympy.abc import y
645
+ >>> from sympy import S
646
+
647
+ >>> a, b = [1, 3, 2, S(3)/2], [1 + y, y, 2, y + 3]
648
+ >>> G_Function(a, b, [2], [y]).compute_buckets()
649
+ ({0: [3, 2, 1], 1/2: [3/2]},
650
+ {0: [2], y: [y, y + 1, y + 3]}, {0: [2]}, {y: [y]})
651
+
652
+ """
653
+ dicts = pan, pap, pbm, pbq = [defaultdict(list) for i in range(4)]
654
+ for dic, lis in zip(dicts, (self.an, self.ap, self.bm, self.bq)):
655
+ for x in lis:
656
+ dic[_mod1(x)].append(x)
657
+
658
+ for dic, flip in zip(dicts, (True, False, False, True)):
659
+ for m, items in dic.items():
660
+ x0 = items[0]
661
+ items.sort(key=lambda x: x - x0, reverse=flip)
662
+ dic[m] = items
663
+
664
+ return tuple([dict(w) for w in dicts])
665
+
666
+ @property
667
+ def signature(self):
668
+ return (len(self.an), len(self.ap), len(self.bm), len(self.bq))
669
+
670
+
671
+ # Dummy variable.
672
+ _x = Dummy('x')
673
+
674
+ class Formula:
675
+ """
676
+ This class represents hypergeometric formulae.
677
+
678
+ Explanation
679
+ ===========
680
+
681
+ Its data members are:
682
+ - z, the argument
683
+ - closed_form, the closed form expression
684
+ - symbols, the free symbols (parameters) in the formula
685
+ - func, the function
686
+ - B, C, M (see _compute_basis)
687
+
688
+ Examples
689
+ ========
690
+
691
+ >>> from sympy.abc import a, b, z
692
+ >>> from sympy.simplify.hyperexpand import Formula, Hyper_Function
693
+ >>> func = Hyper_Function((a/2, a/3 + b, (1+a)/2), (a, b, (a+b)/7))
694
+ >>> f = Formula(func, z, None, [a, b])
695
+
696
+ """
697
+
698
+ def _compute_basis(self, closed_form):
699
+ """
700
+ Compute a set of functions B=(f1, ..., fn), a nxn matrix M
701
+ and a 1xn matrix C such that:
702
+ closed_form = C B
703
+ z d/dz B = M B.
704
+ """
705
+ afactors = [_x + a for a in self.func.ap]
706
+ bfactors = [_x + b - 1 for b in self.func.bq]
707
+ expr = _x*Mul(*bfactors) - self.z*Mul(*afactors)
708
+ poly = Poly(expr, _x)
709
+
710
+ n = poly.degree() - 1
711
+ b = [closed_form]
712
+ for _ in range(n):
713
+ b.append(self.z*b[-1].diff(self.z))
714
+
715
+ self.B = Matrix(b)
716
+ self.C = Matrix([[1] + [0]*n])
717
+
718
+ m = eye(n)
719
+ m = m.col_insert(0, zeros(n, 1))
720
+ l = poly.all_coeffs()[1:]
721
+ l.reverse()
722
+ self.M = m.row_insert(n, -Matrix([l])/poly.all_coeffs()[0])
723
+
724
+ def __init__(self, func, z, res, symbols, B=None, C=None, M=None):
725
+ z = sympify(z)
726
+ res = sympify(res)
727
+ symbols = [x for x in sympify(symbols) if func.has(x)]
728
+
729
+ self.z = z
730
+ self.symbols = symbols
731
+ self.B = B
732
+ self.C = C
733
+ self.M = M
734
+ self.func = func
735
+
736
+ # TODO with symbolic parameters, it could be advantageous
737
+ # (for prettier answers) to compute a basis only *after*
738
+ # instantiation
739
+ if res is not None:
740
+ self._compute_basis(res)
741
+
742
+ @property
743
+ def closed_form(self):
744
+ return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero)
745
+
746
+ def find_instantiations(self, func):
747
+ """
748
+ Find substitutions of the free symbols that match ``func``.
749
+
750
+ Return the substitution dictionaries as a list. Note that the returned
751
+ instantiations need not actually match, or be valid!
752
+
753
+ """
754
+ from sympy.solvers import solve
755
+ ap = func.ap
756
+ bq = func.bq
757
+ if len(ap) != len(self.func.ap) or len(bq) != len(self.func.bq):
758
+ raise TypeError('Cannot instantiate other number of parameters')
759
+ symbol_values = []
760
+ for a in self.symbols:
761
+ if a in self.func.ap.args:
762
+ symbol_values.append(ap)
763
+ elif a in self.func.bq.args:
764
+ symbol_values.append(bq)
765
+ else:
766
+ raise ValueError("At least one of the parameters of the "
767
+ "formula must be equal to %s" % (a,))
768
+ base_repl = [dict(list(zip(self.symbols, values)))
769
+ for values in product(*symbol_values)]
770
+ abuckets, bbuckets = [sift(params, _mod1) for params in [ap, bq]]
771
+ a_inv, b_inv = [{a: len(vals) for a, vals in bucket.items()}
772
+ for bucket in [abuckets, bbuckets]]
773
+ critical_values = [[0] for _ in self.symbols]
774
+ result = []
775
+ _n = Dummy()
776
+ for repl in base_repl:
777
+ symb_a, symb_b = [sift(params, lambda x: _mod1(x.xreplace(repl)))
778
+ for params in [self.func.ap, self.func.bq]]
779
+ for bucket, obucket in [(abuckets, symb_a), (bbuckets, symb_b)]:
780
+ for mod in set(list(bucket.keys()) + list(obucket.keys())):
781
+ if (mod not in bucket) or (mod not in obucket) \
782
+ or len(bucket[mod]) != len(obucket[mod]):
783
+ break
784
+ for a, vals in zip(self.symbols, critical_values):
785
+ if repl[a].free_symbols:
786
+ continue
787
+ exprs = [expr for expr in obucket[mod] if expr.has(a)]
788
+ repl0 = repl.copy()
789
+ repl0[a] += _n
790
+ for expr in exprs:
791
+ for target in bucket[mod]:
792
+ n0, = solve(expr.xreplace(repl0) - target, _n)
793
+ if n0.free_symbols:
794
+ raise ValueError("Value should not be true")
795
+ vals.append(n0)
796
+ else:
797
+ values = []
798
+ for a, vals in zip(self.symbols, critical_values):
799
+ a0 = repl[a]
800
+ min_ = floor(min(vals))
801
+ max_ = ceiling(max(vals))
802
+ values.append([a0 + n for n in range(min_, max_ + 1)])
803
+ result.extend(dict(list(zip(self.symbols, l))) for l in product(*values))
804
+ return result
805
+
806
+
807
+
808
+
809
+ class FormulaCollection:
810
+ """ A collection of formulae to use as origins. """
811
+
812
+ def __init__(self):
813
+ """ Doing this globally at module init time is a pain ... """
814
+ self.symbolic_formulae = {}
815
+ self.concrete_formulae = {}
816
+ self.formulae = []
817
+
818
+ add_formulae(self.formulae)
819
+
820
+ # Now process the formulae into a helpful form.
821
+ # These dicts are indexed by (p, q).
822
+
823
+ for f in self.formulae:
824
+ sizes = f.func.sizes
825
+ if len(f.symbols) > 0:
826
+ self.symbolic_formulae.setdefault(sizes, []).append(f)
827
+ else:
828
+ inv = f.func.build_invariants()
829
+ self.concrete_formulae.setdefault(sizes, {})[inv] = f
830
+
831
+ def lookup_origin(self, func):
832
+ """
833
+ Given the suitable target ``func``, try to find an origin in our
834
+ knowledge base.
835
+
836
+ Examples
837
+ ========
838
+
839
+ >>> from sympy.simplify.hyperexpand import (FormulaCollection,
840
+ ... Hyper_Function)
841
+ >>> f = FormulaCollection()
842
+ >>> f.lookup_origin(Hyper_Function((), ())).closed_form
843
+ exp(_z)
844
+ >>> f.lookup_origin(Hyper_Function([1], ())).closed_form
845
+ HyperRep_power1(-1, _z)
846
+
847
+ >>> from sympy import S
848
+ >>> i = Hyper_Function([S('1/4'), S('3/4 + 4')], [S.Half])
849
+ >>> f.lookup_origin(i).closed_form
850
+ HyperRep_sqrts1(-1/4, _z)
851
+ """
852
+ inv = func.build_invariants()
853
+ sizes = func.sizes
854
+ if sizes in self.concrete_formulae and \
855
+ inv in self.concrete_formulae[sizes]:
856
+ return self.concrete_formulae[sizes][inv]
857
+
858
+ # We don't have a concrete formula. Try to instantiate.
859
+ if sizes not in self.symbolic_formulae:
860
+ return None # Too bad...
861
+
862
+ possible = []
863
+ for f in self.symbolic_formulae[sizes]:
864
+ repls = f.find_instantiations(func)
865
+ for repl in repls:
866
+ func2 = f.func.xreplace(repl)
867
+ if not func2._is_suitable_origin():
868
+ continue
869
+ diff = func2.difficulty(func)
870
+ if diff == -1:
871
+ continue
872
+ possible.append((diff, repl, f, func2))
873
+
874
+ # find the nearest origin
875
+ possible.sort(key=lambda x: x[0])
876
+ for _, repl, f, func2 in possible:
877
+ f2 = Formula(func2, f.z, None, [], f.B.subs(repl),
878
+ f.C.subs(repl), f.M.subs(repl))
879
+ if not any(e.has(S.NaN, oo, -oo, zoo) for e in [f2.B, f2.M, f2.C]):
880
+ return f2
881
+
882
+ return None
883
+
884
+
885
+ class MeijerFormula:
886
+ """
887
+ This class represents a Meijer G-function formula.
888
+
889
+ Its data members are:
890
+ - z, the argument
891
+ - symbols, the free symbols (parameters) in the formula
892
+ - func, the function
893
+ - B, C, M (c/f ordinary Formula)
894
+ """
895
+
896
+ def __init__(self, an, ap, bm, bq, z, symbols, B, C, M, matcher):
897
+ an, ap, bm, bq = [Tuple(*list(map(expand, w))) for w in [an, ap, bm, bq]]
898
+ self.func = G_Function(an, ap, bm, bq)
899
+ self.z = z
900
+ self.symbols = symbols
901
+ self._matcher = matcher
902
+ self.B = B
903
+ self.C = C
904
+ self.M = M
905
+
906
+ @property
907
+ def closed_form(self):
908
+ return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero)
909
+
910
+ def try_instantiate(self, func):
911
+ """
912
+ Try to instantiate the current formula to (almost) match func.
913
+ This uses the _matcher passed on init.
914
+ """
915
+ if func.signature != self.func.signature:
916
+ return None
917
+ res = self._matcher(func)
918
+ if res is not None:
919
+ subs, newfunc = res
920
+ return MeijerFormula(newfunc.an, newfunc.ap, newfunc.bm, newfunc.bq,
921
+ self.z, [],
922
+ self.B.subs(subs), self.C.subs(subs),
923
+ self.M.subs(subs), None)
924
+
925
+
926
+ class MeijerFormulaCollection:
927
+ """
928
+ This class holds a collection of meijer g formulae.
929
+ """
930
+
931
+ def __init__(self):
932
+ formulae = []
933
+ add_meijerg_formulae(formulae)
934
+ self.formulae = defaultdict(list)
935
+ for formula in formulae:
936
+ self.formulae[formula.func.signature].append(formula)
937
+ self.formulae = dict(self.formulae)
938
+
939
+ def lookup_origin(self, func):
940
+ """ Try to find a formula that matches func. """
941
+ if func.signature not in self.formulae:
942
+ return None
943
+ for formula in self.formulae[func.signature]:
944
+ res = formula.try_instantiate(func)
945
+ if res is not None:
946
+ return res
947
+
948
+
949
+ class Operator:
950
+ """
951
+ Base class for operators to be applied to our functions.
952
+
953
+ Explanation
954
+ ===========
955
+
956
+ These operators are differential operators. They are by convention
957
+ expressed in the variable D = z*d/dz (although this base class does
958
+ not actually care).
959
+ Note that when the operator is applied to an object, we typically do
960
+ *not* blindly differentiate but instead use a different representation
961
+ of the z*d/dz operator (see make_derivative_operator).
962
+
963
+ To subclass from this, define a __init__ method that initializes a
964
+ self._poly variable. This variable stores a polynomial. By convention
965
+ the generator is z*d/dz, and acts to the right of all coefficients.
966
+
967
+ Thus this poly
968
+ x**2 + 2*z*x + 1
969
+ represents the differential operator
970
+ (z*d/dz)**2 + 2*z**2*d/dz.
971
+
972
+ This class is used only in the implementation of the hypergeometric
973
+ function expansion algorithm.
974
+ """
975
+
976
+ def apply(self, obj, op):
977
+ """
978
+ Apply ``self`` to the object ``obj``, where the generator is ``op``.
979
+
980
+ Examples
981
+ ========
982
+
983
+ >>> from sympy.simplify.hyperexpand import Operator
984
+ >>> from sympy.polys.polytools import Poly
985
+ >>> from sympy.abc import x, y, z
986
+ >>> op = Operator()
987
+ >>> op._poly = Poly(x**2 + z*x + y, x)
988
+ >>> op.apply(z**7, lambda f: f.diff(z))
989
+ y*z**7 + 7*z**7 + 42*z**5
990
+ """
991
+ coeffs = self._poly.all_coeffs()
992
+ coeffs.reverse()
993
+ diffs = [obj]
994
+ for c in coeffs[1:]:
995
+ diffs.append(op(diffs[-1]))
996
+ r = coeffs[0]*diffs[0]
997
+ for c, d in zip(coeffs[1:], diffs[1:]):
998
+ r += c*d
999
+ return r
1000
+
1001
+
1002
+ class MultOperator(Operator):
1003
+ """ Simply multiply by a "constant" """
1004
+
1005
+ def __init__(self, p):
1006
+ self._poly = Poly(p, _x)
1007
+
1008
+
1009
+ class ShiftA(Operator):
1010
+ """ Increment an upper index. """
1011
+
1012
+ def __init__(self, ai):
1013
+ ai = sympify(ai)
1014
+ if ai == 0:
1015
+ raise ValueError('Cannot increment zero upper index.')
1016
+ self._poly = Poly(_x/ai + 1, _x)
1017
+
1018
+ def __str__(self):
1019
+ return '<Increment upper %s.>' % (1/self._poly.all_coeffs()[0])
1020
+
1021
+
1022
+ class ShiftB(Operator):
1023
+ """ Decrement a lower index. """
1024
+
1025
+ def __init__(self, bi):
1026
+ bi = sympify(bi)
1027
+ if bi == 1:
1028
+ raise ValueError('Cannot decrement unit lower index.')
1029
+ self._poly = Poly(_x/(bi - 1) + 1, _x)
1030
+
1031
+ def __str__(self):
1032
+ return '<Decrement lower %s.>' % (1/self._poly.all_coeffs()[0] + 1)
1033
+
1034
+
1035
+ class UnShiftA(Operator):
1036
+ """ Decrement an upper index. """
1037
+
1038
+ def __init__(self, ap, bq, i, z):
1039
+ """ Note: i counts from zero! """
1040
+ ap, bq, i = list(map(sympify, [ap, bq, i]))
1041
+
1042
+ self._ap = ap
1043
+ self._bq = bq
1044
+ self._i = i
1045
+
1046
+ ap = list(ap)
1047
+ bq = list(bq)
1048
+ ai = ap.pop(i) - 1
1049
+
1050
+ if ai == 0:
1051
+ raise ValueError('Cannot decrement unit upper index.')
1052
+
1053
+ m = Poly(z*ai, _x)
1054
+ for a in ap:
1055
+ m *= Poly(_x + a, _x)
1056
+
1057
+ A = Dummy('A')
1058
+ n = D = Poly(ai*A - ai, A)
1059
+ for b in bq:
1060
+ n *= D + (b - 1).as_poly(A)
1061
+
1062
+ b0 = -n.nth(0)
1063
+ if b0 == 0:
1064
+ raise ValueError('Cannot decrement upper index: '
1065
+ 'cancels with lower')
1066
+
1067
+ n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, _x/ai + 1), _x)
1068
+
1069
+ self._poly = Poly((n - m)/b0, _x)
1070
+
1071
+ def __str__(self):
1072
+ return '<Decrement upper index #%s of %s, %s.>' % (self._i,
1073
+ self._ap, self._bq)
1074
+
1075
+
1076
+ class UnShiftB(Operator):
1077
+ """ Increment a lower index. """
1078
+
1079
+ def __init__(self, ap, bq, i, z):
1080
+ """ Note: i counts from zero! """
1081
+ ap, bq, i = list(map(sympify, [ap, bq, i]))
1082
+
1083
+ self._ap = ap
1084
+ self._bq = bq
1085
+ self._i = i
1086
+
1087
+ ap = list(ap)
1088
+ bq = list(bq)
1089
+ bi = bq.pop(i) + 1
1090
+
1091
+ if bi == 0:
1092
+ raise ValueError('Cannot increment -1 lower index.')
1093
+
1094
+ m = Poly(_x*(bi - 1), _x)
1095
+ for b in bq:
1096
+ m *= Poly(_x + b - 1, _x)
1097
+
1098
+ B = Dummy('B')
1099
+ D = Poly((bi - 1)*B - bi + 1, B)
1100
+ n = Poly(z, B)
1101
+ for a in ap:
1102
+ n *= (D + a.as_poly(B))
1103
+
1104
+ b0 = n.nth(0)
1105
+ if b0 == 0:
1106
+ raise ValueError('Cannot increment index: cancels with upper')
1107
+
1108
+ n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
1109
+ B, _x/(bi - 1) + 1), _x)
1110
+
1111
+ self._poly = Poly((m - n)/b0, _x)
1112
+
1113
+ def __str__(self):
1114
+ return '<Increment lower index #%s of %s, %s.>' % (self._i,
1115
+ self._ap, self._bq)
1116
+
1117
+
1118
+ class MeijerShiftA(Operator):
1119
+ """ Increment an upper b index. """
1120
+
1121
+ def __init__(self, bi):
1122
+ bi = sympify(bi)
1123
+ self._poly = Poly(bi - _x, _x)
1124
+
1125
+ def __str__(self):
1126
+ return '<Increment upper b=%s.>' % (self._poly.all_coeffs()[1])
1127
+
1128
+
1129
+ class MeijerShiftB(Operator):
1130
+ """ Decrement an upper a index. """
1131
+
1132
+ def __init__(self, bi):
1133
+ bi = sympify(bi)
1134
+ self._poly = Poly(1 - bi + _x, _x)
1135
+
1136
+ def __str__(self):
1137
+ return '<Decrement upper a=%s.>' % (1 - self._poly.all_coeffs()[1])
1138
+
1139
+
1140
+ class MeijerShiftC(Operator):
1141
+ """ Increment a lower b index. """
1142
+
1143
+ def __init__(self, bi):
1144
+ bi = sympify(bi)
1145
+ self._poly = Poly(-bi + _x, _x)
1146
+
1147
+ def __str__(self):
1148
+ return '<Increment lower b=%s.>' % (-self._poly.all_coeffs()[1])
1149
+
1150
+
1151
+ class MeijerShiftD(Operator):
1152
+ """ Decrement a lower a index. """
1153
+
1154
+ def __init__(self, bi):
1155
+ bi = sympify(bi)
1156
+ self._poly = Poly(bi - 1 - _x, _x)
1157
+
1158
+ def __str__(self):
1159
+ return '<Decrement lower a=%s.>' % (self._poly.all_coeffs()[1] + 1)
1160
+
1161
+
1162
+ class MeijerUnShiftA(Operator):
1163
+ """ Decrement an upper b index. """
1164
+
1165
+ def __init__(self, an, ap, bm, bq, i, z):
1166
+ """ Note: i counts from zero! """
1167
+ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
1168
+
1169
+ self._an = an
1170
+ self._ap = ap
1171
+ self._bm = bm
1172
+ self._bq = bq
1173
+ self._i = i
1174
+
1175
+ an = list(an)
1176
+ ap = list(ap)
1177
+ bm = list(bm)
1178
+ bq = list(bq)
1179
+ bi = bm.pop(i) - 1
1180
+
1181
+ m = Poly(1, _x) * prod(Poly(b - _x, _x) for b in bm) * prod(Poly(_x - b, _x) for b in bq)
1182
+
1183
+ A = Dummy('A')
1184
+ D = Poly(bi - A, A)
1185
+ n = Poly(z, A) * prod((D + 1 - a) for a in an) * prod((-D + a - 1) for a in ap)
1186
+
1187
+ b0 = n.nth(0)
1188
+ if b0 == 0:
1189
+ raise ValueError('Cannot decrement upper b index (cancels)')
1190
+
1191
+ n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, bi - _x), _x)
1192
+
1193
+ self._poly = Poly((m - n)/b0, _x)
1194
+
1195
+ def __str__(self):
1196
+ return '<Decrement upper b index #%s of %s, %s, %s, %s.>' % (self._i,
1197
+ self._an, self._ap, self._bm, self._bq)
1198
+
1199
+
1200
+ class MeijerUnShiftB(Operator):
1201
+ """ Increment an upper a index. """
1202
+
1203
+ def __init__(self, an, ap, bm, bq, i, z):
1204
+ """ Note: i counts from zero! """
1205
+ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
1206
+
1207
+ self._an = an
1208
+ self._ap = ap
1209
+ self._bm = bm
1210
+ self._bq = bq
1211
+ self._i = i
1212
+
1213
+ an = list(an)
1214
+ ap = list(ap)
1215
+ bm = list(bm)
1216
+ bq = list(bq)
1217
+ ai = an.pop(i) + 1
1218
+
1219
+ m = Poly(z, _x)
1220
+ for a in an:
1221
+ m *= Poly(1 - a + _x, _x)
1222
+ for a in ap:
1223
+ m *= Poly(a - 1 - _x, _x)
1224
+
1225
+ B = Dummy('B')
1226
+ D = Poly(B + ai - 1, B)
1227
+ n = Poly(1, B)
1228
+ for b in bm:
1229
+ n *= (-D + b)
1230
+ for b in bq:
1231
+ n *= (D - b)
1232
+
1233
+ b0 = n.nth(0)
1234
+ if b0 == 0:
1235
+ raise ValueError('Cannot increment upper a index (cancels)')
1236
+
1237
+ n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
1238
+ B, 1 - ai + _x), _x)
1239
+
1240
+ self._poly = Poly((m - n)/b0, _x)
1241
+
1242
+ def __str__(self):
1243
+ return '<Increment upper a index #%s of %s, %s, %s, %s.>' % (self._i,
1244
+ self._an, self._ap, self._bm, self._bq)
1245
+
1246
+
1247
+ class MeijerUnShiftC(Operator):
1248
+ """ Decrement a lower b index. """
1249
+ # XXX this is "essentially" the same as MeijerUnShiftA. This "essentially"
1250
+ # can be made rigorous using the functional equation G(1/z) = G'(z),
1251
+ # where G' denotes a G function of slightly altered parameters.
1252
+ # However, sorting out the details seems harder than just coding it
1253
+ # again.
1254
+
1255
+ def __init__(self, an, ap, bm, bq, i, z):
1256
+ """ Note: i counts from zero! """
1257
+ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
1258
+
1259
+ self._an = an
1260
+ self._ap = ap
1261
+ self._bm = bm
1262
+ self._bq = bq
1263
+ self._i = i
1264
+
1265
+ an = list(an)
1266
+ ap = list(ap)
1267
+ bm = list(bm)
1268
+ bq = list(bq)
1269
+ bi = bq.pop(i) - 1
1270
+
1271
+ m = Poly(1, _x)
1272
+ for b in bm:
1273
+ m *= Poly(b - _x, _x)
1274
+ for b in bq:
1275
+ m *= Poly(_x - b, _x)
1276
+
1277
+ C = Dummy('C')
1278
+ D = Poly(bi + C, C)
1279
+ n = Poly(z, C)
1280
+ for a in an:
1281
+ n *= (D + 1 - a)
1282
+ for a in ap:
1283
+ n *= (-D + a - 1)
1284
+
1285
+ b0 = n.nth(0)
1286
+ if b0 == 0:
1287
+ raise ValueError('Cannot decrement lower b index (cancels)')
1288
+
1289
+ n = Poly(Poly(n.all_coeffs()[:-1], C).as_expr().subs(C, _x - bi), _x)
1290
+
1291
+ self._poly = Poly((m - n)/b0, _x)
1292
+
1293
+ def __str__(self):
1294
+ return '<Decrement lower b index #%s of %s, %s, %s, %s.>' % (self._i,
1295
+ self._an, self._ap, self._bm, self._bq)
1296
+
1297
+
1298
+ class MeijerUnShiftD(Operator):
1299
+ """ Increment a lower a index. """
1300
+ # XXX This is essentially the same as MeijerUnShiftA.
1301
+ # See comment at MeijerUnShiftC.
1302
+
1303
+ def __init__(self, an, ap, bm, bq, i, z):
1304
+ """ Note: i counts from zero! """
1305
+ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
1306
+
1307
+ self._an = an
1308
+ self._ap = ap
1309
+ self._bm = bm
1310
+ self._bq = bq
1311
+ self._i = i
1312
+
1313
+ an = list(an)
1314
+ ap = list(ap)
1315
+ bm = list(bm)
1316
+ bq = list(bq)
1317
+ ai = ap.pop(i) + 1
1318
+
1319
+ m = Poly(z, _x)
1320
+ for a in an:
1321
+ m *= Poly(1 - a + _x, _x)
1322
+ for a in ap:
1323
+ m *= Poly(a - 1 - _x, _x)
1324
+
1325
+ B = Dummy('B') # - this is the shift operator `D_I`
1326
+ D = Poly(ai - 1 - B, B)
1327
+ n = Poly(1, B)
1328
+ for b in bm:
1329
+ n *= (-D + b)
1330
+ for b in bq:
1331
+ n *= (D - b)
1332
+
1333
+ b0 = n.nth(0)
1334
+ if b0 == 0:
1335
+ raise ValueError('Cannot increment lower a index (cancels)')
1336
+
1337
+ n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
1338
+ B, ai - 1 - _x), _x)
1339
+
1340
+ self._poly = Poly((m - n)/b0, _x)
1341
+
1342
+ def __str__(self):
1343
+ return '<Increment lower a index #%s of %s, %s, %s, %s.>' % (self._i,
1344
+ self._an, self._ap, self._bm, self._bq)
1345
+
1346
+
1347
+ class ReduceOrder(Operator):
1348
+ """ Reduce Order by cancelling an upper and a lower index. """
1349
+
1350
+ def __new__(cls, ai, bj):
1351
+ """ For convenience if reduction is not possible, return None. """
1352
+ ai = sympify(ai)
1353
+ bj = sympify(bj)
1354
+ n = ai - bj
1355
+ if not n.is_Integer or n < 0:
1356
+ return None
1357
+ if bj.is_integer and bj.is_nonpositive:
1358
+ return None
1359
+
1360
+ expr = Operator.__new__(cls)
1361
+
1362
+ p = S.One
1363
+ for k in range(n):
1364
+ p *= (_x + bj + k)/(bj + k)
1365
+
1366
+ expr._poly = Poly(p, _x)
1367
+ expr._a = ai
1368
+ expr._b = bj
1369
+
1370
+ return expr
1371
+
1372
+ @classmethod
1373
+ def _meijer(cls, b, a, sign):
1374
+ """ Cancel b + sign*s and a + sign*s
1375
+ This is for meijer G functions. """
1376
+ b = sympify(b)
1377
+ a = sympify(a)
1378
+ n = b - a
1379
+ if n.is_negative or not n.is_Integer:
1380
+ return None
1381
+
1382
+ expr = Operator.__new__(cls)
1383
+
1384
+ p = S.One
1385
+ for k in range(n):
1386
+ p *= (sign*_x + a + k)
1387
+
1388
+ expr._poly = Poly(p, _x)
1389
+ if sign == -1:
1390
+ expr._a = b
1391
+ expr._b = a
1392
+ else:
1393
+ expr._b = Add(1, a - 1, evaluate=False)
1394
+ expr._a = Add(1, b - 1, evaluate=False)
1395
+
1396
+ return expr
1397
+
1398
+ @classmethod
1399
+ def meijer_minus(cls, b, a):
1400
+ return cls._meijer(b, a, -1)
1401
+
1402
+ @classmethod
1403
+ def meijer_plus(cls, a, b):
1404
+ return cls._meijer(1 - a, 1 - b, 1)
1405
+
1406
+ def __str__(self):
1407
+ return '<Reduce order by cancelling upper %s with lower %s.>' % \
1408
+ (self._a, self._b)
1409
+
1410
+
1411
+ def _reduce_order(ap, bq, gen, key):
1412
+ """ Order reduction algorithm used in Hypergeometric and Meijer G """
1413
+ ap = list(ap)
1414
+ bq = list(bq)
1415
+
1416
+ ap.sort(key=key)
1417
+ bq.sort(key=key)
1418
+
1419
+ nap = []
1420
+ # we will edit bq in place
1421
+ operators = []
1422
+ for a in ap:
1423
+ op = None
1424
+ for i in range(len(bq)):
1425
+ op = gen(a, bq[i])
1426
+ if op is not None:
1427
+ bq.pop(i)
1428
+ break
1429
+ if op is None:
1430
+ nap.append(a)
1431
+ else:
1432
+ operators.append(op)
1433
+
1434
+ return nap, bq, operators
1435
+
1436
+
1437
+ def reduce_order(func):
1438
+ """
1439
+ Given the hypergeometric function ``func``, find a sequence of operators to
1440
+ reduces order as much as possible.
1441
+
1442
+ Explanation
1443
+ ===========
1444
+
1445
+ Return (newfunc, [operators]), where applying the operators to the
1446
+ hypergeometric function newfunc yields func.
1447
+
1448
+ Examples
1449
+ ========
1450
+
1451
+ >>> from sympy.simplify.hyperexpand import reduce_order, Hyper_Function
1452
+ >>> reduce_order(Hyper_Function((1, 2), (3, 4)))
1453
+ (Hyper_Function((1, 2), (3, 4)), [])
1454
+ >>> reduce_order(Hyper_Function((1,), (1,)))
1455
+ (Hyper_Function((), ()), [<Reduce order by cancelling upper 1 with lower 1.>])
1456
+ >>> reduce_order(Hyper_Function((2, 4), (3, 3)))
1457
+ (Hyper_Function((2,), (3,)), [<Reduce order by cancelling
1458
+ upper 4 with lower 3.>])
1459
+ """
1460
+ nap, nbq, operators = _reduce_order(func.ap, func.bq, ReduceOrder, default_sort_key)
1461
+
1462
+ return Hyper_Function(Tuple(*nap), Tuple(*nbq)), operators
1463
+
1464
+
1465
+ def reduce_order_meijer(func):
1466
+ """
1467
+ Given the Meijer G function parameters, ``func``, find a sequence of
1468
+ operators that reduces order as much as possible.
1469
+
1470
+ Return newfunc, [operators].
1471
+
1472
+ Examples
1473
+ ========
1474
+
1475
+ >>> from sympy.simplify.hyperexpand import (reduce_order_meijer,
1476
+ ... G_Function)
1477
+ >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 2]))[0]
1478
+ G_Function((4, 3), (5, 6), (3, 4), (2, 1))
1479
+ >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 8]))[0]
1480
+ G_Function((3,), (5, 6), (3, 4), (1,))
1481
+ >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [1, 5]))[0]
1482
+ G_Function((3,), (), (), (1,))
1483
+ >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [5, 3]))[0]
1484
+ G_Function((), (), (), ())
1485
+ """
1486
+
1487
+ nan, nbq, ops1 = _reduce_order(func.an, func.bq, ReduceOrder.meijer_plus,
1488
+ lambda x: default_sort_key(-x))
1489
+ nbm, nap, ops2 = _reduce_order(func.bm, func.ap, ReduceOrder.meijer_minus,
1490
+ default_sort_key)
1491
+
1492
+ return G_Function(nan, nap, nbm, nbq), ops1 + ops2
1493
+
1494
+
1495
+ def make_derivative_operator(M, z):
1496
+ """ Create a derivative operator, to be passed to Operator.apply. """
1497
+ def doit(C):
1498
+ r = z*C.diff(z) + C*M
1499
+ r = r.applyfunc(make_simp(z))
1500
+ return r
1501
+ return doit
1502
+
1503
+
1504
+ def apply_operators(obj, ops, op):
1505
+ """
1506
+ Apply the list of operators ``ops`` to object ``obj``, substituting
1507
+ ``op`` for the generator.
1508
+ """
1509
+ res = obj
1510
+ for o in reversed(ops):
1511
+ res = o.apply(res, op)
1512
+ return res
1513
+
1514
+
1515
+ def devise_plan(target, origin, z):
1516
+ """
1517
+ Devise a plan (consisting of shift and un-shift operators) to be applied
1518
+ to the hypergeometric function ``target`` to yield ``origin``.
1519
+ Returns a list of operators.
1520
+
1521
+ Examples
1522
+ ========
1523
+
1524
+ >>> from sympy.simplify.hyperexpand import devise_plan, Hyper_Function
1525
+ >>> from sympy.abc import z
1526
+
1527
+ Nothing to do:
1528
+
1529
+ >>> devise_plan(Hyper_Function((1, 2), ()), Hyper_Function((1, 2), ()), z)
1530
+ []
1531
+ >>> devise_plan(Hyper_Function((), (1, 2)), Hyper_Function((), (1, 2)), z)
1532
+ []
1533
+
1534
+ Very simple plans:
1535
+
1536
+ >>> devise_plan(Hyper_Function((2,), ()), Hyper_Function((1,), ()), z)
1537
+ [<Increment upper 1.>]
1538
+ >>> devise_plan(Hyper_Function((), (2,)), Hyper_Function((), (1,)), z)
1539
+ [<Increment lower index #0 of [], [1].>]
1540
+
1541
+ Several buckets:
1542
+
1543
+ >>> from sympy import S
1544
+ >>> devise_plan(Hyper_Function((1, S.Half), ()),
1545
+ ... Hyper_Function((2, S('3/2')), ()), z) #doctest: +NORMALIZE_WHITESPACE
1546
+ [<Decrement upper index #0 of [3/2, 1], [].>,
1547
+ <Decrement upper index #0 of [2, 3/2], [].>]
1548
+
1549
+ A slightly more complicated plan:
1550
+
1551
+ >>> devise_plan(Hyper_Function((1, 3), ()), Hyper_Function((2, 2), ()), z)
1552
+ [<Increment upper 2.>, <Decrement upper index #0 of [2, 2], [].>]
1553
+
1554
+ Another more complicated plan: (note that the ap have to be shifted first!)
1555
+
1556
+ >>> devise_plan(Hyper_Function((1, -1), (2,)), Hyper_Function((3, -2), (4,)), z)
1557
+ [<Decrement lower 3.>, <Decrement lower 4.>,
1558
+ <Decrement upper index #1 of [-1, 2], [4].>,
1559
+ <Decrement upper index #1 of [-1, 3], [4].>, <Increment upper -2.>]
1560
+ """
1561
+ abuckets, bbuckets, nabuckets, nbbuckets = [sift(params, _mod1) for
1562
+ params in (target.ap, target.bq, origin.ap, origin.bq)]
1563
+
1564
+ if len(list(abuckets.keys())) != len(list(nabuckets.keys())) or \
1565
+ len(list(bbuckets.keys())) != len(list(nbbuckets.keys())):
1566
+ raise ValueError('%s not reachable from %s' % (target, origin))
1567
+
1568
+ ops = []
1569
+
1570
+ def do_shifts(fro, to, inc, dec):
1571
+ ops = []
1572
+ for i in range(len(fro)):
1573
+ if to[i] - fro[i] > 0:
1574
+ sh = inc
1575
+ ch = 1
1576
+ else:
1577
+ sh = dec
1578
+ ch = -1
1579
+
1580
+ while to[i] != fro[i]:
1581
+ ops += [sh(fro, i)]
1582
+ fro[i] += ch
1583
+
1584
+ return ops
1585
+
1586
+ def do_shifts_a(nal, nbk, al, aother, bother):
1587
+ """ Shift us from (nal, nbk) to (al, nbk). """
1588
+ return do_shifts(nal, al, lambda p, i: ShiftA(p[i]),
1589
+ lambda p, i: UnShiftA(p + aother, nbk + bother, i, z))
1590
+
1591
+ def do_shifts_b(nal, nbk, bk, aother, bother):
1592
+ """ Shift us from (nal, nbk) to (nal, bk). """
1593
+ return do_shifts(nbk, bk,
1594
+ lambda p, i: UnShiftB(nal + aother, p + bother, i, z),
1595
+ lambda p, i: ShiftB(p[i]))
1596
+
1597
+ for r in sorted(list(abuckets.keys()) + list(bbuckets.keys()), key=default_sort_key):
1598
+ al = ()
1599
+ nal = ()
1600
+ bk = ()
1601
+ nbk = ()
1602
+ if r in abuckets:
1603
+ al = abuckets[r]
1604
+ nal = nabuckets[r]
1605
+ if r in bbuckets:
1606
+ bk = bbuckets[r]
1607
+ nbk = nbbuckets[r]
1608
+ if len(al) != len(nal) or len(bk) != len(nbk):
1609
+ raise ValueError('%s not reachable from %s' % (target, origin))
1610
+
1611
+ al, nal, bk, nbk = [sorted(w, key=default_sort_key)
1612
+ for w in [al, nal, bk, nbk]]
1613
+
1614
+ def others(dic, key):
1615
+ l = []
1616
+ for k in dic:
1617
+ if k != key:
1618
+ l.extend(dic[k])
1619
+ return l
1620
+ aother = others(nabuckets, r)
1621
+ bother = others(nbbuckets, r)
1622
+
1623
+ if len(al) == 0:
1624
+ # there can be no complications, just shift the bs as we please
1625
+ ops += do_shifts_b([], nbk, bk, aother, bother)
1626
+ elif len(bk) == 0:
1627
+ # there can be no complications, just shift the as as we please
1628
+ ops += do_shifts_a(nal, [], al, aother, bother)
1629
+ else:
1630
+ namax = nal[-1]
1631
+ amax = al[-1]
1632
+
1633
+ if nbk[0] - namax <= 0 or bk[0] - amax <= 0:
1634
+ raise ValueError('Non-suitable parameters.')
1635
+
1636
+ if namax - amax > 0:
1637
+ # we are going to shift down - first do the as, then the bs
1638
+ ops += do_shifts_a(nal, nbk, al, aother, bother)
1639
+ ops += do_shifts_b(al, nbk, bk, aother, bother)
1640
+ else:
1641
+ # we are going to shift up - first do the bs, then the as
1642
+ ops += do_shifts_b(nal, nbk, bk, aother, bother)
1643
+ ops += do_shifts_a(nal, bk, al, aother, bother)
1644
+
1645
+ nabuckets[r] = al
1646
+ nbbuckets[r] = bk
1647
+
1648
+ ops.reverse()
1649
+ return ops
1650
+
1651
+
1652
+ def try_shifted_sum(func, z):
1653
+ """ Try to recognise a hypergeometric sum that starts from k > 0. """
1654
+ abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
1655
+ if len(abuckets[S.Zero]) != 1:
1656
+ return None
1657
+ r = abuckets[S.Zero][0]
1658
+ if r <= 0:
1659
+ return None
1660
+ if S.Zero not in bbuckets:
1661
+ return None
1662
+ l = list(bbuckets[S.Zero])
1663
+ l.sort()
1664
+ k = l[0]
1665
+ if k <= 0:
1666
+ return None
1667
+
1668
+ nap = list(func.ap)
1669
+ nap.remove(r)
1670
+ nbq = list(func.bq)
1671
+ nbq.remove(k)
1672
+ k -= 1
1673
+ nap = [x - k for x in nap]
1674
+ nbq = [x - k for x in nbq]
1675
+
1676
+ ops = []
1677
+ for n in range(r - 1):
1678
+ ops.append(ShiftA(n + 1))
1679
+ ops.reverse()
1680
+
1681
+ fac = factorial(k)/z**k
1682
+ fac *= Mul(*[rf(b, k) for b in nbq])
1683
+ fac /= Mul(*[rf(a, k) for a in nap])
1684
+
1685
+ ops += [MultOperator(fac)]
1686
+
1687
+ p = 0
1688
+ for n in range(k):
1689
+ m = z**n/factorial(n)
1690
+ m *= Mul(*[rf(a, n) for a in nap])
1691
+ m /= Mul(*[rf(b, n) for b in nbq])
1692
+ p += m
1693
+
1694
+ return Hyper_Function(nap, nbq), ops, -p
1695
+
1696
+
1697
+ def try_polynomial(func, z):
1698
+ """ Recognise polynomial cases. Returns None if not such a case.
1699
+ Requires order to be fully reduced. """
1700
+ abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
1701
+ a0 = abuckets[S.Zero]
1702
+ b0 = bbuckets[S.Zero]
1703
+ a0.sort()
1704
+ b0.sort()
1705
+ al0 = [x for x in a0 if x <= 0]
1706
+ bl0 = [x for x in b0 if x <= 0]
1707
+
1708
+ if bl0 and all(a < bl0[-1] for a in al0):
1709
+ return oo
1710
+ if not al0:
1711
+ return None
1712
+
1713
+ a = al0[-1]
1714
+ fac = 1
1715
+ res = S.One
1716
+ for n in Tuple(*list(range(-a))):
1717
+ fac *= z
1718
+ fac /= n + 1
1719
+ fac *= Mul(*[a + n for a in func.ap])
1720
+ fac /= Mul(*[b + n for b in func.bq])
1721
+ res += fac
1722
+ return res
1723
+
1724
+
1725
+ def try_lerchphi(func):
1726
+ """
1727
+ Try to find an expression for Hyper_Function ``func`` in terms of Lerch
1728
+ Transcendents.
1729
+
1730
+ Return None if no such expression can be found.
1731
+ """
1732
+ # This is actually quite simple, and is described in Roach's paper,
1733
+ # section 18.
1734
+ # We don't need to implement the reduction to polylog here, this
1735
+ # is handled by expand_func.
1736
+
1737
+ # First we need to figure out if the summation coefficient is a rational
1738
+ # function of the summation index, and construct that rational function.
1739
+ abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
1740
+
1741
+ paired = {}
1742
+ for key, value in abuckets.items():
1743
+ if key != 0 and key not in bbuckets:
1744
+ return None
1745
+ bvalue = bbuckets[key]
1746
+ paired[key] = (list(value), list(bvalue))
1747
+ bbuckets.pop(key, None)
1748
+ if bbuckets != {}:
1749
+ return None
1750
+ if S.Zero not in abuckets:
1751
+ return None
1752
+ aints, bints = paired[S.Zero]
1753
+ # Account for the additional n! in denominator
1754
+ paired[S.Zero] = (aints, bints + [1])
1755
+
1756
+ t = Dummy('t')
1757
+ numer = S.One
1758
+ denom = S.One
1759
+ for key, (avalue, bvalue) in paired.items():
1760
+ if len(avalue) != len(bvalue):
1761
+ return None
1762
+ # Note that since order has been reduced fully, all the b are
1763
+ # bigger than all the a they differ from by an integer. In particular
1764
+ # if there are any negative b left, this function is not well-defined.
1765
+ for a, b in zip(avalue, bvalue):
1766
+ if (a - b).is_positive:
1767
+ k = a - b
1768
+ numer *= rf(b + t, k)
1769
+ denom *= rf(b, k)
1770
+ else:
1771
+ k = b - a
1772
+ numer *= rf(a, k)
1773
+ denom *= rf(a + t, k)
1774
+
1775
+ # Now do a partial fraction decomposition.
1776
+ # We assemble two structures: a list monomials of pairs (a, b) representing
1777
+ # a*t**b (b a non-negative integer), and a dict terms, where
1778
+ # terms[a] = [(b, c)] means that there is a term b/(t-a)**c.
1779
+ part = apart(numer/denom, t)
1780
+ args = Add.make_args(part)
1781
+ monomials = []
1782
+ terms = {}
1783
+ for arg in args:
1784
+ numer, denom = arg.as_numer_denom()
1785
+ if not denom.has(t):
1786
+ p = Poly(numer, t)
1787
+ if not p.is_monomial:
1788
+ raise TypeError("p should be monomial")
1789
+ ((b, ), a) = p.LT()
1790
+ monomials += [(a/denom, b)]
1791
+ continue
1792
+ if numer.has(t):
1793
+ raise NotImplementedError('Need partial fraction decomposition'
1794
+ ' with linear denominators')
1795
+ indep, [dep] = denom.as_coeff_mul(t)
1796
+ n = 1
1797
+ if dep.is_Pow:
1798
+ n = dep.exp
1799
+ dep = dep.base
1800
+ if dep == t:
1801
+ a == 0
1802
+ elif dep.is_Add:
1803
+ a, tmp = dep.as_independent(t)
1804
+ b = 1
1805
+ if tmp != t:
1806
+ b, _ = tmp.as_independent(t)
1807
+ if dep != b*t + a:
1808
+ raise NotImplementedError('unrecognised form %s' % dep)
1809
+ a /= b
1810
+ indep *= b**n
1811
+ else:
1812
+ raise NotImplementedError('unrecognised form of partial fraction')
1813
+ terms.setdefault(a, []).append((numer/indep, n))
1814
+
1815
+ # Now that we have this information, assemble our formula. All the
1816
+ # monomials yield rational functions and go into one basis element.
1817
+ # The terms[a] are related by differentiation. If the largest exponent is
1818
+ # n, we need lerchphi(z, k, a) for k = 1, 2, ..., n.
1819
+ # deriv maps a basis to its derivative, expressed as a C(z)-linear
1820
+ # combination of other basis elements.
1821
+ deriv = {}
1822
+ coeffs = {}
1823
+ z = Dummy('z')
1824
+ monomials.sort(key=lambda x: x[1])
1825
+ mon = {0: 1/(1 - z)}
1826
+ if monomials:
1827
+ for k in range(monomials[-1][1]):
1828
+ mon[k + 1] = z*mon[k].diff(z)
1829
+ for a, n in monomials:
1830
+ coeffs.setdefault(S.One, []).append(a*mon[n])
1831
+ for a, l in terms.items():
1832
+ for c, k in l:
1833
+ coeffs.setdefault(lerchphi(z, k, a), []).append(c)
1834
+ l.sort(key=lambda x: x[1])
1835
+ for k in range(2, l[-1][1] + 1):
1836
+ deriv[lerchphi(z, k, a)] = [(-a, lerchphi(z, k, a)),
1837
+ (1, lerchphi(z, k - 1, a))]
1838
+ deriv[lerchphi(z, 1, a)] = [(-a, lerchphi(z, 1, a)),
1839
+ (1/(1 - z), S.One)]
1840
+ trans = {}
1841
+ for n, b in enumerate([S.One] + list(deriv.keys())):
1842
+ trans[b] = n
1843
+ basis = [expand_func(b) for (b, _) in sorted(trans.items(),
1844
+ key=lambda x:x[1])]
1845
+ B = Matrix(basis)
1846
+ C = Matrix([[0]*len(B)])
1847
+ for b, c in coeffs.items():
1848
+ C[trans[b]] = Add(*c)
1849
+ M = zeros(len(B))
1850
+ for b, l in deriv.items():
1851
+ for c, b2 in l:
1852
+ M[trans[b], trans[b2]] = c
1853
+ return Formula(func, z, None, [], B, C, M)
1854
+
1855
+
1856
+ def build_hypergeometric_formula(func):
1857
+ """
1858
+ Create a formula object representing the hypergeometric function ``func``.
1859
+
1860
+ """
1861
+ # We know that no `ap` are negative integers, otherwise "detect poly"
1862
+ # would have kicked in. However, `ap` could be empty. In this case we can
1863
+ # use a different basis.
1864
+ # I'm not aware of a basis that works in all cases.
1865
+ z = Dummy('z')
1866
+ if func.ap:
1867
+ afactors = [_x + a for a in func.ap]
1868
+ bfactors = [_x + b - 1 for b in func.bq]
1869
+ expr = _x*Mul(*bfactors) - z*Mul(*afactors)
1870
+ poly = Poly(expr, _x)
1871
+ n = poly.degree()
1872
+ basis = []
1873
+ M = zeros(n)
1874
+ for k in range(n):
1875
+ a = func.ap[0] + k
1876
+ basis += [hyper([a] + list(func.ap[1:]), func.bq, z)]
1877
+ if k < n - 1:
1878
+ M[k, k] = -a
1879
+ M[k, k + 1] = a
1880
+ B = Matrix(basis)
1881
+ C = Matrix([[1] + [0]*(n - 1)])
1882
+ derivs = [eye(n)]
1883
+ for k in range(n):
1884
+ derivs.append(M*derivs[k])
1885
+ l = poly.all_coeffs()
1886
+ l.reverse()
1887
+ res = [0]*n
1888
+ for k, c in enumerate(l):
1889
+ for r, d in enumerate(C*derivs[k]):
1890
+ res[r] += c*d
1891
+ for k, c in enumerate(res):
1892
+ M[n - 1, k] = -c/derivs[n - 1][0, n - 1]/poly.all_coeffs()[0]
1893
+ return Formula(func, z, None, [], B, C, M)
1894
+ else:
1895
+ # Since there are no `ap`, none of the `bq` can be non-positive
1896
+ # integers.
1897
+ basis = []
1898
+ bq = list(func.bq[:])
1899
+ for i in range(len(bq)):
1900
+ basis += [hyper([], bq, z)]
1901
+ bq[i] += 1
1902
+ basis += [hyper([], bq, z)]
1903
+ B = Matrix(basis)
1904
+ n = len(B)
1905
+ C = Matrix([[1] + [0]*(n - 1)])
1906
+ M = zeros(n)
1907
+ M[0, n - 1] = z/Mul(*func.bq)
1908
+ for k in range(1, n):
1909
+ M[k, k - 1] = func.bq[k - 1]
1910
+ M[k, k] = -func.bq[k - 1]
1911
+ return Formula(func, z, None, [], B, C, M)
1912
+
1913
+
1914
+ def hyperexpand_special(ap, bq, z):
1915
+ """
1916
+ Try to find a closed-form expression for hyper(ap, bq, z), where ``z``
1917
+ is supposed to be a "special" value, e.g. 1.
1918
+
1919
+ This function tries various of the classical summation formulae
1920
+ (Gauss, Saalschuetz, etc).
1921
+ """
1922
+ # This code is very ad-hoc. There are many clever algorithms
1923
+ # (notably Zeilberger's) related to this problem.
1924
+ # For now we just want a few simple cases to work.
1925
+ p, q = len(ap), len(bq)
1926
+ z_ = z
1927
+ z = unpolarify(z)
1928
+ if z == 0:
1929
+ return S.One
1930
+ from sympy.simplify.simplify import simplify
1931
+ if p == 2 and q == 1:
1932
+ # 2F1
1933
+ a, b, c = ap + bq
1934
+ if z == 1:
1935
+ # Gauss
1936
+ return gamma(c - a - b)*gamma(c)/gamma(c - a)/gamma(c - b)
1937
+ if z == -1 and simplify(b - a + c) == 1:
1938
+ b, a = a, b
1939
+ if z == -1 and simplify(a - b + c) == 1:
1940
+ # Kummer
1941
+ if b.is_integer and b.is_negative:
1942
+ return 2*cos(pi*b/2)*gamma(-b)*gamma(b - a + 1) \
1943
+ /gamma(-b/2)/gamma(b/2 - a + 1)
1944
+ else:
1945
+ return gamma(b/2 + 1)*gamma(b - a + 1) \
1946
+ /gamma(b + 1)/gamma(b/2 - a + 1)
1947
+ # TODO tons of more formulae
1948
+ # investigate what algorithms exist
1949
+ return hyper(ap, bq, z_)
1950
+
1951
+ _collection = None
1952
+
1953
+
1954
+ def _hyperexpand(func, z, ops0=[], z0=Dummy('z0'), premult=1, prem=0,
1955
+ rewrite='default'):
1956
+ """
1957
+ Try to find an expression for the hypergeometric function ``func``.
1958
+
1959
+ Explanation
1960
+ ===========
1961
+
1962
+ The result is expressed in terms of a dummy variable ``z0``. Then it
1963
+ is multiplied by ``premult``. Then ``ops0`` is applied.
1964
+ ``premult`` must be a*z**prem for some a independent of ``z``.
1965
+ """
1966
+
1967
+ if z.is_zero:
1968
+ return S.One
1969
+
1970
+ from sympy.simplify.simplify import simplify
1971
+
1972
+ z = polarify(z, subs=False)
1973
+ if rewrite == 'default':
1974
+ rewrite = 'nonrepsmall'
1975
+
1976
+ def carryout_plan(f, ops):
1977
+ C = apply_operators(f.C.subs(f.z, z0), ops,
1978
+ make_derivative_operator(f.M.subs(f.z, z0), z0))
1979
+ C = apply_operators(C, ops0,
1980
+ make_derivative_operator(f.M.subs(f.z, z0)
1981
+ + prem*eye(f.M.shape[0]), z0))
1982
+
1983
+ if premult == 1:
1984
+ C = C.applyfunc(make_simp(z0))
1985
+ r = reduce(lambda s,m: s+m[0]*m[1], zip(C, f.B.subs(f.z, z0)), S.Zero)*premult
1986
+ res = r.subs(z0, z)
1987
+ if rewrite:
1988
+ res = res.rewrite(rewrite)
1989
+ return res
1990
+
1991
+ # TODO
1992
+ # The following would be possible:
1993
+ # *) PFD Duplication (see Kelly Roach's paper)
1994
+ # *) In a similar spirit, try_lerchphi() can be generalised considerably.
1995
+
1996
+ global _collection
1997
+ if _collection is None:
1998
+ _collection = FormulaCollection()
1999
+
2000
+ debug('Trying to expand hypergeometric function ', func)
2001
+
2002
+ # First reduce order as much as possible.
2003
+ func, ops = reduce_order(func)
2004
+ if ops:
2005
+ debug(' Reduced order to ', func)
2006
+ else:
2007
+ debug(' Could not reduce order.')
2008
+
2009
+ # Now try polynomial cases
2010
+ res = try_polynomial(func, z0)
2011
+ if res is not None:
2012
+ debug(' Recognised polynomial.')
2013
+ p = apply_operators(res, ops, lambda f: z0*f.diff(z0))
2014
+ p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0))
2015
+ return unpolarify(simplify(p).subs(z0, z))
2016
+
2017
+ # Try to recognise a shifted sum.
2018
+ p = S.Zero
2019
+ res = try_shifted_sum(func, z0)
2020
+ if res is not None:
2021
+ func, nops, p = res
2022
+ debug(' Recognised shifted sum, reduced order to ', func)
2023
+ ops += nops
2024
+
2025
+ # apply the plan for poly
2026
+ p = apply_operators(p, ops, lambda f: z0*f.diff(z0))
2027
+ p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0))
2028
+ p = simplify(p).subs(z0, z)
2029
+
2030
+ # Try special expansions early.
2031
+ if unpolarify(z) in [1, -1] and (len(func.ap), len(func.bq)) == (2, 1):
2032
+ f = build_hypergeometric_formula(func)
2033
+ r = carryout_plan(f, ops).replace(hyper, hyperexpand_special)
2034
+ if not r.has(hyper):
2035
+ return r + p
2036
+
2037
+ # Try to find a formula in our collection
2038
+ formula = _collection.lookup_origin(func)
2039
+
2040
+ # Now try a lerch phi formula
2041
+ if formula is None:
2042
+ formula = try_lerchphi(func)
2043
+
2044
+ if formula is None:
2045
+ debug(' Could not find an origin. ',
2046
+ 'Will return answer in terms of '
2047
+ 'simpler hypergeometric functions.')
2048
+ formula = build_hypergeometric_formula(func)
2049
+
2050
+ debug(' Found an origin: ', formula.closed_form, ' ', formula.func)
2051
+
2052
+ # We need to find the operators that convert formula into func.
2053
+ ops += devise_plan(func, formula.func, z0)
2054
+
2055
+ # Now carry out the plan.
2056
+ r = carryout_plan(formula, ops) + p
2057
+
2058
+ return powdenest(r, polar=True).replace(hyper, hyperexpand_special)
2059
+
2060
+
2061
+ def devise_plan_meijer(fro, to, z):
2062
+ """
2063
+ Find operators to convert G-function ``fro`` into G-function ``to``.
2064
+
2065
+ Explanation
2066
+ ===========
2067
+
2068
+ It is assumed that ``fro`` and ``to`` have the same signatures, and that in fact
2069
+ any corresponding pair of parameters differs by integers, and a direct path
2070
+ is possible. I.e. if there are parameters a1 b1 c1 and a2 b2 c2 it is
2071
+ assumed that a1 can be shifted to a2, etc. The only thing this routine
2072
+ determines is the order of shifts to apply, nothing clever will be tried.
2073
+ It is also assumed that ``fro`` is suitable.
2074
+
2075
+ Examples
2076
+ ========
2077
+
2078
+ >>> from sympy.simplify.hyperexpand import (devise_plan_meijer,
2079
+ ... G_Function)
2080
+ >>> from sympy.abc import z
2081
+
2082
+ Empty plan:
2083
+
2084
+ >>> devise_plan_meijer(G_Function([1], [2], [3], [4]),
2085
+ ... G_Function([1], [2], [3], [4]), z)
2086
+ []
2087
+
2088
+ Very simple plans:
2089
+
2090
+ >>> devise_plan_meijer(G_Function([0], [], [], []),
2091
+ ... G_Function([1], [], [], []), z)
2092
+ [<Increment upper a index #0 of [0], [], [], [].>]
2093
+ >>> devise_plan_meijer(G_Function([0], [], [], []),
2094
+ ... G_Function([-1], [], [], []), z)
2095
+ [<Decrement upper a=0.>]
2096
+ >>> devise_plan_meijer(G_Function([], [1], [], []),
2097
+ ... G_Function([], [2], [], []), z)
2098
+ [<Increment lower a index #0 of [], [1], [], [].>]
2099
+
2100
+ Slightly more complicated plans:
2101
+
2102
+ >>> devise_plan_meijer(G_Function([0], [], [], []),
2103
+ ... G_Function([2], [], [], []), z)
2104
+ [<Increment upper a index #0 of [1], [], [], [].>,
2105
+ <Increment upper a index #0 of [0], [], [], [].>]
2106
+ >>> devise_plan_meijer(G_Function([0], [], [0], []),
2107
+ ... G_Function([-1], [], [1], []), z)
2108
+ [<Increment upper b=0.>, <Decrement upper a=0.>]
2109
+
2110
+ Order matters:
2111
+
2112
+ >>> devise_plan_meijer(G_Function([0], [], [0], []),
2113
+ ... G_Function([1], [], [1], []), z)
2114
+ [<Increment upper a index #0 of [0], [], [1], [].>, <Increment upper b=0.>]
2115
+ """
2116
+ # TODO for now, we use the following simple heuristic: inverse-shift
2117
+ # when possible, shift otherwise. Give up if we cannot make progress.
2118
+
2119
+ def try_shift(f, t, shifter, diff, counter):
2120
+ """ Try to apply ``shifter`` in order to bring some element in ``f``
2121
+ nearer to its counterpart in ``to``. ``diff`` is +/- 1 and
2122
+ determines the effect of ``shifter``. Counter is a list of elements
2123
+ blocking the shift.
2124
+
2125
+ Return an operator if change was possible, else None.
2126
+ """
2127
+ for idx, (a, b) in enumerate(zip(f, t)):
2128
+ if (
2129
+ (a - b).is_integer and (b - a)/diff > 0 and
2130
+ all(a != x for x in counter)):
2131
+ sh = shifter(idx)
2132
+ f[idx] += diff
2133
+ return sh
2134
+ fan = list(fro.an)
2135
+ fap = list(fro.ap)
2136
+ fbm = list(fro.bm)
2137
+ fbq = list(fro.bq)
2138
+ ops = []
2139
+ change = True
2140
+ while change:
2141
+ change = False
2142
+ op = try_shift(fan, to.an,
2143
+ lambda i: MeijerUnShiftB(fan, fap, fbm, fbq, i, z),
2144
+ 1, fbm + fbq)
2145
+ if op is not None:
2146
+ ops += [op]
2147
+ change = True
2148
+ continue
2149
+ op = try_shift(fap, to.ap,
2150
+ lambda i: MeijerUnShiftD(fan, fap, fbm, fbq, i, z),
2151
+ 1, fbm + fbq)
2152
+ if op is not None:
2153
+ ops += [op]
2154
+ change = True
2155
+ continue
2156
+ op = try_shift(fbm, to.bm,
2157
+ lambda i: MeijerUnShiftA(fan, fap, fbm, fbq, i, z),
2158
+ -1, fan + fap)
2159
+ if op is not None:
2160
+ ops += [op]
2161
+ change = True
2162
+ continue
2163
+ op = try_shift(fbq, to.bq,
2164
+ lambda i: MeijerUnShiftC(fan, fap, fbm, fbq, i, z),
2165
+ -1, fan + fap)
2166
+ if op is not None:
2167
+ ops += [op]
2168
+ change = True
2169
+ continue
2170
+ op = try_shift(fan, to.an, lambda i: MeijerShiftB(fan[i]), -1, [])
2171
+ if op is not None:
2172
+ ops += [op]
2173
+ change = True
2174
+ continue
2175
+ op = try_shift(fap, to.ap, lambda i: MeijerShiftD(fap[i]), -1, [])
2176
+ if op is not None:
2177
+ ops += [op]
2178
+ change = True
2179
+ continue
2180
+ op = try_shift(fbm, to.bm, lambda i: MeijerShiftA(fbm[i]), 1, [])
2181
+ if op is not None:
2182
+ ops += [op]
2183
+ change = True
2184
+ continue
2185
+ op = try_shift(fbq, to.bq, lambda i: MeijerShiftC(fbq[i]), 1, [])
2186
+ if op is not None:
2187
+ ops += [op]
2188
+ change = True
2189
+ continue
2190
+ if fan != list(to.an) or fap != list(to.ap) or fbm != list(to.bm) or \
2191
+ fbq != list(to.bq):
2192
+ raise NotImplementedError('Could not devise plan.')
2193
+ ops.reverse()
2194
+ return ops
2195
+
2196
+ _meijercollection = None
2197
+
2198
+
2199
+ def _meijergexpand(func, z0, allow_hyper=False, rewrite='default',
2200
+ place=None):
2201
+ """
2202
+ Try to find an expression for the Meijer G function specified
2203
+ by the G_Function ``func``. If ``allow_hyper`` is True, then returning
2204
+ an expression in terms of hypergeometric functions is allowed.
2205
+
2206
+ Currently this just does Slater's theorem.
2207
+ If expansions exist both at zero and at infinity, ``place``
2208
+ can be set to ``0`` or ``zoo`` for the preferred choice.
2209
+ """
2210
+ global _meijercollection
2211
+ if _meijercollection is None:
2212
+ _meijercollection = MeijerFormulaCollection()
2213
+ if rewrite == 'default':
2214
+ rewrite = None
2215
+
2216
+ func0 = func
2217
+ debug('Try to expand Meijer G function corresponding to ', func)
2218
+
2219
+ # We will play games with analytic continuation - rather use a fresh symbol
2220
+ z = Dummy('z')
2221
+
2222
+ func, ops = reduce_order_meijer(func)
2223
+ if ops:
2224
+ debug(' Reduced order to ', func)
2225
+ else:
2226
+ debug(' Could not reduce order.')
2227
+
2228
+ # Try to find a direct formula
2229
+ f = _meijercollection.lookup_origin(func)
2230
+ if f is not None:
2231
+ debug(' Found a Meijer G formula: ', f.func)
2232
+ ops += devise_plan_meijer(f.func, func, z)
2233
+
2234
+ # Now carry out the plan.
2235
+ C = apply_operators(f.C.subs(f.z, z), ops,
2236
+ make_derivative_operator(f.M.subs(f.z, z), z))
2237
+
2238
+ C = C.applyfunc(make_simp(z))
2239
+ r = C*f.B.subs(f.z, z)
2240
+ r = r[0].subs(z, z0)
2241
+ return powdenest(r, polar=True)
2242
+
2243
+ debug(" Could not find a direct formula. Trying Slater's theorem.")
2244
+
2245
+ # TODO the following would be possible:
2246
+ # *) Paired Index Theorems
2247
+ # *) PFD Duplication
2248
+ # (See Kelly Roach's paper for details on either.)
2249
+ #
2250
+ # TODO Also, we tend to create combinations of gamma functions that can be
2251
+ # simplified.
2252
+
2253
+ def can_do(pbm, pap):
2254
+ """ Test if slater applies. """
2255
+ for i in pbm:
2256
+ if len(pbm[i]) > 1:
2257
+ l = 0
2258
+ if i in pap:
2259
+ l = len(pap[i])
2260
+ if l + 1 < len(pbm[i]):
2261
+ return False
2262
+ return True
2263
+
2264
+ def do_slater(an, bm, ap, bq, z, zfinal):
2265
+ # zfinal is the value that will eventually be substituted for z.
2266
+ # We pass it to _hyperexpand to improve performance.
2267
+ func = G_Function(an, bm, ap, bq)
2268
+ _, pbm, pap, _ = func.compute_buckets()
2269
+ if not can_do(pbm, pap):
2270
+ return S.Zero, False
2271
+
2272
+ cond = len(an) + len(ap) < len(bm) + len(bq)
2273
+ if len(an) + len(ap) == len(bm) + len(bq):
2274
+ cond = abs(z) < 1
2275
+ if cond is False:
2276
+ return S.Zero, False
2277
+
2278
+ res = S.Zero
2279
+ for m in pbm:
2280
+ if len(pbm[m]) == 1:
2281
+ bh = pbm[m][0]
2282
+ fac = 1
2283
+ bo = list(bm)
2284
+ bo.remove(bh)
2285
+ for bj in bo:
2286
+ fac *= gamma(bj - bh)
2287
+ for aj in an:
2288
+ fac *= gamma(1 + bh - aj)
2289
+ for bj in bq:
2290
+ fac /= gamma(1 + bh - bj)
2291
+ for aj in ap:
2292
+ fac /= gamma(aj - bh)
2293
+ nap = [1 + bh - a for a in list(an) + list(ap)]
2294
+ nbq = [1 + bh - b for b in list(bo) + list(bq)]
2295
+
2296
+ k = polar_lift(S.NegativeOne**(len(ap) - len(bm)))
2297
+ harg = k*zfinal
2298
+ # NOTE even though k "is" +-1, this has to be t/k instead of
2299
+ # t*k ... we are using polar numbers for consistency!
2300
+ premult = (t/k)**bh
2301
+ hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
2302
+ t, premult, bh, rewrite=None)
2303
+ res += fac * hyp
2304
+ else:
2305
+ b_ = pbm[m][0]
2306
+ ki = [bi - b_ for bi in pbm[m][1:]]
2307
+ u = len(ki)
2308
+ li = [ai - b_ for ai in pap[m][:u + 1]]
2309
+ bo = list(bm)
2310
+ for b in pbm[m]:
2311
+ bo.remove(b)
2312
+ ao = list(ap)
2313
+ for a in pap[m][:u]:
2314
+ ao.remove(a)
2315
+ lu = li[-1]
2316
+ di = [l - k for (l, k) in zip(li, ki)]
2317
+
2318
+ # We first work out the integrand:
2319
+ s = Dummy('s')
2320
+ integrand = z**s
2321
+ for b in bm:
2322
+ if not Mod(b, 1) and b.is_Number:
2323
+ b = int(round(b))
2324
+ integrand *= gamma(b - s)
2325
+ for a in an:
2326
+ integrand *= gamma(1 - a + s)
2327
+ for b in bq:
2328
+ integrand /= gamma(1 - b + s)
2329
+ for a in ap:
2330
+ integrand /= gamma(a - s)
2331
+
2332
+ # Now sum the finitely many residues:
2333
+ # XXX This speeds up some cases - is it a good idea?
2334
+ integrand = expand_func(integrand)
2335
+ for r in range(int(round(lu))):
2336
+ resid = residue(integrand, s, b_ + r)
2337
+ resid = apply_operators(resid, ops, lambda f: z*f.diff(z))
2338
+ res -= resid
2339
+
2340
+ # Now the hypergeometric term.
2341
+ au = b_ + lu
2342
+ k = polar_lift(S.NegativeOne**(len(ao) + len(bo) + 1))
2343
+ harg = k*zfinal
2344
+ premult = (t/k)**au
2345
+ nap = [1 + au - a for a in list(an) + list(ap)] + [1]
2346
+ nbq = [1 + au - b for b in list(bm) + list(bq)]
2347
+
2348
+ hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
2349
+ t, premult, au, rewrite=None)
2350
+
2351
+ C = S.NegativeOne**(lu)/factorial(lu)
2352
+ for i in range(u):
2353
+ C *= S.NegativeOne**di[i]/rf(lu - li[i] + 1, di[i])
2354
+ for a in an:
2355
+ C *= gamma(1 - a + au)
2356
+ for b in bo:
2357
+ C *= gamma(b - au)
2358
+ for a in ao:
2359
+ C /= gamma(a - au)
2360
+ for b in bq:
2361
+ C /= gamma(1 - b + au)
2362
+
2363
+ res += C*hyp
2364
+
2365
+ return res, cond
2366
+
2367
+ t = Dummy('t')
2368
+ slater1, cond1 = do_slater(func.an, func.bm, func.ap, func.bq, z, z0)
2369
+
2370
+ def tr(l):
2371
+ return [1 - x for x in l]
2372
+
2373
+ for op in ops:
2374
+ op._poly = Poly(op._poly.subs({z: 1/t, _x: -_x}), _x)
2375
+ slater2, cond2 = do_slater(tr(func.bm), tr(func.an), tr(func.bq), tr(func.ap),
2376
+ t, 1/z0)
2377
+
2378
+ slater1 = powdenest(slater1.subs(z, z0), polar=True)
2379
+ slater2 = powdenest(slater2.subs(t, 1/z0), polar=True)
2380
+ if not isinstance(cond2, bool):
2381
+ cond2 = cond2.subs(t, 1/z)
2382
+
2383
+ m = func(z)
2384
+ if m.delta > 0 or \
2385
+ (m.delta == 0 and len(m.ap) == len(m.bq) and
2386
+ (re(m.nu) < -1) is not False and polar_lift(z0) == polar_lift(1)):
2387
+ # The condition delta > 0 means that the convergence region is
2388
+ # connected. Any expression we find can be continued analytically
2389
+ # to the entire convergence region.
2390
+ # The conditions delta==0, p==q, re(nu) < -1 imply that G is continuous
2391
+ # on the positive reals, so the values at z=1 agree.
2392
+ if cond1 is not False:
2393
+ cond1 = True
2394
+ if cond2 is not False:
2395
+ cond2 = True
2396
+
2397
+ if cond1 is True:
2398
+ slater1 = slater1.rewrite(rewrite or 'nonrep')
2399
+ else:
2400
+ slater1 = slater1.rewrite(rewrite or 'nonrepsmall')
2401
+ if cond2 is True:
2402
+ slater2 = slater2.rewrite(rewrite or 'nonrep')
2403
+ else:
2404
+ slater2 = slater2.rewrite(rewrite or 'nonrepsmall')
2405
+
2406
+ if cond1 is not False and cond2 is not False:
2407
+ # If one condition is False, there is no choice.
2408
+ if place == 0:
2409
+ cond2 = False
2410
+ if place == zoo:
2411
+ cond1 = False
2412
+
2413
+ if not isinstance(cond1, bool):
2414
+ cond1 = cond1.subs(z, z0)
2415
+ if not isinstance(cond2, bool):
2416
+ cond2 = cond2.subs(z, z0)
2417
+
2418
+ def weight(expr, cond):
2419
+ if cond is True:
2420
+ c0 = 0
2421
+ elif cond is False:
2422
+ c0 = 1
2423
+ else:
2424
+ c0 = 2
2425
+ if expr.has(oo, zoo, -oo, nan):
2426
+ # XXX this actually should not happen, but consider
2427
+ # S('meijerg(((0, -1/2, 0, -1/2, 1/2), ()), ((0,),
2428
+ # (-1/2, -1/2, -1/2, -1)), exp_polar(I*pi))/4')
2429
+ c0 = 3
2430
+ return (c0, expr.count(hyper), expr.count_ops())
2431
+
2432
+ w1 = weight(slater1, cond1)
2433
+ w2 = weight(slater2, cond2)
2434
+ if min(w1, w2) <= (0, 1, oo):
2435
+ if w1 < w2:
2436
+ return slater1
2437
+ else:
2438
+ return slater2
2439
+ if max(w1[0], w2[0]) <= 1 and max(w1[1], w2[1]) <= 1:
2440
+ return Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True))
2441
+
2442
+ # We couldn't find an expression without hypergeometric functions.
2443
+ # TODO it would be helpful to give conditions under which the integral
2444
+ # is known to diverge.
2445
+ r = Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True))
2446
+ if r.has(hyper) and not allow_hyper:
2447
+ debug(' Could express using hypergeometric functions, '
2448
+ 'but not allowed.')
2449
+ if not r.has(hyper) or allow_hyper:
2450
+ return r
2451
+
2452
+ return func0(z0)
2453
+
2454
+
2455
+ def hyperexpand(f, allow_hyper=False, rewrite='default', place=None):
2456
+ """
2457
+ Expand hypergeometric functions. If allow_hyper is True, allow partial
2458
+ simplification (that is a result different from input,
2459
+ but still containing hypergeometric functions).
2460
+
2461
+ If a G-function has expansions both at zero and at infinity,
2462
+ ``place`` can be set to ``0`` or ``zoo`` to indicate the
2463
+ preferred choice.
2464
+
2465
+ Examples
2466
+ ========
2467
+
2468
+ >>> from sympy.simplify.hyperexpand import hyperexpand
2469
+ >>> from sympy.functions import hyper
2470
+ >>> from sympy.abc import z
2471
+ >>> hyperexpand(hyper([], [], z))
2472
+ exp(z)
2473
+
2474
+ Non-hyperegeometric parts of the expression and hypergeometric expressions
2475
+ that are not recognised are left unchanged:
2476
+
2477
+ >>> hyperexpand(1 + hyper([1, 1, 1], [], z))
2478
+ hyper((1, 1, 1), (), z) + 1
2479
+ """
2480
+ f = sympify(f)
2481
+
2482
+ def do_replace(ap, bq, z):
2483
+ r = _hyperexpand(Hyper_Function(ap, bq), z, rewrite=rewrite)
2484
+ if r is None:
2485
+ return hyper(ap, bq, z)
2486
+ else:
2487
+ return r
2488
+
2489
+ def do_meijer(ap, bq, z):
2490
+ r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z,
2491
+ allow_hyper, rewrite=rewrite, place=place)
2492
+ if not r.has(nan, zoo, oo, -oo):
2493
+ return r
2494
+ return f.replace(hyper, do_replace).replace(meijerg, do_meijer)
vllm/lib/python3.10/site-packages/sympy/simplify/ratsimp.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import combinations_with_replacement
2
+ from sympy.core import symbols, Add, Dummy
3
+ from sympy.core.numbers import Rational
4
+ from sympy.polys import cancel, ComputationFailed, parallel_poly_from_expr, reduced, Poly
5
+ from sympy.polys.monomials import Monomial, monomial_div
6
+ from sympy.polys.polyerrors import DomainError, PolificationFailed
7
+ from sympy.utilities.misc import debug, debugf
8
+
9
+ def ratsimp(expr):
10
+ """
11
+ Put an expression over a common denominator, cancel and reduce.
12
+
13
+ Examples
14
+ ========
15
+
16
+ >>> from sympy import ratsimp
17
+ >>> from sympy.abc import x, y
18
+ >>> ratsimp(1/x + 1/y)
19
+ (x + y)/(x*y)
20
+ """
21
+
22
+ f, g = cancel(expr).as_numer_denom()
23
+ try:
24
+ Q, r = reduced(f, [g], field=True, expand=False)
25
+ except ComputationFailed:
26
+ return f/g
27
+
28
+ return Add(*Q) + cancel(r/g)
29
+
30
+
31
+ def ratsimpmodprime(expr, G, *gens, quick=True, polynomial=False, **args):
32
+ """
33
+ Simplifies a rational expression ``expr`` modulo the prime ideal
34
+ generated by ``G``. ``G`` should be a Groebner basis of the
35
+ ideal.
36
+
37
+ Examples
38
+ ========
39
+
40
+ >>> from sympy.simplify.ratsimp import ratsimpmodprime
41
+ >>> from sympy.abc import x, y
42
+ >>> eq = (x + y**5 + y)/(x - y)
43
+ >>> ratsimpmodprime(eq, [x*y**5 - x - y], x, y, order='lex')
44
+ (-x**2 - x*y - x - y)/(-x**2 + x*y)
45
+
46
+ If ``polynomial`` is ``False``, the algorithm computes a rational
47
+ simplification which minimizes the sum of the total degrees of
48
+ the numerator and the denominator.
49
+
50
+ If ``polynomial`` is ``True``, this function just brings numerator and
51
+ denominator into a canonical form. This is much faster, but has
52
+ potentially worse results.
53
+
54
+ References
55
+ ==========
56
+
57
+ .. [1] M. Monagan, R. Pearce, Rational Simplification Modulo a Polynomial
58
+ Ideal, https://dl.acm.org/doi/pdf/10.1145/1145768.1145809
59
+ (specifically, the second algorithm)
60
+ """
61
+ from sympy.solvers.solvers import solve
62
+
63
+ debug('ratsimpmodprime', expr)
64
+
65
+ # usual preparation of polynomials:
66
+
67
+ num, denom = cancel(expr).as_numer_denom()
68
+
69
+ try:
70
+ polys, opt = parallel_poly_from_expr([num, denom] + G, *gens, **args)
71
+ except PolificationFailed:
72
+ return expr
73
+
74
+ domain = opt.domain
75
+
76
+ if domain.has_assoc_Field:
77
+ opt.domain = domain.get_field()
78
+ else:
79
+ raise DomainError(
80
+ "Cannot compute rational simplification over %s" % domain)
81
+
82
+ # compute only once
83
+ leading_monomials = [g.LM(opt.order) for g in polys[2:]]
84
+ tested = set()
85
+
86
+ def staircase(n):
87
+ """
88
+ Compute all monomials with degree less than ``n`` that are
89
+ not divisible by any element of ``leading_monomials``.
90
+ """
91
+ if n == 0:
92
+ return [1]
93
+ S = []
94
+ for mi in combinations_with_replacement(range(len(opt.gens)), n):
95
+ m = [0]*len(opt.gens)
96
+ for i in mi:
97
+ m[i] += 1
98
+ if all(monomial_div(m, lmg) is None for lmg in
99
+ leading_monomials):
100
+ S.append(m)
101
+
102
+ return [Monomial(s).as_expr(*opt.gens) for s in S] + staircase(n - 1)
103
+
104
+ def _ratsimpmodprime(a, b, allsol, N=0, D=0):
105
+ r"""
106
+ Computes a rational simplification of ``a/b`` which minimizes
107
+ the sum of the total degrees of the numerator and the denominator.
108
+
109
+ Explanation
110
+ ===========
111
+
112
+ The algorithm proceeds by looking at ``a * d - b * c`` modulo
113
+ the ideal generated by ``G`` for some ``c`` and ``d`` with degree
114
+ less than ``a`` and ``b`` respectively.
115
+ The coefficients of ``c`` and ``d`` are indeterminates and thus
116
+ the coefficients of the normalform of ``a * d - b * c`` are
117
+ linear polynomials in these indeterminates.
118
+ If these linear polynomials, considered as system of
119
+ equations, have a nontrivial solution, then `\frac{a}{b}
120
+ \equiv \frac{c}{d}` modulo the ideal generated by ``G``. So,
121
+ by construction, the degree of ``c`` and ``d`` is less than
122
+ the degree of ``a`` and ``b``, so a simpler representation
123
+ has been found.
124
+ After a simpler representation has been found, the algorithm
125
+ tries to reduce the degree of the numerator and denominator
126
+ and returns the result afterwards.
127
+
128
+ As an extension, if quick=False, we look at all possible degrees such
129
+ that the total degree is less than *or equal to* the best current
130
+ solution. We retain a list of all solutions of minimal degree, and try
131
+ to find the best one at the end.
132
+ """
133
+ c, d = a, b
134
+ steps = 0
135
+
136
+ maxdeg = a.total_degree() + b.total_degree()
137
+ if quick:
138
+ bound = maxdeg - 1
139
+ else:
140
+ bound = maxdeg
141
+ while N + D <= bound:
142
+ if (N, D) in tested:
143
+ break
144
+ tested.add((N, D))
145
+
146
+ M1 = staircase(N)
147
+ M2 = staircase(D)
148
+ debugf('%s / %s: %s, %s', (N, D, M1, M2))
149
+
150
+ Cs = symbols("c:%d" % len(M1), cls=Dummy)
151
+ Ds = symbols("d:%d" % len(M2), cls=Dummy)
152
+ ng = Cs + Ds
153
+
154
+ c_hat = Poly(
155
+ sum(Cs[i] * M1[i] for i in range(len(M1))), opt.gens + ng)
156
+ d_hat = Poly(
157
+ sum(Ds[i] * M2[i] for i in range(len(M2))), opt.gens + ng)
158
+
159
+ r = reduced(a * d_hat - b * c_hat, G, opt.gens + ng,
160
+ order=opt.order, polys=True)[1]
161
+
162
+ S = Poly(r, gens=opt.gens).coeffs()
163
+ sol = solve(S, Cs + Ds, particular=True, quick=True)
164
+
165
+ if sol and not all(s == 0 for s in sol.values()):
166
+ c = c_hat.subs(sol)
167
+ d = d_hat.subs(sol)
168
+
169
+ # The "free" variables occurring before as parameters
170
+ # might still be in the substituted c, d, so set them
171
+ # to the value chosen before:
172
+ c = c.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds))))))
173
+ d = d.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds))))))
174
+
175
+ c = Poly(c, opt.gens)
176
+ d = Poly(d, opt.gens)
177
+ if d == 0:
178
+ raise ValueError('Ideal not prime?')
179
+
180
+ allsol.append((c_hat, d_hat, S, Cs + Ds))
181
+ if N + D != maxdeg:
182
+ allsol = [allsol[-1]]
183
+
184
+ break
185
+
186
+ steps += 1
187
+ N += 1
188
+ D += 1
189
+
190
+ if steps > 0:
191
+ c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps)
192
+ c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D)
193
+
194
+ return c, d, allsol
195
+
196
+ # preprocessing. this improves performance a bit when deg(num)
197
+ # and deg(denom) are large:
198
+ num = reduced(num, G, opt.gens, order=opt.order)[1]
199
+ denom = reduced(denom, G, opt.gens, order=opt.order)[1]
200
+
201
+ if polynomial:
202
+ return (num/denom).cancel()
203
+
204
+ c, d, allsol = _ratsimpmodprime(
205
+ Poly(num, opt.gens, domain=opt.domain), Poly(denom, opt.gens, domain=opt.domain), [])
206
+ if not quick and allsol:
207
+ debugf('Looking for best minimal solution. Got: %s', len(allsol))
208
+ newsol = []
209
+ for c_hat, d_hat, S, ng in allsol:
210
+ sol = solve(S, ng, particular=True, quick=False)
211
+ # all values of sol should be numbers; if not, solve is broken
212
+ newsol.append((c_hat.subs(sol), d_hat.subs(sol)))
213
+ c, d = min(newsol, key=lambda x: len(x[0].terms()) + len(x[1].terms()))
214
+
215
+ if not domain.is_Field:
216
+ cn, c = c.clear_denoms(convert=True)
217
+ dn, d = d.clear_denoms(convert=True)
218
+ r = Rational(cn, dn)
219
+ else:
220
+ r = Rational(1)
221
+
222
+ return (c*r.q)/(d*r.p)
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_combsimp.cpython-310.pyc ADDED
Binary file (2.73 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_cse.cpython-310.pyc ADDED
Binary file (29.4 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_epathtools.cpython-310.pyc ADDED
Binary file (3.94 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_fu.cpython-310.pyc ADDED
Binary file (22 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_function.cpython-310.pyc ADDED
Binary file (2.37 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_gammasimp.cpython-310.pyc ADDED
Binary file (4.84 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_hyperexpand.cpython-310.pyc ADDED
Binary file (36.2 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_powsimp.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_radsimp.cpython-310.pyc ADDED
Binary file (19.8 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_ratsimp.cpython-310.pyc ADDED
Binary file (2.65 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_rewrite.cpython-310.pyc ADDED
Binary file (1.3 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_simplify.cpython-310.pyc ADDED
Binary file (44.3 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_sqrtdenest.cpython-310.pyc ADDED
Binary file (8.48 kB). View file