ZTWHHH commited on
Commit
c5cace1
·
verified ·
1 Parent(s): ddf6967

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. wemm/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/testutil.cpython-310.pyc +0 -0
  2. wemm/lib/python3.10/site-packages/sympy/geometry/__init__.py +45 -0
  3. wemm/lib/python3.10/site-packages/sympy/geometry/__pycache__/exceptions.cpython-310.pyc +0 -0
  4. wemm/lib/python3.10/site-packages/sympy/geometry/__pycache__/plane.cpython-310.pyc +0 -0
  5. wemm/lib/python3.10/site-packages/sympy/geometry/curve.py +424 -0
  6. wemm/lib/python3.10/site-packages/sympy/geometry/ellipse.py +1767 -0
  7. wemm/lib/python3.10/site-packages/sympy/geometry/entity.py +641 -0
  8. wemm/lib/python3.10/site-packages/sympy/geometry/exceptions.py +5 -0
  9. wemm/lib/python3.10/site-packages/sympy/geometry/line.py +2877 -0
  10. wemm/lib/python3.10/site-packages/sympy/geometry/parabola.py +422 -0
  11. wemm/lib/python3.10/site-packages/sympy/geometry/plane.py +885 -0
  12. wemm/lib/python3.10/site-packages/sympy/geometry/point.py +1378 -0
  13. wemm/lib/python3.10/site-packages/sympy/geometry/polygon.py +2891 -0
  14. wemm/lib/python3.10/site-packages/sympy/geometry/tests/__init__.py +0 -0
  15. wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  16. wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_curve.cpython-310.pyc +0 -0
  17. wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_ellipse.cpython-310.pyc +0 -0
  18. wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_entity.cpython-310.pyc +0 -0
  19. wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_geometrysets.cpython-310.pyc +0 -0
  20. wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_point.cpython-310.pyc +0 -0
  21. wemm/lib/python3.10/site-packages/sympy/geometry/tests/test_curve.py +120 -0
  22. wemm/lib/python3.10/site-packages/sympy/geometry/tests/test_entity.py +120 -0
  23. wemm/lib/python3.10/site-packages/sympy/geometry/tests/test_plane.py +268 -0
  24. wemm/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py +676 -0
  25. wemm/lib/python3.10/site-packages/sympy/geometry/util.py +733 -0
  26. wemm/lib/python3.10/site-packages/sympy/simplify/__init__.py +60 -0
  27. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc +0 -0
  28. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc +0 -0
  29. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc +0 -0
  30. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc +0 -0
  31. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc +0 -0
  32. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc +0 -0
  33. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc +0 -0
  34. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc +0 -0
  35. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand_doc.cpython-310.pyc +0 -0
  36. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc +0 -0
  37. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc +0 -0
  38. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc +0 -0
  39. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc +0 -0
  40. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc +0 -0
  41. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/traversaltools.cpython-310.pyc +0 -0
  42. wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc +0 -0
  43. wemm/lib/python3.10/site-packages/sympy/simplify/cse_main.py +946 -0
  44. wemm/lib/python3.10/site-packages/sympy/simplify/fu.py +2111 -0
  45. wemm/lib/python3.10/site-packages/sympy/simplify/hyperexpand.py +2494 -0
  46. wemm/lib/python3.10/site-packages/sympy/simplify/radsimp.py +1227 -0
  47. wemm/lib/python3.10/site-packages/sympy/simplify/ratsimp.py +222 -0
  48. wemm/lib/python3.10/site-packages/sympy/simplify/sqrtdenest.py +678 -0
  49. wemm/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py +0 -0
  50. wemm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/__init__.cpython-310.pyc +0 -0
wemm/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/testutil.cpython-310.pyc ADDED
Binary file (9.88 kB). View file
 
wemm/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
+ ]
wemm/lib/python3.10/site-packages/sympy/geometry/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (437 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/geometry/__pycache__/plane.cpython-310.pyc ADDED
Binary file (25.7 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/geometry/curve.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Curves in 2-dimensional Euclidean space.
2
+
3
+ Contains
4
+ ========
5
+ Curve
6
+
7
+ """
8
+
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.core import diff
11
+ from sympy.core.containers import Tuple
12
+ from sympy.core.symbol import _symbol
13
+ from sympy.geometry.entity import GeometryEntity, GeometrySet
14
+ from sympy.geometry.point import Point
15
+ from sympy.integrals import integrate
16
+ from sympy.matrices import Matrix, rot_axis3
17
+ from sympy.utilities.iterables import is_sequence
18
+
19
+ from mpmath.libmp.libmpf import prec_to_dps
20
+
21
+
22
+ class Curve(GeometrySet):
23
+ """A curve in space.
24
+
25
+ A curve is defined by parametric functions for the coordinates, a
26
+ parameter and the lower and upper bounds for the parameter value.
27
+
28
+ Parameters
29
+ ==========
30
+
31
+ function : list of functions
32
+ limits : 3-tuple
33
+ Function parameter and lower and upper bounds.
34
+
35
+ Attributes
36
+ ==========
37
+
38
+ functions
39
+ parameter
40
+ limits
41
+
42
+ Raises
43
+ ======
44
+
45
+ ValueError
46
+ When `functions` are specified incorrectly.
47
+ When `limits` are specified incorrectly.
48
+
49
+ Examples
50
+ ========
51
+
52
+ >>> from sympy import Curve, sin, cos, interpolate
53
+ >>> from sympy.abc import t, a
54
+ >>> C = Curve((sin(t), cos(t)), (t, 0, 2))
55
+ >>> C.functions
56
+ (sin(t), cos(t))
57
+ >>> C.limits
58
+ (t, 0, 2)
59
+ >>> C.parameter
60
+ t
61
+ >>> C = Curve((t, interpolate([1, 4, 9, 16], t)), (t, 0, 1)); C
62
+ Curve((t, t**2), (t, 0, 1))
63
+ >>> C.subs(t, 4)
64
+ Point2D(4, 16)
65
+ >>> C.arbitrary_point(a)
66
+ Point2D(a, a**2)
67
+
68
+ See Also
69
+ ========
70
+
71
+ sympy.core.function.Function
72
+ sympy.polys.polyfuncs.interpolate
73
+
74
+ """
75
+
76
+ def __new__(cls, function, limits):
77
+ if not is_sequence(function) or len(function) != 2:
78
+ raise ValueError("Function argument should be (x(t), y(t)) "
79
+ "but got %s" % str(function))
80
+ if not is_sequence(limits) or len(limits) != 3:
81
+ raise ValueError("Limit argument should be (t, tmin, tmax) "
82
+ "but got %s" % str(limits))
83
+
84
+ return GeometryEntity.__new__(cls, Tuple(*function), Tuple(*limits))
85
+
86
+ def __call__(self, f):
87
+ return self.subs(self.parameter, f)
88
+
89
+ def _eval_subs(self, old, new):
90
+ if old == self.parameter:
91
+ return Point(*[f.subs(old, new) for f in self.functions])
92
+
93
+ def _eval_evalf(self, prec=15, **options):
94
+ f, (t, a, b) = self.args
95
+ dps = prec_to_dps(prec)
96
+ f = tuple([i.evalf(n=dps, **options) for i in f])
97
+ a, b = [i.evalf(n=dps, **options) for i in (a, b)]
98
+ return self.func(f, (t, a, b))
99
+
100
+ def arbitrary_point(self, parameter='t'):
101
+ """A parameterized point on the curve.
102
+
103
+ Parameters
104
+ ==========
105
+
106
+ parameter : str or Symbol, optional
107
+ Default value is 't'.
108
+ The Curve's parameter is selected with None or self.parameter
109
+ otherwise the provided symbol is used.
110
+
111
+ Returns
112
+ =======
113
+
114
+ Point :
115
+ Returns a point in parametric form.
116
+
117
+ Raises
118
+ ======
119
+
120
+ ValueError
121
+ When `parameter` already appears in the functions.
122
+
123
+ Examples
124
+ ========
125
+
126
+ >>> from sympy import Curve, Symbol
127
+ >>> from sympy.abc import s
128
+ >>> C = Curve([2*s, s**2], (s, 0, 2))
129
+ >>> C.arbitrary_point()
130
+ Point2D(2*t, t**2)
131
+ >>> C.arbitrary_point(C.parameter)
132
+ Point2D(2*s, s**2)
133
+ >>> C.arbitrary_point(None)
134
+ Point2D(2*s, s**2)
135
+ >>> C.arbitrary_point(Symbol('a'))
136
+ Point2D(2*a, a**2)
137
+
138
+ See Also
139
+ ========
140
+
141
+ sympy.geometry.point.Point
142
+
143
+ """
144
+ if parameter is None:
145
+ return Point(*self.functions)
146
+
147
+ tnew = _symbol(parameter, self.parameter, real=True)
148
+ t = self.parameter
149
+ if (tnew.name != t.name and
150
+ tnew.name in (f.name for f in self.free_symbols)):
151
+ raise ValueError('Symbol %s already appears in object '
152
+ 'and cannot be used as a parameter.' % tnew.name)
153
+ return Point(*[w.subs(t, tnew) for w in self.functions])
154
+
155
+ @property
156
+ def free_symbols(self):
157
+ """Return a set of symbols other than the bound symbols used to
158
+ parametrically define the Curve.
159
+
160
+ Returns
161
+ =======
162
+
163
+ set :
164
+ Set of all non-parameterized symbols.
165
+
166
+ Examples
167
+ ========
168
+
169
+ >>> from sympy.abc import t, a
170
+ >>> from sympy import Curve
171
+ >>> Curve((t, t**2), (t, 0, 2)).free_symbols
172
+ set()
173
+ >>> Curve((t, t**2), (t, a, 2)).free_symbols
174
+ {a}
175
+
176
+ """
177
+ free = set()
178
+ for a in self.functions + self.limits[1:]:
179
+ free |= a.free_symbols
180
+ free = free.difference({self.parameter})
181
+ return free
182
+
183
+ @property
184
+ def ambient_dimension(self):
185
+ """The dimension of the curve.
186
+
187
+ Returns
188
+ =======
189
+
190
+ int :
191
+ the dimension of curve.
192
+
193
+ Examples
194
+ ========
195
+
196
+ >>> from sympy.abc import t
197
+ >>> from sympy import Curve
198
+ >>> C = Curve((t, t**2), (t, 0, 2))
199
+ >>> C.ambient_dimension
200
+ 2
201
+
202
+ """
203
+
204
+ return len(self.args[0])
205
+
206
+ @property
207
+ def functions(self):
208
+ """The functions specifying the curve.
209
+
210
+ Returns
211
+ =======
212
+
213
+ functions :
214
+ list of parameterized coordinate functions.
215
+
216
+ Examples
217
+ ========
218
+
219
+ >>> from sympy.abc import t
220
+ >>> from sympy import Curve
221
+ >>> C = Curve((t, t**2), (t, 0, 2))
222
+ >>> C.functions
223
+ (t, t**2)
224
+
225
+ See Also
226
+ ========
227
+
228
+ parameter
229
+
230
+ """
231
+ return self.args[0]
232
+
233
+ @property
234
+ def limits(self):
235
+ """The limits for the curve.
236
+
237
+ Returns
238
+ =======
239
+
240
+ limits : tuple
241
+ Contains parameter and lower and upper limits.
242
+
243
+ Examples
244
+ ========
245
+
246
+ >>> from sympy.abc import t
247
+ >>> from sympy import Curve
248
+ >>> C = Curve([t, t**3], (t, -2, 2))
249
+ >>> C.limits
250
+ (t, -2, 2)
251
+
252
+ See Also
253
+ ========
254
+
255
+ plot_interval
256
+
257
+ """
258
+ return self.args[1]
259
+
260
+ @property
261
+ def parameter(self):
262
+ """The curve function variable.
263
+
264
+ Returns
265
+ =======
266
+
267
+ Symbol :
268
+ returns a bound symbol.
269
+
270
+ Examples
271
+ ========
272
+
273
+ >>> from sympy.abc import t
274
+ >>> from sympy import Curve
275
+ >>> C = Curve([t, t**2], (t, 0, 2))
276
+ >>> C.parameter
277
+ t
278
+
279
+ See Also
280
+ ========
281
+
282
+ functions
283
+
284
+ """
285
+ return self.args[1][0]
286
+
287
+ @property
288
+ def length(self):
289
+ """The curve length.
290
+
291
+ Examples
292
+ ========
293
+
294
+ >>> from sympy import Curve
295
+ >>> from sympy.abc import t
296
+ >>> Curve((t, t), (t, 0, 1)).length
297
+ sqrt(2)
298
+
299
+ """
300
+ integrand = sqrt(sum(diff(func, self.limits[0])**2 for func in self.functions))
301
+ return integrate(integrand, self.limits)
302
+
303
+ def plot_interval(self, parameter='t'):
304
+ """The plot interval for the default geometric plot of the curve.
305
+
306
+ Parameters
307
+ ==========
308
+
309
+ parameter : str or Symbol, optional
310
+ Default value is 't';
311
+ otherwise the provided symbol is used.
312
+
313
+ Returns
314
+ =======
315
+
316
+ List :
317
+ the plot interval as below:
318
+ [parameter, lower_bound, upper_bound]
319
+
320
+ Examples
321
+ ========
322
+
323
+ >>> from sympy import Curve, sin
324
+ >>> from sympy.abc import x, s
325
+ >>> Curve((x, sin(x)), (x, 1, 2)).plot_interval()
326
+ [t, 1, 2]
327
+ >>> Curve((x, sin(x)), (x, 1, 2)).plot_interval(s)
328
+ [s, 1, 2]
329
+
330
+ See Also
331
+ ========
332
+
333
+ limits : Returns limits of the parameter interval
334
+
335
+ """
336
+ t = _symbol(parameter, self.parameter, real=True)
337
+ return [t] + list(self.limits[1:])
338
+
339
+ def rotate(self, angle=0, pt=None):
340
+ """This function is used to rotate a curve along given point ``pt`` at given angle(in radian).
341
+
342
+ Parameters
343
+ ==========
344
+
345
+ angle :
346
+ the angle at which the curve will be rotated(in radian) in counterclockwise direction.
347
+ default value of angle is 0.
348
+
349
+ pt : Point
350
+ the point along which the curve will be rotated.
351
+ If no point given, the curve will be rotated around origin.
352
+
353
+ Returns
354
+ =======
355
+
356
+ Curve :
357
+ returns a curve rotated at given angle along given point.
358
+
359
+ Examples
360
+ ========
361
+
362
+ >>> from sympy import Curve, pi
363
+ >>> from sympy.abc import x
364
+ >>> Curve((x, x), (x, 0, 1)).rotate(pi/2)
365
+ Curve((-x, x), (x, 0, 1))
366
+
367
+ """
368
+ if pt:
369
+ pt = -Point(pt, dim=2)
370
+ else:
371
+ pt = Point(0,0)
372
+ rv = self.translate(*pt.args)
373
+ f = list(rv.functions)
374
+ f.append(0)
375
+ f = Matrix(1, 3, f)
376
+ f *= rot_axis3(angle)
377
+ rv = self.func(f[0, :2].tolist()[0], self.limits)
378
+ pt = -pt
379
+ return rv.translate(*pt.args)
380
+
381
+ def scale(self, x=1, y=1, pt=None):
382
+ """Override GeometryEntity.scale since Curve is not made up of Points.
383
+
384
+ Returns
385
+ =======
386
+
387
+ Curve :
388
+ returns scaled curve.
389
+
390
+ Examples
391
+ ========
392
+
393
+ >>> from sympy import Curve
394
+ >>> from sympy.abc import x
395
+ >>> Curve((x, x), (x, 0, 1)).scale(2)
396
+ Curve((2*x, x), (x, 0, 1))
397
+
398
+ """
399
+ if pt:
400
+ pt = Point(pt, dim=2)
401
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
402
+ fx, fy = self.functions
403
+ return self.func((fx*x, fy*y), self.limits)
404
+
405
+ def translate(self, x=0, y=0):
406
+ """Translate the Curve by (x, y).
407
+
408
+ Returns
409
+ =======
410
+
411
+ Curve :
412
+ returns a translated curve.
413
+
414
+ Examples
415
+ ========
416
+
417
+ >>> from sympy import Curve
418
+ >>> from sympy.abc import x
419
+ >>> Curve((x, x), (x, 0, 1)).translate(1, 2)
420
+ Curve((x + 1, x + 2), (x, 0, 1))
421
+
422
+ """
423
+ fx, fy = self.functions
424
+ return self.func((fx + x, fy + y), self.limits)
wemm/lib/python3.10/site-packages/sympy/geometry/ellipse.py ADDED
@@ -0,0 +1,1767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Elliptical geometrical entities.
2
+
3
+ Contains
4
+ * Ellipse
5
+ * Circle
6
+
7
+ """
8
+
9
+ from sympy.core.expr import Expr
10
+ from sympy.core.relational import Eq
11
+ from sympy.core import S, pi, sympify
12
+ from sympy.core.evalf import N
13
+ from sympy.core.parameters import global_parameters
14
+ from sympy.core.logic import fuzzy_bool
15
+ from sympy.core.numbers import Rational, oo
16
+ from sympy.core.sorting import ordered
17
+ from sympy.core.symbol import Dummy, uniquely_named_symbol, _symbol
18
+ from sympy.simplify import simplify, trigsimp
19
+ from sympy.functions.elementary.miscellaneous import sqrt, Max
20
+ from sympy.functions.elementary.trigonometric import cos, sin
21
+ from sympy.functions.special.elliptic_integrals import elliptic_e
22
+ from .entity import GeometryEntity, GeometrySet
23
+ from .exceptions import GeometryError
24
+ from .line import Line, Segment, Ray2D, Segment2D, Line2D, LinearEntity3D
25
+ from .point import Point, Point2D, Point3D
26
+ from .util import idiff, find
27
+ from sympy.polys import DomainError, Poly, PolynomialError
28
+ from sympy.polys.polyutils import _not_a_coeff, _nsort
29
+ from sympy.solvers import solve
30
+ from sympy.solvers.solveset import linear_coeffs
31
+ from sympy.utilities.misc import filldedent, func_name
32
+
33
+ from mpmath.libmp.libmpf import prec_to_dps
34
+
35
+ import random
36
+
37
+ x, y = [Dummy('ellipse_dummy', real=True) for i in range(2)]
38
+
39
+
40
+ class Ellipse(GeometrySet):
41
+ """An elliptical GeometryEntity.
42
+
43
+ Parameters
44
+ ==========
45
+
46
+ center : Point, optional
47
+ Default value is Point(0, 0)
48
+ hradius : number or SymPy expression, optional
49
+ vradius : number or SymPy expression, optional
50
+ eccentricity : number or SymPy expression, optional
51
+ Two of `hradius`, `vradius` and `eccentricity` must be supplied to
52
+ create an Ellipse. The third is derived from the two supplied.
53
+
54
+ Attributes
55
+ ==========
56
+
57
+ center
58
+ hradius
59
+ vradius
60
+ area
61
+ circumference
62
+ eccentricity
63
+ periapsis
64
+ apoapsis
65
+ focus_distance
66
+ foci
67
+
68
+ Raises
69
+ ======
70
+
71
+ GeometryError
72
+ When `hradius`, `vradius` and `eccentricity` are incorrectly supplied
73
+ as parameters.
74
+ TypeError
75
+ When `center` is not a Point.
76
+
77
+ See Also
78
+ ========
79
+
80
+ Circle
81
+
82
+ Notes
83
+ -----
84
+ Constructed from a center and two radii, the first being the horizontal
85
+ radius (along the x-axis) and the second being the vertical radius (along
86
+ the y-axis).
87
+
88
+ When symbolic value for hradius and vradius are used, any calculation that
89
+ refers to the foci or the major or minor axis will assume that the ellipse
90
+ has its major radius on the x-axis. If this is not true then a manual
91
+ rotation is necessary.
92
+
93
+ Examples
94
+ ========
95
+
96
+ >>> from sympy import Ellipse, Point, Rational
97
+ >>> e1 = Ellipse(Point(0, 0), 5, 1)
98
+ >>> e1.hradius, e1.vradius
99
+ (5, 1)
100
+ >>> e2 = Ellipse(Point(3, 1), hradius=3, eccentricity=Rational(4, 5))
101
+ >>> e2
102
+ Ellipse(Point2D(3, 1), 3, 9/5)
103
+
104
+ """
105
+
106
+ def __contains__(self, o):
107
+ if isinstance(o, Point):
108
+ res = self.equation(x, y).subs({x: o.x, y: o.y})
109
+ return trigsimp(simplify(res)) is S.Zero
110
+ elif isinstance(o, Ellipse):
111
+ return self == o
112
+ return False
113
+
114
+ def __eq__(self, o):
115
+ """Is the other GeometryEntity the same as this ellipse?"""
116
+ return isinstance(o, Ellipse) and (self.center == o.center and
117
+ self.hradius == o.hradius and
118
+ self.vradius == o.vradius)
119
+
120
+ def __hash__(self):
121
+ return super().__hash__()
122
+
123
+ def __new__(
124
+ cls, center=None, hradius=None, vradius=None, eccentricity=None, **kwargs):
125
+
126
+ hradius = sympify(hradius)
127
+ vradius = sympify(vradius)
128
+
129
+ if center is None:
130
+ center = Point(0, 0)
131
+ else:
132
+ if len(center) != 2:
133
+ raise ValueError('The center of "{}" must be a two dimensional point'.format(cls))
134
+ center = Point(center, dim=2)
135
+
136
+ if len(list(filter(lambda x: x is not None, (hradius, vradius, eccentricity)))) != 2:
137
+ raise ValueError(filldedent('''
138
+ Exactly two arguments of "hradius", "vradius", and
139
+ "eccentricity" must not be None.'''))
140
+
141
+ if eccentricity is not None:
142
+ eccentricity = sympify(eccentricity)
143
+ if eccentricity.is_negative:
144
+ raise GeometryError("Eccentricity of ellipse/circle should lie between [0, 1)")
145
+ elif hradius is None:
146
+ hradius = vradius / sqrt(1 - eccentricity**2)
147
+ elif vradius is None:
148
+ vradius = hradius * sqrt(1 - eccentricity**2)
149
+
150
+ if hradius == vradius:
151
+ return Circle(center, hradius, **kwargs)
152
+
153
+ if S.Zero in (hradius, vradius):
154
+ return Segment(Point(center[0] - hradius, center[1] - vradius), Point(center[0] + hradius, center[1] + vradius))
155
+
156
+ if hradius.is_real is False or vradius.is_real is False:
157
+ raise GeometryError("Invalid value encountered when computing hradius / vradius.")
158
+
159
+ return GeometryEntity.__new__(cls, center, hradius, vradius, **kwargs)
160
+
161
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
162
+ """Returns SVG ellipse element for the Ellipse.
163
+
164
+ Parameters
165
+ ==========
166
+
167
+ scale_factor : float
168
+ Multiplication factor for the SVG stroke-width. Default is 1.
169
+ fill_color : str, optional
170
+ Hex string for fill color. Default is "#66cc99".
171
+ """
172
+
173
+ c = N(self.center)
174
+ h, v = N(self.hradius), N(self.vradius)
175
+ return (
176
+ '<ellipse fill="{1}" stroke="#555555" '
177
+ 'stroke-width="{0}" opacity="0.6" cx="{2}" cy="{3}" rx="{4}" ry="{5}"/>'
178
+ ).format(2. * scale_factor, fill_color, c.x, c.y, h, v)
179
+
180
+ @property
181
+ def ambient_dimension(self):
182
+ return 2
183
+
184
+ @property
185
+ def apoapsis(self):
186
+ """The apoapsis of the ellipse.
187
+
188
+ The greatest distance between the focus and the contour.
189
+
190
+ Returns
191
+ =======
192
+
193
+ apoapsis : number
194
+
195
+ See Also
196
+ ========
197
+
198
+ periapsis : Returns shortest distance between foci and contour
199
+
200
+ Examples
201
+ ========
202
+
203
+ >>> from sympy import Point, Ellipse
204
+ >>> p1 = Point(0, 0)
205
+ >>> e1 = Ellipse(p1, 3, 1)
206
+ >>> e1.apoapsis
207
+ 2*sqrt(2) + 3
208
+
209
+ """
210
+ return self.major * (1 + self.eccentricity)
211
+
212
+ def arbitrary_point(self, parameter='t'):
213
+ """A parameterized point on the ellipse.
214
+
215
+ Parameters
216
+ ==========
217
+
218
+ parameter : str, optional
219
+ Default value is 't'.
220
+
221
+ Returns
222
+ =======
223
+
224
+ arbitrary_point : Point
225
+
226
+ Raises
227
+ ======
228
+
229
+ ValueError
230
+ When `parameter` already appears in the functions.
231
+
232
+ See Also
233
+ ========
234
+
235
+ sympy.geometry.point.Point
236
+
237
+ Examples
238
+ ========
239
+
240
+ >>> from sympy import Point, Ellipse
241
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
242
+ >>> e1.arbitrary_point()
243
+ Point2D(3*cos(t), 2*sin(t))
244
+
245
+ """
246
+ t = _symbol(parameter, real=True)
247
+ if t.name in (f.name for f in self.free_symbols):
248
+ raise ValueError(filldedent('Symbol %s already appears in object '
249
+ 'and cannot be used as a parameter.' % t.name))
250
+ return Point(self.center.x + self.hradius*cos(t),
251
+ self.center.y + self.vradius*sin(t))
252
+
253
+ @property
254
+ def area(self):
255
+ """The area of the ellipse.
256
+
257
+ Returns
258
+ =======
259
+
260
+ area : number
261
+
262
+ Examples
263
+ ========
264
+
265
+ >>> from sympy import Point, Ellipse
266
+ >>> p1 = Point(0, 0)
267
+ >>> e1 = Ellipse(p1, 3, 1)
268
+ >>> e1.area
269
+ 3*pi
270
+
271
+ """
272
+ return simplify(S.Pi * self.hradius * self.vradius)
273
+
274
+ @property
275
+ def bounds(self):
276
+ """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
277
+ rectangle for the geometric figure.
278
+
279
+ """
280
+
281
+ h, v = self.hradius, self.vradius
282
+ return (self.center.x - h, self.center.y - v, self.center.x + h, self.center.y + v)
283
+
284
+ @property
285
+ def center(self):
286
+ """The center of the ellipse.
287
+
288
+ Returns
289
+ =======
290
+
291
+ center : number
292
+
293
+ See Also
294
+ ========
295
+
296
+ sympy.geometry.point.Point
297
+
298
+ Examples
299
+ ========
300
+
301
+ >>> from sympy import Point, Ellipse
302
+ >>> p1 = Point(0, 0)
303
+ >>> e1 = Ellipse(p1, 3, 1)
304
+ >>> e1.center
305
+ Point2D(0, 0)
306
+
307
+ """
308
+ return self.args[0]
309
+
310
+ @property
311
+ def circumference(self):
312
+ """The circumference of the ellipse.
313
+
314
+ Examples
315
+ ========
316
+
317
+ >>> from sympy import Point, Ellipse
318
+ >>> p1 = Point(0, 0)
319
+ >>> e1 = Ellipse(p1, 3, 1)
320
+ >>> e1.circumference
321
+ 12*elliptic_e(8/9)
322
+
323
+ """
324
+ if self.eccentricity == 1:
325
+ # degenerate
326
+ return 4*self.major
327
+ elif self.eccentricity == 0:
328
+ # circle
329
+ return 2*pi*self.hradius
330
+ else:
331
+ return 4*self.major*elliptic_e(self.eccentricity**2)
332
+
333
+ @property
334
+ def eccentricity(self):
335
+ """The eccentricity of the ellipse.
336
+
337
+ Returns
338
+ =======
339
+
340
+ eccentricity : number
341
+
342
+ Examples
343
+ ========
344
+
345
+ >>> from sympy import Point, Ellipse, sqrt
346
+ >>> p1 = Point(0, 0)
347
+ >>> e1 = Ellipse(p1, 3, sqrt(2))
348
+ >>> e1.eccentricity
349
+ sqrt(7)/3
350
+
351
+ """
352
+ return self.focus_distance / self.major
353
+
354
+ def encloses_point(self, p):
355
+ """
356
+ Return True if p is enclosed by (is inside of) self.
357
+
358
+ Notes
359
+ -----
360
+ Being on the border of self is considered False.
361
+
362
+ Parameters
363
+ ==========
364
+
365
+ p : Point
366
+
367
+ Returns
368
+ =======
369
+
370
+ encloses_point : True, False or None
371
+
372
+ See Also
373
+ ========
374
+
375
+ sympy.geometry.point.Point
376
+
377
+ Examples
378
+ ========
379
+
380
+ >>> from sympy import Ellipse, S
381
+ >>> from sympy.abc import t
382
+ >>> e = Ellipse((0, 0), 3, 2)
383
+ >>> e.encloses_point((0, 0))
384
+ True
385
+ >>> e.encloses_point(e.arbitrary_point(t).subs(t, S.Half))
386
+ False
387
+ >>> e.encloses_point((4, 0))
388
+ False
389
+
390
+ """
391
+ p = Point(p, dim=2)
392
+ if p in self:
393
+ return False
394
+
395
+ if len(self.foci) == 2:
396
+ # if the combined distance from the foci to p (h1 + h2) is less
397
+ # than the combined distance from the foci to the minor axis
398
+ # (which is the same as the major axis length) then p is inside
399
+ # the ellipse
400
+ h1, h2 = [f.distance(p) for f in self.foci]
401
+ test = 2*self.major - (h1 + h2)
402
+ else:
403
+ test = self.radius - self.center.distance(p)
404
+
405
+ return fuzzy_bool(test.is_positive)
406
+
407
+ def equation(self, x='x', y='y', _slope=None):
408
+ """
409
+ Returns the equation of an ellipse aligned with the x and y axes;
410
+ when slope is given, the equation returned corresponds to an ellipse
411
+ with a major axis having that slope.
412
+
413
+ Parameters
414
+ ==========
415
+
416
+ x : str, optional
417
+ Label for the x-axis. Default value is 'x'.
418
+ y : str, optional
419
+ Label for the y-axis. Default value is 'y'.
420
+ _slope : Expr, optional
421
+ The slope of the major axis. Ignored when 'None'.
422
+
423
+ Returns
424
+ =======
425
+
426
+ equation : SymPy expression
427
+
428
+ See Also
429
+ ========
430
+
431
+ arbitrary_point : Returns parameterized point on ellipse
432
+
433
+ Examples
434
+ ========
435
+
436
+ >>> from sympy import Point, Ellipse, pi
437
+ >>> from sympy.abc import x, y
438
+ >>> e1 = Ellipse(Point(1, 0), 3, 2)
439
+ >>> eq1 = e1.equation(x, y); eq1
440
+ y**2/4 + (x/3 - 1/3)**2 - 1
441
+ >>> eq2 = e1.equation(x, y, _slope=1); eq2
442
+ (-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1
443
+
444
+ A point on e1 satisfies eq1. Let's use one on the x-axis:
445
+
446
+ >>> p1 = e1.center + Point(e1.major, 0)
447
+ >>> assert eq1.subs(x, p1.x).subs(y, p1.y) == 0
448
+
449
+ When rotated the same as the rotated ellipse, about the center
450
+ point of the ellipse, it will satisfy the rotated ellipse's
451
+ equation, too:
452
+
453
+ >>> r1 = p1.rotate(pi/4, e1.center)
454
+ >>> assert eq2.subs(x, r1.x).subs(y, r1.y) == 0
455
+
456
+ References
457
+ ==========
458
+
459
+ .. [1] https://math.stackexchange.com/questions/108270/what-is-the-equation-of-an-ellipse-that-is-not-aligned-with-the-axis
460
+ .. [2] https://en.wikipedia.org/wiki/Ellipse#Shifted_ellipse
461
+
462
+ """
463
+
464
+ x = _symbol(x, real=True)
465
+ y = _symbol(y, real=True)
466
+
467
+ dx = x - self.center.x
468
+ dy = y - self.center.y
469
+
470
+ if _slope is not None:
471
+ L = (dy - _slope*dx)**2
472
+ l = (_slope*dy + dx)**2
473
+ h = 1 + _slope**2
474
+ b = h*self.major**2
475
+ a = h*self.minor**2
476
+ return l/b + L/a - 1
477
+
478
+ else:
479
+ t1 = (dx/self.hradius)**2
480
+ t2 = (dy/self.vradius)**2
481
+ return t1 + t2 - 1
482
+
483
+ def evolute(self, x='x', y='y'):
484
+ """The equation of evolute of the ellipse.
485
+
486
+ Parameters
487
+ ==========
488
+
489
+ x : str, optional
490
+ Label for the x-axis. Default value is 'x'.
491
+ y : str, optional
492
+ Label for the y-axis. Default value is 'y'.
493
+
494
+ Returns
495
+ =======
496
+
497
+ equation : SymPy expression
498
+
499
+ Examples
500
+ ========
501
+
502
+ >>> from sympy import Point, Ellipse
503
+ >>> e1 = Ellipse(Point(1, 0), 3, 2)
504
+ >>> e1.evolute()
505
+ 2**(2/3)*y**(2/3) + (3*x - 3)**(2/3) - 5**(2/3)
506
+ """
507
+ if len(self.args) != 3:
508
+ raise NotImplementedError('Evolute of arbitrary Ellipse is not supported.')
509
+ x = _symbol(x, real=True)
510
+ y = _symbol(y, real=True)
511
+ t1 = (self.hradius*(x - self.center.x))**Rational(2, 3)
512
+ t2 = (self.vradius*(y - self.center.y))**Rational(2, 3)
513
+ return t1 + t2 - (self.hradius**2 - self.vradius**2)**Rational(2, 3)
514
+
515
+ @property
516
+ def foci(self):
517
+ """The foci of the ellipse.
518
+
519
+ Notes
520
+ -----
521
+ The foci can only be calculated if the major/minor axes are known.
522
+
523
+ Raises
524
+ ======
525
+
526
+ ValueError
527
+ When the major and minor axis cannot be determined.
528
+
529
+ See Also
530
+ ========
531
+
532
+ sympy.geometry.point.Point
533
+ focus_distance : Returns the distance between focus and center
534
+
535
+ Examples
536
+ ========
537
+
538
+ >>> from sympy import Point, Ellipse
539
+ >>> p1 = Point(0, 0)
540
+ >>> e1 = Ellipse(p1, 3, 1)
541
+ >>> e1.foci
542
+ (Point2D(-2*sqrt(2), 0), Point2D(2*sqrt(2), 0))
543
+
544
+ """
545
+ c = self.center
546
+ hr, vr = self.hradius, self.vradius
547
+ if hr == vr:
548
+ return (c, c)
549
+
550
+ # calculate focus distance manually, since focus_distance calls this
551
+ # routine
552
+ fd = sqrt(self.major**2 - self.minor**2)
553
+ if hr == self.minor:
554
+ # foci on the y-axis
555
+ return (c + Point(0, -fd), c + Point(0, fd))
556
+ elif hr == self.major:
557
+ # foci on the x-axis
558
+ return (c + Point(-fd, 0), c + Point(fd, 0))
559
+
560
+ @property
561
+ def focus_distance(self):
562
+ """The focal distance of the ellipse.
563
+
564
+ The distance between the center and one focus.
565
+
566
+ Returns
567
+ =======
568
+
569
+ focus_distance : number
570
+
571
+ See Also
572
+ ========
573
+
574
+ foci
575
+
576
+ Examples
577
+ ========
578
+
579
+ >>> from sympy import Point, Ellipse
580
+ >>> p1 = Point(0, 0)
581
+ >>> e1 = Ellipse(p1, 3, 1)
582
+ >>> e1.focus_distance
583
+ 2*sqrt(2)
584
+
585
+ """
586
+ return Point.distance(self.center, self.foci[0])
587
+
588
+ @property
589
+ def hradius(self):
590
+ """The horizontal radius of the ellipse.
591
+
592
+ Returns
593
+ =======
594
+
595
+ hradius : number
596
+
597
+ See Also
598
+ ========
599
+
600
+ vradius, major, minor
601
+
602
+ Examples
603
+ ========
604
+
605
+ >>> from sympy import Point, Ellipse
606
+ >>> p1 = Point(0, 0)
607
+ >>> e1 = Ellipse(p1, 3, 1)
608
+ >>> e1.hradius
609
+ 3
610
+
611
+ """
612
+ return self.args[1]
613
+
614
+ def intersection(self, o):
615
+ """The intersection of this ellipse and another geometrical entity
616
+ `o`.
617
+
618
+ Parameters
619
+ ==========
620
+
621
+ o : GeometryEntity
622
+
623
+ Returns
624
+ =======
625
+
626
+ intersection : list of GeometryEntity objects
627
+
628
+ Notes
629
+ -----
630
+ Currently supports intersections with Point, Line, Segment, Ray,
631
+ Circle and Ellipse types.
632
+
633
+ See Also
634
+ ========
635
+
636
+ sympy.geometry.entity.GeometryEntity
637
+
638
+ Examples
639
+ ========
640
+
641
+ >>> from sympy import Ellipse, Point, Line
642
+ >>> e = Ellipse(Point(0, 0), 5, 7)
643
+ >>> e.intersection(Point(0, 0))
644
+ []
645
+ >>> e.intersection(Point(5, 0))
646
+ [Point2D(5, 0)]
647
+ >>> e.intersection(Line(Point(0,0), Point(0, 1)))
648
+ [Point2D(0, -7), Point2D(0, 7)]
649
+ >>> e.intersection(Line(Point(5,0), Point(5, 1)))
650
+ [Point2D(5, 0)]
651
+ >>> e.intersection(Line(Point(6,0), Point(6, 1)))
652
+ []
653
+ >>> e = Ellipse(Point(-1, 0), 4, 3)
654
+ >>> e.intersection(Ellipse(Point(1, 0), 4, 3))
655
+ [Point2D(0, -3*sqrt(15)/4), Point2D(0, 3*sqrt(15)/4)]
656
+ >>> e.intersection(Ellipse(Point(5, 0), 4, 3))
657
+ [Point2D(2, -3*sqrt(7)/4), Point2D(2, 3*sqrt(7)/4)]
658
+ >>> e.intersection(Ellipse(Point(100500, 0), 4, 3))
659
+ []
660
+ >>> e.intersection(Ellipse(Point(0, 0), 3, 4))
661
+ [Point2D(3, 0), Point2D(-363/175, -48*sqrt(111)/175), Point2D(-363/175, 48*sqrt(111)/175)]
662
+ >>> e.intersection(Ellipse(Point(-1, 0), 3, 4))
663
+ [Point2D(-17/5, -12/5), Point2D(-17/5, 12/5), Point2D(7/5, -12/5), Point2D(7/5, 12/5)]
664
+ """
665
+ # TODO: Replace solve with nonlinsolve, when nonlinsolve will be able to solve in real domain
666
+
667
+ if isinstance(o, Point):
668
+ if o in self:
669
+ return [o]
670
+ else:
671
+ return []
672
+
673
+ elif isinstance(o, (Segment2D, Ray2D)):
674
+ ellipse_equation = self.equation(x, y)
675
+ result = solve([ellipse_equation, Line(
676
+ o.points[0], o.points[1]).equation(x, y)], [x, y],
677
+ set=True)[1]
678
+ return list(ordered([Point(i) for i in result if i in o]))
679
+
680
+ elif isinstance(o, Polygon):
681
+ return o.intersection(self)
682
+
683
+ elif isinstance(o, (Ellipse, Line2D)):
684
+ if o == self:
685
+ return self
686
+ else:
687
+ ellipse_equation = self.equation(x, y)
688
+ return list(ordered([Point(i) for i in solve(
689
+ [ellipse_equation, o.equation(x, y)], [x, y],
690
+ set=True)[1]]))
691
+ elif isinstance(o, LinearEntity3D):
692
+ raise TypeError('Entity must be two dimensional, not three dimensional')
693
+ else:
694
+ raise TypeError('Intersection not handled for %s' % func_name(o))
695
+
696
+ def is_tangent(self, o):
697
+ """Is `o` tangent to the ellipse?
698
+
699
+ Parameters
700
+ ==========
701
+
702
+ o : GeometryEntity
703
+ An Ellipse, LinearEntity or Polygon
704
+
705
+ Raises
706
+ ======
707
+
708
+ NotImplementedError
709
+ When the wrong type of argument is supplied.
710
+
711
+ Returns
712
+ =======
713
+
714
+ is_tangent: boolean
715
+ True if o is tangent to the ellipse, False otherwise.
716
+
717
+ See Also
718
+ ========
719
+
720
+ tangent_lines
721
+
722
+ Examples
723
+ ========
724
+
725
+ >>> from sympy import Point, Ellipse, Line
726
+ >>> p0, p1, p2 = Point(0, 0), Point(3, 0), Point(3, 3)
727
+ >>> e1 = Ellipse(p0, 3, 2)
728
+ >>> l1 = Line(p1, p2)
729
+ >>> e1.is_tangent(l1)
730
+ True
731
+
732
+ """
733
+ if isinstance(o, Point2D):
734
+ return False
735
+ elif isinstance(o, Ellipse):
736
+ intersect = self.intersection(o)
737
+ if isinstance(intersect, Ellipse):
738
+ return True
739
+ elif intersect:
740
+ return all((self.tangent_lines(i)[0]).equals(o.tangent_lines(i)[0]) for i in intersect)
741
+ else:
742
+ return False
743
+ elif isinstance(o, Line2D):
744
+ hit = self.intersection(o)
745
+ if not hit:
746
+ return False
747
+ if len(hit) == 1:
748
+ return True
749
+ # might return None if it can't decide
750
+ return hit[0].equals(hit[1])
751
+ elif isinstance(o, (Segment2D, Ray2D)):
752
+ intersect = self.intersection(o)
753
+ if len(intersect) == 1:
754
+ return o in self.tangent_lines(intersect[0])[0]
755
+ else:
756
+ return False
757
+ elif isinstance(o, Polygon):
758
+ return all(self.is_tangent(s) for s in o.sides)
759
+ elif isinstance(o, (LinearEntity3D, Point3D)):
760
+ raise TypeError('Entity must be two dimensional, not three dimensional')
761
+ else:
762
+ raise TypeError('Is_tangent not handled for %s' % func_name(o))
763
+
764
+ @property
765
+ def major(self):
766
+ """Longer axis of the ellipse (if it can be determined) else hradius.
767
+
768
+ Returns
769
+ =======
770
+
771
+ major : number or expression
772
+
773
+ See Also
774
+ ========
775
+
776
+ hradius, vradius, minor
777
+
778
+ Examples
779
+ ========
780
+
781
+ >>> from sympy import Point, Ellipse, Symbol
782
+ >>> p1 = Point(0, 0)
783
+ >>> e1 = Ellipse(p1, 3, 1)
784
+ >>> e1.major
785
+ 3
786
+
787
+ >>> a = Symbol('a')
788
+ >>> b = Symbol('b')
789
+ >>> Ellipse(p1, a, b).major
790
+ a
791
+ >>> Ellipse(p1, b, a).major
792
+ b
793
+
794
+ >>> m = Symbol('m')
795
+ >>> M = m + 1
796
+ >>> Ellipse(p1, m, M).major
797
+ m + 1
798
+
799
+ """
800
+ ab = self.args[1:3]
801
+ if len(ab) == 1:
802
+ return ab[0]
803
+ a, b = ab
804
+ o = b - a < 0
805
+ if o == True:
806
+ return a
807
+ elif o == False:
808
+ return b
809
+ return self.hradius
810
+
811
+ @property
812
+ def minor(self):
813
+ """Shorter axis of the ellipse (if it can be determined) else vradius.
814
+
815
+ Returns
816
+ =======
817
+
818
+ minor : number or expression
819
+
820
+ See Also
821
+ ========
822
+
823
+ hradius, vradius, major
824
+
825
+ Examples
826
+ ========
827
+
828
+ >>> from sympy import Point, Ellipse, Symbol
829
+ >>> p1 = Point(0, 0)
830
+ >>> e1 = Ellipse(p1, 3, 1)
831
+ >>> e1.minor
832
+ 1
833
+
834
+ >>> a = Symbol('a')
835
+ >>> b = Symbol('b')
836
+ >>> Ellipse(p1, a, b).minor
837
+ b
838
+ >>> Ellipse(p1, b, a).minor
839
+ a
840
+
841
+ >>> m = Symbol('m')
842
+ >>> M = m + 1
843
+ >>> Ellipse(p1, m, M).minor
844
+ m
845
+
846
+ """
847
+ ab = self.args[1:3]
848
+ if len(ab) == 1:
849
+ return ab[0]
850
+ a, b = ab
851
+ o = a - b < 0
852
+ if o == True:
853
+ return a
854
+ elif o == False:
855
+ return b
856
+ return self.vradius
857
+
858
+ def normal_lines(self, p, prec=None):
859
+ """Normal lines between `p` and the ellipse.
860
+
861
+ Parameters
862
+ ==========
863
+
864
+ p : Point
865
+
866
+ Returns
867
+ =======
868
+
869
+ normal_lines : list with 1, 2 or 4 Lines
870
+
871
+ Examples
872
+ ========
873
+
874
+ >>> from sympy import Point, Ellipse
875
+ >>> e = Ellipse((0, 0), 2, 3)
876
+ >>> c = e.center
877
+ >>> e.normal_lines(c + Point(1, 0))
878
+ [Line2D(Point2D(0, 0), Point2D(1, 0))]
879
+ >>> e.normal_lines(c)
880
+ [Line2D(Point2D(0, 0), Point2D(0, 1)), Line2D(Point2D(0, 0), Point2D(1, 0))]
881
+
882
+ Off-axis points require the solution of a quartic equation. This
883
+ often leads to very large expressions that may be of little practical
884
+ use. An approximate solution of `prec` digits can be obtained by
885
+ passing in the desired value:
886
+
887
+ >>> e.normal_lines((3, 3), prec=2)
888
+ [Line2D(Point2D(-0.81, -2.7), Point2D(0.19, -1.2)),
889
+ Line2D(Point2D(1.5, -2.0), Point2D(2.5, -2.7))]
890
+
891
+ Whereas the above solution has an operation count of 12, the exact
892
+ solution has an operation count of 2020.
893
+ """
894
+ p = Point(p, dim=2)
895
+
896
+ # XXX change True to something like self.angle == 0 if the arbitrarily
897
+ # rotated ellipse is introduced.
898
+ # https://github.com/sympy/sympy/issues/2815)
899
+ if True:
900
+ rv = []
901
+ if p.x == self.center.x:
902
+ rv.append(Line(self.center, slope=oo))
903
+ if p.y == self.center.y:
904
+ rv.append(Line(self.center, slope=0))
905
+ if rv:
906
+ # at these special orientations of p either 1 or 2 normals
907
+ # exist and we are done
908
+ return rv
909
+
910
+ # find the 4 normal points and construct lines through them with
911
+ # the corresponding slope
912
+ eq = self.equation(x, y)
913
+ dydx = idiff(eq, y, x)
914
+ norm = -1/dydx
915
+ slope = Line(p, (x, y)).slope
916
+ seq = slope - norm
917
+
918
+ # TODO: Replace solve with solveset, when this line is tested
919
+ yis = solve(seq, y)[0]
920
+ xeq = eq.subs(y, yis).as_numer_denom()[0].expand()
921
+ if len(xeq.free_symbols) == 1:
922
+ try:
923
+ # this is so much faster, it's worth a try
924
+ xsol = Poly(xeq, x).real_roots()
925
+ except (DomainError, PolynomialError, NotImplementedError):
926
+ # TODO: Replace solve with solveset, when these lines are tested
927
+ xsol = _nsort(solve(xeq, x), separated=True)[0]
928
+ points = [Point(i, solve(eq.subs(x, i), y)[0]) for i in xsol]
929
+ else:
930
+ raise NotImplementedError(
931
+ 'intersections for the general ellipse are not supported')
932
+ slopes = [norm.subs(zip((x, y), pt.args)) for pt in points]
933
+ if prec is not None:
934
+ points = [pt.n(prec) for pt in points]
935
+ slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes]
936
+ return [Line(pt, slope=s) for pt, s in zip(points, slopes)]
937
+
938
+ @property
939
+ def periapsis(self):
940
+ """The periapsis of the ellipse.
941
+
942
+ The shortest distance between the focus and the contour.
943
+
944
+ Returns
945
+ =======
946
+
947
+ periapsis : number
948
+
949
+ See Also
950
+ ========
951
+
952
+ apoapsis : Returns greatest distance between focus and contour
953
+
954
+ Examples
955
+ ========
956
+
957
+ >>> from sympy import Point, Ellipse
958
+ >>> p1 = Point(0, 0)
959
+ >>> e1 = Ellipse(p1, 3, 1)
960
+ >>> e1.periapsis
961
+ 3 - 2*sqrt(2)
962
+
963
+ """
964
+ return self.major * (1 - self.eccentricity)
965
+
966
+ @property
967
+ def semilatus_rectum(self):
968
+ """
969
+ Calculates the semi-latus rectum of the Ellipse.
970
+
971
+ Semi-latus rectum is defined as one half of the chord through a
972
+ focus parallel to the conic section directrix of a conic section.
973
+
974
+ Returns
975
+ =======
976
+
977
+ semilatus_rectum : number
978
+
979
+ See Also
980
+ ========
981
+
982
+ apoapsis : Returns greatest distance between focus and contour
983
+
984
+ periapsis : The shortest distance between the focus and the contour
985
+
986
+ Examples
987
+ ========
988
+
989
+ >>> from sympy import Point, Ellipse
990
+ >>> p1 = Point(0, 0)
991
+ >>> e1 = Ellipse(p1, 3, 1)
992
+ >>> e1.semilatus_rectum
993
+ 1/3
994
+
995
+ References
996
+ ==========
997
+
998
+ .. [1] https://mathworld.wolfram.com/SemilatusRectum.html
999
+ .. [2] https://en.wikipedia.org/wiki/Ellipse#Semi-latus_rectum
1000
+
1001
+ """
1002
+ return self.major * (1 - self.eccentricity ** 2)
1003
+
1004
+ def auxiliary_circle(self):
1005
+ """Returns a Circle whose diameter is the major axis of the ellipse.
1006
+
1007
+ Examples
1008
+ ========
1009
+
1010
+ >>> from sympy import Ellipse, Point, symbols
1011
+ >>> c = Point(1, 2)
1012
+ >>> Ellipse(c, 8, 7).auxiliary_circle()
1013
+ Circle(Point2D(1, 2), 8)
1014
+ >>> a, b = symbols('a b')
1015
+ >>> Ellipse(c, a, b).auxiliary_circle()
1016
+ Circle(Point2D(1, 2), Max(a, b))
1017
+ """
1018
+ return Circle(self.center, Max(self.hradius, self.vradius))
1019
+
1020
+ def director_circle(self):
1021
+ """
1022
+ Returns a Circle consisting of all points where two perpendicular
1023
+ tangent lines to the ellipse cross each other.
1024
+
1025
+ Returns
1026
+ =======
1027
+
1028
+ Circle
1029
+ A director circle returned as a geometric object.
1030
+
1031
+ Examples
1032
+ ========
1033
+
1034
+ >>> from sympy import Ellipse, Point, symbols
1035
+ >>> c = Point(3,8)
1036
+ >>> Ellipse(c, 7, 9).director_circle()
1037
+ Circle(Point2D(3, 8), sqrt(130))
1038
+ >>> a, b = symbols('a b')
1039
+ >>> Ellipse(c, a, b).director_circle()
1040
+ Circle(Point2D(3, 8), sqrt(a**2 + b**2))
1041
+
1042
+ References
1043
+ ==========
1044
+
1045
+ .. [1] https://en.wikipedia.org/wiki/Director_circle
1046
+
1047
+ """
1048
+ return Circle(self.center, sqrt(self.hradius**2 + self.vradius**2))
1049
+
1050
+ def plot_interval(self, parameter='t'):
1051
+ """The plot interval for the default geometric plot of the Ellipse.
1052
+
1053
+ Parameters
1054
+ ==========
1055
+
1056
+ parameter : str, optional
1057
+ Default value is 't'.
1058
+
1059
+ Returns
1060
+ =======
1061
+
1062
+ plot_interval : list
1063
+ [parameter, lower_bound, upper_bound]
1064
+
1065
+ Examples
1066
+ ========
1067
+
1068
+ >>> from sympy import Point, Ellipse
1069
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
1070
+ >>> e1.plot_interval()
1071
+ [t, -pi, pi]
1072
+
1073
+ """
1074
+ t = _symbol(parameter, real=True)
1075
+ return [t, -S.Pi, S.Pi]
1076
+
1077
+ def random_point(self, seed=None):
1078
+ """A random point on the ellipse.
1079
+
1080
+ Returns
1081
+ =======
1082
+
1083
+ point : Point
1084
+
1085
+ Examples
1086
+ ========
1087
+
1088
+ >>> from sympy import Point, Ellipse
1089
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
1090
+ >>> e1.random_point() # gives some random point
1091
+ Point2D(...)
1092
+ >>> p1 = e1.random_point(seed=0); p1.n(2)
1093
+ Point2D(2.1, 1.4)
1094
+
1095
+ Notes
1096
+ =====
1097
+
1098
+ When creating a random point, one may simply replace the
1099
+ parameter with a random number. When doing so, however, the
1100
+ random number should be made a Rational or else the point
1101
+ may not test as being in the ellipse:
1102
+
1103
+ >>> from sympy.abc import t
1104
+ >>> from sympy import Rational
1105
+ >>> arb = e1.arbitrary_point(t); arb
1106
+ Point2D(3*cos(t), 2*sin(t))
1107
+ >>> arb.subs(t, .1) in e1
1108
+ False
1109
+ >>> arb.subs(t, Rational(.1)) in e1
1110
+ True
1111
+ >>> arb.subs(t, Rational('.1')) in e1
1112
+ True
1113
+
1114
+ See Also
1115
+ ========
1116
+ sympy.geometry.point.Point
1117
+ arbitrary_point : Returns parameterized point on ellipse
1118
+ """
1119
+ t = _symbol('t', real=True)
1120
+ x, y = self.arbitrary_point(t).args
1121
+ # get a random value in [-1, 1) corresponding to cos(t)
1122
+ # and confirm that it will test as being in the ellipse
1123
+ if seed is not None:
1124
+ rng = random.Random(seed)
1125
+ else:
1126
+ rng = random
1127
+ # simplify this now or else the Float will turn s into a Float
1128
+ r = Rational(rng.random())
1129
+ c = 2*r - 1
1130
+ s = sqrt(1 - c**2)
1131
+ return Point(x.subs(cos(t), c), y.subs(sin(t), s))
1132
+
1133
+ def reflect(self, line):
1134
+ """Override GeometryEntity.reflect since the radius
1135
+ is not a GeometryEntity.
1136
+
1137
+ Examples
1138
+ ========
1139
+
1140
+ >>> from sympy import Circle, Line
1141
+ >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
1142
+ Circle(Point2D(1, 0), -1)
1143
+ >>> from sympy import Ellipse, Line, Point
1144
+ >>> Ellipse(Point(3, 4), 1, 3).reflect(Line(Point(0, -4), Point(5, 0)))
1145
+ Traceback (most recent call last):
1146
+ ...
1147
+ NotImplementedError:
1148
+ General Ellipse is not supported but the equation of the reflected
1149
+ Ellipse is given by the zeros of: f(x, y) = (9*x/41 + 40*y/41 +
1150
+ 37/41)**2 + (40*x/123 - 3*y/41 - 364/123)**2 - 1
1151
+
1152
+ Notes
1153
+ =====
1154
+
1155
+ Until the general ellipse (with no axis parallel to the x-axis) is
1156
+ supported a NotImplemented error is raised and the equation whose
1157
+ zeros define the rotated ellipse is given.
1158
+
1159
+ """
1160
+
1161
+ if line.slope in (0, oo):
1162
+ c = self.center
1163
+ c = c.reflect(line)
1164
+ return self.func(c, -self.hradius, self.vradius)
1165
+ else:
1166
+ x, y = [uniquely_named_symbol(
1167
+ name, (self, line), modify=lambda s: '_' + s, real=True)
1168
+ for name in 'xy']
1169
+ expr = self.equation(x, y)
1170
+ p = Point(x, y).reflect(line)
1171
+ result = expr.subs(zip((x, y), p.args
1172
+ ), simultaneous=True)
1173
+ raise NotImplementedError(filldedent(
1174
+ 'General Ellipse is not supported but the equation '
1175
+ 'of the reflected Ellipse is given by the zeros of: ' +
1176
+ "f(%s, %s) = %s" % (str(x), str(y), str(result))))
1177
+
1178
+ def rotate(self, angle=0, pt=None):
1179
+ """Rotate ``angle`` radians counterclockwise about Point ``pt``.
1180
+
1181
+ Note: since the general ellipse is not supported, only rotations that
1182
+ are integer multiples of pi/2 are allowed.
1183
+
1184
+ Examples
1185
+ ========
1186
+
1187
+ >>> from sympy import Ellipse, pi
1188
+ >>> Ellipse((1, 0), 2, 1).rotate(pi/2)
1189
+ Ellipse(Point2D(0, 1), 1, 2)
1190
+ >>> Ellipse((1, 0), 2, 1).rotate(pi)
1191
+ Ellipse(Point2D(-1, 0), 2, 1)
1192
+ """
1193
+ if self.hradius == self.vradius:
1194
+ return self.func(self.center.rotate(angle, pt), self.hradius)
1195
+ if (angle/S.Pi).is_integer:
1196
+ return super().rotate(angle, pt)
1197
+ if (2*angle/S.Pi).is_integer:
1198
+ return self.func(self.center.rotate(angle, pt), self.vradius, self.hradius)
1199
+ # XXX see https://github.com/sympy/sympy/issues/2815 for general ellipes
1200
+ raise NotImplementedError('Only rotations of pi/2 are currently supported for Ellipse.')
1201
+
1202
+ def scale(self, x=1, y=1, pt=None):
1203
+ """Override GeometryEntity.scale since it is the major and minor
1204
+ axes which must be scaled and they are not GeometryEntities.
1205
+
1206
+ Examples
1207
+ ========
1208
+
1209
+ >>> from sympy import Ellipse
1210
+ >>> Ellipse((0, 0), 2, 1).scale(2, 4)
1211
+ Circle(Point2D(0, 0), 4)
1212
+ >>> Ellipse((0, 0), 2, 1).scale(2)
1213
+ Ellipse(Point2D(0, 0), 4, 1)
1214
+ """
1215
+ c = self.center
1216
+ if pt:
1217
+ pt = Point(pt, dim=2)
1218
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
1219
+ h = self.hradius
1220
+ v = self.vradius
1221
+ return self.func(c.scale(x, y), hradius=h*x, vradius=v*y)
1222
+
1223
+ def tangent_lines(self, p):
1224
+ """Tangent lines between `p` and the ellipse.
1225
+
1226
+ If `p` is on the ellipse, returns the tangent line through point `p`.
1227
+ Otherwise, returns the tangent line(s) from `p` to the ellipse, or
1228
+ None if no tangent line is possible (e.g., `p` inside ellipse).
1229
+
1230
+ Parameters
1231
+ ==========
1232
+
1233
+ p : Point
1234
+
1235
+ Returns
1236
+ =======
1237
+
1238
+ tangent_lines : list with 1 or 2 Lines
1239
+
1240
+ Raises
1241
+ ======
1242
+
1243
+ NotImplementedError
1244
+ Can only find tangent lines for a point, `p`, on the ellipse.
1245
+
1246
+ See Also
1247
+ ========
1248
+
1249
+ sympy.geometry.point.Point, sympy.geometry.line.Line
1250
+
1251
+ Examples
1252
+ ========
1253
+
1254
+ >>> from sympy import Point, Ellipse
1255
+ >>> e1 = Ellipse(Point(0, 0), 3, 2)
1256
+ >>> e1.tangent_lines(Point(3, 0))
1257
+ [Line2D(Point2D(3, 0), Point2D(3, -12))]
1258
+
1259
+ """
1260
+ p = Point(p, dim=2)
1261
+ if self.encloses_point(p):
1262
+ return []
1263
+
1264
+ if p in self:
1265
+ delta = self.center - p
1266
+ rise = (self.vradius**2)*delta.x
1267
+ run = -(self.hradius**2)*delta.y
1268
+ p2 = Point(simplify(p.x + run),
1269
+ simplify(p.y + rise))
1270
+ return [Line(p, p2)]
1271
+ else:
1272
+ if len(self.foci) == 2:
1273
+ f1, f2 = self.foci
1274
+ maj = self.hradius
1275
+ test = (2*maj -
1276
+ Point.distance(f1, p) -
1277
+ Point.distance(f2, p))
1278
+ else:
1279
+ test = self.radius - Point.distance(self.center, p)
1280
+ if test.is_number and test.is_positive:
1281
+ return []
1282
+ # else p is outside the ellipse or we can't tell. In case of the
1283
+ # latter, the solutions returned will only be valid if
1284
+ # the point is not inside the ellipse; if it is, nan will result.
1285
+ eq = self.equation(x, y)
1286
+ dydx = idiff(eq, y, x)
1287
+ slope = Line(p, Point(x, y)).slope
1288
+
1289
+ # TODO: Replace solve with solveset, when this line is tested
1290
+ tangent_points = solve([slope - dydx, eq], [x, y])
1291
+
1292
+ # handle horizontal and vertical tangent lines
1293
+ if len(tangent_points) == 1:
1294
+ if tangent_points[0][
1295
+ 0] == p.x or tangent_points[0][1] == p.y:
1296
+ return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))]
1297
+ else:
1298
+ return [Line(p, p + Point(0, 1)), Line(p, tangent_points[0])]
1299
+
1300
+ # others
1301
+ return [Line(p, tangent_points[0]), Line(p, tangent_points[1])]
1302
+
1303
+ @property
1304
+ def vradius(self):
1305
+ """The vertical radius of the ellipse.
1306
+
1307
+ Returns
1308
+ =======
1309
+
1310
+ vradius : number
1311
+
1312
+ See Also
1313
+ ========
1314
+
1315
+ hradius, major, minor
1316
+
1317
+ Examples
1318
+ ========
1319
+
1320
+ >>> from sympy import Point, Ellipse
1321
+ >>> p1 = Point(0, 0)
1322
+ >>> e1 = Ellipse(p1, 3, 1)
1323
+ >>> e1.vradius
1324
+ 1
1325
+
1326
+ """
1327
+ return self.args[2]
1328
+
1329
+
1330
+ def second_moment_of_area(self, point=None):
1331
+ """Returns the second moment and product moment area of an ellipse.
1332
+
1333
+ Parameters
1334
+ ==========
1335
+
1336
+ point : Point, two-tuple of sympifiable objects, or None(default=None)
1337
+ point is the point about which second moment of area is to be found.
1338
+ If "point=None" it will be calculated about the axis passing through the
1339
+ centroid of the ellipse.
1340
+
1341
+ Returns
1342
+ =======
1343
+
1344
+ I_xx, I_yy, I_xy : number or SymPy expression
1345
+ I_xx, I_yy are second moment of area of an ellise.
1346
+ I_xy is product moment of area of an ellipse.
1347
+
1348
+ Examples
1349
+ ========
1350
+
1351
+ >>> from sympy import Point, Ellipse
1352
+ >>> p1 = Point(0, 0)
1353
+ >>> e1 = Ellipse(p1, 3, 1)
1354
+ >>> e1.second_moment_of_area()
1355
+ (3*pi/4, 27*pi/4, 0)
1356
+
1357
+ References
1358
+ ==========
1359
+
1360
+ .. [1] https://en.wikipedia.org/wiki/List_of_second_moments_of_area
1361
+
1362
+ """
1363
+
1364
+ I_xx = (S.Pi*(self.hradius)*(self.vradius**3))/4
1365
+ I_yy = (S.Pi*(self.hradius**3)*(self.vradius))/4
1366
+ I_xy = 0
1367
+
1368
+ if point is None:
1369
+ return I_xx, I_yy, I_xy
1370
+
1371
+ # parallel axis theorem
1372
+ I_xx = I_xx + self.area*((point[1] - self.center.y)**2)
1373
+ I_yy = I_yy + self.area*((point[0] - self.center.x)**2)
1374
+ I_xy = I_xy + self.area*(point[0] - self.center.x)*(point[1] - self.center.y)
1375
+
1376
+ return I_xx, I_yy, I_xy
1377
+
1378
+
1379
+ def polar_second_moment_of_area(self):
1380
+ """Returns the polar second moment of area of an Ellipse
1381
+
1382
+ It is a constituent of the second moment of area, linked through
1383
+ the perpendicular axis theorem. While the planar second moment of
1384
+ area describes an object's resistance to deflection (bending) when
1385
+ subjected to a force applied to a plane parallel to the central
1386
+ axis, the polar second moment of area describes an object's
1387
+ resistance to deflection when subjected to a moment applied in a
1388
+ plane perpendicular to the object's central axis (i.e. parallel to
1389
+ the cross-section)
1390
+
1391
+ Examples
1392
+ ========
1393
+
1394
+ >>> from sympy import symbols, Circle, Ellipse
1395
+ >>> c = Circle((5, 5), 4)
1396
+ >>> c.polar_second_moment_of_area()
1397
+ 128*pi
1398
+ >>> a, b = symbols('a, b')
1399
+ >>> e = Ellipse((0, 0), a, b)
1400
+ >>> e.polar_second_moment_of_area()
1401
+ pi*a**3*b/4 + pi*a*b**3/4
1402
+
1403
+ References
1404
+ ==========
1405
+
1406
+ .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia
1407
+
1408
+ """
1409
+ second_moment = self.second_moment_of_area()
1410
+ return second_moment[0] + second_moment[1]
1411
+
1412
+
1413
+ def section_modulus(self, point=None):
1414
+ """Returns a tuple with the section modulus of an ellipse
1415
+
1416
+ Section modulus is a geometric property of an ellipse defined as the
1417
+ ratio of second moment of area to the distance of the extreme end of
1418
+ the ellipse from the centroidal axis.
1419
+
1420
+ Parameters
1421
+ ==========
1422
+
1423
+ point : Point, two-tuple of sympifyable objects, or None(default=None)
1424
+ point is the point at which section modulus is to be found.
1425
+ If "point=None" section modulus will be calculated for the
1426
+ point farthest from the centroidal axis of the ellipse.
1427
+
1428
+ Returns
1429
+ =======
1430
+
1431
+ S_x, S_y: numbers or SymPy expressions
1432
+ S_x is the section modulus with respect to the x-axis
1433
+ S_y is the section modulus with respect to the y-axis
1434
+ A negative sign indicates that the section modulus is
1435
+ determined for a point below the centroidal axis.
1436
+
1437
+ Examples
1438
+ ========
1439
+
1440
+ >>> from sympy import Symbol, Ellipse, Circle, Point2D
1441
+ >>> d = Symbol('d', positive=True)
1442
+ >>> c = Circle((0, 0), d/2)
1443
+ >>> c.section_modulus()
1444
+ (pi*d**3/32, pi*d**3/32)
1445
+ >>> e = Ellipse(Point2D(0, 0), 2, 4)
1446
+ >>> e.section_modulus()
1447
+ (8*pi, 4*pi)
1448
+ >>> e.section_modulus((2, 2))
1449
+ (16*pi, 4*pi)
1450
+
1451
+ References
1452
+ ==========
1453
+
1454
+ .. [1] https://en.wikipedia.org/wiki/Section_modulus
1455
+
1456
+ """
1457
+ x_c, y_c = self.center
1458
+ if point is None:
1459
+ # taking x and y as maximum distances from centroid
1460
+ x_min, y_min, x_max, y_max = self.bounds
1461
+ y = max(y_c - y_min, y_max - y_c)
1462
+ x = max(x_c - x_min, x_max - x_c)
1463
+ else:
1464
+ # taking x and y as distances of the given point from the center
1465
+ point = Point2D(point)
1466
+ y = point.y - y_c
1467
+ x = point.x - x_c
1468
+
1469
+ second_moment = self.second_moment_of_area()
1470
+ S_x = second_moment[0]/y
1471
+ S_y = second_moment[1]/x
1472
+
1473
+ return S_x, S_y
1474
+
1475
+
1476
+ class Circle(Ellipse):
1477
+ """A circle in space.
1478
+
1479
+ Constructed simply from a center and a radius, from three
1480
+ non-collinear points, or the equation of a circle.
1481
+
1482
+ Parameters
1483
+ ==========
1484
+
1485
+ center : Point
1486
+ radius : number or SymPy expression
1487
+ points : sequence of three Points
1488
+ equation : equation of a circle
1489
+
1490
+ Attributes
1491
+ ==========
1492
+
1493
+ radius (synonymous with hradius, vradius, major and minor)
1494
+ circumference
1495
+ equation
1496
+
1497
+ Raises
1498
+ ======
1499
+
1500
+ GeometryError
1501
+ When the given equation is not that of a circle.
1502
+ When trying to construct circle from incorrect parameters.
1503
+
1504
+ See Also
1505
+ ========
1506
+
1507
+ Ellipse, sympy.geometry.point.Point
1508
+
1509
+ Examples
1510
+ ========
1511
+
1512
+ >>> from sympy import Point, Circle, Eq
1513
+ >>> from sympy.abc import x, y, a, b
1514
+
1515
+ A circle constructed from a center and radius:
1516
+
1517
+ >>> c1 = Circle(Point(0, 0), 5)
1518
+ >>> c1.hradius, c1.vradius, c1.radius
1519
+ (5, 5, 5)
1520
+
1521
+ A circle constructed from three points:
1522
+
1523
+ >>> c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0))
1524
+ >>> c2.hradius, c2.vradius, c2.radius, c2.center
1525
+ (sqrt(2)/2, sqrt(2)/2, sqrt(2)/2, Point2D(1/2, 1/2))
1526
+
1527
+ A circle can be constructed from an equation in the form
1528
+ `a*x**2 + by**2 + gx + hy + c = 0`, too:
1529
+
1530
+ >>> Circle(x**2 + y**2 - 25)
1531
+ Circle(Point2D(0, 0), 5)
1532
+
1533
+ If the variables corresponding to x and y are named something
1534
+ else, their name or symbol can be supplied:
1535
+
1536
+ >>> Circle(Eq(a**2 + b**2, 25), x='a', y=b)
1537
+ Circle(Point2D(0, 0), 5)
1538
+ """
1539
+
1540
+ def __new__(cls, *args, **kwargs):
1541
+ evaluate = kwargs.get('evaluate', global_parameters.evaluate)
1542
+ if len(args) == 1 and isinstance(args[0], (Expr, Eq)):
1543
+ x = kwargs.get('x', 'x')
1544
+ y = kwargs.get('y', 'y')
1545
+ equation = args[0].expand()
1546
+ if isinstance(equation, Eq):
1547
+ equation = equation.lhs - equation.rhs
1548
+ x = find(x, equation)
1549
+ y = find(y, equation)
1550
+
1551
+ try:
1552
+ a, b, c, d, e = linear_coeffs(equation, x**2, y**2, x, y)
1553
+ except ValueError:
1554
+ raise GeometryError("The given equation is not that of a circle.")
1555
+
1556
+ if S.Zero in (a, b) or a != b:
1557
+ raise GeometryError("The given equation is not that of a circle.")
1558
+
1559
+ center_x = -c/a/2
1560
+ center_y = -d/b/2
1561
+ r2 = (center_x**2) + (center_y**2) - e/a
1562
+
1563
+ return Circle((center_x, center_y), sqrt(r2), evaluate=evaluate)
1564
+
1565
+ else:
1566
+ c, r = None, None
1567
+ if len(args) == 3:
1568
+ args = [Point(a, dim=2, evaluate=evaluate) for a in args]
1569
+ t = Triangle(*args)
1570
+ if not isinstance(t, Triangle):
1571
+ return t
1572
+ c = t.circumcenter
1573
+ r = t.circumradius
1574
+ elif len(args) == 2:
1575
+ # Assume (center, radius) pair
1576
+ c = Point(args[0], dim=2, evaluate=evaluate)
1577
+ r = args[1]
1578
+ # this will prohibit imaginary radius
1579
+ try:
1580
+ r = Point(r, 0, evaluate=evaluate).x
1581
+ except ValueError:
1582
+ raise GeometryError("Circle with imaginary radius is not permitted")
1583
+
1584
+ if not (c is None or r is None):
1585
+ if r == 0:
1586
+ return c
1587
+ return GeometryEntity.__new__(cls, c, r, **kwargs)
1588
+
1589
+ raise GeometryError("Circle.__new__ received unknown arguments")
1590
+
1591
+ def _eval_evalf(self, prec=15, **options):
1592
+ pt, r = self.args
1593
+ dps = prec_to_dps(prec)
1594
+ pt = pt.evalf(n=dps, **options)
1595
+ r = r.evalf(n=dps, **options)
1596
+ return self.func(pt, r, evaluate=False)
1597
+
1598
+ @property
1599
+ def circumference(self):
1600
+ """The circumference of the circle.
1601
+
1602
+ Returns
1603
+ =======
1604
+
1605
+ circumference : number or SymPy expression
1606
+
1607
+ Examples
1608
+ ========
1609
+
1610
+ >>> from sympy import Point, Circle
1611
+ >>> c1 = Circle(Point(3, 4), 6)
1612
+ >>> c1.circumference
1613
+ 12*pi
1614
+
1615
+ """
1616
+ return 2 * S.Pi * self.radius
1617
+
1618
+ def equation(self, x='x', y='y'):
1619
+ """The equation of the circle.
1620
+
1621
+ Parameters
1622
+ ==========
1623
+
1624
+ x : str or Symbol, optional
1625
+ Default value is 'x'.
1626
+ y : str or Symbol, optional
1627
+ Default value is 'y'.
1628
+
1629
+ Returns
1630
+ =======
1631
+
1632
+ equation : SymPy expression
1633
+
1634
+ Examples
1635
+ ========
1636
+
1637
+ >>> from sympy import Point, Circle
1638
+ >>> c1 = Circle(Point(0, 0), 5)
1639
+ >>> c1.equation()
1640
+ x**2 + y**2 - 25
1641
+
1642
+ """
1643
+ x = _symbol(x, real=True)
1644
+ y = _symbol(y, real=True)
1645
+ t1 = (x - self.center.x)**2
1646
+ t2 = (y - self.center.y)**2
1647
+ return t1 + t2 - self.major**2
1648
+
1649
+ def intersection(self, o):
1650
+ """The intersection of this circle with another geometrical entity.
1651
+
1652
+ Parameters
1653
+ ==========
1654
+
1655
+ o : GeometryEntity
1656
+
1657
+ Returns
1658
+ =======
1659
+
1660
+ intersection : list of GeometryEntities
1661
+
1662
+ Examples
1663
+ ========
1664
+
1665
+ >>> from sympy import Point, Circle, Line, Ray
1666
+ >>> p1, p2, p3 = Point(0, 0), Point(5, 5), Point(6, 0)
1667
+ >>> p4 = Point(5, 0)
1668
+ >>> c1 = Circle(p1, 5)
1669
+ >>> c1.intersection(p2)
1670
+ []
1671
+ >>> c1.intersection(p4)
1672
+ [Point2D(5, 0)]
1673
+ >>> c1.intersection(Ray(p1, p2))
1674
+ [Point2D(5*sqrt(2)/2, 5*sqrt(2)/2)]
1675
+ >>> c1.intersection(Line(p2, p3))
1676
+ []
1677
+
1678
+ """
1679
+ return Ellipse.intersection(self, o)
1680
+
1681
+ @property
1682
+ def radius(self):
1683
+ """The radius of the circle.
1684
+
1685
+ Returns
1686
+ =======
1687
+
1688
+ radius : number or SymPy expression
1689
+
1690
+ See Also
1691
+ ========
1692
+
1693
+ Ellipse.major, Ellipse.minor, Ellipse.hradius, Ellipse.vradius
1694
+
1695
+ Examples
1696
+ ========
1697
+
1698
+ >>> from sympy import Point, Circle
1699
+ >>> c1 = Circle(Point(3, 4), 6)
1700
+ >>> c1.radius
1701
+ 6
1702
+
1703
+ """
1704
+ return self.args[1]
1705
+
1706
+ def reflect(self, line):
1707
+ """Override GeometryEntity.reflect since the radius
1708
+ is not a GeometryEntity.
1709
+
1710
+ Examples
1711
+ ========
1712
+
1713
+ >>> from sympy import Circle, Line
1714
+ >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
1715
+ Circle(Point2D(1, 0), -1)
1716
+ """
1717
+ c = self.center
1718
+ c = c.reflect(line)
1719
+ return self.func(c, -self.radius)
1720
+
1721
+ def scale(self, x=1, y=1, pt=None):
1722
+ """Override GeometryEntity.scale since the radius
1723
+ is not a GeometryEntity.
1724
+
1725
+ Examples
1726
+ ========
1727
+
1728
+ >>> from sympy import Circle
1729
+ >>> Circle((0, 0), 1).scale(2, 2)
1730
+ Circle(Point2D(0, 0), 2)
1731
+ >>> Circle((0, 0), 1).scale(2, 4)
1732
+ Ellipse(Point2D(0, 0), 2, 4)
1733
+ """
1734
+ c = self.center
1735
+ if pt:
1736
+ pt = Point(pt, dim=2)
1737
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
1738
+ c = c.scale(x, y)
1739
+ x, y = [abs(i) for i in (x, y)]
1740
+ if x == y:
1741
+ return self.func(c, x*self.radius)
1742
+ h = v = self.radius
1743
+ return Ellipse(c, hradius=h*x, vradius=v*y)
1744
+
1745
+ @property
1746
+ def vradius(self):
1747
+ """
1748
+ This Ellipse property is an alias for the Circle's radius.
1749
+
1750
+ Whereas hradius, major and minor can use Ellipse's conventions,
1751
+ the vradius does not exist for a circle. It is always a positive
1752
+ value in order that the Circle, like Polygons, will have an
1753
+ area that can be positive or negative as determined by the sign
1754
+ of the hradius.
1755
+
1756
+ Examples
1757
+ ========
1758
+
1759
+ >>> from sympy import Point, Circle
1760
+ >>> c1 = Circle(Point(3, 4), 6)
1761
+ >>> c1.vradius
1762
+ 6
1763
+ """
1764
+ return abs(self.radius)
1765
+
1766
+
1767
+ from .polygon import Polygon, Triangle
wemm/lib/python3.10/site-packages/sympy/geometry/entity.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The definition of the base geometrical entity with attributes common to
2
+ all derived geometrical entities.
3
+
4
+ Contains
5
+ ========
6
+
7
+ GeometryEntity
8
+ GeometricSet
9
+
10
+ Notes
11
+ =====
12
+
13
+ A GeometryEntity is any object that has special geometric properties.
14
+ A GeometrySet is a superclass of any GeometryEntity that can also
15
+ be viewed as a sympy.sets.Set. In particular, points are the only
16
+ GeometryEntity not considered a Set.
17
+
18
+ Rn is a GeometrySet representing n-dimensional Euclidean space. R2 and
19
+ R3 are currently the only ambient spaces implemented.
20
+
21
+ """
22
+ from __future__ import annotations
23
+
24
+ from sympy.core.basic import Basic
25
+ from sympy.core.containers import Tuple
26
+ from sympy.core.evalf import EvalfMixin, N
27
+ from sympy.core.numbers import oo
28
+ from sympy.core.symbol import Dummy
29
+ from sympy.core.sympify import sympify
30
+ from sympy.functions.elementary.trigonometric import cos, sin, atan
31
+ from sympy.matrices import eye
32
+ from sympy.multipledispatch import dispatch
33
+ from sympy.printing import sstr
34
+ from sympy.sets import Set, Union, FiniteSet
35
+ from sympy.sets.handlers.intersection import intersection_sets
36
+ from sympy.sets.handlers.union import union_sets
37
+ from sympy.solvers.solvers import solve
38
+ from sympy.utilities.misc import func_name
39
+ from sympy.utilities.iterables import is_sequence
40
+
41
+
42
+ # How entities are ordered; used by __cmp__ in GeometryEntity
43
+ ordering_of_classes = [
44
+ "Point2D",
45
+ "Point3D",
46
+ "Point",
47
+ "Segment2D",
48
+ "Ray2D",
49
+ "Line2D",
50
+ "Segment3D",
51
+ "Line3D",
52
+ "Ray3D",
53
+ "Segment",
54
+ "Ray",
55
+ "Line",
56
+ "Plane",
57
+ "Triangle",
58
+ "RegularPolygon",
59
+ "Polygon",
60
+ "Circle",
61
+ "Ellipse",
62
+ "Curve",
63
+ "Parabola"
64
+ ]
65
+
66
+
67
+ x, y = [Dummy('entity_dummy') for i in range(2)]
68
+ T = Dummy('entity_dummy', real=True)
69
+
70
+
71
+ class GeometryEntity(Basic, EvalfMixin):
72
+ """The base class for all geometrical entities.
73
+
74
+ This class does not represent any particular geometric entity, it only
75
+ provides the implementation of some methods common to all subclasses.
76
+
77
+ """
78
+
79
+ __slots__: tuple[str, ...] = ()
80
+
81
+ def __cmp__(self, other):
82
+ """Comparison of two GeometryEntities."""
83
+ n1 = self.__class__.__name__
84
+ n2 = other.__class__.__name__
85
+ c = (n1 > n2) - (n1 < n2)
86
+ if not c:
87
+ return 0
88
+
89
+ i1 = -1
90
+ for cls in self.__class__.__mro__:
91
+ try:
92
+ i1 = ordering_of_classes.index(cls.__name__)
93
+ break
94
+ except ValueError:
95
+ i1 = -1
96
+ if i1 == -1:
97
+ return c
98
+
99
+ i2 = -1
100
+ for cls in other.__class__.__mro__:
101
+ try:
102
+ i2 = ordering_of_classes.index(cls.__name__)
103
+ break
104
+ except ValueError:
105
+ i2 = -1
106
+ if i2 == -1:
107
+ return c
108
+
109
+ return (i1 > i2) - (i1 < i2)
110
+
111
+ def __contains__(self, other):
112
+ """Subclasses should implement this method for anything more complex than equality."""
113
+ if type(self) is type(other):
114
+ return self == other
115
+ raise NotImplementedError()
116
+
117
+ def __getnewargs__(self):
118
+ """Returns a tuple that will be passed to __new__ on unpickling."""
119
+ return tuple(self.args)
120
+
121
+ def __ne__(self, o):
122
+ """Test inequality of two geometrical entities."""
123
+ return not self == o
124
+
125
+ def __new__(cls, *args, **kwargs):
126
+ # Points are sequences, but they should not
127
+ # be converted to Tuples, so use this detection function instead.
128
+ def is_seq_and_not_point(a):
129
+ # we cannot use isinstance(a, Point) since we cannot import Point
130
+ if hasattr(a, 'is_Point') and a.is_Point:
131
+ return False
132
+ return is_sequence(a)
133
+
134
+ args = [Tuple(*a) if is_seq_and_not_point(a) else sympify(a) for a in args]
135
+ return Basic.__new__(cls, *args)
136
+
137
+ def __radd__(self, a):
138
+ """Implementation of reverse add method."""
139
+ return a.__add__(self)
140
+
141
+ def __rtruediv__(self, a):
142
+ """Implementation of reverse division method."""
143
+ return a.__truediv__(self)
144
+
145
+ def __repr__(self):
146
+ """String representation of a GeometryEntity that can be evaluated
147
+ by sympy."""
148
+ return type(self).__name__ + repr(self.args)
149
+
150
+ def __rmul__(self, a):
151
+ """Implementation of reverse multiplication method."""
152
+ return a.__mul__(self)
153
+
154
+ def __rsub__(self, a):
155
+ """Implementation of reverse subtraction method."""
156
+ return a.__sub__(self)
157
+
158
+ def __str__(self):
159
+ """String representation of a GeometryEntity."""
160
+ return type(self).__name__ + sstr(self.args)
161
+
162
+ def _eval_subs(self, old, new):
163
+ from sympy.geometry.point import Point, Point3D
164
+ if is_sequence(old) or is_sequence(new):
165
+ if isinstance(self, Point3D):
166
+ old = Point3D(old)
167
+ new = Point3D(new)
168
+ else:
169
+ old = Point(old)
170
+ new = Point(new)
171
+ return self._subs(old, new)
172
+
173
+ def _repr_svg_(self):
174
+ """SVG representation of a GeometryEntity suitable for IPython"""
175
+
176
+ try:
177
+ bounds = self.bounds
178
+ except (NotImplementedError, TypeError):
179
+ # if we have no SVG representation, return None so IPython
180
+ # will fall back to the next representation
181
+ return None
182
+
183
+ if not all(x.is_number and x.is_finite for x in bounds):
184
+ return None
185
+
186
+ svg_top = '''<svg xmlns="http://www.w3.org/2000/svg"
187
+ xmlns:xlink="http://www.w3.org/1999/xlink"
188
+ width="{1}" height="{2}" viewBox="{0}"
189
+ preserveAspectRatio="xMinYMin meet">
190
+ <defs>
191
+ <marker id="markerCircle" markerWidth="8" markerHeight="8"
192
+ refx="5" refy="5" markerUnits="strokeWidth">
193
+ <circle cx="5" cy="5" r="1.5" style="stroke: none; fill:#000000;"/>
194
+ </marker>
195
+ <marker id="markerArrow" markerWidth="13" markerHeight="13" refx="2" refy="4"
196
+ orient="auto" markerUnits="strokeWidth">
197
+ <path d="M2,2 L2,6 L6,4" style="fill: #000000;" />
198
+ </marker>
199
+ <marker id="markerReverseArrow" markerWidth="13" markerHeight="13" refx="6" refy="4"
200
+ orient="auto" markerUnits="strokeWidth">
201
+ <path d="M6,2 L6,6 L2,4" style="fill: #000000;" />
202
+ </marker>
203
+ </defs>'''
204
+
205
+ # Establish SVG canvas that will fit all the data + small space
206
+ xmin, ymin, xmax, ymax = map(N, bounds)
207
+ if xmin == xmax and ymin == ymax:
208
+ # This is a point; buffer using an arbitrary size
209
+ xmin, ymin, xmax, ymax = xmin - .5, ymin -.5, xmax + .5, ymax + .5
210
+ else:
211
+ # Expand bounds by a fraction of the data ranges
212
+ expand = 0.1 # or 10%; this keeps arrowheads in view (R plots use 4%)
213
+ widest_part = max([xmax - xmin, ymax - ymin])
214
+ expand_amount = widest_part * expand
215
+ xmin -= expand_amount
216
+ ymin -= expand_amount
217
+ xmax += expand_amount
218
+ ymax += expand_amount
219
+ dx = xmax - xmin
220
+ dy = ymax - ymin
221
+ width = min([max([100., dx]), 300])
222
+ height = min([max([100., dy]), 300])
223
+
224
+ scale_factor = 1. if max(width, height) == 0 else max(dx, dy) / max(width, height)
225
+ try:
226
+ svg = self._svg(scale_factor)
227
+ except (NotImplementedError, TypeError):
228
+ # if we have no SVG representation, return None so IPython
229
+ # will fall back to the next representation
230
+ return None
231
+
232
+ view_box = "{} {} {} {}".format(xmin, ymin, dx, dy)
233
+ transform = "matrix(1,0,0,-1,0,{})".format(ymax + ymin)
234
+ svg_top = svg_top.format(view_box, width, height)
235
+
236
+ return svg_top + (
237
+ '<g transform="{}">{}</g></svg>'
238
+ ).format(transform, svg)
239
+
240
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
241
+ """Returns SVG path element for the GeometryEntity.
242
+
243
+ Parameters
244
+ ==========
245
+
246
+ scale_factor : float
247
+ Multiplication factor for the SVG stroke-width. Default is 1.
248
+ fill_color : str, optional
249
+ Hex string for fill color. Default is "#66cc99".
250
+ """
251
+ raise NotImplementedError()
252
+
253
+ def _sympy_(self):
254
+ return self
255
+
256
+ @property
257
+ def ambient_dimension(self):
258
+ """What is the dimension of the space that the object is contained in?"""
259
+ raise NotImplementedError()
260
+
261
+ @property
262
+ def bounds(self):
263
+ """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
264
+ rectangle for the geometric figure.
265
+
266
+ """
267
+
268
+ raise NotImplementedError()
269
+
270
+ def encloses(self, o):
271
+ """
272
+ Return True if o is inside (not on or outside) the boundaries of self.
273
+
274
+ The object will be decomposed into Points and individual Entities need
275
+ only define an encloses_point method for their class.
276
+
277
+ See Also
278
+ ========
279
+
280
+ sympy.geometry.ellipse.Ellipse.encloses_point
281
+ sympy.geometry.polygon.Polygon.encloses_point
282
+
283
+ Examples
284
+ ========
285
+
286
+ >>> from sympy import RegularPolygon, Point, Polygon
287
+ >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
288
+ >>> t2 = Polygon(*RegularPolygon(Point(0, 0), 2, 3).vertices)
289
+ >>> t2.encloses(t)
290
+ True
291
+ >>> t.encloses(t2)
292
+ False
293
+
294
+ """
295
+
296
+ from sympy.geometry.point import Point
297
+ from sympy.geometry.line import Segment, Ray, Line
298
+ from sympy.geometry.ellipse import Ellipse
299
+ from sympy.geometry.polygon import Polygon, RegularPolygon
300
+
301
+ if isinstance(o, Point):
302
+ return self.encloses_point(o)
303
+ elif isinstance(o, Segment):
304
+ return all(self.encloses_point(x) for x in o.points)
305
+ elif isinstance(o, (Ray, Line)):
306
+ return False
307
+ elif isinstance(o, Ellipse):
308
+ return self.encloses_point(o.center) and \
309
+ self.encloses_point(
310
+ Point(o.center.x + o.hradius, o.center.y)) and \
311
+ not self.intersection(o)
312
+ elif isinstance(o, Polygon):
313
+ if isinstance(o, RegularPolygon):
314
+ if not self.encloses_point(o.center):
315
+ return False
316
+ return all(self.encloses_point(v) for v in o.vertices)
317
+ raise NotImplementedError()
318
+
319
+ def equals(self, o):
320
+ return self == o
321
+
322
+ def intersection(self, o):
323
+ """
324
+ Returns a list of all of the intersections of self with o.
325
+
326
+ Notes
327
+ =====
328
+
329
+ An entity is not required to implement this method.
330
+
331
+ If two different types of entities can intersect, the item with
332
+ higher index in ordering_of_classes should implement
333
+ intersections with anything having a lower index.
334
+
335
+ See Also
336
+ ========
337
+
338
+ sympy.geometry.util.intersection
339
+
340
+ """
341
+ raise NotImplementedError()
342
+
343
+ def is_similar(self, other):
344
+ """Is this geometrical entity similar to another geometrical entity?
345
+
346
+ Two entities are similar if a uniform scaling (enlarging or
347
+ shrinking) of one of the entities will allow one to obtain the other.
348
+
349
+ Notes
350
+ =====
351
+
352
+ This method is not intended to be used directly but rather
353
+ through the `are_similar` function found in util.py.
354
+ An entity is not required to implement this method.
355
+ If two different types of entities can be similar, it is only
356
+ required that one of them be able to determine this.
357
+
358
+ See Also
359
+ ========
360
+
361
+ scale
362
+
363
+ """
364
+ raise NotImplementedError()
365
+
366
+ def reflect(self, line):
367
+ """
368
+ Reflects an object across a line.
369
+
370
+ Parameters
371
+ ==========
372
+
373
+ line: Line
374
+
375
+ Examples
376
+ ========
377
+
378
+ >>> from sympy import pi, sqrt, Line, RegularPolygon
379
+ >>> l = Line((0, pi), slope=sqrt(2))
380
+ >>> pent = RegularPolygon((1, 2), 1, 5)
381
+ >>> rpent = pent.reflect(l)
382
+ >>> rpent
383
+ RegularPolygon(Point2D(-2*sqrt(2)*pi/3 - 1/3 + 4*sqrt(2)/3, 2/3 + 2*sqrt(2)/3 + 2*pi/3), -1, 5, -atan(2*sqrt(2)) + 3*pi/5)
384
+
385
+ >>> from sympy import pi, Line, Circle, Point
386
+ >>> l = Line((0, pi), slope=1)
387
+ >>> circ = Circle(Point(0, 0), 5)
388
+ >>> rcirc = circ.reflect(l)
389
+ >>> rcirc
390
+ Circle(Point2D(-pi, pi), -5)
391
+
392
+ """
393
+ from sympy.geometry.point import Point
394
+
395
+ g = self
396
+ l = line
397
+ o = Point(0, 0)
398
+ if l.slope.is_zero:
399
+ v = l.args[0].y
400
+ if not v: # x-axis
401
+ return g.scale(y=-1)
402
+ reps = [(p, p.translate(y=2*(v - p.y))) for p in g.atoms(Point)]
403
+ elif l.slope is oo:
404
+ v = l.args[0].x
405
+ if not v: # y-axis
406
+ return g.scale(x=-1)
407
+ reps = [(p, p.translate(x=2*(v - p.x))) for p in g.atoms(Point)]
408
+ else:
409
+ if not hasattr(g, 'reflect') and not all(
410
+ isinstance(arg, Point) for arg in g.args):
411
+ raise NotImplementedError(
412
+ 'reflect undefined or non-Point args in %s' % g)
413
+ a = atan(l.slope)
414
+ c = l.coefficients
415
+ d = -c[-1]/c[1] # y-intercept
416
+ # apply the transform to a single point
417
+ xf = Point(x, y)
418
+ xf = xf.translate(y=-d).rotate(-a, o).scale(y=-1
419
+ ).rotate(a, o).translate(y=d)
420
+ # replace every point using that transform
421
+ reps = [(p, xf.xreplace({x: p.x, y: p.y})) for p in g.atoms(Point)]
422
+ return g.xreplace(dict(reps))
423
+
424
+ def rotate(self, angle, pt=None):
425
+ """Rotate ``angle`` radians counterclockwise about Point ``pt``.
426
+
427
+ The default pt is the origin, Point(0, 0)
428
+
429
+ See Also
430
+ ========
431
+
432
+ scale, translate
433
+
434
+ Examples
435
+ ========
436
+
437
+ >>> from sympy import Point, RegularPolygon, Polygon, pi
438
+ >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
439
+ >>> t # vertex on x axis
440
+ Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
441
+ >>> t.rotate(pi/2) # vertex on y axis now
442
+ Triangle(Point2D(0, 1), Point2D(-sqrt(3)/2, -1/2), Point2D(sqrt(3)/2, -1/2))
443
+
444
+ """
445
+ newargs = []
446
+ for a in self.args:
447
+ if isinstance(a, GeometryEntity):
448
+ newargs.append(a.rotate(angle, pt))
449
+ else:
450
+ newargs.append(a)
451
+ return type(self)(*newargs)
452
+
453
+ def scale(self, x=1, y=1, pt=None):
454
+ """Scale the object by multiplying the x,y-coordinates by x and y.
455
+
456
+ If pt is given, the scaling is done relative to that point; the
457
+ object is shifted by -pt, scaled, and shifted by pt.
458
+
459
+ See Also
460
+ ========
461
+
462
+ rotate, translate
463
+
464
+ Examples
465
+ ========
466
+
467
+ >>> from sympy import RegularPolygon, Point, Polygon
468
+ >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
469
+ >>> t
470
+ Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
471
+ >>> t.scale(2)
472
+ Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)/2), Point2D(-1, -sqrt(3)/2))
473
+ >>> t.scale(2, 2)
474
+ Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)), Point2D(-1, -sqrt(3)))
475
+
476
+ """
477
+ from sympy.geometry.point import Point
478
+ if pt:
479
+ pt = Point(pt, dim=2)
480
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
481
+ return type(self)(*[a.scale(x, y) for a in self.args]) # if this fails, override this class
482
+
483
+ def translate(self, x=0, y=0):
484
+ """Shift the object by adding to the x,y-coordinates the values x and y.
485
+
486
+ See Also
487
+ ========
488
+
489
+ rotate, scale
490
+
491
+ Examples
492
+ ========
493
+
494
+ >>> from sympy import RegularPolygon, Point, Polygon
495
+ >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
496
+ >>> t
497
+ Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
498
+ >>> t.translate(2)
499
+ Triangle(Point2D(3, 0), Point2D(3/2, sqrt(3)/2), Point2D(3/2, -sqrt(3)/2))
500
+ >>> t.translate(2, 2)
501
+ Triangle(Point2D(3, 2), Point2D(3/2, sqrt(3)/2 + 2), Point2D(3/2, 2 - sqrt(3)/2))
502
+
503
+ """
504
+ newargs = []
505
+ for a in self.args:
506
+ if isinstance(a, GeometryEntity):
507
+ newargs.append(a.translate(x, y))
508
+ else:
509
+ newargs.append(a)
510
+ return self.func(*newargs)
511
+
512
+ def parameter_value(self, other, t):
513
+ """Return the parameter corresponding to the given point.
514
+ Evaluating an arbitrary point of the entity at this parameter
515
+ value will return the given point.
516
+
517
+ Examples
518
+ ========
519
+
520
+ >>> from sympy import Line, Point
521
+ >>> from sympy.abc import t
522
+ >>> a = Point(0, 0)
523
+ >>> b = Point(2, 2)
524
+ >>> Line(a, b).parameter_value((1, 1), t)
525
+ {t: 1/2}
526
+ >>> Line(a, b).arbitrary_point(t).subs(_)
527
+ Point2D(1, 1)
528
+ """
529
+ from sympy.geometry.point import Point
530
+ if not isinstance(other, GeometryEntity):
531
+ other = Point(other, dim=self.ambient_dimension)
532
+ if not isinstance(other, Point):
533
+ raise ValueError("other must be a point")
534
+ sol = solve(self.arbitrary_point(T) - other, T, dict=True)
535
+ if not sol:
536
+ raise ValueError("Given point is not on %s" % func_name(self))
537
+ return {t: sol[0][T]}
538
+
539
+
540
+ class GeometrySet(GeometryEntity, Set):
541
+ """Parent class of all GeometryEntity that are also Sets
542
+ (compatible with sympy.sets)
543
+ """
544
+ __slots__ = ()
545
+
546
+ def _contains(self, other):
547
+ """sympy.sets uses the _contains method, so include it for compatibility."""
548
+
549
+ if isinstance(other, Set) and other.is_FiniteSet:
550
+ return all(self.__contains__(i) for i in other)
551
+
552
+ return self.__contains__(other)
553
+
554
+ @dispatch(GeometrySet, Set) # type:ignore # noqa:F811
555
+ def union_sets(self, o): # noqa:F811
556
+ """ Returns the union of self and o
557
+ for use with sympy.sets.Set, if possible. """
558
+
559
+
560
+ # if its a FiniteSet, merge any points
561
+ # we contain and return a union with the rest
562
+ if o.is_FiniteSet:
563
+ other_points = [p for p in o if not self._contains(p)]
564
+ if len(other_points) == len(o):
565
+ return None
566
+ return Union(self, FiniteSet(*other_points))
567
+ if self._contains(o):
568
+ return self
569
+ return None
570
+
571
+
572
+ @dispatch(GeometrySet, Set) # type: ignore # noqa:F811
573
+ def intersection_sets(self, o): # noqa:F811
574
+ """ Returns a sympy.sets.Set of intersection objects,
575
+ if possible. """
576
+
577
+ from sympy.geometry.point import Point
578
+
579
+ try:
580
+ # if o is a FiniteSet, find the intersection directly
581
+ # to avoid infinite recursion
582
+ if o.is_FiniteSet:
583
+ inter = FiniteSet(*(p for p in o if self.contains(p)))
584
+ else:
585
+ inter = self.intersection(o)
586
+ except NotImplementedError:
587
+ # sympy.sets.Set.reduce expects None if an object
588
+ # doesn't know how to simplify
589
+ return None
590
+
591
+ # put the points in a FiniteSet
592
+ points = FiniteSet(*[p for p in inter if isinstance(p, Point)])
593
+ non_points = [p for p in inter if not isinstance(p, Point)]
594
+
595
+ return Union(*(non_points + [points]))
596
+
597
+ def translate(x, y):
598
+ """Return the matrix to translate a 2-D point by x and y."""
599
+ rv = eye(3)
600
+ rv[2, 0] = x
601
+ rv[2, 1] = y
602
+ return rv
603
+
604
+
605
+ def scale(x, y, pt=None):
606
+ """Return the matrix to multiply a 2-D point's coordinates by x and y.
607
+
608
+ If pt is given, the scaling is done relative to that point."""
609
+ rv = eye(3)
610
+ rv[0, 0] = x
611
+ rv[1, 1] = y
612
+ if pt:
613
+ from sympy.geometry.point import Point
614
+ pt = Point(pt, dim=2)
615
+ tr1 = translate(*(-pt).args)
616
+ tr2 = translate(*pt.args)
617
+ return tr1*rv*tr2
618
+ return rv
619
+
620
+
621
+ def rotate(th):
622
+ """Return the matrix to rotate a 2-D point about the origin by ``angle``.
623
+
624
+ The angle is measured in radians. To Point a point about a point other
625
+ then the origin, translate the Point, do the rotation, and
626
+ translate it back:
627
+
628
+ >>> from sympy.geometry.entity import rotate, translate
629
+ >>> from sympy import Point, pi
630
+ >>> rot_about_11 = translate(-1, -1)*rotate(pi/2)*translate(1, 1)
631
+ >>> Point(1, 1).transform(rot_about_11)
632
+ Point2D(1, 1)
633
+ >>> Point(0, 0).transform(rot_about_11)
634
+ Point2D(2, 0)
635
+ """
636
+ s = sin(th)
637
+ rv = eye(3)*cos(th)
638
+ rv[0, 1] = s
639
+ rv[1, 0] = -s
640
+ rv[2, 2] = 1
641
+ return rv
wemm/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
wemm/lib/python3.10/site-packages/sympy/geometry/line.py ADDED
@@ -0,0 +1,2877 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Line-like geometrical entities.
2
+
3
+ Contains
4
+ ========
5
+ LinearEntity
6
+ Line
7
+ Ray
8
+ Segment
9
+ LinearEntity2D
10
+ Line2D
11
+ Ray2D
12
+ Segment2D
13
+ LinearEntity3D
14
+ Line3D
15
+ Ray3D
16
+ Segment3D
17
+
18
+ """
19
+
20
+ from sympy.core.containers import Tuple
21
+ from sympy.core.evalf import N
22
+ from sympy.core.expr import Expr
23
+ from sympy.core.numbers import Rational, oo, Float
24
+ from sympy.core.relational import Eq
25
+ from sympy.core.singleton import S
26
+ from sympy.core.sorting import ordered
27
+ from sympy.core.symbol import _symbol, Dummy, uniquely_named_symbol
28
+ from sympy.core.sympify import sympify
29
+ from sympy.functions.elementary.piecewise import Piecewise
30
+ from sympy.functions.elementary.trigonometric import (_pi_coeff, acos, tan, atan2)
31
+ from .entity import GeometryEntity, GeometrySet
32
+ from .exceptions import GeometryError
33
+ from .point import Point, Point3D
34
+ from .util import find, intersection
35
+ from sympy.logic.boolalg import And
36
+ from sympy.matrices import Matrix
37
+ from sympy.sets.sets import Intersection
38
+ from sympy.simplify.simplify import simplify
39
+ from sympy.solvers.solvers import solve
40
+ from sympy.solvers.solveset import linear_coeffs
41
+ from sympy.utilities.misc import Undecidable, filldedent
42
+
43
+
44
+ import random
45
+
46
+
47
+ t, u = [Dummy('line_dummy') for i in range(2)]
48
+
49
+
50
+ class LinearEntity(GeometrySet):
51
+ """A base class for all linear entities (Line, Ray and Segment)
52
+ in n-dimensional Euclidean space.
53
+
54
+ Attributes
55
+ ==========
56
+
57
+ ambient_dimension
58
+ direction
59
+ length
60
+ p1
61
+ p2
62
+ points
63
+
64
+ Notes
65
+ =====
66
+
67
+ This is an abstract class and is not meant to be instantiated.
68
+
69
+ See Also
70
+ ========
71
+
72
+ sympy.geometry.entity.GeometryEntity
73
+
74
+ """
75
+ def __new__(cls, p1, p2=None, **kwargs):
76
+ p1, p2 = Point._normalize_dimension(p1, p2)
77
+ if p1 == p2:
78
+ # sometimes we return a single point if we are not given two unique
79
+ # points. This is done in the specific subclass
80
+ raise ValueError(
81
+ "%s.__new__ requires two unique Points." % cls.__name__)
82
+ if len(p1) != len(p2):
83
+ raise ValueError(
84
+ "%s.__new__ requires two Points of equal dimension." % cls.__name__)
85
+
86
+ return GeometryEntity.__new__(cls, p1, p2, **kwargs)
87
+
88
+ def __contains__(self, other):
89
+ """Return a definitive answer or else raise an error if it cannot
90
+ be determined that other is on the boundaries of self."""
91
+ result = self.contains(other)
92
+
93
+ if result is not None:
94
+ return result
95
+ else:
96
+ raise Undecidable(
97
+ "Cannot decide whether '%s' contains '%s'" % (self, other))
98
+
99
+ def _span_test(self, other):
100
+ """Test whether the point `other` lies in the positive span of `self`.
101
+ A point x is 'in front' of a point y if x.dot(y) >= 0. Return
102
+ -1 if `other` is behind `self.p1`, 0 if `other` is `self.p1` and
103
+ and 1 if `other` is in front of `self.p1`."""
104
+ if self.p1 == other:
105
+ return 0
106
+
107
+ rel_pos = other - self.p1
108
+ d = self.direction
109
+ if d.dot(rel_pos) > 0:
110
+ return 1
111
+ return -1
112
+
113
+ @property
114
+ def ambient_dimension(self):
115
+ """A property method that returns the dimension of LinearEntity
116
+ object.
117
+
118
+ Parameters
119
+ ==========
120
+
121
+ p1 : LinearEntity
122
+
123
+ Returns
124
+ =======
125
+
126
+ dimension : integer
127
+
128
+ Examples
129
+ ========
130
+
131
+ >>> from sympy import Point, Line
132
+ >>> p1, p2 = Point(0, 0), Point(1, 1)
133
+ >>> l1 = Line(p1, p2)
134
+ >>> l1.ambient_dimension
135
+ 2
136
+
137
+ >>> from sympy import Point, Line
138
+ >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
139
+ >>> l1 = Line(p1, p2)
140
+ >>> l1.ambient_dimension
141
+ 3
142
+
143
+ """
144
+ return len(self.p1)
145
+
146
+ def angle_between(l1, l2):
147
+ """Return the non-reflex angle formed by rays emanating from
148
+ the origin with directions the same as the direction vectors
149
+ of the linear entities.
150
+
151
+ Parameters
152
+ ==========
153
+
154
+ l1 : LinearEntity
155
+ l2 : LinearEntity
156
+
157
+ Returns
158
+ =======
159
+
160
+ angle : angle in radians
161
+
162
+ Notes
163
+ =====
164
+
165
+ From the dot product of vectors v1 and v2 it is known that:
166
+
167
+ ``dot(v1, v2) = |v1|*|v2|*cos(A)``
168
+
169
+ where A is the angle formed between the two vectors. We can
170
+ get the directional vectors of the two lines and readily
171
+ find the angle between the two using the above formula.
172
+
173
+ See Also
174
+ ========
175
+
176
+ is_perpendicular, Ray2D.closing_angle
177
+
178
+ Examples
179
+ ========
180
+
181
+ >>> from sympy import Line
182
+ >>> e = Line((0, 0), (1, 0))
183
+ >>> ne = Line((0, 0), (1, 1))
184
+ >>> sw = Line((1, 1), (0, 0))
185
+ >>> ne.angle_between(e)
186
+ pi/4
187
+ >>> sw.angle_between(e)
188
+ 3*pi/4
189
+
190
+ To obtain the non-obtuse angle at the intersection of lines, use
191
+ the ``smallest_angle_between`` method:
192
+
193
+ >>> sw.smallest_angle_between(e)
194
+ pi/4
195
+
196
+ >>> from sympy import Point3D, Line3D
197
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
198
+ >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
199
+ >>> l1.angle_between(l2)
200
+ acos(-sqrt(2)/3)
201
+ >>> l1.smallest_angle_between(l2)
202
+ acos(sqrt(2)/3)
203
+ """
204
+ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
205
+ raise TypeError('Must pass only LinearEntity objects')
206
+
207
+ v1, v2 = l1.direction, l2.direction
208
+ return acos(v1.dot(v2)/(abs(v1)*abs(v2)))
209
+
210
+ def smallest_angle_between(l1, l2):
211
+ """Return the smallest angle formed at the intersection of the
212
+ lines containing the linear entities.
213
+
214
+ Parameters
215
+ ==========
216
+
217
+ l1 : LinearEntity
218
+ l2 : LinearEntity
219
+
220
+ Returns
221
+ =======
222
+
223
+ angle : angle in radians
224
+
225
+ Examples
226
+ ========
227
+
228
+ >>> from sympy import Point, Line
229
+ >>> p1, p2, p3 = Point(0, 0), Point(0, 4), Point(2, -2)
230
+ >>> l1, l2 = Line(p1, p2), Line(p1, p3)
231
+ >>> l1.smallest_angle_between(l2)
232
+ pi/4
233
+
234
+ See Also
235
+ ========
236
+
237
+ angle_between, is_perpendicular, Ray2D.closing_angle
238
+ """
239
+ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
240
+ raise TypeError('Must pass only LinearEntity objects')
241
+
242
+ v1, v2 = l1.direction, l2.direction
243
+ return acos(abs(v1.dot(v2))/(abs(v1)*abs(v2)))
244
+
245
+ def arbitrary_point(self, parameter='t'):
246
+ """A parameterized point on the Line.
247
+
248
+ Parameters
249
+ ==========
250
+
251
+ parameter : str, optional
252
+ The name of the parameter which will be used for the parametric
253
+ point. The default value is 't'. When this parameter is 0, the
254
+ first point used to define the line will be returned, and when
255
+ it is 1 the second point will be returned.
256
+
257
+ Returns
258
+ =======
259
+
260
+ point : Point
261
+
262
+ Raises
263
+ ======
264
+
265
+ ValueError
266
+ When ``parameter`` already appears in the Line's definition.
267
+
268
+ See Also
269
+ ========
270
+
271
+ sympy.geometry.point.Point
272
+
273
+ Examples
274
+ ========
275
+
276
+ >>> from sympy import Point, Line
277
+ >>> p1, p2 = Point(1, 0), Point(5, 3)
278
+ >>> l1 = Line(p1, p2)
279
+ >>> l1.arbitrary_point()
280
+ Point2D(4*t + 1, 3*t)
281
+ >>> from sympy import Point3D, Line3D
282
+ >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 1)
283
+ >>> l1 = Line3D(p1, p2)
284
+ >>> l1.arbitrary_point()
285
+ Point3D(4*t + 1, 3*t, t)
286
+
287
+ """
288
+ t = _symbol(parameter, real=True)
289
+ if t.name in (f.name for f in self.free_symbols):
290
+ raise ValueError(filldedent('''
291
+ Symbol %s already appears in object
292
+ and cannot be used as a parameter.
293
+ ''' % t.name))
294
+ # multiply on the right so the variable gets
295
+ # combined with the coordinates of the point
296
+ return self.p1 + (self.p2 - self.p1)*t
297
+
298
+ @staticmethod
299
+ def are_concurrent(*lines):
300
+ """Is a sequence of linear entities concurrent?
301
+
302
+ Two or more linear entities are concurrent if they all
303
+ intersect at a single point.
304
+
305
+ Parameters
306
+ ==========
307
+
308
+ lines
309
+ A sequence of linear entities.
310
+
311
+ Returns
312
+ =======
313
+
314
+ True : if the set of linear entities intersect in one point
315
+ False : otherwise.
316
+
317
+ See Also
318
+ ========
319
+
320
+ sympy.geometry.util.intersection
321
+
322
+ Examples
323
+ ========
324
+
325
+ >>> from sympy import Point, Line
326
+ >>> p1, p2 = Point(0, 0), Point(3, 5)
327
+ >>> p3, p4 = Point(-2, -2), Point(0, 2)
328
+ >>> l1, l2, l3 = Line(p1, p2), Line(p1, p3), Line(p1, p4)
329
+ >>> Line.are_concurrent(l1, l2, l3)
330
+ True
331
+ >>> l4 = Line(p2, p3)
332
+ >>> Line.are_concurrent(l2, l3, l4)
333
+ False
334
+ >>> from sympy import Point3D, Line3D
335
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 5, 2)
336
+ >>> p3, p4 = Point3D(-2, -2, -2), Point3D(0, 2, 1)
337
+ >>> l1, l2, l3 = Line3D(p1, p2), Line3D(p1, p3), Line3D(p1, p4)
338
+ >>> Line3D.are_concurrent(l1, l2, l3)
339
+ True
340
+ >>> l4 = Line3D(p2, p3)
341
+ >>> Line3D.are_concurrent(l2, l3, l4)
342
+ False
343
+
344
+ """
345
+ common_points = Intersection(*lines)
346
+ if common_points.is_FiniteSet and len(common_points) == 1:
347
+ return True
348
+ return False
349
+
350
+ def contains(self, other):
351
+ """Subclasses should implement this method and should return
352
+ True if other is on the boundaries of self;
353
+ False if not on the boundaries of self;
354
+ None if a determination cannot be made."""
355
+ raise NotImplementedError()
356
+
357
+ @property
358
+ def direction(self):
359
+ """The direction vector of the LinearEntity.
360
+
361
+ Returns
362
+ =======
363
+
364
+ p : a Point; the ray from the origin to this point is the
365
+ direction of `self`
366
+
367
+ Examples
368
+ ========
369
+
370
+ >>> from sympy import Line
371
+ >>> a, b = (1, 1), (1, 3)
372
+ >>> Line(a, b).direction
373
+ Point2D(0, 2)
374
+ >>> Line(b, a).direction
375
+ Point2D(0, -2)
376
+
377
+ This can be reported so the distance from the origin is 1:
378
+
379
+ >>> Line(b, a).direction.unit
380
+ Point2D(0, -1)
381
+
382
+ See Also
383
+ ========
384
+
385
+ sympy.geometry.point.Point.unit
386
+
387
+ """
388
+ return self.p2 - self.p1
389
+
390
+ def intersection(self, other):
391
+ """The intersection with another geometrical entity.
392
+
393
+ Parameters
394
+ ==========
395
+
396
+ o : Point or LinearEntity
397
+
398
+ Returns
399
+ =======
400
+
401
+ intersection : list of geometrical entities
402
+
403
+ See Also
404
+ ========
405
+
406
+ sympy.geometry.point.Point
407
+
408
+ Examples
409
+ ========
410
+
411
+ >>> from sympy import Point, Line, Segment
412
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)
413
+ >>> l1 = Line(p1, p2)
414
+ >>> l1.intersection(p3)
415
+ [Point2D(7, 7)]
416
+ >>> p4, p5 = Point(5, 0), Point(0, 3)
417
+ >>> l2 = Line(p4, p5)
418
+ >>> l1.intersection(l2)
419
+ [Point2D(15/8, 15/8)]
420
+ >>> p6, p7 = Point(0, 5), Point(2, 6)
421
+ >>> s1 = Segment(p6, p7)
422
+ >>> l1.intersection(s1)
423
+ []
424
+ >>> from sympy import Point3D, Line3D, Segment3D
425
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(7, 7, 7)
426
+ >>> l1 = Line3D(p1, p2)
427
+ >>> l1.intersection(p3)
428
+ [Point3D(7, 7, 7)]
429
+ >>> l1 = Line3D(Point3D(4,19,12), Point3D(5,25,17))
430
+ >>> l2 = Line3D(Point3D(-3, -15, -19), direction_ratio=[2,8,8])
431
+ >>> l1.intersection(l2)
432
+ [Point3D(1, 1, -3)]
433
+ >>> p6, p7 = Point3D(0, 5, 2), Point3D(2, 6, 3)
434
+ >>> s1 = Segment3D(p6, p7)
435
+ >>> l1.intersection(s1)
436
+ []
437
+
438
+ """
439
+ def intersect_parallel_rays(ray1, ray2):
440
+ if ray1.direction.dot(ray2.direction) > 0:
441
+ # rays point in the same direction
442
+ # so return the one that is "in front"
443
+ return [ray2] if ray1._span_test(ray2.p1) >= 0 else [ray1]
444
+ else:
445
+ # rays point in opposite directions
446
+ st = ray1._span_test(ray2.p1)
447
+ if st < 0:
448
+ return []
449
+ elif st == 0:
450
+ return [ray2.p1]
451
+ return [Segment(ray1.p1, ray2.p1)]
452
+
453
+ def intersect_parallel_ray_and_segment(ray, seg):
454
+ st1, st2 = ray._span_test(seg.p1), ray._span_test(seg.p2)
455
+ if st1 < 0 and st2 < 0:
456
+ return []
457
+ elif st1 >= 0 and st2 >= 0:
458
+ return [seg]
459
+ elif st1 >= 0: # st2 < 0:
460
+ return [Segment(ray.p1, seg.p1)]
461
+ else: # st1 < 0 and st2 >= 0:
462
+ return [Segment(ray.p1, seg.p2)]
463
+
464
+ def intersect_parallel_segments(seg1, seg2):
465
+ if seg1.contains(seg2):
466
+ return [seg2]
467
+ if seg2.contains(seg1):
468
+ return [seg1]
469
+
470
+ # direct the segments so they're oriented the same way
471
+ if seg1.direction.dot(seg2.direction) < 0:
472
+ seg2 = Segment(seg2.p2, seg2.p1)
473
+ # order the segments so seg1 is "behind" seg2
474
+ if seg1._span_test(seg2.p1) < 0:
475
+ seg1, seg2 = seg2, seg1
476
+ if seg2._span_test(seg1.p2) < 0:
477
+ return []
478
+ return [Segment(seg2.p1, seg1.p2)]
479
+
480
+ if not isinstance(other, GeometryEntity):
481
+ other = Point(other, dim=self.ambient_dimension)
482
+ if other.is_Point:
483
+ if self.contains(other):
484
+ return [other]
485
+ else:
486
+ return []
487
+ elif isinstance(other, LinearEntity):
488
+ # break into cases based on whether
489
+ # the lines are parallel, non-parallel intersecting, or skew
490
+ pts = Point._normalize_dimension(self.p1, self.p2, other.p1, other.p2)
491
+ rank = Point.affine_rank(*pts)
492
+
493
+ if rank == 1:
494
+ # we're collinear
495
+ if isinstance(self, Line):
496
+ return [other]
497
+ if isinstance(other, Line):
498
+ return [self]
499
+
500
+ if isinstance(self, Ray) and isinstance(other, Ray):
501
+ return intersect_parallel_rays(self, other)
502
+ if isinstance(self, Ray) and isinstance(other, Segment):
503
+ return intersect_parallel_ray_and_segment(self, other)
504
+ if isinstance(self, Segment) and isinstance(other, Ray):
505
+ return intersect_parallel_ray_and_segment(other, self)
506
+ if isinstance(self, Segment) and isinstance(other, Segment):
507
+ return intersect_parallel_segments(self, other)
508
+ elif rank == 2:
509
+ # we're in the same plane
510
+ l1 = Line(*pts[:2])
511
+ l2 = Line(*pts[2:])
512
+
513
+ # check to see if we're parallel. If we are, we can't
514
+ # be intersecting, since the collinear case was already
515
+ # handled
516
+ if l1.direction.is_scalar_multiple(l2.direction):
517
+ return []
518
+
519
+ # find the intersection as if everything were lines
520
+ # by solving the equation t*d + p1 == s*d' + p1'
521
+ m = Matrix([l1.direction, -l2.direction]).transpose()
522
+ v = Matrix([l2.p1 - l1.p1]).transpose()
523
+
524
+ # we cannot use m.solve(v) because that only works for square matrices
525
+ m_rref, pivots = m.col_insert(2, v).rref(simplify=True)
526
+ # rank == 2 ensures we have 2 pivots, but let's check anyway
527
+ if len(pivots) != 2:
528
+ raise GeometryError("Failed when solving Mx=b when M={} and b={}".format(m, v))
529
+ coeff = m_rref[0, 2]
530
+ line_intersection = l1.direction*coeff + self.p1
531
+
532
+ # if both are lines, skip a containment check
533
+ if isinstance(self, Line) and isinstance(other, Line):
534
+ return [line_intersection]
535
+
536
+ if ((isinstance(self, Line) or
537
+ self.contains(line_intersection)) and
538
+ other.contains(line_intersection)):
539
+ return [line_intersection]
540
+ if not self.atoms(Float) and not other.atoms(Float):
541
+ # if it can fail when there are no Floats then
542
+ # maybe the following parametric check should be
543
+ # done
544
+ return []
545
+ # floats may fail exact containment so check that the
546
+ # arbitrary points, when equal, both give a
547
+ # non-negative parameter when the arbitrary point
548
+ # coordinates are equated
549
+ tu = solve(self.arbitrary_point(t) - other.arbitrary_point(u),
550
+ t, u, dict=True)[0]
551
+ def ok(p, l):
552
+ if isinstance(l, Line):
553
+ # p > -oo
554
+ return True
555
+ if isinstance(l, Ray):
556
+ # p >= 0
557
+ return p.is_nonnegative
558
+ if isinstance(l, Segment):
559
+ # 0 <= p <= 1
560
+ return p.is_nonnegative and (1 - p).is_nonnegative
561
+ raise ValueError("unexpected line type")
562
+ if ok(tu[t], self) and ok(tu[u], other):
563
+ return [line_intersection]
564
+ return []
565
+ else:
566
+ # we're skew
567
+ return []
568
+
569
+ return other.intersection(self)
570
+
571
+ def is_parallel(l1, l2):
572
+ """Are two linear entities parallel?
573
+
574
+ Parameters
575
+ ==========
576
+
577
+ l1 : LinearEntity
578
+ l2 : LinearEntity
579
+
580
+ Returns
581
+ =======
582
+
583
+ True : if l1 and l2 are parallel,
584
+ False : otherwise.
585
+
586
+ See Also
587
+ ========
588
+
589
+ coefficients
590
+
591
+ Examples
592
+ ========
593
+
594
+ >>> from sympy import Point, Line
595
+ >>> p1, p2 = Point(0, 0), Point(1, 1)
596
+ >>> p3, p4 = Point(3, 4), Point(6, 7)
597
+ >>> l1, l2 = Line(p1, p2), Line(p3, p4)
598
+ >>> Line.is_parallel(l1, l2)
599
+ True
600
+ >>> p5 = Point(6, 6)
601
+ >>> l3 = Line(p3, p5)
602
+ >>> Line.is_parallel(l1, l3)
603
+ False
604
+ >>> from sympy import Point3D, Line3D
605
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 4, 5)
606
+ >>> p3, p4 = Point3D(2, 1, 1), Point3D(8, 9, 11)
607
+ >>> l1, l2 = Line3D(p1, p2), Line3D(p3, p4)
608
+ >>> Line3D.is_parallel(l1, l2)
609
+ True
610
+ >>> p5 = Point3D(6, 6, 6)
611
+ >>> l3 = Line3D(p3, p5)
612
+ >>> Line3D.is_parallel(l1, l3)
613
+ False
614
+
615
+ """
616
+ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
617
+ raise TypeError('Must pass only LinearEntity objects')
618
+
619
+ return l1.direction.is_scalar_multiple(l2.direction)
620
+
621
+ def is_perpendicular(l1, l2):
622
+ """Are two linear entities perpendicular?
623
+
624
+ Parameters
625
+ ==========
626
+
627
+ l1 : LinearEntity
628
+ l2 : LinearEntity
629
+
630
+ Returns
631
+ =======
632
+
633
+ True : if l1 and l2 are perpendicular,
634
+ False : otherwise.
635
+
636
+ See Also
637
+ ========
638
+
639
+ coefficients
640
+
641
+ Examples
642
+ ========
643
+
644
+ >>> from sympy import Point, Line
645
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(-1, 1)
646
+ >>> l1, l2 = Line(p1, p2), Line(p1, p3)
647
+ >>> l1.is_perpendicular(l2)
648
+ True
649
+ >>> p4 = Point(5, 3)
650
+ >>> l3 = Line(p1, p4)
651
+ >>> l1.is_perpendicular(l3)
652
+ False
653
+ >>> from sympy import Point3D, Line3D
654
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
655
+ >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
656
+ >>> l1.is_perpendicular(l2)
657
+ False
658
+ >>> p4 = Point3D(5, 3, 7)
659
+ >>> l3 = Line3D(p1, p4)
660
+ >>> l1.is_perpendicular(l3)
661
+ False
662
+
663
+ """
664
+ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
665
+ raise TypeError('Must pass only LinearEntity objects')
666
+
667
+ return S.Zero.equals(l1.direction.dot(l2.direction))
668
+
669
+ def is_similar(self, other):
670
+ """
671
+ Return True if self and other are contained in the same line.
672
+
673
+ Examples
674
+ ========
675
+
676
+ >>> from sympy import Point, Line
677
+ >>> p1, p2, p3 = Point(0, 1), Point(3, 4), Point(2, 3)
678
+ >>> l1 = Line(p1, p2)
679
+ >>> l2 = Line(p1, p3)
680
+ >>> l1.is_similar(l2)
681
+ True
682
+ """
683
+ l = Line(self.p1, self.p2)
684
+ return l.contains(other)
685
+
686
+ @property
687
+ def length(self):
688
+ """
689
+ The length of the line.
690
+
691
+ Examples
692
+ ========
693
+
694
+ >>> from sympy import Point, Line
695
+ >>> p1, p2 = Point(0, 0), Point(3, 5)
696
+ >>> l1 = Line(p1, p2)
697
+ >>> l1.length
698
+ oo
699
+ """
700
+ return S.Infinity
701
+
702
+ @property
703
+ def p1(self):
704
+ """The first defining point of a linear entity.
705
+
706
+ See Also
707
+ ========
708
+
709
+ sympy.geometry.point.Point
710
+
711
+ Examples
712
+ ========
713
+
714
+ >>> from sympy import Point, Line
715
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
716
+ >>> l = Line(p1, p2)
717
+ >>> l.p1
718
+ Point2D(0, 0)
719
+
720
+ """
721
+ return self.args[0]
722
+
723
+ @property
724
+ def p2(self):
725
+ """The second defining point of a linear entity.
726
+
727
+ See Also
728
+ ========
729
+
730
+ sympy.geometry.point.Point
731
+
732
+ Examples
733
+ ========
734
+
735
+ >>> from sympy import Point, Line
736
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
737
+ >>> l = Line(p1, p2)
738
+ >>> l.p2
739
+ Point2D(5, 3)
740
+
741
+ """
742
+ return self.args[1]
743
+
744
+ def parallel_line(self, p):
745
+ """Create a new Line parallel to this linear entity which passes
746
+ through the point `p`.
747
+
748
+ Parameters
749
+ ==========
750
+
751
+ p : Point
752
+
753
+ Returns
754
+ =======
755
+
756
+ line : Line
757
+
758
+ See Also
759
+ ========
760
+
761
+ is_parallel
762
+
763
+ Examples
764
+ ========
765
+
766
+ >>> from sympy import Point, Line
767
+ >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
768
+ >>> l1 = Line(p1, p2)
769
+ >>> l2 = l1.parallel_line(p3)
770
+ >>> p3 in l2
771
+ True
772
+ >>> l1.is_parallel(l2)
773
+ True
774
+ >>> from sympy import Point3D, Line3D
775
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
776
+ >>> l1 = Line3D(p1, p2)
777
+ >>> l2 = l1.parallel_line(p3)
778
+ >>> p3 in l2
779
+ True
780
+ >>> l1.is_parallel(l2)
781
+ True
782
+
783
+ """
784
+ p = Point(p, dim=self.ambient_dimension)
785
+ return Line(p, p + self.direction)
786
+
787
+ def perpendicular_line(self, p):
788
+ """Create a new Line perpendicular to this linear entity which passes
789
+ through the point `p`.
790
+
791
+ Parameters
792
+ ==========
793
+
794
+ p : Point
795
+
796
+ Returns
797
+ =======
798
+
799
+ line : Line
800
+
801
+ See Also
802
+ ========
803
+
804
+ sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment
805
+
806
+ Examples
807
+ ========
808
+
809
+ >>> from sympy import Point3D, Line3D
810
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
811
+ >>> L = Line3D(p1, p2)
812
+ >>> P = L.perpendicular_line(p3); P
813
+ Line3D(Point3D(-2, 2, 0), Point3D(4/29, 6/29, 8/29))
814
+ >>> L.is_perpendicular(P)
815
+ True
816
+
817
+ In 3D the, the first point used to define the line is the point
818
+ through which the perpendicular was required to pass; the
819
+ second point is (arbitrarily) contained in the given line:
820
+
821
+ >>> P.p2 in L
822
+ True
823
+ """
824
+ p = Point(p, dim=self.ambient_dimension)
825
+ if p in self:
826
+ p = p + self.direction.orthogonal_direction
827
+ return Line(p, self.projection(p))
828
+
829
+ def perpendicular_segment(self, p):
830
+ """Create a perpendicular line segment from `p` to this line.
831
+
832
+ The endpoints of the segment are ``p`` and the closest point in
833
+ the line containing self. (If self is not a line, the point might
834
+ not be in self.)
835
+
836
+ Parameters
837
+ ==========
838
+
839
+ p : Point
840
+
841
+ Returns
842
+ =======
843
+
844
+ segment : Segment
845
+
846
+ Notes
847
+ =====
848
+
849
+ Returns `p` itself if `p` is on this linear entity.
850
+
851
+ See Also
852
+ ========
853
+
854
+ perpendicular_line
855
+
856
+ Examples
857
+ ========
858
+
859
+ >>> from sympy import Point, Line
860
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 2)
861
+ >>> l1 = Line(p1, p2)
862
+ >>> s1 = l1.perpendicular_segment(p3)
863
+ >>> l1.is_perpendicular(s1)
864
+ True
865
+ >>> p3 in s1
866
+ True
867
+ >>> l1.perpendicular_segment(Point(4, 0))
868
+ Segment2D(Point2D(4, 0), Point2D(2, 2))
869
+ >>> from sympy import Point3D, Line3D
870
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 2, 0)
871
+ >>> l1 = Line3D(p1, p2)
872
+ >>> s1 = l1.perpendicular_segment(p3)
873
+ >>> l1.is_perpendicular(s1)
874
+ True
875
+ >>> p3 in s1
876
+ True
877
+ >>> l1.perpendicular_segment(Point3D(4, 0, 0))
878
+ Segment3D(Point3D(4, 0, 0), Point3D(4/3, 4/3, 4/3))
879
+
880
+ """
881
+ p = Point(p, dim=self.ambient_dimension)
882
+ if p in self:
883
+ return p
884
+ l = self.perpendicular_line(p)
885
+ # The intersection should be unique, so unpack the singleton
886
+ p2, = Intersection(Line(self.p1, self.p2), l)
887
+
888
+ return Segment(p, p2)
889
+
890
+ @property
891
+ def points(self):
892
+ """The two points used to define this linear entity.
893
+
894
+ Returns
895
+ =======
896
+
897
+ points : tuple of Points
898
+
899
+ See Also
900
+ ========
901
+
902
+ sympy.geometry.point.Point
903
+
904
+ Examples
905
+ ========
906
+
907
+ >>> from sympy import Point, Line
908
+ >>> p1, p2 = Point(0, 0), Point(5, 11)
909
+ >>> l1 = Line(p1, p2)
910
+ >>> l1.points
911
+ (Point2D(0, 0), Point2D(5, 11))
912
+
913
+ """
914
+ return (self.p1, self.p2)
915
+
916
+ def projection(self, other):
917
+ """Project a point, line, ray, or segment onto this linear entity.
918
+
919
+ Parameters
920
+ ==========
921
+
922
+ other : Point or LinearEntity (Line, Ray, Segment)
923
+
924
+ Returns
925
+ =======
926
+
927
+ projection : Point or LinearEntity (Line, Ray, Segment)
928
+ The return type matches the type of the parameter ``other``.
929
+
930
+ Raises
931
+ ======
932
+
933
+ GeometryError
934
+ When method is unable to perform projection.
935
+
936
+ Notes
937
+ =====
938
+
939
+ A projection involves taking the two points that define
940
+ the linear entity and projecting those points onto a
941
+ Line and then reforming the linear entity using these
942
+ projections.
943
+ A point P is projected onto a line L by finding the point
944
+ on L that is closest to P. This point is the intersection
945
+ of L and the line perpendicular to L that passes through P.
946
+
947
+ See Also
948
+ ========
949
+
950
+ sympy.geometry.point.Point, perpendicular_line
951
+
952
+ Examples
953
+ ========
954
+
955
+ >>> from sympy import Point, Line, Segment, Rational
956
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(Rational(1, 2), 0)
957
+ >>> l1 = Line(p1, p2)
958
+ >>> l1.projection(p3)
959
+ Point2D(1/4, 1/4)
960
+ >>> p4, p5 = Point(10, 0), Point(12, 1)
961
+ >>> s1 = Segment(p4, p5)
962
+ >>> l1.projection(s1)
963
+ Segment2D(Point2D(5, 5), Point2D(13/2, 13/2))
964
+ >>> p1, p2, p3 = Point(0, 0, 1), Point(1, 1, 2), Point(2, 0, 1)
965
+ >>> l1 = Line(p1, p2)
966
+ >>> l1.projection(p3)
967
+ Point3D(2/3, 2/3, 5/3)
968
+ >>> p4, p5 = Point(10, 0, 1), Point(12, 1, 3)
969
+ >>> s1 = Segment(p4, p5)
970
+ >>> l1.projection(s1)
971
+ Segment3D(Point3D(10/3, 10/3, 13/3), Point3D(5, 5, 6))
972
+
973
+ """
974
+ if not isinstance(other, GeometryEntity):
975
+ other = Point(other, dim=self.ambient_dimension)
976
+
977
+ def proj_point(p):
978
+ return Point.project(p - self.p1, self.direction) + self.p1
979
+
980
+ if isinstance(other, Point):
981
+ return proj_point(other)
982
+ elif isinstance(other, LinearEntity):
983
+ p1, p2 = proj_point(other.p1), proj_point(other.p2)
984
+ # test to see if we're degenerate
985
+ if p1 == p2:
986
+ return p1
987
+ projected = other.__class__(p1, p2)
988
+ projected = Intersection(self, projected)
989
+ if projected.is_empty:
990
+ return projected
991
+ # if we happen to have intersected in only a point, return that
992
+ if projected.is_FiniteSet and len(projected) == 1:
993
+ # projected is a set of size 1, so unpack it in `a`
994
+ a, = projected
995
+ return a
996
+ # order args so projection is in the same direction as self
997
+ if self.direction.dot(projected.direction) < 0:
998
+ p1, p2 = projected.args
999
+ projected = projected.func(p2, p1)
1000
+ return projected
1001
+
1002
+ raise GeometryError(
1003
+ "Do not know how to project %s onto %s" % (other, self))
1004
+
1005
+ def random_point(self, seed=None):
1006
+ """A random point on a LinearEntity.
1007
+
1008
+ Returns
1009
+ =======
1010
+
1011
+ point : Point
1012
+
1013
+ See Also
1014
+ ========
1015
+
1016
+ sympy.geometry.point.Point
1017
+
1018
+ Examples
1019
+ ========
1020
+
1021
+ >>> from sympy import Point, Line, Ray, Segment
1022
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
1023
+ >>> line = Line(p1, p2)
1024
+ >>> r = line.random_point(seed=42) # seed value is optional
1025
+ >>> r.n(3)
1026
+ Point2D(-0.72, -0.432)
1027
+ >>> r in line
1028
+ True
1029
+ >>> Ray(p1, p2).random_point(seed=42).n(3)
1030
+ Point2D(0.72, 0.432)
1031
+ >>> Segment(p1, p2).random_point(seed=42).n(3)
1032
+ Point2D(3.2, 1.92)
1033
+
1034
+ """
1035
+ if seed is not None:
1036
+ rng = random.Random(seed)
1037
+ else:
1038
+ rng = random
1039
+ pt = self.arbitrary_point(t)
1040
+ if isinstance(self, Ray):
1041
+ v = abs(rng.gauss(0, 1))
1042
+ elif isinstance(self, Segment):
1043
+ v = rng.random()
1044
+ elif isinstance(self, Line):
1045
+ v = rng.gauss(0, 1)
1046
+ else:
1047
+ raise NotImplementedError('unhandled line type')
1048
+ return pt.subs(t, Rational(v))
1049
+
1050
+ def bisectors(self, other):
1051
+ """Returns the perpendicular lines which pass through the intersections
1052
+ of self and other that are in the same plane.
1053
+
1054
+ Parameters
1055
+ ==========
1056
+
1057
+ line : Line3D
1058
+
1059
+ Returns
1060
+ =======
1061
+
1062
+ list: two Line instances
1063
+
1064
+ Examples
1065
+ ========
1066
+
1067
+ >>> from sympy import Point3D, Line3D
1068
+ >>> r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
1069
+ >>> r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))
1070
+ >>> r1.bisectors(r2)
1071
+ [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))]
1072
+
1073
+ """
1074
+ if not isinstance(other, LinearEntity):
1075
+ raise GeometryError("Expecting LinearEntity, not %s" % other)
1076
+
1077
+ l1, l2 = self, other
1078
+
1079
+ # make sure dimensions match or else a warning will rise from
1080
+ # intersection calculation
1081
+ if l1.p1.ambient_dimension != l2.p1.ambient_dimension:
1082
+ if isinstance(l1, Line2D):
1083
+ l1, l2 = l2, l1
1084
+ _, p1 = Point._normalize_dimension(l1.p1, l2.p1, on_morph='ignore')
1085
+ _, p2 = Point._normalize_dimension(l1.p2, l2.p2, on_morph='ignore')
1086
+ l2 = Line(p1, p2)
1087
+
1088
+ point = intersection(l1, l2)
1089
+
1090
+ # Three cases: Lines may intersect in a point, may be equal or may not intersect.
1091
+ if not point:
1092
+ raise GeometryError("The lines do not intersect")
1093
+ else:
1094
+ pt = point[0]
1095
+ if isinstance(pt, Line):
1096
+ # Intersection is a line because both lines are coincident
1097
+ return [self]
1098
+
1099
+
1100
+ d1 = l1.direction.unit
1101
+ d2 = l2.direction.unit
1102
+
1103
+ bis1 = Line(pt, pt + d1 + d2)
1104
+ bis2 = Line(pt, pt + d1 - d2)
1105
+
1106
+ return [bis1, bis2]
1107
+
1108
+
1109
+ class Line(LinearEntity):
1110
+ """An infinite line in space.
1111
+
1112
+ A 2D line is declared with two distinct points, point and slope, or
1113
+ an equation. A 3D line may be defined with a point and a direction ratio.
1114
+
1115
+ Parameters
1116
+ ==========
1117
+
1118
+ p1 : Point
1119
+ p2 : Point
1120
+ slope : SymPy expression
1121
+ direction_ratio : list
1122
+ equation : equation of a line
1123
+
1124
+ Notes
1125
+ =====
1126
+
1127
+ `Line` will automatically subclass to `Line2D` or `Line3D` based
1128
+ on the dimension of `p1`. The `slope` argument is only relevant
1129
+ for `Line2D` and the `direction_ratio` argument is only relevant
1130
+ for `Line3D`.
1131
+
1132
+ The order of the points will define the direction of the line
1133
+ which is used when calculating the angle between lines.
1134
+
1135
+ See Also
1136
+ ========
1137
+
1138
+ sympy.geometry.point.Point
1139
+ sympy.geometry.line.Line2D
1140
+ sympy.geometry.line.Line3D
1141
+
1142
+ Examples
1143
+ ========
1144
+
1145
+ >>> from sympy import Line, Segment, Point, Eq
1146
+ >>> from sympy.abc import x, y, a, b
1147
+
1148
+ >>> L = Line(Point(2,3), Point(3,5))
1149
+ >>> L
1150
+ Line2D(Point2D(2, 3), Point2D(3, 5))
1151
+ >>> L.points
1152
+ (Point2D(2, 3), Point2D(3, 5))
1153
+ >>> L.equation()
1154
+ -2*x + y + 1
1155
+ >>> L.coefficients
1156
+ (-2, 1, 1)
1157
+
1158
+ Instantiate with keyword ``slope``:
1159
+
1160
+ >>> Line(Point(0, 0), slope=0)
1161
+ Line2D(Point2D(0, 0), Point2D(1, 0))
1162
+
1163
+ Instantiate with another linear object
1164
+
1165
+ >>> s = Segment((0, 0), (0, 1))
1166
+ >>> Line(s).equation()
1167
+ x
1168
+
1169
+ The line corresponding to an equation in the for `ax + by + c = 0`,
1170
+ can be entered:
1171
+
1172
+ >>> Line(3*x + y + 18)
1173
+ Line2D(Point2D(0, -18), Point2D(1, -21))
1174
+
1175
+ If `x` or `y` has a different name, then they can be specified, too,
1176
+ as a string (to match the name) or symbol:
1177
+
1178
+ >>> Line(Eq(3*a + b, -18), x='a', y=b)
1179
+ Line2D(Point2D(0, -18), Point2D(1, -21))
1180
+ """
1181
+ def __new__(cls, *args, **kwargs):
1182
+ if len(args) == 1 and isinstance(args[0], (Expr, Eq)):
1183
+ missing = uniquely_named_symbol('?', args)
1184
+ if not kwargs:
1185
+ x = 'x'
1186
+ y = 'y'
1187
+ else:
1188
+ x = kwargs.pop('x', missing)
1189
+ y = kwargs.pop('y', missing)
1190
+ if kwargs:
1191
+ raise ValueError('expecting only x and y as keywords')
1192
+
1193
+ equation = args[0]
1194
+ if isinstance(equation, Eq):
1195
+ equation = equation.lhs - equation.rhs
1196
+
1197
+ def find_or_missing(x):
1198
+ try:
1199
+ return find(x, equation)
1200
+ except ValueError:
1201
+ return missing
1202
+ x = find_or_missing(x)
1203
+ y = find_or_missing(y)
1204
+
1205
+ a, b, c = linear_coeffs(equation, x, y)
1206
+
1207
+ if b:
1208
+ return Line((0, -c/b), slope=-a/b)
1209
+ if a:
1210
+ return Line((-c/a, 0), slope=oo)
1211
+
1212
+ raise ValueError('not found in equation: %s' % (set('xy') - {x, y}))
1213
+
1214
+ else:
1215
+ if len(args) > 0:
1216
+ p1 = args[0]
1217
+ if len(args) > 1:
1218
+ p2 = args[1]
1219
+ else:
1220
+ p2 = None
1221
+
1222
+ if isinstance(p1, LinearEntity):
1223
+ if p2:
1224
+ raise ValueError('If p1 is a LinearEntity, p2 must be None.')
1225
+ dim = len(p1.p1)
1226
+ else:
1227
+ p1 = Point(p1)
1228
+ dim = len(p1)
1229
+ if p2 is not None or isinstance(p2, Point) and p2.ambient_dimension != dim:
1230
+ p2 = Point(p2)
1231
+
1232
+ if dim == 2:
1233
+ return Line2D(p1, p2, **kwargs)
1234
+ elif dim == 3:
1235
+ return Line3D(p1, p2, **kwargs)
1236
+ return LinearEntity.__new__(cls, p1, p2, **kwargs)
1237
+
1238
+ def contains(self, other):
1239
+ """
1240
+ Return True if `other` is on this Line, or False otherwise.
1241
+
1242
+ Examples
1243
+ ========
1244
+
1245
+ >>> from sympy import Line,Point
1246
+ >>> p1, p2 = Point(0, 1), Point(3, 4)
1247
+ >>> l = Line(p1, p2)
1248
+ >>> l.contains(p1)
1249
+ True
1250
+ >>> l.contains((0, 1))
1251
+ True
1252
+ >>> l.contains((0, 0))
1253
+ False
1254
+ >>> a = (0, 0, 0)
1255
+ >>> b = (1, 1, 1)
1256
+ >>> c = (2, 2, 2)
1257
+ >>> l1 = Line(a, b)
1258
+ >>> l2 = Line(b, a)
1259
+ >>> l1 == l2
1260
+ False
1261
+ >>> l1 in l2
1262
+ True
1263
+
1264
+ """
1265
+ if not isinstance(other, GeometryEntity):
1266
+ other = Point(other, dim=self.ambient_dimension)
1267
+ if isinstance(other, Point):
1268
+ return Point.is_collinear(other, self.p1, self.p2)
1269
+ if isinstance(other, LinearEntity):
1270
+ return Point.is_collinear(self.p1, self.p2, other.p1, other.p2)
1271
+ return False
1272
+
1273
+ def distance(self, other):
1274
+ """
1275
+ Finds the shortest distance between a line and a point.
1276
+
1277
+ Raises
1278
+ ======
1279
+
1280
+ NotImplementedError is raised if `other` is not a Point
1281
+
1282
+ Examples
1283
+ ========
1284
+
1285
+ >>> from sympy import Point, Line
1286
+ >>> p1, p2 = Point(0, 0), Point(1, 1)
1287
+ >>> s = Line(p1, p2)
1288
+ >>> s.distance(Point(-1, 1))
1289
+ sqrt(2)
1290
+ >>> s.distance((-1, 2))
1291
+ 3*sqrt(2)/2
1292
+ >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
1293
+ >>> s = Line(p1, p2)
1294
+ >>> s.distance(Point(-1, 1, 1))
1295
+ 2*sqrt(6)/3
1296
+ >>> s.distance((-1, 1, 1))
1297
+ 2*sqrt(6)/3
1298
+
1299
+ """
1300
+ if not isinstance(other, GeometryEntity):
1301
+ other = Point(other, dim=self.ambient_dimension)
1302
+ if self.contains(other):
1303
+ return S.Zero
1304
+ return self.perpendicular_segment(other).length
1305
+
1306
+ def equals(self, other):
1307
+ """Returns True if self and other are the same mathematical entities"""
1308
+ if not isinstance(other, Line):
1309
+ return False
1310
+ return Point.is_collinear(self.p1, other.p1, self.p2, other.p2)
1311
+
1312
+ def plot_interval(self, parameter='t'):
1313
+ """The plot interval for the default geometric plot of line. Gives
1314
+ values that will produce a line that is +/- 5 units long (where a
1315
+ unit is the distance between the two points that define the line).
1316
+
1317
+ Parameters
1318
+ ==========
1319
+
1320
+ parameter : str, optional
1321
+ Default value is 't'.
1322
+
1323
+ Returns
1324
+ =======
1325
+
1326
+ plot_interval : list (plot interval)
1327
+ [parameter, lower_bound, upper_bound]
1328
+
1329
+ Examples
1330
+ ========
1331
+
1332
+ >>> from sympy import Point, Line
1333
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
1334
+ >>> l1 = Line(p1, p2)
1335
+ >>> l1.plot_interval()
1336
+ [t, -5, 5]
1337
+
1338
+ """
1339
+ t = _symbol(parameter, real=True)
1340
+ return [t, -5, 5]
1341
+
1342
+
1343
+ class Ray(LinearEntity):
1344
+ """A Ray is a semi-line in the space with a source point and a direction.
1345
+
1346
+ Parameters
1347
+ ==========
1348
+
1349
+ p1 : Point
1350
+ The source of the Ray
1351
+ p2 : Point or radian value
1352
+ This point determines the direction in which the Ray propagates.
1353
+ If given as an angle it is interpreted in radians with the positive
1354
+ direction being ccw.
1355
+
1356
+ Attributes
1357
+ ==========
1358
+
1359
+ source
1360
+
1361
+ See Also
1362
+ ========
1363
+
1364
+ sympy.geometry.line.Ray2D
1365
+ sympy.geometry.line.Ray3D
1366
+ sympy.geometry.point.Point
1367
+ sympy.geometry.line.Line
1368
+
1369
+ Notes
1370
+ =====
1371
+
1372
+ `Ray` will automatically subclass to `Ray2D` or `Ray3D` based on the
1373
+ dimension of `p1`.
1374
+
1375
+ Examples
1376
+ ========
1377
+
1378
+ >>> from sympy import Ray, Point, pi
1379
+ >>> r = Ray(Point(2, 3), Point(3, 5))
1380
+ >>> r
1381
+ Ray2D(Point2D(2, 3), Point2D(3, 5))
1382
+ >>> r.points
1383
+ (Point2D(2, 3), Point2D(3, 5))
1384
+ >>> r.source
1385
+ Point2D(2, 3)
1386
+ >>> r.xdirection
1387
+ oo
1388
+ >>> r.ydirection
1389
+ oo
1390
+ >>> r.slope
1391
+ 2
1392
+ >>> Ray(Point(0, 0), angle=pi/4).slope
1393
+ 1
1394
+
1395
+ """
1396
+ def __new__(cls, p1, p2=None, **kwargs):
1397
+ p1 = Point(p1)
1398
+ if p2 is not None:
1399
+ p1, p2 = Point._normalize_dimension(p1, Point(p2))
1400
+ dim = len(p1)
1401
+
1402
+ if dim == 2:
1403
+ return Ray2D(p1, p2, **kwargs)
1404
+ elif dim == 3:
1405
+ return Ray3D(p1, p2, **kwargs)
1406
+ return LinearEntity.__new__(cls, p1, p2, **kwargs)
1407
+
1408
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
1409
+ """Returns SVG path element for the LinearEntity.
1410
+
1411
+ Parameters
1412
+ ==========
1413
+
1414
+ scale_factor : float
1415
+ Multiplication factor for the SVG stroke-width. Default is 1.
1416
+ fill_color : str, optional
1417
+ Hex string for fill color. Default is "#66cc99".
1418
+ """
1419
+ verts = (N(self.p1), N(self.p2))
1420
+ coords = ["{},{}".format(p.x, p.y) for p in verts]
1421
+ path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
1422
+
1423
+ return (
1424
+ '<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
1425
+ 'stroke-width="{0}" opacity="0.6" d="{1}" '
1426
+ 'marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"/>'
1427
+ ).format(2.*scale_factor, path, fill_color)
1428
+
1429
+ def contains(self, other):
1430
+ """
1431
+ Is other GeometryEntity contained in this Ray?
1432
+
1433
+ Examples
1434
+ ========
1435
+
1436
+ >>> from sympy import Ray,Point,Segment
1437
+ >>> p1, p2 = Point(0, 0), Point(4, 4)
1438
+ >>> r = Ray(p1, p2)
1439
+ >>> r.contains(p1)
1440
+ True
1441
+ >>> r.contains((1, 1))
1442
+ True
1443
+ >>> r.contains((1, 3))
1444
+ False
1445
+ >>> s = Segment((1, 1), (2, 2))
1446
+ >>> r.contains(s)
1447
+ True
1448
+ >>> s = Segment((1, 2), (2, 5))
1449
+ >>> r.contains(s)
1450
+ False
1451
+ >>> r1 = Ray((2, 2), (3, 3))
1452
+ >>> r.contains(r1)
1453
+ True
1454
+ >>> r1 = Ray((2, 2), (3, 5))
1455
+ >>> r.contains(r1)
1456
+ False
1457
+ """
1458
+ if not isinstance(other, GeometryEntity):
1459
+ other = Point(other, dim=self.ambient_dimension)
1460
+ if isinstance(other, Point):
1461
+ if Point.is_collinear(self.p1, self.p2, other):
1462
+ # if we're in the direction of the ray, our
1463
+ # direction vector dot the ray's direction vector
1464
+ # should be non-negative
1465
+ return bool((self.p2 - self.p1).dot(other - self.p1) >= S.Zero)
1466
+ return False
1467
+ elif isinstance(other, Ray):
1468
+ if Point.is_collinear(self.p1, self.p2, other.p1, other.p2):
1469
+ return bool((self.p2 - self.p1).dot(other.p2 - other.p1) > S.Zero)
1470
+ return False
1471
+ elif isinstance(other, Segment):
1472
+ return other.p1 in self and other.p2 in self
1473
+
1474
+ # No other known entity can be contained in a Ray
1475
+ return False
1476
+
1477
+ def distance(self, other):
1478
+ """
1479
+ Finds the shortest distance between the ray and a point.
1480
+
1481
+ Raises
1482
+ ======
1483
+
1484
+ NotImplementedError is raised if `other` is not a Point
1485
+
1486
+ Examples
1487
+ ========
1488
+
1489
+ >>> from sympy import Point, Ray
1490
+ >>> p1, p2 = Point(0, 0), Point(1, 1)
1491
+ >>> s = Ray(p1, p2)
1492
+ >>> s.distance(Point(-1, -1))
1493
+ sqrt(2)
1494
+ >>> s.distance((-1, 2))
1495
+ 3*sqrt(2)/2
1496
+ >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 2)
1497
+ >>> s = Ray(p1, p2)
1498
+ >>> s
1499
+ Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 2))
1500
+ >>> s.distance(Point(-1, -1, 2))
1501
+ 4*sqrt(3)/3
1502
+ >>> s.distance((-1, -1, 2))
1503
+ 4*sqrt(3)/3
1504
+
1505
+ """
1506
+ if not isinstance(other, GeometryEntity):
1507
+ other = Point(other, dim=self.ambient_dimension)
1508
+ if self.contains(other):
1509
+ return S.Zero
1510
+
1511
+ proj = Line(self.p1, self.p2).projection(other)
1512
+ if self.contains(proj):
1513
+ return abs(other - proj)
1514
+ else:
1515
+ return abs(other - self.source)
1516
+
1517
+ def equals(self, other):
1518
+ """Returns True if self and other are the same mathematical entities"""
1519
+ if not isinstance(other, Ray):
1520
+ return False
1521
+ return self.source == other.source and other.p2 in self
1522
+
1523
+ def plot_interval(self, parameter='t'):
1524
+ """The plot interval for the default geometric plot of the Ray. Gives
1525
+ values that will produce a ray that is 10 units long (where a unit is
1526
+ the distance between the two points that define the ray).
1527
+
1528
+ Parameters
1529
+ ==========
1530
+
1531
+ parameter : str, optional
1532
+ Default value is 't'.
1533
+
1534
+ Returns
1535
+ =======
1536
+
1537
+ plot_interval : list
1538
+ [parameter, lower_bound, upper_bound]
1539
+
1540
+ Examples
1541
+ ========
1542
+
1543
+ >>> from sympy import Ray, pi
1544
+ >>> r = Ray((0, 0), angle=pi/4)
1545
+ >>> r.plot_interval()
1546
+ [t, 0, 10]
1547
+
1548
+ """
1549
+ t = _symbol(parameter, real=True)
1550
+ return [t, 0, 10]
1551
+
1552
+ @property
1553
+ def source(self):
1554
+ """The point from which the ray emanates.
1555
+
1556
+ See Also
1557
+ ========
1558
+
1559
+ sympy.geometry.point.Point
1560
+
1561
+ Examples
1562
+ ========
1563
+
1564
+ >>> from sympy import Point, Ray
1565
+ >>> p1, p2 = Point(0, 0), Point(4, 1)
1566
+ >>> r1 = Ray(p1, p2)
1567
+ >>> r1.source
1568
+ Point2D(0, 0)
1569
+ >>> p1, p2 = Point(0, 0, 0), Point(4, 1, 5)
1570
+ >>> r1 = Ray(p2, p1)
1571
+ >>> r1.source
1572
+ Point3D(4, 1, 5)
1573
+
1574
+ """
1575
+ return self.p1
1576
+
1577
+
1578
+ class Segment(LinearEntity):
1579
+ """A line segment in space.
1580
+
1581
+ Parameters
1582
+ ==========
1583
+
1584
+ p1 : Point
1585
+ p2 : Point
1586
+
1587
+ Attributes
1588
+ ==========
1589
+
1590
+ length : number or SymPy expression
1591
+ midpoint : Point
1592
+
1593
+ See Also
1594
+ ========
1595
+
1596
+ sympy.geometry.line.Segment2D
1597
+ sympy.geometry.line.Segment3D
1598
+ sympy.geometry.point.Point
1599
+ sympy.geometry.line.Line
1600
+
1601
+ Notes
1602
+ =====
1603
+
1604
+ If 2D or 3D points are used to define `Segment`, it will
1605
+ be automatically subclassed to `Segment2D` or `Segment3D`.
1606
+
1607
+ Examples
1608
+ ========
1609
+
1610
+ >>> from sympy import Point, Segment
1611
+ >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
1612
+ Segment2D(Point2D(1, 0), Point2D(1, 1))
1613
+ >>> s = Segment(Point(4, 3), Point(1, 1))
1614
+ >>> s.points
1615
+ (Point2D(4, 3), Point2D(1, 1))
1616
+ >>> s.slope
1617
+ 2/3
1618
+ >>> s.length
1619
+ sqrt(13)
1620
+ >>> s.midpoint
1621
+ Point2D(5/2, 2)
1622
+ >>> Segment((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
1623
+ Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
1624
+ >>> s = Segment(Point(4, 3, 9), Point(1, 1, 7)); s
1625
+ Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
1626
+ >>> s.points
1627
+ (Point3D(4, 3, 9), Point3D(1, 1, 7))
1628
+ >>> s.length
1629
+ sqrt(17)
1630
+ >>> s.midpoint
1631
+ Point3D(5/2, 2, 8)
1632
+
1633
+ """
1634
+ def __new__(cls, p1, p2, **kwargs):
1635
+ p1, p2 = Point._normalize_dimension(Point(p1), Point(p2))
1636
+ dim = len(p1)
1637
+
1638
+ if dim == 2:
1639
+ return Segment2D(p1, p2, **kwargs)
1640
+ elif dim == 3:
1641
+ return Segment3D(p1, p2, **kwargs)
1642
+ return LinearEntity.__new__(cls, p1, p2, **kwargs)
1643
+
1644
+ def contains(self, other):
1645
+ """
1646
+ Is the other GeometryEntity contained within this Segment?
1647
+
1648
+ Examples
1649
+ ========
1650
+
1651
+ >>> from sympy import Point, Segment
1652
+ >>> p1, p2 = Point(0, 1), Point(3, 4)
1653
+ >>> s = Segment(p1, p2)
1654
+ >>> s2 = Segment(p2, p1)
1655
+ >>> s.contains(s2)
1656
+ True
1657
+ >>> from sympy import Point3D, Segment3D
1658
+ >>> p1, p2 = Point3D(0, 1, 1), Point3D(3, 4, 5)
1659
+ >>> s = Segment3D(p1, p2)
1660
+ >>> s2 = Segment3D(p2, p1)
1661
+ >>> s.contains(s2)
1662
+ True
1663
+ >>> s.contains((p1 + p2)/2)
1664
+ True
1665
+ """
1666
+ if not isinstance(other, GeometryEntity):
1667
+ other = Point(other, dim=self.ambient_dimension)
1668
+ if isinstance(other, Point):
1669
+ if Point.is_collinear(other, self.p1, self.p2):
1670
+ if isinstance(self, Segment2D):
1671
+ # if it is collinear and is in the bounding box of the
1672
+ # segment then it must be on the segment
1673
+ vert = (1/self.slope).equals(0)
1674
+ if vert is False:
1675
+ isin = (self.p1.x - other.x)*(self.p2.x - other.x) <= 0
1676
+ if isin in (True, False):
1677
+ return isin
1678
+ if vert is True:
1679
+ isin = (self.p1.y - other.y)*(self.p2.y - other.y) <= 0
1680
+ if isin in (True, False):
1681
+ return isin
1682
+ # use the triangle inequality
1683
+ d1, d2 = other - self.p1, other - self.p2
1684
+ d = self.p2 - self.p1
1685
+ # without the call to simplify, SymPy cannot tell that an expression
1686
+ # like (a+b)*(a/2+b/2) is always non-negative. If it cannot be
1687
+ # determined, raise an Undecidable error
1688
+ try:
1689
+ # the triangle inequality says that |d1|+|d2| >= |d| and is strict
1690
+ # only if other lies in the line segment
1691
+ return bool(simplify(Eq(abs(d1) + abs(d2) - abs(d), 0)))
1692
+ except TypeError:
1693
+ raise Undecidable("Cannot determine if {} is in {}".format(other, self))
1694
+ if isinstance(other, Segment):
1695
+ return other.p1 in self and other.p2 in self
1696
+
1697
+ return False
1698
+
1699
+ def equals(self, other):
1700
+ """Returns True if self and other are the same mathematical entities"""
1701
+ return isinstance(other, self.func) and list(
1702
+ ordered(self.args)) == list(ordered(other.args))
1703
+
1704
+ def distance(self, other):
1705
+ """
1706
+ Finds the shortest distance between a line segment and a point.
1707
+
1708
+ Raises
1709
+ ======
1710
+
1711
+ NotImplementedError is raised if `other` is not a Point
1712
+
1713
+ Examples
1714
+ ========
1715
+
1716
+ >>> from sympy import Point, Segment
1717
+ >>> p1, p2 = Point(0, 1), Point(3, 4)
1718
+ >>> s = Segment(p1, p2)
1719
+ >>> s.distance(Point(10, 15))
1720
+ sqrt(170)
1721
+ >>> s.distance((0, 12))
1722
+ sqrt(73)
1723
+ >>> from sympy import Point3D, Segment3D
1724
+ >>> p1, p2 = Point3D(0, 0, 3), Point3D(1, 1, 4)
1725
+ >>> s = Segment3D(p1, p2)
1726
+ >>> s.distance(Point3D(10, 15, 12))
1727
+ sqrt(341)
1728
+ >>> s.distance((10, 15, 12))
1729
+ sqrt(341)
1730
+ """
1731
+ if not isinstance(other, GeometryEntity):
1732
+ other = Point(other, dim=self.ambient_dimension)
1733
+ if isinstance(other, Point):
1734
+ vp1 = other - self.p1
1735
+ vp2 = other - self.p2
1736
+
1737
+ dot_prod_sign_1 = self.direction.dot(vp1) >= 0
1738
+ dot_prod_sign_2 = self.direction.dot(vp2) <= 0
1739
+ if dot_prod_sign_1 and dot_prod_sign_2:
1740
+ return Line(self.p1, self.p2).distance(other)
1741
+ if dot_prod_sign_1 and not dot_prod_sign_2:
1742
+ return abs(vp2)
1743
+ if not dot_prod_sign_1 and dot_prod_sign_2:
1744
+ return abs(vp1)
1745
+ raise NotImplementedError()
1746
+
1747
+ @property
1748
+ def length(self):
1749
+ """The length of the line segment.
1750
+
1751
+ See Also
1752
+ ========
1753
+
1754
+ sympy.geometry.point.Point.distance
1755
+
1756
+ Examples
1757
+ ========
1758
+
1759
+ >>> from sympy import Point, Segment
1760
+ >>> p1, p2 = Point(0, 0), Point(4, 3)
1761
+ >>> s1 = Segment(p1, p2)
1762
+ >>> s1.length
1763
+ 5
1764
+ >>> from sympy import Point3D, Segment3D
1765
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
1766
+ >>> s1 = Segment3D(p1, p2)
1767
+ >>> s1.length
1768
+ sqrt(34)
1769
+
1770
+ """
1771
+ return Point.distance(self.p1, self.p2)
1772
+
1773
+ @property
1774
+ def midpoint(self):
1775
+ """The midpoint of the line segment.
1776
+
1777
+ See Also
1778
+ ========
1779
+
1780
+ sympy.geometry.point.Point.midpoint
1781
+
1782
+ Examples
1783
+ ========
1784
+
1785
+ >>> from sympy import Point, Segment
1786
+ >>> p1, p2 = Point(0, 0), Point(4, 3)
1787
+ >>> s1 = Segment(p1, p2)
1788
+ >>> s1.midpoint
1789
+ Point2D(2, 3/2)
1790
+ >>> from sympy import Point3D, Segment3D
1791
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
1792
+ >>> s1 = Segment3D(p1, p2)
1793
+ >>> s1.midpoint
1794
+ Point3D(2, 3/2, 3/2)
1795
+
1796
+ """
1797
+ return Point.midpoint(self.p1, self.p2)
1798
+
1799
+ def perpendicular_bisector(self, p=None):
1800
+ """The perpendicular bisector of this segment.
1801
+
1802
+ If no point is specified or the point specified is not on the
1803
+ bisector then the bisector is returned as a Line. Otherwise a
1804
+ Segment is returned that joins the point specified and the
1805
+ intersection of the bisector and the segment.
1806
+
1807
+ Parameters
1808
+ ==========
1809
+
1810
+ p : Point
1811
+
1812
+ Returns
1813
+ =======
1814
+
1815
+ bisector : Line or Segment
1816
+
1817
+ See Also
1818
+ ========
1819
+
1820
+ LinearEntity.perpendicular_segment
1821
+
1822
+ Examples
1823
+ ========
1824
+
1825
+ >>> from sympy import Point, Segment
1826
+ >>> p1, p2, p3 = Point(0, 0), Point(6, 6), Point(5, 1)
1827
+ >>> s1 = Segment(p1, p2)
1828
+ >>> s1.perpendicular_bisector()
1829
+ Line2D(Point2D(3, 3), Point2D(-3, 9))
1830
+
1831
+ >>> s1.perpendicular_bisector(p3)
1832
+ Segment2D(Point2D(5, 1), Point2D(3, 3))
1833
+
1834
+ """
1835
+ l = self.perpendicular_line(self.midpoint)
1836
+ if p is not None:
1837
+ p2 = Point(p, dim=self.ambient_dimension)
1838
+ if p2 in l:
1839
+ return Segment(p2, self.midpoint)
1840
+ return l
1841
+
1842
+ def plot_interval(self, parameter='t'):
1843
+ """The plot interval for the default geometric plot of the Segment gives
1844
+ values that will produce the full segment in a plot.
1845
+
1846
+ Parameters
1847
+ ==========
1848
+
1849
+ parameter : str, optional
1850
+ Default value is 't'.
1851
+
1852
+ Returns
1853
+ =======
1854
+
1855
+ plot_interval : list
1856
+ [parameter, lower_bound, upper_bound]
1857
+
1858
+ Examples
1859
+ ========
1860
+
1861
+ >>> from sympy import Point, Segment
1862
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
1863
+ >>> s1 = Segment(p1, p2)
1864
+ >>> s1.plot_interval()
1865
+ [t, 0, 1]
1866
+
1867
+ """
1868
+ t = _symbol(parameter, real=True)
1869
+ return [t, 0, 1]
1870
+
1871
+
1872
+ class LinearEntity2D(LinearEntity):
1873
+ """A base class for all linear entities (line, ray and segment)
1874
+ in a 2-dimensional Euclidean space.
1875
+
1876
+ Attributes
1877
+ ==========
1878
+
1879
+ p1
1880
+ p2
1881
+ coefficients
1882
+ slope
1883
+ points
1884
+
1885
+ Notes
1886
+ =====
1887
+
1888
+ This is an abstract class and is not meant to be instantiated.
1889
+
1890
+ See Also
1891
+ ========
1892
+
1893
+ sympy.geometry.entity.GeometryEntity
1894
+
1895
+ """
1896
+ @property
1897
+ def bounds(self):
1898
+ """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
1899
+ rectangle for the geometric figure.
1900
+
1901
+ """
1902
+ verts = self.points
1903
+ xs = [p.x for p in verts]
1904
+ ys = [p.y for p in verts]
1905
+ return (min(xs), min(ys), max(xs), max(ys))
1906
+
1907
+ def perpendicular_line(self, p):
1908
+ """Create a new Line perpendicular to this linear entity which passes
1909
+ through the point `p`.
1910
+
1911
+ Parameters
1912
+ ==========
1913
+
1914
+ p : Point
1915
+
1916
+ Returns
1917
+ =======
1918
+
1919
+ line : Line
1920
+
1921
+ See Also
1922
+ ========
1923
+
1924
+ sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment
1925
+
1926
+ Examples
1927
+ ========
1928
+
1929
+ >>> from sympy import Point, Line
1930
+ >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
1931
+ >>> L = Line(p1, p2)
1932
+ >>> P = L.perpendicular_line(p3); P
1933
+ Line2D(Point2D(-2, 2), Point2D(-5, 4))
1934
+ >>> L.is_perpendicular(P)
1935
+ True
1936
+
1937
+ In 2D, the first point of the perpendicular line is the
1938
+ point through which was required to pass; the second
1939
+ point is arbitrarily chosen. To get a line that explicitly
1940
+ uses a point in the line, create a line from the perpendicular
1941
+ segment from the line to the point:
1942
+
1943
+ >>> Line(L.perpendicular_segment(p3))
1944
+ Line2D(Point2D(-2, 2), Point2D(4/13, 6/13))
1945
+ """
1946
+ p = Point(p, dim=self.ambient_dimension)
1947
+ # any two lines in R^2 intersect, so blindly making
1948
+ # a line through p in an orthogonal direction will work
1949
+ # and is faster than finding the projection point as in 3D
1950
+ return Line(p, p + self.direction.orthogonal_direction)
1951
+
1952
+ @property
1953
+ def slope(self):
1954
+ """The slope of this linear entity, or infinity if vertical.
1955
+
1956
+ Returns
1957
+ =======
1958
+
1959
+ slope : number or SymPy expression
1960
+
1961
+ See Also
1962
+ ========
1963
+
1964
+ coefficients
1965
+
1966
+ Examples
1967
+ ========
1968
+
1969
+ >>> from sympy import Point, Line
1970
+ >>> p1, p2 = Point(0, 0), Point(3, 5)
1971
+ >>> l1 = Line(p1, p2)
1972
+ >>> l1.slope
1973
+ 5/3
1974
+
1975
+ >>> p3 = Point(0, 4)
1976
+ >>> l2 = Line(p1, p3)
1977
+ >>> l2.slope
1978
+ oo
1979
+
1980
+ """
1981
+ d1, d2 = (self.p1 - self.p2).args
1982
+ if d1 == 0:
1983
+ return S.Infinity
1984
+ return simplify(d2/d1)
1985
+
1986
+
1987
+ class Line2D(LinearEntity2D, Line):
1988
+ """An infinite line in space 2D.
1989
+
1990
+ A line is declared with two distinct points or a point and slope
1991
+ as defined using keyword `slope`.
1992
+
1993
+ Parameters
1994
+ ==========
1995
+
1996
+ p1 : Point
1997
+ pt : Point
1998
+ slope : SymPy expression
1999
+
2000
+ See Also
2001
+ ========
2002
+
2003
+ sympy.geometry.point.Point
2004
+
2005
+ Examples
2006
+ ========
2007
+
2008
+ >>> from sympy import Line, Segment, Point
2009
+ >>> L = Line(Point(2,3), Point(3,5))
2010
+ >>> L
2011
+ Line2D(Point2D(2, 3), Point2D(3, 5))
2012
+ >>> L.points
2013
+ (Point2D(2, 3), Point2D(3, 5))
2014
+ >>> L.equation()
2015
+ -2*x + y + 1
2016
+ >>> L.coefficients
2017
+ (-2, 1, 1)
2018
+
2019
+ Instantiate with keyword ``slope``:
2020
+
2021
+ >>> Line(Point(0, 0), slope=0)
2022
+ Line2D(Point2D(0, 0), Point2D(1, 0))
2023
+
2024
+ Instantiate with another linear object
2025
+
2026
+ >>> s = Segment((0, 0), (0, 1))
2027
+ >>> Line(s).equation()
2028
+ x
2029
+ """
2030
+ def __new__(cls, p1, pt=None, slope=None, **kwargs):
2031
+ if isinstance(p1, LinearEntity):
2032
+ if pt is not None:
2033
+ raise ValueError('When p1 is a LinearEntity, pt should be None')
2034
+ p1, pt = Point._normalize_dimension(*p1.args, dim=2)
2035
+ else:
2036
+ p1 = Point(p1, dim=2)
2037
+ if pt is not None and slope is None:
2038
+ try:
2039
+ p2 = Point(pt, dim=2)
2040
+ except (NotImplementedError, TypeError, ValueError):
2041
+ raise ValueError(filldedent('''
2042
+ The 2nd argument was not a valid Point.
2043
+ If it was a slope, enter it with keyword "slope".
2044
+ '''))
2045
+ elif slope is not None and pt is None:
2046
+ slope = sympify(slope)
2047
+ if slope.is_finite is False:
2048
+ # when infinite slope, don't change x
2049
+ dx = 0
2050
+ dy = 1
2051
+ else:
2052
+ # go over 1 up slope
2053
+ dx = 1
2054
+ dy = slope
2055
+ # XXX avoiding simplification by adding to coords directly
2056
+ p2 = Point(p1.x + dx, p1.y + dy, evaluate=False)
2057
+ else:
2058
+ raise ValueError('A 2nd Point or keyword "slope" must be used.')
2059
+ return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
2060
+
2061
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
2062
+ """Returns SVG path element for the LinearEntity.
2063
+
2064
+ Parameters
2065
+ ==========
2066
+
2067
+ scale_factor : float
2068
+ Multiplication factor for the SVG stroke-width. Default is 1.
2069
+ fill_color : str, optional
2070
+ Hex string for fill color. Default is "#66cc99".
2071
+ """
2072
+ verts = (N(self.p1), N(self.p2))
2073
+ coords = ["{},{}".format(p.x, p.y) for p in verts]
2074
+ path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
2075
+
2076
+ return (
2077
+ '<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
2078
+ 'stroke-width="{0}" opacity="0.6" d="{1}" '
2079
+ 'marker-start="url(#markerReverseArrow)" marker-end="url(#markerArrow)"/>'
2080
+ ).format(2.*scale_factor, path, fill_color)
2081
+
2082
+ @property
2083
+ def coefficients(self):
2084
+ """The coefficients (`a`, `b`, `c`) for `ax + by + c = 0`.
2085
+
2086
+ See Also
2087
+ ========
2088
+
2089
+ sympy.geometry.line.Line2D.equation
2090
+
2091
+ Examples
2092
+ ========
2093
+
2094
+ >>> from sympy import Point, Line
2095
+ >>> from sympy.abc import x, y
2096
+ >>> p1, p2 = Point(0, 0), Point(5, 3)
2097
+ >>> l = Line(p1, p2)
2098
+ >>> l.coefficients
2099
+ (-3, 5, 0)
2100
+
2101
+ >>> p3 = Point(x, y)
2102
+ >>> l2 = Line(p1, p3)
2103
+ >>> l2.coefficients
2104
+ (-y, x, 0)
2105
+
2106
+ """
2107
+ p1, p2 = self.points
2108
+ if p1.x == p2.x:
2109
+ return (S.One, S.Zero, -p1.x)
2110
+ elif p1.y == p2.y:
2111
+ return (S.Zero, S.One, -p1.y)
2112
+ return tuple([simplify(i) for i in
2113
+ (self.p1.y - self.p2.y,
2114
+ self.p2.x - self.p1.x,
2115
+ self.p1.x*self.p2.y - self.p1.y*self.p2.x)])
2116
+
2117
+ def equation(self, x='x', y='y'):
2118
+ """The equation of the line: ax + by + c.
2119
+
2120
+ Parameters
2121
+ ==========
2122
+
2123
+ x : str, optional
2124
+ The name to use for the x-axis, default value is 'x'.
2125
+ y : str, optional
2126
+ The name to use for the y-axis, default value is 'y'.
2127
+
2128
+ Returns
2129
+ =======
2130
+
2131
+ equation : SymPy expression
2132
+
2133
+ See Also
2134
+ ========
2135
+
2136
+ sympy.geometry.line.Line2D.coefficients
2137
+
2138
+ Examples
2139
+ ========
2140
+
2141
+ >>> from sympy import Point, Line
2142
+ >>> p1, p2 = Point(1, 0), Point(5, 3)
2143
+ >>> l1 = Line(p1, p2)
2144
+ >>> l1.equation()
2145
+ -3*x + 4*y + 3
2146
+
2147
+ """
2148
+ x = _symbol(x, real=True)
2149
+ y = _symbol(y, real=True)
2150
+ p1, p2 = self.points
2151
+ if p1.x == p2.x:
2152
+ return x - p1.x
2153
+ elif p1.y == p2.y:
2154
+ return y - p1.y
2155
+
2156
+ a, b, c = self.coefficients
2157
+ return a*x + b*y + c
2158
+
2159
+
2160
+ class Ray2D(LinearEntity2D, Ray):
2161
+ """
2162
+ A Ray is a semi-line in the space with a source point and a direction.
2163
+
2164
+ Parameters
2165
+ ==========
2166
+
2167
+ p1 : Point
2168
+ The source of the Ray
2169
+ p2 : Point or radian value
2170
+ This point determines the direction in which the Ray propagates.
2171
+ If given as an angle it is interpreted in radians with the positive
2172
+ direction being ccw.
2173
+
2174
+ Attributes
2175
+ ==========
2176
+
2177
+ source
2178
+ xdirection
2179
+ ydirection
2180
+
2181
+ See Also
2182
+ ========
2183
+
2184
+ sympy.geometry.point.Point, Line
2185
+
2186
+ Examples
2187
+ ========
2188
+
2189
+ >>> from sympy import Point, pi, Ray
2190
+ >>> r = Ray(Point(2, 3), Point(3, 5))
2191
+ >>> r
2192
+ Ray2D(Point2D(2, 3), Point2D(3, 5))
2193
+ >>> r.points
2194
+ (Point2D(2, 3), Point2D(3, 5))
2195
+ >>> r.source
2196
+ Point2D(2, 3)
2197
+ >>> r.xdirection
2198
+ oo
2199
+ >>> r.ydirection
2200
+ oo
2201
+ >>> r.slope
2202
+ 2
2203
+ >>> Ray(Point(0, 0), angle=pi/4).slope
2204
+ 1
2205
+
2206
+ """
2207
+ def __new__(cls, p1, pt=None, angle=None, **kwargs):
2208
+ p1 = Point(p1, dim=2)
2209
+ if pt is not None and angle is None:
2210
+ try:
2211
+ p2 = Point(pt, dim=2)
2212
+ except (NotImplementedError, TypeError, ValueError):
2213
+ raise ValueError(filldedent('''
2214
+ The 2nd argument was not a valid Point; if
2215
+ it was meant to be an angle it should be
2216
+ given with keyword "angle".'''))
2217
+ if p1 == p2:
2218
+ raise ValueError('A Ray requires two distinct points.')
2219
+ elif angle is not None and pt is None:
2220
+ # we need to know if the angle is an odd multiple of pi/2
2221
+ angle = sympify(angle)
2222
+ c = _pi_coeff(angle)
2223
+ p2 = None
2224
+ if c is not None:
2225
+ if c.is_Rational:
2226
+ if c.q == 2:
2227
+ if c.p == 1:
2228
+ p2 = p1 + Point(0, 1)
2229
+ elif c.p == 3:
2230
+ p2 = p1 + Point(0, -1)
2231
+ elif c.q == 1:
2232
+ if c.p == 0:
2233
+ p2 = p1 + Point(1, 0)
2234
+ elif c.p == 1:
2235
+ p2 = p1 + Point(-1, 0)
2236
+ if p2 is None:
2237
+ c *= S.Pi
2238
+ else:
2239
+ c = angle % (2*S.Pi)
2240
+ if not p2:
2241
+ m = 2*c/S.Pi
2242
+ left = And(1 < m, m < 3) # is it in quadrant 2 or 3?
2243
+ x = Piecewise((-1, left), (Piecewise((0, Eq(m % 1, 0)), (1, True)), True))
2244
+ y = Piecewise((-tan(c), left), (Piecewise((1, Eq(m, 1)), (-1, Eq(m, 3)), (tan(c), True)), True))
2245
+ p2 = p1 + Point(x, y)
2246
+ else:
2247
+ raise ValueError('A 2nd point or keyword "angle" must be used.')
2248
+
2249
+ return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
2250
+
2251
+ @property
2252
+ def xdirection(self):
2253
+ """The x direction of the ray.
2254
+
2255
+ Positive infinity if the ray points in the positive x direction,
2256
+ negative infinity if the ray points in the negative x direction,
2257
+ or 0 if the ray is vertical.
2258
+
2259
+ See Also
2260
+ ========
2261
+
2262
+ ydirection
2263
+
2264
+ Examples
2265
+ ========
2266
+
2267
+ >>> from sympy import Point, Ray
2268
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, -1)
2269
+ >>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
2270
+ >>> r1.xdirection
2271
+ oo
2272
+ >>> r2.xdirection
2273
+ 0
2274
+
2275
+ """
2276
+ if self.p1.x < self.p2.x:
2277
+ return S.Infinity
2278
+ elif self.p1.x == self.p2.x:
2279
+ return S.Zero
2280
+ else:
2281
+ return S.NegativeInfinity
2282
+
2283
+ @property
2284
+ def ydirection(self):
2285
+ """The y direction of the ray.
2286
+
2287
+ Positive infinity if the ray points in the positive y direction,
2288
+ negative infinity if the ray points in the negative y direction,
2289
+ or 0 if the ray is horizontal.
2290
+
2291
+ See Also
2292
+ ========
2293
+
2294
+ xdirection
2295
+
2296
+ Examples
2297
+ ========
2298
+
2299
+ >>> from sympy import Point, Ray
2300
+ >>> p1, p2, p3 = Point(0, 0), Point(-1, -1), Point(-1, 0)
2301
+ >>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
2302
+ >>> r1.ydirection
2303
+ -oo
2304
+ >>> r2.ydirection
2305
+ 0
2306
+
2307
+ """
2308
+ if self.p1.y < self.p2.y:
2309
+ return S.Infinity
2310
+ elif self.p1.y == self.p2.y:
2311
+ return S.Zero
2312
+ else:
2313
+ return S.NegativeInfinity
2314
+
2315
+ def closing_angle(r1, r2):
2316
+ """Return the angle by which r2 must be rotated so it faces the same
2317
+ direction as r1.
2318
+
2319
+ Parameters
2320
+ ==========
2321
+
2322
+ r1 : Ray2D
2323
+ r2 : Ray2D
2324
+
2325
+ Returns
2326
+ =======
2327
+
2328
+ angle : angle in radians (ccw angle is positive)
2329
+
2330
+ See Also
2331
+ ========
2332
+
2333
+ LinearEntity.angle_between
2334
+
2335
+ Examples
2336
+ ========
2337
+
2338
+ >>> from sympy import Ray, pi
2339
+ >>> r1 = Ray((0, 0), (1, 0))
2340
+ >>> r2 = r1.rotate(-pi/2)
2341
+ >>> angle = r1.closing_angle(r2); angle
2342
+ pi/2
2343
+ >>> r2.rotate(angle).direction.unit == r1.direction.unit
2344
+ True
2345
+ >>> r2.closing_angle(r1)
2346
+ -pi/2
2347
+ """
2348
+ if not all(isinstance(r, Ray2D) for r in (r1, r2)):
2349
+ # although the direction property is defined for
2350
+ # all linear entities, only the Ray is truly a
2351
+ # directed object
2352
+ raise TypeError('Both arguments must be Ray2D objects.')
2353
+
2354
+ a1 = atan2(*list(reversed(r1.direction.args)))
2355
+ a2 = atan2(*list(reversed(r2.direction.args)))
2356
+ if a1*a2 < 0:
2357
+ a1 = 2*S.Pi + a1 if a1 < 0 else a1
2358
+ a2 = 2*S.Pi + a2 if a2 < 0 else a2
2359
+ return a1 - a2
2360
+
2361
+
2362
+ class Segment2D(LinearEntity2D, Segment):
2363
+ """A line segment in 2D space.
2364
+
2365
+ Parameters
2366
+ ==========
2367
+
2368
+ p1 : Point
2369
+ p2 : Point
2370
+
2371
+ Attributes
2372
+ ==========
2373
+
2374
+ length : number or SymPy expression
2375
+ midpoint : Point
2376
+
2377
+ See Also
2378
+ ========
2379
+
2380
+ sympy.geometry.point.Point, Line
2381
+
2382
+ Examples
2383
+ ========
2384
+
2385
+ >>> from sympy import Point, Segment
2386
+ >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
2387
+ Segment2D(Point2D(1, 0), Point2D(1, 1))
2388
+ >>> s = Segment(Point(4, 3), Point(1, 1)); s
2389
+ Segment2D(Point2D(4, 3), Point2D(1, 1))
2390
+ >>> s.points
2391
+ (Point2D(4, 3), Point2D(1, 1))
2392
+ >>> s.slope
2393
+ 2/3
2394
+ >>> s.length
2395
+ sqrt(13)
2396
+ >>> s.midpoint
2397
+ Point2D(5/2, 2)
2398
+
2399
+ """
2400
+ def __new__(cls, p1, p2, **kwargs):
2401
+ p1 = Point(p1, dim=2)
2402
+ p2 = Point(p2, dim=2)
2403
+
2404
+ if p1 == p2:
2405
+ return p1
2406
+
2407
+ return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
2408
+
2409
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
2410
+ """Returns SVG path element for the LinearEntity.
2411
+
2412
+ Parameters
2413
+ ==========
2414
+
2415
+ scale_factor : float
2416
+ Multiplication factor for the SVG stroke-width. Default is 1.
2417
+ fill_color : str, optional
2418
+ Hex string for fill color. Default is "#66cc99".
2419
+ """
2420
+ verts = (N(self.p1), N(self.p2))
2421
+ coords = ["{},{}".format(p.x, p.y) for p in verts]
2422
+ path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
2423
+ return (
2424
+ '<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
2425
+ 'stroke-width="{0}" opacity="0.6" d="{1}" />'
2426
+ ).format(2.*scale_factor, path, fill_color)
2427
+
2428
+
2429
+ class LinearEntity3D(LinearEntity):
2430
+ """An base class for all linear entities (line, ray and segment)
2431
+ in a 3-dimensional Euclidean space.
2432
+
2433
+ Attributes
2434
+ ==========
2435
+
2436
+ p1
2437
+ p2
2438
+ direction_ratio
2439
+ direction_cosine
2440
+ points
2441
+
2442
+ Notes
2443
+ =====
2444
+
2445
+ This is a base class and is not meant to be instantiated.
2446
+ """
2447
+ def __new__(cls, p1, p2, **kwargs):
2448
+ p1 = Point3D(p1, dim=3)
2449
+ p2 = Point3D(p2, dim=3)
2450
+ if p1 == p2:
2451
+ # if it makes sense to return a Point, handle in subclass
2452
+ raise ValueError(
2453
+ "%s.__new__ requires two unique Points." % cls.__name__)
2454
+
2455
+ return GeometryEntity.__new__(cls, p1, p2, **kwargs)
2456
+
2457
+ ambient_dimension = 3
2458
+
2459
+ @property
2460
+ def direction_ratio(self):
2461
+ """The direction ratio of a given line in 3D.
2462
+
2463
+ See Also
2464
+ ========
2465
+
2466
+ sympy.geometry.line.Line3D.equation
2467
+
2468
+ Examples
2469
+ ========
2470
+
2471
+ >>> from sympy import Point3D, Line3D
2472
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
2473
+ >>> l = Line3D(p1, p2)
2474
+ >>> l.direction_ratio
2475
+ [5, 3, 1]
2476
+ """
2477
+ p1, p2 = self.points
2478
+ return p1.direction_ratio(p2)
2479
+
2480
+ @property
2481
+ def direction_cosine(self):
2482
+ """The normalized direction ratio of a given line in 3D.
2483
+
2484
+ See Also
2485
+ ========
2486
+
2487
+ sympy.geometry.line.Line3D.equation
2488
+
2489
+ Examples
2490
+ ========
2491
+
2492
+ >>> from sympy import Point3D, Line3D
2493
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
2494
+ >>> l = Line3D(p1, p2)
2495
+ >>> l.direction_cosine
2496
+ [sqrt(35)/7, 3*sqrt(35)/35, sqrt(35)/35]
2497
+ >>> sum(i**2 for i in _)
2498
+ 1
2499
+ """
2500
+ p1, p2 = self.points
2501
+ return p1.direction_cosine(p2)
2502
+
2503
+
2504
+ class Line3D(LinearEntity3D, Line):
2505
+ """An infinite 3D line in space.
2506
+
2507
+ A line is declared with two distinct points or a point and direction_ratio
2508
+ as defined using keyword `direction_ratio`.
2509
+
2510
+ Parameters
2511
+ ==========
2512
+
2513
+ p1 : Point3D
2514
+ pt : Point3D
2515
+ direction_ratio : list
2516
+
2517
+ See Also
2518
+ ========
2519
+
2520
+ sympy.geometry.point.Point3D
2521
+ sympy.geometry.line.Line
2522
+ sympy.geometry.line.Line2D
2523
+
2524
+ Examples
2525
+ ========
2526
+
2527
+ >>> from sympy import Line3D, Point3D
2528
+ >>> L = Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
2529
+ >>> L
2530
+ Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
2531
+ >>> L.points
2532
+ (Point3D(2, 3, 4), Point3D(3, 5, 1))
2533
+ """
2534
+ def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs):
2535
+ if isinstance(p1, LinearEntity3D):
2536
+ if pt is not None:
2537
+ raise ValueError('if p1 is a LinearEntity, pt must be None.')
2538
+ p1, pt = p1.args
2539
+ else:
2540
+ p1 = Point(p1, dim=3)
2541
+ if pt is not None and len(direction_ratio) == 0:
2542
+ pt = Point(pt, dim=3)
2543
+ elif len(direction_ratio) == 3 and pt is None:
2544
+ pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1],
2545
+ p1.z + direction_ratio[2])
2546
+ else:
2547
+ raise ValueError('A 2nd Point or keyword "direction_ratio" must '
2548
+ 'be used.')
2549
+
2550
+ return LinearEntity3D.__new__(cls, p1, pt, **kwargs)
2551
+
2552
+ def equation(self, x='x', y='y', z='z'):
2553
+ """Return the equations that define the line in 3D.
2554
+
2555
+ Parameters
2556
+ ==========
2557
+
2558
+ x : str, optional
2559
+ The name to use for the x-axis, default value is 'x'.
2560
+ y : str, optional
2561
+ The name to use for the y-axis, default value is 'y'.
2562
+ z : str, optional
2563
+ The name to use for the z-axis, default value is 'z'.
2564
+
2565
+ Returns
2566
+ =======
2567
+
2568
+ equation : Tuple of simultaneous equations
2569
+
2570
+ Examples
2571
+ ========
2572
+
2573
+ >>> from sympy import Point3D, Line3D, solve
2574
+ >>> from sympy.abc import x, y, z
2575
+ >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 0)
2576
+ >>> l1 = Line3D(p1, p2)
2577
+ >>> eq = l1.equation(x, y, z); eq
2578
+ (-3*x + 4*y + 3, z)
2579
+ >>> solve(eq.subs(z, 0), (x, y, z))
2580
+ {x: 4*y/3 + 1}
2581
+ """
2582
+ x, y, z, k = [_symbol(i, real=True) for i in (x, y, z, 'k')]
2583
+ p1, p2 = self.points
2584
+ d1, d2, d3 = p1.direction_ratio(p2)
2585
+ x1, y1, z1 = p1
2586
+ eqs = [-d1*k + x - x1, -d2*k + y - y1, -d3*k + z - z1]
2587
+ # eliminate k from equations by solving first eq with k for k
2588
+ for i, e in enumerate(eqs):
2589
+ if e.has(k):
2590
+ kk = solve(eqs[i], k)[0]
2591
+ eqs.pop(i)
2592
+ break
2593
+ return Tuple(*[i.subs(k, kk).as_numer_denom()[0] for i in eqs])
2594
+
2595
+ def distance(self, other):
2596
+ """
2597
+ Finds the shortest distance between a line and another object.
2598
+
2599
+ Parameters
2600
+ ==========
2601
+
2602
+ Point3D, Line3D, Plane, tuple, list
2603
+
2604
+ Returns
2605
+ =======
2606
+
2607
+ distance
2608
+
2609
+ Notes
2610
+ =====
2611
+
2612
+ This method accepts only 3D entities as it's parameter
2613
+
2614
+ Tuples and lists are converted to Point3D and therefore must be of
2615
+ length 3, 2 or 1.
2616
+
2617
+ NotImplementedError is raised if `other` is not an instance of one
2618
+ of the specified classes: Point3D, Line3D, or Plane.
2619
+
2620
+ Examples
2621
+ ========
2622
+
2623
+ >>> from sympy.geometry import Line3D
2624
+ >>> l1 = Line3D((0, 0, 0), (0, 0, 1))
2625
+ >>> l2 = Line3D((0, 1, 0), (1, 1, 1))
2626
+ >>> l1.distance(l2)
2627
+ 1
2628
+
2629
+ The computed distance may be symbolic, too:
2630
+
2631
+ >>> from sympy.abc import x, y
2632
+ >>> l1 = Line3D((0, 0, 0), (0, 0, 1))
2633
+ >>> l2 = Line3D((0, x, 0), (y, x, 1))
2634
+ >>> l1.distance(l2)
2635
+ Abs(x*y)/Abs(sqrt(y**2))
2636
+
2637
+ """
2638
+
2639
+ from .plane import Plane # Avoid circular import
2640
+
2641
+ if isinstance(other, (tuple, list)):
2642
+ try:
2643
+ other = Point3D(other)
2644
+ except ValueError:
2645
+ pass
2646
+
2647
+ if isinstance(other, Point3D):
2648
+ return super().distance(other)
2649
+
2650
+ if isinstance(other, Line3D):
2651
+ if self == other:
2652
+ return S.Zero
2653
+ if self.is_parallel(other):
2654
+ return super().distance(other.p1)
2655
+
2656
+ # Skew lines
2657
+ self_direction = Matrix(self.direction_ratio)
2658
+ other_direction = Matrix(other.direction_ratio)
2659
+ normal = self_direction.cross(other_direction)
2660
+ plane_through_self = Plane(p1=self.p1, normal_vector=normal)
2661
+ return other.p1.distance(plane_through_self)
2662
+
2663
+ if isinstance(other, Plane):
2664
+ return other.distance(self)
2665
+
2666
+ msg = f"{other} has type {type(other)}, which is unsupported"
2667
+ raise NotImplementedError(msg)
2668
+
2669
+
2670
+ class Ray3D(LinearEntity3D, Ray):
2671
+ """
2672
+ A Ray is a semi-line in the space with a source point and a direction.
2673
+
2674
+ Parameters
2675
+ ==========
2676
+
2677
+ p1 : Point3D
2678
+ The source of the Ray
2679
+ p2 : Point or a direction vector
2680
+ direction_ratio: Determines the direction in which the Ray propagates.
2681
+
2682
+
2683
+ Attributes
2684
+ ==========
2685
+
2686
+ source
2687
+ xdirection
2688
+ ydirection
2689
+ zdirection
2690
+
2691
+ See Also
2692
+ ========
2693
+
2694
+ sympy.geometry.point.Point3D, Line3D
2695
+
2696
+
2697
+ Examples
2698
+ ========
2699
+
2700
+ >>> from sympy import Point3D, Ray3D
2701
+ >>> r = Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
2702
+ >>> r
2703
+ Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
2704
+ >>> r.points
2705
+ (Point3D(2, 3, 4), Point3D(3, 5, 0))
2706
+ >>> r.source
2707
+ Point3D(2, 3, 4)
2708
+ >>> r.xdirection
2709
+ oo
2710
+ >>> r.ydirection
2711
+ oo
2712
+ >>> r.direction_ratio
2713
+ [1, 2, -4]
2714
+
2715
+ """
2716
+ def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs):
2717
+ if isinstance(p1, LinearEntity3D):
2718
+ if pt is not None:
2719
+ raise ValueError('If p1 is a LinearEntity, pt must be None')
2720
+ p1, pt = p1.args
2721
+ else:
2722
+ p1 = Point(p1, dim=3)
2723
+ if pt is not None and len(direction_ratio) == 0:
2724
+ pt = Point(pt, dim=3)
2725
+ elif len(direction_ratio) == 3 and pt is None:
2726
+ pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1],
2727
+ p1.z + direction_ratio[2])
2728
+ else:
2729
+ raise ValueError(filldedent('''
2730
+ A 2nd Point or keyword "direction_ratio" must be used.
2731
+ '''))
2732
+
2733
+ return LinearEntity3D.__new__(cls, p1, pt, **kwargs)
2734
+
2735
+ @property
2736
+ def xdirection(self):
2737
+ """The x direction of the ray.
2738
+
2739
+ Positive infinity if the ray points in the positive x direction,
2740
+ negative infinity if the ray points in the negative x direction,
2741
+ or 0 if the ray is vertical.
2742
+
2743
+ See Also
2744
+ ========
2745
+
2746
+ ydirection
2747
+
2748
+ Examples
2749
+ ========
2750
+
2751
+ >>> from sympy import Point3D, Ray3D
2752
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, -1, 0)
2753
+ >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
2754
+ >>> r1.xdirection
2755
+ oo
2756
+ >>> r2.xdirection
2757
+ 0
2758
+
2759
+ """
2760
+ if self.p1.x < self.p2.x:
2761
+ return S.Infinity
2762
+ elif self.p1.x == self.p2.x:
2763
+ return S.Zero
2764
+ else:
2765
+ return S.NegativeInfinity
2766
+
2767
+ @property
2768
+ def ydirection(self):
2769
+ """The y direction of the ray.
2770
+
2771
+ Positive infinity if the ray points in the positive y direction,
2772
+ negative infinity if the ray points in the negative y direction,
2773
+ or 0 if the ray is horizontal.
2774
+
2775
+ See Also
2776
+ ========
2777
+
2778
+ xdirection
2779
+
2780
+ Examples
2781
+ ========
2782
+
2783
+ >>> from sympy import Point3D, Ray3D
2784
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
2785
+ >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
2786
+ >>> r1.ydirection
2787
+ -oo
2788
+ >>> r2.ydirection
2789
+ 0
2790
+
2791
+ """
2792
+ if self.p1.y < self.p2.y:
2793
+ return S.Infinity
2794
+ elif self.p1.y == self.p2.y:
2795
+ return S.Zero
2796
+ else:
2797
+ return S.NegativeInfinity
2798
+
2799
+ @property
2800
+ def zdirection(self):
2801
+ """The z direction of the ray.
2802
+
2803
+ Positive infinity if the ray points in the positive z direction,
2804
+ negative infinity if the ray points in the negative z direction,
2805
+ or 0 if the ray is horizontal.
2806
+
2807
+ See Also
2808
+ ========
2809
+
2810
+ xdirection
2811
+
2812
+ Examples
2813
+ ========
2814
+
2815
+ >>> from sympy import Point3D, Ray3D
2816
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
2817
+ >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
2818
+ >>> r1.ydirection
2819
+ -oo
2820
+ >>> r2.ydirection
2821
+ 0
2822
+ >>> r2.zdirection
2823
+ 0
2824
+
2825
+ """
2826
+ if self.p1.z < self.p2.z:
2827
+ return S.Infinity
2828
+ elif self.p1.z == self.p2.z:
2829
+ return S.Zero
2830
+ else:
2831
+ return S.NegativeInfinity
2832
+
2833
+
2834
+ class Segment3D(LinearEntity3D, Segment):
2835
+ """A line segment in a 3D space.
2836
+
2837
+ Parameters
2838
+ ==========
2839
+
2840
+ p1 : Point3D
2841
+ p2 : Point3D
2842
+
2843
+ Attributes
2844
+ ==========
2845
+
2846
+ length : number or SymPy expression
2847
+ midpoint : Point3D
2848
+
2849
+ See Also
2850
+ ========
2851
+
2852
+ sympy.geometry.point.Point3D, Line3D
2853
+
2854
+ Examples
2855
+ ========
2856
+
2857
+ >>> from sympy import Point3D, Segment3D
2858
+ >>> Segment3D((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
2859
+ Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
2860
+ >>> s = Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)); s
2861
+ Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
2862
+ >>> s.points
2863
+ (Point3D(4, 3, 9), Point3D(1, 1, 7))
2864
+ >>> s.length
2865
+ sqrt(17)
2866
+ >>> s.midpoint
2867
+ Point3D(5/2, 2, 8)
2868
+
2869
+ """
2870
+ def __new__(cls, p1, p2, **kwargs):
2871
+ p1 = Point(p1, dim=3)
2872
+ p2 = Point(p2, dim=3)
2873
+
2874
+ if p1 == p2:
2875
+ return p1
2876
+
2877
+ return LinearEntity3D.__new__(cls, p1, p2, **kwargs)
wemm/lib/python3.10/site-packages/sympy/geometry/parabola.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parabolic geometrical entity.
2
+
3
+ Contains
4
+ * Parabola
5
+
6
+ """
7
+
8
+ from sympy.core import S
9
+ from sympy.core.sorting import ordered
10
+ from sympy.core.symbol import _symbol, symbols
11
+ from sympy.geometry.entity import GeometryEntity, GeometrySet
12
+ from sympy.geometry.point import Point, Point2D
13
+ from sympy.geometry.line import Line, Line2D, Ray2D, Segment2D, LinearEntity3D
14
+ from sympy.geometry.ellipse import Ellipse
15
+ from sympy.functions import sign
16
+ from sympy.simplify import simplify
17
+ from sympy.solvers.solvers import solve
18
+
19
+
20
+ class Parabola(GeometrySet):
21
+ """A parabolic GeometryEntity.
22
+
23
+ A parabola is declared with a point, that is called 'focus', and
24
+ a line, that is called 'directrix'.
25
+ Only vertical or horizontal parabolas are currently supported.
26
+
27
+ Parameters
28
+ ==========
29
+
30
+ focus : Point
31
+ Default value is Point(0, 0)
32
+ directrix : Line
33
+
34
+ Attributes
35
+ ==========
36
+
37
+ focus
38
+ directrix
39
+ axis of symmetry
40
+ focal length
41
+ p parameter
42
+ vertex
43
+ eccentricity
44
+
45
+ Raises
46
+ ======
47
+ ValueError
48
+ When `focus` is not a two dimensional point.
49
+ When `focus` is a point of directrix.
50
+ NotImplementedError
51
+ When `directrix` is neither horizontal nor vertical.
52
+
53
+ Examples
54
+ ========
55
+
56
+ >>> from sympy import Parabola, Point, Line
57
+ >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7,8)))
58
+ >>> p1.focus
59
+ Point2D(0, 0)
60
+ >>> p1.directrix
61
+ Line2D(Point2D(5, 8), Point2D(7, 8))
62
+
63
+ """
64
+
65
+ def __new__(cls, focus=None, directrix=None, **kwargs):
66
+
67
+ if focus:
68
+ focus = Point(focus, dim=2)
69
+ else:
70
+ focus = Point(0, 0)
71
+
72
+ directrix = Line(directrix)
73
+
74
+ if directrix.contains(focus):
75
+ raise ValueError('The focus must not be a point of directrix')
76
+
77
+ return GeometryEntity.__new__(cls, focus, directrix, **kwargs)
78
+
79
+ @property
80
+ def ambient_dimension(self):
81
+ """Returns the ambient dimension of parabola.
82
+
83
+ Returns
84
+ =======
85
+
86
+ ambient_dimension : integer
87
+
88
+ Examples
89
+ ========
90
+
91
+ >>> from sympy import Parabola, Point, Line
92
+ >>> f1 = Point(0, 0)
93
+ >>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8)))
94
+ >>> p1.ambient_dimension
95
+ 2
96
+
97
+ """
98
+ return 2
99
+
100
+ @property
101
+ def axis_of_symmetry(self):
102
+ """Return the axis of symmetry of the parabola: a line
103
+ perpendicular to the directrix passing through the focus.
104
+
105
+ Returns
106
+ =======
107
+
108
+ axis_of_symmetry : Line
109
+
110
+ See Also
111
+ ========
112
+
113
+ sympy.geometry.line.Line
114
+
115
+ Examples
116
+ ========
117
+
118
+ >>> from sympy import Parabola, Point, Line
119
+ >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
120
+ >>> p1.axis_of_symmetry
121
+ Line2D(Point2D(0, 0), Point2D(0, 1))
122
+
123
+ """
124
+ return self.directrix.perpendicular_line(self.focus)
125
+
126
+ @property
127
+ def directrix(self):
128
+ """The directrix of the parabola.
129
+
130
+ Returns
131
+ =======
132
+
133
+ directrix : Line
134
+
135
+ See Also
136
+ ========
137
+
138
+ sympy.geometry.line.Line
139
+
140
+ Examples
141
+ ========
142
+
143
+ >>> from sympy import Parabola, Point, Line
144
+ >>> l1 = Line(Point(5, 8), Point(7, 8))
145
+ >>> p1 = Parabola(Point(0, 0), l1)
146
+ >>> p1.directrix
147
+ Line2D(Point2D(5, 8), Point2D(7, 8))
148
+
149
+ """
150
+ return self.args[1]
151
+
152
+ @property
153
+ def eccentricity(self):
154
+ """The eccentricity of the parabola.
155
+
156
+ Returns
157
+ =======
158
+
159
+ eccentricity : number
160
+
161
+ A parabola may also be characterized as a conic section with an
162
+ eccentricity of 1. As a consequence of this, all parabolas are
163
+ similar, meaning that while they can be different sizes,
164
+ they are all the same shape.
165
+
166
+ See Also
167
+ ========
168
+
169
+ https://en.wikipedia.org/wiki/Parabola
170
+
171
+
172
+ Examples
173
+ ========
174
+
175
+ >>> from sympy import Parabola, Point, Line
176
+ >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
177
+ >>> p1.eccentricity
178
+ 1
179
+
180
+ Notes
181
+ -----
182
+ The eccentricity for every Parabola is 1 by definition.
183
+
184
+ """
185
+ return S.One
186
+
187
+ def equation(self, x='x', y='y'):
188
+ """The equation of the parabola.
189
+
190
+ Parameters
191
+ ==========
192
+ x : str, optional
193
+ Label for the x-axis. Default value is 'x'.
194
+ y : str, optional
195
+ Label for the y-axis. Default value is 'y'.
196
+
197
+ Returns
198
+ =======
199
+ equation : SymPy expression
200
+
201
+ Examples
202
+ ========
203
+
204
+ >>> from sympy import Parabola, Point, Line
205
+ >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
206
+ >>> p1.equation()
207
+ -x**2 - 16*y + 64
208
+ >>> p1.equation('f')
209
+ -f**2 - 16*y + 64
210
+ >>> p1.equation(y='z')
211
+ -x**2 - 16*z + 64
212
+
213
+ """
214
+ x = _symbol(x, real=True)
215
+ y = _symbol(y, real=True)
216
+
217
+ m = self.directrix.slope
218
+ if m is S.Infinity:
219
+ t1 = 4 * (self.p_parameter) * (x - self.vertex.x)
220
+ t2 = (y - self.vertex.y)**2
221
+ elif m == 0:
222
+ t1 = 4 * (self.p_parameter) * (y - self.vertex.y)
223
+ t2 = (x - self.vertex.x)**2
224
+ else:
225
+ a, b = self.focus
226
+ c, d = self.directrix.coefficients[:2]
227
+ t1 = (x - a)**2 + (y - b)**2
228
+ t2 = self.directrix.equation(x, y)**2/(c**2 + d**2)
229
+ return t1 - t2
230
+
231
+ @property
232
+ def focal_length(self):
233
+ """The focal length of the parabola.
234
+
235
+ Returns
236
+ =======
237
+
238
+ focal_lenght : number or symbolic expression
239
+
240
+ Notes
241
+ =====
242
+
243
+ The distance between the vertex and the focus
244
+ (or the vertex and directrix), measured along the axis
245
+ of symmetry, is the "focal length".
246
+
247
+ See Also
248
+ ========
249
+
250
+ https://en.wikipedia.org/wiki/Parabola
251
+
252
+ Examples
253
+ ========
254
+
255
+ >>> from sympy import Parabola, Point, Line
256
+ >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
257
+ >>> p1.focal_length
258
+ 4
259
+
260
+ """
261
+ distance = self.directrix.distance(self.focus)
262
+ focal_length = distance/2
263
+
264
+ return focal_length
265
+
266
+ @property
267
+ def focus(self):
268
+ """The focus of the parabola.
269
+
270
+ Returns
271
+ =======
272
+
273
+ focus : Point
274
+
275
+ See Also
276
+ ========
277
+
278
+ sympy.geometry.point.Point
279
+
280
+ Examples
281
+ ========
282
+
283
+ >>> from sympy import Parabola, Point, Line
284
+ >>> f1 = Point(0, 0)
285
+ >>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8)))
286
+ >>> p1.focus
287
+ Point2D(0, 0)
288
+
289
+ """
290
+ return self.args[0]
291
+
292
+ def intersection(self, o):
293
+ """The intersection of the parabola and another geometrical entity `o`.
294
+
295
+ Parameters
296
+ ==========
297
+
298
+ o : GeometryEntity, LinearEntity
299
+
300
+ Returns
301
+ =======
302
+
303
+ intersection : list of GeometryEntity objects
304
+
305
+ Examples
306
+ ========
307
+
308
+ >>> from sympy import Parabola, Point, Ellipse, Line, Segment
309
+ >>> p1 = Point(0,0)
310
+ >>> l1 = Line(Point(1, -2), Point(-1,-2))
311
+ >>> parabola1 = Parabola(p1, l1)
312
+ >>> parabola1.intersection(Ellipse(Point(0, 0), 2, 5))
313
+ [Point2D(-2, 0), Point2D(2, 0)]
314
+ >>> parabola1.intersection(Line(Point(-7, 3), Point(12, 3)))
315
+ [Point2D(-4, 3), Point2D(4, 3)]
316
+ >>> parabola1.intersection(Segment((-12, -65), (14, -68)))
317
+ []
318
+
319
+ """
320
+ x, y = symbols('x y', real=True)
321
+ parabola_eq = self.equation()
322
+ if isinstance(o, Parabola):
323
+ if o in self:
324
+ return [o]
325
+ else:
326
+ return list(ordered([Point(i) for i in solve(
327
+ [parabola_eq, o.equation()], [x, y], set=True)[1]]))
328
+ elif isinstance(o, Point2D):
329
+ if simplify(parabola_eq.subs([(x, o._args[0]), (y, o._args[1])])) == 0:
330
+ return [o]
331
+ else:
332
+ return []
333
+ elif isinstance(o, (Segment2D, Ray2D)):
334
+ result = solve([parabola_eq,
335
+ Line2D(o.points[0], o.points[1]).equation()],
336
+ [x, y], set=True)[1]
337
+ return list(ordered([Point2D(i) for i in result if i in o]))
338
+ elif isinstance(o, (Line2D, Ellipse)):
339
+ return list(ordered([Point2D(i) for i in solve(
340
+ [parabola_eq, o.equation()], [x, y], set=True)[1]]))
341
+ elif isinstance(o, LinearEntity3D):
342
+ raise TypeError('Entity must be two dimensional, not three dimensional')
343
+ else:
344
+ raise TypeError('Wrong type of argument were put')
345
+
346
+ @property
347
+ def p_parameter(self):
348
+ """P is a parameter of parabola.
349
+
350
+ Returns
351
+ =======
352
+
353
+ p : number or symbolic expression
354
+
355
+ Notes
356
+ =====
357
+
358
+ The absolute value of p is the focal length. The sign on p tells
359
+ which way the parabola faces. Vertical parabolas that open up
360
+ and horizontal that open right, give a positive value for p.
361
+ Vertical parabolas that open down and horizontal that open left,
362
+ give a negative value for p.
363
+
364
+
365
+ See Also
366
+ ========
367
+
368
+ https://www.sparknotes.com/math/precalc/conicsections/section2/
369
+
370
+ Examples
371
+ ========
372
+
373
+ >>> from sympy import Parabola, Point, Line
374
+ >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
375
+ >>> p1.p_parameter
376
+ -4
377
+
378
+ """
379
+ m = self.directrix.slope
380
+ if m is S.Infinity:
381
+ x = self.directrix.coefficients[2]
382
+ p = sign(self.focus.args[0] + x)
383
+ elif m == 0:
384
+ y = self.directrix.coefficients[2]
385
+ p = sign(self.focus.args[1] + y)
386
+ else:
387
+ d = self.directrix.projection(self.focus)
388
+ p = sign(self.focus.x - d.x)
389
+ return p * self.focal_length
390
+
391
+ @property
392
+ def vertex(self):
393
+ """The vertex of the parabola.
394
+
395
+ Returns
396
+ =======
397
+
398
+ vertex : Point
399
+
400
+ See Also
401
+ ========
402
+
403
+ sympy.geometry.point.Point
404
+
405
+ Examples
406
+ ========
407
+
408
+ >>> from sympy import Parabola, Point, Line
409
+ >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
410
+ >>> p1.vertex
411
+ Point2D(0, 4)
412
+
413
+ """
414
+ focus = self.focus
415
+ m = self.directrix.slope
416
+ if m is S.Infinity:
417
+ vertex = Point(focus.args[0] - self.p_parameter, focus.args[1])
418
+ elif m == 0:
419
+ vertex = Point(focus.args[0], focus.args[1] - self.p_parameter)
420
+ else:
421
+ vertex = self.axis_of_symmetry.intersection(self)[0]
422
+ return vertex
wemm/lib/python3.10/site-packages/sympy/geometry/plane.py ADDED
@@ -0,0 +1,885 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Geometrical Planes.
2
+
3
+ Contains
4
+ ========
5
+ Plane
6
+
7
+ """
8
+
9
+ from sympy.core import Dummy, Rational, S, Symbol
10
+ from sympy.core.symbol import _symbol
11
+ from sympy.functions.elementary.trigonometric import cos, sin, acos, asin, sqrt
12
+ from .entity import GeometryEntity
13
+ from .line import (Line, Ray, Segment, Line3D, LinearEntity, LinearEntity3D,
14
+ Ray3D, Segment3D)
15
+ from .point import Point, Point3D
16
+ from sympy.matrices import Matrix
17
+ from sympy.polys.polytools import cancel
18
+ from sympy.solvers import solve, linsolve
19
+ from sympy.utilities.iterables import uniq, is_sequence
20
+ from sympy.utilities.misc import filldedent, func_name, Undecidable
21
+
22
+ from mpmath.libmp.libmpf import prec_to_dps
23
+
24
+ import random
25
+
26
+
27
+ x, y, z, t = [Dummy('plane_dummy') for i in range(4)]
28
+
29
+
30
+ class Plane(GeometryEntity):
31
+ """
32
+ A plane is a flat, two-dimensional surface. A plane is the two-dimensional
33
+ analogue of a point (zero-dimensions), a line (one-dimension) and a solid
34
+ (three-dimensions). A plane can generally be constructed by two types of
35
+ inputs. They are:
36
+ - three non-collinear points
37
+ - a point and the plane's normal vector
38
+
39
+ Attributes
40
+ ==========
41
+
42
+ p1
43
+ normal_vector
44
+
45
+ Examples
46
+ ========
47
+
48
+ >>> from sympy import Plane, Point3D
49
+ >>> Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
50
+ Plane(Point3D(1, 1, 1), (-1, 2, -1))
51
+ >>> Plane((1, 1, 1), (2, 3, 4), (2, 2, 2))
52
+ Plane(Point3D(1, 1, 1), (-1, 2, -1))
53
+ >>> Plane(Point3D(1, 1, 1), normal_vector=(1,4,7))
54
+ Plane(Point3D(1, 1, 1), (1, 4, 7))
55
+
56
+ """
57
+ def __new__(cls, p1, a=None, b=None, **kwargs):
58
+ p1 = Point3D(p1, dim=3)
59
+ if a and b:
60
+ p2 = Point(a, dim=3)
61
+ p3 = Point(b, dim=3)
62
+ if Point3D.are_collinear(p1, p2, p3):
63
+ raise ValueError('Enter three non-collinear points')
64
+ a = p1.direction_ratio(p2)
65
+ b = p1.direction_ratio(p3)
66
+ normal_vector = tuple(Matrix(a).cross(Matrix(b)))
67
+ else:
68
+ a = kwargs.pop('normal_vector', a)
69
+ evaluate = kwargs.get('evaluate', True)
70
+ if is_sequence(a) and len(a) == 3:
71
+ normal_vector = Point3D(a).args if evaluate else a
72
+ else:
73
+ raise ValueError(filldedent('''
74
+ Either provide 3 3D points or a point with a
75
+ normal vector expressed as a sequence of length 3'''))
76
+ if all(coord.is_zero for coord in normal_vector):
77
+ raise ValueError('Normal vector cannot be zero vector')
78
+ return GeometryEntity.__new__(cls, p1, normal_vector, **kwargs)
79
+
80
+ def __contains__(self, o):
81
+ k = self.equation(x, y, z)
82
+ if isinstance(o, (LinearEntity, LinearEntity3D)):
83
+ d = Point3D(o.arbitrary_point(t))
84
+ e = k.subs([(x, d.x), (y, d.y), (z, d.z)])
85
+ return e.equals(0)
86
+ try:
87
+ o = Point(o, dim=3, strict=True)
88
+ d = k.xreplace(dict(zip((x, y, z), o.args)))
89
+ return d.equals(0)
90
+ except TypeError:
91
+ return False
92
+
93
+ def _eval_evalf(self, prec=15, **options):
94
+ pt, tup = self.args
95
+ dps = prec_to_dps(prec)
96
+ pt = pt.evalf(n=dps, **options)
97
+ tup = tuple([i.evalf(n=dps, **options) for i in tup])
98
+ return self.func(pt, normal_vector=tup, evaluate=False)
99
+
100
+ def angle_between(self, o):
101
+ """Angle between the plane and other geometric entity.
102
+
103
+ Parameters
104
+ ==========
105
+
106
+ LinearEntity3D, Plane.
107
+
108
+ Returns
109
+ =======
110
+
111
+ angle : angle in radians
112
+
113
+ Notes
114
+ =====
115
+
116
+ This method accepts only 3D entities as it's parameter, but if you want
117
+ to calculate the angle between a 2D entity and a plane you should
118
+ first convert to a 3D entity by projecting onto a desired plane and
119
+ then proceed to calculate the angle.
120
+
121
+ Examples
122
+ ========
123
+
124
+ >>> from sympy import Point3D, Line3D, Plane
125
+ >>> a = Plane(Point3D(1, 2, 2), normal_vector=(1, 2, 3))
126
+ >>> b = Line3D(Point3D(1, 3, 4), Point3D(2, 2, 2))
127
+ >>> a.angle_between(b)
128
+ -asin(sqrt(21)/6)
129
+
130
+ """
131
+ if isinstance(o, LinearEntity3D):
132
+ a = Matrix(self.normal_vector)
133
+ b = Matrix(o.direction_ratio)
134
+ c = a.dot(b)
135
+ d = sqrt(sum(i**2 for i in self.normal_vector))
136
+ e = sqrt(sum(i**2 for i in o.direction_ratio))
137
+ return asin(c/(d*e))
138
+ if isinstance(o, Plane):
139
+ a = Matrix(self.normal_vector)
140
+ b = Matrix(o.normal_vector)
141
+ c = a.dot(b)
142
+ d = sqrt(sum(i**2 for i in self.normal_vector))
143
+ e = sqrt(sum(i**2 for i in o.normal_vector))
144
+ return acos(c/(d*e))
145
+
146
+
147
+ def arbitrary_point(self, u=None, v=None):
148
+ """ Returns an arbitrary point on the Plane. If given two
149
+ parameters, the point ranges over the entire plane. If given 1
150
+ or no parameters, returns a point with one parameter which,
151
+ when varying from 0 to 2*pi, moves the point in a circle of
152
+ radius 1 about p1 of the Plane.
153
+
154
+ Examples
155
+ ========
156
+
157
+ >>> from sympy import Plane, Ray
158
+ >>> from sympy.abc import u, v, t, r
159
+ >>> p = Plane((1, 1, 1), normal_vector=(1, 0, 0))
160
+ >>> p.arbitrary_point(u, v)
161
+ Point3D(1, u + 1, v + 1)
162
+ >>> p.arbitrary_point(t)
163
+ Point3D(1, cos(t) + 1, sin(t) + 1)
164
+
165
+ While arbitrary values of u and v can move the point anywhere in
166
+ the plane, the single-parameter point can be used to construct a
167
+ ray whose arbitrary point can be located at angle t and radius
168
+ r from p.p1:
169
+
170
+ >>> Ray(p.p1, _).arbitrary_point(r)
171
+ Point3D(1, r*cos(t) + 1, r*sin(t) + 1)
172
+
173
+ Returns
174
+ =======
175
+
176
+ Point3D
177
+
178
+ """
179
+ circle = v is None
180
+ if circle:
181
+ u = _symbol(u or 't', real=True)
182
+ else:
183
+ u = _symbol(u or 'u', real=True)
184
+ v = _symbol(v or 'v', real=True)
185
+ x, y, z = self.normal_vector
186
+ a, b, c = self.p1.args
187
+ # x1, y1, z1 is a nonzero vector parallel to the plane
188
+ if x.is_zero and y.is_zero:
189
+ x1, y1, z1 = S.One, S.Zero, S.Zero
190
+ else:
191
+ x1, y1, z1 = -y, x, S.Zero
192
+ # x2, y2, z2 is also parallel to the plane, and orthogonal to x1, y1, z1
193
+ x2, y2, z2 = tuple(Matrix((x, y, z)).cross(Matrix((x1, y1, z1))))
194
+ if circle:
195
+ x1, y1, z1 = (w/sqrt(x1**2 + y1**2 + z1**2) for w in (x1, y1, z1))
196
+ x2, y2, z2 = (w/sqrt(x2**2 + y2**2 + z2**2) for w in (x2, y2, z2))
197
+ p = Point3D(a + x1*cos(u) + x2*sin(u), \
198
+ b + y1*cos(u) + y2*sin(u), \
199
+ c + z1*cos(u) + z2*sin(u))
200
+ else:
201
+ p = Point3D(a + x1*u + x2*v, b + y1*u + y2*v, c + z1*u + z2*v)
202
+ return p
203
+
204
+
205
+ @staticmethod
206
+ def are_concurrent(*planes):
207
+ """Is a sequence of Planes concurrent?
208
+
209
+ Two or more Planes are concurrent if their intersections
210
+ are a common line.
211
+
212
+ Parameters
213
+ ==========
214
+
215
+ planes: list
216
+
217
+ Returns
218
+ =======
219
+
220
+ Boolean
221
+
222
+ Examples
223
+ ========
224
+
225
+ >>> from sympy import Plane, Point3D
226
+ >>> a = Plane(Point3D(5, 0, 0), normal_vector=(1, -1, 1))
227
+ >>> b = Plane(Point3D(0, -2, 0), normal_vector=(3, 1, 1))
228
+ >>> c = Plane(Point3D(0, -1, 0), normal_vector=(5, -1, 9))
229
+ >>> Plane.are_concurrent(a, b)
230
+ True
231
+ >>> Plane.are_concurrent(a, b, c)
232
+ False
233
+
234
+ """
235
+ planes = list(uniq(planes))
236
+ for i in planes:
237
+ if not isinstance(i, Plane):
238
+ raise ValueError('All objects should be Planes but got %s' % i.func)
239
+ if len(planes) < 2:
240
+ return False
241
+ planes = list(planes)
242
+ first = planes.pop(0)
243
+ sol = first.intersection(planes[0])
244
+ if sol == []:
245
+ return False
246
+ else:
247
+ line = sol[0]
248
+ for i in planes[1:]:
249
+ l = first.intersection(i)
250
+ if not l or l[0] not in line:
251
+ return False
252
+ return True
253
+
254
+
255
+ def distance(self, o):
256
+ """Distance between the plane and another geometric entity.
257
+
258
+ Parameters
259
+ ==========
260
+
261
+ Point3D, LinearEntity3D, Plane.
262
+
263
+ Returns
264
+ =======
265
+
266
+ distance
267
+
268
+ Notes
269
+ =====
270
+
271
+ This method accepts only 3D entities as it's parameter, but if you want
272
+ to calculate the distance between a 2D entity and a plane you should
273
+ first convert to a 3D entity by projecting onto a desired plane and
274
+ then proceed to calculate the distance.
275
+
276
+ Examples
277
+ ========
278
+
279
+ >>> from sympy import Point3D, Line3D, Plane
280
+ >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
281
+ >>> b = Point3D(1, 2, 3)
282
+ >>> a.distance(b)
283
+ sqrt(3)
284
+ >>> c = Line3D(Point3D(2, 3, 1), Point3D(1, 2, 2))
285
+ >>> a.distance(c)
286
+ 0
287
+
288
+ """
289
+ if self.intersection(o) != []:
290
+ return S.Zero
291
+
292
+ if isinstance(o, (Segment3D, Ray3D)):
293
+ a, b = o.p1, o.p2
294
+ pi, = self.intersection(Line3D(a, b))
295
+ if pi in o:
296
+ return self.distance(pi)
297
+ elif a in Segment3D(pi, b):
298
+ return self.distance(a)
299
+ else:
300
+ assert isinstance(o, Segment3D) is True
301
+ return self.distance(b)
302
+
303
+ # following code handles `Point3D`, `LinearEntity3D`, `Plane`
304
+ a = o if isinstance(o, Point3D) else o.p1
305
+ n = Point3D(self.normal_vector).unit
306
+ d = (a - self.p1).dot(n)
307
+ return abs(d)
308
+
309
+
310
+ def equals(self, o):
311
+ """
312
+ Returns True if self and o are the same mathematical entities.
313
+
314
+ Examples
315
+ ========
316
+
317
+ >>> from sympy import Plane, Point3D
318
+ >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
319
+ >>> b = Plane(Point3D(1, 2, 3), normal_vector=(2, 2, 2))
320
+ >>> c = Plane(Point3D(1, 2, 3), normal_vector=(-1, 4, 6))
321
+ >>> a.equals(a)
322
+ True
323
+ >>> a.equals(b)
324
+ True
325
+ >>> a.equals(c)
326
+ False
327
+ """
328
+ if isinstance(o, Plane):
329
+ a = self.equation()
330
+ b = o.equation()
331
+ return cancel(a/b).is_constant()
332
+ else:
333
+ return False
334
+
335
+
336
+ def equation(self, x=None, y=None, z=None):
337
+ """The equation of the Plane.
338
+
339
+ Examples
340
+ ========
341
+
342
+ >>> from sympy import Point3D, Plane
343
+ >>> a = Plane(Point3D(1, 1, 2), Point3D(2, 4, 7), Point3D(3, 5, 1))
344
+ >>> a.equation()
345
+ -23*x + 11*y - 2*z + 16
346
+ >>> a = Plane(Point3D(1, 4, 2), normal_vector=(6, 6, 6))
347
+ >>> a.equation()
348
+ 6*x + 6*y + 6*z - 42
349
+
350
+ """
351
+ x, y, z = [i if i else Symbol(j, real=True) for i, j in zip((x, y, z), 'xyz')]
352
+ a = Point3D(x, y, z)
353
+ b = self.p1.direction_ratio(a)
354
+ c = self.normal_vector
355
+ return (sum(i*j for i, j in zip(b, c)))
356
+
357
+
358
+ def intersection(self, o):
359
+ """ The intersection with other geometrical entity.
360
+
361
+ Parameters
362
+ ==========
363
+
364
+ Point, Point3D, LinearEntity, LinearEntity3D, Plane
365
+
366
+ Returns
367
+ =======
368
+
369
+ List
370
+
371
+ Examples
372
+ ========
373
+
374
+ >>> from sympy import Point3D, Line3D, Plane
375
+ >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
376
+ >>> b = Point3D(1, 2, 3)
377
+ >>> a.intersection(b)
378
+ [Point3D(1, 2, 3)]
379
+ >>> c = Line3D(Point3D(1, 4, 7), Point3D(2, 2, 2))
380
+ >>> a.intersection(c)
381
+ [Point3D(2, 2, 2)]
382
+ >>> d = Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3))
383
+ >>> e = Plane(Point3D(2, 0, 0), normal_vector=(3, 4, -3))
384
+ >>> d.intersection(e)
385
+ [Line3D(Point3D(78/23, -24/23, 0), Point3D(147/23, 321/23, 23))]
386
+
387
+ """
388
+ if not isinstance(o, GeometryEntity):
389
+ o = Point(o, dim=3)
390
+ if isinstance(o, Point):
391
+ if o in self:
392
+ return [o]
393
+ else:
394
+ return []
395
+ if isinstance(o, (LinearEntity, LinearEntity3D)):
396
+ # recast to 3D
397
+ p1, p2 = o.p1, o.p2
398
+ if isinstance(o, Segment):
399
+ o = Segment3D(p1, p2)
400
+ elif isinstance(o, Ray):
401
+ o = Ray3D(p1, p2)
402
+ elif isinstance(o, Line):
403
+ o = Line3D(p1, p2)
404
+ else:
405
+ raise ValueError('unhandled linear entity: %s' % o.func)
406
+ if o in self:
407
+ return [o]
408
+ else:
409
+ a = Point3D(o.arbitrary_point(t))
410
+ p1, n = self.p1, Point3D(self.normal_vector)
411
+
412
+ # TODO: Replace solve with solveset, when this line is tested
413
+ c = solve((a - p1).dot(n), t)
414
+ if not c:
415
+ return []
416
+ else:
417
+ c = [i for i in c if i.is_real is not False]
418
+ if len(c) > 1:
419
+ c = [i for i in c if i.is_real]
420
+ if len(c) != 1:
421
+ raise Undecidable("not sure which point is real")
422
+ p = a.subs(t, c[0])
423
+ if p not in o:
424
+ return [] # e.g. a segment might not intersect a plane
425
+ return [p]
426
+ if isinstance(o, Plane):
427
+ if self.equals(o):
428
+ return [self]
429
+ if self.is_parallel(o):
430
+ return []
431
+ else:
432
+ x, y, z = map(Dummy, 'xyz')
433
+ a, b = Matrix([self.normal_vector]), Matrix([o.normal_vector])
434
+ c = list(a.cross(b))
435
+ d = self.equation(x, y, z)
436
+ e = o.equation(x, y, z)
437
+ result = list(linsolve([d, e], x, y, z))[0]
438
+ for i in (x, y, z): result = result.subs(i, 0)
439
+ return [Line3D(Point3D(result), direction_ratio=c)]
440
+
441
+
442
+ def is_coplanar(self, o):
443
+ """ Returns True if `o` is coplanar with self, else False.
444
+
445
+ Examples
446
+ ========
447
+
448
+ >>> from sympy import Plane
449
+ >>> o = (0, 0, 0)
450
+ >>> p = Plane(o, (1, 1, 1))
451
+ >>> p2 = Plane(o, (2, 2, 2))
452
+ >>> p == p2
453
+ False
454
+ >>> p.is_coplanar(p2)
455
+ True
456
+ """
457
+ if isinstance(o, Plane):
458
+ return not cancel(self.equation(x, y, z)/o.equation(x, y, z)).has(x, y, z)
459
+ if isinstance(o, Point3D):
460
+ return o in self
461
+ elif isinstance(o, LinearEntity3D):
462
+ return all(i in self for i in self)
463
+ elif isinstance(o, GeometryEntity): # XXX should only be handling 2D objects now
464
+ return all(i == 0 for i in self.normal_vector[:2])
465
+
466
+
467
+ def is_parallel(self, l):
468
+ """Is the given geometric entity parallel to the plane?
469
+
470
+ Parameters
471
+ ==========
472
+
473
+ LinearEntity3D or Plane
474
+
475
+ Returns
476
+ =======
477
+
478
+ Boolean
479
+
480
+ Examples
481
+ ========
482
+
483
+ >>> from sympy import Plane, Point3D
484
+ >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
485
+ >>> b = Plane(Point3D(3,1,3), normal_vector=(4, 8, 12))
486
+ >>> a.is_parallel(b)
487
+ True
488
+
489
+ """
490
+ if isinstance(l, LinearEntity3D):
491
+ a = l.direction_ratio
492
+ b = self.normal_vector
493
+ c = sum(i*j for i, j in zip(a, b))
494
+ if c == 0:
495
+ return True
496
+ else:
497
+ return False
498
+ elif isinstance(l, Plane):
499
+ a = Matrix(l.normal_vector)
500
+ b = Matrix(self.normal_vector)
501
+ if a.cross(b).is_zero_matrix:
502
+ return True
503
+ else:
504
+ return False
505
+
506
+
507
+ def is_perpendicular(self, l):
508
+ """Is the given geometric entity perpendicualar to the given plane?
509
+
510
+ Parameters
511
+ ==========
512
+
513
+ LinearEntity3D or Plane
514
+
515
+ Returns
516
+ =======
517
+
518
+ Boolean
519
+
520
+ Examples
521
+ ========
522
+
523
+ >>> from sympy import Plane, Point3D
524
+ >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
525
+ >>> b = Plane(Point3D(2, 2, 2), normal_vector=(-1, 2, -1))
526
+ >>> a.is_perpendicular(b)
527
+ True
528
+
529
+ """
530
+ if isinstance(l, LinearEntity3D):
531
+ a = Matrix(l.direction_ratio)
532
+ b = Matrix(self.normal_vector)
533
+ if a.cross(b).is_zero_matrix:
534
+ return True
535
+ else:
536
+ return False
537
+ elif isinstance(l, Plane):
538
+ a = Matrix(l.normal_vector)
539
+ b = Matrix(self.normal_vector)
540
+ if a.dot(b) == 0:
541
+ return True
542
+ else:
543
+ return False
544
+ else:
545
+ return False
546
+
547
+ @property
548
+ def normal_vector(self):
549
+ """Normal vector of the given plane.
550
+
551
+ Examples
552
+ ========
553
+
554
+ >>> from sympy import Point3D, Plane
555
+ >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
556
+ >>> a.normal_vector
557
+ (-1, 2, -1)
558
+ >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 4, 7))
559
+ >>> a.normal_vector
560
+ (1, 4, 7)
561
+
562
+ """
563
+ return self.args[1]
564
+
565
+ @property
566
+ def p1(self):
567
+ """The only defining point of the plane. Others can be obtained from the
568
+ arbitrary_point method.
569
+
570
+ See Also
571
+ ========
572
+
573
+ sympy.geometry.point.Point3D
574
+
575
+ Examples
576
+ ========
577
+
578
+ >>> from sympy import Point3D, Plane
579
+ >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
580
+ >>> a.p1
581
+ Point3D(1, 1, 1)
582
+
583
+ """
584
+ return self.args[0]
585
+
586
+ def parallel_plane(self, pt):
587
+ """
588
+ Plane parallel to the given plane and passing through the point pt.
589
+
590
+ Parameters
591
+ ==========
592
+
593
+ pt: Point3D
594
+
595
+ Returns
596
+ =======
597
+
598
+ Plane
599
+
600
+ Examples
601
+ ========
602
+
603
+ >>> from sympy import Plane, Point3D
604
+ >>> a = Plane(Point3D(1, 4, 6), normal_vector=(2, 4, 6))
605
+ >>> a.parallel_plane(Point3D(2, 3, 5))
606
+ Plane(Point3D(2, 3, 5), (2, 4, 6))
607
+
608
+ """
609
+ a = self.normal_vector
610
+ return Plane(pt, normal_vector=a)
611
+
612
+ def perpendicular_line(self, pt):
613
+ """A line perpendicular to the given plane.
614
+
615
+ Parameters
616
+ ==========
617
+
618
+ pt: Point3D
619
+
620
+ Returns
621
+ =======
622
+
623
+ Line3D
624
+
625
+ Examples
626
+ ========
627
+
628
+ >>> from sympy import Plane, Point3D
629
+ >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
630
+ >>> a.perpendicular_line(Point3D(9, 8, 7))
631
+ Line3D(Point3D(9, 8, 7), Point3D(11, 12, 13))
632
+
633
+ """
634
+ a = self.normal_vector
635
+ return Line3D(pt, direction_ratio=a)
636
+
637
+ def perpendicular_plane(self, *pts):
638
+ """
639
+ Return a perpendicular passing through the given points. If the
640
+ direction ratio between the points is the same as the Plane's normal
641
+ vector then, to select from the infinite number of possible planes,
642
+ a third point will be chosen on the z-axis (or the y-axis
643
+ if the normal vector is already parallel to the z-axis). If less than
644
+ two points are given they will be supplied as follows: if no point is
645
+ given then pt1 will be self.p1; if a second point is not given it will
646
+ be a point through pt1 on a line parallel to the z-axis (if the normal
647
+ is not already the z-axis, otherwise on the line parallel to the
648
+ y-axis).
649
+
650
+ Parameters
651
+ ==========
652
+
653
+ pts: 0, 1 or 2 Point3D
654
+
655
+ Returns
656
+ =======
657
+
658
+ Plane
659
+
660
+ Examples
661
+ ========
662
+
663
+ >>> from sympy import Plane, Point3D
664
+ >>> a, b = Point3D(0, 0, 0), Point3D(0, 1, 0)
665
+ >>> Z = (0, 0, 1)
666
+ >>> p = Plane(a, normal_vector=Z)
667
+ >>> p.perpendicular_plane(a, b)
668
+ Plane(Point3D(0, 0, 0), (1, 0, 0))
669
+ """
670
+ if len(pts) > 2:
671
+ raise ValueError('No more than 2 pts should be provided.')
672
+
673
+ pts = list(pts)
674
+ if len(pts) == 0:
675
+ pts.append(self.p1)
676
+ if len(pts) == 1:
677
+ x, y, z = self.normal_vector
678
+ if x == y == 0:
679
+ dir = (0, 1, 0)
680
+ else:
681
+ dir = (0, 0, 1)
682
+ pts.append(pts[0] + Point3D(*dir))
683
+
684
+ p1, p2 = [Point(i, dim=3) for i in pts]
685
+ l = Line3D(p1, p2)
686
+ n = Line3D(p1, direction_ratio=self.normal_vector)
687
+ if l in n: # XXX should an error be raised instead?
688
+ # there are infinitely many perpendicular planes;
689
+ x, y, z = self.normal_vector
690
+ if x == y == 0:
691
+ # the z axis is the normal so pick a pt on the y-axis
692
+ p3 = Point3D(0, 1, 0) # case 1
693
+ else:
694
+ # else pick a pt on the z axis
695
+ p3 = Point3D(0, 0, 1) # case 2
696
+ # in case that point is already given, move it a bit
697
+ if p3 in l:
698
+ p3 *= 2 # case 3
699
+ else:
700
+ p3 = p1 + Point3D(*self.normal_vector) # case 4
701
+ return Plane(p1, p2, p3)
702
+
703
+ def projection_line(self, line):
704
+ """Project the given line onto the plane through the normal plane
705
+ containing the line.
706
+
707
+ Parameters
708
+ ==========
709
+
710
+ LinearEntity or LinearEntity3D
711
+
712
+ Returns
713
+ =======
714
+
715
+ Point3D, Line3D, Ray3D or Segment3D
716
+
717
+ Notes
718
+ =====
719
+
720
+ For the interaction between 2D and 3D lines(segments, rays), you should
721
+ convert the line to 3D by using this method. For example for finding the
722
+ intersection between a 2D and a 3D line, convert the 2D line to a 3D line
723
+ by projecting it on a required plane and then proceed to find the
724
+ intersection between those lines.
725
+
726
+ Examples
727
+ ========
728
+
729
+ >>> from sympy import Plane, Line, Line3D, Point3D
730
+ >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
731
+ >>> b = Line(Point3D(1, 1), Point3D(2, 2))
732
+ >>> a.projection_line(b)
733
+ Line3D(Point3D(4/3, 4/3, 1/3), Point3D(5/3, 5/3, -1/3))
734
+ >>> c = Line3D(Point3D(1, 1, 1), Point3D(2, 2, 2))
735
+ >>> a.projection_line(c)
736
+ Point3D(1, 1, 1)
737
+
738
+ """
739
+ if not isinstance(line, (LinearEntity, LinearEntity3D)):
740
+ raise NotImplementedError('Enter a linear entity only')
741
+ a, b = self.projection(line.p1), self.projection(line.p2)
742
+ if a == b:
743
+ # projection does not imply intersection so for
744
+ # this case (line parallel to plane's normal) we
745
+ # return the projection point
746
+ return a
747
+ if isinstance(line, (Line, Line3D)):
748
+ return Line3D(a, b)
749
+ if isinstance(line, (Ray, Ray3D)):
750
+ return Ray3D(a, b)
751
+ if isinstance(line, (Segment, Segment3D)):
752
+ return Segment3D(a, b)
753
+
754
+ def projection(self, pt):
755
+ """Project the given point onto the plane along the plane normal.
756
+
757
+ Parameters
758
+ ==========
759
+
760
+ Point or Point3D
761
+
762
+ Returns
763
+ =======
764
+
765
+ Point3D
766
+
767
+ Examples
768
+ ========
769
+
770
+ >>> from sympy import Plane, Point3D
771
+ >>> A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1))
772
+
773
+ The projection is along the normal vector direction, not the z
774
+ axis, so (1, 1) does not project to (1, 1, 2) on the plane A:
775
+
776
+ >>> b = Point3D(1, 1)
777
+ >>> A.projection(b)
778
+ Point3D(5/3, 5/3, 2/3)
779
+ >>> _ in A
780
+ True
781
+
782
+ But the point (1, 1, 2) projects to (1, 1) on the XY-plane:
783
+
784
+ >>> XY = Plane((0, 0, 0), (0, 0, 1))
785
+ >>> XY.projection((1, 1, 2))
786
+ Point3D(1, 1, 0)
787
+ """
788
+ rv = Point(pt, dim=3)
789
+ if rv in self:
790
+ return rv
791
+ return self.intersection(Line3D(rv, rv + Point3D(self.normal_vector)))[0]
792
+
793
+ def random_point(self, seed=None):
794
+ """ Returns a random point on the Plane.
795
+
796
+ Returns
797
+ =======
798
+
799
+ Point3D
800
+
801
+ Examples
802
+ ========
803
+
804
+ >>> from sympy import Plane
805
+ >>> p = Plane((1, 0, 0), normal_vector=(0, 1, 0))
806
+ >>> r = p.random_point(seed=42) # seed value is optional
807
+ >>> r.n(3)
808
+ Point3D(2.29, 0, -1.35)
809
+
810
+ The random point can be moved to lie on the circle of radius
811
+ 1 centered on p1:
812
+
813
+ >>> c = p.p1 + (r - p.p1).unit
814
+ >>> c.distance(p.p1).equals(1)
815
+ True
816
+ """
817
+ if seed is not None:
818
+ rng = random.Random(seed)
819
+ else:
820
+ rng = random
821
+ params = {
822
+ x: 2*Rational(rng.gauss(0, 1)) - 1,
823
+ y: 2*Rational(rng.gauss(0, 1)) - 1}
824
+ return self.arbitrary_point(x, y).subs(params)
825
+
826
+ def parameter_value(self, other, u, v=None):
827
+ """Return the parameter(s) corresponding to the given point.
828
+
829
+ Examples
830
+ ========
831
+
832
+ >>> from sympy import pi, Plane
833
+ >>> from sympy.abc import t, u, v
834
+ >>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0))
835
+
836
+ By default, the parameter value returned defines a point
837
+ that is a distance of 1 from the Plane's p1 value and
838
+ in line with the given point:
839
+
840
+ >>> on_circle = p.arbitrary_point(t).subs(t, pi/4)
841
+ >>> on_circle.distance(p.p1)
842
+ 1
843
+ >>> p.parameter_value(on_circle, t)
844
+ {t: pi/4}
845
+
846
+ Moving the point twice as far from p1 does not change
847
+ the parameter value:
848
+
849
+ >>> off_circle = p.p1 + (on_circle - p.p1)*2
850
+ >>> off_circle.distance(p.p1)
851
+ 2
852
+ >>> p.parameter_value(off_circle, t)
853
+ {t: pi/4}
854
+
855
+ If the 2-value parameter is desired, supply the two
856
+ parameter symbols and a replacement dictionary will
857
+ be returned:
858
+
859
+ >>> p.parameter_value(on_circle, u, v)
860
+ {u: sqrt(10)/10, v: sqrt(10)/30}
861
+ >>> p.parameter_value(off_circle, u, v)
862
+ {u: sqrt(10)/5, v: sqrt(10)/15}
863
+ """
864
+ if not isinstance(other, GeometryEntity):
865
+ other = Point(other, dim=self.ambient_dimension)
866
+ if not isinstance(other, Point):
867
+ raise ValueError("other must be a point")
868
+ if other == self.p1:
869
+ return other
870
+ if isinstance(u, Symbol) and v is None:
871
+ delta = self.arbitrary_point(u) - self.p1
872
+ eq = delta - (other - self.p1).unit
873
+ sol = solve(eq, u, dict=True)
874
+ elif isinstance(u, Symbol) and isinstance(v, Symbol):
875
+ pt = self.arbitrary_point(u, v)
876
+ sol = solve(pt - other, (u, v), dict=True)
877
+ else:
878
+ raise ValueError('expecting 1 or 2 symbols')
879
+ if not sol:
880
+ raise ValueError("Given point is not on %s" % func_name(self))
881
+ return sol[0] # {t: tval} or {u: uval, v: vval}
882
+
883
+ @property
884
+ def ambient_dimension(self):
885
+ return self.p1.ambient_dimension
wemm/lib/python3.10/site-packages/sympy/geometry/point.py ADDED
@@ -0,0 +1,1378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Geometrical Points.
2
+
3
+ Contains
4
+ ========
5
+ Point
6
+ Point2D
7
+ Point3D
8
+
9
+ When methods of Point require 1 or more points as arguments, they
10
+ can be passed as a sequence of coordinates or Points:
11
+
12
+ >>> from sympy import Point
13
+ >>> Point(1, 1).is_collinear((2, 2), (3, 4))
14
+ False
15
+ >>> Point(1, 1).is_collinear(Point(2, 2), Point(3, 4))
16
+ False
17
+
18
+ """
19
+
20
+ import warnings
21
+
22
+ from sympy.core import S, sympify, Expr
23
+ from sympy.core.add import Add
24
+ from sympy.core.containers import Tuple
25
+ from sympy.core.numbers import Float
26
+ from sympy.core.parameters import global_parameters
27
+ from sympy.simplify import nsimplify, simplify
28
+ from sympy.geometry.exceptions import GeometryError
29
+ from sympy.functions.elementary.miscellaneous import sqrt
30
+ from sympy.functions.elementary.complexes import im
31
+ from sympy.functions.elementary.trigonometric import cos, sin
32
+ from sympy.matrices import Matrix
33
+ from sympy.matrices.expressions import Transpose
34
+ from sympy.utilities.iterables import uniq, is_sequence
35
+ from sympy.utilities.misc import filldedent, func_name, Undecidable
36
+
37
+ from .entity import GeometryEntity
38
+
39
+ from mpmath.libmp.libmpf import prec_to_dps
40
+
41
+
42
+ class Point(GeometryEntity):
43
+ """A point in a n-dimensional Euclidean space.
44
+
45
+ Parameters
46
+ ==========
47
+
48
+ coords : sequence of n-coordinate values. In the special
49
+ case where n=2 or 3, a Point2D or Point3D will be created
50
+ as appropriate.
51
+ evaluate : if `True` (default), all floats are turn into
52
+ exact types.
53
+ dim : number of coordinates the point should have. If coordinates
54
+ are unspecified, they are padded with zeros.
55
+ on_morph : indicates what should happen when the number of
56
+ coordinates of a point need to be changed by adding or
57
+ removing zeros. Possible values are `'warn'`, `'error'`, or
58
+ `ignore` (default). No warning or error is given when `*args`
59
+ is empty and `dim` is given. An error is always raised when
60
+ trying to remove nonzero coordinates.
61
+
62
+
63
+ Attributes
64
+ ==========
65
+
66
+ length
67
+ origin: A `Point` representing the origin of the
68
+ appropriately-dimensioned space.
69
+
70
+ Raises
71
+ ======
72
+
73
+ TypeError : When instantiating with anything but a Point or sequence
74
+ ValueError : when instantiating with a sequence with length < 2 or
75
+ when trying to reduce dimensions if keyword `on_morph='error'` is
76
+ set.
77
+
78
+ See Also
79
+ ========
80
+
81
+ sympy.geometry.line.Segment : Connects two Points
82
+
83
+ Examples
84
+ ========
85
+
86
+ >>> from sympy import Point
87
+ >>> from sympy.abc import x
88
+ >>> Point(1, 2, 3)
89
+ Point3D(1, 2, 3)
90
+ >>> Point([1, 2])
91
+ Point2D(1, 2)
92
+ >>> Point(0, x)
93
+ Point2D(0, x)
94
+ >>> Point(dim=4)
95
+ Point(0, 0, 0, 0)
96
+
97
+ Floats are automatically converted to Rational unless the
98
+ evaluate flag is False:
99
+
100
+ >>> Point(0.5, 0.25)
101
+ Point2D(1/2, 1/4)
102
+ >>> Point(0.5, 0.25, evaluate=False)
103
+ Point2D(0.5, 0.25)
104
+
105
+ """
106
+
107
+ is_Point = True
108
+
109
+ def __new__(cls, *args, **kwargs):
110
+ evaluate = kwargs.get('evaluate', global_parameters.evaluate)
111
+ on_morph = kwargs.get('on_morph', 'ignore')
112
+
113
+ # unpack into coords
114
+ coords = args[0] if len(args) == 1 else args
115
+
116
+ # check args and handle quickly handle Point instances
117
+ if isinstance(coords, Point):
118
+ # even if we're mutating the dimension of a point, we
119
+ # don't reevaluate its coordinates
120
+ evaluate = False
121
+ if len(coords) == kwargs.get('dim', len(coords)):
122
+ return coords
123
+
124
+ if not is_sequence(coords):
125
+ raise TypeError(filldedent('''
126
+ Expecting sequence of coordinates, not `{}`'''
127
+ .format(func_name(coords))))
128
+ # A point where only `dim` is specified is initialized
129
+ # to zeros.
130
+ if len(coords) == 0 and kwargs.get('dim', None):
131
+ coords = (S.Zero,)*kwargs.get('dim')
132
+
133
+ coords = Tuple(*coords)
134
+ dim = kwargs.get('dim', len(coords))
135
+
136
+ if len(coords) < 2:
137
+ raise ValueError(filldedent('''
138
+ Point requires 2 or more coordinates or
139
+ keyword `dim` > 1.'''))
140
+ if len(coords) != dim:
141
+ message = ("Dimension of {} needs to be changed "
142
+ "from {} to {}.").format(coords, len(coords), dim)
143
+ if on_morph == 'ignore':
144
+ pass
145
+ elif on_morph == "error":
146
+ raise ValueError(message)
147
+ elif on_morph == 'warn':
148
+ warnings.warn(message, stacklevel=2)
149
+ else:
150
+ raise ValueError(filldedent('''
151
+ on_morph value should be 'error',
152
+ 'warn' or 'ignore'.'''))
153
+ if any(coords[dim:]):
154
+ raise ValueError('Nonzero coordinates cannot be removed.')
155
+ if any(a.is_number and im(a).is_zero is False for a in coords):
156
+ raise ValueError('Imaginary coordinates are not permitted.')
157
+ if not all(isinstance(a, Expr) for a in coords):
158
+ raise TypeError('Coordinates must be valid SymPy expressions.')
159
+
160
+ # pad with zeros appropriately
161
+ coords = coords[:dim] + (S.Zero,)*(dim - len(coords))
162
+
163
+ # Turn any Floats into rationals and simplify
164
+ # any expressions before we instantiate
165
+ if evaluate:
166
+ coords = coords.xreplace({
167
+ f: simplify(nsimplify(f, rational=True))
168
+ for f in coords.atoms(Float)})
169
+
170
+ # return 2D or 3D instances
171
+ if len(coords) == 2:
172
+ kwargs['_nocheck'] = True
173
+ return Point2D(*coords, **kwargs)
174
+ elif len(coords) == 3:
175
+ kwargs['_nocheck'] = True
176
+ return Point3D(*coords, **kwargs)
177
+
178
+ # the general Point
179
+ return GeometryEntity.__new__(cls, *coords)
180
+
181
+ def __abs__(self):
182
+ """Returns the distance between this point and the origin."""
183
+ origin = Point([0]*len(self))
184
+ return Point.distance(origin, self)
185
+
186
+ def __add__(self, other):
187
+ """Add other to self by incrementing self's coordinates by
188
+ those of other.
189
+
190
+ Notes
191
+ =====
192
+
193
+ >>> from sympy import Point
194
+
195
+ When sequences of coordinates are passed to Point methods, they
196
+ are converted to a Point internally. This __add__ method does
197
+ not do that so if floating point values are used, a floating
198
+ point result (in terms of SymPy Floats) will be returned.
199
+
200
+ >>> Point(1, 2) + (.1, .2)
201
+ Point2D(1.1, 2.2)
202
+
203
+ If this is not desired, the `translate` method can be used or
204
+ another Point can be added:
205
+
206
+ >>> Point(1, 2).translate(.1, .2)
207
+ Point2D(11/10, 11/5)
208
+ >>> Point(1, 2) + Point(.1, .2)
209
+ Point2D(11/10, 11/5)
210
+
211
+ See Also
212
+ ========
213
+
214
+ sympy.geometry.point.Point.translate
215
+
216
+ """
217
+ try:
218
+ s, o = Point._normalize_dimension(self, Point(other, evaluate=False))
219
+ except TypeError:
220
+ raise GeometryError("Don't know how to add {} and a Point object".format(other))
221
+
222
+ coords = [simplify(a + b) for a, b in zip(s, o)]
223
+ return Point(coords, evaluate=False)
224
+
225
+ def __contains__(self, item):
226
+ return item in self.args
227
+
228
+ def __truediv__(self, divisor):
229
+ """Divide point's coordinates by a factor."""
230
+ divisor = sympify(divisor)
231
+ coords = [simplify(x/divisor) for x in self.args]
232
+ return Point(coords, evaluate=False)
233
+
234
+ def __eq__(self, other):
235
+ if not isinstance(other, Point) or len(self.args) != len(other.args):
236
+ return False
237
+ return self.args == other.args
238
+
239
+ def __getitem__(self, key):
240
+ return self.args[key]
241
+
242
+ def __hash__(self):
243
+ return hash(self.args)
244
+
245
+ def __iter__(self):
246
+ return self.args.__iter__()
247
+
248
+ def __len__(self):
249
+ return len(self.args)
250
+
251
+ def __mul__(self, factor):
252
+ """Multiply point's coordinates by a factor.
253
+
254
+ Notes
255
+ =====
256
+
257
+ >>> from sympy import Point
258
+
259
+ When multiplying a Point by a floating point number,
260
+ the coordinates of the Point will be changed to Floats:
261
+
262
+ >>> Point(1, 2)*0.1
263
+ Point2D(0.1, 0.2)
264
+
265
+ If this is not desired, the `scale` method can be used or
266
+ else only multiply or divide by integers:
267
+
268
+ >>> Point(1, 2).scale(1.1, 1.1)
269
+ Point2D(11/10, 11/5)
270
+ >>> Point(1, 2)*11/10
271
+ Point2D(11/10, 11/5)
272
+
273
+ See Also
274
+ ========
275
+
276
+ sympy.geometry.point.Point.scale
277
+ """
278
+ factor = sympify(factor)
279
+ coords = [simplify(x*factor) for x in self.args]
280
+ return Point(coords, evaluate=False)
281
+
282
+ def __rmul__(self, factor):
283
+ """Multiply a factor by point's coordinates."""
284
+ return self.__mul__(factor)
285
+
286
+ def __neg__(self):
287
+ """Negate the point."""
288
+ coords = [-x for x in self.args]
289
+ return Point(coords, evaluate=False)
290
+
291
+ def __sub__(self, other):
292
+ """Subtract two points, or subtract a factor from this point's
293
+ coordinates."""
294
+ return self + [-x for x in other]
295
+
296
+ @classmethod
297
+ def _normalize_dimension(cls, *points, **kwargs):
298
+ """Ensure that points have the same dimension.
299
+ By default `on_morph='warn'` is passed to the
300
+ `Point` constructor."""
301
+ # if we have a built-in ambient dimension, use it
302
+ dim = getattr(cls, '_ambient_dimension', None)
303
+ # override if we specified it
304
+ dim = kwargs.get('dim', dim)
305
+ # if no dim was given, use the highest dimensional point
306
+ if dim is None:
307
+ dim = max(i.ambient_dimension for i in points)
308
+ if all(i.ambient_dimension == dim for i in points):
309
+ return list(points)
310
+ kwargs['dim'] = dim
311
+ kwargs['on_morph'] = kwargs.get('on_morph', 'warn')
312
+ return [Point(i, **kwargs) for i in points]
313
+
314
+ @staticmethod
315
+ def affine_rank(*args):
316
+ """The affine rank of a set of points is the dimension
317
+ of the smallest affine space containing all the points.
318
+ For example, if the points lie on a line (and are not all
319
+ the same) their affine rank is 1. If the points lie on a plane
320
+ but not a line, their affine rank is 2. By convention, the empty
321
+ set has affine rank -1."""
322
+
323
+ if len(args) == 0:
324
+ return -1
325
+ # make sure we're genuinely points
326
+ # and translate every point to the origin
327
+ points = Point._normalize_dimension(*[Point(i) for i in args])
328
+ origin = points[0]
329
+ points = [i - origin for i in points[1:]]
330
+
331
+ m = Matrix([i.args for i in points])
332
+ # XXX fragile -- what is a better way?
333
+ return m.rank(iszerofunc = lambda x:
334
+ abs(x.n(2)) < 1e-12 if x.is_number else x.is_zero)
335
+
336
+ @property
337
+ def ambient_dimension(self):
338
+ """Number of components this point has."""
339
+ return getattr(self, '_ambient_dimension', len(self))
340
+
341
+ @classmethod
342
+ def are_coplanar(cls, *points):
343
+ """Return True if there exists a plane in which all the points
344
+ lie. A trivial True value is returned if `len(points) < 3` or
345
+ all Points are 2-dimensional.
346
+
347
+ Parameters
348
+ ==========
349
+
350
+ A set of points
351
+
352
+ Raises
353
+ ======
354
+
355
+ ValueError : if less than 3 unique points are given
356
+
357
+ Returns
358
+ =======
359
+
360
+ boolean
361
+
362
+ Examples
363
+ ========
364
+
365
+ >>> from sympy import Point3D
366
+ >>> p1 = Point3D(1, 2, 2)
367
+ >>> p2 = Point3D(2, 7, 2)
368
+ >>> p3 = Point3D(0, 0, 2)
369
+ >>> p4 = Point3D(1, 1, 2)
370
+ >>> Point3D.are_coplanar(p1, p2, p3, p4)
371
+ True
372
+ >>> p5 = Point3D(0, 1, 3)
373
+ >>> Point3D.are_coplanar(p1, p2, p3, p5)
374
+ False
375
+
376
+ """
377
+ if len(points) <= 1:
378
+ return True
379
+
380
+ points = cls._normalize_dimension(*[Point(i) for i in points])
381
+ # quick exit if we are in 2D
382
+ if points[0].ambient_dimension == 2:
383
+ return True
384
+ points = list(uniq(points))
385
+ return Point.affine_rank(*points) <= 2
386
+
387
+ def distance(self, other):
388
+ """The Euclidean distance between self and another GeometricEntity.
389
+
390
+ Returns
391
+ =======
392
+
393
+ distance : number or symbolic expression.
394
+
395
+ Raises
396
+ ======
397
+
398
+ TypeError : if other is not recognized as a GeometricEntity or is a
399
+ GeometricEntity for which distance is not defined.
400
+
401
+ See Also
402
+ ========
403
+
404
+ sympy.geometry.line.Segment.length
405
+ sympy.geometry.point.Point.taxicab_distance
406
+
407
+ Examples
408
+ ========
409
+
410
+ >>> from sympy import Point, Line
411
+ >>> p1, p2 = Point(1, 1), Point(4, 5)
412
+ >>> l = Line((3, 1), (2, 2))
413
+ >>> p1.distance(p2)
414
+ 5
415
+ >>> p1.distance(l)
416
+ sqrt(2)
417
+
418
+ The computed distance may be symbolic, too:
419
+
420
+ >>> from sympy.abc import x, y
421
+ >>> p3 = Point(x, y)
422
+ >>> p3.distance((0, 0))
423
+ sqrt(x**2 + y**2)
424
+
425
+ """
426
+ if not isinstance(other, GeometryEntity):
427
+ try:
428
+ other = Point(other, dim=self.ambient_dimension)
429
+ except TypeError:
430
+ raise TypeError("not recognized as a GeometricEntity: %s" % type(other))
431
+ if isinstance(other, Point):
432
+ s, p = Point._normalize_dimension(self, Point(other))
433
+ return sqrt(Add(*((a - b)**2 for a, b in zip(s, p))))
434
+ distance = getattr(other, 'distance', None)
435
+ if distance is None:
436
+ raise TypeError("distance between Point and %s is not defined" % type(other))
437
+ return distance(self)
438
+
439
+ def dot(self, p):
440
+ """Return dot product of self with another Point."""
441
+ if not is_sequence(p):
442
+ p = Point(p) # raise the error via Point
443
+ return Add(*(a*b for a, b in zip(self, p)))
444
+
445
+ def equals(self, other):
446
+ """Returns whether the coordinates of self and other agree."""
447
+ # a point is equal to another point if all its components are equal
448
+ if not isinstance(other, Point) or len(self) != len(other):
449
+ return False
450
+ return all(a.equals(b) for a, b in zip(self, other))
451
+
452
+ def _eval_evalf(self, prec=15, **options):
453
+ """Evaluate the coordinates of the point.
454
+
455
+ This method will, where possible, create and return a new Point
456
+ where the coordinates are evaluated as floating point numbers to
457
+ the precision indicated (default=15).
458
+
459
+ Parameters
460
+ ==========
461
+
462
+ prec : int
463
+
464
+ Returns
465
+ =======
466
+
467
+ point : Point
468
+
469
+ Examples
470
+ ========
471
+
472
+ >>> from sympy import Point, Rational
473
+ >>> p1 = Point(Rational(1, 2), Rational(3, 2))
474
+ >>> p1
475
+ Point2D(1/2, 3/2)
476
+ >>> p1.evalf()
477
+ Point2D(0.5, 1.5)
478
+
479
+ """
480
+ dps = prec_to_dps(prec)
481
+ coords = [x.evalf(n=dps, **options) for x in self.args]
482
+ return Point(*coords, evaluate=False)
483
+
484
+ def intersection(self, other):
485
+ """The intersection between this point and another GeometryEntity.
486
+
487
+ Parameters
488
+ ==========
489
+
490
+ other : GeometryEntity or sequence of coordinates
491
+
492
+ Returns
493
+ =======
494
+
495
+ intersection : list of Points
496
+
497
+ Notes
498
+ =====
499
+
500
+ The return value will either be an empty list if there is no
501
+ intersection, otherwise it will contain this point.
502
+
503
+ Examples
504
+ ========
505
+
506
+ >>> from sympy import Point
507
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 0)
508
+ >>> p1.intersection(p2)
509
+ []
510
+ >>> p1.intersection(p3)
511
+ [Point2D(0, 0)]
512
+
513
+ """
514
+ if not isinstance(other, GeometryEntity):
515
+ other = Point(other)
516
+ if isinstance(other, Point):
517
+ if self == other:
518
+ return [self]
519
+ p1, p2 = Point._normalize_dimension(self, other)
520
+ if p1 == self and p1 == p2:
521
+ return [self]
522
+ return []
523
+ return other.intersection(self)
524
+
525
+ def is_collinear(self, *args):
526
+ """Returns `True` if there exists a line
527
+ that contains `self` and `points`. Returns `False` otherwise.
528
+ A trivially True value is returned if no points are given.
529
+
530
+ Parameters
531
+ ==========
532
+
533
+ args : sequence of Points
534
+
535
+ Returns
536
+ =======
537
+
538
+ is_collinear : boolean
539
+
540
+ See Also
541
+ ========
542
+
543
+ sympy.geometry.line.Line
544
+
545
+ Examples
546
+ ========
547
+
548
+ >>> from sympy import Point
549
+ >>> from sympy.abc import x
550
+ >>> p1, p2 = Point(0, 0), Point(1, 1)
551
+ >>> p3, p4, p5 = Point(2, 2), Point(x, x), Point(1, 2)
552
+ >>> Point.is_collinear(p1, p2, p3, p4)
553
+ True
554
+ >>> Point.is_collinear(p1, p2, p3, p5)
555
+ False
556
+
557
+ """
558
+ points = (self,) + args
559
+ points = Point._normalize_dimension(*[Point(i) for i in points])
560
+ points = list(uniq(points))
561
+ return Point.affine_rank(*points) <= 1
562
+
563
+ def is_concyclic(self, *args):
564
+ """Do `self` and the given sequence of points lie in a circle?
565
+
566
+ Returns True if the set of points are concyclic and
567
+ False otherwise. A trivial value of True is returned
568
+ if there are fewer than 2 other points.
569
+
570
+ Parameters
571
+ ==========
572
+
573
+ args : sequence of Points
574
+
575
+ Returns
576
+ =======
577
+
578
+ is_concyclic : boolean
579
+
580
+
581
+ Examples
582
+ ========
583
+
584
+ >>> from sympy import Point
585
+
586
+ Define 4 points that are on the unit circle:
587
+
588
+ >>> p1, p2, p3, p4 = Point(1, 0), (0, 1), (-1, 0), (0, -1)
589
+
590
+ >>> p1.is_concyclic() == p1.is_concyclic(p2, p3, p4) == True
591
+ True
592
+
593
+ Define a point not on that circle:
594
+
595
+ >>> p = Point(1, 1)
596
+
597
+ >>> p.is_concyclic(p1, p2, p3)
598
+ False
599
+
600
+ """
601
+ points = (self,) + args
602
+ points = Point._normalize_dimension(*[Point(i) for i in points])
603
+ points = list(uniq(points))
604
+ if not Point.affine_rank(*points) <= 2:
605
+ return False
606
+ origin = points[0]
607
+ points = [p - origin for p in points]
608
+ # points are concyclic if they are coplanar and
609
+ # there is a point c so that ||p_i-c|| == ||p_j-c|| for all
610
+ # i and j. Rearranging this equation gives us the following
611
+ # condition: the matrix `mat` must not a pivot in the last
612
+ # column.
613
+ mat = Matrix([list(i) + [i.dot(i)] for i in points])
614
+ rref, pivots = mat.rref()
615
+ if len(origin) not in pivots:
616
+ return True
617
+ return False
618
+
619
+ @property
620
+ def is_nonzero(self):
621
+ """True if any coordinate is nonzero, False if every coordinate is zero,
622
+ and None if it cannot be determined."""
623
+ is_zero = self.is_zero
624
+ if is_zero is None:
625
+ return None
626
+ return not is_zero
627
+
628
+ def is_scalar_multiple(self, p):
629
+ """Returns whether each coordinate of `self` is a scalar
630
+ multiple of the corresponding coordinate in point p.
631
+ """
632
+ s, o = Point._normalize_dimension(self, Point(p))
633
+ # 2d points happen a lot, so optimize this function call
634
+ if s.ambient_dimension == 2:
635
+ (x1, y1), (x2, y2) = s.args, o.args
636
+ rv = (x1*y2 - x2*y1).equals(0)
637
+ if rv is None:
638
+ raise Undecidable(filldedent(
639
+ '''Cannot determine if %s is a scalar multiple of
640
+ %s''' % (s, o)))
641
+
642
+ # if the vectors p1 and p2 are linearly dependent, then they must
643
+ # be scalar multiples of each other
644
+ m = Matrix([s.args, o.args])
645
+ return m.rank() < 2
646
+
647
+ @property
648
+ def is_zero(self):
649
+ """True if every coordinate is zero, False if any coordinate is not zero,
650
+ and None if it cannot be determined."""
651
+ nonzero = [x.is_nonzero for x in self.args]
652
+ if any(nonzero):
653
+ return False
654
+ if any(x is None for x in nonzero):
655
+ return None
656
+ return True
657
+
658
+ @property
659
+ def length(self):
660
+ """
661
+ Treating a Point as a Line, this returns 0 for the length of a Point.
662
+
663
+ Examples
664
+ ========
665
+
666
+ >>> from sympy import Point
667
+ >>> p = Point(0, 1)
668
+ >>> p.length
669
+ 0
670
+ """
671
+ return S.Zero
672
+
673
+ def midpoint(self, p):
674
+ """The midpoint between self and point p.
675
+
676
+ Parameters
677
+ ==========
678
+
679
+ p : Point
680
+
681
+ Returns
682
+ =======
683
+
684
+ midpoint : Point
685
+
686
+ See Also
687
+ ========
688
+
689
+ sympy.geometry.line.Segment.midpoint
690
+
691
+ Examples
692
+ ========
693
+
694
+ >>> from sympy import Point
695
+ >>> p1, p2 = Point(1, 1), Point(13, 5)
696
+ >>> p1.midpoint(p2)
697
+ Point2D(7, 3)
698
+
699
+ """
700
+ s, p = Point._normalize_dimension(self, Point(p))
701
+ return Point([simplify((a + b)*S.Half) for a, b in zip(s, p)])
702
+
703
+ @property
704
+ def origin(self):
705
+ """A point of all zeros of the same ambient dimension
706
+ as the current point"""
707
+ return Point([0]*len(self), evaluate=False)
708
+
709
+ @property
710
+ def orthogonal_direction(self):
711
+ """Returns a non-zero point that is orthogonal to the
712
+ line containing `self` and the origin.
713
+
714
+ Examples
715
+ ========
716
+
717
+ >>> from sympy import Line, Point
718
+ >>> a = Point(1, 2, 3)
719
+ >>> a.orthogonal_direction
720
+ Point3D(-2, 1, 0)
721
+ >>> b = _
722
+ >>> Line(b, b.origin).is_perpendicular(Line(a, a.origin))
723
+ True
724
+ """
725
+ dim = self.ambient_dimension
726
+ # if a coordinate is zero, we can put a 1 there and zeros elsewhere
727
+ if self[0].is_zero:
728
+ return Point([1] + (dim - 1)*[0])
729
+ if self[1].is_zero:
730
+ return Point([0,1] + (dim - 2)*[0])
731
+ # if the first two coordinates aren't zero, we can create a non-zero
732
+ # orthogonal vector by swapping them, negating one, and padding with zeros
733
+ return Point([-self[1], self[0]] + (dim - 2)*[0])
734
+
735
+ @staticmethod
736
+ def project(a, b):
737
+ """Project the point `a` onto the line between the origin
738
+ and point `b` along the normal direction.
739
+
740
+ Parameters
741
+ ==========
742
+
743
+ a : Point
744
+ b : Point
745
+
746
+ Returns
747
+ =======
748
+
749
+ p : Point
750
+
751
+ See Also
752
+ ========
753
+
754
+ sympy.geometry.line.LinearEntity.projection
755
+
756
+ Examples
757
+ ========
758
+
759
+ >>> from sympy import Line, Point
760
+ >>> a = Point(1, 2)
761
+ >>> b = Point(2, 5)
762
+ >>> z = a.origin
763
+ >>> p = Point.project(a, b)
764
+ >>> Line(p, a).is_perpendicular(Line(p, b))
765
+ True
766
+ >>> Point.is_collinear(z, p, b)
767
+ True
768
+ """
769
+ a, b = Point._normalize_dimension(Point(a), Point(b))
770
+ if b.is_zero:
771
+ raise ValueError("Cannot project to the zero vector.")
772
+ return b*(a.dot(b) / b.dot(b))
773
+
774
+ def taxicab_distance(self, p):
775
+ """The Taxicab Distance from self to point p.
776
+
777
+ Returns the sum of the horizontal and vertical distances to point p.
778
+
779
+ Parameters
780
+ ==========
781
+
782
+ p : Point
783
+
784
+ Returns
785
+ =======
786
+
787
+ taxicab_distance : The sum of the horizontal
788
+ and vertical distances to point p.
789
+
790
+ See Also
791
+ ========
792
+
793
+ sympy.geometry.point.Point.distance
794
+
795
+ Examples
796
+ ========
797
+
798
+ >>> from sympy import Point
799
+ >>> p1, p2 = Point(1, 1), Point(4, 5)
800
+ >>> p1.taxicab_distance(p2)
801
+ 7
802
+
803
+ """
804
+ s, p = Point._normalize_dimension(self, Point(p))
805
+ return Add(*(abs(a - b) for a, b in zip(s, p)))
806
+
807
+ def canberra_distance(self, p):
808
+ """The Canberra Distance from self to point p.
809
+
810
+ Returns the weighted sum of horizontal and vertical distances to
811
+ point p.
812
+
813
+ Parameters
814
+ ==========
815
+
816
+ p : Point
817
+
818
+ Returns
819
+ =======
820
+
821
+ canberra_distance : The weighted sum of horizontal and vertical
822
+ distances to point p. The weight used is the sum of absolute values
823
+ of the coordinates.
824
+
825
+ Examples
826
+ ========
827
+
828
+ >>> from sympy import Point
829
+ >>> p1, p2 = Point(1, 1), Point(3, 3)
830
+ >>> p1.canberra_distance(p2)
831
+ 1
832
+ >>> p1, p2 = Point(0, 0), Point(3, 3)
833
+ >>> p1.canberra_distance(p2)
834
+ 2
835
+
836
+ Raises
837
+ ======
838
+
839
+ ValueError when both vectors are zero.
840
+
841
+ See Also
842
+ ========
843
+
844
+ sympy.geometry.point.Point.distance
845
+
846
+ """
847
+
848
+ s, p = Point._normalize_dimension(self, Point(p))
849
+ if self.is_zero and p.is_zero:
850
+ raise ValueError("Cannot project to the zero vector.")
851
+ return Add(*((abs(a - b)/(abs(a) + abs(b))) for a, b in zip(s, p)))
852
+
853
+ @property
854
+ def unit(self):
855
+ """Return the Point that is in the same direction as `self`
856
+ and a distance of 1 from the origin"""
857
+ return self / abs(self)
858
+
859
+
860
+ class Point2D(Point):
861
+ """A point in a 2-dimensional Euclidean space.
862
+
863
+ Parameters
864
+ ==========
865
+
866
+ coords
867
+ A sequence of 2 coordinate values.
868
+
869
+ Attributes
870
+ ==========
871
+
872
+ x
873
+ y
874
+ length
875
+
876
+ Raises
877
+ ======
878
+
879
+ TypeError
880
+ When trying to add or subtract points with different dimensions.
881
+ When trying to create a point with more than two dimensions.
882
+ When `intersection` is called with object other than a Point.
883
+
884
+ See Also
885
+ ========
886
+
887
+ sympy.geometry.line.Segment : Connects two Points
888
+
889
+ Examples
890
+ ========
891
+
892
+ >>> from sympy import Point2D
893
+ >>> from sympy.abc import x
894
+ >>> Point2D(1, 2)
895
+ Point2D(1, 2)
896
+ >>> Point2D([1, 2])
897
+ Point2D(1, 2)
898
+ >>> Point2D(0, x)
899
+ Point2D(0, x)
900
+
901
+ Floats are automatically converted to Rational unless the
902
+ evaluate flag is False:
903
+
904
+ >>> Point2D(0.5, 0.25)
905
+ Point2D(1/2, 1/4)
906
+ >>> Point2D(0.5, 0.25, evaluate=False)
907
+ Point2D(0.5, 0.25)
908
+
909
+ """
910
+
911
+ _ambient_dimension = 2
912
+
913
+ def __new__(cls, *args, _nocheck=False, **kwargs):
914
+ if not _nocheck:
915
+ kwargs['dim'] = 2
916
+ args = Point(*args, **kwargs)
917
+ return GeometryEntity.__new__(cls, *args)
918
+
919
+ def __contains__(self, item):
920
+ return item == self
921
+
922
+ @property
923
+ def bounds(self):
924
+ """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
925
+ rectangle for the geometric figure.
926
+
927
+ """
928
+
929
+ return (self.x, self.y, self.x, self.y)
930
+
931
+ def rotate(self, angle, pt=None):
932
+ """Rotate ``angle`` radians counterclockwise about Point ``pt``.
933
+
934
+ See Also
935
+ ========
936
+
937
+ translate, scale
938
+
939
+ Examples
940
+ ========
941
+
942
+ >>> from sympy import Point2D, pi
943
+ >>> t = Point2D(1, 0)
944
+ >>> t.rotate(pi/2)
945
+ Point2D(0, 1)
946
+ >>> t.rotate(pi/2, (2, 0))
947
+ Point2D(2, -1)
948
+
949
+ """
950
+ c = cos(angle)
951
+ s = sin(angle)
952
+
953
+ rv = self
954
+ if pt is not None:
955
+ pt = Point(pt, dim=2)
956
+ rv -= pt
957
+ x, y = rv.args
958
+ rv = Point(c*x - s*y, s*x + c*y)
959
+ if pt is not None:
960
+ rv += pt
961
+ return rv
962
+
963
+ def scale(self, x=1, y=1, pt=None):
964
+ """Scale the coordinates of the Point by multiplying by
965
+ ``x`` and ``y`` after subtracting ``pt`` -- default is (0, 0) --
966
+ and then adding ``pt`` back again (i.e. ``pt`` is the point of
967
+ reference for the scaling).
968
+
969
+ See Also
970
+ ========
971
+
972
+ rotate, translate
973
+
974
+ Examples
975
+ ========
976
+
977
+ >>> from sympy import Point2D
978
+ >>> t = Point2D(1, 1)
979
+ >>> t.scale(2)
980
+ Point2D(2, 1)
981
+ >>> t.scale(2, 2)
982
+ Point2D(2, 2)
983
+
984
+ """
985
+ if pt:
986
+ pt = Point(pt, dim=2)
987
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
988
+ return Point(self.x*x, self.y*y)
989
+
990
+ def transform(self, matrix):
991
+ """Return the point after applying the transformation described
992
+ by the 3x3 Matrix, ``matrix``.
993
+
994
+ See Also
995
+ ========
996
+ sympy.geometry.point.Point2D.rotate
997
+ sympy.geometry.point.Point2D.scale
998
+ sympy.geometry.point.Point2D.translate
999
+ """
1000
+ if not (matrix.is_Matrix and matrix.shape == (3, 3)):
1001
+ raise ValueError("matrix must be a 3x3 matrix")
1002
+ x, y = self.args
1003
+ return Point(*(Matrix(1, 3, [x, y, 1])*matrix).tolist()[0][:2])
1004
+
1005
+ def translate(self, x=0, y=0):
1006
+ """Shift the Point by adding x and y to the coordinates of the Point.
1007
+
1008
+ See Also
1009
+ ========
1010
+
1011
+ sympy.geometry.point.Point2D.rotate, scale
1012
+
1013
+ Examples
1014
+ ========
1015
+
1016
+ >>> from sympy import Point2D
1017
+ >>> t = Point2D(0, 1)
1018
+ >>> t.translate(2)
1019
+ Point2D(2, 1)
1020
+ >>> t.translate(2, 2)
1021
+ Point2D(2, 3)
1022
+ >>> t + Point2D(2, 2)
1023
+ Point2D(2, 3)
1024
+
1025
+ """
1026
+ return Point(self.x + x, self.y + y)
1027
+
1028
+ @property
1029
+ def coordinates(self):
1030
+ """
1031
+ Returns the two coordinates of the Point.
1032
+
1033
+ Examples
1034
+ ========
1035
+
1036
+ >>> from sympy import Point2D
1037
+ >>> p = Point2D(0, 1)
1038
+ >>> p.coordinates
1039
+ (0, 1)
1040
+ """
1041
+ return self.args
1042
+
1043
+ @property
1044
+ def x(self):
1045
+ """
1046
+ Returns the X coordinate of the Point.
1047
+
1048
+ Examples
1049
+ ========
1050
+
1051
+ >>> from sympy import Point2D
1052
+ >>> p = Point2D(0, 1)
1053
+ >>> p.x
1054
+ 0
1055
+ """
1056
+ return self.args[0]
1057
+
1058
+ @property
1059
+ def y(self):
1060
+ """
1061
+ Returns the Y coordinate of the Point.
1062
+
1063
+ Examples
1064
+ ========
1065
+
1066
+ >>> from sympy import Point2D
1067
+ >>> p = Point2D(0, 1)
1068
+ >>> p.y
1069
+ 1
1070
+ """
1071
+ return self.args[1]
1072
+
1073
+ class Point3D(Point):
1074
+ """A point in a 3-dimensional Euclidean space.
1075
+
1076
+ Parameters
1077
+ ==========
1078
+
1079
+ coords
1080
+ A sequence of 3 coordinate values.
1081
+
1082
+ Attributes
1083
+ ==========
1084
+
1085
+ x
1086
+ y
1087
+ z
1088
+ length
1089
+
1090
+ Raises
1091
+ ======
1092
+
1093
+ TypeError
1094
+ When trying to add or subtract points with different dimensions.
1095
+ When `intersection` is called with object other than a Point.
1096
+
1097
+ Examples
1098
+ ========
1099
+
1100
+ >>> from sympy import Point3D
1101
+ >>> from sympy.abc import x
1102
+ >>> Point3D(1, 2, 3)
1103
+ Point3D(1, 2, 3)
1104
+ >>> Point3D([1, 2, 3])
1105
+ Point3D(1, 2, 3)
1106
+ >>> Point3D(0, x, 3)
1107
+ Point3D(0, x, 3)
1108
+
1109
+ Floats are automatically converted to Rational unless the
1110
+ evaluate flag is False:
1111
+
1112
+ >>> Point3D(0.5, 0.25, 2)
1113
+ Point3D(1/2, 1/4, 2)
1114
+ >>> Point3D(0.5, 0.25, 3, evaluate=False)
1115
+ Point3D(0.5, 0.25, 3)
1116
+
1117
+ """
1118
+
1119
+ _ambient_dimension = 3
1120
+
1121
+ def __new__(cls, *args, _nocheck=False, **kwargs):
1122
+ if not _nocheck:
1123
+ kwargs['dim'] = 3
1124
+ args = Point(*args, **kwargs)
1125
+ return GeometryEntity.__new__(cls, *args)
1126
+
1127
+ def __contains__(self, item):
1128
+ return item == self
1129
+
1130
+ @staticmethod
1131
+ def are_collinear(*points):
1132
+ """Is a sequence of points collinear?
1133
+
1134
+ Test whether or not a set of points are collinear. Returns True if
1135
+ the set of points are collinear, or False otherwise.
1136
+
1137
+ Parameters
1138
+ ==========
1139
+
1140
+ points : sequence of Point
1141
+
1142
+ Returns
1143
+ =======
1144
+
1145
+ are_collinear : boolean
1146
+
1147
+ See Also
1148
+ ========
1149
+
1150
+ sympy.geometry.line.Line3D
1151
+
1152
+ Examples
1153
+ ========
1154
+
1155
+ >>> from sympy import Point3D
1156
+ >>> from sympy.abc import x
1157
+ >>> p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1)
1158
+ >>> p3, p4, p5 = Point3D(2, 2, 2), Point3D(x, x, x), Point3D(1, 2, 6)
1159
+ >>> Point3D.are_collinear(p1, p2, p3, p4)
1160
+ True
1161
+ >>> Point3D.are_collinear(p1, p2, p3, p5)
1162
+ False
1163
+ """
1164
+ return Point.is_collinear(*points)
1165
+
1166
+ def direction_cosine(self, point):
1167
+ """
1168
+ Gives the direction cosine between 2 points
1169
+
1170
+ Parameters
1171
+ ==========
1172
+
1173
+ p : Point3D
1174
+
1175
+ Returns
1176
+ =======
1177
+
1178
+ list
1179
+
1180
+ Examples
1181
+ ========
1182
+
1183
+ >>> from sympy import Point3D
1184
+ >>> p1 = Point3D(1, 2, 3)
1185
+ >>> p1.direction_cosine(Point3D(2, 3, 5))
1186
+ [sqrt(6)/6, sqrt(6)/6, sqrt(6)/3]
1187
+ """
1188
+ a = self.direction_ratio(point)
1189
+ b = sqrt(Add(*(i**2 for i in a)))
1190
+ return [(point.x - self.x) / b,(point.y - self.y) / b,
1191
+ (point.z - self.z) / b]
1192
+
1193
+ def direction_ratio(self, point):
1194
+ """
1195
+ Gives the direction ratio between 2 points
1196
+
1197
+ Parameters
1198
+ ==========
1199
+
1200
+ p : Point3D
1201
+
1202
+ Returns
1203
+ =======
1204
+
1205
+ list
1206
+
1207
+ Examples
1208
+ ========
1209
+
1210
+ >>> from sympy import Point3D
1211
+ >>> p1 = Point3D(1, 2, 3)
1212
+ >>> p1.direction_ratio(Point3D(2, 3, 5))
1213
+ [1, 1, 2]
1214
+ """
1215
+ return [(point.x - self.x),(point.y - self.y),(point.z - self.z)]
1216
+
1217
+ def intersection(self, other):
1218
+ """The intersection between this point and another GeometryEntity.
1219
+
1220
+ Parameters
1221
+ ==========
1222
+
1223
+ other : GeometryEntity or sequence of coordinates
1224
+
1225
+ Returns
1226
+ =======
1227
+
1228
+ intersection : list of Points
1229
+
1230
+ Notes
1231
+ =====
1232
+
1233
+ The return value will either be an empty list if there is no
1234
+ intersection, otherwise it will contain this point.
1235
+
1236
+ Examples
1237
+ ========
1238
+
1239
+ >>> from sympy import Point3D
1240
+ >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 0, 0)
1241
+ >>> p1.intersection(p2)
1242
+ []
1243
+ >>> p1.intersection(p3)
1244
+ [Point3D(0, 0, 0)]
1245
+
1246
+ """
1247
+ if not isinstance(other, GeometryEntity):
1248
+ other = Point(other, dim=3)
1249
+ if isinstance(other, Point3D):
1250
+ if self == other:
1251
+ return [self]
1252
+ return []
1253
+ return other.intersection(self)
1254
+
1255
+ def scale(self, x=1, y=1, z=1, pt=None):
1256
+ """Scale the coordinates of the Point by multiplying by
1257
+ ``x`` and ``y`` after subtracting ``pt`` -- default is (0, 0) --
1258
+ and then adding ``pt`` back again (i.e. ``pt`` is the point of
1259
+ reference for the scaling).
1260
+
1261
+ See Also
1262
+ ========
1263
+
1264
+ translate
1265
+
1266
+ Examples
1267
+ ========
1268
+
1269
+ >>> from sympy import Point3D
1270
+ >>> t = Point3D(1, 1, 1)
1271
+ >>> t.scale(2)
1272
+ Point3D(2, 1, 1)
1273
+ >>> t.scale(2, 2)
1274
+ Point3D(2, 2, 1)
1275
+
1276
+ """
1277
+ if pt:
1278
+ pt = Point3D(pt)
1279
+ return self.translate(*(-pt).args).scale(x, y, z).translate(*pt.args)
1280
+ return Point3D(self.x*x, self.y*y, self.z*z)
1281
+
1282
+ def transform(self, matrix):
1283
+ """Return the point after applying the transformation described
1284
+ by the 4x4 Matrix, ``matrix``.
1285
+
1286
+ See Also
1287
+ ========
1288
+ sympy.geometry.point.Point3D.scale
1289
+ sympy.geometry.point.Point3D.translate
1290
+ """
1291
+ if not (matrix.is_Matrix and matrix.shape == (4, 4)):
1292
+ raise ValueError("matrix must be a 4x4 matrix")
1293
+ x, y, z = self.args
1294
+ m = Transpose(matrix)
1295
+ return Point3D(*(Matrix(1, 4, [x, y, z, 1])*m).tolist()[0][:3])
1296
+
1297
+ def translate(self, x=0, y=0, z=0):
1298
+ """Shift the Point by adding x and y to the coordinates of the Point.
1299
+
1300
+ See Also
1301
+ ========
1302
+
1303
+ scale
1304
+
1305
+ Examples
1306
+ ========
1307
+
1308
+ >>> from sympy import Point3D
1309
+ >>> t = Point3D(0, 1, 1)
1310
+ >>> t.translate(2)
1311
+ Point3D(2, 1, 1)
1312
+ >>> t.translate(2, 2)
1313
+ Point3D(2, 3, 1)
1314
+ >>> t + Point3D(2, 2, 2)
1315
+ Point3D(2, 3, 3)
1316
+
1317
+ """
1318
+ return Point3D(self.x + x, self.y + y, self.z + z)
1319
+
1320
+ @property
1321
+ def coordinates(self):
1322
+ """
1323
+ Returns the three coordinates of the Point.
1324
+
1325
+ Examples
1326
+ ========
1327
+
1328
+ >>> from sympy import Point3D
1329
+ >>> p = Point3D(0, 1, 2)
1330
+ >>> p.coordinates
1331
+ (0, 1, 2)
1332
+ """
1333
+ return self.args
1334
+
1335
+ @property
1336
+ def x(self):
1337
+ """
1338
+ Returns the X coordinate of the Point.
1339
+
1340
+ Examples
1341
+ ========
1342
+
1343
+ >>> from sympy import Point3D
1344
+ >>> p = Point3D(0, 1, 3)
1345
+ >>> p.x
1346
+ 0
1347
+ """
1348
+ return self.args[0]
1349
+
1350
+ @property
1351
+ def y(self):
1352
+ """
1353
+ Returns the Y coordinate of the Point.
1354
+
1355
+ Examples
1356
+ ========
1357
+
1358
+ >>> from sympy import Point3D
1359
+ >>> p = Point3D(0, 1, 2)
1360
+ >>> p.y
1361
+ 1
1362
+ """
1363
+ return self.args[1]
1364
+
1365
+ @property
1366
+ def z(self):
1367
+ """
1368
+ Returns the Z coordinate of the Point.
1369
+
1370
+ Examples
1371
+ ========
1372
+
1373
+ >>> from sympy import Point3D
1374
+ >>> p = Point3D(0, 1, 1)
1375
+ >>> p.z
1376
+ 1
1377
+ """
1378
+ return self.args[2]
wemm/lib/python3.10/site-packages/sympy/geometry/polygon.py ADDED
@@ -0,0 +1,2891 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Expr, S, oo, pi, sympify
2
+ from sympy.core.evalf import N
3
+ from sympy.core.sorting import default_sort_key, ordered
4
+ from sympy.core.symbol import _symbol, Dummy, Symbol
5
+ from sympy.functions.elementary.complexes import sign
6
+ from sympy.functions.elementary.piecewise import Piecewise
7
+ from sympy.functions.elementary.trigonometric import cos, sin, tan
8
+ from .ellipse import Circle
9
+ from .entity import GeometryEntity, GeometrySet
10
+ from .exceptions import GeometryError
11
+ from .line import Line, Segment, Ray
12
+ from .point import Point
13
+ from sympy.logic import And
14
+ from sympy.matrices import Matrix
15
+ from sympy.simplify.simplify import simplify
16
+ from sympy.solvers.solvers import solve
17
+ from sympy.utilities.iterables import has_dups, has_variety, uniq, rotate_left, least_rotation
18
+ from sympy.utilities.misc import as_int, func_name
19
+
20
+ from mpmath.libmp.libmpf import prec_to_dps
21
+
22
+ import warnings
23
+
24
+
25
+ x, y, T = [Dummy('polygon_dummy', real=True) for i in range(3)]
26
+
27
+
28
+ class Polygon(GeometrySet):
29
+ """A two-dimensional polygon.
30
+
31
+ A simple polygon in space. Can be constructed from a sequence of points
32
+ or from a center, radius, number of sides and rotation angle.
33
+
34
+ Parameters
35
+ ==========
36
+
37
+ vertices
38
+ A sequence of points.
39
+
40
+ n : int, optional
41
+ If $> 0$, an n-sided RegularPolygon is created.
42
+ Default value is $0$.
43
+
44
+ Attributes
45
+ ==========
46
+
47
+ area
48
+ angles
49
+ perimeter
50
+ vertices
51
+ centroid
52
+ sides
53
+
54
+ Raises
55
+ ======
56
+
57
+ GeometryError
58
+ If all parameters are not Points.
59
+
60
+ See Also
61
+ ========
62
+
63
+ sympy.geometry.point.Point, sympy.geometry.line.Segment, Triangle
64
+
65
+ Notes
66
+ =====
67
+
68
+ Polygons are treated as closed paths rather than 2D areas so
69
+ some calculations can be be negative or positive (e.g., area)
70
+ based on the orientation of the points.
71
+
72
+ Any consecutive identical points are reduced to a single point
73
+ and any points collinear and between two points will be removed
74
+ unless they are needed to define an explicit intersection (see examples).
75
+
76
+ A Triangle, Segment or Point will be returned when there are 3 or
77
+ fewer points provided.
78
+
79
+ Examples
80
+ ========
81
+
82
+ >>> from sympy import Polygon, pi
83
+ >>> p1, p2, p3, p4, p5 = [(0, 0), (1, 0), (5, 1), (0, 1), (3, 0)]
84
+ >>> Polygon(p1, p2, p3, p4)
85
+ Polygon(Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1))
86
+ >>> Polygon(p1, p2)
87
+ Segment2D(Point2D(0, 0), Point2D(1, 0))
88
+ >>> Polygon(p1, p2, p5)
89
+ Segment2D(Point2D(0, 0), Point2D(3, 0))
90
+
91
+ The area of a polygon is calculated as positive when vertices are
92
+ traversed in a ccw direction. When the sides of a polygon cross the
93
+ area will have positive and negative contributions. The following
94
+ defines a Z shape where the bottom right connects back to the top
95
+ left.
96
+
97
+ >>> Polygon((0, 2), (2, 2), (0, 0), (2, 0)).area
98
+ 0
99
+
100
+ When the keyword `n` is used to define the number of sides of the
101
+ Polygon then a RegularPolygon is created and the other arguments are
102
+ interpreted as center, radius and rotation. The unrotated RegularPolygon
103
+ will always have a vertex at Point(r, 0) where `r` is the radius of the
104
+ circle that circumscribes the RegularPolygon. Its method `spin` can be
105
+ used to increment that angle.
106
+
107
+ >>> p = Polygon((0,0), 1, n=3)
108
+ >>> p
109
+ RegularPolygon(Point2D(0, 0), 1, 3, 0)
110
+ >>> p.vertices[0]
111
+ Point2D(1, 0)
112
+ >>> p.args[0]
113
+ Point2D(0, 0)
114
+ >>> p.spin(pi/2)
115
+ >>> p.vertices[0]
116
+ Point2D(0, 1)
117
+
118
+ """
119
+
120
+ __slots__ = ()
121
+
122
+ def __new__(cls, *args, n = 0, **kwargs):
123
+ if n:
124
+ args = list(args)
125
+ # return a virtual polygon with n sides
126
+ if len(args) == 2: # center, radius
127
+ args.append(n)
128
+ elif len(args) == 3: # center, radius, rotation
129
+ args.insert(2, n)
130
+ return RegularPolygon(*args, **kwargs)
131
+
132
+ vertices = [Point(a, dim=2, **kwargs) for a in args]
133
+
134
+ # remove consecutive duplicates
135
+ nodup = []
136
+ for p in vertices:
137
+ if nodup and p == nodup[-1]:
138
+ continue
139
+ nodup.append(p)
140
+ if len(nodup) > 1 and nodup[-1] == nodup[0]:
141
+ nodup.pop() # last point was same as first
142
+
143
+ # remove collinear points
144
+ i = -3
145
+ while i < len(nodup) - 3 and len(nodup) > 2:
146
+ a, b, c = nodup[i], nodup[i + 1], nodup[i + 2]
147
+ if Point.is_collinear(a, b, c):
148
+ nodup.pop(i + 1)
149
+ if a == c:
150
+ nodup.pop(i)
151
+ else:
152
+ i += 1
153
+
154
+ vertices = list(nodup)
155
+
156
+ if len(vertices) > 3:
157
+ return GeometryEntity.__new__(cls, *vertices, **kwargs)
158
+ elif len(vertices) == 3:
159
+ return Triangle(*vertices, **kwargs)
160
+ elif len(vertices) == 2:
161
+ return Segment(*vertices, **kwargs)
162
+ else:
163
+ return Point(*vertices, **kwargs)
164
+
165
+ @property
166
+ def area(self):
167
+ """
168
+ The area of the polygon.
169
+
170
+ Notes
171
+ =====
172
+
173
+ The area calculation can be positive or negative based on the
174
+ orientation of the points. If any side of the polygon crosses
175
+ any other side, there will be areas having opposite signs.
176
+
177
+ See Also
178
+ ========
179
+
180
+ sympy.geometry.ellipse.Ellipse.area
181
+
182
+ Examples
183
+ ========
184
+
185
+ >>> from sympy import Point, Polygon
186
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
187
+ >>> poly = Polygon(p1, p2, p3, p4)
188
+ >>> poly.area
189
+ 3
190
+
191
+ In the Z shaped polygon (with the lower right connecting back
192
+ to the upper left) the areas cancel out:
193
+
194
+ >>> Z = Polygon((0, 1), (1, 1), (0, 0), (1, 0))
195
+ >>> Z.area
196
+ 0
197
+
198
+ In the M shaped polygon, areas do not cancel because no side
199
+ crosses any other (though there is a point of contact).
200
+
201
+ >>> M = Polygon((0, 0), (0, 1), (2, 0), (3, 1), (3, 0))
202
+ >>> M.area
203
+ -3/2
204
+
205
+ """
206
+ area = 0
207
+ args = self.args
208
+ for i in range(len(args)):
209
+ x1, y1 = args[i - 1].args
210
+ x2, y2 = args[i].args
211
+ area += x1*y2 - x2*y1
212
+ return simplify(area) / 2
213
+
214
+ @staticmethod
215
+ def _is_clockwise(a, b, c):
216
+ """Return True/False for cw/ccw orientation.
217
+
218
+ Examples
219
+ ========
220
+
221
+ >>> from sympy import Point, Polygon
222
+ >>> a, b, c = [Point(i) for i in [(0, 0), (1, 1), (1, 0)]]
223
+ >>> Polygon._is_clockwise(a, b, c)
224
+ True
225
+ >>> Polygon._is_clockwise(a, c, b)
226
+ False
227
+ """
228
+ ba = b - a
229
+ ca = c - a
230
+ t_area = simplify(ba.x*ca.y - ca.x*ba.y)
231
+ res = t_area.is_nonpositive
232
+ if res is None:
233
+ raise ValueError("Can't determine orientation")
234
+ return res
235
+
236
+ @property
237
+ def angles(self):
238
+ """The internal angle at each vertex.
239
+
240
+ Returns
241
+ =======
242
+
243
+ angles : dict
244
+ A dictionary where each key is a vertex and each value is the
245
+ internal angle at that vertex. The vertices are represented as
246
+ Points.
247
+
248
+ See Also
249
+ ========
250
+
251
+ sympy.geometry.point.Point, sympy.geometry.line.LinearEntity.angle_between
252
+
253
+ Examples
254
+ ========
255
+
256
+ >>> from sympy import Point, Polygon
257
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
258
+ >>> poly = Polygon(p1, p2, p3, p4)
259
+ >>> poly.angles[p1]
260
+ pi/2
261
+ >>> poly.angles[p2]
262
+ acos(-4*sqrt(17)/17)
263
+
264
+ """
265
+
266
+ args = self.vertices
267
+ n = len(args)
268
+ ret = {}
269
+ for i in range(n):
270
+ a, b, c = args[i - 2], args[i - 1], args[i]
271
+ reflex_ang = Ray(b, a).angle_between(Ray(b, c))
272
+ if self._is_clockwise(a, b, c):
273
+ ret[b] = 2*S.Pi - reflex_ang
274
+ else:
275
+ ret[b] = reflex_ang
276
+
277
+ # internal sum should be pi*(n - 2), not pi*(n+2)
278
+ # so if ratio is (n+2)/(n-2) > 1 it is wrong
279
+ wrong = ((sum(ret.values())/S.Pi-1)/(n - 2) - 1).is_positive
280
+ if wrong:
281
+ two_pi = 2*S.Pi
282
+ for b in ret:
283
+ ret[b] = two_pi - ret[b]
284
+ elif wrong is None:
285
+ raise ValueError("could not determine Polygon orientation.")
286
+ return ret
287
+
288
+ @property
289
+ def ambient_dimension(self):
290
+ return self.vertices[0].ambient_dimension
291
+
292
+ @property
293
+ def perimeter(self):
294
+ """The perimeter of the polygon.
295
+
296
+ Returns
297
+ =======
298
+
299
+ perimeter : number or Basic instance
300
+
301
+ See Also
302
+ ========
303
+
304
+ sympy.geometry.line.Segment.length
305
+
306
+ Examples
307
+ ========
308
+
309
+ >>> from sympy import Point, Polygon
310
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
311
+ >>> poly = Polygon(p1, p2, p3, p4)
312
+ >>> poly.perimeter
313
+ sqrt(17) + 7
314
+ """
315
+ p = 0
316
+ args = self.vertices
317
+ for i in range(len(args)):
318
+ p += args[i - 1].distance(args[i])
319
+ return simplify(p)
320
+
321
+ @property
322
+ def vertices(self):
323
+ """The vertices of the polygon.
324
+
325
+ Returns
326
+ =======
327
+
328
+ vertices : list of Points
329
+
330
+ Notes
331
+ =====
332
+
333
+ When iterating over the vertices, it is more efficient to index self
334
+ rather than to request the vertices and index them. Only use the
335
+ vertices when you want to process all of them at once. This is even
336
+ more important with RegularPolygons that calculate each vertex.
337
+
338
+ See Also
339
+ ========
340
+
341
+ sympy.geometry.point.Point
342
+
343
+ Examples
344
+ ========
345
+
346
+ >>> from sympy import Point, Polygon
347
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
348
+ >>> poly = Polygon(p1, p2, p3, p4)
349
+ >>> poly.vertices
350
+ [Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1)]
351
+ >>> poly.vertices[0]
352
+ Point2D(0, 0)
353
+
354
+ """
355
+ return list(self.args)
356
+
357
+ @property
358
+ def centroid(self):
359
+ """The centroid of the polygon.
360
+
361
+ Returns
362
+ =======
363
+
364
+ centroid : Point
365
+
366
+ See Also
367
+ ========
368
+
369
+ sympy.geometry.point.Point, sympy.geometry.util.centroid
370
+
371
+ Examples
372
+ ========
373
+
374
+ >>> from sympy import Point, Polygon
375
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
376
+ >>> poly = Polygon(p1, p2, p3, p4)
377
+ >>> poly.centroid
378
+ Point2D(31/18, 11/18)
379
+
380
+ """
381
+ A = 1/(6*self.area)
382
+ cx, cy = 0, 0
383
+ args = self.args
384
+ for i in range(len(args)):
385
+ x1, y1 = args[i - 1].args
386
+ x2, y2 = args[i].args
387
+ v = x1*y2 - x2*y1
388
+ cx += v*(x1 + x2)
389
+ cy += v*(y1 + y2)
390
+ return Point(simplify(A*cx), simplify(A*cy))
391
+
392
+
393
+ def second_moment_of_area(self, point=None):
394
+ """Returns the second moment and product moment of area of a two dimensional polygon.
395
+
396
+ Parameters
397
+ ==========
398
+
399
+ point : Point, two-tuple of sympifyable objects, or None(default=None)
400
+ point is the point about which second moment of area is to be found.
401
+ If "point=None" it will be calculated about the axis passing through the
402
+ centroid of the polygon.
403
+
404
+ Returns
405
+ =======
406
+
407
+ I_xx, I_yy, I_xy : number or SymPy expression
408
+ I_xx, I_yy are second moment of area of a two dimensional polygon.
409
+ I_xy is product moment of area of a two dimensional polygon.
410
+
411
+ Examples
412
+ ========
413
+
414
+ >>> from sympy import Polygon, symbols
415
+ >>> a, b = symbols('a, b')
416
+ >>> p1, p2, p3, p4, p5 = [(0, 0), (a, 0), (a, b), (0, b), (a/3, b/3)]
417
+ >>> rectangle = Polygon(p1, p2, p3, p4)
418
+ >>> rectangle.second_moment_of_area()
419
+ (a*b**3/12, a**3*b/12, 0)
420
+ >>> rectangle.second_moment_of_area(p5)
421
+ (a*b**3/9, a**3*b/9, a**2*b**2/36)
422
+
423
+ References
424
+ ==========
425
+
426
+ .. [1] https://en.wikipedia.org/wiki/Second_moment_of_area
427
+
428
+ """
429
+
430
+ I_xx, I_yy, I_xy = 0, 0, 0
431
+ args = self.vertices
432
+ for i in range(len(args)):
433
+ x1, y1 = args[i-1].args
434
+ x2, y2 = args[i].args
435
+ v = x1*y2 - x2*y1
436
+ I_xx += (y1**2 + y1*y2 + y2**2)*v
437
+ I_yy += (x1**2 + x1*x2 + x2**2)*v
438
+ I_xy += (x1*y2 + 2*x1*y1 + 2*x2*y2 + x2*y1)*v
439
+ A = self.area
440
+ c_x = self.centroid[0]
441
+ c_y = self.centroid[1]
442
+ # parallel axis theorem
443
+ I_xx_c = (I_xx/12) - (A*(c_y**2))
444
+ I_yy_c = (I_yy/12) - (A*(c_x**2))
445
+ I_xy_c = (I_xy/24) - (A*(c_x*c_y))
446
+ if point is None:
447
+ return I_xx_c, I_yy_c, I_xy_c
448
+
449
+ I_xx = (I_xx_c + A*((point[1]-c_y)**2))
450
+ I_yy = (I_yy_c + A*((point[0]-c_x)**2))
451
+ I_xy = (I_xy_c + A*((point[0]-c_x)*(point[1]-c_y)))
452
+
453
+ return I_xx, I_yy, I_xy
454
+
455
+
456
+ def first_moment_of_area(self, point=None):
457
+ """
458
+ Returns the first moment of area of a two-dimensional polygon with
459
+ respect to a certain point of interest.
460
+
461
+ First moment of area is a measure of the distribution of the area
462
+ of a polygon in relation to an axis. The first moment of area of
463
+ the entire polygon about its own centroid is always zero. Therefore,
464
+ here it is calculated for an area, above or below a certain point
465
+ of interest, that makes up a smaller portion of the polygon. This
466
+ area is bounded by the point of interest and the extreme end
467
+ (top or bottom) of the polygon. The first moment for this area is
468
+ is then determined about the centroidal axis of the initial polygon.
469
+
470
+ References
471
+ ==========
472
+
473
+ .. [1] https://skyciv.com/docs/tutorials/section-tutorials/calculating-the-statical-or-first-moment-of-area-of-beam-sections/?cc=BMD
474
+ .. [2] https://mechanicalc.com/reference/cross-sections
475
+
476
+ Parameters
477
+ ==========
478
+
479
+ point: Point, two-tuple of sympifyable objects, or None (default=None)
480
+ point is the point above or below which the area of interest lies
481
+ If ``point=None`` then the centroid acts as the point of interest.
482
+
483
+ Returns
484
+ =======
485
+
486
+ Q_x, Q_y: number or SymPy expressions
487
+ Q_x is the first moment of area about the x-axis
488
+ Q_y is the first moment of area about the y-axis
489
+ A negative sign indicates that the section modulus is
490
+ determined for a section below (or left of) the centroidal axis
491
+
492
+ Examples
493
+ ========
494
+
495
+ >>> from sympy import Point, Polygon
496
+ >>> a, b = 50, 10
497
+ >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)]
498
+ >>> p = Polygon(p1, p2, p3, p4)
499
+ >>> p.first_moment_of_area()
500
+ (625, 3125)
501
+ >>> p.first_moment_of_area(point=Point(30, 7))
502
+ (525, 3000)
503
+ """
504
+ if point:
505
+ xc, yc = self.centroid
506
+ else:
507
+ point = self.centroid
508
+ xc, yc = point
509
+
510
+ h_line = Line(point, slope=0)
511
+ v_line = Line(point, slope=S.Infinity)
512
+
513
+ h_poly = self.cut_section(h_line)
514
+ v_poly = self.cut_section(v_line)
515
+
516
+ poly_1 = h_poly[0] if h_poly[0].area <= h_poly[1].area else h_poly[1]
517
+ poly_2 = v_poly[0] if v_poly[0].area <= v_poly[1].area else v_poly[1]
518
+
519
+ Q_x = (poly_1.centroid.y - yc)*poly_1.area
520
+ Q_y = (poly_2.centroid.x - xc)*poly_2.area
521
+
522
+ return Q_x, Q_y
523
+
524
+
525
+ def polar_second_moment_of_area(self):
526
+ """Returns the polar modulus of a two-dimensional polygon
527
+
528
+ It is a constituent of the second moment of area, linked through
529
+ the perpendicular axis theorem. While the planar second moment of
530
+ area describes an object's resistance to deflection (bending) when
531
+ subjected to a force applied to a plane parallel to the central
532
+ axis, the polar second moment of area describes an object's
533
+ resistance to deflection when subjected to a moment applied in a
534
+ plane perpendicular to the object's central axis (i.e. parallel to
535
+ the cross-section)
536
+
537
+ Examples
538
+ ========
539
+
540
+ >>> from sympy import Polygon, symbols
541
+ >>> a, b = symbols('a, b')
542
+ >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b))
543
+ >>> rectangle.polar_second_moment_of_area()
544
+ a**3*b/12 + a*b**3/12
545
+
546
+ References
547
+ ==========
548
+
549
+ .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia
550
+
551
+ """
552
+ second_moment = self.second_moment_of_area()
553
+ return second_moment[0] + second_moment[1]
554
+
555
+
556
+ def section_modulus(self, point=None):
557
+ """Returns a tuple with the section modulus of a two-dimensional
558
+ polygon.
559
+
560
+ Section modulus is a geometric property of a polygon defined as the
561
+ ratio of second moment of area to the distance of the extreme end of
562
+ the polygon from the centroidal axis.
563
+
564
+ Parameters
565
+ ==========
566
+
567
+ point : Point, two-tuple of sympifyable objects, or None(default=None)
568
+ point is the point at which section modulus is to be found.
569
+ If "point=None" it will be calculated for the point farthest from the
570
+ centroidal axis of the polygon.
571
+
572
+ Returns
573
+ =======
574
+
575
+ S_x, S_y: numbers or SymPy expressions
576
+ S_x is the section modulus with respect to the x-axis
577
+ S_y is the section modulus with respect to the y-axis
578
+ A negative sign indicates that the section modulus is
579
+ determined for a point below the centroidal axis
580
+
581
+ Examples
582
+ ========
583
+
584
+ >>> from sympy import symbols, Polygon, Point
585
+ >>> a, b = symbols('a, b', positive=True)
586
+ >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b))
587
+ >>> rectangle.section_modulus()
588
+ (a*b**2/6, a**2*b/6)
589
+ >>> rectangle.section_modulus(Point(a/4, b/4))
590
+ (-a*b**2/3, -a**2*b/3)
591
+
592
+ References
593
+ ==========
594
+
595
+ .. [1] https://en.wikipedia.org/wiki/Section_modulus
596
+
597
+ """
598
+ x_c, y_c = self.centroid
599
+ if point is None:
600
+ # taking x and y as maximum distances from centroid
601
+ x_min, y_min, x_max, y_max = self.bounds
602
+ y = max(y_c - y_min, y_max - y_c)
603
+ x = max(x_c - x_min, x_max - x_c)
604
+ else:
605
+ # taking x and y as distances of the given point from the centroid
606
+ y = point.y - y_c
607
+ x = point.x - x_c
608
+
609
+ second_moment= self.second_moment_of_area()
610
+ S_x = second_moment[0]/y
611
+ S_y = second_moment[1]/x
612
+
613
+ return S_x, S_y
614
+
615
+
616
+ @property
617
+ def sides(self):
618
+ """The directed line segments that form the sides of the polygon.
619
+
620
+ Returns
621
+ =======
622
+
623
+ sides : list of sides
624
+ Each side is a directed Segment.
625
+
626
+ See Also
627
+ ========
628
+
629
+ sympy.geometry.point.Point, sympy.geometry.line.Segment
630
+
631
+ Examples
632
+ ========
633
+
634
+ >>> from sympy import Point, Polygon
635
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
636
+ >>> poly = Polygon(p1, p2, p3, p4)
637
+ >>> poly.sides
638
+ [Segment2D(Point2D(0, 0), Point2D(1, 0)),
639
+ Segment2D(Point2D(1, 0), Point2D(5, 1)),
640
+ Segment2D(Point2D(5, 1), Point2D(0, 1)), Segment2D(Point2D(0, 1), Point2D(0, 0))]
641
+
642
+ """
643
+ res = []
644
+ args = self.vertices
645
+ for i in range(-len(args), 0):
646
+ res.append(Segment(args[i], args[i + 1]))
647
+ return res
648
+
649
+ @property
650
+ def bounds(self):
651
+ """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
652
+ rectangle for the geometric figure.
653
+
654
+ """
655
+
656
+ verts = self.vertices
657
+ xs = [p.x for p in verts]
658
+ ys = [p.y for p in verts]
659
+ return (min(xs), min(ys), max(xs), max(ys))
660
+
661
+ def is_convex(self):
662
+ """Is the polygon convex?
663
+
664
+ A polygon is convex if all its interior angles are less than 180
665
+ degrees and there are no intersections between sides.
666
+
667
+ Returns
668
+ =======
669
+
670
+ is_convex : boolean
671
+ True if this polygon is convex, False otherwise.
672
+
673
+ See Also
674
+ ========
675
+
676
+ sympy.geometry.util.convex_hull
677
+
678
+ Examples
679
+ ========
680
+
681
+ >>> from sympy import Point, Polygon
682
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
683
+ >>> poly = Polygon(p1, p2, p3, p4)
684
+ >>> poly.is_convex()
685
+ True
686
+
687
+ """
688
+ # Determine orientation of points
689
+ args = self.vertices
690
+ cw = self._is_clockwise(args[-2], args[-1], args[0])
691
+ for i in range(1, len(args)):
692
+ if cw ^ self._is_clockwise(args[i - 2], args[i - 1], args[i]):
693
+ return False
694
+ # check for intersecting sides
695
+ sides = self.sides
696
+ for i, si in enumerate(sides):
697
+ pts = si.args
698
+ # exclude the sides connected to si
699
+ for j in range(1 if i == len(sides) - 1 else 0, i - 1):
700
+ sj = sides[j]
701
+ if sj.p1 not in pts and sj.p2 not in pts:
702
+ hit = si.intersection(sj)
703
+ if hit:
704
+ return False
705
+ return True
706
+
707
+ def encloses_point(self, p):
708
+ """
709
+ Return True if p is enclosed by (is inside of) self.
710
+
711
+ Notes
712
+ =====
713
+
714
+ Being on the border of self is considered False.
715
+
716
+ Parameters
717
+ ==========
718
+
719
+ p : Point
720
+
721
+ Returns
722
+ =======
723
+
724
+ encloses_point : True, False or None
725
+
726
+ See Also
727
+ ========
728
+
729
+ sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.encloses_point
730
+
731
+ Examples
732
+ ========
733
+
734
+ >>> from sympy import Polygon, Point
735
+ >>> p = Polygon((0, 0), (4, 0), (4, 4))
736
+ >>> p.encloses_point(Point(2, 1))
737
+ True
738
+ >>> p.encloses_point(Point(2, 2))
739
+ False
740
+ >>> p.encloses_point(Point(5, 5))
741
+ False
742
+
743
+ References
744
+ ==========
745
+
746
+ .. [1] https://paulbourke.net/geometry/polygonmesh/#insidepoly
747
+
748
+ """
749
+ p = Point(p, dim=2)
750
+ if p in self.vertices or any(p in s for s in self.sides):
751
+ return False
752
+
753
+ # move to p, checking that the result is numeric
754
+ lit = []
755
+ for v in self.vertices:
756
+ lit.append(v - p) # the difference is simplified
757
+ if lit[-1].free_symbols:
758
+ return None
759
+
760
+ poly = Polygon(*lit)
761
+
762
+ # polygon closure is assumed in the following test but Polygon removes duplicate pts so
763
+ # the last point has to be added so all sides are computed. Using Polygon.sides is
764
+ # not good since Segments are unordered.
765
+ args = poly.args
766
+ indices = list(range(-len(args), 1))
767
+
768
+ if poly.is_convex():
769
+ orientation = None
770
+ for i in indices:
771
+ a = args[i]
772
+ b = args[i + 1]
773
+ test = ((-a.y)*(b.x - a.x) - (-a.x)*(b.y - a.y)).is_negative
774
+ if orientation is None:
775
+ orientation = test
776
+ elif test is not orientation:
777
+ return False
778
+ return True
779
+
780
+ hit_odd = False
781
+ p1x, p1y = args[0].args
782
+ for i in indices[1:]:
783
+ p2x, p2y = args[i].args
784
+ if 0 > min(p1y, p2y):
785
+ if 0 <= max(p1y, p2y):
786
+ if 0 <= max(p1x, p2x):
787
+ if p1y != p2y:
788
+ xinters = (-p1y)*(p2x - p1x)/(p2y - p1y) + p1x
789
+ if p1x == p2x or 0 <= xinters:
790
+ hit_odd = not hit_odd
791
+ p1x, p1y = p2x, p2y
792
+ return hit_odd
793
+
794
+ def arbitrary_point(self, parameter='t'):
795
+ """A parameterized point on the polygon.
796
+
797
+ The parameter, varying from 0 to 1, assigns points to the position on
798
+ the perimeter that is that fraction of the total perimeter. So the
799
+ point evaluated at t=1/2 would return the point from the first vertex
800
+ that is 1/2 way around the polygon.
801
+
802
+ Parameters
803
+ ==========
804
+
805
+ parameter : str, optional
806
+ Default value is 't'.
807
+
808
+ Returns
809
+ =======
810
+
811
+ arbitrary_point : Point
812
+
813
+ Raises
814
+ ======
815
+
816
+ ValueError
817
+ When `parameter` already appears in the Polygon's definition.
818
+
819
+ See Also
820
+ ========
821
+
822
+ sympy.geometry.point.Point
823
+
824
+ Examples
825
+ ========
826
+
827
+ >>> from sympy import Polygon, Symbol
828
+ >>> t = Symbol('t', real=True)
829
+ >>> tri = Polygon((0, 0), (1, 0), (1, 1))
830
+ >>> p = tri.arbitrary_point('t')
831
+ >>> perimeter = tri.perimeter
832
+ >>> s1, s2 = [s.length for s in tri.sides[:2]]
833
+ >>> p.subs(t, (s1 + s2/2)/perimeter)
834
+ Point2D(1, 1/2)
835
+
836
+ """
837
+ t = _symbol(parameter, real=True)
838
+ if t.name in (f.name for f in self.free_symbols):
839
+ raise ValueError('Symbol %s already appears in object and cannot be used as a parameter.' % t.name)
840
+ sides = []
841
+ perimeter = self.perimeter
842
+ perim_fraction_start = 0
843
+ for s in self.sides:
844
+ side_perim_fraction = s.length/perimeter
845
+ perim_fraction_end = perim_fraction_start + side_perim_fraction
846
+ pt = s.arbitrary_point(parameter).subs(
847
+ t, (t - perim_fraction_start)/side_perim_fraction)
848
+ sides.append(
849
+ (pt, (And(perim_fraction_start <= t, t < perim_fraction_end))))
850
+ perim_fraction_start = perim_fraction_end
851
+ return Piecewise(*sides)
852
+
853
+ def parameter_value(self, other, t):
854
+ if not isinstance(other,GeometryEntity):
855
+ other = Point(other, dim=self.ambient_dimension)
856
+ if not isinstance(other,Point):
857
+ raise ValueError("other must be a point")
858
+ if other.free_symbols:
859
+ raise NotImplementedError('non-numeric coordinates')
860
+ unknown = False
861
+ p = self.arbitrary_point(T)
862
+ for pt, cond in p.args:
863
+ sol = solve(pt - other, T, dict=True)
864
+ if not sol:
865
+ continue
866
+ value = sol[0][T]
867
+ if simplify(cond.subs(T, value)) == True:
868
+ return {t: value}
869
+ unknown = True
870
+ if unknown:
871
+ raise ValueError("Given point may not be on %s" % func_name(self))
872
+ raise ValueError("Given point is not on %s" % func_name(self))
873
+
874
+ def plot_interval(self, parameter='t'):
875
+ """The plot interval for the default geometric plot of the polygon.
876
+
877
+ Parameters
878
+ ==========
879
+
880
+ parameter : str, optional
881
+ Default value is 't'.
882
+
883
+ Returns
884
+ =======
885
+
886
+ plot_interval : list (plot interval)
887
+ [parameter, lower_bound, upper_bound]
888
+
889
+ Examples
890
+ ========
891
+
892
+ >>> from sympy import Polygon
893
+ >>> p = Polygon((0, 0), (1, 0), (1, 1))
894
+ >>> p.plot_interval()
895
+ [t, 0, 1]
896
+
897
+ """
898
+ t = Symbol(parameter, real=True)
899
+ return [t, 0, 1]
900
+
901
+ def intersection(self, o):
902
+ """The intersection of polygon and geometry entity.
903
+
904
+ The intersection may be empty and can contain individual Points and
905
+ complete Line Segments.
906
+
907
+ Parameters
908
+ ==========
909
+
910
+ other: GeometryEntity
911
+
912
+ Returns
913
+ =======
914
+
915
+ intersection : list
916
+ The list of Segments and Points
917
+
918
+ See Also
919
+ ========
920
+
921
+ sympy.geometry.point.Point, sympy.geometry.line.Segment
922
+
923
+ Examples
924
+ ========
925
+
926
+ >>> from sympy import Point, Polygon, Line
927
+ >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
928
+ >>> poly1 = Polygon(p1, p2, p3, p4)
929
+ >>> p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)])
930
+ >>> poly2 = Polygon(p5, p6, p7)
931
+ >>> poly1.intersection(poly2)
932
+ [Point2D(1/3, 1), Point2D(2/3, 0), Point2D(9/5, 1/5), Point2D(7/3, 1)]
933
+ >>> poly1.intersection(Line(p1, p2))
934
+ [Segment2D(Point2D(0, 0), Point2D(1, 0))]
935
+ >>> poly1.intersection(p1)
936
+ [Point2D(0, 0)]
937
+ """
938
+ intersection_result = []
939
+ k = o.sides if isinstance(o, Polygon) else [o]
940
+ for side in self.sides:
941
+ for side1 in k:
942
+ intersection_result.extend(side.intersection(side1))
943
+
944
+ intersection_result = list(uniq(intersection_result))
945
+ points = [entity for entity in intersection_result if isinstance(entity, Point)]
946
+ segments = [entity for entity in intersection_result if isinstance(entity, Segment)]
947
+
948
+ if points and segments:
949
+ points_in_segments = list(uniq([point for point in points for segment in segments if point in segment]))
950
+ if points_in_segments:
951
+ for i in points_in_segments:
952
+ points.remove(i)
953
+ return list(ordered(segments + points))
954
+ else:
955
+ return list(ordered(intersection_result))
956
+
957
+
958
+ def cut_section(self, line):
959
+ """
960
+ Returns a tuple of two polygon segments that lie above and below
961
+ the intersecting line respectively.
962
+
963
+ Parameters
964
+ ==========
965
+
966
+ line: Line object of geometry module
967
+ line which cuts the Polygon. The part of the Polygon that lies
968
+ above and below this line is returned.
969
+
970
+ Returns
971
+ =======
972
+
973
+ upper_polygon, lower_polygon: Polygon objects or None
974
+ upper_polygon is the polygon that lies above the given line.
975
+ lower_polygon is the polygon that lies below the given line.
976
+ upper_polygon and lower polygon are ``None`` when no polygon
977
+ exists above the line or below the line.
978
+
979
+ Raises
980
+ ======
981
+
982
+ ValueError: When the line does not intersect the polygon
983
+
984
+ Examples
985
+ ========
986
+
987
+ >>> from sympy import Polygon, Line
988
+ >>> a, b = 20, 10
989
+ >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)]
990
+ >>> rectangle = Polygon(p1, p2, p3, p4)
991
+ >>> t = rectangle.cut_section(Line((0, 5), slope=0))
992
+ >>> t
993
+ (Polygon(Point2D(0, 10), Point2D(0, 5), Point2D(20, 5), Point2D(20, 10)),
994
+ Polygon(Point2D(0, 5), Point2D(0, 0), Point2D(20, 0), Point2D(20, 5)))
995
+ >>> upper_segment, lower_segment = t
996
+ >>> upper_segment.area
997
+ 100
998
+ >>> upper_segment.centroid
999
+ Point2D(10, 15/2)
1000
+ >>> lower_segment.centroid
1001
+ Point2D(10, 5/2)
1002
+
1003
+ References
1004
+ ==========
1005
+
1006
+ .. [1] https://github.com/sympy/sympy/wiki/A-method-to-return-a-cut-section-of-any-polygon-geometry
1007
+
1008
+ """
1009
+ intersection_points = self.intersection(line)
1010
+ if not intersection_points:
1011
+ raise ValueError("This line does not intersect the polygon")
1012
+
1013
+ points = list(self.vertices)
1014
+ points.append(points[0])
1015
+
1016
+ eq = line.equation(x, y)
1017
+
1018
+ # considering equation of line to be `ax +by + c`
1019
+ a = eq.coeff(x)
1020
+ b = eq.coeff(y)
1021
+
1022
+ upper_vertices = []
1023
+ lower_vertices = []
1024
+ # prev is true when previous point is above the line
1025
+ prev = True
1026
+ prev_point = None
1027
+ for point in points:
1028
+ # when coefficient of y is 0, right side of the line is
1029
+ # considered
1030
+ compare = eq.subs({x: point.x, y: point.y})/b if b \
1031
+ else eq.subs(x, point.x)/a
1032
+
1033
+ # if point lies above line
1034
+ if compare > 0:
1035
+ if not prev:
1036
+ # if previous point lies below the line, the intersection
1037
+ # point of the polygon edge and the line has to be included
1038
+ edge = Line(point, prev_point)
1039
+ new_point = edge.intersection(line)
1040
+ upper_vertices.append(new_point[0])
1041
+ lower_vertices.append(new_point[0])
1042
+
1043
+ upper_vertices.append(point)
1044
+ prev = True
1045
+ else:
1046
+ if prev and prev_point:
1047
+ edge = Line(point, prev_point)
1048
+ new_point = edge.intersection(line)
1049
+ upper_vertices.append(new_point[0])
1050
+ lower_vertices.append(new_point[0])
1051
+ lower_vertices.append(point)
1052
+ prev = False
1053
+ prev_point = point
1054
+
1055
+ upper_polygon, lower_polygon = None, None
1056
+ if upper_vertices and isinstance(Polygon(*upper_vertices), Polygon):
1057
+ upper_polygon = Polygon(*upper_vertices)
1058
+ if lower_vertices and isinstance(Polygon(*lower_vertices), Polygon):
1059
+ lower_polygon = Polygon(*lower_vertices)
1060
+
1061
+ return upper_polygon, lower_polygon
1062
+
1063
+
1064
+ def distance(self, o):
1065
+ """
1066
+ Returns the shortest distance between self and o.
1067
+
1068
+ If o is a point, then self does not need to be convex.
1069
+ If o is another polygon self and o must be convex.
1070
+
1071
+ Examples
1072
+ ========
1073
+
1074
+ >>> from sympy import Point, Polygon, RegularPolygon
1075
+ >>> p1, p2 = map(Point, [(0, 0), (7, 5)])
1076
+ >>> poly = Polygon(*RegularPolygon(p1, 1, 3).vertices)
1077
+ >>> poly.distance(p2)
1078
+ sqrt(61)
1079
+ """
1080
+ if isinstance(o, Point):
1081
+ dist = oo
1082
+ for side in self.sides:
1083
+ current = side.distance(o)
1084
+ if current == 0:
1085
+ return S.Zero
1086
+ elif current < dist:
1087
+ dist = current
1088
+ return dist
1089
+ elif isinstance(o, Polygon) and self.is_convex() and o.is_convex():
1090
+ return self._do_poly_distance(o)
1091
+ raise NotImplementedError()
1092
+
1093
+ def _do_poly_distance(self, e2):
1094
+ """
1095
+ Calculates the least distance between the exteriors of two
1096
+ convex polygons e1 and e2. Does not check for the convexity
1097
+ of the polygons as this is checked by Polygon.distance.
1098
+
1099
+ Notes
1100
+ =====
1101
+
1102
+ - Prints a warning if the two polygons possibly intersect as the return
1103
+ value will not be valid in such a case. For a more through test of
1104
+ intersection use intersection().
1105
+
1106
+ See Also
1107
+ ========
1108
+
1109
+ sympy.geometry.point.Point.distance
1110
+
1111
+ Examples
1112
+ ========
1113
+
1114
+ >>> from sympy import Point, Polygon
1115
+ >>> square = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
1116
+ >>> triangle = Polygon(Point(1, 2), Point(2, 2), Point(2, 1))
1117
+ >>> square._do_poly_distance(triangle)
1118
+ sqrt(2)/2
1119
+
1120
+ Description of method used
1121
+ ==========================
1122
+
1123
+ Method:
1124
+ [1] https://web.archive.org/web/20150509035744/http://cgm.cs.mcgill.ca/~orm/mind2p.html
1125
+ Uses rotating calipers:
1126
+ [2] https://en.wikipedia.org/wiki/Rotating_calipers
1127
+ and antipodal points:
1128
+ [3] https://en.wikipedia.org/wiki/Antipodal_point
1129
+ """
1130
+ e1 = self
1131
+
1132
+ '''Tests for a possible intersection between the polygons and outputs a warning'''
1133
+ e1_center = e1.centroid
1134
+ e2_center = e2.centroid
1135
+ e1_max_radius = S.Zero
1136
+ e2_max_radius = S.Zero
1137
+ for vertex in e1.vertices:
1138
+ r = Point.distance(e1_center, vertex)
1139
+ if e1_max_radius < r:
1140
+ e1_max_radius = r
1141
+ for vertex in e2.vertices:
1142
+ r = Point.distance(e2_center, vertex)
1143
+ if e2_max_radius < r:
1144
+ e2_max_radius = r
1145
+ center_dist = Point.distance(e1_center, e2_center)
1146
+ if center_dist <= e1_max_radius + e2_max_radius:
1147
+ warnings.warn("Polygons may intersect producing erroneous output",
1148
+ stacklevel=3)
1149
+
1150
+ '''
1151
+ Find the upper rightmost vertex of e1 and the lowest leftmost vertex of e2
1152
+ '''
1153
+ e1_ymax = Point(0, -oo)
1154
+ e2_ymin = Point(0, oo)
1155
+
1156
+ for vertex in e1.vertices:
1157
+ if vertex.y > e1_ymax.y or (vertex.y == e1_ymax.y and vertex.x > e1_ymax.x):
1158
+ e1_ymax = vertex
1159
+ for vertex in e2.vertices:
1160
+ if vertex.y < e2_ymin.y or (vertex.y == e2_ymin.y and vertex.x < e2_ymin.x):
1161
+ e2_ymin = vertex
1162
+ min_dist = Point.distance(e1_ymax, e2_ymin)
1163
+
1164
+ '''
1165
+ Produce a dictionary with vertices of e1 as the keys and, for each vertex, the points
1166
+ to which the vertex is connected as its value. The same is then done for e2.
1167
+ '''
1168
+ e1_connections = {}
1169
+ e2_connections = {}
1170
+
1171
+ for side in e1.sides:
1172
+ if side.p1 in e1_connections:
1173
+ e1_connections[side.p1].append(side.p2)
1174
+ else:
1175
+ e1_connections[side.p1] = [side.p2]
1176
+
1177
+ if side.p2 in e1_connections:
1178
+ e1_connections[side.p2].append(side.p1)
1179
+ else:
1180
+ e1_connections[side.p2] = [side.p1]
1181
+
1182
+ for side in e2.sides:
1183
+ if side.p1 in e2_connections:
1184
+ e2_connections[side.p1].append(side.p2)
1185
+ else:
1186
+ e2_connections[side.p1] = [side.p2]
1187
+
1188
+ if side.p2 in e2_connections:
1189
+ e2_connections[side.p2].append(side.p1)
1190
+ else:
1191
+ e2_connections[side.p2] = [side.p1]
1192
+
1193
+ e1_current = e1_ymax
1194
+ e2_current = e2_ymin
1195
+ support_line = Line(Point(S.Zero, S.Zero), Point(S.One, S.Zero))
1196
+
1197
+ '''
1198
+ Determine which point in e1 and e2 will be selected after e2_ymin and e1_ymax,
1199
+ this information combined with the above produced dictionaries determines the
1200
+ path that will be taken around the polygons
1201
+ '''
1202
+ point1 = e1_connections[e1_ymax][0]
1203
+ point2 = e1_connections[e1_ymax][1]
1204
+ angle1 = support_line.angle_between(Line(e1_ymax, point1))
1205
+ angle2 = support_line.angle_between(Line(e1_ymax, point2))
1206
+ if angle1 < angle2:
1207
+ e1_next = point1
1208
+ elif angle2 < angle1:
1209
+ e1_next = point2
1210
+ elif Point.distance(e1_ymax, point1) > Point.distance(e1_ymax, point2):
1211
+ e1_next = point2
1212
+ else:
1213
+ e1_next = point1
1214
+
1215
+ point1 = e2_connections[e2_ymin][0]
1216
+ point2 = e2_connections[e2_ymin][1]
1217
+ angle1 = support_line.angle_between(Line(e2_ymin, point1))
1218
+ angle2 = support_line.angle_between(Line(e2_ymin, point2))
1219
+ if angle1 > angle2:
1220
+ e2_next = point1
1221
+ elif angle2 > angle1:
1222
+ e2_next = point2
1223
+ elif Point.distance(e2_ymin, point1) > Point.distance(e2_ymin, point2):
1224
+ e2_next = point2
1225
+ else:
1226
+ e2_next = point1
1227
+
1228
+ '''
1229
+ Loop which determines the distance between anti-podal pairs and updates the
1230
+ minimum distance accordingly. It repeats until it reaches the starting position.
1231
+ '''
1232
+ while True:
1233
+ e1_angle = support_line.angle_between(Line(e1_current, e1_next))
1234
+ e2_angle = pi - support_line.angle_between(Line(
1235
+ e2_current, e2_next))
1236
+
1237
+ if (e1_angle < e2_angle) is True:
1238
+ support_line = Line(e1_current, e1_next)
1239
+ e1_segment = Segment(e1_current, e1_next)
1240
+ min_dist_current = e1_segment.distance(e2_current)
1241
+
1242
+ if min_dist_current.evalf() < min_dist.evalf():
1243
+ min_dist = min_dist_current
1244
+
1245
+ if e1_connections[e1_next][0] != e1_current:
1246
+ e1_current = e1_next
1247
+ e1_next = e1_connections[e1_next][0]
1248
+ else:
1249
+ e1_current = e1_next
1250
+ e1_next = e1_connections[e1_next][1]
1251
+ elif (e1_angle > e2_angle) is True:
1252
+ support_line = Line(e2_next, e2_current)
1253
+ e2_segment = Segment(e2_current, e2_next)
1254
+ min_dist_current = e2_segment.distance(e1_current)
1255
+
1256
+ if min_dist_current.evalf() < min_dist.evalf():
1257
+ min_dist = min_dist_current
1258
+
1259
+ if e2_connections[e2_next][0] != e2_current:
1260
+ e2_current = e2_next
1261
+ e2_next = e2_connections[e2_next][0]
1262
+ else:
1263
+ e2_current = e2_next
1264
+ e2_next = e2_connections[e2_next][1]
1265
+ else:
1266
+ support_line = Line(e1_current, e1_next)
1267
+ e1_segment = Segment(e1_current, e1_next)
1268
+ e2_segment = Segment(e2_current, e2_next)
1269
+ min1 = e1_segment.distance(e2_next)
1270
+ min2 = e2_segment.distance(e1_next)
1271
+
1272
+ min_dist_current = min(min1, min2)
1273
+ if min_dist_current.evalf() < min_dist.evalf():
1274
+ min_dist = min_dist_current
1275
+
1276
+ if e1_connections[e1_next][0] != e1_current:
1277
+ e1_current = e1_next
1278
+ e1_next = e1_connections[e1_next][0]
1279
+ else:
1280
+ e1_current = e1_next
1281
+ e1_next = e1_connections[e1_next][1]
1282
+
1283
+ if e2_connections[e2_next][0] != e2_current:
1284
+ e2_current = e2_next
1285
+ e2_next = e2_connections[e2_next][0]
1286
+ else:
1287
+ e2_current = e2_next
1288
+ e2_next = e2_connections[e2_next][1]
1289
+ if e1_current == e1_ymax and e2_current == e2_ymin:
1290
+ break
1291
+ return min_dist
1292
+
1293
+ def _svg(self, scale_factor=1., fill_color="#66cc99"):
1294
+ """Returns SVG path element for the Polygon.
1295
+
1296
+ Parameters
1297
+ ==========
1298
+
1299
+ scale_factor : float
1300
+ Multiplication factor for the SVG stroke-width. Default is 1.
1301
+ fill_color : str, optional
1302
+ Hex string for fill color. Default is "#66cc99".
1303
+ """
1304
+ verts = map(N, self.vertices)
1305
+ coords = ["{},{}".format(p.x, p.y) for p in verts]
1306
+ path = "M {} L {} z".format(coords[0], " L ".join(coords[1:]))
1307
+ return (
1308
+ '<path fill-rule="evenodd" fill="{2}" stroke="#555555" '
1309
+ 'stroke-width="{0}" opacity="0.6" d="{1}" />'
1310
+ ).format(2. * scale_factor, path, fill_color)
1311
+
1312
+ def _hashable_content(self):
1313
+
1314
+ D = {}
1315
+ def ref_list(point_list):
1316
+ kee = {}
1317
+ for i, p in enumerate(ordered(set(point_list))):
1318
+ kee[p] = i
1319
+ D[i] = p
1320
+ return [kee[p] for p in point_list]
1321
+
1322
+ S1 = ref_list(self.args)
1323
+ r_nor = rotate_left(S1, least_rotation(S1))
1324
+ S2 = ref_list(list(reversed(self.args)))
1325
+ r_rev = rotate_left(S2, least_rotation(S2))
1326
+ if r_nor < r_rev:
1327
+ r = r_nor
1328
+ else:
1329
+ r = r_rev
1330
+ canonical_args = [ D[order] for order in r ]
1331
+ return tuple(canonical_args)
1332
+
1333
+ def __contains__(self, o):
1334
+ """
1335
+ Return True if o is contained within the boundary lines of self.altitudes
1336
+
1337
+ Parameters
1338
+ ==========
1339
+
1340
+ other : GeometryEntity
1341
+
1342
+ Returns
1343
+ =======
1344
+
1345
+ contained in : bool
1346
+ The points (and sides, if applicable) are contained in self.
1347
+
1348
+ See Also
1349
+ ========
1350
+
1351
+ sympy.geometry.entity.GeometryEntity.encloses
1352
+
1353
+ Examples
1354
+ ========
1355
+
1356
+ >>> from sympy import Line, Segment, Point
1357
+ >>> p = Point(0, 0)
1358
+ >>> q = Point(1, 1)
1359
+ >>> s = Segment(p, q*2)
1360
+ >>> l = Line(p, q)
1361
+ >>> p in q
1362
+ False
1363
+ >>> p in s
1364
+ True
1365
+ >>> q*3 in s
1366
+ False
1367
+ >>> s in l
1368
+ True
1369
+
1370
+ """
1371
+
1372
+ if isinstance(o, Polygon):
1373
+ return self == o
1374
+ elif isinstance(o, Segment):
1375
+ return any(o in s for s in self.sides)
1376
+ elif isinstance(o, Point):
1377
+ if o in self.vertices:
1378
+ return True
1379
+ for side in self.sides:
1380
+ if o in side:
1381
+ return True
1382
+
1383
+ return False
1384
+
1385
+ def bisectors(p, prec=None):
1386
+ """Returns angle bisectors of a polygon. If prec is given
1387
+ then approximate the point defining the ray to that precision.
1388
+
1389
+ The distance between the points defining the bisector ray is 1.
1390
+
1391
+ Examples
1392
+ ========
1393
+
1394
+ >>> from sympy import Polygon, Point
1395
+ >>> p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3))
1396
+ >>> p.bisectors(2)
1397
+ {Point2D(0, 0): Ray2D(Point2D(0, 0), Point2D(0.71, 0.71)),
1398
+ Point2D(0, 3): Ray2D(Point2D(0, 3), Point2D(0.23, 2.0)),
1399
+ Point2D(1, 1): Ray2D(Point2D(1, 1), Point2D(0.19, 0.42)),
1400
+ Point2D(2, 0): Ray2D(Point2D(2, 0), Point2D(1.1, 0.38))}
1401
+ """
1402
+ b = {}
1403
+ pts = list(p.args)
1404
+ pts.append(pts[0]) # close it
1405
+ cw = Polygon._is_clockwise(*pts[:3])
1406
+ if cw:
1407
+ pts = list(reversed(pts))
1408
+ for v, a in p.angles.items():
1409
+ i = pts.index(v)
1410
+ p1, p2 = Point._normalize_dimension(pts[i], pts[i + 1])
1411
+ ray = Ray(p1, p2).rotate(a/2, v)
1412
+ dir = ray.direction
1413
+ ray = Ray(ray.p1, ray.p1 + dir/dir.distance((0, 0)))
1414
+ if prec is not None:
1415
+ ray = Ray(ray.p1, ray.p2.n(prec))
1416
+ b[v] = ray
1417
+ return b
1418
+
1419
+
1420
+ class RegularPolygon(Polygon):
1421
+ """
1422
+ A regular polygon.
1423
+
1424
+ Such a polygon has all internal angles equal and all sides the same length.
1425
+
1426
+ Parameters
1427
+ ==========
1428
+
1429
+ center : Point
1430
+ radius : number or Basic instance
1431
+ The distance from the center to a vertex
1432
+ n : int
1433
+ The number of sides
1434
+
1435
+ Attributes
1436
+ ==========
1437
+
1438
+ vertices
1439
+ center
1440
+ radius
1441
+ rotation
1442
+ apothem
1443
+ interior_angle
1444
+ exterior_angle
1445
+ circumcircle
1446
+ incircle
1447
+ angles
1448
+
1449
+ Raises
1450
+ ======
1451
+
1452
+ GeometryError
1453
+ If the `center` is not a Point, or the `radius` is not a number or Basic
1454
+ instance, or the number of sides, `n`, is less than three.
1455
+
1456
+ Notes
1457
+ =====
1458
+
1459
+ A RegularPolygon can be instantiated with Polygon with the kwarg n.
1460
+
1461
+ Regular polygons are instantiated with a center, radius, number of sides
1462
+ and a rotation angle. Whereas the arguments of a Polygon are vertices, the
1463
+ vertices of the RegularPolygon must be obtained with the vertices method.
1464
+
1465
+ See Also
1466
+ ========
1467
+
1468
+ sympy.geometry.point.Point, Polygon
1469
+
1470
+ Examples
1471
+ ========
1472
+
1473
+ >>> from sympy import RegularPolygon, Point
1474
+ >>> r = RegularPolygon(Point(0, 0), 5, 3)
1475
+ >>> r
1476
+ RegularPolygon(Point2D(0, 0), 5, 3, 0)
1477
+ >>> r.vertices[0]
1478
+ Point2D(5, 0)
1479
+
1480
+ """
1481
+
1482
+ __slots__ = ('_n', '_center', '_radius', '_rot')
1483
+
1484
+ def __new__(self, c, r, n, rot=0, **kwargs):
1485
+ r, n, rot = map(sympify, (r, n, rot))
1486
+ c = Point(c, dim=2, **kwargs)
1487
+ if not isinstance(r, Expr):
1488
+ raise GeometryError("r must be an Expr object, not %s" % r)
1489
+ if n.is_Number:
1490
+ as_int(n) # let an error raise if necessary
1491
+ if n < 3:
1492
+ raise GeometryError("n must be a >= 3, not %s" % n)
1493
+
1494
+ obj = GeometryEntity.__new__(self, c, r, n, **kwargs)
1495
+ obj._n = n
1496
+ obj._center = c
1497
+ obj._radius = r
1498
+ obj._rot = rot % (2*S.Pi/n) if rot.is_number else rot
1499
+ return obj
1500
+
1501
+ def _eval_evalf(self, prec=15, **options):
1502
+ c, r, n, a = self.args
1503
+ dps = prec_to_dps(prec)
1504
+ c, r, a = [i.evalf(n=dps, **options) for i in (c, r, a)]
1505
+ return self.func(c, r, n, a)
1506
+
1507
+ @property
1508
+ def args(self):
1509
+ """
1510
+ Returns the center point, the radius,
1511
+ the number of sides, and the orientation angle.
1512
+
1513
+ Examples
1514
+ ========
1515
+
1516
+ >>> from sympy import RegularPolygon, Point
1517
+ >>> r = RegularPolygon(Point(0, 0), 5, 3)
1518
+ >>> r.args
1519
+ (Point2D(0, 0), 5, 3, 0)
1520
+ """
1521
+ return self._center, self._radius, self._n, self._rot
1522
+
1523
+ def __str__(self):
1524
+ return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args)
1525
+
1526
+ def __repr__(self):
1527
+ return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args)
1528
+
1529
+ @property
1530
+ def area(self):
1531
+ """Returns the area.
1532
+
1533
+ Examples
1534
+ ========
1535
+
1536
+ >>> from sympy import RegularPolygon
1537
+ >>> square = RegularPolygon((0, 0), 1, 4)
1538
+ >>> square.area
1539
+ 2
1540
+ >>> _ == square.length**2
1541
+ True
1542
+ """
1543
+ c, r, n, rot = self.args
1544
+ return sign(r)*n*self.length**2/(4*tan(pi/n))
1545
+
1546
+ @property
1547
+ def length(self):
1548
+ """Returns the length of the sides.
1549
+
1550
+ The half-length of the side and the apothem form two legs
1551
+ of a right triangle whose hypotenuse is the radius of the
1552
+ regular polygon.
1553
+
1554
+ Examples
1555
+ ========
1556
+
1557
+ >>> from sympy import RegularPolygon
1558
+ >>> from sympy import sqrt
1559
+ >>> s = square_in_unit_circle = RegularPolygon((0, 0), 1, 4)
1560
+ >>> s.length
1561
+ sqrt(2)
1562
+ >>> sqrt((_/2)**2 + s.apothem**2) == s.radius
1563
+ True
1564
+
1565
+ """
1566
+ return self.radius*2*sin(pi/self._n)
1567
+
1568
+ @property
1569
+ def center(self):
1570
+ """The center of the RegularPolygon
1571
+
1572
+ This is also the center of the circumscribing circle.
1573
+
1574
+ Returns
1575
+ =======
1576
+
1577
+ center : Point
1578
+
1579
+ See Also
1580
+ ========
1581
+
1582
+ sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.center
1583
+
1584
+ Examples
1585
+ ========
1586
+
1587
+ >>> from sympy import RegularPolygon, Point
1588
+ >>> rp = RegularPolygon(Point(0, 0), 5, 4)
1589
+ >>> rp.center
1590
+ Point2D(0, 0)
1591
+ """
1592
+ return self._center
1593
+
1594
+ centroid = center
1595
+
1596
+ @property
1597
+ def circumcenter(self):
1598
+ """
1599
+ Alias for center.
1600
+
1601
+ Examples
1602
+ ========
1603
+
1604
+ >>> from sympy import RegularPolygon, Point
1605
+ >>> rp = RegularPolygon(Point(0, 0), 5, 4)
1606
+ >>> rp.circumcenter
1607
+ Point2D(0, 0)
1608
+ """
1609
+ return self.center
1610
+
1611
+ @property
1612
+ def radius(self):
1613
+ """Radius of the RegularPolygon
1614
+
1615
+ This is also the radius of the circumscribing circle.
1616
+
1617
+ Returns
1618
+ =======
1619
+
1620
+ radius : number or instance of Basic
1621
+
1622
+ See Also
1623
+ ========
1624
+
1625
+ sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius
1626
+
1627
+ Examples
1628
+ ========
1629
+
1630
+ >>> from sympy import Symbol
1631
+ >>> from sympy import RegularPolygon, Point
1632
+ >>> radius = Symbol('r')
1633
+ >>> rp = RegularPolygon(Point(0, 0), radius, 4)
1634
+ >>> rp.radius
1635
+ r
1636
+
1637
+ """
1638
+ return self._radius
1639
+
1640
+ @property
1641
+ def circumradius(self):
1642
+ """
1643
+ Alias for radius.
1644
+
1645
+ Examples
1646
+ ========
1647
+
1648
+ >>> from sympy import Symbol
1649
+ >>> from sympy import RegularPolygon, Point
1650
+ >>> radius = Symbol('r')
1651
+ >>> rp = RegularPolygon(Point(0, 0), radius, 4)
1652
+ >>> rp.circumradius
1653
+ r
1654
+ """
1655
+ return self.radius
1656
+
1657
+ @property
1658
+ def rotation(self):
1659
+ """CCW angle by which the RegularPolygon is rotated
1660
+
1661
+ Returns
1662
+ =======
1663
+
1664
+ rotation : number or instance of Basic
1665
+
1666
+ Examples
1667
+ ========
1668
+
1669
+ >>> from sympy import pi
1670
+ >>> from sympy.abc import a
1671
+ >>> from sympy import RegularPolygon, Point
1672
+ >>> RegularPolygon(Point(0, 0), 3, 4, pi/4).rotation
1673
+ pi/4
1674
+
1675
+ Numerical rotation angles are made canonical:
1676
+
1677
+ >>> RegularPolygon(Point(0, 0), 3, 4, a).rotation
1678
+ a
1679
+ >>> RegularPolygon(Point(0, 0), 3, 4, pi).rotation
1680
+ 0
1681
+
1682
+ """
1683
+ return self._rot
1684
+
1685
+ @property
1686
+ def apothem(self):
1687
+ """The inradius of the RegularPolygon.
1688
+
1689
+ The apothem/inradius is the radius of the inscribed circle.
1690
+
1691
+ Returns
1692
+ =======
1693
+
1694
+ apothem : number or instance of Basic
1695
+
1696
+ See Also
1697
+ ========
1698
+
1699
+ sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius
1700
+
1701
+ Examples
1702
+ ========
1703
+
1704
+ >>> from sympy import Symbol
1705
+ >>> from sympy import RegularPolygon, Point
1706
+ >>> radius = Symbol('r')
1707
+ >>> rp = RegularPolygon(Point(0, 0), radius, 4)
1708
+ >>> rp.apothem
1709
+ sqrt(2)*r/2
1710
+
1711
+ """
1712
+ return self.radius * cos(S.Pi/self._n)
1713
+
1714
+ @property
1715
+ def inradius(self):
1716
+ """
1717
+ Alias for apothem.
1718
+
1719
+ Examples
1720
+ ========
1721
+
1722
+ >>> from sympy import Symbol
1723
+ >>> from sympy import RegularPolygon, Point
1724
+ >>> radius = Symbol('r')
1725
+ >>> rp = RegularPolygon(Point(0, 0), radius, 4)
1726
+ >>> rp.inradius
1727
+ sqrt(2)*r/2
1728
+ """
1729
+ return self.apothem
1730
+
1731
+ @property
1732
+ def interior_angle(self):
1733
+ """Measure of the interior angles.
1734
+
1735
+ Returns
1736
+ =======
1737
+
1738
+ interior_angle : number
1739
+
1740
+ See Also
1741
+ ========
1742
+
1743
+ sympy.geometry.line.LinearEntity.angle_between
1744
+
1745
+ Examples
1746
+ ========
1747
+
1748
+ >>> from sympy import RegularPolygon, Point
1749
+ >>> rp = RegularPolygon(Point(0, 0), 4, 8)
1750
+ >>> rp.interior_angle
1751
+ 3*pi/4
1752
+
1753
+ """
1754
+ return (self._n - 2)*S.Pi/self._n
1755
+
1756
+ @property
1757
+ def exterior_angle(self):
1758
+ """Measure of the exterior angles.
1759
+
1760
+ Returns
1761
+ =======
1762
+
1763
+ exterior_angle : number
1764
+
1765
+ See Also
1766
+ ========
1767
+
1768
+ sympy.geometry.line.LinearEntity.angle_between
1769
+
1770
+ Examples
1771
+ ========
1772
+
1773
+ >>> from sympy import RegularPolygon, Point
1774
+ >>> rp = RegularPolygon(Point(0, 0), 4, 8)
1775
+ >>> rp.exterior_angle
1776
+ pi/4
1777
+
1778
+ """
1779
+ return 2*S.Pi/self._n
1780
+
1781
+ @property
1782
+ def circumcircle(self):
1783
+ """The circumcircle of the RegularPolygon.
1784
+
1785
+ Returns
1786
+ =======
1787
+
1788
+ circumcircle : Circle
1789
+
1790
+ See Also
1791
+ ========
1792
+
1793
+ circumcenter, sympy.geometry.ellipse.Circle
1794
+
1795
+ Examples
1796
+ ========
1797
+
1798
+ >>> from sympy import RegularPolygon, Point
1799
+ >>> rp = RegularPolygon(Point(0, 0), 4, 8)
1800
+ >>> rp.circumcircle
1801
+ Circle(Point2D(0, 0), 4)
1802
+
1803
+ """
1804
+ return Circle(self.center, self.radius)
1805
+
1806
+ @property
1807
+ def incircle(self):
1808
+ """The incircle of the RegularPolygon.
1809
+
1810
+ Returns
1811
+ =======
1812
+
1813
+ incircle : Circle
1814
+
1815
+ See Also
1816
+ ========
1817
+
1818
+ inradius, sympy.geometry.ellipse.Circle
1819
+
1820
+ Examples
1821
+ ========
1822
+
1823
+ >>> from sympy import RegularPolygon, Point
1824
+ >>> rp = RegularPolygon(Point(0, 0), 4, 7)
1825
+ >>> rp.incircle
1826
+ Circle(Point2D(0, 0), 4*cos(pi/7))
1827
+
1828
+ """
1829
+ return Circle(self.center, self.apothem)
1830
+
1831
+ @property
1832
+ def angles(self):
1833
+ """
1834
+ Returns a dictionary with keys, the vertices of the Polygon,
1835
+ and values, the interior angle at each vertex.
1836
+
1837
+ Examples
1838
+ ========
1839
+
1840
+ >>> from sympy import RegularPolygon, Point
1841
+ >>> r = RegularPolygon(Point(0, 0), 5, 3)
1842
+ >>> r.angles
1843
+ {Point2D(-5/2, -5*sqrt(3)/2): pi/3,
1844
+ Point2D(-5/2, 5*sqrt(3)/2): pi/3,
1845
+ Point2D(5, 0): pi/3}
1846
+ """
1847
+ ret = {}
1848
+ ang = self.interior_angle
1849
+ for v in self.vertices:
1850
+ ret[v] = ang
1851
+ return ret
1852
+
1853
+ def encloses_point(self, p):
1854
+ """
1855
+ Return True if p is enclosed by (is inside of) self.
1856
+
1857
+ Notes
1858
+ =====
1859
+
1860
+ Being on the border of self is considered False.
1861
+
1862
+ The general Polygon.encloses_point method is called only if
1863
+ a point is not within or beyond the incircle or circumcircle,
1864
+ respectively.
1865
+
1866
+ Parameters
1867
+ ==========
1868
+
1869
+ p : Point
1870
+
1871
+ Returns
1872
+ =======
1873
+
1874
+ encloses_point : True, False or None
1875
+
1876
+ See Also
1877
+ ========
1878
+
1879
+ sympy.geometry.ellipse.Ellipse.encloses_point
1880
+
1881
+ Examples
1882
+ ========
1883
+
1884
+ >>> from sympy import RegularPolygon, S, Point, Symbol
1885
+ >>> p = RegularPolygon((0, 0), 3, 4)
1886
+ >>> p.encloses_point(Point(0, 0))
1887
+ True
1888
+ >>> r, R = p.inradius, p.circumradius
1889
+ >>> p.encloses_point(Point((r + R)/2, 0))
1890
+ True
1891
+ >>> p.encloses_point(Point(R/2, R/2 + (R - r)/10))
1892
+ False
1893
+ >>> t = Symbol('t', real=True)
1894
+ >>> p.encloses_point(p.arbitrary_point().subs(t, S.Half))
1895
+ False
1896
+ >>> p.encloses_point(Point(5, 5))
1897
+ False
1898
+
1899
+ """
1900
+
1901
+ c = self.center
1902
+ d = Segment(c, p).length
1903
+ if d >= self.radius:
1904
+ return False
1905
+ elif d < self.inradius:
1906
+ return True
1907
+ else:
1908
+ # now enumerate the RegularPolygon like a general polygon.
1909
+ return Polygon.encloses_point(self, p)
1910
+
1911
+ def spin(self, angle):
1912
+ """Increment *in place* the virtual Polygon's rotation by ccw angle.
1913
+
1914
+ See also: rotate method which moves the center.
1915
+
1916
+ >>> from sympy import Polygon, Point, pi
1917
+ >>> r = Polygon(Point(0,0), 1, n=3)
1918
+ >>> r.vertices[0]
1919
+ Point2D(1, 0)
1920
+ >>> r.spin(pi/6)
1921
+ >>> r.vertices[0]
1922
+ Point2D(sqrt(3)/2, 1/2)
1923
+
1924
+ See Also
1925
+ ========
1926
+
1927
+ rotation
1928
+ rotate : Creates a copy of the RegularPolygon rotated about a Point
1929
+
1930
+ """
1931
+ self._rot += angle
1932
+
1933
+ def rotate(self, angle, pt=None):
1934
+ """Override GeometryEntity.rotate to first rotate the RegularPolygon
1935
+ about its center.
1936
+
1937
+ >>> from sympy import Point, RegularPolygon, pi
1938
+ >>> t = RegularPolygon(Point(1, 0), 1, 3)
1939
+ >>> t.vertices[0] # vertex on x-axis
1940
+ Point2D(2, 0)
1941
+ >>> t.rotate(pi/2).vertices[0] # vertex on y axis now
1942
+ Point2D(0, 2)
1943
+
1944
+ See Also
1945
+ ========
1946
+
1947
+ rotation
1948
+ spin : Rotates a RegularPolygon in place
1949
+
1950
+ """
1951
+
1952
+ r = type(self)(*self.args) # need a copy or else changes are in-place
1953
+ r._rot += angle
1954
+ return GeometryEntity.rotate(r, angle, pt)
1955
+
1956
+ def scale(self, x=1, y=1, pt=None):
1957
+ """Override GeometryEntity.scale since it is the radius that must be
1958
+ scaled (if x == y) or else a new Polygon must be returned.
1959
+
1960
+ >>> from sympy import RegularPolygon
1961
+
1962
+ Symmetric scaling returns a RegularPolygon:
1963
+
1964
+ >>> RegularPolygon((0, 0), 1, 4).scale(2, 2)
1965
+ RegularPolygon(Point2D(0, 0), 2, 4, 0)
1966
+
1967
+ Asymmetric scaling returns a kite as a Polygon:
1968
+
1969
+ >>> RegularPolygon((0, 0), 1, 4).scale(2, 1)
1970
+ Polygon(Point2D(2, 0), Point2D(0, 1), Point2D(-2, 0), Point2D(0, -1))
1971
+
1972
+ """
1973
+ if pt:
1974
+ pt = Point(pt, dim=2)
1975
+ return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
1976
+ if x != y:
1977
+ return Polygon(*self.vertices).scale(x, y)
1978
+ c, r, n, rot = self.args
1979
+ r *= x
1980
+ return self.func(c, r, n, rot)
1981
+
1982
+ def reflect(self, line):
1983
+ """Override GeometryEntity.reflect since this is not made of only
1984
+ points.
1985
+
1986
+ Examples
1987
+ ========
1988
+
1989
+ >>> from sympy import RegularPolygon, Line
1990
+
1991
+ >>> RegularPolygon((0, 0), 1, 4).reflect(Line((0, 1), slope=-2))
1992
+ RegularPolygon(Point2D(4/5, 2/5), -1, 4, atan(4/3))
1993
+
1994
+ """
1995
+ c, r, n, rot = self.args
1996
+ v = self.vertices[0]
1997
+ d = v - c
1998
+ cc = c.reflect(line)
1999
+ vv = v.reflect(line)
2000
+ dd = vv - cc
2001
+ # calculate rotation about the new center
2002
+ # which will align the vertices
2003
+ l1 = Ray((0, 0), dd)
2004
+ l2 = Ray((0, 0), d)
2005
+ ang = l1.closing_angle(l2)
2006
+ rot += ang
2007
+ # change sign of radius as point traversal is reversed
2008
+ return self.func(cc, -r, n, rot)
2009
+
2010
+ @property
2011
+ def vertices(self):
2012
+ """The vertices of the RegularPolygon.
2013
+
2014
+ Returns
2015
+ =======
2016
+
2017
+ vertices : list
2018
+ Each vertex is a Point.
2019
+
2020
+ See Also
2021
+ ========
2022
+
2023
+ sympy.geometry.point.Point
2024
+
2025
+ Examples
2026
+ ========
2027
+
2028
+ >>> from sympy import RegularPolygon, Point
2029
+ >>> rp = RegularPolygon(Point(0, 0), 5, 4)
2030
+ >>> rp.vertices
2031
+ [Point2D(5, 0), Point2D(0, 5), Point2D(-5, 0), Point2D(0, -5)]
2032
+
2033
+ """
2034
+ c = self._center
2035
+ r = abs(self._radius)
2036
+ rot = self._rot
2037
+ v = 2*S.Pi/self._n
2038
+
2039
+ return [Point(c.x + r*cos(k*v + rot), c.y + r*sin(k*v + rot))
2040
+ for k in range(self._n)]
2041
+
2042
+ def __eq__(self, o):
2043
+ if not isinstance(o, Polygon):
2044
+ return False
2045
+ elif not isinstance(o, RegularPolygon):
2046
+ return Polygon.__eq__(o, self)
2047
+ return self.args == o.args
2048
+
2049
+ def __hash__(self):
2050
+ return super().__hash__()
2051
+
2052
+
2053
+ class Triangle(Polygon):
2054
+ """
2055
+ A polygon with three vertices and three sides.
2056
+
2057
+ Parameters
2058
+ ==========
2059
+
2060
+ points : sequence of Points
2061
+ keyword: asa, sas, or sss to specify sides/angles of the triangle
2062
+
2063
+ Attributes
2064
+ ==========
2065
+
2066
+ vertices
2067
+ altitudes
2068
+ orthocenter
2069
+ circumcenter
2070
+ circumradius
2071
+ circumcircle
2072
+ inradius
2073
+ incircle
2074
+ exradii
2075
+ medians
2076
+ medial
2077
+ nine_point_circle
2078
+
2079
+ Raises
2080
+ ======
2081
+
2082
+ GeometryError
2083
+ If the number of vertices is not equal to three, or one of the vertices
2084
+ is not a Point, or a valid keyword is not given.
2085
+
2086
+ See Also
2087
+ ========
2088
+
2089
+ sympy.geometry.point.Point, Polygon
2090
+
2091
+ Examples
2092
+ ========
2093
+
2094
+ >>> from sympy import Triangle, Point
2095
+ >>> Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2096
+ Triangle(Point2D(0, 0), Point2D(4, 0), Point2D(4, 3))
2097
+
2098
+ Keywords sss, sas, or asa can be used to give the desired
2099
+ side lengths (in order) and interior angles (in degrees) that
2100
+ define the triangle:
2101
+
2102
+ >>> Triangle(sss=(3, 4, 5))
2103
+ Triangle(Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
2104
+ >>> Triangle(asa=(30, 1, 30))
2105
+ Triangle(Point2D(0, 0), Point2D(1, 0), Point2D(1/2, sqrt(3)/6))
2106
+ >>> Triangle(sas=(1, 45, 2))
2107
+ Triangle(Point2D(0, 0), Point2D(2, 0), Point2D(sqrt(2)/2, sqrt(2)/2))
2108
+
2109
+ """
2110
+
2111
+ def __new__(cls, *args, **kwargs):
2112
+ if len(args) != 3:
2113
+ if 'sss' in kwargs:
2114
+ return _sss(*[simplify(a) for a in kwargs['sss']])
2115
+ if 'asa' in kwargs:
2116
+ return _asa(*[simplify(a) for a in kwargs['asa']])
2117
+ if 'sas' in kwargs:
2118
+ return _sas(*[simplify(a) for a in kwargs['sas']])
2119
+ msg = "Triangle instantiates with three points or a valid keyword."
2120
+ raise GeometryError(msg)
2121
+
2122
+ vertices = [Point(a, dim=2, **kwargs) for a in args]
2123
+
2124
+ # remove consecutive duplicates
2125
+ nodup = []
2126
+ for p in vertices:
2127
+ if nodup and p == nodup[-1]:
2128
+ continue
2129
+ nodup.append(p)
2130
+ if len(nodup) > 1 and nodup[-1] == nodup[0]:
2131
+ nodup.pop() # last point was same as first
2132
+
2133
+ # remove collinear points
2134
+ i = -3
2135
+ while i < len(nodup) - 3 and len(nodup) > 2:
2136
+ a, b, c = sorted(
2137
+ [nodup[i], nodup[i + 1], nodup[i + 2]], key=default_sort_key)
2138
+ if Point.is_collinear(a, b, c):
2139
+ nodup[i] = a
2140
+ nodup[i + 1] = None
2141
+ nodup.pop(i + 1)
2142
+ i += 1
2143
+
2144
+ vertices = list(filter(lambda x: x is not None, nodup))
2145
+
2146
+ if len(vertices) == 3:
2147
+ return GeometryEntity.__new__(cls, *vertices, **kwargs)
2148
+ elif len(vertices) == 2:
2149
+ return Segment(*vertices, **kwargs)
2150
+ else:
2151
+ return Point(*vertices, **kwargs)
2152
+
2153
+ @property
2154
+ def vertices(self):
2155
+ """The triangle's vertices
2156
+
2157
+ Returns
2158
+ =======
2159
+
2160
+ vertices : tuple
2161
+ Each element in the tuple is a Point
2162
+
2163
+ See Also
2164
+ ========
2165
+
2166
+ sympy.geometry.point.Point
2167
+
2168
+ Examples
2169
+ ========
2170
+
2171
+ >>> from sympy import Triangle, Point
2172
+ >>> t = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2173
+ >>> t.vertices
2174
+ (Point2D(0, 0), Point2D(4, 0), Point2D(4, 3))
2175
+
2176
+ """
2177
+ return self.args
2178
+
2179
+ def is_similar(t1, t2):
2180
+ """Is another triangle similar to this one.
2181
+
2182
+ Two triangles are similar if one can be uniformly scaled to the other.
2183
+
2184
+ Parameters
2185
+ ==========
2186
+
2187
+ other: Triangle
2188
+
2189
+ Returns
2190
+ =======
2191
+
2192
+ is_similar : boolean
2193
+
2194
+ See Also
2195
+ ========
2196
+
2197
+ sympy.geometry.entity.GeometryEntity.is_similar
2198
+
2199
+ Examples
2200
+ ========
2201
+
2202
+ >>> from sympy import Triangle, Point
2203
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2204
+ >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -3))
2205
+ >>> t1.is_similar(t2)
2206
+ True
2207
+
2208
+ >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -4))
2209
+ >>> t1.is_similar(t2)
2210
+ False
2211
+
2212
+ """
2213
+ if not isinstance(t2, Polygon):
2214
+ return False
2215
+
2216
+ s1_1, s1_2, s1_3 = [side.length for side in t1.sides]
2217
+ s2 = [side.length for side in t2.sides]
2218
+
2219
+ def _are_similar(u1, u2, u3, v1, v2, v3):
2220
+ e1 = simplify(u1/v1)
2221
+ e2 = simplify(u2/v2)
2222
+ e3 = simplify(u3/v3)
2223
+ return bool(e1 == e2) and bool(e2 == e3)
2224
+
2225
+ # There's only 6 permutations, so write them out
2226
+ return _are_similar(s1_1, s1_2, s1_3, *s2) or \
2227
+ _are_similar(s1_1, s1_3, s1_2, *s2) or \
2228
+ _are_similar(s1_2, s1_1, s1_3, *s2) or \
2229
+ _are_similar(s1_2, s1_3, s1_1, *s2) or \
2230
+ _are_similar(s1_3, s1_1, s1_2, *s2) or \
2231
+ _are_similar(s1_3, s1_2, s1_1, *s2)
2232
+
2233
+ def is_equilateral(self):
2234
+ """Are all the sides the same length?
2235
+
2236
+ Returns
2237
+ =======
2238
+
2239
+ is_equilateral : boolean
2240
+
2241
+ See Also
2242
+ ========
2243
+
2244
+ sympy.geometry.entity.GeometryEntity.is_similar, RegularPolygon
2245
+ is_isosceles, is_right, is_scalene
2246
+
2247
+ Examples
2248
+ ========
2249
+
2250
+ >>> from sympy import Triangle, Point
2251
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2252
+ >>> t1.is_equilateral()
2253
+ False
2254
+
2255
+ >>> from sympy import sqrt
2256
+ >>> t2 = Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3)))
2257
+ >>> t2.is_equilateral()
2258
+ True
2259
+
2260
+ """
2261
+ return not has_variety(s.length for s in self.sides)
2262
+
2263
+ def is_isosceles(self):
2264
+ """Are two or more of the sides the same length?
2265
+
2266
+ Returns
2267
+ =======
2268
+
2269
+ is_isosceles : boolean
2270
+
2271
+ See Also
2272
+ ========
2273
+
2274
+ is_equilateral, is_right, is_scalene
2275
+
2276
+ Examples
2277
+ ========
2278
+
2279
+ >>> from sympy import Triangle, Point
2280
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(2, 4))
2281
+ >>> t1.is_isosceles()
2282
+ True
2283
+
2284
+ """
2285
+ return has_dups(s.length for s in self.sides)
2286
+
2287
+ def is_scalene(self):
2288
+ """Are all the sides of the triangle of different lengths?
2289
+
2290
+ Returns
2291
+ =======
2292
+
2293
+ is_scalene : boolean
2294
+
2295
+ See Also
2296
+ ========
2297
+
2298
+ is_equilateral, is_isosceles, is_right
2299
+
2300
+ Examples
2301
+ ========
2302
+
2303
+ >>> from sympy import Triangle, Point
2304
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(1, 4))
2305
+ >>> t1.is_scalene()
2306
+ True
2307
+
2308
+ """
2309
+ return not has_dups(s.length for s in self.sides)
2310
+
2311
+ def is_right(self):
2312
+ """Is the triangle right-angled.
2313
+
2314
+ Returns
2315
+ =======
2316
+
2317
+ is_right : boolean
2318
+
2319
+ See Also
2320
+ ========
2321
+
2322
+ sympy.geometry.line.LinearEntity.is_perpendicular
2323
+ is_equilateral, is_isosceles, is_scalene
2324
+
2325
+ Examples
2326
+ ========
2327
+
2328
+ >>> from sympy import Triangle, Point
2329
+ >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
2330
+ >>> t1.is_right()
2331
+ True
2332
+
2333
+ """
2334
+ s = self.sides
2335
+ return Segment.is_perpendicular(s[0], s[1]) or \
2336
+ Segment.is_perpendicular(s[1], s[2]) or \
2337
+ Segment.is_perpendicular(s[0], s[2])
2338
+
2339
+ @property
2340
+ def altitudes(self):
2341
+ """The altitudes of the triangle.
2342
+
2343
+ An altitude of a triangle is a segment through a vertex,
2344
+ perpendicular to the opposite side, with length being the
2345
+ height of the vertex measured from the line containing the side.
2346
+
2347
+ Returns
2348
+ =======
2349
+
2350
+ altitudes : dict
2351
+ The dictionary consists of keys which are vertices and values
2352
+ which are Segments.
2353
+
2354
+ See Also
2355
+ ========
2356
+
2357
+ sympy.geometry.point.Point, sympy.geometry.line.Segment.length
2358
+
2359
+ Examples
2360
+ ========
2361
+
2362
+ >>> from sympy import Point, Triangle
2363
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2364
+ >>> t = Triangle(p1, p2, p3)
2365
+ >>> t.altitudes[p1]
2366
+ Segment2D(Point2D(0, 0), Point2D(1/2, 1/2))
2367
+
2368
+ """
2369
+ s = self.sides
2370
+ v = self.vertices
2371
+ return {v[0]: s[1].perpendicular_segment(v[0]),
2372
+ v[1]: s[2].perpendicular_segment(v[1]),
2373
+ v[2]: s[0].perpendicular_segment(v[2])}
2374
+
2375
+ @property
2376
+ def orthocenter(self):
2377
+ """The orthocenter of the triangle.
2378
+
2379
+ The orthocenter is the intersection of the altitudes of a triangle.
2380
+ It may lie inside, outside or on the triangle.
2381
+
2382
+ Returns
2383
+ =======
2384
+
2385
+ orthocenter : Point
2386
+
2387
+ See Also
2388
+ ========
2389
+
2390
+ sympy.geometry.point.Point
2391
+
2392
+ Examples
2393
+ ========
2394
+
2395
+ >>> from sympy import Point, Triangle
2396
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2397
+ >>> t = Triangle(p1, p2, p3)
2398
+ >>> t.orthocenter
2399
+ Point2D(0, 0)
2400
+
2401
+ """
2402
+ a = self.altitudes
2403
+ v = self.vertices
2404
+ return Line(a[v[0]]).intersection(Line(a[v[1]]))[0]
2405
+
2406
+ @property
2407
+ def circumcenter(self):
2408
+ """The circumcenter of the triangle
2409
+
2410
+ The circumcenter is the center of the circumcircle.
2411
+
2412
+ Returns
2413
+ =======
2414
+
2415
+ circumcenter : Point
2416
+
2417
+ See Also
2418
+ ========
2419
+
2420
+ sympy.geometry.point.Point
2421
+
2422
+ Examples
2423
+ ========
2424
+
2425
+ >>> from sympy import Point, Triangle
2426
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2427
+ >>> t = Triangle(p1, p2, p3)
2428
+ >>> t.circumcenter
2429
+ Point2D(1/2, 1/2)
2430
+ """
2431
+ a, b, c = [x.perpendicular_bisector() for x in self.sides]
2432
+ return a.intersection(b)[0]
2433
+
2434
+ @property
2435
+ def circumradius(self):
2436
+ """The radius of the circumcircle of the triangle.
2437
+
2438
+ Returns
2439
+ =======
2440
+
2441
+ circumradius : number of Basic instance
2442
+
2443
+ See Also
2444
+ ========
2445
+
2446
+ sympy.geometry.ellipse.Circle.radius
2447
+
2448
+ Examples
2449
+ ========
2450
+
2451
+ >>> from sympy import Symbol
2452
+ >>> from sympy import Point, Triangle
2453
+ >>> a = Symbol('a')
2454
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, a)
2455
+ >>> t = Triangle(p1, p2, p3)
2456
+ >>> t.circumradius
2457
+ sqrt(a**2/4 + 1/4)
2458
+ """
2459
+ return Point.distance(self.circumcenter, self.vertices[0])
2460
+
2461
+ @property
2462
+ def circumcircle(self):
2463
+ """The circle which passes through the three vertices of the triangle.
2464
+
2465
+ Returns
2466
+ =======
2467
+
2468
+ circumcircle : Circle
2469
+
2470
+ See Also
2471
+ ========
2472
+
2473
+ sympy.geometry.ellipse.Circle
2474
+
2475
+ Examples
2476
+ ========
2477
+
2478
+ >>> from sympy import Point, Triangle
2479
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2480
+ >>> t = Triangle(p1, p2, p3)
2481
+ >>> t.circumcircle
2482
+ Circle(Point2D(1/2, 1/2), sqrt(2)/2)
2483
+
2484
+ """
2485
+ return Circle(self.circumcenter, self.circumradius)
2486
+
2487
+ def bisectors(self):
2488
+ """The angle bisectors of the triangle.
2489
+
2490
+ An angle bisector of a triangle is a straight line through a vertex
2491
+ which cuts the corresponding angle in half.
2492
+
2493
+ Returns
2494
+ =======
2495
+
2496
+ bisectors : dict
2497
+ Each key is a vertex (Point) and each value is the corresponding
2498
+ bisector (Segment).
2499
+
2500
+ See Also
2501
+ ========
2502
+
2503
+ sympy.geometry.point.Point, sympy.geometry.line.Segment
2504
+
2505
+ Examples
2506
+ ========
2507
+
2508
+ >>> from sympy import Point, Triangle, Segment
2509
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2510
+ >>> t = Triangle(p1, p2, p3)
2511
+ >>> from sympy import sqrt
2512
+ >>> t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1))
2513
+ True
2514
+
2515
+ """
2516
+ # use lines containing sides so containment check during
2517
+ # intersection calculation can be avoided, thus reducing
2518
+ # the processing time for calculating the bisectors
2519
+ s = [Line(l) for l in self.sides]
2520
+ v = self.vertices
2521
+ c = self.incenter
2522
+ l1 = Segment(v[0], Line(v[0], c).intersection(s[1])[0])
2523
+ l2 = Segment(v[1], Line(v[1], c).intersection(s[2])[0])
2524
+ l3 = Segment(v[2], Line(v[2], c).intersection(s[0])[0])
2525
+ return {v[0]: l1, v[1]: l2, v[2]: l3}
2526
+
2527
+ @property
2528
+ def incenter(self):
2529
+ """The center of the incircle.
2530
+
2531
+ The incircle is the circle which lies inside the triangle and touches
2532
+ all three sides.
2533
+
2534
+ Returns
2535
+ =======
2536
+
2537
+ incenter : Point
2538
+
2539
+ See Also
2540
+ ========
2541
+
2542
+ incircle, sympy.geometry.point.Point
2543
+
2544
+ Examples
2545
+ ========
2546
+
2547
+ >>> from sympy import Point, Triangle
2548
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2549
+ >>> t = Triangle(p1, p2, p3)
2550
+ >>> t.incenter
2551
+ Point2D(1 - sqrt(2)/2, 1 - sqrt(2)/2)
2552
+
2553
+ """
2554
+ s = self.sides
2555
+ l = Matrix([s[i].length for i in [1, 2, 0]])
2556
+ p = sum(l)
2557
+ v = self.vertices
2558
+ x = simplify(l.dot(Matrix([vi.x for vi in v]))/p)
2559
+ y = simplify(l.dot(Matrix([vi.y for vi in v]))/p)
2560
+ return Point(x, y)
2561
+
2562
+ @property
2563
+ def inradius(self):
2564
+ """The radius of the incircle.
2565
+
2566
+ Returns
2567
+ =======
2568
+
2569
+ inradius : number of Basic instance
2570
+
2571
+ See Also
2572
+ ========
2573
+
2574
+ incircle, sympy.geometry.ellipse.Circle.radius
2575
+
2576
+ Examples
2577
+ ========
2578
+
2579
+ >>> from sympy import Point, Triangle
2580
+ >>> p1, p2, p3 = Point(0, 0), Point(4, 0), Point(0, 3)
2581
+ >>> t = Triangle(p1, p2, p3)
2582
+ >>> t.inradius
2583
+ 1
2584
+
2585
+ """
2586
+ return simplify(2 * self.area / self.perimeter)
2587
+
2588
+ @property
2589
+ def incircle(self):
2590
+ """The incircle of the triangle.
2591
+
2592
+ The incircle is the circle which lies inside the triangle and touches
2593
+ all three sides.
2594
+
2595
+ Returns
2596
+ =======
2597
+
2598
+ incircle : Circle
2599
+
2600
+ See Also
2601
+ ========
2602
+
2603
+ sympy.geometry.ellipse.Circle
2604
+
2605
+ Examples
2606
+ ========
2607
+
2608
+ >>> from sympy import Point, Triangle
2609
+ >>> p1, p2, p3 = Point(0, 0), Point(2, 0), Point(0, 2)
2610
+ >>> t = Triangle(p1, p2, p3)
2611
+ >>> t.incircle
2612
+ Circle(Point2D(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2))
2613
+
2614
+ """
2615
+ return Circle(self.incenter, self.inradius)
2616
+
2617
+ @property
2618
+ def exradii(self):
2619
+ """The radius of excircles of a triangle.
2620
+
2621
+ An excircle of the triangle is a circle lying outside the triangle,
2622
+ tangent to one of its sides and tangent to the extensions of the
2623
+ other two.
2624
+
2625
+ Returns
2626
+ =======
2627
+
2628
+ exradii : dict
2629
+
2630
+ See Also
2631
+ ========
2632
+
2633
+ sympy.geometry.polygon.Triangle.inradius
2634
+
2635
+ Examples
2636
+ ========
2637
+
2638
+ The exradius touches the side of the triangle to which it is keyed, e.g.
2639
+ the exradius touching side 2 is:
2640
+
2641
+ >>> from sympy import Point, Triangle
2642
+ >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2)
2643
+ >>> t = Triangle(p1, p2, p3)
2644
+ >>> t.exradii[t.sides[2]]
2645
+ -2 + sqrt(10)
2646
+
2647
+ References
2648
+ ==========
2649
+
2650
+ .. [1] https://mathworld.wolfram.com/Exradius.html
2651
+ .. [2] https://mathworld.wolfram.com/Excircles.html
2652
+
2653
+ """
2654
+
2655
+ side = self.sides
2656
+ a = side[0].length
2657
+ b = side[1].length
2658
+ c = side[2].length
2659
+ s = (a+b+c)/2
2660
+ area = self.area
2661
+ exradii = {self.sides[0]: simplify(area/(s-a)),
2662
+ self.sides[1]: simplify(area/(s-b)),
2663
+ self.sides[2]: simplify(area/(s-c))}
2664
+
2665
+ return exradii
2666
+
2667
+ @property
2668
+ def excenters(self):
2669
+ """Excenters of the triangle.
2670
+
2671
+ An excenter is the center of a circle that is tangent to a side of the
2672
+ triangle and the extensions of the other two sides.
2673
+
2674
+ Returns
2675
+ =======
2676
+
2677
+ excenters : dict
2678
+
2679
+
2680
+ Examples
2681
+ ========
2682
+
2683
+ The excenters are keyed to the side of the triangle to which their corresponding
2684
+ excircle is tangent: The center is keyed, e.g. the excenter of a circle touching
2685
+ side 0 is:
2686
+
2687
+ >>> from sympy import Point, Triangle
2688
+ >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2)
2689
+ >>> t = Triangle(p1, p2, p3)
2690
+ >>> t.excenters[t.sides[0]]
2691
+ Point2D(12*sqrt(10), 2/3 + sqrt(10)/3)
2692
+
2693
+ See Also
2694
+ ========
2695
+
2696
+ sympy.geometry.polygon.Triangle.exradii
2697
+
2698
+ References
2699
+ ==========
2700
+
2701
+ .. [1] https://mathworld.wolfram.com/Excircles.html
2702
+
2703
+ """
2704
+
2705
+ s = self.sides
2706
+ v = self.vertices
2707
+ a = s[0].length
2708
+ b = s[1].length
2709
+ c = s[2].length
2710
+ x = [v[0].x, v[1].x, v[2].x]
2711
+ y = [v[0].y, v[1].y, v[2].y]
2712
+
2713
+ exc_coords = {
2714
+ "x1": simplify(-a*x[0]+b*x[1]+c*x[2]/(-a+b+c)),
2715
+ "x2": simplify(a*x[0]-b*x[1]+c*x[2]/(a-b+c)),
2716
+ "x3": simplify(a*x[0]+b*x[1]-c*x[2]/(a+b-c)),
2717
+ "y1": simplify(-a*y[0]+b*y[1]+c*y[2]/(-a+b+c)),
2718
+ "y2": simplify(a*y[0]-b*y[1]+c*y[2]/(a-b+c)),
2719
+ "y3": simplify(a*y[0]+b*y[1]-c*y[2]/(a+b-c))
2720
+ }
2721
+
2722
+ excenters = {
2723
+ s[0]: Point(exc_coords["x1"], exc_coords["y1"]),
2724
+ s[1]: Point(exc_coords["x2"], exc_coords["y2"]),
2725
+ s[2]: Point(exc_coords["x3"], exc_coords["y3"])
2726
+ }
2727
+
2728
+ return excenters
2729
+
2730
+ @property
2731
+ def medians(self):
2732
+ """The medians of the triangle.
2733
+
2734
+ A median of a triangle is a straight line through a vertex and the
2735
+ midpoint of the opposite side, and divides the triangle into two
2736
+ equal areas.
2737
+
2738
+ Returns
2739
+ =======
2740
+
2741
+ medians : dict
2742
+ Each key is a vertex (Point) and each value is the median (Segment)
2743
+ at that point.
2744
+
2745
+ See Also
2746
+ ========
2747
+
2748
+ sympy.geometry.point.Point.midpoint, sympy.geometry.line.Segment.midpoint
2749
+
2750
+ Examples
2751
+ ========
2752
+
2753
+ >>> from sympy import Point, Triangle
2754
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2755
+ >>> t = Triangle(p1, p2, p3)
2756
+ >>> t.medians[p1]
2757
+ Segment2D(Point2D(0, 0), Point2D(1/2, 1/2))
2758
+
2759
+ """
2760
+ s = self.sides
2761
+ v = self.vertices
2762
+ return {v[0]: Segment(v[0], s[1].midpoint),
2763
+ v[1]: Segment(v[1], s[2].midpoint),
2764
+ v[2]: Segment(v[2], s[0].midpoint)}
2765
+
2766
+ @property
2767
+ def medial(self):
2768
+ """The medial triangle of the triangle.
2769
+
2770
+ The triangle which is formed from the midpoints of the three sides.
2771
+
2772
+ Returns
2773
+ =======
2774
+
2775
+ medial : Triangle
2776
+
2777
+ See Also
2778
+ ========
2779
+
2780
+ sympy.geometry.line.Segment.midpoint
2781
+
2782
+ Examples
2783
+ ========
2784
+
2785
+ >>> from sympy import Point, Triangle
2786
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2787
+ >>> t = Triangle(p1, p2, p3)
2788
+ >>> t.medial
2789
+ Triangle(Point2D(1/2, 0), Point2D(1/2, 1/2), Point2D(0, 1/2))
2790
+
2791
+ """
2792
+ s = self.sides
2793
+ return Triangle(s[0].midpoint, s[1].midpoint, s[2].midpoint)
2794
+
2795
+ @property
2796
+ def nine_point_circle(self):
2797
+ """The nine-point circle of the triangle.
2798
+
2799
+ Nine-point circle is the circumcircle of the medial triangle, which
2800
+ passes through the feet of altitudes and the middle points of segments
2801
+ connecting the vertices and the orthocenter.
2802
+
2803
+ Returns
2804
+ =======
2805
+
2806
+ nine_point_circle : Circle
2807
+
2808
+ See also
2809
+ ========
2810
+
2811
+ sympy.geometry.line.Segment.midpoint
2812
+ sympy.geometry.polygon.Triangle.medial
2813
+ sympy.geometry.polygon.Triangle.orthocenter
2814
+
2815
+ Examples
2816
+ ========
2817
+
2818
+ >>> from sympy import Point, Triangle
2819
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2820
+ >>> t = Triangle(p1, p2, p3)
2821
+ >>> t.nine_point_circle
2822
+ Circle(Point2D(1/4, 1/4), sqrt(2)/4)
2823
+
2824
+ """
2825
+ return Circle(*self.medial.vertices)
2826
+
2827
+ @property
2828
+ def eulerline(self):
2829
+ """The Euler line of the triangle.
2830
+
2831
+ The line which passes through circumcenter, centroid and orthocenter.
2832
+
2833
+ Returns
2834
+ =======
2835
+
2836
+ eulerline : Line (or Point for equilateral triangles in which case all
2837
+ centers coincide)
2838
+
2839
+ Examples
2840
+ ========
2841
+
2842
+ >>> from sympy import Point, Triangle
2843
+ >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
2844
+ >>> t = Triangle(p1, p2, p3)
2845
+ >>> t.eulerline
2846
+ Line2D(Point2D(0, 0), Point2D(1/2, 1/2))
2847
+
2848
+ """
2849
+ if self.is_equilateral():
2850
+ return self.orthocenter
2851
+ return Line(self.orthocenter, self.circumcenter)
2852
+
2853
+ def rad(d):
2854
+ """Return the radian value for the given degrees (pi = 180 degrees)."""
2855
+ return d*pi/180
2856
+
2857
+
2858
+ def deg(r):
2859
+ """Return the degree value for the given radians (pi = 180 degrees)."""
2860
+ return r/pi*180
2861
+
2862
+
2863
+ def _slope(d):
2864
+ rv = tan(rad(d))
2865
+ return rv
2866
+
2867
+
2868
+ def _asa(d1, l, d2):
2869
+ """Return triangle having side with length l on the x-axis."""
2870
+ xy = Line((0, 0), slope=_slope(d1)).intersection(
2871
+ Line((l, 0), slope=_slope(180 - d2)))[0]
2872
+ return Triangle((0, 0), (l, 0), xy)
2873
+
2874
+
2875
+ def _sss(l1, l2, l3):
2876
+ """Return triangle having side of length l1 on the x-axis."""
2877
+ c1 = Circle((0, 0), l3)
2878
+ c2 = Circle((l1, 0), l2)
2879
+ inter = [a for a in c1.intersection(c2) if a.y.is_nonnegative]
2880
+ if not inter:
2881
+ return None
2882
+ pt = inter[0]
2883
+ return Triangle((0, 0), (l1, 0), pt)
2884
+
2885
+
2886
+ def _sas(l1, d, l2):
2887
+ """Return triangle having side with length l2 on the x-axis."""
2888
+ p1 = Point(0, 0)
2889
+ p2 = Point(l2, 0)
2890
+ p3 = Point(cos(rad(d))*l1, sin(rad(d))*l1)
2891
+ return Triangle(p1, p2, p3)
wemm/lib/python3.10/site-packages/sympy/geometry/tests/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_curve.cpython-310.pyc ADDED
Binary file (5.23 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_ellipse.cpython-310.pyc ADDED
Binary file (23.9 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_entity.cpython-310.pyc ADDED
Binary file (4.4 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_geometrysets.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/geometry/tests/__pycache__/test_point.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/geometry/tests/test_curve.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.containers import Tuple
2
+ from sympy.core.numbers import (Rational, pi)
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import (Symbol, symbols)
5
+ from sympy.functions.elementary.hyperbolic import asinh
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.geometry import Curve, Line, Point, Ellipse, Ray, Segment, Circle, Polygon, RegularPolygon
8
+ from sympy.testing.pytest import raises, slow
9
+
10
+
11
+ def test_curve():
12
+ x = Symbol('x', real=True)
13
+ s = Symbol('s')
14
+ z = Symbol('z')
15
+
16
+ # this curve is independent of the indicated parameter
17
+ c = Curve([2*s, s**2], (z, 0, 2))
18
+
19
+ assert c.parameter == z
20
+ assert c.functions == (2*s, s**2)
21
+ assert c.arbitrary_point() == Point(2*s, s**2)
22
+ assert c.arbitrary_point(z) == Point(2*s, s**2)
23
+
24
+ # this is how it is normally used
25
+ c = Curve([2*s, s**2], (s, 0, 2))
26
+
27
+ assert c.parameter == s
28
+ assert c.functions == (2*s, s**2)
29
+ t = Symbol('t')
30
+ # the t returned as assumptions
31
+ assert c.arbitrary_point() != Point(2*t, t**2)
32
+ t = Symbol('t', real=True)
33
+ # now t has the same assumptions so the test passes
34
+ assert c.arbitrary_point() == Point(2*t, t**2)
35
+ assert c.arbitrary_point(z) == Point(2*z, z**2)
36
+ assert c.arbitrary_point(c.parameter) == Point(2*s, s**2)
37
+ assert c.arbitrary_point(None) == Point(2*s, s**2)
38
+ assert c.plot_interval() == [t, 0, 2]
39
+ assert c.plot_interval(z) == [z, 0, 2]
40
+
41
+ assert Curve([x, x], (x, 0, 1)).rotate(pi/2) == Curve([-x, x], (x, 0, 1))
42
+ assert Curve([x, x], (x, 0, 1)).rotate(pi/2, (1, 2)).scale(2, 3).translate(
43
+ 1, 3).arbitrary_point(s) == \
44
+ Line((0, 0), (1, 1)).rotate(pi/2, (1, 2)).scale(2, 3).translate(
45
+ 1, 3).arbitrary_point(s) == \
46
+ Point(-2*s + 7, 3*s + 6)
47
+
48
+ raises(ValueError, lambda: Curve((s), (s, 1, 2)))
49
+ raises(ValueError, lambda: Curve((x, x * 2), (1, x)))
50
+
51
+ raises(ValueError, lambda: Curve((s, s + t), (s, 1, 2)).arbitrary_point())
52
+ raises(ValueError, lambda: Curve((s, s + t), (t, 1, 2)).arbitrary_point(s))
53
+
54
+
55
+ @slow
56
+ def test_free_symbols():
57
+ a, b, c, d, e, f, s = symbols('a:f,s')
58
+ assert Point(a, b).free_symbols == {a, b}
59
+ assert Line((a, b), (c, d)).free_symbols == {a, b, c, d}
60
+ assert Ray((a, b), (c, d)).free_symbols == {a, b, c, d}
61
+ assert Ray((a, b), angle=c).free_symbols == {a, b, c}
62
+ assert Segment((a, b), (c, d)).free_symbols == {a, b, c, d}
63
+ assert Line((a, b), slope=c).free_symbols == {a, b, c}
64
+ assert Curve((a*s, b*s), (s, c, d)).free_symbols == {a, b, c, d}
65
+ assert Ellipse((a, b), c, d).free_symbols == {a, b, c, d}
66
+ assert Ellipse((a, b), c, eccentricity=d).free_symbols == \
67
+ {a, b, c, d}
68
+ assert Ellipse((a, b), vradius=c, eccentricity=d).free_symbols == \
69
+ {a, b, c, d}
70
+ assert Circle((a, b), c).free_symbols == {a, b, c}
71
+ assert Circle((a, b), (c, d), (e, f)).free_symbols == \
72
+ {e, d, c, b, f, a}
73
+ assert Polygon((a, b), (c, d), (e, f)).free_symbols == \
74
+ {e, b, d, f, a, c}
75
+ assert RegularPolygon((a, b), c, d, e).free_symbols == {e, a, b, c, d}
76
+
77
+
78
+ def test_transform():
79
+ x = Symbol('x', real=True)
80
+ y = Symbol('y', real=True)
81
+ c = Curve((x, x**2), (x, 0, 1))
82
+ cout = Curve((2*x - 4, 3*x**2 - 10), (x, 0, 1))
83
+ pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)]
84
+ pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)]
85
+
86
+ assert c.scale(2, 3, (4, 5)) == cout
87
+ assert [c.subs(x, xi/2) for xi in Tuple(0, 1, 2)] == pts
88
+ assert [cout.subs(x, xi/2) for xi in Tuple(0, 1, 2)] == pts_out
89
+ assert Curve((x + y, 3*x), (x, 0, 1)).subs(y, S.Half) == \
90
+ Curve((x + S.Half, 3*x), (x, 0, 1))
91
+ assert Curve((x, 3*x), (x, 0, 1)).translate(4, 5) == \
92
+ Curve((x + 4, 3*x + 5), (x, 0, 1))
93
+
94
+
95
+ def test_length():
96
+ t = Symbol('t', real=True)
97
+
98
+ c1 = Curve((t, 0), (t, 0, 1))
99
+ assert c1.length == 1
100
+
101
+ c2 = Curve((t, t), (t, 0, 1))
102
+ assert c2.length == sqrt(2)
103
+
104
+ c3 = Curve((t ** 2, t), (t, 2, 5))
105
+ assert c3.length == -sqrt(17) - asinh(4) / 4 + asinh(10) / 4 + 5 * sqrt(101) / 2
106
+
107
+
108
+ def test_parameter_value():
109
+ t = Symbol('t')
110
+ C = Curve([2*t, t**2], (t, 0, 2))
111
+ assert C.parameter_value((2, 1), t) == {t: 1}
112
+ raises(ValueError, lambda: C.parameter_value((2, 0), t))
113
+
114
+
115
+ def test_issue_17997():
116
+ t, s = symbols('t s')
117
+ c = Curve((t, t**2), (t, 0, 10))
118
+ p = Curve([2*s, s**2], (s, 0, 2))
119
+ assert c(2) == Point(2, 4)
120
+ assert p(1) == Point(2, 1)
wemm/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))
wemm/lib/python3.10/site-packages/sympy/geometry/tests/test_plane.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (Rational, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import (Dummy, symbols)
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.functions.elementary.trigonometric import (asin, cos, sin)
6
+ from sympy.geometry import Line, Point, Ray, Segment, Point3D, Line3D, Ray3D, Segment3D, Plane, Circle
7
+ from sympy.geometry.util import are_coplanar
8
+ from sympy.testing.pytest import raises
9
+
10
+
11
+ def test_plane():
12
+ x, y, z, u, v = symbols('x y z u v', real=True)
13
+ p1 = Point3D(0, 0, 0)
14
+ p2 = Point3D(1, 1, 1)
15
+ p3 = Point3D(1, 2, 3)
16
+ pl3 = Plane(p1, p2, p3)
17
+ pl4 = Plane(p1, normal_vector=(1, 1, 1))
18
+ pl4b = Plane(p1, p2)
19
+ pl5 = Plane(p3, normal_vector=(1, 2, 3))
20
+ pl6 = Plane(Point3D(2, 3, 7), normal_vector=(2, 2, 2))
21
+ pl7 = Plane(Point3D(1, -5, -6), normal_vector=(1, -2, 1))
22
+ pl8 = Plane(p1, normal_vector=(0, 0, 1))
23
+ pl9 = Plane(p1, normal_vector=(0, 12, 0))
24
+ pl10 = Plane(p1, normal_vector=(-2, 0, 0))
25
+ pl11 = Plane(p2, normal_vector=(0, 0, 1))
26
+ l1 = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
27
+ l2 = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
28
+ l3 = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
29
+
30
+ raises(ValueError, lambda: Plane(p1, p1, p1))
31
+
32
+ assert Plane(p1, p2, p3) != Plane(p1, p3, p2)
33
+ assert Plane(p1, p2, p3).is_coplanar(Plane(p1, p3, p2))
34
+ assert Plane(p1, p2, p3).is_coplanar(p1)
35
+ assert Plane(p1, p2, p3).is_coplanar(Circle(p1, 1)) is False
36
+ assert Plane(p1, normal_vector=(0, 0, 1)).is_coplanar(Circle(p1, 1))
37
+
38
+ assert pl3 == Plane(Point3D(0, 0, 0), normal_vector=(1, -2, 1))
39
+ assert pl3 != pl4
40
+ assert pl4 == pl4b
41
+ assert pl5 == Plane(Point3D(1, 2, 3), normal_vector=(1, 2, 3))
42
+
43
+ assert pl5.equation(x, y, z) == x + 2*y + 3*z - 14
44
+ assert pl3.equation(x, y, z) == x - 2*y + z
45
+
46
+ assert pl3.p1 == p1
47
+ assert pl4.p1 == p1
48
+ assert pl5.p1 == p3
49
+
50
+ assert pl4.normal_vector == (1, 1, 1)
51
+ assert pl5.normal_vector == (1, 2, 3)
52
+
53
+ assert p1 in pl3
54
+ assert p1 in pl4
55
+ assert p3 in pl5
56
+
57
+ assert pl3.projection(Point(0, 0)) == p1
58
+ p = pl3.projection(Point3D(1, 1, 0))
59
+ assert p == Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6))
60
+ assert p in pl3
61
+
62
+ l = pl3.projection_line(Line(Point(0, 0), Point(1, 1)))
63
+ assert l == Line3D(Point3D(0, 0, 0), Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6)))
64
+ assert l in pl3
65
+ # get a segment that does not intersect the plane which is also
66
+ # parallel to pl3's normal veector
67
+ t = Dummy()
68
+ r = pl3.random_point()
69
+ a = pl3.perpendicular_line(r).arbitrary_point(t)
70
+ s = Segment3D(a.subs(t, 1), a.subs(t, 2))
71
+ assert s.p1 not in pl3 and s.p2 not in pl3
72
+ assert pl3.projection_line(s).equals(r)
73
+ assert pl3.projection_line(Segment(Point(1, 0), Point(1, 1))) == \
74
+ Segment3D(Point3D(Rational(5, 6), Rational(1, 3), Rational(-1, 6)), Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6)))
75
+ assert pl6.projection_line(Ray(Point(1, 0), Point(1, 1))) == \
76
+ Ray3D(Point3D(Rational(14, 3), Rational(11, 3), Rational(11, 3)), Point3D(Rational(13, 3), Rational(13, 3), Rational(10, 3)))
77
+ assert pl3.perpendicular_line(r.args) == pl3.perpendicular_line(r)
78
+
79
+ assert pl3.is_parallel(pl6) is False
80
+ assert pl4.is_parallel(pl6)
81
+ assert pl3.is_parallel(Line(p1, p2))
82
+ assert pl6.is_parallel(l1) is False
83
+
84
+ assert pl3.is_perpendicular(pl6)
85
+ assert pl4.is_perpendicular(pl7)
86
+ assert pl6.is_perpendicular(pl7)
87
+ assert pl6.is_perpendicular(pl4) is False
88
+ assert pl6.is_perpendicular(l1) is False
89
+ assert pl6.is_perpendicular(Line((0, 0, 0), (1, 1, 1)))
90
+ assert pl6.is_perpendicular((1, 1)) is False
91
+
92
+ assert pl6.distance(pl6.arbitrary_point(u, v)) == 0
93
+ assert pl7.distance(pl7.arbitrary_point(u, v)) == 0
94
+ assert pl6.distance(pl6.arbitrary_point(t)) == 0
95
+ assert pl7.distance(pl7.arbitrary_point(t)) == 0
96
+ assert pl6.p1.distance(pl6.arbitrary_point(t)).simplify() == 1
97
+ assert pl7.p1.distance(pl7.arbitrary_point(t)).simplify() == 1
98
+ assert pl3.arbitrary_point(t) == Point3D(-sqrt(30)*sin(t)/30 + \
99
+ 2*sqrt(5)*cos(t)/5, sqrt(30)*sin(t)/15 + sqrt(5)*cos(t)/5, sqrt(30)*sin(t)/6)
100
+ assert pl3.arbitrary_point(u, v) == Point3D(2*u - v, u + 2*v, 5*v)
101
+
102
+ assert pl7.distance(Point3D(1, 3, 5)) == 5*sqrt(6)/6
103
+ assert pl6.distance(Point3D(0, 0, 0)) == 4*sqrt(3)
104
+ assert pl6.distance(pl6.p1) == 0
105
+ assert pl7.distance(pl6) == 0
106
+ assert pl7.distance(l1) == 0
107
+ assert pl6.distance(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == \
108
+ pl6.distance(Point3D(1, 3, 4)) == 4*sqrt(3)/3
109
+ assert pl6.distance(Segment3D(Point3D(1, 3, 4), Point3D(0, 3, 7))) == \
110
+ pl6.distance(Point3D(0, 3, 7)) == 2*sqrt(3)/3
111
+ assert pl6.distance(Segment3D(Point3D(0, 3, 7), Point3D(-1, 3, 10))) == 0
112
+ assert pl6.distance(Segment3D(Point3D(-1, 3, 10), Point3D(-2, 3, 13))) == 0
113
+ assert pl6.distance(Segment3D(Point3D(-2, 3, 13), Point3D(-3, 3, 16))) == \
114
+ pl6.distance(Point3D(-2, 3, 13)) == 2*sqrt(3)/3
115
+ assert pl6.distance(Plane(Point3D(5, 5, 5), normal_vector=(8, 8, 8))) == sqrt(3)
116
+ assert pl6.distance(Ray3D(Point3D(1, 3, 4), direction_ratio=[1, 0, -3])) == 4*sqrt(3)/3
117
+ assert pl6.distance(Ray3D(Point3D(2, 3, 1), direction_ratio=[-1, 0, 3])) == 0
118
+
119
+
120
+ assert pl6.angle_between(pl3) == pi/2
121
+ assert pl6.angle_between(pl6) == 0
122
+ assert pl6.angle_between(pl4) == 0
123
+ assert pl7.angle_between(Line3D(Point3D(2, 3, 5), Point3D(2, 4, 6))) == \
124
+ -asin(sqrt(3)/6)
125
+ assert pl6.angle_between(Ray3D(Point3D(2, 4, 1), Point3D(6, 5, 3))) == \
126
+ asin(sqrt(7)/3)
127
+ assert pl7.angle_between(Segment3D(Point3D(5, 6, 1), Point3D(1, 2, 4))) == \
128
+ asin(7*sqrt(246)/246)
129
+
130
+ assert are_coplanar(l1, l2, l3) is False
131
+ assert are_coplanar(l1) is False
132
+ assert are_coplanar(Point3D(2, 7, 2), Point3D(0, 0, 2),
133
+ Point3D(1, 1, 2), Point3D(1, 2, 2))
134
+ assert are_coplanar(Plane(p1, p2, p3), Plane(p1, p3, p2))
135
+ assert Plane.are_concurrent(pl3, pl4, pl5) is False
136
+ assert Plane.are_concurrent(pl6) is False
137
+ raises(ValueError, lambda: Plane.are_concurrent(Point3D(0, 0, 0)))
138
+ raises(ValueError, lambda: Plane((1, 2, 3), normal_vector=(0, 0, 0)))
139
+
140
+ assert pl3.parallel_plane(Point3D(1, 2, 5)) == Plane(Point3D(1, 2, 5), \
141
+ normal_vector=(1, -2, 1))
142
+
143
+ # perpendicular_plane
144
+ p = Plane((0, 0, 0), (1, 0, 0))
145
+ # default
146
+ assert p.perpendicular_plane() == Plane(Point3D(0, 0, 0), (0, 1, 0))
147
+ # 1 pt
148
+ assert p.perpendicular_plane(Point3D(1, 0, 1)) == \
149
+ Plane(Point3D(1, 0, 1), (0, 1, 0))
150
+ # pts as tuples
151
+ assert p.perpendicular_plane((1, 0, 1), (1, 1, 1)) == \
152
+ Plane(Point3D(1, 0, 1), (0, 0, -1))
153
+ # more than two planes
154
+ raises(ValueError, lambda: p.perpendicular_plane((1, 0, 1), (1, 1, 1), (1, 1, 0)))
155
+
156
+ a, b = Point3D(0, 0, 0), Point3D(0, 1, 0)
157
+ Z = (0, 0, 1)
158
+ p = Plane(a, normal_vector=Z)
159
+ # case 4
160
+ assert p.perpendicular_plane(a, b) == Plane(a, (1, 0, 0))
161
+ n = Point3D(*Z)
162
+ # case 1
163
+ assert p.perpendicular_plane(a, n) == Plane(a, (-1, 0, 0))
164
+ # case 2
165
+ assert Plane(a, normal_vector=b.args).perpendicular_plane(a, a + b) == \
166
+ Plane(Point3D(0, 0, 0), (1, 0, 0))
167
+ # case 1&3
168
+ assert Plane(b, normal_vector=Z).perpendicular_plane(b, b + n) == \
169
+ Plane(Point3D(0, 1, 0), (-1, 0, 0))
170
+ # case 2&3
171
+ assert Plane(b, normal_vector=b.args).perpendicular_plane(n, n + b) == \
172
+ Plane(Point3D(0, 0, 1), (1, 0, 0))
173
+
174
+ p = Plane(a, normal_vector=(0, 0, 1))
175
+ assert p.perpendicular_plane() == Plane(a, normal_vector=(1, 0, 0))
176
+
177
+ assert pl6.intersection(pl6) == [pl6]
178
+ assert pl4.intersection(pl4.p1) == [pl4.p1]
179
+ assert pl3.intersection(pl6) == [
180
+ Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6))]
181
+ assert pl3.intersection(Line3D(Point3D(1,2,4), Point3D(4,4,2))) == [
182
+ Point3D(2, Rational(8, 3), Rational(10, 3))]
183
+ assert pl3.intersection(Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3))
184
+ ) == [Line3D(Point3D(-24, -12, 0), Point3D(-25, -13, -1))]
185
+ assert pl6.intersection(Ray3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == [
186
+ Point3D(-1, 3, 10)]
187
+ assert pl6.intersection(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == []
188
+ assert pl7.intersection(Line(Point(2, 3), Point(4, 2))) == [
189
+ Point3D(Rational(13, 2), Rational(3, 4), 0)]
190
+ r = Ray(Point(2, 3), Point(4, 2))
191
+ assert Plane((1,2,0), normal_vector=(0,0,1)).intersection(r) == [
192
+ Ray3D(Point(2, 3), Point(4, 2))]
193
+ assert pl9.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, 0))]
194
+ assert pl10.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(0, 2, 1))]
195
+ assert pl4.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))]
196
+ assert pl11.intersection(pl8) == []
197
+ assert pl9.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(12, 0, 1))]
198
+ assert pl9.intersection(pl4) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, -12))]
199
+ assert pl3.random_point() in pl3
200
+ assert pl3.random_point(seed=1) in pl3
201
+
202
+ # test geometrical entity using equals
203
+ assert pl4.intersection(pl4.p1)[0].equals(pl4.p1)
204
+ assert pl3.intersection(pl6)[0].equals(Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6)))
205
+ pl8 = Plane((1, 2, 0), normal_vector=(0, 0, 1))
206
+ assert pl8.intersection(Line3D(p1, (1, 12, 0)))[0].equals(Line((0, 0, 0), (0.1, 1.2, 0)))
207
+ assert pl8.intersection(Ray3D(p1, (1, 12, 0)))[0].equals(Ray((0, 0, 0), (1, 12, 0)))
208
+ assert pl8.intersection(Segment3D(p1, (21, 1, 0)))[0].equals(Segment3D(p1, (21, 1, 0)))
209
+ assert pl8.intersection(Plane(p1, normal_vector=(0, 0, 112)))[0].equals(pl8)
210
+ assert pl8.intersection(Plane(p1, normal_vector=(0, 12, 0)))[0].equals(
211
+ Line3D(p1, direction_ratio=(112 * pi, 0, 0)))
212
+ assert pl8.intersection(Plane(p1, normal_vector=(11, 0, 1)))[0].equals(
213
+ Line3D(p1, direction_ratio=(0, -11, 0)))
214
+ assert pl8.intersection(Plane(p1, normal_vector=(1, 0, 11)))[0].equals(
215
+ Line3D(p1, direction_ratio=(0, 11, 0)))
216
+ assert pl8.intersection(Plane(p1, normal_vector=(-1, -1, -11)))[0].equals(
217
+ Line3D(p1, direction_ratio=(1, -1, 0)))
218
+ assert pl3.random_point() in pl3
219
+ assert len(pl8.intersection(Ray3D(Point3D(0, 2, 3), Point3D(1, 0, 3)))) == 0
220
+ # check if two plane are equals
221
+ assert pl6.intersection(pl6)[0].equals(pl6)
222
+ assert pl8.equals(Plane(p1, normal_vector=(0, 12, 0))) is False
223
+ assert pl8.equals(pl8)
224
+ assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12)))
225
+ assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12*sqrt(3))))
226
+ assert pl8.equals(p1) is False
227
+
228
+ # issue 8570
229
+ l2 = Line3D(Point3D(Rational(50000004459633, 5000000000000),
230
+ Rational(-891926590718643, 1000000000000000),
231
+ Rational(231800966893633, 100000000000000)),
232
+ Point3D(Rational(50000004459633, 50000000000000),
233
+ Rational(-222981647679771, 250000000000000),
234
+ Rational(231800966893633, 100000000000000)))
235
+
236
+ p2 = Plane(Point3D(Rational(402775636372767, 100000000000000),
237
+ Rational(-97224357654973, 100000000000000),
238
+ Rational(216793600814789, 100000000000000)),
239
+ (-S('9.00000087501922'), -S('4.81170658872543e-13'),
240
+ S('0.0')))
241
+
242
+ assert str([i.n(2) for i in p2.intersection(l2)]) == \
243
+ '[Point3D(4.0, -0.89, 2.3)]'
244
+
245
+
246
+ def test_dimension_normalization():
247
+ A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1))
248
+ b = Point(1, 1)
249
+ assert A.projection(b) == Point(Rational(5, 3), Rational(5, 3), Rational(2, 3))
250
+
251
+ a, b = Point(0, 0), Point3D(0, 1)
252
+ Z = (0, 0, 1)
253
+ p = Plane(a, normal_vector=Z)
254
+ assert p.perpendicular_plane(a, b) == Plane(Point3D(0, 0, 0), (1, 0, 0))
255
+ assert Plane((1, 2, 1), (2, 1, 0), (3, 1, 2)
256
+ ).intersection((2, 1)) == [Point(2, 1, 0)]
257
+
258
+
259
+ def test_parameter_value():
260
+ t, u, v = symbols("t, u v")
261
+ p1, p2, p3 = Point(0, 0, 0), Point(0, 0, 1), Point(0, 1, 0)
262
+ p = Plane(p1, p2, p3)
263
+ assert p.parameter_value((0, -3, 2), t) == {t: asin(2*sqrt(13)/13)}
264
+ assert p.parameter_value((0, -3, 2), u, v) == {u: 3, v: 2}
265
+ assert p.parameter_value(p1, t) == p1
266
+ raises(ValueError, lambda: p.parameter_value((1, 0, 0), t))
267
+ raises(ValueError, lambda: p.parameter_value(Line(Point(0, 0), Point(1, 1)), t))
268
+ raises(ValueError, lambda: p.parameter_value((0, -3, 2), t, 1))
wemm/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
wemm/lib/python3.10/site-packages/sympy/geometry/util.py ADDED
@@ -0,0 +1,733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility functions for geometrical entities.
2
+
3
+ Contains
4
+ ========
5
+ intersection
6
+ convex_hull
7
+ closest_points
8
+ farthest_points
9
+ are_coplanar
10
+ are_similar
11
+
12
+ """
13
+
14
+ from collections import deque
15
+ from math import sqrt as _sqrt
16
+
17
+ from sympy import nsimplify
18
+ from .entity import GeometryEntity
19
+ from .exceptions import GeometryError
20
+ from .point import Point, Point2D, Point3D
21
+ from sympy.core.containers import OrderedSet
22
+ from sympy.core.exprtools import factor_terms
23
+ from sympy.core.function import Function, expand_mul
24
+ from sympy.core.numbers import Float
25
+ from sympy.core.sorting import ordered
26
+ from sympy.core.symbol import Symbol
27
+ from sympy.core.singleton import S
28
+ from sympy.polys.polytools import cancel
29
+ from sympy.functions.elementary.miscellaneous import sqrt
30
+ from sympy.utilities.iterables import is_sequence
31
+
32
+ from mpmath.libmp.libmpf import prec_to_dps
33
+
34
+
35
+ def find(x, equation):
36
+ """
37
+ Checks whether a Symbol matching ``x`` is present in ``equation``
38
+ or not. If present, the matching symbol is returned, else a
39
+ ValueError is raised. If ``x`` is a string the matching symbol
40
+ will have the same name; if ``x`` is a Symbol then it will be
41
+ returned if found.
42
+
43
+ Examples
44
+ ========
45
+
46
+ >>> from sympy.geometry.util import find
47
+ >>> from sympy import Dummy
48
+ >>> from sympy.abc import x
49
+ >>> find('x', x)
50
+ x
51
+ >>> find('x', Dummy('x'))
52
+ _x
53
+
54
+ The dummy symbol is returned since it has a matching name:
55
+
56
+ >>> _.name == 'x'
57
+ True
58
+ >>> find(x, Dummy('x'))
59
+ Traceback (most recent call last):
60
+ ...
61
+ ValueError: could not find x
62
+ """
63
+
64
+ free = equation.free_symbols
65
+ xs = [i for i in free if (i.name if isinstance(x, str) else i) == x]
66
+ if not xs:
67
+ raise ValueError('could not find %s' % x)
68
+ if len(xs) != 1:
69
+ raise ValueError('ambiguous %s' % x)
70
+ return xs[0]
71
+
72
+
73
+ def _ordered_points(p):
74
+ """Return the tuple of points sorted numerically according to args"""
75
+ return tuple(sorted(p, key=lambda x: x.args))
76
+
77
+
78
+ def are_coplanar(*e):
79
+ """ Returns True if the given entities are coplanar otherwise False
80
+
81
+ Parameters
82
+ ==========
83
+
84
+ e: entities to be checked for being coplanar
85
+
86
+ Returns
87
+ =======
88
+
89
+ Boolean
90
+
91
+ Examples
92
+ ========
93
+
94
+ >>> from sympy import Point3D, Line3D
95
+ >>> from sympy.geometry.util import are_coplanar
96
+ >>> a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
97
+ >>> b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
98
+ >>> c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
99
+ >>> are_coplanar(a, b, c)
100
+ False
101
+
102
+ """
103
+ from .line import LinearEntity3D
104
+ from .plane import Plane
105
+ # XXX update tests for coverage
106
+
107
+ e = set(e)
108
+ # first work with a Plane if present
109
+ for i in list(e):
110
+ if isinstance(i, Plane):
111
+ e.remove(i)
112
+ return all(p.is_coplanar(i) for p in e)
113
+
114
+ if all(isinstance(i, Point3D) for i in e):
115
+ if len(e) < 3:
116
+ return False
117
+
118
+ # remove pts that are collinear with 2 pts
119
+ a, b = e.pop(), e.pop()
120
+ for i in list(e):
121
+ if Point3D.are_collinear(a, b, i):
122
+ e.remove(i)
123
+
124
+ if not e:
125
+ return False
126
+ else:
127
+ # define a plane
128
+ p = Plane(a, b, e.pop())
129
+ for i in e:
130
+ if i not in p:
131
+ return False
132
+ return True
133
+ else:
134
+ pt3d = []
135
+ for i in e:
136
+ if isinstance(i, Point3D):
137
+ pt3d.append(i)
138
+ elif isinstance(i, LinearEntity3D):
139
+ pt3d.extend(i.args)
140
+ elif isinstance(i, GeometryEntity): # XXX we should have a GeometryEntity3D class so we can tell the difference between 2D and 3D -- here we just want to deal with 2D objects; if new 3D objects are encountered that we didn't handle above, an error should be raised
141
+ # all 2D objects have some Point that defines them; so convert those points to 3D pts by making z=0
142
+ for p in i.args:
143
+ if isinstance(p, Point):
144
+ pt3d.append(Point3D(*(p.args + (0,))))
145
+ return are_coplanar(*pt3d)
146
+
147
+
148
+ def are_similar(e1, e2):
149
+ """Are two geometrical entities similar.
150
+
151
+ Can one geometrical entity be uniformly scaled to the other?
152
+
153
+ Parameters
154
+ ==========
155
+
156
+ e1 : GeometryEntity
157
+ e2 : GeometryEntity
158
+
159
+ Returns
160
+ =======
161
+
162
+ are_similar : boolean
163
+
164
+ Raises
165
+ ======
166
+
167
+ GeometryError
168
+ When `e1` and `e2` cannot be compared.
169
+
170
+ Notes
171
+ =====
172
+
173
+ If the two objects are equal then they are similar.
174
+
175
+ See Also
176
+ ========
177
+
178
+ sympy.geometry.entity.GeometryEntity.is_similar
179
+
180
+ Examples
181
+ ========
182
+
183
+ >>> from sympy import Point, Circle, Triangle, are_similar
184
+ >>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3)
185
+ >>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
186
+ >>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2))
187
+ >>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1))
188
+ >>> are_similar(t1, t2)
189
+ True
190
+ >>> are_similar(t1, t3)
191
+ False
192
+
193
+ """
194
+ if e1 == e2:
195
+ return True
196
+ is_similar1 = getattr(e1, 'is_similar', None)
197
+ if is_similar1:
198
+ return is_similar1(e2)
199
+ is_similar2 = getattr(e2, 'is_similar', None)
200
+ if is_similar2:
201
+ return is_similar2(e1)
202
+ n1 = e1.__class__.__name__
203
+ n2 = e2.__class__.__name__
204
+ raise GeometryError(
205
+ "Cannot test similarity between %s and %s" % (n1, n2))
206
+
207
+
208
+ def centroid(*args):
209
+ """Find the centroid (center of mass) of the collection containing only Points,
210
+ Segments or Polygons. The centroid is the weighted average of the individual centroid
211
+ where the weights are the lengths (of segments) or areas (of polygons).
212
+ Overlapping regions will add to the weight of that region.
213
+
214
+ If there are no objects (or a mixture of objects) then None is returned.
215
+
216
+ See Also
217
+ ========
218
+
219
+ sympy.geometry.point.Point, sympy.geometry.line.Segment,
220
+ sympy.geometry.polygon.Polygon
221
+
222
+ Examples
223
+ ========
224
+
225
+ >>> from sympy import Point, Segment, Polygon
226
+ >>> from sympy.geometry.util import centroid
227
+ >>> p = Polygon((0, 0), (10, 0), (10, 10))
228
+ >>> q = p.translate(0, 20)
229
+ >>> p.centroid, q.centroid
230
+ (Point2D(20/3, 10/3), Point2D(20/3, 70/3))
231
+ >>> centroid(p, q)
232
+ Point2D(20/3, 40/3)
233
+ >>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))
234
+ >>> centroid(p, q)
235
+ Point2D(1, 2 - sqrt(2))
236
+ >>> centroid(Point(0, 0), Point(2, 0))
237
+ Point2D(1, 0)
238
+
239
+ Stacking 3 polygons on top of each other effectively triples the
240
+ weight of that polygon:
241
+
242
+ >>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))
243
+ >>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))
244
+ >>> centroid(p, q)
245
+ Point2D(3/2, 1/2)
246
+ >>> centroid(p, p, p, q) # centroid x-coord shifts left
247
+ Point2D(11/10, 1/2)
248
+
249
+ Stacking the squares vertically above and below p has the same
250
+ effect:
251
+
252
+ >>> centroid(p, p.translate(0, 1), p.translate(0, -1), q)
253
+ Point2D(11/10, 1/2)
254
+
255
+ """
256
+ from .line import Segment
257
+ from .polygon import Polygon
258
+ if args:
259
+ if all(isinstance(g, Point) for g in args):
260
+ c = Point(0, 0)
261
+ for g in args:
262
+ c += g
263
+ den = len(args)
264
+ elif all(isinstance(g, Segment) for g in args):
265
+ c = Point(0, 0)
266
+ L = 0
267
+ for g in args:
268
+ l = g.length
269
+ c += g.midpoint*l
270
+ L += l
271
+ den = L
272
+ elif all(isinstance(g, Polygon) for g in args):
273
+ c = Point(0, 0)
274
+ A = 0
275
+ for g in args:
276
+ a = g.area
277
+ c += g.centroid*a
278
+ A += a
279
+ den = A
280
+ c /= den
281
+ return c.func(*[i.simplify() for i in c.args])
282
+
283
+
284
+ def closest_points(*args):
285
+ """Return the subset of points from a set of points that were
286
+ the closest to each other in the 2D plane.
287
+
288
+ Parameters
289
+ ==========
290
+
291
+ args
292
+ A collection of Points on 2D plane.
293
+
294
+ Notes
295
+ =====
296
+
297
+ This can only be performed on a set of points whose coordinates can
298
+ be ordered on the number line. If there are no ties then a single
299
+ pair of Points will be in the set.
300
+
301
+ Examples
302
+ ========
303
+
304
+ >>> from sympy import closest_points, Triangle
305
+ >>> Triangle(sss=(3, 4, 5)).args
306
+ (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
307
+ >>> closest_points(*_)
308
+ {(Point2D(0, 0), Point2D(3, 0))}
309
+
310
+ References
311
+ ==========
312
+
313
+ .. [1] https://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html
314
+
315
+ .. [2] Sweep line algorithm
316
+ https://en.wikipedia.org/wiki/Sweep_line_algorithm
317
+
318
+ """
319
+ p = [Point2D(i) for i in set(args)]
320
+ if len(p) < 2:
321
+ raise ValueError('At least 2 distinct points must be given.')
322
+
323
+ try:
324
+ p.sort(key=lambda x: x.args)
325
+ except TypeError:
326
+ raise ValueError("The points could not be sorted.")
327
+
328
+ if not all(i.is_Rational for j in p for i in j.args):
329
+ def hypot(x, y):
330
+ arg = x*x + y*y
331
+ if arg.is_Rational:
332
+ return _sqrt(arg)
333
+ return sqrt(arg)
334
+ else:
335
+ from math import hypot
336
+
337
+ rv = [(0, 1)]
338
+ best_dist = hypot(p[1].x - p[0].x, p[1].y - p[0].y)
339
+ i = 2
340
+ left = 0
341
+ box = deque([0, 1])
342
+ while i < len(p):
343
+ while left < i and p[i][0] - p[left][0] > best_dist:
344
+ box.popleft()
345
+ left += 1
346
+
347
+ for j in box:
348
+ d = hypot(p[i].x - p[j].x, p[i].y - p[j].y)
349
+ if d < best_dist:
350
+ rv = [(j, i)]
351
+ elif d == best_dist:
352
+ rv.append((j, i))
353
+ else:
354
+ continue
355
+ best_dist = d
356
+ box.append(i)
357
+ i += 1
358
+
359
+ return {tuple([p[i] for i in pair]) for pair in rv}
360
+
361
+
362
+ def convex_hull(*args, polygon=True):
363
+ """The convex hull surrounding the Points contained in the list of entities.
364
+
365
+ Parameters
366
+ ==========
367
+
368
+ args : a collection of Points, Segments and/or Polygons
369
+
370
+ Optional parameters
371
+ ===================
372
+
373
+ polygon : Boolean. If True, returns a Polygon, if false a tuple, see below.
374
+ Default is True.
375
+
376
+ Returns
377
+ =======
378
+
379
+ convex_hull : Polygon if ``polygon`` is True else as a tuple `(U, L)` where
380
+ ``L`` and ``U`` are the lower and upper hulls, respectively.
381
+
382
+ Notes
383
+ =====
384
+
385
+ This can only be performed on a set of points whose coordinates can
386
+ be ordered on the number line.
387
+
388
+ See Also
389
+ ========
390
+
391
+ sympy.geometry.point.Point, sympy.geometry.polygon.Polygon
392
+
393
+ Examples
394
+ ========
395
+
396
+ >>> from sympy import convex_hull
397
+ >>> points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
398
+ >>> convex_hull(*points)
399
+ Polygon(Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4))
400
+ >>> convex_hull(*points, **dict(polygon=False))
401
+ ([Point2D(-5, 2), Point2D(15, 4)],
402
+ [Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)])
403
+
404
+ References
405
+ ==========
406
+
407
+ .. [1] https://en.wikipedia.org/wiki/Graham_scan
408
+
409
+ .. [2] Andrew's Monotone Chain Algorithm
410
+ (A.M. Andrew,
411
+ "Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979)
412
+ https://web.archive.org/web/20210511015444/http://geomalgorithms.com/a10-_hull-1.html
413
+
414
+ """
415
+ from .line import Segment
416
+ from .polygon import Polygon
417
+ p = OrderedSet()
418
+ for e in args:
419
+ if not isinstance(e, GeometryEntity):
420
+ try:
421
+ e = Point(e)
422
+ except NotImplementedError:
423
+ raise ValueError('%s is not a GeometryEntity and cannot be made into Point' % str(e))
424
+ if isinstance(e, Point):
425
+ p.add(e)
426
+ elif isinstance(e, Segment):
427
+ p.update(e.points)
428
+ elif isinstance(e, Polygon):
429
+ p.update(e.vertices)
430
+ else:
431
+ raise NotImplementedError(
432
+ 'Convex hull for %s not implemented.' % type(e))
433
+
434
+ # make sure all our points are of the same dimension
435
+ if any(len(x) != 2 for x in p):
436
+ raise ValueError('Can only compute the convex hull in two dimensions')
437
+
438
+ p = list(p)
439
+ if len(p) == 1:
440
+ return p[0] if polygon else (p[0], None)
441
+ elif len(p) == 2:
442
+ s = Segment(p[0], p[1])
443
+ return s if polygon else (s, None)
444
+
445
+ def _orientation(p, q, r):
446
+ '''Return positive if p-q-r are clockwise, neg if ccw, zero if
447
+ collinear.'''
448
+ return (q.y - p.y)*(r.x - p.x) - (q.x - p.x)*(r.y - p.y)
449
+
450
+ # scan to find upper and lower convex hulls of a set of 2d points.
451
+ U = []
452
+ L = []
453
+ try:
454
+ p.sort(key=lambda x: x.args)
455
+ except TypeError:
456
+ raise ValueError("The points could not be sorted.")
457
+ for p_i in p:
458
+ while len(U) > 1 and _orientation(U[-2], U[-1], p_i) <= 0:
459
+ U.pop()
460
+ while len(L) > 1 and _orientation(L[-2], L[-1], p_i) >= 0:
461
+ L.pop()
462
+ U.append(p_i)
463
+ L.append(p_i)
464
+ U.reverse()
465
+ convexHull = tuple(L + U[1:-1])
466
+
467
+ if len(convexHull) == 2:
468
+ s = Segment(convexHull[0], convexHull[1])
469
+ return s if polygon else (s, None)
470
+ if polygon:
471
+ return Polygon(*convexHull)
472
+ else:
473
+ U.reverse()
474
+ return (U, L)
475
+
476
+ def farthest_points(*args):
477
+ """Return the subset of points from a set of points that were
478
+ the furthest apart from each other in the 2D plane.
479
+
480
+ Parameters
481
+ ==========
482
+
483
+ args
484
+ A collection of Points on 2D plane.
485
+
486
+ Notes
487
+ =====
488
+
489
+ This can only be performed on a set of points whose coordinates can
490
+ be ordered on the number line. If there are no ties then a single
491
+ pair of Points will be in the set.
492
+
493
+ Examples
494
+ ========
495
+
496
+ >>> from sympy.geometry import farthest_points, Triangle
497
+ >>> Triangle(sss=(3, 4, 5)).args
498
+ (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
499
+ >>> farthest_points(*_)
500
+ {(Point2D(0, 0), Point2D(3, 4))}
501
+
502
+ References
503
+ ==========
504
+
505
+ .. [1] https://code.activestate.com/recipes/117225-convex-hull-and-diameter-of-2d-point-sets/
506
+
507
+ .. [2] Rotating Callipers Technique
508
+ https://en.wikipedia.org/wiki/Rotating_calipers
509
+
510
+ """
511
+
512
+ def rotatingCalipers(Points):
513
+ U, L = convex_hull(*Points, **{"polygon": False})
514
+
515
+ if L is None:
516
+ if isinstance(U, Point):
517
+ raise ValueError('At least two distinct points must be given.')
518
+ yield U.args
519
+ else:
520
+ i = 0
521
+ j = len(L) - 1
522
+ while i < len(U) - 1 or j > 0:
523
+ yield U[i], L[j]
524
+ # if all the way through one side of hull, advance the other side
525
+ if i == len(U) - 1:
526
+ j -= 1
527
+ elif j == 0:
528
+ i += 1
529
+ # still points left on both lists, compare slopes of next hull edges
530
+ # being careful to avoid divide-by-zero in slope calculation
531
+ elif (U[i+1].y - U[i].y) * (L[j].x - L[j-1].x) > \
532
+ (L[j].y - L[j-1].y) * (U[i+1].x - U[i].x):
533
+ i += 1
534
+ else:
535
+ j -= 1
536
+
537
+ p = [Point2D(i) for i in set(args)]
538
+
539
+ if not all(i.is_Rational for j in p for i in j.args):
540
+ def hypot(x, y):
541
+ arg = x*x + y*y
542
+ if arg.is_Rational:
543
+ return _sqrt(arg)
544
+ return sqrt(arg)
545
+ else:
546
+ from math import hypot
547
+
548
+ rv = []
549
+ diam = 0
550
+ for pair in rotatingCalipers(args):
551
+ h, q = _ordered_points(pair)
552
+ d = hypot(h.x - q.x, h.y - q.y)
553
+ if d > diam:
554
+ rv = [(h, q)]
555
+ elif d == diam:
556
+ rv.append((h, q))
557
+ else:
558
+ continue
559
+ diam = d
560
+
561
+ return set(rv)
562
+
563
+
564
+ def idiff(eq, y, x, n=1):
565
+ """Return ``dy/dx`` assuming that ``eq == 0``.
566
+
567
+ Parameters
568
+ ==========
569
+
570
+ y : the dependent variable or a list of dependent variables (with y first)
571
+ x : the variable that the derivative is being taken with respect to
572
+ n : the order of the derivative (default is 1)
573
+
574
+ Examples
575
+ ========
576
+
577
+ >>> from sympy.abc import x, y, a
578
+ >>> from sympy.geometry.util import idiff
579
+
580
+ >>> circ = x**2 + y**2 - 4
581
+ >>> idiff(circ, y, x)
582
+ -x/y
583
+ >>> idiff(circ, y, x, 2).simplify()
584
+ (-x**2 - y**2)/y**3
585
+
586
+ Here, ``a`` is assumed to be independent of ``x``:
587
+
588
+ >>> idiff(x + a + y, y, x)
589
+ -1
590
+
591
+ Now the x-dependence of ``a`` is made explicit by listing ``a`` after
592
+ ``y`` in a list.
593
+
594
+ >>> idiff(x + a + y, [y, a], x)
595
+ -Derivative(a, x) - 1
596
+
597
+ See Also
598
+ ========
599
+
600
+ sympy.core.function.Derivative: represents unevaluated derivatives
601
+ sympy.core.function.diff: explicitly differentiates wrt symbols
602
+
603
+ """
604
+ if is_sequence(y):
605
+ dep = set(y)
606
+ y = y[0]
607
+ elif isinstance(y, Symbol):
608
+ dep = {y}
609
+ elif isinstance(y, Function):
610
+ pass
611
+ else:
612
+ raise ValueError("expecting x-dependent symbol(s) or function(s) but got: %s" % y)
613
+
614
+ f = {s: Function(s.name)(x) for s in eq.free_symbols
615
+ if s != x and s in dep}
616
+
617
+ if isinstance(y, Symbol):
618
+ dydx = Function(y.name)(x).diff(x)
619
+ else:
620
+ dydx = y.diff(x)
621
+
622
+ eq = eq.subs(f)
623
+ derivs = {}
624
+ for i in range(n):
625
+ # equation will be linear in dydx, a*dydx + b, so dydx = -b/a
626
+ deq = eq.diff(x)
627
+ b = deq.xreplace({dydx: S.Zero})
628
+ a = (deq - b).xreplace({dydx: S.One})
629
+ yp = factor_terms(expand_mul(cancel((-b/a).subs(derivs)), deep=False))
630
+ if i == n - 1:
631
+ return yp.subs([(v, k) for k, v in f.items()])
632
+ derivs[dydx] = yp
633
+ eq = dydx - yp
634
+ dydx = dydx.diff(x)
635
+
636
+
637
+ def intersection(*entities, pairwise=False, **kwargs):
638
+ """The intersection of a collection of GeometryEntity instances.
639
+
640
+ Parameters
641
+ ==========
642
+ entities : sequence of GeometryEntity
643
+ pairwise (keyword argument) : Can be either True or False
644
+
645
+ Returns
646
+ =======
647
+ intersection : list of GeometryEntity
648
+
649
+ Raises
650
+ ======
651
+ NotImplementedError
652
+ When unable to calculate intersection.
653
+
654
+ Notes
655
+ =====
656
+ The intersection of any geometrical entity with itself should return
657
+ a list with one item: the entity in question.
658
+ An intersection requires two or more entities. If only a single
659
+ entity is given then the function will return an empty list.
660
+ It is possible for `intersection` to miss intersections that one
661
+ knows exists because the required quantities were not fully
662
+ simplified internally.
663
+ Reals should be converted to Rationals, e.g. Rational(str(real_num))
664
+ or else failures due to floating point issues may result.
665
+
666
+ Case 1: When the keyword argument 'pairwise' is False (default value):
667
+ In this case, the function returns a list of intersections common to
668
+ all entities.
669
+
670
+ Case 2: When the keyword argument 'pairwise' is True:
671
+ In this case, the functions returns a list intersections that occur
672
+ between any pair of entities.
673
+
674
+ See Also
675
+ ========
676
+
677
+ sympy.geometry.entity.GeometryEntity.intersection
678
+
679
+ Examples
680
+ ========
681
+
682
+ >>> from sympy import Ray, Circle, intersection
683
+ >>> c = Circle((0, 1), 1)
684
+ >>> intersection(c, c.center)
685
+ []
686
+ >>> right = Ray((0, 0), (1, 0))
687
+ >>> up = Ray((0, 0), (0, 1))
688
+ >>> intersection(c, right, up)
689
+ [Point2D(0, 0)]
690
+ >>> intersection(c, right, up, pairwise=True)
691
+ [Point2D(0, 0), Point2D(0, 2)]
692
+ >>> left = Ray((1, 0), (0, 0))
693
+ >>> intersection(right, left)
694
+ [Segment2D(Point2D(0, 0), Point2D(1, 0))]
695
+
696
+ """
697
+ if len(entities) <= 1:
698
+ return []
699
+
700
+ entities = list(entities)
701
+ prec = None
702
+ for i, e in enumerate(entities):
703
+ if not isinstance(e, GeometryEntity):
704
+ # entities may be an immutable tuple
705
+ e = Point(e)
706
+ # convert to exact Rationals
707
+ d = {}
708
+ for f in e.atoms(Float):
709
+ prec = f._prec if prec is None else min(f._prec, prec)
710
+ d.setdefault(f, nsimplify(f, rational=True))
711
+ entities[i] = e.xreplace(d)
712
+
713
+ if not pairwise:
714
+ # find the intersection common to all objects
715
+ res = entities[0].intersection(entities[1])
716
+ for entity in entities[2:]:
717
+ newres = []
718
+ for x in res:
719
+ newres.extend(x.intersection(entity))
720
+ res = newres
721
+ else:
722
+ # find all pairwise intersections
723
+ ans = []
724
+ for j in range(len(entities)):
725
+ for k in range(j + 1, len(entities)):
726
+ ans.extend(intersection(entities[j], entities[k]))
727
+ res = list(ordered(set(ans)))
728
+
729
+ # convert back to Floats
730
+ if prec is not None:
731
+ p = prec_to_dps(prec)
732
+ res = [i.n(p) for i in res]
733
+ return res
wemm/lib/python3.10/site-packages/sympy/simplify/__init__.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The module helps converting SymPy expressions into shorter forms of them.
2
+
3
+ for example:
4
+ the expression E**(pi*I) will be converted into -1
5
+ the expression (x+x)**2 will be converted into 4*x**2
6
+ """
7
+ from .simplify import (simplify, hypersimp, hypersimilar,
8
+ logcombine, separatevars, posify, besselsimp, kroneckersimp,
9
+ signsimp, nsimplify)
10
+
11
+ from .fu import FU, fu
12
+
13
+ from .sqrtdenest import sqrtdenest
14
+
15
+ from .cse_main import cse
16
+
17
+ from .epathtools import epath, EPath
18
+
19
+ from .hyperexpand import hyperexpand
20
+
21
+ from .radsimp import collect, rcollect, radsimp, collect_const, fraction, numer, denom
22
+
23
+ from .trigsimp import trigsimp, exptrigsimp
24
+
25
+ from .powsimp import powsimp, powdenest
26
+
27
+ from .combsimp import combsimp
28
+
29
+ from .gammasimp import gammasimp
30
+
31
+ from .ratsimp import ratsimp, ratsimpmodprime
32
+
33
+ __all__ = [
34
+ 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars',
35
+ 'posify', 'besselsimp', 'kroneckersimp', 'signsimp',
36
+ 'nsimplify',
37
+
38
+ 'FU', 'fu',
39
+
40
+ 'sqrtdenest',
41
+
42
+ 'cse',
43
+
44
+ 'epath', 'EPath',
45
+
46
+ 'hyperexpand',
47
+
48
+ 'collect', 'rcollect', 'radsimp', 'collect_const', 'fraction', 'numer',
49
+ 'denom',
50
+
51
+ 'trigsimp', 'exptrigsimp',
52
+
53
+ 'powsimp', 'powdenest',
54
+
55
+ 'combsimp',
56
+
57
+ 'gammasimp',
58
+
59
+ 'ratsimp', 'ratsimpmodprime',
60
+ ]
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.34 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc ADDED
Binary file (3.67 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc ADDED
Binary file (26 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc ADDED
Binary file (1.61 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc ADDED
Binary file (8.48 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc ADDED
Binary file (52.1 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc ADDED
Binary file (73.4 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand_doc.cpython-310.pyc ADDED
Binary file (722 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc ADDED
Binary file (17.8 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc ADDED
Binary file (34.6 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc ADDED
Binary file (7.63 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc ADDED
Binary file (57.4 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc ADDED
Binary file (19.5 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/traversaltools.cpython-310.pyc ADDED
Binary file (587 Bytes). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc ADDED
Binary file (33.9 kB). View file
 
wemm/lib/python3.10/site-packages/sympy/simplify/cse_main.py ADDED
@@ -0,0 +1,946 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Tools for doing common subexpression elimination.
2
+ """
3
+ from collections import defaultdict
4
+
5
+ from sympy.core import Basic, Mul, Add, Pow, sympify
6
+ from sympy.core.containers import Tuple, OrderedSet
7
+ from sympy.core.exprtools import factor_terms
8
+ from sympy.core.singleton import S
9
+ from sympy.core.sorting import ordered
10
+ from sympy.core.symbol import symbols, Symbol
11
+ from sympy.matrices import (MatrixBase, Matrix, ImmutableMatrix,
12
+ SparseMatrix, ImmutableSparseMatrix)
13
+ from sympy.matrices.expressions import (MatrixExpr, MatrixSymbol, MatMul,
14
+ MatAdd, MatPow, Inverse)
15
+ from sympy.matrices.expressions.matexpr import MatrixElement
16
+ from sympy.polys.rootoftools import RootOf
17
+ from sympy.utilities.iterables import numbered_symbols, sift, \
18
+ topological_sort, iterable
19
+
20
+ from . import cse_opts
21
+
22
+ # (preprocessor, postprocessor) pairs which are commonly useful. They should
23
+ # each take a SymPy expression and return a possibly transformed expression.
24
+ # When used in the function ``cse()``, the target expressions will be transformed
25
+ # by each of the preprocessor functions in order. After the common
26
+ # subexpressions are eliminated, each resulting expression will have the
27
+ # postprocessor functions transform them in *reverse* order in order to undo the
28
+ # transformation if necessary. This allows the algorithm to operate on
29
+ # a representation of the expressions that allows for more optimization
30
+ # opportunities.
31
+ # ``None`` can be used to specify no transformation for either the preprocessor or
32
+ # postprocessor.
33
+
34
+
35
+ basic_optimizations = [(cse_opts.sub_pre, cse_opts.sub_post),
36
+ (factor_terms, None)]
37
+
38
+ # sometimes we want the output in a different format; non-trivial
39
+ # transformations can be put here for users
40
+ # ===============================================================
41
+
42
+
43
+ def reps_toposort(r):
44
+ """Sort replacements ``r`` so (k1, v1) appears before (k2, v2)
45
+ if k2 is in v1's free symbols. This orders items in the
46
+ way that cse returns its results (hence, in order to use the
47
+ replacements in a substitution option it would make sense
48
+ to reverse the order).
49
+
50
+ Examples
51
+ ========
52
+
53
+ >>> from sympy.simplify.cse_main import reps_toposort
54
+ >>> from sympy.abc import x, y
55
+ >>> from sympy import Eq
56
+ >>> for l, r in reps_toposort([(x, y + 1), (y, 2)]):
57
+ ... print(Eq(l, r))
58
+ ...
59
+ Eq(y, 2)
60
+ Eq(x, y + 1)
61
+
62
+ """
63
+ r = sympify(r)
64
+ E = []
65
+ for c1, (k1, v1) in enumerate(r):
66
+ for c2, (k2, v2) in enumerate(r):
67
+ if k1 in v2.free_symbols:
68
+ E.append((c1, c2))
69
+ return [r[i] for i in topological_sort((range(len(r)), E))]
70
+
71
+
72
+ def cse_separate(r, e):
73
+ """Move expressions that are in the form (symbol, expr) out of the
74
+ expressions and sort them into the replacements using the reps_toposort.
75
+
76
+ Examples
77
+ ========
78
+
79
+ >>> from sympy.simplify.cse_main import cse_separate
80
+ >>> from sympy.abc import x, y, z
81
+ >>> from sympy import cos, exp, cse, Eq, symbols
82
+ >>> x0, x1 = symbols('x:2')
83
+ >>> eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1))
84
+ >>> cse([eq, Eq(x, z + 1), z - 2], postprocess=cse_separate) in [
85
+ ... [[(x0, y + 1), (x, z + 1), (x1, x + 1)],
86
+ ... [x1 + exp(x1/x0) + cos(x0), z - 2]],
87
+ ... [[(x1, y + 1), (x, z + 1), (x0, x + 1)],
88
+ ... [x0 + exp(x0/x1) + cos(x1), z - 2]]]
89
+ ...
90
+ True
91
+ """
92
+ d = sift(e, lambda w: w.is_Equality and w.lhs.is_Symbol)
93
+ r = r + [w.args for w in d[True]]
94
+ e = d[False]
95
+ return [reps_toposort(r), e]
96
+
97
+
98
+ def cse_release_variables(r, e):
99
+ """
100
+ Return tuples giving ``(a, b)`` where ``a`` is a symbol and ``b`` is
101
+ either an expression or None. The value of None is used when a
102
+ symbol is no longer needed for subsequent expressions.
103
+
104
+ Use of such output can reduce the memory footprint of lambdified
105
+ expressions that contain large, repeated subexpressions.
106
+
107
+ Examples
108
+ ========
109
+
110
+ >>> from sympy import cse
111
+ >>> from sympy.simplify.cse_main import cse_release_variables
112
+ >>> from sympy.abc import x, y
113
+ >>> eqs = [(x + y - 1)**2, x, x + y, (x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)]
114
+ >>> defs, rvs = cse_release_variables(*cse(eqs))
115
+ >>> for i in defs:
116
+ ... print(i)
117
+ ...
118
+ (x0, x + y)
119
+ (x1, (x0 - 1)**2)
120
+ (x2, 2*x + 1)
121
+ (_3, x0/x2 + x1)
122
+ (_4, x2**x0)
123
+ (x2, None)
124
+ (_0, x1)
125
+ (x1, None)
126
+ (_2, x0)
127
+ (x0, None)
128
+ (_1, x)
129
+ >>> print(rvs)
130
+ (_0, _1, _2, _3, _4)
131
+ """
132
+ if not r:
133
+ return r, e
134
+
135
+ s, p = zip(*r)
136
+ esyms = symbols('_:%d' % len(e))
137
+ syms = list(esyms)
138
+ s = list(s)
139
+ in_use = set(s)
140
+ p = list(p)
141
+ # sort e so those with most sub-expressions appear first
142
+ e = [(e[i], syms[i]) for i in range(len(e))]
143
+ e, syms = zip(*sorted(e,
144
+ key=lambda x: -sum(p[s.index(i)].count_ops()
145
+ for i in x[0].free_symbols & in_use)))
146
+ syms = list(syms)
147
+ p += e
148
+ rv = []
149
+ i = len(p) - 1
150
+ while i >= 0:
151
+ _p = p.pop()
152
+ c = in_use & _p.free_symbols
153
+ if c: # sorting for canonical results
154
+ rv.extend([(s, None) for s in sorted(c, key=str)])
155
+ if i >= len(r):
156
+ rv.append((syms.pop(), _p))
157
+ else:
158
+ rv.append((s[i], _p))
159
+ in_use -= c
160
+ i -= 1
161
+ rv.reverse()
162
+ return rv, esyms
163
+
164
+
165
+ # ====end of cse postprocess idioms===========================
166
+
167
+
168
+ def preprocess_for_cse(expr, optimizations):
169
+ """ Preprocess an expression to optimize for common subexpression
170
+ elimination.
171
+
172
+ Parameters
173
+ ==========
174
+
175
+ expr : SymPy expression
176
+ The target expression to optimize.
177
+ optimizations : list of (callable, callable) pairs
178
+ The (preprocessor, postprocessor) pairs.
179
+
180
+ Returns
181
+ =======
182
+
183
+ expr : SymPy expression
184
+ The transformed expression.
185
+ """
186
+ for pre, post in optimizations:
187
+ if pre is not None:
188
+ expr = pre(expr)
189
+ return expr
190
+
191
+
192
+ def postprocess_for_cse(expr, optimizations):
193
+ """Postprocess an expression after common subexpression elimination to
194
+ return the expression to canonical SymPy form.
195
+
196
+ Parameters
197
+ ==========
198
+
199
+ expr : SymPy expression
200
+ The target expression to transform.
201
+ optimizations : list of (callable, callable) pairs, optional
202
+ The (preprocessor, postprocessor) pairs. The postprocessors will be
203
+ applied in reversed order to undo the effects of the preprocessors
204
+ correctly.
205
+
206
+ Returns
207
+ =======
208
+
209
+ expr : SymPy expression
210
+ The transformed expression.
211
+ """
212
+ for pre, post in reversed(optimizations):
213
+ if post is not None:
214
+ expr = post(expr)
215
+ return expr
216
+
217
+
218
+ class FuncArgTracker:
219
+ """
220
+ A class which manages a mapping from functions to arguments and an inverse
221
+ mapping from arguments to functions.
222
+ """
223
+
224
+ def __init__(self, funcs):
225
+ # To minimize the number of symbolic comparisons, all function arguments
226
+ # get assigned a value number.
227
+ self.value_numbers = {}
228
+ self.value_number_to_value = []
229
+
230
+ # Both of these maps use integer indices for arguments / functions.
231
+ self.arg_to_funcset = []
232
+ self.func_to_argset = []
233
+
234
+ for func_i, func in enumerate(funcs):
235
+ func_argset = OrderedSet()
236
+
237
+ for func_arg in func.args:
238
+ arg_number = self.get_or_add_value_number(func_arg)
239
+ func_argset.add(arg_number)
240
+ self.arg_to_funcset[arg_number].add(func_i)
241
+
242
+ self.func_to_argset.append(func_argset)
243
+
244
+ def get_args_in_value_order(self, argset):
245
+ """
246
+ Return the list of arguments in sorted order according to their value
247
+ numbers.
248
+ """
249
+ return [self.value_number_to_value[argn] for argn in sorted(argset)]
250
+
251
+ def get_or_add_value_number(self, value):
252
+ """
253
+ Return the value number for the given argument.
254
+ """
255
+ nvalues = len(self.value_numbers)
256
+ value_number = self.value_numbers.setdefault(value, nvalues)
257
+ if value_number == nvalues:
258
+ self.value_number_to_value.append(value)
259
+ self.arg_to_funcset.append(OrderedSet())
260
+ return value_number
261
+
262
+ def stop_arg_tracking(self, func_i):
263
+ """
264
+ Remove the function func_i from the argument to function mapping.
265
+ """
266
+ for arg in self.func_to_argset[func_i]:
267
+ self.arg_to_funcset[arg].remove(func_i)
268
+
269
+
270
+ def get_common_arg_candidates(self, argset, min_func_i=0):
271
+ """Return a dict whose keys are function numbers. The entries of the dict are
272
+ the number of arguments said function has in common with
273
+ ``argset``. Entries have at least 2 items in common. All keys have
274
+ value at least ``min_func_i``.
275
+ """
276
+ count_map = defaultdict(lambda: 0)
277
+ if not argset:
278
+ return count_map
279
+
280
+ funcsets = [self.arg_to_funcset[arg] for arg in argset]
281
+ # As an optimization below, we handle the largest funcset separately from
282
+ # the others.
283
+ largest_funcset = max(funcsets, key=len)
284
+
285
+ for funcset in funcsets:
286
+ if largest_funcset is funcset:
287
+ continue
288
+ for func_i in funcset:
289
+ if func_i >= min_func_i:
290
+ count_map[func_i] += 1
291
+
292
+ # We pick the smaller of the two containers (count_map, largest_funcset)
293
+ # to iterate over to reduce the number of iterations needed.
294
+ (smaller_funcs_container,
295
+ larger_funcs_container) = sorted(
296
+ [largest_funcset, count_map],
297
+ key=len)
298
+
299
+ for func_i in smaller_funcs_container:
300
+ # Not already in count_map? It can't possibly be in the output, so
301
+ # skip it.
302
+ if count_map[func_i] < 1:
303
+ continue
304
+
305
+ if func_i in larger_funcs_container:
306
+ count_map[func_i] += 1
307
+
308
+ return {k: v for k, v in count_map.items() if v >= 2}
309
+
310
+ def get_subset_candidates(self, argset, restrict_to_funcset=None):
311
+ """
312
+ Return a set of functions each of which whose argument list contains
313
+ ``argset``, optionally filtered only to contain functions in
314
+ ``restrict_to_funcset``.
315
+ """
316
+ iarg = iter(argset)
317
+
318
+ indices = OrderedSet(
319
+ fi for fi in self.arg_to_funcset[next(iarg)])
320
+
321
+ if restrict_to_funcset is not None:
322
+ indices &= restrict_to_funcset
323
+
324
+ for arg in iarg:
325
+ indices &= self.arg_to_funcset[arg]
326
+
327
+ return indices
328
+
329
+ def update_func_argset(self, func_i, new_argset):
330
+ """
331
+ Update a function with a new set of arguments.
332
+ """
333
+ new_args = OrderedSet(new_argset)
334
+ old_args = self.func_to_argset[func_i]
335
+
336
+ for deleted_arg in old_args - new_args:
337
+ self.arg_to_funcset[deleted_arg].remove(func_i)
338
+ for added_arg in new_args - old_args:
339
+ self.arg_to_funcset[added_arg].add(func_i)
340
+
341
+ self.func_to_argset[func_i].clear()
342
+ self.func_to_argset[func_i].update(new_args)
343
+
344
+
345
+ class Unevaluated:
346
+
347
+ def __init__(self, func, args):
348
+ self.func = func
349
+ self.args = args
350
+
351
+ def __str__(self):
352
+ return "Uneval<{}>({})".format(
353
+ self.func, ", ".join(str(a) for a in self.args))
354
+
355
+ def as_unevaluated_basic(self):
356
+ return self.func(*self.args, evaluate=False)
357
+
358
+ @property
359
+ def free_symbols(self):
360
+ return set().union(*[a.free_symbols for a in self.args])
361
+
362
+ __repr__ = __str__
363
+
364
+
365
+ def match_common_args(func_class, funcs, opt_subs):
366
+ """
367
+ Recognize and extract common subexpressions of function arguments within a
368
+ set of function calls. For instance, for the following function calls::
369
+
370
+ x + z + y
371
+ sin(x + y)
372
+
373
+ this will extract a common subexpression of `x + y`::
374
+
375
+ w = x + y
376
+ w + z
377
+ sin(w)
378
+
379
+ The function we work with is assumed to be associative and commutative.
380
+
381
+ Parameters
382
+ ==========
383
+
384
+ func_class: class
385
+ The function class (e.g. Add, Mul)
386
+ funcs: list of functions
387
+ A list of function calls.
388
+ opt_subs: dict
389
+ A dictionary of substitutions which this function may update.
390
+ """
391
+
392
+ # Sort to ensure that whole-function subexpressions come before the items
393
+ # that use them.
394
+ funcs = sorted(funcs, key=lambda f: len(f.args))
395
+ arg_tracker = FuncArgTracker(funcs)
396
+
397
+ changed = OrderedSet()
398
+
399
+ for i in range(len(funcs)):
400
+ common_arg_candidates_counts = arg_tracker.get_common_arg_candidates(
401
+ arg_tracker.func_to_argset[i], min_func_i=i + 1)
402
+
403
+ # Sort the candidates in order of match size.
404
+ # This makes us try combining smaller matches first.
405
+ common_arg_candidates = OrderedSet(sorted(
406
+ common_arg_candidates_counts.keys(),
407
+ key=lambda k: (common_arg_candidates_counts[k], k)))
408
+
409
+ while common_arg_candidates:
410
+ j = common_arg_candidates.pop(last=False)
411
+
412
+ com_args = arg_tracker.func_to_argset[i].intersection(
413
+ arg_tracker.func_to_argset[j])
414
+
415
+ if len(com_args) <= 1:
416
+ # This may happen if a set of common arguments was already
417
+ # combined in a previous iteration.
418
+ continue
419
+
420
+ # For all sets, replace the common symbols by the function
421
+ # over them, to allow recursive matches.
422
+
423
+ diff_i = arg_tracker.func_to_argset[i].difference(com_args)
424
+ if diff_i:
425
+ # com_func needs to be unevaluated to allow for recursive matches.
426
+ com_func = Unevaluated(
427
+ func_class, arg_tracker.get_args_in_value_order(com_args))
428
+ com_func_number = arg_tracker.get_or_add_value_number(com_func)
429
+ arg_tracker.update_func_argset(i, diff_i | OrderedSet([com_func_number]))
430
+ changed.add(i)
431
+ else:
432
+ # Treat the whole expression as a CSE.
433
+ #
434
+ # The reason this needs to be done is somewhat subtle. Within
435
+ # tree_cse(), to_eliminate only contains expressions that are
436
+ # seen more than once. The problem is unevaluated expressions
437
+ # do not compare equal to the evaluated equivalent. So
438
+ # tree_cse() won't mark funcs[i] as a CSE if we use an
439
+ # unevaluated version.
440
+ com_func_number = arg_tracker.get_or_add_value_number(funcs[i])
441
+
442
+ diff_j = arg_tracker.func_to_argset[j].difference(com_args)
443
+ arg_tracker.update_func_argset(j, diff_j | OrderedSet([com_func_number]))
444
+ changed.add(j)
445
+
446
+ for k in arg_tracker.get_subset_candidates(
447
+ com_args, common_arg_candidates):
448
+ diff_k = arg_tracker.func_to_argset[k].difference(com_args)
449
+ arg_tracker.update_func_argset(k, diff_k | OrderedSet([com_func_number]))
450
+ changed.add(k)
451
+
452
+ if i in changed:
453
+ opt_subs[funcs[i]] = Unevaluated(func_class,
454
+ arg_tracker.get_args_in_value_order(arg_tracker.func_to_argset[i]))
455
+
456
+ arg_tracker.stop_arg_tracking(i)
457
+
458
+
459
+ def opt_cse(exprs, order='canonical'):
460
+ """Find optimization opportunities in Adds, Muls, Pows and negative
461
+ coefficient Muls.
462
+
463
+ Parameters
464
+ ==========
465
+
466
+ exprs : list of SymPy expressions
467
+ The expressions to optimize.
468
+ order : string, 'none' or 'canonical'
469
+ The order by which Mul and Add arguments are processed. For large
470
+ expressions where speed is a concern, use the setting order='none'.
471
+
472
+ Returns
473
+ =======
474
+
475
+ opt_subs : dictionary of expression substitutions
476
+ The expression substitutions which can be useful to optimize CSE.
477
+
478
+ Examples
479
+ ========
480
+
481
+ >>> from sympy.simplify.cse_main import opt_cse
482
+ >>> from sympy.abc import x
483
+ >>> opt_subs = opt_cse([x**-2])
484
+ >>> k, v = list(opt_subs.keys())[0], list(opt_subs.values())[0]
485
+ >>> print((k, v.as_unevaluated_basic()))
486
+ (x**(-2), 1/(x**2))
487
+ """
488
+ opt_subs = {}
489
+
490
+ adds = OrderedSet()
491
+ muls = OrderedSet()
492
+
493
+ seen_subexp = set()
494
+ collapsible_subexp = set()
495
+
496
+ def _find_opts(expr):
497
+
498
+ if not isinstance(expr, (Basic, Unevaluated)):
499
+ return
500
+
501
+ if expr.is_Atom or expr.is_Order:
502
+ return
503
+
504
+ if iterable(expr):
505
+ list(map(_find_opts, expr))
506
+ return
507
+
508
+ if expr in seen_subexp:
509
+ return expr
510
+ seen_subexp.add(expr)
511
+
512
+ list(map(_find_opts, expr.args))
513
+
514
+ if not isinstance(expr, MatrixExpr) and expr.could_extract_minus_sign():
515
+ # XXX -expr does not always work rigorously for some expressions
516
+ # containing UnevaluatedExpr.
517
+ # https://github.com/sympy/sympy/issues/24818
518
+ if isinstance(expr, Add):
519
+ neg_expr = Add(*(-i for i in expr.args))
520
+ else:
521
+ neg_expr = -expr
522
+
523
+ if not neg_expr.is_Atom:
524
+ opt_subs[expr] = Unevaluated(Mul, (S.NegativeOne, neg_expr))
525
+ seen_subexp.add(neg_expr)
526
+ expr = neg_expr
527
+
528
+ if isinstance(expr, (Mul, MatMul)):
529
+ if len(expr.args) == 1:
530
+ collapsible_subexp.add(expr)
531
+ else:
532
+ muls.add(expr)
533
+
534
+ elif isinstance(expr, (Add, MatAdd)):
535
+ if len(expr.args) == 1:
536
+ collapsible_subexp.add(expr)
537
+ else:
538
+ adds.add(expr)
539
+
540
+ elif isinstance(expr, Inverse):
541
+ # Do not want to treat `Inverse` as a `MatPow`
542
+ pass
543
+
544
+ elif isinstance(expr, (Pow, MatPow)):
545
+ base, exp = expr.base, expr.exp
546
+ if exp.could_extract_minus_sign():
547
+ opt_subs[expr] = Unevaluated(Pow, (Pow(base, -exp), -1))
548
+
549
+ for e in exprs:
550
+ if isinstance(e, (Basic, Unevaluated)):
551
+ _find_opts(e)
552
+
553
+ # Handle collapsing of multinary operations with single arguments
554
+ edges = [(s, s.args[0]) for s in collapsible_subexp
555
+ if s.args[0] in collapsible_subexp]
556
+ for e in reversed(topological_sort((collapsible_subexp, edges))):
557
+ opt_subs[e] = opt_subs.get(e.args[0], e.args[0])
558
+
559
+ # split muls into commutative
560
+ commutative_muls = OrderedSet()
561
+ for m in muls:
562
+ c, nc = m.args_cnc(cset=False)
563
+ if c:
564
+ c_mul = m.func(*c)
565
+ if nc:
566
+ if c_mul == 1:
567
+ new_obj = m.func(*nc)
568
+ else:
569
+ if isinstance(m, MatMul):
570
+ new_obj = m.func(c_mul, *nc, evaluate=False)
571
+ else:
572
+ new_obj = m.func(c_mul, m.func(*nc), evaluate=False)
573
+ opt_subs[m] = new_obj
574
+ if len(c) > 1:
575
+ commutative_muls.add(c_mul)
576
+
577
+ match_common_args(Add, adds, opt_subs)
578
+ match_common_args(Mul, commutative_muls, opt_subs)
579
+
580
+ return opt_subs
581
+
582
+
583
+ def tree_cse(exprs, symbols, opt_subs=None, order='canonical', ignore=()):
584
+ """Perform raw CSE on expression tree, taking opt_subs into account.
585
+
586
+ Parameters
587
+ ==========
588
+
589
+ exprs : list of SymPy expressions
590
+ The expressions to reduce.
591
+ symbols : infinite iterator yielding unique Symbols
592
+ The symbols used to label the common subexpressions which are pulled
593
+ out.
594
+ opt_subs : dictionary of expression substitutions
595
+ The expressions to be substituted before any CSE action is performed.
596
+ order : string, 'none' or 'canonical'
597
+ The order by which Mul and Add arguments are processed. For large
598
+ expressions where speed is a concern, use the setting order='none'.
599
+ ignore : iterable of Symbols
600
+ Substitutions containing any Symbol from ``ignore`` will be ignored.
601
+ """
602
+ if opt_subs is None:
603
+ opt_subs = {}
604
+
605
+ ## Find repeated sub-expressions
606
+
607
+ to_eliminate = set()
608
+
609
+ seen_subexp = set()
610
+ excluded_symbols = set()
611
+
612
+ def _find_repeated(expr):
613
+ if not isinstance(expr, (Basic, Unevaluated)):
614
+ return
615
+
616
+ if isinstance(expr, RootOf):
617
+ return
618
+
619
+ if isinstance(expr, Basic) and (
620
+ expr.is_Atom or
621
+ expr.is_Order or
622
+ isinstance(expr, (MatrixSymbol, MatrixElement))):
623
+ if expr.is_Symbol:
624
+ excluded_symbols.add(expr.name)
625
+ return
626
+
627
+ if iterable(expr):
628
+ args = expr
629
+
630
+ else:
631
+ if expr in seen_subexp:
632
+ for ign in ignore:
633
+ if ign in expr.free_symbols:
634
+ break
635
+ else:
636
+ to_eliminate.add(expr)
637
+ return
638
+
639
+ seen_subexp.add(expr)
640
+
641
+ if expr in opt_subs:
642
+ expr = opt_subs[expr]
643
+
644
+ args = expr.args
645
+
646
+ list(map(_find_repeated, args))
647
+
648
+ for e in exprs:
649
+ if isinstance(e, Basic):
650
+ _find_repeated(e)
651
+
652
+ ## Rebuild tree
653
+
654
+ # Remove symbols from the generator that conflict with names in the expressions.
655
+ symbols = (_ for _ in symbols if _.name not in excluded_symbols)
656
+
657
+ replacements = []
658
+
659
+ subs = {}
660
+
661
+ def _rebuild(expr):
662
+ if not isinstance(expr, (Basic, Unevaluated)):
663
+ return expr
664
+
665
+ if not expr.args:
666
+ return expr
667
+
668
+ if iterable(expr):
669
+ new_args = [_rebuild(arg) for arg in expr.args]
670
+ return expr.func(*new_args)
671
+
672
+ if expr in subs:
673
+ return subs[expr]
674
+
675
+ orig_expr = expr
676
+ if expr in opt_subs:
677
+ expr = opt_subs[expr]
678
+
679
+ # If enabled, parse Muls and Adds arguments by order to ensure
680
+ # replacement order independent from hashes
681
+ if order != 'none':
682
+ if isinstance(expr, (Mul, MatMul)):
683
+ c, nc = expr.args_cnc()
684
+ if c == [1]:
685
+ args = nc
686
+ else:
687
+ args = list(ordered(c)) + nc
688
+ elif isinstance(expr, (Add, MatAdd)):
689
+ args = list(ordered(expr.args))
690
+ else:
691
+ args = expr.args
692
+ else:
693
+ args = expr.args
694
+
695
+ new_args = list(map(_rebuild, args))
696
+ if isinstance(expr, Unevaluated) or new_args != args:
697
+ new_expr = expr.func(*new_args)
698
+ else:
699
+ new_expr = expr
700
+
701
+ if orig_expr in to_eliminate:
702
+ try:
703
+ sym = next(symbols)
704
+ except StopIteration:
705
+ raise ValueError("Symbols iterator ran out of symbols.")
706
+
707
+ if isinstance(orig_expr, MatrixExpr):
708
+ sym = MatrixSymbol(sym.name, orig_expr.rows,
709
+ orig_expr.cols)
710
+
711
+ subs[orig_expr] = sym
712
+ replacements.append((sym, new_expr))
713
+ return sym
714
+
715
+ else:
716
+ return new_expr
717
+
718
+ reduced_exprs = []
719
+ for e in exprs:
720
+ if isinstance(e, Basic):
721
+ reduced_e = _rebuild(e)
722
+ else:
723
+ reduced_e = e
724
+ reduced_exprs.append(reduced_e)
725
+ return replacements, reduced_exprs
726
+
727
+
728
+ def cse(exprs, symbols=None, optimizations=None, postprocess=None,
729
+ order='canonical', ignore=(), list=True):
730
+ """ Perform common subexpression elimination on an expression.
731
+
732
+ Parameters
733
+ ==========
734
+
735
+ exprs : list of SymPy expressions, or a single SymPy expression
736
+ The expressions to reduce.
737
+ symbols : infinite iterator yielding unique Symbols
738
+ The symbols used to label the common subexpressions which are pulled
739
+ out. The ``numbered_symbols`` generator is useful. The default is a
740
+ stream of symbols of the form "x0", "x1", etc. This must be an
741
+ infinite iterator.
742
+ optimizations : list of (callable, callable) pairs
743
+ The (preprocessor, postprocessor) pairs of external optimization
744
+ functions. Optionally 'basic' can be passed for a set of predefined
745
+ basic optimizations. Such 'basic' optimizations were used by default
746
+ in old implementation, however they can be really slow on larger
747
+ expressions. Now, no pre or post optimizations are made by default.
748
+ postprocess : a function which accepts the two return values of cse and
749
+ returns the desired form of output from cse, e.g. if you want the
750
+ replacements reversed the function might be the following lambda:
751
+ lambda r, e: return reversed(r), e
752
+ order : string, 'none' or 'canonical'
753
+ The order by which Mul and Add arguments are processed. If set to
754
+ 'canonical', arguments will be canonically ordered. If set to 'none',
755
+ ordering will be faster but dependent on expressions hashes, thus
756
+ machine dependent and variable. For large expressions where speed is a
757
+ concern, use the setting order='none'.
758
+ ignore : iterable of Symbols
759
+ Substitutions containing any Symbol from ``ignore`` will be ignored.
760
+ list : bool, (default True)
761
+ Returns expression in list or else with same type as input (when False).
762
+
763
+ Returns
764
+ =======
765
+
766
+ replacements : list of (Symbol, expression) pairs
767
+ All of the common subexpressions that were replaced. Subexpressions
768
+ earlier in this list might show up in subexpressions later in this
769
+ list.
770
+ reduced_exprs : list of SymPy expressions
771
+ The reduced expressions with all of the replacements above.
772
+
773
+ Examples
774
+ ========
775
+
776
+ >>> from sympy import cse, SparseMatrix
777
+ >>> from sympy.abc import x, y, z, w
778
+ >>> cse(((w + x + y + z)*(w + y + z))/(w + x)**3)
779
+ ([(x0, y + z), (x1, w + x)], [(w + x0)*(x0 + x1)/x1**3])
780
+
781
+
782
+ List of expressions with recursive substitutions:
783
+
784
+ >>> m = SparseMatrix([x + y, x + y + z])
785
+ >>> cse([(x+y)**2, x + y + z, y + z, x + z + y, m])
786
+ ([(x0, x + y), (x1, x0 + z)], [x0**2, x1, y + z, x1, Matrix([
787
+ [x0],
788
+ [x1]])])
789
+
790
+ Note: the type and mutability of input matrices is retained.
791
+
792
+ >>> isinstance(_[1][-1], SparseMatrix)
793
+ True
794
+
795
+ The user may disallow substitutions containing certain symbols:
796
+
797
+ >>> cse([y**2*(x + 1), 3*y**2*(x + 1)], ignore=(y,))
798
+ ([(x0, x + 1)], [x0*y**2, 3*x0*y**2])
799
+
800
+ The default return value for the reduced expression(s) is a list, even if there is only
801
+ one expression. The `list` flag preserves the type of the input in the output:
802
+
803
+ >>> cse(x)
804
+ ([], [x])
805
+ >>> cse(x, list=False)
806
+ ([], x)
807
+ """
808
+ if not list:
809
+ return _cse_homogeneous(exprs,
810
+ symbols=symbols, optimizations=optimizations,
811
+ postprocess=postprocess, order=order, ignore=ignore)
812
+
813
+ if isinstance(exprs, (int, float)):
814
+ exprs = sympify(exprs)
815
+
816
+ # Handle the case if just one expression was passed.
817
+ if isinstance(exprs, (Basic, MatrixBase)):
818
+ exprs = [exprs]
819
+
820
+ copy = exprs
821
+ temp = []
822
+ for e in exprs:
823
+ if isinstance(e, (Matrix, ImmutableMatrix)):
824
+ temp.append(Tuple(*e.flat()))
825
+ elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)):
826
+ temp.append(Tuple(*e.todok().items()))
827
+ else:
828
+ temp.append(e)
829
+ exprs = temp
830
+ del temp
831
+
832
+ if optimizations is None:
833
+ optimizations = []
834
+ elif optimizations == 'basic':
835
+ optimizations = basic_optimizations
836
+
837
+ # Preprocess the expressions to give us better optimization opportunities.
838
+ reduced_exprs = [preprocess_for_cse(e, optimizations) for e in exprs]
839
+
840
+ if symbols is None:
841
+ symbols = numbered_symbols(cls=Symbol)
842
+ else:
843
+ # In case we get passed an iterable with an __iter__ method instead of
844
+ # an actual iterator.
845
+ symbols = iter(symbols)
846
+
847
+ # Find other optimization opportunities.
848
+ opt_subs = opt_cse(reduced_exprs, order)
849
+
850
+ # Main CSE algorithm.
851
+ replacements, reduced_exprs = tree_cse(reduced_exprs, symbols, opt_subs,
852
+ order, ignore)
853
+
854
+ # Postprocess the expressions to return the expressions to canonical form.
855
+ exprs = copy
856
+ for i, (sym, subtree) in enumerate(replacements):
857
+ subtree = postprocess_for_cse(subtree, optimizations)
858
+ replacements[i] = (sym, subtree)
859
+ reduced_exprs = [postprocess_for_cse(e, optimizations)
860
+ for e in reduced_exprs]
861
+
862
+ # Get the matrices back
863
+ for i, e in enumerate(exprs):
864
+ if isinstance(e, (Matrix, ImmutableMatrix)):
865
+ reduced_exprs[i] = Matrix(e.rows, e.cols, reduced_exprs[i])
866
+ if isinstance(e, ImmutableMatrix):
867
+ reduced_exprs[i] = reduced_exprs[i].as_immutable()
868
+ elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)):
869
+ m = SparseMatrix(e.rows, e.cols, {})
870
+ for k, v in reduced_exprs[i]:
871
+ m[k] = v
872
+ if isinstance(e, ImmutableSparseMatrix):
873
+ m = m.as_immutable()
874
+ reduced_exprs[i] = m
875
+
876
+ if postprocess is None:
877
+ return replacements, reduced_exprs
878
+
879
+ return postprocess(replacements, reduced_exprs)
880
+
881
+
882
+ def _cse_homogeneous(exprs, **kwargs):
883
+ """
884
+ Same as ``cse`` but the ``reduced_exprs`` are returned
885
+ with the same type as ``exprs`` or a sympified version of the same.
886
+
887
+ Parameters
888
+ ==========
889
+
890
+ exprs : an Expr, iterable of Expr or dictionary with Expr values
891
+ the expressions in which repeated subexpressions will be identified
892
+ kwargs : additional arguments for the ``cse`` function
893
+
894
+ Returns
895
+ =======
896
+
897
+ replacements : list of (Symbol, expression) pairs
898
+ All of the common subexpressions that were replaced. Subexpressions
899
+ earlier in this list might show up in subexpressions later in this
900
+ list.
901
+ reduced_exprs : list of SymPy expressions
902
+ The reduced expressions with all of the replacements above.
903
+
904
+ Examples
905
+ ========
906
+
907
+ >>> from sympy.simplify.cse_main import cse
908
+ >>> from sympy import cos, Tuple, Matrix
909
+ >>> from sympy.abc import x
910
+ >>> output = lambda x: type(cse(x, list=False)[1])
911
+ >>> output(1)
912
+ <class 'sympy.core.numbers.One'>
913
+ >>> output('cos(x)')
914
+ <class 'str'>
915
+ >>> output(cos(x))
916
+ cos
917
+ >>> output(Tuple(1, x))
918
+ <class 'sympy.core.containers.Tuple'>
919
+ >>> output(Matrix([[1,0], [0,1]]))
920
+ <class 'sympy.matrices.dense.MutableDenseMatrix'>
921
+ >>> output([1, x])
922
+ <class 'list'>
923
+ >>> output((1, x))
924
+ <class 'tuple'>
925
+ >>> output({1, x})
926
+ <class 'set'>
927
+ """
928
+ if isinstance(exprs, str):
929
+ replacements, reduced_exprs = _cse_homogeneous(
930
+ sympify(exprs), **kwargs)
931
+ return replacements, repr(reduced_exprs)
932
+ if isinstance(exprs, (list, tuple, set)):
933
+ replacements, reduced_exprs = cse(exprs, **kwargs)
934
+ return replacements, type(exprs)(reduced_exprs)
935
+ if isinstance(exprs, dict):
936
+ keys = list(exprs.keys()) # In order to guarantee the order of the elements.
937
+ replacements, values = cse([exprs[k] for k in keys], **kwargs)
938
+ reduced_exprs = dict(zip(keys, values))
939
+ return replacements, reduced_exprs
940
+
941
+ try:
942
+ replacements, (reduced_exprs,) = cse(exprs, **kwargs)
943
+ except TypeError: # For example 'mpf' objects
944
+ return [], exprs
945
+ else:
946
+ return replacements, reduced_exprs
wemm/lib/python3.10/site-packages/sympy/simplify/fu.py ADDED
@@ -0,0 +1,2111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ from sympy.core.add import Add
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.exprtools import Factors, gcd_terms, factor_terms
6
+ from sympy.core.function import expand_mul
7
+ from sympy.core.mul import Mul
8
+ from sympy.core.numbers import pi, I
9
+ from sympy.core.power import Pow
10
+ from sympy.core.singleton import S
11
+ from sympy.core.sorting import ordered
12
+ from sympy.core.symbol import Dummy
13
+ from sympy.core.sympify import sympify
14
+ from sympy.core.traversal import bottom_up
15
+ from sympy.functions.combinatorial.factorials import binomial
16
+ from sympy.functions.elementary.hyperbolic import (
17
+ cosh, sinh, tanh, coth, sech, csch, HyperbolicFunction)
18
+ from sympy.functions.elementary.trigonometric import (
19
+ cos, sin, tan, cot, sec, csc, sqrt, TrigonometricFunction)
20
+ from sympy.ntheory.factor_ import perfect_power
21
+ from sympy.polys.polytools import factor
22
+ from sympy.strategies.tree import greedy
23
+ from sympy.strategies.core import identity, debug
24
+
25
+ from sympy import SYMPY_DEBUG
26
+
27
+
28
+ # ================== Fu-like tools ===========================
29
+
30
+
31
+ def TR0(rv):
32
+ """Simplification of rational polynomials, trying to simplify
33
+ the expression, e.g. combine things like 3*x + 2*x, etc....
34
+ """
35
+ # although it would be nice to use cancel, it doesn't work
36
+ # with noncommutatives
37
+ return rv.normal().factor().expand()
38
+
39
+
40
+ def TR1(rv):
41
+ """Replace sec, csc with 1/cos, 1/sin
42
+
43
+ Examples
44
+ ========
45
+
46
+ >>> from sympy.simplify.fu import TR1, sec, csc
47
+ >>> from sympy.abc import x
48
+ >>> TR1(2*csc(x) + sec(x))
49
+ 1/cos(x) + 2/sin(x)
50
+ """
51
+
52
+ def f(rv):
53
+ if isinstance(rv, sec):
54
+ a = rv.args[0]
55
+ return S.One/cos(a)
56
+ elif isinstance(rv, csc):
57
+ a = rv.args[0]
58
+ return S.One/sin(a)
59
+ return rv
60
+
61
+ return bottom_up(rv, f)
62
+
63
+
64
+ def TR2(rv):
65
+ """Replace tan and cot with sin/cos and cos/sin
66
+
67
+ Examples
68
+ ========
69
+
70
+ >>> from sympy.simplify.fu import TR2
71
+ >>> from sympy.abc import x
72
+ >>> from sympy import tan, cot, sin, cos
73
+ >>> TR2(tan(x))
74
+ sin(x)/cos(x)
75
+ >>> TR2(cot(x))
76
+ cos(x)/sin(x)
77
+ >>> TR2(tan(tan(x) - sin(x)/cos(x)))
78
+ 0
79
+
80
+ """
81
+
82
+ def f(rv):
83
+ if isinstance(rv, tan):
84
+ a = rv.args[0]
85
+ return sin(a)/cos(a)
86
+ elif isinstance(rv, cot):
87
+ a = rv.args[0]
88
+ return cos(a)/sin(a)
89
+ return rv
90
+
91
+ return bottom_up(rv, f)
92
+
93
+
94
+ def TR2i(rv, half=False):
95
+ """Converts ratios involving sin and cos as follows::
96
+ sin(x)/cos(x) -> tan(x)
97
+ sin(x)/(cos(x) + 1) -> tan(x/2) if half=True
98
+
99
+ Examples
100
+ ========
101
+
102
+ >>> from sympy.simplify.fu import TR2i
103
+ >>> from sympy.abc import x, a
104
+ >>> from sympy import sin, cos
105
+ >>> TR2i(sin(x)/cos(x))
106
+ tan(x)
107
+
108
+ Powers of the numerator and denominator are also recognized
109
+
110
+ >>> TR2i(sin(x)**2/(cos(x) + 1)**2, half=True)
111
+ tan(x/2)**2
112
+
113
+ The transformation does not take place unless assumptions allow
114
+ (i.e. the base must be positive or the exponent must be an integer
115
+ for both numerator and denominator)
116
+
117
+ >>> TR2i(sin(x)**a/(cos(x) + 1)**a)
118
+ sin(x)**a/(cos(x) + 1)**a
119
+
120
+ """
121
+
122
+ def f(rv):
123
+ if not rv.is_Mul:
124
+ return rv
125
+
126
+ n, d = rv.as_numer_denom()
127
+ if n.is_Atom or d.is_Atom:
128
+ return rv
129
+
130
+ def ok(k, e):
131
+ # initial filtering of factors
132
+ return (
133
+ (e.is_integer or k.is_positive) and (
134
+ k.func in (sin, cos) or (half and
135
+ k.is_Add and
136
+ len(k.args) >= 2 and
137
+ any(any(isinstance(ai, cos) or ai.is_Pow and ai.base is cos
138
+ for ai in Mul.make_args(a)) for a in k.args))))
139
+
140
+ n = n.as_powers_dict()
141
+ ndone = [(k, n.pop(k)) for k in list(n.keys()) if not ok(k, n[k])]
142
+ if not n:
143
+ return rv
144
+
145
+ d = d.as_powers_dict()
146
+ ddone = [(k, d.pop(k)) for k in list(d.keys()) if not ok(k, d[k])]
147
+ if not d:
148
+ return rv
149
+
150
+ # factoring if necessary
151
+
152
+ def factorize(d, ddone):
153
+ newk = []
154
+ for k in d:
155
+ if k.is_Add and len(k.args) > 1:
156
+ knew = factor(k) if half else factor_terms(k)
157
+ if knew != k:
158
+ newk.append((k, knew))
159
+ if newk:
160
+ for i, (k, knew) in enumerate(newk):
161
+ del d[k]
162
+ newk[i] = knew
163
+ newk = Mul(*newk).as_powers_dict()
164
+ for k in newk:
165
+ v = d[k] + newk[k]
166
+ if ok(k, v):
167
+ d[k] = v
168
+ else:
169
+ ddone.append((k, v))
170
+ del newk
171
+ factorize(n, ndone)
172
+ factorize(d, ddone)
173
+
174
+ # joining
175
+ t = []
176
+ for k in n:
177
+ if isinstance(k, sin):
178
+ a = cos(k.args[0], evaluate=False)
179
+ if a in d and d[a] == n[k]:
180
+ t.append(tan(k.args[0])**n[k])
181
+ n[k] = d[a] = None
182
+ elif half:
183
+ a1 = 1 + a
184
+ if a1 in d and d[a1] == n[k]:
185
+ t.append((tan(k.args[0]/2))**n[k])
186
+ n[k] = d[a1] = None
187
+ elif isinstance(k, cos):
188
+ a = sin(k.args[0], evaluate=False)
189
+ if a in d and d[a] == n[k]:
190
+ t.append(tan(k.args[0])**-n[k])
191
+ n[k] = d[a] = None
192
+ elif half and k.is_Add and k.args[0] is S.One and \
193
+ isinstance(k.args[1], cos):
194
+ a = sin(k.args[1].args[0], evaluate=False)
195
+ if a in d and d[a] == n[k] and (d[a].is_integer or \
196
+ a.is_positive):
197
+ t.append(tan(a.args[0]/2)**-n[k])
198
+ n[k] = d[a] = None
199
+
200
+ if t:
201
+ rv = Mul(*(t + [b**e for b, e in n.items() if e]))/\
202
+ Mul(*[b**e for b, e in d.items() if e])
203
+ rv *= Mul(*[b**e for b, e in ndone])/Mul(*[b**e for b, e in ddone])
204
+
205
+ return rv
206
+
207
+ return bottom_up(rv, f)
208
+
209
+
210
+ def TR3(rv):
211
+ """Induced formula: example sin(-a) = -sin(a)
212
+
213
+ Examples
214
+ ========
215
+
216
+ >>> from sympy.simplify.fu import TR3
217
+ >>> from sympy.abc import x, y
218
+ >>> from sympy import pi
219
+ >>> from sympy import cos
220
+ >>> TR3(cos(y - x*(y - x)))
221
+ cos(x*(x - y) + y)
222
+ >>> cos(pi/2 + x)
223
+ -sin(x)
224
+ >>> cos(30*pi/2 + x)
225
+ -cos(x)
226
+
227
+ """
228
+ from sympy.simplify.simplify import signsimp
229
+
230
+ # Negative argument (already automatic for funcs like sin(-x) -> -sin(x)
231
+ # but more complicated expressions can use it, too). Also, trig angles
232
+ # between pi/4 and pi/2 are not reduced to an angle between 0 and pi/4.
233
+ # The following are automatically handled:
234
+ # Argument of type: pi/2 +/- angle
235
+ # Argument of type: pi +/- angle
236
+ # Argument of type : 2k*pi +/- angle
237
+
238
+ def f(rv):
239
+ if not isinstance(rv, TrigonometricFunction):
240
+ return rv
241
+ rv = rv.func(signsimp(rv.args[0]))
242
+ if not isinstance(rv, TrigonometricFunction):
243
+ return rv
244
+ if (rv.args[0] - S.Pi/4).is_positive is (S.Pi/2 - rv.args[0]).is_positive is True:
245
+ fmap = {cos: sin, sin: cos, tan: cot, cot: tan, sec: csc, csc: sec}
246
+ rv = fmap[type(rv)](S.Pi/2 - rv.args[0])
247
+ return rv
248
+
249
+ # touch numbers iside of trig functions to let them automatically update
250
+ rv = rv.replace(
251
+ lambda x: isinstance(x, TrigonometricFunction),
252
+ lambda x: x.replace(
253
+ lambda n: n.is_number and n.is_Mul,
254
+ lambda n: n.func(*n.args)))
255
+
256
+ return bottom_up(rv, f)
257
+
258
+
259
+ def TR4(rv):
260
+ """Identify values of special angles.
261
+
262
+ a= 0 pi/6 pi/4 pi/3 pi/2
263
+ ----------------------------------------------------
264
+ sin(a) 0 1/2 sqrt(2)/2 sqrt(3)/2 1
265
+ cos(a) 1 sqrt(3)/2 sqrt(2)/2 1/2 0
266
+ tan(a) 0 sqt(3)/3 1 sqrt(3) --
267
+
268
+ Examples
269
+ ========
270
+
271
+ >>> from sympy import pi
272
+ >>> from sympy import cos, sin, tan, cot
273
+ >>> for s in (0, pi/6, pi/4, pi/3, pi/2):
274
+ ... print('%s %s %s %s' % (cos(s), sin(s), tan(s), cot(s)))
275
+ ...
276
+ 1 0 0 zoo
277
+ sqrt(3)/2 1/2 sqrt(3)/3 sqrt(3)
278
+ sqrt(2)/2 sqrt(2)/2 1 1
279
+ 1/2 sqrt(3)/2 sqrt(3) sqrt(3)/3
280
+ 0 1 zoo 0
281
+ """
282
+ # special values at 0, pi/6, pi/4, pi/3, pi/2 already handled
283
+ return rv.replace(
284
+ lambda x:
285
+ isinstance(x, TrigonometricFunction) and
286
+ (r:=x.args[0]/pi).is_Rational and r.q in (1, 2, 3, 4, 6),
287
+ lambda x:
288
+ x.func(x.args[0].func(*x.args[0].args)))
289
+
290
+
291
+ def _TR56(rv, f, g, h, max, pow):
292
+ """Helper for TR5 and TR6 to replace f**2 with h(g**2)
293
+
294
+ Options
295
+ =======
296
+
297
+ max : controls size of exponent that can appear on f
298
+ e.g. if max=4 then f**4 will be changed to h(g**2)**2.
299
+ pow : controls whether the exponent must be a perfect power of 2
300
+ e.g. if pow=True (and max >= 6) then f**6 will not be changed
301
+ but f**8 will be changed to h(g**2)**4
302
+
303
+ >>> from sympy.simplify.fu import _TR56 as T
304
+ >>> from sympy.abc import x
305
+ >>> from sympy import sin, cos
306
+ >>> h = lambda x: 1 - x
307
+ >>> T(sin(x)**3, sin, cos, h, 4, False)
308
+ (1 - cos(x)**2)*sin(x)
309
+ >>> T(sin(x)**6, sin, cos, h, 6, False)
310
+ (1 - cos(x)**2)**3
311
+ >>> T(sin(x)**6, sin, cos, h, 6, True)
312
+ sin(x)**6
313
+ >>> T(sin(x)**8, sin, cos, h, 10, True)
314
+ (1 - cos(x)**2)**4
315
+ """
316
+
317
+ def _f(rv):
318
+ # I'm not sure if this transformation should target all even powers
319
+ # or only those expressible as powers of 2. Also, should it only
320
+ # make the changes in powers that appear in sums -- making an isolated
321
+ # change is not going to allow a simplification as far as I can tell.
322
+ if not (rv.is_Pow and rv.base.func == f):
323
+ return rv
324
+ if not rv.exp.is_real:
325
+ return rv
326
+
327
+ if (rv.exp < 0) == True:
328
+ return rv
329
+ if (rv.exp > max) == True:
330
+ return rv
331
+ if rv.exp == 1:
332
+ return rv
333
+ if rv.exp == 2:
334
+ return h(g(rv.base.args[0])**2)
335
+ else:
336
+ if rv.exp % 2 == 1:
337
+ e = rv.exp//2
338
+ return f(rv.base.args[0])*h(g(rv.base.args[0])**2)**e
339
+ elif rv.exp == 4:
340
+ e = 2
341
+ elif not pow:
342
+ if rv.exp % 2:
343
+ return rv
344
+ e = rv.exp//2
345
+ else:
346
+ p = perfect_power(rv.exp)
347
+ if not p:
348
+ return rv
349
+ e = rv.exp//2
350
+ return h(g(rv.base.args[0])**2)**e
351
+
352
+ return bottom_up(rv, _f)
353
+
354
+
355
+ def TR5(rv, max=4, pow=False):
356
+ """Replacement of sin**2 with 1 - cos(x)**2.
357
+
358
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
359
+
360
+ Examples
361
+ ========
362
+
363
+ >>> from sympy.simplify.fu import TR5
364
+ >>> from sympy.abc import x
365
+ >>> from sympy import sin
366
+ >>> TR5(sin(x)**2)
367
+ 1 - cos(x)**2
368
+ >>> TR5(sin(x)**-2) # unchanged
369
+ sin(x)**(-2)
370
+ >>> TR5(sin(x)**4)
371
+ (1 - cos(x)**2)**2
372
+ """
373
+ return _TR56(rv, sin, cos, lambda x: 1 - x, max=max, pow=pow)
374
+
375
+
376
+ def TR6(rv, max=4, pow=False):
377
+ """Replacement of cos**2 with 1 - sin(x)**2.
378
+
379
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
380
+
381
+ Examples
382
+ ========
383
+
384
+ >>> from sympy.simplify.fu import TR6
385
+ >>> from sympy.abc import x
386
+ >>> from sympy import cos
387
+ >>> TR6(cos(x)**2)
388
+ 1 - sin(x)**2
389
+ >>> TR6(cos(x)**-2) #unchanged
390
+ cos(x)**(-2)
391
+ >>> TR6(cos(x)**4)
392
+ (1 - sin(x)**2)**2
393
+ """
394
+ return _TR56(rv, cos, sin, lambda x: 1 - x, max=max, pow=pow)
395
+
396
+
397
+ def TR7(rv):
398
+ """Lowering the degree of cos(x)**2.
399
+
400
+ Examples
401
+ ========
402
+
403
+ >>> from sympy.simplify.fu import TR7
404
+ >>> from sympy.abc import x
405
+ >>> from sympy import cos
406
+ >>> TR7(cos(x)**2)
407
+ cos(2*x)/2 + 1/2
408
+ >>> TR7(cos(x)**2 + 1)
409
+ cos(2*x)/2 + 3/2
410
+
411
+ """
412
+
413
+ def f(rv):
414
+ if not (rv.is_Pow and rv.base.func == cos and rv.exp == 2):
415
+ return rv
416
+ return (1 + cos(2*rv.base.args[0]))/2
417
+
418
+ return bottom_up(rv, f)
419
+
420
+
421
+ def TR8(rv, first=True):
422
+ """Converting products of ``cos`` and/or ``sin`` to a sum or
423
+ difference of ``cos`` and or ``sin`` terms.
424
+
425
+ Examples
426
+ ========
427
+
428
+ >>> from sympy.simplify.fu import TR8
429
+ >>> from sympy import cos, sin
430
+ >>> TR8(cos(2)*cos(3))
431
+ cos(5)/2 + cos(1)/2
432
+ >>> TR8(cos(2)*sin(3))
433
+ sin(5)/2 + sin(1)/2
434
+ >>> TR8(sin(2)*sin(3))
435
+ -cos(5)/2 + cos(1)/2
436
+ """
437
+
438
+ def f(rv):
439
+ if not (
440
+ rv.is_Mul or
441
+ rv.is_Pow and
442
+ rv.base.func in (cos, sin) and
443
+ (rv.exp.is_integer or rv.base.is_positive)):
444
+ return rv
445
+
446
+ if first:
447
+ n, d = [expand_mul(i) for i in rv.as_numer_denom()]
448
+ newn = TR8(n, first=False)
449
+ newd = TR8(d, first=False)
450
+ if newn != n or newd != d:
451
+ rv = gcd_terms(newn/newd)
452
+ if rv.is_Mul and rv.args[0].is_Rational and \
453
+ len(rv.args) == 2 and rv.args[1].is_Add:
454
+ rv = Mul(*rv.as_coeff_Mul())
455
+ return rv
456
+
457
+ args = {cos: [], sin: [], None: []}
458
+ for a in Mul.make_args(rv):
459
+ if a.func in (cos, sin):
460
+ args[type(a)].append(a.args[0])
461
+ elif (a.is_Pow and a.exp.is_Integer and a.exp > 0 and \
462
+ a.base.func in (cos, sin)):
463
+ # XXX this is ok but pathological expression could be handled
464
+ # more efficiently as in TRmorrie
465
+ args[type(a.base)].extend([a.base.args[0]]*a.exp)
466
+ else:
467
+ args[None].append(a)
468
+ c = args[cos]
469
+ s = args[sin]
470
+ if not (c and s or len(c) > 1 or len(s) > 1):
471
+ return rv
472
+
473
+ args = args[None]
474
+ n = min(len(c), len(s))
475
+ for i in range(n):
476
+ a1 = s.pop()
477
+ a2 = c.pop()
478
+ args.append((sin(a1 + a2) + sin(a1 - a2))/2)
479
+ while len(c) > 1:
480
+ a1 = c.pop()
481
+ a2 = c.pop()
482
+ args.append((cos(a1 + a2) + cos(a1 - a2))/2)
483
+ if c:
484
+ args.append(cos(c.pop()))
485
+ while len(s) > 1:
486
+ a1 = s.pop()
487
+ a2 = s.pop()
488
+ args.append((-cos(a1 + a2) + cos(a1 - a2))/2)
489
+ if s:
490
+ args.append(sin(s.pop()))
491
+ return TR8(expand_mul(Mul(*args)))
492
+
493
+ return bottom_up(rv, f)
494
+
495
+
496
+ def TR9(rv):
497
+ """Sum of ``cos`` or ``sin`` terms as a product of ``cos`` or ``sin``.
498
+
499
+ Examples
500
+ ========
501
+
502
+ >>> from sympy.simplify.fu import TR9
503
+ >>> from sympy import cos, sin
504
+ >>> TR9(cos(1) + cos(2))
505
+ 2*cos(1/2)*cos(3/2)
506
+ >>> TR9(cos(1) + 2*sin(1) + 2*sin(2))
507
+ cos(1) + 4*sin(3/2)*cos(1/2)
508
+
509
+ If no change is made by TR9, no re-arrangement of the
510
+ expression will be made. For example, though factoring
511
+ of common term is attempted, if the factored expression
512
+ was not changed, the original expression will be returned:
513
+
514
+ >>> TR9(cos(3) + cos(3)*cos(2))
515
+ cos(3) + cos(2)*cos(3)
516
+
517
+ """
518
+
519
+ def f(rv):
520
+ if not rv.is_Add:
521
+ return rv
522
+
523
+ def do(rv, first=True):
524
+ # cos(a)+/-cos(b) can be combined into a product of cosines and
525
+ # sin(a)+/-sin(b) can be combined into a product of cosine and
526
+ # sine.
527
+ #
528
+ # If there are more than two args, the pairs which "work" will
529
+ # have a gcd extractable and the remaining two terms will have
530
+ # the above structure -- all pairs must be checked to find the
531
+ # ones that work. args that don't have a common set of symbols
532
+ # are skipped since this doesn't lead to a simpler formula and
533
+ # also has the arbitrariness of combining, for example, the x
534
+ # and y term instead of the y and z term in something like
535
+ # cos(x) + cos(y) + cos(z).
536
+
537
+ if not rv.is_Add:
538
+ return rv
539
+
540
+ args = list(ordered(rv.args))
541
+ if len(args) != 2:
542
+ hit = False
543
+ for i in range(len(args)):
544
+ ai = args[i]
545
+ if ai is None:
546
+ continue
547
+ for j in range(i + 1, len(args)):
548
+ aj = args[j]
549
+ if aj is None:
550
+ continue
551
+ was = ai + aj
552
+ new = do(was)
553
+ if new != was:
554
+ args[i] = new # update in place
555
+ args[j] = None
556
+ hit = True
557
+ break # go to next i
558
+ if hit:
559
+ rv = Add(*[_f for _f in args if _f])
560
+ if rv.is_Add:
561
+ rv = do(rv)
562
+
563
+ return rv
564
+
565
+ # two-arg Add
566
+ split = trig_split(*args)
567
+ if not split:
568
+ return rv
569
+ gcd, n1, n2, a, b, iscos = split
570
+
571
+ # application of rule if possible
572
+ if iscos:
573
+ if n1 == n2:
574
+ return gcd*n1*2*cos((a + b)/2)*cos((a - b)/2)
575
+ if n1 < 0:
576
+ a, b = b, a
577
+ return -2*gcd*sin((a + b)/2)*sin((a - b)/2)
578
+ else:
579
+ if n1 == n2:
580
+ return gcd*n1*2*sin((a + b)/2)*cos((a - b)/2)
581
+ if n1 < 0:
582
+ a, b = b, a
583
+ return 2*gcd*cos((a + b)/2)*sin((a - b)/2)
584
+
585
+ return process_common_addends(rv, do) # DON'T sift by free symbols
586
+
587
+ return bottom_up(rv, f)
588
+
589
+
590
+ def TR10(rv, first=True):
591
+ """Separate sums in ``cos`` and ``sin``.
592
+
593
+ Examples
594
+ ========
595
+
596
+ >>> from sympy.simplify.fu import TR10
597
+ >>> from sympy.abc import a, b, c
598
+ >>> from sympy import cos, sin
599
+ >>> TR10(cos(a + b))
600
+ -sin(a)*sin(b) + cos(a)*cos(b)
601
+ >>> TR10(sin(a + b))
602
+ sin(a)*cos(b) + sin(b)*cos(a)
603
+ >>> TR10(sin(a + b + c))
604
+ (-sin(a)*sin(b) + cos(a)*cos(b))*sin(c) + \
605
+ (sin(a)*cos(b) + sin(b)*cos(a))*cos(c)
606
+ """
607
+
608
+ def f(rv):
609
+ if rv.func not in (cos, sin):
610
+ return rv
611
+
612
+ f = rv.func
613
+ arg = rv.args[0]
614
+ if arg.is_Add:
615
+ if first:
616
+ args = list(ordered(arg.args))
617
+ else:
618
+ args = list(arg.args)
619
+ a = args.pop()
620
+ b = Add._from_args(args)
621
+ if b.is_Add:
622
+ if f == sin:
623
+ return sin(a)*TR10(cos(b), first=False) + \
624
+ cos(a)*TR10(sin(b), first=False)
625
+ else:
626
+ return cos(a)*TR10(cos(b), first=False) - \
627
+ sin(a)*TR10(sin(b), first=False)
628
+ else:
629
+ if f == sin:
630
+ return sin(a)*cos(b) + cos(a)*sin(b)
631
+ else:
632
+ return cos(a)*cos(b) - sin(a)*sin(b)
633
+ return rv
634
+
635
+ return bottom_up(rv, f)
636
+
637
+
638
+ def TR10i(rv):
639
+ """Sum of products to function of sum.
640
+
641
+ Examples
642
+ ========
643
+
644
+ >>> from sympy.simplify.fu import TR10i
645
+ >>> from sympy import cos, sin, sqrt
646
+ >>> from sympy.abc import x
647
+
648
+ >>> TR10i(cos(1)*cos(3) + sin(1)*sin(3))
649
+ cos(2)
650
+ >>> TR10i(cos(1)*sin(3) + sin(1)*cos(3) + cos(3))
651
+ cos(3) + sin(4)
652
+ >>> TR10i(sqrt(2)*cos(x)*x + sqrt(6)*sin(x)*x)
653
+ 2*sqrt(2)*x*sin(x + pi/6)
654
+
655
+ """
656
+ global _ROOT2, _ROOT3, _invROOT3
657
+ if _ROOT2 is None:
658
+ _roots()
659
+
660
+ def f(rv):
661
+ if not rv.is_Add:
662
+ return rv
663
+
664
+ def do(rv, first=True):
665
+ # args which can be expressed as A*(cos(a)*cos(b)+/-sin(a)*sin(b))
666
+ # or B*(cos(a)*sin(b)+/-cos(b)*sin(a)) can be combined into
667
+ # A*f(a+/-b) where f is either sin or cos.
668
+ #
669
+ # If there are more than two args, the pairs which "work" will have
670
+ # a gcd extractable and the remaining two terms will have the above
671
+ # structure -- all pairs must be checked to find the ones that
672
+ # work.
673
+
674
+ if not rv.is_Add:
675
+ return rv
676
+
677
+ args = list(ordered(rv.args))
678
+ if len(args) != 2:
679
+ hit = False
680
+ for i in range(len(args)):
681
+ ai = args[i]
682
+ if ai is None:
683
+ continue
684
+ for j in range(i + 1, len(args)):
685
+ aj = args[j]
686
+ if aj is None:
687
+ continue
688
+ was = ai + aj
689
+ new = do(was)
690
+ if new != was:
691
+ args[i] = new # update in place
692
+ args[j] = None
693
+ hit = True
694
+ break # go to next i
695
+ if hit:
696
+ rv = Add(*[_f for _f in args if _f])
697
+ if rv.is_Add:
698
+ rv = do(rv)
699
+
700
+ return rv
701
+
702
+ # two-arg Add
703
+ split = trig_split(*args, two=True)
704
+ if not split:
705
+ return rv
706
+ gcd, n1, n2, a, b, same = split
707
+
708
+ # identify and get c1 to be cos then apply rule if possible
709
+ if same: # coscos, sinsin
710
+ gcd = n1*gcd
711
+ if n1 == n2:
712
+ return gcd*cos(a - b)
713
+ return gcd*cos(a + b)
714
+ else: #cossin, cossin
715
+ gcd = n1*gcd
716
+ if n1 == n2:
717
+ return gcd*sin(a + b)
718
+ return gcd*sin(b - a)
719
+
720
+ rv = process_common_addends(
721
+ rv, do, lambda x: tuple(ordered(x.free_symbols)))
722
+
723
+ # need to check for inducible pairs in ratio of sqrt(3):1 that
724
+ # appeared in different lists when sorting by coefficient
725
+ while rv.is_Add:
726
+ byrad = defaultdict(list)
727
+ for a in rv.args:
728
+ hit = 0
729
+ if a.is_Mul:
730
+ for ai in a.args:
731
+ if ai.is_Pow and ai.exp is S.Half and \
732
+ ai.base.is_Integer:
733
+ byrad[ai].append(a)
734
+ hit = 1
735
+ break
736
+ if not hit:
737
+ byrad[S.One].append(a)
738
+
739
+ # no need to check all pairs -- just check for the onees
740
+ # that have the right ratio
741
+ args = []
742
+ for a in byrad:
743
+ for b in [_ROOT3*a, _invROOT3]:
744
+ if b in byrad:
745
+ for i in range(len(byrad[a])):
746
+ if byrad[a][i] is None:
747
+ continue
748
+ for j in range(len(byrad[b])):
749
+ if byrad[b][j] is None:
750
+ continue
751
+ was = Add(byrad[a][i] + byrad[b][j])
752
+ new = do(was)
753
+ if new != was:
754
+ args.append(new)
755
+ byrad[a][i] = None
756
+ byrad[b][j] = None
757
+ break
758
+ if args:
759
+ rv = Add(*(args + [Add(*[_f for _f in v if _f])
760
+ for v in byrad.values()]))
761
+ else:
762
+ rv = do(rv) # final pass to resolve any new inducible pairs
763
+ break
764
+
765
+ return rv
766
+
767
+ return bottom_up(rv, f)
768
+
769
+
770
+ def TR11(rv, base=None):
771
+ """Function of double angle to product. The ``base`` argument can be used
772
+ to indicate what is the un-doubled argument, e.g. if 3*pi/7 is the base
773
+ then cosine and sine functions with argument 6*pi/7 will be replaced.
774
+
775
+ Examples
776
+ ========
777
+
778
+ >>> from sympy.simplify.fu import TR11
779
+ >>> from sympy import cos, sin, pi
780
+ >>> from sympy.abc import x
781
+ >>> TR11(sin(2*x))
782
+ 2*sin(x)*cos(x)
783
+ >>> TR11(cos(2*x))
784
+ -sin(x)**2 + cos(x)**2
785
+ >>> TR11(sin(4*x))
786
+ 4*(-sin(x)**2 + cos(x)**2)*sin(x)*cos(x)
787
+ >>> TR11(sin(4*x/3))
788
+ 4*(-sin(x/3)**2 + cos(x/3)**2)*sin(x/3)*cos(x/3)
789
+
790
+ If the arguments are simply integers, no change is made
791
+ unless a base is provided:
792
+
793
+ >>> TR11(cos(2))
794
+ cos(2)
795
+ >>> TR11(cos(4), 2)
796
+ -sin(2)**2 + cos(2)**2
797
+
798
+ There is a subtle issue here in that autosimplification will convert
799
+ some higher angles to lower angles
800
+
801
+ >>> cos(6*pi/7) + cos(3*pi/7)
802
+ -cos(pi/7) + cos(3*pi/7)
803
+
804
+ The 6*pi/7 angle is now pi/7 but can be targeted with TR11 by supplying
805
+ the 3*pi/7 base:
806
+
807
+ >>> TR11(_, 3*pi/7)
808
+ -sin(3*pi/7)**2 + cos(3*pi/7)**2 + cos(3*pi/7)
809
+
810
+ """
811
+
812
+ def f(rv):
813
+ if rv.func not in (cos, sin):
814
+ return rv
815
+
816
+ if base:
817
+ f = rv.func
818
+ t = f(base*2)
819
+ co = S.One
820
+ if t.is_Mul:
821
+ co, t = t.as_coeff_Mul()
822
+ if t.func not in (cos, sin):
823
+ return rv
824
+ if rv.args[0] == t.args[0]:
825
+ c = cos(base)
826
+ s = sin(base)
827
+ if f is cos:
828
+ return (c**2 - s**2)/co
829
+ else:
830
+ return 2*c*s/co
831
+ return rv
832
+
833
+ elif not rv.args[0].is_Number:
834
+ # make a change if the leading coefficient's numerator is
835
+ # divisible by 2
836
+ c, m = rv.args[0].as_coeff_Mul(rational=True)
837
+ if c.p % 2 == 0:
838
+ arg = c.p//2*m/c.q
839
+ c = TR11(cos(arg))
840
+ s = TR11(sin(arg))
841
+ if rv.func == sin:
842
+ rv = 2*s*c
843
+ else:
844
+ rv = c**2 - s**2
845
+ return rv
846
+
847
+ return bottom_up(rv, f)
848
+
849
+
850
+ def _TR11(rv):
851
+ """
852
+ Helper for TR11 to find half-arguments for sin in factors of
853
+ num/den that appear in cos or sin factors in the den/num.
854
+
855
+ Examples
856
+ ========
857
+
858
+ >>> from sympy.simplify.fu import TR11, _TR11
859
+ >>> from sympy import cos, sin
860
+ >>> from sympy.abc import x
861
+ >>> TR11(sin(x/3)/(cos(x/6)))
862
+ sin(x/3)/cos(x/6)
863
+ >>> _TR11(sin(x/3)/(cos(x/6)))
864
+ 2*sin(x/6)
865
+ >>> TR11(sin(x/6)/(sin(x/3)))
866
+ sin(x/6)/sin(x/3)
867
+ >>> _TR11(sin(x/6)/(sin(x/3)))
868
+ 1/(2*cos(x/6))
869
+
870
+ """
871
+ def f(rv):
872
+ if not isinstance(rv, Expr):
873
+ return rv
874
+
875
+ def sincos_args(flat):
876
+ # find arguments of sin and cos that
877
+ # appears as bases in args of flat
878
+ # and have Integer exponents
879
+ args = defaultdict(set)
880
+ for fi in Mul.make_args(flat):
881
+ b, e = fi.as_base_exp()
882
+ if e.is_Integer and e > 0:
883
+ if b.func in (cos, sin):
884
+ args[type(b)].add(b.args[0])
885
+ return args
886
+ num_args, den_args = map(sincos_args, rv.as_numer_denom())
887
+ def handle_match(rv, num_args, den_args):
888
+ # for arg in sin args of num_args, look for arg/2
889
+ # in den_args and pass this half-angle to TR11
890
+ # for handling in rv
891
+ for narg in num_args[sin]:
892
+ half = narg/2
893
+ if half in den_args[cos]:
894
+ func = cos
895
+ elif half in den_args[sin]:
896
+ func = sin
897
+ else:
898
+ continue
899
+ rv = TR11(rv, half)
900
+ den_args[func].remove(half)
901
+ return rv
902
+ # sin in num, sin or cos in den
903
+ rv = handle_match(rv, num_args, den_args)
904
+ # sin in den, sin or cos in num
905
+ rv = handle_match(rv, den_args, num_args)
906
+ return rv
907
+
908
+ return bottom_up(rv, f)
909
+
910
+
911
+ def TR12(rv, first=True):
912
+ """Separate sums in ``tan``.
913
+
914
+ Examples
915
+ ========
916
+
917
+ >>> from sympy.abc import x, y
918
+ >>> from sympy import tan
919
+ >>> from sympy.simplify.fu import TR12
920
+ >>> TR12(tan(x + y))
921
+ (tan(x) + tan(y))/(-tan(x)*tan(y) + 1)
922
+ """
923
+
924
+ def f(rv):
925
+ if not rv.func == tan:
926
+ return rv
927
+
928
+ arg = rv.args[0]
929
+ if arg.is_Add:
930
+ if first:
931
+ args = list(ordered(arg.args))
932
+ else:
933
+ args = list(arg.args)
934
+ a = args.pop()
935
+ b = Add._from_args(args)
936
+ if b.is_Add:
937
+ tb = TR12(tan(b), first=False)
938
+ else:
939
+ tb = tan(b)
940
+ return (tan(a) + tb)/(1 - tan(a)*tb)
941
+ return rv
942
+
943
+ return bottom_up(rv, f)
944
+
945
+
946
+ def TR12i(rv):
947
+ """Combine tan arguments as
948
+ (tan(y) + tan(x))/(tan(x)*tan(y) - 1) -> -tan(x + y).
949
+
950
+ Examples
951
+ ========
952
+
953
+ >>> from sympy.simplify.fu import TR12i
954
+ >>> from sympy import tan
955
+ >>> from sympy.abc import a, b, c
956
+ >>> ta, tb, tc = [tan(i) for i in (a, b, c)]
957
+ >>> TR12i((ta + tb)/(-ta*tb + 1))
958
+ tan(a + b)
959
+ >>> TR12i((ta + tb)/(ta*tb - 1))
960
+ -tan(a + b)
961
+ >>> TR12i((-ta - tb)/(ta*tb - 1))
962
+ tan(a + b)
963
+ >>> eq = (ta + tb)/(-ta*tb + 1)**2*(-3*ta - 3*tc)/(2*(ta*tc - 1))
964
+ >>> TR12i(eq.expand())
965
+ -3*tan(a + b)*tan(a + c)/(2*(tan(a) + tan(b) - 1))
966
+ """
967
+ def f(rv):
968
+ if not (rv.is_Add or rv.is_Mul or rv.is_Pow):
969
+ return rv
970
+
971
+ n, d = rv.as_numer_denom()
972
+ if not d.args or not n.args:
973
+ return rv
974
+
975
+ dok = {}
976
+
977
+ def ok(di):
978
+ m = as_f_sign_1(di)
979
+ if m:
980
+ g, f, s = m
981
+ if s is S.NegativeOne and f.is_Mul and len(f.args) == 2 and \
982
+ all(isinstance(fi, tan) for fi in f.args):
983
+ return g, f
984
+
985
+ d_args = list(Mul.make_args(d))
986
+ for i, di in enumerate(d_args):
987
+ m = ok(di)
988
+ if m:
989
+ g, t = m
990
+ s = Add(*[_.args[0] for _ in t.args])
991
+ dok[s] = S.One
992
+ d_args[i] = g
993
+ continue
994
+ if di.is_Add:
995
+ di = factor(di)
996
+ if di.is_Mul:
997
+ d_args.extend(di.args)
998
+ d_args[i] = S.One
999
+ elif di.is_Pow and (di.exp.is_integer or di.base.is_positive):
1000
+ m = ok(di.base)
1001
+ if m:
1002
+ g, t = m
1003
+ s = Add(*[_.args[0] for _ in t.args])
1004
+ dok[s] = di.exp
1005
+ d_args[i] = g**di.exp
1006
+ else:
1007
+ di = factor(di)
1008
+ if di.is_Mul:
1009
+ d_args.extend(di.args)
1010
+ d_args[i] = S.One
1011
+ if not dok:
1012
+ return rv
1013
+
1014
+ def ok(ni):
1015
+ if ni.is_Add and len(ni.args) == 2:
1016
+ a, b = ni.args
1017
+ if isinstance(a, tan) and isinstance(b, tan):
1018
+ return a, b
1019
+ n_args = list(Mul.make_args(factor_terms(n)))
1020
+ hit = False
1021
+ for i, ni in enumerate(n_args):
1022
+ m = ok(ni)
1023
+ if not m:
1024
+ m = ok(-ni)
1025
+ if m:
1026
+ n_args[i] = S.NegativeOne
1027
+ else:
1028
+ if ni.is_Add:
1029
+ ni = factor(ni)
1030
+ if ni.is_Mul:
1031
+ n_args.extend(ni.args)
1032
+ n_args[i] = S.One
1033
+ continue
1034
+ elif ni.is_Pow and (
1035
+ ni.exp.is_integer or ni.base.is_positive):
1036
+ m = ok(ni.base)
1037
+ if m:
1038
+ n_args[i] = S.One
1039
+ else:
1040
+ ni = factor(ni)
1041
+ if ni.is_Mul:
1042
+ n_args.extend(ni.args)
1043
+ n_args[i] = S.One
1044
+ continue
1045
+ else:
1046
+ continue
1047
+ else:
1048
+ n_args[i] = S.One
1049
+ hit = True
1050
+ s = Add(*[_.args[0] for _ in m])
1051
+ ed = dok[s]
1052
+ newed = ed.extract_additively(S.One)
1053
+ if newed is not None:
1054
+ if newed:
1055
+ dok[s] = newed
1056
+ else:
1057
+ dok.pop(s)
1058
+ n_args[i] *= -tan(s)
1059
+
1060
+ if hit:
1061
+ rv = Mul(*n_args)/Mul(*d_args)/Mul(*[(Add(*[
1062
+ tan(a) for a in i.args]) - 1)**e for i, e in dok.items()])
1063
+
1064
+ return rv
1065
+
1066
+ return bottom_up(rv, f)
1067
+
1068
+
1069
+ def TR13(rv):
1070
+ """Change products of ``tan`` or ``cot``.
1071
+
1072
+ Examples
1073
+ ========
1074
+
1075
+ >>> from sympy.simplify.fu import TR13
1076
+ >>> from sympy import tan, cot
1077
+ >>> TR13(tan(3)*tan(2))
1078
+ -tan(2)/tan(5) - tan(3)/tan(5) + 1
1079
+ >>> TR13(cot(3)*cot(2))
1080
+ cot(2)*cot(5) + 1 + cot(3)*cot(5)
1081
+ """
1082
+
1083
+ def f(rv):
1084
+ if not rv.is_Mul:
1085
+ return rv
1086
+
1087
+ # XXX handle products of powers? or let power-reducing handle it?
1088
+ args = {tan: [], cot: [], None: []}
1089
+ for a in Mul.make_args(rv):
1090
+ if a.func in (tan, cot):
1091
+ args[type(a)].append(a.args[0])
1092
+ else:
1093
+ args[None].append(a)
1094
+ t = args[tan]
1095
+ c = args[cot]
1096
+ if len(t) < 2 and len(c) < 2:
1097
+ return rv
1098
+ args = args[None]
1099
+ while len(t) > 1:
1100
+ t1 = t.pop()
1101
+ t2 = t.pop()
1102
+ args.append(1 - (tan(t1)/tan(t1 + t2) + tan(t2)/tan(t1 + t2)))
1103
+ if t:
1104
+ args.append(tan(t.pop()))
1105
+ while len(c) > 1:
1106
+ t1 = c.pop()
1107
+ t2 = c.pop()
1108
+ args.append(1 + cot(t1)*cot(t1 + t2) + cot(t2)*cot(t1 + t2))
1109
+ if c:
1110
+ args.append(cot(c.pop()))
1111
+ return Mul(*args)
1112
+
1113
+ return bottom_up(rv, f)
1114
+
1115
+
1116
+ def TRmorrie(rv):
1117
+ """Returns cos(x)*cos(2*x)*...*cos(2**(k-1)*x) -> sin(2**k*x)/(2**k*sin(x))
1118
+
1119
+ Examples
1120
+ ========
1121
+
1122
+ >>> from sympy.simplify.fu import TRmorrie, TR8, TR3
1123
+ >>> from sympy.abc import x
1124
+ >>> from sympy import Mul, cos, pi
1125
+ >>> TRmorrie(cos(x)*cos(2*x))
1126
+ sin(4*x)/(4*sin(x))
1127
+ >>> TRmorrie(7*Mul(*[cos(x) for x in range(10)]))
1128
+ 7*sin(12)*sin(16)*cos(5)*cos(7)*cos(9)/(64*sin(1)*sin(3))
1129
+
1130
+ Sometimes autosimplification will cause a power to be
1131
+ not recognized. e.g. in the following, cos(4*pi/7) automatically
1132
+ simplifies to -cos(3*pi/7) so only 2 of the 3 terms are
1133
+ recognized:
1134
+
1135
+ >>> TRmorrie(cos(pi/7)*cos(2*pi/7)*cos(4*pi/7))
1136
+ -sin(3*pi/7)*cos(3*pi/7)/(4*sin(pi/7))
1137
+
1138
+ A touch by TR8 resolves the expression to a Rational
1139
+
1140
+ >>> TR8(_)
1141
+ -1/8
1142
+
1143
+ In this case, if eq is unsimplified, the answer is obtained
1144
+ directly:
1145
+
1146
+ >>> eq = cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9)
1147
+ >>> TRmorrie(eq)
1148
+ 1/16
1149
+
1150
+ But if angles are made canonical with TR3 then the answer
1151
+ is not simplified without further work:
1152
+
1153
+ >>> TR3(eq)
1154
+ sin(pi/18)*cos(pi/9)*cos(2*pi/9)/2
1155
+ >>> TRmorrie(_)
1156
+ sin(pi/18)*sin(4*pi/9)/(8*sin(pi/9))
1157
+ >>> TR8(_)
1158
+ cos(7*pi/18)/(16*sin(pi/9))
1159
+ >>> TR3(_)
1160
+ 1/16
1161
+
1162
+ The original expression would have resolve to 1/16 directly with TR8,
1163
+ however:
1164
+
1165
+ >>> TR8(eq)
1166
+ 1/16
1167
+
1168
+ References
1169
+ ==========
1170
+
1171
+ .. [1] https://en.wikipedia.org/wiki/Morrie%27s_law
1172
+
1173
+ """
1174
+
1175
+ def f(rv, first=True):
1176
+ if not rv.is_Mul:
1177
+ return rv
1178
+ if first:
1179
+ n, d = rv.as_numer_denom()
1180
+ return f(n, 0)/f(d, 0)
1181
+
1182
+ args = defaultdict(list)
1183
+ coss = {}
1184
+ other = []
1185
+ for c in rv.args:
1186
+ b, e = c.as_base_exp()
1187
+ if e.is_Integer and isinstance(b, cos):
1188
+ co, a = b.args[0].as_coeff_Mul()
1189
+ args[a].append(co)
1190
+ coss[b] = e
1191
+ else:
1192
+ other.append(c)
1193
+
1194
+ new = []
1195
+ for a in args:
1196
+ c = args[a]
1197
+ c.sort()
1198
+ while c:
1199
+ k = 0
1200
+ cc = ci = c[0]
1201
+ while cc in c:
1202
+ k += 1
1203
+ cc *= 2
1204
+ if k > 1:
1205
+ newarg = sin(2**k*ci*a)/2**k/sin(ci*a)
1206
+ # see how many times this can be taken
1207
+ take = None
1208
+ ccs = []
1209
+ for i in range(k):
1210
+ cc /= 2
1211
+ key = cos(a*cc, evaluate=False)
1212
+ ccs.append(cc)
1213
+ take = min(coss[key], take or coss[key])
1214
+ # update exponent counts
1215
+ for i in range(k):
1216
+ cc = ccs.pop()
1217
+ key = cos(a*cc, evaluate=False)
1218
+ coss[key] -= take
1219
+ if not coss[key]:
1220
+ c.remove(cc)
1221
+ new.append(newarg**take)
1222
+ else:
1223
+ b = cos(c.pop(0)*a)
1224
+ other.append(b**coss[b])
1225
+
1226
+ if new:
1227
+ rv = Mul(*(new + other + [
1228
+ cos(k*a, evaluate=False) for a in args for k in args[a]]))
1229
+
1230
+ return rv
1231
+
1232
+ return bottom_up(rv, f)
1233
+
1234
+
1235
+ def TR14(rv, first=True):
1236
+ """Convert factored powers of sin and cos identities into simpler
1237
+ expressions.
1238
+
1239
+ Examples
1240
+ ========
1241
+
1242
+ >>> from sympy.simplify.fu import TR14
1243
+ >>> from sympy.abc import x, y
1244
+ >>> from sympy import cos, sin
1245
+ >>> TR14((cos(x) - 1)*(cos(x) + 1))
1246
+ -sin(x)**2
1247
+ >>> TR14((sin(x) - 1)*(sin(x) + 1))
1248
+ -cos(x)**2
1249
+ >>> p1 = (cos(x) + 1)*(cos(x) - 1)
1250
+ >>> p2 = (cos(y) - 1)*2*(cos(y) + 1)
1251
+ >>> p3 = (3*(cos(y) - 1))*(3*(cos(y) + 1))
1252
+ >>> TR14(p1*p2*p3*(x - 1))
1253
+ -18*(x - 1)*sin(x)**2*sin(y)**4
1254
+
1255
+ """
1256
+
1257
+ def f(rv):
1258
+ if not rv.is_Mul:
1259
+ return rv
1260
+
1261
+ if first:
1262
+ # sort them by location in numerator and denominator
1263
+ # so the code below can just deal with positive exponents
1264
+ n, d = rv.as_numer_denom()
1265
+ if d is not S.One:
1266
+ newn = TR14(n, first=False)
1267
+ newd = TR14(d, first=False)
1268
+ if newn != n or newd != d:
1269
+ rv = newn/newd
1270
+ return rv
1271
+
1272
+ other = []
1273
+ process = []
1274
+ for a in rv.args:
1275
+ if a.is_Pow:
1276
+ b, e = a.as_base_exp()
1277
+ if not (e.is_integer or b.is_positive):
1278
+ other.append(a)
1279
+ continue
1280
+ a = b
1281
+ else:
1282
+ e = S.One
1283
+ m = as_f_sign_1(a)
1284
+ if not m or m[1].func not in (cos, sin):
1285
+ if e is S.One:
1286
+ other.append(a)
1287
+ else:
1288
+ other.append(a**e)
1289
+ continue
1290
+ g, f, si = m
1291
+ process.append((g, e.is_Number, e, f, si, a))
1292
+
1293
+ # sort them to get like terms next to each other
1294
+ process = list(ordered(process))
1295
+
1296
+ # keep track of whether there was any change
1297
+ nother = len(other)
1298
+
1299
+ # access keys
1300
+ keys = (g, t, e, f, si, a) = list(range(6))
1301
+
1302
+ while process:
1303
+ A = process.pop(0)
1304
+ if process:
1305
+ B = process[0]
1306
+
1307
+ if A[e].is_Number and B[e].is_Number:
1308
+ # both exponents are numbers
1309
+ if A[f] == B[f]:
1310
+ if A[si] != B[si]:
1311
+ B = process.pop(0)
1312
+ take = min(A[e], B[e])
1313
+
1314
+ # reinsert any remainder
1315
+ # the B will likely sort after A so check it first
1316
+ if B[e] != take:
1317
+ rem = [B[i] for i in keys]
1318
+ rem[e] -= take
1319
+ process.insert(0, rem)
1320
+ elif A[e] != take:
1321
+ rem = [A[i] for i in keys]
1322
+ rem[e] -= take
1323
+ process.insert(0, rem)
1324
+
1325
+ if isinstance(A[f], cos):
1326
+ t = sin
1327
+ else:
1328
+ t = cos
1329
+ other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take)
1330
+ continue
1331
+
1332
+ elif A[e] == B[e]:
1333
+ # both exponents are equal symbols
1334
+ if A[f] == B[f]:
1335
+ if A[si] != B[si]:
1336
+ B = process.pop(0)
1337
+ take = A[e]
1338
+ if isinstance(A[f], cos):
1339
+ t = sin
1340
+ else:
1341
+ t = cos
1342
+ other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take)
1343
+ continue
1344
+
1345
+ # either we are done or neither condition above applied
1346
+ other.append(A[a]**A[e])
1347
+
1348
+ if len(other) != nother:
1349
+ rv = Mul(*other)
1350
+
1351
+ return rv
1352
+
1353
+ return bottom_up(rv, f)
1354
+
1355
+
1356
+ def TR15(rv, max=4, pow=False):
1357
+ """Convert sin(x)**-2 to 1 + cot(x)**2.
1358
+
1359
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
1360
+
1361
+ Examples
1362
+ ========
1363
+
1364
+ >>> from sympy.simplify.fu import TR15
1365
+ >>> from sympy.abc import x
1366
+ >>> from sympy import sin
1367
+ >>> TR15(1 - 1/sin(x)**2)
1368
+ -cot(x)**2
1369
+
1370
+ """
1371
+
1372
+ def f(rv):
1373
+ if not (isinstance(rv, Pow) and isinstance(rv.base, sin)):
1374
+ return rv
1375
+
1376
+ e = rv.exp
1377
+ if e % 2 == 1:
1378
+ return TR15(rv.base**(e + 1))/rv.base
1379
+
1380
+ ia = 1/rv
1381
+ a = _TR56(ia, sin, cot, lambda x: 1 + x, max=max, pow=pow)
1382
+ if a != ia:
1383
+ rv = a
1384
+ return rv
1385
+
1386
+ return bottom_up(rv, f)
1387
+
1388
+
1389
+ def TR16(rv, max=4, pow=False):
1390
+ """Convert cos(x)**-2 to 1 + tan(x)**2.
1391
+
1392
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
1393
+
1394
+ Examples
1395
+ ========
1396
+
1397
+ >>> from sympy.simplify.fu import TR16
1398
+ >>> from sympy.abc import x
1399
+ >>> from sympy import cos
1400
+ >>> TR16(1 - 1/cos(x)**2)
1401
+ -tan(x)**2
1402
+
1403
+ """
1404
+
1405
+ def f(rv):
1406
+ if not (isinstance(rv, Pow) and isinstance(rv.base, cos)):
1407
+ return rv
1408
+
1409
+ e = rv.exp
1410
+ if e % 2 == 1:
1411
+ return TR15(rv.base**(e + 1))/rv.base
1412
+
1413
+ ia = 1/rv
1414
+ a = _TR56(ia, cos, tan, lambda x: 1 + x, max=max, pow=pow)
1415
+ if a != ia:
1416
+ rv = a
1417
+ return rv
1418
+
1419
+ return bottom_up(rv, f)
1420
+
1421
+
1422
+ def TR111(rv):
1423
+ """Convert f(x)**-i to g(x)**i where either ``i`` is an integer
1424
+ or the base is positive and f, g are: tan, cot; sin, csc; or cos, sec.
1425
+
1426
+ Examples
1427
+ ========
1428
+
1429
+ >>> from sympy.simplify.fu import TR111
1430
+ >>> from sympy.abc import x
1431
+ >>> from sympy import tan
1432
+ >>> TR111(1 - 1/tan(x)**2)
1433
+ 1 - cot(x)**2
1434
+
1435
+ """
1436
+
1437
+ def f(rv):
1438
+ if not (
1439
+ isinstance(rv, Pow) and
1440
+ (rv.base.is_positive or rv.exp.is_integer and rv.exp.is_negative)):
1441
+ return rv
1442
+
1443
+ if isinstance(rv.base, tan):
1444
+ return cot(rv.base.args[0])**-rv.exp
1445
+ elif isinstance(rv.base, sin):
1446
+ return csc(rv.base.args[0])**-rv.exp
1447
+ elif isinstance(rv.base, cos):
1448
+ return sec(rv.base.args[0])**-rv.exp
1449
+ return rv
1450
+
1451
+ return bottom_up(rv, f)
1452
+
1453
+
1454
+ def TR22(rv, max=4, pow=False):
1455
+ """Convert tan(x)**2 to sec(x)**2 - 1 and cot(x)**2 to csc(x)**2 - 1.
1456
+
1457
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
1458
+
1459
+ Examples
1460
+ ========
1461
+
1462
+ >>> from sympy.simplify.fu import TR22
1463
+ >>> from sympy.abc import x
1464
+ >>> from sympy import tan, cot
1465
+ >>> TR22(1 + tan(x)**2)
1466
+ sec(x)**2
1467
+ >>> TR22(1 + cot(x)**2)
1468
+ csc(x)**2
1469
+
1470
+ """
1471
+
1472
+ def f(rv):
1473
+ if not (isinstance(rv, Pow) and rv.base.func in (cot, tan)):
1474
+ return rv
1475
+
1476
+ rv = _TR56(rv, tan, sec, lambda x: x - 1, max=max, pow=pow)
1477
+ rv = _TR56(rv, cot, csc, lambda x: x - 1, max=max, pow=pow)
1478
+ return rv
1479
+
1480
+ return bottom_up(rv, f)
1481
+
1482
+
1483
+ def TRpower(rv):
1484
+ """Convert sin(x)**n and cos(x)**n with positive n to sums.
1485
+
1486
+ Examples
1487
+ ========
1488
+
1489
+ >>> from sympy.simplify.fu import TRpower
1490
+ >>> from sympy.abc import x
1491
+ >>> from sympy import cos, sin
1492
+ >>> TRpower(sin(x)**6)
1493
+ -15*cos(2*x)/32 + 3*cos(4*x)/16 - cos(6*x)/32 + 5/16
1494
+ >>> TRpower(sin(x)**3*cos(2*x)**4)
1495
+ (3*sin(x)/4 - sin(3*x)/4)*(cos(4*x)/2 + cos(8*x)/8 + 3/8)
1496
+
1497
+ References
1498
+ ==========
1499
+
1500
+ .. [1] https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Power-reduction_formulae
1501
+
1502
+ """
1503
+
1504
+ def f(rv):
1505
+ if not (isinstance(rv, Pow) and isinstance(rv.base, (sin, cos))):
1506
+ return rv
1507
+ b, n = rv.as_base_exp()
1508
+ x = b.args[0]
1509
+ if n.is_Integer and n.is_positive:
1510
+ if n.is_odd and isinstance(b, cos):
1511
+ rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x)
1512
+ for k in range((n + 1)/2)])
1513
+ elif n.is_odd and isinstance(b, sin):
1514
+ rv = 2**(1-n)*S.NegativeOne**((n-1)/2)*Add(*[binomial(n, k)*
1515
+ S.NegativeOne**k*sin((n - 2*k)*x) for k in range((n + 1)/2)])
1516
+ elif n.is_even and isinstance(b, cos):
1517
+ rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x)
1518
+ for k in range(n/2)])
1519
+ elif n.is_even and isinstance(b, sin):
1520
+ rv = 2**(1-n)*S.NegativeOne**(n/2)*Add(*[binomial(n, k)*
1521
+ S.NegativeOne**k*cos((n - 2*k)*x) for k in range(n/2)])
1522
+ if n.is_even:
1523
+ rv += 2**(-n)*binomial(n, n/2)
1524
+ return rv
1525
+
1526
+ return bottom_up(rv, f)
1527
+
1528
+
1529
+ def L(rv):
1530
+ """Return count of trigonometric functions in expression.
1531
+
1532
+ Examples
1533
+ ========
1534
+
1535
+ >>> from sympy.simplify.fu import L
1536
+ >>> from sympy.abc import x
1537
+ >>> from sympy import cos, sin
1538
+ >>> L(cos(x)+sin(x))
1539
+ 2
1540
+ """
1541
+ return S(rv.count(TrigonometricFunction))
1542
+
1543
+
1544
+ # ============== end of basic Fu-like tools =====================
1545
+
1546
+ if SYMPY_DEBUG:
1547
+ (TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13,
1548
+ TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22
1549
+ )= list(map(debug,
1550
+ (TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13,
1551
+ TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22)))
1552
+
1553
+
1554
+ # tuples are chains -- (f, g) -> lambda x: g(f(x))
1555
+ # lists are choices -- [f, g] -> lambda x: min(f(x), g(x), key=objective)
1556
+
1557
+ CTR1 = [(TR5, TR0), (TR6, TR0), identity]
1558
+
1559
+ CTR2 = (TR11, [(TR5, TR0), (TR6, TR0), TR0])
1560
+
1561
+ CTR3 = [(TRmorrie, TR8, TR0), (TRmorrie, TR8, TR10i, TR0), identity]
1562
+
1563
+ CTR4 = [(TR4, TR10i), identity]
1564
+
1565
+ RL1 = (TR4, TR3, TR4, TR12, TR4, TR13, TR4, TR0)
1566
+
1567
+
1568
+ # XXX it's a little unclear how this one is to be implemented
1569
+ # see Fu paper of reference, page 7. What is the Union symbol referring to?
1570
+ # The diagram shows all these as one chain of transformations, but the
1571
+ # text refers to them being applied independently. Also, a break
1572
+ # if L starts to increase has not been implemented.
1573
+ RL2 = [
1574
+ (TR4, TR3, TR10, TR4, TR3, TR11),
1575
+ (TR5, TR7, TR11, TR4),
1576
+ (CTR3, CTR1, TR9, CTR2, TR4, TR9, TR9, CTR4),
1577
+ identity,
1578
+ ]
1579
+
1580
+
1581
+ def fu(rv, measure=lambda x: (L(x), x.count_ops())):
1582
+ """Attempt to simplify expression by using transformation rules given
1583
+ in the algorithm by Fu et al.
1584
+
1585
+ :func:`fu` will try to minimize the objective function ``measure``.
1586
+ By default this first minimizes the number of trig terms and then minimizes
1587
+ the number of total operations.
1588
+
1589
+ Examples
1590
+ ========
1591
+
1592
+ >>> from sympy.simplify.fu import fu
1593
+ >>> from sympy import cos, sin, tan, pi, S, sqrt
1594
+ >>> from sympy.abc import x, y, a, b
1595
+
1596
+ >>> fu(sin(50)**2 + cos(50)**2 + sin(pi/6))
1597
+ 3/2
1598
+ >>> fu(sqrt(6)*cos(x) + sqrt(2)*sin(x))
1599
+ 2*sqrt(2)*sin(x + pi/3)
1600
+
1601
+ CTR1 example
1602
+
1603
+ >>> eq = sin(x)**4 - cos(y)**2 + sin(y)**2 + 2*cos(x)**2
1604
+ >>> fu(eq)
1605
+ cos(x)**4 - 2*cos(y)**2 + 2
1606
+
1607
+ CTR2 example
1608
+
1609
+ >>> fu(S.Half - cos(2*x)/2)
1610
+ sin(x)**2
1611
+
1612
+ CTR3 example
1613
+
1614
+ >>> fu(sin(a)*(cos(b) - sin(b)) + cos(a)*(sin(b) + cos(b)))
1615
+ sqrt(2)*sin(a + b + pi/4)
1616
+
1617
+ CTR4 example
1618
+
1619
+ >>> fu(sqrt(3)*cos(x)/2 + sin(x)/2)
1620
+ sin(x + pi/3)
1621
+
1622
+ Example 1
1623
+
1624
+ >>> fu(1-sin(2*x)**2/4-sin(y)**2-cos(x)**4)
1625
+ -cos(x)**2 + cos(y)**2
1626
+
1627
+ Example 2
1628
+
1629
+ >>> fu(cos(4*pi/9))
1630
+ sin(pi/18)
1631
+ >>> fu(cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9))
1632
+ 1/16
1633
+
1634
+ Example 3
1635
+
1636
+ >>> fu(tan(7*pi/18)+tan(5*pi/18)-sqrt(3)*tan(5*pi/18)*tan(7*pi/18))
1637
+ -sqrt(3)
1638
+
1639
+ Objective function example
1640
+
1641
+ >>> fu(sin(x)/cos(x)) # default objective function
1642
+ tan(x)
1643
+ >>> fu(sin(x)/cos(x), measure=lambda x: -x.count_ops()) # maximize op count
1644
+ sin(x)/cos(x)
1645
+
1646
+ References
1647
+ ==========
1648
+
1649
+ .. [1] https://www.sciencedirect.com/science/article/pii/S0895717706001609
1650
+ """
1651
+ fRL1 = greedy(RL1, measure)
1652
+ fRL2 = greedy(RL2, measure)
1653
+
1654
+ was = rv
1655
+ rv = sympify(rv)
1656
+ if not isinstance(rv, Expr):
1657
+ return rv.func(*[fu(a, measure=measure) for a in rv.args])
1658
+ rv = TR1(rv)
1659
+ if rv.has(tan, cot):
1660
+ rv1 = fRL1(rv)
1661
+ if (measure(rv1) < measure(rv)):
1662
+ rv = rv1
1663
+ if rv.has(tan, cot):
1664
+ rv = TR2(rv)
1665
+ if rv.has(sin, cos):
1666
+ rv1 = fRL2(rv)
1667
+ rv2 = TR8(TRmorrie(rv1))
1668
+ rv = min([was, rv, rv1, rv2], key=measure)
1669
+ return min(TR2i(rv), rv, key=measure)
1670
+
1671
+
1672
+ def process_common_addends(rv, do, key2=None, key1=True):
1673
+ """Apply ``do`` to addends of ``rv`` that (if ``key1=True``) share at least
1674
+ a common absolute value of their coefficient and the value of ``key2`` when
1675
+ applied to the argument. If ``key1`` is False ``key2`` must be supplied and
1676
+ will be the only key applied.
1677
+ """
1678
+
1679
+ # collect by absolute value of coefficient and key2
1680
+ absc = defaultdict(list)
1681
+ if key1:
1682
+ for a in rv.args:
1683
+ c, a = a.as_coeff_Mul()
1684
+ if c < 0:
1685
+ c = -c
1686
+ a = -a # put the sign on `a`
1687
+ absc[(c, key2(a) if key2 else 1)].append(a)
1688
+ elif key2:
1689
+ for a in rv.args:
1690
+ absc[(S.One, key2(a))].append(a)
1691
+ else:
1692
+ raise ValueError('must have at least one key')
1693
+
1694
+ args = []
1695
+ hit = False
1696
+ for k in absc:
1697
+ v = absc[k]
1698
+ c, _ = k
1699
+ if len(v) > 1:
1700
+ e = Add(*v, evaluate=False)
1701
+ new = do(e)
1702
+ if new != e:
1703
+ e = new
1704
+ hit = True
1705
+ args.append(c*e)
1706
+ else:
1707
+ args.append(c*v[0])
1708
+ if hit:
1709
+ rv = Add(*args)
1710
+
1711
+ return rv
1712
+
1713
+
1714
+ fufuncs = '''
1715
+ TR0 TR1 TR2 TR3 TR4 TR5 TR6 TR7 TR8 TR9 TR10 TR10i TR11
1716
+ TR12 TR13 L TR2i TRmorrie TR12i
1717
+ TR14 TR15 TR16 TR111 TR22'''.split()
1718
+ FU = dict(list(zip(fufuncs, list(map(locals().get, fufuncs)))))
1719
+
1720
+
1721
+ def _roots():
1722
+ global _ROOT2, _ROOT3, _invROOT3
1723
+ _ROOT2, _ROOT3 = sqrt(2), sqrt(3)
1724
+ _invROOT3 = 1/_ROOT3
1725
+ _ROOT2 = None
1726
+
1727
+
1728
+ def trig_split(a, b, two=False):
1729
+ """Return the gcd, s1, s2, a1, a2, bool where
1730
+
1731
+ If two is False (default) then::
1732
+ a + b = gcd*(s1*f(a1) + s2*f(a2)) where f = cos if bool else sin
1733
+ else:
1734
+ if bool, a + b was +/- cos(a1)*cos(a2) +/- sin(a1)*sin(a2) and equals
1735
+ n1*gcd*cos(a - b) if n1 == n2 else
1736
+ n1*gcd*cos(a + b)
1737
+ else a + b was +/- cos(a1)*sin(a2) +/- sin(a1)*cos(a2) and equals
1738
+ n1*gcd*sin(a + b) if n1 = n2 else
1739
+ n1*gcd*sin(b - a)
1740
+
1741
+ Examples
1742
+ ========
1743
+
1744
+ >>> from sympy.simplify.fu import trig_split
1745
+ >>> from sympy.abc import x, y, z
1746
+ >>> from sympy import cos, sin, sqrt
1747
+
1748
+ >>> trig_split(cos(x), cos(y))
1749
+ (1, 1, 1, x, y, True)
1750
+ >>> trig_split(2*cos(x), -2*cos(y))
1751
+ (2, 1, -1, x, y, True)
1752
+ >>> trig_split(cos(x)*sin(y), cos(y)*sin(y))
1753
+ (sin(y), 1, 1, x, y, True)
1754
+
1755
+ >>> trig_split(cos(x), -sqrt(3)*sin(x), two=True)
1756
+ (2, 1, -1, x, pi/6, False)
1757
+ >>> trig_split(cos(x), sin(x), two=True)
1758
+ (sqrt(2), 1, 1, x, pi/4, False)
1759
+ >>> trig_split(cos(x), -sin(x), two=True)
1760
+ (sqrt(2), 1, -1, x, pi/4, False)
1761
+ >>> trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True)
1762
+ (2*sqrt(2), 1, -1, x, pi/6, False)
1763
+ >>> trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True)
1764
+ (-2*sqrt(2), 1, 1, x, pi/3, False)
1765
+ >>> trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True)
1766
+ (sqrt(6)/3, 1, 1, x, pi/6, False)
1767
+ >>> trig_split(-sqrt(6)*cos(x)*sin(y), -sqrt(2)*sin(x)*sin(y), two=True)
1768
+ (-2*sqrt(2)*sin(y), 1, 1, x, pi/3, False)
1769
+
1770
+ >>> trig_split(cos(x), sin(x))
1771
+ >>> trig_split(cos(x), sin(z))
1772
+ >>> trig_split(2*cos(x), -sin(x))
1773
+ >>> trig_split(cos(x), -sqrt(3)*sin(x))
1774
+ >>> trig_split(cos(x)*cos(y), sin(x)*sin(z))
1775
+ >>> trig_split(cos(x)*cos(y), sin(x)*sin(y))
1776
+ >>> trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True)
1777
+ """
1778
+ global _ROOT2, _ROOT3, _invROOT3
1779
+ if _ROOT2 is None:
1780
+ _roots()
1781
+
1782
+ a, b = [Factors(i) for i in (a, b)]
1783
+ ua, ub = a.normal(b)
1784
+ gcd = a.gcd(b).as_expr()
1785
+ n1 = n2 = 1
1786
+ if S.NegativeOne in ua.factors:
1787
+ ua = ua.quo(S.NegativeOne)
1788
+ n1 = -n1
1789
+ elif S.NegativeOne in ub.factors:
1790
+ ub = ub.quo(S.NegativeOne)
1791
+ n2 = -n2
1792
+ a, b = [i.as_expr() for i in (ua, ub)]
1793
+
1794
+ def pow_cos_sin(a, two):
1795
+ """Return ``a`` as a tuple (r, c, s) such that
1796
+ ``a = (r or 1)*(c or 1)*(s or 1)``.
1797
+
1798
+ Three arguments are returned (radical, c-factor, s-factor) as
1799
+ long as the conditions set by ``two`` are met; otherwise None is
1800
+ returned. If ``two`` is True there will be one or two non-None
1801
+ values in the tuple: c and s or c and r or s and r or s or c with c
1802
+ being a cosine function (if possible) else a sine, and s being a sine
1803
+ function (if possible) else oosine. If ``two`` is False then there
1804
+ will only be a c or s term in the tuple.
1805
+
1806
+ ``two`` also require that either two cos and/or sin be present (with
1807
+ the condition that if the functions are the same the arguments are
1808
+ different or vice versa) or that a single cosine or a single sine
1809
+ be present with an optional radical.
1810
+
1811
+ If the above conditions dictated by ``two`` are not met then None
1812
+ is returned.
1813
+ """
1814
+ c = s = None
1815
+ co = S.One
1816
+ if a.is_Mul:
1817
+ co, a = a.as_coeff_Mul()
1818
+ if len(a.args) > 2 or not two:
1819
+ return None
1820
+ if a.is_Mul:
1821
+ args = list(a.args)
1822
+ else:
1823
+ args = [a]
1824
+ a = args.pop(0)
1825
+ if isinstance(a, cos):
1826
+ c = a
1827
+ elif isinstance(a, sin):
1828
+ s = a
1829
+ elif a.is_Pow and a.exp is S.Half: # autoeval doesn't allow -1/2
1830
+ co *= a
1831
+ else:
1832
+ return None
1833
+ if args:
1834
+ b = args[0]
1835
+ if isinstance(b, cos):
1836
+ if c:
1837
+ s = b
1838
+ else:
1839
+ c = b
1840
+ elif isinstance(b, sin):
1841
+ if s:
1842
+ c = b
1843
+ else:
1844
+ s = b
1845
+ elif b.is_Pow and b.exp is S.Half:
1846
+ co *= b
1847
+ else:
1848
+ return None
1849
+ return co if co is not S.One else None, c, s
1850
+ elif isinstance(a, cos):
1851
+ c = a
1852
+ elif isinstance(a, sin):
1853
+ s = a
1854
+ if c is None and s is None:
1855
+ return
1856
+ co = co if co is not S.One else None
1857
+ return co, c, s
1858
+
1859
+ # get the parts
1860
+ m = pow_cos_sin(a, two)
1861
+ if m is None:
1862
+ return
1863
+ coa, ca, sa = m
1864
+ m = pow_cos_sin(b, two)
1865
+ if m is None:
1866
+ return
1867
+ cob, cb, sb = m
1868
+
1869
+ # check them
1870
+ if (not ca) and cb or ca and isinstance(ca, sin):
1871
+ coa, ca, sa, cob, cb, sb = cob, cb, sb, coa, ca, sa
1872
+ n1, n2 = n2, n1
1873
+ if not two: # need cos(x) and cos(y) or sin(x) and sin(y)
1874
+ c = ca or sa
1875
+ s = cb or sb
1876
+ if not isinstance(c, s.func):
1877
+ return None
1878
+ return gcd, n1, n2, c.args[0], s.args[0], isinstance(c, cos)
1879
+ else:
1880
+ if not coa and not cob:
1881
+ if (ca and cb and sa and sb):
1882
+ if isinstance(ca, sa.func) is not isinstance(cb, sb.func):
1883
+ return
1884
+ args = {j.args for j in (ca, sa)}
1885
+ if not all(i.args in args for i in (cb, sb)):
1886
+ return
1887
+ return gcd, n1, n2, ca.args[0], sa.args[0], isinstance(ca, sa.func)
1888
+ if ca and sa or cb and sb or \
1889
+ two and (ca is None and sa is None or cb is None and sb is None):
1890
+ return
1891
+ c = ca or sa
1892
+ s = cb or sb
1893
+ if c.args != s.args:
1894
+ return
1895
+ if not coa:
1896
+ coa = S.One
1897
+ if not cob:
1898
+ cob = S.One
1899
+ if coa is cob:
1900
+ gcd *= _ROOT2
1901
+ return gcd, n1, n2, c.args[0], pi/4, False
1902
+ elif coa/cob == _ROOT3:
1903
+ gcd *= 2*cob
1904
+ return gcd, n1, n2, c.args[0], pi/3, False
1905
+ elif coa/cob == _invROOT3:
1906
+ gcd *= 2*coa
1907
+ return gcd, n1, n2, c.args[0], pi/6, False
1908
+
1909
+
1910
+ def as_f_sign_1(e):
1911
+ """If ``e`` is a sum that can be written as ``g*(a + s)`` where
1912
+ ``s`` is ``+/-1``, return ``g``, ``a``, and ``s`` where ``a`` does
1913
+ not have a leading negative coefficient.
1914
+
1915
+ Examples
1916
+ ========
1917
+
1918
+ >>> from sympy.simplify.fu import as_f_sign_1
1919
+ >>> from sympy.abc import x
1920
+ >>> as_f_sign_1(x + 1)
1921
+ (1, x, 1)
1922
+ >>> as_f_sign_1(x - 1)
1923
+ (1, x, -1)
1924
+ >>> as_f_sign_1(-x + 1)
1925
+ (-1, x, -1)
1926
+ >>> as_f_sign_1(-x - 1)
1927
+ (-1, x, 1)
1928
+ >>> as_f_sign_1(2*x + 2)
1929
+ (2, x, 1)
1930
+ """
1931
+ if not e.is_Add or len(e.args) != 2:
1932
+ return
1933
+ # exact match
1934
+ a, b = e.args
1935
+ if a in (S.NegativeOne, S.One):
1936
+ g = S.One
1937
+ if b.is_Mul and b.args[0].is_Number and b.args[0] < 0:
1938
+ a, b = -a, -b
1939
+ g = -g
1940
+ return g, b, a
1941
+ # gcd match
1942
+ a, b = [Factors(i) for i in e.args]
1943
+ ua, ub = a.normal(b)
1944
+ gcd = a.gcd(b).as_expr()
1945
+ if S.NegativeOne in ua.factors:
1946
+ ua = ua.quo(S.NegativeOne)
1947
+ n1 = -1
1948
+ n2 = 1
1949
+ elif S.NegativeOne in ub.factors:
1950
+ ub = ub.quo(S.NegativeOne)
1951
+ n1 = 1
1952
+ n2 = -1
1953
+ else:
1954
+ n1 = n2 = 1
1955
+ a, b = [i.as_expr() for i in (ua, ub)]
1956
+ if a is S.One:
1957
+ a, b = b, a
1958
+ n1, n2 = n2, n1
1959
+ if n1 == -1:
1960
+ gcd = -gcd
1961
+ n2 = -n2
1962
+
1963
+ if b is S.One:
1964
+ return gcd, a, n2
1965
+
1966
+
1967
+ def _osborne(e, d):
1968
+ """Replace all hyperbolic functions with trig functions using
1969
+ the Osborne rule.
1970
+
1971
+ Notes
1972
+ =====
1973
+
1974
+ ``d`` is a dummy variable to prevent automatic evaluation
1975
+ of trigonometric/hyperbolic functions.
1976
+
1977
+
1978
+ References
1979
+ ==========
1980
+
1981
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
1982
+ """
1983
+
1984
+ def f(rv):
1985
+ if not isinstance(rv, HyperbolicFunction):
1986
+ return rv
1987
+ a = rv.args[0]
1988
+ a = a*d if not a.is_Add else Add._from_args([i*d for i in a.args])
1989
+ if isinstance(rv, sinh):
1990
+ return I*sin(a)
1991
+ elif isinstance(rv, cosh):
1992
+ return cos(a)
1993
+ elif isinstance(rv, tanh):
1994
+ return I*tan(a)
1995
+ elif isinstance(rv, coth):
1996
+ return cot(a)/I
1997
+ elif isinstance(rv, sech):
1998
+ return sec(a)
1999
+ elif isinstance(rv, csch):
2000
+ return csc(a)/I
2001
+ else:
2002
+ raise NotImplementedError('unhandled %s' % rv.func)
2003
+
2004
+ return bottom_up(e, f)
2005
+
2006
+
2007
+ def _osbornei(e, d):
2008
+ """Replace all trig functions with hyperbolic functions using
2009
+ the Osborne rule.
2010
+
2011
+ Notes
2012
+ =====
2013
+
2014
+ ``d`` is a dummy variable to prevent automatic evaluation
2015
+ of trigonometric/hyperbolic functions.
2016
+
2017
+ References
2018
+ ==========
2019
+
2020
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
2021
+ """
2022
+
2023
+ def f(rv):
2024
+ if not isinstance(rv, TrigonometricFunction):
2025
+ return rv
2026
+ const, x = rv.args[0].as_independent(d, as_Add=True)
2027
+ a = x.xreplace({d: S.One}) + const*I
2028
+ if isinstance(rv, sin):
2029
+ return sinh(a)/I
2030
+ elif isinstance(rv, cos):
2031
+ return cosh(a)
2032
+ elif isinstance(rv, tan):
2033
+ return tanh(a)/I
2034
+ elif isinstance(rv, cot):
2035
+ return coth(a)*I
2036
+ elif isinstance(rv, sec):
2037
+ return sech(a)
2038
+ elif isinstance(rv, csc):
2039
+ return csch(a)*I
2040
+ else:
2041
+ raise NotImplementedError('unhandled %s' % rv.func)
2042
+
2043
+ return bottom_up(e, f)
2044
+
2045
+
2046
+ def hyper_as_trig(rv):
2047
+ """Return an expression containing hyperbolic functions in terms
2048
+ of trigonometric functions. Any trigonometric functions initially
2049
+ present are replaced with Dummy symbols and the function to undo
2050
+ the masking and the conversion back to hyperbolics is also returned. It
2051
+ should always be true that::
2052
+
2053
+ t, f = hyper_as_trig(expr)
2054
+ expr == f(t)
2055
+
2056
+ Examples
2057
+ ========
2058
+
2059
+ >>> from sympy.simplify.fu import hyper_as_trig, fu
2060
+ >>> from sympy.abc import x
2061
+ >>> from sympy import cosh, sinh
2062
+ >>> eq = sinh(x)**2 + cosh(x)**2
2063
+ >>> t, f = hyper_as_trig(eq)
2064
+ >>> f(fu(t))
2065
+ cosh(2*x)
2066
+
2067
+ References
2068
+ ==========
2069
+
2070
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
2071
+ """
2072
+ from sympy.simplify.simplify import signsimp
2073
+ from sympy.simplify.radsimp import collect
2074
+
2075
+ # mask off trig functions
2076
+ trigs = rv.atoms(TrigonometricFunction)
2077
+ reps = [(t, Dummy()) for t in trigs]
2078
+ masked = rv.xreplace(dict(reps))
2079
+
2080
+ # get inversion substitutions in place
2081
+ reps = [(v, k) for k, v in reps]
2082
+
2083
+ d = Dummy()
2084
+
2085
+ return _osborne(masked, d), lambda x: collect(signsimp(
2086
+ _osbornei(x, d).xreplace(dict(reps))), S.ImaginaryUnit)
2087
+
2088
+
2089
+ def sincos_to_sum(expr):
2090
+ """Convert products and powers of sin and cos to sums.
2091
+
2092
+ Explanation
2093
+ ===========
2094
+
2095
+ Applied power reduction TRpower first, then expands products, and
2096
+ converts products to sums with TR8.
2097
+
2098
+ Examples
2099
+ ========
2100
+
2101
+ >>> from sympy.simplify.fu import sincos_to_sum
2102
+ >>> from sympy.abc import x
2103
+ >>> from sympy import cos, sin
2104
+ >>> sincos_to_sum(16*sin(x)**3*cos(2*x)**2)
2105
+ 7*sin(x) - 5*sin(3*x) + 3*sin(5*x) - sin(7*x)
2106
+ """
2107
+
2108
+ if not expr.has(cos, sin):
2109
+ return expr
2110
+ else:
2111
+ return TR8(expand_mul(TRpower(expr)))
wemm/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)
wemm/lib/python3.10/site-packages/sympy/simplify/radsimp.py ADDED
@@ -0,0 +1,1227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ from sympy.core import sympify, S, Mul, Derivative, Pow
4
+ from sympy.core.add import _unevaluated_Add, Add
5
+ from sympy.core.assumptions import assumptions
6
+ from sympy.core.exprtools import Factors, gcd_terms
7
+ from sympy.core.function import _mexpand, expand_mul, expand_power_base
8
+ from sympy.core.mul import _keep_coeff, _unevaluated_Mul, _mulsort
9
+ from sympy.core.numbers import Rational, zoo, nan
10
+ from sympy.core.parameters import global_parameters
11
+ from sympy.core.sorting import ordered, default_sort_key
12
+ from sympy.core.symbol import Dummy, Wild, symbols
13
+ from sympy.functions import exp, sqrt, log
14
+ from sympy.functions.elementary.complexes import Abs
15
+ from sympy.polys import gcd
16
+ from sympy.simplify.sqrtdenest import sqrtdenest
17
+ from sympy.utilities.iterables import iterable, sift
18
+
19
+
20
+
21
+
22
+ def collect(expr, syms, func=None, evaluate=None, exact=False, distribute_order_term=True):
23
+ """
24
+ Collect additive terms of an expression.
25
+
26
+ Explanation
27
+ ===========
28
+
29
+ This function collects additive terms of an expression with respect
30
+ to a list of expression up to powers with rational exponents. By the
31
+ term symbol here are meant arbitrary expressions, which can contain
32
+ powers, products, sums etc. In other words symbol is a pattern which
33
+ will be searched for in the expression's terms.
34
+
35
+ The input expression is not expanded by :func:`collect`, so user is
36
+ expected to provide an expression in an appropriate form. This makes
37
+ :func:`collect` more predictable as there is no magic happening behind the
38
+ scenes. However, it is important to note, that powers of products are
39
+ converted to products of powers using the :func:`~.expand_power_base`
40
+ function.
41
+
42
+ There are two possible types of output. First, if ``evaluate`` flag is
43
+ set, this function will return an expression with collected terms or
44
+ else it will return a dictionary with expressions up to rational powers
45
+ as keys and collected coefficients as values.
46
+
47
+ Examples
48
+ ========
49
+
50
+ >>> from sympy import S, collect, expand, factor, Wild
51
+ >>> from sympy.abc import a, b, c, x, y
52
+
53
+ This function can collect symbolic coefficients in polynomials or
54
+ rational expressions. It will manage to find all integer or rational
55
+ powers of collection variable::
56
+
57
+ >>> collect(a*x**2 + b*x**2 + a*x - b*x + c, x)
58
+ c + x**2*(a + b) + x*(a - b)
59
+
60
+ The same result can be achieved in dictionary form::
61
+
62
+ >>> d = collect(a*x**2 + b*x**2 + a*x - b*x + c, x, evaluate=False)
63
+ >>> d[x**2]
64
+ a + b
65
+ >>> d[x]
66
+ a - b
67
+ >>> d[S.One]
68
+ c
69
+
70
+ You can also work with multivariate polynomials. However, remember that
71
+ this function is greedy so it will care only about a single symbol at time,
72
+ in specification order::
73
+
74
+ >>> collect(x**2 + y*x**2 + x*y + y + a*y, [x, y])
75
+ x**2*(y + 1) + x*y + y*(a + 1)
76
+
77
+ Also more complicated expressions can be used as patterns::
78
+
79
+ >>> from sympy import sin, log
80
+ >>> collect(a*sin(2*x) + b*sin(2*x), sin(2*x))
81
+ (a + b)*sin(2*x)
82
+
83
+ >>> collect(a*x*log(x) + b*(x*log(x)), x*log(x))
84
+ x*(a + b)*log(x)
85
+
86
+ You can use wildcards in the pattern::
87
+
88
+ >>> w = Wild('w1')
89
+ >>> collect(a*x**y - b*x**y, w**y)
90
+ x**y*(a - b)
91
+
92
+ It is also possible to work with symbolic powers, although it has more
93
+ complicated behavior, because in this case power's base and symbolic part
94
+ of the exponent are treated as a single symbol::
95
+
96
+ >>> collect(a*x**c + b*x**c, x)
97
+ a*x**c + b*x**c
98
+ >>> collect(a*x**c + b*x**c, x**c)
99
+ x**c*(a + b)
100
+
101
+ However if you incorporate rationals to the exponents, then you will get
102
+ well known behavior::
103
+
104
+ >>> collect(a*x**(2*c) + b*x**(2*c), x**c)
105
+ x**(2*c)*(a + b)
106
+
107
+ Note also that all previously stated facts about :func:`collect` function
108
+ apply to the exponential function, so you can get::
109
+
110
+ >>> from sympy import exp
111
+ >>> collect(a*exp(2*x) + b*exp(2*x), exp(x))
112
+ (a + b)*exp(2*x)
113
+
114
+ If you are interested only in collecting specific powers of some symbols
115
+ then set ``exact`` flag to True::
116
+
117
+ >>> collect(a*x**7 + b*x**7, x, exact=True)
118
+ a*x**7 + b*x**7
119
+ >>> collect(a*x**7 + b*x**7, x**7, exact=True)
120
+ x**7*(a + b)
121
+
122
+ If you want to collect on any object containing symbols, set
123
+ ``exact`` to None:
124
+
125
+ >>> collect(x*exp(x) + sin(x)*y + sin(x)*2 + 3*x, x, exact=None)
126
+ x*exp(x) + 3*x + (y + 2)*sin(x)
127
+ >>> collect(a*x*y + x*y + b*x + x, [x, y], exact=None)
128
+ x*y*(a + 1) + x*(b + 1)
129
+
130
+ You can also apply this function to differential equations, where
131
+ derivatives of arbitrary order can be collected. Note that if you
132
+ collect with respect to a function or a derivative of a function, all
133
+ derivatives of that function will also be collected. Use
134
+ ``exact=True`` to prevent this from happening::
135
+
136
+ >>> from sympy import Derivative as D, collect, Function
137
+ >>> f = Function('f') (x)
138
+
139
+ >>> collect(a*D(f,x) + b*D(f,x), D(f,x))
140
+ (a + b)*Derivative(f(x), x)
141
+
142
+ >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), f)
143
+ (a + b)*Derivative(f(x), (x, 2))
144
+
145
+ >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), D(f,x), exact=True)
146
+ a*Derivative(f(x), (x, 2)) + b*Derivative(f(x), (x, 2))
147
+
148
+ >>> collect(a*D(f,x) + b*D(f,x) + a*f + b*f, f)
149
+ (a + b)*f(x) + (a + b)*Derivative(f(x), x)
150
+
151
+ Or you can even match both derivative order and exponent at the same time::
152
+
153
+ >>> collect(a*D(D(f,x),x)**2 + b*D(D(f,x),x)**2, D(f,x))
154
+ (a + b)*Derivative(f(x), (x, 2))**2
155
+
156
+ Finally, you can apply a function to each of the collected coefficients.
157
+ For example you can factorize symbolic coefficients of polynomial::
158
+
159
+ >>> f = expand((x + a + 1)**3)
160
+
161
+ >>> collect(f, x, factor)
162
+ x**3 + 3*x**2*(a + 1) + 3*x*(a + 1)**2 + (a + 1)**3
163
+
164
+ .. note:: Arguments are expected to be in expanded form, so you might have
165
+ to call :func:`~.expand` prior to calling this function.
166
+
167
+ See Also
168
+ ========
169
+
170
+ collect_const, collect_sqrt, rcollect
171
+ """
172
+ expr = sympify(expr)
173
+ syms = [sympify(i) for i in (syms if iterable(syms) else [syms])]
174
+
175
+ # replace syms[i] if it is not x, -x or has Wild symbols
176
+ cond = lambda x: x.is_Symbol or (-x).is_Symbol or bool(
177
+ x.atoms(Wild))
178
+ _, nonsyms = sift(syms, cond, binary=True)
179
+ if nonsyms:
180
+ reps = dict(zip(nonsyms, [Dummy(**assumptions(i)) for i in nonsyms]))
181
+ syms = [reps.get(s, s) for s in syms]
182
+ rv = collect(expr.subs(reps), syms,
183
+ func=func, evaluate=evaluate, exact=exact,
184
+ distribute_order_term=distribute_order_term)
185
+ urep = {v: k for k, v in reps.items()}
186
+ if not isinstance(rv, dict):
187
+ return rv.xreplace(urep)
188
+ else:
189
+ return {urep.get(k, k).xreplace(urep): v.xreplace(urep)
190
+ for k, v in rv.items()}
191
+
192
+ # see if other expressions should be considered
193
+ if exact is None:
194
+ _syms = set()
195
+ for i in Add.make_args(expr):
196
+ if not i.has_free(*syms) or i in syms:
197
+ continue
198
+ if not i.is_Mul and i not in syms:
199
+ _syms.add(i)
200
+ else:
201
+ # identify compound generators
202
+ g = i._new_rawargs(*i.as_coeff_mul(*syms)[1])
203
+ if g not in syms:
204
+ _syms.add(g)
205
+ simple = all(i.is_Pow and i.base in syms for i in _syms)
206
+ syms = syms + list(ordered(_syms))
207
+ if not simple:
208
+ return collect(expr, syms,
209
+ func=func, evaluate=evaluate, exact=False,
210
+ distribute_order_term=distribute_order_term)
211
+
212
+ if evaluate is None:
213
+ evaluate = global_parameters.evaluate
214
+
215
+ def make_expression(terms):
216
+ product = []
217
+
218
+ for term, rat, sym, deriv in terms:
219
+ if deriv is not None:
220
+ var, order = deriv
221
+
222
+ while order > 0:
223
+ term, order = Derivative(term, var), order - 1
224
+
225
+ if sym is None:
226
+ if rat is S.One:
227
+ product.append(term)
228
+ else:
229
+ product.append(Pow(term, rat))
230
+ else:
231
+ product.append(Pow(term, rat*sym))
232
+
233
+ return Mul(*product)
234
+
235
+ def parse_derivative(deriv):
236
+ # scan derivatives tower in the input expression and return
237
+ # underlying function and maximal differentiation order
238
+ expr, sym, order = deriv.expr, deriv.variables[0], 1
239
+
240
+ for s in deriv.variables[1:]:
241
+ if s == sym:
242
+ order += 1
243
+ else:
244
+ raise NotImplementedError(
245
+ 'Improve MV Derivative support in collect')
246
+
247
+ while isinstance(expr, Derivative):
248
+ s0 = expr.variables[0]
249
+
250
+ for s in expr.variables:
251
+ if s != s0:
252
+ raise NotImplementedError(
253
+ 'Improve MV Derivative support in collect')
254
+
255
+ if s0 == sym:
256
+ expr, order = expr.expr, order + len(expr.variables)
257
+ else:
258
+ break
259
+
260
+ return expr, (sym, Rational(order))
261
+
262
+ def parse_term(expr):
263
+ """Parses expression expr and outputs tuple (sexpr, rat_expo,
264
+ sym_expo, deriv)
265
+ where:
266
+ - sexpr is the base expression
267
+ - rat_expo is the rational exponent that sexpr is raised to
268
+ - sym_expo is the symbolic exponent that sexpr is raised to
269
+ - deriv contains the derivatives of the expression
270
+
271
+ For example, the output of x would be (x, 1, None, None)
272
+ the output of 2**x would be (2, 1, x, None).
273
+ """
274
+ rat_expo, sym_expo = S.One, None
275
+ sexpr, deriv = expr, None
276
+
277
+ if expr.is_Pow:
278
+ if isinstance(expr.base, Derivative):
279
+ sexpr, deriv = parse_derivative(expr.base)
280
+ else:
281
+ sexpr = expr.base
282
+
283
+ if expr.base == S.Exp1:
284
+ arg = expr.exp
285
+ if arg.is_Rational:
286
+ sexpr, rat_expo = S.Exp1, arg
287
+ elif arg.is_Mul:
288
+ coeff, tail = arg.as_coeff_Mul(rational=True)
289
+ sexpr, rat_expo = exp(tail), coeff
290
+
291
+ elif expr.exp.is_Number:
292
+ rat_expo = expr.exp
293
+ else:
294
+ coeff, tail = expr.exp.as_coeff_Mul()
295
+
296
+ if coeff.is_Number:
297
+ rat_expo, sym_expo = coeff, tail
298
+ else:
299
+ sym_expo = expr.exp
300
+ elif isinstance(expr, exp):
301
+ arg = expr.exp
302
+ if arg.is_Rational:
303
+ sexpr, rat_expo = S.Exp1, arg
304
+ elif arg.is_Mul:
305
+ coeff, tail = arg.as_coeff_Mul(rational=True)
306
+ sexpr, rat_expo = exp(tail), coeff
307
+ elif isinstance(expr, Derivative):
308
+ sexpr, deriv = parse_derivative(expr)
309
+
310
+ return sexpr, rat_expo, sym_expo, deriv
311
+
312
+ def parse_expression(terms, pattern):
313
+ """Parse terms searching for a pattern.
314
+ Terms is a list of tuples as returned by parse_terms;
315
+ Pattern is an expression treated as a product of factors.
316
+ """
317
+ pattern = Mul.make_args(pattern)
318
+
319
+ if len(terms) < len(pattern):
320
+ # pattern is longer than matched product
321
+ # so no chance for positive parsing result
322
+ return None
323
+ else:
324
+ pattern = [parse_term(elem) for elem in pattern]
325
+
326
+ terms = terms[:] # need a copy
327
+ elems, common_expo, has_deriv = [], None, False
328
+
329
+ for elem, e_rat, e_sym, e_ord in pattern:
330
+
331
+ if elem.is_Number and e_rat == 1 and e_sym is None:
332
+ # a constant is a match for everything
333
+ continue
334
+
335
+ for j in range(len(terms)):
336
+ if terms[j] is None:
337
+ continue
338
+
339
+ term, t_rat, t_sym, t_ord = terms[j]
340
+
341
+ # keeping track of whether one of the terms had
342
+ # a derivative or not as this will require rebuilding
343
+ # the expression later
344
+ if t_ord is not None:
345
+ has_deriv = True
346
+
347
+ if (term.match(elem) is not None and
348
+ (t_sym == e_sym or t_sym is not None and
349
+ e_sym is not None and
350
+ t_sym.match(e_sym) is not None)):
351
+ if exact is False:
352
+ # we don't have to be exact so find common exponent
353
+ # for both expression's term and pattern's element
354
+ expo = t_rat / e_rat
355
+
356
+ if common_expo is None:
357
+ # first time
358
+ common_expo = expo
359
+ else:
360
+ # common exponent was negotiated before so
361
+ # there is no chance for a pattern match unless
362
+ # common and current exponents are equal
363
+ if common_expo != expo:
364
+ common_expo = 1
365
+ else:
366
+ # we ought to be exact so all fields of
367
+ # interest must match in every details
368
+ if e_rat != t_rat or e_ord != t_ord:
369
+ continue
370
+
371
+ # found common term so remove it from the expression
372
+ # and try to match next element in the pattern
373
+ elems.append(terms[j])
374
+ terms[j] = None
375
+
376
+ break
377
+
378
+ else:
379
+ # pattern element not found
380
+ return None
381
+
382
+ return [_f for _f in terms if _f], elems, common_expo, has_deriv
383
+
384
+ if evaluate:
385
+ if expr.is_Add:
386
+ o = expr.getO() or 0
387
+ expr = expr.func(*[
388
+ collect(a, syms, func, True, exact, distribute_order_term)
389
+ for a in expr.args if a != o]) + o
390
+ elif expr.is_Mul:
391
+ return expr.func(*[
392
+ collect(term, syms, func, True, exact, distribute_order_term)
393
+ for term in expr.args])
394
+ elif expr.is_Pow:
395
+ b = collect(
396
+ expr.base, syms, func, True, exact, distribute_order_term)
397
+ return Pow(b, expr.exp)
398
+
399
+ syms = [expand_power_base(i, deep=False) for i in syms]
400
+
401
+ order_term = None
402
+
403
+ if distribute_order_term:
404
+ order_term = expr.getO()
405
+
406
+ if order_term is not None:
407
+ if order_term.has(*syms):
408
+ order_term = None
409
+ else:
410
+ expr = expr.removeO()
411
+
412
+ summa = [expand_power_base(i, deep=False) for i in Add.make_args(expr)]
413
+
414
+ collected, disliked = defaultdict(list), S.Zero
415
+ for product in summa:
416
+ c, nc = product.args_cnc(split_1=False)
417
+ args = list(ordered(c)) + nc
418
+ terms = [parse_term(i) for i in args]
419
+ small_first = True
420
+
421
+ for symbol in syms:
422
+ if isinstance(symbol, Derivative) and small_first:
423
+ terms = list(reversed(terms))
424
+ small_first = not small_first
425
+ result = parse_expression(terms, symbol)
426
+
427
+ if result is not None:
428
+ if not symbol.is_commutative:
429
+ raise AttributeError("Can not collect noncommutative symbol")
430
+
431
+ terms, elems, common_expo, has_deriv = result
432
+
433
+ # when there was derivative in current pattern we
434
+ # will need to rebuild its expression from scratch
435
+ if not has_deriv:
436
+ margs = []
437
+ for elem in elems:
438
+ if elem[2] is None:
439
+ e = elem[1]
440
+ else:
441
+ e = elem[1]*elem[2]
442
+ margs.append(Pow(elem[0], e))
443
+ index = Mul(*margs)
444
+ else:
445
+ index = make_expression(elems)
446
+ terms = expand_power_base(make_expression(terms), deep=False)
447
+ index = expand_power_base(index, deep=False)
448
+ collected[index].append(terms)
449
+ break
450
+ else:
451
+ # none of the patterns matched
452
+ disliked += product
453
+ # add terms now for each key
454
+ collected = {k: Add(*v) for k, v in collected.items()}
455
+
456
+ if disliked is not S.Zero:
457
+ collected[S.One] = disliked
458
+
459
+ if order_term is not None:
460
+ for key, val in collected.items():
461
+ collected[key] = val + order_term
462
+
463
+ if func is not None:
464
+ collected = {
465
+ key: func(val) for key, val in collected.items()}
466
+
467
+ if evaluate:
468
+ return Add(*[key*val for key, val in collected.items()])
469
+ else:
470
+ return collected
471
+
472
+
473
+ def rcollect(expr, *vars):
474
+ """
475
+ Recursively collect sums in an expression.
476
+
477
+ Examples
478
+ ========
479
+
480
+ >>> from sympy.simplify import rcollect
481
+ >>> from sympy.abc import x, y
482
+
483
+ >>> expr = (x**2*y + x*y + x + y)/(x + y)
484
+
485
+ >>> rcollect(expr, y)
486
+ (x + y*(x**2 + x + 1))/(x + y)
487
+
488
+ See Also
489
+ ========
490
+
491
+ collect, collect_const, collect_sqrt
492
+ """
493
+ if expr.is_Atom or not expr.has(*vars):
494
+ return expr
495
+ else:
496
+ expr = expr.__class__(*[rcollect(arg, *vars) for arg in expr.args])
497
+
498
+ if expr.is_Add:
499
+ return collect(expr, vars)
500
+ else:
501
+ return expr
502
+
503
+
504
+ def collect_sqrt(expr, evaluate=None):
505
+ """Return expr with terms having common square roots collected together.
506
+ If ``evaluate`` is False a count indicating the number of sqrt-containing
507
+ terms will be returned and, if non-zero, the terms of the Add will be
508
+ returned, else the expression itself will be returned as a single term.
509
+ If ``evaluate`` is True, the expression with any collected terms will be
510
+ returned.
511
+
512
+ Note: since I = sqrt(-1), it is collected, too.
513
+
514
+ Examples
515
+ ========
516
+
517
+ >>> from sympy import sqrt
518
+ >>> from sympy.simplify.radsimp import collect_sqrt
519
+ >>> from sympy.abc import a, b
520
+
521
+ >>> r2, r3, r5 = [sqrt(i) for i in [2, 3, 5]]
522
+ >>> collect_sqrt(a*r2 + b*r2)
523
+ sqrt(2)*(a + b)
524
+ >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r3)
525
+ sqrt(2)*(a + b) + sqrt(3)*(a + b)
526
+ >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5)
527
+ sqrt(3)*a + sqrt(5)*b + sqrt(2)*(a + b)
528
+
529
+ If evaluate is False then the arguments will be sorted and
530
+ returned as a list and a count of the number of sqrt-containing
531
+ terms will be returned:
532
+
533
+ >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5, evaluate=False)
534
+ ((sqrt(3)*a, sqrt(5)*b, sqrt(2)*(a + b)), 3)
535
+ >>> collect_sqrt(a*sqrt(2) + b, evaluate=False)
536
+ ((b, sqrt(2)*a), 1)
537
+ >>> collect_sqrt(a + b, evaluate=False)
538
+ ((a + b,), 0)
539
+
540
+ See Also
541
+ ========
542
+
543
+ collect, collect_const, rcollect
544
+ """
545
+ if evaluate is None:
546
+ evaluate = global_parameters.evaluate
547
+ # this step will help to standardize any complex arguments
548
+ # of sqrts
549
+ coeff, expr = expr.as_content_primitive()
550
+ vars = set()
551
+ for a in Add.make_args(expr):
552
+ for m in a.args_cnc()[0]:
553
+ if m.is_number and (
554
+ m.is_Pow and m.exp.is_Rational and m.exp.q == 2 or
555
+ m is S.ImaginaryUnit):
556
+ vars.add(m)
557
+
558
+ # we only want radicals, so exclude Number handling; in this case
559
+ # d will be evaluated
560
+ d = collect_const(expr, *vars, Numbers=False)
561
+ hit = expr != d
562
+
563
+ if not evaluate:
564
+ nrad = 0
565
+ # make the evaluated args canonical
566
+ args = list(ordered(Add.make_args(d)))
567
+ for i, m in enumerate(args):
568
+ c, nc = m.args_cnc()
569
+ for ci in c:
570
+ # XXX should this be restricted to ci.is_number as above?
571
+ if ci.is_Pow and ci.exp.is_Rational and ci.exp.q == 2 or \
572
+ ci is S.ImaginaryUnit:
573
+ nrad += 1
574
+ break
575
+ args[i] *= coeff
576
+ if not (hit or nrad):
577
+ args = [Add(*args)]
578
+ return tuple(args), nrad
579
+
580
+ return coeff*d
581
+
582
+
583
+ def collect_abs(expr):
584
+ """Return ``expr`` with arguments of multiple Abs in a term collected
585
+ under a single instance.
586
+
587
+ Examples
588
+ ========
589
+
590
+ >>> from sympy.simplify.radsimp import collect_abs
591
+ >>> from sympy.abc import x
592
+ >>> collect_abs(abs(x + 1)/abs(x**2 - 1))
593
+ Abs((x + 1)/(x**2 - 1))
594
+ >>> collect_abs(abs(1/x))
595
+ Abs(1/x)
596
+ """
597
+ def _abs(mul):
598
+ c, nc = mul.args_cnc()
599
+ a = []
600
+ o = []
601
+ for i in c:
602
+ if isinstance(i, Abs):
603
+ a.append(i.args[0])
604
+ elif isinstance(i, Pow) and isinstance(i.base, Abs) and i.exp.is_real:
605
+ a.append(i.base.args[0]**i.exp)
606
+ else:
607
+ o.append(i)
608
+ if len(a) < 2 and not any(i.exp.is_negative for i in a if isinstance(i, Pow)):
609
+ return mul
610
+ absarg = Mul(*a)
611
+ A = Abs(absarg)
612
+ args = [A]
613
+ args.extend(o)
614
+ if not A.has(Abs):
615
+ args.extend(nc)
616
+ return Mul(*args)
617
+ if not isinstance(A, Abs):
618
+ # reevaluate and make it unevaluated
619
+ A = Abs(absarg, evaluate=False)
620
+ args[0] = A
621
+ _mulsort(args)
622
+ args.extend(nc) # nc always go last
623
+ return Mul._from_args(args, is_commutative=not nc)
624
+
625
+ return expr.replace(
626
+ lambda x: isinstance(x, Mul),
627
+ lambda x: _abs(x)).replace(
628
+ lambda x: isinstance(x, Pow),
629
+ lambda x: _abs(x))
630
+
631
+
632
+ def collect_const(expr, *vars, Numbers=True):
633
+ """A non-greedy collection of terms with similar number coefficients in
634
+ an Add expr. If ``vars`` is given then only those constants will be
635
+ targeted. Although any Number can also be targeted, if this is not
636
+ desired set ``Numbers=False`` and no Float or Rational will be collected.
637
+
638
+ Parameters
639
+ ==========
640
+
641
+ expr : SymPy expression
642
+ This parameter defines the expression the expression from which
643
+ terms with similar coefficients are to be collected. A non-Add
644
+ expression is returned as it is.
645
+
646
+ vars : variable length collection of Numbers, optional
647
+ Specifies the constants to target for collection. Can be multiple in
648
+ number.
649
+
650
+ Numbers : bool
651
+ Specifies to target all instance of
652
+ :class:`sympy.core.numbers.Number` class. If ``Numbers=False``, then
653
+ no Float or Rational will be collected.
654
+
655
+ Returns
656
+ =======
657
+
658
+ expr : Expr
659
+ Returns an expression with similar coefficient terms collected.
660
+
661
+ Examples
662
+ ========
663
+
664
+ >>> from sympy import sqrt
665
+ >>> from sympy.abc import s, x, y, z
666
+ >>> from sympy.simplify.radsimp import collect_const
667
+ >>> collect_const(sqrt(3) + sqrt(3)*(1 + sqrt(2)))
668
+ sqrt(3)*(sqrt(2) + 2)
669
+ >>> collect_const(sqrt(3)*s + sqrt(7)*s + sqrt(3) + sqrt(7))
670
+ (sqrt(3) + sqrt(7))*(s + 1)
671
+ >>> s = sqrt(2) + 2
672
+ >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7))
673
+ (sqrt(2) + 3)*(sqrt(3) + sqrt(7))
674
+ >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7), sqrt(3))
675
+ sqrt(7) + sqrt(3)*(sqrt(2) + 3) + sqrt(7)*(sqrt(2) + 2)
676
+
677
+ The collection is sign-sensitive, giving higher precedence to the
678
+ unsigned values:
679
+
680
+ >>> collect_const(x - y - z)
681
+ x - (y + z)
682
+ >>> collect_const(-y - z)
683
+ -(y + z)
684
+ >>> collect_const(2*x - 2*y - 2*z, 2)
685
+ 2*(x - y - z)
686
+ >>> collect_const(2*x - 2*y - 2*z, -2)
687
+ 2*x - 2*(y + z)
688
+
689
+ See Also
690
+ ========
691
+
692
+ collect, collect_sqrt, rcollect
693
+ """
694
+ if not expr.is_Add:
695
+ return expr
696
+
697
+ recurse = False
698
+
699
+ if not vars:
700
+ recurse = True
701
+ vars = set()
702
+ for a in expr.args:
703
+ for m in Mul.make_args(a):
704
+ if m.is_number:
705
+ vars.add(m)
706
+ else:
707
+ vars = sympify(vars)
708
+ if not Numbers:
709
+ vars = [v for v in vars if not v.is_Number]
710
+
711
+ vars = list(ordered(vars))
712
+ for v in vars:
713
+ terms = defaultdict(list)
714
+ Fv = Factors(v)
715
+ for m in Add.make_args(expr):
716
+ f = Factors(m)
717
+ q, r = f.div(Fv)
718
+ if r.is_one:
719
+ # only accept this as a true factor if
720
+ # it didn't change an exponent from an Integer
721
+ # to a non-Integer, e.g. 2/sqrt(2) -> sqrt(2)
722
+ # -- we aren't looking for this sort of change
723
+ fwas = f.factors.copy()
724
+ fnow = q.factors
725
+ if not any(k in fwas and fwas[k].is_Integer and not
726
+ fnow[k].is_Integer for k in fnow):
727
+ terms[v].append(q.as_expr())
728
+ continue
729
+ terms[S.One].append(m)
730
+
731
+ args = []
732
+ hit = False
733
+ uneval = False
734
+ for k in ordered(terms):
735
+ v = terms[k]
736
+ if k is S.One:
737
+ args.extend(v)
738
+ continue
739
+
740
+ if len(v) > 1:
741
+ v = Add(*v)
742
+ hit = True
743
+ if recurse and v != expr:
744
+ vars.append(v)
745
+ else:
746
+ v = v[0]
747
+
748
+ # be careful not to let uneval become True unless
749
+ # it must be because it's going to be more expensive
750
+ # to rebuild the expression as an unevaluated one
751
+ if Numbers and k.is_Number and v.is_Add:
752
+ args.append(_keep_coeff(k, v, sign=True))
753
+ uneval = True
754
+ else:
755
+ args.append(k*v)
756
+
757
+ if hit:
758
+ if uneval:
759
+ expr = _unevaluated_Add(*args)
760
+ else:
761
+ expr = Add(*args)
762
+ if not expr.is_Add:
763
+ break
764
+
765
+ return expr
766
+
767
+
768
+ def radsimp(expr, symbolic=True, max_terms=4):
769
+ r"""
770
+ Rationalize the denominator by removing square roots.
771
+
772
+ Explanation
773
+ ===========
774
+
775
+ The expression returned from radsimp must be used with caution
776
+ since if the denominator contains symbols, it will be possible to make
777
+ substitutions that violate the assumptions of the simplification process:
778
+ that for a denominator matching a + b*sqrt(c), a != +/-b*sqrt(c). (If
779
+ there are no symbols, this assumptions is made valid by collecting terms
780
+ of sqrt(c) so the match variable ``a`` does not contain ``sqrt(c)``.) If
781
+ you do not want the simplification to occur for symbolic denominators, set
782
+ ``symbolic`` to False.
783
+
784
+ If there are more than ``max_terms`` radical terms then the expression is
785
+ returned unchanged.
786
+
787
+ Examples
788
+ ========
789
+
790
+ >>> from sympy import radsimp, sqrt, Symbol, pprint
791
+ >>> from sympy import factor_terms, fraction, signsimp
792
+ >>> from sympy.simplify.radsimp import collect_sqrt
793
+ >>> from sympy.abc import a, b, c
794
+
795
+ >>> radsimp(1/(2 + sqrt(2)))
796
+ (2 - sqrt(2))/2
797
+ >>> x,y = map(Symbol, 'xy')
798
+ >>> e = ((2 + 2*sqrt(2))*x + (2 + sqrt(8))*y)/(2 + sqrt(2))
799
+ >>> radsimp(e)
800
+ sqrt(2)*(x + y)
801
+
802
+ No simplification beyond removal of the gcd is done. One might
803
+ want to polish the result a little, however, by collecting
804
+ square root terms:
805
+
806
+ >>> r2 = sqrt(2)
807
+ >>> r5 = sqrt(5)
808
+ >>> ans = radsimp(1/(y*r2 + x*r2 + a*r5 + b*r5)); pprint(ans)
809
+ ___ ___ ___ ___
810
+ \/ 5 *a + \/ 5 *b - \/ 2 *x - \/ 2 *y
811
+ ------------------------------------------
812
+ 2 2 2 2
813
+ 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y
814
+
815
+ >>> n, d = fraction(ans)
816
+ >>> pprint(factor_terms(signsimp(collect_sqrt(n))/d, radical=True))
817
+ ___ ___
818
+ \/ 5 *(a + b) - \/ 2 *(x + y)
819
+ ------------------------------------------
820
+ 2 2 2 2
821
+ 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y
822
+
823
+ If radicals in the denominator cannot be removed or there is no denominator,
824
+ the original expression will be returned.
825
+
826
+ >>> radsimp(sqrt(2)*x + sqrt(2))
827
+ sqrt(2)*x + sqrt(2)
828
+
829
+ Results with symbols will not always be valid for all substitutions:
830
+
831
+ >>> eq = 1/(a + b*sqrt(c))
832
+ >>> eq.subs(a, b*sqrt(c))
833
+ 1/(2*b*sqrt(c))
834
+ >>> radsimp(eq).subs(a, b*sqrt(c))
835
+ nan
836
+
837
+ If ``symbolic=False``, symbolic denominators will not be transformed (but
838
+ numeric denominators will still be processed):
839
+
840
+ >>> radsimp(eq, symbolic=False)
841
+ 1/(a + b*sqrt(c))
842
+
843
+ """
844
+ from sympy.simplify.simplify import signsimp
845
+
846
+ syms = symbols("a:d A:D")
847
+ def _num(rterms):
848
+ # return the multiplier that will simplify the expression described
849
+ # by rterms [(sqrt arg, coeff), ... ]
850
+ a, b, c, d, A, B, C, D = syms
851
+ if len(rterms) == 2:
852
+ reps = dict(list(zip([A, a, B, b], [j for i in rterms for j in i])))
853
+ return (
854
+ sqrt(A)*a - sqrt(B)*b).xreplace(reps)
855
+ if len(rterms) == 3:
856
+ reps = dict(list(zip([A, a, B, b, C, c], [j for i in rterms for j in i])))
857
+ return (
858
+ (sqrt(A)*a + sqrt(B)*b - sqrt(C)*c)*(2*sqrt(A)*sqrt(B)*a*b - A*a**2 -
859
+ B*b**2 + C*c**2)).xreplace(reps)
860
+ elif len(rterms) == 4:
861
+ reps = dict(list(zip([A, a, B, b, C, c, D, d], [j for i in rterms for j in i])))
862
+ return ((sqrt(A)*a + sqrt(B)*b - sqrt(C)*c - sqrt(D)*d)*(2*sqrt(A)*sqrt(B)*a*b
863
+ - A*a**2 - B*b**2 - 2*sqrt(C)*sqrt(D)*c*d + C*c**2 +
864
+ D*d**2)*(-8*sqrt(A)*sqrt(B)*sqrt(C)*sqrt(D)*a*b*c*d + A**2*a**4 -
865
+ 2*A*B*a**2*b**2 - 2*A*C*a**2*c**2 - 2*A*D*a**2*d**2 + B**2*b**4 -
866
+ 2*B*C*b**2*c**2 - 2*B*D*b**2*d**2 + C**2*c**4 - 2*C*D*c**2*d**2 +
867
+ D**2*d**4)).xreplace(reps)
868
+ elif len(rterms) == 1:
869
+ return sqrt(rterms[0][0])
870
+ else:
871
+ raise NotImplementedError
872
+
873
+ def ispow2(d, log2=False):
874
+ if not d.is_Pow:
875
+ return False
876
+ e = d.exp
877
+ if e.is_Rational and e.q == 2 or symbolic and denom(e) == 2:
878
+ return True
879
+ if log2:
880
+ q = 1
881
+ if e.is_Rational:
882
+ q = e.q
883
+ elif symbolic:
884
+ d = denom(e)
885
+ if d.is_Integer:
886
+ q = d
887
+ if q != 1 and log(q, 2).is_Integer:
888
+ return True
889
+ return False
890
+
891
+ def handle(expr):
892
+ # Handle first reduces to the case
893
+ # expr = 1/d, where d is an add, or d is base**p/2.
894
+ # We do this by recursively calling handle on each piece.
895
+ from sympy.simplify.simplify import nsimplify
896
+
897
+ n, d = fraction(expr)
898
+
899
+ if expr.is_Atom or (d.is_Atom and n.is_Atom):
900
+ return expr
901
+ elif not n.is_Atom:
902
+ n = n.func(*[handle(a) for a in n.args])
903
+ return _unevaluated_Mul(n, handle(1/d))
904
+ elif n is not S.One:
905
+ return _unevaluated_Mul(n, handle(1/d))
906
+ elif d.is_Mul:
907
+ return _unevaluated_Mul(*[handle(1/d) for d in d.args])
908
+
909
+ # By this step, expr is 1/d, and d is not a mul.
910
+ if not symbolic and d.free_symbols:
911
+ return expr
912
+
913
+ if ispow2(d):
914
+ d2 = sqrtdenest(sqrt(d.base))**numer(d.exp)
915
+ if d2 != d:
916
+ return handle(1/d2)
917
+ elif d.is_Pow and (d.exp.is_integer or d.base.is_positive):
918
+ # (1/d**i) = (1/d)**i
919
+ return handle(1/d.base)**d.exp
920
+
921
+ if not (d.is_Add or ispow2(d)):
922
+ return 1/d.func(*[handle(a) for a in d.args])
923
+
924
+ # handle 1/d treating d as an Add (though it may not be)
925
+
926
+ keep = True # keep changes that are made
927
+
928
+ # flatten it and collect radicals after checking for special
929
+ # conditions
930
+ d = _mexpand(d)
931
+
932
+ # did it change?
933
+ if d.is_Atom:
934
+ return 1/d
935
+
936
+ # is it a number that might be handled easily?
937
+ if d.is_number:
938
+ _d = nsimplify(d)
939
+ if _d.is_Number and _d.equals(d):
940
+ return 1/_d
941
+
942
+ while True:
943
+ # collect similar terms
944
+ collected = defaultdict(list)
945
+ for m in Add.make_args(d): # d might have become non-Add
946
+ p2 = []
947
+ other = []
948
+ for i in Mul.make_args(m):
949
+ if ispow2(i, log2=True):
950
+ p2.append(i.base if i.exp is S.Half else i.base**(2*i.exp))
951
+ elif i is S.ImaginaryUnit:
952
+ p2.append(S.NegativeOne)
953
+ else:
954
+ other.append(i)
955
+ collected[tuple(ordered(p2))].append(Mul(*other))
956
+ rterms = list(ordered(list(collected.items())))
957
+ rterms = [(Mul(*i), Add(*j)) for i, j in rterms]
958
+ nrad = len(rterms) - (1 if rterms[0][0] is S.One else 0)
959
+ if nrad < 1:
960
+ break
961
+ elif nrad > max_terms:
962
+ # there may have been invalid operations leading to this point
963
+ # so don't keep changes, e.g. this expression is troublesome
964
+ # in collecting terms so as not to raise the issue of 2834:
965
+ # r = sqrt(sqrt(5) + 5)
966
+ # eq = 1/(sqrt(5)*r + 2*sqrt(5)*sqrt(-sqrt(5) + 5) + 5*r)
967
+ keep = False
968
+ break
969
+ if len(rterms) > 4:
970
+ # in general, only 4 terms can be removed with repeated squaring
971
+ # but other considerations can guide selection of radical terms
972
+ # so that radicals are removed
973
+ if all(x.is_Integer and (y**2).is_Rational for x, y in rterms):
974
+ nd, d = rad_rationalize(S.One, Add._from_args(
975
+ [sqrt(x)*y for x, y in rterms]))
976
+ n *= nd
977
+ else:
978
+ # is there anything else that might be attempted?
979
+ keep = False
980
+ break
981
+ from sympy.simplify.powsimp import powsimp, powdenest
982
+
983
+ num = powsimp(_num(rterms))
984
+ n *= num
985
+ d *= num
986
+ d = powdenest(_mexpand(d), force=symbolic)
987
+ if d.has(S.Zero, nan, zoo):
988
+ return expr
989
+ if d.is_Atom:
990
+ break
991
+
992
+ if not keep:
993
+ return expr
994
+ return _unevaluated_Mul(n, 1/d)
995
+
996
+ coeff, expr = expr.as_coeff_Add()
997
+ expr = expr.normal()
998
+ old = fraction(expr)
999
+ n, d = fraction(handle(expr))
1000
+ if old != (n, d):
1001
+ if not d.is_Atom:
1002
+ was = (n, d)
1003
+ n = signsimp(n, evaluate=False)
1004
+ d = signsimp(d, evaluate=False)
1005
+ u = Factors(_unevaluated_Mul(n, 1/d))
1006
+ u = _unevaluated_Mul(*[k**v for k, v in u.factors.items()])
1007
+ n, d = fraction(u)
1008
+ if old == (n, d):
1009
+ n, d = was
1010
+ n = expand_mul(n)
1011
+ if d.is_Number or d.is_Add:
1012
+ n2, d2 = fraction(gcd_terms(_unevaluated_Mul(n, 1/d)))
1013
+ if d2.is_Number or (d2.count_ops() <= d.count_ops()):
1014
+ n, d = [signsimp(i) for i in (n2, d2)]
1015
+ if n.is_Mul and n.args[0].is_Number:
1016
+ n = n.func(*n.args)
1017
+
1018
+ return coeff + _unevaluated_Mul(n, 1/d)
1019
+
1020
+
1021
+ def rad_rationalize(num, den):
1022
+ """
1023
+ Rationalize ``num/den`` by removing square roots in the denominator;
1024
+ num and den are sum of terms whose squares are positive rationals.
1025
+
1026
+ Examples
1027
+ ========
1028
+
1029
+ >>> from sympy import sqrt
1030
+ >>> from sympy.simplify.radsimp import rad_rationalize
1031
+ >>> rad_rationalize(sqrt(3), 1 + sqrt(2)/3)
1032
+ (-sqrt(3) + sqrt(6)/3, -7/9)
1033
+ """
1034
+ if not den.is_Add:
1035
+ return num, den
1036
+ g, a, b = split_surds(den)
1037
+ a = a*sqrt(g)
1038
+ num = _mexpand((a - b)*num)
1039
+ den = _mexpand(a**2 - b**2)
1040
+ return rad_rationalize(num, den)
1041
+
1042
+
1043
+ def fraction(expr, exact=False):
1044
+ """Returns a pair with expression's numerator and denominator.
1045
+ If the given expression is not a fraction then this function
1046
+ will return the tuple (expr, 1).
1047
+
1048
+ This function will not make any attempt to simplify nested
1049
+ fractions or to do any term rewriting at all.
1050
+
1051
+ If only one of the numerator/denominator pair is needed then
1052
+ use numer(expr) or denom(expr) functions respectively.
1053
+
1054
+ >>> from sympy import fraction, Rational, Symbol
1055
+ >>> from sympy.abc import x, y
1056
+
1057
+ >>> fraction(x/y)
1058
+ (x, y)
1059
+ >>> fraction(x)
1060
+ (x, 1)
1061
+
1062
+ >>> fraction(1/y**2)
1063
+ (1, y**2)
1064
+
1065
+ >>> fraction(x*y/2)
1066
+ (x*y, 2)
1067
+ >>> fraction(Rational(1, 2))
1068
+ (1, 2)
1069
+
1070
+ This function will also work fine with assumptions:
1071
+
1072
+ >>> k = Symbol('k', negative=True)
1073
+ >>> fraction(x * y**k)
1074
+ (x, y**(-k))
1075
+
1076
+ If we know nothing about sign of some exponent and ``exact``
1077
+ flag is unset, then the exponent's structure will
1078
+ be analyzed and pretty fraction will be returned:
1079
+
1080
+ >>> from sympy import exp, Mul
1081
+ >>> fraction(2*x**(-y))
1082
+ (2, x**y)
1083
+
1084
+ >>> fraction(exp(-x))
1085
+ (1, exp(x))
1086
+
1087
+ >>> fraction(exp(-x), exact=True)
1088
+ (exp(-x), 1)
1089
+
1090
+ The ``exact`` flag will also keep any unevaluated Muls from
1091
+ being evaluated:
1092
+
1093
+ >>> u = Mul(2, x + 1, evaluate=False)
1094
+ >>> fraction(u)
1095
+ (2*x + 2, 1)
1096
+ >>> fraction(u, exact=True)
1097
+ (2*(x + 1), 1)
1098
+ """
1099
+ expr = sympify(expr)
1100
+
1101
+ numer, denom = [], []
1102
+
1103
+ for term in Mul.make_args(expr):
1104
+ if term.is_commutative and (term.is_Pow or isinstance(term, exp)):
1105
+ b, ex = term.as_base_exp()
1106
+ if ex.is_negative:
1107
+ if ex is S.NegativeOne:
1108
+ denom.append(b)
1109
+ elif exact:
1110
+ if ex.is_constant():
1111
+ denom.append(Pow(b, -ex))
1112
+ else:
1113
+ numer.append(term)
1114
+ else:
1115
+ denom.append(Pow(b, -ex))
1116
+ elif ex.is_positive:
1117
+ numer.append(term)
1118
+ elif not exact and ex.is_Mul:
1119
+ n, d = term.as_numer_denom() # this will cause evaluation
1120
+ if n != 1:
1121
+ numer.append(n)
1122
+ denom.append(d)
1123
+ else:
1124
+ numer.append(term)
1125
+ elif term.is_Rational and not term.is_Integer:
1126
+ if term.p != 1:
1127
+ numer.append(term.p)
1128
+ denom.append(term.q)
1129
+ else:
1130
+ numer.append(term)
1131
+ return Mul(*numer, evaluate=not exact), Mul(*denom, evaluate=not exact)
1132
+
1133
+
1134
+ def numer(expr, exact=False): # default matches fraction's default
1135
+ return fraction(expr, exact=exact)[0]
1136
+
1137
+
1138
+ def denom(expr, exact=False): # default matches fraction's default
1139
+ return fraction(expr, exact=exact)[1]
1140
+
1141
+
1142
+ def fraction_expand(expr, **hints):
1143
+ return expr.expand(frac=True, **hints)
1144
+
1145
+
1146
+ def numer_expand(expr, **hints):
1147
+ # default matches fraction's default
1148
+ a, b = fraction(expr, exact=hints.get('exact', False))
1149
+ return a.expand(numer=True, **hints) / b
1150
+
1151
+
1152
+ def denom_expand(expr, **hints):
1153
+ # default matches fraction's default
1154
+ a, b = fraction(expr, exact=hints.get('exact', False))
1155
+ return a / b.expand(denom=True, **hints)
1156
+
1157
+
1158
+ expand_numer = numer_expand
1159
+ expand_denom = denom_expand
1160
+ expand_fraction = fraction_expand
1161
+
1162
+
1163
+ def split_surds(expr):
1164
+ """
1165
+ Split an expression with terms whose squares are positive rationals
1166
+ into a sum of terms whose surds squared have gcd equal to g
1167
+ and a sum of terms with surds squared prime with g.
1168
+
1169
+ Examples
1170
+ ========
1171
+
1172
+ >>> from sympy import sqrt
1173
+ >>> from sympy.simplify.radsimp import split_surds
1174
+ >>> split_surds(3*sqrt(3) + sqrt(5)/7 + sqrt(6) + sqrt(10) + sqrt(15))
1175
+ (3, sqrt(2) + sqrt(5) + 3, sqrt(5)/7 + sqrt(10))
1176
+ """
1177
+ args = sorted(expr.args, key=default_sort_key)
1178
+ coeff_muls = [x.as_coeff_Mul() for x in args]
1179
+ surds = [x[1]**2 for x in coeff_muls if x[1].is_Pow]
1180
+ surds.sort(key=default_sort_key)
1181
+ g, b1, b2 = _split_gcd(*surds)
1182
+ g2 = g
1183
+ if not b2 and len(b1) >= 2:
1184
+ b1n = [x/g for x in b1]
1185
+ b1n = [x for x in b1n if x != 1]
1186
+ # only a common factor has been factored; split again
1187
+ g1, b1n, b2 = _split_gcd(*b1n)
1188
+ g2 = g*g1
1189
+ a1v, a2v = [], []
1190
+ for c, s in coeff_muls:
1191
+ if s.is_Pow and s.exp == S.Half:
1192
+ s1 = s.base
1193
+ if s1 in b1:
1194
+ a1v.append(c*sqrt(s1/g2))
1195
+ else:
1196
+ a2v.append(c*s)
1197
+ else:
1198
+ a2v.append(c*s)
1199
+ a = Add(*a1v)
1200
+ b = Add(*a2v)
1201
+ return g2, a, b
1202
+
1203
+
1204
+ def _split_gcd(*a):
1205
+ """
1206
+ Split the list of integers ``a`` into a list of integers, ``a1`` having
1207
+ ``g = gcd(a1)``, and a list ``a2`` whose elements are not divisible by
1208
+ ``g``. Returns ``g, a1, a2``.
1209
+
1210
+ Examples
1211
+ ========
1212
+
1213
+ >>> from sympy.simplify.radsimp import _split_gcd
1214
+ >>> _split_gcd(55, 35, 22, 14, 77, 10)
1215
+ (5, [55, 35, 10], [22, 14, 77])
1216
+ """
1217
+ g = a[0]
1218
+ b1 = [g]
1219
+ b2 = []
1220
+ for x in a[1:]:
1221
+ g1 = gcd(g, x)
1222
+ if g1 == 1:
1223
+ b2.append(x)
1224
+ else:
1225
+ g = g1
1226
+ b1.append(x)
1227
+ return g, b1, b2
wemm/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)
wemm/lib/python3.10/site-packages/sympy/simplify/sqrtdenest.py ADDED
@@ -0,0 +1,678 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Add, Expr, Mul, S, sympify
2
+ from sympy.core.function import _mexpand, count_ops, expand_mul
3
+ from sympy.core.sorting import default_sort_key
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.functions import root, sign, sqrt
6
+ from sympy.polys import Poly, PolynomialError
7
+
8
+
9
+ def is_sqrt(expr):
10
+ """Return True if expr is a sqrt, otherwise False."""
11
+
12
+ return expr.is_Pow and expr.exp.is_Rational and abs(expr.exp) is S.Half
13
+
14
+
15
+ def sqrt_depth(p) -> int:
16
+ """Return the maximum depth of any square root argument of p.
17
+
18
+ >>> from sympy.functions.elementary.miscellaneous import sqrt
19
+ >>> from sympy.simplify.sqrtdenest import sqrt_depth
20
+
21
+ Neither of these square roots contains any other square roots
22
+ so the depth is 1:
23
+
24
+ >>> sqrt_depth(1 + sqrt(2)*(1 + sqrt(3)))
25
+ 1
26
+
27
+ The sqrt(3) is contained within a square root so the depth is
28
+ 2:
29
+
30
+ >>> sqrt_depth(1 + sqrt(2)*sqrt(1 + sqrt(3)))
31
+ 2
32
+ """
33
+ if p is S.ImaginaryUnit:
34
+ return 1
35
+ if p.is_Atom:
36
+ return 0
37
+ if p.is_Add or p.is_Mul:
38
+ return max(sqrt_depth(x) for x in p.args)
39
+ if is_sqrt(p):
40
+ return sqrt_depth(p.base) + 1
41
+ return 0
42
+
43
+
44
+ def is_algebraic(p):
45
+ """Return True if p is comprised of only Rationals or square roots
46
+ of Rationals and algebraic operations.
47
+
48
+ Examples
49
+ ========
50
+
51
+ >>> from sympy.functions.elementary.miscellaneous import sqrt
52
+ >>> from sympy.simplify.sqrtdenest import is_algebraic
53
+ >>> from sympy import cos
54
+ >>> is_algebraic(sqrt(2)*(3/(sqrt(7) + sqrt(5)*sqrt(2))))
55
+ True
56
+ >>> is_algebraic(sqrt(2)*(3/(sqrt(7) + sqrt(5)*cos(2))))
57
+ False
58
+ """
59
+
60
+ if p.is_Rational:
61
+ return True
62
+ elif p.is_Atom:
63
+ return False
64
+ elif is_sqrt(p) or p.is_Pow and p.exp.is_Integer:
65
+ return is_algebraic(p.base)
66
+ elif p.is_Add or p.is_Mul:
67
+ return all(is_algebraic(x) for x in p.args)
68
+ else:
69
+ return False
70
+
71
+
72
+ def _subsets(n):
73
+ """
74
+ Returns all possible subsets of the set (0, 1, ..., n-1) except the
75
+ empty set, listed in reversed lexicographical order according to binary
76
+ representation, so that the case of the fourth root is treated last.
77
+
78
+ Examples
79
+ ========
80
+
81
+ >>> from sympy.simplify.sqrtdenest import _subsets
82
+ >>> _subsets(2)
83
+ [[1, 0], [0, 1], [1, 1]]
84
+
85
+ """
86
+ if n == 1:
87
+ a = [[1]]
88
+ elif n == 2:
89
+ a = [[1, 0], [0, 1], [1, 1]]
90
+ elif n == 3:
91
+ a = [[1, 0, 0], [0, 1, 0], [1, 1, 0],
92
+ [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
93
+ else:
94
+ b = _subsets(n - 1)
95
+ a0 = [x + [0] for x in b]
96
+ a1 = [x + [1] for x in b]
97
+ a = a0 + [[0]*(n - 1) + [1]] + a1
98
+ return a
99
+
100
+
101
+ def sqrtdenest(expr, max_iter=3):
102
+ """Denests sqrts in an expression that contain other square roots
103
+ if possible, otherwise returns the expr unchanged. This is based on the
104
+ algorithms of [1].
105
+
106
+ Examples
107
+ ========
108
+
109
+ >>> from sympy.simplify.sqrtdenest import sqrtdenest
110
+ >>> from sympy import sqrt
111
+ >>> sqrtdenest(sqrt(5 + 2 * sqrt(6)))
112
+ sqrt(2) + sqrt(3)
113
+
114
+ See Also
115
+ ========
116
+
117
+ sympy.solvers.solvers.unrad
118
+
119
+ References
120
+ ==========
121
+
122
+ .. [1] https://web.archive.org/web/20210806201615/https://researcher.watson.ibm.com/researcher/files/us-fagin/symb85.pdf
123
+
124
+ .. [2] D. J. Jeffrey and A. D. Rich, 'Symplifying Square Roots of Square Roots
125
+ by Denesting' (available at https://www.cybertester.com/data/denest.pdf)
126
+
127
+ """
128
+ expr = expand_mul(expr)
129
+ for i in range(max_iter):
130
+ z = _sqrtdenest0(expr)
131
+ if expr == z:
132
+ return expr
133
+ expr = z
134
+ return expr
135
+
136
+
137
+ def _sqrt_match(p):
138
+ """Return [a, b, r] for p.match(a + b*sqrt(r)) where, in addition to
139
+ matching, sqrt(r) also has then maximal sqrt_depth among addends of p.
140
+
141
+ Examples
142
+ ========
143
+
144
+ >>> from sympy.functions.elementary.miscellaneous import sqrt
145
+ >>> from sympy.simplify.sqrtdenest import _sqrt_match
146
+ >>> _sqrt_match(1 + sqrt(2) + sqrt(2)*sqrt(3) + 2*sqrt(1+sqrt(5)))
147
+ [1 + sqrt(2) + sqrt(6), 2, 1 + sqrt(5)]
148
+ """
149
+ from sympy.simplify.radsimp import split_surds
150
+
151
+ p = _mexpand(p)
152
+ if p.is_Number:
153
+ res = (p, S.Zero, S.Zero)
154
+ elif p.is_Add:
155
+ pargs = sorted(p.args, key=default_sort_key)
156
+ sqargs = [x**2 for x in pargs]
157
+ if all(sq.is_Rational and sq.is_positive for sq in sqargs):
158
+ r, b, a = split_surds(p)
159
+ res = a, b, r
160
+ return list(res)
161
+ # to make the process canonical, the argument is included in the tuple
162
+ # so when the max is selected, it will be the largest arg having a
163
+ # given depth
164
+ v = [(sqrt_depth(x), x, i) for i, x in enumerate(pargs)]
165
+ nmax = max(v, key=default_sort_key)
166
+ if nmax[0] == 0:
167
+ res = []
168
+ else:
169
+ # select r
170
+ depth, _, i = nmax
171
+ r = pargs.pop(i)
172
+ v.pop(i)
173
+ b = S.One
174
+ if r.is_Mul:
175
+ bv = []
176
+ rv = []
177
+ for x in r.args:
178
+ if sqrt_depth(x) < depth:
179
+ bv.append(x)
180
+ else:
181
+ rv.append(x)
182
+ b = Mul._from_args(bv)
183
+ r = Mul._from_args(rv)
184
+ # collect terms comtaining r
185
+ a1 = []
186
+ b1 = [b]
187
+ for x in v:
188
+ if x[0] < depth:
189
+ a1.append(x[1])
190
+ else:
191
+ x1 = x[1]
192
+ if x1 == r:
193
+ b1.append(1)
194
+ else:
195
+ if x1.is_Mul:
196
+ x1args = list(x1.args)
197
+ if r in x1args:
198
+ x1args.remove(r)
199
+ b1.append(Mul(*x1args))
200
+ else:
201
+ a1.append(x[1])
202
+ else:
203
+ a1.append(x[1])
204
+ a = Add(*a1)
205
+ b = Add(*b1)
206
+ res = (a, b, r**2)
207
+ else:
208
+ b, r = p.as_coeff_Mul()
209
+ if is_sqrt(r):
210
+ res = (S.Zero, b, r**2)
211
+ else:
212
+ res = []
213
+ return list(res)
214
+
215
+
216
+ class SqrtdenestStopIteration(StopIteration):
217
+ pass
218
+
219
+
220
+ def _sqrtdenest0(expr):
221
+ """Returns expr after denesting its arguments."""
222
+
223
+ if is_sqrt(expr):
224
+ n, d = expr.as_numer_denom()
225
+ if d is S.One: # n is a square root
226
+ if n.base.is_Add:
227
+ args = sorted(n.base.args, key=default_sort_key)
228
+ if len(args) > 2 and all((x**2).is_Integer for x in args):
229
+ try:
230
+ return _sqrtdenest_rec(n)
231
+ except SqrtdenestStopIteration:
232
+ pass
233
+ expr = sqrt(_mexpand(Add(*[_sqrtdenest0(x) for x in args])))
234
+ return _sqrtdenest1(expr)
235
+ else:
236
+ n, d = [_sqrtdenest0(i) for i in (n, d)]
237
+ return n/d
238
+
239
+ if isinstance(expr, Add):
240
+ cs = []
241
+ args = []
242
+ for arg in expr.args:
243
+ c, a = arg.as_coeff_Mul()
244
+ cs.append(c)
245
+ args.append(a)
246
+
247
+ if all(c.is_Rational for c in cs) and all(is_sqrt(arg) for arg in args):
248
+ return _sqrt_ratcomb(cs, args)
249
+
250
+ if isinstance(expr, Expr):
251
+ args = expr.args
252
+ if args:
253
+ return expr.func(*[_sqrtdenest0(a) for a in args])
254
+ return expr
255
+
256
+
257
+ def _sqrtdenest_rec(expr):
258
+ """Helper that denests the square root of three or more surds.
259
+
260
+ Explanation
261
+ ===========
262
+
263
+ It returns the denested expression; if it cannot be denested it
264
+ throws SqrtdenestStopIteration
265
+
266
+ Algorithm: expr.base is in the extension Q_m = Q(sqrt(r_1),..,sqrt(r_k));
267
+ split expr.base = a + b*sqrt(r_k), where `a` and `b` are on
268
+ Q_(m-1) = Q(sqrt(r_1),..,sqrt(r_(k-1))); then a**2 - b**2*r_k is
269
+ on Q_(m-1); denest sqrt(a**2 - b**2*r_k) and so on.
270
+ See [1], section 6.
271
+
272
+ Examples
273
+ ========
274
+
275
+ >>> from sympy import sqrt
276
+ >>> from sympy.simplify.sqrtdenest import _sqrtdenest_rec
277
+ >>> _sqrtdenest_rec(sqrt(-72*sqrt(2) + 158*sqrt(5) + 498))
278
+ -sqrt(10) + sqrt(2) + 9 + 9*sqrt(5)
279
+ >>> w=-6*sqrt(55)-6*sqrt(35)-2*sqrt(22)-2*sqrt(14)+2*sqrt(77)+6*sqrt(10)+65
280
+ >>> _sqrtdenest_rec(sqrt(w))
281
+ -sqrt(11) - sqrt(7) + sqrt(2) + 3*sqrt(5)
282
+ """
283
+ from sympy.simplify.radsimp import radsimp, rad_rationalize, split_surds
284
+ if not expr.is_Pow:
285
+ return sqrtdenest(expr)
286
+ if expr.base < 0:
287
+ return sqrt(-1)*_sqrtdenest_rec(sqrt(-expr.base))
288
+ g, a, b = split_surds(expr.base)
289
+ a = a*sqrt(g)
290
+ if a < b:
291
+ a, b = b, a
292
+ c2 = _mexpand(a**2 - b**2)
293
+ if len(c2.args) > 2:
294
+ g, a1, b1 = split_surds(c2)
295
+ a1 = a1*sqrt(g)
296
+ if a1 < b1:
297
+ a1, b1 = b1, a1
298
+ c2_1 = _mexpand(a1**2 - b1**2)
299
+ c_1 = _sqrtdenest_rec(sqrt(c2_1))
300
+ d_1 = _sqrtdenest_rec(sqrt(a1 + c_1))
301
+ num, den = rad_rationalize(b1, d_1)
302
+ c = _mexpand(d_1/sqrt(2) + num/(den*sqrt(2)))
303
+ else:
304
+ c = _sqrtdenest1(sqrt(c2))
305
+
306
+ if sqrt_depth(c) > 1:
307
+ raise SqrtdenestStopIteration
308
+ ac = a + c
309
+ if len(ac.args) >= len(expr.args):
310
+ if count_ops(ac) >= count_ops(expr.base):
311
+ raise SqrtdenestStopIteration
312
+ d = sqrtdenest(sqrt(ac))
313
+ if sqrt_depth(d) > 1:
314
+ raise SqrtdenestStopIteration
315
+ num, den = rad_rationalize(b, d)
316
+ r = d/sqrt(2) + num/(den*sqrt(2))
317
+ r = radsimp(r)
318
+ return _mexpand(r)
319
+
320
+
321
+ def _sqrtdenest1(expr, denester=True):
322
+ """Return denested expr after denesting with simpler methods or, that
323
+ failing, using the denester."""
324
+
325
+ from sympy.simplify.simplify import radsimp
326
+
327
+ if not is_sqrt(expr):
328
+ return expr
329
+
330
+ a = expr.base
331
+ if a.is_Atom:
332
+ return expr
333
+ val = _sqrt_match(a)
334
+ if not val:
335
+ return expr
336
+
337
+ a, b, r = val
338
+ # try a quick numeric denesting
339
+ d2 = _mexpand(a**2 - b**2*r)
340
+ if d2.is_Rational:
341
+ if d2.is_positive:
342
+ z = _sqrt_numeric_denest(a, b, r, d2)
343
+ if z is not None:
344
+ return z
345
+ else:
346
+ # fourth root case
347
+ # sqrtdenest(sqrt(3 + 2*sqrt(3))) =
348
+ # sqrt(2)*3**(1/4)/2 + sqrt(2)*3**(3/4)/2
349
+ dr2 = _mexpand(-d2*r)
350
+ dr = sqrt(dr2)
351
+ if dr.is_Rational:
352
+ z = _sqrt_numeric_denest(_mexpand(b*r), a, r, dr2)
353
+ if z is not None:
354
+ return z/root(r, 4)
355
+
356
+ else:
357
+ z = _sqrt_symbolic_denest(a, b, r)
358
+ if z is not None:
359
+ return z
360
+
361
+ if not denester or not is_algebraic(expr):
362
+ return expr
363
+
364
+ res = sqrt_biquadratic_denest(expr, a, b, r, d2)
365
+ if res:
366
+ return res
367
+
368
+ # now call to the denester
369
+ av0 = [a, b, r, d2]
370
+ z = _denester([radsimp(expr**2)], av0, 0, sqrt_depth(expr))[0]
371
+ if av0[1] is None:
372
+ return expr
373
+ if z is not None:
374
+ if sqrt_depth(z) == sqrt_depth(expr) and count_ops(z) > count_ops(expr):
375
+ return expr
376
+ return z
377
+ return expr
378
+
379
+
380
+ def _sqrt_symbolic_denest(a, b, r):
381
+ """Given an expression, sqrt(a + b*sqrt(b)), return the denested
382
+ expression or None.
383
+
384
+ Explanation
385
+ ===========
386
+
387
+ If r = ra + rb*sqrt(rr), try replacing sqrt(rr) in ``a`` with
388
+ (y**2 - ra)/rb, and if the result is a quadratic, ca*y**2 + cb*y + cc, and
389
+ (cb + b)**2 - 4*ca*cc is 0, then sqrt(a + b*sqrt(r)) can be rewritten as
390
+ sqrt(ca*(sqrt(r) + (cb + b)/(2*ca))**2).
391
+
392
+ Examples
393
+ ========
394
+
395
+ >>> from sympy.simplify.sqrtdenest import _sqrt_symbolic_denest, sqrtdenest
396
+ >>> from sympy import sqrt, Symbol
397
+ >>> from sympy.abc import x
398
+
399
+ >>> a, b, r = 16 - 2*sqrt(29), 2, -10*sqrt(29) + 55
400
+ >>> _sqrt_symbolic_denest(a, b, r)
401
+ sqrt(11 - 2*sqrt(29)) + sqrt(5)
402
+
403
+ If the expression is numeric, it will be simplified:
404
+
405
+ >>> w = sqrt(sqrt(sqrt(3) + 1) + 1) + 1 + sqrt(2)
406
+ >>> sqrtdenest(sqrt((w**2).expand()))
407
+ 1 + sqrt(2) + sqrt(1 + sqrt(1 + sqrt(3)))
408
+
409
+ Otherwise, it will only be simplified if assumptions allow:
410
+
411
+ >>> w = w.subs(sqrt(3), sqrt(x + 3))
412
+ >>> sqrtdenest(sqrt((w**2).expand()))
413
+ sqrt((sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2))**2)
414
+
415
+ Notice that the argument of the sqrt is a square. If x is made positive
416
+ then the sqrt of the square is resolved:
417
+
418
+ >>> _.subs(x, Symbol('x', positive=True))
419
+ sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2)
420
+ """
421
+
422
+ a, b, r = map(sympify, (a, b, r))
423
+ rval = _sqrt_match(r)
424
+ if not rval:
425
+ return None
426
+ ra, rb, rr = rval
427
+ if rb:
428
+ y = Dummy('y', positive=True)
429
+ try:
430
+ newa = Poly(a.subs(sqrt(rr), (y**2 - ra)/rb), y)
431
+ except PolynomialError:
432
+ return None
433
+ if newa.degree() == 2:
434
+ ca, cb, cc = newa.all_coeffs()
435
+ cb += b
436
+ if _mexpand(cb**2 - 4*ca*cc).equals(0):
437
+ z = sqrt(ca*(sqrt(r) + cb/(2*ca))**2)
438
+ if z.is_number:
439
+ z = _mexpand(Mul._from_args(z.as_content_primitive()))
440
+ return z
441
+
442
+
443
+ def _sqrt_numeric_denest(a, b, r, d2):
444
+ r"""Helper that denest
445
+ $\sqrt{a + b \sqrt{r}}, d^2 = a^2 - b^2 r > 0$
446
+
447
+ If it cannot be denested, it returns ``None``.
448
+ """
449
+ d = sqrt(d2)
450
+ s = a + d
451
+ # sqrt_depth(res) <= sqrt_depth(s) + 1
452
+ # sqrt_depth(expr) = sqrt_depth(r) + 2
453
+ # there is denesting if sqrt_depth(s) + 1 < sqrt_depth(r) + 2
454
+ # if s**2 is Number there is a fourth root
455
+ if sqrt_depth(s) < sqrt_depth(r) + 1 or (s**2).is_Rational:
456
+ s1, s2 = sign(s), sign(b)
457
+ if s1 == s2 == -1:
458
+ s1 = s2 = 1
459
+ res = (s1 * sqrt(a + d) + s2 * sqrt(a - d)) * sqrt(2) / 2
460
+ return res.expand()
461
+
462
+
463
+ def sqrt_biquadratic_denest(expr, a, b, r, d2):
464
+ """denest expr = sqrt(a + b*sqrt(r))
465
+ where a, b, r are linear combinations of square roots of
466
+ positive rationals on the rationals (SQRR) and r > 0, b != 0,
467
+ d2 = a**2 - b**2*r > 0
468
+
469
+ If it cannot denest it returns None.
470
+
471
+ Explanation
472
+ ===========
473
+
474
+ Search for a solution A of type SQRR of the biquadratic equation
475
+ 4*A**4 - 4*a*A**2 + b**2*r = 0 (1)
476
+ sqd = sqrt(a**2 - b**2*r)
477
+ Choosing the sqrt to be positive, the possible solutions are
478
+ A = sqrt(a/2 +/- sqd/2)
479
+ Since a, b, r are SQRR, then a**2 - b**2*r is a SQRR,
480
+ so if sqd can be denested, it is done by
481
+ _sqrtdenest_rec, and the result is a SQRR.
482
+ Similarly for A.
483
+ Examples of solutions (in both cases a and sqd are positive):
484
+
485
+ Example of expr with solution sqrt(a/2 + sqd/2) but not
486
+ solution sqrt(a/2 - sqd/2):
487
+ expr = sqrt(-sqrt(15) - sqrt(2)*sqrt(-sqrt(5) + 5) - sqrt(3) + 8)
488
+ a = -sqrt(15) - sqrt(3) + 8; sqd = -2*sqrt(5) - 2 + 4*sqrt(3)
489
+
490
+ Example of expr with solution sqrt(a/2 - sqd/2) but not
491
+ solution sqrt(a/2 + sqd/2):
492
+ w = 2 + r2 + r3 + (1 + r3)*sqrt(2 + r2 + 5*r3)
493
+ expr = sqrt((w**2).expand())
494
+ a = 4*sqrt(6) + 8*sqrt(2) + 47 + 28*sqrt(3)
495
+ sqd = 29 + 20*sqrt(3)
496
+
497
+ Define B = b/2*A; eq.(1) implies a = A**2 + B**2*r; then
498
+ expr**2 = a + b*sqrt(r) = (A + B*sqrt(r))**2
499
+
500
+ Examples
501
+ ========
502
+
503
+ >>> from sympy import sqrt
504
+ >>> from sympy.simplify.sqrtdenest import _sqrt_match, sqrt_biquadratic_denest
505
+ >>> z = sqrt((2*sqrt(2) + 4)*sqrt(2 + sqrt(2)) + 5*sqrt(2) + 8)
506
+ >>> a, b, r = _sqrt_match(z**2)
507
+ >>> d2 = a**2 - b**2*r
508
+ >>> sqrt_biquadratic_denest(z, a, b, r, d2)
509
+ sqrt(2) + sqrt(sqrt(2) + 2) + 2
510
+ """
511
+ from sympy.simplify.radsimp import radsimp, rad_rationalize
512
+ if r <= 0 or d2 < 0 or not b or sqrt_depth(expr.base) < 2:
513
+ return None
514
+ for x in (a, b, r):
515
+ for y in x.args:
516
+ y2 = y**2
517
+ if not y2.is_Integer or not y2.is_positive:
518
+ return None
519
+ sqd = _mexpand(sqrtdenest(sqrt(radsimp(d2))))
520
+ if sqrt_depth(sqd) > 1:
521
+ return None
522
+ x1, x2 = [a/2 + sqd/2, a/2 - sqd/2]
523
+ # look for a solution A with depth 1
524
+ for x in (x1, x2):
525
+ A = sqrtdenest(sqrt(x))
526
+ if sqrt_depth(A) > 1:
527
+ continue
528
+ Bn, Bd = rad_rationalize(b, _mexpand(2*A))
529
+ B = Bn/Bd
530
+ z = A + B*sqrt(r)
531
+ if z < 0:
532
+ z = -z
533
+ return _mexpand(z)
534
+ return None
535
+
536
+
537
+ def _denester(nested, av0, h, max_depth_level):
538
+ """Denests a list of expressions that contain nested square roots.
539
+
540
+ Explanation
541
+ ===========
542
+
543
+ Algorithm based on <http://www.almaden.ibm.com/cs/people/fagin/symb85.pdf>.
544
+
545
+ It is assumed that all of the elements of 'nested' share the same
546
+ bottom-level radicand. (This is stated in the paper, on page 177, in
547
+ the paragraph immediately preceding the algorithm.)
548
+
549
+ When evaluating all of the arguments in parallel, the bottom-level
550
+ radicand only needs to be denested once. This means that calling
551
+ _denester with x arguments results in a recursive invocation with x+1
552
+ arguments; hence _denester has polynomial complexity.
553
+
554
+ However, if the arguments were evaluated separately, each call would
555
+ result in two recursive invocations, and the algorithm would have
556
+ exponential complexity.
557
+
558
+ This is discussed in the paper in the middle paragraph of page 179.
559
+ """
560
+ from sympy.simplify.simplify import radsimp
561
+ if h > max_depth_level:
562
+ return None, None
563
+ if av0[1] is None:
564
+ return None, None
565
+ if (av0[0] is None and
566
+ all(n.is_Number for n in nested)): # no arguments are nested
567
+ for f in _subsets(len(nested)): # test subset 'f' of nested
568
+ p = _mexpand(Mul(*[nested[i] for i in range(len(f)) if f[i]]))
569
+ if f.count(1) > 1 and f[-1]:
570
+ p = -p
571
+ sqp = sqrt(p)
572
+ if sqp.is_Rational:
573
+ return sqp, f # got a perfect square so return its square root.
574
+ # Otherwise, return the radicand from the previous invocation.
575
+ return sqrt(nested[-1]), [0]*len(nested)
576
+ else:
577
+ R = None
578
+ if av0[0] is not None:
579
+ values = [av0[:2]]
580
+ R = av0[2]
581
+ nested2 = [av0[3], R]
582
+ av0[0] = None
583
+ else:
584
+ values = list(filter(None, [_sqrt_match(expr) for expr in nested]))
585
+ for v in values:
586
+ if v[2]: # Since if b=0, r is not defined
587
+ if R is not None:
588
+ if R != v[2]:
589
+ av0[1] = None
590
+ return None, None
591
+ else:
592
+ R = v[2]
593
+ if R is None:
594
+ # return the radicand from the previous invocation
595
+ return sqrt(nested[-1]), [0]*len(nested)
596
+ nested2 = [_mexpand(v[0]**2) -
597
+ _mexpand(R*v[1]**2) for v in values] + [R]
598
+ d, f = _denester(nested2, av0, h + 1, max_depth_level)
599
+ if not f:
600
+ return None, None
601
+ if not any(f[i] for i in range(len(nested))):
602
+ v = values[-1]
603
+ return sqrt(v[0] + _mexpand(v[1]*d)), f
604
+ else:
605
+ p = Mul(*[nested[i] for i in range(len(nested)) if f[i]])
606
+ v = _sqrt_match(p)
607
+ if 1 in f and f.index(1) < len(nested) - 1 and f[len(nested) - 1]:
608
+ v[0] = -v[0]
609
+ v[1] = -v[1]
610
+ if not f[len(nested)]: # Solution denests with square roots
611
+ vad = _mexpand(v[0] + d)
612
+ if vad <= 0:
613
+ # return the radicand from the previous invocation.
614
+ return sqrt(nested[-1]), [0]*len(nested)
615
+ if not(sqrt_depth(vad) <= sqrt_depth(R) + 1 or
616
+ (vad**2).is_Number):
617
+ av0[1] = None
618
+ return None, None
619
+
620
+ sqvad = _sqrtdenest1(sqrt(vad), denester=False)
621
+ if not (sqrt_depth(sqvad) <= sqrt_depth(R) + 1):
622
+ av0[1] = None
623
+ return None, None
624
+ sqvad1 = radsimp(1/sqvad)
625
+ res = _mexpand(sqvad/sqrt(2) + (v[1]*sqrt(R)*sqvad1/sqrt(2)))
626
+ return res, f
627
+
628
+ # sign(v[1])*sqrt(_mexpand(v[1]**2*R*vad1/2))), f
629
+ else: # Solution requires a fourth root
630
+ s2 = _mexpand(v[1]*R) + d
631
+ if s2 <= 0:
632
+ return sqrt(nested[-1]), [0]*len(nested)
633
+ FR, s = root(_mexpand(R), 4), sqrt(s2)
634
+ return _mexpand(s/(sqrt(2)*FR) + v[0]*FR/(sqrt(2)*s)), f
635
+
636
+
637
+ def _sqrt_ratcomb(cs, args):
638
+ """Denest rational combinations of radicals.
639
+
640
+ Based on section 5 of [1].
641
+
642
+ Examples
643
+ ========
644
+
645
+ >>> from sympy import sqrt
646
+ >>> from sympy.simplify.sqrtdenest import sqrtdenest
647
+ >>> z = sqrt(1+sqrt(3)) + sqrt(3+3*sqrt(3)) - sqrt(10+6*sqrt(3))
648
+ >>> sqrtdenest(z)
649
+ 0
650
+ """
651
+ from sympy.simplify.radsimp import radsimp
652
+
653
+ # check if there exists a pair of sqrt that can be denested
654
+ def find(a):
655
+ n = len(a)
656
+ for i in range(n - 1):
657
+ for j in range(i + 1, n):
658
+ s1 = a[i].base
659
+ s2 = a[j].base
660
+ p = _mexpand(s1 * s2)
661
+ s = sqrtdenest(sqrt(p))
662
+ if s != sqrt(p):
663
+ return s, i, j
664
+
665
+ indices = find(args)
666
+ if indices is None:
667
+ return Add(*[c * arg for c, arg in zip(cs, args)])
668
+
669
+ s, i1, i2 = indices
670
+
671
+ c2 = cs.pop(i2)
672
+ args.pop(i2)
673
+ a1 = args[i1]
674
+
675
+ # replace a2 by s/a1
676
+ cs[i1] += radsimp(c2 * s / a1.base)
677
+
678
+ return _sqrt_ratcomb(cs, args)
wemm/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py ADDED
File without changes
wemm/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file